Annotation of src/usr.bin/ssh/sftp.c, Revision 1.151
1.151 ! djm 1: /* $OpenBSD: sftp.c,v 1.150 2013/08/07 06:24:51 jmc 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.100 djm 24: #include <sys/statvfs.h>
1.44 djm 25:
1.97 djm 26: #include <ctype.h>
1.85 stevesk 27: #include <errno.h>
1.44 djm 28: #include <glob.h>
1.57 djm 29: #include <histedit.h>
1.71 stevesk 30: #include <paths.h>
1.111 djm 31: #include <libgen.h>
1.146 dtucker 32: #include <locale.h>
1.74 stevesk 33: #include <signal.h>
1.89 stevesk 34: #include <stdlib.h>
1.90 stevesk 35: #include <stdio.h>
1.87 stevesk 36: #include <string.h>
1.86 stevesk 37: #include <unistd.h>
1.100 djm 38: #include <util.h>
1.91 deraadt 39: #include <stdarg.h>
1.1 djm 40:
41: #include "xmalloc.h"
42: #include "log.h"
43: #include "pathnames.h"
1.16 mouring 44: #include "misc.h"
1.1 djm 45:
46: #include "sftp.h"
1.91 deraadt 47: #include "buffer.h"
1.1 djm 48: #include "sftp-common.h"
49: #include "sftp-client.h"
1.43 djm 50:
1.112 djm 51: #define DEFAULT_COPY_BUFLEN 32768 /* Size of buffer for up/download */
52: #define DEFAULT_NUM_REQUESTS 64 /* # concurrent outstanding requests */
53:
1.44 djm 54: /* File to read commands from */
55: FILE* infile;
1.15 mouring 56:
1.44 djm 57: /* Are we in batchfile mode? */
1.39 djm 58: int batchmode = 0;
1.44 djm 59:
60: /* PID of ssh transport process */
1.36 djm 61: static pid_t sshpid = -1;
1.7 markus 62:
1.143 djm 63: /* Suppress diagnositic messages */
64: int quiet = 0;
65:
1.44 djm 66: /* This is set to 0 if the progressmeter is not desired. */
1.45 djm 67: int showprogress = 1;
1.44 djm 68:
1.111 djm 69: /* When this option is set, we always recursively download/upload directories */
70: int global_rflag = 0;
71:
1.148 djm 72: /* When this option is set, we resume download if possible */
73: int global_aflag = 0;
74:
1.111 djm 75: /* When this option is set, the file transfers will always preserve times */
76: int global_pflag = 0;
77:
1.46 djm 78: /* SIGINT received during command processing */
79: volatile sig_atomic_t interrupted = 0;
80:
1.52 djm 81: /* I wish qsort() took a separate ctx for the comparison function...*/
82: int sort_flag;
83:
1.116 djm 84: /* Context used for commandline completion */
85: struct complete_ctx {
86: struct sftp_conn *conn;
87: char **remote_pathp;
88: };
89:
1.44 djm 90: int remote_glob(struct sftp_conn *, const char *, int,
91: int (*)(const char *, int), glob_t *); /* proto for sftp-glob.c */
92:
93: /* Separators for interactive commands */
94: #define WHITESPACE " \t\r\n"
95:
1.52 djm 96: /* ls flags */
1.119 djm 97: #define LS_LONG_VIEW 0x0001 /* Full view ala ls -l */
98: #define LS_SHORT_VIEW 0x0002 /* Single row view ala ls -1 */
99: #define LS_NUMERIC_VIEW 0x0004 /* Long view with numeric uid/gid */
100: #define LS_NAME_SORT 0x0008 /* Sort by name (default) */
101: #define LS_TIME_SORT 0x0010 /* Sort by mtime */
102: #define LS_SIZE_SORT 0x0020 /* Sort by file size */
103: #define LS_REVERSE_SORT 0x0040 /* Reverse sort order */
104: #define LS_SHOW_ALL 0x0080 /* Don't skip filenames starting with '.' */
105: #define LS_SI_UNITS 0x0100 /* Display sizes as K, M, G, etc. */
1.52 djm 106:
1.119 djm 107: #define VIEW_FLAGS (LS_LONG_VIEW|LS_SHORT_VIEW|LS_NUMERIC_VIEW|LS_SI_UNITS)
1.53 djm 108: #define SORT_FLAGS (LS_NAME_SORT|LS_TIME_SORT|LS_SIZE_SORT)
1.44 djm 109:
110: /* Commands for interactive mode */
1.149 djm 111: enum sftp_command {
112: I_CHDIR = 1,
113: I_CHGRP,
114: I_CHMOD,
115: I_CHOWN,
116: I_DF,
117: I_GET,
118: I_HELP,
119: I_LCHDIR,
120: I_LINK,
121: I_LLS,
122: I_LMKDIR,
123: I_LPWD,
124: I_LS,
125: I_LUMASK,
126: I_MKDIR,
127: I_PUT,
128: I_PWD,
129: I_QUIT,
130: I_RENAME,
131: I_RM,
132: I_RMDIR,
133: I_SHELL,
134: I_SYMLINK,
135: I_VERSION,
136: I_PROGRESS,
137: I_REGET,
138: };
1.44 djm 139:
140: struct CMD {
141: const char *c;
142: const int n;
1.116 djm 143: const int t;
1.44 djm 144: };
145:
1.116 djm 146: /* Type of completion */
147: #define NOARGS 0
148: #define REMOTE 1
149: #define LOCAL 2
150:
1.44 djm 151: static const struct CMD cmds[] = {
1.116 djm 152: { "bye", I_QUIT, NOARGS },
153: { "cd", I_CHDIR, REMOTE },
154: { "chdir", I_CHDIR, REMOTE },
155: { "chgrp", I_CHGRP, REMOTE },
156: { "chmod", I_CHMOD, REMOTE },
157: { "chown", I_CHOWN, REMOTE },
158: { "df", I_DF, REMOTE },
159: { "dir", I_LS, REMOTE },
160: { "exit", I_QUIT, NOARGS },
161: { "get", I_GET, REMOTE },
162: { "help", I_HELP, NOARGS },
163: { "lcd", I_LCHDIR, LOCAL },
164: { "lchdir", I_LCHDIR, LOCAL },
165: { "lls", I_LLS, LOCAL },
166: { "lmkdir", I_LMKDIR, LOCAL },
1.132 djm 167: { "ln", I_LINK, REMOTE },
1.116 djm 168: { "lpwd", I_LPWD, LOCAL },
169: { "ls", I_LS, REMOTE },
170: { "lumask", I_LUMASK, NOARGS },
171: { "mkdir", I_MKDIR, REMOTE },
1.124 dtucker 172: { "mget", I_GET, REMOTE },
173: { "mput", I_PUT, LOCAL },
1.116 djm 174: { "progress", I_PROGRESS, NOARGS },
175: { "put", I_PUT, LOCAL },
176: { "pwd", I_PWD, REMOTE },
177: { "quit", I_QUIT, NOARGS },
1.148 djm 178: { "reget", I_REGET, REMOTE },
1.116 djm 179: { "rename", I_RENAME, REMOTE },
180: { "rm", I_RM, REMOTE },
181: { "rmdir", I_RMDIR, REMOTE },
182: { "symlink", I_SYMLINK, REMOTE },
183: { "version", I_VERSION, NOARGS },
184: { "!", I_SHELL, NOARGS },
185: { "?", I_HELP, NOARGS },
186: { NULL, -1, -1 }
1.44 djm 187: };
188:
1.112 djm 189: int interactive_loop(struct sftp_conn *, char *file1, char *file2);
1.44 djm 190:
1.96 stevesk 191: /* ARGSUSED */
1.44 djm 192: static void
1.46 djm 193: killchild(int signo)
194: {
1.61 dtucker 195: if (sshpid > 1) {
1.46 djm 196: kill(sshpid, SIGTERM);
1.61 dtucker 197: waitpid(sshpid, NULL, 0);
198: }
1.46 djm 199:
200: _exit(1);
201: }
202:
1.96 stevesk 203: /* ARGSUSED */
1.46 djm 204: static void
205: cmd_interrupt(int signo)
206: {
207: const char msg[] = "\rInterrupt \n";
1.59 djm 208: int olderrno = errno;
1.46 djm 209:
1.144 dtucker 210: (void)write(STDERR_FILENO, msg, sizeof(msg) - 1);
1.46 djm 211: interrupted = 1;
1.59 djm 212: errno = olderrno;
1.46 djm 213: }
214:
215: static void
1.44 djm 216: help(void)
217: {
1.106 sobrado 218: printf("Available commands:\n"
219: "bye Quit sftp\n"
220: "cd path Change remote directory to 'path'\n"
221: "chgrp grp path Change group of file 'path' to 'grp'\n"
222: "chmod mode path Change permissions of file 'path' to 'mode'\n"
223: "chown own path Change owner of file 'path' to 'own'\n"
224: "df [-hi] [path] Display statistics for current directory or\n"
225: " filesystem containing 'path'\n"
226: "exit Quit sftp\n"
1.121 jmc 227: "get [-Ppr] remote [local] Download file\n"
1.148 djm 228: "reget remote [local] Resume download file\n"
1.106 sobrado 229: "help Display this help text\n"
230: "lcd path Change local directory to 'path'\n"
231: "lls [ls-options [path]] Display local directory listing\n"
232: "lmkdir path Create local directory\n"
1.132 djm 233: "ln [-s] oldpath newpath Link remote file (-s for symlink)\n"
1.106 sobrado 234: "lpwd Print local working directory\n"
1.121 jmc 235: "ls [-1afhlnrSt] [path] Display remote directory listing\n"
1.106 sobrado 236: "lumask umask Set local umask to 'umask'\n"
237: "mkdir path Create remote directory\n"
238: "progress Toggle display of progress meter\n"
1.121 jmc 239: "put [-Ppr] local [remote] Upload file\n"
1.106 sobrado 240: "pwd Display remote working directory\n"
241: "quit Quit sftp\n"
242: "rename oldpath newpath Rename remote file\n"
243: "rm path Delete remote file\n"
244: "rmdir path Remove remote directory\n"
245: "symlink oldpath newpath Symlink remote file\n"
246: "version Show SFTP version\n"
247: "!command Execute 'command' in local shell\n"
248: "! Escape to local shell\n"
249: "? Synonym for help\n");
1.44 djm 250: }
251:
252: static void
253: local_do_shell(const char *args)
254: {
255: int status;
256: char *shell;
257: pid_t pid;
258:
259: if (!*args)
260: args = NULL;
261:
1.130 djm 262: if ((shell = getenv("SHELL")) == NULL || *shell == '\0')
1.44 djm 263: shell = _PATH_BSHELL;
264:
265: if ((pid = fork()) == -1)
266: fatal("Couldn't fork: %s", strerror(errno));
267:
268: if (pid == 0) {
269: /* XXX: child has pipe fds to ssh subproc open - issue? */
270: if (args) {
271: debug3("Executing %s -c \"%s\"", shell, args);
272: execl(shell, shell, "-c", args, (char *)NULL);
273: } else {
274: debug3("Executing %s", shell);
275: execl(shell, shell, (char *)NULL);
276: }
277: fprintf(stderr, "Couldn't execute \"%s\": %s\n", shell,
278: strerror(errno));
279: _exit(1);
280: }
281: while (waitpid(pid, &status, 0) == -1)
282: if (errno != EINTR)
283: fatal("Couldn't wait for child: %s", strerror(errno));
284: if (!WIFEXITED(status))
1.78 djm 285: error("Shell exited abnormally");
1.44 djm 286: else if (WEXITSTATUS(status))
287: error("Shell exited with status %d", WEXITSTATUS(status));
288: }
289:
290: static void
291: local_do_ls(const char *args)
292: {
293: if (!args || !*args)
294: local_do_shell(_PATH_LS);
295: else {
296: int len = strlen(_PATH_LS " ") + strlen(args) + 1;
297: char *buf = xmalloc(len);
298:
299: /* XXX: quoting - rip quoting code from ftp? */
300: snprintf(buf, len, _PATH_LS " %s", args);
301: local_do_shell(buf);
1.145 djm 302: free(buf);
1.44 djm 303: }
304: }
305:
306: /* Strip one path (usually the pwd) from the start of another */
307: static char *
308: path_strip(char *path, char *strip)
309: {
310: size_t len;
311:
312: if (strip == NULL)
313: return (xstrdup(path));
314:
315: len = strlen(strip);
1.59 djm 316: if (strncmp(path, strip, len) == 0) {
1.44 djm 317: if (strip[len - 1] != '/' && path[len] == '/')
318: len++;
319: return (xstrdup(path + len));
320: }
321:
322: return (xstrdup(path));
323: }
324:
325: static char *
326: make_absolute(char *p, char *pwd)
327: {
1.51 avsm 328: char *abs_str;
1.44 djm 329:
330: /* Derelativise */
331: if (p && p[0] != '/') {
1.51 avsm 332: abs_str = path_append(pwd, p);
1.145 djm 333: free(p);
1.51 avsm 334: return(abs_str);
1.44 djm 335: } else
336: return(p);
337: }
338:
339: static int
1.148 djm 340: parse_getput_flags(const char *cmd, char **argv, int argc,
341: int *aflag, int *pflag, int *rflag)
1.44 djm 342: {
1.102 martynas 343: extern int opterr, optind, optopt, optreset;
1.97 djm 344: int ch;
1.44 djm 345:
1.97 djm 346: optind = optreset = 1;
347: opterr = 0;
348:
1.148 djm 349: *aflag = *rflag = *pflag = 0;
350: while ((ch = getopt(argc, argv, "aPpRr")) != -1) {
1.97 djm 351: switch (ch) {
1.148 djm 352: case 'a':
353: *aflag = 1;
354: break;
1.44 djm 355: case 'p':
356: case 'P':
357: *pflag = 1;
358: break;
1.111 djm 359: case 'r':
360: case 'R':
361: *rflag = 1;
362: break;
1.44 djm 363: default:
1.102 martynas 364: error("%s: Invalid flag -%c", cmd, optopt);
1.97 djm 365: return -1;
1.44 djm 366: }
367: }
368:
1.97 djm 369: return optind;
1.44 djm 370: }
371:
372: static int
1.132 djm 373: parse_link_flags(const char *cmd, char **argv, int argc, int *sflag)
374: {
375: extern int opterr, optind, optopt, optreset;
376: int ch;
377:
378: optind = optreset = 1;
379: opterr = 0;
380:
381: *sflag = 0;
382: while ((ch = getopt(argc, argv, "s")) != -1) {
383: switch (ch) {
384: case 's':
385: *sflag = 1;
386: break;
387: default:
388: error("%s: Invalid flag -%c", cmd, optopt);
389: return -1;
390: }
391: }
392:
393: return optind;
394: }
395:
396: static int
1.97 djm 397: parse_ls_flags(char **argv, int argc, int *lflag)
1.44 djm 398: {
1.102 martynas 399: extern int opterr, optind, optopt, optreset;
1.97 djm 400: int ch;
401:
402: optind = optreset = 1;
403: opterr = 0;
1.44 djm 404:
1.53 djm 405: *lflag = LS_NAME_SORT;
1.119 djm 406: while ((ch = getopt(argc, argv, "1Safhlnrt")) != -1) {
1.97 djm 407: switch (ch) {
408: case '1':
409: *lflag &= ~VIEW_FLAGS;
410: *lflag |= LS_SHORT_VIEW;
411: break;
412: case 'S':
413: *lflag &= ~SORT_FLAGS;
414: *lflag |= LS_SIZE_SORT;
415: break;
416: case 'a':
417: *lflag |= LS_SHOW_ALL;
418: break;
419: case 'f':
420: *lflag &= ~SORT_FLAGS;
421: break;
1.119 djm 422: case 'h':
423: *lflag |= LS_SI_UNITS;
424: break;
1.97 djm 425: case 'l':
1.119 djm 426: *lflag &= ~LS_SHORT_VIEW;
1.97 djm 427: *lflag |= LS_LONG_VIEW;
428: break;
429: case 'n':
1.119 djm 430: *lflag &= ~LS_SHORT_VIEW;
1.97 djm 431: *lflag |= LS_NUMERIC_VIEW|LS_LONG_VIEW;
432: break;
433: case 'r':
434: *lflag |= LS_REVERSE_SORT;
435: break;
436: case 't':
437: *lflag &= ~SORT_FLAGS;
438: *lflag |= LS_TIME_SORT;
439: break;
440: default:
1.102 martynas 441: error("ls: Invalid flag -%c", optopt);
1.97 djm 442: return -1;
1.44 djm 443: }
444: }
445:
1.97 djm 446: return optind;
1.44 djm 447: }
448:
449: static int
1.100 djm 450: parse_df_flags(const char *cmd, char **argv, int argc, int *hflag, int *iflag)
451: {
1.102 martynas 452: extern int opterr, optind, optopt, optreset;
1.100 djm 453: int ch;
454:
455: optind = optreset = 1;
456: opterr = 0;
457:
458: *hflag = *iflag = 0;
459: while ((ch = getopt(argc, argv, "hi")) != -1) {
460: switch (ch) {
461: case 'h':
462: *hflag = 1;
463: break;
464: case 'i':
465: *iflag = 1;
466: break;
467: default:
1.102 martynas 468: error("%s: Invalid flag -%c", cmd, optopt);
1.100 djm 469: return -1;
470: }
471: }
472:
473: return optind;
474: }
475:
476: static int
1.44 djm 477: is_dir(char *path)
478: {
479: struct stat sb;
480:
481: /* XXX: report errors? */
482: if (stat(path, &sb) == -1)
483: return(0);
484:
1.92 otto 485: return(S_ISDIR(sb.st_mode));
1.44 djm 486: }
487:
488: static int
489: remote_is_dir(struct sftp_conn *conn, char *path)
490: {
491: Attrib *a;
492:
493: /* XXX: report errors? */
494: if ((a = do_stat(conn, path, 1)) == NULL)
495: return(0);
496: if (!(a->flags & SSH2_FILEXFER_ATTR_PERMISSIONS))
497: return(0);
1.92 otto 498: return(S_ISDIR(a->perm));
1.44 djm 499: }
500:
1.111 djm 501: /* Check whether path returned from glob(..., GLOB_MARK, ...) is a directory */
502: static int
503: pathname_is_dir(char *pathname)
504: {
505: size_t l = strlen(pathname);
506:
507: return l > 0 && pathname[l - 1] == '/';
508: }
509:
1.44 djm 510: static int
1.111 djm 511: process_get(struct sftp_conn *conn, char *src, char *dst, char *pwd,
1.148 djm 512: int pflag, int rflag, int resume)
1.44 djm 513: {
514: char *abs_src = NULL;
515: char *abs_dst = NULL;
516: glob_t g;
1.111 djm 517: char *filename, *tmp=NULL;
518: int i, err = 0;
1.44 djm 519:
520: abs_src = xstrdup(src);
521: abs_src = make_absolute(abs_src, pwd);
1.111 djm 522: memset(&g, 0, sizeof(g));
1.44 djm 523:
524: debug3("Looking up %s", abs_src);
1.111 djm 525: if (remote_glob(conn, abs_src, GLOB_MARK, NULL, &g)) {
1.44 djm 526: error("File \"%s\" not found.", abs_src);
527: err = -1;
528: goto out;
529: }
530:
1.111 djm 531: /*
532: * If multiple matches then dst must be a directory or
533: * unspecified.
534: */
535: if (g.gl_matchc > 1 && dst != NULL && !is_dir(dst)) {
536: error("Multiple source paths, but destination "
537: "\"%s\" is not a directory", dst);
1.44 djm 538: err = -1;
539: goto out;
540: }
541:
1.46 djm 542: for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
1.111 djm 543: tmp = xstrdup(g.gl_pathv[i]);
544: if ((filename = basename(tmp)) == NULL) {
545: error("basename %s: %s", tmp, strerror(errno));
1.145 djm 546: free(tmp);
1.44 djm 547: err = -1;
548: goto out;
549: }
550:
551: if (g.gl_matchc == 1 && dst) {
552: if (is_dir(dst)) {
1.111 djm 553: abs_dst = path_append(dst, filename);
554: } else {
1.44 djm 555: abs_dst = xstrdup(dst);
1.111 djm 556: }
1.44 djm 557: } else if (dst) {
1.111 djm 558: abs_dst = path_append(dst, filename);
559: } else {
560: abs_dst = xstrdup(filename);
561: }
1.145 djm 562: free(tmp);
1.44 djm 563:
1.148 djm 564: resume |= global_aflag;
565: if (!quiet && resume)
566: printf("Resuming %s to %s\n", g.gl_pathv[i], abs_dst);
567: else if (!quiet && !resume)
1.143 djm 568: printf("Fetching %s to %s\n", g.gl_pathv[i], abs_dst);
1.111 djm 569: if (pathname_is_dir(g.gl_pathv[i]) && (rflag || global_rflag)) {
1.148 djm 570: if (download_dir(conn, g.gl_pathv[i], abs_dst, NULL,
571: pflag || global_pflag, 1, resume) == -1)
1.111 djm 572: err = -1;
573: } else {
574: if (do_download(conn, g.gl_pathv[i], abs_dst, NULL,
1.148 djm 575: pflag || global_pflag, resume) == -1)
1.111 djm 576: err = -1;
577: }
1.145 djm 578: free(abs_dst);
1.44 djm 579: abs_dst = NULL;
580: }
581:
582: out:
1.145 djm 583: free(abs_src);
1.44 djm 584: globfree(&g);
585: return(err);
586: }
587:
588: static int
1.111 djm 589: process_put(struct sftp_conn *conn, char *src, char *dst, char *pwd,
590: int pflag, int rflag)
1.44 djm 591: {
592: char *tmp_dst = NULL;
593: char *abs_dst = NULL;
1.111 djm 594: char *tmp = NULL, *filename = NULL;
1.44 djm 595: glob_t g;
596: int err = 0;
1.111 djm 597: int i, dst_is_dir = 1;
1.99 djm 598: struct stat sb;
1.44 djm 599:
600: if (dst) {
601: tmp_dst = xstrdup(dst);
602: tmp_dst = make_absolute(tmp_dst, pwd);
603: }
604:
605: memset(&g, 0, sizeof(g));
606: debug3("Looking up %s", src);
1.111 djm 607: if (glob(src, GLOB_NOCHECK | GLOB_MARK, NULL, &g)) {
1.44 djm 608: error("File \"%s\" not found.", src);
609: err = -1;
610: goto out;
611: }
612:
1.111 djm 613: /* If we aren't fetching to pwd then stash this status for later */
614: if (tmp_dst != NULL)
615: dst_is_dir = remote_is_dir(conn, tmp_dst);
616:
1.44 djm 617: /* If multiple matches, dst may be directory or unspecified */
1.111 djm 618: if (g.gl_matchc > 1 && tmp_dst && !dst_is_dir) {
619: error("Multiple paths match, but destination "
620: "\"%s\" is not a directory", tmp_dst);
1.44 djm 621: err = -1;
622: goto out;
623: }
624:
1.46 djm 625: for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
1.99 djm 626: if (stat(g.gl_pathv[i], &sb) == -1) {
627: err = -1;
628: error("stat %s: %s", g.gl_pathv[i], strerror(errno));
629: continue;
630: }
1.149 djm 631:
1.111 djm 632: tmp = xstrdup(g.gl_pathv[i]);
633: if ((filename = basename(tmp)) == NULL) {
634: error("basename %s: %s", tmp, strerror(errno));
1.145 djm 635: free(tmp);
1.44 djm 636: err = -1;
637: goto out;
638: }
639:
640: if (g.gl_matchc == 1 && tmp_dst) {
641: /* If directory specified, append filename */
1.111 djm 642: if (dst_is_dir)
643: abs_dst = path_append(tmp_dst, filename);
644: else
1.44 djm 645: abs_dst = xstrdup(tmp_dst);
646: } else if (tmp_dst) {
1.111 djm 647: abs_dst = path_append(tmp_dst, filename);
648: } else {
649: abs_dst = make_absolute(xstrdup(filename), pwd);
650: }
1.145 djm 651: free(tmp);
1.44 djm 652:
1.143 djm 653: if (!quiet)
654: printf("Uploading %s to %s\n", g.gl_pathv[i], abs_dst);
1.111 djm 655: if (pathname_is_dir(g.gl_pathv[i]) && (rflag || global_rflag)) {
656: if (upload_dir(conn, g.gl_pathv[i], abs_dst,
657: pflag || global_pflag, 1) == -1)
658: err = -1;
659: } else {
660: if (do_upload(conn, g.gl_pathv[i], abs_dst,
661: pflag || global_pflag) == -1)
662: err = -1;
663: }
1.44 djm 664: }
665:
666: out:
1.145 djm 667: free(abs_dst);
668: free(tmp_dst);
1.44 djm 669: globfree(&g);
670: return(err);
671: }
672:
673: static int
674: sdirent_comp(const void *aa, const void *bb)
675: {
676: SFTP_DIRENT *a = *(SFTP_DIRENT **)aa;
677: SFTP_DIRENT *b = *(SFTP_DIRENT **)bb;
1.53 djm 678: int rmul = sort_flag & LS_REVERSE_SORT ? -1 : 1;
1.44 djm 679:
1.52 djm 680: #define NCMP(a,b) (a == b ? 0 : (a < b ? 1 : -1))
1.53 djm 681: if (sort_flag & LS_NAME_SORT)
1.52 djm 682: return (rmul * strcmp(a->filename, b->filename));
1.53 djm 683: else if (sort_flag & LS_TIME_SORT)
1.52 djm 684: return (rmul * NCMP(a->a.mtime, b->a.mtime));
1.53 djm 685: else if (sort_flag & LS_SIZE_SORT)
1.52 djm 686: return (rmul * NCMP(a->a.size, b->a.size));
687:
688: fatal("Unknown ls sort type");
1.44 djm 689: }
690:
691: /* sftp ls.1 replacement for directories */
692: static int
693: do_ls_dir(struct sftp_conn *conn, char *path, char *strip_path, int lflag)
694: {
1.64 djm 695: int n;
696: u_int c = 1, colspace = 0, columns = 1;
1.44 djm 697: SFTP_DIRENT **d;
698:
699: if ((n = do_readdir(conn, path, &d)) != 0)
700: return (n);
701:
1.53 djm 702: if (!(lflag & LS_SHORT_VIEW)) {
1.64 djm 703: u_int m = 0, width = 80;
1.44 djm 704: struct winsize ws;
705: char *tmp;
706:
707: /* Count entries for sort and find longest filename */
1.54 djm 708: for (n = 0; d[n] != NULL; n++) {
709: if (d[n]->filename[0] != '.' || (lflag & LS_SHOW_ALL))
710: m = MAX(m, strlen(d[n]->filename));
711: }
1.44 djm 712:
713: /* Add any subpath that also needs to be counted */
714: tmp = path_strip(path, strip_path);
715: m += strlen(tmp);
1.145 djm 716: free(tmp);
1.44 djm 717:
718: if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) != -1)
719: width = ws.ws_col;
720:
721: columns = width / (m + 2);
722: columns = MAX(columns, 1);
723: colspace = width / columns;
724: colspace = MIN(colspace, width);
725: }
726:
1.52 djm 727: if (lflag & SORT_FLAGS) {
1.68 dtucker 728: for (n = 0; d[n] != NULL; n++)
729: ; /* count entries */
1.53 djm 730: sort_flag = lflag & (SORT_FLAGS|LS_REVERSE_SORT);
1.52 djm 731: qsort(d, n, sizeof(*d), sdirent_comp);
732: }
1.44 djm 733:
1.46 djm 734: for (n = 0; d[n] != NULL && !interrupted; n++) {
1.44 djm 735: char *tmp, *fname;
1.54 djm 736:
737: if (d[n]->filename[0] == '.' && !(lflag & LS_SHOW_ALL))
738: continue;
1.44 djm 739:
740: tmp = path_append(path, d[n]->filename);
741: fname = path_strip(tmp, strip_path);
1.145 djm 742: free(tmp);
1.44 djm 743:
1.53 djm 744: if (lflag & LS_LONG_VIEW) {
1.119 djm 745: if (lflag & (LS_NUMERIC_VIEW|LS_SI_UNITS)) {
1.50 djm 746: char *lname;
747: struct stat sb;
748:
749: memset(&sb, 0, sizeof(sb));
750: attrib_to_stat(&d[n]->a, &sb);
1.119 djm 751: lname = ls_file(fname, &sb, 1,
752: (lflag & LS_SI_UNITS));
1.50 djm 753: printf("%s\n", lname);
1.145 djm 754: free(lname);
1.50 djm 755: } else
756: printf("%s\n", d[n]->longname);
1.44 djm 757: } else {
758: printf("%-*s", colspace, fname);
759: if (c >= columns) {
760: printf("\n");
761: c = 1;
762: } else
763: c++;
764: }
765:
1.145 djm 766: free(fname);
1.44 djm 767: }
768:
1.53 djm 769: if (!(lflag & LS_LONG_VIEW) && (c != 1))
1.44 djm 770: printf("\n");
771:
772: free_sftp_dirents(d);
773: return (0);
774: }
775:
776: /* sftp ls.1 replacement which handles path globs */
777: static int
778: do_globbed_ls(struct sftp_conn *conn, char *path, char *strip_path,
779: int lflag)
780: {
1.129 djm 781: char *fname, *lname;
1.44 djm 782: glob_t g;
1.128 djm 783: int err;
1.129 djm 784: struct winsize ws;
785: u_int i, c = 1, colspace = 0, columns = 1, m = 0, width = 80;
1.44 djm 786:
787: memset(&g, 0, sizeof(g));
788:
1.128 djm 789: if (remote_glob(conn, path,
1.133 djm 790: GLOB_MARK|GLOB_NOCHECK|GLOB_BRACE|GLOB_KEEPSTAT|GLOB_NOSORT,
791: NULL, &g) ||
1.128 djm 792: (g.gl_pathc && !g.gl_matchc)) {
1.60 fgsch 793: if (g.gl_pathc)
794: globfree(&g);
1.44 djm 795: error("Can't ls: \"%s\" not found", path);
1.128 djm 796: return -1;
1.44 djm 797: }
798:
1.46 djm 799: if (interrupted)
800: goto out;
801:
1.44 djm 802: /*
1.60 fgsch 803: * If the glob returns a single match and it is a directory,
804: * then just list its contents.
1.44 djm 805: */
1.128 djm 806: if (g.gl_matchc == 1 && g.gl_statv[0] != NULL &&
807: S_ISDIR(g.gl_statv[0]->st_mode)) {
808: err = do_ls_dir(conn, g.gl_pathv[0], strip_path, lflag);
809: globfree(&g);
810: return err;
1.44 djm 811: }
812:
1.129 djm 813: if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) != -1)
814: width = ws.ws_col;
815:
1.53 djm 816: if (!(lflag & LS_SHORT_VIEW)) {
1.44 djm 817: /* Count entries for sort and find longest filename */
818: for (i = 0; g.gl_pathv[i]; i++)
819: m = MAX(m, strlen(g.gl_pathv[i]));
820:
821: columns = width / (m + 2);
822: columns = MAX(columns, 1);
823: colspace = width / columns;
824: }
825:
1.136 dtucker 826: for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
1.44 djm 827: fname = path_strip(g.gl_pathv[i], strip_path);
1.53 djm 828: if (lflag & LS_LONG_VIEW) {
1.128 djm 829: if (g.gl_statv[i] == NULL) {
830: error("no stat information for %s", fname);
831: continue;
832: }
833: lname = ls_file(fname, g.gl_statv[i], 1,
834: (lflag & LS_SI_UNITS));
1.44 djm 835: printf("%s\n", lname);
1.145 djm 836: free(lname);
1.44 djm 837: } else {
838: printf("%-*s", colspace, fname);
839: if (c >= columns) {
840: printf("\n");
841: c = 1;
842: } else
843: c++;
844: }
1.145 djm 845: free(fname);
1.44 djm 846: }
847:
1.53 djm 848: if (!(lflag & LS_LONG_VIEW) && (c != 1))
1.44 djm 849: printf("\n");
850:
1.46 djm 851: out:
1.44 djm 852: if (g.gl_pathc)
853: globfree(&g);
854:
1.128 djm 855: return 0;
1.44 djm 856: }
857:
1.100 djm 858: static int
859: do_df(struct sftp_conn *conn, char *path, int hflag, int iflag)
860: {
1.101 dtucker 861: struct sftp_statvfs st;
1.100 djm 862: char s_used[FMT_SCALED_STRSIZE];
863: char s_avail[FMT_SCALED_STRSIZE];
864: char s_root[FMT_SCALED_STRSIZE];
865: char s_total[FMT_SCALED_STRSIZE];
1.114 dtucker 866: unsigned long long ffree;
1.100 djm 867:
868: if (do_statvfs(conn, path, &st, 1) == -1)
869: return -1;
870: if (iflag) {
1.114 dtucker 871: ffree = st.f_files ? (100 * (st.f_files - st.f_ffree) / st.f_files) : 0;
1.100 djm 872: printf(" Inodes Used Avail "
873: "(root) %%Capacity\n");
874: printf("%11llu %11llu %11llu %11llu %3llu%%\n",
875: (unsigned long long)st.f_files,
876: (unsigned long long)(st.f_files - st.f_ffree),
877: (unsigned long long)st.f_favail,
1.114 dtucker 878: (unsigned long long)st.f_ffree, ffree);
1.100 djm 879: } else if (hflag) {
880: strlcpy(s_used, "error", sizeof(s_used));
881: strlcpy(s_avail, "error", sizeof(s_avail));
882: strlcpy(s_root, "error", sizeof(s_root));
883: strlcpy(s_total, "error", sizeof(s_total));
884: fmt_scaled((st.f_blocks - st.f_bfree) * st.f_frsize, s_used);
885: fmt_scaled(st.f_bavail * st.f_frsize, s_avail);
886: fmt_scaled(st.f_bfree * st.f_frsize, s_root);
887: fmt_scaled(st.f_blocks * st.f_frsize, s_total);
888: printf(" Size Used Avail (root) %%Capacity\n");
889: printf("%7sB %7sB %7sB %7sB %3llu%%\n",
890: s_total, s_used, s_avail, s_root,
891: (unsigned long long)(100 * (st.f_blocks - st.f_bfree) /
892: st.f_blocks));
893: } else {
894: printf(" Size Used Avail "
895: "(root) %%Capacity\n");
896: printf("%12llu %12llu %12llu %12llu %3llu%%\n",
897: (unsigned long long)(st.f_frsize * st.f_blocks / 1024),
898: (unsigned long long)(st.f_frsize *
899: (st.f_blocks - st.f_bfree) / 1024),
900: (unsigned long long)(st.f_frsize * st.f_bavail / 1024),
901: (unsigned long long)(st.f_frsize * st.f_bfree / 1024),
902: (unsigned long long)(100 * (st.f_blocks - st.f_bfree) /
903: st.f_blocks));
904: }
905: return 0;
906: }
907:
1.97 djm 908: /*
909: * Undo escaping of glob sequences in place. Used to undo extra escaping
910: * applied in makeargv() when the string is destined for a function that
911: * does not glob it.
912: */
913: static void
914: undo_glob_escape(char *s)
915: {
916: size_t i, j;
917:
918: for (i = j = 0;;) {
919: if (s[i] == '\0') {
920: s[j] = '\0';
921: return;
922: }
923: if (s[i] != '\\') {
924: s[j++] = s[i++];
925: continue;
926: }
927: /* s[i] == '\\' */
928: ++i;
929: switch (s[i]) {
930: case '?':
931: case '[':
932: case '*':
933: case '\\':
934: s[j++] = s[i++];
935: break;
936: case '\0':
937: s[j++] = '\\';
938: s[j] = '\0';
939: return;
940: default:
941: s[j++] = '\\';
942: s[j++] = s[i++];
943: break;
944: }
945: }
946: }
947:
948: /*
949: * Split a string into an argument vector using sh(1)-style quoting,
950: * comment and escaping rules, but with some tweaks to handle glob(3)
951: * wildcards.
1.116 djm 952: * The "sloppy" flag allows for recovery from missing terminating quote, for
953: * use in parsing incomplete commandlines during tab autocompletion.
954: *
1.97 djm 955: * Returns NULL on error or a NULL-terminated array of arguments.
1.116 djm 956: *
957: * If "lastquote" is not NULL, the quoting character used for the last
958: * argument is placed in *lastquote ("\0", "'" or "\"").
1.149 djm 959: *
1.116 djm 960: * If "terminated" is not NULL, *terminated will be set to 1 when the
961: * last argument's quote has been properly terminated or 0 otherwise.
962: * This parameter is only of use if "sloppy" is set.
1.97 djm 963: */
964: #define MAXARGS 128
965: #define MAXARGLEN 8192
966: static char **
1.116 djm 967: makeargv(const char *arg, int *argcp, int sloppy, char *lastquote,
968: u_int *terminated)
1.97 djm 969: {
970: int argc, quot;
971: size_t i, j;
972: static char argvs[MAXARGLEN];
973: static char *argv[MAXARGS + 1];
974: enum { MA_START, MA_SQUOTE, MA_DQUOTE, MA_UNQUOTED } state, q;
975:
976: *argcp = argc = 0;
977: if (strlen(arg) > sizeof(argvs) - 1) {
978: args_too_longs:
979: error("string too long");
980: return NULL;
981: }
1.116 djm 982: if (terminated != NULL)
983: *terminated = 1;
984: if (lastquote != NULL)
985: *lastquote = '\0';
1.97 djm 986: state = MA_START;
987: i = j = 0;
988: for (;;) {
1.141 markus 989: if ((size_t)argc >= sizeof(argv) / sizeof(*argv)){
1.138 dtucker 990: error("Too many arguments.");
991: return NULL;
992: }
1.97 djm 993: if (isspace(arg[i])) {
994: if (state == MA_UNQUOTED) {
995: /* Terminate current argument */
996: argvs[j++] = '\0';
997: argc++;
998: state = MA_START;
999: } else if (state != MA_START)
1000: argvs[j++] = arg[i];
1001: } else if (arg[i] == '"' || arg[i] == '\'') {
1002: q = arg[i] == '"' ? MA_DQUOTE : MA_SQUOTE;
1003: if (state == MA_START) {
1004: argv[argc] = argvs + j;
1005: state = q;
1.116 djm 1006: if (lastquote != NULL)
1007: *lastquote = arg[i];
1.149 djm 1008: } else if (state == MA_UNQUOTED)
1.97 djm 1009: state = q;
1010: else if (state == q)
1011: state = MA_UNQUOTED;
1012: else
1013: argvs[j++] = arg[i];
1014: } else if (arg[i] == '\\') {
1015: if (state == MA_SQUOTE || state == MA_DQUOTE) {
1016: quot = state == MA_SQUOTE ? '\'' : '"';
1017: /* Unescape quote we are in */
1018: /* XXX support \n and friends? */
1019: if (arg[i + 1] == quot) {
1020: i++;
1021: argvs[j++] = arg[i];
1022: } else if (arg[i + 1] == '?' ||
1023: arg[i + 1] == '[' || arg[i + 1] == '*') {
1024: /*
1025: * Special case for sftp: append
1026: * double-escaped glob sequence -
1027: * glob will undo one level of
1028: * escaping. NB. string can grow here.
1029: */
1030: if (j >= sizeof(argvs) - 5)
1031: goto args_too_longs;
1032: argvs[j++] = '\\';
1033: argvs[j++] = arg[i++];
1034: argvs[j++] = '\\';
1035: argvs[j++] = arg[i];
1036: } else {
1037: argvs[j++] = arg[i++];
1038: argvs[j++] = arg[i];
1039: }
1040: } else {
1041: if (state == MA_START) {
1042: argv[argc] = argvs + j;
1043: state = MA_UNQUOTED;
1.116 djm 1044: if (lastquote != NULL)
1045: *lastquote = '\0';
1.97 djm 1046: }
1047: if (arg[i + 1] == '?' || arg[i + 1] == '[' ||
1048: arg[i + 1] == '*' || arg[i + 1] == '\\') {
1049: /*
1050: * Special case for sftp: append
1051: * escaped glob sequence -
1052: * glob will undo one level of
1053: * escaping.
1054: */
1055: argvs[j++] = arg[i++];
1056: argvs[j++] = arg[i];
1057: } else {
1058: /* Unescape everything */
1059: /* XXX support \n and friends? */
1060: i++;
1061: argvs[j++] = arg[i];
1062: }
1063: }
1064: } else if (arg[i] == '#') {
1065: if (state == MA_SQUOTE || state == MA_DQUOTE)
1066: argvs[j++] = arg[i];
1067: else
1068: goto string_done;
1069: } else if (arg[i] == '\0') {
1070: if (state == MA_SQUOTE || state == MA_DQUOTE) {
1.116 djm 1071: if (sloppy) {
1072: state = MA_UNQUOTED;
1073: if (terminated != NULL)
1074: *terminated = 0;
1075: goto string_done;
1076: }
1.97 djm 1077: error("Unterminated quoted argument");
1078: return NULL;
1079: }
1080: string_done:
1081: if (state == MA_UNQUOTED) {
1082: argvs[j++] = '\0';
1083: argc++;
1084: }
1085: break;
1086: } else {
1087: if (state == MA_START) {
1088: argv[argc] = argvs + j;
1089: state = MA_UNQUOTED;
1.116 djm 1090: if (lastquote != NULL)
1091: *lastquote = '\0';
1.97 djm 1092: }
1093: if ((state == MA_SQUOTE || state == MA_DQUOTE) &&
1094: (arg[i] == '?' || arg[i] == '[' || arg[i] == '*')) {
1095: /*
1096: * Special case for sftp: escape quoted
1097: * glob(3) wildcards. NB. string can grow
1098: * here.
1099: */
1100: if (j >= sizeof(argvs) - 3)
1101: goto args_too_longs;
1102: argvs[j++] = '\\';
1103: argvs[j++] = arg[i];
1104: } else
1105: argvs[j++] = arg[i];
1106: }
1107: i++;
1108: }
1109: *argcp = argc;
1110: return argv;
1111: }
1112:
1.44 djm 1113: static int
1.148 djm 1114: parse_args(const char **cpp, int *aflag, int *hflag, int *iflag, int *lflag,
1115: int *pflag, int *rflag, int *sflag, unsigned long *n_arg,
1116: char **path1, char **path2)
1.44 djm 1117: {
1118: const char *cmd, *cp = *cpp;
1.97 djm 1119: char *cp2, **argv;
1.44 djm 1120: int base = 0;
1121: long l;
1.97 djm 1122: int i, cmdnum, optidx, argc;
1.44 djm 1123:
1124: /* Skip leading whitespace */
1125: cp = cp + strspn(cp, WHITESPACE);
1126:
1127: /* Check for leading '-' (disable error processing) */
1128: *iflag = 0;
1129: if (*cp == '-') {
1130: *iflag = 1;
1131: cp++;
1.118 dtucker 1132: cp = cp + strspn(cp, WHITESPACE);
1.44 djm 1133: }
1.118 dtucker 1134:
1135: /* Ignore blank lines and lines which begin with comment '#' char */
1136: if (*cp == '\0' || *cp == '#')
1137: return (0);
1.44 djm 1138:
1.116 djm 1139: if ((argv = makeargv(cp, &argc, 0, NULL, NULL)) == NULL)
1.97 djm 1140: return -1;
1141:
1.44 djm 1142: /* Figure out which command we have */
1.97 djm 1143: for (i = 0; cmds[i].c != NULL; i++) {
1.142 djm 1144: if (argv[0] != NULL && strcasecmp(cmds[i].c, argv[0]) == 0)
1.44 djm 1145: break;
1146: }
1147: cmdnum = cmds[i].n;
1148: cmd = cmds[i].c;
1149:
1150: /* Special case */
1151: if (*cp == '!') {
1152: cp++;
1153: cmdnum = I_SHELL;
1154: } else if (cmdnum == -1) {
1155: error("Invalid command.");
1.97 djm 1156: return -1;
1.44 djm 1157: }
1158:
1159: /* Get arguments and parse flags */
1.148 djm 1160: *aflag = *lflag = *pflag = *rflag = *hflag = *n_arg = 0;
1.44 djm 1161: *path1 = *path2 = NULL;
1.97 djm 1162: optidx = 1;
1.44 djm 1163: switch (cmdnum) {
1164: case I_GET:
1.148 djm 1165: case I_REGET:
1.44 djm 1166: case I_PUT:
1.132 djm 1167: if ((optidx = parse_getput_flags(cmd, argv, argc,
1.148 djm 1168: aflag, pflag, rflag)) == -1)
1.97 djm 1169: return -1;
1.44 djm 1170: /* Get first pathname (mandatory) */
1.97 djm 1171: if (argc - optidx < 1) {
1.44 djm 1172: error("You must specify at least one path after a "
1173: "%s command.", cmd);
1.97 djm 1174: return -1;
1175: }
1176: *path1 = xstrdup(argv[optidx]);
1177: /* Get second pathname (optional) */
1178: if (argc - optidx > 1) {
1179: *path2 = xstrdup(argv[optidx + 1]);
1180: /* Destination is not globbed */
1181: undo_glob_escape(*path2);
1.44 djm 1182: }
1.148 djm 1183: if (*aflag && cmdnum == I_PUT) {
1184: /* XXX implement resume for uploads */
1185: error("Resume is not supported for uploads");
1186: return -1;
1187: }
1.44 djm 1188: break;
1.132 djm 1189: case I_LINK:
1190: if ((optidx = parse_link_flags(cmd, argv, argc, sflag)) == -1)
1191: return -1;
1192: case I_SYMLINK:
1.44 djm 1193: case I_RENAME:
1.97 djm 1194: if (argc - optidx < 2) {
1.44 djm 1195: error("You must specify two paths after a %s "
1196: "command.", cmd);
1.97 djm 1197: return -1;
1.44 djm 1198: }
1.97 djm 1199: *path1 = xstrdup(argv[optidx]);
1200: *path2 = xstrdup(argv[optidx + 1]);
1201: /* Paths are not globbed */
1202: undo_glob_escape(*path1);
1203: undo_glob_escape(*path2);
1.44 djm 1204: break;
1205: case I_RM:
1206: case I_MKDIR:
1207: case I_RMDIR:
1208: case I_CHDIR:
1209: case I_LCHDIR:
1210: case I_LMKDIR:
1211: /* Get pathname (mandatory) */
1.97 djm 1212: if (argc - optidx < 1) {
1.44 djm 1213: error("You must specify a path after a %s command.",
1214: cmd);
1.97 djm 1215: return -1;
1.44 djm 1216: }
1.97 djm 1217: *path1 = xstrdup(argv[optidx]);
1218: /* Only "rm" globs */
1219: if (cmdnum != I_RM)
1220: undo_glob_escape(*path1);
1.44 djm 1221: break;
1.100 djm 1222: case I_DF:
1223: if ((optidx = parse_df_flags(cmd, argv, argc, hflag,
1224: iflag)) == -1)
1225: return -1;
1226: /* Default to current directory if no path specified */
1227: if (argc - optidx < 1)
1228: *path1 = NULL;
1229: else {
1230: *path1 = xstrdup(argv[optidx]);
1231: undo_glob_escape(*path1);
1232: }
1233: break;
1.44 djm 1234: case I_LS:
1.97 djm 1235: if ((optidx = parse_ls_flags(argv, argc, lflag)) == -1)
1.44 djm 1236: return(-1);
1237: /* Path is optional */
1.97 djm 1238: if (argc - optidx > 0)
1239: *path1 = xstrdup(argv[optidx]);
1.44 djm 1240: break;
1241: case I_LLS:
1.98 djm 1242: /* Skip ls command and following whitespace */
1243: cp = cp + strlen(cmd) + strspn(cp, WHITESPACE);
1.44 djm 1244: case I_SHELL:
1245: /* Uses the rest of the line */
1246: break;
1247: case I_LUMASK:
1248: case I_CHMOD:
1249: base = 8;
1250: case I_CHOWN:
1251: case I_CHGRP:
1252: /* Get numeric arg (mandatory) */
1.97 djm 1253: if (argc - optidx < 1)
1254: goto need_num_arg;
1.93 ray 1255: errno = 0;
1.97 djm 1256: l = strtol(argv[optidx], &cp2, base);
1257: if (cp2 == argv[optidx] || *cp2 != '\0' ||
1258: ((l == LONG_MIN || l == LONG_MAX) && errno == ERANGE) ||
1259: l < 0) {
1260: need_num_arg:
1.44 djm 1261: error("You must supply a numeric argument "
1262: "to the %s command.", cmd);
1.97 djm 1263: return -1;
1.44 djm 1264: }
1265: *n_arg = l;
1.97 djm 1266: if (cmdnum == I_LUMASK)
1.44 djm 1267: break;
1268: /* Get pathname (mandatory) */
1.97 djm 1269: if (argc - optidx < 2) {
1.44 djm 1270: error("You must specify a path after a %s command.",
1271: cmd);
1.97 djm 1272: return -1;
1.44 djm 1273: }
1.97 djm 1274: *path1 = xstrdup(argv[optidx + 1]);
1.44 djm 1275: break;
1276: case I_QUIT:
1277: case I_PWD:
1278: case I_LPWD:
1279: case I_HELP:
1280: case I_VERSION:
1281: case I_PROGRESS:
1282: break;
1283: default:
1284: fatal("Command not implemented");
1285: }
1286:
1287: *cpp = cp;
1288: return(cmdnum);
1289: }
1290:
1291: static int
1292: parse_dispatch_command(struct sftp_conn *conn, const char *cmd, char **pwd,
1293: int err_abort)
1294: {
1295: char *path1, *path2, *tmp;
1.148 djm 1296: int aflag = 0, hflag = 0, iflag = 0, lflag = 0, pflag = 0;
1297: int rflag = 0, sflag = 0;
1.132 djm 1298: int cmdnum, i;
1.107 dtucker 1299: unsigned long n_arg = 0;
1.44 djm 1300: Attrib a, *aa;
1301: char path_buf[MAXPATHLEN];
1302: int err = 0;
1303: glob_t g;
1304:
1305: path1 = path2 = NULL;
1.148 djm 1306: cmdnum = parse_args(&cmd, &aflag, &hflag, &iflag, &lflag, &pflag,
1307: &rflag, &sflag, &n_arg, &path1, &path2);
1.44 djm 1308: if (iflag != 0)
1309: err_abort = 0;
1310:
1311: memset(&g, 0, sizeof(g));
1312:
1313: /* Perform command */
1314: switch (cmdnum) {
1315: case 0:
1316: /* Blank line */
1317: break;
1318: case -1:
1319: /* Unrecognized command */
1320: err = -1;
1321: break;
1.148 djm 1322: case I_REGET:
1323: aflag = 1;
1324: /* FALLTHROUGH */
1.44 djm 1325: case I_GET:
1.148 djm 1326: err = process_get(conn, path1, path2, *pwd, pflag,
1327: rflag, aflag);
1.44 djm 1328: break;
1329: case I_PUT:
1.111 djm 1330: err = process_put(conn, path1, path2, *pwd, pflag, rflag);
1.44 djm 1331: break;
1332: case I_RENAME:
1333: path1 = make_absolute(path1, *pwd);
1334: path2 = make_absolute(path2, *pwd);
1335: err = do_rename(conn, path1, path2);
1336: break;
1337: case I_SYMLINK:
1.132 djm 1338: sflag = 1;
1339: case I_LINK:
1.151 ! djm 1340: if (!sflag)
! 1341: path1 = make_absolute(path1, *pwd);
1.44 djm 1342: path2 = make_absolute(path2, *pwd);
1.132 djm 1343: err = (sflag ? do_symlink : do_hardlink)(conn, path1, path2);
1.44 djm 1344: break;
1345: case I_RM:
1346: path1 = make_absolute(path1, *pwd);
1347: remote_glob(conn, path1, GLOB_NOCHECK, NULL, &g);
1.46 djm 1348: for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
1.143 djm 1349: if (!quiet)
1350: printf("Removing %s\n", g.gl_pathv[i]);
1.44 djm 1351: err = do_rm(conn, g.gl_pathv[i]);
1352: if (err != 0 && err_abort)
1353: break;
1354: }
1355: break;
1356: case I_MKDIR:
1357: path1 = make_absolute(path1, *pwd);
1358: attrib_clear(&a);
1359: a.flags |= SSH2_FILEXFER_ATTR_PERMISSIONS;
1360: a.perm = 0777;
1.111 djm 1361: err = do_mkdir(conn, path1, &a, 1);
1.44 djm 1362: break;
1363: case I_RMDIR:
1364: path1 = make_absolute(path1, *pwd);
1365: err = do_rmdir(conn, path1);
1366: break;
1367: case I_CHDIR:
1368: path1 = make_absolute(path1, *pwd);
1369: if ((tmp = do_realpath(conn, path1)) == NULL) {
1370: err = 1;
1371: break;
1372: }
1373: if ((aa = do_stat(conn, tmp, 0)) == NULL) {
1.145 djm 1374: free(tmp);
1.44 djm 1375: err = 1;
1376: break;
1377: }
1378: if (!(aa->flags & SSH2_FILEXFER_ATTR_PERMISSIONS)) {
1379: error("Can't change directory: Can't check target");
1.145 djm 1380: free(tmp);
1.44 djm 1381: err = 1;
1382: break;
1383: }
1384: if (!S_ISDIR(aa->perm)) {
1385: error("Can't change directory: \"%s\" is not "
1386: "a directory", tmp);
1.145 djm 1387: free(tmp);
1.44 djm 1388: err = 1;
1389: break;
1390: }
1.145 djm 1391: free(*pwd);
1.44 djm 1392: *pwd = tmp;
1393: break;
1394: case I_LS:
1395: if (!path1) {
1.125 djm 1396: do_ls_dir(conn, *pwd, *pwd, lflag);
1.44 djm 1397: break;
1398: }
1399:
1400: /* Strip pwd off beginning of non-absolute paths */
1401: tmp = NULL;
1402: if (*path1 != '/')
1403: tmp = *pwd;
1404:
1405: path1 = make_absolute(path1, *pwd);
1406: err = do_globbed_ls(conn, path1, tmp, lflag);
1.100 djm 1407: break;
1408: case I_DF:
1409: /* Default to current directory if no path specified */
1410: if (path1 == NULL)
1411: path1 = xstrdup(*pwd);
1412: path1 = make_absolute(path1, *pwd);
1413: err = do_df(conn, path1, hflag, iflag);
1.44 djm 1414: break;
1415: case I_LCHDIR:
1416: if (chdir(path1) == -1) {
1417: error("Couldn't change local directory to "
1418: "\"%s\": %s", path1, strerror(errno));
1419: err = 1;
1420: }
1421: break;
1422: case I_LMKDIR:
1423: if (mkdir(path1, 0777) == -1) {
1424: error("Couldn't create local directory "
1425: "\"%s\": %s", path1, strerror(errno));
1426: err = 1;
1427: }
1428: break;
1429: case I_LLS:
1430: local_do_ls(cmd);
1431: break;
1432: case I_SHELL:
1433: local_do_shell(cmd);
1434: break;
1435: case I_LUMASK:
1436: umask(n_arg);
1437: printf("Local umask: %03lo\n", n_arg);
1438: break;
1439: case I_CHMOD:
1440: path1 = make_absolute(path1, *pwd);
1441: attrib_clear(&a);
1442: a.flags |= SSH2_FILEXFER_ATTR_PERMISSIONS;
1443: a.perm = n_arg;
1444: remote_glob(conn, path1, GLOB_NOCHECK, NULL, &g);
1.46 djm 1445: for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
1.143 djm 1446: if (!quiet)
1447: printf("Changing mode on %s\n", g.gl_pathv[i]);
1.44 djm 1448: err = do_setstat(conn, g.gl_pathv[i], &a);
1449: if (err != 0 && err_abort)
1450: break;
1451: }
1452: break;
1453: case I_CHOWN:
1454: case I_CHGRP:
1455: path1 = make_absolute(path1, *pwd);
1456: remote_glob(conn, path1, GLOB_NOCHECK, NULL, &g);
1.46 djm 1457: for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
1.44 djm 1458: if (!(aa = do_stat(conn, g.gl_pathv[i], 0))) {
1.104 djm 1459: if (err_abort) {
1460: err = -1;
1.44 djm 1461: break;
1.104 djm 1462: } else
1.44 djm 1463: continue;
1464: }
1465: if (!(aa->flags & SSH2_FILEXFER_ATTR_UIDGID)) {
1466: error("Can't get current ownership of "
1467: "remote file \"%s\"", g.gl_pathv[i]);
1.104 djm 1468: if (err_abort) {
1469: err = -1;
1.44 djm 1470: break;
1.104 djm 1471: } else
1.44 djm 1472: continue;
1473: }
1474: aa->flags &= SSH2_FILEXFER_ATTR_UIDGID;
1475: if (cmdnum == I_CHOWN) {
1.143 djm 1476: if (!quiet)
1477: printf("Changing owner on %s\n",
1478: g.gl_pathv[i]);
1.44 djm 1479: aa->uid = n_arg;
1480: } else {
1.143 djm 1481: if (!quiet)
1482: printf("Changing group on %s\n",
1483: g.gl_pathv[i]);
1.44 djm 1484: aa->gid = n_arg;
1485: }
1486: err = do_setstat(conn, g.gl_pathv[i], aa);
1487: if (err != 0 && err_abort)
1488: break;
1489: }
1490: break;
1491: case I_PWD:
1492: printf("Remote working directory: %s\n", *pwd);
1493: break;
1494: case I_LPWD:
1495: if (!getcwd(path_buf, sizeof(path_buf))) {
1496: error("Couldn't get local cwd: %s", strerror(errno));
1497: err = -1;
1498: break;
1499: }
1500: printf("Local working directory: %s\n", path_buf);
1501: break;
1502: case I_QUIT:
1503: /* Processed below */
1504: break;
1505: case I_HELP:
1506: help();
1507: break;
1508: case I_VERSION:
1509: printf("SFTP protocol version %u\n", sftp_proto_version(conn));
1510: break;
1511: case I_PROGRESS:
1512: showprogress = !showprogress;
1513: if (showprogress)
1514: printf("Progress meter enabled\n");
1515: else
1516: printf("Progress meter disabled\n");
1517: break;
1518: default:
1519: fatal("%d is not implemented", cmdnum);
1520: }
1521:
1522: if (g.gl_pathc)
1523: globfree(&g);
1.145 djm 1524: free(path1);
1525: free(path2);
1.44 djm 1526:
1527: /* If an unignored error occurs in batch mode we should abort. */
1528: if (err_abort && err != 0)
1529: return (-1);
1530: else if (cmdnum == I_QUIT)
1531: return (1);
1532:
1533: return (0);
1534: }
1535:
1.57 djm 1536: static char *
1537: prompt(EditLine *el)
1538: {
1539: return ("sftp> ");
1540: }
1541:
1.116 djm 1542: /* Display entries in 'list' after skipping the first 'len' chars */
1543: static void
1544: complete_display(char **list, u_int len)
1545: {
1546: u_int y, m = 0, width = 80, columns = 1, colspace = 0, llen;
1547: struct winsize ws;
1548: char *tmp;
1549:
1550: /* Count entries for sort and find longest */
1.149 djm 1551: for (y = 0; list[y]; y++)
1.116 djm 1552: m = MAX(m, strlen(list[y]));
1553:
1554: if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) != -1)
1555: width = ws.ws_col;
1556:
1557: m = m > len ? m - len : 0;
1558: columns = width / (m + 2);
1559: columns = MAX(columns, 1);
1560: colspace = width / columns;
1561: colspace = MIN(colspace, width);
1562:
1563: printf("\n");
1564: m = 1;
1565: for (y = 0; list[y]; y++) {
1566: llen = strlen(list[y]);
1567: tmp = llen > len ? list[y] + len : "";
1568: printf("%-*s", colspace, tmp);
1569: if (m >= columns) {
1570: printf("\n");
1571: m = 1;
1572: } else
1573: m++;
1574: }
1575: printf("\n");
1576: }
1577:
1578: /*
1579: * Given a "list" of words that begin with a common prefix of "word",
1580: * attempt to find an autocompletion to extends "word" by the next
1581: * characters common to all entries in "list".
1582: */
1583: static char *
1584: complete_ambiguous(const char *word, char **list, size_t count)
1585: {
1586: if (word == NULL)
1587: return NULL;
1588:
1589: if (count > 0) {
1590: u_int y, matchlen = strlen(list[0]);
1591:
1592: /* Find length of common stem */
1593: for (y = 1; list[y]; y++) {
1594: u_int x;
1595:
1.149 djm 1596: for (x = 0; x < matchlen; x++)
1597: if (list[0][x] != list[y][x])
1.116 djm 1598: break;
1599:
1600: matchlen = x;
1601: }
1602:
1603: if (matchlen > strlen(word)) {
1604: char *tmp = xstrdup(list[0]);
1605:
1.117 dtucker 1606: tmp[matchlen] = '\0';
1.116 djm 1607: return tmp;
1608: }
1.149 djm 1609: }
1.116 djm 1610:
1611: return xstrdup(word);
1612: }
1613:
1614: /* Autocomplete a sftp command */
1615: static int
1616: complete_cmd_parse(EditLine *el, char *cmd, int lastarg, char quote,
1617: int terminated)
1618: {
1619: u_int y, count = 0, cmdlen, tmplen;
1620: char *tmp, **list, argterm[3];
1621: const LineInfo *lf;
1622:
1623: list = xcalloc((sizeof(cmds) / sizeof(*cmds)) + 1, sizeof(char *));
1624:
1625: /* No command specified: display all available commands */
1626: if (cmd == NULL) {
1627: for (y = 0; cmds[y].c; y++)
1628: list[count++] = xstrdup(cmds[y].c);
1.149 djm 1629:
1.116 djm 1630: list[count] = NULL;
1631: complete_display(list, 0);
1632:
1.149 djm 1633: for (y = 0; list[y] != NULL; y++)
1634: free(list[y]);
1.145 djm 1635: free(list);
1.116 djm 1636: return count;
1637: }
1638:
1639: /* Prepare subset of commands that start with "cmd" */
1640: cmdlen = strlen(cmd);
1641: for (y = 0; cmds[y].c; y++) {
1.149 djm 1642: if (!strncasecmp(cmd, cmds[y].c, cmdlen))
1.116 djm 1643: list[count++] = xstrdup(cmds[y].c);
1644: }
1645: list[count] = NULL;
1646:
1.134 oga 1647: if (count == 0) {
1.145 djm 1648: free(list);
1.116 djm 1649: return 0;
1.134 oga 1650: }
1.116 djm 1651:
1652: /* Complete ambigious command */
1653: tmp = complete_ambiguous(cmd, list, count);
1654: if (count > 1)
1655: complete_display(list, 0);
1656:
1.149 djm 1657: for (y = 0; list[y]; y++)
1658: free(list[y]);
1.145 djm 1659: free(list);
1.116 djm 1660:
1661: if (tmp != NULL) {
1662: tmplen = strlen(tmp);
1663: cmdlen = strlen(cmd);
1664: /* If cmd may be extended then do so */
1665: if (tmplen > cmdlen)
1666: if (el_insertstr(el, tmp + cmdlen) == -1)
1667: fatal("el_insertstr failed.");
1668: lf = el_line(el);
1669: /* Terminate argument cleanly */
1670: if (count == 1) {
1671: y = 0;
1672: if (!terminated)
1673: argterm[y++] = quote;
1674: if (lastarg || *(lf->cursor) != ' ')
1675: argterm[y++] = ' ';
1676: argterm[y] = '\0';
1677: if (y > 0 && el_insertstr(el, argterm) == -1)
1678: fatal("el_insertstr failed.");
1679: }
1.145 djm 1680: free(tmp);
1.116 djm 1681: }
1682:
1683: return count;
1684: }
1685:
1686: /*
1687: * Determine whether a particular sftp command's arguments (if any)
1688: * represent local or remote files.
1689: */
1690: static int
1691: complete_is_remote(char *cmd) {
1692: int i;
1693:
1694: if (cmd == NULL)
1695: return -1;
1696:
1697: for (i = 0; cmds[i].c; i++) {
1.149 djm 1698: if (!strncasecmp(cmd, cmds[i].c, strlen(cmds[i].c)))
1.116 djm 1699: return cmds[i].t;
1700: }
1701:
1702: return -1;
1703: }
1704:
1705: /* Autocomplete a filename "file" */
1706: static int
1707: complete_match(EditLine *el, struct sftp_conn *conn, char *remote_path,
1708: char *file, int remote, int lastarg, char quote, int terminated)
1709: {
1710: glob_t g;
1.146 dtucker 1711: char *tmp, *tmp2, ins[8];
1.140 dtucker 1712: u_int i, hadglob, pwdlen, len, tmplen, filelen, cesc, isesc, isabs;
1.146 dtucker 1713: int clen;
1.116 djm 1714: const LineInfo *lf;
1.149 djm 1715:
1.116 djm 1716: /* Glob from "file" location */
1717: if (file == NULL)
1718: tmp = xstrdup("*");
1719: else
1720: xasprintf(&tmp, "%s*", file);
1721:
1.139 dtucker 1722: /* Check if the path is absolute. */
1723: isabs = tmp[0] == '/';
1724:
1.116 djm 1725: memset(&g, 0, sizeof(g));
1726: if (remote != LOCAL) {
1727: tmp = make_absolute(tmp, remote_path);
1728: remote_glob(conn, tmp, GLOB_DOOFFS|GLOB_MARK, NULL, &g);
1.149 djm 1729: } else
1.116 djm 1730: glob(tmp, GLOB_DOOFFS|GLOB_MARK, NULL, &g);
1.149 djm 1731:
1.116 djm 1732: /* Determine length of pwd so we can trim completion display */
1733: for (hadglob = tmplen = pwdlen = 0; tmp[tmplen] != 0; tmplen++) {
1734: /* Terminate counting on first unescaped glob metacharacter */
1735: if (tmp[tmplen] == '*' || tmp[tmplen] == '?') {
1736: if (tmp[tmplen] != '*' || tmp[tmplen + 1] != '\0')
1737: hadglob = 1;
1738: break;
1739: }
1740: if (tmp[tmplen] == '\\' && tmp[tmplen + 1] != '\0')
1741: tmplen++;
1742: if (tmp[tmplen] == '/')
1743: pwdlen = tmplen + 1; /* track last seen '/' */
1744: }
1.145 djm 1745: free(tmp);
1.116 djm 1746:
1.149 djm 1747: if (g.gl_matchc == 0)
1.116 djm 1748: goto out;
1749:
1750: if (g.gl_matchc > 1)
1751: complete_display(g.gl_pathv, pwdlen);
1752:
1753: tmp = NULL;
1754: /* Don't try to extend globs */
1755: if (file == NULL || hadglob)
1756: goto out;
1757:
1758: tmp2 = complete_ambiguous(file, g.gl_pathv, g.gl_matchc);
1.139 dtucker 1759: tmp = path_strip(tmp2, isabs ? NULL : remote_path);
1.145 djm 1760: free(tmp2);
1.116 djm 1761:
1762: if (tmp == NULL)
1763: goto out;
1764:
1765: tmplen = strlen(tmp);
1766: filelen = strlen(file);
1767:
1.140 dtucker 1768: /* Count the number of escaped characters in the input string. */
1769: cesc = isesc = 0;
1770: for (i = 0; i < filelen; i++) {
1771: if (!isesc && file[i] == '\\' && i + 1 < filelen){
1772: isesc = 1;
1773: cesc++;
1774: } else
1775: isesc = 0;
1776: }
1777:
1778: if (tmplen > (filelen - cesc)) {
1779: tmp2 = tmp + filelen - cesc;
1.149 djm 1780: len = strlen(tmp2);
1.116 djm 1781: /* quote argument on way out */
1.146 dtucker 1782: for (i = 0; i < len; i += clen) {
1783: if ((clen = mblen(tmp2 + i, len - i)) < 0 ||
1784: (size_t)clen > sizeof(ins) - 2)
1785: fatal("invalid multibyte character");
1.116 djm 1786: ins[0] = '\\';
1.146 dtucker 1787: memcpy(ins + 1, tmp2 + i, clen);
1788: ins[clen + 1] = '\0';
1.116 djm 1789: switch (tmp2[i]) {
1790: case '\'':
1791: case '"':
1792: case '\\':
1793: case '\t':
1.131 sthen 1794: case '[':
1.116 djm 1795: case ' ':
1.140 dtucker 1796: case '#':
1797: case '*':
1.116 djm 1798: if (quote == '\0' || tmp2[i] == quote) {
1799: if (el_insertstr(el, ins) == -1)
1800: fatal("el_insertstr "
1801: "failed.");
1802: break;
1803: }
1804: /* FALLTHROUGH */
1805: default:
1806: if (el_insertstr(el, ins + 1) == -1)
1807: fatal("el_insertstr failed.");
1808: break;
1809: }
1810: }
1811: }
1812:
1813: lf = el_line(el);
1814: if (g.gl_matchc == 1) {
1815: i = 0;
1816: if (!terminated)
1817: ins[i++] = quote;
1.120 djm 1818: if (*(lf->cursor - 1) != '/' &&
1819: (lastarg || *(lf->cursor) != ' '))
1.116 djm 1820: ins[i++] = ' ';
1821: ins[i] = '\0';
1822: if (i > 0 && el_insertstr(el, ins) == -1)
1823: fatal("el_insertstr failed.");
1824: }
1.145 djm 1825: free(tmp);
1.116 djm 1826:
1827: out:
1828: globfree(&g);
1829: return g.gl_matchc;
1830: }
1831:
1832: /* tab-completion hook function, called via libedit */
1833: static unsigned char
1834: complete(EditLine *el, int ch)
1835: {
1.149 djm 1836: char **argv, *line, quote;
1.147 djm 1837: int argc, carg;
1838: u_int cursor, len, terminated, ret = CC_ERROR;
1.116 djm 1839: const LineInfo *lf;
1840: struct complete_ctx *complete_ctx;
1841:
1842: lf = el_line(el);
1843: if (el_get(el, EL_CLIENTDATA, (void**)&complete_ctx) != 0)
1844: fatal("%s: el_get failed", __func__);
1845:
1846: /* Figure out which argument the cursor points to */
1847: cursor = lf->cursor - lf->buffer;
1848: line = (char *)xmalloc(cursor + 1);
1849: memcpy(line, lf->buffer, cursor);
1850: line[cursor] = '\0';
1851: argv = makeargv(line, &carg, 1, "e, &terminated);
1.145 djm 1852: free(line);
1.116 djm 1853:
1854: /* Get all the arguments on the line */
1855: len = lf->lastchar - lf->buffer;
1856: line = (char *)xmalloc(len + 1);
1857: memcpy(line, lf->buffer, len);
1858: line[len] = '\0';
1859: argv = makeargv(line, &argc, 1, NULL, NULL);
1860:
1861: /* Ensure cursor is at EOL or a argument boundary */
1862: if (line[cursor] != ' ' && line[cursor] != '\0' &&
1863: line[cursor] != '\n') {
1.145 djm 1864: free(line);
1.116 djm 1865: return ret;
1866: }
1867:
1868: if (carg == 0) {
1869: /* Show all available commands */
1870: complete_cmd_parse(el, NULL, argc == carg, '\0', 1);
1871: ret = CC_REDISPLAY;
1872: } else if (carg == 1 && cursor > 0 && line[cursor - 1] != ' ') {
1873: /* Handle the command parsing */
1874: if (complete_cmd_parse(el, argv[0], argc == carg,
1.149 djm 1875: quote, terminated) != 0)
1.116 djm 1876: ret = CC_REDISPLAY;
1877: } else if (carg >= 1) {
1878: /* Handle file parsing */
1879: int remote = complete_is_remote(argv[0]);
1880: char *filematch = NULL;
1881:
1882: if (carg > 1 && line[cursor-1] != ' ')
1883: filematch = argv[carg - 1];
1884:
1885: if (remote != 0 &&
1886: complete_match(el, complete_ctx->conn,
1887: *complete_ctx->remote_pathp, filematch,
1.149 djm 1888: remote, carg == argc, quote, terminated) != 0)
1.116 djm 1889: ret = CC_REDISPLAY;
1890: }
1891:
1.149 djm 1892: free(line);
1.116 djm 1893: return ret;
1894: }
1895:
1.44 djm 1896: int
1.112 djm 1897: interactive_loop(struct sftp_conn *conn, char *file1, char *file2)
1.44 djm 1898: {
1.116 djm 1899: char *remote_path;
1.44 djm 1900: char *dir = NULL;
1901: char cmd[2048];
1.66 jaredy 1902: int err, interactive;
1.57 djm 1903: EditLine *el = NULL;
1904: History *hl = NULL;
1905: HistEvent hev;
1906: extern char *__progname;
1.116 djm 1907: struct complete_ctx complete_ctx;
1.57 djm 1908:
1909: if (!batchmode && isatty(STDIN_FILENO)) {
1910: if ((el = el_init(__progname, stdin, stdout, stderr)) == NULL)
1911: fatal("Couldn't initialise editline");
1912: if ((hl = history_init()) == NULL)
1913: fatal("Couldn't initialise editline history");
1914: history(hl, &hev, H_SETSIZE, 100);
1915: el_set(el, EL_HIST, history, hl);
1916:
1917: el_set(el, EL_PROMPT, prompt);
1918: el_set(el, EL_EDITOR, "emacs");
1919: el_set(el, EL_TERMINAL, NULL);
1920: el_set(el, EL_SIGNAL, 1);
1921: el_source(el, NULL);
1.116 djm 1922:
1923: /* Tab Completion */
1.149 djm 1924: el_set(el, EL_ADDFN, "ftp-complete",
1.131 sthen 1925: "Context sensitive argument completion", complete);
1.116 djm 1926: complete_ctx.conn = conn;
1927: complete_ctx.remote_pathp = &remote_path;
1928: el_set(el, EL_CLIENTDATA, (void*)&complete_ctx);
1929: el_set(el, EL_BIND, "^I", "ftp-complete", NULL);
1.57 djm 1930: }
1.44 djm 1931:
1.116 djm 1932: remote_path = do_realpath(conn, ".");
1933: if (remote_path == NULL)
1.44 djm 1934: fatal("Need cwd");
1935:
1936: if (file1 != NULL) {
1937: dir = xstrdup(file1);
1.116 djm 1938: dir = make_absolute(dir, remote_path);
1.44 djm 1939:
1940: if (remote_is_dir(conn, dir) && file2 == NULL) {
1.143 djm 1941: if (!quiet)
1942: printf("Changing to: %s\n", dir);
1.44 djm 1943: snprintf(cmd, sizeof cmd, "cd \"%s\"", dir);
1.116 djm 1944: if (parse_dispatch_command(conn, cmd,
1945: &remote_path, 1) != 0) {
1.145 djm 1946: free(dir);
1947: free(remote_path);
1948: free(conn);
1.44 djm 1949: return (-1);
1.58 markus 1950: }
1.44 djm 1951: } else {
1.137 djm 1952: /* XXX this is wrong wrt quoting */
1.148 djm 1953: snprintf(cmd, sizeof cmd, "get%s %s%s%s",
1954: global_aflag ? " -a" : "", dir,
1955: file2 == NULL ? "" : " ",
1956: file2 == NULL ? "" : file2);
1.116 djm 1957: err = parse_dispatch_command(conn, cmd,
1958: &remote_path, 1);
1.145 djm 1959: free(dir);
1960: free(remote_path);
1961: free(conn);
1.44 djm 1962: return (err);
1963: }
1.145 djm 1964: free(dir);
1.44 djm 1965: }
1966:
1.135 djm 1967: setlinebuf(stdout);
1968: setlinebuf(infile);
1.44 djm 1969:
1.66 jaredy 1970: interactive = !batchmode && isatty(STDIN_FILENO);
1.44 djm 1971: err = 0;
1972: for (;;) {
1973: char *cp;
1.57 djm 1974: const char *line;
1975: int count = 0;
1.44 djm 1976:
1.46 djm 1977: signal(SIGINT, SIG_IGN);
1978:
1.57 djm 1979: if (el == NULL) {
1.66 jaredy 1980: if (interactive)
1981: printf("sftp> ");
1.57 djm 1982: if (fgets(cmd, sizeof(cmd), infile) == NULL) {
1.66 jaredy 1983: if (interactive)
1984: printf("\n");
1.57 djm 1985: break;
1986: }
1.66 jaredy 1987: if (!interactive) { /* Echo command */
1988: printf("sftp> %s", cmd);
1989: if (strlen(cmd) > 0 &&
1990: cmd[strlen(cmd) - 1] != '\n')
1991: printf("\n");
1992: }
1.57 djm 1993: } else {
1.116 djm 1994: if ((line = el_gets(el, &count)) == NULL ||
1995: count <= 0) {
1.66 jaredy 1996: printf("\n");
1.57 djm 1997: break;
1.66 jaredy 1998: }
1.57 djm 1999: history(hl, &hev, H_ENTER, line);
2000: if (strlcpy(cmd, line, sizeof(cmd)) >= sizeof(cmd)) {
2001: fprintf(stderr, "Error: input line too long\n");
2002: continue;
2003: }
1.44 djm 2004: }
2005:
2006: cp = strrchr(cmd, '\n');
2007: if (cp)
2008: *cp = '\0';
2009:
1.46 djm 2010: /* Handle user interrupts gracefully during commands */
2011: interrupted = 0;
2012: signal(SIGINT, cmd_interrupt);
2013:
1.116 djm 2014: err = parse_dispatch_command(conn, cmd, &remote_path,
2015: batchmode);
1.44 djm 2016: if (err != 0)
2017: break;
2018: }
1.145 djm 2019: free(remote_path);
2020: free(conn);
1.66 jaredy 2021:
2022: if (el != NULL)
2023: el_end(el);
1.44 djm 2024:
2025: /* err == 1 signifies normal "quit" exit */
2026: return (err >= 0 ? 0 : -1);
2027: }
1.34 fgsch 2028:
1.18 itojun 2029: static void
1.36 djm 2030: connect_to_server(char *path, char **args, int *in, int *out)
1.1 djm 2031: {
2032: int c_in, c_out;
1.30 deraadt 2033:
1.1 djm 2034: int inout[2];
1.30 deraadt 2035:
1.1 djm 2036: if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) == -1)
2037: fatal("socketpair: %s", strerror(errno));
2038: *in = *out = inout[0];
2039: c_in = c_out = inout[1];
2040:
1.36 djm 2041: if ((sshpid = fork()) == -1)
1.1 djm 2042: fatal("fork: %s", strerror(errno));
1.36 djm 2043: else if (sshpid == 0) {
1.1 djm 2044: if ((dup2(c_in, STDIN_FILENO) == -1) ||
2045: (dup2(c_out, STDOUT_FILENO) == -1)) {
2046: fprintf(stderr, "dup2: %s\n", strerror(errno));
1.47 djm 2047: _exit(1);
1.1 djm 2048: }
2049: close(*in);
2050: close(*out);
2051: close(c_in);
2052: close(c_out);
1.46 djm 2053:
2054: /*
2055: * The underlying ssh is in the same process group, so we must
1.56 deraadt 2056: * ignore SIGINT if we want to gracefully abort commands,
2057: * otherwise the signal will make it to the ssh process and
1.122 guenther 2058: * kill it too. Contrawise, since sftp sends SIGTERMs to the
2059: * underlying ssh, it must *not* ignore that signal.
1.46 djm 2060: */
2061: signal(SIGINT, SIG_IGN);
1.122 guenther 2062: signal(SIGTERM, SIG_DFL);
1.49 dtucker 2063: execvp(path, args);
1.23 djm 2064: fprintf(stderr, "exec: %s: %s\n", path, strerror(errno));
1.47 djm 2065: _exit(1);
1.1 djm 2066: }
2067:
1.36 djm 2068: signal(SIGTERM, killchild);
2069: signal(SIGINT, killchild);
2070: signal(SIGHUP, killchild);
1.1 djm 2071: close(c_in);
2072: close(c_out);
2073: }
2074:
1.18 itojun 2075: static void
1.1 djm 2076: usage(void)
2077: {
1.25 mpech 2078: extern char *__progname;
1.27 markus 2079:
1.19 stevesk 2080: fprintf(stderr,
1.150 jmc 2081: "usage: %s [-1246aCpqrv] [-B buffer_size] [-b batchfile] [-c cipher]\n"
1.110 jmc 2082: " [-D sftp_server_path] [-F ssh_config] "
1.127 jmc 2083: "[-i identity_file] [-l limit]\n"
1.110 jmc 2084: " [-o ssh_option] [-P port] [-R num_requests] "
2085: "[-S program]\n"
1.108 djm 2086: " [-s subsystem | sftp_server] host\n"
1.105 djm 2087: " %s [user@]host[:file ...]\n"
2088: " %s [user@]host[:dir[/]]\n"
1.108 djm 2089: " %s -b batchfile [user@]host\n",
2090: __progname, __progname, __progname, __progname);
1.1 djm 2091: exit(1);
2092: }
2093:
1.2 stevesk 2094: int
1.1 djm 2095: main(int argc, char **argv)
2096: {
1.33 djm 2097: int in, out, ch, err;
1.117 dtucker 2098: char *host = NULL, *userhost, *cp, *file2 = NULL;
1.17 mouring 2099: int debug_level = 0, sshver = 2;
2100: char *file1 = NULL, *sftp_server = NULL;
1.23 djm 2101: char *ssh_program = _PATH_SSH_PROGRAM, *sftp_direct = NULL;
1.126 djm 2102: const char *errstr;
1.17 mouring 2103: LogLevel ll = SYSLOG_LEVEL_INFO;
2104: arglist args;
1.3 djm 2105: extern int optind;
2106: extern char *optarg;
1.112 djm 2107: struct sftp_conn *conn;
2108: size_t copy_buffer_len = DEFAULT_COPY_BUFLEN;
2109: size_t num_requests = DEFAULT_NUM_REQUESTS;
1.126 djm 2110: long long limit_kbps = 0;
1.67 djm 2111:
2112: /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
2113: sanitise_stdfd();
1.146 dtucker 2114: setlocale(LC_CTYPE, "");
1.1 djm 2115:
1.70 djm 2116: memset(&args, '\0', sizeof(args));
1.17 mouring 2117: args.list = NULL;
1.80 djm 2118: addargs(&args, "%s", ssh_program);
1.17 mouring 2119: addargs(&args, "-oForwardX11 no");
2120: addargs(&args, "-oForwardAgent no");
1.69 reyk 2121: addargs(&args, "-oPermitLocalCommand no");
1.21 stevesk 2122: addargs(&args, "-oClearAllForwardings yes");
1.40 djm 2123:
1.17 mouring 2124: ll = SYSLOG_LEVEL_INFO;
1.40 djm 2125: infile = stdin;
1.3 djm 2126:
1.109 djm 2127: while ((ch = getopt(argc, argv,
1.148 djm 2128: "1246ahpqrvCc:D:i:l:o:s:S:b:B:F:P:R:")) != -1) {
1.3 djm 2129: switch (ch) {
1.108 djm 2130: /* Passed through to ssh(1) */
2131: case '4':
2132: case '6':
1.3 djm 2133: case 'C':
1.108 djm 2134: addargs(&args, "-%c", ch);
2135: break;
2136: /* Passed through to ssh(1) with argument */
2137: case 'F':
2138: case 'c':
2139: case 'i':
2140: case 'o':
1.113 halex 2141: addargs(&args, "-%c", ch);
2142: addargs(&args, "%s", optarg);
1.108 djm 2143: break;
2144: case 'q':
1.143 djm 2145: ll = SYSLOG_LEVEL_ERROR;
2146: quiet = 1;
1.108 djm 2147: showprogress = 0;
2148: addargs(&args, "-%c", ch);
1.3 djm 2149: break;
1.109 djm 2150: case 'P':
2151: addargs(&args, "-oPort %s", optarg);
2152: break;
1.3 djm 2153: case 'v':
1.17 mouring 2154: if (debug_level < 3) {
2155: addargs(&args, "-v");
2156: ll = SYSLOG_LEVEL_DEBUG1 + debug_level;
2157: }
2158: debug_level++;
1.3 djm 2159: break;
1.7 markus 2160: case '1':
1.17 mouring 2161: sshver = 1;
1.7 markus 2162: if (sftp_server == NULL)
2163: sftp_server = _PATH_SFTP_SERVER;
2164: break;
1.108 djm 2165: case '2':
2166: sshver = 2;
1.148 djm 2167: break;
2168: case 'a':
2169: global_aflag = 1;
1.7 markus 2170: break;
1.108 djm 2171: case 'B':
2172: copy_buffer_len = strtol(optarg, &cp, 10);
2173: if (copy_buffer_len == 0 || *cp != '\0')
2174: fatal("Invalid buffer size \"%s\"", optarg);
1.3 djm 2175: break;
1.10 deraadt 2176: case 'b':
1.39 djm 2177: if (batchmode)
2178: fatal("Batch file already specified.");
2179:
2180: /* Allow "-" as stdin */
1.56 deraadt 2181: if (strcmp(optarg, "-") != 0 &&
1.65 djm 2182: (infile = fopen(optarg, "r")) == NULL)
1.39 djm 2183: fatal("%s (%s).", strerror(errno), optarg);
1.34 fgsch 2184: showprogress = 0;
1.143 djm 2185: quiet = batchmode = 1;
1.62 djm 2186: addargs(&args, "-obatchmode yes");
1.10 deraadt 2187: break;
1.111 djm 2188: case 'p':
2189: global_pflag = 1;
2190: break;
1.109 djm 2191: case 'D':
1.23 djm 2192: sftp_direct = optarg;
1.111 djm 2193: break;
1.126 djm 2194: case 'l':
2195: limit_kbps = strtonum(optarg, 1, 100 * 1024 * 1024,
2196: &errstr);
2197: if (errstr != NULL)
2198: usage();
2199: limit_kbps *= 1024; /* kbps */
2200: break;
1.111 djm 2201: case 'r':
2202: global_rflag = 1;
1.24 djm 2203: break;
1.26 djm 2204: case 'R':
2205: num_requests = strtol(optarg, &cp, 10);
2206: if (num_requests == 0 || *cp != '\0')
1.27 markus 2207: fatal("Invalid number of requests \"%s\"",
1.26 djm 2208: optarg);
1.108 djm 2209: break;
2210: case 's':
2211: sftp_server = optarg;
2212: break;
2213: case 'S':
2214: ssh_program = optarg;
2215: replacearg(&args, 0, "%s", ssh_program);
1.23 djm 2216: break;
1.3 djm 2217: case 'h':
2218: default:
1.1 djm 2219: usage();
2220: }
2221: }
1.45 djm 2222:
2223: if (!isatty(STDERR_FILENO))
2224: showprogress = 0;
1.1 djm 2225:
1.29 markus 2226: log_init(argv[0], ll, SYSLOG_FACILITY_USER, 1);
2227:
1.23 djm 2228: if (sftp_direct == NULL) {
2229: if (optind == argc || argc > (optind + 2))
2230: usage();
2231:
2232: userhost = xstrdup(argv[optind]);
2233: file2 = argv[optind+1];
1.1 djm 2234:
1.32 markus 2235: if ((host = strrchr(userhost, '@')) == NULL)
1.23 djm 2236: host = userhost;
2237: else {
2238: *host++ = '\0';
2239: if (!userhost[0]) {
2240: fprintf(stderr, "Missing username\n");
2241: usage();
2242: }
1.115 guenther 2243: addargs(&args, "-l");
2244: addargs(&args, "%s", userhost);
1.41 djm 2245: }
2246:
2247: if ((cp = colon(host)) != NULL) {
2248: *cp++ = '\0';
2249: file1 = cp;
1.23 djm 2250: }
1.3 djm 2251:
1.23 djm 2252: host = cleanhostname(host);
2253: if (!*host) {
2254: fprintf(stderr, "Missing hostname\n");
1.1 djm 2255: usage();
2256: }
2257:
1.23 djm 2258: addargs(&args, "-oProtocol %d", sshver);
2259:
2260: /* no subsystem if the server-spec contains a '/' */
2261: if (sftp_server == NULL || strchr(sftp_server, '/') == NULL)
2262: addargs(&args, "-s");
2263:
1.115 guenther 2264: addargs(&args, "--");
1.23 djm 2265: addargs(&args, "%s", host);
1.27 markus 2266: addargs(&args, "%s", (sftp_server != NULL ?
1.23 djm 2267: sftp_server : "sftp"));
2268:
1.36 djm 2269: connect_to_server(ssh_program, args.list, &in, &out);
1.23 djm 2270: } else {
2271: args.list = NULL;
2272: addargs(&args, "sftp-server");
2273:
1.36 djm 2274: connect_to_server(sftp_direct, args.list, &in, &out);
1.1 djm 2275: }
1.70 djm 2276: freeargs(&args);
1.1 djm 2277:
1.126 djm 2278: conn = do_init(in, out, copy_buffer_len, num_requests, limit_kbps);
1.112 djm 2279: if (conn == NULL)
2280: fatal("Couldn't initialise connection to server");
2281:
1.143 djm 2282: if (!quiet) {
1.112 djm 2283: if (sftp_direct == NULL)
2284: fprintf(stderr, "Connected to %s.\n", host);
2285: else
2286: fprintf(stderr, "Attached to %s.\n", sftp_direct);
2287: }
2288:
2289: err = interactive_loop(conn, file1, file2);
1.1 djm 2290:
2291: close(in);
2292: close(out);
1.39 djm 2293: if (batchmode)
1.10 deraadt 2294: fclose(infile);
1.1 djm 2295:
1.28 markus 2296: while (waitpid(sshpid, NULL, 0) == -1)
2297: if (errno != EINTR)
2298: fatal("Couldn't wait for ssh process: %s",
2299: strerror(errno));
1.1 djm 2300:
1.33 djm 2301: exit(err == 0 ? 0 : 1);
1.1 djm 2302: }