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