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