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