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