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