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
23 /* GUI Adaptation - Sept 2000 */
27 #define PUTTY_DO_GLOBALS
31 #define TIME_POSIX_TO_WIN(t, ft) (*(LONGLONG*)&(ft) = \
32 ((LONGLONG) (t) + (LONGLONG) 11644473600) * (LONGLONG) 10000000)
33 #define TIME_WIN_TO_POSIX(ft, t) ((t) = (unsigned long) \
34 ((*(LONGLONG*)&(ft)) / (LONGLONG) 10000000 - (LONGLONG) 11644473600))
36 /* GUI Adaptation - Sept 2000 */
37 #define WM_APP_BASE 0x8000
38 #define WM_STD_OUT_CHAR ( WM_APP_BASE+400 )
39 #define WM_STD_ERR_CHAR ( WM_APP_BASE+401 )
40 #define WM_STATS_CHAR ( WM_APP_BASE+402 )
41 #define WM_STATS_SIZE ( WM_APP_BASE+403 )
42 #define WM_STATS_PERCENT ( WM_APP_BASE+404 )
43 #define WM_STATS_ELAPSED ( WM_APP_BASE+405 )
44 #define WM_RET_ERR_CNT ( WM_APP_BASE+406 )
45 #define WM_LS_RET_ERR_CNT ( WM_APP_BASE+407 )
47 static int verbose
= 0;
48 static int recursive
= 0;
49 static int preserve
= 0;
50 static int targetshouldbedirectory
= 0;
51 static int statistics
= 1;
52 static int portnumber
= 0;
53 static char *password
= NULL
;
55 static int connection_open
= 0;
56 /* GUI Adaptation - Sept 2000 */
57 #define NAME_STR_MAX 2048
58 static char statname
[NAME_STR_MAX
+1];
59 static unsigned long statsize
= 0;
60 static int statperct
= 0;
61 static time_t statelapsed
= 0;
62 static int gui_mode
= 0;
63 static char *gui_hwnd
= NULL
;
65 static void source(char *src
);
66 static void rsource(char *src
);
67 static void sink(char *targ
);
68 /* GUI Adaptation - Sept 2000 */
69 static void tell_char(FILE *stream
, char c
);
70 static void tell_str(FILE *stream
, char *str
);
71 static void tell_user(FILE *stream
, char *fmt
, ...);
72 static void send_char_msg(unsigned int msg_id
, char c
);
73 static void send_str_msg(unsigned int msg_id
, char *str
);
74 static void gui_update_stats(char *name
, unsigned long size
, int percentage
, time_t elapsed
);
77 * These functions are needed to link with ssh.c, but never get called.
83 void begin_session(void) {
86 /* GUI Adaptation - Sept 2000 */
87 void send_msg(HWND h
, UINT message
, WPARAM wParam
)
89 while (!PostMessage( h
, message
, wParam
, 0))
93 void tell_char(FILE *stream
, char c
)
99 unsigned int msg_id
= WM_STD_OUT_CHAR
;
100 if (stream
= stderr
) msg_id
= WM_STD_ERR_CHAR
;
101 send_msg( (HWND
)atoi(gui_hwnd
), msg_id
, (WPARAM
)c
);
105 void tell_str(FILE *stream
, char *str
)
109 for( i
= 0; i
< strlen(str
); ++i
)
110 tell_char(stream
, str
[i
]);
113 void tell_user(FILE *stream
, char *fmt
, ...)
115 char str
[0x100]; /* Make the size big enough */
118 vsprintf(str
, fmt
, ap
);
121 tell_str(stream
, str
);
124 void gui_update_stats(char *name
, unsigned long size
, int percentage
, time_t elapsed
)
128 if (strcmp(name
,statname
) != 0)
130 for( i
= 0; i
< strlen(name
); ++i
)
131 send_msg( (HWND
)atoi(gui_hwnd
), WM_STATS_CHAR
, (WPARAM
)name
[i
]);
132 send_msg( (HWND
)atoi(gui_hwnd
), WM_STATS_CHAR
, (WPARAM
)'\n' );
133 strcpy(statname
,name
);
135 if (statsize
!= size
)
137 send_msg( (HWND
)atoi(gui_hwnd
), WM_STATS_SIZE
, (WPARAM
)size
);
140 if (statelapsed
!= elapsed
)
142 send_msg( (HWND
)atoi(gui_hwnd
), WM_STATS_ELAPSED
, (WPARAM
)elapsed
);
143 statelapsed
= elapsed
;
145 if (statperct
!= percentage
)
147 send_msg( (HWND
)atoi(gui_hwnd
), WM_STATS_PERCENT
, (WPARAM
)percentage
);
148 statperct
= percentage
;
153 * Print an error message and perform a fatal exit.
155 void fatalbox(char *fmt
, ...)
157 char str
[0x100]; /* Make the size big enough */
160 strcpy(str
, "Fatal:");
161 vsprintf(str
+strlen(str
), fmt
, ap
);
164 tell_str(stderr
, str
);
168 void connection_fatal(char *fmt
, ...)
170 char str
[0x100]; /* Make the size big enough */
173 strcpy(str
, "Fatal:");
174 vsprintf(str
+strlen(str
), fmt
, ap
);
177 tell_str(stderr
, str
);
183 * Print an error message and exit after closing the SSH link.
185 static void bump(char *fmt
, ...)
187 char str
[0x100]; /* Make the size big enough */
190 strcpy(str
, "Fatal:");
191 vsprintf(str
+strlen(str
), fmt
, ap
);
194 tell_str(stderr
, str
);
196 if (connection_open
) {
199 ssh_scp_recv(&ch
, 1);
204 static int get_password(const char *prompt
, char *str
, int maxlen
)
210 static int tried_once
= 0;
215 strncpy(str
, password
, maxlen
);
216 str
[maxlen
-1] = '\0';
222 /* GUI Adaptation - Sept 2000 */
224 if (maxlen
>0) str
[0] = '\0';
226 hin
= GetStdHandle(STD_INPUT_HANDLE
);
227 hout
= GetStdHandle(STD_OUTPUT_HANDLE
);
228 if (hin
== INVALID_HANDLE_VALUE
|| hout
== INVALID_HANDLE_VALUE
)
229 bump("Cannot get standard input/output handles");
231 GetConsoleMode(hin
, &savemode
);
232 SetConsoleMode(hin
, (savemode
& (~ENABLE_ECHO_INPUT
)) |
233 ENABLE_PROCESSED_INPUT
| ENABLE_LINE_INPUT
);
235 WriteFile(hout
, prompt
, strlen(prompt
), &i
, NULL
);
236 ReadFile(hin
, str
, maxlen
-1, &i
, NULL
);
238 SetConsoleMode(hin
, savemode
);
240 if ((int)i
> maxlen
) i
= maxlen
-1; else i
= i
- 2;
243 WriteFile(hout
, "\r\n", 2, &i
, NULL
);
250 * Open an SSH connection to user@host and execute cmd.
252 static void do_cmd(char *host
, char *user
, char *cmd
)
254 char *err
, *realhost
;
256 if (host
== NULL
|| host
[0] == '\0')
257 bump("Empty host name");
259 /* Try to load settings for this host */
261 if (cfg
.host
[0] == '\0') {
262 /* No settings for this host; use defaults */
263 strncpy(cfg
.host
, host
, sizeof(cfg
.host
)-1);
264 cfg
.host
[sizeof(cfg
.host
)-1] = '\0';
269 if (user
!= NULL
&& user
[0] != '\0') {
270 strncpy(cfg
.username
, user
, sizeof(cfg
.username
)-1);
271 cfg
.username
[sizeof(cfg
.username
)-1] = '\0';
272 } else if (cfg
.username
[0] == '\0') {
273 bump("Empty user name");
276 if (cfg
.protocol
!= PROT_SSH
)
280 cfg
.port
= portnumber
;
282 err
= ssh_scp_init(cfg
.host
, cfg
.port
, cmd
, &realhost
);
284 bump("ssh_init: %s", err
);
285 if (verbose
&& realhost
!= NULL
)
286 tell_user(stderr
, "Connected to %s\n", realhost
);
292 * Update statistic information about current file.
294 static void print_stats(char *name
, unsigned long size
, unsigned long done
,
295 time_t start
, time_t now
)
302 /* GUI Adaptation - Sept 2000 */
304 gui_update_stats(name
, size
, ((done
*100) / size
), now
-start
);
307 ratebs
= (float) done
/ (now
- start
);
309 ratebs
= (float) done
;
314 eta
= (unsigned long) ((size
- done
) / ratebs
);
315 sprintf(etastr
, "%02ld:%02ld:%02ld",
316 eta
/ 3600, (eta
% 3600) / 60, eta
% 60);
318 pct
= (int) (100.0 * (float) done
/ size
);
320 printf("\r%-25.25s | %10ld kB | %5.1f kB/s | ETA: %8s | %3d%%",
321 name
, done
/ 1024, ratebs
/ 1024.0,
330 * Find a colon in str and return a pointer to the colon.
331 * This is used to separate hostname from filename.
333 static char * colon(char *str
)
335 /* We ignore a leading colon, since the hostname cannot be
336 empty. We also ignore a colon as second character because
337 of filenames like f:myfile.txt. */
338 if (str
[0] == '\0' ||
342 while (*str
!= '\0' &&
354 * Wait for a response from the other side.
355 * Return 0 if ok, -1 if error.
357 static int response(void)
359 char ch
, resp
, rbuf
[2048];
362 if (ssh_scp_recv(&resp
, 1) <= 0)
363 bump("Lost connection");
373 case 2: /* fatal error */
375 if (ssh_scp_recv(&ch
, 1) <= 0)
376 bump("Protocol error: Lost connection");
378 } while (p
< sizeof(rbuf
) && ch
!= '\n');
381 tell_user(stderr
, "%s\n", rbuf
);
390 * Send an error message to the other side and to the screen.
391 * Increment error counter.
393 static void run_err(const char *fmt
, ...)
399 strcpy(str
, "\01scp: ");
400 vsprintf(str
+strlen(str
), fmt
, ap
);
402 ssh_scp_send(str
, strlen(str
));
403 tell_user(stderr
, "%s",str
);
408 * Execute the source part of the SCP protocol.
410 static void source(char *src
)
418 unsigned long stat_bytes
;
419 time_t stat_starttime
, stat_lasttime
;
421 attr
= GetFileAttributes(src
);
422 if (attr
== (DWORD
)-1) {
423 run_err("%s: No such file or directory", src
);
427 if ((attr
& FILE_ATTRIBUTE_DIRECTORY
) != 0) {
430 * Avoid . and .. directories.
433 p
= strrchr(src
, '/');
435 p
= strrchr(src
, '\\');
440 if (!strcmp(p
, ".") || !strcmp(p
, ".."))
445 run_err("%s: not a regular file", src
);
450 if ((last
= strrchr(src
, '/')) == NULL
)
454 if (strrchr(last
, '\\') != NULL
)
455 last
= strrchr(last
, '\\') + 1;
456 if (last
== src
&& strchr(src
, ':') != NULL
)
457 last
= strchr(src
, ':') + 1;
459 f
= CreateFile(src
, GENERIC_READ
, FILE_SHARE_READ
, NULL
,
460 OPEN_EXISTING
, 0, 0);
461 if (f
== INVALID_HANDLE_VALUE
) {
462 run_err("%s: Cannot open file", src
);
467 FILETIME actime
, wrtime
;
468 unsigned long mtime
, atime
;
469 GetFileTime(f
, NULL
, &actime
, &wrtime
);
470 TIME_WIN_TO_POSIX(actime
, atime
);
471 TIME_WIN_TO_POSIX(wrtime
, mtime
);
472 sprintf(buf
, "T%lu 0 %lu 0\n", mtime
, atime
);
473 ssh_scp_send(buf
, strlen(buf
));
478 size
= GetFileSize(f
, NULL
);
479 sprintf(buf
, "C0644 %lu %s\n", size
, last
);
481 tell_user(stderr
, "Sending file modes: %s", buf
);
482 ssh_scp_send(buf
, strlen(buf
));
488 stat_starttime
= time(NULL
);
492 for (i
= 0; i
< size
; i
+= 4096) {
495 if (i
+ k
> size
) k
= size
- i
;
496 if (! ReadFile(f
, transbuf
, k
, &j
, NULL
) || j
!= k
) {
497 if (statistics
) printf("\n");
498 bump("%s: Read error", src
);
500 ssh_scp_send(transbuf
, k
);
503 if (time(NULL
) != stat_lasttime
||
505 stat_lasttime
= time(NULL
);
506 print_stats(last
, size
, stat_bytes
,
507 stat_starttime
, stat_lasttime
);
518 * Recursively send the contents of a directory.
520 static void rsource(char *src
)
525 WIN32_FIND_DATA fdat
;
528 if ((last
= strrchr(src
, '/')) == NULL
)
532 if (strrchr(last
, '\\') != NULL
)
533 last
= strrchr(last
, '\\') + 1;
534 if (last
== src
&& strchr(src
, ':') != NULL
)
535 last
= strchr(src
, ':') + 1;
537 /* maybe send filetime */
539 sprintf(buf
, "D0755 0 %s\n", last
);
541 tell_user(stderr
, "Entering directory: %s", buf
);
542 ssh_scp_send(buf
, strlen(buf
));
546 sprintf(buf
, "%s/*", src
);
547 dir
= FindFirstFile(buf
, &fdat
);
548 ok
= (dir
!= INVALID_HANDLE_VALUE
);
550 if (strcmp(fdat
.cFileName
, ".") == 0 ||
551 strcmp(fdat
.cFileName
, "..") == 0) {
552 } else if (strlen(src
) + 1 + strlen(fdat
.cFileName
) >=
554 run_err("%s/%s: Name too long", src
, fdat
.cFileName
);
556 sprintf(buf
, "%s/%s", src
, fdat
.cFileName
);
559 ok
= FindNextFile(dir
, &fdat
);
564 ssh_scp_send(buf
, strlen(buf
));
569 * Execute the sink part of the SCP protocol.
571 static void sink(char *targ
)
581 unsigned long mtime
, atime
;
583 unsigned long size
, i
;
585 unsigned long stat_bytes
;
586 time_t stat_starttime
, stat_lasttime
;
589 attr
= GetFileAttributes(targ
);
590 if (attr
!= (DWORD
)-1 && (attr
& FILE_ATTRIBUTE_DIRECTORY
) != 0)
593 if (targetshouldbedirectory
&& !targisdir
)
594 bump("%s: Not a directory", targ
);
600 if (ssh_scp_recv(&ch
, 1) <= 0)
603 bump("Protocol error: Unexpected newline");
607 if (ssh_scp_recv(&ch
, 1) <= 0)
608 bump("Lost connection");
610 } while (i
< sizeof(buf
) && ch
!= '\n');
613 case '\01': /* error */
614 tell_user(stderr
, "%s\n", buf
+1);
617 case '\02': /* fatal error */
623 if (sscanf(buf
, "T%ld %*d %ld %*d",
624 &mtime
, &atime
) == 2) {
629 bump("Protocol error: Illegal time format");
634 bump("Protocol error: Expected control record");
637 if (sscanf(buf
+1, "%u %lu %[^\n]", &mode
, &size
, namebuf
) != 3)
638 bump("Protocol error: Illegal file descriptor format");
647 strcpy(namebuf
, targ
);
649 attr
= GetFileAttributes(namebuf
);
650 exists
= (attr
!= (DWORD
)-1);
653 if (exists
&& (attr
& FILE_ATTRIBUTE_DIRECTORY
) == 0) {
654 run_err("%s: Not a directory", namebuf
);
658 if (! CreateDirectory(namebuf
, NULL
)) {
659 run_err("%s: Cannot create directory",
665 /* can we set the timestamp for directories ? */
669 f
= CreateFile(namebuf
, GENERIC_WRITE
, 0, NULL
,
670 CREATE_ALWAYS
, FILE_ATTRIBUTE_NORMAL
, 0);
671 if (f
== INVALID_HANDLE_VALUE
) {
672 run_err("%s: Cannot create file", namebuf
);
680 stat_starttime
= time(NULL
);
682 if ((stat_name
= strrchr(namebuf
, '/')) == NULL
)
686 if (strrchr(stat_name
, '\\') != NULL
)
687 stat_name
= strrchr(stat_name
, '\\') + 1;
690 for (i
= 0; i
< size
; i
+= 4096) {
693 if (i
+ k
> size
) k
= size
- i
;
694 if (ssh_scp_recv(transbuf
, k
) == 0)
695 bump("Lost connection");
696 if (wrerror
) continue;
697 if (! WriteFile(f
, transbuf
, k
, &j
, NULL
) || j
!= k
) {
700 printf("\r%-25.25s | %50s\n",
702 "Write error.. waiting for end of file");
707 if (time(NULL
) > stat_lasttime
||
709 stat_lasttime
= time(NULL
);
710 print_stats(stat_name
, size
, stat_bytes
,
711 stat_starttime
, stat_lasttime
);
718 FILETIME actime
, wrtime
;
719 TIME_POSIX_TO_WIN(atime
, actime
);
720 TIME_POSIX_TO_WIN(mtime
, wrtime
);
721 SetFileTime(f
, NULL
, &actime
, &wrtime
);
726 run_err("%s: Write error", namebuf
);
734 * We will copy local files to a remote server.
736 static void toremote(int argc
, char *argv
[])
738 char *src
, *targ
, *host
, *user
;
744 /* Separate host from filename */
748 bump("targ == NULL in toremote()");
752 /* Substitute "." for emtpy target */
754 /* Separate host and username */
756 host
= strrchr(host
, '@');
767 /* Find out if the source filespec covers multiple files
768 if so, we should set the targetshouldbedirectory flag */
770 WIN32_FIND_DATA fdat
;
771 if (colon(argv
[0]) != NULL
)
772 bump("%s: Remote to remote not supported", argv
[0]);
773 fh
= FindFirstFile(argv
[0], &fdat
);
774 if (fh
== INVALID_HANDLE_VALUE
)
775 bump("%s: No such file or directory\n", argv
[0]);
776 if (FindNextFile(fh
, &fdat
))
777 targetshouldbedirectory
= 1;
781 cmd
= smalloc(strlen(targ
) + 100);
782 sprintf(cmd
, "scp%s%s%s%s -t %s",
783 verbose ?
" -v" : "",
784 recursive ?
" -r" : "",
785 preserve ?
" -p" : "",
786 targetshouldbedirectory ?
" -d" : "",
788 do_cmd(host
, user
, cmd
);
793 for (i
= 0; i
< argc
- 1; i
++) {
795 WIN32_FIND_DATA fdat
;
797 if (colon(src
) != NULL
) {
798 tell_user(stderr
, "%s: Remote to remote not supported\n", src
);
802 dir
= FindFirstFile(src
, &fdat
);
803 if (dir
== INVALID_HANDLE_VALUE
) {
804 run_err("%s: No such file or directory", src
);
810 if (strlen(src
) + strlen(fdat
.cFileName
) >=
812 tell_user(stderr
, "%s: Name too long", src
);
815 strcpy(namebuf
, src
);
816 if ((last
= strrchr(namebuf
, '/')) == NULL
)
820 if (strrchr(last
, '\\') != NULL
)
821 last
= strrchr(last
, '\\') + 1;
822 if (last
== namebuf
&& strrchr(namebuf
, ':') != NULL
)
823 last
= strchr(namebuf
, ':') + 1;
824 strcpy(last
, fdat
.cFileName
);
826 } while (FindNextFile(dir
, &fdat
));
832 * We will copy files from a remote server to the local machine.
834 static void tolocal(int argc
, char *argv
[])
836 char *src
, *targ
, *host
, *user
;
840 bump("More than one remote source not supported");
845 /* Separate host from filename */
849 bump("Local to local copy not supported");
853 /* Substitute "." for empty filename */
855 /* Separate username and hostname */
857 host
= strrchr(host
, '@');
867 cmd
= smalloc(strlen(src
) + 100);
868 sprintf(cmd
, "scp%s%s%s%s -f %s",
869 verbose ?
" -v" : "",
870 recursive ?
" -r" : "",
871 preserve ?
" -p" : "",
872 targetshouldbedirectory ?
" -d" : "",
874 do_cmd(host
, user
, cmd
);
881 * We will issue a list command to get a remote directory.
883 static void get_dir_list(int argc
, char *argv
[])
885 char *src
, *host
, *user
;
891 /* Separate host from filename */
895 bump("Local to local copy not supported");
899 /* Substitute "." for empty filename */
901 /* Separate username and hostname */
903 host
= strrchr(host
, '@');
913 cmd
= smalloc(4*strlen(src
) + 100);
914 strcpy(cmd
, "ls -la '");
915 p
= cmd
+ strlen(cmd
);
916 for (q
= src
; *q
; q
++) {
918 *p
++ = '\''; *p
++ = '\\'; *p
++ = '\''; *p
++ = '\'';
926 do_cmd(host
, user
, cmd
);
929 while (ssh_scp_recv(&c
, 1) > 0)
930 tell_char(stdout
, c
);
934 * Initialize the Win$ock driver.
936 static void init_winsock(void)
941 winsock_ver
= MAKEWORD(1, 1);
942 if (WSAStartup(winsock_ver
, &wsadata
))
943 bump("Unable to initialise WinSock");
944 if (LOBYTE(wsadata
.wVersion
) != 1 ||
945 HIBYTE(wsadata
.wVersion
) != 1)
946 bump("WinSock version is incompatible with 1.1");
950 * Short description of parameters.
952 static void usage(void)
954 printf("PuTTY Secure Copy client\n");
956 printf("Usage: pscp [options] [user@]host:source target\n");
957 printf(" pscp [options] source [source...] [user@]host:target\n");
958 printf(" pscp [options] -ls user@host:filespec\n");
959 printf("Options:\n");
960 printf(" -p preserve file attributes\n");
961 printf(" -q quiet, don't show statistics\n");
962 printf(" -r copy directories recursively\n");
963 printf(" -v show verbose messages\n");
964 printf(" -P port connect to specified port\n");
965 printf(" -pw passw login with specified password\n");
966 /* GUI Adaptation - Sept 2000 */
967 printf(" -gui hWnd GUI mode with the windows handle for receiving messages\n");
972 * Main program (no, really?)
974 int main(int argc
, char *argv
[])
979 default_protocol
= PROT_TELNET
;
982 ssh_get_password
= &get_password
;
985 for (i
= 1; i
< argc
; i
++) {
986 if (argv
[i
][0] != '-')
988 if (strcmp(argv
[i
], "-v") == 0)
989 verbose
= 1, flags
|= FLAG_VERBOSE
;
990 else if (strcmp(argv
[i
], "-r") == 0)
992 else if (strcmp(argv
[i
], "-p") == 0)
994 else if (strcmp(argv
[i
], "-q") == 0)
996 else if (strcmp(argv
[i
], "-h") == 0 ||
997 strcmp(argv
[i
], "-?") == 0)
999 else if (strcmp(argv
[i
], "-P") == 0 && i
+1 < argc
)
1000 portnumber
= atoi(argv
[++i
]);
1001 else if (strcmp(argv
[i
], "-pw") == 0 && i
+1 < argc
)
1002 password
= argv
[++i
];
1003 else if (strcmp(argv
[i
], "-gui") == 0 && i
+1 < argc
) {
1004 gui_hwnd
= argv
[++i
];
1006 } else if (strcmp(argv
[i
], "-ls") == 0)
1008 else if (strcmp(argv
[i
], "--") == 0)
1019 get_dir_list(argc
, argv
);
1026 targetshouldbedirectory
= 1;
1028 if (colon(argv
[argc
-1]) != NULL
)
1029 toremote(argc
, argv
);
1031 tolocal(argc
, argv
);
1034 if (connection_open
) {
1037 ssh_scp_recv(&ch
, 1);
1042 /* GUI Adaptation - August 2000 */
1044 unsigned int msg_id
= WM_RET_ERR_CNT
;
1045 if (list
) msg_id
= WM_LS_RET_ERR_CNT
;
1046 while (!PostMessage( (HWND
)atoi(gui_hwnd
), msg_id
, (WPARAM
)errs
, 0/*lParam*/ ) )
1049 return (errs
== 0 ?
0 : 1);