1 /* $OpenBSD: sftp.c,v 1.98 2007/12/12 05:04:03 djm Exp $ */
3 * Copyright (c) 2001-2004 Damien Miller <djm@openbsd.org>
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.
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.
20 #include <sys/types.h>
21 #include <sys/ioctl.h>
22 #ifdef HAVE_SYS_STAT_H
23 # include <sys/stat.h>
25 #include <sys/param.h>
26 #include <sys/socket.h>
38 typedef void EditLine;
49 #include "pathnames.h"
54 #include "sftp-common.h"
55 #include "sftp-client.h"
57 /* File to read commands from */
60 /* Are we in batchfile mode? */
63 /* Size of buffer used when copying files */
64 size_t copy_buffer_len = 32768;
66 /* Number of concurrent outstanding requests */
67 size_t num_requests = 16;
69 /* PID of ssh transport process */
70 static pid_t sshpid = -1;
72 /* This is set to 0 if the progressmeter is not desired. */
75 /* SIGINT received during command processing */
76 volatile sig_atomic_t interrupted = 0;
78 /* I wish qsort() took a separate ctx for the comparison function...*/
81 int remote_glob(struct sftp_conn *, const char *, int,
82 int (*)(const char *, int), glob_t *); /* proto for sftp-glob.c */
84 extern char *__progname;
86 /* Separators for interactive commands */
87 #define WHITESPACE " \t\r\n"
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 */
97 #define LS_SHOW_ALL 0x80 /* Don't skip filenames starting with '.' */
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)
102 /* Commands for interactive mode */
125 #define I_PROGRESS 23
132 static const struct CMD cmds[] = {
135 { "chdir", I_CHDIR },
136 { "chgrp", I_CHGRP },
137 { "chmod", I_CHMOD },
138 { "chown", I_CHOWN },
145 { "lchdir", I_LCHDIR },
147 { "lmkdir", I_LMKDIR },
151 { "lumask", I_LUMASK },
152 { "mkdir", I_MKDIR },
153 { "progress", I_PROGRESS },
158 { "rename", I_RENAME },
160 { "rmdir", I_RMDIR },
161 { "symlink", I_SYMLINK },
162 { "version", I_VERSION },
168 int interactive_loop(int fd_in, int fd_out, char *file1, char *file2);
175 kill(sshpid, SIGTERM);
176 waitpid(sshpid, NULL, 0);
184 cmd_interrupt(int signo)
186 const char msg[] = "\rInterrupt \n";
187 int olderrno = errno;
189 write(STDERR_FILENO, msg, sizeof(msg) - 1);
197 printf("Available commands:\n");
198 printf("cd path Change remote directory to 'path'\n");
199 printf("lcd path Change local directory to 'path'\n");
200 printf("chgrp grp path Change group of file 'path' to 'grp'\n");
201 printf("chmod mode path Change permissions of file 'path' to 'mode'\n");
202 printf("chown own path Change owner of file 'path' to 'own'\n");
203 printf("help Display this help text\n");
204 printf("get remote-path [local-path] Download file\n");
205 printf("lls [ls-options [path]] Display local directory listing\n");
206 printf("ln oldpath newpath Symlink remote file\n");
207 printf("lmkdir path Create local directory\n");
208 printf("lpwd Print local working directory\n");
209 printf("ls [path] Display remote directory listing\n");
210 printf("lumask umask Set local umask to 'umask'\n");
211 printf("mkdir path Create remote directory\n");
212 printf("progress Toggle display of progress meter\n");
213 printf("put local-path [remote-path] Upload file\n");
214 printf("pwd Display remote working directory\n");
215 printf("exit Quit sftp\n");
216 printf("quit Quit sftp\n");
217 printf("rename oldpath newpath Rename remote file\n");
218 printf("rmdir path Remove remote directory\n");
219 printf("rm path Delete remote file\n");
220 printf("symlink oldpath newpath Symlink remote file\n");
221 printf("version Show SFTP version\n");
222 printf("!command Execute 'command' in local shell\n");
223 printf("! Escape to local shell\n");
224 printf("? Synonym for help\n");
228 local_do_shell(const char *args)
237 if ((shell = getenv("SHELL")) == NULL)
238 shell = _PATH_BSHELL;
240 if ((pid = fork()) == -1)
241 fatal("Couldn't fork: %s", strerror(errno));
244 /* XXX: child has pipe fds to ssh subproc open - issue? */
246 debug3("Executing %s -c \"%s\"", shell, args);
247 execl(shell, shell, "-c", args, (char *)NULL);
249 debug3("Executing %s", shell);
250 execl(shell, shell, (char *)NULL);
252 fprintf(stderr, "Couldn't execute \"%s\": %s\n", shell,
256 while (waitpid(pid, &status, 0) == -1)
258 fatal("Couldn't wait for child: %s", strerror(errno));
259 if (!WIFEXITED(status))
260 error("Shell exited abnormally");
261 else if (WEXITSTATUS(status))
262 error("Shell exited with status %d", WEXITSTATUS(status));
266 local_do_ls(const char *args)
269 local_do_shell(_PATH_LS);
271 int len = strlen(_PATH_LS " ") + strlen(args) + 1;
272 char *buf = xmalloc(len);
274 /* XXX: quoting - rip quoting code from ftp? */
275 snprintf(buf, len, _PATH_LS " %s", args);
281 /* Strip one path (usually the pwd) from the start of another */
283 path_strip(char *path, char *strip)
288 return (xstrdup(path));
291 if (strncmp(path, strip, len) == 0) {
292 if (strip[len - 1] != '/' && path[len] == '/')
294 return (xstrdup(path + len));
297 return (xstrdup(path));
301 path_append(char *p1, char *p2)
304 size_t len = strlen(p1) + strlen(p2) + 2;
307 strlcpy(ret, p1, len);
308 if (p1[0] != '\0' && p1[strlen(p1) - 1] != '/')
309 strlcat(ret, "/", len);
310 strlcat(ret, p2, len);
316 make_absolute(char *p, char *pwd)
321 if (p && p[0] != '/') {
322 abs_str = path_append(pwd, p);
330 infer_path(const char *p, char **ifp)
334 cp = strrchr(p, '/');
341 error("Invalid path");
345 *ifp = xstrdup(cp + 1);
350 parse_getput_flags(const char *cmd, char **argv, int argc, int *pflag)
352 extern int optind, optreset, opterr;
355 optind = optreset = 1;
359 while ((ch = getopt(argc, argv, "Pp")) != -1) {
366 error("%s: Invalid flag -%c", cmd, ch);
375 parse_ls_flags(char **argv, int argc, int *lflag)
377 extern int optind, optreset, opterr;
380 optind = optreset = 1;
383 *lflag = LS_NAME_SORT;
384 while ((ch = getopt(argc, argv, "1Saflnrt")) != -1) {
387 *lflag &= ~VIEW_FLAGS;
388 *lflag |= LS_SHORT_VIEW;
391 *lflag &= ~SORT_FLAGS;
392 *lflag |= LS_SIZE_SORT;
395 *lflag |= LS_SHOW_ALL;
398 *lflag &= ~SORT_FLAGS;
401 *lflag &= ~VIEW_FLAGS;
402 *lflag |= LS_LONG_VIEW;
405 *lflag &= ~VIEW_FLAGS;
406 *lflag |= LS_NUMERIC_VIEW|LS_LONG_VIEW;
409 *lflag |= LS_REVERSE_SORT;
412 *lflag &= ~SORT_FLAGS;
413 *lflag |= LS_TIME_SORT;
416 error("ls: Invalid flag -%c", ch);
429 /* XXX: report errors? */
430 if (stat(path, &sb) == -1)
433 return(S_ISDIR(sb.st_mode));
441 if (stat(path, &sb) == -1)
442 fatal("stat %s: %s", path, strerror(errno));
444 return(S_ISREG(sb.st_mode));
448 remote_is_dir(struct sftp_conn *conn, char *path)
452 /* XXX: report errors? */
453 if ((a = do_stat(conn, path, 1)) == NULL)
455 if (!(a->flags & SSH2_FILEXFER_ATTR_PERMISSIONS))
457 return(S_ISDIR(a->perm));
461 process_get(struct sftp_conn *conn, char *src, char *dst, char *pwd, int pflag)
463 char *abs_src = NULL;
464 char *abs_dst = NULL;
470 abs_src = xstrdup(src);
471 abs_src = make_absolute(abs_src, pwd);
473 memset(&g, 0, sizeof(g));
474 debug3("Looking up %s", abs_src);
475 if (remote_glob(conn, abs_src, 0, NULL, &g)) {
476 error("File \"%s\" not found.", abs_src);
481 /* If multiple matches, dst must be a directory or unspecified */
482 if (g.gl_matchc > 1 && dst && !is_dir(dst)) {
483 error("Multiple files match, but \"%s\" is not a directory",
489 for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
490 if (infer_path(g.gl_pathv[i], &tmp)) {
495 if (g.gl_matchc == 1 && dst) {
496 /* If directory specified, append filename */
499 if (infer_path(g.gl_pathv[0], &tmp)) {
503 abs_dst = path_append(dst, tmp);
506 abs_dst = xstrdup(dst);
508 abs_dst = path_append(dst, tmp);
513 printf("Fetching %s to %s\n", g.gl_pathv[i], abs_dst);
514 if (do_download(conn, g.gl_pathv[i], abs_dst, pflag) == -1)
527 process_put(struct sftp_conn *conn, char *src, char *dst, char *pwd, int pflag)
529 char *tmp_dst = NULL;
530 char *abs_dst = NULL;
537 tmp_dst = xstrdup(dst);
538 tmp_dst = make_absolute(tmp_dst, pwd);
541 memset(&g, 0, sizeof(g));
542 debug3("Looking up %s", src);
543 if (glob(src, 0, NULL, &g)) {
544 error("File \"%s\" not found.", src);
549 /* If multiple matches, dst may be directory or unspecified */
550 if (g.gl_matchc > 1 && tmp_dst && !remote_is_dir(conn, tmp_dst)) {
551 error("Multiple files match, but \"%s\" is not a directory",
557 for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
558 if (!is_reg(g.gl_pathv[i])) {
559 error("skipping non-regular file %s",
563 if (infer_path(g.gl_pathv[i], &tmp)) {
568 if (g.gl_matchc == 1 && tmp_dst) {
569 /* If directory specified, append filename */
570 if (remote_is_dir(conn, tmp_dst)) {
571 if (infer_path(g.gl_pathv[0], &tmp)) {
575 abs_dst = path_append(tmp_dst, tmp);
578 abs_dst = xstrdup(tmp_dst);
580 } else if (tmp_dst) {
581 abs_dst = path_append(tmp_dst, tmp);
584 abs_dst = make_absolute(tmp, pwd);
586 printf("Uploading %s to %s\n", g.gl_pathv[i], abs_dst);
587 if (do_upload(conn, g.gl_pathv[i], abs_dst, pflag) == -1)
601 sdirent_comp(const void *aa, const void *bb)
603 SFTP_DIRENT *a = *(SFTP_DIRENT **)aa;
604 SFTP_DIRENT *b = *(SFTP_DIRENT **)bb;
605 int rmul = sort_flag & LS_REVERSE_SORT ? -1 : 1;
607 #define NCMP(a,b) (a == b ? 0 : (a < b ? 1 : -1))
608 if (sort_flag & LS_NAME_SORT)
609 return (rmul * strcmp(a->filename, b->filename));
610 else if (sort_flag & LS_TIME_SORT)
611 return (rmul * NCMP(a->a.mtime, b->a.mtime));
612 else if (sort_flag & LS_SIZE_SORT)
613 return (rmul * NCMP(a->a.size, b->a.size));
615 fatal("Unknown ls sort type");
618 /* sftp ls.1 replacement for directories */
620 do_ls_dir(struct sftp_conn *conn, char *path, char *strip_path, int lflag)
623 u_int c = 1, colspace = 0, columns = 1;
626 if ((n = do_readdir(conn, path, &d)) != 0)
629 if (!(lflag & LS_SHORT_VIEW)) {
630 u_int m = 0, width = 80;
634 /* Count entries for sort and find longest filename */
635 for (n = 0; d[n] != NULL; n++) {
636 if (d[n]->filename[0] != '.' || (lflag & LS_SHOW_ALL))
637 m = MAX(m, strlen(d[n]->filename));
640 /* Add any subpath that also needs to be counted */
641 tmp = path_strip(path, strip_path);
645 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) != -1)
648 columns = width / (m + 2);
649 columns = MAX(columns, 1);
650 colspace = width / columns;
651 colspace = MIN(colspace, width);
654 if (lflag & SORT_FLAGS) {
655 for (n = 0; d[n] != NULL; n++)
656 ; /* count entries */
657 sort_flag = lflag & (SORT_FLAGS|LS_REVERSE_SORT);
658 qsort(d, n, sizeof(*d), sdirent_comp);
661 for (n = 0; d[n] != NULL && !interrupted; n++) {
664 if (d[n]->filename[0] == '.' && !(lflag & LS_SHOW_ALL))
667 tmp = path_append(path, d[n]->filename);
668 fname = path_strip(tmp, strip_path);
671 if (lflag & LS_LONG_VIEW) {
672 if (lflag & LS_NUMERIC_VIEW) {
676 memset(&sb, 0, sizeof(sb));
677 attrib_to_stat(&d[n]->a, &sb);
678 lname = ls_file(fname, &sb, 1);
679 printf("%s\n", lname);
682 printf("%s\n", d[n]->longname);
684 printf("%-*s", colspace, fname);
695 if (!(lflag & LS_LONG_VIEW) && (c != 1))
698 free_sftp_dirents(d);
702 /* sftp ls.1 replacement which handles path globs */
704 do_globbed_ls(struct sftp_conn *conn, char *path, char *strip_path,
708 u_int i, c = 1, colspace = 0, columns = 1;
711 memset(&g, 0, sizeof(g));
713 if (remote_glob(conn, path, GLOB_MARK|GLOB_NOCHECK|GLOB_BRACE,
714 NULL, &g) || (g.gl_pathc && !g.gl_matchc)) {
717 error("Can't ls: \"%s\" not found", path);
725 * If the glob returns a single match and it is a directory,
726 * then just list its contents.
728 if (g.gl_matchc == 1) {
729 if ((a = do_lstat(conn, g.gl_pathv[0], 1)) == NULL) {
733 if ((a->flags & SSH2_FILEXFER_ATTR_PERMISSIONS) &&
737 err = do_ls_dir(conn, g.gl_pathv[0], strip_path, lflag);
743 if (!(lflag & LS_SHORT_VIEW)) {
744 u_int m = 0, width = 80;
747 /* Count entries for sort and find longest filename */
748 for (i = 0; g.gl_pathv[i]; i++)
749 m = MAX(m, strlen(g.gl_pathv[i]));
751 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) != -1)
754 columns = width / (m + 2);
755 columns = MAX(columns, 1);
756 colspace = width / columns;
759 for (i = 0; g.gl_pathv[i] && !interrupted; i++, a = NULL) {
762 fname = path_strip(g.gl_pathv[i], strip_path);
764 if (lflag & LS_LONG_VIEW) {
769 * XXX: this is slow - 1 roundtrip per path
770 * A solution to this is to fork glob() and
771 * build a sftp specific version which keeps the
772 * attribs (which currently get thrown away)
773 * that the server returns as well as the filenames.
775 memset(&sb, 0, sizeof(sb));
777 a = do_lstat(conn, g.gl_pathv[i], 1);
779 attrib_to_stat(a, &sb);
780 lname = ls_file(fname, &sb, 1);
781 printf("%s\n", lname);
784 printf("%-*s", colspace, fname);
794 if (!(lflag & LS_LONG_VIEW) && (c != 1))
805 * Undo escaping of glob sequences in place. Used to undo extra escaping
806 * applied in makeargv() when the string is destined for a function that
810 undo_glob_escape(char *s)
845 * Split a string into an argument vector using sh(1)-style quoting,
846 * comment and escaping rules, but with some tweaks to handle glob(3)
848 * Returns NULL on error or a NULL-terminated array of arguments.
851 #define MAXARGLEN 8192
853 makeargv(const char *arg, int *argcp)
857 static char argvs[MAXARGLEN];
858 static char *argv[MAXARGS + 1];
859 enum { MA_START, MA_SQUOTE, MA_DQUOTE, MA_UNQUOTED } state, q;
862 if (strlen(arg) > sizeof(argvs) - 1) {
864 error("string too long");
870 if (isspace(arg[i])) {
871 if (state == MA_UNQUOTED) {
872 /* Terminate current argument */
876 } else if (state != MA_START)
878 } else if (arg[i] == '"' || arg[i] == '\'') {
879 q = arg[i] == '"' ? MA_DQUOTE : MA_SQUOTE;
880 if (state == MA_START) {
881 argv[argc] = argvs + j;
883 } else if (state == MA_UNQUOTED)
889 } else if (arg[i] == '\\') {
890 if (state == MA_SQUOTE || state == MA_DQUOTE) {
891 quot = state == MA_SQUOTE ? '\'' : '"';
892 /* Unescape quote we are in */
893 /* XXX support \n and friends? */
894 if (arg[i + 1] == quot) {
897 } else if (arg[i + 1] == '?' ||
898 arg[i + 1] == '[' || arg[i + 1] == '*') {
900 * Special case for sftp: append
901 * double-escaped glob sequence -
902 * glob will undo one level of
903 * escaping. NB. string can grow here.
905 if (j >= sizeof(argvs) - 5)
908 argvs[j++] = arg[i++];
912 argvs[j++] = arg[i++];
916 if (state == MA_START) {
917 argv[argc] = argvs + j;
920 if (arg[i + 1] == '?' || arg[i + 1] == '[' ||
921 arg[i + 1] == '*' || arg[i + 1] == '\\') {
923 * Special case for sftp: append
924 * escaped glob sequence -
925 * glob will undo one level of
928 argvs[j++] = arg[i++];
931 /* Unescape everything */
932 /* XXX support \n and friends? */
937 } else if (arg[i] == '#') {
938 if (state == MA_SQUOTE || state == MA_DQUOTE)
942 } else if (arg[i] == '\0') {
943 if (state == MA_SQUOTE || state == MA_DQUOTE) {
944 error("Unterminated quoted argument");
948 if (state == MA_UNQUOTED) {
954 if (state == MA_START) {
955 argv[argc] = argvs + j;
958 if ((state == MA_SQUOTE || state == MA_DQUOTE) &&
959 (arg[i] == '?' || arg[i] == '[' || arg[i] == '*')) {
961 * Special case for sftp: escape quoted
962 * glob(3) wildcards. NB. string can grow
965 if (j >= sizeof(argvs) - 3)
979 parse_args(const char **cpp, int *pflag, int *lflag, int *iflag,
980 unsigned long *n_arg, char **path1, char **path2)
982 const char *cmd, *cp = *cpp;
986 int i, cmdnum, optidx, argc;
988 /* Skip leading whitespace */
989 cp = cp + strspn(cp, WHITESPACE);
991 /* Ignore blank lines and lines which begin with comment '#' char */
992 if (*cp == '\0' || *cp == '#')
995 /* Check for leading '-' (disable error processing) */
1002 if ((argv = makeargv(cp, &argc)) == NULL)
1005 /* Figure out which command we have */
1006 for (i = 0; cmds[i].c != NULL; i++) {
1007 if (strcasecmp(cmds[i].c, argv[0]) == 0)
1017 } else if (cmdnum == -1) {
1018 error("Invalid command.");
1022 /* Get arguments and parse flags */
1023 *lflag = *pflag = *n_arg = 0;
1024 *path1 = *path2 = NULL;
1029 if ((optidx = parse_getput_flags(cmd, argv, argc, pflag)) == -1)
1031 /* Get first pathname (mandatory) */
1032 if (argc - optidx < 1) {
1033 error("You must specify at least one path after a "
1034 "%s command.", cmd);
1037 *path1 = xstrdup(argv[optidx]);
1038 /* Get second pathname (optional) */
1039 if (argc - optidx > 1) {
1040 *path2 = xstrdup(argv[optidx + 1]);
1041 /* Destination is not globbed */
1042 undo_glob_escape(*path2);
1047 if (argc - optidx < 2) {
1048 error("You must specify two paths after a %s "
1052 *path1 = xstrdup(argv[optidx]);
1053 *path2 = xstrdup(argv[optidx + 1]);
1054 /* Paths are not globbed */
1055 undo_glob_escape(*path1);
1056 undo_glob_escape(*path2);
1064 /* Get pathname (mandatory) */
1065 if (argc - optidx < 1) {
1066 error("You must specify a path after a %s command.",
1070 *path1 = xstrdup(argv[optidx]);
1071 /* Only "rm" globs */
1073 undo_glob_escape(*path1);
1076 if ((optidx = parse_ls_flags(argv, argc, lflag)) == -1)
1078 /* Path is optional */
1079 if (argc - optidx > 0)
1080 *path1 = xstrdup(argv[optidx]);
1083 /* Skip ls command and following whitespace */
1084 cp = cp + strlen(cmd) + strspn(cp, WHITESPACE);
1086 /* Uses the rest of the line */
1093 /* Get numeric arg (mandatory) */
1094 if (argc - optidx < 1)
1097 l = strtol(argv[optidx], &cp2, base);
1098 if (cp2 == argv[optidx] || *cp2 != '\0' ||
1099 ((l == LONG_MIN || l == LONG_MAX) && errno == ERANGE) ||
1102 error("You must supply a numeric argument "
1103 "to the %s command.", cmd);
1107 if (cmdnum == I_LUMASK)
1109 /* Get pathname (mandatory) */
1110 if (argc - optidx < 2) {
1111 error("You must specify a path after a %s command.",
1115 *path1 = xstrdup(argv[optidx + 1]);
1125 fatal("Command not implemented");
1133 parse_dispatch_command(struct sftp_conn *conn, const char *cmd, char **pwd,
1136 char *path1, *path2, *tmp;
1137 int pflag, lflag, iflag, cmdnum, i;
1138 unsigned long n_arg;
1140 char path_buf[MAXPATHLEN];
1144 path1 = path2 = NULL;
1145 cmdnum = parse_args(&cmd, &pflag, &lflag, &iflag, &n_arg,
1151 memset(&g, 0, sizeof(g));
1153 /* Perform command */
1159 /* Unrecognized command */
1163 err = process_get(conn, path1, path2, *pwd, pflag);
1166 err = process_put(conn, path1, path2, *pwd, pflag);
1169 path1 = make_absolute(path1, *pwd);
1170 path2 = make_absolute(path2, *pwd);
1171 err = do_rename(conn, path1, path2);
1174 path2 = make_absolute(path2, *pwd);
1175 err = do_symlink(conn, path1, path2);
1178 path1 = make_absolute(path1, *pwd);
1179 remote_glob(conn, path1, GLOB_NOCHECK, NULL, &g);
1180 for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
1181 printf("Removing %s\n", g.gl_pathv[i]);
1182 err = do_rm(conn, g.gl_pathv[i]);
1183 if (err != 0 && err_abort)
1188 path1 = make_absolute(path1, *pwd);
1190 a.flags |= SSH2_FILEXFER_ATTR_PERMISSIONS;
1192 err = do_mkdir(conn, path1, &a);
1195 path1 = make_absolute(path1, *pwd);
1196 err = do_rmdir(conn, path1);
1199 path1 = make_absolute(path1, *pwd);
1200 if ((tmp = do_realpath(conn, path1)) == NULL) {
1204 if ((aa = do_stat(conn, tmp, 0)) == NULL) {
1209 if (!(aa->flags & SSH2_FILEXFER_ATTR_PERMISSIONS)) {
1210 error("Can't change directory: Can't check target");
1215 if (!S_ISDIR(aa->perm)) {
1216 error("Can't change directory: \"%s\" is not "
1217 "a directory", tmp);
1227 do_globbed_ls(conn, *pwd, *pwd, lflag);
1231 /* Strip pwd off beginning of non-absolute paths */
1236 path1 = make_absolute(path1, *pwd);
1237 err = do_globbed_ls(conn, path1, tmp, lflag);
1240 if (chdir(path1) == -1) {
1241 error("Couldn't change local directory to "
1242 "\"%s\": %s", path1, strerror(errno));
1247 if (mkdir(path1, 0777) == -1) {
1248 error("Couldn't create local directory "
1249 "\"%s\": %s", path1, strerror(errno));
1257 local_do_shell(cmd);
1261 printf("Local umask: %03lo\n", n_arg);
1264 path1 = make_absolute(path1, *pwd);
1266 a.flags |= SSH2_FILEXFER_ATTR_PERMISSIONS;
1268 remote_glob(conn, path1, GLOB_NOCHECK, NULL, &g);
1269 for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
1270 printf("Changing mode on %s\n", g.gl_pathv[i]);
1271 err = do_setstat(conn, g.gl_pathv[i], &a);
1272 if (err != 0 && err_abort)
1278 path1 = make_absolute(path1, *pwd);
1279 remote_glob(conn, path1, GLOB_NOCHECK, NULL, &g);
1280 for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
1281 if (!(aa = do_stat(conn, g.gl_pathv[i], 0))) {
1282 if (err != 0 && err_abort)
1287 if (!(aa->flags & SSH2_FILEXFER_ATTR_UIDGID)) {
1288 error("Can't get current ownership of "
1289 "remote file \"%s\"", g.gl_pathv[i]);
1290 if (err != 0 && err_abort)
1295 aa->flags &= SSH2_FILEXFER_ATTR_UIDGID;
1296 if (cmdnum == I_CHOWN) {
1297 printf("Changing owner on %s\n", g.gl_pathv[i]);
1300 printf("Changing group on %s\n", g.gl_pathv[i]);
1303 err = do_setstat(conn, g.gl_pathv[i], aa);
1304 if (err != 0 && err_abort)
1309 printf("Remote working directory: %s\n", *pwd);
1312 if (!getcwd(path_buf, sizeof(path_buf))) {
1313 error("Couldn't get local cwd: %s", strerror(errno));
1317 printf("Local working directory: %s\n", path_buf);
1320 /* Processed below */
1326 printf("SFTP protocol version %u\n", sftp_proto_version(conn));
1329 showprogress = !showprogress;
1331 printf("Progress meter enabled\n");
1333 printf("Progress meter disabled\n");
1336 fatal("%d is not implemented", cmdnum);
1346 /* If an unignored error occurs in batch mode we should abort. */
1347 if (err_abort && err != 0)
1349 else if (cmdnum == I_QUIT)
1357 prompt(EditLine *el)
1364 interactive_loop(int fd_in, int fd_out, char *file1, char *file2)
1369 struct sftp_conn *conn;
1370 int err, interactive;
1371 EditLine *el = NULL;
1375 extern char *__progname;
1377 if (!batchmode && isatty(STDIN_FILENO)) {
1378 if ((el = el_init(__progname, stdin, stdout, stderr)) == NULL)
1379 fatal("Couldn't initialise editline");
1380 if ((hl = history_init()) == NULL)
1381 fatal("Couldn't initialise editline history");
1382 history(hl, &hev, H_SETSIZE, 100);
1383 el_set(el, EL_HIST, history, hl);
1385 el_set(el, EL_PROMPT, prompt);
1386 el_set(el, EL_EDITOR, "emacs");
1387 el_set(el, EL_TERMINAL, NULL);
1388 el_set(el, EL_SIGNAL, 1);
1389 el_source(el, NULL);
1391 #endif /* USE_LIBEDIT */
1393 conn = do_init(fd_in, fd_out, copy_buffer_len, num_requests);
1395 fatal("Couldn't initialise connection to server");
1397 pwd = do_realpath(conn, ".");
1401 if (file1 != NULL) {
1402 dir = xstrdup(file1);
1403 dir = make_absolute(dir, pwd);
1405 if (remote_is_dir(conn, dir) && file2 == NULL) {
1406 printf("Changing to: %s\n", dir);
1407 snprintf(cmd, sizeof cmd, "cd \"%s\"", dir);
1408 if (parse_dispatch_command(conn, cmd, &pwd, 1) != 0) {
1416 snprintf(cmd, sizeof cmd, "get %s", dir);
1418 snprintf(cmd, sizeof cmd, "get %s %s", dir,
1421 err = parse_dispatch_command(conn, cmd, &pwd, 1);
1430 #if defined(HAVE_SETVBUF) && !defined(BROKEN_SETVBUF)
1431 setvbuf(stdout, NULL, _IOLBF, 0);
1432 setvbuf(infile, NULL, _IOLBF, 0);
1438 interactive = !batchmode && isatty(STDIN_FILENO);
1443 signal(SIGINT, SIG_IGN);
1448 if (fgets(cmd, sizeof(cmd), infile) == NULL) {
1453 if (!interactive) { /* Echo command */
1454 printf("sftp> %s", cmd);
1455 if (strlen(cmd) > 0 &&
1456 cmd[strlen(cmd) - 1] != '\n')
1464 if ((line = el_gets(el, &count)) == NULL || count <= 0) {
1468 history(hl, &hev, H_ENTER, line);
1469 if (strlcpy(cmd, line, sizeof(cmd)) >= sizeof(cmd)) {
1470 fprintf(stderr, "Error: input line too long\n");
1473 #endif /* USE_LIBEDIT */
1476 cp = strrchr(cmd, '\n');
1480 /* Handle user interrupts gracefully during commands */
1482 signal(SIGINT, cmd_interrupt);
1484 err = parse_dispatch_command(conn, cmd, &pwd, batchmode);
1494 #endif /* USE_LIBEDIT */
1496 /* err == 1 signifies normal "quit" exit */
1497 return (err >= 0 ? 0 : -1);
1501 connect_to_server(char *path, char **args, int *in, int *out)
1506 int pin[2], pout[2];
1508 if ((pipe(pin) == -1) || (pipe(pout) == -1))
1509 fatal("pipe: %s", strerror(errno));
1514 #else /* USE_PIPES */
1517 if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) == -1)
1518 fatal("socketpair: %s", strerror(errno));
1519 *in = *out = inout[0];
1520 c_in = c_out = inout[1];
1521 #endif /* USE_PIPES */
1523 if ((sshpid = fork()) == -1)
1524 fatal("fork: %s", strerror(errno));
1525 else if (sshpid == 0) {
1526 if ((dup2(c_in, STDIN_FILENO) == -1) ||
1527 (dup2(c_out, STDOUT_FILENO) == -1)) {
1528 fprintf(stderr, "dup2: %s\n", strerror(errno));
1537 * The underlying ssh is in the same process group, so we must
1538 * ignore SIGINT if we want to gracefully abort commands,
1539 * otherwise the signal will make it to the ssh process and
1542 signal(SIGINT, SIG_IGN);
1544 fprintf(stderr, "exec: %s: %s\n", path, strerror(errno));
1548 signal(SIGTERM, killchild);
1549 signal(SIGINT, killchild);
1550 signal(SIGHUP, killchild);
1558 extern char *__progname;
1561 "usage: %s [-1Cv] [-B buffer_size] [-b batchfile] [-F ssh_config]\n"
1562 " [-o ssh_option] [-P sftp_server_path] [-R num_requests]\n"
1563 " [-S program] [-s subsystem | sftp_server] host\n"
1564 " %s [[user@]host[:file [file]]]\n"
1565 " %s [[user@]host[:dir[/]]]\n"
1566 " %s -b batchfile [user@]host\n", __progname, __progname, __progname, __progname);
1571 main(int argc, char **argv)
1573 int in, out, ch, err;
1574 char *host, *userhost, *cp, *file2 = NULL;
1575 int debug_level = 0, sshver = 2;
1576 char *file1 = NULL, *sftp_server = NULL;
1577 char *ssh_program = _PATH_SSH_PROGRAM, *sftp_direct = NULL;
1578 LogLevel ll = SYSLOG_LEVEL_INFO;
1581 extern char *optarg;
1583 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
1586 __progname = ssh_get_progname(argv[0]);
1587 memset(&args, '\0', sizeof(args));
1589 addargs(&args, "%s", ssh_program);
1590 addargs(&args, "-oForwardX11 no");
1591 addargs(&args, "-oForwardAgent no");
1592 addargs(&args, "-oPermitLocalCommand no");
1593 addargs(&args, "-oClearAllForwardings yes");
1595 ll = SYSLOG_LEVEL_INFO;
1598 while ((ch = getopt(argc, argv, "1hvCo:s:S:b:B:F:P:R:")) != -1) {
1601 addargs(&args, "-C");
1604 if (debug_level < 3) {
1605 addargs(&args, "-v");
1606 ll = SYSLOG_LEVEL_DEBUG1 + debug_level;
1612 addargs(&args, "-%c%s", ch, optarg);
1616 if (sftp_server == NULL)
1617 sftp_server = _PATH_SFTP_SERVER;
1620 sftp_server = optarg;
1623 ssh_program = optarg;
1624 replacearg(&args, 0, "%s", ssh_program);
1628 fatal("Batch file already specified.");
1630 /* Allow "-" as stdin */
1631 if (strcmp(optarg, "-") != 0 &&
1632 (infile = fopen(optarg, "r")) == NULL)
1633 fatal("%s (%s).", strerror(errno), optarg);
1636 addargs(&args, "-obatchmode yes");
1639 sftp_direct = optarg;
1642 copy_buffer_len = strtol(optarg, &cp, 10);
1643 if (copy_buffer_len == 0 || *cp != '\0')
1644 fatal("Invalid buffer size \"%s\"", optarg);
1647 num_requests = strtol(optarg, &cp, 10);
1648 if (num_requests == 0 || *cp != '\0')
1649 fatal("Invalid number of requests \"%s\"",
1658 if (!isatty(STDERR_FILENO))
1661 log_init(argv[0], ll, SYSLOG_FACILITY_USER, 1);
1663 if (sftp_direct == NULL) {
1664 if (optind == argc || argc > (optind + 2))
1667 userhost = xstrdup(argv[optind]);
1668 file2 = argv[optind+1];
1670 if ((host = strrchr(userhost, '@')) == NULL)
1675 fprintf(stderr, "Missing username\n");
1678 addargs(&args, "-l%s", userhost);
1681 if ((cp = colon(host)) != NULL) {
1686 host = cleanhostname(host);
1688 fprintf(stderr, "Missing hostname\n");
1692 addargs(&args, "-oProtocol %d", sshver);
1694 /* no subsystem if the server-spec contains a '/' */
1695 if (sftp_server == NULL || strchr(sftp_server, '/') == NULL)
1696 addargs(&args, "-s");
1698 addargs(&args, "%s", host);
1699 addargs(&args, "%s", (sftp_server != NULL ?
1700 sftp_server : "sftp"));
1703 fprintf(stderr, "Connecting to %s...\n", host);
1704 connect_to_server(ssh_program, args.list, &in, &out);
1707 addargs(&args, "sftp-server");
1710 fprintf(stderr, "Attaching to %s...\n", sftp_direct);
1711 connect_to_server(sftp_direct, args.list, &in, &out);
1715 err = interactive_loop(in, out, file1, file2);
1717 #if !defined(USE_PIPES)
1718 shutdown(in, SHUT_RDWR);
1719 shutdown(out, SHUT_RDWR);
1727 while (waitpid(sshpid, NULL, 0) == -1)
1729 fatal("Couldn't wait for ssh process: %s",
1732 exit(err == 0 ? 0 : 1);