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