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