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