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