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.51 2003/01/08 23:53:26 djm 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 /* Seperators for interactive commands */
51 #define WHITESPACE " \t\r\n"
53 /* Commands for interactive mode */
82 const struct CMD cmds[] = {
95 { "lchdir", I_LCHDIR },
97 { "lmkdir", I_LMKDIR },
101 { "lumask", I_LUMASK },
102 { "mkdir", I_MKDIR },
107 { "rename", I_RENAME },
109 { "rmdir", I_RMDIR },
110 { "symlink", I_SYMLINK },
111 { "version", I_VERSION },
120 printf("Available commands:\n");
121 printf("cd path Change remote directory to 'path'\n");
122 printf("lcd path Change local directory to 'path'\n");
123 printf("chgrp grp path Change group of file 'path' to 'grp'\n");
124 printf("chmod mode path Change permissions of file 'path' to 'mode'\n");
125 printf("chown own path Change owner of file 'path' to 'own'\n");
126 printf("help Display this help text\n");
127 printf("get remote-path [local-path] Download file\n");
128 printf("lls [ls-options [path]] Display local directory listing\n");
129 printf("ln oldpath newpath Symlink remote file\n");
130 printf("lmkdir path Create local directory\n");
131 printf("lpwd Print local working directory\n");
132 printf("ls [path] Display remote directory listing\n");
133 printf("lumask umask Set local umask to 'umask'\n");
134 printf("mkdir path Create remote directory\n");
135 printf("put local-path [remote-path] Upload file\n");
136 printf("pwd Display remote working directory\n");
137 printf("exit Quit sftp\n");
138 printf("quit Quit sftp\n");
139 printf("rename oldpath newpath Rename remote file\n");
140 printf("rmdir path Remove remote directory\n");
141 printf("rm path Delete remote file\n");
142 printf("symlink oldpath newpath Symlink remote file\n");
143 printf("version Show SFTP version\n");
144 printf("!command Execute 'command' in local shell\n");
145 printf("! Escape to local shell\n");
146 printf("? Synonym for help\n");
150 local_do_shell(const char *args)
159 if ((shell = getenv("SHELL")) == NULL)
160 shell = _PATH_BSHELL;
162 if ((pid = fork()) == -1)
163 fatal("Couldn't fork: %s", strerror(errno));
166 /* XXX: child has pipe fds to ssh subproc open - issue? */
168 debug3("Executing %s -c \"%s\"", shell, args);
169 execl(shell, shell, "-c", args, (char *)NULL);
171 debug3("Executing %s", shell);
172 execl(shell, shell, (char *)NULL);
174 fprintf(stderr, "Couldn't execute \"%s\": %s\n", shell,
178 while (waitpid(pid, &status, 0) == -1)
180 fatal("Couldn't wait for child: %s", strerror(errno));
181 if (!WIFEXITED(status))
182 error("Shell exited abormally");
183 else if (WEXITSTATUS(status))
184 error("Shell exited with status %d", WEXITSTATUS(status));
188 local_do_ls(const char *args)
191 local_do_shell(_PATH_LS);
193 int len = strlen(_PATH_LS " ") + strlen(args) + 1;
194 char *buf = xmalloc(len);
196 /* XXX: quoting - rip quoting code from ftp? */
197 snprintf(buf, len, _PATH_LS " %s", args);
203 /* Strip one path (usually the pwd) from the start of another */
205 path_strip(char *path, char *strip)
210 return (xstrdup(path));
213 if (strip != NULL && strncmp(path, strip, len) == 0) {
214 if (strip[len - 1] != '/' && path[len] == '/')
216 return (xstrdup(path + len));
219 return (xstrdup(path));
223 path_append(char *p1, char *p2)
226 int len = strlen(p1) + strlen(p2) + 2;
229 strlcpy(ret, p1, len);
230 if (p1[strlen(p1) - 1] != '/')
231 strlcat(ret, "/", len);
232 strlcat(ret, p2, len);
238 make_absolute(char *p, char *pwd)
243 if (p && p[0] != '/') {
244 abs = path_append(pwd, p);
252 infer_path(const char *p, char **ifp)
256 cp = strrchr(p, '/');
263 error("Invalid path");
267 *ifp = xstrdup(cp + 1);
272 parse_getput_flags(const char **cpp, int *pflag)
274 const char *cp = *cpp;
276 /* Check for flags */
277 if (cp[0] == '-' && cp[1] && strchr(WHITESPACE, cp[2])) {
284 error("Invalid flag -%c", cp[1]);
288 *cpp = cp + strspn(cp, WHITESPACE);
295 parse_ls_flags(const char **cpp, int *lflag)
297 const char *cp = *cpp;
299 /* Check for flags */
300 if (cp++[0] == '-') {
301 for(; strchr(WHITESPACE, *cp) == NULL; cp++) {
307 error("Invalid flag -%c", *cp);
311 *cpp = cp + strspn(cp, WHITESPACE);
318 get_pathname(const char **cpp, char **path)
320 const char *cp = *cpp, *end;
324 cp += strspn(cp, WHITESPACE);
331 /* Check for quoted filenames */
332 if (*cp == '\"' || *cp == '\'') {
335 end = strchr(cp, quot);
337 error("Unterminated quote");
341 error("Empty quotes");
344 *cpp = end + 1 + strspn(end + 1, WHITESPACE);
346 /* Read to end of filename */
347 end = strpbrk(cp, WHITESPACE);
349 end = strchr(cp, '\0');
350 *cpp = end + strspn(end, WHITESPACE);
355 *path = xmalloc(i + 1);
356 memcpy(*path, cp, i);
370 /* XXX: report errors? */
371 if (stat(path, &sb) == -1)
374 return(sb.st_mode & S_IFDIR);
378 remote_is_dir(struct sftp_conn *conn, char *path)
382 /* XXX: report errors? */
383 if ((a = do_stat(conn, path, 1)) == NULL)
385 if (!(a->flags & SSH2_FILEXFER_ATTR_PERMISSIONS))
387 return(a->perm & S_IFDIR);
391 process_get(struct sftp_conn *conn, char *src, char *dst, char *pwd, int pflag)
393 char *abs_src = NULL;
394 char *abs_dst = NULL;
400 abs_src = xstrdup(src);
401 abs_src = make_absolute(abs_src, pwd);
403 memset(&g, 0, sizeof(g));
404 debug3("Looking up %s", abs_src);
405 if (remote_glob(conn, abs_src, 0, NULL, &g)) {
406 error("File \"%s\" not found.", abs_src);
411 /* Only one match, dst may be file, directory or unspecified */
412 if (g.gl_pathv[0] && g.gl_matchc == 1) {
414 /* If directory specified, append filename */
416 if (infer_path(g.gl_pathv[0], &tmp)) {
420 abs_dst = path_append(dst, tmp);
423 abs_dst = xstrdup(dst);
424 } else if (infer_path(g.gl_pathv[0], &abs_dst)) {
428 printf("Fetching %s to %s\n", g.gl_pathv[0], abs_dst);
429 err = do_download(conn, g.gl_pathv[0], abs_dst, pflag);
433 /* Multiple matches, dst may be directory or unspecified */
434 if (dst && !is_dir(dst)) {
435 error("Multiple files match, but \"%s\" is not a directory",
441 for (i = 0; g.gl_pathv[i]; i++) {
442 if (infer_path(g.gl_pathv[i], &tmp)) {
447 abs_dst = path_append(dst, tmp);
452 printf("Fetching %s to %s\n", g.gl_pathv[i], abs_dst);
453 if (do_download(conn, g.gl_pathv[i], abs_dst, pflag) == -1)
468 process_put(struct sftp_conn *conn, char *src, char *dst, char *pwd, int pflag)
470 char *tmp_dst = NULL;
471 char *abs_dst = NULL;
478 tmp_dst = xstrdup(dst);
479 tmp_dst = make_absolute(tmp_dst, pwd);
482 memset(&g, 0, sizeof(g));
483 debug3("Looking up %s", src);
484 if (glob(src, 0, NULL, &g)) {
485 error("File \"%s\" not found.", src);
490 /* Only one match, dst may be file, directory or unspecified */
491 if (g.gl_pathv[0] && g.gl_matchc == 1) {
493 /* If directory specified, append filename */
494 if (remote_is_dir(conn, tmp_dst)) {
495 if (infer_path(g.gl_pathv[0], &tmp)) {
499 abs_dst = path_append(tmp_dst, tmp);
502 abs_dst = xstrdup(tmp_dst);
504 if (infer_path(g.gl_pathv[0], &abs_dst)) {
508 abs_dst = make_absolute(abs_dst, pwd);
510 printf("Uploading %s to %s\n", g.gl_pathv[0], abs_dst);
511 err = do_upload(conn, g.gl_pathv[0], abs_dst, pflag);
515 /* Multiple matches, dst may be directory or unspecified */
516 if (tmp_dst && !remote_is_dir(conn, tmp_dst)) {
517 error("Multiple files match, but \"%s\" is not a directory",
523 for (i = 0; g.gl_pathv[i]; i++) {
524 if (infer_path(g.gl_pathv[i], &tmp)) {
529 abs_dst = path_append(tmp_dst, tmp);
532 abs_dst = make_absolute(tmp, pwd);
534 printf("Uploading %s to %s\n", g.gl_pathv[i], abs_dst);
535 if (do_upload(conn, g.gl_pathv[i], abs_dst, pflag) == -1)
548 sdirent_comp(const void *aa, const void *bb)
550 SFTP_DIRENT *a = *(SFTP_DIRENT **)aa;
551 SFTP_DIRENT *b = *(SFTP_DIRENT **)bb;
553 return (strcmp(a->filename, b->filename));
556 /* sftp ls.1 replacement for directories */
558 do_ls_dir(struct sftp_conn *conn, char *path, char *strip_path, int lflag)
563 if ((n = do_readdir(conn, path, &d)) != 0)
566 /* Count entries for sort */
567 for (n = 0; d[n] != NULL; n++)
570 qsort(d, n, sizeof(*d), sdirent_comp);
572 for (n = 0; d[n] != NULL; n++) {
575 tmp = path_append(path, d[n]->filename);
576 fname = path_strip(tmp, strip_path);
583 memset(&sb, 0, sizeof(sb));
584 attrib_to_stat(&d[n]->a, &sb);
585 lname = ls_file(fname, &sb, 1);
586 printf("%s\n", lname);
589 /* XXX - multicolumn display would be nice here */
590 printf("%s\n", fname);
596 free_sftp_dirents(d);
600 /* sftp ls.1 replacement which handles path globs */
602 do_globbed_ls(struct sftp_conn *conn, char *path, char *strip_path,
610 memset(&g, 0, sizeof(g));
612 if (remote_glob(conn, path, GLOB_MARK|GLOB_NOCHECK|GLOB_BRACE,
614 error("Can't ls: \"%s\" not found", path);
619 * If the glob returns a single match, which is the same as the
620 * input glob, and it is a directory, then just list its contents
622 if (g.gl_pathc == 1 &&
623 strncmp(path, g.gl_pathv[0], strlen(g.gl_pathv[0]) - 1) == 0) {
624 if ((a = do_lstat(conn, path, 1)) == NULL) {
628 if ((a->flags & SSH2_FILEXFER_ATTR_PERMISSIONS) &&
631 return (do_ls_dir(conn, path, strip_path, lflag));
635 for (i = 0; g.gl_pathv[i]; i++) {
638 fname = path_strip(g.gl_pathv[i], strip_path);
642 * XXX: this is slow - 1 roundtrip per path
643 * A solution to this is to fork glob() and
644 * build a sftp specific version which keeps the
645 * attribs (which currently get thrown away)
646 * that the server returns as well as the filenames.
648 memset(&sb, 0, sizeof(sb));
649 a = do_lstat(conn, g.gl_pathv[i], 1);
651 attrib_to_stat(a, &sb);
652 lname = ls_file(fname, &sb, 1);
653 printf("%s\n", lname);
656 /* XXX - multicolumn display would be nice here */
657 printf("%s\n", fname);
669 parse_args(const char **cpp, int *pflag, int *lflag, int *iflag,
670 unsigned long *n_arg, char **path1, char **path2)
672 const char *cmd, *cp = *cpp;
678 /* Skip leading whitespace */
679 cp = cp + strspn(cp, WHITESPACE);
681 /* Ignore blank lines and lines which begin with comment '#' char */
682 if (*cp == '\0' || *cp == '#')
685 /* Check for leading '-' (disable error processing) */
692 /* Figure out which command we have */
693 for (i = 0; cmds[i].c; i++) {
694 int cmdlen = strlen(cmds[i].c);
696 /* Check for command followed by whitespace */
697 if (!strncasecmp(cp, cmds[i].c, cmdlen) &&
698 strchr(WHITESPACE, cp[cmdlen])) {
700 cp = cp + strspn(cp, WHITESPACE);
711 } else if (cmdnum == -1) {
712 error("Invalid command.");
716 /* Get arguments and parse flags */
717 *lflag = *pflag = *n_arg = 0;
718 *path1 = *path2 = NULL;
722 if (parse_getput_flags(&cp, pflag))
724 /* Get first pathname (mandatory) */
725 if (get_pathname(&cp, path1))
727 if (*path1 == NULL) {
728 error("You must specify at least one path after a "
732 /* Try to get second pathname (optional) */
733 if (get_pathname(&cp, path2))
738 if (get_pathname(&cp, path1))
740 if (get_pathname(&cp, path2))
742 if (!*path1 || !*path2) {
743 error("You must specify two paths after a %s "
754 /* Get pathname (mandatory) */
755 if (get_pathname(&cp, path1))
757 if (*path1 == NULL) {
758 error("You must specify a path after a %s command.",
764 if (parse_ls_flags(&cp, lflag))
766 /* Path is optional */
767 if (get_pathname(&cp, path1))
772 /* Uses the rest of the line */
780 /* Get numeric arg (mandatory) */
781 l = strtol(cp, &cp2, base);
782 if (cp2 == cp || ((l == LONG_MIN || l == LONG_MAX) &&
783 errno == ERANGE) || l < 0) {
784 error("You must supply a numeric argument "
785 "to the %s command.", cmd);
790 if (cmdnum == I_LUMASK && strchr(WHITESPACE, *cp))
792 if (cmdnum == I_LUMASK || !strchr(WHITESPACE, *cp)) {
793 error("You must supply a numeric argument "
794 "to the %s command.", cmd);
797 cp += strspn(cp, WHITESPACE);
799 /* Get pathname (mandatory) */
800 if (get_pathname(&cp, path1))
802 if (*path1 == NULL) {
803 error("You must specify a path after a %s command.",
815 fatal("Command not implemented");
823 parse_dispatch_command(struct sftp_conn *conn, const char *cmd, char **pwd,
826 char *path1, *path2, *tmp;
827 int pflag, lflag, iflag, cmdnum, i;
830 char path_buf[MAXPATHLEN];
834 path1 = path2 = NULL;
835 cmdnum = parse_args(&cmd, &pflag, &lflag, &iflag, &n_arg,
841 memset(&g, 0, sizeof(g));
843 /* Perform command */
849 /* Unrecognized command */
853 err = process_get(conn, path1, path2, *pwd, pflag);
856 err = process_put(conn, path1, path2, *pwd, pflag);
859 path1 = make_absolute(path1, *pwd);
860 path2 = make_absolute(path2, *pwd);
861 err = do_rename(conn, path1, path2);
864 path2 = make_absolute(path2, *pwd);
865 err = do_symlink(conn, path1, path2);
868 path1 = make_absolute(path1, *pwd);
869 remote_glob(conn, path1, GLOB_NOCHECK, NULL, &g);
870 for (i = 0; g.gl_pathv[i]; i++) {
871 printf("Removing %s\n", g.gl_pathv[i]);
872 err = do_rm(conn, g.gl_pathv[i]);
873 if (err != 0 && err_abort)
878 path1 = make_absolute(path1, *pwd);
880 a.flags |= SSH2_FILEXFER_ATTR_PERMISSIONS;
882 err = do_mkdir(conn, path1, &a);
885 path1 = make_absolute(path1, *pwd);
886 err = do_rmdir(conn, path1);
889 path1 = make_absolute(path1, *pwd);
890 if ((tmp = do_realpath(conn, path1)) == NULL) {
894 if ((aa = do_stat(conn, tmp, 0)) == NULL) {
899 if (!(aa->flags & SSH2_FILEXFER_ATTR_PERMISSIONS)) {
900 error("Can't change directory: Can't check target");
905 if (!S_ISDIR(aa->perm)) {
906 error("Can't change directory: \"%s\" is not "
917 do_globbed_ls(conn, *pwd, *pwd, lflag);
921 /* Strip pwd off beginning of non-absolute paths */
926 path1 = make_absolute(path1, *pwd);
927 err = do_globbed_ls(conn, path1, tmp, lflag);
930 if (chdir(path1) == -1) {
931 error("Couldn't change local directory to "
932 "\"%s\": %s", path1, strerror(errno));
937 if (mkdir(path1, 0777) == -1) {
938 error("Couldn't create local directory "
939 "\"%s\": %s", path1, strerror(errno));
951 printf("Local umask: %03lo\n", n_arg);
954 path1 = make_absolute(path1, *pwd);
956 a.flags |= SSH2_FILEXFER_ATTR_PERMISSIONS;
958 remote_glob(conn, path1, GLOB_NOCHECK, NULL, &g);
959 for (i = 0; g.gl_pathv[i]; i++) {
960 printf("Changing mode on %s\n", g.gl_pathv[i]);
961 err = do_setstat(conn, g.gl_pathv[i], &a);
962 if (err != 0 && err_abort)
968 path1 = make_absolute(path1, *pwd);
969 remote_glob(conn, path1, GLOB_NOCHECK, NULL, &g);
970 for (i = 0; g.gl_pathv[i]; i++) {
971 if (!(aa = do_stat(conn, g.gl_pathv[i], 0))) {
972 if (err != 0 && err_abort)
977 if (!(aa->flags & SSH2_FILEXFER_ATTR_UIDGID)) {
978 error("Can't get current ownership of "
979 "remote file \"%s\"", g.gl_pathv[i]);
980 if (err != 0 && err_abort)
985 aa->flags &= SSH2_FILEXFER_ATTR_UIDGID;
986 if (cmdnum == I_CHOWN) {
987 printf("Changing owner on %s\n", g.gl_pathv[i]);
990 printf("Changing group on %s\n", g.gl_pathv[i]);
993 err = do_setstat(conn, g.gl_pathv[i], aa);
994 if (err != 0 && err_abort)
999 printf("Remote working directory: %s\n", *pwd);
1002 if (!getcwd(path_buf, sizeof(path_buf))) {
1003 error("Couldn't get local cwd: %s", strerror(errno));
1007 printf("Local working directory: %s\n", path_buf);
1010 /* Processed below */
1016 printf("SFTP protocol version %u\n", sftp_proto_version(conn));
1019 fatal("%d is not implemented", cmdnum);
1029 /* If an unignored error occurs in batch mode we should abort. */
1030 if (err_abort && err != 0)
1032 else if (cmdnum == I_QUIT)
1039 interactive_loop(int fd_in, int fd_out, char *file1, char *file2)
1044 struct sftp_conn *conn;
1047 conn = do_init(fd_in, fd_out, copy_buffer_len, num_requests);
1049 fatal("Couldn't initialise connection to server");
1051 pwd = do_realpath(conn, ".");
1055 if (file1 != NULL) {
1056 dir = xstrdup(file1);
1057 dir = make_absolute(dir, pwd);
1059 if (remote_is_dir(conn, dir) && file2 == NULL) {
1060 printf("Changing to: %s\n", dir);
1061 snprintf(cmd, sizeof cmd, "cd \"%s\"", dir);
1062 if (parse_dispatch_command(conn, cmd, &pwd, 1) != 0)
1066 snprintf(cmd, sizeof cmd, "get %s", dir);
1068 snprintf(cmd, sizeof cmd, "get %s %s", dir,
1071 err = parse_dispatch_command(conn, cmd, &pwd, 1);
1079 setvbuf(stdout, NULL, _IOLBF, 0);
1080 setvbuf(infile, NULL, _IOLBF, 0);
1092 /* XXX: use libedit */
1093 if (fgets(cmd, sizeof(cmd), infile) == NULL) {
1096 } else if (infile != stdin) /* Bluff typing */
1099 cp = strrchr(cmd, '\n');
1103 err = parse_dispatch_command(conn, cmd, &pwd, infile != stdin);
1109 /* err == 1 signifies normal "quit" exit */
1110 return (err >= 0 ? 0 : -1);