Annotation of src/usr.bin/ssh/sftp.c, Revision 1.149
1.149 ! djm 1: /* $OpenBSD: sftp.c,v 1.148 2013/07/25 00:56:52 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.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:
1340: path1 = make_absolute(path1, *pwd);
1.44 djm 1341: path2 = make_absolute(path2, *pwd);
1.132 djm 1342: err = (sflag ? do_symlink : do_hardlink)(conn, path1, path2);
1.44 djm 1343: break;
1344: case I_RM:
1345: path1 = make_absolute(path1, *pwd);
1346: remote_glob(conn, path1, GLOB_NOCHECK, NULL, &g);
1.46 djm 1347: for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
1.143 djm 1348: if (!quiet)
1349: printf("Removing %s\n", g.gl_pathv[i]);
1.44 djm 1350: err = do_rm(conn, g.gl_pathv[i]);
1351: if (err != 0 && err_abort)
1352: break;
1353: }
1354: break;
1355: case I_MKDIR:
1356: path1 = make_absolute(path1, *pwd);
1357: attrib_clear(&a);
1358: a.flags |= SSH2_FILEXFER_ATTR_PERMISSIONS;
1359: a.perm = 0777;
1.111 djm 1360: err = do_mkdir(conn, path1, &a, 1);
1.44 djm 1361: break;
1362: case I_RMDIR:
1363: path1 = make_absolute(path1, *pwd);
1364: err = do_rmdir(conn, path1);
1365: break;
1366: case I_CHDIR:
1367: path1 = make_absolute(path1, *pwd);
1368: if ((tmp = do_realpath(conn, path1)) == NULL) {
1369: err = 1;
1370: break;
1371: }
1372: if ((aa = do_stat(conn, tmp, 0)) == NULL) {
1.145 djm 1373: free(tmp);
1.44 djm 1374: err = 1;
1375: break;
1376: }
1377: if (!(aa->flags & SSH2_FILEXFER_ATTR_PERMISSIONS)) {
1378: error("Can't change directory: Can't check target");
1.145 djm 1379: free(tmp);
1.44 djm 1380: err = 1;
1381: break;
1382: }
1383: if (!S_ISDIR(aa->perm)) {
1384: error("Can't change directory: \"%s\" is not "
1385: "a directory", tmp);
1.145 djm 1386: free(tmp);
1.44 djm 1387: err = 1;
1388: break;
1389: }
1.145 djm 1390: free(*pwd);
1.44 djm 1391: *pwd = tmp;
1392: break;
1393: case I_LS:
1394: if (!path1) {
1.125 djm 1395: do_ls_dir(conn, *pwd, *pwd, lflag);
1.44 djm 1396: break;
1397: }
1398:
1399: /* Strip pwd off beginning of non-absolute paths */
1400: tmp = NULL;
1401: if (*path1 != '/')
1402: tmp = *pwd;
1403:
1404: path1 = make_absolute(path1, *pwd);
1405: err = do_globbed_ls(conn, path1, tmp, lflag);
1.100 djm 1406: break;
1407: case I_DF:
1408: /* Default to current directory if no path specified */
1409: if (path1 == NULL)
1410: path1 = xstrdup(*pwd);
1411: path1 = make_absolute(path1, *pwd);
1412: err = do_df(conn, path1, hflag, iflag);
1.44 djm 1413: break;
1414: case I_LCHDIR:
1415: if (chdir(path1) == -1) {
1416: error("Couldn't change local directory to "
1417: "\"%s\": %s", path1, strerror(errno));
1418: err = 1;
1419: }
1420: break;
1421: case I_LMKDIR:
1422: if (mkdir(path1, 0777) == -1) {
1423: error("Couldn't create local directory "
1424: "\"%s\": %s", path1, strerror(errno));
1425: err = 1;
1426: }
1427: break;
1428: case I_LLS:
1429: local_do_ls(cmd);
1430: break;
1431: case I_SHELL:
1432: local_do_shell(cmd);
1433: break;
1434: case I_LUMASK:
1435: umask(n_arg);
1436: printf("Local umask: %03lo\n", n_arg);
1437: break;
1438: case I_CHMOD:
1439: path1 = make_absolute(path1, *pwd);
1440: attrib_clear(&a);
1441: a.flags |= SSH2_FILEXFER_ATTR_PERMISSIONS;
1442: a.perm = n_arg;
1443: remote_glob(conn, path1, GLOB_NOCHECK, NULL, &g);
1.46 djm 1444: for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
1.143 djm 1445: if (!quiet)
1446: printf("Changing mode on %s\n", g.gl_pathv[i]);
1.44 djm 1447: err = do_setstat(conn, g.gl_pathv[i], &a);
1448: if (err != 0 && err_abort)
1449: break;
1450: }
1451: break;
1452: case I_CHOWN:
1453: case I_CHGRP:
1454: path1 = make_absolute(path1, *pwd);
1455: remote_glob(conn, path1, GLOB_NOCHECK, NULL, &g);
1.46 djm 1456: for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
1.44 djm 1457: if (!(aa = do_stat(conn, g.gl_pathv[i], 0))) {
1.104 djm 1458: if (err_abort) {
1459: err = -1;
1.44 djm 1460: break;
1.104 djm 1461: } else
1.44 djm 1462: continue;
1463: }
1464: if (!(aa->flags & SSH2_FILEXFER_ATTR_UIDGID)) {
1465: error("Can't get current ownership of "
1466: "remote file \"%s\"", g.gl_pathv[i]);
1.104 djm 1467: if (err_abort) {
1468: err = -1;
1.44 djm 1469: break;
1.104 djm 1470: } else
1.44 djm 1471: continue;
1472: }
1473: aa->flags &= SSH2_FILEXFER_ATTR_UIDGID;
1474: if (cmdnum == I_CHOWN) {
1.143 djm 1475: if (!quiet)
1476: printf("Changing owner on %s\n",
1477: g.gl_pathv[i]);
1.44 djm 1478: aa->uid = n_arg;
1479: } else {
1.143 djm 1480: if (!quiet)
1481: printf("Changing group on %s\n",
1482: g.gl_pathv[i]);
1.44 djm 1483: aa->gid = n_arg;
1484: }
1485: err = do_setstat(conn, g.gl_pathv[i], aa);
1486: if (err != 0 && err_abort)
1487: break;
1488: }
1489: break;
1490: case I_PWD:
1491: printf("Remote working directory: %s\n", *pwd);
1492: break;
1493: case I_LPWD:
1494: if (!getcwd(path_buf, sizeof(path_buf))) {
1495: error("Couldn't get local cwd: %s", strerror(errno));
1496: err = -1;
1497: break;
1498: }
1499: printf("Local working directory: %s\n", path_buf);
1500: break;
1501: case I_QUIT:
1502: /* Processed below */
1503: break;
1504: case I_HELP:
1505: help();
1506: break;
1507: case I_VERSION:
1508: printf("SFTP protocol version %u\n", sftp_proto_version(conn));
1509: break;
1510: case I_PROGRESS:
1511: showprogress = !showprogress;
1512: if (showprogress)
1513: printf("Progress meter enabled\n");
1514: else
1515: printf("Progress meter disabled\n");
1516: break;
1517: default:
1518: fatal("%d is not implemented", cmdnum);
1519: }
1520:
1521: if (g.gl_pathc)
1522: globfree(&g);
1.145 djm 1523: free(path1);
1524: free(path2);
1.44 djm 1525:
1526: /* If an unignored error occurs in batch mode we should abort. */
1527: if (err_abort && err != 0)
1528: return (-1);
1529: else if (cmdnum == I_QUIT)
1530: return (1);
1531:
1532: return (0);
1533: }
1534:
1.57 djm 1535: static char *
1536: prompt(EditLine *el)
1537: {
1538: return ("sftp> ");
1539: }
1540:
1.116 djm 1541: /* Display entries in 'list' after skipping the first 'len' chars */
1542: static void
1543: complete_display(char **list, u_int len)
1544: {
1545: u_int y, m = 0, width = 80, columns = 1, colspace = 0, llen;
1546: struct winsize ws;
1547: char *tmp;
1548:
1549: /* Count entries for sort and find longest */
1.149 ! djm 1550: for (y = 0; list[y]; y++)
1.116 djm 1551: m = MAX(m, strlen(list[y]));
1552:
1553: if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) != -1)
1554: width = ws.ws_col;
1555:
1556: m = m > len ? m - len : 0;
1557: columns = width / (m + 2);
1558: columns = MAX(columns, 1);
1559: colspace = width / columns;
1560: colspace = MIN(colspace, width);
1561:
1562: printf("\n");
1563: m = 1;
1564: for (y = 0; list[y]; y++) {
1565: llen = strlen(list[y]);
1566: tmp = llen > len ? list[y] + len : "";
1567: printf("%-*s", colspace, tmp);
1568: if (m >= columns) {
1569: printf("\n");
1570: m = 1;
1571: } else
1572: m++;
1573: }
1574: printf("\n");
1575: }
1576:
1577: /*
1578: * Given a "list" of words that begin with a common prefix of "word",
1579: * attempt to find an autocompletion to extends "word" by the next
1580: * characters common to all entries in "list".
1581: */
1582: static char *
1583: complete_ambiguous(const char *word, char **list, size_t count)
1584: {
1585: if (word == NULL)
1586: return NULL;
1587:
1588: if (count > 0) {
1589: u_int y, matchlen = strlen(list[0]);
1590:
1591: /* Find length of common stem */
1592: for (y = 1; list[y]; y++) {
1593: u_int x;
1594:
1.149 ! djm 1595: for (x = 0; x < matchlen; x++)
! 1596: if (list[0][x] != list[y][x])
1.116 djm 1597: break;
1598:
1599: matchlen = x;
1600: }
1601:
1602: if (matchlen > strlen(word)) {
1603: char *tmp = xstrdup(list[0]);
1604:
1.117 dtucker 1605: tmp[matchlen] = '\0';
1.116 djm 1606: return tmp;
1607: }
1.149 ! djm 1608: }
1.116 djm 1609:
1610: return xstrdup(word);
1611: }
1612:
1613: /* Autocomplete a sftp command */
1614: static int
1615: complete_cmd_parse(EditLine *el, char *cmd, int lastarg, char quote,
1616: int terminated)
1617: {
1618: u_int y, count = 0, cmdlen, tmplen;
1619: char *tmp, **list, argterm[3];
1620: const LineInfo *lf;
1621:
1622: list = xcalloc((sizeof(cmds) / sizeof(*cmds)) + 1, sizeof(char *));
1623:
1624: /* No command specified: display all available commands */
1625: if (cmd == NULL) {
1626: for (y = 0; cmds[y].c; y++)
1627: list[count++] = xstrdup(cmds[y].c);
1.149 ! djm 1628:
1.116 djm 1629: list[count] = NULL;
1630: complete_display(list, 0);
1631:
1.149 ! djm 1632: for (y = 0; list[y] != NULL; y++)
! 1633: free(list[y]);
1.145 djm 1634: free(list);
1.116 djm 1635: return count;
1636: }
1637:
1638: /* Prepare subset of commands that start with "cmd" */
1639: cmdlen = strlen(cmd);
1640: for (y = 0; cmds[y].c; y++) {
1.149 ! djm 1641: if (!strncasecmp(cmd, cmds[y].c, cmdlen))
1.116 djm 1642: list[count++] = xstrdup(cmds[y].c);
1643: }
1644: list[count] = NULL;
1645:
1.134 oga 1646: if (count == 0) {
1.145 djm 1647: free(list);
1.116 djm 1648: return 0;
1.134 oga 1649: }
1.116 djm 1650:
1651: /* Complete ambigious command */
1652: tmp = complete_ambiguous(cmd, list, count);
1653: if (count > 1)
1654: complete_display(list, 0);
1655:
1.149 ! djm 1656: for (y = 0; list[y]; y++)
! 1657: free(list[y]);
1.145 djm 1658: free(list);
1.116 djm 1659:
1660: if (tmp != NULL) {
1661: tmplen = strlen(tmp);
1662: cmdlen = strlen(cmd);
1663: /* If cmd may be extended then do so */
1664: if (tmplen > cmdlen)
1665: if (el_insertstr(el, tmp + cmdlen) == -1)
1666: fatal("el_insertstr failed.");
1667: lf = el_line(el);
1668: /* Terminate argument cleanly */
1669: if (count == 1) {
1670: y = 0;
1671: if (!terminated)
1672: argterm[y++] = quote;
1673: if (lastarg || *(lf->cursor) != ' ')
1674: argterm[y++] = ' ';
1675: argterm[y] = '\0';
1676: if (y > 0 && el_insertstr(el, argterm) == -1)
1677: fatal("el_insertstr failed.");
1678: }
1.145 djm 1679: free(tmp);
1.116 djm 1680: }
1681:
1682: return count;
1683: }
1684:
1685: /*
1686: * Determine whether a particular sftp command's arguments (if any)
1687: * represent local or remote files.
1688: */
1689: static int
1690: complete_is_remote(char *cmd) {
1691: int i;
1692:
1693: if (cmd == NULL)
1694: return -1;
1695:
1696: for (i = 0; cmds[i].c; i++) {
1.149 ! djm 1697: if (!strncasecmp(cmd, cmds[i].c, strlen(cmds[i].c)))
1.116 djm 1698: return cmds[i].t;
1699: }
1700:
1701: return -1;
1702: }
1703:
1704: /* Autocomplete a filename "file" */
1705: static int
1706: complete_match(EditLine *el, struct sftp_conn *conn, char *remote_path,
1707: char *file, int remote, int lastarg, char quote, int terminated)
1708: {
1709: glob_t g;
1.146 dtucker 1710: char *tmp, *tmp2, ins[8];
1.140 dtucker 1711: u_int i, hadglob, pwdlen, len, tmplen, filelen, cesc, isesc, isabs;
1.146 dtucker 1712: int clen;
1.116 djm 1713: const LineInfo *lf;
1.149 ! djm 1714:
1.116 djm 1715: /* Glob from "file" location */
1716: if (file == NULL)
1717: tmp = xstrdup("*");
1718: else
1719: xasprintf(&tmp, "%s*", file);
1720:
1.139 dtucker 1721: /* Check if the path is absolute. */
1722: isabs = tmp[0] == '/';
1723:
1.116 djm 1724: memset(&g, 0, sizeof(g));
1725: if (remote != LOCAL) {
1726: tmp = make_absolute(tmp, remote_path);
1727: remote_glob(conn, tmp, GLOB_DOOFFS|GLOB_MARK, NULL, &g);
1.149 ! djm 1728: } else
1.116 djm 1729: glob(tmp, GLOB_DOOFFS|GLOB_MARK, NULL, &g);
1.149 ! djm 1730:
1.116 djm 1731: /* Determine length of pwd so we can trim completion display */
1732: for (hadglob = tmplen = pwdlen = 0; tmp[tmplen] != 0; tmplen++) {
1733: /* Terminate counting on first unescaped glob metacharacter */
1734: if (tmp[tmplen] == '*' || tmp[tmplen] == '?') {
1735: if (tmp[tmplen] != '*' || tmp[tmplen + 1] != '\0')
1736: hadglob = 1;
1737: break;
1738: }
1739: if (tmp[tmplen] == '\\' && tmp[tmplen + 1] != '\0')
1740: tmplen++;
1741: if (tmp[tmplen] == '/')
1742: pwdlen = tmplen + 1; /* track last seen '/' */
1743: }
1.145 djm 1744: free(tmp);
1.116 djm 1745:
1.149 ! djm 1746: if (g.gl_matchc == 0)
1.116 djm 1747: goto out;
1748:
1749: if (g.gl_matchc > 1)
1750: complete_display(g.gl_pathv, pwdlen);
1751:
1752: tmp = NULL;
1753: /* Don't try to extend globs */
1754: if (file == NULL || hadglob)
1755: goto out;
1756:
1757: tmp2 = complete_ambiguous(file, g.gl_pathv, g.gl_matchc);
1.139 dtucker 1758: tmp = path_strip(tmp2, isabs ? NULL : remote_path);
1.145 djm 1759: free(tmp2);
1.116 djm 1760:
1761: if (tmp == NULL)
1762: goto out;
1763:
1764: tmplen = strlen(tmp);
1765: filelen = strlen(file);
1766:
1.140 dtucker 1767: /* Count the number of escaped characters in the input string. */
1768: cesc = isesc = 0;
1769: for (i = 0; i < filelen; i++) {
1770: if (!isesc && file[i] == '\\' && i + 1 < filelen){
1771: isesc = 1;
1772: cesc++;
1773: } else
1774: isesc = 0;
1775: }
1776:
1777: if (tmplen > (filelen - cesc)) {
1778: tmp2 = tmp + filelen - cesc;
1.149 ! djm 1779: len = strlen(tmp2);
1.116 djm 1780: /* quote argument on way out */
1.146 dtucker 1781: for (i = 0; i < len; i += clen) {
1782: if ((clen = mblen(tmp2 + i, len - i)) < 0 ||
1783: (size_t)clen > sizeof(ins) - 2)
1784: fatal("invalid multibyte character");
1.116 djm 1785: ins[0] = '\\';
1.146 dtucker 1786: memcpy(ins + 1, tmp2 + i, clen);
1787: ins[clen + 1] = '\0';
1.116 djm 1788: switch (tmp2[i]) {
1789: case '\'':
1790: case '"':
1791: case '\\':
1792: case '\t':
1.131 sthen 1793: case '[':
1.116 djm 1794: case ' ':
1.140 dtucker 1795: case '#':
1796: case '*':
1.116 djm 1797: if (quote == '\0' || tmp2[i] == quote) {
1798: if (el_insertstr(el, ins) == -1)
1799: fatal("el_insertstr "
1800: "failed.");
1801: break;
1802: }
1803: /* FALLTHROUGH */
1804: default:
1805: if (el_insertstr(el, ins + 1) == -1)
1806: fatal("el_insertstr failed.");
1807: break;
1808: }
1809: }
1810: }
1811:
1812: lf = el_line(el);
1813: if (g.gl_matchc == 1) {
1814: i = 0;
1815: if (!terminated)
1816: ins[i++] = quote;
1.120 djm 1817: if (*(lf->cursor - 1) != '/' &&
1818: (lastarg || *(lf->cursor) != ' '))
1.116 djm 1819: ins[i++] = ' ';
1820: ins[i] = '\0';
1821: if (i > 0 && el_insertstr(el, ins) == -1)
1822: fatal("el_insertstr failed.");
1823: }
1.145 djm 1824: free(tmp);
1.116 djm 1825:
1826: out:
1827: globfree(&g);
1828: return g.gl_matchc;
1829: }
1830:
1831: /* tab-completion hook function, called via libedit */
1832: static unsigned char
1833: complete(EditLine *el, int ch)
1834: {
1.149 ! djm 1835: char **argv, *line, quote;
1.147 djm 1836: int argc, carg;
1837: u_int cursor, len, terminated, ret = CC_ERROR;
1.116 djm 1838: const LineInfo *lf;
1839: struct complete_ctx *complete_ctx;
1840:
1841: lf = el_line(el);
1842: if (el_get(el, EL_CLIENTDATA, (void**)&complete_ctx) != 0)
1843: fatal("%s: el_get failed", __func__);
1844:
1845: /* Figure out which argument the cursor points to */
1846: cursor = lf->cursor - lf->buffer;
1847: line = (char *)xmalloc(cursor + 1);
1848: memcpy(line, lf->buffer, cursor);
1849: line[cursor] = '\0';
1850: argv = makeargv(line, &carg, 1, "e, &terminated);
1.145 djm 1851: free(line);
1.116 djm 1852:
1853: /* Get all the arguments on the line */
1854: len = lf->lastchar - lf->buffer;
1855: line = (char *)xmalloc(len + 1);
1856: memcpy(line, lf->buffer, len);
1857: line[len] = '\0';
1858: argv = makeargv(line, &argc, 1, NULL, NULL);
1859:
1860: /* Ensure cursor is at EOL or a argument boundary */
1861: if (line[cursor] != ' ' && line[cursor] != '\0' &&
1862: line[cursor] != '\n') {
1.145 djm 1863: free(line);
1.116 djm 1864: return ret;
1865: }
1866:
1867: if (carg == 0) {
1868: /* Show all available commands */
1869: complete_cmd_parse(el, NULL, argc == carg, '\0', 1);
1870: ret = CC_REDISPLAY;
1871: } else if (carg == 1 && cursor > 0 && line[cursor - 1] != ' ') {
1872: /* Handle the command parsing */
1873: if (complete_cmd_parse(el, argv[0], argc == carg,
1.149 ! djm 1874: quote, terminated) != 0)
1.116 djm 1875: ret = CC_REDISPLAY;
1876: } else if (carg >= 1) {
1877: /* Handle file parsing */
1878: int remote = complete_is_remote(argv[0]);
1879: char *filematch = NULL;
1880:
1881: if (carg > 1 && line[cursor-1] != ' ')
1882: filematch = argv[carg - 1];
1883:
1884: if (remote != 0 &&
1885: complete_match(el, complete_ctx->conn,
1886: *complete_ctx->remote_pathp, filematch,
1.149 ! djm 1887: remote, carg == argc, quote, terminated) != 0)
1.116 djm 1888: ret = CC_REDISPLAY;
1889: }
1890:
1.149 ! djm 1891: free(line);
1.116 djm 1892: return ret;
1893: }
1894:
1.44 djm 1895: int
1.112 djm 1896: interactive_loop(struct sftp_conn *conn, char *file1, char *file2)
1.44 djm 1897: {
1.116 djm 1898: char *remote_path;
1.44 djm 1899: char *dir = NULL;
1900: char cmd[2048];
1.66 jaredy 1901: int err, interactive;
1.57 djm 1902: EditLine *el = NULL;
1903: History *hl = NULL;
1904: HistEvent hev;
1905: extern char *__progname;
1.116 djm 1906: struct complete_ctx complete_ctx;
1.57 djm 1907:
1908: if (!batchmode && isatty(STDIN_FILENO)) {
1909: if ((el = el_init(__progname, stdin, stdout, stderr)) == NULL)
1910: fatal("Couldn't initialise editline");
1911: if ((hl = history_init()) == NULL)
1912: fatal("Couldn't initialise editline history");
1913: history(hl, &hev, H_SETSIZE, 100);
1914: el_set(el, EL_HIST, history, hl);
1915:
1916: el_set(el, EL_PROMPT, prompt);
1917: el_set(el, EL_EDITOR, "emacs");
1918: el_set(el, EL_TERMINAL, NULL);
1919: el_set(el, EL_SIGNAL, 1);
1920: el_source(el, NULL);
1.116 djm 1921:
1922: /* Tab Completion */
1.149 ! djm 1923: el_set(el, EL_ADDFN, "ftp-complete",
1.131 sthen 1924: "Context sensitive argument completion", complete);
1.116 djm 1925: complete_ctx.conn = conn;
1926: complete_ctx.remote_pathp = &remote_path;
1927: el_set(el, EL_CLIENTDATA, (void*)&complete_ctx);
1928: el_set(el, EL_BIND, "^I", "ftp-complete", NULL);
1.57 djm 1929: }
1.44 djm 1930:
1.116 djm 1931: remote_path = do_realpath(conn, ".");
1932: if (remote_path == NULL)
1.44 djm 1933: fatal("Need cwd");
1934:
1935: if (file1 != NULL) {
1936: dir = xstrdup(file1);
1.116 djm 1937: dir = make_absolute(dir, remote_path);
1.44 djm 1938:
1939: if (remote_is_dir(conn, dir) && file2 == NULL) {
1.143 djm 1940: if (!quiet)
1941: printf("Changing to: %s\n", dir);
1.44 djm 1942: snprintf(cmd, sizeof cmd, "cd \"%s\"", dir);
1.116 djm 1943: if (parse_dispatch_command(conn, cmd,
1944: &remote_path, 1) != 0) {
1.145 djm 1945: free(dir);
1946: free(remote_path);
1947: free(conn);
1.44 djm 1948: return (-1);
1.58 markus 1949: }
1.44 djm 1950: } else {
1.137 djm 1951: /* XXX this is wrong wrt quoting */
1.148 djm 1952: snprintf(cmd, sizeof cmd, "get%s %s%s%s",
1953: global_aflag ? " -a" : "", dir,
1954: file2 == NULL ? "" : " ",
1955: file2 == NULL ? "" : file2);
1.116 djm 1956: err = parse_dispatch_command(conn, cmd,
1957: &remote_path, 1);
1.145 djm 1958: free(dir);
1959: free(remote_path);
1960: free(conn);
1.44 djm 1961: return (err);
1962: }
1.145 djm 1963: free(dir);
1.44 djm 1964: }
1965:
1.135 djm 1966: setlinebuf(stdout);
1967: setlinebuf(infile);
1.44 djm 1968:
1.66 jaredy 1969: interactive = !batchmode && isatty(STDIN_FILENO);
1.44 djm 1970: err = 0;
1971: for (;;) {
1972: char *cp;
1.57 djm 1973: const char *line;
1974: int count = 0;
1.44 djm 1975:
1.46 djm 1976: signal(SIGINT, SIG_IGN);
1977:
1.57 djm 1978: if (el == NULL) {
1.66 jaredy 1979: if (interactive)
1980: printf("sftp> ");
1.57 djm 1981: if (fgets(cmd, sizeof(cmd), infile) == NULL) {
1.66 jaredy 1982: if (interactive)
1983: printf("\n");
1.57 djm 1984: break;
1985: }
1.66 jaredy 1986: if (!interactive) { /* Echo command */
1987: printf("sftp> %s", cmd);
1988: if (strlen(cmd) > 0 &&
1989: cmd[strlen(cmd) - 1] != '\n')
1990: printf("\n");
1991: }
1.57 djm 1992: } else {
1.116 djm 1993: if ((line = el_gets(el, &count)) == NULL ||
1994: count <= 0) {
1.66 jaredy 1995: printf("\n");
1.57 djm 1996: break;
1.66 jaredy 1997: }
1.57 djm 1998: history(hl, &hev, H_ENTER, line);
1999: if (strlcpy(cmd, line, sizeof(cmd)) >= sizeof(cmd)) {
2000: fprintf(stderr, "Error: input line too long\n");
2001: continue;
2002: }
1.44 djm 2003: }
2004:
2005: cp = strrchr(cmd, '\n');
2006: if (cp)
2007: *cp = '\0';
2008:
1.46 djm 2009: /* Handle user interrupts gracefully during commands */
2010: interrupted = 0;
2011: signal(SIGINT, cmd_interrupt);
2012:
1.116 djm 2013: err = parse_dispatch_command(conn, cmd, &remote_path,
2014: batchmode);
1.44 djm 2015: if (err != 0)
2016: break;
2017: }
1.145 djm 2018: free(remote_path);
2019: free(conn);
1.66 jaredy 2020:
2021: if (el != NULL)
2022: el_end(el);
1.44 djm 2023:
2024: /* err == 1 signifies normal "quit" exit */
2025: return (err >= 0 ? 0 : -1);
2026: }
1.34 fgsch 2027:
1.18 itojun 2028: static void
1.36 djm 2029: connect_to_server(char *path, char **args, int *in, int *out)
1.1 djm 2030: {
2031: int c_in, c_out;
1.30 deraadt 2032:
1.1 djm 2033: int inout[2];
1.30 deraadt 2034:
1.1 djm 2035: if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) == -1)
2036: fatal("socketpair: %s", strerror(errno));
2037: *in = *out = inout[0];
2038: c_in = c_out = inout[1];
2039:
1.36 djm 2040: if ((sshpid = fork()) == -1)
1.1 djm 2041: fatal("fork: %s", strerror(errno));
1.36 djm 2042: else if (sshpid == 0) {
1.1 djm 2043: if ((dup2(c_in, STDIN_FILENO) == -1) ||
2044: (dup2(c_out, STDOUT_FILENO) == -1)) {
2045: fprintf(stderr, "dup2: %s\n", strerror(errno));
1.47 djm 2046: _exit(1);
1.1 djm 2047: }
2048: close(*in);
2049: close(*out);
2050: close(c_in);
2051: close(c_out);
1.46 djm 2052:
2053: /*
2054: * The underlying ssh is in the same process group, so we must
1.56 deraadt 2055: * ignore SIGINT if we want to gracefully abort commands,
2056: * otherwise the signal will make it to the ssh process and
1.122 guenther 2057: * kill it too. Contrawise, since sftp sends SIGTERMs to the
2058: * underlying ssh, it must *not* ignore that signal.
1.46 djm 2059: */
2060: signal(SIGINT, SIG_IGN);
1.122 guenther 2061: signal(SIGTERM, SIG_DFL);
1.49 dtucker 2062: execvp(path, args);
1.23 djm 2063: fprintf(stderr, "exec: %s: %s\n", path, strerror(errno));
1.47 djm 2064: _exit(1);
1.1 djm 2065: }
2066:
1.36 djm 2067: signal(SIGTERM, killchild);
2068: signal(SIGINT, killchild);
2069: signal(SIGHUP, killchild);
1.1 djm 2070: close(c_in);
2071: close(c_out);
2072: }
2073:
1.18 itojun 2074: static void
1.1 djm 2075: usage(void)
2076: {
1.25 mpech 2077: extern char *__progname;
1.27 markus 2078:
1.19 stevesk 2079: fprintf(stderr,
1.149 ! djm 2080: "usage: %s [-1246Capqrv] [-B buffer_size] [-b batchfile] [-c cipher]\n"
1.110 jmc 2081: " [-D sftp_server_path] [-F ssh_config] "
1.127 jmc 2082: "[-i identity_file] [-l limit]\n"
1.110 jmc 2083: " [-o ssh_option] [-P port] [-R num_requests] "
2084: "[-S program]\n"
1.108 djm 2085: " [-s subsystem | sftp_server] host\n"
1.105 djm 2086: " %s [user@]host[:file ...]\n"
2087: " %s [user@]host[:dir[/]]\n"
1.108 djm 2088: " %s -b batchfile [user@]host\n",
2089: __progname, __progname, __progname, __progname);
1.1 djm 2090: exit(1);
2091: }
2092:
1.2 stevesk 2093: int
1.1 djm 2094: main(int argc, char **argv)
2095: {
1.33 djm 2096: int in, out, ch, err;
1.117 dtucker 2097: char *host = NULL, *userhost, *cp, *file2 = NULL;
1.17 mouring 2098: int debug_level = 0, sshver = 2;
2099: char *file1 = NULL, *sftp_server = NULL;
1.23 djm 2100: char *ssh_program = _PATH_SSH_PROGRAM, *sftp_direct = NULL;
1.126 djm 2101: const char *errstr;
1.17 mouring 2102: LogLevel ll = SYSLOG_LEVEL_INFO;
2103: arglist args;
1.3 djm 2104: extern int optind;
2105: extern char *optarg;
1.112 djm 2106: struct sftp_conn *conn;
2107: size_t copy_buffer_len = DEFAULT_COPY_BUFLEN;
2108: size_t num_requests = DEFAULT_NUM_REQUESTS;
1.126 djm 2109: long long limit_kbps = 0;
1.67 djm 2110:
2111: /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
2112: sanitise_stdfd();
1.146 dtucker 2113: setlocale(LC_CTYPE, "");
1.1 djm 2114:
1.70 djm 2115: memset(&args, '\0', sizeof(args));
1.17 mouring 2116: args.list = NULL;
1.80 djm 2117: addargs(&args, "%s", ssh_program);
1.17 mouring 2118: addargs(&args, "-oForwardX11 no");
2119: addargs(&args, "-oForwardAgent no");
1.69 reyk 2120: addargs(&args, "-oPermitLocalCommand no");
1.21 stevesk 2121: addargs(&args, "-oClearAllForwardings yes");
1.40 djm 2122:
1.17 mouring 2123: ll = SYSLOG_LEVEL_INFO;
1.40 djm 2124: infile = stdin;
1.3 djm 2125:
1.109 djm 2126: while ((ch = getopt(argc, argv,
1.148 djm 2127: "1246ahpqrvCc:D:i:l:o:s:S:b:B:F:P:R:")) != -1) {
1.3 djm 2128: switch (ch) {
1.108 djm 2129: /* Passed through to ssh(1) */
2130: case '4':
2131: case '6':
1.3 djm 2132: case 'C':
1.108 djm 2133: addargs(&args, "-%c", ch);
2134: break;
2135: /* Passed through to ssh(1) with argument */
2136: case 'F':
2137: case 'c':
2138: case 'i':
2139: case 'o':
1.113 halex 2140: addargs(&args, "-%c", ch);
2141: addargs(&args, "%s", optarg);
1.108 djm 2142: break;
2143: case 'q':
1.143 djm 2144: ll = SYSLOG_LEVEL_ERROR;
2145: quiet = 1;
1.108 djm 2146: showprogress = 0;
2147: addargs(&args, "-%c", ch);
1.3 djm 2148: break;
1.109 djm 2149: case 'P':
2150: addargs(&args, "-oPort %s", optarg);
2151: break;
1.3 djm 2152: case 'v':
1.17 mouring 2153: if (debug_level < 3) {
2154: addargs(&args, "-v");
2155: ll = SYSLOG_LEVEL_DEBUG1 + debug_level;
2156: }
2157: debug_level++;
1.3 djm 2158: break;
1.7 markus 2159: case '1':
1.17 mouring 2160: sshver = 1;
1.7 markus 2161: if (sftp_server == NULL)
2162: sftp_server = _PATH_SFTP_SERVER;
2163: break;
1.108 djm 2164: case '2':
2165: sshver = 2;
1.148 djm 2166: break;
2167: case 'a':
2168: global_aflag = 1;
1.7 markus 2169: break;
1.108 djm 2170: case 'B':
2171: copy_buffer_len = strtol(optarg, &cp, 10);
2172: if (copy_buffer_len == 0 || *cp != '\0')
2173: fatal("Invalid buffer size \"%s\"", optarg);
1.3 djm 2174: break;
1.10 deraadt 2175: case 'b':
1.39 djm 2176: if (batchmode)
2177: fatal("Batch file already specified.");
2178:
2179: /* Allow "-" as stdin */
1.56 deraadt 2180: if (strcmp(optarg, "-") != 0 &&
1.65 djm 2181: (infile = fopen(optarg, "r")) == NULL)
1.39 djm 2182: fatal("%s (%s).", strerror(errno), optarg);
1.34 fgsch 2183: showprogress = 0;
1.143 djm 2184: quiet = batchmode = 1;
1.62 djm 2185: addargs(&args, "-obatchmode yes");
1.10 deraadt 2186: break;
1.111 djm 2187: case 'p':
2188: global_pflag = 1;
2189: break;
1.109 djm 2190: case 'D':
1.23 djm 2191: sftp_direct = optarg;
1.111 djm 2192: break;
1.126 djm 2193: case 'l':
2194: limit_kbps = strtonum(optarg, 1, 100 * 1024 * 1024,
2195: &errstr);
2196: if (errstr != NULL)
2197: usage();
2198: limit_kbps *= 1024; /* kbps */
2199: break;
1.111 djm 2200: case 'r':
2201: global_rflag = 1;
1.24 djm 2202: break;
1.26 djm 2203: case 'R':
2204: num_requests = strtol(optarg, &cp, 10);
2205: if (num_requests == 0 || *cp != '\0')
1.27 markus 2206: fatal("Invalid number of requests \"%s\"",
1.26 djm 2207: optarg);
1.108 djm 2208: break;
2209: case 's':
2210: sftp_server = optarg;
2211: break;
2212: case 'S':
2213: ssh_program = optarg;
2214: replacearg(&args, 0, "%s", ssh_program);
1.23 djm 2215: break;
1.3 djm 2216: case 'h':
2217: default:
1.1 djm 2218: usage();
2219: }
2220: }
1.45 djm 2221:
2222: if (!isatty(STDERR_FILENO))
2223: showprogress = 0;
1.1 djm 2224:
1.29 markus 2225: log_init(argv[0], ll, SYSLOG_FACILITY_USER, 1);
2226:
1.23 djm 2227: if (sftp_direct == NULL) {
2228: if (optind == argc || argc > (optind + 2))
2229: usage();
2230:
2231: userhost = xstrdup(argv[optind]);
2232: file2 = argv[optind+1];
1.1 djm 2233:
1.32 markus 2234: if ((host = strrchr(userhost, '@')) == NULL)
1.23 djm 2235: host = userhost;
2236: else {
2237: *host++ = '\0';
2238: if (!userhost[0]) {
2239: fprintf(stderr, "Missing username\n");
2240: usage();
2241: }
1.115 guenther 2242: addargs(&args, "-l");
2243: addargs(&args, "%s", userhost);
1.41 djm 2244: }
2245:
2246: if ((cp = colon(host)) != NULL) {
2247: *cp++ = '\0';
2248: file1 = cp;
1.23 djm 2249: }
1.3 djm 2250:
1.23 djm 2251: host = cleanhostname(host);
2252: if (!*host) {
2253: fprintf(stderr, "Missing hostname\n");
1.1 djm 2254: usage();
2255: }
2256:
1.23 djm 2257: addargs(&args, "-oProtocol %d", sshver);
2258:
2259: /* no subsystem if the server-spec contains a '/' */
2260: if (sftp_server == NULL || strchr(sftp_server, '/') == NULL)
2261: addargs(&args, "-s");
2262:
1.115 guenther 2263: addargs(&args, "--");
1.23 djm 2264: addargs(&args, "%s", host);
1.27 markus 2265: addargs(&args, "%s", (sftp_server != NULL ?
1.23 djm 2266: sftp_server : "sftp"));
2267:
1.36 djm 2268: connect_to_server(ssh_program, args.list, &in, &out);
1.23 djm 2269: } else {
2270: args.list = NULL;
2271: addargs(&args, "sftp-server");
2272:
1.36 djm 2273: connect_to_server(sftp_direct, args.list, &in, &out);
1.1 djm 2274: }
1.70 djm 2275: freeargs(&args);
1.1 djm 2276:
1.126 djm 2277: conn = do_init(in, out, copy_buffer_len, num_requests, limit_kbps);
1.112 djm 2278: if (conn == NULL)
2279: fatal("Couldn't initialise connection to server");
2280:
1.143 djm 2281: if (!quiet) {
1.112 djm 2282: if (sftp_direct == NULL)
2283: fprintf(stderr, "Connected to %s.\n", host);
2284: else
2285: fprintf(stderr, "Attached to %s.\n", sftp_direct);
2286: }
2287:
2288: err = interactive_loop(conn, file1, file2);
1.1 djm 2289:
2290: close(in);
2291: close(out);
1.39 djm 2292: if (batchmode)
1.10 deraadt 2293: fclose(infile);
1.1 djm 2294:
1.28 markus 2295: while (waitpid(sshpid, NULL, 0) == -1)
2296: if (errno != EINTR)
2297: fatal("Couldn't wait for ssh process: %s",
2298: strerror(errno));
1.1 djm 2299:
1.33 djm 2300: exit(err == 0 ? 0 : 1);
1.1 djm 2301: }