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 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, '\\');
172 * qsort comparison routine for fxp_name structures. Sorts by real
175 static int sftp_name_compare(const void *av, const void *bv)
177 const struct fxp_name *const *a = (const struct fxp_name *const *) av;
178 const struct fxp_name *const *b = (const struct fxp_name *const *) bv;
179 return strcmp((*a)->filename, (*b)->filename);
183 * Likewise, but for a bare char *.
185 static int bare_name_compare(const void *av, const void *bv)
187 const char **a = (const char **) av;
188 const char **b = (const char **) bv;
189 return strcmp(*a, *b);
192 static void not_connected(void)
194 printf("psftp: not connected to a host; use \"open host.name\"\n");
197 /* ----------------------------------------------------------------------
198 * The meat of the `get' and `put' commands.
200 int sftp_get_file(char *fname, char *outfname, int recurse, int restart)
202 struct fxp_handle *fh;
203 struct sftp_packet *pktin;
204 struct sftp_request *req, *rreq;
205 struct fxp_xfer *xfer;
208 int ret, shown_err = FALSE;
211 * In recursive mode, see if we're dealing with a directory.
212 * (If we're not in recursive mode, we need not even check: the
213 * subsequent FXP_OPEN will return a usable error message.)
216 struct fxp_attrs attrs;
219 sftp_register(req = fxp_stat_send(fname));
220 rreq = sftp_find_request(pktin = sftp_recv());
222 result = fxp_stat_recv(pktin, rreq, &attrs);
225 (attrs.flags & SSH_FILEXFER_ATTR_PERMISSIONS) &&
226 (attrs.permissions & 0040000)) {
228 struct fxp_handle *dirhandle;
229 int nnames, namesize;
230 struct fxp_name **ournames;
231 struct fxp_names *names;
235 * First, attempt to create the destination directory,
236 * unless it already exists.
238 if (file_type(outfname) != FILE_TYPE_DIRECTORY &&
239 !create_directory(outfname)) {
240 printf("%s: Cannot create directory\n", outfname);
245 * Now get the list of filenames in the remote
248 sftp_register(req = fxp_opendir_send(fname));
249 rreq = sftp_find_request(pktin = sftp_recv());
251 dirhandle = fxp_opendir_recv(pktin, rreq);
254 printf("%s: unable to open directory: %s\n",
258 nnames = namesize = 0;
263 sftp_register(req = fxp_readdir_send(dirhandle));
264 rreq = sftp_find_request(pktin = sftp_recv());
266 names = fxp_readdir_recv(pktin, rreq);
269 if (fxp_error_type() == SSH_FX_EOF)
271 printf("%s: reading directory: %s\n", fname, fxp_error());
275 if (names->nnames == 0) {
276 fxp_free_names(names);
279 if (nnames + names->nnames >= namesize) {
280 namesize += names->nnames + 128;
281 ournames = sresize(ournames, namesize, struct fxp_name *);
283 for (i = 0; i < names->nnames; i++)
284 if (strcmp(names->names[i].filename, ".") &&
285 strcmp(names->names[i].filename, "..")) {
286 if (!vet_filename(names->names[i].filename)) {
287 printf("ignoring potentially dangerous server-"
288 "supplied filename '%s'\n",
289 names->names[i].filename);
292 fxp_dup_name(&names->names[i]);
295 fxp_free_names(names);
297 sftp_register(req = fxp_close_send(dirhandle));
298 rreq = sftp_find_request(pktin = sftp_recv());
300 fxp_close_recv(pktin, rreq);
303 * Sort the names into a clear order. This ought to
304 * make things more predictable when we're doing a
305 * reget of the same directory, just in case two
306 * readdirs on the same remote directory return a
309 qsort(ournames, nnames, sizeof(*ournames), sftp_name_compare);
312 * If we're in restart mode, find the last filename on
313 * this list that already exists. We may have to do a
314 * reget on _that_ file, but shouldn't have to do
315 * anything on the previous files.
317 * If none of them exists, of course, we start at 0.
324 nextoutfname = dir_file_cat(outfname,
325 ournames[i]->filename);
327 nextoutfname = dupstr(ournames[i]->filename);
328 ret = (file_type(nextoutfname) == FILE_TYPE_NONEXISTENT);
338 * Now we're ready to recurse. Starting at ournames[i]
339 * and continuing on to the end of the list, we
340 * construct a new source and target file name, and
341 * call sftp_get_file again.
343 for (; i < nnames; i++) {
344 char *nextfname, *nextoutfname;
347 nextfname = dupcat(fname, "/", ournames[i]->filename, NULL);
349 nextoutfname = dir_file_cat(outfname,
350 ournames[i]->filename);
352 nextoutfname = dupstr(ournames[i]->filename);
353 ret = sftp_get_file(nextfname, nextoutfname, recurse, restart);
354 restart = FALSE; /* after first partial file, do full */
358 for (i = 0; i < nnames; i++) {
359 fxp_free_name(ournames[i]);
367 * Done this recursion level. Free everything.
369 for (i = 0; i < nnames; i++) {
370 fxp_free_name(ournames[i]);
378 sftp_register(req = fxp_open_send(fname, SSH_FXF_READ));
379 rreq = sftp_find_request(pktin = sftp_recv());
381 fh = fxp_open_recv(pktin, rreq);
384 printf("%s: %s\n", fname, fxp_error());
389 fp = fopen(outfname, "rb+");
391 fp = fopen(outfname, "wb");
395 printf("local: unable to open %s\n", outfname);
397 sftp_register(req = fxp_close_send(fh));
398 rreq = sftp_find_request(pktin = sftp_recv());
400 fxp_close_recv(pktin, rreq);
407 fseek(fp, 0L, SEEK_END);
409 printf("reget: restarting at file position %ld\n", posn);
410 offset = uint64_make(0, posn);
412 offset = uint64_make(0, 0);
415 printf("remote:%s => local:%s\n", fname, outfname);
418 * FIXME: we can use FXP_FSTAT here to get the file size, and
419 * thus put up a progress bar.
422 xfer = xfer_download_init(fh, offset);
423 while (!xfer_done(xfer)) {
428 xfer_download_queue(xfer);
430 ret = xfer_download_gotpkt(xfer, pktin);
434 printf("error while reading: %s\n", fxp_error());
440 while (xfer_download_data(xfer, &vbuf, &len)) {
441 unsigned char *buf = (unsigned char *)vbuf;
445 wlen = fwrite(buf + wpos, 1, len - wpos, fp);
447 printf("error while writing local file\n");
449 xfer_set_error(xfer);
453 if (wpos < len) { /* we had an error */
455 xfer_set_error(xfer);
466 sftp_register(req = fxp_close_send(fh));
467 rreq = sftp_find_request(pktin = sftp_recv());
469 fxp_close_recv(pktin, rreq);
474 int sftp_put_file(char *fname, char *outfname, int recurse, int restart)
476 struct fxp_handle *fh;
477 struct fxp_xfer *xfer;
478 struct sftp_packet *pktin;
479 struct sftp_request *req, *rreq;
485 * In recursive mode, see if we're dealing with a directory.
486 * (If we're not in recursive mode, we need not even check: the
487 * subsequent fopen will return an error message.)
489 if (recurse && file_type(fname) == FILE_TYPE_DIRECTORY) {
490 struct fxp_attrs attrs;
492 int nnames, namesize;
493 char *name, **ournames;
498 * First, attempt to create the destination directory,
499 * unless it already exists.
501 sftp_register(req = fxp_stat_send(outfname));
502 rreq = sftp_find_request(pktin = sftp_recv());
504 result = fxp_stat_recv(pktin, rreq, &attrs);
506 !(attrs.flags & SSH_FILEXFER_ATTR_PERMISSIONS) ||
507 !(attrs.permissions & 0040000)) {
508 sftp_register(req = fxp_mkdir_send(outfname));
509 rreq = sftp_find_request(pktin = sftp_recv());
511 result = fxp_mkdir_recv(pktin, rreq);
514 printf("%s: create directory: %s\n",
515 outfname, fxp_error());
521 * Now get the list of filenames in the local directory.
523 nnames = namesize = 0;
526 dh = open_directory(fname);
528 printf("%s: unable to open directory\n", fname);
531 while ((name = read_filename(dh)) != NULL) {
532 if (nnames >= namesize) {
534 ournames = sresize(ournames, namesize, char *);
536 ournames[nnames++] = name;
541 * Sort the names into a clear order. This ought to make
542 * things more predictable when we're doing a reput of the
543 * same directory, just in case two readdirs on the same
544 * local directory return a different order.
546 qsort(ournames, nnames, sizeof(*ournames), bare_name_compare);
549 * If we're in restart mode, find the last filename on this
550 * list that already exists. We may have to do a reput on
551 * _that_ file, but shouldn't have to do anything on the
554 * If none of them exists, of course, we start at 0.
559 nextoutfname = dupcat(outfname, "/", ournames[i], NULL);
560 sftp_register(req = fxp_stat_send(nextoutfname));
561 rreq = sftp_find_request(pktin = sftp_recv());
563 result = fxp_stat_recv(pktin, rreq, &attrs);
573 * Now we're ready to recurse. Starting at ournames[i]
574 * and continuing on to the end of the list, we
575 * construct a new source and target file name, and
576 * call sftp_put_file again.
578 for (; i < nnames; i++) {
579 char *nextfname, *nextoutfname;
583 nextfname = dir_file_cat(fname, ournames[i]);
585 nextfname = dupstr(ournames[i]);
586 nextoutfname = dupcat(outfname, "/", ournames[i], NULL);
587 ret = sftp_put_file(nextfname, nextoutfname, recurse, restart);
588 restart = FALSE; /* after first partial file, do full */
592 for (i = 0; i < nnames; i++) {
601 * Done this recursion level. Free everything.
603 for (i = 0; i < nnames; i++) {
611 fp = fopen(fname, "rb");
613 printf("local: unable to open %s\n", fname);
617 sftp_register(req = fxp_open_send(outfname, SSH_FXF_WRITE));
619 sftp_register(req = fxp_open_send(outfname, SSH_FXF_WRITE |
620 SSH_FXF_CREAT | SSH_FXF_TRUNC));
622 rreq = sftp_find_request(pktin = sftp_recv());
624 fh = fxp_open_recv(pktin, rreq);
627 printf("%s: %s\n", outfname, fxp_error());
633 struct fxp_attrs attrs;
636 sftp_register(req = fxp_fstat_send(fh));
637 rreq = sftp_find_request(pktin = sftp_recv());
639 ret = fxp_fstat_recv(pktin, rreq, &attrs);
642 printf("read size of %s: %s\n", outfname, fxp_error());
645 if (!(attrs.flags & SSH_FILEXFER_ATTR_SIZE)) {
646 printf("read size of %s: size was not given\n", outfname);
650 uint64_decimal(offset, decbuf);
651 printf("reput: restarting at file position %s\n", decbuf);
652 if (uint64_compare(offset, uint64_make(0, LONG_MAX)) > 0) {
653 printf("reput: remote file is larger than we can deal with\n");
656 if (fseek(fp, offset.lo, SEEK_SET) != 0)
657 fseek(fp, 0, SEEK_END); /* *shrug* */
659 offset = uint64_make(0, 0);
662 printf("local:%s => remote:%s\n", fname, outfname);
665 * FIXME: we can use FXP_FSTAT here to get the file size, and
666 * thus put up a progress bar.
669 xfer = xfer_upload_init(fh, offset);
671 while ((!err && !eof) || !xfer_done(xfer)) {
675 while (xfer_upload_ready(xfer) && !err && !eof) {
676 len = fread(buffer, 1, sizeof(buffer), fp);
678 printf("error while reading local file\n");
680 } else if (len == 0) {
683 xfer_upload_data(xfer, buffer, len);
687 if (!xfer_done(xfer)) {
689 ret = xfer_upload_gotpkt(xfer, pktin);
691 printf("error while writing: %s\n", fxp_error());
699 sftp_register(req = fxp_close_send(fh));
700 rreq = sftp_find_request(pktin = sftp_recv());
702 fxp_close_recv(pktin, rreq);
709 /* ----------------------------------------------------------------------
710 * A remote wildcard matcher, providing a similar interface to the
711 * local one in psftp.h.
714 typedef struct SftpWildcardMatcher {
715 struct fxp_handle *dirh;
716 struct fxp_names *names;
718 char *wildcard, *prefix;
719 } SftpWildcardMatcher;
721 SftpWildcardMatcher *sftp_begin_wildcard_matching(char *name)
723 struct sftp_packet *pktin;
724 struct sftp_request *req, *rreq;
726 char *unwcdir, *tmpdir, *cdir;
728 SftpWildcardMatcher *swcm;
729 struct fxp_handle *dirh;
732 * We don't handle multi-level wildcards; so we expect to find
733 * a fully specified directory part, followed by a wildcard
736 wildcard = stripslashes(name, 0);
738 unwcdir = dupstr(name);
739 len = wildcard - name;
741 if (len > 0 && unwcdir[len-1] == '/')
742 unwcdir[len-1] = '\0';
743 tmpdir = snewn(1 + len, char);
744 check = wc_unescape(tmpdir, unwcdir);
748 printf("Multiple-level wildcards are not supported\n");
753 cdir = canonify(unwcdir);
755 sftp_register(req = fxp_opendir_send(cdir));
756 rreq = sftp_find_request(pktin = sftp_recv());
758 dirh = fxp_opendir_recv(pktin, rreq);
761 swcm = snew(SftpWildcardMatcher);
764 swcm->wildcard = dupstr(wildcard);
765 swcm->prefix = unwcdir;
767 printf("Unable to open %s: %s\n", cdir, fxp_error());
777 char *sftp_wildcard_get_filename(SftpWildcardMatcher *swcm)
779 struct fxp_name *name;
780 struct sftp_packet *pktin;
781 struct sftp_request *req, *rreq;
784 if (swcm->names && swcm->namepos >= swcm->names->nnames) {
785 fxp_free_names(swcm->names);
790 sftp_register(req = fxp_readdir_send(swcm->dirh));
791 rreq = sftp_find_request(pktin = sftp_recv());
793 swcm->names = fxp_readdir_recv(pktin, rreq);
796 if (fxp_error_type() != SSH_FX_EOF)
797 printf("%s: reading directory: %s\n", swcm->prefix,
805 assert(swcm->names && swcm->namepos < swcm->names->nnames);
807 name = &swcm->names->names[swcm->namepos++];
809 if (!strcmp(name->filename, ".") || !strcmp(name->filename, ".."))
810 continue; /* expected bad filenames */
812 if (!vet_filename(name->filename)) {
813 printf("ignoring potentially dangerous server-"
814 "supplied filename '%s'\n", name->filename);
815 continue; /* unexpected bad filename */
818 if (!wc_match(swcm->wildcard, name->filename))
819 continue; /* doesn't match the wildcard */
822 * We have a working filename. Return it.
824 return dupprintf("%s%s%s", swcm->prefix,
826 swcm->prefix[strlen(swcm->prefix)-1]=='/' ?
832 void sftp_finish_wildcard_matching(SftpWildcardMatcher *swcm)
834 struct sftp_packet *pktin;
835 struct sftp_request *req, *rreq;
837 sftp_register(req = fxp_close_send(swcm->dirh));
838 rreq = sftp_find_request(pktin = sftp_recv());
840 fxp_close_recv(pktin, rreq);
843 fxp_free_names(swcm->names);
846 sfree(swcm->wildcard);
852 * General function to match a potential wildcard in a filename
853 * argument and iterate over every matching file. Used in several
854 * PSFTP commands (rmdir, rm, chmod, mv).
856 int wildcard_iterate(char *filename, int (*func)(void *, char *), void *ctx)
858 char *unwcfname, *newname, *cname;
861 unwcfname = snewn(strlen(filename)+1, char);
862 is_wc = !wc_unescape(unwcfname, filename);
865 SftpWildcardMatcher *swcm = sftp_begin_wildcard_matching(filename);
874 while ( (newname = sftp_wildcard_get_filename(swcm)) != NULL ) {
875 cname = canonify(newname);
877 printf("%s: %s\n", newname, fxp_error());
881 ret &= func(ctx, cname);
886 /* Politely warn the user that nothing matched. */
887 printf("%s: nothing matched\n", filename);
890 sftp_finish_wildcard_matching(swcm);
892 cname = canonify(unwcfname);
894 printf("%s: %s\n", filename, fxp_error());
897 ret = func(ctx, cname);
906 * Handy helper function.
908 int is_wildcard(char *name)
910 char *unwcfname = snewn(strlen(name)+1, char);
911 int is_wc = !wc_unescape(unwcfname, name);
916 /* ----------------------------------------------------------------------
917 * Actual sftp commands.
919 struct sftp_command {
921 int nwords, wordssize;
922 int (*obey) (struct sftp_command *); /* returns <0 to quit */
925 int sftp_cmd_null(struct sftp_command *cmd)
927 return 1; /* success */
930 int sftp_cmd_unknown(struct sftp_command *cmd)
932 printf("psftp: unknown command \"%s\"\n", cmd->words[0]);
933 return 0; /* failure */
936 int sftp_cmd_quit(struct sftp_command *cmd)
941 int sftp_cmd_close(struct sftp_command *cmd)
948 if (back != NULL && back->socket(backhandle) != NULL) {
950 back->special(backhandle, TS_EOF);
951 sftp_recvdata(&ch, 1);
959 * List a directory. If no arguments are given, list pwd; otherwise
960 * list the directory given in words[1].
962 int sftp_cmd_ls(struct sftp_command *cmd)
964 struct fxp_handle *dirh;
965 struct fxp_names *names;
966 struct fxp_name **ournames;
967 int nnames, namesize;
968 char *dir, *cdir, *unwcdir, *wildcard;
969 struct sftp_packet *pktin;
970 struct sftp_request *req, *rreq;
983 unwcdir = snewn(1 + strlen(dir), char);
984 if (wc_unescape(unwcdir, dir)) {
991 wildcard = stripslashes(dir, 0);
992 unwcdir = dupstr(dir);
993 len = wildcard - dir;
995 if (len > 0 && unwcdir[len-1] == '/')
996 unwcdir[len-1] = '\0';
997 tmpdir = snewn(1 + len, char);
998 check = wc_unescape(tmpdir, unwcdir);
1001 printf("Multiple-level wildcards are not supported\n");
1008 cdir = canonify(dir);
1010 printf("%s: %s\n", dir, fxp_error());
1015 printf("Listing directory %s\n", cdir);
1017 sftp_register(req = fxp_opendir_send(cdir));
1018 rreq = sftp_find_request(pktin = sftp_recv());
1019 assert(rreq == req);
1020 dirh = fxp_opendir_recv(pktin, rreq);
1023 printf("Unable to open %s: %s\n", dir, fxp_error());
1025 nnames = namesize = 0;
1030 sftp_register(req = fxp_readdir_send(dirh));
1031 rreq = sftp_find_request(pktin = sftp_recv());
1032 assert(rreq == req);
1033 names = fxp_readdir_recv(pktin, rreq);
1035 if (names == NULL) {
1036 if (fxp_error_type() == SSH_FX_EOF)
1038 printf("Reading directory %s: %s\n", dir, fxp_error());
1041 if (names->nnames == 0) {
1042 fxp_free_names(names);
1046 if (nnames + names->nnames >= namesize) {
1047 namesize += names->nnames + 128;
1048 ournames = sresize(ournames, namesize, struct fxp_name *);
1051 for (i = 0; i < names->nnames; i++)
1052 if (!wildcard || wc_match(wildcard, names->names[i].filename))
1053 ournames[nnames++] = fxp_dup_name(&names->names[i]);
1055 fxp_free_names(names);
1057 sftp_register(req = fxp_close_send(dirh));
1058 rreq = sftp_find_request(pktin = sftp_recv());
1059 assert(rreq == req);
1060 fxp_close_recv(pktin, rreq);
1063 * Now we have our filenames. Sort them by actual file
1064 * name, and then output the longname parts.
1066 qsort(ournames, nnames, sizeof(*ournames), sftp_name_compare);
1071 for (i = 0; i < nnames; i++) {
1072 printf("%s\n", ournames[i]->longname);
1073 fxp_free_name(ournames[i]);
1085 * Change directories. We do this by canonifying the new name, then
1086 * trying to OPENDIR it. Only if that succeeds do we set the new pwd.
1088 int sftp_cmd_cd(struct sftp_command *cmd)
1090 struct fxp_handle *dirh;
1091 struct sftp_packet *pktin;
1092 struct sftp_request *req, *rreq;
1100 if (cmd->nwords < 2)
1101 dir = dupstr(homedir);
1103 dir = canonify(cmd->words[1]);
1106 printf("%s: %s\n", dir, fxp_error());
1110 sftp_register(req = fxp_opendir_send(dir));
1111 rreq = sftp_find_request(pktin = sftp_recv());
1112 assert(rreq == req);
1113 dirh = fxp_opendir_recv(pktin, rreq);
1116 printf("Directory %s: %s\n", dir, fxp_error());
1121 sftp_register(req = fxp_close_send(dirh));
1122 rreq = sftp_find_request(pktin = sftp_recv());
1123 assert(rreq == req);
1124 fxp_close_recv(pktin, rreq);
1128 printf("Remote directory is now %s\n", pwd);
1134 * Print current directory. Easy as pie.
1136 int sftp_cmd_pwd(struct sftp_command *cmd)
1143 printf("Remote directory is %s\n", pwd);
1148 * Get a file and save it at the local end. We have three very
1149 * similar commands here. The basic one is `get'; `reget' differs
1150 * in that it checks for the existence of the destination file and
1151 * starts from where a previous aborted transfer left off; `mget'
1152 * differs in that it interprets all its arguments as files to
1153 * transfer (never as a different local name for a remote file) and
1154 * can handle wildcards.
1156 int sftp_general_get(struct sftp_command *cmd, int restart, int multiple)
1158 char *fname, *unwcfname, *origfname, *origwfname, *outfname;
1160 int recurse = FALSE;
1168 while (i < cmd->nwords && cmd->words[i][0] == '-') {
1169 if (!strcmp(cmd->words[i], "--")) {
1170 /* finish processing options */
1173 } else if (!strcmp(cmd->words[i], "-r")) {
1176 printf("%s: unrecognised option '%s'\n", cmd->words[0], cmd->words[i]);
1182 if (i >= cmd->nwords) {
1183 printf("%s: expects a filename\n", cmd->words[0]);
1189 SftpWildcardMatcher *swcm;
1191 origfname = cmd->words[i++];
1192 unwcfname = snewn(strlen(origfname)+1, char);
1194 if (multiple && !wc_unescape(unwcfname, origfname)) {
1195 swcm = sftp_begin_wildcard_matching(origfname);
1200 origwfname = sftp_wildcard_get_filename(swcm);
1202 /* Politely warn the user that nothing matched. */
1203 printf("%s: nothing matched\n", origfname);
1204 sftp_finish_wildcard_matching(swcm);
1209 origwfname = origfname;
1213 while (origwfname) {
1214 fname = canonify(origwfname);
1217 printf("%s: %s\n", origwfname, fxp_error());
1222 if (!multiple && i < cmd->nwords)
1223 outfname = cmd->words[i++];
1225 outfname = stripslashes(origwfname, 0);
1227 ret = sftp_get_file(fname, outfname, recurse, restart);
1233 origwfname = sftp_wildcard_get_filename(swcm);
1240 sftp_finish_wildcard_matching(swcm);
1244 } while (multiple && i < cmd->nwords);
1248 int sftp_cmd_get(struct sftp_command *cmd)
1250 return sftp_general_get(cmd, 0, 0);
1252 int sftp_cmd_mget(struct sftp_command *cmd)
1254 return sftp_general_get(cmd, 0, 1);
1256 int sftp_cmd_reget(struct sftp_command *cmd)
1258 return sftp_general_get(cmd, 1, 0);
1262 * Send a file and store it at the remote end. We have three very
1263 * similar commands here. The basic one is `put'; `reput' differs
1264 * in that it checks for the existence of the destination file and
1265 * starts from where a previous aborted transfer left off; `mput'
1266 * differs in that it interprets all its arguments as files to
1267 * transfer (never as a different remote name for a local file) and
1268 * can handle wildcards.
1270 int sftp_general_put(struct sftp_command *cmd, int restart, int multiple)
1272 char *fname, *wfname, *origoutfname, *outfname;
1274 int recurse = FALSE;
1282 while (i < cmd->nwords && cmd->words[i][0] == '-') {
1283 if (!strcmp(cmd->words[i], "--")) {
1284 /* finish processing options */
1287 } else if (!strcmp(cmd->words[i], "-r")) {
1290 printf("%s: unrecognised option '%s'\n", cmd->words[0], cmd->words[i]);
1296 if (i >= cmd->nwords) {
1297 printf("%s: expects a filename\n", cmd->words[0]);
1303 WildcardMatcher *wcm;
1304 fname = cmd->words[i++];
1306 if (multiple && test_wildcard(fname, FALSE) == WCTYPE_WILDCARD) {
1307 wcm = begin_wildcard_matching(fname);
1308 wfname = wildcard_get_filename(wcm);
1310 /* Politely warn the user that nothing matched. */
1311 printf("%s: nothing matched\n", fname);
1312 finish_wildcard_matching(wcm);
1321 if (!multiple && i < cmd->nwords)
1322 origoutfname = cmd->words[i++];
1324 origoutfname = stripslashes(wfname, 1);
1326 outfname = canonify(origoutfname);
1328 printf("%s: %s\n", origoutfname, fxp_error());
1331 finish_wildcard_matching(wcm);
1335 ret = sftp_put_file(wfname, outfname, recurse, restart);
1340 wfname = wildcard_get_filename(wcm);
1347 finish_wildcard_matching(wcm);
1352 } while (multiple && i < cmd->nwords);
1356 int sftp_cmd_put(struct sftp_command *cmd)
1358 return sftp_general_put(cmd, 0, 0);
1360 int sftp_cmd_mput(struct sftp_command *cmd)
1362 return sftp_general_put(cmd, 0, 1);
1364 int sftp_cmd_reput(struct sftp_command *cmd)
1366 return sftp_general_put(cmd, 1, 0);
1369 int sftp_cmd_mkdir(struct sftp_command *cmd)
1372 struct sftp_packet *pktin;
1373 struct sftp_request *req, *rreq;
1382 if (cmd->nwords < 2) {
1383 printf("mkdir: expects a directory\n");
1388 for (i = 1; i < cmd->nwords; i++) {
1389 dir = canonify(cmd->words[i]);
1391 printf("%s: %s\n", dir, fxp_error());
1395 sftp_register(req = fxp_mkdir_send(dir));
1396 rreq = sftp_find_request(pktin = sftp_recv());
1397 assert(rreq == req);
1398 result = fxp_mkdir_recv(pktin, rreq);
1401 printf("mkdir %s: %s\n", dir, fxp_error());
1404 printf("mkdir %s: OK\n", dir);
1412 static int sftp_action_rmdir(void *vctx, char *dir)
1414 struct sftp_packet *pktin;
1415 struct sftp_request *req, *rreq;
1418 sftp_register(req = fxp_rmdir_send(dir));
1419 rreq = sftp_find_request(pktin = sftp_recv());
1420 assert(rreq == req);
1421 result = fxp_rmdir_recv(pktin, rreq);
1424 printf("rmdir %s: %s\n", dir, fxp_error());
1428 printf("rmdir %s: OK\n", dir);
1433 int sftp_cmd_rmdir(struct sftp_command *cmd)
1442 if (cmd->nwords < 2) {
1443 printf("rmdir: expects a directory\n");
1448 for (i = 1; i < cmd->nwords; i++)
1449 ret &= wildcard_iterate(cmd->words[i], sftp_action_rmdir, NULL);
1454 static int sftp_action_rm(void *vctx, char *fname)
1456 struct sftp_packet *pktin;
1457 struct sftp_request *req, *rreq;
1460 sftp_register(req = fxp_remove_send(fname));
1461 rreq = sftp_find_request(pktin = sftp_recv());
1462 assert(rreq == req);
1463 result = fxp_remove_recv(pktin, rreq);
1466 printf("rm %s: %s\n", fname, fxp_error());
1470 printf("rm %s: OK\n", fname);
1475 int sftp_cmd_rm(struct sftp_command *cmd)
1484 if (cmd->nwords < 2) {
1485 printf("rm: expects a filename\n");
1490 for (i = 1; i < cmd->nwords; i++)
1491 ret &= wildcard_iterate(cmd->words[i], sftp_action_rm, NULL);
1496 static int check_is_dir(char *dstfname)
1498 struct sftp_packet *pktin;
1499 struct sftp_request *req, *rreq;
1500 struct fxp_attrs attrs;
1503 sftp_register(req = fxp_stat_send(dstfname));
1504 rreq = sftp_find_request(pktin = sftp_recv());
1505 assert(rreq == req);
1506 result = fxp_stat_recv(pktin, rreq, &attrs);
1509 (attrs.flags & SSH_FILEXFER_ATTR_PERMISSIONS) &&
1510 (attrs.permissions & 0040000))
1516 struct sftp_context_mv {
1521 static int sftp_action_mv(void *vctx, char *srcfname)
1523 struct sftp_context_mv *ctx = (struct sftp_context_mv *)vctx;
1524 struct sftp_packet *pktin;
1525 struct sftp_request *req, *rreq;
1527 char *finalfname, *newcanon = NULL;
1530 if (ctx->dest_is_dir) {
1534 p = srcfname + strlen(srcfname);
1535 while (p > srcfname && p[-1] != '/') p--;
1536 newname = dupcat(ctx->dstfname, "/", p, NULL);
1537 newcanon = canonify(newname);
1539 printf("%s: %s\n", newname, fxp_error());
1545 finalfname = newcanon;
1547 finalfname = ctx->dstfname;
1550 sftp_register(req = fxp_rename_send(srcfname, finalfname));
1551 rreq = sftp_find_request(pktin = sftp_recv());
1552 assert(rreq == req);
1553 result = fxp_rename_recv(pktin, rreq);
1555 error = result ? NULL : fxp_error();
1558 printf("mv %s %s: %s\n", srcfname, finalfname, error);
1561 printf("%s -> %s\n", srcfname, finalfname);
1569 int sftp_cmd_mv(struct sftp_command *cmd)
1571 struct sftp_context_mv actx, *ctx = &actx;
1579 if (cmd->nwords < 3) {
1580 printf("mv: expects two filenames\n");
1584 ctx->dstfname = canonify(cmd->words[cmd->nwords-1]);
1585 if (!ctx->dstfname) {
1586 printf("%s: %s\n", ctx->dstfname, fxp_error());
1591 * If there's more than one source argument, or one source
1592 * argument which is a wildcard, we _require_ that the
1593 * destination is a directory.
1595 ctx->dest_is_dir = check_is_dir(ctx->dstfname);
1596 if ((cmd->nwords > 3 || is_wildcard(cmd->words[1])) && !ctx->dest_is_dir) {
1597 printf("mv: multiple or wildcard arguments require the destination"
1598 " to be a directory\n");
1599 sfree(ctx->dstfname);
1604 * Now iterate over the source arguments.
1607 for (i = 1; i < cmd->nwords-1; i++)
1608 ret &= wildcard_iterate(cmd->words[i], sftp_action_mv, ctx);
1610 sfree(ctx->dstfname);
1614 struct sftp_context_chmod {
1615 unsigned attrs_clr, attrs_xor;
1618 static int sftp_action_chmod(void *vctx, char *fname)
1620 struct fxp_attrs attrs;
1621 struct sftp_packet *pktin;
1622 struct sftp_request *req, *rreq;
1624 unsigned oldperms, newperms;
1625 struct sftp_context_chmod *ctx = (struct sftp_context_chmod *)vctx;
1627 sftp_register(req = fxp_stat_send(fname));
1628 rreq = sftp_find_request(pktin = sftp_recv());
1629 assert(rreq == req);
1630 result = fxp_stat_recv(pktin, rreq, &attrs);
1632 if (!result || !(attrs.flags & SSH_FILEXFER_ATTR_PERMISSIONS)) {
1633 printf("get attrs for %s: %s\n", fname,
1634 result ? "file permissions not provided" : fxp_error());
1638 attrs.flags = SSH_FILEXFER_ATTR_PERMISSIONS; /* perms _only_ */
1639 oldperms = attrs.permissions & 07777;
1640 attrs.permissions &= ~ctx->attrs_clr;
1641 attrs.permissions ^= ctx->attrs_xor;
1642 newperms = attrs.permissions & 07777;
1644 if (oldperms == newperms)
1645 return 1; /* no need to do anything! */
1647 sftp_register(req = fxp_setstat_send(fname, attrs));
1648 rreq = sftp_find_request(pktin = sftp_recv());
1649 assert(rreq == req);
1650 result = fxp_setstat_recv(pktin, rreq);
1653 printf("set attrs for %s: %s\n", fname, fxp_error());
1657 printf("%s: %04o -> %04o\n", fname, oldperms, newperms);
1662 int sftp_cmd_chmod(struct sftp_command *cmd)
1666 struct sftp_context_chmod actx, *ctx = &actx;
1673 if (cmd->nwords < 3) {
1674 printf("chmod: expects a mode specifier and a filename\n");
1679 * Attempt to parse the mode specifier in cmd->words[1]. We
1680 * don't support the full horror of Unix chmod; instead we
1681 * support a much simpler syntax in which the user can either
1682 * specify an octal number, or a comma-separated sequence of
1683 * [ugoa]*[-+=][rwxst]+. (The initial [ugoa] sequence may
1684 * _only_ be omitted if the only attribute mentioned is t,
1685 * since all others require a user/group/other specification.
1686 * Additionally, the s attribute may not be specified for any
1687 * [ugoa] specifications other than exactly u or exactly g.
1689 ctx->attrs_clr = ctx->attrs_xor = 0;
1690 mode = cmd->words[1];
1691 if (mode[0] >= '0' && mode[0] <= '9') {
1692 if (mode[strspn(mode, "01234567")]) {
1693 printf("chmod: numeric file modes should"
1694 " contain digits 0-7 only\n");
1697 ctx->attrs_clr = 07777;
1698 sscanf(mode, "%o", &ctx->attrs_xor);
1699 ctx->attrs_xor &= ctx->attrs_clr;
1702 char *modebegin = mode;
1703 unsigned subset, perms;
1707 while (*mode && *mode != ',' &&
1708 *mode != '+' && *mode != '-' && *mode != '=') {
1710 case 'u': subset |= 04700; break; /* setuid, user perms */
1711 case 'g': subset |= 02070; break; /* setgid, group perms */
1712 case 'o': subset |= 00007; break; /* just other perms */
1713 case 'a': subset |= 06777; break; /* all of the above */
1715 printf("chmod: file mode '%.*s' contains unrecognised"
1716 " user/group/other specifier '%c'\n",
1717 (int)strcspn(modebegin, ","), modebegin, *mode);
1722 if (!*mode || *mode == ',') {
1723 printf("chmod: file mode '%.*s' is incomplete\n",
1724 (int)strcspn(modebegin, ","), modebegin);
1728 if (!*mode || *mode == ',') {
1729 printf("chmod: file mode '%.*s' is incomplete\n",
1730 (int)strcspn(modebegin, ","), modebegin);
1734 while (*mode && *mode != ',') {
1736 case 'r': perms |= 00444; break;
1737 case 'w': perms |= 00222; break;
1738 case 'x': perms |= 00111; break;
1739 case 't': perms |= 01000; subset |= 01000; break;
1741 if ((subset & 06777) != 04700 &&
1742 (subset & 06777) != 02070) {
1743 printf("chmod: file mode '%.*s': set[ug]id bit should"
1744 " be used with exactly one of u or g only\n",
1745 (int)strcspn(modebegin, ","), modebegin);
1751 printf("chmod: file mode '%.*s' contains unrecognised"
1752 " permission specifier '%c'\n",
1753 (int)strcspn(modebegin, ","), modebegin, *mode);
1758 if (!(subset & 06777) && (perms &~ subset)) {
1759 printf("chmod: file mode '%.*s' contains no user/group/other"
1760 " specifier and permissions other than 't' \n",
1761 (int)strcspn(modebegin, ","), modebegin);
1767 ctx->attrs_clr |= perms;
1768 ctx->attrs_xor |= perms;
1771 ctx->attrs_clr |= perms;
1772 ctx->attrs_xor &= ~perms;
1775 ctx->attrs_clr |= subset;
1776 ctx->attrs_xor |= perms;
1779 if (*mode) mode++; /* eat comma */
1784 for (i = 2; i < cmd->nwords; i++)
1785 ret &= wildcard_iterate(cmd->words[i], sftp_action_chmod, ctx);
1790 static int sftp_cmd_open(struct sftp_command *cmd)
1795 printf("psftp: already connected\n");
1799 if (cmd->nwords < 2) {
1800 printf("open: expects a host name\n");
1804 if (cmd->nwords > 2) {
1805 portnumber = atoi(cmd->words[2]);
1806 if (portnumber == 0) {
1807 printf("open: invalid port number\n");
1813 if (psftp_connect(cmd->words[1], NULL, portnumber)) {
1814 back = NULL; /* connection is already closed */
1815 return -1; /* this is fatal */
1821 static int sftp_cmd_lcd(struct sftp_command *cmd)
1823 char *currdir, *errmsg;
1825 if (cmd->nwords < 2) {
1826 printf("lcd: expects a local directory name\n");
1830 errmsg = psftp_lcd(cmd->words[1]);
1832 printf("lcd: unable to change directory: %s\n", errmsg);
1837 currdir = psftp_getcwd();
1838 printf("New local directory is %s\n", currdir);
1844 static int sftp_cmd_lpwd(struct sftp_command *cmd)
1848 currdir = psftp_getcwd();
1849 printf("Current local directory is %s\n", currdir);
1855 static int sftp_cmd_pling(struct sftp_command *cmd)
1859 exitcode = system(cmd->words[1]);
1860 return (exitcode == 0);
1863 static int sftp_cmd_help(struct sftp_command *cmd);
1865 static struct sftp_cmd_lookup {
1868 * For help purposes, there are two kinds of command:
1870 * - primary commands, in which `longhelp' is non-NULL. In
1871 * this case `shorthelp' is descriptive text, and `longhelp'
1872 * is longer descriptive text intended to be printed after
1875 * - alias commands, in which `longhelp' is NULL. In this case
1876 * `shorthelp' is the name of a primary command, which
1877 * contains the help that should double up for this command.
1879 int listed; /* do we list this in primary help? */
1882 int (*obey) (struct sftp_command *);
1885 * List of sftp commands. This is binary-searched so it MUST be
1889 "!", TRUE, "run a local command",
1891 /* FIXME: this example is crap for non-Windows. */
1892 " Runs a local command. For example, \"!del myfile\".\n",
1896 "bye", TRUE, "finish your SFTP session",
1898 " Terminates your SFTP session and quits the PSFTP program.\n",
1902 "cd", TRUE, "change your remote working directory",
1903 " [ <new working directory> ]\n"
1904 " Change the remote working directory for your SFTP session.\n"
1905 " If a new working directory is not supplied, you will be\n"
1906 " returned to your home directory.\n",
1910 "chmod", TRUE, "change file permissions and modes",
1911 " <modes> <filename-or-wildcard> [ <filename-or-wildcard>... ]\n"
1912 " Change the file permissions on one or more remote files or\n"
1914 " <modes> can be any octal Unix permission specifier.\n"
1915 " Alternatively, <modes> can include the following modifiers:\n"
1916 " u+r make file readable by owning user\n"
1917 " u+w make file writable by owning user\n"
1918 " u+x make file executable by owning user\n"
1919 " u-r make file not readable by owning user\n"
1920 " [also u-w, u-x]\n"
1921 " g+r make file readable by members of owning group\n"
1922 " [also g+w, g+x, g-r, g-w, g-x]\n"
1923 " o+r make file readable by all other users\n"
1924 " [also o+w, o+x, o-r, o-w, o-x]\n"
1925 " a+r make file readable by absolutely everybody\n"
1926 " [also a+w, a+x, a-r, a-w, a-x]\n"
1927 " u+s enable the Unix set-user-ID bit\n"
1928 " u-s disable the Unix set-user-ID bit\n"
1929 " g+s enable the Unix set-group-ID bit\n"
1930 " g-s disable the Unix set-group-ID bit\n"
1931 " +t enable the Unix \"sticky bit\"\n"
1932 " You can give more than one modifier for the same user (\"g-rwx\"), and\n"
1933 " more than one user for the same modifier (\"ug+w\"). You can\n"
1934 " use commas to separate different modifiers (\"u+rwx,g+s\").\n",
1938 "close", TRUE, "finish your SFTP session but do not quit PSFTP",
1940 " Terminates your SFTP session, but does not quit the PSFTP\n"
1941 " program. You can then use \"open\" to start another SFTP\n"
1942 " session, to the same server or to a different one.\n",
1946 "del", TRUE, "delete files on the remote server",
1947 " <filename-or-wildcard> [ <filename-or-wildcard>... ]\n"
1948 " Delete a file or files from the server.\n",
1952 "delete", FALSE, "del", NULL, sftp_cmd_rm
1955 "dir", TRUE, "list remote files",
1956 " [ <directory-name> ]/[ <wildcard> ]\n"
1957 " List the contents of a specified directory on the server.\n"
1958 " If <directory-name> is not given, the current working directory\n"
1960 " If <wildcard> is given, it is treated as a set of files to\n"
1961 " list; otherwise, all files are listed.\n",
1965 "exit", TRUE, "bye", NULL, sftp_cmd_quit
1968 "get", TRUE, "download a file from the server to your local machine",
1969 " [ -r ] [ -- ] <filename> [ <local-filename> ]\n"
1970 " Downloads a file on the server and stores it locally under\n"
1971 " the same name, or under a different one if you supply the\n"
1972 " argument <local-filename>.\n"
1973 " If -r specified, recursively fetch a directory.\n",
1977 "help", TRUE, "give help",
1978 " [ <command> [ <command> ... ] ]\n"
1979 " Give general help if no commands are specified.\n"
1980 " If one or more commands are specified, give specific help on\n"
1981 " those particular commands.\n",
1985 "lcd", TRUE, "change local working directory",
1986 " <local-directory-name>\n"
1987 " Change the local working directory of the PSFTP program (the\n"
1988 " default location where the \"get\" command will save files).\n",
1992 "lpwd", TRUE, "print local working directory",
1994 " Print the local working directory of the PSFTP program (the\n"
1995 " default location where the \"get\" command will save files).\n",
1999 "ls", TRUE, "dir", NULL,
2003 "mget", TRUE, "download multiple files at once",
2004 " [ -r ] [ -- ] <filename-or-wildcard> [ <filename-or-wildcard>... ]\n"
2005 " Downloads many files from the server, storing each one under\n"
2006 " the same name it has on the server side. You can use wildcards\n"
2007 " such as \"*.c\" to specify lots of files at once.\n"
2008 " If -r specified, recursively fetch files and directories.\n",
2012 "mkdir", TRUE, "create directories on the remote server",
2013 " <directory-name> [ <directory-name>... ]\n"
2014 " Creates directories with the given names on the server.\n",
2018 "mput", TRUE, "upload multiple files at once",
2019 " [ -r ] [ -- ] <filename-or-wildcard> [ <filename-or-wildcard>... ]\n"
2020 " Uploads many files to the server, storing each one under the\n"
2021 " same name it has on the client side. You can use wildcards\n"
2022 " such as \"*.c\" to specify lots of files at once.\n"
2023 " If -r specified, recursively store files and directories.\n",
2027 "mv", TRUE, "move or rename file(s) on the remote server",
2028 " <source> [ <source>... ] <destination>\n"
2029 " Moves or renames <source>(s) on the server to <destination>,\n"
2030 " also on the server.\n"
2031 " If <destination> specifies an existing directory, then <source>\n"
2032 " may be a wildcard, and multiple <source>s may be given; all\n"
2033 " source files are moved into <destination>.\n"
2034 " Otherwise, <source> must specify a single file, which is moved\n"
2035 " or renamed so that it is accessible under the name <destination>.\n",
2039 "open", TRUE, "connect to a host",
2040 " [<user>@]<hostname> [<port>]\n"
2041 " Establishes an SFTP connection to a given host. Only usable\n"
2042 " when you are not already connected to a server.\n",
2046 "put", TRUE, "upload a file from your local machine to the server",
2047 " [ -r ] [ -- ] <filename> [ <remote-filename> ]\n"
2048 " Uploads a file to the server and stores it there under\n"
2049 " the same name, or under a different one if you supply the\n"
2050 " argument <remote-filename>.\n"
2051 " If -r specified, recursively store a directory.\n",
2055 "pwd", TRUE, "print your remote working directory",
2057 " Print the current remote working directory for your SFTP session.\n",
2061 "quit", TRUE, "bye", NULL,
2065 "reget", TRUE, "continue downloading files",
2066 " [ -r ] [ -- ] <filename> [ <local-filename> ]\n"
2067 " Works exactly like the \"get\" command, but the local file\n"
2068 " must already exist. The download will begin at the end of the\n"
2069 " file. This is for resuming a download that was interrupted.\n"
2070 " If -r specified, resume interrupted \"get -r\".\n",
2074 "ren", TRUE, "mv", NULL,
2078 "rename", FALSE, "mv", NULL,
2082 "reput", TRUE, "continue uploading files",
2083 " [ -r ] [ -- ] <filename> [ <remote-filename> ]\n"
2084 " Works exactly like the \"put\" command, but the remote file\n"
2085 " must already exist. The upload will begin at the end of the\n"
2086 " file. This is for resuming an upload that was interrupted.\n"
2087 " If -r specified, resume interrupted \"put -r\".\n",
2091 "rm", TRUE, "del", NULL,
2095 "rmdir", TRUE, "remove directories on the remote server",
2096 " <directory-name> [ <directory-name>... ]\n"
2097 " Removes the directory with the given name on the server.\n"
2098 " The directory will not be removed unless it is empty.\n"
2099 " Wildcards may be used to specify multiple directories.\n",
2104 const struct sftp_cmd_lookup *lookup_command(char *name)
2109 j = sizeof(sftp_lookup) / sizeof(*sftp_lookup);
2112 cmp = strcmp(name, sftp_lookup[k].name);
2118 return &sftp_lookup[k];
2124 static int sftp_cmd_help(struct sftp_command *cmd)
2127 if (cmd->nwords == 1) {
2129 * Give short help on each command.
2133 for (i = 0; i < sizeof(sftp_lookup) / sizeof(*sftp_lookup); i++) {
2135 if (!sftp_lookup[i].listed)
2137 len = strlen(sftp_lookup[i].name);
2141 for (i = 0; i < sizeof(sftp_lookup) / sizeof(*sftp_lookup); i++) {
2142 const struct sftp_cmd_lookup *lookup;
2143 if (!sftp_lookup[i].listed)
2145 lookup = &sftp_lookup[i];
2146 printf("%-*s", maxlen+2, lookup->name);
2147 if (lookup->longhelp == NULL)
2148 lookup = lookup_command(lookup->shorthelp);
2149 printf("%s\n", lookup->shorthelp);
2153 * Give long help on specific commands.
2155 for (i = 1; i < cmd->nwords; i++) {
2156 const struct sftp_cmd_lookup *lookup;
2157 lookup = lookup_command(cmd->words[i]);
2159 printf("help: %s: command not found\n", cmd->words[i]);
2161 printf("%s", lookup->name);
2162 if (lookup->longhelp == NULL)
2163 lookup = lookup_command(lookup->shorthelp);
2164 printf("%s", lookup->longhelp);
2171 /* ----------------------------------------------------------------------
2172 * Command line reading and parsing.
2174 struct sftp_command *sftp_getcmd(FILE *fp, int mode, int modeflags)
2177 struct sftp_command *cmd;
2181 cmd = snew(struct sftp_command);
2191 line = fgetline(fp);
2193 line = ssh_sftp_get_cmdline("psftp> ", back == NULL);
2196 if (!line || !*line) {
2197 cmd->obey = sftp_cmd_quit;
2198 if ((mode == 0) || (modeflags & 1))
2200 return cmd; /* eof */
2203 line[strcspn(line, "\r\n")] = '\0';
2205 if (modeflags & 1) {
2206 printf("%s\n", line);
2210 while (*p && (*p == ' ' || *p == '\t'))
2215 * Special case: the ! command. This is always parsed as
2216 * exactly two words: one containing the !, and the second
2217 * containing everything else on the line.
2219 cmd->nwords = cmd->wordssize = 2;
2220 cmd->words = sresize(cmd->words, cmd->wordssize, char *);
2221 cmd->words[0] = dupstr("!");
2222 cmd->words[1] = dupstr(p+1);
2226 * Parse the command line into words. The syntax is:
2227 * - double quotes are removed, but cause spaces within to be
2228 * treated as non-separating.
2229 * - a double-doublequote pair is a literal double quote, inside
2230 * _or_ outside quotes. Like this:
2232 * firstword "second word" "this has ""quotes"" in" and""this""
2238 * >this has "quotes" in<
2242 /* skip whitespace */
2243 while (*p && (*p == ' ' || *p == '\t'))
2245 /* mark start of word */
2246 q = r = p; /* q sits at start, r writes word */
2249 if (!quoting && (*p == ' ' || *p == '\t'))
2250 break; /* reached end of word */
2251 else if (*p == '"' && p[1] == '"')
2252 p += 2, *r++ = '"'; /* a literal quote */
2254 p++, quoting = !quoting;
2259 p++; /* skip over the whitespace */
2261 if (cmd->nwords >= cmd->wordssize) {
2262 cmd->wordssize = cmd->nwords + 16;
2263 cmd->words = sresize(cmd->words, cmd->wordssize, char *);
2265 cmd->words[cmd->nwords++] = dupstr(q);
2272 * Now parse the first word and assign a function.
2275 if (cmd->nwords == 0)
2276 cmd->obey = sftp_cmd_null;
2278 const struct sftp_cmd_lookup *lookup;
2279 lookup = lookup_command(cmd->words[0]);
2281 cmd->obey = sftp_cmd_unknown;
2283 cmd->obey = lookup->obey;
2289 static int do_sftp_init(void)
2291 struct sftp_packet *pktin;
2292 struct sftp_request *req, *rreq;
2295 * Do protocol initialisation.
2299 "Fatal: unable to initialise SFTP: %s\n", fxp_error());
2300 return 1; /* failure */
2304 * Find out where our home directory is.
2306 sftp_register(req = fxp_realpath_send("."));
2307 rreq = sftp_find_request(pktin = sftp_recv());
2308 assert(rreq == req);
2309 homedir = fxp_realpath_recv(pktin, rreq);
2313 "Warning: failed to resolve home directory: %s\n",
2315 homedir = dupstr(".");
2317 printf("Remote working directory is %s\n", homedir);
2319 pwd = dupstr(homedir);
2323 void do_sftp_cleanup()
2327 back->special(backhandle, TS_EOF);
2328 sftp_recvdata(&ch, 1);
2329 back->free(backhandle);
2330 sftp_cleanup_request();
2344 void do_sftp(int mode, int modeflags, char *batchfile)
2354 /* ------------------------------------------------------------------
2355 * Now we're ready to do Real Stuff.
2358 struct sftp_command *cmd;
2359 cmd = sftp_getcmd(NULL, 0, 0);
2362 ret = cmd->obey(cmd);
2365 for(i = 0; i < cmd->nwords; i++)
2366 sfree(cmd->words[i]);
2374 fp = fopen(batchfile, "r");
2376 printf("Fatal: unable to open %s\n", batchfile);
2380 struct sftp_command *cmd;
2381 cmd = sftp_getcmd(fp, mode, modeflags);
2384 ret = cmd->obey(cmd);
2388 if (!(modeflags & 2))
2397 /* ----------------------------------------------------------------------
2398 * Dirty bits: integration with PuTTY.
2401 static int verbose = 0;
2404 * Print an error message and perform a fatal exit.
2406 void fatalbox(char *fmt, ...)
2411 str = dupvprintf(fmt, ap);
2412 str2 = dupcat("Fatal: ", str, "\n", NULL);
2415 fputs(str2, stderr);
2420 void modalfatalbox(char *fmt, ...)
2425 str = dupvprintf(fmt, ap);
2426 str2 = dupcat("Fatal: ", str, "\n", NULL);
2429 fputs(str2, stderr);
2434 void connection_fatal(void *frontend, char *fmt, ...)
2439 str = dupvprintf(fmt, ap);
2440 str2 = dupcat("Fatal: ", str, "\n", NULL);
2443 fputs(str2, stderr);
2449 void ldisc_send(void *handle, char *buf, int len, int interactive)
2452 * This is only here because of the calls to ldisc_send(NULL,
2453 * 0) in ssh.c. Nothing in PSFTP actually needs to use the
2454 * ldisc as an ldisc. So if we get called with any real data, I
2455 * want to know about it.
2461 * In psftp, all agent requests should be synchronous, so this is a
2462 * never-called stub.
2464 void agent_schedule_callback(void (*callback)(void *, void *, int),
2465 void *callback_ctx, void *data, int len)
2467 assert(!"We shouldn't be here");
2471 * Receive a block of data from the SSH link. Block until all data
2474 * To do this, we repeatedly call the SSH protocol module, with our
2475 * own trap in from_backend() to catch the data that comes back. We
2476 * do this until we have enough data.
2479 static unsigned char *outptr; /* where to put the data */
2480 static unsigned outlen; /* how much data required */
2481 static unsigned char *pending = NULL; /* any spare data */
2482 static unsigned pendlen = 0, pendsize = 0; /* length and phys. size of buffer */
2483 int from_backend(void *frontend, int is_stderr, const char *data, int datalen)
2485 unsigned char *p = (unsigned char *) data;
2486 unsigned len = (unsigned) datalen;
2489 * stderr data is just spouted to local stderr and otherwise
2494 fwrite(data, 1, len, stderr);
2499 * If this is before the real session begins, just return.
2504 if ((outlen > 0) && (len > 0)) {
2505 unsigned used = outlen;
2508 memcpy(outptr, p, used);
2516 if (pendsize < pendlen + len) {
2517 pendsize = pendlen + len + 4096;
2518 pending = sresize(pending, pendsize, unsigned char);
2520 memcpy(pending + pendlen, p, len);
2526 int sftp_recvdata(char *buf, int len)
2528 outptr = (unsigned char *) buf;
2532 * See if the pending-input block contains some of what we
2536 unsigned pendused = pendlen;
2537 if (pendused > outlen)
2539 memcpy(outptr, pending, pendused);
2540 memmove(pending, pending + pendused, pendlen - pendused);
2543 pendlen -= pendused;
2553 while (outlen > 0) {
2554 if (ssh_sftp_loop_iteration() < 0)
2555 return 0; /* doom */
2560 int sftp_senddata(char *buf, int len)
2562 back->send(backhandle, buf, len);
2567 * Short description of parameters.
2569 static void usage(void)
2571 printf("PuTTY Secure File Transfer (SFTP) client\n");
2572 printf("%s\n", ver);
2573 printf("Usage: psftp [options] [user@]host\n");
2574 printf("Options:\n");
2575 printf(" -V print version information and exit\n");
2576 printf(" -pgpfp print PGP key fingerprints and exit\n");
2577 printf(" -b file use specified batchfile\n");
2578 printf(" -bc output batchfile commands\n");
2579 printf(" -be don't stop batchfile processing if errors\n");
2580 printf(" -v show verbose messages\n");
2581 printf(" -load sessname Load settings from saved session\n");
2582 printf(" -l user connect with specified username\n");
2583 printf(" -P port connect to specified port\n");
2584 printf(" -pw passw login with specified password\n");
2585 printf(" -1 -2 force use of particular SSH protocol version\n");
2586 printf(" -4 -6 force use of IPv4 or IPv6\n");
2587 printf(" -C enable compression\n");
2588 printf(" -i key private key file for authentication\n");
2589 printf(" -batch disable all interactive prompts\n");
2593 static void version(void)
2595 printf("psftp: %s\n", ver);
2600 * Connect to a host.
2602 static int psftp_connect(char *userhost, char *user, int portnumber)
2604 char *host, *realhost;
2608 /* Separate host and username */
2610 host = strrchr(host, '@');
2616 printf("psftp: multiple usernames specified; using \"%s\"\n",
2623 * If we haven't loaded session details already (e.g., from -load),
2624 * try looking for a session called "host".
2626 if (!loaded_session) {
2627 /* Try to load settings for `host' into a temporary config */
2629 cfg2.host[0] = '\0';
2630 do_defaults(host, &cfg2);
2631 if (cfg2.host[0] != '\0') {
2632 /* Settings present and include hostname */
2633 /* Re-load data into the real config. */
2634 do_defaults(host, &cfg);
2636 /* Session doesn't exist or mention a hostname. */
2637 /* Use `host' as a bare hostname. */
2638 strncpy(cfg.host, host, sizeof(cfg.host) - 1);
2639 cfg.host[sizeof(cfg.host) - 1] = '\0';
2642 /* Patch in hostname `host' to session details. */
2643 strncpy(cfg.host, host, sizeof(cfg.host) - 1);
2644 cfg.host[sizeof(cfg.host) - 1] = '\0';
2648 * Force use of SSH. (If they got the protocol wrong we assume the
2649 * port is useless too.)
2651 if (cfg.protocol != PROT_SSH) {
2652 cfg.protocol = PROT_SSH;
2657 * If saved session / Default Settings says SSH-1 (`1 only' or `1'),
2658 * then change it to SSH-2, on the grounds that that's more likely to
2659 * work for SFTP. (Can be overridden with `-1' option.)
2660 * But if it says `2 only' or `2', respect which.
2662 if (cfg.sshprot != 2 && cfg.sshprot != 3)
2666 * Enact command-line overrides.
2668 cmdline_run_saved(&cfg);
2671 * Trim leading whitespace off the hostname if it's there.
2674 int space = strspn(cfg.host, " \t");
2675 memmove(cfg.host, cfg.host+space, 1+strlen(cfg.host)-space);
2678 /* See if host is of the form user@host */
2679 if (cfg.host[0] != '\0') {
2680 char *atsign = strrchr(cfg.host, '@');
2681 /* Make sure we're not overflowing the user field */
2683 if (atsign - cfg.host < sizeof cfg.username) {
2684 strncpy(cfg.username, cfg.host, atsign - cfg.host);
2685 cfg.username[atsign - cfg.host] = '\0';
2687 memmove(cfg.host, atsign + 1, 1 + strlen(atsign + 1));
2692 * Trim a colon suffix off the hostname if it's there.
2694 cfg.host[strcspn(cfg.host, ":")] = '\0';
2697 * Remove any remaining whitespace from the hostname.
2701 while (cfg.host[p2] != '\0') {
2702 if (cfg.host[p2] != ' ' && cfg.host[p2] != '\t') {
2703 cfg.host[p1] = cfg.host[p2];
2708 cfg.host[p1] = '\0';
2712 if (user != NULL && user[0] != '\0') {
2713 strncpy(cfg.username, user, sizeof(cfg.username) - 1);
2714 cfg.username[sizeof(cfg.username) - 1] = '\0';
2716 if (!cfg.username[0]) {
2717 if (!console_get_line("login as: ",
2718 cfg.username, sizeof(cfg.username), FALSE)) {
2719 fprintf(stderr, "psftp: no username, aborting\n");
2722 int len = strlen(cfg.username);
2723 if (cfg.username[len - 1] == '\n')
2724 cfg.username[len - 1] = '\0';
2729 cfg.port = portnumber;
2732 * Disable scary things which shouldn't be enabled for simple
2733 * things like SCP and SFTP: agent forwarding, port forwarding,
2736 cfg.x11_forward = 0;
2738 cfg.portfwd[0] = cfg.portfwd[1] = '\0';
2740 /* Set up subsystem name. */
2741 strcpy(cfg.remote_cmd, "sftp");
2742 cfg.ssh_subsys = TRUE;
2746 * Set up fallback option, for SSH-1 servers or servers with the
2747 * sftp subsystem not enabled but the server binary installed
2748 * in the usual place. We only support fallback on Unix
2749 * systems, and we use a kludgy piece of shellery which should
2750 * try to find sftp-server in various places (the obvious
2751 * systemwide spots /usr/lib and /usr/local/lib, and then the
2752 * user's PATH) and finally give up.
2754 * test -x /usr/lib/sftp-server && exec /usr/lib/sftp-server
2755 * test -x /usr/local/lib/sftp-server && exec /usr/local/lib/sftp-server
2758 * the idea being that this will attempt to use either of the
2759 * obvious pathnames and then give up, and when it does give up
2760 * it will print the preferred pathname in the error messages.
2762 cfg.remote_cmd_ptr2 =
2763 "test -x /usr/lib/sftp-server && exec /usr/lib/sftp-server\n"
2764 "test -x /usr/local/lib/sftp-server && exec /usr/local/lib/sftp-server\n"
2766 cfg.ssh_subsys2 = FALSE;
2768 back = &ssh_backend;
2770 err = back->init(NULL, &backhandle, &cfg, cfg.host, cfg.port, &realhost,
2771 0, cfg.tcp_keepalives);
2773 fprintf(stderr, "ssh_init: %s\n", err);
2776 logctx = log_init(NULL, &cfg);
2777 back->provide_logctx(backhandle, logctx);
2778 console_provide_logctx(logctx);
2779 while (!back->sendok(backhandle)) {
2780 if (ssh_sftp_loop_iteration() < 0) {
2781 fprintf(stderr, "ssh_init: error during SSH connection setup\n");
2785 if (verbose && realhost != NULL)
2786 printf("Connected to %s\n", realhost);
2787 if (realhost != NULL)
2792 void cmdline_error(char *p, ...)
2795 fprintf(stderr, "psftp: ");
2797 vfprintf(stderr, p, ap);
2799 fprintf(stderr, "\n try typing \"psftp -h\" for help\n");
2804 * Main program. Parse arguments etc.
2806 int psftp_main(int argc, char *argv[])
2810 char *userhost, *user;
2813 char *batchfile = NULL;
2816 flags = FLAG_STDERR | FLAG_INTERACTIVE
2817 #ifdef FLAG_SYNCAGENT
2821 cmdline_tooltype = TOOLTYPE_FILETRANSFER;
2822 ssh_get_line = &console_get_line;
2825 userhost = user = NULL;
2827 /* Load Default Settings before doing anything else. */
2828 do_defaults(NULL, &cfg);
2829 loaded_session = FALSE;
2832 for (i = 1; i < argc; i++) {
2834 if (argv[i][0] != '-') {
2838 userhost = dupstr(argv[i]);
2841 ret = cmdline_process_param(argv[i], i+1<argc?argv[i+1]:NULL, 1, &cfg);
2843 cmdline_error("option \"%s\" requires an argument", argv[i]);
2844 } else if (ret == 2) {
2845 i++; /* skip next argument */
2846 } else if (ret == 1) {
2847 /* We have our own verbosity in addition to `flags'. */
2848 if (flags & FLAG_VERBOSE)
2850 } else if (strcmp(argv[i], "-h") == 0 ||
2851 strcmp(argv[i], "-?") == 0) {
2853 } else if (strcmp(argv[i], "-pgpfp") == 0) {
2856 } else if (strcmp(argv[i], "-V") == 0) {
2858 } else if (strcmp(argv[i], "-batch") == 0) {
2859 console_batch_mode = 1;
2860 } else if (strcmp(argv[i], "-b") == 0 && i + 1 < argc) {
2862 batchfile = argv[++i];
2863 } else if (strcmp(argv[i], "-bc") == 0) {
2864 modeflags = modeflags | 1;
2865 } else if (strcmp(argv[i], "-be") == 0) {
2866 modeflags = modeflags | 2;
2867 } else if (strcmp(argv[i], "--") == 0) {
2871 cmdline_error("unknown option \"%s\"", argv[i]);
2879 * If the loaded session provides a hostname, and a hostname has not
2880 * otherwise been specified, pop it in `userhost' so that
2881 * `psftp -load sessname' is sufficient to start a session.
2883 if (!userhost && cfg.host[0] != '\0') {
2884 userhost = dupstr(cfg.host);
2888 * If a user@host string has already been provided, connect to
2893 ret = psftp_connect(userhost, user, portnumber);
2900 printf("psftp: no hostname specified; use \"open host.name\""
2904 do_sftp(mode, modeflags, batchfile);
2906 if (back != NULL && back->socket(backhandle) != NULL) {
2908 back->special(backhandle, TS_EOF);
2909 sftp_recvdata(&ch, 1);
2914 console_provide_logctx(NULL);