Prevent network errors from summarily closing the window when CoE is off
[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 #include <winsock.h>
13 #include <stdlib.h>
14 #include <stdio.h>
15 #include <string.h>
16 #include <time.h>
17 /* GUI Adaptation - Sept 2000 */
18 #include <winuser.h>
19 #include <winbase.h>
20
21 #define PUTTY_DO_GLOBALS
22 #include "putty.h"
23 #include "scp.h"
24
25 #define TIME_POSIX_TO_WIN(t, ft) (*(LONGLONG*)&(ft) = \
26 ((LONGLONG) (t) + (LONGLONG) 11644473600) * (LONGLONG) 10000000)
27 #define TIME_WIN_TO_POSIX(ft, t) ((t) = (unsigned long) \
28 ((*(LONGLONG*)&(ft)) / (LONGLONG) 10000000 - (LONGLONG) 11644473600))
29
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
41 static int verbose = 0;
42 static int recursive = 0;
43 static int preserve = 0;
44 static int targetshouldbedirectory = 0;
45 static int statistics = 1;
46 static int portnumber = 0;
47 static char *password = NULL;
48 static int errs = 0;
49 static int connection_open = 0;
50 /* GUI Adaptation - Sept 2000 */
51 #define NAME_STR_MAX 2048
52 static char statname[NAME_STR_MAX+1];
53 static unsigned long statsize = 0;
54 static int statperct = 0;
55 static time_t statelapsed = 0;
56 static int gui_mode = 0;
57 static char *gui_hwnd = NULL;
58
59 static void source(char *src);
60 static void rsource(char *src);
61 static void sink(char *targ);
62 /* GUI Adaptation - Sept 2000 */
63 static void tell_char(FILE *stream, char c);
64 static void tell_str(FILE *stream, char *str);
65 static void tell_user(FILE *stream, char *fmt, ...);
66 static void send_char_msg(unsigned int msg_id, char c);
67 static void send_str_msg(unsigned int msg_id, char *str);
68 static void gui_update_stats(char *name, unsigned long size, int percentage, time_t elapsed);
69
70 /*
71 * This function is needed to link with ssh.c, but it never gets called.
72 */
73 void term_out(void)
74 {
75 abort();
76 }
77
78 /* GUI Adaptation - Sept 2000 */
79 void send_msg(HWND h, UINT message, WPARAM wParam)
80 {
81 while (!PostMessage( h, message, wParam, 0))
82 SleepEx(1000,TRUE);
83 }
84
85 void 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
97 void 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
105 void 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
116 void 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
144 /*
145 * Print an error message and perform a fatal exit.
146 */
147 void fatalbox(char *fmt, ...)
148 {
149 char str[0x100]; /* Make the size big enough */
150 va_list ap;
151 va_start(ap, fmt);
152 strcpy(str, "Fatal:");
153 vsprintf(str+strlen(str), fmt, ap);
154 va_end(ap);
155 strcat(str, "\n");
156 tell_str(stderr, str);
157
158 exit(1);
159 }
160 void 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 }
173
174 /*
175 * Print an error message and exit after closing the SSH link.
176 */
177 static void bump(char *fmt, ...)
178 {
179 char str[0x100]; /* Make the size big enough */
180 va_list ap;
181 va_start(ap, fmt);
182 strcpy(str, "Fatal:");
183 vsprintf(str+strlen(str), fmt, ap);
184 va_end(ap);
185 strcat(str, "\n");
186 tell_str(stderr, str);
187
188 if (connection_open) {
189 char ch;
190 ssh_scp_send_eof();
191 ssh_scp_recv(&ch, 1);
192 }
193 exit(1);
194 }
195
196 static int get_password(const char *prompt, char *str, int maxlen)
197 {
198 HANDLE hin, hout;
199 DWORD savemode, i;
200
201 if (password) {
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 }
212 }
213
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");
222
223 GetConsoleMode(hin, &savemode);
224 SetConsoleMode(hin, (savemode & (~ENABLE_ECHO_INPUT)) |
225 ENABLE_PROCESSED_INPUT | ENABLE_LINE_INPUT);
226
227 WriteFile(hout, prompt, strlen(prompt), &i, NULL);
228 ReadFile(hin, str, maxlen-1, &i, NULL);
229
230 SetConsoleMode(hin, savemode);
231
232 if ((int)i > maxlen) i = maxlen-1; else i = i - 2;
233 str[i] = '\0';
234
235 WriteFile(hout, "\r\n", 2, &i, NULL);
236 }
237
238 return 1;
239 }
240
241 /*
242 * Open an SSH connection to user@host and execute cmd.
243 */
244 static void do_cmd(char *host, char *user, char *cmd)
245 {
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';
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
271 if (portnumber)
272 cfg.port = portnumber;
273
274 err = ssh_scp_init(cfg.host, cfg.port, cmd, &realhost);
275 if (err != NULL)
276 bump("ssh_init: %s", err);
277 if (verbose && realhost != NULL)
278 tell_user(stderr, "Connected to %s\n", realhost);
279
280 connection_open = 1;
281 }
282
283 /*
284 * Update statistic information about current file.
285 */
286 static void print_stats(char *name, unsigned long size, unsigned long done,
287 time_t start, time_t now)
288 {
289 float ratebs;
290 unsigned long eta;
291 char etastr[10];
292 int pct;
293
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;
302
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);
309
310 pct = (int) (100.0 * (float) done / size);
311
312 printf("\r%-25.25s | %10ld kB | %5.1f kB/s | ETA: %8s | %3d%%",
313 name, done / 1024, ratebs / 1024.0,
314 etastr, pct);
315
316 if (done == size)
317 printf("\n");
318 }
319 }
320
321 /*
322 * Find a colon in str and return a pointer to the colon.
323 * This is used to separate hostname from filename.
324 */
325 static char * colon(char *str)
326 {
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);
343 }
344
345 /*
346 * Wait for a response from the other side.
347 * Return 0 if ok, -1 if error.
348 */
349 static int response(void)
350 {
351 char ch, resp, rbuf[2048];
352 int p;
353
354 if (ssh_scp_recv(&resp, 1) <= 0)
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 {
367 if (ssh_scp_recv(&ch, 1) <= 0)
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)
373 tell_user(stderr, "%s\n", rbuf);
374 else
375 bump("%s", rbuf);
376 errs++;
377 return (-1);
378 }
379 }
380
381 /*
382 * Send an error message to the other side and to the screen.
383 * Increment error counter.
384 */
385 static void run_err(const char *fmt, ...)
386 {
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");
394 ssh_scp_send(str, strlen(str));
395 tell_user(stderr, "%s",str);
396 va_end(ap);
397 }
398
399 /*
400 * Execute the source part of the SCP protocol.
401 */
402 static void source(char *src)
403 {
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);
414 if (attr == (DWORD)-1) {
415 run_err("%s: No such file or directory", src);
416 return;
417 }
418
419 if ((attr & FILE_ATTRIBUTE_DIRECTORY) != 0) {
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 {
437 run_err("%s: not a regular file", src);
438 }
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) {
454 run_err("%s: Cannot open file", src);
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);
465 ssh_scp_send(buf, strlen(buf));
466 if (response())
467 return;
468 }
469
470 size = GetFileSize(f, NULL);
471 sprintf(buf, "C0644 %lu %s\n", size, last);
472 if (verbose)
473 tell_user(stderr, "Sending file modes: %s", buf);
474 ssh_scp_send(buf, strlen(buf));
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);
491 }
492 ssh_scp_send(transbuf, k);
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 }
501 }
502 }
503 CloseHandle(f);
504
505 ssh_scp_send("", 1);
506 (void) response();
507 }
508
509 /*
510 * Recursively send the contents of a directory.
511 */
512 static void rsource(char *src)
513 {
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)
533 tell_user(stderr, "Entering directory: %s", buf);
534 ssh_scp_send(buf, strlen(buf));
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);
550 }
551 ok = FindNextFile(dir, &fdat);
552 }
553 FindClose(dir);
554
555 sprintf(buf, "E\n");
556 ssh_scp_send(buf, strlen(buf));
557 (void) response();
558 }
559
560 /*
561 * Execute the sink part of the SCP protocol.
562 */
563 static void sink(char *targ)
564 {
565 char buf[2048];
566 char namebuf[2048];
567 char ch;
568 int targisdir = 0;
569 int settime;
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);
582 if (attr != (DWORD)-1 && (attr & FILE_ATTRIBUTE_DIRECTORY) != 0)
583 targisdir = 1;
584
585 if (targetshouldbedirectory && !targisdir)
586 bump("%s: Not a directory", targ);
587
588 ssh_scp_send("", 1);
589 while (1) {
590 settime = 0;
591 gottime:
592 if (ssh_scp_recv(&ch, 1) <= 0)
593 return;
594 if (ch == '\n')
595 bump("Protocol error: Unexpected newline");
596 i = 0;
597 buf[i++] = ch;
598 do {
599 if (ssh_scp_recv(&ch, 1) <= 0)
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 */
606 tell_user(stderr, "%s\n", buf+1);
607 errs++;
608 continue;
609 case '\02': /* fatal error */
610 bump("%s", buf+1);
611 case 'E':
612 ssh_scp_send("", 1);
613 return;
614 case 'T':
615 if (sscanf(buf, "T%ld %*d %ld %*d",
616 &mtime, &atime) == 2) {
617 settime = 1;
618 ssh_scp_send("", 1);
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 }
628
629 if (sscanf(buf+1, "%u %lu %[^\n]", &mode, &size, namebuf) != 3)
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);
642 exists = (attr != (DWORD)-1);
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 }
660
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 }
667
668 ssh_scp_send("", 1);
669
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 }
681
682 for (i = 0; i < size; i += 4096) {
683 char transbuf[4096];
684 DWORD j, k = 4096;
685 if (i + k > size) k = size - i;
686 if (ssh_scp_recv(transbuf, k) == 0)
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);
704 }
705 }
706 }
707 (void) response();
708
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);
714 }
715
716 CloseHandle(f);
717 if (wrerror) {
718 run_err("%s: Write error", namebuf);
719 continue;
720 }
721 ssh_scp_send("", 1);
722 }
723 }
724
725 /*
726 * We will copy local files to a remote server.
727 */
728 static void toremote(int argc, char *argv[])
729 {
730 char *src, *targ, *host, *user;
731 char *cmd;
732 int i;
733
734 targ = argv[argc-1];
735
736 /* Separate host from filename */
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
746 /* Separate host and username */
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) {
790 tell_user(stderr, "%s: Remote to remote not supported\n", src);
791 errs++;
792 continue;
793 }
794 dir = FindFirstFile(src, &fdat);
795 if (dir == INVALID_HANDLE_VALUE) {
796 run_err("%s: No such file or directory", src);
797 continue;
798 }
799 do {
800 char *last;
801 char namebuf[2048];
802 if (strlen(src) + strlen(fdat.cFileName) >=
803 sizeof(namebuf)) {
804 tell_user(stderr, "%s: Name too long", src);
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 }
821 }
822
823 /*
824 * We will copy files from a remote server to the local machine.
825 */
826 static void tolocal(int argc, char *argv[])
827 {
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
837 /* Separate host from filename */
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
847 /* Separate username and hostname */
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);
870 }
871
872 /*
873 * We will issue a list command to get a remote directory.
874 */
875 static 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';
917
918 do_cmd(host, user, cmd);
919 sfree(cmd);
920
921 while (ssh_scp_recv(&c, 1) > 0)
922 tell_char(stdout, c);
923 }
924
925 /*
926 * Initialize the Win$ock driver.
927 */
928 static void init_winsock(void)
929 {
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");
939 }
940
941 /*
942 * Short description of parameters.
943 */
944 static void usage(void)
945 {
946 printf("PuTTY Secure Copy client\n");
947 printf("%s\n", ver);
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");
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");
958 /* GUI Adaptation - Sept 2000 */
959 printf(" -gui hWnd GUI mode with the windows handle for receiving messages\n");
960 exit(1);
961 }
962
963 /*
964 * Main program (no, really?)
965 */
966 int main(int argc, char *argv[])
967 {
968 int i;
969 int list = 0;
970
971 default_protocol = PROT_TELNET;
972
973 flags = FLAG_STDERR;
974 ssh_get_password = &get_password;
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)
981 verbose = 1, flags |= FLAG_VERBOSE;
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();
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];
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;
1000 else if (strcmp(argv[i], "--") == 0)
1001 { i++; break; }
1002 else
1003 usage();
1004 }
1005 argc -= i;
1006 argv += i;
1007
1008 if (list) {
1009 if (argc != 1)
1010 usage();
1011 get_dir_list(argc, argv);
1012
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 }
1025
1026 if (connection_open) {
1027 char ch;
1028 ssh_scp_send_eof();
1029 ssh_scp_recv(&ch, 1);
1030 }
1031 WSACleanup();
1032 random_save_seed();
1033
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 }
1041 return (errs == 0 ? 0 : 1);
1042 }
1043
1044 /* end */