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;
44 static int uploading = 0;
47 static void *backhandle;
51 static void source(const char *src);
52 static void rsource(const char *src);
53 static void sink(const char *targ, const char *src);
55 const char *const appname = "PSCP";
58 * The maximum amount of queued data we accept before we stop and
59 * wait for the server to process some.
61 #define MAX_SCP_BUFSIZE 16384
63 void ldisc_echoedit_update(void *handle) { }
65 static void tell_char(FILE *stream, char c)
70 static void tell_str(FILE *stream, const char *str)
74 for (i = 0; i < strlen(str); ++i)
75 tell_char(stream, str[i]);
78 static void tell_user(FILE *stream, const char *fmt, ...)
83 str = dupvprintf(fmt, ap);
85 str2 = dupcat(str, "\n", NULL);
87 tell_str(stream, str2);
92 * Print an error message and perform a fatal exit.
94 void fatalbox(const char *fmt, ...)
99 str = dupvprintf(fmt, ap);
100 str2 = dupcat("Fatal: ", str, "\n", NULL);
103 tell_str(stderr, str2);
109 void modalfatalbox(const char *fmt, ...)
114 str = dupvprintf(fmt, ap);
115 str2 = dupcat("Fatal: ", str, "\n", NULL);
118 tell_str(stderr, str2);
124 void nonfatal(const char *fmt, ...)
129 str = dupvprintf(fmt, ap);
130 str2 = dupcat("Error: ", str, "\n", NULL);
133 tell_str(stderr, str2);
137 void connection_fatal(void *frontend, const char *fmt, ...)
142 str = dupvprintf(fmt, ap);
143 str2 = dupcat("Fatal: ", str, "\n", NULL);
146 tell_str(stderr, str2);
154 * In pscp, all agent requests should be synchronous, so this is a
157 void agent_schedule_callback(void (*callback)(void *, void *, int),
158 void *callback_ctx, void *data, int len)
160 assert(!"We shouldn't be here");
164 * Receive a block of data from the SSH link. Block until all data
167 * To do this, we repeatedly call the SSH protocol module, with our
168 * own trap in from_backend() to catch the data that comes back. We
169 * do this until we have enough data.
172 static unsigned char *outptr; /* where to put the data */
173 static unsigned outlen; /* how much data required */
174 static unsigned char *pending = NULL; /* any spare data */
175 static unsigned pendlen = 0, pendsize = 0; /* length and phys. size of buffer */
176 int from_backend(void *frontend, int is_stderr, const char *data, int datalen)
178 unsigned char *p = (unsigned char *) data;
179 unsigned len = (unsigned) datalen;
182 * stderr data is just spouted to local stderr and otherwise
187 if (fwrite(data, 1, len, stderr) < len)
192 if ((outlen > 0) && (len > 0)) {
193 unsigned used = outlen;
196 memcpy(outptr, p, used);
204 if (pendsize < pendlen + len) {
205 pendsize = pendlen + len + 4096;
206 pending = sresize(pending, pendsize, unsigned char);
208 memcpy(pending + pendlen, p, len);
214 int from_backend_untrusted(void *frontend_handle, const char *data, int len)
217 * No "untrusted" output should get here (the way the code is
218 * currently, it's all diverted by FLAG_STDERR).
220 assert(!"Unexpected call to from_backend_untrusted()");
221 return 0; /* not reached */
223 int from_backend_eof(void *frontend)
226 * We usually expect to be the party deciding when to close the
227 * connection, so if we see EOF before we sent it ourselves, we
228 * should panic. The exception is if we're using old-style scp and
229 * downloading rather than uploading.
231 if ((using_sftp || uploading) && !sent_eof) {
232 connection_fatal(frontend,
233 "Received unexpected end-of-file from server");
237 static int ssh_scp_recv(unsigned char *buf, int len)
243 * See if the pending-input block contains some of what we
247 unsigned pendused = pendlen;
248 if (pendused > outlen)
250 memcpy(outptr, pending, pendused);
251 memmove(pending, pending + pendused, pendlen - pendused);
265 if (back->exitcode(backhandle) >= 0 || ssh_sftp_loop_iteration() < 0)
273 * Loop through the ssh connection and authentication process.
275 static void ssh_scp_init(void)
277 while (!back->sendok(backhandle)) {
278 if (back->exitcode(backhandle) >= 0) {
282 if (ssh_sftp_loop_iteration() < 0) {
288 /* Work out which backend we ended up using. */
289 if (!ssh_fallback_cmd(backhandle))
290 using_sftp = main_cmd_is_sftp;
292 using_sftp = fallback_cmd_is_sftp;
296 tell_user(stderr, "Using SFTP");
298 tell_user(stderr, "Using SCP1");
303 * Print an error message and exit after closing the SSH link.
305 static void bump(const char *fmt, ...)
310 str = dupvprintf(fmt, ap);
312 str2 = dupcat(str, "\n", NULL);
314 tell_str(stderr, str2);
318 if (back != NULL && back->connected(backhandle)) {
320 back->special(backhandle, TS_EOF);
322 ssh_scp_recv((unsigned char *) &ch, 1);
329 * Wait for the reply to a single SFTP request. Parallels the same
330 * function in psftp.c (but isn't centralised into sftp.c because the
331 * latter module handles SFTP only and shouldn't assume that SFTP is
332 * the only thing going on by calling connection_fatal).
334 struct sftp_packet *sftp_wait_for_reply(struct sftp_request *req)
336 struct sftp_packet *pktin;
337 struct sftp_request *rreq;
342 connection_fatal(NULL, "did not receive SFTP response packet "
344 rreq = sftp_find_request(pktin);
346 connection_fatal(NULL, "unable to understand SFTP response packet "
347 "from server: %s", fxp_error());
352 * Open an SSH connection to user@host and execute cmd.
354 static void do_cmd(char *host, char *user, char *cmd)
360 if (host == NULL || host[0] == '\0')
361 bump("Empty host name");
364 * Remove a colon suffix.
366 host[host_strcspn(host, ":")] = '\0';
369 * If we haven't loaded session details already (e.g., from -load),
370 * try looking for a session called "host".
372 if (!loaded_session) {
373 /* Try to load settings for `host' into a temporary config */
374 Conf *conf2 = conf_new();
375 conf_set_str(conf2, CONF_host, "");
376 do_defaults(host, conf2);
377 if (conf_get_str(conf2, CONF_host)[0] != '\0') {
378 /* Settings present and include hostname */
379 /* Re-load data into the real config. */
380 do_defaults(host, conf);
382 /* Session doesn't exist or mention a hostname. */
383 /* Use `host' as a bare hostname. */
384 conf_set_str(conf, CONF_host, host);
388 /* Patch in hostname `host' to session details. */
389 conf_set_str(conf, CONF_host, host);
393 * Force use of SSH. (If they got the protocol wrong we assume the
394 * port is useless too.)
396 if (conf_get_int(conf, CONF_protocol) != PROT_SSH) {
397 conf_set_int(conf, CONF_protocol, PROT_SSH);
398 conf_set_int(conf, CONF_port, 22);
402 * Enact command-line overrides.
404 cmdline_run_saved(conf);
407 * Muck about with the hostname in various ways.
410 char *hostbuf = dupstr(conf_get_str(conf, CONF_host));
411 char *host = hostbuf;
415 * Trim leading whitespace.
417 host += strspn(host, " \t");
420 * See if host is of the form user@host, and separate out
421 * the username if so.
423 if (host[0] != '\0') {
424 char *atsign = strrchr(host, '@');
427 conf_set_str(conf, CONF_username, host);
433 * Remove any remaining whitespace.
438 if (*q != ' ' && *q != '\t')
444 conf_set_str(conf, CONF_host, hostbuf);
449 if (user != NULL && user[0] != '\0') {
450 conf_set_str(conf, CONF_username, user);
451 } else if (conf_get_str(conf, CONF_username)[0] == '\0') {
452 user = get_username();
454 bump("Empty user name");
457 tell_user(stderr, "Guessing user name: %s", user);
458 conf_set_str(conf, CONF_username, user);
464 * Disable scary things which shouldn't be enabled for simple
465 * things like SCP and SFTP: agent forwarding, port forwarding,
468 conf_set_int(conf, CONF_x11_forward, 0);
469 conf_set_int(conf, CONF_agentfwd, 0);
470 conf_set_int(conf, CONF_ssh_simple, TRUE);
473 while ((key = conf_get_str_nthstrkey(conf, CONF_portfwd, 0)) != NULL)
474 conf_del_str_str(conf, CONF_portfwd, key);
478 * Set up main and possibly fallback command depending on
479 * options specified by user.
480 * Attempt to start the SFTP subsystem as a first choice,
481 * falling back to the provided scp command if that fails.
483 conf_set_str(conf, CONF_remote_cmd2, "");
485 /* First choice is SFTP subsystem. */
486 main_cmd_is_sftp = 1;
487 conf_set_str(conf, CONF_remote_cmd, "sftp");
488 conf_set_int(conf, CONF_ssh_subsys, TRUE);
490 /* Fallback is to use the provided scp command. */
491 fallback_cmd_is_sftp = 0;
492 conf_set_str(conf, CONF_remote_cmd2, cmd);
493 conf_set_int(conf, CONF_ssh_subsys2, FALSE);
495 /* Since we're not going to try SCP, we may as well try
496 * harder to find an SFTP server, since in the current
497 * implementation we have a spare slot. */
498 fallback_cmd_is_sftp = 1;
499 /* see psftp.c for full explanation of this kludge */
500 conf_set_str(conf, CONF_remote_cmd2,
501 "test -x /usr/lib/sftp-server &&"
502 " exec /usr/lib/sftp-server\n"
503 "test -x /usr/local/lib/sftp-server &&"
504 " exec /usr/local/lib/sftp-server\n"
506 conf_set_int(conf, CONF_ssh_subsys2, FALSE);
509 /* Don't try SFTP at all; just try the scp command. */
510 main_cmd_is_sftp = 0;
511 conf_set_str(conf, CONF_remote_cmd, cmd);
512 conf_set_int(conf, CONF_ssh_subsys, FALSE);
514 conf_set_int(conf, CONF_nopty, TRUE);
518 logctx = log_init(NULL, conf);
519 console_provide_logctx(logctx);
521 platform_psftp_pre_conn_setup();
523 err = back->init(NULL, &backhandle, conf,
524 conf_get_str(conf, CONF_host),
525 conf_get_int(conf, CONF_port),
527 conf_get_int(conf, CONF_tcp_keepalives));
529 bump("ssh_init: %s", err);
530 back->provide_logctx(backhandle, logctx);
532 if (verbose && realhost != NULL && errs == 0)
533 tell_user(stderr, "Connected to %s", realhost);
538 * Update statistic information about current file.
540 static void print_stats(const char *name, uint64 size, uint64 done,
541 time_t start, time_t now)
552 elap = (unsigned long) difftime(now, start);
555 ratebs = (float) (uint64_to_double(done) / elap);
557 ratebs = (float) uint64_to_double(done);
560 eta = (unsigned long) (uint64_to_double(uint64_subtract(size, done)));
562 eta = (unsigned long)
563 ((uint64_to_double(uint64_subtract(size, done)) / ratebs));
566 etastr = dupprintf("%02ld:%02ld:%02ld",
567 eta / 3600, (eta % 3600) / 60, eta % 60);
569 donedbl = uint64_to_double(done);
570 sizedbl = uint64_to_double(size);
571 pct = (int) (100 * (donedbl * 1.0 / sizedbl));
575 /* divide by 1024 to provide kB */
576 uint64_decimal(uint64_shift_right(done, 10), donekb);
577 len = printf("\r%-25.25s | %s kB | %5.1f kB/s | ETA: %8s | %3d%%",
579 donekb, ratebs / 1024.0, etastr, pct);
580 if (len < prev_stats_len)
581 printf("%*s", prev_stats_len - len, "");
582 prev_stats_len = len;
584 if (uint64_compare(done, size) == 0)
594 * Find a colon in str and return a pointer to the colon.
595 * This is used to separate hostname from filename.
597 static char *colon(char *str)
599 /* We ignore a leading colon, since the hostname cannot be
600 empty. We also ignore a colon as second character because
601 of filenames like f:myfile.txt. */
602 if (str[0] == '\0' || str[0] == ':' ||
603 (str[0] != '[' && str[1] == ':'))
605 str += host_strcspn(str, ":/\\");
613 * Determine whether a string is entirely composed of dots.
615 static int is_dots(char *str)
617 return str[strspn(str, ".")] == '\0';
621 * Wait for a response from the other side.
622 * Return 0 if ok, -1 if error.
624 static int response(void)
626 char ch, resp, rbuf[2048];
629 if (ssh_scp_recv((unsigned char *) &resp, 1) <= 0)
630 bump("Lost connection");
640 case 2: /* fatal error */
642 if (ssh_scp_recv((unsigned char *) &ch, 1) <= 0)
643 bump("Protocol error: Lost connection");
645 } while (p < sizeof(rbuf) && ch != '\n');
648 tell_user(stderr, "%s", rbuf);
656 int sftp_recvdata(char *buf, int len)
658 return ssh_scp_recv((unsigned char *) buf, len);
660 int sftp_senddata(char *buf, int len)
662 back->send(backhandle, buf, len);
665 int sftp_sendbuffer(void)
667 return back->sendbuffer(backhandle);
670 /* ----------------------------------------------------------------------
671 * sftp-based replacement for the hacky `pscp -ls'.
673 static int sftp_ls_compare(const void *av, const void *bv)
675 const struct fxp_name *a = (const struct fxp_name *) av;
676 const struct fxp_name *b = (const struct fxp_name *) bv;
677 return strcmp(a->filename, b->filename);
679 void scp_sftp_listdir(const char *dirname)
681 struct fxp_handle *dirh;
682 struct fxp_names *names;
683 struct fxp_name *ournames;
684 struct sftp_packet *pktin;
685 struct sftp_request *req;
686 int nnames, namesize;
690 tell_user(stderr, "unable to initialise SFTP: %s", fxp_error());
695 printf("Listing directory %s\n", dirname);
697 req = fxp_opendir_send(dirname);
698 pktin = sftp_wait_for_reply(req);
699 dirh = fxp_opendir_recv(pktin, req);
702 tell_user(stderr, "Unable to open %s: %s\n", dirname, fxp_error());
705 nnames = namesize = 0;
710 req = fxp_readdir_send(dirh);
711 pktin = sftp_wait_for_reply(req);
712 names = fxp_readdir_recv(pktin, req);
715 if (fxp_error_type() == SSH_FX_EOF)
717 printf("Reading directory %s: %s\n", dirname, fxp_error());
720 if (names->nnames == 0) {
721 fxp_free_names(names);
725 if (nnames + names->nnames >= namesize) {
726 namesize += names->nnames + 128;
727 ournames = sresize(ournames, namesize, struct fxp_name);
730 for (i = 0; i < names->nnames; i++)
731 ournames[nnames++] = names->names[i];
732 names->nnames = 0; /* prevent free_names */
733 fxp_free_names(names);
735 req = fxp_close_send(dirh);
736 pktin = sftp_wait_for_reply(req);
737 fxp_close_recv(pktin, req);
740 * Now we have our filenames. Sort them by actual file
741 * name, and then output the longname parts.
744 qsort(ournames, nnames, sizeof(*ournames), sftp_ls_compare);
749 for (i = 0; i < nnames; i++)
750 printf("%s\n", ournames[i].longname);
756 /* ----------------------------------------------------------------------
757 * Helper routines that contain the actual SCP protocol elements,
758 * implemented both as SCP1 and SFTP.
761 static struct scp_sftp_dirstack {
762 struct scp_sftp_dirstack *next;
763 struct fxp_name *names;
764 int namepos, namelen;
767 int matched_something; /* wildcard match set was non-empty */
768 } *scp_sftp_dirstack_head;
769 static char *scp_sftp_remotepath, *scp_sftp_currentname;
770 static char *scp_sftp_wildcard;
771 static int scp_sftp_targetisdir, scp_sftp_donethistarget;
772 static int scp_sftp_preserve, scp_sftp_recursive;
773 static unsigned long scp_sftp_mtime, scp_sftp_atime;
774 static int scp_has_times;
775 static struct fxp_handle *scp_sftp_filehandle;
776 static struct fxp_xfer *scp_sftp_xfer;
777 static uint64 scp_sftp_fileoffset;
779 int scp_source_setup(const char *target, int shouldbedir)
783 * Find out whether the target filespec is in fact a
786 struct sftp_packet *pktin;
787 struct sftp_request *req;
788 struct fxp_attrs attrs;
792 tell_user(stderr, "unable to initialise SFTP: %s", fxp_error());
797 req = fxp_stat_send(target);
798 pktin = sftp_wait_for_reply(req);
799 ret = fxp_stat_recv(pktin, req, &attrs);
801 if (!ret || !(attrs.flags & SSH_FILEXFER_ATTR_PERMISSIONS))
802 scp_sftp_targetisdir = 0;
804 scp_sftp_targetisdir = (attrs.permissions & 0040000) != 0;
806 if (shouldbedir && !scp_sftp_targetisdir) {
807 bump("pscp: remote filespec %s: not a directory\n", target);
810 scp_sftp_remotepath = dupstr(target);
819 int scp_send_errmsg(char *str)
822 /* do nothing; we never need to send our errors to the server */
824 back->send(backhandle, "\001", 1);/* scp protocol error prefix */
825 back->send(backhandle, str, strlen(str));
827 return 0; /* can't fail */
830 int scp_send_filetimes(unsigned long mtime, unsigned long atime)
833 scp_sftp_mtime = mtime;
834 scp_sftp_atime = atime;
839 sprintf(buf, "T%lu 0 %lu 0\n", mtime, atime);
840 back->send(backhandle, buf, strlen(buf));
845 int scp_send_filename(const char *name, uint64 size, int permissions)
849 struct sftp_packet *pktin;
850 struct sftp_request *req;
851 struct fxp_attrs attrs;
853 if (scp_sftp_targetisdir) {
854 fullname = dupcat(scp_sftp_remotepath, "/", name, NULL);
856 fullname = dupstr(scp_sftp_remotepath);
860 PUT_PERMISSIONS(attrs, permissions);
862 req = fxp_open_send(fullname,
863 SSH_FXF_WRITE | SSH_FXF_CREAT | SSH_FXF_TRUNC,
865 pktin = sftp_wait_for_reply(req);
866 scp_sftp_filehandle = fxp_open_recv(pktin, req);
868 if (!scp_sftp_filehandle) {
869 tell_user(stderr, "pscp: unable to open %s: %s",
870 fullname, fxp_error());
875 scp_sftp_fileoffset = uint64_make(0, 0);
876 scp_sftp_xfer = xfer_upload_init(scp_sftp_filehandle,
877 scp_sftp_fileoffset);
883 uint64_decimal(size, sizestr);
886 sprintf(buf, "C%04o %s ", (int)(permissions & 07777), sizestr);
887 back->send(backhandle, buf, strlen(buf));
888 back->send(backhandle, name, strlen(name));
889 back->send(backhandle, "\n", 1);
894 int scp_send_filedata(char *data, int len)
898 struct sftp_packet *pktin;
900 if (!scp_sftp_filehandle) {
904 while (!xfer_upload_ready(scp_sftp_xfer)) {
906 ret = xfer_upload_gotpkt(scp_sftp_xfer, pktin);
908 tell_user(stderr, "error while writing: %s", fxp_error());
909 if (ret == INT_MIN) /* pktin not even freed */
916 xfer_upload_data(scp_sftp_xfer, data, len);
918 scp_sftp_fileoffset = uint64_add32(scp_sftp_fileoffset, len);
921 int bufsize = back->send(backhandle, data, len);
924 * If the network transfer is backing up - that is, the
925 * remote site is not accepting data as fast as we can
926 * produce it - then we must loop on network events until
927 * we have space in the buffer again.
929 while (bufsize > MAX_SCP_BUFSIZE) {
930 if (ssh_sftp_loop_iteration() < 0)
932 bufsize = back->sendbuffer(backhandle);
939 int scp_send_finish(void)
942 struct fxp_attrs attrs;
943 struct sftp_packet *pktin;
944 struct sftp_request *req;
947 while (!xfer_done(scp_sftp_xfer)) {
949 ret = xfer_upload_gotpkt(scp_sftp_xfer, pktin);
951 tell_user(stderr, "error while writing: %s", fxp_error());
952 if (ret == INT_MIN) /* pktin not even freed */
958 xfer_cleanup(scp_sftp_xfer);
960 if (!scp_sftp_filehandle) {
964 attrs.flags = SSH_FILEXFER_ATTR_ACMODTIME;
965 attrs.atime = scp_sftp_atime;
966 attrs.mtime = scp_sftp_mtime;
967 req = fxp_fsetstat_send(scp_sftp_filehandle, attrs);
968 pktin = sftp_wait_for_reply(req);
969 ret = fxp_fsetstat_recv(pktin, req);
971 tell_user(stderr, "unable to set file times: %s", fxp_error());
975 req = fxp_close_send(scp_sftp_filehandle);
976 pktin = sftp_wait_for_reply(req);
977 fxp_close_recv(pktin, req);
981 back->send(backhandle, "", 1);
986 char *scp_save_remotepath(void)
989 return scp_sftp_remotepath;
994 void scp_restore_remotepath(char *data)
997 scp_sftp_remotepath = data;
1000 int scp_send_dirname(const char *name, int modes)
1005 struct fxp_attrs attrs;
1006 struct sftp_packet *pktin;
1007 struct sftp_request *req;
1010 if (scp_sftp_targetisdir) {
1011 fullname = dupcat(scp_sftp_remotepath, "/", name, NULL);
1013 fullname = dupstr(scp_sftp_remotepath);
1017 * We don't worry about whether we managed to create the
1018 * directory, because if it exists already it's OK just to
1019 * use it. Instead, we will stat it afterwards, and if it
1020 * exists and is a directory we will assume we were either
1021 * successful or it didn't matter.
1023 req = fxp_mkdir_send(fullname);
1024 pktin = sftp_wait_for_reply(req);
1025 ret = fxp_mkdir_recv(pktin, req);
1030 err = "server reported no error";
1032 req = fxp_stat_send(fullname);
1033 pktin = sftp_wait_for_reply(req);
1034 ret = fxp_stat_recv(pktin, req, &attrs);
1036 if (!ret || !(attrs.flags & SSH_FILEXFER_ATTR_PERMISSIONS) ||
1037 !(attrs.permissions & 0040000)) {
1038 tell_user(stderr, "unable to create directory %s: %s",
1045 scp_sftp_remotepath = fullname;
1050 sprintf(buf, "D%04o 0 ", modes);
1051 back->send(backhandle, buf, strlen(buf));
1052 back->send(backhandle, name, strlen(name));
1053 back->send(backhandle, "\n", 1);
1058 int scp_send_enddir(void)
1061 sfree(scp_sftp_remotepath);
1064 back->send(backhandle, "E\n", 2);
1070 * Yes, I know; I have an scp_sink_setup _and_ an scp_sink_init.
1071 * That's bad. The difference is that scp_sink_setup is called once
1072 * right at the start, whereas scp_sink_init is called to
1073 * initialise every level of recursion in the protocol.
1075 int scp_sink_setup(const char *source, int preserve, int recursive)
1081 tell_user(stderr, "unable to initialise SFTP: %s", fxp_error());
1086 * It's possible that the source string we've been given
1087 * contains a wildcard. If so, we must split the directory
1088 * away from the wildcard itself (throwing an error if any
1089 * wildcardness comes before the final slash) and arrange
1090 * things so that a dirstack entry will be set up.
1092 newsource = snewn(1+strlen(source), char);
1093 if (!wc_unescape(newsource, source)) {
1094 /* Yes, here we go; it's a wildcard. Bah. */
1095 char *dupsource, *lastpart, *dirpart, *wildcard;
1099 dupsource = dupstr(source);
1100 lastpart = stripslashes(dupsource, 0);
1101 wildcard = dupstr(lastpart);
1103 if (*dupsource && dupsource[1]) {
1105 * The remains of dupsource are at least two
1106 * characters long, meaning the pathname wasn't
1107 * empty or just `/'. Hence, we remove the trailing
1110 lastpart[-1] = '\0';
1111 } else if (!*dupsource) {
1113 * The remains of dupsource are _empty_ - the whole
1114 * pathname was a wildcard. Hence we need to
1115 * replace it with ".".
1118 dupsource = dupstr(".");
1122 * Now we have separated our string into dupsource (the
1123 * directory part) and wildcard. Both of these will
1124 * need freeing at some point. Next step is to remove
1125 * wildcard escapes from the directory part, throwing
1126 * an error if it contains a real wildcard.
1128 dirpart = snewn(1+strlen(dupsource), char);
1129 if (!wc_unescape(dirpart, dupsource)) {
1130 tell_user(stderr, "%s: multiple-level wildcards unsupported",
1140 * Now we have dirpart (unescaped, ie a valid remote
1141 * path), and wildcard (a wildcard). This will be
1142 * sufficient to arrange a dirstack entry.
1144 scp_sftp_remotepath = dirpart;
1145 scp_sftp_wildcard = wildcard;
1148 scp_sftp_remotepath = newsource;
1149 scp_sftp_wildcard = NULL;
1151 scp_sftp_preserve = preserve;
1152 scp_sftp_recursive = recursive;
1153 scp_sftp_donethistarget = 0;
1154 scp_sftp_dirstack_head = NULL;
1159 int scp_sink_init(void)
1162 back->send(backhandle, "", 1);
1167 #define SCP_SINK_FILE 1
1168 #define SCP_SINK_DIR 2
1169 #define SCP_SINK_ENDDIR 3
1170 #define SCP_SINK_RETRY 4 /* not an action; just try again */
1171 struct scp_sink_action {
1172 int action; /* FILE, DIR, ENDDIR */
1173 char *buf; /* will need freeing after use */
1174 char *name; /* filename or dirname (not ENDDIR) */
1175 long permissions; /* access permissions (not ENDDIR) */
1176 uint64 size; /* file size (not ENDDIR) */
1177 int settime; /* 1 if atime and mtime are filled */
1178 unsigned long atime, mtime; /* access times for the file */
1181 int scp_get_sink_action(struct scp_sink_action *act)
1185 int must_free_fname;
1186 struct fxp_attrs attrs;
1187 struct sftp_packet *pktin;
1188 struct sftp_request *req;
1191 if (!scp_sftp_dirstack_head) {
1192 if (!scp_sftp_donethistarget) {
1194 * Simple case: we are only dealing with one file.
1196 fname = scp_sftp_remotepath;
1197 must_free_fname = 0;
1198 scp_sftp_donethistarget = 1;
1201 * Even simpler case: one file _which we've done_.
1202 * Return 1 (finished).
1208 * We're now in the middle of stepping through a list
1209 * of names returned from fxp_readdir(); so let's carry
1212 struct scp_sftp_dirstack *head = scp_sftp_dirstack_head;
1213 while (head->namepos < head->namelen &&
1214 (is_dots(head->names[head->namepos].filename) ||
1216 !wc_match(head->wildcard,
1217 head->names[head->namepos].filename))))
1218 head->namepos++; /* skip . and .. */
1219 if (head->namepos < head->namelen) {
1220 head->matched_something = 1;
1221 fname = dupcat(head->dirpath, "/",
1222 head->names[head->namepos++].filename,
1224 must_free_fname = 1;
1227 * We've come to the end of the list; pop it off
1228 * the stack and return an ENDDIR action (or RETRY
1229 * if this was a wildcard match).
1231 if (head->wildcard) {
1232 act->action = SCP_SINK_RETRY;
1233 if (!head->matched_something) {
1234 tell_user(stderr, "pscp: wildcard '%s' matched "
1235 "no files", head->wildcard);
1238 sfree(head->wildcard);
1241 act->action = SCP_SINK_ENDDIR;
1244 sfree(head->dirpath);
1246 scp_sftp_dirstack_head = head->next;
1254 * Now we have a filename. Stat it, and see if it's a file
1257 req = fxp_stat_send(fname);
1258 pktin = sftp_wait_for_reply(req);
1259 ret = fxp_stat_recv(pktin, req, &attrs);
1261 if (!ret || !(attrs.flags & SSH_FILEXFER_ATTR_PERMISSIONS)) {
1262 tell_user(stderr, "unable to identify %s: %s", fname,
1263 ret ? "file type not supplied" : fxp_error());
1264 if (must_free_fname) sfree(fname);
1269 if (attrs.permissions & 0040000) {
1270 struct scp_sftp_dirstack *newitem;
1271 struct fxp_handle *dirhandle;
1272 int nnames, namesize;
1273 struct fxp_name *ournames;
1274 struct fxp_names *names;
1277 * It's a directory. If we're not in recursive mode,
1278 * this merits a complaint (which is fatal if the name
1279 * was specified directly, but not if it was matched by
1282 * We skip this complaint completely if
1283 * scp_sftp_wildcard is set, because that's an
1284 * indication that we're not actually supposed to
1285 * _recursively_ transfer the dir, just scan it for
1286 * things matching the wildcard.
1288 if (!scp_sftp_recursive && !scp_sftp_wildcard) {
1289 tell_user(stderr, "pscp: %s: is a directory", fname);
1291 if (must_free_fname) sfree(fname);
1292 if (scp_sftp_dirstack_head) {
1293 act->action = SCP_SINK_RETRY;
1301 * Otherwise, the fun begins. We must fxp_opendir() the
1302 * directory, slurp the filenames into memory, return
1303 * SCP_SINK_DIR (unless this is a wildcard match), and
1304 * set targetisdir. The next time we're called, we will
1305 * run through the list of filenames one by one,
1306 * matching them against a wildcard if present.
1308 * If targetisdir is _already_ set (meaning we're
1309 * already in the middle of going through another such
1310 * list), we must push the other (target,namelist) pair
1313 req = fxp_opendir_send(fname);
1314 pktin = sftp_wait_for_reply(req);
1315 dirhandle = fxp_opendir_recv(pktin, req);
1318 tell_user(stderr, "pscp: unable to open directory %s: %s",
1319 fname, fxp_error());
1320 if (must_free_fname) sfree(fname);
1324 nnames = namesize = 0;
1329 req = fxp_readdir_send(dirhandle);
1330 pktin = sftp_wait_for_reply(req);
1331 names = fxp_readdir_recv(pktin, req);
1333 if (names == NULL) {
1334 if (fxp_error_type() == SSH_FX_EOF)
1336 tell_user(stderr, "pscp: reading directory %s: %s",
1337 fname, fxp_error());
1339 req = fxp_close_send(dirhandle);
1340 pktin = sftp_wait_for_reply(req);
1341 fxp_close_recv(pktin, req);
1343 if (must_free_fname) sfree(fname);
1348 if (names->nnames == 0) {
1349 fxp_free_names(names);
1352 if (nnames + names->nnames >= namesize) {
1353 namesize += names->nnames + 128;
1354 ournames = sresize(ournames, namesize, struct fxp_name);
1356 for (i = 0; i < names->nnames; i++) {
1357 if (!strcmp(names->names[i].filename, ".") ||
1358 !strcmp(names->names[i].filename, "..")) {
1360 * . and .. are normal consequences of
1361 * reading a directory, and aren't worth
1362 * complaining about.
1364 } else if (!vet_filename(names->names[i].filename)) {
1365 tell_user(stderr, "ignoring potentially dangerous server-"
1366 "supplied filename '%s'",
1367 names->names[i].filename);
1369 ournames[nnames++] = names->names[i];
1371 names->nnames = 0; /* prevent free_names */
1372 fxp_free_names(names);
1374 req = fxp_close_send(dirhandle);
1375 pktin = sftp_wait_for_reply(req);
1376 fxp_close_recv(pktin, req);
1378 newitem = snew(struct scp_sftp_dirstack);
1379 newitem->next = scp_sftp_dirstack_head;
1380 newitem->names = ournames;
1381 newitem->namepos = 0;
1382 newitem->namelen = nnames;
1383 if (must_free_fname)
1384 newitem->dirpath = fname;
1386 newitem->dirpath = dupstr(fname);
1387 if (scp_sftp_wildcard) {
1388 newitem->wildcard = scp_sftp_wildcard;
1389 newitem->matched_something = 0;
1390 scp_sftp_wildcard = NULL;
1392 newitem->wildcard = NULL;
1394 scp_sftp_dirstack_head = newitem;
1396 if (newitem->wildcard) {
1397 act->action = SCP_SINK_RETRY;
1399 act->action = SCP_SINK_DIR;
1400 act->buf = dupstr(stripslashes(fname, 0));
1401 act->name = act->buf;
1402 act->size = uint64_make(0,0); /* duhh, it's a directory */
1403 act->permissions = 07777 & attrs.permissions;
1404 if (scp_sftp_preserve &&
1405 (attrs.flags & SSH_FILEXFER_ATTR_ACMODTIME)) {
1406 act->atime = attrs.atime;
1407 act->mtime = attrs.mtime;
1416 * It's a file. Return SCP_SINK_FILE.
1418 act->action = SCP_SINK_FILE;
1419 act->buf = dupstr(stripslashes(fname, 0));
1420 act->name = act->buf;
1421 if (attrs.flags & SSH_FILEXFER_ATTR_SIZE) {
1422 act->size = attrs.size;
1424 act->size = uint64_make(ULONG_MAX,ULONG_MAX); /* no idea */
1425 act->permissions = 07777 & attrs.permissions;
1426 if (scp_sftp_preserve &&
1427 (attrs.flags & SSH_FILEXFER_ATTR_ACMODTIME)) {
1428 act->atime = attrs.atime;
1429 act->mtime = attrs.mtime;
1433 if (must_free_fname)
1434 scp_sftp_currentname = fname;
1436 scp_sftp_currentname = dupstr(fname);
1451 if (ssh_scp_recv((unsigned char *) &ch, 1) <= 0)
1454 bump("Protocol error: Unexpected newline");
1458 if (ssh_scp_recv((unsigned char *) &ch, 1) <= 0)
1459 bump("Lost connection");
1462 act->buf = sresize(act->buf, bufsize, char);
1465 } while (ch != '\n');
1466 act->buf[i - 1] = '\0';
1468 case '\01': /* error */
1469 tell_user(stderr, "%s", act->buf);
1471 continue; /* go round again */
1472 case '\02': /* fatal error */
1473 bump("%s", act->buf);
1475 back->send(backhandle, "", 1);
1476 act->action = SCP_SINK_ENDDIR;
1479 if (sscanf(act->buf, "%ld %*d %ld %*d",
1480 &act->mtime, &act->atime) == 2) {
1482 back->send(backhandle, "", 1);
1483 continue; /* go round again */
1485 bump("Protocol error: Illegal time format");
1488 act->action = (action == 'C' ? SCP_SINK_FILE : SCP_SINK_DIR);
1491 bump("Protocol error: Expected control record");
1494 * We will go round this loop only once, unless we hit
1501 * If we get here, we must have seen SCP_SINK_FILE or
1507 if (sscanf(act->buf, "%lo %39s %n", &act->permissions,
1509 bump("Protocol error: Illegal file descriptor format");
1510 act->size = uint64_from_decimal(sizestr);
1511 act->name = act->buf + i;
1517 int scp_accept_filexfer(void)
1520 struct sftp_packet *pktin;
1521 struct sftp_request *req;
1523 req = fxp_open_send(scp_sftp_currentname, SSH_FXF_READ, NULL);
1524 pktin = sftp_wait_for_reply(req);
1525 scp_sftp_filehandle = fxp_open_recv(pktin, req);
1527 if (!scp_sftp_filehandle) {
1528 tell_user(stderr, "pscp: unable to open %s: %s",
1529 scp_sftp_currentname, fxp_error());
1533 scp_sftp_fileoffset = uint64_make(0, 0);
1534 scp_sftp_xfer = xfer_download_init(scp_sftp_filehandle,
1535 scp_sftp_fileoffset);
1536 sfree(scp_sftp_currentname);
1539 back->send(backhandle, "", 1);
1540 return 0; /* can't fail */
1544 int scp_recv_filedata(char *data, int len)
1547 struct sftp_packet *pktin;
1551 xfer_download_queue(scp_sftp_xfer);
1552 pktin = sftp_recv();
1553 ret = xfer_download_gotpkt(scp_sftp_xfer, pktin);
1555 tell_user(stderr, "pscp: error while reading: %s", fxp_error());
1556 if (ret == INT_MIN) /* pktin not even freed */
1562 if (xfer_download_data(scp_sftp_xfer, &vbuf, &actuallen)) {
1563 if (actuallen <= 0) {
1564 tell_user(stderr, "pscp: end of file while reading");
1570 * This assertion relies on the fact that the natural
1571 * block size used in the xfer manager is at most that
1572 * used in this module. I don't like crossing layers in
1573 * this way, but it'll do for now.
1575 assert(actuallen <= len);
1576 memcpy(data, vbuf, actuallen);
1581 scp_sftp_fileoffset = uint64_add32(scp_sftp_fileoffset, actuallen);
1585 return ssh_scp_recv((unsigned char *) data, len);
1589 int scp_finish_filerecv(void)
1592 struct sftp_packet *pktin;
1593 struct sftp_request *req;
1596 * Ensure that xfer_done() will work correctly, so we can
1597 * clean up any outstanding requests from the file
1600 xfer_set_error(scp_sftp_xfer);
1601 while (!xfer_done(scp_sftp_xfer)) {
1605 pktin = sftp_recv();
1606 ret = xfer_download_gotpkt(scp_sftp_xfer, pktin);
1608 tell_user(stderr, "pscp: error while reading: %s", fxp_error());
1609 if (ret == INT_MIN) /* pktin not even freed */
1614 if (xfer_download_data(scp_sftp_xfer, &vbuf, &len))
1617 xfer_cleanup(scp_sftp_xfer);
1619 req = fxp_close_send(scp_sftp_filehandle);
1620 pktin = sftp_wait_for_reply(req);
1621 fxp_close_recv(pktin, req);
1624 back->send(backhandle, "", 1);
1629 /* ----------------------------------------------------------------------
1630 * Send an error message to the other side and to the screen.
1631 * Increment error counter.
1633 static void run_err(const char *fmt, ...)
1639 str = dupvprintf(fmt, ap);
1640 str2 = dupcat("pscp: ", str, "\n", NULL);
1642 scp_send_errmsg(str2);
1643 tell_user(stderr, "%s", str2);
1649 * Execute the source part of the SCP protocol.
1651 static void source(const char *src)
1654 unsigned long mtime, atime;
1661 time_t stat_starttime, stat_lasttime;
1663 attr = file_type(src);
1664 if (attr == FILE_TYPE_NONEXISTENT ||
1665 attr == FILE_TYPE_WEIRD) {
1666 run_err("%s: %s file or directory", src,
1667 (attr == FILE_TYPE_WEIRD ? "Not a" : "No such"));
1671 if (attr == FILE_TYPE_DIRECTORY) {
1674 * Avoid . and .. directories.
1677 p = strrchr(src, '/');
1679 p = strrchr(src, '\\');
1684 if (!strcmp(p, ".") || !strcmp(p, ".."))
1685 /* skip . and .. */ ;
1689 run_err("%s: not a regular file", src);
1694 if ((last = strrchr(src, '/')) == NULL)
1698 if (strrchr(last, '\\') != NULL)
1699 last = strrchr(last, '\\') + 1;
1700 if (last == src && strchr(src, ':') != NULL)
1701 last = strchr(src, ':') + 1;
1703 f = open_existing_file(src, &size, &mtime, &atime, &permissions);
1705 run_err("%s: Cannot open file", src);
1709 if (scp_send_filetimes(mtime, atime)) {
1717 uint64_decimal(size, sizestr);
1718 tell_user(stderr, "Sending file %s, size=%s", last, sizestr);
1720 if (scp_send_filename(last, size, permissions)) {
1725 stat_bytes = uint64_make(0,0);
1726 stat_starttime = time(NULL);
1729 #define PSCP_SEND_BLOCK 4096
1730 for (i = uint64_make(0,0);
1731 uint64_compare(i,size) < 0;
1732 i = uint64_add32(i,PSCP_SEND_BLOCK)) {
1733 char transbuf[PSCP_SEND_BLOCK];
1734 int j, k = PSCP_SEND_BLOCK;
1736 if (uint64_compare(uint64_add32(i, k),size) > 0) /* i + k > size */
1737 k = (uint64_subtract(size, i)).lo; /* k = size - i; */
1738 if ((j = read_from_file(f, transbuf, k)) != k) {
1741 bump("%s: Read error", src);
1743 if (scp_send_filedata(transbuf, k))
1744 bump("%s: Network error occurred", src);
1747 stat_bytes = uint64_add32(stat_bytes, k);
1748 if (time(NULL) != stat_lasttime ||
1749 (uint64_compare(uint64_add32(i, k), size) == 0)) {
1750 stat_lasttime = time(NULL);
1751 print_stats(last, size, stat_bytes,
1752 stat_starttime, stat_lasttime);
1759 (void) scp_send_finish();
1763 * Recursively send the contents of a directory.
1765 static void rsource(const char *src)
1771 if ((last = strrchr(src, '/')) == NULL)
1775 if (strrchr(last, '\\') != NULL)
1776 last = strrchr(last, '\\') + 1;
1777 if (last == src && strchr(src, ':') != NULL)
1778 last = strchr(src, ':') + 1;
1780 /* maybe send filetime */
1782 save_target = scp_save_remotepath();
1785 tell_user(stderr, "Entering directory: %s", last);
1786 if (scp_send_dirname(last, 0755))
1789 dir = open_directory(src);
1792 while ((filename = read_filename(dir)) != NULL) {
1793 char *foundfile = dupcat(src, "/", filename, NULL);
1799 close_directory(dir);
1801 (void) scp_send_enddir();
1803 scp_restore_remotepath(save_target);
1807 * Execute the sink part of the SCP protocol.
1809 static void sink(const char *targ, const char *src)
1819 time_t stat_starttime, stat_lasttime;
1822 attr = file_type(targ);
1823 if (attr == FILE_TYPE_DIRECTORY)
1826 if (targetshouldbedirectory && !targisdir)
1827 bump("%s: Not a directory", targ);
1831 struct scp_sink_action act;
1832 if (scp_get_sink_action(&act))
1835 if (act.action == SCP_SINK_ENDDIR)
1838 if (act.action == SCP_SINK_RETRY)
1843 * Prevent the remote side from maliciously writing to
1844 * files outside the target area by sending a filename
1845 * containing `../'. In fact, it shouldn't be sending
1846 * filenames with any slashes or colons in at all; so
1847 * we'll find the last slash, backslash or colon in the
1848 * filename and use only the part after that. (And
1851 * In addition, we also ensure here that if we're
1852 * copying a single file and the target is a directory
1853 * (common usage: `pscp host:filename .') the remote
1854 * can't send us a _different_ file name. We can
1855 * distinguish this case because `src' will be non-NULL
1856 * and the last component of that will fail to match
1857 * (the last component of) the name sent.
1859 * Well, not always; if `src' is a wildcard, we do
1860 * expect to get back filenames that don't correspond
1861 * exactly to it. Ideally in this case, we would like
1862 * to ensure that the returned filename actually
1863 * matches the wildcard pattern - but one of SCP's
1864 * protocol infelicities is that wildcard matching is
1865 * done at the server end _by the server's rules_ and
1866 * so in general this is infeasible. Hence, we only
1867 * accept filenames that don't correspond to `src' if
1868 * unsafe mode is enabled or we are using SFTP (which
1869 * resolves remote wildcards on the client side and can
1872 char *striptarget, *stripsrc;
1874 striptarget = stripslashes(act.name, 1);
1875 if (striptarget != act.name) {
1876 tell_user(stderr, "warning: remote host sent a compound"
1877 " pathname '%s'", act.name);
1878 tell_user(stderr, " renaming local file to '%s'",
1883 * Also check to see if the target filename is '.' or
1884 * '..', or indeed '...' and so on because Windows
1885 * appears to interpret those like '..'.
1887 if (is_dots(striptarget)) {
1888 bump("security violation: remote host attempted to write to"
1889 " a '.' or '..' path!");
1893 stripsrc = stripslashes(src, 1);
1894 if (strcmp(striptarget, stripsrc) &&
1895 !using_sftp && !scp_unsafe_mode) {
1896 tell_user(stderr, "warning: remote host tried to write "
1897 "to a file called '%s'", striptarget);
1898 tell_user(stderr, " when we requested a file "
1899 "called '%s'.", stripsrc);
1900 tell_user(stderr, " If this is a wildcard, "
1901 "consider upgrading to SSH-2 or using");
1902 tell_user(stderr, " the '-unsafe' option. Renaming"
1903 " of this file has been disallowed.");
1904 /* Override the name the server provided with our own. */
1905 striptarget = stripsrc;
1909 if (targ[0] != '\0')
1910 destfname = dir_file_cat(targ, striptarget);
1912 destfname = dupstr(striptarget);
1915 * In this branch of the if, the target area is a
1916 * single file with an explicitly specified name in any
1917 * case, so there's no danger.
1919 destfname = dupstr(targ);
1921 attr = file_type(destfname);
1922 exists = (attr != FILE_TYPE_NONEXISTENT);
1924 if (act.action == SCP_SINK_DIR) {
1925 if (exists && attr != FILE_TYPE_DIRECTORY) {
1926 run_err("%s: Not a directory", destfname);
1931 if (!create_directory(destfname)) {
1932 run_err("%s: Cannot create directory", destfname);
1937 sink(destfname, NULL);
1938 /* can we set the timestamp for directories ? */
1943 f = open_new_file(destfname, act.permissions);
1945 run_err("%s: Cannot create file", destfname);
1950 if (scp_accept_filexfer()) {
1956 stat_bytes = uint64_make(0, 0);
1957 stat_starttime = time(NULL);
1959 stat_name = stripslashes(destfname, 1);
1961 received = uint64_make(0, 0);
1962 while (uint64_compare(received,act.size) < 0) {
1963 char transbuf[32768];
1966 blksize = uint64_make(0, 32768);
1967 if (uint64_compare(blksize,uint64_subtract(act.size,received)) > 0)
1968 blksize = uint64_subtract(act.size,received);
1969 read = scp_recv_filedata(transbuf, (int)blksize.lo);
1971 bump("Lost connection");
1973 received = uint64_add32(received, read);
1976 if (write_to_file(f, transbuf, read) != (int)read) {
1978 /* FIXME: in sftp we can actually abort the transfer */
1980 printf("\r%-25.25s | %50s\n",
1982 "Write error.. waiting for end of file");
1983 received = uint64_add32(received, read);
1987 stat_bytes = uint64_add32(stat_bytes,read);
1988 if (time(NULL) > stat_lasttime ||
1989 uint64_compare(uint64_add32(received, read), act.size) == 0) {
1990 stat_lasttime = time(NULL);
1991 print_stats(stat_name, act.size, stat_bytes,
1992 stat_starttime, stat_lasttime);
1995 received = uint64_add32(received, read);
1998 set_file_times(f, act.mtime, act.atime);
2003 run_err("%s: Write error", destfname);
2007 (void) scp_finish_filerecv();
2014 * We will copy local files to a remote server.
2016 static void toremote(int argc, char *argv[])
2018 char *src, *wtarg, *host, *user;
2025 wtarg = argv[argc - 1];
2027 /* Separate host from filename */
2029 wtarg = colon(wtarg);
2031 bump("wtarg == NULL in toremote()");
2033 /* Substitute "." for empty target */
2039 /* Separate host and username */
2041 host = strrchr(host, '@');
2052 if (colon(argv[0]) != NULL)
2053 bump("%s: Remote to remote not supported", argv[0]);
2055 wc_type = test_wildcard(argv[0], 1);
2056 if (wc_type == WCTYPE_NONEXISTENT)
2057 bump("%s: No such file or directory\n", argv[0]);
2058 else if (wc_type == WCTYPE_WILDCARD)
2059 targetshouldbedirectory = 1;
2062 cmd = dupprintf("scp%s%s%s%s -t %s",
2063 verbose ? " -v" : "",
2064 recursive ? " -r" : "",
2065 preserve ? " -p" : "",
2066 targetshouldbedirectory ? " -d" : "", targ);
2067 do_cmd(host, user, cmd);
2070 if (scp_source_setup(targ, targetshouldbedirectory))
2073 for (i = 0; i < argc - 1; i++) {
2075 if (colon(src) != NULL) {
2076 tell_user(stderr, "%s: Remote to remote not supported\n", src);
2081 wc_type = test_wildcard(src, 1);
2082 if (wc_type == WCTYPE_NONEXISTENT) {
2083 run_err("%s: No such file or directory", src);
2085 } else if (wc_type == WCTYPE_FILENAME) {
2089 WildcardMatcher *wc;
2092 wc = begin_wildcard_matching(src);
2094 run_err("%s: No such file or directory", src);
2098 while ((filename = wildcard_get_filename(wc)) != NULL) {
2103 finish_wildcard_matching(wc);
2109 * We will copy files from a remote server to the local machine.
2111 static void tolocal(int argc, char *argv[])
2113 char *wsrc, *host, *user;
2114 const char *src, *targ;
2120 bump("More than one remote source not supported");
2125 /* Separate host from filename */
2129 bump("Local to local copy not supported");
2131 /* Substitute "." for empty filename */
2137 /* Separate username and hostname */
2139 host = strrchr(host, '@');
2149 cmd = dupprintf("scp%s%s%s%s -f %s",
2150 verbose ? " -v" : "",
2151 recursive ? " -r" : "",
2152 preserve ? " -p" : "",
2153 targetshouldbedirectory ? " -d" : "", src);
2154 do_cmd(host, user, cmd);
2157 if (scp_sink_setup(src, preserve, recursive))
2164 * We will issue a list command to get a remote directory.
2166 static void get_dir_list(int argc, char *argv[])
2168 char *wsrc, *host, *user;
2176 /* Separate host from filename */
2180 bump("Local file listing not supported");
2182 /* Substitute "." for empty filename */
2188 /* Separate username and hostname */
2190 host = strrchr(host, '@');
2200 cmd = snewn(4 * strlen(src) + 100, char);
2201 strcpy(cmd, "ls -la '");
2202 p = cmd + strlen(cmd);
2203 for (q = src; *q; q++) {
2216 do_cmd(host, user, cmd);
2220 scp_sftp_listdir(src);
2222 while (ssh_scp_recv((unsigned char *) &c, 1) > 0)
2223 tell_char(stdout, c);
2228 * Short description of parameters.
2230 static void usage(void)
2232 printf("PuTTY Secure Copy client\n");
2233 printf("%s\n", ver);
2234 printf("Usage: pscp [options] [user@]host:source target\n");
2236 (" pscp [options] source [source...] [user@]host:target\n");
2237 printf(" pscp [options] -ls [user@]host:filespec\n");
2238 printf("Options:\n");
2239 printf(" -V print version information and exit\n");
2240 printf(" -pgpfp print PGP key fingerprints and exit\n");
2241 printf(" -p preserve file attributes\n");
2242 printf(" -q quiet, don't show statistics\n");
2243 printf(" -r copy directories recursively\n");
2244 printf(" -v show verbose messages\n");
2245 printf(" -load sessname Load settings from saved session\n");
2246 printf(" -P port connect to specified port\n");
2247 printf(" -l user connect with specified username\n");
2248 printf(" -pw passw login with specified password\n");
2249 printf(" -1 -2 force use of particular SSH protocol version\n");
2250 printf(" -4 -6 force use of IPv4 or IPv6\n");
2251 printf(" -C enable compression\n");
2252 printf(" -i key private key file for user authentication\n");
2253 printf(" -noagent disable use of Pageant\n");
2254 printf(" -agent enable use of Pageant\n");
2255 printf(" -hostkey aa:bb:cc:...\n");
2256 printf(" manually specify a host key (may be repeated)\n");
2257 printf(" -batch disable all interactive prompts\n");
2258 printf(" -proxycmd command\n");
2259 printf(" use 'command' as local proxy\n");
2260 printf(" -unsafe allow server-side wildcards (DANGEROUS)\n");
2261 printf(" -sftp force use of SFTP protocol\n");
2262 printf(" -scp force use of SCP protocol\n");
2263 printf(" -sshlog file\n");
2264 printf(" -sshrawlog file\n");
2265 printf(" log protocol details to a file\n");
2268 * -gui is an internal option, used by GUI front ends to get
2269 * pscp to pass progress reports back to them. It's not an
2270 * ordinary user-accessible option, so it shouldn't be part of
2271 * the command-line help. The only people who need to know
2272 * about it are programmers, and they can read the source.
2275 (" -gui hWnd GUI mode with the windows handle for receiving messages\n");
2282 char *buildinfo_text = buildinfo("\n");
2283 printf("pscp: %s\n%s\n", ver, buildinfo_text);
2284 sfree(buildinfo_text);
2288 void cmdline_error(const char *p, ...)
2291 fprintf(stderr, "pscp: ");
2293 vfprintf(stderr, p, ap);
2295 fprintf(stderr, "\n try typing just \"pscp\" for help\n");
2299 const int share_can_be_downstream = TRUE;
2300 const int share_can_be_upstream = FALSE;
2303 * Main program. (Called `psftp_main' because it gets called from
2304 * *sftp.c; bit silly, I know, but it had to be called _something_.)
2306 int psftp_main(int argc, char *argv[])
2310 default_protocol = PROT_TELNET;
2313 #ifdef FLAG_SYNCAGENT
2317 cmdline_tooltype = TOOLTYPE_FILETRANSFER;
2320 /* Load Default Settings before doing anything else. */
2322 do_defaults(NULL, conf);
2323 loaded_session = FALSE;
2325 for (i = 1; i < argc; i++) {
2327 if (argv[i][0] != '-')
2329 ret = cmdline_process_param(argv[i], i+1<argc?argv[i+1]:NULL, 1, conf);
2331 cmdline_error("option \"%s\" requires an argument", argv[i]);
2332 } else if (ret == 2) {
2333 i++; /* skip next argument */
2334 } else if (ret == 1) {
2335 /* We have our own verbosity in addition to `flags'. */
2336 if (flags & FLAG_VERBOSE)
2338 } else if (strcmp(argv[i], "-pgpfp") == 0) {
2341 } else if (strcmp(argv[i], "-r") == 0) {
2343 } else if (strcmp(argv[i], "-p") == 0) {
2345 } else if (strcmp(argv[i], "-q") == 0) {
2347 } else if (strcmp(argv[i], "-h") == 0 ||
2348 strcmp(argv[i], "-?") == 0 ||
2349 strcmp(argv[i], "--help") == 0) {
2351 } else if (strcmp(argv[i], "-V") == 0 ||
2352 strcmp(argv[i], "--version") == 0) {
2354 } else if (strcmp(argv[i], "-ls") == 0) {
2356 } else if (strcmp(argv[i], "-batch") == 0) {
2357 console_batch_mode = 1;
2358 } else if (strcmp(argv[i], "-unsafe") == 0) {
2359 scp_unsafe_mode = 1;
2360 } else if (strcmp(argv[i], "-sftp") == 0) {
2361 try_scp = 0; try_sftp = 1;
2362 } else if (strcmp(argv[i], "-scp") == 0) {
2363 try_scp = 1; try_sftp = 0;
2364 } else if (strcmp(argv[i], "--") == 0) {
2368 cmdline_error("unknown option \"%s\"", argv[i]);
2378 get_dir_list(argc, argv);
2385 targetshouldbedirectory = 1;
2387 if (colon(argv[argc - 1]) != NULL)
2388 toremote(argc, argv);
2390 tolocal(argc, argv);
2393 if (back != NULL && back->connected(backhandle)) {
2395 back->special(backhandle, TS_EOF);
2397 ssh_scp_recv((unsigned char *) &ch, 1);
2402 console_provide_logctx(NULL);
2403 back->free(backhandle);
2407 return (errs == 0 ? 0 : 1);