2 * Copyright (c) 2001,2002 Damien Miller. All rights reserved.
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
7 * 1. Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * 2. Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
13 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
14 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
15 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
16 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
17 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
18 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
19 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
20 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
21 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
22 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25 /* XXX: recursive operations */
28 RCSID("$OpenBSD: sftp-int.c,v 1.67 2004/01/23 17:57:48 mouring Exp $");
33 #include "pathnames.h"
36 #include "sftp-common.h"
37 #include "sftp-glob.h"
38 #include "sftp-client.h"
41 /* File to read commands from */
44 /* Are we in batchfile mode? */
47 /* Size of buffer used when copying files */
48 extern size_t copy_buffer_len;
50 /* Number of concurrent outstanding requests */
51 extern int num_requests;
53 /* This is set to 0 if the progressmeter is not desired. */
56 /* Separators for interactive commands */
57 #define WHITESPACE " \t\r\n"
59 /* Define what type of ls view (0 - multi-column) */
60 #define LONG_VIEW 1 /* Full view ala ls -l */
61 #define SHORT_VIEW 2 /* Single row view ala ls -1 */
63 /* Commands for interactive mode */
93 static const struct CMD cmds[] = {
106 { "lchdir", I_LCHDIR },
108 { "lmkdir", I_LMKDIR },
112 { "lumask", I_LUMASK },
113 { "mkdir", I_MKDIR },
114 { "progress", I_PROGRESS },
119 { "rename", I_RENAME },
121 { "rmdir", I_RMDIR },
122 { "symlink", I_SYMLINK },
123 { "version", I_VERSION },
132 printf("Available commands:\n");
133 printf("cd path Change remote directory to 'path'\n");
134 printf("lcd path Change local directory to 'path'\n");
135 printf("chgrp grp path Change group of file 'path' to 'grp'\n");
136 printf("chmod mode path Change permissions of file 'path' to 'mode'\n");
137 printf("chown own path Change owner of file 'path' to 'own'\n");
138 printf("help Display this help text\n");
139 printf("get remote-path [local-path] Download file\n");
140 printf("lls [ls-options [path]] Display local directory listing\n");
141 printf("ln oldpath newpath Symlink remote file\n");
142 printf("lmkdir path Create local directory\n");
143 printf("lpwd Print local working directory\n");
144 printf("ls [path] Display remote directory listing\n");
145 printf("lumask umask Set local umask to 'umask'\n");
146 printf("mkdir path Create remote directory\n");
147 printf("progress Toggle display of progress meter\n");
148 printf("put local-path [remote-path] Upload file\n");
149 printf("pwd Display remote working directory\n");
150 printf("exit Quit sftp\n");
151 printf("quit Quit sftp\n");
152 printf("rename oldpath newpath Rename remote file\n");
153 printf("rmdir path Remove remote directory\n");
154 printf("rm path Delete remote file\n");
155 printf("symlink oldpath newpath Symlink remote file\n");
156 printf("version Show SFTP version\n");
157 printf("!command Execute 'command' in local shell\n");
158 printf("! Escape to local shell\n");
159 printf("? Synonym for help\n");
163 local_do_shell(const char *args)
172 if ((shell = getenv("SHELL")) == NULL)
173 shell = _PATH_BSHELL;
175 if ((pid = fork()) == -1)
176 fatal("Couldn't fork: %s", strerror(errno));
179 /* XXX: child has pipe fds to ssh subproc open - issue? */
181 debug3("Executing %s -c \"%s\"", shell, args);
182 execl(shell, shell, "-c", args, (char *)NULL);
184 debug3("Executing %s", shell);
185 execl(shell, shell, (char *)NULL);
187 fprintf(stderr, "Couldn't execute \"%s\": %s\n", shell,
191 while (waitpid(pid, &status, 0) == -1)
193 fatal("Couldn't wait for child: %s", strerror(errno));
194 if (!WIFEXITED(status))
195 error("Shell exited abormally");
196 else if (WEXITSTATUS(status))
197 error("Shell exited with status %d", WEXITSTATUS(status));
201 local_do_ls(const char *args)
204 local_do_shell(_PATH_LS);
206 int len = strlen(_PATH_LS " ") + strlen(args) + 1;
207 char *buf = xmalloc(len);
209 /* XXX: quoting - rip quoting code from ftp? */
210 snprintf(buf, len, _PATH_LS " %s", args);
216 /* Strip one path (usually the pwd) from the start of another */
218 path_strip(char *path, char *strip)
223 return (xstrdup(path));
226 if (strip != NULL && strncmp(path, strip, len) == 0) {
227 if (strip[len - 1] != '/' && path[len] == '/')
229 return (xstrdup(path + len));
232 return (xstrdup(path));
236 path_append(char *p1, char *p2)
239 int len = strlen(p1) + strlen(p2) + 2;
242 strlcpy(ret, p1, len);
243 if (p1[strlen(p1) - 1] != '/')
244 strlcat(ret, "/", len);
245 strlcat(ret, p2, len);
251 make_absolute(char *p, char *pwd)
256 if (p && p[0] != '/') {
257 abs = path_append(pwd, p);
265 infer_path(const char *p, char **ifp)
269 cp = strrchr(p, '/');
276 error("Invalid path");
280 *ifp = xstrdup(cp + 1);
285 parse_getput_flags(const char **cpp, int *pflag)
287 const char *cp = *cpp;
289 /* Check for flags */
290 if (cp[0] == '-' && cp[1] && strchr(WHITESPACE, cp[2])) {
297 error("Invalid flag -%c", cp[1]);
301 *cpp = cp + strspn(cp, WHITESPACE);
308 parse_ls_flags(const char **cpp, int *lflag)
310 const char *cp = *cpp;
312 /* Check for flags */
313 if (cp++[0] == '-') {
314 for(; strchr(WHITESPACE, *cp) == NULL; cp++) {
323 error("Invalid flag -%c", *cp);
327 *cpp = cp + strspn(cp, WHITESPACE);
334 get_pathname(const char **cpp, char **path)
336 const char *cp = *cpp, *end;
340 cp += strspn(cp, WHITESPACE);
347 *path = xmalloc(strlen(cp) + 1);
349 /* Check for quoted filenames */
350 if (*cp == '\"' || *cp == '\'') {
353 /* Search for terminating quote, unescape some chars */
354 for (i = j = 0; i <= strlen(cp); i++) {
355 if (cp[i] == quot) { /* Found quote */
360 if (cp[i] == '\0') { /* End of string */
361 error("Unterminated quote");
364 if (cp[i] == '\\') { /* Escaped characters */
366 if (cp[i] != '\'' && cp[i] != '\"' &&
368 error("Bad escaped character '\%c'",
373 (*path)[j++] = cp[i];
377 error("Empty quotes");
380 *cpp = cp + i + strspn(cp + i, WHITESPACE);
382 /* Read to end of filename */
383 end = strpbrk(cp, WHITESPACE);
385 end = strchr(cp, '\0');
386 *cpp = end + strspn(end, WHITESPACE);
388 memcpy(*path, cp, end - cp);
389 (*path)[end - cp] = '\0';
404 /* XXX: report errors? */
405 if (stat(path, &sb) == -1)
408 return(sb.st_mode & S_IFDIR);
416 if (stat(path, &sb) == -1)
417 fatal("stat %s: %s", path, strerror(errno));
419 return(S_ISREG(sb.st_mode));
423 remote_is_dir(struct sftp_conn *conn, char *path)
427 /* XXX: report errors? */
428 if ((a = do_stat(conn, path, 1)) == NULL)
430 if (!(a->flags & SSH2_FILEXFER_ATTR_PERMISSIONS))
432 return(a->perm & S_IFDIR);
436 process_get(struct sftp_conn *conn, char *src, char *dst, char *pwd, int pflag)
438 char *abs_src = NULL;
439 char *abs_dst = NULL;
445 abs_src = xstrdup(src);
446 abs_src = make_absolute(abs_src, pwd);
448 memset(&g, 0, sizeof(g));
449 debug3("Looking up %s", abs_src);
450 if (remote_glob(conn, abs_src, 0, NULL, &g)) {
451 error("File \"%s\" not found.", abs_src);
456 /* If multiple matches, dst must be a directory or unspecified */
457 if (g.gl_matchc > 1 && dst && !is_dir(dst)) {
458 error("Multiple files match, but \"%s\" is not a directory",
464 for (i = 0; g.gl_pathv[i]; i++) {
465 if (infer_path(g.gl_pathv[i], &tmp)) {
470 if (g.gl_matchc == 1 && dst) {
471 /* If directory specified, append filename */
473 if (infer_path(g.gl_pathv[0], &tmp)) {
477 abs_dst = path_append(dst, tmp);
480 abs_dst = xstrdup(dst);
482 abs_dst = path_append(dst, tmp);
487 printf("Fetching %s to %s\n", g.gl_pathv[i], abs_dst);
488 if (do_download(conn, g.gl_pathv[i], abs_dst, pflag) == -1)
503 process_put(struct sftp_conn *conn, char *src, char *dst, char *pwd, int pflag)
505 char *tmp_dst = NULL;
506 char *abs_dst = NULL;
513 tmp_dst = xstrdup(dst);
514 tmp_dst = make_absolute(tmp_dst, pwd);
517 memset(&g, 0, sizeof(g));
518 debug3("Looking up %s", src);
519 if (glob(src, 0, NULL, &g)) {
520 error("File \"%s\" not found.", src);
525 /* If multiple matches, dst may be directory or unspecified */
526 if (g.gl_matchc > 1 && tmp_dst && !remote_is_dir(conn, tmp_dst)) {
527 error("Multiple files match, but \"%s\" is not a directory",
533 for (i = 0; g.gl_pathv[i]; i++) {
534 if (!is_reg(g.gl_pathv[i])) {
535 error("skipping non-regular file %s",
539 if (infer_path(g.gl_pathv[i], &tmp)) {
544 if (g.gl_matchc == 1 && tmp_dst) {
545 /* If directory specified, append filename */
546 if (remote_is_dir(conn, tmp_dst)) {
547 if (infer_path(g.gl_pathv[0], &tmp)) {
551 abs_dst = path_append(tmp_dst, tmp);
554 abs_dst = xstrdup(tmp_dst);
556 } else if (tmp_dst) {
557 abs_dst = path_append(tmp_dst, tmp);
560 abs_dst = make_absolute(tmp, pwd);
562 printf("Uploading %s to %s\n", g.gl_pathv[i], abs_dst);
563 if (do_upload(conn, g.gl_pathv[i], abs_dst, pflag) == -1)
577 sdirent_comp(const void *aa, const void *bb)
579 SFTP_DIRENT *a = *(SFTP_DIRENT **)aa;
580 SFTP_DIRENT *b = *(SFTP_DIRENT **)bb;
582 return (strcmp(a->filename, b->filename));
585 /* sftp ls.1 replacement for directories */
587 do_ls_dir(struct sftp_conn *conn, char *path, char *strip_path, int lflag)
589 int n, c = 1, colspace = 0, columns = 1;
592 if ((n = do_readdir(conn, path, &d)) != 0)
595 if (!(lflag & SHORT_VIEW)) {
596 int m = 0, width = 80;
600 /* Count entries for sort and find longest filename */
601 for (n = 0; d[n] != NULL; n++)
602 m = MAX(m, strlen(d[n]->filename));
604 /* Add any subpath that also needs to be counted */
605 tmp = path_strip(path, strip_path);
609 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) != -1)
612 columns = width / (m + 2);
613 columns = MAX(columns, 1);
614 colspace = width / columns;
615 colspace = MIN(colspace, width);
618 qsort(d, n, sizeof(*d), sdirent_comp);
620 for (n = 0; d[n] != NULL; n++) {
623 tmp = path_append(path, d[n]->filename);
624 fname = path_strip(tmp, strip_path);
627 if (lflag & LONG_VIEW) {
631 memset(&sb, 0, sizeof(sb));
632 attrib_to_stat(&d[n]->a, &sb);
633 lname = ls_file(fname, &sb, 1);
634 printf("%s\n", lname);
637 printf("%-*s", colspace, fname);
648 if (!(lflag & LONG_VIEW) && (c != 1))
651 free_sftp_dirents(d);
655 /* sftp ls.1 replacement which handles path globs */
657 do_globbed_ls(struct sftp_conn *conn, char *path, char *strip_path,
661 int i, c = 1, colspace = 0, columns = 1;
664 memset(&g, 0, sizeof(g));
666 if (remote_glob(conn, path, GLOB_MARK|GLOB_NOCHECK|GLOB_BRACE,
668 error("Can't ls: \"%s\" not found", path);
673 * If the glob returns a single match, which is the same as the
674 * input glob, and it is a directory, then just list its contents
676 if (g.gl_pathc == 1 &&
677 strncmp(path, g.gl_pathv[0], strlen(g.gl_pathv[0]) - 1) == 0) {
678 if ((a = do_lstat(conn, path, 1)) == NULL) {
682 if ((a->flags & SSH2_FILEXFER_ATTR_PERMISSIONS) &&
685 return (do_ls_dir(conn, path, strip_path, lflag));
689 if (!(lflag & SHORT_VIEW)) {
690 int m = 0, width = 80;
693 /* Count entries for sort and find longest filename */
694 for (i = 0; g.gl_pathv[i]; i++)
695 m = MAX(m, strlen(g.gl_pathv[i]));
697 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) != -1)
700 columns = width / (m + 2);
701 columns = MAX(columns, 1);
702 colspace = width / columns;
705 for (i = 0; g.gl_pathv[i]; i++) {
708 fname = path_strip(g.gl_pathv[i], strip_path);
710 if (lflag & LONG_VIEW) {
715 * XXX: this is slow - 1 roundtrip per path
716 * A solution to this is to fork glob() and
717 * build a sftp specific version which keeps the
718 * attribs (which currently get thrown away)
719 * that the server returns as well as the filenames.
721 memset(&sb, 0, sizeof(sb));
722 a = do_lstat(conn, g.gl_pathv[i], 1);
724 attrib_to_stat(a, &sb);
725 lname = ls_file(fname, &sb, 1);
726 printf("%s\n", lname);
729 printf("%-*s", colspace, fname);
739 if (!(lflag & LONG_VIEW) && (c != 1))
749 parse_args(const char **cpp, int *pflag, int *lflag, int *iflag,
750 unsigned long *n_arg, char **path1, char **path2)
752 const char *cmd, *cp = *cpp;
758 /* Skip leading whitespace */
759 cp = cp + strspn(cp, WHITESPACE);
761 /* Ignore blank lines and lines which begin with comment '#' char */
762 if (*cp == '\0' || *cp == '#')
765 /* Check for leading '-' (disable error processing) */
772 /* Figure out which command we have */
773 for (i = 0; cmds[i].c; i++) {
774 int cmdlen = strlen(cmds[i].c);
776 /* Check for command followed by whitespace */
777 if (!strncasecmp(cp, cmds[i].c, cmdlen) &&
778 strchr(WHITESPACE, cp[cmdlen])) {
780 cp = cp + strspn(cp, WHITESPACE);
791 } else if (cmdnum == -1) {
792 error("Invalid command.");
796 /* Get arguments and parse flags */
797 *lflag = *pflag = *n_arg = 0;
798 *path1 = *path2 = NULL;
802 if (parse_getput_flags(&cp, pflag))
804 /* Get first pathname (mandatory) */
805 if (get_pathname(&cp, path1))
807 if (*path1 == NULL) {
808 error("You must specify at least one path after a "
812 /* Try to get second pathname (optional) */
813 if (get_pathname(&cp, path2))
818 if (get_pathname(&cp, path1))
820 if (get_pathname(&cp, path2))
822 if (!*path1 || !*path2) {
823 error("You must specify two paths after a %s "
834 /* Get pathname (mandatory) */
835 if (get_pathname(&cp, path1))
837 if (*path1 == NULL) {
838 error("You must specify a path after a %s command.",
844 if (parse_ls_flags(&cp, lflag))
846 /* Path is optional */
847 if (get_pathname(&cp, path1))
852 /* Uses the rest of the line */
860 /* Get numeric arg (mandatory) */
861 l = strtol(cp, &cp2, base);
862 if (cp2 == cp || ((l == LONG_MIN || l == LONG_MAX) &&
863 errno == ERANGE) || l < 0) {
864 error("You must supply a numeric argument "
865 "to the %s command.", cmd);
870 if (cmdnum == I_LUMASK && strchr(WHITESPACE, *cp))
872 if (cmdnum == I_LUMASK || !strchr(WHITESPACE, *cp)) {
873 error("You must supply a numeric argument "
874 "to the %s command.", cmd);
877 cp += strspn(cp, WHITESPACE);
879 /* Get pathname (mandatory) */
880 if (get_pathname(&cp, path1))
882 if (*path1 == NULL) {
883 error("You must specify a path after a %s command.",
896 fatal("Command not implemented");
904 parse_dispatch_command(struct sftp_conn *conn, const char *cmd, char **pwd,
907 char *path1, *path2, *tmp;
908 int pflag, lflag, iflag, cmdnum, i;
911 char path_buf[MAXPATHLEN];
915 path1 = path2 = NULL;
916 cmdnum = parse_args(&cmd, &pflag, &lflag, &iflag, &n_arg,
922 memset(&g, 0, sizeof(g));
924 /* Perform command */
930 /* Unrecognized command */
934 err = process_get(conn, path1, path2, *pwd, pflag);
937 err = process_put(conn, path1, path2, *pwd, pflag);
940 path1 = make_absolute(path1, *pwd);
941 path2 = make_absolute(path2, *pwd);
942 err = do_rename(conn, path1, path2);
945 path2 = make_absolute(path2, *pwd);
946 err = do_symlink(conn, path1, path2);
949 path1 = make_absolute(path1, *pwd);
950 remote_glob(conn, path1, GLOB_NOCHECK, NULL, &g);
951 for (i = 0; g.gl_pathv[i]; i++) {
952 printf("Removing %s\n", g.gl_pathv[i]);
953 err = do_rm(conn, g.gl_pathv[i]);
954 if (err != 0 && err_abort)
959 path1 = make_absolute(path1, *pwd);
961 a.flags |= SSH2_FILEXFER_ATTR_PERMISSIONS;
963 err = do_mkdir(conn, path1, &a);
966 path1 = make_absolute(path1, *pwd);
967 err = do_rmdir(conn, path1);
970 path1 = make_absolute(path1, *pwd);
971 if ((tmp = do_realpath(conn, path1)) == NULL) {
975 if ((aa = do_stat(conn, tmp, 0)) == NULL) {
980 if (!(aa->flags & SSH2_FILEXFER_ATTR_PERMISSIONS)) {
981 error("Can't change directory: Can't check target");
986 if (!S_ISDIR(aa->perm)) {
987 error("Can't change directory: \"%s\" is not "
998 do_globbed_ls(conn, *pwd, *pwd, lflag);
1002 /* Strip pwd off beginning of non-absolute paths */
1007 path1 = make_absolute(path1, *pwd);
1008 err = do_globbed_ls(conn, path1, tmp, lflag);
1011 if (chdir(path1) == -1) {
1012 error("Couldn't change local directory to "
1013 "\"%s\": %s", path1, strerror(errno));
1018 if (mkdir(path1, 0777) == -1) {
1019 error("Couldn't create local directory "
1020 "\"%s\": %s", path1, strerror(errno));
1028 local_do_shell(cmd);
1032 printf("Local umask: %03lo\n", n_arg);
1035 path1 = make_absolute(path1, *pwd);
1037 a.flags |= SSH2_FILEXFER_ATTR_PERMISSIONS;
1039 remote_glob(conn, path1, GLOB_NOCHECK, NULL, &g);
1040 for (i = 0; g.gl_pathv[i]; i++) {
1041 printf("Changing mode on %s\n", g.gl_pathv[i]);
1042 err = do_setstat(conn, g.gl_pathv[i], &a);
1043 if (err != 0 && err_abort)
1049 path1 = make_absolute(path1, *pwd);
1050 remote_glob(conn, path1, GLOB_NOCHECK, NULL, &g);
1051 for (i = 0; g.gl_pathv[i]; i++) {
1052 if (!(aa = do_stat(conn, g.gl_pathv[i], 0))) {
1053 if (err != 0 && err_abort)
1058 if (!(aa->flags & SSH2_FILEXFER_ATTR_UIDGID)) {
1059 error("Can't get current ownership of "
1060 "remote file \"%s\"", g.gl_pathv[i]);
1061 if (err != 0 && err_abort)
1066 aa->flags &= SSH2_FILEXFER_ATTR_UIDGID;
1067 if (cmdnum == I_CHOWN) {
1068 printf("Changing owner on %s\n", g.gl_pathv[i]);
1071 printf("Changing group on %s\n", g.gl_pathv[i]);
1074 err = do_setstat(conn, g.gl_pathv[i], aa);
1075 if (err != 0 && err_abort)
1080 printf("Remote working directory: %s\n", *pwd);
1083 if (!getcwd(path_buf, sizeof(path_buf))) {
1084 error("Couldn't get local cwd: %s", strerror(errno));
1088 printf("Local working directory: %s\n", path_buf);
1091 /* Processed below */
1097 printf("SFTP protocol version %u\n", sftp_proto_version(conn));
1100 showprogress = !showprogress;
1102 printf("Progress meter enabled\n");
1104 printf("Progress meter disabled\n");
1107 fatal("%d is not implemented", cmdnum);
1117 /* If an unignored error occurs in batch mode we should abort. */
1118 if (err_abort && err != 0)
1120 else if (cmdnum == I_QUIT)
1127 interactive_loop(int fd_in, int fd_out, char *file1, char *file2)
1132 struct sftp_conn *conn;
1135 conn = do_init(fd_in, fd_out, copy_buffer_len, num_requests);
1137 fatal("Couldn't initialise connection to server");
1139 pwd = do_realpath(conn, ".");
1143 if (file1 != NULL) {
1144 dir = xstrdup(file1);
1145 dir = make_absolute(dir, pwd);
1147 if (remote_is_dir(conn, dir) && file2 == NULL) {
1148 printf("Changing to: %s\n", dir);
1149 snprintf(cmd, sizeof cmd, "cd \"%s\"", dir);
1150 if (parse_dispatch_command(conn, cmd, &pwd, 1) != 0)
1154 snprintf(cmd, sizeof cmd, "get %s", dir);
1156 snprintf(cmd, sizeof cmd, "get %s %s", dir,
1159 err = parse_dispatch_command(conn, cmd, &pwd, 1);
1168 setvbuf(stdout, NULL, _IOLBF, 0);
1169 setvbuf(infile, NULL, _IOLBF, 0);
1181 /* XXX: use libedit */
1182 if (fgets(cmd, sizeof(cmd), infile) == NULL) {
1187 if (batchmode) /* Echo command */
1190 cp = strrchr(cmd, '\n');
1194 err = parse_dispatch_command(conn, cmd, &pwd, batchmode);
1200 /* err == 1 signifies normal "quit" exit */
1201 return (err >= 0 ? 0 : -1);