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.45 2004/03/03 09:31:20 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 int remote_glob(struct sftp_conn
*, const char *, int,
50 int (*)(const char *, int), glob_t
*); /* proto for sftp-glob.c */
52 #ifdef HAVE___PROGNAME
53 extern char *__progname
;
58 /* Separators for interactive commands */
59 #define WHITESPACE " \t\r\n"
61 /* Define what type of ls view (0 - multi-column) */
62 #define LONG_VIEW 1 /* Full view ala ls -l */
63 #define SHORT_VIEW 2 /* Single row view ala ls -1 */
65 /* Commands for interactive mode */
95 static const struct CMD cmds
[] = {
100 { "chmod", I_CHMOD
},
101 { "chown", I_CHOWN
},
108 { "lchdir", I_LCHDIR
},
110 { "lmkdir", I_LMKDIR
},
114 { "lumask", I_LUMASK
},
115 { "mkdir", I_MKDIR
},
116 { "progress", I_PROGRESS
},
121 { "rename", I_RENAME
},
123 { "rmdir", I_RMDIR
},
124 { "symlink", I_SYMLINK
},
125 { "version", I_VERSION
},
131 int interactive_loop(int fd_in
, int fd_out
, char *file1
, char *file2
);
136 printf("Available commands:\n");
137 printf("cd path Change remote directory to 'path'\n");
138 printf("lcd path Change local directory to 'path'\n");
139 printf("chgrp grp path Change group of file 'path' to 'grp'\n");
140 printf("chmod mode path Change permissions of file 'path' to 'mode'\n");
141 printf("chown own path Change owner of file 'path' to 'own'\n");
142 printf("help Display this help text\n");
143 printf("get remote-path [local-path] Download file\n");
144 printf("lls [ls-options [path]] Display local directory listing\n");
145 printf("ln oldpath newpath Symlink remote file\n");
146 printf("lmkdir path Create local directory\n");
147 printf("lpwd Print local working directory\n");
148 printf("ls [path] Display remote directory listing\n");
149 printf("lumask umask Set local umask to 'umask'\n");
150 printf("mkdir path Create remote directory\n");
151 printf("progress Toggle display of progress meter\n");
152 printf("put local-path [remote-path] Upload file\n");
153 printf("pwd Display remote working directory\n");
154 printf("exit Quit sftp\n");
155 printf("quit Quit sftp\n");
156 printf("rename oldpath newpath Rename remote file\n");
157 printf("rmdir path Remove remote directory\n");
158 printf("rm path Delete remote file\n");
159 printf("symlink oldpath newpath Symlink remote file\n");
160 printf("version Show SFTP version\n");
161 printf("!command Execute 'command' in local shell\n");
162 printf("! Escape to local shell\n");
163 printf("? Synonym for help\n");
167 local_do_shell(const char *args
)
176 if ((shell
= getenv("SHELL")) == NULL
)
177 shell
= _PATH_BSHELL
;
179 if ((pid
= fork()) == -1)
180 fatal("Couldn't fork: %s", strerror(errno
));
183 /* XXX: child has pipe fds to ssh subproc open - issue? */
185 debug3("Executing %s -c \"%s\"", shell
, args
);
186 execl(shell
, shell
, "-c", args
, (char *)NULL
);
188 debug3("Executing %s", shell
);
189 execl(shell
, shell
, (char *)NULL
);
191 fprintf(stderr
, "Couldn't execute \"%s\": %s\n", shell
,
195 while (waitpid(pid
, &status
, 0) == -1)
197 fatal("Couldn't wait for child: %s", strerror(errno
));
198 if (!WIFEXITED(status
))
199 error("Shell exited abormally");
200 else if (WEXITSTATUS(status
))
201 error("Shell exited with status %d", WEXITSTATUS(status
));
205 local_do_ls(const char *args
)
208 local_do_shell(_PATH_LS
);
210 int len
= strlen(_PATH_LS
" ") + strlen(args
) + 1;
211 char *buf
= xmalloc(len
);
213 /* XXX: quoting - rip quoting code from ftp? */
214 snprintf(buf
, len
, _PATH_LS
" %s", args
);
220 /* Strip one path (usually the pwd) from the start of another */
222 path_strip(char *path
, char *strip
)
227 return (xstrdup(path
));
230 if (strip
!= NULL
&& strncmp(path
, strip
, len
) == 0) {
231 if (strip
[len
- 1] != '/' && path
[len
] == '/')
233 return (xstrdup(path
+ len
));
236 return (xstrdup(path
));
240 path_append(char *p1
, char *p2
)
243 int len
= strlen(p1
) + strlen(p2
) + 2;
246 strlcpy(ret
, p1
, len
);
247 if (p1
[strlen(p1
) - 1] != '/')
248 strlcat(ret
, "/", len
);
249 strlcat(ret
, p2
, len
);
255 make_absolute(char *p
, char *pwd
)
260 if (p
&& p
[0] != '/') {
261 abs
= path_append(pwd
, p
);
269 infer_path(const char *p
, char **ifp
)
273 cp
= strrchr(p
, '/');
280 error("Invalid path");
284 *ifp
= xstrdup(cp
+ 1);
289 parse_getput_flags(const char **cpp
, int *pflag
)
291 const char *cp
= *cpp
;
293 /* Check for flags */
294 if (cp
[0] == '-' && cp
[1] && strchr(WHITESPACE
, cp
[2])) {
301 error("Invalid flag -%c", cp
[1]);
305 *cpp
= cp
+ strspn(cp
, WHITESPACE
);
312 parse_ls_flags(const char **cpp
, int *lflag
)
314 const char *cp
= *cpp
;
316 /* Check for flags */
317 if (cp
++[0] == '-') {
318 for(; strchr(WHITESPACE
, *cp
) == NULL
; cp
++) {
327 error("Invalid flag -%c", *cp
);
331 *cpp
= cp
+ strspn(cp
, WHITESPACE
);
338 get_pathname(const char **cpp
, char **path
)
340 const char *cp
= *cpp
, *end
;
344 cp
+= strspn(cp
, WHITESPACE
);
351 *path
= xmalloc(strlen(cp
) + 1);
353 /* Check for quoted filenames */
354 if (*cp
== '\"' || *cp
== '\'') {
357 /* Search for terminating quote, unescape some chars */
358 for (i
= j
= 0; i
<= strlen(cp
); i
++) {
359 if (cp
[i
] == quot
) { /* Found quote */
364 if (cp
[i
] == '\0') { /* End of string */
365 error("Unterminated quote");
368 if (cp
[i
] == '\\') { /* Escaped characters */
370 if (cp
[i
] != '\'' && cp
[i
] != '\"' &&
372 error("Bad escaped character '\%c'",
377 (*path
)[j
++] = cp
[i
];
381 error("Empty quotes");
384 *cpp
= cp
+ i
+ strspn(cp
+ i
, WHITESPACE
);
386 /* Read to end of filename */
387 end
= strpbrk(cp
, WHITESPACE
);
389 end
= strchr(cp
, '\0');
390 *cpp
= end
+ strspn(end
, WHITESPACE
);
392 memcpy(*path
, cp
, end
- cp
);
393 (*path
)[end
- cp
] = '\0';
408 /* XXX: report errors? */
409 if (stat(path
, &sb
) == -1)
412 return(sb
.st_mode
& S_IFDIR
);
420 if (stat(path
, &sb
) == -1)
421 fatal("stat %s: %s", path
, strerror(errno
));
423 return(S_ISREG(sb
.st_mode
));
427 remote_is_dir(struct sftp_conn
*conn
, char *path
)
431 /* XXX: report errors? */
432 if ((a
= do_stat(conn
, path
, 1)) == NULL
)
434 if (!(a
->flags
& SSH2_FILEXFER_ATTR_PERMISSIONS
))
436 return(a
->perm
& S_IFDIR
);
440 process_get(struct sftp_conn
*conn
, char *src
, char *dst
, char *pwd
, int pflag
)
442 char *abs_src
= NULL
;
443 char *abs_dst
= NULL
;
449 abs_src
= xstrdup(src
);
450 abs_src
= make_absolute(abs_src
, pwd
);
452 memset(&g
, 0, sizeof(g
));
453 debug3("Looking up %s", abs_src
);
454 if (remote_glob(conn
, abs_src
, 0, NULL
, &g
)) {
455 error("File \"%s\" not found.", abs_src
);
460 /* If multiple matches, dst must be a directory or unspecified */
461 if (g
.gl_matchc
> 1 && dst
&& !is_dir(dst
)) {
462 error("Multiple files match, but \"%s\" is not a directory",
468 for (i
= 0; g
.gl_pathv
[i
]; i
++) {
469 if (infer_path(g
.gl_pathv
[i
], &tmp
)) {
474 if (g
.gl_matchc
== 1 && dst
) {
475 /* If directory specified, append filename */
477 if (infer_path(g
.gl_pathv
[0], &tmp
)) {
481 abs_dst
= path_append(dst
, tmp
);
484 abs_dst
= xstrdup(dst
);
486 abs_dst
= path_append(dst
, tmp
);
491 printf("Fetching %s to %s\n", g
.gl_pathv
[i
], abs_dst
);
492 if (do_download(conn
, g
.gl_pathv
[i
], abs_dst
, pflag
) == -1)
507 process_put(struct sftp_conn
*conn
, char *src
, char *dst
, char *pwd
, int pflag
)
509 char *tmp_dst
= NULL
;
510 char *abs_dst
= NULL
;
517 tmp_dst
= xstrdup(dst
);
518 tmp_dst
= make_absolute(tmp_dst
, pwd
);
521 memset(&g
, 0, sizeof(g
));
522 debug3("Looking up %s", src
);
523 if (glob(src
, 0, NULL
, &g
)) {
524 error("File \"%s\" not found.", src
);
529 /* If multiple matches, dst may be directory or unspecified */
530 if (g
.gl_matchc
> 1 && tmp_dst
&& !remote_is_dir(conn
, tmp_dst
)) {
531 error("Multiple files match, but \"%s\" is not a directory",
537 for (i
= 0; g
.gl_pathv
[i
]; i
++) {
538 if (!is_reg(g
.gl_pathv
[i
])) {
539 error("skipping non-regular file %s",
543 if (infer_path(g
.gl_pathv
[i
], &tmp
)) {
548 if (g
.gl_matchc
== 1 && tmp_dst
) {
549 /* If directory specified, append filename */
550 if (remote_is_dir(conn
, tmp_dst
)) {
551 if (infer_path(g
.gl_pathv
[0], &tmp
)) {
555 abs_dst
= path_append(tmp_dst
, tmp
);
558 abs_dst
= xstrdup(tmp_dst
);
560 } else if (tmp_dst
) {
561 abs_dst
= path_append(tmp_dst
, tmp
);
564 abs_dst
= make_absolute(tmp
, pwd
);
566 printf("Uploading %s to %s\n", g
.gl_pathv
[i
], abs_dst
);
567 if (do_upload(conn
, g
.gl_pathv
[i
], abs_dst
, pflag
) == -1)
581 sdirent_comp(const void *aa
, const void *bb
)
583 SFTP_DIRENT
*a
= *(SFTP_DIRENT
**)aa
;
584 SFTP_DIRENT
*b
= *(SFTP_DIRENT
**)bb
;
586 return (strcmp(a
->filename
, b
->filename
));
589 /* sftp ls.1 replacement for directories */
591 do_ls_dir(struct sftp_conn
*conn
, char *path
, char *strip_path
, int lflag
)
593 int n
, c
= 1, colspace
= 0, columns
= 1;
596 if ((n
= do_readdir(conn
, path
, &d
)) != 0)
599 if (!(lflag
& SHORT_VIEW
)) {
600 int m
= 0, width
= 80;
604 /* Count entries for sort and find longest filename */
605 for (n
= 0; d
[n
] != NULL
; n
++)
606 m
= MAX(m
, strlen(d
[n
]->filename
));
608 /* Add any subpath that also needs to be counted */
609 tmp
= path_strip(path
, strip_path
);
613 if (ioctl(fileno(stdin
), TIOCGWINSZ
, &ws
) != -1)
616 columns
= width
/ (m
+ 2);
617 columns
= MAX(columns
, 1);
618 colspace
= width
/ columns
;
619 colspace
= MIN(colspace
, width
);
622 qsort(d
, n
, sizeof(*d
), sdirent_comp
);
624 for (n
= 0; d
[n
] != NULL
; n
++) {
627 tmp
= path_append(path
, d
[n
]->filename
);
628 fname
= path_strip(tmp
, strip_path
);
631 if (lflag
& LONG_VIEW
) {
635 memset(&sb
, 0, sizeof(sb
));
636 attrib_to_stat(&d
[n
]->a
, &sb
);
637 lname
= ls_file(fname
, &sb
, 1);
638 printf("%s\n", lname
);
641 printf("%-*s", colspace
, fname
);
652 if (!(lflag
& LONG_VIEW
) && (c
!= 1))
655 free_sftp_dirents(d
);
659 /* sftp ls.1 replacement which handles path globs */
661 do_globbed_ls(struct sftp_conn
*conn
, char *path
, char *strip_path
,
665 int i
, c
= 1, colspace
= 0, columns
= 1;
668 memset(&g
, 0, sizeof(g
));
670 if (remote_glob(conn
, path
, GLOB_MARK
|GLOB_NOCHECK
|GLOB_BRACE
,
672 error("Can't ls: \"%s\" not found", path
);
677 * If the glob returns a single match, which is the same as the
678 * input glob, and it is a directory, then just list its contents
680 if (g
.gl_pathc
== 1 &&
681 strncmp(path
, g
.gl_pathv
[0], strlen(g
.gl_pathv
[0]) - 1) == 0) {
682 if ((a
= do_lstat(conn
, path
, 1)) == NULL
) {
686 if ((a
->flags
& SSH2_FILEXFER_ATTR_PERMISSIONS
) &&
689 return (do_ls_dir(conn
, path
, strip_path
, lflag
));
693 if (!(lflag
& SHORT_VIEW
)) {
694 int m
= 0, width
= 80;
697 /* Count entries for sort and find longest filename */
698 for (i
= 0; g
.gl_pathv
[i
]; i
++)
699 m
= MAX(m
, strlen(g
.gl_pathv
[i
]));
701 if (ioctl(fileno(stdin
), TIOCGWINSZ
, &ws
) != -1)
704 columns
= width
/ (m
+ 2);
705 columns
= MAX(columns
, 1);
706 colspace
= width
/ columns
;
709 for (i
= 0; g
.gl_pathv
[i
]; i
++) {
712 fname
= path_strip(g
.gl_pathv
[i
], strip_path
);
714 if (lflag
& LONG_VIEW
) {
719 * XXX: this is slow - 1 roundtrip per path
720 * A solution to this is to fork glob() and
721 * build a sftp specific version which keeps the
722 * attribs (which currently get thrown away)
723 * that the server returns as well as the filenames.
725 memset(&sb
, 0, sizeof(sb
));
726 a
= do_lstat(conn
, g
.gl_pathv
[i
], 1);
728 attrib_to_stat(a
, &sb
);
729 lname
= ls_file(fname
, &sb
, 1);
730 printf("%s\n", lname
);
733 printf("%-*s", colspace
, fname
);
743 if (!(lflag
& LONG_VIEW
) && (c
!= 1))
753 parse_args(const char **cpp
, int *pflag
, int *lflag
, int *iflag
,
754 unsigned long *n_arg
, char **path1
, char **path2
)
756 const char *cmd
, *cp
= *cpp
;
762 /* Skip leading whitespace */
763 cp
= cp
+ strspn(cp
, WHITESPACE
);
765 /* Ignore blank lines and lines which begin with comment '#' char */
766 if (*cp
== '\0' || *cp
== '#')
769 /* Check for leading '-' (disable error processing) */
776 /* Figure out which command we have */
777 for (i
= 0; cmds
[i
].c
; i
++) {
778 int cmdlen
= strlen(cmds
[i
].c
);
780 /* Check for command followed by whitespace */
781 if (!strncasecmp(cp
, cmds
[i
].c
, cmdlen
) &&
782 strchr(WHITESPACE
, cp
[cmdlen
])) {
784 cp
= cp
+ strspn(cp
, WHITESPACE
);
795 } else if (cmdnum
== -1) {
796 error("Invalid command.");
800 /* Get arguments and parse flags */
801 *lflag
= *pflag
= *n_arg
= 0;
802 *path1
= *path2
= NULL
;
806 if (parse_getput_flags(&cp
, pflag
))
808 /* Get first pathname (mandatory) */
809 if (get_pathname(&cp
, path1
))
811 if (*path1
== NULL
) {
812 error("You must specify at least one path after a "
816 /* Try to get second pathname (optional) */
817 if (get_pathname(&cp
, path2
))
822 if (get_pathname(&cp
, path1
))
824 if (get_pathname(&cp
, path2
))
826 if (!*path1
|| !*path2
) {
827 error("You must specify two paths after a %s "
838 /* Get pathname (mandatory) */
839 if (get_pathname(&cp
, path1
))
841 if (*path1
== NULL
) {
842 error("You must specify a path after a %s command.",
848 if (parse_ls_flags(&cp
, lflag
))
850 /* Path is optional */
851 if (get_pathname(&cp
, path1
))
856 /* Uses the rest of the line */
864 /* Get numeric arg (mandatory) */
865 l
= strtol(cp
, &cp2
, base
);
866 if (cp2
== cp
|| ((l
== LONG_MIN
|| l
== LONG_MAX
) &&
867 errno
== ERANGE
) || l
< 0) {
868 error("You must supply a numeric argument "
869 "to the %s command.", cmd
);
874 if (cmdnum
== I_LUMASK
&& strchr(WHITESPACE
, *cp
))
876 if (cmdnum
== I_LUMASK
|| !strchr(WHITESPACE
, *cp
)) {
877 error("You must supply a numeric argument "
878 "to the %s command.", cmd
);
881 cp
+= strspn(cp
, WHITESPACE
);
883 /* Get pathname (mandatory) */
884 if (get_pathname(&cp
, path1
))
886 if (*path1
== NULL
) {
887 error("You must specify a path after a %s command.",
900 fatal("Command not implemented");
908 parse_dispatch_command(struct sftp_conn
*conn
, const char *cmd
, char **pwd
,
911 char *path1
, *path2
, *tmp
;
912 int pflag
, lflag
, iflag
, cmdnum
, i
;
915 char path_buf
[MAXPATHLEN
];
919 path1
= path2
= NULL
;
920 cmdnum
= parse_args(&cmd
, &pflag
, &lflag
, &iflag
, &n_arg
,
926 memset(&g
, 0, sizeof(g
));
928 /* Perform command */
934 /* Unrecognized command */
938 err
= process_get(conn
, path1
, path2
, *pwd
, pflag
);
941 err
= process_put(conn
, path1
, path2
, *pwd
, pflag
);
944 path1
= make_absolute(path1
, *pwd
);
945 path2
= make_absolute(path2
, *pwd
);
946 err
= do_rename(conn
, path1
, path2
);
949 path2
= make_absolute(path2
, *pwd
);
950 err
= do_symlink(conn
, path1
, path2
);
953 path1
= make_absolute(path1
, *pwd
);
954 remote_glob(conn
, path1
, GLOB_NOCHECK
, NULL
, &g
);
955 for (i
= 0; g
.gl_pathv
[i
]; i
++) {
956 printf("Removing %s\n", g
.gl_pathv
[i
]);
957 err
= do_rm(conn
, g
.gl_pathv
[i
]);
958 if (err
!= 0 && err_abort
)
963 path1
= make_absolute(path1
, *pwd
);
965 a
.flags
|= SSH2_FILEXFER_ATTR_PERMISSIONS
;
967 err
= do_mkdir(conn
, path1
, &a
);
970 path1
= make_absolute(path1
, *pwd
);
971 err
= do_rmdir(conn
, path1
);
974 path1
= make_absolute(path1
, *pwd
);
975 if ((tmp
= do_realpath(conn
, path1
)) == NULL
) {
979 if ((aa
= do_stat(conn
, tmp
, 0)) == NULL
) {
984 if (!(aa
->flags
& SSH2_FILEXFER_ATTR_PERMISSIONS
)) {
985 error("Can't change directory: Can't check target");
990 if (!S_ISDIR(aa
->perm
)) {
991 error("Can't change directory: \"%s\" is not "
1002 do_globbed_ls(conn
, *pwd
, *pwd
, lflag
);
1006 /* Strip pwd off beginning of non-absolute paths */
1011 path1
= make_absolute(path1
, *pwd
);
1012 err
= do_globbed_ls(conn
, path1
, tmp
, lflag
);
1015 if (chdir(path1
) == -1) {
1016 error("Couldn't change local directory to "
1017 "\"%s\": %s", path1
, strerror(errno
));
1022 if (mkdir(path1
, 0777) == -1) {
1023 error("Couldn't create local directory "
1024 "\"%s\": %s", path1
, strerror(errno
));
1032 local_do_shell(cmd
);
1036 printf("Local umask: %03lo\n", n_arg
);
1039 path1
= make_absolute(path1
, *pwd
);
1041 a
.flags
|= SSH2_FILEXFER_ATTR_PERMISSIONS
;
1043 remote_glob(conn
, path1
, GLOB_NOCHECK
, NULL
, &g
);
1044 for (i
= 0; g
.gl_pathv
[i
]; i
++) {
1045 printf("Changing mode on %s\n", g
.gl_pathv
[i
]);
1046 err
= do_setstat(conn
, g
.gl_pathv
[i
], &a
);
1047 if (err
!= 0 && err_abort
)
1053 path1
= make_absolute(path1
, *pwd
);
1054 remote_glob(conn
, path1
, GLOB_NOCHECK
, NULL
, &g
);
1055 for (i
= 0; g
.gl_pathv
[i
]; i
++) {
1056 if (!(aa
= do_stat(conn
, g
.gl_pathv
[i
], 0))) {
1057 if (err
!= 0 && err_abort
)
1062 if (!(aa
->flags
& SSH2_FILEXFER_ATTR_UIDGID
)) {
1063 error("Can't get current ownership of "
1064 "remote file \"%s\"", g
.gl_pathv
[i
]);
1065 if (err
!= 0 && err_abort
)
1070 aa
->flags
&= SSH2_FILEXFER_ATTR_UIDGID
;
1071 if (cmdnum
== I_CHOWN
) {
1072 printf("Changing owner on %s\n", g
.gl_pathv
[i
]);
1075 printf("Changing group on %s\n", g
.gl_pathv
[i
]);
1078 err
= do_setstat(conn
, g
.gl_pathv
[i
], aa
);
1079 if (err
!= 0 && err_abort
)
1084 printf("Remote working directory: %s\n", *pwd
);
1087 if (!getcwd(path_buf
, sizeof(path_buf
))) {
1088 error("Couldn't get local cwd: %s", strerror(errno
));
1092 printf("Local working directory: %s\n", path_buf
);
1095 /* Processed below */
1101 printf("SFTP protocol version %u\n", sftp_proto_version(conn
));
1104 showprogress
= !showprogress
;
1106 printf("Progress meter enabled\n");
1108 printf("Progress meter disabled\n");
1111 fatal("%d is not implemented", cmdnum
);
1121 /* If an unignored error occurs in batch mode we should abort. */
1122 if (err_abort
&& err
!= 0)
1124 else if (cmdnum
== I_QUIT
)
1131 interactive_loop(int fd_in
, int fd_out
, char *file1
, char *file2
)
1136 struct sftp_conn
*conn
;
1139 conn
= do_init(fd_in
, fd_out
, copy_buffer_len
, num_requests
);
1141 fatal("Couldn't initialise connection to server");
1143 pwd
= do_realpath(conn
, ".");
1147 if (file1
!= NULL
) {
1148 dir
= xstrdup(file1
);
1149 dir
= make_absolute(dir
, pwd
);
1151 if (remote_is_dir(conn
, dir
) && file2
== NULL
) {
1152 printf("Changing to: %s\n", dir
);
1153 snprintf(cmd
, sizeof cmd
, "cd \"%s\"", dir
);
1154 if (parse_dispatch_command(conn
, cmd
, &pwd
, 1) != 0)
1158 snprintf(cmd
, sizeof cmd
, "get %s", dir
);
1160 snprintf(cmd
, sizeof cmd
, "get %s %s", dir
,
1163 err
= parse_dispatch_command(conn
, cmd
, &pwd
, 1);
1172 setvbuf(stdout
, NULL
, _IOLBF
, 0);
1173 setvbuf(infile
, NULL
, _IOLBF
, 0);
1185 /* XXX: use libedit */
1186 if (fgets(cmd
, sizeof(cmd
), infile
) == NULL
) {
1191 if (batchmode
) /* Echo command */
1194 cp
= strrchr(cmd
, '\n');
1198 err
= parse_dispatch_command(conn
, cmd
, &pwd
, batchmode
);
1204 /* err == 1 signifies normal "quit" exit */
1205 return (err
>= 0 ? 0 : -1);
1209 killchild(int signo
)
1212 kill(sshpid
, signo
);
1218 connect_to_server(char *path
, char **args
, int *in
, int *out
)
1223 int pin
[2], pout
[2];
1225 if ((pipe(pin
) == -1) || (pipe(pout
) == -1))
1226 fatal("pipe: %s", strerror(errno
));
1231 #else /* USE_PIPES */
1234 if (socketpair(AF_UNIX
, SOCK_STREAM
, 0, inout
) == -1)
1235 fatal("socketpair: %s", strerror(errno
));
1236 *in
= *out
= inout
[0];
1237 c_in
= c_out
= inout
[1];
1238 #endif /* USE_PIPES */
1240 if ((sshpid
= fork()) == -1)
1241 fatal("fork: %s", strerror(errno
));
1242 else if (sshpid
== 0) {
1243 if ((dup2(c_in
, STDIN_FILENO
) == -1) ||
1244 (dup2(c_out
, STDOUT_FILENO
) == -1)) {
1245 fprintf(stderr
, "dup2: %s\n", strerror(errno
));
1253 fprintf(stderr
, "exec: %s: %s\n", path
, strerror(errno
));
1257 signal(SIGTERM
, killchild
);
1258 signal(SIGINT
, killchild
);
1259 signal(SIGHUP
, killchild
);
1267 extern char *__progname
;
1270 "usage: %s [-1Cv] [-B buffer_size] [-b batchfile] [-F ssh_config]\n"
1271 " [-o ssh_option] [-P sftp_server_path] [-R num_requests]\n"
1272 " [-S program] [-s subsystem | sftp_server] host\n"
1273 " %s [[user@]host[:file [file]]]\n"
1274 " %s [[user@]host[:dir[/]]]\n"
1275 " %s -b batchfile [user@]host\n", __progname
, __progname
, __progname
, __progname
);
1280 main(int argc
, char **argv
)
1282 int in
, out
, ch
, err
;
1283 char *host
, *userhost
, *cp
, *file2
;
1284 int debug_level
= 0, sshver
= 2;
1285 char *file1
= NULL
, *sftp_server
= NULL
;
1286 char *ssh_program
= _PATH_SSH_PROGRAM
, *sftp_direct
= NULL
;
1287 LogLevel ll
= SYSLOG_LEVEL_INFO
;
1290 extern char *optarg
;
1292 __progname
= ssh_get_progname(argv
[0]);
1294 addargs(&args
, "ssh"); /* overwritten with ssh_program */
1295 addargs(&args
, "-oForwardX11 no");
1296 addargs(&args
, "-oForwardAgent no");
1297 addargs(&args
, "-oClearAllForwardings yes");
1299 ll
= SYSLOG_LEVEL_INFO
;
1302 while ((ch
= getopt(argc
, argv
, "1hvCo:s:S:b:B:F:P:R:")) != -1) {
1305 addargs(&args
, "-C");
1308 if (debug_level
< 3) {
1309 addargs(&args
, "-v");
1310 ll
= SYSLOG_LEVEL_DEBUG1
+ debug_level
;
1316 addargs(&args
, "-%c%s", ch
, optarg
);
1320 if (sftp_server
== NULL
)
1321 sftp_server
= _PATH_SFTP_SERVER
;
1324 sftp_server
= optarg
;
1327 ssh_program
= optarg
;
1331 fatal("Batch file already specified.");
1333 /* Allow "-" as stdin */
1334 if (strcmp(optarg
, "-") != 0 &&
1335 (infile
= fopen(optarg
, "r")) == NULL
)
1336 fatal("%s (%s).", strerror(errno
), optarg
);
1341 sftp_direct
= optarg
;
1344 copy_buffer_len
= strtol(optarg
, &cp
, 10);
1345 if (copy_buffer_len
== 0 || *cp
!= '\0')
1346 fatal("Invalid buffer size \"%s\"", optarg
);
1349 num_requests
= strtol(optarg
, &cp
, 10);
1350 if (num_requests
== 0 || *cp
!= '\0')
1351 fatal("Invalid number of requests \"%s\"",
1360 if (!isatty(STDERR_FILENO
))
1363 log_init(argv
[0], ll
, SYSLOG_FACILITY_USER
, 1);
1365 if (sftp_direct
== NULL
) {
1366 if (optind
== argc
|| argc
> (optind
+ 2))
1369 userhost
= xstrdup(argv
[optind
]);
1370 file2
= argv
[optind
+1];
1372 if ((host
= strrchr(userhost
, '@')) == NULL
)
1377 fprintf(stderr
, "Missing username\n");
1380 addargs(&args
, "-l%s",userhost
);
1383 if ((cp
= colon(host
)) != NULL
) {
1388 host
= cleanhostname(host
);
1390 fprintf(stderr
, "Missing hostname\n");
1394 addargs(&args
, "-oProtocol %d", sshver
);
1396 /* no subsystem if the server-spec contains a '/' */
1397 if (sftp_server
== NULL
|| strchr(sftp_server
, '/') == NULL
)
1398 addargs(&args
, "-s");
1400 addargs(&args
, "%s", host
);
1401 addargs(&args
, "%s", (sftp_server
!= NULL
?
1402 sftp_server
: "sftp"));
1403 args
.list
[0] = ssh_program
;
1406 fprintf(stderr
, "Connecting to %s...\n", host
);
1407 connect_to_server(ssh_program
, args
.list
, &in
, &out
);
1410 addargs(&args
, "sftp-server");
1413 fprintf(stderr
, "Attaching to %s...\n", sftp_direct
);
1414 connect_to_server(sftp_direct
, args
.list
, &in
, &out
);
1417 err
= interactive_loop(in
, out
, file1
, file2
);
1419 #if !defined(USE_PIPES)
1420 shutdown(in
, SHUT_RDWR
);
1421 shutdown(out
, SHUT_RDWR
);
1429 while (waitpid(sshpid
, NULL
, 0) == -1)
1431 fatal("Couldn't wait for ssh process: %s",
1434 exit(err
== 0 ? 0 : 1);