]> andersk Git - openssh.git/blob - sftp.c
- djm@cvs.openbsd.org 2004/05/19 12:17:33
[openssh.git] / sftp.c
1 /*
2  * Copyright (c) 2001-2004 Damien Miller <djm@openbsd.org>
3  *
4  * Permission to use, copy, modify, and distribute this software for any
5  * purpose with or without fee is hereby granted, provided that the above
6  * copyright notice and this permission notice appear in all copies.
7  *
8  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15  */
16
17 #include "includes.h"
18
19 RCSID("$OpenBSD: sftp.c,v 1.46 2004/05/19 12:17:33 djm Exp $");
20
21 #include "buffer.h"
22 #include "xmalloc.h"
23 #include "log.h"
24 #include "pathnames.h"
25 #include "misc.h"
26
27 #include "sftp.h"
28 #include "sftp-common.h"
29 #include "sftp-client.h"
30
31 /* File to read commands from */
32 FILE* infile;
33
34 /* Are we in batchfile mode? */
35 int batchmode = 0;
36
37 /* Size of buffer used when copying files */
38 size_t copy_buffer_len = 32768;
39
40 /* Number of concurrent outstanding requests */
41 size_t num_requests = 16;
42
43 /* PID of ssh transport process */
44 static pid_t sshpid = -1;
45
46 /* This is set to 0 if the progressmeter is not desired. */
47 int showprogress = 1;
48
49 /* SIGINT received during command processing */
50 volatile sig_atomic_t interrupted = 0;
51
52 int remote_glob(struct sftp_conn *, const char *, int,
53     int (*)(const char *, int), glob_t *); /* proto for sftp-glob.c */
54
55 #ifdef HAVE___PROGNAME
56 extern char *__progname;
57 #else
58 char *__progname;
59 #endif
60
61 /* Separators for interactive commands */
62 #define WHITESPACE " \t\r\n"
63
64 /* Define what type of ls view (0 - multi-column) */
65 #define LONG_VIEW 1             /* Full view ala ls -l */
66 #define SHORT_VIEW 2            /* Single row view ala ls -1 */
67
68 /* Commands for interactive mode */
69 #define I_CHDIR         1
70 #define I_CHGRP         2
71 #define I_CHMOD         3
72 #define I_CHOWN         4
73 #define I_GET           5
74 #define I_HELP          6
75 #define I_LCHDIR        7
76 #define I_LLS           8
77 #define I_LMKDIR        9
78 #define I_LPWD          10
79 #define I_LS            11
80 #define I_LUMASK        12
81 #define I_MKDIR         13
82 #define I_PUT           14
83 #define I_PWD           15
84 #define I_QUIT          16
85 #define I_RENAME        17
86 #define I_RM            18
87 #define I_RMDIR         19
88 #define I_SHELL         20
89 #define I_SYMLINK       21
90 #define I_VERSION       22
91 #define I_PROGRESS      23
92
93 struct CMD {
94         const char *c;
95         const int n;
96 };
97
98 static const struct CMD cmds[] = {
99         { "bye",        I_QUIT },
100         { "cd",         I_CHDIR },
101         { "chdir",      I_CHDIR },
102         { "chgrp",      I_CHGRP },
103         { "chmod",      I_CHMOD },
104         { "chown",      I_CHOWN },
105         { "dir",        I_LS },
106         { "exit",       I_QUIT },
107         { "get",        I_GET },
108         { "mget",       I_GET },
109         { "help",       I_HELP },
110         { "lcd",        I_LCHDIR },
111         { "lchdir",     I_LCHDIR },
112         { "lls",        I_LLS },
113         { "lmkdir",     I_LMKDIR },
114         { "ln",         I_SYMLINK },
115         { "lpwd",       I_LPWD },
116         { "ls",         I_LS },
117         { "lumask",     I_LUMASK },
118         { "mkdir",      I_MKDIR },
119         { "progress",   I_PROGRESS },
120         { "put",        I_PUT },
121         { "mput",       I_PUT },
122         { "pwd",        I_PWD },
123         { "quit",       I_QUIT },
124         { "rename",     I_RENAME },
125         { "rm",         I_RM },
126         { "rmdir",      I_RMDIR },
127         { "symlink",    I_SYMLINK },
128         { "version",    I_VERSION },
129         { "!",          I_SHELL },
130         { "?",          I_HELP },
131         { NULL,                 -1}
132 };
133
134 int interactive_loop(int fd_in, int fd_out, char *file1, char *file2);
135
136 static void
137 killchild(int signo)
138 {
139         if (sshpid > 1)
140                 kill(sshpid, SIGTERM);
141
142         _exit(1);
143 }
144
145 static void
146 cmd_interrupt(int signo)
147 {
148         const char msg[] = "\rInterrupt  \n";
149
150         write(STDERR_FILENO, msg, sizeof(msg) - 1);
151         interrupted = 1;
152 }
153
154 static void
155 help(void)
156 {
157         printf("Available commands:\n");
158         printf("cd path                       Change remote directory to 'path'\n");
159         printf("lcd path                      Change local directory to 'path'\n");
160         printf("chgrp grp path                Change group of file 'path' to 'grp'\n");
161         printf("chmod mode path               Change permissions of file 'path' to 'mode'\n");
162         printf("chown own path                Change owner of file 'path' to 'own'\n");
163         printf("help                          Display this help text\n");
164         printf("get remote-path [local-path]  Download file\n");
165         printf("lls [ls-options [path]]       Display local directory listing\n");
166         printf("ln oldpath newpath            Symlink remote file\n");
167         printf("lmkdir path                   Create local directory\n");
168         printf("lpwd                          Print local working directory\n");
169         printf("ls [path]                     Display remote directory listing\n");
170         printf("lumask umask                  Set local umask to 'umask'\n");
171         printf("mkdir path                    Create remote directory\n");
172         printf("progress                      Toggle display of progress meter\n");
173         printf("put local-path [remote-path]  Upload file\n");
174         printf("pwd                           Display remote working directory\n");
175         printf("exit                          Quit sftp\n");
176         printf("quit                          Quit sftp\n");
177         printf("rename oldpath newpath        Rename remote file\n");
178         printf("rmdir path                    Remove remote directory\n");
179         printf("rm path                       Delete remote file\n");
180         printf("symlink oldpath newpath       Symlink remote file\n");
181         printf("version                       Show SFTP version\n");
182         printf("!command                      Execute 'command' in local shell\n");
183         printf("!                             Escape to local shell\n");
184         printf("?                             Synonym for help\n");
185 }
186
187 static void
188 local_do_shell(const char *args)
189 {
190         int status;
191         char *shell;
192         pid_t pid;
193
194         if (!*args)
195                 args = NULL;
196
197         if ((shell = getenv("SHELL")) == NULL)
198                 shell = _PATH_BSHELL;
199
200         if ((pid = fork()) == -1)
201                 fatal("Couldn't fork: %s", strerror(errno));
202
203         if (pid == 0) {
204                 /* XXX: child has pipe fds to ssh subproc open - issue? */
205                 if (args) {
206                         debug3("Executing %s -c \"%s\"", shell, args);
207                         execl(shell, shell, "-c", args, (char *)NULL);
208                 } else {
209                         debug3("Executing %s", shell);
210                         execl(shell, shell, (char *)NULL);
211                 }
212                 fprintf(stderr, "Couldn't execute \"%s\": %s\n", shell,
213                     strerror(errno));
214                 _exit(1);
215         }
216         while (waitpid(pid, &status, 0) == -1)
217                 if (errno != EINTR)
218                         fatal("Couldn't wait for child: %s", strerror(errno));
219         if (!WIFEXITED(status))
220                 error("Shell exited abormally");
221         else if (WEXITSTATUS(status))
222                 error("Shell exited with status %d", WEXITSTATUS(status));
223 }
224
225 static void
226 local_do_ls(const char *args)
227 {
228         if (!args || !*args)
229                 local_do_shell(_PATH_LS);
230         else {
231                 int len = strlen(_PATH_LS " ") + strlen(args) + 1;
232                 char *buf = xmalloc(len);
233
234                 /* XXX: quoting - rip quoting code from ftp? */
235                 snprintf(buf, len, _PATH_LS " %s", args);
236                 local_do_shell(buf);
237                 xfree(buf);
238         }
239 }
240
241 /* Strip one path (usually the pwd) from the start of another */
242 static char *
243 path_strip(char *path, char *strip)
244 {
245         size_t len;
246
247         if (strip == NULL)
248                 return (xstrdup(path));
249
250         len = strlen(strip);
251         if (strip != NULL && strncmp(path, strip, len) == 0) {
252                 if (strip[len - 1] != '/' && path[len] == '/')
253                         len++;
254                 return (xstrdup(path + len));
255         }
256
257         return (xstrdup(path));
258 }
259
260 static char *
261 path_append(char *p1, char *p2)
262 {
263         char *ret;
264         int len = strlen(p1) + strlen(p2) + 2;
265
266         ret = xmalloc(len);
267         strlcpy(ret, p1, len);
268         if (p1[strlen(p1) - 1] != '/')
269                 strlcat(ret, "/", len);
270         strlcat(ret, p2, len);
271
272         return(ret);
273 }
274
275 static char *
276 make_absolute(char *p, char *pwd)
277 {
278         char *abs;
279
280         /* Derelativise */
281         if (p && p[0] != '/') {
282                 abs = path_append(pwd, p);
283                 xfree(p);
284                 return(abs);
285         } else
286                 return(p);
287 }
288
289 static int
290 infer_path(const char *p, char **ifp)
291 {
292         char *cp;
293
294         cp = strrchr(p, '/');
295         if (cp == NULL) {
296                 *ifp = xstrdup(p);
297                 return(0);
298         }
299
300         if (!cp[1]) {
301                 error("Invalid path");
302                 return(-1);
303         }
304
305         *ifp = xstrdup(cp + 1);
306         return(0);
307 }
308
309 static int
310 parse_getput_flags(const char **cpp, int *pflag)
311 {
312         const char *cp = *cpp;
313
314         /* Check for flags */
315         if (cp[0] == '-' && cp[1] && strchr(WHITESPACE, cp[2])) {
316                 switch (cp[1]) {
317                 case 'p':
318                 case 'P':
319                         *pflag = 1;
320                         break;
321                 default:
322                         error("Invalid flag -%c", cp[1]);
323                         return(-1);
324                 }
325                 cp += 2;
326                 *cpp = cp + strspn(cp, WHITESPACE);
327         }
328
329         return(0);
330 }
331
332 static int
333 parse_ls_flags(const char **cpp, int *lflag)
334 {
335         const char *cp = *cpp;
336
337         /* Check for flags */
338         if (cp++[0] == '-') {
339                 for(; strchr(WHITESPACE, *cp) == NULL; cp++) {
340                         switch (*cp) {
341                         case 'l':
342                                 *lflag = LONG_VIEW;
343                                 break;
344                         case '1':
345                                 *lflag = SHORT_VIEW;
346                                 break;
347                         default:
348                                 error("Invalid flag -%c", *cp);
349                                 return(-1);
350                         }
351                 }
352                 *cpp = cp + strspn(cp, WHITESPACE);
353         }
354
355         return(0);
356 }
357
358 static int
359 get_pathname(const char **cpp, char **path)
360 {
361         const char *cp = *cpp, *end;
362         char quot;
363         int i, j;
364
365         cp += strspn(cp, WHITESPACE);
366         if (!*cp) {
367                 *cpp = cp;
368                 *path = NULL;
369                 return (0);
370         }
371
372         *path = xmalloc(strlen(cp) + 1);
373
374         /* Check for quoted filenames */
375         if (*cp == '\"' || *cp == '\'') {
376                 quot = *cp++;
377
378                 /* Search for terminating quote, unescape some chars */
379                 for (i = j = 0; i <= strlen(cp); i++) {
380                         if (cp[i] == quot) {    /* Found quote */
381                                 i++;
382                                 (*path)[j] = '\0';
383                                 break;
384                         }
385                         if (cp[i] == '\0') {    /* End of string */
386                                 error("Unterminated quote");
387                                 goto fail;
388                         }
389                         if (cp[i] == '\\') {    /* Escaped characters */
390                                 i++;
391                                 if (cp[i] != '\'' && cp[i] != '\"' &&
392                                     cp[i] != '\\') {
393                                         error("Bad escaped character '\%c'",
394                                             cp[i]);
395                                         goto fail;
396                                 }
397                         }
398                         (*path)[j++] = cp[i];
399                 }
400
401                 if (j == 0) {
402                         error("Empty quotes");
403                         goto fail;
404                 }
405                 *cpp = cp + i + strspn(cp + i, WHITESPACE);
406         } else {
407                 /* Read to end of filename */
408                 end = strpbrk(cp, WHITESPACE);
409                 if (end == NULL)
410                         end = strchr(cp, '\0');
411                 *cpp = end + strspn(end, WHITESPACE);
412
413                 memcpy(*path, cp, end - cp);
414                 (*path)[end - cp] = '\0';
415         }
416         return (0);
417
418  fail:
419         xfree(*path);
420         *path = NULL;
421         return (-1);
422 }
423
424 static int
425 is_dir(char *path)
426 {
427         struct stat sb;
428
429         /* XXX: report errors? */
430         if (stat(path, &sb) == -1)
431                 return(0);
432
433         return(sb.st_mode & S_IFDIR);
434 }
435
436 static int
437 is_reg(char *path)
438 {
439         struct stat sb;
440
441         if (stat(path, &sb) == -1)
442                 fatal("stat %s: %s", path, strerror(errno));
443
444         return(S_ISREG(sb.st_mode));
445 }
446
447 static int
448 remote_is_dir(struct sftp_conn *conn, char *path)
449 {
450         Attrib *a;
451
452         /* XXX: report errors? */
453         if ((a = do_stat(conn, path, 1)) == NULL)
454                 return(0);
455         if (!(a->flags & SSH2_FILEXFER_ATTR_PERMISSIONS))
456                 return(0);
457         return(a->perm & S_IFDIR);
458 }
459
460 static int
461 process_get(struct sftp_conn *conn, char *src, char *dst, char *pwd, int pflag)
462 {
463         char *abs_src = NULL;
464         char *abs_dst = NULL;
465         char *tmp;
466         glob_t g;
467         int err = 0;
468         int i;
469
470         abs_src = xstrdup(src);
471         abs_src = make_absolute(abs_src, pwd);
472
473         memset(&g, 0, sizeof(g));
474         debug3("Looking up %s", abs_src);
475         if (remote_glob(conn, abs_src, 0, NULL, &g)) {
476                 error("File \"%s\" not found.", abs_src);
477                 err = -1;
478                 goto out;
479         }
480
481         /* If multiple matches, dst must be a directory or unspecified */
482         if (g.gl_matchc > 1 && dst && !is_dir(dst)) {
483                 error("Multiple files match, but \"%s\" is not a directory",
484                     dst);
485                 err = -1;
486                 goto out;
487         }
488
489         for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
490                 if (infer_path(g.gl_pathv[i], &tmp)) {
491                         err = -1;
492                         goto out;
493                 }
494
495                 if (g.gl_matchc == 1 && dst) {
496                         /* If directory specified, append filename */
497                         if (is_dir(dst)) {
498                                 if (infer_path(g.gl_pathv[0], &tmp)) {
499                                         err = 1;
500                                         goto out;
501                                 }
502                                 abs_dst = path_append(dst, tmp);
503                                 xfree(tmp);
504                         } else
505                                 abs_dst = xstrdup(dst);
506                 } else if (dst) {
507                         abs_dst = path_append(dst, tmp);
508                         xfree(tmp);
509                 } else
510                         abs_dst = tmp;
511
512                 printf("Fetching %s to %s\n", g.gl_pathv[i], abs_dst);
513                 if (do_download(conn, g.gl_pathv[i], abs_dst, pflag) == -1)
514                         err = -1;
515                 xfree(abs_dst);
516                 abs_dst = NULL;
517         }
518
519 out:
520         xfree(abs_src);
521         if (abs_dst)
522                 xfree(abs_dst);
523         globfree(&g);
524         return(err);
525 }
526
527 static int
528 process_put(struct sftp_conn *conn, char *src, char *dst, char *pwd, int pflag)
529 {
530         char *tmp_dst = NULL;
531         char *abs_dst = NULL;
532         char *tmp;
533         glob_t g;
534         int err = 0;
535         int i;
536
537         if (dst) {
538                 tmp_dst = xstrdup(dst);
539                 tmp_dst = make_absolute(tmp_dst, pwd);
540         }
541
542         memset(&g, 0, sizeof(g));
543         debug3("Looking up %s", src);
544         if (glob(src, 0, NULL, &g)) {
545                 error("File \"%s\" not found.", src);
546                 err = -1;
547                 goto out;
548         }
549
550         /* If multiple matches, dst may be directory or unspecified */
551         if (g.gl_matchc > 1 && tmp_dst && !remote_is_dir(conn, tmp_dst)) {
552                 error("Multiple files match, but \"%s\" is not a directory",
553                     tmp_dst);
554                 err = -1;
555                 goto out;
556         }
557
558         for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
559                 if (!is_reg(g.gl_pathv[i])) {
560                         error("skipping non-regular file %s",
561                             g.gl_pathv[i]);
562                         continue;
563                 }
564                 if (infer_path(g.gl_pathv[i], &tmp)) {
565                         err = -1;
566                         goto out;
567                 }
568
569                 if (g.gl_matchc == 1 && tmp_dst) {
570                         /* If directory specified, append filename */
571                         if (remote_is_dir(conn, tmp_dst)) {
572                                 if (infer_path(g.gl_pathv[0], &tmp)) {
573                                         err = 1;
574                                         goto out;
575                                 }
576                                 abs_dst = path_append(tmp_dst, tmp);
577                                 xfree(tmp);
578                         } else
579                                 abs_dst = xstrdup(tmp_dst);
580
581                 } else if (tmp_dst) {
582                         abs_dst = path_append(tmp_dst, tmp);
583                         xfree(tmp);
584                 } else
585                         abs_dst = make_absolute(tmp, pwd);
586
587                 printf("Uploading %s to %s\n", g.gl_pathv[i], abs_dst);
588                 if (do_upload(conn, g.gl_pathv[i], abs_dst, pflag) == -1)
589                         err = -1;
590         }
591
592 out:
593         if (abs_dst)
594                 xfree(abs_dst);
595         if (tmp_dst)
596                 xfree(tmp_dst);
597         globfree(&g);
598         return(err);
599 }
600
601 static int
602 sdirent_comp(const void *aa, const void *bb)
603 {
604         SFTP_DIRENT *a = *(SFTP_DIRENT **)aa;
605         SFTP_DIRENT *b = *(SFTP_DIRENT **)bb;
606
607         return (strcmp(a->filename, b->filename));
608 }
609
610 /* sftp ls.1 replacement for directories */
611 static int
612 do_ls_dir(struct sftp_conn *conn, char *path, char *strip_path, int lflag)
613 {
614         int n, c = 1, colspace = 0, columns = 1;
615         SFTP_DIRENT **d;
616
617         if ((n = do_readdir(conn, path, &d)) != 0)
618                 return (n);
619
620         if (!(lflag & SHORT_VIEW)) {
621                 int m = 0, width = 80;
622                 struct winsize ws;
623                 char *tmp;
624
625                 /* Count entries for sort and find longest filename */
626                 for (n = 0; d[n] != NULL; n++)
627                         m = MAX(m, strlen(d[n]->filename));
628
629                 /* Add any subpath that also needs to be counted */
630                 tmp = path_strip(path, strip_path);
631                 m += strlen(tmp);
632                 xfree(tmp);
633
634                 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) != -1)
635                         width = ws.ws_col;
636
637                 columns = width / (m + 2);
638                 columns = MAX(columns, 1);
639                 colspace = width / columns;
640                 colspace = MIN(colspace, width);
641         }
642
643         qsort(d, n, sizeof(*d), sdirent_comp);
644
645         for (n = 0; d[n] != NULL && !interrupted; n++) {
646                 char *tmp, *fname;
647
648                 tmp = path_append(path, d[n]->filename);
649                 fname = path_strip(tmp, strip_path);
650                 xfree(tmp);
651
652                 if (lflag & LONG_VIEW) {
653                         char *lname;
654                         struct stat sb;
655
656                         memset(&sb, 0, sizeof(sb));
657                         attrib_to_stat(&d[n]->a, &sb);
658                         lname = ls_file(fname, &sb, 1);
659                         printf("%s\n", lname);
660                         xfree(lname);
661                 } else {
662                         printf("%-*s", colspace, fname);
663                         if (c >= columns) {
664                                 printf("\n");
665                                 c = 1;
666                         } else
667                                 c++;
668                 }
669
670                 xfree(fname);
671         }
672
673         if (!(lflag & LONG_VIEW) && (c != 1))
674                 printf("\n");
675
676         free_sftp_dirents(d);
677         return (0);
678 }
679
680 /* sftp ls.1 replacement which handles path globs */
681 static int
682 do_globbed_ls(struct sftp_conn *conn, char *path, char *strip_path,
683     int lflag)
684 {
685         glob_t g;
686         int i, c = 1, colspace = 0, columns = 1;
687         Attrib *a;
688
689         memset(&g, 0, sizeof(g));
690
691         if (remote_glob(conn, path, GLOB_MARK|GLOB_NOCHECK|GLOB_BRACE,
692             NULL, &g)) {
693                 error("Can't ls: \"%s\" not found", path);
694                 return (-1);
695         }
696
697         if (interrupted)
698                 goto out;
699
700         /*
701          * If the glob returns a single match, which is the same as the
702          * input glob, and it is a directory, then just list its contents
703          */
704         if (g.gl_pathc == 1 &&
705             strncmp(path, g.gl_pathv[0], strlen(g.gl_pathv[0]) - 1) == 0) {
706                 if ((a = do_lstat(conn, path, 1)) == NULL) {
707                         globfree(&g);
708                         return (-1);
709                 }
710                 if ((a->flags & SSH2_FILEXFER_ATTR_PERMISSIONS) &&
711                     S_ISDIR(a->perm)) {
712                         globfree(&g);
713                         return (do_ls_dir(conn, path, strip_path, lflag));
714                 }
715         }
716
717         if (!(lflag & SHORT_VIEW)) {
718                 int m = 0, width = 80;
719                 struct winsize ws;
720
721                 /* Count entries for sort and find longest filename */
722                 for (i = 0; g.gl_pathv[i]; i++)
723                         m = MAX(m, strlen(g.gl_pathv[i]));
724
725                 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) != -1)
726                         width = ws.ws_col;
727
728                 columns = width / (m + 2);
729                 columns = MAX(columns, 1);
730                 colspace = width / columns;
731         }
732
733         for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
734                 char *fname;
735
736                 fname = path_strip(g.gl_pathv[i], strip_path);
737
738                 if (lflag & LONG_VIEW) {
739                         char *lname;
740                         struct stat sb;
741
742                         /*
743                          * XXX: this is slow - 1 roundtrip per path
744                          * A solution to this is to fork glob() and
745                          * build a sftp specific version which keeps the
746                          * attribs (which currently get thrown away)
747                          * that the server returns as well as the filenames.
748                          */
749                         memset(&sb, 0, sizeof(sb));
750                         a = do_lstat(conn, g.gl_pathv[i], 1);
751                         if (a != NULL)
752                                 attrib_to_stat(a, &sb);
753                         lname = ls_file(fname, &sb, 1);
754                         printf("%s\n", lname);
755                         xfree(lname);
756                 } else {
757                         printf("%-*s", colspace, fname);
758                         if (c >= columns) {
759                                 printf("\n");
760                                 c = 1;
761                         } else
762                                 c++;
763                 }
764                 xfree(fname);
765         }
766
767         if (!(lflag & LONG_VIEW) && (c != 1))
768                 printf("\n");
769
770  out:
771         if (g.gl_pathc)
772                 globfree(&g);
773
774         return (0);
775 }
776
777 static int
778 parse_args(const char **cpp, int *pflag, int *lflag, int *iflag,
779     unsigned long *n_arg, char **path1, char **path2)
780 {
781         const char *cmd, *cp = *cpp;
782         char *cp2;
783         int base = 0;
784         long l;
785         int i, cmdnum;
786
787         /* Skip leading whitespace */
788         cp = cp + strspn(cp, WHITESPACE);
789
790         /* Ignore blank lines and lines which begin with comment '#' char */
791         if (*cp == '\0' || *cp == '#')
792                 return (0);
793
794         /* Check for leading '-' (disable error processing) */
795         *iflag = 0;
796         if (*cp == '-') {
797                 *iflag = 1;
798                 cp++;
799         }
800
801         /* Figure out which command we have */
802         for (i = 0; cmds[i].c; i++) {
803                 int cmdlen = strlen(cmds[i].c);
804
805                 /* Check for command followed by whitespace */
806                 if (!strncasecmp(cp, cmds[i].c, cmdlen) &&
807                     strchr(WHITESPACE, cp[cmdlen])) {
808                         cp += cmdlen;
809                         cp = cp + strspn(cp, WHITESPACE);
810                         break;
811                 }
812         }
813         cmdnum = cmds[i].n;
814         cmd = cmds[i].c;
815
816         /* Special case */
817         if (*cp == '!') {
818                 cp++;
819                 cmdnum = I_SHELL;
820         } else if (cmdnum == -1) {
821                 error("Invalid command.");
822                 return (-1);
823         }
824
825         /* Get arguments and parse flags */
826         *lflag = *pflag = *n_arg = 0;
827         *path1 = *path2 = NULL;
828         switch (cmdnum) {
829         case I_GET:
830         case I_PUT:
831                 if (parse_getput_flags(&cp, pflag))
832                         return(-1);
833                 /* Get first pathname (mandatory) */
834                 if (get_pathname(&cp, path1))
835                         return(-1);
836                 if (*path1 == NULL) {
837                         error("You must specify at least one path after a "
838                             "%s command.", cmd);
839                         return(-1);
840                 }
841                 /* Try to get second pathname (optional) */
842                 if (get_pathname(&cp, path2))
843                         return(-1);
844                 break;
845         case I_RENAME:
846         case I_SYMLINK:
847                 if (get_pathname(&cp, path1))
848                         return(-1);
849                 if (get_pathname(&cp, path2))
850                         return(-1);
851                 if (!*path1 || !*path2) {
852                         error("You must specify two paths after a %s "
853                             "command.", cmd);
854                         return(-1);
855                 }
856                 break;
857         case I_RM:
858         case I_MKDIR:
859         case I_RMDIR:
860         case I_CHDIR:
861         case I_LCHDIR:
862         case I_LMKDIR:
863                 /* Get pathname (mandatory) */
864                 if (get_pathname(&cp, path1))
865                         return(-1);
866                 if (*path1 == NULL) {
867                         error("You must specify a path after a %s command.",
868                             cmd);
869                         return(-1);
870                 }
871                 break;
872         case I_LS:
873                 if (parse_ls_flags(&cp, lflag))
874                         return(-1);
875                 /* Path is optional */
876                 if (get_pathname(&cp, path1))
877                         return(-1);
878                 break;
879         case I_LLS:
880         case I_SHELL:
881                 /* Uses the rest of the line */
882                 break;
883         case I_LUMASK:
884                 base = 8;
885         case I_CHMOD:
886                 base = 8;
887         case I_CHOWN:
888         case I_CHGRP:
889                 /* Get numeric arg (mandatory) */
890                 l = strtol(cp, &cp2, base);
891                 if (cp2 == cp || ((l == LONG_MIN || l == LONG_MAX) &&
892                     errno == ERANGE) || l < 0) {
893                         error("You must supply a numeric argument "
894                             "to the %s command.", cmd);
895                         return(-1);
896                 }
897                 cp = cp2;
898                 *n_arg = l;
899                 if (cmdnum == I_LUMASK && strchr(WHITESPACE, *cp))
900                         break;
901                 if (cmdnum == I_LUMASK || !strchr(WHITESPACE, *cp)) {
902                         error("You must supply a numeric argument "
903                             "to the %s command.", cmd);
904                         return(-1);
905                 }
906                 cp += strspn(cp, WHITESPACE);
907
908                 /* Get pathname (mandatory) */
909                 if (get_pathname(&cp, path1))
910                         return(-1);
911                 if (*path1 == NULL) {
912                         error("You must specify a path after a %s command.",
913                             cmd);
914                         return(-1);
915                 }
916                 break;
917         case I_QUIT:
918         case I_PWD:
919         case I_LPWD:
920         case I_HELP:
921         case I_VERSION:
922         case I_PROGRESS:
923                 break;
924         default:
925                 fatal("Command not implemented");
926         }
927
928         *cpp = cp;
929         return(cmdnum);
930 }
931
932 static int
933 parse_dispatch_command(struct sftp_conn *conn, const char *cmd, char **pwd,
934     int err_abort)
935 {
936         char *path1, *path2, *tmp;
937         int pflag, lflag, iflag, cmdnum, i;
938         unsigned long n_arg;
939         Attrib a, *aa;
940         char path_buf[MAXPATHLEN];
941         int err = 0;
942         glob_t g;
943
944         path1 = path2 = NULL;
945         cmdnum = parse_args(&cmd, &pflag, &lflag, &iflag, &n_arg,
946             &path1, &path2);
947
948         if (iflag != 0)
949                 err_abort = 0;
950
951         memset(&g, 0, sizeof(g));
952
953         /* Perform command */
954         switch (cmdnum) {
955         case 0:
956                 /* Blank line */
957                 break;
958         case -1:
959                 /* Unrecognized command */
960                 err = -1;
961                 break;
962         case I_GET:
963                 err = process_get(conn, path1, path2, *pwd, pflag);
964                 break;
965         case I_PUT:
966                 err = process_put(conn, path1, path2, *pwd, pflag);
967                 break;
968         case I_RENAME:
969                 path1 = make_absolute(path1, *pwd);
970                 path2 = make_absolute(path2, *pwd);
971                 err = do_rename(conn, path1, path2);
972                 break;
973         case I_SYMLINK:
974                 path2 = make_absolute(path2, *pwd);
975                 err = do_symlink(conn, path1, path2);
976                 break;
977         case I_RM:
978                 path1 = make_absolute(path1, *pwd);
979                 remote_glob(conn, path1, GLOB_NOCHECK, NULL, &g);
980                 for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
981                         printf("Removing %s\n", g.gl_pathv[i]);
982                         err = do_rm(conn, g.gl_pathv[i]);
983                         if (err != 0 && err_abort)
984                                 break;
985                 }
986                 break;
987         case I_MKDIR:
988                 path1 = make_absolute(path1, *pwd);
989                 attrib_clear(&a);
990                 a.flags |= SSH2_FILEXFER_ATTR_PERMISSIONS;
991                 a.perm = 0777;
992                 err = do_mkdir(conn, path1, &a);
993                 break;
994         case I_RMDIR:
995                 path1 = make_absolute(path1, *pwd);
996                 err = do_rmdir(conn, path1);
997                 break;
998         case I_CHDIR:
999                 path1 = make_absolute(path1, *pwd);
1000                 if ((tmp = do_realpath(conn, path1)) == NULL) {
1001                         err = 1;
1002                         break;
1003                 }
1004                 if ((aa = do_stat(conn, tmp, 0)) == NULL) {
1005                         xfree(tmp);
1006                         err = 1;
1007                         break;
1008                 }
1009                 if (!(aa->flags & SSH2_FILEXFER_ATTR_PERMISSIONS)) {
1010                         error("Can't change directory: Can't check target");
1011                         xfree(tmp);
1012                         err = 1;
1013                         break;
1014                 }
1015                 if (!S_ISDIR(aa->perm)) {
1016                         error("Can't change directory: \"%s\" is not "
1017                             "a directory", tmp);
1018                         xfree(tmp);
1019                         err = 1;
1020                         break;
1021                 }
1022                 xfree(*pwd);
1023                 *pwd = tmp;
1024                 break;
1025         case I_LS:
1026                 if (!path1) {
1027                         do_globbed_ls(conn, *pwd, *pwd, lflag);
1028                         break;
1029                 }
1030
1031                 /* Strip pwd off beginning of non-absolute paths */
1032                 tmp = NULL;
1033                 if (*path1 != '/')
1034                         tmp = *pwd;
1035
1036                 path1 = make_absolute(path1, *pwd);
1037                 err = do_globbed_ls(conn, path1, tmp, lflag);
1038                 break;
1039         case I_LCHDIR:
1040                 if (chdir(path1) == -1) {
1041                         error("Couldn't change local directory to "
1042                             "\"%s\": %s", path1, strerror(errno));
1043                         err = 1;
1044                 }
1045                 break;
1046         case I_LMKDIR:
1047                 if (mkdir(path1, 0777) == -1) {
1048                         error("Couldn't create local directory "
1049                             "\"%s\": %s", path1, strerror(errno));
1050                         err = 1;
1051                 }
1052                 break;
1053         case I_LLS:
1054                 local_do_ls(cmd);
1055                 break;
1056         case I_SHELL:
1057                 local_do_shell(cmd);
1058                 break;
1059         case I_LUMASK:
1060                 umask(n_arg);
1061                 printf("Local umask: %03lo\n", n_arg);
1062                 break;
1063         case I_CHMOD:
1064                 path1 = make_absolute(path1, *pwd);
1065                 attrib_clear(&a);
1066                 a.flags |= SSH2_FILEXFER_ATTR_PERMISSIONS;
1067                 a.perm = n_arg;
1068                 remote_glob(conn, path1, GLOB_NOCHECK, NULL, &g);
1069                 for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
1070                         printf("Changing mode on %s\n", g.gl_pathv[i]);
1071                         err = do_setstat(conn, g.gl_pathv[i], &a);
1072                         if (err != 0 && err_abort)
1073                                 break;
1074                 }
1075                 break;
1076         case I_CHOWN:
1077         case I_CHGRP:
1078                 path1 = make_absolute(path1, *pwd);
1079                 remote_glob(conn, path1, GLOB_NOCHECK, NULL, &g);
1080                 for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
1081                         if (!(aa = do_stat(conn, g.gl_pathv[i], 0))) {
1082                                 if (err != 0 && err_abort)
1083                                         break;
1084                                 else
1085                                         continue;
1086                         }
1087                         if (!(aa->flags & SSH2_FILEXFER_ATTR_UIDGID)) {
1088                                 error("Can't get current ownership of "
1089                                     "remote file \"%s\"", g.gl_pathv[i]);
1090                                 if (err != 0 && err_abort)
1091                                         break;
1092                                 else
1093                                         continue;
1094                         }
1095                         aa->flags &= SSH2_FILEXFER_ATTR_UIDGID;
1096                         if (cmdnum == I_CHOWN) {
1097                                 printf("Changing owner on %s\n", g.gl_pathv[i]);
1098                                 aa->uid = n_arg;
1099                         } else {
1100                                 printf("Changing group on %s\n", g.gl_pathv[i]);
1101                                 aa->gid = n_arg;
1102                         }
1103                         err = do_setstat(conn, g.gl_pathv[i], aa);
1104                         if (err != 0 && err_abort)
1105                                 break;
1106                 }
1107                 break;
1108         case I_PWD:
1109                 printf("Remote working directory: %s\n", *pwd);
1110                 break;
1111         case I_LPWD:
1112                 if (!getcwd(path_buf, sizeof(path_buf))) {
1113                         error("Couldn't get local cwd: %s", strerror(errno));
1114                         err = -1;
1115                         break;
1116                 }
1117                 printf("Local working directory: %s\n", path_buf);
1118                 break;
1119         case I_QUIT:
1120                 /* Processed below */
1121                 break;
1122         case I_HELP:
1123                 help();
1124                 break;
1125         case I_VERSION:
1126                 printf("SFTP protocol version %u\n", sftp_proto_version(conn));
1127                 break;
1128         case I_PROGRESS:
1129                 showprogress = !showprogress;
1130                 if (showprogress)
1131                         printf("Progress meter enabled\n");
1132                 else
1133                         printf("Progress meter disabled\n");
1134                 break;
1135         default:
1136                 fatal("%d is not implemented", cmdnum);
1137         }
1138
1139         if (g.gl_pathc)
1140                 globfree(&g);
1141         if (path1)
1142                 xfree(path1);
1143         if (path2)
1144                 xfree(path2);
1145
1146         /* If an unignored error occurs in batch mode we should abort. */
1147         if (err_abort && err != 0)
1148                 return (-1);
1149         else if (cmdnum == I_QUIT)
1150                 return (1);
1151
1152         return (0);
1153 }
1154
1155 int
1156 interactive_loop(int fd_in, int fd_out, char *file1, char *file2)
1157 {
1158         char *pwd;
1159         char *dir = NULL;
1160         char cmd[2048];
1161         struct sftp_conn *conn;
1162         int err;
1163
1164         conn = do_init(fd_in, fd_out, copy_buffer_len, num_requests);
1165         if (conn == NULL)
1166                 fatal("Couldn't initialise connection to server");
1167
1168         pwd = do_realpath(conn, ".");
1169         if (pwd == NULL)
1170                 fatal("Need cwd");
1171
1172         if (file1 != NULL) {
1173                 dir = xstrdup(file1);
1174                 dir = make_absolute(dir, pwd);
1175
1176                 if (remote_is_dir(conn, dir) && file2 == NULL) {
1177                         printf("Changing to: %s\n", dir);
1178                         snprintf(cmd, sizeof cmd, "cd \"%s\"", dir);
1179                         if (parse_dispatch_command(conn, cmd, &pwd, 1) != 0)
1180                                 return (-1);
1181                 } else {
1182                         if (file2 == NULL)
1183                                 snprintf(cmd, sizeof cmd, "get %s", dir);
1184                         else
1185                                 snprintf(cmd, sizeof cmd, "get %s %s", dir,
1186                                     file2);
1187
1188                         err = parse_dispatch_command(conn, cmd, &pwd, 1);
1189                         xfree(dir);
1190                         xfree(pwd);
1191                         return (err);
1192                 }
1193                 xfree(dir);
1194         }
1195
1196 #if HAVE_SETVBUF
1197         setvbuf(stdout, NULL, _IOLBF, 0);
1198         setvbuf(infile, NULL, _IOLBF, 0);
1199 #else
1200        setlinebuf(stdout);
1201        setlinebuf(infile);
1202 #endif
1203
1204         err = 0;
1205         for (;;) {
1206                 char *cp;
1207
1208                 signal(SIGINT, SIG_IGN);
1209
1210                 printf("sftp> ");
1211
1212                 /* XXX: use libedit */
1213                 if (fgets(cmd, sizeof(cmd), infile) == NULL) {
1214                         printf("\n");
1215                         break;
1216                 }
1217
1218                 if (batchmode) /* Echo command */
1219                         printf("%s", cmd);
1220
1221                 cp = strrchr(cmd, '\n');
1222                 if (cp)
1223                         *cp = '\0';
1224
1225                 /* Handle user interrupts gracefully during commands */
1226                 interrupted = 0;
1227                 signal(SIGINT, cmd_interrupt);
1228
1229                 err = parse_dispatch_command(conn, cmd, &pwd, batchmode);
1230                 if (err != 0)
1231                         break;
1232         }
1233         xfree(pwd);
1234
1235         /* err == 1 signifies normal "quit" exit */
1236         return (err >= 0 ? 0 : -1);
1237 }
1238
1239 static void
1240 connect_to_server(char *path, char **args, int *in, int *out)
1241 {
1242         int c_in, c_out;
1243
1244 #ifdef USE_PIPES
1245         int pin[2], pout[2];
1246
1247         if ((pipe(pin) == -1) || (pipe(pout) == -1))
1248                 fatal("pipe: %s", strerror(errno));
1249         *in = pin[0];
1250         *out = pout[1];
1251         c_in = pout[0];
1252         c_out = pin[1];
1253 #else /* USE_PIPES */
1254         int inout[2];
1255
1256         if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) == -1)
1257                 fatal("socketpair: %s", strerror(errno));
1258         *in = *out = inout[0];
1259         c_in = c_out = inout[1];
1260 #endif /* USE_PIPES */
1261
1262         if ((sshpid = fork()) == -1)
1263                 fatal("fork: %s", strerror(errno));
1264         else if (sshpid == 0) {
1265                 if ((dup2(c_in, STDIN_FILENO) == -1) ||
1266                     (dup2(c_out, STDOUT_FILENO) == -1)) {
1267                         fprintf(stderr, "dup2: %s\n", strerror(errno));
1268                         exit(1);
1269                 }
1270                 close(*in);
1271                 close(*out);
1272                 close(c_in);
1273                 close(c_out);
1274
1275                 /*
1276                  * The underlying ssh is in the same process group, so we must
1277                  * ignore SIGINT if we want to gracefully abort commands, 
1278                  * otherwise the signal will make it to the ssh process and 
1279                  * kill it too
1280                  */
1281                 signal(SIGINT, SIG_IGN);
1282                 execv(path, args);
1283                 fprintf(stderr, "exec: %s: %s\n", path, strerror(errno));
1284                 exit(1);
1285         }
1286
1287         signal(SIGTERM, killchild);
1288         signal(SIGINT, killchild);
1289         signal(SIGHUP, killchild);
1290         close(c_in);
1291         close(c_out);
1292 }
1293
1294 static void
1295 usage(void)
1296 {
1297         extern char *__progname;
1298
1299         fprintf(stderr,
1300             "usage: %s [-1Cv] [-B buffer_size] [-b batchfile] [-F ssh_config]\n"
1301             "            [-o ssh_option] [-P sftp_server_path] [-R num_requests]\n"
1302             "            [-S program] [-s subsystem | sftp_server] host\n"
1303             "       %s [[user@]host[:file [file]]]\n"
1304             "       %s [[user@]host[:dir[/]]]\n"
1305             "       %s -b batchfile [user@]host\n", __progname, __progname, __progname, __progname);
1306         exit(1);
1307 }
1308
1309 int
1310 main(int argc, char **argv)
1311 {
1312         int in, out, ch, err;
1313         char *host, *userhost, *cp, *file2;
1314         int debug_level = 0, sshver = 2;
1315         char *file1 = NULL, *sftp_server = NULL;
1316         char *ssh_program = _PATH_SSH_PROGRAM, *sftp_direct = NULL;
1317         LogLevel ll = SYSLOG_LEVEL_INFO;
1318         arglist args;
1319         extern int optind;
1320         extern char *optarg;
1321
1322         __progname = ssh_get_progname(argv[0]);
1323         args.list = NULL;
1324         addargs(&args, "ssh");          /* overwritten with ssh_program */
1325         addargs(&args, "-oForwardX11 no");
1326         addargs(&args, "-oForwardAgent no");
1327         addargs(&args, "-oClearAllForwardings yes");
1328
1329         ll = SYSLOG_LEVEL_INFO;
1330         infile = stdin;
1331
1332         while ((ch = getopt(argc, argv, "1hvCo:s:S:b:B:F:P:R:")) != -1) {
1333                 switch (ch) {
1334                 case 'C':
1335                         addargs(&args, "-C");
1336                         break;
1337                 case 'v':
1338                         if (debug_level < 3) {
1339                                 addargs(&args, "-v");
1340                                 ll = SYSLOG_LEVEL_DEBUG1 + debug_level;
1341                         }
1342                         debug_level++;
1343                         break;
1344                 case 'F':
1345                 case 'o':
1346                         addargs(&args, "-%c%s", ch, optarg);
1347                         break;
1348                 case '1':
1349                         sshver = 1;
1350                         if (sftp_server == NULL)
1351                                 sftp_server = _PATH_SFTP_SERVER;
1352                         break;
1353                 case 's':
1354                         sftp_server = optarg;
1355                         break;
1356                 case 'S':
1357                         ssh_program = optarg;
1358                         break;
1359                 case 'b':
1360                         if (batchmode)
1361                                 fatal("Batch file already specified.");
1362
1363                         /* Allow "-" as stdin */
1364                         if (strcmp(optarg, "-") != 0 && 
1365                            (infile = fopen(optarg, "r")) == NULL)
1366                                 fatal("%s (%s).", strerror(errno), optarg);
1367                         showprogress = 0;
1368                         batchmode = 1;
1369                         break;
1370                 case 'P':
1371                         sftp_direct = optarg;
1372                         break;
1373                 case 'B':
1374                         copy_buffer_len = strtol(optarg, &cp, 10);
1375                         if (copy_buffer_len == 0 || *cp != '\0')
1376                                 fatal("Invalid buffer size \"%s\"", optarg);
1377                         break;
1378                 case 'R':
1379                         num_requests = strtol(optarg, &cp, 10);
1380                         if (num_requests == 0 || *cp != '\0')
1381                                 fatal("Invalid number of requests \"%s\"",
1382                                     optarg);
1383                         break;
1384                 case 'h':
1385                 default:
1386                         usage();
1387                 }
1388         }
1389
1390         if (!isatty(STDERR_FILENO))
1391                 showprogress = 0;
1392
1393         log_init(argv[0], ll, SYSLOG_FACILITY_USER, 1);
1394
1395         if (sftp_direct == NULL) {
1396                 if (optind == argc || argc > (optind + 2))
1397                         usage();
1398
1399                 userhost = xstrdup(argv[optind]);
1400                 file2 = argv[optind+1];
1401
1402                 if ((host = strrchr(userhost, '@')) == NULL)
1403                         host = userhost;
1404                 else {
1405                         *host++ = '\0';
1406                         if (!userhost[0]) {
1407                                 fprintf(stderr, "Missing username\n");
1408                                 usage();
1409                         }
1410                         addargs(&args, "-l%s",userhost);
1411                 }
1412
1413                 if ((cp = colon(host)) != NULL) {
1414                         *cp++ = '\0';
1415                         file1 = cp;
1416                 }
1417
1418                 host = cleanhostname(host);
1419                 if (!*host) {
1420                         fprintf(stderr, "Missing hostname\n");
1421                         usage();
1422                 }
1423
1424                 addargs(&args, "-oProtocol %d", sshver);
1425
1426                 /* no subsystem if the server-spec contains a '/' */
1427                 if (sftp_server == NULL || strchr(sftp_server, '/') == NULL)
1428                         addargs(&args, "-s");
1429
1430                 addargs(&args, "%s", host);
1431                 addargs(&args, "%s", (sftp_server != NULL ?
1432                     sftp_server : "sftp"));
1433                 args.list[0] = ssh_program;
1434
1435                 if (!batchmode)
1436                         fprintf(stderr, "Connecting to %s...\n", host);
1437                 connect_to_server(ssh_program, args.list, &in, &out);
1438         } else {
1439                 args.list = NULL;
1440                 addargs(&args, "sftp-server");
1441
1442                 if (!batchmode)
1443                         fprintf(stderr, "Attaching to %s...\n", sftp_direct);
1444                 connect_to_server(sftp_direct, args.list, &in, &out);
1445         }
1446
1447         err = interactive_loop(in, out, file1, file2);
1448
1449 #if !defined(USE_PIPES)
1450        shutdown(in, SHUT_RDWR);
1451        shutdown(out, SHUT_RDWR);
1452 #endif
1453
1454         close(in);
1455         close(out);
1456         if (batchmode)
1457                 fclose(infile);
1458
1459         while (waitpid(sshpid, NULL, 0) == -1)
1460                 if (errno != EINTR)
1461                         fatal("Couldn't wait for ssh process: %s",
1462                             strerror(errno));
1463
1464         exit(err == 0 ? 0 : 1);
1465 }
This page took 0.343169 seconds and 5 git commands to generate.