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 #ifdef HAVE_SYS_STATVFS_H
29 #include <sys/statvfs.h>
41 typedef void EditLine;
60 #include "pathnames.h"
65 #include "sftp-common.h"
66 #include "sftp-client.h"
68 /* File to read commands from */
71 /* Are we in batchfile mode? */
74 /* Size of buffer used when copying files */
75 size_t copy_buffer_len = 32768;
77 /* Number of concurrent outstanding requests */
78 size_t num_requests = 16;
80 /* PID of ssh transport process */
81 static pid_t sshpid = -1;
83 /* This is set to 0 if the progressmeter is not desired. */
86 /* SIGINT received during command processing */
87 volatile sig_atomic_t interrupted = 0;
89 /* I wish qsort() took a separate ctx for the comparison function...*/
92 int remote_glob(struct sftp_conn *, const char *, int,
93 int (*)(const char *, int), glob_t *); /* proto for sftp-glob.c */
95 extern char *__progname;
97 /* Separators for interactive commands */
98 #define WHITESPACE " \t\r\n"
101 #define LS_LONG_VIEW 0x01 /* Full view ala ls -l */
102 #define LS_SHORT_VIEW 0x02 /* Single row view ala ls -1 */
103 #define LS_NUMERIC_VIEW 0x04 /* Long view with numeric uid/gid */
104 #define LS_NAME_SORT 0x08 /* Sort by name (default) */
105 #define LS_TIME_SORT 0x10 /* Sort by mtime */
106 #define LS_SIZE_SORT 0x20 /* Sort by file size */
107 #define LS_REVERSE_SORT 0x40 /* Reverse sort order */
108 #define LS_SHOW_ALL 0x80 /* Don't skip filenames starting with '.' */
110 #define VIEW_FLAGS (LS_LONG_VIEW|LS_SHORT_VIEW|LS_NUMERIC_VIEW)
111 #define SORT_FLAGS (LS_NAME_SORT|LS_TIME_SORT|LS_SIZE_SORT)
113 /* Commands for interactive mode */
137 #define I_PROGRESS 23
144 static const struct CMD cmds[] = {
147 { "chdir", I_CHDIR },
148 { "chgrp", I_CHGRP },
149 { "chmod", I_CHMOD },
150 { "chown", I_CHOWN },
158 { "lchdir", I_LCHDIR },
160 { "lmkdir", I_LMKDIR },
164 { "lumask", I_LUMASK },
165 { "mkdir", I_MKDIR },
166 { "progress", I_PROGRESS },
171 { "rename", I_RENAME },
173 { "rmdir", I_RMDIR },
174 { "symlink", I_SYMLINK },
175 { "version", I_VERSION },
181 int interactive_loop(int fd_in, int fd_out, char *file1, char *file2);
188 kill(sshpid, SIGTERM);
189 waitpid(sshpid, NULL, 0);
197 cmd_interrupt(int signo)
199 const char msg[] = "\rInterrupt \n";
200 int olderrno = errno;
202 write(STDERR_FILENO, msg, sizeof(msg) - 1);
210 printf("Available commands:\n");
211 printf("cd path Change remote directory to 'path'\n");
212 printf("lcd path Change local directory to 'path'\n");
213 printf("chgrp grp path Change group of file 'path' to 'grp'\n");
214 printf("chmod mode path Change permissions of file 'path' to 'mode'\n");
215 printf("chown own path Change owner of file 'path' to 'own'\n");
216 printf("df [path] Display statistics for current directory or\n");
217 printf(" filesystem containing 'path'\n");
218 printf("help Display this help text\n");
219 printf("get remote-path [local-path] Download file\n");
220 printf("lls [ls-options [path]] Display local directory listing\n");
221 printf("ln oldpath newpath Symlink remote file\n");
222 printf("lmkdir path Create local directory\n");
223 printf("lpwd Print local working directory\n");
224 printf("ls [path] Display remote directory listing\n");
225 printf("lumask umask Set local umask to 'umask'\n");
226 printf("mkdir path Create remote directory\n");
227 printf("progress Toggle display of progress meter\n");
228 printf("put local-path [remote-path] Upload file\n");
229 printf("pwd Display remote working directory\n");
230 printf("exit Quit sftp\n");
231 printf("quit Quit sftp\n");
232 printf("rename oldpath newpath Rename remote file\n");
233 printf("rmdir path Remove remote directory\n");
234 printf("rm path Delete remote file\n");
235 printf("symlink oldpath newpath Symlink remote file\n");
236 printf("version Show SFTP version\n");
237 printf("!command Execute 'command' in local shell\n");
238 printf("! Escape to local shell\n");
239 printf("? Synonym for help\n");
243 local_do_shell(const char *args)
252 if ((shell = getenv("SHELL")) == NULL)
253 shell = _PATH_BSHELL;
255 if ((pid = fork()) == -1)
256 fatal("Couldn't fork: %s", strerror(errno));
259 /* XXX: child has pipe fds to ssh subproc open - issue? */
261 debug3("Executing %s -c \"%s\"", shell, args);
262 execl(shell, shell, "-c", args, (char *)NULL);
264 debug3("Executing %s", shell);
265 execl(shell, shell, (char *)NULL);
267 fprintf(stderr, "Couldn't execute \"%s\": %s\n", shell,
271 while (waitpid(pid, &status, 0) == -1)
273 fatal("Couldn't wait for child: %s", strerror(errno));
274 if (!WIFEXITED(status))
275 error("Shell exited abnormally");
276 else if (WEXITSTATUS(status))
277 error("Shell exited with status %d", WEXITSTATUS(status));
281 local_do_ls(const char *args)
284 local_do_shell(_PATH_LS);
286 int len = strlen(_PATH_LS " ") + strlen(args) + 1;
287 char *buf = xmalloc(len);
289 /* XXX: quoting - rip quoting code from ftp? */
290 snprintf(buf, len, _PATH_LS " %s", args);
296 /* Strip one path (usually the pwd) from the start of another */
298 path_strip(char *path, char *strip)
303 return (xstrdup(path));
306 if (strncmp(path, strip, len) == 0) {
307 if (strip[len - 1] != '/' && path[len] == '/')
309 return (xstrdup(path + len));
312 return (xstrdup(path));
316 path_append(char *p1, char *p2)
319 size_t len = strlen(p1) + strlen(p2) + 2;
322 strlcpy(ret, p1, len);
323 if (p1[0] != '\0' && p1[strlen(p1) - 1] != '/')
324 strlcat(ret, "/", len);
325 strlcat(ret, p2, len);
331 make_absolute(char *p, char *pwd)
336 if (p && p[0] != '/') {
337 abs_str = path_append(pwd, p);
345 infer_path(const char *p, char **ifp)
349 cp = strrchr(p, '/');
356 error("Invalid path");
360 *ifp = xstrdup(cp + 1);
365 parse_getput_flags(const char *cmd, char **argv, int argc, int *pflag)
367 extern int optind, optreset, opterr;
370 optind = optreset = 1;
374 while ((ch = getopt(argc, argv, "Pp")) != -1) {
381 error("%s: Invalid flag -%c", cmd, ch);
390 parse_ls_flags(char **argv, int argc, int *lflag)
392 extern int optind, optreset, opterr;
395 optind = optreset = 1;
398 *lflag = LS_NAME_SORT;
399 while ((ch = getopt(argc, argv, "1Saflnrt")) != -1) {
402 *lflag &= ~VIEW_FLAGS;
403 *lflag |= LS_SHORT_VIEW;
406 *lflag &= ~SORT_FLAGS;
407 *lflag |= LS_SIZE_SORT;
410 *lflag |= LS_SHOW_ALL;
413 *lflag &= ~SORT_FLAGS;
416 *lflag &= ~VIEW_FLAGS;
417 *lflag |= LS_LONG_VIEW;
420 *lflag &= ~VIEW_FLAGS;
421 *lflag |= LS_NUMERIC_VIEW|LS_LONG_VIEW;
424 *lflag |= LS_REVERSE_SORT;
427 *lflag &= ~SORT_FLAGS;
428 *lflag |= LS_TIME_SORT;
431 error("ls: Invalid flag -%c", ch);
440 parse_df_flags(const char *cmd, char **argv, int argc, int *hflag, int *iflag)
442 extern int optind, optreset, opterr;
445 optind = optreset = 1;
449 while ((ch = getopt(argc, argv, "hi")) != -1) {
458 error("%s: Invalid flag -%c", cmd, ch);
471 /* XXX: report errors? */
472 if (stat(path, &sb) == -1)
475 return(S_ISDIR(sb.st_mode));
479 remote_is_dir(struct sftp_conn *conn, char *path)
483 /* XXX: report errors? */
484 if ((a = do_stat(conn, path, 1)) == NULL)
486 if (!(a->flags & SSH2_FILEXFER_ATTR_PERMISSIONS))
488 return(S_ISDIR(a->perm));
492 process_get(struct sftp_conn *conn, char *src, char *dst, char *pwd, int pflag)
494 char *abs_src = NULL;
495 char *abs_dst = NULL;
501 abs_src = xstrdup(src);
502 abs_src = make_absolute(abs_src, pwd);
504 memset(&g, 0, sizeof(g));
505 debug3("Looking up %s", abs_src);
506 if (remote_glob(conn, abs_src, 0, NULL, &g)) {
507 error("File \"%s\" not found.", abs_src);
512 /* If multiple matches, dst must be a directory or unspecified */
513 if (g.gl_matchc > 1 && dst && !is_dir(dst)) {
514 error("Multiple files match, but \"%s\" is not a directory",
520 for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
521 if (infer_path(g.gl_pathv[i], &tmp)) {
526 if (g.gl_matchc == 1 && dst) {
527 /* If directory specified, append filename */
530 if (infer_path(g.gl_pathv[0], &tmp)) {
534 abs_dst = path_append(dst, tmp);
537 abs_dst = xstrdup(dst);
539 abs_dst = path_append(dst, tmp);
544 printf("Fetching %s to %s\n", g.gl_pathv[i], abs_dst);
545 if (do_download(conn, g.gl_pathv[i], abs_dst, pflag) == -1)
558 process_put(struct sftp_conn *conn, char *src, char *dst, char *pwd, int pflag)
560 char *tmp_dst = NULL;
561 char *abs_dst = NULL;
569 tmp_dst = xstrdup(dst);
570 tmp_dst = make_absolute(tmp_dst, pwd);
573 memset(&g, 0, sizeof(g));
574 debug3("Looking up %s", src);
575 if (glob(src, GLOB_NOCHECK, NULL, &g)) {
576 error("File \"%s\" not found.", src);
581 /* If multiple matches, dst may be directory or unspecified */
582 if (g.gl_matchc > 1 && tmp_dst && !remote_is_dir(conn, tmp_dst)) {
583 error("Multiple files match, but \"%s\" is not a directory",
589 for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
590 if (stat(g.gl_pathv[i], &sb) == -1) {
592 error("stat %s: %s", g.gl_pathv[i], strerror(errno));
596 if (!S_ISREG(sb.st_mode)) {
597 error("skipping non-regular file %s",
601 if (infer_path(g.gl_pathv[i], &tmp)) {
606 if (g.gl_matchc == 1 && tmp_dst) {
607 /* If directory specified, append filename */
608 if (remote_is_dir(conn, tmp_dst)) {
609 if (infer_path(g.gl_pathv[0], &tmp)) {
613 abs_dst = path_append(tmp_dst, tmp);
616 abs_dst = xstrdup(tmp_dst);
618 } else if (tmp_dst) {
619 abs_dst = path_append(tmp_dst, tmp);
622 abs_dst = make_absolute(tmp, pwd);
624 printf("Uploading %s to %s\n", g.gl_pathv[i], abs_dst);
625 if (do_upload(conn, g.gl_pathv[i], abs_dst, pflag) == -1)
639 sdirent_comp(const void *aa, const void *bb)
641 SFTP_DIRENT *a = *(SFTP_DIRENT **)aa;
642 SFTP_DIRENT *b = *(SFTP_DIRENT **)bb;
643 int rmul = sort_flag & LS_REVERSE_SORT ? -1 : 1;
645 #define NCMP(a,b) (a == b ? 0 : (a < b ? 1 : -1))
646 if (sort_flag & LS_NAME_SORT)
647 return (rmul * strcmp(a->filename, b->filename));
648 else if (sort_flag & LS_TIME_SORT)
649 return (rmul * NCMP(a->a.mtime, b->a.mtime));
650 else if (sort_flag & LS_SIZE_SORT)
651 return (rmul * NCMP(a->a.size, b->a.size));
653 fatal("Unknown ls sort type");
656 /* sftp ls.1 replacement for directories */
658 do_ls_dir(struct sftp_conn *conn, char *path, char *strip_path, int lflag)
661 u_int c = 1, colspace = 0, columns = 1;
664 if ((n = do_readdir(conn, path, &d)) != 0)
667 if (!(lflag & LS_SHORT_VIEW)) {
668 u_int m = 0, width = 80;
672 /* Count entries for sort and find longest filename */
673 for (n = 0; d[n] != NULL; n++) {
674 if (d[n]->filename[0] != '.' || (lflag & LS_SHOW_ALL))
675 m = MAX(m, strlen(d[n]->filename));
678 /* Add any subpath that also needs to be counted */
679 tmp = path_strip(path, strip_path);
683 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) != -1)
686 columns = width / (m + 2);
687 columns = MAX(columns, 1);
688 colspace = width / columns;
689 colspace = MIN(colspace, width);
692 if (lflag & SORT_FLAGS) {
693 for (n = 0; d[n] != NULL; n++)
694 ; /* count entries */
695 sort_flag = lflag & (SORT_FLAGS|LS_REVERSE_SORT);
696 qsort(d, n, sizeof(*d), sdirent_comp);
699 for (n = 0; d[n] != NULL && !interrupted; n++) {
702 if (d[n]->filename[0] == '.' && !(lflag & LS_SHOW_ALL))
705 tmp = path_append(path, d[n]->filename);
706 fname = path_strip(tmp, strip_path);
709 if (lflag & LS_LONG_VIEW) {
710 if (lflag & LS_NUMERIC_VIEW) {
714 memset(&sb, 0, sizeof(sb));
715 attrib_to_stat(&d[n]->a, &sb);
716 lname = ls_file(fname, &sb, 1);
717 printf("%s\n", lname);
720 printf("%s\n", d[n]->longname);
722 printf("%-*s", colspace, fname);
733 if (!(lflag & LS_LONG_VIEW) && (c != 1))
736 free_sftp_dirents(d);
740 /* sftp ls.1 replacement which handles path globs */
742 do_globbed_ls(struct sftp_conn *conn, char *path, char *strip_path,
746 u_int i, c = 1, colspace = 0, columns = 1;
749 memset(&g, 0, sizeof(g));
751 if (remote_glob(conn, path, GLOB_MARK|GLOB_NOCHECK|GLOB_BRACE,
752 NULL, &g) || (g.gl_pathc && !g.gl_matchc)) {
755 error("Can't ls: \"%s\" not found", path);
763 * If the glob returns a single match and it is a directory,
764 * then just list its contents.
766 if (g.gl_matchc == 1) {
767 if ((a = do_lstat(conn, g.gl_pathv[0], 1)) == NULL) {
771 if ((a->flags & SSH2_FILEXFER_ATTR_PERMISSIONS) &&
775 err = do_ls_dir(conn, g.gl_pathv[0], strip_path, lflag);
781 if (!(lflag & LS_SHORT_VIEW)) {
782 u_int m = 0, width = 80;
785 /* Count entries for sort and find longest filename */
786 for (i = 0; g.gl_pathv[i]; i++)
787 m = MAX(m, strlen(g.gl_pathv[i]));
789 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) != -1)
792 columns = width / (m + 2);
793 columns = MAX(columns, 1);
794 colspace = width / columns;
797 for (i = 0; g.gl_pathv[i] && !interrupted; i++, a = NULL) {
800 fname = path_strip(g.gl_pathv[i], strip_path);
802 if (lflag & LS_LONG_VIEW) {
807 * XXX: this is slow - 1 roundtrip per path
808 * A solution to this is to fork glob() and
809 * build a sftp specific version which keeps the
810 * attribs (which currently get thrown away)
811 * that the server returns as well as the filenames.
813 memset(&sb, 0, sizeof(sb));
815 a = do_lstat(conn, g.gl_pathv[i], 1);
817 attrib_to_stat(a, &sb);
818 lname = ls_file(fname, &sb, 1);
819 printf("%s\n", lname);
822 printf("%-*s", colspace, fname);
832 if (!(lflag & LS_LONG_VIEW) && (c != 1))
843 do_df(struct sftp_conn *conn, char *path, int hflag, int iflag)
847 char s_used[FMT_SCALED_STRSIZE];
848 char s_avail[FMT_SCALED_STRSIZE];
849 char s_root[FMT_SCALED_STRSIZE];
850 char s_total[FMT_SCALED_STRSIZE];
852 if (do_statvfs(conn, path, &st, 1) == -1)
855 printf(" Inodes Used Avail "
856 "(root) %%Capacity\n");
857 printf("%11llu %11llu %11llu %11llu %3llu%%\n",
858 (unsigned long long)st.f_files,
859 (unsigned long long)(st.f_files - st.f_ffree),
860 (unsigned long long)st.f_favail,
861 (unsigned long long)st.f_ffree,
862 (unsigned long long)(100 * (st.f_files - st.f_ffree) /
865 strlcpy(s_used, "error", sizeof(s_used));
866 strlcpy(s_avail, "error", sizeof(s_avail));
867 strlcpy(s_root, "error", sizeof(s_root));
868 strlcpy(s_total, "error", sizeof(s_total));
869 fmt_scaled((st.f_blocks - st.f_bfree) * st.f_frsize, s_used);
870 fmt_scaled(st.f_bavail * st.f_frsize, s_avail);
871 fmt_scaled(st.f_bfree * st.f_frsize, s_root);
872 fmt_scaled(st.f_blocks * st.f_frsize, s_total);
873 printf(" Size Used Avail (root) %%Capacity\n");
874 printf("%7sB %7sB %7sB %7sB %3llu%%\n",
875 s_total, s_used, s_avail, s_root,
876 (unsigned long long)(100 * (st.f_blocks - st.f_bfree) /
879 printf(" Size Used Avail "
880 "(root) %%Capacity\n");
881 printf("%12llu %12llu %12llu %12llu %3llu%%\n",
882 (unsigned long long)(st.f_frsize * st.f_blocks / 1024),
883 (unsigned long long)(st.f_frsize *
884 (st.f_blocks - st.f_bfree) / 1024),
885 (unsigned long long)(st.f_frsize * st.f_bavail / 1024),
886 (unsigned long long)(st.f_frsize * st.f_bfree / 1024),
887 (unsigned long long)(100 * (st.f_blocks - st.f_bfree) /
892 error("client does not support statvfs extension");
898 * Undo escaping of glob sequences in place. Used to undo extra escaping
899 * applied in makeargv() when the string is destined for a function that
903 undo_glob_escape(char *s)
938 * Split a string into an argument vector using sh(1)-style quoting,
939 * comment and escaping rules, but with some tweaks to handle glob(3)
941 * Returns NULL on error or a NULL-terminated array of arguments.
944 #define MAXARGLEN 8192
946 makeargv(const char *arg, int *argcp)
950 static char argvs[MAXARGLEN];
951 static char *argv[MAXARGS + 1];
952 enum { MA_START, MA_SQUOTE, MA_DQUOTE, MA_UNQUOTED } state, q;
955 if (strlen(arg) > sizeof(argvs) - 1) {
957 error("string too long");
963 if (isspace(arg[i])) {
964 if (state == MA_UNQUOTED) {
965 /* Terminate current argument */
969 } else if (state != MA_START)
971 } else if (arg[i] == '"' || arg[i] == '\'') {
972 q = arg[i] == '"' ? MA_DQUOTE : MA_SQUOTE;
973 if (state == MA_START) {
974 argv[argc] = argvs + j;
976 } else if (state == MA_UNQUOTED)
982 } else if (arg[i] == '\\') {
983 if (state == MA_SQUOTE || state == MA_DQUOTE) {
984 quot = state == MA_SQUOTE ? '\'' : '"';
985 /* Unescape quote we are in */
986 /* XXX support \n and friends? */
987 if (arg[i + 1] == quot) {
990 } else if (arg[i + 1] == '?' ||
991 arg[i + 1] == '[' || arg[i + 1] == '*') {
993 * Special case for sftp: append
994 * double-escaped glob sequence -
995 * glob will undo one level of
996 * escaping. NB. string can grow here.
998 if (j >= sizeof(argvs) - 5)
1001 argvs[j++] = arg[i++];
1003 argvs[j++] = arg[i];
1005 argvs[j++] = arg[i++];
1006 argvs[j++] = arg[i];
1009 if (state == MA_START) {
1010 argv[argc] = argvs + j;
1011 state = MA_UNQUOTED;
1013 if (arg[i + 1] == '?' || arg[i + 1] == '[' ||
1014 arg[i + 1] == '*' || arg[i + 1] == '\\') {
1016 * Special case for sftp: append
1017 * escaped glob sequence -
1018 * glob will undo one level of
1021 argvs[j++] = arg[i++];
1022 argvs[j++] = arg[i];
1024 /* Unescape everything */
1025 /* XXX support \n and friends? */
1027 argvs[j++] = arg[i];
1030 } else if (arg[i] == '#') {
1031 if (state == MA_SQUOTE || state == MA_DQUOTE)
1032 argvs[j++] = arg[i];
1035 } else if (arg[i] == '\0') {
1036 if (state == MA_SQUOTE || state == MA_DQUOTE) {
1037 error("Unterminated quoted argument");
1041 if (state == MA_UNQUOTED) {
1047 if (state == MA_START) {
1048 argv[argc] = argvs + j;
1049 state = MA_UNQUOTED;
1051 if ((state == MA_SQUOTE || state == MA_DQUOTE) &&
1052 (arg[i] == '?' || arg[i] == '[' || arg[i] == '*')) {
1054 * Special case for sftp: escape quoted
1055 * glob(3) wildcards. NB. string can grow
1058 if (j >= sizeof(argvs) - 3)
1059 goto args_too_longs;
1061 argvs[j++] = arg[i];
1063 argvs[j++] = arg[i];
1072 parse_args(const char **cpp, int *pflag, int *lflag, int *iflag, int *hflag,
1073 unsigned long *n_arg, char **path1, char **path2)
1075 const char *cmd, *cp = *cpp;
1079 int i, cmdnum, optidx, argc;
1081 /* Skip leading whitespace */
1082 cp = cp + strspn(cp, WHITESPACE);
1084 /* Ignore blank lines and lines which begin with comment '#' char */
1085 if (*cp == '\0' || *cp == '#')
1088 /* Check for leading '-' (disable error processing) */
1095 if ((argv = makeargv(cp, &argc)) == NULL)
1098 /* Figure out which command we have */
1099 for (i = 0; cmds[i].c != NULL; i++) {
1100 if (strcasecmp(cmds[i].c, argv[0]) == 0)
1110 } else if (cmdnum == -1) {
1111 error("Invalid command.");
1115 /* Get arguments and parse flags */
1116 *lflag = *pflag = *hflag = *n_arg = 0;
1117 *path1 = *path2 = NULL;
1122 if ((optidx = parse_getput_flags(cmd, argv, argc, pflag)) == -1)
1124 /* Get first pathname (mandatory) */
1125 if (argc - optidx < 1) {
1126 error("You must specify at least one path after a "
1127 "%s command.", cmd);
1130 *path1 = xstrdup(argv[optidx]);
1131 /* Get second pathname (optional) */
1132 if (argc - optidx > 1) {
1133 *path2 = xstrdup(argv[optidx + 1]);
1134 /* Destination is not globbed */
1135 undo_glob_escape(*path2);
1140 if (argc - optidx < 2) {
1141 error("You must specify two paths after a %s "
1145 *path1 = xstrdup(argv[optidx]);
1146 *path2 = xstrdup(argv[optidx + 1]);
1147 /* Paths are not globbed */
1148 undo_glob_escape(*path1);
1149 undo_glob_escape(*path2);
1157 /* Get pathname (mandatory) */
1158 if (argc - optidx < 1) {
1159 error("You must specify a path after a %s command.",
1163 *path1 = xstrdup(argv[optidx]);
1164 /* Only "rm" globs */
1166 undo_glob_escape(*path1);
1169 if ((optidx = parse_df_flags(cmd, argv, argc, hflag,
1172 /* Default to current directory if no path specified */
1173 if (argc - optidx < 1)
1176 *path1 = xstrdup(argv[optidx]);
1177 undo_glob_escape(*path1);
1181 if ((optidx = parse_ls_flags(argv, argc, lflag)) == -1)
1183 /* Path is optional */
1184 if (argc - optidx > 0)
1185 *path1 = xstrdup(argv[optidx]);
1188 /* Skip ls command and following whitespace */
1189 cp = cp + strlen(cmd) + strspn(cp, WHITESPACE);
1191 /* Uses the rest of the line */
1198 /* Get numeric arg (mandatory) */
1199 if (argc - optidx < 1)
1202 l = strtol(argv[optidx], &cp2, base);
1203 if (cp2 == argv[optidx] || *cp2 != '\0' ||
1204 ((l == LONG_MIN || l == LONG_MAX) && errno == ERANGE) ||
1207 error("You must supply a numeric argument "
1208 "to the %s command.", cmd);
1212 if (cmdnum == I_LUMASK)
1214 /* Get pathname (mandatory) */
1215 if (argc - optidx < 2) {
1216 error("You must specify a path after a %s command.",
1220 *path1 = xstrdup(argv[optidx + 1]);
1230 fatal("Command not implemented");
1238 parse_dispatch_command(struct sftp_conn *conn, const char *cmd, char **pwd,
1241 char *path1, *path2, *tmp;
1242 int pflag, lflag, iflag, hflag, cmdnum, i;
1243 unsigned long n_arg;
1245 char path_buf[MAXPATHLEN];
1249 path1 = path2 = NULL;
1250 cmdnum = parse_args(&cmd, &pflag, &lflag, &iflag, &hflag, &n_arg,
1256 memset(&g, 0, sizeof(g));
1258 /* Perform command */
1264 /* Unrecognized command */
1268 err = process_get(conn, path1, path2, *pwd, pflag);
1271 err = process_put(conn, path1, path2, *pwd, pflag);
1274 path1 = make_absolute(path1, *pwd);
1275 path2 = make_absolute(path2, *pwd);
1276 err = do_rename(conn, path1, path2);
1279 path2 = make_absolute(path2, *pwd);
1280 err = do_symlink(conn, path1, path2);
1283 path1 = make_absolute(path1, *pwd);
1284 remote_glob(conn, path1, GLOB_NOCHECK, NULL, &g);
1285 for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
1286 printf("Removing %s\n", g.gl_pathv[i]);
1287 err = do_rm(conn, g.gl_pathv[i]);
1288 if (err != 0 && err_abort)
1293 path1 = make_absolute(path1, *pwd);
1295 a.flags |= SSH2_FILEXFER_ATTR_PERMISSIONS;
1297 err = do_mkdir(conn, path1, &a);
1300 path1 = make_absolute(path1, *pwd);
1301 err = do_rmdir(conn, path1);
1304 path1 = make_absolute(path1, *pwd);
1305 if ((tmp = do_realpath(conn, path1)) == NULL) {
1309 if ((aa = do_stat(conn, tmp, 0)) == NULL) {
1314 if (!(aa->flags & SSH2_FILEXFER_ATTR_PERMISSIONS)) {
1315 error("Can't change directory: Can't check target");
1320 if (!S_ISDIR(aa->perm)) {
1321 error("Can't change directory: \"%s\" is not "
1322 "a directory", tmp);
1332 do_globbed_ls(conn, *pwd, *pwd, lflag);
1336 /* Strip pwd off beginning of non-absolute paths */
1341 path1 = make_absolute(path1, *pwd);
1342 err = do_globbed_ls(conn, path1, tmp, lflag);
1345 /* Default to current directory if no path specified */
1347 path1 = xstrdup(*pwd);
1348 path1 = make_absolute(path1, *pwd);
1349 err = do_df(conn, path1, hflag, iflag);
1352 if (chdir(path1) == -1) {
1353 error("Couldn't change local directory to "
1354 "\"%s\": %s", path1, strerror(errno));
1359 if (mkdir(path1, 0777) == -1) {
1360 error("Couldn't create local directory "
1361 "\"%s\": %s", path1, strerror(errno));
1369 local_do_shell(cmd);
1373 printf("Local umask: %03lo\n", n_arg);
1376 path1 = make_absolute(path1, *pwd);
1378 a.flags |= SSH2_FILEXFER_ATTR_PERMISSIONS;
1380 remote_glob(conn, path1, GLOB_NOCHECK, NULL, &g);
1381 for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
1382 printf("Changing mode on %s\n", g.gl_pathv[i]);
1383 err = do_setstat(conn, g.gl_pathv[i], &a);
1384 if (err != 0 && err_abort)
1390 path1 = make_absolute(path1, *pwd);
1391 remote_glob(conn, path1, GLOB_NOCHECK, NULL, &g);
1392 for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
1393 if (!(aa = do_stat(conn, g.gl_pathv[i], 0))) {
1394 if (err != 0 && err_abort)
1399 if (!(aa->flags & SSH2_FILEXFER_ATTR_UIDGID)) {
1400 error("Can't get current ownership of "
1401 "remote file \"%s\"", g.gl_pathv[i]);
1402 if (err != 0 && err_abort)
1407 aa->flags &= SSH2_FILEXFER_ATTR_UIDGID;
1408 if (cmdnum == I_CHOWN) {
1409 printf("Changing owner on %s\n", g.gl_pathv[i]);
1412 printf("Changing group on %s\n", g.gl_pathv[i]);
1415 err = do_setstat(conn, g.gl_pathv[i], aa);
1416 if (err != 0 && err_abort)
1421 printf("Remote working directory: %s\n", *pwd);
1424 if (!getcwd(path_buf, sizeof(path_buf))) {
1425 error("Couldn't get local cwd: %s", strerror(errno));
1429 printf("Local working directory: %s\n", path_buf);
1432 /* Processed below */
1438 printf("SFTP protocol version %u\n", sftp_proto_version(conn));
1441 showprogress = !showprogress;
1443 printf("Progress meter enabled\n");
1445 printf("Progress meter disabled\n");
1448 fatal("%d is not implemented", cmdnum);
1458 /* If an unignored error occurs in batch mode we should abort. */
1459 if (err_abort && err != 0)
1461 else if (cmdnum == I_QUIT)
1469 prompt(EditLine *el)
1476 interactive_loop(int fd_in, int fd_out, char *file1, char *file2)
1481 struct sftp_conn *conn;
1482 int err, interactive;
1483 EditLine *el = NULL;
1487 extern char *__progname;
1489 if (!batchmode && isatty(STDIN_FILENO)) {
1490 if ((el = el_init(__progname, stdin, stdout, stderr)) == NULL)
1491 fatal("Couldn't initialise editline");
1492 if ((hl = history_init()) == NULL)
1493 fatal("Couldn't initialise editline history");
1494 history(hl, &hev, H_SETSIZE, 100);
1495 el_set(el, EL_HIST, history, hl);
1497 el_set(el, EL_PROMPT, prompt);
1498 el_set(el, EL_EDITOR, "emacs");
1499 el_set(el, EL_TERMINAL, NULL);
1500 el_set(el, EL_SIGNAL, 1);
1501 el_source(el, NULL);
1503 #endif /* USE_LIBEDIT */
1505 conn = do_init(fd_in, fd_out, copy_buffer_len, num_requests);
1507 fatal("Couldn't initialise connection to server");
1509 pwd = do_realpath(conn, ".");
1513 if (file1 != NULL) {
1514 dir = xstrdup(file1);
1515 dir = make_absolute(dir, pwd);
1517 if (remote_is_dir(conn, dir) && file2 == NULL) {
1518 printf("Changing to: %s\n", dir);
1519 snprintf(cmd, sizeof cmd, "cd \"%s\"", dir);
1520 if (parse_dispatch_command(conn, cmd, &pwd, 1) != 0) {
1528 snprintf(cmd, sizeof cmd, "get %s", dir);
1530 snprintf(cmd, sizeof cmd, "get %s %s", dir,
1533 err = parse_dispatch_command(conn, cmd, &pwd, 1);
1542 #if defined(HAVE_SETVBUF) && !defined(BROKEN_SETVBUF)
1543 setvbuf(stdout, NULL, _IOLBF, 0);
1544 setvbuf(infile, NULL, _IOLBF, 0);
1550 interactive = !batchmode && isatty(STDIN_FILENO);
1555 signal(SIGINT, SIG_IGN);
1560 if (fgets(cmd, sizeof(cmd), infile) == NULL) {
1565 if (!interactive) { /* Echo command */
1566 printf("sftp> %s", cmd);
1567 if (strlen(cmd) > 0 &&
1568 cmd[strlen(cmd) - 1] != '\n')
1576 if ((line = el_gets(el, &count)) == NULL || count <= 0) {
1580 history(hl, &hev, H_ENTER, line);
1581 if (strlcpy(cmd, line, sizeof(cmd)) >= sizeof(cmd)) {
1582 fprintf(stderr, "Error: input line too long\n");
1585 #endif /* USE_LIBEDIT */
1588 cp = strrchr(cmd, '\n');
1592 /* Handle user interrupts gracefully during commands */
1594 signal(SIGINT, cmd_interrupt);
1596 err = parse_dispatch_command(conn, cmd, &pwd, batchmode);
1606 #endif /* USE_LIBEDIT */
1608 /* err == 1 signifies normal "quit" exit */
1609 return (err >= 0 ? 0 : -1);
1613 connect_to_server(char *path, char **args, int *in, int *out)
1618 int pin[2], pout[2];
1620 if ((pipe(pin) == -1) || (pipe(pout) == -1))
1621 fatal("pipe: %s", strerror(errno));
1626 #else /* USE_PIPES */
1629 if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) == -1)
1630 fatal("socketpair: %s", strerror(errno));
1631 *in = *out = inout[0];
1632 c_in = c_out = inout[1];
1633 #endif /* USE_PIPES */
1635 if ((sshpid = fork()) == -1)
1636 fatal("fork: %s", strerror(errno));
1637 else if (sshpid == 0) {
1638 if ((dup2(c_in, STDIN_FILENO) == -1) ||
1639 (dup2(c_out, STDOUT_FILENO) == -1)) {
1640 fprintf(stderr, "dup2: %s\n", strerror(errno));
1649 * The underlying ssh is in the same process group, so we must
1650 * ignore SIGINT if we want to gracefully abort commands,
1651 * otherwise the signal will make it to the ssh process and
1654 signal(SIGINT, SIG_IGN);
1656 fprintf(stderr, "exec: %s: %s\n", path, strerror(errno));
1660 signal(SIGTERM, killchild);
1661 signal(SIGINT, killchild);
1662 signal(SIGHUP, killchild);
1670 extern char *__progname;
1673 "usage: %s [-1Cv] [-B buffer_size] [-b batchfile] [-F ssh_config]\n"
1674 " [-o ssh_option] [-P sftp_server_path] [-R num_requests]\n"
1675 " [-S program] [-s subsystem | sftp_server] host\n"
1676 " %s [[user@]host[:file [file]]]\n"
1677 " %s [[user@]host[:dir[/]]]\n"
1678 " %s -b batchfile [user@]host\n", __progname, __progname, __progname, __progname);
1683 main(int argc, char **argv)
1685 int in, out, ch, err;
1686 char *host, *userhost, *cp, *file2 = NULL;
1687 int debug_level = 0, sshver = 2;
1688 char *file1 = NULL, *sftp_server = NULL;
1689 char *ssh_program = _PATH_SSH_PROGRAM, *sftp_direct = NULL;
1690 LogLevel ll = SYSLOG_LEVEL_INFO;
1693 extern char *optarg;
1695 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
1698 __progname = ssh_get_progname(argv[0]);
1699 memset(&args, '\0', sizeof(args));
1701 addargs(&args, "%s", ssh_program);
1702 addargs(&args, "-oForwardX11 no");
1703 addargs(&args, "-oForwardAgent no");
1704 addargs(&args, "-oPermitLocalCommand no");
1705 addargs(&args, "-oClearAllForwardings yes");
1707 ll = SYSLOG_LEVEL_INFO;
1710 while ((ch = getopt(argc, argv, "1hvCo:s:S:b:B:F:P:R:")) != -1) {
1713 addargs(&args, "-C");
1716 if (debug_level < 3) {
1717 addargs(&args, "-v");
1718 ll = SYSLOG_LEVEL_DEBUG1 + debug_level;
1724 addargs(&args, "-%c%s", ch, optarg);
1728 if (sftp_server == NULL)
1729 sftp_server = _PATH_SFTP_SERVER;
1732 sftp_server = optarg;
1735 ssh_program = optarg;
1736 replacearg(&args, 0, "%s", ssh_program);
1740 fatal("Batch file already specified.");
1742 /* Allow "-" as stdin */
1743 if (strcmp(optarg, "-") != 0 &&
1744 (infile = fopen(optarg, "r")) == NULL)
1745 fatal("%s (%s).", strerror(errno), optarg);
1748 addargs(&args, "-obatchmode yes");
1751 sftp_direct = optarg;
1754 copy_buffer_len = strtol(optarg, &cp, 10);
1755 if (copy_buffer_len == 0 || *cp != '\0')
1756 fatal("Invalid buffer size \"%s\"", optarg);
1759 num_requests = strtol(optarg, &cp, 10);
1760 if (num_requests == 0 || *cp != '\0')
1761 fatal("Invalid number of requests \"%s\"",
1770 if (!isatty(STDERR_FILENO))
1773 log_init(argv[0], ll, SYSLOG_FACILITY_USER, 1);
1775 if (sftp_direct == NULL) {
1776 if (optind == argc || argc > (optind + 2))
1779 userhost = xstrdup(argv[optind]);
1780 file2 = argv[optind+1];
1782 if ((host = strrchr(userhost, '@')) == NULL)
1787 fprintf(stderr, "Missing username\n");
1790 addargs(&args, "-l%s", userhost);
1793 if ((cp = colon(host)) != NULL) {
1798 host = cleanhostname(host);
1800 fprintf(stderr, "Missing hostname\n");
1804 addargs(&args, "-oProtocol %d", sshver);
1806 /* no subsystem if the server-spec contains a '/' */
1807 if (sftp_server == NULL || strchr(sftp_server, '/') == NULL)
1808 addargs(&args, "-s");
1810 addargs(&args, "%s", host);
1811 addargs(&args, "%s", (sftp_server != NULL ?
1812 sftp_server : "sftp"));
1815 fprintf(stderr, "Connecting to %s...\n", host);
1816 connect_to_server(ssh_program, args.list, &in, &out);
1819 addargs(&args, "sftp-server");
1822 fprintf(stderr, "Attaching to %s...\n", sftp_direct);
1823 connect_to_server(sftp_direct, args.list, &in, &out);
1827 err = interactive_loop(in, out, file1, file2);
1829 #if !defined(USE_PIPES)
1830 shutdown(in, SHUT_RDWR);
1831 shutdown(out, SHUT_RDWR);
1839 while (waitpid(sshpid, NULL, 0) == -1)
1841 fatal("Couldn't wait for ssh process: %s",
1844 exit(err == 0 ? 0 : 1);