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.63 2005/03/10 22:01:05 deraadt 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
);
155 waitpid(sshpid
, NULL
, 0);
162 cmd_interrupt(int signo
)
164 const char msg
[] = "\rInterrupt \n";
165 int olderrno
= errno
;
167 write(STDERR_FILENO
, msg
, sizeof(msg
) - 1);
175 printf("Available commands:\n");
176 printf("cd path Change remote directory to 'path'\n");
177 printf("lcd path Change local directory to 'path'\n");
178 printf("chgrp grp path Change group of file 'path' to 'grp'\n");
179 printf("chmod mode path Change permissions of file 'path' to 'mode'\n");
180 printf("chown own path Change owner of file 'path' to 'own'\n");
181 printf("help Display this help text\n");
182 printf("get remote-path [local-path] Download file\n");
183 printf("lls [ls-options [path]] Display local directory listing\n");
184 printf("ln oldpath newpath Symlink remote file\n");
185 printf("lmkdir path Create local directory\n");
186 printf("lpwd Print local working directory\n");
187 printf("ls [path] Display remote directory listing\n");
188 printf("lumask umask Set local umask to 'umask'\n");
189 printf("mkdir path Create remote directory\n");
190 printf("progress Toggle display of progress meter\n");
191 printf("put local-path [remote-path] Upload file\n");
192 printf("pwd Display remote working directory\n");
193 printf("exit Quit sftp\n");
194 printf("quit Quit sftp\n");
195 printf("rename oldpath newpath Rename remote file\n");
196 printf("rmdir path Remove remote directory\n");
197 printf("rm path Delete remote file\n");
198 printf("symlink oldpath newpath Symlink remote file\n");
199 printf("version Show SFTP version\n");
200 printf("!command Execute 'command' in local shell\n");
201 printf("! Escape to local shell\n");
202 printf("? Synonym for help\n");
206 local_do_shell(const char *args
)
215 if ((shell
= getenv("SHELL")) == NULL
)
216 shell
= _PATH_BSHELL
;
218 if ((pid
= fork()) == -1)
219 fatal("Couldn't fork: %s", strerror(errno
));
222 /* XXX: child has pipe fds to ssh subproc open - issue? */
224 debug3("Executing %s -c \"%s\"", shell
, args
);
225 execl(shell
, shell
, "-c", args
, (char *)NULL
);
227 debug3("Executing %s", shell
);
228 execl(shell
, shell
, (char *)NULL
);
230 fprintf(stderr
, "Couldn't execute \"%s\": %s\n", shell
,
234 while (waitpid(pid
, &status
, 0) == -1)
236 fatal("Couldn't wait for child: %s", strerror(errno
));
237 if (!WIFEXITED(status
))
238 error("Shell exited abormally");
239 else if (WEXITSTATUS(status
))
240 error("Shell exited with status %d", WEXITSTATUS(status
));
244 local_do_ls(const char *args
)
247 local_do_shell(_PATH_LS
);
249 int len
= strlen(_PATH_LS
" ") + strlen(args
) + 1;
250 char *buf
= xmalloc(len
);
252 /* XXX: quoting - rip quoting code from ftp? */
253 snprintf(buf
, len
, _PATH_LS
" %s", args
);
259 /* Strip one path (usually the pwd) from the start of another */
261 path_strip(char *path
, char *strip
)
266 return (xstrdup(path
));
269 if (strncmp(path
, strip
, len
) == 0) {
270 if (strip
[len
- 1] != '/' && path
[len
] == '/')
272 return (xstrdup(path
+ len
));
275 return (xstrdup(path
));
279 path_append(char *p1
, char *p2
)
282 int len
= strlen(p1
) + strlen(p2
) + 2;
285 strlcpy(ret
, p1
, len
);
286 if (p1
[strlen(p1
) - 1] != '/')
287 strlcat(ret
, "/", len
);
288 strlcat(ret
, p2
, len
);
294 make_absolute(char *p
, char *pwd
)
299 if (p
&& p
[0] != '/') {
300 abs_str
= path_append(pwd
, p
);
308 infer_path(const char *p
, char **ifp
)
312 cp
= strrchr(p
, '/');
319 error("Invalid path");
323 *ifp
= xstrdup(cp
+ 1);
328 parse_getput_flags(const char **cpp
, int *pflag
)
330 const char *cp
= *cpp
;
332 /* Check for flags */
333 if (cp
[0] == '-' && cp
[1] && strchr(WHITESPACE
, cp
[2])) {
340 error("Invalid flag -%c", cp
[1]);
344 *cpp
= cp
+ strspn(cp
, WHITESPACE
);
351 parse_ls_flags(const char **cpp
, int *lflag
)
353 const char *cp
= *cpp
;
356 *lflag
= LS_NAME_SORT
;
358 /* Check for flags */
359 if (cp
++[0] == '-') {
360 for (; strchr(WHITESPACE
, *cp
) == NULL
; cp
++) {
363 *lflag
&= ~VIEW_FLAGS
;
364 *lflag
|= LS_LONG_VIEW
;
367 *lflag
&= ~VIEW_FLAGS
;
368 *lflag
|= LS_SHORT_VIEW
;
371 *lflag
&= ~VIEW_FLAGS
;
372 *lflag
|= LS_NUMERIC_VIEW
|LS_LONG_VIEW
;
375 *lflag
&= ~SORT_FLAGS
;
376 *lflag
|= LS_SIZE_SORT
;
379 *lflag
&= ~SORT_FLAGS
;
380 *lflag
|= LS_TIME_SORT
;
383 *lflag
|= LS_REVERSE_SORT
;
386 *lflag
&= ~SORT_FLAGS
;
389 *lflag
|= LS_SHOW_ALL
;
392 error("Invalid flag -%c", *cp
);
396 *cpp
= cp
+ strspn(cp
, WHITESPACE
);
403 get_pathname(const char **cpp
, char **path
)
405 const char *cp
= *cpp
, *end
;
409 cp
+= strspn(cp
, WHITESPACE
);
416 *path
= xmalloc(strlen(cp
) + 1);
418 /* Check for quoted filenames */
419 if (*cp
== '\"' || *cp
== '\'') {
422 /* Search for terminating quote, unescape some chars */
423 for (i
= j
= 0; i
<= strlen(cp
); i
++) {
424 if (cp
[i
] == quot
) { /* Found quote */
429 if (cp
[i
] == '\0') { /* End of string */
430 error("Unterminated quote");
433 if (cp
[i
] == '\\') { /* Escaped characters */
435 if (cp
[i
] != '\'' && cp
[i
] != '\"' &&
437 error("Bad escaped character '\\%c'",
442 (*path
)[j
++] = cp
[i
];
446 error("Empty quotes");
449 *cpp
= cp
+ i
+ strspn(cp
+ i
, WHITESPACE
);
451 /* Read to end of filename */
452 end
= strpbrk(cp
, WHITESPACE
);
454 end
= strchr(cp
, '\0');
455 *cpp
= end
+ strspn(end
, WHITESPACE
);
457 memcpy(*path
, cp
, end
- cp
);
458 (*path
)[end
- cp
] = '\0';
473 /* XXX: report errors? */
474 if (stat(path
, &sb
) == -1)
477 return(sb
.st_mode
& S_IFDIR
);
485 if (stat(path
, &sb
) == -1)
486 fatal("stat %s: %s", path
, strerror(errno
));
488 return(S_ISREG(sb
.st_mode
));
492 remote_is_dir(struct sftp_conn
*conn
, char *path
)
496 /* XXX: report errors? */
497 if ((a
= do_stat(conn
, path
, 1)) == NULL
)
499 if (!(a
->flags
& SSH2_FILEXFER_ATTR_PERMISSIONS
))
501 return(a
->perm
& S_IFDIR
);
505 process_get(struct sftp_conn
*conn
, char *src
, char *dst
, char *pwd
, int pflag
)
507 char *abs_src
= NULL
;
508 char *abs_dst
= NULL
;
514 abs_src
= xstrdup(src
);
515 abs_src
= make_absolute(abs_src
, pwd
);
517 memset(&g
, 0, sizeof(g
));
518 debug3("Looking up %s", abs_src
);
519 if (remote_glob(conn
, abs_src
, 0, NULL
, &g
)) {
520 error("File \"%s\" not found.", abs_src
);
525 /* If multiple matches, dst must be a directory or unspecified */
526 if (g
.gl_matchc
> 1 && dst
&& !is_dir(dst
)) {
527 error("Multiple files match, but \"%s\" is not a directory",
533 for (i
= 0; g
.gl_pathv
[i
] && !interrupted
; i
++) {
534 if (infer_path(g
.gl_pathv
[i
], &tmp
)) {
539 if (g
.gl_matchc
== 1 && dst
) {
540 /* If directory specified, append filename */
542 if (infer_path(g
.gl_pathv
[0], &tmp
)) {
546 abs_dst
= path_append(dst
, tmp
);
549 abs_dst
= xstrdup(dst
);
551 abs_dst
= path_append(dst
, tmp
);
556 printf("Fetching %s to %s\n", g
.gl_pathv
[i
], abs_dst
);
557 if (do_download(conn
, g
.gl_pathv
[i
], abs_dst
, pflag
) == -1)
572 process_put(struct sftp_conn
*conn
, char *src
, char *dst
, char *pwd
, int pflag
)
574 char *tmp_dst
= NULL
;
575 char *abs_dst
= NULL
;
582 tmp_dst
= xstrdup(dst
);
583 tmp_dst
= make_absolute(tmp_dst
, pwd
);
586 memset(&g
, 0, sizeof(g
));
587 debug3("Looking up %s", src
);
588 if (glob(src
, 0, NULL
, &g
)) {
589 error("File \"%s\" not found.", src
);
594 /* If multiple matches, dst may be directory or unspecified */
595 if (g
.gl_matchc
> 1 && tmp_dst
&& !remote_is_dir(conn
, tmp_dst
)) {
596 error("Multiple files match, but \"%s\" is not a directory",
602 for (i
= 0; g
.gl_pathv
[i
] && !interrupted
; i
++) {
603 if (!is_reg(g
.gl_pathv
[i
])) {
604 error("skipping non-regular file %s",
608 if (infer_path(g
.gl_pathv
[i
], &tmp
)) {
613 if (g
.gl_matchc
== 1 && tmp_dst
) {
614 /* If directory specified, append filename */
615 if (remote_is_dir(conn
, tmp_dst
)) {
616 if (infer_path(g
.gl_pathv
[0], &tmp
)) {
620 abs_dst
= path_append(tmp_dst
, tmp
);
623 abs_dst
= xstrdup(tmp_dst
);
625 } else if (tmp_dst
) {
626 abs_dst
= path_append(tmp_dst
, tmp
);
629 abs_dst
= make_absolute(tmp
, pwd
);
631 printf("Uploading %s to %s\n", g
.gl_pathv
[i
], abs_dst
);
632 if (do_upload(conn
, g
.gl_pathv
[i
], abs_dst
, pflag
) == -1)
646 sdirent_comp(const void *aa
, const void *bb
)
648 SFTP_DIRENT
*a
= *(SFTP_DIRENT
**)aa
;
649 SFTP_DIRENT
*b
= *(SFTP_DIRENT
**)bb
;
650 int rmul
= sort_flag
& LS_REVERSE_SORT
? -1 : 1;
652 #define NCMP(a,b) (a == b ? 0 : (a < b ? 1 : -1))
653 if (sort_flag
& LS_NAME_SORT
)
654 return (rmul
* strcmp(a
->filename
, b
->filename
));
655 else if (sort_flag
& LS_TIME_SORT
)
656 return (rmul
* NCMP(a
->a
.mtime
, b
->a
.mtime
));
657 else if (sort_flag
& LS_SIZE_SORT
)
658 return (rmul
* NCMP(a
->a
.size
, b
->a
.size
));
660 fatal("Unknown ls sort type");
663 /* sftp ls.1 replacement for directories */
665 do_ls_dir(struct sftp_conn
*conn
, char *path
, char *strip_path
, int lflag
)
667 int n
, c
= 1, colspace
= 0, columns
= 1;
670 if ((n
= do_readdir(conn
, path
, &d
)) != 0)
673 if (!(lflag
& LS_SHORT_VIEW
)) {
674 int m
= 0, width
= 80;
678 /* Count entries for sort and find longest filename */
679 for (n
= 0; d
[n
] != NULL
; n
++) {
680 if (d
[n
]->filename
[0] != '.' || (lflag
& LS_SHOW_ALL
))
681 m
= MAX(m
, strlen(d
[n
]->filename
));
684 /* Add any subpath that also needs to be counted */
685 tmp
= path_strip(path
, strip_path
);
689 if (ioctl(fileno(stdin
), TIOCGWINSZ
, &ws
) != -1)
692 columns
= width
/ (m
+ 2);
693 columns
= MAX(columns
, 1);
694 colspace
= width
/ columns
;
695 colspace
= MIN(colspace
, width
);
698 if (lflag
& SORT_FLAGS
) {
699 sort_flag
= lflag
& (SORT_FLAGS
|LS_REVERSE_SORT
);
700 qsort(d
, n
, sizeof(*d
), sdirent_comp
);
703 for (n
= 0; d
[n
] != NULL
&& !interrupted
; n
++) {
706 if (d
[n
]->filename
[0] == '.' && !(lflag
& LS_SHOW_ALL
))
709 tmp
= path_append(path
, d
[n
]->filename
);
710 fname
= path_strip(tmp
, strip_path
);
713 if (lflag
& LS_LONG_VIEW
) {
714 if (lflag
& LS_NUMERIC_VIEW
) {
718 memset(&sb
, 0, sizeof(sb
));
719 attrib_to_stat(&d
[n
]->a
, &sb
);
720 lname
= ls_file(fname
, &sb
, 1);
721 printf("%s\n", lname
);
724 printf("%s\n", d
[n
]->longname
);
726 printf("%-*s", colspace
, fname
);
737 if (!(lflag
& LS_LONG_VIEW
) && (c
!= 1))
740 free_sftp_dirents(d
);
744 /* sftp ls.1 replacement which handles path globs */
746 do_globbed_ls(struct sftp_conn
*conn
, char *path
, char *strip_path
,
750 int i
, c
= 1, colspace
= 0, columns
= 1;
753 memset(&g
, 0, sizeof(g
));
755 if (remote_glob(conn
, path
, GLOB_MARK
|GLOB_NOCHECK
|GLOB_BRACE
,
756 NULL
, &g
) || (g
.gl_pathc
&& !g
.gl_matchc
)) {
759 error("Can't ls: \"%s\" not found", path
);
767 * If the glob returns a single match and it is a directory,
768 * then just list its contents.
770 if (g
.gl_matchc
== 1) {
771 if ((a
= do_lstat(conn
, g
.gl_pathv
[0], 1)) == NULL
) {
775 if ((a
->flags
& SSH2_FILEXFER_ATTR_PERMISSIONS
) &&
779 err
= do_ls_dir(conn
, g
.gl_pathv
[0], strip_path
, lflag
);
785 if (!(lflag
& LS_SHORT_VIEW
)) {
786 int m
= 0, width
= 80;
789 /* Count entries for sort and find longest filename */
790 for (i
= 0; g
.gl_pathv
[i
]; i
++)
791 m
= MAX(m
, strlen(g
.gl_pathv
[i
]));
793 if (ioctl(fileno(stdin
), TIOCGWINSZ
, &ws
) != -1)
796 columns
= width
/ (m
+ 2);
797 columns
= MAX(columns
, 1);
798 colspace
= width
/ columns
;
801 for (i
= 0; g
.gl_pathv
[i
] && !interrupted
; i
++, a
= NULL
) {
804 fname
= path_strip(g
.gl_pathv
[i
], strip_path
);
806 if (lflag
& LS_LONG_VIEW
) {
811 * XXX: this is slow - 1 roundtrip per path
812 * A solution to this is to fork glob() and
813 * build a sftp specific version which keeps the
814 * attribs (which currently get thrown away)
815 * that the server returns as well as the filenames.
817 memset(&sb
, 0, sizeof(sb
));
819 a
= do_lstat(conn
, g
.gl_pathv
[i
], 1);
821 attrib_to_stat(a
, &sb
);
822 lname
= ls_file(fname
, &sb
, 1);
823 printf("%s\n", lname
);
826 printf("%-*s", colspace
, fname
);
836 if (!(lflag
& LS_LONG_VIEW
) && (c
!= 1))
847 parse_args(const char **cpp
, int *pflag
, int *lflag
, int *iflag
,
848 unsigned long *n_arg
, char **path1
, char **path2
)
850 const char *cmd
, *cp
= *cpp
;
856 /* Skip leading whitespace */
857 cp
= cp
+ strspn(cp
, WHITESPACE
);
859 /* Ignore blank lines and lines which begin with comment '#' char */
860 if (*cp
== '\0' || *cp
== '#')
863 /* Check for leading '-' (disable error processing) */
870 /* Figure out which command we have */
871 for (i
= 0; cmds
[i
].c
; i
++) {
872 int cmdlen
= strlen(cmds
[i
].c
);
874 /* Check for command followed by whitespace */
875 if (!strncasecmp(cp
, cmds
[i
].c
, cmdlen
) &&
876 strchr(WHITESPACE
, cp
[cmdlen
])) {
878 cp
= cp
+ strspn(cp
, WHITESPACE
);
889 } else if (cmdnum
== -1) {
890 error("Invalid command.");
894 /* Get arguments and parse flags */
895 *lflag
= *pflag
= *n_arg
= 0;
896 *path1
= *path2
= NULL
;
900 if (parse_getput_flags(&cp
, pflag
))
902 /* Get first pathname (mandatory) */
903 if (get_pathname(&cp
, path1
))
905 if (*path1
== NULL
) {
906 error("You must specify at least one path after a "
910 /* Try to get second pathname (optional) */
911 if (get_pathname(&cp
, path2
))
916 if (get_pathname(&cp
, path1
))
918 if (get_pathname(&cp
, path2
))
920 if (!*path1
|| !*path2
) {
921 error("You must specify two paths after a %s "
932 /* Get pathname (mandatory) */
933 if (get_pathname(&cp
, path1
))
935 if (*path1
== NULL
) {
936 error("You must specify a path after a %s command.",
942 if (parse_ls_flags(&cp
, lflag
))
944 /* Path is optional */
945 if (get_pathname(&cp
, path1
))
950 /* Uses the rest of the line */
958 /* Get numeric arg (mandatory) */
959 l
= strtol(cp
, &cp2
, base
);
960 if (cp2
== cp
|| ((l
== LONG_MIN
|| l
== LONG_MAX
) &&
961 errno
== ERANGE
) || l
< 0) {
962 error("You must supply a numeric argument "
963 "to the %s command.", cmd
);
968 if (cmdnum
== I_LUMASK
&& strchr(WHITESPACE
, *cp
))
970 if (cmdnum
== I_LUMASK
|| !strchr(WHITESPACE
, *cp
)) {
971 error("You must supply a numeric argument "
972 "to the %s command.", cmd
);
975 cp
+= strspn(cp
, WHITESPACE
);
977 /* Get pathname (mandatory) */
978 if (get_pathname(&cp
, path1
))
980 if (*path1
== NULL
) {
981 error("You must specify a path after a %s command.",
994 fatal("Command not implemented");
1002 parse_dispatch_command(struct sftp_conn
*conn
, const char *cmd
, char **pwd
,
1005 char *path1
, *path2
, *tmp
;
1006 int pflag
, lflag
, iflag
, cmdnum
, i
;
1007 unsigned long n_arg
;
1009 char path_buf
[MAXPATHLEN
];
1013 path1
= path2
= NULL
;
1014 cmdnum
= parse_args(&cmd
, &pflag
, &lflag
, &iflag
, &n_arg
,
1020 memset(&g
, 0, sizeof(g
));
1022 /* Perform command */
1028 /* Unrecognized command */
1032 err
= process_get(conn
, path1
, path2
, *pwd
, pflag
);
1035 err
= process_put(conn
, path1
, path2
, *pwd
, pflag
);
1038 path1
= make_absolute(path1
, *pwd
);
1039 path2
= make_absolute(path2
, *pwd
);
1040 err
= do_rename(conn
, path1
, path2
);
1043 path2
= make_absolute(path2
, *pwd
);
1044 err
= do_symlink(conn
, path1
, path2
);
1047 path1
= make_absolute(path1
, *pwd
);
1048 remote_glob(conn
, path1
, GLOB_NOCHECK
, NULL
, &g
);
1049 for (i
= 0; g
.gl_pathv
[i
] && !interrupted
; i
++) {
1050 printf("Removing %s\n", g
.gl_pathv
[i
]);
1051 err
= do_rm(conn
, g
.gl_pathv
[i
]);
1052 if (err
!= 0 && err_abort
)
1057 path1
= make_absolute(path1
, *pwd
);
1059 a
.flags
|= SSH2_FILEXFER_ATTR_PERMISSIONS
;
1061 err
= do_mkdir(conn
, path1
, &a
);
1064 path1
= make_absolute(path1
, *pwd
);
1065 err
= do_rmdir(conn
, path1
);
1068 path1
= make_absolute(path1
, *pwd
);
1069 if ((tmp
= do_realpath(conn
, path1
)) == NULL
) {
1073 if ((aa
= do_stat(conn
, tmp
, 0)) == NULL
) {
1078 if (!(aa
->flags
& SSH2_FILEXFER_ATTR_PERMISSIONS
)) {
1079 error("Can't change directory: Can't check target");
1084 if (!S_ISDIR(aa
->perm
)) {
1085 error("Can't change directory: \"%s\" is not "
1086 "a directory", tmp
);
1096 do_globbed_ls(conn
, *pwd
, *pwd
, lflag
);
1100 /* Strip pwd off beginning of non-absolute paths */
1105 path1
= make_absolute(path1
, *pwd
);
1106 err
= do_globbed_ls(conn
, path1
, tmp
, lflag
);
1109 if (chdir(path1
) == -1) {
1110 error("Couldn't change local directory to "
1111 "\"%s\": %s", path1
, strerror(errno
));
1116 if (mkdir(path1
, 0777) == -1) {
1117 error("Couldn't create local directory "
1118 "\"%s\": %s", path1
, strerror(errno
));
1126 local_do_shell(cmd
);
1130 printf("Local umask: %03lo\n", n_arg
);
1133 path1
= make_absolute(path1
, *pwd
);
1135 a
.flags
|= SSH2_FILEXFER_ATTR_PERMISSIONS
;
1137 remote_glob(conn
, path1
, GLOB_NOCHECK
, NULL
, &g
);
1138 for (i
= 0; g
.gl_pathv
[i
] && !interrupted
; i
++) {
1139 printf("Changing mode on %s\n", g
.gl_pathv
[i
]);
1140 err
= do_setstat(conn
, g
.gl_pathv
[i
], &a
);
1141 if (err
!= 0 && err_abort
)
1147 path1
= make_absolute(path1
, *pwd
);
1148 remote_glob(conn
, path1
, GLOB_NOCHECK
, NULL
, &g
);
1149 for (i
= 0; g
.gl_pathv
[i
] && !interrupted
; i
++) {
1150 if (!(aa
= do_stat(conn
, g
.gl_pathv
[i
], 0))) {
1151 if (err
!= 0 && err_abort
)
1156 if (!(aa
->flags
& SSH2_FILEXFER_ATTR_UIDGID
)) {
1157 error("Can't get current ownership of "
1158 "remote file \"%s\"", g
.gl_pathv
[i
]);
1159 if (err
!= 0 && err_abort
)
1164 aa
->flags
&= SSH2_FILEXFER_ATTR_UIDGID
;
1165 if (cmdnum
== I_CHOWN
) {
1166 printf("Changing owner on %s\n", g
.gl_pathv
[i
]);
1169 printf("Changing group on %s\n", g
.gl_pathv
[i
]);
1172 err
= do_setstat(conn
, g
.gl_pathv
[i
], aa
);
1173 if (err
!= 0 && err_abort
)
1178 printf("Remote working directory: %s\n", *pwd
);
1181 if (!getcwd(path_buf
, sizeof(path_buf
))) {
1182 error("Couldn't get local cwd: %s", strerror(errno
));
1186 printf("Local working directory: %s\n", path_buf
);
1189 /* Processed below */
1195 printf("SFTP protocol version %u\n", sftp_proto_version(conn
));
1198 showprogress
= !showprogress
;
1200 printf("Progress meter enabled\n");
1202 printf("Progress meter disabled\n");
1205 fatal("%d is not implemented", cmdnum
);
1215 /* If an unignored error occurs in batch mode we should abort. */
1216 if (err_abort
&& err
!= 0)
1218 else if (cmdnum
== I_QUIT
)
1226 prompt(EditLine
*el
)
1233 interactive_loop(int fd_in
, int fd_out
, char *file1
, char *file2
)
1238 struct sftp_conn
*conn
;
1240 EditLine
*el
= NULL
;
1244 extern char *__progname
;
1246 if (!batchmode
&& isatty(STDIN_FILENO
)) {
1247 if ((el
= el_init(__progname
, stdin
, stdout
, stderr
)) == NULL
)
1248 fatal("Couldn't initialise editline");
1249 if ((hl
= history_init()) == NULL
)
1250 fatal("Couldn't initialise editline history");
1251 history(hl
, &hev
, H_SETSIZE
, 100);
1252 el_set(el
, EL_HIST
, history
, hl
);
1254 el_set(el
, EL_PROMPT
, prompt
);
1255 el_set(el
, EL_EDITOR
, "emacs");
1256 el_set(el
, EL_TERMINAL
, NULL
);
1257 el_set(el
, EL_SIGNAL
, 1);
1258 el_source(el
, NULL
);
1260 #endif /* USE_LIBEDIT */
1262 conn
= do_init(fd_in
, fd_out
, copy_buffer_len
, num_requests
);
1264 fatal("Couldn't initialise connection to server");
1266 pwd
= do_realpath(conn
, ".");
1270 if (file1
!= NULL
) {
1271 dir
= xstrdup(file1
);
1272 dir
= make_absolute(dir
, pwd
);
1274 if (remote_is_dir(conn
, dir
) && file2
== NULL
) {
1275 printf("Changing to: %s\n", dir
);
1276 snprintf(cmd
, sizeof cmd
, "cd \"%s\"", dir
);
1277 if (parse_dispatch_command(conn
, cmd
, &pwd
, 1) != 0) {
1284 snprintf(cmd
, sizeof cmd
, "get %s", dir
);
1286 snprintf(cmd
, sizeof cmd
, "get %s %s", dir
,
1289 err
= parse_dispatch_command(conn
, cmd
, &pwd
, 1);
1298 setvbuf(stdout
, NULL
, _IOLBF
, 0);
1299 setvbuf(infile
, NULL
, _IOLBF
, 0);
1309 signal(SIGINT
, SIG_IGN
);
1313 if (fgets(cmd
, sizeof(cmd
), infile
) == NULL
) {
1317 if (batchmode
) /* Echo command */
1324 if ((line
= el_gets(el
, &count
)) == NULL
|| count
<= 0)
1326 history(hl
, &hev
, H_ENTER
, line
);
1327 if (strlcpy(cmd
, line
, sizeof(cmd
)) >= sizeof(cmd
)) {
1328 fprintf(stderr
, "Error: input line too long\n");
1331 #endif /* USE_LIBEDIT */
1334 cp
= strrchr(cmd
, '\n');
1338 /* Handle user interrupts gracefully during commands */
1340 signal(SIGINT
, cmd_interrupt
);
1342 err
= parse_dispatch_command(conn
, cmd
, &pwd
, batchmode
);
1348 /* err == 1 signifies normal "quit" exit */
1349 return (err
>= 0 ? 0 : -1);
1353 connect_to_server(char *path
, char **args
, int *in
, int *out
)
1358 int pin
[2], pout
[2];
1360 if ((pipe(pin
) == -1) || (pipe(pout
) == -1))
1361 fatal("pipe: %s", strerror(errno
));
1366 #else /* USE_PIPES */
1369 if (socketpair(AF_UNIX
, SOCK_STREAM
, 0, inout
) == -1)
1370 fatal("socketpair: %s", strerror(errno
));
1371 *in
= *out
= inout
[0];
1372 c_in
= c_out
= inout
[1];
1373 #endif /* USE_PIPES */
1375 if ((sshpid
= fork()) == -1)
1376 fatal("fork: %s", strerror(errno
));
1377 else if (sshpid
== 0) {
1378 if ((dup2(c_in
, STDIN_FILENO
) == -1) ||
1379 (dup2(c_out
, STDOUT_FILENO
) == -1)) {
1380 fprintf(stderr
, "dup2: %s\n", strerror(errno
));
1389 * The underlying ssh is in the same process group, so we must
1390 * ignore SIGINT if we want to gracefully abort commands,
1391 * otherwise the signal will make it to the ssh process and
1394 signal(SIGINT
, SIG_IGN
);
1396 fprintf(stderr
, "exec: %s: %s\n", path
, strerror(errno
));
1400 signal(SIGTERM
, killchild
);
1401 signal(SIGINT
, killchild
);
1402 signal(SIGHUP
, killchild
);
1410 extern char *__progname
;
1413 "usage: %s [-1Cv] [-B buffer_size] [-b batchfile] [-F ssh_config]\n"
1414 " [-o ssh_option] [-P sftp_server_path] [-R num_requests]\n"
1415 " [-S program] [-s subsystem | sftp_server] host\n"
1416 " %s [[user@]host[:file [file]]]\n"
1417 " %s [[user@]host[:dir[/]]]\n"
1418 " %s -b batchfile [user@]host\n", __progname
, __progname
, __progname
, __progname
);
1423 main(int argc
, char **argv
)
1425 int in
, out
, ch
, err
;
1426 char *host
, *userhost
, *cp
, *file2
= NULL
;
1427 int debug_level
= 0, sshver
= 2;
1428 char *file1
= NULL
, *sftp_server
= NULL
;
1429 char *ssh_program
= _PATH_SSH_PROGRAM
, *sftp_direct
= NULL
;
1430 LogLevel ll
= SYSLOG_LEVEL_INFO
;
1433 extern char *optarg
;
1435 __progname
= ssh_get_progname(argv
[0]);
1437 addargs(&args
, "ssh"); /* overwritten with ssh_program */
1438 addargs(&args
, "-oForwardX11 no");
1439 addargs(&args
, "-oForwardAgent no");
1440 addargs(&args
, "-oClearAllForwardings yes");
1442 ll
= SYSLOG_LEVEL_INFO
;
1445 while ((ch
= getopt(argc
, argv
, "1hvCo:s:S:b:B:F:P:R:")) != -1) {
1448 addargs(&args
, "-C");
1451 if (debug_level
< 3) {
1452 addargs(&args
, "-v");
1453 ll
= SYSLOG_LEVEL_DEBUG1
+ debug_level
;
1459 addargs(&args
, "-%c%s", ch
, optarg
);
1463 if (sftp_server
== NULL
)
1464 sftp_server
= _PATH_SFTP_SERVER
;
1467 sftp_server
= optarg
;
1470 ssh_program
= optarg
;
1474 fatal("Batch file already specified.");
1476 /* Allow "-" as stdin */
1477 if (strcmp(optarg
, "-") != 0 &&
1478 (infile
= fopen(optarg
, "r")) == NULL
)
1479 fatal("%s (%s).", strerror(errno
), optarg
);
1482 addargs(&args
, "-obatchmode yes");
1485 sftp_direct
= optarg
;
1488 copy_buffer_len
= strtol(optarg
, &cp
, 10);
1489 if (copy_buffer_len
== 0 || *cp
!= '\0')
1490 fatal("Invalid buffer size \"%s\"", optarg
);
1493 num_requests
= strtol(optarg
, &cp
, 10);
1494 if (num_requests
== 0 || *cp
!= '\0')
1495 fatal("Invalid number of requests \"%s\"",
1504 if (!isatty(STDERR_FILENO
))
1507 log_init(argv
[0], ll
, SYSLOG_FACILITY_USER
, 1);
1509 if (sftp_direct
== NULL
) {
1510 if (optind
== argc
|| argc
> (optind
+ 2))
1513 userhost
= xstrdup(argv
[optind
]);
1514 file2
= argv
[optind
+1];
1516 if ((host
= strrchr(userhost
, '@')) == NULL
)
1521 fprintf(stderr
, "Missing username\n");
1524 addargs(&args
, "-l%s",userhost
);
1527 if ((cp
= colon(host
)) != NULL
) {
1532 host
= cleanhostname(host
);
1534 fprintf(stderr
, "Missing hostname\n");
1538 addargs(&args
, "-oProtocol %d", sshver
);
1540 /* no subsystem if the server-spec contains a '/' */
1541 if (sftp_server
== NULL
|| strchr(sftp_server
, '/') == NULL
)
1542 addargs(&args
, "-s");
1544 addargs(&args
, "%s", host
);
1545 addargs(&args
, "%s", (sftp_server
!= NULL
?
1546 sftp_server
: "sftp"));
1547 args
.list
[0] = ssh_program
;
1550 fprintf(stderr
, "Connecting to %s...\n", host
);
1551 connect_to_server(ssh_program
, args
.list
, &in
, &out
);
1554 addargs(&args
, "sftp-server");
1557 fprintf(stderr
, "Attaching to %s...\n", sftp_direct
);
1558 connect_to_server(sftp_direct
, args
.list
, &in
, &out
);
1561 err
= interactive_loop(in
, out
, file1
, file2
);
1563 #if !defined(USE_PIPES)
1564 shutdown(in
, SHUT_RDWR
);
1565 shutdown(out
, SHUT_RDWR
);
1573 while (waitpid(sshpid
, NULL
, 0) == -1)
1575 fatal("Couldn't wait for ssh process: %s",
1578 exit(err
== 0 ? 0 : 1);