]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - psftp.c
Uploads turn out to be much easier than downloads, so here's faster
[PuTTY.git] / psftp.c
1 /*
2  * psftp.c: 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
29 /* ----------------------------------------------------------------------
30  * sftp client state.
31  */
32
33 char *pwd, *homedir;
34 static Backend *back;
35 static void *backhandle;
36 static Config cfg;
37
38 /* ----------------------------------------------------------------------
39  * Higher-level helper functions used in commands.
40  */
41
42 /*
43  * Attempt to canonify a pathname starting from the pwd. If
44  * canonification fails, at least fall back to returning a _valid_
45  * pathname (though it may be ugly, eg /home/simon/../foobar).
46  */
47 char *canonify(char *name)
48 {
49     char *fullname, *canonname;
50     struct sftp_packet *pktin;
51     struct sftp_request *req, *rreq;
52
53     if (name[0] == '/') {
54         fullname = dupstr(name);
55     } else {
56         char *slash;
57         if (pwd[strlen(pwd) - 1] == '/')
58             slash = "";
59         else
60             slash = "/";
61         fullname = dupcat(pwd, slash, name, NULL);
62     }
63
64     sftp_register(req = fxp_realpath_send(fullname));
65     rreq = sftp_find_request(pktin = sftp_recv());
66     assert(rreq == req);
67     canonname = fxp_realpath_recv(pktin, rreq);
68
69     if (canonname) {
70         sfree(fullname);
71         return canonname;
72     } else {
73         /*
74          * Attempt number 2. Some FXP_REALPATH implementations
75          * (glibc-based ones, in particular) require the _whole_
76          * path to point to something that exists, whereas others
77          * (BSD-based) only require all but the last component to
78          * exist. So if the first call failed, we should strip off
79          * everything from the last slash onwards and try again,
80          * then put the final component back on.
81          * 
82          * Special cases:
83          * 
84          *  - if the last component is "/." or "/..", then we don't
85          *    bother trying this because there's no way it can work.
86          * 
87          *  - if the thing actually ends with a "/", we remove it
88          *    before we start. Except if the string is "/" itself
89          *    (although I can't see why we'd have got here if so,
90          *    because surely "/" would have worked the first
91          *    time?), in which case we don't bother.
92          * 
93          *  - if there's no slash in the string at all, give up in
94          *    confusion (we expect at least one because of the way
95          *    we constructed the string).
96          */
97
98         int i;
99         char *returnname;
100
101         i = strlen(fullname);
102         if (i > 2 && fullname[i - 1] == '/')
103             fullname[--i] = '\0';      /* strip trailing / unless at pos 0 */
104         while (i > 0 && fullname[--i] != '/');
105
106         /*
107          * Give up on special cases.
108          */
109         if (fullname[i] != '/' ||      /* no slash at all */
110             !strcmp(fullname + i, "/.") ||      /* ends in /. */
111             !strcmp(fullname + i, "/..") ||     /* ends in /.. */
112             !strcmp(fullname, "/")) {
113             return fullname;
114         }
115
116         /*
117          * Now i points at the slash. Deal with the final special
118          * case i==0 (ie the whole path was "/nonexistentfile").
119          */
120         fullname[i] = '\0';            /* separate the string */
121         if (i == 0) {
122             sftp_register(req = fxp_realpath_send("/"));
123         } else {
124             sftp_register(req = fxp_realpath_send(fullname));
125         }
126         rreq = sftp_find_request(pktin = sftp_recv());
127         assert(rreq == req);
128         canonname = fxp_realpath_recv(pktin, rreq);
129
130         if (!canonname)
131             return fullname;           /* even that failed; give up */
132
133         /*
134          * We have a canonical name for all but the last path
135          * component. Concatenate the last component and return.
136          */
137         returnname = dupcat(canonname,
138                             canonname[strlen(canonname) - 1] ==
139                             '/' ? "" : "/", fullname + i + 1, NULL);
140         sfree(fullname);
141         sfree(canonname);
142         return returnname;
143     }
144 }
145
146 /*
147  * Return a pointer to the portion of str that comes after the last
148  * slash (or backslash or colon, if `local' is TRUE).
149  */
150 static char *stripslashes(char *str, int local)
151 {
152     char *p;
153
154     if (local) {
155         p = strchr(str, ':');
156         if (p) str = p+1;
157     }
158
159     p = strrchr(str, '/');
160     if (p) str = p+1;
161
162     if (local) {
163         p = strrchr(str, '\\');
164         if (p) str = p+1;
165     }
166
167     return str;
168 }
169
170 /* ----------------------------------------------------------------------
171  * Actual sftp commands.
172  */
173 struct sftp_command {
174     char **words;
175     int nwords, wordssize;
176     int (*obey) (struct sftp_command *);        /* returns <0 to quit */
177 };
178
179 int sftp_cmd_null(struct sftp_command *cmd)
180 {
181     return 1;                          /* success */
182 }
183
184 int sftp_cmd_unknown(struct sftp_command *cmd)
185 {
186     printf("psftp: unknown command \"%s\"\n", cmd->words[0]);
187     return 0;                          /* failure */
188 }
189
190 int sftp_cmd_quit(struct sftp_command *cmd)
191 {
192     return -1;
193 }
194
195 /*
196  * List a directory. If no arguments are given, list pwd; otherwise
197  * list the directory given in words[1].
198  */
199 static int sftp_ls_compare(const void *av, const void *bv)
200 {
201     const struct fxp_name *const *a = (const struct fxp_name *const *) av;
202     const struct fxp_name *const *b = (const struct fxp_name *const *) bv;
203     return strcmp((*a)->filename, (*b)->filename);
204 }
205 int sftp_cmd_ls(struct sftp_command *cmd)
206 {
207     struct fxp_handle *dirh;
208     struct fxp_names *names;
209     struct fxp_name **ournames;
210     int nnames, namesize;
211     char *dir, *cdir;
212     struct sftp_packet *pktin;
213     struct sftp_request *req, *rreq;
214     int i;
215
216     if (back == NULL) {
217         printf("psftp: not connected to a host; use \"open host.name\"\n");
218         return 0;
219     }
220
221     if (cmd->nwords < 2)
222         dir = ".";
223     else
224         dir = cmd->words[1];
225
226     cdir = canonify(dir);
227     if (!cdir) {
228         printf("%s: %s\n", dir, fxp_error());
229         return 0;
230     }
231
232     printf("Listing directory %s\n", cdir);
233
234     sftp_register(req = fxp_opendir_send(cdir));
235     rreq = sftp_find_request(pktin = sftp_recv());
236     assert(rreq == req);
237     dirh = fxp_opendir_recv(pktin, rreq);
238
239     if (dirh == NULL) {
240         printf("Unable to open %s: %s\n", dir, fxp_error());
241     } else {
242         nnames = namesize = 0;
243         ournames = NULL;
244
245         while (1) {
246
247             sftp_register(req = fxp_readdir_send(dirh));
248             rreq = sftp_find_request(pktin = sftp_recv());
249             assert(rreq == req);
250             names = fxp_readdir_recv(pktin, rreq);
251
252             if (names == NULL) {
253                 if (fxp_error_type() == SSH_FX_EOF)
254                     break;
255                 printf("Reading directory %s: %s\n", dir, fxp_error());
256                 break;
257             }
258             if (names->nnames == 0) {
259                 fxp_free_names(names);
260                 break;
261             }
262
263             if (nnames + names->nnames >= namesize) {
264                 namesize += names->nnames + 128;
265                 ournames = sresize(ournames, namesize, struct fxp_name *);
266             }
267
268             for (i = 0; i < names->nnames; i++)
269                 ournames[nnames++] = fxp_dup_name(&names->names[i]);
270
271             fxp_free_names(names);
272         }
273         sftp_register(req = fxp_close_send(dirh));
274         rreq = sftp_find_request(pktin = sftp_recv());
275         assert(rreq == req);
276         fxp_close_recv(pktin, rreq);
277
278         /*
279          * Now we have our filenames. Sort them by actual file
280          * name, and then output the longname parts.
281          */
282         qsort(ournames, nnames, sizeof(*ournames), sftp_ls_compare);
283
284         /*
285          * And print them.
286          */
287         for (i = 0; i < nnames; i++) {
288             printf("%s\n", ournames[i]->longname);
289             fxp_free_name(ournames[i]);
290         }
291         sfree(ournames);
292     }
293
294     sfree(cdir);
295
296     return 1;
297 }
298
299 /*
300  * Change directories. We do this by canonifying the new name, then
301  * trying to OPENDIR it. Only if that succeeds do we set the new pwd.
302  */
303 int sftp_cmd_cd(struct sftp_command *cmd)
304 {
305     struct fxp_handle *dirh;
306     struct sftp_packet *pktin;
307     struct sftp_request *req, *rreq;
308     char *dir;
309
310     if (back == NULL) {
311         printf("psftp: not connected to a host; use \"open host.name\"\n");
312         return 0;
313     }
314
315     if (cmd->nwords < 2)
316         dir = dupstr(homedir);
317     else
318         dir = canonify(cmd->words[1]);
319
320     if (!dir) {
321         printf("%s: %s\n", dir, fxp_error());
322         return 0;
323     }
324
325     sftp_register(req = fxp_opendir_send(dir));
326     rreq = sftp_find_request(pktin = sftp_recv());
327     assert(rreq == req);
328     dirh = fxp_opendir_recv(pktin, rreq);
329
330     if (!dirh) {
331         printf("Directory %s: %s\n", dir, fxp_error());
332         sfree(dir);
333         return 0;
334     }
335
336     sftp_register(req = fxp_close_send(dirh));
337     rreq = sftp_find_request(pktin = sftp_recv());
338     assert(rreq == req);
339     fxp_close_recv(pktin, rreq);
340
341     sfree(pwd);
342     pwd = dir;
343     printf("Remote directory is now %s\n", pwd);
344
345     return 1;
346 }
347
348 /*
349  * Print current directory. Easy as pie.
350  */
351 int sftp_cmd_pwd(struct sftp_command *cmd)
352 {
353     if (back == NULL) {
354         printf("psftp: not connected to a host; use \"open host.name\"\n");
355         return 0;
356     }
357
358     printf("Remote directory is %s\n", pwd);
359     return 1;
360 }
361
362 /*
363  * Get a file and save it at the local end. We have two very
364  * similar commands here: `get' and `reget', which differ in that
365  * `reget' checks for the existence of the destination file and
366  * starts from where a previous aborted transfer left off.
367  */
368 int sftp_general_get(struct sftp_command *cmd, int restart)
369 {
370     struct fxp_handle *fh;
371     struct sftp_packet *pktin;
372     struct sftp_request *req, *rreq;
373     struct fxp_xfer *xfer;
374     char *fname, *outfname;
375     uint64 offset;
376     FILE *fp;
377     int ret;
378
379     if (back == NULL) {
380         printf("psftp: not connected to a host; use \"open host.name\"\n");
381         return 0;
382     }
383
384     if (cmd->nwords < 2) {
385         printf("get: expects a filename\n");
386         return 0;
387     }
388
389     fname = canonify(cmd->words[1]);
390     if (!fname) {
391         printf("%s: %s\n", cmd->words[1], fxp_error());
392         return 0;
393     }
394     outfname = (cmd->nwords == 2 ?
395                 stripslashes(cmd->words[1], 0) : cmd->words[2]);
396
397     sftp_register(req = fxp_open_send(fname, SSH_FXF_READ));
398     rreq = sftp_find_request(pktin = sftp_recv());
399     assert(rreq == req);
400     fh = fxp_open_recv(pktin, rreq);
401
402     if (!fh) {
403         printf("%s: %s\n", fname, fxp_error());
404         sfree(fname);
405         return 0;
406     }
407
408     if (restart) {
409         fp = fopen(outfname, "rb+");
410     } else {
411         fp = fopen(outfname, "wb");
412     }
413
414     if (!fp) {
415         printf("local: unable to open %s\n", outfname);
416
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         sfree(fname);
423         return 0;
424     }
425
426     if (restart) {
427         long posn;
428         fseek(fp, 0L, SEEK_END);
429         posn = ftell(fp);
430         printf("reget: restarting at file position %ld\n", posn);
431         offset = uint64_make(0, posn);
432     } else {
433         offset = uint64_make(0, 0);
434     }
435
436     printf("remote:%s => local:%s\n", fname, outfname);
437
438     /*
439      * FIXME: we can use FXP_FSTAT here to get the file size, and
440      * thus put up a progress bar.
441      */
442     ret = 1;
443     xfer = xfer_download_init(fh, offset);
444     while (!xfer_done(xfer)) {
445         void *vbuf;
446         int ret, len;
447         int wpos, wlen;
448
449         xfer_download_queue(xfer);
450         pktin = sftp_recv();
451         ret = xfer_download_gotpkt(xfer, pktin);
452
453         if (ret < 0) {
454             printf("error while reading: %s\n", fxp_error());
455             ret = 0;
456         }
457
458         while (xfer_download_data(xfer, &vbuf, &len)) {
459             unsigned char *buf = (unsigned char *)vbuf;
460
461             wpos = 0;
462             while (wpos < len) {
463                 wlen = fwrite(buf + wpos, 1, len - wpos, fp);
464                 if (wlen <= 0) {
465                     printf("error while writing local file\n");
466                     ret = 0;
467                     xfer_set_error(xfer);
468                 }
469                 wpos += wlen;
470             }
471             if (wpos < len) {          /* we had an error */
472                 ret = 0;
473                 xfer_set_error(xfer);
474             }
475         }
476     }
477
478     xfer_cleanup(xfer);
479
480     fclose(fp);
481
482     sftp_register(req = fxp_close_send(fh));
483     rreq = sftp_find_request(pktin = sftp_recv());
484     assert(rreq == req);
485     fxp_close_recv(pktin, rreq);
486
487     sfree(fname);
488
489     return ret;
490 }
491 int sftp_cmd_get(struct sftp_command *cmd)
492 {
493     return sftp_general_get(cmd, 0);
494 }
495 int sftp_cmd_reget(struct sftp_command *cmd)
496 {
497     return sftp_general_get(cmd, 1);
498 }
499
500 /*
501  * Send a file and store it at the remote end. We have two very
502  * similar commands here: `put' and `reput', which differ in that
503  * `reput' checks for the existence of the destination file and
504  * starts from where a previous aborted transfer left off.
505  */
506 int sftp_general_put(struct sftp_command *cmd, int restart)
507 {
508     struct fxp_handle *fh;
509     struct fxp_xfer *xfer;
510     char *fname, *origoutfname, *outfname;
511     struct sftp_packet *pktin;
512     struct sftp_request *req, *rreq;
513     uint64 offset;
514     FILE *fp;
515     int ret, err, eof;
516
517     if (back == NULL) {
518         printf("psftp: not connected to a host; use \"open host.name\"\n");
519         return 0;
520     }
521
522     if (cmd->nwords < 2) {
523         printf("put: expects a filename\n");
524         return 0;
525     }
526
527     fname = cmd->words[1];
528     origoutfname = (cmd->nwords == 2 ?
529                     stripslashes(cmd->words[1], 1) : cmd->words[2]);
530     outfname = canonify(origoutfname);
531     if (!outfname) {
532         printf("%s: %s\n", origoutfname, fxp_error());
533         return 0;
534     }
535
536     fp = fopen(fname, "rb");
537     if (!fp) {
538         printf("local: unable to open %s\n", fname);
539         sfree(outfname);
540         return 0;
541     }
542     if (restart) {
543         sftp_register(req = fxp_open_send(outfname, SSH_FXF_WRITE));
544     } else {
545         sftp_register(req = fxp_open_send(outfname, SSH_FXF_WRITE |
546                                           SSH_FXF_CREAT | SSH_FXF_TRUNC));
547     }
548     rreq = sftp_find_request(pktin = sftp_recv());
549     assert(rreq == req);
550     fh = fxp_open_recv(pktin, rreq);
551
552     if (!fh) {
553         printf("%s: %s\n", outfname, fxp_error());
554         sfree(outfname);
555         return 0;
556     }
557
558     if (restart) {
559         char decbuf[30];
560         struct fxp_attrs attrs;
561         int ret;
562
563         sftp_register(req = fxp_fstat_send(fh));
564         rreq = sftp_find_request(pktin = sftp_recv());
565         assert(rreq == req);
566         ret = fxp_fstat_recv(pktin, rreq, &attrs);
567
568         if (!ret) {
569             printf("read size of %s: %s\n", outfname, fxp_error());
570             sfree(outfname);
571             return 0;
572         }
573         if (!(attrs.flags & SSH_FILEXFER_ATTR_SIZE)) {
574             printf("read size of %s: size was not given\n", outfname);
575             sfree(outfname);
576             return 0;
577         }
578         offset = attrs.size;
579         uint64_decimal(offset, decbuf);
580         printf("reput: restarting at file position %s\n", decbuf);
581         if (uint64_compare(offset, uint64_make(0, LONG_MAX)) > 0) {
582             printf("reput: remote file is larger than we can deal with\n");
583             sfree(outfname);
584             return 0;
585         }
586         if (fseek(fp, offset.lo, SEEK_SET) != 0)
587             fseek(fp, 0, SEEK_END);    /* *shrug* */
588     } else {
589         offset = uint64_make(0, 0);
590     }
591
592     printf("local:%s => remote:%s\n", fname, outfname);
593
594     /*
595      * FIXME: we can use FXP_FSTAT here to get the file size, and
596      * thus put up a progress bar.
597      */
598     ret = 1;
599     xfer = xfer_upload_init(fh, offset);
600     err = eof = 0;
601     while ((!err && !eof) || !xfer_done(xfer)) {
602         char buffer[4096];
603         int len, ret;
604
605         while (xfer_upload_ready(xfer) && !err && !eof) {
606             len = fread(buffer, 1, sizeof(buffer), fp);
607             if (len == -1) {
608                 printf("error while reading local file\n");
609                 err = 1;
610             } else if (len == 0) {
611                 eof = 1;
612             } else {
613                 xfer_upload_data(xfer, buffer, len);
614             }
615         }
616
617         pktin = sftp_recv();
618         ret = xfer_upload_gotpkt(xfer, pktin);
619
620         if (!ret) {
621             printf("error while writing: %s\n", fxp_error());
622             err = 1;
623         }
624     }
625
626     xfer_cleanup(xfer);
627
628     sftp_register(req = fxp_close_send(fh));
629     rreq = sftp_find_request(pktin = sftp_recv());
630     assert(rreq == req);
631     fxp_close_recv(pktin, rreq);
632
633     fclose(fp);
634     sfree(outfname);
635
636     return ret;
637 }
638 int sftp_cmd_put(struct sftp_command *cmd)
639 {
640     return sftp_general_put(cmd, 0);
641 }
642 int sftp_cmd_reput(struct sftp_command *cmd)
643 {
644     return sftp_general_put(cmd, 1);
645 }
646
647 int sftp_cmd_mkdir(struct sftp_command *cmd)
648 {
649     char *dir;
650     struct sftp_packet *pktin;
651     struct sftp_request *req, *rreq;
652     int result;
653
654     if (back == NULL) {
655         printf("psftp: not connected to a host; use \"open host.name\"\n");
656         return 0;
657     }
658
659     if (cmd->nwords < 2) {
660         printf("mkdir: expects a directory\n");
661         return 0;
662     }
663
664     dir = canonify(cmd->words[1]);
665     if (!dir) {
666         printf("%s: %s\n", dir, fxp_error());
667         return 0;
668     }
669
670     sftp_register(req = fxp_mkdir_send(dir));
671     rreq = sftp_find_request(pktin = sftp_recv());
672     assert(rreq == req);
673     result = fxp_mkdir_recv(pktin, rreq);
674
675     if (!result) {
676         printf("mkdir %s: %s\n", dir, fxp_error());
677         sfree(dir);
678         return 0;
679     }
680
681     sfree(dir);
682     return 1;
683 }
684
685 int sftp_cmd_rmdir(struct sftp_command *cmd)
686 {
687     char *dir;
688     struct sftp_packet *pktin;
689     struct sftp_request *req, *rreq;
690     int result;
691
692     if (back == NULL) {
693         printf("psftp: not connected to a host; use \"open host.name\"\n");
694         return 0;
695     }
696
697     if (cmd->nwords < 2) {
698         printf("rmdir: expects a directory\n");
699         return 0;
700     }
701
702     dir = canonify(cmd->words[1]);
703     if (!dir) {
704         printf("%s: %s\n", dir, fxp_error());
705         return 0;
706     }
707
708     sftp_register(req = fxp_rmdir_send(dir));
709     rreq = sftp_find_request(pktin = sftp_recv());
710     assert(rreq == req);
711     result = fxp_rmdir_recv(pktin, rreq);
712
713     if (!result) {
714         printf("rmdir %s: %s\n", dir, fxp_error());
715         sfree(dir);
716         return 0;
717     }
718
719     sfree(dir);
720     return 1;
721 }
722
723 int sftp_cmd_rm(struct sftp_command *cmd)
724 {
725     char *fname;
726     struct sftp_packet *pktin;
727     struct sftp_request *req, *rreq;
728     int result;
729
730     if (back == NULL) {
731         printf("psftp: not connected to a host; use \"open host.name\"\n");
732         return 0;
733     }
734
735     if (cmd->nwords < 2) {
736         printf("rm: expects a filename\n");
737         return 0;
738     }
739
740     fname = canonify(cmd->words[1]);
741     if (!fname) {
742         printf("%s: %s\n", fname, fxp_error());
743         return 0;
744     }
745
746     sftp_register(req = fxp_remove_send(fname));
747     rreq = sftp_find_request(pktin = sftp_recv());
748     assert(rreq == req);
749     result = fxp_remove_recv(pktin, rreq);
750
751     if (!result) {
752         printf("rm %s: %s\n", fname, fxp_error());
753         sfree(fname);
754         return 0;
755     }
756
757     sfree(fname);
758     return 1;
759 }
760
761 int sftp_cmd_mv(struct sftp_command *cmd)
762 {
763     char *srcfname, *dstfname;
764     struct sftp_packet *pktin;
765     struct sftp_request *req, *rreq;
766     int result;
767
768     if (back == NULL) {
769         printf("psftp: not connected to a host; use \"open host.name\"\n");
770         return 0;
771     }
772
773     if (cmd->nwords < 3) {
774         printf("mv: expects two filenames\n");
775         return 0;
776     }
777     srcfname = canonify(cmd->words[1]);
778     if (!srcfname) {
779         printf("%s: %s\n", srcfname, fxp_error());
780         return 0;
781     }
782
783     dstfname = canonify(cmd->words[2]);
784     if (!dstfname) {
785         printf("%s: %s\n", dstfname, fxp_error());
786         return 0;
787     }
788
789     sftp_register(req = fxp_rename_send(srcfname, dstfname));
790     rreq = sftp_find_request(pktin = sftp_recv());
791     assert(rreq == req);
792     result = fxp_rename_recv(pktin, rreq);
793
794     if (!result) {
795         char const *error = fxp_error();
796         struct fxp_attrs attrs;
797
798         /*
799          * The move might have failed because dstfname pointed at a
800          * directory. We check this possibility now: if dstfname
801          * _is_ a directory, we re-attempt the move by appending
802          * the basename of srcfname to dstfname.
803          */
804         sftp_register(req = fxp_stat_send(dstfname));
805         rreq = sftp_find_request(pktin = sftp_recv());
806         assert(rreq == req);
807         result = fxp_stat_recv(pktin, rreq, &attrs);
808
809         if (result &&
810             (attrs.flags & SSH_FILEXFER_ATTR_PERMISSIONS) &&
811             (attrs.permissions & 0040000)) {
812             char *p;
813             char *newname, *newcanon;
814             printf("(destination %s is a directory)\n", dstfname);
815             p = srcfname + strlen(srcfname);
816             while (p > srcfname && p[-1] != '/') p--;
817             newname = dupcat(dstfname, "/", p, NULL);
818             newcanon = canonify(newname);
819             sfree(newname);
820             if (newcanon) {
821                 sfree(dstfname);
822                 dstfname = newcanon;
823
824                 sftp_register(req = fxp_rename_send(srcfname, dstfname));
825                 rreq = sftp_find_request(pktin = sftp_recv());
826                 assert(rreq == req);
827                 result = fxp_rename_recv(pktin, rreq);
828
829                 error = result ? NULL : fxp_error();
830             }
831         }
832         if (error) {
833             printf("mv %s %s: %s\n", srcfname, dstfname, error);
834             sfree(srcfname);
835             sfree(dstfname);
836             return 0;
837         }
838     }
839     printf("%s -> %s\n", srcfname, dstfname);
840
841     sfree(srcfname);
842     sfree(dstfname);
843     return 1;
844 }
845
846 int sftp_cmd_chmod(struct sftp_command *cmd)
847 {
848     char *fname, *mode;
849     int result;
850     struct fxp_attrs attrs;
851     unsigned attrs_clr, attrs_xor, oldperms, newperms;
852     struct sftp_packet *pktin;
853     struct sftp_request *req, *rreq;
854
855     if (back == NULL) {
856         printf("psftp: not connected to a host; use \"open host.name\"\n");
857         return 0;
858     }
859
860     if (cmd->nwords < 3) {
861         printf("chmod: expects a mode specifier and a filename\n");
862         return 0;
863     }
864
865     /*
866      * Attempt to parse the mode specifier in cmd->words[1]. We
867      * don't support the full horror of Unix chmod; instead we
868      * support a much simpler syntax in which the user can either
869      * specify an octal number, or a comma-separated sequence of
870      * [ugoa]*[-+=][rwxst]+. (The initial [ugoa] sequence may
871      * _only_ be omitted if the only attribute mentioned is t,
872      * since all others require a user/group/other specification.
873      * Additionally, the s attribute may not be specified for any
874      * [ugoa] specifications other than exactly u or exactly g.
875      */
876     attrs_clr = attrs_xor = 0;
877     mode = cmd->words[1];
878     if (mode[0] >= '0' && mode[0] <= '9') {
879         if (mode[strspn(mode, "01234567")]) {
880             printf("chmod: numeric file modes should"
881                    " contain digits 0-7 only\n");
882             return 0;
883         }
884         attrs_clr = 07777;
885         sscanf(mode, "%o", &attrs_xor);
886         attrs_xor &= attrs_clr;
887     } else {
888         while (*mode) {
889             char *modebegin = mode;
890             unsigned subset, perms;
891             int action;
892
893             subset = 0;
894             while (*mode && *mode != ',' &&
895                    *mode != '+' && *mode != '-' && *mode != '=') {
896                 switch (*mode) {
897                   case 'u': subset |= 04700; break; /* setuid, user perms */
898                   case 'g': subset |= 02070; break; /* setgid, group perms */
899                   case 'o': subset |= 00007; break; /* just other perms */
900                   case 'a': subset |= 06777; break; /* all of the above */
901                   default:
902                     printf("chmod: file mode '%.*s' contains unrecognised"
903                            " user/group/other specifier '%c'\n",
904                            (int)strcspn(modebegin, ","), modebegin, *mode);
905                     return 0;
906                 }
907                 mode++;
908             }
909             if (!*mode || *mode == ',') {
910                 printf("chmod: file mode '%.*s' is incomplete\n",
911                        (int)strcspn(modebegin, ","), modebegin);
912                 return 0;
913             }
914             action = *mode++;
915             if (!*mode || *mode == ',') {
916                 printf("chmod: file mode '%.*s' is incomplete\n",
917                        (int)strcspn(modebegin, ","), modebegin);
918                 return 0;
919             }
920             perms = 0;
921             while (*mode && *mode != ',') {
922                 switch (*mode) {
923                   case 'r': perms |= 00444; break;
924                   case 'w': perms |= 00222; break;
925                   case 'x': perms |= 00111; break;
926                   case 't': perms |= 01000; subset |= 01000; break;
927                   case 's':
928                     if ((subset & 06777) != 04700 &&
929                         (subset & 06777) != 02070) {
930                         printf("chmod: file mode '%.*s': set[ug]id bit should"
931                                " be used with exactly one of u or g only\n",
932                                (int)strcspn(modebegin, ","), modebegin);
933                         return 0;
934                     }
935                     perms |= 06000;
936                     break;
937                   default:
938                     printf("chmod: file mode '%.*s' contains unrecognised"
939                            " permission specifier '%c'\n",
940                            (int)strcspn(modebegin, ","), modebegin, *mode);
941                     return 0;
942                 }
943                 mode++;
944             }
945             if (!(subset & 06777) && (perms &~ subset)) {
946                 printf("chmod: file mode '%.*s' contains no user/group/other"
947                        " specifier and permissions other than 't' \n",
948                        (int)strcspn(modebegin, ","), modebegin);
949                 return 0;
950             }
951             perms &= subset;
952             switch (action) {
953               case '+':
954                 attrs_clr |= perms;
955                 attrs_xor |= perms;
956                 break;
957               case '-':
958                 attrs_clr |= perms;
959                 attrs_xor &= ~perms;
960                 break;
961               case '=':
962                 attrs_clr |= subset;
963                 attrs_xor |= perms;
964                 break;
965             }
966             if (*mode) mode++;         /* eat comma */
967         }
968     }
969
970     fname = canonify(cmd->words[2]);
971     if (!fname) {
972         printf("%s: %s\n", fname, fxp_error());
973         return 0;
974     }
975
976     sftp_register(req = fxp_stat_send(fname));
977     rreq = sftp_find_request(pktin = sftp_recv());
978     assert(rreq == req);
979     result = fxp_stat_recv(pktin, rreq, &attrs);
980
981     if (!result || !(attrs.flags & SSH_FILEXFER_ATTR_PERMISSIONS)) {
982         printf("get attrs for %s: %s\n", fname,
983                result ? "file permissions not provided" : fxp_error());
984         sfree(fname);
985         return 0;
986     }
987
988     attrs.flags = SSH_FILEXFER_ATTR_PERMISSIONS;   /* perms _only_ */
989     oldperms = attrs.permissions & 07777;
990     attrs.permissions &= ~attrs_clr;
991     attrs.permissions ^= attrs_xor;
992     newperms = attrs.permissions & 07777;
993
994     sftp_register(req = fxp_setstat_send(fname, attrs));
995     rreq = sftp_find_request(pktin = sftp_recv());
996     assert(rreq == req);
997     result = fxp_setstat_recv(pktin, rreq);
998
999     if (!result) {
1000         printf("set attrs for %s: %s\n", fname, fxp_error());
1001         sfree(fname);
1002         return 0;
1003     }
1004
1005     printf("%s: %04o -> %04o\n", fname, oldperms, newperms);
1006
1007     sfree(fname);
1008     return 1;
1009 }
1010
1011 static int sftp_cmd_open(struct sftp_command *cmd)
1012 {
1013     if (back != NULL) {
1014         printf("psftp: already connected\n");
1015         return 0;
1016     }
1017
1018     if (cmd->nwords < 2) {
1019         printf("open: expects a host name\n");
1020         return 0;
1021     }
1022
1023     if (psftp_connect(cmd->words[1], NULL, 0)) {
1024         back = NULL;                   /* connection is already closed */
1025         return -1;                     /* this is fatal */
1026     }
1027     do_sftp_init();
1028     return 1;
1029 }
1030
1031 static int sftp_cmd_lcd(struct sftp_command *cmd)
1032 {
1033     char *currdir, *errmsg;
1034
1035     if (cmd->nwords < 2) {
1036         printf("lcd: expects a local directory name\n");
1037         return 0;
1038     }
1039
1040     errmsg = psftp_lcd(cmd->words[1]);
1041     if (errmsg) {
1042         printf("lcd: unable to change directory: %s\n", errmsg);
1043         sfree(errmsg);
1044         return 0;
1045     }
1046
1047     currdir = psftp_getcwd();
1048     printf("New local directory is %s\n", currdir);
1049     sfree(currdir);
1050
1051     return 1;
1052 }
1053
1054 static int sftp_cmd_lpwd(struct sftp_command *cmd)
1055 {
1056     char *currdir;
1057
1058     currdir = psftp_getcwd();
1059     printf("Current local directory is %s\n", currdir);
1060     sfree(currdir);
1061
1062     return 1;
1063 }
1064
1065 static int sftp_cmd_pling(struct sftp_command *cmd)
1066 {
1067     int exitcode;
1068
1069     exitcode = system(cmd->words[1]);
1070     return (exitcode == 0);
1071 }
1072
1073 static int sftp_cmd_help(struct sftp_command *cmd);
1074
1075 static struct sftp_cmd_lookup {
1076     char *name;
1077     /*
1078      * For help purposes, there are two kinds of command:
1079      * 
1080      *  - primary commands, in which `longhelp' is non-NULL. In
1081      *    this case `shorthelp' is descriptive text, and `longhelp'
1082      *    is longer descriptive text intended to be printed after
1083      *    the command name.
1084      * 
1085      *  - alias commands, in which `longhelp' is NULL. In this case
1086      *    `shorthelp' is the name of a primary command, which
1087      *    contains the help that should double up for this command.
1088      */
1089     int listed;                        /* do we list this in primary help? */
1090     char *shorthelp;
1091     char *longhelp;
1092     int (*obey) (struct sftp_command *);
1093 } sftp_lookup[] = {
1094     /*
1095      * List of sftp commands. This is binary-searched so it MUST be
1096      * in ASCII order.
1097      */
1098     {
1099         "!", TRUE, "run a local command",
1100             "<command>\n"
1101             /* FIXME: this example is crap for non-Windows. */
1102             "  Runs a local command. For example, \"!del myfile\".\n",
1103             sftp_cmd_pling
1104     },
1105     {
1106         "bye", TRUE, "finish your SFTP session",
1107             "\n"
1108             "  Terminates your SFTP session and quits the PSFTP program.\n",
1109             sftp_cmd_quit
1110     },
1111     {
1112         "cd", TRUE, "change your remote working directory",
1113             " [ <New working directory> ]\n"
1114             "  Change the remote working directory for your SFTP session.\n"
1115             "  If a new working directory is not supplied, you will be\n"
1116             "  returned to your home directory.\n",
1117             sftp_cmd_cd
1118     },
1119     {
1120         "chmod", TRUE, "change file permissions and modes",
1121             " ( <octal-digits> | <modifiers> ) <filename>\n"
1122             "  Change the file permissions on a file or directory.\n"
1123             "  <octal-digits> can be any octal Unix permission specifier.\n"
1124             "  Alternatively, <modifiers> can include:\n"
1125             "    u+r     make file readable by owning user\n"
1126             "    u+w     make file writable by owning user\n"
1127             "    u+x     make file executable by owning user\n"
1128             "    u-r     make file not readable by owning user\n"
1129             "    [also u-w, u-x]\n"
1130             "    g+r     make file readable by members of owning group\n"
1131             "    [also g+w, g+x, g-r, g-w, g-x]\n"
1132             "    o+r     make file readable by all other users\n"
1133             "    [also o+w, o+x, o-r, o-w, o-x]\n"
1134             "    a+r     make file readable by absolutely everybody\n"
1135             "    [also a+w, a+x, a-r, a-w, a-x]\n"
1136             "    u+s     enable the Unix set-user-ID bit\n"
1137             "    u-s     disable the Unix set-user-ID bit\n"
1138             "    g+s     enable the Unix set-group-ID bit\n"
1139             "    g-s     disable the Unix set-group-ID bit\n"
1140             "    +t      enable the Unix \"sticky bit\"\n"
1141             "  You can give more than one modifier for the same user (\"g-rwx\"), and\n"
1142             "  more than one user for the same modifier (\"ug+w\"). You can\n"
1143             "  use commas to separate different modifiers (\"u+rwx,g+s\").\n",
1144             sftp_cmd_chmod
1145     },
1146     {
1147         "del", TRUE, "delete a file",
1148             " <filename>\n"
1149             "  Delete a file.\n",
1150             sftp_cmd_rm
1151     },
1152     {
1153         "delete", FALSE, "del", NULL, sftp_cmd_rm
1154     },
1155     {
1156         "dir", TRUE, "list contents of a remote directory",
1157             " [ <directory-name> ]\n"
1158             "  List the contents of a specified directory on the server.\n"
1159             "  If <directory-name> is not given, the current working directory\n"
1160             "  will be listed.\n",
1161             sftp_cmd_ls
1162     },
1163     {
1164         "exit", TRUE, "bye", NULL, sftp_cmd_quit
1165     },
1166     {
1167         "get", TRUE, "download a file from the server to your local machine",
1168             " <filename> [ <local-filename> ]\n"
1169             "  Downloads a file on the server and stores it locally under\n"
1170             "  the same name, or under a different one if you supply the\n"
1171             "  argument <local-filename>.\n",
1172             sftp_cmd_get
1173     },
1174     {
1175         "help", TRUE, "give help",
1176             " [ <command> [ <command> ... ] ]\n"
1177             "  Give general help if no commands are specified.\n"
1178             "  If one or more commands are specified, give specific help on\n"
1179             "  those particular commands.\n",
1180             sftp_cmd_help
1181     },
1182     {
1183         "lcd", TRUE, "change local working directory",
1184             " <local-directory-name>\n"
1185             "  Change the local working directory of the PSFTP program (the\n"
1186             "  default location where the \"get\" command will save files).\n",
1187             sftp_cmd_lcd
1188     },
1189     {
1190         "lpwd", TRUE, "print local working directory",
1191             "\n"
1192             "  Print the local working directory of the PSFTP program (the\n"
1193             "  default location where the \"get\" command will save files).\n",
1194             sftp_cmd_lpwd
1195     },
1196     {
1197         "ls", TRUE, "dir", NULL,
1198             sftp_cmd_ls
1199     },
1200     {
1201         "mkdir", TRUE, "create a directory on the remote server",
1202             " <directory-name>\n"
1203             "  Creates a directory with the given name on the server.\n",
1204             sftp_cmd_mkdir
1205     },
1206     {
1207         "mv", TRUE, "move or rename a file on the remote server",
1208             " <source-filename> <destination-filename>\n"
1209             "  Moves or renames the file <source-filename> on the server,\n"
1210             "  so that it is accessible under the name <destination-filename>.\n",
1211             sftp_cmd_mv
1212     },
1213     {
1214         "open", TRUE, "connect to a host",
1215             " [<user>@]<hostname>\n"
1216             "  Establishes an SFTP connection to a given host. Only usable\n"
1217             "  when you did not already specify a host name on the command\n"
1218             "  line.\n",
1219             sftp_cmd_open
1220     },
1221     {
1222         "put", TRUE, "upload a file from your local machine to the server",
1223             " <filename> [ <remote-filename> ]\n"
1224             "  Uploads a file to the server and stores it there under\n"
1225             "  the same name, or under a different one if you supply the\n"
1226             "  argument <remote-filename>.\n",
1227             sftp_cmd_put
1228     },
1229     {
1230         "pwd", TRUE, "print your remote working directory",
1231             "\n"
1232             "  Print the current remote working directory for your SFTP session.\n",
1233             sftp_cmd_pwd
1234     },
1235     {
1236         "quit", TRUE, "bye", NULL,
1237             sftp_cmd_quit
1238     },
1239     {
1240         "reget", TRUE, "continue downloading a file",
1241             " <filename> [ <local-filename> ]\n"
1242             "  Works exactly like the \"get\" command, but the local file\n"
1243             "  must already exist. The download will begin at the end of the\n"
1244             "  file. This is for resuming a download that was interrupted.\n",
1245             sftp_cmd_reget
1246     },
1247     {
1248         "ren", TRUE, "mv", NULL,
1249             sftp_cmd_mv
1250     },
1251     {
1252         "rename", FALSE, "mv", NULL,
1253             sftp_cmd_mv
1254     },
1255     {
1256         "reput", TRUE, "continue uploading a file",
1257             " <filename> [ <remote-filename> ]\n"
1258             "  Works exactly like the \"put\" command, but the remote file\n"
1259             "  must already exist. The upload will begin at the end of the\n"
1260             "  file. This is for resuming an upload that was interrupted.\n",
1261             sftp_cmd_reput
1262     },
1263     {
1264         "rm", TRUE, "del", NULL,
1265             sftp_cmd_rm
1266     },
1267     {
1268         "rmdir", TRUE, "remove a directory on the remote server",
1269             " <directory-name>\n"
1270             "  Removes the directory with the given name on the server.\n"
1271             "  The directory will not be removed unless it is empty.\n",
1272             sftp_cmd_rmdir
1273     }
1274 };
1275
1276 const struct sftp_cmd_lookup *lookup_command(char *name)
1277 {
1278     int i, j, k, cmp;
1279
1280     i = -1;
1281     j = sizeof(sftp_lookup) / sizeof(*sftp_lookup);
1282     while (j - i > 1) {
1283         k = (j + i) / 2;
1284         cmp = strcmp(name, sftp_lookup[k].name);
1285         if (cmp < 0)
1286             j = k;
1287         else if (cmp > 0)
1288             i = k;
1289         else {
1290             return &sftp_lookup[k];
1291         }
1292     }
1293     return NULL;
1294 }
1295
1296 static int sftp_cmd_help(struct sftp_command *cmd)
1297 {
1298     int i;
1299     if (cmd->nwords == 1) {
1300         /*
1301          * Give short help on each command.
1302          */
1303         int maxlen;
1304         maxlen = 0;
1305         for (i = 0; i < sizeof(sftp_lookup) / sizeof(*sftp_lookup); i++) {
1306             int len;
1307             if (!sftp_lookup[i].listed)
1308                 continue;
1309             len = strlen(sftp_lookup[i].name);
1310             if (maxlen < len)
1311                 maxlen = len;
1312         }
1313         for (i = 0; i < sizeof(sftp_lookup) / sizeof(*sftp_lookup); i++) {
1314             const struct sftp_cmd_lookup *lookup;
1315             if (!sftp_lookup[i].listed)
1316                 continue;
1317             lookup = &sftp_lookup[i];
1318             printf("%-*s", maxlen+2, lookup->name);
1319             if (lookup->longhelp == NULL)
1320                 lookup = lookup_command(lookup->shorthelp);
1321             printf("%s\n", lookup->shorthelp);
1322         }
1323     } else {
1324         /*
1325          * Give long help on specific commands.
1326          */
1327         for (i = 1; i < cmd->nwords; i++) {
1328             const struct sftp_cmd_lookup *lookup;
1329             lookup = lookup_command(cmd->words[i]);
1330             if (!lookup) {
1331                 printf("help: %s: command not found\n", cmd->words[i]);
1332             } else {
1333                 printf("%s", lookup->name);
1334                 if (lookup->longhelp == NULL)
1335                     lookup = lookup_command(lookup->shorthelp);
1336                 printf("%s", lookup->longhelp);
1337             }
1338         }
1339     }
1340     return 1;
1341 }
1342
1343 /* ----------------------------------------------------------------------
1344  * Command line reading and parsing.
1345  */
1346 struct sftp_command *sftp_getcmd(FILE *fp, int mode, int modeflags)
1347 {
1348     char *line;
1349     int linelen, linesize;
1350     struct sftp_command *cmd;
1351     char *p, *q, *r;
1352     int quoting;
1353
1354     if ((mode == 0) || (modeflags & 1)) {
1355         printf("psftp> ");
1356     }
1357     fflush(stdout);
1358
1359     cmd = snew(struct sftp_command);
1360     cmd->words = NULL;
1361     cmd->nwords = 0;
1362     cmd->wordssize = 0;
1363
1364     line = NULL;
1365     linesize = linelen = 0;
1366     while (1) {
1367         int len;
1368         char *ret;
1369
1370         linesize += 512;
1371         line = sresize(line, linesize, char);
1372         ret = fgets(line + linelen, linesize - linelen, fp);
1373
1374         if (!ret || (linelen == 0 && line[0] == '\0')) {
1375             cmd->obey = sftp_cmd_quit;
1376             if ((mode == 0) || (modeflags & 1))
1377                 printf("quit\n");
1378             return cmd;                /* eof */
1379         }
1380         len = linelen + strlen(line + linelen);
1381         linelen += len;
1382         if (line[linelen - 1] == '\n') {
1383             linelen--;
1384             line[linelen] = '\0';
1385             break;
1386         }
1387     }
1388     if (modeflags & 1) {
1389         printf("%s\n", line);
1390     }
1391
1392     p = line;
1393     while (*p && (*p == ' ' || *p == '\t'))
1394         p++;
1395
1396     if (*p == '!') {
1397         /*
1398          * Special case: the ! command. This is always parsed as
1399          * exactly two words: one containing the !, and the second
1400          * containing everything else on the line.
1401          */
1402         cmd->nwords = cmd->wordssize = 2;
1403         cmd->words = sresize(cmd->words, cmd->wordssize, char *);
1404         cmd->words[0] = "!";
1405         cmd->words[1] = p+1;
1406     } else {
1407
1408         /*
1409          * Parse the command line into words. The syntax is:
1410          *  - double quotes are removed, but cause spaces within to be
1411          *    treated as non-separating.
1412          *  - a double-doublequote pair is a literal double quote, inside
1413          *    _or_ outside quotes. Like this:
1414          *
1415          *      firstword "second word" "this has ""quotes"" in" and""this""
1416          *
1417          * becomes
1418          *
1419          *      >firstword<
1420          *      >second word<
1421          *      >this has "quotes" in<
1422          *      >and"this"<
1423          */
1424         while (*p) {
1425             /* skip whitespace */
1426             while (*p && (*p == ' ' || *p == '\t'))
1427                 p++;
1428             /* mark start of word */
1429             q = r = p;                 /* q sits at start, r writes word */
1430             quoting = 0;
1431             while (*p) {
1432                 if (!quoting && (*p == ' ' || *p == '\t'))
1433                     break;                     /* reached end of word */
1434                 else if (*p == '"' && p[1] == '"')
1435                     p += 2, *r++ = '"';    /* a literal quote */
1436                 else if (*p == '"')
1437                     p++, quoting = !quoting;
1438                 else
1439                     *r++ = *p++;
1440             }
1441             if (*p)
1442                 p++;                   /* skip over the whitespace */
1443             *r = '\0';
1444             if (cmd->nwords >= cmd->wordssize) {
1445                 cmd->wordssize = cmd->nwords + 16;
1446                 cmd->words = sresize(cmd->words, cmd->wordssize, char *);
1447             }
1448             cmd->words[cmd->nwords++] = q;
1449         }
1450     }
1451
1452     /*
1453      * Now parse the first word and assign a function.
1454      */
1455
1456     if (cmd->nwords == 0)
1457         cmd->obey = sftp_cmd_null;
1458     else {
1459         const struct sftp_cmd_lookup *lookup;
1460         lookup = lookup_command(cmd->words[0]);
1461         if (!lookup)
1462             cmd->obey = sftp_cmd_unknown;
1463         else
1464             cmd->obey = lookup->obey;
1465     }
1466
1467     return cmd;
1468 }
1469
1470 static int do_sftp_init(void)
1471 {
1472     struct sftp_packet *pktin;
1473     struct sftp_request *req, *rreq;
1474
1475     /*
1476      * Do protocol initialisation. 
1477      */
1478     if (!fxp_init()) {
1479         fprintf(stderr,
1480                 "Fatal: unable to initialise SFTP: %s\n", fxp_error());
1481         return 1;                      /* failure */
1482     }
1483
1484     /*
1485      * Find out where our home directory is.
1486      */
1487     sftp_register(req = fxp_realpath_send("."));
1488     rreq = sftp_find_request(pktin = sftp_recv());
1489     assert(rreq == req);
1490     homedir = fxp_realpath_recv(pktin, rreq);
1491
1492     if (!homedir) {
1493         fprintf(stderr,
1494                 "Warning: failed to resolve home directory: %s\n",
1495                 fxp_error());
1496         homedir = dupstr(".");
1497     } else {
1498         printf("Remote working directory is %s\n", homedir);
1499     }
1500     pwd = dupstr(homedir);
1501     return 0;
1502 }
1503
1504 void do_sftp(int mode, int modeflags, char *batchfile)
1505 {
1506     FILE *fp;
1507     int ret;
1508
1509     /*
1510      * Batch mode?
1511      */
1512     if (mode == 0) {
1513
1514         /* ------------------------------------------------------------------
1515          * Now we're ready to do Real Stuff.
1516          */
1517         while (1) {
1518             struct sftp_command *cmd;
1519             cmd = sftp_getcmd(stdin, 0, 0);
1520             if (!cmd)
1521                 break;
1522             if (cmd->obey(cmd) < 0)
1523                 break;
1524         }
1525     } else {
1526         fp = fopen(batchfile, "r");
1527         if (!fp) {
1528             printf("Fatal: unable to open %s\n", batchfile);
1529             return;
1530         }
1531         while (1) {
1532             struct sftp_command *cmd;
1533             cmd = sftp_getcmd(fp, mode, modeflags);
1534             if (!cmd)
1535                 break;
1536             ret = cmd->obey(cmd);
1537             if (ret < 0)
1538                 break;
1539             if (ret == 0) {
1540                 if (!(modeflags & 2))
1541                     break;
1542             }
1543         }
1544         fclose(fp);
1545
1546     }
1547 }
1548
1549 /* ----------------------------------------------------------------------
1550  * Dirty bits: integration with PuTTY.
1551  */
1552
1553 static int verbose = 0;
1554
1555 /*
1556  *  Print an error message and perform a fatal exit.
1557  */
1558 void fatalbox(char *fmt, ...)
1559 {
1560     char *str, *str2;
1561     va_list ap;
1562     va_start(ap, fmt);
1563     str = dupvprintf(fmt, ap);
1564     str2 = dupcat("Fatal: ", str, "\n", NULL);
1565     sfree(str);
1566     va_end(ap);
1567     fputs(str2, stderr);
1568     sfree(str2);
1569
1570     cleanup_exit(1);
1571 }
1572 void modalfatalbox(char *fmt, ...)
1573 {
1574     char *str, *str2;
1575     va_list ap;
1576     va_start(ap, fmt);
1577     str = dupvprintf(fmt, ap);
1578     str2 = dupcat("Fatal: ", str, "\n", NULL);
1579     sfree(str);
1580     va_end(ap);
1581     fputs(str2, stderr);
1582     sfree(str2);
1583
1584     cleanup_exit(1);
1585 }
1586 void connection_fatal(void *frontend, char *fmt, ...)
1587 {
1588     char *str, *str2;
1589     va_list ap;
1590     va_start(ap, fmt);
1591     str = dupvprintf(fmt, ap);
1592     str2 = dupcat("Fatal: ", str, "\n", NULL);
1593     sfree(str);
1594     va_end(ap);
1595     fputs(str2, stderr);
1596     sfree(str2);
1597
1598     cleanup_exit(1);
1599 }
1600
1601 void ldisc_send(void *handle, char *buf, int len, int interactive)
1602 {
1603     /*
1604      * This is only here because of the calls to ldisc_send(NULL,
1605      * 0) in ssh.c. Nothing in PSFTP actually needs to use the
1606      * ldisc as an ldisc. So if we get called with any real data, I
1607      * want to know about it.
1608      */
1609     assert(len == 0);
1610 }
1611
1612 /*
1613  * In psftp, all agent requests should be synchronous, so this is a
1614  * never-called stub.
1615  */
1616 void agent_schedule_callback(void (*callback)(void *, void *, int),
1617                              void *callback_ctx, void *data, int len)
1618 {
1619     assert(!"We shouldn't be here");
1620 }
1621
1622 /*
1623  * Receive a block of data from the SSH link. Block until all data
1624  * is available.
1625  *
1626  * To do this, we repeatedly call the SSH protocol module, with our
1627  * own trap in from_backend() to catch the data that comes back. We
1628  * do this until we have enough data.
1629  */
1630
1631 static unsigned char *outptr;          /* where to put the data */
1632 static unsigned outlen;                /* how much data required */
1633 static unsigned char *pending = NULL;  /* any spare data */
1634 static unsigned pendlen = 0, pendsize = 0;      /* length and phys. size of buffer */
1635 int from_backend(void *frontend, int is_stderr, const char *data, int datalen)
1636 {
1637     unsigned char *p = (unsigned char *) data;
1638     unsigned len = (unsigned) datalen;
1639
1640     assert(len > 0);
1641
1642     /*
1643      * stderr data is just spouted to local stderr and otherwise
1644      * ignored.
1645      */
1646     if (is_stderr) {
1647         fwrite(data, 1, len, stderr);
1648         return 0;
1649     }
1650
1651     /*
1652      * If this is before the real session begins, just return.
1653      */
1654     if (!outptr)
1655         return 0;
1656
1657     if (outlen > 0) {
1658         unsigned used = outlen;
1659         if (used > len)
1660             used = len;
1661         memcpy(outptr, p, used);
1662         outptr += used;
1663         outlen -= used;
1664         p += used;
1665         len -= used;
1666     }
1667
1668     if (len > 0) {
1669         if (pendsize < pendlen + len) {
1670             pendsize = pendlen + len + 4096;
1671             pending = sresize(pending, pendsize, unsigned char);
1672         }
1673         memcpy(pending + pendlen, p, len);
1674         pendlen += len;
1675     }
1676
1677     return 0;
1678 }
1679 int sftp_recvdata(char *buf, int len)
1680 {
1681     outptr = (unsigned char *) buf;
1682     outlen = len;
1683
1684     /*
1685      * See if the pending-input block contains some of what we
1686      * need.
1687      */
1688     if (pendlen > 0) {
1689         unsigned pendused = pendlen;
1690         if (pendused > outlen)
1691             pendused = outlen;
1692         memcpy(outptr, pending, pendused);
1693         memmove(pending, pending + pendused, pendlen - pendused);
1694         outptr += pendused;
1695         outlen -= pendused;
1696         pendlen -= pendused;
1697         if (pendlen == 0) {
1698             pendsize = 0;
1699             sfree(pending);
1700             pending = NULL;
1701         }
1702         if (outlen == 0)
1703             return 1;
1704     }
1705
1706     while (outlen > 0) {
1707         if (ssh_sftp_loop_iteration() < 0)
1708             return 0;                  /* doom */
1709     }
1710
1711     return 1;
1712 }
1713 int sftp_senddata(char *buf, int len)
1714 {
1715     back->send(backhandle, (unsigned char *) buf, len);
1716     return 1;
1717 }
1718
1719 /*
1720  *  Short description of parameters.
1721  */
1722 static void usage(void)
1723 {
1724     printf("PuTTY Secure File Transfer (SFTP) client\n");
1725     printf("%s\n", ver);
1726     printf("Usage: psftp [options] user@host\n");
1727     printf("Options:\n");
1728     printf("  -b file   use specified batchfile\n");
1729     printf("  -bc       output batchfile commands\n");
1730     printf("  -be       don't stop batchfile processing if errors\n");
1731     printf("  -v        show verbose messages\n");
1732     printf("  -load sessname  Load settings from saved session\n");
1733     printf("  -l user   connect with specified username\n");
1734     printf("  -P port   connect to specified port\n");
1735     printf("  -pw passw login with specified password\n");
1736     printf("  -1 -2     force use of particular SSH protocol version\n");
1737     printf("  -C        enable compression\n");
1738     printf("  -i key    private key file for authentication\n");
1739     printf("  -batch    disable all interactive prompts\n");
1740     cleanup_exit(1);
1741 }
1742
1743 /*
1744  * Connect to a host.
1745  */
1746 static int psftp_connect(char *userhost, char *user, int portnumber)
1747 {
1748     char *host, *realhost;
1749     const char *err;
1750     void *logctx;
1751
1752     /* Separate host and username */
1753     host = userhost;
1754     host = strrchr(host, '@');
1755     if (host == NULL) {
1756         host = userhost;
1757     } else {
1758         *host++ = '\0';
1759         if (user) {
1760             printf("psftp: multiple usernames specified; using \"%s\"\n",
1761                    user);
1762         } else
1763             user = userhost;
1764     }
1765
1766     /* Try to load settings for this host */
1767     do_defaults(host, &cfg);
1768     if (cfg.host[0] == '\0') {
1769         /* No settings for this host; use defaults */
1770         do_defaults(NULL, &cfg);
1771         strncpy(cfg.host, host, sizeof(cfg.host) - 1);
1772         cfg.host[sizeof(cfg.host) - 1] = '\0';
1773     }
1774
1775     /*
1776      * Force use of SSH. (If they got the protocol wrong we assume the
1777      * port is useless too.)
1778      */
1779     if (cfg.protocol != PROT_SSH) {
1780         cfg.protocol = PROT_SSH;
1781         cfg.port = 22;
1782     }
1783
1784     /*
1785      * Enact command-line overrides.
1786      */
1787     cmdline_run_saved(&cfg);
1788
1789     /*
1790      * Trim leading whitespace off the hostname if it's there.
1791      */
1792     {
1793         int space = strspn(cfg.host, " \t");
1794         memmove(cfg.host, cfg.host+space, 1+strlen(cfg.host)-space);
1795     }
1796
1797     /* See if host is of the form user@host */
1798     if (cfg.host[0] != '\0') {
1799         char *atsign = strchr(cfg.host, '@');
1800         /* Make sure we're not overflowing the user field */
1801         if (atsign) {
1802             if (atsign - cfg.host < sizeof cfg.username) {
1803                 strncpy(cfg.username, cfg.host, atsign - cfg.host);
1804                 cfg.username[atsign - cfg.host] = '\0';
1805             }
1806             memmove(cfg.host, atsign + 1, 1 + strlen(atsign + 1));
1807         }
1808     }
1809
1810     /*
1811      * Trim a colon suffix off the hostname if it's there.
1812      */
1813     cfg.host[strcspn(cfg.host, ":")] = '\0';
1814
1815     /*
1816      * Remove any remaining whitespace from the hostname.
1817      */
1818     {
1819         int p1 = 0, p2 = 0;
1820         while (cfg.host[p2] != '\0') {
1821             if (cfg.host[p2] != ' ' && cfg.host[p2] != '\t') {
1822                 cfg.host[p1] = cfg.host[p2];
1823                 p1++;
1824             }
1825             p2++;
1826         }
1827         cfg.host[p1] = '\0';
1828     }
1829
1830     /* Set username */
1831     if (user != NULL && user[0] != '\0') {
1832         strncpy(cfg.username, user, sizeof(cfg.username) - 1);
1833         cfg.username[sizeof(cfg.username) - 1] = '\0';
1834     }
1835     if (!cfg.username[0]) {
1836         printf("login as: ");
1837         fflush(stdout);
1838         if (!fgets(cfg.username, sizeof(cfg.username), stdin)) {
1839             fprintf(stderr, "psftp: aborting\n");
1840             cleanup_exit(1);
1841         } else {
1842             int len = strlen(cfg.username);
1843             if (cfg.username[len - 1] == '\n')
1844                 cfg.username[len - 1] = '\0';
1845         }
1846     }
1847
1848     if (portnumber)
1849         cfg.port = portnumber;
1850
1851     /* SFTP uses SSH2 by default always */
1852     cfg.sshprot = 2;
1853
1854     /*
1855      * Disable scary things which shouldn't be enabled for simple
1856      * things like SCP and SFTP: agent forwarding, port forwarding,
1857      * X forwarding.
1858      */
1859     cfg.x11_forward = 0;
1860     cfg.agentfwd = 0;
1861     cfg.portfwd[0] = cfg.portfwd[1] = '\0';
1862
1863     /* Set up subsystem name. */
1864     strcpy(cfg.remote_cmd, "sftp");
1865     cfg.ssh_subsys = TRUE;
1866     cfg.nopty = TRUE;
1867
1868     /*
1869      * Set up fallback option, for SSH1 servers or servers with the
1870      * sftp subsystem not enabled but the server binary installed
1871      * in the usual place. We only support fallback on Unix
1872      * systems, and we use a kludgy piece of shellery which should
1873      * try to find sftp-server in various places (the obvious
1874      * systemwide spots /usr/lib and /usr/local/lib, and then the
1875      * user's PATH) and finally give up.
1876      * 
1877      *   test -x /usr/lib/sftp-server && exec /usr/lib/sftp-server
1878      *   test -x /usr/local/lib/sftp-server && exec /usr/local/lib/sftp-server
1879      *   exec sftp-server
1880      * 
1881      * the idea being that this will attempt to use either of the
1882      * obvious pathnames and then give up, and when it does give up
1883      * it will print the preferred pathname in the error messages.
1884      */
1885     cfg.remote_cmd_ptr2 =
1886         "test -x /usr/lib/sftp-server && exec /usr/lib/sftp-server\n"
1887         "test -x /usr/local/lib/sftp-server && exec /usr/local/lib/sftp-server\n"
1888         "exec sftp-server";
1889     cfg.ssh_subsys2 = FALSE;
1890
1891     back = &ssh_backend;
1892
1893     err = back->init(NULL, &backhandle, &cfg, cfg.host, cfg.port, &realhost,0);
1894     if (err != NULL) {
1895         fprintf(stderr, "ssh_init: %s\n", err);
1896         return 1;
1897     }
1898     logctx = log_init(NULL, &cfg);
1899     back->provide_logctx(backhandle, logctx);
1900     console_provide_logctx(logctx);
1901     while (!back->sendok(backhandle)) {
1902         if (ssh_sftp_loop_iteration() < 0) {
1903             fprintf(stderr, "ssh_init: error during SSH connection setup\n");
1904             return 1;
1905         }
1906     }
1907     if (verbose && realhost != NULL)
1908         printf("Connected to %s\n", realhost);
1909     return 0;
1910 }
1911
1912 void cmdline_error(char *p, ...)
1913 {
1914     va_list ap;
1915     fprintf(stderr, "psftp: ");
1916     va_start(ap, p);
1917     vfprintf(stderr, p, ap);
1918     va_end(ap);
1919     fprintf(stderr, "\n       try typing \"psftp -h\" for help\n");
1920     exit(1);
1921 }
1922
1923 /*
1924  * Main program. Parse arguments etc.
1925  */
1926 int psftp_main(int argc, char *argv[])
1927 {
1928     int i;
1929     int portnumber = 0;
1930     char *userhost, *user;
1931     int mode = 0;
1932     int modeflags = 0;
1933     char *batchfile = NULL;
1934     int errors = 0;
1935
1936     flags = FLAG_STDERR | FLAG_INTERACTIVE
1937 #ifdef FLAG_SYNCAGENT
1938         | FLAG_SYNCAGENT
1939 #endif
1940         ;
1941     cmdline_tooltype = TOOLTYPE_FILETRANSFER;
1942     ssh_get_line = &console_get_line;
1943     sk_init();
1944
1945     userhost = user = NULL;
1946
1947     errors = 0;
1948     for (i = 1; i < argc; i++) {
1949         int ret;
1950         if (argv[i][0] != '-') {
1951             if (userhost)
1952                 usage();
1953             else
1954                 userhost = dupstr(argv[i]);
1955             continue;
1956         }
1957         ret = cmdline_process_param(argv[i], i+1<argc?argv[i+1]:NULL, 1, &cfg);
1958         if (ret == -2) {
1959             cmdline_error("option \"%s\" requires an argument", argv[i]);
1960         } else if (ret == 2) {
1961             i++;               /* skip next argument */
1962         } else if (ret == 1) {
1963             /* We have our own verbosity in addition to `flags'. */
1964             if (flags & FLAG_VERBOSE)
1965                 verbose = 1;
1966         } else if (strcmp(argv[i], "-h") == 0 ||
1967                    strcmp(argv[i], "-?") == 0) {
1968             usage();
1969         } else if (strcmp(argv[i], "-batch") == 0) {
1970             console_batch_mode = 1;
1971         } else if (strcmp(argv[i], "-b") == 0 && i + 1 < argc) {
1972             mode = 1;
1973             batchfile = argv[++i];
1974         } else if (strcmp(argv[i], "-bc") == 0) {
1975             modeflags = modeflags | 1;
1976         } else if (strcmp(argv[i], "-be") == 0) {
1977             modeflags = modeflags | 2;
1978         } else if (strcmp(argv[i], "--") == 0) {
1979             i++;
1980             break;
1981         } else {
1982             cmdline_error("unknown option \"%s\"", argv[i]);
1983         }
1984     }
1985     argc -= i;
1986     argv += i;
1987     back = NULL;
1988
1989     /*
1990      * If a user@host string has already been provided, connect to
1991      * it now.
1992      */
1993     if (userhost) {
1994         if (psftp_connect(userhost, user, portnumber))
1995             return 1;
1996         if (do_sftp_init())
1997             return 1;
1998     } else {
1999         printf("psftp: no hostname specified; use \"open host.name\""
2000             " to connect\n");
2001     }
2002
2003     do_sftp(mode, modeflags, batchfile);
2004
2005     if (back != NULL && back->socket(backhandle) != NULL) {
2006         char ch;
2007         back->special(backhandle, TS_EOF);
2008         sftp_recvdata(&ch, 1);
2009     }
2010     random_save_seed();
2011
2012     return 0;
2013 }