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