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