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
24 /* GUI Adaptation - Sept 2000 */
28 #define PUTTY_DO_GLOBALS
33 #define TIME_POSIX_TO_WIN(t, ft) (*(LONGLONG*)&(ft) = \
34 ((LONGLONG) (t) + (LONGLONG) 11644473600) * (LONGLONG) 10000000)
35 #define TIME_WIN_TO_POSIX(ft, t) ((t) = (unsigned long) \
36 ((*(LONGLONG*)&(ft)) / (LONGLONG) 10000000 - (LONGLONG) 11644473600))
38 /* GUI Adaptation - Sept 2000 */
39 #define WM_APP_BASE 0x8000
40 #define WM_STD_OUT_CHAR ( WM_APP_BASE+400 )
41 #define WM_STD_ERR_CHAR ( WM_APP_BASE+401 )
42 #define WM_STATS_CHAR ( WM_APP_BASE+402 )
43 #define WM_STATS_SIZE ( WM_APP_BASE+403 )
44 #define WM_STATS_PERCENT ( WM_APP_BASE+404 )
45 #define WM_STATS_ELAPSED ( WM_APP_BASE+405 )
46 #define WM_RET_ERR_CNT ( WM_APP_BASE+406 )
47 #define WM_LS_RET_ERR_CNT ( WM_APP_BASE+407 )
50 static int verbose
= 0;
51 static int recursive
= 0;
52 static int preserve
= 0;
53 static int targetshouldbedirectory
= 0;
54 static int statistics
= 1;
55 static int portnumber
= 0;
56 static int prev_stats_len
= 0;
57 static char *password
= NULL
;
59 /* GUI Adaptation - Sept 2000 */
60 #define NAME_STR_MAX 2048
61 static char statname
[NAME_STR_MAX
+ 1];
62 static unsigned long statsize
= 0;
63 static int statperct
= 0;
64 static unsigned long statelapsed
= 0;
65 static int gui_mode
= 0;
66 static char *gui_hwnd
= NULL
;
68 static void source(char *src
);
69 static void rsource(char *src
);
70 static void sink(char *targ
, char *src
);
71 /* GUI Adaptation - Sept 2000 */
72 static void tell_char(FILE * stream
, char c
);
73 static void tell_str(FILE * stream
, char *str
);
74 static void tell_user(FILE * stream
, char *fmt
, ...);
75 static void gui_update_stats(char *name
, unsigned long size
,
76 int percentage
, unsigned long elapsed
);
79 * The maximum amount of queued data we accept before we stop and
80 * wait for the server to process some.
82 #define MAX_SCP_BUFSIZE 16384
84 void logevent(char *string
)
88 void ldisc_send(char *buf
, int len
)
91 * This is only here because of the calls to ldisc_send(NULL,
92 * 0) in ssh.c. Nothing in PSCP actually needs to use the ldisc
93 * as an ldisc. So if we get called with any real data, I want
99 void verify_ssh_host_key(char *host
, int port
, char *keytype
,
100 char *keystr
, char *fingerprint
)
106 static const char absentmsg
[] =
107 "The server's host key is not cached in the registry. You\n"
108 "have no guarantee that the server is the computer you\n"
110 "The server's key fingerprint is:\n"
112 "If you trust this host, enter \"y\" to add the key to\n"
113 "PuTTY's cache and carry on connecting.\n"
114 "If you want to carry on connecting just once, without\n"
115 "adding the key to the cache, enter \"n\".\n"
116 "If you do not trust this host, press Return to abandon the\n"
118 "Store key in cache? (y/n) ";
120 static const char wrongmsg
[] =
121 "WARNING - POTENTIAL SECURITY BREACH!\n"
122 "The server's host key does not match the one PuTTY has\n"
123 "cached in the registry. This means that either the\n"
124 "server administrator has changed the host key, or you\n"
125 "have actually connected to another computer pretending\n"
126 "to be the server.\n"
127 "The new key fingerprint is:\n"
129 "If you were expecting this change and trust the new key,\n"
130 "enter \"y\" to update PuTTY's cache and continue connecting.\n"
131 "If you want to carry on connecting but without updating\n"
132 "the cache, enter \"n\".\n"
133 "If you want to abandon the connection completely, press\n"
134 "Return to cancel. Pressing Return is the ONLY guaranteed\n"
136 "Update cached key? (y/n, Return cancels connection) ";
138 static const char abandoned
[] = "Connection abandoned.\n";
143 * Verify the key against the registry.
145 ret
= verify_host_key(host
, port
, keytype
, keystr
);
147 if (ret
== 0) /* success - key matched OK */
150 if (ret
== 2) { /* key was different */
151 fprintf(stderr
, wrongmsg
, fingerprint
);
154 if (ret
== 1) { /* key was absent */
155 fprintf(stderr
, absentmsg
, fingerprint
);
159 hin
= GetStdHandle(STD_INPUT_HANDLE
);
160 GetConsoleMode(hin
, &savemode
);
161 SetConsoleMode(hin
, (savemode
| ENABLE_ECHO_INPUT
|
162 ENABLE_PROCESSED_INPUT
| ENABLE_LINE_INPUT
));
163 ReadFile(hin
, line
, sizeof(line
) - 1, &i
, NULL
);
164 SetConsoleMode(hin
, savemode
);
166 if (line
[0] != '\0' && line
[0] != '\r' && line
[0] != '\n') {
167 if (line
[0] == 'y' || line
[0] == 'Y')
168 store_host_key(host
, port
, keytype
, keystr
);
170 fprintf(stderr
, abandoned
);
176 * Ask whether the selected cipher is acceptable (since it was
177 * below the configured 'warn' threshold).
178 * cs: 0 = both ways, 1 = client->server, 2 = server->client
180 void askcipher(char *ciphername
, int cs
)
185 static const char msg
[] =
186 "The first %scipher supported by the server is\n"
187 "%s, which is below the configured warning threshold.\n"
188 "Continue with connection? (y/n) ";
189 static const char abandoned
[] = "Connection abandoned.\n";
195 (cs
== 1) ?
"client-to-server " :
200 hin
= GetStdHandle(STD_INPUT_HANDLE
);
201 GetConsoleMode(hin
, &savemode
);
202 SetConsoleMode(hin
, (savemode
| ENABLE_ECHO_INPUT
|
203 ENABLE_PROCESSED_INPUT
| ENABLE_LINE_INPUT
));
204 ReadFile(hin
, line
, sizeof(line
) - 1, &i
, NULL
);
205 SetConsoleMode(hin
, savemode
);
207 if (line
[0] == 'y' || line
[0] == 'Y') {
210 fprintf(stderr
, abandoned
);
215 /* GUI Adaptation - Sept 2000 */
216 static void send_msg(HWND h
, UINT message
, WPARAM wParam
)
218 while (!PostMessage(h
, message
, wParam
, 0))
222 static void tell_char(FILE * stream
, char c
)
227 unsigned int msg_id
= WM_STD_OUT_CHAR
;
228 if (stream
== stderr
)
229 msg_id
= WM_STD_ERR_CHAR
;
230 send_msg((HWND
) atoi(gui_hwnd
), msg_id
, (WPARAM
) c
);
234 static void tell_str(FILE * stream
, char *str
)
238 for (i
= 0; i
< strlen(str
); ++i
)
239 tell_char(stream
, str
[i
]);
242 static void tell_user(FILE * stream
, char *fmt
, ...)
244 char str
[0x100]; /* Make the size big enough */
247 vsprintf(str
, fmt
, ap
);
250 tell_str(stream
, str
);
253 static void gui_update_stats(char *name
, unsigned long size
,
254 int percentage
, unsigned long elapsed
)
258 if (strcmp(name
, statname
) != 0) {
259 for (i
= 0; i
< strlen(name
); ++i
)
260 send_msg((HWND
) atoi(gui_hwnd
), WM_STATS_CHAR
,
262 send_msg((HWND
) atoi(gui_hwnd
), WM_STATS_CHAR
, (WPARAM
) '\n');
263 strcpy(statname
, name
);
265 if (statsize
!= size
) {
266 send_msg((HWND
) atoi(gui_hwnd
), WM_STATS_SIZE
, (WPARAM
) size
);
269 if (statelapsed
!= elapsed
) {
270 send_msg((HWND
) atoi(gui_hwnd
), WM_STATS_ELAPSED
,
272 statelapsed
= elapsed
;
274 if (statperct
!= percentage
) {
275 send_msg((HWND
) atoi(gui_hwnd
), WM_STATS_PERCENT
,
276 (WPARAM
) percentage
);
277 statperct
= percentage
;
282 * Print an error message and perform a fatal exit.
284 void fatalbox(char *fmt
, ...)
286 char str
[0x100]; /* Make the size big enough */
289 strcpy(str
, "Fatal:");
290 vsprintf(str
+ strlen(str
), fmt
, ap
);
293 tell_str(stderr
, str
);
297 unsigned int msg_id
= WM_RET_ERR_CNT
;
299 msg_id
= WM_LS_RET_ERR_CNT
;
301 ((HWND
) atoi(gui_hwnd
), msg_id
, (WPARAM
) errs
,
302 0 /*lParam */ ))SleepEx(1000, TRUE
);
307 void connection_fatal(char *fmt
, ...)
309 char str
[0x100]; /* Make the size big enough */
312 strcpy(str
, "Fatal:");
313 vsprintf(str
+ strlen(str
), fmt
, ap
);
316 tell_str(stderr
, str
);
320 unsigned int msg_id
= WM_RET_ERR_CNT
;
322 msg_id
= WM_LS_RET_ERR_CNT
;
324 ((HWND
) atoi(gui_hwnd
), msg_id
, (WPARAM
) errs
,
325 0 /*lParam */ ))SleepEx(1000, TRUE
);
332 * Be told what socket we're supposed to be using.
334 static SOCKET scp_ssh_socket
;
335 char *do_select(SOCKET skt
, int startup
)
338 scp_ssh_socket
= skt
;
340 scp_ssh_socket
= INVALID_SOCKET
;
343 extern int select_result(WPARAM
, LPARAM
);
346 * Receive a block of data from the SSH link. Block until all data
349 * To do this, we repeatedly call the SSH protocol module, with our
350 * own trap in from_backend() to catch the data that comes back. We
351 * do this until we have enough data.
354 static unsigned char *outptr
; /* where to put the data */
355 static unsigned outlen
; /* how much data required */
356 static unsigned char *pending
= NULL
; /* any spare data */
357 static unsigned pendlen
= 0, pendsize
= 0; /* length and phys. size of buffer */
358 int from_backend(int is_stderr
, char *data
, int datalen
)
360 unsigned char *p
= (unsigned char *) data
;
361 unsigned len
= (unsigned) datalen
;
364 * stderr data is just spouted to local stderr and otherwise
368 fwrite(data
, 1, len
, stderr
);
375 * If this is before the real session begins, just return.
381 unsigned used
= outlen
;
384 memcpy(outptr
, p
, used
);
392 if (pendsize
< pendlen
+ len
) {
393 pendsize
= pendlen
+ len
+ 4096;
394 pending
= (pending ?
srealloc(pending
, pendsize
) :
397 fatalbox("Out of memory");
399 memcpy(pending
+ pendlen
, p
, len
);
405 static int scp_process_network_event(void)
410 FD_SET(scp_ssh_socket
, &readfds
);
411 if (select(1, &readfds
, NULL
, NULL
, NULL
) < 0)
413 select_result((WPARAM
) scp_ssh_socket
, (LPARAM
) FD_READ
);
416 static int ssh_scp_recv(unsigned char *buf
, int len
)
422 * See if the pending-input block contains some of what we
426 unsigned pendused
= pendlen
;
427 if (pendused
> outlen
)
429 memcpy(outptr
, pending
, pendused
);
430 memmove(pending
, pending
+ pendused
, pendlen
- pendused
);
444 if (!scp_process_network_event())
452 * Loop through the ssh connection and authentication process.
454 static void ssh_scp_init(void)
456 if (scp_ssh_socket
== INVALID_SOCKET
)
458 while (!back
->sendok()) {
461 FD_SET(scp_ssh_socket
, &readfds
);
462 if (select(1, &readfds
, NULL
, NULL
, NULL
) < 0)
464 select_result((WPARAM
) scp_ssh_socket
, (LPARAM
) FD_READ
);
469 * Print an error message and exit after closing the SSH link.
471 static void bump(char *fmt
, ...)
473 char str
[0x100]; /* Make the size big enough */
476 strcpy(str
, "Fatal:");
477 vsprintf(str
+ strlen(str
), fmt
, ap
);
480 tell_str(stderr
, str
);
483 if (back
!= NULL
&& back
->socket() != NULL
) {
485 back
->special(TS_EOF
);
486 ssh_scp_recv(&ch
, 1);
490 unsigned int msg_id
= WM_RET_ERR_CNT
;
492 msg_id
= WM_LS_RET_ERR_CNT
;
494 ((HWND
) atoi(gui_hwnd
), msg_id
, (WPARAM
) errs
,
495 0 /*lParam */ ))SleepEx(1000, TRUE
);
501 static int get_line(const char *prompt
, char *str
, int maxlen
, int is_pw
)
504 DWORD savemode
, newmode
, i
;
506 if (is_pw
&& password
) {
507 static int tried_once
= 0;
512 strncpy(str
, password
, maxlen
);
513 str
[maxlen
- 1] = '\0';
519 /* GUI Adaptation - Sept 2000 */
524 hin
= GetStdHandle(STD_INPUT_HANDLE
);
525 hout
= GetStdHandle(STD_OUTPUT_HANDLE
);
526 if (hin
== INVALID_HANDLE_VALUE
|| hout
== INVALID_HANDLE_VALUE
)
527 bump("Cannot get standard input/output handles");
529 GetConsoleMode(hin
, &savemode
);
530 newmode
= savemode
| ENABLE_PROCESSED_INPUT
| ENABLE_LINE_INPUT
;
532 newmode
&= ~ENABLE_ECHO_INPUT
;
534 newmode
|= ENABLE_ECHO_INPUT
;
535 SetConsoleMode(hin
, newmode
);
537 WriteFile(hout
, prompt
, strlen(prompt
), &i
, NULL
);
538 ReadFile(hin
, str
, maxlen
- 1, &i
, NULL
);
540 SetConsoleMode(hin
, savemode
);
542 if ((int) i
> maxlen
)
549 WriteFile(hout
, "\r\n", 2, &i
, NULL
);
556 * Open an SSH connection to user@host and execute cmd.
558 static void do_cmd(char *host
, char *user
, char *cmd
)
560 char *err
, *realhost
;
563 if (host
== NULL
|| host
[0] == '\0')
564 bump("Empty host name");
566 /* Try to load settings for this host */
567 do_defaults(host
, &cfg
);
568 if (cfg
.host
[0] == '\0') {
569 /* No settings for this host; use defaults */
570 do_defaults(NULL
, &cfg
);
571 strncpy(cfg
.host
, host
, sizeof(cfg
.host
) - 1);
572 cfg
.host
[sizeof(cfg
.host
) - 1] = '\0';
577 if (user
!= NULL
&& user
[0] != '\0') {
578 strncpy(cfg
.username
, user
, sizeof(cfg
.username
) - 1);
579 cfg
.username
[sizeof(cfg
.username
) - 1] = '\0';
580 } else if (cfg
.username
[0] == '\0') {
582 if (GetUserName(user
, &namelen
) == FALSE
)
583 bump("Empty user name");
584 user
= smalloc(namelen
* sizeof(char));
585 GetUserName(user
, &namelen
);
587 tell_user(stderr
, "Guessing user name: %s", user
);
588 strncpy(cfg
.username
, user
, sizeof(cfg
.username
) - 1);
589 cfg
.username
[sizeof(cfg
.username
) - 1] = '\0';
593 if (cfg
.protocol
!= PROT_SSH
)
597 cfg
.port
= portnumber
;
599 strncpy(cfg
.remote_cmd
, cmd
, sizeof(cfg
.remote_cmd
));
600 cfg
.remote_cmd
[sizeof(cfg
.remote_cmd
) - 1] = '\0';
605 err
= back
->init(cfg
.host
, cfg
.port
, &realhost
);
607 bump("ssh_init: %s", err
);
609 if (verbose
&& realhost
!= NULL
)
610 tell_user(stderr
, "Connected to %s\n", realhost
);
615 * Update statistic information about current file.
617 static void print_stats(char *name
, unsigned long size
, unsigned long done
,
618 time_t start
, time_t now
)
626 /* GUI Adaptation - Sept 2000 */
628 gui_update_stats(name
, size
, (int) (100 * (done
* 1.0 / size
)),
629 (unsigned long) difftime(now
, start
));
632 ratebs
= (float) done
/ (now
- start
);
634 ratebs
= (float) done
;
639 eta
= (unsigned long) ((size
- done
) / ratebs
);
640 sprintf(etastr
, "%02ld:%02ld:%02ld",
641 eta
/ 3600, (eta
% 3600) / 60, eta
% 60);
643 pct
= (int) (100.0 * (float) done
/ size
);
645 len
= printf("\r%-25.25s | %10ld kB | %5.1f kB/s | ETA: %8s | %3d%%",
646 name
, done
/ 1024, ratebs
/ 1024.0, etastr
, pct
);
647 if (len
< prev_stats_len
)
648 printf("%*s", prev_stats_len
- len
, "");
649 prev_stats_len
= len
;
657 * Find a colon in str and return a pointer to the colon.
658 * This is used to separate hostname from filename.
660 static char *colon(char *str
)
662 /* We ignore a leading colon, since the hostname cannot be
663 empty. We also ignore a colon as second character because
664 of filenames like f:myfile.txt. */
665 if (str
[0] == '\0' || str
[0] == ':' || str
[1] == ':')
667 while (*str
!= '\0' && *str
!= ':' && *str
!= '/' && *str
!= '\\')
676 * Wait for a response from the other side.
677 * Return 0 if ok, -1 if error.
679 static int response(void)
681 char ch
, resp
, rbuf
[2048];
684 if (ssh_scp_recv(&resp
, 1) <= 0)
685 bump("Lost connection");
695 case 2: /* fatal error */
697 if (ssh_scp_recv(&ch
, 1) <= 0)
698 bump("Protocol error: Lost connection");
700 } while (p
< sizeof(rbuf
) && ch
!= '\n');
703 tell_user(stderr
, "%s\n", rbuf
);
712 * Send an error message to the other side and to the screen.
713 * Increment error counter.
715 static void run_err(const char *fmt
, ...)
721 strcpy(str
, "scp: ");
722 vsprintf(str
+ strlen(str
), fmt
, ap
);
724 back
->send("\001", 1); /* scp protocol error prefix */
725 back
->send(str
, strlen(str
));
726 tell_user(stderr
, "%s", str
);
731 * Execute the source part of the SCP protocol.
733 static void source(char *src
)
741 unsigned long stat_bytes
;
742 time_t stat_starttime
, stat_lasttime
;
744 attr
= GetFileAttributes(src
);
745 if (attr
== (DWORD
) - 1) {
746 run_err("%s: No such file or directory", src
);
750 if ((attr
& FILE_ATTRIBUTE_DIRECTORY
) != 0) {
753 * Avoid . and .. directories.
756 p
= strrchr(src
, '/');
758 p
= strrchr(src
, '\\');
763 if (!strcmp(p
, ".") || !strcmp(p
, ".."))
764 /* skip . and .. */ ;
768 run_err("%s: not a regular file", src
);
773 if ((last
= strrchr(src
, '/')) == NULL
)
777 if (strrchr(last
, '\\') != NULL
)
778 last
= strrchr(last
, '\\') + 1;
779 if (last
== src
&& strchr(src
, ':') != NULL
)
780 last
= strchr(src
, ':') + 1;
782 f
= CreateFile(src
, GENERIC_READ
, FILE_SHARE_READ
, NULL
,
783 OPEN_EXISTING
, 0, 0);
784 if (f
== INVALID_HANDLE_VALUE
) {
785 run_err("%s: Cannot open file", src
);
790 FILETIME actime
, wrtime
;
791 unsigned long mtime
, atime
;
792 GetFileTime(f
, NULL
, &actime
, &wrtime
);
793 TIME_WIN_TO_POSIX(actime
, atime
);
794 TIME_WIN_TO_POSIX(wrtime
, mtime
);
795 sprintf(buf
, "T%lu 0 %lu 0\n", mtime
, atime
);
796 back
->send(buf
, strlen(buf
));
801 size
= GetFileSize(f
, NULL
);
802 sprintf(buf
, "C0644 %lu %s\n", size
, last
);
804 tell_user(stderr
, "Sending file modes: %s", buf
);
805 back
->send(buf
, strlen(buf
));
810 stat_starttime
= time(NULL
);
813 for (i
= 0; i
< size
; i
+= 4096) {
820 if (!ReadFile(f
, transbuf
, k
, &j
, NULL
) || j
!= k
) {
823 bump("%s: Read error", src
);
825 bufsize
= back
->send(transbuf
, k
);
828 if (time(NULL
) != stat_lasttime
|| i
+ k
== size
) {
829 stat_lasttime
= time(NULL
);
830 print_stats(last
, size
, stat_bytes
,
831 stat_starttime
, stat_lasttime
);
836 * If the network transfer is backing up - that is, the
837 * remote site is not accepting data as fast as we can
838 * produce it - then we must loop on network events until
839 * we have space in the buffer again.
841 while (bufsize
> MAX_SCP_BUFSIZE
) {
842 if (!scp_process_network_event())
843 bump("%s: Network error occurred", src
);
844 bufsize
= back
->sendbuffer();
854 * Recursively send the contents of a directory.
856 static void rsource(char *src
)
861 WIN32_FIND_DATA fdat
;
864 if ((last
= strrchr(src
, '/')) == NULL
)
868 if (strrchr(last
, '\\') != NULL
)
869 last
= strrchr(last
, '\\') + 1;
870 if (last
== src
&& strchr(src
, ':') != NULL
)
871 last
= strchr(src
, ':') + 1;
873 /* maybe send filetime */
875 sprintf(buf
, "D0755 0 %s\n", last
);
877 tell_user(stderr
, "Entering directory: %s", buf
);
878 back
->send(buf
, strlen(buf
));
882 sprintf(buf
, "%s/*", src
);
883 dir
= FindFirstFile(buf
, &fdat
);
884 ok
= (dir
!= INVALID_HANDLE_VALUE
);
886 if (strcmp(fdat
.cFileName
, ".") == 0 ||
887 strcmp(fdat
.cFileName
, "..") == 0) {
888 } else if (strlen(src
) + 1 + strlen(fdat
.cFileName
) >= sizeof(buf
)) {
889 run_err("%s/%s: Name too long", src
, fdat
.cFileName
);
891 sprintf(buf
, "%s/%s", src
, fdat
.cFileName
);
894 ok
= FindNextFile(dir
, &fdat
);
899 back
->send(buf
, strlen(buf
));
904 * Execute the sink part of the SCP protocol.
906 static void sink(char *targ
, char *src
)
916 unsigned long mtime
, atime
;
918 unsigned long size
, i
;
920 unsigned long stat_bytes
;
921 time_t stat_starttime
, stat_lasttime
;
924 attr
= GetFileAttributes(targ
);
925 if (attr
!= (DWORD
) - 1 && (attr
& FILE_ATTRIBUTE_DIRECTORY
) != 0)
928 if (targetshouldbedirectory
&& !targisdir
)
929 bump("%s: Not a directory", targ
);
935 if (ssh_scp_recv(&ch
, 1) <= 0)
938 bump("Protocol error: Unexpected newline");
942 if (ssh_scp_recv(&ch
, 1) <= 0)
943 bump("Lost connection");
945 } while (i
< sizeof(buf
) && ch
!= '\n');
948 case '\01': /* error */
949 tell_user(stderr
, "%s\n", buf
+ 1);
952 case '\02': /* fatal error */
958 if (sscanf(buf
, "T%ld %*d %ld %*d", &mtime
, &atime
) == 2) {
963 bump("Protocol error: Illegal time format");
968 bump("Protocol error: Expected control record");
971 if (sscanf(buf
+ 1, "%u %lu %[^\n]", &mode
, &size
, namebuf
) != 3)
972 bump("Protocol error: Illegal file descriptor format");
973 /* Security fix: ensure the file ends up where we asked for it. */
980 p
= namebuf
+ strlen(namebuf
);
981 while (p
> namebuf
&& p
[-1] != '/' && p
[-1] != '\\')
986 strcpy(namebuf
, targ
);
988 attr
= GetFileAttributes(namebuf
);
989 exists
= (attr
!= (DWORD
) - 1);
992 if (exists
&& (attr
& FILE_ATTRIBUTE_DIRECTORY
) == 0) {
993 run_err("%s: Not a directory", namebuf
);
997 if (!CreateDirectory(namebuf
, NULL
)) {
998 run_err("%s: Cannot create directory", namebuf
);
1002 sink(namebuf
, NULL
);
1003 /* can we set the timestamp for directories ? */
1007 f
= CreateFile(namebuf
, GENERIC_WRITE
, 0, NULL
,
1008 CREATE_ALWAYS
, FILE_ATTRIBUTE_NORMAL
, 0);
1009 if (f
== INVALID_HANDLE_VALUE
) {
1010 run_err("%s: Cannot create file", namebuf
);
1017 stat_starttime
= time(NULL
);
1019 if ((stat_name
= strrchr(namebuf
, '/')) == NULL
)
1020 stat_name
= namebuf
;
1023 if (strrchr(stat_name
, '\\') != NULL
)
1024 stat_name
= strrchr(stat_name
, '\\') + 1;
1026 for (i
= 0; i
< size
; i
+= 4096) {
1027 char transbuf
[4096];
1031 if (ssh_scp_recv(transbuf
, k
) == 0)
1032 bump("Lost connection");
1035 if (!WriteFile(f
, transbuf
, k
, &j
, NULL
) || j
!= k
) {
1038 printf("\r%-25.25s | %50s\n",
1040 "Write error.. waiting for end of file");
1045 if (time(NULL
) > stat_lasttime
|| i
+ k
== size
) {
1046 stat_lasttime
= time(NULL
);
1047 print_stats(stat_name
, size
, stat_bytes
,
1048 stat_starttime
, stat_lasttime
);
1055 FILETIME actime
, wrtime
;
1056 TIME_POSIX_TO_WIN(atime
, actime
);
1057 TIME_POSIX_TO_WIN(mtime
, wrtime
);
1058 SetFileTime(f
, NULL
, &actime
, &wrtime
);
1063 run_err("%s: Write error", namebuf
);
1071 * We will copy local files to a remote server.
1073 static void toremote(int argc
, char *argv
[])
1075 char *src
, *targ
, *host
, *user
;
1079 targ
= argv
[argc
- 1];
1081 /* Separate host from filename */
1085 bump("targ == NULL in toremote()");
1089 /* Substitute "." for emtpy target */
1091 /* Separate host and username */
1093 host
= strrchr(host
, '@');
1104 /* Find out if the source filespec covers multiple files
1105 if so, we should set the targetshouldbedirectory flag */
1107 WIN32_FIND_DATA fdat
;
1108 if (colon(argv
[0]) != NULL
)
1109 bump("%s: Remote to remote not supported", argv
[0]);
1110 fh
= FindFirstFile(argv
[0], &fdat
);
1111 if (fh
== INVALID_HANDLE_VALUE
)
1112 bump("%s: No such file or directory\n", argv
[0]);
1113 if (FindNextFile(fh
, &fdat
))
1114 targetshouldbedirectory
= 1;
1118 cmd
= smalloc(strlen(targ
) + 100);
1119 sprintf(cmd
, "scp%s%s%s%s -t %s",
1120 verbose ?
" -v" : "",
1121 recursive ?
" -r" : "",
1122 preserve ?
" -p" : "",
1123 targetshouldbedirectory ?
" -d" : "", targ
);
1124 do_cmd(host
, user
, cmd
);
1129 for (i
= 0; i
< argc
- 1; i
++) {
1131 WIN32_FIND_DATA fdat
;
1133 if (colon(src
) != NULL
) {
1134 tell_user(stderr
, "%s: Remote to remote not supported\n", src
);
1138 dir
= FindFirstFile(src
, &fdat
);
1139 if (dir
== INVALID_HANDLE_VALUE
) {
1140 run_err("%s: No such file or directory", src
);
1147 * Ensure that . and .. are never matched by wildcards,
1148 * but only by deliberate action.
1150 if (!strcmp(fdat
.cFileName
, ".") ||
1151 !strcmp(fdat
.cFileName
, "..")) {
1153 * Find*File has returned a special dir. We require
1154 * that _either_ `src' ends in a backslash followed
1155 * by that string, _or_ `src' is precisely that
1158 int len
= strlen(src
), dlen
= strlen(fdat
.cFileName
);
1159 if (len
== dlen
&& !strcmp(src
, fdat
.cFileName
)) {
1161 } else if (len
> dlen
+ 1 && src
[len
- dlen
- 1] == '\\' &&
1162 !strcmp(src
+ len
- dlen
, fdat
.cFileName
)) {
1165 continue; /* ignore this one */
1167 if (strlen(src
) + strlen(fdat
.cFileName
) >= sizeof(namebuf
)) {
1168 tell_user(stderr
, "%s: Name too long", src
);
1171 strcpy(namebuf
, src
);
1172 if ((last
= strrchr(namebuf
, '/')) == NULL
)
1176 if (strrchr(last
, '\\') != NULL
)
1177 last
= strrchr(last
, '\\') + 1;
1178 if (last
== namebuf
&& strrchr(namebuf
, ':') != NULL
)
1179 last
= strchr(namebuf
, ':') + 1;
1180 strcpy(last
, fdat
.cFileName
);
1182 } while (FindNextFile(dir
, &fdat
));
1188 * We will copy files from a remote server to the local machine.
1190 static void tolocal(int argc
, char *argv
[])
1192 char *src
, *targ
, *host
, *user
;
1196 bump("More than one remote source not supported");
1201 /* Separate host from filename */
1205 bump("Local to local copy not supported");
1209 /* Substitute "." for empty filename */
1211 /* Separate username and hostname */
1213 host
= strrchr(host
, '@');
1223 cmd
= smalloc(strlen(src
) + 100);
1224 sprintf(cmd
, "scp%s%s%s%s -f %s",
1225 verbose ?
" -v" : "",
1226 recursive ?
" -r" : "",
1227 preserve ?
" -p" : "",
1228 targetshouldbedirectory ?
" -d" : "", src
);
1229 do_cmd(host
, user
, cmd
);
1236 * We will issue a list command to get a remote directory.
1238 static void get_dir_list(int argc
, char *argv
[])
1240 char *src
, *host
, *user
;
1246 /* Separate host from filename */
1250 bump("Local to local copy not supported");
1254 /* Substitute "." for empty filename */
1256 /* Separate username and hostname */
1258 host
= strrchr(host
, '@');
1268 cmd
= smalloc(4 * strlen(src
) + 100);
1269 strcpy(cmd
, "ls -la '");
1270 p
= cmd
+ strlen(cmd
);
1271 for (q
= src
; *q
; q
++) {
1284 do_cmd(host
, user
, cmd
);
1287 while (ssh_scp_recv(&c
, 1) > 0)
1288 tell_char(stdout
, c
);
1292 * Initialize the Win$ock driver.
1294 static void init_winsock(void)
1299 winsock_ver
= MAKEWORD(1, 1);
1300 if (WSAStartup(winsock_ver
, &wsadata
))
1301 bump("Unable to initialise WinSock");
1302 if (LOBYTE(wsadata
.wVersion
) != 1 || HIBYTE(wsadata
.wVersion
) != 1)
1303 bump("WinSock version is incompatible with 1.1");
1307 * Short description of parameters.
1309 static void usage(void)
1311 printf("PuTTY Secure Copy client\n");
1312 printf("%s\n", ver
);
1313 printf("Usage: pscp [options] [user@]host:source target\n");
1315 (" pscp [options] source [source...] [user@]host:target\n");
1316 printf(" pscp [options] -ls user@host:filespec\n");
1317 printf("Options:\n");
1318 printf(" -p preserve file attributes\n");
1319 printf(" -q quiet, don't show statistics\n");
1320 printf(" -r copy directories recursively\n");
1321 printf(" -v show verbose messages\n");
1322 printf(" -P port connect to specified port\n");
1323 printf(" -pw passw login with specified password\n");
1326 * -gui is an internal option, used by GUI front ends to get
1327 * pscp to pass progress reports back to them. It's not an
1328 * ordinary user-accessible option, so it shouldn't be part of
1329 * the command-line help. The only people who need to know
1330 * about it are programmers, and they can read the source.
1333 (" -gui hWnd GUI mode with the windows handle for receiving messages\n");
1339 * Main program (no, really?)
1341 int main(int argc
, char *argv
[])
1345 default_protocol
= PROT_TELNET
;
1347 flags
= FLAG_STDERR
;
1348 ssh_get_line
= &get_line
;
1352 for (i
= 1; i
< argc
; i
++) {
1353 if (argv
[i
][0] != '-')
1355 if (strcmp(argv
[i
], "-v") == 0)
1356 verbose
= 1, flags
|= FLAG_VERBOSE
;
1357 else if (strcmp(argv
[i
], "-r") == 0)
1359 else if (strcmp(argv
[i
], "-p") == 0)
1361 else if (strcmp(argv
[i
], "-q") == 0)
1363 else if (strcmp(argv
[i
], "-h") == 0 || strcmp(argv
[i
], "-?") == 0)
1365 else if (strcmp(argv
[i
], "-P") == 0 && i
+ 1 < argc
)
1366 portnumber
= atoi(argv
[++i
]);
1367 else if (strcmp(argv
[i
], "-pw") == 0 && i
+ 1 < argc
)
1368 password
= argv
[++i
];
1369 else if (strcmp(argv
[i
], "-gui") == 0 && i
+ 1 < argc
) {
1370 gui_hwnd
= argv
[++i
];
1372 } else if (strcmp(argv
[i
], "-ls") == 0)
1374 else if (strcmp(argv
[i
], "--") == 0) {
1387 get_dir_list(argc
, argv
);
1394 targetshouldbedirectory
= 1;
1396 if (colon(argv
[argc
- 1]) != NULL
)
1397 toremote(argc
, argv
);
1399 tolocal(argc
, argv
);
1402 if (back
!= NULL
&& back
->socket() != NULL
) {
1404 back
->special(TS_EOF
);
1405 ssh_scp_recv(&ch
, 1);
1410 /* GUI Adaptation - August 2000 */
1412 unsigned int msg_id
= WM_RET_ERR_CNT
;
1414 msg_id
= WM_LS_RET_ERR_CNT
;
1416 ((HWND
) atoi(gui_hwnd
), msg_id
, (WPARAM
) errs
,
1417 0 /*lParam */ ))SleepEx(1000, TRUE
);
1419 return (errs
== 0 ?
0 : 1);