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