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