]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - scp.c
Implement Simon's suggestion of moving DEFAULT_PROTOCOL into a per-backend-
[PuTTY.git] / 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, 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 = (pending ? srealloc(pending, pendsize) :
357                        smalloc(pendsize));
358             if (!pending)
359                 fatalbox("Out of memory");
360         }
361         memcpy(pending + pendlen, p, len);
362         pendlen += len;
363     }
364
365     return 0;
366 }
367 static int scp_process_network_event(void)
368 {
369     fd_set readfds;
370
371     FD_ZERO(&readfds);
372     FD_SET(scp_ssh_socket, &readfds);
373     if (select(1, &readfds, NULL, NULL, NULL) < 0)
374         return 0;                      /* doom */
375     select_result((WPARAM) scp_ssh_socket, (LPARAM) FD_READ);
376     return 1;
377 }
378 static int ssh_scp_recv(unsigned char *buf, int len)
379 {
380     outptr = buf;
381     outlen = len;
382
383     /*
384      * See if the pending-input block contains some of what we
385      * need.
386      */
387     if (pendlen > 0) {
388         unsigned pendused = pendlen;
389         if (pendused > outlen)
390             pendused = outlen;
391         memcpy(outptr, pending, pendused);
392         memmove(pending, pending + pendused, pendlen - pendused);
393         outptr += pendused;
394         outlen -= pendused;
395         pendlen -= pendused;
396         if (pendlen == 0) {
397             pendsize = 0;
398             sfree(pending);
399             pending = NULL;
400         }
401         if (outlen == 0)
402             return len;
403     }
404
405     while (outlen > 0) {
406         if (!scp_process_network_event())
407             return 0;                  /* doom */
408     }
409
410     return len;
411 }
412
413 /*
414  * Loop through the ssh connection and authentication process.
415  */
416 static void ssh_scp_init(void)
417 {
418     if (scp_ssh_socket == INVALID_SOCKET)
419         return;
420     while (!back->sendok(backhandle)) {
421         fd_set readfds;
422         FD_ZERO(&readfds);
423         FD_SET(scp_ssh_socket, &readfds);
424         if (select(1, &readfds, NULL, NULL, NULL) < 0)
425             return;                    /* doom */
426         select_result((WPARAM) scp_ssh_socket, (LPARAM) FD_READ);
427     }
428     using_sftp = !ssh_fallback_cmd(backhandle);
429 }
430
431 /*
432  *  Print an error message and exit after closing the SSH link.
433  */
434 static void bump(char *fmt, ...)
435 {
436     char *str, *str2;
437     va_list ap;
438     va_start(ap, fmt);
439     str = dupvprintf(fmt, ap);
440     va_end(ap);
441     str2 = dupcat(str, "\n", NULL);
442     sfree(str);
443     tell_str(stderr, str2);
444     sfree(str2);
445     errs++;
446
447     if (back != NULL && back->socket(backhandle) != NULL) {
448         char ch;
449         back->special(backhandle, TS_EOF);
450         ssh_scp_recv(&ch, 1);
451     }
452
453     if (gui_mode) {
454         unsigned int msg_id = WM_RET_ERR_CNT;
455         if (list)
456             msg_id = WM_LS_RET_ERR_CNT;
457         while (!PostMessage
458                ((HWND) atoi(gui_hwnd), msg_id, (WPARAM) errs,
459                 0 /*lParam */ ))SleepEx(1000, TRUE);
460     }
461
462     cleanup_exit(1);
463 }
464
465 /*
466  *  Open an SSH connection to user@host and execute cmd.
467  */
468 static void do_cmd(char *host, char *user, char *cmd)
469 {
470     char *err, *realhost;
471     DWORD namelen;
472
473     if (host == NULL || host[0] == '\0')
474         bump("Empty host name");
475
476     /* Try to load settings for this host */
477     do_defaults(host, &cfg);
478     if (cfg.host[0] == '\0') {
479         /* No settings for this host; use defaults */
480         do_defaults(NULL, &cfg);
481         strncpy(cfg.host, host, sizeof(cfg.host) - 1);
482         cfg.host[sizeof(cfg.host) - 1] = '\0';
483     }
484
485     /*
486      * Force use of SSH. (If they got the protocol wrong we assume the
487      * port is useless too.)
488      */
489     if (cfg.protocol != PROT_SSH) {
490         cfg.protocol = PROT_SSH;
491         cfg.port = 22;
492     }
493
494     /*
495      * Enact command-line overrides.
496      */
497     cmdline_run_saved(&cfg);
498
499     /*
500      * Trim leading whitespace off the hostname if it's there.
501      */
502     {
503         int space = strspn(cfg.host, " \t");
504         memmove(cfg.host, cfg.host+space, 1+strlen(cfg.host)-space);
505     }
506
507     /* See if host is of the form user@host */
508     if (cfg.host[0] != '\0') {
509         char *atsign = strchr(cfg.host, '@');
510         /* Make sure we're not overflowing the user field */
511         if (atsign) {
512             if (atsign - cfg.host < sizeof cfg.username) {
513                 strncpy(cfg.username, cfg.host, atsign - cfg.host);
514                 cfg.username[atsign - cfg.host] = '\0';
515             }
516             memmove(cfg.host, atsign + 1, 1 + strlen(atsign + 1));
517         }
518     }
519
520     /*
521      * Trim a colon suffix off the hostname if it's there.
522      */
523     cfg.host[strcspn(cfg.host, ":")] = '\0';
524
525     /*
526      * Remove any remaining whitespace from the hostname.
527      */
528     {
529         int p1 = 0, p2 = 0;
530         while (cfg.host[p2] != '\0') {
531             if (cfg.host[p2] != ' ' && cfg.host[p2] != '\t') {
532                 cfg.host[p1] = cfg.host[p2];
533                 p1++;
534             }
535             p2++;
536         }
537         cfg.host[p1] = '\0';
538     }
539
540     /* Set username */
541     if (user != NULL && user[0] != '\0') {
542         strncpy(cfg.username, user, sizeof(cfg.username) - 1);
543         cfg.username[sizeof(cfg.username) - 1] = '\0';
544     } else if (cfg.username[0] == '\0') {
545         namelen = 0;
546         if (GetUserName(user, &namelen) == FALSE)
547             bump("Empty user name");
548         user = smalloc(namelen * sizeof(char));
549         GetUserName(user, &namelen);
550         if (verbose)
551             tell_user(stderr, "Guessing user name: %s", user);
552         strncpy(cfg.username, user, sizeof(cfg.username) - 1);
553         cfg.username[sizeof(cfg.username) - 1] = '\0';
554         free(user);
555     }
556
557     /*
558      * Disable scary things which shouldn't be enabled for simple
559      * things like SCP and SFTP: agent forwarding, port forwarding,
560      * X forwarding.
561      */
562     cfg.x11_forward = 0;
563     cfg.agentfwd = 0;
564     cfg.portfwd[0] = cfg.portfwd[1] = '\0';
565
566     /*
567      * Attempt to start the SFTP subsystem as a first choice,
568      * falling back to the provided scp command if that fails.
569      */
570     strcpy(cfg.remote_cmd, "sftp");
571     cfg.ssh_subsys = TRUE;
572     cfg.remote_cmd_ptr2 = cmd;
573     cfg.ssh_subsys2 = FALSE;
574     cfg.nopty = TRUE;
575
576     back = &ssh_backend;
577
578     err = back->init(NULL, &backhandle, &cfg, cfg.host, cfg.port, &realhost,0);
579     if (err != NULL)
580         bump("ssh_init: %s", err);
581     logctx = log_init(NULL, &cfg);
582     back->provide_logctx(backhandle, 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 =
780                     srealloc(ournames, namesize * sizeof(*ournames));
781             }
782
783             for (i = 0; i < names->nnames; i++)
784                 ournames[nnames++] = names->names[i];
785
786             names->nnames = 0;         /* prevent free_names */
787             fxp_free_names(names);
788         }
789         fxp_close(dirh);
790
791         /*
792          * Now we have our filenames. Sort them by actual file
793          * name, and then output the longname parts.
794          */
795         qsort(ournames, nnames, sizeof(*ournames), sftp_ls_compare);
796
797         /*
798          * And print them.
799          */
800         for (i = 0; i < nnames; i++)
801             printf("%s\n", ournames[i].longname);
802     }
803 }
804
805 /* ----------------------------------------------------------------------
806  * Helper routines that contain the actual SCP protocol elements,
807  * implemented both as SCP1 and SFTP.
808  */
809
810 static struct scp_sftp_dirstack {
811     struct scp_sftp_dirstack *next;
812     struct fxp_name *names;
813     int namepos, namelen;
814     char *dirpath;
815     char *wildcard;
816     int matched_something;             /* wildcard match set was non-empty */
817 } *scp_sftp_dirstack_head;
818 static char *scp_sftp_remotepath, *scp_sftp_currentname;
819 static char *scp_sftp_wildcard;
820 static int scp_sftp_targetisdir, scp_sftp_donethistarget;
821 static int scp_sftp_preserve, scp_sftp_recursive;
822 static unsigned long scp_sftp_mtime, scp_sftp_atime;
823 static int scp_has_times;
824 static struct fxp_handle *scp_sftp_filehandle;
825 static uint64 scp_sftp_fileoffset;
826
827 void scp_source_setup(char *target, int shouldbedir)
828 {
829     if (using_sftp) {
830         /*
831          * Find out whether the target filespec is in fact a
832          * directory.
833          */
834         struct fxp_attrs attrs;
835
836         if (!fxp_init()) {
837             tell_user(stderr, "unable to initialise SFTP: %s", fxp_error());
838             errs++;
839             return;
840         }
841
842         if (!fxp_stat(target, &attrs) ||
843             !(attrs.flags & SSH_FILEXFER_ATTR_PERMISSIONS))
844             scp_sftp_targetisdir = 0;
845         else
846             scp_sftp_targetisdir = (attrs.permissions & 0040000) != 0;
847
848         if (shouldbedir && !scp_sftp_targetisdir) {
849             bump("pscp: remote filespec %s: not a directory\n", target);
850         }
851
852         scp_sftp_remotepath = dupstr(target);
853
854         scp_has_times = 0;
855     } else {
856         (void) response();
857     }
858 }
859
860 int scp_send_errmsg(char *str)
861 {
862     if (using_sftp) {
863         /* do nothing; we never need to send our errors to the server */
864     } else {
865         back->send(backhandle, "\001", 1);/* scp protocol error prefix */
866         back->send(backhandle, str, strlen(str));
867     }
868     return 0;                          /* can't fail */
869 }
870
871 int scp_send_filetimes(unsigned long mtime, unsigned long atime)
872 {
873     if (using_sftp) {
874         scp_sftp_mtime = mtime;
875         scp_sftp_atime = atime;
876         scp_has_times = 1;
877         return 0;
878     } else {
879         char buf[80];
880         sprintf(buf, "T%lu 0 %lu 0\n", mtime, atime);
881         back->send(backhandle, buf, strlen(buf));
882         return response();
883     }
884 }
885
886 int scp_send_filename(char *name, unsigned long size, int modes)
887 {
888     if (using_sftp) {
889         char *fullname;
890         if (scp_sftp_targetisdir) {
891             fullname = dupcat(scp_sftp_remotepath, "/", name, NULL);
892         } else {
893             fullname = dupstr(scp_sftp_remotepath);
894         }
895         scp_sftp_filehandle =
896             fxp_open(fullname, SSH_FXF_WRITE | SSH_FXF_CREAT | SSH_FXF_TRUNC);
897         if (!scp_sftp_filehandle) {
898             tell_user(stderr, "pscp: unable to open %s: %s",
899                       fullname, fxp_error());
900             errs++;
901             return 1;
902         }
903         scp_sftp_fileoffset = uint64_make(0, 0);
904         sfree(fullname);
905         return 0;
906     } else {
907         char buf[40];
908         sprintf(buf, "C%04o %lu ", modes, size);
909         back->send(backhandle, buf, strlen(buf));
910         back->send(backhandle, name, strlen(name));
911         back->send(backhandle, "\n", 1);
912         return response();
913     }
914 }
915
916 int scp_send_filedata(char *data, int len)
917 {
918     if (using_sftp) {
919         if (!scp_sftp_filehandle) {
920             return 1;
921         }
922         if (!fxp_write(scp_sftp_filehandle, data, scp_sftp_fileoffset, len)) {
923             tell_user(stderr, "error while writing: %s\n", fxp_error());
924             errs++;
925             return 1;
926         }
927         scp_sftp_fileoffset = uint64_add32(scp_sftp_fileoffset, len);
928         return 0;
929     } else {
930         int bufsize = back->send(backhandle, data, len);
931
932         /*
933          * If the network transfer is backing up - that is, the
934          * remote site is not accepting data as fast as we can
935          * produce it - then we must loop on network events until
936          * we have space in the buffer again.
937          */
938         while (bufsize > MAX_SCP_BUFSIZE) {
939             if (!scp_process_network_event())
940                 return 1;
941             bufsize = back->sendbuffer(backhandle);
942         }
943
944         return 0;
945     }
946 }
947
948 int scp_send_finish(void)
949 {
950     if (using_sftp) {
951         struct fxp_attrs attrs;
952         if (!scp_sftp_filehandle) {
953             return 1;
954         }
955         if (scp_has_times) {
956             attrs.flags = SSH_FILEXFER_ATTR_ACMODTIME;
957             attrs.atime = scp_sftp_atime;
958             attrs.mtime = scp_sftp_mtime;
959             if (!fxp_fsetstat(scp_sftp_filehandle, attrs)) {
960                 tell_user(stderr, "unable to set file times: %s\n", fxp_error());
961                 errs++;
962             }
963         }
964         fxp_close(scp_sftp_filehandle);
965         scp_has_times = 0;
966         return 0;
967     } else {
968         back->send(backhandle, "", 1);
969         return response();
970     }
971 }
972
973 char *scp_save_remotepath(void)
974 {
975     if (using_sftp)
976         return scp_sftp_remotepath;
977     else
978         return NULL;
979 }
980
981 void scp_restore_remotepath(char *data)
982 {
983     if (using_sftp)
984         scp_sftp_remotepath = data;
985 }
986
987 int scp_send_dirname(char *name, int modes)
988 {
989     if (using_sftp) {
990         char *fullname;
991         char const *err;
992         struct fxp_attrs attrs;
993         if (scp_sftp_targetisdir) {
994             fullname = dupcat(scp_sftp_remotepath, "/", name, NULL);
995         } else {
996             fullname = dupstr(scp_sftp_remotepath);
997         }
998
999         /*
1000          * We don't worry about whether we managed to create the
1001          * directory, because if it exists already it's OK just to
1002          * use it. Instead, we will stat it afterwards, and if it
1003          * exists and is a directory we will assume we were either
1004          * successful or it didn't matter.
1005          */
1006         if (!fxp_mkdir(fullname))
1007             err = fxp_error();
1008         else
1009             err = "server reported no error";
1010         if (!fxp_stat(fullname, &attrs) ||
1011             !(attrs.flags & SSH_FILEXFER_ATTR_PERMISSIONS) ||
1012             !(attrs.permissions & 0040000)) {
1013             tell_user(stderr, "unable to create directory %s: %s",
1014                       fullname, err);
1015             errs++;
1016             return 1;
1017         }
1018
1019         scp_sftp_remotepath = fullname;
1020
1021         return 0;
1022     } else {
1023         char buf[40];
1024         sprintf(buf, "D%04o 0 ", modes);
1025         back->send(backhandle, buf, strlen(buf));
1026         back->send(backhandle, name, strlen(name));
1027         back->send(backhandle, "\n", 1);
1028         return response();
1029     }
1030 }
1031
1032 int scp_send_enddir(void)
1033 {
1034     if (using_sftp) {
1035         sfree(scp_sftp_remotepath);
1036         return 0;
1037     } else {
1038         back->send(backhandle, "E\n", 2);
1039         return response();
1040     }
1041 }
1042
1043 /*
1044  * Yes, I know; I have an scp_sink_setup _and_ an scp_sink_init.
1045  * That's bad. The difference is that scp_sink_setup is called once
1046  * right at the start, whereas scp_sink_init is called to
1047  * initialise every level of recursion in the protocol.
1048  */
1049 int scp_sink_setup(char *source, int preserve, int recursive)
1050 {
1051     if (using_sftp) {
1052         char *newsource;
1053
1054         if (!fxp_init()) {
1055             tell_user(stderr, "unable to initialise SFTP: %s", fxp_error());
1056             errs++;
1057             return 1;
1058         }
1059         /*
1060          * It's possible that the source string we've been given
1061          * contains a wildcard. If so, we must split the directory
1062          * away from the wildcard itself (throwing an error if any
1063          * wildcardness comes before the final slash) and arrange
1064          * things so that a dirstack entry will be set up.
1065          */
1066         newsource = smalloc(1+strlen(source));
1067         if (!wc_unescape(newsource, source)) {
1068             /* Yes, here we go; it's a wildcard. Bah. */
1069             char *dupsource, *lastpart, *dirpart, *wildcard;
1070             dupsource = dupstr(source);
1071             lastpart = stripslashes(dupsource, 0);
1072             wildcard = dupstr(lastpart);
1073             *lastpart = '\0';
1074             if (*dupsource && dupsource[1]) {
1075                 /*
1076                  * The remains of dupsource are at least two
1077                  * characters long, meaning the pathname wasn't
1078                  * empty or just `/'. Hence, we remove the trailing
1079                  * slash.
1080                  */
1081                 lastpart[-1] = '\0';
1082             } else if (!*dupsource) {
1083                 /*
1084                  * The remains of dupsource are _empty_ - the whole
1085                  * pathname was a wildcard. Hence we need to
1086                  * replace it with ".".
1087                  */
1088                 sfree(dupsource);
1089                 dupsource = dupstr(".");
1090             }
1091
1092             /*
1093              * Now we have separated our string into dupsource (the
1094              * directory part) and wildcard. Both of these will
1095              * need freeing at some point. Next step is to remove
1096              * wildcard escapes from the directory part, throwing
1097              * an error if it contains a real wildcard.
1098              */
1099             dirpart = smalloc(1+strlen(dupsource));
1100             if (!wc_unescape(dirpart, dupsource)) {
1101                 tell_user(stderr, "%s: multiple-level wildcards unsupported",
1102                           source);
1103                 errs++;
1104                 sfree(dirpart);
1105                 sfree(wildcard);
1106                 sfree(dupsource);
1107                 return 1;
1108             }
1109
1110             /*
1111              * Now we have dirpart (unescaped, ie a valid remote
1112              * path), and wildcard (a wildcard). This will be
1113              * sufficient to arrange a dirstack entry.
1114              */
1115             scp_sftp_remotepath = dirpart;
1116             scp_sftp_wildcard = wildcard;
1117             sfree(dupsource);
1118         } else {
1119             scp_sftp_remotepath = newsource;
1120             scp_sftp_wildcard = NULL;
1121         }
1122         scp_sftp_preserve = preserve;
1123         scp_sftp_recursive = recursive;
1124         scp_sftp_donethistarget = 0;
1125         scp_sftp_dirstack_head = NULL;
1126     }
1127     return 0;
1128 }
1129
1130 int scp_sink_init(void)
1131 {
1132     if (!using_sftp) {
1133         back->send(backhandle, "", 1);
1134     }
1135     return 0;
1136 }
1137
1138 #define SCP_SINK_FILE   1
1139 #define SCP_SINK_DIR    2
1140 #define SCP_SINK_ENDDIR 3
1141 #define SCP_SINK_RETRY  4              /* not an action; just try again */
1142 struct scp_sink_action {
1143     int action;                        /* FILE, DIR, ENDDIR */
1144     char *buf;                         /* will need freeing after use */
1145     char *name;                        /* filename or dirname (not ENDDIR) */
1146     int mode;                          /* access mode (not ENDDIR) */
1147     unsigned long size;                /* file size (not ENDDIR) */
1148     int settime;                       /* 1 if atime and mtime are filled */
1149     unsigned long atime, mtime;        /* access times for the file */
1150 };
1151
1152 int scp_get_sink_action(struct scp_sink_action *act)
1153 {
1154     if (using_sftp) {
1155         char *fname;
1156         int must_free_fname;
1157         struct fxp_attrs attrs;
1158         int ret;
1159
1160         if (!scp_sftp_dirstack_head) {
1161             if (!scp_sftp_donethistarget) {
1162                 /*
1163                  * Simple case: we are only dealing with one file.
1164                  */
1165                 fname = scp_sftp_remotepath;
1166                 must_free_fname = 0;
1167                 scp_sftp_donethistarget = 1;
1168             } else {
1169                 /*
1170                  * Even simpler case: one file _which we've done_.
1171                  * Return 1 (finished).
1172                  */
1173                 return 1;
1174             }
1175         } else {
1176             /*
1177              * We're now in the middle of stepping through a list
1178              * of names returned from fxp_readdir(); so let's carry
1179              * on.
1180              */
1181             struct scp_sftp_dirstack *head = scp_sftp_dirstack_head;
1182             while (head->namepos < head->namelen &&
1183                    (is_dots(head->names[head->namepos].filename) ||
1184                     (head->wildcard &&
1185                      !wc_match(head->wildcard,
1186                                head->names[head->namepos].filename))))
1187                 head->namepos++;       /* skip . and .. */
1188             if (head->namepos < head->namelen) {
1189                 head->matched_something = 1;
1190                 fname = dupcat(head->dirpath, "/",
1191                                head->names[head->namepos++].filename,
1192                                NULL);
1193                 must_free_fname = 1;
1194             } else {
1195                 /*
1196                  * We've come to the end of the list; pop it off
1197                  * the stack and return an ENDDIR action (or RETRY
1198                  * if this was a wildcard match).
1199                  */
1200                 if (head->wildcard) {
1201                     act->action = SCP_SINK_RETRY;
1202                     if (!head->matched_something) {
1203                         tell_user(stderr, "pscp: wildcard '%s' matched "
1204                                   "no files", head->wildcard);
1205                         errs++;
1206                     }
1207                     sfree(head->wildcard);
1208
1209                 } else {
1210                     act->action = SCP_SINK_ENDDIR;
1211                 }
1212
1213                 sfree(head->dirpath);
1214                 sfree(head->names);
1215                 scp_sftp_dirstack_head = head->next;
1216                 sfree(head);
1217
1218                 return 0;
1219             }
1220         }
1221
1222         /*
1223          * Now we have a filename. Stat it, and see if it's a file
1224          * or a directory.
1225          */
1226         ret = fxp_stat(fname, &attrs);
1227         if (!ret || !(attrs.flags & SSH_FILEXFER_ATTR_PERMISSIONS)) {
1228             tell_user(stderr, "unable to identify %s: %s", fname,
1229                       ret ? "file type not supplied" : fxp_error());
1230             errs++;
1231             return 1;
1232         }
1233
1234         if (attrs.permissions & 0040000) {
1235             struct scp_sftp_dirstack *newitem;
1236             struct fxp_handle *dirhandle;
1237             int nnames, namesize;
1238             struct fxp_name *ournames;
1239             struct fxp_names *names;
1240
1241             /*
1242              * It's a directory. If we're not in recursive mode,
1243              * this merits a complaint (which is fatal if the name
1244              * was specified directly, but not if it was matched by
1245              * a wildcard).
1246              * 
1247              * We skip this complaint completely if
1248              * scp_sftp_wildcard is set, because that's an
1249              * indication that we're not actually supposed to
1250              * _recursively_ transfer the dir, just scan it for
1251              * things matching the wildcard.
1252              */
1253             if (!scp_sftp_recursive && !scp_sftp_wildcard) {
1254                 tell_user(stderr, "pscp: %s: is a directory", fname);
1255                 errs++;
1256                 if (must_free_fname) sfree(fname);
1257                 if (scp_sftp_dirstack_head) {
1258                     act->action = SCP_SINK_RETRY;
1259                     return 0;
1260                 } else {
1261                     return 1;
1262                 }
1263             }
1264
1265             /*
1266              * Otherwise, the fun begins. We must fxp_opendir() the
1267              * directory, slurp the filenames into memory, return
1268              * SCP_SINK_DIR (unless this is a wildcard match), and
1269              * set targetisdir. The next time we're called, we will
1270              * run through the list of filenames one by one,
1271              * matching them against a wildcard if present.
1272              * 
1273              * If targetisdir is _already_ set (meaning we're
1274              * already in the middle of going through another such
1275              * list), we must push the other (target,namelist) pair
1276              * on a stack.
1277              */
1278             dirhandle = fxp_opendir(fname);
1279             if (!dirhandle) {
1280                 tell_user(stderr, "scp: unable to open directory %s: %s",
1281                           fname, fxp_error());
1282                 if (must_free_fname) sfree(fname);
1283                 errs++;
1284                 return 1;
1285             }
1286             nnames = namesize = 0;
1287             ournames = NULL;
1288             while (1) {
1289                 int i;
1290
1291                 names = fxp_readdir(dirhandle);
1292                 if (names == NULL) {
1293                     if (fxp_error_type() == SSH_FX_EOF)
1294                         break;
1295                     tell_user(stderr, "scp: reading directory %s: %s\n",
1296                               fname, fxp_error());
1297                     if (must_free_fname) sfree(fname);
1298                     sfree(ournames);
1299                     errs++;
1300                     return 1;
1301                 }
1302                 if (names->nnames == 0) {
1303                     fxp_free_names(names);
1304                     break;
1305                 }
1306                 if (nnames + names->nnames >= namesize) {
1307                     namesize += names->nnames + 128;
1308                     ournames =
1309                         srealloc(ournames, namesize * sizeof(*ournames));
1310                 }
1311                 for (i = 0; i < names->nnames; i++)
1312                     ournames[nnames++] = names->names[i];
1313                 names->nnames = 0;             /* prevent free_names */
1314                 fxp_free_names(names);
1315             }
1316             fxp_close(dirhandle);
1317
1318             newitem = smalloc(sizeof(struct scp_sftp_dirstack));
1319             newitem->next = scp_sftp_dirstack_head;
1320             newitem->names = ournames;
1321             newitem->namepos = 0;
1322             newitem->namelen = nnames;
1323             if (must_free_fname)
1324                 newitem->dirpath = fname;
1325             else
1326                 newitem->dirpath = dupstr(fname);
1327             if (scp_sftp_wildcard) {
1328                 newitem->wildcard = scp_sftp_wildcard;
1329                 newitem->matched_something = 0;
1330                 scp_sftp_wildcard = NULL;
1331             } else {
1332                 newitem->wildcard = NULL;
1333             }
1334             scp_sftp_dirstack_head = newitem;
1335
1336             if (newitem->wildcard) {
1337                 act->action = SCP_SINK_RETRY;
1338             } else {
1339                 act->action = SCP_SINK_DIR;
1340                 act->buf = dupstr(stripslashes(fname, 0));
1341                 act->name = act->buf;
1342                 act->size = 0;         /* duhh, it's a directory */
1343                 act->mode = 07777 & attrs.permissions;
1344                 if (scp_sftp_preserve &&
1345                     (attrs.flags & SSH_FILEXFER_ATTR_ACMODTIME)) {
1346                     act->atime = attrs.atime;
1347                     act->mtime = attrs.mtime;
1348                     act->settime = 1;
1349                 } else
1350                     act->settime = 0;
1351             }
1352             return 0;
1353
1354         } else {
1355             /*
1356              * It's a file. Return SCP_SINK_FILE.
1357              */
1358             act->action = SCP_SINK_FILE;
1359             act->buf = dupstr(stripslashes(fname, 0));
1360             act->name = act->buf;
1361             if (attrs.flags & SSH_FILEXFER_ATTR_SIZE) {
1362                 if (uint64_compare(attrs.size,
1363                                    uint64_make(0, ULONG_MAX)) > 0) {
1364                     act->size = ULONG_MAX;   /* *boggle* */
1365                 } else
1366                     act->size = attrs.size.lo;
1367             } else
1368                 act->size = ULONG_MAX;   /* no idea */
1369             act->mode = 07777 & attrs.permissions;
1370             if (scp_sftp_preserve &&
1371                 (attrs.flags & SSH_FILEXFER_ATTR_ACMODTIME)) {
1372                 act->atime = attrs.atime;
1373                 act->mtime = attrs.mtime;
1374                 act->settime = 1;
1375             } else
1376                 act->settime = 0;
1377             if (must_free_fname)
1378                 scp_sftp_currentname = fname;
1379             else
1380                 scp_sftp_currentname = dupstr(fname);
1381             return 0;
1382         }
1383
1384     } else {
1385         int done = 0;
1386         int i, bufsize;
1387         int action;
1388         char ch;
1389
1390         act->settime = 0;
1391         act->buf = NULL;
1392         bufsize = 0;
1393
1394         while (!done) {
1395             if (ssh_scp_recv(&ch, 1) <= 0)
1396                 return 1;
1397             if (ch == '\n')
1398                 bump("Protocol error: Unexpected newline");
1399             i = 0;
1400             action = ch;
1401             do {
1402                 if (ssh_scp_recv(&ch, 1) <= 0)
1403                     bump("Lost connection");
1404                 if (i >= bufsize) {
1405                     bufsize = i + 128;
1406                     act->buf = srealloc(act->buf, bufsize);
1407                 }
1408                 act->buf[i++] = ch;
1409             } while (ch != '\n');
1410             act->buf[i - 1] = '\0';
1411             switch (action) {
1412               case '\01':                      /* error */
1413                 tell_user(stderr, "%s\n", act->buf);
1414                 errs++;
1415                 continue;                      /* go round again */
1416               case '\02':                      /* fatal error */
1417                 bump("%s", act->buf);
1418               case 'E':
1419                 back->send(backhandle, "", 1);
1420                 act->action = SCP_SINK_ENDDIR;
1421                 return 0;
1422               case 'T':
1423                 if (sscanf(act->buf, "%ld %*d %ld %*d",
1424                            &act->mtime, &act->atime) == 2) {
1425                     act->settime = 1;
1426                     back->send(backhandle, "", 1);
1427                     continue;          /* go round again */
1428                 }
1429                 bump("Protocol error: Illegal time format");
1430               case 'C':
1431               case 'D':
1432                 act->action = (action == 'C' ? SCP_SINK_FILE : SCP_SINK_DIR);
1433                 break;
1434               default:
1435                 bump("Protocol error: Expected control record");
1436             }
1437             /*
1438              * We will go round this loop only once, unless we hit
1439              * `continue' above.
1440              */
1441             done = 1;
1442         }
1443
1444         /*
1445          * If we get here, we must have seen SCP_SINK_FILE or
1446          * SCP_SINK_DIR.
1447          */
1448         if (sscanf(act->buf, "%o %lu %n", &act->mode, &act->size, &i) != 2)
1449             bump("Protocol error: Illegal file descriptor format");
1450         act->name = act->buf + i;
1451         return 0;
1452     }
1453 }
1454
1455 int scp_accept_filexfer(void)
1456 {
1457     if (using_sftp) {
1458         scp_sftp_filehandle =
1459             fxp_open(scp_sftp_currentname, SSH_FXF_READ);
1460         if (!scp_sftp_filehandle) {
1461             tell_user(stderr, "pscp: unable to open %s: %s",
1462                       scp_sftp_currentname, fxp_error());
1463             errs++;
1464             return 1;
1465         }
1466         scp_sftp_fileoffset = uint64_make(0, 0);
1467         sfree(scp_sftp_currentname);
1468         return 0;
1469     } else {
1470         back->send(backhandle, "", 1);
1471         return 0;                      /* can't fail */
1472     }
1473 }
1474
1475 int scp_recv_filedata(char *data, int len)
1476 {
1477     if (using_sftp) {
1478         int actuallen = fxp_read(scp_sftp_filehandle, data,
1479                                  scp_sftp_fileoffset, len);
1480         if (actuallen == -1 && fxp_error_type() != SSH_FX_EOF) {
1481             tell_user(stderr, "pscp: error while reading: %s", fxp_error());
1482             errs++;
1483             return -1;
1484         }
1485         if (actuallen < 0)
1486             actuallen = 0;
1487
1488         scp_sftp_fileoffset = uint64_add32(scp_sftp_fileoffset, actuallen);
1489
1490         return actuallen;
1491     } else {
1492         return ssh_scp_recv(data, len);
1493     }
1494 }
1495
1496 int scp_finish_filerecv(void)
1497 {
1498     if (using_sftp) {
1499         fxp_close(scp_sftp_filehandle);
1500         return 0;
1501     } else {
1502         back->send(backhandle, "", 1);
1503         return response();
1504     }
1505 }
1506
1507 /* ----------------------------------------------------------------------
1508  *  Send an error message to the other side and to the screen.
1509  *  Increment error counter.
1510  */
1511 static void run_err(const char *fmt, ...)
1512 {
1513     char *str, *str2;
1514     va_list ap;
1515     va_start(ap, fmt);
1516     errs++;
1517     str = dupvprintf(fmt, ap);
1518     str2 = dupcat("scp: ", str, "\n", NULL);
1519     sfree(str);
1520     scp_send_errmsg(str2);
1521     tell_user(stderr, "%s", str2);
1522     va_end(ap);
1523     sfree(str2);
1524 }
1525
1526 /*
1527  *  Execute the source part of the SCP protocol.
1528  */
1529 static void source(char *src)
1530 {
1531     unsigned long size;
1532     char *last;
1533     HANDLE f;
1534     DWORD attr;
1535     unsigned long i;
1536     unsigned long stat_bytes;
1537     time_t stat_starttime, stat_lasttime;
1538
1539     attr = GetFileAttributes(src);
1540     if (attr == (DWORD) - 1) {
1541         run_err("%s: No such file or directory", src);
1542         return;
1543     }
1544
1545     if ((attr & FILE_ATTRIBUTE_DIRECTORY) != 0) {
1546         if (recursive) {
1547             /*
1548              * Avoid . and .. directories.
1549              */
1550             char *p;
1551             p = strrchr(src, '/');
1552             if (!p)
1553                 p = strrchr(src, '\\');
1554             if (!p)
1555                 p = src;
1556             else
1557                 p++;
1558             if (!strcmp(p, ".") || !strcmp(p, ".."))
1559                 /* skip . and .. */ ;
1560             else
1561                 rsource(src);
1562         } else {
1563             run_err("%s: not a regular file", src);
1564         }
1565         return;
1566     }
1567
1568     if ((last = strrchr(src, '/')) == NULL)
1569         last = src;
1570     else
1571         last++;
1572     if (strrchr(last, '\\') != NULL)
1573         last = strrchr(last, '\\') + 1;
1574     if (last == src && strchr(src, ':') != NULL)
1575         last = strchr(src, ':') + 1;
1576
1577     f = CreateFile(src, GENERIC_READ, FILE_SHARE_READ, NULL,
1578                    OPEN_EXISTING, 0, 0);
1579     if (f == INVALID_HANDLE_VALUE) {
1580         run_err("%s: Cannot open file", src);
1581         return;
1582     }
1583
1584     if (preserve) {
1585         FILETIME actime, wrtime;
1586         unsigned long mtime, atime;
1587         GetFileTime(f, NULL, &actime, &wrtime);
1588         TIME_WIN_TO_POSIX(actime, atime);
1589         TIME_WIN_TO_POSIX(wrtime, mtime);
1590         if (scp_send_filetimes(mtime, atime))
1591             return;
1592     }
1593
1594     size = GetFileSize(f, NULL);
1595     if (verbose)
1596         tell_user(stderr, "Sending file %s, size=%lu", last, size);
1597     if (scp_send_filename(last, size, 0644))
1598         return;
1599
1600     stat_bytes = 0;
1601     stat_starttime = time(NULL);
1602     stat_lasttime = 0;
1603
1604     for (i = 0; i < size; i += 4096) {
1605         char transbuf[4096];
1606         DWORD j, k = 4096;
1607
1608         if (i + k > size)
1609             k = size - i;
1610         if (!ReadFile(f, transbuf, k, &j, NULL) || j != k) {
1611             if (statistics)
1612                 printf("\n");
1613             bump("%s: Read error", src);
1614         }
1615         if (scp_send_filedata(transbuf, k))
1616             bump("%s: Network error occurred", src);
1617
1618         if (statistics) {
1619             stat_bytes += k;
1620             if (time(NULL) != stat_lasttime || i + k == size) {
1621                 stat_lasttime = time(NULL);
1622                 print_stats(last, size, stat_bytes,
1623                             stat_starttime, stat_lasttime);
1624             }
1625         }
1626
1627     }
1628     CloseHandle(f);
1629
1630     (void) scp_send_finish();
1631 }
1632
1633 /*
1634  *  Recursively send the contents of a directory.
1635  */
1636 static void rsource(char *src)
1637 {
1638     char *last, *findfile;
1639     char *save_target;
1640     HANDLE dir;
1641     WIN32_FIND_DATA fdat;
1642     int ok;
1643
1644     if ((last = strrchr(src, '/')) == NULL)
1645         last = src;
1646     else
1647         last++;
1648     if (strrchr(last, '\\') != NULL)
1649         last = strrchr(last, '\\') + 1;
1650     if (last == src && strchr(src, ':') != NULL)
1651         last = strchr(src, ':') + 1;
1652
1653     /* maybe send filetime */
1654
1655     save_target = scp_save_remotepath();
1656
1657     if (verbose)
1658         tell_user(stderr, "Entering directory: %s", last);
1659     if (scp_send_dirname(last, 0755))
1660         return;
1661
1662     findfile = dupcat(src, "/*", NULL);
1663     dir = FindFirstFile(findfile, &fdat);
1664     ok = (dir != INVALID_HANDLE_VALUE);
1665     while (ok) {
1666         if (strcmp(fdat.cFileName, ".") == 0 ||
1667             strcmp(fdat.cFileName, "..") == 0) {
1668             /* ignore . and .. */
1669         } else {
1670             char *foundfile = dupcat(src, "/", fdat.cFileName, NULL);
1671             source(foundfile);
1672             sfree(foundfile);
1673         }
1674         ok = FindNextFile(dir, &fdat);
1675     }
1676     FindClose(dir);
1677     sfree(findfile);
1678
1679     (void) scp_send_enddir();
1680
1681     scp_restore_remotepath(save_target);
1682 }
1683
1684 /*
1685  * Execute the sink part of the SCP protocol.
1686  */
1687 static void sink(char *targ, char *src)
1688 {
1689     char *destfname;
1690     int targisdir = 0;
1691     int exists;
1692     DWORD attr;
1693     HANDLE f;
1694     unsigned long received;
1695     int wrerror = 0;
1696     unsigned long stat_bytes;
1697     time_t stat_starttime, stat_lasttime;
1698     char *stat_name;
1699
1700     attr = GetFileAttributes(targ);
1701     if (attr != (DWORD) - 1 && (attr & FILE_ATTRIBUTE_DIRECTORY) != 0)
1702         targisdir = 1;
1703
1704     if (targetshouldbedirectory && !targisdir)
1705         bump("%s: Not a directory", targ);
1706
1707     scp_sink_init();
1708     while (1) {
1709         struct scp_sink_action act;
1710         if (scp_get_sink_action(&act))
1711             return;
1712
1713         if (act.action == SCP_SINK_ENDDIR)
1714             return;
1715
1716         if (act.action == SCP_SINK_RETRY)
1717             continue;
1718
1719         if (targisdir) {
1720             /*
1721              * Prevent the remote side from maliciously writing to
1722              * files outside the target area by sending a filename
1723              * containing `../'. In fact, it shouldn't be sending
1724              * filenames with any slashes or colons in at all; so
1725              * we'll find the last slash, backslash or colon in the
1726              * filename and use only the part after that. (And
1727              * warn!)
1728              * 
1729              * In addition, we also ensure here that if we're
1730              * copying a single file and the target is a directory
1731              * (common usage: `pscp host:filename .') the remote
1732              * can't send us a _different_ file name. We can
1733              * distinguish this case because `src' will be non-NULL
1734              * and the last component of that will fail to match
1735              * (the last component of) the name sent.
1736              * 
1737              * Well, not always; if `src' is a wildcard, we do
1738              * expect to get back filenames that don't correspond
1739              * exactly to it. Ideally in this case, we would like
1740              * to ensure that the returned filename actually
1741              * matches the wildcard pattern - but one of SCP's
1742              * protocol infelicities is that wildcard matching is
1743              * done at the server end _by the server's rules_ and
1744              * so in general this is infeasible. Hence, we only
1745              * accept filenames that don't correspond to `src' if
1746              * unsafe mode is enabled or we are using SFTP (which
1747              * resolves remote wildcards on the client side and can
1748              * be trusted).
1749              */
1750             char *striptarget, *stripsrc;
1751
1752             striptarget = stripslashes(act.name, 1);
1753             if (striptarget != act.name) {
1754                 tell_user(stderr, "warning: remote host sent a compound"
1755                           " pathname '%s'", act.name);
1756                 tell_user(stderr, "         renaming local file to '%s'",
1757                           striptarget);
1758             }
1759
1760             /*
1761              * Also check to see if the target filename is '.' or
1762              * '..', or indeed '...' and so on because Windows
1763              * appears to interpret those like '..'.
1764              */
1765             if (is_dots(striptarget)) {
1766                 bump("security violation: remote host attempted to write to"
1767                      " a '.' or '..' path!");
1768             }
1769
1770             if (src) {
1771                 stripsrc = stripslashes(src, 1);
1772                 if (strcmp(striptarget, stripsrc) &&
1773                     !using_sftp && !scp_unsafe_mode) {
1774                     tell_user(stderr, "warning: remote host tried to write "
1775                               "to a file called '%s'", striptarget);
1776                     tell_user(stderr, "         when we requested a file "
1777                               "called '%s'.", stripsrc);
1778                     tell_user(stderr, "         If this is a wildcard, "
1779                               "consider upgrading to SSH 2 or using");
1780                     tell_user(stderr, "         the '-unsafe' option. Renaming"
1781                               " of this file has been disallowed.");
1782                     /* Override the name the server provided with our own. */
1783                     striptarget = stripsrc;
1784                 }
1785             }
1786
1787             if (targ[0] != '\0')
1788                 destfname = dupcat(targ, "\\", striptarget, NULL);
1789             else
1790                 destfname = dupstr(striptarget);
1791         } else {
1792             /*
1793              * In this branch of the if, the target area is a
1794              * single file with an explicitly specified name in any
1795              * case, so there's no danger.
1796              */
1797             destfname = dupstr(targ);
1798         }
1799         attr = GetFileAttributes(destfname);
1800         exists = (attr != (DWORD) - 1);
1801
1802         if (act.action == SCP_SINK_DIR) {
1803             if (exists && (attr & FILE_ATTRIBUTE_DIRECTORY) == 0) {
1804                 run_err("%s: Not a directory", destfname);
1805                 continue;
1806             }
1807             if (!exists) {
1808                 if (!CreateDirectory(destfname, NULL)) {
1809                     run_err("%s: Cannot create directory", destfname);
1810                     continue;
1811                 }
1812             }
1813             sink(destfname, NULL);
1814             /* can we set the timestamp for directories ? */
1815             continue;
1816         }
1817
1818         f = CreateFile(destfname, GENERIC_WRITE, 0, NULL,
1819                        CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
1820         if (f == INVALID_HANDLE_VALUE) {
1821             run_err("%s: Cannot create file", destfname);
1822             continue;
1823         }
1824
1825         if (scp_accept_filexfer())
1826             return;
1827
1828         stat_bytes = 0;
1829         stat_starttime = time(NULL);
1830         stat_lasttime = 0;
1831         stat_name = stripslashes(destfname, 1);
1832
1833         received = 0;
1834         while (received < act.size) {
1835             char transbuf[4096];
1836             DWORD blksize, read, written;
1837             blksize = 4096;
1838             if (blksize > act.size - received)
1839                 blksize = act.size - received;
1840             read = scp_recv_filedata(transbuf, blksize);
1841             if (read <= 0)
1842                 bump("Lost connection");
1843             if (wrerror)
1844                 continue;
1845             if (!WriteFile(f, transbuf, read, &written, NULL) ||
1846                 written != read) {
1847                 wrerror = 1;
1848                 /* FIXME: in sftp we can actually abort the transfer */
1849                 if (statistics)
1850                     printf("\r%-25.25s | %50s\n",
1851                            stat_name,
1852                            "Write error.. waiting for end of file");
1853                 continue;
1854             }
1855             if (statistics) {
1856                 stat_bytes += read;
1857                 if (time(NULL) > stat_lasttime ||
1858                     received + read == act.size) {
1859                     stat_lasttime = time(NULL);
1860                     print_stats(stat_name, act.size, stat_bytes,
1861                                 stat_starttime, stat_lasttime);
1862                 }
1863             }
1864             received += read;
1865         }
1866         if (act.settime) {
1867             FILETIME actime, wrtime;
1868             TIME_POSIX_TO_WIN(act.atime, actime);
1869             TIME_POSIX_TO_WIN(act.mtime, wrtime);
1870             SetFileTime(f, NULL, &actime, &wrtime);
1871         }
1872
1873         CloseHandle(f);
1874         if (wrerror) {
1875             run_err("%s: Write error", destfname);
1876             continue;
1877         }
1878         (void) scp_finish_filerecv();
1879         sfree(destfname);
1880         sfree(act.buf);
1881     }
1882 }
1883
1884 /*
1885  * We will copy local files to a remote server.
1886  */
1887 static void toremote(int argc, char *argv[])
1888 {
1889     char *src, *targ, *host, *user;
1890     char *cmd;
1891     int i;
1892
1893     targ = argv[argc - 1];
1894
1895     /* Separate host from filename */
1896     host = targ;
1897     targ = colon(targ);
1898     if (targ == NULL)
1899         bump("targ == NULL in toremote()");
1900     *targ++ = '\0';
1901     if (*targ == '\0')
1902         targ = ".";
1903     /* Substitute "." for emtpy target */
1904
1905     /* Separate host and username */
1906     user = host;
1907     host = strrchr(host, '@');
1908     if (host == NULL) {
1909         host = user;
1910         user = NULL;
1911     } else {
1912         *host++ = '\0';
1913         if (*user == '\0')
1914             user = NULL;
1915     }
1916
1917     if (argc == 2) {
1918         /* Find out if the source filespec covers multiple files
1919            if so, we should set the targetshouldbedirectory flag */
1920         HANDLE fh;
1921         WIN32_FIND_DATA fdat;
1922         if (colon(argv[0]) != NULL)
1923             bump("%s: Remote to remote not supported", argv[0]);
1924         fh = FindFirstFile(argv[0], &fdat);
1925         if (fh == INVALID_HANDLE_VALUE)
1926             bump("%s: No such file or directory\n", argv[0]);
1927         if (FindNextFile(fh, &fdat))
1928             targetshouldbedirectory = 1;
1929         FindClose(fh);
1930     }
1931
1932     cmd = dupprintf("scp%s%s%s%s -t %s",
1933                     verbose ? " -v" : "",
1934                     recursive ? " -r" : "",
1935                     preserve ? " -p" : "",
1936                     targetshouldbedirectory ? " -d" : "", targ);
1937     do_cmd(host, user, cmd);
1938     sfree(cmd);
1939
1940     scp_source_setup(targ, targetshouldbedirectory);
1941
1942     for (i = 0; i < argc - 1; i++) {
1943         char *srcpath, *last;
1944         HANDLE dir;
1945         WIN32_FIND_DATA fdat;
1946         src = argv[i];
1947         if (colon(src) != NULL) {
1948             tell_user(stderr, "%s: Remote to remote not supported\n", src);
1949             errs++;
1950             continue;
1951         }
1952
1953         /*
1954          * Trim off the last pathname component of `src', to
1955          * provide the base pathname which will be prepended to
1956          * filenames returned from Find{First,Next}File.
1957          */
1958         srcpath = dupstr(src);
1959         last = stripslashes(srcpath, 1);
1960         *last = '\0';
1961
1962         dir = FindFirstFile(src, &fdat);
1963         if (dir == INVALID_HANDLE_VALUE) {
1964             run_err("%s: No such file or directory", src);
1965             continue;
1966         }
1967         do {
1968             char *filename;
1969             /*
1970              * Ensure that . and .. are never matched by wildcards,
1971              * but only by deliberate action.
1972              */
1973             if (!strcmp(fdat.cFileName, ".") ||
1974                 !strcmp(fdat.cFileName, "..")) {
1975                 /*
1976                  * Find*File has returned a special dir. We require
1977                  * that _either_ `src' ends in a backslash followed
1978                  * by that string, _or_ `src' is precisely that
1979                  * string.
1980                  */
1981                 int len = strlen(src), dlen = strlen(fdat.cFileName);
1982                 if (len == dlen && !strcmp(src, fdat.cFileName)) {
1983                     /* ok */ ;
1984                 } else if (len > dlen + 1 && src[len - dlen - 1] == '\\' &&
1985                            !strcmp(src + len - dlen, fdat.cFileName)) {
1986                     /* ok */ ;
1987                 } else
1988                     continue;          /* ignore this one */
1989             }
1990             filename = dupcat(srcpath, fdat.cFileName, NULL);
1991             source(filename);
1992             sfree(filename);
1993         } while (FindNextFile(dir, &fdat));
1994         FindClose(dir);
1995         sfree(srcpath);
1996     }
1997 }
1998
1999 /*
2000  *  We will copy files from a remote server to the local machine.
2001  */
2002 static void tolocal(int argc, char *argv[])
2003 {
2004     char *src, *targ, *host, *user;
2005     char *cmd;
2006
2007     if (argc != 2)
2008         bump("More than one remote source not supported");
2009
2010     src = argv[0];
2011     targ = argv[1];
2012
2013     /* Separate host from filename */
2014     host = src;
2015     src = colon(src);
2016     if (src == NULL)
2017         bump("Local to local copy not supported");
2018     *src++ = '\0';
2019     if (*src == '\0')
2020         src = ".";
2021     /* Substitute "." for empty filename */
2022
2023     /* Separate username and hostname */
2024     user = host;
2025     host = strrchr(host, '@');
2026     if (host == NULL) {
2027         host = user;
2028         user = NULL;
2029     } else {
2030         *host++ = '\0';
2031         if (*user == '\0')
2032             user = NULL;
2033     }
2034
2035     cmd = dupprintf("scp%s%s%s%s -f %s",
2036                     verbose ? " -v" : "",
2037                     recursive ? " -r" : "",
2038                     preserve ? " -p" : "",
2039                     targetshouldbedirectory ? " -d" : "", src);
2040     do_cmd(host, user, cmd);
2041     sfree(cmd);
2042
2043     if (scp_sink_setup(src, preserve, recursive))
2044         return;
2045
2046     sink(targ, src);
2047 }
2048
2049 /*
2050  *  We will issue a list command to get a remote directory.
2051  */
2052 static void get_dir_list(int argc, char *argv[])
2053 {
2054     char *src, *host, *user;
2055     char *cmd, *p, *q;
2056     char c;
2057
2058     src = argv[0];
2059
2060     /* Separate host from filename */
2061     host = src;
2062     src = colon(src);
2063     if (src == NULL)
2064         bump("Local to local copy not supported");
2065     *src++ = '\0';
2066     if (*src == '\0')
2067         src = ".";
2068     /* Substitute "." for empty filename */
2069
2070     /* Separate username and hostname */
2071     user = host;
2072     host = strrchr(host, '@');
2073     if (host == NULL) {
2074         host = user;
2075         user = NULL;
2076     } else {
2077         *host++ = '\0';
2078         if (*user == '\0')
2079             user = NULL;
2080     }
2081
2082     cmd = smalloc(4 * strlen(src) + 100);
2083     strcpy(cmd, "ls -la '");
2084     p = cmd + strlen(cmd);
2085     for (q = src; *q; q++) {
2086         if (*q == '\'') {
2087             *p++ = '\'';
2088             *p++ = '\\';
2089             *p++ = '\'';
2090             *p++ = '\'';
2091         } else {
2092             *p++ = *q;
2093         }
2094     }
2095     *p++ = '\'';
2096     *p = '\0';
2097
2098     do_cmd(host, user, cmd);
2099     sfree(cmd);
2100
2101     if (using_sftp) {
2102         scp_sftp_listdir(src);
2103     } else {
2104         while (ssh_scp_recv(&c, 1) > 0)
2105             tell_char(stdout, c);
2106     }
2107 }
2108
2109 /*
2110  *  Initialize the Win$ock driver.
2111  */
2112 static void init_winsock(void)
2113 {
2114     WORD winsock_ver;
2115     WSADATA wsadata;
2116
2117     winsock_ver = MAKEWORD(1, 1);
2118     if (WSAStartup(winsock_ver, &wsadata))
2119         bump("Unable to initialise WinSock");
2120     if (LOBYTE(wsadata.wVersion) != 1 || HIBYTE(wsadata.wVersion) != 1)
2121         bump("WinSock version is incompatible with 1.1");
2122 }
2123
2124 /*
2125  *  Short description of parameters.
2126  */
2127 static void usage(void)
2128 {
2129     printf("PuTTY Secure Copy client\n");
2130     printf("%s\n", ver);
2131     printf("Usage: pscp [options] [user@]host:source target\n");
2132     printf
2133         ("       pscp [options] source [source...] [user@]host:target\n");
2134     printf("       pscp [options] -ls user@host:filespec\n");
2135     printf("Options:\n");
2136     printf("  -p        preserve file attributes\n");
2137     printf("  -q        quiet, don't show statistics\n");
2138     printf("  -r        copy directories recursively\n");
2139     printf("  -v        show verbose messages\n");
2140     printf("  -load sessname  Load settings from saved session\n");
2141     printf("  -P port   connect to specified port\n");
2142     printf("  -l user   connect with specified username\n");
2143     printf("  -pw passw login with specified password\n");
2144     printf("  -1 -2     force use of particular SSH protocol version\n");
2145     printf("  -C        enable compression\n");
2146     printf("  -i key    private key file for authentication\n");
2147     printf("  -batch    disable all interactive prompts\n");
2148     printf("  -unsafe   allow server-side wildcards (DANGEROUS)\n");
2149 #if 0
2150     /*
2151      * -gui is an internal option, used by GUI front ends to get
2152      * pscp to pass progress reports back to them. It's not an
2153      * ordinary user-accessible option, so it shouldn't be part of
2154      * the command-line help. The only people who need to know
2155      * about it are programmers, and they can read the source.
2156      */
2157     printf
2158         ("  -gui hWnd GUI mode with the windows handle for receiving messages\n");
2159 #endif
2160     cleanup_exit(1);
2161 }
2162
2163 void cmdline_error(char *p, ...)
2164 {
2165     va_list ap;
2166     fprintf(stderr, "pscp: ");
2167     va_start(ap, p);
2168     vfprintf(stderr, p, ap);
2169     va_end(ap);
2170     fprintf(stderr, "\n      try typing just \"pscp\" for help\n");
2171     exit(1);
2172 }
2173
2174 /*
2175  *  Main program (no, really?)
2176  */
2177 int main(int argc, char *argv[])
2178 {
2179     int i;
2180
2181     default_protocol = PROT_TELNET;
2182
2183     flags = FLAG_STDERR;
2184     cmdline_tooltype = TOOLTYPE_FILETRANSFER;
2185     ssh_get_line = &console_get_line;
2186     init_winsock();
2187     sk_init();
2188
2189     for (i = 1; i < argc; i++) {
2190         int ret;
2191         if (argv[i][0] != '-')
2192             break;
2193         ret = cmdline_process_param(argv[i], i+1<argc?argv[i+1]:NULL, 1, &cfg);
2194         if (ret == -2) {
2195             cmdline_error("option \"%s\" requires an argument", argv[i]);
2196         } else if (ret == 2) {
2197             i++;               /* skip next argument */
2198         } else if (ret == 1) {
2199             /* We have our own verbosity in addition to `flags'. */
2200             if (flags & FLAG_VERBOSE)
2201                 verbose = 1;
2202         } else if (strcmp(argv[i], "-r") == 0) {
2203             recursive = 1;
2204         } else if (strcmp(argv[i], "-p") == 0) {
2205             preserve = 1;
2206         } else if (strcmp(argv[i], "-q") == 0) {
2207             statistics = 0;
2208         } else if (strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "-?") == 0) {
2209             usage();
2210         } else if (strcmp(argv[i], "-gui") == 0 && i + 1 < argc) {
2211             gui_hwnd = argv[++i];
2212             gui_mode = 1;
2213             console_batch_mode = TRUE;
2214         } else if (strcmp(argv[i], "-ls") == 0) {
2215             list = 1;
2216         } else if (strcmp(argv[i], "-batch") == 0) {
2217             console_batch_mode = 1;
2218         } else if (strcmp(argv[i], "-unsafe") == 0) {
2219             scp_unsafe_mode = 1;
2220         } else if (strcmp(argv[i], "--") == 0) {
2221             i++;
2222             break;
2223         } else {
2224             cmdline_error("unknown option \"%s\"", argv[i]);
2225         }
2226     }
2227     argc -= i;
2228     argv += i;
2229     back = NULL;
2230
2231     if (list) {
2232         if (argc != 1)
2233             usage();
2234         get_dir_list(argc, argv);
2235
2236     } else {
2237
2238         if (argc < 2)
2239             usage();
2240         if (argc > 2)
2241             targetshouldbedirectory = 1;
2242
2243         if (colon(argv[argc - 1]) != NULL)
2244             toremote(argc, argv);
2245         else
2246             tolocal(argc, argv);
2247     }
2248
2249     if (back != NULL && back->socket(backhandle) != NULL) {
2250         char ch;
2251         back->special(backhandle, TS_EOF);
2252         ssh_scp_recv(&ch, 1);
2253     }
2254     WSACleanup();
2255     random_save_seed();
2256
2257     /* GUI Adaptation - August 2000 */
2258     if (gui_mode) {
2259         unsigned int msg_id = WM_RET_ERR_CNT;
2260         if (list)
2261             msg_id = WM_LS_RET_ERR_CNT;
2262         while (!PostMessage
2263                ((HWND) atoi(gui_hwnd), msg_id, (WPARAM) errs,
2264                 0 /*lParam */ ))SleepEx(1000, TRUE);
2265     }
2266     return (errs == 0 ? 0 : 1);
2267 }
2268
2269 /* end */