]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - pscp.c
wintime: add a precautionary memset to zero.
[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         printf("Unable to open %s: %s\n", dirname, fxp_error());
703     } else {
704         nnames = namesize = 0;
705         ournames = NULL;
706
707         while (1) {
708
709             req = fxp_readdir_send(dirh);
710             pktin = sftp_wait_for_reply(req);
711             names = fxp_readdir_recv(pktin, req);
712
713             if (names == NULL) {
714                 if (fxp_error_type() == SSH_FX_EOF)
715                     break;
716                 printf("Reading directory %s: %s\n", dirname, fxp_error());
717                 break;
718             }
719             if (names->nnames == 0) {
720                 fxp_free_names(names);
721                 break;
722             }
723
724             if (nnames + names->nnames >= namesize) {
725                 namesize += names->nnames + 128;
726                 ournames = sresize(ournames, namesize, struct fxp_name);
727             }
728
729             for (i = 0; i < names->nnames; i++)
730                 ournames[nnames++] = names->names[i];
731             names->nnames = 0;         /* prevent free_names */
732             fxp_free_names(names);
733         }
734         req = fxp_close_send(dirh);
735         pktin = sftp_wait_for_reply(req);
736         fxp_close_recv(pktin, req);
737
738         /*
739          * Now we have our filenames. Sort them by actual file
740          * name, and then output the longname parts.
741          */
742         if (nnames > 0)
743             qsort(ournames, nnames, sizeof(*ournames), sftp_ls_compare);
744
745         /*
746          * And print them.
747          */
748         for (i = 0; i < nnames; i++)
749             printf("%s\n", ournames[i].longname);
750
751         sfree(ournames);
752     }
753 }
754
755 /* ----------------------------------------------------------------------
756  * Helper routines that contain the actual SCP protocol elements,
757  * implemented both as SCP1 and SFTP.
758  */
759
760 static struct scp_sftp_dirstack {
761     struct scp_sftp_dirstack *next;
762     struct fxp_name *names;
763     int namepos, namelen;
764     char *dirpath;
765     char *wildcard;
766     int matched_something;             /* wildcard match set was non-empty */
767 } *scp_sftp_dirstack_head;
768 static char *scp_sftp_remotepath, *scp_sftp_currentname;
769 static char *scp_sftp_wildcard;
770 static int scp_sftp_targetisdir, scp_sftp_donethistarget;
771 static int scp_sftp_preserve, scp_sftp_recursive;
772 static unsigned long scp_sftp_mtime, scp_sftp_atime;
773 static int scp_has_times;
774 static struct fxp_handle *scp_sftp_filehandle;
775 static struct fxp_xfer *scp_sftp_xfer;
776 static uint64 scp_sftp_fileoffset;
777
778 int scp_source_setup(const char *target, int shouldbedir)
779 {
780     if (using_sftp) {
781         /*
782          * Find out whether the target filespec is in fact a
783          * directory.
784          */
785         struct sftp_packet *pktin;
786         struct sftp_request *req;
787         struct fxp_attrs attrs;
788         int ret;
789
790         if (!fxp_init()) {
791             tell_user(stderr, "unable to initialise SFTP: %s", fxp_error());
792             errs++;
793             return 1;
794         }
795
796         req = fxp_stat_send(target);
797         pktin = sftp_wait_for_reply(req);
798         ret = fxp_stat_recv(pktin, req, &attrs);
799
800         if (!ret || !(attrs.flags & SSH_FILEXFER_ATTR_PERMISSIONS))
801             scp_sftp_targetisdir = 0;
802         else
803             scp_sftp_targetisdir = (attrs.permissions & 0040000) != 0;
804
805         if (shouldbedir && !scp_sftp_targetisdir) {
806             bump("pscp: remote filespec %s: not a directory\n", target);
807         }
808
809         scp_sftp_remotepath = dupstr(target);
810
811         scp_has_times = 0;
812     } else {
813         (void) response();
814     }
815     return 0;
816 }
817
818 int scp_send_errmsg(char *str)
819 {
820     if (using_sftp) {
821         /* do nothing; we never need to send our errors to the server */
822     } else {
823         back->send(backhandle, "\001", 1);/* scp protocol error prefix */
824         back->send(backhandle, str, strlen(str));
825     }
826     return 0;                          /* can't fail */
827 }
828
829 int scp_send_filetimes(unsigned long mtime, unsigned long atime)
830 {
831     if (using_sftp) {
832         scp_sftp_mtime = mtime;
833         scp_sftp_atime = atime;
834         scp_has_times = 1;
835         return 0;
836     } else {
837         char buf[80];
838         sprintf(buf, "T%lu 0 %lu 0\n", mtime, atime);
839         back->send(backhandle, buf, strlen(buf));
840         return response();
841     }
842 }
843
844 int scp_send_filename(const char *name, uint64 size, int permissions)
845 {
846     if (using_sftp) {
847         char *fullname;
848         struct sftp_packet *pktin;
849         struct sftp_request *req;
850         struct fxp_attrs attrs;
851
852         if (scp_sftp_targetisdir) {
853             fullname = dupcat(scp_sftp_remotepath, "/", name, NULL);
854         } else {
855             fullname = dupstr(scp_sftp_remotepath);
856         }
857
858         attrs.flags = 0;
859         PUT_PERMISSIONS(attrs, permissions);
860
861         req = fxp_open_send(fullname,
862                             SSH_FXF_WRITE | SSH_FXF_CREAT | SSH_FXF_TRUNC,
863                             &attrs);
864         pktin = sftp_wait_for_reply(req);
865         scp_sftp_filehandle = fxp_open_recv(pktin, req);
866
867         if (!scp_sftp_filehandle) {
868             tell_user(stderr, "pscp: unable to open %s: %s",
869                       fullname, fxp_error());
870             sfree(fullname);
871             errs++;
872             return 1;
873         }
874         scp_sftp_fileoffset = uint64_make(0, 0);
875         scp_sftp_xfer = xfer_upload_init(scp_sftp_filehandle,
876                                          scp_sftp_fileoffset);
877         sfree(fullname);
878         return 0;
879     } else {
880         char buf[40];
881         char sizestr[40];
882         uint64_decimal(size, sizestr);
883         if (permissions < 0)
884             permissions = 0644;
885         sprintf(buf, "C%04o %s ", (int)(permissions & 07777), sizestr);
886         back->send(backhandle, buf, strlen(buf));
887         back->send(backhandle, name, strlen(name));
888         back->send(backhandle, "\n", 1);
889         return response();
890     }
891 }
892
893 int scp_send_filedata(char *data, int len)
894 {
895     if (using_sftp) {
896         int ret;
897         struct sftp_packet *pktin;
898
899         if (!scp_sftp_filehandle) {
900             return 1;
901         }
902
903         while (!xfer_upload_ready(scp_sftp_xfer)) {
904             pktin = sftp_recv();
905             ret = xfer_upload_gotpkt(scp_sftp_xfer, pktin);
906             if (ret <= 0) {
907                 tell_user(stderr, "error while writing: %s", fxp_error());
908                 if (ret == INT_MIN)        /* pktin not even freed */
909                     sfree(pktin);
910                 errs++;
911                 return 1;
912             }
913         }
914
915         xfer_upload_data(scp_sftp_xfer, data, len);
916
917         scp_sftp_fileoffset = uint64_add32(scp_sftp_fileoffset, len);
918         return 0;
919     } else {
920         int bufsize = back->send(backhandle, data, len);
921
922         /*
923          * If the network transfer is backing up - that is, the
924          * remote site is not accepting data as fast as we can
925          * produce it - then we must loop on network events until
926          * we have space in the buffer again.
927          */
928         while (bufsize > MAX_SCP_BUFSIZE) {
929             if (ssh_sftp_loop_iteration() < 0)
930                 return 1;
931             bufsize = back->sendbuffer(backhandle);
932         }
933
934         return 0;
935     }
936 }
937
938 int scp_send_finish(void)
939 {
940     if (using_sftp) {
941         struct fxp_attrs attrs;
942         struct sftp_packet *pktin;
943         struct sftp_request *req;
944         int ret;
945
946         while (!xfer_done(scp_sftp_xfer)) {
947             pktin = sftp_recv();
948             ret = xfer_upload_gotpkt(scp_sftp_xfer, pktin);
949             if (ret <= 0) {
950                 tell_user(stderr, "error while writing: %s", fxp_error());
951                 if (ret == INT_MIN)        /* pktin not even freed */
952                     sfree(pktin);
953                 errs++;
954                 return 1;
955             }
956         }
957         xfer_cleanup(scp_sftp_xfer);
958
959         if (!scp_sftp_filehandle) {
960             return 1;
961         }
962         if (scp_has_times) {
963             attrs.flags = SSH_FILEXFER_ATTR_ACMODTIME;
964             attrs.atime = scp_sftp_atime;
965             attrs.mtime = scp_sftp_mtime;
966             req = fxp_fsetstat_send(scp_sftp_filehandle, attrs);
967             pktin = sftp_wait_for_reply(req);
968             ret = fxp_fsetstat_recv(pktin, req);
969             if (!ret) {
970                 tell_user(stderr, "unable to set file times: %s", fxp_error());
971                 errs++;
972             }
973         }
974         req = fxp_close_send(scp_sftp_filehandle);
975         pktin = sftp_wait_for_reply(req);
976         fxp_close_recv(pktin, req);
977         scp_has_times = 0;
978         return 0;
979     } else {
980         back->send(backhandle, "", 1);
981         return response();
982     }
983 }
984
985 char *scp_save_remotepath(void)
986 {
987     if (using_sftp)
988         return scp_sftp_remotepath;
989     else
990         return NULL;
991 }
992
993 void scp_restore_remotepath(char *data)
994 {
995     if (using_sftp)
996         scp_sftp_remotepath = data;
997 }
998
999 int scp_send_dirname(const char *name, int modes)
1000 {
1001     if (using_sftp) {
1002         char *fullname;
1003         char const *err;
1004         struct fxp_attrs attrs;
1005         struct sftp_packet *pktin;
1006         struct sftp_request *req;
1007         int ret;
1008
1009         if (scp_sftp_targetisdir) {
1010             fullname = dupcat(scp_sftp_remotepath, "/", name, NULL);
1011         } else {
1012             fullname = dupstr(scp_sftp_remotepath);
1013         }
1014
1015         /*
1016          * We don't worry about whether we managed to create the
1017          * directory, because if it exists already it's OK just to
1018          * use it. Instead, we will stat it afterwards, and if it
1019          * exists and is a directory we will assume we were either
1020          * successful or it didn't matter.
1021          */
1022         req = fxp_mkdir_send(fullname);
1023         pktin = sftp_wait_for_reply(req);
1024         ret = fxp_mkdir_recv(pktin, req);
1025
1026         if (!ret)
1027             err = fxp_error();
1028         else
1029             err = "server reported no error";
1030
1031         req = fxp_stat_send(fullname);
1032         pktin = sftp_wait_for_reply(req);
1033         ret = fxp_stat_recv(pktin, req, &attrs);
1034
1035         if (!ret || !(attrs.flags & SSH_FILEXFER_ATTR_PERMISSIONS) ||
1036             !(attrs.permissions & 0040000)) {
1037             tell_user(stderr, "unable to create directory %s: %s",
1038                       fullname, err);
1039             sfree(fullname);
1040             errs++;
1041             return 1;
1042         }
1043
1044         scp_sftp_remotepath = fullname;
1045
1046         return 0;
1047     } else {
1048         char buf[40];
1049         sprintf(buf, "D%04o 0 ", modes);
1050         back->send(backhandle, buf, strlen(buf));
1051         back->send(backhandle, name, strlen(name));
1052         back->send(backhandle, "\n", 1);
1053         return response();
1054     }
1055 }
1056
1057 int scp_send_enddir(void)
1058 {
1059     if (using_sftp) {
1060         sfree(scp_sftp_remotepath);
1061         return 0;
1062     } else {
1063         back->send(backhandle, "E\n", 2);
1064         return response();
1065     }
1066 }
1067
1068 /*
1069  * Yes, I know; I have an scp_sink_setup _and_ an scp_sink_init.
1070  * That's bad. The difference is that scp_sink_setup is called once
1071  * right at the start, whereas scp_sink_init is called to
1072  * initialise every level of recursion in the protocol.
1073  */
1074 int scp_sink_setup(const char *source, int preserve, int recursive)
1075 {
1076     if (using_sftp) {
1077         char *newsource;
1078
1079         if (!fxp_init()) {
1080             tell_user(stderr, "unable to initialise SFTP: %s", fxp_error());
1081             errs++;
1082             return 1;
1083         }
1084         /*
1085          * It's possible that the source string we've been given
1086          * contains a wildcard. If so, we must split the directory
1087          * away from the wildcard itself (throwing an error if any
1088          * wildcardness comes before the final slash) and arrange
1089          * things so that a dirstack entry will be set up.
1090          */
1091         newsource = snewn(1+strlen(source), char);
1092         if (!wc_unescape(newsource, source)) {
1093             /* Yes, here we go; it's a wildcard. Bah. */
1094             char *dupsource, *lastpart, *dirpart, *wildcard;
1095
1096             sfree(newsource);
1097
1098             dupsource = dupstr(source);
1099             lastpart = stripslashes(dupsource, 0);
1100             wildcard = dupstr(lastpart);
1101             *lastpart = '\0';
1102             if (*dupsource && dupsource[1]) {
1103                 /*
1104                  * The remains of dupsource are at least two
1105                  * characters long, meaning the pathname wasn't
1106                  * empty or just `/'. Hence, we remove the trailing
1107                  * slash.
1108                  */
1109                 lastpart[-1] = '\0';
1110             } else if (!*dupsource) {
1111                 /*
1112                  * The remains of dupsource are _empty_ - the whole
1113                  * pathname was a wildcard. Hence we need to
1114                  * replace it with ".".
1115                  */
1116                 sfree(dupsource);
1117                 dupsource = dupstr(".");
1118             }
1119
1120             /*
1121              * Now we have separated our string into dupsource (the
1122              * directory part) and wildcard. Both of these will
1123              * need freeing at some point. Next step is to remove
1124              * wildcard escapes from the directory part, throwing
1125              * an error if it contains a real wildcard.
1126              */
1127             dirpart = snewn(1+strlen(dupsource), char);
1128             if (!wc_unescape(dirpart, dupsource)) {
1129                 tell_user(stderr, "%s: multiple-level wildcards unsupported",
1130                           source);
1131                 errs++;
1132                 sfree(dirpart);
1133                 sfree(wildcard);
1134                 sfree(dupsource);
1135                 return 1;
1136             }
1137
1138             /*
1139              * Now we have dirpart (unescaped, ie a valid remote
1140              * path), and wildcard (a wildcard). This will be
1141              * sufficient to arrange a dirstack entry.
1142              */
1143             scp_sftp_remotepath = dirpart;
1144             scp_sftp_wildcard = wildcard;
1145             sfree(dupsource);
1146         } else {
1147             scp_sftp_remotepath = newsource;
1148             scp_sftp_wildcard = NULL;
1149         }
1150         scp_sftp_preserve = preserve;
1151         scp_sftp_recursive = recursive;
1152         scp_sftp_donethistarget = 0;
1153         scp_sftp_dirstack_head = NULL;
1154     }
1155     return 0;
1156 }
1157
1158 int scp_sink_init(void)
1159 {
1160     if (!using_sftp) {
1161         back->send(backhandle, "", 1);
1162     }
1163     return 0;
1164 }
1165
1166 #define SCP_SINK_FILE   1
1167 #define SCP_SINK_DIR    2
1168 #define SCP_SINK_ENDDIR 3
1169 #define SCP_SINK_RETRY  4              /* not an action; just try again */
1170 struct scp_sink_action {
1171     int action;                        /* FILE, DIR, ENDDIR */
1172     char *buf;                         /* will need freeing after use */
1173     char *name;                        /* filename or dirname (not ENDDIR) */
1174     long permissions;          /* access permissions (not ENDDIR) */
1175     uint64 size;                       /* file size (not ENDDIR) */
1176     int settime;                       /* 1 if atime and mtime are filled */
1177     unsigned long atime, mtime;        /* access times for the file */
1178 };
1179
1180 int scp_get_sink_action(struct scp_sink_action *act)
1181 {
1182     if (using_sftp) {
1183         char *fname;
1184         int must_free_fname;
1185         struct fxp_attrs attrs;
1186         struct sftp_packet *pktin;
1187         struct sftp_request *req;
1188         int ret;
1189
1190         if (!scp_sftp_dirstack_head) {
1191             if (!scp_sftp_donethistarget) {
1192                 /*
1193                  * Simple case: we are only dealing with one file.
1194                  */
1195                 fname = scp_sftp_remotepath;
1196                 must_free_fname = 0;
1197                 scp_sftp_donethistarget = 1;
1198             } else {
1199                 /*
1200                  * Even simpler case: one file _which we've done_.
1201                  * Return 1 (finished).
1202                  */
1203                 return 1;
1204             }
1205         } else {
1206             /*
1207              * We're now in the middle of stepping through a list
1208              * of names returned from fxp_readdir(); so let's carry
1209              * on.
1210              */
1211             struct scp_sftp_dirstack *head = scp_sftp_dirstack_head;
1212             while (head->namepos < head->namelen &&
1213                    (is_dots(head->names[head->namepos].filename) ||
1214                     (head->wildcard &&
1215                      !wc_match(head->wildcard,
1216                                head->names[head->namepos].filename))))
1217                 head->namepos++;       /* skip . and .. */
1218             if (head->namepos < head->namelen) {
1219                 head->matched_something = 1;
1220                 fname = dupcat(head->dirpath, "/",
1221                                head->names[head->namepos++].filename,
1222                                NULL);
1223                 must_free_fname = 1;
1224             } else {
1225                 /*
1226                  * We've come to the end of the list; pop it off
1227                  * the stack and return an ENDDIR action (or RETRY
1228                  * if this was a wildcard match).
1229                  */
1230                 if (head->wildcard) {
1231                     act->action = SCP_SINK_RETRY;
1232                     if (!head->matched_something) {
1233                         tell_user(stderr, "pscp: wildcard '%s' matched "
1234                                   "no files", head->wildcard);
1235                         errs++;
1236                     }
1237                     sfree(head->wildcard);
1238
1239                 } else {
1240                     act->action = SCP_SINK_ENDDIR;
1241                 }
1242
1243                 sfree(head->dirpath);
1244                 sfree(head->names);
1245                 scp_sftp_dirstack_head = head->next;
1246                 sfree(head);
1247
1248                 return 0;
1249             }
1250         }
1251
1252         /*
1253          * Now we have a filename. Stat it, and see if it's a file
1254          * or a directory.
1255          */
1256         req = fxp_stat_send(fname);
1257         pktin = sftp_wait_for_reply(req);
1258         ret = fxp_stat_recv(pktin, req, &attrs);
1259
1260         if (!ret || !(attrs.flags & SSH_FILEXFER_ATTR_PERMISSIONS)) {
1261             tell_user(stderr, "unable to identify %s: %s", fname,
1262                       ret ? "file type not supplied" : fxp_error());
1263             if (must_free_fname) sfree(fname);
1264             errs++;
1265             return 1;
1266         }
1267
1268         if (attrs.permissions & 0040000) {
1269             struct scp_sftp_dirstack *newitem;
1270             struct fxp_handle *dirhandle;
1271             int nnames, namesize;
1272             struct fxp_name *ournames;
1273             struct fxp_names *names;
1274
1275             /*
1276              * It's a directory. If we're not in recursive mode,
1277              * this merits a complaint (which is fatal if the name
1278              * was specified directly, but not if it was matched by
1279              * a wildcard).
1280              * 
1281              * We skip this complaint completely if
1282              * scp_sftp_wildcard is set, because that's an
1283              * indication that we're not actually supposed to
1284              * _recursively_ transfer the dir, just scan it for
1285              * things matching the wildcard.
1286              */
1287             if (!scp_sftp_recursive && !scp_sftp_wildcard) {
1288                 tell_user(stderr, "pscp: %s: is a directory", fname);
1289                 errs++;
1290                 if (must_free_fname) sfree(fname);
1291                 if (scp_sftp_dirstack_head) {
1292                     act->action = SCP_SINK_RETRY;
1293                     return 0;
1294                 } else {
1295                     return 1;
1296                 }
1297             }
1298
1299             /*
1300              * Otherwise, the fun begins. We must fxp_opendir() the
1301              * directory, slurp the filenames into memory, return
1302              * SCP_SINK_DIR (unless this is a wildcard match), and
1303              * set targetisdir. The next time we're called, we will
1304              * run through the list of filenames one by one,
1305              * matching them against a wildcard if present.
1306              * 
1307              * If targetisdir is _already_ set (meaning we're
1308              * already in the middle of going through another such
1309              * list), we must push the other (target,namelist) pair
1310              * on a stack.
1311              */
1312             req = fxp_opendir_send(fname);
1313             pktin = sftp_wait_for_reply(req);
1314             dirhandle = fxp_opendir_recv(pktin, req);
1315
1316             if (!dirhandle) {
1317                 tell_user(stderr, "pscp: unable to open directory %s: %s",
1318                           fname, fxp_error());
1319                 if (must_free_fname) sfree(fname);
1320                 errs++;
1321                 return 1;
1322             }
1323             nnames = namesize = 0;
1324             ournames = NULL;
1325             while (1) {
1326                 int i;
1327
1328                 req = fxp_readdir_send(dirhandle);
1329                 pktin = sftp_wait_for_reply(req);
1330                 names = fxp_readdir_recv(pktin, req);
1331
1332                 if (names == NULL) {
1333                     if (fxp_error_type() == SSH_FX_EOF)
1334                         break;
1335                     tell_user(stderr, "pscp: reading directory %s: %s",
1336                               fname, fxp_error());
1337
1338                     req = fxp_close_send(dirhandle);
1339                     pktin = sftp_wait_for_reply(req);
1340                     fxp_close_recv(pktin, req);
1341
1342                     if (must_free_fname) sfree(fname);
1343                     sfree(ournames);
1344                     errs++;
1345                     return 1;
1346                 }
1347                 if (names->nnames == 0) {
1348                     fxp_free_names(names);
1349                     break;
1350                 }
1351                 if (nnames + names->nnames >= namesize) {
1352                     namesize += names->nnames + 128;
1353                     ournames = sresize(ournames, namesize, struct fxp_name);
1354                 }
1355                 for (i = 0; i < names->nnames; i++) {
1356                     if (!strcmp(names->names[i].filename, ".") ||
1357                         !strcmp(names->names[i].filename, "..")) {
1358                         /*
1359                          * . and .. are normal consequences of
1360                          * reading a directory, and aren't worth
1361                          * complaining about.
1362                          */
1363                     } else if (!vet_filename(names->names[i].filename)) {
1364                         tell_user(stderr, "ignoring potentially dangerous server-"
1365                                   "supplied filename '%s'",
1366                                   names->names[i].filename);
1367                     } else
1368                         ournames[nnames++] = names->names[i];
1369                 }
1370                 names->nnames = 0;             /* prevent free_names */
1371                 fxp_free_names(names);
1372             }
1373             req = fxp_close_send(dirhandle);
1374             pktin = sftp_wait_for_reply(req);
1375             fxp_close_recv(pktin, req);
1376
1377             newitem = snew(struct scp_sftp_dirstack);
1378             newitem->next = scp_sftp_dirstack_head;
1379             newitem->names = ournames;
1380             newitem->namepos = 0;
1381             newitem->namelen = nnames;
1382             if (must_free_fname)
1383                 newitem->dirpath = fname;
1384             else
1385                 newitem->dirpath = dupstr(fname);
1386             if (scp_sftp_wildcard) {
1387                 newitem->wildcard = scp_sftp_wildcard;
1388                 newitem->matched_something = 0;
1389                 scp_sftp_wildcard = NULL;
1390             } else {
1391                 newitem->wildcard = NULL;
1392             }
1393             scp_sftp_dirstack_head = newitem;
1394
1395             if (newitem->wildcard) {
1396                 act->action = SCP_SINK_RETRY;
1397             } else {
1398                 act->action = SCP_SINK_DIR;
1399                 act->buf = dupstr(stripslashes(fname, 0));
1400                 act->name = act->buf;
1401                 act->size = uint64_make(0,0);     /* duhh, it's a directory */
1402                 act->permissions = 07777 & attrs.permissions;
1403                 if (scp_sftp_preserve &&
1404                     (attrs.flags & SSH_FILEXFER_ATTR_ACMODTIME)) {
1405                     act->atime = attrs.atime;
1406                     act->mtime = attrs.mtime;
1407                     act->settime = 1;
1408                 } else
1409                     act->settime = 0;
1410             }
1411             return 0;
1412
1413         } else {
1414             /*
1415              * It's a file. Return SCP_SINK_FILE.
1416              */
1417             act->action = SCP_SINK_FILE;
1418             act->buf = dupstr(stripslashes(fname, 0));
1419             act->name = act->buf;
1420             if (attrs.flags & SSH_FILEXFER_ATTR_SIZE) {
1421                 act->size = attrs.size;
1422             } else
1423                 act->size = uint64_make(ULONG_MAX,ULONG_MAX);   /* no idea */
1424             act->permissions = 07777 & attrs.permissions;
1425             if (scp_sftp_preserve &&
1426                 (attrs.flags & SSH_FILEXFER_ATTR_ACMODTIME)) {
1427                 act->atime = attrs.atime;
1428                 act->mtime = attrs.mtime;
1429                 act->settime = 1;
1430             } else
1431                 act->settime = 0;
1432             if (must_free_fname)
1433                 scp_sftp_currentname = fname;
1434             else
1435                 scp_sftp_currentname = dupstr(fname);
1436             return 0;
1437         }
1438
1439     } else {
1440         int done = 0;
1441         int i, bufsize;
1442         int action;
1443         char ch;
1444
1445         act->settime = 0;
1446         act->buf = NULL;
1447         bufsize = 0;
1448
1449         while (!done) {
1450             if (ssh_scp_recv((unsigned char *) &ch, 1) <= 0)
1451                 return 1;
1452             if (ch == '\n')
1453                 bump("Protocol error: Unexpected newline");
1454             i = 0;
1455             action = ch;
1456             do {
1457                 if (ssh_scp_recv((unsigned char *) &ch, 1) <= 0)
1458                     bump("Lost connection");
1459                 if (i >= bufsize) {
1460                     bufsize = i + 128;
1461                     act->buf = sresize(act->buf, bufsize, char);
1462                 }
1463                 act->buf[i++] = ch;
1464             } while (ch != '\n');
1465             act->buf[i - 1] = '\0';
1466             switch (action) {
1467               case '\01':                      /* error */
1468                 tell_user(stderr, "%s", act->buf);
1469                 errs++;
1470                 continue;                      /* go round again */
1471               case '\02':                      /* fatal error */
1472                 bump("%s", act->buf);
1473               case 'E':
1474                 back->send(backhandle, "", 1);
1475                 act->action = SCP_SINK_ENDDIR;
1476                 return 0;
1477               case 'T':
1478                 if (sscanf(act->buf, "%ld %*d %ld %*d",
1479                            &act->mtime, &act->atime) == 2) {
1480                     act->settime = 1;
1481                     back->send(backhandle, "", 1);
1482                     continue;          /* go round again */
1483                 }
1484                 bump("Protocol error: Illegal time format");
1485               case 'C':
1486               case 'D':
1487                 act->action = (action == 'C' ? SCP_SINK_FILE : SCP_SINK_DIR);
1488                 break;
1489               default:
1490                 bump("Protocol error: Expected control record");
1491             }
1492             /*
1493              * We will go round this loop only once, unless we hit
1494              * `continue' above.
1495              */
1496             done = 1;
1497         }
1498
1499         /*
1500          * If we get here, we must have seen SCP_SINK_FILE or
1501          * SCP_SINK_DIR.
1502          */
1503         {
1504             char sizestr[40];
1505         
1506             if (sscanf(act->buf, "%lo %39s %n", &act->permissions,
1507                        sizestr, &i) != 2)
1508                 bump("Protocol error: Illegal file descriptor format");
1509             act->size = uint64_from_decimal(sizestr);
1510             act->name = act->buf + i;
1511             return 0;
1512         }
1513     }
1514 }
1515
1516 int scp_accept_filexfer(void)
1517 {
1518     if (using_sftp) {
1519         struct sftp_packet *pktin;
1520         struct sftp_request *req;
1521
1522         req = fxp_open_send(scp_sftp_currentname, SSH_FXF_READ, NULL);
1523         pktin = sftp_wait_for_reply(req);
1524         scp_sftp_filehandle = fxp_open_recv(pktin, req);
1525
1526         if (!scp_sftp_filehandle) {
1527             tell_user(stderr, "pscp: unable to open %s: %s",
1528                       scp_sftp_currentname, fxp_error());
1529             errs++;
1530             return 1;
1531         }
1532         scp_sftp_fileoffset = uint64_make(0, 0);
1533         scp_sftp_xfer = xfer_download_init(scp_sftp_filehandle,
1534                                            scp_sftp_fileoffset);
1535         sfree(scp_sftp_currentname);
1536         return 0;
1537     } else {
1538         back->send(backhandle, "", 1);
1539         return 0;                      /* can't fail */
1540     }
1541 }
1542
1543 int scp_recv_filedata(char *data, int len)
1544 {
1545     if (using_sftp) {
1546         struct sftp_packet *pktin;
1547         int ret, actuallen;
1548         void *vbuf;
1549
1550         xfer_download_queue(scp_sftp_xfer);
1551         pktin = sftp_recv();
1552         ret = xfer_download_gotpkt(scp_sftp_xfer, pktin);
1553         if (ret <= 0) {
1554             tell_user(stderr, "pscp: error while reading: %s", fxp_error());
1555             if (ret == INT_MIN)        /* pktin not even freed */
1556                 sfree(pktin);
1557             errs++;
1558             return -1;
1559         }
1560
1561         if (xfer_download_data(scp_sftp_xfer, &vbuf, &actuallen)) {
1562             /*
1563              * This assertion relies on the fact that the natural
1564              * block size used in the xfer manager is at most that
1565              * used in this module. I don't like crossing layers in
1566              * this way, but it'll do for now.
1567              */
1568             assert(actuallen <= len);
1569             memcpy(data, vbuf, actuallen);
1570             sfree(vbuf);
1571         } else
1572             actuallen = 0;
1573
1574         scp_sftp_fileoffset = uint64_add32(scp_sftp_fileoffset, actuallen);
1575
1576         return actuallen;
1577     } else {
1578         return ssh_scp_recv((unsigned char *) data, len);
1579     }
1580 }
1581
1582 int scp_finish_filerecv(void)
1583 {
1584     if (using_sftp) {
1585         struct sftp_packet *pktin;
1586         struct sftp_request *req;
1587
1588         /*
1589          * Ensure that xfer_done() will work correctly, so we can
1590          * clean up any outstanding requests from the file
1591          * transfer.
1592          */
1593         xfer_set_error(scp_sftp_xfer);
1594         while (!xfer_done(scp_sftp_xfer)) {
1595             void *vbuf;
1596             int ret, len;
1597
1598             pktin = sftp_recv();
1599             ret = xfer_download_gotpkt(scp_sftp_xfer, pktin);
1600             if (ret <= 0) {
1601                 tell_user(stderr, "pscp: error while reading: %s", fxp_error());
1602                 if (ret == INT_MIN)        /* pktin not even freed */
1603                     sfree(pktin);
1604                 errs++;
1605                 return -1;
1606             }
1607             if (xfer_download_data(scp_sftp_xfer, &vbuf, &len))
1608                 sfree(vbuf);
1609         }
1610         xfer_cleanup(scp_sftp_xfer);
1611
1612         req = fxp_close_send(scp_sftp_filehandle);
1613         pktin = sftp_wait_for_reply(req);
1614         fxp_close_recv(pktin, req);
1615         return 0;
1616     } else {
1617         back->send(backhandle, "", 1);
1618         return response();
1619     }
1620 }
1621
1622 /* ----------------------------------------------------------------------
1623  *  Send an error message to the other side and to the screen.
1624  *  Increment error counter.
1625  */
1626 static void run_err(const char *fmt, ...)
1627 {
1628     char *str, *str2;
1629     va_list ap;
1630     va_start(ap, fmt);
1631     errs++;
1632     str = dupvprintf(fmt, ap);
1633     str2 = dupcat("pscp: ", str, "\n", NULL);
1634     sfree(str);
1635     scp_send_errmsg(str2);
1636     tell_user(stderr, "%s", str2);
1637     va_end(ap);
1638     sfree(str2);
1639 }
1640
1641 /*
1642  *  Execute the source part of the SCP protocol.
1643  */
1644 static void source(const char *src)
1645 {
1646     uint64 size;
1647     unsigned long mtime, atime;
1648     long permissions;
1649     const char *last;
1650     RFile *f;
1651     int attr;
1652     uint64 i;
1653     uint64 stat_bytes;
1654     time_t stat_starttime, stat_lasttime;
1655
1656     attr = file_type(src);
1657     if (attr == FILE_TYPE_NONEXISTENT ||
1658         attr == FILE_TYPE_WEIRD) {
1659         run_err("%s: %s file or directory", src,
1660                 (attr == FILE_TYPE_WEIRD ? "Not a" : "No such"));
1661         return;
1662     }
1663
1664     if (attr == FILE_TYPE_DIRECTORY) {
1665         if (recursive) {
1666             /*
1667              * Avoid . and .. directories.
1668              */
1669             const char *p;
1670             p = strrchr(src, '/');
1671             if (!p)
1672                 p = strrchr(src, '\\');
1673             if (!p)
1674                 p = src;
1675             else
1676                 p++;
1677             if (!strcmp(p, ".") || !strcmp(p, ".."))
1678                 /* skip . and .. */ ;
1679             else
1680                 rsource(src);
1681         } else {
1682             run_err("%s: not a regular file", src);
1683         }
1684         return;
1685     }
1686
1687     if ((last = strrchr(src, '/')) == NULL)
1688         last = src;
1689     else
1690         last++;
1691     if (strrchr(last, '\\') != NULL)
1692         last = strrchr(last, '\\') + 1;
1693     if (last == src && strchr(src, ':') != NULL)
1694         last = strchr(src, ':') + 1;
1695
1696     f = open_existing_file(src, &size, &mtime, &atime, &permissions);
1697     if (f == NULL) {
1698         run_err("%s: Cannot open file", src);
1699         return;
1700     }
1701     if (preserve) {
1702         if (scp_send_filetimes(mtime, atime)) {
1703             close_rfile(f);
1704             return;
1705         }
1706     }
1707
1708     if (verbose) {
1709         char sizestr[40];
1710         uint64_decimal(size, sizestr);
1711         tell_user(stderr, "Sending file %s, size=%s", last, sizestr);
1712     }
1713     if (scp_send_filename(last, size, permissions)) {
1714         close_rfile(f);
1715         return;
1716     }
1717
1718     stat_bytes = uint64_make(0,0);
1719     stat_starttime = time(NULL);
1720     stat_lasttime = 0;
1721
1722 #define PSCP_SEND_BLOCK 4096
1723     for (i = uint64_make(0,0);
1724          uint64_compare(i,size) < 0;
1725          i = uint64_add32(i,PSCP_SEND_BLOCK)) {
1726         char transbuf[PSCP_SEND_BLOCK];
1727         int j, k = PSCP_SEND_BLOCK;
1728
1729         if (uint64_compare(uint64_add32(i, k),size) > 0) /* i + k > size */ 
1730             k = (uint64_subtract(size, i)).lo;  /* k = size - i; */
1731         if ((j = read_from_file(f, transbuf, k)) != k) {
1732             if (statistics)
1733                 printf("\n");
1734             bump("%s: Read error", src);
1735         }
1736         if (scp_send_filedata(transbuf, k))
1737             bump("%s: Network error occurred", src);
1738
1739         if (statistics) {
1740             stat_bytes = uint64_add32(stat_bytes, k);
1741             if (time(NULL) != stat_lasttime ||
1742                 (uint64_compare(uint64_add32(i, k), size) == 0)) {
1743                 stat_lasttime = time(NULL);
1744                 print_stats(last, size, stat_bytes,
1745                             stat_starttime, stat_lasttime);
1746             }
1747         }
1748
1749     }
1750     close_rfile(f);
1751
1752     (void) scp_send_finish();
1753 }
1754
1755 /*
1756  *  Recursively send the contents of a directory.
1757  */
1758 static void rsource(const char *src)
1759 {
1760     const char *last;
1761     char *save_target;
1762     DirHandle *dir;
1763
1764     if ((last = strrchr(src, '/')) == NULL)
1765         last = src;
1766     else
1767         last++;
1768     if (strrchr(last, '\\') != NULL)
1769         last = strrchr(last, '\\') + 1;
1770     if (last == src && strchr(src, ':') != NULL)
1771         last = strchr(src, ':') + 1;
1772
1773     /* maybe send filetime */
1774
1775     save_target = scp_save_remotepath();
1776
1777     if (verbose)
1778         tell_user(stderr, "Entering directory: %s", last);
1779     if (scp_send_dirname(last, 0755))
1780         return;
1781
1782     dir = open_directory(src);
1783     if (dir != NULL) {
1784         char *filename;
1785         while ((filename = read_filename(dir)) != NULL) {
1786             char *foundfile = dupcat(src, "/", filename, NULL);
1787             source(foundfile);
1788             sfree(foundfile);
1789             sfree(filename);
1790         }
1791     }
1792     close_directory(dir);
1793
1794     (void) scp_send_enddir();
1795
1796     scp_restore_remotepath(save_target);
1797 }
1798
1799 /*
1800  * Execute the sink part of the SCP protocol.
1801  */
1802 static void sink(const char *targ, const char *src)
1803 {
1804     char *destfname;
1805     int targisdir = 0;
1806     int exists;
1807     int attr;
1808     WFile *f;
1809     uint64 received;
1810     int wrerror = 0;
1811     uint64 stat_bytes;
1812     time_t stat_starttime, stat_lasttime;
1813     char *stat_name;
1814
1815     attr = file_type(targ);
1816     if (attr == FILE_TYPE_DIRECTORY)
1817         targisdir = 1;
1818
1819     if (targetshouldbedirectory && !targisdir)
1820         bump("%s: Not a directory", targ);
1821
1822     scp_sink_init();
1823     while (1) {
1824         struct scp_sink_action act;
1825         if (scp_get_sink_action(&act))
1826             return;
1827
1828         if (act.action == SCP_SINK_ENDDIR)
1829             return;
1830
1831         if (act.action == SCP_SINK_RETRY)
1832             continue;
1833
1834         if (targisdir) {
1835             /*
1836              * Prevent the remote side from maliciously writing to
1837              * files outside the target area by sending a filename
1838              * containing `../'. In fact, it shouldn't be sending
1839              * filenames with any slashes or colons in at all; so
1840              * we'll find the last slash, backslash or colon in the
1841              * filename and use only the part after that. (And
1842              * warn!)
1843              * 
1844              * In addition, we also ensure here that if we're
1845              * copying a single file and the target is a directory
1846              * (common usage: `pscp host:filename .') the remote
1847              * can't send us a _different_ file name. We can
1848              * distinguish this case because `src' will be non-NULL
1849              * and the last component of that will fail to match
1850              * (the last component of) the name sent.
1851              * 
1852              * Well, not always; if `src' is a wildcard, we do
1853              * expect to get back filenames that don't correspond
1854              * exactly to it. Ideally in this case, we would like
1855              * to ensure that the returned filename actually
1856              * matches the wildcard pattern - but one of SCP's
1857              * protocol infelicities is that wildcard matching is
1858              * done at the server end _by the server's rules_ and
1859              * so in general this is infeasible. Hence, we only
1860              * accept filenames that don't correspond to `src' if
1861              * unsafe mode is enabled or we are using SFTP (which
1862              * resolves remote wildcards on the client side and can
1863              * be trusted).
1864              */
1865             char *striptarget, *stripsrc;
1866
1867             striptarget = stripslashes(act.name, 1);
1868             if (striptarget != act.name) {
1869                 tell_user(stderr, "warning: remote host sent a compound"
1870                           " pathname '%s'", act.name);
1871                 tell_user(stderr, "         renaming local file to '%s'",
1872                           striptarget);
1873             }
1874
1875             /*
1876              * Also check to see if the target filename is '.' or
1877              * '..', or indeed '...' and so on because Windows
1878              * appears to interpret those like '..'.
1879              */
1880             if (is_dots(striptarget)) {
1881                 bump("security violation: remote host attempted to write to"
1882                      " a '.' or '..' path!");
1883             }
1884
1885             if (src) {
1886                 stripsrc = stripslashes(src, 1);
1887                 if (strcmp(striptarget, stripsrc) &&
1888                     !using_sftp && !scp_unsafe_mode) {
1889                     tell_user(stderr, "warning: remote host tried to write "
1890                               "to a file called '%s'", striptarget);
1891                     tell_user(stderr, "         when we requested a file "
1892                               "called '%s'.", stripsrc);
1893                     tell_user(stderr, "         If this is a wildcard, "
1894                               "consider upgrading to SSH-2 or using");
1895                     tell_user(stderr, "         the '-unsafe' option. Renaming"
1896                               " of this file has been disallowed.");
1897                     /* Override the name the server provided with our own. */
1898                     striptarget = stripsrc;
1899                 }
1900             }
1901
1902             if (targ[0] != '\0')
1903                 destfname = dir_file_cat(targ, striptarget);
1904             else
1905                 destfname = dupstr(striptarget);
1906         } else {
1907             /*
1908              * In this branch of the if, the target area is a
1909              * single file with an explicitly specified name in any
1910              * case, so there's no danger.
1911              */
1912             destfname = dupstr(targ);
1913         }
1914         attr = file_type(destfname);
1915         exists = (attr != FILE_TYPE_NONEXISTENT);
1916
1917         if (act.action == SCP_SINK_DIR) {
1918             if (exists && attr != FILE_TYPE_DIRECTORY) {
1919                 run_err("%s: Not a directory", destfname);
1920                 sfree(destfname);
1921                 continue;
1922             }
1923             if (!exists) {
1924                 if (!create_directory(destfname)) {
1925                     run_err("%s: Cannot create directory", destfname);
1926                     sfree(destfname);
1927                     continue;
1928                 }
1929             }
1930             sink(destfname, NULL);
1931             /* can we set the timestamp for directories ? */
1932             sfree(destfname);
1933             continue;
1934         }
1935
1936         f = open_new_file(destfname, act.permissions);
1937         if (f == NULL) {
1938             run_err("%s: Cannot create file", destfname);
1939             sfree(destfname);
1940             continue;
1941         }
1942
1943         if (scp_accept_filexfer()) {
1944             sfree(destfname);
1945             close_wfile(f);
1946             return;
1947         }
1948
1949         stat_bytes = uint64_make(0, 0);
1950         stat_starttime = time(NULL);
1951         stat_lasttime = 0;
1952         stat_name = stripslashes(destfname, 1);
1953
1954         received = uint64_make(0, 0);
1955         while (uint64_compare(received,act.size) < 0) {
1956             char transbuf[32768];
1957             uint64 blksize;
1958             int read;
1959             blksize = uint64_make(0, 32768);
1960             if (uint64_compare(blksize,uint64_subtract(act.size,received)) > 0)
1961               blksize = uint64_subtract(act.size,received);
1962             read = scp_recv_filedata(transbuf, (int)blksize.lo);
1963             if (read <= 0)
1964                 bump("Lost connection");
1965             if (wrerror)
1966                 continue;
1967             if (write_to_file(f, transbuf, read) != (int)read) {
1968                 wrerror = 1;
1969                 /* FIXME: in sftp we can actually abort the transfer */
1970                 if (statistics)
1971                     printf("\r%-25.25s | %50s\n",
1972                            stat_name,
1973                            "Write error.. waiting for end of file");
1974                 continue;
1975             }
1976             if (statistics) {
1977                 stat_bytes = uint64_add32(stat_bytes,read);
1978                 if (time(NULL) > stat_lasttime ||
1979                     uint64_compare(uint64_add32(received, read), act.size) == 0) {
1980                     stat_lasttime = time(NULL);
1981                     print_stats(stat_name, act.size, stat_bytes,
1982                                 stat_starttime, stat_lasttime);
1983                 }
1984             }
1985             received = uint64_add32(received, read);
1986         }
1987         if (act.settime) {
1988             set_file_times(f, act.mtime, act.atime);
1989         }
1990
1991         close_wfile(f);
1992         if (wrerror) {
1993             run_err("%s: Write error", destfname);
1994             sfree(destfname);
1995             continue;
1996         }
1997         (void) scp_finish_filerecv();
1998         sfree(destfname);
1999         sfree(act.buf);
2000     }
2001 }
2002
2003 /*
2004  * We will copy local files to a remote server.
2005  */
2006 static void toremote(int argc, char *argv[])
2007 {
2008     char *src, *wtarg, *host, *user;
2009     const char *targ;
2010     char *cmd;
2011     int i, wc_type;
2012
2013     uploading = 1;
2014
2015     wtarg = argv[argc - 1];
2016
2017     /* Separate host from filename */
2018     host = wtarg;
2019     wtarg = colon(wtarg);
2020     if (wtarg == NULL)
2021         bump("wtarg == NULL in toremote()");
2022     *wtarg++ = '\0';
2023     /* Substitute "." for empty target */
2024     if (*wtarg == '\0')
2025         targ = ".";
2026     else
2027         targ = wtarg;
2028
2029     /* Separate host and username */
2030     user = host;
2031     host = strrchr(host, '@');
2032     if (host == NULL) {
2033         host = user;
2034         user = NULL;
2035     } else {
2036         *host++ = '\0';
2037         if (*user == '\0')
2038             user = NULL;
2039     }
2040
2041     if (argc == 2) {
2042         if (colon(argv[0]) != NULL)
2043             bump("%s: Remote to remote not supported", argv[0]);
2044
2045         wc_type = test_wildcard(argv[0], 1);
2046         if (wc_type == WCTYPE_NONEXISTENT)
2047             bump("%s: No such file or directory\n", argv[0]);
2048         else if (wc_type == WCTYPE_WILDCARD)
2049             targetshouldbedirectory = 1;
2050     }
2051
2052     cmd = dupprintf("scp%s%s%s%s -t %s",
2053                     verbose ? " -v" : "",
2054                     recursive ? " -r" : "",
2055                     preserve ? " -p" : "",
2056                     targetshouldbedirectory ? " -d" : "", targ);
2057     do_cmd(host, user, cmd);
2058     sfree(cmd);
2059
2060     if (scp_source_setup(targ, targetshouldbedirectory))
2061         return;
2062
2063     for (i = 0; i < argc - 1; i++) {
2064         src = argv[i];
2065         if (colon(src) != NULL) {
2066             tell_user(stderr, "%s: Remote to remote not supported\n", src);
2067             errs++;
2068             continue;
2069         }
2070
2071         wc_type = test_wildcard(src, 1);
2072         if (wc_type == WCTYPE_NONEXISTENT) {
2073             run_err("%s: No such file or directory", src);
2074             continue;
2075         } else if (wc_type == WCTYPE_FILENAME) {
2076             source(src);
2077             continue;
2078         } else {
2079             WildcardMatcher *wc;
2080             char *filename;
2081
2082             wc = begin_wildcard_matching(src);
2083             if (wc == NULL) {
2084                 run_err("%s: No such file or directory", src);
2085                 continue;
2086             }
2087
2088             while ((filename = wildcard_get_filename(wc)) != NULL) {
2089                 source(filename);
2090                 sfree(filename);
2091             }
2092
2093             finish_wildcard_matching(wc);
2094         }
2095     }
2096 }
2097
2098 /*
2099  *  We will copy files from a remote server to the local machine.
2100  */
2101 static void tolocal(int argc, char *argv[])
2102 {
2103     char *wsrc, *host, *user;
2104     const char *src, *targ;
2105     char *cmd;
2106
2107     uploading = 0;
2108
2109     if (argc != 2)
2110         bump("More than one remote source not supported");
2111
2112     wsrc = argv[0];
2113     targ = argv[1];
2114
2115     /* Separate host from filename */
2116     host = wsrc;
2117     wsrc = colon(wsrc);
2118     if (wsrc == NULL)
2119         bump("Local to local copy not supported");
2120     *wsrc++ = '\0';
2121     /* Substitute "." for empty filename */
2122     if (*wsrc == '\0')
2123         src = ".";
2124     else
2125         src = wsrc;
2126
2127     /* Separate username and hostname */
2128     user = host;
2129     host = strrchr(host, '@');
2130     if (host == NULL) {
2131         host = user;
2132         user = NULL;
2133     } else {
2134         *host++ = '\0';
2135         if (*user == '\0')
2136             user = NULL;
2137     }
2138
2139     cmd = dupprintf("scp%s%s%s%s -f %s",
2140                     verbose ? " -v" : "",
2141                     recursive ? " -r" : "",
2142                     preserve ? " -p" : "",
2143                     targetshouldbedirectory ? " -d" : "", src);
2144     do_cmd(host, user, cmd);
2145     sfree(cmd);
2146
2147     if (scp_sink_setup(src, preserve, recursive))
2148         return;
2149
2150     sink(targ, src);
2151 }
2152
2153 /*
2154  *  We will issue a list command to get a remote directory.
2155  */
2156 static void get_dir_list(int argc, char *argv[])
2157 {
2158     char *wsrc, *host, *user;
2159     const char *src;
2160     char *cmd, *p;
2161     const char *q;
2162     char c;
2163
2164     wsrc = argv[0];
2165
2166     /* Separate host from filename */
2167     host = wsrc;
2168     wsrc = colon(wsrc);
2169     if (wsrc == NULL)
2170         bump("Local file listing not supported");
2171     *wsrc++ = '\0';
2172     /* Substitute "." for empty filename */
2173     if (*wsrc == '\0')
2174         src = ".";
2175     else
2176         src = wsrc;
2177
2178     /* Separate username and hostname */
2179     user = host;
2180     host = strrchr(host, '@');
2181     if (host == NULL) {
2182         host = user;
2183         user = NULL;
2184     } else {
2185         *host++ = '\0';
2186         if (*user == '\0')
2187             user = NULL;
2188     }
2189
2190     cmd = snewn(4 * strlen(src) + 100, char);
2191     strcpy(cmd, "ls -la '");
2192     p = cmd + strlen(cmd);
2193     for (q = src; *q; q++) {
2194         if (*q == '\'') {
2195             *p++ = '\'';
2196             *p++ = '\\';
2197             *p++ = '\'';
2198             *p++ = '\'';
2199         } else {
2200             *p++ = *q;
2201         }
2202     }
2203     *p++ = '\'';
2204     *p = '\0';
2205
2206     do_cmd(host, user, cmd);
2207     sfree(cmd);
2208
2209     if (using_sftp) {
2210         scp_sftp_listdir(src);
2211     } else {
2212         while (ssh_scp_recv((unsigned char *) &c, 1) > 0)
2213             tell_char(stdout, c);
2214     }
2215 }
2216
2217 /*
2218  *  Short description of parameters.
2219  */
2220 static void usage(void)
2221 {
2222     printf("PuTTY Secure Copy client\n");
2223     printf("%s\n", ver);
2224     printf("Usage: pscp [options] [user@]host:source target\n");
2225     printf
2226         ("       pscp [options] source [source...] [user@]host:target\n");
2227     printf("       pscp [options] -ls [user@]host:filespec\n");
2228     printf("Options:\n");
2229     printf("  -V        print version information and exit\n");
2230     printf("  -pgpfp    print PGP key fingerprints and exit\n");
2231     printf("  -p        preserve file attributes\n");
2232     printf("  -q        quiet, don't show statistics\n");
2233     printf("  -r        copy directories recursively\n");
2234     printf("  -v        show verbose messages\n");
2235     printf("  -load sessname  Load settings from saved session\n");
2236     printf("  -P port   connect to specified port\n");
2237     printf("  -l user   connect with specified username\n");
2238     printf("  -pw passw login with specified password\n");
2239     printf("  -1 -2     force use of particular SSH protocol version\n");
2240     printf("  -4 -6     force use of IPv4 or IPv6\n");
2241     printf("  -C        enable compression\n");
2242     printf("  -i key    private key file for user authentication\n");
2243     printf("  -noagent  disable use of Pageant\n");
2244     printf("  -agent    enable use of Pageant\n");
2245     printf("  -hostkey aa:bb:cc:...\n");
2246     printf("            manually specify a host key (may be repeated)\n");
2247     printf("  -batch    disable all interactive prompts\n");
2248     printf("  -proxycmd command\n");
2249     printf("            use 'command' as local proxy\n");
2250     printf("  -unsafe   allow server-side wildcards (DANGEROUS)\n");
2251     printf("  -sftp     force use of SFTP protocol\n");
2252     printf("  -scp      force use of SCP protocol\n");
2253     printf("  -sshlog file\n");
2254     printf("  -sshrawlog file\n");
2255     printf("            log protocol details to a file\n");
2256 #if 0
2257     /*
2258      * -gui is an internal option, used by GUI front ends to get
2259      * pscp to pass progress reports back to them. It's not an
2260      * ordinary user-accessible option, so it shouldn't be part of
2261      * the command-line help. The only people who need to know
2262      * about it are programmers, and they can read the source.
2263      */
2264     printf
2265         ("  -gui hWnd GUI mode with the windows handle for receiving messages\n");
2266 #endif
2267     cleanup_exit(1);
2268 }
2269
2270 void version(void)
2271 {
2272     char *buildinfo_text = buildinfo("\n");
2273     printf("pscp: %s\n%s\n", ver, buildinfo_text);
2274     sfree(buildinfo_text);
2275     cleanup_exit(1);
2276 }
2277
2278 void cmdline_error(const char *p, ...)
2279 {
2280     va_list ap;
2281     fprintf(stderr, "pscp: ");
2282     va_start(ap, p);
2283     vfprintf(stderr, p, ap);
2284     va_end(ap);
2285     fprintf(stderr, "\n      try typing just \"pscp\" for help\n");
2286     exit(1);
2287 }
2288
2289 const int share_can_be_downstream = TRUE;
2290 const int share_can_be_upstream = FALSE;
2291
2292 /*
2293  * Main program. (Called `psftp_main' because it gets called from
2294  * *sftp.c; bit silly, I know, but it had to be called _something_.)
2295  */
2296 int psftp_main(int argc, char *argv[])
2297 {
2298     int i;
2299
2300     default_protocol = PROT_TELNET;
2301
2302     flags = FLAG_STDERR
2303 #ifdef FLAG_SYNCAGENT
2304         | FLAG_SYNCAGENT
2305 #endif
2306         ;
2307     cmdline_tooltype = TOOLTYPE_FILETRANSFER;
2308     sk_init();
2309
2310     /* Load Default Settings before doing anything else. */
2311     conf = conf_new();
2312     do_defaults(NULL, conf);
2313     loaded_session = FALSE;
2314
2315     for (i = 1; i < argc; i++) {
2316         int ret;
2317         if (argv[i][0] != '-')
2318             break;
2319         ret = cmdline_process_param(argv[i], i+1<argc?argv[i+1]:NULL, 1, conf);
2320         if (ret == -2) {
2321             cmdline_error("option \"%s\" requires an argument", argv[i]);
2322         } else if (ret == 2) {
2323             i++;               /* skip next argument */
2324         } else if (ret == 1) {
2325             /* We have our own verbosity in addition to `flags'. */
2326             if (flags & FLAG_VERBOSE)
2327                 verbose = 1;
2328         } else if (strcmp(argv[i], "-pgpfp") == 0) {
2329             pgp_fingerprints();
2330             return 1;
2331         } else if (strcmp(argv[i], "-r") == 0) {
2332             recursive = 1;
2333         } else if (strcmp(argv[i], "-p") == 0) {
2334             preserve = 1;
2335         } else if (strcmp(argv[i], "-q") == 0) {
2336             statistics = 0;
2337         } else if (strcmp(argv[i], "-h") == 0 ||
2338                    strcmp(argv[i], "-?") == 0 ||
2339                    strcmp(argv[i], "--help") == 0) {
2340             usage();
2341         } else if (strcmp(argv[i], "-V") == 0 ||
2342                    strcmp(argv[i], "--version") == 0) {
2343             version();
2344         } else if (strcmp(argv[i], "-ls") == 0) {
2345             list = 1;
2346         } else if (strcmp(argv[i], "-batch") == 0) {
2347             console_batch_mode = 1;
2348         } else if (strcmp(argv[i], "-unsafe") == 0) {
2349             scp_unsafe_mode = 1;
2350         } else if (strcmp(argv[i], "-sftp") == 0) {
2351             try_scp = 0; try_sftp = 1;
2352         } else if (strcmp(argv[i], "-scp") == 0) {
2353             try_scp = 1; try_sftp = 0;
2354         } else if (strcmp(argv[i], "--") == 0) {
2355             i++;
2356             break;
2357         } else {
2358             cmdline_error("unknown option \"%s\"", argv[i]);
2359         }
2360     }
2361     argc -= i;
2362     argv += i;
2363     back = NULL;
2364
2365     if (list) {
2366         if (argc != 1)
2367             usage();
2368         get_dir_list(argc, argv);
2369
2370     } else {
2371
2372         if (argc < 2)
2373             usage();
2374         if (argc > 2)
2375             targetshouldbedirectory = 1;
2376
2377         if (colon(argv[argc - 1]) != NULL)
2378             toremote(argc, argv);
2379         else
2380             tolocal(argc, argv);
2381     }
2382
2383     if (back != NULL && back->connected(backhandle)) {
2384         char ch;
2385         back->special(backhandle, TS_EOF);
2386         sent_eof = TRUE;
2387         ssh_scp_recv((unsigned char *) &ch, 1);
2388     }
2389     random_save_seed();
2390
2391     cmdline_cleanup();
2392     console_provide_logctx(NULL);
2393     back->free(backhandle);
2394     backhandle = NULL;
2395     back = NULL;
2396     sk_cleanup();
2397     return (errs == 0 ? 0 : 1);
2398 }
2399
2400 /* end */