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.73 2006/02/10 01:44:27 stevesk Exp $");
20 #include <sys/ioctl.h>
21 #include <sys/types.h>
30 typedef void EditLine;
36 #include "pathnames.h"
40 #include "sftp-common.h"
41 #include "sftp-client.h"
43 /* File to read commands from */
46 /* Are we in batchfile mode? */
49 /* Size of buffer used when copying files */
50 size_t copy_buffer_len = 32768;
52 /* Number of concurrent outstanding requests */
53 size_t num_requests = 16;
55 /* PID of ssh transport process */
56 static pid_t sshpid = -1;
58 /* This is set to 0 if the progressmeter is not desired. */
61 /* SIGINT received during command processing */
62 volatile sig_atomic_t interrupted = 0;
64 /* I wish qsort() took a separate ctx for the comparison function...*/
67 int remote_glob(struct sftp_conn *, const char *, int,
68 int (*)(const char *, int), glob_t *); /* proto for sftp-glob.c */
70 extern char *__progname;
72 /* Separators for interactive commands */
73 #define WHITESPACE " \t\r\n"
76 #define LS_LONG_VIEW 0x01 /* Full view ala ls -l */
77 #define LS_SHORT_VIEW 0x02 /* Single row view ala ls -1 */
78 #define LS_NUMERIC_VIEW 0x04 /* Long view with numeric uid/gid */
79 #define LS_NAME_SORT 0x08 /* Sort by name (default) */
80 #define LS_TIME_SORT 0x10 /* Sort by mtime */
81 #define LS_SIZE_SORT 0x20 /* Sort by file size */
82 #define LS_REVERSE_SORT 0x40 /* Reverse sort order */
83 #define LS_SHOW_ALL 0x80 /* Don't skip filenames starting with '.' */
85 #define VIEW_FLAGS (LS_LONG_VIEW|LS_SHORT_VIEW|LS_NUMERIC_VIEW)
86 #define SORT_FLAGS (LS_NAME_SORT|LS_TIME_SORT|LS_SIZE_SORT)
88 /* Commands for interactive mode */
111 #define I_PROGRESS 23
118 static const struct CMD cmds[] = {
121 { "chdir", I_CHDIR },
122 { "chgrp", I_CHGRP },
123 { "chmod", I_CHMOD },
124 { "chown", I_CHOWN },
131 { "lchdir", I_LCHDIR },
133 { "lmkdir", I_LMKDIR },
137 { "lumask", I_LUMASK },
138 { "mkdir", I_MKDIR },
139 { "progress", I_PROGRESS },
144 { "rename", I_RENAME },
146 { "rmdir", I_RMDIR },
147 { "symlink", I_SYMLINK },
148 { "version", I_VERSION },
154 int interactive_loop(int fd_in, int fd_out, char *file1, char *file2);
160 kill(sshpid, SIGTERM);
161 waitpid(sshpid, NULL, 0);
168 cmd_interrupt(int signo)
170 const char msg[] = "\rInterrupt \n";
171 int olderrno = errno;
173 write(STDERR_FILENO, msg, sizeof(msg) - 1);
181 printf("Available commands:\n");
182 printf("cd path Change remote directory to 'path'\n");
183 printf("lcd path Change local directory to 'path'\n");
184 printf("chgrp grp path Change group of file 'path' to 'grp'\n");
185 printf("chmod mode path Change permissions of file 'path' to 'mode'\n");
186 printf("chown own path Change owner of file 'path' to 'own'\n");
187 printf("help Display this help text\n");
188 printf("get remote-path [local-path] Download file\n");
189 printf("lls [ls-options [path]] Display local directory listing\n");
190 printf("ln oldpath newpath Symlink remote file\n");
191 printf("lmkdir path Create local directory\n");
192 printf("lpwd Print local working directory\n");
193 printf("ls [path] Display remote directory listing\n");
194 printf("lumask umask Set local umask to 'umask'\n");
195 printf("mkdir path Create remote directory\n");
196 printf("progress Toggle display of progress meter\n");
197 printf("put local-path [remote-path] Upload file\n");
198 printf("pwd Display remote working directory\n");
199 printf("exit Quit sftp\n");
200 printf("quit Quit sftp\n");
201 printf("rename oldpath newpath Rename remote file\n");
202 printf("rmdir path Remove remote directory\n");
203 printf("rm path Delete remote file\n");
204 printf("symlink oldpath newpath Symlink remote file\n");
205 printf("version Show SFTP version\n");
206 printf("!command Execute 'command' in local shell\n");
207 printf("! Escape to local shell\n");
208 printf("? Synonym for help\n");
212 local_do_shell(const char *args)
221 if ((shell = getenv("SHELL")) == NULL)
222 shell = _PATH_BSHELL;
224 if ((pid = fork()) == -1)
225 fatal("Couldn't fork: %s", strerror(errno));
228 /* XXX: child has pipe fds to ssh subproc open - issue? */
230 debug3("Executing %s -c \"%s\"", shell, args);
231 execl(shell, shell, "-c", args, (char *)NULL);
233 debug3("Executing %s", shell);
234 execl(shell, shell, (char *)NULL);
236 fprintf(stderr, "Couldn't execute \"%s\": %s\n", shell,
240 while (waitpid(pid, &status, 0) == -1)
242 fatal("Couldn't wait for child: %s", strerror(errno));
243 if (!WIFEXITED(status))
244 error("Shell exited abormally");
245 else if (WEXITSTATUS(status))
246 error("Shell exited with status %d", WEXITSTATUS(status));
250 local_do_ls(const char *args)
253 local_do_shell(_PATH_LS);
255 int len = strlen(_PATH_LS " ") + strlen(args) + 1;
256 char *buf = xmalloc(len);
258 /* XXX: quoting - rip quoting code from ftp? */
259 snprintf(buf, len, _PATH_LS " %s", args);
265 /* Strip one path (usually the pwd) from the start of another */
267 path_strip(char *path, char *strip)
272 return (xstrdup(path));
275 if (strncmp(path, strip, len) == 0) {
276 if (strip[len - 1] != '/' && path[len] == '/')
278 return (xstrdup(path + len));
281 return (xstrdup(path));
285 path_append(char *p1, char *p2)
288 int len = strlen(p1) + strlen(p2) + 2;
291 strlcpy(ret, p1, len);
292 if (p1[strlen(p1) - 1] != '/')
293 strlcat(ret, "/", len);
294 strlcat(ret, p2, len);
300 make_absolute(char *p, char *pwd)
305 if (p && p[0] != '/') {
306 abs_str = path_append(pwd, p);
314 infer_path(const char *p, char **ifp)
318 cp = strrchr(p, '/');
325 error("Invalid path");
329 *ifp = xstrdup(cp + 1);
334 parse_getput_flags(const char **cpp, int *pflag)
336 const char *cp = *cpp;
338 /* Check for flags */
339 if (cp[0] == '-' && cp[1] && strchr(WHITESPACE, cp[2])) {
346 error("Invalid flag -%c", cp[1]);
350 *cpp = cp + strspn(cp, WHITESPACE);
357 parse_ls_flags(const char **cpp, int *lflag)
359 const char *cp = *cpp;
362 *lflag = LS_NAME_SORT;
364 /* Check for flags */
365 if (cp++[0] == '-') {
366 for (; strchr(WHITESPACE, *cp) == NULL; cp++) {
369 *lflag &= ~VIEW_FLAGS;
370 *lflag |= LS_LONG_VIEW;
373 *lflag &= ~VIEW_FLAGS;
374 *lflag |= LS_SHORT_VIEW;
377 *lflag &= ~VIEW_FLAGS;
378 *lflag |= LS_NUMERIC_VIEW|LS_LONG_VIEW;
381 *lflag &= ~SORT_FLAGS;
382 *lflag |= LS_SIZE_SORT;
385 *lflag &= ~SORT_FLAGS;
386 *lflag |= LS_TIME_SORT;
389 *lflag |= LS_REVERSE_SORT;
392 *lflag &= ~SORT_FLAGS;
395 *lflag |= LS_SHOW_ALL;
398 error("Invalid flag -%c", *cp);
402 *cpp = cp + strspn(cp, WHITESPACE);
409 get_pathname(const char **cpp, char **path)
411 const char *cp = *cpp, *end;
415 cp += strspn(cp, WHITESPACE);
422 *path = xmalloc(strlen(cp) + 1);
424 /* Check for quoted filenames */
425 if (*cp == '\"' || *cp == '\'') {
428 /* Search for terminating quote, unescape some chars */
429 for (i = j = 0; i <= strlen(cp); i++) {
430 if (cp[i] == quot) { /* Found quote */
435 if (cp[i] == '\0') { /* End of string */
436 error("Unterminated quote");
439 if (cp[i] == '\\') { /* Escaped characters */
441 if (cp[i] != '\'' && cp[i] != '\"' &&
443 error("Bad escaped character '\\%c'",
448 (*path)[j++] = cp[i];
452 error("Empty quotes");
455 *cpp = cp + i + strspn(cp + i, WHITESPACE);
457 /* Read to end of filename */
458 end = strpbrk(cp, WHITESPACE);
460 end = strchr(cp, '\0');
461 *cpp = end + strspn(end, WHITESPACE);
463 memcpy(*path, cp, end - cp);
464 (*path)[end - cp] = '\0';
479 /* XXX: report errors? */
480 if (stat(path, &sb) == -1)
483 return(sb.st_mode & S_IFDIR);
491 if (stat(path, &sb) == -1)
492 fatal("stat %s: %s", path, strerror(errno));
494 return(S_ISREG(sb.st_mode));
498 remote_is_dir(struct sftp_conn *conn, char *path)
502 /* XXX: report errors? */
503 if ((a = do_stat(conn, path, 1)) == NULL)
505 if (!(a->flags & SSH2_FILEXFER_ATTR_PERMISSIONS))
507 return(a->perm & S_IFDIR);
511 process_get(struct sftp_conn *conn, char *src, char *dst, char *pwd, int pflag)
513 char *abs_src = NULL;
514 char *abs_dst = NULL;
520 abs_src = xstrdup(src);
521 abs_src = make_absolute(abs_src, pwd);
523 memset(&g, 0, sizeof(g));
524 debug3("Looking up %s", abs_src);
525 if (remote_glob(conn, abs_src, 0, NULL, &g)) {
526 error("File \"%s\" not found.", abs_src);
531 /* If multiple matches, dst must be a directory or unspecified */
532 if (g.gl_matchc > 1 && dst && !is_dir(dst)) {
533 error("Multiple files match, but \"%s\" is not a directory",
539 for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
540 if (infer_path(g.gl_pathv[i], &tmp)) {
545 if (g.gl_matchc == 1 && dst) {
546 /* If directory specified, append filename */
548 if (infer_path(g.gl_pathv[0], &tmp)) {
552 abs_dst = path_append(dst, tmp);
555 abs_dst = xstrdup(dst);
557 abs_dst = path_append(dst, tmp);
562 printf("Fetching %s to %s\n", g.gl_pathv[i], abs_dst);
563 if (do_download(conn, g.gl_pathv[i], abs_dst, pflag) == -1)
578 process_put(struct sftp_conn *conn, char *src, char *dst, char *pwd, int pflag)
580 char *tmp_dst = NULL;
581 char *abs_dst = NULL;
588 tmp_dst = xstrdup(dst);
589 tmp_dst = make_absolute(tmp_dst, pwd);
592 memset(&g, 0, sizeof(g));
593 debug3("Looking up %s", src);
594 if (glob(src, 0, NULL, &g)) {
595 error("File \"%s\" not found.", src);
600 /* If multiple matches, dst may be directory or unspecified */
601 if (g.gl_matchc > 1 && tmp_dst && !remote_is_dir(conn, tmp_dst)) {
602 error("Multiple files match, but \"%s\" is not a directory",
608 for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
609 if (!is_reg(g.gl_pathv[i])) {
610 error("skipping non-regular file %s",
614 if (infer_path(g.gl_pathv[i], &tmp)) {
619 if (g.gl_matchc == 1 && tmp_dst) {
620 /* If directory specified, append filename */
621 if (remote_is_dir(conn, tmp_dst)) {
622 if (infer_path(g.gl_pathv[0], &tmp)) {
626 abs_dst = path_append(tmp_dst, tmp);
629 abs_dst = xstrdup(tmp_dst);
631 } else if (tmp_dst) {
632 abs_dst = path_append(tmp_dst, tmp);
635 abs_dst = make_absolute(tmp, pwd);
637 printf("Uploading %s to %s\n", g.gl_pathv[i], abs_dst);
638 if (do_upload(conn, g.gl_pathv[i], abs_dst, pflag) == -1)
652 sdirent_comp(const void *aa, const void *bb)
654 SFTP_DIRENT *a = *(SFTP_DIRENT **)aa;
655 SFTP_DIRENT *b = *(SFTP_DIRENT **)bb;
656 int rmul = sort_flag & LS_REVERSE_SORT ? -1 : 1;
658 #define NCMP(a,b) (a == b ? 0 : (a < b ? 1 : -1))
659 if (sort_flag & LS_NAME_SORT)
660 return (rmul * strcmp(a->filename, b->filename));
661 else if (sort_flag & LS_TIME_SORT)
662 return (rmul * NCMP(a->a.mtime, b->a.mtime));
663 else if (sort_flag & LS_SIZE_SORT)
664 return (rmul * NCMP(a->a.size, b->a.size));
666 fatal("Unknown ls sort type");
669 /* sftp ls.1 replacement for directories */
671 do_ls_dir(struct sftp_conn *conn, char *path, char *strip_path, int lflag)
674 u_int c = 1, colspace = 0, columns = 1;
677 if ((n = do_readdir(conn, path, &d)) != 0)
680 if (!(lflag & LS_SHORT_VIEW)) {
681 u_int m = 0, width = 80;
685 /* Count entries for sort and find longest filename */
686 for (n = 0; d[n] != NULL; n++) {
687 if (d[n]->filename[0] != '.' || (lflag & LS_SHOW_ALL))
688 m = MAX(m, strlen(d[n]->filename));
691 /* Add any subpath that also needs to be counted */
692 tmp = path_strip(path, strip_path);
696 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) != -1)
699 columns = width / (m + 2);
700 columns = MAX(columns, 1);
701 colspace = width / columns;
702 colspace = MIN(colspace, width);
705 if (lflag & SORT_FLAGS) {
706 for (n = 0; d[n] != NULL; n++)
707 ; /* count entries */
708 sort_flag = lflag & (SORT_FLAGS|LS_REVERSE_SORT);
709 qsort(d, n, sizeof(*d), sdirent_comp);
712 for (n = 0; d[n] != NULL && !interrupted; n++) {
715 if (d[n]->filename[0] == '.' && !(lflag & LS_SHOW_ALL))
718 tmp = path_append(path, d[n]->filename);
719 fname = path_strip(tmp, strip_path);
722 if (lflag & LS_LONG_VIEW) {
723 if (lflag & LS_NUMERIC_VIEW) {
727 memset(&sb, 0, sizeof(sb));
728 attrib_to_stat(&d[n]->a, &sb);
729 lname = ls_file(fname, &sb, 1);
730 printf("%s\n", lname);
733 printf("%s\n", d[n]->longname);
735 printf("%-*s", colspace, fname);
746 if (!(lflag & LS_LONG_VIEW) && (c != 1))
749 free_sftp_dirents(d);
753 /* sftp ls.1 replacement which handles path globs */
755 do_globbed_ls(struct sftp_conn *conn, char *path, char *strip_path,
759 u_int i, c = 1, colspace = 0, columns = 1;
762 memset(&g, 0, sizeof(g));
764 if (remote_glob(conn, path, GLOB_MARK|GLOB_NOCHECK|GLOB_BRACE,
765 NULL, &g) || (g.gl_pathc && !g.gl_matchc)) {
768 error("Can't ls: \"%s\" not found", path);
776 * If the glob returns a single match and it is a directory,
777 * then just list its contents.
779 if (g.gl_matchc == 1) {
780 if ((a = do_lstat(conn, g.gl_pathv[0], 1)) == NULL) {
784 if ((a->flags & SSH2_FILEXFER_ATTR_PERMISSIONS) &&
788 err = do_ls_dir(conn, g.gl_pathv[0], strip_path, lflag);
794 if (!(lflag & LS_SHORT_VIEW)) {
795 u_int m = 0, width = 80;
798 /* Count entries for sort and find longest filename */
799 for (i = 0; g.gl_pathv[i]; i++)
800 m = MAX(m, strlen(g.gl_pathv[i]));
802 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) != -1)
805 columns = width / (m + 2);
806 columns = MAX(columns, 1);
807 colspace = width / columns;
810 for (i = 0; g.gl_pathv[i] && !interrupted; i++, a = NULL) {
813 fname = path_strip(g.gl_pathv[i], strip_path);
815 if (lflag & LS_LONG_VIEW) {
820 * XXX: this is slow - 1 roundtrip per path
821 * A solution to this is to fork glob() and
822 * build a sftp specific version which keeps the
823 * attribs (which currently get thrown away)
824 * that the server returns as well as the filenames.
826 memset(&sb, 0, sizeof(sb));
828 a = do_lstat(conn, g.gl_pathv[i], 1);
830 attrib_to_stat(a, &sb);
831 lname = ls_file(fname, &sb, 1);
832 printf("%s\n", lname);
835 printf("%-*s", colspace, fname);
845 if (!(lflag & LS_LONG_VIEW) && (c != 1))
856 parse_args(const char **cpp, int *pflag, int *lflag, int *iflag,
857 unsigned long *n_arg, char **path1, char **path2)
859 const char *cmd, *cp = *cpp;
865 /* Skip leading whitespace */
866 cp = cp + strspn(cp, WHITESPACE);
868 /* Ignore blank lines and lines which begin with comment '#' char */
869 if (*cp == '\0' || *cp == '#')
872 /* Check for leading '-' (disable error processing) */
879 /* Figure out which command we have */
880 for (i = 0; cmds[i].c; i++) {
881 int cmdlen = strlen(cmds[i].c);
883 /* Check for command followed by whitespace */
884 if (!strncasecmp(cp, cmds[i].c, cmdlen) &&
885 strchr(WHITESPACE, cp[cmdlen])) {
887 cp = cp + strspn(cp, WHITESPACE);
898 } else if (cmdnum == -1) {
899 error("Invalid command.");
903 /* Get arguments and parse flags */
904 *lflag = *pflag = *n_arg = 0;
905 *path1 = *path2 = NULL;
909 if (parse_getput_flags(&cp, pflag))
911 /* Get first pathname (mandatory) */
912 if (get_pathname(&cp, path1))
914 if (*path1 == NULL) {
915 error("You must specify at least one path after a "
919 /* Try to get second pathname (optional) */
920 if (get_pathname(&cp, path2))
925 if (get_pathname(&cp, path1))
927 if (get_pathname(&cp, path2))
929 if (!*path1 || !*path2) {
930 error("You must specify two paths after a %s "
941 /* Get pathname (mandatory) */
942 if (get_pathname(&cp, path1))
944 if (*path1 == NULL) {
945 error("You must specify a path after a %s command.",
951 if (parse_ls_flags(&cp, lflag))
953 /* Path is optional */
954 if (get_pathname(&cp, path1))
959 /* Uses the rest of the line */
967 /* Get numeric arg (mandatory) */
968 l = strtol(cp, &cp2, base);
969 if (cp2 == cp || ((l == LONG_MIN || l == LONG_MAX) &&
970 errno == ERANGE) || l < 0) {
971 error("You must supply a numeric argument "
972 "to the %s command.", cmd);
977 if (cmdnum == I_LUMASK && strchr(WHITESPACE, *cp))
979 if (cmdnum == I_LUMASK || !strchr(WHITESPACE, *cp)) {
980 error("You must supply a numeric argument "
981 "to the %s command.", cmd);
984 cp += strspn(cp, WHITESPACE);
986 /* Get pathname (mandatory) */
987 if (get_pathname(&cp, path1))
989 if (*path1 == NULL) {
990 error("You must specify a path after a %s command.",
1003 fatal("Command not implemented");
1011 parse_dispatch_command(struct sftp_conn *conn, const char *cmd, char **pwd,
1014 char *path1, *path2, *tmp;
1015 int pflag, lflag, iflag, cmdnum, i;
1016 unsigned long n_arg;
1018 char path_buf[MAXPATHLEN];
1022 path1 = path2 = NULL;
1023 cmdnum = parse_args(&cmd, &pflag, &lflag, &iflag, &n_arg,
1029 memset(&g, 0, sizeof(g));
1031 /* Perform command */
1037 /* Unrecognized command */
1041 err = process_get(conn, path1, path2, *pwd, pflag);
1044 err = process_put(conn, path1, path2, *pwd, pflag);
1047 path1 = make_absolute(path1, *pwd);
1048 path2 = make_absolute(path2, *pwd);
1049 err = do_rename(conn, path1, path2);
1052 path2 = make_absolute(path2, *pwd);
1053 err = do_symlink(conn, path1, path2);
1056 path1 = make_absolute(path1, *pwd);
1057 remote_glob(conn, path1, GLOB_NOCHECK, NULL, &g);
1058 for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
1059 printf("Removing %s\n", g.gl_pathv[i]);
1060 err = do_rm(conn, g.gl_pathv[i]);
1061 if (err != 0 && err_abort)
1066 path1 = make_absolute(path1, *pwd);
1068 a.flags |= SSH2_FILEXFER_ATTR_PERMISSIONS;
1070 err = do_mkdir(conn, path1, &a);
1073 path1 = make_absolute(path1, *pwd);
1074 err = do_rmdir(conn, path1);
1077 path1 = make_absolute(path1, *pwd);
1078 if ((tmp = do_realpath(conn, path1)) == NULL) {
1082 if ((aa = do_stat(conn, tmp, 0)) == NULL) {
1087 if (!(aa->flags & SSH2_FILEXFER_ATTR_PERMISSIONS)) {
1088 error("Can't change directory: Can't check target");
1093 if (!S_ISDIR(aa->perm)) {
1094 error("Can't change directory: \"%s\" is not "
1095 "a directory", tmp);
1105 do_globbed_ls(conn, *pwd, *pwd, lflag);
1109 /* Strip pwd off beginning of non-absolute paths */
1114 path1 = make_absolute(path1, *pwd);
1115 err = do_globbed_ls(conn, path1, tmp, lflag);
1118 if (chdir(path1) == -1) {
1119 error("Couldn't change local directory to "
1120 "\"%s\": %s", path1, strerror(errno));
1125 if (mkdir(path1, 0777) == -1) {
1126 error("Couldn't create local directory "
1127 "\"%s\": %s", path1, strerror(errno));
1135 local_do_shell(cmd);
1139 printf("Local umask: %03lo\n", n_arg);
1142 path1 = make_absolute(path1, *pwd);
1144 a.flags |= SSH2_FILEXFER_ATTR_PERMISSIONS;
1146 remote_glob(conn, path1, GLOB_NOCHECK, NULL, &g);
1147 for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
1148 printf("Changing mode on %s\n", g.gl_pathv[i]);
1149 err = do_setstat(conn, g.gl_pathv[i], &a);
1150 if (err != 0 && err_abort)
1156 path1 = make_absolute(path1, *pwd);
1157 remote_glob(conn, path1, GLOB_NOCHECK, NULL, &g);
1158 for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
1159 if (!(aa = do_stat(conn, g.gl_pathv[i], 0))) {
1160 if (err != 0 && err_abort)
1165 if (!(aa->flags & SSH2_FILEXFER_ATTR_UIDGID)) {
1166 error("Can't get current ownership of "
1167 "remote file \"%s\"", g.gl_pathv[i]);
1168 if (err != 0 && err_abort)
1173 aa->flags &= SSH2_FILEXFER_ATTR_UIDGID;
1174 if (cmdnum == I_CHOWN) {
1175 printf("Changing owner on %s\n", g.gl_pathv[i]);
1178 printf("Changing group on %s\n", g.gl_pathv[i]);
1181 err = do_setstat(conn, g.gl_pathv[i], aa);
1182 if (err != 0 && err_abort)
1187 printf("Remote working directory: %s\n", *pwd);
1190 if (!getcwd(path_buf, sizeof(path_buf))) {
1191 error("Couldn't get local cwd: %s", strerror(errno));
1195 printf("Local working directory: %s\n", path_buf);
1198 /* Processed below */
1204 printf("SFTP protocol version %u\n", sftp_proto_version(conn));
1207 showprogress = !showprogress;
1209 printf("Progress meter enabled\n");
1211 printf("Progress meter disabled\n");
1214 fatal("%d is not implemented", cmdnum);
1224 /* If an unignored error occurs in batch mode we should abort. */
1225 if (err_abort && err != 0)
1227 else if (cmdnum == I_QUIT)
1235 prompt(EditLine *el)
1242 interactive_loop(int fd_in, int fd_out, char *file1, char *file2)
1247 struct sftp_conn *conn;
1248 int err, interactive;
1249 EditLine *el = NULL;
1253 extern char *__progname;
1255 if (!batchmode && isatty(STDIN_FILENO)) {
1256 if ((el = el_init(__progname, stdin, stdout, stderr)) == NULL)
1257 fatal("Couldn't initialise editline");
1258 if ((hl = history_init()) == NULL)
1259 fatal("Couldn't initialise editline history");
1260 history(hl, &hev, H_SETSIZE, 100);
1261 el_set(el, EL_HIST, history, hl);
1263 el_set(el, EL_PROMPT, prompt);
1264 el_set(el, EL_EDITOR, "emacs");
1265 el_set(el, EL_TERMINAL, NULL);
1266 el_set(el, EL_SIGNAL, 1);
1267 el_source(el, NULL);
1269 #endif /* USE_LIBEDIT */
1271 conn = do_init(fd_in, fd_out, copy_buffer_len, num_requests);
1273 fatal("Couldn't initialise connection to server");
1275 pwd = do_realpath(conn, ".");
1279 if (file1 != NULL) {
1280 dir = xstrdup(file1);
1281 dir = make_absolute(dir, pwd);
1283 if (remote_is_dir(conn, dir) && file2 == NULL) {
1284 printf("Changing to: %s\n", dir);
1285 snprintf(cmd, sizeof cmd, "cd \"%s\"", dir);
1286 if (parse_dispatch_command(conn, cmd, &pwd, 1) != 0) {
1293 snprintf(cmd, sizeof cmd, "get %s", dir);
1295 snprintf(cmd, sizeof cmd, "get %s %s", dir,
1298 err = parse_dispatch_command(conn, cmd, &pwd, 1);
1306 #if defined(HAVE_SETVBUF) && !defined(BROKEN_SETVBUF)
1307 setvbuf(stdout, NULL, _IOLBF, 0);
1308 setvbuf(infile, NULL, _IOLBF, 0);
1314 interactive = !batchmode && isatty(STDIN_FILENO);
1319 signal(SIGINT, SIG_IGN);
1324 if (fgets(cmd, sizeof(cmd), infile) == NULL) {
1329 if (!interactive) { /* Echo command */
1330 printf("sftp> %s", cmd);
1331 if (strlen(cmd) > 0 &&
1332 cmd[strlen(cmd) - 1] != '\n')
1340 if ((line = el_gets(el, &count)) == NULL || count <= 0) {
1344 history(hl, &hev, H_ENTER, line);
1345 if (strlcpy(cmd, line, sizeof(cmd)) >= sizeof(cmd)) {
1346 fprintf(stderr, "Error: input line too long\n");
1349 #endif /* USE_LIBEDIT */
1352 cp = strrchr(cmd, '\n');
1356 /* Handle user interrupts gracefully during commands */
1358 signal(SIGINT, cmd_interrupt);
1360 err = parse_dispatch_command(conn, cmd, &pwd, batchmode);
1369 #endif /* USE_LIBEDIT */
1371 /* err == 1 signifies normal "quit" exit */
1372 return (err >= 0 ? 0 : -1);
1376 connect_to_server(char *path, char **args, int *in, int *out)
1381 int pin[2], pout[2];
1383 if ((pipe(pin) == -1) || (pipe(pout) == -1))
1384 fatal("pipe: %s", strerror(errno));
1389 #else /* USE_PIPES */
1392 if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) == -1)
1393 fatal("socketpair: %s", strerror(errno));
1394 *in = *out = inout[0];
1395 c_in = c_out = inout[1];
1396 #endif /* USE_PIPES */
1398 if ((sshpid = fork()) == -1)
1399 fatal("fork: %s", strerror(errno));
1400 else if (sshpid == 0) {
1401 if ((dup2(c_in, STDIN_FILENO) == -1) ||
1402 (dup2(c_out, STDOUT_FILENO) == -1)) {
1403 fprintf(stderr, "dup2: %s\n", strerror(errno));
1412 * The underlying ssh is in the same process group, so we must
1413 * ignore SIGINT if we want to gracefully abort commands,
1414 * otherwise the signal will make it to the ssh process and
1417 signal(SIGINT, SIG_IGN);
1419 fprintf(stderr, "exec: %s: %s\n", path, strerror(errno));
1423 signal(SIGTERM, killchild);
1424 signal(SIGINT, killchild);
1425 signal(SIGHUP, killchild);
1433 extern char *__progname;
1436 "usage: %s [-1Cv] [-B buffer_size] [-b batchfile] [-F ssh_config]\n"
1437 " [-o ssh_option] [-P sftp_server_path] [-R num_requests]\n"
1438 " [-S program] [-s subsystem | sftp_server] host\n"
1439 " %s [[user@]host[:file [file]]]\n"
1440 " %s [[user@]host[:dir[/]]]\n"
1441 " %s -b batchfile [user@]host\n", __progname, __progname, __progname, __progname);
1446 main(int argc, char **argv)
1448 int in, out, ch, err;
1449 char *host, *userhost, *cp, *file2 = NULL;
1450 int debug_level = 0, sshver = 2;
1451 char *file1 = NULL, *sftp_server = NULL;
1452 char *ssh_program = _PATH_SSH_PROGRAM, *sftp_direct = NULL;
1453 LogLevel ll = SYSLOG_LEVEL_INFO;
1456 extern char *optarg;
1458 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
1461 __progname = ssh_get_progname(argv[0]);
1462 memset(&args, '\0', sizeof(args));
1464 addargs(&args, ssh_program);
1465 addargs(&args, "-oForwardX11 no");
1466 addargs(&args, "-oForwardAgent no");
1467 addargs(&args, "-oPermitLocalCommand no");
1468 addargs(&args, "-oClearAllForwardings yes");
1470 ll = SYSLOG_LEVEL_INFO;
1473 while ((ch = getopt(argc, argv, "1hvCo:s:S:b:B:F:P:R:")) != -1) {
1476 addargs(&args, "-C");
1479 if (debug_level < 3) {
1480 addargs(&args, "-v");
1481 ll = SYSLOG_LEVEL_DEBUG1 + debug_level;
1487 addargs(&args, "-%c%s", ch, optarg);
1491 if (sftp_server == NULL)
1492 sftp_server = _PATH_SFTP_SERVER;
1495 sftp_server = optarg;
1498 ssh_program = optarg;
1499 replacearg(&args, 0, "%s", ssh_program);
1503 fatal("Batch file already specified.");
1505 /* Allow "-" as stdin */
1506 if (strcmp(optarg, "-") != 0 &&
1507 (infile = fopen(optarg, "r")) == NULL)
1508 fatal("%s (%s).", strerror(errno), optarg);
1511 addargs(&args, "-obatchmode yes");
1514 sftp_direct = optarg;
1517 copy_buffer_len = strtol(optarg, &cp, 10);
1518 if (copy_buffer_len == 0 || *cp != '\0')
1519 fatal("Invalid buffer size \"%s\"", optarg);
1522 num_requests = strtol(optarg, &cp, 10);
1523 if (num_requests == 0 || *cp != '\0')
1524 fatal("Invalid number of requests \"%s\"",
1533 if (!isatty(STDERR_FILENO))
1536 log_init(argv[0], ll, SYSLOG_FACILITY_USER, 1);
1538 if (sftp_direct == NULL) {
1539 if (optind == argc || argc > (optind + 2))
1542 userhost = xstrdup(argv[optind]);
1543 file2 = argv[optind+1];
1545 if ((host = strrchr(userhost, '@')) == NULL)
1550 fprintf(stderr, "Missing username\n");
1553 addargs(&args, "-l%s",userhost);
1556 if ((cp = colon(host)) != NULL) {
1561 host = cleanhostname(host);
1563 fprintf(stderr, "Missing hostname\n");
1567 addargs(&args, "-oProtocol %d", sshver);
1569 /* no subsystem if the server-spec contains a '/' */
1570 if (sftp_server == NULL || strchr(sftp_server, '/') == NULL)
1571 addargs(&args, "-s");
1573 addargs(&args, "%s", host);
1574 addargs(&args, "%s", (sftp_server != NULL ?
1575 sftp_server : "sftp"));
1578 fprintf(stderr, "Connecting to %s...\n", host);
1579 connect_to_server(ssh_program, args.list, &in, &out);
1582 addargs(&args, "sftp-server");
1585 fprintf(stderr, "Attaching to %s...\n", sftp_direct);
1586 connect_to_server(sftp_direct, args.list, &in, &out);
1590 err = interactive_loop(in, out, file1, file2);
1592 #if !defined(USE_PIPES)
1593 shutdown(in, SHUT_RDWR);
1594 shutdown(out, SHUT_RDWR);
1602 while (waitpid(sshpid, NULL, 0) == -1)
1604 fatal("Couldn't wait for ssh process: %s",
1607 exit(err == 0 ? 0 : 1);