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