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