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