1 /* $OpenBSD: sftp.c,v 1.79 2006/03/25 13:17:02 djm 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>
33 typedef void EditLine;
40 #include "pathnames.h"
44 #include "sftp-common.h"
45 #include "sftp-client.h"
47 /* File to read commands from */
50 /* Are we in batchfile mode? */
53 /* Size of buffer used when copying files */
54 size_t copy_buffer_len = 32768;
56 /* Number of concurrent outstanding requests */
57 size_t num_requests = 16;
59 /* PID of ssh transport process */
60 static pid_t sshpid = -1;
62 /* This is set to 0 if the progressmeter is not desired. */
65 /* SIGINT received during command processing */
66 volatile sig_atomic_t interrupted = 0;
68 /* I wish qsort() took a separate ctx for the comparison function...*/
71 int remote_glob(struct sftp_conn *, const char *, int,
72 int (*)(const char *, int), glob_t *); /* proto for sftp-glob.c */
74 extern char *__progname;
76 /* Separators for interactive commands */
77 #define WHITESPACE " \t\r\n"
80 #define LS_LONG_VIEW 0x01 /* Full view ala ls -l */
81 #define LS_SHORT_VIEW 0x02 /* Single row view ala ls -1 */
82 #define LS_NUMERIC_VIEW 0x04 /* Long view with numeric uid/gid */
83 #define LS_NAME_SORT 0x08 /* Sort by name (default) */
84 #define LS_TIME_SORT 0x10 /* Sort by mtime */
85 #define LS_SIZE_SORT 0x20 /* Sort by file size */
86 #define LS_REVERSE_SORT 0x40 /* Reverse sort order */
87 #define LS_SHOW_ALL 0x80 /* Don't skip filenames starting with '.' */
89 #define VIEW_FLAGS (LS_LONG_VIEW|LS_SHORT_VIEW|LS_NUMERIC_VIEW)
90 #define SORT_FLAGS (LS_NAME_SORT|LS_TIME_SORT|LS_SIZE_SORT)
92 /* Commands for interactive mode */
115 #define I_PROGRESS 23
122 static const struct CMD cmds[] = {
125 { "chdir", I_CHDIR },
126 { "chgrp", I_CHGRP },
127 { "chmod", I_CHMOD },
128 { "chown", I_CHOWN },
135 { "lchdir", I_LCHDIR },
137 { "lmkdir", I_LMKDIR },
141 { "lumask", I_LUMASK },
142 { "mkdir", I_MKDIR },
143 { "progress", I_PROGRESS },
148 { "rename", I_RENAME },
150 { "rmdir", I_RMDIR },
151 { "symlink", I_SYMLINK },
152 { "version", I_VERSION },
158 int interactive_loop(int fd_in, int fd_out, char *file1, char *file2);
164 kill(sshpid, SIGTERM);
165 waitpid(sshpid, NULL, 0);
172 cmd_interrupt(int signo)
174 const char msg[] = "\rInterrupt \n";
175 int olderrno = errno;
177 write(STDERR_FILENO, msg, sizeof(msg) - 1);
185 printf("Available commands:\n");
186 printf("cd path Change remote directory to 'path'\n");
187 printf("lcd path Change local directory to 'path'\n");
188 printf("chgrp grp path Change group of file 'path' to 'grp'\n");
189 printf("chmod mode path Change permissions of file 'path' to 'mode'\n");
190 printf("chown own path Change owner of file 'path' to 'own'\n");
191 printf("help Display this help text\n");
192 printf("get remote-path [local-path] Download file\n");
193 printf("lls [ls-options [path]] Display local directory listing\n");
194 printf("ln oldpath newpath Symlink remote file\n");
195 printf("lmkdir path Create local directory\n");
196 printf("lpwd Print local working directory\n");
197 printf("ls [path] Display remote directory listing\n");
198 printf("lumask umask Set local umask to 'umask'\n");
199 printf("mkdir path Create remote directory\n");
200 printf("progress Toggle display of progress meter\n");
201 printf("put local-path [remote-path] Upload file\n");
202 printf("pwd Display remote working directory\n");
203 printf("exit Quit sftp\n");
204 printf("quit Quit sftp\n");
205 printf("rename oldpath newpath Rename remote file\n");
206 printf("rmdir path Remove remote directory\n");
207 printf("rm path Delete remote file\n");
208 printf("symlink oldpath newpath Symlink remote file\n");
209 printf("version Show SFTP version\n");
210 printf("!command Execute 'command' in local shell\n");
211 printf("! Escape to local shell\n");
212 printf("? Synonym for help\n");
216 local_do_shell(const char *args)
225 if ((shell = getenv("SHELL")) == NULL)
226 shell = _PATH_BSHELL;
228 if ((pid = fork()) == -1)
229 fatal("Couldn't fork: %s", strerror(errno));
232 /* XXX: child has pipe fds to ssh subproc open - issue? */
234 debug3("Executing %s -c \"%s\"", shell, args);
235 execl(shell, shell, "-c", args, (char *)NULL);
237 debug3("Executing %s", shell);
238 execl(shell, shell, (char *)NULL);
240 fprintf(stderr, "Couldn't execute \"%s\": %s\n", shell,
244 while (waitpid(pid, &status, 0) == -1)
246 fatal("Couldn't wait for child: %s", strerror(errno));
247 if (!WIFEXITED(status))
248 error("Shell exited abnormally");
249 else if (WEXITSTATUS(status))
250 error("Shell exited with status %d", WEXITSTATUS(status));
254 local_do_ls(const char *args)
257 local_do_shell(_PATH_LS);
259 int len = strlen(_PATH_LS " ") + strlen(args) + 1;
260 char *buf = xmalloc(len);
262 /* XXX: quoting - rip quoting code from ftp? */
263 snprintf(buf, len, _PATH_LS " %s", args);
269 /* Strip one path (usually the pwd) from the start of another */
271 path_strip(char *path, char *strip)
276 return (xstrdup(path));
279 if (strncmp(path, strip, len) == 0) {
280 if (strip[len - 1] != '/' && path[len] == '/')
282 return (xstrdup(path + len));
285 return (xstrdup(path));
289 path_append(char *p1, char *p2)
292 int len = strlen(p1) + strlen(p2) + 2;
295 strlcpy(ret, p1, len);
296 if (p1[strlen(p1) - 1] != '/')
297 strlcat(ret, "/", len);
298 strlcat(ret, p2, len);
304 make_absolute(char *p, char *pwd)
309 if (p && p[0] != '/') {
310 abs_str = path_append(pwd, p);
318 infer_path(const char *p, char **ifp)
322 cp = strrchr(p, '/');
329 error("Invalid path");
333 *ifp = xstrdup(cp + 1);
338 parse_getput_flags(const char **cpp, int *pflag)
340 const char *cp = *cpp;
342 /* Check for flags */
343 if (cp[0] == '-' && cp[1] && strchr(WHITESPACE, cp[2])) {
350 error("Invalid flag -%c", cp[1]);
354 *cpp = cp + strspn(cp, WHITESPACE);
361 parse_ls_flags(const char **cpp, int *lflag)
363 const char *cp = *cpp;
366 *lflag = LS_NAME_SORT;
368 /* Check for flags */
369 if (cp++[0] == '-') {
370 for (; strchr(WHITESPACE, *cp) == NULL; cp++) {
373 *lflag &= ~VIEW_FLAGS;
374 *lflag |= LS_LONG_VIEW;
377 *lflag &= ~VIEW_FLAGS;
378 *lflag |= LS_SHORT_VIEW;
381 *lflag &= ~VIEW_FLAGS;
382 *lflag |= LS_NUMERIC_VIEW|LS_LONG_VIEW;
385 *lflag &= ~SORT_FLAGS;
386 *lflag |= LS_SIZE_SORT;
389 *lflag &= ~SORT_FLAGS;
390 *lflag |= LS_TIME_SORT;
393 *lflag |= LS_REVERSE_SORT;
396 *lflag &= ~SORT_FLAGS;
399 *lflag |= LS_SHOW_ALL;
402 error("Invalid flag -%c", *cp);
406 *cpp = cp + strspn(cp, WHITESPACE);
413 get_pathname(const char **cpp, char **path)
415 const char *cp = *cpp, *end;
419 cp += strspn(cp, WHITESPACE);
426 *path = xmalloc(strlen(cp) + 1);
428 /* Check for quoted filenames */
429 if (*cp == '\"' || *cp == '\'') {
432 /* Search for terminating quote, unescape some chars */
433 for (i = j = 0; i <= strlen(cp); i++) {
434 if (cp[i] == quot) { /* Found quote */
439 if (cp[i] == '\0') { /* End of string */
440 error("Unterminated quote");
443 if (cp[i] == '\\') { /* Escaped characters */
445 if (cp[i] != '\'' && cp[i] != '\"' &&
447 error("Bad escaped character '\\%c'",
452 (*path)[j++] = cp[i];
456 error("Empty quotes");
459 *cpp = cp + i + strspn(cp + i, WHITESPACE);
461 /* Read to end of filename */
462 end = strpbrk(cp, WHITESPACE);
464 end = strchr(cp, '\0');
465 *cpp = end + strspn(end, WHITESPACE);
467 memcpy(*path, cp, end - cp);
468 (*path)[end - cp] = '\0';
483 /* XXX: report errors? */
484 if (stat(path, &sb) == -1)
487 return(sb.st_mode & S_IFDIR);
495 if (stat(path, &sb) == -1)
496 fatal("stat %s: %s", path, strerror(errno));
498 return(S_ISREG(sb.st_mode));
502 remote_is_dir(struct sftp_conn *conn, char *path)
506 /* XXX: report errors? */
507 if ((a = do_stat(conn, path, 1)) == NULL)
509 if (!(a->flags & SSH2_FILEXFER_ATTR_PERMISSIONS))
511 return(a->perm & S_IFDIR);
515 process_get(struct sftp_conn *conn, char *src, char *dst, char *pwd, int pflag)
517 char *abs_src = NULL;
518 char *abs_dst = NULL;
524 abs_src = xstrdup(src);
525 abs_src = make_absolute(abs_src, pwd);
527 memset(&g, 0, sizeof(g));
528 debug3("Looking up %s", abs_src);
529 if (remote_glob(conn, abs_src, 0, NULL, &g)) {
530 error("File \"%s\" not found.", abs_src);
535 /* If multiple matches, dst must be a directory or unspecified */
536 if (g.gl_matchc > 1 && dst && !is_dir(dst)) {
537 error("Multiple files match, but \"%s\" is not a directory",
543 for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
544 if (infer_path(g.gl_pathv[i], &tmp)) {
549 if (g.gl_matchc == 1 && dst) {
550 /* If directory specified, append filename */
552 if (infer_path(g.gl_pathv[0], &tmp)) {
556 abs_dst = path_append(dst, tmp);
559 abs_dst = xstrdup(dst);
561 abs_dst = path_append(dst, tmp);
566 printf("Fetching %s to %s\n", g.gl_pathv[i], abs_dst);
567 if (do_download(conn, g.gl_pathv[i], abs_dst, pflag) == -1)
582 process_put(struct sftp_conn *conn, char *src, char *dst, char *pwd, int pflag)
584 char *tmp_dst = NULL;
585 char *abs_dst = NULL;
592 tmp_dst = xstrdup(dst);
593 tmp_dst = make_absolute(tmp_dst, pwd);
596 memset(&g, 0, sizeof(g));
597 debug3("Looking up %s", src);
598 if (glob(src, 0, NULL, &g)) {
599 error("File \"%s\" not found.", src);
604 /* If multiple matches, dst may be directory or unspecified */
605 if (g.gl_matchc > 1 && tmp_dst && !remote_is_dir(conn, tmp_dst)) {
606 error("Multiple files match, but \"%s\" is not a directory",
612 for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
613 if (!is_reg(g.gl_pathv[i])) {
614 error("skipping non-regular file %s",
618 if (infer_path(g.gl_pathv[i], &tmp)) {
623 if (g.gl_matchc == 1 && tmp_dst) {
624 /* If directory specified, append filename */
625 if (remote_is_dir(conn, tmp_dst)) {
626 if (infer_path(g.gl_pathv[0], &tmp)) {
630 abs_dst = path_append(tmp_dst, tmp);
633 abs_dst = xstrdup(tmp_dst);
635 } else if (tmp_dst) {
636 abs_dst = path_append(tmp_dst, tmp);
639 abs_dst = make_absolute(tmp, pwd);
641 printf("Uploading %s to %s\n", g.gl_pathv[i], abs_dst);
642 if (do_upload(conn, g.gl_pathv[i], abs_dst, pflag) == -1)
656 sdirent_comp(const void *aa, const void *bb)
658 SFTP_DIRENT *a = *(SFTP_DIRENT **)aa;
659 SFTP_DIRENT *b = *(SFTP_DIRENT **)bb;
660 int rmul = sort_flag & LS_REVERSE_SORT ? -1 : 1;
662 #define NCMP(a,b) (a == b ? 0 : (a < b ? 1 : -1))
663 if (sort_flag & LS_NAME_SORT)
664 return (rmul * strcmp(a->filename, b->filename));
665 else if (sort_flag & LS_TIME_SORT)
666 return (rmul * NCMP(a->a.mtime, b->a.mtime));
667 else if (sort_flag & LS_SIZE_SORT)
668 return (rmul * NCMP(a->a.size, b->a.size));
670 fatal("Unknown ls sort type");
673 /* sftp ls.1 replacement for directories */
675 do_ls_dir(struct sftp_conn *conn, char *path, char *strip_path, int lflag)
678 u_int c = 1, colspace = 0, columns = 1;
681 if ((n = do_readdir(conn, path, &d)) != 0)
684 if (!(lflag & LS_SHORT_VIEW)) {
685 u_int m = 0, width = 80;
689 /* Count entries for sort and find longest filename */
690 for (n = 0; d[n] != NULL; n++) {
691 if (d[n]->filename[0] != '.' || (lflag & LS_SHOW_ALL))
692 m = MAX(m, strlen(d[n]->filename));
695 /* Add any subpath that also needs to be counted */
696 tmp = path_strip(path, strip_path);
700 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) != -1)
703 columns = width / (m + 2);
704 columns = MAX(columns, 1);
705 colspace = width / columns;
706 colspace = MIN(colspace, width);
709 if (lflag & SORT_FLAGS) {
710 for (n = 0; d[n] != NULL; n++)
711 ; /* count entries */
712 sort_flag = lflag & (SORT_FLAGS|LS_REVERSE_SORT);
713 qsort(d, n, sizeof(*d), sdirent_comp);
716 for (n = 0; d[n] != NULL && !interrupted; n++) {
719 if (d[n]->filename[0] == '.' && !(lflag & LS_SHOW_ALL))
722 tmp = path_append(path, d[n]->filename);
723 fname = path_strip(tmp, strip_path);
726 if (lflag & LS_LONG_VIEW) {
727 if (lflag & LS_NUMERIC_VIEW) {
731 memset(&sb, 0, sizeof(sb));
732 attrib_to_stat(&d[n]->a, &sb);
733 lname = ls_file(fname, &sb, 1);
734 printf("%s\n", lname);
737 printf("%s\n", d[n]->longname);
739 printf("%-*s", colspace, fname);
750 if (!(lflag & LS_LONG_VIEW) && (c != 1))
753 free_sftp_dirents(d);
757 /* sftp ls.1 replacement which handles path globs */
759 do_globbed_ls(struct sftp_conn *conn, char *path, char *strip_path,
763 u_int i, c = 1, colspace = 0, columns = 1;
766 memset(&g, 0, sizeof(g));
768 if (remote_glob(conn, path, GLOB_MARK|GLOB_NOCHECK|GLOB_BRACE,
769 NULL, &g) || (g.gl_pathc && !g.gl_matchc)) {
772 error("Can't ls: \"%s\" not found", path);
780 * If the glob returns a single match and it is a directory,
781 * then just list its contents.
783 if (g.gl_matchc == 1) {
784 if ((a = do_lstat(conn, g.gl_pathv[0], 1)) == NULL) {
788 if ((a->flags & SSH2_FILEXFER_ATTR_PERMISSIONS) &&
792 err = do_ls_dir(conn, g.gl_pathv[0], strip_path, lflag);
798 if (!(lflag & LS_SHORT_VIEW)) {
799 u_int m = 0, width = 80;
802 /* Count entries for sort and find longest filename */
803 for (i = 0; g.gl_pathv[i]; i++)
804 m = MAX(m, strlen(g.gl_pathv[i]));
806 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) != -1)
809 columns = width / (m + 2);
810 columns = MAX(columns, 1);
811 colspace = width / columns;
814 for (i = 0; g.gl_pathv[i] && !interrupted; i++, a = NULL) {
817 fname = path_strip(g.gl_pathv[i], strip_path);
819 if (lflag & LS_LONG_VIEW) {
824 * XXX: this is slow - 1 roundtrip per path
825 * A solution to this is to fork glob() and
826 * build a sftp specific version which keeps the
827 * attribs (which currently get thrown away)
828 * that the server returns as well as the filenames.
830 memset(&sb, 0, sizeof(sb));
832 a = do_lstat(conn, g.gl_pathv[i], 1);
834 attrib_to_stat(a, &sb);
835 lname = ls_file(fname, &sb, 1);
836 printf("%s\n", lname);
839 printf("%-*s", colspace, fname);
849 if (!(lflag & LS_LONG_VIEW) && (c != 1))
860 parse_args(const char **cpp, int *pflag, int *lflag, int *iflag,
861 unsigned long *n_arg, char **path1, char **path2)
863 const char *cmd, *cp = *cpp;
869 /* Skip leading whitespace */
870 cp = cp + strspn(cp, WHITESPACE);
872 /* Ignore blank lines and lines which begin with comment '#' char */
873 if (*cp == '\0' || *cp == '#')
876 /* Check for leading '-' (disable error processing) */
883 /* Figure out which command we have */
884 for (i = 0; cmds[i].c; i++) {
885 int cmdlen = strlen(cmds[i].c);
887 /* Check for command followed by whitespace */
888 if (!strncasecmp(cp, cmds[i].c, cmdlen) &&
889 strchr(WHITESPACE, cp[cmdlen])) {
891 cp = cp + strspn(cp, WHITESPACE);
902 } else if (cmdnum == -1) {
903 error("Invalid command.");
907 /* Get arguments and parse flags */
908 *lflag = *pflag = *n_arg = 0;
909 *path1 = *path2 = NULL;
913 if (parse_getput_flags(&cp, pflag))
915 /* Get first pathname (mandatory) */
916 if (get_pathname(&cp, path1))
918 if (*path1 == NULL) {
919 error("You must specify at least one path after a "
923 /* Try to get second pathname (optional) */
924 if (get_pathname(&cp, path2))
929 if (get_pathname(&cp, path1))
931 if (get_pathname(&cp, path2))
933 if (!*path1 || !*path2) {
934 error("You must specify two paths after a %s "
945 /* Get pathname (mandatory) */
946 if (get_pathname(&cp, path1))
948 if (*path1 == NULL) {
949 error("You must specify a path after a %s command.",
955 if (parse_ls_flags(&cp, lflag))
957 /* Path is optional */
958 if (get_pathname(&cp, path1))
963 /* Uses the rest of the line */
971 /* Get numeric arg (mandatory) */
972 l = strtol(cp, &cp2, base);
973 if (cp2 == cp || ((l == LONG_MIN || l == LONG_MAX) &&
974 errno == ERANGE) || l < 0) {
975 error("You must supply a numeric argument "
976 "to the %s command.", cmd);
981 if (cmdnum == I_LUMASK && strchr(WHITESPACE, *cp))
983 if (cmdnum == I_LUMASK || !strchr(WHITESPACE, *cp)) {
984 error("You must supply a numeric argument "
985 "to the %s command.", cmd);
988 cp += strspn(cp, WHITESPACE);
990 /* Get pathname (mandatory) */
991 if (get_pathname(&cp, path1))
993 if (*path1 == NULL) {
994 error("You must specify a path after a %s command.",
1007 fatal("Command not implemented");
1015 parse_dispatch_command(struct sftp_conn *conn, const char *cmd, char **pwd,
1018 char *path1, *path2, *tmp;
1019 int pflag, lflag, iflag, cmdnum, i;
1020 unsigned long n_arg;
1022 char path_buf[MAXPATHLEN];
1026 path1 = path2 = NULL;
1027 cmdnum = parse_args(&cmd, &pflag, &lflag, &iflag, &n_arg,
1033 memset(&g, 0, sizeof(g));
1035 /* Perform command */
1041 /* Unrecognized command */
1045 err = process_get(conn, path1, path2, *pwd, pflag);
1048 err = process_put(conn, path1, path2, *pwd, pflag);
1051 path1 = make_absolute(path1, *pwd);
1052 path2 = make_absolute(path2, *pwd);
1053 err = do_rename(conn, path1, path2);
1056 path2 = make_absolute(path2, *pwd);
1057 err = do_symlink(conn, path1, path2);
1060 path1 = make_absolute(path1, *pwd);
1061 remote_glob(conn, path1, GLOB_NOCHECK, NULL, &g);
1062 for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
1063 printf("Removing %s\n", g.gl_pathv[i]);
1064 err = do_rm(conn, g.gl_pathv[i]);
1065 if (err != 0 && err_abort)
1070 path1 = make_absolute(path1, *pwd);
1072 a.flags |= SSH2_FILEXFER_ATTR_PERMISSIONS;
1074 err = do_mkdir(conn, path1, &a);
1077 path1 = make_absolute(path1, *pwd);
1078 err = do_rmdir(conn, path1);
1081 path1 = make_absolute(path1, *pwd);
1082 if ((tmp = do_realpath(conn, path1)) == NULL) {
1086 if ((aa = do_stat(conn, tmp, 0)) == NULL) {
1091 if (!(aa->flags & SSH2_FILEXFER_ATTR_PERMISSIONS)) {
1092 error("Can't change directory: Can't check target");
1097 if (!S_ISDIR(aa->perm)) {
1098 error("Can't change directory: \"%s\" is not "
1099 "a directory", tmp);
1109 do_globbed_ls(conn, *pwd, *pwd, lflag);
1113 /* Strip pwd off beginning of non-absolute paths */
1118 path1 = make_absolute(path1, *pwd);
1119 err = do_globbed_ls(conn, path1, tmp, lflag);
1122 if (chdir(path1) == -1) {
1123 error("Couldn't change local directory to "
1124 "\"%s\": %s", path1, strerror(errno));
1129 if (mkdir(path1, 0777) == -1) {
1130 error("Couldn't create local directory "
1131 "\"%s\": %s", path1, strerror(errno));
1139 local_do_shell(cmd);
1143 printf("Local umask: %03lo\n", n_arg);
1146 path1 = make_absolute(path1, *pwd);
1148 a.flags |= SSH2_FILEXFER_ATTR_PERMISSIONS;
1150 remote_glob(conn, path1, GLOB_NOCHECK, NULL, &g);
1151 for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
1152 printf("Changing mode on %s\n", g.gl_pathv[i]);
1153 err = do_setstat(conn, g.gl_pathv[i], &a);
1154 if (err != 0 && err_abort)
1160 path1 = make_absolute(path1, *pwd);
1161 remote_glob(conn, path1, GLOB_NOCHECK, NULL, &g);
1162 for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
1163 if (!(aa = do_stat(conn, g.gl_pathv[i], 0))) {
1164 if (err != 0 && err_abort)
1169 if (!(aa->flags & SSH2_FILEXFER_ATTR_UIDGID)) {
1170 error("Can't get current ownership of "
1171 "remote file \"%s\"", g.gl_pathv[i]);
1172 if (err != 0 && err_abort)
1177 aa->flags &= SSH2_FILEXFER_ATTR_UIDGID;
1178 if (cmdnum == I_CHOWN) {
1179 printf("Changing owner on %s\n", g.gl_pathv[i]);
1182 printf("Changing group on %s\n", g.gl_pathv[i]);
1185 err = do_setstat(conn, g.gl_pathv[i], aa);
1186 if (err != 0 && err_abort)
1191 printf("Remote working directory: %s\n", *pwd);
1194 if (!getcwd(path_buf, sizeof(path_buf))) {
1195 error("Couldn't get local cwd: %s", strerror(errno));
1199 printf("Local working directory: %s\n", path_buf);
1202 /* Processed below */
1208 printf("SFTP protocol version %u\n", sftp_proto_version(conn));
1211 showprogress = !showprogress;
1213 printf("Progress meter enabled\n");
1215 printf("Progress meter disabled\n");
1218 fatal("%d is not implemented", cmdnum);
1228 /* If an unignored error occurs in batch mode we should abort. */
1229 if (err_abort && err != 0)
1231 else if (cmdnum == I_QUIT)
1239 prompt(EditLine *el)
1246 interactive_loop(int fd_in, int fd_out, char *file1, char *file2)
1251 struct sftp_conn *conn;
1252 int err, interactive;
1253 EditLine *el = NULL;
1257 extern char *__progname;
1259 if (!batchmode && isatty(STDIN_FILENO)) {
1260 if ((el = el_init(__progname, stdin, stdout, stderr)) == NULL)
1261 fatal("Couldn't initialise editline");
1262 if ((hl = history_init()) == NULL)
1263 fatal("Couldn't initialise editline history");
1264 history(hl, &hev, H_SETSIZE, 100);
1265 el_set(el, EL_HIST, history, hl);
1267 el_set(el, EL_PROMPT, prompt);
1268 el_set(el, EL_EDITOR, "emacs");
1269 el_set(el, EL_TERMINAL, NULL);
1270 el_set(el, EL_SIGNAL, 1);
1271 el_source(el, NULL);
1273 #endif /* USE_LIBEDIT */
1275 conn = do_init(fd_in, fd_out, copy_buffer_len, num_requests);
1277 fatal("Couldn't initialise connection to server");
1279 pwd = do_realpath(conn, ".");
1283 if (file1 != NULL) {
1284 dir = xstrdup(file1);
1285 dir = make_absolute(dir, pwd);
1287 if (remote_is_dir(conn, dir) && file2 == NULL) {
1288 printf("Changing to: %s\n", dir);
1289 snprintf(cmd, sizeof cmd, "cd \"%s\"", dir);
1290 if (parse_dispatch_command(conn, cmd, &pwd, 1) != 0) {
1298 snprintf(cmd, sizeof cmd, "get %s", dir);
1300 snprintf(cmd, sizeof cmd, "get %s %s", dir,
1303 err = parse_dispatch_command(conn, cmd, &pwd, 1);
1312 #if defined(HAVE_SETVBUF) && !defined(BROKEN_SETVBUF)
1313 setvbuf(stdout, NULL, _IOLBF, 0);
1314 setvbuf(infile, NULL, _IOLBF, 0);
1320 interactive = !batchmode && isatty(STDIN_FILENO);
1325 signal(SIGINT, SIG_IGN);
1330 if (fgets(cmd, sizeof(cmd), infile) == NULL) {
1335 if (!interactive) { /* Echo command */
1336 printf("sftp> %s", cmd);
1337 if (strlen(cmd) > 0 &&
1338 cmd[strlen(cmd) - 1] != '\n')
1346 if ((line = el_gets(el, &count)) == NULL || count <= 0) {
1350 history(hl, &hev, H_ENTER, line);
1351 if (strlcpy(cmd, line, sizeof(cmd)) >= sizeof(cmd)) {
1352 fprintf(stderr, "Error: input line too long\n");
1355 #endif /* USE_LIBEDIT */
1358 cp = strrchr(cmd, '\n');
1362 /* Handle user interrupts gracefully during commands */
1364 signal(SIGINT, cmd_interrupt);
1366 err = parse_dispatch_command(conn, cmd, &pwd, batchmode);
1376 #endif /* USE_LIBEDIT */
1378 /* err == 1 signifies normal "quit" exit */
1379 return (err >= 0 ? 0 : -1);
1383 connect_to_server(char *path, char **args, int *in, int *out)
1388 int pin[2], pout[2];
1390 if ((pipe(pin) == -1) || (pipe(pout) == -1))
1391 fatal("pipe: %s", strerror(errno));
1396 #else /* USE_PIPES */
1399 if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) == -1)
1400 fatal("socketpair: %s", strerror(errno));
1401 *in = *out = inout[0];
1402 c_in = c_out = inout[1];
1403 #endif /* USE_PIPES */
1405 if ((sshpid = fork()) == -1)
1406 fatal("fork: %s", strerror(errno));
1407 else if (sshpid == 0) {
1408 if ((dup2(c_in, STDIN_FILENO) == -1) ||
1409 (dup2(c_out, STDOUT_FILENO) == -1)) {
1410 fprintf(stderr, "dup2: %s\n", strerror(errno));
1419 * The underlying ssh is in the same process group, so we must
1420 * ignore SIGINT if we want to gracefully abort commands,
1421 * otherwise the signal will make it to the ssh process and
1424 signal(SIGINT, SIG_IGN);
1426 fprintf(stderr, "exec: %s: %s\n", path, strerror(errno));
1430 signal(SIGTERM, killchild);
1431 signal(SIGINT, killchild);
1432 signal(SIGHUP, killchild);
1440 extern char *__progname;
1443 "usage: %s [-1Cv] [-B buffer_size] [-b batchfile] [-F ssh_config]\n"
1444 " [-o ssh_option] [-P sftp_server_path] [-R num_requests]\n"
1445 " [-S program] [-s subsystem | sftp_server] host\n"
1446 " %s [[user@]host[:file [file]]]\n"
1447 " %s [[user@]host[:dir[/]]]\n"
1448 " %s -b batchfile [user@]host\n", __progname, __progname, __progname, __progname);
1453 main(int argc, char **argv)
1455 int in, out, ch, err;
1456 char *host, *userhost, *cp, *file2 = NULL;
1457 int debug_level = 0, sshver = 2;
1458 char *file1 = NULL, *sftp_server = NULL;
1459 char *ssh_program = _PATH_SSH_PROGRAM, *sftp_direct = NULL;
1460 LogLevel ll = SYSLOG_LEVEL_INFO;
1463 extern char *optarg;
1465 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
1468 __progname = ssh_get_progname(argv[0]);
1469 memset(&args, '\0', sizeof(args));
1471 addargs(&args, ssh_program);
1472 addargs(&args, "-oForwardX11 no");
1473 addargs(&args, "-oForwardAgent no");
1474 addargs(&args, "-oPermitLocalCommand no");
1475 addargs(&args, "-oClearAllForwardings yes");
1477 ll = SYSLOG_LEVEL_INFO;
1480 while ((ch = getopt(argc, argv, "1hvCo:s:S:b:B:F:P:R:")) != -1) {
1483 addargs(&args, "-C");
1486 if (debug_level < 3) {
1487 addargs(&args, "-v");
1488 ll = SYSLOG_LEVEL_DEBUG1 + debug_level;
1494 addargs(&args, "-%c%s", ch, optarg);
1498 if (sftp_server == NULL)
1499 sftp_server = _PATH_SFTP_SERVER;
1502 sftp_server = optarg;
1505 ssh_program = optarg;
1506 replacearg(&args, 0, "%s", ssh_program);
1510 fatal("Batch file already specified.");
1512 /* Allow "-" as stdin */
1513 if (strcmp(optarg, "-") != 0 &&
1514 (infile = fopen(optarg, "r")) == NULL)
1515 fatal("%s (%s).", strerror(errno), optarg);
1518 addargs(&args, "-obatchmode yes");
1521 sftp_direct = optarg;
1524 copy_buffer_len = strtol(optarg, &cp, 10);
1525 if (copy_buffer_len == 0 || *cp != '\0')
1526 fatal("Invalid buffer size \"%s\"", optarg);
1529 num_requests = strtol(optarg, &cp, 10);
1530 if (num_requests == 0 || *cp != '\0')
1531 fatal("Invalid number of requests \"%s\"",
1540 if (!isatty(STDERR_FILENO))
1543 log_init(argv[0], ll, SYSLOG_FACILITY_USER, 1);
1545 if (sftp_direct == NULL) {
1546 if (optind == argc || argc > (optind + 2))
1549 userhost = xstrdup(argv[optind]);
1550 file2 = argv[optind+1];
1552 if ((host = strrchr(userhost, '@')) == NULL)
1557 fprintf(stderr, "Missing username\n");
1560 addargs(&args, "-l%s",userhost);
1563 if ((cp = colon(host)) != NULL) {
1568 host = cleanhostname(host);
1570 fprintf(stderr, "Missing hostname\n");
1574 addargs(&args, "-oProtocol %d", sshver);
1576 /* no subsystem if the server-spec contains a '/' */
1577 if (sftp_server == NULL || strchr(sftp_server, '/') == NULL)
1578 addargs(&args, "-s");
1580 addargs(&args, "%s", host);
1581 addargs(&args, "%s", (sftp_server != NULL ?
1582 sftp_server : "sftp"));
1585 fprintf(stderr, "Connecting to %s...\n", host);
1586 connect_to_server(ssh_program, args.list, &in, &out);
1589 addargs(&args, "sftp-server");
1592 fprintf(stderr, "Attaching to %s...\n", sftp_direct);
1593 connect_to_server(sftp_direct, args.list, &in, &out);
1597 err = interactive_loop(in, out, file1, file2);
1599 #if !defined(USE_PIPES)
1600 shutdown(in, SHUT_RDWR);
1601 shutdown(out, SHUT_RDWR);
1609 while (waitpid(sshpid, NULL, 0) == -1)
1611 fatal("Couldn't wait for ssh process: %s",
1614 exit(err == 0 ? 0 : 1);