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.57 2004/11/05 12:19:56 djm Exp $");
24 typedef void EditLine;
30 #include "pathnames.h"
34 #include "sftp-common.h"
35 #include "sftp-client.h"
37 /* File to read commands from */
40 /* Are we in batchfile mode? */
43 /* Size of buffer used when copying files */
44 size_t copy_buffer_len = 32768;
46 /* Number of concurrent outstanding requests */
47 size_t num_requests = 16;
49 /* PID of ssh transport process */
50 static pid_t sshpid = -1;
52 /* This is set to 0 if the progressmeter is not desired. */
55 /* SIGINT received during command processing */
56 volatile sig_atomic_t interrupted = 0;
58 /* I wish qsort() took a separate ctx for the comparison function...*/
61 int remote_glob(struct sftp_conn *, const char *, int,
62 int (*)(const char *, int), glob_t *); /* proto for sftp-glob.c */
64 extern char *__progname;
66 /* Separators for interactive commands */
67 #define WHITESPACE " \t\r\n"
70 #define LS_LONG_VIEW 0x01 /* Full view ala ls -l */
71 #define LS_SHORT_VIEW 0x02 /* Single row view ala ls -1 */
72 #define LS_NUMERIC_VIEW 0x04 /* Long view with numeric uid/gid */
73 #define LS_NAME_SORT 0x08 /* Sort by name (default) */
74 #define LS_TIME_SORT 0x10 /* Sort by mtime */
75 #define LS_SIZE_SORT 0x20 /* Sort by file size */
76 #define LS_REVERSE_SORT 0x40 /* Reverse sort order */
77 #define LS_SHOW_ALL 0x80 /* Don't skip filenames starting with '.' */
79 #define VIEW_FLAGS (LS_LONG_VIEW|LS_SHORT_VIEW|LS_NUMERIC_VIEW)
80 #define SORT_FLAGS (LS_NAME_SORT|LS_TIME_SORT|LS_SIZE_SORT)
82 /* Commands for interactive mode */
105 #define I_PROGRESS 23
112 static const struct CMD cmds[] = {
115 { "chdir", I_CHDIR },
116 { "chgrp", I_CHGRP },
117 { "chmod", I_CHMOD },
118 { "chown", I_CHOWN },
125 { "lchdir", I_LCHDIR },
127 { "lmkdir", I_LMKDIR },
131 { "lumask", I_LUMASK },
132 { "mkdir", I_MKDIR },
133 { "progress", I_PROGRESS },
138 { "rename", I_RENAME },
140 { "rmdir", I_RMDIR },
141 { "symlink", I_SYMLINK },
142 { "version", I_VERSION },
148 int interactive_loop(int fd_in, int fd_out, char *file1, char *file2);
154 kill(sshpid, SIGTERM);
160 cmd_interrupt(int signo)
162 const char msg[] = "\rInterrupt \n";
164 write(STDERR_FILENO, msg, sizeof(msg) - 1);
171 printf("Available commands:\n");
172 printf("cd path Change remote directory to 'path'\n");
173 printf("lcd path Change local directory to 'path'\n");
174 printf("chgrp grp path Change group of file 'path' to 'grp'\n");
175 printf("chmod mode path Change permissions of file 'path' to 'mode'\n");
176 printf("chown own path Change owner of file 'path' to 'own'\n");
177 printf("help Display this help text\n");
178 printf("get remote-path [local-path] Download file\n");
179 printf("lls [ls-options [path]] Display local directory listing\n");
180 printf("ln oldpath newpath Symlink remote file\n");
181 printf("lmkdir path Create local directory\n");
182 printf("lpwd Print local working directory\n");
183 printf("ls [path] Display remote directory listing\n");
184 printf("lumask umask Set local umask to 'umask'\n");
185 printf("mkdir path Create remote directory\n");
186 printf("progress Toggle display of progress meter\n");
187 printf("put local-path [remote-path] Upload file\n");
188 printf("pwd Display remote working directory\n");
189 printf("exit Quit sftp\n");
190 printf("quit Quit sftp\n");
191 printf("rename oldpath newpath Rename remote file\n");
192 printf("rmdir path Remove remote directory\n");
193 printf("rm path Delete remote file\n");
194 printf("symlink oldpath newpath Symlink remote file\n");
195 printf("version Show SFTP version\n");
196 printf("!command Execute 'command' in local shell\n");
197 printf("! Escape to local shell\n");
198 printf("? Synonym for help\n");
202 local_do_shell(const char *args)
211 if ((shell = getenv("SHELL")) == NULL)
212 shell = _PATH_BSHELL;
214 if ((pid = fork()) == -1)
215 fatal("Couldn't fork: %s", strerror(errno));
218 /* XXX: child has pipe fds to ssh subproc open - issue? */
220 debug3("Executing %s -c \"%s\"", shell, args);
221 execl(shell, shell, "-c", args, (char *)NULL);
223 debug3("Executing %s", shell);
224 execl(shell, shell, (char *)NULL);
226 fprintf(stderr, "Couldn't execute \"%s\": %s\n", shell,
230 while (waitpid(pid, &status, 0) == -1)
232 fatal("Couldn't wait for child: %s", strerror(errno));
233 if (!WIFEXITED(status))
234 error("Shell exited abormally");
235 else if (WEXITSTATUS(status))
236 error("Shell exited with status %d", WEXITSTATUS(status));
240 local_do_ls(const char *args)
243 local_do_shell(_PATH_LS);
245 int len = strlen(_PATH_LS " ") + strlen(args) + 1;
246 char *buf = xmalloc(len);
248 /* XXX: quoting - rip quoting code from ftp? */
249 snprintf(buf, len, _PATH_LS " %s", args);
255 /* Strip one path (usually the pwd) from the start of another */
257 path_strip(char *path, char *strip)
262 return (xstrdup(path));
265 if (strip != NULL && strncmp(path, strip, len) == 0) {
266 if (strip[len - 1] != '/' && path[len] == '/')
268 return (xstrdup(path + len));
271 return (xstrdup(path));
275 path_append(char *p1, char *p2)
278 int len = strlen(p1) + strlen(p2) + 2;
281 strlcpy(ret, p1, len);
282 if (p1[strlen(p1) - 1] != '/')
283 strlcat(ret, "/", len);
284 strlcat(ret, p2, len);
290 make_absolute(char *p, char *pwd)
295 if (p && p[0] != '/') {
296 abs_str = path_append(pwd, p);
304 infer_path(const char *p, char **ifp)
308 cp = strrchr(p, '/');
315 error("Invalid path");
319 *ifp = xstrdup(cp + 1);
324 parse_getput_flags(const char **cpp, int *pflag)
326 const char *cp = *cpp;
328 /* Check for flags */
329 if (cp[0] == '-' && cp[1] && strchr(WHITESPACE, cp[2])) {
336 error("Invalid flag -%c", cp[1]);
340 *cpp = cp + strspn(cp, WHITESPACE);
347 parse_ls_flags(const char **cpp, int *lflag)
349 const char *cp = *cpp;
352 *lflag = LS_NAME_SORT;
354 /* Check for flags */
355 if (cp++[0] == '-') {
356 for(; strchr(WHITESPACE, *cp) == NULL; cp++) {
359 *lflag &= ~VIEW_FLAGS;
360 *lflag |= LS_LONG_VIEW;
363 *lflag &= ~VIEW_FLAGS;
364 *lflag |= LS_SHORT_VIEW;
367 *lflag &= ~VIEW_FLAGS;
368 *lflag |= LS_NUMERIC_VIEW|LS_LONG_VIEW;
371 *lflag &= ~SORT_FLAGS;
372 *lflag |= LS_SIZE_SORT;
375 *lflag &= ~SORT_FLAGS;
376 *lflag |= LS_TIME_SORT;
379 *lflag |= LS_REVERSE_SORT;
382 *lflag &= ~SORT_FLAGS;
385 *lflag |= LS_SHOW_ALL;
388 error("Invalid flag -%c", *cp);
392 *cpp = cp + strspn(cp, WHITESPACE);
399 get_pathname(const char **cpp, char **path)
401 const char *cp = *cpp, *end;
405 cp += strspn(cp, WHITESPACE);
412 *path = xmalloc(strlen(cp) + 1);
414 /* Check for quoted filenames */
415 if (*cp == '\"' || *cp == '\'') {
418 /* Search for terminating quote, unescape some chars */
419 for (i = j = 0; i <= strlen(cp); i++) {
420 if (cp[i] == quot) { /* Found quote */
425 if (cp[i] == '\0') { /* End of string */
426 error("Unterminated quote");
429 if (cp[i] == '\\') { /* Escaped characters */
431 if (cp[i] != '\'' && cp[i] != '\"' &&
433 error("Bad escaped character '\\%c'",
438 (*path)[j++] = cp[i];
442 error("Empty quotes");
445 *cpp = cp + i + strspn(cp + i, WHITESPACE);
447 /* Read to end of filename */
448 end = strpbrk(cp, WHITESPACE);
450 end = strchr(cp, '\0');
451 *cpp = end + strspn(end, WHITESPACE);
453 memcpy(*path, cp, end - cp);
454 (*path)[end - cp] = '\0';
469 /* XXX: report errors? */
470 if (stat(path, &sb) == -1)
473 return(sb.st_mode & S_IFDIR);
481 if (stat(path, &sb) == -1)
482 fatal("stat %s: %s", path, strerror(errno));
484 return(S_ISREG(sb.st_mode));
488 remote_is_dir(struct sftp_conn *conn, char *path)
492 /* XXX: report errors? */
493 if ((a = do_stat(conn, path, 1)) == NULL)
495 if (!(a->flags & SSH2_FILEXFER_ATTR_PERMISSIONS))
497 return(a->perm & S_IFDIR);
501 process_get(struct sftp_conn *conn, char *src, char *dst, char *pwd, int pflag)
503 char *abs_src = NULL;
504 char *abs_dst = NULL;
510 abs_src = xstrdup(src);
511 abs_src = make_absolute(abs_src, pwd);
513 memset(&g, 0, sizeof(g));
514 debug3("Looking up %s", abs_src);
515 if (remote_glob(conn, abs_src, 0, NULL, &g)) {
516 error("File \"%s\" not found.", abs_src);
521 /* If multiple matches, dst must be a directory or unspecified */
522 if (g.gl_matchc > 1 && dst && !is_dir(dst)) {
523 error("Multiple files match, but \"%s\" is not a directory",
529 for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
530 if (infer_path(g.gl_pathv[i], &tmp)) {
535 if (g.gl_matchc == 1 && dst) {
536 /* If directory specified, append filename */
538 if (infer_path(g.gl_pathv[0], &tmp)) {
542 abs_dst = path_append(dst, tmp);
545 abs_dst = xstrdup(dst);
547 abs_dst = path_append(dst, tmp);
552 printf("Fetching %s to %s\n", g.gl_pathv[i], abs_dst);
553 if (do_download(conn, g.gl_pathv[i], abs_dst, pflag) == -1)
568 process_put(struct sftp_conn *conn, char *src, char *dst, char *pwd, int pflag)
570 char *tmp_dst = NULL;
571 char *abs_dst = NULL;
578 tmp_dst = xstrdup(dst);
579 tmp_dst = make_absolute(tmp_dst, pwd);
582 memset(&g, 0, sizeof(g));
583 debug3("Looking up %s", src);
584 if (glob(src, 0, NULL, &g)) {
585 error("File \"%s\" not found.", src);
590 /* If multiple matches, dst may be directory or unspecified */
591 if (g.gl_matchc > 1 && tmp_dst && !remote_is_dir(conn, tmp_dst)) {
592 error("Multiple files match, but \"%s\" is not a directory",
598 for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
599 if (!is_reg(g.gl_pathv[i])) {
600 error("skipping non-regular file %s",
604 if (infer_path(g.gl_pathv[i], &tmp)) {
609 if (g.gl_matchc == 1 && tmp_dst) {
610 /* If directory specified, append filename */
611 if (remote_is_dir(conn, tmp_dst)) {
612 if (infer_path(g.gl_pathv[0], &tmp)) {
616 abs_dst = path_append(tmp_dst, tmp);
619 abs_dst = xstrdup(tmp_dst);
621 } else if (tmp_dst) {
622 abs_dst = path_append(tmp_dst, tmp);
625 abs_dst = make_absolute(tmp, pwd);
627 printf("Uploading %s to %s\n", g.gl_pathv[i], abs_dst);
628 if (do_upload(conn, g.gl_pathv[i], abs_dst, pflag) == -1)
642 sdirent_comp(const void *aa, const void *bb)
644 SFTP_DIRENT *a = *(SFTP_DIRENT **)aa;
645 SFTP_DIRENT *b = *(SFTP_DIRENT **)bb;
646 int rmul = sort_flag & LS_REVERSE_SORT ? -1 : 1;
648 #define NCMP(a,b) (a == b ? 0 : (a < b ? 1 : -1))
649 if (sort_flag & LS_NAME_SORT)
650 return (rmul * strcmp(a->filename, b->filename));
651 else if (sort_flag & LS_TIME_SORT)
652 return (rmul * NCMP(a->a.mtime, b->a.mtime));
653 else if (sort_flag & LS_SIZE_SORT)
654 return (rmul * NCMP(a->a.size, b->a.size));
656 fatal("Unknown ls sort type");
659 /* sftp ls.1 replacement for directories */
661 do_ls_dir(struct sftp_conn *conn, char *path, char *strip_path, int lflag)
663 int n, c = 1, colspace = 0, columns = 1;
666 if ((n = do_readdir(conn, path, &d)) != 0)
669 if (!(lflag & LS_SHORT_VIEW)) {
670 int m = 0, width = 80;
674 /* Count entries for sort and find longest filename */
675 for (n = 0; d[n] != NULL; n++) {
676 if (d[n]->filename[0] != '.' || (lflag & LS_SHOW_ALL))
677 m = MAX(m, strlen(d[n]->filename));
680 /* Add any subpath that also needs to be counted */
681 tmp = path_strip(path, strip_path);
685 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) != -1)
688 columns = width / (m + 2);
689 columns = MAX(columns, 1);
690 colspace = width / columns;
691 colspace = MIN(colspace, width);
694 if (lflag & SORT_FLAGS) {
695 sort_flag = lflag & (SORT_FLAGS|LS_REVERSE_SORT);
696 qsort(d, n, sizeof(*d), sdirent_comp);
699 for (n = 0; d[n] != NULL && !interrupted; n++) {
702 if (d[n]->filename[0] == '.' && !(lflag & LS_SHOW_ALL))
705 tmp = path_append(path, d[n]->filename);
706 fname = path_strip(tmp, strip_path);
709 if (lflag & LS_LONG_VIEW) {
710 if (lflag & LS_NUMERIC_VIEW) {
714 memset(&sb, 0, sizeof(sb));
715 attrib_to_stat(&d[n]->a, &sb);
716 lname = ls_file(fname, &sb, 1);
717 printf("%s\n", lname);
720 printf("%s\n", d[n]->longname);
722 printf("%-*s", colspace, fname);
733 if (!(lflag & LS_LONG_VIEW) && (c != 1))
736 free_sftp_dirents(d);
740 /* sftp ls.1 replacement which handles path globs */
742 do_globbed_ls(struct sftp_conn *conn, char *path, char *strip_path,
746 int i, c = 1, colspace = 0, columns = 1;
749 memset(&g, 0, sizeof(g));
751 if (remote_glob(conn, path, GLOB_MARK|GLOB_NOCHECK|GLOB_BRACE,
753 error("Can't ls: \"%s\" not found", path);
761 * If the glob returns a single match, which is the same as the
762 * input glob, and it is a directory, then just list its contents
764 if (g.gl_pathc == 1 &&
765 strncmp(path, g.gl_pathv[0], strlen(g.gl_pathv[0]) - 1) == 0) {
766 if ((a = do_lstat(conn, path, 1)) == NULL) {
770 if ((a->flags & SSH2_FILEXFER_ATTR_PERMISSIONS) &&
773 return (do_ls_dir(conn, path, strip_path, lflag));
777 if (!(lflag & LS_SHORT_VIEW)) {
778 int m = 0, width = 80;
781 /* Count entries for sort and find longest filename */
782 for (i = 0; g.gl_pathv[i]; i++)
783 m = MAX(m, strlen(g.gl_pathv[i]));
785 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) != -1)
788 columns = width / (m + 2);
789 columns = MAX(columns, 1);
790 colspace = width / columns;
793 for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
796 fname = path_strip(g.gl_pathv[i], strip_path);
798 if (lflag & LS_LONG_VIEW) {
803 * XXX: this is slow - 1 roundtrip per path
804 * A solution to this is to fork glob() and
805 * build a sftp specific version which keeps the
806 * attribs (which currently get thrown away)
807 * that the server returns as well as the filenames.
809 memset(&sb, 0, sizeof(sb));
810 a = do_lstat(conn, g.gl_pathv[i], 1);
812 attrib_to_stat(a, &sb);
813 lname = ls_file(fname, &sb, 1);
814 printf("%s\n", lname);
817 printf("%-*s", colspace, fname);
827 if (!(lflag & LS_LONG_VIEW) && (c != 1))
838 parse_args(const char **cpp, int *pflag, int *lflag, int *iflag,
839 unsigned long *n_arg, char **path1, char **path2)
841 const char *cmd, *cp = *cpp;
847 /* Skip leading whitespace */
848 cp = cp + strspn(cp, WHITESPACE);
850 /* Ignore blank lines and lines which begin with comment '#' char */
851 if (*cp == '\0' || *cp == '#')
854 /* Check for leading '-' (disable error processing) */
861 /* Figure out which command we have */
862 for (i = 0; cmds[i].c; i++) {
863 int cmdlen = strlen(cmds[i].c);
865 /* Check for command followed by whitespace */
866 if (!strncasecmp(cp, cmds[i].c, cmdlen) &&
867 strchr(WHITESPACE, cp[cmdlen])) {
869 cp = cp + strspn(cp, WHITESPACE);
880 } else if (cmdnum == -1) {
881 error("Invalid command.");
885 /* Get arguments and parse flags */
886 *lflag = *pflag = *n_arg = 0;
887 *path1 = *path2 = NULL;
891 if (parse_getput_flags(&cp, pflag))
893 /* Get first pathname (mandatory) */
894 if (get_pathname(&cp, path1))
896 if (*path1 == NULL) {
897 error("You must specify at least one path after a "
901 /* Try to get second pathname (optional) */
902 if (get_pathname(&cp, path2))
907 if (get_pathname(&cp, path1))
909 if (get_pathname(&cp, path2))
911 if (!*path1 || !*path2) {
912 error("You must specify two paths after a %s "
923 /* Get pathname (mandatory) */
924 if (get_pathname(&cp, path1))
926 if (*path1 == NULL) {
927 error("You must specify a path after a %s command.",
933 if (parse_ls_flags(&cp, lflag))
935 /* Path is optional */
936 if (get_pathname(&cp, path1))
941 /* Uses the rest of the line */
949 /* Get numeric arg (mandatory) */
950 l = strtol(cp, &cp2, base);
951 if (cp2 == cp || ((l == LONG_MIN || l == LONG_MAX) &&
952 errno == ERANGE) || l < 0) {
953 error("You must supply a numeric argument "
954 "to the %s command.", cmd);
959 if (cmdnum == I_LUMASK && strchr(WHITESPACE, *cp))
961 if (cmdnum == I_LUMASK || !strchr(WHITESPACE, *cp)) {
962 error("You must supply a numeric argument "
963 "to the %s command.", cmd);
966 cp += strspn(cp, WHITESPACE);
968 /* Get pathname (mandatory) */
969 if (get_pathname(&cp, path1))
971 if (*path1 == NULL) {
972 error("You must specify a path after a %s command.",
985 fatal("Command not implemented");
993 parse_dispatch_command(struct sftp_conn *conn, const char *cmd, char **pwd,
996 char *path1, *path2, *tmp;
997 int pflag, lflag, iflag, cmdnum, i;
1000 char path_buf[MAXPATHLEN];
1004 path1 = path2 = NULL;
1005 cmdnum = parse_args(&cmd, &pflag, &lflag, &iflag, &n_arg,
1011 memset(&g, 0, sizeof(g));
1013 /* Perform command */
1019 /* Unrecognized command */
1023 err = process_get(conn, path1, path2, *pwd, pflag);
1026 err = process_put(conn, path1, path2, *pwd, pflag);
1029 path1 = make_absolute(path1, *pwd);
1030 path2 = make_absolute(path2, *pwd);
1031 err = do_rename(conn, path1, path2);
1034 path2 = make_absolute(path2, *pwd);
1035 err = do_symlink(conn, path1, path2);
1038 path1 = make_absolute(path1, *pwd);
1039 remote_glob(conn, path1, GLOB_NOCHECK, NULL, &g);
1040 for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
1041 printf("Removing %s\n", g.gl_pathv[i]);
1042 err = do_rm(conn, g.gl_pathv[i]);
1043 if (err != 0 && err_abort)
1048 path1 = make_absolute(path1, *pwd);
1050 a.flags |= SSH2_FILEXFER_ATTR_PERMISSIONS;
1052 err = do_mkdir(conn, path1, &a);
1055 path1 = make_absolute(path1, *pwd);
1056 err = do_rmdir(conn, path1);
1059 path1 = make_absolute(path1, *pwd);
1060 if ((tmp = do_realpath(conn, path1)) == NULL) {
1064 if ((aa = do_stat(conn, tmp, 0)) == NULL) {
1069 if (!(aa->flags & SSH2_FILEXFER_ATTR_PERMISSIONS)) {
1070 error("Can't change directory: Can't check target");
1075 if (!S_ISDIR(aa->perm)) {
1076 error("Can't change directory: \"%s\" is not "
1077 "a directory", tmp);
1087 do_globbed_ls(conn, *pwd, *pwd, lflag);
1091 /* Strip pwd off beginning of non-absolute paths */
1096 path1 = make_absolute(path1, *pwd);
1097 err = do_globbed_ls(conn, path1, tmp, lflag);
1100 if (chdir(path1) == -1) {
1101 error("Couldn't change local directory to "
1102 "\"%s\": %s", path1, strerror(errno));
1107 if (mkdir(path1, 0777) == -1) {
1108 error("Couldn't create local directory "
1109 "\"%s\": %s", path1, strerror(errno));
1117 local_do_shell(cmd);
1121 printf("Local umask: %03lo\n", n_arg);
1124 path1 = make_absolute(path1, *pwd);
1126 a.flags |= SSH2_FILEXFER_ATTR_PERMISSIONS;
1128 remote_glob(conn, path1, GLOB_NOCHECK, NULL, &g);
1129 for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
1130 printf("Changing mode on %s\n", g.gl_pathv[i]);
1131 err = do_setstat(conn, g.gl_pathv[i], &a);
1132 if (err != 0 && err_abort)
1138 path1 = make_absolute(path1, *pwd);
1139 remote_glob(conn, path1, GLOB_NOCHECK, NULL, &g);
1140 for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
1141 if (!(aa = do_stat(conn, g.gl_pathv[i], 0))) {
1142 if (err != 0 && err_abort)
1147 if (!(aa->flags & SSH2_FILEXFER_ATTR_UIDGID)) {
1148 error("Can't get current ownership of "
1149 "remote file \"%s\"", g.gl_pathv[i]);
1150 if (err != 0 && err_abort)
1155 aa->flags &= SSH2_FILEXFER_ATTR_UIDGID;
1156 if (cmdnum == I_CHOWN) {
1157 printf("Changing owner on %s\n", g.gl_pathv[i]);
1160 printf("Changing group on %s\n", g.gl_pathv[i]);
1163 err = do_setstat(conn, g.gl_pathv[i], aa);
1164 if (err != 0 && err_abort)
1169 printf("Remote working directory: %s\n", *pwd);
1172 if (!getcwd(path_buf, sizeof(path_buf))) {
1173 error("Couldn't get local cwd: %s", strerror(errno));
1177 printf("Local working directory: %s\n", path_buf);
1180 /* Processed below */
1186 printf("SFTP protocol version %u\n", sftp_proto_version(conn));
1189 showprogress = !showprogress;
1191 printf("Progress meter enabled\n");
1193 printf("Progress meter disabled\n");
1196 fatal("%d is not implemented", cmdnum);
1206 /* If an unignored error occurs in batch mode we should abort. */
1207 if (err_abort && err != 0)
1209 else if (cmdnum == I_QUIT)
1217 prompt(EditLine *el)
1224 interactive_loop(int fd_in, int fd_out, char *file1, char *file2)
1229 struct sftp_conn *conn;
1231 EditLine *el = NULL;
1235 extern char *__progname;
1237 if (!batchmode && isatty(STDIN_FILENO)) {
1238 if ((el = el_init(__progname, stdin, stdout, stderr)) == NULL)
1239 fatal("Couldn't initialise editline");
1240 if ((hl = history_init()) == NULL)
1241 fatal("Couldn't initialise editline history");
1242 history(hl, &hev, H_SETSIZE, 100);
1243 el_set(el, EL_HIST, history, hl);
1245 el_set(el, EL_PROMPT, prompt);
1246 el_set(el, EL_EDITOR, "emacs");
1247 el_set(el, EL_TERMINAL, NULL);
1248 el_set(el, EL_SIGNAL, 1);
1249 el_source(el, NULL);
1251 #endif /* USE_LIBEDIT */
1253 conn = do_init(fd_in, fd_out, copy_buffer_len, num_requests);
1255 fatal("Couldn't initialise connection to server");
1257 pwd = do_realpath(conn, ".");
1261 if (file1 != NULL) {
1262 dir = xstrdup(file1);
1263 dir = make_absolute(dir, pwd);
1265 if (remote_is_dir(conn, dir) && file2 == NULL) {
1266 printf("Changing to: %s\n", dir);
1267 snprintf(cmd, sizeof cmd, "cd \"%s\"", dir);
1268 if (parse_dispatch_command(conn, cmd, &pwd, 1) != 0)
1272 snprintf(cmd, sizeof cmd, "get %s", dir);
1274 snprintf(cmd, sizeof cmd, "get %s %s", dir,
1277 err = parse_dispatch_command(conn, cmd, &pwd, 1);
1286 setvbuf(stdout, NULL, _IOLBF, 0);
1287 setvbuf(infile, NULL, _IOLBF, 0);
1297 signal(SIGINT, SIG_IGN);
1301 if (fgets(cmd, sizeof(cmd), infile) == NULL) {
1305 if (batchmode) /* Echo command */
1312 if ((line = el_gets(el, &count)) == NULL || count <= 0)
1314 history(hl, &hev, H_ENTER, line);
1315 if (strlcpy(cmd, line, sizeof(cmd)) >= sizeof(cmd)) {
1316 fprintf(stderr, "Error: input line too long\n");
1319 #endif /* USE_LIBEDIT */
1322 cp = strrchr(cmd, '\n');
1326 /* Handle user interrupts gracefully during commands */
1328 signal(SIGINT, cmd_interrupt);
1330 err = parse_dispatch_command(conn, cmd, &pwd, batchmode);
1336 /* err == 1 signifies normal "quit" exit */
1337 return (err >= 0 ? 0 : -1);
1341 connect_to_server(char *path, char **args, int *in, int *out)
1346 int pin[2], pout[2];
1348 if ((pipe(pin) == -1) || (pipe(pout) == -1))
1349 fatal("pipe: %s", strerror(errno));
1354 #else /* USE_PIPES */
1357 if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) == -1)
1358 fatal("socketpair: %s", strerror(errno));
1359 *in = *out = inout[0];
1360 c_in = c_out = inout[1];
1361 #endif /* USE_PIPES */
1363 if ((sshpid = fork()) == -1)
1364 fatal("fork: %s", strerror(errno));
1365 else if (sshpid == 0) {
1366 if ((dup2(c_in, STDIN_FILENO) == -1) ||
1367 (dup2(c_out, STDOUT_FILENO) == -1)) {
1368 fprintf(stderr, "dup2: %s\n", strerror(errno));
1377 * The underlying ssh is in the same process group, so we must
1378 * ignore SIGINT if we want to gracefully abort commands,
1379 * otherwise the signal will make it to the ssh process and
1382 signal(SIGINT, SIG_IGN);
1384 fprintf(stderr, "exec: %s: %s\n", path, strerror(errno));
1388 signal(SIGTERM, killchild);
1389 signal(SIGINT, killchild);
1390 signal(SIGHUP, killchild);
1398 extern char *__progname;
1401 "usage: %s [-1Cv] [-B buffer_size] [-b batchfile] [-F ssh_config]\n"
1402 " [-o ssh_option] [-P sftp_server_path] [-R num_requests]\n"
1403 " [-S program] [-s subsystem | sftp_server] host\n"
1404 " %s [[user@]host[:file [file]]]\n"
1405 " %s [[user@]host[:dir[/]]]\n"
1406 " %s -b batchfile [user@]host\n", __progname, __progname, __progname, __progname);
1411 main(int argc, char **argv)
1413 int in, out, ch, err;
1414 char *host, *userhost, *cp, *file2 = NULL;
1415 int debug_level = 0, sshver = 2;
1416 char *file1 = NULL, *sftp_server = NULL;
1417 char *ssh_program = _PATH_SSH_PROGRAM, *sftp_direct = NULL;
1418 LogLevel ll = SYSLOG_LEVEL_INFO;
1421 extern char *optarg;
1423 __progname = ssh_get_progname(argv[0]);
1425 addargs(&args, "ssh"); /* overwritten with ssh_program */
1426 addargs(&args, "-oForwardX11 no");
1427 addargs(&args, "-oForwardAgent no");
1428 addargs(&args, "-oClearAllForwardings yes");
1430 ll = SYSLOG_LEVEL_INFO;
1433 while ((ch = getopt(argc, argv, "1hvCo:s:S:b:B:F:P:R:")) != -1) {
1436 addargs(&args, "-C");
1439 if (debug_level < 3) {
1440 addargs(&args, "-v");
1441 ll = SYSLOG_LEVEL_DEBUG1 + debug_level;
1447 addargs(&args, "-%c%s", ch, optarg);
1451 if (sftp_server == NULL)
1452 sftp_server = _PATH_SFTP_SERVER;
1455 sftp_server = optarg;
1458 ssh_program = optarg;
1462 fatal("Batch file already specified.");
1464 /* Allow "-" as stdin */
1465 if (strcmp(optarg, "-") != 0 &&
1466 (infile = fopen(optarg, "r")) == NULL)
1467 fatal("%s (%s).", strerror(errno), optarg);
1472 sftp_direct = optarg;
1475 copy_buffer_len = strtol(optarg, &cp, 10);
1476 if (copy_buffer_len == 0 || *cp != '\0')
1477 fatal("Invalid buffer size \"%s\"", optarg);
1480 num_requests = strtol(optarg, &cp, 10);
1481 if (num_requests == 0 || *cp != '\0')
1482 fatal("Invalid number of requests \"%s\"",
1491 if (!isatty(STDERR_FILENO))
1494 log_init(argv[0], ll, SYSLOG_FACILITY_USER, 1);
1496 if (sftp_direct == NULL) {
1497 if (optind == argc || argc > (optind + 2))
1500 userhost = xstrdup(argv[optind]);
1501 file2 = argv[optind+1];
1503 if ((host = strrchr(userhost, '@')) == NULL)
1508 fprintf(stderr, "Missing username\n");
1511 addargs(&args, "-l%s",userhost);
1514 if ((cp = colon(host)) != NULL) {
1519 host = cleanhostname(host);
1521 fprintf(stderr, "Missing hostname\n");
1525 addargs(&args, "-oProtocol %d", sshver);
1527 /* no subsystem if the server-spec contains a '/' */
1528 if (sftp_server == NULL || strchr(sftp_server, '/') == NULL)
1529 addargs(&args, "-s");
1531 addargs(&args, "%s", host);
1532 addargs(&args, "%s", (sftp_server != NULL ?
1533 sftp_server : "sftp"));
1534 args.list[0] = ssh_program;
1537 fprintf(stderr, "Connecting to %s...\n", host);
1538 connect_to_server(ssh_program, args.list, &in, &out);
1541 addargs(&args, "sftp-server");
1544 fprintf(stderr, "Attaching to %s...\n", sftp_direct);
1545 connect_to_server(sftp_direct, args.list, &in, &out);
1548 err = interactive_loop(in, out, file1, file2);
1550 #if !defined(USE_PIPES)
1551 shutdown(in, SHUT_RDWR);
1552 shutdown(out, SHUT_RDWR);
1560 while (waitpid(sshpid, NULL, 0) == -1)
1562 fatal("Couldn't wait for ssh process: %s",
1565 exit(err == 0 ? 0 : 1);