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