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