Install dma(8) config files with mode 640 as root:mail to prevent ``normal''
[dragonfly/netmp.git] / crypto / openssh-4 / sftp.c
blobf98ed7d27505c0cf24f4b8f7cb2c292b49f9087c
1 /*
2 * Copyright (c) 2001-2004 Damien Miller <djm@openbsd.org>
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 #include "includes.h"
19 RCSID("$OpenBSD: sftp.c,v 1.66 2005/08/08 13:22:48 jaredy Exp $");
21 #ifdef USE_LIBEDIT
22 #include <histedit.h>
23 #else
24 typedef void EditLine;
25 #endif
27 #include "buffer.h"
28 #include "xmalloc.h"
29 #include "log.h"
30 #include "pathnames.h"
31 #include "misc.h"
33 #include "sftp.h"
34 #include "sftp-common.h"
35 #include "sftp-client.h"
37 /* File to read commands from */
38 FILE* infile;
40 /* Are we in batchfile mode? */
41 int batchmode = 0;
43 /* Size of buffer used when copying files */
44 size_t copy_buffer_len = 32768;
46 /* Number of concurrent outstanding requests */
47 size_t num_requests = 16;
49 /* PID of ssh transport process */
50 static pid_t sshpid = -1;
52 /* This is set to 0 if the progressmeter is not desired. */
53 int showprogress = 1;
55 /* SIGINT received during command processing */
56 volatile sig_atomic_t interrupted = 0;
58 /* I wish qsort() took a separate ctx for the comparison function...*/
59 int sort_flag;
61 int remote_glob(struct sftp_conn *, const char *, int,
62 int (*)(const char *, int), glob_t *); /* proto for sftp-glob.c */
64 extern char *__progname;
66 /* Separators for interactive commands */
67 #define WHITESPACE " \t\r\n"
69 /* ls flags */
70 #define LS_LONG_VIEW 0x01 /* Full view ala ls -l */
71 #define LS_SHORT_VIEW 0x02 /* Single row view ala ls -1 */
72 #define LS_NUMERIC_VIEW 0x04 /* Long view with numeric uid/gid */
73 #define LS_NAME_SORT 0x08 /* Sort by name (default) */
74 #define LS_TIME_SORT 0x10 /* Sort by mtime */
75 #define LS_SIZE_SORT 0x20 /* Sort by file size */
76 #define LS_REVERSE_SORT 0x40 /* Reverse sort order */
77 #define LS_SHOW_ALL 0x80 /* Don't skip filenames starting with '.' */
79 #define VIEW_FLAGS (LS_LONG_VIEW|LS_SHORT_VIEW|LS_NUMERIC_VIEW)
80 #define SORT_FLAGS (LS_NAME_SORT|LS_TIME_SORT|LS_SIZE_SORT)
82 /* Commands for interactive mode */
83 #define I_CHDIR 1
84 #define I_CHGRP 2
85 #define I_CHMOD 3
86 #define I_CHOWN 4
87 #define I_GET 5
88 #define I_HELP 6
89 #define I_LCHDIR 7
90 #define I_LLS 8
91 #define I_LMKDIR 9
92 #define I_LPWD 10
93 #define I_LS 11
94 #define I_LUMASK 12
95 #define I_MKDIR 13
96 #define I_PUT 14
97 #define I_PWD 15
98 #define I_QUIT 16
99 #define I_RENAME 17
100 #define I_RM 18
101 #define I_RMDIR 19
102 #define I_SHELL 20
103 #define I_SYMLINK 21
104 #define I_VERSION 22
105 #define I_PROGRESS 23
107 struct CMD {
108 const char *c;
109 const int n;
112 static const struct CMD cmds[] = {
113 { "bye", I_QUIT },
114 { "cd", I_CHDIR },
115 { "chdir", I_CHDIR },
116 { "chgrp", I_CHGRP },
117 { "chmod", I_CHMOD },
118 { "chown", I_CHOWN },
119 { "dir", I_LS },
120 { "exit", I_QUIT },
121 { "get", I_GET },
122 { "mget", I_GET },
123 { "help", I_HELP },
124 { "lcd", I_LCHDIR },
125 { "lchdir", I_LCHDIR },
126 { "lls", I_LLS },
127 { "lmkdir", I_LMKDIR },
128 { "ln", I_SYMLINK },
129 { "lpwd", I_LPWD },
130 { "ls", I_LS },
131 { "lumask", I_LUMASK },
132 { "mkdir", I_MKDIR },
133 { "progress", I_PROGRESS },
134 { "put", I_PUT },
135 { "mput", I_PUT },
136 { "pwd", I_PWD },
137 { "quit", I_QUIT },
138 { "rename", I_RENAME },
139 { "rm", I_RM },
140 { "rmdir", I_RMDIR },
141 { "symlink", I_SYMLINK },
142 { "version", I_VERSION },
143 { "!", I_SHELL },
144 { "?", I_HELP },
145 { NULL, -1}
148 int interactive_loop(int fd_in, int fd_out, char *file1, char *file2);
150 static void
151 killchild(int signo)
153 if (sshpid > 1) {
154 kill(sshpid, SIGTERM);
155 waitpid(sshpid, NULL, 0);
158 _exit(1);
161 static void
162 cmd_interrupt(int signo)
164 const char msg[] = "\rInterrupt \n";
165 int olderrno = errno;
167 write(STDERR_FILENO, msg, sizeof(msg) - 1);
168 interrupted = 1;
169 errno = olderrno;
172 static void
173 help(void)
175 printf("Available commands:\n");
176 printf("cd path Change remote directory to 'path'\n");
177 printf("lcd path Change local directory to 'path'\n");
178 printf("chgrp grp path Change group of file 'path' to 'grp'\n");
179 printf("chmod mode path Change permissions of file 'path' to 'mode'\n");
180 printf("chown own path Change owner of file 'path' to 'own'\n");
181 printf("help Display this help text\n");
182 printf("get remote-path [local-path] Download file\n");
183 printf("lls [ls-options [path]] Display local directory listing\n");
184 printf("ln oldpath newpath Symlink remote file\n");
185 printf("lmkdir path Create local directory\n");
186 printf("lpwd Print local working directory\n");
187 printf("ls [path] Display remote directory listing\n");
188 printf("lumask umask Set local umask to 'umask'\n");
189 printf("mkdir path Create remote directory\n");
190 printf("progress Toggle display of progress meter\n");
191 printf("put local-path [remote-path] Upload file\n");
192 printf("pwd Display remote working directory\n");
193 printf("exit Quit sftp\n");
194 printf("quit Quit sftp\n");
195 printf("rename oldpath newpath Rename remote file\n");
196 printf("rmdir path Remove remote directory\n");
197 printf("rm path Delete remote file\n");
198 printf("symlink oldpath newpath Symlink remote file\n");
199 printf("version Show SFTP version\n");
200 printf("!command Execute 'command' in local shell\n");
201 printf("! Escape to local shell\n");
202 printf("? Synonym for help\n");
205 static void
206 local_do_shell(const char *args)
208 int status;
209 char *shell;
210 pid_t pid;
212 if (!*args)
213 args = NULL;
215 if ((shell = getenv("SHELL")) == NULL)
216 shell = _PATH_BSHELL;
218 if ((pid = fork()) == -1)
219 fatal("Couldn't fork: %s", strerror(errno));
221 if (pid == 0) {
222 /* XXX: child has pipe fds to ssh subproc open - issue? */
223 if (args) {
224 debug3("Executing %s -c \"%s\"", shell, args);
225 execl(shell, shell, "-c", args, (char *)NULL);
226 } else {
227 debug3("Executing %s", shell);
228 execl(shell, shell, (char *)NULL);
230 fprintf(stderr, "Couldn't execute \"%s\": %s\n", shell,
231 strerror(errno));
232 _exit(1);
234 while (waitpid(pid, &status, 0) == -1)
235 if (errno != EINTR)
236 fatal("Couldn't wait for child: %s", strerror(errno));
237 if (!WIFEXITED(status))
238 error("Shell exited abormally");
239 else if (WEXITSTATUS(status))
240 error("Shell exited with status %d", WEXITSTATUS(status));
243 static void
244 local_do_ls(const char *args)
246 if (!args || !*args)
247 local_do_shell(_PATH_LS);
248 else {
249 int len = strlen(_PATH_LS " ") + strlen(args) + 1;
250 char *buf = xmalloc(len);
252 /* XXX: quoting - rip quoting code from ftp? */
253 snprintf(buf, len, _PATH_LS " %s", args);
254 local_do_shell(buf);
255 xfree(buf);
259 /* Strip one path (usually the pwd) from the start of another */
260 static char *
261 path_strip(char *path, char *strip)
263 size_t len;
265 if (strip == NULL)
266 return (xstrdup(path));
268 len = strlen(strip);
269 if (strncmp(path, strip, len) == 0) {
270 if (strip[len - 1] != '/' && path[len] == '/')
271 len++;
272 return (xstrdup(path + len));
275 return (xstrdup(path));
278 static char *
279 path_append(char *p1, char *p2)
281 char *ret;
282 int len = strlen(p1) + strlen(p2) + 2;
284 ret = xmalloc(len);
285 strlcpy(ret, p1, len);
286 if (p1[strlen(p1) - 1] != '/')
287 strlcat(ret, "/", len);
288 strlcat(ret, p2, len);
290 return(ret);
293 static char *
294 make_absolute(char *p, char *pwd)
296 char *abs_str;
298 /* Derelativise */
299 if (p && p[0] != '/') {
300 abs_str = path_append(pwd, p);
301 xfree(p);
302 return(abs_str);
303 } else
304 return(p);
307 static int
308 infer_path(const char *p, char **ifp)
310 char *cp;
312 cp = strrchr(p, '/');
313 if (cp == NULL) {
314 *ifp = xstrdup(p);
315 return(0);
318 if (!cp[1]) {
319 error("Invalid path");
320 return(-1);
323 *ifp = xstrdup(cp + 1);
324 return(0);
327 static int
328 parse_getput_flags(const char **cpp, int *pflag)
330 const char *cp = *cpp;
332 /* Check for flags */
333 if (cp[0] == '-' && cp[1] && strchr(WHITESPACE, cp[2])) {
334 switch (cp[1]) {
335 case 'p':
336 case 'P':
337 *pflag = 1;
338 break;
339 default:
340 error("Invalid flag -%c", cp[1]);
341 return(-1);
343 cp += 2;
344 *cpp = cp + strspn(cp, WHITESPACE);
347 return(0);
350 static int
351 parse_ls_flags(const char **cpp, int *lflag)
353 const char *cp = *cpp;
355 /* Defaults */
356 *lflag = LS_NAME_SORT;
358 /* Check for flags */
359 if (cp++[0] == '-') {
360 for (; strchr(WHITESPACE, *cp) == NULL; cp++) {
361 switch (*cp) {
362 case 'l':
363 *lflag &= ~VIEW_FLAGS;
364 *lflag |= LS_LONG_VIEW;
365 break;
366 case '1':
367 *lflag &= ~VIEW_FLAGS;
368 *lflag |= LS_SHORT_VIEW;
369 break;
370 case 'n':
371 *lflag &= ~VIEW_FLAGS;
372 *lflag |= LS_NUMERIC_VIEW|LS_LONG_VIEW;
373 break;
374 case 'S':
375 *lflag &= ~SORT_FLAGS;
376 *lflag |= LS_SIZE_SORT;
377 break;
378 case 't':
379 *lflag &= ~SORT_FLAGS;
380 *lflag |= LS_TIME_SORT;
381 break;
382 case 'r':
383 *lflag |= LS_REVERSE_SORT;
384 break;
385 case 'f':
386 *lflag &= ~SORT_FLAGS;
387 break;
388 case 'a':
389 *lflag |= LS_SHOW_ALL;
390 break;
391 default:
392 error("Invalid flag -%c", *cp);
393 return(-1);
396 *cpp = cp + strspn(cp, WHITESPACE);
399 return(0);
402 static int
403 get_pathname(const char **cpp, char **path)
405 const char *cp = *cpp, *end;
406 char quot;
407 u_int i, j;
409 cp += strspn(cp, WHITESPACE);
410 if (!*cp) {
411 *cpp = cp;
412 *path = NULL;
413 return (0);
416 *path = xmalloc(strlen(cp) + 1);
418 /* Check for quoted filenames */
419 if (*cp == '\"' || *cp == '\'') {
420 quot = *cp++;
422 /* Search for terminating quote, unescape some chars */
423 for (i = j = 0; i <= strlen(cp); i++) {
424 if (cp[i] == quot) { /* Found quote */
425 i++;
426 (*path)[j] = '\0';
427 break;
429 if (cp[i] == '\0') { /* End of string */
430 error("Unterminated quote");
431 goto fail;
433 if (cp[i] == '\\') { /* Escaped characters */
434 i++;
435 if (cp[i] != '\'' && cp[i] != '\"' &&
436 cp[i] != '\\') {
437 error("Bad escaped character '\\%c'",
438 cp[i]);
439 goto fail;
442 (*path)[j++] = cp[i];
445 if (j == 0) {
446 error("Empty quotes");
447 goto fail;
449 *cpp = cp + i + strspn(cp + i, WHITESPACE);
450 } else {
451 /* Read to end of filename */
452 end = strpbrk(cp, WHITESPACE);
453 if (end == NULL)
454 end = strchr(cp, '\0');
455 *cpp = end + strspn(end, WHITESPACE);
457 memcpy(*path, cp, end - cp);
458 (*path)[end - cp] = '\0';
460 return (0);
462 fail:
463 xfree(*path);
464 *path = NULL;
465 return (-1);
468 static int
469 is_dir(char *path)
471 struct stat sb;
473 /* XXX: report errors? */
474 if (stat(path, &sb) == -1)
475 return(0);
477 return(sb.st_mode & S_IFDIR);
480 static int
481 is_reg(char *path)
483 struct stat sb;
485 if (stat(path, &sb) == -1)
486 fatal("stat %s: %s", path, strerror(errno));
488 return(S_ISREG(sb.st_mode));
491 static int
492 remote_is_dir(struct sftp_conn *conn, char *path)
494 Attrib *a;
496 /* XXX: report errors? */
497 if ((a = do_stat(conn, path, 1)) == NULL)
498 return(0);
499 if (!(a->flags & SSH2_FILEXFER_ATTR_PERMISSIONS))
500 return(0);
501 return(a->perm & S_IFDIR);
504 static int
505 process_get(struct sftp_conn *conn, char *src, char *dst, char *pwd, int pflag)
507 char *abs_src = NULL;
508 char *abs_dst = NULL;
509 char *tmp;
510 glob_t g;
511 int err = 0;
512 int i;
514 abs_src = xstrdup(src);
515 abs_src = make_absolute(abs_src, pwd);
517 memset(&g, 0, sizeof(g));
518 debug3("Looking up %s", abs_src);
519 if (remote_glob(conn, abs_src, 0, NULL, &g)) {
520 error("File \"%s\" not found.", abs_src);
521 err = -1;
522 goto out;
525 /* If multiple matches, dst must be a directory or unspecified */
526 if (g.gl_matchc > 1 && dst && !is_dir(dst)) {
527 error("Multiple files match, but \"%s\" is not a directory",
528 dst);
529 err = -1;
530 goto out;
533 for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
534 if (infer_path(g.gl_pathv[i], &tmp)) {
535 err = -1;
536 goto out;
539 if (g.gl_matchc == 1 && dst) {
540 /* If directory specified, append filename */
541 if (is_dir(dst)) {
542 if (infer_path(g.gl_pathv[0], &tmp)) {
543 err = 1;
544 goto out;
546 abs_dst = path_append(dst, tmp);
547 xfree(tmp);
548 } else
549 abs_dst = xstrdup(dst);
550 } else if (dst) {
551 abs_dst = path_append(dst, tmp);
552 xfree(tmp);
553 } else
554 abs_dst = tmp;
556 printf("Fetching %s to %s\n", g.gl_pathv[i], abs_dst);
557 if (do_download(conn, g.gl_pathv[i], abs_dst, pflag) == -1)
558 err = -1;
559 xfree(abs_dst);
560 abs_dst = NULL;
563 out:
564 xfree(abs_src);
565 if (abs_dst)
566 xfree(abs_dst);
567 globfree(&g);
568 return(err);
571 static int
572 process_put(struct sftp_conn *conn, char *src, char *dst, char *pwd, int pflag)
574 char *tmp_dst = NULL;
575 char *abs_dst = NULL;
576 char *tmp;
577 glob_t g;
578 int err = 0;
579 int i;
581 if (dst) {
582 tmp_dst = xstrdup(dst);
583 tmp_dst = make_absolute(tmp_dst, pwd);
586 memset(&g, 0, sizeof(g));
587 debug3("Looking up %s", src);
588 if (glob(src, 0, NULL, &g)) {
589 error("File \"%s\" not found.", src);
590 err = -1;
591 goto out;
594 /* If multiple matches, dst may be directory or unspecified */
595 if (g.gl_matchc > 1 && tmp_dst && !remote_is_dir(conn, tmp_dst)) {
596 error("Multiple files match, but \"%s\" is not a directory",
597 tmp_dst);
598 err = -1;
599 goto out;
602 for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
603 if (!is_reg(g.gl_pathv[i])) {
604 error("skipping non-regular file %s",
605 g.gl_pathv[i]);
606 continue;
608 if (infer_path(g.gl_pathv[i], &tmp)) {
609 err = -1;
610 goto out;
613 if (g.gl_matchc == 1 && tmp_dst) {
614 /* If directory specified, append filename */
615 if (remote_is_dir(conn, tmp_dst)) {
616 if (infer_path(g.gl_pathv[0], &tmp)) {
617 err = 1;
618 goto out;
620 abs_dst = path_append(tmp_dst, tmp);
621 xfree(tmp);
622 } else
623 abs_dst = xstrdup(tmp_dst);
625 } else if (tmp_dst) {
626 abs_dst = path_append(tmp_dst, tmp);
627 xfree(tmp);
628 } else
629 abs_dst = make_absolute(tmp, pwd);
631 printf("Uploading %s to %s\n", g.gl_pathv[i], abs_dst);
632 if (do_upload(conn, g.gl_pathv[i], abs_dst, pflag) == -1)
633 err = -1;
636 out:
637 if (abs_dst)
638 xfree(abs_dst);
639 if (tmp_dst)
640 xfree(tmp_dst);
641 globfree(&g);
642 return(err);
645 static int
646 sdirent_comp(const void *aa, const void *bb)
648 SFTP_DIRENT *a = *(SFTP_DIRENT **)aa;
649 SFTP_DIRENT *b = *(SFTP_DIRENT **)bb;
650 int rmul = sort_flag & LS_REVERSE_SORT ? -1 : 1;
652 #define NCMP(a,b) (a == b ? 0 : (a < b ? 1 : -1))
653 if (sort_flag & LS_NAME_SORT)
654 return (rmul * strcmp(a->filename, b->filename));
655 else if (sort_flag & LS_TIME_SORT)
656 return (rmul * NCMP(a->a.mtime, b->a.mtime));
657 else if (sort_flag & LS_SIZE_SORT)
658 return (rmul * NCMP(a->a.size, b->a.size));
660 fatal("Unknown ls sort type");
663 /* sftp ls.1 replacement for directories */
664 static int
665 do_ls_dir(struct sftp_conn *conn, char *path, char *strip_path, int lflag)
667 int n;
668 u_int c = 1, colspace = 0, columns = 1;
669 SFTP_DIRENT **d;
671 if ((n = do_readdir(conn, path, &d)) != 0)
672 return (n);
674 if (!(lflag & LS_SHORT_VIEW)) {
675 u_int m = 0, width = 80;
676 struct winsize ws;
677 char *tmp;
679 /* Count entries for sort and find longest filename */
680 for (n = 0; d[n] != NULL; n++) {
681 if (d[n]->filename[0] != '.' || (lflag & LS_SHOW_ALL))
682 m = MAX(m, strlen(d[n]->filename));
685 /* Add any subpath that also needs to be counted */
686 tmp = path_strip(path, strip_path);
687 m += strlen(tmp);
688 xfree(tmp);
690 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) != -1)
691 width = ws.ws_col;
693 columns = width / (m + 2);
694 columns = MAX(columns, 1);
695 colspace = width / columns;
696 colspace = MIN(colspace, width);
699 if (lflag & SORT_FLAGS) {
700 sort_flag = lflag & (SORT_FLAGS|LS_REVERSE_SORT);
701 qsort(d, n, sizeof(*d), sdirent_comp);
704 for (n = 0; d[n] != NULL && !interrupted; n++) {
705 char *tmp, *fname;
707 if (d[n]->filename[0] == '.' && !(lflag & LS_SHOW_ALL))
708 continue;
710 tmp = path_append(path, d[n]->filename);
711 fname = path_strip(tmp, strip_path);
712 xfree(tmp);
714 if (lflag & LS_LONG_VIEW) {
715 if (lflag & LS_NUMERIC_VIEW) {
716 char *lname;
717 struct stat sb;
719 memset(&sb, 0, sizeof(sb));
720 attrib_to_stat(&d[n]->a, &sb);
721 lname = ls_file(fname, &sb, 1);
722 printf("%s\n", lname);
723 xfree(lname);
724 } else
725 printf("%s\n", d[n]->longname);
726 } else {
727 printf("%-*s", colspace, fname);
728 if (c >= columns) {
729 printf("\n");
730 c = 1;
731 } else
732 c++;
735 xfree(fname);
738 if (!(lflag & LS_LONG_VIEW) && (c != 1))
739 printf("\n");
741 free_sftp_dirents(d);
742 return (0);
745 /* sftp ls.1 replacement which handles path globs */
746 static int
747 do_globbed_ls(struct sftp_conn *conn, char *path, char *strip_path,
748 int lflag)
750 glob_t g;
751 u_int i, c = 1, colspace = 0, columns = 1;
752 Attrib *a = NULL;
754 memset(&g, 0, sizeof(g));
756 if (remote_glob(conn, path, GLOB_MARK|GLOB_NOCHECK|GLOB_BRACE,
757 NULL, &g) || (g.gl_pathc && !g.gl_matchc)) {
758 if (g.gl_pathc)
759 globfree(&g);
760 error("Can't ls: \"%s\" not found", path);
761 return (-1);
764 if (interrupted)
765 goto out;
768 * If the glob returns a single match and it is a directory,
769 * then just list its contents.
771 if (g.gl_matchc == 1) {
772 if ((a = do_lstat(conn, g.gl_pathv[0], 1)) == NULL) {
773 globfree(&g);
774 return (-1);
776 if ((a->flags & SSH2_FILEXFER_ATTR_PERMISSIONS) &&
777 S_ISDIR(a->perm)) {
778 int err;
780 err = do_ls_dir(conn, g.gl_pathv[0], strip_path, lflag);
781 globfree(&g);
782 return (err);
786 if (!(lflag & LS_SHORT_VIEW)) {
787 u_int m = 0, width = 80;
788 struct winsize ws;
790 /* Count entries for sort and find longest filename */
791 for (i = 0; g.gl_pathv[i]; i++)
792 m = MAX(m, strlen(g.gl_pathv[i]));
794 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) != -1)
795 width = ws.ws_col;
797 columns = width / (m + 2);
798 columns = MAX(columns, 1);
799 colspace = width / columns;
802 for (i = 0; g.gl_pathv[i] && !interrupted; i++, a = NULL) {
803 char *fname;
805 fname = path_strip(g.gl_pathv[i], strip_path);
807 if (lflag & LS_LONG_VIEW) {
808 char *lname;
809 struct stat sb;
812 * XXX: this is slow - 1 roundtrip per path
813 * A solution to this is to fork glob() and
814 * build a sftp specific version which keeps the
815 * attribs (which currently get thrown away)
816 * that the server returns as well as the filenames.
818 memset(&sb, 0, sizeof(sb));
819 if (a == NULL)
820 a = do_lstat(conn, g.gl_pathv[i], 1);
821 if (a != NULL)
822 attrib_to_stat(a, &sb);
823 lname = ls_file(fname, &sb, 1);
824 printf("%s\n", lname);
825 xfree(lname);
826 } else {
827 printf("%-*s", colspace, fname);
828 if (c >= columns) {
829 printf("\n");
830 c = 1;
831 } else
832 c++;
834 xfree(fname);
837 if (!(lflag & LS_LONG_VIEW) && (c != 1))
838 printf("\n");
840 out:
841 if (g.gl_pathc)
842 globfree(&g);
844 return (0);
847 static int
848 parse_args(const char **cpp, int *pflag, int *lflag, int *iflag,
849 unsigned long *n_arg, char **path1, char **path2)
851 const char *cmd, *cp = *cpp;
852 char *cp2;
853 int base = 0;
854 long l;
855 int i, cmdnum;
857 /* Skip leading whitespace */
858 cp = cp + strspn(cp, WHITESPACE);
860 /* Ignore blank lines and lines which begin with comment '#' char */
861 if (*cp == '\0' || *cp == '#')
862 return (0);
864 /* Check for leading '-' (disable error processing) */
865 *iflag = 0;
866 if (*cp == '-') {
867 *iflag = 1;
868 cp++;
871 /* Figure out which command we have */
872 for (i = 0; cmds[i].c; i++) {
873 int cmdlen = strlen(cmds[i].c);
875 /* Check for command followed by whitespace */
876 if (!strncasecmp(cp, cmds[i].c, cmdlen) &&
877 strchr(WHITESPACE, cp[cmdlen])) {
878 cp += cmdlen;
879 cp = cp + strspn(cp, WHITESPACE);
880 break;
883 cmdnum = cmds[i].n;
884 cmd = cmds[i].c;
886 /* Special case */
887 if (*cp == '!') {
888 cp++;
889 cmdnum = I_SHELL;
890 } else if (cmdnum == -1) {
891 error("Invalid command.");
892 return (-1);
895 /* Get arguments and parse flags */
896 *lflag = *pflag = *n_arg = 0;
897 *path1 = *path2 = NULL;
898 switch (cmdnum) {
899 case I_GET:
900 case I_PUT:
901 if (parse_getput_flags(&cp, pflag))
902 return(-1);
903 /* Get first pathname (mandatory) */
904 if (get_pathname(&cp, path1))
905 return(-1);
906 if (*path1 == NULL) {
907 error("You must specify at least one path after a "
908 "%s command.", cmd);
909 return(-1);
911 /* Try to get second pathname (optional) */
912 if (get_pathname(&cp, path2))
913 return(-1);
914 break;
915 case I_RENAME:
916 case I_SYMLINK:
917 if (get_pathname(&cp, path1))
918 return(-1);
919 if (get_pathname(&cp, path2))
920 return(-1);
921 if (!*path1 || !*path2) {
922 error("You must specify two paths after a %s "
923 "command.", cmd);
924 return(-1);
926 break;
927 case I_RM:
928 case I_MKDIR:
929 case I_RMDIR:
930 case I_CHDIR:
931 case I_LCHDIR:
932 case I_LMKDIR:
933 /* Get pathname (mandatory) */
934 if (get_pathname(&cp, path1))
935 return(-1);
936 if (*path1 == NULL) {
937 error("You must specify a path after a %s command.",
938 cmd);
939 return(-1);
941 break;
942 case I_LS:
943 if (parse_ls_flags(&cp, lflag))
944 return(-1);
945 /* Path is optional */
946 if (get_pathname(&cp, path1))
947 return(-1);
948 break;
949 case I_LLS:
950 case I_SHELL:
951 /* Uses the rest of the line */
952 break;
953 case I_LUMASK:
954 base = 8;
955 case I_CHMOD:
956 base = 8;
957 case I_CHOWN:
958 case I_CHGRP:
959 /* Get numeric arg (mandatory) */
960 l = strtol(cp, &cp2, base);
961 if (cp2 == cp || ((l == LONG_MIN || l == LONG_MAX) &&
962 errno == ERANGE) || l < 0) {
963 error("You must supply a numeric argument "
964 "to the %s command.", cmd);
965 return(-1);
967 cp = cp2;
968 *n_arg = l;
969 if (cmdnum == I_LUMASK && strchr(WHITESPACE, *cp))
970 break;
971 if (cmdnum == I_LUMASK || !strchr(WHITESPACE, *cp)) {
972 error("You must supply a numeric argument "
973 "to the %s command.", cmd);
974 return(-1);
976 cp += strspn(cp, WHITESPACE);
978 /* Get pathname (mandatory) */
979 if (get_pathname(&cp, path1))
980 return(-1);
981 if (*path1 == NULL) {
982 error("You must specify a path after a %s command.",
983 cmd);
984 return(-1);
986 break;
987 case I_QUIT:
988 case I_PWD:
989 case I_LPWD:
990 case I_HELP:
991 case I_VERSION:
992 case I_PROGRESS:
993 break;
994 default:
995 fatal("Command not implemented");
998 *cpp = cp;
999 return(cmdnum);
1002 static int
1003 parse_dispatch_command(struct sftp_conn *conn, const char *cmd, char **pwd,
1004 int err_abort)
1006 char *path1, *path2, *tmp;
1007 int pflag, lflag, iflag, cmdnum, i;
1008 unsigned long n_arg;
1009 Attrib a, *aa;
1010 char path_buf[MAXPATHLEN];
1011 int err = 0;
1012 glob_t g;
1014 path1 = path2 = NULL;
1015 cmdnum = parse_args(&cmd, &pflag, &lflag, &iflag, &n_arg,
1016 &path1, &path2);
1018 if (iflag != 0)
1019 err_abort = 0;
1021 memset(&g, 0, sizeof(g));
1023 /* Perform command */
1024 switch (cmdnum) {
1025 case 0:
1026 /* Blank line */
1027 break;
1028 case -1:
1029 /* Unrecognized command */
1030 err = -1;
1031 break;
1032 case I_GET:
1033 err = process_get(conn, path1, path2, *pwd, pflag);
1034 break;
1035 case I_PUT:
1036 err = process_put(conn, path1, path2, *pwd, pflag);
1037 break;
1038 case I_RENAME:
1039 path1 = make_absolute(path1, *pwd);
1040 path2 = make_absolute(path2, *pwd);
1041 err = do_rename(conn, path1, path2);
1042 break;
1043 case I_SYMLINK:
1044 path2 = make_absolute(path2, *pwd);
1045 err = do_symlink(conn, path1, path2);
1046 break;
1047 case I_RM:
1048 path1 = make_absolute(path1, *pwd);
1049 remote_glob(conn, path1, GLOB_NOCHECK, NULL, &g);
1050 for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
1051 printf("Removing %s\n", g.gl_pathv[i]);
1052 err = do_rm(conn, g.gl_pathv[i]);
1053 if (err != 0 && err_abort)
1054 break;
1056 break;
1057 case I_MKDIR:
1058 path1 = make_absolute(path1, *pwd);
1059 attrib_clear(&a);
1060 a.flags |= SSH2_FILEXFER_ATTR_PERMISSIONS;
1061 a.perm = 0777;
1062 err = do_mkdir(conn, path1, &a);
1063 break;
1064 case I_RMDIR:
1065 path1 = make_absolute(path1, *pwd);
1066 err = do_rmdir(conn, path1);
1067 break;
1068 case I_CHDIR:
1069 path1 = make_absolute(path1, *pwd);
1070 if ((tmp = do_realpath(conn, path1)) == NULL) {
1071 err = 1;
1072 break;
1074 if ((aa = do_stat(conn, tmp, 0)) == NULL) {
1075 xfree(tmp);
1076 err = 1;
1077 break;
1079 if (!(aa->flags & SSH2_FILEXFER_ATTR_PERMISSIONS)) {
1080 error("Can't change directory: Can't check target");
1081 xfree(tmp);
1082 err = 1;
1083 break;
1085 if (!S_ISDIR(aa->perm)) {
1086 error("Can't change directory: \"%s\" is not "
1087 "a directory", tmp);
1088 xfree(tmp);
1089 err = 1;
1090 break;
1092 xfree(*pwd);
1093 *pwd = tmp;
1094 break;
1095 case I_LS:
1096 if (!path1) {
1097 do_globbed_ls(conn, *pwd, *pwd, lflag);
1098 break;
1101 /* Strip pwd off beginning of non-absolute paths */
1102 tmp = NULL;
1103 if (*path1 != '/')
1104 tmp = *pwd;
1106 path1 = make_absolute(path1, *pwd);
1107 err = do_globbed_ls(conn, path1, tmp, lflag);
1108 break;
1109 case I_LCHDIR:
1110 if (chdir(path1) == -1) {
1111 error("Couldn't change local directory to "
1112 "\"%s\": %s", path1, strerror(errno));
1113 err = 1;
1115 break;
1116 case I_LMKDIR:
1117 if (mkdir(path1, 0777) == -1) {
1118 error("Couldn't create local directory "
1119 "\"%s\": %s", path1, strerror(errno));
1120 err = 1;
1122 break;
1123 case I_LLS:
1124 local_do_ls(cmd);
1125 break;
1126 case I_SHELL:
1127 local_do_shell(cmd);
1128 break;
1129 case I_LUMASK:
1130 umask(n_arg);
1131 printf("Local umask: %03lo\n", n_arg);
1132 break;
1133 case I_CHMOD:
1134 path1 = make_absolute(path1, *pwd);
1135 attrib_clear(&a);
1136 a.flags |= SSH2_FILEXFER_ATTR_PERMISSIONS;
1137 a.perm = n_arg;
1138 remote_glob(conn, path1, GLOB_NOCHECK, NULL, &g);
1139 for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
1140 printf("Changing mode on %s\n", g.gl_pathv[i]);
1141 err = do_setstat(conn, g.gl_pathv[i], &a);
1142 if (err != 0 && err_abort)
1143 break;
1145 break;
1146 case I_CHOWN:
1147 case I_CHGRP:
1148 path1 = make_absolute(path1, *pwd);
1149 remote_glob(conn, path1, GLOB_NOCHECK, NULL, &g);
1150 for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
1151 if (!(aa = do_stat(conn, g.gl_pathv[i], 0))) {
1152 if (err != 0 && err_abort)
1153 break;
1154 else
1155 continue;
1157 if (!(aa->flags & SSH2_FILEXFER_ATTR_UIDGID)) {
1158 error("Can't get current ownership of "
1159 "remote file \"%s\"", g.gl_pathv[i]);
1160 if (err != 0 && err_abort)
1161 break;
1162 else
1163 continue;
1165 aa->flags &= SSH2_FILEXFER_ATTR_UIDGID;
1166 if (cmdnum == I_CHOWN) {
1167 printf("Changing owner on %s\n", g.gl_pathv[i]);
1168 aa->uid = n_arg;
1169 } else {
1170 printf("Changing group on %s\n", g.gl_pathv[i]);
1171 aa->gid = n_arg;
1173 err = do_setstat(conn, g.gl_pathv[i], aa);
1174 if (err != 0 && err_abort)
1175 break;
1177 break;
1178 case I_PWD:
1179 printf("Remote working directory: %s\n", *pwd);
1180 break;
1181 case I_LPWD:
1182 if (!getcwd(path_buf, sizeof(path_buf))) {
1183 error("Couldn't get local cwd: %s", strerror(errno));
1184 err = -1;
1185 break;
1187 printf("Local working directory: %s\n", path_buf);
1188 break;
1189 case I_QUIT:
1190 /* Processed below */
1191 break;
1192 case I_HELP:
1193 help();
1194 break;
1195 case I_VERSION:
1196 printf("SFTP protocol version %u\n", sftp_proto_version(conn));
1197 break;
1198 case I_PROGRESS:
1199 showprogress = !showprogress;
1200 if (showprogress)
1201 printf("Progress meter enabled\n");
1202 else
1203 printf("Progress meter disabled\n");
1204 break;
1205 default:
1206 fatal("%d is not implemented", cmdnum);
1209 if (g.gl_pathc)
1210 globfree(&g);
1211 if (path1)
1212 xfree(path1);
1213 if (path2)
1214 xfree(path2);
1216 /* If an unignored error occurs in batch mode we should abort. */
1217 if (err_abort && err != 0)
1218 return (-1);
1219 else if (cmdnum == I_QUIT)
1220 return (1);
1222 return (0);
1225 #ifdef USE_LIBEDIT
1226 static char *
1227 prompt(EditLine *el)
1229 return ("sftp> ");
1231 #endif
1234 interactive_loop(int fd_in, int fd_out, char *file1, char *file2)
1236 char *pwd;
1237 char *dir = NULL;
1238 char cmd[2048];
1239 struct sftp_conn *conn;
1240 int err, interactive;
1241 EditLine *el = NULL;
1242 #ifdef USE_LIBEDIT
1243 History *hl = NULL;
1244 HistEvent hev;
1245 extern char *__progname;
1247 if (!batchmode && isatty(STDIN_FILENO)) {
1248 if ((el = el_init(__progname, stdin, stdout, stderr)) == NULL)
1249 fatal("Couldn't initialise editline");
1250 if ((hl = history_init()) == NULL)
1251 fatal("Couldn't initialise editline history");
1252 history(hl, &hev, H_SETSIZE, 100);
1253 el_set(el, EL_HIST, history, hl);
1255 el_set(el, EL_PROMPT, prompt);
1256 el_set(el, EL_EDITOR, "emacs");
1257 el_set(el, EL_TERMINAL, NULL);
1258 el_set(el, EL_SIGNAL, 1);
1259 el_source(el, NULL);
1261 #endif /* USE_LIBEDIT */
1263 conn = do_init(fd_in, fd_out, copy_buffer_len, num_requests);
1264 if (conn == NULL)
1265 fatal("Couldn't initialise connection to server");
1267 pwd = do_realpath(conn, ".");
1268 if (pwd == NULL)
1269 fatal("Need cwd");
1271 if (file1 != NULL) {
1272 dir = xstrdup(file1);
1273 dir = make_absolute(dir, pwd);
1275 if (remote_is_dir(conn, dir) && file2 == NULL) {
1276 printf("Changing to: %s\n", dir);
1277 snprintf(cmd, sizeof cmd, "cd \"%s\"", dir);
1278 if (parse_dispatch_command(conn, cmd, &pwd, 1) != 0) {
1279 xfree(dir);
1280 xfree(pwd);
1281 return (-1);
1283 } else {
1284 if (file2 == NULL)
1285 snprintf(cmd, sizeof cmd, "get %s", dir);
1286 else
1287 snprintf(cmd, sizeof cmd, "get %s %s", dir,
1288 file2);
1290 err = parse_dispatch_command(conn, cmd, &pwd, 1);
1291 xfree(dir);
1292 xfree(pwd);
1293 return (err);
1295 xfree(dir);
1298 #if defined(HAVE_SETVBUF) && !defined(BROKEN_SETVBUF)
1299 setvbuf(stdout, NULL, _IOLBF, 0);
1300 setvbuf(infile, NULL, _IOLBF, 0);
1301 #else
1302 setlinebuf(stdout);
1303 setlinebuf(infile);
1304 #endif
1306 interactive = !batchmode && isatty(STDIN_FILENO);
1307 err = 0;
1308 for (;;) {
1309 char *cp;
1311 signal(SIGINT, SIG_IGN);
1313 if (el == NULL) {
1314 if (interactive)
1315 printf("sftp> ");
1316 if (fgets(cmd, sizeof(cmd), infile) == NULL) {
1317 if (interactive)
1318 printf("\n");
1319 break;
1321 if (!interactive) { /* Echo command */
1322 printf("sftp> %s", cmd);
1323 if (strlen(cmd) > 0 &&
1324 cmd[strlen(cmd) - 1] != '\n')
1325 printf("\n");
1327 } else {
1328 #ifdef USE_LIBEDIT
1329 const char *line;
1330 int count = 0;
1332 if ((line = el_gets(el, &count)) == NULL || count <= 0) {
1333 printf("\n");
1334 break;
1336 history(hl, &hev, H_ENTER, line);
1337 if (strlcpy(cmd, line, sizeof(cmd)) >= sizeof(cmd)) {
1338 fprintf(stderr, "Error: input line too long\n");
1339 continue;
1341 #endif /* USE_LIBEDIT */
1344 cp = strrchr(cmd, '\n');
1345 if (cp)
1346 *cp = '\0';
1348 /* Handle user interrupts gracefully during commands */
1349 interrupted = 0;
1350 signal(SIGINT, cmd_interrupt);
1352 err = parse_dispatch_command(conn, cmd, &pwd, batchmode);
1353 if (err != 0)
1354 break;
1356 xfree(pwd);
1358 #ifdef USE_LIBEDIT
1359 if (el != NULL)
1360 el_end(el);
1361 #endif /* USE_LIBEDIT */
1363 /* err == 1 signifies normal "quit" exit */
1364 return (err >= 0 ? 0 : -1);
1367 static void
1368 connect_to_server(char *path, char **args, int *in, int *out)
1370 int c_in, c_out;
1372 #ifdef USE_PIPES
1373 int pin[2], pout[2];
1375 if ((pipe(pin) == -1) || (pipe(pout) == -1))
1376 fatal("pipe: %s", strerror(errno));
1377 *in = pin[0];
1378 *out = pout[1];
1379 c_in = pout[0];
1380 c_out = pin[1];
1381 #else /* USE_PIPES */
1382 int inout[2];
1384 if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) == -1)
1385 fatal("socketpair: %s", strerror(errno));
1386 *in = *out = inout[0];
1387 c_in = c_out = inout[1];
1388 #endif /* USE_PIPES */
1390 if ((sshpid = fork()) == -1)
1391 fatal("fork: %s", strerror(errno));
1392 else if (sshpid == 0) {
1393 if ((dup2(c_in, STDIN_FILENO) == -1) ||
1394 (dup2(c_out, STDOUT_FILENO) == -1)) {
1395 fprintf(stderr, "dup2: %s\n", strerror(errno));
1396 _exit(1);
1398 close(*in);
1399 close(*out);
1400 close(c_in);
1401 close(c_out);
1404 * The underlying ssh is in the same process group, so we must
1405 * ignore SIGINT if we want to gracefully abort commands,
1406 * otherwise the signal will make it to the ssh process and
1407 * kill it too
1409 signal(SIGINT, SIG_IGN);
1410 execvp(path, args);
1411 fprintf(stderr, "exec: %s: %s\n", path, strerror(errno));
1412 _exit(1);
1415 signal(SIGTERM, killchild);
1416 signal(SIGINT, killchild);
1417 signal(SIGHUP, killchild);
1418 close(c_in);
1419 close(c_out);
1422 static void
1423 usage(void)
1425 extern char *__progname;
1427 fprintf(stderr,
1428 "usage: %s [-1Cv] [-B buffer_size] [-b batchfile] [-F ssh_config]\n"
1429 " [-o ssh_option] [-P sftp_server_path] [-R num_requests]\n"
1430 " [-S program] [-s subsystem | sftp_server] host\n"
1431 " %s [[user@]host[:file [file]]]\n"
1432 " %s [[user@]host[:dir[/]]]\n"
1433 " %s -b batchfile [user@]host\n", __progname, __progname, __progname, __progname);
1434 exit(1);
1438 main(int argc, char **argv)
1440 int in, out, ch, err;
1441 char *host, *userhost, *cp, *file2 = NULL;
1442 int debug_level = 0, sshver = 2;
1443 char *file1 = NULL, *sftp_server = NULL;
1444 char *ssh_program = _PATH_SSH_PROGRAM, *sftp_direct = NULL;
1445 LogLevel ll = SYSLOG_LEVEL_INFO;
1446 arglist args;
1447 extern int optind;
1448 extern char *optarg;
1450 __progname = ssh_get_progname(argv[0]);
1451 args.list = NULL;
1452 addargs(&args, "ssh"); /* overwritten with ssh_program */
1453 addargs(&args, "-oForwardX11 no");
1454 addargs(&args, "-oForwardAgent no");
1455 addargs(&args, "-oClearAllForwardings yes");
1457 ll = SYSLOG_LEVEL_INFO;
1458 infile = stdin;
1460 while ((ch = getopt(argc, argv, "1hvCo:s:S:b:B:F:P:R:")) != -1) {
1461 switch (ch) {
1462 case 'C':
1463 addargs(&args, "-C");
1464 break;
1465 case 'v':
1466 if (debug_level < 3) {
1467 addargs(&args, "-v");
1468 ll = SYSLOG_LEVEL_DEBUG1 + debug_level;
1470 debug_level++;
1471 break;
1472 case 'F':
1473 case 'o':
1474 addargs(&args, "-%c%s", ch, optarg);
1475 break;
1476 case '1':
1477 sshver = 1;
1478 if (sftp_server == NULL)
1479 sftp_server = _PATH_SFTP_SERVER;
1480 break;
1481 case 's':
1482 sftp_server = optarg;
1483 break;
1484 case 'S':
1485 ssh_program = optarg;
1486 break;
1487 case 'b':
1488 if (batchmode)
1489 fatal("Batch file already specified.");
1491 /* Allow "-" as stdin */
1492 if (strcmp(optarg, "-") != 0 &&
1493 (infile = fopen(optarg, "r")) == NULL)
1494 fatal("%s (%s).", strerror(errno), optarg);
1495 showprogress = 0;
1496 batchmode = 1;
1497 addargs(&args, "-obatchmode yes");
1498 break;
1499 case 'P':
1500 sftp_direct = optarg;
1501 break;
1502 case 'B':
1503 copy_buffer_len = strtol(optarg, &cp, 10);
1504 if (copy_buffer_len == 0 || *cp != '\0')
1505 fatal("Invalid buffer size \"%s\"", optarg);
1506 break;
1507 case 'R':
1508 num_requests = strtol(optarg, &cp, 10);
1509 if (num_requests == 0 || *cp != '\0')
1510 fatal("Invalid number of requests \"%s\"",
1511 optarg);
1512 break;
1513 case 'h':
1514 default:
1515 usage();
1519 if (!isatty(STDERR_FILENO))
1520 showprogress = 0;
1522 log_init(argv[0], ll, SYSLOG_FACILITY_USER, 1);
1524 if (sftp_direct == NULL) {
1525 if (optind == argc || argc > (optind + 2))
1526 usage();
1528 userhost = xstrdup(argv[optind]);
1529 file2 = argv[optind+1];
1531 if ((host = strrchr(userhost, '@')) == NULL)
1532 host = userhost;
1533 else {
1534 *host++ = '\0';
1535 if (!userhost[0]) {
1536 fprintf(stderr, "Missing username\n");
1537 usage();
1539 addargs(&args, "-l%s",userhost);
1542 if ((cp = colon(host)) != NULL) {
1543 *cp++ = '\0';
1544 file1 = cp;
1547 host = cleanhostname(host);
1548 if (!*host) {
1549 fprintf(stderr, "Missing hostname\n");
1550 usage();
1553 addargs(&args, "-oProtocol %d", sshver);
1555 /* no subsystem if the server-spec contains a '/' */
1556 if (sftp_server == NULL || strchr(sftp_server, '/') == NULL)
1557 addargs(&args, "-s");
1559 addargs(&args, "%s", host);
1560 addargs(&args, "%s", (sftp_server != NULL ?
1561 sftp_server : "sftp"));
1562 args.list[0] = ssh_program;
1564 if (!batchmode)
1565 fprintf(stderr, "Connecting to %s...\n", host);
1566 connect_to_server(ssh_program, args.list, &in, &out);
1567 } else {
1568 args.list = NULL;
1569 addargs(&args, "sftp-server");
1571 if (!batchmode)
1572 fprintf(stderr, "Attaching to %s...\n", sftp_direct);
1573 connect_to_server(sftp_direct, args.list, &in, &out);
1576 err = interactive_loop(in, out, file1, file2);
1578 #if !defined(USE_PIPES)
1579 shutdown(in, SHUT_RDWR);
1580 shutdown(out, SHUT_RDWR);
1581 #endif
1583 close(in);
1584 close(out);
1585 if (batchmode)
1586 fclose(infile);
1588 while (waitpid(sshpid, NULL, 0) == -1)
1589 if (errno != EINTR)
1590 fatal("Couldn't wait for ssh process: %s",
1591 strerror(errno));
1593 exit(err == 0 ? 0 : 1);