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.
18 RCSID("$OpenBSD: sftp.c,v 1.72 2006/02/10 00:27:13 stevesk Exp $");
20 #include <sys/ioctl.h>
28 typedef void EditLine;
34 #include "pathnames.h"
38 #include "sftp-common.h"
39 #include "sftp-client.h"
41 /* File to read commands from */
44 /* Are we in batchfile mode? */
47 /* Size of buffer used when copying files */
48 size_t copy_buffer_len = 32768;
50 /* Number of concurrent outstanding requests */
51 size_t num_requests = 16;
53 /* PID of ssh transport process */
54 static pid_t sshpid = -1;
56 /* This is set to 0 if the progressmeter is not desired. */
59 /* SIGINT received during command processing */
60 volatile sig_atomic_t interrupted = 0;
62 /* I wish qsort() took a separate ctx for the comparison function...*/
65 int remote_glob(struct sftp_conn *, const char *, int,
66 int (*)(const char *, int), glob_t *); /* proto for sftp-glob.c */
68 extern char *__progname;
70 /* Separators for interactive commands */
71 #define WHITESPACE " \t\r\n"
74 #define LS_LONG_VIEW 0x01 /* Full view ala ls -l */
75 #define LS_SHORT_VIEW 0x02 /* Single row view ala ls -1 */
76 #define LS_NUMERIC_VIEW 0x04 /* Long view with numeric uid/gid */
77 #define LS_NAME_SORT 0x08 /* Sort by name (default) */
78 #define LS_TIME_SORT 0x10 /* Sort by mtime */
79 #define LS_SIZE_SORT 0x20 /* Sort by file size */
80 #define LS_REVERSE_SORT 0x40 /* Reverse sort order */
81 #define LS_SHOW_ALL 0x80 /* Don't skip filenames starting with '.' */
83 #define VIEW_FLAGS (LS_LONG_VIEW|LS_SHORT_VIEW|LS_NUMERIC_VIEW)
84 #define SORT_FLAGS (LS_NAME_SORT|LS_TIME_SORT|LS_SIZE_SORT)
86 /* Commands for interactive mode */
109 #define I_PROGRESS 23
116 static const struct CMD cmds[] = {
119 { "chdir", I_CHDIR },
120 { "chgrp", I_CHGRP },
121 { "chmod", I_CHMOD },
122 { "chown", I_CHOWN },
129 { "lchdir", I_LCHDIR },
131 { "lmkdir", I_LMKDIR },
135 { "lumask", I_LUMASK },
136 { "mkdir", I_MKDIR },
137 { "progress", I_PROGRESS },
142 { "rename", I_RENAME },
144 { "rmdir", I_RMDIR },
145 { "symlink", I_SYMLINK },
146 { "version", I_VERSION },
152 int interactive_loop(int fd_in, int fd_out, char *file1, char *file2);
158 kill(sshpid, SIGTERM);
159 waitpid(sshpid, NULL, 0);
166 cmd_interrupt(int signo)
168 const char msg[] = "\rInterrupt \n";
169 int olderrno = errno;
171 write(STDERR_FILENO, msg, sizeof(msg) - 1);
179 printf("Available commands:\n");
180 printf("cd path Change remote directory to 'path'\n");
181 printf("lcd path Change local directory to 'path'\n");
182 printf("chgrp grp path Change group of file 'path' to 'grp'\n");
183 printf("chmod mode path Change permissions of file 'path' to 'mode'\n");
184 printf("chown own path Change owner of file 'path' to 'own'\n");
185 printf("help Display this help text\n");
186 printf("get remote-path [local-path] Download file\n");
187 printf("lls [ls-options [path]] Display local directory listing\n");
188 printf("ln oldpath newpath Symlink remote file\n");
189 printf("lmkdir path Create local directory\n");
190 printf("lpwd Print local working directory\n");
191 printf("ls [path] Display remote directory listing\n");
192 printf("lumask umask Set local umask to 'umask'\n");
193 printf("mkdir path Create remote directory\n");
194 printf("progress Toggle display of progress meter\n");
195 printf("put local-path [remote-path] Upload file\n");
196 printf("pwd Display remote working directory\n");
197 printf("exit Quit sftp\n");
198 printf("quit Quit sftp\n");
199 printf("rename oldpath newpath Rename remote file\n");
200 printf("rmdir path Remove remote directory\n");
201 printf("rm path Delete remote file\n");
202 printf("symlink oldpath newpath Symlink remote file\n");
203 printf("version Show SFTP version\n");
204 printf("!command Execute 'command' in local shell\n");
205 printf("! Escape to local shell\n");
206 printf("? Synonym for help\n");
210 local_do_shell(const char *args)
219 if ((shell = getenv("SHELL")) == NULL)
220 shell = _PATH_BSHELL;
222 if ((pid = fork()) == -1)
223 fatal("Couldn't fork: %s", strerror(errno));
226 /* XXX: child has pipe fds to ssh subproc open - issue? */
228 debug3("Executing %s -c \"%s\"", shell, args);
229 execl(shell, shell, "-c", args, (char *)NULL);
231 debug3("Executing %s", shell);
232 execl(shell, shell, (char *)NULL);
234 fprintf(stderr, "Couldn't execute \"%s\": %s\n", shell,
238 while (waitpid(pid, &status, 0) == -1)
240 fatal("Couldn't wait for child: %s", strerror(errno));
241 if (!WIFEXITED(status))
242 error("Shell exited abormally");
243 else if (WEXITSTATUS(status))
244 error("Shell exited with status %d", WEXITSTATUS(status));
248 local_do_ls(const char *args)
251 local_do_shell(_PATH_LS);
253 int len = strlen(_PATH_LS " ") + strlen(args) + 1;
254 char *buf = xmalloc(len);
256 /* XXX: quoting - rip quoting code from ftp? */
257 snprintf(buf, len, _PATH_LS " %s", args);
263 /* Strip one path (usually the pwd) from the start of another */
265 path_strip(char *path, char *strip)
270 return (xstrdup(path));
273 if (strncmp(path, strip, len) == 0) {
274 if (strip[len - 1] != '/' && path[len] == '/')
276 return (xstrdup(path + len));
279 return (xstrdup(path));
283 path_append(char *p1, char *p2)
286 int len = strlen(p1) + strlen(p2) + 2;
289 strlcpy(ret, p1, len);
290 if (p1[strlen(p1) - 1] != '/')
291 strlcat(ret, "/", len);
292 strlcat(ret, p2, len);
298 make_absolute(char *p, char *pwd)
303 if (p && p[0] != '/') {
304 abs_str = path_append(pwd, p);
312 infer_path(const char *p, char **ifp)
316 cp = strrchr(p, '/');
323 error("Invalid path");
327 *ifp = xstrdup(cp + 1);
332 parse_getput_flags(const char **cpp, int *pflag)
334 const char *cp = *cpp;
336 /* Check for flags */
337 if (cp[0] == '-' && cp[1] && strchr(WHITESPACE, cp[2])) {
344 error("Invalid flag -%c", cp[1]);
348 *cpp = cp + strspn(cp, WHITESPACE);
355 parse_ls_flags(const char **cpp, int *lflag)
357 const char *cp = *cpp;
360 *lflag = LS_NAME_SORT;
362 /* Check for flags */
363 if (cp++[0] == '-') {
364 for (; strchr(WHITESPACE, *cp) == NULL; cp++) {
367 *lflag &= ~VIEW_FLAGS;
368 *lflag |= LS_LONG_VIEW;
371 *lflag &= ~VIEW_FLAGS;
372 *lflag |= LS_SHORT_VIEW;
375 *lflag &= ~VIEW_FLAGS;
376 *lflag |= LS_NUMERIC_VIEW|LS_LONG_VIEW;
379 *lflag &= ~SORT_FLAGS;
380 *lflag |= LS_SIZE_SORT;
383 *lflag &= ~SORT_FLAGS;
384 *lflag |= LS_TIME_SORT;
387 *lflag |= LS_REVERSE_SORT;
390 *lflag &= ~SORT_FLAGS;
393 *lflag |= LS_SHOW_ALL;
396 error("Invalid flag -%c", *cp);
400 *cpp = cp + strspn(cp, WHITESPACE);
407 get_pathname(const char **cpp, char **path)
409 const char *cp = *cpp, *end;
413 cp += strspn(cp, WHITESPACE);
420 *path = xmalloc(strlen(cp) + 1);
422 /* Check for quoted filenames */
423 if (*cp == '\"' || *cp == '\'') {
426 /* Search for terminating quote, unescape some chars */
427 for (i = j = 0; i <= strlen(cp); i++) {
428 if (cp[i] == quot) { /* Found quote */
433 if (cp[i] == '\0') { /* End of string */
434 error("Unterminated quote");
437 if (cp[i] == '\\') { /* Escaped characters */
439 if (cp[i] != '\'' && cp[i] != '\"' &&
441 error("Bad escaped character '\\%c'",
446 (*path)[j++] = cp[i];
450 error("Empty quotes");
453 *cpp = cp + i + strspn(cp + i, WHITESPACE);
455 /* Read to end of filename */
456 end = strpbrk(cp, WHITESPACE);
458 end = strchr(cp, '\0');
459 *cpp = end + strspn(end, WHITESPACE);
461 memcpy(*path, cp, end - cp);
462 (*path)[end - cp] = '\0';
477 /* XXX: report errors? */
478 if (stat(path, &sb) == -1)
481 return(sb.st_mode & S_IFDIR);
489 if (stat(path, &sb) == -1)
490 fatal("stat %s: %s", path, strerror(errno));
492 return(S_ISREG(sb.st_mode));
496 remote_is_dir(struct sftp_conn *conn, char *path)
500 /* XXX: report errors? */
501 if ((a = do_stat(conn, path, 1)) == NULL)
503 if (!(a->flags & SSH2_FILEXFER_ATTR_PERMISSIONS))
505 return(a->perm & S_IFDIR);
509 process_get(struct sftp_conn *conn, char *src, char *dst, char *pwd, int pflag)
511 char *abs_src = NULL;
512 char *abs_dst = NULL;
518 abs_src = xstrdup(src);
519 abs_src = make_absolute(abs_src, pwd);
521 memset(&g, 0, sizeof(g));
522 debug3("Looking up %s", abs_src);
523 if (remote_glob(conn, abs_src, 0, NULL, &g)) {
524 error("File \"%s\" not found.", abs_src);
529 /* If multiple matches, dst must be a directory or unspecified */
530 if (g.gl_matchc > 1 && dst && !is_dir(dst)) {
531 error("Multiple files match, but \"%s\" is not a directory",
537 for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
538 if (infer_path(g.gl_pathv[i], &tmp)) {
543 if (g.gl_matchc == 1 && dst) {
544 /* If directory specified, append filename */
546 if (infer_path(g.gl_pathv[0], &tmp)) {
550 abs_dst = path_append(dst, tmp);
553 abs_dst = xstrdup(dst);
555 abs_dst = path_append(dst, tmp);
560 printf("Fetching %s to %s\n", g.gl_pathv[i], abs_dst);
561 if (do_download(conn, g.gl_pathv[i], abs_dst, pflag) == -1)
576 process_put(struct sftp_conn *conn, char *src, char *dst, char *pwd, int pflag)
578 char *tmp_dst = NULL;
579 char *abs_dst = NULL;
586 tmp_dst = xstrdup(dst);
587 tmp_dst = make_absolute(tmp_dst, pwd);
590 memset(&g, 0, sizeof(g));
591 debug3("Looking up %s", src);
592 if (glob(src, 0, NULL, &g)) {
593 error("File \"%s\" not found.", src);
598 /* If multiple matches, dst may be directory or unspecified */
599 if (g.gl_matchc > 1 && tmp_dst && !remote_is_dir(conn, tmp_dst)) {
600 error("Multiple files match, but \"%s\" is not a directory",
606 for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
607 if (!is_reg(g.gl_pathv[i])) {
608 error("skipping non-regular file %s",
612 if (infer_path(g.gl_pathv[i], &tmp)) {
617 if (g.gl_matchc == 1 && tmp_dst) {
618 /* If directory specified, append filename */
619 if (remote_is_dir(conn, tmp_dst)) {
620 if (infer_path(g.gl_pathv[0], &tmp)) {
624 abs_dst = path_append(tmp_dst, tmp);
627 abs_dst = xstrdup(tmp_dst);
629 } else if (tmp_dst) {
630 abs_dst = path_append(tmp_dst, tmp);
633 abs_dst = make_absolute(tmp, pwd);
635 printf("Uploading %s to %s\n", g.gl_pathv[i], abs_dst);
636 if (do_upload(conn, g.gl_pathv[i], abs_dst, pflag) == -1)
650 sdirent_comp(const void *aa, const void *bb)
652 SFTP_DIRENT *a = *(SFTP_DIRENT **)aa;
653 SFTP_DIRENT *b = *(SFTP_DIRENT **)bb;
654 int rmul = sort_flag & LS_REVERSE_SORT ? -1 : 1;
656 #define NCMP(a,b) (a == b ? 0 : (a < b ? 1 : -1))
657 if (sort_flag & LS_NAME_SORT)
658 return (rmul * strcmp(a->filename, b->filename));
659 else if (sort_flag & LS_TIME_SORT)
660 return (rmul * NCMP(a->a.mtime, b->a.mtime));
661 else if (sort_flag & LS_SIZE_SORT)
662 return (rmul * NCMP(a->a.size, b->a.size));
664 fatal("Unknown ls sort type");
667 /* sftp ls.1 replacement for directories */
669 do_ls_dir(struct sftp_conn *conn, char *path, char *strip_path, int lflag)
672 u_int c = 1, colspace = 0, columns = 1;
675 if ((n = do_readdir(conn, path, &d)) != 0)
678 if (!(lflag & LS_SHORT_VIEW)) {
679 u_int m = 0, width = 80;
683 /* Count entries for sort and find longest filename */
684 for (n = 0; d[n] != NULL; n++) {
685 if (d[n]->filename[0] != '.' || (lflag & LS_SHOW_ALL))
686 m = MAX(m, strlen(d[n]->filename));
689 /* Add any subpath that also needs to be counted */
690 tmp = path_strip(path, strip_path);
694 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) != -1)
697 columns = width / (m + 2);
698 columns = MAX(columns, 1);
699 colspace = width / columns;
700 colspace = MIN(colspace, width);
703 if (lflag & SORT_FLAGS) {
704 for (n = 0; d[n] != NULL; n++)
705 ; /* count entries */
706 sort_flag = lflag & (SORT_FLAGS|LS_REVERSE_SORT);
707 qsort(d, n, sizeof(*d), sdirent_comp);
710 for (n = 0; d[n] != NULL && !interrupted; n++) {
713 if (d[n]->filename[0] == '.' && !(lflag & LS_SHOW_ALL))
716 tmp = path_append(path, d[n]->filename);
717 fname = path_strip(tmp, strip_path);
720 if (lflag & LS_LONG_VIEW) {
721 if (lflag & LS_NUMERIC_VIEW) {
725 memset(&sb, 0, sizeof(sb));
726 attrib_to_stat(&d[n]->a, &sb);
727 lname = ls_file(fname, &sb, 1);
728 printf("%s\n", lname);
731 printf("%s\n", d[n]->longname);
733 printf("%-*s", colspace, fname);
744 if (!(lflag & LS_LONG_VIEW) && (c != 1))
747 free_sftp_dirents(d);
751 /* sftp ls.1 replacement which handles path globs */
753 do_globbed_ls(struct sftp_conn *conn, char *path, char *strip_path,
757 u_int i, c = 1, colspace = 0, columns = 1;
760 memset(&g, 0, sizeof(g));
762 if (remote_glob(conn, path, GLOB_MARK|GLOB_NOCHECK|GLOB_BRACE,
763 NULL, &g) || (g.gl_pathc && !g.gl_matchc)) {
766 error("Can't ls: \"%s\" not found", path);
774 * If the glob returns a single match and it is a directory,
775 * then just list its contents.
777 if (g.gl_matchc == 1) {
778 if ((a = do_lstat(conn, g.gl_pathv[0], 1)) == NULL) {
782 if ((a->flags & SSH2_FILEXFER_ATTR_PERMISSIONS) &&
786 err = do_ls_dir(conn, g.gl_pathv[0], strip_path, lflag);
792 if (!(lflag & LS_SHORT_VIEW)) {
793 u_int m = 0, width = 80;
796 /* Count entries for sort and find longest filename */
797 for (i = 0; g.gl_pathv[i]; i++)
798 m = MAX(m, strlen(g.gl_pathv[i]));
800 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) != -1)
803 columns = width / (m + 2);
804 columns = MAX(columns, 1);
805 colspace = width / columns;
808 for (i = 0; g.gl_pathv[i] && !interrupted; i++, a = NULL) {
811 fname = path_strip(g.gl_pathv[i], strip_path);
813 if (lflag & LS_LONG_VIEW) {
818 * XXX: this is slow - 1 roundtrip per path
819 * A solution to this is to fork glob() and
820 * build a sftp specific version which keeps the
821 * attribs (which currently get thrown away)
822 * that the server returns as well as the filenames.
824 memset(&sb, 0, sizeof(sb));
826 a = do_lstat(conn, g.gl_pathv[i], 1);
828 attrib_to_stat(a, &sb);
829 lname = ls_file(fname, &sb, 1);
830 printf("%s\n", lname);
833 printf("%-*s", colspace, fname);
843 if (!(lflag & LS_LONG_VIEW) && (c != 1))
854 parse_args(const char **cpp, int *pflag, int *lflag, int *iflag,
855 unsigned long *n_arg, char **path1, char **path2)
857 const char *cmd, *cp = *cpp;
863 /* Skip leading whitespace */
864 cp = cp + strspn(cp, WHITESPACE);
866 /* Ignore blank lines and lines which begin with comment '#' char */
867 if (*cp == '\0' || *cp == '#')
870 /* Check for leading '-' (disable error processing) */
877 /* Figure out which command we have */
878 for (i = 0; cmds[i].c; i++) {
879 int cmdlen = strlen(cmds[i].c);
881 /* Check for command followed by whitespace */
882 if (!strncasecmp(cp, cmds[i].c, cmdlen) &&
883 strchr(WHITESPACE, cp[cmdlen])) {
885 cp = cp + strspn(cp, WHITESPACE);
896 } else if (cmdnum == -1) {
897 error("Invalid command.");
901 /* Get arguments and parse flags */
902 *lflag = *pflag = *n_arg = 0;
903 *path1 = *path2 = NULL;
907 if (parse_getput_flags(&cp, pflag))
909 /* Get first pathname (mandatory) */
910 if (get_pathname(&cp, path1))
912 if (*path1 == NULL) {
913 error("You must specify at least one path after a "
917 /* Try to get second pathname (optional) */
918 if (get_pathname(&cp, path2))
923 if (get_pathname(&cp, path1))
925 if (get_pathname(&cp, path2))
927 if (!*path1 || !*path2) {
928 error("You must specify two paths after a %s "
939 /* Get pathname (mandatory) */
940 if (get_pathname(&cp, path1))
942 if (*path1 == NULL) {
943 error("You must specify a path after a %s command.",
949 if (parse_ls_flags(&cp, lflag))
951 /* Path is optional */
952 if (get_pathname(&cp, path1))
957 /* Uses the rest of the line */
965 /* Get numeric arg (mandatory) */
966 l = strtol(cp, &cp2, base);
967 if (cp2 == cp || ((l == LONG_MIN || l == LONG_MAX) &&
968 errno == ERANGE) || l < 0) {
969 error("You must supply a numeric argument "
970 "to the %s command.", cmd);
975 if (cmdnum == I_LUMASK && strchr(WHITESPACE, *cp))
977 if (cmdnum == I_LUMASK || !strchr(WHITESPACE, *cp)) {
978 error("You must supply a numeric argument "
979 "to the %s command.", cmd);
982 cp += strspn(cp, WHITESPACE);
984 /* Get pathname (mandatory) */
985 if (get_pathname(&cp, path1))
987 if (*path1 == NULL) {
988 error("You must specify a path after a %s command.",
1001 fatal("Command not implemented");
1009 parse_dispatch_command(struct sftp_conn *conn, const char *cmd, char **pwd,
1012 char *path1, *path2, *tmp;
1013 int pflag, lflag, iflag, cmdnum, i;
1014 unsigned long n_arg;
1016 char path_buf[MAXPATHLEN];
1020 path1 = path2 = NULL;
1021 cmdnum = parse_args(&cmd, &pflag, &lflag, &iflag, &n_arg,
1027 memset(&g, 0, sizeof(g));
1029 /* Perform command */
1035 /* Unrecognized command */
1039 err = process_get(conn, path1, path2, *pwd, pflag);
1042 err = process_put(conn, path1, path2, *pwd, pflag);
1045 path1 = make_absolute(path1, *pwd);
1046 path2 = make_absolute(path2, *pwd);
1047 err = do_rename(conn, path1, path2);
1050 path2 = make_absolute(path2, *pwd);
1051 err = do_symlink(conn, path1, path2);
1054 path1 = make_absolute(path1, *pwd);
1055 remote_glob(conn, path1, GLOB_NOCHECK, NULL, &g);
1056 for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
1057 printf("Removing %s\n", g.gl_pathv[i]);
1058 err = do_rm(conn, g.gl_pathv[i]);
1059 if (err != 0 && err_abort)
1064 path1 = make_absolute(path1, *pwd);
1066 a.flags |= SSH2_FILEXFER_ATTR_PERMISSIONS;
1068 err = do_mkdir(conn, path1, &a);
1071 path1 = make_absolute(path1, *pwd);
1072 err = do_rmdir(conn, path1);
1075 path1 = make_absolute(path1, *pwd);
1076 if ((tmp = do_realpath(conn, path1)) == NULL) {
1080 if ((aa = do_stat(conn, tmp, 0)) == NULL) {
1085 if (!(aa->flags & SSH2_FILEXFER_ATTR_PERMISSIONS)) {
1086 error("Can't change directory: Can't check target");
1091 if (!S_ISDIR(aa->perm)) {
1092 error("Can't change directory: \"%s\" is not "
1093 "a directory", tmp);
1103 do_globbed_ls(conn, *pwd, *pwd, lflag);
1107 /* Strip pwd off beginning of non-absolute paths */
1112 path1 = make_absolute(path1, *pwd);
1113 err = do_globbed_ls(conn, path1, tmp, lflag);
1116 if (chdir(path1) == -1) {
1117 error("Couldn't change local directory to "
1118 "\"%s\": %s", path1, strerror(errno));
1123 if (mkdir(path1, 0777) == -1) {
1124 error("Couldn't create local directory "
1125 "\"%s\": %s", path1, strerror(errno));
1133 local_do_shell(cmd);
1137 printf("Local umask: %03lo\n", n_arg);
1140 path1 = make_absolute(path1, *pwd);
1142 a.flags |= SSH2_FILEXFER_ATTR_PERMISSIONS;
1144 remote_glob(conn, path1, GLOB_NOCHECK, NULL, &g);
1145 for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
1146 printf("Changing mode on %s\n", g.gl_pathv[i]);
1147 err = do_setstat(conn, g.gl_pathv[i], &a);
1148 if (err != 0 && err_abort)
1154 path1 = make_absolute(path1, *pwd);
1155 remote_glob(conn, path1, GLOB_NOCHECK, NULL, &g);
1156 for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
1157 if (!(aa = do_stat(conn, g.gl_pathv[i], 0))) {
1158 if (err != 0 && err_abort)
1163 if (!(aa->flags & SSH2_FILEXFER_ATTR_UIDGID)) {
1164 error("Can't get current ownership of "
1165 "remote file \"%s\"", g.gl_pathv[i]);
1166 if (err != 0 && err_abort)
1171 aa->flags &= SSH2_FILEXFER_ATTR_UIDGID;
1172 if (cmdnum == I_CHOWN) {
1173 printf("Changing owner on %s\n", g.gl_pathv[i]);
1176 printf("Changing group on %s\n", g.gl_pathv[i]);
1179 err = do_setstat(conn, g.gl_pathv[i], aa);
1180 if (err != 0 && err_abort)
1185 printf("Remote working directory: %s\n", *pwd);
1188 if (!getcwd(path_buf, sizeof(path_buf))) {
1189 error("Couldn't get local cwd: %s", strerror(errno));
1193 printf("Local working directory: %s\n", path_buf);
1196 /* Processed below */
1202 printf("SFTP protocol version %u\n", sftp_proto_version(conn));
1205 showprogress = !showprogress;
1207 printf("Progress meter enabled\n");
1209 printf("Progress meter disabled\n");
1212 fatal("%d is not implemented", cmdnum);
1222 /* If an unignored error occurs in batch mode we should abort. */
1223 if (err_abort && err != 0)
1225 else if (cmdnum == I_QUIT)
1233 prompt(EditLine *el)
1240 interactive_loop(int fd_in, int fd_out, char *file1, char *file2)
1245 struct sftp_conn *conn;
1246 int err, interactive;
1247 EditLine *el = NULL;
1251 extern char *__progname;
1253 if (!batchmode && isatty(STDIN_FILENO)) {
1254 if ((el = el_init(__progname, stdin, stdout, stderr)) == NULL)
1255 fatal("Couldn't initialise editline");
1256 if ((hl = history_init()) == NULL)
1257 fatal("Couldn't initialise editline history");
1258 history(hl, &hev, H_SETSIZE, 100);
1259 el_set(el, EL_HIST, history, hl);
1261 el_set(el, EL_PROMPT, prompt);
1262 el_set(el, EL_EDITOR, "emacs");
1263 el_set(el, EL_TERMINAL, NULL);
1264 el_set(el, EL_SIGNAL, 1);
1265 el_source(el, NULL);
1267 #endif /* USE_LIBEDIT */
1269 conn = do_init(fd_in, fd_out, copy_buffer_len, num_requests);
1271 fatal("Couldn't initialise connection to server");
1273 pwd = do_realpath(conn, ".");
1277 if (file1 != NULL) {
1278 dir = xstrdup(file1);
1279 dir = make_absolute(dir, pwd);
1281 if (remote_is_dir(conn, dir) && file2 == NULL) {
1282 printf("Changing to: %s\n", dir);
1283 snprintf(cmd, sizeof cmd, "cd \"%s\"", dir);
1284 if (parse_dispatch_command(conn, cmd, &pwd, 1) != 0) {
1291 snprintf(cmd, sizeof cmd, "get %s", dir);
1293 snprintf(cmd, sizeof cmd, "get %s %s", dir,
1296 err = parse_dispatch_command(conn, cmd, &pwd, 1);
1304 #if defined(HAVE_SETVBUF) && !defined(BROKEN_SETVBUF)
1305 setvbuf(stdout, NULL, _IOLBF, 0);
1306 setvbuf(infile, NULL, _IOLBF, 0);
1312 interactive = !batchmode && isatty(STDIN_FILENO);
1317 signal(SIGINT, SIG_IGN);
1322 if (fgets(cmd, sizeof(cmd), infile) == NULL) {
1327 if (!interactive) { /* Echo command */
1328 printf("sftp> %s", cmd);
1329 if (strlen(cmd) > 0 &&
1330 cmd[strlen(cmd) - 1] != '\n')
1338 if ((line = el_gets(el, &count)) == NULL || count <= 0) {
1342 history(hl, &hev, H_ENTER, line);
1343 if (strlcpy(cmd, line, sizeof(cmd)) >= sizeof(cmd)) {
1344 fprintf(stderr, "Error: input line too long\n");
1347 #endif /* USE_LIBEDIT */
1350 cp = strrchr(cmd, '\n');
1354 /* Handle user interrupts gracefully during commands */
1356 signal(SIGINT, cmd_interrupt);
1358 err = parse_dispatch_command(conn, cmd, &pwd, batchmode);
1367 #endif /* USE_LIBEDIT */
1369 /* err == 1 signifies normal "quit" exit */
1370 return (err >= 0 ? 0 : -1);
1374 connect_to_server(char *path, char **args, int *in, int *out)
1379 int pin[2], pout[2];
1381 if ((pipe(pin) == -1) || (pipe(pout) == -1))
1382 fatal("pipe: %s", strerror(errno));
1387 #else /* USE_PIPES */
1390 if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) == -1)
1391 fatal("socketpair: %s", strerror(errno));
1392 *in = *out = inout[0];
1393 c_in = c_out = inout[1];
1394 #endif /* USE_PIPES */
1396 if ((sshpid = fork()) == -1)
1397 fatal("fork: %s", strerror(errno));
1398 else if (sshpid == 0) {
1399 if ((dup2(c_in, STDIN_FILENO) == -1) ||
1400 (dup2(c_out, STDOUT_FILENO) == -1)) {
1401 fprintf(stderr, "dup2: %s\n", strerror(errno));
1410 * The underlying ssh is in the same process group, so we must
1411 * ignore SIGINT if we want to gracefully abort commands,
1412 * otherwise the signal will make it to the ssh process and
1415 signal(SIGINT, SIG_IGN);
1417 fprintf(stderr, "exec: %s: %s\n", path, strerror(errno));
1421 signal(SIGTERM, killchild);
1422 signal(SIGINT, killchild);
1423 signal(SIGHUP, killchild);
1431 extern char *__progname;
1434 "usage: %s [-1Cv] [-B buffer_size] [-b batchfile] [-F ssh_config]\n"
1435 " [-o ssh_option] [-P sftp_server_path] [-R num_requests]\n"
1436 " [-S program] [-s subsystem | sftp_server] host\n"
1437 " %s [[user@]host[:file [file]]]\n"
1438 " %s [[user@]host[:dir[/]]]\n"
1439 " %s -b batchfile [user@]host\n", __progname, __progname, __progname, __progname);
1444 main(int argc, char **argv)
1446 int in, out, ch, err;
1447 char *host, *userhost, *cp, *file2 = NULL;
1448 int debug_level = 0, sshver = 2;
1449 char *file1 = NULL, *sftp_server = NULL;
1450 char *ssh_program = _PATH_SSH_PROGRAM, *sftp_direct = NULL;
1451 LogLevel ll = SYSLOG_LEVEL_INFO;
1454 extern char *optarg;
1456 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
1459 __progname = ssh_get_progname(argv[0]);
1460 memset(&args, '\0', sizeof(args));
1462 addargs(&args, ssh_program);
1463 addargs(&args, "-oForwardX11 no");
1464 addargs(&args, "-oForwardAgent no");
1465 addargs(&args, "-oPermitLocalCommand no");
1466 addargs(&args, "-oClearAllForwardings yes");
1468 ll = SYSLOG_LEVEL_INFO;
1471 while ((ch = getopt(argc, argv, "1hvCo:s:S:b:B:F:P:R:")) != -1) {
1474 addargs(&args, "-C");
1477 if (debug_level < 3) {
1478 addargs(&args, "-v");
1479 ll = SYSLOG_LEVEL_DEBUG1 + debug_level;
1485 addargs(&args, "-%c%s", ch, optarg);
1489 if (sftp_server == NULL)
1490 sftp_server = _PATH_SFTP_SERVER;
1493 sftp_server = optarg;
1496 ssh_program = optarg;
1497 replacearg(&args, 0, "%s", ssh_program);
1501 fatal("Batch file already specified.");
1503 /* Allow "-" as stdin */
1504 if (strcmp(optarg, "-") != 0 &&
1505 (infile = fopen(optarg, "r")) == NULL)
1506 fatal("%s (%s).", strerror(errno), optarg);
1509 addargs(&args, "-obatchmode yes");
1512 sftp_direct = optarg;
1515 copy_buffer_len = strtol(optarg, &cp, 10);
1516 if (copy_buffer_len == 0 || *cp != '\0')
1517 fatal("Invalid buffer size \"%s\"", optarg);
1520 num_requests = strtol(optarg, &cp, 10);
1521 if (num_requests == 0 || *cp != '\0')
1522 fatal("Invalid number of requests \"%s\"",
1531 if (!isatty(STDERR_FILENO))
1534 log_init(argv[0], ll, SYSLOG_FACILITY_USER, 1);
1536 if (sftp_direct == NULL) {
1537 if (optind == argc || argc > (optind + 2))
1540 userhost = xstrdup(argv[optind]);
1541 file2 = argv[optind+1];
1543 if ((host = strrchr(userhost, '@')) == NULL)
1548 fprintf(stderr, "Missing username\n");
1551 addargs(&args, "-l%s",userhost);
1554 if ((cp = colon(host)) != NULL) {
1559 host = cleanhostname(host);
1561 fprintf(stderr, "Missing hostname\n");
1565 addargs(&args, "-oProtocol %d", sshver);
1567 /* no subsystem if the server-spec contains a '/' */
1568 if (sftp_server == NULL || strchr(sftp_server, '/') == NULL)
1569 addargs(&args, "-s");
1571 addargs(&args, "%s", host);
1572 addargs(&args, "%s", (sftp_server != NULL ?
1573 sftp_server : "sftp"));
1576 fprintf(stderr, "Connecting to %s...\n", host);
1577 connect_to_server(ssh_program, args.list, &in, &out);
1580 addargs(&args, "sftp-server");
1583 fprintf(stderr, "Attaching to %s...\n", sftp_direct);
1584 connect_to_server(sftp_direct, args.list, &in, &out);
1588 err = interactive_loop(in, out, file1, file2);
1590 #if !defined(USE_PIPES)
1591 shutdown(in, SHUT_RDWR);
1592 shutdown(out, SHUT_RDWR);
1600 while (waitpid(sshpid, NULL, 0) == -1)
1602 fatal("Couldn't wait for ssh process: %s",
1605 exit(err == 0 ? 0 : 1);