Enable better build-time flexibility over which WinSock to include
[u/mdw/putty] / scp.c
1 /*
2 * scp.c - Scp (Secure Copy) client for PuTTY.
3 * Joris van Rantwijk, Simon Tatham
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.
7 *
8 * Adaptations to enable connecting a GUI by L. Gunnarsson - Sept 2000
9 */
10
11 #include <windows.h>
12 #ifndef AUTO_WINSOCK
13 #ifdef WINSOCK_TWO
14 #include <winsock2.h>
15 #else
16 #include <winsock.h>
17 #endif
18 #endif
19 #include <stdlib.h>
20 #include <stdio.h>
21 #include <string.h>
22 #include <time.h>
23 /* GUI Adaptation - Sept 2000 */
24 #include <winuser.h>
25 #include <winbase.h>
26
27 #define PUTTY_DO_GLOBALS
28 #include "putty.h"
29 #include "scp.h"
30
31 #define TIME_POSIX_TO_WIN(t, ft) (*(LONGLONG*)&(ft) = \
32 ((LONGLONG) (t) + (LONGLONG) 11644473600) * (LONGLONG) 10000000)
33 #define TIME_WIN_TO_POSIX(ft, t) ((t) = (unsigned long) \
34 ((*(LONGLONG*)&(ft)) / (LONGLONG) 10000000 - (LONGLONG) 11644473600))
35
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
47 static int verbose = 0;
48 static int recursive = 0;
49 static int preserve = 0;
50 static int targetshouldbedirectory = 0;
51 static int statistics = 1;
52 static int portnumber = 0;
53 static char *password = NULL;
54 static int errs = 0;
55 static int connection_open = 0;
56 /* GUI Adaptation - Sept 2000 */
57 #define NAME_STR_MAX 2048
58 static char statname[NAME_STR_MAX+1];
59 static unsigned long statsize = 0;
60 static int statperct = 0;
61 static time_t statelapsed = 0;
62 static int gui_mode = 0;
63 static char *gui_hwnd = NULL;
64
65 static void source(char *src);
66 static void rsource(char *src);
67 static void sink(char *targ);
68 /* GUI Adaptation - Sept 2000 */
69 static void tell_char(FILE *stream, char c);
70 static void tell_str(FILE *stream, char *str);
71 static void tell_user(FILE *stream, char *fmt, ...);
72 static void send_char_msg(unsigned int msg_id, char c);
73 static void send_str_msg(unsigned int msg_id, char *str);
74 static void gui_update_stats(char *name, unsigned long size, int percentage, time_t elapsed);
75
76 /*
77 * These functions are needed to link with ssh.c, but never get called.
78 */
79 void term_out(void)
80 {
81 abort();
82 }
83 void begin_session(void) {
84 }
85
86 /* GUI Adaptation - Sept 2000 */
87 void send_msg(HWND h, UINT message, WPARAM wParam)
88 {
89 while (!PostMessage( h, message, wParam, 0))
90 SleepEx(1000,TRUE);
91 }
92
93 void 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
105 void 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
113 void 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
124 void 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
152 /*
153 * Print an error message and perform a fatal exit.
154 */
155 void fatalbox(char *fmt, ...)
156 {
157 char str[0x100]; /* Make the size big enough */
158 va_list ap;
159 va_start(ap, fmt);
160 strcpy(str, "Fatal:");
161 vsprintf(str+strlen(str), fmt, ap);
162 va_end(ap);
163 strcat(str, "\n");
164 tell_str(stderr, str);
165
166 exit(1);
167 }
168 void 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 }
181
182 /*
183 * Print an error message and exit after closing the SSH link.
184 */
185 static void bump(char *fmt, ...)
186 {
187 char str[0x100]; /* Make the size big enough */
188 va_list ap;
189 va_start(ap, fmt);
190 strcpy(str, "Fatal:");
191 vsprintf(str+strlen(str), fmt, ap);
192 va_end(ap);
193 strcat(str, "\n");
194 tell_str(stderr, str);
195
196 if (connection_open) {
197 char ch;
198 ssh_scp_send_eof();
199 ssh_scp_recv(&ch, 1);
200 }
201 exit(1);
202 }
203
204 static int get_password(const char *prompt, char *str, int maxlen)
205 {
206 HANDLE hin, hout;
207 DWORD savemode, i;
208
209 if (password) {
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 }
220 }
221
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");
230
231 GetConsoleMode(hin, &savemode);
232 SetConsoleMode(hin, (savemode & (~ENABLE_ECHO_INPUT)) |
233 ENABLE_PROCESSED_INPUT | ENABLE_LINE_INPUT);
234
235 WriteFile(hout, prompt, strlen(prompt), &i, NULL);
236 ReadFile(hin, str, maxlen-1, &i, NULL);
237
238 SetConsoleMode(hin, savemode);
239
240 if ((int)i > maxlen) i = maxlen-1; else i = i - 2;
241 str[i] = '\0';
242
243 WriteFile(hout, "\r\n", 2, &i, NULL);
244 }
245
246 return 1;
247 }
248
249 /*
250 * Open an SSH connection to user@host and execute cmd.
251 */
252 static void do_cmd(char *host, char *user, char *cmd)
253 {
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';
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
279 if (portnumber)
280 cfg.port = portnumber;
281
282 err = ssh_scp_init(cfg.host, cfg.port, cmd, &realhost);
283 if (err != NULL)
284 bump("ssh_init: %s", err);
285 if (verbose && realhost != NULL)
286 tell_user(stderr, "Connected to %s\n", realhost);
287
288 connection_open = 1;
289 }
290
291 /*
292 * Update statistic information about current file.
293 */
294 static void print_stats(char *name, unsigned long size, unsigned long done,
295 time_t start, time_t now)
296 {
297 float ratebs;
298 unsigned long eta;
299 char etastr[10];
300 int pct;
301
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;
310
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);
317
318 pct = (int) (100.0 * (float) done / size);
319
320 printf("\r%-25.25s | %10ld kB | %5.1f kB/s | ETA: %8s | %3d%%",
321 name, done / 1024, ratebs / 1024.0,
322 etastr, pct);
323
324 if (done == size)
325 printf("\n");
326 }
327 }
328
329 /*
330 * Find a colon in str and return a pointer to the colon.
331 * This is used to separate hostname from filename.
332 */
333 static char * colon(char *str)
334 {
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);
351 }
352
353 /*
354 * Wait for a response from the other side.
355 * Return 0 if ok, -1 if error.
356 */
357 static int response(void)
358 {
359 char ch, resp, rbuf[2048];
360 int p;
361
362 if (ssh_scp_recv(&resp, 1) <= 0)
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 {
375 if (ssh_scp_recv(&ch, 1) <= 0)
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)
381 tell_user(stderr, "%s\n", rbuf);
382 else
383 bump("%s", rbuf);
384 errs++;
385 return (-1);
386 }
387 }
388
389 /*
390 * Send an error message to the other side and to the screen.
391 * Increment error counter.
392 */
393 static void run_err(const char *fmt, ...)
394 {
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");
402 ssh_scp_send(str, strlen(str));
403 tell_user(stderr, "%s",str);
404 va_end(ap);
405 }
406
407 /*
408 * Execute the source part of the SCP protocol.
409 */
410 static void source(char *src)
411 {
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);
422 if (attr == (DWORD)-1) {
423 run_err("%s: No such file or directory", src);
424 return;
425 }
426
427 if ((attr & FILE_ATTRIBUTE_DIRECTORY) != 0) {
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 {
445 run_err("%s: not a regular file", src);
446 }
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) {
462 run_err("%s: Cannot open file", src);
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);
473 ssh_scp_send(buf, strlen(buf));
474 if (response())
475 return;
476 }
477
478 size = GetFileSize(f, NULL);
479 sprintf(buf, "C0644 %lu %s\n", size, last);
480 if (verbose)
481 tell_user(stderr, "Sending file modes: %s", buf);
482 ssh_scp_send(buf, strlen(buf));
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);
499 }
500 ssh_scp_send(transbuf, k);
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 }
509 }
510 }
511 CloseHandle(f);
512
513 ssh_scp_send("", 1);
514 (void) response();
515 }
516
517 /*
518 * Recursively send the contents of a directory.
519 */
520 static void rsource(char *src)
521 {
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)
541 tell_user(stderr, "Entering directory: %s", buf);
542 ssh_scp_send(buf, strlen(buf));
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);
558 }
559 ok = FindNextFile(dir, &fdat);
560 }
561 FindClose(dir);
562
563 sprintf(buf, "E\n");
564 ssh_scp_send(buf, strlen(buf));
565 (void) response();
566 }
567
568 /*
569 * Execute the sink part of the SCP protocol.
570 */
571 static void sink(char *targ)
572 {
573 char buf[2048];
574 char namebuf[2048];
575 char ch;
576 int targisdir = 0;
577 int settime;
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);
590 if (attr != (DWORD)-1 && (attr & FILE_ATTRIBUTE_DIRECTORY) != 0)
591 targisdir = 1;
592
593 if (targetshouldbedirectory && !targisdir)
594 bump("%s: Not a directory", targ);
595
596 ssh_scp_send("", 1);
597 while (1) {
598 settime = 0;
599 gottime:
600 if (ssh_scp_recv(&ch, 1) <= 0)
601 return;
602 if (ch == '\n')
603 bump("Protocol error: Unexpected newline");
604 i = 0;
605 buf[i++] = ch;
606 do {
607 if (ssh_scp_recv(&ch, 1) <= 0)
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 */
614 tell_user(stderr, "%s\n", buf+1);
615 errs++;
616 continue;
617 case '\02': /* fatal error */
618 bump("%s", buf+1);
619 case 'E':
620 ssh_scp_send("", 1);
621 return;
622 case 'T':
623 if (sscanf(buf, "T%ld %*d %ld %*d",
624 &mtime, &atime) == 2) {
625 settime = 1;
626 ssh_scp_send("", 1);
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 }
636
637 if (sscanf(buf+1, "%u %lu %[^\n]", &mode, &size, namebuf) != 3)
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);
650 exists = (attr != (DWORD)-1);
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 }
668
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 }
675
676 ssh_scp_send("", 1);
677
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 }
689
690 for (i = 0; i < size; i += 4096) {
691 char transbuf[4096];
692 DWORD j, k = 4096;
693 if (i + k > size) k = size - i;
694 if (ssh_scp_recv(transbuf, k) == 0)
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);
712 }
713 }
714 }
715 (void) response();
716
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);
722 }
723
724 CloseHandle(f);
725 if (wrerror) {
726 run_err("%s: Write error", namebuf);
727 continue;
728 }
729 ssh_scp_send("", 1);
730 }
731 }
732
733 /*
734 * We will copy local files to a remote server.
735 */
736 static void toremote(int argc, char *argv[])
737 {
738 char *src, *targ, *host, *user;
739 char *cmd;
740 int i;
741
742 targ = argv[argc-1];
743
744 /* Separate host from filename */
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
754 /* Separate host and username */
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) {
798 tell_user(stderr, "%s: Remote to remote not supported\n", src);
799 errs++;
800 continue;
801 }
802 dir = FindFirstFile(src, &fdat);
803 if (dir == INVALID_HANDLE_VALUE) {
804 run_err("%s: No such file or directory", src);
805 continue;
806 }
807 do {
808 char *last;
809 char namebuf[2048];
810 if (strlen(src) + strlen(fdat.cFileName) >=
811 sizeof(namebuf)) {
812 tell_user(stderr, "%s: Name too long", src);
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 }
829 }
830
831 /*
832 * We will copy files from a remote server to the local machine.
833 */
834 static void tolocal(int argc, char *argv[])
835 {
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
845 /* Separate host from filename */
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
855 /* Separate username and hostname */
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);
878 }
879
880 /*
881 * We will issue a list command to get a remote directory.
882 */
883 static 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';
925
926 do_cmd(host, user, cmd);
927 sfree(cmd);
928
929 while (ssh_scp_recv(&c, 1) > 0)
930 tell_char(stdout, c);
931 }
932
933 /*
934 * Initialize the Win$ock driver.
935 */
936 static void init_winsock(void)
937 {
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");
947 }
948
949 /*
950 * Short description of parameters.
951 */
952 static void usage(void)
953 {
954 printf("PuTTY Secure Copy client\n");
955 printf("%s\n", ver);
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");
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");
966 /* GUI Adaptation - Sept 2000 */
967 printf(" -gui hWnd GUI mode with the windows handle for receiving messages\n");
968 exit(1);
969 }
970
971 /*
972 * Main program (no, really?)
973 */
974 int main(int argc, char *argv[])
975 {
976 int i;
977 int list = 0;
978
979 default_protocol = PROT_TELNET;
980
981 flags = FLAG_STDERR;
982 ssh_get_password = &get_password;
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)
989 verbose = 1, flags |= FLAG_VERBOSE;
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();
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];
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;
1008 else if (strcmp(argv[i], "--") == 0)
1009 { i++; break; }
1010 else
1011 usage();
1012 }
1013 argc -= i;
1014 argv += i;
1015
1016 if (list) {
1017 if (argc != 1)
1018 usage();
1019 get_dir_list(argc, argv);
1020
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 }
1033
1034 if (connection_open) {
1035 char ch;
1036 ssh_scp_send_eof();
1037 ssh_scp_recv(&ch, 1);
1038 }
1039 WSACleanup();
1040 random_save_seed();
1041
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 }
1049 return (errs == 0 ? 0 : 1);
1050 }
1051
1052 /* end */