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