1 /* $OpenBSD: sftp.c,v 1.87 2006/07/22 20:48:23 stevesk Exp $ */
3 * Copyright (c) 2001-2004 Damien Miller <djm@openbsd.org>
5 * Permission to use, copy, modify, and distribute this software for any
6 * purpose with or without fee is hereby granted, provided that the above
7 * copyright notice and this permission notice appear in all copies.
9 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
20 #include <sys/types.h>
21 #ifdef HAVE_SYS_STAT_H
22 # include <sys/stat.h>
24 #include <sys/ioctl.h>
25 #include <sys/socket.h>
36 typedef void EditLine;
44 #include "pathnames.h"
48 #include "sftp-common.h"
49 #include "sftp-client.h"
51 /* File to read commands from */
54 /* Are we in batchfile mode? */
57 /* Size of buffer used when copying files */
58 size_t copy_buffer_len = 32768;
60 /* Number of concurrent outstanding requests */
61 size_t num_requests = 16;
63 /* PID of ssh transport process */
64 static pid_t sshpid = -1;
66 /* This is set to 0 if the progressmeter is not desired. */
69 /* SIGINT received during command processing */
70 volatile sig_atomic_t interrupted = 0;
72 /* I wish qsort() took a separate ctx for the comparison function...*/
75 int remote_glob(struct sftp_conn *, const char *, int,
76 int (*)(const char *, int), glob_t *); /* proto for sftp-glob.c */
78 extern char *__progname;
80 /* Separators for interactive commands */
81 #define WHITESPACE " \t\r\n"
84 #define LS_LONG_VIEW 0x01 /* Full view ala ls -l */
85 #define LS_SHORT_VIEW 0x02 /* Single row view ala ls -1 */
86 #define LS_NUMERIC_VIEW 0x04 /* Long view with numeric uid/gid */
87 #define LS_NAME_SORT 0x08 /* Sort by name (default) */
88 #define LS_TIME_SORT 0x10 /* Sort by mtime */
89 #define LS_SIZE_SORT 0x20 /* Sort by file size */
90 #define LS_REVERSE_SORT 0x40 /* Reverse sort order */
91 #define LS_SHOW_ALL 0x80 /* Don't skip filenames starting with '.' */
93 #define VIEW_FLAGS (LS_LONG_VIEW|LS_SHORT_VIEW|LS_NUMERIC_VIEW)
94 #define SORT_FLAGS (LS_NAME_SORT|LS_TIME_SORT|LS_SIZE_SORT)
96 /* Commands for interactive mode */
119 #define I_PROGRESS 23
126 static const struct CMD cmds[] = {
129 { "chdir", I_CHDIR },
130 { "chgrp", I_CHGRP },
131 { "chmod", I_CHMOD },
132 { "chown", I_CHOWN },
139 { "lchdir", I_LCHDIR },
141 { "lmkdir", I_LMKDIR },
145 { "lumask", I_LUMASK },
146 { "mkdir", I_MKDIR },
147 { "progress", I_PROGRESS },
152 { "rename", I_RENAME },
154 { "rmdir", I_RMDIR },
155 { "symlink", I_SYMLINK },
156 { "version", I_VERSION },
162 int interactive_loop(int fd_in, int fd_out, char *file1, char *file2);
168 kill(sshpid, SIGTERM);
169 waitpid(sshpid, NULL, 0);
176 cmd_interrupt(int signo)
178 const char msg[] = "\rInterrupt \n";
179 int olderrno = errno;
181 write(STDERR_FILENO, msg, sizeof(msg) - 1);
189 printf("Available commands:\n");
190 printf("cd path Change remote directory to 'path'\n");
191 printf("lcd path Change local directory to 'path'\n");
192 printf("chgrp grp path Change group of file 'path' to 'grp'\n");
193 printf("chmod mode path Change permissions of file 'path' to 'mode'\n");
194 printf("chown own path Change owner of file 'path' to 'own'\n");
195 printf("help Display this help text\n");
196 printf("get remote-path [local-path] Download file\n");
197 printf("lls [ls-options [path]] Display local directory listing\n");
198 printf("ln oldpath newpath Symlink remote file\n");
199 printf("lmkdir path Create local directory\n");
200 printf("lpwd Print local working directory\n");
201 printf("ls [path] Display remote directory listing\n");
202 printf("lumask umask Set local umask to 'umask'\n");
203 printf("mkdir path Create remote directory\n");
204 printf("progress Toggle display of progress meter\n");
205 printf("put local-path [remote-path] Upload file\n");
206 printf("pwd Display remote working directory\n");
207 printf("exit Quit sftp\n");
208 printf("quit Quit sftp\n");
209 printf("rename oldpath newpath Rename remote file\n");
210 printf("rmdir path Remove remote directory\n");
211 printf("rm path Delete remote file\n");
212 printf("symlink oldpath newpath Symlink remote file\n");
213 printf("version Show SFTP version\n");
214 printf("!command Execute 'command' in local shell\n");
215 printf("! Escape to local shell\n");
216 printf("? Synonym for help\n");
220 local_do_shell(const char *args)
229 if ((shell = getenv("SHELL")) == NULL)
230 shell = _PATH_BSHELL;
232 if ((pid = fork()) == -1)
233 fatal("Couldn't fork: %s", strerror(errno));
236 /* XXX: child has pipe fds to ssh subproc open - issue? */
238 debug3("Executing %s -c \"%s\"", shell, args);
239 execl(shell, shell, "-c", args, (char *)NULL);
241 debug3("Executing %s", shell);
242 execl(shell, shell, (char *)NULL);
244 fprintf(stderr, "Couldn't execute \"%s\": %s\n", shell,
248 while (waitpid(pid, &status, 0) == -1)
250 fatal("Couldn't wait for child: %s", strerror(errno));
251 if (!WIFEXITED(status))
252 error("Shell exited abnormally");
253 else if (WEXITSTATUS(status))
254 error("Shell exited with status %d", WEXITSTATUS(status));
258 local_do_ls(const char *args)
261 local_do_shell(_PATH_LS);
263 int len = strlen(_PATH_LS " ") + strlen(args) + 1;
264 char *buf = xmalloc(len);
266 /* XXX: quoting - rip quoting code from ftp? */
267 snprintf(buf, len, _PATH_LS " %s", args);
273 /* Strip one path (usually the pwd) from the start of another */
275 path_strip(char *path, char *strip)
280 return (xstrdup(path));
283 if (strncmp(path, strip, len) == 0) {
284 if (strip[len - 1] != '/' && path[len] == '/')
286 return (xstrdup(path + len));
289 return (xstrdup(path));
293 path_append(char *p1, char *p2)
296 int len = strlen(p1) + strlen(p2) + 2;
299 strlcpy(ret, p1, len);
300 if (p1[strlen(p1) - 1] != '/')
301 strlcat(ret, "/", len);
302 strlcat(ret, p2, len);
308 make_absolute(char *p, char *pwd)
313 if (p && p[0] != '/') {
314 abs_str = path_append(pwd, p);
322 infer_path(const char *p, char **ifp)
326 cp = strrchr(p, '/');
333 error("Invalid path");
337 *ifp = xstrdup(cp + 1);
342 parse_getput_flags(const char **cpp, int *pflag)
344 const char *cp = *cpp;
346 /* Check for flags */
347 if (cp[0] == '-' && cp[1] && strchr(WHITESPACE, cp[2])) {
354 error("Invalid flag -%c", cp[1]);
358 *cpp = cp + strspn(cp, WHITESPACE);
365 parse_ls_flags(const char **cpp, int *lflag)
367 const char *cp = *cpp;
370 *lflag = LS_NAME_SORT;
372 /* Check for flags */
373 if (cp++[0] == '-') {
374 for (; strchr(WHITESPACE, *cp) == NULL; cp++) {
377 *lflag &= ~VIEW_FLAGS;
378 *lflag |= LS_LONG_VIEW;
381 *lflag &= ~VIEW_FLAGS;
382 *lflag |= LS_SHORT_VIEW;
385 *lflag &= ~VIEW_FLAGS;
386 *lflag |= LS_NUMERIC_VIEW|LS_LONG_VIEW;
389 *lflag &= ~SORT_FLAGS;
390 *lflag |= LS_SIZE_SORT;
393 *lflag &= ~SORT_FLAGS;
394 *lflag |= LS_TIME_SORT;
397 *lflag |= LS_REVERSE_SORT;
400 *lflag &= ~SORT_FLAGS;
403 *lflag |= LS_SHOW_ALL;
406 error("Invalid flag -%c", *cp);
410 *cpp = cp + strspn(cp, WHITESPACE);
417 get_pathname(const char **cpp, char **path)
419 const char *cp = *cpp, *end;
423 cp += strspn(cp, WHITESPACE);
430 *path = xmalloc(strlen(cp) + 1);
432 /* Check for quoted filenames */
433 if (*cp == '\"' || *cp == '\'') {
436 /* Search for terminating quote, unescape some chars */
437 for (i = j = 0; i <= strlen(cp); i++) {
438 if (cp[i] == quot) { /* Found quote */
443 if (cp[i] == '\0') { /* End of string */
444 error("Unterminated quote");
447 if (cp[i] == '\\') { /* Escaped characters */
449 if (cp[i] != '\'' && cp[i] != '\"' &&
451 error("Bad escaped character '\\%c'",
456 (*path)[j++] = cp[i];
460 error("Empty quotes");
463 *cpp = cp + i + strspn(cp + i, WHITESPACE);
465 /* Read to end of filename */
466 end = strpbrk(cp, WHITESPACE);
468 end = strchr(cp, '\0');
469 *cpp = end + strspn(end, WHITESPACE);
471 memcpy(*path, cp, end - cp);
472 (*path)[end - cp] = '\0';
487 /* XXX: report errors? */
488 if (stat(path, &sb) == -1)
491 return(sb.st_mode & S_IFDIR);
499 if (stat(path, &sb) == -1)
500 fatal("stat %s: %s", path, strerror(errno));
502 return(S_ISREG(sb.st_mode));
506 remote_is_dir(struct sftp_conn *conn, char *path)
510 /* XXX: report errors? */
511 if ((a = do_stat(conn, path, 1)) == NULL)
513 if (!(a->flags & SSH2_FILEXFER_ATTR_PERMISSIONS))
515 return(a->perm & S_IFDIR);
519 process_get(struct sftp_conn *conn, char *src, char *dst, char *pwd, int pflag)
521 char *abs_src = NULL;
522 char *abs_dst = NULL;
528 abs_src = xstrdup(src);
529 abs_src = make_absolute(abs_src, pwd);
531 memset(&g, 0, sizeof(g));
532 debug3("Looking up %s", abs_src);
533 if (remote_glob(conn, abs_src, 0, NULL, &g)) {
534 error("File \"%s\" not found.", abs_src);
539 /* If multiple matches, dst must be a directory or unspecified */
540 if (g.gl_matchc > 1 && dst && !is_dir(dst)) {
541 error("Multiple files match, but \"%s\" is not a directory",
547 for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
548 if (infer_path(g.gl_pathv[i], &tmp)) {
553 if (g.gl_matchc == 1 && dst) {
554 /* If directory specified, append filename */
557 if (infer_path(g.gl_pathv[0], &tmp)) {
561 abs_dst = path_append(dst, tmp);
564 abs_dst = xstrdup(dst);
566 abs_dst = path_append(dst, tmp);
571 printf("Fetching %s to %s\n", g.gl_pathv[i], abs_dst);
572 if (do_download(conn, g.gl_pathv[i], abs_dst, pflag) == -1)
585 process_put(struct sftp_conn *conn, char *src, char *dst, char *pwd, int pflag)
587 char *tmp_dst = NULL;
588 char *abs_dst = NULL;
595 tmp_dst = xstrdup(dst);
596 tmp_dst = make_absolute(tmp_dst, pwd);
599 memset(&g, 0, sizeof(g));
600 debug3("Looking up %s", src);
601 if (glob(src, 0, NULL, &g)) {
602 error("File \"%s\" not found.", src);
607 /* If multiple matches, dst may be directory or unspecified */
608 if (g.gl_matchc > 1 && tmp_dst && !remote_is_dir(conn, tmp_dst)) {
609 error("Multiple files match, but \"%s\" is not a directory",
615 for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
616 if (!is_reg(g.gl_pathv[i])) {
617 error("skipping non-regular file %s",
621 if (infer_path(g.gl_pathv[i], &tmp)) {
626 if (g.gl_matchc == 1 && tmp_dst) {
627 /* If directory specified, append filename */
628 if (remote_is_dir(conn, tmp_dst)) {
629 if (infer_path(g.gl_pathv[0], &tmp)) {
633 abs_dst = path_append(tmp_dst, tmp);
636 abs_dst = xstrdup(tmp_dst);
638 } else if (tmp_dst) {
639 abs_dst = path_append(tmp_dst, tmp);
642 abs_dst = make_absolute(tmp, pwd);
644 printf("Uploading %s to %s\n", g.gl_pathv[i], abs_dst);
645 if (do_upload(conn, g.gl_pathv[i], abs_dst, pflag) == -1)
659 sdirent_comp(const void *aa, const void *bb)
661 SFTP_DIRENT *a = *(SFTP_DIRENT **)aa;
662 SFTP_DIRENT *b = *(SFTP_DIRENT **)bb;
663 int rmul = sort_flag & LS_REVERSE_SORT ? -1 : 1;
665 #define NCMP(a,b) (a == b ? 0 : (a < b ? 1 : -1))
666 if (sort_flag & LS_NAME_SORT)
667 return (rmul * strcmp(a->filename, b->filename));
668 else if (sort_flag & LS_TIME_SORT)
669 return (rmul * NCMP(a->a.mtime, b->a.mtime));
670 else if (sort_flag & LS_SIZE_SORT)
671 return (rmul * NCMP(a->a.size, b->a.size));
673 fatal("Unknown ls sort type");
676 /* sftp ls.1 replacement for directories */
678 do_ls_dir(struct sftp_conn *conn, char *path, char *strip_path, int lflag)
681 u_int c = 1, colspace = 0, columns = 1;
684 if ((n = do_readdir(conn, path, &d)) != 0)
687 if (!(lflag & LS_SHORT_VIEW)) {
688 u_int m = 0, width = 80;
692 /* Count entries for sort and find longest filename */
693 for (n = 0; d[n] != NULL; n++) {
694 if (d[n]->filename[0] != '.' || (lflag & LS_SHOW_ALL))
695 m = MAX(m, strlen(d[n]->filename));
698 /* Add any subpath that also needs to be counted */
699 tmp = path_strip(path, strip_path);
703 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) != -1)
706 columns = width / (m + 2);
707 columns = MAX(columns, 1);
708 colspace = width / columns;
709 colspace = MIN(colspace, width);
712 if (lflag & SORT_FLAGS) {
713 for (n = 0; d[n] != NULL; n++)
714 ; /* count entries */
715 sort_flag = lflag & (SORT_FLAGS|LS_REVERSE_SORT);
716 qsort(d, n, sizeof(*d), sdirent_comp);
719 for (n = 0; d[n] != NULL && !interrupted; n++) {
722 if (d[n]->filename[0] == '.' && !(lflag & LS_SHOW_ALL))
725 tmp = path_append(path, d[n]->filename);
726 fname = path_strip(tmp, strip_path);
729 if (lflag & LS_LONG_VIEW) {
730 if (lflag & LS_NUMERIC_VIEW) {
734 memset(&sb, 0, sizeof(sb));
735 attrib_to_stat(&d[n]->a, &sb);
736 lname = ls_file(fname, &sb, 1);
737 printf("%s\n", lname);
740 printf("%s\n", d[n]->longname);
742 printf("%-*s", colspace, fname);
753 if (!(lflag & LS_LONG_VIEW) && (c != 1))
756 free_sftp_dirents(d);
760 /* sftp ls.1 replacement which handles path globs */
762 do_globbed_ls(struct sftp_conn *conn, char *path, char *strip_path,
766 u_int i, c = 1, colspace = 0, columns = 1;
769 memset(&g, 0, sizeof(g));
771 if (remote_glob(conn, path, GLOB_MARK|GLOB_NOCHECK|GLOB_BRACE,
772 NULL, &g) || (g.gl_pathc && !g.gl_matchc)) {
775 error("Can't ls: \"%s\" not found", path);
783 * If the glob returns a single match and it is a directory,
784 * then just list its contents.
786 if (g.gl_matchc == 1) {
787 if ((a = do_lstat(conn, g.gl_pathv[0], 1)) == NULL) {
791 if ((a->flags & SSH2_FILEXFER_ATTR_PERMISSIONS) &&
795 err = do_ls_dir(conn, g.gl_pathv[0], strip_path, lflag);
801 if (!(lflag & LS_SHORT_VIEW)) {
802 u_int m = 0, width = 80;
805 /* Count entries for sort and find longest filename */
806 for (i = 0; g.gl_pathv[i]; i++)
807 m = MAX(m, strlen(g.gl_pathv[i]));
809 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) != -1)
812 columns = width / (m + 2);
813 columns = MAX(columns, 1);
814 colspace = width / columns;
817 for (i = 0; g.gl_pathv[i] && !interrupted; i++, a = NULL) {
820 fname = path_strip(g.gl_pathv[i], strip_path);
822 if (lflag & LS_LONG_VIEW) {
827 * XXX: this is slow - 1 roundtrip per path
828 * A solution to this is to fork glob() and
829 * build a sftp specific version which keeps the
830 * attribs (which currently get thrown away)
831 * that the server returns as well as the filenames.
833 memset(&sb, 0, sizeof(sb));
835 a = do_lstat(conn, g.gl_pathv[i], 1);
837 attrib_to_stat(a, &sb);
838 lname = ls_file(fname, &sb, 1);
839 printf("%s\n", lname);
842 printf("%-*s", colspace, fname);
852 if (!(lflag & LS_LONG_VIEW) && (c != 1))
863 parse_args(const char **cpp, int *pflag, int *lflag, int *iflag,
864 unsigned long *n_arg, char **path1, char **path2)
866 const char *cmd, *cp = *cpp;
872 /* Skip leading whitespace */
873 cp = cp + strspn(cp, WHITESPACE);
875 /* Ignore blank lines and lines which begin with comment '#' char */
876 if (*cp == '\0' || *cp == '#')
879 /* Check for leading '-' (disable error processing) */
886 /* Figure out which command we have */
887 for (i = 0; cmds[i].c; i++) {
888 int cmdlen = strlen(cmds[i].c);
890 /* Check for command followed by whitespace */
891 if (!strncasecmp(cp, cmds[i].c, cmdlen) &&
892 strchr(WHITESPACE, cp[cmdlen])) {
894 cp = cp + strspn(cp, WHITESPACE);
905 } else if (cmdnum == -1) {
906 error("Invalid command.");
910 /* Get arguments and parse flags */
911 *lflag = *pflag = *n_arg = 0;
912 *path1 = *path2 = NULL;
916 if (parse_getput_flags(&cp, pflag))
918 /* Get first pathname (mandatory) */
919 if (get_pathname(&cp, path1))
921 if (*path1 == NULL) {
922 error("You must specify at least one path after a "
926 /* Try to get second pathname (optional) */
927 if (get_pathname(&cp, path2))
932 if (get_pathname(&cp, path1))
934 if (get_pathname(&cp, path2))
936 if (!*path1 || !*path2) {
937 error("You must specify two paths after a %s "
948 /* Get pathname (mandatory) */
949 if (get_pathname(&cp, path1))
951 if (*path1 == NULL) {
952 error("You must specify a path after a %s command.",
958 if (parse_ls_flags(&cp, lflag))
960 /* Path is optional */
961 if (get_pathname(&cp, path1))
966 /* Uses the rest of the line */
974 /* Get numeric arg (mandatory) */
975 l = strtol(cp, &cp2, base);
976 if (cp2 == cp || ((l == LONG_MIN || l == LONG_MAX) &&
977 errno == ERANGE) || l < 0) {
978 error("You must supply a numeric argument "
979 "to the %s command.", cmd);
984 if (cmdnum == I_LUMASK && strchr(WHITESPACE, *cp))
986 if (cmdnum == I_LUMASK || !strchr(WHITESPACE, *cp)) {
987 error("You must supply a numeric argument "
988 "to the %s command.", cmd);
991 cp += strspn(cp, WHITESPACE);
993 /* Get pathname (mandatory) */
994 if (get_pathname(&cp, path1))
996 if (*path1 == NULL) {
997 error("You must specify a path after a %s command.",
1010 fatal("Command not implemented");
1018 parse_dispatch_command(struct sftp_conn *conn, const char *cmd, char **pwd,
1021 char *path1, *path2, *tmp;
1022 int pflag, lflag, iflag, cmdnum, i;
1023 unsigned long n_arg;
1025 char path_buf[MAXPATHLEN];
1029 path1 = path2 = NULL;
1030 cmdnum = parse_args(&cmd, &pflag, &lflag, &iflag, &n_arg,
1036 memset(&g, 0, sizeof(g));
1038 /* Perform command */
1044 /* Unrecognized command */
1048 err = process_get(conn, path1, path2, *pwd, pflag);
1051 err = process_put(conn, path1, path2, *pwd, pflag);
1054 path1 = make_absolute(path1, *pwd);
1055 path2 = make_absolute(path2, *pwd);
1056 err = do_rename(conn, path1, path2);
1059 path2 = make_absolute(path2, *pwd);
1060 err = do_symlink(conn, path1, path2);
1063 path1 = make_absolute(path1, *pwd);
1064 remote_glob(conn, path1, GLOB_NOCHECK, NULL, &g);
1065 for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
1066 printf("Removing %s\n", g.gl_pathv[i]);
1067 err = do_rm(conn, g.gl_pathv[i]);
1068 if (err != 0 && err_abort)
1073 path1 = make_absolute(path1, *pwd);
1075 a.flags |= SSH2_FILEXFER_ATTR_PERMISSIONS;
1077 err = do_mkdir(conn, path1, &a);
1080 path1 = make_absolute(path1, *pwd);
1081 err = do_rmdir(conn, path1);
1084 path1 = make_absolute(path1, *pwd);
1085 if ((tmp = do_realpath(conn, path1)) == NULL) {
1089 if ((aa = do_stat(conn, tmp, 0)) == NULL) {
1094 if (!(aa->flags & SSH2_FILEXFER_ATTR_PERMISSIONS)) {
1095 error("Can't change directory: Can't check target");
1100 if (!S_ISDIR(aa->perm)) {
1101 error("Can't change directory: \"%s\" is not "
1102 "a directory", tmp);
1112 do_globbed_ls(conn, *pwd, *pwd, lflag);
1116 /* Strip pwd off beginning of non-absolute paths */
1121 path1 = make_absolute(path1, *pwd);
1122 err = do_globbed_ls(conn, path1, tmp, lflag);
1125 if (chdir(path1) == -1) {
1126 error("Couldn't change local directory to "
1127 "\"%s\": %s", path1, strerror(errno));
1132 if (mkdir(path1, 0777) == -1) {
1133 error("Couldn't create local directory "
1134 "\"%s\": %s", path1, strerror(errno));
1142 local_do_shell(cmd);
1146 printf("Local umask: %03lo\n", n_arg);
1149 path1 = make_absolute(path1, *pwd);
1151 a.flags |= SSH2_FILEXFER_ATTR_PERMISSIONS;
1153 remote_glob(conn, path1, GLOB_NOCHECK, NULL, &g);
1154 for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
1155 printf("Changing mode on %s\n", g.gl_pathv[i]);
1156 err = do_setstat(conn, g.gl_pathv[i], &a);
1157 if (err != 0 && err_abort)
1163 path1 = make_absolute(path1, *pwd);
1164 remote_glob(conn, path1, GLOB_NOCHECK, NULL, &g);
1165 for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
1166 if (!(aa = do_stat(conn, g.gl_pathv[i], 0))) {
1167 if (err != 0 && err_abort)
1172 if (!(aa->flags & SSH2_FILEXFER_ATTR_UIDGID)) {
1173 error("Can't get current ownership of "
1174 "remote file \"%s\"", g.gl_pathv[i]);
1175 if (err != 0 && err_abort)
1180 aa->flags &= SSH2_FILEXFER_ATTR_UIDGID;
1181 if (cmdnum == I_CHOWN) {
1182 printf("Changing owner on %s\n", g.gl_pathv[i]);
1185 printf("Changing group on %s\n", g.gl_pathv[i]);
1188 err = do_setstat(conn, g.gl_pathv[i], aa);
1189 if (err != 0 && err_abort)
1194 printf("Remote working directory: %s\n", *pwd);
1197 if (!getcwd(path_buf, sizeof(path_buf))) {
1198 error("Couldn't get local cwd: %s", strerror(errno));
1202 printf("Local working directory: %s\n", path_buf);
1205 /* Processed below */
1211 printf("SFTP protocol version %u\n", sftp_proto_version(conn));
1214 showprogress = !showprogress;
1216 printf("Progress meter enabled\n");
1218 printf("Progress meter disabled\n");
1221 fatal("%d is not implemented", cmdnum);
1231 /* If an unignored error occurs in batch mode we should abort. */
1232 if (err_abort && err != 0)
1234 else if (cmdnum == I_QUIT)
1242 prompt(EditLine *el)
1249 interactive_loop(int fd_in, int fd_out, char *file1, char *file2)
1254 struct sftp_conn *conn;
1255 int err, interactive;
1256 EditLine *el = NULL;
1260 extern char *__progname;
1262 if (!batchmode && isatty(STDIN_FILENO)) {
1263 if ((el = el_init(__progname, stdin, stdout, stderr)) == NULL)
1264 fatal("Couldn't initialise editline");
1265 if ((hl = history_init()) == NULL)
1266 fatal("Couldn't initialise editline history");
1267 history(hl, &hev, H_SETSIZE, 100);
1268 el_set(el, EL_HIST, history, hl);
1270 el_set(el, EL_PROMPT, prompt);
1271 el_set(el, EL_EDITOR, "emacs");
1272 el_set(el, EL_TERMINAL, NULL);
1273 el_set(el, EL_SIGNAL, 1);
1274 el_source(el, NULL);
1276 #endif /* USE_LIBEDIT */
1278 conn = do_init(fd_in, fd_out, copy_buffer_len, num_requests);
1280 fatal("Couldn't initialise connection to server");
1282 pwd = do_realpath(conn, ".");
1286 if (file1 != NULL) {
1287 dir = xstrdup(file1);
1288 dir = make_absolute(dir, pwd);
1290 if (remote_is_dir(conn, dir) && file2 == NULL) {
1291 printf("Changing to: %s\n", dir);
1292 snprintf(cmd, sizeof cmd, "cd \"%s\"", dir);
1293 if (parse_dispatch_command(conn, cmd, &pwd, 1) != 0) {
1301 snprintf(cmd, sizeof cmd, "get %s", dir);
1303 snprintf(cmd, sizeof cmd, "get %s %s", dir,
1306 err = parse_dispatch_command(conn, cmd, &pwd, 1);
1315 #if defined(HAVE_SETVBUF) && !defined(BROKEN_SETVBUF)
1316 setvbuf(stdout, NULL, _IOLBF, 0);
1317 setvbuf(infile, NULL, _IOLBF, 0);
1323 interactive = !batchmode && isatty(STDIN_FILENO);
1328 signal(SIGINT, SIG_IGN);
1333 if (fgets(cmd, sizeof(cmd), infile) == NULL) {
1338 if (!interactive) { /* Echo command */
1339 printf("sftp> %s", cmd);
1340 if (strlen(cmd) > 0 &&
1341 cmd[strlen(cmd) - 1] != '\n')
1349 if ((line = el_gets(el, &count)) == NULL || count <= 0) {
1353 history(hl, &hev, H_ENTER, line);
1354 if (strlcpy(cmd, line, sizeof(cmd)) >= sizeof(cmd)) {
1355 fprintf(stderr, "Error: input line too long\n");
1358 #endif /* USE_LIBEDIT */
1361 cp = strrchr(cmd, '\n');
1365 /* Handle user interrupts gracefully during commands */
1367 signal(SIGINT, cmd_interrupt);
1369 err = parse_dispatch_command(conn, cmd, &pwd, batchmode);
1379 #endif /* USE_LIBEDIT */
1381 /* err == 1 signifies normal "quit" exit */
1382 return (err >= 0 ? 0 : -1);
1386 connect_to_server(char *path, char **args, int *in, int *out)
1391 int pin[2], pout[2];
1393 if ((pipe(pin) == -1) || (pipe(pout) == -1))
1394 fatal("pipe: %s", strerror(errno));
1399 #else /* USE_PIPES */
1402 if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) == -1)
1403 fatal("socketpair: %s", strerror(errno));
1404 *in = *out = inout[0];
1405 c_in = c_out = inout[1];
1406 #endif /* USE_PIPES */
1408 if ((sshpid = fork()) == -1)
1409 fatal("fork: %s", strerror(errno));
1410 else if (sshpid == 0) {
1411 if ((dup2(c_in, STDIN_FILENO) == -1) ||
1412 (dup2(c_out, STDOUT_FILENO) == -1)) {
1413 fprintf(stderr, "dup2: %s\n", strerror(errno));
1422 * The underlying ssh is in the same process group, so we must
1423 * ignore SIGINT if we want to gracefully abort commands,
1424 * otherwise the signal will make it to the ssh process and
1427 signal(SIGINT, SIG_IGN);
1429 fprintf(stderr, "exec: %s: %s\n", path, strerror(errno));
1433 signal(SIGTERM, killchild);
1434 signal(SIGINT, killchild);
1435 signal(SIGHUP, killchild);
1443 extern char *__progname;
1446 "usage: %s [-1Cv] [-B buffer_size] [-b batchfile] [-F ssh_config]\n"
1447 " [-o ssh_option] [-P sftp_server_path] [-R num_requests]\n"
1448 " [-S program] [-s subsystem | sftp_server] host\n"
1449 " %s [[user@]host[:file [file]]]\n"
1450 " %s [[user@]host[:dir[/]]]\n"
1451 " %s -b batchfile [user@]host\n", __progname, __progname, __progname, __progname);
1456 main(int argc, char **argv)
1458 int in, out, ch, err;
1459 char *host, *userhost, *cp, *file2 = NULL;
1460 int debug_level = 0, sshver = 2;
1461 char *file1 = NULL, *sftp_server = NULL;
1462 char *ssh_program = _PATH_SSH_PROGRAM, *sftp_direct = NULL;
1463 LogLevel ll = SYSLOG_LEVEL_INFO;
1466 extern char *optarg;
1468 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
1471 __progname = ssh_get_progname(argv[0]);
1472 memset(&args, '\0', sizeof(args));
1474 addargs(&args, "%s", ssh_program);
1475 addargs(&args, "-oForwardX11 no");
1476 addargs(&args, "-oForwardAgent no");
1477 addargs(&args, "-oPermitLocalCommand no");
1478 addargs(&args, "-oClearAllForwardings yes");
1480 ll = SYSLOG_LEVEL_INFO;
1483 while ((ch = getopt(argc, argv, "1hvCo:s:S:b:B:F:P:R:")) != -1) {
1486 addargs(&args, "-C");
1489 if (debug_level < 3) {
1490 addargs(&args, "-v");
1491 ll = SYSLOG_LEVEL_DEBUG1 + debug_level;
1497 addargs(&args, "-%c%s", ch, optarg);
1501 if (sftp_server == NULL)
1502 sftp_server = _PATH_SFTP_SERVER;
1505 sftp_server = optarg;
1508 ssh_program = optarg;
1509 replacearg(&args, 0, "%s", ssh_program);
1513 fatal("Batch file already specified.");
1515 /* Allow "-" as stdin */
1516 if (strcmp(optarg, "-") != 0 &&
1517 (infile = fopen(optarg, "r")) == NULL)
1518 fatal("%s (%s).", strerror(errno), optarg);
1521 addargs(&args, "-obatchmode yes");
1524 sftp_direct = optarg;
1527 copy_buffer_len = strtol(optarg, &cp, 10);
1528 if (copy_buffer_len == 0 || *cp != '\0')
1529 fatal("Invalid buffer size \"%s\"", optarg);
1532 num_requests = strtol(optarg, &cp, 10);
1533 if (num_requests == 0 || *cp != '\0')
1534 fatal("Invalid number of requests \"%s\"",
1543 if (!isatty(STDERR_FILENO))
1546 log_init(argv[0], ll, SYSLOG_FACILITY_USER, 1);
1548 if (sftp_direct == NULL) {
1549 if (optind == argc || argc > (optind + 2))
1552 userhost = xstrdup(argv[optind]);
1553 file2 = argv[optind+1];
1555 if ((host = strrchr(userhost, '@')) == NULL)
1560 fprintf(stderr, "Missing username\n");
1563 addargs(&args, "-l%s",userhost);
1566 if ((cp = colon(host)) != NULL) {
1571 host = cleanhostname(host);
1573 fprintf(stderr, "Missing hostname\n");
1577 addargs(&args, "-oProtocol %d", sshver);
1579 /* no subsystem if the server-spec contains a '/' */
1580 if (sftp_server == NULL || strchr(sftp_server, '/') == NULL)
1581 addargs(&args, "-s");
1583 addargs(&args, "%s", host);
1584 addargs(&args, "%s", (sftp_server != NULL ?
1585 sftp_server : "sftp"));
1588 fprintf(stderr, "Connecting to %s...\n", host);
1589 connect_to_server(ssh_program, args.list, &in, &out);
1592 addargs(&args, "sftp-server");
1595 fprintf(stderr, "Attaching to %s...\n", sftp_direct);
1596 connect_to_server(sftp_direct, args.list, &in, &out);
1600 err = interactive_loop(in, out, file1, file2);
1602 #if !defined(USE_PIPES)
1603 shutdown(in, SHUT_RDWR);
1604 shutdown(out, SHUT_RDWR);
1612 while (waitpid(sshpid, NULL, 0) == -1)
1614 fatal("Couldn't wait for ssh process: %s",
1617 exit(err == 0 ? 0 : 1);