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