2 * psftp.c: front end for PSFTP.
13 #define PUTTY_DO_GLOBALS
21 * Since SFTP is a request-response oriented protocol, it requires
22 * no buffer management: when we send data, we stop and wait for an
23 * acknowledgement _anyway_, and so we can't possibly overfill our
27 static int psftp_connect(char *userhost, char *user, int portnumber);
28 static int do_sftp_init(void);
30 /* ----------------------------------------------------------------------
36 static void *backhandle;
38 /* ----------------------------------------------------------------------
39 * Higher-level helper functions used in commands.
43 * Attempt to canonify a pathname starting from the pwd. If
44 * canonification fails, at least fall back to returning a _valid_
45 * pathname (though it may be ugly, eg /home/simon/../foobar).
47 char *canonify(char *name)
49 char *fullname, *canonname;
52 fullname = dupstr(name);
55 if (pwd[strlen(pwd) - 1] == '/')
59 fullname = dupcat(pwd, slash, name, NULL);
62 canonname = fxp_realpath(fullname);
69 * Attempt number 2. Some FXP_REALPATH implementations
70 * (glibc-based ones, in particular) require the _whole_
71 * path to point to something that exists, whereas others
72 * (BSD-based) only require all but the last component to
73 * exist. So if the first call failed, we should strip off
74 * everything from the last slash onwards and try again,
75 * then put the final component back on.
79 * - if the last component is "/." or "/..", then we don't
80 * bother trying this because there's no way it can work.
82 * - if the thing actually ends with a "/", we remove it
83 * before we start. Except if the string is "/" itself
84 * (although I can't see why we'd have got here if so,
85 * because surely "/" would have worked the first
86 * time?), in which case we don't bother.
88 * - if there's no slash in the string at all, give up in
89 * confusion (we expect at least one because of the way
90 * we constructed the string).
97 if (i > 2 && fullname[i - 1] == '/')
98 fullname[--i] = '\0'; /* strip trailing / unless at pos 0 */
99 while (i > 0 && fullname[--i] != '/');
102 * Give up on special cases.
104 if (fullname[i] != '/' || /* no slash at all */
105 !strcmp(fullname + i, "/.") || /* ends in /. */
106 !strcmp(fullname + i, "/..") || /* ends in /.. */
107 !strcmp(fullname, "/")) {
112 * Now i points at the slash. Deal with the final special
113 * case i==0 (ie the whole path was "/nonexistentfile").
115 fullname[i] = '\0'; /* separate the string */
117 canonname = fxp_realpath("/");
119 canonname = fxp_realpath(fullname);
123 return fullname; /* even that failed; give up */
126 * We have a canonical name for all but the last path
127 * component. Concatenate the last component and return.
129 returnname = dupcat(canonname,
130 canonname[strlen(canonname) - 1] ==
131 '/' ? "" : "/", fullname + i + 1, NULL);
139 * Return a pointer to the portion of str that comes after the last
140 * slash (or backslash or colon, if `local' is TRUE).
142 static char *stripslashes(char *str, int local)
147 p = strchr(str, ':');
151 p = strrchr(str, '/');
155 p = strrchr(str, '\\');
162 /* ----------------------------------------------------------------------
163 * Actual sftp commands.
165 struct sftp_command {
167 int nwords, wordssize;
168 int (*obey) (struct sftp_command *); /* returns <0 to quit */
171 int sftp_cmd_null(struct sftp_command *cmd)
173 return 1; /* success */
176 int sftp_cmd_unknown(struct sftp_command *cmd)
178 printf("psftp: unknown command \"%s\"\n", cmd->words[0]);
179 return 0; /* failure */
182 int sftp_cmd_quit(struct sftp_command *cmd)
188 * List a directory. If no arguments are given, list pwd; otherwise
189 * list the directory given in words[1].
191 static int sftp_ls_compare(const void *av, const void *bv)
193 const struct fxp_name *const *a = (const struct fxp_name *const *) av;
194 const struct fxp_name *const *b = (const struct fxp_name *const *) bv;
195 return strcmp((*a)->filename, (*b)->filename);
197 int sftp_cmd_ls(struct sftp_command *cmd)
199 struct fxp_handle *dirh;
200 struct fxp_names *names;
201 struct fxp_name **ournames;
202 int nnames, namesize;
207 printf("psftp: not connected to a host; use \"open host.name\"\n");
216 cdir = canonify(dir);
218 printf("%s: %s\n", dir, fxp_error());
222 printf("Listing directory %s\n", cdir);
224 dirh = fxp_opendir(cdir);
226 printf("Unable to open %s: %s\n", dir, fxp_error());
228 nnames = namesize = 0;
233 names = fxp_readdir(dirh);
235 if (fxp_error_type() == SSH_FX_EOF)
237 printf("Reading directory %s: %s\n", dir, fxp_error());
240 if (names->nnames == 0) {
241 fxp_free_names(names);
245 if (nnames + names->nnames >= namesize) {
246 namesize += names->nnames + 128;
248 srealloc(ournames, namesize * sizeof(*ournames));
251 for (i = 0; i < names->nnames; i++)
252 ournames[nnames++] = fxp_dup_name(&names->names[i]);
254 fxp_free_names(names);
259 * Now we have our filenames. Sort them by actual file
260 * name, and then output the longname parts.
262 qsort(ournames, nnames, sizeof(*ournames), sftp_ls_compare);
267 for (i = 0; i < nnames; i++) {
268 printf("%s\n", ournames[i]->longname);
269 fxp_free_name(ournames[i]);
280 * Change directories. We do this by canonifying the new name, then
281 * trying to OPENDIR it. Only if that succeeds do we set the new pwd.
283 int sftp_cmd_cd(struct sftp_command *cmd)
285 struct fxp_handle *dirh;
289 printf("psftp: not connected to a host; use \"open host.name\"\n");
294 dir = dupstr(homedir);
296 dir = canonify(cmd->words[1]);
299 printf("%s: %s\n", dir, fxp_error());
303 dirh = fxp_opendir(dir);
305 printf("Directory %s: %s\n", dir, fxp_error());
314 printf("Remote directory is now %s\n", pwd);
320 * Print current directory. Easy as pie.
322 int sftp_cmd_pwd(struct sftp_command *cmd)
325 printf("psftp: not connected to a host; use \"open host.name\"\n");
329 printf("Remote directory is %s\n", pwd);
334 * Get a file and save it at the local end. We have two very
335 * similar commands here: `get' and `reget', which differ in that
336 * `reget' checks for the existence of the destination file and
337 * starts from where a previous aborted transfer left off.
339 int sftp_general_get(struct sftp_command *cmd, int restart)
341 struct fxp_handle *fh;
342 char *fname, *outfname;
348 printf("psftp: not connected to a host; use \"open host.name\"\n");
352 if (cmd->nwords < 2) {
353 printf("get: expects a filename\n");
357 fname = canonify(cmd->words[1]);
359 printf("%s: %s\n", cmd->words[1], fxp_error());
362 outfname = (cmd->nwords == 2 ?
363 stripslashes(cmd->words[1], 0) : cmd->words[2]);
365 fh = fxp_open(fname, SSH_FXF_READ);
367 printf("%s: %s\n", fname, fxp_error());
373 fp = fopen(outfname, "rb+");
375 fp = fopen(outfname, "wb");
379 printf("local: unable to open %s\n", outfname);
387 fseek(fp, 0L, SEEK_END);
389 printf("reget: restarting at file position %ld\n", posn);
390 offset = uint64_make(0, posn);
392 offset = uint64_make(0, 0);
395 printf("remote:%s => local:%s\n", fname, outfname);
398 * FIXME: we can use FXP_FSTAT here to get the file size, and
399 * thus put up a progress bar.
407 len = fxp_read(fh, buffer, offset, sizeof(buffer));
408 if ((len == -1 && fxp_error_type() == SSH_FX_EOF) || len == 0)
411 printf("error while reading: %s\n", fxp_error());
418 wlen = fwrite(buffer, 1, len - wpos, fp);
420 printf("error while writing local file\n");
426 if (wpos < len) { /* we had an error */
430 offset = uint64_add32(offset, len);
439 int sftp_cmd_get(struct sftp_command *cmd)
441 return sftp_general_get(cmd, 0);
443 int sftp_cmd_reget(struct sftp_command *cmd)
445 return sftp_general_get(cmd, 1);
449 * Send a file and store it at the remote end. We have two very
450 * similar commands here: `put' and `reput', which differ in that
451 * `reput' checks for the existence of the destination file and
452 * starts from where a previous aborted transfer left off.
454 int sftp_general_put(struct sftp_command *cmd, int restart)
456 struct fxp_handle *fh;
457 char *fname, *origoutfname, *outfname;
463 printf("psftp: not connected to a host; use \"open host.name\"\n");
467 if (cmd->nwords < 2) {
468 printf("put: expects a filename\n");
472 fname = cmd->words[1];
473 origoutfname = (cmd->nwords == 2 ?
474 stripslashes(cmd->words[1], 1) : cmd->words[2]);
475 outfname = canonify(origoutfname);
477 printf("%s: %s\n", origoutfname, fxp_error());
481 fp = fopen(fname, "rb");
483 printf("local: unable to open %s\n", fname);
488 fh = fxp_open(outfname,
491 fh = fxp_open(outfname,
492 SSH_FXF_WRITE | SSH_FXF_CREAT | SSH_FXF_TRUNC);
495 printf("%s: %s\n", outfname, fxp_error());
502 struct fxp_attrs attrs;
503 if (!fxp_fstat(fh, &attrs)) {
504 printf("read size of %s: %s\n", outfname, fxp_error());
508 if (!(attrs.flags & SSH_FILEXFER_ATTR_SIZE)) {
509 printf("read size of %s: size was not given\n", outfname);
514 uint64_decimal(offset, decbuf);
515 printf("reput: restarting at file position %s\n", decbuf);
516 if (uint64_compare(offset, uint64_make(0, LONG_MAX)) > 0) {
517 printf("reput: remote file is larger than we can deal with\n");
521 if (fseek(fp, offset.lo, SEEK_SET) != 0)
522 fseek(fp, 0, SEEK_END); /* *shrug* */
524 offset = uint64_make(0, 0);
527 printf("local:%s => remote:%s\n", fname, outfname);
530 * FIXME: we can use FXP_FSTAT here to get the file size, and
531 * thus put up a progress bar.
538 len = fread(buffer, 1, sizeof(buffer), fp);
540 printf("error while reading local file\n");
543 } else if (len == 0) {
546 if (!fxp_write(fh, buffer, offset, len)) {
547 printf("error while writing: %s\n", fxp_error());
551 offset = uint64_add32(offset, len);
560 int sftp_cmd_put(struct sftp_command *cmd)
562 return sftp_general_put(cmd, 0);
564 int sftp_cmd_reput(struct sftp_command *cmd)
566 return sftp_general_put(cmd, 1);
569 int sftp_cmd_mkdir(struct sftp_command *cmd)
575 printf("psftp: not connected to a host; use \"open host.name\"\n");
579 if (cmd->nwords < 2) {
580 printf("mkdir: expects a directory\n");
584 dir = canonify(cmd->words[1]);
586 printf("%s: %s\n", dir, fxp_error());
590 result = fxp_mkdir(dir);
592 printf("mkdir %s: %s\n", dir, fxp_error());
601 int sftp_cmd_rmdir(struct sftp_command *cmd)
607 printf("psftp: not connected to a host; use \"open host.name\"\n");
611 if (cmd->nwords < 2) {
612 printf("rmdir: expects a directory\n");
616 dir = canonify(cmd->words[1]);
618 printf("%s: %s\n", dir, fxp_error());
622 result = fxp_rmdir(dir);
624 printf("rmdir %s: %s\n", dir, fxp_error());
633 int sftp_cmd_rm(struct sftp_command *cmd)
639 printf("psftp: not connected to a host; use \"open host.name\"\n");
643 if (cmd->nwords < 2) {
644 printf("rm: expects a filename\n");
648 fname = canonify(cmd->words[1]);
650 printf("%s: %s\n", fname, fxp_error());
654 result = fxp_remove(fname);
656 printf("rm %s: %s\n", fname, fxp_error());
665 int sftp_cmd_mv(struct sftp_command *cmd)
667 char *srcfname, *dstfname;
671 printf("psftp: not connected to a host; use \"open host.name\"\n");
675 if (cmd->nwords < 3) {
676 printf("mv: expects two filenames\n");
679 srcfname = canonify(cmd->words[1]);
681 printf("%s: %s\n", srcfname, fxp_error());
685 dstfname = canonify(cmd->words[2]);
687 printf("%s: %s\n", dstfname, fxp_error());
691 result = fxp_rename(srcfname, dstfname);
693 char const *error = fxp_error();
694 struct fxp_attrs attrs;
697 * The move might have failed because dstfname pointed at a
698 * directory. We check this possibility now: if dstfname
699 * _is_ a directory, we re-attempt the move by appending
700 * the basename of srcfname to dstfname.
702 result = fxp_stat(dstfname, &attrs);
704 (attrs.flags & SSH_FILEXFER_ATTR_PERMISSIONS) &&
705 (attrs.permissions & 0040000)) {
707 char *newname, *newcanon;
708 printf("(destination %s is a directory)\n", dstfname);
709 p = srcfname + strlen(srcfname);
710 while (p > srcfname && p[-1] != '/') p--;
711 newname = dupcat(dstfname, "/", p, NULL);
712 newcanon = canonify(newname);
717 result = fxp_rename(srcfname, dstfname);
718 error = result ? NULL : fxp_error();
722 printf("mv %s %s: %s\n", srcfname, dstfname, error);
728 printf("%s -> %s\n", srcfname, dstfname);
735 int sftp_cmd_chmod(struct sftp_command *cmd)
739 struct fxp_attrs attrs;
740 unsigned attrs_clr, attrs_xor, oldperms, newperms;
743 printf("psftp: not connected to a host; use \"open host.name\"\n");
747 if (cmd->nwords < 3) {
748 printf("chmod: expects a mode specifier and a filename\n");
753 * Attempt to parse the mode specifier in cmd->words[1]. We
754 * don't support the full horror of Unix chmod; instead we
755 * support a much simpler syntax in which the user can either
756 * specify an octal number, or a comma-separated sequence of
757 * [ugoa]*[-+=][rwxst]+. (The initial [ugoa] sequence may
758 * _only_ be omitted if the only attribute mentioned is t,
759 * since all others require a user/group/other specification.
760 * Additionally, the s attribute may not be specified for any
761 * [ugoa] specifications other than exactly u or exactly g.
763 attrs_clr = attrs_xor = 0;
764 mode = cmd->words[1];
765 if (mode[0] >= '0' && mode[0] <= '9') {
766 if (mode[strspn(mode, "01234567")]) {
767 printf("chmod: numeric file modes should"
768 " contain digits 0-7 only\n");
772 sscanf(mode, "%o", &attrs_xor);
773 attrs_xor &= attrs_clr;
776 char *modebegin = mode;
777 unsigned subset, perms;
781 while (*mode && *mode != ',' &&
782 *mode != '+' && *mode != '-' && *mode != '=') {
784 case 'u': subset |= 04700; break; /* setuid, user perms */
785 case 'g': subset |= 02070; break; /* setgid, group perms */
786 case 'o': subset |= 00007; break; /* just other perms */
787 case 'a': subset |= 06777; break; /* all of the above */
789 printf("chmod: file mode '%.*s' contains unrecognised"
790 " user/group/other specifier '%c'\n",
791 strcspn(modebegin, ","), modebegin, *mode);
796 if (!*mode || *mode == ',') {
797 printf("chmod: file mode '%.*s' is incomplete\n",
798 strcspn(modebegin, ","), modebegin);
802 if (!*mode || *mode == ',') {
803 printf("chmod: file mode '%.*s' is incomplete\n",
804 strcspn(modebegin, ","), modebegin);
808 while (*mode && *mode != ',') {
810 case 'r': perms |= 00444; break;
811 case 'w': perms |= 00222; break;
812 case 'x': perms |= 00111; break;
813 case 't': perms |= 01000; subset |= 01000; break;
815 if ((subset & 06777) != 04700 &&
816 (subset & 06777) != 02070) {
817 printf("chmod: file mode '%.*s': set[ug]id bit should"
818 " be used with exactly one of u or g only\n",
819 strcspn(modebegin, ","), modebegin);
825 printf("chmod: file mode '%.*s' contains unrecognised"
826 " permission specifier '%c'\n",
827 strcspn(modebegin, ","), modebegin, *mode);
832 if (!(subset & 06777) && (perms &~ subset)) {
833 printf("chmod: file mode '%.*s' contains no user/group/other"
834 " specifier and permissions other than 't' \n",
835 strcspn(modebegin, ","), modebegin);
853 if (*mode) mode++; /* eat comma */
857 fname = canonify(cmd->words[2]);
859 printf("%s: %s\n", fname, fxp_error());
863 result = fxp_stat(fname, &attrs);
864 if (!result || !(attrs.flags & SSH_FILEXFER_ATTR_PERMISSIONS)) {
865 printf("get attrs for %s: %s\n", fname,
866 result ? "file permissions not provided" : fxp_error());
871 attrs.flags = SSH_FILEXFER_ATTR_PERMISSIONS; /* perms _only_ */
872 oldperms = attrs.permissions & 07777;
873 attrs.permissions &= ~attrs_clr;
874 attrs.permissions ^= attrs_xor;
875 newperms = attrs.permissions & 07777;
877 result = fxp_setstat(fname, attrs);
880 printf("set attrs for %s: %s\n", fname, fxp_error());
885 printf("%s: %04o -> %04o\n", fname, oldperms, newperms);
891 static int sftp_cmd_open(struct sftp_command *cmd)
894 printf("psftp: already connected\n");
898 if (cmd->nwords < 2) {
899 printf("open: expects a host name\n");
903 if (psftp_connect(cmd->words[1], NULL, 0)) {
904 back = NULL; /* connection is already closed */
905 return -1; /* this is fatal */
911 static int sftp_cmd_lcd(struct sftp_command *cmd)
916 if (cmd->nwords < 2) {
917 printf("lcd: expects a local directory name\n");
921 if (!SetCurrentDirectory(cmd->words[1])) {
924 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
925 FORMAT_MESSAGE_FROM_SYSTEM |
926 FORMAT_MESSAGE_IGNORE_INSERTS,
927 NULL, GetLastError(),
928 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
929 (LPTSTR)&message, 0, NULL);
930 i = strcspn((char *)message, "\n");
931 printf("lcd: unable to change directory: %.*s\n", i, (LPCTSTR)message);
936 currdir = smalloc(256);
937 len = GetCurrentDirectory(256, currdir);
939 currdir = srealloc(currdir, len);
940 GetCurrentDirectory(len, currdir);
941 printf("New local directory is %s\n", currdir);
947 static int sftp_cmd_lpwd(struct sftp_command *cmd)
952 currdir = smalloc(256);
953 len = GetCurrentDirectory(256, currdir);
955 currdir = srealloc(currdir, len);
956 GetCurrentDirectory(len, currdir);
957 printf("Current local directory is %s\n", currdir);
963 static int sftp_cmd_pling(struct sftp_command *cmd)
967 exitcode = system(cmd->words[1]);
968 return (exitcode == 0);
971 static int sftp_cmd_help(struct sftp_command *cmd);
973 static struct sftp_cmd_lookup {
976 * For help purposes, there are two kinds of command:
978 * - primary commands, in which `longhelp' is non-NULL. In
979 * this case `shorthelp' is descriptive text, and `longhelp'
980 * is longer descriptive text intended to be printed after
983 * - alias commands, in which `longhelp' is NULL. In this case
984 * `shorthelp' is the name of a primary command, which
985 * contains the help that should double up for this command.
987 int listed; /* do we list this in primary help? */
990 int (*obey) (struct sftp_command *);
993 * List of sftp commands. This is binary-searched so it MUST be
997 "!", TRUE, "run a local Windows command",
999 " Runs a local Windows command. For example, \"!del myfile\".\n",
1003 "bye", TRUE, "finish your SFTP session",
1005 " Terminates your SFTP session and quits the PSFTP program.\n",
1009 "cd", TRUE, "change your remote working directory",
1010 " [ <New working directory> ]\n"
1011 " Change the remote working directory for your SFTP session.\n"
1012 " If a new working directory is not supplied, you will be\n"
1013 " returned to your home directory.\n",
1017 "chmod", TRUE, "change file permissions and modes",
1018 " ( <octal-digits> | <modifiers> ) <filename>\n"
1019 " Change the file permissions on a file or directory.\n"
1020 " <octal-digits> can be any octal Unix permission specifier.\n"
1021 " Alternatively, <modifiers> can include:\n"
1022 " u+r make file readable by owning user\n"
1023 " u+w make file writable by owning user\n"
1024 " u+x make file executable by owning user\n"
1025 " u-r make file not readable by owning user\n"
1026 " [also u-w, u-x]\n"
1027 " g+r make file readable by members of owning group\n"
1028 " [also g+w, g+x, g-r, g-w, g-x]\n"
1029 " o+r make file readable by all other users\n"
1030 " [also o+w, o+x, o-r, o-w, o-x]\n"
1031 " a+r make file readable by absolutely everybody\n"
1032 " [also a+w, a+x, a-r, a-w, a-x]\n"
1033 " u+s enable the Unix set-user-ID bit\n"
1034 " u-s disable the Unix set-user-ID bit\n"
1035 " g+s enable the Unix set-group-ID bit\n"
1036 " g-s disable the Unix set-group-ID bit\n"
1037 " +t enable the Unix \"sticky bit\"\n"
1038 " You can give more than one modifier for the same user (\"g-rwx\"), and\n"
1039 " more than one user for the same modifier (\"ug+w\"). You can\n"
1040 " use commas to separate different modifiers (\"u+rwx,g+s\").\n",
1044 "del", TRUE, "delete a file",
1046 " Delete a file.\n",
1050 "delete", FALSE, "del", NULL, sftp_cmd_rm
1053 "dir", TRUE, "list contents of a remote directory",
1054 " [ <directory-name> ]\n"
1055 " List the contents of a specified directory on the server.\n"
1056 " If <directory-name> is not given, the current working directory\n"
1057 " will be listed.\n",
1061 "exit", TRUE, "bye", NULL, sftp_cmd_quit
1064 "get", TRUE, "download a file from the server to your local machine",
1065 " <filename> [ <local-filename> ]\n"
1066 " Downloads a file on the server and stores it locally under\n"
1067 " the same name, or under a different one if you supply the\n"
1068 " argument <local-filename>.\n",
1072 "help", TRUE, "give help",
1073 " [ <command> [ <command> ... ] ]\n"
1074 " Give general help if no commands are specified.\n"
1075 " If one or more commands are specified, give specific help on\n"
1076 " those particular commands.\n",
1080 "lcd", TRUE, "change local working directory",
1081 " <local-directory-name>\n"
1082 " Change the local working directory of the PSFTP program (the\n"
1083 " default location where the \"get\" command will save files).\n",
1087 "lpwd", TRUE, "print local working directory",
1089 " Print the local working directory of the PSFTP program (the\n"
1090 " default location where the \"get\" command will save files).\n",
1094 "ls", TRUE, "dir", NULL,
1098 "mkdir", TRUE, "create a directory on the remote server",
1099 " <directory-name>\n"
1100 " Creates a directory with the given name on the server.\n",
1104 "mv", TRUE, "move or rename a file on the remote server",
1105 " <source-filename> <destination-filename>\n"
1106 " Moves or renames the file <source-filename> on the server,\n"
1107 " so that it is accessible under the name <destination-filename>.\n",
1111 "open", TRUE, "connect to a host",
1112 " [<user>@]<hostname>\n"
1113 " Establishes an SFTP connection to a given host. Only usable\n"
1114 " when you did not already specify a host name on the command\n"
1119 "put", TRUE, "upload a file from your local machine to the server",
1120 " <filename> [ <remote-filename> ]\n"
1121 " Uploads a file to the server and stores it there under\n"
1122 " the same name, or under a different one if you supply the\n"
1123 " argument <remote-filename>.\n",
1127 "pwd", TRUE, "print your remote working directory",
1129 " Print the current remote working directory for your SFTP session.\n",
1133 "quit", TRUE, "bye", NULL,
1137 "reget", TRUE, "continue downloading a file",
1138 " <filename> [ <local-filename> ]\n"
1139 " Works exactly like the \"get\" command, but the local file\n"
1140 " must already exist. The download will begin at the end of the\n"
1141 " file. This is for resuming a download that was interrupted.\n",
1145 "ren", TRUE, "mv", NULL,
1149 "rename", FALSE, "mv", NULL,
1153 "reput", TRUE, "continue uploading a file",
1154 " <filename> [ <remote-filename> ]\n"
1155 " Works exactly like the \"put\" command, but the remote file\n"
1156 " must already exist. The upload will begin at the end of the\n"
1157 " file. This is for resuming an upload that was interrupted.\n",
1161 "rm", TRUE, "del", NULL,
1165 "rmdir", TRUE, "remove a directory on the remote server",
1166 " <directory-name>\n"
1167 " Removes the directory with the given name on the server.\n"
1168 " The directory will not be removed unless it is empty.\n",
1173 const struct sftp_cmd_lookup *lookup_command(char *name)
1178 j = sizeof(sftp_lookup) / sizeof(*sftp_lookup);
1181 cmp = strcmp(name, sftp_lookup[k].name);
1187 return &sftp_lookup[k];
1193 static int sftp_cmd_help(struct sftp_command *cmd)
1196 if (cmd->nwords == 1) {
1198 * Give short help on each command.
1202 for (i = 0; i < sizeof(sftp_lookup) / sizeof(*sftp_lookup); i++) {
1204 if (!sftp_lookup[i].listed)
1206 len = strlen(sftp_lookup[i].name);
1210 for (i = 0; i < sizeof(sftp_lookup) / sizeof(*sftp_lookup); i++) {
1211 const struct sftp_cmd_lookup *lookup;
1212 if (!sftp_lookup[i].listed)
1214 lookup = &sftp_lookup[i];
1215 printf("%-*s", maxlen+2, lookup->name);
1216 if (lookup->longhelp == NULL)
1217 lookup = lookup_command(lookup->shorthelp);
1218 printf("%s\n", lookup->shorthelp);
1222 * Give long help on specific commands.
1224 for (i = 1; i < cmd->nwords; i++) {
1225 const struct sftp_cmd_lookup *lookup;
1226 lookup = lookup_command(cmd->words[i]);
1228 printf("help: %s: command not found\n", cmd->words[i]);
1230 printf("%s", lookup->name);
1231 if (lookup->longhelp == NULL)
1232 lookup = lookup_command(lookup->shorthelp);
1233 printf("%s", lookup->longhelp);
1240 /* ----------------------------------------------------------------------
1241 * Command line reading and parsing.
1243 struct sftp_command *sftp_getcmd(FILE *fp, int mode, int modeflags)
1246 int linelen, linesize;
1247 struct sftp_command *cmd;
1251 if ((mode == 0) || (modeflags & 1)) {
1256 cmd = smalloc(sizeof(struct sftp_command));
1262 linesize = linelen = 0;
1268 line = srealloc(line, linesize);
1269 ret = fgets(line + linelen, linesize - linelen, fp);
1271 if (!ret || (linelen == 0 && line[0] == '\0')) {
1272 cmd->obey = sftp_cmd_quit;
1273 if ((mode == 0) || (modeflags & 1))
1275 return cmd; /* eof */
1277 len = linelen + strlen(line + linelen);
1279 if (line[linelen - 1] == '\n') {
1281 line[linelen] = '\0';
1285 if (modeflags & 1) {
1286 printf("%s\n", line);
1290 while (*p && (*p == ' ' || *p == '\t'))
1295 * Special case: the ! command. This is always parsed as
1296 * exactly two words: one containing the !, and the second
1297 * containing everything else on the line.
1299 cmd->nwords = cmd->wordssize = 2;
1300 cmd->words = srealloc(cmd->words, cmd->wordssize * sizeof(char *));
1301 cmd->words[0] = "!";
1302 cmd->words[1] = p+1;
1306 * Parse the command line into words. The syntax is:
1307 * - double quotes are removed, but cause spaces within to be
1308 * treated as non-separating.
1309 * - a double-doublequote pair is a literal double quote, inside
1310 * _or_ outside quotes. Like this:
1312 * firstword "second word" "this has ""quotes"" in" and""this""
1318 * >this has "quotes" in<
1322 /* skip whitespace */
1323 while (*p && (*p == ' ' || *p == '\t'))
1325 /* mark start of word */
1326 q = r = p; /* q sits at start, r writes word */
1329 if (!quoting && (*p == ' ' || *p == '\t'))
1330 break; /* reached end of word */
1331 else if (*p == '"' && p[1] == '"')
1332 p += 2, *r++ = '"'; /* a literal quote */
1334 p++, quoting = !quoting;
1339 p++; /* skip over the whitespace */
1341 if (cmd->nwords >= cmd->wordssize) {
1342 cmd->wordssize = cmd->nwords + 16;
1344 srealloc(cmd->words, cmd->wordssize * sizeof(char *));
1346 cmd->words[cmd->nwords++] = q;
1351 * Now parse the first word and assign a function.
1354 if (cmd->nwords == 0)
1355 cmd->obey = sftp_cmd_null;
1357 const struct sftp_cmd_lookup *lookup;
1358 lookup = lookup_command(cmd->words[0]);
1360 cmd->obey = sftp_cmd_unknown;
1362 cmd->obey = lookup->obey;
1368 static int do_sftp_init(void)
1371 * Do protocol initialisation.
1375 "Fatal: unable to initialise SFTP: %s\n", fxp_error());
1376 return 1; /* failure */
1380 * Find out where our home directory is.
1382 homedir = fxp_realpath(".");
1385 "Warning: failed to resolve home directory: %s\n",
1387 homedir = dupstr(".");
1389 printf("Remote working directory is %s\n", homedir);
1391 pwd = dupstr(homedir);
1395 void do_sftp(int mode, int modeflags, char *batchfile)
1405 /* ------------------------------------------------------------------
1406 * Now we're ready to do Real Stuff.
1409 struct sftp_command *cmd;
1410 cmd = sftp_getcmd(stdin, 0, 0);
1413 if (cmd->obey(cmd) < 0)
1417 fp = fopen(batchfile, "r");
1419 printf("Fatal: unable to open %s\n", batchfile);
1423 struct sftp_command *cmd;
1424 cmd = sftp_getcmd(fp, mode, modeflags);
1427 ret = cmd->obey(cmd);
1431 if (!(modeflags & 2))
1440 /* ----------------------------------------------------------------------
1441 * Dirty bits: integration with PuTTY.
1444 static int verbose = 0;
1447 * Print an error message and perform a fatal exit.
1449 void fatalbox(char *fmt, ...)
1454 str = dupvprintf(fmt, ap);
1455 str2 = dupcat("Fatal: ", str, "\n", NULL);
1458 fputs(str2, stderr);
1463 void modalfatalbox(char *fmt, ...)
1468 str = dupvprintf(fmt, ap);
1469 str2 = dupcat("Fatal: ", str, "\n", NULL);
1472 fputs(str2, stderr);
1477 void connection_fatal(void *frontend, char *fmt, ...)
1482 str = dupvprintf(fmt, ap);
1483 str2 = dupcat("Fatal: ", str, "\n", NULL);
1486 fputs(str2, stderr);
1492 void ldisc_send(void *handle, char *buf, int len, int interactive)
1495 * This is only here because of the calls to ldisc_send(NULL,
1496 * 0) in ssh.c. Nothing in PSFTP actually needs to use the
1497 * ldisc as an ldisc. So if we get called with any real data, I
1498 * want to know about it.
1504 * Be told what socket we're supposed to be using.
1506 static SOCKET sftp_ssh_socket;
1507 char *do_select(SOCKET skt, int startup)
1510 sftp_ssh_socket = skt;
1512 sftp_ssh_socket = INVALID_SOCKET;
1515 extern int select_result(WPARAM, LPARAM);
1518 * Receive a block of data from the SSH link. Block until all data
1521 * To do this, we repeatedly call the SSH protocol module, with our
1522 * own trap in from_backend() to catch the data that comes back. We
1523 * do this until we have enough data.
1526 static unsigned char *outptr; /* where to put the data */
1527 static unsigned outlen; /* how much data required */
1528 static unsigned char *pending = NULL; /* any spare data */
1529 static unsigned pendlen = 0, pendsize = 0; /* length and phys. size of buffer */
1530 int from_backend(void *frontend, int is_stderr, char *data, int datalen)
1532 unsigned char *p = (unsigned char *) data;
1533 unsigned len = (unsigned) datalen;
1538 * stderr data is just spouted to local stderr and otherwise
1542 fwrite(data, 1, len, stderr);
1547 * If this is before the real session begins, just return.
1553 unsigned used = outlen;
1556 memcpy(outptr, p, used);
1564 if (pendsize < pendlen + len) {
1565 pendsize = pendlen + len + 4096;
1566 pending = (pending ? srealloc(pending, pendsize) :
1569 fatalbox("Out of memory");
1571 memcpy(pending + pendlen, p, len);
1577 int sftp_recvdata(char *buf, int len)
1579 outptr = (unsigned char *) buf;
1583 * See if the pending-input block contains some of what we
1587 unsigned pendused = pendlen;
1588 if (pendused > outlen)
1590 memcpy(outptr, pending, pendused);
1591 memmove(pending, pending + pendused, pendlen - pendused);
1594 pendlen -= pendused;
1604 while (outlen > 0) {
1608 FD_SET(sftp_ssh_socket, &readfds);
1609 if (select(1, &readfds, NULL, NULL, NULL) < 0)
1610 return 0; /* doom */
1611 select_result((WPARAM) sftp_ssh_socket, (LPARAM) FD_READ);
1616 int sftp_senddata(char *buf, int len)
1618 back->send(backhandle, (unsigned char *) buf, len);
1623 * Loop through the ssh connection and authentication process.
1625 static void ssh_sftp_init(void)
1627 if (sftp_ssh_socket == INVALID_SOCKET)
1629 while (!back->sendok(backhandle)) {
1632 FD_SET(sftp_ssh_socket, &readfds);
1633 if (select(1, &readfds, NULL, NULL, NULL) < 0)
1635 select_result((WPARAM) sftp_ssh_socket, (LPARAM) FD_READ);
1640 * Initialize the Win$ock driver.
1642 static void init_winsock(void)
1647 winsock_ver = MAKEWORD(1, 1);
1648 if (WSAStartup(winsock_ver, &wsadata)) {
1649 fprintf(stderr, "Unable to initialise WinSock");
1652 if (LOBYTE(wsadata.wVersion) != 1 || HIBYTE(wsadata.wVersion) != 1) {
1653 fprintf(stderr, "WinSock version is incompatible with 1.1");
1659 * Short description of parameters.
1661 static void usage(void)
1663 printf("PuTTY Secure File Transfer (SFTP) client\n");
1664 printf("%s\n", ver);
1665 printf("Usage: psftp [options] user@host\n");
1666 printf("Options:\n");
1667 printf(" -b file use specified batchfile\n");
1668 printf(" -bc output batchfile commands\n");
1669 printf(" -be don't stop batchfile processing if errors\n");
1670 printf(" -v show verbose messages\n");
1671 printf(" -load sessname Load settings from saved session\n");
1672 printf(" -l user connect with specified username\n");
1673 printf(" -P port connect to specified port\n");
1674 printf(" -pw passw login with specified password\n");
1675 printf(" -1 -2 force use of particular SSH protocol version\n");
1676 printf(" -C enable compression\n");
1677 printf(" -i key private key file for authentication\n");
1678 printf(" -batch disable all interactive prompts\n");
1683 * Connect to a host.
1685 static int psftp_connect(char *userhost, char *user, int portnumber)
1687 char *host, *realhost;
1690 /* Separate host and username */
1692 host = strrchr(host, '@');
1698 printf("psftp: multiple usernames specified; using \"%s\"\n",
1704 /* Try to load settings for this host */
1705 do_defaults(host, &cfg);
1706 if (cfg.host[0] == '\0') {
1707 /* No settings for this host; use defaults */
1708 do_defaults(NULL, &cfg);
1709 strncpy(cfg.host, host, sizeof(cfg.host) - 1);
1710 cfg.host[sizeof(cfg.host) - 1] = '\0';
1714 * Force use of SSH. (If they got the protocol wrong we assume the
1715 * port is useless too.)
1717 if (cfg.protocol != PROT_SSH) {
1718 cfg.protocol = PROT_SSH;
1723 * Enact command-line overrides.
1725 cmdline_run_saved(&cfg);
1728 * Trim leading whitespace off the hostname if it's there.
1731 int space = strspn(cfg.host, " \t");
1732 memmove(cfg.host, cfg.host+space, 1+strlen(cfg.host)-space);
1735 /* See if host is of the form user@host */
1736 if (cfg.host[0] != '\0') {
1737 char *atsign = strchr(cfg.host, '@');
1738 /* Make sure we're not overflowing the user field */
1740 if (atsign - cfg.host < sizeof cfg.username) {
1741 strncpy(cfg.username, cfg.host, atsign - cfg.host);
1742 cfg.username[atsign - cfg.host] = '\0';
1744 memmove(cfg.host, atsign + 1, 1 + strlen(atsign + 1));
1749 * Trim a colon suffix off the hostname if it's there.
1751 cfg.host[strcspn(cfg.host, ":")] = '\0';
1754 * Remove any remaining whitespace from the hostname.
1758 while (cfg.host[p2] != '\0') {
1759 if (cfg.host[p2] != ' ' && cfg.host[p2] != '\t') {
1760 cfg.host[p1] = cfg.host[p2];
1765 cfg.host[p1] = '\0';
1769 if (user != NULL && user[0] != '\0') {
1770 strncpy(cfg.username, user, sizeof(cfg.username) - 1);
1771 cfg.username[sizeof(cfg.username) - 1] = '\0';
1773 if (!cfg.username[0]) {
1774 printf("login as: ");
1776 if (!fgets(cfg.username, sizeof(cfg.username), stdin)) {
1777 fprintf(stderr, "psftp: aborting\n");
1780 int len = strlen(cfg.username);
1781 if (cfg.username[len - 1] == '\n')
1782 cfg.username[len - 1] = '\0';
1787 cfg.port = portnumber;
1789 /* SFTP uses SSH2 by default always */
1793 * Disable scary things which shouldn't be enabled for simple
1794 * things like SCP and SFTP: agent forwarding, port forwarding,
1797 cfg.x11_forward = 0;
1799 cfg.portfwd[0] = cfg.portfwd[1] = '\0';
1801 /* Set up subsystem name. */
1802 strcpy(cfg.remote_cmd, "sftp");
1803 cfg.ssh_subsys = TRUE;
1807 * Set up fallback option, for SSH1 servers or servers with the
1808 * sftp subsystem not enabled but the server binary installed
1809 * in the usual place. We only support fallback on Unix
1810 * systems, and we use a kludgy piece of shellery which should
1811 * try to find sftp-server in various places (the obvious
1812 * systemwide spots /usr/lib and /usr/local/lib, and then the
1813 * user's PATH) and finally give up.
1815 * test -x /usr/lib/sftp-server && exec /usr/lib/sftp-server
1816 * test -x /usr/local/lib/sftp-server && exec /usr/local/lib/sftp-server
1819 * the idea being that this will attempt to use either of the
1820 * obvious pathnames and then give up, and when it does give up
1821 * it will print the preferred pathname in the error messages.
1823 cfg.remote_cmd_ptr2 =
1824 "test -x /usr/lib/sftp-server && exec /usr/lib/sftp-server\n"
1825 "test -x /usr/local/lib/sftp-server && exec /usr/local/lib/sftp-server\n"
1827 cfg.ssh_subsys2 = FALSE;
1829 back = &ssh_backend;
1831 err = back->init(NULL, &backhandle, cfg.host, cfg.port, &realhost, 0);
1833 fprintf(stderr, "ssh_init: %s\n", err);
1836 logctx = log_init(NULL);
1837 back->provide_logctx(backhandle, logctx);
1839 if (verbose && realhost != NULL)
1840 printf("Connected to %s\n", realhost);
1844 void cmdline_error(char *p, ...)
1847 fprintf(stderr, "psftp: ");
1849 vfprintf(stderr, p, ap);
1851 fprintf(stderr, "\n try typing \"psftp -h\" for help\n");
1856 * Main program. Parse arguments etc.
1858 int main(int argc, char *argv[])
1862 char *userhost, *user;
1865 char *batchfile = NULL;
1868 flags = FLAG_STDERR | FLAG_INTERACTIVE;
1869 cmdline_tooltype = TOOLTYPE_FILETRANSFER;
1870 ssh_get_line = &console_get_line;
1874 userhost = user = NULL;
1877 for (i = 1; i < argc; i++) {
1879 if (argv[i][0] != '-') {
1883 userhost = dupstr(argv[i]);
1886 ret = cmdline_process_param(argv[i], i+1<argc?argv[i+1]:NULL, 1, &cfg);
1888 cmdline_error("option \"%s\" requires an argument", argv[i]);
1889 } else if (ret == 2) {
1890 i++; /* skip next argument */
1891 } else if (ret == 1) {
1892 /* We have our own verbosity in addition to `flags'. */
1893 if (flags & FLAG_VERBOSE)
1895 } else if (strcmp(argv[i], "-h") == 0 ||
1896 strcmp(argv[i], "-?") == 0) {
1898 } else if (strcmp(argv[i], "-batch") == 0) {
1899 console_batch_mode = 1;
1900 } else if (strcmp(argv[i], "-b") == 0 && i + 1 < argc) {
1902 batchfile = argv[++i];
1903 } else if (strcmp(argv[i], "-bc") == 0) {
1904 modeflags = modeflags | 1;
1905 } else if (strcmp(argv[i], "-be") == 0) {
1906 modeflags = modeflags | 2;
1907 } else if (strcmp(argv[i], "--") == 0) {
1911 cmdline_error("unknown option \"%s\"", argv[i]);
1919 * If a user@host string has already been provided, connect to
1923 if (psftp_connect(userhost, user, portnumber))
1928 printf("psftp: no hostname specified; use \"open host.name\""
1932 do_sftp(mode, modeflags, batchfile);
1934 if (back != NULL && back->socket(backhandle) != NULL) {
1936 back->special(backhandle, TS_EOF);
1937 sftp_recvdata(&ch, 1);