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