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