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