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
30 static int verbose
= 0;
31 static int recursive
= 0;
32 static int preserve
= 0;
33 static int targetshouldbedirectory
= 0;
34 static int statistics
= 1;
35 static int prev_stats_len
= 0;
36 static int scp_unsafe_mode
= 0;
38 static int gui_mode
= 0;
39 static int try_scp
= 1;
40 static int try_sftp
= 1;
41 static int main_cmd_is_sftp
= 0;
42 static int fallback_cmd_is_sftp
= 0;
43 static int using_sftp
= 0;
46 static void *backhandle
;
49 static void source(char *src
);
50 static void rsource(char *src
);
51 static void sink(char *targ
, char *src
);
54 * The maximum amount of queued data we accept before we stop and
55 * wait for the server to process some.
57 #define MAX_SCP_BUFSIZE 16384
59 void ldisc_send(void *handle
, char *buf
, int len
, int interactive
)
62 * This is only here because of the calls to ldisc_send(NULL,
63 * 0) in ssh.c. Nothing in PSCP actually needs to use the ldisc
64 * as an ldisc. So if we get called with any real data, I want
70 static void tell_char(FILE * stream
, char c
)
75 gui_send_char(stream
== stderr
, 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
);
116 gui_send_errcount(list
, errs
);
120 void modalfatalbox(char *fmt
, ...)
125 str
= dupvprintf(fmt
, ap
);
126 str2
= dupcat("Fatal: ", str
, "\n", NULL
);
129 tell_str(stderr
, str2
);
134 gui_send_errcount(list
, errs
);
138 void connection_fatal(void *frontend
, char *fmt
, ...)
143 str
= dupvprintf(fmt
, ap
);
144 str2
= dupcat("Fatal: ", str
, "\n", NULL
);
147 tell_str(stderr
, str2
);
152 gui_send_errcount(list
, errs
);
158 * In pscp, all agent requests should be synchronous, so this is a
161 void agent_schedule_callback(void (*callback
)(void *, void *, int),
162 void *callback_ctx
, void *data
, int len
)
164 assert(!"We shouldn't be here");
168 * Receive a block of data from the SSH link. Block until all data
171 * To do this, we repeatedly call the SSH protocol module, with our
172 * own trap in from_backend() to catch the data that comes back. We
173 * do this until we have enough data.
176 static unsigned char *outptr
; /* where to put the data */
177 static unsigned outlen
; /* how much data required */
178 static unsigned char *pending
= NULL
; /* any spare data */
179 static unsigned pendlen
= 0, pendsize
= 0; /* length and phys. size of buffer */
180 int from_backend(void *frontend
, int is_stderr
, const char *data
, int datalen
)
182 unsigned char *p
= (unsigned char *) data
;
183 unsigned len
= (unsigned) datalen
;
186 * stderr data is just spouted to local stderr and otherwise
191 fwrite(data
, 1, len
, stderr
);
196 * If this is before the real session begins, just return.
201 if ((outlen
> 0) && (len
> 0)) {
202 unsigned used
= outlen
;
205 memcpy(outptr
, p
, used
);
213 if (pendsize
< pendlen
+ len
) {
214 pendsize
= pendlen
+ len
+ 4096;
215 pending
= sresize(pending
, pendsize
, unsigned char);
217 fatalbox("Out of memory");
219 memcpy(pending
+ pendlen
, p
, len
);
225 static int ssh_scp_recv(unsigned char *buf
, int len
)
231 * See if the pending-input block contains some of what we
235 unsigned pendused
= pendlen
;
236 if (pendused
> outlen
)
238 memcpy(outptr
, pending
, pendused
);
239 memmove(pending
, pending
+ pendused
, pendlen
- pendused
);
253 if (ssh_sftp_loop_iteration() < 0)
261 * Loop through the ssh connection and authentication process.
263 static void ssh_scp_init(void)
265 while (!back
->sendok(backhandle
)) {
266 if (ssh_sftp_loop_iteration() < 0)
270 /* Work out which backend we ended up using. */
271 if (!ssh_fallback_cmd(backhandle
))
272 using_sftp
= main_cmd_is_sftp
;
274 using_sftp
= fallback_cmd_is_sftp
;
278 tell_user(stderr
, "Using SFTP");
280 tell_user(stderr
, "Using SCP1");
285 * Print an error message and exit after closing the SSH link.
287 static void bump(char *fmt
, ...)
292 str
= dupvprintf(fmt
, ap
);
294 str2
= dupcat(str
, "\n", NULL
);
296 tell_str(stderr
, str2
);
300 if (back
!= NULL
&& back
->socket(backhandle
) != NULL
) {
302 back
->special(backhandle
, TS_EOF
);
303 ssh_scp_recv((unsigned char *) &ch
, 1);
307 gui_send_errcount(list
, errs
);
313 * Open an SSH connection to user@host and execute cmd.
315 static void do_cmd(char *host
, char *user
, char *cmd
)
321 if (host
== NULL
|| host
[0] == '\0')
322 bump("Empty host name");
325 * Remove fiddly bits of address: remove a colon suffix, and
326 * the square brackets around an IPv6 literal address.
328 if (host
[0] == '[') {
330 host
[strcspn(host
, "]")] = '\0';
332 host
[strcspn(host
, ":")] = '\0';
336 * If we haven't loaded session details already (e.g., from -load),
337 * try looking for a session called "host".
339 if (!loaded_session
) {
340 /* Try to load settings for `host' into a temporary config */
343 do_defaults(host
, &cfg2
);
344 if (cfg2
.host
[0] != '\0') {
345 /* Settings present and include hostname */
346 /* Re-load data into the real config. */
347 do_defaults(host
, &cfg
);
349 /* Session doesn't exist or mention a hostname. */
350 /* Use `host' as a bare hostname. */
351 strncpy(cfg
.host
, host
, sizeof(cfg
.host
) - 1);
352 cfg
.host
[sizeof(cfg
.host
) - 1] = '\0';
355 /* Patch in hostname `host' to session details. */
356 strncpy(cfg
.host
, host
, sizeof(cfg
.host
) - 1);
357 cfg
.host
[sizeof(cfg
.host
) - 1] = '\0';
361 * Force use of SSH. (If they got the protocol wrong we assume the
362 * port is useless too.)
364 if (cfg
.protocol
!= PROT_SSH
) {
365 cfg
.protocol
= PROT_SSH
;
370 * Enact command-line overrides.
372 cmdline_run_saved(&cfg
);
375 * Trim leading whitespace off the hostname if it's there.
378 int space
= strspn(cfg
.host
, " \t");
379 memmove(cfg
.host
, cfg
.host
+space
, 1+strlen(cfg
.host
)-space
);
382 /* See if host is of the form user@host */
383 if (cfg
.host
[0] != '\0') {
384 char *atsign
= strrchr(cfg
.host
, '@');
385 /* Make sure we're not overflowing the user field */
387 if (atsign
- cfg
.host
< sizeof cfg
.username
) {
388 strncpy(cfg
.username
, cfg
.host
, atsign
- cfg
.host
);
389 cfg
.username
[atsign
- cfg
.host
] = '\0';
391 memmove(cfg
.host
, atsign
+ 1, 1 + strlen(atsign
+ 1));
396 * Remove any remaining whitespace from the hostname.
400 while (cfg
.host
[p2
] != '\0') {
401 if (cfg
.host
[p2
] != ' ' && cfg
.host
[p2
] != '\t') {
402 cfg
.host
[p1
] = cfg
.host
[p2
];
411 if (user
!= NULL
&& user
[0] != '\0') {
412 strncpy(cfg
.username
, user
, sizeof(cfg
.username
) - 1);
413 cfg
.username
[sizeof(cfg
.username
) - 1] = '\0';
414 } else if (cfg
.username
[0] == '\0') {
415 user
= get_username();
417 bump("Empty user name");
420 tell_user(stderr
, "Guessing user name: %s", user
);
421 strncpy(cfg
.username
, user
, sizeof(cfg
.username
) - 1);
422 cfg
.username
[sizeof(cfg
.username
) - 1] = '\0';
428 * Disable scary things which shouldn't be enabled for simple
429 * things like SCP and SFTP: agent forwarding, port forwarding,
434 cfg
.portfwd
[0] = cfg
.portfwd
[1] = '\0';
437 * Set up main and possibly fallback command depending on
438 * options specified by user.
439 * Attempt to start the SFTP subsystem as a first choice,
440 * falling back to the provided scp command if that fails.
442 cfg
.remote_cmd_ptr2
= NULL
;
444 /* First choice is SFTP subsystem. */
445 main_cmd_is_sftp
= 1;
446 strcpy(cfg
.remote_cmd
, "sftp");
447 cfg
.ssh_subsys
= TRUE
;
449 /* Fallback is to use the provided scp command. */
450 fallback_cmd_is_sftp
= 0;
451 cfg
.remote_cmd_ptr2
= cmd
;
452 cfg
.ssh_subsys2
= FALSE
;
454 /* Since we're not going to try SCP, we may as well try
455 * harder to find an SFTP server, since in the current
456 * implementation we have a spare slot. */
457 fallback_cmd_is_sftp
= 1;
458 /* see psftp.c for full explanation of this kludge */
459 cfg
.remote_cmd_ptr2
=
460 "test -x /usr/lib/sftp-server && exec /usr/lib/sftp-server\n"
461 "test -x /usr/local/lib/sftp-server && exec /usr/local/lib/sftp-server\n"
463 cfg
.ssh_subsys2
= FALSE
;
466 /* Don't try SFTP at all; just try the scp command. */
467 main_cmd_is_sftp
= 0;
468 cfg
.remote_cmd_ptr
= cmd
;
469 cfg
.ssh_subsys
= FALSE
;
475 err
= back
->init(NULL
, &backhandle
, &cfg
, cfg
.host
, cfg
.port
, &realhost
,
476 0, cfg
.tcp_keepalives
);
478 bump("ssh_init: %s", err
);
479 logctx
= log_init(NULL
, &cfg
);
480 back
->provide_logctx(backhandle
, logctx
);
481 console_provide_logctx(logctx
);
483 if (verbose
&& realhost
!= NULL
)
484 tell_user(stderr
, "Connected to %s\n", realhost
);
489 * Update statistic information about current file.
491 static void print_stats(char *name
, unsigned long size
, unsigned long done
,
492 time_t start
, time_t now
)
501 elap
= (unsigned long) difftime(now
, start
);
504 ratebs
= (float) done
/ elap
;
506 ratebs
= (float) done
;
511 eta
= (unsigned long) ((size
- done
) / ratebs
);
512 etastr
= dupprintf("%02ld:%02ld:%02ld",
513 eta
/ 3600, (eta
% 3600) / 60, eta
% 60);
515 pct
= (int) (100 * (done
* 1.0 / size
));
518 gui_update_stats(name
, size
, pct
, elap
, done
, eta
,
519 (unsigned long) ratebs
);
521 len
= printf("\r%-25.25s | %10ld kB | %5.1f kB/s | ETA: %8s | %3d%%",
522 name
, done
/ 1024, ratebs
/ 1024.0, etastr
, pct
);
523 if (len
< prev_stats_len
)
524 printf("%*s", prev_stats_len
- len
, "");
525 prev_stats_len
= len
;
537 * Find a colon in str and return a pointer to the colon.
538 * This is used to separate hostname from filename.
540 static char *colon(char *str
)
542 /* Check and process IPv6 literal addresses
543 * (eg: 'jeroen@[2001:db8::1]:myfile.txt') */
544 char *ipv6
= strchr(str
, '[');
546 str
= strchr(str
, ']');
548 /* Terminate on the closing bracket */
555 /* We ignore a leading colon, since the hostname cannot be
556 empty. We also ignore a colon as second character because
557 of filenames like f:myfile.txt. */
558 if (str
[0] == '\0' || str
[0] == ':' || str
[1] == ':')
560 while (*str
!= '\0' && *str
!= ':' && *str
!= '/' && *str
!= '\\')
569 * Return a pointer to the portion of str that comes after the last
570 * slash (or backslash or colon, if `local' is TRUE).
572 static char *stripslashes(char *str
, int local
)
577 p
= strchr(str
, ':');
581 p
= strrchr(str
, '/');
585 p
= strrchr(str
, '\\');
593 * Determine whether a string is entirely composed of dots.
595 static int is_dots(char *str
)
597 return str
[strspn(str
, ".")] == '\0';
601 * Wait for a response from the other side.
602 * Return 0 if ok, -1 if error.
604 static int response(void)
606 char ch
, resp
, rbuf
[2048];
609 if (ssh_scp_recv((unsigned char *) &resp
, 1) <= 0)
610 bump("Lost connection");
620 case 2: /* fatal error */
622 if (ssh_scp_recv((unsigned char *) &ch
, 1) <= 0)
623 bump("Protocol error: Lost connection");
625 } while (p
< sizeof(rbuf
) && ch
!= '\n');
628 tell_user(stderr
, "%s\n", rbuf
);
636 int sftp_recvdata(char *buf
, int len
)
638 return ssh_scp_recv((unsigned char *) buf
, len
);
640 int sftp_senddata(char *buf
, int len
)
642 back
->send(backhandle
, buf
, len
);
646 /* ----------------------------------------------------------------------
647 * sftp-based replacement for the hacky `pscp -ls'.
649 static int sftp_ls_compare(const void *av
, const void *bv
)
651 const struct fxp_name
*a
= (const struct fxp_name
*) av
;
652 const struct fxp_name
*b
= (const struct fxp_name
*) bv
;
653 return strcmp(a
->filename
, b
->filename
);
655 void scp_sftp_listdir(char *dirname
)
657 struct fxp_handle
*dirh
;
658 struct fxp_names
*names
;
659 struct fxp_name
*ournames
;
660 struct sftp_packet
*pktin
;
661 struct sftp_request
*req
, *rreq
;
662 int nnames
, namesize
;
666 tell_user(stderr
, "unable to initialise SFTP: %s", fxp_error());
671 printf("Listing directory %s\n", dirname
);
673 sftp_register(req
= fxp_opendir_send(dirname
));
674 rreq
= sftp_find_request(pktin
= sftp_recv());
676 dirh
= fxp_opendir_recv(pktin
, rreq
);
679 printf("Unable to open %s: %s\n", dirname
, fxp_error());
681 nnames
= namesize
= 0;
686 sftp_register(req
= fxp_readdir_send(dirh
));
687 rreq
= sftp_find_request(pktin
= sftp_recv());
689 names
= fxp_readdir_recv(pktin
, rreq
);
692 if (fxp_error_type() == SSH_FX_EOF
)
694 printf("Reading directory %s: %s\n", dirname
, fxp_error());
697 if (names
->nnames
== 0) {
698 fxp_free_names(names
);
702 if (nnames
+ names
->nnames
>= namesize
) {
703 namesize
+= names
->nnames
+ 128;
704 ournames
= sresize(ournames
, namesize
, struct fxp_name
);
707 for (i
= 0; i
< names
->nnames
; i
++)
708 ournames
[nnames
++] = names
->names
[i
];
709 names
->nnames
= 0; /* prevent free_names */
710 fxp_free_names(names
);
712 sftp_register(req
= fxp_close_send(dirh
));
713 rreq
= sftp_find_request(pktin
= sftp_recv());
715 fxp_close_recv(pktin
, rreq
);
718 * Now we have our filenames. Sort them by actual file
719 * name, and then output the longname parts.
721 qsort(ournames
, nnames
, sizeof(*ournames
), sftp_ls_compare
);
726 for (i
= 0; i
< nnames
; i
++)
727 printf("%s\n", ournames
[i
].longname
);
731 /* ----------------------------------------------------------------------
732 * Helper routines that contain the actual SCP protocol elements,
733 * implemented both as SCP1 and SFTP.
736 static struct scp_sftp_dirstack
{
737 struct scp_sftp_dirstack
*next
;
738 struct fxp_name
*names
;
739 int namepos
, namelen
;
742 int matched_something
; /* wildcard match set was non-empty */
743 } *scp_sftp_dirstack_head
;
744 static char *scp_sftp_remotepath
, *scp_sftp_currentname
;
745 static char *scp_sftp_wildcard
;
746 static int scp_sftp_targetisdir
, scp_sftp_donethistarget
;
747 static int scp_sftp_preserve
, scp_sftp_recursive
;
748 static unsigned long scp_sftp_mtime
, scp_sftp_atime
;
749 static int scp_has_times
;
750 static struct fxp_handle
*scp_sftp_filehandle
;
751 static struct fxp_xfer
*scp_sftp_xfer
;
752 static uint64 scp_sftp_fileoffset
;
754 void scp_source_setup(char *target
, int shouldbedir
)
758 * Find out whether the target filespec is in fact a
761 struct sftp_packet
*pktin
;
762 struct sftp_request
*req
, *rreq
;
763 struct fxp_attrs attrs
;
767 tell_user(stderr
, "unable to initialise SFTP: %s", fxp_error());
772 sftp_register(req
= fxp_stat_send(target
));
773 rreq
= sftp_find_request(pktin
= sftp_recv());
775 ret
= fxp_stat_recv(pktin
, rreq
, &attrs
);
777 if (!ret
|| !(attrs
.flags
& SSH_FILEXFER_ATTR_PERMISSIONS
))
778 scp_sftp_targetisdir
= 0;
780 scp_sftp_targetisdir
= (attrs
.permissions
& 0040000) != 0;
782 if (shouldbedir
&& !scp_sftp_targetisdir
) {
783 bump("pscp: remote filespec %s: not a directory\n", target
);
786 scp_sftp_remotepath
= dupstr(target
);
794 int scp_send_errmsg(char *str
)
797 /* do nothing; we never need to send our errors to the server */
799 back
->send(backhandle
, "\001", 1);/* scp protocol error prefix */
800 back
->send(backhandle
, str
, strlen(str
));
802 return 0; /* can't fail */
805 int scp_send_filetimes(unsigned long mtime
, unsigned long atime
)
808 scp_sftp_mtime
= mtime
;
809 scp_sftp_atime
= atime
;
814 sprintf(buf
, "T%lu 0 %lu 0\n", mtime
, atime
);
815 back
->send(backhandle
, buf
, strlen(buf
));
820 int scp_send_filename(char *name
, unsigned long size
, int modes
)
824 struct sftp_packet
*pktin
;
825 struct sftp_request
*req
, *rreq
;
827 if (scp_sftp_targetisdir
) {
828 fullname
= dupcat(scp_sftp_remotepath
, "/", name
, NULL
);
830 fullname
= dupstr(scp_sftp_remotepath
);
833 sftp_register(req
= fxp_open_send(fullname
, SSH_FXF_WRITE
|
834 SSH_FXF_CREAT
| SSH_FXF_TRUNC
));
835 rreq
= sftp_find_request(pktin
= sftp_recv());
837 scp_sftp_filehandle
= fxp_open_recv(pktin
, rreq
);
839 if (!scp_sftp_filehandle
) {
840 tell_user(stderr
, "pscp: unable to open %s: %s",
841 fullname
, fxp_error());
845 scp_sftp_fileoffset
= uint64_make(0, 0);
846 scp_sftp_xfer
= xfer_upload_init(scp_sftp_filehandle
,
847 scp_sftp_fileoffset
);
852 sprintf(buf
, "C%04o %lu ", modes
, size
);
853 back
->send(backhandle
, buf
, strlen(buf
));
854 back
->send(backhandle
, name
, strlen(name
));
855 back
->send(backhandle
, "\n", 1);
860 int scp_send_filedata(char *data
, int len
)
864 struct sftp_packet
*pktin
;
866 if (!scp_sftp_filehandle
) {
870 while (!xfer_upload_ready(scp_sftp_xfer
)) {
872 ret
= xfer_upload_gotpkt(scp_sftp_xfer
, pktin
);
874 tell_user(stderr
, "error while writing: %s\n", fxp_error());
880 xfer_upload_data(scp_sftp_xfer
, data
, len
);
882 scp_sftp_fileoffset
= uint64_add32(scp_sftp_fileoffset
, len
);
885 int bufsize
= back
->send(backhandle
, data
, len
);
888 * If the network transfer is backing up - that is, the
889 * remote site is not accepting data as fast as we can
890 * produce it - then we must loop on network events until
891 * we have space in the buffer again.
893 while (bufsize
> MAX_SCP_BUFSIZE
) {
894 if (ssh_sftp_loop_iteration() < 0)
896 bufsize
= back
->sendbuffer(backhandle
);
903 int scp_send_finish(void)
906 struct fxp_attrs attrs
;
907 struct sftp_packet
*pktin
;
908 struct sftp_request
*req
, *rreq
;
911 while (!xfer_done(scp_sftp_xfer
)) {
913 xfer_upload_gotpkt(scp_sftp_xfer
, pktin
);
915 xfer_cleanup(scp_sftp_xfer
);
917 if (!scp_sftp_filehandle
) {
921 attrs
.flags
= SSH_FILEXFER_ATTR_ACMODTIME
;
922 attrs
.atime
= scp_sftp_atime
;
923 attrs
.mtime
= scp_sftp_mtime
;
924 sftp_register(req
= fxp_fsetstat_send(scp_sftp_filehandle
, attrs
));
925 rreq
= sftp_find_request(pktin
= sftp_recv());
927 ret
= fxp_fsetstat_recv(pktin
, rreq
);
929 tell_user(stderr
, "unable to set file times: %s\n", fxp_error());
933 sftp_register(req
= fxp_close_send(scp_sftp_filehandle
));
934 rreq
= sftp_find_request(pktin
= sftp_recv());
936 fxp_close_recv(pktin
, rreq
);
940 back
->send(backhandle
, "", 1);
945 char *scp_save_remotepath(void)
948 return scp_sftp_remotepath
;
953 void scp_restore_remotepath(char *data
)
956 scp_sftp_remotepath
= data
;
959 int scp_send_dirname(char *name
, int modes
)
964 struct fxp_attrs attrs
;
965 struct sftp_packet
*pktin
;
966 struct sftp_request
*req
, *rreq
;
969 if (scp_sftp_targetisdir
) {
970 fullname
= dupcat(scp_sftp_remotepath
, "/", name
, NULL
);
972 fullname
= dupstr(scp_sftp_remotepath
);
976 * We don't worry about whether we managed to create the
977 * directory, because if it exists already it's OK just to
978 * use it. Instead, we will stat it afterwards, and if it
979 * exists and is a directory we will assume we were either
980 * successful or it didn't matter.
982 sftp_register(req
= fxp_mkdir_send(fullname
));
983 rreq
= sftp_find_request(pktin
= sftp_recv());
985 ret
= fxp_mkdir_recv(pktin
, rreq
);
990 err
= "server reported no error";
992 sftp_register(req
= fxp_stat_send(fullname
));
993 rreq
= sftp_find_request(pktin
= sftp_recv());
995 ret
= fxp_stat_recv(pktin
, rreq
, &attrs
);
997 if (!ret
|| !(attrs
.flags
& SSH_FILEXFER_ATTR_PERMISSIONS
) ||
998 !(attrs
.permissions
& 0040000)) {
999 tell_user(stderr
, "unable to create directory %s: %s",
1005 scp_sftp_remotepath
= fullname
;
1010 sprintf(buf
, "D%04o 0 ", modes
);
1011 back
->send(backhandle
, buf
, strlen(buf
));
1012 back
->send(backhandle
, name
, strlen(name
));
1013 back
->send(backhandle
, "\n", 1);
1018 int scp_send_enddir(void)
1021 sfree(scp_sftp_remotepath
);
1024 back
->send(backhandle
, "E\n", 2);
1030 * Yes, I know; I have an scp_sink_setup _and_ an scp_sink_init.
1031 * That's bad. The difference is that scp_sink_setup is called once
1032 * right at the start, whereas scp_sink_init is called to
1033 * initialise every level of recursion in the protocol.
1035 int scp_sink_setup(char *source
, int preserve
, int recursive
)
1041 tell_user(stderr
, "unable to initialise SFTP: %s", fxp_error());
1046 * It's possible that the source string we've been given
1047 * contains a wildcard. If so, we must split the directory
1048 * away from the wildcard itself (throwing an error if any
1049 * wildcardness comes before the final slash) and arrange
1050 * things so that a dirstack entry will be set up.
1052 newsource
= snewn(1+strlen(source
), char);
1053 if (!wc_unescape(newsource
, source
)) {
1054 /* Yes, here we go; it's a wildcard. Bah. */
1055 char *dupsource
, *lastpart
, *dirpart
, *wildcard
;
1056 dupsource
= dupstr(source
);
1057 lastpart
= stripslashes(dupsource
, 0);
1058 wildcard
= dupstr(lastpart
);
1060 if (*dupsource
&& dupsource
[1]) {
1062 * The remains of dupsource are at least two
1063 * characters long, meaning the pathname wasn't
1064 * empty or just `/'. Hence, we remove the trailing
1067 lastpart
[-1] = '\0';
1068 } else if (!*dupsource
) {
1070 * The remains of dupsource are _empty_ - the whole
1071 * pathname was a wildcard. Hence we need to
1072 * replace it with ".".
1075 dupsource
= dupstr(".");
1079 * Now we have separated our string into dupsource (the
1080 * directory part) and wildcard. Both of these will
1081 * need freeing at some point. Next step is to remove
1082 * wildcard escapes from the directory part, throwing
1083 * an error if it contains a real wildcard.
1085 dirpart
= snewn(1+strlen(dupsource
), char);
1086 if (!wc_unescape(dirpart
, dupsource
)) {
1087 tell_user(stderr
, "%s: multiple-level wildcards unsupported",
1097 * Now we have dirpart (unescaped, ie a valid remote
1098 * path), and wildcard (a wildcard). This will be
1099 * sufficient to arrange a dirstack entry.
1101 scp_sftp_remotepath
= dirpart
;
1102 scp_sftp_wildcard
= wildcard
;
1105 scp_sftp_remotepath
= newsource
;
1106 scp_sftp_wildcard
= NULL
;
1108 scp_sftp_preserve
= preserve
;
1109 scp_sftp_recursive
= recursive
;
1110 scp_sftp_donethistarget
= 0;
1111 scp_sftp_dirstack_head
= NULL
;
1116 int scp_sink_init(void)
1119 back
->send(backhandle
, "", 1);
1124 #define SCP_SINK_FILE 1
1125 #define SCP_SINK_DIR 2
1126 #define SCP_SINK_ENDDIR 3
1127 #define SCP_SINK_RETRY 4 /* not an action; just try again */
1128 struct scp_sink_action
{
1129 int action
; /* FILE, DIR, ENDDIR */
1130 char *buf
; /* will need freeing after use */
1131 char *name
; /* filename or dirname (not ENDDIR) */
1132 int mode
; /* access mode (not ENDDIR) */
1133 unsigned long size
; /* file size (not ENDDIR) */
1134 int settime
; /* 1 if atime and mtime are filled */
1135 unsigned long atime
, mtime
; /* access times for the file */
1138 int scp_get_sink_action(struct scp_sink_action
*act
)
1142 int must_free_fname
;
1143 struct fxp_attrs attrs
;
1144 struct sftp_packet
*pktin
;
1145 struct sftp_request
*req
, *rreq
;
1148 if (!scp_sftp_dirstack_head
) {
1149 if (!scp_sftp_donethistarget
) {
1151 * Simple case: we are only dealing with one file.
1153 fname
= scp_sftp_remotepath
;
1154 must_free_fname
= 0;
1155 scp_sftp_donethistarget
= 1;
1158 * Even simpler case: one file _which we've done_.
1159 * Return 1 (finished).
1165 * We're now in the middle of stepping through a list
1166 * of names returned from fxp_readdir(); so let's carry
1169 struct scp_sftp_dirstack
*head
= scp_sftp_dirstack_head
;
1170 while (head
->namepos
< head
->namelen
&&
1171 (is_dots(head
->names
[head
->namepos
].filename
) ||
1173 !wc_match(head
->wildcard
,
1174 head
->names
[head
->namepos
].filename
))))
1175 head
->namepos
++; /* skip . and .. */
1176 if (head
->namepos
< head
->namelen
) {
1177 head
->matched_something
= 1;
1178 fname
= dupcat(head
->dirpath
, "/",
1179 head
->names
[head
->namepos
++].filename
,
1181 must_free_fname
= 1;
1184 * We've come to the end of the list; pop it off
1185 * the stack and return an ENDDIR action (or RETRY
1186 * if this was a wildcard match).
1188 if (head
->wildcard
) {
1189 act
->action
= SCP_SINK_RETRY
;
1190 if (!head
->matched_something
) {
1191 tell_user(stderr
, "pscp: wildcard '%s' matched "
1192 "no files", head
->wildcard
);
1195 sfree(head
->wildcard
);
1198 act
->action
= SCP_SINK_ENDDIR
;
1201 sfree(head
->dirpath
);
1203 scp_sftp_dirstack_head
= head
->next
;
1211 * Now we have a filename. Stat it, and see if it's a file
1214 sftp_register(req
= fxp_stat_send(fname
));
1215 rreq
= sftp_find_request(pktin
= sftp_recv());
1216 assert(rreq
== req
);
1217 ret
= fxp_stat_recv(pktin
, rreq
, &attrs
);
1219 if (!ret
|| !(attrs
.flags
& SSH_FILEXFER_ATTR_PERMISSIONS
)) {
1220 tell_user(stderr
, "unable to identify %s: %s", fname
,
1221 ret ?
"file type not supplied" : fxp_error());
1226 if (attrs
.permissions
& 0040000) {
1227 struct scp_sftp_dirstack
*newitem
;
1228 struct fxp_handle
*dirhandle
;
1229 int nnames
, namesize
;
1230 struct fxp_name
*ournames
;
1231 struct fxp_names
*names
;
1234 * It's a directory. If we're not in recursive mode,
1235 * this merits a complaint (which is fatal if the name
1236 * was specified directly, but not if it was matched by
1239 * We skip this complaint completely if
1240 * scp_sftp_wildcard is set, because that's an
1241 * indication that we're not actually supposed to
1242 * _recursively_ transfer the dir, just scan it for
1243 * things matching the wildcard.
1245 if (!scp_sftp_recursive
&& !scp_sftp_wildcard
) {
1246 tell_user(stderr
, "pscp: %s: is a directory", fname
);
1248 if (must_free_fname
) sfree(fname
);
1249 if (scp_sftp_dirstack_head
) {
1250 act
->action
= SCP_SINK_RETRY
;
1258 * Otherwise, the fun begins. We must fxp_opendir() the
1259 * directory, slurp the filenames into memory, return
1260 * SCP_SINK_DIR (unless this is a wildcard match), and
1261 * set targetisdir. The next time we're called, we will
1262 * run through the list of filenames one by one,
1263 * matching them against a wildcard if present.
1265 * If targetisdir is _already_ set (meaning we're
1266 * already in the middle of going through another such
1267 * list), we must push the other (target,namelist) pair
1270 sftp_register(req
= fxp_opendir_send(fname
));
1271 rreq
= sftp_find_request(pktin
= sftp_recv());
1272 assert(rreq
== req
);
1273 dirhandle
= fxp_opendir_recv(pktin
, rreq
);
1276 tell_user(stderr
, "scp: unable to open directory %s: %s",
1277 fname
, fxp_error());
1278 if (must_free_fname
) sfree(fname
);
1282 nnames
= namesize
= 0;
1287 sftp_register(req
= fxp_readdir_send(dirhandle
));
1288 rreq
= sftp_find_request(pktin
= sftp_recv());
1289 assert(rreq
== req
);
1290 names
= fxp_readdir_recv(pktin
, rreq
);
1292 if (names
== NULL
) {
1293 if (fxp_error_type() == SSH_FX_EOF
)
1295 tell_user(stderr
, "scp: reading directory %s: %s\n",
1296 fname
, fxp_error());
1297 if (must_free_fname
) sfree(fname
);
1302 if (names
->nnames
== 0) {
1303 fxp_free_names(names
);
1306 if (nnames
+ names
->nnames
>= namesize
) {
1307 namesize
+= names
->nnames
+ 128;
1308 ournames
= sresize(ournames
, namesize
, struct fxp_name
);
1310 for (i
= 0; i
< names
->nnames
; i
++) {
1311 if (!strcmp(names
->names
[i
].filename
, ".") ||
1312 !strcmp(names
->names
[i
].filename
, "..")) {
1314 * . and .. are normal consequences of
1315 * reading a directory, and aren't worth
1316 * complaining about.
1318 } else if (!vet_filename(names
->names
[i
].filename
)) {
1319 tell_user(stderr
, "ignoring potentially dangerous server-"
1320 "supplied filename '%s'\n",
1321 names
->names
[i
].filename
);
1323 ournames
[nnames
++] = names
->names
[i
];
1325 names
->nnames
= 0; /* prevent free_names */
1326 fxp_free_names(names
);
1328 sftp_register(req
= fxp_close_send(dirhandle
));
1329 rreq
= sftp_find_request(pktin
= sftp_recv());
1330 assert(rreq
== req
);
1331 fxp_close_recv(pktin
, rreq
);
1333 newitem
= snew(struct scp_sftp_dirstack
);
1334 newitem
->next
= scp_sftp_dirstack_head
;
1335 newitem
->names
= ournames
;
1336 newitem
->namepos
= 0;
1337 newitem
->namelen
= nnames
;
1338 if (must_free_fname
)
1339 newitem
->dirpath
= fname
;
1341 newitem
->dirpath
= dupstr(fname
);
1342 if (scp_sftp_wildcard
) {
1343 newitem
->wildcard
= scp_sftp_wildcard
;
1344 newitem
->matched_something
= 0;
1345 scp_sftp_wildcard
= NULL
;
1347 newitem
->wildcard
= NULL
;
1349 scp_sftp_dirstack_head
= newitem
;
1351 if (newitem
->wildcard
) {
1352 act
->action
= SCP_SINK_RETRY
;
1354 act
->action
= SCP_SINK_DIR
;
1355 act
->buf
= dupstr(stripslashes(fname
, 0));
1356 act
->name
= act
->buf
;
1357 act
->size
= 0; /* duhh, it's a directory */
1358 act
->mode
= 07777 & attrs
.permissions
;
1359 if (scp_sftp_preserve
&&
1360 (attrs
.flags
& SSH_FILEXFER_ATTR_ACMODTIME
)) {
1361 act
->atime
= attrs
.atime
;
1362 act
->mtime
= attrs
.mtime
;
1371 * It's a file. Return SCP_SINK_FILE.
1373 act
->action
= SCP_SINK_FILE
;
1374 act
->buf
= dupstr(stripslashes(fname
, 0));
1375 act
->name
= act
->buf
;
1376 if (attrs
.flags
& SSH_FILEXFER_ATTR_SIZE
) {
1377 if (uint64_compare(attrs
.size
,
1378 uint64_make(0, ULONG_MAX
)) > 0) {
1379 act
->size
= ULONG_MAX
; /* *boggle* */
1381 act
->size
= attrs
.size
.lo
;
1383 act
->size
= ULONG_MAX
; /* no idea */
1384 act
->mode
= 07777 & attrs
.permissions
;
1385 if (scp_sftp_preserve
&&
1386 (attrs
.flags
& SSH_FILEXFER_ATTR_ACMODTIME
)) {
1387 act
->atime
= attrs
.atime
;
1388 act
->mtime
= attrs
.mtime
;
1392 if (must_free_fname
)
1393 scp_sftp_currentname
= fname
;
1395 scp_sftp_currentname
= dupstr(fname
);
1410 if (ssh_scp_recv((unsigned char *) &ch
, 1) <= 0)
1413 bump("Protocol error: Unexpected newline");
1417 if (ssh_scp_recv((unsigned char *) &ch
, 1) <= 0)
1418 bump("Lost connection");
1421 act
->buf
= sresize(act
->buf
, bufsize
, char);
1424 } while (ch
!= '\n');
1425 act
->buf
[i
- 1] = '\0';
1427 case '\01': /* error */
1428 tell_user(stderr
, "%s\n", act
->buf
);
1430 continue; /* go round again */
1431 case '\02': /* fatal error */
1432 bump("%s", act
->buf
);
1434 back
->send(backhandle
, "", 1);
1435 act
->action
= SCP_SINK_ENDDIR
;
1438 if (sscanf(act
->buf
, "%ld %*d %ld %*d",
1439 &act
->mtime
, &act
->atime
) == 2) {
1441 back
->send(backhandle
, "", 1);
1442 continue; /* go round again */
1444 bump("Protocol error: Illegal time format");
1447 act
->action
= (action
== 'C' ? SCP_SINK_FILE
: SCP_SINK_DIR
);
1450 bump("Protocol error: Expected control record");
1453 * We will go round this loop only once, unless we hit
1460 * If we get here, we must have seen SCP_SINK_FILE or
1463 if (sscanf(act
->buf
, "%o %lu %n", &act
->mode
, &act
->size
, &i
) != 2)
1464 bump("Protocol error: Illegal file descriptor format");
1465 act
->name
= act
->buf
+ i
;
1470 int scp_accept_filexfer(void)
1473 struct sftp_packet
*pktin
;
1474 struct sftp_request
*req
, *rreq
;
1476 sftp_register(req
= fxp_open_send(scp_sftp_currentname
, SSH_FXF_READ
));
1477 rreq
= sftp_find_request(pktin
= sftp_recv());
1478 assert(rreq
== req
);
1479 scp_sftp_filehandle
= fxp_open_recv(pktin
, rreq
);
1481 if (!scp_sftp_filehandle
) {
1482 tell_user(stderr
, "pscp: unable to open %s: %s",
1483 scp_sftp_currentname
, fxp_error());
1487 scp_sftp_fileoffset
= uint64_make(0, 0);
1488 scp_sftp_xfer
= xfer_download_init(scp_sftp_filehandle
,
1489 scp_sftp_fileoffset
);
1490 sfree(scp_sftp_currentname
);
1493 back
->send(backhandle
, "", 1);
1494 return 0; /* can't fail */
1498 int scp_recv_filedata(char *data
, int len
)
1501 struct sftp_packet
*pktin
;
1505 xfer_download_queue(scp_sftp_xfer
);
1506 pktin
= sftp_recv();
1507 ret
= xfer_download_gotpkt(scp_sftp_xfer
, pktin
);
1510 tell_user(stderr
, "pscp: error while reading: %s", fxp_error());
1515 if (xfer_download_data(scp_sftp_xfer
, &vbuf
, &actuallen
)) {
1517 * This assertion relies on the fact that the natural
1518 * block size used in the xfer manager is at most that
1519 * used in this module. I don't like crossing layers in
1520 * this way, but it'll do for now.
1522 assert(actuallen
<= len
);
1523 memcpy(data
, vbuf
, actuallen
);
1528 scp_sftp_fileoffset
= uint64_add32(scp_sftp_fileoffset
, actuallen
);
1532 return ssh_scp_recv((unsigned char *) data
, len
);
1536 int scp_finish_filerecv(void)
1539 struct sftp_packet
*pktin
;
1540 struct sftp_request
*req
, *rreq
;
1543 * Ensure that xfer_done() will work correctly, so we can
1544 * clean up any outstanding requests from the file
1547 xfer_set_error(scp_sftp_xfer
);
1548 while (!xfer_done(scp_sftp_xfer
)) {
1552 pktin
= sftp_recv();
1553 xfer_download_gotpkt(scp_sftp_xfer
, pktin
);
1554 if (xfer_download_data(scp_sftp_xfer
, &vbuf
, &len
))
1557 xfer_cleanup(scp_sftp_xfer
);
1559 sftp_register(req
= fxp_close_send(scp_sftp_filehandle
));
1560 rreq
= sftp_find_request(pktin
= sftp_recv());
1561 assert(rreq
== req
);
1562 fxp_close_recv(pktin
, rreq
);
1565 back
->send(backhandle
, "", 1);
1570 /* ----------------------------------------------------------------------
1571 * Send an error message to the other side and to the screen.
1572 * Increment error counter.
1574 static void run_err(const char *fmt
, ...)
1580 str
= dupvprintf(fmt
, ap
);
1581 str2
= dupcat("scp: ", str
, "\n", NULL
);
1583 scp_send_errmsg(str2
);
1584 tell_user(stderr
, "%s", str2
);
1590 * Execute the source part of the SCP protocol.
1592 static void source(char *src
)
1595 unsigned long mtime
, atime
;
1600 unsigned long stat_bytes
;
1601 time_t stat_starttime
, stat_lasttime
;
1603 attr
= file_type(src
);
1604 if (attr
== FILE_TYPE_NONEXISTENT
||
1605 attr
== FILE_TYPE_WEIRD
) {
1606 run_err("%s: %s file or directory", src
,
1607 (attr
== FILE_TYPE_WEIRD ?
"Not a" : "No such"));
1611 if (attr
== FILE_TYPE_DIRECTORY
) {
1614 * Avoid . and .. directories.
1617 p
= strrchr(src
, '/');
1619 p
= strrchr(src
, '\\');
1624 if (!strcmp(p
, ".") || !strcmp(p
, ".."))
1625 /* skip . and .. */ ;
1629 run_err("%s: not a regular file", src
);
1634 if ((last
= strrchr(src
, '/')) == NULL
)
1638 if (strrchr(last
, '\\') != NULL
)
1639 last
= strrchr(last
, '\\') + 1;
1640 if (last
== src
&& strchr(src
, ':') != NULL
)
1641 last
= strchr(src
, ':') + 1;
1643 f
= open_existing_file(src
, &size
, &mtime
, &atime
);
1645 run_err("%s: Cannot open file", src
);
1649 if (scp_send_filetimes(mtime
, atime
))
1654 tell_user(stderr
, "Sending file %s, size=%lu", last
, size
);
1655 if (scp_send_filename(last
, size
, 0644))
1659 stat_starttime
= time(NULL
);
1662 for (i
= 0; i
< size
; i
+= 4096) {
1663 char transbuf
[4096];
1668 if ((j
= read_from_file(f
, transbuf
, k
)) != k
) {
1671 bump("%s: Read error", src
);
1673 if (scp_send_filedata(transbuf
, k
))
1674 bump("%s: Network error occurred", src
);
1678 if (time(NULL
) != stat_lasttime
|| i
+ k
== size
) {
1679 stat_lasttime
= time(NULL
);
1680 print_stats(last
, size
, stat_bytes
,
1681 stat_starttime
, stat_lasttime
);
1688 (void) scp_send_finish();
1692 * Recursively send the contents of a directory.
1694 static void rsource(char *src
)
1700 if ((last
= strrchr(src
, '/')) == NULL
)
1704 if (strrchr(last
, '\\') != NULL
)
1705 last
= strrchr(last
, '\\') + 1;
1706 if (last
== src
&& strchr(src
, ':') != NULL
)
1707 last
= strchr(src
, ':') + 1;
1709 /* maybe send filetime */
1711 save_target
= scp_save_remotepath();
1714 tell_user(stderr
, "Entering directory: %s", last
);
1715 if (scp_send_dirname(last
, 0755))
1718 dir
= open_directory(src
);
1721 while ((filename
= read_filename(dir
)) != NULL
) {
1722 char *foundfile
= dupcat(src
, "/", filename
, NULL
);
1728 close_directory(dir
);
1730 (void) scp_send_enddir();
1732 scp_restore_remotepath(save_target
);
1736 * Execute the sink part of the SCP protocol.
1738 static void sink(char *targ
, char *src
)
1745 unsigned long received
;
1747 unsigned long stat_bytes
;
1748 time_t stat_starttime
, stat_lasttime
;
1751 attr
= file_type(targ
);
1752 if (attr
== FILE_TYPE_DIRECTORY
)
1755 if (targetshouldbedirectory
&& !targisdir
)
1756 bump("%s: Not a directory", targ
);
1760 struct scp_sink_action act
;
1761 if (scp_get_sink_action(&act
))
1764 if (act
.action
== SCP_SINK_ENDDIR
)
1767 if (act
.action
== SCP_SINK_RETRY
)
1772 * Prevent the remote side from maliciously writing to
1773 * files outside the target area by sending a filename
1774 * containing `../'. In fact, it shouldn't be sending
1775 * filenames with any slashes or colons in at all; so
1776 * we'll find the last slash, backslash or colon in the
1777 * filename and use only the part after that. (And
1780 * In addition, we also ensure here that if we're
1781 * copying a single file and the target is a directory
1782 * (common usage: `pscp host:filename .') the remote
1783 * can't send us a _different_ file name. We can
1784 * distinguish this case because `src' will be non-NULL
1785 * and the last component of that will fail to match
1786 * (the last component of) the name sent.
1788 * Well, not always; if `src' is a wildcard, we do
1789 * expect to get back filenames that don't correspond
1790 * exactly to it. Ideally in this case, we would like
1791 * to ensure that the returned filename actually
1792 * matches the wildcard pattern - but one of SCP's
1793 * protocol infelicities is that wildcard matching is
1794 * done at the server end _by the server's rules_ and
1795 * so in general this is infeasible. Hence, we only
1796 * accept filenames that don't correspond to `src' if
1797 * unsafe mode is enabled or we are using SFTP (which
1798 * resolves remote wildcards on the client side and can
1801 char *striptarget
, *stripsrc
;
1803 striptarget
= stripslashes(act
.name
, 1);
1804 if (striptarget
!= act
.name
) {
1805 tell_user(stderr
, "warning: remote host sent a compound"
1806 " pathname '%s'", act
.name
);
1807 tell_user(stderr
, " renaming local file to '%s'",
1812 * Also check to see if the target filename is '.' or
1813 * '..', or indeed '...' and so on because Windows
1814 * appears to interpret those like '..'.
1816 if (is_dots(striptarget
)) {
1817 bump("security violation: remote host attempted to write to"
1818 " a '.' or '..' path!");
1822 stripsrc
= stripslashes(src
, 1);
1823 if (strcmp(striptarget
, stripsrc
) &&
1824 !using_sftp
&& !scp_unsafe_mode
) {
1825 tell_user(stderr
, "warning: remote host tried to write "
1826 "to a file called '%s'", striptarget
);
1827 tell_user(stderr
, " when we requested a file "
1828 "called '%s'.", stripsrc
);
1829 tell_user(stderr
, " If this is a wildcard, "
1830 "consider upgrading to SSH 2 or using");
1831 tell_user(stderr
, " the '-unsafe' option. Renaming"
1832 " of this file has been disallowed.");
1833 /* Override the name the server provided with our own. */
1834 striptarget
= stripsrc
;
1838 if (targ
[0] != '\0')
1839 destfname
= dir_file_cat(targ
, striptarget
);
1841 destfname
= dupstr(striptarget
);
1844 * In this branch of the if, the target area is a
1845 * single file with an explicitly specified name in any
1846 * case, so there's no danger.
1848 destfname
= dupstr(targ
);
1850 attr
= file_type(destfname
);
1851 exists
= (attr
!= FILE_TYPE_NONEXISTENT
);
1853 if (act
.action
== SCP_SINK_DIR
) {
1854 if (exists
&& attr
!= FILE_TYPE_DIRECTORY
) {
1855 run_err("%s: Not a directory", destfname
);
1859 if (!create_directory(destfname
)) {
1860 run_err("%s: Cannot create directory", destfname
);
1864 sink(destfname
, NULL
);
1865 /* can we set the timestamp for directories ? */
1869 f
= open_new_file(destfname
);
1871 run_err("%s: Cannot create file", destfname
);
1875 if (scp_accept_filexfer())
1879 stat_starttime
= time(NULL
);
1881 stat_name
= stripslashes(destfname
, 1);
1884 while (received
< act
.size
) {
1885 char transbuf
[4096];
1886 unsigned long blksize
;
1889 if (blksize
> (act
.size
- received
))
1890 blksize
= act
.size
- received
;
1891 read
= scp_recv_filedata(transbuf
, (int)blksize
);
1893 bump("Lost connection");
1896 if (write_to_file(f
, transbuf
, read
) != (int)read
) {
1898 /* FIXME: in sftp we can actually abort the transfer */
1900 printf("\r%-25.25s | %50s\n",
1902 "Write error.. waiting for end of file");
1907 if (time(NULL
) > stat_lasttime
||
1908 received
+ read
== act
.size
) {
1909 stat_lasttime
= time(NULL
);
1910 print_stats(stat_name
, act
.size
, stat_bytes
,
1911 stat_starttime
, stat_lasttime
);
1917 set_file_times(f
, act
.mtime
, act
.atime
);
1922 run_err("%s: Write error", destfname
);
1925 (void) scp_finish_filerecv();
1932 * We will copy local files to a remote server.
1934 static void toremote(int argc
, char *argv
[])
1936 char *src
, *targ
, *host
, *user
;
1940 targ
= argv
[argc
- 1];
1942 /* Separate host from filename */
1946 bump("targ == NULL in toremote()");
1950 /* Substitute "." for empty target */
1952 /* Separate host and username */
1954 host
= strrchr(host
, '@');
1965 if (colon(argv
[0]) != NULL
)
1966 bump("%s: Remote to remote not supported", argv
[0]);
1968 wc_type
= test_wildcard(argv
[0], 1);
1969 if (wc_type
== WCTYPE_NONEXISTENT
)
1970 bump("%s: No such file or directory\n", argv
[0]);
1971 else if (wc_type
== WCTYPE_WILDCARD
)
1972 targetshouldbedirectory
= 1;
1975 cmd
= dupprintf("scp%s%s%s%s -t %s",
1976 verbose ?
" -v" : "",
1977 recursive ?
" -r" : "",
1978 preserve ?
" -p" : "",
1979 targetshouldbedirectory ?
" -d" : "", targ
);
1980 do_cmd(host
, user
, cmd
);
1983 scp_source_setup(targ
, targetshouldbedirectory
);
1985 for (i
= 0; i
< argc
- 1; i
++) {
1987 if (colon(src
) != NULL
) {
1988 tell_user(stderr
, "%s: Remote to remote not supported\n", src
);
1993 wc_type
= test_wildcard(src
, 1);
1994 if (wc_type
== WCTYPE_NONEXISTENT
) {
1995 run_err("%s: No such file or directory", src
);
1997 } else if (wc_type
== WCTYPE_FILENAME
) {
2001 WildcardMatcher
*wc
;
2004 wc
= begin_wildcard_matching(src
);
2006 run_err("%s: No such file or directory", src
);
2010 while ((filename
= wildcard_get_filename(wc
)) != NULL
) {
2015 finish_wildcard_matching(wc
);
2021 * We will copy files from a remote server to the local machine.
2023 static void tolocal(int argc
, char *argv
[])
2025 char *src
, *targ
, *host
, *user
;
2029 bump("More than one remote source not supported");
2034 /* Separate host from filename */
2038 bump("Local to local copy not supported");
2042 /* Substitute "." for empty filename */
2044 /* Separate username and hostname */
2046 host
= strrchr(host
, '@');
2056 cmd
= dupprintf("scp%s%s%s%s -f %s",
2057 verbose ?
" -v" : "",
2058 recursive ?
" -r" : "",
2059 preserve ?
" -p" : "",
2060 targetshouldbedirectory ?
" -d" : "", src
);
2061 do_cmd(host
, user
, cmd
);
2064 if (scp_sink_setup(src
, preserve
, recursive
))
2071 * We will issue a list command to get a remote directory.
2073 static void get_dir_list(int argc
, char *argv
[])
2075 char *src
, *host
, *user
;
2081 /* Separate host from filename */
2085 bump("Local to local copy not supported");
2089 /* Substitute "." for empty filename */
2091 /* Separate username and hostname */
2093 host
= strrchr(host
, '@');
2103 cmd
= snewn(4 * strlen(src
) + 100, char);
2104 strcpy(cmd
, "ls -la '");
2105 p
= cmd
+ strlen(cmd
);
2106 for (q
= src
; *q
; q
++) {
2119 do_cmd(host
, user
, cmd
);
2123 scp_sftp_listdir(src
);
2125 while (ssh_scp_recv((unsigned char *) &c
, 1) > 0)
2126 tell_char(stdout
, c
);
2131 * Short description of parameters.
2133 static void usage(void)
2135 printf("PuTTY Secure Copy client\n");
2136 printf("%s\n", ver
);
2137 printf("Usage: pscp [options] [user@]host:source target\n");
2139 (" pscp [options] source [source...] [user@]host:target\n");
2140 printf(" pscp [options] -ls [user@]host:filespec\n");
2141 printf("Options:\n");
2142 printf(" -p preserve file attributes\n");
2143 printf(" -q quiet, don't show statistics\n");
2144 printf(" -r copy directories recursively\n");
2145 printf(" -v show verbose messages\n");
2146 printf(" -load sessname Load settings from saved session\n");
2147 printf(" -P port connect to specified port\n");
2148 printf(" -l user connect with specified username\n");
2149 printf(" -pw passw login with specified password\n");
2150 printf(" -1 -2 force use of particular SSH protocol version\n");
2151 printf(" -4 -6 force use of IPv4 or IPv6\n");
2152 printf(" -C enable compression\n");
2153 printf(" -i key private key file for authentication\n");
2154 printf(" -batch disable all interactive prompts\n");
2155 printf(" -unsafe allow server-side wildcards (DANGEROUS)\n");
2156 printf(" -V print version information\n");
2157 printf(" -sftp force use of SFTP protocol\n");
2158 printf(" -scp force use of SCP protocol\n");
2161 * -gui is an internal option, used by GUI front ends to get
2162 * pscp to pass progress reports back to them. It's not an
2163 * ordinary user-accessible option, so it shouldn't be part of
2164 * the command-line help. The only people who need to know
2165 * about it are programmers, and they can read the source.
2168 (" -gui hWnd GUI mode with the windows handle for receiving messages\n");
2175 printf("pscp: %s\n", ver
);
2179 void cmdline_error(char *p
, ...)
2182 fprintf(stderr
, "pscp: ");
2184 vfprintf(stderr
, p
, ap
);
2186 fprintf(stderr
, "\n try typing just \"pscp\" for help\n");
2191 * Main program. (Called `psftp_main' because it gets called from
2192 * *sftp.c; bit silly, I know, but it had to be called _something_.)
2194 int psftp_main(int argc
, char *argv
[])
2198 default_protocol
= PROT_TELNET
;
2201 #ifdef FLAG_SYNCAGENT
2205 cmdline_tooltype
= TOOLTYPE_FILETRANSFER
;
2206 ssh_get_line
= &console_get_line
;
2209 /* Load Default Settings before doing anything else. */
2210 do_defaults(NULL
, &cfg
);
2211 loaded_session
= FALSE
;
2213 for (i
= 1; i
< argc
; i
++) {
2215 if (argv
[i
][0] != '-')
2217 ret
= cmdline_process_param(argv
[i
], i
+1<argc?argv
[i
+1]:NULL
, 1, &cfg
);
2219 cmdline_error("option \"%s\" requires an argument", argv
[i
]);
2220 } else if (ret
== 2) {
2221 i
++; /* skip next argument */
2222 } else if (ret
== 1) {
2223 /* We have our own verbosity in addition to `flags'. */
2224 if (flags
& FLAG_VERBOSE
)
2226 } else if (strcmp(argv
[i
], "-r") == 0) {
2228 } else if (strcmp(argv
[i
], "-p") == 0) {
2230 } else if (strcmp(argv
[i
], "-q") == 0) {
2232 } else if (strcmp(argv
[i
], "-h") == 0 || strcmp(argv
[i
], "-?") == 0) {
2234 } else if (strcmp(argv
[i
], "-V") == 0) {
2236 } else if (strcmp(argv
[i
], "-gui") == 0 && i
+ 1 < argc
) {
2237 gui_enable(argv
[++i
]);
2239 console_batch_mode
= TRUE
;
2240 } else if (strcmp(argv
[i
], "-ls") == 0) {
2242 } else if (strcmp(argv
[i
], "-batch") == 0) {
2243 console_batch_mode
= 1;
2244 } else if (strcmp(argv
[i
], "-unsafe") == 0) {
2245 scp_unsafe_mode
= 1;
2246 } else if (strcmp(argv
[i
], "-sftp") == 0) {
2247 try_scp
= 0; try_sftp
= 1;
2248 } else if (strcmp(argv
[i
], "-scp") == 0) {
2249 try_scp
= 1; try_sftp
= 0;
2250 } else if (strcmp(argv
[i
], "--") == 0) {
2254 cmdline_error("unknown option \"%s\"", argv
[i
]);
2264 get_dir_list(argc
, argv
);
2271 targetshouldbedirectory
= 1;
2273 if (colon(argv
[argc
- 1]) != NULL
)
2274 toremote(argc
, argv
);
2276 tolocal(argc
, argv
);
2279 if (back
!= NULL
&& back
->socket(backhandle
) != NULL
) {
2281 back
->special(backhandle
, TS_EOF
);
2282 ssh_scp_recv((unsigned char *) &ch
, 1);
2287 gui_send_errcount(list
, errs
);
2290 console_provide_logctx(NULL
);
2291 back
->free(backhandle
);
2295 return (errs
== 0 ?
0 : 1);