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.62 2003/08/25 08:13:09 fgsch 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 /* Define what type of ls view (0 - multi-column) */
57 #define LONG_VIEW 1 /* Full view ala ls -l */
58 #define SHORT_VIEW 2 /* Single row view ala ls -1 */
60 /* Commands for interactive mode */
90 static const struct CMD cmds[] = {
103 { "lchdir", I_LCHDIR },
105 { "lmkdir", I_LMKDIR },
109 { "lumask", I_LUMASK },
110 { "mkdir", I_MKDIR },
111 { "progress", I_PROGRESS },
116 { "rename", I_RENAME },
118 { "rmdir", I_RMDIR },
119 { "symlink", I_SYMLINK },
120 { "version", I_VERSION },
129 printf("Available commands:\n");
130 printf("cd path Change remote directory to 'path'\n");
131 printf("lcd path Change local directory to 'path'\n");
132 printf("chgrp grp path Change group of file 'path' to 'grp'\n");
133 printf("chmod mode path Change permissions of file 'path' to 'mode'\n");
134 printf("chown own path Change owner of file 'path' to 'own'\n");
135 printf("help Display this help text\n");
136 printf("get remote-path [local-path] Download file\n");
137 printf("lls [ls-options [path]] Display local directory listing\n");
138 printf("ln oldpath newpath Symlink remote file\n");
139 printf("lmkdir path Create local directory\n");
140 printf("lpwd Print local working directory\n");
141 printf("ls [path] Display remote directory listing\n");
142 printf("lumask umask Set local umask to 'umask'\n");
143 printf("mkdir path Create remote directory\n");
144 printf("progress Toggle display of progress meter\n");
145 printf("put local-path [remote-path] Upload file\n");
146 printf("pwd Display remote working directory\n");
147 printf("exit Quit sftp\n");
148 printf("quit Quit sftp\n");
149 printf("rename oldpath newpath Rename remote file\n");
150 printf("rmdir path Remove remote directory\n");
151 printf("rm path Delete remote file\n");
152 printf("symlink oldpath newpath Symlink remote file\n");
153 printf("version Show SFTP version\n");
154 printf("!command Execute 'command' in local shell\n");
155 printf("! Escape to local shell\n");
156 printf("? Synonym for help\n");
160 local_do_shell(const char *args)
169 if ((shell = getenv("SHELL")) == NULL)
170 shell = _PATH_BSHELL;
172 if ((pid = fork()) == -1)
173 fatal("Couldn't fork: %s", strerror(errno));
176 /* XXX: child has pipe fds to ssh subproc open - issue? */
178 debug3("Executing %s -c \"%s\"", shell, args);
179 execl(shell, shell, "-c", args, (char *)NULL);
181 debug3("Executing %s", shell);
182 execl(shell, shell, (char *)NULL);
184 fprintf(stderr, "Couldn't execute \"%s\": %s\n", shell,
188 while (waitpid(pid, &status, 0) == -1)
190 fatal("Couldn't wait for child: %s", strerror(errno));
191 if (!WIFEXITED(status))
192 error("Shell exited abormally");
193 else if (WEXITSTATUS(status))
194 error("Shell exited with status %d", WEXITSTATUS(status));
198 local_do_ls(const char *args)
201 local_do_shell(_PATH_LS);
203 int len = strlen(_PATH_LS " ") + strlen(args) + 1;
204 char *buf = xmalloc(len);
206 /* XXX: quoting - rip quoting code from ftp? */
207 snprintf(buf, len, _PATH_LS " %s", args);
213 /* Strip one path (usually the pwd) from the start of another */
215 path_strip(char *path, char *strip)
220 return (xstrdup(path));
223 if (strip != NULL && strncmp(path, strip, len) == 0) {
224 if (strip[len - 1] != '/' && path[len] == '/')
226 return (xstrdup(path + len));
229 return (xstrdup(path));
233 path_append(char *p1, char *p2)
236 int len = strlen(p1) + strlen(p2) + 2;
239 strlcpy(ret, p1, len);
240 if (p1[strlen(p1) - 1] != '/')
241 strlcat(ret, "/", len);
242 strlcat(ret, p2, len);
248 make_absolute(char *p, char *pwd)
253 if (p && p[0] != '/') {
254 abs = path_append(pwd, p);
262 infer_path(const char *p, char **ifp)
266 cp = strrchr(p, '/');
273 error("Invalid path");
277 *ifp = xstrdup(cp + 1);
282 parse_getput_flags(const char **cpp, int *pflag)
284 const char *cp = *cpp;
286 /* Check for flags */
287 if (cp[0] == '-' && cp[1] && strchr(WHITESPACE, cp[2])) {
294 error("Invalid flag -%c", cp[1]);
298 *cpp = cp + strspn(cp, WHITESPACE);
305 parse_ls_flags(const char **cpp, int *lflag)
307 const char *cp = *cpp;
309 /* Check for flags */
310 if (cp++[0] == '-') {
311 for(; strchr(WHITESPACE, *cp) == NULL; cp++) {
320 error("Invalid flag -%c", *cp);
324 *cpp = cp + strspn(cp, WHITESPACE);
331 get_pathname(const char **cpp, char **path)
333 const char *cp = *cpp, *end;
337 cp += strspn(cp, WHITESPACE);
344 *path = xmalloc(strlen(cp) + 1);
346 /* Check for quoted filenames */
347 if (*cp == '\"' || *cp == '\'') {
350 /* Search for terminating quote, unescape some chars */
351 for (i = j = 0; i <= strlen(cp); i++) {
352 if (cp[i] == quot) { /* Found quote */
357 if (cp[i] == '\0') { /* End of string */
358 error("Unterminated quote");
361 if (cp[i] == '\\') { /* Escaped characters */
363 if (cp[i] != '\'' && cp[i] != '\"' &&
365 error("Bad escaped character '\%c'",
370 (*path)[j++] = cp[i];
374 error("Empty quotes");
377 *cpp = cp + i + strspn(cp + i, WHITESPACE);
379 /* Read to end of filename */
380 end = strpbrk(cp, WHITESPACE);
382 end = strchr(cp, '\0');
383 *cpp = end + strspn(end, WHITESPACE);
385 memcpy(*path, cp, end - cp);
386 (*path)[end - cp] = '\0';
401 /* XXX: report errors? */
402 if (stat(path, &sb) == -1)
405 return(sb.st_mode & S_IFDIR);
413 if (stat(path, &sb) == -1)
414 fatal("stat %s: %s", path, strerror(errno));
416 return(S_ISREG(sb.st_mode));
420 remote_is_dir(struct sftp_conn *conn, char *path)
424 /* XXX: report errors? */
425 if ((a = do_stat(conn, path, 1)) == NULL)
427 if (!(a->flags & SSH2_FILEXFER_ATTR_PERMISSIONS))
429 return(a->perm & S_IFDIR);
433 process_get(struct sftp_conn *conn, char *src, char *dst, char *pwd, int pflag)
435 char *abs_src = NULL;
436 char *abs_dst = NULL;
442 abs_src = xstrdup(src);
443 abs_src = make_absolute(abs_src, pwd);
445 memset(&g, 0, sizeof(g));
446 debug3("Looking up %s", abs_src);
447 if (remote_glob(conn, abs_src, 0, NULL, &g)) {
448 error("File \"%s\" not found.", abs_src);
453 /* If multiple matches, dst must be a directory or unspecified */
454 if (g.gl_matchc > 1 && dst && !is_dir(dst)) {
455 error("Multiple files match, but \"%s\" is not a directory",
461 for (i = 0; g.gl_pathv[i]; i++) {
462 if (infer_path(g.gl_pathv[i], &tmp)) {
467 if (g.gl_matchc == 1 && dst) {
468 /* If directory specified, append filename */
470 if (infer_path(g.gl_pathv[0], &tmp)) {
474 abs_dst = path_append(dst, tmp);
477 abs_dst = xstrdup(dst);
479 abs_dst = path_append(dst, tmp);
484 printf("Fetching %s to %s\n", g.gl_pathv[i], abs_dst);
485 if (do_download(conn, g.gl_pathv[i], abs_dst, pflag) == -1)
500 process_put(struct sftp_conn *conn, char *src, char *dst, char *pwd, int pflag)
502 char *tmp_dst = NULL;
503 char *abs_dst = NULL;
510 tmp_dst = xstrdup(dst);
511 tmp_dst = make_absolute(tmp_dst, pwd);
514 memset(&g, 0, sizeof(g));
515 debug3("Looking up %s", src);
516 if (glob(src, 0, NULL, &g)) {
517 error("File \"%s\" not found.", src);
522 /* If multiple matches, dst may be directory or unspecified */
523 if (g.gl_matchc > 1 && tmp_dst && !remote_is_dir(conn, tmp_dst)) {
524 error("Multiple files match, but \"%s\" is not a directory",
530 for (i = 0; g.gl_pathv[i]; i++) {
531 if (!is_reg(g.gl_pathv[i])) {
532 error("skipping non-regular file %s",
536 if (infer_path(g.gl_pathv[i], &tmp)) {
541 if (g.gl_matchc == 1 && tmp_dst) {
542 /* If directory specified, append filename */
543 if (remote_is_dir(conn, tmp_dst)) {
544 if (infer_path(g.gl_pathv[0], &tmp)) {
548 abs_dst = path_append(tmp_dst, tmp);
551 abs_dst = xstrdup(tmp_dst);
553 } else if (tmp_dst) {
554 abs_dst = path_append(tmp_dst, tmp);
557 abs_dst = make_absolute(tmp, pwd);
559 printf("Uploading %s to %s\n", g.gl_pathv[i], abs_dst);
560 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)
586 int n, c = 1, colspace = 0, columns = 1;
589 if ((n = do_readdir(conn, path, &d)) != 0)
592 if (!(lflag & SHORT_VIEW)) {
593 int m = 0, width = 80;
596 /* Count entries for sort and find longest filename */
597 for (n = 0; d[n] != NULL; n++)
598 m = MAX(m, strlen(d[n]->filename));
600 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) != -1)
603 columns = width / (m + 2);
604 columns = MAX(columns, 1);
605 colspace = width / columns;
608 qsort(d, n, sizeof(*d), sdirent_comp);
610 for (n = 0; d[n] != NULL; n++) {
613 tmp = path_append(path, d[n]->filename);
614 fname = path_strip(tmp, strip_path);
617 if (lflag & LONG_VIEW) {
621 memset(&sb, 0, sizeof(sb));
622 attrib_to_stat(&d[n]->a, &sb);
623 lname = ls_file(fname, &sb, 1);
624 printf("%s\n", lname);
627 printf("%-*s", colspace, fname);
638 if (!(lflag & LONG_VIEW) && (c != 1))
641 free_sftp_dirents(d);
645 /* sftp ls.1 replacement which handles path globs */
647 do_globbed_ls(struct sftp_conn *conn, char *path, char *strip_path,
651 int i, c = 1, colspace = 0, columns = 1;
654 memset(&g, 0, sizeof(g));
656 if (remote_glob(conn, path, GLOB_MARK|GLOB_NOCHECK|GLOB_BRACE,
658 error("Can't ls: \"%s\" not found", path);
663 * If the glob returns a single match, which is the same as the
664 * input glob, and it is a directory, then just list its contents
666 if (g.gl_pathc == 1 &&
667 strncmp(path, g.gl_pathv[0], strlen(g.gl_pathv[0]) - 1) == 0) {
668 if ((a = do_lstat(conn, path, 1)) == NULL) {
672 if ((a->flags & SSH2_FILEXFER_ATTR_PERMISSIONS) &&
675 return (do_ls_dir(conn, path, strip_path, lflag));
679 if (!(lflag & SHORT_VIEW)) {
680 int m = 0, width = 80;
683 /* Count entries for sort and find longest filename */
684 for (i = 0; g.gl_pathv[i]; i++)
685 m = MAX(m, strlen(g.gl_pathv[i]));
687 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) != -1)
690 columns = width / (m + 2);
691 columns = MAX(columns, 1);
692 colspace = width / columns;
695 for (i = 0; g.gl_pathv[i]; i++) {
698 fname = path_strip(g.gl_pathv[i], strip_path);
700 if (lflag & LONG_VIEW) {
705 * XXX: this is slow - 1 roundtrip per path
706 * A solution to this is to fork glob() and
707 * build a sftp specific version which keeps the
708 * attribs (which currently get thrown away)
709 * that the server returns as well as the filenames.
711 memset(&sb, 0, sizeof(sb));
712 a = do_lstat(conn, g.gl_pathv[i], 1);
714 attrib_to_stat(a, &sb);
715 lname = ls_file(fname, &sb, 1);
716 printf("%s\n", lname);
719 printf("%-*s", colspace, fname);
729 if (!(lflag & LONG_VIEW) && (c != 1))
739 parse_args(const char **cpp, int *pflag, int *lflag, int *iflag,
740 unsigned long *n_arg, char **path1, char **path2)
742 const char *cmd, *cp = *cpp;
748 /* Skip leading whitespace */
749 cp = cp + strspn(cp, WHITESPACE);
751 /* Ignore blank lines and lines which begin with comment '#' char */
752 if (*cp == '\0' || *cp == '#')
755 /* Check for leading '-' (disable error processing) */
762 /* Figure out which command we have */
763 for (i = 0; cmds[i].c; i++) {
764 int cmdlen = strlen(cmds[i].c);
766 /* Check for command followed by whitespace */
767 if (!strncasecmp(cp, cmds[i].c, cmdlen) &&
768 strchr(WHITESPACE, cp[cmdlen])) {
770 cp = cp + strspn(cp, WHITESPACE);
781 } else if (cmdnum == -1) {
782 error("Invalid command.");
786 /* Get arguments and parse flags */
787 *lflag = *pflag = *n_arg = 0;
788 *path1 = *path2 = NULL;
792 if (parse_getput_flags(&cp, pflag))
794 /* Get first pathname (mandatory) */
795 if (get_pathname(&cp, path1))
797 if (*path1 == NULL) {
798 error("You must specify at least one path after a "
802 /* Try to get second pathname (optional) */
803 if (get_pathname(&cp, path2))
808 if (get_pathname(&cp, path1))
810 if (get_pathname(&cp, path2))
812 if (!*path1 || !*path2) {
813 error("You must specify two paths after a %s "
824 /* Get pathname (mandatory) */
825 if (get_pathname(&cp, path1))
827 if (*path1 == NULL) {
828 error("You must specify a path after a %s command.",
834 if (parse_ls_flags(&cp, lflag))
836 /* Path is optional */
837 if (get_pathname(&cp, path1))
842 /* Uses the rest of the line */
850 /* Get numeric arg (mandatory) */
851 l = strtol(cp, &cp2, base);
852 if (cp2 == cp || ((l == LONG_MIN || l == LONG_MAX) &&
853 errno == ERANGE) || l < 0) {
854 error("You must supply a numeric argument "
855 "to the %s command.", cmd);
860 if (cmdnum == I_LUMASK && strchr(WHITESPACE, *cp))
862 if (cmdnum == I_LUMASK || !strchr(WHITESPACE, *cp)) {
863 error("You must supply a numeric argument "
864 "to the %s command.", cmd);
867 cp += strspn(cp, WHITESPACE);
869 /* Get pathname (mandatory) */
870 if (get_pathname(&cp, path1))
872 if (*path1 == NULL) {
873 error("You must specify a path after a %s command.",
886 fatal("Command not implemented");
894 parse_dispatch_command(struct sftp_conn *conn, const char *cmd, char **pwd,
897 char *path1, *path2, *tmp;
898 int pflag, lflag, iflag, cmdnum, i;
901 char path_buf[MAXPATHLEN];
905 path1 = path2 = NULL;
906 cmdnum = parse_args(&cmd, &pflag, &lflag, &iflag, &n_arg,
912 memset(&g, 0, sizeof(g));
914 /* Perform command */
920 /* Unrecognized command */
924 err = process_get(conn, path1, path2, *pwd, pflag);
927 err = process_put(conn, path1, path2, *pwd, pflag);
930 path1 = make_absolute(path1, *pwd);
931 path2 = make_absolute(path2, *pwd);
932 err = do_rename(conn, path1, path2);
935 path2 = make_absolute(path2, *pwd);
936 err = do_symlink(conn, path1, path2);
939 path1 = make_absolute(path1, *pwd);
940 remote_glob(conn, path1, GLOB_NOCHECK, NULL, &g);
941 for (i = 0; g.gl_pathv[i]; i++) {
942 printf("Removing %s\n", g.gl_pathv[i]);
943 err = do_rm(conn, g.gl_pathv[i]);
944 if (err != 0 && err_abort)
949 path1 = make_absolute(path1, *pwd);
951 a.flags |= SSH2_FILEXFER_ATTR_PERMISSIONS;
953 err = do_mkdir(conn, path1, &a);
956 path1 = make_absolute(path1, *pwd);
957 err = do_rmdir(conn, path1);
960 path1 = make_absolute(path1, *pwd);
961 if ((tmp = do_realpath(conn, path1)) == NULL) {
965 if ((aa = do_stat(conn, tmp, 0)) == NULL) {
970 if (!(aa->flags & SSH2_FILEXFER_ATTR_PERMISSIONS)) {
971 error("Can't change directory: Can't check target");
976 if (!S_ISDIR(aa->perm)) {
977 error("Can't change directory: \"%s\" is not "
988 do_globbed_ls(conn, *pwd, *pwd, lflag);
992 /* Strip pwd off beginning of non-absolute paths */
997 path1 = make_absolute(path1, *pwd);
998 err = do_globbed_ls(conn, path1, tmp, lflag);
1001 if (chdir(path1) == -1) {
1002 error("Couldn't change local directory to "
1003 "\"%s\": %s", path1, strerror(errno));
1008 if (mkdir(path1, 0777) == -1) {
1009 error("Couldn't create local directory "
1010 "\"%s\": %s", path1, strerror(errno));
1018 local_do_shell(cmd);
1022 printf("Local umask: %03lo\n", n_arg);
1025 path1 = make_absolute(path1, *pwd);
1027 a.flags |= SSH2_FILEXFER_ATTR_PERMISSIONS;
1029 remote_glob(conn, path1, GLOB_NOCHECK, NULL, &g);
1030 for (i = 0; g.gl_pathv[i]; i++) {
1031 printf("Changing mode on %s\n", g.gl_pathv[i]);
1032 err = do_setstat(conn, g.gl_pathv[i], &a);
1033 if (err != 0 && err_abort)
1039 path1 = make_absolute(path1, *pwd);
1040 remote_glob(conn, path1, GLOB_NOCHECK, NULL, &g);
1041 for (i = 0; g.gl_pathv[i]; i++) {
1042 if (!(aa = do_stat(conn, g.gl_pathv[i], 0))) {
1043 if (err != 0 && err_abort)
1048 if (!(aa->flags & SSH2_FILEXFER_ATTR_UIDGID)) {
1049 error("Can't get current ownership of "
1050 "remote file \"%s\"", g.gl_pathv[i]);
1051 if (err != 0 && err_abort)
1056 aa->flags &= SSH2_FILEXFER_ATTR_UIDGID;
1057 if (cmdnum == I_CHOWN) {
1058 printf("Changing owner on %s\n", g.gl_pathv[i]);
1061 printf("Changing group on %s\n", g.gl_pathv[i]);
1064 err = do_setstat(conn, g.gl_pathv[i], aa);
1065 if (err != 0 && err_abort)
1070 printf("Remote working directory: %s\n", *pwd);
1073 if (!getcwd(path_buf, sizeof(path_buf))) {
1074 error("Couldn't get local cwd: %s", strerror(errno));
1078 printf("Local working directory: %s\n", path_buf);
1081 /* Processed below */
1087 printf("SFTP protocol version %u\n", sftp_proto_version(conn));
1090 showprogress = !showprogress;
1092 printf("Progress meter enabled\n");
1094 printf("Progress meter disabled\n");
1097 fatal("%d is not implemented", cmdnum);
1107 /* If an unignored error occurs in batch mode we should abort. */
1108 if (err_abort && err != 0)
1110 else if (cmdnum == I_QUIT)
1117 interactive_loop(int fd_in, int fd_out, char *file1, char *file2)
1122 struct sftp_conn *conn;
1125 conn = do_init(fd_in, fd_out, copy_buffer_len, num_requests);
1127 fatal("Couldn't initialise connection to server");
1129 pwd = do_realpath(conn, ".");
1133 if (file1 != NULL) {
1134 dir = xstrdup(file1);
1135 dir = make_absolute(dir, pwd);
1137 if (remote_is_dir(conn, dir) && file2 == NULL) {
1138 printf("Changing to: %s\n", dir);
1139 snprintf(cmd, sizeof cmd, "cd \"%s\"", dir);
1140 if (parse_dispatch_command(conn, cmd, &pwd, 1) != 0)
1144 snprintf(cmd, sizeof cmd, "get %s", dir);
1146 snprintf(cmd, sizeof cmd, "get %s %s", dir,
1149 err = parse_dispatch_command(conn, cmd, &pwd, 1);
1158 setvbuf(stdout, NULL, _IOLBF, 0);
1159 setvbuf(infile, NULL, _IOLBF, 0);
1171 /* XXX: use libedit */
1172 if (fgets(cmd, sizeof(cmd), infile) == NULL) {
1175 } else if (infile != stdin) /* Bluff typing */
1178 cp = strrchr(cmd, '\n');
1182 err = parse_dispatch_command(conn, cmd, &pwd, infile != stdin);
1188 /* err == 1 signifies normal "quit" exit */
1189 return (err >= 0 ? 0 : -1);