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 * These functions are needed to link with ssh.c, but never get called.
77 void begin_session(void) {
80 /* GUI Adaptation - Sept 2000 */
81 void send_msg(HWND h
, UINT message
, WPARAM wParam
)
83 while (!PostMessage( h
, message
, wParam
, 0))
87 void tell_char(FILE *stream
, char c
)
93 unsigned int msg_id
= WM_STD_OUT_CHAR
;
94 if (stream
= stderr
) msg_id
= WM_STD_ERR_CHAR
;
95 send_msg( (HWND
)atoi(gui_hwnd
), msg_id
, (WPARAM
)c
);
99 void tell_str(FILE *stream
, char *str
)
103 for( i
= 0; i
< strlen(str
); ++i
)
104 tell_char(stream
, str
[i
]);
107 void tell_user(FILE *stream
, char *fmt
, ...)
109 char str
[0x100]; /* Make the size big enough */
112 vsprintf(str
, fmt
, ap
);
115 tell_str(stream
, str
);
118 void gui_update_stats(char *name
, unsigned long size
, int percentage
, time_t elapsed
)
122 if (strcmp(name
,statname
) != 0)
124 for( i
= 0; i
< strlen(name
); ++i
)
125 send_msg( (HWND
)atoi(gui_hwnd
), WM_STATS_CHAR
, (WPARAM
)name
[i
]);
126 send_msg( (HWND
)atoi(gui_hwnd
), WM_STATS_CHAR
, (WPARAM
)'\n' );
127 strcpy(statname
,name
);
129 if (statsize
!= size
)
131 send_msg( (HWND
)atoi(gui_hwnd
), WM_STATS_SIZE
, (WPARAM
)size
);
134 if (statelapsed
!= elapsed
)
136 send_msg( (HWND
)atoi(gui_hwnd
), WM_STATS_ELAPSED
, (WPARAM
)elapsed
);
137 statelapsed
= elapsed
;
139 if (statperct
!= percentage
)
141 send_msg( (HWND
)atoi(gui_hwnd
), WM_STATS_PERCENT
, (WPARAM
)percentage
);
142 statperct
= percentage
;
147 * Print an error message and perform a fatal exit.
149 void fatalbox(char *fmt
, ...)
151 char str
[0x100]; /* Make the size big enough */
154 strcpy(str
, "Fatal:");
155 vsprintf(str
+strlen(str
), fmt
, ap
);
158 tell_str(stderr
, str
);
162 void connection_fatal(char *fmt
, ...)
164 char str
[0x100]; /* Make the size big enough */
167 strcpy(str
, "Fatal:");
168 vsprintf(str
+strlen(str
), fmt
, ap
);
171 tell_str(stderr
, str
);
177 * Print an error message and exit after closing the SSH link.
179 static void bump(char *fmt
, ...)
181 char str
[0x100]; /* Make the size big enough */
184 strcpy(str
, "Fatal:");
185 vsprintf(str
+strlen(str
), fmt
, ap
);
188 tell_str(stderr
, str
);
190 if (connection_open
) {
193 ssh_scp_recv(&ch
, 1);
198 static int get_password(const char *prompt
, char *str
, int maxlen
)
204 static int tried_once
= 0;
209 strncpy(str
, password
, maxlen
);
210 str
[maxlen
-1] = '\0';
216 /* GUI Adaptation - Sept 2000 */
218 if (maxlen
>0) str
[0] = '\0';
220 hin
= GetStdHandle(STD_INPUT_HANDLE
);
221 hout
= GetStdHandle(STD_OUTPUT_HANDLE
);
222 if (hin
== INVALID_HANDLE_VALUE
|| hout
== INVALID_HANDLE_VALUE
)
223 bump("Cannot get standard input/output handles");
225 GetConsoleMode(hin
, &savemode
);
226 SetConsoleMode(hin
, (savemode
& (~ENABLE_ECHO_INPUT
)) |
227 ENABLE_PROCESSED_INPUT
| ENABLE_LINE_INPUT
);
229 WriteFile(hout
, prompt
, strlen(prompt
), &i
, NULL
);
230 ReadFile(hin
, str
, maxlen
-1, &i
, NULL
);
232 SetConsoleMode(hin
, savemode
);
234 if ((int)i
> maxlen
) i
= maxlen
-1; else i
= i
- 2;
237 WriteFile(hout
, "\r\n", 2, &i
, NULL
);
244 * Open an SSH connection to user@host and execute cmd.
246 static void do_cmd(char *host
, char *user
, char *cmd
)
248 char *err
, *realhost
;
250 if (host
== NULL
|| host
[0] == '\0')
251 bump("Empty host name");
253 /* Try to load settings for this host */
255 if (cfg
.host
[0] == '\0') {
256 /* No settings for this host; use defaults */
257 strncpy(cfg
.host
, host
, sizeof(cfg
.host
)-1);
258 cfg
.host
[sizeof(cfg
.host
)-1] = '\0';
263 if (user
!= NULL
&& user
[0] != '\0') {
264 strncpy(cfg
.username
, user
, sizeof(cfg
.username
)-1);
265 cfg
.username
[sizeof(cfg
.username
)-1] = '\0';
266 } else if (cfg
.username
[0] == '\0') {
267 bump("Empty user name");
270 if (cfg
.protocol
!= PROT_SSH
)
274 cfg
.port
= portnumber
;
276 err
= ssh_scp_init(cfg
.host
, cfg
.port
, cmd
, &realhost
);
278 bump("ssh_init: %s", err
);
279 if (verbose
&& realhost
!= NULL
)
280 tell_user(stderr
, "Connected to %s\n", realhost
);
286 * Update statistic information about current file.
288 static void print_stats(char *name
, unsigned long size
, unsigned long done
,
289 time_t start
, time_t now
)
296 /* GUI Adaptation - Sept 2000 */
298 gui_update_stats(name
, size
, ((done
*100) / size
), now
-start
);
301 ratebs
= (float) done
/ (now
- start
);
303 ratebs
= (float) done
;
308 eta
= (unsigned long) ((size
- done
) / ratebs
);
309 sprintf(etastr
, "%02ld:%02ld:%02ld",
310 eta
/ 3600, (eta
% 3600) / 60, eta
% 60);
312 pct
= (int) (100.0 * (float) done
/ size
);
314 printf("\r%-25.25s | %10ld kB | %5.1f kB/s | ETA: %8s | %3d%%",
315 name
, done
/ 1024, ratebs
/ 1024.0,
324 * Find a colon in str and return a pointer to the colon.
325 * This is used to separate hostname from filename.
327 static char * colon(char *str
)
329 /* We ignore a leading colon, since the hostname cannot be
330 empty. We also ignore a colon as second character because
331 of filenames like f:myfile.txt. */
332 if (str
[0] == '\0' ||
336 while (*str
!= '\0' &&
348 * Wait for a response from the other side.
349 * Return 0 if ok, -1 if error.
351 static int response(void)
353 char ch
, resp
, rbuf
[2048];
356 if (ssh_scp_recv(&resp
, 1) <= 0)
357 bump("Lost connection");
367 case 2: /* fatal error */
369 if (ssh_scp_recv(&ch
, 1) <= 0)
370 bump("Protocol error: Lost connection");
372 } while (p
< sizeof(rbuf
) && ch
!= '\n');
375 tell_user(stderr
, "%s\n", rbuf
);
384 * Send an error message to the other side and to the screen.
385 * Increment error counter.
387 static void run_err(const char *fmt
, ...)
393 strcpy(str
, "\01scp: ");
394 vsprintf(str
+strlen(str
), fmt
, ap
);
396 ssh_scp_send(str
, strlen(str
));
397 tell_user(stderr
, "%s",str
);
402 * Execute the source part of the SCP protocol.
404 static void source(char *src
)
412 unsigned long stat_bytes
;
413 time_t stat_starttime
, stat_lasttime
;
415 attr
= GetFileAttributes(src
);
416 if (attr
== (DWORD
)-1) {
417 run_err("%s: No such file or directory", src
);
421 if ((attr
& FILE_ATTRIBUTE_DIRECTORY
) != 0) {
424 * Avoid . and .. directories.
427 p
= strrchr(src
, '/');
429 p
= strrchr(src
, '\\');
434 if (!strcmp(p
, ".") || !strcmp(p
, ".."))
439 run_err("%s: not a regular file", src
);
444 if ((last
= strrchr(src
, '/')) == NULL
)
448 if (strrchr(last
, '\\') != NULL
)
449 last
= strrchr(last
, '\\') + 1;
450 if (last
== src
&& strchr(src
, ':') != NULL
)
451 last
= strchr(src
, ':') + 1;
453 f
= CreateFile(src
, GENERIC_READ
, FILE_SHARE_READ
, NULL
,
454 OPEN_EXISTING
, 0, 0);
455 if (f
== INVALID_HANDLE_VALUE
) {
456 run_err("%s: Cannot open file", src
);
461 FILETIME actime
, wrtime
;
462 unsigned long mtime
, atime
;
463 GetFileTime(f
, NULL
, &actime
, &wrtime
);
464 TIME_WIN_TO_POSIX(actime
, atime
);
465 TIME_WIN_TO_POSIX(wrtime
, mtime
);
466 sprintf(buf
, "T%lu 0 %lu 0\n", mtime
, atime
);
467 ssh_scp_send(buf
, strlen(buf
));
472 size
= GetFileSize(f
, NULL
);
473 sprintf(buf
, "C0644 %lu %s\n", size
, last
);
475 tell_user(stderr
, "Sending file modes: %s", buf
);
476 ssh_scp_send(buf
, strlen(buf
));
482 stat_starttime
= time(NULL
);
486 for (i
= 0; i
< size
; i
+= 4096) {
489 if (i
+ k
> size
) k
= size
- i
;
490 if (! ReadFile(f
, transbuf
, k
, &j
, NULL
) || j
!= k
) {
491 if (statistics
) printf("\n");
492 bump("%s: Read error", src
);
494 ssh_scp_send(transbuf
, k
);
497 if (time(NULL
) != stat_lasttime
||
499 stat_lasttime
= time(NULL
);
500 print_stats(last
, size
, stat_bytes
,
501 stat_starttime
, stat_lasttime
);
512 * Recursively send the contents of a directory.
514 static void rsource(char *src
)
519 WIN32_FIND_DATA fdat
;
522 if ((last
= strrchr(src
, '/')) == NULL
)
526 if (strrchr(last
, '\\') != NULL
)
527 last
= strrchr(last
, '\\') + 1;
528 if (last
== src
&& strchr(src
, ':') != NULL
)
529 last
= strchr(src
, ':') + 1;
531 /* maybe send filetime */
533 sprintf(buf
, "D0755 0 %s\n", last
);
535 tell_user(stderr
, "Entering directory: %s", buf
);
536 ssh_scp_send(buf
, strlen(buf
));
540 sprintf(buf
, "%s/*", src
);
541 dir
= FindFirstFile(buf
, &fdat
);
542 ok
= (dir
!= INVALID_HANDLE_VALUE
);
544 if (strcmp(fdat
.cFileName
, ".") == 0 ||
545 strcmp(fdat
.cFileName
, "..") == 0) {
546 } else if (strlen(src
) + 1 + strlen(fdat
.cFileName
) >=
548 run_err("%s/%s: Name too long", src
, fdat
.cFileName
);
550 sprintf(buf
, "%s/%s", src
, fdat
.cFileName
);
553 ok
= FindNextFile(dir
, &fdat
);
558 ssh_scp_send(buf
, strlen(buf
));
563 * Execute the sink part of the SCP protocol.
565 static void sink(char *targ
)
575 unsigned long mtime
, atime
;
577 unsigned long size
, i
;
579 unsigned long stat_bytes
;
580 time_t stat_starttime
, stat_lasttime
;
583 attr
= GetFileAttributes(targ
);
584 if (attr
!= (DWORD
)-1 && (attr
& FILE_ATTRIBUTE_DIRECTORY
) != 0)
587 if (targetshouldbedirectory
&& !targisdir
)
588 bump("%s: Not a directory", targ
);
594 if (ssh_scp_recv(&ch
, 1) <= 0)
597 bump("Protocol error: Unexpected newline");
601 if (ssh_scp_recv(&ch
, 1) <= 0)
602 bump("Lost connection");
604 } while (i
< sizeof(buf
) && ch
!= '\n');
607 case '\01': /* error */
608 tell_user(stderr
, "%s\n", buf
+1);
611 case '\02': /* fatal error */
617 if (sscanf(buf
, "T%ld %*d %ld %*d",
618 &mtime
, &atime
) == 2) {
623 bump("Protocol error: Illegal time format");
628 bump("Protocol error: Expected control record");
631 if (sscanf(buf
+1, "%u %lu %[^\n]", &mode
, &size
, namebuf
) != 3)
632 bump("Protocol error: Illegal file descriptor format");
641 strcpy(namebuf
, targ
);
643 attr
= GetFileAttributes(namebuf
);
644 exists
= (attr
!= (DWORD
)-1);
647 if (exists
&& (attr
& FILE_ATTRIBUTE_DIRECTORY
) == 0) {
648 run_err("%s: Not a directory", namebuf
);
652 if (! CreateDirectory(namebuf
, NULL
)) {
653 run_err("%s: Cannot create directory",
659 /* can we set the timestamp for directories ? */
663 f
= CreateFile(namebuf
, GENERIC_WRITE
, 0, NULL
,
664 CREATE_ALWAYS
, FILE_ATTRIBUTE_NORMAL
, 0);
665 if (f
== INVALID_HANDLE_VALUE
) {
666 run_err("%s: Cannot create file", namebuf
);
674 stat_starttime
= time(NULL
);
676 if ((stat_name
= strrchr(namebuf
, '/')) == NULL
)
680 if (strrchr(stat_name
, '\\') != NULL
)
681 stat_name
= strrchr(stat_name
, '\\') + 1;
684 for (i
= 0; i
< size
; i
+= 4096) {
687 if (i
+ k
> size
) k
= size
- i
;
688 if (ssh_scp_recv(transbuf
, k
) == 0)
689 bump("Lost connection");
690 if (wrerror
) continue;
691 if (! WriteFile(f
, transbuf
, k
, &j
, NULL
) || j
!= k
) {
694 printf("\r%-25.25s | %50s\n",
696 "Write error.. waiting for end of file");
701 if (time(NULL
) > stat_lasttime
||
703 stat_lasttime
= time(NULL
);
704 print_stats(stat_name
, size
, stat_bytes
,
705 stat_starttime
, stat_lasttime
);
712 FILETIME actime
, wrtime
;
713 TIME_POSIX_TO_WIN(atime
, actime
);
714 TIME_POSIX_TO_WIN(mtime
, wrtime
);
715 SetFileTime(f
, NULL
, &actime
, &wrtime
);
720 run_err("%s: Write error", namebuf
);
728 * We will copy local files to a remote server.
730 static void toremote(int argc
, char *argv
[])
732 char *src
, *targ
, *host
, *user
;
738 /* Separate host from filename */
742 bump("targ == NULL in toremote()");
746 /* Substitute "." for emtpy target */
748 /* Separate host and username */
750 host
= strrchr(host
, '@');
761 /* Find out if the source filespec covers multiple files
762 if so, we should set the targetshouldbedirectory flag */
764 WIN32_FIND_DATA fdat
;
765 if (colon(argv
[0]) != NULL
)
766 bump("%s: Remote to remote not supported", argv
[0]);
767 fh
= FindFirstFile(argv
[0], &fdat
);
768 if (fh
== INVALID_HANDLE_VALUE
)
769 bump("%s: No such file or directory\n", argv
[0]);
770 if (FindNextFile(fh
, &fdat
))
771 targetshouldbedirectory
= 1;
775 cmd
= smalloc(strlen(targ
) + 100);
776 sprintf(cmd
, "scp%s%s%s%s -t %s",
777 verbose ?
" -v" : "",
778 recursive ?
" -r" : "",
779 preserve ?
" -p" : "",
780 targetshouldbedirectory ?
" -d" : "",
782 do_cmd(host
, user
, cmd
);
787 for (i
= 0; i
< argc
- 1; i
++) {
789 WIN32_FIND_DATA fdat
;
791 if (colon(src
) != NULL
) {
792 tell_user(stderr
, "%s: Remote to remote not supported\n", src
);
796 dir
= FindFirstFile(src
, &fdat
);
797 if (dir
== INVALID_HANDLE_VALUE
) {
798 run_err("%s: No such file or directory", src
);
804 if (strlen(src
) + strlen(fdat
.cFileName
) >=
806 tell_user(stderr
, "%s: Name too long", src
);
809 strcpy(namebuf
, src
);
810 if ((last
= strrchr(namebuf
, '/')) == NULL
)
814 if (strrchr(last
, '\\') != NULL
)
815 last
= strrchr(last
, '\\') + 1;
816 if (last
== namebuf
&& strrchr(namebuf
, ':') != NULL
)
817 last
= strchr(namebuf
, ':') + 1;
818 strcpy(last
, fdat
.cFileName
);
820 } while (FindNextFile(dir
, &fdat
));
826 * We will copy files from a remote server to the local machine.
828 static void tolocal(int argc
, char *argv
[])
830 char *src
, *targ
, *host
, *user
;
834 bump("More than one remote source not supported");
839 /* Separate host from filename */
843 bump("Local to local copy not supported");
847 /* Substitute "." for empty filename */
849 /* Separate username and hostname */
851 host
= strrchr(host
, '@');
861 cmd
= smalloc(strlen(src
) + 100);
862 sprintf(cmd
, "scp%s%s%s%s -f %s",
863 verbose ?
" -v" : "",
864 recursive ?
" -r" : "",
865 preserve ?
" -p" : "",
866 targetshouldbedirectory ?
" -d" : "",
868 do_cmd(host
, user
, cmd
);
875 * We will issue a list command to get a remote directory.
877 static void get_dir_list(int argc
, char *argv
[])
879 char *src
, *host
, *user
;
885 /* Separate host from filename */
889 bump("Local to local copy not supported");
893 /* Substitute "." for empty filename */
895 /* Separate username and hostname */
897 host
= strrchr(host
, '@');
907 cmd
= smalloc(4*strlen(src
) + 100);
908 strcpy(cmd
, "ls -la '");
909 p
= cmd
+ strlen(cmd
);
910 for (q
= src
; *q
; q
++) {
912 *p
++ = '\''; *p
++ = '\\'; *p
++ = '\''; *p
++ = '\'';
920 do_cmd(host
, user
, cmd
);
923 while (ssh_scp_recv(&c
, 1) > 0)
924 tell_char(stdout
, c
);
928 * Initialize the Win$ock driver.
930 static void init_winsock(void)
935 winsock_ver
= MAKEWORD(1, 1);
936 if (WSAStartup(winsock_ver
, &wsadata
))
937 bump("Unable to initialise WinSock");
938 if (LOBYTE(wsadata
.wVersion
) != 1 ||
939 HIBYTE(wsadata
.wVersion
) != 1)
940 bump("WinSock version is incompatible with 1.1");
944 * Short description of parameters.
946 static void usage(void)
948 printf("PuTTY Secure Copy client\n");
950 printf("Usage: pscp [options] [user@]host:source target\n");
951 printf(" pscp [options] source [source...] [user@]host:target\n");
952 printf(" pscp [options] -ls user@host:filespec\n");
953 printf("Options:\n");
954 printf(" -p preserve file attributes\n");
955 printf(" -q quiet, don't show statistics\n");
956 printf(" -r copy directories recursively\n");
957 printf(" -v show verbose messages\n");
958 printf(" -P port connect to specified port\n");
959 printf(" -pw passw login with specified password\n");
960 /* GUI Adaptation - Sept 2000 */
961 printf(" -gui hWnd GUI mode with the windows handle for receiving messages\n");
966 * Main program (no, really?)
968 int main(int argc
, char *argv
[])
973 default_protocol
= PROT_TELNET
;
976 ssh_get_password
= &get_password
;
979 for (i
= 1; i
< argc
; i
++) {
980 if (argv
[i
][0] != '-')
982 if (strcmp(argv
[i
], "-v") == 0)
983 verbose
= 1, flags
|= FLAG_VERBOSE
;
984 else if (strcmp(argv
[i
], "-r") == 0)
986 else if (strcmp(argv
[i
], "-p") == 0)
988 else if (strcmp(argv
[i
], "-q") == 0)
990 else if (strcmp(argv
[i
], "-h") == 0 ||
991 strcmp(argv
[i
], "-?") == 0)
993 else if (strcmp(argv
[i
], "-P") == 0 && i
+1 < argc
)
994 portnumber
= atoi(argv
[++i
]);
995 else if (strcmp(argv
[i
], "-pw") == 0 && i
+1 < argc
)
996 password
= argv
[++i
];
997 else if (strcmp(argv
[i
], "-gui") == 0 && i
+1 < argc
) {
998 gui_hwnd
= argv
[++i
];
1000 } else if (strcmp(argv
[i
], "-ls") == 0)
1002 else if (strcmp(argv
[i
], "--") == 0)
1013 get_dir_list(argc
, argv
);
1020 targetshouldbedirectory
= 1;
1022 if (colon(argv
[argc
-1]) != NULL
)
1023 toremote(argc
, argv
);
1025 tolocal(argc
, argv
);
1028 if (connection_open
) {
1031 ssh_scp_recv(&ch
, 1);
1036 /* GUI Adaptation - August 2000 */
1038 unsigned int msg_id
= WM_RET_ERR_CNT
;
1039 if (list
) msg_id
= WM_LS_RET_ERR_CNT
;
1040 while (!PostMessage( (HWND
)atoi(gui_hwnd
), msg_id
, (WPARAM
)errs
, 0/*lParam*/ ) )
1043 return (errs
== 0 ?
0 : 1);