2 * scp.c - Scp (Secure Copy) client for PuTTY.
3 * Joris van Rantwijk, Simon Tatham
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.
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.)
22 #define PUTTY_DO_GLOBALS
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;
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;
46 static void *backhandle;
49 static void source(char *src);
50 static void rsource(char *src);
51 static void sink(char *targ, char *src);
54 * The maximum amount of queued data we accept before we stop and
55 * wait for the server to process some.
57 #define MAX_SCP_BUFSIZE 16384
59 void ldisc_send(void *handle, char *buf, int len, int interactive)
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
70 static void tell_char(FILE * stream, char c)
75 static void tell_str(FILE * stream, char *str)
79 for (i = 0; i < strlen(str); ++i)
80 tell_char(stream, str[i]);
83 static void tell_user(FILE * stream, char *fmt, ...)
88 str = dupvprintf(fmt, ap);
90 str2 = dupcat(str, "\n", NULL);
92 tell_str(stream, str2);
97 * Print an error message and perform a fatal exit.
99 void fatalbox(char *fmt, ...)
104 str = dupvprintf(fmt, ap);
105 str2 = dupcat("Fatal: ", str, "\n", NULL);
108 tell_str(stderr, str2);
114 void modalfatalbox(char *fmt, ...)
119 str = dupvprintf(fmt, ap);
120 str2 = dupcat("Fatal: ", str, "\n", NULL);
123 tell_str(stderr, str2);
129 void connection_fatal(void *frontend, char *fmt, ...)
134 str = dupvprintf(fmt, ap);
135 str2 = dupcat("Fatal: ", str, "\n", NULL);
138 tell_str(stderr, str2);
146 * In pscp, all agent requests should be synchronous, so this is a
149 void agent_schedule_callback(void (*callback)(void *, void *, int),
150 void *callback_ctx, void *data, int len)
152 assert(!"We shouldn't be here");
156 * Receive a block of data from the SSH link. Block until all data
159 * To do this, we repeatedly call the SSH protocol module, with our
160 * own trap in from_backend() to catch the data that comes back. We
161 * do this until we have enough data.
164 static unsigned char *outptr; /* where to put the data */
165 static unsigned outlen; /* how much data required */
166 static unsigned char *pending = NULL; /* any spare data */
167 static unsigned pendlen = 0, pendsize = 0; /* length and phys. size of buffer */
168 int from_backend(void *frontend, int is_stderr, const char *data, int datalen)
170 unsigned char *p = (unsigned char *) data;
171 unsigned len = (unsigned) datalen;
174 * stderr data is just spouted to local stderr and otherwise
179 fwrite(data, 1, len, stderr);
183 if ((outlen > 0) && (len > 0)) {
184 unsigned used = outlen;
187 memcpy(outptr, p, used);
195 if (pendsize < pendlen + len) {
196 pendsize = pendlen + len + 4096;
197 pending = sresize(pending, pendsize, unsigned char);
199 memcpy(pending + pendlen, p, len);
205 int from_backend_untrusted(void *frontend_handle, const char *data, int len)
208 * No "untrusted" output should get here (the way the code is
209 * currently, it's all diverted by FLAG_STDERR).
211 assert(!"Unexpected call to from_backend_untrusted()");
212 return 0; /* not reached */
214 static int ssh_scp_recv(unsigned char *buf, int len)
220 * See if the pending-input block contains some of what we
224 unsigned pendused = pendlen;
225 if (pendused > outlen)
227 memcpy(outptr, pending, pendused);
228 memmove(pending, pending + pendused, pendlen - pendused);
242 if (back->exitcode(backhandle) >= 0 || ssh_sftp_loop_iteration() < 0)
250 * Loop through the ssh connection and authentication process.
252 static void ssh_scp_init(void)
254 while (!back->sendok(backhandle)) {
255 if (ssh_sftp_loop_iteration() < 0)
259 /* Work out which backend we ended up using. */
260 if (!ssh_fallback_cmd(backhandle))
261 using_sftp = main_cmd_is_sftp;
263 using_sftp = fallback_cmd_is_sftp;
267 tell_user(stderr, "Using SFTP");
269 tell_user(stderr, "Using SCP1");
274 * Print an error message and exit after closing the SSH link.
276 static void bump(char *fmt, ...)
281 str = dupvprintf(fmt, ap);
283 str2 = dupcat(str, "\n", NULL);
285 tell_str(stderr, str2);
289 if (back != NULL && back->connected(backhandle)) {
291 back->special(backhandle, TS_EOF);
292 ssh_scp_recv((unsigned char *) &ch, 1);
299 * Open an SSH connection to user@host and execute cmd.
301 static void do_cmd(char *host, char *user, char *cmd)
307 if (host == NULL || host[0] == '\0')
308 bump("Empty host name");
311 * Remove fiddly bits of address: remove a colon suffix, and
312 * the square brackets around an IPv6 literal address.
314 if (host[0] == '[') {
316 host[strcspn(host, "]")] = '\0';
318 host[strcspn(host, ":")] = '\0';
322 * If we haven't loaded session details already (e.g., from -load),
323 * try looking for a session called "host".
325 if (!loaded_session) {
326 /* Try to load settings for `host' into a temporary config */
329 do_defaults(host, &cfg2);
330 if (cfg2.host[0] != '\0') {
331 /* Settings present and include hostname */
332 /* Re-load data into the real config. */
333 do_defaults(host, &cfg);
335 /* Session doesn't exist or mention a hostname. */
336 /* Use `host' as a bare hostname. */
337 strncpy(cfg.host, host, sizeof(cfg.host) - 1);
338 cfg.host[sizeof(cfg.host) - 1] = '\0';
341 /* Patch in hostname `host' to session details. */
342 strncpy(cfg.host, host, sizeof(cfg.host) - 1);
343 cfg.host[sizeof(cfg.host) - 1] = '\0';
347 * Force use of SSH. (If they got the protocol wrong we assume the
348 * port is useless too.)
350 if (cfg.protocol != PROT_SSH) {
351 cfg.protocol = PROT_SSH;
356 * Enact command-line overrides.
358 cmdline_run_saved(&cfg);
361 * Trim leading whitespace off the hostname if it's there.
364 int space = strspn(cfg.host, " \t");
365 memmove(cfg.host, cfg.host+space, 1+strlen(cfg.host)-space);
368 /* See if host is of the form user@host */
369 if (cfg.host[0] != '\0') {
370 char *atsign = strrchr(cfg.host, '@');
371 /* Make sure we're not overflowing the user field */
373 if (atsign - cfg.host < sizeof cfg.username) {
374 strncpy(cfg.username, cfg.host, atsign - cfg.host);
375 cfg.username[atsign - cfg.host] = '\0';
377 memmove(cfg.host, atsign + 1, 1 + strlen(atsign + 1));
382 * Remove any remaining whitespace from the hostname.
386 while (cfg.host[p2] != '\0') {
387 if (cfg.host[p2] != ' ' && cfg.host[p2] != '\t') {
388 cfg.host[p1] = cfg.host[p2];
397 if (user != NULL && user[0] != '\0') {
398 strncpy(cfg.username, user, sizeof(cfg.username) - 1);
399 cfg.username[sizeof(cfg.username) - 1] = '\0';
400 } else if (cfg.username[0] == '\0') {
401 user = get_username();
403 bump("Empty user name");
406 tell_user(stderr, "Guessing user name: %s", user);
407 strncpy(cfg.username, user, sizeof(cfg.username) - 1);
408 cfg.username[sizeof(cfg.username) - 1] = '\0';
414 * Disable scary things which shouldn't be enabled for simple
415 * things like SCP and SFTP: agent forwarding, port forwarding,
420 cfg.portfwd[0] = cfg.portfwd[1] = '\0';
423 * Set up main and possibly fallback command depending on
424 * options specified by user.
425 * Attempt to start the SFTP subsystem as a first choice,
426 * falling back to the provided scp command if that fails.
428 cfg.remote_cmd_ptr2 = NULL;
430 /* First choice is SFTP subsystem. */
431 main_cmd_is_sftp = 1;
432 strcpy(cfg.remote_cmd, "sftp");
433 cfg.ssh_subsys = TRUE;
435 /* Fallback is to use the provided scp command. */
436 fallback_cmd_is_sftp = 0;
437 cfg.remote_cmd_ptr2 = cmd;
438 cfg.ssh_subsys2 = FALSE;
440 /* Since we're not going to try SCP, we may as well try
441 * harder to find an SFTP server, since in the current
442 * implementation we have a spare slot. */
443 fallback_cmd_is_sftp = 1;
444 /* see psftp.c for full explanation of this kludge */
445 cfg.remote_cmd_ptr2 =
446 "test -x /usr/lib/sftp-server && exec /usr/lib/sftp-server\n"
447 "test -x /usr/local/lib/sftp-server && exec /usr/local/lib/sftp-server\n"
449 cfg.ssh_subsys2 = FALSE;
452 /* Don't try SFTP at all; just try the scp command. */
453 main_cmd_is_sftp = 0;
454 cfg.remote_cmd_ptr = cmd;
455 cfg.ssh_subsys = FALSE;
461 err = back->init(NULL, &backhandle, &cfg, cfg.host, cfg.port, &realhost,
462 0, cfg.tcp_keepalives);
464 bump("ssh_init: %s", err);
465 logctx = log_init(NULL, &cfg);
466 back->provide_logctx(backhandle, logctx);
467 console_provide_logctx(logctx);
469 if (verbose && realhost != NULL)
470 tell_user(stderr, "Connected to %s\n", realhost);
475 * Update statistic information about current file.
477 static void print_stats(char *name, uint64 size, uint64 done,
478 time_t start, time_t now)
489 elap = (unsigned long) difftime(now, start);
492 ratebs = (float) (uint64_to_double(done) / elap);
494 ratebs = (float) uint64_to_double(done);
497 eta = (unsigned long) (uint64_to_double(uint64_subtract(size, done)));
499 eta = (unsigned long)
500 ((uint64_to_double(uint64_subtract(size, done)) / ratebs));
503 etastr = dupprintf("%02ld:%02ld:%02ld",
504 eta / 3600, (eta % 3600) / 60, eta % 60);
506 donedbl = uint64_to_double(done);
507 sizedbl = uint64_to_double(size);
508 pct = (int) (100 * (donedbl * 1.0 / sizedbl));
512 /* divide by 1024 to provide kB */
513 uint64_decimal(uint64_shift_right(done, 10), donekb);
514 len = printf("\r%-25.25s | %s kB | %5.1f kB/s | ETA: %8s | %3d%%",
516 donekb, ratebs / 1024.0, etastr, pct);
517 if (len < prev_stats_len)
518 printf("%*s", prev_stats_len - len, "");
519 prev_stats_len = len;
521 if (uint64_compare(done, size) == 0)
531 * Find a colon in str and return a pointer to the colon.
532 * This is used to separate hostname from filename.
534 static char *colon(char *str)
536 /* We ignore a leading colon, since the hostname cannot be
537 empty. We also ignore a colon as second character because
538 of filenames like f:myfile.txt. */
539 if (str[0] == '\0' || str[0] == ':' ||
540 (str[0] != '[' && str[1] == ':'))
542 while (*str != '\0' && *str != ':' && *str != '/' && *str != '\\') {
544 /* Skip over IPv6 literal addresses
545 * (eg: 'jeroen@[2001:db8::1]:myfile.txt') */
546 char *ipv6_end = strchr(str, ']');
560 * Return a pointer to the portion of str that comes after the last
561 * slash (or backslash or colon, if `local' is TRUE).
563 static char *stripslashes(char *str, int local)
568 p = strchr(str, ':');
572 p = strrchr(str, '/');
576 p = strrchr(str, '\\');
584 * Determine whether a string is entirely composed of dots.
586 static int is_dots(char *str)
588 return str[strspn(str, ".")] == '\0';
592 * Wait for a response from the other side.
593 * Return 0 if ok, -1 if error.
595 static int response(void)
597 char ch, resp, rbuf[2048];
600 if (ssh_scp_recv((unsigned char *) &resp, 1) <= 0)
601 bump("Lost connection");
611 case 2: /* fatal error */
613 if (ssh_scp_recv((unsigned char *) &ch, 1) <= 0)
614 bump("Protocol error: Lost connection");
616 } while (p < sizeof(rbuf) && ch != '\n');
619 tell_user(stderr, "%s\n", rbuf);
627 int sftp_recvdata(char *buf, int len)
629 return ssh_scp_recv((unsigned char *) buf, len);
631 int sftp_senddata(char *buf, int len)
633 back->send(backhandle, buf, len);
637 /* ----------------------------------------------------------------------
638 * sftp-based replacement for the hacky `pscp -ls'.
640 static int sftp_ls_compare(const void *av, const void *bv)
642 const struct fxp_name *a = (const struct fxp_name *) av;
643 const struct fxp_name *b = (const struct fxp_name *) bv;
644 return strcmp(a->filename, b->filename);
646 void scp_sftp_listdir(char *dirname)
648 struct fxp_handle *dirh;
649 struct fxp_names *names;
650 struct fxp_name *ournames;
651 struct sftp_packet *pktin;
652 struct sftp_request *req, *rreq;
653 int nnames, namesize;
657 tell_user(stderr, "unable to initialise SFTP: %s", fxp_error());
662 printf("Listing directory %s\n", dirname);
664 sftp_register(req = fxp_opendir_send(dirname));
665 rreq = sftp_find_request(pktin = sftp_recv());
667 dirh = fxp_opendir_recv(pktin, rreq);
670 printf("Unable to open %s: %s\n", dirname, fxp_error());
672 nnames = namesize = 0;
677 sftp_register(req = fxp_readdir_send(dirh));
678 rreq = sftp_find_request(pktin = sftp_recv());
680 names = fxp_readdir_recv(pktin, rreq);
683 if (fxp_error_type() == SSH_FX_EOF)
685 printf("Reading directory %s: %s\n", dirname, fxp_error());
688 if (names->nnames == 0) {
689 fxp_free_names(names);
693 if (nnames + names->nnames >= namesize) {
694 namesize += names->nnames + 128;
695 ournames = sresize(ournames, namesize, struct fxp_name);
698 for (i = 0; i < names->nnames; i++)
699 ournames[nnames++] = names->names[i];
700 names->nnames = 0; /* prevent free_names */
701 fxp_free_names(names);
703 sftp_register(req = fxp_close_send(dirh));
704 rreq = sftp_find_request(pktin = sftp_recv());
706 fxp_close_recv(pktin, rreq);
709 * Now we have our filenames. Sort them by actual file
710 * name, and then output the longname parts.
712 qsort(ournames, nnames, sizeof(*ournames), sftp_ls_compare);
717 for (i = 0; i < nnames; i++)
718 printf("%s\n", ournames[i].longname);
722 /* ----------------------------------------------------------------------
723 * Helper routines that contain the actual SCP protocol elements,
724 * implemented both as SCP1 and SFTP.
727 static struct scp_sftp_dirstack {
728 struct scp_sftp_dirstack *next;
729 struct fxp_name *names;
730 int namepos, namelen;
733 int matched_something; /* wildcard match set was non-empty */
734 } *scp_sftp_dirstack_head;
735 static char *scp_sftp_remotepath, *scp_sftp_currentname;
736 static char *scp_sftp_wildcard;
737 static int scp_sftp_targetisdir, scp_sftp_donethistarget;
738 static int scp_sftp_preserve, scp_sftp_recursive;
739 static unsigned long scp_sftp_mtime, scp_sftp_atime;
740 static int scp_has_times;
741 static struct fxp_handle *scp_sftp_filehandle;
742 static struct fxp_xfer *scp_sftp_xfer;
743 static uint64 scp_sftp_fileoffset;
745 int scp_source_setup(char *target, int shouldbedir)
749 * Find out whether the target filespec is in fact a
752 struct sftp_packet *pktin;
753 struct sftp_request *req, *rreq;
754 struct fxp_attrs attrs;
758 tell_user(stderr, "unable to initialise SFTP: %s", fxp_error());
763 sftp_register(req = fxp_stat_send(target));
764 rreq = sftp_find_request(pktin = sftp_recv());
766 ret = fxp_stat_recv(pktin, rreq, &attrs);
768 if (!ret || !(attrs.flags & SSH_FILEXFER_ATTR_PERMISSIONS))
769 scp_sftp_targetisdir = 0;
771 scp_sftp_targetisdir = (attrs.permissions & 0040000) != 0;
773 if (shouldbedir && !scp_sftp_targetisdir) {
774 bump("pscp: remote filespec %s: not a directory\n", target);
777 scp_sftp_remotepath = dupstr(target);
786 int scp_send_errmsg(char *str)
789 /* do nothing; we never need to send our errors to the server */
791 back->send(backhandle, "\001", 1);/* scp protocol error prefix */
792 back->send(backhandle, str, strlen(str));
794 return 0; /* can't fail */
797 int scp_send_filetimes(unsigned long mtime, unsigned long atime)
800 scp_sftp_mtime = mtime;
801 scp_sftp_atime = atime;
806 sprintf(buf, "T%lu 0 %lu 0\n", mtime, atime);
807 back->send(backhandle, buf, strlen(buf));
812 int scp_send_filename(char *name, uint64 size, int modes)
816 struct sftp_packet *pktin;
817 struct sftp_request *req, *rreq;
819 if (scp_sftp_targetisdir) {
820 fullname = dupcat(scp_sftp_remotepath, "/", name, NULL);
822 fullname = dupstr(scp_sftp_remotepath);
825 sftp_register(req = fxp_open_send(fullname, SSH_FXF_WRITE |
826 SSH_FXF_CREAT | SSH_FXF_TRUNC));
827 rreq = sftp_find_request(pktin = sftp_recv());
829 scp_sftp_filehandle = fxp_open_recv(pktin, rreq);
831 if (!scp_sftp_filehandle) {
832 tell_user(stderr, "pscp: unable to open %s: %s",
833 fullname, fxp_error());
837 scp_sftp_fileoffset = uint64_make(0, 0);
838 scp_sftp_xfer = xfer_upload_init(scp_sftp_filehandle,
839 scp_sftp_fileoffset);
845 uint64_decimal(size, sizestr);
846 sprintf(buf, "C%04o %s ", modes, sizestr);
847 back->send(backhandle, buf, strlen(buf));
848 back->send(backhandle, name, strlen(name));
849 back->send(backhandle, "\n", 1);
854 int scp_send_filedata(char *data, int len)
858 struct sftp_packet *pktin;
860 if (!scp_sftp_filehandle) {
864 while (!xfer_upload_ready(scp_sftp_xfer)) {
866 ret = xfer_upload_gotpkt(scp_sftp_xfer, pktin);
868 tell_user(stderr, "error while writing: %s\n", fxp_error());
874 xfer_upload_data(scp_sftp_xfer, data, len);
876 scp_sftp_fileoffset = uint64_add32(scp_sftp_fileoffset, len);
879 int bufsize = back->send(backhandle, data, len);
882 * If the network transfer is backing up - that is, the
883 * remote site is not accepting data as fast as we can
884 * produce it - then we must loop on network events until
885 * we have space in the buffer again.
887 while (bufsize > MAX_SCP_BUFSIZE) {
888 if (ssh_sftp_loop_iteration() < 0)
890 bufsize = back->sendbuffer(backhandle);
897 int scp_send_finish(void)
900 struct fxp_attrs attrs;
901 struct sftp_packet *pktin;
902 struct sftp_request *req, *rreq;
905 while (!xfer_done(scp_sftp_xfer)) {
907 xfer_upload_gotpkt(scp_sftp_xfer, pktin);
909 xfer_cleanup(scp_sftp_xfer);
911 if (!scp_sftp_filehandle) {
915 attrs.flags = SSH_FILEXFER_ATTR_ACMODTIME;
916 attrs.atime = scp_sftp_atime;
917 attrs.mtime = scp_sftp_mtime;
918 sftp_register(req = fxp_fsetstat_send(scp_sftp_filehandle, attrs));
919 rreq = sftp_find_request(pktin = sftp_recv());
921 ret = fxp_fsetstat_recv(pktin, rreq);
923 tell_user(stderr, "unable to set file times: %s\n", fxp_error());
927 sftp_register(req = fxp_close_send(scp_sftp_filehandle));
928 rreq = sftp_find_request(pktin = sftp_recv());
930 fxp_close_recv(pktin, rreq);
934 back->send(backhandle, "", 1);
939 char *scp_save_remotepath(void)
942 return scp_sftp_remotepath;
947 void scp_restore_remotepath(char *data)
950 scp_sftp_remotepath = data;
953 int scp_send_dirname(char *name, int modes)
958 struct fxp_attrs attrs;
959 struct sftp_packet *pktin;
960 struct sftp_request *req, *rreq;
963 if (scp_sftp_targetisdir) {
964 fullname = dupcat(scp_sftp_remotepath, "/", name, NULL);
966 fullname = dupstr(scp_sftp_remotepath);
970 * We don't worry about whether we managed to create the
971 * directory, because if it exists already it's OK just to
972 * use it. Instead, we will stat it afterwards, and if it
973 * exists and is a directory we will assume we were either
974 * successful or it didn't matter.
976 sftp_register(req = fxp_mkdir_send(fullname));
977 rreq = sftp_find_request(pktin = sftp_recv());
979 ret = fxp_mkdir_recv(pktin, rreq);
984 err = "server reported no error";
986 sftp_register(req = fxp_stat_send(fullname));
987 rreq = sftp_find_request(pktin = sftp_recv());
989 ret = fxp_stat_recv(pktin, rreq, &attrs);
991 if (!ret || !(attrs.flags & SSH_FILEXFER_ATTR_PERMISSIONS) ||
992 !(attrs.permissions & 0040000)) {
993 tell_user(stderr, "unable to create directory %s: %s",
999 scp_sftp_remotepath = fullname;
1004 sprintf(buf, "D%04o 0 ", modes);
1005 back->send(backhandle, buf, strlen(buf));
1006 back->send(backhandle, name, strlen(name));
1007 back->send(backhandle, "\n", 1);
1012 int scp_send_enddir(void)
1015 sfree(scp_sftp_remotepath);
1018 back->send(backhandle, "E\n", 2);
1024 * Yes, I know; I have an scp_sink_setup _and_ an scp_sink_init.
1025 * That's bad. The difference is that scp_sink_setup is called once
1026 * right at the start, whereas scp_sink_init is called to
1027 * initialise every level of recursion in the protocol.
1029 int scp_sink_setup(char *source, int preserve, int recursive)
1035 tell_user(stderr, "unable to initialise SFTP: %s", fxp_error());
1040 * It's possible that the source string we've been given
1041 * contains a wildcard. If so, we must split the directory
1042 * away from the wildcard itself (throwing an error if any
1043 * wildcardness comes before the final slash) and arrange
1044 * things so that a dirstack entry will be set up.
1046 newsource = snewn(1+strlen(source), char);
1047 if (!wc_unescape(newsource, source)) {
1048 /* Yes, here we go; it's a wildcard. Bah. */
1049 char *dupsource, *lastpart, *dirpart, *wildcard;
1050 dupsource = dupstr(source);
1051 lastpart = stripslashes(dupsource, 0);
1052 wildcard = dupstr(lastpart);
1054 if (*dupsource && dupsource[1]) {
1056 * The remains of dupsource are at least two
1057 * characters long, meaning the pathname wasn't
1058 * empty or just `/'. Hence, we remove the trailing
1061 lastpart[-1] = '\0';
1062 } else if (!*dupsource) {
1064 * The remains of dupsource are _empty_ - the whole
1065 * pathname was a wildcard. Hence we need to
1066 * replace it with ".".
1069 dupsource = dupstr(".");
1073 * Now we have separated our string into dupsource (the
1074 * directory part) and wildcard. Both of these will
1075 * need freeing at some point. Next step is to remove
1076 * wildcard escapes from the directory part, throwing
1077 * an error if it contains a real wildcard.
1079 dirpart = snewn(1+strlen(dupsource), char);
1080 if (!wc_unescape(dirpart, dupsource)) {
1081 tell_user(stderr, "%s: multiple-level wildcards unsupported",
1091 * Now we have dirpart (unescaped, ie a valid remote
1092 * path), and wildcard (a wildcard). This will be
1093 * sufficient to arrange a dirstack entry.
1095 scp_sftp_remotepath = dirpart;
1096 scp_sftp_wildcard = wildcard;
1099 scp_sftp_remotepath = newsource;
1100 scp_sftp_wildcard = NULL;
1102 scp_sftp_preserve = preserve;
1103 scp_sftp_recursive = recursive;
1104 scp_sftp_donethistarget = 0;
1105 scp_sftp_dirstack_head = NULL;
1110 int scp_sink_init(void)
1113 back->send(backhandle, "", 1);
1118 #define SCP_SINK_FILE 1
1119 #define SCP_SINK_DIR 2
1120 #define SCP_SINK_ENDDIR 3
1121 #define SCP_SINK_RETRY 4 /* not an action; just try again */
1122 struct scp_sink_action {
1123 int action; /* FILE, DIR, ENDDIR */
1124 char *buf; /* will need freeing after use */
1125 char *name; /* filename or dirname (not ENDDIR) */
1126 int mode; /* access mode (not ENDDIR) */
1127 uint64 size; /* file size (not ENDDIR) */
1128 int settime; /* 1 if atime and mtime are filled */
1129 unsigned long atime, mtime; /* access times for the file */
1132 int scp_get_sink_action(struct scp_sink_action *act)
1136 int must_free_fname;
1137 struct fxp_attrs attrs;
1138 struct sftp_packet *pktin;
1139 struct sftp_request *req, *rreq;
1142 if (!scp_sftp_dirstack_head) {
1143 if (!scp_sftp_donethistarget) {
1145 * Simple case: we are only dealing with one file.
1147 fname = scp_sftp_remotepath;
1148 must_free_fname = 0;
1149 scp_sftp_donethistarget = 1;
1152 * Even simpler case: one file _which we've done_.
1153 * Return 1 (finished).
1159 * We're now in the middle of stepping through a list
1160 * of names returned from fxp_readdir(); so let's carry
1163 struct scp_sftp_dirstack *head = scp_sftp_dirstack_head;
1164 while (head->namepos < head->namelen &&
1165 (is_dots(head->names[head->namepos].filename) ||
1167 !wc_match(head->wildcard,
1168 head->names[head->namepos].filename))))
1169 head->namepos++; /* skip . and .. */
1170 if (head->namepos < head->namelen) {
1171 head->matched_something = 1;
1172 fname = dupcat(head->dirpath, "/",
1173 head->names[head->namepos++].filename,
1175 must_free_fname = 1;
1178 * We've come to the end of the list; pop it off
1179 * the stack and return an ENDDIR action (or RETRY
1180 * if this was a wildcard match).
1182 if (head->wildcard) {
1183 act->action = SCP_SINK_RETRY;
1184 if (!head->matched_something) {
1185 tell_user(stderr, "pscp: wildcard '%s' matched "
1186 "no files", head->wildcard);
1189 sfree(head->wildcard);
1192 act->action = SCP_SINK_ENDDIR;
1195 sfree(head->dirpath);
1197 scp_sftp_dirstack_head = head->next;
1205 * Now we have a filename. Stat it, and see if it's a file
1208 sftp_register(req = fxp_stat_send(fname));
1209 rreq = sftp_find_request(pktin = sftp_recv());
1210 assert(rreq == req);
1211 ret = fxp_stat_recv(pktin, rreq, &attrs);
1213 if (!ret || !(attrs.flags & SSH_FILEXFER_ATTR_PERMISSIONS)) {
1214 tell_user(stderr, "unable to identify %s: %s", fname,
1215 ret ? "file type not supplied" : fxp_error());
1220 if (attrs.permissions & 0040000) {
1221 struct scp_sftp_dirstack *newitem;
1222 struct fxp_handle *dirhandle;
1223 int nnames, namesize;
1224 struct fxp_name *ournames;
1225 struct fxp_names *names;
1228 * It's a directory. If we're not in recursive mode,
1229 * this merits a complaint (which is fatal if the name
1230 * was specified directly, but not if it was matched by
1233 * We skip this complaint completely if
1234 * scp_sftp_wildcard is set, because that's an
1235 * indication that we're not actually supposed to
1236 * _recursively_ transfer the dir, just scan it for
1237 * things matching the wildcard.
1239 if (!scp_sftp_recursive && !scp_sftp_wildcard) {
1240 tell_user(stderr, "pscp: %s: is a directory", fname);
1242 if (must_free_fname) sfree(fname);
1243 if (scp_sftp_dirstack_head) {
1244 act->action = SCP_SINK_RETRY;
1252 * Otherwise, the fun begins. We must fxp_opendir() the
1253 * directory, slurp the filenames into memory, return
1254 * SCP_SINK_DIR (unless this is a wildcard match), and
1255 * set targetisdir. The next time we're called, we will
1256 * run through the list of filenames one by one,
1257 * matching them against a wildcard if present.
1259 * If targetisdir is _already_ set (meaning we're
1260 * already in the middle of going through another such
1261 * list), we must push the other (target,namelist) pair
1264 sftp_register(req = fxp_opendir_send(fname));
1265 rreq = sftp_find_request(pktin = sftp_recv());
1266 assert(rreq == req);
1267 dirhandle = fxp_opendir_recv(pktin, rreq);
1270 tell_user(stderr, "scp: unable to open directory %s: %s",
1271 fname, fxp_error());
1272 if (must_free_fname) sfree(fname);
1276 nnames = namesize = 0;
1281 sftp_register(req = fxp_readdir_send(dirhandle));
1282 rreq = sftp_find_request(pktin = sftp_recv());
1283 assert(rreq == req);
1284 names = fxp_readdir_recv(pktin, rreq);
1286 if (names == NULL) {
1287 if (fxp_error_type() == SSH_FX_EOF)
1289 tell_user(stderr, "scp: reading directory %s: %s\n",
1290 fname, fxp_error());
1291 if (must_free_fname) sfree(fname);
1296 if (names->nnames == 0) {
1297 fxp_free_names(names);
1300 if (nnames + names->nnames >= namesize) {
1301 namesize += names->nnames + 128;
1302 ournames = sresize(ournames, namesize, struct fxp_name);
1304 for (i = 0; i < names->nnames; i++) {
1305 if (!strcmp(names->names[i].filename, ".") ||
1306 !strcmp(names->names[i].filename, "..")) {
1308 * . and .. are normal consequences of
1309 * reading a directory, and aren't worth
1310 * complaining about.
1312 } else if (!vet_filename(names->names[i].filename)) {
1313 tell_user(stderr, "ignoring potentially dangerous server-"
1314 "supplied filename '%s'\n",
1315 names->names[i].filename);
1317 ournames[nnames++] = names->names[i];
1319 names->nnames = 0; /* prevent free_names */
1320 fxp_free_names(names);
1322 sftp_register(req = fxp_close_send(dirhandle));
1323 rreq = sftp_find_request(pktin = sftp_recv());
1324 assert(rreq == req);
1325 fxp_close_recv(pktin, rreq);
1327 newitem = snew(struct scp_sftp_dirstack);
1328 newitem->next = scp_sftp_dirstack_head;
1329 newitem->names = ournames;
1330 newitem->namepos = 0;
1331 newitem->namelen = nnames;
1332 if (must_free_fname)
1333 newitem->dirpath = fname;
1335 newitem->dirpath = dupstr(fname);
1336 if (scp_sftp_wildcard) {
1337 newitem->wildcard = scp_sftp_wildcard;
1338 newitem->matched_something = 0;
1339 scp_sftp_wildcard = NULL;
1341 newitem->wildcard = NULL;
1343 scp_sftp_dirstack_head = newitem;
1345 if (newitem->wildcard) {
1346 act->action = SCP_SINK_RETRY;
1348 act->action = SCP_SINK_DIR;
1349 act->buf = dupstr(stripslashes(fname, 0));
1350 act->name = act->buf;
1351 act->size = uint64_make(0,0); /* duhh, it's a directory */
1352 act->mode = 07777 & attrs.permissions;
1353 if (scp_sftp_preserve &&
1354 (attrs.flags & SSH_FILEXFER_ATTR_ACMODTIME)) {
1355 act->atime = attrs.atime;
1356 act->mtime = attrs.mtime;
1365 * It's a file. Return SCP_SINK_FILE.
1367 act->action = SCP_SINK_FILE;
1368 act->buf = dupstr(stripslashes(fname, 0));
1369 act->name = act->buf;
1370 if (attrs.flags & SSH_FILEXFER_ATTR_SIZE) {
1371 act->size = attrs.size;
1373 act->size = uint64_make(ULONG_MAX,ULONG_MAX); /* no idea */
1374 act->mode = 07777 & attrs.permissions;
1375 if (scp_sftp_preserve &&
1376 (attrs.flags & SSH_FILEXFER_ATTR_ACMODTIME)) {
1377 act->atime = attrs.atime;
1378 act->mtime = attrs.mtime;
1382 if (must_free_fname)
1383 scp_sftp_currentname = fname;
1385 scp_sftp_currentname = dupstr(fname);
1400 if (ssh_scp_recv((unsigned char *) &ch, 1) <= 0)
1403 bump("Protocol error: Unexpected newline");
1407 if (ssh_scp_recv((unsigned char *) &ch, 1) <= 0)
1408 bump("Lost connection");
1411 act->buf = sresize(act->buf, bufsize, char);
1414 } while (ch != '\n');
1415 act->buf[i - 1] = '\0';
1417 case '\01': /* error */
1418 tell_user(stderr, "%s\n", act->buf);
1420 continue; /* go round again */
1421 case '\02': /* fatal error */
1422 bump("%s", act->buf);
1424 back->send(backhandle, "", 1);
1425 act->action = SCP_SINK_ENDDIR;
1428 if (sscanf(act->buf, "%ld %*d %ld %*d",
1429 &act->mtime, &act->atime) == 2) {
1431 back->send(backhandle, "", 1);
1432 continue; /* go round again */
1434 bump("Protocol error: Illegal time format");
1437 act->action = (action == 'C' ? SCP_SINK_FILE : SCP_SINK_DIR);
1440 bump("Protocol error: Expected control record");
1443 * We will go round this loop only once, unless we hit
1450 * If we get here, we must have seen SCP_SINK_FILE or
1456 if (sscanf(act->buf, "%o %s %n", &act->mode, sizestr, &i) != 2)
1457 bump("Protocol error: Illegal file descriptor format");
1458 act->size = uint64_from_decimal(sizestr);
1459 act->name = act->buf + i;
1465 int scp_accept_filexfer(void)
1468 struct sftp_packet *pktin;
1469 struct sftp_request *req, *rreq;
1471 sftp_register(req = fxp_open_send(scp_sftp_currentname, SSH_FXF_READ));
1472 rreq = sftp_find_request(pktin = sftp_recv());
1473 assert(rreq == req);
1474 scp_sftp_filehandle = fxp_open_recv(pktin, rreq);
1476 if (!scp_sftp_filehandle) {
1477 tell_user(stderr, "pscp: unable to open %s: %s",
1478 scp_sftp_currentname, fxp_error());
1482 scp_sftp_fileoffset = uint64_make(0, 0);
1483 scp_sftp_xfer = xfer_download_init(scp_sftp_filehandle,
1484 scp_sftp_fileoffset);
1485 sfree(scp_sftp_currentname);
1488 back->send(backhandle, "", 1);
1489 return 0; /* can't fail */
1493 int scp_recv_filedata(char *data, int len)
1496 struct sftp_packet *pktin;
1500 xfer_download_queue(scp_sftp_xfer);
1501 pktin = sftp_recv();
1502 ret = xfer_download_gotpkt(scp_sftp_xfer, pktin);
1505 tell_user(stderr, "pscp: error while reading: %s", fxp_error());
1510 if (xfer_download_data(scp_sftp_xfer, &vbuf, &actuallen)) {
1512 * This assertion relies on the fact that the natural
1513 * block size used in the xfer manager is at most that
1514 * used in this module. I don't like crossing layers in
1515 * this way, but it'll do for now.
1517 assert(actuallen <= len);
1518 memcpy(data, vbuf, actuallen);
1523 scp_sftp_fileoffset = uint64_add32(scp_sftp_fileoffset, actuallen);
1527 return ssh_scp_recv((unsigned char *) data, len);
1531 int scp_finish_filerecv(void)
1534 struct sftp_packet *pktin;
1535 struct sftp_request *req, *rreq;
1538 * Ensure that xfer_done() will work correctly, so we can
1539 * clean up any outstanding requests from the file
1542 xfer_set_error(scp_sftp_xfer);
1543 while (!xfer_done(scp_sftp_xfer)) {
1547 pktin = sftp_recv();
1548 xfer_download_gotpkt(scp_sftp_xfer, pktin);
1549 if (xfer_download_data(scp_sftp_xfer, &vbuf, &len))
1552 xfer_cleanup(scp_sftp_xfer);
1554 sftp_register(req = fxp_close_send(scp_sftp_filehandle));
1555 rreq = sftp_find_request(pktin = sftp_recv());
1556 assert(rreq == req);
1557 fxp_close_recv(pktin, rreq);
1560 back->send(backhandle, "", 1);
1565 /* ----------------------------------------------------------------------
1566 * Send an error message to the other side and to the screen.
1567 * Increment error counter.
1569 static void run_err(const char *fmt, ...)
1575 str = dupvprintf(fmt, ap);
1576 str2 = dupcat("scp: ", str, "\n", NULL);
1578 scp_send_errmsg(str2);
1579 tell_user(stderr, "%s", str2);
1585 * Execute the source part of the SCP protocol.
1587 static void source(char *src)
1590 unsigned long mtime, atime;
1596 time_t stat_starttime, stat_lasttime;
1598 attr = file_type(src);
1599 if (attr == FILE_TYPE_NONEXISTENT ||
1600 attr == FILE_TYPE_WEIRD) {
1601 run_err("%s: %s file or directory", src,
1602 (attr == FILE_TYPE_WEIRD ? "Not a" : "No such"));
1606 if (attr == FILE_TYPE_DIRECTORY) {
1609 * Avoid . and .. directories.
1612 p = strrchr(src, '/');
1614 p = strrchr(src, '\\');
1619 if (!strcmp(p, ".") || !strcmp(p, ".."))
1620 /* skip . and .. */ ;
1624 run_err("%s: not a regular file", src);
1629 if ((last = strrchr(src, '/')) == NULL)
1633 if (strrchr(last, '\\') != NULL)
1634 last = strrchr(last, '\\') + 1;
1635 if (last == src && strchr(src, ':') != NULL)
1636 last = strchr(src, ':') + 1;
1638 f = open_existing_file(src, &size, &mtime, &atime);
1640 run_err("%s: Cannot open file", src);
1644 if (scp_send_filetimes(mtime, atime))
1650 uint64_decimal(size, sizestr);
1651 tell_user(stderr, "Sending file %s, size=%s", last, sizestr);
1653 if (scp_send_filename(last, size, 0644))
1656 stat_bytes = uint64_make(0,0);
1657 stat_starttime = time(NULL);
1660 for (i = uint64_make(0,0);
1661 uint64_compare(i,size) < 0;
1662 i = uint64_add32(i,4096)) {
1663 char transbuf[4096];
1666 if (uint64_compare(uint64_add32(i, k),size) > 0) /* i + k > size */
1667 k = (uint64_subtract(size, i)).lo; /* k = size - i; */
1668 if ((j = read_from_file(f, transbuf, k)) != k) {
1671 bump("%s: Read error", src);
1673 if (scp_send_filedata(transbuf, k))
1674 bump("%s: Network error occurred", src);
1677 stat_bytes = uint64_add32(stat_bytes, k);
1678 if (time(NULL) != stat_lasttime ||
1679 (uint64_compare(uint64_add32(i, k), size) == 0)) {
1680 stat_lasttime = time(NULL);
1681 print_stats(last, size, stat_bytes,
1682 stat_starttime, stat_lasttime);
1689 (void) scp_send_finish();
1693 * Recursively send the contents of a directory.
1695 static void rsource(char *src)
1701 if ((last = strrchr(src, '/')) == NULL)
1705 if (strrchr(last, '\\') != NULL)
1706 last = strrchr(last, '\\') + 1;
1707 if (last == src && strchr(src, ':') != NULL)
1708 last = strchr(src, ':') + 1;
1710 /* maybe send filetime */
1712 save_target = scp_save_remotepath();
1715 tell_user(stderr, "Entering directory: %s", last);
1716 if (scp_send_dirname(last, 0755))
1719 dir = open_directory(src);
1722 while ((filename = read_filename(dir)) != NULL) {
1723 char *foundfile = dupcat(src, "/", filename, NULL);
1729 close_directory(dir);
1731 (void) scp_send_enddir();
1733 scp_restore_remotepath(save_target);
1737 * Execute the sink part of the SCP protocol.
1739 static void sink(char *targ, char *src)
1749 time_t stat_starttime, stat_lasttime;
1752 attr = file_type(targ);
1753 if (attr == FILE_TYPE_DIRECTORY)
1756 if (targetshouldbedirectory && !targisdir)
1757 bump("%s: Not a directory", targ);
1761 struct scp_sink_action act;
1762 if (scp_get_sink_action(&act))
1765 if (act.action == SCP_SINK_ENDDIR)
1768 if (act.action == SCP_SINK_RETRY)
1773 * Prevent the remote side from maliciously writing to
1774 * files outside the target area by sending a filename
1775 * containing `../'. In fact, it shouldn't be sending
1776 * filenames with any slashes or colons in at all; so
1777 * we'll find the last slash, backslash or colon in the
1778 * filename and use only the part after that. (And
1781 * In addition, we also ensure here that if we're
1782 * copying a single file and the target is a directory
1783 * (common usage: `pscp host:filename .') the remote
1784 * can't send us a _different_ file name. We can
1785 * distinguish this case because `src' will be non-NULL
1786 * and the last component of that will fail to match
1787 * (the last component of) the name sent.
1789 * Well, not always; if `src' is a wildcard, we do
1790 * expect to get back filenames that don't correspond
1791 * exactly to it. Ideally in this case, we would like
1792 * to ensure that the returned filename actually
1793 * matches the wildcard pattern - but one of SCP's
1794 * protocol infelicities is that wildcard matching is
1795 * done at the server end _by the server's rules_ and
1796 * so in general this is infeasible. Hence, we only
1797 * accept filenames that don't correspond to `src' if
1798 * unsafe mode is enabled or we are using SFTP (which
1799 * resolves remote wildcards on the client side and can
1802 char *striptarget, *stripsrc;
1804 striptarget = stripslashes(act.name, 1);
1805 if (striptarget != act.name) {
1806 tell_user(stderr, "warning: remote host sent a compound"
1807 " pathname '%s'", act.name);
1808 tell_user(stderr, " renaming local file to '%s'",
1813 * Also check to see if the target filename is '.' or
1814 * '..', or indeed '...' and so on because Windows
1815 * appears to interpret those like '..'.
1817 if (is_dots(striptarget)) {
1818 bump("security violation: remote host attempted to write to"
1819 " a '.' or '..' path!");
1823 stripsrc = stripslashes(src, 1);
1824 if (strcmp(striptarget, stripsrc) &&
1825 !using_sftp && !scp_unsafe_mode) {
1826 tell_user(stderr, "warning: remote host tried to write "
1827 "to a file called '%s'", striptarget);
1828 tell_user(stderr, " when we requested a file "
1829 "called '%s'.", stripsrc);
1830 tell_user(stderr, " If this is a wildcard, "
1831 "consider upgrading to SSH-2 or using");
1832 tell_user(stderr, " the '-unsafe' option. Renaming"
1833 " of this file has been disallowed.");
1834 /* Override the name the server provided with our own. */
1835 striptarget = stripsrc;
1839 if (targ[0] != '\0')
1840 destfname = dir_file_cat(targ, striptarget);
1842 destfname = dupstr(striptarget);
1845 * In this branch of the if, the target area is a
1846 * single file with an explicitly specified name in any
1847 * case, so there's no danger.
1849 destfname = dupstr(targ);
1851 attr = file_type(destfname);
1852 exists = (attr != FILE_TYPE_NONEXISTENT);
1854 if (act.action == SCP_SINK_DIR) {
1855 if (exists && attr != FILE_TYPE_DIRECTORY) {
1856 run_err("%s: Not a directory", destfname);
1860 if (!create_directory(destfname)) {
1861 run_err("%s: Cannot create directory", destfname);
1865 sink(destfname, NULL);
1866 /* can we set the timestamp for directories ? */
1870 f = open_new_file(destfname);
1872 run_err("%s: Cannot create file", destfname);
1876 if (scp_accept_filexfer())
1879 stat_bytes = uint64_make(0, 0);
1880 stat_starttime = time(NULL);
1882 stat_name = stripslashes(destfname, 1);
1884 received = uint64_make(0, 0);
1885 while (uint64_compare(received,act.size) < 0) {
1886 char transbuf[32768];
1889 blksize = uint64_make(0, 32768);
1890 if (uint64_compare(blksize,uint64_subtract(act.size,received)) > 0)
1891 blksize = uint64_subtract(act.size,received);
1892 read = scp_recv_filedata(transbuf, (int)blksize.lo);
1894 bump("Lost connection");
1897 if (write_to_file(f, transbuf, read) != (int)read) {
1899 /* FIXME: in sftp we can actually abort the transfer */
1901 printf("\r%-25.25s | %50s\n",
1903 "Write error.. waiting for end of file");
1907 stat_bytes = uint64_add32(stat_bytes,read);
1908 if (time(NULL) > stat_lasttime ||
1909 uint64_compare(uint64_add32(received, read), act.size) == 0) {
1910 stat_lasttime = time(NULL);
1911 print_stats(stat_name, act.size, stat_bytes,
1912 stat_starttime, stat_lasttime);
1915 received = uint64_add32(received, read);
1918 set_file_times(f, act.mtime, act.atime);
1923 run_err("%s: Write error", destfname);
1926 (void) scp_finish_filerecv();
1933 * We will copy local files to a remote server.
1935 static void toremote(int argc, char *argv[])
1937 char *src, *targ, *host, *user;
1941 targ = argv[argc - 1];
1943 /* Separate host from filename */
1947 bump("targ == NULL in toremote()");
1951 /* Substitute "." for empty target */
1953 /* Separate host and username */
1955 host = strrchr(host, '@');
1966 if (colon(argv[0]) != NULL)
1967 bump("%s: Remote to remote not supported", argv[0]);
1969 wc_type = test_wildcard(argv[0], 1);
1970 if (wc_type == WCTYPE_NONEXISTENT)
1971 bump("%s: No such file or directory\n", argv[0]);
1972 else if (wc_type == WCTYPE_WILDCARD)
1973 targetshouldbedirectory = 1;
1976 cmd = dupprintf("scp%s%s%s%s -t %s",
1977 verbose ? " -v" : "",
1978 recursive ? " -r" : "",
1979 preserve ? " -p" : "",
1980 targetshouldbedirectory ? " -d" : "", targ);
1981 do_cmd(host, user, cmd);
1984 if (scp_source_setup(targ, targetshouldbedirectory))
1987 for (i = 0; i < argc - 1; i++) {
1989 if (colon(src) != NULL) {
1990 tell_user(stderr, "%s: Remote to remote not supported\n", src);
1995 wc_type = test_wildcard(src, 1);
1996 if (wc_type == WCTYPE_NONEXISTENT) {
1997 run_err("%s: No such file or directory", src);
1999 } else if (wc_type == WCTYPE_FILENAME) {
2003 WildcardMatcher *wc;
2006 wc = begin_wildcard_matching(src);
2008 run_err("%s: No such file or directory", src);
2012 while ((filename = wildcard_get_filename(wc)) != NULL) {
2017 finish_wildcard_matching(wc);
2023 * We will copy files from a remote server to the local machine.
2025 static void tolocal(int argc, char *argv[])
2027 char *src, *targ, *host, *user;
2031 bump("More than one remote source not supported");
2036 /* Separate host from filename */
2040 bump("Local to local copy not supported");
2044 /* Substitute "." for empty filename */
2046 /* Separate username and hostname */
2048 host = strrchr(host, '@');
2058 cmd = dupprintf("scp%s%s%s%s -f %s",
2059 verbose ? " -v" : "",
2060 recursive ? " -r" : "",
2061 preserve ? " -p" : "",
2062 targetshouldbedirectory ? " -d" : "", src);
2063 do_cmd(host, user, cmd);
2066 if (scp_sink_setup(src, preserve, recursive))
2073 * We will issue a list command to get a remote directory.
2075 static void get_dir_list(int argc, char *argv[])
2077 char *src, *host, *user;
2083 /* Separate host from filename */
2087 bump("Local to local copy not supported");
2091 /* Substitute "." for empty filename */
2093 /* Separate username and hostname */
2095 host = strrchr(host, '@');
2105 cmd = snewn(4 * strlen(src) + 100, char);
2106 strcpy(cmd, "ls -la '");
2107 p = cmd + strlen(cmd);
2108 for (q = src; *q; q++) {
2121 do_cmd(host, user, cmd);
2125 scp_sftp_listdir(src);
2127 while (ssh_scp_recv((unsigned char *) &c, 1) > 0)
2128 tell_char(stdout, c);
2133 * Short description of parameters.
2135 static void usage(void)
2137 printf("PuTTY Secure Copy client\n");
2138 printf("%s\n", ver);
2139 printf("Usage: pscp [options] [user@]host:source target\n");
2141 (" pscp [options] source [source...] [user@]host:target\n");
2142 printf(" pscp [options] -ls [user@]host:filespec\n");
2143 printf("Options:\n");
2144 printf(" -V print version information and exit\n");
2145 printf(" -pgpfp print PGP key fingerprints and exit\n");
2146 printf(" -p preserve file attributes\n");
2147 printf(" -q quiet, don't show statistics\n");
2148 printf(" -r copy directories recursively\n");
2149 printf(" -v show verbose messages\n");
2150 printf(" -load sessname Load settings from saved session\n");
2151 printf(" -P port connect to specified port\n");
2152 printf(" -l user connect with specified username\n");
2153 printf(" -pw passw login with specified password\n");
2154 printf(" -1 -2 force use of particular SSH protocol version\n");
2155 printf(" -4 -6 force use of IPv4 or IPv6\n");
2156 printf(" -C enable compression\n");
2157 printf(" -i key private key file for authentication\n");
2158 printf(" -noagent disable use of Pageant\n");
2159 printf(" -agent enable use of Pageant\n");
2160 printf(" -batch disable all interactive prompts\n");
2161 printf(" -unsafe allow server-side wildcards (DANGEROUS)\n");
2162 printf(" -sftp force use of SFTP protocol\n");
2163 printf(" -scp force use of SCP protocol\n");
2166 * -gui is an internal option, used by GUI front ends to get
2167 * pscp to pass progress reports back to them. It's not an
2168 * ordinary user-accessible option, so it shouldn't be part of
2169 * the command-line help. The only people who need to know
2170 * about it are programmers, and they can read the source.
2173 (" -gui hWnd GUI mode with the windows handle for receiving messages\n");
2180 printf("pscp: %s\n", ver);
2184 void cmdline_error(char *p, ...)
2187 fprintf(stderr, "pscp: ");
2189 vfprintf(stderr, p, ap);
2191 fprintf(stderr, "\n try typing just \"pscp\" for help\n");
2196 * Main program. (Called `psftp_main' because it gets called from
2197 * *sftp.c; bit silly, I know, but it had to be called _something_.)
2199 int psftp_main(int argc, char *argv[])
2203 default_protocol = PROT_TELNET;
2206 #ifdef FLAG_SYNCAGENT
2210 cmdline_tooltype = TOOLTYPE_FILETRANSFER;
2213 /* Load Default Settings before doing anything else. */
2214 do_defaults(NULL, &cfg);
2215 loaded_session = FALSE;
2217 for (i = 1; i < argc; i++) {
2219 if (argv[i][0] != '-')
2221 ret = cmdline_process_param(argv[i], i+1<argc?argv[i+1]:NULL, 1, &cfg);
2223 cmdline_error("option \"%s\" requires an argument", argv[i]);
2224 } else if (ret == 2) {
2225 i++; /* skip next argument */
2226 } else if (ret == 1) {
2227 /* We have our own verbosity in addition to `flags'. */
2228 if (flags & FLAG_VERBOSE)
2230 } else if (strcmp(argv[i], "-pgpfp") == 0) {
2233 } else if (strcmp(argv[i], "-r") == 0) {
2235 } else if (strcmp(argv[i], "-p") == 0) {
2237 } else if (strcmp(argv[i], "-q") == 0) {
2239 } else if (strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "-?") == 0) {
2241 } else if (strcmp(argv[i], "-V") == 0) {
2243 } else if (strcmp(argv[i], "-ls") == 0) {
2245 } else if (strcmp(argv[i], "-batch") == 0) {
2246 console_batch_mode = 1;
2247 } else if (strcmp(argv[i], "-unsafe") == 0) {
2248 scp_unsafe_mode = 1;
2249 } else if (strcmp(argv[i], "-sftp") == 0) {
2250 try_scp = 0; try_sftp = 1;
2251 } else if (strcmp(argv[i], "-scp") == 0) {
2252 try_scp = 1; try_sftp = 0;
2253 } else if (strcmp(argv[i], "--") == 0) {
2257 cmdline_error("unknown option \"%s\"", argv[i]);
2267 get_dir_list(argc, argv);
2274 targetshouldbedirectory = 1;
2276 if (colon(argv[argc - 1]) != NULL)
2277 toremote(argc, argv);
2279 tolocal(argc, argv);
2282 if (back != NULL && back->connected(backhandle)) {
2284 back->special(backhandle, TS_EOF);
2285 ssh_scp_recv((unsigned char *) &ch, 1);
2290 console_provide_logctx(NULL);
2291 back->free(backhandle);
2295 return (errs == 0 ? 0 : 1);