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.46 2004/05/19 12:17:33 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 int remote_glob(struct sftp_conn *, const char *, int,
53 int (*)(const char *, int), glob_t *); /* proto for sftp-glob.c */
55 #ifdef HAVE___PROGNAME
56 extern char *__progname;
61 /* Separators for interactive commands */
62 #define WHITESPACE " \t\r\n"
64 /* Define what type of ls view (0 - multi-column) */
65 #define LONG_VIEW 1 /* Full view ala ls -l */
66 #define SHORT_VIEW 2 /* Single row view ala ls -1 */
68 /* Commands for interactive mode */
98 static const struct CMD cmds[] = {
101 { "chdir", I_CHDIR },
102 { "chgrp", I_CHGRP },
103 { "chmod", I_CHMOD },
104 { "chown", I_CHOWN },
111 { "lchdir", I_LCHDIR },
113 { "lmkdir", I_LMKDIR },
117 { "lumask", I_LUMASK },
118 { "mkdir", I_MKDIR },
119 { "progress", I_PROGRESS },
124 { "rename", I_RENAME },
126 { "rmdir", I_RMDIR },
127 { "symlink", I_SYMLINK },
128 { "version", I_VERSION },
134 int interactive_loop(int fd_in, int fd_out, char *file1, char *file2);
140 kill(sshpid, SIGTERM);
146 cmd_interrupt(int signo)
148 const char msg[] = "\rInterrupt \n";
150 write(STDERR_FILENO, msg, sizeof(msg) - 1);
157 printf("Available commands:\n");
158 printf("cd path Change remote directory to 'path'\n");
159 printf("lcd path Change local directory to 'path'\n");
160 printf("chgrp grp path Change group of file 'path' to 'grp'\n");
161 printf("chmod mode path Change permissions of file 'path' to 'mode'\n");
162 printf("chown own path Change owner of file 'path' to 'own'\n");
163 printf("help Display this help text\n");
164 printf("get remote-path [local-path] Download file\n");
165 printf("lls [ls-options [path]] Display local directory listing\n");
166 printf("ln oldpath newpath Symlink remote file\n");
167 printf("lmkdir path Create local directory\n");
168 printf("lpwd Print local working directory\n");
169 printf("ls [path] Display remote directory listing\n");
170 printf("lumask umask Set local umask to 'umask'\n");
171 printf("mkdir path Create remote directory\n");
172 printf("progress Toggle display of progress meter\n");
173 printf("put local-path [remote-path] Upload file\n");
174 printf("pwd Display remote working directory\n");
175 printf("exit Quit sftp\n");
176 printf("quit Quit sftp\n");
177 printf("rename oldpath newpath Rename remote file\n");
178 printf("rmdir path Remove remote directory\n");
179 printf("rm path Delete remote file\n");
180 printf("symlink oldpath newpath Symlink remote file\n");
181 printf("version Show SFTP version\n");
182 printf("!command Execute 'command' in local shell\n");
183 printf("! Escape to local shell\n");
184 printf("? Synonym for help\n");
188 local_do_shell(const char *args)
197 if ((shell = getenv("SHELL")) == NULL)
198 shell = _PATH_BSHELL;
200 if ((pid = fork()) == -1)
201 fatal("Couldn't fork: %s", strerror(errno));
204 /* XXX: child has pipe fds to ssh subproc open - issue? */
206 debug3("Executing %s -c \"%s\"", shell, args);
207 execl(shell, shell, "-c", args, (char *)NULL);
209 debug3("Executing %s", shell);
210 execl(shell, shell, (char *)NULL);
212 fprintf(stderr, "Couldn't execute \"%s\": %s\n", shell,
216 while (waitpid(pid, &status, 0) == -1)
218 fatal("Couldn't wait for child: %s", strerror(errno));
219 if (!WIFEXITED(status))
220 error("Shell exited abormally");
221 else if (WEXITSTATUS(status))
222 error("Shell exited with status %d", WEXITSTATUS(status));
226 local_do_ls(const char *args)
229 local_do_shell(_PATH_LS);
231 int len = strlen(_PATH_LS " ") + strlen(args) + 1;
232 char *buf = xmalloc(len);
234 /* XXX: quoting - rip quoting code from ftp? */
235 snprintf(buf, len, _PATH_LS " %s", args);
241 /* Strip one path (usually the pwd) from the start of another */
243 path_strip(char *path, char *strip)
248 return (xstrdup(path));
251 if (strip != NULL && strncmp(path, strip, len) == 0) {
252 if (strip[len - 1] != '/' && path[len] == '/')
254 return (xstrdup(path + len));
257 return (xstrdup(path));
261 path_append(char *p1, char *p2)
264 int len = strlen(p1) + strlen(p2) + 2;
267 strlcpy(ret, p1, len);
268 if (p1[strlen(p1) - 1] != '/')
269 strlcat(ret, "/", len);
270 strlcat(ret, p2, len);
276 make_absolute(char *p, char *pwd)
281 if (p && p[0] != '/') {
282 abs = path_append(pwd, p);
290 infer_path(const char *p, char **ifp)
294 cp = strrchr(p, '/');
301 error("Invalid path");
305 *ifp = xstrdup(cp + 1);
310 parse_getput_flags(const char **cpp, int *pflag)
312 const char *cp = *cpp;
314 /* Check for flags */
315 if (cp[0] == '-' && cp[1] && strchr(WHITESPACE, cp[2])) {
322 error("Invalid flag -%c", cp[1]);
326 *cpp = cp + strspn(cp, WHITESPACE);
333 parse_ls_flags(const char **cpp, int *lflag)
335 const char *cp = *cpp;
337 /* Check for flags */
338 if (cp++[0] == '-') {
339 for(; strchr(WHITESPACE, *cp) == NULL; cp++) {
348 error("Invalid flag -%c", *cp);
352 *cpp = cp + strspn(cp, WHITESPACE);
359 get_pathname(const char **cpp, char **path)
361 const char *cp = *cpp, *end;
365 cp += strspn(cp, WHITESPACE);
372 *path = xmalloc(strlen(cp) + 1);
374 /* Check for quoted filenames */
375 if (*cp == '\"' || *cp == '\'') {
378 /* Search for terminating quote, unescape some chars */
379 for (i = j = 0; i <= strlen(cp); i++) {
380 if (cp[i] == quot) { /* Found quote */
385 if (cp[i] == '\0') { /* End of string */
386 error("Unterminated quote");
389 if (cp[i] == '\\') { /* Escaped characters */
391 if (cp[i] != '\'' && cp[i] != '\"' &&
393 error("Bad escaped character '\%c'",
398 (*path)[j++] = cp[i];
402 error("Empty quotes");
405 *cpp = cp + i + strspn(cp + i, WHITESPACE);
407 /* Read to end of filename */
408 end = strpbrk(cp, WHITESPACE);
410 end = strchr(cp, '\0');
411 *cpp = end + strspn(end, WHITESPACE);
413 memcpy(*path, cp, end - cp);
414 (*path)[end - cp] = '\0';
429 /* XXX: report errors? */
430 if (stat(path, &sb) == -1)
433 return(sb.st_mode & S_IFDIR);
441 if (stat(path, &sb) == -1)
442 fatal("stat %s: %s", path, strerror(errno));
444 return(S_ISREG(sb.st_mode));
448 remote_is_dir(struct sftp_conn *conn, char *path)
452 /* XXX: report errors? */
453 if ((a = do_stat(conn, path, 1)) == NULL)
455 if (!(a->flags & SSH2_FILEXFER_ATTR_PERMISSIONS))
457 return(a->perm & S_IFDIR);
461 process_get(struct sftp_conn *conn, char *src, char *dst, char *pwd, int pflag)
463 char *abs_src = NULL;
464 char *abs_dst = NULL;
470 abs_src = xstrdup(src);
471 abs_src = make_absolute(abs_src, pwd);
473 memset(&g, 0, sizeof(g));
474 debug3("Looking up %s", abs_src);
475 if (remote_glob(conn, abs_src, 0, NULL, &g)) {
476 error("File \"%s\" not found.", abs_src);
481 /* If multiple matches, dst must be a directory or unspecified */
482 if (g.gl_matchc > 1 && dst && !is_dir(dst)) {
483 error("Multiple files match, but \"%s\" is not a directory",
489 for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
490 if (infer_path(g.gl_pathv[i], &tmp)) {
495 if (g.gl_matchc == 1 && dst) {
496 /* If directory specified, append filename */
498 if (infer_path(g.gl_pathv[0], &tmp)) {
502 abs_dst = path_append(dst, tmp);
505 abs_dst = xstrdup(dst);
507 abs_dst = path_append(dst, tmp);
512 printf("Fetching %s to %s\n", g.gl_pathv[i], abs_dst);
513 if (do_download(conn, g.gl_pathv[i], abs_dst, pflag) == -1)
528 process_put(struct sftp_conn *conn, char *src, char *dst, char *pwd, int pflag)
530 char *tmp_dst = NULL;
531 char *abs_dst = NULL;
538 tmp_dst = xstrdup(dst);
539 tmp_dst = make_absolute(tmp_dst, pwd);
542 memset(&g, 0, sizeof(g));
543 debug3("Looking up %s", src);
544 if (glob(src, 0, NULL, &g)) {
545 error("File \"%s\" not found.", src);
550 /* If multiple matches, dst may be directory or unspecified */
551 if (g.gl_matchc > 1 && tmp_dst && !remote_is_dir(conn, tmp_dst)) {
552 error("Multiple files match, but \"%s\" is not a directory",
558 for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
559 if (!is_reg(g.gl_pathv[i])) {
560 error("skipping non-regular file %s",
564 if (infer_path(g.gl_pathv[i], &tmp)) {
569 if (g.gl_matchc == 1 && tmp_dst) {
570 /* If directory specified, append filename */
571 if (remote_is_dir(conn, tmp_dst)) {
572 if (infer_path(g.gl_pathv[0], &tmp)) {
576 abs_dst = path_append(tmp_dst, tmp);
579 abs_dst = xstrdup(tmp_dst);
581 } else if (tmp_dst) {
582 abs_dst = path_append(tmp_dst, tmp);
585 abs_dst = make_absolute(tmp, pwd);
587 printf("Uploading %s to %s\n", g.gl_pathv[i], abs_dst);
588 if (do_upload(conn, g.gl_pathv[i], abs_dst, pflag) == -1)
602 sdirent_comp(const void *aa, const void *bb)
604 SFTP_DIRENT *a = *(SFTP_DIRENT **)aa;
605 SFTP_DIRENT *b = *(SFTP_DIRENT **)bb;
607 return (strcmp(a->filename, b->filename));
610 /* sftp ls.1 replacement for directories */
612 do_ls_dir(struct sftp_conn *conn, char *path, char *strip_path, int lflag)
614 int n, c = 1, colspace = 0, columns = 1;
617 if ((n = do_readdir(conn, path, &d)) != 0)
620 if (!(lflag & SHORT_VIEW)) {
621 int m = 0, width = 80;
625 /* Count entries for sort and find longest filename */
626 for (n = 0; d[n] != NULL; n++)
627 m = MAX(m, strlen(d[n]->filename));
629 /* Add any subpath that also needs to be counted */
630 tmp = path_strip(path, strip_path);
634 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) != -1)
637 columns = width / (m + 2);
638 columns = MAX(columns, 1);
639 colspace = width / columns;
640 colspace = MIN(colspace, width);
643 qsort(d, n, sizeof(*d), sdirent_comp);
645 for (n = 0; d[n] != NULL && !interrupted; n++) {
648 tmp = path_append(path, d[n]->filename);
649 fname = path_strip(tmp, strip_path);
652 if (lflag & LONG_VIEW) {
656 memset(&sb, 0, sizeof(sb));
657 attrib_to_stat(&d[n]->a, &sb);
658 lname = ls_file(fname, &sb, 1);
659 printf("%s\n", lname);
662 printf("%-*s", colspace, fname);
673 if (!(lflag & LONG_VIEW) && (c != 1))
676 free_sftp_dirents(d);
680 /* sftp ls.1 replacement which handles path globs */
682 do_globbed_ls(struct sftp_conn *conn, char *path, char *strip_path,
686 int i, c = 1, colspace = 0, columns = 1;
689 memset(&g, 0, sizeof(g));
691 if (remote_glob(conn, path, GLOB_MARK|GLOB_NOCHECK|GLOB_BRACE,
693 error("Can't ls: \"%s\" not found", path);
701 * If the glob returns a single match, which is the same as the
702 * input glob, and it is a directory, then just list its contents
704 if (g.gl_pathc == 1 &&
705 strncmp(path, g.gl_pathv[0], strlen(g.gl_pathv[0]) - 1) == 0) {
706 if ((a = do_lstat(conn, path, 1)) == NULL) {
710 if ((a->flags & SSH2_FILEXFER_ATTR_PERMISSIONS) &&
713 return (do_ls_dir(conn, path, strip_path, lflag));
717 if (!(lflag & SHORT_VIEW)) {
718 int m = 0, width = 80;
721 /* Count entries for sort and find longest filename */
722 for (i = 0; g.gl_pathv[i]; i++)
723 m = MAX(m, strlen(g.gl_pathv[i]));
725 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) != -1)
728 columns = width / (m + 2);
729 columns = MAX(columns, 1);
730 colspace = width / columns;
733 for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
736 fname = path_strip(g.gl_pathv[i], strip_path);
738 if (lflag & LONG_VIEW) {
743 * XXX: this is slow - 1 roundtrip per path
744 * A solution to this is to fork glob() and
745 * build a sftp specific version which keeps the
746 * attribs (which currently get thrown away)
747 * that the server returns as well as the filenames.
749 memset(&sb, 0, sizeof(sb));
750 a = do_lstat(conn, g.gl_pathv[i], 1);
752 attrib_to_stat(a, &sb);
753 lname = ls_file(fname, &sb, 1);
754 printf("%s\n", lname);
757 printf("%-*s", colspace, fname);
767 if (!(lflag & LONG_VIEW) && (c != 1))
778 parse_args(const char **cpp, int *pflag, int *lflag, int *iflag,
779 unsigned long *n_arg, char **path1, char **path2)
781 const char *cmd, *cp = *cpp;
787 /* Skip leading whitespace */
788 cp = cp + strspn(cp, WHITESPACE);
790 /* Ignore blank lines and lines which begin with comment '#' char */
791 if (*cp == '\0' || *cp == '#')
794 /* Check for leading '-' (disable error processing) */
801 /* Figure out which command we have */
802 for (i = 0; cmds[i].c; i++) {
803 int cmdlen = strlen(cmds[i].c);
805 /* Check for command followed by whitespace */
806 if (!strncasecmp(cp, cmds[i].c, cmdlen) &&
807 strchr(WHITESPACE, cp[cmdlen])) {
809 cp = cp + strspn(cp, WHITESPACE);
820 } else if (cmdnum == -1) {
821 error("Invalid command.");
825 /* Get arguments and parse flags */
826 *lflag = *pflag = *n_arg = 0;
827 *path1 = *path2 = NULL;
831 if (parse_getput_flags(&cp, pflag))
833 /* Get first pathname (mandatory) */
834 if (get_pathname(&cp, path1))
836 if (*path1 == NULL) {
837 error("You must specify at least one path after a "
841 /* Try to get second pathname (optional) */
842 if (get_pathname(&cp, path2))
847 if (get_pathname(&cp, path1))
849 if (get_pathname(&cp, path2))
851 if (!*path1 || !*path2) {
852 error("You must specify two paths after a %s "
863 /* Get pathname (mandatory) */
864 if (get_pathname(&cp, path1))
866 if (*path1 == NULL) {
867 error("You must specify a path after a %s command.",
873 if (parse_ls_flags(&cp, lflag))
875 /* Path is optional */
876 if (get_pathname(&cp, path1))
881 /* Uses the rest of the line */
889 /* Get numeric arg (mandatory) */
890 l = strtol(cp, &cp2, base);
891 if (cp2 == cp || ((l == LONG_MIN || l == LONG_MAX) &&
892 errno == ERANGE) || l < 0) {
893 error("You must supply a numeric argument "
894 "to the %s command.", cmd);
899 if (cmdnum == I_LUMASK && strchr(WHITESPACE, *cp))
901 if (cmdnum == I_LUMASK || !strchr(WHITESPACE, *cp)) {
902 error("You must supply a numeric argument "
903 "to the %s command.", cmd);
906 cp += strspn(cp, WHITESPACE);
908 /* Get pathname (mandatory) */
909 if (get_pathname(&cp, path1))
911 if (*path1 == NULL) {
912 error("You must specify a path after a %s command.",
925 fatal("Command not implemented");
933 parse_dispatch_command(struct sftp_conn *conn, const char *cmd, char **pwd,
936 char *path1, *path2, *tmp;
937 int pflag, lflag, iflag, cmdnum, i;
940 char path_buf[MAXPATHLEN];
944 path1 = path2 = NULL;
945 cmdnum = parse_args(&cmd, &pflag, &lflag, &iflag, &n_arg,
951 memset(&g, 0, sizeof(g));
953 /* Perform command */
959 /* Unrecognized command */
963 err = process_get(conn, path1, path2, *pwd, pflag);
966 err = process_put(conn, path1, path2, *pwd, pflag);
969 path1 = make_absolute(path1, *pwd);
970 path2 = make_absolute(path2, *pwd);
971 err = do_rename(conn, path1, path2);
974 path2 = make_absolute(path2, *pwd);
975 err = do_symlink(conn, path1, path2);
978 path1 = make_absolute(path1, *pwd);
979 remote_glob(conn, path1, GLOB_NOCHECK, NULL, &g);
980 for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
981 printf("Removing %s\n", g.gl_pathv[i]);
982 err = do_rm(conn, g.gl_pathv[i]);
983 if (err != 0 && err_abort)
988 path1 = make_absolute(path1, *pwd);
990 a.flags |= SSH2_FILEXFER_ATTR_PERMISSIONS;
992 err = do_mkdir(conn, path1, &a);
995 path1 = make_absolute(path1, *pwd);
996 err = do_rmdir(conn, path1);
999 path1 = make_absolute(path1, *pwd);
1000 if ((tmp = do_realpath(conn, path1)) == NULL) {
1004 if ((aa = do_stat(conn, tmp, 0)) == NULL) {
1009 if (!(aa->flags & SSH2_FILEXFER_ATTR_PERMISSIONS)) {
1010 error("Can't change directory: Can't check target");
1015 if (!S_ISDIR(aa->perm)) {
1016 error("Can't change directory: \"%s\" is not "
1017 "a directory", tmp);
1027 do_globbed_ls(conn, *pwd, *pwd, lflag);
1031 /* Strip pwd off beginning of non-absolute paths */
1036 path1 = make_absolute(path1, *pwd);
1037 err = do_globbed_ls(conn, path1, tmp, lflag);
1040 if (chdir(path1) == -1) {
1041 error("Couldn't change local directory to "
1042 "\"%s\": %s", path1, strerror(errno));
1047 if (mkdir(path1, 0777) == -1) {
1048 error("Couldn't create local directory "
1049 "\"%s\": %s", path1, strerror(errno));
1057 local_do_shell(cmd);
1061 printf("Local umask: %03lo\n", n_arg);
1064 path1 = make_absolute(path1, *pwd);
1066 a.flags |= SSH2_FILEXFER_ATTR_PERMISSIONS;
1068 remote_glob(conn, path1, GLOB_NOCHECK, NULL, &g);
1069 for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
1070 printf("Changing mode on %s\n", g.gl_pathv[i]);
1071 err = do_setstat(conn, g.gl_pathv[i], &a);
1072 if (err != 0 && err_abort)
1078 path1 = make_absolute(path1, *pwd);
1079 remote_glob(conn, path1, GLOB_NOCHECK, NULL, &g);
1080 for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
1081 if (!(aa = do_stat(conn, g.gl_pathv[i], 0))) {
1082 if (err != 0 && err_abort)
1087 if (!(aa->flags & SSH2_FILEXFER_ATTR_UIDGID)) {
1088 error("Can't get current ownership of "
1089 "remote file \"%s\"", g.gl_pathv[i]);
1090 if (err != 0 && err_abort)
1095 aa->flags &= SSH2_FILEXFER_ATTR_UIDGID;
1096 if (cmdnum == I_CHOWN) {
1097 printf("Changing owner on %s\n", g.gl_pathv[i]);
1100 printf("Changing group on %s\n", g.gl_pathv[i]);
1103 err = do_setstat(conn, g.gl_pathv[i], aa);
1104 if (err != 0 && err_abort)
1109 printf("Remote working directory: %s\n", *pwd);
1112 if (!getcwd(path_buf, sizeof(path_buf))) {
1113 error("Couldn't get local cwd: %s", strerror(errno));
1117 printf("Local working directory: %s\n", path_buf);
1120 /* Processed below */
1126 printf("SFTP protocol version %u\n", sftp_proto_version(conn));
1129 showprogress = !showprogress;
1131 printf("Progress meter enabled\n");
1133 printf("Progress meter disabled\n");
1136 fatal("%d is not implemented", cmdnum);
1146 /* If an unignored error occurs in batch mode we should abort. */
1147 if (err_abort && err != 0)
1149 else if (cmdnum == I_QUIT)
1156 interactive_loop(int fd_in, int fd_out, char *file1, char *file2)
1161 struct sftp_conn *conn;
1164 conn = do_init(fd_in, fd_out, copy_buffer_len, num_requests);
1166 fatal("Couldn't initialise connection to server");
1168 pwd = do_realpath(conn, ".");
1172 if (file1 != NULL) {
1173 dir = xstrdup(file1);
1174 dir = make_absolute(dir, pwd);
1176 if (remote_is_dir(conn, dir) && file2 == NULL) {
1177 printf("Changing to: %s\n", dir);
1178 snprintf(cmd, sizeof cmd, "cd \"%s\"", dir);
1179 if (parse_dispatch_command(conn, cmd, &pwd, 1) != 0)
1183 snprintf(cmd, sizeof cmd, "get %s", dir);
1185 snprintf(cmd, sizeof cmd, "get %s %s", dir,
1188 err = parse_dispatch_command(conn, cmd, &pwd, 1);
1197 setvbuf(stdout, NULL, _IOLBF, 0);
1198 setvbuf(infile, NULL, _IOLBF, 0);
1208 signal(SIGINT, SIG_IGN);
1212 /* XXX: use libedit */
1213 if (fgets(cmd, sizeof(cmd), infile) == NULL) {
1218 if (batchmode) /* Echo command */
1221 cp = strrchr(cmd, '\n');
1225 /* Handle user interrupts gracefully during commands */
1227 signal(SIGINT, cmd_interrupt);
1229 err = parse_dispatch_command(conn, cmd, &pwd, batchmode);
1235 /* err == 1 signifies normal "quit" exit */
1236 return (err >= 0 ? 0 : -1);
1240 connect_to_server(char *path, char **args, int *in, int *out)
1245 int pin[2], pout[2];
1247 if ((pipe(pin) == -1) || (pipe(pout) == -1))
1248 fatal("pipe: %s", strerror(errno));
1253 #else /* USE_PIPES */
1256 if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) == -1)
1257 fatal("socketpair: %s", strerror(errno));
1258 *in = *out = inout[0];
1259 c_in = c_out = inout[1];
1260 #endif /* USE_PIPES */
1262 if ((sshpid = fork()) == -1)
1263 fatal("fork: %s", strerror(errno));
1264 else if (sshpid == 0) {
1265 if ((dup2(c_in, STDIN_FILENO) == -1) ||
1266 (dup2(c_out, STDOUT_FILENO) == -1)) {
1267 fprintf(stderr, "dup2: %s\n", strerror(errno));
1276 * The underlying ssh is in the same process group, so we must
1277 * ignore SIGINT if we want to gracefully abort commands,
1278 * otherwise the signal will make it to the ssh process and
1281 signal(SIGINT, SIG_IGN);
1283 fprintf(stderr, "exec: %s: %s\n", path, strerror(errno));
1287 signal(SIGTERM, killchild);
1288 signal(SIGINT, killchild);
1289 signal(SIGHUP, killchild);
1297 extern char *__progname;
1300 "usage: %s [-1Cv] [-B buffer_size] [-b batchfile] [-F ssh_config]\n"
1301 " [-o ssh_option] [-P sftp_server_path] [-R num_requests]\n"
1302 " [-S program] [-s subsystem | sftp_server] host\n"
1303 " %s [[user@]host[:file [file]]]\n"
1304 " %s [[user@]host[:dir[/]]]\n"
1305 " %s -b batchfile [user@]host\n", __progname, __progname, __progname, __progname);
1310 main(int argc, char **argv)
1312 int in, out, ch, err;
1313 char *host, *userhost, *cp, *file2;
1314 int debug_level = 0, sshver = 2;
1315 char *file1 = NULL, *sftp_server = NULL;
1316 char *ssh_program = _PATH_SSH_PROGRAM, *sftp_direct = NULL;
1317 LogLevel ll = SYSLOG_LEVEL_INFO;
1320 extern char *optarg;
1322 __progname = ssh_get_progname(argv[0]);
1324 addargs(&args, "ssh"); /* overwritten with ssh_program */
1325 addargs(&args, "-oForwardX11 no");
1326 addargs(&args, "-oForwardAgent no");
1327 addargs(&args, "-oClearAllForwardings yes");
1329 ll = SYSLOG_LEVEL_INFO;
1332 while ((ch = getopt(argc, argv, "1hvCo:s:S:b:B:F:P:R:")) != -1) {
1335 addargs(&args, "-C");
1338 if (debug_level < 3) {
1339 addargs(&args, "-v");
1340 ll = SYSLOG_LEVEL_DEBUG1 + debug_level;
1346 addargs(&args, "-%c%s", ch, optarg);
1350 if (sftp_server == NULL)
1351 sftp_server = _PATH_SFTP_SERVER;
1354 sftp_server = optarg;
1357 ssh_program = optarg;
1361 fatal("Batch file already specified.");
1363 /* Allow "-" as stdin */
1364 if (strcmp(optarg, "-") != 0 &&
1365 (infile = fopen(optarg, "r")) == NULL)
1366 fatal("%s (%s).", strerror(errno), optarg);
1371 sftp_direct = optarg;
1374 copy_buffer_len = strtol(optarg, &cp, 10);
1375 if (copy_buffer_len == 0 || *cp != '\0')
1376 fatal("Invalid buffer size \"%s\"", optarg);
1379 num_requests = strtol(optarg, &cp, 10);
1380 if (num_requests == 0 || *cp != '\0')
1381 fatal("Invalid number of requests \"%s\"",
1390 if (!isatty(STDERR_FILENO))
1393 log_init(argv[0], ll, SYSLOG_FACILITY_USER, 1);
1395 if (sftp_direct == NULL) {
1396 if (optind == argc || argc > (optind + 2))
1399 userhost = xstrdup(argv[optind]);
1400 file2 = argv[optind+1];
1402 if ((host = strrchr(userhost, '@')) == NULL)
1407 fprintf(stderr, "Missing username\n");
1410 addargs(&args, "-l%s",userhost);
1413 if ((cp = colon(host)) != NULL) {
1418 host = cleanhostname(host);
1420 fprintf(stderr, "Missing hostname\n");
1424 addargs(&args, "-oProtocol %d", sshver);
1426 /* no subsystem if the server-spec contains a '/' */
1427 if (sftp_server == NULL || strchr(sftp_server, '/') == NULL)
1428 addargs(&args, "-s");
1430 addargs(&args, "%s", host);
1431 addargs(&args, "%s", (sftp_server != NULL ?
1432 sftp_server : "sftp"));
1433 args.list[0] = ssh_program;
1436 fprintf(stderr, "Connecting to %s...\n", host);
1437 connect_to_server(ssh_program, args.list, &in, &out);
1440 addargs(&args, "sftp-server");
1443 fprintf(stderr, "Attaching to %s...\n", sftp_direct);
1444 connect_to_server(sftp_direct, args.list, &in, &out);
1447 err = interactive_loop(in, out, file1, file2);
1449 #if !defined(USE_PIPES)
1450 shutdown(in, SHUT_RDWR);
1451 shutdown(out, SHUT_RDWR);
1459 while (waitpid(sshpid, NULL, 0) == -1)
1461 fatal("Couldn't wait for ssh process: %s",
1464 exit(err == 0 ? 0 : 1);