2 * psftp.c: (platform-independent) 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 /* Even that failed. Restore our best guess at the
133 * constructed filename and give up */
134 fullname[i] = '/'; /* restore slash and last component */
139 * We have a canonical name for all but the last path
140 * component. Concatenate the last component and return.
142 returnname = dupcat(canonname,
143 canonname[strlen(canonname) - 1] ==
144 '/' ? "" : "/", fullname + i + 1, NULL);
152 * Return a pointer to the portion of str that comes after the last
153 * slash (or backslash or colon, if `local' is TRUE).
155 static char *stripslashes(char *str, int local)
160 p = strchr(str, ':');
164 p = strrchr(str, '/');
168 p = strrchr(str, '\\');
176 * qsort comparison routine for fxp_name structures. Sorts by real
179 static int sftp_name_compare(const void *av, const void *bv)
181 const struct fxp_name *const *a = (const struct fxp_name *const *) av;
182 const struct fxp_name *const *b = (const struct fxp_name *const *) bv;
183 return strcmp((*a)->filename, (*b)->filename);
187 * Likewise, but for a bare char *.
189 static int bare_name_compare(const void *av, const void *bv)
191 const char **a = (const char **) av;
192 const char **b = (const char **) bv;
193 return strcmp(*a, *b);
196 static void not_connected(void)
198 printf("psftp: not connected to a host; use \"open host.name\"\n");
201 /* ----------------------------------------------------------------------
202 * The meat of the `get' and `put' commands.
204 int sftp_get_file(char *fname, char *outfname, int recurse, int restart)
206 struct fxp_handle *fh;
207 struct sftp_packet *pktin;
208 struct sftp_request *req, *rreq;
209 struct fxp_xfer *xfer;
212 int ret, shown_err = FALSE;
215 * In recursive mode, see if we're dealing with a directory.
216 * (If we're not in recursive mode, we need not even check: the
217 * subsequent FXP_OPEN will return a usable error message.)
220 struct fxp_attrs attrs;
223 sftp_register(req = fxp_stat_send(fname));
224 rreq = sftp_find_request(pktin = sftp_recv());
226 result = fxp_stat_recv(pktin, rreq, &attrs);
229 (attrs.flags & SSH_FILEXFER_ATTR_PERMISSIONS) &&
230 (attrs.permissions & 0040000)) {
232 struct fxp_handle *dirhandle;
233 int nnames, namesize;
234 struct fxp_name **ournames;
235 struct fxp_names *names;
239 * First, attempt to create the destination directory,
240 * unless it already exists.
242 if (file_type(outfname) != FILE_TYPE_DIRECTORY &&
243 !create_directory(outfname)) {
244 printf("%s: Cannot create directory\n", outfname);
249 * Now get the list of filenames in the remote
252 sftp_register(req = fxp_opendir_send(fname));
253 rreq = sftp_find_request(pktin = sftp_recv());
255 dirhandle = fxp_opendir_recv(pktin, rreq);
258 printf("%s: unable to open directory: %s\n",
262 nnames = namesize = 0;
267 sftp_register(req = fxp_readdir_send(dirhandle));
268 rreq = sftp_find_request(pktin = sftp_recv());
270 names = fxp_readdir_recv(pktin, rreq);
273 if (fxp_error_type() == SSH_FX_EOF)
275 printf("%s: reading directory: %s\n", fname, fxp_error());
279 if (names->nnames == 0) {
280 fxp_free_names(names);
283 if (nnames + names->nnames >= namesize) {
284 namesize += names->nnames + 128;
285 ournames = sresize(ournames, namesize, struct fxp_name *);
287 for (i = 0; i < names->nnames; i++)
288 if (strcmp(names->names[i].filename, ".") &&
289 strcmp(names->names[i].filename, "..")) {
290 if (!vet_filename(names->names[i].filename)) {
291 printf("ignoring potentially dangerous server-"
292 "supplied filename '%s'\n",
293 names->names[i].filename);
296 fxp_dup_name(&names->names[i]);
299 fxp_free_names(names);
301 sftp_register(req = fxp_close_send(dirhandle));
302 rreq = sftp_find_request(pktin = sftp_recv());
304 fxp_close_recv(pktin, rreq);
307 * Sort the names into a clear order. This ought to
308 * make things more predictable when we're doing a
309 * reget of the same directory, just in case two
310 * readdirs on the same remote directory return a
313 qsort(ournames, nnames, sizeof(*ournames), sftp_name_compare);
316 * If we're in restart mode, find the last filename on
317 * this list that already exists. We may have to do a
318 * reget on _that_ file, but shouldn't have to do
319 * anything on the previous files.
321 * If none of them exists, of course, we start at 0.
329 nextoutfname = dir_file_cat(outfname,
330 ournames[i]->filename);
332 nextoutfname = dupstr(ournames[i]->filename);
333 ret = (file_type(nextoutfname) == FILE_TYPE_NONEXISTENT);
344 * Now we're ready to recurse. Starting at ournames[i]
345 * and continuing on to the end of the list, we
346 * construct a new source and target file name, and
347 * call sftp_get_file again.
349 for (; i < nnames; i++) {
350 char *nextfname, *nextoutfname;
353 nextfname = dupcat(fname, "/", ournames[i]->filename, NULL);
355 nextoutfname = dir_file_cat(outfname,
356 ournames[i]->filename);
358 nextoutfname = dupstr(ournames[i]->filename);
359 ret = sftp_get_file(nextfname, nextoutfname, recurse, restart);
360 restart = FALSE; /* after first partial file, do full */
364 for (i = 0; i < nnames; i++) {
365 fxp_free_name(ournames[i]);
373 * Done this recursion level. Free everything.
375 for (i = 0; i < nnames; i++) {
376 fxp_free_name(ournames[i]);
384 sftp_register(req = fxp_open_send(fname, SSH_FXF_READ));
385 rreq = sftp_find_request(pktin = sftp_recv());
387 fh = fxp_open_recv(pktin, rreq);
390 printf("%s: open for read: %s\n", fname, fxp_error());
395 file = open_existing_wfile(outfname, NULL);
397 file = open_new_file(outfname);
401 printf("local: unable to open %s\n", outfname);
403 sftp_register(req = fxp_close_send(fh));
404 rreq = sftp_find_request(pktin = sftp_recv());
406 fxp_close_recv(pktin, rreq);
413 if (seek_file(file, uint64_make(0,0) , FROM_END) == -1) {
415 printf("reget: cannot restart %s - file too large\n",
417 sftp_register(req = fxp_close_send(fh));
418 rreq = sftp_find_request(pktin = sftp_recv());
420 fxp_close_recv(pktin, rreq);
425 offset = get_file_posn(file);
426 uint64_decimal(offset, decbuf);
427 printf("reget: restarting at file position %s\n", decbuf);
429 offset = uint64_make(0, 0);
432 printf("remote:%s => local:%s\n", fname, outfname);
435 * FIXME: we can use FXP_FSTAT here to get the file size, and
436 * thus put up a progress bar.
439 xfer = xfer_download_init(fh, offset);
440 while (!xfer_done(xfer)) {
445 xfer_download_queue(xfer);
447 ret = xfer_download_gotpkt(xfer, pktin);
451 printf("error while reading: %s\n", fxp_error());
457 while (xfer_download_data(xfer, &vbuf, &len)) {
458 unsigned char *buf = (unsigned char *)vbuf;
462 wlen = write_to_file(file, buf + wpos, len - wpos);
464 printf("error while writing local file\n");
466 xfer_set_error(xfer);
471 if (wpos < len) { /* we had an error */
473 xfer_set_error(xfer);
484 sftp_register(req = fxp_close_send(fh));
485 rreq = sftp_find_request(pktin = sftp_recv());
487 fxp_close_recv(pktin, rreq);
492 int sftp_put_file(char *fname, char *outfname, int recurse, int restart)
494 struct fxp_handle *fh;
495 struct fxp_xfer *xfer;
496 struct sftp_packet *pktin;
497 struct sftp_request *req, *rreq;
503 * In recursive mode, see if we're dealing with a directory.
504 * (If we're not in recursive mode, we need not even check: the
505 * subsequent fopen will return an error message.)
507 if (recurse && file_type(fname) == FILE_TYPE_DIRECTORY) {
508 struct fxp_attrs attrs;
510 int nnames, namesize;
511 char *name, **ournames;
516 * First, attempt to create the destination directory,
517 * unless it already exists.
519 sftp_register(req = fxp_stat_send(outfname));
520 rreq = sftp_find_request(pktin = sftp_recv());
522 result = fxp_stat_recv(pktin, rreq, &attrs);
524 !(attrs.flags & SSH_FILEXFER_ATTR_PERMISSIONS) ||
525 !(attrs.permissions & 0040000)) {
526 sftp_register(req = fxp_mkdir_send(outfname));
527 rreq = sftp_find_request(pktin = sftp_recv());
529 result = fxp_mkdir_recv(pktin, rreq);
532 printf("%s: create directory: %s\n",
533 outfname, fxp_error());
539 * Now get the list of filenames in the local directory.
541 nnames = namesize = 0;
544 dh = open_directory(fname);
546 printf("%s: unable to open directory\n", fname);
549 while ((name = read_filename(dh)) != NULL) {
550 if (nnames >= namesize) {
552 ournames = sresize(ournames, namesize, char *);
554 ournames[nnames++] = name;
559 * Sort the names into a clear order. This ought to make
560 * things more predictable when we're doing a reput of the
561 * same directory, just in case two readdirs on the same
562 * local directory return a different order.
564 qsort(ournames, nnames, sizeof(*ournames), bare_name_compare);
567 * If we're in restart mode, find the last filename on this
568 * list that already exists. We may have to do a reput on
569 * _that_ file, but shouldn't have to do anything on the
572 * If none of them exists, of course, we start at 0.
578 nextoutfname = dupcat(outfname, "/", ournames[i], NULL);
579 sftp_register(req = fxp_stat_send(nextoutfname));
580 rreq = sftp_find_request(pktin = sftp_recv());
582 result = fxp_stat_recv(pktin, rreq, &attrs);
593 * Now we're ready to recurse. Starting at ournames[i]
594 * and continuing on to the end of the list, we
595 * construct a new source and target file name, and
596 * call sftp_put_file again.
598 for (; i < nnames; i++) {
599 char *nextfname, *nextoutfname;
603 nextfname = dir_file_cat(fname, ournames[i]);
605 nextfname = dupstr(ournames[i]);
606 nextoutfname = dupcat(outfname, "/", ournames[i], NULL);
607 ret = sftp_put_file(nextfname, nextoutfname, recurse, restart);
608 restart = FALSE; /* after first partial file, do full */
612 for (i = 0; i < nnames; i++) {
621 * Done this recursion level. Free everything.
623 for (i = 0; i < nnames; i++) {
631 file = open_existing_file(fname, NULL, NULL, NULL);
633 printf("local: unable to open %s\n", fname);
637 sftp_register(req = fxp_open_send(outfname, SSH_FXF_WRITE));
639 sftp_register(req = fxp_open_send(outfname, SSH_FXF_WRITE |
640 SSH_FXF_CREAT | SSH_FXF_TRUNC));
642 rreq = sftp_find_request(pktin = sftp_recv());
644 fh = fxp_open_recv(pktin, rreq);
648 printf("%s: open for write: %s\n", outfname, fxp_error());
654 struct fxp_attrs attrs;
657 sftp_register(req = fxp_fstat_send(fh));
658 rreq = sftp_find_request(pktin = sftp_recv());
660 ret = fxp_fstat_recv(pktin, rreq, &attrs);
664 printf("read size of %s: %s\n", outfname, fxp_error());
667 if (!(attrs.flags & SSH_FILEXFER_ATTR_SIZE)) {
669 printf("read size of %s: size was not given\n", outfname);
673 uint64_decimal(offset, decbuf);
674 printf("reput: restarting at file position %s\n", decbuf);
676 if (seek_file((WFile *)file, offset, FROM_START) != 0)
677 seek_file((WFile *)file, uint64_make(0,0), FROM_END); /* *shrug* */
679 offset = uint64_make(0, 0);
682 printf("local:%s => remote:%s\n", fname, outfname);
685 * FIXME: we can use FXP_FSTAT here to get the file size, and
686 * thus put up a progress bar.
689 xfer = xfer_upload_init(fh, offset);
691 while ((!err && !eof) || !xfer_done(xfer)) {
695 while (xfer_upload_ready(xfer) && !err && !eof) {
696 len = read_from_file(file, buffer, sizeof(buffer));
698 printf("error while reading local file\n");
700 } else if (len == 0) {
703 xfer_upload_data(xfer, buffer, len);
707 if (!xfer_done(xfer)) {
709 ret = xfer_upload_gotpkt(xfer, pktin);
711 printf("error while writing: %s\n", fxp_error());
719 sftp_register(req = fxp_close_send(fh));
720 rreq = sftp_find_request(pktin = sftp_recv());
722 fxp_close_recv(pktin, rreq);
729 /* ----------------------------------------------------------------------
730 * A remote wildcard matcher, providing a similar interface to the
731 * local one in psftp.h.
734 typedef struct SftpWildcardMatcher {
735 struct fxp_handle *dirh;
736 struct fxp_names *names;
738 char *wildcard, *prefix;
739 } SftpWildcardMatcher;
741 SftpWildcardMatcher *sftp_begin_wildcard_matching(char *name)
743 struct sftp_packet *pktin;
744 struct sftp_request *req, *rreq;
746 char *unwcdir, *tmpdir, *cdir;
748 SftpWildcardMatcher *swcm;
749 struct fxp_handle *dirh;
752 * We don't handle multi-level wildcards; so we expect to find
753 * a fully specified directory part, followed by a wildcard
756 wildcard = stripslashes(name, 0);
758 unwcdir = dupstr(name);
759 len = wildcard - name;
761 if (len > 0 && unwcdir[len-1] == '/')
762 unwcdir[len-1] = '\0';
763 tmpdir = snewn(1 + len, char);
764 check = wc_unescape(tmpdir, unwcdir);
768 printf("Multiple-level wildcards are not supported\n");
773 cdir = canonify(unwcdir);
775 sftp_register(req = fxp_opendir_send(cdir));
776 rreq = sftp_find_request(pktin = sftp_recv());
778 dirh = fxp_opendir_recv(pktin, rreq);
781 swcm = snew(SftpWildcardMatcher);
784 swcm->wildcard = dupstr(wildcard);
785 swcm->prefix = unwcdir;
787 printf("Unable to open %s: %s\n", cdir, fxp_error());
797 char *sftp_wildcard_get_filename(SftpWildcardMatcher *swcm)
799 struct fxp_name *name;
800 struct sftp_packet *pktin;
801 struct sftp_request *req, *rreq;
804 if (swcm->names && swcm->namepos >= swcm->names->nnames) {
805 fxp_free_names(swcm->names);
810 sftp_register(req = fxp_readdir_send(swcm->dirh));
811 rreq = sftp_find_request(pktin = sftp_recv());
813 swcm->names = fxp_readdir_recv(pktin, rreq);
816 if (fxp_error_type() != SSH_FX_EOF)
817 printf("%s: reading directory: %s\n", swcm->prefix,
825 assert(swcm->names && swcm->namepos < swcm->names->nnames);
827 name = &swcm->names->names[swcm->namepos++];
829 if (!strcmp(name->filename, ".") || !strcmp(name->filename, ".."))
830 continue; /* expected bad filenames */
832 if (!vet_filename(name->filename)) {
833 printf("ignoring potentially dangerous server-"
834 "supplied filename '%s'\n", name->filename);
835 continue; /* unexpected bad filename */
838 if (!wc_match(swcm->wildcard, name->filename))
839 continue; /* doesn't match the wildcard */
842 * We have a working filename. Return it.
844 return dupprintf("%s%s%s", swcm->prefix,
846 swcm->prefix[strlen(swcm->prefix)-1]=='/' ?
852 void sftp_finish_wildcard_matching(SftpWildcardMatcher *swcm)
854 struct sftp_packet *pktin;
855 struct sftp_request *req, *rreq;
857 sftp_register(req = fxp_close_send(swcm->dirh));
858 rreq = sftp_find_request(pktin = sftp_recv());
860 fxp_close_recv(pktin, rreq);
863 fxp_free_names(swcm->names);
866 sfree(swcm->wildcard);
872 * General function to match a potential wildcard in a filename
873 * argument and iterate over every matching file. Used in several
874 * PSFTP commands (rmdir, rm, chmod, mv).
876 int wildcard_iterate(char *filename, int (*func)(void *, char *), void *ctx)
878 char *unwcfname, *newname, *cname;
881 unwcfname = snewn(strlen(filename)+1, char);
882 is_wc = !wc_unescape(unwcfname, filename);
885 SftpWildcardMatcher *swcm = sftp_begin_wildcard_matching(filename);
894 while ( (newname = sftp_wildcard_get_filename(swcm)) != NULL ) {
895 cname = canonify(newname);
897 printf("%s: canonify: %s\n", newname, fxp_error());
901 ret &= func(ctx, cname);
906 /* Politely warn the user that nothing matched. */
907 printf("%s: nothing matched\n", filename);
910 sftp_finish_wildcard_matching(swcm);
912 cname = canonify(unwcfname);
914 printf("%s: canonify: %s\n", filename, fxp_error());
917 ret = func(ctx, cname);
926 * Handy helper function.
928 int is_wildcard(char *name)
930 char *unwcfname = snewn(strlen(name)+1, char);
931 int is_wc = !wc_unescape(unwcfname, name);
936 /* ----------------------------------------------------------------------
937 * Actual sftp commands.
939 struct sftp_command {
941 int nwords, wordssize;
942 int (*obey) (struct sftp_command *); /* returns <0 to quit */
945 int sftp_cmd_null(struct sftp_command *cmd)
947 return 1; /* success */
950 int sftp_cmd_unknown(struct sftp_command *cmd)
952 printf("psftp: unknown command \"%s\"\n", cmd->words[0]);
953 return 0; /* failure */
956 int sftp_cmd_quit(struct sftp_command *cmd)
961 int sftp_cmd_close(struct sftp_command *cmd)
968 if (back != NULL && back->connected(backhandle)) {
970 back->special(backhandle, TS_EOF);
971 sftp_recvdata(&ch, 1);
979 * List a directory. If no arguments are given, list pwd; otherwise
980 * list the directory given in words[1].
982 int sftp_cmd_ls(struct sftp_command *cmd)
984 struct fxp_handle *dirh;
985 struct fxp_names *names;
986 struct fxp_name **ournames;
987 int nnames, namesize;
988 char *dir, *cdir, *unwcdir, *wildcard;
989 struct sftp_packet *pktin;
990 struct sftp_request *req, *rreq;
1001 dir = cmd->words[1];
1003 unwcdir = snewn(1 + strlen(dir), char);
1004 if (wc_unescape(unwcdir, dir)) {
1011 wildcard = stripslashes(dir, 0);
1012 unwcdir = dupstr(dir);
1013 len = wildcard - dir;
1014 unwcdir[len] = '\0';
1015 if (len > 0 && unwcdir[len-1] == '/')
1016 unwcdir[len-1] = '\0';
1017 tmpdir = snewn(1 + len, char);
1018 check = wc_unescape(tmpdir, unwcdir);
1021 printf("Multiple-level wildcards are not supported\n");
1028 cdir = canonify(dir);
1030 printf("%s: canonify: %s\n", dir, fxp_error());
1035 printf("Listing directory %s\n", cdir);
1037 sftp_register(req = fxp_opendir_send(cdir));
1038 rreq = sftp_find_request(pktin = sftp_recv());
1039 assert(rreq == req);
1040 dirh = fxp_opendir_recv(pktin, rreq);
1043 printf("Unable to open %s: %s\n", dir, fxp_error());
1045 nnames = namesize = 0;
1050 sftp_register(req = fxp_readdir_send(dirh));
1051 rreq = sftp_find_request(pktin = sftp_recv());
1052 assert(rreq == req);
1053 names = fxp_readdir_recv(pktin, rreq);
1055 if (names == NULL) {
1056 if (fxp_error_type() == SSH_FX_EOF)
1058 printf("Reading directory %s: %s\n", dir, fxp_error());
1061 if (names->nnames == 0) {
1062 fxp_free_names(names);
1066 if (nnames + names->nnames >= namesize) {
1067 namesize += names->nnames + 128;
1068 ournames = sresize(ournames, namesize, struct fxp_name *);
1071 for (i = 0; i < names->nnames; i++)
1072 if (!wildcard || wc_match(wildcard, names->names[i].filename))
1073 ournames[nnames++] = fxp_dup_name(&names->names[i]);
1075 fxp_free_names(names);
1077 sftp_register(req = fxp_close_send(dirh));
1078 rreq = sftp_find_request(pktin = sftp_recv());
1079 assert(rreq == req);
1080 fxp_close_recv(pktin, rreq);
1083 * Now we have our filenames. Sort them by actual file
1084 * name, and then output the longname parts.
1086 qsort(ournames, nnames, sizeof(*ournames), sftp_name_compare);
1091 for (i = 0; i < nnames; i++) {
1092 printf("%s\n", ournames[i]->longname);
1093 fxp_free_name(ournames[i]);
1105 * Change directories. We do this by canonifying the new name, then
1106 * trying to OPENDIR it. Only if that succeeds do we set the new pwd.
1108 int sftp_cmd_cd(struct sftp_command *cmd)
1110 struct fxp_handle *dirh;
1111 struct sftp_packet *pktin;
1112 struct sftp_request *req, *rreq;
1120 if (cmd->nwords < 2)
1121 dir = dupstr(homedir);
1123 dir = canonify(cmd->words[1]);
1126 printf("%s: canonify: %s\n", dir, fxp_error());
1130 sftp_register(req = fxp_opendir_send(dir));
1131 rreq = sftp_find_request(pktin = sftp_recv());
1132 assert(rreq == req);
1133 dirh = fxp_opendir_recv(pktin, rreq);
1136 printf("Directory %s: %s\n", dir, fxp_error());
1141 sftp_register(req = fxp_close_send(dirh));
1142 rreq = sftp_find_request(pktin = sftp_recv());
1143 assert(rreq == req);
1144 fxp_close_recv(pktin, rreq);
1148 printf("Remote directory is now %s\n", pwd);
1154 * Print current directory. Easy as pie.
1156 int sftp_cmd_pwd(struct sftp_command *cmd)
1163 printf("Remote directory is %s\n", pwd);
1168 * Get a file and save it at the local end. We have three very
1169 * similar commands here. The basic one is `get'; `reget' differs
1170 * in that it checks for the existence of the destination file and
1171 * starts from where a previous aborted transfer left off; `mget'
1172 * differs in that it interprets all its arguments as files to
1173 * transfer (never as a different local name for a remote file) and
1174 * can handle wildcards.
1176 int sftp_general_get(struct sftp_command *cmd, int restart, int multiple)
1178 char *fname, *unwcfname, *origfname, *origwfname, *outfname;
1180 int recurse = FALSE;
1188 while (i < cmd->nwords && cmd->words[i][0] == '-') {
1189 if (!strcmp(cmd->words[i], "--")) {
1190 /* finish processing options */
1193 } else if (!strcmp(cmd->words[i], "-r")) {
1196 printf("%s: unrecognised option '%s'\n", cmd->words[0], cmd->words[i]);
1202 if (i >= cmd->nwords) {
1203 printf("%s: expects a filename\n", cmd->words[0]);
1209 SftpWildcardMatcher *swcm;
1211 origfname = cmd->words[i++];
1212 unwcfname = snewn(strlen(origfname)+1, char);
1214 if (multiple && !wc_unescape(unwcfname, origfname)) {
1215 swcm = sftp_begin_wildcard_matching(origfname);
1220 origwfname = sftp_wildcard_get_filename(swcm);
1222 /* Politely warn the user that nothing matched. */
1223 printf("%s: nothing matched\n", origfname);
1224 sftp_finish_wildcard_matching(swcm);
1229 origwfname = origfname;
1233 while (origwfname) {
1234 fname = canonify(origwfname);
1237 printf("%s: canonify: %s\n", origwfname, fxp_error());
1242 if (!multiple && i < cmd->nwords)
1243 outfname = cmd->words[i++];
1245 outfname = stripslashes(origwfname, 0);
1247 ret = sftp_get_file(fname, outfname, recurse, restart);
1253 origwfname = sftp_wildcard_get_filename(swcm);
1260 sftp_finish_wildcard_matching(swcm);
1264 } while (multiple && i < cmd->nwords);
1268 int sftp_cmd_get(struct sftp_command *cmd)
1270 return sftp_general_get(cmd, 0, 0);
1272 int sftp_cmd_mget(struct sftp_command *cmd)
1274 return sftp_general_get(cmd, 0, 1);
1276 int sftp_cmd_reget(struct sftp_command *cmd)
1278 return sftp_general_get(cmd, 1, 0);
1282 * Send a file and store it at the remote end. We have three very
1283 * similar commands here. The basic one is `put'; `reput' differs
1284 * in that it checks for the existence of the destination file and
1285 * starts from where a previous aborted transfer left off; `mput'
1286 * differs in that it interprets all its arguments as files to
1287 * transfer (never as a different remote name for a local file) and
1288 * can handle wildcards.
1290 int sftp_general_put(struct sftp_command *cmd, int restart, int multiple)
1292 char *fname, *wfname, *origoutfname, *outfname;
1294 int recurse = FALSE;
1302 while (i < cmd->nwords && cmd->words[i][0] == '-') {
1303 if (!strcmp(cmd->words[i], "--")) {
1304 /* finish processing options */
1307 } else if (!strcmp(cmd->words[i], "-r")) {
1310 printf("%s: unrecognised option '%s'\n", cmd->words[0], cmd->words[i]);
1316 if (i >= cmd->nwords) {
1317 printf("%s: expects a filename\n", cmd->words[0]);
1323 WildcardMatcher *wcm;
1324 fname = cmd->words[i++];
1326 if (multiple && test_wildcard(fname, FALSE) == WCTYPE_WILDCARD) {
1327 wcm = begin_wildcard_matching(fname);
1328 wfname = wildcard_get_filename(wcm);
1330 /* Politely warn the user that nothing matched. */
1331 printf("%s: nothing matched\n", fname);
1332 finish_wildcard_matching(wcm);
1341 if (!multiple && i < cmd->nwords)
1342 origoutfname = cmd->words[i++];
1344 origoutfname = stripslashes(wfname, 1);
1346 outfname = canonify(origoutfname);
1348 printf("%s: canonify: %s\n", origoutfname, fxp_error());
1351 finish_wildcard_matching(wcm);
1355 ret = sftp_put_file(wfname, outfname, recurse, restart);
1360 wfname = wildcard_get_filename(wcm);
1367 finish_wildcard_matching(wcm);
1372 } while (multiple && i < cmd->nwords);
1376 int sftp_cmd_put(struct sftp_command *cmd)
1378 return sftp_general_put(cmd, 0, 0);
1380 int sftp_cmd_mput(struct sftp_command *cmd)
1382 return sftp_general_put(cmd, 0, 1);
1384 int sftp_cmd_reput(struct sftp_command *cmd)
1386 return sftp_general_put(cmd, 1, 0);
1389 int sftp_cmd_mkdir(struct sftp_command *cmd)
1392 struct sftp_packet *pktin;
1393 struct sftp_request *req, *rreq;
1402 if (cmd->nwords < 2) {
1403 printf("mkdir: expects a directory\n");
1408 for (i = 1; i < cmd->nwords; i++) {
1409 dir = canonify(cmd->words[i]);
1411 printf("%s: canonify: %s\n", dir, fxp_error());
1415 sftp_register(req = fxp_mkdir_send(dir));
1416 rreq = sftp_find_request(pktin = sftp_recv());
1417 assert(rreq == req);
1418 result = fxp_mkdir_recv(pktin, rreq);
1421 printf("mkdir %s: %s\n", dir, fxp_error());
1424 printf("mkdir %s: OK\n", dir);
1432 static int sftp_action_rmdir(void *vctx, char *dir)
1434 struct sftp_packet *pktin;
1435 struct sftp_request *req, *rreq;
1438 sftp_register(req = fxp_rmdir_send(dir));
1439 rreq = sftp_find_request(pktin = sftp_recv());
1440 assert(rreq == req);
1441 result = fxp_rmdir_recv(pktin, rreq);
1444 printf("rmdir %s: %s\n", dir, fxp_error());
1448 printf("rmdir %s: OK\n", dir);
1453 int sftp_cmd_rmdir(struct sftp_command *cmd)
1462 if (cmd->nwords < 2) {
1463 printf("rmdir: expects a directory\n");
1468 for (i = 1; i < cmd->nwords; i++)
1469 ret &= wildcard_iterate(cmd->words[i], sftp_action_rmdir, NULL);
1474 static int sftp_action_rm(void *vctx, char *fname)
1476 struct sftp_packet *pktin;
1477 struct sftp_request *req, *rreq;
1480 sftp_register(req = fxp_remove_send(fname));
1481 rreq = sftp_find_request(pktin = sftp_recv());
1482 assert(rreq == req);
1483 result = fxp_remove_recv(pktin, rreq);
1486 printf("rm %s: %s\n", fname, fxp_error());
1490 printf("rm %s: OK\n", fname);
1495 int sftp_cmd_rm(struct sftp_command *cmd)
1504 if (cmd->nwords < 2) {
1505 printf("rm: expects a filename\n");
1510 for (i = 1; i < cmd->nwords; i++)
1511 ret &= wildcard_iterate(cmd->words[i], sftp_action_rm, NULL);
1516 static int check_is_dir(char *dstfname)
1518 struct sftp_packet *pktin;
1519 struct sftp_request *req, *rreq;
1520 struct fxp_attrs attrs;
1523 sftp_register(req = fxp_stat_send(dstfname));
1524 rreq = sftp_find_request(pktin = sftp_recv());
1525 assert(rreq == req);
1526 result = fxp_stat_recv(pktin, rreq, &attrs);
1529 (attrs.flags & SSH_FILEXFER_ATTR_PERMISSIONS) &&
1530 (attrs.permissions & 0040000))
1536 struct sftp_context_mv {
1541 static int sftp_action_mv(void *vctx, char *srcfname)
1543 struct sftp_context_mv *ctx = (struct sftp_context_mv *)vctx;
1544 struct sftp_packet *pktin;
1545 struct sftp_request *req, *rreq;
1547 char *finalfname, *newcanon = NULL;
1550 if (ctx->dest_is_dir) {
1554 p = srcfname + strlen(srcfname);
1555 while (p > srcfname && p[-1] != '/') p--;
1556 newname = dupcat(ctx->dstfname, "/", p, NULL);
1557 newcanon = canonify(newname);
1559 printf("%s: canonify: %s\n", newname, fxp_error());
1565 finalfname = newcanon;
1567 finalfname = ctx->dstfname;
1570 sftp_register(req = fxp_rename_send(srcfname, finalfname));
1571 rreq = sftp_find_request(pktin = sftp_recv());
1572 assert(rreq == req);
1573 result = fxp_rename_recv(pktin, rreq);
1575 error = result ? NULL : fxp_error();
1578 printf("mv %s %s: %s\n", srcfname, finalfname, error);
1581 printf("%s -> %s\n", srcfname, finalfname);
1589 int sftp_cmd_mv(struct sftp_command *cmd)
1591 struct sftp_context_mv actx, *ctx = &actx;
1599 if (cmd->nwords < 3) {
1600 printf("mv: expects two filenames\n");
1604 ctx->dstfname = canonify(cmd->words[cmd->nwords-1]);
1605 if (!ctx->dstfname) {
1606 printf("%s: canonify: %s\n", ctx->dstfname, fxp_error());
1611 * If there's more than one source argument, or one source
1612 * argument which is a wildcard, we _require_ that the
1613 * destination is a directory.
1615 ctx->dest_is_dir = check_is_dir(ctx->dstfname);
1616 if ((cmd->nwords > 3 || is_wildcard(cmd->words[1])) && !ctx->dest_is_dir) {
1617 printf("mv: multiple or wildcard arguments require the destination"
1618 " to be a directory\n");
1619 sfree(ctx->dstfname);
1624 * Now iterate over the source arguments.
1627 for (i = 1; i < cmd->nwords-1; i++)
1628 ret &= wildcard_iterate(cmd->words[i], sftp_action_mv, ctx);
1630 sfree(ctx->dstfname);
1634 struct sftp_context_chmod {
1635 unsigned attrs_clr, attrs_xor;
1638 static int sftp_action_chmod(void *vctx, char *fname)
1640 struct fxp_attrs attrs;
1641 struct sftp_packet *pktin;
1642 struct sftp_request *req, *rreq;
1644 unsigned oldperms, newperms;
1645 struct sftp_context_chmod *ctx = (struct sftp_context_chmod *)vctx;
1647 sftp_register(req = fxp_stat_send(fname));
1648 rreq = sftp_find_request(pktin = sftp_recv());
1649 assert(rreq == req);
1650 result = fxp_stat_recv(pktin, rreq, &attrs);
1652 if (!result || !(attrs.flags & SSH_FILEXFER_ATTR_PERMISSIONS)) {
1653 printf("get attrs for %s: %s\n", fname,
1654 result ? "file permissions not provided" : fxp_error());
1658 attrs.flags = SSH_FILEXFER_ATTR_PERMISSIONS; /* perms _only_ */
1659 oldperms = attrs.permissions & 07777;
1660 attrs.permissions &= ~ctx->attrs_clr;
1661 attrs.permissions ^= ctx->attrs_xor;
1662 newperms = attrs.permissions & 07777;
1664 if (oldperms == newperms)
1665 return 1; /* no need to do anything! */
1667 sftp_register(req = fxp_setstat_send(fname, attrs));
1668 rreq = sftp_find_request(pktin = sftp_recv());
1669 assert(rreq == req);
1670 result = fxp_setstat_recv(pktin, rreq);
1673 printf("set attrs for %s: %s\n", fname, fxp_error());
1677 printf("%s: %04o -> %04o\n", fname, oldperms, newperms);
1682 int sftp_cmd_chmod(struct sftp_command *cmd)
1686 struct sftp_context_chmod actx, *ctx = &actx;
1693 if (cmd->nwords < 3) {
1694 printf("chmod: expects a mode specifier and a filename\n");
1699 * Attempt to parse the mode specifier in cmd->words[1]. We
1700 * don't support the full horror of Unix chmod; instead we
1701 * support a much simpler syntax in which the user can either
1702 * specify an octal number, or a comma-separated sequence of
1703 * [ugoa]*[-+=][rwxst]+. (The initial [ugoa] sequence may
1704 * _only_ be omitted if the only attribute mentioned is t,
1705 * since all others require a user/group/other specification.
1706 * Additionally, the s attribute may not be specified for any
1707 * [ugoa] specifications other than exactly u or exactly g.
1709 ctx->attrs_clr = ctx->attrs_xor = 0;
1710 mode = cmd->words[1];
1711 if (mode[0] >= '0' && mode[0] <= '9') {
1712 if (mode[strspn(mode, "01234567")]) {
1713 printf("chmod: numeric file modes should"
1714 " contain digits 0-7 only\n");
1717 ctx->attrs_clr = 07777;
1718 sscanf(mode, "%o", &ctx->attrs_xor);
1719 ctx->attrs_xor &= ctx->attrs_clr;
1722 char *modebegin = mode;
1723 unsigned subset, perms;
1727 while (*mode && *mode != ',' &&
1728 *mode != '+' && *mode != '-' && *mode != '=') {
1730 case 'u': subset |= 04700; break; /* setuid, user perms */
1731 case 'g': subset |= 02070; break; /* setgid, group perms */
1732 case 'o': subset |= 00007; break; /* just other perms */
1733 case 'a': subset |= 06777; break; /* all of the above */
1735 printf("chmod: file mode '%.*s' contains unrecognised"
1736 " user/group/other specifier '%c'\n",
1737 (int)strcspn(modebegin, ","), modebegin, *mode);
1742 if (!*mode || *mode == ',') {
1743 printf("chmod: file mode '%.*s' is incomplete\n",
1744 (int)strcspn(modebegin, ","), modebegin);
1748 if (!*mode || *mode == ',') {
1749 printf("chmod: file mode '%.*s' is incomplete\n",
1750 (int)strcspn(modebegin, ","), modebegin);
1754 while (*mode && *mode != ',') {
1756 case 'r': perms |= 00444; break;
1757 case 'w': perms |= 00222; break;
1758 case 'x': perms |= 00111; break;
1759 case 't': perms |= 01000; subset |= 01000; break;
1761 if ((subset & 06777) != 04700 &&
1762 (subset & 06777) != 02070) {
1763 printf("chmod: file mode '%.*s': set[ug]id bit should"
1764 " be used with exactly one of u or g only\n",
1765 (int)strcspn(modebegin, ","), modebegin);
1771 printf("chmod: file mode '%.*s' contains unrecognised"
1772 " permission specifier '%c'\n",
1773 (int)strcspn(modebegin, ","), modebegin, *mode);
1778 if (!(subset & 06777) && (perms &~ subset)) {
1779 printf("chmod: file mode '%.*s' contains no user/group/other"
1780 " specifier and permissions other than 't' \n",
1781 (int)strcspn(modebegin, ","), modebegin);
1787 ctx->attrs_clr |= perms;
1788 ctx->attrs_xor |= perms;
1791 ctx->attrs_clr |= perms;
1792 ctx->attrs_xor &= ~perms;
1795 ctx->attrs_clr |= subset;
1796 ctx->attrs_xor |= perms;
1799 if (*mode) mode++; /* eat comma */
1804 for (i = 2; i < cmd->nwords; i++)
1805 ret &= wildcard_iterate(cmd->words[i], sftp_action_chmod, ctx);
1810 static int sftp_cmd_open(struct sftp_command *cmd)
1815 printf("psftp: already connected\n");
1819 if (cmd->nwords < 2) {
1820 printf("open: expects a host name\n");
1824 if (cmd->nwords > 2) {
1825 portnumber = atoi(cmd->words[2]);
1826 if (portnumber == 0) {
1827 printf("open: invalid port number\n");
1833 if (psftp_connect(cmd->words[1], NULL, portnumber)) {
1834 back = NULL; /* connection is already closed */
1835 return -1; /* this is fatal */
1841 static int sftp_cmd_lcd(struct sftp_command *cmd)
1843 char *currdir, *errmsg;
1845 if (cmd->nwords < 2) {
1846 printf("lcd: expects a local directory name\n");
1850 errmsg = psftp_lcd(cmd->words[1]);
1852 printf("lcd: unable to change directory: %s\n", errmsg);
1857 currdir = psftp_getcwd();
1858 printf("New local directory is %s\n", currdir);
1864 static int sftp_cmd_lpwd(struct sftp_command *cmd)
1868 currdir = psftp_getcwd();
1869 printf("Current local directory is %s\n", currdir);
1875 static int sftp_cmd_pling(struct sftp_command *cmd)
1879 exitcode = system(cmd->words[1]);
1880 return (exitcode == 0);
1883 static int sftp_cmd_help(struct sftp_command *cmd);
1885 static struct sftp_cmd_lookup {
1888 * For help purposes, there are two kinds of command:
1890 * - primary commands, in which `longhelp' is non-NULL. In
1891 * this case `shorthelp' is descriptive text, and `longhelp'
1892 * is longer descriptive text intended to be printed after
1895 * - alias commands, in which `longhelp' is NULL. In this case
1896 * `shorthelp' is the name of a primary command, which
1897 * contains the help that should double up for this command.
1899 int listed; /* do we list this in primary help? */
1902 int (*obey) (struct sftp_command *);
1905 * List of sftp commands. This is binary-searched so it MUST be
1909 "!", TRUE, "run a local command",
1911 /* FIXME: this example is crap for non-Windows. */
1912 " Runs a local command. For example, \"!del myfile\".\n",
1916 "bye", TRUE, "finish your SFTP session",
1918 " Terminates your SFTP session and quits the PSFTP program.\n",
1922 "cd", TRUE, "change your remote working directory",
1923 " [ <new working directory> ]\n"
1924 " Change the remote working directory for your SFTP session.\n"
1925 " If a new working directory is not supplied, you will be\n"
1926 " returned to your home directory.\n",
1930 "chmod", TRUE, "change file permissions and modes",
1931 " <modes> <filename-or-wildcard> [ <filename-or-wildcard>... ]\n"
1932 " Change the file permissions on one or more remote files or\n"
1934 " <modes> can be any octal Unix permission specifier.\n"
1935 " Alternatively, <modes> can include the following modifiers:\n"
1936 " u+r make file readable by owning user\n"
1937 " u+w make file writable by owning user\n"
1938 " u+x make file executable by owning user\n"
1939 " u-r make file not readable by owning user\n"
1940 " [also u-w, u-x]\n"
1941 " g+r make file readable by members of owning group\n"
1942 " [also g+w, g+x, g-r, g-w, g-x]\n"
1943 " o+r make file readable by all other users\n"
1944 " [also o+w, o+x, o-r, o-w, o-x]\n"
1945 " a+r make file readable by absolutely everybody\n"
1946 " [also a+w, a+x, a-r, a-w, a-x]\n"
1947 " u+s enable the Unix set-user-ID bit\n"
1948 " u-s disable the Unix set-user-ID bit\n"
1949 " g+s enable the Unix set-group-ID bit\n"
1950 " g-s disable the Unix set-group-ID bit\n"
1951 " +t enable the Unix \"sticky bit\"\n"
1952 " You can give more than one modifier for the same user (\"g-rwx\"), and\n"
1953 " more than one user for the same modifier (\"ug+w\"). You can\n"
1954 " use commas to separate different modifiers (\"u+rwx,g+s\").\n",
1958 "close", TRUE, "finish your SFTP session but do not quit PSFTP",
1960 " Terminates your SFTP session, but does not quit the PSFTP\n"
1961 " program. You can then use \"open\" to start another SFTP\n"
1962 " session, to the same server or to a different one.\n",
1966 "del", TRUE, "delete files on the remote server",
1967 " <filename-or-wildcard> [ <filename-or-wildcard>... ]\n"
1968 " Delete a file or files from the server.\n",
1972 "delete", FALSE, "del", NULL, sftp_cmd_rm
1975 "dir", TRUE, "list remote files",
1976 " [ <directory-name> ]/[ <wildcard> ]\n"
1977 " List the contents of a specified directory on the server.\n"
1978 " If <directory-name> is not given, the current working directory\n"
1980 " If <wildcard> is given, it is treated as a set of files to\n"
1981 " list; otherwise, all files are listed.\n",
1985 "exit", TRUE, "bye", NULL, sftp_cmd_quit
1988 "get", TRUE, "download a file from the server to your local machine",
1989 " [ -r ] [ -- ] <filename> [ <local-filename> ]\n"
1990 " Downloads a file on the server and stores it locally under\n"
1991 " the same name, or under a different one if you supply the\n"
1992 " argument <local-filename>.\n"
1993 " If -r specified, recursively fetch a directory.\n",
1997 "help", TRUE, "give help",
1998 " [ <command> [ <command> ... ] ]\n"
1999 " Give general help if no commands are specified.\n"
2000 " If one or more commands are specified, give specific help on\n"
2001 " those particular commands.\n",
2005 "lcd", TRUE, "change local working directory",
2006 " <local-directory-name>\n"
2007 " Change the local working directory of the PSFTP program (the\n"
2008 " default location where the \"get\" command will save files).\n",
2012 "lpwd", TRUE, "print local working directory",
2014 " Print the local working directory of the PSFTP program (the\n"
2015 " default location where the \"get\" command will save files).\n",
2019 "ls", TRUE, "dir", NULL,
2023 "mget", TRUE, "download multiple files at once",
2024 " [ -r ] [ -- ] <filename-or-wildcard> [ <filename-or-wildcard>... ]\n"
2025 " Downloads many files from the server, storing each one under\n"
2026 " the same name it has on the server side. You can use wildcards\n"
2027 " such as \"*.c\" to specify lots of files at once.\n"
2028 " If -r specified, recursively fetch files and directories.\n",
2032 "mkdir", TRUE, "create directories on the remote server",
2033 " <directory-name> [ <directory-name>... ]\n"
2034 " Creates directories with the given names on the server.\n",
2038 "mput", TRUE, "upload multiple files at once",
2039 " [ -r ] [ -- ] <filename-or-wildcard> [ <filename-or-wildcard>... ]\n"
2040 " Uploads many files to the server, storing each one under the\n"
2041 " same name it has on the client side. You can use wildcards\n"
2042 " such as \"*.c\" to specify lots of files at once.\n"
2043 " If -r specified, recursively store files and directories.\n",
2047 "mv", TRUE, "move or rename file(s) on the remote server",
2048 " <source> [ <source>... ] <destination>\n"
2049 " Moves or renames <source>(s) on the server to <destination>,\n"
2050 " also on the server.\n"
2051 " If <destination> specifies an existing directory, then <source>\n"
2052 " may be a wildcard, and multiple <source>s may be given; all\n"
2053 " source files are moved into <destination>.\n"
2054 " Otherwise, <source> must specify a single file, which is moved\n"
2055 " or renamed so that it is accessible under the name <destination>.\n",
2059 "open", TRUE, "connect to a host",
2060 " [<user>@]<hostname> [<port>]\n"
2061 " Establishes an SFTP connection to a given host. Only usable\n"
2062 " when you are not already connected to a server.\n",
2066 "put", TRUE, "upload a file from your local machine to the server",
2067 " [ -r ] [ -- ] <filename> [ <remote-filename> ]\n"
2068 " Uploads a file to the server and stores it there under\n"
2069 " the same name, or under a different one if you supply the\n"
2070 " argument <remote-filename>.\n"
2071 " If -r specified, recursively store a directory.\n",
2075 "pwd", TRUE, "print your remote working directory",
2077 " Print the current remote working directory for your SFTP session.\n",
2081 "quit", TRUE, "bye", NULL,
2085 "reget", TRUE, "continue downloading files",
2086 " [ -r ] [ -- ] <filename> [ <local-filename> ]\n"
2087 " Works exactly like the \"get\" command, but the local file\n"
2088 " must already exist. The download will begin at the end of the\n"
2089 " file. This is for resuming a download that was interrupted.\n"
2090 " If -r specified, resume interrupted \"get -r\".\n",
2094 "ren", TRUE, "mv", NULL,
2098 "rename", FALSE, "mv", NULL,
2102 "reput", TRUE, "continue uploading files",
2103 " [ -r ] [ -- ] <filename> [ <remote-filename> ]\n"
2104 " Works exactly like the \"put\" command, but the remote file\n"
2105 " must already exist. The upload will begin at the end of the\n"
2106 " file. This is for resuming an upload that was interrupted.\n"
2107 " If -r specified, resume interrupted \"put -r\".\n",
2111 "rm", TRUE, "del", NULL,
2115 "rmdir", TRUE, "remove directories on the remote server",
2116 " <directory-name> [ <directory-name>... ]\n"
2117 " Removes the directory with the given name on the server.\n"
2118 " The directory will not be removed unless it is empty.\n"
2119 " Wildcards may be used to specify multiple directories.\n",
2124 const struct sftp_cmd_lookup *lookup_command(char *name)
2129 j = sizeof(sftp_lookup) / sizeof(*sftp_lookup);
2132 cmp = strcmp(name, sftp_lookup[k].name);
2138 return &sftp_lookup[k];
2144 static int sftp_cmd_help(struct sftp_command *cmd)
2147 if (cmd->nwords == 1) {
2149 * Give short help on each command.
2153 for (i = 0; i < sizeof(sftp_lookup) / sizeof(*sftp_lookup); i++) {
2155 if (!sftp_lookup[i].listed)
2157 len = strlen(sftp_lookup[i].name);
2161 for (i = 0; i < sizeof(sftp_lookup) / sizeof(*sftp_lookup); i++) {
2162 const struct sftp_cmd_lookup *lookup;
2163 if (!sftp_lookup[i].listed)
2165 lookup = &sftp_lookup[i];
2166 printf("%-*s", maxlen+2, lookup->name);
2167 if (lookup->longhelp == NULL)
2168 lookup = lookup_command(lookup->shorthelp);
2169 printf("%s\n", lookup->shorthelp);
2173 * Give long help on specific commands.
2175 for (i = 1; i < cmd->nwords; i++) {
2176 const struct sftp_cmd_lookup *lookup;
2177 lookup = lookup_command(cmd->words[i]);
2179 printf("help: %s: command not found\n", cmd->words[i]);
2181 printf("%s", lookup->name);
2182 if (lookup->longhelp == NULL)
2183 lookup = lookup_command(lookup->shorthelp);
2184 printf("%s", lookup->longhelp);
2191 /* ----------------------------------------------------------------------
2192 * Command line reading and parsing.
2194 struct sftp_command *sftp_getcmd(FILE *fp, int mode, int modeflags)
2197 struct sftp_command *cmd;
2201 cmd = snew(struct sftp_command);
2211 line = fgetline(fp);
2213 line = ssh_sftp_get_cmdline("psftp> ", back == NULL);
2216 if (!line || !*line) {
2217 cmd->obey = sftp_cmd_quit;
2218 if ((mode == 0) || (modeflags & 1))
2220 return cmd; /* eof */
2223 line[strcspn(line, "\r\n")] = '\0';
2225 if (modeflags & 1) {
2226 printf("%s\n", line);
2230 while (*p && (*p == ' ' || *p == '\t'))
2235 * Special case: the ! command. This is always parsed as
2236 * exactly two words: one containing the !, and the second
2237 * containing everything else on the line.
2239 cmd->nwords = cmd->wordssize = 2;
2240 cmd->words = sresize(cmd->words, cmd->wordssize, char *);
2241 cmd->words[0] = dupstr("!");
2242 cmd->words[1] = dupstr(p+1);
2246 * Parse the command line into words. The syntax is:
2247 * - double quotes are removed, but cause spaces within to be
2248 * treated as non-separating.
2249 * - a double-doublequote pair is a literal double quote, inside
2250 * _or_ outside quotes. Like this:
2252 * firstword "second word" "this has ""quotes"" in" and""this""
2258 * >this has "quotes" in<
2262 /* skip whitespace */
2263 while (*p && (*p == ' ' || *p == '\t'))
2265 /* mark start of word */
2266 q = r = p; /* q sits at start, r writes word */
2269 if (!quoting && (*p == ' ' || *p == '\t'))
2270 break; /* reached end of word */
2271 else if (*p == '"' && p[1] == '"')
2272 p += 2, *r++ = '"'; /* a literal quote */
2274 p++, quoting = !quoting;
2279 p++; /* skip over the whitespace */
2281 if (cmd->nwords >= cmd->wordssize) {
2282 cmd->wordssize = cmd->nwords + 16;
2283 cmd->words = sresize(cmd->words, cmd->wordssize, char *);
2285 cmd->words[cmd->nwords++] = dupstr(q);
2292 * Now parse the first word and assign a function.
2295 if (cmd->nwords == 0)
2296 cmd->obey = sftp_cmd_null;
2298 const struct sftp_cmd_lookup *lookup;
2299 lookup = lookup_command(cmd->words[0]);
2301 cmd->obey = sftp_cmd_unknown;
2303 cmd->obey = lookup->obey;
2309 static int do_sftp_init(void)
2311 struct sftp_packet *pktin;
2312 struct sftp_request *req, *rreq;
2315 * Do protocol initialisation.
2319 "Fatal: unable to initialise SFTP: %s\n", fxp_error());
2320 return 1; /* failure */
2324 * Find out where our home directory is.
2326 sftp_register(req = fxp_realpath_send("."));
2327 rreq = sftp_find_request(pktin = sftp_recv());
2328 assert(rreq == req);
2329 homedir = fxp_realpath_recv(pktin, rreq);
2333 "Warning: failed to resolve home directory: %s\n",
2335 homedir = dupstr(".");
2337 printf("Remote working directory is %s\n", homedir);
2339 pwd = dupstr(homedir);
2343 void do_sftp_cleanup()
2347 back->special(backhandle, TS_EOF);
2348 sftp_recvdata(&ch, 1);
2349 back->free(backhandle);
2350 sftp_cleanup_request();
2364 void do_sftp(int mode, int modeflags, char *batchfile)
2374 /* ------------------------------------------------------------------
2375 * Now we're ready to do Real Stuff.
2378 struct sftp_command *cmd;
2379 cmd = sftp_getcmd(NULL, 0, 0);
2382 ret = cmd->obey(cmd);
2385 for(i = 0; i < cmd->nwords; i++)
2386 sfree(cmd->words[i]);
2394 fp = fopen(batchfile, "r");
2396 printf("Fatal: unable to open %s\n", batchfile);
2400 struct sftp_command *cmd;
2401 cmd = sftp_getcmd(fp, mode, modeflags);
2404 ret = cmd->obey(cmd);
2408 if (!(modeflags & 2))
2417 /* ----------------------------------------------------------------------
2418 * Dirty bits: integration with PuTTY.
2421 static int verbose = 0;
2424 * Print an error message and perform a fatal exit.
2426 void fatalbox(char *fmt, ...)
2431 str = dupvprintf(fmt, ap);
2432 str2 = dupcat("Fatal: ", str, "\n", NULL);
2435 fputs(str2, stderr);
2440 void modalfatalbox(char *fmt, ...)
2445 str = dupvprintf(fmt, ap);
2446 str2 = dupcat("Fatal: ", str, "\n", NULL);
2449 fputs(str2, stderr);
2454 void connection_fatal(void *frontend, char *fmt, ...)
2459 str = dupvprintf(fmt, ap);
2460 str2 = dupcat("Fatal: ", str, "\n", NULL);
2463 fputs(str2, stderr);
2469 void ldisc_send(void *handle, char *buf, int len, int interactive)
2472 * This is only here because of the calls to ldisc_send(NULL,
2473 * 0) in ssh.c. Nothing in PSFTP actually needs to use the
2474 * ldisc as an ldisc. So if we get called with any real data, I
2475 * want to know about it.
2481 * In psftp, all agent requests should be synchronous, so this is a
2482 * never-called stub.
2484 void agent_schedule_callback(void (*callback)(void *, void *, int),
2485 void *callback_ctx, void *data, int len)
2487 assert(!"We shouldn't be here");
2491 * Receive a block of data from the SSH link. Block until all data
2494 * To do this, we repeatedly call the SSH protocol module, with our
2495 * own trap in from_backend() to catch the data that comes back. We
2496 * do this until we have enough data.
2499 static unsigned char *outptr; /* where to put the data */
2500 static unsigned outlen; /* how much data required */
2501 static unsigned char *pending = NULL; /* any spare data */
2502 static unsigned pendlen = 0, pendsize = 0; /* length and phys. size of buffer */
2503 int from_backend(void *frontend, int is_stderr, const char *data, int datalen)
2505 unsigned char *p = (unsigned char *) data;
2506 unsigned len = (unsigned) datalen;
2509 * stderr data is just spouted to local stderr and otherwise
2514 fwrite(data, 1, len, stderr);
2519 * If this is before the real session begins, just return.
2524 if ((outlen > 0) && (len > 0)) {
2525 unsigned used = outlen;
2528 memcpy(outptr, p, used);
2536 if (pendsize < pendlen + len) {
2537 pendsize = pendlen + len + 4096;
2538 pending = sresize(pending, pendsize, unsigned char);
2540 memcpy(pending + pendlen, p, len);
2546 int from_backend_untrusted(void *frontend_handle, const char *data, int len)
2549 * No "untrusted" output should get here (the way the code is
2550 * currently, it's all diverted by FLAG_STDERR).
2552 assert(!"Unexpected call to from_backend_untrusted()");
2553 return 0; /* not reached */
2555 int sftp_recvdata(char *buf, int len)
2557 outptr = (unsigned char *) buf;
2561 * See if the pending-input block contains some of what we
2565 unsigned pendused = pendlen;
2566 if (pendused > outlen)
2568 memcpy(outptr, pending, pendused);
2569 memmove(pending, pending + pendused, pendlen - pendused);
2572 pendlen -= pendused;
2582 while (outlen > 0) {
2583 if (back->exitcode(backhandle) >= 0 || ssh_sftp_loop_iteration() < 0)
2584 return 0; /* doom */
2589 int sftp_senddata(char *buf, int len)
2591 back->send(backhandle, buf, len);
2596 * Short description of parameters.
2598 static void usage(void)
2600 printf("PuTTY Secure File Transfer (SFTP) client\n");
2601 printf("%s\n", ver);
2602 printf("Usage: psftp [options] [user@]host\n");
2603 printf("Options:\n");
2604 printf(" -V print version information and exit\n");
2605 printf(" -pgpfp print PGP key fingerprints and exit\n");
2606 printf(" -b file use specified batchfile\n");
2607 printf(" -bc output batchfile commands\n");
2608 printf(" -be don't stop batchfile processing if errors\n");
2609 printf(" -v show verbose messages\n");
2610 printf(" -load sessname Load settings from saved session\n");
2611 printf(" -l user connect with specified username\n");
2612 printf(" -P port connect to specified port\n");
2613 printf(" -pw passw login with specified password\n");
2614 printf(" -1 -2 force use of particular SSH protocol version\n");
2615 printf(" -4 -6 force use of IPv4 or IPv6\n");
2616 printf(" -C enable compression\n");
2617 printf(" -i key private key file for authentication\n");
2618 printf(" -noagent disable use of Pageant\n");
2619 printf(" -agent enable use of Pageant\n");
2620 printf(" -batch disable all interactive prompts\n");
2624 static void version(void)
2626 printf("psftp: %s\n", ver);
2631 * Connect to a host.
2633 static int psftp_connect(char *userhost, char *user, int portnumber)
2635 char *host, *realhost;
2639 /* Separate host and username */
2641 host = strrchr(host, '@');
2647 printf("psftp: multiple usernames specified; using \"%s\"\n",
2654 * If we haven't loaded session details already (e.g., from -load),
2655 * try looking for a session called "host".
2657 if (!loaded_session) {
2658 /* Try to load settings for `host' into a temporary config */
2660 cfg2.host[0] = '\0';
2661 do_defaults(host, &cfg2);
2662 if (cfg2.host[0] != '\0') {
2663 /* Settings present and include hostname */
2664 /* Re-load data into the real config. */
2665 do_defaults(host, &cfg);
2667 /* Session doesn't exist or mention a hostname. */
2668 /* Use `host' as a bare hostname. */
2669 strncpy(cfg.host, host, sizeof(cfg.host) - 1);
2670 cfg.host[sizeof(cfg.host) - 1] = '\0';
2673 /* Patch in hostname `host' to session details. */
2674 strncpy(cfg.host, host, sizeof(cfg.host) - 1);
2675 cfg.host[sizeof(cfg.host) - 1] = '\0';
2679 * Force use of SSH. (If they got the protocol wrong we assume the
2680 * port is useless too.)
2682 if (cfg.protocol != PROT_SSH) {
2683 cfg.protocol = PROT_SSH;
2688 * If saved session / Default Settings says SSH-1 (`1 only' or `1'),
2689 * then change it to SSH-2, on the grounds that that's more likely to
2690 * work for SFTP. (Can be overridden with `-1' option.)
2691 * But if it says `2 only' or `2', respect which.
2693 if (cfg.sshprot != 2 && cfg.sshprot != 3)
2697 * Enact command-line overrides.
2699 cmdline_run_saved(&cfg);
2702 * Trim leading whitespace off the hostname if it's there.
2705 int space = strspn(cfg.host, " \t");
2706 memmove(cfg.host, cfg.host+space, 1+strlen(cfg.host)-space);
2709 /* See if host is of the form user@host */
2710 if (cfg.host[0] != '\0') {
2711 char *atsign = strrchr(cfg.host, '@');
2712 /* Make sure we're not overflowing the user field */
2714 if (atsign - cfg.host < sizeof cfg.username) {
2715 strncpy(cfg.username, cfg.host, atsign - cfg.host);
2716 cfg.username[atsign - cfg.host] = '\0';
2718 memmove(cfg.host, atsign + 1, 1 + strlen(atsign + 1));
2723 * Trim a colon suffix off the hostname if it's there.
2725 cfg.host[strcspn(cfg.host, ":")] = '\0';
2728 * Remove any remaining whitespace from the hostname.
2732 while (cfg.host[p2] != '\0') {
2733 if (cfg.host[p2] != ' ' && cfg.host[p2] != '\t') {
2734 cfg.host[p1] = cfg.host[p2];
2739 cfg.host[p1] = '\0';
2743 if (user != NULL && user[0] != '\0') {
2744 strncpy(cfg.username, user, sizeof(cfg.username) - 1);
2745 cfg.username[sizeof(cfg.username) - 1] = '\0';
2749 cfg.port = portnumber;
2752 * Disable scary things which shouldn't be enabled for simple
2753 * things like SCP and SFTP: agent forwarding, port forwarding,
2756 cfg.x11_forward = 0;
2758 cfg.portfwd[0] = cfg.portfwd[1] = '\0';
2759 cfg.ssh_simple = TRUE;
2761 /* Set up subsystem name. */
2762 strcpy(cfg.remote_cmd, "sftp");
2763 cfg.ssh_subsys = TRUE;
2767 * Set up fallback option, for SSH-1 servers or servers with the
2768 * sftp subsystem not enabled but the server binary installed
2769 * in the usual place. We only support fallback on Unix
2770 * systems, and we use a kludgy piece of shellery which should
2771 * try to find sftp-server in various places (the obvious
2772 * systemwide spots /usr/lib and /usr/local/lib, and then the
2773 * user's PATH) and finally give up.
2775 * test -x /usr/lib/sftp-server && exec /usr/lib/sftp-server
2776 * test -x /usr/local/lib/sftp-server && exec /usr/local/lib/sftp-server
2779 * the idea being that this will attempt to use either of the
2780 * obvious pathnames and then give up, and when it does give up
2781 * it will print the preferred pathname in the error messages.
2783 cfg.remote_cmd_ptr2 =
2784 "test -x /usr/lib/sftp-server && exec /usr/lib/sftp-server\n"
2785 "test -x /usr/local/lib/sftp-server && exec /usr/local/lib/sftp-server\n"
2787 cfg.ssh_subsys2 = FALSE;
2789 back = &ssh_backend;
2791 err = back->init(NULL, &backhandle, &cfg, cfg.host, cfg.port, &realhost,
2792 0, cfg.tcp_keepalives);
2794 fprintf(stderr, "ssh_init: %s\n", err);
2797 logctx = log_init(NULL, &cfg);
2798 back->provide_logctx(backhandle, logctx);
2799 console_provide_logctx(logctx);
2800 while (!back->sendok(backhandle)) {
2801 if (back->exitcode(backhandle) >= 0)
2803 if (ssh_sftp_loop_iteration() < 0) {
2804 fprintf(stderr, "ssh_init: error during SSH connection setup\n");
2808 if (verbose && realhost != NULL)
2809 printf("Connected to %s\n", realhost);
2810 if (realhost != NULL)
2815 void cmdline_error(char *p, ...)
2818 fprintf(stderr, "psftp: ");
2820 vfprintf(stderr, p, ap);
2822 fprintf(stderr, "\n try typing \"psftp -h\" for help\n");
2827 * Main program. Parse arguments etc.
2829 int psftp_main(int argc, char *argv[])
2833 char *userhost, *user;
2836 char *batchfile = NULL;
2839 flags = FLAG_STDERR | FLAG_INTERACTIVE
2840 #ifdef FLAG_SYNCAGENT
2844 cmdline_tooltype = TOOLTYPE_FILETRANSFER;
2847 userhost = user = NULL;
2849 /* Load Default Settings before doing anything else. */
2850 do_defaults(NULL, &cfg);
2851 loaded_session = FALSE;
2854 for (i = 1; i < argc; i++) {
2856 if (argv[i][0] != '-') {
2860 userhost = dupstr(argv[i]);
2863 ret = cmdline_process_param(argv[i], i+1<argc?argv[i+1]:NULL, 1, &cfg);
2865 cmdline_error("option \"%s\" requires an argument", argv[i]);
2866 } else if (ret == 2) {
2867 i++; /* skip next argument */
2868 } else if (ret == 1) {
2869 /* We have our own verbosity in addition to `flags'. */
2870 if (flags & FLAG_VERBOSE)
2872 } else if (strcmp(argv[i], "-h") == 0 ||
2873 strcmp(argv[i], "-?") == 0) {
2875 } else if (strcmp(argv[i], "-pgpfp") == 0) {
2878 } else if (strcmp(argv[i], "-V") == 0) {
2880 } else if (strcmp(argv[i], "-batch") == 0) {
2881 console_batch_mode = 1;
2882 } else if (strcmp(argv[i], "-b") == 0 && i + 1 < argc) {
2884 batchfile = argv[++i];
2885 } else if (strcmp(argv[i], "-bc") == 0) {
2886 modeflags = modeflags | 1;
2887 } else if (strcmp(argv[i], "-be") == 0) {
2888 modeflags = modeflags | 2;
2889 } else if (strcmp(argv[i], "--") == 0) {
2893 cmdline_error("unknown option \"%s\"", argv[i]);
2901 * If the loaded session provides a hostname, and a hostname has not
2902 * otherwise been specified, pop it in `userhost' so that
2903 * `psftp -load sessname' is sufficient to start a session.
2905 if (!userhost && cfg.host[0] != '\0') {
2906 userhost = dupstr(cfg.host);
2910 * If a user@host string has already been provided, connect to
2915 ret = psftp_connect(userhost, user, portnumber);
2922 printf("psftp: no hostname specified; use \"open host.name\""
2926 do_sftp(mode, modeflags, batchfile);
2928 if (back != NULL && back->connected(backhandle)) {
2930 back->special(backhandle, TS_EOF);
2931 sftp_recvdata(&ch, 1);
2936 console_provide_logctx(NULL);