2 * Copyright (c) 2001-2004 Damien Miller <djm@openbsd.org>
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
19 RCSID("$OpenBSD: sftp.c,v 1.54 2004/06/22 01:16:39 djm Exp $");
24 #include "pathnames.h"
28 #include "sftp-common.h"
29 #include "sftp-client.h"
31 /* File to read commands from */
34 /* Are we in batchfile mode? */
37 /* Size of buffer used when copying files */
38 size_t copy_buffer_len = 32768;
40 /* Number of concurrent outstanding requests */
41 size_t num_requests = 16;
43 /* PID of ssh transport process */
44 static pid_t sshpid = -1;
46 /* This is set to 0 if the progressmeter is not desired. */
49 /* SIGINT received during command processing */
50 volatile sig_atomic_t interrupted = 0;
52 /* I wish qsort() took a separate ctx for the comparison function...*/
55 int remote_glob(struct sftp_conn *, const char *, int,
56 int (*)(const char *, int), glob_t *); /* proto for sftp-glob.c */
58 #ifdef HAVE___PROGNAME
59 extern char *__progname;
64 /* Separators for interactive commands */
65 #define WHITESPACE " \t\r\n"
68 #define LS_LONG_VIEW 0x01 /* Full view ala ls -l */
69 #define LS_SHORT_VIEW 0x02 /* Single row view ala ls -1 */
70 #define LS_NUMERIC_VIEW 0x04 /* Long view with numeric uid/gid */
71 #define LS_NAME_SORT 0x08 /* Sort by name (default) */
72 #define LS_TIME_SORT 0x10 /* Sort by mtime */
73 #define LS_SIZE_SORT 0x20 /* Sort by file size */
74 #define LS_REVERSE_SORT 0x40 /* Reverse sort order */
75 #define LS_SHOW_ALL 0x80 /* Don't skip filenames starting with '.' */
77 #define VIEW_FLAGS (LS_LONG_VIEW|LS_SHORT_VIEW|LS_NUMERIC_VIEW)
78 #define SORT_FLAGS (LS_NAME_SORT|LS_TIME_SORT|LS_SIZE_SORT)
80 /* Commands for interactive mode */
103 #define I_PROGRESS 23
110 static const struct CMD cmds[] = {
113 { "chdir", I_CHDIR },
114 { "chgrp", I_CHGRP },
115 { "chmod", I_CHMOD },
116 { "chown", I_CHOWN },
123 { "lchdir", I_LCHDIR },
125 { "lmkdir", I_LMKDIR },
129 { "lumask", I_LUMASK },
130 { "mkdir", I_MKDIR },
131 { "progress", I_PROGRESS },
136 { "rename", I_RENAME },
138 { "rmdir", I_RMDIR },
139 { "symlink", I_SYMLINK },
140 { "version", I_VERSION },
146 int interactive_loop(int fd_in, int fd_out, char *file1, char *file2);
152 kill(sshpid, SIGTERM);
158 cmd_interrupt(int signo)
160 const char msg[] = "\rInterrupt \n";
162 write(STDERR_FILENO, msg, sizeof(msg) - 1);
169 printf("Available commands:\n");
170 printf("cd path Change remote directory to 'path'\n");
171 printf("lcd path Change local directory to 'path'\n");
172 printf("chgrp grp path Change group of file 'path' to 'grp'\n");
173 printf("chmod mode path Change permissions of file 'path' to 'mode'\n");
174 printf("chown own path Change owner of file 'path' to 'own'\n");
175 printf("help Display this help text\n");
176 printf("get remote-path [local-path] Download file\n");
177 printf("lls [ls-options [path]] Display local directory listing\n");
178 printf("ln oldpath newpath Symlink remote file\n");
179 printf("lmkdir path Create local directory\n");
180 printf("lpwd Print local working directory\n");
181 printf("ls [path] Display remote directory listing\n");
182 printf("lumask umask Set local umask to 'umask'\n");
183 printf("mkdir path Create remote directory\n");
184 printf("progress Toggle display of progress meter\n");
185 printf("put local-path [remote-path] Upload file\n");
186 printf("pwd Display remote working directory\n");
187 printf("exit Quit sftp\n");
188 printf("quit Quit sftp\n");
189 printf("rename oldpath newpath Rename remote file\n");
190 printf("rmdir path Remove remote directory\n");
191 printf("rm path Delete remote file\n");
192 printf("symlink oldpath newpath Symlink remote file\n");
193 printf("version Show SFTP version\n");
194 printf("!command Execute 'command' in local shell\n");
195 printf("! Escape to local shell\n");
196 printf("? Synonym for help\n");
200 local_do_shell(const char *args)
209 if ((shell = getenv("SHELL")) == NULL)
210 shell = _PATH_BSHELL;
212 if ((pid = fork()) == -1)
213 fatal("Couldn't fork: %s", strerror(errno));
216 /* XXX: child has pipe fds to ssh subproc open - issue? */
218 debug3("Executing %s -c \"%s\"", shell, args);
219 execl(shell, shell, "-c", args, (char *)NULL);
221 debug3("Executing %s", shell);
222 execl(shell, shell, (char *)NULL);
224 fprintf(stderr, "Couldn't execute \"%s\": %s\n", shell,
228 while (waitpid(pid, &status, 0) == -1)
230 fatal("Couldn't wait for child: %s", strerror(errno));
231 if (!WIFEXITED(status))
232 error("Shell exited abormally");
233 else if (WEXITSTATUS(status))
234 error("Shell exited with status %d", WEXITSTATUS(status));
238 local_do_ls(const char *args)
241 local_do_shell(_PATH_LS);
243 int len = strlen(_PATH_LS " ") + strlen(args) + 1;
244 char *buf = xmalloc(len);
246 /* XXX: quoting - rip quoting code from ftp? */
247 snprintf(buf, len, _PATH_LS " %s", args);
253 /* Strip one path (usually the pwd) from the start of another */
255 path_strip(char *path, char *strip)
260 return (xstrdup(path));
263 if (strip != NULL && strncmp(path, strip, len) == 0) {
264 if (strip[len - 1] != '/' && path[len] == '/')
266 return (xstrdup(path + len));
269 return (xstrdup(path));
273 path_append(char *p1, char *p2)
276 int len = strlen(p1) + strlen(p2) + 2;
279 strlcpy(ret, p1, len);
280 if (p1[strlen(p1) - 1] != '/')
281 strlcat(ret, "/", len);
282 strlcat(ret, p2, len);
288 make_absolute(char *p, char *pwd)
293 if (p && p[0] != '/') {
294 abs_str = path_append(pwd, p);
302 infer_path(const char *p, char **ifp)
306 cp = strrchr(p, '/');
313 error("Invalid path");
317 *ifp = xstrdup(cp + 1);
322 parse_getput_flags(const char **cpp, int *pflag)
324 const char *cp = *cpp;
326 /* Check for flags */
327 if (cp[0] == '-' && cp[1] && strchr(WHITESPACE, cp[2])) {
334 error("Invalid flag -%c", cp[1]);
338 *cpp = cp + strspn(cp, WHITESPACE);
345 parse_ls_flags(const char **cpp, int *lflag)
347 const char *cp = *cpp;
350 *lflag = LS_NAME_SORT;
352 /* Check for flags */
353 if (cp++[0] == '-') {
354 for(; strchr(WHITESPACE, *cp) == NULL; cp++) {
357 *lflag &= ~VIEW_FLAGS;
358 *lflag |= LS_LONG_VIEW;
361 *lflag &= ~VIEW_FLAGS;
362 *lflag |= LS_SHORT_VIEW;
365 *lflag &= ~VIEW_FLAGS;
366 *lflag |= LS_NUMERIC_VIEW|LS_LONG_VIEW;
369 *lflag &= ~SORT_FLAGS;
370 *lflag |= LS_SIZE_SORT;
373 *lflag &= ~SORT_FLAGS;
374 *lflag |= LS_TIME_SORT;
377 *lflag |= LS_REVERSE_SORT;
380 *lflag &= ~SORT_FLAGS;
383 *lflag |= LS_SHOW_ALL;
386 error("Invalid flag -%c", *cp);
390 *cpp = cp + strspn(cp, WHITESPACE);
397 get_pathname(const char **cpp, char **path)
399 const char *cp = *cpp, *end;
403 cp += strspn(cp, WHITESPACE);
410 *path = xmalloc(strlen(cp) + 1);
412 /* Check for quoted filenames */
413 if (*cp == '\"' || *cp == '\'') {
416 /* Search for terminating quote, unescape some chars */
417 for (i = j = 0; i <= strlen(cp); i++) {
418 if (cp[i] == quot) { /* Found quote */
423 if (cp[i] == '\0') { /* End of string */
424 error("Unterminated quote");
427 if (cp[i] == '\\') { /* Escaped characters */
429 if (cp[i] != '\'' && cp[i] != '\"' &&
431 error("Bad escaped character '\%c'",
436 (*path)[j++] = cp[i];
440 error("Empty quotes");
443 *cpp = cp + i + strspn(cp + i, WHITESPACE);
445 /* Read to end of filename */
446 end = strpbrk(cp, WHITESPACE);
448 end = strchr(cp, '\0');
449 *cpp = end + strspn(end, WHITESPACE);
451 memcpy(*path, cp, end - cp);
452 (*path)[end - cp] = '\0';
467 /* XXX: report errors? */
468 if (stat(path, &sb) == -1)
471 return(sb.st_mode & S_IFDIR);
479 if (stat(path, &sb) == -1)
480 fatal("stat %s: %s", path, strerror(errno));
482 return(S_ISREG(sb.st_mode));
486 remote_is_dir(struct sftp_conn *conn, char *path)
490 /* XXX: report errors? */
491 if ((a = do_stat(conn, path, 1)) == NULL)
493 if (!(a->flags & SSH2_FILEXFER_ATTR_PERMISSIONS))
495 return(a->perm & S_IFDIR);
499 process_get(struct sftp_conn *conn, char *src, char *dst, char *pwd, int pflag)
501 char *abs_src = NULL;
502 char *abs_dst = NULL;
508 abs_src = xstrdup(src);
509 abs_src = make_absolute(abs_src, pwd);
511 memset(&g, 0, sizeof(g));
512 debug3("Looking up %s", abs_src);
513 if (remote_glob(conn, abs_src, 0, NULL, &g)) {
514 error("File \"%s\" not found.", abs_src);
519 /* If multiple matches, dst must be a directory or unspecified */
520 if (g.gl_matchc > 1 && dst && !is_dir(dst)) {
521 error("Multiple files match, but \"%s\" is not a directory",
527 for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
528 if (infer_path(g.gl_pathv[i], &tmp)) {
533 if (g.gl_matchc == 1 && dst) {
534 /* If directory specified, append filename */
536 if (infer_path(g.gl_pathv[0], &tmp)) {
540 abs_dst = path_append(dst, tmp);
543 abs_dst = xstrdup(dst);
545 abs_dst = path_append(dst, tmp);
550 printf("Fetching %s to %s\n", g.gl_pathv[i], abs_dst);
551 if (do_download(conn, g.gl_pathv[i], abs_dst, pflag) == -1)
566 process_put(struct sftp_conn *conn, char *src, char *dst, char *pwd, int pflag)
568 char *tmp_dst = NULL;
569 char *abs_dst = NULL;
576 tmp_dst = xstrdup(dst);
577 tmp_dst = make_absolute(tmp_dst, pwd);
580 memset(&g, 0, sizeof(g));
581 debug3("Looking up %s", src);
582 if (glob(src, 0, NULL, &g)) {
583 error("File \"%s\" not found.", src);
588 /* If multiple matches, dst may be directory or unspecified */
589 if (g.gl_matchc > 1 && tmp_dst && !remote_is_dir(conn, tmp_dst)) {
590 error("Multiple files match, but \"%s\" is not a directory",
596 for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
597 if (!is_reg(g.gl_pathv[i])) {
598 error("skipping non-regular file %s",
602 if (infer_path(g.gl_pathv[i], &tmp)) {
607 if (g.gl_matchc == 1 && tmp_dst) {
608 /* If directory specified, append filename */
609 if (remote_is_dir(conn, tmp_dst)) {
610 if (infer_path(g.gl_pathv[0], &tmp)) {
614 abs_dst = path_append(tmp_dst, tmp);
617 abs_dst = xstrdup(tmp_dst);
619 } else if (tmp_dst) {
620 abs_dst = path_append(tmp_dst, tmp);
623 abs_dst = make_absolute(tmp, pwd);
625 printf("Uploading %s to %s\n", g.gl_pathv[i], abs_dst);
626 if (do_upload(conn, g.gl_pathv[i], abs_dst, pflag) == -1)
640 sdirent_comp(const void *aa, const void *bb)
642 SFTP_DIRENT *a = *(SFTP_DIRENT **)aa;
643 SFTP_DIRENT *b = *(SFTP_DIRENT **)bb;
644 int rmul = sort_flag & LS_REVERSE_SORT ? -1 : 1;
646 #define NCMP(a,b) (a == b ? 0 : (a < b ? 1 : -1))
647 if (sort_flag & LS_NAME_SORT)
648 return (rmul * strcmp(a->filename, b->filename));
649 else if (sort_flag & LS_TIME_SORT)
650 return (rmul * NCMP(a->a.mtime, b->a.mtime));
651 else if (sort_flag & LS_SIZE_SORT)
652 return (rmul * NCMP(a->a.size, b->a.size));
654 fatal("Unknown ls sort type");
657 /* sftp ls.1 replacement for directories */
659 do_ls_dir(struct sftp_conn *conn, char *path, char *strip_path, int lflag)
661 int n, c = 1, colspace = 0, columns = 1;
664 if ((n = do_readdir(conn, path, &d)) != 0)
667 if (!(lflag & LS_SHORT_VIEW)) {
668 int m = 0, width = 80;
672 /* Count entries for sort and find longest filename */
673 for (n = 0; d[n] != NULL; n++) {
674 if (d[n]->filename[0] != '.' || (lflag & LS_SHOW_ALL))
675 m = MAX(m, strlen(d[n]->filename));
678 /* Add any subpath that also needs to be counted */
679 tmp = path_strip(path, strip_path);
683 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) != -1)
686 columns = width / (m + 2);
687 columns = MAX(columns, 1);
688 colspace = width / columns;
689 colspace = MIN(colspace, width);
692 if (lflag & SORT_FLAGS) {
693 sort_flag = lflag & (SORT_FLAGS|LS_REVERSE_SORT);
694 qsort(d, n, sizeof(*d), sdirent_comp);
697 for (n = 0; d[n] != NULL && !interrupted; n++) {
700 if (d[n]->filename[0] == '.' && !(lflag & LS_SHOW_ALL))
703 tmp = path_append(path, d[n]->filename);
704 fname = path_strip(tmp, strip_path);
707 if (lflag & LS_LONG_VIEW) {
708 if (lflag & LS_NUMERIC_VIEW) {
712 memset(&sb, 0, sizeof(sb));
713 attrib_to_stat(&d[n]->a, &sb);
714 lname = ls_file(fname, &sb, 1);
715 printf("%s\n", lname);
718 printf("%s\n", d[n]->longname);
720 printf("%-*s", colspace, fname);
731 if (!(lflag & LS_LONG_VIEW) && (c != 1))
734 free_sftp_dirents(d);
738 /* sftp ls.1 replacement which handles path globs */
740 do_globbed_ls(struct sftp_conn *conn, char *path, char *strip_path,
744 int i, c = 1, colspace = 0, columns = 1;
747 memset(&g, 0, sizeof(g));
749 if (remote_glob(conn, path, GLOB_MARK|GLOB_NOCHECK|GLOB_BRACE,
751 error("Can't ls: \"%s\" not found", path);
759 * If the glob returns a single match, which is the same as the
760 * input glob, and it is a directory, then just list its contents
762 if (g.gl_pathc == 1 &&
763 strncmp(path, g.gl_pathv[0], strlen(g.gl_pathv[0]) - 1) == 0) {
764 if ((a = do_lstat(conn, path, 1)) == NULL) {
768 if ((a->flags & SSH2_FILEXFER_ATTR_PERMISSIONS) &&
771 return (do_ls_dir(conn, path, strip_path, lflag));
775 if (!(lflag & LS_SHORT_VIEW)) {
776 int m = 0, width = 80;
779 /* Count entries for sort and find longest filename */
780 for (i = 0; g.gl_pathv[i]; i++)
781 m = MAX(m, strlen(g.gl_pathv[i]));
783 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) != -1)
786 columns = width / (m + 2);
787 columns = MAX(columns, 1);
788 colspace = width / columns;
791 for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
794 fname = path_strip(g.gl_pathv[i], strip_path);
796 if (lflag & LS_LONG_VIEW) {
801 * XXX: this is slow - 1 roundtrip per path
802 * A solution to this is to fork glob() and
803 * build a sftp specific version which keeps the
804 * attribs (which currently get thrown away)
805 * that the server returns as well as the filenames.
807 memset(&sb, 0, sizeof(sb));
808 a = do_lstat(conn, g.gl_pathv[i], 1);
810 attrib_to_stat(a, &sb);
811 lname = ls_file(fname, &sb, 1);
812 printf("%s\n", lname);
815 printf("%-*s", colspace, fname);
825 if (!(lflag & LS_LONG_VIEW) && (c != 1))
836 parse_args(const char **cpp, int *pflag, int *lflag, int *iflag,
837 unsigned long *n_arg, char **path1, char **path2)
839 const char *cmd, *cp = *cpp;
845 /* Skip leading whitespace */
846 cp = cp + strspn(cp, WHITESPACE);
848 /* Ignore blank lines and lines which begin with comment '#' char */
849 if (*cp == '\0' || *cp == '#')
852 /* Check for leading '-' (disable error processing) */
859 /* Figure out which command we have */
860 for (i = 0; cmds[i].c; i++) {
861 int cmdlen = strlen(cmds[i].c);
863 /* Check for command followed by whitespace */
864 if (!strncasecmp(cp, cmds[i].c, cmdlen) &&
865 strchr(WHITESPACE, cp[cmdlen])) {
867 cp = cp + strspn(cp, WHITESPACE);
878 } else if (cmdnum == -1) {
879 error("Invalid command.");
883 /* Get arguments and parse flags */
884 *lflag = *pflag = *n_arg = 0;
885 *path1 = *path2 = NULL;
889 if (parse_getput_flags(&cp, pflag))
891 /* Get first pathname (mandatory) */
892 if (get_pathname(&cp, path1))
894 if (*path1 == NULL) {
895 error("You must specify at least one path after a "
899 /* Try to get second pathname (optional) */
900 if (get_pathname(&cp, path2))
905 if (get_pathname(&cp, path1))
907 if (get_pathname(&cp, path2))
909 if (!*path1 || !*path2) {
910 error("You must specify two paths after a %s "
921 /* Get pathname (mandatory) */
922 if (get_pathname(&cp, path1))
924 if (*path1 == NULL) {
925 error("You must specify a path after a %s command.",
931 if (parse_ls_flags(&cp, lflag))
933 /* Path is optional */
934 if (get_pathname(&cp, path1))
939 /* Uses the rest of the line */
947 /* Get numeric arg (mandatory) */
948 l = strtol(cp, &cp2, base);
949 if (cp2 == cp || ((l == LONG_MIN || l == LONG_MAX) &&
950 errno == ERANGE) || l < 0) {
951 error("You must supply a numeric argument "
952 "to the %s command.", cmd);
957 if (cmdnum == I_LUMASK && strchr(WHITESPACE, *cp))
959 if (cmdnum == I_LUMASK || !strchr(WHITESPACE, *cp)) {
960 error("You must supply a numeric argument "
961 "to the %s command.", cmd);
964 cp += strspn(cp, WHITESPACE);
966 /* Get pathname (mandatory) */
967 if (get_pathname(&cp, path1))
969 if (*path1 == NULL) {
970 error("You must specify a path after a %s command.",
983 fatal("Command not implemented");
991 parse_dispatch_command(struct sftp_conn *conn, const char *cmd, char **pwd,
994 char *path1, *path2, *tmp;
995 int pflag, lflag, iflag, cmdnum, i;
998 char path_buf[MAXPATHLEN];
1002 path1 = path2 = NULL;
1003 cmdnum = parse_args(&cmd, &pflag, &lflag, &iflag, &n_arg,
1009 memset(&g, 0, sizeof(g));
1011 /* Perform command */
1017 /* Unrecognized command */
1021 err = process_get(conn, path1, path2, *pwd, pflag);
1024 err = process_put(conn, path1, path2, *pwd, pflag);
1027 path1 = make_absolute(path1, *pwd);
1028 path2 = make_absolute(path2, *pwd);
1029 err = do_rename(conn, path1, path2);
1032 path2 = make_absolute(path2, *pwd);
1033 err = do_symlink(conn, path1, path2);
1036 path1 = make_absolute(path1, *pwd);
1037 remote_glob(conn, path1, GLOB_NOCHECK, NULL, &g);
1038 for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
1039 printf("Removing %s\n", g.gl_pathv[i]);
1040 err = do_rm(conn, g.gl_pathv[i]);
1041 if (err != 0 && err_abort)
1046 path1 = make_absolute(path1, *pwd);
1048 a.flags |= SSH2_FILEXFER_ATTR_PERMISSIONS;
1050 err = do_mkdir(conn, path1, &a);
1053 path1 = make_absolute(path1, *pwd);
1054 err = do_rmdir(conn, path1);
1057 path1 = make_absolute(path1, *pwd);
1058 if ((tmp = do_realpath(conn, path1)) == NULL) {
1062 if ((aa = do_stat(conn, tmp, 0)) == NULL) {
1067 if (!(aa->flags & SSH2_FILEXFER_ATTR_PERMISSIONS)) {
1068 error("Can't change directory: Can't check target");
1073 if (!S_ISDIR(aa->perm)) {
1074 error("Can't change directory: \"%s\" is not "
1075 "a directory", tmp);
1085 do_globbed_ls(conn, *pwd, *pwd, lflag);
1089 /* Strip pwd off beginning of non-absolute paths */
1094 path1 = make_absolute(path1, *pwd);
1095 err = do_globbed_ls(conn, path1, tmp, lflag);
1098 if (chdir(path1) == -1) {
1099 error("Couldn't change local directory to "
1100 "\"%s\": %s", path1, strerror(errno));
1105 if (mkdir(path1, 0777) == -1) {
1106 error("Couldn't create local directory "
1107 "\"%s\": %s", path1, strerror(errno));
1115 local_do_shell(cmd);
1119 printf("Local umask: %03lo\n", n_arg);
1122 path1 = make_absolute(path1, *pwd);
1124 a.flags |= SSH2_FILEXFER_ATTR_PERMISSIONS;
1126 remote_glob(conn, path1, GLOB_NOCHECK, NULL, &g);
1127 for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
1128 printf("Changing mode on %s\n", g.gl_pathv[i]);
1129 err = do_setstat(conn, g.gl_pathv[i], &a);
1130 if (err != 0 && err_abort)
1136 path1 = make_absolute(path1, *pwd);
1137 remote_glob(conn, path1, GLOB_NOCHECK, NULL, &g);
1138 for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
1139 if (!(aa = do_stat(conn, g.gl_pathv[i], 0))) {
1140 if (err != 0 && err_abort)
1145 if (!(aa->flags & SSH2_FILEXFER_ATTR_UIDGID)) {
1146 error("Can't get current ownership of "
1147 "remote file \"%s\"", g.gl_pathv[i]);
1148 if (err != 0 && err_abort)
1153 aa->flags &= SSH2_FILEXFER_ATTR_UIDGID;
1154 if (cmdnum == I_CHOWN) {
1155 printf("Changing owner on %s\n", g.gl_pathv[i]);
1158 printf("Changing group on %s\n", g.gl_pathv[i]);
1161 err = do_setstat(conn, g.gl_pathv[i], aa);
1162 if (err != 0 && err_abort)
1167 printf("Remote working directory: %s\n", *pwd);
1170 if (!getcwd(path_buf, sizeof(path_buf))) {
1171 error("Couldn't get local cwd: %s", strerror(errno));
1175 printf("Local working directory: %s\n", path_buf);
1178 /* Processed below */
1184 printf("SFTP protocol version %u\n", sftp_proto_version(conn));
1187 showprogress = !showprogress;
1189 printf("Progress meter enabled\n");
1191 printf("Progress meter disabled\n");
1194 fatal("%d is not implemented", cmdnum);
1204 /* If an unignored error occurs in batch mode we should abort. */
1205 if (err_abort && err != 0)
1207 else if (cmdnum == I_QUIT)
1214 interactive_loop(int fd_in, int fd_out, char *file1, char *file2)
1219 struct sftp_conn *conn;
1222 conn = do_init(fd_in, fd_out, copy_buffer_len, num_requests);
1224 fatal("Couldn't initialise connection to server");
1226 pwd = do_realpath(conn, ".");
1230 if (file1 != NULL) {
1231 dir = xstrdup(file1);
1232 dir = make_absolute(dir, pwd);
1234 if (remote_is_dir(conn, dir) && file2 == NULL) {
1235 printf("Changing to: %s\n", dir);
1236 snprintf(cmd, sizeof cmd, "cd \"%s\"", dir);
1237 if (parse_dispatch_command(conn, cmd, &pwd, 1) != 0)
1241 snprintf(cmd, sizeof cmd, "get %s", dir);
1243 snprintf(cmd, sizeof cmd, "get %s %s", dir,
1246 err = parse_dispatch_command(conn, cmd, &pwd, 1);
1255 setvbuf(stdout, NULL, _IOLBF, 0);
1256 setvbuf(infile, NULL, _IOLBF, 0);
1266 signal(SIGINT, SIG_IGN);
1270 /* XXX: use libedit */
1271 if (fgets(cmd, sizeof(cmd), infile) == NULL) {
1276 if (batchmode) /* Echo command */
1279 cp = strrchr(cmd, '\n');
1283 /* Handle user interrupts gracefully during commands */
1285 signal(SIGINT, cmd_interrupt);
1287 err = parse_dispatch_command(conn, cmd, &pwd, batchmode);
1293 /* err == 1 signifies normal "quit" exit */
1294 return (err >= 0 ? 0 : -1);
1298 connect_to_server(char *path, char **args, int *in, int *out)
1303 int pin[2], pout[2];
1305 if ((pipe(pin) == -1) || (pipe(pout) == -1))
1306 fatal("pipe: %s", strerror(errno));
1311 #else /* USE_PIPES */
1314 if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) == -1)
1315 fatal("socketpair: %s", strerror(errno));
1316 *in = *out = inout[0];
1317 c_in = c_out = inout[1];
1318 #endif /* USE_PIPES */
1320 if ((sshpid = fork()) == -1)
1321 fatal("fork: %s", strerror(errno));
1322 else if (sshpid == 0) {
1323 if ((dup2(c_in, STDIN_FILENO) == -1) ||
1324 (dup2(c_out, STDOUT_FILENO) == -1)) {
1325 fprintf(stderr, "dup2: %s\n", strerror(errno));
1334 * The underlying ssh is in the same process group, so we must
1335 * ignore SIGINT if we want to gracefully abort commands,
1336 * otherwise the signal will make it to the ssh process and
1339 signal(SIGINT, SIG_IGN);
1341 fprintf(stderr, "exec: %s: %s\n", path, strerror(errno));
1345 signal(SIGTERM, killchild);
1346 signal(SIGINT, killchild);
1347 signal(SIGHUP, killchild);
1355 extern char *__progname;
1358 "usage: %s [-1Cv] [-B buffer_size] [-b batchfile] [-F ssh_config]\n"
1359 " [-o ssh_option] [-P sftp_server_path] [-R num_requests]\n"
1360 " [-S program] [-s subsystem | sftp_server] host\n"
1361 " %s [[user@]host[:file [file]]]\n"
1362 " %s [[user@]host[:dir[/]]]\n"
1363 " %s -b batchfile [user@]host\n", __progname, __progname, __progname, __progname);
1368 main(int argc, char **argv)
1370 int in, out, ch, err;
1371 char *host, *userhost, *cp, *file2 = NULL;
1372 int debug_level = 0, sshver = 2;
1373 char *file1 = NULL, *sftp_server = NULL;
1374 char *ssh_program = _PATH_SSH_PROGRAM, *sftp_direct = NULL;
1375 LogLevel ll = SYSLOG_LEVEL_INFO;
1378 extern char *optarg;
1380 __progname = ssh_get_progname(argv[0]);
1382 addargs(&args, "ssh"); /* overwritten with ssh_program */
1383 addargs(&args, "-oForwardX11 no");
1384 addargs(&args, "-oForwardAgent no");
1385 addargs(&args, "-oClearAllForwardings yes");
1387 ll = SYSLOG_LEVEL_INFO;
1390 while ((ch = getopt(argc, argv, "1hvCo:s:S:b:B:F:P:R:")) != -1) {
1393 addargs(&args, "-C");
1396 if (debug_level < 3) {
1397 addargs(&args, "-v");
1398 ll = SYSLOG_LEVEL_DEBUG1 + debug_level;
1404 addargs(&args, "-%c%s", ch, optarg);
1408 if (sftp_server == NULL)
1409 sftp_server = _PATH_SFTP_SERVER;
1412 sftp_server = optarg;
1415 ssh_program = optarg;
1419 fatal("Batch file already specified.");
1421 /* Allow "-" as stdin */
1422 if (strcmp(optarg, "-") != 0 &&
1423 (infile = fopen(optarg, "r")) == NULL)
1424 fatal("%s (%s).", strerror(errno), optarg);
1429 sftp_direct = optarg;
1432 copy_buffer_len = strtol(optarg, &cp, 10);
1433 if (copy_buffer_len == 0 || *cp != '\0')
1434 fatal("Invalid buffer size \"%s\"", optarg);
1437 num_requests = strtol(optarg, &cp, 10);
1438 if (num_requests == 0 || *cp != '\0')
1439 fatal("Invalid number of requests \"%s\"",
1448 if (!isatty(STDERR_FILENO))
1451 log_init(argv[0], ll, SYSLOG_FACILITY_USER, 1);
1453 if (sftp_direct == NULL) {
1454 if (optind == argc || argc > (optind + 2))
1457 userhost = xstrdup(argv[optind]);
1458 file2 = argv[optind+1];
1460 if ((host = strrchr(userhost, '@')) == NULL)
1465 fprintf(stderr, "Missing username\n");
1468 addargs(&args, "-l%s",userhost);
1471 if ((cp = colon(host)) != NULL) {
1476 host = cleanhostname(host);
1478 fprintf(stderr, "Missing hostname\n");
1482 addargs(&args, "-oProtocol %d", sshver);
1484 /* no subsystem if the server-spec contains a '/' */
1485 if (sftp_server == NULL || strchr(sftp_server, '/') == NULL)
1486 addargs(&args, "-s");
1488 addargs(&args, "%s", host);
1489 addargs(&args, "%s", (sftp_server != NULL ?
1490 sftp_server : "sftp"));
1491 args.list[0] = ssh_program;
1494 fprintf(stderr, "Connecting to %s...\n", host);
1495 connect_to_server(ssh_program, args.list, &in, &out);
1498 addargs(&args, "sftp-server");
1501 fprintf(stderr, "Attaching to %s...\n", sftp_direct);
1502 connect_to_server(sftp_direct, args.list, &in, &out);
1505 err = interactive_loop(in, out, file1, file2);
1507 #if !defined(USE_PIPES)
1508 shutdown(in, SHUT_RDWR);
1509 shutdown(out, SHUT_RDWR);
1517 while (waitpid(sshpid, NULL, 0) == -1)
1519 fatal("Couldn't wait for ssh process: %s",
1522 exit(err == 0 ? 0 : 1);