1 /* $OpenBSD: sftp.c,v 1.89 2006/07/26 13:57:17 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/param.h>
26 #include <sys/socket.h>
37 typedef void EditLine;
46 #include "pathnames.h"
50 #include "sftp-common.h"
51 #include "sftp-client.h"
53 /* File to read commands from */
56 /* Are we in batchfile mode? */
59 /* Size of buffer used when copying files */
60 size_t copy_buffer_len = 32768;
62 /* Number of concurrent outstanding requests */
63 size_t num_requests = 16;
65 /* PID of ssh transport process */
66 static pid_t sshpid = -1;
68 /* This is set to 0 if the progressmeter is not desired. */
71 /* SIGINT received during command processing */
72 volatile sig_atomic_t interrupted = 0;
74 /* I wish qsort() took a separate ctx for the comparison function...*/
77 int remote_glob(struct sftp_conn *, const char *, int,
78 int (*)(const char *, int), glob_t *); /* proto for sftp-glob.c */
80 extern char *__progname;
82 /* Separators for interactive commands */
83 #define WHITESPACE " \t\r\n"
86 #define LS_LONG_VIEW 0x01 /* Full view ala ls -l */
87 #define LS_SHORT_VIEW 0x02 /* Single row view ala ls -1 */
88 #define LS_NUMERIC_VIEW 0x04 /* Long view with numeric uid/gid */
89 #define LS_NAME_SORT 0x08 /* Sort by name (default) */
90 #define LS_TIME_SORT 0x10 /* Sort by mtime */
91 #define LS_SIZE_SORT 0x20 /* Sort by file size */
92 #define LS_REVERSE_SORT 0x40 /* Reverse sort order */
93 #define LS_SHOW_ALL 0x80 /* Don't skip filenames starting with '.' */
95 #define VIEW_FLAGS (LS_LONG_VIEW|LS_SHORT_VIEW|LS_NUMERIC_VIEW)
96 #define SORT_FLAGS (LS_NAME_SORT|LS_TIME_SORT|LS_SIZE_SORT)
98 /* Commands for interactive mode */
121 #define I_PROGRESS 23
128 static const struct CMD cmds[] = {
131 { "chdir", I_CHDIR },
132 { "chgrp", I_CHGRP },
133 { "chmod", I_CHMOD },
134 { "chown", I_CHOWN },
141 { "lchdir", I_LCHDIR },
143 { "lmkdir", I_LMKDIR },
147 { "lumask", I_LUMASK },
148 { "mkdir", I_MKDIR },
149 { "progress", I_PROGRESS },
154 { "rename", I_RENAME },
156 { "rmdir", I_RMDIR },
157 { "symlink", I_SYMLINK },
158 { "version", I_VERSION },
164 int interactive_loop(int fd_in, int fd_out, char *file1, char *file2);
170 kill(sshpid, SIGTERM);
171 waitpid(sshpid, NULL, 0);
178 cmd_interrupt(int signo)
180 const char msg[] = "\rInterrupt \n";
181 int olderrno = errno;
183 write(STDERR_FILENO, msg, sizeof(msg) - 1);
191 printf("Available commands:\n");
192 printf("cd path Change remote directory to 'path'\n");
193 printf("lcd path Change local directory to 'path'\n");
194 printf("chgrp grp path Change group of file 'path' to 'grp'\n");
195 printf("chmod mode path Change permissions of file 'path' to 'mode'\n");
196 printf("chown own path Change owner of file 'path' to 'own'\n");
197 printf("help Display this help text\n");
198 printf("get remote-path [local-path] Download file\n");
199 printf("lls [ls-options [path]] Display local directory listing\n");
200 printf("ln oldpath newpath Symlink remote file\n");
201 printf("lmkdir path Create local directory\n");
202 printf("lpwd Print local working directory\n");
203 printf("ls [path] Display remote directory listing\n");
204 printf("lumask umask Set local umask to 'umask'\n");
205 printf("mkdir path Create remote directory\n");
206 printf("progress Toggle display of progress meter\n");
207 printf("put local-path [remote-path] Upload file\n");
208 printf("pwd Display remote working directory\n");
209 printf("exit Quit sftp\n");
210 printf("quit Quit sftp\n");
211 printf("rename oldpath newpath Rename remote file\n");
212 printf("rmdir path Remove remote directory\n");
213 printf("rm path Delete remote file\n");
214 printf("symlink oldpath newpath Symlink remote file\n");
215 printf("version Show SFTP version\n");
216 printf("!command Execute 'command' in local shell\n");
217 printf("! Escape to local shell\n");
218 printf("? Synonym for help\n");
222 local_do_shell(const char *args)
231 if ((shell = getenv("SHELL")) == NULL)
232 shell = _PATH_BSHELL;
234 if ((pid = fork()) == -1)
235 fatal("Couldn't fork: %s", strerror(errno));
238 /* XXX: child has pipe fds to ssh subproc open - issue? */
240 debug3("Executing %s -c \"%s\"", shell, args);
241 execl(shell, shell, "-c", args, (char *)NULL);
243 debug3("Executing %s", shell);
244 execl(shell, shell, (char *)NULL);
246 fprintf(stderr, "Couldn't execute \"%s\": %s\n", shell,
250 while (waitpid(pid, &status, 0) == -1)
252 fatal("Couldn't wait for child: %s", strerror(errno));
253 if (!WIFEXITED(status))
254 error("Shell exited abnormally");
255 else if (WEXITSTATUS(status))
256 error("Shell exited with status %d", WEXITSTATUS(status));
260 local_do_ls(const char *args)
263 local_do_shell(_PATH_LS);
265 int len = strlen(_PATH_LS " ") + strlen(args) + 1;
266 char *buf = xmalloc(len);
268 /* XXX: quoting - rip quoting code from ftp? */
269 snprintf(buf, len, _PATH_LS " %s", args);
275 /* Strip one path (usually the pwd) from the start of another */
277 path_strip(char *path, char *strip)
282 return (xstrdup(path));
285 if (strncmp(path, strip, len) == 0) {
286 if (strip[len - 1] != '/' && path[len] == '/')
288 return (xstrdup(path + len));
291 return (xstrdup(path));
295 path_append(char *p1, char *p2)
298 int len = strlen(p1) + strlen(p2) + 2;
301 strlcpy(ret, p1, len);
302 if (p1[strlen(p1) - 1] != '/')
303 strlcat(ret, "/", len);
304 strlcat(ret, p2, len);
310 make_absolute(char *p, char *pwd)
315 if (p && p[0] != '/') {
316 abs_str = path_append(pwd, p);
324 infer_path(const char *p, char **ifp)
328 cp = strrchr(p, '/');
335 error("Invalid path");
339 *ifp = xstrdup(cp + 1);
344 parse_getput_flags(const char **cpp, int *pflag)
346 const char *cp = *cpp;
348 /* Check for flags */
349 if (cp[0] == '-' && cp[1] && strchr(WHITESPACE, cp[2])) {
356 error("Invalid flag -%c", cp[1]);
360 *cpp = cp + strspn(cp, WHITESPACE);
367 parse_ls_flags(const char **cpp, int *lflag)
369 const char *cp = *cpp;
372 *lflag = LS_NAME_SORT;
374 /* Check for flags */
375 if (cp++[0] == '-') {
376 for (; strchr(WHITESPACE, *cp) == NULL; cp++) {
379 *lflag &= ~VIEW_FLAGS;
380 *lflag |= LS_LONG_VIEW;
383 *lflag &= ~VIEW_FLAGS;
384 *lflag |= LS_SHORT_VIEW;
387 *lflag &= ~VIEW_FLAGS;
388 *lflag |= LS_NUMERIC_VIEW|LS_LONG_VIEW;
391 *lflag &= ~SORT_FLAGS;
392 *lflag |= LS_SIZE_SORT;
395 *lflag &= ~SORT_FLAGS;
396 *lflag |= LS_TIME_SORT;
399 *lflag |= LS_REVERSE_SORT;
402 *lflag &= ~SORT_FLAGS;
405 *lflag |= LS_SHOW_ALL;
408 error("Invalid flag -%c", *cp);
412 *cpp = cp + strspn(cp, WHITESPACE);
419 get_pathname(const char **cpp, char **path)
421 const char *cp = *cpp, *end;
425 cp += strspn(cp, WHITESPACE);
432 *path = xmalloc(strlen(cp) + 1);
434 /* Check for quoted filenames */
435 if (*cp == '\"' || *cp == '\'') {
438 /* Search for terminating quote, unescape some chars */
439 for (i = j = 0; i <= strlen(cp); i++) {
440 if (cp[i] == quot) { /* Found quote */
445 if (cp[i] == '\0') { /* End of string */
446 error("Unterminated quote");
449 if (cp[i] == '\\') { /* Escaped characters */
451 if (cp[i] != '\'' && cp[i] != '\"' &&
453 error("Bad escaped character '\\%c'",
458 (*path)[j++] = cp[i];
462 error("Empty quotes");
465 *cpp = cp + i + strspn(cp + i, WHITESPACE);
467 /* Read to end of filename */
468 end = strpbrk(cp, WHITESPACE);
470 end = strchr(cp, '\0');
471 *cpp = end + strspn(end, WHITESPACE);
473 memcpy(*path, cp, end - cp);
474 (*path)[end - cp] = '\0';
489 /* XXX: report errors? */
490 if (stat(path, &sb) == -1)
493 return(sb.st_mode & S_IFDIR);
501 if (stat(path, &sb) == -1)
502 fatal("stat %s: %s", path, strerror(errno));
504 return(S_ISREG(sb.st_mode));
508 remote_is_dir(struct sftp_conn *conn, char *path)
512 /* XXX: report errors? */
513 if ((a = do_stat(conn, path, 1)) == NULL)
515 if (!(a->flags & SSH2_FILEXFER_ATTR_PERMISSIONS))
517 return(a->perm & S_IFDIR);
521 process_get(struct sftp_conn *conn, char *src, char *dst, char *pwd, int pflag)
523 char *abs_src = NULL;
524 char *abs_dst = NULL;
530 abs_src = xstrdup(src);
531 abs_src = make_absolute(abs_src, pwd);
533 memset(&g, 0, sizeof(g));
534 debug3("Looking up %s", abs_src);
535 if (remote_glob(conn, abs_src, 0, NULL, &g)) {
536 error("File \"%s\" not found.", abs_src);
541 /* If multiple matches, dst must be a directory or unspecified */
542 if (g.gl_matchc > 1 && dst && !is_dir(dst)) {
543 error("Multiple files match, but \"%s\" is not a directory",
549 for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
550 if (infer_path(g.gl_pathv[i], &tmp)) {
555 if (g.gl_matchc == 1 && dst) {
556 /* If directory specified, append filename */
559 if (infer_path(g.gl_pathv[0], &tmp)) {
563 abs_dst = path_append(dst, tmp);
566 abs_dst = xstrdup(dst);
568 abs_dst = path_append(dst, tmp);
573 printf("Fetching %s to %s\n", g.gl_pathv[i], abs_dst);
574 if (do_download(conn, g.gl_pathv[i], abs_dst, pflag) == -1)
587 process_put(struct sftp_conn *conn, char *src, char *dst, char *pwd, int pflag)
589 char *tmp_dst = NULL;
590 char *abs_dst = NULL;
597 tmp_dst = xstrdup(dst);
598 tmp_dst = make_absolute(tmp_dst, pwd);
601 memset(&g, 0, sizeof(g));
602 debug3("Looking up %s", src);
603 if (glob(src, 0, NULL, &g)) {
604 error("File \"%s\" not found.", src);
609 /* If multiple matches, dst may be directory or unspecified */
610 if (g.gl_matchc > 1 && tmp_dst && !remote_is_dir(conn, tmp_dst)) {
611 error("Multiple files match, but \"%s\" is not a directory",
617 for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
618 if (!is_reg(g.gl_pathv[i])) {
619 error("skipping non-regular file %s",
623 if (infer_path(g.gl_pathv[i], &tmp)) {
628 if (g.gl_matchc == 1 && tmp_dst) {
629 /* If directory specified, append filename */
630 if (remote_is_dir(conn, tmp_dst)) {
631 if (infer_path(g.gl_pathv[0], &tmp)) {
635 abs_dst = path_append(tmp_dst, tmp);
638 abs_dst = xstrdup(tmp_dst);
640 } else if (tmp_dst) {
641 abs_dst = path_append(tmp_dst, tmp);
644 abs_dst = make_absolute(tmp, pwd);
646 printf("Uploading %s to %s\n", g.gl_pathv[i], abs_dst);
647 if (do_upload(conn, g.gl_pathv[i], abs_dst, pflag) == -1)
661 sdirent_comp(const void *aa, const void *bb)
663 SFTP_DIRENT *a = *(SFTP_DIRENT **)aa;
664 SFTP_DIRENT *b = *(SFTP_DIRENT **)bb;
665 int rmul = sort_flag & LS_REVERSE_SORT ? -1 : 1;
667 #define NCMP(a,b) (a == b ? 0 : (a < b ? 1 : -1))
668 if (sort_flag & LS_NAME_SORT)
669 return (rmul * strcmp(a->filename, b->filename));
670 else if (sort_flag & LS_TIME_SORT)
671 return (rmul * NCMP(a->a.mtime, b->a.mtime));
672 else if (sort_flag & LS_SIZE_SORT)
673 return (rmul * NCMP(a->a.size, b->a.size));
675 fatal("Unknown ls sort type");
678 /* sftp ls.1 replacement for directories */
680 do_ls_dir(struct sftp_conn *conn, char *path, char *strip_path, int lflag)
683 u_int c = 1, colspace = 0, columns = 1;
686 if ((n = do_readdir(conn, path, &d)) != 0)
689 if (!(lflag & LS_SHORT_VIEW)) {
690 u_int m = 0, width = 80;
694 /* Count entries for sort and find longest filename */
695 for (n = 0; d[n] != NULL; n++) {
696 if (d[n]->filename[0] != '.' || (lflag & LS_SHOW_ALL))
697 m = MAX(m, strlen(d[n]->filename));
700 /* Add any subpath that also needs to be counted */
701 tmp = path_strip(path, strip_path);
705 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) != -1)
708 columns = width / (m + 2);
709 columns = MAX(columns, 1);
710 colspace = width / columns;
711 colspace = MIN(colspace, width);
714 if (lflag & SORT_FLAGS) {
715 for (n = 0; d[n] != NULL; n++)
716 ; /* count entries */
717 sort_flag = lflag & (SORT_FLAGS|LS_REVERSE_SORT);
718 qsort(d, n, sizeof(*d), sdirent_comp);
721 for (n = 0; d[n] != NULL && !interrupted; n++) {
724 if (d[n]->filename[0] == '.' && !(lflag & LS_SHOW_ALL))
727 tmp = path_append(path, d[n]->filename);
728 fname = path_strip(tmp, strip_path);
731 if (lflag & LS_LONG_VIEW) {
732 if (lflag & LS_NUMERIC_VIEW) {
736 memset(&sb, 0, sizeof(sb));
737 attrib_to_stat(&d[n]->a, &sb);
738 lname = ls_file(fname, &sb, 1);
739 printf("%s\n", lname);
742 printf("%s\n", d[n]->longname);
744 printf("%-*s", colspace, fname);
755 if (!(lflag & LS_LONG_VIEW) && (c != 1))
758 free_sftp_dirents(d);
762 /* sftp ls.1 replacement which handles path globs */
764 do_globbed_ls(struct sftp_conn *conn, char *path, char *strip_path,
768 u_int i, c = 1, colspace = 0, columns = 1;
771 memset(&g, 0, sizeof(g));
773 if (remote_glob(conn, path, GLOB_MARK|GLOB_NOCHECK|GLOB_BRACE,
774 NULL, &g) || (g.gl_pathc && !g.gl_matchc)) {
777 error("Can't ls: \"%s\" not found", path);
785 * If the glob returns a single match and it is a directory,
786 * then just list its contents.
788 if (g.gl_matchc == 1) {
789 if ((a = do_lstat(conn, g.gl_pathv[0], 1)) == NULL) {
793 if ((a->flags & SSH2_FILEXFER_ATTR_PERMISSIONS) &&
797 err = do_ls_dir(conn, g.gl_pathv[0], strip_path, lflag);
803 if (!(lflag & LS_SHORT_VIEW)) {
804 u_int m = 0, width = 80;
807 /* Count entries for sort and find longest filename */
808 for (i = 0; g.gl_pathv[i]; i++)
809 m = MAX(m, strlen(g.gl_pathv[i]));
811 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) != -1)
814 columns = width / (m + 2);
815 columns = MAX(columns, 1);
816 colspace = width / columns;
819 for (i = 0; g.gl_pathv[i] && !interrupted; i++, a = NULL) {
822 fname = path_strip(g.gl_pathv[i], strip_path);
824 if (lflag & LS_LONG_VIEW) {
829 * XXX: this is slow - 1 roundtrip per path
830 * A solution to this is to fork glob() and
831 * build a sftp specific version which keeps the
832 * attribs (which currently get thrown away)
833 * that the server returns as well as the filenames.
835 memset(&sb, 0, sizeof(sb));
837 a = do_lstat(conn, g.gl_pathv[i], 1);
839 attrib_to_stat(a, &sb);
840 lname = ls_file(fname, &sb, 1);
841 printf("%s\n", lname);
844 printf("%-*s", colspace, fname);
854 if (!(lflag & LS_LONG_VIEW) && (c != 1))
865 parse_args(const char **cpp, int *pflag, int *lflag, int *iflag,
866 unsigned long *n_arg, char **path1, char **path2)
868 const char *cmd, *cp = *cpp;
874 /* Skip leading whitespace */
875 cp = cp + strspn(cp, WHITESPACE);
877 /* Ignore blank lines and lines which begin with comment '#' char */
878 if (*cp == '\0' || *cp == '#')
881 /* Check for leading '-' (disable error processing) */
888 /* Figure out which command we have */
889 for (i = 0; cmds[i].c; i++) {
890 int cmdlen = strlen(cmds[i].c);
892 /* Check for command followed by whitespace */
893 if (!strncasecmp(cp, cmds[i].c, cmdlen) &&
894 strchr(WHITESPACE, cp[cmdlen])) {
896 cp = cp + strspn(cp, WHITESPACE);
907 } else if (cmdnum == -1) {
908 error("Invalid command.");
912 /* Get arguments and parse flags */
913 *lflag = *pflag = *n_arg = 0;
914 *path1 = *path2 = NULL;
918 if (parse_getput_flags(&cp, pflag))
920 /* Get first pathname (mandatory) */
921 if (get_pathname(&cp, path1))
923 if (*path1 == NULL) {
924 error("You must specify at least one path after a "
928 /* Try to get second pathname (optional) */
929 if (get_pathname(&cp, path2))
934 if (get_pathname(&cp, path1))
936 if (get_pathname(&cp, path2))
938 if (!*path1 || !*path2) {
939 error("You must specify two paths after a %s "
950 /* Get pathname (mandatory) */
951 if (get_pathname(&cp, path1))
953 if (*path1 == NULL) {
954 error("You must specify a path after a %s command.",
960 if (parse_ls_flags(&cp, lflag))
962 /* Path is optional */
963 if (get_pathname(&cp, path1))
968 /* Uses the rest of the line */
976 /* Get numeric arg (mandatory) */
977 l = strtol(cp, &cp2, base);
978 if (cp2 == cp || ((l == LONG_MIN || l == LONG_MAX) &&
979 errno == ERANGE) || l < 0) {
980 error("You must supply a numeric argument "
981 "to the %s command.", cmd);
986 if (cmdnum == I_LUMASK && strchr(WHITESPACE, *cp))
988 if (cmdnum == I_LUMASK || !strchr(WHITESPACE, *cp)) {
989 error("You must supply a numeric argument "
990 "to the %s command.", cmd);
993 cp += strspn(cp, WHITESPACE);
995 /* Get pathname (mandatory) */
996 if (get_pathname(&cp, path1))
998 if (*path1 == NULL) {
999 error("You must specify a path after a %s command.",
1012 fatal("Command not implemented");
1020 parse_dispatch_command(struct sftp_conn *conn, const char *cmd, char **pwd,
1023 char *path1, *path2, *tmp;
1024 int pflag, lflag, iflag, cmdnum, i;
1025 unsigned long n_arg;
1027 char path_buf[MAXPATHLEN];
1031 path1 = path2 = NULL;
1032 cmdnum = parse_args(&cmd, &pflag, &lflag, &iflag, &n_arg,
1038 memset(&g, 0, sizeof(g));
1040 /* Perform command */
1046 /* Unrecognized command */
1050 err = process_get(conn, path1, path2, *pwd, pflag);
1053 err = process_put(conn, path1, path2, *pwd, pflag);
1056 path1 = make_absolute(path1, *pwd);
1057 path2 = make_absolute(path2, *pwd);
1058 err = do_rename(conn, path1, path2);
1061 path2 = make_absolute(path2, *pwd);
1062 err = do_symlink(conn, path1, path2);
1065 path1 = make_absolute(path1, *pwd);
1066 remote_glob(conn, path1, GLOB_NOCHECK, NULL, &g);
1067 for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
1068 printf("Removing %s\n", g.gl_pathv[i]);
1069 err = do_rm(conn, g.gl_pathv[i]);
1070 if (err != 0 && err_abort)
1075 path1 = make_absolute(path1, *pwd);
1077 a.flags |= SSH2_FILEXFER_ATTR_PERMISSIONS;
1079 err = do_mkdir(conn, path1, &a);
1082 path1 = make_absolute(path1, *pwd);
1083 err = do_rmdir(conn, path1);
1086 path1 = make_absolute(path1, *pwd);
1087 if ((tmp = do_realpath(conn, path1)) == NULL) {
1091 if ((aa = do_stat(conn, tmp, 0)) == NULL) {
1096 if (!(aa->flags & SSH2_FILEXFER_ATTR_PERMISSIONS)) {
1097 error("Can't change directory: Can't check target");
1102 if (!S_ISDIR(aa->perm)) {
1103 error("Can't change directory: \"%s\" is not "
1104 "a directory", tmp);
1114 do_globbed_ls(conn, *pwd, *pwd, lflag);
1118 /* Strip pwd off beginning of non-absolute paths */
1123 path1 = make_absolute(path1, *pwd);
1124 err = do_globbed_ls(conn, path1, tmp, lflag);
1127 if (chdir(path1) == -1) {
1128 error("Couldn't change local directory to "
1129 "\"%s\": %s", path1, strerror(errno));
1134 if (mkdir(path1, 0777) == -1) {
1135 error("Couldn't create local directory "
1136 "\"%s\": %s", path1, strerror(errno));
1144 local_do_shell(cmd);
1148 printf("Local umask: %03lo\n", n_arg);
1151 path1 = make_absolute(path1, *pwd);
1153 a.flags |= SSH2_FILEXFER_ATTR_PERMISSIONS;
1155 remote_glob(conn, path1, GLOB_NOCHECK, NULL, &g);
1156 for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
1157 printf("Changing mode on %s\n", g.gl_pathv[i]);
1158 err = do_setstat(conn, g.gl_pathv[i], &a);
1159 if (err != 0 && err_abort)
1165 path1 = make_absolute(path1, *pwd);
1166 remote_glob(conn, path1, GLOB_NOCHECK, NULL, &g);
1167 for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
1168 if (!(aa = do_stat(conn, g.gl_pathv[i], 0))) {
1169 if (err != 0 && err_abort)
1174 if (!(aa->flags & SSH2_FILEXFER_ATTR_UIDGID)) {
1175 error("Can't get current ownership of "
1176 "remote file \"%s\"", g.gl_pathv[i]);
1177 if (err != 0 && err_abort)
1182 aa->flags &= SSH2_FILEXFER_ATTR_UIDGID;
1183 if (cmdnum == I_CHOWN) {
1184 printf("Changing owner on %s\n", g.gl_pathv[i]);
1187 printf("Changing group on %s\n", g.gl_pathv[i]);
1190 err = do_setstat(conn, g.gl_pathv[i], aa);
1191 if (err != 0 && err_abort)
1196 printf("Remote working directory: %s\n", *pwd);
1199 if (!getcwd(path_buf, sizeof(path_buf))) {
1200 error("Couldn't get local cwd: %s", strerror(errno));
1204 printf("Local working directory: %s\n", path_buf);
1207 /* Processed below */
1213 printf("SFTP protocol version %u\n", sftp_proto_version(conn));
1216 showprogress = !showprogress;
1218 printf("Progress meter enabled\n");
1220 printf("Progress meter disabled\n");
1223 fatal("%d is not implemented", cmdnum);
1233 /* If an unignored error occurs in batch mode we should abort. */
1234 if (err_abort && err != 0)
1236 else if (cmdnum == I_QUIT)
1244 prompt(EditLine *el)
1251 interactive_loop(int fd_in, int fd_out, char *file1, char *file2)
1256 struct sftp_conn *conn;
1257 int err, interactive;
1258 EditLine *el = NULL;
1262 extern char *__progname;
1264 if (!batchmode && isatty(STDIN_FILENO)) {
1265 if ((el = el_init(__progname, stdin, stdout, stderr)) == NULL)
1266 fatal("Couldn't initialise editline");
1267 if ((hl = history_init()) == NULL)
1268 fatal("Couldn't initialise editline history");
1269 history(hl, &hev, H_SETSIZE, 100);
1270 el_set(el, EL_HIST, history, hl);
1272 el_set(el, EL_PROMPT, prompt);
1273 el_set(el, EL_EDITOR, "emacs");
1274 el_set(el, EL_TERMINAL, NULL);
1275 el_set(el, EL_SIGNAL, 1);
1276 el_source(el, NULL);
1278 #endif /* USE_LIBEDIT */
1280 conn = do_init(fd_in, fd_out, copy_buffer_len, num_requests);
1282 fatal("Couldn't initialise connection to server");
1284 pwd = do_realpath(conn, ".");
1288 if (file1 != NULL) {
1289 dir = xstrdup(file1);
1290 dir = make_absolute(dir, pwd);
1292 if (remote_is_dir(conn, dir) && file2 == NULL) {
1293 printf("Changing to: %s\n", dir);
1294 snprintf(cmd, sizeof cmd, "cd \"%s\"", dir);
1295 if (parse_dispatch_command(conn, cmd, &pwd, 1) != 0) {
1303 snprintf(cmd, sizeof cmd, "get %s", dir);
1305 snprintf(cmd, sizeof cmd, "get %s %s", dir,
1308 err = parse_dispatch_command(conn, cmd, &pwd, 1);
1317 #if defined(HAVE_SETVBUF) && !defined(BROKEN_SETVBUF)
1318 setvbuf(stdout, NULL, _IOLBF, 0);
1319 setvbuf(infile, NULL, _IOLBF, 0);
1325 interactive = !batchmode && isatty(STDIN_FILENO);
1330 signal(SIGINT, SIG_IGN);
1335 if (fgets(cmd, sizeof(cmd), infile) == NULL) {
1340 if (!interactive) { /* Echo command */
1341 printf("sftp> %s", cmd);
1342 if (strlen(cmd) > 0 &&
1343 cmd[strlen(cmd) - 1] != '\n')
1351 if ((line = el_gets(el, &count)) == NULL || count <= 0) {
1355 history(hl, &hev, H_ENTER, line);
1356 if (strlcpy(cmd, line, sizeof(cmd)) >= sizeof(cmd)) {
1357 fprintf(stderr, "Error: input line too long\n");
1360 #endif /* USE_LIBEDIT */
1363 cp = strrchr(cmd, '\n');
1367 /* Handle user interrupts gracefully during commands */
1369 signal(SIGINT, cmd_interrupt);
1371 err = parse_dispatch_command(conn, cmd, &pwd, batchmode);
1381 #endif /* USE_LIBEDIT */
1383 /* err == 1 signifies normal "quit" exit */
1384 return (err >= 0 ? 0 : -1);
1388 connect_to_server(char *path, char **args, int *in, int *out)
1393 int pin[2], pout[2];
1395 if ((pipe(pin) == -1) || (pipe(pout) == -1))
1396 fatal("pipe: %s", strerror(errno));
1401 #else /* USE_PIPES */
1404 if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) == -1)
1405 fatal("socketpair: %s", strerror(errno));
1406 *in = *out = inout[0];
1407 c_in = c_out = inout[1];
1408 #endif /* USE_PIPES */
1410 if ((sshpid = fork()) == -1)
1411 fatal("fork: %s", strerror(errno));
1412 else if (sshpid == 0) {
1413 if ((dup2(c_in, STDIN_FILENO) == -1) ||
1414 (dup2(c_out, STDOUT_FILENO) == -1)) {
1415 fprintf(stderr, "dup2: %s\n", strerror(errno));
1424 * The underlying ssh is in the same process group, so we must
1425 * ignore SIGINT if we want to gracefully abort commands,
1426 * otherwise the signal will make it to the ssh process and
1429 signal(SIGINT, SIG_IGN);
1431 fprintf(stderr, "exec: %s: %s\n", path, strerror(errno));
1435 signal(SIGTERM, killchild);
1436 signal(SIGINT, killchild);
1437 signal(SIGHUP, killchild);
1445 extern char *__progname;
1448 "usage: %s [-1Cv] [-B buffer_size] [-b batchfile] [-F ssh_config]\n"
1449 " [-o ssh_option] [-P sftp_server_path] [-R num_requests]\n"
1450 " [-S program] [-s subsystem | sftp_server] host\n"
1451 " %s [[user@]host[:file [file]]]\n"
1452 " %s [[user@]host[:dir[/]]]\n"
1453 " %s -b batchfile [user@]host\n", __progname, __progname, __progname, __progname);
1458 main(int argc, char **argv)
1460 int in, out, ch, err;
1461 char *host, *userhost, *cp, *file2 = NULL;
1462 int debug_level = 0, sshver = 2;
1463 char *file1 = NULL, *sftp_server = NULL;
1464 char *ssh_program = _PATH_SSH_PROGRAM, *sftp_direct = NULL;
1465 LogLevel ll = SYSLOG_LEVEL_INFO;
1468 extern char *optarg;
1470 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
1473 __progname = ssh_get_progname(argv[0]);
1474 memset(&args, '\0', sizeof(args));
1476 addargs(&args, "%s", ssh_program);
1477 addargs(&args, "-oForwardX11 no");
1478 addargs(&args, "-oForwardAgent no");
1479 addargs(&args, "-oPermitLocalCommand no");
1480 addargs(&args, "-oClearAllForwardings yes");
1482 ll = SYSLOG_LEVEL_INFO;
1485 while ((ch = getopt(argc, argv, "1hvCo:s:S:b:B:F:P:R:")) != -1) {
1488 addargs(&args, "-C");
1491 if (debug_level < 3) {
1492 addargs(&args, "-v");
1493 ll = SYSLOG_LEVEL_DEBUG1 + debug_level;
1499 addargs(&args, "-%c%s", ch, optarg);
1503 if (sftp_server == NULL)
1504 sftp_server = _PATH_SFTP_SERVER;
1507 sftp_server = optarg;
1510 ssh_program = optarg;
1511 replacearg(&args, 0, "%s", ssh_program);
1515 fatal("Batch file already specified.");
1517 /* Allow "-" as stdin */
1518 if (strcmp(optarg, "-") != 0 &&
1519 (infile = fopen(optarg, "r")) == NULL)
1520 fatal("%s (%s).", strerror(errno), optarg);
1523 addargs(&args, "-obatchmode yes");
1526 sftp_direct = optarg;
1529 copy_buffer_len = strtol(optarg, &cp, 10);
1530 if (copy_buffer_len == 0 || *cp != '\0')
1531 fatal("Invalid buffer size \"%s\"", optarg);
1534 num_requests = strtol(optarg, &cp, 10);
1535 if (num_requests == 0 || *cp != '\0')
1536 fatal("Invalid number of requests \"%s\"",
1545 if (!isatty(STDERR_FILENO))
1548 log_init(argv[0], ll, SYSLOG_FACILITY_USER, 1);
1550 if (sftp_direct == NULL) {
1551 if (optind == argc || argc > (optind + 2))
1554 userhost = xstrdup(argv[optind]);
1555 file2 = argv[optind+1];
1557 if ((host = strrchr(userhost, '@')) == NULL)
1562 fprintf(stderr, "Missing username\n");
1565 addargs(&args, "-l%s",userhost);
1568 if ((cp = colon(host)) != NULL) {
1573 host = cleanhostname(host);
1575 fprintf(stderr, "Missing hostname\n");
1579 addargs(&args, "-oProtocol %d", sshver);
1581 /* no subsystem if the server-spec contains a '/' */
1582 if (sftp_server == NULL || strchr(sftp_server, '/') == NULL)
1583 addargs(&args, "-s");
1585 addargs(&args, "%s", host);
1586 addargs(&args, "%s", (sftp_server != NULL ?
1587 sftp_server : "sftp"));
1590 fprintf(stderr, "Connecting to %s...\n", host);
1591 connect_to_server(ssh_program, args.list, &in, &out);
1594 addargs(&args, "sftp-server");
1597 fprintf(stderr, "Attaching to %s...\n", sftp_direct);
1598 connect_to_server(sftp_direct, args.list, &in, &out);
1602 err = interactive_loop(in, out, file1, file2);
1604 #if !defined(USE_PIPES)
1605 shutdown(in, SHUT_RDWR);
1606 shutdown(out, SHUT_RDWR);
1614 while (waitpid(sshpid, NULL, 0) == -1)
1616 fatal("Couldn't wait for ssh process: %s",
1619 exit(err == 0 ? 0 : 1);