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.)
30 #define PUTTY_DO_GLOBALS
37 #define TIME_POSIX_TO_WIN(t, ft) (*(LONGLONG*)&(ft) = \
38 ((LONGLONG) (t) + (LONGLONG) 11644473600) * (LONGLONG) 10000000)
39 #define TIME_WIN_TO_POSIX(ft, t) ((t) = (unsigned long) \
40 ((*(LONGLONG*)&(ft)) / (LONGLONG) 10000000 - (LONGLONG) 11644473600))
42 /* GUI Adaptation - Sept 2000 */
43 #define WM_APP_BASE 0x8000
44 #define WM_STD_OUT_CHAR ( WM_APP_BASE+400 )
45 #define WM_STD_ERR_CHAR ( WM_APP_BASE+401 )
46 #define WM_STATS_CHAR ( WM_APP_BASE+402 )
47 #define WM_STATS_SIZE ( WM_APP_BASE+403 )
48 #define WM_STATS_PERCENT ( WM_APP_BASE+404 )
49 #define WM_STATS_ELAPSED ( WM_APP_BASE+405 )
50 #define WM_RET_ERR_CNT ( WM_APP_BASE+406 )
51 #define WM_LS_RET_ERR_CNT ( WM_APP_BASE+407 )
54 static int verbose
= 0;
55 static int recursive
= 0;
56 static int preserve
= 0;
57 static int targetshouldbedirectory
= 0;
58 static int statistics
= 1;
59 static int portnumber
= 0;
60 static int prev_stats_len
= 0;
61 static int scp_unsafe_mode
= 0;
62 static char *password
= NULL
;
64 /* GUI Adaptation - Sept 2000 */
65 #define NAME_STR_MAX 2048
66 static char statname
[NAME_STR_MAX
+ 1];
67 static unsigned long statsize
= 0;
68 static int statperct
= 0;
69 static unsigned long statelapsed
= 0;
70 static int gui_mode
= 0;
71 static char *gui_hwnd
= NULL
;
72 static int using_sftp
= 0;
74 static void source(char *src
);
75 static void rsource(char *src
);
76 static void sink(char *targ
, char *src
);
77 /* GUI Adaptation - Sept 2000 */
78 static void tell_char(FILE * stream
, char c
);
79 static void tell_str(FILE * stream
, char *str
);
80 static void tell_user(FILE * stream
, char *fmt
, ...);
81 static void gui_update_stats(char *name
, unsigned long size
,
82 int percentage
, unsigned long elapsed
);
85 * The maximum amount of queued data we accept before we stop and
86 * wait for the server to process some.
88 #define MAX_SCP_BUFSIZE 16384
90 void logevent(char *string
)
94 void ldisc_send(char *buf
, int len
)
97 * This is only here because of the calls to ldisc_send(NULL,
98 * 0) in ssh.c. Nothing in PSCP actually needs to use the ldisc
99 * as an ldisc. So if we get called with any real data, I want
105 void verify_ssh_host_key(char *host
, int port
, char *keytype
,
106 char *keystr
, char *fingerprint
)
112 static const char absentmsg
[] =
113 "The server's host key is not cached in the registry. You\n"
114 "have no guarantee that the server is the computer you\n"
116 "The server's key fingerprint is:\n"
118 "If you trust this host, enter \"y\" to add the key to\n"
119 "PuTTY's cache and carry on connecting.\n"
120 "If you want to carry on connecting just once, without\n"
121 "adding the key to the cache, enter \"n\".\n"
122 "If you do not trust this host, press Return to abandon the\n"
124 "Store key in cache? (y/n) ";
126 static const char wrongmsg
[] =
127 "WARNING - POTENTIAL SECURITY BREACH!\n"
128 "The server's host key does not match the one PuTTY has\n"
129 "cached in the registry. This means that either the\n"
130 "server administrator has changed the host key, or you\n"
131 "have actually connected to another computer pretending\n"
132 "to be the server.\n"
133 "The new key fingerprint is:\n"
135 "If you were expecting this change and trust the new key,\n"
136 "enter \"y\" to update PuTTY's cache and continue connecting.\n"
137 "If you want to carry on connecting but without updating\n"
138 "the cache, enter \"n\".\n"
139 "If you want to abandon the connection completely, press\n"
140 "Return to cancel. Pressing Return is the ONLY guaranteed\n"
142 "Update cached key? (y/n, Return cancels connection) ";
144 static const char abandoned
[] = "Connection abandoned.\n";
149 * Verify the key against the registry.
151 ret
= verify_host_key(host
, port
, keytype
, keystr
);
153 if (ret
== 0) /* success - key matched OK */
156 if (ret
== 2) { /* key was different */
157 fprintf(stderr
, wrongmsg
, fingerprint
);
160 if (ret
== 1) { /* key was absent */
161 fprintf(stderr
, absentmsg
, fingerprint
);
165 hin
= GetStdHandle(STD_INPUT_HANDLE
);
166 GetConsoleMode(hin
, &savemode
);
167 SetConsoleMode(hin
, (savemode
| ENABLE_ECHO_INPUT
|
168 ENABLE_PROCESSED_INPUT
| ENABLE_LINE_INPUT
));
169 ReadFile(hin
, line
, sizeof(line
) - 1, &i
, NULL
);
170 SetConsoleMode(hin
, savemode
);
172 if (line
[0] != '\0' && line
[0] != '\r' && line
[0] != '\n') {
173 if (line
[0] == 'y' || line
[0] == 'Y')
174 store_host_key(host
, port
, keytype
, keystr
);
176 fprintf(stderr
, abandoned
);
182 * Ask whether the selected cipher is acceptable (since it was
183 * below the configured 'warn' threshold).
184 * cs: 0 = both ways, 1 = client->server, 2 = server->client
186 void askcipher(char *ciphername
, int cs
)
191 static const char msg
[] =
192 "The first %scipher supported by the server is\n"
193 "%s, which is below the configured warning threshold.\n"
194 "Continue with connection? (y/n) ";
195 static const char abandoned
[] = "Connection abandoned.\n";
201 (cs
== 1) ?
"client-to-server " :
206 hin
= GetStdHandle(STD_INPUT_HANDLE
);
207 GetConsoleMode(hin
, &savemode
);
208 SetConsoleMode(hin
, (savemode
| ENABLE_ECHO_INPUT
|
209 ENABLE_PROCESSED_INPUT
| ENABLE_LINE_INPUT
));
210 ReadFile(hin
, line
, sizeof(line
) - 1, &i
, NULL
);
211 SetConsoleMode(hin
, savemode
);
213 if (line
[0] == 'y' || line
[0] == 'Y') {
216 fprintf(stderr
, abandoned
);
221 /* GUI Adaptation - Sept 2000 */
222 static void send_msg(HWND h
, UINT message
, WPARAM wParam
)
224 while (!PostMessage(h
, message
, wParam
, 0))
228 static void tell_char(FILE * stream
, char c
)
233 unsigned int msg_id
= WM_STD_OUT_CHAR
;
234 if (stream
== stderr
)
235 msg_id
= WM_STD_ERR_CHAR
;
236 send_msg((HWND
) atoi(gui_hwnd
), msg_id
, (WPARAM
) c
);
240 static void tell_str(FILE * stream
, char *str
)
244 for (i
= 0; i
< strlen(str
); ++i
)
245 tell_char(stream
, str
[i
]);
248 static void tell_user(FILE * stream
, char *fmt
, ...)
250 char str
[0x100]; /* Make the size big enough */
253 vsprintf(str
, fmt
, ap
);
256 tell_str(stream
, str
);
259 static void gui_update_stats(char *name
, unsigned long size
,
260 int percentage
, unsigned long elapsed
)
264 if (strcmp(name
, statname
) != 0) {
265 for (i
= 0; i
< strlen(name
); ++i
)
266 send_msg((HWND
) atoi(gui_hwnd
), WM_STATS_CHAR
,
268 send_msg((HWND
) atoi(gui_hwnd
), WM_STATS_CHAR
, (WPARAM
) '\n');
269 strcpy(statname
, name
);
271 if (statsize
!= size
) {
272 send_msg((HWND
) atoi(gui_hwnd
), WM_STATS_SIZE
, (WPARAM
) size
);
275 if (statelapsed
!= elapsed
) {
276 send_msg((HWND
) atoi(gui_hwnd
), WM_STATS_ELAPSED
,
278 statelapsed
= elapsed
;
280 if (statperct
!= percentage
) {
281 send_msg((HWND
) atoi(gui_hwnd
), WM_STATS_PERCENT
,
282 (WPARAM
) percentage
);
283 statperct
= percentage
;
288 * Print an error message and perform a fatal exit.
290 void fatalbox(char *fmt
, ...)
292 char str
[0x100]; /* Make the size big enough */
295 strcpy(str
, "Fatal: ");
296 vsprintf(str
+ strlen(str
), fmt
, ap
);
299 tell_str(stderr
, str
);
303 unsigned int msg_id
= WM_RET_ERR_CNT
;
305 msg_id
= WM_LS_RET_ERR_CNT
;
307 ((HWND
) atoi(gui_hwnd
), msg_id
, (WPARAM
) errs
,
308 0 /*lParam */ ))SleepEx(1000, TRUE
);
313 void connection_fatal(char *fmt
, ...)
315 char str
[0x100]; /* Make the size big enough */
318 strcpy(str
, "Fatal: ");
319 vsprintf(str
+ strlen(str
), fmt
, ap
);
322 tell_str(stderr
, str
);
326 unsigned int msg_id
= WM_RET_ERR_CNT
;
328 msg_id
= WM_LS_RET_ERR_CNT
;
330 ((HWND
) atoi(gui_hwnd
), msg_id
, (WPARAM
) errs
,
331 0 /*lParam */ ))SleepEx(1000, TRUE
);
338 * Be told what socket we're supposed to be using.
340 static SOCKET scp_ssh_socket
;
341 char *do_select(SOCKET skt
, int startup
)
344 scp_ssh_socket
= skt
;
346 scp_ssh_socket
= INVALID_SOCKET
;
349 extern int select_result(WPARAM
, LPARAM
);
352 * Receive a block of data from the SSH link. Block until all data
355 * To do this, we repeatedly call the SSH protocol module, with our
356 * own trap in from_backend() to catch the data that comes back. We
357 * do this until we have enough data.
360 static unsigned char *outptr
; /* where to put the data */
361 static unsigned outlen
; /* how much data required */
362 static unsigned char *pending
= NULL
; /* any spare data */
363 static unsigned pendlen
= 0, pendsize
= 0; /* length and phys. size of buffer */
364 int from_backend(int is_stderr
, char *data
, int datalen
)
366 unsigned char *p
= (unsigned char *) data
;
367 unsigned len
= (unsigned) datalen
;
370 * stderr data is just spouted to local stderr and otherwise
374 fwrite(data
, 1, len
, stderr
);
381 * If this is before the real session begins, just return.
387 unsigned used
= outlen
;
390 memcpy(outptr
, p
, used
);
398 if (pendsize
< pendlen
+ len
) {
399 pendsize
= pendlen
+ len
+ 4096;
400 pending
= (pending ?
srealloc(pending
, pendsize
) :
403 fatalbox("Out of memory");
405 memcpy(pending
+ pendlen
, p
, len
);
411 static int scp_process_network_event(void)
416 FD_SET(scp_ssh_socket
, &readfds
);
417 if (select(1, &readfds
, NULL
, NULL
, NULL
) < 0)
419 select_result((WPARAM
) scp_ssh_socket
, (LPARAM
) FD_READ
);
422 static int ssh_scp_recv(unsigned char *buf
, int len
)
428 * See if the pending-input block contains some of what we
432 unsigned pendused
= pendlen
;
433 if (pendused
> outlen
)
435 memcpy(outptr
, pending
, pendused
);
436 memmove(pending
, pending
+ pendused
, pendlen
- pendused
);
450 if (!scp_process_network_event())
458 * Loop through the ssh connection and authentication process.
460 static void ssh_scp_init(void)
462 if (scp_ssh_socket
== INVALID_SOCKET
)
464 while (!back
->sendok()) {
467 FD_SET(scp_ssh_socket
, &readfds
);
468 if (select(1, &readfds
, NULL
, NULL
, NULL
) < 0)
470 select_result((WPARAM
) scp_ssh_socket
, (LPARAM
) FD_READ
);
472 using_sftp
= !ssh_fallback_cmd
;
476 * Print an error message and exit after closing the SSH link.
478 static void bump(char *fmt
, ...)
480 char str
[0x100]; /* Make the size big enough */
483 strcpy(str
, "Fatal: ");
484 vsprintf(str
+ strlen(str
), fmt
, ap
);
487 tell_str(stderr
, str
);
490 if (back
!= NULL
&& back
->socket() != NULL
) {
492 back
->special(TS_EOF
);
493 ssh_scp_recv(&ch
, 1);
497 unsigned int msg_id
= WM_RET_ERR_CNT
;
499 msg_id
= WM_LS_RET_ERR_CNT
;
501 ((HWND
) atoi(gui_hwnd
), msg_id
, (WPARAM
) errs
,
502 0 /*lParam */ ))SleepEx(1000, TRUE
);
508 static int get_line(const char *prompt
, char *str
, int maxlen
, int is_pw
)
511 DWORD savemode
, newmode
, i
;
513 if (is_pw
&& password
) {
514 static int tried_once
= 0;
519 strncpy(str
, password
, maxlen
);
520 str
[maxlen
- 1] = '\0';
526 /* GUI Adaptation - Sept 2000 */
531 hin
= GetStdHandle(STD_INPUT_HANDLE
);
532 hout
= GetStdHandle(STD_OUTPUT_HANDLE
);
533 if (hin
== INVALID_HANDLE_VALUE
|| hout
== INVALID_HANDLE_VALUE
)
534 bump("Cannot get standard input/output handles");
536 GetConsoleMode(hin
, &savemode
);
537 newmode
= savemode
| ENABLE_PROCESSED_INPUT
| ENABLE_LINE_INPUT
;
539 newmode
&= ~ENABLE_ECHO_INPUT
;
541 newmode
|= ENABLE_ECHO_INPUT
;
542 SetConsoleMode(hin
, newmode
);
544 WriteFile(hout
, prompt
, strlen(prompt
), &i
, NULL
);
545 ReadFile(hin
, str
, maxlen
- 1, &i
, NULL
);
547 SetConsoleMode(hin
, savemode
);
549 if ((int) i
> maxlen
)
556 WriteFile(hout
, "\r\n", 2, &i
, NULL
);
563 * Open an SSH connection to user@host and execute cmd.
565 static void do_cmd(char *host
, char *user
, char *cmd
)
567 char *err
, *realhost
;
570 if (host
== NULL
|| host
[0] == '\0')
571 bump("Empty host name");
573 /* Try to load settings for this host */
574 do_defaults(host
, &cfg
);
575 if (cfg
.host
[0] == '\0') {
576 /* No settings for this host; use defaults */
577 do_defaults(NULL
, &cfg
);
578 strncpy(cfg
.host
, host
, sizeof(cfg
.host
) - 1);
579 cfg
.host
[sizeof(cfg
.host
) - 1] = '\0';
584 if (user
!= NULL
&& user
[0] != '\0') {
585 strncpy(cfg
.username
, user
, sizeof(cfg
.username
) - 1);
586 cfg
.username
[sizeof(cfg
.username
) - 1] = '\0';
587 } else if (cfg
.username
[0] == '\0') {
589 if (GetUserName(user
, &namelen
) == FALSE
)
590 bump("Empty user name");
591 user
= smalloc(namelen
* sizeof(char));
592 GetUserName(user
, &namelen
);
594 tell_user(stderr
, "Guessing user name: %s", user
);
595 strncpy(cfg
.username
, user
, sizeof(cfg
.username
) - 1);
596 cfg
.username
[sizeof(cfg
.username
) - 1] = '\0';
600 if (cfg
.protocol
!= PROT_SSH
)
604 cfg
.port
= portnumber
;
607 * Attempt to start the SFTP subsystem as a first choice,
608 * falling back to the provided scp command if that fails.
610 strcpy(cfg
.remote_cmd
, "sftp");
611 cfg
.ssh_subsys
= TRUE
;
612 cfg
.remote_cmd_ptr2
= cmd
;
613 cfg
.ssh_subsys2
= FALSE
;
618 err
= back
->init(cfg
.host
, cfg
.port
, &realhost
);
620 bump("ssh_init: %s", err
);
622 if (verbose
&& realhost
!= NULL
)
623 tell_user(stderr
, "Connected to %s\n", realhost
);
628 * Update statistic information about current file.
630 static void print_stats(char *name
, unsigned long size
, unsigned long done
,
631 time_t start
, time_t now
)
639 /* GUI Adaptation - Sept 2000 */
641 gui_update_stats(name
, size
, (int) (100 * (done
* 1.0 / size
)),
642 (unsigned long) difftime(now
, start
));
645 ratebs
= (float) done
/ (now
- start
);
647 ratebs
= (float) done
;
652 eta
= (unsigned long) ((size
- done
) / ratebs
);
653 sprintf(etastr
, "%02ld:%02ld:%02ld",
654 eta
/ 3600, (eta
% 3600) / 60, eta
% 60);
656 pct
= (int) (100 * (done
* 1.0 / size
));
658 len
= printf("\r%-25.25s | %10ld kB | %5.1f kB/s | ETA: %8s | %3d%%",
659 name
, done
/ 1024, ratebs
/ 1024.0, etastr
, pct
);
660 if (len
< prev_stats_len
)
661 printf("%*s", prev_stats_len
- len
, "");
662 prev_stats_len
= len
;
670 * Find a colon in str and return a pointer to the colon.
671 * This is used to separate hostname from filename.
673 static char *colon(char *str
)
675 /* We ignore a leading colon, since the hostname cannot be
676 empty. We also ignore a colon as second character because
677 of filenames like f:myfile.txt. */
678 if (str
[0] == '\0' || str
[0] == ':' || str
[1] == ':')
680 while (*str
!= '\0' && *str
!= ':' && *str
!= '/' && *str
!= '\\')
689 * Return a pointer to the portion of str that comes after the last
690 * slash (or backslash or colon, if `local' is TRUE).
692 static char *stripslashes(char *str
, int local
)
697 p
= strchr(str
, ':');
701 p
= strrchr(str
, '/');
705 p
= strrchr(str
, '\\');
713 * Determine whether a string is entirely composed of dots.
715 static int is_dots(char *str
)
717 return str
[strspn(str
, ".")] == '\0';
721 * Wait for a response from the other side.
722 * Return 0 if ok, -1 if error.
724 static int response(void)
726 char ch
, resp
, rbuf
[2048];
729 if (ssh_scp_recv(&resp
, 1) <= 0)
730 bump("Lost connection");
740 case 2: /* fatal error */
742 if (ssh_scp_recv(&ch
, 1) <= 0)
743 bump("Protocol error: Lost connection");
745 } while (p
< sizeof(rbuf
) && ch
!= '\n');
748 tell_user(stderr
, "%s\n", rbuf
);
756 int sftp_recvdata(char *buf
, int len
)
758 return ssh_scp_recv(buf
, len
);
760 int sftp_senddata(char *buf
, int len
)
762 back
->send((unsigned char *) buf
, len
);
766 /* ----------------------------------------------------------------------
767 * sftp-based replacement for the hacky `pscp -ls'.
769 static int sftp_ls_compare(const void *av
, const void *bv
)
771 const struct fxp_name
*a
= (const struct fxp_name
*) av
;
772 const struct fxp_name
*b
= (const struct fxp_name
*) bv
;
773 return strcmp(a
->filename
, b
->filename
);
775 void scp_sftp_listdir(char *dirname
)
777 struct fxp_handle
*dirh
;
778 struct fxp_names
*names
;
779 struct fxp_name
*ournames
;
780 int nnames
, namesize
;
783 printf("Listing directory %s\n", dirname
);
785 dirh
= fxp_opendir(dirname
);
787 printf("Unable to open %s: %s\n", dirname
, fxp_error());
789 nnames
= namesize
= 0;
794 names
= fxp_readdir(dirh
);
796 if (fxp_error_type() == SSH_FX_EOF
)
798 printf("Reading directory %s: %s\n", dirname
, fxp_error());
801 if (names
->nnames
== 0) {
802 fxp_free_names(names
);
806 if (nnames
+ names
->nnames
>= namesize
) {
807 namesize
+= names
->nnames
+ 128;
809 srealloc(ournames
, namesize
* sizeof(*ournames
));
812 for (i
= 0; i
< names
->nnames
; i
++)
813 ournames
[nnames
++] = names
->names
[i
];
815 names
->nnames
= 0; /* prevent free_names */
816 fxp_free_names(names
);
821 * Now we have our filenames. Sort them by actual file
822 * name, and then output the longname parts.
824 qsort(ournames
, nnames
, sizeof(*ournames
), sftp_ls_compare
);
829 for (i
= 0; i
< nnames
; i
++)
830 printf("%s\n", ournames
[i
].longname
);
834 /* ----------------------------------------------------------------------
835 * Helper routines that contain the actual SCP protocol elements,
836 * implemented both as SCP1 and SFTP.
839 static struct scp_sftp_dirstack
{
840 struct scp_sftp_dirstack
*next
;
841 struct fxp_name
*names
;
842 int namepos
, namelen
;
845 int matched_something
; /* wildcard match set was non-empty */
846 } *scp_sftp_dirstack_head
;
847 static char *scp_sftp_remotepath
, *scp_sftp_currentname
;
848 static char *scp_sftp_wildcard
;
849 static int scp_sftp_targetisdir
, scp_sftp_donethistarget
;
850 static int scp_sftp_preserve
, scp_sftp_recursive
;
851 static unsigned long scp_sftp_mtime
, scp_sftp_atime
;
852 static int scp_has_times
;
853 static struct fxp_handle
*scp_sftp_filehandle
;
854 static uint64 scp_sftp_fileoffset
;
856 void scp_source_setup(char *target
, int shouldbedir
)
860 * Find out whether the target filespec is in fact a
863 struct fxp_attrs attrs
;
865 if (!fxp_stat(target
, &attrs
) ||
866 !(attrs
.flags
& SSH_FILEXFER_ATTR_PERMISSIONS
))
867 scp_sftp_targetisdir
= 0;
869 scp_sftp_targetisdir
= (attrs
.permissions
& 0040000) != 0;
871 if (shouldbedir
&& !scp_sftp_targetisdir
) {
872 bump("pscp: remote filespec %s: not a directory\n", target
);
875 scp_sftp_remotepath
= dupstr(target
);
883 int scp_send_errmsg(char *str
)
886 /* do nothing; we never need to send our errors to the server */
888 back
->send("\001", 1); /* scp protocol error prefix */
889 back
->send(str
, strlen(str
));
891 return 0; /* can't fail */
894 int scp_send_filetimes(unsigned long mtime
, unsigned long atime
)
897 scp_sftp_mtime
= mtime
;
898 scp_sftp_atime
= atime
;
903 sprintf(buf
, "T%lu 0 %lu 0\n", mtime
, atime
);
904 back
->send(buf
, strlen(buf
));
909 int scp_send_filename(char *name
, unsigned long size
, int modes
)
913 if (scp_sftp_targetisdir
) {
914 fullname
= dupcat(scp_sftp_remotepath
, "/", name
, NULL
);
916 fullname
= dupstr(scp_sftp_remotepath
);
918 scp_sftp_filehandle
=
919 fxp_open(fullname
, SSH_FXF_WRITE
| SSH_FXF_CREAT
| SSH_FXF_TRUNC
);
920 if (!scp_sftp_filehandle
) {
921 tell_user(stderr
, "pscp: unable to open %s: %s",
922 fullname
, fxp_error());
926 scp_sftp_fileoffset
= uint64_make(0, 0);
931 sprintf(buf
, "C%04o %lu ", modes
, size
);
932 back
->send(buf
, strlen(buf
));
933 back
->send(name
, strlen(name
));
939 int scp_send_filedata(char *data
, int len
)
942 if (!scp_sftp_filehandle
) {
945 if (!fxp_write(scp_sftp_filehandle
, data
, scp_sftp_fileoffset
, len
)) {
946 tell_user(stderr
, "error while writing: %s\n", fxp_error());
950 scp_sftp_fileoffset
= uint64_add32(scp_sftp_fileoffset
, len
);
953 int bufsize
= back
->send(data
, len
);
956 * If the network transfer is backing up - that is, the
957 * remote site is not accepting data as fast as we can
958 * produce it - then we must loop on network events until
959 * we have space in the buffer again.
961 while (bufsize
> MAX_SCP_BUFSIZE
) {
962 if (!scp_process_network_event())
964 bufsize
= back
->sendbuffer();
971 int scp_send_finish(void)
974 struct fxp_attrs attrs
;
975 if (!scp_sftp_filehandle
) {
979 attrs
.flags
= SSH_FILEXFER_ATTR_ACMODTIME
;
980 attrs
.atime
= scp_sftp_atime
;
981 attrs
.mtime
= scp_sftp_mtime
;
982 if (!fxp_fsetstat(scp_sftp_filehandle
, attrs
)) {
983 tell_user(stderr
, "unable to set file times: %s\n", fxp_error());
987 fxp_close(scp_sftp_filehandle
);
996 char *scp_save_remotepath(void)
999 return scp_sftp_remotepath
;
1004 void scp_restore_remotepath(char *data
)
1007 scp_sftp_remotepath
= data
;
1010 int scp_send_dirname(char *name
, int modes
)
1015 struct fxp_attrs attrs
;
1016 if (scp_sftp_targetisdir
) {
1017 fullname
= dupcat(scp_sftp_remotepath
, "/", name
, NULL
);
1019 fullname
= dupstr(scp_sftp_remotepath
);
1023 * We don't worry about whether we managed to create the
1024 * directory, because if it exists already it's OK just to
1025 * use it. Instead, we will stat it afterwards, and if it
1026 * exists and is a directory we will assume we were either
1027 * successful or it didn't matter.
1029 if (!fxp_mkdir(fullname
))
1032 err
= "server reported no error";
1033 if (!fxp_stat(fullname
, &attrs
) ||
1034 !(attrs
.flags
& SSH_FILEXFER_ATTR_PERMISSIONS
) ||
1035 !(attrs
.permissions
& 0040000)) {
1036 tell_user(stderr
, "unable to create directory %s: %s",
1042 scp_sftp_remotepath
= fullname
;
1047 sprintf(buf
, "D%04o 0 ", modes
);
1048 back
->send(buf
, strlen(buf
));
1049 back
->send(name
, strlen(name
));
1050 back
->send("\n", 1);
1055 int scp_send_enddir(void)
1058 sfree(scp_sftp_remotepath
);
1061 back
->send("E\n", 2);
1067 * Yes, I know; I have an scp_sink_setup _and_ an scp_sink_init.
1068 * That's bad. The difference is that scp_sink_setup is called once
1069 * right at the start, whereas scp_sink_init is called to
1070 * initialise every level of recursion in the protocol.
1072 int scp_sink_setup(char *source
, int preserve
, int recursive
)
1077 * It's possible that the source string we've been given
1078 * contains a wildcard. If so, we must split the directory
1079 * away from the wildcard itself (throwing an error if any
1080 * wildcardness comes before the final slash) and arrange
1081 * things so that a dirstack entry will be set up.
1083 newsource
= smalloc(1+strlen(source
));
1084 if (!wc_unescape(newsource
, source
)) {
1085 /* Yes, here we go; it's a wildcard. Bah. */
1086 char *dupsource
, *lastpart
, *dirpart
, *wildcard
;
1087 dupsource
= dupstr(source
);
1088 lastpart
= stripslashes(dupsource
, 0);
1089 wildcard
= dupstr(lastpart
);
1091 if (*dupsource
&& dupsource
[1]) {
1093 * The remains of dupsource are at least two
1094 * characters long, meaning the pathname wasn't
1095 * empty or just `/'. Hence, we remove the trailing
1098 lastpart
[-1] = '\0';
1099 } else if (!*dupsource
) {
1101 * The remains of dupsource are _empty_ - the whole
1102 * pathname was a wildcard. Hence we need to
1103 * replace it with ".".
1106 dupsource
= dupstr(".");
1110 * Now we have separated our string into dupsource (the
1111 * directory part) and wildcard. Both of these will
1112 * need freeing at some point. Next step is to remove
1113 * wildcard escapes from the directory part, throwing
1114 * an error if it contains a real wildcard.
1116 dirpart
= smalloc(1+strlen(dupsource
));
1117 if (!wc_unescape(dirpart
, dupsource
)) {
1118 tell_user(stderr
, "%s: multiple-level wildcards unsupported",
1128 * Now we have dirpart (unescaped, ie a valid remote
1129 * path), and wildcard (a wildcard). This will be
1130 * sufficient to arrange a dirstack entry.
1132 scp_sftp_remotepath
= dirpart
;
1133 scp_sftp_wildcard
= wildcard
;
1136 scp_sftp_remotepath
= newsource
;
1137 scp_sftp_wildcard
= NULL
;
1139 scp_sftp_preserve
= preserve
;
1140 scp_sftp_recursive
= recursive
;
1141 scp_sftp_donethistarget
= 0;
1142 scp_sftp_dirstack_head
= NULL
;
1147 int scp_sink_init(void)
1155 #define SCP_SINK_FILE 1
1156 #define SCP_SINK_DIR 2
1157 #define SCP_SINK_ENDDIR 3
1158 #define SCP_SINK_RETRY 4 /* not an action; just try again */
1159 struct scp_sink_action
{
1160 int action
; /* FILE, DIR, ENDDIR */
1161 char *buf
; /* will need freeing after use */
1162 char *name
; /* filename or dirname (not ENDDIR) */
1163 int mode
; /* access mode (not ENDDIR) */
1164 unsigned long size
; /* file size (not ENDDIR) */
1165 int settime
; /* 1 if atime and mtime are filled */
1166 unsigned long atime
, mtime
; /* access times for the file */
1169 int scp_get_sink_action(struct scp_sink_action
*act
)
1173 int must_free_fname
;
1174 struct fxp_attrs attrs
;
1177 if (!scp_sftp_dirstack_head
) {
1178 if (!scp_sftp_donethistarget
) {
1180 * Simple case: we are only dealing with one file.
1182 fname
= scp_sftp_remotepath
;
1183 must_free_fname
= 0;
1184 scp_sftp_donethistarget
= 1;
1187 * Even simpler case: one file _which we've done_.
1188 * Return 1 (finished).
1194 * We're now in the middle of stepping through a list
1195 * of names returned from fxp_readdir(); so let's carry
1198 struct scp_sftp_dirstack
*head
= scp_sftp_dirstack_head
;
1199 while (head
->namepos
< head
->namelen
&&
1200 (is_dots(head
->names
[head
->namepos
].filename
) ||
1202 !wc_match(head
->wildcard
,
1203 head
->names
[head
->namepos
].filename
))))
1204 head
->namepos
++; /* skip . and .. */
1205 if (head
->namepos
< head
->namelen
) {
1206 head
->matched_something
= 1;
1207 fname
= dupcat(head
->dirpath
, "/",
1208 head
->names
[head
->namepos
++].filename
,
1210 must_free_fname
= 1;
1213 * We've come to the end of the list; pop it off
1214 * the stack and return an ENDDIR action (or RETRY
1215 * if this was a wildcard match).
1217 if (head
->wildcard
) {
1218 act
->action
= SCP_SINK_RETRY
;
1219 if (!head
->matched_something
) {
1220 tell_user(stderr
, "pscp: wildcard '%s' matched "
1221 "no files", head
->wildcard
);
1224 sfree(head
->wildcard
);
1227 act
->action
= SCP_SINK_ENDDIR
;
1230 sfree(head
->dirpath
);
1232 scp_sftp_dirstack_head
= head
->next
;
1240 * Now we have a filename. Stat it, and see if it's a file
1243 ret
= fxp_stat(fname
, &attrs
);
1244 if (!ret
|| !(attrs
.flags
& SSH_FILEXFER_ATTR_PERMISSIONS
)) {
1245 tell_user(stderr
, "unable to identify %s: %s", fname
,
1246 ret ?
"file type not supplied" : fxp_error());
1251 if (attrs
.permissions
& 0040000) {
1252 struct scp_sftp_dirstack
*newitem
;
1253 struct fxp_handle
*dirhandle
;
1254 int nnames
, namesize
;
1255 struct fxp_name
*ournames
;
1256 struct fxp_names
*names
;
1259 * It's a directory. If we're not in recursive mode,
1260 * this merits a complaint (which is fatal if the name
1261 * was specified directly, but not if it was matched by
1264 * We skip this complaint completely if
1265 * scp_sftp_wildcard is set, because that's an
1266 * indication that we're not actually supposed to
1267 * _recursively_ transfer the dir, just scan it for
1268 * things matching the wildcard.
1270 if (!scp_sftp_recursive
&& !scp_sftp_wildcard
) {
1271 tell_user(stderr
, "pscp: %s: is a directory", fname
);
1273 if (must_free_fname
) sfree(fname
);
1274 if (scp_sftp_dirstack_head
) {
1275 act
->action
= SCP_SINK_RETRY
;
1283 * Otherwise, the fun begins. We must fxp_opendir() the
1284 * directory, slurp the filenames into memory, return
1285 * SCP_SINK_DIR (unless this is a wildcard match), and
1286 * set targetisdir. The next time we're called, we will
1287 * run through the list of filenames one by one,
1288 * matching them against a wildcard if present.
1290 * If targetisdir is _already_ set (meaning we're
1291 * already in the middle of going through another such
1292 * list), we must push the other (target,namelist) pair
1295 dirhandle
= fxp_opendir(fname
);
1297 tell_user(stderr
, "scp: unable to open directory %s: %s",
1298 fname
, fxp_error());
1299 if (must_free_fname
) sfree(fname
);
1303 nnames
= namesize
= 0;
1308 names
= fxp_readdir(dirhandle
);
1309 if (names
== NULL
) {
1310 if (fxp_error_type() == SSH_FX_EOF
)
1312 tell_user(stderr
, "scp: reading directory %s: %s\n",
1313 fname
, fxp_error());
1314 if (must_free_fname
) sfree(fname
);
1319 if (names
->nnames
== 0) {
1320 fxp_free_names(names
);
1323 if (nnames
+ names
->nnames
>= namesize
) {
1324 namesize
+= names
->nnames
+ 128;
1326 srealloc(ournames
, namesize
* sizeof(*ournames
));
1328 for (i
= 0; i
< names
->nnames
; i
++)
1329 ournames
[nnames
++] = names
->names
[i
];
1330 names
->nnames
= 0; /* prevent free_names */
1331 fxp_free_names(names
);
1333 fxp_close(dirhandle
);
1335 newitem
= smalloc(sizeof(struct scp_sftp_dirstack
));
1336 newitem
->next
= scp_sftp_dirstack_head
;
1337 newitem
->names
= ournames
;
1338 newitem
->namepos
= 0;
1339 newitem
->namelen
= nnames
;
1340 if (must_free_fname
)
1341 newitem
->dirpath
= fname
;
1343 newitem
->dirpath
= dupstr(fname
);
1344 if (scp_sftp_wildcard
) {
1345 newitem
->wildcard
= scp_sftp_wildcard
;
1346 newitem
->matched_something
= 0;
1347 scp_sftp_wildcard
= NULL
;
1349 newitem
->wildcard
= NULL
;
1351 scp_sftp_dirstack_head
= newitem
;
1353 if (newitem
->wildcard
) {
1354 act
->action
= SCP_SINK_RETRY
;
1356 act
->action
= SCP_SINK_DIR
;
1357 act
->buf
= dupstr(stripslashes(fname
, 0));
1358 act
->name
= act
->buf
;
1359 act
->size
= 0; /* duhh, it's a directory */
1360 act
->mode
= 07777 & attrs
.permissions
;
1361 if (scp_sftp_preserve
&&
1362 (attrs
.flags
& SSH_FILEXFER_ATTR_ACMODTIME
)) {
1363 act
->atime
= attrs
.atime
;
1364 act
->mtime
= attrs
.mtime
;
1373 * It's a file. Return SCP_SINK_FILE.
1375 act
->action
= SCP_SINK_FILE
;
1376 act
->buf
= dupstr(stripslashes(fname
, 0));
1377 act
->name
= act
->buf
;
1378 if (attrs
.flags
& SSH_FILEXFER_ATTR_SIZE
) {
1379 if (uint64_compare(attrs
.size
,
1380 uint64_make(0, ULONG_MAX
)) > 0) {
1381 act
->size
= ULONG_MAX
; /* *boggle* */
1383 act
->size
= attrs
.size
.lo
;
1385 act
->size
= ULONG_MAX
; /* no idea */
1386 act
->mode
= 07777 & attrs
.permissions
;
1387 if (scp_sftp_preserve
&&
1388 (attrs
.flags
& SSH_FILEXFER_ATTR_ACMODTIME
)) {
1389 act
->atime
= attrs
.atime
;
1390 act
->mtime
= attrs
.mtime
;
1394 if (must_free_fname
)
1395 scp_sftp_currentname
= fname
;
1397 scp_sftp_currentname
= dupstr(fname
);
1412 if (ssh_scp_recv(&ch
, 1) <= 0)
1415 bump("Protocol error: Unexpected newline");
1419 if (ssh_scp_recv(&ch
, 1) <= 0)
1420 bump("Lost connection");
1423 act
->buf
= srealloc(act
->buf
, bufsize
);
1426 } while (ch
!= '\n');
1427 act
->buf
[i
- 1] = '\0';
1429 case '\01': /* error */
1430 tell_user(stderr
, "%s\n", act
->buf
);
1432 continue; /* go round again */
1433 case '\02': /* fatal error */
1434 bump("%s", act
->buf
);
1437 act
->action
= SCP_SINK_ENDDIR
;
1440 if (sscanf(act
->buf
, "%ld %*d %ld %*d",
1441 &act
->mtime
, &act
->atime
) == 2) {
1444 continue; /* go round again */
1446 bump("Protocol error: Illegal time format");
1449 act
->action
= (action
== 'C' ? SCP_SINK_FILE
: SCP_SINK_DIR
);
1452 bump("Protocol error: Expected control record");
1455 * We will go round this loop only once, unless we hit
1462 * If we get here, we must have seen SCP_SINK_FILE or
1465 if (sscanf(act
->buf
, "%o %lu %n", &act
->mode
, &act
->size
, &i
) != 2)
1466 bump("Protocol error: Illegal file descriptor format");
1467 act
->name
= act
->buf
+ i
;
1472 int scp_accept_filexfer(void)
1475 scp_sftp_filehandle
=
1476 fxp_open(scp_sftp_currentname
, SSH_FXF_READ
);
1477 if (!scp_sftp_filehandle
) {
1478 tell_user(stderr
, "pscp: unable to open %s: %s",
1479 scp_sftp_currentname
, fxp_error());
1483 scp_sftp_fileoffset
= uint64_make(0, 0);
1484 sfree(scp_sftp_currentname
);
1488 return 0; /* can't fail */
1492 int scp_recv_filedata(char *data
, int len
)
1495 int actuallen
= fxp_read(scp_sftp_filehandle
, data
,
1496 scp_sftp_fileoffset
, len
);
1497 if (actuallen
== -1 && fxp_error_type() != SSH_FX_EOF
) {
1498 tell_user(stderr
, "pscp: error while reading: %s", fxp_error());
1505 scp_sftp_fileoffset
= uint64_add32(scp_sftp_fileoffset
, actuallen
);
1509 return ssh_scp_recv(data
, len
);
1513 int scp_finish_filerecv(void)
1516 fxp_close(scp_sftp_filehandle
);
1524 /* ----------------------------------------------------------------------
1525 * Send an error message to the other side and to the screen.
1526 * Increment error counter.
1528 static void run_err(const char *fmt
, ...)
1534 strcpy(str
, "scp: ");
1535 vsprintf(str
+ strlen(str
), fmt
, ap
);
1537 scp_send_errmsg(str
);
1538 tell_user(stderr
, "%s", str
);
1543 * Execute the source part of the SCP protocol.
1545 static void source(char *src
)
1552 unsigned long stat_bytes
;
1553 time_t stat_starttime
, stat_lasttime
;
1555 attr
= GetFileAttributes(src
);
1556 if (attr
== (DWORD
) - 1) {
1557 run_err("%s: No such file or directory", src
);
1561 if ((attr
& FILE_ATTRIBUTE_DIRECTORY
) != 0) {
1564 * Avoid . and .. directories.
1567 p
= strrchr(src
, '/');
1569 p
= strrchr(src
, '\\');
1574 if (!strcmp(p
, ".") || !strcmp(p
, ".."))
1575 /* skip . and .. */ ;
1579 run_err("%s: not a regular file", src
);
1584 if ((last
= strrchr(src
, '/')) == NULL
)
1588 if (strrchr(last
, '\\') != NULL
)
1589 last
= strrchr(last
, '\\') + 1;
1590 if (last
== src
&& strchr(src
, ':') != NULL
)
1591 last
= strchr(src
, ':') + 1;
1593 f
= CreateFile(src
, GENERIC_READ
, FILE_SHARE_READ
, NULL
,
1594 OPEN_EXISTING
, 0, 0);
1595 if (f
== INVALID_HANDLE_VALUE
) {
1596 run_err("%s: Cannot open file", src
);
1601 FILETIME actime
, wrtime
;
1602 unsigned long mtime
, atime
;
1603 GetFileTime(f
, NULL
, &actime
, &wrtime
);
1604 TIME_WIN_TO_POSIX(actime
, atime
);
1605 TIME_WIN_TO_POSIX(wrtime
, mtime
);
1606 if (scp_send_filetimes(mtime
, atime
))
1610 size
= GetFileSize(f
, NULL
);
1612 tell_user(stderr
, "Sending file %s, size=%lu", last
, size
);
1613 if (scp_send_filename(last
, size
, 0644))
1617 stat_starttime
= time(NULL
);
1620 for (i
= 0; i
< size
; i
+= 4096) {
1621 char transbuf
[4096];
1626 if (!ReadFile(f
, transbuf
, k
, &j
, NULL
) || j
!= k
) {
1629 bump("%s: Read error", src
);
1631 if (scp_send_filedata(transbuf
, k
))
1632 bump("%s: Network error occurred", src
);
1636 if (time(NULL
) != stat_lasttime
|| i
+ k
== size
) {
1637 stat_lasttime
= time(NULL
);
1638 print_stats(last
, size
, stat_bytes
,
1639 stat_starttime
, stat_lasttime
);
1646 (void) scp_send_finish();
1650 * Recursively send the contents of a directory.
1652 static void rsource(char *src
)
1654 char *last
, *findfile
;
1657 WIN32_FIND_DATA fdat
;
1660 if ((last
= strrchr(src
, '/')) == NULL
)
1664 if (strrchr(last
, '\\') != NULL
)
1665 last
= strrchr(last
, '\\') + 1;
1666 if (last
== src
&& strchr(src
, ':') != NULL
)
1667 last
= strchr(src
, ':') + 1;
1669 /* maybe send filetime */
1671 save_target
= scp_save_remotepath();
1674 tell_user(stderr
, "Entering directory: %s", last
);
1675 if (scp_send_dirname(last
, 0755))
1678 findfile
= dupcat(src
, "/*", NULL
);
1679 dir
= FindFirstFile(findfile
, &fdat
);
1680 ok
= (dir
!= INVALID_HANDLE_VALUE
);
1682 if (strcmp(fdat
.cFileName
, ".") == 0 ||
1683 strcmp(fdat
.cFileName
, "..") == 0) {
1684 /* ignore . and .. */
1686 char *foundfile
= dupcat(src
, "/", fdat
.cFileName
, NULL
);
1690 ok
= FindNextFile(dir
, &fdat
);
1695 (void) scp_send_enddir();
1697 scp_restore_remotepath(save_target
);
1701 * Execute the sink part of the SCP protocol.
1703 static void sink(char *targ
, char *src
)
1710 unsigned long received
;
1712 unsigned long stat_bytes
;
1713 time_t stat_starttime
, stat_lasttime
;
1716 attr
= GetFileAttributes(targ
);
1717 if (attr
!= (DWORD
) - 1 && (attr
& FILE_ATTRIBUTE_DIRECTORY
) != 0)
1720 if (targetshouldbedirectory
&& !targisdir
)
1721 bump("%s: Not a directory", targ
);
1725 struct scp_sink_action act
;
1726 if (scp_get_sink_action(&act
))
1729 if (act
.action
== SCP_SINK_ENDDIR
)
1732 if (act
.action
== SCP_SINK_RETRY
)
1737 * Prevent the remote side from maliciously writing to
1738 * files outside the target area by sending a filename
1739 * containing `../'. In fact, it shouldn't be sending
1740 * filenames with any slashes or colons in at all; so
1741 * we'll find the last slash, backslash or colon in the
1742 * filename and use only the part after that. (And
1745 * In addition, we also ensure here that if we're
1746 * copying a single file and the target is a directory
1747 * (common usage: `pscp host:filename .') the remote
1748 * can't send us a _different_ file name. We can
1749 * distinguish this case because `src' will be non-NULL
1750 * and the last component of that will fail to match
1751 * (the last component of) the name sent.
1753 * Well, not always; if `src' is a wildcard, we do
1754 * expect to get back filenames that don't correspond
1755 * exactly to it. Ideally in this case, we would like
1756 * to ensure that the returned filename actually
1757 * matches the wildcard pattern - but one of SCP's
1758 * protocol infelicities is that wildcard matching is
1759 * done at the server end _by the server's rules_ and
1760 * so in general this is infeasible. Hence, we only
1761 * accept filenames that don't correspond to `src' if
1762 * unsafe mode is enabled or we are using SFTP (which
1763 * resolves remote wildcards on the client side and can
1766 char *striptarget
, *stripsrc
;
1768 striptarget
= stripslashes(act
.name
, 1);
1769 if (striptarget
!= act
.name
) {
1770 tell_user(stderr
, "warning: remote host sent a compound"
1771 " pathname '%s'", act
.name
);
1772 tell_user(stderr
, " renaming local file to '%s'",
1777 * Also check to see if the target filename is '.' or
1778 * '..', or indeed '...' and so on because Windows
1779 * appears to interpret those like '..'.
1781 if (is_dots(striptarget
)) {
1782 bump("security violation: remote host attempted to write to"
1783 " a '.' or '..' path!");
1787 stripsrc
= stripslashes(src
, 1);
1788 if (strcmp(striptarget
, stripsrc
) &&
1789 !using_sftp
&& !scp_unsafe_mode
) {
1790 tell_user(stderr
, "warning: remote host tried to write "
1791 "to a file called '%s'", striptarget
);
1792 tell_user(stderr
, " when we requested a file "
1793 "called '%s'.", stripsrc
);
1794 tell_user(stderr
, " If this is a wildcard, "
1795 "consider upgrading to SSH 2 or using");
1796 tell_user(stderr
, " the '-unsafe' option. Renaming"
1797 " of this file has been disallowed.");
1798 /* Override the name the server provided with our own. */
1799 striptarget
= stripsrc
;
1803 if (targ
[0] != '\0')
1804 destfname
= dupcat(targ
, "\\", striptarget
, NULL
);
1806 destfname
= dupstr(striptarget
);
1809 * In this branch of the if, the target area is a
1810 * single file with an explicitly specified name in any
1811 * case, so there's no danger.
1813 destfname
= dupstr(targ
);
1815 attr
= GetFileAttributes(destfname
);
1816 exists
= (attr
!= (DWORD
) - 1);
1818 if (act
.action
== SCP_SINK_DIR
) {
1819 if (exists
&& (attr
& FILE_ATTRIBUTE_DIRECTORY
) == 0) {
1820 run_err("%s: Not a directory", destfname
);
1824 if (!CreateDirectory(destfname
, NULL
)) {
1825 run_err("%s: Cannot create directory", destfname
);
1829 sink(destfname
, NULL
);
1830 /* can we set the timestamp for directories ? */
1834 f
= CreateFile(destfname
, GENERIC_WRITE
, 0, NULL
,
1835 CREATE_ALWAYS
, FILE_ATTRIBUTE_NORMAL
, 0);
1836 if (f
== INVALID_HANDLE_VALUE
) {
1837 run_err("%s: Cannot create file", destfname
);
1841 if (scp_accept_filexfer())
1845 stat_starttime
= time(NULL
);
1847 stat_name
= stripslashes(destfname
, 1);
1850 while (received
< act
.size
) {
1851 char transbuf
[4096];
1852 DWORD blksize
, read
, written
;
1854 if (blksize
> act
.size
- received
)
1855 blksize
= act
.size
- received
;
1856 read
= scp_recv_filedata(transbuf
, blksize
);
1858 bump("Lost connection");
1861 if (!WriteFile(f
, transbuf
, read
, &written
, NULL
) ||
1864 /* FIXME: in sftp we can actually abort the transfer */
1866 printf("\r%-25.25s | %50s\n",
1868 "Write error.. waiting for end of file");
1873 if (time(NULL
) > stat_lasttime
||
1874 received
+ read
== act
.size
) {
1875 stat_lasttime
= time(NULL
);
1876 print_stats(stat_name
, act
.size
, stat_bytes
,
1877 stat_starttime
, stat_lasttime
);
1883 FILETIME actime
, wrtime
;
1884 TIME_POSIX_TO_WIN(act
.atime
, actime
);
1885 TIME_POSIX_TO_WIN(act
.mtime
, wrtime
);
1886 SetFileTime(f
, NULL
, &actime
, &wrtime
);
1891 run_err("%s: Write error", destfname
);
1894 (void) scp_finish_filerecv();
1901 * We will copy local files to a remote server.
1903 static void toremote(int argc
, char *argv
[])
1905 char *src
, *targ
, *host
, *user
;
1909 targ
= argv
[argc
- 1];
1911 /* Separate host from filename */
1915 bump("targ == NULL in toremote()");
1919 /* Substitute "." for emtpy target */
1921 /* Separate host and username */
1923 host
= strrchr(host
, '@');
1934 /* Find out if the source filespec covers multiple files
1935 if so, we should set the targetshouldbedirectory flag */
1937 WIN32_FIND_DATA fdat
;
1938 if (colon(argv
[0]) != NULL
)
1939 bump("%s: Remote to remote not supported", argv
[0]);
1940 fh
= FindFirstFile(argv
[0], &fdat
);
1941 if (fh
== INVALID_HANDLE_VALUE
)
1942 bump("%s: No such file or directory\n", argv
[0]);
1943 if (FindNextFile(fh
, &fdat
))
1944 targetshouldbedirectory
= 1;
1948 cmd
= smalloc(strlen(targ
) + 100);
1949 sprintf(cmd
, "scp%s%s%s%s -t %s",
1950 verbose ?
" -v" : "",
1951 recursive ?
" -r" : "",
1952 preserve ?
" -p" : "",
1953 targetshouldbedirectory ?
" -d" : "", targ
);
1954 do_cmd(host
, user
, cmd
);
1957 scp_source_setup(targ
, targetshouldbedirectory
);
1959 for (i
= 0; i
< argc
- 1; i
++) {
1960 char *srcpath
, *last
;
1962 WIN32_FIND_DATA fdat
;
1964 if (colon(src
) != NULL
) {
1965 tell_user(stderr
, "%s: Remote to remote not supported\n", src
);
1971 * Trim off the last pathname component of `src', to
1972 * provide the base pathname which will be prepended to
1973 * filenames returned from Find{First,Next}File.
1975 srcpath
= dupstr(src
);
1976 last
= stripslashes(srcpath
, 1);
1979 dir
= FindFirstFile(src
, &fdat
);
1980 if (dir
== INVALID_HANDLE_VALUE
) {
1981 run_err("%s: No such file or directory", src
);
1987 * Ensure that . and .. are never matched by wildcards,
1988 * but only by deliberate action.
1990 if (!strcmp(fdat
.cFileName
, ".") ||
1991 !strcmp(fdat
.cFileName
, "..")) {
1993 * Find*File has returned a special dir. We require
1994 * that _either_ `src' ends in a backslash followed
1995 * by that string, _or_ `src' is precisely that
1998 int len
= strlen(src
), dlen
= strlen(fdat
.cFileName
);
1999 if (len
== dlen
&& !strcmp(src
, fdat
.cFileName
)) {
2001 } else if (len
> dlen
+ 1 && src
[len
- dlen
- 1] == '\\' &&
2002 !strcmp(src
+ len
- dlen
, fdat
.cFileName
)) {
2005 continue; /* ignore this one */
2007 filename
= dupcat(srcpath
, fdat
.cFileName
, NULL
);
2010 } while (FindNextFile(dir
, &fdat
));
2017 * We will copy files from a remote server to the local machine.
2019 static void tolocal(int argc
, char *argv
[])
2021 char *src
, *targ
, *host
, *user
;
2025 bump("More than one remote source not supported");
2030 /* Separate host from filename */
2034 bump("Local to local copy not supported");
2038 /* Substitute "." for empty filename */
2040 /* Separate username and hostname */
2042 host
= strrchr(host
, '@');
2052 cmd
= smalloc(strlen(src
) + 100);
2053 sprintf(cmd
, "scp%s%s%s%s -f %s",
2054 verbose ?
" -v" : "",
2055 recursive ?
" -r" : "",
2056 preserve ?
" -p" : "",
2057 targetshouldbedirectory ?
" -d" : "", src
);
2058 do_cmd(host
, user
, cmd
);
2061 if (scp_sink_setup(src
, preserve
, recursive
))
2068 * We will issue a list command to get a remote directory.
2070 static void get_dir_list(int argc
, char *argv
[])
2072 char *src
, *host
, *user
;
2078 /* Separate host from filename */
2082 bump("Local to local copy not supported");
2086 /* Substitute "." for empty filename */
2088 /* Separate username and hostname */
2090 host
= strrchr(host
, '@');
2100 cmd
= smalloc(4 * strlen(src
) + 100);
2101 strcpy(cmd
, "ls -la '");
2102 p
= cmd
+ strlen(cmd
);
2103 for (q
= src
; *q
; q
++) {
2116 do_cmd(host
, user
, cmd
);
2120 scp_sftp_listdir(src
);
2122 while (ssh_scp_recv(&c
, 1) > 0)
2123 tell_char(stdout
, c
);
2128 * Initialize the Win$ock driver.
2130 static void init_winsock(void)
2135 winsock_ver
= MAKEWORD(1, 1);
2136 if (WSAStartup(winsock_ver
, &wsadata
))
2137 bump("Unable to initialise WinSock");
2138 if (LOBYTE(wsadata
.wVersion
) != 1 || HIBYTE(wsadata
.wVersion
) != 1)
2139 bump("WinSock version is incompatible with 1.1");
2143 * Short description of parameters.
2145 static void usage(void)
2147 printf("PuTTY Secure Copy client\n");
2148 printf("%s\n", ver
);
2149 printf("Usage: pscp [options] [user@]host:source target\n");
2151 (" pscp [options] source [source...] [user@]host:target\n");
2152 printf(" pscp [options] -ls user@host:filespec\n");
2153 printf("Options:\n");
2154 printf(" -p preserve file attributes\n");
2155 printf(" -q quiet, don't show statistics\n");
2156 printf(" -r copy directories recursively\n");
2157 printf(" -v show verbose messages\n");
2158 printf(" -P port connect to specified port\n");
2159 printf(" -pw passw login with specified password\n");
2160 printf(" -unsafe allow server-side wildcards (DANGEROUS)\n");
2163 * -gui is an internal option, used by GUI front ends to get
2164 * pscp to pass progress reports back to them. It's not an
2165 * ordinary user-accessible option, so it shouldn't be part of
2166 * the command-line help. The only people who need to know
2167 * about it are programmers, and they can read the source.
2170 (" -gui hWnd GUI mode with the windows handle for receiving messages\n");
2176 * Main program (no, really?)
2178 int main(int argc
, char *argv
[])
2182 default_protocol
= PROT_TELNET
;
2184 flags
= FLAG_STDERR
;
2185 ssh_get_line
= &get_line
;
2189 for (i
= 1; i
< argc
; i
++) {
2190 if (argv
[i
][0] != '-')
2192 if (strcmp(argv
[i
], "-v") == 0)
2193 verbose
= 1, flags
|= FLAG_VERBOSE
;
2194 else if (strcmp(argv
[i
], "-r") == 0)
2196 else if (strcmp(argv
[i
], "-p") == 0)
2198 else if (strcmp(argv
[i
], "-q") == 0)
2200 else if (strcmp(argv
[i
], "-h") == 0 || strcmp(argv
[i
], "-?") == 0)
2202 else if (strcmp(argv
[i
], "-P") == 0 && i
+ 1 < argc
)
2203 portnumber
= atoi(argv
[++i
]);
2204 else if (strcmp(argv
[i
], "-pw") == 0 && i
+ 1 < argc
)
2205 password
= argv
[++i
];
2206 else if (strcmp(argv
[i
], "-gui") == 0 && i
+ 1 < argc
) {
2207 gui_hwnd
= argv
[++i
];
2209 } else if (strcmp(argv
[i
], "-ls") == 0)
2211 else if (strcmp(argv
[i
], "-unsafe") == 0)
2212 scp_unsafe_mode
= 1;
2213 else if (strcmp(argv
[i
], "--") == 0) {
2226 get_dir_list(argc
, argv
);
2233 targetshouldbedirectory
= 1;
2235 if (colon(argv
[argc
- 1]) != NULL
)
2236 toremote(argc
, argv
);
2238 tolocal(argc
, argv
);
2241 if (back
!= NULL
&& back
->socket() != NULL
) {
2243 back
->special(TS_EOF
);
2244 ssh_scp_recv(&ch
, 1);
2249 /* GUI Adaptation - August 2000 */
2251 unsigned int msg_id
= WM_RET_ERR_CNT
;
2253 msg_id
= WM_LS_RET_ERR_CNT
;
2255 ((HWND
) atoi(gui_hwnd
), msg_id
, (WPARAM
) errs
,
2256 0 /*lParam */ ))SleepEx(1000, TRUE
);
2258 return (errs
== 0 ?
0 : 1);