2 * psftp.c: front end for PSFTP.
11 #define PUTTY_DO_GLOBALS
20 * Since SFTP is a request-response oriented protocol, it requires
21 * no buffer management: when we send data, we stop and wait for an
22 * acknowledgement _anyway_, and so we can't possibly overfill our
26 static int psftp_connect(char *userhost, char *user, int portnumber);
27 static int do_sftp_init(void);
28 void do_sftp_cleanup();
30 /* ----------------------------------------------------------------------
36 static void *backhandle;
39 /* ----------------------------------------------------------------------
40 * Higher-level helper functions used in commands.
44 * Attempt to canonify a pathname starting from the pwd. If
45 * canonification fails, at least fall back to returning a _valid_
46 * pathname (though it may be ugly, eg /home/simon/../foobar).
48 char *canonify(char *name)
50 char *fullname, *canonname;
51 struct sftp_packet *pktin;
52 struct sftp_request *req, *rreq;
55 fullname = dupstr(name);
58 if (pwd[strlen(pwd) - 1] == '/')
62 fullname = dupcat(pwd, slash, name, NULL);
65 sftp_register(req = fxp_realpath_send(fullname));
66 rreq = sftp_find_request(pktin = sftp_recv());
68 canonname = fxp_realpath_recv(pktin, rreq);
75 * Attempt number 2. Some FXP_REALPATH implementations
76 * (glibc-based ones, in particular) require the _whole_
77 * path to point to something that exists, whereas others
78 * (BSD-based) only require all but the last component to
79 * exist. So if the first call failed, we should strip off
80 * everything from the last slash onwards and try again,
81 * then put the final component back on.
85 * - if the last component is "/." or "/..", then we don't
86 * bother trying this because there's no way it can work.
88 * - if the thing actually ends with a "/", we remove it
89 * before we start. Except if the string is "/" itself
90 * (although I can't see why we'd have got here if so,
91 * because surely "/" would have worked the first
92 * time?), in which case we don't bother.
94 * - if there's no slash in the string at all, give up in
95 * confusion (we expect at least one because of the way
96 * we constructed the string).
102 i = strlen(fullname);
103 if (i > 2 && fullname[i - 1] == '/')
104 fullname[--i] = '\0'; /* strip trailing / unless at pos 0 */
105 while (i > 0 && fullname[--i] != '/');
108 * Give up on special cases.
110 if (fullname[i] != '/' || /* no slash at all */
111 !strcmp(fullname + i, "/.") || /* ends in /. */
112 !strcmp(fullname + i, "/..") || /* ends in /.. */
113 !strcmp(fullname, "/")) {
118 * Now i points at the slash. Deal with the final special
119 * case i==0 (ie the whole path was "/nonexistentfile").
121 fullname[i] = '\0'; /* separate the string */
123 sftp_register(req = fxp_realpath_send("/"));
125 sftp_register(req = fxp_realpath_send(fullname));
127 rreq = sftp_find_request(pktin = sftp_recv());
129 canonname = fxp_realpath_recv(pktin, rreq);
132 return fullname; /* even that failed; give up */
135 * We have a canonical name for all but the last path
136 * component. Concatenate the last component and return.
138 returnname = dupcat(canonname,
139 canonname[strlen(canonname) - 1] ==
140 '/' ? "" : "/", fullname + i + 1, NULL);
148 * Return a pointer to the portion of str that comes after the last
149 * slash (or backslash or colon, if `local' is TRUE).
151 static char *stripslashes(char *str, int local)
156 p = strchr(str, ':');
160 p = strrchr(str, '/');
164 p = strrchr(str, '\\');
171 /* ----------------------------------------------------------------------
172 * Actual sftp commands.
174 struct sftp_command {
176 int nwords, wordssize;
177 int (*obey) (struct sftp_command *); /* returns <0 to quit */
180 int sftp_cmd_null(struct sftp_command *cmd)
182 return 1; /* success */
185 int sftp_cmd_unknown(struct sftp_command *cmd)
187 printf("psftp: unknown command \"%s\"\n", cmd->words[0]);
188 return 0; /* failure */
191 int sftp_cmd_quit(struct sftp_command *cmd)
197 * List a directory. If no arguments are given, list pwd; otherwise
198 * list the directory given in words[1].
200 static int sftp_ls_compare(const void *av, const void *bv)
202 const struct fxp_name *const *a = (const struct fxp_name *const *) av;
203 const struct fxp_name *const *b = (const struct fxp_name *const *) bv;
204 return strcmp((*a)->filename, (*b)->filename);
206 int sftp_cmd_ls(struct sftp_command *cmd)
208 struct fxp_handle *dirh;
209 struct fxp_names *names;
210 struct fxp_name **ournames;
211 int nnames, namesize;
213 struct sftp_packet *pktin;
214 struct sftp_request *req, *rreq;
218 printf("psftp: not connected to a host; use \"open host.name\"\n");
227 cdir = canonify(dir);
229 printf("%s: %s\n", dir, fxp_error());
233 printf("Listing directory %s\n", cdir);
235 sftp_register(req = fxp_opendir_send(cdir));
236 rreq = sftp_find_request(pktin = sftp_recv());
238 dirh = fxp_opendir_recv(pktin, rreq);
241 printf("Unable to open %s: %s\n", dir, fxp_error());
243 nnames = namesize = 0;
248 sftp_register(req = fxp_readdir_send(dirh));
249 rreq = sftp_find_request(pktin = sftp_recv());
251 names = fxp_readdir_recv(pktin, rreq);
254 if (fxp_error_type() == SSH_FX_EOF)
256 printf("Reading directory %s: %s\n", dir, fxp_error());
259 if (names->nnames == 0) {
260 fxp_free_names(names);
264 if (nnames + names->nnames >= namesize) {
265 namesize += names->nnames + 128;
266 ournames = sresize(ournames, namesize, struct fxp_name *);
269 for (i = 0; i < names->nnames; i++)
270 ournames[nnames++] = fxp_dup_name(&names->names[i]);
272 fxp_free_names(names);
274 sftp_register(req = fxp_close_send(dirh));
275 rreq = sftp_find_request(pktin = sftp_recv());
277 fxp_close_recv(pktin, rreq);
280 * Now we have our filenames. Sort them by actual file
281 * name, and then output the longname parts.
283 qsort(ournames, nnames, sizeof(*ournames), sftp_ls_compare);
288 for (i = 0; i < nnames; i++) {
289 printf("%s\n", ournames[i]->longname);
290 fxp_free_name(ournames[i]);
301 * Change directories. We do this by canonifying the new name, then
302 * trying to OPENDIR it. Only if that succeeds do we set the new pwd.
304 int sftp_cmd_cd(struct sftp_command *cmd)
306 struct fxp_handle *dirh;
307 struct sftp_packet *pktin;
308 struct sftp_request *req, *rreq;
312 printf("psftp: not connected to a host; use \"open host.name\"\n");
317 dir = dupstr(homedir);
319 dir = canonify(cmd->words[1]);
322 printf("%s: %s\n", dir, fxp_error());
326 sftp_register(req = fxp_opendir_send(dir));
327 rreq = sftp_find_request(pktin = sftp_recv());
329 dirh = fxp_opendir_recv(pktin, rreq);
332 printf("Directory %s: %s\n", dir, fxp_error());
337 sftp_register(req = fxp_close_send(dirh));
338 rreq = sftp_find_request(pktin = sftp_recv());
340 fxp_close_recv(pktin, rreq);
344 printf("Remote directory is now %s\n", pwd);
350 * Print current directory. Easy as pie.
352 int sftp_cmd_pwd(struct sftp_command *cmd)
355 printf("psftp: not connected to a host; use \"open host.name\"\n");
359 printf("Remote directory is %s\n", pwd);
364 * Get a file and save it at the local end. We have two very
365 * similar commands here: `get' and `reget', which differ in that
366 * `reget' checks for the existence of the destination file and
367 * starts from where a previous aborted transfer left off.
369 int sftp_general_get(struct sftp_command *cmd, int restart)
371 struct fxp_handle *fh;
372 struct sftp_packet *pktin;
373 struct sftp_request *req, *rreq;
374 struct fxp_xfer *xfer;
375 char *fname, *outfname;
381 printf("psftp: not connected to a host; use \"open host.name\"\n");
385 if (cmd->nwords < 2) {
386 printf("get: expects a filename\n");
390 fname = canonify(cmd->words[1]);
392 printf("%s: %s\n", cmd->words[1], fxp_error());
395 outfname = (cmd->nwords == 2 ?
396 stripslashes(cmd->words[1], 0) : cmd->words[2]);
398 sftp_register(req = fxp_open_send(fname, SSH_FXF_READ));
399 rreq = sftp_find_request(pktin = sftp_recv());
401 fh = fxp_open_recv(pktin, rreq);
404 printf("%s: %s\n", fname, fxp_error());
410 fp = fopen(outfname, "rb+");
412 fp = fopen(outfname, "wb");
416 printf("local: unable to open %s\n", outfname);
418 sftp_register(req = fxp_close_send(fh));
419 rreq = sftp_find_request(pktin = sftp_recv());
421 fxp_close_recv(pktin, rreq);
429 fseek(fp, 0L, SEEK_END);
431 printf("reget: restarting at file position %ld\n", posn);
432 offset = uint64_make(0, posn);
434 offset = uint64_make(0, 0);
437 printf("remote:%s => local:%s\n", fname, outfname);
440 * FIXME: we can use FXP_FSTAT here to get the file size, and
441 * thus put up a progress bar.
444 xfer = xfer_download_init(fh, offset);
445 while (!xfer_done(xfer)) {
450 xfer_download_queue(xfer);
452 ret = xfer_download_gotpkt(xfer, pktin);
455 printf("error while reading: %s\n", fxp_error());
459 while (xfer_download_data(xfer, &vbuf, &len)) {
460 unsigned char *buf = (unsigned char *)vbuf;
464 wlen = fwrite(buf + wpos, 1, len - wpos, fp);
466 printf("error while writing local file\n");
468 xfer_set_error(xfer);
472 if (wpos < len) { /* we had an error */
474 xfer_set_error(xfer);
485 sftp_register(req = fxp_close_send(fh));
486 rreq = sftp_find_request(pktin = sftp_recv());
488 fxp_close_recv(pktin, rreq);
494 int sftp_cmd_get(struct sftp_command *cmd)
496 return sftp_general_get(cmd, 0);
498 int sftp_cmd_reget(struct sftp_command *cmd)
500 return sftp_general_get(cmd, 1);
504 * Send a file and store it at the remote end. We have two very
505 * similar commands here: `put' and `reput', which differ in that
506 * `reput' checks for the existence of the destination file and
507 * starts from where a previous aborted transfer left off.
509 int sftp_general_put(struct sftp_command *cmd, int restart)
511 struct fxp_handle *fh;
512 struct fxp_xfer *xfer;
513 char *fname, *origoutfname, *outfname;
514 struct sftp_packet *pktin;
515 struct sftp_request *req, *rreq;
521 printf("psftp: not connected to a host; use \"open host.name\"\n");
525 if (cmd->nwords < 2) {
526 printf("put: expects a filename\n");
530 fname = cmd->words[1];
531 origoutfname = (cmd->nwords == 2 ?
532 stripslashes(cmd->words[1], 1) : cmd->words[2]);
533 outfname = canonify(origoutfname);
535 printf("%s: %s\n", origoutfname, fxp_error());
539 fp = fopen(fname, "rb");
541 printf("local: unable to open %s\n", fname);
546 sftp_register(req = fxp_open_send(outfname, SSH_FXF_WRITE));
548 sftp_register(req = fxp_open_send(outfname, SSH_FXF_WRITE |
549 SSH_FXF_CREAT | SSH_FXF_TRUNC));
551 rreq = sftp_find_request(pktin = sftp_recv());
553 fh = fxp_open_recv(pktin, rreq);
556 printf("%s: %s\n", outfname, fxp_error());
563 struct fxp_attrs attrs;
566 sftp_register(req = fxp_fstat_send(fh));
567 rreq = sftp_find_request(pktin = sftp_recv());
569 ret = fxp_fstat_recv(pktin, rreq, &attrs);
572 printf("read size of %s: %s\n", outfname, fxp_error());
576 if (!(attrs.flags & SSH_FILEXFER_ATTR_SIZE)) {
577 printf("read size of %s: size was not given\n", outfname);
582 uint64_decimal(offset, decbuf);
583 printf("reput: restarting at file position %s\n", decbuf);
584 if (uint64_compare(offset, uint64_make(0, LONG_MAX)) > 0) {
585 printf("reput: remote file is larger than we can deal with\n");
589 if (fseek(fp, offset.lo, SEEK_SET) != 0)
590 fseek(fp, 0, SEEK_END); /* *shrug* */
592 offset = uint64_make(0, 0);
595 printf("local:%s => remote:%s\n", fname, outfname);
598 * FIXME: we can use FXP_FSTAT here to get the file size, and
599 * thus put up a progress bar.
602 xfer = xfer_upload_init(fh, offset);
604 while ((!err && !eof) || !xfer_done(xfer)) {
608 while (xfer_upload_ready(xfer) && !err && !eof) {
609 len = fread(buffer, 1, sizeof(buffer), fp);
611 printf("error while reading local file\n");
613 } else if (len == 0) {
616 xfer_upload_data(xfer, buffer, len);
620 if (!xfer_done(xfer)) {
622 ret = xfer_upload_gotpkt(xfer, pktin);
624 printf("error while writing: %s\n", fxp_error());
632 sftp_register(req = fxp_close_send(fh));
633 rreq = sftp_find_request(pktin = sftp_recv());
635 fxp_close_recv(pktin, rreq);
642 int sftp_cmd_put(struct sftp_command *cmd)
644 return sftp_general_put(cmd, 0);
646 int sftp_cmd_reput(struct sftp_command *cmd)
648 return sftp_general_put(cmd, 1);
651 int sftp_cmd_mkdir(struct sftp_command *cmd)
654 struct sftp_packet *pktin;
655 struct sftp_request *req, *rreq;
659 printf("psftp: not connected to a host; use \"open host.name\"\n");
663 if (cmd->nwords < 2) {
664 printf("mkdir: expects a directory\n");
668 dir = canonify(cmd->words[1]);
670 printf("%s: %s\n", dir, fxp_error());
674 sftp_register(req = fxp_mkdir_send(dir));
675 rreq = sftp_find_request(pktin = sftp_recv());
677 result = fxp_mkdir_recv(pktin, rreq);
680 printf("mkdir %s: %s\n", dir, fxp_error());
689 int sftp_cmd_rmdir(struct sftp_command *cmd)
692 struct sftp_packet *pktin;
693 struct sftp_request *req, *rreq;
697 printf("psftp: not connected to a host; use \"open host.name\"\n");
701 if (cmd->nwords < 2) {
702 printf("rmdir: expects a directory\n");
706 dir = canonify(cmd->words[1]);
708 printf("%s: %s\n", dir, fxp_error());
712 sftp_register(req = fxp_rmdir_send(dir));
713 rreq = sftp_find_request(pktin = sftp_recv());
715 result = fxp_rmdir_recv(pktin, rreq);
718 printf("rmdir %s: %s\n", dir, fxp_error());
727 int sftp_cmd_rm(struct sftp_command *cmd)
730 struct sftp_packet *pktin;
731 struct sftp_request *req, *rreq;
735 printf("psftp: not connected to a host; use \"open host.name\"\n");
739 if (cmd->nwords < 2) {
740 printf("rm: expects a filename\n");
744 fname = canonify(cmd->words[1]);
746 printf("%s: %s\n", fname, fxp_error());
750 sftp_register(req = fxp_remove_send(fname));
751 rreq = sftp_find_request(pktin = sftp_recv());
753 result = fxp_remove_recv(pktin, rreq);
756 printf("rm %s: %s\n", fname, fxp_error());
765 int sftp_cmd_mv(struct sftp_command *cmd)
767 char *srcfname, *dstfname;
768 struct sftp_packet *pktin;
769 struct sftp_request *req, *rreq;
773 printf("psftp: not connected to a host; use \"open host.name\"\n");
777 if (cmd->nwords < 3) {
778 printf("mv: expects two filenames\n");
781 srcfname = canonify(cmd->words[1]);
783 printf("%s: %s\n", srcfname, fxp_error());
787 dstfname = canonify(cmd->words[2]);
789 printf("%s: %s\n", dstfname, fxp_error());
793 sftp_register(req = fxp_rename_send(srcfname, dstfname));
794 rreq = sftp_find_request(pktin = sftp_recv());
796 result = fxp_rename_recv(pktin, rreq);
799 char const *error = fxp_error();
800 struct fxp_attrs attrs;
803 * The move might have failed because dstfname pointed at a
804 * directory. We check this possibility now: if dstfname
805 * _is_ a directory, we re-attempt the move by appending
806 * the basename of srcfname to dstfname.
808 sftp_register(req = fxp_stat_send(dstfname));
809 rreq = sftp_find_request(pktin = sftp_recv());
811 result = fxp_stat_recv(pktin, rreq, &attrs);
814 (attrs.flags & SSH_FILEXFER_ATTR_PERMISSIONS) &&
815 (attrs.permissions & 0040000)) {
817 char *newname, *newcanon;
818 printf("(destination %s is a directory)\n", dstfname);
819 p = srcfname + strlen(srcfname);
820 while (p > srcfname && p[-1] != '/') p--;
821 newname = dupcat(dstfname, "/", p, NULL);
822 newcanon = canonify(newname);
828 sftp_register(req = fxp_rename_send(srcfname, dstfname));
829 rreq = sftp_find_request(pktin = sftp_recv());
831 result = fxp_rename_recv(pktin, rreq);
833 error = result ? NULL : fxp_error();
837 printf("mv %s %s: %s\n", srcfname, dstfname, error);
843 printf("%s -> %s\n", srcfname, dstfname);
850 int sftp_cmd_chmod(struct sftp_command *cmd)
854 struct fxp_attrs attrs;
855 unsigned attrs_clr, attrs_xor, oldperms, newperms;
856 struct sftp_packet *pktin;
857 struct sftp_request *req, *rreq;
860 printf("psftp: not connected to a host; use \"open host.name\"\n");
864 if (cmd->nwords < 3) {
865 printf("chmod: expects a mode specifier and a filename\n");
870 * Attempt to parse the mode specifier in cmd->words[1]. We
871 * don't support the full horror of Unix chmod; instead we
872 * support a much simpler syntax in which the user can either
873 * specify an octal number, or a comma-separated sequence of
874 * [ugoa]*[-+=][rwxst]+. (The initial [ugoa] sequence may
875 * _only_ be omitted if the only attribute mentioned is t,
876 * since all others require a user/group/other specification.
877 * Additionally, the s attribute may not be specified for any
878 * [ugoa] specifications other than exactly u or exactly g.
880 attrs_clr = attrs_xor = 0;
881 mode = cmd->words[1];
882 if (mode[0] >= '0' && mode[0] <= '9') {
883 if (mode[strspn(mode, "01234567")]) {
884 printf("chmod: numeric file modes should"
885 " contain digits 0-7 only\n");
889 sscanf(mode, "%o", &attrs_xor);
890 attrs_xor &= attrs_clr;
893 char *modebegin = mode;
894 unsigned subset, perms;
898 while (*mode && *mode != ',' &&
899 *mode != '+' && *mode != '-' && *mode != '=') {
901 case 'u': subset |= 04700; break; /* setuid, user perms */
902 case 'g': subset |= 02070; break; /* setgid, group perms */
903 case 'o': subset |= 00007; break; /* just other perms */
904 case 'a': subset |= 06777; break; /* all of the above */
906 printf("chmod: file mode '%.*s' contains unrecognised"
907 " user/group/other specifier '%c'\n",
908 (int)strcspn(modebegin, ","), modebegin, *mode);
913 if (!*mode || *mode == ',') {
914 printf("chmod: file mode '%.*s' is incomplete\n",
915 (int)strcspn(modebegin, ","), modebegin);
919 if (!*mode || *mode == ',') {
920 printf("chmod: file mode '%.*s' is incomplete\n",
921 (int)strcspn(modebegin, ","), modebegin);
925 while (*mode && *mode != ',') {
927 case 'r': perms |= 00444; break;
928 case 'w': perms |= 00222; break;
929 case 'x': perms |= 00111; break;
930 case 't': perms |= 01000; subset |= 01000; break;
932 if ((subset & 06777) != 04700 &&
933 (subset & 06777) != 02070) {
934 printf("chmod: file mode '%.*s': set[ug]id bit should"
935 " be used with exactly one of u or g only\n",
936 (int)strcspn(modebegin, ","), modebegin);
942 printf("chmod: file mode '%.*s' contains unrecognised"
943 " permission specifier '%c'\n",
944 (int)strcspn(modebegin, ","), modebegin, *mode);
949 if (!(subset & 06777) && (perms &~ subset)) {
950 printf("chmod: file mode '%.*s' contains no user/group/other"
951 " specifier and permissions other than 't' \n",
952 (int)strcspn(modebegin, ","), modebegin);
970 if (*mode) mode++; /* eat comma */
974 fname = canonify(cmd->words[2]);
976 printf("%s: %s\n", fname, fxp_error());
980 sftp_register(req = fxp_stat_send(fname));
981 rreq = sftp_find_request(pktin = sftp_recv());
983 result = fxp_stat_recv(pktin, rreq, &attrs);
985 if (!result || !(attrs.flags & SSH_FILEXFER_ATTR_PERMISSIONS)) {
986 printf("get attrs for %s: %s\n", fname,
987 result ? "file permissions not provided" : fxp_error());
992 attrs.flags = SSH_FILEXFER_ATTR_PERMISSIONS; /* perms _only_ */
993 oldperms = attrs.permissions & 07777;
994 attrs.permissions &= ~attrs_clr;
995 attrs.permissions ^= attrs_xor;
996 newperms = attrs.permissions & 07777;
998 sftp_register(req = fxp_setstat_send(fname, attrs));
999 rreq = sftp_find_request(pktin = sftp_recv());
1000 assert(rreq == req);
1001 result = fxp_setstat_recv(pktin, rreq);
1004 printf("set attrs for %s: %s\n", fname, fxp_error());
1009 printf("%s: %04o -> %04o\n", fname, oldperms, newperms);
1015 static int sftp_cmd_open(struct sftp_command *cmd)
1018 printf("psftp: already connected\n");
1022 if (cmd->nwords < 2) {
1023 printf("open: expects a host name\n");
1027 if (psftp_connect(cmd->words[1], NULL, 0)) {
1028 back = NULL; /* connection is already closed */
1029 return -1; /* this is fatal */
1035 static int sftp_cmd_lcd(struct sftp_command *cmd)
1037 char *currdir, *errmsg;
1039 if (cmd->nwords < 2) {
1040 printf("lcd: expects a local directory name\n");
1044 errmsg = psftp_lcd(cmd->words[1]);
1046 printf("lcd: unable to change directory: %s\n", errmsg);
1051 currdir = psftp_getcwd();
1052 printf("New local directory is %s\n", currdir);
1058 static int sftp_cmd_lpwd(struct sftp_command *cmd)
1062 currdir = psftp_getcwd();
1063 printf("Current local directory is %s\n", currdir);
1069 static int sftp_cmd_pling(struct sftp_command *cmd)
1073 exitcode = system(cmd->words[1]);
1074 return (exitcode == 0);
1077 static int sftp_cmd_help(struct sftp_command *cmd);
1079 static struct sftp_cmd_lookup {
1082 * For help purposes, there are two kinds of command:
1084 * - primary commands, in which `longhelp' is non-NULL. In
1085 * this case `shorthelp' is descriptive text, and `longhelp'
1086 * is longer descriptive text intended to be printed after
1089 * - alias commands, in which `longhelp' is NULL. In this case
1090 * `shorthelp' is the name of a primary command, which
1091 * contains the help that should double up for this command.
1093 int listed; /* do we list this in primary help? */
1096 int (*obey) (struct sftp_command *);
1099 * List of sftp commands. This is binary-searched so it MUST be
1103 "!", TRUE, "run a local command",
1105 /* FIXME: this example is crap for non-Windows. */
1106 " Runs a local command. For example, \"!del myfile\".\n",
1110 "bye", TRUE, "finish your SFTP session",
1112 " Terminates your SFTP session and quits the PSFTP program.\n",
1116 "cd", TRUE, "change your remote working directory",
1117 " [ <New working directory> ]\n"
1118 " Change the remote working directory for your SFTP session.\n"
1119 " If a new working directory is not supplied, you will be\n"
1120 " returned to your home directory.\n",
1124 "chmod", TRUE, "change file permissions and modes",
1125 " ( <octal-digits> | <modifiers> ) <filename>\n"
1126 " Change the file permissions on a file or directory.\n"
1127 " <octal-digits> can be any octal Unix permission specifier.\n"
1128 " Alternatively, <modifiers> can include:\n"
1129 " u+r make file readable by owning user\n"
1130 " u+w make file writable by owning user\n"
1131 " u+x make file executable by owning user\n"
1132 " u-r make file not readable by owning user\n"
1133 " [also u-w, u-x]\n"
1134 " g+r make file readable by members of owning group\n"
1135 " [also g+w, g+x, g-r, g-w, g-x]\n"
1136 " o+r make file readable by all other users\n"
1137 " [also o+w, o+x, o-r, o-w, o-x]\n"
1138 " a+r make file readable by absolutely everybody\n"
1139 " [also a+w, a+x, a-r, a-w, a-x]\n"
1140 " u+s enable the Unix set-user-ID bit\n"
1141 " u-s disable the Unix set-user-ID bit\n"
1142 " g+s enable the Unix set-group-ID bit\n"
1143 " g-s disable the Unix set-group-ID bit\n"
1144 " +t enable the Unix \"sticky bit\"\n"
1145 " You can give more than one modifier for the same user (\"g-rwx\"), and\n"
1146 " more than one user for the same modifier (\"ug+w\"). You can\n"
1147 " use commas to separate different modifiers (\"u+rwx,g+s\").\n",
1151 "del", TRUE, "delete a file",
1153 " Delete a file.\n",
1157 "delete", FALSE, "del", NULL, sftp_cmd_rm
1160 "dir", TRUE, "list contents of a remote directory",
1161 " [ <directory-name> ]\n"
1162 " List the contents of a specified directory on the server.\n"
1163 " If <directory-name> is not given, the current working directory\n"
1164 " will be listed.\n",
1168 "exit", TRUE, "bye", NULL, sftp_cmd_quit
1171 "get", TRUE, "download a file from the server to your local machine",
1172 " <filename> [ <local-filename> ]\n"
1173 " Downloads a file on the server and stores it locally under\n"
1174 " the same name, or under a different one if you supply the\n"
1175 " argument <local-filename>.\n",
1179 "help", TRUE, "give help",
1180 " [ <command> [ <command> ... ] ]\n"
1181 " Give general help if no commands are specified.\n"
1182 " If one or more commands are specified, give specific help on\n"
1183 " those particular commands.\n",
1187 "lcd", TRUE, "change local working directory",
1188 " <local-directory-name>\n"
1189 " Change the local working directory of the PSFTP program (the\n"
1190 " default location where the \"get\" command will save files).\n",
1194 "lpwd", TRUE, "print local working directory",
1196 " Print the local working directory of the PSFTP program (the\n"
1197 " default location where the \"get\" command will save files).\n",
1201 "ls", TRUE, "dir", NULL,
1205 "mkdir", TRUE, "create a directory on the remote server",
1206 " <directory-name>\n"
1207 " Creates a directory with the given name on the server.\n",
1211 "mv", TRUE, "move or rename a file on the remote server",
1212 " <source-filename> <destination-filename>\n"
1213 " Moves or renames the file <source-filename> on the server,\n"
1214 " so that it is accessible under the name <destination-filename>.\n",
1218 "open", TRUE, "connect to a host",
1219 " [<user>@]<hostname>\n"
1220 " Establishes an SFTP connection to a given host. Only usable\n"
1221 " when you did not already specify a host name on the command\n"
1226 "put", TRUE, "upload a file from your local machine to the server",
1227 " <filename> [ <remote-filename> ]\n"
1228 " Uploads a file to the server and stores it there under\n"
1229 " the same name, or under a different one if you supply the\n"
1230 " argument <remote-filename>.\n",
1234 "pwd", TRUE, "print your remote working directory",
1236 " Print the current remote working directory for your SFTP session.\n",
1240 "quit", TRUE, "bye", NULL,
1244 "reget", TRUE, "continue downloading a file",
1245 " <filename> [ <local-filename> ]\n"
1246 " Works exactly like the \"get\" command, but the local file\n"
1247 " must already exist. The download will begin at the end of the\n"
1248 " file. This is for resuming a download that was interrupted.\n",
1252 "ren", TRUE, "mv", NULL,
1256 "rename", FALSE, "mv", NULL,
1260 "reput", TRUE, "continue uploading a file",
1261 " <filename> [ <remote-filename> ]\n"
1262 " Works exactly like the \"put\" command, but the remote file\n"
1263 " must already exist. The upload will begin at the end of the\n"
1264 " file. This is for resuming an upload that was interrupted.\n",
1268 "rm", TRUE, "del", NULL,
1272 "rmdir", TRUE, "remove a directory on the remote server",
1273 " <directory-name>\n"
1274 " Removes the directory with the given name on the server.\n"
1275 " The directory will not be removed unless it is empty.\n",
1280 const struct sftp_cmd_lookup *lookup_command(char *name)
1285 j = sizeof(sftp_lookup) / sizeof(*sftp_lookup);
1288 cmp = strcmp(name, sftp_lookup[k].name);
1294 return &sftp_lookup[k];
1300 static int sftp_cmd_help(struct sftp_command *cmd)
1303 if (cmd->nwords == 1) {
1305 * Give short help on each command.
1309 for (i = 0; i < sizeof(sftp_lookup) / sizeof(*sftp_lookup); i++) {
1311 if (!sftp_lookup[i].listed)
1313 len = strlen(sftp_lookup[i].name);
1317 for (i = 0; i < sizeof(sftp_lookup) / sizeof(*sftp_lookup); i++) {
1318 const struct sftp_cmd_lookup *lookup;
1319 if (!sftp_lookup[i].listed)
1321 lookup = &sftp_lookup[i];
1322 printf("%-*s", maxlen+2, lookup->name);
1323 if (lookup->longhelp == NULL)
1324 lookup = lookup_command(lookup->shorthelp);
1325 printf("%s\n", lookup->shorthelp);
1329 * Give long help on specific commands.
1331 for (i = 1; i < cmd->nwords; i++) {
1332 const struct sftp_cmd_lookup *lookup;
1333 lookup = lookup_command(cmd->words[i]);
1335 printf("help: %s: command not found\n", cmd->words[i]);
1337 printf("%s", lookup->name);
1338 if (lookup->longhelp == NULL)
1339 lookup = lookup_command(lookup->shorthelp);
1340 printf("%s", lookup->longhelp);
1347 /* ----------------------------------------------------------------------
1348 * Command line reading and parsing.
1350 struct sftp_command *sftp_getcmd(FILE *fp, int mode, int modeflags)
1353 int linelen, linesize;
1354 struct sftp_command *cmd;
1358 if ((mode == 0) || (modeflags & 1)) {
1363 cmd = snew(struct sftp_command);
1369 linesize = linelen = 0;
1375 line = sresize(line, linesize, char);
1376 ret = fgets(line + linelen, linesize - linelen, fp);
1378 if (!ret || (linelen == 0 && line[0] == '\0')) {
1379 cmd->obey = sftp_cmd_quit;
1380 if ((mode == 0) || (modeflags & 1))
1382 return cmd; /* eof */
1384 len = linelen + strlen(line + linelen);
1386 if (line[linelen - 1] == '\n') {
1388 line[linelen] = '\0';
1392 if (modeflags & 1) {
1393 printf("%s\n", line);
1397 while (*p && (*p == ' ' || *p == '\t'))
1402 * Special case: the ! command. This is always parsed as
1403 * exactly two words: one containing the !, and the second
1404 * containing everything else on the line.
1406 cmd->nwords = cmd->wordssize = 2;
1407 cmd->words = sresize(cmd->words, cmd->wordssize, char *);
1408 cmd->words[0] = dupstr("!");
1409 cmd->words[1] = dupstr(p+1);
1413 * Parse the command line into words. The syntax is:
1414 * - double quotes are removed, but cause spaces within to be
1415 * treated as non-separating.
1416 * - a double-doublequote pair is a literal double quote, inside
1417 * _or_ outside quotes. Like this:
1419 * firstword "second word" "this has ""quotes"" in" and""this""
1425 * >this has "quotes" in<
1429 /* skip whitespace */
1430 while (*p && (*p == ' ' || *p == '\t'))
1432 /* mark start of word */
1433 q = r = p; /* q sits at start, r writes word */
1436 if (!quoting && (*p == ' ' || *p == '\t'))
1437 break; /* reached end of word */
1438 else if (*p == '"' && p[1] == '"')
1439 p += 2, *r++ = '"'; /* a literal quote */
1441 p++, quoting = !quoting;
1446 p++; /* skip over the whitespace */
1448 if (cmd->nwords >= cmd->wordssize) {
1449 cmd->wordssize = cmd->nwords + 16;
1450 cmd->words = sresize(cmd->words, cmd->wordssize, char *);
1452 cmd->words[cmd->nwords++] = dupstr(q);
1458 * Now parse the first word and assign a function.
1461 if (cmd->nwords == 0)
1462 cmd->obey = sftp_cmd_null;
1464 const struct sftp_cmd_lookup *lookup;
1465 lookup = lookup_command(cmd->words[0]);
1467 cmd->obey = sftp_cmd_unknown;
1469 cmd->obey = lookup->obey;
1475 static int do_sftp_init(void)
1477 struct sftp_packet *pktin;
1478 struct sftp_request *req, *rreq;
1481 * Do protocol initialisation.
1485 "Fatal: unable to initialise SFTP: %s\n", fxp_error());
1486 return 1; /* failure */
1490 * Find out where our home directory is.
1492 sftp_register(req = fxp_realpath_send("."));
1493 rreq = sftp_find_request(pktin = sftp_recv());
1494 assert(rreq == req);
1495 homedir = fxp_realpath_recv(pktin, rreq);
1499 "Warning: failed to resolve home directory: %s\n",
1501 homedir = dupstr(".");
1503 printf("Remote working directory is %s\n", homedir);
1505 pwd = dupstr(homedir);
1509 void do_sftp_cleanup()
1512 back->special(backhandle, TS_EOF);
1513 sftp_recvdata(&ch, 1);
1514 back->free(backhandle);
1515 sftp_cleanup_request();
1526 void do_sftp(int mode, int modeflags, char *batchfile)
1536 /* ------------------------------------------------------------------
1537 * Now we're ready to do Real Stuff.
1540 struct sftp_command *cmd;
1541 cmd = sftp_getcmd(stdin, 0, 0);
1544 ret = cmd->obey(cmd);
1547 for(i = 0; i < cmd->nwords; i++)
1548 sfree(cmd->words[i]);
1556 fp = fopen(batchfile, "r");
1558 printf("Fatal: unable to open %s\n", batchfile);
1562 struct sftp_command *cmd;
1563 cmd = sftp_getcmd(fp, mode, modeflags);
1566 ret = cmd->obey(cmd);
1570 if (!(modeflags & 2))
1579 /* ----------------------------------------------------------------------
1580 * Dirty bits: integration with PuTTY.
1583 static int verbose = 0;
1586 * Print an error message and perform a fatal exit.
1588 void fatalbox(char *fmt, ...)
1593 str = dupvprintf(fmt, ap);
1594 str2 = dupcat("Fatal: ", str, "\n", NULL);
1597 fputs(str2, stderr);
1602 void modalfatalbox(char *fmt, ...)
1607 str = dupvprintf(fmt, ap);
1608 str2 = dupcat("Fatal: ", str, "\n", NULL);
1611 fputs(str2, stderr);
1616 void connection_fatal(void *frontend, char *fmt, ...)
1621 str = dupvprintf(fmt, ap);
1622 str2 = dupcat("Fatal: ", str, "\n", NULL);
1625 fputs(str2, stderr);
1631 void ldisc_send(void *handle, char *buf, int len, int interactive)
1634 * This is only here because of the calls to ldisc_send(NULL,
1635 * 0) in ssh.c. Nothing in PSFTP actually needs to use the
1636 * ldisc as an ldisc. So if we get called with any real data, I
1637 * want to know about it.
1643 * In psftp, all agent requests should be synchronous, so this is a
1644 * never-called stub.
1646 void agent_schedule_callback(void (*callback)(void *, void *, int),
1647 void *callback_ctx, void *data, int len)
1649 assert(!"We shouldn't be here");
1653 * Receive a block of data from the SSH link. Block until all data
1656 * To do this, we repeatedly call the SSH protocol module, with our
1657 * own trap in from_backend() to catch the data that comes back. We
1658 * do this until we have enough data.
1661 static unsigned char *outptr; /* where to put the data */
1662 static unsigned outlen; /* how much data required */
1663 static unsigned char *pending = NULL; /* any spare data */
1664 static unsigned pendlen = 0, pendsize = 0; /* length and phys. size of buffer */
1665 int from_backend(void *frontend, int is_stderr, const char *data, int datalen)
1667 unsigned char *p = (unsigned char *) data;
1668 unsigned len = (unsigned) datalen;
1671 * stderr data is just spouted to local stderr and otherwise
1676 fwrite(data, 1, len, stderr);
1681 * If this is before the real session begins, just return.
1686 if ((outlen > 0) && (len > 0)) {
1687 unsigned used = outlen;
1690 memcpy(outptr, p, used);
1698 if (pendsize < pendlen + len) {
1699 pendsize = pendlen + len + 4096;
1700 pending = sresize(pending, pendsize, unsigned char);
1702 memcpy(pending + pendlen, p, len);
1708 int sftp_recvdata(char *buf, int len)
1710 outptr = (unsigned char *) buf;
1714 * See if the pending-input block contains some of what we
1718 unsigned pendused = pendlen;
1719 if (pendused > outlen)
1721 memcpy(outptr, pending, pendused);
1722 memmove(pending, pending + pendused, pendlen - pendused);
1725 pendlen -= pendused;
1735 while (outlen > 0) {
1736 if (ssh_sftp_loop_iteration() < 0)
1737 return 0; /* doom */
1742 int sftp_senddata(char *buf, int len)
1744 back->send(backhandle, (unsigned char *) buf, len);
1749 * Short description of parameters.
1751 static void usage(void)
1753 printf("PuTTY Secure File Transfer (SFTP) client\n");
1754 printf("%s\n", ver);
1755 printf("Usage: psftp [options] user@host\n");
1756 printf("Options:\n");
1757 printf(" -b file use specified batchfile\n");
1758 printf(" -bc output batchfile commands\n");
1759 printf(" -be don't stop batchfile processing if errors\n");
1760 printf(" -v show verbose messages\n");
1761 printf(" -load sessname Load settings from saved session\n");
1762 printf(" -l user connect with specified username\n");
1763 printf(" -P port connect to specified port\n");
1764 printf(" -pw passw login with specified password\n");
1765 printf(" -1 -2 force use of particular SSH protocol version\n");
1766 printf(" -C enable compression\n");
1767 printf(" -i key private key file for authentication\n");
1768 printf(" -batch disable all interactive prompts\n");
1773 * Connect to a host.
1775 static int psftp_connect(char *userhost, char *user, int portnumber)
1777 char *host, *realhost;
1781 /* Separate host and username */
1783 host = strrchr(host, '@');
1789 printf("psftp: multiple usernames specified; using \"%s\"\n",
1795 /* Try to load settings for this host */
1796 do_defaults(host, &cfg);
1797 if (cfg.host[0] == '\0') {
1798 /* No settings for this host; use defaults */
1799 do_defaults(NULL, &cfg);
1800 strncpy(cfg.host, host, sizeof(cfg.host) - 1);
1801 cfg.host[sizeof(cfg.host) - 1] = '\0';
1805 * Force use of SSH. (If they got the protocol wrong we assume the
1806 * port is useless too.)
1808 if (cfg.protocol != PROT_SSH) {
1809 cfg.protocol = PROT_SSH;
1814 * Enact command-line overrides.
1816 cmdline_run_saved(&cfg);
1819 * Trim leading whitespace off the hostname if it's there.
1822 int space = strspn(cfg.host, " \t");
1823 memmove(cfg.host, cfg.host+space, 1+strlen(cfg.host)-space);
1826 /* See if host is of the form user@host */
1827 if (cfg.host[0] != '\0') {
1828 char *atsign = strchr(cfg.host, '@');
1829 /* Make sure we're not overflowing the user field */
1831 if (atsign - cfg.host < sizeof cfg.username) {
1832 strncpy(cfg.username, cfg.host, atsign - cfg.host);
1833 cfg.username[atsign - cfg.host] = '\0';
1835 memmove(cfg.host, atsign + 1, 1 + strlen(atsign + 1));
1840 * Trim a colon suffix off the hostname if it's there.
1842 cfg.host[strcspn(cfg.host, ":")] = '\0';
1845 * Remove any remaining whitespace from the hostname.
1849 while (cfg.host[p2] != '\0') {
1850 if (cfg.host[p2] != ' ' && cfg.host[p2] != '\t') {
1851 cfg.host[p1] = cfg.host[p2];
1856 cfg.host[p1] = '\0';
1860 if (user != NULL && user[0] != '\0') {
1861 strncpy(cfg.username, user, sizeof(cfg.username) - 1);
1862 cfg.username[sizeof(cfg.username) - 1] = '\0';
1864 if (!cfg.username[0]) {
1865 printf("login as: ");
1867 if (!fgets(cfg.username, sizeof(cfg.username), stdin)) {
1868 fprintf(stderr, "psftp: aborting\n");
1871 int len = strlen(cfg.username);
1872 if (cfg.username[len - 1] == '\n')
1873 cfg.username[len - 1] = '\0';
1878 cfg.port = portnumber;
1880 /* SFTP uses SSH2 by default always */
1884 * Disable scary things which shouldn't be enabled for simple
1885 * things like SCP and SFTP: agent forwarding, port forwarding,
1888 cfg.x11_forward = 0;
1890 cfg.portfwd[0] = cfg.portfwd[1] = '\0';
1892 /* Set up subsystem name. */
1893 strcpy(cfg.remote_cmd, "sftp");
1894 cfg.ssh_subsys = TRUE;
1898 * Set up fallback option, for SSH1 servers or servers with the
1899 * sftp subsystem not enabled but the server binary installed
1900 * in the usual place. We only support fallback on Unix
1901 * systems, and we use a kludgy piece of shellery which should
1902 * try to find sftp-server in various places (the obvious
1903 * systemwide spots /usr/lib and /usr/local/lib, and then the
1904 * user's PATH) and finally give up.
1906 * test -x /usr/lib/sftp-server && exec /usr/lib/sftp-server
1907 * test -x /usr/local/lib/sftp-server && exec /usr/local/lib/sftp-server
1910 * the idea being that this will attempt to use either of the
1911 * obvious pathnames and then give up, and when it does give up
1912 * it will print the preferred pathname in the error messages.
1914 cfg.remote_cmd_ptr2 =
1915 "test -x /usr/lib/sftp-server && exec /usr/lib/sftp-server\n"
1916 "test -x /usr/local/lib/sftp-server && exec /usr/local/lib/sftp-server\n"
1918 cfg.ssh_subsys2 = FALSE;
1920 back = &ssh_backend;
1922 err = back->init(NULL, &backhandle, &cfg, cfg.host, cfg.port, &realhost,0);
1924 fprintf(stderr, "ssh_init: %s\n", err);
1927 logctx = log_init(NULL, &cfg);
1928 back->provide_logctx(backhandle, logctx);
1929 console_provide_logctx(logctx);
1930 while (!back->sendok(backhandle)) {
1931 if (ssh_sftp_loop_iteration() < 0) {
1932 fprintf(stderr, "ssh_init: error during SSH connection setup\n");
1936 if (verbose && realhost != NULL)
1937 printf("Connected to %s\n", realhost);
1938 if (realhost != NULL)
1943 void cmdline_error(char *p, ...)
1946 fprintf(stderr, "psftp: ");
1948 vfprintf(stderr, p, ap);
1950 fprintf(stderr, "\n try typing \"psftp -h\" for help\n");
1955 * Main program. Parse arguments etc.
1957 int psftp_main(int argc, char *argv[])
1961 char *userhost, *user;
1964 char *batchfile = NULL;
1967 flags = FLAG_STDERR | FLAG_INTERACTIVE
1968 #ifdef FLAG_SYNCAGENT
1972 cmdline_tooltype = TOOLTYPE_FILETRANSFER;
1973 ssh_get_line = &console_get_line;
1976 userhost = user = NULL;
1979 for (i = 1; i < argc; i++) {
1981 if (argv[i][0] != '-') {
1985 userhost = dupstr(argv[i]);
1988 ret = cmdline_process_param(argv[i], i+1<argc?argv[i+1]:NULL, 1, &cfg);
1990 cmdline_error("option \"%s\" requires an argument", argv[i]);
1991 } else if (ret == 2) {
1992 i++; /* skip next argument */
1993 } else if (ret == 1) {
1994 /* We have our own verbosity in addition to `flags'. */
1995 if (flags & FLAG_VERBOSE)
1997 } else if (strcmp(argv[i], "-h") == 0 ||
1998 strcmp(argv[i], "-?") == 0) {
2000 } else if (strcmp(argv[i], "-batch") == 0) {
2001 console_batch_mode = 1;
2002 } else if (strcmp(argv[i], "-b") == 0 && i + 1 < argc) {
2004 batchfile = argv[++i];
2005 } else if (strcmp(argv[i], "-bc") == 0) {
2006 modeflags = modeflags | 1;
2007 } else if (strcmp(argv[i], "-be") == 0) {
2008 modeflags = modeflags | 2;
2009 } else if (strcmp(argv[i], "--") == 0) {
2013 cmdline_error("unknown option \"%s\"", argv[i]);
2021 * If a user@host string has already been provided, connect to
2026 ret = psftp_connect(userhost, user, portnumber);
2033 printf("psftp: no hostname specified; use \"open host.name\""
2037 do_sftp(mode, modeflags, batchfile);
2039 if (back != NULL && back->socket(backhandle) != NULL) {
2041 back->special(backhandle, TS_EOF);
2042 sftp_recvdata(&ch, 1);
2046 console_provide_logctx(NULL);