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