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 * Adaptations to enable connecting a GUI by L. Gunnarsson - Sept 2000
25 /* GUI Adaptation - Sept 2000 */
29 #define PUTTY_DO_GLOBALS
36 #define TIME_POSIX_TO_WIN(t, ft) (*(LONGLONG*)&(ft) = \
37 ((LONGLONG) (t) + (LONGLONG) 11644473600) * (LONGLONG) 10000000)
38 #define TIME_WIN_TO_POSIX(ft, t) ((t) = (unsigned long) \
39 ((*(LONGLONG*)&(ft)) / (LONGLONG) 10000000 - (LONGLONG) 11644473600))
41 /* GUI Adaptation - Sept 2000 */
42 #define WM_APP_BASE 0x8000
43 #define WM_STD_OUT_CHAR ( WM_APP_BASE+400 )
44 #define WM_STD_ERR_CHAR ( WM_APP_BASE+401 )
45 #define WM_STATS_CHAR ( WM_APP_BASE+402 )
46 #define WM_STATS_SIZE ( WM_APP_BASE+403 )
47 #define WM_STATS_PERCENT ( WM_APP_BASE+404 )
48 #define WM_STATS_ELAPSED ( WM_APP_BASE+405 )
49 #define WM_RET_ERR_CNT ( WM_APP_BASE+406 )
50 #define WM_LS_RET_ERR_CNT ( WM_APP_BASE+407 )
53 static int verbose
= 0;
54 static int recursive
= 0;
55 static int preserve
= 0;
56 static int targetshouldbedirectory
= 0;
57 static int statistics
= 1;
58 static int portnumber
= 0;
59 static int prev_stats_len
= 0;
60 static int scp_unsafe_mode
= 0;
61 static char *password
= NULL
;
63 /* GUI Adaptation - Sept 2000 */
64 #define NAME_STR_MAX 2048
65 static char statname
[NAME_STR_MAX
+ 1];
66 static unsigned long statsize
= 0;
67 static int statperct
= 0;
68 static unsigned long statelapsed
= 0;
69 static int gui_mode
= 0;
70 static char *gui_hwnd
= NULL
;
71 static int using_sftp
= 0;
73 static void source(char *src
);
74 static void rsource(char *src
);
75 static void sink(char *targ
, char *src
);
76 /* GUI Adaptation - Sept 2000 */
77 static void tell_char(FILE * stream
, char c
);
78 static void tell_str(FILE * stream
, char *str
);
79 static void tell_user(FILE * stream
, char *fmt
, ...);
80 static void gui_update_stats(char *name
, unsigned long size
,
81 int percentage
, unsigned long elapsed
);
84 * The maximum amount of queued data we accept before we stop and
85 * wait for the server to process some.
87 #define MAX_SCP_BUFSIZE 16384
89 void logevent(char *string
)
93 void ldisc_send(char *buf
, int len
)
96 * This is only here because of the calls to ldisc_send(NULL,
97 * 0) in ssh.c. Nothing in PSCP actually needs to use the ldisc
98 * as an ldisc. So if we get called with any real data, I want
104 void verify_ssh_host_key(char *host
, int port
, char *keytype
,
105 char *keystr
, char *fingerprint
)
111 static const char absentmsg
[] =
112 "The server's host key is not cached in the registry. You\n"
113 "have no guarantee that the server is the computer you\n"
115 "The server's key fingerprint is:\n"
117 "If you trust this host, enter \"y\" to add the key to\n"
118 "PuTTY's cache and carry on connecting.\n"
119 "If you want to carry on connecting just once, without\n"
120 "adding the key to the cache, enter \"n\".\n"
121 "If you do not trust this host, press Return to abandon the\n"
123 "Store key in cache? (y/n) ";
125 static const char wrongmsg
[] =
126 "WARNING - POTENTIAL SECURITY BREACH!\n"
127 "The server's host key does not match the one PuTTY has\n"
128 "cached in the registry. This means that either the\n"
129 "server administrator has changed the host key, or you\n"
130 "have actually connected to another computer pretending\n"
131 "to be the server.\n"
132 "The new key fingerprint is:\n"
134 "If you were expecting this change and trust the new key,\n"
135 "enter \"y\" to update PuTTY's cache and continue connecting.\n"
136 "If you want to carry on connecting but without updating\n"
137 "the cache, enter \"n\".\n"
138 "If you want to abandon the connection completely, press\n"
139 "Return to cancel. Pressing Return is the ONLY guaranteed\n"
141 "Update cached key? (y/n, Return cancels connection) ";
143 static const char abandoned
[] = "Connection abandoned.\n";
148 * Verify the key against the registry.
150 ret
= verify_host_key(host
, port
, keytype
, keystr
);
152 if (ret
== 0) /* success - key matched OK */
155 if (ret
== 2) { /* key was different */
156 fprintf(stderr
, wrongmsg
, fingerprint
);
159 if (ret
== 1) { /* key was absent */
160 fprintf(stderr
, absentmsg
, fingerprint
);
164 hin
= GetStdHandle(STD_INPUT_HANDLE
);
165 GetConsoleMode(hin
, &savemode
);
166 SetConsoleMode(hin
, (savemode
| ENABLE_ECHO_INPUT
|
167 ENABLE_PROCESSED_INPUT
| ENABLE_LINE_INPUT
));
168 ReadFile(hin
, line
, sizeof(line
) - 1, &i
, NULL
);
169 SetConsoleMode(hin
, savemode
);
171 if (line
[0] != '\0' && line
[0] != '\r' && line
[0] != '\n') {
172 if (line
[0] == 'y' || line
[0] == 'Y')
173 store_host_key(host
, port
, keytype
, keystr
);
175 fprintf(stderr
, abandoned
);
181 * Ask whether the selected cipher is acceptable (since it was
182 * below the configured 'warn' threshold).
183 * cs: 0 = both ways, 1 = client->server, 2 = server->client
185 void askcipher(char *ciphername
, int cs
)
190 static const char msg
[] =
191 "The first %scipher supported by the server is\n"
192 "%s, which is below the configured warning threshold.\n"
193 "Continue with connection? (y/n) ";
194 static const char abandoned
[] = "Connection abandoned.\n";
200 (cs
== 1) ?
"client-to-server " :
205 hin
= GetStdHandle(STD_INPUT_HANDLE
);
206 GetConsoleMode(hin
, &savemode
);
207 SetConsoleMode(hin
, (savemode
| ENABLE_ECHO_INPUT
|
208 ENABLE_PROCESSED_INPUT
| ENABLE_LINE_INPUT
));
209 ReadFile(hin
, line
, sizeof(line
) - 1, &i
, NULL
);
210 SetConsoleMode(hin
, savemode
);
212 if (line
[0] == 'y' || line
[0] == 'Y') {
215 fprintf(stderr
, abandoned
);
220 /* GUI Adaptation - Sept 2000 */
221 static void send_msg(HWND h
, UINT message
, WPARAM wParam
)
223 while (!PostMessage(h
, message
, wParam
, 0))
227 static void tell_char(FILE * stream
, char c
)
232 unsigned int msg_id
= WM_STD_OUT_CHAR
;
233 if (stream
== stderr
)
234 msg_id
= WM_STD_ERR_CHAR
;
235 send_msg((HWND
) atoi(gui_hwnd
), msg_id
, (WPARAM
) c
);
239 static void tell_str(FILE * stream
, char *str
)
243 for (i
= 0; i
< strlen(str
); ++i
)
244 tell_char(stream
, str
[i
]);
247 static void tell_user(FILE * stream
, char *fmt
, ...)
249 char str
[0x100]; /* Make the size big enough */
252 vsprintf(str
, fmt
, ap
);
255 tell_str(stream
, str
);
258 static void gui_update_stats(char *name
, unsigned long size
,
259 int percentage
, unsigned long elapsed
)
263 if (strcmp(name
, statname
) != 0) {
264 for (i
= 0; i
< strlen(name
); ++i
)
265 send_msg((HWND
) atoi(gui_hwnd
), WM_STATS_CHAR
,
267 send_msg((HWND
) atoi(gui_hwnd
), WM_STATS_CHAR
, (WPARAM
) '\n');
268 strcpy(statname
, name
);
270 if (statsize
!= size
) {
271 send_msg((HWND
) atoi(gui_hwnd
), WM_STATS_SIZE
, (WPARAM
) size
);
274 if (statelapsed
!= elapsed
) {
275 send_msg((HWND
) atoi(gui_hwnd
), WM_STATS_ELAPSED
,
277 statelapsed
= elapsed
;
279 if (statperct
!= percentage
) {
280 send_msg((HWND
) atoi(gui_hwnd
), WM_STATS_PERCENT
,
281 (WPARAM
) percentage
);
282 statperct
= percentage
;
287 * Print an error message and perform a fatal exit.
289 void fatalbox(char *fmt
, ...)
291 char str
[0x100]; /* Make the size big enough */
294 strcpy(str
, "Fatal: ");
295 vsprintf(str
+ strlen(str
), fmt
, ap
);
298 tell_str(stderr
, str
);
302 unsigned int msg_id
= WM_RET_ERR_CNT
;
304 msg_id
= WM_LS_RET_ERR_CNT
;
306 ((HWND
) atoi(gui_hwnd
), msg_id
, (WPARAM
) errs
,
307 0 /*lParam */ ))SleepEx(1000, TRUE
);
312 void connection_fatal(char *fmt
, ...)
314 char str
[0x100]; /* Make the size big enough */
317 strcpy(str
, "Fatal: ");
318 vsprintf(str
+ strlen(str
), fmt
, ap
);
321 tell_str(stderr
, str
);
325 unsigned int msg_id
= WM_RET_ERR_CNT
;
327 msg_id
= WM_LS_RET_ERR_CNT
;
329 ((HWND
) atoi(gui_hwnd
), msg_id
, (WPARAM
) errs
,
330 0 /*lParam */ ))SleepEx(1000, TRUE
);
337 * Be told what socket we're supposed to be using.
339 static SOCKET scp_ssh_socket
;
340 char *do_select(SOCKET skt
, int startup
)
343 scp_ssh_socket
= skt
;
345 scp_ssh_socket
= INVALID_SOCKET
;
348 extern int select_result(WPARAM
, LPARAM
);
351 * Receive a block of data from the SSH link. Block until all data
354 * To do this, we repeatedly call the SSH protocol module, with our
355 * own trap in from_backend() to catch the data that comes back. We
356 * do this until we have enough data.
359 static unsigned char *outptr
; /* where to put the data */
360 static unsigned outlen
; /* how much data required */
361 static unsigned char *pending
= NULL
; /* any spare data */
362 static unsigned pendlen
= 0, pendsize
= 0; /* length and phys. size of buffer */
363 int from_backend(int is_stderr
, char *data
, int datalen
)
365 unsigned char *p
= (unsigned char *) data
;
366 unsigned len
= (unsigned) datalen
;
369 * stderr data is just spouted to local stderr and otherwise
373 fwrite(data
, 1, len
, stderr
);
380 * If this is before the real session begins, just return.
386 unsigned used
= outlen
;
389 memcpy(outptr
, p
, used
);
397 if (pendsize
< pendlen
+ len
) {
398 pendsize
= pendlen
+ len
+ 4096;
399 pending
= (pending ?
srealloc(pending
, pendsize
) :
402 fatalbox("Out of memory");
404 memcpy(pending
+ pendlen
, p
, len
);
410 static int scp_process_network_event(void)
415 FD_SET(scp_ssh_socket
, &readfds
);
416 if (select(1, &readfds
, NULL
, NULL
, NULL
) < 0)
418 select_result((WPARAM
) scp_ssh_socket
, (LPARAM
) FD_READ
);
421 static int ssh_scp_recv(unsigned char *buf
, int len
)
427 * See if the pending-input block contains some of what we
431 unsigned pendused
= pendlen
;
432 if (pendused
> outlen
)
434 memcpy(outptr
, pending
, pendused
);
435 memmove(pending
, pending
+ pendused
, pendlen
- pendused
);
449 if (!scp_process_network_event())
457 * Loop through the ssh connection and authentication process.
459 static void ssh_scp_init(void)
461 if (scp_ssh_socket
== INVALID_SOCKET
)
463 while (!back
->sendok()) {
466 FD_SET(scp_ssh_socket
, &readfds
);
467 if (select(1, &readfds
, NULL
, NULL
, NULL
) < 0)
469 select_result((WPARAM
) scp_ssh_socket
, (LPARAM
) FD_READ
);
471 using_sftp
= !ssh_fallback_cmd
;
475 * Print an error message and exit after closing the SSH link.
477 static void bump(char *fmt
, ...)
479 char str
[0x100]; /* Make the size big enough */
482 strcpy(str
, "Fatal: ");
483 vsprintf(str
+ strlen(str
), fmt
, ap
);
486 tell_str(stderr
, str
);
489 if (back
!= NULL
&& back
->socket() != NULL
) {
491 back
->special(TS_EOF
);
492 ssh_scp_recv(&ch
, 1);
496 unsigned int msg_id
= WM_RET_ERR_CNT
;
498 msg_id
= WM_LS_RET_ERR_CNT
;
500 ((HWND
) atoi(gui_hwnd
), msg_id
, (WPARAM
) errs
,
501 0 /*lParam */ ))SleepEx(1000, TRUE
);
507 static int get_line(const char *prompt
, char *str
, int maxlen
, int is_pw
)
510 DWORD savemode
, newmode
, i
;
512 if (is_pw
&& password
) {
513 static int tried_once
= 0;
518 strncpy(str
, password
, maxlen
);
519 str
[maxlen
- 1] = '\0';
525 /* GUI Adaptation - Sept 2000 */
530 hin
= GetStdHandle(STD_INPUT_HANDLE
);
531 hout
= GetStdHandle(STD_OUTPUT_HANDLE
);
532 if (hin
== INVALID_HANDLE_VALUE
|| hout
== INVALID_HANDLE_VALUE
)
533 bump("Cannot get standard input/output handles");
535 GetConsoleMode(hin
, &savemode
);
536 newmode
= savemode
| ENABLE_PROCESSED_INPUT
| ENABLE_LINE_INPUT
;
538 newmode
&= ~ENABLE_ECHO_INPUT
;
540 newmode
|= ENABLE_ECHO_INPUT
;
541 SetConsoleMode(hin
, newmode
);
543 WriteFile(hout
, prompt
, strlen(prompt
), &i
, NULL
);
544 ReadFile(hin
, str
, maxlen
- 1, &i
, NULL
);
546 SetConsoleMode(hin
, savemode
);
548 if ((int) i
> maxlen
)
555 WriteFile(hout
, "\r\n", 2, &i
, NULL
);
562 * Open an SSH connection to user@host and execute cmd.
564 static void do_cmd(char *host
, char *user
, char *cmd
)
566 char *err
, *realhost
;
569 if (host
== NULL
|| host
[0] == '\0')
570 bump("Empty host name");
572 /* Try to load settings for this host */
573 do_defaults(host
, &cfg
);
574 if (cfg
.host
[0] == '\0') {
575 /* No settings for this host; use defaults */
576 do_defaults(NULL
, &cfg
);
577 strncpy(cfg
.host
, host
, sizeof(cfg
.host
) - 1);
578 cfg
.host
[sizeof(cfg
.host
) - 1] = '\0';
583 if (user
!= NULL
&& user
[0] != '\0') {
584 strncpy(cfg
.username
, user
, sizeof(cfg
.username
) - 1);
585 cfg
.username
[sizeof(cfg
.username
) - 1] = '\0';
586 } else if (cfg
.username
[0] == '\0') {
588 if (GetUserName(user
, &namelen
) == FALSE
)
589 bump("Empty user name");
590 user
= smalloc(namelen
* sizeof(char));
591 GetUserName(user
, &namelen
);
593 tell_user(stderr
, "Guessing user name: %s", user
);
594 strncpy(cfg
.username
, user
, sizeof(cfg
.username
) - 1);
595 cfg
.username
[sizeof(cfg
.username
) - 1] = '\0';
599 if (cfg
.protocol
!= PROT_SSH
)
603 cfg
.port
= portnumber
;
606 * Attempt to start the SFTP subsystem as a first choice,
607 * falling back to the provided scp command if that fails.
609 strcpy(cfg
.remote_cmd
, "sftp");
610 cfg
.ssh_subsys
= TRUE
;
611 cfg
.remote_cmd_ptr2
= cmd
;
612 cfg
.ssh_subsys2
= FALSE
;
617 err
= back
->init(cfg
.host
, cfg
.port
, &realhost
);
619 bump("ssh_init: %s", err
);
621 if (verbose
&& realhost
!= NULL
)
622 tell_user(stderr
, "Connected to %s\n", realhost
);
627 * Update statistic information about current file.
629 static void print_stats(char *name
, unsigned long size
, unsigned long done
,
630 time_t start
, time_t now
)
638 /* GUI Adaptation - Sept 2000 */
640 gui_update_stats(name
, size
, (int) (100 * (done
* 1.0 / size
)),
641 (unsigned long) difftime(now
, start
));
644 ratebs
= (float) done
/ (now
- start
);
646 ratebs
= (float) done
;
651 eta
= (unsigned long) ((size
- done
) / ratebs
);
652 sprintf(etastr
, "%02ld:%02ld:%02ld",
653 eta
/ 3600, (eta
% 3600) / 60, eta
% 60);
655 pct
= (int) (100.0 * (float) done
/ size
);
657 len
= printf("\r%-25.25s | %10ld kB | %5.1f kB/s | ETA: %8s | %3d%%",
658 name
, done
/ 1024, ratebs
/ 1024.0, etastr
, pct
);
659 if (len
< prev_stats_len
)
660 printf("%*s", prev_stats_len
- len
, "");
661 prev_stats_len
= len
;
669 * Find a colon in str and return a pointer to the colon.
670 * This is used to separate hostname from filename.
672 static char *colon(char *str
)
674 /* We ignore a leading colon, since the hostname cannot be
675 empty. We also ignore a colon as second character because
676 of filenames like f:myfile.txt. */
677 if (str
[0] == '\0' || str
[0] == ':' || str
[1] == ':')
679 while (*str
!= '\0' && *str
!= ':' && *str
!= '/' && *str
!= '\\')
688 * Return a pointer to the portion of str that comes after the last
689 * slash (or backslash or colon, if `local' is TRUE).
691 static char *stripslashes(char *str
, int local
)
696 p
= strchr(str
, ':');
700 p
= strrchr(str
, '/');
704 p
= strrchr(str
, '\\');
712 * Determine whether a string is entirely composed of dots.
714 static int is_dots(char *str
)
716 return str
[strspn(str
, ".")] == '\0';
720 * Wait for a response from the other side.
721 * Return 0 if ok, -1 if error.
723 static int response(void)
725 char ch
, resp
, rbuf
[2048];
728 if (ssh_scp_recv(&resp
, 1) <= 0)
729 bump("Lost connection");
739 case 2: /* fatal error */
741 if (ssh_scp_recv(&ch
, 1) <= 0)
742 bump("Protocol error: Lost connection");
744 } while (p
< sizeof(rbuf
) && ch
!= '\n');
747 tell_user(stderr
, "%s\n", rbuf
);
755 int sftp_recvdata(char *buf
, int len
)
757 return ssh_scp_recv(buf
, len
);
759 int sftp_senddata(char *buf
, int len
)
761 back
->send((unsigned char *) buf
, len
);
765 /* ----------------------------------------------------------------------
766 * sftp-based replacement for the hacky `pscp -ls'.
768 static int sftp_ls_compare(const void *av
, const void *bv
)
770 const struct fxp_name
*a
= (const struct fxp_name
*) av
;
771 const struct fxp_name
*b
= (const struct fxp_name
*) bv
;
772 return strcmp(a
->filename
, b
->filename
);
774 void scp_sftp_listdir(char *dirname
)
776 struct fxp_handle
*dirh
;
777 struct fxp_names
*names
;
778 struct fxp_name
*ournames
;
779 int nnames
, namesize
;
782 printf("Listing directory %s\n", dirname
);
784 dirh
= fxp_opendir(dirname
);
786 printf("Unable to open %s: %s\n", dirname
, fxp_error());
788 nnames
= namesize
= 0;
793 names
= fxp_readdir(dirh
);
795 if (fxp_error_type() == SSH_FX_EOF
)
797 printf("Reading directory %s: %s\n", dirname
, fxp_error());
800 if (names
->nnames
== 0) {
801 fxp_free_names(names
);
805 if (nnames
+ names
->nnames
>= namesize
) {
806 namesize
+= names
->nnames
+ 128;
808 srealloc(ournames
, namesize
* sizeof(*ournames
));
811 for (i
= 0; i
< names
->nnames
; i
++)
812 ournames
[nnames
++] = names
->names
[i
];
814 names
->nnames
= 0; /* prevent free_names */
815 fxp_free_names(names
);
820 * Now we have our filenames. Sort them by actual file
821 * name, and then output the longname parts.
823 qsort(ournames
, nnames
, sizeof(*ournames
), sftp_ls_compare
);
828 for (i
= 0; i
< nnames
; i
++)
829 printf("%s\n", ournames
[i
].longname
);
833 /* ----------------------------------------------------------------------
834 * Helper routines that contain the actual SCP protocol elements,
835 * implemented both as SCP1 and SFTP.
838 static struct scp_sftp_dirstack
{
839 struct scp_sftp_dirstack
*next
;
840 struct fxp_name
*names
;
841 int namepos
, namelen
;
844 } *scp_sftp_dirstack_head
;
845 static char *scp_sftp_remotepath
, *scp_sftp_currentname
;
846 static char *scp_sftp_wildcard
;
847 static int scp_sftp_targetisdir
, scp_sftp_donethistarget
;
848 static int scp_sftp_preserve
, scp_sftp_recursive
;
849 static unsigned long scp_sftp_mtime
, scp_sftp_atime
;
850 static int scp_has_times
;
851 static struct fxp_handle
*scp_sftp_filehandle
;
852 static uint64 scp_sftp_fileoffset
;
854 void scp_source_setup(char *target
, int shouldbedir
)
858 * Find out whether the target filespec is in fact a
861 struct fxp_attrs attrs
;
863 if (!fxp_stat(target
, &attrs
) ||
864 !(attrs
.flags
& SSH_FILEXFER_ATTR_PERMISSIONS
))
865 scp_sftp_targetisdir
= 0;
867 scp_sftp_targetisdir
= (attrs
.permissions
& 0040000) != 0;
869 if (shouldbedir
&& !scp_sftp_targetisdir
) {
870 bump("pscp: remote filespec %s: not a directory\n", target
);
873 scp_sftp_remotepath
= dupstr(target
);
881 int scp_send_errmsg(char *str
)
884 /* do nothing; we never need to send our errors to the server */
886 back
->send("\001", 1); /* scp protocol error prefix */
887 back
->send(str
, strlen(str
));
889 return 0; /* can't fail */
892 int scp_send_filetimes(unsigned long mtime
, unsigned long atime
)
895 scp_sftp_mtime
= mtime
;
896 scp_sftp_atime
= atime
;
901 sprintf(buf
, "T%lu 0 %lu 0\n", mtime
, atime
);
902 back
->send(buf
, strlen(buf
));
907 int scp_send_filename(char *name
, unsigned long size
, int modes
)
911 if (scp_sftp_targetisdir
) {
912 fullname
= dupcat(scp_sftp_remotepath
, "/", name
, NULL
);
914 fullname
= dupstr(scp_sftp_remotepath
);
916 scp_sftp_filehandle
=
917 fxp_open(fullname
, SSH_FXF_WRITE
| SSH_FXF_CREAT
| SSH_FXF_TRUNC
);
918 if (!scp_sftp_filehandle
) {
919 tell_user(stderr
, "pscp: unable to open %s: %s",
920 fullname
, fxp_error());
924 scp_sftp_fileoffset
= uint64_make(0, 0);
929 sprintf(buf
, "C%04o %lu ", modes
, size
);
930 back
->send(buf
, strlen(buf
));
931 back
->send(name
, strlen(name
));
937 int scp_send_filedata(char *data
, int len
)
940 if (!scp_sftp_filehandle
) {
943 if (!fxp_write(scp_sftp_filehandle
, data
, scp_sftp_fileoffset
, len
)) {
944 tell_user(stderr
, "error while writing: %s\n", fxp_error());
948 scp_sftp_fileoffset
= uint64_add32(scp_sftp_fileoffset
, len
);
951 int bufsize
= back
->send(data
, len
);
954 * If the network transfer is backing up - that is, the
955 * remote site is not accepting data as fast as we can
956 * produce it - then we must loop on network events until
957 * we have space in the buffer again.
959 while (bufsize
> MAX_SCP_BUFSIZE
) {
960 if (!scp_process_network_event())
962 bufsize
= back
->sendbuffer();
969 int scp_send_finish(void)
972 struct fxp_attrs attrs
;
973 if (!scp_sftp_filehandle
) {
977 attrs
.flags
= SSH_FILEXFER_ATTR_ACMODTIME
;
978 attrs
.atime
= scp_sftp_atime
;
979 attrs
.mtime
= scp_sftp_mtime
;
980 if (!fxp_fsetstat(scp_sftp_filehandle
, attrs
)) {
981 tell_user(stderr
, "unable to set file times: %s\n", fxp_error());
985 fxp_close(scp_sftp_filehandle
);
994 char *scp_save_remotepath(void)
997 return scp_sftp_remotepath
;
1002 void scp_restore_remotepath(char *data
)
1005 scp_sftp_remotepath
= data
;
1008 int scp_send_dirname(char *name
, int modes
)
1013 struct fxp_attrs attrs
;
1014 if (scp_sftp_targetisdir
) {
1015 fullname
= dupcat(scp_sftp_remotepath
, "/", name
, NULL
);
1017 fullname
= dupstr(scp_sftp_remotepath
);
1021 * We don't worry about whether we managed to create the
1022 * directory, because if it exists already it's OK just to
1023 * use it. Instead, we will stat it afterwards, and if it
1024 * exists and is a directory we will assume we were either
1025 * successful or it didn't matter.
1027 if (!fxp_mkdir(fullname
))
1030 err
= "server reported no error";
1031 if (!fxp_stat(fullname
, &attrs
) ||
1032 !(attrs
.flags
& SSH_FILEXFER_ATTR_PERMISSIONS
) ||
1033 !(attrs
.permissions
& 0040000)) {
1034 tell_user(stderr
, "unable to create directory %s: %s",
1040 scp_sftp_remotepath
= fullname
;
1045 sprintf(buf
, "D%04o 0 ", modes
);
1046 back
->send(buf
, strlen(buf
));
1047 back
->send(name
, strlen(name
));
1048 back
->send("\n", 1);
1053 int scp_send_enddir(void)
1056 sfree(scp_sftp_remotepath
);
1059 back
->send("E\n", 2);
1065 * Yes, I know; I have an scp_sink_setup _and_ an scp_sink_init.
1066 * That's bad. The difference is that scp_sink_setup is called once
1067 * right at the start, whereas scp_sink_init is called to
1068 * initialise every level of recursion in the protocol.
1070 int scp_sink_setup(char *source
, int preserve
, int recursive
)
1075 * It's possible that the source string we've been given
1076 * contains a wildcard. If so, we must split the directory
1077 * away from the wildcard itself (throwing an error if any
1078 * wildcardness comes before the final slash) and arrange
1079 * things so that a dirstack entry will be set up.
1081 newsource
= smalloc(1+strlen(source
));
1082 if (!wc_unescape(newsource
, source
)) {
1083 /* Yes, here we go; it's a wildcard. Bah. */
1084 char *dupsource
, *lastpart
, *dirpart
, *wildcard
;
1085 dupsource
= dupstr(source
);
1086 lastpart
= stripslashes(dupsource
, 0);
1087 wildcard
= dupstr(lastpart
);
1089 if (*dupsource
&& dupsource
[1]) {
1091 * The remains of dupsource are at least two
1092 * characters long, meaning the pathname wasn't
1093 * empty or just `/'. Hence, we remove the trailing
1096 lastpart
[-1] = '\0';
1097 } else if (!*dupsource
) {
1099 * The remains of dupsource are _empty_ - the whole
1100 * pathname was a wildcard. Hence we need to
1101 * replace it with ".".
1104 dupsource
= dupstr(".");
1108 * Now we have separated our string into dupsource (the
1109 * directory part) and wildcard. Both of these will
1110 * need freeing at some point. Next step is to remove
1111 * wildcard escapes from the directory part, throwing
1112 * an error if it contains a real wildcard.
1114 dirpart
= smalloc(1+strlen(dupsource
));
1115 if (!wc_unescape(dirpart
, dupsource
)) {
1116 tell_user(stderr
, "%s: multiple-level wildcards unsupported",
1126 * Now we have dirpart (unescaped, ie a valid remote
1127 * path), and wildcard (a wildcard). This will be
1128 * sufficient to arrange a dirstack entry.
1130 scp_sftp_remotepath
= dirpart
;
1131 scp_sftp_wildcard
= wildcard
;
1134 scp_sftp_remotepath
= newsource
;
1135 scp_sftp_wildcard
= NULL
;
1137 scp_sftp_preserve
= preserve
;
1138 scp_sftp_recursive
= recursive
;
1139 scp_sftp_donethistarget
= 0;
1140 scp_sftp_dirstack_head
= NULL
;
1145 int scp_sink_init(void)
1153 #define SCP_SINK_FILE 1
1154 #define SCP_SINK_DIR 2
1155 #define SCP_SINK_ENDDIR 3
1156 #define SCP_SINK_RETRY 4 /* not an action; just try again */
1157 struct scp_sink_action
{
1158 int action
; /* FILE, DIR, ENDDIR */
1159 char *buf
; /* will need freeing after use */
1160 char *name
; /* filename or dirname (not ENDDIR) */
1161 int mode
; /* access mode (not ENDDIR) */
1162 unsigned long size
; /* file size (not ENDDIR) */
1163 int settime
; /* 1 if atime and mtime are filled */
1164 unsigned long atime
, mtime
; /* access times for the file */
1167 int scp_get_sink_action(struct scp_sink_action
*act
)
1171 int must_free_fname
;
1172 struct fxp_attrs attrs
;
1175 if (!scp_sftp_dirstack_head
) {
1176 if (!scp_sftp_donethistarget
) {
1178 * Simple case: we are only dealing with one file.
1180 fname
= scp_sftp_remotepath
;
1181 must_free_fname
= 0;
1182 scp_sftp_donethistarget
= 1;
1185 * Even simpler case: one file _which we've done_.
1186 * Return 1 (finished).
1192 * We're now in the middle of stepping through a list
1193 * of names returned from fxp_readdir(); so let's carry
1196 struct scp_sftp_dirstack
*head
= scp_sftp_dirstack_head
;
1197 while (head
->namepos
< head
->namelen
&&
1198 (is_dots(head
->names
[head
->namepos
].filename
) ||
1200 !wc_match(head
->wildcard
,
1201 head
->names
[head
->namepos
].filename
))))
1202 head
->namepos
++; /* skip . and .. */
1203 if (head
->namepos
< head
->namelen
) {
1204 fname
= dupcat(head
->dirpath
, "/",
1205 head
->names
[head
->namepos
++].filename
,
1207 must_free_fname
= 1;
1210 * We've come to the end of the list; pop it off
1211 * the stack and return an ENDDIR action (or RETRY
1212 * if this was a wildcard match).
1214 if (head
->wildcard
) {
1215 act
->action
= SCP_SINK_RETRY
;
1216 sfree(head
->wildcard
);
1218 act
->action
= SCP_SINK_ENDDIR
;
1221 sfree(head
->dirpath
);
1223 scp_sftp_dirstack_head
= head
->next
;
1231 * Now we have a filename. Stat it, and see if it's a file
1234 ret
= fxp_stat(fname
, &attrs
);
1235 if (!ret
|| !(attrs
.flags
& SSH_FILEXFER_ATTR_PERMISSIONS
)) {
1236 tell_user(stderr
, "unable to identify %s: %s", fname
,
1237 ret ?
"file type not supplied" : fxp_error());
1242 if (attrs
.permissions
& 0040000) {
1243 struct scp_sftp_dirstack
*newitem
;
1244 struct fxp_handle
*dirhandle
;
1245 int nnames
, namesize
;
1246 struct fxp_name
*ournames
;
1247 struct fxp_names
*names
;
1250 * It's a directory. If we're not in recursive mode,
1251 * this merits a complaint (which is fatal if the name
1252 * was specified directly, but not if it was matched by
1255 * We skip this complaint completely if
1256 * scp_sftp_wildcard is set, because that's an
1257 * indication that we're not actually supposed to
1258 * _recursively_ transfer the dir, just scan it for
1259 * things matching the wildcard.
1261 if (!scp_sftp_recursive
&& !scp_sftp_wildcard
) {
1262 tell_user(stderr
, "pscp: %s: is a directory", fname
);
1264 if (must_free_fname
) sfree(fname
);
1265 if (scp_sftp_dirstack_head
) {
1266 act
->action
= SCP_SINK_RETRY
;
1274 * Otherwise, the fun begins. We must fxp_opendir() the
1275 * directory, slurp the filenames into memory, return
1276 * SCP_SINK_DIR (unless this is a wildcard match), and
1277 * set targetisdir. The next time we're called, we will
1278 * run through the list of filenames one by one,
1279 * matching them against a wildcard if present.
1281 * If targetisdir is _already_ set (meaning we're
1282 * already in the middle of going through another such
1283 * list), we must push the other (target,namelist) pair
1286 dirhandle
= fxp_opendir(fname
);
1288 tell_user(stderr
, "scp: unable to open directory %s: %s",
1289 fname
, fxp_error());
1290 if (must_free_fname
) sfree(fname
);
1294 nnames
= namesize
= 0;
1299 names
= fxp_readdir(dirhandle
);
1300 if (names
== NULL
) {
1301 if (fxp_error_type() == SSH_FX_EOF
)
1303 tell_user(stderr
, "scp: reading directory %s: %s\n",
1304 fname
, fxp_error());
1305 if (must_free_fname
) sfree(fname
);
1310 if (names
->nnames
== 0) {
1311 fxp_free_names(names
);
1314 if (nnames
+ names
->nnames
>= namesize
) {
1315 namesize
+= names
->nnames
+ 128;
1317 srealloc(ournames
, namesize
* sizeof(*ournames
));
1319 for (i
= 0; i
< names
->nnames
; i
++)
1320 ournames
[nnames
++] = names
->names
[i
];
1321 names
->nnames
= 0; /* prevent free_names */
1322 fxp_free_names(names
);
1324 fxp_close(dirhandle
);
1326 newitem
= smalloc(sizeof(struct scp_sftp_dirstack
));
1327 newitem
->next
= scp_sftp_dirstack_head
;
1328 newitem
->names
= ournames
;
1329 newitem
->namepos
= 0;
1330 newitem
->namelen
= nnames
;
1331 if (must_free_fname
)
1332 newitem
->dirpath
= fname
;
1334 newitem
->dirpath
= dupstr(fname
);
1335 if (scp_sftp_wildcard
) {
1336 newitem
->wildcard
= scp_sftp_wildcard
;
1337 scp_sftp_wildcard
= NULL
;
1339 newitem
->wildcard
= NULL
;
1341 scp_sftp_dirstack_head
= newitem
;
1343 if (newitem
->wildcard
) {
1344 act
->action
= SCP_SINK_RETRY
;
1346 act
->action
= SCP_SINK_DIR
;
1347 act
->buf
= dupstr(stripslashes(fname
, 0));
1348 act
->name
= act
->buf
;
1349 act
->size
= 0; /* duhh, it's a directory */
1350 act
->mode
= 07777 & attrs
.permissions
;
1351 if (scp_sftp_preserve
&&
1352 (attrs
.flags
& SSH_FILEXFER_ATTR_ACMODTIME
)) {
1353 act
->atime
= attrs
.atime
;
1354 act
->mtime
= attrs
.mtime
;
1363 * It's a file. Return SCP_SINK_FILE.
1365 act
->action
= SCP_SINK_FILE
;
1366 act
->buf
= dupstr(stripslashes(fname
, 0));
1367 act
->name
= act
->buf
;
1368 if (attrs
.flags
& SSH_FILEXFER_ATTR_SIZE
) {
1369 if (uint64_compare(attrs
.size
,
1370 uint64_make(0, ULONG_MAX
)) > 0) {
1371 act
->size
= ULONG_MAX
; /* *boggle* */
1373 act
->size
= attrs
.size
.lo
;
1375 act
->size
= ULONG_MAX
; /* no idea */
1376 act
->mode
= 07777 & attrs
.permissions
;
1377 if (scp_sftp_preserve
&&
1378 (attrs
.flags
& SSH_FILEXFER_ATTR_ACMODTIME
)) {
1379 act
->atime
= attrs
.atime
;
1380 act
->mtime
= attrs
.mtime
;
1384 if (must_free_fname
)
1385 scp_sftp_currentname
= fname
;
1387 scp_sftp_currentname
= dupstr(fname
);
1402 if (ssh_scp_recv(&ch
, 1) <= 0)
1405 bump("Protocol error: Unexpected newline");
1409 if (ssh_scp_recv(&ch
, 1) <= 0)
1410 bump("Lost connection");
1413 act
->buf
= srealloc(act
->buf
, bufsize
);
1416 } while (ch
!= '\n');
1417 act
->buf
[i
- 1] = '\0';
1419 case '\01': /* error */
1420 tell_user(stderr
, "%s\n", act
->buf
);
1422 continue; /* go round again */
1423 case '\02': /* fatal error */
1424 bump("%s", act
->buf
);
1427 act
->action
= SCP_SINK_ENDDIR
;
1430 if (sscanf(act
->buf
, "%ld %*d %ld %*d",
1431 &act
->mtime
, &act
->atime
) == 2) {
1434 continue; /* go round again */
1436 bump("Protocol error: Illegal time format");
1439 act
->action
= (action
== 'C' ? SCP_SINK_FILE
: SCP_SINK_DIR
);
1442 bump("Protocol error: Expected control record");
1445 * We will go round this loop only once, unless we hit
1452 * If we get here, we must have seen SCP_SINK_FILE or
1455 if (sscanf(act
->buf
, "%o %lu %n", &act
->mode
, &act
->size
, &i
) != 2)
1456 bump("Protocol error: Illegal file descriptor format");
1457 act
->name
= act
->buf
+ i
;
1462 int scp_accept_filexfer(void)
1465 scp_sftp_filehandle
=
1466 fxp_open(scp_sftp_currentname
, SSH_FXF_READ
);
1467 if (!scp_sftp_filehandle
) {
1468 tell_user(stderr
, "pscp: unable to open %s: %s",
1469 scp_sftp_currentname
, fxp_error());
1473 scp_sftp_fileoffset
= uint64_make(0, 0);
1474 sfree(scp_sftp_currentname
);
1478 return 0; /* can't fail */
1482 int scp_recv_filedata(char *data
, int len
)
1485 int actuallen
= fxp_read(scp_sftp_filehandle
, data
,
1486 scp_sftp_fileoffset
, len
);
1487 if (actuallen
== -1 && fxp_error_type() != SSH_FX_EOF
) {
1488 tell_user(stderr
, "pscp: error while reading: %s", fxp_error());
1495 scp_sftp_fileoffset
= uint64_add32(scp_sftp_fileoffset
, actuallen
);
1499 return ssh_scp_recv(data
, len
);
1503 int scp_finish_filerecv(void)
1506 fxp_close(scp_sftp_filehandle
);
1514 /* ----------------------------------------------------------------------
1515 * Send an error message to the other side and to the screen.
1516 * Increment error counter.
1518 static void run_err(const char *fmt
, ...)
1524 strcpy(str
, "scp: ");
1525 vsprintf(str
+ strlen(str
), fmt
, ap
);
1527 scp_send_errmsg(str
);
1528 tell_user(stderr
, "%s", str
);
1533 * Execute the source part of the SCP protocol.
1535 static void source(char *src
)
1542 unsigned long stat_bytes
;
1543 time_t stat_starttime
, stat_lasttime
;
1545 attr
= GetFileAttributes(src
);
1546 if (attr
== (DWORD
) - 1) {
1547 run_err("%s: No such file or directory", src
);
1551 if ((attr
& FILE_ATTRIBUTE_DIRECTORY
) != 0) {
1554 * Avoid . and .. directories.
1557 p
= strrchr(src
, '/');
1559 p
= strrchr(src
, '\\');
1564 if (!strcmp(p
, ".") || !strcmp(p
, ".."))
1565 /* skip . and .. */ ;
1569 run_err("%s: not a regular file", src
);
1574 if ((last
= strrchr(src
, '/')) == NULL
)
1578 if (strrchr(last
, '\\') != NULL
)
1579 last
= strrchr(last
, '\\') + 1;
1580 if (last
== src
&& strchr(src
, ':') != NULL
)
1581 last
= strchr(src
, ':') + 1;
1583 f
= CreateFile(src
, GENERIC_READ
, FILE_SHARE_READ
, NULL
,
1584 OPEN_EXISTING
, 0, 0);
1585 if (f
== INVALID_HANDLE_VALUE
) {
1586 run_err("%s: Cannot open file", src
);
1591 FILETIME actime
, wrtime
;
1592 unsigned long mtime
, atime
;
1593 GetFileTime(f
, NULL
, &actime
, &wrtime
);
1594 TIME_WIN_TO_POSIX(actime
, atime
);
1595 TIME_WIN_TO_POSIX(wrtime
, mtime
);
1596 if (scp_send_filetimes(mtime
, atime
))
1600 size
= GetFileSize(f
, NULL
);
1602 tell_user(stderr
, "Sending file %s, size=%lu", last
, size
);
1603 if (scp_send_filename(last
, size
, 0644))
1607 stat_starttime
= time(NULL
);
1610 for (i
= 0; i
< size
; i
+= 4096) {
1611 char transbuf
[4096];
1616 if (!ReadFile(f
, transbuf
, k
, &j
, NULL
) || j
!= k
) {
1619 bump("%s: Read error", src
);
1621 if (scp_send_filedata(transbuf
, k
))
1622 bump("%s: Network error occurred", src
);
1626 if (time(NULL
) != stat_lasttime
|| i
+ k
== size
) {
1627 stat_lasttime
= time(NULL
);
1628 print_stats(last
, size
, stat_bytes
,
1629 stat_starttime
, stat_lasttime
);
1636 (void) scp_send_finish();
1640 * Recursively send the contents of a directory.
1642 static void rsource(char *src
)
1644 char *last
, *findfile
;
1647 WIN32_FIND_DATA fdat
;
1650 if ((last
= strrchr(src
, '/')) == NULL
)
1654 if (strrchr(last
, '\\') != NULL
)
1655 last
= strrchr(last
, '\\') + 1;
1656 if (last
== src
&& strchr(src
, ':') != NULL
)
1657 last
= strchr(src
, ':') + 1;
1659 /* maybe send filetime */
1661 save_target
= scp_save_remotepath();
1664 tell_user(stderr
, "Entering directory: %s", last
);
1665 if (scp_send_dirname(last
, 0755))
1668 findfile
= dupcat(src
, "/*", NULL
);
1669 dir
= FindFirstFile(findfile
, &fdat
);
1670 ok
= (dir
!= INVALID_HANDLE_VALUE
);
1672 if (strcmp(fdat
.cFileName
, ".") == 0 ||
1673 strcmp(fdat
.cFileName
, "..") == 0) {
1674 /* ignore . and .. */
1676 char *foundfile
= dupcat(src
, "/", fdat
.cFileName
, NULL
);
1680 ok
= FindNextFile(dir
, &fdat
);
1685 (void) scp_send_enddir();
1687 scp_restore_remotepath(save_target
);
1691 * Execute the sink part of the SCP protocol.
1693 static void sink(char *targ
, char *src
)
1700 unsigned long received
;
1702 unsigned long stat_bytes
;
1703 time_t stat_starttime
, stat_lasttime
;
1706 attr
= GetFileAttributes(targ
);
1707 if (attr
!= (DWORD
) - 1 && (attr
& FILE_ATTRIBUTE_DIRECTORY
) != 0)
1710 if (targetshouldbedirectory
&& !targisdir
)
1711 bump("%s: Not a directory", targ
);
1715 struct scp_sink_action act
;
1716 if (scp_get_sink_action(&act
))
1719 if (act
.action
== SCP_SINK_ENDDIR
)
1722 if (act
.action
== SCP_SINK_RETRY
)
1727 * Prevent the remote side from maliciously writing to
1728 * files outside the target area by sending a filename
1729 * containing `../'. In fact, it shouldn't be sending
1730 * filenames with any slashes or colons in at all; so
1731 * we'll find the last slash, backslash or colon in the
1732 * filename and use only the part after that. (And
1735 * In addition, we also ensure here that if we're
1736 * copying a single file and the target is a directory
1737 * (common usage: `pscp host:filename .') the remote
1738 * can't send us a _different_ file name. We can
1739 * distinguish this case because `src' will be non-NULL
1740 * and the last component of that will fail to match
1741 * (the last component of) the name sent.
1743 * Well, not always; if `src' is a wildcard, we do
1744 * expect to get back filenames that don't correspond
1745 * exactly to it. Ideally in this case, we would like
1746 * to ensure that the returned filename actually
1747 * matches the wildcard pattern - but one of SCP's
1748 * protocol infelicities is that wildcard matching is
1749 * done at the server end _by the server's rules_ and
1750 * so in general this is infeasible. Hence, we only
1751 * accept filenames that don't correspond to `src' if
1752 * unsafe mode is enabled or we are using SFTP (which
1753 * resolves remote wildcards on the client side and can
1756 char *striptarget
, *stripsrc
;
1758 striptarget
= stripslashes(act
.name
, 1);
1759 if (striptarget
!= act
.name
) {
1760 tell_user(stderr
, "warning: remote host sent a compound"
1761 " pathname '%s'", act
.name
);
1762 tell_user(stderr
, " renaming local file to '%s'",
1767 * Also check to see if the target filename is '.' or
1768 * '..', or indeed '...' and so on because Windows
1769 * appears to interpret those like '..'.
1771 if (is_dots(striptarget
)) {
1772 bump("security violation: remote host attempted to write to"
1773 " a '.' or '..' path!");
1777 stripsrc
= stripslashes(src
, 1);
1778 if (strcmp(striptarget
, stripsrc
) &&
1779 !using_sftp
&& !scp_unsafe_mode
) {
1780 tell_user(stderr
, "warning: remote host tried to write "
1781 "to a file called '%s'", striptarget
);
1782 tell_user(stderr
, " when we requested a file "
1783 "called '%s'.", stripsrc
);
1784 tell_user(stderr
, " If this is a wildcard, "
1785 "consider upgrading to SSH 2 or using");
1786 tell_user(stderr
, " the '-unsafe' option. Renaming"
1787 " of this file has been disallowed.");
1788 /* Override the name the server provided with our own. */
1789 striptarget
= stripsrc
;
1793 if (targ
[0] != '\0')
1794 destfname
= dupcat(targ
, "\\", striptarget
, NULL
);
1796 destfname
= dupstr(striptarget
);
1799 * In this branch of the if, the target area is a
1800 * single file with an explicitly specified name in any
1801 * case, so there's no danger.
1803 destfname
= dupstr(targ
);
1805 attr
= GetFileAttributes(destfname
);
1806 exists
= (attr
!= (DWORD
) - 1);
1808 if (act
.action
== SCP_SINK_DIR
) {
1809 if (exists
&& (attr
& FILE_ATTRIBUTE_DIRECTORY
) == 0) {
1810 run_err("%s: Not a directory", destfname
);
1814 if (!CreateDirectory(destfname
, NULL
)) {
1815 run_err("%s: Cannot create directory", destfname
);
1819 sink(destfname
, NULL
);
1820 /* can we set the timestamp for directories ? */
1824 f
= CreateFile(destfname
, GENERIC_WRITE
, 0, NULL
,
1825 CREATE_ALWAYS
, FILE_ATTRIBUTE_NORMAL
, 0);
1826 if (f
== INVALID_HANDLE_VALUE
) {
1827 run_err("%s: Cannot create file", destfname
);
1831 if (scp_accept_filexfer())
1835 stat_starttime
= time(NULL
);
1837 stat_name
= stripslashes(destfname
, 1);
1840 while (received
< act
.size
) {
1841 char transbuf
[4096];
1842 DWORD blksize
, read
, written
;
1844 if (blksize
> act
.size
- received
)
1845 blksize
= act
.size
- received
;
1846 read
= scp_recv_filedata(transbuf
, blksize
);
1848 bump("Lost connection");
1851 if (!WriteFile(f
, transbuf
, read
, &written
, NULL
) ||
1854 /* FIXME: in sftp we can actually abort the transfer */
1856 printf("\r%-25.25s | %50s\n",
1858 "Write error.. waiting for end of file");
1863 if (time(NULL
) > stat_lasttime
||
1864 received
+ read
== act
.size
) {
1865 stat_lasttime
= time(NULL
);
1866 print_stats(stat_name
, act
.size
, stat_bytes
,
1867 stat_starttime
, stat_lasttime
);
1873 FILETIME actime
, wrtime
;
1874 TIME_POSIX_TO_WIN(act
.atime
, actime
);
1875 TIME_POSIX_TO_WIN(act
.mtime
, wrtime
);
1876 SetFileTime(f
, NULL
, &actime
, &wrtime
);
1881 run_err("%s: Write error", destfname
);
1884 (void) scp_finish_filerecv();
1891 * We will copy local files to a remote server.
1893 static void toremote(int argc
, char *argv
[])
1895 char *src
, *targ
, *host
, *user
;
1899 targ
= argv
[argc
- 1];
1901 /* Separate host from filename */
1905 bump("targ == NULL in toremote()");
1909 /* Substitute "." for emtpy target */
1911 /* Separate host and username */
1913 host
= strrchr(host
, '@');
1924 /* Find out if the source filespec covers multiple files
1925 if so, we should set the targetshouldbedirectory flag */
1927 WIN32_FIND_DATA fdat
;
1928 if (colon(argv
[0]) != NULL
)
1929 bump("%s: Remote to remote not supported", argv
[0]);
1930 fh
= FindFirstFile(argv
[0], &fdat
);
1931 if (fh
== INVALID_HANDLE_VALUE
)
1932 bump("%s: No such file or directory\n", argv
[0]);
1933 if (FindNextFile(fh
, &fdat
))
1934 targetshouldbedirectory
= 1;
1938 cmd
= smalloc(strlen(targ
) + 100);
1939 sprintf(cmd
, "scp%s%s%s%s -t %s",
1940 verbose ?
" -v" : "",
1941 recursive ?
" -r" : "",
1942 preserve ?
" -p" : "",
1943 targetshouldbedirectory ?
" -d" : "", targ
);
1944 do_cmd(host
, user
, cmd
);
1947 scp_source_setup(targ
, targetshouldbedirectory
);
1949 for (i
= 0; i
< argc
- 1; i
++) {
1950 char *srcpath
, *last
;
1952 WIN32_FIND_DATA fdat
;
1954 if (colon(src
) != NULL
) {
1955 tell_user(stderr
, "%s: Remote to remote not supported\n", src
);
1961 * Trim off the last pathname component of `src', to
1962 * provide the base pathname which will be prepended to
1963 * filenames returned from Find{First,Next}File.
1965 srcpath
= dupstr(src
);
1966 last
= stripslashes(srcpath
, 1);
1969 dir
= FindFirstFile(src
, &fdat
);
1970 if (dir
== INVALID_HANDLE_VALUE
) {
1971 run_err("%s: No such file or directory", src
);
1977 * Ensure that . and .. are never matched by wildcards,
1978 * but only by deliberate action.
1980 if (!strcmp(fdat
.cFileName
, ".") ||
1981 !strcmp(fdat
.cFileName
, "..")) {
1983 * Find*File has returned a special dir. We require
1984 * that _either_ `src' ends in a backslash followed
1985 * by that string, _or_ `src' is precisely that
1988 int len
= strlen(src
), dlen
= strlen(fdat
.cFileName
);
1989 if (len
== dlen
&& !strcmp(src
, fdat
.cFileName
)) {
1991 } else if (len
> dlen
+ 1 && src
[len
- dlen
- 1] == '\\' &&
1992 !strcmp(src
+ len
- dlen
, fdat
.cFileName
)) {
1995 continue; /* ignore this one */
1997 filename
= dupcat(srcpath
, fdat
.cFileName
, NULL
);
2000 } while (FindNextFile(dir
, &fdat
));
2007 * We will copy files from a remote server to the local machine.
2009 static void tolocal(int argc
, char *argv
[])
2011 char *src
, *targ
, *host
, *user
;
2015 bump("More than one remote source not supported");
2020 /* Separate host from filename */
2024 bump("Local to local copy not supported");
2028 /* Substitute "." for empty filename */
2030 /* Separate username and hostname */
2032 host
= strrchr(host
, '@');
2042 cmd
= smalloc(strlen(src
) + 100);
2043 sprintf(cmd
, "scp%s%s%s%s -f %s",
2044 verbose ?
" -v" : "",
2045 recursive ?
" -r" : "",
2046 preserve ?
" -p" : "",
2047 targetshouldbedirectory ?
" -d" : "", src
);
2048 do_cmd(host
, user
, cmd
);
2051 if (scp_sink_setup(src
, preserve
, recursive
))
2058 * We will issue a list command to get a remote directory.
2060 static void get_dir_list(int argc
, char *argv
[])
2062 char *src
, *host
, *user
;
2068 /* Separate host from filename */
2072 bump("Local to local copy not supported");
2076 /* Substitute "." for empty filename */
2078 /* Separate username and hostname */
2080 host
= strrchr(host
, '@');
2090 cmd
= smalloc(4 * strlen(src
) + 100);
2091 strcpy(cmd
, "ls -la '");
2092 p
= cmd
+ strlen(cmd
);
2093 for (q
= src
; *q
; q
++) {
2106 do_cmd(host
, user
, cmd
);
2110 scp_sftp_listdir(src
);
2112 while (ssh_scp_recv(&c
, 1) > 0)
2113 tell_char(stdout
, c
);
2118 * Initialize the Win$ock driver.
2120 static void init_winsock(void)
2125 winsock_ver
= MAKEWORD(1, 1);
2126 if (WSAStartup(winsock_ver
, &wsadata
))
2127 bump("Unable to initialise WinSock");
2128 if (LOBYTE(wsadata
.wVersion
) != 1 || HIBYTE(wsadata
.wVersion
) != 1)
2129 bump("WinSock version is incompatible with 1.1");
2133 * Short description of parameters.
2135 static void usage(void)
2137 printf("PuTTY Secure Copy client\n");
2138 printf("%s\n", ver
);
2139 printf("Usage: pscp [options] [user@]host:source target\n");
2141 (" pscp [options] source [source...] [user@]host:target\n");
2142 printf(" pscp [options] -ls user@host:filespec\n");
2143 printf("Options:\n");
2144 printf(" -p preserve file attributes\n");
2145 printf(" -q quiet, don't show statistics\n");
2146 printf(" -r copy directories recursively\n");
2147 printf(" -v show verbose messages\n");
2148 printf(" -P port connect to specified port\n");
2149 printf(" -pw passw login with specified password\n");
2150 printf(" -unsafe allow server-side wildcards (DANGEROUS)\n");
2153 * -gui is an internal option, used by GUI front ends to get
2154 * pscp to pass progress reports back to them. It's not an
2155 * ordinary user-accessible option, so it shouldn't be part of
2156 * the command-line help. The only people who need to know
2157 * about it are programmers, and they can read the source.
2160 (" -gui hWnd GUI mode with the windows handle for receiving messages\n");
2166 * Main program (no, really?)
2168 int main(int argc
, char *argv
[])
2172 default_protocol
= PROT_TELNET
;
2174 flags
= FLAG_STDERR
;
2175 ssh_get_line
= &get_line
;
2179 for (i
= 1; i
< argc
; i
++) {
2180 if (argv
[i
][0] != '-')
2182 if (strcmp(argv
[i
], "-v") == 0)
2183 verbose
= 1, flags
|= FLAG_VERBOSE
;
2184 else if (strcmp(argv
[i
], "-r") == 0)
2186 else if (strcmp(argv
[i
], "-p") == 0)
2188 else if (strcmp(argv
[i
], "-q") == 0)
2190 else if (strcmp(argv
[i
], "-h") == 0 || strcmp(argv
[i
], "-?") == 0)
2192 else if (strcmp(argv
[i
], "-P") == 0 && i
+ 1 < argc
)
2193 portnumber
= atoi(argv
[++i
]);
2194 else if (strcmp(argv
[i
], "-pw") == 0 && i
+ 1 < argc
)
2195 password
= argv
[++i
];
2196 else if (strcmp(argv
[i
], "-gui") == 0 && i
+ 1 < argc
) {
2197 gui_hwnd
= argv
[++i
];
2199 } else if (strcmp(argv
[i
], "-ls") == 0)
2201 else if (strcmp(argv
[i
], "-unsafe") == 0)
2202 scp_unsafe_mode
= 1;
2203 else if (strcmp(argv
[i
], "--") == 0) {
2216 get_dir_list(argc
, argv
);
2223 targetshouldbedirectory
= 1;
2225 if (colon(argv
[argc
- 1]) != NULL
)
2226 toremote(argc
, argv
);
2228 tolocal(argc
, argv
);
2231 if (back
!= NULL
&& back
->socket() != NULL
) {
2233 back
->special(TS_EOF
);
2234 ssh_scp_recv(&ch
, 1);
2239 /* GUI Adaptation - August 2000 */
2241 unsigned int msg_id
= WM_RET_ERR_CNT
;
2243 msg_id
= WM_LS_RET_ERR_CNT
;
2245 ((HWND
) atoi(gui_hwnd
), msg_id
, (WPARAM
) errs
,
2246 0 /*lParam */ ))SleepEx(1000, TRUE
);
2248 return (errs
== 0 ?
0 : 1);