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