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