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