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 * Wait for the reply to a single SFTP request. Parallels the same
324 * function in psftp.c (but isn't centralised into sftp.c because the
325 * latter module handles SFTP only and shouldn't assume that SFTP is
326 * the only thing going on by calling connection_fatal).
328 struct sftp_packet
*sftp_wait_for_reply(struct sftp_request
*req
)
330 struct sftp_packet
*pktin
;
331 struct sftp_request
*rreq
;
336 connection_fatal(NULL
, "did not receive SFTP response packet "
338 rreq
= sftp_find_request(pktin
);
340 connection_fatal(NULL
, "unable to understand SFTP response packet "
341 "from server: %s", fxp_error());
346 * Open an SSH connection to user@host and execute cmd.
348 static void do_cmd(char *host
, char *user
, char *cmd
)
354 if (host
== NULL
|| host
[0] == '\0')
355 bump("Empty host name");
358 * Remove fiddly bits of address: remove a colon suffix, and
359 * the square brackets around an IPv6 literal address.
361 if (host
[0] == '[') {
363 host
[strcspn(host
, "]")] = '\0';
365 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
);
387 /* Patch in hostname `host' to session details. */
388 conf_set_str(conf
, CONF_host
, host
);
392 * Force use of SSH. (If they got the protocol wrong we assume the
393 * port is useless too.)
395 if (conf_get_int(conf
, CONF_protocol
) != PROT_SSH
) {
396 conf_set_int(conf
, CONF_protocol
, PROT_SSH
);
397 conf_set_int(conf
, CONF_port
, 22);
401 * Enact command-line overrides.
403 cmdline_run_saved(conf
);
406 * Muck about with the hostname in various ways.
409 char *hostbuf
= dupstr(conf_get_str(conf
, CONF_host
));
410 char *host
= hostbuf
;
414 * Trim leading whitespace.
416 host
+= strspn(host
, " \t");
419 * See if host is of the form user@host, and separate out
420 * the username if so.
422 if (host
[0] != '\0') {
423 char *atsign
= strrchr(host
, '@');
426 conf_set_str(conf
, CONF_username
, host
);
432 * Remove any remaining whitespace.
437 if (*q
!= ' ' && *q
!= '\t')
443 conf_set_str(conf
, CONF_host
, hostbuf
);
448 if (user
!= NULL
&& user
[0] != '\0') {
449 conf_set_str(conf
, CONF_username
, user
);
450 } else if (conf_get_str(conf
, CONF_username
)[0] == '\0') {
451 user
= get_username();
453 bump("Empty user name");
456 tell_user(stderr
, "Guessing user name: %s", user
);
457 conf_set_str(conf
, CONF_username
, user
);
463 * Disable scary things which shouldn't be enabled for simple
464 * things like SCP and SFTP: agent forwarding, port forwarding,
467 conf_set_int(conf
, CONF_x11_forward
, 0);
468 conf_set_int(conf
, CONF_agentfwd
, 0);
469 conf_set_int(conf
, CONF_ssh_simple
, TRUE
);
472 while ((key
= conf_get_str_nthstrkey(conf
, CONF_portfwd
, 0)) != NULL
)
473 conf_del_str_str(conf
, CONF_portfwd
, key
);
477 * Set up main and possibly fallback command depending on
478 * options specified by user.
479 * Attempt to start the SFTP subsystem as a first choice,
480 * falling back to the provided scp command if that fails.
482 conf_set_str(conf
, CONF_remote_cmd2
, "");
484 /* First choice is SFTP subsystem. */
485 main_cmd_is_sftp
= 1;
486 conf_set_str(conf
, CONF_remote_cmd
, "sftp");
487 conf_set_int(conf
, CONF_ssh_subsys
, TRUE
);
489 /* Fallback is to use the provided scp command. */
490 fallback_cmd_is_sftp
= 0;
491 conf_set_str(conf
, CONF_remote_cmd2
, cmd
);
492 conf_set_int(conf
, CONF_ssh_subsys2
, FALSE
);
494 /* Since we're not going to try SCP, we may as well try
495 * harder to find an SFTP server, since in the current
496 * implementation we have a spare slot. */
497 fallback_cmd_is_sftp
= 1;
498 /* see psftp.c for full explanation of this kludge */
499 conf_set_str(conf
, CONF_remote_cmd2
,
500 "test -x /usr/lib/sftp-server &&"
501 " exec /usr/lib/sftp-server\n"
502 "test -x /usr/local/lib/sftp-server &&"
503 " exec /usr/local/lib/sftp-server\n"
505 conf_set_int(conf
, CONF_ssh_subsys2
, FALSE
);
508 /* Don't try SFTP at all; just try the scp command. */
509 main_cmd_is_sftp
= 0;
510 conf_set_str(conf
, CONF_remote_cmd
, cmd
);
511 conf_set_int(conf
, CONF_ssh_subsys
, FALSE
);
513 conf_set_int(conf
, CONF_nopty
, TRUE
);
517 err
= back
->init(NULL
, &backhandle
, conf
,
518 conf_get_str(conf
, CONF_host
),
519 conf_get_int(conf
, CONF_port
),
521 conf_get_int(conf
, CONF_tcp_keepalives
));
523 bump("ssh_init: %s", err
);
524 logctx
= log_init(NULL
, conf
);
525 back
->provide_logctx(backhandle
, logctx
);
526 console_provide_logctx(logctx
);
528 if (verbose
&& realhost
!= NULL
&& errs
== 0)
529 tell_user(stderr
, "Connected to %s\n", realhost
);
534 * Update statistic information about current file.
536 static void print_stats(char *name
, uint64 size
, uint64 done
,
537 time_t start
, time_t now
)
548 elap
= (unsigned long) difftime(now
, start
);
551 ratebs
= (float) (uint64_to_double(done
) / elap
);
553 ratebs
= (float) uint64_to_double(done
);
556 eta
= (unsigned long) (uint64_to_double(uint64_subtract(size
, done
)));
558 eta
= (unsigned long)
559 ((uint64_to_double(uint64_subtract(size
, done
)) / ratebs
));
562 etastr
= dupprintf("%02ld:%02ld:%02ld",
563 eta
/ 3600, (eta
% 3600) / 60, eta
% 60);
565 donedbl
= uint64_to_double(done
);
566 sizedbl
= uint64_to_double(size
);
567 pct
= (int) (100 * (donedbl
* 1.0 / sizedbl
));
571 /* divide by 1024 to provide kB */
572 uint64_decimal(uint64_shift_right(done
, 10), donekb
);
573 len
= printf("\r%-25.25s | %s kB | %5.1f kB/s | ETA: %8s | %3d%%",
575 donekb
, ratebs
/ 1024.0, etastr
, pct
);
576 if (len
< prev_stats_len
)
577 printf("%*s", prev_stats_len
- len
, "");
578 prev_stats_len
= len
;
580 if (uint64_compare(done
, size
) == 0)
590 * Find a colon in str and return a pointer to the colon.
591 * This is used to separate hostname from filename.
593 static char *colon(char *str
)
595 /* We ignore a leading colon, since the hostname cannot be
596 empty. We also ignore a colon as second character because
597 of filenames like f:myfile.txt. */
598 if (str
[0] == '\0' || str
[0] == ':' ||
599 (str
[0] != '[' && str
[1] == ':'))
601 while (*str
!= '\0' && *str
!= ':' && *str
!= '/' && *str
!= '\\') {
603 /* Skip over IPv6 literal addresses
604 * (eg: 'jeroen@[2001:db8::1]:myfile.txt') */
605 char *ipv6_end
= strchr(str
, ']');
619 * Return a pointer to the portion of str that comes after the last
620 * slash (or backslash or colon, if `local' is TRUE).
622 static char *stripslashes(char *str
, int local
)
627 p
= strchr(str
, ':');
631 p
= strrchr(str
, '/');
635 p
= strrchr(str
, '\\');
643 * Determine whether a string is entirely composed of dots.
645 static int is_dots(char *str
)
647 return str
[strspn(str
, ".")] == '\0';
651 * Wait for a response from the other side.
652 * Return 0 if ok, -1 if error.
654 static int response(void)
656 char ch
, resp
, rbuf
[2048];
659 if (ssh_scp_recv((unsigned char *) &resp
, 1) <= 0)
660 bump("Lost connection");
670 case 2: /* fatal error */
672 if (ssh_scp_recv((unsigned char *) &ch
, 1) <= 0)
673 bump("Protocol error: Lost connection");
675 } while (p
< sizeof(rbuf
) && ch
!= '\n');
678 tell_user(stderr
, "%s\n", rbuf
);
686 int sftp_recvdata(char *buf
, int len
)
688 return ssh_scp_recv((unsigned char *) buf
, len
);
690 int sftp_senddata(char *buf
, int len
)
692 back
->send(backhandle
, buf
, len
);
696 /* ----------------------------------------------------------------------
697 * sftp-based replacement for the hacky `pscp -ls'.
699 static int sftp_ls_compare(const void *av
, const void *bv
)
701 const struct fxp_name
*a
= (const struct fxp_name
*) av
;
702 const struct fxp_name
*b
= (const struct fxp_name
*) bv
;
703 return strcmp(a
->filename
, b
->filename
);
705 void scp_sftp_listdir(char *dirname
)
707 struct fxp_handle
*dirh
;
708 struct fxp_names
*names
;
709 struct fxp_name
*ournames
;
710 struct sftp_packet
*pktin
;
711 struct sftp_request
*req
;
712 int nnames
, namesize
;
716 tell_user(stderr
, "unable to initialise SFTP: %s", fxp_error());
721 printf("Listing directory %s\n", dirname
);
723 req
= fxp_opendir_send(dirname
);
724 pktin
= sftp_wait_for_reply(req
);
725 dirh
= fxp_opendir_recv(pktin
, req
);
728 printf("Unable to open %s: %s\n", dirname
, fxp_error());
730 nnames
= namesize
= 0;
735 req
= fxp_readdir_send(dirh
);
736 pktin
= sftp_wait_for_reply(req
);
737 names
= fxp_readdir_recv(pktin
, req
);
740 if (fxp_error_type() == SSH_FX_EOF
)
742 printf("Reading directory %s: %s\n", dirname
, fxp_error());
745 if (names
->nnames
== 0) {
746 fxp_free_names(names
);
750 if (nnames
+ names
->nnames
>= namesize
) {
751 namesize
+= names
->nnames
+ 128;
752 ournames
= sresize(ournames
, namesize
, struct fxp_name
);
755 for (i
= 0; i
< names
->nnames
; i
++)
756 ournames
[nnames
++] = names
->names
[i
];
757 names
->nnames
= 0; /* prevent free_names */
758 fxp_free_names(names
);
760 req
= fxp_close_send(dirh
);
761 pktin
= sftp_wait_for_reply(req
);
762 fxp_close_recv(pktin
, req
);
765 * Now we have our filenames. Sort them by actual file
766 * name, and then output the longname parts.
769 qsort(ournames
, nnames
, sizeof(*ournames
), sftp_ls_compare
);
774 for (i
= 0; i
< nnames
; i
++)
775 printf("%s\n", ournames
[i
].longname
);
779 /* ----------------------------------------------------------------------
780 * Helper routines that contain the actual SCP protocol elements,
781 * implemented both as SCP1 and SFTP.
784 static struct scp_sftp_dirstack
{
785 struct scp_sftp_dirstack
*next
;
786 struct fxp_name
*names
;
787 int namepos
, namelen
;
790 int matched_something
; /* wildcard match set was non-empty */
791 } *scp_sftp_dirstack_head
;
792 static char *scp_sftp_remotepath
, *scp_sftp_currentname
;
793 static char *scp_sftp_wildcard
;
794 static int scp_sftp_targetisdir
, scp_sftp_donethistarget
;
795 static int scp_sftp_preserve
, scp_sftp_recursive
;
796 static unsigned long scp_sftp_mtime
, scp_sftp_atime
;
797 static int scp_has_times
;
798 static struct fxp_handle
*scp_sftp_filehandle
;
799 static struct fxp_xfer
*scp_sftp_xfer
;
800 static uint64 scp_sftp_fileoffset
;
802 int scp_source_setup(char *target
, int shouldbedir
)
806 * Find out whether the target filespec is in fact a
809 struct sftp_packet
*pktin
;
810 struct sftp_request
*req
;
811 struct fxp_attrs attrs
;
815 tell_user(stderr
, "unable to initialise SFTP: %s", fxp_error());
820 req
= fxp_stat_send(target
);
821 pktin
= sftp_wait_for_reply(req
);
822 ret
= fxp_stat_recv(pktin
, req
, &attrs
);
824 if (!ret
|| !(attrs
.flags
& SSH_FILEXFER_ATTR_PERMISSIONS
))
825 scp_sftp_targetisdir
= 0;
827 scp_sftp_targetisdir
= (attrs
.permissions
& 0040000) != 0;
829 if (shouldbedir
&& !scp_sftp_targetisdir
) {
830 bump("pscp: remote filespec %s: not a directory\n", target
);
833 scp_sftp_remotepath
= dupstr(target
);
842 int scp_send_errmsg(char *str
)
845 /* do nothing; we never need to send our errors to the server */
847 back
->send(backhandle
, "\001", 1);/* scp protocol error prefix */
848 back
->send(backhandle
, str
, strlen(str
));
850 return 0; /* can't fail */
853 int scp_send_filetimes(unsigned long mtime
, unsigned long atime
)
856 scp_sftp_mtime
= mtime
;
857 scp_sftp_atime
= atime
;
862 sprintf(buf
, "T%lu 0 %lu 0\n", mtime
, atime
);
863 back
->send(backhandle
, buf
, strlen(buf
));
868 int scp_send_filename(char *name
, uint64 size
, int permissions
)
872 struct sftp_packet
*pktin
;
873 struct sftp_request
*req
;
874 struct fxp_attrs attrs
;
876 if (scp_sftp_targetisdir
) {
877 fullname
= dupcat(scp_sftp_remotepath
, "/", name
, NULL
);
879 fullname
= dupstr(scp_sftp_remotepath
);
883 PUT_PERMISSIONS(attrs
, permissions
);
885 req
= fxp_open_send(fullname
,
886 SSH_FXF_WRITE
| SSH_FXF_CREAT
| SSH_FXF_TRUNC
,
888 pktin
= sftp_wait_for_reply(req
);
889 scp_sftp_filehandle
= fxp_open_recv(pktin
, req
);
891 if (!scp_sftp_filehandle
) {
892 tell_user(stderr
, "pscp: unable to open %s: %s",
893 fullname
, fxp_error());
897 scp_sftp_fileoffset
= uint64_make(0, 0);
898 scp_sftp_xfer
= xfer_upload_init(scp_sftp_filehandle
,
899 scp_sftp_fileoffset
);
905 uint64_decimal(size
, sizestr
);
908 sprintf(buf
, "C%04o %s ", (int)(permissions
& 07777), sizestr
);
909 back
->send(backhandle
, buf
, strlen(buf
));
910 back
->send(backhandle
, name
, strlen(name
));
911 back
->send(backhandle
, "\n", 1);
916 int scp_send_filedata(char *data
, int len
)
920 struct sftp_packet
*pktin
;
922 if (!scp_sftp_filehandle
) {
926 while (!xfer_upload_ready(scp_sftp_xfer
)) {
928 ret
= xfer_upload_gotpkt(scp_sftp_xfer
, pktin
);
930 tell_user(stderr
, "error while writing: %s\n", fxp_error());
936 xfer_upload_data(scp_sftp_xfer
, data
, len
);
938 scp_sftp_fileoffset
= uint64_add32(scp_sftp_fileoffset
, len
);
941 int bufsize
= back
->send(backhandle
, data
, len
);
944 * If the network transfer is backing up - that is, the
945 * remote site is not accepting data as fast as we can
946 * produce it - then we must loop on network events until
947 * we have space in the buffer again.
949 while (bufsize
> MAX_SCP_BUFSIZE
) {
950 if (ssh_sftp_loop_iteration() < 0)
952 bufsize
= back
->sendbuffer(backhandle
);
959 int scp_send_finish(void)
962 struct fxp_attrs attrs
;
963 struct sftp_packet
*pktin
;
964 struct sftp_request
*req
;
967 while (!xfer_done(scp_sftp_xfer
)) {
969 ret
= xfer_upload_gotpkt(scp_sftp_xfer
, pktin
);
971 tell_user(stderr
, "error while writing: %s\n", fxp_error());
976 xfer_cleanup(scp_sftp_xfer
);
978 if (!scp_sftp_filehandle
) {
982 attrs
.flags
= SSH_FILEXFER_ATTR_ACMODTIME
;
983 attrs
.atime
= scp_sftp_atime
;
984 attrs
.mtime
= scp_sftp_mtime
;
985 req
= fxp_fsetstat_send(scp_sftp_filehandle
, attrs
);
986 pktin
= sftp_wait_for_reply(req
);
987 ret
= fxp_fsetstat_recv(pktin
, req
);
989 tell_user(stderr
, "unable to set file times: %s\n", fxp_error());
993 req
= fxp_close_send(scp_sftp_filehandle
);
994 pktin
= sftp_wait_for_reply(req
);
995 fxp_close_recv(pktin
, req
);
999 back
->send(backhandle
, "", 1);
1004 char *scp_save_remotepath(void)
1007 return scp_sftp_remotepath
;
1012 void scp_restore_remotepath(char *data
)
1015 scp_sftp_remotepath
= data
;
1018 int scp_send_dirname(char *name
, int modes
)
1023 struct fxp_attrs attrs
;
1024 struct sftp_packet
*pktin
;
1025 struct sftp_request
*req
;
1028 if (scp_sftp_targetisdir
) {
1029 fullname
= dupcat(scp_sftp_remotepath
, "/", name
, NULL
);
1031 fullname
= dupstr(scp_sftp_remotepath
);
1035 * We don't worry about whether we managed to create the
1036 * directory, because if it exists already it's OK just to
1037 * use it. Instead, we will stat it afterwards, and if it
1038 * exists and is a directory we will assume we were either
1039 * successful or it didn't matter.
1041 req
= fxp_mkdir_send(fullname
);
1042 pktin
= sftp_wait_for_reply(req
);
1043 ret
= fxp_mkdir_recv(pktin
, req
);
1048 err
= "server reported no error";
1050 req
= fxp_stat_send(fullname
);
1051 pktin
= sftp_wait_for_reply(req
);
1052 ret
= fxp_stat_recv(pktin
, req
, &attrs
);
1054 if (!ret
|| !(attrs
.flags
& SSH_FILEXFER_ATTR_PERMISSIONS
) ||
1055 !(attrs
.permissions
& 0040000)) {
1056 tell_user(stderr
, "unable to create directory %s: %s",
1062 scp_sftp_remotepath
= fullname
;
1067 sprintf(buf
, "D%04o 0 ", modes
);
1068 back
->send(backhandle
, buf
, strlen(buf
));
1069 back
->send(backhandle
, name
, strlen(name
));
1070 back
->send(backhandle
, "\n", 1);
1075 int scp_send_enddir(void)
1078 sfree(scp_sftp_remotepath
);
1081 back
->send(backhandle
, "E\n", 2);
1087 * Yes, I know; I have an scp_sink_setup _and_ an scp_sink_init.
1088 * That's bad. The difference is that scp_sink_setup is called once
1089 * right at the start, whereas scp_sink_init is called to
1090 * initialise every level of recursion in the protocol.
1092 int scp_sink_setup(char *source
, int preserve
, int recursive
)
1098 tell_user(stderr
, "unable to initialise SFTP: %s", fxp_error());
1103 * It's possible that the source string we've been given
1104 * contains a wildcard. If so, we must split the directory
1105 * away from the wildcard itself (throwing an error if any
1106 * wildcardness comes before the final slash) and arrange
1107 * things so that a dirstack entry will be set up.
1109 newsource
= snewn(1+strlen(source
), char);
1110 if (!wc_unescape(newsource
, source
)) {
1111 /* Yes, here we go; it's a wildcard. Bah. */
1112 char *dupsource
, *lastpart
, *dirpart
, *wildcard
;
1113 dupsource
= dupstr(source
);
1114 lastpart
= stripslashes(dupsource
, 0);
1115 wildcard
= dupstr(lastpart
);
1117 if (*dupsource
&& dupsource
[1]) {
1119 * The remains of dupsource are at least two
1120 * characters long, meaning the pathname wasn't
1121 * empty or just `/'. Hence, we remove the trailing
1124 lastpart
[-1] = '\0';
1125 } else if (!*dupsource
) {
1127 * The remains of dupsource are _empty_ - the whole
1128 * pathname was a wildcard. Hence we need to
1129 * replace it with ".".
1132 dupsource
= dupstr(".");
1136 * Now we have separated our string into dupsource (the
1137 * directory part) and wildcard. Both of these will
1138 * need freeing at some point. Next step is to remove
1139 * wildcard escapes from the directory part, throwing
1140 * an error if it contains a real wildcard.
1142 dirpart
= snewn(1+strlen(dupsource
), char);
1143 if (!wc_unescape(dirpart
, dupsource
)) {
1144 tell_user(stderr
, "%s: multiple-level wildcards unsupported",
1154 * Now we have dirpart (unescaped, ie a valid remote
1155 * path), and wildcard (a wildcard). This will be
1156 * sufficient to arrange a dirstack entry.
1158 scp_sftp_remotepath
= dirpart
;
1159 scp_sftp_wildcard
= wildcard
;
1162 scp_sftp_remotepath
= newsource
;
1163 scp_sftp_wildcard
= NULL
;
1165 scp_sftp_preserve
= preserve
;
1166 scp_sftp_recursive
= recursive
;
1167 scp_sftp_donethistarget
= 0;
1168 scp_sftp_dirstack_head
= NULL
;
1173 int scp_sink_init(void)
1176 back
->send(backhandle
, "", 1);
1181 #define SCP_SINK_FILE 1
1182 #define SCP_SINK_DIR 2
1183 #define SCP_SINK_ENDDIR 3
1184 #define SCP_SINK_RETRY 4 /* not an action; just try again */
1185 struct scp_sink_action
{
1186 int action
; /* FILE, DIR, ENDDIR */
1187 char *buf
; /* will need freeing after use */
1188 char *name
; /* filename or dirname (not ENDDIR) */
1189 long permissions
; /* access permissions (not ENDDIR) */
1190 uint64 size
; /* file size (not ENDDIR) */
1191 int settime
; /* 1 if atime and mtime are filled */
1192 unsigned long atime
, mtime
; /* access times for the file */
1195 int scp_get_sink_action(struct scp_sink_action
*act
)
1199 int must_free_fname
;
1200 struct fxp_attrs attrs
;
1201 struct sftp_packet
*pktin
;
1202 struct sftp_request
*req
;
1205 if (!scp_sftp_dirstack_head
) {
1206 if (!scp_sftp_donethistarget
) {
1208 * Simple case: we are only dealing with one file.
1210 fname
= scp_sftp_remotepath
;
1211 must_free_fname
= 0;
1212 scp_sftp_donethistarget
= 1;
1215 * Even simpler case: one file _which we've done_.
1216 * Return 1 (finished).
1222 * We're now in the middle of stepping through a list
1223 * of names returned from fxp_readdir(); so let's carry
1226 struct scp_sftp_dirstack
*head
= scp_sftp_dirstack_head
;
1227 while (head
->namepos
< head
->namelen
&&
1228 (is_dots(head
->names
[head
->namepos
].filename
) ||
1230 !wc_match(head
->wildcard
,
1231 head
->names
[head
->namepos
].filename
))))
1232 head
->namepos
++; /* skip . and .. */
1233 if (head
->namepos
< head
->namelen
) {
1234 head
->matched_something
= 1;
1235 fname
= dupcat(head
->dirpath
, "/",
1236 head
->names
[head
->namepos
++].filename
,
1238 must_free_fname
= 1;
1241 * We've come to the end of the list; pop it off
1242 * the stack and return an ENDDIR action (or RETRY
1243 * if this was a wildcard match).
1245 if (head
->wildcard
) {
1246 act
->action
= SCP_SINK_RETRY
;
1247 if (!head
->matched_something
) {
1248 tell_user(stderr
, "pscp: wildcard '%s' matched "
1249 "no files", head
->wildcard
);
1252 sfree(head
->wildcard
);
1255 act
->action
= SCP_SINK_ENDDIR
;
1258 sfree(head
->dirpath
);
1260 scp_sftp_dirstack_head
= head
->next
;
1268 * Now we have a filename. Stat it, and see if it's a file
1271 req
= fxp_stat_send(fname
);
1272 pktin
= sftp_wait_for_reply(req
);
1273 ret
= fxp_stat_recv(pktin
, req
, &attrs
);
1275 if (!ret
|| !(attrs
.flags
& SSH_FILEXFER_ATTR_PERMISSIONS
)) {
1276 tell_user(stderr
, "unable to identify %s: %s", fname
,
1277 ret ?
"file type not supplied" : fxp_error());
1282 if (attrs
.permissions
& 0040000) {
1283 struct scp_sftp_dirstack
*newitem
;
1284 struct fxp_handle
*dirhandle
;
1285 int nnames
, namesize
;
1286 struct fxp_name
*ournames
;
1287 struct fxp_names
*names
;
1290 * It's a directory. If we're not in recursive mode,
1291 * this merits a complaint (which is fatal if the name
1292 * was specified directly, but not if it was matched by
1295 * We skip this complaint completely if
1296 * scp_sftp_wildcard is set, because that's an
1297 * indication that we're not actually supposed to
1298 * _recursively_ transfer the dir, just scan it for
1299 * things matching the wildcard.
1301 if (!scp_sftp_recursive
&& !scp_sftp_wildcard
) {
1302 tell_user(stderr
, "pscp: %s: is a directory", fname
);
1304 if (must_free_fname
) sfree(fname
);
1305 if (scp_sftp_dirstack_head
) {
1306 act
->action
= SCP_SINK_RETRY
;
1314 * Otherwise, the fun begins. We must fxp_opendir() the
1315 * directory, slurp the filenames into memory, return
1316 * SCP_SINK_DIR (unless this is a wildcard match), and
1317 * set targetisdir. The next time we're called, we will
1318 * run through the list of filenames one by one,
1319 * matching them against a wildcard if present.
1321 * If targetisdir is _already_ set (meaning we're
1322 * already in the middle of going through another such
1323 * list), we must push the other (target,namelist) pair
1326 req
= fxp_opendir_send(fname
);
1327 pktin
= sftp_wait_for_reply(req
);
1328 dirhandle
= fxp_opendir_recv(pktin
, req
);
1331 tell_user(stderr
, "scp: unable to open directory %s: %s",
1332 fname
, fxp_error());
1333 if (must_free_fname
) sfree(fname
);
1337 nnames
= namesize
= 0;
1342 req
= fxp_readdir_send(dirhandle
);
1343 pktin
= sftp_wait_for_reply(req
);
1344 names
= fxp_readdir_recv(pktin
, req
);
1346 if (names
== NULL
) {
1347 if (fxp_error_type() == SSH_FX_EOF
)
1349 tell_user(stderr
, "scp: reading directory %s: %s\n",
1350 fname
, fxp_error());
1352 req
= fxp_close_send(dirhandle
);
1353 pktin
= sftp_wait_for_reply(req
);
1354 fxp_close_recv(pktin
, req
);
1356 if (must_free_fname
) sfree(fname
);
1361 if (names
->nnames
== 0) {
1362 fxp_free_names(names
);
1365 if (nnames
+ names
->nnames
>= namesize
) {
1366 namesize
+= names
->nnames
+ 128;
1367 ournames
= sresize(ournames
, namesize
, struct fxp_name
);
1369 for (i
= 0; i
< names
->nnames
; i
++) {
1370 if (!strcmp(names
->names
[i
].filename
, ".") ||
1371 !strcmp(names
->names
[i
].filename
, "..")) {
1373 * . and .. are normal consequences of
1374 * reading a directory, and aren't worth
1375 * complaining about.
1377 } else if (!vet_filename(names
->names
[i
].filename
)) {
1378 tell_user(stderr
, "ignoring potentially dangerous server-"
1379 "supplied filename '%s'\n",
1380 names
->names
[i
].filename
);
1382 ournames
[nnames
++] = names
->names
[i
];
1384 names
->nnames
= 0; /* prevent free_names */
1385 fxp_free_names(names
);
1387 req
= fxp_close_send(dirhandle
);
1388 pktin
= sftp_wait_for_reply(req
);
1389 fxp_close_recv(pktin
, req
);
1391 newitem
= snew(struct scp_sftp_dirstack
);
1392 newitem
->next
= scp_sftp_dirstack_head
;
1393 newitem
->names
= ournames
;
1394 newitem
->namepos
= 0;
1395 newitem
->namelen
= nnames
;
1396 if (must_free_fname
)
1397 newitem
->dirpath
= fname
;
1399 newitem
->dirpath
= dupstr(fname
);
1400 if (scp_sftp_wildcard
) {
1401 newitem
->wildcard
= scp_sftp_wildcard
;
1402 newitem
->matched_something
= 0;
1403 scp_sftp_wildcard
= NULL
;
1405 newitem
->wildcard
= NULL
;
1407 scp_sftp_dirstack_head
= newitem
;
1409 if (newitem
->wildcard
) {
1410 act
->action
= SCP_SINK_RETRY
;
1412 act
->action
= SCP_SINK_DIR
;
1413 act
->buf
= dupstr(stripslashes(fname
, 0));
1414 act
->name
= act
->buf
;
1415 act
->size
= uint64_make(0,0); /* duhh, it's a directory */
1416 act
->permissions
= 07777 & attrs
.permissions
;
1417 if (scp_sftp_preserve
&&
1418 (attrs
.flags
& SSH_FILEXFER_ATTR_ACMODTIME
)) {
1419 act
->atime
= attrs
.atime
;
1420 act
->mtime
= attrs
.mtime
;
1429 * It's a file. Return SCP_SINK_FILE.
1431 act
->action
= SCP_SINK_FILE
;
1432 act
->buf
= dupstr(stripslashes(fname
, 0));
1433 act
->name
= act
->buf
;
1434 if (attrs
.flags
& SSH_FILEXFER_ATTR_SIZE
) {
1435 act
->size
= attrs
.size
;
1437 act
->size
= uint64_make(ULONG_MAX
,ULONG_MAX
); /* no idea */
1438 act
->permissions
= 07777 & attrs
.permissions
;
1439 if (scp_sftp_preserve
&&
1440 (attrs
.flags
& SSH_FILEXFER_ATTR_ACMODTIME
)) {
1441 act
->atime
= attrs
.atime
;
1442 act
->mtime
= attrs
.mtime
;
1446 if (must_free_fname
)
1447 scp_sftp_currentname
= fname
;
1449 scp_sftp_currentname
= dupstr(fname
);
1464 if (ssh_scp_recv((unsigned char *) &ch
, 1) <= 0)
1467 bump("Protocol error: Unexpected newline");
1471 if (ssh_scp_recv((unsigned char *) &ch
, 1) <= 0)
1472 bump("Lost connection");
1475 act
->buf
= sresize(act
->buf
, bufsize
, char);
1478 } while (ch
!= '\n');
1479 act
->buf
[i
- 1] = '\0';
1481 case '\01': /* error */
1482 tell_user(stderr
, "%s\n", act
->buf
);
1484 continue; /* go round again */
1485 case '\02': /* fatal error */
1486 bump("%s", act
->buf
);
1488 back
->send(backhandle
, "", 1);
1489 act
->action
= SCP_SINK_ENDDIR
;
1492 if (sscanf(act
->buf
, "%ld %*d %ld %*d",
1493 &act
->mtime
, &act
->atime
) == 2) {
1495 back
->send(backhandle
, "", 1);
1496 continue; /* go round again */
1498 bump("Protocol error: Illegal time format");
1501 act
->action
= (action
== 'C' ? SCP_SINK_FILE
: SCP_SINK_DIR
);
1504 bump("Protocol error: Expected control record");
1507 * We will go round this loop only once, unless we hit
1514 * If we get here, we must have seen SCP_SINK_FILE or
1520 if (sscanf(act
->buf
, "%lo %s %n", &act
->permissions
,
1522 bump("Protocol error: Illegal file descriptor format");
1523 act
->size
= uint64_from_decimal(sizestr
);
1524 act
->name
= act
->buf
+ i
;
1530 int scp_accept_filexfer(void)
1533 struct sftp_packet
*pktin
;
1534 struct sftp_request
*req
;
1536 req
= fxp_open_send(scp_sftp_currentname
, SSH_FXF_READ
, NULL
);
1537 pktin
= sftp_wait_for_reply(req
);
1538 scp_sftp_filehandle
= fxp_open_recv(pktin
, req
);
1540 if (!scp_sftp_filehandle
) {
1541 tell_user(stderr
, "pscp: unable to open %s: %s",
1542 scp_sftp_currentname
, fxp_error());
1546 scp_sftp_fileoffset
= uint64_make(0, 0);
1547 scp_sftp_xfer
= xfer_download_init(scp_sftp_filehandle
,
1548 scp_sftp_fileoffset
);
1549 sfree(scp_sftp_currentname
);
1552 back
->send(backhandle
, "", 1);
1553 return 0; /* can't fail */
1557 int scp_recv_filedata(char *data
, int len
)
1560 struct sftp_packet
*pktin
;
1564 xfer_download_queue(scp_sftp_xfer
);
1565 pktin
= sftp_recv();
1566 ret
= xfer_download_gotpkt(scp_sftp_xfer
, pktin
);
1568 tell_user(stderr
, "pscp: error while reading: %s", fxp_error());
1573 if (xfer_download_data(scp_sftp_xfer
, &vbuf
, &actuallen
)) {
1575 * This assertion relies on the fact that the natural
1576 * block size used in the xfer manager is at most that
1577 * used in this module. I don't like crossing layers in
1578 * this way, but it'll do for now.
1580 assert(actuallen
<= len
);
1581 memcpy(data
, vbuf
, actuallen
);
1586 scp_sftp_fileoffset
= uint64_add32(scp_sftp_fileoffset
, actuallen
);
1590 return ssh_scp_recv((unsigned char *) data
, len
);
1594 int scp_finish_filerecv(void)
1597 struct sftp_packet
*pktin
;
1598 struct sftp_request
*req
;
1601 * Ensure that xfer_done() will work correctly, so we can
1602 * clean up any outstanding requests from the file
1605 xfer_set_error(scp_sftp_xfer
);
1606 while (!xfer_done(scp_sftp_xfer
)) {
1610 pktin
= sftp_recv();
1611 ret
= xfer_download_gotpkt(scp_sftp_xfer
, pktin
);
1613 tell_user(stderr
, "pscp: error while reading: %s", fxp_error());
1617 if (xfer_download_data(scp_sftp_xfer
, &vbuf
, &len
))
1620 xfer_cleanup(scp_sftp_xfer
);
1622 req
= fxp_close_send(scp_sftp_filehandle
);
1623 pktin
= sftp_wait_for_reply(req
);
1624 fxp_close_recv(pktin
, req
);
1627 back
->send(backhandle
, "", 1);
1632 /* ----------------------------------------------------------------------
1633 * Send an error message to the other side and to the screen.
1634 * Increment error counter.
1636 static void run_err(const char *fmt
, ...)
1642 str
= dupvprintf(fmt
, ap
);
1643 str2
= dupcat("scp: ", str
, "\n", NULL
);
1645 scp_send_errmsg(str2
);
1646 tell_user(stderr
, "%s", str2
);
1652 * Execute the source part of the SCP protocol.
1654 static void source(char *src
)
1657 unsigned long mtime
, atime
;
1664 time_t stat_starttime
, stat_lasttime
;
1666 attr
= file_type(src
);
1667 if (attr
== FILE_TYPE_NONEXISTENT
||
1668 attr
== FILE_TYPE_WEIRD
) {
1669 run_err("%s: %s file or directory", src
,
1670 (attr
== FILE_TYPE_WEIRD ?
"Not a" : "No such"));
1674 if (attr
== FILE_TYPE_DIRECTORY
) {
1677 * Avoid . and .. directories.
1680 p
= strrchr(src
, '/');
1682 p
= strrchr(src
, '\\');
1687 if (!strcmp(p
, ".") || !strcmp(p
, ".."))
1688 /* skip . and .. */ ;
1692 run_err("%s: not a regular file", src
);
1697 if ((last
= strrchr(src
, '/')) == NULL
)
1701 if (strrchr(last
, '\\') != NULL
)
1702 last
= strrchr(last
, '\\') + 1;
1703 if (last
== src
&& strchr(src
, ':') != NULL
)
1704 last
= strchr(src
, ':') + 1;
1706 f
= open_existing_file(src
, &size
, &mtime
, &atime
, &permissions
);
1708 run_err("%s: Cannot open file", src
);
1712 if (scp_send_filetimes(mtime
, atime
))
1718 uint64_decimal(size
, sizestr
);
1719 tell_user(stderr
, "Sending file %s, size=%s", last
, sizestr
);
1721 if (scp_send_filename(last
, size
, permissions
))
1724 stat_bytes
= uint64_make(0,0);
1725 stat_starttime
= time(NULL
);
1728 for (i
= uint64_make(0,0);
1729 uint64_compare(i
,size
) < 0;
1730 i
= uint64_add32(i
,4096)) {
1731 char transbuf
[4096];
1734 if (uint64_compare(uint64_add32(i
, k
),size
) > 0) /* i + k > size */
1735 k
= (uint64_subtract(size
, i
)).lo
; /* k = size - i; */
1736 if ((j
= read_from_file(f
, transbuf
, k
)) != k
) {
1739 bump("%s: Read error", src
);
1741 if (scp_send_filedata(transbuf
, k
))
1742 bump("%s: Network error occurred", src
);
1745 stat_bytes
= uint64_add32(stat_bytes
, k
);
1746 if (time(NULL
) != stat_lasttime
||
1747 (uint64_compare(uint64_add32(i
, k
), size
) == 0)) {
1748 stat_lasttime
= time(NULL
);
1749 print_stats(last
, size
, stat_bytes
,
1750 stat_starttime
, stat_lasttime
);
1757 (void) scp_send_finish();
1761 * Recursively send the contents of a directory.
1763 static void rsource(char *src
)
1769 if ((last
= strrchr(src
, '/')) == NULL
)
1773 if (strrchr(last
, '\\') != NULL
)
1774 last
= strrchr(last
, '\\') + 1;
1775 if (last
== src
&& strchr(src
, ':') != NULL
)
1776 last
= strchr(src
, ':') + 1;
1778 /* maybe send filetime */
1780 save_target
= scp_save_remotepath();
1783 tell_user(stderr
, "Entering directory: %s", last
);
1784 if (scp_send_dirname(last
, 0755))
1787 dir
= open_directory(src
);
1790 while ((filename
= read_filename(dir
)) != NULL
) {
1791 char *foundfile
= dupcat(src
, "/", filename
, NULL
);
1797 close_directory(dir
);
1799 (void) scp_send_enddir();
1801 scp_restore_remotepath(save_target
);
1805 * Execute the sink part of the SCP protocol.
1807 static void sink(char *targ
, char *src
)
1817 time_t stat_starttime
, stat_lasttime
;
1820 attr
= file_type(targ
);
1821 if (attr
== FILE_TYPE_DIRECTORY
)
1824 if (targetshouldbedirectory
&& !targisdir
)
1825 bump("%s: Not a directory", targ
);
1829 struct scp_sink_action act
;
1830 if (scp_get_sink_action(&act
))
1833 if (act
.action
== SCP_SINK_ENDDIR
)
1836 if (act
.action
== SCP_SINK_RETRY
)
1841 * Prevent the remote side from maliciously writing to
1842 * files outside the target area by sending a filename
1843 * containing `../'. In fact, it shouldn't be sending
1844 * filenames with any slashes or colons in at all; so
1845 * we'll find the last slash, backslash or colon in the
1846 * filename and use only the part after that. (And
1849 * In addition, we also ensure here that if we're
1850 * copying a single file and the target is a directory
1851 * (common usage: `pscp host:filename .') the remote
1852 * can't send us a _different_ file name. We can
1853 * distinguish this case because `src' will be non-NULL
1854 * and the last component of that will fail to match
1855 * (the last component of) the name sent.
1857 * Well, not always; if `src' is a wildcard, we do
1858 * expect to get back filenames that don't correspond
1859 * exactly to it. Ideally in this case, we would like
1860 * to ensure that the returned filename actually
1861 * matches the wildcard pattern - but one of SCP's
1862 * protocol infelicities is that wildcard matching is
1863 * done at the server end _by the server's rules_ and
1864 * so in general this is infeasible. Hence, we only
1865 * accept filenames that don't correspond to `src' if
1866 * unsafe mode is enabled or we are using SFTP (which
1867 * resolves remote wildcards on the client side and can
1870 char *striptarget
, *stripsrc
;
1872 striptarget
= stripslashes(act
.name
, 1);
1873 if (striptarget
!= act
.name
) {
1874 tell_user(stderr
, "warning: remote host sent a compound"
1875 " pathname '%s'", act
.name
);
1876 tell_user(stderr
, " renaming local file to '%s'",
1881 * Also check to see if the target filename is '.' or
1882 * '..', or indeed '...' and so on because Windows
1883 * appears to interpret those like '..'.
1885 if (is_dots(striptarget
)) {
1886 bump("security violation: remote host attempted to write to"
1887 " a '.' or '..' path!");
1891 stripsrc
= stripslashes(src
, 1);
1892 if (strcmp(striptarget
, stripsrc
) &&
1893 !using_sftp
&& !scp_unsafe_mode
) {
1894 tell_user(stderr
, "warning: remote host tried to write "
1895 "to a file called '%s'", striptarget
);
1896 tell_user(stderr
, " when we requested a file "
1897 "called '%s'.", stripsrc
);
1898 tell_user(stderr
, " If this is a wildcard, "
1899 "consider upgrading to SSH-2 or using");
1900 tell_user(stderr
, " the '-unsafe' option. Renaming"
1901 " of this file has been disallowed.");
1902 /* Override the name the server provided with our own. */
1903 striptarget
= stripsrc
;
1907 if (targ
[0] != '\0')
1908 destfname
= dir_file_cat(targ
, striptarget
);
1910 destfname
= dupstr(striptarget
);
1913 * In this branch of the if, the target area is a
1914 * single file with an explicitly specified name in any
1915 * case, so there's no danger.
1917 destfname
= dupstr(targ
);
1919 attr
= file_type(destfname
);
1920 exists
= (attr
!= FILE_TYPE_NONEXISTENT
);
1922 if (act
.action
== SCP_SINK_DIR
) {
1923 if (exists
&& attr
!= FILE_TYPE_DIRECTORY
) {
1924 run_err("%s: Not a directory", destfname
);
1928 if (!create_directory(destfname
)) {
1929 run_err("%s: Cannot create directory", destfname
);
1933 sink(destfname
, NULL
);
1934 /* can we set the timestamp for directories ? */
1938 f
= open_new_file(destfname
, act
.permissions
);
1940 run_err("%s: Cannot create file", destfname
);
1944 if (scp_accept_filexfer())
1947 stat_bytes
= uint64_make(0, 0);
1948 stat_starttime
= time(NULL
);
1950 stat_name
= stripslashes(destfname
, 1);
1952 received
= uint64_make(0, 0);
1953 while (uint64_compare(received
,act
.size
) < 0) {
1954 char transbuf
[32768];
1957 blksize
= uint64_make(0, 32768);
1958 if (uint64_compare(blksize
,uint64_subtract(act
.size
,received
)) > 0)
1959 blksize
= uint64_subtract(act
.size
,received
);
1960 read
= scp_recv_filedata(transbuf
, (int)blksize
.lo
);
1962 bump("Lost connection");
1965 if (write_to_file(f
, transbuf
, read
) != (int)read
) {
1967 /* FIXME: in sftp we can actually abort the transfer */
1969 printf("\r%-25.25s | %50s\n",
1971 "Write error.. waiting for end of file");
1975 stat_bytes
= uint64_add32(stat_bytes
,read
);
1976 if (time(NULL
) > stat_lasttime
||
1977 uint64_compare(uint64_add32(received
, read
), act
.size
) == 0) {
1978 stat_lasttime
= time(NULL
);
1979 print_stats(stat_name
, act
.size
, stat_bytes
,
1980 stat_starttime
, stat_lasttime
);
1983 received
= uint64_add32(received
, read
);
1986 set_file_times(f
, act
.mtime
, act
.atime
);
1991 run_err("%s: Write error", destfname
);
1994 (void) scp_finish_filerecv();
2001 * We will copy local files to a remote server.
2003 static void toremote(int argc
, char *argv
[])
2005 char *src
, *targ
, *host
, *user
;
2009 targ
= argv
[argc
- 1];
2011 /* Separate host from filename */
2015 bump("targ == NULL in toremote()");
2019 /* Substitute "." for empty target */
2021 /* Separate host and username */
2023 host
= strrchr(host
, '@');
2034 if (colon(argv
[0]) != NULL
)
2035 bump("%s: Remote to remote not supported", argv
[0]);
2037 wc_type
= test_wildcard(argv
[0], 1);
2038 if (wc_type
== WCTYPE_NONEXISTENT
)
2039 bump("%s: No such file or directory\n", argv
[0]);
2040 else if (wc_type
== WCTYPE_WILDCARD
)
2041 targetshouldbedirectory
= 1;
2044 cmd
= dupprintf("scp%s%s%s%s -t %s",
2045 verbose ?
" -v" : "",
2046 recursive ?
" -r" : "",
2047 preserve ?
" -p" : "",
2048 targetshouldbedirectory ?
" -d" : "", targ
);
2049 do_cmd(host
, user
, cmd
);
2052 if (scp_source_setup(targ
, targetshouldbedirectory
))
2055 for (i
= 0; i
< argc
- 1; i
++) {
2057 if (colon(src
) != NULL
) {
2058 tell_user(stderr
, "%s: Remote to remote not supported\n", src
);
2063 wc_type
= test_wildcard(src
, 1);
2064 if (wc_type
== WCTYPE_NONEXISTENT
) {
2065 run_err("%s: No such file or directory", src
);
2067 } else if (wc_type
== WCTYPE_FILENAME
) {
2071 WildcardMatcher
*wc
;
2074 wc
= begin_wildcard_matching(src
);
2076 run_err("%s: No such file or directory", src
);
2080 while ((filename
= wildcard_get_filename(wc
)) != NULL
) {
2085 finish_wildcard_matching(wc
);
2091 * We will copy files from a remote server to the local machine.
2093 static void tolocal(int argc
, char *argv
[])
2095 char *src
, *targ
, *host
, *user
;
2099 bump("More than one remote source not supported");
2104 /* Separate host from filename */
2108 bump("Local to local copy not supported");
2112 /* Substitute "." for empty filename */
2114 /* Separate username and hostname */
2116 host
= strrchr(host
, '@');
2126 cmd
= dupprintf("scp%s%s%s%s -f %s",
2127 verbose ?
" -v" : "",
2128 recursive ?
" -r" : "",
2129 preserve ?
" -p" : "",
2130 targetshouldbedirectory ?
" -d" : "", src
);
2131 do_cmd(host
, user
, cmd
);
2134 if (scp_sink_setup(src
, preserve
, recursive
))
2141 * We will issue a list command to get a remote directory.
2143 static void get_dir_list(int argc
, char *argv
[])
2145 char *src
, *host
, *user
;
2151 /* Separate host from filename */
2155 bump("Local file listing not supported");
2159 /* Substitute "." for empty filename */
2161 /* Separate username and hostname */
2163 host
= strrchr(host
, '@');
2173 cmd
= snewn(4 * strlen(src
) + 100, char);
2174 strcpy(cmd
, "ls -la '");
2175 p
= cmd
+ strlen(cmd
);
2176 for (q
= src
; *q
; q
++) {
2189 do_cmd(host
, user
, cmd
);
2193 scp_sftp_listdir(src
);
2195 while (ssh_scp_recv((unsigned char *) &c
, 1) > 0)
2196 tell_char(stdout
, c
);
2201 * Short description of parameters.
2203 static void usage(void)
2205 printf("PuTTY Secure Copy client\n");
2206 printf("%s\n", ver
);
2207 printf("Usage: pscp [options] [user@]host:source target\n");
2209 (" pscp [options] source [source...] [user@]host:target\n");
2210 printf(" pscp [options] -ls [user@]host:filespec\n");
2211 printf("Options:\n");
2212 printf(" -V print version information and exit\n");
2213 printf(" -pgpfp print PGP key fingerprints and exit\n");
2214 printf(" -p preserve file attributes\n");
2215 printf(" -q quiet, don't show statistics\n");
2216 printf(" -r copy directories recursively\n");
2217 printf(" -v show verbose messages\n");
2218 printf(" -load sessname Load settings from saved session\n");
2219 printf(" -P port connect to specified port\n");
2220 printf(" -l user connect with specified username\n");
2221 printf(" -pw passw login with specified password\n");
2222 printf(" -1 -2 force use of particular SSH protocol version\n");
2223 printf(" -4 -6 force use of IPv4 or IPv6\n");
2224 printf(" -C enable compression\n");
2225 printf(" -i key private key file for authentication\n");
2226 printf(" -noagent disable use of Pageant\n");
2227 printf(" -agent enable use of Pageant\n");
2228 printf(" -batch disable all interactive prompts\n");
2229 printf(" -unsafe allow server-side wildcards (DANGEROUS)\n");
2230 printf(" -sftp force use of SFTP protocol\n");
2231 printf(" -scp force use of SCP protocol\n");
2234 * -gui is an internal option, used by GUI front ends to get
2235 * pscp to pass progress reports back to them. It's not an
2236 * ordinary user-accessible option, so it shouldn't be part of
2237 * the command-line help. The only people who need to know
2238 * about it are programmers, and they can read the source.
2241 (" -gui hWnd GUI mode with the windows handle for receiving messages\n");
2248 printf("pscp: %s\n", ver
);
2252 void cmdline_error(char *p
, ...)
2255 fprintf(stderr
, "pscp: ");
2257 vfprintf(stderr
, p
, ap
);
2259 fprintf(stderr
, "\n try typing just \"pscp\" for help\n");
2264 * Main program. (Called `psftp_main' because it gets called from
2265 * *sftp.c; bit silly, I know, but it had to be called _something_.)
2267 int psftp_main(int argc
, char *argv
[])
2271 default_protocol
= PROT_TELNET
;
2274 #ifdef FLAG_SYNCAGENT
2278 cmdline_tooltype
= TOOLTYPE_FILETRANSFER
;
2281 /* Load Default Settings before doing anything else. */
2283 do_defaults(NULL
, conf
);
2284 loaded_session
= FALSE
;
2286 for (i
= 1; i
< argc
; i
++) {
2288 if (argv
[i
][0] != '-')
2290 ret
= cmdline_process_param(argv
[i
], i
+1<argc?argv
[i
+1]:NULL
, 1, conf
);
2292 cmdline_error("option \"%s\" requires an argument", argv
[i
]);
2293 } else if (ret
== 2) {
2294 i
++; /* skip next argument */
2295 } else if (ret
== 1) {
2296 /* We have our own verbosity in addition to `flags'. */
2297 if (flags
& FLAG_VERBOSE
)
2299 } else if (strcmp(argv
[i
], "-pgpfp") == 0) {
2302 } else if (strcmp(argv
[i
], "-r") == 0) {
2304 } else if (strcmp(argv
[i
], "-p") == 0) {
2306 } else if (strcmp(argv
[i
], "-q") == 0) {
2308 } else if (strcmp(argv
[i
], "-h") == 0 ||
2309 strcmp(argv
[i
], "-?") == 0 ||
2310 strcmp(argv
[i
], "--help") == 0) {
2312 } else if (strcmp(argv
[i
], "-V") == 0 ||
2313 strcmp(argv
[i
], "--version") == 0) {
2315 } else if (strcmp(argv
[i
], "-ls") == 0) {
2317 } else if (strcmp(argv
[i
], "-batch") == 0) {
2318 console_batch_mode
= 1;
2319 } else if (strcmp(argv
[i
], "-unsafe") == 0) {
2320 scp_unsafe_mode
= 1;
2321 } else if (strcmp(argv
[i
], "-sftp") == 0) {
2322 try_scp
= 0; try_sftp
= 1;
2323 } else if (strcmp(argv
[i
], "-scp") == 0) {
2324 try_scp
= 1; try_sftp
= 0;
2325 } else if (strcmp(argv
[i
], "--") == 0) {
2329 cmdline_error("unknown option \"%s\"", argv
[i
]);
2339 get_dir_list(argc
, argv
);
2346 targetshouldbedirectory
= 1;
2348 if (colon(argv
[argc
- 1]) != NULL
)
2349 toremote(argc
, argv
);
2351 tolocal(argc
, argv
);
2354 if (back
!= NULL
&& back
->connected(backhandle
)) {
2356 back
->special(backhandle
, TS_EOF
);
2358 ssh_scp_recv((unsigned char *) &ch
, 1);
2363 console_provide_logctx(NULL
);
2364 back
->free(backhandle
);
2368 return (errs
== 0 ?
0 : 1);