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
;
50 static void source(char *src
);
51 static void rsource(char *src
);
52 static void sink(char *targ
, char *src
);
54 const char *const appname
= "PSCP";
57 * The maximum amount of queued data we accept before we stop and
58 * wait for the server to process some.
60 #define MAX_SCP_BUFSIZE 16384
62 void ldisc_send(void *handle
, char *buf
, int len
, int interactive
)
65 * This is only here because of the calls to ldisc_send(NULL,
66 * 0) in ssh.c. Nothing in PSCP actually needs to use the ldisc
67 * as an ldisc. So if we get called with any real data, I want
73 static void tell_char(FILE * stream
, char c
)
78 static void tell_str(FILE * stream
, char *str
)
82 for (i
= 0; i
< strlen(str
); ++i
)
83 tell_char(stream
, str
[i
]);
86 static void tell_user(FILE * stream
, char *fmt
, ...)
91 str
= dupvprintf(fmt
, ap
);
93 str2
= dupcat(str
, "\n", NULL
);
95 tell_str(stream
, str2
);
100 * Print an error message and perform a fatal exit.
102 void fatalbox(char *fmt
, ...)
107 str
= dupvprintf(fmt
, ap
);
108 str2
= dupcat("Fatal: ", str
, "\n", NULL
);
111 tell_str(stderr
, str2
);
117 void modalfatalbox(char *fmt
, ...)
122 str
= dupvprintf(fmt
, ap
);
123 str2
= dupcat("Fatal: ", str
, "\n", NULL
);
126 tell_str(stderr
, str2
);
132 void connection_fatal(void *frontend
, char *fmt
, ...)
137 str
= dupvprintf(fmt
, ap
);
138 str2
= dupcat("Fatal: ", str
, "\n", NULL
);
141 tell_str(stderr
, str2
);
149 * In pscp, all agent requests should be synchronous, so this is a
152 void agent_schedule_callback(void (*callback
)(void *, void *, int),
153 void *callback_ctx
, void *data
, int len
)
155 assert(!"We shouldn't be here");
159 * Receive a block of data from the SSH link. Block until all data
162 * To do this, we repeatedly call the SSH protocol module, with our
163 * own trap in from_backend() to catch the data that comes back. We
164 * do this until we have enough data.
167 static unsigned char *outptr
; /* where to put the data */
168 static unsigned outlen
; /* how much data required */
169 static unsigned char *pending
= NULL
; /* any spare data */
170 static unsigned pendlen
= 0, pendsize
= 0; /* length and phys. size of buffer */
171 int from_backend(void *frontend
, int is_stderr
, const char *data
, int datalen
)
173 unsigned char *p
= (unsigned char *) data
;
174 unsigned len
= (unsigned) datalen
;
177 * stderr data is just spouted to local stderr and otherwise
182 if (fwrite(data
, 1, len
, stderr
) < len
)
187 if ((outlen
> 0) && (len
> 0)) {
188 unsigned used
= outlen
;
191 memcpy(outptr
, p
, used
);
199 if (pendsize
< pendlen
+ len
) {
200 pendsize
= pendlen
+ len
+ 4096;
201 pending
= sresize(pending
, pendsize
, unsigned char);
203 memcpy(pending
+ pendlen
, p
, len
);
209 int from_backend_untrusted(void *frontend_handle
, const char *data
, int len
)
212 * No "untrusted" output should get here (the way the code is
213 * currently, it's all diverted by FLAG_STDERR).
215 assert(!"Unexpected call to from_backend_untrusted()");
216 return 0; /* not reached */
218 int from_backend_eof(void *frontend
)
221 * We expect to be the party deciding when to close the
222 * connection, so if we see EOF before we sent it ourselves, we
226 connection_fatal(frontend
,
227 "Received unexpected end-of-file from server");
231 static int ssh_scp_recv(unsigned char *buf
, int len
)
237 * See if the pending-input block contains some of what we
241 unsigned pendused
= pendlen
;
242 if (pendused
> outlen
)
244 memcpy(outptr
, pending
, pendused
);
245 memmove(pending
, pending
+ pendused
, pendlen
- pendused
);
259 if (back
->exitcode(backhandle
) >= 0 || ssh_sftp_loop_iteration() < 0)
267 * Loop through the ssh connection and authentication process.
269 static void ssh_scp_init(void)
271 while (!back
->sendok(backhandle
)) {
272 if (back
->exitcode(backhandle
) >= 0) {
276 if (ssh_sftp_loop_iteration() < 0) {
282 /* Work out which backend we ended up using. */
283 if (!ssh_fallback_cmd(backhandle
))
284 using_sftp
= main_cmd_is_sftp
;
286 using_sftp
= fallback_cmd_is_sftp
;
290 tell_user(stderr
, "Using SFTP");
292 tell_user(stderr
, "Using SCP1");
297 * Print an error message and exit after closing the SSH link.
299 static void bump(char *fmt
, ...)
304 str
= dupvprintf(fmt
, ap
);
306 str2
= dupcat(str
, "\n", NULL
);
308 tell_str(stderr
, str2
);
312 if (back
!= NULL
&& back
->connected(backhandle
)) {
314 back
->special(backhandle
, TS_EOF
);
316 ssh_scp_recv((unsigned char *) &ch
, 1);
323 * Open an SSH connection to user@host and execute cmd.
325 static void do_cmd(char *host
, char *user
, char *cmd
)
331 if (host
== NULL
|| host
[0] == '\0')
332 bump("Empty host name");
335 * Remove fiddly bits of address: remove a colon suffix, and
336 * the square brackets around an IPv6 literal address.
338 if (host
[0] == '[') {
340 host
[strcspn(host
, "]")] = '\0';
342 host
[strcspn(host
, ":")] = '\0';
346 * If we haven't loaded session details already (e.g., from -load),
347 * try looking for a session called "host".
349 if (!loaded_session
) {
350 /* Try to load settings for `host' into a temporary config */
351 Conf
*conf2
= conf_new();
352 conf_set_str(conf2
, CONF_host
, "");
353 do_defaults(host
, conf2
);
354 if (conf_get_str(conf2
, CONF_host
)[0] != '\0') {
355 /* Settings present and include hostname */
356 /* Re-load data into the real config. */
357 do_defaults(host
, conf
);
359 /* Session doesn't exist or mention a hostname. */
360 /* Use `host' as a bare hostname. */
361 conf_set_str(conf
, CONF_host
, host
);
364 /* Patch in hostname `host' to session details. */
365 conf_set_str(conf
, CONF_host
, host
);
369 * Force use of SSH. (If they got the protocol wrong we assume the
370 * port is useless too.)
372 if (conf_get_int(conf
, CONF_protocol
) != PROT_SSH
) {
373 conf_set_int(conf
, CONF_protocol
, PROT_SSH
);
374 conf_set_int(conf
, CONF_port
, 22);
378 * Enact command-line overrides.
380 cmdline_run_saved(conf
);
383 * Muck about with the hostname in various ways.
386 char *hostbuf
= dupstr(conf_get_str(conf
, CONF_host
));
387 char *host
= hostbuf
;
391 * Trim leading whitespace.
393 host
+= strspn(host
, " \t");
396 * See if host is of the form user@host, and separate out
397 * the username if so.
399 if (host
[0] != '\0') {
400 char *atsign
= strrchr(host
, '@');
403 conf_set_str(conf
, CONF_username
, host
);
409 * Remove any remaining whitespace.
414 if (*q
!= ' ' && *q
!= '\t')
420 conf_set_str(conf
, CONF_host
, hostbuf
);
425 if (user
!= NULL
&& user
[0] != '\0') {
426 conf_set_str(conf
, CONF_username
, user
);
427 } else if (conf_get_str(conf
, CONF_username
)[0] == '\0') {
428 user
= get_username();
430 bump("Empty user name");
433 tell_user(stderr
, "Guessing user name: %s", user
);
434 conf_set_str(conf
, CONF_username
, user
);
440 * Disable scary things which shouldn't be enabled for simple
441 * things like SCP and SFTP: agent forwarding, port forwarding,
444 conf_set_int(conf
, CONF_x11_forward
, 0);
445 conf_set_int(conf
, CONF_agentfwd
, 0);
446 conf_set_int(conf
, CONF_ssh_simple
, TRUE
);
449 while ((key
= conf_get_str_nthstrkey(conf
, CONF_portfwd
, 0)) != NULL
)
450 conf_del_str_str(conf
, CONF_portfwd
, key
);
454 * Set up main and possibly fallback command depending on
455 * options specified by user.
456 * Attempt to start the SFTP subsystem as a first choice,
457 * falling back to the provided scp command if that fails.
459 conf_set_str(conf
, CONF_remote_cmd2
, "");
461 /* First choice is SFTP subsystem. */
462 main_cmd_is_sftp
= 1;
463 conf_set_str(conf
, CONF_remote_cmd
, "sftp");
464 conf_set_int(conf
, CONF_ssh_subsys
, TRUE
);
466 /* Fallback is to use the provided scp command. */
467 fallback_cmd_is_sftp
= 0;
468 conf_set_str(conf
, CONF_remote_cmd2
, cmd
);
469 conf_set_int(conf
, CONF_ssh_subsys2
, FALSE
);
471 /* Since we're not going to try SCP, we may as well try
472 * harder to find an SFTP server, since in the current
473 * implementation we have a spare slot. */
474 fallback_cmd_is_sftp
= 1;
475 /* see psftp.c for full explanation of this kludge */
476 conf_set_str(conf
, CONF_remote_cmd2
,
477 "test -x /usr/lib/sftp-server &&"
478 " exec /usr/lib/sftp-server\n"
479 "test -x /usr/local/lib/sftp-server &&"
480 " exec /usr/local/lib/sftp-server\n"
482 conf_set_int(conf
, CONF_ssh_subsys2
, FALSE
);
485 /* Don't try SFTP at all; just try the scp command. */
486 main_cmd_is_sftp
= 0;
487 conf_set_str(conf
, CONF_remote_cmd
, cmd
);
488 conf_set_int(conf
, CONF_ssh_subsys
, FALSE
);
490 conf_set_int(conf
, CONF_nopty
, TRUE
);
494 err
= back
->init(NULL
, &backhandle
, conf
,
495 conf_get_str(conf
, CONF_host
),
496 conf_get_int(conf
, CONF_port
),
498 conf_get_int(conf
, CONF_tcp_keepalives
));
500 bump("ssh_init: %s", err
);
501 logctx
= log_init(NULL
, conf
);
502 back
->provide_logctx(backhandle
, logctx
);
503 console_provide_logctx(logctx
);
505 if (verbose
&& realhost
!= NULL
&& errs
== 0)
506 tell_user(stderr
, "Connected to %s\n", realhost
);
511 * Update statistic information about current file.
513 static void print_stats(char *name
, uint64 size
, uint64 done
,
514 time_t start
, time_t now
)
525 elap
= (unsigned long) difftime(now
, start
);
528 ratebs
= (float) (uint64_to_double(done
) / elap
);
530 ratebs
= (float) uint64_to_double(done
);
533 eta
= (unsigned long) (uint64_to_double(uint64_subtract(size
, done
)));
535 eta
= (unsigned long)
536 ((uint64_to_double(uint64_subtract(size
, done
)) / ratebs
));
539 etastr
= dupprintf("%02ld:%02ld:%02ld",
540 eta
/ 3600, (eta
% 3600) / 60, eta
% 60);
542 donedbl
= uint64_to_double(done
);
543 sizedbl
= uint64_to_double(size
);
544 pct
= (int) (100 * (donedbl
* 1.0 / sizedbl
));
548 /* divide by 1024 to provide kB */
549 uint64_decimal(uint64_shift_right(done
, 10), donekb
);
550 len
= printf("\r%-25.25s | %s kB | %5.1f kB/s | ETA: %8s | %3d%%",
552 donekb
, ratebs
/ 1024.0, etastr
, pct
);
553 if (len
< prev_stats_len
)
554 printf("%*s", prev_stats_len
- len
, "");
555 prev_stats_len
= len
;
557 if (uint64_compare(done
, size
) == 0)
567 * Find a colon in str and return a pointer to the colon.
568 * This is used to separate hostname from filename.
570 static char *colon(char *str
)
572 /* We ignore a leading colon, since the hostname cannot be
573 empty. We also ignore a colon as second character because
574 of filenames like f:myfile.txt. */
575 if (str
[0] == '\0' || str
[0] == ':' ||
576 (str
[0] != '[' && str
[1] == ':'))
578 while (*str
!= '\0' && *str
!= ':' && *str
!= '/' && *str
!= '\\') {
580 /* Skip over IPv6 literal addresses
581 * (eg: 'jeroen@[2001:db8::1]:myfile.txt') */
582 char *ipv6_end
= strchr(str
, ']');
596 * Return a pointer to the portion of str that comes after the last
597 * slash (or backslash or colon, if `local' is TRUE).
599 static char *stripslashes(char *str
, int local
)
604 p
= strchr(str
, ':');
608 p
= strrchr(str
, '/');
612 p
= strrchr(str
, '\\');
620 * Determine whether a string is entirely composed of dots.
622 static int is_dots(char *str
)
624 return str
[strspn(str
, ".")] == '\0';
628 * Wait for a response from the other side.
629 * Return 0 if ok, -1 if error.
631 static int response(void)
633 char ch
, resp
, rbuf
[2048];
636 if (ssh_scp_recv((unsigned char *) &resp
, 1) <= 0)
637 bump("Lost connection");
647 case 2: /* fatal error */
649 if (ssh_scp_recv((unsigned char *) &ch
, 1) <= 0)
650 bump("Protocol error: Lost connection");
652 } while (p
< sizeof(rbuf
) && ch
!= '\n');
655 tell_user(stderr
, "%s\n", rbuf
);
663 int sftp_recvdata(char *buf
, int len
)
665 return ssh_scp_recv((unsigned char *) buf
, len
);
667 int sftp_senddata(char *buf
, int len
)
669 back
->send(backhandle
, buf
, len
);
673 /* ----------------------------------------------------------------------
674 * sftp-based replacement for the hacky `pscp -ls'.
676 static int sftp_ls_compare(const void *av
, const void *bv
)
678 const struct fxp_name
*a
= (const struct fxp_name
*) av
;
679 const struct fxp_name
*b
= (const struct fxp_name
*) bv
;
680 return strcmp(a
->filename
, b
->filename
);
682 void scp_sftp_listdir(char *dirname
)
684 struct fxp_handle
*dirh
;
685 struct fxp_names
*names
;
686 struct fxp_name
*ournames
;
687 struct sftp_packet
*pktin
;
688 struct sftp_request
*req
, *rreq
;
689 int nnames
, namesize
;
693 tell_user(stderr
, "unable to initialise SFTP: %s", fxp_error());
698 printf("Listing directory %s\n", dirname
);
700 sftp_register(req
= fxp_opendir_send(dirname
));
701 rreq
= sftp_find_request(pktin
= sftp_recv());
703 dirh
= fxp_opendir_recv(pktin
, rreq
);
706 printf("Unable to open %s: %s\n", dirname
, fxp_error());
708 nnames
= namesize
= 0;
713 sftp_register(req
= fxp_readdir_send(dirh
));
714 rreq
= sftp_find_request(pktin
= sftp_recv());
716 names
= fxp_readdir_recv(pktin
, rreq
);
719 if (fxp_error_type() == SSH_FX_EOF
)
721 printf("Reading directory %s: %s\n", dirname
, fxp_error());
724 if (names
->nnames
== 0) {
725 fxp_free_names(names
);
729 if (nnames
+ names
->nnames
>= namesize
) {
730 namesize
+= names
->nnames
+ 128;
731 ournames
= sresize(ournames
, namesize
, struct fxp_name
);
734 for (i
= 0; i
< names
->nnames
; i
++)
735 ournames
[nnames
++] = names
->names
[i
];
736 names
->nnames
= 0; /* prevent free_names */
737 fxp_free_names(names
);
739 sftp_register(req
= fxp_close_send(dirh
));
740 rreq
= sftp_find_request(pktin
= sftp_recv());
742 fxp_close_recv(pktin
, rreq
);
745 * Now we have our filenames. Sort them by actual file
746 * name, and then output the longname parts.
748 qsort(ournames
, nnames
, sizeof(*ournames
), sftp_ls_compare
);
753 for (i
= 0; i
< nnames
; i
++)
754 printf("%s\n", ournames
[i
].longname
);
758 /* ----------------------------------------------------------------------
759 * Helper routines that contain the actual SCP protocol elements,
760 * implemented both as SCP1 and SFTP.
763 static struct scp_sftp_dirstack
{
764 struct scp_sftp_dirstack
*next
;
765 struct fxp_name
*names
;
766 int namepos
, namelen
;
769 int matched_something
; /* wildcard match set was non-empty */
770 } *scp_sftp_dirstack_head
;
771 static char *scp_sftp_remotepath
, *scp_sftp_currentname
;
772 static char *scp_sftp_wildcard
;
773 static int scp_sftp_targetisdir
, scp_sftp_donethistarget
;
774 static int scp_sftp_preserve
, scp_sftp_recursive
;
775 static unsigned long scp_sftp_mtime
, scp_sftp_atime
;
776 static int scp_has_times
;
777 static struct fxp_handle
*scp_sftp_filehandle
;
778 static struct fxp_xfer
*scp_sftp_xfer
;
779 static uint64 scp_sftp_fileoffset
;
781 int scp_source_setup(char *target
, int shouldbedir
)
785 * Find out whether the target filespec is in fact a
788 struct sftp_packet
*pktin
;
789 struct sftp_request
*req
, *rreq
;
790 struct fxp_attrs attrs
;
794 tell_user(stderr
, "unable to initialise SFTP: %s", fxp_error());
799 sftp_register(req
= fxp_stat_send(target
));
800 rreq
= sftp_find_request(pktin
= sftp_recv());
802 ret
= fxp_stat_recv(pktin
, rreq
, &attrs
);
804 if (!ret
|| !(attrs
.flags
& SSH_FILEXFER_ATTR_PERMISSIONS
))
805 scp_sftp_targetisdir
= 0;
807 scp_sftp_targetisdir
= (attrs
.permissions
& 0040000) != 0;
809 if (shouldbedir
&& !scp_sftp_targetisdir
) {
810 bump("pscp: remote filespec %s: not a directory\n", target
);
813 scp_sftp_remotepath
= dupstr(target
);
822 int scp_send_errmsg(char *str
)
825 /* do nothing; we never need to send our errors to the server */
827 back
->send(backhandle
, "\001", 1);/* scp protocol error prefix */
828 back
->send(backhandle
, str
, strlen(str
));
830 return 0; /* can't fail */
833 int scp_send_filetimes(unsigned long mtime
, unsigned long atime
)
836 scp_sftp_mtime
= mtime
;
837 scp_sftp_atime
= atime
;
842 sprintf(buf
, "T%lu 0 %lu 0\n", mtime
, atime
);
843 back
->send(backhandle
, buf
, strlen(buf
));
848 int scp_send_filename(char *name
, uint64 size
, int permissions
)
852 struct sftp_packet
*pktin
;
853 struct sftp_request
*req
, *rreq
;
854 struct fxp_attrs attrs
;
856 if (scp_sftp_targetisdir
) {
857 fullname
= dupcat(scp_sftp_remotepath
, "/", name
, NULL
);
859 fullname
= dupstr(scp_sftp_remotepath
);
863 PUT_PERMISSIONS(attrs
, permissions
);
865 sftp_register(req
= fxp_open_send(fullname
, SSH_FXF_WRITE
|
866 SSH_FXF_CREAT
| SSH_FXF_TRUNC
,
868 rreq
= sftp_find_request(pktin
= sftp_recv());
870 scp_sftp_filehandle
= fxp_open_recv(pktin
, rreq
);
872 if (!scp_sftp_filehandle
) {
873 tell_user(stderr
, "pscp: unable to open %s: %s",
874 fullname
, fxp_error());
878 scp_sftp_fileoffset
= uint64_make(0, 0);
879 scp_sftp_xfer
= xfer_upload_init(scp_sftp_filehandle
,
880 scp_sftp_fileoffset
);
886 uint64_decimal(size
, sizestr
);
889 sprintf(buf
, "C%04o %s ", (int)(permissions
& 07777), sizestr
);
890 back
->send(backhandle
, buf
, strlen(buf
));
891 back
->send(backhandle
, name
, strlen(name
));
892 back
->send(backhandle
, "\n", 1);
897 int scp_send_filedata(char *data
, int len
)
901 struct sftp_packet
*pktin
;
903 if (!scp_sftp_filehandle
) {
907 while (!xfer_upload_ready(scp_sftp_xfer
)) {
909 ret
= xfer_upload_gotpkt(scp_sftp_xfer
, pktin
);
911 tell_user(stderr
, "error while writing: %s\n", fxp_error());
917 xfer_upload_data(scp_sftp_xfer
, data
, len
);
919 scp_sftp_fileoffset
= uint64_add32(scp_sftp_fileoffset
, len
);
922 int bufsize
= back
->send(backhandle
, data
, len
);
925 * If the network transfer is backing up - that is, the
926 * remote site is not accepting data as fast as we can
927 * produce it - then we must loop on network events until
928 * we have space in the buffer again.
930 while (bufsize
> MAX_SCP_BUFSIZE
) {
931 if (ssh_sftp_loop_iteration() < 0)
933 bufsize
= back
->sendbuffer(backhandle
);
940 int scp_send_finish(void)
943 struct fxp_attrs attrs
;
944 struct sftp_packet
*pktin
;
945 struct sftp_request
*req
, *rreq
;
948 while (!xfer_done(scp_sftp_xfer
)) {
950 xfer_upload_gotpkt(scp_sftp_xfer
, pktin
);
952 xfer_cleanup(scp_sftp_xfer
);
954 if (!scp_sftp_filehandle
) {
958 attrs
.flags
= SSH_FILEXFER_ATTR_ACMODTIME
;
959 attrs
.atime
= scp_sftp_atime
;
960 attrs
.mtime
= scp_sftp_mtime
;
961 sftp_register(req
= fxp_fsetstat_send(scp_sftp_filehandle
, attrs
));
962 rreq
= sftp_find_request(pktin
= sftp_recv());
964 ret
= fxp_fsetstat_recv(pktin
, rreq
);
966 tell_user(stderr
, "unable to set file times: %s\n", fxp_error());
970 sftp_register(req
= fxp_close_send(scp_sftp_filehandle
));
971 rreq
= sftp_find_request(pktin
= sftp_recv());
973 fxp_close_recv(pktin
, rreq
);
977 back
->send(backhandle
, "", 1);
982 char *scp_save_remotepath(void)
985 return scp_sftp_remotepath
;
990 void scp_restore_remotepath(char *data
)
993 scp_sftp_remotepath
= data
;
996 int scp_send_dirname(char *name
, int modes
)
1001 struct fxp_attrs attrs
;
1002 struct sftp_packet
*pktin
;
1003 struct sftp_request
*req
, *rreq
;
1006 if (scp_sftp_targetisdir
) {
1007 fullname
= dupcat(scp_sftp_remotepath
, "/", name
, NULL
);
1009 fullname
= dupstr(scp_sftp_remotepath
);
1013 * We don't worry about whether we managed to create the
1014 * directory, because if it exists already it's OK just to
1015 * use it. Instead, we will stat it afterwards, and if it
1016 * exists and is a directory we will assume we were either
1017 * successful or it didn't matter.
1019 sftp_register(req
= fxp_mkdir_send(fullname
));
1020 rreq
= sftp_find_request(pktin
= sftp_recv());
1021 assert(rreq
== req
);
1022 ret
= fxp_mkdir_recv(pktin
, rreq
);
1027 err
= "server reported no error";
1029 sftp_register(req
= fxp_stat_send(fullname
));
1030 rreq
= sftp_find_request(pktin
= sftp_recv());
1031 assert(rreq
== req
);
1032 ret
= fxp_stat_recv(pktin
, rreq
, &attrs
);
1034 if (!ret
|| !(attrs
.flags
& SSH_FILEXFER_ATTR_PERMISSIONS
) ||
1035 !(attrs
.permissions
& 0040000)) {
1036 tell_user(stderr
, "unable to create directory %s: %s",
1042 scp_sftp_remotepath
= fullname
;
1047 sprintf(buf
, "D%04o 0 ", modes
);
1048 back
->send(backhandle
, buf
, strlen(buf
));
1049 back
->send(backhandle
, name
, strlen(name
));
1050 back
->send(backhandle
, "\n", 1);
1055 int scp_send_enddir(void)
1058 sfree(scp_sftp_remotepath
);
1061 back
->send(backhandle
, "E\n", 2);
1067 * Yes, I know; I have an scp_sink_setup _and_ an scp_sink_init.
1068 * That's bad. The difference is that scp_sink_setup is called once
1069 * right at the start, whereas scp_sink_init is called to
1070 * initialise every level of recursion in the protocol.
1072 int scp_sink_setup(char *source
, int preserve
, int recursive
)
1078 tell_user(stderr
, "unable to initialise SFTP: %s", fxp_error());
1083 * It's possible that the source string we've been given
1084 * contains a wildcard. If so, we must split the directory
1085 * away from the wildcard itself (throwing an error if any
1086 * wildcardness comes before the final slash) and arrange
1087 * things so that a dirstack entry will be set up.
1089 newsource
= snewn(1+strlen(source
), char);
1090 if (!wc_unescape(newsource
, source
)) {
1091 /* Yes, here we go; it's a wildcard. Bah. */
1092 char *dupsource
, *lastpart
, *dirpart
, *wildcard
;
1093 dupsource
= dupstr(source
);
1094 lastpart
= stripslashes(dupsource
, 0);
1095 wildcard
= dupstr(lastpart
);
1097 if (*dupsource
&& dupsource
[1]) {
1099 * The remains of dupsource are at least two
1100 * characters long, meaning the pathname wasn't
1101 * empty or just `/'. Hence, we remove the trailing
1104 lastpart
[-1] = '\0';
1105 } else if (!*dupsource
) {
1107 * The remains of dupsource are _empty_ - the whole
1108 * pathname was a wildcard. Hence we need to
1109 * replace it with ".".
1112 dupsource
= dupstr(".");
1116 * Now we have separated our string into dupsource (the
1117 * directory part) and wildcard. Both of these will
1118 * need freeing at some point. Next step is to remove
1119 * wildcard escapes from the directory part, throwing
1120 * an error if it contains a real wildcard.
1122 dirpart
= snewn(1+strlen(dupsource
), char);
1123 if (!wc_unescape(dirpart
, dupsource
)) {
1124 tell_user(stderr
, "%s: multiple-level wildcards unsupported",
1134 * Now we have dirpart (unescaped, ie a valid remote
1135 * path), and wildcard (a wildcard). This will be
1136 * sufficient to arrange a dirstack entry.
1138 scp_sftp_remotepath
= dirpart
;
1139 scp_sftp_wildcard
= wildcard
;
1142 scp_sftp_remotepath
= newsource
;
1143 scp_sftp_wildcard
= NULL
;
1145 scp_sftp_preserve
= preserve
;
1146 scp_sftp_recursive
= recursive
;
1147 scp_sftp_donethistarget
= 0;
1148 scp_sftp_dirstack_head
= NULL
;
1153 int scp_sink_init(void)
1156 back
->send(backhandle
, "", 1);
1161 #define SCP_SINK_FILE 1
1162 #define SCP_SINK_DIR 2
1163 #define SCP_SINK_ENDDIR 3
1164 #define SCP_SINK_RETRY 4 /* not an action; just try again */
1165 struct scp_sink_action
{
1166 int action
; /* FILE, DIR, ENDDIR */
1167 char *buf
; /* will need freeing after use */
1168 char *name
; /* filename or dirname (not ENDDIR) */
1169 long permissions
; /* access permissions (not ENDDIR) */
1170 uint64 size
; /* file size (not ENDDIR) */
1171 int settime
; /* 1 if atime and mtime are filled */
1172 unsigned long atime
, mtime
; /* access times for the file */
1175 int scp_get_sink_action(struct scp_sink_action
*act
)
1179 int must_free_fname
;
1180 struct fxp_attrs attrs
;
1181 struct sftp_packet
*pktin
;
1182 struct sftp_request
*req
, *rreq
;
1185 if (!scp_sftp_dirstack_head
) {
1186 if (!scp_sftp_donethistarget
) {
1188 * Simple case: we are only dealing with one file.
1190 fname
= scp_sftp_remotepath
;
1191 must_free_fname
= 0;
1192 scp_sftp_donethistarget
= 1;
1195 * Even simpler case: one file _which we've done_.
1196 * Return 1 (finished).
1202 * We're now in the middle of stepping through a list
1203 * of names returned from fxp_readdir(); so let's carry
1206 struct scp_sftp_dirstack
*head
= scp_sftp_dirstack_head
;
1207 while (head
->namepos
< head
->namelen
&&
1208 (is_dots(head
->names
[head
->namepos
].filename
) ||
1210 !wc_match(head
->wildcard
,
1211 head
->names
[head
->namepos
].filename
))))
1212 head
->namepos
++; /* skip . and .. */
1213 if (head
->namepos
< head
->namelen
) {
1214 head
->matched_something
= 1;
1215 fname
= dupcat(head
->dirpath
, "/",
1216 head
->names
[head
->namepos
++].filename
,
1218 must_free_fname
= 1;
1221 * We've come to the end of the list; pop it off
1222 * the stack and return an ENDDIR action (or RETRY
1223 * if this was a wildcard match).
1225 if (head
->wildcard
) {
1226 act
->action
= SCP_SINK_RETRY
;
1227 if (!head
->matched_something
) {
1228 tell_user(stderr
, "pscp: wildcard '%s' matched "
1229 "no files", head
->wildcard
);
1232 sfree(head
->wildcard
);
1235 act
->action
= SCP_SINK_ENDDIR
;
1238 sfree(head
->dirpath
);
1240 scp_sftp_dirstack_head
= head
->next
;
1248 * Now we have a filename. Stat it, and see if it's a file
1251 sftp_register(req
= fxp_stat_send(fname
));
1252 rreq
= sftp_find_request(pktin
= sftp_recv());
1253 assert(rreq
== req
);
1254 ret
= fxp_stat_recv(pktin
, rreq
, &attrs
);
1256 if (!ret
|| !(attrs
.flags
& SSH_FILEXFER_ATTR_PERMISSIONS
)) {
1257 tell_user(stderr
, "unable to identify %s: %s", fname
,
1258 ret ?
"file type not supplied" : fxp_error());
1263 if (attrs
.permissions
& 0040000) {
1264 struct scp_sftp_dirstack
*newitem
;
1265 struct fxp_handle
*dirhandle
;
1266 int nnames
, namesize
;
1267 struct fxp_name
*ournames
;
1268 struct fxp_names
*names
;
1271 * It's a directory. If we're not in recursive mode,
1272 * this merits a complaint (which is fatal if the name
1273 * was specified directly, but not if it was matched by
1276 * We skip this complaint completely if
1277 * scp_sftp_wildcard is set, because that's an
1278 * indication that we're not actually supposed to
1279 * _recursively_ transfer the dir, just scan it for
1280 * things matching the wildcard.
1282 if (!scp_sftp_recursive
&& !scp_sftp_wildcard
) {
1283 tell_user(stderr
, "pscp: %s: is a directory", fname
);
1285 if (must_free_fname
) sfree(fname
);
1286 if (scp_sftp_dirstack_head
) {
1287 act
->action
= SCP_SINK_RETRY
;
1295 * Otherwise, the fun begins. We must fxp_opendir() the
1296 * directory, slurp the filenames into memory, return
1297 * SCP_SINK_DIR (unless this is a wildcard match), and
1298 * set targetisdir. The next time we're called, we will
1299 * run through the list of filenames one by one,
1300 * matching them against a wildcard if present.
1302 * If targetisdir is _already_ set (meaning we're
1303 * already in the middle of going through another such
1304 * list), we must push the other (target,namelist) pair
1307 sftp_register(req
= fxp_opendir_send(fname
));
1308 rreq
= sftp_find_request(pktin
= sftp_recv());
1309 assert(rreq
== req
);
1310 dirhandle
= fxp_opendir_recv(pktin
, rreq
);
1313 tell_user(stderr
, "scp: unable to open directory %s: %s",
1314 fname
, fxp_error());
1315 if (must_free_fname
) sfree(fname
);
1319 nnames
= namesize
= 0;
1324 sftp_register(req
= fxp_readdir_send(dirhandle
));
1325 rreq
= sftp_find_request(pktin
= sftp_recv());
1326 assert(rreq
== req
);
1327 names
= fxp_readdir_recv(pktin
, rreq
);
1329 if (names
== NULL
) {
1330 if (fxp_error_type() == SSH_FX_EOF
)
1332 tell_user(stderr
, "scp: reading directory %s: %s\n",
1333 fname
, fxp_error());
1334 if (must_free_fname
) sfree(fname
);
1339 if (names
->nnames
== 0) {
1340 fxp_free_names(names
);
1343 if (nnames
+ names
->nnames
>= namesize
) {
1344 namesize
+= names
->nnames
+ 128;
1345 ournames
= sresize(ournames
, namesize
, struct fxp_name
);
1347 for (i
= 0; i
< names
->nnames
; i
++) {
1348 if (!strcmp(names
->names
[i
].filename
, ".") ||
1349 !strcmp(names
->names
[i
].filename
, "..")) {
1351 * . and .. are normal consequences of
1352 * reading a directory, and aren't worth
1353 * complaining about.
1355 } else if (!vet_filename(names
->names
[i
].filename
)) {
1356 tell_user(stderr
, "ignoring potentially dangerous server-"
1357 "supplied filename '%s'\n",
1358 names
->names
[i
].filename
);
1360 ournames
[nnames
++] = names
->names
[i
];
1362 names
->nnames
= 0; /* prevent free_names */
1363 fxp_free_names(names
);
1365 sftp_register(req
= fxp_close_send(dirhandle
));
1366 rreq
= sftp_find_request(pktin
= sftp_recv());
1367 assert(rreq
== req
);
1368 fxp_close_recv(pktin
, rreq
);
1370 newitem
= snew(struct scp_sftp_dirstack
);
1371 newitem
->next
= scp_sftp_dirstack_head
;
1372 newitem
->names
= ournames
;
1373 newitem
->namepos
= 0;
1374 newitem
->namelen
= nnames
;
1375 if (must_free_fname
)
1376 newitem
->dirpath
= fname
;
1378 newitem
->dirpath
= dupstr(fname
);
1379 if (scp_sftp_wildcard
) {
1380 newitem
->wildcard
= scp_sftp_wildcard
;
1381 newitem
->matched_something
= 0;
1382 scp_sftp_wildcard
= NULL
;
1384 newitem
->wildcard
= NULL
;
1386 scp_sftp_dirstack_head
= newitem
;
1388 if (newitem
->wildcard
) {
1389 act
->action
= SCP_SINK_RETRY
;
1391 act
->action
= SCP_SINK_DIR
;
1392 act
->buf
= dupstr(stripslashes(fname
, 0));
1393 act
->name
= act
->buf
;
1394 act
->size
= uint64_make(0,0); /* duhh, it's a directory */
1395 act
->permissions
= 07777 & attrs
.permissions
;
1396 if (scp_sftp_preserve
&&
1397 (attrs
.flags
& SSH_FILEXFER_ATTR_ACMODTIME
)) {
1398 act
->atime
= attrs
.atime
;
1399 act
->mtime
= attrs
.mtime
;
1408 * It's a file. Return SCP_SINK_FILE.
1410 act
->action
= SCP_SINK_FILE
;
1411 act
->buf
= dupstr(stripslashes(fname
, 0));
1412 act
->name
= act
->buf
;
1413 if (attrs
.flags
& SSH_FILEXFER_ATTR_SIZE
) {
1414 act
->size
= attrs
.size
;
1416 act
->size
= uint64_make(ULONG_MAX
,ULONG_MAX
); /* no idea */
1417 act
->permissions
= 07777 & attrs
.permissions
;
1418 if (scp_sftp_preserve
&&
1419 (attrs
.flags
& SSH_FILEXFER_ATTR_ACMODTIME
)) {
1420 act
->atime
= attrs
.atime
;
1421 act
->mtime
= attrs
.mtime
;
1425 if (must_free_fname
)
1426 scp_sftp_currentname
= fname
;
1428 scp_sftp_currentname
= dupstr(fname
);
1443 if (ssh_scp_recv((unsigned char *) &ch
, 1) <= 0)
1446 bump("Protocol error: Unexpected newline");
1450 if (ssh_scp_recv((unsigned char *) &ch
, 1) <= 0)
1451 bump("Lost connection");
1454 act
->buf
= sresize(act
->buf
, bufsize
, char);
1457 } while (ch
!= '\n');
1458 act
->buf
[i
- 1] = '\0';
1460 case '\01': /* error */
1461 tell_user(stderr
, "%s\n", act
->buf
);
1463 continue; /* go round again */
1464 case '\02': /* fatal error */
1465 bump("%s", act
->buf
);
1467 back
->send(backhandle
, "", 1);
1468 act
->action
= SCP_SINK_ENDDIR
;
1471 if (sscanf(act
->buf
, "%ld %*d %ld %*d",
1472 &act
->mtime
, &act
->atime
) == 2) {
1474 back
->send(backhandle
, "", 1);
1475 continue; /* go round again */
1477 bump("Protocol error: Illegal time format");
1480 act
->action
= (action
== 'C' ? SCP_SINK_FILE
: SCP_SINK_DIR
);
1483 bump("Protocol error: Expected control record");
1486 * We will go round this loop only once, unless we hit
1493 * If we get here, we must have seen SCP_SINK_FILE or
1499 if (sscanf(act
->buf
, "%lo %s %n", &act
->permissions
,
1501 bump("Protocol error: Illegal file descriptor format");
1502 act
->size
= uint64_from_decimal(sizestr
);
1503 act
->name
= act
->buf
+ i
;
1509 int scp_accept_filexfer(void)
1512 struct sftp_packet
*pktin
;
1513 struct sftp_request
*req
, *rreq
;
1515 sftp_register(req
= fxp_open_send(scp_sftp_currentname
, SSH_FXF_READ
,
1517 rreq
= sftp_find_request(pktin
= sftp_recv());
1518 assert(rreq
== req
);
1519 scp_sftp_filehandle
= fxp_open_recv(pktin
, rreq
);
1521 if (!scp_sftp_filehandle
) {
1522 tell_user(stderr
, "pscp: unable to open %s: %s",
1523 scp_sftp_currentname
, fxp_error());
1527 scp_sftp_fileoffset
= uint64_make(0, 0);
1528 scp_sftp_xfer
= xfer_download_init(scp_sftp_filehandle
,
1529 scp_sftp_fileoffset
);
1530 sfree(scp_sftp_currentname
);
1533 back
->send(backhandle
, "", 1);
1534 return 0; /* can't fail */
1538 int scp_recv_filedata(char *data
, int len
)
1541 struct sftp_packet
*pktin
;
1545 xfer_download_queue(scp_sftp_xfer
);
1546 pktin
= sftp_recv();
1547 ret
= xfer_download_gotpkt(scp_sftp_xfer
, pktin
);
1550 tell_user(stderr
, "pscp: error while reading: %s", fxp_error());
1555 if (xfer_download_data(scp_sftp_xfer
, &vbuf
, &actuallen
)) {
1557 * This assertion relies on the fact that the natural
1558 * block size used in the xfer manager is at most that
1559 * used in this module. I don't like crossing layers in
1560 * this way, but it'll do for now.
1562 assert(actuallen
<= len
);
1563 memcpy(data
, vbuf
, actuallen
);
1568 scp_sftp_fileoffset
= uint64_add32(scp_sftp_fileoffset
, actuallen
);
1572 return ssh_scp_recv((unsigned char *) data
, len
);
1576 int scp_finish_filerecv(void)
1579 struct sftp_packet
*pktin
;
1580 struct sftp_request
*req
, *rreq
;
1583 * Ensure that xfer_done() will work correctly, so we can
1584 * clean up any outstanding requests from the file
1587 xfer_set_error(scp_sftp_xfer
);
1588 while (!xfer_done(scp_sftp_xfer
)) {
1592 pktin
= sftp_recv();
1593 xfer_download_gotpkt(scp_sftp_xfer
, pktin
);
1594 if (xfer_download_data(scp_sftp_xfer
, &vbuf
, &len
))
1597 xfer_cleanup(scp_sftp_xfer
);
1599 sftp_register(req
= fxp_close_send(scp_sftp_filehandle
));
1600 rreq
= sftp_find_request(pktin
= sftp_recv());
1601 assert(rreq
== req
);
1602 fxp_close_recv(pktin
, rreq
);
1605 back
->send(backhandle
, "", 1);
1610 /* ----------------------------------------------------------------------
1611 * Send an error message to the other side and to the screen.
1612 * Increment error counter.
1614 static void run_err(const char *fmt
, ...)
1620 str
= dupvprintf(fmt
, ap
);
1621 str2
= dupcat("scp: ", str
, "\n", NULL
);
1623 scp_send_errmsg(str2
);
1624 tell_user(stderr
, "%s", str2
);
1630 * Execute the source part of the SCP protocol.
1632 static void source(char *src
)
1635 unsigned long mtime
, atime
;
1642 time_t stat_starttime
, stat_lasttime
;
1644 attr
= file_type(src
);
1645 if (attr
== FILE_TYPE_NONEXISTENT
||
1646 attr
== FILE_TYPE_WEIRD
) {
1647 run_err("%s: %s file or directory", src
,
1648 (attr
== FILE_TYPE_WEIRD ?
"Not a" : "No such"));
1652 if (attr
== FILE_TYPE_DIRECTORY
) {
1655 * Avoid . and .. directories.
1658 p
= strrchr(src
, '/');
1660 p
= strrchr(src
, '\\');
1665 if (!strcmp(p
, ".") || !strcmp(p
, ".."))
1666 /* skip . and .. */ ;
1670 run_err("%s: not a regular file", src
);
1675 if ((last
= strrchr(src
, '/')) == NULL
)
1679 if (strrchr(last
, '\\') != NULL
)
1680 last
= strrchr(last
, '\\') + 1;
1681 if (last
== src
&& strchr(src
, ':') != NULL
)
1682 last
= strchr(src
, ':') + 1;
1684 f
= open_existing_file(src
, &size
, &mtime
, &atime
, &permissions
);
1686 run_err("%s: Cannot open file", src
);
1690 if (scp_send_filetimes(mtime
, atime
))
1696 uint64_decimal(size
, sizestr
);
1697 tell_user(stderr
, "Sending file %s, size=%s", last
, sizestr
);
1699 if (scp_send_filename(last
, size
, permissions
))
1702 stat_bytes
= uint64_make(0,0);
1703 stat_starttime
= time(NULL
);
1706 for (i
= uint64_make(0,0);
1707 uint64_compare(i
,size
) < 0;
1708 i
= uint64_add32(i
,4096)) {
1709 char transbuf
[4096];
1712 if (uint64_compare(uint64_add32(i
, k
),size
) > 0) /* i + k > size */
1713 k
= (uint64_subtract(size
, i
)).lo
; /* k = size - i; */
1714 if ((j
= read_from_file(f
, transbuf
, k
)) != k
) {
1717 bump("%s: Read error", src
);
1719 if (scp_send_filedata(transbuf
, k
))
1720 bump("%s: Network error occurred", src
);
1723 stat_bytes
= uint64_add32(stat_bytes
, k
);
1724 if (time(NULL
) != stat_lasttime
||
1725 (uint64_compare(uint64_add32(i
, k
), size
) == 0)) {
1726 stat_lasttime
= time(NULL
);
1727 print_stats(last
, size
, stat_bytes
,
1728 stat_starttime
, stat_lasttime
);
1735 (void) scp_send_finish();
1739 * Recursively send the contents of a directory.
1741 static void rsource(char *src
)
1747 if ((last
= strrchr(src
, '/')) == NULL
)
1751 if (strrchr(last
, '\\') != NULL
)
1752 last
= strrchr(last
, '\\') + 1;
1753 if (last
== src
&& strchr(src
, ':') != NULL
)
1754 last
= strchr(src
, ':') + 1;
1756 /* maybe send filetime */
1758 save_target
= scp_save_remotepath();
1761 tell_user(stderr
, "Entering directory: %s", last
);
1762 if (scp_send_dirname(last
, 0755))
1765 dir
= open_directory(src
);
1768 while ((filename
= read_filename(dir
)) != NULL
) {
1769 char *foundfile
= dupcat(src
, "/", filename
, NULL
);
1775 close_directory(dir
);
1777 (void) scp_send_enddir();
1779 scp_restore_remotepath(save_target
);
1783 * Execute the sink part of the SCP protocol.
1785 static void sink(char *targ
, char *src
)
1795 time_t stat_starttime
, stat_lasttime
;
1798 attr
= file_type(targ
);
1799 if (attr
== FILE_TYPE_DIRECTORY
)
1802 if (targetshouldbedirectory
&& !targisdir
)
1803 bump("%s: Not a directory", targ
);
1807 struct scp_sink_action act
;
1808 if (scp_get_sink_action(&act
))
1811 if (act
.action
== SCP_SINK_ENDDIR
)
1814 if (act
.action
== SCP_SINK_RETRY
)
1819 * Prevent the remote side from maliciously writing to
1820 * files outside the target area by sending a filename
1821 * containing `../'. In fact, it shouldn't be sending
1822 * filenames with any slashes or colons in at all; so
1823 * we'll find the last slash, backslash or colon in the
1824 * filename and use only the part after that. (And
1827 * In addition, we also ensure here that if we're
1828 * copying a single file and the target is a directory
1829 * (common usage: `pscp host:filename .') the remote
1830 * can't send us a _different_ file name. We can
1831 * distinguish this case because `src' will be non-NULL
1832 * and the last component of that will fail to match
1833 * (the last component of) the name sent.
1835 * Well, not always; if `src' is a wildcard, we do
1836 * expect to get back filenames that don't correspond
1837 * exactly to it. Ideally in this case, we would like
1838 * to ensure that the returned filename actually
1839 * matches the wildcard pattern - but one of SCP's
1840 * protocol infelicities is that wildcard matching is
1841 * done at the server end _by the server's rules_ and
1842 * so in general this is infeasible. Hence, we only
1843 * accept filenames that don't correspond to `src' if
1844 * unsafe mode is enabled or we are using SFTP (which
1845 * resolves remote wildcards on the client side and can
1848 char *striptarget
, *stripsrc
;
1850 striptarget
= stripslashes(act
.name
, 1);
1851 if (striptarget
!= act
.name
) {
1852 tell_user(stderr
, "warning: remote host sent a compound"
1853 " pathname '%s'", act
.name
);
1854 tell_user(stderr
, " renaming local file to '%s'",
1859 * Also check to see if the target filename is '.' or
1860 * '..', or indeed '...' and so on because Windows
1861 * appears to interpret those like '..'.
1863 if (is_dots(striptarget
)) {
1864 bump("security violation: remote host attempted to write to"
1865 " a '.' or '..' path!");
1869 stripsrc
= stripslashes(src
, 1);
1870 if (strcmp(striptarget
, stripsrc
) &&
1871 !using_sftp
&& !scp_unsafe_mode
) {
1872 tell_user(stderr
, "warning: remote host tried to write "
1873 "to a file called '%s'", striptarget
);
1874 tell_user(stderr
, " when we requested a file "
1875 "called '%s'.", stripsrc
);
1876 tell_user(stderr
, " If this is a wildcard, "
1877 "consider upgrading to SSH-2 or using");
1878 tell_user(stderr
, " the '-unsafe' option. Renaming"
1879 " of this file has been disallowed.");
1880 /* Override the name the server provided with our own. */
1881 striptarget
= stripsrc
;
1885 if (targ
[0] != '\0')
1886 destfname
= dir_file_cat(targ
, striptarget
);
1888 destfname
= dupstr(striptarget
);
1891 * In this branch of the if, the target area is a
1892 * single file with an explicitly specified name in any
1893 * case, so there's no danger.
1895 destfname
= dupstr(targ
);
1897 attr
= file_type(destfname
);
1898 exists
= (attr
!= FILE_TYPE_NONEXISTENT
);
1900 if (act
.action
== SCP_SINK_DIR
) {
1901 if (exists
&& attr
!= FILE_TYPE_DIRECTORY
) {
1902 run_err("%s: Not a directory", destfname
);
1906 if (!create_directory(destfname
)) {
1907 run_err("%s: Cannot create directory", destfname
);
1911 sink(destfname
, NULL
);
1912 /* can we set the timestamp for directories ? */
1916 f
= open_new_file(destfname
, act
.permissions
);
1918 run_err("%s: Cannot create file", destfname
);
1922 if (scp_accept_filexfer())
1925 stat_bytes
= uint64_make(0, 0);
1926 stat_starttime
= time(NULL
);
1928 stat_name
= stripslashes(destfname
, 1);
1930 received
= uint64_make(0, 0);
1931 while (uint64_compare(received
,act
.size
) < 0) {
1932 char transbuf
[32768];
1935 blksize
= uint64_make(0, 32768);
1936 if (uint64_compare(blksize
,uint64_subtract(act
.size
,received
)) > 0)
1937 blksize
= uint64_subtract(act
.size
,received
);
1938 read
= scp_recv_filedata(transbuf
, (int)blksize
.lo
);
1940 bump("Lost connection");
1943 if (write_to_file(f
, transbuf
, read
) != (int)read
) {
1945 /* FIXME: in sftp we can actually abort the transfer */
1947 printf("\r%-25.25s | %50s\n",
1949 "Write error.. waiting for end of file");
1953 stat_bytes
= uint64_add32(stat_bytes
,read
);
1954 if (time(NULL
) > stat_lasttime
||
1955 uint64_compare(uint64_add32(received
, read
), act
.size
) == 0) {
1956 stat_lasttime
= time(NULL
);
1957 print_stats(stat_name
, act
.size
, stat_bytes
,
1958 stat_starttime
, stat_lasttime
);
1961 received
= uint64_add32(received
, read
);
1964 set_file_times(f
, act
.mtime
, act
.atime
);
1969 run_err("%s: Write error", destfname
);
1972 (void) scp_finish_filerecv();
1979 * We will copy local files to a remote server.
1981 static void toremote(int argc
, char *argv
[])
1983 char *src
, *targ
, *host
, *user
;
1987 targ
= argv
[argc
- 1];
1989 /* Separate host from filename */
1993 bump("targ == NULL in toremote()");
1997 /* Substitute "." for empty target */
1999 /* Separate host and username */
2001 host
= strrchr(host
, '@');
2012 if (colon(argv
[0]) != NULL
)
2013 bump("%s: Remote to remote not supported", argv
[0]);
2015 wc_type
= test_wildcard(argv
[0], 1);
2016 if (wc_type
== WCTYPE_NONEXISTENT
)
2017 bump("%s: No such file or directory\n", argv
[0]);
2018 else if (wc_type
== WCTYPE_WILDCARD
)
2019 targetshouldbedirectory
= 1;
2022 cmd
= dupprintf("scp%s%s%s%s -t %s",
2023 verbose ?
" -v" : "",
2024 recursive ?
" -r" : "",
2025 preserve ?
" -p" : "",
2026 targetshouldbedirectory ?
" -d" : "", targ
);
2027 do_cmd(host
, user
, cmd
);
2030 if (scp_source_setup(targ
, targetshouldbedirectory
))
2033 for (i
= 0; i
< argc
- 1; i
++) {
2035 if (colon(src
) != NULL
) {
2036 tell_user(stderr
, "%s: Remote to remote not supported\n", src
);
2041 wc_type
= test_wildcard(src
, 1);
2042 if (wc_type
== WCTYPE_NONEXISTENT
) {
2043 run_err("%s: No such file or directory", src
);
2045 } else if (wc_type
== WCTYPE_FILENAME
) {
2049 WildcardMatcher
*wc
;
2052 wc
= begin_wildcard_matching(src
);
2054 run_err("%s: No such file or directory", src
);
2058 while ((filename
= wildcard_get_filename(wc
)) != NULL
) {
2063 finish_wildcard_matching(wc
);
2069 * We will copy files from a remote server to the local machine.
2071 static void tolocal(int argc
, char *argv
[])
2073 char *src
, *targ
, *host
, *user
;
2077 bump("More than one remote source not supported");
2082 /* Separate host from filename */
2086 bump("Local to local copy not supported");
2090 /* Substitute "." for empty filename */
2092 /* Separate username and hostname */
2094 host
= strrchr(host
, '@');
2104 cmd
= dupprintf("scp%s%s%s%s -f %s",
2105 verbose ?
" -v" : "",
2106 recursive ?
" -r" : "",
2107 preserve ?
" -p" : "",
2108 targetshouldbedirectory ?
" -d" : "", src
);
2109 do_cmd(host
, user
, cmd
);
2112 if (scp_sink_setup(src
, preserve
, recursive
))
2119 * We will issue a list command to get a remote directory.
2121 static void get_dir_list(int argc
, char *argv
[])
2123 char *src
, *host
, *user
;
2129 /* Separate host from filename */
2133 bump("Local file listing not supported");
2137 /* Substitute "." for empty filename */
2139 /* Separate username and hostname */
2141 host
= strrchr(host
, '@');
2151 cmd
= snewn(4 * strlen(src
) + 100, char);
2152 strcpy(cmd
, "ls -la '");
2153 p
= cmd
+ strlen(cmd
);
2154 for (q
= src
; *q
; q
++) {
2167 do_cmd(host
, user
, cmd
);
2171 scp_sftp_listdir(src
);
2173 while (ssh_scp_recv((unsigned char *) &c
, 1) > 0)
2174 tell_char(stdout
, c
);
2179 * Short description of parameters.
2181 static void usage(void)
2183 printf("PuTTY Secure Copy client\n");
2184 printf("%s\n", ver
);
2185 printf("Usage: pscp [options] [user@]host:source target\n");
2187 (" pscp [options] source [source...] [user@]host:target\n");
2188 printf(" pscp [options] -ls [user@]host:filespec\n");
2189 printf("Options:\n");
2190 printf(" -V print version information and exit\n");
2191 printf(" -pgpfp print PGP key fingerprints and exit\n");
2192 printf(" -p preserve file attributes\n");
2193 printf(" -q quiet, don't show statistics\n");
2194 printf(" -r copy directories recursively\n");
2195 printf(" -v show verbose messages\n");
2196 printf(" -load sessname Load settings from saved session\n");
2197 printf(" -P port connect to specified port\n");
2198 printf(" -l user connect with specified username\n");
2199 printf(" -pw passw login with specified password\n");
2200 printf(" -1 -2 force use of particular SSH protocol version\n");
2201 printf(" -4 -6 force use of IPv4 or IPv6\n");
2202 printf(" -C enable compression\n");
2203 printf(" -i key private key file for authentication\n");
2204 printf(" -noagent disable use of Pageant\n");
2205 printf(" -agent enable use of Pageant\n");
2206 printf(" -batch disable all interactive prompts\n");
2207 printf(" -unsafe allow server-side wildcards (DANGEROUS)\n");
2208 printf(" -sftp force use of SFTP protocol\n");
2209 printf(" -scp force use of SCP protocol\n");
2212 * -gui is an internal option, used by GUI front ends to get
2213 * pscp to pass progress reports back to them. It's not an
2214 * ordinary user-accessible option, so it shouldn't be part of
2215 * the command-line help. The only people who need to know
2216 * about it are programmers, and they can read the source.
2219 (" -gui hWnd GUI mode with the windows handle for receiving messages\n");
2226 printf("pscp: %s\n", ver
);
2230 void cmdline_error(char *p
, ...)
2233 fprintf(stderr
, "pscp: ");
2235 vfprintf(stderr
, p
, ap
);
2237 fprintf(stderr
, "\n try typing just \"pscp\" for help\n");
2242 * Main program. (Called `psftp_main' because it gets called from
2243 * *sftp.c; bit silly, I know, but it had to be called _something_.)
2245 int psftp_main(int argc
, char *argv
[])
2249 default_protocol
= PROT_TELNET
;
2252 #ifdef FLAG_SYNCAGENT
2256 cmdline_tooltype
= TOOLTYPE_FILETRANSFER
;
2259 /* Load Default Settings before doing anything else. */
2261 do_defaults(NULL
, conf
);
2262 loaded_session
= FALSE
;
2264 for (i
= 1; i
< argc
; i
++) {
2266 if (argv
[i
][0] != '-')
2268 ret
= cmdline_process_param(argv
[i
], i
+1<argc?argv
[i
+1]:NULL
, 1, conf
);
2270 cmdline_error("option \"%s\" requires an argument", argv
[i
]);
2271 } else if (ret
== 2) {
2272 i
++; /* skip next argument */
2273 } else if (ret
== 1) {
2274 /* We have our own verbosity in addition to `flags'. */
2275 if (flags
& FLAG_VERBOSE
)
2277 } else if (strcmp(argv
[i
], "-pgpfp") == 0) {
2280 } else if (strcmp(argv
[i
], "-r") == 0) {
2282 } else if (strcmp(argv
[i
], "-p") == 0) {
2284 } else if (strcmp(argv
[i
], "-q") == 0) {
2286 } else if (strcmp(argv
[i
], "-h") == 0 ||
2287 strcmp(argv
[i
], "-?") == 0 ||
2288 strcmp(argv
[i
], "--help") == 0) {
2290 } else if (strcmp(argv
[i
], "-V") == 0 ||
2291 strcmp(argv
[i
], "--version") == 0) {
2293 } else if (strcmp(argv
[i
], "-ls") == 0) {
2295 } else if (strcmp(argv
[i
], "-batch") == 0) {
2296 console_batch_mode
= 1;
2297 } else if (strcmp(argv
[i
], "-unsafe") == 0) {
2298 scp_unsafe_mode
= 1;
2299 } else if (strcmp(argv
[i
], "-sftp") == 0) {
2300 try_scp
= 0; try_sftp
= 1;
2301 } else if (strcmp(argv
[i
], "-scp") == 0) {
2302 try_scp
= 1; try_sftp
= 0;
2303 } else if (strcmp(argv
[i
], "--") == 0) {
2307 cmdline_error("unknown option \"%s\"", argv
[i
]);
2317 get_dir_list(argc
, argv
);
2324 targetshouldbedirectory
= 1;
2326 if (colon(argv
[argc
- 1]) != NULL
)
2327 toremote(argc
, argv
);
2329 tolocal(argc
, argv
);
2332 if (back
!= NULL
&& back
->connected(backhandle
)) {
2334 back
->special(backhandle
, TS_EOF
);
2336 ssh_scp_recv((unsigned char *) &ch
, 1);
2341 console_provide_logctx(NULL
);
2342 back
->free(backhandle
);
2346 return (errs
== 0 ?
0 : 1);