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