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