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