]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - psftp.c
Consistently use a single notation to refer to SSH protocol versions, as
[PuTTY.git] / psftp.c
1 /*
2  * psftp.c: (platform-independent) front end for PSFTP.
3  */
4
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <stdarg.h>
8 #include <assert.h>
9 #include <limits.h>
10
11 #define PUTTY_DO_GLOBALS
12 #include "putty.h"
13 #include "psftp.h"
14 #include "storage.h"
15 #include "ssh.h"
16 #include "sftp.h"
17 #include "int64.h"
18
19 /*
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
23  * send buffer.
24  */
25
26 static int psftp_connect(char *userhost, char *user, int portnumber);
27 static int do_sftp_init(void);
28 void do_sftp_cleanup();
29
30 /* ----------------------------------------------------------------------
31  * sftp client state.
32  */
33
34 char *pwd, *homedir;
35 static Backend *back;
36 static void *backhandle;
37 static Config cfg;
38
39 /* ----------------------------------------------------------------------
40  * Higher-level helper functions used in commands.
41  */
42
43 /*
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).
47  */
48 char *canonify(char *name)
49 {
50     char *fullname, *canonname;
51     struct sftp_packet *pktin;
52     struct sftp_request *req, *rreq;
53
54     if (name[0] == '/') {
55         fullname = dupstr(name);
56     } else {
57         char *slash;
58         if (pwd[strlen(pwd) - 1] == '/')
59             slash = "";
60         else
61             slash = "/";
62         fullname = dupcat(pwd, slash, name, NULL);
63     }
64
65     sftp_register(req = fxp_realpath_send(fullname));
66     rreq = sftp_find_request(pktin = sftp_recv());
67     assert(rreq == req);
68     canonname = fxp_realpath_recv(pktin, rreq);
69
70     if (canonname) {
71         sfree(fullname);
72         return canonname;
73     } else {
74         /*
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.
82          * 
83          * Special cases:
84          * 
85          *  - if the last component is "/." or "/..", then we don't
86          *    bother trying this because there's no way it can work.
87          * 
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.
93          * 
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).
97          */
98
99         int i;
100         char *returnname;
101
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] != '/');
106
107         /*
108          * Give up on special cases.
109          */
110         if (fullname[i] != '/' ||      /* no slash at all */
111             !strcmp(fullname + i, "/.") ||      /* ends in /. */
112             !strcmp(fullname + i, "/..") ||     /* ends in /.. */
113             !strcmp(fullname, "/")) {
114             return fullname;
115         }
116
117         /*
118          * Now i points at the slash. Deal with the final special
119          * case i==0 (ie the whole path was "/nonexistentfile").
120          */
121         fullname[i] = '\0';            /* separate the string */
122         if (i == 0) {
123             sftp_register(req = fxp_realpath_send("/"));
124         } else {
125             sftp_register(req = fxp_realpath_send(fullname));
126         }
127         rreq = sftp_find_request(pktin = sftp_recv());
128         assert(rreq == req);
129         canonname = fxp_realpath_recv(pktin, rreq);
130
131         if (!canonname)
132             return fullname;           /* even that failed; give up */
133
134         /*
135          * We have a canonical name for all but the last path
136          * component. Concatenate the last component and return.
137          */
138         returnname = dupcat(canonname,
139                             canonname[strlen(canonname) - 1] ==
140                             '/' ? "" : "/", fullname + i + 1, NULL);
141         sfree(fullname);
142         sfree(canonname);
143         return returnname;
144     }
145 }
146
147 /*
148  * Return a pointer to the portion of str that comes after the last
149  * slash (or backslash or colon, if `local' is TRUE).
150  */
151 static char *stripslashes(char *str, int local)
152 {
153     char *p;
154
155     if (local) {
156         p = strchr(str, ':');
157         if (p) str = p+1;
158     }
159
160     p = strrchr(str, '/');
161     if (p) str = p+1;
162
163     if (local) {
164         p = strrchr(str, '\\');
165         if (p) str = p+1;
166     }
167
168     return str;
169 }
170
171 /*
172  * qsort comparison routine for fxp_name structures. Sorts by real
173  * file name.
174  */
175 static int sftp_name_compare(const void *av, const void *bv)
176 {
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);
180 }
181
182 /*
183  * Likewise, but for a bare char *.
184  */
185 static int bare_name_compare(const void *av, const void *bv)
186 {
187     const char **a = (const char **) av;
188     const char **b = (const char **) bv;
189     return strcmp(*a, *b);
190 }
191
192 static void not_connected(void)
193 {
194     printf("psftp: not connected to a host; use \"open host.name\"\n");
195 }
196
197 /* ----------------------------------------------------------------------
198  * The meat of the `get' and `put' commands.
199  */
200 int sftp_get_file(char *fname, char *outfname, int recurse, int restart)
201 {
202     struct fxp_handle *fh;
203     struct sftp_packet *pktin;
204     struct sftp_request *req, *rreq;
205     struct fxp_xfer *xfer;
206     uint64 offset;
207     FILE *fp;
208     int ret, shown_err = FALSE;
209
210     /*
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.)
214      */
215     if (recurse) {
216         struct fxp_attrs attrs;
217         int result;
218
219         sftp_register(req = fxp_stat_send(fname));
220         rreq = sftp_find_request(pktin = sftp_recv());
221         assert(rreq == req);
222         result = fxp_stat_recv(pktin, rreq, &attrs);
223
224         if (result &&
225             (attrs.flags & SSH_FILEXFER_ATTR_PERMISSIONS) &&
226             (attrs.permissions & 0040000)) {
227
228             struct fxp_handle *dirhandle;
229             int nnames, namesize;
230             struct fxp_name **ournames;
231             struct fxp_names *names;
232             int i;
233
234             /*
235              * First, attempt to create the destination directory,
236              * unless it already exists.
237              */
238             if (file_type(outfname) != FILE_TYPE_DIRECTORY &&
239                 !create_directory(outfname)) {
240                 printf("%s: Cannot create directory\n", outfname);
241                 return 0;
242             }
243
244             /*
245              * Now get the list of filenames in the remote
246              * directory.
247              */
248             sftp_register(req = fxp_opendir_send(fname));
249             rreq = sftp_find_request(pktin = sftp_recv());
250             assert(rreq == req);
251             dirhandle = fxp_opendir_recv(pktin, rreq);
252
253             if (!dirhandle) {
254                 printf("%s: unable to open directory: %s\n",
255                        fname, fxp_error());
256                 return 0;
257             }
258             nnames = namesize = 0;
259             ournames = NULL;
260             while (1) {
261                 int i;
262
263                 sftp_register(req = fxp_readdir_send(dirhandle));
264                 rreq = sftp_find_request(pktin = sftp_recv());
265                 assert(rreq == req);
266                 names = fxp_readdir_recv(pktin, rreq);
267
268                 if (names == NULL) {
269                     if (fxp_error_type() == SSH_FX_EOF)
270                         break;
271                     printf("%s: reading directory: %s\n", fname, fxp_error());
272                     sfree(ournames);
273                     return 0;
274                 }
275                 if (names->nnames == 0) {
276                     fxp_free_names(names);
277                     break;
278                 }
279                 if (nnames + names->nnames >= namesize) {
280                     namesize += names->nnames + 128;
281                     ournames = sresize(ournames, namesize, struct fxp_name *);
282                 }
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);
290                         } else {
291                             ournames[nnames++] =
292                                 fxp_dup_name(&names->names[i]);
293                         }
294                     }
295                 fxp_free_names(names);
296             }
297             sftp_register(req = fxp_close_send(dirhandle));
298             rreq = sftp_find_request(pktin = sftp_recv());
299             assert(rreq == req);
300             fxp_close_recv(pktin, rreq);
301
302             /*
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
307              * different order.
308              */
309             qsort(ournames, nnames, sizeof(*ournames), sftp_name_compare);
310
311             /*
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.
316              * 
317              * If none of them exists, of course, we start at 0.
318              */
319             i = 0;
320             while (i < nnames) {
321                 char *nextoutfname;
322                 int ret;
323                 if (outfname)
324                     nextoutfname = dir_file_cat(outfname,
325                                                 ournames[i]->filename);
326                 else
327                     nextoutfname = dupstr(ournames[i]->filename);
328                 ret = (file_type(nextoutfname) == FILE_TYPE_NONEXISTENT);
329                 sfree(nextoutfname);
330                 if (ret)
331                     break;
332                 i++;
333             }
334             if (i > 0)
335                 i--;
336
337             /*
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.
342              */
343             for (; i < nnames; i++) {
344                 char *nextfname, *nextoutfname;
345                 int ret;
346                 
347                 nextfname = dupcat(fname, "/", ournames[i]->filename, NULL);
348                 if (outfname)
349                     nextoutfname = dir_file_cat(outfname,
350                                                 ournames[i]->filename);
351                 else
352                     nextoutfname = dupstr(ournames[i]->filename);
353                 ret = sftp_get_file(nextfname, nextoutfname, recurse, restart);
354                 restart = FALSE;       /* after first partial file, do full */
355                 sfree(nextoutfname);
356                 sfree(nextfname);
357                 if (!ret) {
358                     for (i = 0; i < nnames; i++) {
359                         fxp_free_name(ournames[i]);
360                     }
361                     sfree(ournames);
362                     return 0;
363                 }
364             }
365
366             /*
367              * Done this recursion level. Free everything.
368              */
369             for (i = 0; i < nnames; i++) {
370                 fxp_free_name(ournames[i]);
371             }
372             sfree(ournames);
373
374             return 1;
375         }
376     }
377
378     sftp_register(req = fxp_open_send(fname, SSH_FXF_READ));
379     rreq = sftp_find_request(pktin = sftp_recv());
380     assert(rreq == req);
381     fh = fxp_open_recv(pktin, rreq);
382
383     if (!fh) {
384         printf("%s: %s\n", fname, fxp_error());
385         return 0;
386     }
387
388     if (restart) {
389         fp = fopen(outfname, "rb+");
390     } else {
391         fp = fopen(outfname, "wb");
392     }
393
394     if (!fp) {
395         printf("local: unable to open %s\n", outfname);
396
397         sftp_register(req = fxp_close_send(fh));
398         rreq = sftp_find_request(pktin = sftp_recv());
399         assert(rreq == req);
400         fxp_close_recv(pktin, rreq);
401
402         return 0;
403     }
404
405     if (restart) {
406         long posn;
407         fseek(fp, 0L, SEEK_END);
408         posn = ftell(fp);
409         printf("reget: restarting at file position %ld\n", posn);
410         offset = uint64_make(0, posn);
411     } else {
412         offset = uint64_make(0, 0);
413     }
414
415     printf("remote:%s => local:%s\n", fname, outfname);
416
417     /*
418      * FIXME: we can use FXP_FSTAT here to get the file size, and
419      * thus put up a progress bar.
420      */
421     ret = 1;
422     xfer = xfer_download_init(fh, offset);
423     while (!xfer_done(xfer)) {
424         void *vbuf;
425         int ret, len;
426         int wpos, wlen;
427
428         xfer_download_queue(xfer);
429         pktin = sftp_recv();
430         ret = xfer_download_gotpkt(xfer, pktin);
431
432         if (ret < 0) {
433             if (!shown_err) {
434                 printf("error while reading: %s\n", fxp_error());
435                 shown_err = TRUE;
436             }
437             ret = 0;
438         }
439
440         while (xfer_download_data(xfer, &vbuf, &len)) {
441             unsigned char *buf = (unsigned char *)vbuf;
442
443             wpos = 0;
444             while (wpos < len) {
445                 wlen = fwrite(buf + wpos, 1, len - wpos, fp);
446                 if (wlen <= 0) {
447                     printf("error while writing local file\n");
448                     ret = 0;
449                     xfer_set_error(xfer);
450                 }
451                 wpos += wlen;
452             }
453             if (wpos < len) {          /* we had an error */
454                 ret = 0;
455                 xfer_set_error(xfer);
456             }
457
458             sfree(vbuf);
459         }
460     }
461
462     xfer_cleanup(xfer);
463
464     fclose(fp);
465
466     sftp_register(req = fxp_close_send(fh));
467     rreq = sftp_find_request(pktin = sftp_recv());
468     assert(rreq == req);
469     fxp_close_recv(pktin, rreq);
470
471     return ret;
472 }
473
474 int sftp_put_file(char *fname, char *outfname, int recurse, int restart)
475 {
476     struct fxp_handle *fh;
477     struct fxp_xfer *xfer;
478     struct sftp_packet *pktin;
479     struct sftp_request *req, *rreq;
480     uint64 offset;
481     FILE *fp;
482     int ret, err, eof;
483
484     /*
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.)
488      */
489     if (recurse && file_type(fname) == FILE_TYPE_DIRECTORY) {
490         struct fxp_attrs attrs;
491         int result;
492         int nnames, namesize;
493         char *name, **ournames;
494         DirHandle *dh;
495         int i;
496
497         /*
498          * First, attempt to create the destination directory,
499          * unless it already exists.
500          */
501         sftp_register(req = fxp_stat_send(outfname));
502         rreq = sftp_find_request(pktin = sftp_recv());
503         assert(rreq == req);
504         result = fxp_stat_recv(pktin, rreq, &attrs);
505         if (!result ||
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());
510             assert(rreq == req);
511             result = fxp_mkdir_recv(pktin, rreq);
512
513             if (!result) {
514                 printf("%s: create directory: %s\n",
515                        outfname, fxp_error());
516                 return 0;
517             }
518         }
519
520         /*
521          * Now get the list of filenames in the local directory.
522          */
523         nnames = namesize = 0;
524         ournames = NULL;
525
526         dh = open_directory(fname);
527         if (!dh) {
528             printf("%s: unable to open directory\n", fname);
529             return 0;
530         }
531         while ((name = read_filename(dh)) != NULL) {
532             if (nnames >= namesize) {
533                 namesize += 128;
534                 ournames = sresize(ournames, namesize, char *);
535             }
536             ournames[nnames++] = name;
537         }
538         close_directory(dh);
539
540         /*
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.
545          */
546         qsort(ournames, nnames, sizeof(*ournames), bare_name_compare);
547
548         /*
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
552          * previous files.
553          *
554          * If none of them exists, of course, we start at 0.
555          */
556         i = 0;
557         while (i < nnames) {
558             char *nextoutfname;
559             nextoutfname = dupcat(outfname, "/", ournames[i], NULL);
560             sftp_register(req = fxp_stat_send(nextoutfname));
561             rreq = sftp_find_request(pktin = sftp_recv());
562             assert(rreq == req);
563             result = fxp_stat_recv(pktin, rreq, &attrs);
564             sfree(nextoutfname);
565             if (!result)
566                 break;
567             i++;
568         }
569         if (i > 0)
570             i--;
571
572         /*
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.
577          */
578         for (; i < nnames; i++) {
579             char *nextfname, *nextoutfname;
580             int ret;
581
582             if (fname)
583                 nextfname = dir_file_cat(fname, ournames[i]);
584             else
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 */
589             sfree(nextoutfname);
590             sfree(nextfname);
591             if (!ret) {
592                 for (i = 0; i < nnames; i++) {
593                     sfree(ournames[i]);
594                 }
595                 sfree(ournames);
596                 return 0;
597             }
598         }
599
600         /*
601          * Done this recursion level. Free everything.
602          */
603         for (i = 0; i < nnames; i++) {
604             sfree(ournames[i]);
605         }
606         sfree(ournames);
607
608         return 1;
609     }
610
611     fp = fopen(fname, "rb");
612     if (!fp) {
613         printf("local: unable to open %s\n", fname);
614         return 0;
615     }
616     if (restart) {
617         sftp_register(req = fxp_open_send(outfname, SSH_FXF_WRITE));
618     } else {
619         sftp_register(req = fxp_open_send(outfname, SSH_FXF_WRITE |
620                                           SSH_FXF_CREAT | SSH_FXF_TRUNC));
621     }
622     rreq = sftp_find_request(pktin = sftp_recv());
623     assert(rreq == req);
624     fh = fxp_open_recv(pktin, rreq);
625
626     if (!fh) {
627         printf("%s: %s\n", outfname, fxp_error());
628         return 0;
629     }
630
631     if (restart) {
632         char decbuf[30];
633         struct fxp_attrs attrs;
634         int ret;
635
636         sftp_register(req = fxp_fstat_send(fh));
637         rreq = sftp_find_request(pktin = sftp_recv());
638         assert(rreq == req);
639         ret = fxp_fstat_recv(pktin, rreq, &attrs);
640
641         if (!ret) {
642             printf("read size of %s: %s\n", outfname, fxp_error());
643             return 0;
644         }
645         if (!(attrs.flags & SSH_FILEXFER_ATTR_SIZE)) {
646             printf("read size of %s: size was not given\n", outfname);
647             return 0;
648         }
649         offset = attrs.size;
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");
654             return 0;
655         }
656         if (fseek(fp, offset.lo, SEEK_SET) != 0)
657             fseek(fp, 0, SEEK_END);    /* *shrug* */
658     } else {
659         offset = uint64_make(0, 0);
660     }
661
662     printf("local:%s => remote:%s\n", fname, outfname);
663
664     /*
665      * FIXME: we can use FXP_FSTAT here to get the file size, and
666      * thus put up a progress bar.
667      */
668     ret = 1;
669     xfer = xfer_upload_init(fh, offset);
670     err = eof = 0;
671     while ((!err && !eof) || !xfer_done(xfer)) {
672         char buffer[4096];
673         int len, ret;
674
675         while (xfer_upload_ready(xfer) && !err && !eof) {
676             len = fread(buffer, 1, sizeof(buffer), fp);
677             if (len == -1) {
678                 printf("error while reading local file\n");
679                 err = 1;
680             } else if (len == 0) {
681                 eof = 1;
682             } else {
683                 xfer_upload_data(xfer, buffer, len);
684             }
685         }
686
687         if (!xfer_done(xfer)) {
688             pktin = sftp_recv();
689             ret = xfer_upload_gotpkt(xfer, pktin);
690             if (!ret) {
691                 printf("error while writing: %s\n", fxp_error());
692                 err = 1;
693             }
694         }
695     }
696
697     xfer_cleanup(xfer);
698
699     sftp_register(req = fxp_close_send(fh));
700     rreq = sftp_find_request(pktin = sftp_recv());
701     assert(rreq == req);
702     fxp_close_recv(pktin, rreq);
703
704     fclose(fp);
705
706     return ret;
707 }
708
709 /* ----------------------------------------------------------------------
710  * A remote wildcard matcher, providing a similar interface to the
711  * local one in psftp.h.
712  */
713
714 typedef struct SftpWildcardMatcher {
715     struct fxp_handle *dirh;
716     struct fxp_names *names;
717     int namepos;
718     char *wildcard, *prefix;
719 } SftpWildcardMatcher;
720
721 SftpWildcardMatcher *sftp_begin_wildcard_matching(char *name)
722 {
723     struct sftp_packet *pktin;
724     struct sftp_request *req, *rreq;
725     char *wildcard;
726     char *unwcdir, *tmpdir, *cdir;
727     int len, check;
728     SftpWildcardMatcher *swcm;
729     struct fxp_handle *dirh;
730
731     /*
732      * We don't handle multi-level wildcards; so we expect to find
733      * a fully specified directory part, followed by a wildcard
734      * after that.
735      */
736     wildcard = stripslashes(name, 0);
737
738     unwcdir = dupstr(name);
739     len = wildcard - name;
740     unwcdir[len] = '\0';
741     if (len > 0 && unwcdir[len-1] == '/')
742         unwcdir[len-1] = '\0';
743     tmpdir = snewn(1 + len, char);
744     check = wc_unescape(tmpdir, unwcdir);
745     sfree(tmpdir);
746
747     if (!check) {
748         printf("Multiple-level wildcards are not supported\n");
749         sfree(unwcdir);
750         return NULL;
751     }
752
753     cdir = canonify(unwcdir);
754
755     sftp_register(req = fxp_opendir_send(cdir));
756     rreq = sftp_find_request(pktin = sftp_recv());
757     assert(rreq == req);
758     dirh = fxp_opendir_recv(pktin, rreq);
759
760     if (dirh) {
761         swcm = snew(SftpWildcardMatcher);
762         swcm->dirh = dirh;
763         swcm->names = NULL;
764         swcm->wildcard = dupstr(wildcard);
765         swcm->prefix = unwcdir;
766     } else {
767         printf("Unable to open %s: %s\n", cdir, fxp_error());
768         swcm = NULL;
769         sfree(unwcdir);
770     }
771
772     sfree(cdir);
773
774     return swcm;
775 }
776
777 char *sftp_wildcard_get_filename(SftpWildcardMatcher *swcm)
778 {
779     struct fxp_name *name;
780     struct sftp_packet *pktin;
781     struct sftp_request *req, *rreq;
782
783     while (1) {
784         if (swcm->names && swcm->namepos >= swcm->names->nnames) {
785             fxp_free_names(swcm->names);
786             swcm->names = NULL;
787         }
788
789         if (!swcm->names) {
790             sftp_register(req = fxp_readdir_send(swcm->dirh));
791             rreq = sftp_find_request(pktin = sftp_recv());
792             assert(rreq == req);
793             swcm->names = fxp_readdir_recv(pktin, rreq);
794
795             if (!swcm->names) {
796                 if (fxp_error_type() != SSH_FX_EOF)
797                     printf("%s: reading directory: %s\n", swcm->prefix,
798                            fxp_error());
799                 return NULL;
800             }
801
802             swcm->namepos = 0;
803         }
804
805         assert(swcm->names && swcm->namepos < swcm->names->nnames);
806
807         name = &swcm->names->names[swcm->namepos++];
808
809         if (!strcmp(name->filename, ".") || !strcmp(name->filename, ".."))
810             continue;                  /* expected bad filenames */
811
812         if (!vet_filename(name->filename)) {
813             printf("ignoring potentially dangerous server-"
814                    "supplied filename '%s'\n", name->filename);
815             continue;                  /* unexpected bad filename */
816         }
817
818         if (!wc_match(swcm->wildcard, name->filename))
819             continue;                  /* doesn't match the wildcard */
820
821         /*
822          * We have a working filename. Return it.
823          */
824         return dupprintf("%s%s%s", swcm->prefix,
825                          (!swcm->prefix[0] ||
826                           swcm->prefix[strlen(swcm->prefix)-1]=='/' ?
827                           "" : "/"),
828                          name->filename);
829     }
830 }
831
832 void sftp_finish_wildcard_matching(SftpWildcardMatcher *swcm)
833 {
834     struct sftp_packet *pktin;
835     struct sftp_request *req, *rreq;
836
837     sftp_register(req = fxp_close_send(swcm->dirh));
838     rreq = sftp_find_request(pktin = sftp_recv());
839     assert(rreq == req);
840     fxp_close_recv(pktin, rreq);
841
842     if (swcm->names)
843         fxp_free_names(swcm->names);
844
845     sfree(swcm->prefix);
846     sfree(swcm->wildcard);
847
848     sfree(swcm);
849 }
850
851 /*
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).
855  */
856 int wildcard_iterate(char *filename, int (*func)(void *, char *), void *ctx)
857 {
858     char *unwcfname, *newname, *cname;
859     int is_wc, ret;
860
861     unwcfname = snewn(strlen(filename)+1, char);
862     is_wc = !wc_unescape(unwcfname, filename);
863
864     if (is_wc) {
865         SftpWildcardMatcher *swcm = sftp_begin_wildcard_matching(filename);
866         int matched = FALSE;
867         sfree(unwcfname);
868
869         if (!swcm)
870             return 0;
871
872         ret = 1;
873
874         while ( (newname = sftp_wildcard_get_filename(swcm)) != NULL ) {
875             cname = canonify(newname);
876             if (!cname) {
877                 printf("%s: %s\n", newname, fxp_error());
878                 ret = 0;
879             }
880             matched = TRUE;
881             ret &= func(ctx, cname);
882             sfree(cname);
883         }
884
885         if (!matched) {
886             /* Politely warn the user that nothing matched. */
887             printf("%s: nothing matched\n", filename);
888         }
889
890         sftp_finish_wildcard_matching(swcm);
891     } else {
892         cname = canonify(unwcfname);
893         if (!cname) {
894             printf("%s: %s\n", filename, fxp_error());
895             ret = 0;
896         }
897         ret = func(ctx, cname);
898         sfree(cname);
899         sfree(unwcfname);
900     }
901
902     return ret;
903 }
904
905 /*
906  * Handy helper function.
907  */
908 int is_wildcard(char *name)
909 {
910     char *unwcfname = snewn(strlen(name)+1, char);
911     int is_wc = !wc_unescape(unwcfname, name);
912     sfree(unwcfname);
913     return is_wc;
914 }
915
916 /* ----------------------------------------------------------------------
917  * Actual sftp commands.
918  */
919 struct sftp_command {
920     char **words;
921     int nwords, wordssize;
922     int (*obey) (struct sftp_command *);        /* returns <0 to quit */
923 };
924
925 int sftp_cmd_null(struct sftp_command *cmd)
926 {
927     return 1;                          /* success */
928 }
929
930 int sftp_cmd_unknown(struct sftp_command *cmd)
931 {
932     printf("psftp: unknown command \"%s\"\n", cmd->words[0]);
933     return 0;                          /* failure */
934 }
935
936 int sftp_cmd_quit(struct sftp_command *cmd)
937 {
938     return -1;
939 }
940
941 int sftp_cmd_close(struct sftp_command *cmd)
942 {
943     if (back == NULL) {
944         not_connected();
945         return 0;
946     }
947
948     if (back != NULL && back->socket(backhandle) != NULL) {
949         char ch;
950         back->special(backhandle, TS_EOF);
951         sftp_recvdata(&ch, 1);
952     }
953     do_sftp_cleanup();
954
955     return 0;
956 }
957
958 /*
959  * List a directory. If no arguments are given, list pwd; otherwise
960  * list the directory given in words[1].
961  */
962 int sftp_cmd_ls(struct sftp_command *cmd)
963 {
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;
971     int i;
972
973     if (back == NULL) {
974         not_connected();
975         return 0;
976     }
977
978     if (cmd->nwords < 2)
979         dir = ".";
980     else
981         dir = cmd->words[1];
982
983     unwcdir = snewn(1 + strlen(dir), char);
984     if (wc_unescape(unwcdir, dir)) {
985         dir = unwcdir;
986         wildcard = NULL;
987     } else {
988         char *tmpdir;
989         int len, check;
990
991         wildcard = stripslashes(dir, 0);
992         unwcdir = dupstr(dir);
993         len = wildcard - dir;
994         unwcdir[len] = '\0';
995         if (len > 0 && unwcdir[len-1] == '/')
996             unwcdir[len-1] = '\0';
997         tmpdir = snewn(1 + len, char);
998         check = wc_unescape(tmpdir, unwcdir);
999         sfree(tmpdir);
1000         if (!check) {
1001             printf("Multiple-level wildcards are not supported\n");
1002             sfree(unwcdir);
1003             return 0;
1004         }
1005         dir = unwcdir;
1006     }
1007
1008     cdir = canonify(dir);
1009     if (!cdir) {
1010         printf("%s: %s\n", dir, fxp_error());
1011         sfree(unwcdir);
1012         return 0;
1013     }
1014
1015     printf("Listing directory %s\n", cdir);
1016
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);
1021
1022     if (dirh == NULL) {
1023         printf("Unable to open %s: %s\n", dir, fxp_error());
1024     } else {
1025         nnames = namesize = 0;
1026         ournames = NULL;
1027
1028         while (1) {
1029
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);
1034
1035             if (names == NULL) {
1036                 if (fxp_error_type() == SSH_FX_EOF)
1037                     break;
1038                 printf("Reading directory %s: %s\n", dir, fxp_error());
1039                 break;
1040             }
1041             if (names->nnames == 0) {
1042                 fxp_free_names(names);
1043                 break;
1044             }
1045
1046             if (nnames + names->nnames >= namesize) {
1047                 namesize += names->nnames + 128;
1048                 ournames = sresize(ournames, namesize, struct fxp_name *);
1049             }
1050
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]);
1054
1055             fxp_free_names(names);
1056         }
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);
1061
1062         /*
1063          * Now we have our filenames. Sort them by actual file
1064          * name, and then output the longname parts.
1065          */
1066         qsort(ournames, nnames, sizeof(*ournames), sftp_name_compare);
1067
1068         /*
1069          * And print them.
1070          */
1071         for (i = 0; i < nnames; i++) {
1072             printf("%s\n", ournames[i]->longname);
1073             fxp_free_name(ournames[i]);
1074         }
1075         sfree(ournames);
1076     }
1077
1078     sfree(cdir);
1079     sfree(unwcdir);
1080
1081     return 1;
1082 }
1083
1084 /*
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.
1087  */
1088 int sftp_cmd_cd(struct sftp_command *cmd)
1089 {
1090     struct fxp_handle *dirh;
1091     struct sftp_packet *pktin;
1092     struct sftp_request *req, *rreq;
1093     char *dir;
1094
1095     if (back == NULL) {
1096         not_connected();
1097         return 0;
1098     }
1099
1100     if (cmd->nwords < 2)
1101         dir = dupstr(homedir);
1102     else
1103         dir = canonify(cmd->words[1]);
1104
1105     if (!dir) {
1106         printf("%s: %s\n", dir, fxp_error());
1107         return 0;
1108     }
1109
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);
1114
1115     if (!dirh) {
1116         printf("Directory %s: %s\n", dir, fxp_error());
1117         sfree(dir);
1118         return 0;
1119     }
1120
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);
1125
1126     sfree(pwd);
1127     pwd = dir;
1128     printf("Remote directory is now %s\n", pwd);
1129
1130     return 1;
1131 }
1132
1133 /*
1134  * Print current directory. Easy as pie.
1135  */
1136 int sftp_cmd_pwd(struct sftp_command *cmd)
1137 {
1138     if (back == NULL) {
1139         not_connected();
1140         return 0;
1141     }
1142
1143     printf("Remote directory is %s\n", pwd);
1144     return 1;
1145 }
1146
1147 /*
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.
1155  */
1156 int sftp_general_get(struct sftp_command *cmd, int restart, int multiple)
1157 {
1158     char *fname, *unwcfname, *origfname, *origwfname, *outfname;
1159     int i, ret;
1160     int recurse = FALSE;
1161
1162     if (back == NULL) {
1163         not_connected();
1164         return 0;
1165     }
1166
1167     i = 1;
1168     while (i < cmd->nwords && cmd->words[i][0] == '-') {
1169         if (!strcmp(cmd->words[i], "--")) {
1170             /* finish processing options */
1171             i++;
1172             break;
1173         } else if (!strcmp(cmd->words[i], "-r")) {
1174             recurse = TRUE;
1175         } else {
1176             printf("%s: unrecognised option '%s'\n", cmd->words[0], cmd->words[i]);
1177             return 0;
1178         }
1179         i++;
1180     }
1181
1182     if (i >= cmd->nwords) {
1183         printf("%s: expects a filename\n", cmd->words[0]);
1184         return 0;
1185     }
1186
1187     ret = 1;
1188     do {
1189         SftpWildcardMatcher *swcm;
1190
1191         origfname = cmd->words[i++];
1192         unwcfname = snewn(strlen(origfname)+1, char);
1193
1194         if (multiple && !wc_unescape(unwcfname, origfname)) {
1195             swcm = sftp_begin_wildcard_matching(origfname);
1196             if (!swcm) {
1197                 sfree(unwcfname);
1198                 continue;
1199             }
1200             origwfname = sftp_wildcard_get_filename(swcm);
1201             if (!origwfname) {
1202                 /* Politely warn the user that nothing matched. */
1203                 printf("%s: nothing matched\n", origfname);
1204                 sftp_finish_wildcard_matching(swcm);
1205                 sfree(unwcfname);
1206                 continue;
1207             }
1208         } else {
1209             origwfname = origfname;
1210             swcm = NULL;
1211         }
1212
1213         while (origwfname) {
1214             fname = canonify(origwfname);
1215
1216             if (!fname) {
1217                 printf("%s: %s\n", origwfname, fxp_error());
1218                 sfree(unwcfname);
1219                 return 0;
1220             }
1221
1222             if (!multiple && i < cmd->nwords)
1223                 outfname = cmd->words[i++];
1224             else
1225                 outfname = stripslashes(origwfname, 0);
1226
1227             ret = sftp_get_file(fname, outfname, recurse, restart);
1228
1229             sfree(fname);
1230
1231             if (swcm) {
1232                 sfree(origwfname);
1233                 origwfname = sftp_wildcard_get_filename(swcm);
1234             } else {
1235                 origwfname = NULL;
1236             }
1237         }
1238         sfree(unwcfname);
1239         if (swcm)
1240             sftp_finish_wildcard_matching(swcm);
1241         if (!ret)
1242             return ret;
1243
1244     } while (multiple && i < cmd->nwords);
1245
1246     return ret;
1247 }
1248 int sftp_cmd_get(struct sftp_command *cmd)
1249 {
1250     return sftp_general_get(cmd, 0, 0);
1251 }
1252 int sftp_cmd_mget(struct sftp_command *cmd)
1253 {
1254     return sftp_general_get(cmd, 0, 1);
1255 }
1256 int sftp_cmd_reget(struct sftp_command *cmd)
1257 {
1258     return sftp_general_get(cmd, 1, 0);
1259 }
1260
1261 /*
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.
1269  */
1270 int sftp_general_put(struct sftp_command *cmd, int restart, int multiple)
1271 {
1272     char *fname, *wfname, *origoutfname, *outfname;
1273     int i, ret;
1274     int recurse = FALSE;
1275
1276     if (back == NULL) {
1277         not_connected();
1278         return 0;
1279     }
1280
1281     i = 1;
1282     while (i < cmd->nwords && cmd->words[i][0] == '-') {
1283         if (!strcmp(cmd->words[i], "--")) {
1284             /* finish processing options */
1285             i++;
1286             break;
1287         } else if (!strcmp(cmd->words[i], "-r")) {
1288             recurse = TRUE;
1289         } else {
1290             printf("%s: unrecognised option '%s'\n", cmd->words[0], cmd->words[i]);
1291             return 0;
1292         }
1293         i++;
1294     }
1295
1296     if (i >= cmd->nwords) {
1297         printf("%s: expects a filename\n", cmd->words[0]);
1298         return 0;
1299     }
1300
1301     ret = 1;
1302     do {
1303         WildcardMatcher *wcm;
1304         fname = cmd->words[i++];
1305
1306         if (multiple && test_wildcard(fname, FALSE) == WCTYPE_WILDCARD) {
1307             wcm = begin_wildcard_matching(fname);
1308             wfname = wildcard_get_filename(wcm);
1309             if (!wfname) {
1310                 /* Politely warn the user that nothing matched. */
1311                 printf("%s: nothing matched\n", fname);
1312                 finish_wildcard_matching(wcm);
1313                 continue;
1314             }
1315         } else {
1316             wfname = fname;
1317             wcm = NULL;
1318         }
1319
1320         while (wfname) {
1321             if (!multiple && i < cmd->nwords)
1322                 origoutfname = cmd->words[i++];
1323             else
1324                 origoutfname = stripslashes(wfname, 1);
1325
1326             outfname = canonify(origoutfname);
1327             if (!outfname) {
1328                 printf("%s: %s\n", origoutfname, fxp_error());
1329                 if (wcm) {
1330                     sfree(wfname);
1331                     finish_wildcard_matching(wcm);
1332                 }
1333                 return 0;
1334             }
1335             ret = sftp_put_file(wfname, outfname, recurse, restart);
1336             sfree(outfname);
1337
1338             if (wcm) {
1339                 sfree(wfname);
1340                 wfname = wildcard_get_filename(wcm);
1341             } else {
1342                 wfname = NULL;
1343             }
1344         }
1345
1346         if (wcm)
1347             finish_wildcard_matching(wcm);
1348
1349         if (!ret)
1350             return ret;
1351
1352     } while (multiple && i < cmd->nwords);
1353
1354     return ret;
1355 }
1356 int sftp_cmd_put(struct sftp_command *cmd)
1357 {
1358     return sftp_general_put(cmd, 0, 0);
1359 }
1360 int sftp_cmd_mput(struct sftp_command *cmd)
1361 {
1362     return sftp_general_put(cmd, 0, 1);
1363 }
1364 int sftp_cmd_reput(struct sftp_command *cmd)
1365 {
1366     return sftp_general_put(cmd, 1, 0);
1367 }
1368
1369 int sftp_cmd_mkdir(struct sftp_command *cmd)
1370 {
1371     char *dir;
1372     struct sftp_packet *pktin;
1373     struct sftp_request *req, *rreq;
1374     int result;
1375     int i, ret;
1376
1377     if (back == NULL) {
1378         not_connected();
1379         return 0;
1380     }
1381
1382     if (cmd->nwords < 2) {
1383         printf("mkdir: expects a directory\n");
1384         return 0;
1385     }
1386
1387     ret = 1;
1388     for (i = 1; i < cmd->nwords; i++) {
1389         dir = canonify(cmd->words[i]);
1390         if (!dir) {
1391             printf("%s: %s\n", dir, fxp_error());
1392             return 0;
1393         }
1394
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);
1399
1400         if (!result) {
1401             printf("mkdir %s: %s\n", dir, fxp_error());
1402             sfree(dir);
1403             ret = 0;
1404         } else
1405             printf("mkdir %s: OK\n", dir);
1406
1407         sfree(dir);
1408     }
1409
1410     return ret;
1411 }
1412
1413 static int sftp_action_rmdir(void *vctx, char *dir)
1414 {
1415     struct sftp_packet *pktin;
1416     struct sftp_request *req, *rreq;
1417     int result;
1418
1419     sftp_register(req = fxp_rmdir_send(dir));
1420     rreq = sftp_find_request(pktin = sftp_recv());
1421     assert(rreq == req);
1422     result = fxp_rmdir_recv(pktin, rreq);
1423
1424     if (!result) {
1425         printf("rmdir %s: %s\n", dir, fxp_error());
1426         return 0;
1427     }
1428
1429     printf("rmdir %s: OK\n", dir);
1430
1431     return 1;
1432 }
1433
1434 int sftp_cmd_rmdir(struct sftp_command *cmd)
1435 {
1436     int i, ret;
1437
1438     if (back == NULL) {
1439         not_connected();
1440         return 0;
1441     }
1442
1443     if (cmd->nwords < 2) {
1444         printf("rmdir: expects a directory\n");
1445         return 0;
1446     }
1447
1448     ret = 1;
1449     for (i = 1; i < cmd->nwords; i++)
1450         ret &= wildcard_iterate(cmd->words[i], sftp_action_rmdir, NULL);
1451
1452     return ret;
1453 }
1454
1455 static int sftp_action_rm(void *vctx, char *fname)
1456 {
1457     struct sftp_packet *pktin;
1458     struct sftp_request *req, *rreq;
1459     int result;
1460
1461     sftp_register(req = fxp_remove_send(fname));
1462     rreq = sftp_find_request(pktin = sftp_recv());
1463     assert(rreq == req);
1464     result = fxp_remove_recv(pktin, rreq);
1465
1466     if (!result) {
1467         printf("rm %s: %s\n", fname, fxp_error());
1468         return 0;
1469     }
1470
1471     printf("rm %s: OK\n", fname);
1472
1473     return 1;
1474 }
1475
1476 int sftp_cmd_rm(struct sftp_command *cmd)
1477 {
1478     int i, ret;
1479
1480     if (back == NULL) {
1481         not_connected();
1482         return 0;
1483     }
1484
1485     if (cmd->nwords < 2) {
1486         printf("rm: expects a filename\n");
1487         return 0;
1488     }
1489
1490     ret = 1;
1491     for (i = 1; i < cmd->nwords; i++)
1492         ret &= wildcard_iterate(cmd->words[i], sftp_action_rm, NULL);
1493
1494     return ret;
1495 }
1496
1497 static int check_is_dir(char *dstfname)
1498 {
1499     struct sftp_packet *pktin;
1500     struct sftp_request *req, *rreq;
1501     struct fxp_attrs attrs;
1502     int result;
1503
1504     sftp_register(req = fxp_stat_send(dstfname));
1505     rreq = sftp_find_request(pktin = sftp_recv());
1506     assert(rreq == req);
1507     result = fxp_stat_recv(pktin, rreq, &attrs);
1508
1509     if (result &&
1510         (attrs.flags & SSH_FILEXFER_ATTR_PERMISSIONS) &&
1511         (attrs.permissions & 0040000))
1512         return TRUE;
1513     else
1514         return FALSE;
1515 }
1516
1517 struct sftp_context_mv {
1518     char *dstfname;
1519     int dest_is_dir;
1520 };
1521
1522 static int sftp_action_mv(void *vctx, char *srcfname)
1523 {
1524     struct sftp_context_mv *ctx = (struct sftp_context_mv *)vctx;
1525     struct sftp_packet *pktin;
1526     struct sftp_request *req, *rreq;
1527     const char *error;
1528     char *finalfname, *newcanon = NULL;
1529     int ret, result;
1530
1531     if (ctx->dest_is_dir) {
1532         char *p;
1533         char *newname;
1534
1535         p = srcfname + strlen(srcfname);
1536         while (p > srcfname && p[-1] != '/') p--;
1537         newname = dupcat(ctx->dstfname, "/", p, NULL);
1538         newcanon = canonify(newname);
1539         if (!newcanon) {
1540             printf("%s: %s\n", newname, fxp_error());
1541             sfree(newname);
1542             return 0;
1543         }
1544         sfree(newname);
1545
1546         finalfname = newcanon;
1547     } else {
1548         finalfname = ctx->dstfname;
1549     }
1550
1551     sftp_register(req = fxp_rename_send(srcfname, finalfname));
1552     rreq = sftp_find_request(pktin = sftp_recv());
1553     assert(rreq == req);
1554     result = fxp_rename_recv(pktin, rreq);
1555
1556     error = result ? NULL : fxp_error();
1557
1558     if (error) {
1559         printf("mv %s %s: %s\n", srcfname, finalfname, error);
1560         ret = 0;
1561     } else {
1562         printf("%s -> %s\n", srcfname, finalfname);
1563         ret = 1;
1564     }
1565
1566     sfree(newcanon);
1567     return ret;
1568 }
1569
1570 int sftp_cmd_mv(struct sftp_command *cmd)
1571 {
1572     struct sftp_context_mv actx, *ctx = &actx;
1573     int i, ret;
1574
1575     if (back == NULL) {
1576         not_connected();
1577         return 0;
1578     }
1579
1580     if (cmd->nwords < 3) {
1581         printf("mv: expects two filenames\n");
1582         return 0;
1583     }
1584
1585     ctx->dstfname = canonify(cmd->words[cmd->nwords-1]);
1586     if (!ctx->dstfname) {
1587         printf("%s: %s\n", ctx->dstfname, fxp_error());
1588         return 0;
1589     }
1590
1591     /*
1592      * If there's more than one source argument, or one source
1593      * argument which is a wildcard, we _require_ that the
1594      * destination is a directory.
1595      */
1596     ctx->dest_is_dir = check_is_dir(ctx->dstfname);
1597     if ((cmd->nwords > 3 || is_wildcard(cmd->words[1])) && !ctx->dest_is_dir) {
1598         printf("mv: multiple or wildcard arguments require the destination"
1599                " to be a directory\n");
1600         sfree(ctx->dstfname);
1601         return 0;
1602     }
1603
1604     /*
1605      * Now iterate over the source arguments.
1606      */
1607     ret = 1;
1608     for (i = 1; i < cmd->nwords-1; i++)
1609         ret &= wildcard_iterate(cmd->words[i], sftp_action_mv, ctx);
1610
1611     sfree(ctx->dstfname);
1612     return ret;
1613 }
1614
1615 struct sftp_context_chmod {
1616     unsigned attrs_clr, attrs_xor;
1617 };
1618
1619 static int sftp_action_chmod(void *vctx, char *fname)
1620 {
1621     struct fxp_attrs attrs;
1622     struct sftp_packet *pktin;
1623     struct sftp_request *req, *rreq;
1624     int result;
1625     unsigned oldperms, newperms;
1626     struct sftp_context_chmod *ctx = (struct sftp_context_chmod *)vctx;
1627
1628     sftp_register(req = fxp_stat_send(fname));
1629     rreq = sftp_find_request(pktin = sftp_recv());
1630     assert(rreq == req);
1631     result = fxp_stat_recv(pktin, rreq, &attrs);
1632
1633     if (!result || !(attrs.flags & SSH_FILEXFER_ATTR_PERMISSIONS)) {
1634         printf("get attrs for %s: %s\n", fname,
1635                result ? "file permissions not provided" : fxp_error());
1636         return 0;
1637     }
1638
1639     attrs.flags = SSH_FILEXFER_ATTR_PERMISSIONS;   /* perms _only_ */
1640     oldperms = attrs.permissions & 07777;
1641     attrs.permissions &= ~ctx->attrs_clr;
1642     attrs.permissions ^= ctx->attrs_xor;
1643     newperms = attrs.permissions & 07777;
1644
1645     if (oldperms == newperms)
1646         return 1;                      /* no need to do anything! */
1647
1648     sftp_register(req = fxp_setstat_send(fname, attrs));
1649     rreq = sftp_find_request(pktin = sftp_recv());
1650     assert(rreq == req);
1651     result = fxp_setstat_recv(pktin, rreq);
1652
1653     if (!result) {
1654         printf("set attrs for %s: %s\n", fname, fxp_error());
1655         return 0;
1656     }
1657
1658     printf("%s: %04o -> %04o\n", fname, oldperms, newperms);
1659
1660     return 1;
1661 }
1662
1663 int sftp_cmd_chmod(struct sftp_command *cmd)
1664 {
1665     char *mode;
1666     int i, ret;
1667     struct sftp_context_chmod actx, *ctx = &actx;
1668
1669     if (back == NULL) {
1670         not_connected();
1671         return 0;
1672     }
1673
1674     if (cmd->nwords < 3) {
1675         printf("chmod: expects a mode specifier and a filename\n");
1676         return 0;
1677     }
1678
1679     /*
1680      * Attempt to parse the mode specifier in cmd->words[1]. We
1681      * don't support the full horror of Unix chmod; instead we
1682      * support a much simpler syntax in which the user can either
1683      * specify an octal number, or a comma-separated sequence of
1684      * [ugoa]*[-+=][rwxst]+. (The initial [ugoa] sequence may
1685      * _only_ be omitted if the only attribute mentioned is t,
1686      * since all others require a user/group/other specification.
1687      * Additionally, the s attribute may not be specified for any
1688      * [ugoa] specifications other than exactly u or exactly g.
1689      */
1690     ctx->attrs_clr = ctx->attrs_xor = 0;
1691     mode = cmd->words[1];
1692     if (mode[0] >= '0' && mode[0] <= '9') {
1693         if (mode[strspn(mode, "01234567")]) {
1694             printf("chmod: numeric file modes should"
1695                    " contain digits 0-7 only\n");
1696             return 0;
1697         }
1698         ctx->attrs_clr = 07777;
1699         sscanf(mode, "%o", &ctx->attrs_xor);
1700         ctx->attrs_xor &= ctx->attrs_clr;
1701     } else {
1702         while (*mode) {
1703             char *modebegin = mode;
1704             unsigned subset, perms;
1705             int action;
1706
1707             subset = 0;
1708             while (*mode && *mode != ',' &&
1709                    *mode != '+' && *mode != '-' && *mode != '=') {
1710                 switch (*mode) {
1711                   case 'u': subset |= 04700; break; /* setuid, user perms */
1712                   case 'g': subset |= 02070; break; /* setgid, group perms */
1713                   case 'o': subset |= 00007; break; /* just other perms */
1714                   case 'a': subset |= 06777; break; /* all of the above */
1715                   default:
1716                     printf("chmod: file mode '%.*s' contains unrecognised"
1717                            " user/group/other specifier '%c'\n",
1718                            (int)strcspn(modebegin, ","), modebegin, *mode);
1719                     return 0;
1720                 }
1721                 mode++;
1722             }
1723             if (!*mode || *mode == ',') {
1724                 printf("chmod: file mode '%.*s' is incomplete\n",
1725                        (int)strcspn(modebegin, ","), modebegin);
1726                 return 0;
1727             }
1728             action = *mode++;
1729             if (!*mode || *mode == ',') {
1730                 printf("chmod: file mode '%.*s' is incomplete\n",
1731                        (int)strcspn(modebegin, ","), modebegin);
1732                 return 0;
1733             }
1734             perms = 0;
1735             while (*mode && *mode != ',') {
1736                 switch (*mode) {
1737                   case 'r': perms |= 00444; break;
1738                   case 'w': perms |= 00222; break;
1739                   case 'x': perms |= 00111; break;
1740                   case 't': perms |= 01000; subset |= 01000; break;
1741                   case 's':
1742                     if ((subset & 06777) != 04700 &&
1743                         (subset & 06777) != 02070) {
1744                         printf("chmod: file mode '%.*s': set[ug]id bit should"
1745                                " be used with exactly one of u or g only\n",
1746                                (int)strcspn(modebegin, ","), modebegin);
1747                         return 0;
1748                     }
1749                     perms |= 06000;
1750                     break;
1751                   default:
1752                     printf("chmod: file mode '%.*s' contains unrecognised"
1753                            " permission specifier '%c'\n",
1754                            (int)strcspn(modebegin, ","), modebegin, *mode);
1755                     return 0;
1756                 }
1757                 mode++;
1758             }
1759             if (!(subset & 06777) && (perms &~ subset)) {
1760                 printf("chmod: file mode '%.*s' contains no user/group/other"
1761                        " specifier and permissions other than 't' \n",
1762                        (int)strcspn(modebegin, ","), modebegin);
1763                 return 0;
1764             }
1765             perms &= subset;
1766             switch (action) {
1767               case '+':
1768                 ctx->attrs_clr |= perms;
1769                 ctx->attrs_xor |= perms;
1770                 break;
1771               case '-':
1772                 ctx->attrs_clr |= perms;
1773                 ctx->attrs_xor &= ~perms;
1774                 break;
1775               case '=':
1776                 ctx->attrs_clr |= subset;
1777                 ctx->attrs_xor |= perms;
1778                 break;
1779             }
1780             if (*mode) mode++;         /* eat comma */
1781         }
1782     }
1783
1784     ret = 1;
1785     for (i = 2; i < cmd->nwords; i++)
1786         ret &= wildcard_iterate(cmd->words[i], sftp_action_chmod, ctx);
1787
1788     return ret;
1789 }
1790
1791 static int sftp_cmd_open(struct sftp_command *cmd)
1792 {
1793     int portnumber;
1794
1795     if (back != NULL) {
1796         printf("psftp: already connected\n");
1797         return 0;
1798     }
1799
1800     if (cmd->nwords < 2) {
1801         printf("open: expects a host name\n");
1802         return 0;
1803     }
1804
1805     if (cmd->nwords > 2) {
1806         portnumber = atoi(cmd->words[2]);
1807         if (portnumber == 0) {
1808             printf("open: invalid port number\n");
1809             return 0;
1810         }
1811     } else
1812         portnumber = 0;
1813
1814     if (psftp_connect(cmd->words[1], NULL, portnumber)) {
1815         back = NULL;                   /* connection is already closed */
1816         return -1;                     /* this is fatal */
1817     }
1818     do_sftp_init();
1819     return 1;
1820 }
1821
1822 static int sftp_cmd_lcd(struct sftp_command *cmd)
1823 {
1824     char *currdir, *errmsg;
1825
1826     if (cmd->nwords < 2) {
1827         printf("lcd: expects a local directory name\n");
1828         return 0;
1829     }
1830
1831     errmsg = psftp_lcd(cmd->words[1]);
1832     if (errmsg) {
1833         printf("lcd: unable to change directory: %s\n", errmsg);
1834         sfree(errmsg);
1835         return 0;
1836     }
1837
1838     currdir = psftp_getcwd();
1839     printf("New local directory is %s\n", currdir);
1840     sfree(currdir);
1841
1842     return 1;
1843 }
1844
1845 static int sftp_cmd_lpwd(struct sftp_command *cmd)
1846 {
1847     char *currdir;
1848
1849     currdir = psftp_getcwd();
1850     printf("Current local directory is %s\n", currdir);
1851     sfree(currdir);
1852
1853     return 1;
1854 }
1855
1856 static int sftp_cmd_pling(struct sftp_command *cmd)
1857 {
1858     int exitcode;
1859
1860     exitcode = system(cmd->words[1]);
1861     return (exitcode == 0);
1862 }
1863
1864 static int sftp_cmd_help(struct sftp_command *cmd);
1865
1866 static struct sftp_cmd_lookup {
1867     char *name;
1868     /*
1869      * For help purposes, there are two kinds of command:
1870      * 
1871      *  - primary commands, in which `longhelp' is non-NULL. In
1872      *    this case `shorthelp' is descriptive text, and `longhelp'
1873      *    is longer descriptive text intended to be printed after
1874      *    the command name.
1875      * 
1876      *  - alias commands, in which `longhelp' is NULL. In this case
1877      *    `shorthelp' is the name of a primary command, which
1878      *    contains the help that should double up for this command.
1879      */
1880     int listed;                        /* do we list this in primary help? */
1881     char *shorthelp;
1882     char *longhelp;
1883     int (*obey) (struct sftp_command *);
1884 } sftp_lookup[] = {
1885     /*
1886      * List of sftp commands. This is binary-searched so it MUST be
1887      * in ASCII order.
1888      */
1889     {
1890         "!", TRUE, "run a local command",
1891             "<command>\n"
1892             /* FIXME: this example is crap for non-Windows. */
1893             "  Runs a local command. For example, \"!del myfile\".\n",
1894             sftp_cmd_pling
1895     },
1896     {
1897         "bye", TRUE, "finish your SFTP session",
1898             "\n"
1899             "  Terminates your SFTP session and quits the PSFTP program.\n",
1900             sftp_cmd_quit
1901     },
1902     {
1903         "cd", TRUE, "change your remote working directory",
1904             " [ <new working directory> ]\n"
1905             "  Change the remote working directory for your SFTP session.\n"
1906             "  If a new working directory is not supplied, you will be\n"
1907             "  returned to your home directory.\n",
1908             sftp_cmd_cd
1909     },
1910     {
1911         "chmod", TRUE, "change file permissions and modes",
1912             " <modes> <filename-or-wildcard> [ <filename-or-wildcard>... ]\n"
1913             "  Change the file permissions on one or more remote files or\n"
1914             "  directories.\n"
1915             "  <modes> can be any octal Unix permission specifier.\n"
1916             "  Alternatively, <modes> can include the following modifiers:\n"
1917             "    u+r     make file readable by owning user\n"
1918             "    u+w     make file writable by owning user\n"
1919             "    u+x     make file executable by owning user\n"
1920             "    u-r     make file not readable by owning user\n"
1921             "    [also u-w, u-x]\n"
1922             "    g+r     make file readable by members of owning group\n"
1923             "    [also g+w, g+x, g-r, g-w, g-x]\n"
1924             "    o+r     make file readable by all other users\n"
1925             "    [also o+w, o+x, o-r, o-w, o-x]\n"
1926             "    a+r     make file readable by absolutely everybody\n"
1927             "    [also a+w, a+x, a-r, a-w, a-x]\n"
1928             "    u+s     enable the Unix set-user-ID bit\n"
1929             "    u-s     disable the Unix set-user-ID bit\n"
1930             "    g+s     enable the Unix set-group-ID bit\n"
1931             "    g-s     disable the Unix set-group-ID bit\n"
1932             "    +t      enable the Unix \"sticky bit\"\n"
1933             "  You can give more than one modifier for the same user (\"g-rwx\"), and\n"
1934             "  more than one user for the same modifier (\"ug+w\"). You can\n"
1935             "  use commas to separate different modifiers (\"u+rwx,g+s\").\n",
1936             sftp_cmd_chmod
1937     },
1938     {
1939         "close", TRUE, "finish your SFTP session but do not quit PSFTP",
1940             "\n"
1941             "  Terminates your SFTP session, but does not quit the PSFTP\n"
1942             "  program. You can then use \"open\" to start another SFTP\n"
1943             "  session, to the same server or to a different one.\n",
1944             sftp_cmd_close
1945     },
1946     {
1947         "del", TRUE, "delete files on the remote server",
1948             " <filename-or-wildcard> [ <filename-or-wildcard>... ]\n"
1949             "  Delete a file or files from the server.\n",
1950             sftp_cmd_rm
1951     },
1952     {
1953         "delete", FALSE, "del", NULL, sftp_cmd_rm
1954     },
1955     {
1956         "dir", TRUE, "list remote files",
1957             " [ <directory-name> ]/[ <wildcard> ]\n"
1958             "  List the contents of a specified directory on the server.\n"
1959             "  If <directory-name> is not given, the current working directory\n"
1960             "  is assumed.\n"
1961             "  If <wildcard> is given, it is treated as a set of files to\n"
1962             "  list; otherwise, all files are listed.\n",
1963             sftp_cmd_ls
1964     },
1965     {
1966         "exit", TRUE, "bye", NULL, sftp_cmd_quit
1967     },
1968     {
1969         "get", TRUE, "download a file from the server to your local machine",
1970             " [ -r ] [ -- ] <filename> [ <local-filename> ]\n"
1971             "  Downloads a file on the server and stores it locally under\n"
1972             "  the same name, or under a different one if you supply the\n"
1973             "  argument <local-filename>.\n"
1974             "  If -r specified, recursively fetch a directory.\n",
1975             sftp_cmd_get
1976     },
1977     {
1978         "help", TRUE, "give help",
1979             " [ <command> [ <command> ... ] ]\n"
1980             "  Give general help if no commands are specified.\n"
1981             "  If one or more commands are specified, give specific help on\n"
1982             "  those particular commands.\n",
1983             sftp_cmd_help
1984     },
1985     {
1986         "lcd", TRUE, "change local working directory",
1987             " <local-directory-name>\n"
1988             "  Change the local working directory of the PSFTP program (the\n"
1989             "  default location where the \"get\" command will save files).\n",
1990             sftp_cmd_lcd
1991     },
1992     {
1993         "lpwd", TRUE, "print local working directory",
1994             "\n"
1995             "  Print the local working directory of the PSFTP program (the\n"
1996             "  default location where the \"get\" command will save files).\n",
1997             sftp_cmd_lpwd
1998     },
1999     {
2000         "ls", TRUE, "dir", NULL,
2001             sftp_cmd_ls
2002     },
2003     {
2004         "mget", TRUE, "download multiple files at once",
2005             " [ -r ] [ -- ] <filename-or-wildcard> [ <filename-or-wildcard>... ]\n"
2006             "  Downloads many files from the server, storing each one under\n"
2007             "  the same name it has on the server side. You can use wildcards\n"
2008             "  such as \"*.c\" to specify lots of files at once.\n"
2009             "  If -r specified, recursively fetch files and directories.\n",
2010             sftp_cmd_mget
2011     },
2012     {
2013         "mkdir", TRUE, "create directories on the remote server",
2014             " <directory-name> [ <directory-name>... ]\n"
2015             "  Creates directories with the given names on the server.\n",
2016             sftp_cmd_mkdir
2017     },
2018     {
2019         "mput", TRUE, "upload multiple files at once",
2020             " [ -r ] [ -- ] <filename-or-wildcard> [ <filename-or-wildcard>... ]\n"
2021             "  Uploads many files to the server, storing each one under the\n"
2022             "  same name it has on the client side. You can use wildcards\n"
2023             "  such as \"*.c\" to specify lots of files at once.\n"
2024             "  If -r specified, recursively store files and directories.\n",
2025             sftp_cmd_mput
2026     },
2027     {
2028         "mv", TRUE, "move or rename file(s) on the remote server",
2029             " <source> [ <source>... ] <destination>\n"
2030             "  Moves or renames <source>(s) on the server to <destination>,\n"
2031             "  also on the server.\n"
2032             "  If <destination> specifies an existing directory, then <source>\n"
2033             "  may be a wildcard, and multiple <source>s may be given; all\n"
2034             "  source files are moved into <destination>.\n"
2035             "  Otherwise, <source> must specify a single file, which is moved\n"
2036             "  or renamed so that it is accessible under the name <destination>.\n",
2037             sftp_cmd_mv
2038     },
2039     {
2040         "open", TRUE, "connect to a host",
2041             " [<user>@]<hostname> [<port>]\n"
2042             "  Establishes an SFTP connection to a given host. Only usable\n"
2043             "  when you are not already connected to a server.\n",
2044             sftp_cmd_open
2045     },
2046     {
2047         "put", TRUE, "upload a file from your local machine to the server",
2048             " [ -r ] [ -- ] <filename> [ <remote-filename> ]\n"
2049             "  Uploads a file to the server and stores it there under\n"
2050             "  the same name, or under a different one if you supply the\n"
2051             "  argument <remote-filename>.\n"
2052             "  If -r specified, recursively store a directory.\n",
2053             sftp_cmd_put
2054     },
2055     {
2056         "pwd", TRUE, "print your remote working directory",
2057             "\n"
2058             "  Print the current remote working directory for your SFTP session.\n",
2059             sftp_cmd_pwd
2060     },
2061     {
2062         "quit", TRUE, "bye", NULL,
2063             sftp_cmd_quit
2064     },
2065     {
2066         "reget", TRUE, "continue downloading files",
2067             " [ -r ] [ -- ] <filename> [ <local-filename> ]\n"
2068             "  Works exactly like the \"get\" command, but the local file\n"
2069             "  must already exist. The download will begin at the end of the\n"
2070             "  file. This is for resuming a download that was interrupted.\n"
2071             "  If -r specified, resume interrupted \"get -r\".\n",
2072             sftp_cmd_reget
2073     },
2074     {
2075         "ren", TRUE, "mv", NULL,
2076             sftp_cmd_mv
2077     },
2078     {
2079         "rename", FALSE, "mv", NULL,
2080             sftp_cmd_mv
2081     },
2082     {
2083         "reput", TRUE, "continue uploading files",
2084             " [ -r ] [ -- ] <filename> [ <remote-filename> ]\n"
2085             "  Works exactly like the \"put\" command, but the remote file\n"
2086             "  must already exist. The upload will begin at the end of the\n"
2087             "  file. This is for resuming an upload that was interrupted.\n"
2088             "  If -r specified, resume interrupted \"put -r\".\n",
2089             sftp_cmd_reput
2090     },
2091     {
2092         "rm", TRUE, "del", NULL,
2093             sftp_cmd_rm
2094     },
2095     {
2096         "rmdir", TRUE, "remove directories on the remote server",
2097             " <directory-name> [ <directory-name>... ]\n"
2098             "  Removes the directory with the given name on the server.\n"
2099             "  The directory will not be removed unless it is empty.\n"
2100             "  Wildcards may be used to specify multiple directories.\n",
2101             sftp_cmd_rmdir
2102     }
2103 };
2104
2105 const struct sftp_cmd_lookup *lookup_command(char *name)
2106 {
2107     int i, j, k, cmp;
2108
2109     i = -1;
2110     j = sizeof(sftp_lookup) / sizeof(*sftp_lookup);
2111     while (j - i > 1) {
2112         k = (j + i) / 2;
2113         cmp = strcmp(name, sftp_lookup[k].name);
2114         if (cmp < 0)
2115             j = k;
2116         else if (cmp > 0)
2117             i = k;
2118         else {
2119             return &sftp_lookup[k];
2120         }
2121     }
2122     return NULL;
2123 }
2124
2125 static int sftp_cmd_help(struct sftp_command *cmd)
2126 {
2127     int i;
2128     if (cmd->nwords == 1) {
2129         /*
2130          * Give short help on each command.
2131          */
2132         int maxlen;
2133         maxlen = 0;
2134         for (i = 0; i < sizeof(sftp_lookup) / sizeof(*sftp_lookup); i++) {
2135             int len;
2136             if (!sftp_lookup[i].listed)
2137                 continue;
2138             len = strlen(sftp_lookup[i].name);
2139             if (maxlen < len)
2140                 maxlen = len;
2141         }
2142         for (i = 0; i < sizeof(sftp_lookup) / sizeof(*sftp_lookup); i++) {
2143             const struct sftp_cmd_lookup *lookup;
2144             if (!sftp_lookup[i].listed)
2145                 continue;
2146             lookup = &sftp_lookup[i];
2147             printf("%-*s", maxlen+2, lookup->name);
2148             if (lookup->longhelp == NULL)
2149                 lookup = lookup_command(lookup->shorthelp);
2150             printf("%s\n", lookup->shorthelp);
2151         }
2152     } else {
2153         /*
2154          * Give long help on specific commands.
2155          */
2156         for (i = 1; i < cmd->nwords; i++) {
2157             const struct sftp_cmd_lookup *lookup;
2158             lookup = lookup_command(cmd->words[i]);
2159             if (!lookup) {
2160                 printf("help: %s: command not found\n", cmd->words[i]);
2161             } else {
2162                 printf("%s", lookup->name);
2163                 if (lookup->longhelp == NULL)
2164                     lookup = lookup_command(lookup->shorthelp);
2165                 printf("%s", lookup->longhelp);
2166             }
2167         }
2168     }
2169     return 1;
2170 }
2171
2172 /* ----------------------------------------------------------------------
2173  * Command line reading and parsing.
2174  */
2175 struct sftp_command *sftp_getcmd(FILE *fp, int mode, int modeflags)
2176 {
2177     char *line;
2178     struct sftp_command *cmd;
2179     char *p, *q, *r;
2180     int quoting;
2181
2182     cmd = snew(struct sftp_command);
2183     cmd->words = NULL;
2184     cmd->nwords = 0;
2185     cmd->wordssize = 0;
2186
2187     line = NULL;
2188
2189     if (fp) {
2190         if (modeflags & 1)
2191             printf("psftp> ");
2192         line = fgetline(fp);
2193     } else {
2194         line = ssh_sftp_get_cmdline("psftp> ", back == NULL);
2195     }
2196
2197     if (!line || !*line) {
2198         cmd->obey = sftp_cmd_quit;
2199         if ((mode == 0) || (modeflags & 1))
2200             printf("quit\n");
2201         return cmd;                    /* eof */
2202     }
2203
2204     line[strcspn(line, "\r\n")] = '\0';
2205
2206     if (modeflags & 1) {
2207         printf("%s\n", line);
2208     }
2209
2210     p = line;
2211     while (*p && (*p == ' ' || *p == '\t'))
2212         p++;
2213
2214     if (*p == '!') {
2215         /*
2216          * Special case: the ! command. This is always parsed as
2217          * exactly two words: one containing the !, and the second
2218          * containing everything else on the line.
2219          */
2220         cmd->nwords = cmd->wordssize = 2;
2221         cmd->words = sresize(cmd->words, cmd->wordssize, char *);
2222         cmd->words[0] = dupstr("!");
2223         cmd->words[1] = dupstr(p+1);
2224     } else {
2225
2226         /*
2227          * Parse the command line into words. The syntax is:
2228          *  - double quotes are removed, but cause spaces within to be
2229          *    treated as non-separating.
2230          *  - a double-doublequote pair is a literal double quote, inside
2231          *    _or_ outside quotes. Like this:
2232          *
2233          *      firstword "second word" "this has ""quotes"" in" and""this""
2234          *
2235          * becomes
2236          *
2237          *      >firstword<
2238          *      >second word<
2239          *      >this has "quotes" in<
2240          *      >and"this"<
2241          */
2242         while (*p) {
2243             /* skip whitespace */
2244             while (*p && (*p == ' ' || *p == '\t'))
2245                 p++;
2246             /* mark start of word */
2247             q = r = p;                 /* q sits at start, r writes word */
2248             quoting = 0;
2249             while (*p) {
2250                 if (!quoting && (*p == ' ' || *p == '\t'))
2251                     break;                     /* reached end of word */
2252                 else if (*p == '"' && p[1] == '"')
2253                     p += 2, *r++ = '"';    /* a literal quote */
2254                 else if (*p == '"')
2255                     p++, quoting = !quoting;
2256                 else
2257                     *r++ = *p++;
2258             }
2259             if (*p)
2260                 p++;                   /* skip over the whitespace */
2261             *r = '\0';
2262             if (cmd->nwords >= cmd->wordssize) {
2263                 cmd->wordssize = cmd->nwords + 16;
2264                 cmd->words = sresize(cmd->words, cmd->wordssize, char *);
2265             }
2266             cmd->words[cmd->nwords++] = dupstr(q);
2267         }
2268     }
2269
2270     sfree(line);
2271
2272     /*
2273      * Now parse the first word and assign a function.
2274      */
2275
2276     if (cmd->nwords == 0)
2277         cmd->obey = sftp_cmd_null;
2278     else {
2279         const struct sftp_cmd_lookup *lookup;
2280         lookup = lookup_command(cmd->words[0]);
2281         if (!lookup)
2282             cmd->obey = sftp_cmd_unknown;
2283         else
2284             cmd->obey = lookup->obey;
2285     }
2286
2287     return cmd;
2288 }
2289
2290 static int do_sftp_init(void)
2291 {
2292     struct sftp_packet *pktin;
2293     struct sftp_request *req, *rreq;
2294
2295     /*
2296      * Do protocol initialisation. 
2297      */
2298     if (!fxp_init()) {
2299         fprintf(stderr,
2300                 "Fatal: unable to initialise SFTP: %s\n", fxp_error());
2301         return 1;                      /* failure */
2302     }
2303
2304     /*
2305      * Find out where our home directory is.
2306      */
2307     sftp_register(req = fxp_realpath_send("."));
2308     rreq = sftp_find_request(pktin = sftp_recv());
2309     assert(rreq == req);
2310     homedir = fxp_realpath_recv(pktin, rreq);
2311
2312     if (!homedir) {
2313         fprintf(stderr,
2314                 "Warning: failed to resolve home directory: %s\n",
2315                 fxp_error());
2316         homedir = dupstr(".");
2317     } else {
2318         printf("Remote working directory is %s\n", homedir);
2319     }
2320     pwd = dupstr(homedir);
2321     return 0;
2322 }
2323
2324 void do_sftp_cleanup()
2325 {
2326     char ch;
2327     if (back) {
2328         back->special(backhandle, TS_EOF);
2329         sftp_recvdata(&ch, 1);
2330         back->free(backhandle);
2331         sftp_cleanup_request();
2332         back = NULL;
2333         backhandle = NULL;
2334     }
2335     if (pwd) {
2336         sfree(pwd);
2337         pwd = NULL;
2338     }
2339     if (homedir) {
2340         sfree(homedir);
2341         homedir = NULL;
2342     }
2343 }
2344
2345 void do_sftp(int mode, int modeflags, char *batchfile)
2346 {
2347     FILE *fp;
2348     int ret;
2349
2350     /*
2351      * Batch mode?
2352      */
2353     if (mode == 0) {
2354
2355         /* ------------------------------------------------------------------
2356          * Now we're ready to do Real Stuff.
2357          */
2358         while (1) {
2359             struct sftp_command *cmd;
2360             cmd = sftp_getcmd(NULL, 0, 0);
2361             if (!cmd)
2362                 break;
2363             ret = cmd->obey(cmd);
2364             if (cmd->words) {
2365                 int i;
2366                 for(i = 0; i < cmd->nwords; i++)
2367                     sfree(cmd->words[i]);
2368                 sfree(cmd->words);
2369             }
2370             sfree(cmd);
2371             if (ret < 0)
2372                 break;
2373         }
2374     } else {
2375         fp = fopen(batchfile, "r");
2376         if (!fp) {
2377             printf("Fatal: unable to open %s\n", batchfile);
2378             return;
2379         }
2380         while (1) {
2381             struct sftp_command *cmd;
2382             cmd = sftp_getcmd(fp, mode, modeflags);
2383             if (!cmd)
2384                 break;
2385             ret = cmd->obey(cmd);
2386             if (ret < 0)
2387                 break;
2388             if (ret == 0) {
2389                 if (!(modeflags & 2))
2390                     break;
2391             }
2392         }
2393         fclose(fp);
2394
2395     }
2396 }
2397
2398 /* ----------------------------------------------------------------------
2399  * Dirty bits: integration with PuTTY.
2400  */
2401
2402 static int verbose = 0;
2403
2404 /*
2405  *  Print an error message and perform a fatal exit.
2406  */
2407 void fatalbox(char *fmt, ...)
2408 {
2409     char *str, *str2;
2410     va_list ap;
2411     va_start(ap, fmt);
2412     str = dupvprintf(fmt, ap);
2413     str2 = dupcat("Fatal: ", str, "\n", NULL);
2414     sfree(str);
2415     va_end(ap);
2416     fputs(str2, stderr);
2417     sfree(str2);
2418
2419     cleanup_exit(1);
2420 }
2421 void modalfatalbox(char *fmt, ...)
2422 {
2423     char *str, *str2;
2424     va_list ap;
2425     va_start(ap, fmt);
2426     str = dupvprintf(fmt, ap);
2427     str2 = dupcat("Fatal: ", str, "\n", NULL);
2428     sfree(str);
2429     va_end(ap);
2430     fputs(str2, stderr);
2431     sfree(str2);
2432
2433     cleanup_exit(1);
2434 }
2435 void connection_fatal(void *frontend, char *fmt, ...)
2436 {
2437     char *str, *str2;
2438     va_list ap;
2439     va_start(ap, fmt);
2440     str = dupvprintf(fmt, ap);
2441     str2 = dupcat("Fatal: ", str, "\n", NULL);
2442     sfree(str);
2443     va_end(ap);
2444     fputs(str2, stderr);
2445     sfree(str2);
2446
2447     cleanup_exit(1);
2448 }
2449
2450 void ldisc_send(void *handle, char *buf, int len, int interactive)
2451 {
2452     /*
2453      * This is only here because of the calls to ldisc_send(NULL,
2454      * 0) in ssh.c. Nothing in PSFTP actually needs to use the
2455      * ldisc as an ldisc. So if we get called with any real data, I
2456      * want to know about it.
2457      */
2458     assert(len == 0);
2459 }
2460
2461 /*
2462  * In psftp, all agent requests should be synchronous, so this is a
2463  * never-called stub.
2464  */
2465 void agent_schedule_callback(void (*callback)(void *, void *, int),
2466                              void *callback_ctx, void *data, int len)
2467 {
2468     assert(!"We shouldn't be here");
2469 }
2470
2471 /*
2472  * Receive a block of data from the SSH link. Block until all data
2473  * is available.
2474  *
2475  * To do this, we repeatedly call the SSH protocol module, with our
2476  * own trap in from_backend() to catch the data that comes back. We
2477  * do this until we have enough data.
2478  */
2479
2480 static unsigned char *outptr;          /* where to put the data */
2481 static unsigned outlen;                /* how much data required */
2482 static unsigned char *pending = NULL;  /* any spare data */
2483 static unsigned pendlen = 0, pendsize = 0;      /* length and phys. size of buffer */
2484 int from_backend(void *frontend, int is_stderr, const char *data, int datalen)
2485 {
2486     unsigned char *p = (unsigned char *) data;
2487     unsigned len = (unsigned) datalen;
2488
2489     /*
2490      * stderr data is just spouted to local stderr and otherwise
2491      * ignored.
2492      */
2493     if (is_stderr) {
2494         if (len > 0)
2495             fwrite(data, 1, len, stderr);
2496         return 0;
2497     }
2498
2499     /*
2500      * If this is before the real session begins, just return.
2501      */
2502     if (!outptr)
2503         return 0;
2504
2505     if ((outlen > 0) && (len > 0)) {
2506         unsigned used = outlen;
2507         if (used > len)
2508             used = len;
2509         memcpy(outptr, p, used);
2510         outptr += used;
2511         outlen -= used;
2512         p += used;
2513         len -= used;
2514     }
2515
2516     if (len > 0) {
2517         if (pendsize < pendlen + len) {
2518             pendsize = pendlen + len + 4096;
2519             pending = sresize(pending, pendsize, unsigned char);
2520         }
2521         memcpy(pending + pendlen, p, len);
2522         pendlen += len;
2523     }
2524
2525     return 0;
2526 }
2527 int sftp_recvdata(char *buf, int len)
2528 {
2529     outptr = (unsigned char *) buf;
2530     outlen = len;
2531
2532     /*
2533      * See if the pending-input block contains some of what we
2534      * need.
2535      */
2536     if (pendlen > 0) {
2537         unsigned pendused = pendlen;
2538         if (pendused > outlen)
2539             pendused = outlen;
2540         memcpy(outptr, pending, pendused);
2541         memmove(pending, pending + pendused, pendlen - pendused);
2542         outptr += pendused;
2543         outlen -= pendused;
2544         pendlen -= pendused;
2545         if (pendlen == 0) {
2546             pendsize = 0;
2547             sfree(pending);
2548             pending = NULL;
2549         }
2550         if (outlen == 0)
2551             return 1;
2552     }
2553
2554     while (outlen > 0) {
2555         if (ssh_sftp_loop_iteration() < 0)
2556             return 0;                  /* doom */
2557     }
2558
2559     return 1;
2560 }
2561 int sftp_senddata(char *buf, int len)
2562 {
2563     back->send(backhandle, buf, len);
2564     return 1;
2565 }
2566
2567 /*
2568  *  Short description of parameters.
2569  */
2570 static void usage(void)
2571 {
2572     printf("PuTTY Secure File Transfer (SFTP) client\n");
2573     printf("%s\n", ver);
2574     printf("Usage: psftp [options] [user@]host\n");
2575     printf("Options:\n");
2576     printf("  -b file   use specified batchfile\n");
2577     printf("  -bc       output batchfile commands\n");
2578     printf("  -be       don't stop batchfile processing if errors\n");
2579     printf("  -v        show verbose messages\n");
2580     printf("  -load sessname  Load settings from saved session\n");
2581     printf("  -l user   connect with specified username\n");
2582     printf("  -P port   connect to specified port\n");
2583     printf("  -pw passw login with specified password\n");
2584     printf("  -1 -2     force use of particular SSH protocol version\n");
2585     printf("  -4 -6     force use of IPv4 or IPv6\n");
2586     printf("  -C        enable compression\n");
2587     printf("  -i key    private key file for authentication\n");
2588     printf("  -batch    disable all interactive prompts\n");
2589     printf("  -V        print version information\n");
2590     cleanup_exit(1);
2591 }
2592
2593 static void version(void)
2594 {
2595   printf("psftp: %s\n", ver);
2596   cleanup_exit(1);
2597 }
2598
2599 /*
2600  * Connect to a host.
2601  */
2602 static int psftp_connect(char *userhost, char *user, int portnumber)
2603 {
2604     char *host, *realhost;
2605     const char *err;
2606     void *logctx;
2607
2608     /* Separate host and username */
2609     host = userhost;
2610     host = strrchr(host, '@');
2611     if (host == NULL) {
2612         host = userhost;
2613     } else {
2614         *host++ = '\0';
2615         if (user) {
2616             printf("psftp: multiple usernames specified; using \"%s\"\n",
2617                    user);
2618         } else
2619             user = userhost;
2620     }
2621
2622     /*
2623      * If we haven't loaded session details already (e.g., from -load),
2624      * try looking for a session called "host".
2625      */
2626     if (!loaded_session) {
2627         /* Try to load settings for `host' into a temporary config */
2628         Config cfg2;
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);
2635         } else {
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';
2640         }
2641     } else {
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';
2645     }
2646
2647     /*
2648      * Force use of SSH. (If they got the protocol wrong we assume the
2649      * port is useless too.)
2650      */
2651     if (cfg.protocol != PROT_SSH) {
2652         cfg.protocol = PROT_SSH;
2653         cfg.port = 22;
2654     }
2655
2656     /*
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.
2661      */
2662     if (cfg.sshprot != 2 && cfg.sshprot != 3)
2663         cfg.sshprot = 2;
2664
2665     /*
2666      * Enact command-line overrides.
2667      */
2668     cmdline_run_saved(&cfg);
2669
2670     /*
2671      * Trim leading whitespace off the hostname if it's there.
2672      */
2673     {
2674         int space = strspn(cfg.host, " \t");
2675         memmove(cfg.host, cfg.host+space, 1+strlen(cfg.host)-space);
2676     }
2677
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 */
2682         if (atsign) {
2683             if (atsign - cfg.host < sizeof cfg.username) {
2684                 strncpy(cfg.username, cfg.host, atsign - cfg.host);
2685                 cfg.username[atsign - cfg.host] = '\0';
2686             }
2687             memmove(cfg.host, atsign + 1, 1 + strlen(atsign + 1));
2688         }
2689     }
2690
2691     /*
2692      * Trim a colon suffix off the hostname if it's there.
2693      */
2694     cfg.host[strcspn(cfg.host, ":")] = '\0';
2695
2696     /*
2697      * Remove any remaining whitespace from the hostname.
2698      */
2699     {
2700         int p1 = 0, p2 = 0;
2701         while (cfg.host[p2] != '\0') {
2702             if (cfg.host[p2] != ' ' && cfg.host[p2] != '\t') {
2703                 cfg.host[p1] = cfg.host[p2];
2704                 p1++;
2705             }
2706             p2++;
2707         }
2708         cfg.host[p1] = '\0';
2709     }
2710
2711     /* Set username */
2712     if (user != NULL && user[0] != '\0') {
2713         strncpy(cfg.username, user, sizeof(cfg.username) - 1);
2714         cfg.username[sizeof(cfg.username) - 1] = '\0';
2715     }
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");
2720             cleanup_exit(1);
2721         } else {
2722             int len = strlen(cfg.username);
2723             if (cfg.username[len - 1] == '\n')
2724                 cfg.username[len - 1] = '\0';
2725         }
2726     }
2727
2728     if (portnumber)
2729         cfg.port = portnumber;
2730
2731     /*
2732      * Disable scary things which shouldn't be enabled for simple
2733      * things like SCP and SFTP: agent forwarding, port forwarding,
2734      * X forwarding.
2735      */
2736     cfg.x11_forward = 0;
2737     cfg.agentfwd = 0;
2738     cfg.portfwd[0] = cfg.portfwd[1] = '\0';
2739
2740     /* Set up subsystem name. */
2741     strcpy(cfg.remote_cmd, "sftp");
2742     cfg.ssh_subsys = TRUE;
2743     cfg.nopty = TRUE;
2744
2745     /*
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.
2753      * 
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
2756      *   exec sftp-server
2757      * 
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.
2761      */
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"
2765         "exec sftp-server";
2766     cfg.ssh_subsys2 = FALSE;
2767
2768     back = &ssh_backend;
2769
2770     err = back->init(NULL, &backhandle, &cfg, cfg.host, cfg.port, &realhost,
2771                      0, cfg.tcp_keepalives);
2772     if (err != NULL) {
2773         fprintf(stderr, "ssh_init: %s\n", err);
2774         return 1;
2775     }
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");
2782             return 1;
2783         }
2784     }
2785     if (verbose && realhost != NULL)
2786         printf("Connected to %s\n", realhost);
2787     if (realhost != NULL)
2788         sfree(realhost);
2789     return 0;
2790 }
2791
2792 void cmdline_error(char *p, ...)
2793 {
2794     va_list ap;
2795     fprintf(stderr, "psftp: ");
2796     va_start(ap, p);
2797     vfprintf(stderr, p, ap);
2798     va_end(ap);
2799     fprintf(stderr, "\n       try typing \"psftp -h\" for help\n");
2800     exit(1);
2801 }
2802
2803 /*
2804  * Main program. Parse arguments etc.
2805  */
2806 int psftp_main(int argc, char *argv[])
2807 {
2808     int i;
2809     int portnumber = 0;
2810     char *userhost, *user;
2811     int mode = 0;
2812     int modeflags = 0;
2813     char *batchfile = NULL;
2814     int errors = 0;
2815
2816     flags = FLAG_STDERR | FLAG_INTERACTIVE
2817 #ifdef FLAG_SYNCAGENT
2818         | FLAG_SYNCAGENT
2819 #endif
2820         ;
2821     cmdline_tooltype = TOOLTYPE_FILETRANSFER;
2822     ssh_get_line = &console_get_line;
2823     sk_init();
2824
2825     userhost = user = NULL;
2826
2827     /* Load Default Settings before doing anything else. */
2828     do_defaults(NULL, &cfg);
2829     loaded_session = FALSE;
2830
2831     errors = 0;
2832     for (i = 1; i < argc; i++) {
2833         int ret;
2834         if (argv[i][0] != '-') {
2835             if (userhost)
2836                 usage();
2837             else
2838                 userhost = dupstr(argv[i]);
2839             continue;
2840         }
2841         ret = cmdline_process_param(argv[i], i+1<argc?argv[i+1]:NULL, 1, &cfg);
2842         if (ret == -2) {
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)
2849                 verbose = 1;
2850         } else if (strcmp(argv[i], "-h") == 0 ||
2851                    strcmp(argv[i], "-?") == 0) {
2852             usage();
2853         } else if (strcmp(argv[i], "-V") == 0) {
2854             version();
2855         } else if (strcmp(argv[i], "-batch") == 0) {
2856             console_batch_mode = 1;
2857         } else if (strcmp(argv[i], "-b") == 0 && i + 1 < argc) {
2858             mode = 1;
2859             batchfile = argv[++i];
2860         } else if (strcmp(argv[i], "-bc") == 0) {
2861             modeflags = modeflags | 1;
2862         } else if (strcmp(argv[i], "-be") == 0) {
2863             modeflags = modeflags | 2;
2864         } else if (strcmp(argv[i], "--") == 0) {
2865             i++;
2866             break;
2867         } else {
2868             cmdline_error("unknown option \"%s\"", argv[i]);
2869         }
2870     }
2871     argc -= i;
2872     argv += i;
2873     back = NULL;
2874
2875     /*
2876      * If the loaded session provides a hostname, and a hostname has not
2877      * otherwise been specified, pop it in `userhost' so that
2878      * `psftp -load sessname' is sufficient to start a session.
2879      */
2880     if (!userhost && cfg.host[0] != '\0') {
2881         userhost = dupstr(cfg.host);
2882     }
2883
2884     /*
2885      * If a user@host string has already been provided, connect to
2886      * it now.
2887      */
2888     if (userhost) {
2889         int ret;
2890         ret = psftp_connect(userhost, user, portnumber);
2891         sfree(userhost);
2892         if (ret)
2893             return 1;
2894         if (do_sftp_init())
2895             return 1;
2896     } else {
2897         printf("psftp: no hostname specified; use \"open host.name\""
2898                " to connect\n");
2899     }
2900
2901     do_sftp(mode, modeflags, batchfile);
2902
2903     if (back != NULL && back->socket(backhandle) != NULL) {
2904         char ch;
2905         back->special(backhandle, TS_EOF);
2906         sftp_recvdata(&ch, 1);
2907     }
2908     do_sftp_cleanup();
2909     random_save_seed();
2910     cmdline_cleanup();
2911     console_provide_logctx(NULL);
2912     sk_cleanup();
2913
2914     return 0;
2915 }