Prevent network errors from summarily closing the window when CoE is off
[u/mdw/putty] / scp.c
CommitLineData
07d9aa13 1/*
2 * scp.c - Scp (Secure Copy) client for PuTTY.
fb09bf1c 3 * Joris van Rantwijk, Simon Tatham
07d9aa13 4 *
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.
cc87246d 7 *
8 * Adaptations to enable connecting a GUI by L. Gunnarsson - Sept 2000
07d9aa13 9 */
10
07d9aa13 11#include <windows.h>
12#include <winsock.h>
13#include <stdlib.h>
14#include <stdio.h>
15#include <string.h>
16#include <time.h>
cc87246d 17/* GUI Adaptation - Sept 2000 */
18#include <winuser.h>
19#include <winbase.h>
07d9aa13 20
21#define PUTTY_DO_GLOBALS
22#include "putty.h"
23#include "scp.h"
24
07d9aa13 25#define TIME_POSIX_TO_WIN(t, ft) (*(LONGLONG*)&(ft) = \
c51a56e2 26 ((LONGLONG) (t) + (LONGLONG) 11644473600) * (LONGLONG) 10000000)
07d9aa13 27#define TIME_WIN_TO_POSIX(ft, t) ((t) = (unsigned long) \
c51a56e2 28 ((*(LONGLONG*)&(ft)) / (LONGLONG) 10000000 - (LONGLONG) 11644473600))
07d9aa13 29
cc87246d 30/* GUI Adaptation - Sept 2000 */
31#define WM_APP_BASE 0x8000
32#define WM_STD_OUT_CHAR ( WM_APP_BASE+400 )
33#define WM_STD_ERR_CHAR ( WM_APP_BASE+401 )
34#define WM_STATS_CHAR ( WM_APP_BASE+402 )
35#define WM_STATS_SIZE ( WM_APP_BASE+403 )
36#define WM_STATS_PERCENT ( WM_APP_BASE+404 )
37#define WM_STATS_ELAPSED ( WM_APP_BASE+405 )
38#define WM_RET_ERR_CNT ( WM_APP_BASE+406 )
39#define WM_LS_RET_ERR_CNT ( WM_APP_BASE+407 )
40
fb09bf1c 41static int verbose = 0;
07d9aa13 42static int recursive = 0;
43static int preserve = 0;
44static int targetshouldbedirectory = 0;
45static int statistics = 1;
b8a19193 46static int portnumber = 0;
47static char *password = NULL;
07d9aa13 48static int errs = 0;
49static int connection_open = 0;
cc87246d 50/* GUI Adaptation - Sept 2000 */
51#define NAME_STR_MAX 2048
52static char statname[NAME_STR_MAX+1];
53static unsigned long statsize = 0;
54static int statperct = 0;
55static time_t statelapsed = 0;
56static int gui_mode = 0;
57static char *gui_hwnd = NULL;
07d9aa13 58
59static void source(char *src);
60static void rsource(char *src);
61static void sink(char *targ);
cc87246d 62/* GUI Adaptation - Sept 2000 */
63static void tell_char(FILE *stream, char c);
64static void tell_str(FILE *stream, char *str);
65static void tell_user(FILE *stream, char *fmt, ...);
66static void send_char_msg(unsigned int msg_id, char c);
67static void send_str_msg(unsigned int msg_id, char *str);
68static void gui_update_stats(char *name, unsigned long size, int percentage, time_t elapsed);
07d9aa13 69
07d9aa13 70/*
fb09bf1c 71 * This function is needed to link with ssh.c, but it never gets called.
72 */
73void term_out(void)
74{
75 abort();
76}
77
cc87246d 78/* GUI Adaptation - Sept 2000 */
79void send_msg(HWND h, UINT message, WPARAM wParam)
80{
81 while (!PostMessage( h, message, wParam, 0))
82 SleepEx(1000,TRUE);
83}
84
85void tell_char(FILE *stream, char c)
86{
87 if (!gui_mode)
88 fputc(c, stream);
89 else
90 {
91 unsigned int msg_id = WM_STD_OUT_CHAR;
92 if (stream = stderr) msg_id = WM_STD_ERR_CHAR;
93 send_msg( (HWND)atoi(gui_hwnd), msg_id, (WPARAM)c );
94 }
95}
96
97void tell_str(FILE *stream, char *str)
98{
99 unsigned int i;
100
101 for( i = 0; i < strlen(str); ++i )
102 tell_char(stream, str[i]);
103}
104
105void tell_user(FILE *stream, char *fmt, ...)
106{
107 char str[0x100]; /* Make the size big enough */
108 va_list ap;
109 va_start(ap, fmt);
110 vsprintf(str, fmt, ap);
111 va_end(ap);
112 strcat(str, "\n");
113 tell_str(stream, str);
114}
115
116void gui_update_stats(char *name, unsigned long size, int percentage, time_t elapsed)
117{
118 unsigned int i;
119
120 if (strcmp(name,statname) != 0)
121 {
122 for( i = 0; i < strlen(name); ++i )
123 send_msg( (HWND)atoi(gui_hwnd), WM_STATS_CHAR, (WPARAM)name[i]);
124 send_msg( (HWND)atoi(gui_hwnd), WM_STATS_CHAR, (WPARAM)'\n' );
125 strcpy(statname,name);
126 }
127 if (statsize != size)
128 {
129 send_msg( (HWND)atoi(gui_hwnd), WM_STATS_SIZE, (WPARAM)size );
130 statsize = size;
131 }
132 if (statelapsed != elapsed)
133 {
134 send_msg( (HWND)atoi(gui_hwnd), WM_STATS_ELAPSED, (WPARAM)elapsed );
135 statelapsed = elapsed;
136 }
137 if (statperct != percentage)
138 {
139 send_msg( (HWND)atoi(gui_hwnd), WM_STATS_PERCENT, (WPARAM)percentage );
140 statperct = percentage;
141 }
142}
143
fb09bf1c 144/*
07d9aa13 145 * Print an error message and perform a fatal exit.
146 */
147void fatalbox(char *fmt, ...)
148{
cc87246d 149 char str[0x100]; /* Make the size big enough */
c51a56e2 150 va_list ap;
151 va_start(ap, fmt);
cc87246d 152 strcpy(str, "Fatal:");
153 vsprintf(str+strlen(str), fmt, ap);
c51a56e2 154 va_end(ap);
cc87246d 155 strcat(str, "\n");
156 tell_str(stderr, str);
157
c51a56e2 158 exit(1);
07d9aa13 159}
8d5de777 160void connection_fatal(char *fmt, ...)
161{
162 char str[0x100]; /* Make the size big enough */
163 va_list ap;
164 va_start(ap, fmt);
165 strcpy(str, "Fatal:");
166 vsprintf(str+strlen(str), fmt, ap);
167 va_end(ap);
168 strcat(str, "\n");
169 tell_str(stderr, str);
170
171 exit(1);
172}
07d9aa13 173
07d9aa13 174/*
175 * Print an error message and exit after closing the SSH link.
176 */
177static void bump(char *fmt, ...)
178{
cc87246d 179 char str[0x100]; /* Make the size big enough */
c51a56e2 180 va_list ap;
181 va_start(ap, fmt);
cc87246d 182 strcpy(str, "Fatal:");
183 vsprintf(str+strlen(str), fmt, ap);
c51a56e2 184 va_end(ap);
cc87246d 185 strcat(str, "\n");
186 tell_str(stderr, str);
187
c51a56e2 188 if (connection_open) {
189 char ch;
fb09bf1c 190 ssh_scp_send_eof();
191 ssh_scp_recv(&ch, 1);
c51a56e2 192 }
193 exit(1);
07d9aa13 194}
195
85ee8208 196static int get_password(const char *prompt, char *str, int maxlen)
07d9aa13 197{
c51a56e2 198 HANDLE hin, hout;
b8a19193 199 DWORD savemode, i;
200
201 if (password) {
85ee8208 202 static int tried_once = 0;
203
204 if (tried_once) {
205 return 0;
206 } else {
207 strncpy(str, password, maxlen);
208 str[maxlen-1] = '\0';
209 tried_once = 1;
210 return 1;
211 }
b8a19193 212 }
07d9aa13 213
cc87246d 214 /* GUI Adaptation - Sept 2000 */
215 if (gui_mode) {
216 if (maxlen>0) str[0] = '\0';
217 } else {
218 hin = GetStdHandle(STD_INPUT_HANDLE);
219 hout = GetStdHandle(STD_OUTPUT_HANDLE);
220 if (hin == INVALID_HANDLE_VALUE || hout == INVALID_HANDLE_VALUE)
221 bump("Cannot get standard input/output handles");
07d9aa13 222
cc87246d 223 GetConsoleMode(hin, &savemode);
224 SetConsoleMode(hin, (savemode & (~ENABLE_ECHO_INPUT)) |
225 ENABLE_PROCESSED_INPUT | ENABLE_LINE_INPUT);
07d9aa13 226
cc87246d 227 WriteFile(hout, prompt, strlen(prompt), &i, NULL);
228 ReadFile(hin, str, maxlen-1, &i, NULL);
07d9aa13 229
cc87246d 230 SetConsoleMode(hin, savemode);
07d9aa13 231
cc87246d 232 if ((int)i > maxlen) i = maxlen-1; else i = i - 2;
233 str[i] = '\0';
07d9aa13 234
cc87246d 235 WriteFile(hout, "\r\n", 2, &i, NULL);
236 }
85ee8208 237
238 return 1;
07d9aa13 239}
240
07d9aa13 241/*
242 * Open an SSH connection to user@host and execute cmd.
243 */
244static void do_cmd(char *host, char *user, char *cmd)
245{
c51a56e2 246 char *err, *realhost;
247
248 if (host == NULL || host[0] == '\0')
249 bump("Empty host name");
250
251 /* Try to load settings for this host */
252 do_defaults(host);
253 if (cfg.host[0] == '\0') {
254 /* No settings for this host; use defaults */
255 strncpy(cfg.host, host, sizeof(cfg.host)-1);
256 cfg.host[sizeof(cfg.host)-1] = '\0';
257 cfg.port = 22;
258 }
259
260 /* Set username */
261 if (user != NULL && user[0] != '\0') {
262 strncpy(cfg.username, user, sizeof(cfg.username)-1);
263 cfg.username[sizeof(cfg.username)-1] = '\0';
c51a56e2 264 } else if (cfg.username[0] == '\0') {
265 bump("Empty user name");
266 }
267
268 if (cfg.protocol != PROT_SSH)
269 cfg.port = 22;
270
ed89e8a5 271 if (portnumber)
272 cfg.port = portnumber;
273
fb09bf1c 274 err = ssh_scp_init(cfg.host, cfg.port, cmd, &realhost);
c51a56e2 275 if (err != NULL)
276 bump("ssh_init: %s", err);
277 if (verbose && realhost != NULL)
cc87246d 278 tell_user(stderr, "Connected to %s\n", realhost);
c51a56e2 279
280 connection_open = 1;
07d9aa13 281}
282
07d9aa13 283/*
284 * Update statistic information about current file.
285 */
286static void print_stats(char *name, unsigned long size, unsigned long done,
c51a56e2 287 time_t start, time_t now)
07d9aa13 288{
c51a56e2 289 float ratebs;
290 unsigned long eta;
291 char etastr[10];
292 int pct;
293
cc87246d 294 /* GUI Adaptation - Sept 2000 */
295 if (gui_mode)
296 gui_update_stats(name, size, ((done *100) / size), now-start);
297 else {
298 if (now > start)
299 ratebs = (float) done / (now - start);
300 else
301 ratebs = (float) done;
c51a56e2 302
cc87246d 303 if (ratebs < 1.0)
304 eta = size - done;
305 else
306 eta = (unsigned long) ((size - done) / ratebs);
307 sprintf(etastr, "%02ld:%02ld:%02ld",
308 eta / 3600, (eta % 3600) / 60, eta % 60);
c51a56e2 309
cc87246d 310 pct = (int) (100.0 * (float) done / size);
c51a56e2 311
cc87246d 312 printf("\r%-25.25s | %10ld kB | %5.1f kB/s | ETA: %8s | %3d%%",
313 name, done / 1024, ratebs / 1024.0,
314 etastr, pct);
c51a56e2 315
cc87246d 316 if (done == size)
317 printf("\n");
318 }
07d9aa13 319}
320
07d9aa13 321/*
322 * Find a colon in str and return a pointer to the colon.
39ddf0ff 323 * This is used to separate hostname from filename.
07d9aa13 324 */
325static char * colon(char *str)
326{
c51a56e2 327 /* We ignore a leading colon, since the hostname cannot be
328 empty. We also ignore a colon as second character because
329 of filenames like f:myfile.txt. */
330 if (str[0] == '\0' ||
331 str[0] == ':' ||
332 str[1] == ':')
333 return (NULL);
334 while (*str != '\0' &&
335 *str != ':' &&
336 *str != '/' &&
337 *str != '\\')
338 str++;
339 if (*str == ':')
340 return (str);
341 else
342 return (NULL);
07d9aa13 343}
344
07d9aa13 345/*
346 * Wait for a response from the other side.
347 * Return 0 if ok, -1 if error.
348 */
349static int response(void)
350{
c51a56e2 351 char ch, resp, rbuf[2048];
352 int p;
353
fb09bf1c 354 if (ssh_scp_recv(&resp, 1) <= 0)
c51a56e2 355 bump("Lost connection");
356
357 p = 0;
358 switch (resp) {
359 case 0: /* ok */
360 return (0);
361 default:
362 rbuf[p++] = resp;
363 /* fallthrough */
364 case 1: /* error */
365 case 2: /* fatal error */
366 do {
fb09bf1c 367 if (ssh_scp_recv(&ch, 1) <= 0)
c51a56e2 368 bump("Protocol error: Lost connection");
369 rbuf[p++] = ch;
370 } while (p < sizeof(rbuf) && ch != '\n');
371 rbuf[p-1] = '\0';
372 if (resp == 1)
cc87246d 373 tell_user(stderr, "%s\n", rbuf);
c51a56e2 374 else
375 bump("%s", rbuf);
376 errs++;
377 return (-1);
378 }
07d9aa13 379}
380
07d9aa13 381/*
382 * Send an error message to the other side and to the screen.
383 * Increment error counter.
384 */
385static void run_err(const char *fmt, ...)
386{
c51a56e2 387 char str[2048];
388 va_list ap;
389 va_start(ap, fmt);
390 errs++;
391 strcpy(str, "\01scp: ");
392 vsprintf(str+strlen(str), fmt, ap);
393 strcat(str, "\n");
fb09bf1c 394 ssh_scp_send(str, strlen(str));
cc87246d 395 tell_user(stderr, "%s",str);
c51a56e2 396 va_end(ap);
07d9aa13 397}
398
07d9aa13 399/*
400 * Execute the source part of the SCP protocol.
401 */
402static void source(char *src)
403{
c51a56e2 404 char buf[2048];
405 unsigned long size;
406 char *last;
407 HANDLE f;
408 DWORD attr;
409 unsigned long i;
410 unsigned long stat_bytes;
411 time_t stat_starttime, stat_lasttime;
412
413 attr = GetFileAttributes(src);
996c8c3b 414 if (attr == (DWORD)-1) {
c51a56e2 415 run_err("%s: No such file or directory", src);
416 return;
417 }
418
419 if ((attr & FILE_ATTRIBUTE_DIRECTORY) != 0) {
7f1f80de 420 if (recursive) {
421 /*
422 * Avoid . and .. directories.
423 */
424 char *p;
425 p = strrchr(src, '/');
426 if (!p)
427 p = strrchr(src, '\\');
428 if (!p)
429 p = src;
430 else
431 p++;
432 if (!strcmp(p, ".") || !strcmp(p, ".."))
433 /* skip . and .. */;
434 else
435 rsource(src);
436 } else {
c51a56e2 437 run_err("%s: not a regular file", src);
7f1f80de 438 }
c51a56e2 439 return;
440 }
441
442 if ((last = strrchr(src, '/')) == NULL)
443 last = src;
444 else
445 last++;
446 if (strrchr(last, '\\') != NULL)
447 last = strrchr(last, '\\') + 1;
448 if (last == src && strchr(src, ':') != NULL)
449 last = strchr(src, ':') + 1;
450
451 f = CreateFile(src, GENERIC_READ, FILE_SHARE_READ, NULL,
452 OPEN_EXISTING, 0, 0);
453 if (f == INVALID_HANDLE_VALUE) {
486543a1 454 run_err("%s: Cannot open file", src);
c51a56e2 455 return;
456 }
457
458 if (preserve) {
459 FILETIME actime, wrtime;
460 unsigned long mtime, atime;
461 GetFileTime(f, NULL, &actime, &wrtime);
462 TIME_WIN_TO_POSIX(actime, atime);
463 TIME_WIN_TO_POSIX(wrtime, mtime);
464 sprintf(buf, "T%lu 0 %lu 0\n", mtime, atime);
fb09bf1c 465 ssh_scp_send(buf, strlen(buf));
07d9aa13 466 if (response())
c51a56e2 467 return;
468 }
469
470 size = GetFileSize(f, NULL);
471 sprintf(buf, "C0644 %lu %s\n", size, last);
472 if (verbose)
cc87246d 473 tell_user(stderr, "Sending file modes: %s", buf);
fb09bf1c 474 ssh_scp_send(buf, strlen(buf));
c51a56e2 475 if (response())
476 return;
477
478 if (statistics) {
479 stat_bytes = 0;
480 stat_starttime = time(NULL);
481 stat_lasttime = 0;
482 }
483
484 for (i = 0; i < size; i += 4096) {
485 char transbuf[4096];
486 DWORD j, k = 4096;
487 if (i + k > size) k = size - i;
488 if (! ReadFile(f, transbuf, k, &j, NULL) || j != k) {
489 if (statistics) printf("\n");
490 bump("%s: Read error", src);
07d9aa13 491 }
fb09bf1c 492 ssh_scp_send(transbuf, k);
c51a56e2 493 if (statistics) {
494 stat_bytes += k;
495 if (time(NULL) != stat_lasttime ||
496 i + k == size) {
497 stat_lasttime = time(NULL);
498 print_stats(last, size, stat_bytes,
499 stat_starttime, stat_lasttime);
500 }
07d9aa13 501 }
c51a56e2 502 }
503 CloseHandle(f);
07d9aa13 504
fb09bf1c 505 ssh_scp_send("", 1);
c51a56e2 506 (void) response();
07d9aa13 507}
508
07d9aa13 509/*
510 * Recursively send the contents of a directory.
511 */
512static void rsource(char *src)
513{
c51a56e2 514 char buf[2048];
515 char *last;
516 HANDLE dir;
517 WIN32_FIND_DATA fdat;
518 int ok;
519
520 if ((last = strrchr(src, '/')) == NULL)
521 last = src;
522 else
523 last++;
524 if (strrchr(last, '\\') != NULL)
525 last = strrchr(last, '\\') + 1;
526 if (last == src && strchr(src, ':') != NULL)
527 last = strchr(src, ':') + 1;
528
529 /* maybe send filetime */
530
531 sprintf(buf, "D0755 0 %s\n", last);
532 if (verbose)
cc87246d 533 tell_user(stderr, "Entering directory: %s", buf);
fb09bf1c 534 ssh_scp_send(buf, strlen(buf));
c51a56e2 535 if (response())
536 return;
537
538 sprintf(buf, "%s/*", src);
539 dir = FindFirstFile(buf, &fdat);
540 ok = (dir != INVALID_HANDLE_VALUE);
541 while (ok) {
542 if (strcmp(fdat.cFileName, ".") == 0 ||
543 strcmp(fdat.cFileName, "..") == 0) {
544 } else if (strlen(src) + 1 + strlen(fdat.cFileName) >=
545 sizeof(buf)) {
546 run_err("%s/%s: Name too long", src, fdat.cFileName);
547 } else {
548 sprintf(buf, "%s/%s", src, fdat.cFileName);
549 source(buf);
07d9aa13 550 }
c51a56e2 551 ok = FindNextFile(dir, &fdat);
552 }
553 FindClose(dir);
07d9aa13 554
c51a56e2 555 sprintf(buf, "E\n");
fb09bf1c 556 ssh_scp_send(buf, strlen(buf));
c51a56e2 557 (void) response();
07d9aa13 558}
559
07d9aa13 560/*
561 * Execute the sink part of the SCP protocol.
562 */
563static void sink(char *targ)
564{
c51a56e2 565 char buf[2048];
566 char namebuf[2048];
567 char ch;
568 int targisdir = 0;
996c8c3b 569 int settime;
c51a56e2 570 int exists;
571 DWORD attr;
572 HANDLE f;
573 unsigned long mtime, atime;
574 unsigned int mode;
575 unsigned long size, i;
576 int wrerror = 0;
577 unsigned long stat_bytes;
578 time_t stat_starttime, stat_lasttime;
579 char *stat_name;
580
581 attr = GetFileAttributes(targ);
996c8c3b 582 if (attr != (DWORD)-1 && (attr & FILE_ATTRIBUTE_DIRECTORY) != 0)
c51a56e2 583 targisdir = 1;
584
585 if (targetshouldbedirectory && !targisdir)
586 bump("%s: Not a directory", targ);
587
fb09bf1c 588 ssh_scp_send("", 1);
c51a56e2 589 while (1) {
590 settime = 0;
591 gottime:
fb09bf1c 592 if (ssh_scp_recv(&ch, 1) <= 0)
c51a56e2 593 return;
594 if (ch == '\n')
595 bump("Protocol error: Unexpected newline");
596 i = 0;
597 buf[i++] = ch;
598 do {
fb09bf1c 599 if (ssh_scp_recv(&ch, 1) <= 0)
c51a56e2 600 bump("Lost connection");
601 buf[i++] = ch;
602 } while (i < sizeof(buf) && ch != '\n');
603 buf[i-1] = '\0';
604 switch (buf[0]) {
605 case '\01': /* error */
cc87246d 606 tell_user(stderr, "%s\n", buf+1);
c51a56e2 607 errs++;
608 continue;
609 case '\02': /* fatal error */
610 bump("%s", buf+1);
611 case 'E':
fb09bf1c 612 ssh_scp_send("", 1);
c51a56e2 613 return;
614 case 'T':
1d470ad2 615 if (sscanf(buf, "T%ld %*d %ld %*d",
c51a56e2 616 &mtime, &atime) == 2) {
617 settime = 1;
fb09bf1c 618 ssh_scp_send("", 1);
c51a56e2 619 goto gottime;
620 }
621 bump("Protocol error: Illegal time format");
622 case 'C':
623 case 'D':
624 break;
625 default:
626 bump("Protocol error: Expected control record");
627 }
07d9aa13 628
1d470ad2 629 if (sscanf(buf+1, "%u %lu %[^\n]", &mode, &size, namebuf) != 3)
c51a56e2 630 bump("Protocol error: Illegal file descriptor format");
631 if (targisdir) {
632 char t[2048];
633 strcpy(t, targ);
634 if (targ[0] != '\0')
635 strcat(t, "/");
636 strcat(t, namebuf);
637 strcpy(namebuf, t);
638 } else {
639 strcpy(namebuf, targ);
640 }
641 attr = GetFileAttributes(namebuf);
996c8c3b 642 exists = (attr != (DWORD)-1);
c51a56e2 643
644 if (buf[0] == 'D') {
645 if (exists && (attr & FILE_ATTRIBUTE_DIRECTORY) == 0) {
646 run_err("%s: Not a directory", namebuf);
647 continue;
648 }
649 if (!exists) {
650 if (! CreateDirectory(namebuf, NULL)) {
651 run_err("%s: Cannot create directory",
652 namebuf);
653 continue;
654 }
655 }
656 sink(namebuf);
657 /* can we set the timestamp for directories ? */
658 continue;
659 }
07d9aa13 660
c51a56e2 661 f = CreateFile(namebuf, GENERIC_WRITE, 0, NULL,
662 CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
663 if (f == INVALID_HANDLE_VALUE) {
664 run_err("%s: Cannot create file", namebuf);
665 continue;
666 }
07d9aa13 667
fb09bf1c 668 ssh_scp_send("", 1);
07d9aa13 669
c51a56e2 670 if (statistics) {
671 stat_bytes = 0;
672 stat_starttime = time(NULL);
673 stat_lasttime = 0;
674 if ((stat_name = strrchr(namebuf, '/')) == NULL)
675 stat_name = namebuf;
676 else
677 stat_name++;
678 if (strrchr(stat_name, '\\') != NULL)
679 stat_name = strrchr(stat_name, '\\') + 1;
680 }
07d9aa13 681
c51a56e2 682 for (i = 0; i < size; i += 4096) {
683 char transbuf[4096];
996c8c3b 684 DWORD j, k = 4096;
c51a56e2 685 if (i + k > size) k = size - i;
fb09bf1c 686 if (ssh_scp_recv(transbuf, k) == 0)
c51a56e2 687 bump("Lost connection");
688 if (wrerror) continue;
689 if (! WriteFile(f, transbuf, k, &j, NULL) || j != k) {
690 wrerror = 1;
691 if (statistics)
692 printf("\r%-25.25s | %50s\n",
693 stat_name,
694 "Write error.. waiting for end of file");
695 continue;
696 }
697 if (statistics) {
698 stat_bytes += k;
699 if (time(NULL) > stat_lasttime ||
700 i + k == size) {
701 stat_lasttime = time(NULL);
702 print_stats(stat_name, size, stat_bytes,
703 stat_starttime, stat_lasttime);
07d9aa13 704 }
c51a56e2 705 }
706 }
707 (void) response();
07d9aa13 708
c51a56e2 709 if (settime) {
710 FILETIME actime, wrtime;
711 TIME_POSIX_TO_WIN(atime, actime);
712 TIME_POSIX_TO_WIN(mtime, wrtime);
713 SetFileTime(f, NULL, &actime, &wrtime);
07d9aa13 714 }
07d9aa13 715
c51a56e2 716 CloseHandle(f);
717 if (wrerror) {
718 run_err("%s: Write error", namebuf);
719 continue;
720 }
fb09bf1c 721 ssh_scp_send("", 1);
c51a56e2 722 }
723}
07d9aa13 724
725/*
726 * We will copy local files to a remote server.
727 */
728static void toremote(int argc, char *argv[])
729{
c51a56e2 730 char *src, *targ, *host, *user;
731 char *cmd;
732 int i;
733
734 targ = argv[argc-1];
735
39ddf0ff 736 /* Separate host from filename */
c51a56e2 737 host = targ;
738 targ = colon(targ);
739 if (targ == NULL)
740 bump("targ == NULL in toremote()");
741 *targ++ = '\0';
742 if (*targ == '\0')
743 targ = ".";
744 /* Substitute "." for emtpy target */
745
39ddf0ff 746 /* Separate host and username */
c51a56e2 747 user = host;
748 host = strrchr(host, '@');
749 if (host == NULL) {
750 host = user;
751 user = NULL;
752 } else {
753 *host++ = '\0';
754 if (*user == '\0')
755 user = NULL;
756 }
757
758 if (argc == 2) {
759 /* Find out if the source filespec covers multiple files
760 if so, we should set the targetshouldbedirectory flag */
761 HANDLE fh;
762 WIN32_FIND_DATA fdat;
763 if (colon(argv[0]) != NULL)
764 bump("%s: Remote to remote not supported", argv[0]);
765 fh = FindFirstFile(argv[0], &fdat);
766 if (fh == INVALID_HANDLE_VALUE)
767 bump("%s: No such file or directory\n", argv[0]);
768 if (FindNextFile(fh, &fdat))
769 targetshouldbedirectory = 1;
770 FindClose(fh);
771 }
772
773 cmd = smalloc(strlen(targ) + 100);
774 sprintf(cmd, "scp%s%s%s%s -t %s",
775 verbose ? " -v" : "",
776 recursive ? " -r" : "",
777 preserve ? " -p" : "",
778 targetshouldbedirectory ? " -d" : "",
779 targ);
780 do_cmd(host, user, cmd);
781 sfree(cmd);
782
783 (void) response();
784
785 for (i = 0; i < argc - 1; i++) {
786 HANDLE dir;
787 WIN32_FIND_DATA fdat;
788 src = argv[i];
789 if (colon(src) != NULL) {
cc87246d 790 tell_user(stderr, "%s: Remote to remote not supported\n", src);
c51a56e2 791 errs++;
792 continue;
07d9aa13 793 }
c51a56e2 794 dir = FindFirstFile(src, &fdat);
795 if (dir == INVALID_HANDLE_VALUE) {
796 run_err("%s: No such file or directory", src);
797 continue;
07d9aa13 798 }
c51a56e2 799 do {
800 char *last;
801 char namebuf[2048];
802 if (strlen(src) + strlen(fdat.cFileName) >=
803 sizeof(namebuf)) {
cc87246d 804 tell_user(stderr, "%s: Name too long", src);
c51a56e2 805 continue;
806 }
807 strcpy(namebuf, src);
808 if ((last = strrchr(namebuf, '/')) == NULL)
809 last = namebuf;
810 else
811 last++;
812 if (strrchr(last, '\\') != NULL)
813 last = strrchr(last, '\\') + 1;
814 if (last == namebuf && strrchr(namebuf, ':') != NULL)
815 last = strchr(namebuf, ':') + 1;
816 strcpy(last, fdat.cFileName);
817 source(namebuf);
818 } while (FindNextFile(dir, &fdat));
819 FindClose(dir);
820 }
07d9aa13 821}
822
07d9aa13 823/*
824 * We will copy files from a remote server to the local machine.
825 */
826static void tolocal(int argc, char *argv[])
827{
c51a56e2 828 char *src, *targ, *host, *user;
829 char *cmd;
830
831 if (argc != 2)
832 bump("More than one remote source not supported");
833
834 src = argv[0];
835 targ = argv[1];
836
39ddf0ff 837 /* Separate host from filename */
c51a56e2 838 host = src;
839 src = colon(src);
840 if (src == NULL)
841 bump("Local to local copy not supported");
842 *src++ = '\0';
843 if (*src == '\0')
844 src = ".";
845 /* Substitute "." for empty filename */
846
39ddf0ff 847 /* Separate username and hostname */
c51a56e2 848 user = host;
849 host = strrchr(host, '@');
850 if (host == NULL) {
851 host = user;
852 user = NULL;
853 } else {
854 *host++ = '\0';
855 if (*user == '\0')
856 user = NULL;
857 }
858
859 cmd = smalloc(strlen(src) + 100);
860 sprintf(cmd, "scp%s%s%s%s -f %s",
861 verbose ? " -v" : "",
862 recursive ? " -r" : "",
863 preserve ? " -p" : "",
864 targetshouldbedirectory ? " -d" : "",
865 src);
866 do_cmd(host, user, cmd);
867 sfree(cmd);
868
869 sink(targ);
07d9aa13 870}
871
07d9aa13 872/*
39ddf0ff 873 * We will issue a list command to get a remote directory.
874 */
875static void get_dir_list(int argc, char *argv[])
876{
877 char *src, *host, *user;
878 char *cmd, *p, *q;
879 char c;
880
881 src = argv[0];
882
883 /* Separate host from filename */
884 host = src;
885 src = colon(src);
886 if (src == NULL)
887 bump("Local to local copy not supported");
888 *src++ = '\0';
889 if (*src == '\0')
890 src = ".";
891 /* Substitute "." for empty filename */
892
893 /* Separate username and hostname */
894 user = host;
895 host = strrchr(host, '@');
896 if (host == NULL) {
897 host = user;
898 user = NULL;
899 } else {
900 *host++ = '\0';
901 if (*user == '\0')
902 user = NULL;
903 }
904
905 cmd = smalloc(4*strlen(src) + 100);
906 strcpy(cmd, "ls -la '");
907 p = cmd + strlen(cmd);
908 for (q = src; *q; q++) {
909 if (*q == '\'') {
910 *p++ = '\''; *p++ = '\\'; *p++ = '\''; *p++ = '\'';
911 } else {
912 *p++ = *q;
913 }
914 }
915 *p++ = '\'';
916 *p = '\0';
cc87246d 917
39ddf0ff 918 do_cmd(host, user, cmd);
919 sfree(cmd);
920
fb09bf1c 921 while (ssh_scp_recv(&c, 1) > 0)
cc87246d 922 tell_char(stdout, c);
39ddf0ff 923}
924
925/*
07d9aa13 926 * Initialize the Win$ock driver.
927 */
996c8c3b 928static void init_winsock(void)
07d9aa13 929{
c51a56e2 930 WORD winsock_ver;
931 WSADATA wsadata;
932
933 winsock_ver = MAKEWORD(1, 1);
934 if (WSAStartup(winsock_ver, &wsadata))
935 bump("Unable to initialise WinSock");
936 if (LOBYTE(wsadata.wVersion) != 1 ||
937 HIBYTE(wsadata.wVersion) != 1)
938 bump("WinSock version is incompatible with 1.1");
07d9aa13 939}
940
07d9aa13 941/*
942 * Short description of parameters.
943 */
996c8c3b 944static void usage(void)
07d9aa13 945{
c51a56e2 946 printf("PuTTY Secure Copy client\n");
947 printf("%s\n", ver);
a3e55ea1 948 printf("Usage: pscp [options] [user@]host:source target\n");
949 printf(" pscp [options] source [source...] [user@]host:target\n");
950 printf(" pscp [options] -ls user@host:filespec\n");
b8a19193 951 printf("Options:\n");
952 printf(" -p preserve file attributes\n");
953 printf(" -q quiet, don't show statistics\n");
954 printf(" -r copy directories recursively\n");
955 printf(" -v show verbose messages\n");
956 printf(" -P port connect to specified port\n");
957 printf(" -pw passw login with specified password\n");
cc87246d 958 /* GUI Adaptation - Sept 2000 */
959 printf(" -gui hWnd GUI mode with the windows handle for receiving messages\n");
c51a56e2 960 exit(1);
07d9aa13 961}
962
07d9aa13 963/*
964 * Main program (no, really?)
965 */
966int main(int argc, char *argv[])
967{
c51a56e2 968 int i;
39ddf0ff 969 int list = 0;
c51a56e2 970
fb09bf1c 971 default_protocol = PROT_TELNET;
972
67779be7 973 flags = FLAG_STDERR;
fb09bf1c 974 ssh_get_password = &get_password;
c51a56e2 975 init_winsock();
976
977 for (i = 1; i < argc; i++) {
978 if (argv[i][0] != '-')
979 break;
980 if (strcmp(argv[i], "-v") == 0)
4017be6d 981 verbose = 1, flags |= FLAG_VERBOSE;
c51a56e2 982 else if (strcmp(argv[i], "-r") == 0)
983 recursive = 1;
984 else if (strcmp(argv[i], "-p") == 0)
985 preserve = 1;
986 else if (strcmp(argv[i], "-q") == 0)
987 statistics = 0;
988 else if (strcmp(argv[i], "-h") == 0 ||
989 strcmp(argv[i], "-?") == 0)
990 usage();
b8a19193 991 else if (strcmp(argv[i], "-P") == 0 && i+1 < argc)
992 portnumber = atoi(argv[++i]);
993 else if (strcmp(argv[i], "-pw") == 0 && i+1 < argc)
994 password = argv[++i];
cc87246d 995 else if (strcmp(argv[i], "-gui") == 0 && i+1 < argc) {
996 gui_hwnd = argv[++i];
997 gui_mode = 1;
998 } else if (strcmp(argv[i], "-ls") == 0)
999 list = 1;
c51a56e2 1000 else if (strcmp(argv[i], "--") == 0)
1001 { i++; break; }
07d9aa13 1002 else
c51a56e2 1003 usage();
1004 }
1005 argc -= i;
1006 argv += i;
1007
39ddf0ff 1008 if (list) {
1009 if (argc != 1)
1010 usage();
1011 get_dir_list(argc, argv);
c51a56e2 1012
39ddf0ff 1013 } else {
1014
1015 if (argc < 2)
1016 usage();
1017 if (argc > 2)
1018 targetshouldbedirectory = 1;
1019
1020 if (colon(argv[argc-1]) != NULL)
1021 toremote(argc, argv);
1022 else
1023 tolocal(argc, argv);
1024 }
c51a56e2 1025
1026 if (connection_open) {
1027 char ch;
fb09bf1c 1028 ssh_scp_send_eof();
1029 ssh_scp_recv(&ch, 1);
c51a56e2 1030 }
1031 WSACleanup();
1032 random_save_seed();
07d9aa13 1033
cc87246d 1034 /* GUI Adaptation - August 2000 */
1035 if (gui_mode) {
1036 unsigned int msg_id = WM_RET_ERR_CNT;
1037 if (list) msg_id = WM_LS_RET_ERR_CNT;
1038 while (!PostMessage( (HWND)atoi(gui_hwnd), msg_id, (WPARAM)errs, 0/*lParam*/ ) )
1039 SleepEx(1000,TRUE);
1040 }
c51a56e2 1041 return (errs == 0 ? 0 : 1);
07d9aa13 1042}
1043
1044/* end */