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