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 #include <sys/types.h>
20 #ifdef HAVE_SYS_STAT_H
21 # include <sys/stat.h>
23 #include <sys/ioctl.h>
32 typedef void EditLine;
39 #include "pathnames.h"
43 #include "sftp-common.h"
44 #include "sftp-client.h"
46 /* File to read commands from */
49 /* Are we in batchfile mode? */
52 /* Size of buffer used when copying files */
53 size_t copy_buffer_len = 32768;
55 /* Number of concurrent outstanding requests */
56 size_t num_requests = 16;
58 /* PID of ssh transport process */
59 static pid_t sshpid = -1;
61 /* This is set to 0 if the progressmeter is not desired. */
64 /* SIGINT received during command processing */
65 volatile sig_atomic_t interrupted = 0;
67 /* I wish qsort() took a separate ctx for the comparison function...*/
70 int remote_glob(struct sftp_conn *, const char *, int,
71 int (*)(const char *, int), glob_t *); /* proto for sftp-glob.c */
73 extern char *__progname;
75 /* Separators for interactive commands */
76 #define WHITESPACE " \t\r\n"
79 #define LS_LONG_VIEW 0x01 /* Full view ala ls -l */
80 #define LS_SHORT_VIEW 0x02 /* Single row view ala ls -1 */
81 #define LS_NUMERIC_VIEW 0x04 /* Long view with numeric uid/gid */
82 #define LS_NAME_SORT 0x08 /* Sort by name (default) */
83 #define LS_TIME_SORT 0x10 /* Sort by mtime */
84 #define LS_SIZE_SORT 0x20 /* Sort by file size */
85 #define LS_REVERSE_SORT 0x40 /* Reverse sort order */
86 #define LS_SHOW_ALL 0x80 /* Don't skip filenames starting with '.' */
88 #define VIEW_FLAGS (LS_LONG_VIEW|LS_SHORT_VIEW|LS_NUMERIC_VIEW)
89 #define SORT_FLAGS (LS_NAME_SORT|LS_TIME_SORT|LS_SIZE_SORT)
91 /* Commands for interactive mode */
114 #define I_PROGRESS 23
121 static const struct CMD cmds[] = {
124 { "chdir", I_CHDIR },
125 { "chgrp", I_CHGRP },
126 { "chmod", I_CHMOD },
127 { "chown", I_CHOWN },
134 { "lchdir", I_LCHDIR },
136 { "lmkdir", I_LMKDIR },
140 { "lumask", I_LUMASK },
141 { "mkdir", I_MKDIR },
142 { "progress", I_PROGRESS },
147 { "rename", I_RENAME },
149 { "rmdir", I_RMDIR },
150 { "symlink", I_SYMLINK },
151 { "version", I_VERSION },
157 int interactive_loop(int fd_in, int fd_out, char *file1, char *file2);
163 kill(sshpid, SIGTERM);
164 waitpid(sshpid, NULL, 0);
171 cmd_interrupt(int signo)
173 const char msg[] = "\rInterrupt \n";
174 int olderrno = errno;
176 write(STDERR_FILENO, msg, sizeof(msg) - 1);
184 printf("Available commands:\n");
185 printf("cd path Change remote directory to 'path'\n");
186 printf("lcd path Change local directory to 'path'\n");
187 printf("chgrp grp path Change group of file 'path' to 'grp'\n");
188 printf("chmod mode path Change permissions of file 'path' to 'mode'\n");
189 printf("chown own path Change owner of file 'path' to 'own'\n");
190 printf("help Display this help text\n");
191 printf("get remote-path [local-path] Download file\n");
192 printf("lls [ls-options [path]] Display local directory listing\n");
193 printf("ln oldpath newpath Symlink remote file\n");
194 printf("lmkdir path Create local directory\n");
195 printf("lpwd Print local working directory\n");
196 printf("ls [path] Display remote directory listing\n");
197 printf("lumask umask Set local umask to 'umask'\n");
198 printf("mkdir path Create remote directory\n");
199 printf("progress Toggle display of progress meter\n");
200 printf("put local-path [remote-path] Upload file\n");
201 printf("pwd Display remote working directory\n");
202 printf("exit Quit sftp\n");
203 printf("quit Quit sftp\n");
204 printf("rename oldpath newpath Rename remote file\n");
205 printf("rmdir path Remove remote directory\n");
206 printf("rm path Delete remote file\n");
207 printf("symlink oldpath newpath Symlink remote file\n");
208 printf("version Show SFTP version\n");
209 printf("!command Execute 'command' in local shell\n");
210 printf("! Escape to local shell\n");
211 printf("? Synonym for help\n");
215 local_do_shell(const char *args)
224 if ((shell = getenv("SHELL")) == NULL)
225 shell = _PATH_BSHELL;
227 if ((pid = fork()) == -1)
228 fatal("Couldn't fork: %s", strerror(errno));
231 /* XXX: child has pipe fds to ssh subproc open - issue? */
233 debug3("Executing %s -c \"%s\"", shell, args);
234 execl(shell, shell, "-c", args, (char *)NULL);
236 debug3("Executing %s", shell);
237 execl(shell, shell, (char *)NULL);
239 fprintf(stderr, "Couldn't execute \"%s\": %s\n", shell,
243 while (waitpid(pid, &status, 0) == -1)
245 fatal("Couldn't wait for child: %s", strerror(errno));
246 if (!WIFEXITED(status))
247 error("Shell exited abormally");
248 else if (WEXITSTATUS(status))
249 error("Shell exited with status %d", WEXITSTATUS(status));
253 local_do_ls(const char *args)
256 local_do_shell(_PATH_LS);
258 int len = strlen(_PATH_LS " ") + strlen(args) + 1;
259 char *buf = xmalloc(len);
261 /* XXX: quoting - rip quoting code from ftp? */
262 snprintf(buf, len, _PATH_LS " %s", args);
268 /* Strip one path (usually the pwd) from the start of another */
270 path_strip(char *path, char *strip)
275 return (xstrdup(path));
278 if (strncmp(path, strip, len) == 0) {
279 if (strip[len - 1] != '/' && path[len] == '/')
281 return (xstrdup(path + len));
284 return (xstrdup(path));
288 path_append(char *p1, char *p2)
291 int len = strlen(p1) + strlen(p2) + 2;
294 strlcpy(ret, p1, len);
295 if (p1[strlen(p1) - 1] != '/')
296 strlcat(ret, "/", len);
297 strlcat(ret, p2, len);
303 make_absolute(char *p, char *pwd)
308 if (p && p[0] != '/') {
309 abs_str = path_append(pwd, p);
317 infer_path(const char *p, char **ifp)
321 cp = strrchr(p, '/');
328 error("Invalid path");
332 *ifp = xstrdup(cp + 1);
337 parse_getput_flags(const char **cpp, int *pflag)
339 const char *cp = *cpp;
341 /* Check for flags */
342 if (cp[0] == '-' && cp[1] && strchr(WHITESPACE, cp[2])) {
349 error("Invalid flag -%c", cp[1]);
353 *cpp = cp + strspn(cp, WHITESPACE);
360 parse_ls_flags(const char **cpp, int *lflag)
362 const char *cp = *cpp;
365 *lflag = LS_NAME_SORT;
367 /* Check for flags */
368 if (cp++[0] == '-') {
369 for (; strchr(WHITESPACE, *cp) == NULL; cp++) {
372 *lflag &= ~VIEW_FLAGS;
373 *lflag |= LS_LONG_VIEW;
376 *lflag &= ~VIEW_FLAGS;
377 *lflag |= LS_SHORT_VIEW;
380 *lflag &= ~VIEW_FLAGS;
381 *lflag |= LS_NUMERIC_VIEW|LS_LONG_VIEW;
384 *lflag &= ~SORT_FLAGS;
385 *lflag |= LS_SIZE_SORT;
388 *lflag &= ~SORT_FLAGS;
389 *lflag |= LS_TIME_SORT;
392 *lflag |= LS_REVERSE_SORT;
395 *lflag &= ~SORT_FLAGS;
398 *lflag |= LS_SHOW_ALL;
401 error("Invalid flag -%c", *cp);
405 *cpp = cp + strspn(cp, WHITESPACE);
412 get_pathname(const char **cpp, char **path)
414 const char *cp = *cpp, *end;
418 cp += strspn(cp, WHITESPACE);
425 *path = xmalloc(strlen(cp) + 1);
427 /* Check for quoted filenames */
428 if (*cp == '\"' || *cp == '\'') {
431 /* Search for terminating quote, unescape some chars */
432 for (i = j = 0; i <= strlen(cp); i++) {
433 if (cp[i] == quot) { /* Found quote */
438 if (cp[i] == '\0') { /* End of string */
439 error("Unterminated quote");
442 if (cp[i] == '\\') { /* Escaped characters */
444 if (cp[i] != '\'' && cp[i] != '\"' &&
446 error("Bad escaped character '\\%c'",
451 (*path)[j++] = cp[i];
455 error("Empty quotes");
458 *cpp = cp + i + strspn(cp + i, WHITESPACE);
460 /* Read to end of filename */
461 end = strpbrk(cp, WHITESPACE);
463 end = strchr(cp, '\0');
464 *cpp = end + strspn(end, WHITESPACE);
466 memcpy(*path, cp, end - cp);
467 (*path)[end - cp] = '\0';
482 /* XXX: report errors? */
483 if (stat(path, &sb) == -1)
486 return(sb.st_mode & S_IFDIR);
494 if (stat(path, &sb) == -1)
495 fatal("stat %s: %s", path, strerror(errno));
497 return(S_ISREG(sb.st_mode));
501 remote_is_dir(struct sftp_conn *conn, char *path)
505 /* XXX: report errors? */
506 if ((a = do_stat(conn, path, 1)) == NULL)
508 if (!(a->flags & SSH2_FILEXFER_ATTR_PERMISSIONS))
510 return(a->perm & S_IFDIR);
514 process_get(struct sftp_conn *conn, char *src, char *dst, char *pwd, int pflag)
516 char *abs_src = NULL;
517 char *abs_dst = NULL;
523 abs_src = xstrdup(src);
524 abs_src = make_absolute(abs_src, pwd);
526 memset(&g, 0, sizeof(g));
527 debug3("Looking up %s", abs_src);
528 if (remote_glob(conn, abs_src, 0, NULL, &g)) {
529 error("File \"%s\" not found.", abs_src);
534 /* If multiple matches, dst must be a directory or unspecified */
535 if (g.gl_matchc > 1 && dst && !is_dir(dst)) {
536 error("Multiple files match, but \"%s\" is not a directory",
542 for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
543 if (infer_path(g.gl_pathv[i], &tmp)) {
548 if (g.gl_matchc == 1 && dst) {
549 /* If directory specified, append filename */
551 if (infer_path(g.gl_pathv[0], &tmp)) {
555 abs_dst = path_append(dst, tmp);
558 abs_dst = xstrdup(dst);
560 abs_dst = path_append(dst, tmp);
565 printf("Fetching %s to %s\n", g.gl_pathv[i], abs_dst);
566 if (do_download(conn, g.gl_pathv[i], abs_dst, pflag) == -1)
581 process_put(struct sftp_conn *conn, char *src, char *dst, char *pwd, int pflag)
583 char *tmp_dst = NULL;
584 char *abs_dst = NULL;
591 tmp_dst = xstrdup(dst);
592 tmp_dst = make_absolute(tmp_dst, pwd);
595 memset(&g, 0, sizeof(g));
596 debug3("Looking up %s", src);
597 if (glob(src, 0, NULL, &g)) {
598 error("File \"%s\" not found.", src);
603 /* If multiple matches, dst may be directory or unspecified */
604 if (g.gl_matchc > 1 && tmp_dst && !remote_is_dir(conn, tmp_dst)) {
605 error("Multiple files match, but \"%s\" is not a directory",
611 for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
612 if (!is_reg(g.gl_pathv[i])) {
613 error("skipping non-regular file %s",
617 if (infer_path(g.gl_pathv[i], &tmp)) {
622 if (g.gl_matchc == 1 && tmp_dst) {
623 /* If directory specified, append filename */
624 if (remote_is_dir(conn, tmp_dst)) {
625 if (infer_path(g.gl_pathv[0], &tmp)) {
629 abs_dst = path_append(tmp_dst, tmp);
632 abs_dst = xstrdup(tmp_dst);
634 } else if (tmp_dst) {
635 abs_dst = path_append(tmp_dst, tmp);
638 abs_dst = make_absolute(tmp, pwd);
640 printf("Uploading %s to %s\n", g.gl_pathv[i], abs_dst);
641 if (do_upload(conn, g.gl_pathv[i], abs_dst, pflag) == -1)
655 sdirent_comp(const void *aa, const void *bb)
657 SFTP_DIRENT *a = *(SFTP_DIRENT **)aa;
658 SFTP_DIRENT *b = *(SFTP_DIRENT **)bb;
659 int rmul = sort_flag & LS_REVERSE_SORT ? -1 : 1;
661 #define NCMP(a,b) (a == b ? 0 : (a < b ? 1 : -1))
662 if (sort_flag & LS_NAME_SORT)
663 return (rmul * strcmp(a->filename, b->filename));
664 else if (sort_flag & LS_TIME_SORT)
665 return (rmul * NCMP(a->a.mtime, b->a.mtime));
666 else if (sort_flag & LS_SIZE_SORT)
667 return (rmul * NCMP(a->a.size, b->a.size));
669 fatal("Unknown ls sort type");
672 /* sftp ls.1 replacement for directories */
674 do_ls_dir(struct sftp_conn *conn, char *path, char *strip_path, int lflag)
677 u_int c = 1, colspace = 0, columns = 1;
680 if ((n = do_readdir(conn, path, &d)) != 0)
683 if (!(lflag & LS_SHORT_VIEW)) {
684 u_int m = 0, width = 80;
688 /* Count entries for sort and find longest filename */
689 for (n = 0; d[n] != NULL; n++) {
690 if (d[n]->filename[0] != '.' || (lflag & LS_SHOW_ALL))
691 m = MAX(m, strlen(d[n]->filename));
694 /* Add any subpath that also needs to be counted */
695 tmp = path_strip(path, strip_path);
699 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) != -1)
702 columns = width / (m + 2);
703 columns = MAX(columns, 1);
704 colspace = width / columns;
705 colspace = MIN(colspace, width);
708 if (lflag & SORT_FLAGS) {
709 for (n = 0; d[n] != NULL; n++)
710 ; /* count entries */
711 sort_flag = lflag & (SORT_FLAGS|LS_REVERSE_SORT);
712 qsort(d, n, sizeof(*d), sdirent_comp);
715 for (n = 0; d[n] != NULL && !interrupted; n++) {
718 if (d[n]->filename[0] == '.' && !(lflag & LS_SHOW_ALL))
721 tmp = path_append(path, d[n]->filename);
722 fname = path_strip(tmp, strip_path);
725 if (lflag & LS_LONG_VIEW) {
726 if (lflag & LS_NUMERIC_VIEW) {
730 memset(&sb, 0, sizeof(sb));
731 attrib_to_stat(&d[n]->a, &sb);
732 lname = ls_file(fname, &sb, 1);
733 printf("%s\n", lname);
736 printf("%s\n", d[n]->longname);
738 printf("%-*s", colspace, fname);
749 if (!(lflag & LS_LONG_VIEW) && (c != 1))
752 free_sftp_dirents(d);
756 /* sftp ls.1 replacement which handles path globs */
758 do_globbed_ls(struct sftp_conn *conn, char *path, char *strip_path,
762 u_int i, c = 1, colspace = 0, columns = 1;
765 memset(&g, 0, sizeof(g));
767 if (remote_glob(conn, path, GLOB_MARK|GLOB_NOCHECK|GLOB_BRACE,
768 NULL, &g) || (g.gl_pathc && !g.gl_matchc)) {
771 error("Can't ls: \"%s\" not found", path);
779 * If the glob returns a single match and it is a directory,
780 * then just list its contents.
782 if (g.gl_matchc == 1) {
783 if ((a = do_lstat(conn, g.gl_pathv[0], 1)) == NULL) {
787 if ((a->flags & SSH2_FILEXFER_ATTR_PERMISSIONS) &&
791 err = do_ls_dir(conn, g.gl_pathv[0], strip_path, lflag);
797 if (!(lflag & LS_SHORT_VIEW)) {
798 u_int m = 0, width = 80;
801 /* Count entries for sort and find longest filename */
802 for (i = 0; g.gl_pathv[i]; i++)
803 m = MAX(m, strlen(g.gl_pathv[i]));
805 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) != -1)
808 columns = width / (m + 2);
809 columns = MAX(columns, 1);
810 colspace = width / columns;
813 for (i = 0; g.gl_pathv[i] && !interrupted; i++, a = NULL) {
816 fname = path_strip(g.gl_pathv[i], strip_path);
818 if (lflag & LS_LONG_VIEW) {
823 * XXX: this is slow - 1 roundtrip per path
824 * A solution to this is to fork glob() and
825 * build a sftp specific version which keeps the
826 * attribs (which currently get thrown away)
827 * that the server returns as well as the filenames.
829 memset(&sb, 0, sizeof(sb));
831 a = do_lstat(conn, g.gl_pathv[i], 1);
833 attrib_to_stat(a, &sb);
834 lname = ls_file(fname, &sb, 1);
835 printf("%s\n", lname);
838 printf("%-*s", colspace, fname);
848 if (!(lflag & LS_LONG_VIEW) && (c != 1))
859 parse_args(const char **cpp, int *pflag, int *lflag, int *iflag,
860 unsigned long *n_arg, char **path1, char **path2)
862 const char *cmd, *cp = *cpp;
868 /* Skip leading whitespace */
869 cp = cp + strspn(cp, WHITESPACE);
871 /* Ignore blank lines and lines which begin with comment '#' char */
872 if (*cp == '\0' || *cp == '#')
875 /* Check for leading '-' (disable error processing) */
882 /* Figure out which command we have */
883 for (i = 0; cmds[i].c; i++) {
884 int cmdlen = strlen(cmds[i].c);
886 /* Check for command followed by whitespace */
887 if (!strncasecmp(cp, cmds[i].c, cmdlen) &&
888 strchr(WHITESPACE, cp[cmdlen])) {
890 cp = cp + strspn(cp, WHITESPACE);
901 } else if (cmdnum == -1) {
902 error("Invalid command.");
906 /* Get arguments and parse flags */
907 *lflag = *pflag = *n_arg = 0;
908 *path1 = *path2 = NULL;
912 if (parse_getput_flags(&cp, pflag))
914 /* Get first pathname (mandatory) */
915 if (get_pathname(&cp, path1))
917 if (*path1 == NULL) {
918 error("You must specify at least one path after a "
922 /* Try to get second pathname (optional) */
923 if (get_pathname(&cp, path2))
928 if (get_pathname(&cp, path1))
930 if (get_pathname(&cp, path2))
932 if (!*path1 || !*path2) {
933 error("You must specify two paths after a %s "
944 /* Get pathname (mandatory) */
945 if (get_pathname(&cp, path1))
947 if (*path1 == NULL) {
948 error("You must specify a path after a %s command.",
954 if (parse_ls_flags(&cp, lflag))
956 /* Path is optional */
957 if (get_pathname(&cp, path1))
962 /* Uses the rest of the line */
970 /* Get numeric arg (mandatory) */
971 l = strtol(cp, &cp2, base);
972 if (cp2 == cp || ((l == LONG_MIN || l == LONG_MAX) &&
973 errno == ERANGE) || l < 0) {
974 error("You must supply a numeric argument "
975 "to the %s command.", cmd);
980 if (cmdnum == I_LUMASK && strchr(WHITESPACE, *cp))
982 if (cmdnum == I_LUMASK || !strchr(WHITESPACE, *cp)) {
983 error("You must supply a numeric argument "
984 "to the %s command.", cmd);
987 cp += strspn(cp, WHITESPACE);
989 /* Get pathname (mandatory) */
990 if (get_pathname(&cp, path1))
992 if (*path1 == NULL) {
993 error("You must specify a path after a %s command.",
1006 fatal("Command not implemented");
1014 parse_dispatch_command(struct sftp_conn *conn, const char *cmd, char **pwd,
1017 char *path1, *path2, *tmp;
1018 int pflag, lflag, iflag, cmdnum, i;
1019 unsigned long n_arg;
1021 char path_buf[MAXPATHLEN];
1025 path1 = path2 = NULL;
1026 cmdnum = parse_args(&cmd, &pflag, &lflag, &iflag, &n_arg,
1032 memset(&g, 0, sizeof(g));
1034 /* Perform command */
1040 /* Unrecognized command */
1044 err = process_get(conn, path1, path2, *pwd, pflag);
1047 err = process_put(conn, path1, path2, *pwd, pflag);
1050 path1 = make_absolute(path1, *pwd);
1051 path2 = make_absolute(path2, *pwd);
1052 err = do_rename(conn, path1, path2);
1055 path2 = make_absolute(path2, *pwd);
1056 err = do_symlink(conn, path1, path2);
1059 path1 = make_absolute(path1, *pwd);
1060 remote_glob(conn, path1, GLOB_NOCHECK, NULL, &g);
1061 for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
1062 printf("Removing %s\n", g.gl_pathv[i]);
1063 err = do_rm(conn, g.gl_pathv[i]);
1064 if (err != 0 && err_abort)
1069 path1 = make_absolute(path1, *pwd);
1071 a.flags |= SSH2_FILEXFER_ATTR_PERMISSIONS;
1073 err = do_mkdir(conn, path1, &a);
1076 path1 = make_absolute(path1, *pwd);
1077 err = do_rmdir(conn, path1);
1080 path1 = make_absolute(path1, *pwd);
1081 if ((tmp = do_realpath(conn, path1)) == NULL) {
1085 if ((aa = do_stat(conn, tmp, 0)) == NULL) {
1090 if (!(aa->flags & SSH2_FILEXFER_ATTR_PERMISSIONS)) {
1091 error("Can't change directory: Can't check target");
1096 if (!S_ISDIR(aa->perm)) {
1097 error("Can't change directory: \"%s\" is not "
1098 "a directory", tmp);
1108 do_globbed_ls(conn, *pwd, *pwd, lflag);
1112 /* Strip pwd off beginning of non-absolute paths */
1117 path1 = make_absolute(path1, *pwd);
1118 err = do_globbed_ls(conn, path1, tmp, lflag);
1121 if (chdir(path1) == -1) {
1122 error("Couldn't change local directory to "
1123 "\"%s\": %s", path1, strerror(errno));
1128 if (mkdir(path1, 0777) == -1) {
1129 error("Couldn't create local directory "
1130 "\"%s\": %s", path1, strerror(errno));
1138 local_do_shell(cmd);
1142 printf("Local umask: %03lo\n", n_arg);
1145 path1 = make_absolute(path1, *pwd);
1147 a.flags |= SSH2_FILEXFER_ATTR_PERMISSIONS;
1149 remote_glob(conn, path1, GLOB_NOCHECK, NULL, &g);
1150 for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
1151 printf("Changing mode on %s\n", g.gl_pathv[i]);
1152 err = do_setstat(conn, g.gl_pathv[i], &a);
1153 if (err != 0 && err_abort)
1159 path1 = make_absolute(path1, *pwd);
1160 remote_glob(conn, path1, GLOB_NOCHECK, NULL, &g);
1161 for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
1162 if (!(aa = do_stat(conn, g.gl_pathv[i], 0))) {
1163 if (err != 0 && err_abort)
1168 if (!(aa->flags & SSH2_FILEXFER_ATTR_UIDGID)) {
1169 error("Can't get current ownership of "
1170 "remote file \"%s\"", g.gl_pathv[i]);
1171 if (err != 0 && err_abort)
1176 aa->flags &= SSH2_FILEXFER_ATTR_UIDGID;
1177 if (cmdnum == I_CHOWN) {
1178 printf("Changing owner on %s\n", g.gl_pathv[i]);
1181 printf("Changing group on %s\n", g.gl_pathv[i]);
1184 err = do_setstat(conn, g.gl_pathv[i], aa);
1185 if (err != 0 && err_abort)
1190 printf("Remote working directory: %s\n", *pwd);
1193 if (!getcwd(path_buf, sizeof(path_buf))) {
1194 error("Couldn't get local cwd: %s", strerror(errno));
1198 printf("Local working directory: %s\n", path_buf);
1201 /* Processed below */
1207 printf("SFTP protocol version %u\n", sftp_proto_version(conn));
1210 showprogress = !showprogress;
1212 printf("Progress meter enabled\n");
1214 printf("Progress meter disabled\n");
1217 fatal("%d is not implemented", cmdnum);
1227 /* If an unignored error occurs in batch mode we should abort. */
1228 if (err_abort && err != 0)
1230 else if (cmdnum == I_QUIT)
1238 prompt(EditLine *el)
1245 interactive_loop(int fd_in, int fd_out, char *file1, char *file2)
1250 struct sftp_conn *conn;
1251 int err, interactive;
1252 EditLine *el = NULL;
1256 extern char *__progname;
1258 if (!batchmode && isatty(STDIN_FILENO)) {
1259 if ((el = el_init(__progname, stdin, stdout, stderr)) == NULL)
1260 fatal("Couldn't initialise editline");
1261 if ((hl = history_init()) == NULL)
1262 fatal("Couldn't initialise editline history");
1263 history(hl, &hev, H_SETSIZE, 100);
1264 el_set(el, EL_HIST, history, hl);
1266 el_set(el, EL_PROMPT, prompt);
1267 el_set(el, EL_EDITOR, "emacs");
1268 el_set(el, EL_TERMINAL, NULL);
1269 el_set(el, EL_SIGNAL, 1);
1270 el_source(el, NULL);
1272 #endif /* USE_LIBEDIT */
1274 conn = do_init(fd_in, fd_out, copy_buffer_len, num_requests);
1276 fatal("Couldn't initialise connection to server");
1278 pwd = do_realpath(conn, ".");
1282 if (file1 != NULL) {
1283 dir = xstrdup(file1);
1284 dir = make_absolute(dir, pwd);
1286 if (remote_is_dir(conn, dir) && file2 == NULL) {
1287 printf("Changing to: %s\n", dir);
1288 snprintf(cmd, sizeof cmd, "cd \"%s\"", dir);
1289 if (parse_dispatch_command(conn, cmd, &pwd, 1) != 0) {
1296 snprintf(cmd, sizeof cmd, "get %s", dir);
1298 snprintf(cmd, sizeof cmd, "get %s %s", dir,
1301 err = parse_dispatch_command(conn, cmd, &pwd, 1);
1309 #if defined(HAVE_SETVBUF) && !defined(BROKEN_SETVBUF)
1310 setvbuf(stdout, NULL, _IOLBF, 0);
1311 setvbuf(infile, NULL, _IOLBF, 0);
1317 interactive = !batchmode && isatty(STDIN_FILENO);
1322 signal(SIGINT, SIG_IGN);
1327 if (fgets(cmd, sizeof(cmd), infile) == NULL) {
1332 if (!interactive) { /* Echo command */
1333 printf("sftp> %s", cmd);
1334 if (strlen(cmd) > 0 &&
1335 cmd[strlen(cmd) - 1] != '\n')
1343 if ((line = el_gets(el, &count)) == NULL || count <= 0) {
1347 history(hl, &hev, H_ENTER, line);
1348 if (strlcpy(cmd, line, sizeof(cmd)) >= sizeof(cmd)) {
1349 fprintf(stderr, "Error: input line too long\n");
1352 #endif /* USE_LIBEDIT */
1355 cp = strrchr(cmd, '\n');
1359 /* Handle user interrupts gracefully during commands */
1361 signal(SIGINT, cmd_interrupt);
1363 err = parse_dispatch_command(conn, cmd, &pwd, batchmode);
1372 #endif /* USE_LIBEDIT */
1374 /* err == 1 signifies normal "quit" exit */
1375 return (err >= 0 ? 0 : -1);
1379 connect_to_server(char *path, char **args, int *in, int *out)
1384 int pin[2], pout[2];
1386 if ((pipe(pin) == -1) || (pipe(pout) == -1))
1387 fatal("pipe: %s", strerror(errno));
1392 #else /* USE_PIPES */
1395 if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) == -1)
1396 fatal("socketpair: %s", strerror(errno));
1397 *in = *out = inout[0];
1398 c_in = c_out = inout[1];
1399 #endif /* USE_PIPES */
1401 if ((sshpid = fork()) == -1)
1402 fatal("fork: %s", strerror(errno));
1403 else if (sshpid == 0) {
1404 if ((dup2(c_in, STDIN_FILENO) == -1) ||
1405 (dup2(c_out, STDOUT_FILENO) == -1)) {
1406 fprintf(stderr, "dup2: %s\n", strerror(errno));
1415 * The underlying ssh is in the same process group, so we must
1416 * ignore SIGINT if we want to gracefully abort commands,
1417 * otherwise the signal will make it to the ssh process and
1420 signal(SIGINT, SIG_IGN);
1422 fprintf(stderr, "exec: %s: %s\n", path, strerror(errno));
1426 signal(SIGTERM, killchild);
1427 signal(SIGINT, killchild);
1428 signal(SIGHUP, killchild);
1436 extern char *__progname;
1439 "usage: %s [-1Cv] [-B buffer_size] [-b batchfile] [-F ssh_config]\n"
1440 " [-o ssh_option] [-P sftp_server_path] [-R num_requests]\n"
1441 " [-S program] [-s subsystem | sftp_server] host\n"
1442 " %s [[user@]host[:file [file]]]\n"
1443 " %s [[user@]host[:dir[/]]]\n"
1444 " %s -b batchfile [user@]host\n", __progname, __progname, __progname, __progname);
1449 main(int argc, char **argv)
1451 int in, out, ch, err;
1452 char *host, *userhost, *cp, *file2 = NULL;
1453 int debug_level = 0, sshver = 2;
1454 char *file1 = NULL, *sftp_server = NULL;
1455 char *ssh_program = _PATH_SSH_PROGRAM, *sftp_direct = NULL;
1456 LogLevel ll = SYSLOG_LEVEL_INFO;
1459 extern char *optarg;
1461 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
1464 __progname = ssh_get_progname(argv[0]);
1465 memset(&args, '\0', sizeof(args));
1467 addargs(&args, ssh_program);
1468 addargs(&args, "-oForwardX11 no");
1469 addargs(&args, "-oForwardAgent no");
1470 addargs(&args, "-oPermitLocalCommand no");
1471 addargs(&args, "-oClearAllForwardings yes");
1473 ll = SYSLOG_LEVEL_INFO;
1476 while ((ch = getopt(argc, argv, "1hvCo:s:S:b:B:F:P:R:")) != -1) {
1479 addargs(&args, "-C");
1482 if (debug_level < 3) {
1483 addargs(&args, "-v");
1484 ll = SYSLOG_LEVEL_DEBUG1 + debug_level;
1490 addargs(&args, "-%c%s", ch, optarg);
1494 if (sftp_server == NULL)
1495 sftp_server = _PATH_SFTP_SERVER;
1498 sftp_server = optarg;
1501 ssh_program = optarg;
1502 replacearg(&args, 0, "%s", ssh_program);
1506 fatal("Batch file already specified.");
1508 /* Allow "-" as stdin */
1509 if (strcmp(optarg, "-") != 0 &&
1510 (infile = fopen(optarg, "r")) == NULL)
1511 fatal("%s (%s).", strerror(errno), optarg);
1514 addargs(&args, "-obatchmode yes");
1517 sftp_direct = optarg;
1520 copy_buffer_len = strtol(optarg, &cp, 10);
1521 if (copy_buffer_len == 0 || *cp != '\0')
1522 fatal("Invalid buffer size \"%s\"", optarg);
1525 num_requests = strtol(optarg, &cp, 10);
1526 if (num_requests == 0 || *cp != '\0')
1527 fatal("Invalid number of requests \"%s\"",
1536 if (!isatty(STDERR_FILENO))
1539 log_init(argv[0], ll, SYSLOG_FACILITY_USER, 1);
1541 if (sftp_direct == NULL) {
1542 if (optind == argc || argc > (optind + 2))
1545 userhost = xstrdup(argv[optind]);
1546 file2 = argv[optind+1];
1548 if ((host = strrchr(userhost, '@')) == NULL)
1553 fprintf(stderr, "Missing username\n");
1556 addargs(&args, "-l%s",userhost);
1559 if ((cp = colon(host)) != NULL) {
1564 host = cleanhostname(host);
1566 fprintf(stderr, "Missing hostname\n");
1570 addargs(&args, "-oProtocol %d", sshver);
1572 /* no subsystem if the server-spec contains a '/' */
1573 if (sftp_server == NULL || strchr(sftp_server, '/') == NULL)
1574 addargs(&args, "-s");
1576 addargs(&args, "%s", host);
1577 addargs(&args, "%s", (sftp_server != NULL ?
1578 sftp_server : "sftp"));
1581 fprintf(stderr, "Connecting to %s...\n", host);
1582 connect_to_server(ssh_program, args.list, &in, &out);
1585 addargs(&args, "sftp-server");
1588 fprintf(stderr, "Attaching to %s...\n", sftp_direct);
1589 connect_to_server(sftp_direct, args.list, &in, &out);
1593 err = interactive_loop(in, out, file1, file2);
1595 #if !defined(USE_PIPES)
1596 shutdown(in, SHUT_RDWR);
1597 shutdown(out, SHUT_RDWR);
1605 while (waitpid(sshpid, NULL, 0) == -1)
1607 fatal("Couldn't wait for ssh process: %s",
1610 exit(err == 0 ? 0 : 1);