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