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