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