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