1 /* $OpenBSD: sftp.c,v 1.91 2006/08/03 03:34:42 deraadt Exp $ */
3 * Copyright (c) 2001-2004 Damien Miller <djm@openbsd.org>
5 * Permission to use, copy, modify, and distribute this software for any
6 * purpose with or without fee is hereby granted, provided that the above
7 * copyright notice and this permission notice appear in all copies.
9 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
20 #include <sys/types.h>
21 #include <sys/ioctl.h>
22 #ifdef HAVE_SYS_STAT_H
23 # include <sys/stat.h>
25 #include <sys/param.h>
26 #include <sys/socket.h>
37 typedef void EditLine
;
48 #include "pathnames.h"
53 #include "sftp-common.h"
54 #include "sftp-client.h"
56 /* File to read commands from */
59 /* Are we in batchfile mode? */
62 /* Size of buffer used when copying files */
63 size_t copy_buffer_len
= 32768;
65 /* Number of concurrent outstanding requests */
66 size_t num_requests
= 16;
68 /* PID of ssh transport process */
69 static pid_t sshpid
= -1;
71 /* This is set to 0 if the progressmeter is not desired. */
74 /* SIGINT received during command processing */
75 volatile sig_atomic_t interrupted
= 0;
77 /* I wish qsort() took a separate ctx for the comparison function...*/
80 int remote_glob(struct sftp_conn
*, const char *, int,
81 int (*)(const char *, int), glob_t
*); /* proto for sftp-glob.c */
83 extern char *__progname
;
85 /* Separators for interactive commands */
86 #define WHITESPACE " \t\r\n"
89 #define LS_LONG_VIEW 0x01 /* Full view ala ls -l */
90 #define LS_SHORT_VIEW 0x02 /* Single row view ala ls -1 */
91 #define LS_NUMERIC_VIEW 0x04 /* Long view with numeric uid/gid */
92 #define LS_NAME_SORT 0x08 /* Sort by name (default) */
93 #define LS_TIME_SORT 0x10 /* Sort by mtime */
94 #define LS_SIZE_SORT 0x20 /* Sort by file size */
95 #define LS_REVERSE_SORT 0x40 /* Reverse sort order */
96 #define LS_SHOW_ALL 0x80 /* Don't skip filenames starting with '.' */
98 #define VIEW_FLAGS (LS_LONG_VIEW|LS_SHORT_VIEW|LS_NUMERIC_VIEW)
99 #define SORT_FLAGS (LS_NAME_SORT|LS_TIME_SORT|LS_SIZE_SORT)
101 /* Commands for interactive mode */
124 #define I_PROGRESS 23
131 static const struct CMD cmds
[] = {
134 { "chdir", I_CHDIR
},
135 { "chgrp", I_CHGRP
},
136 { "chmod", I_CHMOD
},
137 { "chown", I_CHOWN
},
144 { "lchdir", I_LCHDIR
},
146 { "lmkdir", I_LMKDIR
},
150 { "lumask", I_LUMASK
},
151 { "mkdir", I_MKDIR
},
152 { "progress", I_PROGRESS
},
157 { "rename", I_RENAME
},
159 { "rmdir", I_RMDIR
},
160 { "symlink", I_SYMLINK
},
161 { "version", I_VERSION
},
167 int interactive_loop(int fd_in
, int fd_out
, char *file1
, char *file2
);
173 kill(sshpid
, SIGTERM
);
174 waitpid(sshpid
, NULL
, 0);
181 cmd_interrupt(int signo
)
183 const char msg
[] = "\rInterrupt \n";
184 int olderrno
= errno
;
186 write(STDERR_FILENO
, msg
, sizeof(msg
) - 1);
194 printf("Available commands:\n");
195 printf("cd path Change remote directory to 'path'\n");
196 printf("lcd path Change local directory to 'path'\n");
197 printf("chgrp grp path Change group of file 'path' to 'grp'\n");
198 printf("chmod mode path Change permissions of file 'path' to 'mode'\n");
199 printf("chown own path Change owner of file 'path' to 'own'\n");
200 printf("help Display this help text\n");
201 printf("get remote-path [local-path] Download file\n");
202 printf("lls [ls-options [path]] Display local directory listing\n");
203 printf("ln oldpath newpath Symlink remote file\n");
204 printf("lmkdir path Create local directory\n");
205 printf("lpwd Print local working directory\n");
206 printf("ls [path] Display remote directory listing\n");
207 printf("lumask umask Set local umask to 'umask'\n");
208 printf("mkdir path Create remote directory\n");
209 printf("progress Toggle display of progress meter\n");
210 printf("put local-path [remote-path] Upload file\n");
211 printf("pwd Display remote working directory\n");
212 printf("exit Quit sftp\n");
213 printf("quit Quit sftp\n");
214 printf("rename oldpath newpath Rename remote file\n");
215 printf("rmdir path Remove remote directory\n");
216 printf("rm path Delete remote file\n");
217 printf("symlink oldpath newpath Symlink remote file\n");
218 printf("version Show SFTP version\n");
219 printf("!command Execute 'command' in local shell\n");
220 printf("! Escape to local shell\n");
221 printf("? Synonym for help\n");
225 local_do_shell(const char *args
)
234 if ((shell
= getenv("SHELL")) == NULL
)
235 shell
= _PATH_BSHELL
;
237 if ((pid
= fork()) == -1)
238 fatal("Couldn't fork: %s", strerror(errno
));
241 /* XXX: child has pipe fds to ssh subproc open - issue? */
243 debug3("Executing %s -c \"%s\"", shell
, args
);
244 execl(shell
, shell
, "-c", args
, (char *)NULL
);
246 debug3("Executing %s", shell
);
247 execl(shell
, shell
, (char *)NULL
);
249 fprintf(stderr
, "Couldn't execute \"%s\": %s\n", shell
,
253 while (waitpid(pid
, &status
, 0) == -1)
255 fatal("Couldn't wait for child: %s", strerror(errno
));
256 if (!WIFEXITED(status
))
257 error("Shell exited abnormally");
258 else if (WEXITSTATUS(status
))
259 error("Shell exited with status %d", WEXITSTATUS(status
));
263 local_do_ls(const char *args
)
266 local_do_shell(_PATH_LS
);
268 int len
= strlen(_PATH_LS
" ") + strlen(args
) + 1;
269 char *buf
= xmalloc(len
);
271 /* XXX: quoting - rip quoting code from ftp? */
272 snprintf(buf
, len
, _PATH_LS
" %s", args
);
278 /* Strip one path (usually the pwd) from the start of another */
280 path_strip(char *path
, char *strip
)
285 return (xstrdup(path
));
288 if (strncmp(path
, strip
, len
) == 0) {
289 if (strip
[len
- 1] != '/' && path
[len
] == '/')
291 return (xstrdup(path
+ len
));
294 return (xstrdup(path
));
298 path_append(char *p1
, char *p2
)
301 int len
= strlen(p1
) + strlen(p2
) + 2;
304 strlcpy(ret
, p1
, len
);
305 if (p1
[strlen(p1
) - 1] != '/')
306 strlcat(ret
, "/", len
);
307 strlcat(ret
, p2
, len
);
313 make_absolute(char *p
, char *pwd
)
318 if (p
&& p
[0] != '/') {
319 abs_str
= path_append(pwd
, p
);
327 infer_path(const char *p
, char **ifp
)
331 cp
= strrchr(p
, '/');
338 error("Invalid path");
342 *ifp
= xstrdup(cp
+ 1);
347 parse_getput_flags(const char **cpp
, int *pflag
)
349 const char *cp
= *cpp
;
351 /* Check for flags */
352 if (cp
[0] == '-' && cp
[1] && strchr(WHITESPACE
, cp
[2])) {
359 error("Invalid flag -%c", cp
[1]);
363 *cpp
= cp
+ strspn(cp
, WHITESPACE
);
370 parse_ls_flags(const char **cpp
, int *lflag
)
372 const char *cp
= *cpp
;
375 *lflag
= LS_NAME_SORT
;
377 /* Check for flags */
378 if (cp
++[0] == '-') {
379 for (; strchr(WHITESPACE
, *cp
) == NULL
; cp
++) {
382 *lflag
&= ~VIEW_FLAGS
;
383 *lflag
|= LS_LONG_VIEW
;
386 *lflag
&= ~VIEW_FLAGS
;
387 *lflag
|= LS_SHORT_VIEW
;
390 *lflag
&= ~VIEW_FLAGS
;
391 *lflag
|= LS_NUMERIC_VIEW
|LS_LONG_VIEW
;
394 *lflag
&= ~SORT_FLAGS
;
395 *lflag
|= LS_SIZE_SORT
;
398 *lflag
&= ~SORT_FLAGS
;
399 *lflag
|= LS_TIME_SORT
;
402 *lflag
|= LS_REVERSE_SORT
;
405 *lflag
&= ~SORT_FLAGS
;
408 *lflag
|= LS_SHOW_ALL
;
411 error("Invalid flag -%c", *cp
);
415 *cpp
= cp
+ strspn(cp
, WHITESPACE
);
422 get_pathname(const char **cpp
, char **path
)
424 const char *cp
= *cpp
, *end
;
428 cp
+= strspn(cp
, WHITESPACE
);
435 *path
= xmalloc(strlen(cp
) + 1);
437 /* Check for quoted filenames */
438 if (*cp
== '\"' || *cp
== '\'') {
441 /* Search for terminating quote, unescape some chars */
442 for (i
= j
= 0; i
<= strlen(cp
); i
++) {
443 if (cp
[i
] == quot
) { /* Found quote */
448 if (cp
[i
] == '\0') { /* End of string */
449 error("Unterminated quote");
452 if (cp
[i
] == '\\') { /* Escaped characters */
454 if (cp
[i
] != '\'' && cp
[i
] != '\"' &&
456 error("Bad escaped character '\\%c'",
461 (*path
)[j
++] = cp
[i
];
465 error("Empty quotes");
468 *cpp
= cp
+ i
+ strspn(cp
+ i
, WHITESPACE
);
470 /* Read to end of filename */
471 end
= strpbrk(cp
, WHITESPACE
);
473 end
= strchr(cp
, '\0');
474 *cpp
= end
+ strspn(end
, WHITESPACE
);
476 memcpy(*path
, cp
, end
- cp
);
477 (*path
)[end
- cp
] = '\0';
492 /* XXX: report errors? */
493 if (stat(path
, &sb
) == -1)
496 return(sb
.st_mode
& S_IFDIR
);
504 if (stat(path
, &sb
) == -1)
505 fatal("stat %s: %s", path
, strerror(errno
));
507 return(S_ISREG(sb
.st_mode
));
511 remote_is_dir(struct sftp_conn
*conn
, char *path
)
515 /* XXX: report errors? */
516 if ((a
= do_stat(conn
, path
, 1)) == NULL
)
518 if (!(a
->flags
& SSH2_FILEXFER_ATTR_PERMISSIONS
))
520 return(a
->perm
& S_IFDIR
);
524 process_get(struct sftp_conn
*conn
, char *src
, char *dst
, char *pwd
, int pflag
)
526 char *abs_src
= NULL
;
527 char *abs_dst
= NULL
;
533 abs_src
= xstrdup(src
);
534 abs_src
= make_absolute(abs_src
, pwd
);
536 memset(&g
, 0, sizeof(g
));
537 debug3("Looking up %s", abs_src
);
538 if (remote_glob(conn
, abs_src
, 0, NULL
, &g
)) {
539 error("File \"%s\" not found.", abs_src
);
544 /* If multiple matches, dst must be a directory or unspecified */
545 if (g
.gl_matchc
> 1 && dst
&& !is_dir(dst
)) {
546 error("Multiple files match, but \"%s\" is not a directory",
552 for (i
= 0; g
.gl_pathv
[i
] && !interrupted
; i
++) {
553 if (infer_path(g
.gl_pathv
[i
], &tmp
)) {
558 if (g
.gl_matchc
== 1 && dst
) {
559 /* If directory specified, append filename */
562 if (infer_path(g
.gl_pathv
[0], &tmp
)) {
566 abs_dst
= path_append(dst
, tmp
);
569 abs_dst
= xstrdup(dst
);
571 abs_dst
= path_append(dst
, tmp
);
576 printf("Fetching %s to %s\n", g
.gl_pathv
[i
], abs_dst
);
577 if (do_download(conn
, g
.gl_pathv
[i
], abs_dst
, pflag
) == -1)
590 process_put(struct sftp_conn
*conn
, char *src
, char *dst
, char *pwd
, int pflag
)
592 char *tmp_dst
= NULL
;
593 char *abs_dst
= NULL
;
600 tmp_dst
= xstrdup(dst
);
601 tmp_dst
= make_absolute(tmp_dst
, pwd
);
604 memset(&g
, 0, sizeof(g
));
605 debug3("Looking up %s", src
);
606 if (glob(src
, 0, NULL
, &g
)) {
607 error("File \"%s\" not found.", src
);
612 /* If multiple matches, dst may be directory or unspecified */
613 if (g
.gl_matchc
> 1 && tmp_dst
&& !remote_is_dir(conn
, tmp_dst
)) {
614 error("Multiple files match, but \"%s\" is not a directory",
620 for (i
= 0; g
.gl_pathv
[i
] && !interrupted
; i
++) {
621 if (!is_reg(g
.gl_pathv
[i
])) {
622 error("skipping non-regular file %s",
626 if (infer_path(g
.gl_pathv
[i
], &tmp
)) {
631 if (g
.gl_matchc
== 1 && tmp_dst
) {
632 /* If directory specified, append filename */
633 if (remote_is_dir(conn
, tmp_dst
)) {
634 if (infer_path(g
.gl_pathv
[0], &tmp
)) {
638 abs_dst
= path_append(tmp_dst
, tmp
);
641 abs_dst
= xstrdup(tmp_dst
);
643 } else if (tmp_dst
) {
644 abs_dst
= path_append(tmp_dst
, tmp
);
647 abs_dst
= make_absolute(tmp
, pwd
);
649 printf("Uploading %s to %s\n", g
.gl_pathv
[i
], abs_dst
);
650 if (do_upload(conn
, g
.gl_pathv
[i
], abs_dst
, pflag
) == -1)
664 sdirent_comp(const void *aa
, const void *bb
)
666 SFTP_DIRENT
*a
= *(SFTP_DIRENT
**)aa
;
667 SFTP_DIRENT
*b
= *(SFTP_DIRENT
**)bb
;
668 int rmul
= sort_flag
& LS_REVERSE_SORT
? -1 : 1;
670 #define NCMP(a,b) (a == b ? 0 : (a < b ? 1 : -1))
671 if (sort_flag
& LS_NAME_SORT
)
672 return (rmul
* strcmp(a
->filename
, b
->filename
));
673 else if (sort_flag
& LS_TIME_SORT
)
674 return (rmul
* NCMP(a
->a
.mtime
, b
->a
.mtime
));
675 else if (sort_flag
& LS_SIZE_SORT
)
676 return (rmul
* NCMP(a
->a
.size
, b
->a
.size
));
678 fatal("Unknown ls sort type");
681 /* sftp ls.1 replacement for directories */
683 do_ls_dir(struct sftp_conn
*conn
, char *path
, char *strip_path
, int lflag
)
686 u_int c
= 1, colspace
= 0, columns
= 1;
689 if ((n
= do_readdir(conn
, path
, &d
)) != 0)
692 if (!(lflag
& LS_SHORT_VIEW
)) {
693 u_int m
= 0, width
= 80;
697 /* Count entries for sort and find longest filename */
698 for (n
= 0; d
[n
] != NULL
; n
++) {
699 if (d
[n
]->filename
[0] != '.' || (lflag
& LS_SHOW_ALL
))
700 m
= MAX(m
, strlen(d
[n
]->filename
));
703 /* Add any subpath that also needs to be counted */
704 tmp
= path_strip(path
, strip_path
);
708 if (ioctl(fileno(stdin
), TIOCGWINSZ
, &ws
) != -1)
711 columns
= width
/ (m
+ 2);
712 columns
= MAX(columns
, 1);
713 colspace
= width
/ columns
;
714 colspace
= MIN(colspace
, width
);
717 if (lflag
& SORT_FLAGS
) {
718 for (n
= 0; d
[n
] != NULL
; n
++)
719 ; /* count entries */
720 sort_flag
= lflag
& (SORT_FLAGS
|LS_REVERSE_SORT
);
721 qsort(d
, n
, sizeof(*d
), sdirent_comp
);
724 for (n
= 0; d
[n
] != NULL
&& !interrupted
; n
++) {
727 if (d
[n
]->filename
[0] == '.' && !(lflag
& LS_SHOW_ALL
))
730 tmp
= path_append(path
, d
[n
]->filename
);
731 fname
= path_strip(tmp
, strip_path
);
734 if (lflag
& LS_LONG_VIEW
) {
735 if (lflag
& LS_NUMERIC_VIEW
) {
739 memset(&sb
, 0, sizeof(sb
));
740 attrib_to_stat(&d
[n
]->a
, &sb
);
741 lname
= ls_file(fname
, &sb
, 1);
742 printf("%s\n", lname
);
745 printf("%s\n", d
[n
]->longname
);
747 printf("%-*s", colspace
, fname
);
758 if (!(lflag
& LS_LONG_VIEW
) && (c
!= 1))
761 free_sftp_dirents(d
);
765 /* sftp ls.1 replacement which handles path globs */
767 do_globbed_ls(struct sftp_conn
*conn
, char *path
, char *strip_path
,
771 u_int i
, c
= 1, colspace
= 0, columns
= 1;
774 memset(&g
, 0, sizeof(g
));
776 if (remote_glob(conn
, path
, GLOB_MARK
|GLOB_NOCHECK
|GLOB_BRACE
,
777 NULL
, &g
) || (g
.gl_pathc
&& !g
.gl_matchc
)) {
780 error("Can't ls: \"%s\" not found", path
);
788 * If the glob returns a single match and it is a directory,
789 * then just list its contents.
791 if (g
.gl_matchc
== 1) {
792 if ((a
= do_lstat(conn
, g
.gl_pathv
[0], 1)) == NULL
) {
796 if ((a
->flags
& SSH2_FILEXFER_ATTR_PERMISSIONS
) &&
800 err
= do_ls_dir(conn
, g
.gl_pathv
[0], strip_path
, lflag
);
806 if (!(lflag
& LS_SHORT_VIEW
)) {
807 u_int m
= 0, width
= 80;
810 /* Count entries for sort and find longest filename */
811 for (i
= 0; g
.gl_pathv
[i
]; i
++)
812 m
= MAX(m
, strlen(g
.gl_pathv
[i
]));
814 if (ioctl(fileno(stdin
), TIOCGWINSZ
, &ws
) != -1)
817 columns
= width
/ (m
+ 2);
818 columns
= MAX(columns
, 1);
819 colspace
= width
/ columns
;
822 for (i
= 0; g
.gl_pathv
[i
] && !interrupted
; i
++, a
= NULL
) {
825 fname
= path_strip(g
.gl_pathv
[i
], strip_path
);
827 if (lflag
& LS_LONG_VIEW
) {
832 * XXX: this is slow - 1 roundtrip per path
833 * A solution to this is to fork glob() and
834 * build a sftp specific version which keeps the
835 * attribs (which currently get thrown away)
836 * that the server returns as well as the filenames.
838 memset(&sb
, 0, sizeof(sb
));
840 a
= do_lstat(conn
, g
.gl_pathv
[i
], 1);
842 attrib_to_stat(a
, &sb
);
843 lname
= ls_file(fname
, &sb
, 1);
844 printf("%s\n", lname
);
847 printf("%-*s", colspace
, fname
);
857 if (!(lflag
& LS_LONG_VIEW
) && (c
!= 1))
868 parse_args(const char **cpp
, int *pflag
, int *lflag
, int *iflag
,
869 unsigned long *n_arg
, char **path1
, char **path2
)
871 const char *cmd
, *cp
= *cpp
;
877 /* Skip leading whitespace */
878 cp
= cp
+ strspn(cp
, WHITESPACE
);
880 /* Ignore blank lines and lines which begin with comment '#' char */
881 if (*cp
== '\0' || *cp
== '#')
884 /* Check for leading '-' (disable error processing) */
891 /* Figure out which command we have */
892 for (i
= 0; cmds
[i
].c
; i
++) {
893 int cmdlen
= strlen(cmds
[i
].c
);
895 /* Check for command followed by whitespace */
896 if (!strncasecmp(cp
, cmds
[i
].c
, cmdlen
) &&
897 strchr(WHITESPACE
, cp
[cmdlen
])) {
899 cp
= cp
+ strspn(cp
, WHITESPACE
);
910 } else if (cmdnum
== -1) {
911 error("Invalid command.");
915 /* Get arguments and parse flags */
916 *lflag
= *pflag
= *n_arg
= 0;
917 *path1
= *path2
= NULL
;
921 if (parse_getput_flags(&cp
, pflag
))
923 /* Get first pathname (mandatory) */
924 if (get_pathname(&cp
, path1
))
926 if (*path1
== NULL
) {
927 error("You must specify at least one path after a "
931 /* Try to get second pathname (optional) */
932 if (get_pathname(&cp
, path2
))
937 if (get_pathname(&cp
, path1
))
939 if (get_pathname(&cp
, path2
))
941 if (!*path1
|| !*path2
) {
942 error("You must specify two paths after a %s "
953 /* Get pathname (mandatory) */
954 if (get_pathname(&cp
, path1
))
956 if (*path1
== NULL
) {
957 error("You must specify a path after a %s command.",
963 if (parse_ls_flags(&cp
, lflag
))
965 /* Path is optional */
966 if (get_pathname(&cp
, path1
))
971 /* Uses the rest of the line */
979 /* Get numeric arg (mandatory) */
980 l
= strtol(cp
, &cp2
, base
);
981 if (cp2
== cp
|| ((l
== LONG_MIN
|| l
== LONG_MAX
) &&
982 errno
== ERANGE
) || l
< 0) {
983 error("You must supply a numeric argument "
984 "to the %s command.", cmd
);
989 if (cmdnum
== I_LUMASK
&& strchr(WHITESPACE
, *cp
))
991 if (cmdnum
== I_LUMASK
|| !strchr(WHITESPACE
, *cp
)) {
992 error("You must supply a numeric argument "
993 "to the %s command.", cmd
);
996 cp
+= strspn(cp
, WHITESPACE
);
998 /* Get pathname (mandatory) */
999 if (get_pathname(&cp
, path1
))
1001 if (*path1
== NULL
) {
1002 error("You must specify a path after a %s command.",
1015 fatal("Command not implemented");
1023 parse_dispatch_command(struct sftp_conn
*conn
, const char *cmd
, char **pwd
,
1026 char *path1
, *path2
, *tmp
;
1027 int pflag
, lflag
, iflag
, cmdnum
, i
;
1028 unsigned long n_arg
;
1030 char path_buf
[MAXPATHLEN
];
1034 path1
= path2
= NULL
;
1035 cmdnum
= parse_args(&cmd
, &pflag
, &lflag
, &iflag
, &n_arg
,
1041 memset(&g
, 0, sizeof(g
));
1043 /* Perform command */
1049 /* Unrecognized command */
1053 err
= process_get(conn
, path1
, path2
, *pwd
, pflag
);
1056 err
= process_put(conn
, path1
, path2
, *pwd
, pflag
);
1059 path1
= make_absolute(path1
, *pwd
);
1060 path2
= make_absolute(path2
, *pwd
);
1061 err
= do_rename(conn
, path1
, path2
);
1064 path2
= make_absolute(path2
, *pwd
);
1065 err
= do_symlink(conn
, path1
, path2
);
1068 path1
= make_absolute(path1
, *pwd
);
1069 remote_glob(conn
, path1
, GLOB_NOCHECK
, NULL
, &g
);
1070 for (i
= 0; g
.gl_pathv
[i
] && !interrupted
; i
++) {
1071 printf("Removing %s\n", g
.gl_pathv
[i
]);
1072 err
= do_rm(conn
, g
.gl_pathv
[i
]);
1073 if (err
!= 0 && err_abort
)
1078 path1
= make_absolute(path1
, *pwd
);
1080 a
.flags
|= SSH2_FILEXFER_ATTR_PERMISSIONS
;
1082 err
= do_mkdir(conn
, path1
, &a
);
1085 path1
= make_absolute(path1
, *pwd
);
1086 err
= do_rmdir(conn
, path1
);
1089 path1
= make_absolute(path1
, *pwd
);
1090 if ((tmp
= do_realpath(conn
, path1
)) == NULL
) {
1094 if ((aa
= do_stat(conn
, tmp
, 0)) == NULL
) {
1099 if (!(aa
->flags
& SSH2_FILEXFER_ATTR_PERMISSIONS
)) {
1100 error("Can't change directory: Can't check target");
1105 if (!S_ISDIR(aa
->perm
)) {
1106 error("Can't change directory: \"%s\" is not "
1107 "a directory", tmp
);
1117 do_globbed_ls(conn
, *pwd
, *pwd
, lflag
);
1121 /* Strip pwd off beginning of non-absolute paths */
1126 path1
= make_absolute(path1
, *pwd
);
1127 err
= do_globbed_ls(conn
, path1
, tmp
, lflag
);
1130 if (chdir(path1
) == -1) {
1131 error("Couldn't change local directory to "
1132 "\"%s\": %s", path1
, strerror(errno
));
1137 if (mkdir(path1
, 0777) == -1) {
1138 error("Couldn't create local directory "
1139 "\"%s\": %s", path1
, strerror(errno
));
1147 local_do_shell(cmd
);
1151 printf("Local umask: %03lo\n", n_arg
);
1154 path1
= make_absolute(path1
, *pwd
);
1156 a
.flags
|= SSH2_FILEXFER_ATTR_PERMISSIONS
;
1158 remote_glob(conn
, path1
, GLOB_NOCHECK
, NULL
, &g
);
1159 for (i
= 0; g
.gl_pathv
[i
] && !interrupted
; i
++) {
1160 printf("Changing mode on %s\n", g
.gl_pathv
[i
]);
1161 err
= do_setstat(conn
, g
.gl_pathv
[i
], &a
);
1162 if (err
!= 0 && err_abort
)
1168 path1
= make_absolute(path1
, *pwd
);
1169 remote_glob(conn
, path1
, GLOB_NOCHECK
, NULL
, &g
);
1170 for (i
= 0; g
.gl_pathv
[i
] && !interrupted
; i
++) {
1171 if (!(aa
= do_stat(conn
, g
.gl_pathv
[i
], 0))) {
1172 if (err
!= 0 && err_abort
)
1177 if (!(aa
->flags
& SSH2_FILEXFER_ATTR_UIDGID
)) {
1178 error("Can't get current ownership of "
1179 "remote file \"%s\"", g
.gl_pathv
[i
]);
1180 if (err
!= 0 && err_abort
)
1185 aa
->flags
&= SSH2_FILEXFER_ATTR_UIDGID
;
1186 if (cmdnum
== I_CHOWN
) {
1187 printf("Changing owner on %s\n", g
.gl_pathv
[i
]);
1190 printf("Changing group on %s\n", g
.gl_pathv
[i
]);
1193 err
= do_setstat(conn
, g
.gl_pathv
[i
], aa
);
1194 if (err
!= 0 && err_abort
)
1199 printf("Remote working directory: %s\n", *pwd
);
1202 if (!getcwd(path_buf
, sizeof(path_buf
))) {
1203 error("Couldn't get local cwd: %s", strerror(errno
));
1207 printf("Local working directory: %s\n", path_buf
);
1210 /* Processed below */
1216 printf("SFTP protocol version %u\n", sftp_proto_version(conn
));
1219 showprogress
= !showprogress
;
1221 printf("Progress meter enabled\n");
1223 printf("Progress meter disabled\n");
1226 fatal("%d is not implemented", cmdnum
);
1236 /* If an unignored error occurs in batch mode we should abort. */
1237 if (err_abort
&& err
!= 0)
1239 else if (cmdnum
== I_QUIT
)
1247 prompt(EditLine
*el
)
1254 interactive_loop(int fd_in
, int fd_out
, char *file1
, char *file2
)
1259 struct sftp_conn
*conn
;
1260 int err
, interactive
;
1261 EditLine
*el
= NULL
;
1265 extern char *__progname
;
1267 if (!batchmode
&& isatty(STDIN_FILENO
)) {
1268 if ((el
= el_init(__progname
, stdin
, stdout
, stderr
)) == NULL
)
1269 fatal("Couldn't initialise editline");
1270 if ((hl
= history_init()) == NULL
)
1271 fatal("Couldn't initialise editline history");
1272 history(hl
, &hev
, H_SETSIZE
, 100);
1273 el_set(el
, EL_HIST
, history
, hl
);
1275 el_set(el
, EL_PROMPT
, prompt
);
1276 el_set(el
, EL_EDITOR
, "emacs");
1277 el_set(el
, EL_TERMINAL
, NULL
);
1278 el_set(el
, EL_SIGNAL
, 1);
1279 el_source(el
, NULL
);
1281 #endif /* USE_LIBEDIT */
1283 conn
= do_init(fd_in
, fd_out
, copy_buffer_len
, num_requests
);
1285 fatal("Couldn't initialise connection to server");
1287 pwd
= do_realpath(conn
, ".");
1291 if (file1
!= NULL
) {
1292 dir
= xstrdup(file1
);
1293 dir
= make_absolute(dir
, pwd
);
1295 if (remote_is_dir(conn
, dir
) && file2
== NULL
) {
1296 printf("Changing to: %s\n", dir
);
1297 snprintf(cmd
, sizeof cmd
, "cd \"%s\"", dir
);
1298 if (parse_dispatch_command(conn
, cmd
, &pwd
, 1) != 0) {
1306 snprintf(cmd
, sizeof cmd
, "get %s", dir
);
1308 snprintf(cmd
, sizeof cmd
, "get %s %s", dir
,
1311 err
= parse_dispatch_command(conn
, cmd
, &pwd
, 1);
1320 #if defined(HAVE_SETVBUF) && !defined(BROKEN_SETVBUF)
1321 setvbuf(stdout
, NULL
, _IOLBF
, 0);
1322 setvbuf(infile
, NULL
, _IOLBF
, 0);
1328 interactive
= !batchmode
&& isatty(STDIN_FILENO
);
1333 signal(SIGINT
, SIG_IGN
);
1338 if (fgets(cmd
, sizeof(cmd
), infile
) == NULL
) {
1343 if (!interactive
) { /* Echo command */
1344 printf("sftp> %s", cmd
);
1345 if (strlen(cmd
) > 0 &&
1346 cmd
[strlen(cmd
) - 1] != '\n')
1354 if ((line
= el_gets(el
, &count
)) == NULL
|| count
<= 0) {
1358 history(hl
, &hev
, H_ENTER
, line
);
1359 if (strlcpy(cmd
, line
, sizeof(cmd
)) >= sizeof(cmd
)) {
1360 fprintf(stderr
, "Error: input line too long\n");
1363 #endif /* USE_LIBEDIT */
1366 cp
= strrchr(cmd
, '\n');
1370 /* Handle user interrupts gracefully during commands */
1372 signal(SIGINT
, cmd_interrupt
);
1374 err
= parse_dispatch_command(conn
, cmd
, &pwd
, batchmode
);
1384 #endif /* USE_LIBEDIT */
1386 /* err == 1 signifies normal "quit" exit */
1387 return (err
>= 0 ? 0 : -1);
1391 connect_to_server(char *path
, char **args
, int *in
, int *out
)
1396 int pin
[2], pout
[2];
1398 if ((pipe(pin
) == -1) || (pipe(pout
) == -1))
1399 fatal("pipe: %s", strerror(errno
));
1404 #else /* USE_PIPES */
1407 if (socketpair(AF_UNIX
, SOCK_STREAM
, 0, inout
) == -1)
1408 fatal("socketpair: %s", strerror(errno
));
1409 *in
= *out
= inout
[0];
1410 c_in
= c_out
= inout
[1];
1411 #endif /* USE_PIPES */
1413 if ((sshpid
= fork()) == -1)
1414 fatal("fork: %s", strerror(errno
));
1415 else if (sshpid
== 0) {
1416 if ((dup2(c_in
, STDIN_FILENO
) == -1) ||
1417 (dup2(c_out
, STDOUT_FILENO
) == -1)) {
1418 fprintf(stderr
, "dup2: %s\n", strerror(errno
));
1427 * The underlying ssh is in the same process group, so we must
1428 * ignore SIGINT if we want to gracefully abort commands,
1429 * otherwise the signal will make it to the ssh process and
1432 signal(SIGINT
, SIG_IGN
);
1434 fprintf(stderr
, "exec: %s: %s\n", path
, strerror(errno
));
1438 signal(SIGTERM
, killchild
);
1439 signal(SIGINT
, killchild
);
1440 signal(SIGHUP
, killchild
);
1448 extern char *__progname
;
1451 "usage: %s [-1Cv] [-B buffer_size] [-b batchfile] [-F ssh_config]\n"
1452 " [-o ssh_option] [-P sftp_server_path] [-R num_requests]\n"
1453 " [-S program] [-s subsystem | sftp_server] host\n"
1454 " %s [[user@]host[:file [file]]]\n"
1455 " %s [[user@]host[:dir[/]]]\n"
1456 " %s -b batchfile [user@]host\n", __progname
, __progname
, __progname
, __progname
);
1461 main(int argc
, char **argv
)
1463 int in
, out
, ch
, err
;
1464 char *host
, *userhost
, *cp
, *file2
= NULL
;
1465 int debug_level
= 0, sshver
= 2;
1466 char *file1
= NULL
, *sftp_server
= NULL
;
1467 char *ssh_program
= _PATH_SSH_PROGRAM
, *sftp_direct
= NULL
;
1468 LogLevel ll
= SYSLOG_LEVEL_INFO
;
1471 extern char *optarg
;
1473 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
1476 __progname
= ssh_get_progname(argv
[0]);
1477 memset(&args
, '\0', sizeof(args
));
1479 addargs(&args
, "%s", ssh_program
);
1480 addargs(&args
, "-oForwardX11 no");
1481 addargs(&args
, "-oForwardAgent no");
1482 addargs(&args
, "-oPermitLocalCommand no");
1483 addargs(&args
, "-oClearAllForwardings yes");
1485 ll
= SYSLOG_LEVEL_INFO
;
1488 while ((ch
= getopt(argc
, argv
, "1hvCo:s:S:b:B:F:P:R:")) != -1) {
1491 addargs(&args
, "-C");
1494 if (debug_level
< 3) {
1495 addargs(&args
, "-v");
1496 ll
= SYSLOG_LEVEL_DEBUG1
+ debug_level
;
1502 addargs(&args
, "-%c%s", ch
, optarg
);
1506 if (sftp_server
== NULL
)
1507 sftp_server
= _PATH_SFTP_SERVER
;
1510 sftp_server
= optarg
;
1513 ssh_program
= optarg
;
1514 replacearg(&args
, 0, "%s", ssh_program
);
1518 fatal("Batch file already specified.");
1520 /* Allow "-" as stdin */
1521 if (strcmp(optarg
, "-") != 0 &&
1522 (infile
= fopen(optarg
, "r")) == NULL
)
1523 fatal("%s (%s).", strerror(errno
), optarg
);
1526 addargs(&args
, "-obatchmode yes");
1529 sftp_direct
= optarg
;
1532 copy_buffer_len
= strtol(optarg
, &cp
, 10);
1533 if (copy_buffer_len
== 0 || *cp
!= '\0')
1534 fatal("Invalid buffer size \"%s\"", optarg
);
1537 num_requests
= strtol(optarg
, &cp
, 10);
1538 if (num_requests
== 0 || *cp
!= '\0')
1539 fatal("Invalid number of requests \"%s\"",
1548 if (!isatty(STDERR_FILENO
))
1551 log_init(argv
[0], ll
, SYSLOG_FACILITY_USER
, 1);
1553 if (sftp_direct
== NULL
) {
1554 if (optind
== argc
|| argc
> (optind
+ 2))
1557 userhost
= xstrdup(argv
[optind
]);
1558 file2
= argv
[optind
+1];
1560 if ((host
= strrchr(userhost
, '@')) == NULL
)
1565 fprintf(stderr
, "Missing username\n");
1568 addargs(&args
, "-l%s",userhost
);
1571 if ((cp
= colon(host
)) != NULL
) {
1576 host
= cleanhostname(host
);
1578 fprintf(stderr
, "Missing hostname\n");
1582 addargs(&args
, "-oProtocol %d", sshver
);
1584 /* no subsystem if the server-spec contains a '/' */
1585 if (sftp_server
== NULL
|| strchr(sftp_server
, '/') == NULL
)
1586 addargs(&args
, "-s");
1588 addargs(&args
, "%s", host
);
1589 addargs(&args
, "%s", (sftp_server
!= NULL
?
1590 sftp_server
: "sftp"));
1593 fprintf(stderr
, "Connecting to %s...\n", host
);
1594 connect_to_server(ssh_program
, args
.list
, &in
, &out
);
1597 addargs(&args
, "sftp-server");
1600 fprintf(stderr
, "Attaching to %s...\n", sftp_direct
);
1601 connect_to_server(sftp_direct
, args
.list
, &in
, &out
);
1605 err
= interactive_loop(in
, out
, file1
, file2
);
1607 #if !defined(USE_PIPES)
1608 shutdown(in
, SHUT_RDWR
);
1609 shutdown(out
, SHUT_RDWR
);
1617 while (waitpid(sshpid
, NULL
, 0) == -1)
1619 fatal("Couldn't wait for ssh process: %s",
1622 exit(err
== 0 ? 0 : 1);