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