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