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
17 /* GUI Adaptation - Sept 2000 */
21 #define PUTTY_DO_GLOBALS
25 #define TIME_POSIX_TO_WIN(t, ft) (*(LONGLONG*)&(ft) = \
26 ((LONGLONG) (t) + (LONGLONG) 11644473600) * (LONGLONG) 10000000)
27 #define TIME_WIN_TO_POSIX(ft, t) ((t) = (unsigned long) \
28 ((*(LONGLONG*)&(ft)) / (LONGLONG) 10000000 - (LONGLONG) 11644473600))
30 /* GUI Adaptation - Sept 2000 */
31 #define WM_APP_BASE 0x8000
32 #define WM_STD_OUT_CHAR ( WM_APP_BASE+400 )
33 #define WM_STD_ERR_CHAR ( WM_APP_BASE+401 )
34 #define WM_STATS_CHAR ( WM_APP_BASE+402 )
35 #define WM_STATS_SIZE ( WM_APP_BASE+403 )
36 #define WM_STATS_PERCENT ( WM_APP_BASE+404 )
37 #define WM_STATS_ELAPSED ( WM_APP_BASE+405 )
38 #define WM_RET_ERR_CNT ( WM_APP_BASE+406 )
39 #define WM_LS_RET_ERR_CNT ( WM_APP_BASE+407 )
41 static int verbose
= 0;
42 static int recursive
= 0;
43 static int preserve
= 0;
44 static int targetshouldbedirectory
= 0;
45 static int statistics
= 1;
46 static int portnumber
= 0;
47 static char *password
= NULL
;
49 static int connection_open
= 0;
50 /* GUI Adaptation - Sept 2000 */
51 #define NAME_STR_MAX 2048
52 static char statname
[NAME_STR_MAX
+1];
53 static unsigned long statsize
= 0;
54 static int statperct
= 0;
55 static time_t statelapsed
= 0;
56 static int gui_mode
= 0;
57 static char *gui_hwnd
= NULL
;
59 static void source(char *src
);
60 static void rsource(char *src
);
61 static void sink(char *targ
);
62 /* GUI Adaptation - Sept 2000 */
63 static void tell_char(FILE *stream
, char c
);
64 static void tell_str(FILE *stream
, char *str
);
65 static void tell_user(FILE *stream
, char *fmt
, ...);
66 static void send_char_msg(unsigned int msg_id
, char c
);
67 static void send_str_msg(unsigned int msg_id
, char *str
);
68 static void gui_update_stats(char *name
, unsigned long size
, int percentage
, time_t elapsed
);
71 * This function is needed to link with ssh.c, but it never gets called.
78 /* GUI Adaptation - Sept 2000 */
79 void send_msg(HWND h
, UINT message
, WPARAM wParam
)
81 while (!PostMessage( h
, message
, wParam
, 0))
85 void tell_char(FILE *stream
, char c
)
91 unsigned int msg_id
= WM_STD_OUT_CHAR
;
92 if (stream
= stderr
) msg_id
= WM_STD_ERR_CHAR
;
93 send_msg( (HWND
)atoi(gui_hwnd
), msg_id
, (WPARAM
)c
);
97 void tell_str(FILE *stream
, char *str
)
101 for( i
= 0; i
< strlen(str
); ++i
)
102 tell_char(stream
, str
[i
]);
105 void tell_user(FILE *stream
, char *fmt
, ...)
107 char str
[0x100]; /* Make the size big enough */
110 vsprintf(str
, fmt
, ap
);
113 tell_str(stream
, str
);
116 void gui_update_stats(char *name
, unsigned long size
, int percentage
, time_t elapsed
)
120 if (strcmp(name
,statname
) != 0)
122 for( i
= 0; i
< strlen(name
); ++i
)
123 send_msg( (HWND
)atoi(gui_hwnd
), WM_STATS_CHAR
, (WPARAM
)name
[i
]);
124 send_msg( (HWND
)atoi(gui_hwnd
), WM_STATS_CHAR
, (WPARAM
)'\n' );
125 strcpy(statname
,name
);
127 if (statsize
!= size
)
129 send_msg( (HWND
)atoi(gui_hwnd
), WM_STATS_SIZE
, (WPARAM
)size
);
132 if (statelapsed
!= elapsed
)
134 send_msg( (HWND
)atoi(gui_hwnd
), WM_STATS_ELAPSED
, (WPARAM
)elapsed
);
135 statelapsed
= elapsed
;
137 if (statperct
!= percentage
)
139 send_msg( (HWND
)atoi(gui_hwnd
), WM_STATS_PERCENT
, (WPARAM
)percentage
);
140 statperct
= percentage
;
145 * Print an error message and perform a fatal exit.
147 void fatalbox(char *fmt
, ...)
149 char str
[0x100]; /* Make the size big enough */
152 strcpy(str
, "Fatal:");
153 vsprintf(str
+strlen(str
), fmt
, ap
);
156 tell_str(stderr
, str
);
160 void connection_fatal(char *fmt
, ...)
162 char str
[0x100]; /* Make the size big enough */
165 strcpy(str
, "Fatal:");
166 vsprintf(str
+strlen(str
), fmt
, ap
);
169 tell_str(stderr
, str
);
175 * Print an error message and exit after closing the SSH link.
177 static void bump(char *fmt
, ...)
179 char str
[0x100]; /* Make the size big enough */
182 strcpy(str
, "Fatal:");
183 vsprintf(str
+strlen(str
), fmt
, ap
);
186 tell_str(stderr
, str
);
188 if (connection_open
) {
191 ssh_scp_recv(&ch
, 1);
196 static int get_password(const char *prompt
, char *str
, int maxlen
)
202 static int tried_once
= 0;
207 strncpy(str
, password
, maxlen
);
208 str
[maxlen
-1] = '\0';
214 /* GUI Adaptation - Sept 2000 */
216 if (maxlen
>0) str
[0] = '\0';
218 hin
= GetStdHandle(STD_INPUT_HANDLE
);
219 hout
= GetStdHandle(STD_OUTPUT_HANDLE
);
220 if (hin
== INVALID_HANDLE_VALUE
|| hout
== INVALID_HANDLE_VALUE
)
221 bump("Cannot get standard input/output handles");
223 GetConsoleMode(hin
, &savemode
);
224 SetConsoleMode(hin
, (savemode
& (~ENABLE_ECHO_INPUT
)) |
225 ENABLE_PROCESSED_INPUT
| ENABLE_LINE_INPUT
);
227 WriteFile(hout
, prompt
, strlen(prompt
), &i
, NULL
);
228 ReadFile(hin
, str
, maxlen
-1, &i
, NULL
);
230 SetConsoleMode(hin
, savemode
);
232 if ((int)i
> maxlen
) i
= maxlen
-1; else i
= i
- 2;
235 WriteFile(hout
, "\r\n", 2, &i
, NULL
);
242 * Open an SSH connection to user@host and execute cmd.
244 static void do_cmd(char *host
, char *user
, char *cmd
)
246 char *err
, *realhost
;
248 if (host
== NULL
|| host
[0] == '\0')
249 bump("Empty host name");
251 /* Try to load settings for this host */
253 if (cfg
.host
[0] == '\0') {
254 /* No settings for this host; use defaults */
255 strncpy(cfg
.host
, host
, sizeof(cfg
.host
)-1);
256 cfg
.host
[sizeof(cfg
.host
)-1] = '\0';
261 if (user
!= NULL
&& user
[0] != '\0') {
262 strncpy(cfg
.username
, user
, sizeof(cfg
.username
)-1);
263 cfg
.username
[sizeof(cfg
.username
)-1] = '\0';
264 } else if (cfg
.username
[0] == '\0') {
265 bump("Empty user name");
268 if (cfg
.protocol
!= PROT_SSH
)
272 cfg
.port
= portnumber
;
274 err
= ssh_scp_init(cfg
.host
, cfg
.port
, cmd
, &realhost
);
276 bump("ssh_init: %s", err
);
277 if (verbose
&& realhost
!= NULL
)
278 tell_user(stderr
, "Connected to %s\n", realhost
);
284 * Update statistic information about current file.
286 static void print_stats(char *name
, unsigned long size
, unsigned long done
,
287 time_t start
, time_t now
)
294 /* GUI Adaptation - Sept 2000 */
296 gui_update_stats(name
, size
, ((done
*100) / size
), now
-start
);
299 ratebs
= (float) done
/ (now
- start
);
301 ratebs
= (float) done
;
306 eta
= (unsigned long) ((size
- done
) / ratebs
);
307 sprintf(etastr
, "%02ld:%02ld:%02ld",
308 eta
/ 3600, (eta
% 3600) / 60, eta
% 60);
310 pct
= (int) (100.0 * (float) done
/ size
);
312 printf("\r%-25.25s | %10ld kB | %5.1f kB/s | ETA: %8s | %3d%%",
313 name
, done
/ 1024, ratebs
/ 1024.0,
322 * Find a colon in str and return a pointer to the colon.
323 * This is used to separate hostname from filename.
325 static char * colon(char *str
)
327 /* We ignore a leading colon, since the hostname cannot be
328 empty. We also ignore a colon as second character because
329 of filenames like f:myfile.txt. */
330 if (str
[0] == '\0' ||
334 while (*str
!= '\0' &&
346 * Wait for a response from the other side.
347 * Return 0 if ok, -1 if error.
349 static int response(void)
351 char ch
, resp
, rbuf
[2048];
354 if (ssh_scp_recv(&resp
, 1) <= 0)
355 bump("Lost connection");
365 case 2: /* fatal error */
367 if (ssh_scp_recv(&ch
, 1) <= 0)
368 bump("Protocol error: Lost connection");
370 } while (p
< sizeof(rbuf
) && ch
!= '\n');
373 tell_user(stderr
, "%s\n", rbuf
);
382 * Send an error message to the other side and to the screen.
383 * Increment error counter.
385 static void run_err(const char *fmt
, ...)
391 strcpy(str
, "\01scp: ");
392 vsprintf(str
+strlen(str
), fmt
, ap
);
394 ssh_scp_send(str
, strlen(str
));
395 tell_user(stderr
, "%s",str
);
400 * Execute the source part of the SCP protocol.
402 static void source(char *src
)
410 unsigned long stat_bytes
;
411 time_t stat_starttime
, stat_lasttime
;
413 attr
= GetFileAttributes(src
);
414 if (attr
== (DWORD
)-1) {
415 run_err("%s: No such file or directory", src
);
419 if ((attr
& FILE_ATTRIBUTE_DIRECTORY
) != 0) {
422 * Avoid . and .. directories.
425 p
= strrchr(src
, '/');
427 p
= strrchr(src
, '\\');
432 if (!strcmp(p
, ".") || !strcmp(p
, ".."))
437 run_err("%s: not a regular file", src
);
442 if ((last
= strrchr(src
, '/')) == NULL
)
446 if (strrchr(last
, '\\') != NULL
)
447 last
= strrchr(last
, '\\') + 1;
448 if (last
== src
&& strchr(src
, ':') != NULL
)
449 last
= strchr(src
, ':') + 1;
451 f
= CreateFile(src
, GENERIC_READ
, FILE_SHARE_READ
, NULL
,
452 OPEN_EXISTING
, 0, 0);
453 if (f
== INVALID_HANDLE_VALUE
) {
454 run_err("%s: Cannot open file", src
);
459 FILETIME actime
, wrtime
;
460 unsigned long mtime
, atime
;
461 GetFileTime(f
, NULL
, &actime
, &wrtime
);
462 TIME_WIN_TO_POSIX(actime
, atime
);
463 TIME_WIN_TO_POSIX(wrtime
, mtime
);
464 sprintf(buf
, "T%lu 0 %lu 0\n", mtime
, atime
);
465 ssh_scp_send(buf
, strlen(buf
));
470 size
= GetFileSize(f
, NULL
);
471 sprintf(buf
, "C0644 %lu %s\n", size
, last
);
473 tell_user(stderr
, "Sending file modes: %s", buf
);
474 ssh_scp_send(buf
, strlen(buf
));
480 stat_starttime
= time(NULL
);
484 for (i
= 0; i
< size
; i
+= 4096) {
487 if (i
+ k
> size
) k
= size
- i
;
488 if (! ReadFile(f
, transbuf
, k
, &j
, NULL
) || j
!= k
) {
489 if (statistics
) printf("\n");
490 bump("%s: Read error", src
);
492 ssh_scp_send(transbuf
, k
);
495 if (time(NULL
) != stat_lasttime
||
497 stat_lasttime
= time(NULL
);
498 print_stats(last
, size
, stat_bytes
,
499 stat_starttime
, stat_lasttime
);
510 * Recursively send the contents of a directory.
512 static void rsource(char *src
)
517 WIN32_FIND_DATA fdat
;
520 if ((last
= strrchr(src
, '/')) == NULL
)
524 if (strrchr(last
, '\\') != NULL
)
525 last
= strrchr(last
, '\\') + 1;
526 if (last
== src
&& strchr(src
, ':') != NULL
)
527 last
= strchr(src
, ':') + 1;
529 /* maybe send filetime */
531 sprintf(buf
, "D0755 0 %s\n", last
);
533 tell_user(stderr
, "Entering directory: %s", buf
);
534 ssh_scp_send(buf
, strlen(buf
));
538 sprintf(buf
, "%s/*", src
);
539 dir
= FindFirstFile(buf
, &fdat
);
540 ok
= (dir
!= INVALID_HANDLE_VALUE
);
542 if (strcmp(fdat
.cFileName
, ".") == 0 ||
543 strcmp(fdat
.cFileName
, "..") == 0) {
544 } else if (strlen(src
) + 1 + strlen(fdat
.cFileName
) >=
546 run_err("%s/%s: Name too long", src
, fdat
.cFileName
);
548 sprintf(buf
, "%s/%s", src
, fdat
.cFileName
);
551 ok
= FindNextFile(dir
, &fdat
);
556 ssh_scp_send(buf
, strlen(buf
));
561 * Execute the sink part of the SCP protocol.
563 static void sink(char *targ
)
573 unsigned long mtime
, atime
;
575 unsigned long size
, i
;
577 unsigned long stat_bytes
;
578 time_t stat_starttime
, stat_lasttime
;
581 attr
= GetFileAttributes(targ
);
582 if (attr
!= (DWORD
)-1 && (attr
& FILE_ATTRIBUTE_DIRECTORY
) != 0)
585 if (targetshouldbedirectory
&& !targisdir
)
586 bump("%s: Not a directory", targ
);
592 if (ssh_scp_recv(&ch
, 1) <= 0)
595 bump("Protocol error: Unexpected newline");
599 if (ssh_scp_recv(&ch
, 1) <= 0)
600 bump("Lost connection");
602 } while (i
< sizeof(buf
) && ch
!= '\n');
605 case '\01': /* error */
606 tell_user(stderr
, "%s\n", buf
+1);
609 case '\02': /* fatal error */
615 if (sscanf(buf
, "T%ld %*d %ld %*d",
616 &mtime
, &atime
) == 2) {
621 bump("Protocol error: Illegal time format");
626 bump("Protocol error: Expected control record");
629 if (sscanf(buf
+1, "%u %lu %[^\n]", &mode
, &size
, namebuf
) != 3)
630 bump("Protocol error: Illegal file descriptor format");
639 strcpy(namebuf
, targ
);
641 attr
= GetFileAttributes(namebuf
);
642 exists
= (attr
!= (DWORD
)-1);
645 if (exists
&& (attr
& FILE_ATTRIBUTE_DIRECTORY
) == 0) {
646 run_err("%s: Not a directory", namebuf
);
650 if (! CreateDirectory(namebuf
, NULL
)) {
651 run_err("%s: Cannot create directory",
657 /* can we set the timestamp for directories ? */
661 f
= CreateFile(namebuf
, GENERIC_WRITE
, 0, NULL
,
662 CREATE_ALWAYS
, FILE_ATTRIBUTE_NORMAL
, 0);
663 if (f
== INVALID_HANDLE_VALUE
) {
664 run_err("%s: Cannot create file", namebuf
);
672 stat_starttime
= time(NULL
);
674 if ((stat_name
= strrchr(namebuf
, '/')) == NULL
)
678 if (strrchr(stat_name
, '\\') != NULL
)
679 stat_name
= strrchr(stat_name
, '\\') + 1;
682 for (i
= 0; i
< size
; i
+= 4096) {
685 if (i
+ k
> size
) k
= size
- i
;
686 if (ssh_scp_recv(transbuf
, k
) == 0)
687 bump("Lost connection");
688 if (wrerror
) continue;
689 if (! WriteFile(f
, transbuf
, k
, &j
, NULL
) || j
!= k
) {
692 printf("\r%-25.25s | %50s\n",
694 "Write error.. waiting for end of file");
699 if (time(NULL
) > stat_lasttime
||
701 stat_lasttime
= time(NULL
);
702 print_stats(stat_name
, size
, stat_bytes
,
703 stat_starttime
, stat_lasttime
);
710 FILETIME actime
, wrtime
;
711 TIME_POSIX_TO_WIN(atime
, actime
);
712 TIME_POSIX_TO_WIN(mtime
, wrtime
);
713 SetFileTime(f
, NULL
, &actime
, &wrtime
);
718 run_err("%s: Write error", namebuf
);
726 * We will copy local files to a remote server.
728 static void toremote(int argc
, char *argv
[])
730 char *src
, *targ
, *host
, *user
;
736 /* Separate host from filename */
740 bump("targ == NULL in toremote()");
744 /* Substitute "." for emtpy target */
746 /* Separate host and username */
748 host
= strrchr(host
, '@');
759 /* Find out if the source filespec covers multiple files
760 if so, we should set the targetshouldbedirectory flag */
762 WIN32_FIND_DATA fdat
;
763 if (colon(argv
[0]) != NULL
)
764 bump("%s: Remote to remote not supported", argv
[0]);
765 fh
= FindFirstFile(argv
[0], &fdat
);
766 if (fh
== INVALID_HANDLE_VALUE
)
767 bump("%s: No such file or directory\n", argv
[0]);
768 if (FindNextFile(fh
, &fdat
))
769 targetshouldbedirectory
= 1;
773 cmd
= smalloc(strlen(targ
) + 100);
774 sprintf(cmd
, "scp%s%s%s%s -t %s",
775 verbose ?
" -v" : "",
776 recursive ?
" -r" : "",
777 preserve ?
" -p" : "",
778 targetshouldbedirectory ?
" -d" : "",
780 do_cmd(host
, user
, cmd
);
785 for (i
= 0; i
< argc
- 1; i
++) {
787 WIN32_FIND_DATA fdat
;
789 if (colon(src
) != NULL
) {
790 tell_user(stderr
, "%s: Remote to remote not supported\n", src
);
794 dir
= FindFirstFile(src
, &fdat
);
795 if (dir
== INVALID_HANDLE_VALUE
) {
796 run_err("%s: No such file or directory", src
);
802 if (strlen(src
) + strlen(fdat
.cFileName
) >=
804 tell_user(stderr
, "%s: Name too long", src
);
807 strcpy(namebuf
, src
);
808 if ((last
= strrchr(namebuf
, '/')) == NULL
)
812 if (strrchr(last
, '\\') != NULL
)
813 last
= strrchr(last
, '\\') + 1;
814 if (last
== namebuf
&& strrchr(namebuf
, ':') != NULL
)
815 last
= strchr(namebuf
, ':') + 1;
816 strcpy(last
, fdat
.cFileName
);
818 } while (FindNextFile(dir
, &fdat
));
824 * We will copy files from a remote server to the local machine.
826 static void tolocal(int argc
, char *argv
[])
828 char *src
, *targ
, *host
, *user
;
832 bump("More than one remote source not supported");
837 /* Separate host from filename */
841 bump("Local to local copy not supported");
845 /* Substitute "." for empty filename */
847 /* Separate username and hostname */
849 host
= strrchr(host
, '@');
859 cmd
= smalloc(strlen(src
) + 100);
860 sprintf(cmd
, "scp%s%s%s%s -f %s",
861 verbose ?
" -v" : "",
862 recursive ?
" -r" : "",
863 preserve ?
" -p" : "",
864 targetshouldbedirectory ?
" -d" : "",
866 do_cmd(host
, user
, cmd
);
873 * We will issue a list command to get a remote directory.
875 static void get_dir_list(int argc
, char *argv
[])
877 char *src
, *host
, *user
;
883 /* Separate host from filename */
887 bump("Local to local copy not supported");
891 /* Substitute "." for empty filename */
893 /* Separate username and hostname */
895 host
= strrchr(host
, '@');
905 cmd
= smalloc(4*strlen(src
) + 100);
906 strcpy(cmd
, "ls -la '");
907 p
= cmd
+ strlen(cmd
);
908 for (q
= src
; *q
; q
++) {
910 *p
++ = '\''; *p
++ = '\\'; *p
++ = '\''; *p
++ = '\'';
918 do_cmd(host
, user
, cmd
);
921 while (ssh_scp_recv(&c
, 1) > 0)
922 tell_char(stdout
, c
);
926 * Initialize the Win$ock driver.
928 static void init_winsock(void)
933 winsock_ver
= MAKEWORD(1, 1);
934 if (WSAStartup(winsock_ver
, &wsadata
))
935 bump("Unable to initialise WinSock");
936 if (LOBYTE(wsadata
.wVersion
) != 1 ||
937 HIBYTE(wsadata
.wVersion
) != 1)
938 bump("WinSock version is incompatible with 1.1");
942 * Short description of parameters.
944 static void usage(void)
946 printf("PuTTY Secure Copy client\n");
948 printf("Usage: pscp [options] [user@]host:source target\n");
949 printf(" pscp [options] source [source...] [user@]host:target\n");
950 printf(" pscp [options] -ls user@host:filespec\n");
951 printf("Options:\n");
952 printf(" -p preserve file attributes\n");
953 printf(" -q quiet, don't show statistics\n");
954 printf(" -r copy directories recursively\n");
955 printf(" -v show verbose messages\n");
956 printf(" -P port connect to specified port\n");
957 printf(" -pw passw login with specified password\n");
958 /* GUI Adaptation - Sept 2000 */
959 printf(" -gui hWnd GUI mode with the windows handle for receiving messages\n");
964 * Main program (no, really?)
966 int main(int argc
, char *argv
[])
971 default_protocol
= PROT_TELNET
;
974 ssh_get_password
= &get_password
;
977 for (i
= 1; i
< argc
; i
++) {
978 if (argv
[i
][0] != '-')
980 if (strcmp(argv
[i
], "-v") == 0)
981 verbose
= 1, flags
|= FLAG_VERBOSE
;
982 else if (strcmp(argv
[i
], "-r") == 0)
984 else if (strcmp(argv
[i
], "-p") == 0)
986 else if (strcmp(argv
[i
], "-q") == 0)
988 else if (strcmp(argv
[i
], "-h") == 0 ||
989 strcmp(argv
[i
], "-?") == 0)
991 else if (strcmp(argv
[i
], "-P") == 0 && i
+1 < argc
)
992 portnumber
= atoi(argv
[++i
]);
993 else if (strcmp(argv
[i
], "-pw") == 0 && i
+1 < argc
)
994 password
= argv
[++i
];
995 else if (strcmp(argv
[i
], "-gui") == 0 && i
+1 < argc
) {
996 gui_hwnd
= argv
[++i
];
998 } else if (strcmp(argv
[i
], "-ls") == 0)
1000 else if (strcmp(argv
[i
], "--") == 0)
1011 get_dir_list(argc
, argv
);
1018 targetshouldbedirectory
= 1;
1020 if (colon(argv
[argc
-1]) != NULL
)
1021 toremote(argc
, argv
);
1023 tolocal(argc
, argv
);
1026 if (connection_open
) {
1029 ssh_scp_recv(&ch
, 1);
1034 /* GUI Adaptation - August 2000 */
1036 unsigned int msg_id
= WM_RET_ERR_CNT
;
1037 if (list
) msg_id
= WM_LS_RET_ERR_CNT
;
1038 while (!PostMessage( (HWND
)atoi(gui_hwnd
), msg_id
, (WPARAM
)errs
, 0/*lParam*/ ) )
1041 return (errs
== 0 ?
0 : 1);