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.57 2003/03/05 22:33:43 markus 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 /* Size of buffer used when copying files */
45 extern size_t copy_buffer_len;
47 /* Number of concurrent outstanding requests */
48 extern int num_requests;
50 /* This is set to 0 if the progressmeter is not desired. */
53 /* Seperators for interactive commands */
54 #define WHITESPACE " \t\r\n"
56 /* Commands for interactive mode */
86 static const struct CMD cmds[] = {
99 { "lchdir", I_LCHDIR },
101 { "lmkdir", I_LMKDIR },
105 { "lumask", I_LUMASK },
106 { "mkdir", I_MKDIR },
107 { "progress", I_PROGRESS },
112 { "rename", I_RENAME },
114 { "rmdir", I_RMDIR },
115 { "symlink", I_SYMLINK },
116 { "version", I_VERSION },
125 printf("Available commands:\n");
126 printf("cd path Change remote directory to 'path'\n");
127 printf("lcd path Change local directory to 'path'\n");
128 printf("chgrp grp path Change group of file 'path' to 'grp'\n");
129 printf("chmod mode path Change permissions of file 'path' to 'mode'\n");
130 printf("chown own path Change owner of file 'path' to 'own'\n");
131 printf("help Display this help text\n");
132 printf("get remote-path [local-path] Download file\n");
133 printf("lls [ls-options [path]] Display local directory listing\n");
134 printf("ln oldpath newpath Symlink remote file\n");
135 printf("lmkdir path Create local directory\n");
136 printf("lpwd Print local working directory\n");
137 printf("ls [path] Display remote directory listing\n");
138 printf("lumask umask Set local umask to 'umask'\n");
139 printf("mkdir path Create remote directory\n");
140 printf("progress Toggle display of progress meter\n");
141 printf("put local-path [remote-path] Upload file\n");
142 printf("pwd Display remote working directory\n");
143 printf("exit Quit sftp\n");
144 printf("quit Quit sftp\n");
145 printf("rename oldpath newpath Rename remote file\n");
146 printf("rmdir path Remove remote directory\n");
147 printf("rm path Delete remote file\n");
148 printf("symlink oldpath newpath Symlink remote file\n");
149 printf("version Show SFTP version\n");
150 printf("!command Execute 'command' in local shell\n");
151 printf("! Escape to local shell\n");
152 printf("? Synonym for help\n");
156 local_do_shell(const char *args)
165 if ((shell = getenv("SHELL")) == NULL)
166 shell = _PATH_BSHELL;
168 if ((pid = fork()) == -1)
169 fatal("Couldn't fork: %s", strerror(errno));
172 /* XXX: child has pipe fds to ssh subproc open - issue? */
174 debug3("Executing %s -c \"%s\"", shell, args);
175 execl(shell, shell, "-c", args, (char *)NULL);
177 debug3("Executing %s", shell);
178 execl(shell, shell, (char *)NULL);
180 fprintf(stderr, "Couldn't execute \"%s\": %s\n", shell,
184 while (waitpid(pid, &status, 0) == -1)
186 fatal("Couldn't wait for child: %s", strerror(errno));
187 if (!WIFEXITED(status))
188 error("Shell exited abormally");
189 else if (WEXITSTATUS(status))
190 error("Shell exited with status %d", WEXITSTATUS(status));
194 local_do_ls(const char *args)
197 local_do_shell(_PATH_LS);
199 int len = strlen(_PATH_LS " ") + strlen(args) + 1;
200 char *buf = xmalloc(len);
202 /* XXX: quoting - rip quoting code from ftp? */
203 snprintf(buf, len, _PATH_LS " %s", args);
209 /* Strip one path (usually the pwd) from the start of another */
211 path_strip(char *path, char *strip)
216 return (xstrdup(path));
219 if (strip != NULL && strncmp(path, strip, len) == 0) {
220 if (strip[len - 1] != '/' && path[len] == '/')
222 return (xstrdup(path + len));
225 return (xstrdup(path));
229 path_append(char *p1, char *p2)
232 int len = strlen(p1) + strlen(p2) + 2;
235 strlcpy(ret, p1, len);
236 if (p1[strlen(p1) - 1] != '/')
237 strlcat(ret, "/", len);
238 strlcat(ret, p2, len);
244 make_absolute(char *p, char *pwd)
249 if (p && p[0] != '/') {
250 abs = path_append(pwd, p);
258 infer_path(const char *p, char **ifp)
262 cp = strrchr(p, '/');
269 error("Invalid path");
273 *ifp = xstrdup(cp + 1);
278 parse_getput_flags(const char **cpp, int *pflag)
280 const char *cp = *cpp;
282 /* Check for flags */
283 if (cp[0] == '-' && cp[1] && strchr(WHITESPACE, cp[2])) {
290 error("Invalid flag -%c", cp[1]);
294 *cpp = cp + strspn(cp, WHITESPACE);
301 parse_ls_flags(const char **cpp, int *lflag)
303 const char *cp = *cpp;
305 /* Check for flags */
306 if (cp++[0] == '-') {
307 for(; strchr(WHITESPACE, *cp) == NULL; cp++) {
313 error("Invalid flag -%c", *cp);
317 *cpp = cp + strspn(cp, WHITESPACE);
324 get_pathname(const char **cpp, char **path)
326 const char *cp = *cpp, *end;
330 cp += strspn(cp, WHITESPACE);
337 /* Check for quoted filenames */
338 if (*cp == '\"' || *cp == '\'') {
341 end = strchr(cp, quot);
343 error("Unterminated quote");
347 error("Empty quotes");
350 *cpp = end + 1 + strspn(end + 1, WHITESPACE);
352 /* Read to end of filename */
353 end = strpbrk(cp, WHITESPACE);
355 end = strchr(cp, '\0');
356 *cpp = end + strspn(end, WHITESPACE);
361 *path = xmalloc(i + 1);
362 memcpy(*path, cp, i);
376 /* XXX: report errors? */
377 if (stat(path, &sb) == -1)
380 return(sb.st_mode & S_IFDIR);
388 if (stat(path, &sb) == -1)
389 fatal("stat %s: %s", path, strerror(errno));
391 return(S_ISREG(sb.st_mode));
395 remote_is_dir(struct sftp_conn *conn, char *path)
399 /* XXX: report errors? */
400 if ((a = do_stat(conn, path, 1)) == NULL)
402 if (!(a->flags & SSH2_FILEXFER_ATTR_PERMISSIONS))
404 return(a->perm & S_IFDIR);
408 process_get(struct sftp_conn *conn, char *src, char *dst, char *pwd, int pflag)
410 char *abs_src = NULL;
411 char *abs_dst = NULL;
417 abs_src = xstrdup(src);
418 abs_src = make_absolute(abs_src, pwd);
420 memset(&g, 0, sizeof(g));
421 debug3("Looking up %s", abs_src);
422 if (remote_glob(conn, abs_src, 0, NULL, &g)) {
423 error("File \"%s\" not found.", abs_src);
428 /* Only one match, dst may be file, directory or unspecified */
429 if (g.gl_pathv[0] && g.gl_matchc == 1) {
431 /* If directory specified, append filename */
433 if (infer_path(g.gl_pathv[0], &tmp)) {
437 abs_dst = path_append(dst, tmp);
440 abs_dst = xstrdup(dst);
441 } else if (infer_path(g.gl_pathv[0], &abs_dst)) {
445 err = do_download(conn, g.gl_pathv[0], abs_dst, pflag);
449 /* Multiple matches, dst may be directory or unspecified */
450 if (dst && !is_dir(dst)) {
451 error("Multiple files match, but \"%s\" is not a directory",
457 for (i = 0; g.gl_pathv[i]; i++) {
458 if (infer_path(g.gl_pathv[i], &tmp)) {
463 abs_dst = path_append(dst, tmp);
468 printf("Fetching %s to %s\n", g.gl_pathv[i], abs_dst);
469 if (do_download(conn, g.gl_pathv[i], abs_dst, pflag) == -1)
484 process_put(struct sftp_conn *conn, char *src, char *dst, char *pwd, int pflag)
486 char *tmp_dst = NULL;
487 char *abs_dst = NULL;
494 tmp_dst = xstrdup(dst);
495 tmp_dst = make_absolute(tmp_dst, pwd);
498 memset(&g, 0, sizeof(g));
499 debug3("Looking up %s", src);
500 if (glob(src, 0, NULL, &g)) {
501 error("File \"%s\" not found.", src);
506 /* Only one match, dst may be file, directory or unspecified */
507 if (g.gl_pathv[0] && g.gl_matchc == 1) {
508 if (!is_reg(g.gl_pathv[0])) {
509 error("Can't upload %s: not a regular file",
515 /* If directory specified, append filename */
516 if (remote_is_dir(conn, tmp_dst)) {
517 if (infer_path(g.gl_pathv[0], &tmp)) {
521 abs_dst = path_append(tmp_dst, tmp);
524 abs_dst = xstrdup(tmp_dst);
526 if (infer_path(g.gl_pathv[0], &abs_dst)) {
530 abs_dst = make_absolute(abs_dst, pwd);
532 err = do_upload(conn, g.gl_pathv[0], abs_dst, pflag);
536 /* Multiple matches, dst may be directory or unspecified */
537 if (tmp_dst && !remote_is_dir(conn, tmp_dst)) {
538 error("Multiple files match, but \"%s\" is not a directory",
544 for (i = 0; g.gl_pathv[i]; i++) {
545 if (!is_reg(g.gl_pathv[i])) {
546 error("skipping non-regular file %s",
550 if (infer_path(g.gl_pathv[i], &tmp)) {
555 abs_dst = path_append(tmp_dst, tmp);
558 abs_dst = make_absolute(tmp, pwd);
560 printf("Uploading %s to %s\n", g.gl_pathv[i], abs_dst);
561 if (do_upload(conn, g.gl_pathv[i], abs_dst, pflag) == -1)
574 sdirent_comp(const void *aa, const void *bb)
576 SFTP_DIRENT *a = *(SFTP_DIRENT **)aa;
577 SFTP_DIRENT *b = *(SFTP_DIRENT **)bb;
579 return (strcmp(a->filename, b->filename));
582 /* sftp ls.1 replacement for directories */
584 do_ls_dir(struct sftp_conn *conn, char *path, char *strip_path, int lflag)
589 if ((n = do_readdir(conn, path, &d)) != 0)
592 /* Count entries for sort */
593 for (n = 0; d[n] != NULL; n++)
596 qsort(d, n, sizeof(*d), sdirent_comp);
598 for (n = 0; d[n] != NULL; n++) {
601 tmp = path_append(path, d[n]->filename);
602 fname = path_strip(tmp, strip_path);
609 memset(&sb, 0, sizeof(sb));
610 attrib_to_stat(&d[n]->a, &sb);
611 lname = ls_file(fname, &sb, 1);
612 printf("%s\n", lname);
615 /* XXX - multicolumn display would be nice here */
616 printf("%s\n", fname);
622 free_sftp_dirents(d);
626 /* sftp ls.1 replacement which handles path globs */
628 do_globbed_ls(struct sftp_conn *conn, char *path, char *strip_path,
636 memset(&g, 0, sizeof(g));
638 if (remote_glob(conn, path, GLOB_MARK|GLOB_NOCHECK|GLOB_BRACE,
640 error("Can't ls: \"%s\" not found", path);
645 * If the glob returns a single match, which is the same as the
646 * input glob, and it is a directory, then just list its contents
648 if (g.gl_pathc == 1 &&
649 strncmp(path, g.gl_pathv[0], strlen(g.gl_pathv[0]) - 1) == 0) {
650 if ((a = do_lstat(conn, path, 1)) == NULL) {
654 if ((a->flags & SSH2_FILEXFER_ATTR_PERMISSIONS) &&
657 return (do_ls_dir(conn, path, strip_path, lflag));
661 for (i = 0; g.gl_pathv[i]; i++) {
664 fname = path_strip(g.gl_pathv[i], strip_path);
668 * XXX: this is slow - 1 roundtrip per path
669 * A solution to this is to fork glob() and
670 * build a sftp specific version which keeps the
671 * attribs (which currently get thrown away)
672 * that the server returns as well as the filenames.
674 memset(&sb, 0, sizeof(sb));
675 a = do_lstat(conn, g.gl_pathv[i], 1);
677 attrib_to_stat(a, &sb);
678 lname = ls_file(fname, &sb, 1);
679 printf("%s\n", lname);
682 /* XXX - multicolumn display would be nice here */
683 printf("%s\n", fname);
695 parse_args(const char **cpp, int *pflag, int *lflag, int *iflag,
696 unsigned long *n_arg, char **path1, char **path2)
698 const char *cmd, *cp = *cpp;
704 /* Skip leading whitespace */
705 cp = cp + strspn(cp, WHITESPACE);
707 /* Ignore blank lines and lines which begin with comment '#' char */
708 if (*cp == '\0' || *cp == '#')
711 /* Check for leading '-' (disable error processing) */
718 /* Figure out which command we have */
719 for (i = 0; cmds[i].c; i++) {
720 int cmdlen = strlen(cmds[i].c);
722 /* Check for command followed by whitespace */
723 if (!strncasecmp(cp, cmds[i].c, cmdlen) &&
724 strchr(WHITESPACE, cp[cmdlen])) {
726 cp = cp + strspn(cp, WHITESPACE);
737 } else if (cmdnum == -1) {
738 error("Invalid command.");
742 /* Get arguments and parse flags */
743 *lflag = *pflag = *n_arg = 0;
744 *path1 = *path2 = NULL;
748 if (parse_getput_flags(&cp, pflag))
750 /* Get first pathname (mandatory) */
751 if (get_pathname(&cp, path1))
753 if (*path1 == NULL) {
754 error("You must specify at least one path after a "
758 /* Try to get second pathname (optional) */
759 if (get_pathname(&cp, path2))
764 if (get_pathname(&cp, path1))
766 if (get_pathname(&cp, path2))
768 if (!*path1 || !*path2) {
769 error("You must specify two paths after a %s "
780 /* Get pathname (mandatory) */
781 if (get_pathname(&cp, path1))
783 if (*path1 == NULL) {
784 error("You must specify a path after a %s command.",
790 if (parse_ls_flags(&cp, lflag))
792 /* Path is optional */
793 if (get_pathname(&cp, path1))
798 /* Uses the rest of the line */
806 /* Get numeric arg (mandatory) */
807 l = strtol(cp, &cp2, base);
808 if (cp2 == cp || ((l == LONG_MIN || l == LONG_MAX) &&
809 errno == ERANGE) || l < 0) {
810 error("You must supply a numeric argument "
811 "to the %s command.", cmd);
816 if (cmdnum == I_LUMASK && strchr(WHITESPACE, *cp))
818 if (cmdnum == I_LUMASK || !strchr(WHITESPACE, *cp)) {
819 error("You must supply a numeric argument "
820 "to the %s command.", cmd);
823 cp += strspn(cp, WHITESPACE);
825 /* Get pathname (mandatory) */
826 if (get_pathname(&cp, path1))
828 if (*path1 == NULL) {
829 error("You must specify a path after a %s command.",
842 fatal("Command not implemented");
850 parse_dispatch_command(struct sftp_conn *conn, const char *cmd, char **pwd,
853 char *path1, *path2, *tmp;
854 int pflag, lflag, iflag, cmdnum, i;
857 char path_buf[MAXPATHLEN];
861 path1 = path2 = NULL;
862 cmdnum = parse_args(&cmd, &pflag, &lflag, &iflag, &n_arg,
868 memset(&g, 0, sizeof(g));
870 /* Perform command */
876 /* Unrecognized command */
880 err = process_get(conn, path1, path2, *pwd, pflag);
883 err = process_put(conn, path1, path2, *pwd, pflag);
886 path1 = make_absolute(path1, *pwd);
887 path2 = make_absolute(path2, *pwd);
888 err = do_rename(conn, path1, path2);
891 path2 = make_absolute(path2, *pwd);
892 err = do_symlink(conn, path1, path2);
895 path1 = make_absolute(path1, *pwd);
896 remote_glob(conn, path1, GLOB_NOCHECK, NULL, &g);
897 for (i = 0; g.gl_pathv[i]; i++) {
898 printf("Removing %s\n", g.gl_pathv[i]);
899 err = do_rm(conn, g.gl_pathv[i]);
900 if (err != 0 && err_abort)
905 path1 = make_absolute(path1, *pwd);
907 a.flags |= SSH2_FILEXFER_ATTR_PERMISSIONS;
909 err = do_mkdir(conn, path1, &a);
912 path1 = make_absolute(path1, *pwd);
913 err = do_rmdir(conn, path1);
916 path1 = make_absolute(path1, *pwd);
917 if ((tmp = do_realpath(conn, path1)) == NULL) {
921 if ((aa = do_stat(conn, tmp, 0)) == NULL) {
926 if (!(aa->flags & SSH2_FILEXFER_ATTR_PERMISSIONS)) {
927 error("Can't change directory: Can't check target");
932 if (!S_ISDIR(aa->perm)) {
933 error("Can't change directory: \"%s\" is not "
944 do_globbed_ls(conn, *pwd, *pwd, lflag);
948 /* Strip pwd off beginning of non-absolute paths */
953 path1 = make_absolute(path1, *pwd);
954 err = do_globbed_ls(conn, path1, tmp, lflag);
957 if (chdir(path1) == -1) {
958 error("Couldn't change local directory to "
959 "\"%s\": %s", path1, strerror(errno));
964 if (mkdir(path1, 0777) == -1) {
965 error("Couldn't create local directory "
966 "\"%s\": %s", path1, strerror(errno));
978 printf("Local umask: %03lo\n", n_arg);
981 path1 = make_absolute(path1, *pwd);
983 a.flags |= SSH2_FILEXFER_ATTR_PERMISSIONS;
985 remote_glob(conn, path1, GLOB_NOCHECK, NULL, &g);
986 for (i = 0; g.gl_pathv[i]; i++) {
987 printf("Changing mode on %s\n", g.gl_pathv[i]);
988 err = do_setstat(conn, g.gl_pathv[i], &a);
989 if (err != 0 && err_abort)
995 path1 = make_absolute(path1, *pwd);
996 remote_glob(conn, path1, GLOB_NOCHECK, NULL, &g);
997 for (i = 0; g.gl_pathv[i]; i++) {
998 if (!(aa = do_stat(conn, g.gl_pathv[i], 0))) {
999 if (err != 0 && err_abort)
1004 if (!(aa->flags & SSH2_FILEXFER_ATTR_UIDGID)) {
1005 error("Can't get current ownership of "
1006 "remote file \"%s\"", g.gl_pathv[i]);
1007 if (err != 0 && err_abort)
1012 aa->flags &= SSH2_FILEXFER_ATTR_UIDGID;
1013 if (cmdnum == I_CHOWN) {
1014 printf("Changing owner on %s\n", g.gl_pathv[i]);
1017 printf("Changing group on %s\n", g.gl_pathv[i]);
1020 err = do_setstat(conn, g.gl_pathv[i], aa);
1021 if (err != 0 && err_abort)
1026 printf("Remote working directory: %s\n", *pwd);
1029 if (!getcwd(path_buf, sizeof(path_buf))) {
1030 error("Couldn't get local cwd: %s", strerror(errno));
1034 printf("Local working directory: %s\n", path_buf);
1037 /* Processed below */
1043 printf("SFTP protocol version %u\n", sftp_proto_version(conn));
1046 showprogress = !showprogress;
1048 printf("Progress meter enabled\n");
1050 printf("Progress meter disabled\n");
1053 fatal("%d is not implemented", cmdnum);
1063 /* If an unignored error occurs in batch mode we should abort. */
1064 if (err_abort && err != 0)
1066 else if (cmdnum == I_QUIT)
1073 interactive_loop(int fd_in, int fd_out, char *file1, char *file2)
1078 struct sftp_conn *conn;
1081 conn = do_init(fd_in, fd_out, copy_buffer_len, num_requests);
1083 fatal("Couldn't initialise connection to server");
1085 pwd = do_realpath(conn, ".");
1089 if (file1 != NULL) {
1090 dir = xstrdup(file1);
1091 dir = make_absolute(dir, pwd);
1093 if (remote_is_dir(conn, dir) && file2 == NULL) {
1094 printf("Changing to: %s\n", dir);
1095 snprintf(cmd, sizeof cmd, "cd \"%s\"", dir);
1096 if (parse_dispatch_command(conn, cmd, &pwd, 1) != 0)
1100 snprintf(cmd, sizeof cmd, "get %s", dir);
1102 snprintf(cmd, sizeof cmd, "get %s %s", dir,
1105 err = parse_dispatch_command(conn, cmd, &pwd, 1);
1114 setvbuf(stdout, NULL, _IOLBF, 0);
1115 setvbuf(infile, NULL, _IOLBF, 0);
1127 /* XXX: use libedit */
1128 if (fgets(cmd, sizeof(cmd), infile) == NULL) {
1131 } else if (infile != stdin) /* Bluff typing */
1134 cp = strrchr(cmd, '\n');
1138 err = parse_dispatch_command(conn, cmd, &pwd, infile != stdin);
1144 /* err == 1 signifies normal "quit" exit */
1145 return (err >= 0 ? 0 : -1);