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