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