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