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