1 /* $OpenBSD: sftp.c,v 1.100 2008/04/18 12:32:11 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>
28 #include <sys/statvfs.h>
39 typedef void EditLine;
58 #include "pathnames.h"
63 #include "sftp-common.h"
64 #include "sftp-client.h"
66 /* File to read commands from */
69 /* Are we in batchfile mode? */
72 /* Size of buffer used when copying files */
73 size_t copy_buffer_len = 32768;
75 /* Number of concurrent outstanding requests */
76 size_t num_requests = 16;
78 /* PID of ssh transport process */
79 static pid_t sshpid = -1;
81 /* This is set to 0 if the progressmeter is not desired. */
84 /* SIGINT received during command processing */
85 volatile sig_atomic_t interrupted = 0;
87 /* I wish qsort() took a separate ctx for the comparison function...*/
90 int remote_glob(struct sftp_conn *, const char *, int,
91 int (*)(const char *, int), glob_t *); /* proto for sftp-glob.c */
93 extern char *__progname;
95 /* Separators for interactive commands */
96 #define WHITESPACE " \t\r\n"
99 #define LS_LONG_VIEW 0x01 /* Full view ala ls -l */
100 #define LS_SHORT_VIEW 0x02 /* Single row view ala ls -1 */
101 #define LS_NUMERIC_VIEW 0x04 /* Long view with numeric uid/gid */
102 #define LS_NAME_SORT 0x08 /* Sort by name (default) */
103 #define LS_TIME_SORT 0x10 /* Sort by mtime */
104 #define LS_SIZE_SORT 0x20 /* Sort by file size */
105 #define LS_REVERSE_SORT 0x40 /* Reverse sort order */
106 #define LS_SHOW_ALL 0x80 /* Don't skip filenames starting with '.' */
108 #define VIEW_FLAGS (LS_LONG_VIEW|LS_SHORT_VIEW|LS_NUMERIC_VIEW)
109 #define SORT_FLAGS (LS_NAME_SORT|LS_TIME_SORT|LS_SIZE_SORT)
111 /* Commands for interactive mode */
135 #define I_PROGRESS 23
142 static const struct CMD cmds[] = {
145 { "chdir", I_CHDIR },
146 { "chgrp", I_CHGRP },
147 { "chmod", I_CHMOD },
148 { "chown", I_CHOWN },
156 { "lchdir", I_LCHDIR },
158 { "lmkdir", I_LMKDIR },
162 { "lumask", I_LUMASK },
163 { "mkdir", I_MKDIR },
164 { "progress", I_PROGRESS },
169 { "rename", I_RENAME },
171 { "rmdir", I_RMDIR },
172 { "symlink", I_SYMLINK },
173 { "version", I_VERSION },
179 int interactive_loop(int fd_in, int fd_out, char *file1, char *file2);
186 kill(sshpid, SIGTERM);
187 waitpid(sshpid, NULL, 0);
195 cmd_interrupt(int signo)
197 const char msg[] = "\rInterrupt \n";
198 int olderrno = errno;
200 write(STDERR_FILENO, msg, sizeof(msg) - 1);
208 printf("Available commands:\n");
209 printf("cd path Change remote directory to 'path'\n");
210 printf("lcd path Change local directory to 'path'\n");
211 printf("chgrp grp path Change group of file 'path' to 'grp'\n");
212 printf("chmod mode path Change permissions of file 'path' to 'mode'\n");
213 printf("chown own path Change owner of file 'path' to 'own'\n");
214 printf("df [path] Display statistics for current directory or\n");
215 printf(" filesystem containing 'path'\n");
216 printf("help Display this help text\n");
217 printf("get remote-path [local-path] Download file\n");
218 printf("lls [ls-options [path]] Display local directory listing\n");
219 printf("ln oldpath newpath Symlink remote file\n");
220 printf("lmkdir path Create local directory\n");
221 printf("lpwd Print local working directory\n");
222 printf("ls [path] Display remote directory listing\n");
223 printf("lumask umask Set local umask to 'umask'\n");
224 printf("mkdir path Create remote directory\n");
225 printf("progress Toggle display of progress meter\n");
226 printf("put local-path [remote-path] Upload file\n");
227 printf("pwd Display remote working directory\n");
228 printf("exit Quit sftp\n");
229 printf("quit Quit sftp\n");
230 printf("rename oldpath newpath Rename remote file\n");
231 printf("rmdir path Remove remote directory\n");
232 printf("rm path Delete remote file\n");
233 printf("symlink oldpath newpath Symlink remote file\n");
234 printf("version Show SFTP version\n");
235 printf("!command Execute 'command' in local shell\n");
236 printf("! Escape to local shell\n");
237 printf("? Synonym for help\n");
241 local_do_shell(const char *args)
250 if ((shell = getenv("SHELL")) == NULL)
251 shell = _PATH_BSHELL;
253 if ((pid = fork()) == -1)
254 fatal("Couldn't fork: %s", strerror(errno));
257 /* XXX: child has pipe fds to ssh subproc open - issue? */
259 debug3("Executing %s -c \"%s\"", shell, args);
260 execl(shell, shell, "-c", args, (char *)NULL);
262 debug3("Executing %s", shell);
263 execl(shell, shell, (char *)NULL);
265 fprintf(stderr, "Couldn't execute \"%s\": %s\n", shell,
269 while (waitpid(pid, &status, 0) == -1)
271 fatal("Couldn't wait for child: %s", strerror(errno));
272 if (!WIFEXITED(status))
273 error("Shell exited abnormally");
274 else if (WEXITSTATUS(status))
275 error("Shell exited with status %d", WEXITSTATUS(status));
279 local_do_ls(const char *args)
282 local_do_shell(_PATH_LS);
284 int len = strlen(_PATH_LS " ") + strlen(args) + 1;
285 char *buf = xmalloc(len);
287 /* XXX: quoting - rip quoting code from ftp? */
288 snprintf(buf, len, _PATH_LS " %s", args);
294 /* Strip one path (usually the pwd) from the start of another */
296 path_strip(char *path, char *strip)
301 return (xstrdup(path));
304 if (strncmp(path, strip, len) == 0) {
305 if (strip[len - 1] != '/' && path[len] == '/')
307 return (xstrdup(path + len));
310 return (xstrdup(path));
314 path_append(char *p1, char *p2)
317 size_t len = strlen(p1) + strlen(p2) + 2;
320 strlcpy(ret, p1, len);
321 if (p1[0] != '\0' && p1[strlen(p1) - 1] != '/')
322 strlcat(ret, "/", len);
323 strlcat(ret, p2, len);
329 make_absolute(char *p, char *pwd)
334 if (p && p[0] != '/') {
335 abs_str = path_append(pwd, p);
343 infer_path(const char *p, char **ifp)
347 cp = strrchr(p, '/');
354 error("Invalid path");
358 *ifp = xstrdup(cp + 1);
363 parse_getput_flags(const char *cmd, char **argv, int argc, int *pflag)
365 extern int optind, optreset, opterr;
368 optind = optreset = 1;
372 while ((ch = getopt(argc, argv, "Pp")) != -1) {
379 error("%s: Invalid flag -%c", cmd, ch);
388 parse_ls_flags(char **argv, int argc, int *lflag)
390 extern int optind, optreset, opterr;
393 optind = optreset = 1;
396 *lflag = LS_NAME_SORT;
397 while ((ch = getopt(argc, argv, "1Saflnrt")) != -1) {
400 *lflag &= ~VIEW_FLAGS;
401 *lflag |= LS_SHORT_VIEW;
404 *lflag &= ~SORT_FLAGS;
405 *lflag |= LS_SIZE_SORT;
408 *lflag |= LS_SHOW_ALL;
411 *lflag &= ~SORT_FLAGS;
414 *lflag &= ~VIEW_FLAGS;
415 *lflag |= LS_LONG_VIEW;
418 *lflag &= ~VIEW_FLAGS;
419 *lflag |= LS_NUMERIC_VIEW|LS_LONG_VIEW;
422 *lflag |= LS_REVERSE_SORT;
425 *lflag &= ~SORT_FLAGS;
426 *lflag |= LS_TIME_SORT;
429 error("ls: Invalid flag -%c", ch);
438 parse_df_flags(const char *cmd, char **argv, int argc, int *hflag, int *iflag)
440 extern int optind, optreset, opterr;
443 optind = optreset = 1;
447 while ((ch = getopt(argc, argv, "hi")) != -1) {
456 error("%s: Invalid flag -%c", cmd, ch);
469 /* XXX: report errors? */
470 if (stat(path, &sb) == -1)
473 return(S_ISDIR(sb.st_mode));
477 remote_is_dir(struct sftp_conn *conn, char *path)
481 /* XXX: report errors? */
482 if ((a = do_stat(conn, path, 1)) == NULL)
484 if (!(a->flags & SSH2_FILEXFER_ATTR_PERMISSIONS))
486 return(S_ISDIR(a->perm));
490 process_get(struct sftp_conn *conn, char *src, char *dst, char *pwd, int pflag)
492 char *abs_src = NULL;
493 char *abs_dst = NULL;
499 abs_src = xstrdup(src);
500 abs_src = make_absolute(abs_src, pwd);
502 memset(&g, 0, sizeof(g));
503 debug3("Looking up %s", abs_src);
504 if (remote_glob(conn, abs_src, 0, NULL, &g)) {
505 error("File \"%s\" not found.", abs_src);
510 /* If multiple matches, dst must be a directory or unspecified */
511 if (g.gl_matchc > 1 && dst && !is_dir(dst)) {
512 error("Multiple files match, but \"%s\" is not a directory",
518 for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
519 if (infer_path(g.gl_pathv[i], &tmp)) {
524 if (g.gl_matchc == 1 && dst) {
525 /* If directory specified, append filename */
528 if (infer_path(g.gl_pathv[0], &tmp)) {
532 abs_dst = path_append(dst, tmp);
535 abs_dst = xstrdup(dst);
537 abs_dst = path_append(dst, tmp);
542 printf("Fetching %s to %s\n", g.gl_pathv[i], abs_dst);
543 if (do_download(conn, g.gl_pathv[i], abs_dst, pflag) == -1)
556 process_put(struct sftp_conn *conn, char *src, char *dst, char *pwd, int pflag)
558 char *tmp_dst = NULL;
559 char *abs_dst = NULL;
567 tmp_dst = xstrdup(dst);
568 tmp_dst = make_absolute(tmp_dst, pwd);
571 memset(&g, 0, sizeof(g));
572 debug3("Looking up %s", src);
573 if (glob(src, GLOB_NOCHECK, NULL, &g)) {
574 error("File \"%s\" not found.", src);
579 /* If multiple matches, dst may be directory or unspecified */
580 if (g.gl_matchc > 1 && tmp_dst && !remote_is_dir(conn, tmp_dst)) {
581 error("Multiple files match, but \"%s\" is not a directory",
587 for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
588 if (stat(g.gl_pathv[i], &sb) == -1) {
590 error("stat %s: %s", g.gl_pathv[i], strerror(errno));
594 if (!S_ISREG(sb.st_mode)) {
595 error("skipping non-regular file %s",
599 if (infer_path(g.gl_pathv[i], &tmp)) {
604 if (g.gl_matchc == 1 && tmp_dst) {
605 /* If directory specified, append filename */
606 if (remote_is_dir(conn, tmp_dst)) {
607 if (infer_path(g.gl_pathv[0], &tmp)) {
611 abs_dst = path_append(tmp_dst, tmp);
614 abs_dst = xstrdup(tmp_dst);
616 } else if (tmp_dst) {
617 abs_dst = path_append(tmp_dst, tmp);
620 abs_dst = make_absolute(tmp, pwd);
622 printf("Uploading %s to %s\n", g.gl_pathv[i], abs_dst);
623 if (do_upload(conn, g.gl_pathv[i], abs_dst, pflag) == -1)
637 sdirent_comp(const void *aa, const void *bb)
639 SFTP_DIRENT *a = *(SFTP_DIRENT **)aa;
640 SFTP_DIRENT *b = *(SFTP_DIRENT **)bb;
641 int rmul = sort_flag & LS_REVERSE_SORT ? -1 : 1;
643 #define NCMP(a,b) (a == b ? 0 : (a < b ? 1 : -1))
644 if (sort_flag & LS_NAME_SORT)
645 return (rmul * strcmp(a->filename, b->filename));
646 else if (sort_flag & LS_TIME_SORT)
647 return (rmul * NCMP(a->a.mtime, b->a.mtime));
648 else if (sort_flag & LS_SIZE_SORT)
649 return (rmul * NCMP(a->a.size, b->a.size));
651 fatal("Unknown ls sort type");
654 /* sftp ls.1 replacement for directories */
656 do_ls_dir(struct sftp_conn *conn, char *path, char *strip_path, int lflag)
659 u_int c = 1, colspace = 0, columns = 1;
662 if ((n = do_readdir(conn, path, &d)) != 0)
665 if (!(lflag & LS_SHORT_VIEW)) {
666 u_int m = 0, width = 80;
670 /* Count entries for sort and find longest filename */
671 for (n = 0; d[n] != NULL; n++) {
672 if (d[n]->filename[0] != '.' || (lflag & LS_SHOW_ALL))
673 m = MAX(m, strlen(d[n]->filename));
676 /* Add any subpath that also needs to be counted */
677 tmp = path_strip(path, strip_path);
681 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) != -1)
684 columns = width / (m + 2);
685 columns = MAX(columns, 1);
686 colspace = width / columns;
687 colspace = MIN(colspace, width);
690 if (lflag & SORT_FLAGS) {
691 for (n = 0; d[n] != NULL; n++)
692 ; /* count entries */
693 sort_flag = lflag & (SORT_FLAGS|LS_REVERSE_SORT);
694 qsort(d, n, sizeof(*d), sdirent_comp);
697 for (n = 0; d[n] != NULL && !interrupted; n++) {
700 if (d[n]->filename[0] == '.' && !(lflag & LS_SHOW_ALL))
703 tmp = path_append(path, d[n]->filename);
704 fname = path_strip(tmp, strip_path);
707 if (lflag & LS_LONG_VIEW) {
708 if (lflag & LS_NUMERIC_VIEW) {
712 memset(&sb, 0, sizeof(sb));
713 attrib_to_stat(&d[n]->a, &sb);
714 lname = ls_file(fname, &sb, 1);
715 printf("%s\n", lname);
718 printf("%s\n", d[n]->longname);
720 printf("%-*s", colspace, fname);
731 if (!(lflag & LS_LONG_VIEW) && (c != 1))
734 free_sftp_dirents(d);
738 /* sftp ls.1 replacement which handles path globs */
740 do_globbed_ls(struct sftp_conn *conn, char *path, char *strip_path,
744 u_int i, c = 1, colspace = 0, columns = 1;
747 memset(&g, 0, sizeof(g));
749 if (remote_glob(conn, path, GLOB_MARK|GLOB_NOCHECK|GLOB_BRACE,
750 NULL, &g) || (g.gl_pathc && !g.gl_matchc)) {
753 error("Can't ls: \"%s\" not found", path);
761 * If the glob returns a single match and it is a directory,
762 * then just list its contents.
764 if (g.gl_matchc == 1) {
765 if ((a = do_lstat(conn, g.gl_pathv[0], 1)) == NULL) {
769 if ((a->flags & SSH2_FILEXFER_ATTR_PERMISSIONS) &&
773 err = do_ls_dir(conn, g.gl_pathv[0], strip_path, lflag);
779 if (!(lflag & LS_SHORT_VIEW)) {
780 u_int m = 0, width = 80;
783 /* Count entries for sort and find longest filename */
784 for (i = 0; g.gl_pathv[i]; i++)
785 m = MAX(m, strlen(g.gl_pathv[i]));
787 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) != -1)
790 columns = width / (m + 2);
791 columns = MAX(columns, 1);
792 colspace = width / columns;
795 for (i = 0; g.gl_pathv[i] && !interrupted; i++, a = NULL) {
798 fname = path_strip(g.gl_pathv[i], strip_path);
800 if (lflag & LS_LONG_VIEW) {
805 * XXX: this is slow - 1 roundtrip per path
806 * A solution to this is to fork glob() and
807 * build a sftp specific version which keeps the
808 * attribs (which currently get thrown away)
809 * that the server returns as well as the filenames.
811 memset(&sb, 0, sizeof(sb));
813 a = do_lstat(conn, g.gl_pathv[i], 1);
815 attrib_to_stat(a, &sb);
816 lname = ls_file(fname, &sb, 1);
817 printf("%s\n", lname);
820 printf("%-*s", colspace, fname);
830 if (!(lflag & LS_LONG_VIEW) && (c != 1))
841 do_df(struct sftp_conn *conn, char *path, int hflag, int iflag)
844 char s_used[FMT_SCALED_STRSIZE];
845 char s_avail[FMT_SCALED_STRSIZE];
846 char s_root[FMT_SCALED_STRSIZE];
847 char s_total[FMT_SCALED_STRSIZE];
849 if (do_statvfs(conn, path, &st, 1) == -1)
852 printf(" Inodes Used Avail "
853 "(root) %%Capacity\n");
854 printf("%11llu %11llu %11llu %11llu %3llu%%\n",
855 (unsigned long long)st.f_files,
856 (unsigned long long)(st.f_files - st.f_ffree),
857 (unsigned long long)st.f_favail,
858 (unsigned long long)st.f_ffree,
859 (unsigned long long)(100 * (st.f_files - st.f_ffree) /
862 strlcpy(s_used, "error", sizeof(s_used));
863 strlcpy(s_avail, "error", sizeof(s_avail));
864 strlcpy(s_root, "error", sizeof(s_root));
865 strlcpy(s_total, "error", sizeof(s_total));
866 fmt_scaled((st.f_blocks - st.f_bfree) * st.f_frsize, s_used);
867 fmt_scaled(st.f_bavail * st.f_frsize, s_avail);
868 fmt_scaled(st.f_bfree * st.f_frsize, s_root);
869 fmt_scaled(st.f_blocks * st.f_frsize, s_total);
870 printf(" Size Used Avail (root) %%Capacity\n");
871 printf("%7sB %7sB %7sB %7sB %3llu%%\n",
872 s_total, s_used, s_avail, s_root,
873 (unsigned long long)(100 * (st.f_blocks - st.f_bfree) /
876 printf(" Size Used Avail "
877 "(root) %%Capacity\n");
878 printf("%12llu %12llu %12llu %12llu %3llu%%\n",
879 (unsigned long long)(st.f_frsize * st.f_blocks / 1024),
880 (unsigned long long)(st.f_frsize *
881 (st.f_blocks - st.f_bfree) / 1024),
882 (unsigned long long)(st.f_frsize * st.f_bavail / 1024),
883 (unsigned long long)(st.f_frsize * st.f_bfree / 1024),
884 (unsigned long long)(100 * (st.f_blocks - st.f_bfree) /
891 * Undo escaping of glob sequences in place. Used to undo extra escaping
892 * applied in makeargv() when the string is destined for a function that
896 undo_glob_escape(char *s)
931 * Split a string into an argument vector using sh(1)-style quoting,
932 * comment and escaping rules, but with some tweaks to handle glob(3)
934 * Returns NULL on error or a NULL-terminated array of arguments.
937 #define MAXARGLEN 8192
939 makeargv(const char *arg, int *argcp)
943 static char argvs[MAXARGLEN];
944 static char *argv[MAXARGS + 1];
945 enum { MA_START, MA_SQUOTE, MA_DQUOTE, MA_UNQUOTED } state, q;
948 if (strlen(arg) > sizeof(argvs) - 1) {
950 error("string too long");
956 if (isspace(arg[i])) {
957 if (state == MA_UNQUOTED) {
958 /* Terminate current argument */
962 } else if (state != MA_START)
964 } else if (arg[i] == '"' || arg[i] == '\'') {
965 q = arg[i] == '"' ? MA_DQUOTE : MA_SQUOTE;
966 if (state == MA_START) {
967 argv[argc] = argvs + j;
969 } else if (state == MA_UNQUOTED)
975 } else if (arg[i] == '\\') {
976 if (state == MA_SQUOTE || state == MA_DQUOTE) {
977 quot = state == MA_SQUOTE ? '\'' : '"';
978 /* Unescape quote we are in */
979 /* XXX support \n and friends? */
980 if (arg[i + 1] == quot) {
983 } else if (arg[i + 1] == '?' ||
984 arg[i + 1] == '[' || arg[i + 1] == '*') {
986 * Special case for sftp: append
987 * double-escaped glob sequence -
988 * glob will undo one level of
989 * escaping. NB. string can grow here.
991 if (j >= sizeof(argvs) - 5)
994 argvs[j++] = arg[i++];
998 argvs[j++] = arg[i++];
1002 if (state == MA_START) {
1003 argv[argc] = argvs + j;
1004 state = MA_UNQUOTED;
1006 if (arg[i + 1] == '?' || arg[i + 1] == '[' ||
1007 arg[i + 1] == '*' || arg[i + 1] == '\\') {
1009 * Special case for sftp: append
1010 * escaped glob sequence -
1011 * glob will undo one level of
1014 argvs[j++] = arg[i++];
1015 argvs[j++] = arg[i];
1017 /* Unescape everything */
1018 /* XXX support \n and friends? */
1020 argvs[j++] = arg[i];
1023 } else if (arg[i] == '#') {
1024 if (state == MA_SQUOTE || state == MA_DQUOTE)
1025 argvs[j++] = arg[i];
1028 } else if (arg[i] == '\0') {
1029 if (state == MA_SQUOTE || state == MA_DQUOTE) {
1030 error("Unterminated quoted argument");
1034 if (state == MA_UNQUOTED) {
1040 if (state == MA_START) {
1041 argv[argc] = argvs + j;
1042 state = MA_UNQUOTED;
1044 if ((state == MA_SQUOTE || state == MA_DQUOTE) &&
1045 (arg[i] == '?' || arg[i] == '[' || arg[i] == '*')) {
1047 * Special case for sftp: escape quoted
1048 * glob(3) wildcards. NB. string can grow
1051 if (j >= sizeof(argvs) - 3)
1052 goto args_too_longs;
1054 argvs[j++] = arg[i];
1056 argvs[j++] = arg[i];
1065 parse_args(const char **cpp, int *pflag, int *lflag, int *iflag, int *hflag,
1066 unsigned long *n_arg, char **path1, char **path2)
1068 const char *cmd, *cp = *cpp;
1072 int i, cmdnum, optidx, argc;
1074 /* Skip leading whitespace */
1075 cp = cp + strspn(cp, WHITESPACE);
1077 /* Ignore blank lines and lines which begin with comment '#' char */
1078 if (*cp == '\0' || *cp == '#')
1081 /* Check for leading '-' (disable error processing) */
1088 if ((argv = makeargv(cp, &argc)) == NULL)
1091 /* Figure out which command we have */
1092 for (i = 0; cmds[i].c != NULL; i++) {
1093 if (strcasecmp(cmds[i].c, argv[0]) == 0)
1103 } else if (cmdnum == -1) {
1104 error("Invalid command.");
1108 /* Get arguments and parse flags */
1109 *lflag = *pflag = *hflag = *n_arg = 0;
1110 *path1 = *path2 = NULL;
1115 if ((optidx = parse_getput_flags(cmd, argv, argc, pflag)) == -1)
1117 /* Get first pathname (mandatory) */
1118 if (argc - optidx < 1) {
1119 error("You must specify at least one path after a "
1120 "%s command.", cmd);
1123 *path1 = xstrdup(argv[optidx]);
1124 /* Get second pathname (optional) */
1125 if (argc - optidx > 1) {
1126 *path2 = xstrdup(argv[optidx + 1]);
1127 /* Destination is not globbed */
1128 undo_glob_escape(*path2);
1133 if (argc - optidx < 2) {
1134 error("You must specify two paths after a %s "
1138 *path1 = xstrdup(argv[optidx]);
1139 *path2 = xstrdup(argv[optidx + 1]);
1140 /* Paths are not globbed */
1141 undo_glob_escape(*path1);
1142 undo_glob_escape(*path2);
1150 /* Get pathname (mandatory) */
1151 if (argc - optidx < 1) {
1152 error("You must specify a path after a %s command.",
1156 *path1 = xstrdup(argv[optidx]);
1157 /* Only "rm" globs */
1159 undo_glob_escape(*path1);
1162 if ((optidx = parse_df_flags(cmd, argv, argc, hflag,
1165 /* Default to current directory if no path specified */
1166 if (argc - optidx < 1)
1169 *path1 = xstrdup(argv[optidx]);
1170 undo_glob_escape(*path1);
1174 if ((optidx = parse_ls_flags(argv, argc, lflag)) == -1)
1176 /* Path is optional */
1177 if (argc - optidx > 0)
1178 *path1 = xstrdup(argv[optidx]);
1181 /* Skip ls command and following whitespace */
1182 cp = cp + strlen(cmd) + strspn(cp, WHITESPACE);
1184 /* Uses the rest of the line */
1191 /* Get numeric arg (mandatory) */
1192 if (argc - optidx < 1)
1195 l = strtol(argv[optidx], &cp2, base);
1196 if (cp2 == argv[optidx] || *cp2 != '\0' ||
1197 ((l == LONG_MIN || l == LONG_MAX) && errno == ERANGE) ||
1200 error("You must supply a numeric argument "
1201 "to the %s command.", cmd);
1205 if (cmdnum == I_LUMASK)
1207 /* Get pathname (mandatory) */
1208 if (argc - optidx < 2) {
1209 error("You must specify a path after a %s command.",
1213 *path1 = xstrdup(argv[optidx + 1]);
1223 fatal("Command not implemented");
1231 parse_dispatch_command(struct sftp_conn *conn, const char *cmd, char **pwd,
1234 char *path1, *path2, *tmp;
1235 int pflag, lflag, iflag, hflag, cmdnum, i;
1236 unsigned long n_arg;
1238 char path_buf[MAXPATHLEN];
1242 path1 = path2 = NULL;
1243 cmdnum = parse_args(&cmd, &pflag, &lflag, &iflag, &hflag, &n_arg,
1249 memset(&g, 0, sizeof(g));
1251 /* Perform command */
1257 /* Unrecognized command */
1261 err = process_get(conn, path1, path2, *pwd, pflag);
1264 err = process_put(conn, path1, path2, *pwd, pflag);
1267 path1 = make_absolute(path1, *pwd);
1268 path2 = make_absolute(path2, *pwd);
1269 err = do_rename(conn, path1, path2);
1272 path2 = make_absolute(path2, *pwd);
1273 err = do_symlink(conn, path1, path2);
1276 path1 = make_absolute(path1, *pwd);
1277 remote_glob(conn, path1, GLOB_NOCHECK, NULL, &g);
1278 for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
1279 printf("Removing %s\n", g.gl_pathv[i]);
1280 err = do_rm(conn, g.gl_pathv[i]);
1281 if (err != 0 && err_abort)
1286 path1 = make_absolute(path1, *pwd);
1288 a.flags |= SSH2_FILEXFER_ATTR_PERMISSIONS;
1290 err = do_mkdir(conn, path1, &a);
1293 path1 = make_absolute(path1, *pwd);
1294 err = do_rmdir(conn, path1);
1297 path1 = make_absolute(path1, *pwd);
1298 if ((tmp = do_realpath(conn, path1)) == NULL) {
1302 if ((aa = do_stat(conn, tmp, 0)) == NULL) {
1307 if (!(aa->flags & SSH2_FILEXFER_ATTR_PERMISSIONS)) {
1308 error("Can't change directory: Can't check target");
1313 if (!S_ISDIR(aa->perm)) {
1314 error("Can't change directory: \"%s\" is not "
1315 "a directory", tmp);
1325 do_globbed_ls(conn, *pwd, *pwd, lflag);
1329 /* Strip pwd off beginning of non-absolute paths */
1334 path1 = make_absolute(path1, *pwd);
1335 err = do_globbed_ls(conn, path1, tmp, lflag);
1338 /* Default to current directory if no path specified */
1340 path1 = xstrdup(*pwd);
1341 path1 = make_absolute(path1, *pwd);
1342 err = do_df(conn, path1, hflag, iflag);
1345 if (chdir(path1) == -1) {
1346 error("Couldn't change local directory to "
1347 "\"%s\": %s", path1, strerror(errno));
1352 if (mkdir(path1, 0777) == -1) {
1353 error("Couldn't create local directory "
1354 "\"%s\": %s", path1, strerror(errno));
1362 local_do_shell(cmd);
1366 printf("Local umask: %03lo\n", n_arg);
1369 path1 = make_absolute(path1, *pwd);
1371 a.flags |= SSH2_FILEXFER_ATTR_PERMISSIONS;
1373 remote_glob(conn, path1, GLOB_NOCHECK, NULL, &g);
1374 for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
1375 printf("Changing mode on %s\n", g.gl_pathv[i]);
1376 err = do_setstat(conn, g.gl_pathv[i], &a);
1377 if (err != 0 && err_abort)
1383 path1 = make_absolute(path1, *pwd);
1384 remote_glob(conn, path1, GLOB_NOCHECK, NULL, &g);
1385 for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
1386 if (!(aa = do_stat(conn, g.gl_pathv[i], 0))) {
1387 if (err != 0 && err_abort)
1392 if (!(aa->flags & SSH2_FILEXFER_ATTR_UIDGID)) {
1393 error("Can't get current ownership of "
1394 "remote file \"%s\"", g.gl_pathv[i]);
1395 if (err != 0 && err_abort)
1400 aa->flags &= SSH2_FILEXFER_ATTR_UIDGID;
1401 if (cmdnum == I_CHOWN) {
1402 printf("Changing owner on %s\n", g.gl_pathv[i]);
1405 printf("Changing group on %s\n", g.gl_pathv[i]);
1408 err = do_setstat(conn, g.gl_pathv[i], aa);
1409 if (err != 0 && err_abort)
1414 printf("Remote working directory: %s\n", *pwd);
1417 if (!getcwd(path_buf, sizeof(path_buf))) {
1418 error("Couldn't get local cwd: %s", strerror(errno));
1422 printf("Local working directory: %s\n", path_buf);
1425 /* Processed below */
1431 printf("SFTP protocol version %u\n", sftp_proto_version(conn));
1434 showprogress = !showprogress;
1436 printf("Progress meter enabled\n");
1438 printf("Progress meter disabled\n");
1441 fatal("%d is not implemented", cmdnum);
1451 /* If an unignored error occurs in batch mode we should abort. */
1452 if (err_abort && err != 0)
1454 else if (cmdnum == I_QUIT)
1462 prompt(EditLine *el)
1469 interactive_loop(int fd_in, int fd_out, char *file1, char *file2)
1474 struct sftp_conn *conn;
1475 int err, interactive;
1476 EditLine *el = NULL;
1480 extern char *__progname;
1482 if (!batchmode && isatty(STDIN_FILENO)) {
1483 if ((el = el_init(__progname, stdin, stdout, stderr)) == NULL)
1484 fatal("Couldn't initialise editline");
1485 if ((hl = history_init()) == NULL)
1486 fatal("Couldn't initialise editline history");
1487 history(hl, &hev, H_SETSIZE, 100);
1488 el_set(el, EL_HIST, history, hl);
1490 el_set(el, EL_PROMPT, prompt);
1491 el_set(el, EL_EDITOR, "emacs");
1492 el_set(el, EL_TERMINAL, NULL);
1493 el_set(el, EL_SIGNAL, 1);
1494 el_source(el, NULL);
1496 #endif /* USE_LIBEDIT */
1498 conn = do_init(fd_in, fd_out, copy_buffer_len, num_requests);
1500 fatal("Couldn't initialise connection to server");
1502 pwd = do_realpath(conn, ".");
1506 if (file1 != NULL) {
1507 dir = xstrdup(file1);
1508 dir = make_absolute(dir, pwd);
1510 if (remote_is_dir(conn, dir) && file2 == NULL) {
1511 printf("Changing to: %s\n", dir);
1512 snprintf(cmd, sizeof cmd, "cd \"%s\"", dir);
1513 if (parse_dispatch_command(conn, cmd, &pwd, 1) != 0) {
1521 snprintf(cmd, sizeof cmd, "get %s", dir);
1523 snprintf(cmd, sizeof cmd, "get %s %s", dir,
1526 err = parse_dispatch_command(conn, cmd, &pwd, 1);
1535 #if defined(HAVE_SETVBUF) && !defined(BROKEN_SETVBUF)
1536 setvbuf(stdout, NULL, _IOLBF, 0);
1537 setvbuf(infile, NULL, _IOLBF, 0);
1543 interactive = !batchmode && isatty(STDIN_FILENO);
1548 signal(SIGINT, SIG_IGN);
1553 if (fgets(cmd, sizeof(cmd), infile) == NULL) {
1558 if (!interactive) { /* Echo command */
1559 printf("sftp> %s", cmd);
1560 if (strlen(cmd) > 0 &&
1561 cmd[strlen(cmd) - 1] != '\n')
1569 if ((line = el_gets(el, &count)) == NULL || count <= 0) {
1573 history(hl, &hev, H_ENTER, line);
1574 if (strlcpy(cmd, line, sizeof(cmd)) >= sizeof(cmd)) {
1575 fprintf(stderr, "Error: input line too long\n");
1578 #endif /* USE_LIBEDIT */
1581 cp = strrchr(cmd, '\n');
1585 /* Handle user interrupts gracefully during commands */
1587 signal(SIGINT, cmd_interrupt);
1589 err = parse_dispatch_command(conn, cmd, &pwd, batchmode);
1599 #endif /* USE_LIBEDIT */
1601 /* err == 1 signifies normal "quit" exit */
1602 return (err >= 0 ? 0 : -1);
1606 connect_to_server(char *path, char **args, int *in, int *out)
1611 int pin[2], pout[2];
1613 if ((pipe(pin) == -1) || (pipe(pout) == -1))
1614 fatal("pipe: %s", strerror(errno));
1619 #else /* USE_PIPES */
1622 if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) == -1)
1623 fatal("socketpair: %s", strerror(errno));
1624 *in = *out = inout[0];
1625 c_in = c_out = inout[1];
1626 #endif /* USE_PIPES */
1628 if ((sshpid = fork()) == -1)
1629 fatal("fork: %s", strerror(errno));
1630 else if (sshpid == 0) {
1631 if ((dup2(c_in, STDIN_FILENO) == -1) ||
1632 (dup2(c_out, STDOUT_FILENO) == -1)) {
1633 fprintf(stderr, "dup2: %s\n", strerror(errno));
1642 * The underlying ssh is in the same process group, so we must
1643 * ignore SIGINT if we want to gracefully abort commands,
1644 * otherwise the signal will make it to the ssh process and
1647 signal(SIGINT, SIG_IGN);
1649 fprintf(stderr, "exec: %s: %s\n", path, strerror(errno));
1653 signal(SIGTERM, killchild);
1654 signal(SIGINT, killchild);
1655 signal(SIGHUP, killchild);
1663 extern char *__progname;
1666 "usage: %s [-1Cv] [-B buffer_size] [-b batchfile] [-F ssh_config]\n"
1667 " [-o ssh_option] [-P sftp_server_path] [-R num_requests]\n"
1668 " [-S program] [-s subsystem | sftp_server] host\n"
1669 " %s [[user@]host[:file [file]]]\n"
1670 " %s [[user@]host[:dir[/]]]\n"
1671 " %s -b batchfile [user@]host\n", __progname, __progname, __progname, __progname);
1676 main(int argc, char **argv)
1678 int in, out, ch, err;
1679 char *host, *userhost, *cp, *file2 = NULL;
1680 int debug_level = 0, sshver = 2;
1681 char *file1 = NULL, *sftp_server = NULL;
1682 char *ssh_program = _PATH_SSH_PROGRAM, *sftp_direct = NULL;
1683 LogLevel ll = SYSLOG_LEVEL_INFO;
1686 extern char *optarg;
1688 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
1691 __progname = ssh_get_progname(argv[0]);
1692 memset(&args, '\0', sizeof(args));
1694 addargs(&args, "%s", ssh_program);
1695 addargs(&args, "-oForwardX11 no");
1696 addargs(&args, "-oForwardAgent no");
1697 addargs(&args, "-oPermitLocalCommand no");
1698 addargs(&args, "-oClearAllForwardings yes");
1700 ll = SYSLOG_LEVEL_INFO;
1703 while ((ch = getopt(argc, argv, "1hvCo:s:S:b:B:F:P:R:")) != -1) {
1706 addargs(&args, "-C");
1709 if (debug_level < 3) {
1710 addargs(&args, "-v");
1711 ll = SYSLOG_LEVEL_DEBUG1 + debug_level;
1717 addargs(&args, "-%c%s", ch, optarg);
1721 if (sftp_server == NULL)
1722 sftp_server = _PATH_SFTP_SERVER;
1725 sftp_server = optarg;
1728 ssh_program = optarg;
1729 replacearg(&args, 0, "%s", ssh_program);
1733 fatal("Batch file already specified.");
1735 /* Allow "-" as stdin */
1736 if (strcmp(optarg, "-") != 0 &&
1737 (infile = fopen(optarg, "r")) == NULL)
1738 fatal("%s (%s).", strerror(errno), optarg);
1741 addargs(&args, "-obatchmode yes");
1744 sftp_direct = optarg;
1747 copy_buffer_len = strtol(optarg, &cp, 10);
1748 if (copy_buffer_len == 0 || *cp != '\0')
1749 fatal("Invalid buffer size \"%s\"", optarg);
1752 num_requests = strtol(optarg, &cp, 10);
1753 if (num_requests == 0 || *cp != '\0')
1754 fatal("Invalid number of requests \"%s\"",
1763 if (!isatty(STDERR_FILENO))
1766 log_init(argv[0], ll, SYSLOG_FACILITY_USER, 1);
1768 if (sftp_direct == NULL) {
1769 if (optind == argc || argc > (optind + 2))
1772 userhost = xstrdup(argv[optind]);
1773 file2 = argv[optind+1];
1775 if ((host = strrchr(userhost, '@')) == NULL)
1780 fprintf(stderr, "Missing username\n");
1783 addargs(&args, "-l%s", userhost);
1786 if ((cp = colon(host)) != NULL) {
1791 host = cleanhostname(host);
1793 fprintf(stderr, "Missing hostname\n");
1797 addargs(&args, "-oProtocol %d", sshver);
1799 /* no subsystem if the server-spec contains a '/' */
1800 if (sftp_server == NULL || strchr(sftp_server, '/') == NULL)
1801 addargs(&args, "-s");
1803 addargs(&args, "%s", host);
1804 addargs(&args, "%s", (sftp_server != NULL ?
1805 sftp_server : "sftp"));
1808 fprintf(stderr, "Connecting to %s...\n", host);
1809 connect_to_server(ssh_program, args.list, &in, &out);
1812 addargs(&args, "sftp-server");
1815 fprintf(stderr, "Attaching to %s...\n", sftp_direct);
1816 connect_to_server(sftp_direct, args.list, &in, &out);
1820 err = interactive_loop(in, out, file1, file2);
1822 #if !defined(USE_PIPES)
1823 shutdown(in, SHUT_RDWR);
1824 shutdown(out, SHUT_RDWR);
1832 while (waitpid(sshpid, NULL, 0) == -1)
1834 fatal("Couldn't wait for ssh process: %s",
1837 exit(err == 0 ? 0 : 1);