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