]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - pscp.c
first pass
[PuTTY.git] / pscp.c
1 /*
2  * scp.c  -  Scp (Secure Copy) client for PuTTY.
3  * Joris van Rantwijk, Simon Tatham
4  *
5  * This is mainly based on ssh-1.2.26/scp.c by Timo Rinne & Tatu Ylonen.
6  * They, in turn, used stuff from BSD rcp.
7  * 
8  * (SGT, 2001-09-10: Joris van Rantwijk assures me that although
9  * this file as originally submitted was inspired by, and
10  * _structurally_ based on, ssh-1.2.26's scp.c, there wasn't any
11  * actual code duplicated, so the above comment shouldn't give rise
12  * to licensing issues.)
13  */
14
15 #include <stdlib.h>
16 #include <stdio.h>
17 #include <string.h>
18 #include <limits.h>
19 #include <time.h>
20 #include <assert.h>
21
22 #define PUTTY_DO_GLOBALS
23 #include "putty.h"
24 #include "psftp.h"
25 #include "ssh.h"
26 #include "sftp.h"
27 #include "storage.h"
28 #include "int64.h"
29
30 static int list = 0;
31 static int verbose = 0;
32 static int recursive = 0;
33 static int preserve = 0;
34 static int targetshouldbedirectory = 0;
35 static int statistics = 1;
36 static int prev_stats_len = 0;
37 static int scp_unsafe_mode = 0;
38 static int errs = 0;
39 static int try_scp = 1;
40 static int try_sftp = 1;
41 static int main_cmd_is_sftp = 0;
42 static int fallback_cmd_is_sftp = 0;
43 static int using_sftp = 0;
44 static int uploading = 0;
45
46 static Backend *back;
47 static void *backhandle;
48 static Conf *conf;
49 int sent_eof = FALSE;
50
51 static void source(const char *src);
52 static void rsource(const char *src);
53 static void sink(const char *targ, const char *src);
54
55 const char *const appname = "PSCP";
56
57 /*
58  * The maximum amount of queued data we accept before we stop and
59  * wait for the server to process some.
60  */
61 #define MAX_SCP_BUFSIZE 16384
62
63 void ldisc_echoedit_update(void *handle) { }
64
65 static void tell_char(FILE *stream, char c)
66 {
67     fputc(c, stream);
68 }
69
70 static void tell_str(FILE *stream, const char *str)
71 {
72     unsigned int i;
73
74     for (i = 0; i < strlen(str); ++i)
75         tell_char(stream, str[i]);
76 }
77
78 static void tell_user(FILE *stream, const char *fmt, ...)
79 {
80     char *str, *str2;
81     va_list ap;
82     va_start(ap, fmt);
83     str = dupvprintf(fmt, ap);
84     va_end(ap);
85     str2 = dupcat(str, "\n", NULL);
86     sfree(str);
87     tell_str(stream, str2);
88     sfree(str2);
89 }
90
91 /*
92  *  Print an error message and perform a fatal exit.
93  */
94 void fatalbox(const char *fmt, ...)
95 {
96     char *str, *str2;
97     va_list ap;
98     va_start(ap, fmt);
99     str = dupvprintf(fmt, ap);
100     str2 = dupcat("Fatal: ", str, "\n", NULL);
101     sfree(str);
102     va_end(ap);
103     tell_str(stderr, str2);
104     sfree(str2);
105     errs++;
106
107     cleanup_exit(1);
108 }
109 void modalfatalbox(const char *fmt, ...)
110 {
111     char *str, *str2;
112     va_list ap;
113     va_start(ap, fmt);
114     str = dupvprintf(fmt, ap);
115     str2 = dupcat("Fatal: ", str, "\n", NULL);
116     sfree(str);
117     va_end(ap);
118     tell_str(stderr, str2);
119     sfree(str2);
120     errs++;
121
122     cleanup_exit(1);
123 }
124 void nonfatal(const char *fmt, ...)
125 {
126     char *str, *str2;
127     va_list ap;
128     va_start(ap, fmt);
129     str = dupvprintf(fmt, ap);
130     str2 = dupcat("Error: ", str, "\n", NULL);
131     sfree(str);
132     va_end(ap);
133     tell_str(stderr, str2);
134     sfree(str2);
135     errs++;
136 }
137 void connection_fatal(void *frontend, const char *fmt, ...)
138 {
139     char *str, *str2;
140     va_list ap;
141     va_start(ap, fmt);
142     str = dupvprintf(fmt, ap);
143     str2 = dupcat("Fatal: ", str, "\n", NULL);
144     sfree(str);
145     va_end(ap);
146     tell_str(stderr, str2);
147     sfree(str2);
148     errs++;
149
150     cleanup_exit(1);
151 }
152
153 /*
154  * In pscp, all agent requests should be synchronous, so this is a
155  * never-called stub.
156  */
157 void agent_schedule_callback(void (*callback)(void *, void *, int),
158                              void *callback_ctx, void *data, int len)
159 {
160     assert(!"We shouldn't be here");
161 }
162
163 /*
164  * Receive a block of data from the SSH link. Block until all data
165  * is available.
166  *
167  * To do this, we repeatedly call the SSH protocol module, with our
168  * own trap in from_backend() to catch the data that comes back. We
169  * do this until we have enough data.
170  */
171
172 static unsigned char *outptr;          /* where to put the data */
173 static unsigned outlen;                /* how much data required */
174 static unsigned char *pending = NULL;  /* any spare data */
175 static unsigned pendlen = 0, pendsize = 0;      /* length and phys. size of buffer */
176 int from_backend(void *frontend, int is_stderr, const char *data, int datalen)
177 {
178     unsigned char *p = (unsigned char *) data;
179     unsigned len = (unsigned) datalen;
180
181     /*
182      * stderr data is just spouted to local stderr and otherwise
183      * ignored.
184      */
185     if (is_stderr) {
186         if (len > 0)
187             if (fwrite(data, 1, len, stderr) < len)
188                 /* oh well */;
189         return 0;
190     }
191
192     if ((outlen > 0) && (len > 0)) {
193         unsigned used = outlen;
194         if (used > len)
195             used = len;
196         memcpy(outptr, p, used);
197         outptr += used;
198         outlen -= used;
199         p += used;
200         len -= used;
201     }
202
203     if (len > 0) {
204         if (pendsize < pendlen + len) {
205             pendsize = pendlen + len + 4096;
206             pending = sresize(pending, pendsize, unsigned char);
207         }
208         memcpy(pending + pendlen, p, len);
209         pendlen += len;
210     }
211
212     return 0;
213 }
214 int from_backend_untrusted(void *frontend_handle, const char *data, int len)
215 {
216     /*
217      * No "untrusted" output should get here (the way the code is
218      * currently, it's all diverted by FLAG_STDERR).
219      */
220     assert(!"Unexpected call to from_backend_untrusted()");
221     return 0; /* not reached */
222 }
223 int from_backend_eof(void *frontend)
224 {
225     /*
226      * We usually expect to be the party deciding when to close the
227      * connection, so if we see EOF before we sent it ourselves, we
228      * should panic. The exception is if we're using old-style scp and
229      * downloading rather than uploading.
230      */
231     if ((using_sftp || uploading) && !sent_eof) {
232         connection_fatal(frontend,
233                          "Received unexpected end-of-file from server");
234     }
235     return FALSE;
236 }
237 static int ssh_scp_recv(unsigned char *buf, int len)
238 {
239     outptr = buf;
240     outlen = len;
241
242     /*
243      * See if the pending-input block contains some of what we
244      * need.
245      */
246     if (pendlen > 0) {
247         unsigned pendused = pendlen;
248         if (pendused > outlen)
249             pendused = outlen;
250         memcpy(outptr, pending, pendused);
251         memmove(pending, pending + pendused, pendlen - pendused);
252         outptr += pendused;
253         outlen -= pendused;
254         pendlen -= pendused;
255         if (pendlen == 0) {
256             pendsize = 0;
257             sfree(pending);
258             pending = NULL;
259         }
260         if (outlen == 0)
261             return len;
262     }
263
264     while (outlen > 0) {
265         if (back->exitcode(backhandle) >= 0 || ssh_sftp_loop_iteration() < 0)
266             return 0;                  /* doom */
267     }
268
269     return len;
270 }
271
272 /*
273  * Loop through the ssh connection and authentication process.
274  */
275 static void ssh_scp_init(void)
276 {
277     while (!back->sendok(backhandle)) {
278         if (back->exitcode(backhandle) >= 0) {
279             errs++;
280             return;
281         }
282         if (ssh_sftp_loop_iteration() < 0) {
283             errs++;
284             return;                    /* doom */
285         }
286     }
287
288     /* Work out which backend we ended up using. */
289     if (!ssh_fallback_cmd(backhandle))
290         using_sftp = main_cmd_is_sftp;
291     else
292         using_sftp = fallback_cmd_is_sftp;
293
294     if (verbose) {
295         if (using_sftp)
296             tell_user(stderr, "Using SFTP");
297         else
298             tell_user(stderr, "Using SCP1");
299     }
300 }
301
302 /*
303  *  Print an error message and exit after closing the SSH link.
304  */
305 static void bump(const char *fmt, ...)
306 {
307     char *str, *str2;
308     va_list ap;
309     va_start(ap, fmt);
310     str = dupvprintf(fmt, ap);
311     va_end(ap);
312     str2 = dupcat(str, "\n", NULL);
313     sfree(str);
314     tell_str(stderr, str2);
315     sfree(str2);
316     errs++;
317
318     if (back != NULL && back->connected(backhandle)) {
319         char ch;
320         back->special(backhandle, TS_EOF);
321         sent_eof = TRUE;
322         ssh_scp_recv((unsigned char *) &ch, 1);
323     }
324
325     cleanup_exit(1);
326 }
327
328 /*
329  * Wait for the reply to a single SFTP request. Parallels the same
330  * function in psftp.c (but isn't centralised into sftp.c because the
331  * latter module handles SFTP only and shouldn't assume that SFTP is
332  * the only thing going on by calling connection_fatal).
333  */
334 struct sftp_packet *sftp_wait_for_reply(struct sftp_request *req)
335 {
336     struct sftp_packet *pktin;
337     struct sftp_request *rreq;
338
339     sftp_register(req);
340     pktin = sftp_recv();
341     if (pktin == NULL)
342         connection_fatal(NULL, "did not receive SFTP response packet "
343                          "from server");
344     rreq = sftp_find_request(pktin);
345     if (rreq != req)
346         connection_fatal(NULL, "unable to understand SFTP response packet "
347                          "from server: %s", fxp_error());
348     return pktin;
349 }
350
351 /*
352  *  Open an SSH connection to user@host and execute cmd.
353  */
354 static void do_cmd(char *host, char *user, char *cmd)
355 {
356     const char *err;
357     char *realhost;
358     void *logctx;
359
360     if (host == NULL || host[0] == '\0')
361         bump("Empty host name");
362
363     /*
364      * Remove a colon suffix.
365      */
366     host[host_strcspn(host, ":")] = '\0';
367
368     /*
369      * If we haven't loaded session details already (e.g., from -load),
370      * try looking for a session called "host".
371      */
372     if (!loaded_session) {
373         /* Try to load settings for `host' into a temporary config */
374         Conf *conf2 = conf_new();
375         conf_set_str(conf2, CONF_host, "");
376         do_defaults(host, conf2);
377         if (conf_get_str(conf2, CONF_host)[0] != '\0') {
378             /* Settings present and include hostname */
379             /* Re-load data into the real config. */
380             do_defaults(host, conf);
381         } else {
382             /* Session doesn't exist or mention a hostname. */
383             /* Use `host' as a bare hostname. */
384             conf_set_str(conf, CONF_host, host);
385         }
386         conf_free(conf2);
387     } else {
388         /* Patch in hostname `host' to session details. */
389         conf_set_str(conf, CONF_host, host);
390     }
391
392     /*
393      * Force use of SSH. (If they got the protocol wrong we assume the
394      * port is useless too.)
395      */
396     if (conf_get_int(conf, CONF_protocol) != PROT_SSH) {
397         conf_set_int(conf, CONF_protocol, PROT_SSH);
398         conf_set_int(conf, CONF_port, 22);
399     }
400
401     /*
402      * Enact command-line overrides.
403      */
404     cmdline_run_saved(conf);
405
406     /*
407      * Muck about with the hostname in various ways.
408      */
409     {
410         char *hostbuf = dupstr(conf_get_str(conf, CONF_host));
411         char *host = hostbuf;
412         char *p, *q;
413
414         /*
415          * Trim leading whitespace.
416          */
417         host += strspn(host, " \t");
418
419         /*
420          * See if host is of the form user@host, and separate out
421          * the username if so.
422          */
423         if (host[0] != '\0') {
424             char *atsign = strrchr(host, '@');
425             if (atsign) {
426                 *atsign = '\0';
427                 conf_set_str(conf, CONF_username, host);
428                 host = atsign + 1;
429             }
430         }
431
432         /*
433          * Remove any remaining whitespace.
434          */
435         p = hostbuf;
436         q = host;
437         while (*q) {
438             if (*q != ' ' && *q != '\t')
439                 *p++ = *q;
440             q++;
441         }
442         *p = '\0';
443
444         conf_set_str(conf, CONF_host, hostbuf);
445         sfree(hostbuf);
446     }
447
448     /* Set username */
449     if (user != NULL && user[0] != '\0') {
450         conf_set_str(conf, CONF_username, user);
451     } else if (conf_get_str(conf, CONF_username)[0] == '\0') {
452         user = get_username();
453         if (!user)
454             bump("Empty user name");
455         else {
456             if (verbose)
457                 tell_user(stderr, "Guessing user name: %s", user);
458             conf_set_str(conf, CONF_username, user);
459             sfree(user);
460         }
461     }
462
463     /*
464      * Disable scary things which shouldn't be enabled for simple
465      * things like SCP and SFTP: agent forwarding, port forwarding,
466      * X forwarding.
467      */
468     conf_set_int(conf, CONF_x11_forward, 0);
469     conf_set_int(conf, CONF_agentfwd, 0);
470     conf_set_int(conf, CONF_ssh_simple, TRUE);
471     {
472         char *key;
473         while ((key = conf_get_str_nthstrkey(conf, CONF_portfwd, 0)) != NULL)
474             conf_del_str_str(conf, CONF_portfwd, key);
475     }
476
477     /*
478      * Set up main and possibly fallback command depending on
479      * options specified by user.
480      * Attempt to start the SFTP subsystem as a first choice,
481      * falling back to the provided scp command if that fails.
482      */
483     conf_set_str(conf, CONF_remote_cmd2, "");
484     if (try_sftp) {
485         /* First choice is SFTP subsystem. */
486         main_cmd_is_sftp = 1;
487         conf_set_str(conf, CONF_remote_cmd, "sftp");
488         conf_set_int(conf, CONF_ssh_subsys, TRUE);
489         if (try_scp) {
490             /* Fallback is to use the provided scp command. */
491             fallback_cmd_is_sftp = 0;
492             conf_set_str(conf, CONF_remote_cmd2, cmd);
493             conf_set_int(conf, CONF_ssh_subsys2, FALSE);
494         } else {
495             /* Since we're not going to try SCP, we may as well try
496              * harder to find an SFTP server, since in the current
497              * implementation we have a spare slot. */
498             fallback_cmd_is_sftp = 1;
499             /* see psftp.c for full explanation of this kludge */
500             conf_set_str(conf, CONF_remote_cmd2,
501                          "test -x /usr/lib/sftp-server &&"
502                          " exec /usr/lib/sftp-server\n"
503                          "test -x /usr/local/lib/sftp-server &&"
504                          " exec /usr/local/lib/sftp-server\n"
505                          "exec sftp-server");
506             conf_set_int(conf, CONF_ssh_subsys2, FALSE);
507         }
508     } else {
509         /* Don't try SFTP at all; just try the scp command. */
510         main_cmd_is_sftp = 0;
511         conf_set_str(conf, CONF_remote_cmd, cmd);
512         conf_set_int(conf, CONF_ssh_subsys, FALSE);
513     }
514     conf_set_int(conf, CONF_nopty, TRUE);
515
516     back = &ssh_backend;
517
518     logctx = log_init(NULL, conf);
519     console_provide_logctx(logctx);
520
521     platform_psftp_pre_conn_setup();
522
523     err = back->init(NULL, &backhandle, conf,
524                      conf_get_str(conf, CONF_host),
525                      conf_get_int(conf, CONF_port),
526                      &realhost, 0,
527                      conf_get_int(conf, CONF_tcp_keepalives));
528     if (err != NULL)
529         bump("ssh_init: %s", err);
530     back->provide_logctx(backhandle, logctx);
531     ssh_scp_init();
532     if (verbose && realhost != NULL && errs == 0)
533         tell_user(stderr, "Connected to %s", realhost);
534     sfree(realhost);
535 }
536
537 /*
538  *  Update statistic information about current file.
539  */
540 static void print_stats(const char *name, uint64 size, uint64 done,
541                         time_t start, time_t now)
542 {
543     float ratebs;
544     unsigned long eta;
545     char *etastr;
546     int pct;
547     int len;
548     int elap;
549     double donedbl;
550     double sizedbl;
551
552     elap = (unsigned long) difftime(now, start);
553
554     if (now > start)
555         ratebs = (float) (uint64_to_double(done) / elap);
556     else
557         ratebs = (float) uint64_to_double(done);
558
559     if (ratebs < 1.0)
560         eta = (unsigned long) (uint64_to_double(uint64_subtract(size, done)));
561     else {
562         eta = (unsigned long)
563             ((uint64_to_double(uint64_subtract(size, done)) / ratebs));
564     }
565
566     etastr = dupprintf("%02ld:%02ld:%02ld",
567                        eta / 3600, (eta % 3600) / 60, eta % 60);
568
569     donedbl = uint64_to_double(done);
570     sizedbl = uint64_to_double(size);
571     pct = (int) (100 * (donedbl * 1.0 / sizedbl));
572
573     {
574         char donekb[40];
575         /* divide by 1024 to provide kB */
576         uint64_decimal(uint64_shift_right(done, 10), donekb);
577         len = printf("\r%-25.25s | %s kB | %5.1f kB/s | ETA: %8s | %3d%%",
578                      name,
579                      donekb, ratebs / 1024.0, etastr, pct);
580         if (len < prev_stats_len)
581             printf("%*s", prev_stats_len - len, "");
582         prev_stats_len = len;
583
584         if (uint64_compare(done, size) == 0)
585             printf("\n");
586
587         fflush(stdout);
588     }
589
590     free(etastr);
591 }
592
593 /*
594  *  Find a colon in str and return a pointer to the colon.
595  *  This is used to separate hostname from filename.
596  */
597 static char *colon(char *str)
598 {
599     /* We ignore a leading colon, since the hostname cannot be
600        empty. We also ignore a colon as second character because
601        of filenames like f:myfile.txt. */
602     if (str[0] == '\0' || str[0] == ':' ||
603         (str[0] != '[' && str[1] == ':'))
604         return (NULL);
605     str += host_strcspn(str, ":/\\");
606     if (*str == ':')
607         return (str);
608     else
609         return (NULL);
610 }
611
612 /*
613  * Determine whether a string is entirely composed of dots.
614  */
615 static int is_dots(char *str)
616 {
617     return str[strspn(str, ".")] == '\0';
618 }
619
620 /*
621  *  Wait for a response from the other side.
622  *  Return 0 if ok, -1 if error.
623  */
624 static int response(void)
625 {
626     char ch, resp, rbuf[2048];
627     int p;
628
629     if (ssh_scp_recv((unsigned char *) &resp, 1) <= 0)
630         bump("Lost connection");
631
632     p = 0;
633     switch (resp) {
634       case 0:                          /* ok */
635         return (0);
636       default:
637         rbuf[p++] = resp;
638         /* fallthrough */
639       case 1:                          /* error */
640       case 2:                          /* fatal error */
641         do {
642             if (ssh_scp_recv((unsigned char *) &ch, 1) <= 0)
643                 bump("Protocol error: Lost connection");
644             rbuf[p++] = ch;
645         } while (p < sizeof(rbuf) && ch != '\n');
646         rbuf[p - 1] = '\0';
647         if (resp == 1)
648             tell_user(stderr, "%s", rbuf);
649         else
650             bump("%s", rbuf);
651         errs++;
652         return (-1);
653     }
654 }
655
656 int sftp_recvdata(char *buf, int len)
657 {
658     return ssh_scp_recv((unsigned char *) buf, len);
659 }
660 int sftp_senddata(char *buf, int len)
661 {
662     back->send(backhandle, buf, len);
663     return 1;
664 }
665 int sftp_sendbuffer(void)
666 {
667     return back->sendbuffer(backhandle);
668 }
669
670 /* ----------------------------------------------------------------------
671  * sftp-based replacement for the hacky `pscp -ls'.
672  */
673 static int sftp_ls_compare(const void *av, const void *bv)
674 {
675     const struct fxp_name *a = (const struct fxp_name *) av;
676     const struct fxp_name *b = (const struct fxp_name *) bv;
677     return strcmp(a->filename, b->filename);
678 }
679 void scp_sftp_listdir(const char *dirname)
680 {
681     struct fxp_handle *dirh;
682     struct fxp_names *names;
683     struct fxp_name *ournames;
684     struct sftp_packet *pktin;
685     struct sftp_request *req;
686     int nnames, namesize;
687     int i;
688
689     if (!fxp_init()) {
690         tell_user(stderr, "unable to initialise SFTP: %s", fxp_error());
691         errs++;
692         return;
693     }
694
695     printf("Listing directory %s\n", dirname);
696
697     req = fxp_opendir_send(dirname);
698     pktin = sftp_wait_for_reply(req);
699     dirh = fxp_opendir_recv(pktin, req);
700
701     if (dirh == NULL) {
702                 tell_user(stderr, "Unable to open %s: %s\n", dirname, fxp_error());
703                 errs++;
704     } else {
705         nnames = namesize = 0;
706         ournames = NULL;
707
708         while (1) {
709
710             req = fxp_readdir_send(dirh);
711             pktin = sftp_wait_for_reply(req);
712             names = fxp_readdir_recv(pktin, req);
713
714             if (names == NULL) {
715                 if (fxp_error_type() == SSH_FX_EOF)
716                     break;
717                 printf("Reading directory %s: %s\n", dirname, fxp_error());
718                 break;
719             }
720             if (names->nnames == 0) {
721                 fxp_free_names(names);
722                 break;
723             }
724
725             if (nnames + names->nnames >= namesize) {
726                 namesize += names->nnames + 128;
727                 ournames = sresize(ournames, namesize, struct fxp_name);
728             }
729
730             for (i = 0; i < names->nnames; i++)
731                 ournames[nnames++] = names->names[i];
732             names->nnames = 0;         /* prevent free_names */
733             fxp_free_names(names);
734         }
735         req = fxp_close_send(dirh);
736         pktin = sftp_wait_for_reply(req);
737         fxp_close_recv(pktin, req);
738
739         /*
740          * Now we have our filenames. Sort them by actual file
741          * name, and then output the longname parts.
742          */
743         if (nnames > 0)
744             qsort(ournames, nnames, sizeof(*ournames), sftp_ls_compare);
745
746         /*
747          * And print them.
748          */
749         for (i = 0; i < nnames; i++)
750             printf("%s\n", ournames[i].longname);
751
752         sfree(ournames);
753     }
754 }
755
756 /* ----------------------------------------------------------------------
757  * Helper routines that contain the actual SCP protocol elements,
758  * implemented both as SCP1 and SFTP.
759  */
760
761 static struct scp_sftp_dirstack {
762     struct scp_sftp_dirstack *next;
763     struct fxp_name *names;
764     int namepos, namelen;
765     char *dirpath;
766     char *wildcard;
767     int matched_something;             /* wildcard match set was non-empty */
768 } *scp_sftp_dirstack_head;
769 static char *scp_sftp_remotepath, *scp_sftp_currentname;
770 static char *scp_sftp_wildcard;
771 static int scp_sftp_targetisdir, scp_sftp_donethistarget;
772 static int scp_sftp_preserve, scp_sftp_recursive;
773 static unsigned long scp_sftp_mtime, scp_sftp_atime;
774 static int scp_has_times;
775 static struct fxp_handle *scp_sftp_filehandle;
776 static struct fxp_xfer *scp_sftp_xfer;
777 static uint64 scp_sftp_fileoffset;
778
779 int scp_source_setup(const char *target, int shouldbedir)
780 {
781     if (using_sftp) {
782         /*
783          * Find out whether the target filespec is in fact a
784          * directory.
785          */
786         struct sftp_packet *pktin;
787         struct sftp_request *req;
788         struct fxp_attrs attrs;
789         int ret;
790
791         if (!fxp_init()) {
792             tell_user(stderr, "unable to initialise SFTP: %s", fxp_error());
793             errs++;
794             return 1;
795         }
796
797         req = fxp_stat_send(target);
798         pktin = sftp_wait_for_reply(req);
799         ret = fxp_stat_recv(pktin, req, &attrs);
800
801         if (!ret || !(attrs.flags & SSH_FILEXFER_ATTR_PERMISSIONS))
802             scp_sftp_targetisdir = 0;
803         else
804             scp_sftp_targetisdir = (attrs.permissions & 0040000) != 0;
805
806         if (shouldbedir && !scp_sftp_targetisdir) {
807             bump("pscp: remote filespec %s: not a directory\n", target);
808         }
809
810         scp_sftp_remotepath = dupstr(target);
811
812         scp_has_times = 0;
813     } else {
814         (void) response();
815     }
816     return 0;
817 }
818
819 int scp_send_errmsg(char *str)
820 {
821     if (using_sftp) {
822         /* do nothing; we never need to send our errors to the server */
823     } else {
824         back->send(backhandle, "\001", 1);/* scp protocol error prefix */
825         back->send(backhandle, str, strlen(str));
826     }
827     return 0;                          /* can't fail */
828 }
829
830 int scp_send_filetimes(unsigned long mtime, unsigned long atime)
831 {
832     if (using_sftp) {
833         scp_sftp_mtime = mtime;
834         scp_sftp_atime = atime;
835         scp_has_times = 1;
836         return 0;
837     } else {
838         char buf[80];
839         sprintf(buf, "T%lu 0 %lu 0\n", mtime, atime);
840         back->send(backhandle, buf, strlen(buf));
841         return response();
842     }
843 }
844
845 int scp_send_filename(const char *name, uint64 size, int permissions)
846 {
847     if (using_sftp) {
848         char *fullname;
849         struct sftp_packet *pktin;
850         struct sftp_request *req;
851         struct fxp_attrs attrs;
852
853         if (scp_sftp_targetisdir) {
854             fullname = dupcat(scp_sftp_remotepath, "/", name, NULL);
855         } else {
856             fullname = dupstr(scp_sftp_remotepath);
857         }
858
859         attrs.flags = 0;
860         PUT_PERMISSIONS(attrs, permissions);
861
862         req = fxp_open_send(fullname,
863                             SSH_FXF_WRITE | SSH_FXF_CREAT | SSH_FXF_TRUNC,
864                             &attrs);
865         pktin = sftp_wait_for_reply(req);
866         scp_sftp_filehandle = fxp_open_recv(pktin, req);
867
868         if (!scp_sftp_filehandle) {
869             tell_user(stderr, "pscp: unable to open %s: %s",
870                       fullname, fxp_error());
871             sfree(fullname);
872             errs++;
873             return 1;
874         }
875         scp_sftp_fileoffset = uint64_make(0, 0);
876         scp_sftp_xfer = xfer_upload_init(scp_sftp_filehandle,
877                                          scp_sftp_fileoffset);
878         sfree(fullname);
879         return 0;
880     } else {
881         char buf[40];
882         char sizestr[40];
883         uint64_decimal(size, sizestr);
884         if (permissions < 0)
885             permissions = 0644;
886         sprintf(buf, "C%04o %s ", (int)(permissions & 07777), sizestr);
887         back->send(backhandle, buf, strlen(buf));
888         back->send(backhandle, name, strlen(name));
889         back->send(backhandle, "\n", 1);
890         return response();
891     }
892 }
893
894 int scp_send_filedata(char *data, int len)
895 {
896     if (using_sftp) {
897         int ret;
898         struct sftp_packet *pktin;
899
900         if (!scp_sftp_filehandle) {
901             return 1;
902         }
903
904         while (!xfer_upload_ready(scp_sftp_xfer)) {
905             pktin = sftp_recv();
906             ret = xfer_upload_gotpkt(scp_sftp_xfer, pktin);
907             if (ret <= 0) {
908                 tell_user(stderr, "error while writing: %s", fxp_error());
909                 if (ret == INT_MIN)        /* pktin not even freed */
910                     sfree(pktin);
911                 errs++;
912                 return 1;
913             }
914         }
915
916         xfer_upload_data(scp_sftp_xfer, data, len);
917
918         scp_sftp_fileoffset = uint64_add32(scp_sftp_fileoffset, len);
919         return 0;
920     } else {
921         int bufsize = back->send(backhandle, data, len);
922
923         /*
924          * If the network transfer is backing up - that is, the
925          * remote site is not accepting data as fast as we can
926          * produce it - then we must loop on network events until
927          * we have space in the buffer again.
928          */
929         while (bufsize > MAX_SCP_BUFSIZE) {
930             if (ssh_sftp_loop_iteration() < 0)
931                 return 1;
932             bufsize = back->sendbuffer(backhandle);
933         }
934
935         return 0;
936     }
937 }
938
939 int scp_send_finish(void)
940 {
941     if (using_sftp) {
942         struct fxp_attrs attrs;
943         struct sftp_packet *pktin;
944         struct sftp_request *req;
945         int ret;
946
947         while (!xfer_done(scp_sftp_xfer)) {
948             pktin = sftp_recv();
949             ret = xfer_upload_gotpkt(scp_sftp_xfer, pktin);
950             if (ret <= 0) {
951                 tell_user(stderr, "error while writing: %s", fxp_error());
952                 if (ret == INT_MIN)        /* pktin not even freed */
953                     sfree(pktin);
954                 errs++;
955                 return 1;
956             }
957         }
958         xfer_cleanup(scp_sftp_xfer);
959
960         if (!scp_sftp_filehandle) {
961             return 1;
962         }
963         if (scp_has_times) {
964             attrs.flags = SSH_FILEXFER_ATTR_ACMODTIME;
965             attrs.atime = scp_sftp_atime;
966             attrs.mtime = scp_sftp_mtime;
967             req = fxp_fsetstat_send(scp_sftp_filehandle, attrs);
968             pktin = sftp_wait_for_reply(req);
969             ret = fxp_fsetstat_recv(pktin, req);
970             if (!ret) {
971                 tell_user(stderr, "unable to set file times: %s", fxp_error());
972                 errs++;
973             }
974         }
975         req = fxp_close_send(scp_sftp_filehandle);
976         pktin = sftp_wait_for_reply(req);
977         fxp_close_recv(pktin, req);
978         scp_has_times = 0;
979         return 0;
980     } else {
981         back->send(backhandle, "", 1);
982         return response();
983     }
984 }
985
986 char *scp_save_remotepath(void)
987 {
988     if (using_sftp)
989         return scp_sftp_remotepath;
990     else
991         return NULL;
992 }
993
994 void scp_restore_remotepath(char *data)
995 {
996     if (using_sftp)
997         scp_sftp_remotepath = data;
998 }
999
1000 int scp_send_dirname(const char *name, int modes)
1001 {
1002     if (using_sftp) {
1003         char *fullname;
1004         char const *err;
1005         struct fxp_attrs attrs;
1006         struct sftp_packet *pktin;
1007         struct sftp_request *req;
1008         int ret;
1009
1010         if (scp_sftp_targetisdir) {
1011             fullname = dupcat(scp_sftp_remotepath, "/", name, NULL);
1012         } else {
1013             fullname = dupstr(scp_sftp_remotepath);
1014         }
1015
1016         /*
1017          * We don't worry about whether we managed to create the
1018          * directory, because if it exists already it's OK just to
1019          * use it. Instead, we will stat it afterwards, and if it
1020          * exists and is a directory we will assume we were either
1021          * successful or it didn't matter.
1022          */
1023         req = fxp_mkdir_send(fullname);
1024         pktin = sftp_wait_for_reply(req);
1025         ret = fxp_mkdir_recv(pktin, req);
1026
1027         if (!ret)
1028             err = fxp_error();
1029         else
1030             err = "server reported no error";
1031
1032         req = fxp_stat_send(fullname);
1033         pktin = sftp_wait_for_reply(req);
1034         ret = fxp_stat_recv(pktin, req, &attrs);
1035
1036         if (!ret || !(attrs.flags & SSH_FILEXFER_ATTR_PERMISSIONS) ||
1037             !(attrs.permissions & 0040000)) {
1038             tell_user(stderr, "unable to create directory %s: %s",
1039                       fullname, err);
1040             sfree(fullname);
1041             errs++;
1042             return 1;
1043         }
1044
1045         scp_sftp_remotepath = fullname;
1046
1047         return 0;
1048     } else {
1049         char buf[40];
1050         sprintf(buf, "D%04o 0 ", modes);
1051         back->send(backhandle, buf, strlen(buf));
1052         back->send(backhandle, name, strlen(name));
1053         back->send(backhandle, "\n", 1);
1054         return response();
1055     }
1056 }
1057
1058 int scp_send_enddir(void)
1059 {
1060     if (using_sftp) {
1061         sfree(scp_sftp_remotepath);
1062         return 0;
1063     } else {
1064         back->send(backhandle, "E\n", 2);
1065         return response();
1066     }
1067 }
1068
1069 /*
1070  * Yes, I know; I have an scp_sink_setup _and_ an scp_sink_init.
1071  * That's bad. The difference is that scp_sink_setup is called once
1072  * right at the start, whereas scp_sink_init is called to
1073  * initialise every level of recursion in the protocol.
1074  */
1075 int scp_sink_setup(const char *source, int preserve, int recursive)
1076 {
1077     if (using_sftp) {
1078         char *newsource;
1079
1080         if (!fxp_init()) {
1081             tell_user(stderr, "unable to initialise SFTP: %s", fxp_error());
1082             errs++;
1083             return 1;
1084         }
1085         /*
1086          * It's possible that the source string we've been given
1087          * contains a wildcard. If so, we must split the directory
1088          * away from the wildcard itself (throwing an error if any
1089          * wildcardness comes before the final slash) and arrange
1090          * things so that a dirstack entry will be set up.
1091          */
1092         newsource = snewn(1+strlen(source), char);
1093         if (!wc_unescape(newsource, source)) {
1094             /* Yes, here we go; it's a wildcard. Bah. */
1095             char *dupsource, *lastpart, *dirpart, *wildcard;
1096
1097             sfree(newsource);
1098
1099             dupsource = dupstr(source);
1100             lastpart = stripslashes(dupsource, 0);
1101             wildcard = dupstr(lastpart);
1102             *lastpart = '\0';
1103             if (*dupsource && dupsource[1]) {
1104                 /*
1105                  * The remains of dupsource are at least two
1106                  * characters long, meaning the pathname wasn't
1107                  * empty or just `/'. Hence, we remove the trailing
1108                  * slash.
1109                  */
1110                 lastpart[-1] = '\0';
1111             } else if (!*dupsource) {
1112                 /*
1113                  * The remains of dupsource are _empty_ - the whole
1114                  * pathname was a wildcard. Hence we need to
1115                  * replace it with ".".
1116                  */
1117                 sfree(dupsource);
1118                 dupsource = dupstr(".");
1119             }
1120
1121             /*
1122              * Now we have separated our string into dupsource (the
1123              * directory part) and wildcard. Both of these will
1124              * need freeing at some point. Next step is to remove
1125              * wildcard escapes from the directory part, throwing
1126              * an error if it contains a real wildcard.
1127              */
1128             dirpart = snewn(1+strlen(dupsource), char);
1129             if (!wc_unescape(dirpart, dupsource)) {
1130                 tell_user(stderr, "%s: multiple-level wildcards unsupported",
1131                           source);
1132                 errs++;
1133                 sfree(dirpart);
1134                 sfree(wildcard);
1135                 sfree(dupsource);
1136                 return 1;
1137             }
1138
1139             /*
1140              * Now we have dirpart (unescaped, ie a valid remote
1141              * path), and wildcard (a wildcard). This will be
1142              * sufficient to arrange a dirstack entry.
1143              */
1144             scp_sftp_remotepath = dirpart;
1145             scp_sftp_wildcard = wildcard;
1146             sfree(dupsource);
1147         } else {
1148             scp_sftp_remotepath = newsource;
1149             scp_sftp_wildcard = NULL;
1150         }
1151         scp_sftp_preserve = preserve;
1152         scp_sftp_recursive = recursive;
1153         scp_sftp_donethistarget = 0;
1154         scp_sftp_dirstack_head = NULL;
1155     }
1156     return 0;
1157 }
1158
1159 int scp_sink_init(void)
1160 {
1161     if (!using_sftp) {
1162         back->send(backhandle, "", 1);
1163     }
1164     return 0;
1165 }
1166
1167 #define SCP_SINK_FILE   1
1168 #define SCP_SINK_DIR    2
1169 #define SCP_SINK_ENDDIR 3
1170 #define SCP_SINK_RETRY  4              /* not an action; just try again */
1171 struct scp_sink_action {
1172     int action;                        /* FILE, DIR, ENDDIR */
1173     char *buf;                         /* will need freeing after use */
1174     char *name;                        /* filename or dirname (not ENDDIR) */
1175     long permissions;          /* access permissions (not ENDDIR) */
1176     uint64 size;                       /* file size (not ENDDIR) */
1177     int settime;                       /* 1 if atime and mtime are filled */
1178     unsigned long atime, mtime;        /* access times for the file */
1179 };
1180
1181 int scp_get_sink_action(struct scp_sink_action *act)
1182 {
1183     if (using_sftp) {
1184         char *fname;
1185         int must_free_fname;
1186         struct fxp_attrs attrs;
1187         struct sftp_packet *pktin;
1188         struct sftp_request *req;
1189         int ret;
1190
1191         if (!scp_sftp_dirstack_head) {
1192             if (!scp_sftp_donethistarget) {
1193                 /*
1194                  * Simple case: we are only dealing with one file.
1195                  */
1196                 fname = scp_sftp_remotepath;
1197                 must_free_fname = 0;
1198                 scp_sftp_donethistarget = 1;
1199             } else {
1200                 /*
1201                  * Even simpler case: one file _which we've done_.
1202                  * Return 1 (finished).
1203                  */
1204                 return 1;
1205             }
1206         } else {
1207             /*
1208              * We're now in the middle of stepping through a list
1209              * of names returned from fxp_readdir(); so let's carry
1210              * on.
1211              */
1212             struct scp_sftp_dirstack *head = scp_sftp_dirstack_head;
1213             while (head->namepos < head->namelen &&
1214                    (is_dots(head->names[head->namepos].filename) ||
1215                     (head->wildcard &&
1216                      !wc_match(head->wildcard,
1217                                head->names[head->namepos].filename))))
1218                 head->namepos++;       /* skip . and .. */
1219             if (head->namepos < head->namelen) {
1220                 head->matched_something = 1;
1221                 fname = dupcat(head->dirpath, "/",
1222                                head->names[head->namepos++].filename,
1223                                NULL);
1224                 must_free_fname = 1;
1225             } else {
1226                 /*
1227                  * We've come to the end of the list; pop it off
1228                  * the stack and return an ENDDIR action (or RETRY
1229                  * if this was a wildcard match).
1230                  */
1231                 if (head->wildcard) {
1232                     act->action = SCP_SINK_RETRY;
1233                     if (!head->matched_something) {
1234                         tell_user(stderr, "pscp: wildcard '%s' matched "
1235                                   "no files", head->wildcard);
1236                         errs++;
1237                     }
1238                     sfree(head->wildcard);
1239
1240                 } else {
1241                     act->action = SCP_SINK_ENDDIR;
1242                 }
1243
1244                 sfree(head->dirpath);
1245                 sfree(head->names);
1246                 scp_sftp_dirstack_head = head->next;
1247                 sfree(head);
1248
1249                 return 0;
1250             }
1251         }
1252
1253         /*
1254          * Now we have a filename. Stat it, and see if it's a file
1255          * or a directory.
1256          */
1257         req = fxp_stat_send(fname);
1258         pktin = sftp_wait_for_reply(req);
1259         ret = fxp_stat_recv(pktin, req, &attrs);
1260
1261         if (!ret || !(attrs.flags & SSH_FILEXFER_ATTR_PERMISSIONS)) {
1262             tell_user(stderr, "unable to identify %s: %s", fname,
1263                       ret ? "file type not supplied" : fxp_error());
1264             if (must_free_fname) sfree(fname);
1265             errs++;
1266             return 1;
1267         }
1268
1269         if (attrs.permissions & 0040000) {
1270             struct scp_sftp_dirstack *newitem;
1271             struct fxp_handle *dirhandle;
1272             int nnames, namesize;
1273             struct fxp_name *ournames;
1274             struct fxp_names *names;
1275
1276             /*
1277              * It's a directory. If we're not in recursive mode,
1278              * this merits a complaint (which is fatal if the name
1279              * was specified directly, but not if it was matched by
1280              * a wildcard).
1281              * 
1282              * We skip this complaint completely if
1283              * scp_sftp_wildcard is set, because that's an
1284              * indication that we're not actually supposed to
1285              * _recursively_ transfer the dir, just scan it for
1286              * things matching the wildcard.
1287              */
1288             if (!scp_sftp_recursive && !scp_sftp_wildcard) {
1289                 tell_user(stderr, "pscp: %s: is a directory", fname);
1290                 errs++;
1291                 if (must_free_fname) sfree(fname);
1292                 if (scp_sftp_dirstack_head) {
1293                     act->action = SCP_SINK_RETRY;
1294                     return 0;
1295                 } else {
1296                     return 1;
1297                 }
1298             }
1299
1300             /*
1301              * Otherwise, the fun begins. We must fxp_opendir() the
1302              * directory, slurp the filenames into memory, return
1303              * SCP_SINK_DIR (unless this is a wildcard match), and
1304              * set targetisdir. The next time we're called, we will
1305              * run through the list of filenames one by one,
1306              * matching them against a wildcard if present.
1307              * 
1308              * If targetisdir is _already_ set (meaning we're
1309              * already in the middle of going through another such
1310              * list), we must push the other (target,namelist) pair
1311              * on a stack.
1312              */
1313             req = fxp_opendir_send(fname);
1314             pktin = sftp_wait_for_reply(req);
1315             dirhandle = fxp_opendir_recv(pktin, req);
1316
1317             if (!dirhandle) {
1318                 tell_user(stderr, "pscp: unable to open directory %s: %s",
1319                           fname, fxp_error());
1320                 if (must_free_fname) sfree(fname);
1321                 errs++;
1322                 return 1;
1323             }
1324             nnames = namesize = 0;
1325             ournames = NULL;
1326             while (1) {
1327                 int i;
1328
1329                 req = fxp_readdir_send(dirhandle);
1330                 pktin = sftp_wait_for_reply(req);
1331                 names = fxp_readdir_recv(pktin, req);
1332
1333                 if (names == NULL) {
1334                     if (fxp_error_type() == SSH_FX_EOF)
1335                         break;
1336                     tell_user(stderr, "pscp: reading directory %s: %s",
1337                               fname, fxp_error());
1338
1339                     req = fxp_close_send(dirhandle);
1340                     pktin = sftp_wait_for_reply(req);
1341                     fxp_close_recv(pktin, req);
1342
1343                     if (must_free_fname) sfree(fname);
1344                     sfree(ournames);
1345                     errs++;
1346                     return 1;
1347                 }
1348                 if (names->nnames == 0) {
1349                     fxp_free_names(names);
1350                     break;
1351                 }
1352                 if (nnames + names->nnames >= namesize) {
1353                     namesize += names->nnames + 128;
1354                     ournames = sresize(ournames, namesize, struct fxp_name);
1355                 }
1356                 for (i = 0; i < names->nnames; i++) {
1357                     if (!strcmp(names->names[i].filename, ".") ||
1358                         !strcmp(names->names[i].filename, "..")) {
1359                         /*
1360                          * . and .. are normal consequences of
1361                          * reading a directory, and aren't worth
1362                          * complaining about.
1363                          */
1364                     } else if (!vet_filename(names->names[i].filename)) {
1365                         tell_user(stderr, "ignoring potentially dangerous server-"
1366                                   "supplied filename '%s'",
1367                                   names->names[i].filename);
1368                     } else
1369                         ournames[nnames++] = names->names[i];
1370                 }
1371                 names->nnames = 0;             /* prevent free_names */
1372                 fxp_free_names(names);
1373             }
1374             req = fxp_close_send(dirhandle);
1375             pktin = sftp_wait_for_reply(req);
1376             fxp_close_recv(pktin, req);
1377
1378             newitem = snew(struct scp_sftp_dirstack);
1379             newitem->next = scp_sftp_dirstack_head;
1380             newitem->names = ournames;
1381             newitem->namepos = 0;
1382             newitem->namelen = nnames;
1383             if (must_free_fname)
1384                 newitem->dirpath = fname;
1385             else
1386                 newitem->dirpath = dupstr(fname);
1387             if (scp_sftp_wildcard) {
1388                 newitem->wildcard = scp_sftp_wildcard;
1389                 newitem->matched_something = 0;
1390                 scp_sftp_wildcard = NULL;
1391             } else {
1392                 newitem->wildcard = NULL;
1393             }
1394             scp_sftp_dirstack_head = newitem;
1395
1396             if (newitem->wildcard) {
1397                 act->action = SCP_SINK_RETRY;
1398             } else {
1399                 act->action = SCP_SINK_DIR;
1400                 act->buf = dupstr(stripslashes(fname, 0));
1401                 act->name = act->buf;
1402                 act->size = uint64_make(0,0);     /* duhh, it's a directory */
1403                 act->permissions = 07777 & attrs.permissions;
1404                 if (scp_sftp_preserve &&
1405                     (attrs.flags & SSH_FILEXFER_ATTR_ACMODTIME)) {
1406                     act->atime = attrs.atime;
1407                     act->mtime = attrs.mtime;
1408                     act->settime = 1;
1409                 } else
1410                     act->settime = 0;
1411             }
1412             return 0;
1413
1414         } else {
1415             /*
1416              * It's a file. Return SCP_SINK_FILE.
1417              */
1418             act->action = SCP_SINK_FILE;
1419             act->buf = dupstr(stripslashes(fname, 0));
1420             act->name = act->buf;
1421             if (attrs.flags & SSH_FILEXFER_ATTR_SIZE) {
1422                 act->size = attrs.size;
1423             } else
1424                 act->size = uint64_make(ULONG_MAX,ULONG_MAX);   /* no idea */
1425             act->permissions = 07777 & attrs.permissions;
1426             if (scp_sftp_preserve &&
1427                 (attrs.flags & SSH_FILEXFER_ATTR_ACMODTIME)) {
1428                 act->atime = attrs.atime;
1429                 act->mtime = attrs.mtime;
1430                 act->settime = 1;
1431             } else
1432                 act->settime = 0;
1433             if (must_free_fname)
1434                 scp_sftp_currentname = fname;
1435             else
1436                 scp_sftp_currentname = dupstr(fname);
1437             return 0;
1438         }
1439
1440     } else {
1441         int done = 0;
1442         int i, bufsize;
1443         int action;
1444         char ch;
1445
1446         act->settime = 0;
1447         act->buf = NULL;
1448         bufsize = 0;
1449
1450         while (!done) {
1451             if (ssh_scp_recv((unsigned char *) &ch, 1) <= 0)
1452                 return 1;
1453             if (ch == '\n')
1454                 bump("Protocol error: Unexpected newline");
1455             i = 0;
1456             action = ch;
1457             do {
1458                 if (ssh_scp_recv((unsigned char *) &ch, 1) <= 0)
1459                     bump("Lost connection");
1460                 if (i >= bufsize) {
1461                     bufsize = i + 128;
1462                     act->buf = sresize(act->buf, bufsize, char);
1463                 }
1464                 act->buf[i++] = ch;
1465             } while (ch != '\n');
1466             act->buf[i - 1] = '\0';
1467             switch (action) {
1468               case '\01':                      /* error */
1469                 tell_user(stderr, "%s", act->buf);
1470                 errs++;
1471                 continue;                      /* go round again */
1472               case '\02':                      /* fatal error */
1473                 bump("%s", act->buf);
1474               case 'E':
1475                 back->send(backhandle, "", 1);
1476                 act->action = SCP_SINK_ENDDIR;
1477                 return 0;
1478               case 'T':
1479                 if (sscanf(act->buf, "%ld %*d %ld %*d",
1480                            &act->mtime, &act->atime) == 2) {
1481                     act->settime = 1;
1482                     back->send(backhandle, "", 1);
1483                     continue;          /* go round again */
1484                 }
1485                 bump("Protocol error: Illegal time format");
1486               case 'C':
1487               case 'D':
1488                 act->action = (action == 'C' ? SCP_SINK_FILE : SCP_SINK_DIR);
1489                 break;
1490               default:
1491                 bump("Protocol error: Expected control record");
1492             }
1493             /*
1494              * We will go round this loop only once, unless we hit
1495              * `continue' above.
1496              */
1497             done = 1;
1498         }
1499
1500         /*
1501          * If we get here, we must have seen SCP_SINK_FILE or
1502          * SCP_SINK_DIR.
1503          */
1504         {
1505             char sizestr[40];
1506         
1507             if (sscanf(act->buf, "%lo %39s %n", &act->permissions,
1508                        sizestr, &i) != 2)
1509                 bump("Protocol error: Illegal file descriptor format");
1510             act->size = uint64_from_decimal(sizestr);
1511             act->name = act->buf + i;
1512             return 0;
1513         }
1514     }
1515 }
1516
1517 int scp_accept_filexfer(void)
1518 {
1519     if (using_sftp) {
1520         struct sftp_packet *pktin;
1521         struct sftp_request *req;
1522
1523         req = fxp_open_send(scp_sftp_currentname, SSH_FXF_READ, NULL);
1524         pktin = sftp_wait_for_reply(req);
1525         scp_sftp_filehandle = fxp_open_recv(pktin, req);
1526
1527         if (!scp_sftp_filehandle) {
1528             tell_user(stderr, "pscp: unable to open %s: %s",
1529                       scp_sftp_currentname, fxp_error());
1530             errs++;
1531             return 1;
1532         }
1533         scp_sftp_fileoffset = uint64_make(0, 0);
1534         scp_sftp_xfer = xfer_download_init(scp_sftp_filehandle,
1535                                            scp_sftp_fileoffset);
1536         sfree(scp_sftp_currentname);
1537         return 0;
1538     } else {
1539         back->send(backhandle, "", 1);
1540         return 0;                      /* can't fail */
1541     }
1542 }
1543
1544 int scp_recv_filedata(char *data, int len)
1545 {
1546     if (using_sftp) {
1547         struct sftp_packet *pktin;
1548         int ret, actuallen;
1549         void *vbuf;
1550
1551         xfer_download_queue(scp_sftp_xfer);
1552         pktin = sftp_recv();
1553         ret = xfer_download_gotpkt(scp_sftp_xfer, pktin);
1554         if (ret <= 0) {
1555             tell_user(stderr, "pscp: error while reading: %s", fxp_error());
1556             if (ret == INT_MIN)        /* pktin not even freed */
1557                 sfree(pktin);
1558             errs++;
1559             return -1;
1560         }
1561
1562         if (xfer_download_data(scp_sftp_xfer, &vbuf, &actuallen)) {
1563             if (actuallen <= 0) {
1564                 tell_user(stderr, "pscp: end of file while reading");
1565                 errs++;
1566                 sfree(vbuf);
1567                 return -1;
1568             }
1569             /*
1570              * This assertion relies on the fact that the natural
1571              * block size used in the xfer manager is at most that
1572              * used in this module. I don't like crossing layers in
1573              * this way, but it'll do for now.
1574              */
1575             assert(actuallen <= len);
1576             memcpy(data, vbuf, actuallen);
1577             sfree(vbuf);
1578         } else
1579             actuallen = 0;
1580
1581         scp_sftp_fileoffset = uint64_add32(scp_sftp_fileoffset, actuallen);
1582
1583         return actuallen;
1584     } else {
1585         return ssh_scp_recv((unsigned char *) data, len);
1586     }
1587 }
1588
1589 int scp_finish_filerecv(void)
1590 {
1591     if (using_sftp) {
1592         struct sftp_packet *pktin;
1593         struct sftp_request *req;
1594
1595         /*
1596          * Ensure that xfer_done() will work correctly, so we can
1597          * clean up any outstanding requests from the file
1598          * transfer.
1599          */
1600         xfer_set_error(scp_sftp_xfer);
1601         while (!xfer_done(scp_sftp_xfer)) {
1602             void *vbuf;
1603             int ret, len;
1604
1605             pktin = sftp_recv();
1606             ret = xfer_download_gotpkt(scp_sftp_xfer, pktin);
1607             if (ret <= 0) {
1608                 tell_user(stderr, "pscp: error while reading: %s", fxp_error());
1609                 if (ret == INT_MIN)        /* pktin not even freed */
1610                     sfree(pktin);
1611                 errs++;
1612                 return -1;
1613             }
1614             if (xfer_download_data(scp_sftp_xfer, &vbuf, &len))
1615                 sfree(vbuf);
1616         }
1617         xfer_cleanup(scp_sftp_xfer);
1618
1619         req = fxp_close_send(scp_sftp_filehandle);
1620         pktin = sftp_wait_for_reply(req);
1621         fxp_close_recv(pktin, req);
1622         return 0;
1623     } else {
1624         back->send(backhandle, "", 1);
1625         return response();
1626     }
1627 }
1628
1629 /* ----------------------------------------------------------------------
1630  *  Send an error message to the other side and to the screen.
1631  *  Increment error counter.
1632  */
1633 static void run_err(const char *fmt, ...)
1634 {
1635     char *str, *str2;
1636     va_list ap;
1637     va_start(ap, fmt);
1638     errs++;
1639     str = dupvprintf(fmt, ap);
1640     str2 = dupcat("pscp: ", str, "\n", NULL);
1641     sfree(str);
1642     scp_send_errmsg(str2);
1643     tell_user(stderr, "%s", str2);
1644     va_end(ap);
1645     sfree(str2);
1646 }
1647
1648 /*
1649  *  Execute the source part of the SCP protocol.
1650  */
1651 static void source(const char *src)
1652 {
1653     uint64 size;
1654     unsigned long mtime, atime;
1655     long permissions;
1656     const char *last;
1657     RFile *f;
1658     int attr;
1659     uint64 i;
1660     uint64 stat_bytes;
1661     time_t stat_starttime, stat_lasttime;
1662
1663     attr = file_type(src);
1664     if (attr == FILE_TYPE_NONEXISTENT ||
1665         attr == FILE_TYPE_WEIRD) {
1666         run_err("%s: %s file or directory", src,
1667                 (attr == FILE_TYPE_WEIRD ? "Not a" : "No such"));
1668         return;
1669     }
1670
1671     if (attr == FILE_TYPE_DIRECTORY) {
1672         if (recursive) {
1673             /*
1674              * Avoid . and .. directories.
1675              */
1676             const char *p;
1677             p = strrchr(src, '/');
1678             if (!p)
1679                 p = strrchr(src, '\\');
1680             if (!p)
1681                 p = src;
1682             else
1683                 p++;
1684             if (!strcmp(p, ".") || !strcmp(p, ".."))
1685                 /* skip . and .. */ ;
1686             else
1687                 rsource(src);
1688         } else {
1689             run_err("%s: not a regular file", src);
1690         }
1691         return;
1692     }
1693
1694     if ((last = strrchr(src, '/')) == NULL)
1695         last = src;
1696     else
1697         last++;
1698     if (strrchr(last, '\\') != NULL)
1699         last = strrchr(last, '\\') + 1;
1700     if (last == src && strchr(src, ':') != NULL)
1701         last = strchr(src, ':') + 1;
1702
1703     f = open_existing_file(src, &size, &mtime, &atime, &permissions);
1704     if (f == NULL) {
1705         run_err("%s: Cannot open file", src);
1706         return;
1707     }
1708     if (preserve) {
1709         if (scp_send_filetimes(mtime, atime)) {
1710             close_rfile(f);
1711             return;
1712         }
1713     }
1714
1715     if (verbose) {
1716         char sizestr[40];
1717         uint64_decimal(size, sizestr);
1718         tell_user(stderr, "Sending file %s, size=%s", last, sizestr);
1719     }
1720     if (scp_send_filename(last, size, permissions)) {
1721         close_rfile(f);
1722         return;
1723     }
1724
1725     stat_bytes = uint64_make(0,0);
1726     stat_starttime = time(NULL);
1727     stat_lasttime = 0;
1728
1729 #define PSCP_SEND_BLOCK 4096
1730     for (i = uint64_make(0,0);
1731          uint64_compare(i,size) < 0;
1732          i = uint64_add32(i,PSCP_SEND_BLOCK)) {
1733         char transbuf[PSCP_SEND_BLOCK];
1734         int j, k = PSCP_SEND_BLOCK;
1735
1736         if (uint64_compare(uint64_add32(i, k),size) > 0) /* i + k > size */ 
1737             k = (uint64_subtract(size, i)).lo;  /* k = size - i; */
1738         if ((j = read_from_file(f, transbuf, k)) != k) {
1739             if (statistics)
1740                 printf("\n");
1741             bump("%s: Read error", src);
1742         }
1743         if (scp_send_filedata(transbuf, k))
1744             bump("%s: Network error occurred", src);
1745
1746         if (statistics) {
1747             stat_bytes = uint64_add32(stat_bytes, k);
1748             if (time(NULL) != stat_lasttime ||
1749                 (uint64_compare(uint64_add32(i, k), size) == 0)) {
1750                 stat_lasttime = time(NULL);
1751                 print_stats(last, size, stat_bytes,
1752                             stat_starttime, stat_lasttime);
1753             }
1754         }
1755
1756     }
1757     close_rfile(f);
1758
1759     (void) scp_send_finish();
1760 }
1761
1762 /*
1763  *  Recursively send the contents of a directory.
1764  */
1765 static void rsource(const char *src)
1766 {
1767     const char *last;
1768     char *save_target;
1769     DirHandle *dir;
1770
1771     if ((last = strrchr(src, '/')) == NULL)
1772         last = src;
1773     else
1774         last++;
1775     if (strrchr(last, '\\') != NULL)
1776         last = strrchr(last, '\\') + 1;
1777     if (last == src && strchr(src, ':') != NULL)
1778         last = strchr(src, ':') + 1;
1779
1780     /* maybe send filetime */
1781
1782     save_target = scp_save_remotepath();
1783
1784     if (verbose)
1785         tell_user(stderr, "Entering directory: %s", last);
1786     if (scp_send_dirname(last, 0755))
1787         return;
1788
1789     dir = open_directory(src);
1790     if (dir != NULL) {
1791         char *filename;
1792         while ((filename = read_filename(dir)) != NULL) {
1793             char *foundfile = dupcat(src, "/", filename, NULL);
1794             source(foundfile);
1795             sfree(foundfile);
1796             sfree(filename);
1797         }
1798     }
1799     close_directory(dir);
1800
1801     (void) scp_send_enddir();
1802
1803     scp_restore_remotepath(save_target);
1804 }
1805
1806 /*
1807  * Execute the sink part of the SCP protocol.
1808  */
1809 static void sink(const char *targ, const char *src)
1810 {
1811     char *destfname;
1812     int targisdir = 0;
1813     int exists;
1814     int attr;
1815     WFile *f;
1816     uint64 received;
1817     int wrerror = 0;
1818     uint64 stat_bytes;
1819     time_t stat_starttime, stat_lasttime;
1820     char *stat_name;
1821
1822     attr = file_type(targ);
1823     if (attr == FILE_TYPE_DIRECTORY)
1824         targisdir = 1;
1825
1826     if (targetshouldbedirectory && !targisdir)
1827         bump("%s: Not a directory", targ);
1828
1829     scp_sink_init();
1830     while (1) {
1831         struct scp_sink_action act;
1832         if (scp_get_sink_action(&act))
1833             return;
1834
1835         if (act.action == SCP_SINK_ENDDIR)
1836             return;
1837
1838         if (act.action == SCP_SINK_RETRY)
1839             continue;
1840
1841         if (targisdir) {
1842             /*
1843              * Prevent the remote side from maliciously writing to
1844              * files outside the target area by sending a filename
1845              * containing `../'. In fact, it shouldn't be sending
1846              * filenames with any slashes or colons in at all; so
1847              * we'll find the last slash, backslash or colon in the
1848              * filename and use only the part after that. (And
1849              * warn!)
1850              * 
1851              * In addition, we also ensure here that if we're
1852              * copying a single file and the target is a directory
1853              * (common usage: `pscp host:filename .') the remote
1854              * can't send us a _different_ file name. We can
1855              * distinguish this case because `src' will be non-NULL
1856              * and the last component of that will fail to match
1857              * (the last component of) the name sent.
1858              * 
1859              * Well, not always; if `src' is a wildcard, we do
1860              * expect to get back filenames that don't correspond
1861              * exactly to it. Ideally in this case, we would like
1862              * to ensure that the returned filename actually
1863              * matches the wildcard pattern - but one of SCP's
1864              * protocol infelicities is that wildcard matching is
1865              * done at the server end _by the server's rules_ and
1866              * so in general this is infeasible. Hence, we only
1867              * accept filenames that don't correspond to `src' if
1868              * unsafe mode is enabled or we are using SFTP (which
1869              * resolves remote wildcards on the client side and can
1870              * be trusted).
1871              */
1872             char *striptarget, *stripsrc;
1873
1874             striptarget = stripslashes(act.name, 1);
1875             if (striptarget != act.name) {
1876                 tell_user(stderr, "warning: remote host sent a compound"
1877                           " pathname '%s'", act.name);
1878                 tell_user(stderr, "         renaming local file to '%s'",
1879                           striptarget);
1880             }
1881
1882             /*
1883              * Also check to see if the target filename is '.' or
1884              * '..', or indeed '...' and so on because Windows
1885              * appears to interpret those like '..'.
1886              */
1887             if (is_dots(striptarget)) {
1888                 bump("security violation: remote host attempted to write to"
1889                      " a '.' or '..' path!");
1890             }
1891
1892             if (src) {
1893                 stripsrc = stripslashes(src, 1);
1894                 if (strcmp(striptarget, stripsrc) &&
1895                     !using_sftp && !scp_unsafe_mode) {
1896                     tell_user(stderr, "warning: remote host tried to write "
1897                               "to a file called '%s'", striptarget);
1898                     tell_user(stderr, "         when we requested a file "
1899                               "called '%s'.", stripsrc);
1900                     tell_user(stderr, "         If this is a wildcard, "
1901                               "consider upgrading to SSH-2 or using");
1902                     tell_user(stderr, "         the '-unsafe' option. Renaming"
1903                               " of this file has been disallowed.");
1904                     /* Override the name the server provided with our own. */
1905                     striptarget = stripsrc;
1906                 }
1907             }
1908
1909             if (targ[0] != '\0')
1910                 destfname = dir_file_cat(targ, striptarget);
1911             else
1912                 destfname = dupstr(striptarget);
1913         } else {
1914             /*
1915              * In this branch of the if, the target area is a
1916              * single file with an explicitly specified name in any
1917              * case, so there's no danger.
1918              */
1919             destfname = dupstr(targ);
1920         }
1921         attr = file_type(destfname);
1922         exists = (attr != FILE_TYPE_NONEXISTENT);
1923
1924         if (act.action == SCP_SINK_DIR) {
1925             if (exists && attr != FILE_TYPE_DIRECTORY) {
1926                 run_err("%s: Not a directory", destfname);
1927                 sfree(destfname);
1928                 continue;
1929             }
1930             if (!exists) {
1931                 if (!create_directory(destfname)) {
1932                     run_err("%s: Cannot create directory", destfname);
1933                     sfree(destfname);
1934                     continue;
1935                 }
1936             }
1937             sink(destfname, NULL);
1938             /* can we set the timestamp for directories ? */
1939             sfree(destfname);
1940             continue;
1941         }
1942
1943         f = open_new_file(destfname, act.permissions);
1944         if (f == NULL) {
1945             run_err("%s: Cannot create file", destfname);
1946             sfree(destfname);
1947             continue;
1948         }
1949
1950         if (scp_accept_filexfer()) {
1951             sfree(destfname);
1952             close_wfile(f);
1953             return;
1954         }
1955
1956         stat_bytes = uint64_make(0, 0);
1957         stat_starttime = time(NULL);
1958         stat_lasttime = 0;
1959         stat_name = stripslashes(destfname, 1);
1960
1961         received = uint64_make(0, 0);
1962         while (uint64_compare(received,act.size) < 0) {
1963             char transbuf[32768];
1964             uint64 blksize;
1965             int read;
1966             blksize = uint64_make(0, 32768);
1967             if (uint64_compare(blksize,uint64_subtract(act.size,received)) > 0)
1968               blksize = uint64_subtract(act.size,received);
1969             read = scp_recv_filedata(transbuf, (int)blksize.lo);
1970             if (read <= 0)
1971                 bump("Lost connection");
1972             if (wrerror) {
1973                 received = uint64_add32(received, read);
1974                 continue;
1975             }
1976             if (write_to_file(f, transbuf, read) != (int)read) {
1977                 wrerror = 1;
1978                 /* FIXME: in sftp we can actually abort the transfer */
1979                 if (statistics)
1980                     printf("\r%-25.25s | %50s\n",
1981                            stat_name,
1982                            "Write error.. waiting for end of file");
1983                 received = uint64_add32(received, read);
1984                 continue;
1985             }
1986             if (statistics) {
1987                 stat_bytes = uint64_add32(stat_bytes,read);
1988                 if (time(NULL) > stat_lasttime ||
1989                     uint64_compare(uint64_add32(received, read), act.size) == 0) {
1990                     stat_lasttime = time(NULL);
1991                     print_stats(stat_name, act.size, stat_bytes,
1992                                 stat_starttime, stat_lasttime);
1993                 }
1994             }
1995             received = uint64_add32(received, read);
1996         }
1997         if (act.settime) {
1998             set_file_times(f, act.mtime, act.atime);
1999         }
2000
2001         close_wfile(f);
2002         if (wrerror) {
2003             run_err("%s: Write error", destfname);
2004             sfree(destfname);
2005             continue;
2006         }
2007         (void) scp_finish_filerecv();
2008         sfree(destfname);
2009         sfree(act.buf);
2010     }
2011 }
2012
2013 /*
2014  * We will copy local files to a remote server.
2015  */
2016 static void toremote(int argc, char *argv[])
2017 {
2018     char *src, *wtarg, *host, *user;
2019     const char *targ;
2020     char *cmd;
2021     int i, wc_type;
2022
2023     uploading = 1;
2024
2025     wtarg = argv[argc - 1];
2026
2027     /* Separate host from filename */
2028     host = wtarg;
2029     wtarg = colon(wtarg);
2030     if (wtarg == NULL)
2031         bump("wtarg == NULL in toremote()");
2032     *wtarg++ = '\0';
2033     /* Substitute "." for empty target */
2034     if (*wtarg == '\0')
2035         targ = ".";
2036     else
2037         targ = wtarg;
2038
2039     /* Separate host and username */
2040     user = host;
2041     host = strrchr(host, '@');
2042     if (host == NULL) {
2043         host = user;
2044         user = NULL;
2045     } else {
2046         *host++ = '\0';
2047         if (*user == '\0')
2048             user = NULL;
2049     }
2050
2051     if (argc == 2) {
2052         if (colon(argv[0]) != NULL)
2053             bump("%s: Remote to remote not supported", argv[0]);
2054
2055         wc_type = test_wildcard(argv[0], 1);
2056         if (wc_type == WCTYPE_NONEXISTENT)
2057             bump("%s: No such file or directory\n", argv[0]);
2058         else if (wc_type == WCTYPE_WILDCARD)
2059             targetshouldbedirectory = 1;
2060     }
2061
2062     cmd = dupprintf("scp%s%s%s%s -t %s",
2063                     verbose ? " -v" : "",
2064                     recursive ? " -r" : "",
2065                     preserve ? " -p" : "",
2066                     targetshouldbedirectory ? " -d" : "", targ);
2067     do_cmd(host, user, cmd);
2068     sfree(cmd);
2069
2070     if (scp_source_setup(targ, targetshouldbedirectory))
2071         return;
2072
2073     for (i = 0; i < argc - 1; i++) {
2074         src = argv[i];
2075         if (colon(src) != NULL) {
2076             tell_user(stderr, "%s: Remote to remote not supported\n", src);
2077             errs++;
2078             continue;
2079         }
2080
2081         wc_type = test_wildcard(src, 1);
2082         if (wc_type == WCTYPE_NONEXISTENT) {
2083             run_err("%s: No such file or directory", src);
2084             continue;
2085         } else if (wc_type == WCTYPE_FILENAME) {
2086             source(src);
2087             continue;
2088         } else {
2089             WildcardMatcher *wc;
2090             char *filename;
2091
2092             wc = begin_wildcard_matching(src);
2093             if (wc == NULL) {
2094                 run_err("%s: No such file or directory", src);
2095                 continue;
2096             }
2097
2098             while ((filename = wildcard_get_filename(wc)) != NULL) {
2099                 source(filename);
2100                 sfree(filename);
2101             }
2102
2103             finish_wildcard_matching(wc);
2104         }
2105     }
2106 }
2107
2108 /*
2109  *  We will copy files from a remote server to the local machine.
2110  */
2111 static void tolocal(int argc, char *argv[])
2112 {
2113     char *wsrc, *host, *user;
2114     const char *src, *targ;
2115     char *cmd;
2116
2117     uploading = 0;
2118
2119     if (argc != 2)
2120         bump("More than one remote source not supported");
2121
2122     wsrc = argv[0];
2123     targ = argv[1];
2124
2125     /* Separate host from filename */
2126     host = wsrc;
2127     wsrc = colon(wsrc);
2128     if (wsrc == NULL)
2129         bump("Local to local copy not supported");
2130     *wsrc++ = '\0';
2131     /* Substitute "." for empty filename */
2132     if (*wsrc == '\0')
2133         src = ".";
2134     else
2135         src = wsrc;
2136
2137     /* Separate username and hostname */
2138     user = host;
2139     host = strrchr(host, '@');
2140     if (host == NULL) {
2141         host = user;
2142         user = NULL;
2143     } else {
2144         *host++ = '\0';
2145         if (*user == '\0')
2146             user = NULL;
2147     }
2148
2149     cmd = dupprintf("scp%s%s%s%s -f %s",
2150                     verbose ? " -v" : "",
2151                     recursive ? " -r" : "",
2152                     preserve ? " -p" : "",
2153                     targetshouldbedirectory ? " -d" : "", src);
2154     do_cmd(host, user, cmd);
2155     sfree(cmd);
2156
2157     if (scp_sink_setup(src, preserve, recursive))
2158         return;
2159
2160     sink(targ, src);
2161 }
2162
2163 /*
2164  *  We will issue a list command to get a remote directory.
2165  */
2166 static void get_dir_list(int argc, char *argv[])
2167 {
2168     char *wsrc, *host, *user;
2169     const char *src;
2170     char *cmd, *p;
2171     const char *q;
2172     char c;
2173
2174     wsrc = argv[0];
2175
2176     /* Separate host from filename */
2177     host = wsrc;
2178     wsrc = colon(wsrc);
2179     if (wsrc == NULL)
2180         bump("Local file listing not supported");
2181     *wsrc++ = '\0';
2182     /* Substitute "." for empty filename */
2183     if (*wsrc == '\0')
2184         src = ".";
2185     else
2186         src = wsrc;
2187
2188     /* Separate username and hostname */
2189     user = host;
2190     host = strrchr(host, '@');
2191     if (host == NULL) {
2192         host = user;
2193         user = NULL;
2194     } else {
2195         *host++ = '\0';
2196         if (*user == '\0')
2197             user = NULL;
2198     }
2199
2200     cmd = snewn(4 * strlen(src) + 100, char);
2201     strcpy(cmd, "ls -la '");
2202     p = cmd + strlen(cmd);
2203     for (q = src; *q; q++) {
2204         if (*q == '\'') {
2205             *p++ = '\'';
2206             *p++ = '\\';
2207             *p++ = '\'';
2208             *p++ = '\'';
2209         } else {
2210             *p++ = *q;
2211         }
2212     }
2213     *p++ = '\'';
2214     *p = '\0';
2215
2216     do_cmd(host, user, cmd);
2217     sfree(cmd);
2218
2219     if (using_sftp) {
2220         scp_sftp_listdir(src);
2221     } else {
2222         while (ssh_scp_recv((unsigned char *) &c, 1) > 0)
2223             tell_char(stdout, c);
2224     }
2225 }
2226
2227 /*
2228  *  Short description of parameters.
2229  */
2230 static void usage(void)
2231 {
2232     printf("PuTTY Secure Copy client\n");
2233     printf("%s\n", ver);
2234     printf("Usage: pscp [options] [user@]host:source target\n");
2235     printf
2236         ("       pscp [options] source [source...] [user@]host:target\n");
2237     printf("       pscp [options] -ls [user@]host:filespec\n");
2238     printf("Options:\n");
2239     printf("  -V        print version information and exit\n");
2240     printf("  -pgpfp    print PGP key fingerprints and exit\n");
2241     printf("  -p        preserve file attributes\n");
2242     printf("  -q        quiet, don't show statistics\n");
2243     printf("  -r        copy directories recursively\n");
2244     printf("  -v        show verbose messages\n");
2245     printf("  -load sessname  Load settings from saved session\n");
2246     printf("  -P port   connect to specified port\n");
2247     printf("  -l user   connect with specified username\n");
2248     printf("  -pw passw login with specified password\n");
2249     printf("  -1 -2     force use of particular SSH protocol version\n");
2250     printf("  -4 -6     force use of IPv4 or IPv6\n");
2251     printf("  -C        enable compression\n");
2252     printf("  -i key    private key file for user authentication\n");
2253     printf("  -noagent  disable use of Pageant\n");
2254     printf("  -agent    enable use of Pageant\n");
2255     printf("  -hostkey aa:bb:cc:...\n");
2256     printf("            manually specify a host key (may be repeated)\n");
2257     printf("  -batch    disable all interactive prompts\n");
2258     printf("  -proxycmd command\n");
2259     printf("            use 'command' as local proxy\n");
2260     printf("  -unsafe   allow server-side wildcards (DANGEROUS)\n");
2261     printf("  -sftp     force use of SFTP protocol\n");
2262     printf("  -scp      force use of SCP protocol\n");
2263     printf("  -sshlog file\n");
2264     printf("  -sshrawlog file\n");
2265     printf("            log protocol details to a file\n");
2266 #if 0
2267     /*
2268      * -gui is an internal option, used by GUI front ends to get
2269      * pscp to pass progress reports back to them. It's not an
2270      * ordinary user-accessible option, so it shouldn't be part of
2271      * the command-line help. The only people who need to know
2272      * about it are programmers, and they can read the source.
2273      */
2274     printf
2275         ("  -gui hWnd GUI mode with the windows handle for receiving messages\n");
2276 #endif
2277     cleanup_exit(1);
2278 }
2279
2280 void version(void)
2281 {
2282     char *buildinfo_text = buildinfo("\n");
2283     printf("pscp: %s\n%s\n", ver, buildinfo_text);
2284     sfree(buildinfo_text);
2285     exit(0);
2286 }
2287
2288 void cmdline_error(const char *p, ...)
2289 {
2290     va_list ap;
2291     fprintf(stderr, "pscp: ");
2292     va_start(ap, p);
2293     vfprintf(stderr, p, ap);
2294     va_end(ap);
2295     fprintf(stderr, "\n      try typing just \"pscp\" for help\n");
2296     exit(1);
2297 }
2298
2299 const int share_can_be_downstream = TRUE;
2300 const int share_can_be_upstream = FALSE;
2301
2302 /*
2303  * Main program. (Called `psftp_main' because it gets called from
2304  * *sftp.c; bit silly, I know, but it had to be called _something_.)
2305  */
2306 int psftp_main(int argc, char *argv[])
2307 {
2308     int i;
2309
2310     default_protocol = PROT_TELNET;
2311
2312     flags = FLAG_STDERR
2313 #ifdef FLAG_SYNCAGENT
2314         | FLAG_SYNCAGENT
2315 #endif
2316         ;
2317     cmdline_tooltype = TOOLTYPE_FILETRANSFER;
2318     sk_init();
2319
2320     /* Load Default Settings before doing anything else. */
2321     conf = conf_new();
2322     do_defaults(NULL, conf);
2323     loaded_session = FALSE;
2324
2325     for (i = 1; i < argc; i++) {
2326         int ret;
2327         if (argv[i][0] != '-')
2328             break;
2329         ret = cmdline_process_param(argv[i], i+1<argc?argv[i+1]:NULL, 1, conf);
2330         if (ret == -2) {
2331             cmdline_error("option \"%s\" requires an argument", argv[i]);
2332         } else if (ret == 2) {
2333             i++;               /* skip next argument */
2334         } else if (ret == 1) {
2335             /* We have our own verbosity in addition to `flags'. */
2336             if (flags & FLAG_VERBOSE)
2337                 verbose = 1;
2338         } else if (strcmp(argv[i], "-pgpfp") == 0) {
2339             pgp_fingerprints();
2340             return 1;
2341         } else if (strcmp(argv[i], "-r") == 0) {
2342             recursive = 1;
2343         } else if (strcmp(argv[i], "-p") == 0) {
2344             preserve = 1;
2345         } else if (strcmp(argv[i], "-q") == 0) {
2346             statistics = 0;
2347         } else if (strcmp(argv[i], "-h") == 0 ||
2348                    strcmp(argv[i], "-?") == 0 ||
2349                    strcmp(argv[i], "--help") == 0) {
2350             usage();
2351         } else if (strcmp(argv[i], "-V") == 0 ||
2352                    strcmp(argv[i], "--version") == 0) {
2353             version();
2354         } else if (strcmp(argv[i], "-ls") == 0) {
2355             list = 1;
2356         } else if (strcmp(argv[i], "-batch") == 0) {
2357             console_batch_mode = 1;
2358         } else if (strcmp(argv[i], "-unsafe") == 0) {
2359             scp_unsafe_mode = 1;
2360         } else if (strcmp(argv[i], "-sftp") == 0) {
2361             try_scp = 0; try_sftp = 1;
2362         } else if (strcmp(argv[i], "-scp") == 0) {
2363             try_scp = 1; try_sftp = 0;
2364         } else if (strcmp(argv[i], "--") == 0) {
2365             i++;
2366             break;
2367         } else {
2368             cmdline_error("unknown option \"%s\"", argv[i]);
2369         }
2370     }
2371     argc -= i;
2372     argv += i;
2373     back = NULL;
2374
2375     if (list) {
2376         if (argc != 1)
2377             usage();
2378         get_dir_list(argc, argv);
2379
2380     } else {
2381
2382         if (argc < 2)
2383             usage();
2384         if (argc > 2)
2385             targetshouldbedirectory = 1;
2386
2387         if (colon(argv[argc - 1]) != NULL)
2388             toremote(argc, argv);
2389         else
2390             tolocal(argc, argv);
2391     }
2392
2393     if (back != NULL && back->connected(backhandle)) {
2394         char ch;
2395         back->special(backhandle, TS_EOF);
2396         sent_eof = TRUE;
2397         ssh_scp_recv((unsigned char *) &ch, 1);
2398     }
2399     random_save_seed();
2400
2401     cmdline_cleanup();
2402     console_provide_logctx(NULL);
2403     back->free(backhandle);
2404     backhandle = NULL;
2405     back = NULL;
2406     sk_cleanup();
2407     return (errs == 0 ? 0 : 1);
2408 }
2409
2410 /* end */