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