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