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