1 /* $OpenBSD: sftp.c,v 1.86 2006/07/17 01:31:09 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;
43 #include "pathnames.h"
47 #include "sftp-common.h"
48 #include "sftp-client.h"
50 /* File to read commands from */
53 /* Are we in batchfile mode? */
56 /* Size of buffer used when copying files */
57 size_t copy_buffer_len = 32768;
59 /* Number of concurrent outstanding requests */
60 size_t num_requests = 16;
62 /* PID of ssh transport process */
63 static pid_t sshpid = -1;
65 /* This is set to 0 if the progressmeter is not desired. */
68 /* SIGINT received during command processing */
69 volatile sig_atomic_t interrupted = 0;
71 /* I wish qsort() took a separate ctx for the comparison function...*/
74 int remote_glob(struct sftp_conn *, const char *, int,
75 int (*)(const char *, int), glob_t *); /* proto for sftp-glob.c */
77 extern char *__progname;
79 /* Separators for interactive commands */
80 #define WHITESPACE " \t\r\n"
83 #define LS_LONG_VIEW 0x01 /* Full view ala ls -l */
84 #define LS_SHORT_VIEW 0x02 /* Single row view ala ls -1 */
85 #define LS_NUMERIC_VIEW 0x04 /* Long view with numeric uid/gid */
86 #define LS_NAME_SORT 0x08 /* Sort by name (default) */
87 #define LS_TIME_SORT 0x10 /* Sort by mtime */
88 #define LS_SIZE_SORT 0x20 /* Sort by file size */
89 #define LS_REVERSE_SORT 0x40 /* Reverse sort order */
90 #define LS_SHOW_ALL 0x80 /* Don't skip filenames starting with '.' */
92 #define VIEW_FLAGS (LS_LONG_VIEW|LS_SHORT_VIEW|LS_NUMERIC_VIEW)
93 #define SORT_FLAGS (LS_NAME_SORT|LS_TIME_SORT|LS_SIZE_SORT)
95 /* Commands for interactive mode */
118 #define I_PROGRESS 23
125 static const struct CMD cmds[] = {
128 { "chdir", I_CHDIR },
129 { "chgrp", I_CHGRP },
130 { "chmod", I_CHMOD },
131 { "chown", I_CHOWN },
138 { "lchdir", I_LCHDIR },
140 { "lmkdir", I_LMKDIR },
144 { "lumask", I_LUMASK },
145 { "mkdir", I_MKDIR },
146 { "progress", I_PROGRESS },
151 { "rename", I_RENAME },
153 { "rmdir", I_RMDIR },
154 { "symlink", I_SYMLINK },
155 { "version", I_VERSION },
161 int interactive_loop(int fd_in, int fd_out, char *file1, char *file2);
167 kill(sshpid, SIGTERM);
168 waitpid(sshpid, NULL, 0);
175 cmd_interrupt(int signo)
177 const char msg[] = "\rInterrupt \n";
178 int olderrno = errno;
180 write(STDERR_FILENO, msg, sizeof(msg) - 1);
188 printf("Available commands:\n");
189 printf("cd path Change remote directory to 'path'\n");
190 printf("lcd path Change local directory to 'path'\n");
191 printf("chgrp grp path Change group of file 'path' to 'grp'\n");
192 printf("chmod mode path Change permissions of file 'path' to 'mode'\n");
193 printf("chown own path Change owner of file 'path' to 'own'\n");
194 printf("help Display this help text\n");
195 printf("get remote-path [local-path] Download file\n");
196 printf("lls [ls-options [path]] Display local directory listing\n");
197 printf("ln oldpath newpath Symlink remote file\n");
198 printf("lmkdir path Create local directory\n");
199 printf("lpwd Print local working directory\n");
200 printf("ls [path] Display remote directory listing\n");
201 printf("lumask umask Set local umask to 'umask'\n");
202 printf("mkdir path Create remote directory\n");
203 printf("progress Toggle display of progress meter\n");
204 printf("put local-path [remote-path] Upload file\n");
205 printf("pwd Display remote working directory\n");
206 printf("exit Quit sftp\n");
207 printf("quit Quit sftp\n");
208 printf("rename oldpath newpath Rename remote file\n");
209 printf("rmdir path Remove remote directory\n");
210 printf("rm path Delete remote file\n");
211 printf("symlink oldpath newpath Symlink remote file\n");
212 printf("version Show SFTP version\n");
213 printf("!command Execute 'command' in local shell\n");
214 printf("! Escape to local shell\n");
215 printf("? Synonym for help\n");
219 local_do_shell(const char *args)
228 if ((shell = getenv("SHELL")) == NULL)
229 shell = _PATH_BSHELL;
231 if ((pid = fork()) == -1)
232 fatal("Couldn't fork: %s", strerror(errno));
235 /* XXX: child has pipe fds to ssh subproc open - issue? */
237 debug3("Executing %s -c \"%s\"", shell, args);
238 execl(shell, shell, "-c", args, (char *)NULL);
240 debug3("Executing %s", shell);
241 execl(shell, shell, (char *)NULL);
243 fprintf(stderr, "Couldn't execute \"%s\": %s\n", shell,
247 while (waitpid(pid, &status, 0) == -1)
249 fatal("Couldn't wait for child: %s", strerror(errno));
250 if (!WIFEXITED(status))
251 error("Shell exited abnormally");
252 else if (WEXITSTATUS(status))
253 error("Shell exited with status %d", WEXITSTATUS(status));
257 local_do_ls(const char *args)
260 local_do_shell(_PATH_LS);
262 int len = strlen(_PATH_LS " ") + strlen(args) + 1;
263 char *buf = xmalloc(len);
265 /* XXX: quoting - rip quoting code from ftp? */
266 snprintf(buf, len, _PATH_LS " %s", args);
272 /* Strip one path (usually the pwd) from the start of another */
274 path_strip(char *path, char *strip)
279 return (xstrdup(path));
282 if (strncmp(path, strip, len) == 0) {
283 if (strip[len - 1] != '/' && path[len] == '/')
285 return (xstrdup(path + len));
288 return (xstrdup(path));
292 path_append(char *p1, char *p2)
295 int len = strlen(p1) + strlen(p2) + 2;
298 strlcpy(ret, p1, len);
299 if (p1[strlen(p1) - 1] != '/')
300 strlcat(ret, "/", len);
301 strlcat(ret, p2, len);
307 make_absolute(char *p, char *pwd)
312 if (p && p[0] != '/') {
313 abs_str = path_append(pwd, p);
321 infer_path(const char *p, char **ifp)
325 cp = strrchr(p, '/');
332 error("Invalid path");
336 *ifp = xstrdup(cp + 1);
341 parse_getput_flags(const char **cpp, int *pflag)
343 const char *cp = *cpp;
345 /* Check for flags */
346 if (cp[0] == '-' && cp[1] && strchr(WHITESPACE, cp[2])) {
353 error("Invalid flag -%c", cp[1]);
357 *cpp = cp + strspn(cp, WHITESPACE);
364 parse_ls_flags(const char **cpp, int *lflag)
366 const char *cp = *cpp;
369 *lflag = LS_NAME_SORT;
371 /* Check for flags */
372 if (cp++[0] == '-') {
373 for (; strchr(WHITESPACE, *cp) == NULL; cp++) {
376 *lflag &= ~VIEW_FLAGS;
377 *lflag |= LS_LONG_VIEW;
380 *lflag &= ~VIEW_FLAGS;
381 *lflag |= LS_SHORT_VIEW;
384 *lflag &= ~VIEW_FLAGS;
385 *lflag |= LS_NUMERIC_VIEW|LS_LONG_VIEW;
388 *lflag &= ~SORT_FLAGS;
389 *lflag |= LS_SIZE_SORT;
392 *lflag &= ~SORT_FLAGS;
393 *lflag |= LS_TIME_SORT;
396 *lflag |= LS_REVERSE_SORT;
399 *lflag &= ~SORT_FLAGS;
402 *lflag |= LS_SHOW_ALL;
405 error("Invalid flag -%c", *cp);
409 *cpp = cp + strspn(cp, WHITESPACE);
416 get_pathname(const char **cpp, char **path)
418 const char *cp = *cpp, *end;
422 cp += strspn(cp, WHITESPACE);
429 *path = xmalloc(strlen(cp) + 1);
431 /* Check for quoted filenames */
432 if (*cp == '\"' || *cp == '\'') {
435 /* Search for terminating quote, unescape some chars */
436 for (i = j = 0; i <= strlen(cp); i++) {
437 if (cp[i] == quot) { /* Found quote */
442 if (cp[i] == '\0') { /* End of string */
443 error("Unterminated quote");
446 if (cp[i] == '\\') { /* Escaped characters */
448 if (cp[i] != '\'' && cp[i] != '\"' &&
450 error("Bad escaped character '\\%c'",
455 (*path)[j++] = cp[i];
459 error("Empty quotes");
462 *cpp = cp + i + strspn(cp + i, WHITESPACE);
464 /* Read to end of filename */
465 end = strpbrk(cp, WHITESPACE);
467 end = strchr(cp, '\0');
468 *cpp = end + strspn(end, WHITESPACE);
470 memcpy(*path, cp, end - cp);
471 (*path)[end - cp] = '\0';
486 /* XXX: report errors? */
487 if (stat(path, &sb) == -1)
490 return(sb.st_mode & S_IFDIR);
498 if (stat(path, &sb) == -1)
499 fatal("stat %s: %s", path, strerror(errno));
501 return(S_ISREG(sb.st_mode));
505 remote_is_dir(struct sftp_conn *conn, char *path)
509 /* XXX: report errors? */
510 if ((a = do_stat(conn, path, 1)) == NULL)
512 if (!(a->flags & SSH2_FILEXFER_ATTR_PERMISSIONS))
514 return(a->perm & S_IFDIR);
518 process_get(struct sftp_conn *conn, char *src, char *dst, char *pwd, int pflag)
520 char *abs_src = NULL;
521 char *abs_dst = NULL;
527 abs_src = xstrdup(src);
528 abs_src = make_absolute(abs_src, pwd);
530 memset(&g, 0, sizeof(g));
531 debug3("Looking up %s", abs_src);
532 if (remote_glob(conn, abs_src, 0, NULL, &g)) {
533 error("File \"%s\" not found.", abs_src);
538 /* If multiple matches, dst must be a directory or unspecified */
539 if (g.gl_matchc > 1 && dst && !is_dir(dst)) {
540 error("Multiple files match, but \"%s\" is not a directory",
546 for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
547 if (infer_path(g.gl_pathv[i], &tmp)) {
552 if (g.gl_matchc == 1 && dst) {
553 /* If directory specified, append filename */
556 if (infer_path(g.gl_pathv[0], &tmp)) {
560 abs_dst = path_append(dst, tmp);
563 abs_dst = xstrdup(dst);
565 abs_dst = path_append(dst, tmp);
570 printf("Fetching %s to %s\n", g.gl_pathv[i], abs_dst);
571 if (do_download(conn, g.gl_pathv[i], abs_dst, pflag) == -1)
584 process_put(struct sftp_conn *conn, char *src, char *dst, char *pwd, int pflag)
586 char *tmp_dst = NULL;
587 char *abs_dst = NULL;
594 tmp_dst = xstrdup(dst);
595 tmp_dst = make_absolute(tmp_dst, pwd);
598 memset(&g, 0, sizeof(g));
599 debug3("Looking up %s", src);
600 if (glob(src, 0, NULL, &g)) {
601 error("File \"%s\" not found.", src);
606 /* If multiple matches, dst may be directory or unspecified */
607 if (g.gl_matchc > 1 && tmp_dst && !remote_is_dir(conn, tmp_dst)) {
608 error("Multiple files match, but \"%s\" is not a directory",
614 for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
615 if (!is_reg(g.gl_pathv[i])) {
616 error("skipping non-regular file %s",
620 if (infer_path(g.gl_pathv[i], &tmp)) {
625 if (g.gl_matchc == 1 && tmp_dst) {
626 /* If directory specified, append filename */
627 if (remote_is_dir(conn, tmp_dst)) {
628 if (infer_path(g.gl_pathv[0], &tmp)) {
632 abs_dst = path_append(tmp_dst, tmp);
635 abs_dst = xstrdup(tmp_dst);
637 } else if (tmp_dst) {
638 abs_dst = path_append(tmp_dst, tmp);
641 abs_dst = make_absolute(tmp, pwd);
643 printf("Uploading %s to %s\n", g.gl_pathv[i], abs_dst);
644 if (do_upload(conn, g.gl_pathv[i], abs_dst, pflag) == -1)
658 sdirent_comp(const void *aa, const void *bb)
660 SFTP_DIRENT *a = *(SFTP_DIRENT **)aa;
661 SFTP_DIRENT *b = *(SFTP_DIRENT **)bb;
662 int rmul = sort_flag & LS_REVERSE_SORT ? -1 : 1;
664 #define NCMP(a,b) (a == b ? 0 : (a < b ? 1 : -1))
665 if (sort_flag & LS_NAME_SORT)
666 return (rmul * strcmp(a->filename, b->filename));
667 else if (sort_flag & LS_TIME_SORT)
668 return (rmul * NCMP(a->a.mtime, b->a.mtime));
669 else if (sort_flag & LS_SIZE_SORT)
670 return (rmul * NCMP(a->a.size, b->a.size));
672 fatal("Unknown ls sort type");
675 /* sftp ls.1 replacement for directories */
677 do_ls_dir(struct sftp_conn *conn, char *path, char *strip_path, int lflag)
680 u_int c = 1, colspace = 0, columns = 1;
683 if ((n = do_readdir(conn, path, &d)) != 0)
686 if (!(lflag & LS_SHORT_VIEW)) {
687 u_int m = 0, width = 80;
691 /* Count entries for sort and find longest filename */
692 for (n = 0; d[n] != NULL; n++) {
693 if (d[n]->filename[0] != '.' || (lflag & LS_SHOW_ALL))
694 m = MAX(m, strlen(d[n]->filename));
697 /* Add any subpath that also needs to be counted */
698 tmp = path_strip(path, strip_path);
702 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) != -1)
705 columns = width / (m + 2);
706 columns = MAX(columns, 1);
707 colspace = width / columns;
708 colspace = MIN(colspace, width);
711 if (lflag & SORT_FLAGS) {
712 for (n = 0; d[n] != NULL; n++)
713 ; /* count entries */
714 sort_flag = lflag & (SORT_FLAGS|LS_REVERSE_SORT);
715 qsort(d, n, sizeof(*d), sdirent_comp);
718 for (n = 0; d[n] != NULL && !interrupted; n++) {
721 if (d[n]->filename[0] == '.' && !(lflag & LS_SHOW_ALL))
724 tmp = path_append(path, d[n]->filename);
725 fname = path_strip(tmp, strip_path);
728 if (lflag & LS_LONG_VIEW) {
729 if (lflag & LS_NUMERIC_VIEW) {
733 memset(&sb, 0, sizeof(sb));
734 attrib_to_stat(&d[n]->a, &sb);
735 lname = ls_file(fname, &sb, 1);
736 printf("%s\n", lname);
739 printf("%s\n", d[n]->longname);
741 printf("%-*s", colspace, fname);
752 if (!(lflag & LS_LONG_VIEW) && (c != 1))
755 free_sftp_dirents(d);
759 /* sftp ls.1 replacement which handles path globs */
761 do_globbed_ls(struct sftp_conn *conn, char *path, char *strip_path,
765 u_int i, c = 1, colspace = 0, columns = 1;
768 memset(&g, 0, sizeof(g));
770 if (remote_glob(conn, path, GLOB_MARK|GLOB_NOCHECK|GLOB_BRACE,
771 NULL, &g) || (g.gl_pathc && !g.gl_matchc)) {
774 error("Can't ls: \"%s\" not found", path);
782 * If the glob returns a single match and it is a directory,
783 * then just list its contents.
785 if (g.gl_matchc == 1) {
786 if ((a = do_lstat(conn, g.gl_pathv[0], 1)) == NULL) {
790 if ((a->flags & SSH2_FILEXFER_ATTR_PERMISSIONS) &&
794 err = do_ls_dir(conn, g.gl_pathv[0], strip_path, lflag);
800 if (!(lflag & LS_SHORT_VIEW)) {
801 u_int m = 0, width = 80;
804 /* Count entries for sort and find longest filename */
805 for (i = 0; g.gl_pathv[i]; i++)
806 m = MAX(m, strlen(g.gl_pathv[i]));
808 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) != -1)
811 columns = width / (m + 2);
812 columns = MAX(columns, 1);
813 colspace = width / columns;
816 for (i = 0; g.gl_pathv[i] && !interrupted; i++, a = NULL) {
819 fname = path_strip(g.gl_pathv[i], strip_path);
821 if (lflag & LS_LONG_VIEW) {
826 * XXX: this is slow - 1 roundtrip per path
827 * A solution to this is to fork glob() and
828 * build a sftp specific version which keeps the
829 * attribs (which currently get thrown away)
830 * that the server returns as well as the filenames.
832 memset(&sb, 0, sizeof(sb));
834 a = do_lstat(conn, g.gl_pathv[i], 1);
836 attrib_to_stat(a, &sb);
837 lname = ls_file(fname, &sb, 1);
838 printf("%s\n", lname);
841 printf("%-*s", colspace, fname);
851 if (!(lflag & LS_LONG_VIEW) && (c != 1))
862 parse_args(const char **cpp, int *pflag, int *lflag, int *iflag,
863 unsigned long *n_arg, char **path1, char **path2)
865 const char *cmd, *cp = *cpp;
871 /* Skip leading whitespace */
872 cp = cp + strspn(cp, WHITESPACE);
874 /* Ignore blank lines and lines which begin with comment '#' char */
875 if (*cp == '\0' || *cp == '#')
878 /* Check for leading '-' (disable error processing) */
885 /* Figure out which command we have */
886 for (i = 0; cmds[i].c; i++) {
887 int cmdlen = strlen(cmds[i].c);
889 /* Check for command followed by whitespace */
890 if (!strncasecmp(cp, cmds[i].c, cmdlen) &&
891 strchr(WHITESPACE, cp[cmdlen])) {
893 cp = cp + strspn(cp, WHITESPACE);
904 } else if (cmdnum == -1) {
905 error("Invalid command.");
909 /* Get arguments and parse flags */
910 *lflag = *pflag = *n_arg = 0;
911 *path1 = *path2 = NULL;
915 if (parse_getput_flags(&cp, pflag))
917 /* Get first pathname (mandatory) */
918 if (get_pathname(&cp, path1))
920 if (*path1 == NULL) {
921 error("You must specify at least one path after a "
925 /* Try to get second pathname (optional) */
926 if (get_pathname(&cp, path2))
931 if (get_pathname(&cp, path1))
933 if (get_pathname(&cp, path2))
935 if (!*path1 || !*path2) {
936 error("You must specify two paths after a %s "
947 /* Get pathname (mandatory) */
948 if (get_pathname(&cp, path1))
950 if (*path1 == NULL) {
951 error("You must specify a path after a %s command.",
957 if (parse_ls_flags(&cp, lflag))
959 /* Path is optional */
960 if (get_pathname(&cp, path1))
965 /* Uses the rest of the line */
973 /* Get numeric arg (mandatory) */
974 l = strtol(cp, &cp2, base);
975 if (cp2 == cp || ((l == LONG_MIN || l == LONG_MAX) &&
976 errno == ERANGE) || l < 0) {
977 error("You must supply a numeric argument "
978 "to the %s command.", cmd);
983 if (cmdnum == I_LUMASK && strchr(WHITESPACE, *cp))
985 if (cmdnum == I_LUMASK || !strchr(WHITESPACE, *cp)) {
986 error("You must supply a numeric argument "
987 "to the %s command.", cmd);
990 cp += strspn(cp, WHITESPACE);
992 /* Get pathname (mandatory) */
993 if (get_pathname(&cp, path1))
995 if (*path1 == NULL) {
996 error("You must specify a path after a %s command.",
1009 fatal("Command not implemented");
1017 parse_dispatch_command(struct sftp_conn *conn, const char *cmd, char **pwd,
1020 char *path1, *path2, *tmp;
1021 int pflag, lflag, iflag, cmdnum, i;
1022 unsigned long n_arg;
1024 char path_buf[MAXPATHLEN];
1028 path1 = path2 = NULL;
1029 cmdnum = parse_args(&cmd, &pflag, &lflag, &iflag, &n_arg,
1035 memset(&g, 0, sizeof(g));
1037 /* Perform command */
1043 /* Unrecognized command */
1047 err = process_get(conn, path1, path2, *pwd, pflag);
1050 err = process_put(conn, path1, path2, *pwd, pflag);
1053 path1 = make_absolute(path1, *pwd);
1054 path2 = make_absolute(path2, *pwd);
1055 err = do_rename(conn, path1, path2);
1058 path2 = make_absolute(path2, *pwd);
1059 err = do_symlink(conn, path1, path2);
1062 path1 = make_absolute(path1, *pwd);
1063 remote_glob(conn, path1, GLOB_NOCHECK, NULL, &g);
1064 for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
1065 printf("Removing %s\n", g.gl_pathv[i]);
1066 err = do_rm(conn, g.gl_pathv[i]);
1067 if (err != 0 && err_abort)
1072 path1 = make_absolute(path1, *pwd);
1074 a.flags |= SSH2_FILEXFER_ATTR_PERMISSIONS;
1076 err = do_mkdir(conn, path1, &a);
1079 path1 = make_absolute(path1, *pwd);
1080 err = do_rmdir(conn, path1);
1083 path1 = make_absolute(path1, *pwd);
1084 if ((tmp = do_realpath(conn, path1)) == NULL) {
1088 if ((aa = do_stat(conn, tmp, 0)) == NULL) {
1093 if (!(aa->flags & SSH2_FILEXFER_ATTR_PERMISSIONS)) {
1094 error("Can't change directory: Can't check target");
1099 if (!S_ISDIR(aa->perm)) {
1100 error("Can't change directory: \"%s\" is not "
1101 "a directory", tmp);
1111 do_globbed_ls(conn, *pwd, *pwd, lflag);
1115 /* Strip pwd off beginning of non-absolute paths */
1120 path1 = make_absolute(path1, *pwd);
1121 err = do_globbed_ls(conn, path1, tmp, lflag);
1124 if (chdir(path1) == -1) {
1125 error("Couldn't change local directory to "
1126 "\"%s\": %s", path1, strerror(errno));
1131 if (mkdir(path1, 0777) == -1) {
1132 error("Couldn't create local directory "
1133 "\"%s\": %s", path1, strerror(errno));
1141 local_do_shell(cmd);
1145 printf("Local umask: %03lo\n", n_arg);
1148 path1 = make_absolute(path1, *pwd);
1150 a.flags |= SSH2_FILEXFER_ATTR_PERMISSIONS;
1152 remote_glob(conn, path1, GLOB_NOCHECK, NULL, &g);
1153 for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
1154 printf("Changing mode on %s\n", g.gl_pathv[i]);
1155 err = do_setstat(conn, g.gl_pathv[i], &a);
1156 if (err != 0 && err_abort)
1162 path1 = make_absolute(path1, *pwd);
1163 remote_glob(conn, path1, GLOB_NOCHECK, NULL, &g);
1164 for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
1165 if (!(aa = do_stat(conn, g.gl_pathv[i], 0))) {
1166 if (err != 0 && err_abort)
1171 if (!(aa->flags & SSH2_FILEXFER_ATTR_UIDGID)) {
1172 error("Can't get current ownership of "
1173 "remote file \"%s\"", g.gl_pathv[i]);
1174 if (err != 0 && err_abort)
1179 aa->flags &= SSH2_FILEXFER_ATTR_UIDGID;
1180 if (cmdnum == I_CHOWN) {
1181 printf("Changing owner on %s\n", g.gl_pathv[i]);
1184 printf("Changing group on %s\n", g.gl_pathv[i]);
1187 err = do_setstat(conn, g.gl_pathv[i], aa);
1188 if (err != 0 && err_abort)
1193 printf("Remote working directory: %s\n", *pwd);
1196 if (!getcwd(path_buf, sizeof(path_buf))) {
1197 error("Couldn't get local cwd: %s", strerror(errno));
1201 printf("Local working directory: %s\n", path_buf);
1204 /* Processed below */
1210 printf("SFTP protocol version %u\n", sftp_proto_version(conn));
1213 showprogress = !showprogress;
1215 printf("Progress meter enabled\n");
1217 printf("Progress meter disabled\n");
1220 fatal("%d is not implemented", cmdnum);
1230 /* If an unignored error occurs in batch mode we should abort. */
1231 if (err_abort && err != 0)
1233 else if (cmdnum == I_QUIT)
1241 prompt(EditLine *el)
1248 interactive_loop(int fd_in, int fd_out, char *file1, char *file2)
1253 struct sftp_conn *conn;
1254 int err, interactive;
1255 EditLine *el = NULL;
1259 extern char *__progname;
1261 if (!batchmode && isatty(STDIN_FILENO)) {
1262 if ((el = el_init(__progname, stdin, stdout, stderr)) == NULL)
1263 fatal("Couldn't initialise editline");
1264 if ((hl = history_init()) == NULL)
1265 fatal("Couldn't initialise editline history");
1266 history(hl, &hev, H_SETSIZE, 100);
1267 el_set(el, EL_HIST, history, hl);
1269 el_set(el, EL_PROMPT, prompt);
1270 el_set(el, EL_EDITOR, "emacs");
1271 el_set(el, EL_TERMINAL, NULL);
1272 el_set(el, EL_SIGNAL, 1);
1273 el_source(el, NULL);
1275 #endif /* USE_LIBEDIT */
1277 conn = do_init(fd_in, fd_out, copy_buffer_len, num_requests);
1279 fatal("Couldn't initialise connection to server");
1281 pwd = do_realpath(conn, ".");
1285 if (file1 != NULL) {
1286 dir = xstrdup(file1);
1287 dir = make_absolute(dir, pwd);
1289 if (remote_is_dir(conn, dir) && file2 == NULL) {
1290 printf("Changing to: %s\n", dir);
1291 snprintf(cmd, sizeof cmd, "cd \"%s\"", dir);
1292 if (parse_dispatch_command(conn, cmd, &pwd, 1) != 0) {
1300 snprintf(cmd, sizeof cmd, "get %s", dir);
1302 snprintf(cmd, sizeof cmd, "get %s %s", dir,
1305 err = parse_dispatch_command(conn, cmd, &pwd, 1);
1314 #if defined(HAVE_SETVBUF) && !defined(BROKEN_SETVBUF)
1315 setvbuf(stdout, NULL, _IOLBF, 0);
1316 setvbuf(infile, NULL, _IOLBF, 0);
1322 interactive = !batchmode && isatty(STDIN_FILENO);
1327 signal(SIGINT, SIG_IGN);
1332 if (fgets(cmd, sizeof(cmd), infile) == NULL) {
1337 if (!interactive) { /* Echo command */
1338 printf("sftp> %s", cmd);
1339 if (strlen(cmd) > 0 &&
1340 cmd[strlen(cmd) - 1] != '\n')
1348 if ((line = el_gets(el, &count)) == NULL || count <= 0) {
1352 history(hl, &hev, H_ENTER, line);
1353 if (strlcpy(cmd, line, sizeof(cmd)) >= sizeof(cmd)) {
1354 fprintf(stderr, "Error: input line too long\n");
1357 #endif /* USE_LIBEDIT */
1360 cp = strrchr(cmd, '\n');
1364 /* Handle user interrupts gracefully during commands */
1366 signal(SIGINT, cmd_interrupt);
1368 err = parse_dispatch_command(conn, cmd, &pwd, batchmode);
1378 #endif /* USE_LIBEDIT */
1380 /* err == 1 signifies normal "quit" exit */
1381 return (err >= 0 ? 0 : -1);
1385 connect_to_server(char *path, char **args, int *in, int *out)
1390 int pin[2], pout[2];
1392 if ((pipe(pin) == -1) || (pipe(pout) == -1))
1393 fatal("pipe: %s", strerror(errno));
1398 #else /* USE_PIPES */
1401 if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) == -1)
1402 fatal("socketpair: %s", strerror(errno));
1403 *in = *out = inout[0];
1404 c_in = c_out = inout[1];
1405 #endif /* USE_PIPES */
1407 if ((sshpid = fork()) == -1)
1408 fatal("fork: %s", strerror(errno));
1409 else if (sshpid == 0) {
1410 if ((dup2(c_in, STDIN_FILENO) == -1) ||
1411 (dup2(c_out, STDOUT_FILENO) == -1)) {
1412 fprintf(stderr, "dup2: %s\n", strerror(errno));
1421 * The underlying ssh is in the same process group, so we must
1422 * ignore SIGINT if we want to gracefully abort commands,
1423 * otherwise the signal will make it to the ssh process and
1426 signal(SIGINT, SIG_IGN);
1428 fprintf(stderr, "exec: %s: %s\n", path, strerror(errno));
1432 signal(SIGTERM, killchild);
1433 signal(SIGINT, killchild);
1434 signal(SIGHUP, killchild);
1442 extern char *__progname;
1445 "usage: %s [-1Cv] [-B buffer_size] [-b batchfile] [-F ssh_config]\n"
1446 " [-o ssh_option] [-P sftp_server_path] [-R num_requests]\n"
1447 " [-S program] [-s subsystem | sftp_server] host\n"
1448 " %s [[user@]host[:file [file]]]\n"
1449 " %s [[user@]host[:dir[/]]]\n"
1450 " %s -b batchfile [user@]host\n", __progname, __progname, __progname, __progname);
1455 main(int argc, char **argv)
1457 int in, out, ch, err;
1458 char *host, *userhost, *cp, *file2 = NULL;
1459 int debug_level = 0, sshver = 2;
1460 char *file1 = NULL, *sftp_server = NULL;
1461 char *ssh_program = _PATH_SSH_PROGRAM, *sftp_direct = NULL;
1462 LogLevel ll = SYSLOG_LEVEL_INFO;
1465 extern char *optarg;
1467 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
1470 __progname = ssh_get_progname(argv[0]);
1471 memset(&args, '\0', sizeof(args));
1473 addargs(&args, "%s", ssh_program);
1474 addargs(&args, "-oForwardX11 no");
1475 addargs(&args, "-oForwardAgent no");
1476 addargs(&args, "-oPermitLocalCommand no");
1477 addargs(&args, "-oClearAllForwardings yes");
1479 ll = SYSLOG_LEVEL_INFO;
1482 while ((ch = getopt(argc, argv, "1hvCo:s:S:b:B:F:P:R:")) != -1) {
1485 addargs(&args, "-C");
1488 if (debug_level < 3) {
1489 addargs(&args, "-v");
1490 ll = SYSLOG_LEVEL_DEBUG1 + debug_level;
1496 addargs(&args, "-%c%s", ch, optarg);
1500 if (sftp_server == NULL)
1501 sftp_server = _PATH_SFTP_SERVER;
1504 sftp_server = optarg;
1507 ssh_program = optarg;
1508 replacearg(&args, 0, "%s", ssh_program);
1512 fatal("Batch file already specified.");
1514 /* Allow "-" as stdin */
1515 if (strcmp(optarg, "-") != 0 &&
1516 (infile = fopen(optarg, "r")) == NULL)
1517 fatal("%s (%s).", strerror(errno), optarg);
1520 addargs(&args, "-obatchmode yes");
1523 sftp_direct = optarg;
1526 copy_buffer_len = strtol(optarg, &cp, 10);
1527 if (copy_buffer_len == 0 || *cp != '\0')
1528 fatal("Invalid buffer size \"%s\"", optarg);
1531 num_requests = strtol(optarg, &cp, 10);
1532 if (num_requests == 0 || *cp != '\0')
1533 fatal("Invalid number of requests \"%s\"",
1542 if (!isatty(STDERR_FILENO))
1545 log_init(argv[0], ll, SYSLOG_FACILITY_USER, 1);
1547 if (sftp_direct == NULL) {
1548 if (optind == argc || argc > (optind + 2))
1551 userhost = xstrdup(argv[optind]);
1552 file2 = argv[optind+1];
1554 if ((host = strrchr(userhost, '@')) == NULL)
1559 fprintf(stderr, "Missing username\n");
1562 addargs(&args, "-l%s",userhost);
1565 if ((cp = colon(host)) != NULL) {
1570 host = cleanhostname(host);
1572 fprintf(stderr, "Missing hostname\n");
1576 addargs(&args, "-oProtocol %d", sshver);
1578 /* no subsystem if the server-spec contains a '/' */
1579 if (sftp_server == NULL || strchr(sftp_server, '/') == NULL)
1580 addargs(&args, "-s");
1582 addargs(&args, "%s", host);
1583 addargs(&args, "%s", (sftp_server != NULL ?
1584 sftp_server : "sftp"));
1587 fprintf(stderr, "Connecting to %s...\n", host);
1588 connect_to_server(ssh_program, args.list, &in, &out);
1591 addargs(&args, "sftp-server");
1594 fprintf(stderr, "Attaching to %s...\n", sftp_direct);
1595 connect_to_server(sftp_direct, args.list, &in, &out);
1599 err = interactive_loop(in, out, file1, file2);
1601 #if !defined(USE_PIPES)
1602 shutdown(in, SHUT_RDWR);
1603 shutdown(out, SHUT_RDWR);
1611 while (waitpid(sshpid, NULL, 0) == -1)
1613 fatal("Couldn't wait for ssh process: %s",
1616 exit(err == 0 ? 0 : 1);