2 * Copyright (c) 2001-2004 Damien Miller <djm@openbsd.org>
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
19 RCSID("$OpenBSD: sftp.c,v 1.52 2004/06/21 22:04:50 djm Exp $");
24 #include "pathnames.h"
28 #include "sftp-common.h"
29 #include "sftp-client.h"
31 /* File to read commands from */
34 /* Are we in batchfile mode? */
37 /* Size of buffer used when copying files */
38 size_t copy_buffer_len = 32768;
40 /* Number of concurrent outstanding requests */
41 size_t num_requests = 16;
43 /* PID of ssh transport process */
44 static pid_t sshpid = -1;
46 /* This is set to 0 if the progressmeter is not desired. */
49 /* SIGINT received during command processing */
50 volatile sig_atomic_t interrupted = 0;
52 /* I wish qsort() took a separate ctx for the comparison function...*/
55 int remote_glob(struct sftp_conn *, const char *, int,
56 int (*)(const char *, int), glob_t *); /* proto for sftp-glob.c */
58 #ifdef HAVE___PROGNAME
59 extern char *__progname;
64 /* Separators for interactive commands */
65 #define WHITESPACE " \t\r\n"
68 #define LONG_VIEW 0x01 /* Full view ala ls -l */
69 #define SHORT_VIEW 0x02 /* Single row view ala ls -1 */
70 #define NUMERIC_VIEW 0x04 /* Long view with numeric uid/gid */
71 #define NAME_SORT 0x08 /* Sort by name (default) */
72 #define TIME_SORT 0x10 /* Sort by mtime */
73 #define SIZE_SORT 0x20 /* Sort by file size */
74 #define REVERSE_SORT 0x40 /* Reverse sort order */
76 #define VIEW_FLAGS (LONG_VIEW|SHORT_VIEW|NUMERIC_VIEW)
77 #define SORT_FLAGS (NAME_SORT|TIME_SORT|SIZE_SORT)
79 /* Commands for interactive mode */
102 #define I_PROGRESS 23
109 static const struct CMD cmds[] = {
112 { "chdir", I_CHDIR },
113 { "chgrp", I_CHGRP },
114 { "chmod", I_CHMOD },
115 { "chown", I_CHOWN },
122 { "lchdir", I_LCHDIR },
124 { "lmkdir", I_LMKDIR },
128 { "lumask", I_LUMASK },
129 { "mkdir", I_MKDIR },
130 { "progress", I_PROGRESS },
135 { "rename", I_RENAME },
137 { "rmdir", I_RMDIR },
138 { "symlink", I_SYMLINK },
139 { "version", I_VERSION },
145 int interactive_loop(int fd_in, int fd_out, char *file1, char *file2);
151 kill(sshpid, SIGTERM);
157 cmd_interrupt(int signo)
159 const char msg[] = "\rInterrupt \n";
161 write(STDERR_FILENO, msg, sizeof(msg) - 1);
168 printf("Available commands:\n");
169 printf("cd path Change remote directory to 'path'\n");
170 printf("lcd path Change local directory to 'path'\n");
171 printf("chgrp grp path Change group of file 'path' to 'grp'\n");
172 printf("chmod mode path Change permissions of file 'path' to 'mode'\n");
173 printf("chown own path Change owner of file 'path' to 'own'\n");
174 printf("help Display this help text\n");
175 printf("get remote-path [local-path] Download file\n");
176 printf("lls [ls-options [path]] Display local directory listing\n");
177 printf("ln oldpath newpath Symlink remote file\n");
178 printf("lmkdir path Create local directory\n");
179 printf("lpwd Print local working directory\n");
180 printf("ls [path] Display remote directory listing\n");
181 printf("lumask umask Set local umask to 'umask'\n");
182 printf("mkdir path Create remote directory\n");
183 printf("progress Toggle display of progress meter\n");
184 printf("put local-path [remote-path] Upload file\n");
185 printf("pwd Display remote working directory\n");
186 printf("exit Quit sftp\n");
187 printf("quit Quit sftp\n");
188 printf("rename oldpath newpath Rename remote file\n");
189 printf("rmdir path Remove remote directory\n");
190 printf("rm path Delete remote file\n");
191 printf("symlink oldpath newpath Symlink remote file\n");
192 printf("version Show SFTP version\n");
193 printf("!command Execute 'command' in local shell\n");
194 printf("! Escape to local shell\n");
195 printf("? Synonym for help\n");
199 local_do_shell(const char *args)
208 if ((shell = getenv("SHELL")) == NULL)
209 shell = _PATH_BSHELL;
211 if ((pid = fork()) == -1)
212 fatal("Couldn't fork: %s", strerror(errno));
215 /* XXX: child has pipe fds to ssh subproc open - issue? */
217 debug3("Executing %s -c \"%s\"", shell, args);
218 execl(shell, shell, "-c", args, (char *)NULL);
220 debug3("Executing %s", shell);
221 execl(shell, shell, (char *)NULL);
223 fprintf(stderr, "Couldn't execute \"%s\": %s\n", shell,
227 while (waitpid(pid, &status, 0) == -1)
229 fatal("Couldn't wait for child: %s", strerror(errno));
230 if (!WIFEXITED(status))
231 error("Shell exited abormally");
232 else if (WEXITSTATUS(status))
233 error("Shell exited with status %d", WEXITSTATUS(status));
237 local_do_ls(const char *args)
240 local_do_shell(_PATH_LS);
242 int len = strlen(_PATH_LS " ") + strlen(args) + 1;
243 char *buf = xmalloc(len);
245 /* XXX: quoting - rip quoting code from ftp? */
246 snprintf(buf, len, _PATH_LS " %s", args);
252 /* Strip one path (usually the pwd) from the start of another */
254 path_strip(char *path, char *strip)
259 return (xstrdup(path));
262 if (strip != NULL && strncmp(path, strip, len) == 0) {
263 if (strip[len - 1] != '/' && path[len] == '/')
265 return (xstrdup(path + len));
268 return (xstrdup(path));
272 path_append(char *p1, char *p2)
275 int len = strlen(p1) + strlen(p2) + 2;
278 strlcpy(ret, p1, len);
279 if (p1[strlen(p1) - 1] != '/')
280 strlcat(ret, "/", len);
281 strlcat(ret, p2, len);
287 make_absolute(char *p, char *pwd)
292 if (p && p[0] != '/') {
293 abs_str = path_append(pwd, p);
301 infer_path(const char *p, char **ifp)
305 cp = strrchr(p, '/');
312 error("Invalid path");
316 *ifp = xstrdup(cp + 1);
321 parse_getput_flags(const char **cpp, int *pflag)
323 const char *cp = *cpp;
325 /* Check for flags */
326 if (cp[0] == '-' && cp[1] && strchr(WHITESPACE, cp[2])) {
333 error("Invalid flag -%c", cp[1]);
337 *cpp = cp + strspn(cp, WHITESPACE);
344 parse_ls_flags(const char **cpp, int *lflag)
346 const char *cp = *cpp;
351 /* Check for flags */
352 if (cp++[0] == '-') {
353 for(; strchr(WHITESPACE, *cp) == NULL; cp++) {
356 *lflag &= ~VIEW_FLAGS;
360 *lflag &= ~VIEW_FLAGS;
361 *lflag |= SHORT_VIEW;
364 *lflag &= ~VIEW_FLAGS;
365 *lflag |= NUMERIC_VIEW|LONG_VIEW;
368 *lflag &= ~SORT_FLAGS;
372 *lflag &= ~SORT_FLAGS;
376 *lflag |= REVERSE_SORT;
379 *lflag &= ~SORT_FLAGS;
382 error("Invalid flag -%c", *cp);
386 *cpp = cp + strspn(cp, WHITESPACE);
393 get_pathname(const char **cpp, char **path)
395 const char *cp = *cpp, *end;
399 cp += strspn(cp, WHITESPACE);
406 *path = xmalloc(strlen(cp) + 1);
408 /* Check for quoted filenames */
409 if (*cp == '\"' || *cp == '\'') {
412 /* Search for terminating quote, unescape some chars */
413 for (i = j = 0; i <= strlen(cp); i++) {
414 if (cp[i] == quot) { /* Found quote */
419 if (cp[i] == '\0') { /* End of string */
420 error("Unterminated quote");
423 if (cp[i] == '\\') { /* Escaped characters */
425 if (cp[i] != '\'' && cp[i] != '\"' &&
427 error("Bad escaped character '\%c'",
432 (*path)[j++] = cp[i];
436 error("Empty quotes");
439 *cpp = cp + i + strspn(cp + i, WHITESPACE);
441 /* Read to end of filename */
442 end = strpbrk(cp, WHITESPACE);
444 end = strchr(cp, '\0');
445 *cpp = end + strspn(end, WHITESPACE);
447 memcpy(*path, cp, end - cp);
448 (*path)[end - cp] = '\0';
463 /* XXX: report errors? */
464 if (stat(path, &sb) == -1)
467 return(sb.st_mode & S_IFDIR);
475 if (stat(path, &sb) == -1)
476 fatal("stat %s: %s", path, strerror(errno));
478 return(S_ISREG(sb.st_mode));
482 remote_is_dir(struct sftp_conn *conn, char *path)
486 /* XXX: report errors? */
487 if ((a = do_stat(conn, path, 1)) == NULL)
489 if (!(a->flags & SSH2_FILEXFER_ATTR_PERMISSIONS))
491 return(a->perm & S_IFDIR);
495 process_get(struct sftp_conn *conn, char *src, char *dst, char *pwd, int pflag)
497 char *abs_src = NULL;
498 char *abs_dst = NULL;
504 abs_src = xstrdup(src);
505 abs_src = make_absolute(abs_src, pwd);
507 memset(&g, 0, sizeof(g));
508 debug3("Looking up %s", abs_src);
509 if (remote_glob(conn, abs_src, 0, NULL, &g)) {
510 error("File \"%s\" not found.", abs_src);
515 /* If multiple matches, dst must be a directory or unspecified */
516 if (g.gl_matchc > 1 && dst && !is_dir(dst)) {
517 error("Multiple files match, but \"%s\" is not a directory",
523 for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
524 if (infer_path(g.gl_pathv[i], &tmp)) {
529 if (g.gl_matchc == 1 && dst) {
530 /* If directory specified, append filename */
532 if (infer_path(g.gl_pathv[0], &tmp)) {
536 abs_dst = path_append(dst, tmp);
539 abs_dst = xstrdup(dst);
541 abs_dst = path_append(dst, tmp);
546 printf("Fetching %s to %s\n", g.gl_pathv[i], abs_dst);
547 if (do_download(conn, g.gl_pathv[i], abs_dst, pflag) == -1)
562 process_put(struct sftp_conn *conn, char *src, char *dst, char *pwd, int pflag)
564 char *tmp_dst = NULL;
565 char *abs_dst = NULL;
572 tmp_dst = xstrdup(dst);
573 tmp_dst = make_absolute(tmp_dst, pwd);
576 memset(&g, 0, sizeof(g));
577 debug3("Looking up %s", src);
578 if (glob(src, 0, NULL, &g)) {
579 error("File \"%s\" not found.", src);
584 /* If multiple matches, dst may be directory or unspecified */
585 if (g.gl_matchc > 1 && tmp_dst && !remote_is_dir(conn, tmp_dst)) {
586 error("Multiple files match, but \"%s\" is not a directory",
592 for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
593 if (!is_reg(g.gl_pathv[i])) {
594 error("skipping non-regular file %s",
598 if (infer_path(g.gl_pathv[i], &tmp)) {
603 if (g.gl_matchc == 1 && tmp_dst) {
604 /* If directory specified, append filename */
605 if (remote_is_dir(conn, tmp_dst)) {
606 if (infer_path(g.gl_pathv[0], &tmp)) {
610 abs_dst = path_append(tmp_dst, tmp);
613 abs_dst = xstrdup(tmp_dst);
615 } else if (tmp_dst) {
616 abs_dst = path_append(tmp_dst, tmp);
619 abs_dst = make_absolute(tmp, pwd);
621 printf("Uploading %s to %s\n", g.gl_pathv[i], abs_dst);
622 if (do_upload(conn, g.gl_pathv[i], abs_dst, pflag) == -1)
636 sdirent_comp(const void *aa, const void *bb)
638 SFTP_DIRENT *a = *(SFTP_DIRENT **)aa;
639 SFTP_DIRENT *b = *(SFTP_DIRENT **)bb;
640 int rmul = sort_flag & REVERSE_SORT ? -1 : 1;
642 #define NCMP(a,b) (a == b ? 0 : (a < b ? 1 : -1))
643 if (sort_flag & NAME_SORT)
644 return (rmul * strcmp(a->filename, b->filename));
645 else if (sort_flag & TIME_SORT)
646 return (rmul * NCMP(a->a.mtime, b->a.mtime));
647 else if (sort_flag & SIZE_SORT)
648 return (rmul * NCMP(a->a.size, b->a.size));
650 fatal("Unknown ls sort type");
653 /* sftp ls.1 replacement for directories */
655 do_ls_dir(struct sftp_conn *conn, char *path, char *strip_path, int lflag)
657 int n, c = 1, colspace = 0, columns = 1;
660 if ((n = do_readdir(conn, path, &d)) != 0)
663 if (!(lflag & SHORT_VIEW)) {
664 int m = 0, width = 80;
668 /* Count entries for sort and find longest filename */
669 for (n = 0; d[n] != NULL; n++)
670 m = MAX(m, strlen(d[n]->filename));
672 /* Add any subpath that also needs to be counted */
673 tmp = path_strip(path, strip_path);
677 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) != -1)
680 columns = width / (m + 2);
681 columns = MAX(columns, 1);
682 colspace = width / columns;
683 colspace = MIN(colspace, width);
686 if (lflag & SORT_FLAGS) {
687 sort_flag = lflag & (SORT_FLAGS|REVERSE_SORT);
688 qsort(d, n, sizeof(*d), sdirent_comp);
691 for (n = 0; d[n] != NULL && !interrupted; n++) {
694 tmp = path_append(path, d[n]->filename);
695 fname = path_strip(tmp, strip_path);
698 if (lflag & LONG_VIEW) {
699 if (lflag & NUMERIC_VIEW) {
703 memset(&sb, 0, sizeof(sb));
704 attrib_to_stat(&d[n]->a, &sb);
705 lname = ls_file(fname, &sb, 1);
706 printf("%s\n", lname);
709 printf("%s\n", d[n]->longname);
711 printf("%-*s", colspace, fname);
722 if (!(lflag & LONG_VIEW) && (c != 1))
725 free_sftp_dirents(d);
729 /* sftp ls.1 replacement which handles path globs */
731 do_globbed_ls(struct sftp_conn *conn, char *path, char *strip_path,
735 int i, c = 1, colspace = 0, columns = 1;
738 memset(&g, 0, sizeof(g));
740 if (remote_glob(conn, path, GLOB_MARK|GLOB_NOCHECK|GLOB_BRACE,
742 error("Can't ls: \"%s\" not found", path);
750 * If the glob returns a single match, which is the same as the
751 * input glob, and it is a directory, then just list its contents
753 if (g.gl_pathc == 1 &&
754 strncmp(path, g.gl_pathv[0], strlen(g.gl_pathv[0]) - 1) == 0) {
755 if ((a = do_lstat(conn, path, 1)) == NULL) {
759 if ((a->flags & SSH2_FILEXFER_ATTR_PERMISSIONS) &&
762 return (do_ls_dir(conn, path, strip_path, lflag));
766 if (!(lflag & SHORT_VIEW)) {
767 int m = 0, width = 80;
770 /* Count entries for sort and find longest filename */
771 for (i = 0; g.gl_pathv[i]; i++)
772 m = MAX(m, strlen(g.gl_pathv[i]));
774 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) != -1)
777 columns = width / (m + 2);
778 columns = MAX(columns, 1);
779 colspace = width / columns;
782 for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
785 fname = path_strip(g.gl_pathv[i], strip_path);
787 if (lflag & LONG_VIEW) {
792 * XXX: this is slow - 1 roundtrip per path
793 * A solution to this is to fork glob() and
794 * build a sftp specific version which keeps the
795 * attribs (which currently get thrown away)
796 * that the server returns as well as the filenames.
798 memset(&sb, 0, sizeof(sb));
799 a = do_lstat(conn, g.gl_pathv[i], 1);
801 attrib_to_stat(a, &sb);
802 lname = ls_file(fname, &sb, 1);
803 printf("%s\n", lname);
806 printf("%-*s", colspace, fname);
816 if (!(lflag & LONG_VIEW) && (c != 1))
827 parse_args(const char **cpp, int *pflag, int *lflag, int *iflag,
828 unsigned long *n_arg, char **path1, char **path2)
830 const char *cmd, *cp = *cpp;
836 /* Skip leading whitespace */
837 cp = cp + strspn(cp, WHITESPACE);
839 /* Ignore blank lines and lines which begin with comment '#' char */
840 if (*cp == '\0' || *cp == '#')
843 /* Check for leading '-' (disable error processing) */
850 /* Figure out which command we have */
851 for (i = 0; cmds[i].c; i++) {
852 int cmdlen = strlen(cmds[i].c);
854 /* Check for command followed by whitespace */
855 if (!strncasecmp(cp, cmds[i].c, cmdlen) &&
856 strchr(WHITESPACE, cp[cmdlen])) {
858 cp = cp + strspn(cp, WHITESPACE);
869 } else if (cmdnum == -1) {
870 error("Invalid command.");
874 /* Get arguments and parse flags */
875 *lflag = *pflag = *n_arg = 0;
876 *path1 = *path2 = NULL;
880 if (parse_getput_flags(&cp, pflag))
882 /* Get first pathname (mandatory) */
883 if (get_pathname(&cp, path1))
885 if (*path1 == NULL) {
886 error("You must specify at least one path after a "
890 /* Try to get second pathname (optional) */
891 if (get_pathname(&cp, path2))
896 if (get_pathname(&cp, path1))
898 if (get_pathname(&cp, path2))
900 if (!*path1 || !*path2) {
901 error("You must specify two paths after a %s "
912 /* Get pathname (mandatory) */
913 if (get_pathname(&cp, path1))
915 if (*path1 == NULL) {
916 error("You must specify a path after a %s command.",
922 if (parse_ls_flags(&cp, lflag))
924 /* Path is optional */
925 if (get_pathname(&cp, path1))
930 /* Uses the rest of the line */
938 /* Get numeric arg (mandatory) */
939 l = strtol(cp, &cp2, base);
940 if (cp2 == cp || ((l == LONG_MIN || l == LONG_MAX) &&
941 errno == ERANGE) || l < 0) {
942 error("You must supply a numeric argument "
943 "to the %s command.", cmd);
948 if (cmdnum == I_LUMASK && strchr(WHITESPACE, *cp))
950 if (cmdnum == I_LUMASK || !strchr(WHITESPACE, *cp)) {
951 error("You must supply a numeric argument "
952 "to the %s command.", cmd);
955 cp += strspn(cp, WHITESPACE);
957 /* Get pathname (mandatory) */
958 if (get_pathname(&cp, path1))
960 if (*path1 == NULL) {
961 error("You must specify a path after a %s command.",
974 fatal("Command not implemented");
982 parse_dispatch_command(struct sftp_conn *conn, const char *cmd, char **pwd,
985 char *path1, *path2, *tmp;
986 int pflag, lflag, iflag, cmdnum, i;
989 char path_buf[MAXPATHLEN];
993 path1 = path2 = NULL;
994 cmdnum = parse_args(&cmd, &pflag, &lflag, &iflag, &n_arg,
1000 memset(&g, 0, sizeof(g));
1002 /* Perform command */
1008 /* Unrecognized command */
1012 err = process_get(conn, path1, path2, *pwd, pflag);
1015 err = process_put(conn, path1, path2, *pwd, pflag);
1018 path1 = make_absolute(path1, *pwd);
1019 path2 = make_absolute(path2, *pwd);
1020 err = do_rename(conn, path1, path2);
1023 path2 = make_absolute(path2, *pwd);
1024 err = do_symlink(conn, path1, path2);
1027 path1 = make_absolute(path1, *pwd);
1028 remote_glob(conn, path1, GLOB_NOCHECK, NULL, &g);
1029 for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
1030 printf("Removing %s\n", g.gl_pathv[i]);
1031 err = do_rm(conn, g.gl_pathv[i]);
1032 if (err != 0 && err_abort)
1037 path1 = make_absolute(path1, *pwd);
1039 a.flags |= SSH2_FILEXFER_ATTR_PERMISSIONS;
1041 err = do_mkdir(conn, path1, &a);
1044 path1 = make_absolute(path1, *pwd);
1045 err = do_rmdir(conn, path1);
1048 path1 = make_absolute(path1, *pwd);
1049 if ((tmp = do_realpath(conn, path1)) == NULL) {
1053 if ((aa = do_stat(conn, tmp, 0)) == NULL) {
1058 if (!(aa->flags & SSH2_FILEXFER_ATTR_PERMISSIONS)) {
1059 error("Can't change directory: Can't check target");
1064 if (!S_ISDIR(aa->perm)) {
1065 error("Can't change directory: \"%s\" is not "
1066 "a directory", tmp);
1076 do_globbed_ls(conn, *pwd, *pwd, lflag);
1080 /* Strip pwd off beginning of non-absolute paths */
1085 path1 = make_absolute(path1, *pwd);
1086 err = do_globbed_ls(conn, path1, tmp, lflag);
1089 if (chdir(path1) == -1) {
1090 error("Couldn't change local directory to "
1091 "\"%s\": %s", path1, strerror(errno));
1096 if (mkdir(path1, 0777) == -1) {
1097 error("Couldn't create local directory "
1098 "\"%s\": %s", path1, strerror(errno));
1106 local_do_shell(cmd);
1110 printf("Local umask: %03lo\n", n_arg);
1113 path1 = make_absolute(path1, *pwd);
1115 a.flags |= SSH2_FILEXFER_ATTR_PERMISSIONS;
1117 remote_glob(conn, path1, GLOB_NOCHECK, NULL, &g);
1118 for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
1119 printf("Changing mode on %s\n", g.gl_pathv[i]);
1120 err = do_setstat(conn, g.gl_pathv[i], &a);
1121 if (err != 0 && err_abort)
1127 path1 = make_absolute(path1, *pwd);
1128 remote_glob(conn, path1, GLOB_NOCHECK, NULL, &g);
1129 for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
1130 if (!(aa = do_stat(conn, g.gl_pathv[i], 0))) {
1131 if (err != 0 && err_abort)
1136 if (!(aa->flags & SSH2_FILEXFER_ATTR_UIDGID)) {
1137 error("Can't get current ownership of "
1138 "remote file \"%s\"", g.gl_pathv[i]);
1139 if (err != 0 && err_abort)
1144 aa->flags &= SSH2_FILEXFER_ATTR_UIDGID;
1145 if (cmdnum == I_CHOWN) {
1146 printf("Changing owner on %s\n", g.gl_pathv[i]);
1149 printf("Changing group on %s\n", g.gl_pathv[i]);
1152 err = do_setstat(conn, g.gl_pathv[i], aa);
1153 if (err != 0 && err_abort)
1158 printf("Remote working directory: %s\n", *pwd);
1161 if (!getcwd(path_buf, sizeof(path_buf))) {
1162 error("Couldn't get local cwd: %s", strerror(errno));
1166 printf("Local working directory: %s\n", path_buf);
1169 /* Processed below */
1175 printf("SFTP protocol version %u\n", sftp_proto_version(conn));
1178 showprogress = !showprogress;
1180 printf("Progress meter enabled\n");
1182 printf("Progress meter disabled\n");
1185 fatal("%d is not implemented", cmdnum);
1195 /* If an unignored error occurs in batch mode we should abort. */
1196 if (err_abort && err != 0)
1198 else if (cmdnum == I_QUIT)
1205 interactive_loop(int fd_in, int fd_out, char *file1, char *file2)
1210 struct sftp_conn *conn;
1213 conn = do_init(fd_in, fd_out, copy_buffer_len, num_requests);
1215 fatal("Couldn't initialise connection to server");
1217 pwd = do_realpath(conn, ".");
1221 if (file1 != NULL) {
1222 dir = xstrdup(file1);
1223 dir = make_absolute(dir, pwd);
1225 if (remote_is_dir(conn, dir) && file2 == NULL) {
1226 printf("Changing to: %s\n", dir);
1227 snprintf(cmd, sizeof cmd, "cd \"%s\"", dir);
1228 if (parse_dispatch_command(conn, cmd, &pwd, 1) != 0)
1232 snprintf(cmd, sizeof cmd, "get %s", dir);
1234 snprintf(cmd, sizeof cmd, "get %s %s", dir,
1237 err = parse_dispatch_command(conn, cmd, &pwd, 1);
1246 setvbuf(stdout, NULL, _IOLBF, 0);
1247 setvbuf(infile, NULL, _IOLBF, 0);
1257 signal(SIGINT, SIG_IGN);
1261 /* XXX: use libedit */
1262 if (fgets(cmd, sizeof(cmd), infile) == NULL) {
1267 if (batchmode) /* Echo command */
1270 cp = strrchr(cmd, '\n');
1274 /* Handle user interrupts gracefully during commands */
1276 signal(SIGINT, cmd_interrupt);
1278 err = parse_dispatch_command(conn, cmd, &pwd, batchmode);
1284 /* err == 1 signifies normal "quit" exit */
1285 return (err >= 0 ? 0 : -1);
1289 connect_to_server(char *path, char **args, int *in, int *out)
1294 int pin[2], pout[2];
1296 if ((pipe(pin) == -1) || (pipe(pout) == -1))
1297 fatal("pipe: %s", strerror(errno));
1302 #else /* USE_PIPES */
1305 if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) == -1)
1306 fatal("socketpair: %s", strerror(errno));
1307 *in = *out = inout[0];
1308 c_in = c_out = inout[1];
1309 #endif /* USE_PIPES */
1311 if ((sshpid = fork()) == -1)
1312 fatal("fork: %s", strerror(errno));
1313 else if (sshpid == 0) {
1314 if ((dup2(c_in, STDIN_FILENO) == -1) ||
1315 (dup2(c_out, STDOUT_FILENO) == -1)) {
1316 fprintf(stderr, "dup2: %s\n", strerror(errno));
1325 * The underlying ssh is in the same process group, so we must
1326 * ignore SIGINT if we want to gracefully abort commands,
1327 * otherwise the signal will make it to the ssh process and
1330 signal(SIGINT, SIG_IGN);
1332 fprintf(stderr, "exec: %s: %s\n", path, strerror(errno));
1336 signal(SIGTERM, killchild);
1337 signal(SIGINT, killchild);
1338 signal(SIGHUP, killchild);
1346 extern char *__progname;
1349 "usage: %s [-1Cv] [-B buffer_size] [-b batchfile] [-F ssh_config]\n"
1350 " [-o ssh_option] [-P sftp_server_path] [-R num_requests]\n"
1351 " [-S program] [-s subsystem | sftp_server] host\n"
1352 " %s [[user@]host[:file [file]]]\n"
1353 " %s [[user@]host[:dir[/]]]\n"
1354 " %s -b batchfile [user@]host\n", __progname, __progname, __progname, __progname);
1359 main(int argc, char **argv)
1361 int in, out, ch, err;
1362 char *host, *userhost, *cp, *file2 = NULL;
1363 int debug_level = 0, sshver = 2;
1364 char *file1 = NULL, *sftp_server = NULL;
1365 char *ssh_program = _PATH_SSH_PROGRAM, *sftp_direct = NULL;
1366 LogLevel ll = SYSLOG_LEVEL_INFO;
1369 extern char *optarg;
1371 __progname = ssh_get_progname(argv[0]);
1373 addargs(&args, "ssh"); /* overwritten with ssh_program */
1374 addargs(&args, "-oForwardX11 no");
1375 addargs(&args, "-oForwardAgent no");
1376 addargs(&args, "-oClearAllForwardings yes");
1378 ll = SYSLOG_LEVEL_INFO;
1381 while ((ch = getopt(argc, argv, "1hvCo:s:S:b:B:F:P:R:")) != -1) {
1384 addargs(&args, "-C");
1387 if (debug_level < 3) {
1388 addargs(&args, "-v");
1389 ll = SYSLOG_LEVEL_DEBUG1 + debug_level;
1395 addargs(&args, "-%c%s", ch, optarg);
1399 if (sftp_server == NULL)
1400 sftp_server = _PATH_SFTP_SERVER;
1403 sftp_server = optarg;
1406 ssh_program = optarg;
1410 fatal("Batch file already specified.");
1412 /* Allow "-" as stdin */
1413 if (strcmp(optarg, "-") != 0 &&
1414 (infile = fopen(optarg, "r")) == NULL)
1415 fatal("%s (%s).", strerror(errno), optarg);
1420 sftp_direct = optarg;
1423 copy_buffer_len = strtol(optarg, &cp, 10);
1424 if (copy_buffer_len == 0 || *cp != '\0')
1425 fatal("Invalid buffer size \"%s\"", optarg);
1428 num_requests = strtol(optarg, &cp, 10);
1429 if (num_requests == 0 || *cp != '\0')
1430 fatal("Invalid number of requests \"%s\"",
1439 if (!isatty(STDERR_FILENO))
1442 log_init(argv[0], ll, SYSLOG_FACILITY_USER, 1);
1444 if (sftp_direct == NULL) {
1445 if (optind == argc || argc > (optind + 2))
1448 userhost = xstrdup(argv[optind]);
1449 file2 = argv[optind+1];
1451 if ((host = strrchr(userhost, '@')) == NULL)
1456 fprintf(stderr, "Missing username\n");
1459 addargs(&args, "-l%s",userhost);
1462 if ((cp = colon(host)) != NULL) {
1467 host = cleanhostname(host);
1469 fprintf(stderr, "Missing hostname\n");
1473 addargs(&args, "-oProtocol %d", sshver);
1475 /* no subsystem if the server-spec contains a '/' */
1476 if (sftp_server == NULL || strchr(sftp_server, '/') == NULL)
1477 addargs(&args, "-s");
1479 addargs(&args, "%s", host);
1480 addargs(&args, "%s", (sftp_server != NULL ?
1481 sftp_server : "sftp"));
1482 args.list[0] = ssh_program;
1485 fprintf(stderr, "Connecting to %s...\n", host);
1486 connect_to_server(ssh_program, args.list, &in, &out);
1489 addargs(&args, "sftp-server");
1492 fprintf(stderr, "Attaching to %s...\n", sftp_direct);
1493 connect_to_server(sftp_direct, args.list, &in, &out);
1496 err = interactive_loop(in, out, file1, file2);
1498 #if !defined(USE_PIPES)
1499 shutdown(in, SHUT_RDWR);
1500 shutdown(out, SHUT_RDWR);
1508 while (waitpid(sshpid, NULL, 0) == -1)
1510 fatal("Couldn't wait for ssh process: %s",
1513 exit(err == 0 ? 0 : 1);