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