1 /* $OpenBSD: sftp.c,v 1.96 2007/01/03 04:09:15 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 #include <sys/ioctl.h>
22 #ifdef HAVE_SYS_STAT_H
23 # include <sys/stat.h>
25 #include <sys/param.h>
26 #include <sys/socket.h>
37 typedef void EditLine;
48 #include "pathnames.h"
53 #include "sftp-common.h"
54 #include "sftp-client.h"
56 /* File to read commands from */
59 /* Are we in batchfile mode? */
62 /* Size of buffer used when copying files */
63 size_t copy_buffer_len = 32768;
65 /* Number of concurrent outstanding requests */
66 size_t num_requests = 16;
68 /* PID of ssh transport process */
69 static pid_t sshpid = -1;
71 /* This is set to 0 if the progressmeter is not desired. */
74 /* SIGINT received during command processing */
75 volatile sig_atomic_t interrupted = 0;
77 /* I wish qsort() took a separate ctx for the comparison function...*/
80 int remote_glob(struct sftp_conn *, const char *, int,
81 int (*)(const char *, int), glob_t *); /* proto for sftp-glob.c */
83 extern char *__progname;
85 /* Separators for interactive commands */
86 #define WHITESPACE " \t\r\n"
89 #define LS_LONG_VIEW 0x01 /* Full view ala ls -l */
90 #define LS_SHORT_VIEW 0x02 /* Single row view ala ls -1 */
91 #define LS_NUMERIC_VIEW 0x04 /* Long view with numeric uid/gid */
92 #define LS_NAME_SORT 0x08 /* Sort by name (default) */
93 #define LS_TIME_SORT 0x10 /* Sort by mtime */
94 #define LS_SIZE_SORT 0x20 /* Sort by file size */
95 #define LS_REVERSE_SORT 0x40 /* Reverse sort order */
96 #define LS_SHOW_ALL 0x80 /* Don't skip filenames starting with '.' */
98 #define VIEW_FLAGS (LS_LONG_VIEW|LS_SHORT_VIEW|LS_NUMERIC_VIEW)
99 #define SORT_FLAGS (LS_NAME_SORT|LS_TIME_SORT|LS_SIZE_SORT)
101 /* Commands for interactive mode */
124 #define I_PROGRESS 23
131 static const struct CMD cmds[] = {
134 { "chdir", I_CHDIR },
135 { "chgrp", I_CHGRP },
136 { "chmod", I_CHMOD },
137 { "chown", I_CHOWN },
144 { "lchdir", I_LCHDIR },
146 { "lmkdir", I_LMKDIR },
150 { "lumask", I_LUMASK },
151 { "mkdir", I_MKDIR },
152 { "progress", I_PROGRESS },
157 { "rename", I_RENAME },
159 { "rmdir", I_RMDIR },
160 { "symlink", I_SYMLINK },
161 { "version", I_VERSION },
167 int interactive_loop(int fd_in, int fd_out, char *file1, char *file2);
174 kill(sshpid, SIGTERM);
175 waitpid(sshpid, NULL, 0);
183 cmd_interrupt(int signo)
185 const char msg[] = "\rInterrupt \n";
186 int olderrno = errno;
188 write(STDERR_FILENO, msg, sizeof(msg) - 1);
196 printf("Available commands:\n");
197 printf("cd path Change remote directory to 'path'\n");
198 printf("lcd path Change local directory to 'path'\n");
199 printf("chgrp grp path Change group of file 'path' to 'grp'\n");
200 printf("chmod mode path Change permissions of file 'path' to 'mode'\n");
201 printf("chown own path Change owner of file 'path' to 'own'\n");
202 printf("help Display this help text\n");
203 printf("get remote-path [local-path] Download file\n");
204 printf("lls [ls-options [path]] Display local directory listing\n");
205 printf("ln oldpath newpath Symlink remote file\n");
206 printf("lmkdir path Create local directory\n");
207 printf("lpwd Print local working directory\n");
208 printf("ls [path] Display remote directory listing\n");
209 printf("lumask umask Set local umask to 'umask'\n");
210 printf("mkdir path Create remote directory\n");
211 printf("progress Toggle display of progress meter\n");
212 printf("put local-path [remote-path] Upload file\n");
213 printf("pwd Display remote working directory\n");
214 printf("exit Quit sftp\n");
215 printf("quit Quit sftp\n");
216 printf("rename oldpath newpath Rename remote file\n");
217 printf("rmdir path Remove remote directory\n");
218 printf("rm path Delete remote file\n");
219 printf("symlink oldpath newpath Symlink remote file\n");
220 printf("version Show SFTP version\n");
221 printf("!command Execute 'command' in local shell\n");
222 printf("! Escape to local shell\n");
223 printf("? Synonym for help\n");
227 local_do_shell(const char *args)
236 if ((shell = getenv("SHELL")) == NULL)
237 shell = _PATH_BSHELL;
239 if ((pid = fork()) == -1)
240 fatal("Couldn't fork: %s", strerror(errno));
243 /* XXX: child has pipe fds to ssh subproc open - issue? */
245 debug3("Executing %s -c \"%s\"", shell, args);
246 execl(shell, shell, "-c", args, (char *)NULL);
248 debug3("Executing %s", shell);
249 execl(shell, shell, (char *)NULL);
251 fprintf(stderr, "Couldn't execute \"%s\": %s\n", shell,
255 while (waitpid(pid, &status, 0) == -1)
257 fatal("Couldn't wait for child: %s", strerror(errno));
258 if (!WIFEXITED(status))
259 error("Shell exited abnormally");
260 else if (WEXITSTATUS(status))
261 error("Shell exited with status %d", WEXITSTATUS(status));
265 local_do_ls(const char *args)
268 local_do_shell(_PATH_LS);
270 int len = strlen(_PATH_LS " ") + strlen(args) + 1;
271 char *buf = xmalloc(len);
273 /* XXX: quoting - rip quoting code from ftp? */
274 snprintf(buf, len, _PATH_LS " %s", args);
280 /* Strip one path (usually the pwd) from the start of another */
282 path_strip(char *path, char *strip)
287 return (xstrdup(path));
290 if (strncmp(path, strip, len) == 0) {
291 if (strip[len - 1] != '/' && path[len] == '/')
293 return (xstrdup(path + len));
296 return (xstrdup(path));
300 path_append(char *p1, char *p2)
303 size_t len = strlen(p1) + strlen(p2) + 2;
306 strlcpy(ret, p1, len);
307 if (p1[0] != '\0' && p1[strlen(p1) - 1] != '/')
308 strlcat(ret, "/", len);
309 strlcat(ret, p2, len);
315 make_absolute(char *p, char *pwd)
320 if (p && p[0] != '/') {
321 abs_str = path_append(pwd, p);
329 infer_path(const char *p, char **ifp)
333 cp = strrchr(p, '/');
340 error("Invalid path");
344 *ifp = xstrdup(cp + 1);
349 parse_getput_flags(const char **cpp, int *pflag)
351 const char *cp = *cpp;
353 /* Check for flags */
354 if (cp[0] == '-' && cp[1] && strchr(WHITESPACE, cp[2])) {
361 error("Invalid flag -%c", cp[1]);
365 *cpp = cp + strspn(cp, WHITESPACE);
372 parse_ls_flags(const char **cpp, int *lflag)
374 const char *cp = *cpp;
377 *lflag = LS_NAME_SORT;
379 /* Check for flags */
380 if (cp++[0] == '-') {
381 for (; strchr(WHITESPACE, *cp) == NULL; cp++) {
384 *lflag &= ~VIEW_FLAGS;
385 *lflag |= LS_LONG_VIEW;
388 *lflag &= ~VIEW_FLAGS;
389 *lflag |= LS_SHORT_VIEW;
392 *lflag &= ~VIEW_FLAGS;
393 *lflag |= LS_NUMERIC_VIEW|LS_LONG_VIEW;
396 *lflag &= ~SORT_FLAGS;
397 *lflag |= LS_SIZE_SORT;
400 *lflag &= ~SORT_FLAGS;
401 *lflag |= LS_TIME_SORT;
404 *lflag |= LS_REVERSE_SORT;
407 *lflag &= ~SORT_FLAGS;
410 *lflag |= LS_SHOW_ALL;
413 error("Invalid flag -%c", *cp);
417 *cpp = cp + strspn(cp, WHITESPACE);
424 get_pathname(const char **cpp, char **path)
426 const char *cp = *cpp, *end;
430 cp += strspn(cp, WHITESPACE);
437 *path = xmalloc(strlen(cp) + 1);
439 /* Check for quoted filenames */
440 if (*cp == '\"' || *cp == '\'') {
443 /* Search for terminating quote, unescape some chars */
444 for (i = j = 0; i <= strlen(cp); i++) {
445 if (cp[i] == quot) { /* Found quote */
450 if (cp[i] == '\0') { /* End of string */
451 error("Unterminated quote");
454 if (cp[i] == '\\') { /* Escaped characters */
456 if (cp[i] != '\'' && cp[i] != '\"' &&
458 error("Bad escaped character '\\%c'",
463 (*path)[j++] = cp[i];
467 error("Empty quotes");
470 *cpp = cp + i + strspn(cp + i, WHITESPACE);
472 /* Read to end of filename */
473 end = strpbrk(cp, WHITESPACE);
475 end = strchr(cp, '\0');
476 *cpp = end + strspn(end, WHITESPACE);
478 memcpy(*path, cp, end - cp);
479 (*path)[end - cp] = '\0';
494 /* XXX: report errors? */
495 if (stat(path, &sb) == -1)
498 return(S_ISDIR(sb.st_mode));
506 if (stat(path, &sb) == -1)
507 fatal("stat %s: %s", path, strerror(errno));
509 return(S_ISREG(sb.st_mode));
513 remote_is_dir(struct sftp_conn *conn, char *path)
517 /* XXX: report errors? */
518 if ((a = do_stat(conn, path, 1)) == NULL)
520 if (!(a->flags & SSH2_FILEXFER_ATTR_PERMISSIONS))
522 return(S_ISDIR(a->perm));
526 process_get(struct sftp_conn *conn, char *src, char *dst, char *pwd, int pflag)
528 char *abs_src = NULL;
529 char *abs_dst = NULL;
535 abs_src = xstrdup(src);
536 abs_src = make_absolute(abs_src, pwd);
538 memset(&g, 0, sizeof(g));
539 debug3("Looking up %s", abs_src);
540 if (remote_glob(conn, abs_src, 0, NULL, &g)) {
541 error("File \"%s\" not found.", abs_src);
546 /* If multiple matches, dst must be a directory or unspecified */
547 if (g.gl_matchc > 1 && dst && !is_dir(dst)) {
548 error("Multiple files match, but \"%s\" is not a directory",
554 for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
555 if (infer_path(g.gl_pathv[i], &tmp)) {
560 if (g.gl_matchc == 1 && dst) {
561 /* If directory specified, append filename */
564 if (infer_path(g.gl_pathv[0], &tmp)) {
568 abs_dst = path_append(dst, tmp);
571 abs_dst = xstrdup(dst);
573 abs_dst = path_append(dst, tmp);
578 printf("Fetching %s to %s\n", g.gl_pathv[i], abs_dst);
579 if (do_download(conn, g.gl_pathv[i], abs_dst, pflag) == -1)
592 process_put(struct sftp_conn *conn, char *src, char *dst, char *pwd, int pflag)
594 char *tmp_dst = NULL;
595 char *abs_dst = NULL;
602 tmp_dst = xstrdup(dst);
603 tmp_dst = make_absolute(tmp_dst, pwd);
606 memset(&g, 0, sizeof(g));
607 debug3("Looking up %s", src);
608 if (glob(src, 0, NULL, &g)) {
609 error("File \"%s\" not found.", src);
614 /* If multiple matches, dst may be directory or unspecified */
615 if (g.gl_matchc > 1 && tmp_dst && !remote_is_dir(conn, tmp_dst)) {
616 error("Multiple files match, but \"%s\" is not a directory",
622 for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
623 if (!is_reg(g.gl_pathv[i])) {
624 error("skipping non-regular file %s",
628 if (infer_path(g.gl_pathv[i], &tmp)) {
633 if (g.gl_matchc == 1 && tmp_dst) {
634 /* If directory specified, append filename */
635 if (remote_is_dir(conn, tmp_dst)) {
636 if (infer_path(g.gl_pathv[0], &tmp)) {
640 abs_dst = path_append(tmp_dst, tmp);
643 abs_dst = xstrdup(tmp_dst);
645 } else if (tmp_dst) {
646 abs_dst = path_append(tmp_dst, tmp);
649 abs_dst = make_absolute(tmp, pwd);
651 printf("Uploading %s to %s\n", g.gl_pathv[i], abs_dst);
652 if (do_upload(conn, g.gl_pathv[i], abs_dst, pflag) == -1)
666 sdirent_comp(const void *aa, const void *bb)
668 SFTP_DIRENT *a = *(SFTP_DIRENT **)aa;
669 SFTP_DIRENT *b = *(SFTP_DIRENT **)bb;
670 int rmul = sort_flag & LS_REVERSE_SORT ? -1 : 1;
672 #define NCMP(a,b) (a == b ? 0 : (a < b ? 1 : -1))
673 if (sort_flag & LS_NAME_SORT)
674 return (rmul * strcmp(a->filename, b->filename));
675 else if (sort_flag & LS_TIME_SORT)
676 return (rmul * NCMP(a->a.mtime, b->a.mtime));
677 else if (sort_flag & LS_SIZE_SORT)
678 return (rmul * NCMP(a->a.size, b->a.size));
680 fatal("Unknown ls sort type");
683 /* sftp ls.1 replacement for directories */
685 do_ls_dir(struct sftp_conn *conn, char *path, char *strip_path, int lflag)
688 u_int c = 1, colspace = 0, columns = 1;
691 if ((n = do_readdir(conn, path, &d)) != 0)
694 if (!(lflag & LS_SHORT_VIEW)) {
695 u_int m = 0, width = 80;
699 /* Count entries for sort and find longest filename */
700 for (n = 0; d[n] != NULL; n++) {
701 if (d[n]->filename[0] != '.' || (lflag & LS_SHOW_ALL))
702 m = MAX(m, strlen(d[n]->filename));
705 /* Add any subpath that also needs to be counted */
706 tmp = path_strip(path, strip_path);
710 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) != -1)
713 columns = width / (m + 2);
714 columns = MAX(columns, 1);
715 colspace = width / columns;
716 colspace = MIN(colspace, width);
719 if (lflag & SORT_FLAGS) {
720 for (n = 0; d[n] != NULL; n++)
721 ; /* count entries */
722 sort_flag = lflag & (SORT_FLAGS|LS_REVERSE_SORT);
723 qsort(d, n, sizeof(*d), sdirent_comp);
726 for (n = 0; d[n] != NULL && !interrupted; n++) {
729 if (d[n]->filename[0] == '.' && !(lflag & LS_SHOW_ALL))
732 tmp = path_append(path, d[n]->filename);
733 fname = path_strip(tmp, strip_path);
736 if (lflag & LS_LONG_VIEW) {
737 if (lflag & LS_NUMERIC_VIEW) {
741 memset(&sb, 0, sizeof(sb));
742 attrib_to_stat(&d[n]->a, &sb);
743 lname = ls_file(fname, &sb, 1);
744 printf("%s\n", lname);
747 printf("%s\n", d[n]->longname);
749 printf("%-*s", colspace, fname);
760 if (!(lflag & LS_LONG_VIEW) && (c != 1))
763 free_sftp_dirents(d);
767 /* sftp ls.1 replacement which handles path globs */
769 do_globbed_ls(struct sftp_conn *conn, char *path, char *strip_path,
773 u_int i, c = 1, colspace = 0, columns = 1;
776 memset(&g, 0, sizeof(g));
778 if (remote_glob(conn, path, GLOB_MARK|GLOB_NOCHECK|GLOB_BRACE,
779 NULL, &g) || (g.gl_pathc && !g.gl_matchc)) {
782 error("Can't ls: \"%s\" not found", path);
790 * If the glob returns a single match and it is a directory,
791 * then just list its contents.
793 if (g.gl_matchc == 1) {
794 if ((a = do_lstat(conn, g.gl_pathv[0], 1)) == NULL) {
798 if ((a->flags & SSH2_FILEXFER_ATTR_PERMISSIONS) &&
802 err = do_ls_dir(conn, g.gl_pathv[0], strip_path, lflag);
808 if (!(lflag & LS_SHORT_VIEW)) {
809 u_int m = 0, width = 80;
812 /* Count entries for sort and find longest filename */
813 for (i = 0; g.gl_pathv[i]; i++)
814 m = MAX(m, strlen(g.gl_pathv[i]));
816 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) != -1)
819 columns = width / (m + 2);
820 columns = MAX(columns, 1);
821 colspace = width / columns;
824 for (i = 0; g.gl_pathv[i] && !interrupted; i++, a = NULL) {
827 fname = path_strip(g.gl_pathv[i], strip_path);
829 if (lflag & LS_LONG_VIEW) {
834 * XXX: this is slow - 1 roundtrip per path
835 * A solution to this is to fork glob() and
836 * build a sftp specific version which keeps the
837 * attribs (which currently get thrown away)
838 * that the server returns as well as the filenames.
840 memset(&sb, 0, sizeof(sb));
842 a = do_lstat(conn, g.gl_pathv[i], 1);
844 attrib_to_stat(a, &sb);
845 lname = ls_file(fname, &sb, 1);
846 printf("%s\n", lname);
849 printf("%-*s", colspace, fname);
859 if (!(lflag & LS_LONG_VIEW) && (c != 1))
870 parse_args(const char **cpp, int *pflag, int *lflag, int *iflag,
871 unsigned long *n_arg, char **path1, char **path2)
873 const char *cmd, *cp = *cpp;
879 /* Skip leading whitespace */
880 cp = cp + strspn(cp, WHITESPACE);
882 /* Ignore blank lines and lines which begin with comment '#' char */
883 if (*cp == '\0' || *cp == '#')
886 /* Check for leading '-' (disable error processing) */
893 /* Figure out which command we have */
894 for (i = 0; cmds[i].c; i++) {
895 int cmdlen = strlen(cmds[i].c);
897 /* Check for command followed by whitespace */
898 if (!strncasecmp(cp, cmds[i].c, cmdlen) &&
899 strchr(WHITESPACE, cp[cmdlen])) {
901 cp = cp + strspn(cp, WHITESPACE);
912 } else if (cmdnum == -1) {
913 error("Invalid command.");
917 /* Get arguments and parse flags */
918 *lflag = *pflag = *n_arg = 0;
919 *path1 = *path2 = NULL;
923 if (parse_getput_flags(&cp, pflag))
925 /* Get first pathname (mandatory) */
926 if (get_pathname(&cp, path1))
928 if (*path1 == NULL) {
929 error("You must specify at least one path after a "
933 /* Try to get second pathname (optional) */
934 if (get_pathname(&cp, path2))
939 if (get_pathname(&cp, path1))
941 if (get_pathname(&cp, path2))
943 if (!*path1 || !*path2) {
944 error("You must specify two paths after a %s "
955 /* Get pathname (mandatory) */
956 if (get_pathname(&cp, path1))
958 if (*path1 == NULL) {
959 error("You must specify a path after a %s command.",
965 if (parse_ls_flags(&cp, lflag))
967 /* Path is optional */
968 if (get_pathname(&cp, path1))
973 /* Uses the rest of the line */
981 /* Get numeric arg (mandatory) */
983 l = strtol(cp, &cp2, base);
984 if (cp2 == cp || ((l == LONG_MIN || l == LONG_MAX) &&
985 errno == ERANGE) || l < 0) {
986 error("You must supply a numeric argument "
987 "to the %s command.", cmd);
992 if (cmdnum == I_LUMASK && strchr(WHITESPACE, *cp))
994 if (cmdnum == I_LUMASK || !strchr(WHITESPACE, *cp)) {
995 error("You must supply a numeric argument "
996 "to the %s command.", cmd);
999 cp += strspn(cp, WHITESPACE);
1001 /* Get pathname (mandatory) */
1002 if (get_pathname(&cp, path1))
1004 if (*path1 == NULL) {
1005 error("You must specify a path after a %s command.",
1018 fatal("Command not implemented");
1026 parse_dispatch_command(struct sftp_conn *conn, const char *cmd, char **pwd,
1029 char *path1, *path2, *tmp;
1030 int pflag, lflag, iflag, cmdnum, i;
1031 unsigned long n_arg;
1033 char path_buf[MAXPATHLEN];
1037 path1 = path2 = NULL;
1038 cmdnum = parse_args(&cmd, &pflag, &lflag, &iflag, &n_arg,
1044 memset(&g, 0, sizeof(g));
1046 /* Perform command */
1052 /* Unrecognized command */
1056 err = process_get(conn, path1, path2, *pwd, pflag);
1059 err = process_put(conn, path1, path2, *pwd, pflag);
1062 path1 = make_absolute(path1, *pwd);
1063 path2 = make_absolute(path2, *pwd);
1064 err = do_rename(conn, path1, path2);
1067 path2 = make_absolute(path2, *pwd);
1068 err = do_symlink(conn, path1, path2);
1071 path1 = make_absolute(path1, *pwd);
1072 remote_glob(conn, path1, GLOB_NOCHECK, NULL, &g);
1073 for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
1074 printf("Removing %s\n", g.gl_pathv[i]);
1075 err = do_rm(conn, g.gl_pathv[i]);
1076 if (err != 0 && err_abort)
1081 path1 = make_absolute(path1, *pwd);
1083 a.flags |= SSH2_FILEXFER_ATTR_PERMISSIONS;
1085 err = do_mkdir(conn, path1, &a);
1088 path1 = make_absolute(path1, *pwd);
1089 err = do_rmdir(conn, path1);
1092 path1 = make_absolute(path1, *pwd);
1093 if ((tmp = do_realpath(conn, path1)) == NULL) {
1097 if ((aa = do_stat(conn, tmp, 0)) == NULL) {
1102 if (!(aa->flags & SSH2_FILEXFER_ATTR_PERMISSIONS)) {
1103 error("Can't change directory: Can't check target");
1108 if (!S_ISDIR(aa->perm)) {
1109 error("Can't change directory: \"%s\" is not "
1110 "a directory", tmp);
1120 do_globbed_ls(conn, *pwd, *pwd, lflag);
1124 /* Strip pwd off beginning of non-absolute paths */
1129 path1 = make_absolute(path1, *pwd);
1130 err = do_globbed_ls(conn, path1, tmp, lflag);
1133 if (chdir(path1) == -1) {
1134 error("Couldn't change local directory to "
1135 "\"%s\": %s", path1, strerror(errno));
1140 if (mkdir(path1, 0777) == -1) {
1141 error("Couldn't create local directory "
1142 "\"%s\": %s", path1, strerror(errno));
1150 local_do_shell(cmd);
1154 printf("Local umask: %03lo\n", n_arg);
1157 path1 = make_absolute(path1, *pwd);
1159 a.flags |= SSH2_FILEXFER_ATTR_PERMISSIONS;
1161 remote_glob(conn, path1, GLOB_NOCHECK, NULL, &g);
1162 for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
1163 printf("Changing mode on %s\n", g.gl_pathv[i]);
1164 err = do_setstat(conn, g.gl_pathv[i], &a);
1165 if (err != 0 && err_abort)
1171 path1 = make_absolute(path1, *pwd);
1172 remote_glob(conn, path1, GLOB_NOCHECK, NULL, &g);
1173 for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
1174 if (!(aa = do_stat(conn, g.gl_pathv[i], 0))) {
1175 if (err != 0 && err_abort)
1180 if (!(aa->flags & SSH2_FILEXFER_ATTR_UIDGID)) {
1181 error("Can't get current ownership of "
1182 "remote file \"%s\"", g.gl_pathv[i]);
1183 if (err != 0 && err_abort)
1188 aa->flags &= SSH2_FILEXFER_ATTR_UIDGID;
1189 if (cmdnum == I_CHOWN) {
1190 printf("Changing owner on %s\n", g.gl_pathv[i]);
1193 printf("Changing group on %s\n", g.gl_pathv[i]);
1196 err = do_setstat(conn, g.gl_pathv[i], aa);
1197 if (err != 0 && err_abort)
1202 printf("Remote working directory: %s\n", *pwd);
1205 if (!getcwd(path_buf, sizeof(path_buf))) {
1206 error("Couldn't get local cwd: %s", strerror(errno));
1210 printf("Local working directory: %s\n", path_buf);
1213 /* Processed below */
1219 printf("SFTP protocol version %u\n", sftp_proto_version(conn));
1222 showprogress = !showprogress;
1224 printf("Progress meter enabled\n");
1226 printf("Progress meter disabled\n");
1229 fatal("%d is not implemented", cmdnum);
1239 /* If an unignored error occurs in batch mode we should abort. */
1240 if (err_abort && err != 0)
1242 else if (cmdnum == I_QUIT)
1250 prompt(EditLine *el)
1257 interactive_loop(int fd_in, int fd_out, char *file1, char *file2)
1262 struct sftp_conn *conn;
1263 int err, interactive;
1264 EditLine *el = NULL;
1268 extern char *__progname;
1270 if (!batchmode && isatty(STDIN_FILENO)) {
1271 if ((el = el_init(__progname, stdin, stdout, stderr)) == NULL)
1272 fatal("Couldn't initialise editline");
1273 if ((hl = history_init()) == NULL)
1274 fatal("Couldn't initialise editline history");
1275 history(hl, &hev, H_SETSIZE, 100);
1276 el_set(el, EL_HIST, history, hl);
1278 el_set(el, EL_PROMPT, prompt);
1279 el_set(el, EL_EDITOR, "emacs");
1280 el_set(el, EL_TERMINAL, NULL);
1281 el_set(el, EL_SIGNAL, 1);
1282 el_source(el, NULL);
1284 #endif /* USE_LIBEDIT */
1286 conn = do_init(fd_in, fd_out, copy_buffer_len, num_requests);
1288 fatal("Couldn't initialise connection to server");
1290 pwd = do_realpath(conn, ".");
1294 if (file1 != NULL) {
1295 dir = xstrdup(file1);
1296 dir = make_absolute(dir, pwd);
1298 if (remote_is_dir(conn, dir) && file2 == NULL) {
1299 printf("Changing to: %s\n", dir);
1300 snprintf(cmd, sizeof cmd, "cd \"%s\"", dir);
1301 if (parse_dispatch_command(conn, cmd, &pwd, 1) != 0) {
1309 snprintf(cmd, sizeof cmd, "get %s", dir);
1311 snprintf(cmd, sizeof cmd, "get %s %s", dir,
1314 err = parse_dispatch_command(conn, cmd, &pwd, 1);
1323 #if defined(HAVE_SETVBUF) && !defined(BROKEN_SETVBUF)
1324 setvbuf(stdout, NULL, _IOLBF, 0);
1325 setvbuf(infile, NULL, _IOLBF, 0);
1331 interactive = !batchmode && isatty(STDIN_FILENO);
1336 signal(SIGINT, SIG_IGN);
1341 if (fgets(cmd, sizeof(cmd), infile) == NULL) {
1346 if (!interactive) { /* Echo command */
1347 printf("sftp> %s", cmd);
1348 if (strlen(cmd) > 0 &&
1349 cmd[strlen(cmd) - 1] != '\n')
1357 if ((line = el_gets(el, &count)) == NULL || count <= 0) {
1361 history(hl, &hev, H_ENTER, line);
1362 if (strlcpy(cmd, line, sizeof(cmd)) >= sizeof(cmd)) {
1363 fprintf(stderr, "Error: input line too long\n");
1366 #endif /* USE_LIBEDIT */
1369 cp = strrchr(cmd, '\n');
1373 /* Handle user interrupts gracefully during commands */
1375 signal(SIGINT, cmd_interrupt);
1377 err = parse_dispatch_command(conn, cmd, &pwd, batchmode);
1387 #endif /* USE_LIBEDIT */
1389 /* err == 1 signifies normal "quit" exit */
1390 return (err >= 0 ? 0 : -1);
1394 connect_to_server(char *path, char **args, int *in, int *out)
1399 int pin[2], pout[2];
1401 if ((pipe(pin) == -1) || (pipe(pout) == -1))
1402 fatal("pipe: %s", strerror(errno));
1407 #else /* USE_PIPES */
1410 if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) == -1)
1411 fatal("socketpair: %s", strerror(errno));
1412 *in = *out = inout[0];
1413 c_in = c_out = inout[1];
1414 #endif /* USE_PIPES */
1416 if ((sshpid = fork()) == -1)
1417 fatal("fork: %s", strerror(errno));
1418 else if (sshpid == 0) {
1419 if ((dup2(c_in, STDIN_FILENO) == -1) ||
1420 (dup2(c_out, STDOUT_FILENO) == -1)) {
1421 fprintf(stderr, "dup2: %s\n", strerror(errno));
1430 * The underlying ssh is in the same process group, so we must
1431 * ignore SIGINT if we want to gracefully abort commands,
1432 * otherwise the signal will make it to the ssh process and
1435 signal(SIGINT, SIG_IGN);
1437 fprintf(stderr, "exec: %s: %s\n", path, strerror(errno));
1441 signal(SIGTERM, killchild);
1442 signal(SIGINT, killchild);
1443 signal(SIGHUP, killchild);
1451 extern char *__progname;
1454 "usage: %s [-1Cv] [-B buffer_size] [-b batchfile] [-F ssh_config]\n"
1455 " [-o ssh_option] [-P sftp_server_path] [-R num_requests]\n"
1456 " [-S program] [-s subsystem | sftp_server] host\n"
1457 " %s [[user@]host[:file [file]]]\n"
1458 " %s [[user@]host[:dir[/]]]\n"
1459 " %s -b batchfile [user@]host\n", __progname, __progname, __progname, __progname);
1464 main(int argc, char **argv)
1466 int in, out, ch, err;
1467 char *host, *userhost, *cp, *file2 = NULL;
1468 int debug_level = 0, sshver = 2;
1469 char *file1 = NULL, *sftp_server = NULL;
1470 char *ssh_program = _PATH_SSH_PROGRAM, *sftp_direct = NULL;
1471 LogLevel ll = SYSLOG_LEVEL_INFO;
1474 extern char *optarg;
1476 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
1479 __progname = ssh_get_progname(argv[0]);
1480 memset(&args, '\0', sizeof(args));
1482 addargs(&args, "%s", ssh_program);
1483 addargs(&args, "-oForwardX11 no");
1484 addargs(&args, "-oForwardAgent no");
1485 addargs(&args, "-oPermitLocalCommand no");
1486 addargs(&args, "-oClearAllForwardings yes");
1488 ll = SYSLOG_LEVEL_INFO;
1491 while ((ch = getopt(argc, argv, "1hvCo:s:S:b:B:F:P:R:")) != -1) {
1494 addargs(&args, "-C");
1497 if (debug_level < 3) {
1498 addargs(&args, "-v");
1499 ll = SYSLOG_LEVEL_DEBUG1 + debug_level;
1505 addargs(&args, "-%c%s", ch, optarg);
1509 if (sftp_server == NULL)
1510 sftp_server = _PATH_SFTP_SERVER;
1513 sftp_server = optarg;
1516 ssh_program = optarg;
1517 replacearg(&args, 0, "%s", ssh_program);
1521 fatal("Batch file already specified.");
1523 /* Allow "-" as stdin */
1524 if (strcmp(optarg, "-") != 0 &&
1525 (infile = fopen(optarg, "r")) == NULL)
1526 fatal("%s (%s).", strerror(errno), optarg);
1529 addargs(&args, "-obatchmode yes");
1532 sftp_direct = optarg;
1535 copy_buffer_len = strtol(optarg, &cp, 10);
1536 if (copy_buffer_len == 0 || *cp != '\0')
1537 fatal("Invalid buffer size \"%s\"", optarg);
1540 num_requests = strtol(optarg, &cp, 10);
1541 if (num_requests == 0 || *cp != '\0')
1542 fatal("Invalid number of requests \"%s\"",
1551 if (!isatty(STDERR_FILENO))
1554 log_init(argv[0], ll, SYSLOG_FACILITY_USER, 1);
1556 if (sftp_direct == NULL) {
1557 if (optind == argc || argc > (optind + 2))
1560 userhost = xstrdup(argv[optind]);
1561 file2 = argv[optind+1];
1563 if ((host = strrchr(userhost, '@')) == NULL)
1568 fprintf(stderr, "Missing username\n");
1571 addargs(&args, "-l%s", userhost);
1574 if ((cp = colon(host)) != NULL) {
1579 host = cleanhostname(host);
1581 fprintf(stderr, "Missing hostname\n");
1585 addargs(&args, "-oProtocol %d", sshver);
1587 /* no subsystem if the server-spec contains a '/' */
1588 if (sftp_server == NULL || strchr(sftp_server, '/') == NULL)
1589 addargs(&args, "-s");
1591 addargs(&args, "%s", host);
1592 addargs(&args, "%s", (sftp_server != NULL ?
1593 sftp_server : "sftp"));
1596 fprintf(stderr, "Connecting to %s...\n", host);
1597 connect_to_server(ssh_program, args.list, &in, &out);
1600 addargs(&args, "sftp-server");
1603 fprintf(stderr, "Attaching to %s...\n", sftp_direct);
1604 connect_to_server(sftp_direct, args.list, &in, &out);
1608 err = interactive_loop(in, out, file1, file2);
1610 #if !defined(USE_PIPES)
1611 shutdown(in, SHUT_RDWR);
1612 shutdown(out, SHUT_RDWR);
1620 while (waitpid(sshpid, NULL, 0) == -1)
1622 fatal("Couldn't wait for ssh process: %s",
1625 exit(err == 0 ? 0 : 1);