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