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