Annotation of src/usr.bin/ssh/sftp.c, Revision 1.131
1.131 ! sthen 1: /* $OpenBSD: sftp.c,v 1.130 2010/10/05 05:13:18 djm Exp $ */
1.1 djm 2: /*
1.42 djm 3: * Copyright (c) 2001-2004 Damien Miller <djm@openbsd.org>
1.1 djm 4: *
1.42 djm 5: * Permission to use, copy, modify, and distribute this software for any
6: * purpose with or without fee is hereby granted, provided that the above
7: * copyright notice and this permission notice appear in all copies.
1.1 djm 8: *
1.42 djm 9: * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10: * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11: * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12: * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13: * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14: * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15: * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
1.1 djm 16: */
17:
1.91 deraadt 18: #include <sys/types.h>
1.72 stevesk 19: #include <sys/ioctl.h>
1.73 stevesk 20: #include <sys/wait.h>
1.75 stevesk 21: #include <sys/stat.h>
1.83 stevesk 22: #include <sys/socket.h>
1.88 stevesk 23: #include <sys/param.h>
1.100 djm 24: #include <sys/statvfs.h>
1.44 djm 25:
1.97 djm 26: #include <ctype.h>
1.85 stevesk 27: #include <errno.h>
1.44 djm 28: #include <glob.h>
1.57 djm 29: #include <histedit.h>
1.71 stevesk 30: #include <paths.h>
1.111 djm 31: #include <libgen.h>
1.74 stevesk 32: #include <signal.h>
1.89 stevesk 33: #include <stdlib.h>
1.90 stevesk 34: #include <stdio.h>
1.87 stevesk 35: #include <string.h>
1.86 stevesk 36: #include <unistd.h>
1.100 djm 37: #include <util.h>
1.91 deraadt 38: #include <stdarg.h>
1.1 djm 39:
40: #include "xmalloc.h"
41: #include "log.h"
42: #include "pathnames.h"
1.16 mouring 43: #include "misc.h"
1.1 djm 44:
45: #include "sftp.h"
1.91 deraadt 46: #include "buffer.h"
1.1 djm 47: #include "sftp-common.h"
48: #include "sftp-client.h"
1.43 djm 49:
1.112 djm 50: #define DEFAULT_COPY_BUFLEN 32768 /* Size of buffer for up/download */
51: #define DEFAULT_NUM_REQUESTS 64 /* # concurrent outstanding requests */
52:
1.44 djm 53: /* File to read commands from */
54: FILE* infile;
1.15 mouring 55:
1.44 djm 56: /* Are we in batchfile mode? */
1.39 djm 57: int batchmode = 0;
1.44 djm 58:
59: /* PID of ssh transport process */
1.36 djm 60: static pid_t sshpid = -1;
1.7 markus 61:
1.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:
1.130 djm 249: if ((shell = getenv("SHELL")) == NULL || *shell == '\0')
1.44 djm 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: {
1.129 djm 738: Attrib *a = NULL;
739: char *fname, *lname;
1.44 djm 740: glob_t g;
1.128 djm 741: int err;
1.129 djm 742: struct winsize ws;
743: u_int i, c = 1, colspace = 0, columns = 1, m = 0, width = 80;
1.44 djm 744:
745: memset(&g, 0, sizeof(g));
746:
1.128 djm 747: if (remote_glob(conn, path,
748: GLOB_MARK|GLOB_NOCHECK|GLOB_BRACE|GLOB_KEEPSTAT, NULL, &g) ||
749: (g.gl_pathc && !g.gl_matchc)) {
1.60 fgsch 750: if (g.gl_pathc)
751: globfree(&g);
1.44 djm 752: error("Can't ls: \"%s\" not found", path);
1.128 djm 753: return -1;
1.44 djm 754: }
755:
1.46 djm 756: if (interrupted)
757: goto out;
758:
1.44 djm 759: /*
1.60 fgsch 760: * If the glob returns a single match and it is a directory,
761: * then just list its contents.
1.44 djm 762: */
1.128 djm 763: if (g.gl_matchc == 1 && g.gl_statv[0] != NULL &&
764: S_ISDIR(g.gl_statv[0]->st_mode)) {
765: err = do_ls_dir(conn, g.gl_pathv[0], strip_path, lflag);
766: globfree(&g);
767: return err;
1.44 djm 768: }
769:
1.129 djm 770: if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) != -1)
771: width = ws.ws_col;
772:
1.53 djm 773: if (!(lflag & LS_SHORT_VIEW)) {
1.44 djm 774: /* Count entries for sort and find longest filename */
775: for (i = 0; g.gl_pathv[i]; i++)
776: m = MAX(m, strlen(g.gl_pathv[i]));
777:
778: columns = width / (m + 2);
779: columns = MAX(columns, 1);
780: colspace = width / columns;
781: }
782:
1.60 fgsch 783: for (i = 0; g.gl_pathv[i] && !interrupted; i++, a = NULL) {
1.44 djm 784: fname = path_strip(g.gl_pathv[i], strip_path);
1.53 djm 785: if (lflag & LS_LONG_VIEW) {
1.128 djm 786: if (g.gl_statv[i] == NULL) {
787: error("no stat information for %s", fname);
788: continue;
789: }
790: lname = ls_file(fname, g.gl_statv[i], 1,
791: (lflag & LS_SI_UNITS));
1.44 djm 792: printf("%s\n", lname);
793: xfree(lname);
794: } else {
795: printf("%-*s", colspace, fname);
796: if (c >= columns) {
797: printf("\n");
798: c = 1;
799: } else
800: c++;
801: }
802: xfree(fname);
803: }
804:
1.53 djm 805: if (!(lflag & LS_LONG_VIEW) && (c != 1))
1.44 djm 806: printf("\n");
807:
1.46 djm 808: out:
1.44 djm 809: if (g.gl_pathc)
810: globfree(&g);
811:
1.128 djm 812: return 0;
1.44 djm 813: }
814:
1.100 djm 815: static int
816: do_df(struct sftp_conn *conn, char *path, int hflag, int iflag)
817: {
1.101 dtucker 818: struct sftp_statvfs st;
1.100 djm 819: char s_used[FMT_SCALED_STRSIZE];
820: char s_avail[FMT_SCALED_STRSIZE];
821: char s_root[FMT_SCALED_STRSIZE];
822: char s_total[FMT_SCALED_STRSIZE];
1.114 dtucker 823: unsigned long long ffree;
1.100 djm 824:
825: if (do_statvfs(conn, path, &st, 1) == -1)
826: return -1;
827: if (iflag) {
1.114 dtucker 828: ffree = st.f_files ? (100 * (st.f_files - st.f_ffree) / st.f_files) : 0;
1.100 djm 829: printf(" Inodes Used Avail "
830: "(root) %%Capacity\n");
831: printf("%11llu %11llu %11llu %11llu %3llu%%\n",
832: (unsigned long long)st.f_files,
833: (unsigned long long)(st.f_files - st.f_ffree),
834: (unsigned long long)st.f_favail,
1.114 dtucker 835: (unsigned long long)st.f_ffree, ffree);
1.100 djm 836: } else if (hflag) {
837: strlcpy(s_used, "error", sizeof(s_used));
838: strlcpy(s_avail, "error", sizeof(s_avail));
839: strlcpy(s_root, "error", sizeof(s_root));
840: strlcpy(s_total, "error", sizeof(s_total));
841: fmt_scaled((st.f_blocks - st.f_bfree) * st.f_frsize, s_used);
842: fmt_scaled(st.f_bavail * st.f_frsize, s_avail);
843: fmt_scaled(st.f_bfree * st.f_frsize, s_root);
844: fmt_scaled(st.f_blocks * st.f_frsize, s_total);
845: printf(" Size Used Avail (root) %%Capacity\n");
846: printf("%7sB %7sB %7sB %7sB %3llu%%\n",
847: s_total, s_used, s_avail, s_root,
848: (unsigned long long)(100 * (st.f_blocks - st.f_bfree) /
849: st.f_blocks));
850: } else {
851: printf(" Size Used Avail "
852: "(root) %%Capacity\n");
853: printf("%12llu %12llu %12llu %12llu %3llu%%\n",
854: (unsigned long long)(st.f_frsize * st.f_blocks / 1024),
855: (unsigned long long)(st.f_frsize *
856: (st.f_blocks - st.f_bfree) / 1024),
857: (unsigned long long)(st.f_frsize * st.f_bavail / 1024),
858: (unsigned long long)(st.f_frsize * st.f_bfree / 1024),
859: (unsigned long long)(100 * (st.f_blocks - st.f_bfree) /
860: st.f_blocks));
861: }
862: return 0;
863: }
864:
1.97 djm 865: /*
866: * Undo escaping of glob sequences in place. Used to undo extra escaping
867: * applied in makeargv() when the string is destined for a function that
868: * does not glob it.
869: */
870: static void
871: undo_glob_escape(char *s)
872: {
873: size_t i, j;
874:
875: for (i = j = 0;;) {
876: if (s[i] == '\0') {
877: s[j] = '\0';
878: return;
879: }
880: if (s[i] != '\\') {
881: s[j++] = s[i++];
882: continue;
883: }
884: /* s[i] == '\\' */
885: ++i;
886: switch (s[i]) {
887: case '?':
888: case '[':
889: case '*':
890: case '\\':
891: s[j++] = s[i++];
892: break;
893: case '\0':
894: s[j++] = '\\';
895: s[j] = '\0';
896: return;
897: default:
898: s[j++] = '\\';
899: s[j++] = s[i++];
900: break;
901: }
902: }
903: }
904:
905: /*
906: * Split a string into an argument vector using sh(1)-style quoting,
907: * comment and escaping rules, but with some tweaks to handle glob(3)
908: * wildcards.
1.116 djm 909: * The "sloppy" flag allows for recovery from missing terminating quote, for
910: * use in parsing incomplete commandlines during tab autocompletion.
911: *
1.97 djm 912: * Returns NULL on error or a NULL-terminated array of arguments.
1.116 djm 913: *
914: * If "lastquote" is not NULL, the quoting character used for the last
915: * argument is placed in *lastquote ("\0", "'" or "\"").
916: *
917: * If "terminated" is not NULL, *terminated will be set to 1 when the
918: * last argument's quote has been properly terminated or 0 otherwise.
919: * This parameter is only of use if "sloppy" is set.
1.97 djm 920: */
921: #define MAXARGS 128
922: #define MAXARGLEN 8192
923: static char **
1.116 djm 924: makeargv(const char *arg, int *argcp, int sloppy, char *lastquote,
925: u_int *terminated)
1.97 djm 926: {
927: int argc, quot;
928: size_t i, j;
929: static char argvs[MAXARGLEN];
930: static char *argv[MAXARGS + 1];
931: enum { MA_START, MA_SQUOTE, MA_DQUOTE, MA_UNQUOTED } state, q;
932:
933: *argcp = argc = 0;
934: if (strlen(arg) > sizeof(argvs) - 1) {
935: args_too_longs:
936: error("string too long");
937: return NULL;
938: }
1.116 djm 939: if (terminated != NULL)
940: *terminated = 1;
941: if (lastquote != NULL)
942: *lastquote = '\0';
1.97 djm 943: state = MA_START;
944: i = j = 0;
945: for (;;) {
946: if (isspace(arg[i])) {
947: if (state == MA_UNQUOTED) {
948: /* Terminate current argument */
949: argvs[j++] = '\0';
950: argc++;
951: state = MA_START;
952: } else if (state != MA_START)
953: argvs[j++] = arg[i];
954: } else if (arg[i] == '"' || arg[i] == '\'') {
955: q = arg[i] == '"' ? MA_DQUOTE : MA_SQUOTE;
956: if (state == MA_START) {
957: argv[argc] = argvs + j;
958: state = q;
1.116 djm 959: if (lastquote != NULL)
960: *lastquote = arg[i];
1.97 djm 961: } else if (state == MA_UNQUOTED)
962: state = q;
963: else if (state == q)
964: state = MA_UNQUOTED;
965: else
966: argvs[j++] = arg[i];
967: } else if (arg[i] == '\\') {
968: if (state == MA_SQUOTE || state == MA_DQUOTE) {
969: quot = state == MA_SQUOTE ? '\'' : '"';
970: /* Unescape quote we are in */
971: /* XXX support \n and friends? */
972: if (arg[i + 1] == quot) {
973: i++;
974: argvs[j++] = arg[i];
975: } else if (arg[i + 1] == '?' ||
976: arg[i + 1] == '[' || arg[i + 1] == '*') {
977: /*
978: * Special case for sftp: append
979: * double-escaped glob sequence -
980: * glob will undo one level of
981: * escaping. NB. string can grow here.
982: */
983: if (j >= sizeof(argvs) - 5)
984: goto args_too_longs;
985: argvs[j++] = '\\';
986: argvs[j++] = arg[i++];
987: argvs[j++] = '\\';
988: argvs[j++] = arg[i];
989: } else {
990: argvs[j++] = arg[i++];
991: argvs[j++] = arg[i];
992: }
993: } else {
994: if (state == MA_START) {
995: argv[argc] = argvs + j;
996: state = MA_UNQUOTED;
1.116 djm 997: if (lastquote != NULL)
998: *lastquote = '\0';
1.97 djm 999: }
1000: if (arg[i + 1] == '?' || arg[i + 1] == '[' ||
1001: arg[i + 1] == '*' || arg[i + 1] == '\\') {
1002: /*
1003: * Special case for sftp: append
1004: * escaped glob sequence -
1005: * glob will undo one level of
1006: * escaping.
1007: */
1008: argvs[j++] = arg[i++];
1009: argvs[j++] = arg[i];
1010: } else {
1011: /* Unescape everything */
1012: /* XXX support \n and friends? */
1013: i++;
1014: argvs[j++] = arg[i];
1015: }
1016: }
1017: } else if (arg[i] == '#') {
1018: if (state == MA_SQUOTE || state == MA_DQUOTE)
1019: argvs[j++] = arg[i];
1020: else
1021: goto string_done;
1022: } else if (arg[i] == '\0') {
1023: if (state == MA_SQUOTE || state == MA_DQUOTE) {
1.116 djm 1024: if (sloppy) {
1025: state = MA_UNQUOTED;
1026: if (terminated != NULL)
1027: *terminated = 0;
1028: goto string_done;
1029: }
1.97 djm 1030: error("Unterminated quoted argument");
1031: return NULL;
1032: }
1033: string_done:
1034: if (state == MA_UNQUOTED) {
1035: argvs[j++] = '\0';
1036: argc++;
1037: }
1038: break;
1039: } else {
1040: if (state == MA_START) {
1041: argv[argc] = argvs + j;
1042: state = MA_UNQUOTED;
1.116 djm 1043: if (lastquote != NULL)
1044: *lastquote = '\0';
1.97 djm 1045: }
1046: if ((state == MA_SQUOTE || state == MA_DQUOTE) &&
1047: (arg[i] == '?' || arg[i] == '[' || arg[i] == '*')) {
1048: /*
1049: * Special case for sftp: escape quoted
1050: * glob(3) wildcards. NB. string can grow
1051: * here.
1052: */
1053: if (j >= sizeof(argvs) - 3)
1054: goto args_too_longs;
1055: argvs[j++] = '\\';
1056: argvs[j++] = arg[i];
1057: } else
1058: argvs[j++] = arg[i];
1059: }
1060: i++;
1061: }
1062: *argcp = argc;
1063: return argv;
1064: }
1065:
1.44 djm 1066: static int
1.116 djm 1067: parse_args(const char **cpp, int *pflag, int *rflag, int *lflag, int *iflag,
1068: int *hflag, unsigned long *n_arg, char **path1, char **path2)
1.44 djm 1069: {
1070: const char *cmd, *cp = *cpp;
1.97 djm 1071: char *cp2, **argv;
1.44 djm 1072: int base = 0;
1073: long l;
1.97 djm 1074: int i, cmdnum, optidx, argc;
1.44 djm 1075:
1076: /* Skip leading whitespace */
1077: cp = cp + strspn(cp, WHITESPACE);
1078:
1079: /* Check for leading '-' (disable error processing) */
1080: *iflag = 0;
1081: if (*cp == '-') {
1082: *iflag = 1;
1083: cp++;
1.118 dtucker 1084: cp = cp + strspn(cp, WHITESPACE);
1.44 djm 1085: }
1.118 dtucker 1086:
1087: /* Ignore blank lines and lines which begin with comment '#' char */
1088: if (*cp == '\0' || *cp == '#')
1089: return (0);
1.44 djm 1090:
1.116 djm 1091: if ((argv = makeargv(cp, &argc, 0, NULL, NULL)) == NULL)
1.97 djm 1092: return -1;
1093:
1.44 djm 1094: /* Figure out which command we have */
1.97 djm 1095: for (i = 0; cmds[i].c != NULL; i++) {
1096: if (strcasecmp(cmds[i].c, argv[0]) == 0)
1.44 djm 1097: break;
1098: }
1099: cmdnum = cmds[i].n;
1100: cmd = cmds[i].c;
1101:
1102: /* Special case */
1103: if (*cp == '!') {
1104: cp++;
1105: cmdnum = I_SHELL;
1106: } else if (cmdnum == -1) {
1107: error("Invalid command.");
1.97 djm 1108: return -1;
1.44 djm 1109: }
1110:
1111: /* Get arguments and parse flags */
1.111 djm 1112: *lflag = *pflag = *rflag = *hflag = *n_arg = 0;
1.44 djm 1113: *path1 = *path2 = NULL;
1.97 djm 1114: optidx = 1;
1.44 djm 1115: switch (cmdnum) {
1116: case I_GET:
1117: case I_PUT:
1.111 djm 1118: if ((optidx = parse_getput_flags(cmd, argv, argc, pflag, rflag)) == -1)
1.97 djm 1119: return -1;
1.44 djm 1120: /* Get first pathname (mandatory) */
1.97 djm 1121: if (argc - optidx < 1) {
1.44 djm 1122: error("You must specify at least one path after a "
1123: "%s command.", cmd);
1.97 djm 1124: return -1;
1125: }
1126: *path1 = xstrdup(argv[optidx]);
1127: /* Get second pathname (optional) */
1128: if (argc - optidx > 1) {
1129: *path2 = xstrdup(argv[optidx + 1]);
1130: /* Destination is not globbed */
1131: undo_glob_escape(*path2);
1.44 djm 1132: }
1133: break;
1134: case I_RENAME:
1135: case I_SYMLINK:
1.97 djm 1136: if (argc - optidx < 2) {
1.44 djm 1137: error("You must specify two paths after a %s "
1138: "command.", cmd);
1.97 djm 1139: return -1;
1.44 djm 1140: }
1.97 djm 1141: *path1 = xstrdup(argv[optidx]);
1142: *path2 = xstrdup(argv[optidx + 1]);
1143: /* Paths are not globbed */
1144: undo_glob_escape(*path1);
1145: undo_glob_escape(*path2);
1.44 djm 1146: break;
1147: case I_RM:
1148: case I_MKDIR:
1149: case I_RMDIR:
1150: case I_CHDIR:
1151: case I_LCHDIR:
1152: case I_LMKDIR:
1153: /* Get pathname (mandatory) */
1.97 djm 1154: if (argc - optidx < 1) {
1.44 djm 1155: error("You must specify a path after a %s command.",
1156: cmd);
1.97 djm 1157: return -1;
1.44 djm 1158: }
1.97 djm 1159: *path1 = xstrdup(argv[optidx]);
1160: /* Only "rm" globs */
1161: if (cmdnum != I_RM)
1162: undo_glob_escape(*path1);
1.44 djm 1163: break;
1.100 djm 1164: case I_DF:
1165: if ((optidx = parse_df_flags(cmd, argv, argc, hflag,
1166: iflag)) == -1)
1167: return -1;
1168: /* Default to current directory if no path specified */
1169: if (argc - optidx < 1)
1170: *path1 = NULL;
1171: else {
1172: *path1 = xstrdup(argv[optidx]);
1173: undo_glob_escape(*path1);
1174: }
1175: break;
1.44 djm 1176: case I_LS:
1.97 djm 1177: if ((optidx = parse_ls_flags(argv, argc, lflag)) == -1)
1.44 djm 1178: return(-1);
1179: /* Path is optional */
1.97 djm 1180: if (argc - optidx > 0)
1181: *path1 = xstrdup(argv[optidx]);
1.44 djm 1182: break;
1183: case I_LLS:
1.98 djm 1184: /* Skip ls command and following whitespace */
1185: cp = cp + strlen(cmd) + strspn(cp, WHITESPACE);
1.44 djm 1186: case I_SHELL:
1187: /* Uses the rest of the line */
1188: break;
1189: case I_LUMASK:
1190: case I_CHMOD:
1191: base = 8;
1192: case I_CHOWN:
1193: case I_CHGRP:
1194: /* Get numeric arg (mandatory) */
1.97 djm 1195: if (argc - optidx < 1)
1196: goto need_num_arg;
1.93 ray 1197: errno = 0;
1.97 djm 1198: l = strtol(argv[optidx], &cp2, base);
1199: if (cp2 == argv[optidx] || *cp2 != '\0' ||
1200: ((l == LONG_MIN || l == LONG_MAX) && errno == ERANGE) ||
1201: l < 0) {
1202: need_num_arg:
1.44 djm 1203: error("You must supply a numeric argument "
1204: "to the %s command.", cmd);
1.97 djm 1205: return -1;
1.44 djm 1206: }
1207: *n_arg = l;
1.97 djm 1208: if (cmdnum == I_LUMASK)
1.44 djm 1209: break;
1210: /* Get pathname (mandatory) */
1.97 djm 1211: if (argc - optidx < 2) {
1.44 djm 1212: error("You must specify a path after a %s command.",
1213: cmd);
1.97 djm 1214: return -1;
1.44 djm 1215: }
1.97 djm 1216: *path1 = xstrdup(argv[optidx + 1]);
1.44 djm 1217: break;
1218: case I_QUIT:
1219: case I_PWD:
1220: case I_LPWD:
1221: case I_HELP:
1222: case I_VERSION:
1223: case I_PROGRESS:
1224: break;
1225: default:
1226: fatal("Command not implemented");
1227: }
1228:
1229: *cpp = cp;
1230: return(cmdnum);
1231: }
1232:
1233: static int
1234: parse_dispatch_command(struct sftp_conn *conn, const char *cmd, char **pwd,
1235: int err_abort)
1236: {
1237: char *path1, *path2, *tmp;
1.111 djm 1238: int pflag = 0, rflag = 0, lflag = 0, iflag = 0, hflag = 0, cmdnum, i;
1.107 dtucker 1239: unsigned long n_arg = 0;
1.44 djm 1240: Attrib a, *aa;
1241: char path_buf[MAXPATHLEN];
1242: int err = 0;
1243: glob_t g;
1244:
1245: path1 = path2 = NULL;
1.111 djm 1246: cmdnum = parse_args(&cmd, &pflag, &rflag, &lflag, &iflag, &hflag, &n_arg,
1.44 djm 1247: &path1, &path2);
1248:
1249: if (iflag != 0)
1250: err_abort = 0;
1251:
1252: memset(&g, 0, sizeof(g));
1253:
1254: /* Perform command */
1255: switch (cmdnum) {
1256: case 0:
1257: /* Blank line */
1258: break;
1259: case -1:
1260: /* Unrecognized command */
1261: err = -1;
1262: break;
1263: case I_GET:
1.111 djm 1264: err = process_get(conn, path1, path2, *pwd, pflag, rflag);
1.44 djm 1265: break;
1266: case I_PUT:
1.111 djm 1267: err = process_put(conn, path1, path2, *pwd, pflag, rflag);
1.44 djm 1268: break;
1269: case I_RENAME:
1270: path1 = make_absolute(path1, *pwd);
1271: path2 = make_absolute(path2, *pwd);
1272: err = do_rename(conn, path1, path2);
1273: break;
1274: case I_SYMLINK:
1275: path2 = make_absolute(path2, *pwd);
1276: err = do_symlink(conn, path1, path2);
1277: break;
1278: case I_RM:
1279: path1 = make_absolute(path1, *pwd);
1280: remote_glob(conn, path1, GLOB_NOCHECK, NULL, &g);
1.46 djm 1281: for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
1.44 djm 1282: printf("Removing %s\n", g.gl_pathv[i]);
1283: err = do_rm(conn, g.gl_pathv[i]);
1284: if (err != 0 && err_abort)
1285: break;
1286: }
1287: break;
1288: case I_MKDIR:
1289: path1 = make_absolute(path1, *pwd);
1290: attrib_clear(&a);
1291: a.flags |= SSH2_FILEXFER_ATTR_PERMISSIONS;
1292: a.perm = 0777;
1.111 djm 1293: err = do_mkdir(conn, path1, &a, 1);
1.44 djm 1294: break;
1295: case I_RMDIR:
1296: path1 = make_absolute(path1, *pwd);
1297: err = do_rmdir(conn, path1);
1298: break;
1299: case I_CHDIR:
1300: path1 = make_absolute(path1, *pwd);
1301: if ((tmp = do_realpath(conn, path1)) == NULL) {
1302: err = 1;
1303: break;
1304: }
1305: if ((aa = do_stat(conn, tmp, 0)) == NULL) {
1306: xfree(tmp);
1307: err = 1;
1308: break;
1309: }
1310: if (!(aa->flags & SSH2_FILEXFER_ATTR_PERMISSIONS)) {
1311: error("Can't change directory: Can't check target");
1312: xfree(tmp);
1313: err = 1;
1314: break;
1315: }
1316: if (!S_ISDIR(aa->perm)) {
1317: error("Can't change directory: \"%s\" is not "
1318: "a directory", tmp);
1319: xfree(tmp);
1320: err = 1;
1321: break;
1322: }
1323: xfree(*pwd);
1324: *pwd = tmp;
1325: break;
1326: case I_LS:
1327: if (!path1) {
1.125 djm 1328: do_ls_dir(conn, *pwd, *pwd, lflag);
1.44 djm 1329: break;
1330: }
1331:
1332: /* Strip pwd off beginning of non-absolute paths */
1333: tmp = NULL;
1334: if (*path1 != '/')
1335: tmp = *pwd;
1336:
1337: path1 = make_absolute(path1, *pwd);
1338: err = do_globbed_ls(conn, path1, tmp, lflag);
1.100 djm 1339: break;
1340: case I_DF:
1341: /* Default to current directory if no path specified */
1342: if (path1 == NULL)
1343: path1 = xstrdup(*pwd);
1344: path1 = make_absolute(path1, *pwd);
1345: err = do_df(conn, path1, hflag, iflag);
1.44 djm 1346: break;
1347: case I_LCHDIR:
1348: if (chdir(path1) == -1) {
1349: error("Couldn't change local directory to "
1350: "\"%s\": %s", path1, strerror(errno));
1351: err = 1;
1352: }
1353: break;
1354: case I_LMKDIR:
1355: if (mkdir(path1, 0777) == -1) {
1356: error("Couldn't create local directory "
1357: "\"%s\": %s", path1, strerror(errno));
1358: err = 1;
1359: }
1360: break;
1361: case I_LLS:
1362: local_do_ls(cmd);
1363: break;
1364: case I_SHELL:
1365: local_do_shell(cmd);
1366: break;
1367: case I_LUMASK:
1368: umask(n_arg);
1369: printf("Local umask: %03lo\n", n_arg);
1370: break;
1371: case I_CHMOD:
1372: path1 = make_absolute(path1, *pwd);
1373: attrib_clear(&a);
1374: a.flags |= SSH2_FILEXFER_ATTR_PERMISSIONS;
1375: a.perm = n_arg;
1376: remote_glob(conn, path1, GLOB_NOCHECK, NULL, &g);
1.46 djm 1377: for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
1.44 djm 1378: printf("Changing mode on %s\n", g.gl_pathv[i]);
1379: err = do_setstat(conn, g.gl_pathv[i], &a);
1380: if (err != 0 && err_abort)
1381: break;
1382: }
1383: break;
1384: case I_CHOWN:
1385: case I_CHGRP:
1386: path1 = make_absolute(path1, *pwd);
1387: remote_glob(conn, path1, GLOB_NOCHECK, NULL, &g);
1.46 djm 1388: for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
1.44 djm 1389: if (!(aa = do_stat(conn, g.gl_pathv[i], 0))) {
1.104 djm 1390: if (err_abort) {
1391: err = -1;
1.44 djm 1392: break;
1.104 djm 1393: } else
1.44 djm 1394: continue;
1395: }
1396: if (!(aa->flags & SSH2_FILEXFER_ATTR_UIDGID)) {
1397: error("Can't get current ownership of "
1398: "remote file \"%s\"", g.gl_pathv[i]);
1.104 djm 1399: if (err_abort) {
1400: err = -1;
1.44 djm 1401: break;
1.104 djm 1402: } else
1.44 djm 1403: continue;
1404: }
1405: aa->flags &= SSH2_FILEXFER_ATTR_UIDGID;
1406: if (cmdnum == I_CHOWN) {
1407: printf("Changing owner on %s\n", g.gl_pathv[i]);
1408: aa->uid = n_arg;
1409: } else {
1410: printf("Changing group on %s\n", g.gl_pathv[i]);
1411: aa->gid = n_arg;
1412: }
1413: err = do_setstat(conn, g.gl_pathv[i], aa);
1414: if (err != 0 && err_abort)
1415: break;
1416: }
1417: break;
1418: case I_PWD:
1419: printf("Remote working directory: %s\n", *pwd);
1420: break;
1421: case I_LPWD:
1422: if (!getcwd(path_buf, sizeof(path_buf))) {
1423: error("Couldn't get local cwd: %s", strerror(errno));
1424: err = -1;
1425: break;
1426: }
1427: printf("Local working directory: %s\n", path_buf);
1428: break;
1429: case I_QUIT:
1430: /* Processed below */
1431: break;
1432: case I_HELP:
1433: help();
1434: break;
1435: case I_VERSION:
1436: printf("SFTP protocol version %u\n", sftp_proto_version(conn));
1437: break;
1438: case I_PROGRESS:
1439: showprogress = !showprogress;
1440: if (showprogress)
1441: printf("Progress meter enabled\n");
1442: else
1443: printf("Progress meter disabled\n");
1444: break;
1445: default:
1446: fatal("%d is not implemented", cmdnum);
1447: }
1448:
1449: if (g.gl_pathc)
1450: globfree(&g);
1451: if (path1)
1452: xfree(path1);
1453: if (path2)
1454: xfree(path2);
1455:
1456: /* If an unignored error occurs in batch mode we should abort. */
1457: if (err_abort && err != 0)
1458: return (-1);
1459: else if (cmdnum == I_QUIT)
1460: return (1);
1461:
1462: return (0);
1463: }
1464:
1.57 djm 1465: static char *
1466: prompt(EditLine *el)
1467: {
1468: return ("sftp> ");
1469: }
1470:
1.116 djm 1471: /* Display entries in 'list' after skipping the first 'len' chars */
1472: static void
1473: complete_display(char **list, u_int len)
1474: {
1475: u_int y, m = 0, width = 80, columns = 1, colspace = 0, llen;
1476: struct winsize ws;
1477: char *tmp;
1478:
1479: /* Count entries for sort and find longest */
1480: for (y = 0; list[y]; y++)
1481: m = MAX(m, strlen(list[y]));
1482:
1483: if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) != -1)
1484: width = ws.ws_col;
1485:
1486: m = m > len ? m - len : 0;
1487: columns = width / (m + 2);
1488: columns = MAX(columns, 1);
1489: colspace = width / columns;
1490: colspace = MIN(colspace, width);
1491:
1492: printf("\n");
1493: m = 1;
1494: for (y = 0; list[y]; y++) {
1495: llen = strlen(list[y]);
1496: tmp = llen > len ? list[y] + len : "";
1497: printf("%-*s", colspace, tmp);
1498: if (m >= columns) {
1499: printf("\n");
1500: m = 1;
1501: } else
1502: m++;
1503: }
1504: printf("\n");
1505: }
1506:
1507: /*
1508: * Given a "list" of words that begin with a common prefix of "word",
1509: * attempt to find an autocompletion to extends "word" by the next
1510: * characters common to all entries in "list".
1511: */
1512: static char *
1513: complete_ambiguous(const char *word, char **list, size_t count)
1514: {
1515: if (word == NULL)
1516: return NULL;
1517:
1518: if (count > 0) {
1519: u_int y, matchlen = strlen(list[0]);
1520:
1521: /* Find length of common stem */
1522: for (y = 1; list[y]; y++) {
1523: u_int x;
1524:
1525: for (x = 0; x < matchlen; x++)
1526: if (list[0][x] != list[y][x])
1527: break;
1528:
1529: matchlen = x;
1530: }
1531:
1532: if (matchlen > strlen(word)) {
1533: char *tmp = xstrdup(list[0]);
1534:
1.117 dtucker 1535: tmp[matchlen] = '\0';
1.116 djm 1536: return tmp;
1537: }
1538: }
1539:
1540: return xstrdup(word);
1541: }
1542:
1543: /* Autocomplete a sftp command */
1544: static int
1545: complete_cmd_parse(EditLine *el, char *cmd, int lastarg, char quote,
1546: int terminated)
1547: {
1548: u_int y, count = 0, cmdlen, tmplen;
1549: char *tmp, **list, argterm[3];
1550: const LineInfo *lf;
1551:
1552: list = xcalloc((sizeof(cmds) / sizeof(*cmds)) + 1, sizeof(char *));
1553:
1554: /* No command specified: display all available commands */
1555: if (cmd == NULL) {
1556: for (y = 0; cmds[y].c; y++)
1557: list[count++] = xstrdup(cmds[y].c);
1558:
1559: list[count] = NULL;
1560: complete_display(list, 0);
1561:
1562: for (y = 0; list[y] != NULL; y++)
1563: xfree(list[y]);
1564: xfree(list);
1565: return count;
1566: }
1567:
1568: /* Prepare subset of commands that start with "cmd" */
1569: cmdlen = strlen(cmd);
1570: for (y = 0; cmds[y].c; y++) {
1571: if (!strncasecmp(cmd, cmds[y].c, cmdlen))
1572: list[count++] = xstrdup(cmds[y].c);
1573: }
1574: list[count] = NULL;
1575:
1576: if (count == 0)
1577: return 0;
1578:
1579: /* Complete ambigious command */
1580: tmp = complete_ambiguous(cmd, list, count);
1581: if (count > 1)
1582: complete_display(list, 0);
1583:
1584: for (y = 0; list[y]; y++)
1585: xfree(list[y]);
1586: xfree(list);
1587:
1588: if (tmp != NULL) {
1589: tmplen = strlen(tmp);
1590: cmdlen = strlen(cmd);
1591: /* If cmd may be extended then do so */
1592: if (tmplen > cmdlen)
1593: if (el_insertstr(el, tmp + cmdlen) == -1)
1594: fatal("el_insertstr failed.");
1595: lf = el_line(el);
1596: /* Terminate argument cleanly */
1597: if (count == 1) {
1598: y = 0;
1599: if (!terminated)
1600: argterm[y++] = quote;
1601: if (lastarg || *(lf->cursor) != ' ')
1602: argterm[y++] = ' ';
1603: argterm[y] = '\0';
1604: if (y > 0 && el_insertstr(el, argterm) == -1)
1605: fatal("el_insertstr failed.");
1606: }
1607: xfree(tmp);
1608: }
1609:
1610: return count;
1611: }
1612:
1613: /*
1614: * Determine whether a particular sftp command's arguments (if any)
1615: * represent local or remote files.
1616: */
1617: static int
1618: complete_is_remote(char *cmd) {
1619: int i;
1620:
1621: if (cmd == NULL)
1622: return -1;
1623:
1624: for (i = 0; cmds[i].c; i++) {
1625: if (!strncasecmp(cmd, cmds[i].c, strlen(cmds[i].c)))
1626: return cmds[i].t;
1627: }
1628:
1629: return -1;
1630: }
1631:
1632: /* Autocomplete a filename "file" */
1633: static int
1634: complete_match(EditLine *el, struct sftp_conn *conn, char *remote_path,
1635: char *file, int remote, int lastarg, char quote, int terminated)
1636: {
1637: glob_t g;
1638: char *tmp, *tmp2, ins[3];
1639: u_int i, hadglob, pwdlen, len, tmplen, filelen;
1640: const LineInfo *lf;
1641:
1642: /* Glob from "file" location */
1643: if (file == NULL)
1644: tmp = xstrdup("*");
1645: else
1646: xasprintf(&tmp, "%s*", file);
1647:
1648: memset(&g, 0, sizeof(g));
1649: if (remote != LOCAL) {
1650: tmp = make_absolute(tmp, remote_path);
1651: remote_glob(conn, tmp, GLOB_DOOFFS|GLOB_MARK, NULL, &g);
1652: } else
1653: glob(tmp, GLOB_DOOFFS|GLOB_MARK, NULL, &g);
1654:
1655: /* Determine length of pwd so we can trim completion display */
1656: for (hadglob = tmplen = pwdlen = 0; tmp[tmplen] != 0; tmplen++) {
1657: /* Terminate counting on first unescaped glob metacharacter */
1658: if (tmp[tmplen] == '*' || tmp[tmplen] == '?') {
1659: if (tmp[tmplen] != '*' || tmp[tmplen + 1] != '\0')
1660: hadglob = 1;
1661: break;
1662: }
1663: if (tmp[tmplen] == '\\' && tmp[tmplen + 1] != '\0')
1664: tmplen++;
1665: if (tmp[tmplen] == '/')
1666: pwdlen = tmplen + 1; /* track last seen '/' */
1667: }
1668: xfree(tmp);
1669:
1670: if (g.gl_matchc == 0)
1671: goto out;
1672:
1673: if (g.gl_matchc > 1)
1674: complete_display(g.gl_pathv, pwdlen);
1675:
1676: tmp = NULL;
1677: /* Don't try to extend globs */
1678: if (file == NULL || hadglob)
1679: goto out;
1680:
1681: tmp2 = complete_ambiguous(file, g.gl_pathv, g.gl_matchc);
1682: tmp = path_strip(tmp2, remote_path);
1683: xfree(tmp2);
1684:
1685: if (tmp == NULL)
1686: goto out;
1687:
1688: tmplen = strlen(tmp);
1689: filelen = strlen(file);
1690:
1691: if (tmplen > filelen) {
1692: tmp2 = tmp + filelen;
1693: len = strlen(tmp2);
1694: /* quote argument on way out */
1695: for (i = 0; i < len; i++) {
1696: ins[0] = '\\';
1697: ins[1] = tmp2[i];
1698: ins[2] = '\0';
1699: switch (tmp2[i]) {
1700: case '\'':
1701: case '"':
1702: case '\\':
1703: case '\t':
1.131 ! sthen 1704: case '[':
1.116 djm 1705: case ' ':
1706: if (quote == '\0' || tmp2[i] == quote) {
1707: if (el_insertstr(el, ins) == -1)
1708: fatal("el_insertstr "
1709: "failed.");
1710: break;
1711: }
1712: /* FALLTHROUGH */
1713: default:
1714: if (el_insertstr(el, ins + 1) == -1)
1715: fatal("el_insertstr failed.");
1716: break;
1717: }
1718: }
1719: }
1720:
1721: lf = el_line(el);
1722: if (g.gl_matchc == 1) {
1723: i = 0;
1724: if (!terminated)
1725: ins[i++] = quote;
1.120 djm 1726: if (*(lf->cursor - 1) != '/' &&
1727: (lastarg || *(lf->cursor) != ' '))
1.116 djm 1728: ins[i++] = ' ';
1729: ins[i] = '\0';
1730: if (i > 0 && el_insertstr(el, ins) == -1)
1731: fatal("el_insertstr failed.");
1732: }
1733: xfree(tmp);
1734:
1735: out:
1736: globfree(&g);
1737: return g.gl_matchc;
1738: }
1739:
1740: /* tab-completion hook function, called via libedit */
1741: static unsigned char
1742: complete(EditLine *el, int ch)
1743: {
1744: char **argv, *line, quote;
1745: u_int argc, carg, cursor, len, terminated, ret = CC_ERROR;
1746: const LineInfo *lf;
1747: struct complete_ctx *complete_ctx;
1748:
1749: lf = el_line(el);
1750: if (el_get(el, EL_CLIENTDATA, (void**)&complete_ctx) != 0)
1751: fatal("%s: el_get failed", __func__);
1752:
1753: /* Figure out which argument the cursor points to */
1754: cursor = lf->cursor - lf->buffer;
1755: line = (char *)xmalloc(cursor + 1);
1756: memcpy(line, lf->buffer, cursor);
1757: line[cursor] = '\0';
1758: argv = makeargv(line, &carg, 1, "e, &terminated);
1759: xfree(line);
1760:
1761: /* Get all the arguments on the line */
1762: len = lf->lastchar - lf->buffer;
1763: line = (char *)xmalloc(len + 1);
1764: memcpy(line, lf->buffer, len);
1765: line[len] = '\0';
1766: argv = makeargv(line, &argc, 1, NULL, NULL);
1767:
1768: /* Ensure cursor is at EOL or a argument boundary */
1769: if (line[cursor] != ' ' && line[cursor] != '\0' &&
1770: line[cursor] != '\n') {
1771: xfree(line);
1772: return ret;
1773: }
1774:
1775: if (carg == 0) {
1776: /* Show all available commands */
1777: complete_cmd_parse(el, NULL, argc == carg, '\0', 1);
1778: ret = CC_REDISPLAY;
1779: } else if (carg == 1 && cursor > 0 && line[cursor - 1] != ' ') {
1780: /* Handle the command parsing */
1781: if (complete_cmd_parse(el, argv[0], argc == carg,
1782: quote, terminated) != 0)
1783: ret = CC_REDISPLAY;
1784: } else if (carg >= 1) {
1785: /* Handle file parsing */
1786: int remote = complete_is_remote(argv[0]);
1787: char *filematch = NULL;
1788:
1789: if (carg > 1 && line[cursor-1] != ' ')
1790: filematch = argv[carg - 1];
1791:
1792: if (remote != 0 &&
1793: complete_match(el, complete_ctx->conn,
1794: *complete_ctx->remote_pathp, filematch,
1795: remote, carg == argc, quote, terminated) != 0)
1796: ret = CC_REDISPLAY;
1797: }
1798:
1799: xfree(line);
1800: return ret;
1801: }
1802:
1.44 djm 1803: int
1.112 djm 1804: interactive_loop(struct sftp_conn *conn, char *file1, char *file2)
1.44 djm 1805: {
1.116 djm 1806: char *remote_path;
1.44 djm 1807: char *dir = NULL;
1808: char cmd[2048];
1.66 jaredy 1809: int err, interactive;
1.57 djm 1810: EditLine *el = NULL;
1811: History *hl = NULL;
1812: HistEvent hev;
1813: extern char *__progname;
1.116 djm 1814: struct complete_ctx complete_ctx;
1.57 djm 1815:
1816: if (!batchmode && isatty(STDIN_FILENO)) {
1817: if ((el = el_init(__progname, stdin, stdout, stderr)) == NULL)
1818: fatal("Couldn't initialise editline");
1819: if ((hl = history_init()) == NULL)
1820: fatal("Couldn't initialise editline history");
1821: history(hl, &hev, H_SETSIZE, 100);
1822: el_set(el, EL_HIST, history, hl);
1823:
1824: el_set(el, EL_PROMPT, prompt);
1825: el_set(el, EL_EDITOR, "emacs");
1826: el_set(el, EL_TERMINAL, NULL);
1827: el_set(el, EL_SIGNAL, 1);
1828: el_source(el, NULL);
1.116 djm 1829:
1830: /* Tab Completion */
1831: el_set(el, EL_ADDFN, "ftp-complete",
1.131 ! sthen 1832: "Context sensitive argument completion", complete);
1.116 djm 1833: complete_ctx.conn = conn;
1834: complete_ctx.remote_pathp = &remote_path;
1835: el_set(el, EL_CLIENTDATA, (void*)&complete_ctx);
1836: el_set(el, EL_BIND, "^I", "ftp-complete", NULL);
1.57 djm 1837: }
1.44 djm 1838:
1.116 djm 1839: remote_path = do_realpath(conn, ".");
1840: if (remote_path == NULL)
1.44 djm 1841: fatal("Need cwd");
1842:
1843: if (file1 != NULL) {
1844: dir = xstrdup(file1);
1.116 djm 1845: dir = make_absolute(dir, remote_path);
1.44 djm 1846:
1847: if (remote_is_dir(conn, dir) && file2 == NULL) {
1848: printf("Changing to: %s\n", dir);
1849: snprintf(cmd, sizeof cmd, "cd \"%s\"", dir);
1.116 djm 1850: if (parse_dispatch_command(conn, cmd,
1851: &remote_path, 1) != 0) {
1.58 markus 1852: xfree(dir);
1.116 djm 1853: xfree(remote_path);
1.76 djm 1854: xfree(conn);
1.44 djm 1855: return (-1);
1.58 markus 1856: }
1.44 djm 1857: } else {
1858: if (file2 == NULL)
1859: snprintf(cmd, sizeof cmd, "get %s", dir);
1860: else
1861: snprintf(cmd, sizeof cmd, "get %s %s", dir,
1862: file2);
1863:
1.116 djm 1864: err = parse_dispatch_command(conn, cmd,
1865: &remote_path, 1);
1.44 djm 1866: xfree(dir);
1.116 djm 1867: xfree(remote_path);
1.76 djm 1868: xfree(conn);
1.44 djm 1869: return (err);
1870: }
1871: xfree(dir);
1872: }
1873:
1874: setvbuf(stdout, NULL, _IOLBF, 0);
1875: setvbuf(infile, NULL, _IOLBF, 0);
1876:
1.66 jaredy 1877: interactive = !batchmode && isatty(STDIN_FILENO);
1.44 djm 1878: err = 0;
1879: for (;;) {
1880: char *cp;
1.57 djm 1881: const char *line;
1882: int count = 0;
1.44 djm 1883:
1.46 djm 1884: signal(SIGINT, SIG_IGN);
1885:
1.57 djm 1886: if (el == NULL) {
1.66 jaredy 1887: if (interactive)
1888: printf("sftp> ");
1.57 djm 1889: if (fgets(cmd, sizeof(cmd), infile) == NULL) {
1.66 jaredy 1890: if (interactive)
1891: printf("\n");
1.57 djm 1892: break;
1893: }
1.66 jaredy 1894: if (!interactive) { /* Echo command */
1895: printf("sftp> %s", cmd);
1896: if (strlen(cmd) > 0 &&
1897: cmd[strlen(cmd) - 1] != '\n')
1898: printf("\n");
1899: }
1.57 djm 1900: } else {
1.116 djm 1901: if ((line = el_gets(el, &count)) == NULL ||
1902: count <= 0) {
1.66 jaredy 1903: printf("\n");
1.57 djm 1904: break;
1.66 jaredy 1905: }
1.57 djm 1906: history(hl, &hev, H_ENTER, line);
1907: if (strlcpy(cmd, line, sizeof(cmd)) >= sizeof(cmd)) {
1908: fprintf(stderr, "Error: input line too long\n");
1909: continue;
1910: }
1.44 djm 1911: }
1912:
1913: cp = strrchr(cmd, '\n');
1914: if (cp)
1915: *cp = '\0';
1916:
1.46 djm 1917: /* Handle user interrupts gracefully during commands */
1918: interrupted = 0;
1919: signal(SIGINT, cmd_interrupt);
1920:
1.116 djm 1921: err = parse_dispatch_command(conn, cmd, &remote_path,
1922: batchmode);
1.44 djm 1923: if (err != 0)
1924: break;
1925: }
1.116 djm 1926: xfree(remote_path);
1.76 djm 1927: xfree(conn);
1.66 jaredy 1928:
1929: if (el != NULL)
1930: el_end(el);
1.44 djm 1931:
1932: /* err == 1 signifies normal "quit" exit */
1933: return (err >= 0 ? 0 : -1);
1934: }
1.34 fgsch 1935:
1.18 itojun 1936: static void
1.36 djm 1937: connect_to_server(char *path, char **args, int *in, int *out)
1.1 djm 1938: {
1939: int c_in, c_out;
1.30 deraadt 1940:
1.1 djm 1941: int inout[2];
1.30 deraadt 1942:
1.1 djm 1943: if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) == -1)
1944: fatal("socketpair: %s", strerror(errno));
1945: *in = *out = inout[0];
1946: c_in = c_out = inout[1];
1947:
1.36 djm 1948: if ((sshpid = fork()) == -1)
1.1 djm 1949: fatal("fork: %s", strerror(errno));
1.36 djm 1950: else if (sshpid == 0) {
1.1 djm 1951: if ((dup2(c_in, STDIN_FILENO) == -1) ||
1952: (dup2(c_out, STDOUT_FILENO) == -1)) {
1953: fprintf(stderr, "dup2: %s\n", strerror(errno));
1.47 djm 1954: _exit(1);
1.1 djm 1955: }
1956: close(*in);
1957: close(*out);
1958: close(c_in);
1959: close(c_out);
1.46 djm 1960:
1961: /*
1962: * The underlying ssh is in the same process group, so we must
1.56 deraadt 1963: * ignore SIGINT if we want to gracefully abort commands,
1964: * otherwise the signal will make it to the ssh process and
1.122 guenther 1965: * kill it too. Contrawise, since sftp sends SIGTERMs to the
1966: * underlying ssh, it must *not* ignore that signal.
1.46 djm 1967: */
1968: signal(SIGINT, SIG_IGN);
1.122 guenther 1969: signal(SIGTERM, SIG_DFL);
1.49 dtucker 1970: execvp(path, args);
1.23 djm 1971: fprintf(stderr, "exec: %s: %s\n", path, strerror(errno));
1.47 djm 1972: _exit(1);
1.1 djm 1973: }
1974:
1.36 djm 1975: signal(SIGTERM, killchild);
1976: signal(SIGINT, killchild);
1977: signal(SIGHUP, killchild);
1.1 djm 1978: close(c_in);
1979: close(c_out);
1980: }
1981:
1.18 itojun 1982: static void
1.1 djm 1983: usage(void)
1984: {
1.25 mpech 1985: extern char *__progname;
1.27 markus 1986:
1.19 stevesk 1987: fprintf(stderr,
1.111 djm 1988: "usage: %s [-1246Cpqrv] [-B buffer_size] [-b batchfile] [-c cipher]\n"
1.110 jmc 1989: " [-D sftp_server_path] [-F ssh_config] "
1.127 jmc 1990: "[-i identity_file] [-l limit]\n"
1.110 jmc 1991: " [-o ssh_option] [-P port] [-R num_requests] "
1992: "[-S program]\n"
1.108 djm 1993: " [-s subsystem | sftp_server] host\n"
1.105 djm 1994: " %s [user@]host[:file ...]\n"
1995: " %s [user@]host[:dir[/]]\n"
1.108 djm 1996: " %s -b batchfile [user@]host\n",
1997: __progname, __progname, __progname, __progname);
1.1 djm 1998: exit(1);
1999: }
2000:
1.2 stevesk 2001: int
1.1 djm 2002: main(int argc, char **argv)
2003: {
1.33 djm 2004: int in, out, ch, err;
1.117 dtucker 2005: char *host = NULL, *userhost, *cp, *file2 = NULL;
1.17 mouring 2006: int debug_level = 0, sshver = 2;
2007: char *file1 = NULL, *sftp_server = NULL;
1.23 djm 2008: char *ssh_program = _PATH_SSH_PROGRAM, *sftp_direct = NULL;
1.126 djm 2009: const char *errstr;
1.17 mouring 2010: LogLevel ll = SYSLOG_LEVEL_INFO;
2011: arglist args;
1.3 djm 2012: extern int optind;
2013: extern char *optarg;
1.112 djm 2014: struct sftp_conn *conn;
2015: size_t copy_buffer_len = DEFAULT_COPY_BUFLEN;
2016: size_t num_requests = DEFAULT_NUM_REQUESTS;
1.126 djm 2017: long long limit_kbps = 0;
1.67 djm 2018:
2019: /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
2020: sanitise_stdfd();
1.1 djm 2021:
1.70 djm 2022: memset(&args, '\0', sizeof(args));
1.17 mouring 2023: args.list = NULL;
1.80 djm 2024: addargs(&args, "%s", ssh_program);
1.17 mouring 2025: addargs(&args, "-oForwardX11 no");
2026: addargs(&args, "-oForwardAgent no");
1.69 reyk 2027: addargs(&args, "-oPermitLocalCommand no");
1.21 stevesk 2028: addargs(&args, "-oClearAllForwardings yes");
1.40 djm 2029:
1.17 mouring 2030: ll = SYSLOG_LEVEL_INFO;
1.40 djm 2031: infile = stdin;
1.3 djm 2032:
1.109 djm 2033: while ((ch = getopt(argc, argv,
1.126 djm 2034: "1246hpqrvCc:D:i:l:o:s:S:b:B:F:P:R:")) != -1) {
1.3 djm 2035: switch (ch) {
1.108 djm 2036: /* Passed through to ssh(1) */
2037: case '4':
2038: case '6':
1.3 djm 2039: case 'C':
1.108 djm 2040: addargs(&args, "-%c", ch);
2041: break;
2042: /* Passed through to ssh(1) with argument */
2043: case 'F':
2044: case 'c':
2045: case 'i':
2046: case 'o':
1.113 halex 2047: addargs(&args, "-%c", ch);
2048: addargs(&args, "%s", optarg);
1.108 djm 2049: break;
2050: case 'q':
2051: showprogress = 0;
2052: addargs(&args, "-%c", ch);
1.3 djm 2053: break;
1.109 djm 2054: case 'P':
2055: addargs(&args, "-oPort %s", optarg);
2056: break;
1.3 djm 2057: case 'v':
1.17 mouring 2058: if (debug_level < 3) {
2059: addargs(&args, "-v");
2060: ll = SYSLOG_LEVEL_DEBUG1 + debug_level;
2061: }
2062: debug_level++;
1.3 djm 2063: break;
1.7 markus 2064: case '1':
1.17 mouring 2065: sshver = 1;
1.7 markus 2066: if (sftp_server == NULL)
2067: sftp_server = _PATH_SFTP_SERVER;
2068: break;
1.108 djm 2069: case '2':
2070: sshver = 2;
1.7 markus 2071: break;
1.108 djm 2072: case 'B':
2073: copy_buffer_len = strtol(optarg, &cp, 10);
2074: if (copy_buffer_len == 0 || *cp != '\0')
2075: fatal("Invalid buffer size \"%s\"", optarg);
1.3 djm 2076: break;
1.10 deraadt 2077: case 'b':
1.39 djm 2078: if (batchmode)
2079: fatal("Batch file already specified.");
2080:
2081: /* Allow "-" as stdin */
1.56 deraadt 2082: if (strcmp(optarg, "-") != 0 &&
1.65 djm 2083: (infile = fopen(optarg, "r")) == NULL)
1.39 djm 2084: fatal("%s (%s).", strerror(errno), optarg);
1.34 fgsch 2085: showprogress = 0;
1.39 djm 2086: batchmode = 1;
1.62 djm 2087: addargs(&args, "-obatchmode yes");
1.10 deraadt 2088: break;
1.111 djm 2089: case 'p':
2090: global_pflag = 1;
2091: break;
1.109 djm 2092: case 'D':
1.23 djm 2093: sftp_direct = optarg;
1.111 djm 2094: break;
1.126 djm 2095: case 'l':
2096: limit_kbps = strtonum(optarg, 1, 100 * 1024 * 1024,
2097: &errstr);
2098: if (errstr != NULL)
2099: usage();
2100: limit_kbps *= 1024; /* kbps */
2101: break;
1.111 djm 2102: case 'r':
2103: global_rflag = 1;
1.24 djm 2104: break;
1.26 djm 2105: case 'R':
2106: num_requests = strtol(optarg, &cp, 10);
2107: if (num_requests == 0 || *cp != '\0')
1.27 markus 2108: fatal("Invalid number of requests \"%s\"",
1.26 djm 2109: optarg);
1.108 djm 2110: break;
2111: case 's':
2112: sftp_server = optarg;
2113: break;
2114: case 'S':
2115: ssh_program = optarg;
2116: replacearg(&args, 0, "%s", ssh_program);
1.23 djm 2117: break;
1.3 djm 2118: case 'h':
2119: default:
1.1 djm 2120: usage();
2121: }
2122: }
1.45 djm 2123:
2124: if (!isatty(STDERR_FILENO))
2125: showprogress = 0;
1.1 djm 2126:
1.29 markus 2127: log_init(argv[0], ll, SYSLOG_FACILITY_USER, 1);
2128:
1.23 djm 2129: if (sftp_direct == NULL) {
2130: if (optind == argc || argc > (optind + 2))
2131: usage();
2132:
2133: userhost = xstrdup(argv[optind]);
2134: file2 = argv[optind+1];
1.1 djm 2135:
1.32 markus 2136: if ((host = strrchr(userhost, '@')) == NULL)
1.23 djm 2137: host = userhost;
2138: else {
2139: *host++ = '\0';
2140: if (!userhost[0]) {
2141: fprintf(stderr, "Missing username\n");
2142: usage();
2143: }
1.115 guenther 2144: addargs(&args, "-l");
2145: addargs(&args, "%s", userhost);
1.41 djm 2146: }
2147:
2148: if ((cp = colon(host)) != NULL) {
2149: *cp++ = '\0';
2150: file1 = cp;
1.23 djm 2151: }
1.3 djm 2152:
1.23 djm 2153: host = cleanhostname(host);
2154: if (!*host) {
2155: fprintf(stderr, "Missing hostname\n");
1.1 djm 2156: usage();
2157: }
2158:
1.23 djm 2159: addargs(&args, "-oProtocol %d", sshver);
2160:
2161: /* no subsystem if the server-spec contains a '/' */
2162: if (sftp_server == NULL || strchr(sftp_server, '/') == NULL)
2163: addargs(&args, "-s");
2164:
1.115 guenther 2165: addargs(&args, "--");
1.23 djm 2166: addargs(&args, "%s", host);
1.27 markus 2167: addargs(&args, "%s", (sftp_server != NULL ?
1.23 djm 2168: sftp_server : "sftp"));
2169:
1.36 djm 2170: connect_to_server(ssh_program, args.list, &in, &out);
1.23 djm 2171: } else {
2172: args.list = NULL;
2173: addargs(&args, "sftp-server");
2174:
1.36 djm 2175: connect_to_server(sftp_direct, args.list, &in, &out);
1.1 djm 2176: }
1.70 djm 2177: freeargs(&args);
1.1 djm 2178:
1.126 djm 2179: conn = do_init(in, out, copy_buffer_len, num_requests, limit_kbps);
1.112 djm 2180: if (conn == NULL)
2181: fatal("Couldn't initialise connection to server");
2182:
2183: if (!batchmode) {
2184: if (sftp_direct == NULL)
2185: fprintf(stderr, "Connected to %s.\n", host);
2186: else
2187: fprintf(stderr, "Attached to %s.\n", sftp_direct);
2188: }
2189:
2190: err = interactive_loop(conn, file1, file2);
1.1 djm 2191:
2192: close(in);
2193: close(out);
1.39 djm 2194: if (batchmode)
1.10 deraadt 2195: fclose(infile);
1.1 djm 2196:
1.28 markus 2197: while (waitpid(sshpid, NULL, 0) == -1)
2198: if (errno != EINTR)
2199: fatal("Couldn't wait for ssh process: %s",
2200: strerror(errno));
1.1 djm 2201:
1.33 djm 2202: exit(err == 0 ? 0 : 1);
1.1 djm 2203: }