Annotation of src/usr.bin/ssh/sftp.c, Revision 1.227
1.227 ! guenther 1: /* $OpenBSD: sftp.c,v 1.226 2023/02/27 22:12:40 dtucker 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.215 djm 1972: tmp = make_absolute_pwd_glob(tmp, remote_path);
1.116 djm 1973: remote_glob(conn, tmp, GLOB_DOOFFS|GLOB_MARK, NULL, &g);
1.149 djm 1974: } else
1.116 djm 1975: glob(tmp, GLOB_DOOFFS|GLOB_MARK, NULL, &g);
1.149 djm 1976:
1.116 djm 1977: /* Determine length of pwd so we can trim completion display */
1978: for (hadglob = tmplen = pwdlen = 0; tmp[tmplen] != 0; tmplen++) {
1979: /* Terminate counting on first unescaped glob metacharacter */
1980: if (tmp[tmplen] == '*' || tmp[tmplen] == '?') {
1981: if (tmp[tmplen] != '*' || tmp[tmplen + 1] != '\0')
1982: hadglob = 1;
1983: break;
1984: }
1985: if (tmp[tmplen] == '\\' && tmp[tmplen + 1] != '\0')
1986: tmplen++;
1987: if (tmp[tmplen] == '/')
1988: pwdlen = tmplen + 1; /* track last seen '/' */
1989: }
1.145 djm 1990: free(tmp);
1.161 dtucker 1991: tmp = NULL;
1.116 djm 1992:
1.149 djm 1993: if (g.gl_matchc == 0)
1.116 djm 1994: goto out;
1995:
1996: if (g.gl_matchc > 1)
1997: complete_display(g.gl_pathv, pwdlen);
1998:
1999: /* Don't try to extend globs */
2000: if (file == NULL || hadglob)
2001: goto out;
2002:
2003: tmp2 = complete_ambiguous(file, g.gl_pathv, g.gl_matchc);
1.139 dtucker 2004: tmp = path_strip(tmp2, isabs ? NULL : remote_path);
1.145 djm 2005: free(tmp2);
1.116 djm 2006:
2007: if (tmp == NULL)
2008: goto out;
2009:
2010: tmplen = strlen(tmp);
2011: filelen = strlen(file);
2012:
1.140 dtucker 2013: /* Count the number of escaped characters in the input string. */
2014: cesc = isesc = 0;
2015: for (i = 0; i < filelen; i++) {
2016: if (!isesc && file[i] == '\\' && i + 1 < filelen){
2017: isesc = 1;
2018: cesc++;
2019: } else
2020: isesc = 0;
2021: }
2022:
2023: if (tmplen > (filelen - cesc)) {
2024: tmp2 = tmp + filelen - cesc;
1.149 djm 2025: len = strlen(tmp2);
1.116 djm 2026: /* quote argument on way out */
1.146 dtucker 2027: for (i = 0; i < len; i += clen) {
2028: if ((clen = mblen(tmp2 + i, len - i)) < 0 ||
2029: (size_t)clen > sizeof(ins) - 2)
2030: fatal("invalid multibyte character");
1.116 djm 2031: ins[0] = '\\';
1.146 dtucker 2032: memcpy(ins + 1, tmp2 + i, clen);
2033: ins[clen + 1] = '\0';
1.116 djm 2034: switch (tmp2[i]) {
2035: case '\'':
2036: case '"':
2037: case '\\':
2038: case '\t':
1.131 sthen 2039: case '[':
1.116 djm 2040: case ' ':
1.140 dtucker 2041: case '#':
2042: case '*':
1.116 djm 2043: if (quote == '\0' || tmp2[i] == quote) {
2044: if (el_insertstr(el, ins) == -1)
2045: fatal("el_insertstr "
2046: "failed.");
2047: break;
2048: }
2049: /* FALLTHROUGH */
2050: default:
2051: if (el_insertstr(el, ins + 1) == -1)
2052: fatal("el_insertstr failed.");
2053: break;
2054: }
2055: }
2056: }
2057:
2058: lf = el_line(el);
2059: if (g.gl_matchc == 1) {
2060: i = 0;
1.162 dtucker 2061: if (!terminated && quote != '\0')
1.116 djm 2062: ins[i++] = quote;
1.120 djm 2063: if (*(lf->cursor - 1) != '/' &&
2064: (lastarg || *(lf->cursor) != ' '))
1.116 djm 2065: ins[i++] = ' ';
2066: ins[i] = '\0';
2067: if (i > 0 && el_insertstr(el, ins) == -1)
2068: fatal("el_insertstr failed.");
2069: }
1.145 djm 2070: free(tmp);
1.116 djm 2071:
2072: out:
2073: globfree(&g);
2074: return g.gl_matchc;
2075: }
2076:
2077: /* tab-completion hook function, called via libedit */
2078: static unsigned char
2079: complete(EditLine *el, int ch)
2080: {
1.149 djm 2081: char **argv, *line, quote;
1.147 djm 2082: int argc, carg;
2083: u_int cursor, len, terminated, ret = CC_ERROR;
1.116 djm 2084: const LineInfo *lf;
2085: struct complete_ctx *complete_ctx;
2086:
2087: lf = el_line(el);
2088: if (el_get(el, EL_CLIENTDATA, (void**)&complete_ctx) != 0)
1.203 djm 2089: fatal_f("el_get failed");
1.116 djm 2090:
2091: /* Figure out which argument the cursor points to */
2092: cursor = lf->cursor - lf->buffer;
1.171 deraadt 2093: line = xmalloc(cursor + 1);
1.116 djm 2094: memcpy(line, lf->buffer, cursor);
2095: line[cursor] = '\0';
2096: argv = makeargv(line, &carg, 1, "e, &terminated);
1.145 djm 2097: free(line);
1.116 djm 2098:
2099: /* Get all the arguments on the line */
2100: len = lf->lastchar - lf->buffer;
1.171 deraadt 2101: line = xmalloc(len + 1);
1.116 djm 2102: memcpy(line, lf->buffer, len);
2103: line[len] = '\0';
2104: argv = makeargv(line, &argc, 1, NULL, NULL);
2105:
2106: /* Ensure cursor is at EOL or a argument boundary */
2107: if (line[cursor] != ' ' && line[cursor] != '\0' &&
2108: line[cursor] != '\n') {
1.145 djm 2109: free(line);
1.116 djm 2110: return ret;
2111: }
2112:
2113: if (carg == 0) {
2114: /* Show all available commands */
2115: complete_cmd_parse(el, NULL, argc == carg, '\0', 1);
2116: ret = CC_REDISPLAY;
2117: } else if (carg == 1 && cursor > 0 && line[cursor - 1] != ' ') {
2118: /* Handle the command parsing */
2119: if (complete_cmd_parse(el, argv[0], argc == carg,
1.149 djm 2120: quote, terminated) != 0)
1.116 djm 2121: ret = CC_REDISPLAY;
2122: } else if (carg >= 1) {
2123: /* Handle file parsing */
1.220 djm 2124: int remote = 0;
2125: int i = 0, cmdarg = 0;
1.116 djm 2126: char *filematch = NULL;
2127:
2128: if (carg > 1 && line[cursor-1] != ' ')
2129: filematch = argv[carg - 1];
1.220 djm 2130:
2131: for (i = 1; i < carg; i++) {
2132: /* Skip flags */
2133: if (argv[i][0] != '-')
2134: cmdarg++;
2135: }
2136:
2137: /*
2138: * If previous argument is complete, then offer completion
2139: * on the next one.
2140: */
2141: if (line[cursor - 1] == ' ')
2142: cmdarg++;
2143:
2144: remote = complete_is_remote(argv[0], cmdarg);
1.116 djm 2145:
1.219 djm 2146: if ((remote == REMOTE || remote == LOCAL) &&
1.116 djm 2147: complete_match(el, complete_ctx->conn,
2148: *complete_ctx->remote_pathp, filematch,
1.149 djm 2149: remote, carg == argc, quote, terminated) != 0)
1.116 djm 2150: ret = CC_REDISPLAY;
2151: }
2152:
1.149 djm 2153: free(line);
1.116 djm 2154: return ret;
2155: }
2156:
1.182 djm 2157: static int
1.112 djm 2158: interactive_loop(struct sftp_conn *conn, char *file1, char *file2)
1.44 djm 2159: {
1.116 djm 2160: char *remote_path;
1.182 djm 2161: char *dir = NULL, *startdir = NULL;
1.44 djm 2162: char cmd[2048];
1.66 jaredy 2163: int err, interactive;
1.57 djm 2164: EditLine *el = NULL;
2165: History *hl = NULL;
2166: HistEvent hev;
2167: extern char *__progname;
1.116 djm 2168: struct complete_ctx complete_ctx;
1.57 djm 2169:
2170: if (!batchmode && isatty(STDIN_FILENO)) {
2171: if ((el = el_init(__progname, stdin, stdout, stderr)) == NULL)
2172: fatal("Couldn't initialise editline");
2173: if ((hl = history_init()) == NULL)
2174: fatal("Couldn't initialise editline history");
2175: history(hl, &hev, H_SETSIZE, 100);
2176: el_set(el, EL_HIST, history, hl);
2177:
2178: el_set(el, EL_PROMPT, prompt);
2179: el_set(el, EL_EDITOR, "emacs");
2180: el_set(el, EL_TERMINAL, NULL);
2181: el_set(el, EL_SIGNAL, 1);
2182: el_source(el, NULL);
1.116 djm 2183:
2184: /* Tab Completion */
1.149 djm 2185: el_set(el, EL_ADDFN, "ftp-complete",
1.131 sthen 2186: "Context sensitive argument completion", complete);
1.116 djm 2187: complete_ctx.conn = conn;
2188: complete_ctx.remote_pathp = &remote_path;
2189: el_set(el, EL_CLIENTDATA, (void*)&complete_ctx);
2190: el_set(el, EL_BIND, "^I", "ftp-complete", NULL);
1.154 djm 2191: /* enable ctrl-left-arrow and ctrl-right-arrow */
2192: el_set(el, EL_BIND, "\\e[1;5C", "em-next-word", NULL);
1.194 tb 2193: el_set(el, EL_BIND, "\\e\\e[C", "em-next-word", NULL);
1.154 djm 2194: el_set(el, EL_BIND, "\\e[1;5D", "ed-prev-word", NULL);
2195: el_set(el, EL_BIND, "\\e\\e[D", "ed-prev-word", NULL);
1.155 djm 2196: /* make ^w match ksh behaviour */
2197: el_set(el, EL_BIND, "^w", "ed-delete-prev-word", NULL);
1.57 djm 2198: }
1.44 djm 2199:
1.116 djm 2200: remote_path = do_realpath(conn, ".");
2201: if (remote_path == NULL)
1.44 djm 2202: fatal("Need cwd");
1.182 djm 2203: startdir = xstrdup(remote_path);
1.44 djm 2204:
2205: if (file1 != NULL) {
2206: dir = xstrdup(file1);
1.116 djm 2207: dir = make_absolute(dir, remote_path);
1.44 djm 2208:
2209: if (remote_is_dir(conn, dir) && file2 == NULL) {
1.143 djm 2210: if (!quiet)
1.174 schwarze 2211: mprintf("Changing to: %s\n", dir);
1.44 djm 2212: snprintf(cmd, sizeof cmd, "cd \"%s\"", dir);
1.116 djm 2213: if (parse_dispatch_command(conn, cmd,
1.187 djm 2214: &remote_path, startdir, 1, 0) != 0) {
1.145 djm 2215: free(dir);
1.182 djm 2216: free(startdir);
1.145 djm 2217: free(remote_path);
2218: free(conn);
1.44 djm 2219: return (-1);
1.58 markus 2220: }
1.44 djm 2221: } else {
1.137 djm 2222: /* XXX this is wrong wrt quoting */
1.148 djm 2223: snprintf(cmd, sizeof cmd, "get%s %s%s%s",
2224: global_aflag ? " -a" : "", dir,
2225: file2 == NULL ? "" : " ",
2226: file2 == NULL ? "" : file2);
1.116 djm 2227: err = parse_dispatch_command(conn, cmd,
1.187 djm 2228: &remote_path, startdir, 1, 0);
1.145 djm 2229: free(dir);
1.182 djm 2230: free(startdir);
1.145 djm 2231: free(remote_path);
2232: free(conn);
1.44 djm 2233: return (err);
2234: }
1.145 djm 2235: free(dir);
1.44 djm 2236: }
2237:
1.168 millert 2238: setvbuf(stdout, NULL, _IOLBF, 0);
2239: setvbuf(infile, NULL, _IOLBF, 0);
1.44 djm 2240:
1.66 jaredy 2241: interactive = !batchmode && isatty(STDIN_FILENO);
1.44 djm 2242: err = 0;
2243: for (;;) {
1.212 schwarze 2244: struct sigaction sa;
1.57 djm 2245: const char *line;
2246: int count = 0;
1.44 djm 2247:
1.212 schwarze 2248: interrupted = 0;
2249: memset(&sa, 0, sizeof(sa));
2250: sa.sa_handler = interactive ? read_interrupt : killchild;
2251: if (sigaction(SIGINT, &sa, NULL) == -1) {
2252: debug3("sigaction(%s): %s", strsignal(SIGINT),
2253: strerror(errno));
2254: break;
2255: }
1.57 djm 2256: if (el == NULL) {
1.66 jaredy 2257: if (interactive)
2258: printf("sftp> ");
1.57 djm 2259: if (fgets(cmd, sizeof(cmd), infile) == NULL) {
1.66 jaredy 2260: if (interactive)
2261: printf("\n");
1.212 schwarze 2262: if (interrupted)
2263: continue;
1.57 djm 2264: break;
2265: }
2266: } else {
1.116 djm 2267: if ((line = el_gets(el, &count)) == NULL ||
2268: count <= 0) {
1.66 jaredy 2269: printf("\n");
1.211 schwarze 2270: if (interrupted)
2271: continue;
1.57 djm 2272: break;
1.66 jaredy 2273: }
1.57 djm 2274: history(hl, &hev, H_ENTER, line);
2275: if (strlcpy(cmd, line, sizeof(cmd)) >= sizeof(cmd)) {
2276: fprintf(stderr, "Error: input line too long\n");
2277: continue;
2278: }
1.44 djm 2279: }
2280:
1.187 djm 2281: cmd[strcspn(cmd, "\n")] = '\0';
1.44 djm 2282:
1.46 djm 2283: /* Handle user interrupts gracefully during commands */
2284: interrupted = 0;
1.197 dtucker 2285: ssh_signal(SIGINT, cmd_interrupt);
1.46 djm 2286:
1.116 djm 2287: err = parse_dispatch_command(conn, cmd, &remote_path,
1.187 djm 2288: startdir, batchmode, !interactive && el == NULL);
1.44 djm 2289: if (err != 0)
2290: break;
2291: }
1.197 dtucker 2292: ssh_signal(SIGCHLD, SIG_DFL);
1.145 djm 2293: free(remote_path);
1.182 djm 2294: free(startdir);
1.145 djm 2295: free(conn);
1.66 jaredy 2296:
2297: if (el != NULL)
2298: el_end(el);
1.44 djm 2299:
2300: /* err == 1 signifies normal "quit" exit */
2301: return (err >= 0 ? 0 : -1);
2302: }
1.34 fgsch 2303:
1.18 itojun 2304: static void
1.36 djm 2305: connect_to_server(char *path, char **args, int *in, int *out)
1.1 djm 2306: {
1.213 djm 2307: int c_in, c_out, inout[2];
1.30 deraadt 2308:
1.1 djm 2309: if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) == -1)
2310: fatal("socketpair: %s", strerror(errno));
2311: *in = *out = inout[0];
2312: c_in = c_out = inout[1];
2313:
1.36 djm 2314: if ((sshpid = fork()) == -1)
1.1 djm 2315: fatal("fork: %s", strerror(errno));
1.36 djm 2316: else if (sshpid == 0) {
1.1 djm 2317: if ((dup2(c_in, STDIN_FILENO) == -1) ||
2318: (dup2(c_out, STDOUT_FILENO) == -1)) {
2319: fprintf(stderr, "dup2: %s\n", strerror(errno));
1.47 djm 2320: _exit(1);
1.1 djm 2321: }
2322: close(*in);
2323: close(*out);
2324: close(c_in);
2325: close(c_out);
1.46 djm 2326:
2327: /*
2328: * The underlying ssh is in the same process group, so we must
1.56 deraadt 2329: * ignore SIGINT if we want to gracefully abort commands,
2330: * otherwise the signal will make it to the ssh process and
1.122 guenther 2331: * kill it too. Contrawise, since sftp sends SIGTERMs to the
2332: * underlying ssh, it must *not* ignore that signal.
1.46 djm 2333: */
1.197 dtucker 2334: ssh_signal(SIGINT, SIG_IGN);
2335: ssh_signal(SIGTERM, SIG_DFL);
1.49 dtucker 2336: execvp(path, args);
1.23 djm 2337: fprintf(stderr, "exec: %s: %s\n", path, strerror(errno));
1.47 djm 2338: _exit(1);
1.1 djm 2339: }
2340:
1.197 dtucker 2341: ssh_signal(SIGTERM, killchild);
2342: ssh_signal(SIGINT, killchild);
2343: ssh_signal(SIGHUP, killchild);
2344: ssh_signal(SIGTSTP, suspchild);
2345: ssh_signal(SIGTTIN, suspchild);
2346: ssh_signal(SIGTTOU, suspchild);
2347: ssh_signal(SIGCHLD, sigchld_handler);
1.1 djm 2348: close(c_in);
2349: close(c_out);
2350: }
2351:
1.18 itojun 2352: static void
1.1 djm 2353: usage(void)
2354: {
1.25 mpech 2355: extern char *__progname;
1.27 markus 2356:
1.19 stevesk 2357: fprintf(stderr,
1.201 djm 2358: "usage: %s [-46AaCfNpqrv] [-B buffer_size] [-b batchfile] [-c cipher]\n"
1.218 jmc 2359: " [-D sftp_server_command] [-F ssh_config] [-i identity_file]\n"
1.190 tb 2360: " [-J destination] [-l limit] [-o ssh_option] [-P port]\n"
2361: " [-R num_requests] [-S program] [-s subsystem | sftp_server]\n"
1.224 jmc 2362: " [-X sftp_option] destination\n",
1.181 millert 2363: __progname);
1.1 djm 2364: exit(1);
2365: }
2366:
1.2 stevesk 2367: int
1.1 djm 2368: main(int argc, char **argv)
2369: {
1.217 djm 2370: int r, in, out, ch, err, tmp, port = -1, noisy = 0;
2371: char *host = NULL, *user, *cp, **cpp, *file2 = NULL;
1.198 dtucker 2372: int debug_level = 0;
1.17 mouring 2373: char *file1 = NULL, *sftp_server = NULL;
1.23 djm 2374: char *ssh_program = _PATH_SSH_PROGRAM, *sftp_direct = NULL;
1.126 djm 2375: const char *errstr;
1.17 mouring 2376: LogLevel ll = SYSLOG_LEVEL_INFO;
2377: arglist args;
1.3 djm 2378: extern int optind;
2379: extern char *optarg;
1.112 djm 2380: struct sftp_conn *conn;
1.207 djm 2381: size_t copy_buffer_len = 0;
2382: size_t num_requests = 0;
1.223 djm 2383: long long llv, limit_kbps = 0;
1.67 djm 2384:
2385: /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
2386: sanitise_stdfd();
1.146 dtucker 2387: setlocale(LC_CTYPE, "");
1.1 djm 2388:
1.70 djm 2389: memset(&args, '\0', sizeof(args));
1.17 mouring 2390: args.list = NULL;
1.80 djm 2391: addargs(&args, "%s", ssh_program);
1.17 mouring 2392: addargs(&args, "-oForwardX11 no");
1.69 reyk 2393: addargs(&args, "-oPermitLocalCommand no");
1.21 stevesk 2394: addargs(&args, "-oClearAllForwardings yes");
1.40 djm 2395:
1.17 mouring 2396: ll = SYSLOG_LEVEL_INFO;
1.40 djm 2397: infile = stdin;
1.3 djm 2398:
1.109 djm 2399: while ((ch = getopt(argc, argv,
1.223 djm 2400: "1246AafhNpqrvCc:D:i:l:o:s:S:b:B:F:J:P:R:X:")) != -1) {
1.3 djm 2401: switch (ch) {
1.108 djm 2402: /* Passed through to ssh(1) */
1.201 djm 2403: case 'A':
1.108 djm 2404: case '4':
2405: case '6':
1.3 djm 2406: case 'C':
1.108 djm 2407: addargs(&args, "-%c", ch);
2408: break;
2409: /* Passed through to ssh(1) with argument */
2410: case 'F':
1.190 tb 2411: case 'J':
1.108 djm 2412: case 'c':
2413: case 'i':
2414: case 'o':
1.113 halex 2415: addargs(&args, "-%c", ch);
2416: addargs(&args, "%s", optarg);
1.108 djm 2417: break;
2418: case 'q':
1.143 djm 2419: ll = SYSLOG_LEVEL_ERROR;
2420: quiet = 1;
1.108 djm 2421: showprogress = 0;
2422: addargs(&args, "-%c", ch);
1.3 djm 2423: break;
1.109 djm 2424: case 'P':
1.181 millert 2425: port = a2port(optarg);
2426: if (port <= 0)
2427: fatal("Bad port \"%s\"\n", optarg);
1.109 djm 2428: break;
1.3 djm 2429: case 'v':
1.17 mouring 2430: if (debug_level < 3) {
2431: addargs(&args, "-v");
2432: ll = SYSLOG_LEVEL_DEBUG1 + debug_level;
2433: }
2434: debug_level++;
1.3 djm 2435: break;
1.7 markus 2436: case '1':
1.198 dtucker 2437: fatal("SSH protocol v.1 is no longer supported");
1.7 markus 2438: break;
1.108 djm 2439: case '2':
1.198 dtucker 2440: /* accept silently */
1.148 djm 2441: break;
2442: case 'a':
2443: global_aflag = 1;
1.7 markus 2444: break;
1.108 djm 2445: case 'B':
2446: copy_buffer_len = strtol(optarg, &cp, 10);
2447: if (copy_buffer_len == 0 || *cp != '\0')
2448: fatal("Invalid buffer size \"%s\"", optarg);
1.3 djm 2449: break;
1.10 deraadt 2450: case 'b':
1.39 djm 2451: if (batchmode)
2452: fatal("Batch file already specified.");
2453:
2454: /* Allow "-" as stdin */
1.56 deraadt 2455: if (strcmp(optarg, "-") != 0 &&
1.65 djm 2456: (infile = fopen(optarg, "r")) == NULL)
1.39 djm 2457: fatal("%s (%s).", strerror(errno), optarg);
1.34 fgsch 2458: showprogress = 0;
1.143 djm 2459: quiet = batchmode = 1;
1.62 djm 2460: addargs(&args, "-obatchmode yes");
1.156 djm 2461: break;
2462: case 'f':
2463: global_fflag = 1;
1.10 deraadt 2464: break;
1.199 djm 2465: case 'N':
2466: noisy = 1; /* Used to clear quiet mode after getopt */
2467: break;
1.111 djm 2468: case 'p':
2469: global_pflag = 1;
2470: break;
1.109 djm 2471: case 'D':
1.23 djm 2472: sftp_direct = optarg;
1.111 djm 2473: break;
1.126 djm 2474: case 'l':
2475: limit_kbps = strtonum(optarg, 1, 100 * 1024 * 1024,
2476: &errstr);
2477: if (errstr != NULL)
2478: usage();
2479: limit_kbps *= 1024; /* kbps */
2480: break;
1.111 djm 2481: case 'r':
2482: global_rflag = 1;
1.24 djm 2483: break;
1.26 djm 2484: case 'R':
2485: num_requests = strtol(optarg, &cp, 10);
2486: if (num_requests == 0 || *cp != '\0')
1.27 markus 2487: fatal("Invalid number of requests \"%s\"",
1.26 djm 2488: optarg);
1.108 djm 2489: break;
2490: case 's':
2491: sftp_server = optarg;
2492: break;
2493: case 'S':
2494: ssh_program = optarg;
2495: replacearg(&args, 0, "%s", ssh_program);
1.223 djm 2496: break;
2497: case 'X':
2498: /* Please keep in sync with ssh.c -X */
2499: if (strncmp(optarg, "buffer=", 7) == 0) {
2500: r = scan_scaled(optarg + 7, &llv);
2501: if (r == 0 && (llv <= 0 || llv > 256 * 1024)) {
2502: r = -1;
2503: errno = EINVAL;
2504: }
2505: if (r == -1) {
2506: fatal("Invalid buffer size \"%s\": %s",
2507: optarg + 7, strerror(errno));
2508: }
2509: copy_buffer_len = (size_t)llv;
2510: } else if (strncmp(optarg, "nrequests=", 10) == 0) {
2511: llv = strtonum(optarg + 10, 1, 256 * 1024,
2512: &errstr);
2513: if (errstr != NULL) {
2514: fatal("Invalid number of requests "
2515: "\"%s\": %s", optarg + 10, errstr);
2516: }
2517: num_requests = (size_t)llv;
2518: } else {
2519: fatal("Invalid -X option");
2520: }
1.23 djm 2521: break;
1.3 djm 2522: case 'h':
2523: default:
1.1 djm 2524: usage();
2525: }
2526: }
1.201 djm 2527:
2528: /* Do this last because we want the user to be able to override it */
2529: addargs(&args, "-oForwardAgent no");
1.45 djm 2530:
2531: if (!isatty(STDERR_FILENO))
2532: showprogress = 0;
1.199 djm 2533:
2534: if (noisy)
2535: quiet = 0;
1.1 djm 2536:
1.29 markus 2537: log_init(argv[0], ll, SYSLOG_FACILITY_USER, 1);
2538:
1.23 djm 2539: if (sftp_direct == NULL) {
2540: if (optind == argc || argc > (optind + 2))
2541: usage();
1.181 millert 2542: argv += optind;
1.23 djm 2543:
1.181 millert 2544: switch (parse_uri("sftp", *argv, &user, &host, &tmp, &file1)) {
2545: case -1:
2546: usage();
2547: break;
2548: case 0:
2549: if (tmp != -1)
2550: port = tmp;
2551: break;
2552: default:
1.192 dtucker 2553: /* Try with user, host and path. */
1.181 millert 2554: if (parse_user_host_path(*argv, &user, &host,
1.192 dtucker 2555: &file1) == 0)
2556: break;
2557: /* Try with user and host. */
2558: if (parse_user_host_port(*argv, &user, &host, NULL)
2559: == 0)
2560: break;
2561: /* Treat as a plain hostname. */
2562: host = xstrdup(*argv);
2563: host = cleanhostname(host);
1.181 millert 2564: break;
1.23 djm 2565: }
1.181 millert 2566: file2 = *(argv + 1);
1.3 djm 2567:
1.23 djm 2568: if (!*host) {
2569: fprintf(stderr, "Missing hostname\n");
1.1 djm 2570: usage();
2571: }
2572:
1.181 millert 2573: if (port != -1)
2574: addargs(&args, "-oPort %d", port);
2575: if (user != NULL) {
2576: addargs(&args, "-l");
2577: addargs(&args, "%s", user);
2578: }
1.23 djm 2579:
2580: /* no subsystem if the server-spec contains a '/' */
2581: if (sftp_server == NULL || strchr(sftp_server, '/') == NULL)
2582: addargs(&args, "-s");
2583:
1.115 guenther 2584: addargs(&args, "--");
1.23 djm 2585: addargs(&args, "%s", host);
1.27 markus 2586: addargs(&args, "%s", (sftp_server != NULL ?
1.23 djm 2587: sftp_server : "sftp"));
2588:
1.36 djm 2589: connect_to_server(ssh_program, args.list, &in, &out);
1.23 djm 2590: } else {
1.217 djm 2591: if ((r = argv_split(sftp_direct, &tmp, &cpp, 1)) != 0)
2592: fatal_r(r, "Parse -D arguments");
2593: if (cpp[0] == 0)
2594: fatal("No sftp server specified via -D");
2595: connect_to_server(cpp[0], cpp, &in, &out);
2596: argv_free(cpp, tmp);
1.1 djm 2597: }
1.70 djm 2598: freeargs(&args);
1.1 djm 2599:
1.126 djm 2600: conn = do_init(in, out, copy_buffer_len, num_requests, limit_kbps);
1.112 djm 2601: if (conn == NULL)
2602: fatal("Couldn't initialise connection to server");
2603:
1.143 djm 2604: if (!quiet) {
1.112 djm 2605: if (sftp_direct == NULL)
2606: fprintf(stderr, "Connected to %s.\n", host);
2607: else
2608: fprintf(stderr, "Attached to %s.\n", sftp_direct);
2609: }
2610:
2611: err = interactive_loop(conn, file1, file2);
1.1 djm 2612:
2613: close(in);
2614: close(out);
1.39 djm 2615: if (batchmode)
1.10 deraadt 2616: fclose(infile);
1.1 djm 2617:
1.185 bluhm 2618: while (waitpid(sshpid, NULL, 0) == -1 && sshpid > 1)
1.28 markus 2619: if (errno != EINTR)
2620: fatal("Couldn't wait for ssh process: %s",
2621: strerror(errno));
1.1 djm 2622:
1.33 djm 2623: exit(err == 0 ? 0 : 1);
1.1 djm 2624: }