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