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