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 nonfatal(char *fmt
, ...)
137 str
= dupvprintf(fmt
, ap
);
138 str2
= dupcat("Error: ", str
, "\n", NULL
);
141 tell_str(stderr
, str2
);
145 void connection_fatal(void *frontend
, char *fmt
, ...)
150 str
= dupvprintf(fmt
, ap
);
151 str2
= dupcat("Fatal: ", str
, "\n", NULL
);
154 tell_str(stderr
, str2
);
162 * In pscp, all agent requests should be synchronous, so this is a
165 void agent_schedule_callback(void (*callback
)(void *, void *, int),
166 void *callback_ctx
, void *data
, int len
)
168 assert(!"We shouldn't be here");
172 * Receive a block of data from the SSH link. Block until all data
175 * To do this, we repeatedly call the SSH protocol module, with our
176 * own trap in from_backend() to catch the data that comes back. We
177 * do this until we have enough data.
180 static unsigned char *outptr
; /* where to put the data */
181 static unsigned outlen
; /* how much data required */
182 static unsigned char *pending
= NULL
; /* any spare data */
183 static unsigned pendlen
= 0, pendsize
= 0; /* length and phys. size of buffer */
184 int from_backend(void *frontend
, int is_stderr
, const char *data
, int datalen
)
186 unsigned char *p
= (unsigned char *) data
;
187 unsigned len
= (unsigned) datalen
;
190 * stderr data is just spouted to local stderr and otherwise
195 if (fwrite(data
, 1, len
, stderr
) < len
)
200 if ((outlen
> 0) && (len
> 0)) {
201 unsigned used
= outlen
;
204 memcpy(outptr
, p
, used
);
212 if (pendsize
< pendlen
+ len
) {
213 pendsize
= pendlen
+ len
+ 4096;
214 pending
= sresize(pending
, pendsize
, unsigned char);
216 memcpy(pending
+ pendlen
, p
, len
);
222 int from_backend_untrusted(void *frontend_handle
, const char *data
, int len
)
225 * No "untrusted" output should get here (the way the code is
226 * currently, it's all diverted by FLAG_STDERR).
228 assert(!"Unexpected call to from_backend_untrusted()");
229 return 0; /* not reached */
231 int from_backend_eof(void *frontend
)
234 * We expect to be the party deciding when to close the
235 * connection, so if we see EOF before we sent it ourselves, we
239 connection_fatal(frontend
,
240 "Received unexpected end-of-file from server");
244 static int ssh_scp_recv(unsigned char *buf
, int len
)
250 * See if the pending-input block contains some of what we
254 unsigned pendused
= pendlen
;
255 if (pendused
> outlen
)
257 memcpy(outptr
, pending
, pendused
);
258 memmove(pending
, pending
+ pendused
, pendlen
- pendused
);
272 if (back
->exitcode(backhandle
) >= 0 || ssh_sftp_loop_iteration() < 0)
280 * Loop through the ssh connection and authentication process.
282 static void ssh_scp_init(void)
284 while (!back
->sendok(backhandle
)) {
285 if (back
->exitcode(backhandle
) >= 0) {
289 if (ssh_sftp_loop_iteration() < 0) {
295 /* Work out which backend we ended up using. */
296 if (!ssh_fallback_cmd(backhandle
))
297 using_sftp
= main_cmd_is_sftp
;
299 using_sftp
= fallback_cmd_is_sftp
;
303 tell_user(stderr
, "Using SFTP");
305 tell_user(stderr
, "Using SCP1");
310 * Print an error message and exit after closing the SSH link.
312 static void bump(char *fmt
, ...)
317 str
= dupvprintf(fmt
, ap
);
319 str2
= dupcat(str
, "\n", NULL
);
321 tell_str(stderr
, str2
);
325 if (back
!= NULL
&& back
->connected(backhandle
)) {
327 back
->special(backhandle
, TS_EOF
);
329 ssh_scp_recv((unsigned char *) &ch
, 1);
336 * Wait for the reply to a single SFTP request. Parallels the same
337 * function in psftp.c (but isn't centralised into sftp.c because the
338 * latter module handles SFTP only and shouldn't assume that SFTP is
339 * the only thing going on by calling connection_fatal).
341 struct sftp_packet
*sftp_wait_for_reply(struct sftp_request
*req
)
343 struct sftp_packet
*pktin
;
344 struct sftp_request
*rreq
;
349 connection_fatal(NULL
, "did not receive SFTP response packet "
351 rreq
= sftp_find_request(pktin
);
353 connection_fatal(NULL
, "unable to understand SFTP response packet "
354 "from server: %s", fxp_error());
359 * Open an SSH connection to user@host and execute cmd.
361 static void do_cmd(char *host
, char *user
, char *cmd
)
367 if (host
== NULL
|| host
[0] == '\0')
368 bump("Empty host name");
371 * Remove fiddly bits of address: remove a colon suffix, and
372 * the square brackets around an IPv6 literal address.
374 if (host
[0] == '[') {
376 host
[strcspn(host
, "]")] = '\0';
378 host
[strcspn(host
, ":")] = '\0';
382 * If we haven't loaded session details already (e.g., from -load),
383 * try looking for a session called "host".
385 if (!loaded_session
) {
386 /* Try to load settings for `host' into a temporary config */
387 Conf
*conf2
= conf_new();
388 conf_set_str(conf2
, CONF_host
, "");
389 do_defaults(host
, conf2
);
390 if (conf_get_str(conf2
, CONF_host
)[0] != '\0') {
391 /* Settings present and include hostname */
392 /* Re-load data into the real config. */
393 do_defaults(host
, conf
);
395 /* Session doesn't exist or mention a hostname. */
396 /* Use `host' as a bare hostname. */
397 conf_set_str(conf
, CONF_host
, host
);
400 /* Patch in hostname `host' to session details. */
401 conf_set_str(conf
, CONF_host
, host
);
405 * Force use of SSH. (If they got the protocol wrong we assume the
406 * port is useless too.)
408 if (conf_get_int(conf
, CONF_protocol
) != PROT_SSH
) {
409 conf_set_int(conf
, CONF_protocol
, PROT_SSH
);
410 conf_set_int(conf
, CONF_port
, 22);
414 * Enact command-line overrides.
416 cmdline_run_saved(conf
);
419 * Muck about with the hostname in various ways.
422 char *hostbuf
= dupstr(conf_get_str(conf
, CONF_host
));
423 char *host
= hostbuf
;
427 * Trim leading whitespace.
429 host
+= strspn(host
, " \t");
432 * See if host is of the form user@host, and separate out
433 * the username if so.
435 if (host
[0] != '\0') {
436 char *atsign
= strrchr(host
, '@');
439 conf_set_str(conf
, CONF_username
, host
);
445 * Remove any remaining whitespace.
450 if (*q
!= ' ' && *q
!= '\t')
456 conf_set_str(conf
, CONF_host
, hostbuf
);
461 if (user
!= NULL
&& user
[0] != '\0') {
462 conf_set_str(conf
, CONF_username
, user
);
463 } else if (conf_get_str(conf
, CONF_username
)[0] == '\0') {
464 user
= get_username();
466 bump("Empty user name");
469 tell_user(stderr
, "Guessing user name: %s", user
);
470 conf_set_str(conf
, CONF_username
, user
);
476 * Disable scary things which shouldn't be enabled for simple
477 * things like SCP and SFTP: agent forwarding, port forwarding,
480 conf_set_int(conf
, CONF_x11_forward
, 0);
481 conf_set_int(conf
, CONF_agentfwd
, 0);
482 conf_set_int(conf
, CONF_ssh_simple
, TRUE
);
485 while ((key
= conf_get_str_nthstrkey(conf
, CONF_portfwd
, 0)) != NULL
)
486 conf_del_str_str(conf
, CONF_portfwd
, key
);
490 * Set up main and possibly fallback command depending on
491 * options specified by user.
492 * Attempt to start the SFTP subsystem as a first choice,
493 * falling back to the provided scp command if that fails.
495 conf_set_str(conf
, CONF_remote_cmd2
, "");
497 /* First choice is SFTP subsystem. */
498 main_cmd_is_sftp
= 1;
499 conf_set_str(conf
, CONF_remote_cmd
, "sftp");
500 conf_set_int(conf
, CONF_ssh_subsys
, TRUE
);
502 /* Fallback is to use the provided scp command. */
503 fallback_cmd_is_sftp
= 0;
504 conf_set_str(conf
, CONF_remote_cmd2
, cmd
);
505 conf_set_int(conf
, CONF_ssh_subsys2
, FALSE
);
507 /* Since we're not going to try SCP, we may as well try
508 * harder to find an SFTP server, since in the current
509 * implementation we have a spare slot. */
510 fallback_cmd_is_sftp
= 1;
511 /* see psftp.c for full explanation of this kludge */
512 conf_set_str(conf
, CONF_remote_cmd2
,
513 "test -x /usr/lib/sftp-server &&"
514 " exec /usr/lib/sftp-server\n"
515 "test -x /usr/local/lib/sftp-server &&"
516 " exec /usr/local/lib/sftp-server\n"
518 conf_set_int(conf
, CONF_ssh_subsys2
, FALSE
);
521 /* Don't try SFTP at all; just try the scp command. */
522 main_cmd_is_sftp
= 0;
523 conf_set_str(conf
, CONF_remote_cmd
, cmd
);
524 conf_set_int(conf
, CONF_ssh_subsys
, FALSE
);
526 conf_set_int(conf
, CONF_nopty
, TRUE
);
530 err
= back
->init(NULL
, &backhandle
, conf
,
531 conf_get_str(conf
, CONF_host
),
532 conf_get_int(conf
, CONF_port
),
534 conf_get_int(conf
, CONF_tcp_keepalives
));
536 bump("ssh_init: %s", err
);
537 logctx
= log_init(NULL
, conf
);
538 back
->provide_logctx(backhandle
, logctx
);
539 console_provide_logctx(logctx
);
541 if (verbose
&& realhost
!= NULL
&& errs
== 0)
542 tell_user(stderr
, "Connected to %s", realhost
);
547 * Update statistic information about current file.
549 static void print_stats(char *name
, uint64 size
, uint64 done
,
550 time_t start
, time_t now
)
561 elap
= (unsigned long) difftime(now
, start
);
564 ratebs
= (float) (uint64_to_double(done
) / elap
);
566 ratebs
= (float) uint64_to_double(done
);
569 eta
= (unsigned long) (uint64_to_double(uint64_subtract(size
, done
)));
571 eta
= (unsigned long)
572 ((uint64_to_double(uint64_subtract(size
, done
)) / ratebs
));
575 etastr
= dupprintf("%02ld:%02ld:%02ld",
576 eta
/ 3600, (eta
% 3600) / 60, eta
% 60);
578 donedbl
= uint64_to_double(done
);
579 sizedbl
= uint64_to_double(size
);
580 pct
= (int) (100 * (donedbl
* 1.0 / sizedbl
));
584 /* divide by 1024 to provide kB */
585 uint64_decimal(uint64_shift_right(done
, 10), donekb
);
586 len
= printf("\r%-25.25s | %s kB | %5.1f kB/s | ETA: %8s | %3d%%",
588 donekb
, ratebs
/ 1024.0, etastr
, pct
);
589 if (len
< prev_stats_len
)
590 printf("%*s", prev_stats_len
- len
, "");
591 prev_stats_len
= len
;
593 if (uint64_compare(done
, size
) == 0)
603 * Find a colon in str and return a pointer to the colon.
604 * This is used to separate hostname from filename.
606 static char *colon(char *str
)
608 /* We ignore a leading colon, since the hostname cannot be
609 empty. We also ignore a colon as second character because
610 of filenames like f:myfile.txt. */
611 if (str
[0] == '\0' || str
[0] == ':' ||
612 (str
[0] != '[' && str
[1] == ':'))
614 while (*str
!= '\0' && *str
!= ':' && *str
!= '/' && *str
!= '\\') {
616 /* Skip over IPv6 literal addresses
617 * (eg: 'jeroen@[2001:db8::1]:myfile.txt') */
618 char *ipv6_end
= strchr(str
, ']');
632 * Return a pointer to the portion of str that comes after the last
633 * slash (or backslash or colon, if `local' is TRUE).
635 static char *stripslashes(char *str
, int local
)
640 p
= strchr(str
, ':');
644 p
= strrchr(str
, '/');
648 p
= strrchr(str
, '\\');
656 * Determine whether a string is entirely composed of dots.
658 static int is_dots(char *str
)
660 return str
[strspn(str
, ".")] == '\0';
664 * Wait for a response from the other side.
665 * Return 0 if ok, -1 if error.
667 static int response(void)
669 char ch
, resp
, rbuf
[2048];
672 if (ssh_scp_recv((unsigned char *) &resp
, 1) <= 0)
673 bump("Lost connection");
683 case 2: /* fatal error */
685 if (ssh_scp_recv((unsigned char *) &ch
, 1) <= 0)
686 bump("Protocol error: Lost connection");
688 } while (p
< sizeof(rbuf
) && ch
!= '\n');
691 tell_user(stderr
, "%s", rbuf
);
699 int sftp_recvdata(char *buf
, int len
)
701 return ssh_scp_recv((unsigned char *) buf
, len
);
703 int sftp_senddata(char *buf
, int len
)
705 back
->send(backhandle
, buf
, len
);
709 /* ----------------------------------------------------------------------
710 * sftp-based replacement for the hacky `pscp -ls'.
712 static int sftp_ls_compare(const void *av
, const void *bv
)
714 const struct fxp_name
*a
= (const struct fxp_name
*) av
;
715 const struct fxp_name
*b
= (const struct fxp_name
*) bv
;
716 return strcmp(a
->filename
, b
->filename
);
718 void scp_sftp_listdir(char *dirname
)
720 struct fxp_handle
*dirh
;
721 struct fxp_names
*names
;
722 struct fxp_name
*ournames
;
723 struct sftp_packet
*pktin
;
724 struct sftp_request
*req
;
725 int nnames
, namesize
;
729 tell_user(stderr
, "unable to initialise SFTP: %s", fxp_error());
734 printf("Listing directory %s\n", dirname
);
736 req
= fxp_opendir_send(dirname
);
737 pktin
= sftp_wait_for_reply(req
);
738 dirh
= fxp_opendir_recv(pktin
, req
);
741 printf("Unable to open %s: %s\n", dirname
, fxp_error());
743 nnames
= namesize
= 0;
748 req
= fxp_readdir_send(dirh
);
749 pktin
= sftp_wait_for_reply(req
);
750 names
= fxp_readdir_recv(pktin
, req
);
753 if (fxp_error_type() == SSH_FX_EOF
)
755 printf("Reading directory %s: %s\n", dirname
, fxp_error());
758 if (names
->nnames
== 0) {
759 fxp_free_names(names
);
763 if (nnames
+ names
->nnames
>= namesize
) {
764 namesize
+= names
->nnames
+ 128;
765 ournames
= sresize(ournames
, namesize
, struct fxp_name
);
768 for (i
= 0; i
< names
->nnames
; i
++)
769 ournames
[nnames
++] = names
->names
[i
];
770 names
->nnames
= 0; /* prevent free_names */
771 fxp_free_names(names
);
773 req
= fxp_close_send(dirh
);
774 pktin
= sftp_wait_for_reply(req
);
775 fxp_close_recv(pktin
, req
);
778 * Now we have our filenames. Sort them by actual file
779 * name, and then output the longname parts.
782 qsort(ournames
, nnames
, sizeof(*ournames
), sftp_ls_compare
);
787 for (i
= 0; i
< nnames
; i
++)
788 printf("%s\n", ournames
[i
].longname
);
794 /* ----------------------------------------------------------------------
795 * Helper routines that contain the actual SCP protocol elements,
796 * implemented both as SCP1 and SFTP.
799 static struct scp_sftp_dirstack
{
800 struct scp_sftp_dirstack
*next
;
801 struct fxp_name
*names
;
802 int namepos
, namelen
;
805 int matched_something
; /* wildcard match set was non-empty */
806 } *scp_sftp_dirstack_head
;
807 static char *scp_sftp_remotepath
, *scp_sftp_currentname
;
808 static char *scp_sftp_wildcard
;
809 static int scp_sftp_targetisdir
, scp_sftp_donethistarget
;
810 static int scp_sftp_preserve
, scp_sftp_recursive
;
811 static unsigned long scp_sftp_mtime
, scp_sftp_atime
;
812 static int scp_has_times
;
813 static struct fxp_handle
*scp_sftp_filehandle
;
814 static struct fxp_xfer
*scp_sftp_xfer
;
815 static uint64 scp_sftp_fileoffset
;
817 int scp_source_setup(char *target
, int shouldbedir
)
821 * Find out whether the target filespec is in fact a
824 struct sftp_packet
*pktin
;
825 struct sftp_request
*req
;
826 struct fxp_attrs attrs
;
830 tell_user(stderr
, "unable to initialise SFTP: %s", fxp_error());
835 req
= fxp_stat_send(target
);
836 pktin
= sftp_wait_for_reply(req
);
837 ret
= fxp_stat_recv(pktin
, req
, &attrs
);
839 if (!ret
|| !(attrs
.flags
& SSH_FILEXFER_ATTR_PERMISSIONS
))
840 scp_sftp_targetisdir
= 0;
842 scp_sftp_targetisdir
= (attrs
.permissions
& 0040000) != 0;
844 if (shouldbedir
&& !scp_sftp_targetisdir
) {
845 bump("pscp: remote filespec %s: not a directory\n", target
);
848 scp_sftp_remotepath
= dupstr(target
);
857 int scp_send_errmsg(char *str
)
860 /* do nothing; we never need to send our errors to the server */
862 back
->send(backhandle
, "\001", 1);/* scp protocol error prefix */
863 back
->send(backhandle
, str
, strlen(str
));
865 return 0; /* can't fail */
868 int scp_send_filetimes(unsigned long mtime
, unsigned long atime
)
871 scp_sftp_mtime
= mtime
;
872 scp_sftp_atime
= atime
;
877 sprintf(buf
, "T%lu 0 %lu 0\n", mtime
, atime
);
878 back
->send(backhandle
, buf
, strlen(buf
));
883 int scp_send_filename(char *name
, uint64 size
, int permissions
)
887 struct sftp_packet
*pktin
;
888 struct sftp_request
*req
;
889 struct fxp_attrs attrs
;
891 if (scp_sftp_targetisdir
) {
892 fullname
= dupcat(scp_sftp_remotepath
, "/", name
, NULL
);
894 fullname
= dupstr(scp_sftp_remotepath
);
898 PUT_PERMISSIONS(attrs
, permissions
);
900 req
= fxp_open_send(fullname
,
901 SSH_FXF_WRITE
| SSH_FXF_CREAT
| SSH_FXF_TRUNC
,
903 pktin
= sftp_wait_for_reply(req
);
904 scp_sftp_filehandle
= fxp_open_recv(pktin
, req
);
906 if (!scp_sftp_filehandle
) {
907 tell_user(stderr
, "pscp: unable to open %s: %s",
908 fullname
, fxp_error());
913 scp_sftp_fileoffset
= uint64_make(0, 0);
914 scp_sftp_xfer
= xfer_upload_init(scp_sftp_filehandle
,
915 scp_sftp_fileoffset
);
921 uint64_decimal(size
, sizestr
);
924 sprintf(buf
, "C%04o %s ", (int)(permissions
& 07777), sizestr
);
925 back
->send(backhandle
, buf
, strlen(buf
));
926 back
->send(backhandle
, name
, strlen(name
));
927 back
->send(backhandle
, "\n", 1);
932 int scp_send_filedata(char *data
, int len
)
936 struct sftp_packet
*pktin
;
938 if (!scp_sftp_filehandle
) {
942 while (!xfer_upload_ready(scp_sftp_xfer
)) {
944 ret
= xfer_upload_gotpkt(scp_sftp_xfer
, pktin
);
946 tell_user(stderr
, "error while writing: %s", fxp_error());
947 if (ret
== INT_MIN
) /* pktin not even freed */
954 xfer_upload_data(scp_sftp_xfer
, data
, len
);
956 scp_sftp_fileoffset
= uint64_add32(scp_sftp_fileoffset
, len
);
959 int bufsize
= back
->send(backhandle
, data
, len
);
962 * If the network transfer is backing up - that is, the
963 * remote site is not accepting data as fast as we can
964 * produce it - then we must loop on network events until
965 * we have space in the buffer again.
967 while (bufsize
> MAX_SCP_BUFSIZE
) {
968 if (ssh_sftp_loop_iteration() < 0)
970 bufsize
= back
->sendbuffer(backhandle
);
977 int scp_send_finish(void)
980 struct fxp_attrs attrs
;
981 struct sftp_packet
*pktin
;
982 struct sftp_request
*req
;
985 while (!xfer_done(scp_sftp_xfer
)) {
987 ret
= xfer_upload_gotpkt(scp_sftp_xfer
, pktin
);
989 tell_user(stderr
, "error while writing: %s", fxp_error());
990 if (ret
== INT_MIN
) /* pktin not even freed */
996 xfer_cleanup(scp_sftp_xfer
);
998 if (!scp_sftp_filehandle
) {
1001 if (scp_has_times
) {
1002 attrs
.flags
= SSH_FILEXFER_ATTR_ACMODTIME
;
1003 attrs
.atime
= scp_sftp_atime
;
1004 attrs
.mtime
= scp_sftp_mtime
;
1005 req
= fxp_fsetstat_send(scp_sftp_filehandle
, attrs
);
1006 pktin
= sftp_wait_for_reply(req
);
1007 ret
= fxp_fsetstat_recv(pktin
, req
);
1009 tell_user(stderr
, "unable to set file times: %s", fxp_error());
1013 req
= fxp_close_send(scp_sftp_filehandle
);
1014 pktin
= sftp_wait_for_reply(req
);
1015 fxp_close_recv(pktin
, req
);
1019 back
->send(backhandle
, "", 1);
1024 char *scp_save_remotepath(void)
1027 return scp_sftp_remotepath
;
1032 void scp_restore_remotepath(char *data
)
1035 scp_sftp_remotepath
= data
;
1038 int scp_send_dirname(char *name
, int modes
)
1043 struct fxp_attrs attrs
;
1044 struct sftp_packet
*pktin
;
1045 struct sftp_request
*req
;
1048 if (scp_sftp_targetisdir
) {
1049 fullname
= dupcat(scp_sftp_remotepath
, "/", name
, NULL
);
1051 fullname
= dupstr(scp_sftp_remotepath
);
1055 * We don't worry about whether we managed to create the
1056 * directory, because if it exists already it's OK just to
1057 * use it. Instead, we will stat it afterwards, and if it
1058 * exists and is a directory we will assume we were either
1059 * successful or it didn't matter.
1061 req
= fxp_mkdir_send(fullname
);
1062 pktin
= sftp_wait_for_reply(req
);
1063 ret
= fxp_mkdir_recv(pktin
, req
);
1068 err
= "server reported no error";
1070 req
= fxp_stat_send(fullname
);
1071 pktin
= sftp_wait_for_reply(req
);
1072 ret
= fxp_stat_recv(pktin
, req
, &attrs
);
1074 if (!ret
|| !(attrs
.flags
& SSH_FILEXFER_ATTR_PERMISSIONS
) ||
1075 !(attrs
.permissions
& 0040000)) {
1076 tell_user(stderr
, "unable to create directory %s: %s",
1083 scp_sftp_remotepath
= fullname
;
1088 sprintf(buf
, "D%04o 0 ", modes
);
1089 back
->send(backhandle
, buf
, strlen(buf
));
1090 back
->send(backhandle
, name
, strlen(name
));
1091 back
->send(backhandle
, "\n", 1);
1096 int scp_send_enddir(void)
1099 sfree(scp_sftp_remotepath
);
1102 back
->send(backhandle
, "E\n", 2);
1108 * Yes, I know; I have an scp_sink_setup _and_ an scp_sink_init.
1109 * That's bad. The difference is that scp_sink_setup is called once
1110 * right at the start, whereas scp_sink_init is called to
1111 * initialise every level of recursion in the protocol.
1113 int scp_sink_setup(char *source
, int preserve
, int recursive
)
1119 tell_user(stderr
, "unable to initialise SFTP: %s", fxp_error());
1124 * It's possible that the source string we've been given
1125 * contains a wildcard. If so, we must split the directory
1126 * away from the wildcard itself (throwing an error if any
1127 * wildcardness comes before the final slash) and arrange
1128 * things so that a dirstack entry will be set up.
1130 newsource
= snewn(1+strlen(source
), char);
1131 if (!wc_unescape(newsource
, source
)) {
1132 /* Yes, here we go; it's a wildcard. Bah. */
1133 char *dupsource
, *lastpart
, *dirpart
, *wildcard
;
1137 dupsource
= dupstr(source
);
1138 lastpart
= stripslashes(dupsource
, 0);
1139 wildcard
= dupstr(lastpart
);
1141 if (*dupsource
&& dupsource
[1]) {
1143 * The remains of dupsource are at least two
1144 * characters long, meaning the pathname wasn't
1145 * empty or just `/'. Hence, we remove the trailing
1148 lastpart
[-1] = '\0';
1149 } else if (!*dupsource
) {
1151 * The remains of dupsource are _empty_ - the whole
1152 * pathname was a wildcard. Hence we need to
1153 * replace it with ".".
1156 dupsource
= dupstr(".");
1160 * Now we have separated our string into dupsource (the
1161 * directory part) and wildcard. Both of these will
1162 * need freeing at some point. Next step is to remove
1163 * wildcard escapes from the directory part, throwing
1164 * an error if it contains a real wildcard.
1166 dirpart
= snewn(1+strlen(dupsource
), char);
1167 if (!wc_unescape(dirpart
, dupsource
)) {
1168 tell_user(stderr
, "%s: multiple-level wildcards unsupported",
1178 * Now we have dirpart (unescaped, ie a valid remote
1179 * path), and wildcard (a wildcard). This will be
1180 * sufficient to arrange a dirstack entry.
1182 scp_sftp_remotepath
= dirpart
;
1183 scp_sftp_wildcard
= wildcard
;
1186 scp_sftp_remotepath
= newsource
;
1187 scp_sftp_wildcard
= NULL
;
1189 scp_sftp_preserve
= preserve
;
1190 scp_sftp_recursive
= recursive
;
1191 scp_sftp_donethistarget
= 0;
1192 scp_sftp_dirstack_head
= NULL
;
1197 int scp_sink_init(void)
1200 back
->send(backhandle
, "", 1);
1205 #define SCP_SINK_FILE 1
1206 #define SCP_SINK_DIR 2
1207 #define SCP_SINK_ENDDIR 3
1208 #define SCP_SINK_RETRY 4 /* not an action; just try again */
1209 struct scp_sink_action
{
1210 int action
; /* FILE, DIR, ENDDIR */
1211 char *buf
; /* will need freeing after use */
1212 char *name
; /* filename or dirname (not ENDDIR) */
1213 long permissions
; /* access permissions (not ENDDIR) */
1214 uint64 size
; /* file size (not ENDDIR) */
1215 int settime
; /* 1 if atime and mtime are filled */
1216 unsigned long atime
, mtime
; /* access times for the file */
1219 int scp_get_sink_action(struct scp_sink_action
*act
)
1223 int must_free_fname
;
1224 struct fxp_attrs attrs
;
1225 struct sftp_packet
*pktin
;
1226 struct sftp_request
*req
;
1229 if (!scp_sftp_dirstack_head
) {
1230 if (!scp_sftp_donethistarget
) {
1232 * Simple case: we are only dealing with one file.
1234 fname
= scp_sftp_remotepath
;
1235 must_free_fname
= 0;
1236 scp_sftp_donethistarget
= 1;
1239 * Even simpler case: one file _which we've done_.
1240 * Return 1 (finished).
1246 * We're now in the middle of stepping through a list
1247 * of names returned from fxp_readdir(); so let's carry
1250 struct scp_sftp_dirstack
*head
= scp_sftp_dirstack_head
;
1251 while (head
->namepos
< head
->namelen
&&
1252 (is_dots(head
->names
[head
->namepos
].filename
) ||
1254 !wc_match(head
->wildcard
,
1255 head
->names
[head
->namepos
].filename
))))
1256 head
->namepos
++; /* skip . and .. */
1257 if (head
->namepos
< head
->namelen
) {
1258 head
->matched_something
= 1;
1259 fname
= dupcat(head
->dirpath
, "/",
1260 head
->names
[head
->namepos
++].filename
,
1262 must_free_fname
= 1;
1265 * We've come to the end of the list; pop it off
1266 * the stack and return an ENDDIR action (or RETRY
1267 * if this was a wildcard match).
1269 if (head
->wildcard
) {
1270 act
->action
= SCP_SINK_RETRY
;
1271 if (!head
->matched_something
) {
1272 tell_user(stderr
, "pscp: wildcard '%s' matched "
1273 "no files", head
->wildcard
);
1276 sfree(head
->wildcard
);
1279 act
->action
= SCP_SINK_ENDDIR
;
1282 sfree(head
->dirpath
);
1284 scp_sftp_dirstack_head
= head
->next
;
1292 * Now we have a filename. Stat it, and see if it's a file
1295 req
= fxp_stat_send(fname
);
1296 pktin
= sftp_wait_for_reply(req
);
1297 ret
= fxp_stat_recv(pktin
, req
, &attrs
);
1299 if (!ret
|| !(attrs
.flags
& SSH_FILEXFER_ATTR_PERMISSIONS
)) {
1300 tell_user(stderr
, "unable to identify %s: %s", fname
,
1301 ret ?
"file type not supplied" : fxp_error());
1302 if (must_free_fname
) sfree(fname
);
1307 if (attrs
.permissions
& 0040000) {
1308 struct scp_sftp_dirstack
*newitem
;
1309 struct fxp_handle
*dirhandle
;
1310 int nnames
, namesize
;
1311 struct fxp_name
*ournames
;
1312 struct fxp_names
*names
;
1315 * It's a directory. If we're not in recursive mode,
1316 * this merits a complaint (which is fatal if the name
1317 * was specified directly, but not if it was matched by
1320 * We skip this complaint completely if
1321 * scp_sftp_wildcard is set, because that's an
1322 * indication that we're not actually supposed to
1323 * _recursively_ transfer the dir, just scan it for
1324 * things matching the wildcard.
1326 if (!scp_sftp_recursive
&& !scp_sftp_wildcard
) {
1327 tell_user(stderr
, "pscp: %s: is a directory", fname
);
1329 if (must_free_fname
) sfree(fname
);
1330 if (scp_sftp_dirstack_head
) {
1331 act
->action
= SCP_SINK_RETRY
;
1339 * Otherwise, the fun begins. We must fxp_opendir() the
1340 * directory, slurp the filenames into memory, return
1341 * SCP_SINK_DIR (unless this is a wildcard match), and
1342 * set targetisdir. The next time we're called, we will
1343 * run through the list of filenames one by one,
1344 * matching them against a wildcard if present.
1346 * If targetisdir is _already_ set (meaning we're
1347 * already in the middle of going through another such
1348 * list), we must push the other (target,namelist) pair
1351 req
= fxp_opendir_send(fname
);
1352 pktin
= sftp_wait_for_reply(req
);
1353 dirhandle
= fxp_opendir_recv(pktin
, req
);
1356 tell_user(stderr
, "pscp: unable to open directory %s: %s",
1357 fname
, fxp_error());
1358 if (must_free_fname
) sfree(fname
);
1362 nnames
= namesize
= 0;
1367 req
= fxp_readdir_send(dirhandle
);
1368 pktin
= sftp_wait_for_reply(req
);
1369 names
= fxp_readdir_recv(pktin
, req
);
1371 if (names
== NULL
) {
1372 if (fxp_error_type() == SSH_FX_EOF
)
1374 tell_user(stderr
, "pscp: reading directory %s: %s",
1375 fname
, fxp_error());
1377 req
= fxp_close_send(dirhandle
);
1378 pktin
= sftp_wait_for_reply(req
);
1379 fxp_close_recv(pktin
, req
);
1381 if (must_free_fname
) sfree(fname
);
1386 if (names
->nnames
== 0) {
1387 fxp_free_names(names
);
1390 if (nnames
+ names
->nnames
>= namesize
) {
1391 namesize
+= names
->nnames
+ 128;
1392 ournames
= sresize(ournames
, namesize
, struct fxp_name
);
1394 for (i
= 0; i
< names
->nnames
; i
++) {
1395 if (!strcmp(names
->names
[i
].filename
, ".") ||
1396 !strcmp(names
->names
[i
].filename
, "..")) {
1398 * . and .. are normal consequences of
1399 * reading a directory, and aren't worth
1400 * complaining about.
1402 } else if (!vet_filename(names
->names
[i
].filename
)) {
1403 tell_user(stderr
, "ignoring potentially dangerous server-"
1404 "supplied filename '%s'",
1405 names
->names
[i
].filename
);
1407 ournames
[nnames
++] = names
->names
[i
];
1409 names
->nnames
= 0; /* prevent free_names */
1410 fxp_free_names(names
);
1412 req
= fxp_close_send(dirhandle
);
1413 pktin
= sftp_wait_for_reply(req
);
1414 fxp_close_recv(pktin
, req
);
1416 newitem
= snew(struct scp_sftp_dirstack
);
1417 newitem
->next
= scp_sftp_dirstack_head
;
1418 newitem
->names
= ournames
;
1419 newitem
->namepos
= 0;
1420 newitem
->namelen
= nnames
;
1421 if (must_free_fname
)
1422 newitem
->dirpath
= fname
;
1424 newitem
->dirpath
= dupstr(fname
);
1425 if (scp_sftp_wildcard
) {
1426 newitem
->wildcard
= scp_sftp_wildcard
;
1427 newitem
->matched_something
= 0;
1428 scp_sftp_wildcard
= NULL
;
1430 newitem
->wildcard
= NULL
;
1432 scp_sftp_dirstack_head
= newitem
;
1434 if (newitem
->wildcard
) {
1435 act
->action
= SCP_SINK_RETRY
;
1437 act
->action
= SCP_SINK_DIR
;
1438 act
->buf
= dupstr(stripslashes(fname
, 0));
1439 act
->name
= act
->buf
;
1440 act
->size
= uint64_make(0,0); /* duhh, it's a directory */
1441 act
->permissions
= 07777 & attrs
.permissions
;
1442 if (scp_sftp_preserve
&&
1443 (attrs
.flags
& SSH_FILEXFER_ATTR_ACMODTIME
)) {
1444 act
->atime
= attrs
.atime
;
1445 act
->mtime
= attrs
.mtime
;
1454 * It's a file. Return SCP_SINK_FILE.
1456 act
->action
= SCP_SINK_FILE
;
1457 act
->buf
= dupstr(stripslashes(fname
, 0));
1458 act
->name
= act
->buf
;
1459 if (attrs
.flags
& SSH_FILEXFER_ATTR_SIZE
) {
1460 act
->size
= attrs
.size
;
1462 act
->size
= uint64_make(ULONG_MAX
,ULONG_MAX
); /* no idea */
1463 act
->permissions
= 07777 & attrs
.permissions
;
1464 if (scp_sftp_preserve
&&
1465 (attrs
.flags
& SSH_FILEXFER_ATTR_ACMODTIME
)) {
1466 act
->atime
= attrs
.atime
;
1467 act
->mtime
= attrs
.mtime
;
1471 if (must_free_fname
)
1472 scp_sftp_currentname
= fname
;
1474 scp_sftp_currentname
= dupstr(fname
);
1489 if (ssh_scp_recv((unsigned char *) &ch
, 1) <= 0)
1492 bump("Protocol error: Unexpected newline");
1496 if (ssh_scp_recv((unsigned char *) &ch
, 1) <= 0)
1497 bump("Lost connection");
1500 act
->buf
= sresize(act
->buf
, bufsize
, char);
1503 } while (ch
!= '\n');
1504 act
->buf
[i
- 1] = '\0';
1506 case '\01': /* error */
1507 tell_user(stderr
, "%s", act
->buf
);
1509 continue; /* go round again */
1510 case '\02': /* fatal error */
1511 bump("%s", act
->buf
);
1513 back
->send(backhandle
, "", 1);
1514 act
->action
= SCP_SINK_ENDDIR
;
1517 if (sscanf(act
->buf
, "%ld %*d %ld %*d",
1518 &act
->mtime
, &act
->atime
) == 2) {
1520 back
->send(backhandle
, "", 1);
1521 continue; /* go round again */
1523 bump("Protocol error: Illegal time format");
1526 act
->action
= (action
== 'C' ? SCP_SINK_FILE
: SCP_SINK_DIR
);
1529 bump("Protocol error: Expected control record");
1532 * We will go round this loop only once, unless we hit
1539 * If we get here, we must have seen SCP_SINK_FILE or
1545 if (sscanf(act
->buf
, "%lo %s %n", &act
->permissions
,
1547 bump("Protocol error: Illegal file descriptor format");
1548 act
->size
= uint64_from_decimal(sizestr
);
1549 act
->name
= act
->buf
+ i
;
1555 int scp_accept_filexfer(void)
1558 struct sftp_packet
*pktin
;
1559 struct sftp_request
*req
;
1561 req
= fxp_open_send(scp_sftp_currentname
, SSH_FXF_READ
, NULL
);
1562 pktin
= sftp_wait_for_reply(req
);
1563 scp_sftp_filehandle
= fxp_open_recv(pktin
, req
);
1565 if (!scp_sftp_filehandle
) {
1566 tell_user(stderr
, "pscp: unable to open %s: %s",
1567 scp_sftp_currentname
, fxp_error());
1571 scp_sftp_fileoffset
= uint64_make(0, 0);
1572 scp_sftp_xfer
= xfer_download_init(scp_sftp_filehandle
,
1573 scp_sftp_fileoffset
);
1574 sfree(scp_sftp_currentname
);
1577 back
->send(backhandle
, "", 1);
1578 return 0; /* can't fail */
1582 int scp_recv_filedata(char *data
, int len
)
1585 struct sftp_packet
*pktin
;
1589 xfer_download_queue(scp_sftp_xfer
);
1590 pktin
= sftp_recv();
1591 ret
= xfer_download_gotpkt(scp_sftp_xfer
, pktin
);
1593 tell_user(stderr
, "pscp: error while reading: %s", fxp_error());
1594 if (ret
== INT_MIN
) /* pktin not even freed */
1600 if (xfer_download_data(scp_sftp_xfer
, &vbuf
, &actuallen
)) {
1602 * This assertion relies on the fact that the natural
1603 * block size used in the xfer manager is at most that
1604 * used in this module. I don't like crossing layers in
1605 * this way, but it'll do for now.
1607 assert(actuallen
<= len
);
1608 memcpy(data
, vbuf
, actuallen
);
1613 scp_sftp_fileoffset
= uint64_add32(scp_sftp_fileoffset
, actuallen
);
1617 return ssh_scp_recv((unsigned char *) data
, len
);
1621 int scp_finish_filerecv(void)
1624 struct sftp_packet
*pktin
;
1625 struct sftp_request
*req
;
1628 * Ensure that xfer_done() will work correctly, so we can
1629 * clean up any outstanding requests from the file
1632 xfer_set_error(scp_sftp_xfer
);
1633 while (!xfer_done(scp_sftp_xfer
)) {
1637 pktin
= sftp_recv();
1638 ret
= xfer_download_gotpkt(scp_sftp_xfer
, pktin
);
1640 tell_user(stderr
, "pscp: error while reading: %s", fxp_error());
1641 if (ret
== INT_MIN
) /* pktin not even freed */
1646 if (xfer_download_data(scp_sftp_xfer
, &vbuf
, &len
))
1649 xfer_cleanup(scp_sftp_xfer
);
1651 req
= fxp_close_send(scp_sftp_filehandle
);
1652 pktin
= sftp_wait_for_reply(req
);
1653 fxp_close_recv(pktin
, req
);
1656 back
->send(backhandle
, "", 1);
1661 /* ----------------------------------------------------------------------
1662 * Send an error message to the other side and to the screen.
1663 * Increment error counter.
1665 static void run_err(const char *fmt
, ...)
1671 str
= dupvprintf(fmt
, ap
);
1672 str2
= dupcat("pscp: ", str
, "\n", NULL
);
1674 scp_send_errmsg(str2
);
1675 tell_user(stderr
, "%s", str2
);
1681 * Execute the source part of the SCP protocol.
1683 static void source(char *src
)
1686 unsigned long mtime
, atime
;
1693 time_t stat_starttime
, stat_lasttime
;
1695 attr
= file_type(src
);
1696 if (attr
== FILE_TYPE_NONEXISTENT
||
1697 attr
== FILE_TYPE_WEIRD
) {
1698 run_err("%s: %s file or directory", src
,
1699 (attr
== FILE_TYPE_WEIRD ?
"Not a" : "No such"));
1703 if (attr
== FILE_TYPE_DIRECTORY
) {
1706 * Avoid . and .. directories.
1709 p
= strrchr(src
, '/');
1711 p
= strrchr(src
, '\\');
1716 if (!strcmp(p
, ".") || !strcmp(p
, ".."))
1717 /* skip . and .. */ ;
1721 run_err("%s: not a regular file", src
);
1726 if ((last
= strrchr(src
, '/')) == NULL
)
1730 if (strrchr(last
, '\\') != NULL
)
1731 last
= strrchr(last
, '\\') + 1;
1732 if (last
== src
&& strchr(src
, ':') != NULL
)
1733 last
= strchr(src
, ':') + 1;
1735 f
= open_existing_file(src
, &size
, &mtime
, &atime
, &permissions
);
1737 run_err("%s: Cannot open file", src
);
1741 if (scp_send_filetimes(mtime
, atime
)) {
1749 uint64_decimal(size
, sizestr
);
1750 tell_user(stderr
, "Sending file %s, size=%s", last
, sizestr
);
1752 if (scp_send_filename(last
, size
, permissions
)) {
1757 stat_bytes
= uint64_make(0,0);
1758 stat_starttime
= time(NULL
);
1761 for (i
= uint64_make(0,0);
1762 uint64_compare(i
,size
) < 0;
1763 i
= uint64_add32(i
,4096)) {
1764 char transbuf
[4096];
1767 if (uint64_compare(uint64_add32(i
, k
),size
) > 0) /* i + k > size */
1768 k
= (uint64_subtract(size
, i
)).lo
; /* k = size - i; */
1769 if ((j
= read_from_file(f
, transbuf
, k
)) != k
) {
1772 bump("%s: Read error", src
);
1774 if (scp_send_filedata(transbuf
, k
))
1775 bump("%s: Network error occurred", src
);
1778 stat_bytes
= uint64_add32(stat_bytes
, k
);
1779 if (time(NULL
) != stat_lasttime
||
1780 (uint64_compare(uint64_add32(i
, k
), size
) == 0)) {
1781 stat_lasttime
= time(NULL
);
1782 print_stats(last
, size
, stat_bytes
,
1783 stat_starttime
, stat_lasttime
);
1790 (void) scp_send_finish();
1794 * Recursively send the contents of a directory.
1796 static void rsource(char *src
)
1802 if ((last
= strrchr(src
, '/')) == NULL
)
1806 if (strrchr(last
, '\\') != NULL
)
1807 last
= strrchr(last
, '\\') + 1;
1808 if (last
== src
&& strchr(src
, ':') != NULL
)
1809 last
= strchr(src
, ':') + 1;
1811 /* maybe send filetime */
1813 save_target
= scp_save_remotepath();
1816 tell_user(stderr
, "Entering directory: %s", last
);
1817 if (scp_send_dirname(last
, 0755))
1820 dir
= open_directory(src
);
1823 while ((filename
= read_filename(dir
)) != NULL
) {
1824 char *foundfile
= dupcat(src
, "/", filename
, NULL
);
1830 close_directory(dir
);
1832 (void) scp_send_enddir();
1834 scp_restore_remotepath(save_target
);
1838 * Execute the sink part of the SCP protocol.
1840 static void sink(char *targ
, char *src
)
1850 time_t stat_starttime
, stat_lasttime
;
1853 attr
= file_type(targ
);
1854 if (attr
== FILE_TYPE_DIRECTORY
)
1857 if (targetshouldbedirectory
&& !targisdir
)
1858 bump("%s: Not a directory", targ
);
1862 struct scp_sink_action act
;
1863 if (scp_get_sink_action(&act
))
1866 if (act
.action
== SCP_SINK_ENDDIR
)
1869 if (act
.action
== SCP_SINK_RETRY
)
1874 * Prevent the remote side from maliciously writing to
1875 * files outside the target area by sending a filename
1876 * containing `../'. In fact, it shouldn't be sending
1877 * filenames with any slashes or colons in at all; so
1878 * we'll find the last slash, backslash or colon in the
1879 * filename and use only the part after that. (And
1882 * In addition, we also ensure here that if we're
1883 * copying a single file and the target is a directory
1884 * (common usage: `pscp host:filename .') the remote
1885 * can't send us a _different_ file name. We can
1886 * distinguish this case because `src' will be non-NULL
1887 * and the last component of that will fail to match
1888 * (the last component of) the name sent.
1890 * Well, not always; if `src' is a wildcard, we do
1891 * expect to get back filenames that don't correspond
1892 * exactly to it. Ideally in this case, we would like
1893 * to ensure that the returned filename actually
1894 * matches the wildcard pattern - but one of SCP's
1895 * protocol infelicities is that wildcard matching is
1896 * done at the server end _by the server's rules_ and
1897 * so in general this is infeasible. Hence, we only
1898 * accept filenames that don't correspond to `src' if
1899 * unsafe mode is enabled or we are using SFTP (which
1900 * resolves remote wildcards on the client side and can
1903 char *striptarget
, *stripsrc
;
1905 striptarget
= stripslashes(act
.name
, 1);
1906 if (striptarget
!= act
.name
) {
1907 tell_user(stderr
, "warning: remote host sent a compound"
1908 " pathname '%s'", act
.name
);
1909 tell_user(stderr
, " renaming local file to '%s'",
1914 * Also check to see if the target filename is '.' or
1915 * '..', or indeed '...' and so on because Windows
1916 * appears to interpret those like '..'.
1918 if (is_dots(striptarget
)) {
1919 bump("security violation: remote host attempted to write to"
1920 " a '.' or '..' path!");
1924 stripsrc
= stripslashes(src
, 1);
1925 if (strcmp(striptarget
, stripsrc
) &&
1926 !using_sftp
&& !scp_unsafe_mode
) {
1927 tell_user(stderr
, "warning: remote host tried to write "
1928 "to a file called '%s'", striptarget
);
1929 tell_user(stderr
, " when we requested a file "
1930 "called '%s'.", stripsrc
);
1931 tell_user(stderr
, " If this is a wildcard, "
1932 "consider upgrading to SSH-2 or using");
1933 tell_user(stderr
, " the '-unsafe' option. Renaming"
1934 " of this file has been disallowed.");
1935 /* Override the name the server provided with our own. */
1936 striptarget
= stripsrc
;
1940 if (targ
[0] != '\0')
1941 destfname
= dir_file_cat(targ
, striptarget
);
1943 destfname
= dupstr(striptarget
);
1946 * In this branch of the if, the target area is a
1947 * single file with an explicitly specified name in any
1948 * case, so there's no danger.
1950 destfname
= dupstr(targ
);
1952 attr
= file_type(destfname
);
1953 exists
= (attr
!= FILE_TYPE_NONEXISTENT
);
1955 if (act
.action
== SCP_SINK_DIR
) {
1956 if (exists
&& attr
!= FILE_TYPE_DIRECTORY
) {
1957 run_err("%s: Not a directory", destfname
);
1962 if (!create_directory(destfname
)) {
1963 run_err("%s: Cannot create directory", destfname
);
1968 sink(destfname
, NULL
);
1969 /* can we set the timestamp for directories ? */
1974 f
= open_new_file(destfname
, act
.permissions
);
1976 run_err("%s: Cannot create file", destfname
);
1981 if (scp_accept_filexfer()) {
1987 stat_bytes
= uint64_make(0, 0);
1988 stat_starttime
= time(NULL
);
1990 stat_name
= stripslashes(destfname
, 1);
1992 received
= uint64_make(0, 0);
1993 while (uint64_compare(received
,act
.size
) < 0) {
1994 char transbuf
[32768];
1997 blksize
= uint64_make(0, 32768);
1998 if (uint64_compare(blksize
,uint64_subtract(act
.size
,received
)) > 0)
1999 blksize
= uint64_subtract(act
.size
,received
);
2000 read
= scp_recv_filedata(transbuf
, (int)blksize
.lo
);
2002 bump("Lost connection");
2005 if (write_to_file(f
, transbuf
, read
) != (int)read
) {
2007 /* FIXME: in sftp we can actually abort the transfer */
2009 printf("\r%-25.25s | %50s\n",
2011 "Write error.. waiting for end of file");
2015 stat_bytes
= uint64_add32(stat_bytes
,read
);
2016 if (time(NULL
) > stat_lasttime
||
2017 uint64_compare(uint64_add32(received
, read
), act
.size
) == 0) {
2018 stat_lasttime
= time(NULL
);
2019 print_stats(stat_name
, act
.size
, stat_bytes
,
2020 stat_starttime
, stat_lasttime
);
2023 received
= uint64_add32(received
, read
);
2026 set_file_times(f
, act
.mtime
, act
.atime
);
2032 run_err("%s: Write error", destfname
);
2036 (void) scp_finish_filerecv();
2043 * We will copy local files to a remote server.
2045 static void toremote(int argc
, char *argv
[])
2047 char *src
, *targ
, *host
, *user
;
2051 targ
= argv
[argc
- 1];
2053 /* Separate host from filename */
2057 bump("targ == NULL in toremote()");
2061 /* Substitute "." for empty target */
2063 /* Separate host and username */
2065 host
= strrchr(host
, '@');
2076 if (colon(argv
[0]) != NULL
)
2077 bump("%s: Remote to remote not supported", argv
[0]);
2079 wc_type
= test_wildcard(argv
[0], 1);
2080 if (wc_type
== WCTYPE_NONEXISTENT
)
2081 bump("%s: No such file or directory\n", argv
[0]);
2082 else if (wc_type
== WCTYPE_WILDCARD
)
2083 targetshouldbedirectory
= 1;
2086 cmd
= dupprintf("scp%s%s%s%s -t %s",
2087 verbose ?
" -v" : "",
2088 recursive ?
" -r" : "",
2089 preserve ?
" -p" : "",
2090 targetshouldbedirectory ?
" -d" : "", targ
);
2091 do_cmd(host
, user
, cmd
);
2094 if (scp_source_setup(targ
, targetshouldbedirectory
))
2097 for (i
= 0; i
< argc
- 1; i
++) {
2099 if (colon(src
) != NULL
) {
2100 tell_user(stderr
, "%s: Remote to remote not supported\n", src
);
2105 wc_type
= test_wildcard(src
, 1);
2106 if (wc_type
== WCTYPE_NONEXISTENT
) {
2107 run_err("%s: No such file or directory", src
);
2109 } else if (wc_type
== WCTYPE_FILENAME
) {
2113 WildcardMatcher
*wc
;
2116 wc
= begin_wildcard_matching(src
);
2118 run_err("%s: No such file or directory", src
);
2122 while ((filename
= wildcard_get_filename(wc
)) != NULL
) {
2127 finish_wildcard_matching(wc
);
2133 * We will copy files from a remote server to the local machine.
2135 static void tolocal(int argc
, char *argv
[])
2137 char *src
, *targ
, *host
, *user
;
2141 bump("More than one remote source not supported");
2146 /* Separate host from filename */
2150 bump("Local to local copy not supported");
2154 /* Substitute "." for empty filename */
2156 /* Separate username and hostname */
2158 host
= strrchr(host
, '@');
2168 cmd
= dupprintf("scp%s%s%s%s -f %s",
2169 verbose ?
" -v" : "",
2170 recursive ?
" -r" : "",
2171 preserve ?
" -p" : "",
2172 targetshouldbedirectory ?
" -d" : "", src
);
2173 do_cmd(host
, user
, cmd
);
2176 if (scp_sink_setup(src
, preserve
, recursive
))
2183 * We will issue a list command to get a remote directory.
2185 static void get_dir_list(int argc
, char *argv
[])
2187 char *src
, *host
, *user
;
2193 /* Separate host from filename */
2197 bump("Local file listing not supported");
2201 /* Substitute "." for empty filename */
2203 /* Separate username and hostname */
2205 host
= strrchr(host
, '@');
2215 cmd
= snewn(4 * strlen(src
) + 100, char);
2216 strcpy(cmd
, "ls -la '");
2217 p
= cmd
+ strlen(cmd
);
2218 for (q
= src
; *q
; q
++) {
2231 do_cmd(host
, user
, cmd
);
2235 scp_sftp_listdir(src
);
2237 while (ssh_scp_recv((unsigned char *) &c
, 1) > 0)
2238 tell_char(stdout
, c
);
2243 * Short description of parameters.
2245 static void usage(void)
2247 printf("PuTTY Secure Copy client\n");
2248 printf("%s\n", ver
);
2249 printf("Usage: pscp [options] [user@]host:source target\n");
2251 (" pscp [options] source [source...] [user@]host:target\n");
2252 printf(" pscp [options] -ls [user@]host:filespec\n");
2253 printf("Options:\n");
2254 printf(" -V print version information and exit\n");
2255 printf(" -pgpfp print PGP key fingerprints and exit\n");
2256 printf(" -p preserve file attributes\n");
2257 printf(" -q quiet, don't show statistics\n");
2258 printf(" -r copy directories recursively\n");
2259 printf(" -v show verbose messages\n");
2260 printf(" -load sessname Load settings from saved session\n");
2261 printf(" -P port connect to specified port\n");
2262 printf(" -l user connect with specified username\n");
2263 printf(" -pw passw login with specified password\n");
2264 printf(" -1 -2 force use of particular SSH protocol version\n");
2265 printf(" -4 -6 force use of IPv4 or IPv6\n");
2266 printf(" -C enable compression\n");
2267 printf(" -i key private key file for authentication\n");
2268 printf(" -noagent disable use of Pageant\n");
2269 printf(" -agent enable use of Pageant\n");
2270 printf(" -batch disable all interactive prompts\n");
2271 printf(" -unsafe allow server-side wildcards (DANGEROUS)\n");
2272 printf(" -sftp force use of SFTP protocol\n");
2273 printf(" -scp force use of SCP protocol\n");
2276 * -gui is an internal option, used by GUI front ends to get
2277 * pscp to pass progress reports back to them. It's not an
2278 * ordinary user-accessible option, so it shouldn't be part of
2279 * the command-line help. The only people who need to know
2280 * about it are programmers, and they can read the source.
2283 (" -gui hWnd GUI mode with the windows handle for receiving messages\n");
2290 printf("pscp: %s\n", ver
);
2294 void cmdline_error(char *p
, ...)
2297 fprintf(stderr
, "pscp: ");
2299 vfprintf(stderr
, p
, ap
);
2301 fprintf(stderr
, "\n try typing just \"pscp\" for help\n");
2306 * Main program. (Called `psftp_main' because it gets called from
2307 * *sftp.c; bit silly, I know, but it had to be called _something_.)
2309 int psftp_main(int argc
, char *argv
[])
2313 default_protocol
= PROT_TELNET
;
2316 #ifdef FLAG_SYNCAGENT
2320 cmdline_tooltype
= TOOLTYPE_FILETRANSFER
;
2323 /* Load Default Settings before doing anything else. */
2325 do_defaults(NULL
, conf
);
2326 loaded_session
= FALSE
;
2328 for (i
= 1; i
< argc
; i
++) {
2330 if (argv
[i
][0] != '-')
2332 ret
= cmdline_process_param(argv
[i
], i
+1<argc?argv
[i
+1]:NULL
, 1, conf
);
2334 cmdline_error("option \"%s\" requires an argument", argv
[i
]);
2335 } else if (ret
== 2) {
2336 i
++; /* skip next argument */
2337 } else if (ret
== 1) {
2338 /* We have our own verbosity in addition to `flags'. */
2339 if (flags
& FLAG_VERBOSE
)
2341 } else if (strcmp(argv
[i
], "-pgpfp") == 0) {
2344 } else if (strcmp(argv
[i
], "-r") == 0) {
2346 } else if (strcmp(argv
[i
], "-p") == 0) {
2348 } else if (strcmp(argv
[i
], "-q") == 0) {
2350 } else if (strcmp(argv
[i
], "-h") == 0 ||
2351 strcmp(argv
[i
], "-?") == 0 ||
2352 strcmp(argv
[i
], "--help") == 0) {
2354 } else if (strcmp(argv
[i
], "-V") == 0 ||
2355 strcmp(argv
[i
], "--version") == 0) {
2357 } else if (strcmp(argv
[i
], "-ls") == 0) {
2359 } else if (strcmp(argv
[i
], "-batch") == 0) {
2360 console_batch_mode
= 1;
2361 } else if (strcmp(argv
[i
], "-unsafe") == 0) {
2362 scp_unsafe_mode
= 1;
2363 } else if (strcmp(argv
[i
], "-sftp") == 0) {
2364 try_scp
= 0; try_sftp
= 1;
2365 } else if (strcmp(argv
[i
], "-scp") == 0) {
2366 try_scp
= 1; try_sftp
= 0;
2367 } else if (strcmp(argv
[i
], "--") == 0) {
2371 cmdline_error("unknown option \"%s\"", argv
[i
]);
2381 get_dir_list(argc
, argv
);
2388 targetshouldbedirectory
= 1;
2390 if (colon(argv
[argc
- 1]) != NULL
)
2391 toremote(argc
, argv
);
2393 tolocal(argc
, argv
);
2396 if (back
!= NULL
&& back
->connected(backhandle
)) {
2398 back
->special(backhandle
, TS_EOF
);
2400 ssh_scp_recv((unsigned char *) &ch
, 1);
2405 console_provide_logctx(NULL
);
2406 back
->free(backhandle
);
2410 return (errs
== 0 ?
0 : 1);