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