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