]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - pscp.c
Merge tag '0.65'
[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  * Return a pointer to the portion of str that comes after the last
610  * slash (or backslash or colon, if `local' is TRUE).
611  *
612  * This function has the annoying strstr() property of taking a const
613  * char * and returning a char *. You should treat it as if it was a
614  * pair of overloaded functions, one mapping mutable->mutable and the
615  * other const->const :-(
616  */
617 static char *stripslashes(const char *str, int local)
618 {
619     char *p;
620
621     if (local) {
622         p = strchr(str, ':');
623         if (p) str = p+1;
624     }
625
626     p = strrchr(str, '/');
627     if (p) str = p+1;
628
629     if (local) {
630         p = strrchr(str, '\\');
631         if (p) str = p+1;
632     }
633
634     return (char *)str;
635 }
636
637 /*
638  * Determine whether a string is entirely composed of dots.
639  */
640 static int is_dots(char *str)
641 {
642     return str[strspn(str, ".")] == '\0';
643 }
644
645 /*
646  *  Wait for a response from the other side.
647  *  Return 0 if ok, -1 if error.
648  */
649 static int response(void)
650 {
651     char ch, resp, rbuf[2048];
652     int p;
653
654     if (ssh_scp_recv((unsigned char *) &resp, 1) <= 0)
655         bump("Lost connection");
656
657     p = 0;
658     switch (resp) {
659       case 0:                          /* ok */
660         return (0);
661       default:
662         rbuf[p++] = resp;
663         /* fallthrough */
664       case 1:                          /* error */
665       case 2:                          /* fatal error */
666         do {
667             if (ssh_scp_recv((unsigned char *) &ch, 1) <= 0)
668                 bump("Protocol error: Lost connection");
669             rbuf[p++] = ch;
670         } while (p < sizeof(rbuf) && ch != '\n');
671         rbuf[p - 1] = '\0';
672         if (resp == 1)
673             tell_user(stderr, "%s", rbuf);
674         else
675             bump("%s", rbuf);
676         errs++;
677         return (-1);
678     }
679 }
680
681 int sftp_recvdata(char *buf, int len)
682 {
683     return ssh_scp_recv((unsigned char *) buf, len);
684 }
685 int sftp_senddata(char *buf, int len)
686 {
687     back->send(backhandle, buf, len);
688     return 1;
689 }
690
691 /* ----------------------------------------------------------------------
692  * sftp-based replacement for the hacky `pscp -ls'.
693  */
694 static int sftp_ls_compare(const void *av, const void *bv)
695 {
696     const struct fxp_name *a = (const struct fxp_name *) av;
697     const struct fxp_name *b = (const struct fxp_name *) bv;
698     return strcmp(a->filename, b->filename);
699 }
700 void scp_sftp_listdir(const char *dirname)
701 {
702     struct fxp_handle *dirh;
703     struct fxp_names *names;
704     struct fxp_name *ournames;
705     struct sftp_packet *pktin;
706     struct sftp_request *req;
707     int nnames, namesize;
708     int i;
709
710     if (!fxp_init()) {
711         tell_user(stderr, "unable to initialise SFTP: %s", fxp_error());
712         errs++;
713         return;
714     }
715
716     printf("Listing directory %s\n", dirname);
717
718     req = fxp_opendir_send(dirname);
719     pktin = sftp_wait_for_reply(req);
720     dirh = fxp_opendir_recv(pktin, req);
721
722     if (dirh == NULL) {
723         printf("Unable to open %s: %s\n", dirname, fxp_error());
724     } else {
725         nnames = namesize = 0;
726         ournames = NULL;
727
728         while (1) {
729
730             req = fxp_readdir_send(dirh);
731             pktin = sftp_wait_for_reply(req);
732             names = fxp_readdir_recv(pktin, req);
733
734             if (names == NULL) {
735                 if (fxp_error_type() == SSH_FX_EOF)
736                     break;
737                 printf("Reading directory %s: %s\n", dirname, fxp_error());
738                 break;
739             }
740             if (names->nnames == 0) {
741                 fxp_free_names(names);
742                 break;
743             }
744
745             if (nnames + names->nnames >= namesize) {
746                 namesize += names->nnames + 128;
747                 ournames = sresize(ournames, namesize, struct fxp_name);
748             }
749
750             for (i = 0; i < names->nnames; i++)
751                 ournames[nnames++] = names->names[i];
752             names->nnames = 0;         /* prevent free_names */
753             fxp_free_names(names);
754         }
755         req = fxp_close_send(dirh);
756         pktin = sftp_wait_for_reply(req);
757         fxp_close_recv(pktin, req);
758
759         /*
760          * Now we have our filenames. Sort them by actual file
761          * name, and then output the longname parts.
762          */
763         if (nnames > 0)
764             qsort(ournames, nnames, sizeof(*ournames), sftp_ls_compare);
765
766         /*
767          * And print them.
768          */
769         for (i = 0; i < nnames; i++)
770             printf("%s\n", ournames[i].longname);
771
772         sfree(ournames);
773     }
774 }
775
776 /* ----------------------------------------------------------------------
777  * Helper routines that contain the actual SCP protocol elements,
778  * implemented both as SCP1 and SFTP.
779  */
780
781 static struct scp_sftp_dirstack {
782     struct scp_sftp_dirstack *next;
783     struct fxp_name *names;
784     int namepos, namelen;
785     char *dirpath;
786     char *wildcard;
787     int matched_something;             /* wildcard match set was non-empty */
788 } *scp_sftp_dirstack_head;
789 static char *scp_sftp_remotepath, *scp_sftp_currentname;
790 static char *scp_sftp_wildcard;
791 static int scp_sftp_targetisdir, scp_sftp_donethistarget;
792 static int scp_sftp_preserve, scp_sftp_recursive;
793 static unsigned long scp_sftp_mtime, scp_sftp_atime;
794 static int scp_has_times;
795 static struct fxp_handle *scp_sftp_filehandle;
796 static struct fxp_xfer *scp_sftp_xfer;
797 static uint64 scp_sftp_fileoffset;
798
799 int scp_source_setup(const char *target, int shouldbedir)
800 {
801     if (using_sftp) {
802         /*
803          * Find out whether the target filespec is in fact a
804          * directory.
805          */
806         struct sftp_packet *pktin;
807         struct sftp_request *req;
808         struct fxp_attrs attrs;
809         int ret;
810
811         if (!fxp_init()) {
812             tell_user(stderr, "unable to initialise SFTP: %s", fxp_error());
813             errs++;
814             return 1;
815         }
816
817         req = fxp_stat_send(target);
818         pktin = sftp_wait_for_reply(req);
819         ret = fxp_stat_recv(pktin, req, &attrs);
820
821         if (!ret || !(attrs.flags & SSH_FILEXFER_ATTR_PERMISSIONS))
822             scp_sftp_targetisdir = 0;
823         else
824             scp_sftp_targetisdir = (attrs.permissions & 0040000) != 0;
825
826         if (shouldbedir && !scp_sftp_targetisdir) {
827             bump("pscp: remote filespec %s: not a directory\n", target);
828         }
829
830         scp_sftp_remotepath = dupstr(target);
831
832         scp_has_times = 0;
833     } else {
834         (void) response();
835     }
836     return 0;
837 }
838
839 int scp_send_errmsg(char *str)
840 {
841     if (using_sftp) {
842         /* do nothing; we never need to send our errors to the server */
843     } else {
844         back->send(backhandle, "\001", 1);/* scp protocol error prefix */
845         back->send(backhandle, str, strlen(str));
846     }
847     return 0;                          /* can't fail */
848 }
849
850 int scp_send_filetimes(unsigned long mtime, unsigned long atime)
851 {
852     if (using_sftp) {
853         scp_sftp_mtime = mtime;
854         scp_sftp_atime = atime;
855         scp_has_times = 1;
856         return 0;
857     } else {
858         char buf[80];
859         sprintf(buf, "T%lu 0 %lu 0\n", mtime, atime);
860         back->send(backhandle, buf, strlen(buf));
861         return response();
862     }
863 }
864
865 int scp_send_filename(const char *name, uint64 size, int permissions)
866 {
867     if (using_sftp) {
868         char *fullname;
869         struct sftp_packet *pktin;
870         struct sftp_request *req;
871         struct fxp_attrs attrs;
872
873         if (scp_sftp_targetisdir) {
874             fullname = dupcat(scp_sftp_remotepath, "/", name, NULL);
875         } else {
876             fullname = dupstr(scp_sftp_remotepath);
877         }
878
879         attrs.flags = 0;
880         PUT_PERMISSIONS(attrs, permissions);
881
882         req = fxp_open_send(fullname,
883                             SSH_FXF_WRITE | SSH_FXF_CREAT | SSH_FXF_TRUNC,
884                             &attrs);
885         pktin = sftp_wait_for_reply(req);
886         scp_sftp_filehandle = fxp_open_recv(pktin, req);
887
888         if (!scp_sftp_filehandle) {
889             tell_user(stderr, "pscp: unable to open %s: %s",
890                       fullname, fxp_error());
891             sfree(fullname);
892             errs++;
893             return 1;
894         }
895         scp_sftp_fileoffset = uint64_make(0, 0);
896         scp_sftp_xfer = xfer_upload_init(scp_sftp_filehandle,
897                                          scp_sftp_fileoffset);
898         sfree(fullname);
899         return 0;
900     } else {
901         char buf[40];
902         char sizestr[40];
903         uint64_decimal(size, sizestr);
904         if (permissions < 0)
905             permissions = 0644;
906         sprintf(buf, "C%04o %s ", (int)(permissions & 07777), sizestr);
907         back->send(backhandle, buf, strlen(buf));
908         back->send(backhandle, name, strlen(name));
909         back->send(backhandle, "\n", 1);
910         return response();
911     }
912 }
913
914 int scp_send_filedata(char *data, int len)
915 {
916     if (using_sftp) {
917         int ret;
918         struct sftp_packet *pktin;
919
920         if (!scp_sftp_filehandle) {
921             return 1;
922         }
923
924         while (!xfer_upload_ready(scp_sftp_xfer)) {
925             pktin = sftp_recv();
926             ret = xfer_upload_gotpkt(scp_sftp_xfer, pktin);
927             if (ret <= 0) {
928                 tell_user(stderr, "error while writing: %s", fxp_error());
929                 if (ret == INT_MIN)        /* pktin not even freed */
930                     sfree(pktin);
931                 errs++;
932                 return 1;
933             }
934         }
935
936         xfer_upload_data(scp_sftp_xfer, data, len);
937
938         scp_sftp_fileoffset = uint64_add32(scp_sftp_fileoffset, len);
939         return 0;
940     } else {
941         int bufsize = back->send(backhandle, data, len);
942
943         /*
944          * If the network transfer is backing up - that is, the
945          * remote site is not accepting data as fast as we can
946          * produce it - then we must loop on network events until
947          * we have space in the buffer again.
948          */
949         while (bufsize > MAX_SCP_BUFSIZE) {
950             if (ssh_sftp_loop_iteration() < 0)
951                 return 1;
952             bufsize = back->sendbuffer(backhandle);
953         }
954
955         return 0;
956     }
957 }
958
959 int scp_send_finish(void)
960 {
961     if (using_sftp) {
962         struct fxp_attrs attrs;
963         struct sftp_packet *pktin;
964         struct sftp_request *req;
965         int ret;
966
967         while (!xfer_done(scp_sftp_xfer)) {
968             pktin = sftp_recv();
969             ret = xfer_upload_gotpkt(scp_sftp_xfer, pktin);
970             if (ret <= 0) {
971                 tell_user(stderr, "error while writing: %s", fxp_error());
972                 if (ret == INT_MIN)        /* pktin not even freed */
973                     sfree(pktin);
974                 errs++;
975                 return 1;
976             }
977         }
978         xfer_cleanup(scp_sftp_xfer);
979
980         if (!scp_sftp_filehandle) {
981             return 1;
982         }
983         if (scp_has_times) {
984             attrs.flags = SSH_FILEXFER_ATTR_ACMODTIME;
985             attrs.atime = scp_sftp_atime;
986             attrs.mtime = scp_sftp_mtime;
987             req = fxp_fsetstat_send(scp_sftp_filehandle, attrs);
988             pktin = sftp_wait_for_reply(req);
989             ret = fxp_fsetstat_recv(pktin, req);
990             if (!ret) {
991                 tell_user(stderr, "unable to set file times: %s", fxp_error());
992                 errs++;
993             }
994         }
995         req = fxp_close_send(scp_sftp_filehandle);
996         pktin = sftp_wait_for_reply(req);
997         fxp_close_recv(pktin, req);
998         scp_has_times = 0;
999         return 0;
1000     } else {
1001         back->send(backhandle, "", 1);
1002         return response();
1003     }
1004 }
1005
1006 char *scp_save_remotepath(void)
1007 {
1008     if (using_sftp)
1009         return scp_sftp_remotepath;
1010     else
1011         return NULL;
1012 }
1013
1014 void scp_restore_remotepath(char *data)
1015 {
1016     if (using_sftp)
1017         scp_sftp_remotepath = data;
1018 }
1019
1020 int scp_send_dirname(const char *name, int modes)
1021 {
1022     if (using_sftp) {
1023         char *fullname;
1024         char const *err;
1025         struct fxp_attrs attrs;
1026         struct sftp_packet *pktin;
1027         struct sftp_request *req;
1028         int ret;
1029
1030         if (scp_sftp_targetisdir) {
1031             fullname = dupcat(scp_sftp_remotepath, "/", name, NULL);
1032         } else {
1033             fullname = dupstr(scp_sftp_remotepath);
1034         }
1035
1036         /*
1037          * We don't worry about whether we managed to create the
1038          * directory, because if it exists already it's OK just to
1039          * use it. Instead, we will stat it afterwards, and if it
1040          * exists and is a directory we will assume we were either
1041          * successful or it didn't matter.
1042          */
1043         req = fxp_mkdir_send(fullname);
1044         pktin = sftp_wait_for_reply(req);
1045         ret = fxp_mkdir_recv(pktin, req);
1046
1047         if (!ret)
1048             err = fxp_error();
1049         else
1050             err = "server reported no error";
1051
1052         req = fxp_stat_send(fullname);
1053         pktin = sftp_wait_for_reply(req);
1054         ret = fxp_stat_recv(pktin, req, &attrs);
1055
1056         if (!ret || !(attrs.flags & SSH_FILEXFER_ATTR_PERMISSIONS) ||
1057             !(attrs.permissions & 0040000)) {
1058             tell_user(stderr, "unable to create directory %s: %s",
1059                       fullname, err);
1060             sfree(fullname);
1061             errs++;
1062             return 1;
1063         }
1064
1065         scp_sftp_remotepath = fullname;
1066
1067         return 0;
1068     } else {
1069         char buf[40];
1070         sprintf(buf, "D%04o 0 ", modes);
1071         back->send(backhandle, buf, strlen(buf));
1072         back->send(backhandle, name, strlen(name));
1073         back->send(backhandle, "\n", 1);
1074         return response();
1075     }
1076 }
1077
1078 int scp_send_enddir(void)
1079 {
1080     if (using_sftp) {
1081         sfree(scp_sftp_remotepath);
1082         return 0;
1083     } else {
1084         back->send(backhandle, "E\n", 2);
1085         return response();
1086     }
1087 }
1088
1089 /*
1090  * Yes, I know; I have an scp_sink_setup _and_ an scp_sink_init.
1091  * That's bad. The difference is that scp_sink_setup is called once
1092  * right at the start, whereas scp_sink_init is called to
1093  * initialise every level of recursion in the protocol.
1094  */
1095 int scp_sink_setup(const char *source, int preserve, int recursive)
1096 {
1097     if (using_sftp) {
1098         char *newsource;
1099
1100         if (!fxp_init()) {
1101             tell_user(stderr, "unable to initialise SFTP: %s", fxp_error());
1102             errs++;
1103             return 1;
1104         }
1105         /*
1106          * It's possible that the source string we've been given
1107          * contains a wildcard. If so, we must split the directory
1108          * away from the wildcard itself (throwing an error if any
1109          * wildcardness comes before the final slash) and arrange
1110          * things so that a dirstack entry will be set up.
1111          */
1112         newsource = snewn(1+strlen(source), char);
1113         if (!wc_unescape(newsource, source)) {
1114             /* Yes, here we go; it's a wildcard. Bah. */
1115             char *dupsource, *lastpart, *dirpart, *wildcard;
1116
1117             sfree(newsource);
1118
1119             dupsource = dupstr(source);
1120             lastpart = stripslashes(dupsource, 0);
1121             wildcard = dupstr(lastpart);
1122             *lastpart = '\0';
1123             if (*dupsource && dupsource[1]) {
1124                 /*
1125                  * The remains of dupsource are at least two
1126                  * characters long, meaning the pathname wasn't
1127                  * empty or just `/'. Hence, we remove the trailing
1128                  * slash.
1129                  */
1130                 lastpart[-1] = '\0';
1131             } else if (!*dupsource) {
1132                 /*
1133                  * The remains of dupsource are _empty_ - the whole
1134                  * pathname was a wildcard. Hence we need to
1135                  * replace it with ".".
1136                  */
1137                 sfree(dupsource);
1138                 dupsource = dupstr(".");
1139             }
1140
1141             /*
1142              * Now we have separated our string into dupsource (the
1143              * directory part) and wildcard. Both of these will
1144              * need freeing at some point. Next step is to remove
1145              * wildcard escapes from the directory part, throwing
1146              * an error if it contains a real wildcard.
1147              */
1148             dirpart = snewn(1+strlen(dupsource), char);
1149             if (!wc_unescape(dirpart, dupsource)) {
1150                 tell_user(stderr, "%s: multiple-level wildcards unsupported",
1151                           source);
1152                 errs++;
1153                 sfree(dirpart);
1154                 sfree(wildcard);
1155                 sfree(dupsource);
1156                 return 1;
1157             }
1158
1159             /*
1160              * Now we have dirpart (unescaped, ie a valid remote
1161              * path), and wildcard (a wildcard). This will be
1162              * sufficient to arrange a dirstack entry.
1163              */
1164             scp_sftp_remotepath = dirpart;
1165             scp_sftp_wildcard = wildcard;
1166             sfree(dupsource);
1167         } else {
1168             scp_sftp_remotepath = newsource;
1169             scp_sftp_wildcard = NULL;
1170         }
1171         scp_sftp_preserve = preserve;
1172         scp_sftp_recursive = recursive;
1173         scp_sftp_donethistarget = 0;
1174         scp_sftp_dirstack_head = NULL;
1175     }
1176     return 0;
1177 }
1178
1179 int scp_sink_init(void)
1180 {
1181     if (!using_sftp) {
1182         back->send(backhandle, "", 1);
1183     }
1184     return 0;
1185 }
1186
1187 #define SCP_SINK_FILE   1
1188 #define SCP_SINK_DIR    2
1189 #define SCP_SINK_ENDDIR 3
1190 #define SCP_SINK_RETRY  4              /* not an action; just try again */
1191 struct scp_sink_action {
1192     int action;                        /* FILE, DIR, ENDDIR */
1193     char *buf;                         /* will need freeing after use */
1194     char *name;                        /* filename or dirname (not ENDDIR) */
1195     long permissions;          /* access permissions (not ENDDIR) */
1196     uint64 size;                       /* file size (not ENDDIR) */
1197     int settime;                       /* 1 if atime and mtime are filled */
1198     unsigned long atime, mtime;        /* access times for the file */
1199 };
1200
1201 int scp_get_sink_action(struct scp_sink_action *act)
1202 {
1203     if (using_sftp) {
1204         char *fname;
1205         int must_free_fname;
1206         struct fxp_attrs attrs;
1207         struct sftp_packet *pktin;
1208         struct sftp_request *req;
1209         int ret;
1210
1211         if (!scp_sftp_dirstack_head) {
1212             if (!scp_sftp_donethistarget) {
1213                 /*
1214                  * Simple case: we are only dealing with one file.
1215                  */
1216                 fname = scp_sftp_remotepath;
1217                 must_free_fname = 0;
1218                 scp_sftp_donethistarget = 1;
1219             } else {
1220                 /*
1221                  * Even simpler case: one file _which we've done_.
1222                  * Return 1 (finished).
1223                  */
1224                 return 1;
1225             }
1226         } else {
1227             /*
1228              * We're now in the middle of stepping through a list
1229              * of names returned from fxp_readdir(); so let's carry
1230              * on.
1231              */
1232             struct scp_sftp_dirstack *head = scp_sftp_dirstack_head;
1233             while (head->namepos < head->namelen &&
1234                    (is_dots(head->names[head->namepos].filename) ||
1235                     (head->wildcard &&
1236                      !wc_match(head->wildcard,
1237                                head->names[head->namepos].filename))))
1238                 head->namepos++;       /* skip . and .. */
1239             if (head->namepos < head->namelen) {
1240                 head->matched_something = 1;
1241                 fname = dupcat(head->dirpath, "/",
1242                                head->names[head->namepos++].filename,
1243                                NULL);
1244                 must_free_fname = 1;
1245             } else {
1246                 /*
1247                  * We've come to the end of the list; pop it off
1248                  * the stack and return an ENDDIR action (or RETRY
1249                  * if this was a wildcard match).
1250                  */
1251                 if (head->wildcard) {
1252                     act->action = SCP_SINK_RETRY;
1253                     if (!head->matched_something) {
1254                         tell_user(stderr, "pscp: wildcard '%s' matched "
1255                                   "no files", head->wildcard);
1256                         errs++;
1257                     }
1258                     sfree(head->wildcard);
1259
1260                 } else {
1261                     act->action = SCP_SINK_ENDDIR;
1262                 }
1263
1264                 sfree(head->dirpath);
1265                 sfree(head->names);
1266                 scp_sftp_dirstack_head = head->next;
1267                 sfree(head);
1268
1269                 return 0;
1270             }
1271         }
1272
1273         /*
1274          * Now we have a filename. Stat it, and see if it's a file
1275          * or a directory.
1276          */
1277         req = fxp_stat_send(fname);
1278         pktin = sftp_wait_for_reply(req);
1279         ret = fxp_stat_recv(pktin, req, &attrs);
1280
1281         if (!ret || !(attrs.flags & SSH_FILEXFER_ATTR_PERMISSIONS)) {
1282             tell_user(stderr, "unable to identify %s: %s", fname,
1283                       ret ? "file type not supplied" : fxp_error());
1284             if (must_free_fname) sfree(fname);
1285             errs++;
1286             return 1;
1287         }
1288
1289         if (attrs.permissions & 0040000) {
1290             struct scp_sftp_dirstack *newitem;
1291             struct fxp_handle *dirhandle;
1292             int nnames, namesize;
1293             struct fxp_name *ournames;
1294             struct fxp_names *names;
1295
1296             /*
1297              * It's a directory. If we're not in recursive mode,
1298              * this merits a complaint (which is fatal if the name
1299              * was specified directly, but not if it was matched by
1300              * a wildcard).
1301              * 
1302              * We skip this complaint completely if
1303              * scp_sftp_wildcard is set, because that's an
1304              * indication that we're not actually supposed to
1305              * _recursively_ transfer the dir, just scan it for
1306              * things matching the wildcard.
1307              */
1308             if (!scp_sftp_recursive && !scp_sftp_wildcard) {
1309                 tell_user(stderr, "pscp: %s: is a directory", fname);
1310                 errs++;
1311                 if (must_free_fname) sfree(fname);
1312                 if (scp_sftp_dirstack_head) {
1313                     act->action = SCP_SINK_RETRY;
1314                     return 0;
1315                 } else {
1316                     return 1;
1317                 }
1318             }
1319
1320             /*
1321              * Otherwise, the fun begins. We must fxp_opendir() the
1322              * directory, slurp the filenames into memory, return
1323              * SCP_SINK_DIR (unless this is a wildcard match), and
1324              * set targetisdir. The next time we're called, we will
1325              * run through the list of filenames one by one,
1326              * matching them against a wildcard if present.
1327              * 
1328              * If targetisdir is _already_ set (meaning we're
1329              * already in the middle of going through another such
1330              * list), we must push the other (target,namelist) pair
1331              * on a stack.
1332              */
1333             req = fxp_opendir_send(fname);
1334             pktin = sftp_wait_for_reply(req);
1335             dirhandle = fxp_opendir_recv(pktin, req);
1336
1337             if (!dirhandle) {
1338                 tell_user(stderr, "pscp: unable to open directory %s: %s",
1339                           fname, fxp_error());
1340                 if (must_free_fname) sfree(fname);
1341                 errs++;
1342                 return 1;
1343             }
1344             nnames = namesize = 0;
1345             ournames = NULL;
1346             while (1) {
1347                 int i;
1348
1349                 req = fxp_readdir_send(dirhandle);
1350                 pktin = sftp_wait_for_reply(req);
1351                 names = fxp_readdir_recv(pktin, req);
1352
1353                 if (names == NULL) {
1354                     if (fxp_error_type() == SSH_FX_EOF)
1355                         break;
1356                     tell_user(stderr, "pscp: reading directory %s: %s",
1357                               fname, fxp_error());
1358
1359                     req = fxp_close_send(dirhandle);
1360                     pktin = sftp_wait_for_reply(req);
1361                     fxp_close_recv(pktin, req);
1362
1363                     if (must_free_fname) sfree(fname);
1364                     sfree(ournames);
1365                     errs++;
1366                     return 1;
1367                 }
1368                 if (names->nnames == 0) {
1369                     fxp_free_names(names);
1370                     break;
1371                 }
1372                 if (nnames + names->nnames >= namesize) {
1373                     namesize += names->nnames + 128;
1374                     ournames = sresize(ournames, namesize, struct fxp_name);
1375                 }
1376                 for (i = 0; i < names->nnames; i++) {
1377                     if (!strcmp(names->names[i].filename, ".") ||
1378                         !strcmp(names->names[i].filename, "..")) {
1379                         /*
1380                          * . and .. are normal consequences of
1381                          * reading a directory, and aren't worth
1382                          * complaining about.
1383                          */
1384                     } else if (!vet_filename(names->names[i].filename)) {
1385                         tell_user(stderr, "ignoring potentially dangerous server-"
1386                                   "supplied filename '%s'",
1387                                   names->names[i].filename);
1388                     } else
1389                         ournames[nnames++] = names->names[i];
1390                 }
1391                 names->nnames = 0;             /* prevent free_names */
1392                 fxp_free_names(names);
1393             }
1394             req = fxp_close_send(dirhandle);
1395             pktin = sftp_wait_for_reply(req);
1396             fxp_close_recv(pktin, req);
1397
1398             newitem = snew(struct scp_sftp_dirstack);
1399             newitem->next = scp_sftp_dirstack_head;
1400             newitem->names = ournames;
1401             newitem->namepos = 0;
1402             newitem->namelen = nnames;
1403             if (must_free_fname)
1404                 newitem->dirpath = fname;
1405             else
1406                 newitem->dirpath = dupstr(fname);
1407             if (scp_sftp_wildcard) {
1408                 newitem->wildcard = scp_sftp_wildcard;
1409                 newitem->matched_something = 0;
1410                 scp_sftp_wildcard = NULL;
1411             } else {
1412                 newitem->wildcard = NULL;
1413             }
1414             scp_sftp_dirstack_head = newitem;
1415
1416             if (newitem->wildcard) {
1417                 act->action = SCP_SINK_RETRY;
1418             } else {
1419                 act->action = SCP_SINK_DIR;
1420                 act->buf = dupstr(stripslashes(fname, 0));
1421                 act->name = act->buf;
1422                 act->size = uint64_make(0,0);     /* duhh, it's a directory */
1423                 act->permissions = 07777 & attrs.permissions;
1424                 if (scp_sftp_preserve &&
1425                     (attrs.flags & SSH_FILEXFER_ATTR_ACMODTIME)) {
1426                     act->atime = attrs.atime;
1427                     act->mtime = attrs.mtime;
1428                     act->settime = 1;
1429                 } else
1430                     act->settime = 0;
1431             }
1432             return 0;
1433
1434         } else {
1435             /*
1436              * It's a file. Return SCP_SINK_FILE.
1437              */
1438             act->action = SCP_SINK_FILE;
1439             act->buf = dupstr(stripslashes(fname, 0));
1440             act->name = act->buf;
1441             if (attrs.flags & SSH_FILEXFER_ATTR_SIZE) {
1442                 act->size = attrs.size;
1443             } else
1444                 act->size = uint64_make(ULONG_MAX,ULONG_MAX);   /* no idea */
1445             act->permissions = 07777 & attrs.permissions;
1446             if (scp_sftp_preserve &&
1447                 (attrs.flags & SSH_FILEXFER_ATTR_ACMODTIME)) {
1448                 act->atime = attrs.atime;
1449                 act->mtime = attrs.mtime;
1450                 act->settime = 1;
1451             } else
1452                 act->settime = 0;
1453             if (must_free_fname)
1454                 scp_sftp_currentname = fname;
1455             else
1456                 scp_sftp_currentname = dupstr(fname);
1457             return 0;
1458         }
1459
1460     } else {
1461         int done = 0;
1462         int i, bufsize;
1463         int action;
1464         char ch;
1465
1466         act->settime = 0;
1467         act->buf = NULL;
1468         bufsize = 0;
1469
1470         while (!done) {
1471             if (ssh_scp_recv((unsigned char *) &ch, 1) <= 0)
1472                 return 1;
1473             if (ch == '\n')
1474                 bump("Protocol error: Unexpected newline");
1475             i = 0;
1476             action = ch;
1477             do {
1478                 if (ssh_scp_recv((unsigned char *) &ch, 1) <= 0)
1479                     bump("Lost connection");
1480                 if (i >= bufsize) {
1481                     bufsize = i + 128;
1482                     act->buf = sresize(act->buf, bufsize, char);
1483                 }
1484                 act->buf[i++] = ch;
1485             } while (ch != '\n');
1486             act->buf[i - 1] = '\0';
1487             switch (action) {
1488               case '\01':                      /* error */
1489                 tell_user(stderr, "%s", act->buf);
1490                 errs++;
1491                 continue;                      /* go round again */
1492               case '\02':                      /* fatal error */
1493                 bump("%s", act->buf);
1494               case 'E':
1495                 back->send(backhandle, "", 1);
1496                 act->action = SCP_SINK_ENDDIR;
1497                 return 0;
1498               case 'T':
1499                 if (sscanf(act->buf, "%ld %*d %ld %*d",
1500                            &act->mtime, &act->atime) == 2) {
1501                     act->settime = 1;
1502                     back->send(backhandle, "", 1);
1503                     continue;          /* go round again */
1504                 }
1505                 bump("Protocol error: Illegal time format");
1506               case 'C':
1507               case 'D':
1508                 act->action = (action == 'C' ? SCP_SINK_FILE : SCP_SINK_DIR);
1509                 break;
1510               default:
1511                 bump("Protocol error: Expected control record");
1512             }
1513             /*
1514              * We will go round this loop only once, unless we hit
1515              * `continue' above.
1516              */
1517             done = 1;
1518         }
1519
1520         /*
1521          * If we get here, we must have seen SCP_SINK_FILE or
1522          * SCP_SINK_DIR.
1523          */
1524         {
1525             char sizestr[40];
1526         
1527             if (sscanf(act->buf, "%lo %s %n", &act->permissions,
1528                        sizestr, &i) != 2)
1529                 bump("Protocol error: Illegal file descriptor format");
1530             act->size = uint64_from_decimal(sizestr);
1531             act->name = act->buf + i;
1532             return 0;
1533         }
1534     }
1535 }
1536
1537 int scp_accept_filexfer(void)
1538 {
1539     if (using_sftp) {
1540         struct sftp_packet *pktin;
1541         struct sftp_request *req;
1542
1543         req = fxp_open_send(scp_sftp_currentname, SSH_FXF_READ, NULL);
1544         pktin = sftp_wait_for_reply(req);
1545         scp_sftp_filehandle = fxp_open_recv(pktin, req);
1546
1547         if (!scp_sftp_filehandle) {
1548             tell_user(stderr, "pscp: unable to open %s: %s",
1549                       scp_sftp_currentname, fxp_error());
1550             errs++;
1551             return 1;
1552         }
1553         scp_sftp_fileoffset = uint64_make(0, 0);
1554         scp_sftp_xfer = xfer_download_init(scp_sftp_filehandle,
1555                                            scp_sftp_fileoffset);
1556         sfree(scp_sftp_currentname);
1557         return 0;
1558     } else {
1559         back->send(backhandle, "", 1);
1560         return 0;                      /* can't fail */
1561     }
1562 }
1563
1564 int scp_recv_filedata(char *data, int len)
1565 {
1566     if (using_sftp) {
1567         struct sftp_packet *pktin;
1568         int ret, actuallen;
1569         void *vbuf;
1570
1571         xfer_download_queue(scp_sftp_xfer);
1572         pktin = sftp_recv();
1573         ret = xfer_download_gotpkt(scp_sftp_xfer, pktin);
1574         if (ret <= 0) {
1575             tell_user(stderr, "pscp: error while reading: %s", fxp_error());
1576             if (ret == INT_MIN)        /* pktin not even freed */
1577                 sfree(pktin);
1578             errs++;
1579             return -1;
1580         }
1581
1582         if (xfer_download_data(scp_sftp_xfer, &vbuf, &actuallen)) {
1583             /*
1584              * This assertion relies on the fact that the natural
1585              * block size used in the xfer manager is at most that
1586              * used in this module. I don't like crossing layers in
1587              * this way, but it'll do for now.
1588              */
1589             assert(actuallen <= len);
1590             memcpy(data, vbuf, actuallen);
1591             sfree(vbuf);
1592         } else
1593             actuallen = 0;
1594
1595         scp_sftp_fileoffset = uint64_add32(scp_sftp_fileoffset, actuallen);
1596
1597         return actuallen;
1598     } else {
1599         return ssh_scp_recv((unsigned char *) data, len);
1600     }
1601 }
1602
1603 int scp_finish_filerecv(void)
1604 {
1605     if (using_sftp) {
1606         struct sftp_packet *pktin;
1607         struct sftp_request *req;
1608
1609         /*
1610          * Ensure that xfer_done() will work correctly, so we can
1611          * clean up any outstanding requests from the file
1612          * transfer.
1613          */
1614         xfer_set_error(scp_sftp_xfer);
1615         while (!xfer_done(scp_sftp_xfer)) {
1616             void *vbuf;
1617             int ret, len;
1618
1619             pktin = sftp_recv();
1620             ret = xfer_download_gotpkt(scp_sftp_xfer, pktin);
1621             if (ret <= 0) {
1622                 tell_user(stderr, "pscp: error while reading: %s", fxp_error());
1623                 if (ret == INT_MIN)        /* pktin not even freed */
1624                     sfree(pktin);
1625                 errs++;
1626                 return -1;
1627             }
1628             if (xfer_download_data(scp_sftp_xfer, &vbuf, &len))
1629                 sfree(vbuf);
1630         }
1631         xfer_cleanup(scp_sftp_xfer);
1632
1633         req = fxp_close_send(scp_sftp_filehandle);
1634         pktin = sftp_wait_for_reply(req);
1635         fxp_close_recv(pktin, req);
1636         return 0;
1637     } else {
1638         back->send(backhandle, "", 1);
1639         return response();
1640     }
1641 }
1642
1643 /* ----------------------------------------------------------------------
1644  *  Send an error message to the other side and to the screen.
1645  *  Increment error counter.
1646  */
1647 static void run_err(const char *fmt, ...)
1648 {
1649     char *str, *str2;
1650     va_list ap;
1651     va_start(ap, fmt);
1652     errs++;
1653     str = dupvprintf(fmt, ap);
1654     str2 = dupcat("pscp: ", str, "\n", NULL);
1655     sfree(str);
1656     scp_send_errmsg(str2);
1657     tell_user(stderr, "%s", str2);
1658     va_end(ap);
1659     sfree(str2);
1660 }
1661
1662 /*
1663  *  Execute the source part of the SCP protocol.
1664  */
1665 static void source(const char *src)
1666 {
1667     uint64 size;
1668     unsigned long mtime, atime;
1669     long permissions;
1670     const char *last;
1671     RFile *f;
1672     int attr;
1673     uint64 i;
1674     uint64 stat_bytes;
1675     time_t stat_starttime, stat_lasttime;
1676
1677     attr = file_type(src);
1678     if (attr == FILE_TYPE_NONEXISTENT ||
1679         attr == FILE_TYPE_WEIRD) {
1680         run_err("%s: %s file or directory", src,
1681                 (attr == FILE_TYPE_WEIRD ? "Not a" : "No such"));
1682         return;
1683     }
1684
1685     if (attr == FILE_TYPE_DIRECTORY) {
1686         if (recursive) {
1687             /*
1688              * Avoid . and .. directories.
1689              */
1690             const char *p;
1691             p = strrchr(src, '/');
1692             if (!p)
1693                 p = strrchr(src, '\\');
1694             if (!p)
1695                 p = src;
1696             else
1697                 p++;
1698             if (!strcmp(p, ".") || !strcmp(p, ".."))
1699                 /* skip . and .. */ ;
1700             else
1701                 rsource(src);
1702         } else {
1703             run_err("%s: not a regular file", src);
1704         }
1705         return;
1706     }
1707
1708     if ((last = strrchr(src, '/')) == NULL)
1709         last = src;
1710     else
1711         last++;
1712     if (strrchr(last, '\\') != NULL)
1713         last = strrchr(last, '\\') + 1;
1714     if (last == src && strchr(src, ':') != NULL)
1715         last = strchr(src, ':') + 1;
1716
1717     f = open_existing_file(src, &size, &mtime, &atime, &permissions);
1718     if (f == NULL) {
1719         run_err("%s: Cannot open file", src);
1720         return;
1721     }
1722     if (preserve) {
1723         if (scp_send_filetimes(mtime, atime)) {
1724             close_rfile(f);
1725             return;
1726         }
1727     }
1728
1729     if (verbose) {
1730         char sizestr[40];
1731         uint64_decimal(size, sizestr);
1732         tell_user(stderr, "Sending file %s, size=%s", last, sizestr);
1733     }
1734     if (scp_send_filename(last, size, permissions)) {
1735         close_rfile(f);
1736         return;
1737     }
1738
1739     stat_bytes = uint64_make(0,0);
1740     stat_starttime = time(NULL);
1741     stat_lasttime = 0;
1742
1743     for (i = uint64_make(0,0);
1744          uint64_compare(i,size) < 0;
1745          i = uint64_add32(i,4096)) {
1746         char transbuf[4096];
1747         int j, k = 4096;
1748
1749         if (uint64_compare(uint64_add32(i, k),size) > 0) /* i + k > size */ 
1750             k = (uint64_subtract(size, i)).lo;  /* k = size - i; */
1751         if ((j = read_from_file(f, transbuf, k)) != k) {
1752             if (statistics)
1753                 printf("\n");
1754             bump("%s: Read error", src);
1755         }
1756         if (scp_send_filedata(transbuf, k))
1757             bump("%s: Network error occurred", src);
1758
1759         if (statistics) {
1760             stat_bytes = uint64_add32(stat_bytes, k);
1761             if (time(NULL) != stat_lasttime ||
1762                 (uint64_compare(uint64_add32(i, k), size) == 0)) {
1763                 stat_lasttime = time(NULL);
1764                 print_stats(last, size, stat_bytes,
1765                             stat_starttime, stat_lasttime);
1766             }
1767         }
1768
1769     }
1770     close_rfile(f);
1771
1772     (void) scp_send_finish();
1773 }
1774
1775 /*
1776  *  Recursively send the contents of a directory.
1777  */
1778 static void rsource(const char *src)
1779 {
1780     const char *last;
1781     char *save_target;
1782     DirHandle *dir;
1783
1784     if ((last = strrchr(src, '/')) == NULL)
1785         last = src;
1786     else
1787         last++;
1788     if (strrchr(last, '\\') != NULL)
1789         last = strrchr(last, '\\') + 1;
1790     if (last == src && strchr(src, ':') != NULL)
1791         last = strchr(src, ':') + 1;
1792
1793     /* maybe send filetime */
1794
1795     save_target = scp_save_remotepath();
1796
1797     if (verbose)
1798         tell_user(stderr, "Entering directory: %s", last);
1799     if (scp_send_dirname(last, 0755))
1800         return;
1801
1802     dir = open_directory(src);
1803     if (dir != NULL) {
1804         char *filename;
1805         while ((filename = read_filename(dir)) != NULL) {
1806             char *foundfile = dupcat(src, "/", filename, NULL);
1807             source(foundfile);
1808             sfree(foundfile);
1809             sfree(filename);
1810         }
1811     }
1812     close_directory(dir);
1813
1814     (void) scp_send_enddir();
1815
1816     scp_restore_remotepath(save_target);
1817 }
1818
1819 /*
1820  * Execute the sink part of the SCP protocol.
1821  */
1822 static void sink(const char *targ, const char *src)
1823 {
1824     char *destfname;
1825     int targisdir = 0;
1826     int exists;
1827     int attr;
1828     WFile *f;
1829     uint64 received;
1830     int wrerror = 0;
1831     uint64 stat_bytes;
1832     time_t stat_starttime, stat_lasttime;
1833     char *stat_name;
1834
1835     attr = file_type(targ);
1836     if (attr == FILE_TYPE_DIRECTORY)
1837         targisdir = 1;
1838
1839     if (targetshouldbedirectory && !targisdir)
1840         bump("%s: Not a directory", targ);
1841
1842     scp_sink_init();
1843     while (1) {
1844         struct scp_sink_action act;
1845         if (scp_get_sink_action(&act))
1846             return;
1847
1848         if (act.action == SCP_SINK_ENDDIR)
1849             return;
1850
1851         if (act.action == SCP_SINK_RETRY)
1852             continue;
1853
1854         if (targisdir) {
1855             /*
1856              * Prevent the remote side from maliciously writing to
1857              * files outside the target area by sending a filename
1858              * containing `../'. In fact, it shouldn't be sending
1859              * filenames with any slashes or colons in at all; so
1860              * we'll find the last slash, backslash or colon in the
1861              * filename and use only the part after that. (And
1862              * warn!)
1863              * 
1864              * In addition, we also ensure here that if we're
1865              * copying a single file and the target is a directory
1866              * (common usage: `pscp host:filename .') the remote
1867              * can't send us a _different_ file name. We can
1868              * distinguish this case because `src' will be non-NULL
1869              * and the last component of that will fail to match
1870              * (the last component of) the name sent.
1871              * 
1872              * Well, not always; if `src' is a wildcard, we do
1873              * expect to get back filenames that don't correspond
1874              * exactly to it. Ideally in this case, we would like
1875              * to ensure that the returned filename actually
1876              * matches the wildcard pattern - but one of SCP's
1877              * protocol infelicities is that wildcard matching is
1878              * done at the server end _by the server's rules_ and
1879              * so in general this is infeasible. Hence, we only
1880              * accept filenames that don't correspond to `src' if
1881              * unsafe mode is enabled or we are using SFTP (which
1882              * resolves remote wildcards on the client side and can
1883              * be trusted).
1884              */
1885             char *striptarget, *stripsrc;
1886
1887             striptarget = stripslashes(act.name, 1);
1888             if (striptarget != act.name) {
1889                 tell_user(stderr, "warning: remote host sent a compound"
1890                           " pathname '%s'", act.name);
1891                 tell_user(stderr, "         renaming local file to '%s'",
1892                           striptarget);
1893             }
1894
1895             /*
1896              * Also check to see if the target filename is '.' or
1897              * '..', or indeed '...' and so on because Windows
1898              * appears to interpret those like '..'.
1899              */
1900             if (is_dots(striptarget)) {
1901                 bump("security violation: remote host attempted to write to"
1902                      " a '.' or '..' path!");
1903             }
1904
1905             if (src) {
1906                 stripsrc = stripslashes(src, 1);
1907                 if (strcmp(striptarget, stripsrc) &&
1908                     !using_sftp && !scp_unsafe_mode) {
1909                     tell_user(stderr, "warning: remote host tried to write "
1910                               "to a file called '%s'", striptarget);
1911                     tell_user(stderr, "         when we requested a file "
1912                               "called '%s'.", stripsrc);
1913                     tell_user(stderr, "         If this is a wildcard, "
1914                               "consider upgrading to SSH-2 or using");
1915                     tell_user(stderr, "         the '-unsafe' option. Renaming"
1916                               " of this file has been disallowed.");
1917                     /* Override the name the server provided with our own. */
1918                     striptarget = stripsrc;
1919                 }
1920             }
1921
1922             if (targ[0] != '\0')
1923                 destfname = dir_file_cat(targ, striptarget);
1924             else
1925                 destfname = dupstr(striptarget);
1926         } else {
1927             /*
1928              * In this branch of the if, the target area is a
1929              * single file with an explicitly specified name in any
1930              * case, so there's no danger.
1931              */
1932             destfname = dupstr(targ);
1933         }
1934         attr = file_type(destfname);
1935         exists = (attr != FILE_TYPE_NONEXISTENT);
1936
1937         if (act.action == SCP_SINK_DIR) {
1938             if (exists && attr != FILE_TYPE_DIRECTORY) {
1939                 run_err("%s: Not a directory", destfname);
1940                 sfree(destfname);
1941                 continue;
1942             }
1943             if (!exists) {
1944                 if (!create_directory(destfname)) {
1945                     run_err("%s: Cannot create directory", destfname);
1946                     sfree(destfname);
1947                     continue;
1948                 }
1949             }
1950             sink(destfname, NULL);
1951             /* can we set the timestamp for directories ? */
1952             sfree(destfname);
1953             continue;
1954         }
1955
1956         f = open_new_file(destfname, act.permissions);
1957         if (f == NULL) {
1958             run_err("%s: Cannot create file", destfname);
1959             sfree(destfname);
1960             continue;
1961         }
1962
1963         if (scp_accept_filexfer()) {
1964             sfree(destfname);
1965             close_wfile(f);
1966             return;
1967         }
1968
1969         stat_bytes = uint64_make(0, 0);
1970         stat_starttime = time(NULL);
1971         stat_lasttime = 0;
1972         stat_name = stripslashes(destfname, 1);
1973
1974         received = uint64_make(0, 0);
1975         while (uint64_compare(received,act.size) < 0) {
1976             char transbuf[32768];
1977             uint64 blksize;
1978             int read;
1979             blksize = uint64_make(0, 32768);
1980             if (uint64_compare(blksize,uint64_subtract(act.size,received)) > 0)
1981               blksize = uint64_subtract(act.size,received);
1982             read = scp_recv_filedata(transbuf, (int)blksize.lo);
1983             if (read <= 0)
1984                 bump("Lost connection");
1985             if (wrerror)
1986                 continue;
1987             if (write_to_file(f, transbuf, read) != (int)read) {
1988                 wrerror = 1;
1989                 /* FIXME: in sftp we can actually abort the transfer */
1990                 if (statistics)
1991                     printf("\r%-25.25s | %50s\n",
1992                            stat_name,
1993                            "Write error.. waiting for end of file");
1994                 continue;
1995             }
1996             if (statistics) {
1997                 stat_bytes = uint64_add32(stat_bytes,read);
1998                 if (time(NULL) > stat_lasttime ||
1999                     uint64_compare(uint64_add32(received, read), act.size) == 0) {
2000                     stat_lasttime = time(NULL);
2001                     print_stats(stat_name, act.size, stat_bytes,
2002                                 stat_starttime, stat_lasttime);
2003                 }
2004             }
2005             received = uint64_add32(received, read);
2006         }
2007         if (act.settime) {
2008             set_file_times(f, act.mtime, act.atime);
2009         }
2010
2011         close_wfile(f);
2012         if (wrerror) {
2013             run_err("%s: Write error", destfname);
2014             sfree(destfname);
2015             continue;
2016         }
2017         (void) scp_finish_filerecv();
2018         sfree(destfname);
2019         sfree(act.buf);
2020     }
2021 }
2022
2023 /*
2024  * We will copy local files to a remote server.
2025  */
2026 static void toremote(int argc, char *argv[])
2027 {
2028     char *src, *wtarg, *host, *user;
2029     const char *targ;
2030     char *cmd;
2031     int i, wc_type;
2032
2033     uploading = 1;
2034
2035     wtarg = argv[argc - 1];
2036
2037     /* Separate host from filename */
2038     host = wtarg;
2039     wtarg = colon(wtarg);
2040     if (wtarg == NULL)
2041         bump("wtarg == NULL in toremote()");
2042     *wtarg++ = '\0';
2043     /* Substitute "." for empty target */
2044     if (*wtarg == '\0')
2045         targ = ".";
2046     else
2047         targ = wtarg;
2048
2049     /* Separate host and username */
2050     user = host;
2051     host = strrchr(host, '@');
2052     if (host == NULL) {
2053         host = user;
2054         user = NULL;
2055     } else {
2056         *host++ = '\0';
2057         if (*user == '\0')
2058             user = NULL;
2059     }
2060
2061     if (argc == 2) {
2062         if (colon(argv[0]) != NULL)
2063             bump("%s: Remote to remote not supported", argv[0]);
2064
2065         wc_type = test_wildcard(argv[0], 1);
2066         if (wc_type == WCTYPE_NONEXISTENT)
2067             bump("%s: No such file or directory\n", argv[0]);
2068         else if (wc_type == WCTYPE_WILDCARD)
2069             targetshouldbedirectory = 1;
2070     }
2071
2072     cmd = dupprintf("scp%s%s%s%s -t %s",
2073                     verbose ? " -v" : "",
2074                     recursive ? " -r" : "",
2075                     preserve ? " -p" : "",
2076                     targetshouldbedirectory ? " -d" : "", targ);
2077     do_cmd(host, user, cmd);
2078     sfree(cmd);
2079
2080     if (scp_source_setup(targ, targetshouldbedirectory))
2081         return;
2082
2083     for (i = 0; i < argc - 1; i++) {
2084         src = argv[i];
2085         if (colon(src) != NULL) {
2086             tell_user(stderr, "%s: Remote to remote not supported\n", src);
2087             errs++;
2088             continue;
2089         }
2090
2091         wc_type = test_wildcard(src, 1);
2092         if (wc_type == WCTYPE_NONEXISTENT) {
2093             run_err("%s: No such file or directory", src);
2094             continue;
2095         } else if (wc_type == WCTYPE_FILENAME) {
2096             source(src);
2097             continue;
2098         } else {
2099             WildcardMatcher *wc;
2100             char *filename;
2101
2102             wc = begin_wildcard_matching(src);
2103             if (wc == NULL) {
2104                 run_err("%s: No such file or directory", src);
2105                 continue;
2106             }
2107
2108             while ((filename = wildcard_get_filename(wc)) != NULL) {
2109                 source(filename);
2110                 sfree(filename);
2111             }
2112
2113             finish_wildcard_matching(wc);
2114         }
2115     }
2116 }
2117
2118 /*
2119  *  We will copy files from a remote server to the local machine.
2120  */
2121 static void tolocal(int argc, char *argv[])
2122 {
2123     char *wsrc, *host, *user;
2124     const char *src, *targ;
2125     char *cmd;
2126
2127     uploading = 0;
2128
2129     if (argc != 2)
2130         bump("More than one remote source not supported");
2131
2132     wsrc = argv[0];
2133     targ = argv[1];
2134
2135     /* Separate host from filename */
2136     host = wsrc;
2137     wsrc = colon(wsrc);
2138     if (wsrc == NULL)
2139         bump("Local to local copy not supported");
2140     *wsrc++ = '\0';
2141     /* Substitute "." for empty filename */
2142     if (*wsrc == '\0')
2143         src = ".";
2144     else
2145         src = wsrc;
2146
2147     /* Separate username and hostname */
2148     user = host;
2149     host = strrchr(host, '@');
2150     if (host == NULL) {
2151         host = user;
2152         user = NULL;
2153     } else {
2154         *host++ = '\0';
2155         if (*user == '\0')
2156             user = NULL;
2157     }
2158
2159     cmd = dupprintf("scp%s%s%s%s -f %s",
2160                     verbose ? " -v" : "",
2161                     recursive ? " -r" : "",
2162                     preserve ? " -p" : "",
2163                     targetshouldbedirectory ? " -d" : "", src);
2164     do_cmd(host, user, cmd);
2165     sfree(cmd);
2166
2167     if (scp_sink_setup(src, preserve, recursive))
2168         return;
2169
2170     sink(targ, src);
2171 }
2172
2173 /*
2174  *  We will issue a list command to get a remote directory.
2175  */
2176 static void get_dir_list(int argc, char *argv[])
2177 {
2178     char *wsrc, *host, *user;
2179     const char *src;
2180     char *cmd, *p;
2181     const char *q;
2182     char c;
2183
2184     wsrc = argv[0];
2185
2186     /* Separate host from filename */
2187     host = wsrc;
2188     wsrc = colon(wsrc);
2189     if (wsrc == NULL)
2190         bump("Local file listing not supported");
2191     *wsrc++ = '\0';
2192     /* Substitute "." for empty filename */
2193     if (*wsrc == '\0')
2194         src = ".";
2195     else
2196         src = wsrc;
2197
2198     /* Separate username and hostname */
2199     user = host;
2200     host = strrchr(host, '@');
2201     if (host == NULL) {
2202         host = user;
2203         user = NULL;
2204     } else {
2205         *host++ = '\0';
2206         if (*user == '\0')
2207             user = NULL;
2208     }
2209
2210     cmd = snewn(4 * strlen(src) + 100, char);
2211     strcpy(cmd, "ls -la '");
2212     p = cmd + strlen(cmd);
2213     for (q = src; *q; q++) {
2214         if (*q == '\'') {
2215             *p++ = '\'';
2216             *p++ = '\\';
2217             *p++ = '\'';
2218             *p++ = '\'';
2219         } else {
2220             *p++ = *q;
2221         }
2222     }
2223     *p++ = '\'';
2224     *p = '\0';
2225
2226     do_cmd(host, user, cmd);
2227     sfree(cmd);
2228
2229     if (using_sftp) {
2230         scp_sftp_listdir(src);
2231     } else {
2232         while (ssh_scp_recv((unsigned char *) &c, 1) > 0)
2233             tell_char(stdout, c);
2234     }
2235 }
2236
2237 /*
2238  *  Short description of parameters.
2239  */
2240 static void usage(void)
2241 {
2242     printf("PuTTY Secure Copy client\n");
2243     printf("%s\n", ver);
2244     printf("Usage: pscp [options] [user@]host:source target\n");
2245     printf
2246         ("       pscp [options] source [source...] [user@]host:target\n");
2247     printf("       pscp [options] -ls [user@]host:filespec\n");
2248     printf("Options:\n");
2249     printf("  -V        print version information and exit\n");
2250     printf("  -pgpfp    print PGP key fingerprints and exit\n");
2251     printf("  -p        preserve file attributes\n");
2252     printf("  -q        quiet, don't show statistics\n");
2253     printf("  -r        copy directories recursively\n");
2254     printf("  -v        show verbose messages\n");
2255     printf("  -load sessname  Load settings from saved session\n");
2256     printf("  -P port   connect to specified port\n");
2257     printf("  -l user   connect with specified username\n");
2258     printf("  -pw passw login with specified password\n");
2259     printf("  -1 -2     force use of particular SSH protocol version\n");
2260     printf("  -4 -6     force use of IPv4 or IPv6\n");
2261     printf("  -C        enable compression\n");
2262     printf("  -i key    private key file for user authentication\n");
2263     printf("  -noagent  disable use of Pageant\n");
2264     printf("  -agent    enable use of Pageant\n");
2265     printf("  -hostkey aa:bb:cc:...\n");
2266     printf("            manually specify a host key (may be repeated)\n");
2267     printf("  -batch    disable all interactive prompts\n");
2268     printf("  -unsafe   allow server-side wildcards (DANGEROUS)\n");
2269     printf("  -sftp     force use of SFTP protocol\n");
2270     printf("  -scp      force use of SCP protocol\n");
2271 #if 0
2272     /*
2273      * -gui is an internal option, used by GUI front ends to get
2274      * pscp to pass progress reports back to them. It's not an
2275      * ordinary user-accessible option, so it shouldn't be part of
2276      * the command-line help. The only people who need to know
2277      * about it are programmers, and they can read the source.
2278      */
2279     printf
2280         ("  -gui hWnd GUI mode with the windows handle for receiving messages\n");
2281 #endif
2282     cleanup_exit(1);
2283 }
2284
2285 void version(void)
2286 {
2287     printf("pscp: %s\n", ver);
2288     cleanup_exit(1);
2289 }
2290
2291 void cmdline_error(const char *p, ...)
2292 {
2293     va_list ap;
2294     fprintf(stderr, "pscp: ");
2295     va_start(ap, p);
2296     vfprintf(stderr, p, ap);
2297     va_end(ap);
2298     fprintf(stderr, "\n      try typing just \"pscp\" for help\n");
2299     exit(1);
2300 }
2301
2302 const int share_can_be_downstream = TRUE;
2303 const int share_can_be_upstream = FALSE;
2304
2305 /*
2306  * Main program. (Called `psftp_main' because it gets called from
2307  * *sftp.c; bit silly, I know, but it had to be called _something_.)
2308  */
2309 int psftp_main(int argc, char *argv[])
2310 {
2311     int i;
2312
2313     default_protocol = PROT_TELNET;
2314
2315     flags = FLAG_STDERR
2316 #ifdef FLAG_SYNCAGENT
2317         | FLAG_SYNCAGENT
2318 #endif
2319         ;
2320     cmdline_tooltype = TOOLTYPE_FILETRANSFER;
2321     sk_init();
2322
2323     /* Load Default Settings before doing anything else. */
2324     conf = conf_new();
2325     do_defaults(NULL, conf);
2326     loaded_session = FALSE;
2327
2328     for (i = 1; i < argc; i++) {
2329         int ret;
2330         if (argv[i][0] != '-')
2331             break;
2332         ret = cmdline_process_param(argv[i], i+1<argc?argv[i+1]:NULL, 1, conf);
2333         if (ret == -2) {
2334             cmdline_error("option \"%s\" requires an argument", argv[i]);
2335         } else if (ret == 2) {
2336             i++;               /* skip next argument */
2337         } else if (ret == 1) {
2338             /* We have our own verbosity in addition to `flags'. */
2339             if (flags & FLAG_VERBOSE)
2340                 verbose = 1;
2341         } else if (strcmp(argv[i], "-pgpfp") == 0) {
2342             pgp_fingerprints();
2343             return 1;
2344         } else if (strcmp(argv[i], "-r") == 0) {
2345             recursive = 1;
2346         } else if (strcmp(argv[i], "-p") == 0) {
2347             preserve = 1;
2348         } else if (strcmp(argv[i], "-q") == 0) {
2349             statistics = 0;
2350         } else if (strcmp(argv[i], "-h") == 0 ||
2351                    strcmp(argv[i], "-?") == 0 ||
2352                    strcmp(argv[i], "--help") == 0) {
2353             usage();
2354         } else if (strcmp(argv[i], "-V") == 0 ||
2355                    strcmp(argv[i], "--version") == 0) {
2356             version();
2357         } else if (strcmp(argv[i], "-ls") == 0) {
2358             list = 1;
2359         } else if (strcmp(argv[i], "-batch") == 0) {
2360             console_batch_mode = 1;
2361         } else if (strcmp(argv[i], "-unsafe") == 0) {
2362             scp_unsafe_mode = 1;
2363         } else if (strcmp(argv[i], "-sftp") == 0) {
2364             try_scp = 0; try_sftp = 1;
2365         } else if (strcmp(argv[i], "-scp") == 0) {
2366             try_scp = 1; try_sftp = 0;
2367         } else if (strcmp(argv[i], "--") == 0) {
2368             i++;
2369             break;
2370         } else {
2371             cmdline_error("unknown option \"%s\"", argv[i]);
2372         }
2373     }
2374     argc -= i;
2375     argv += i;
2376     back = NULL;
2377
2378     if (list) {
2379         if (argc != 1)
2380             usage();
2381         get_dir_list(argc, argv);
2382
2383     } else {
2384
2385         if (argc < 2)
2386             usage();
2387         if (argc > 2)
2388             targetshouldbedirectory = 1;
2389
2390         if (colon(argv[argc - 1]) != NULL)
2391             toremote(argc, argv);
2392         else
2393             tolocal(argc, argv);
2394     }
2395
2396     if (back != NULL && back->connected(backhandle)) {
2397         char ch;
2398         back->special(backhandle, TS_EOF);
2399         sent_eof = TRUE;
2400         ssh_scp_recv((unsigned char *) &ch, 1);
2401     }
2402     random_save_seed();
2403
2404     cmdline_cleanup();
2405     console_provide_logctx(NULL);
2406     back->free(backhandle);
2407     backhandle = NULL;
2408     back = NULL;
2409     sk_cleanup();
2410     return (errs == 0 ? 0 : 1);
2411 }
2412
2413 /* end */