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.
16 #define PUTTY_DO_GLOBALS
20 #define TIME_POSIX_TO_WIN(t, ft) (*(LONGLONG*)&(ft) = \
21 ((LONGLONG) (t) + (LONGLONG) 11644473600) * (LONGLONG) 10000000)
22 #define TIME_WIN_TO_POSIX(ft, t) ((t) = (unsigned long) \
23 ((*(LONGLONG*)&(ft)) / (LONGLONG) 10000000 - (LONGLONG) 11644473600))
25 static int verbose
= 0;
26 static int recursive
= 0;
27 static int preserve
= 0;
28 static int targetshouldbedirectory
= 0;
29 static int statistics
= 1;
30 static int portnumber
= 0;
31 static char *password
= NULL
;
33 static int connection_open
= 0;
35 static void source(char *src
);
36 static void rsource(char *src
);
37 static void sink(char *targ
);
40 * This function is needed to link with ssh.c, but it never gets called.
48 * Print an error message and perform a fatal exit.
50 void fatalbox(char *fmt
, ...)
54 fprintf(stderr
, "Fatal: ");
55 vfprintf(stderr
, fmt
, ap
);
56 fprintf(stderr
, "\n");
62 * Print an error message and exit after closing the SSH link.
64 static void bump(char *fmt
, ...)
68 fprintf(stderr
, "Fatal: ");
69 vfprintf(stderr
, fmt
, ap
);
70 fprintf(stderr
, "\n");
72 if (connection_open
) {
80 static int get_password(const char *prompt
, char *str
, int maxlen
)
86 static int tried_once
= 0;
91 strncpy(str
, password
, maxlen
);
98 hin
= GetStdHandle(STD_INPUT_HANDLE
);
99 hout
= GetStdHandle(STD_OUTPUT_HANDLE
);
100 if (hin
== INVALID_HANDLE_VALUE
|| hout
== INVALID_HANDLE_VALUE
)
101 bump("Cannot get standard input/output handles");
103 GetConsoleMode(hin
, &savemode
);
104 SetConsoleMode(hin
, (savemode
& (~ENABLE_ECHO_INPUT
)) |
105 ENABLE_PROCESSED_INPUT
| ENABLE_LINE_INPUT
);
107 WriteFile(hout
, prompt
, strlen(prompt
), &i
, NULL
);
108 ReadFile(hin
, str
, maxlen
-1, &i
, NULL
);
110 SetConsoleMode(hin
, savemode
);
112 if ((int)i
> maxlen
) i
= maxlen
-1; else i
= i
- 2;
115 WriteFile(hout
, "\r\n", 2, &i
, NULL
);
121 * Open an SSH connection to user@host and execute cmd.
123 static void do_cmd(char *host
, char *user
, char *cmd
)
125 char *err
, *realhost
;
127 if (host
== NULL
|| host
[0] == '\0')
128 bump("Empty host name");
130 /* Try to load settings for this host */
132 if (cfg
.host
[0] == '\0') {
133 /* No settings for this host; use defaults */
134 strncpy(cfg
.host
, host
, sizeof(cfg
.host
)-1);
135 cfg
.host
[sizeof(cfg
.host
)-1] = '\0';
140 if (user
!= NULL
&& user
[0] != '\0') {
141 strncpy(cfg
.username
, user
, sizeof(cfg
.username
)-1);
142 cfg
.username
[sizeof(cfg
.username
)-1] = '\0';
143 } else if (cfg
.username
[0] == '\0') {
144 bump("Empty user name");
147 if (cfg
.protocol
!= PROT_SSH
)
151 cfg
.port
= portnumber
;
153 err
= ssh_scp_init(cfg
.host
, cfg
.port
, cmd
, &realhost
);
155 bump("ssh_init: %s", err
);
156 if (verbose
&& realhost
!= NULL
)
157 fprintf(stderr
, "Connected to %s\n", realhost
);
163 * Update statistic information about current file.
165 static void print_stats(char *name
, unsigned long size
, unsigned long done
,
166 time_t start
, time_t now
)
174 ratebs
= (float) done
/ (now
- start
);
176 ratebs
= (float) done
;
181 eta
= (unsigned long) ((size
- done
) / ratebs
);
182 sprintf(etastr
, "%02ld:%02ld:%02ld",
183 eta
/ 3600, (eta
% 3600) / 60, eta
% 60);
185 pct
= (int) (100.0 * (float) done
/ size
);
187 printf("\r%-25.25s | %10ld kB | %5.1f kB/s | ETA: %8s | %3d%%",
188 name
, done
/ 1024, ratebs
/ 1024.0,
196 * Find a colon in str and return a pointer to the colon.
197 * This is used to separate hostname from filename.
199 static char * colon(char *str
)
201 /* We ignore a leading colon, since the hostname cannot be
202 empty. We also ignore a colon as second character because
203 of filenames like f:myfile.txt. */
204 if (str
[0] == '\0' ||
208 while (*str
!= '\0' &&
220 * Wait for a response from the other side.
221 * Return 0 if ok, -1 if error.
223 static int response(void)
225 char ch
, resp
, rbuf
[2048];
228 if (ssh_scp_recv(&resp
, 1) <= 0)
229 bump("Lost connection");
239 case 2: /* fatal error */
241 if (ssh_scp_recv(&ch
, 1) <= 0)
242 bump("Protocol error: Lost connection");
244 } while (p
< sizeof(rbuf
) && ch
!= '\n');
247 fprintf(stderr
, "%s\n", rbuf
);
256 * Send an error message to the other side and to the screen.
257 * Increment error counter.
259 static void run_err(const char *fmt
, ...)
265 strcpy(str
, "\01scp: ");
266 vsprintf(str
+strlen(str
), fmt
, ap
);
268 ssh_scp_send(str
, strlen(str
));
269 vfprintf(stderr
, fmt
, ap
);
270 fprintf(stderr
, "\n");
275 * Execute the source part of the SCP protocol.
277 static void source(char *src
)
285 unsigned long stat_bytes
;
286 time_t stat_starttime
, stat_lasttime
;
288 attr
= GetFileAttributes(src
);
289 if (attr
== (DWORD
)-1) {
290 run_err("%s: No such file or directory", src
);
294 if ((attr
& FILE_ATTRIBUTE_DIRECTORY
) != 0) {
297 * Avoid . and .. directories.
300 p
= strrchr(src
, '/');
302 p
= strrchr(src
, '\\');
307 if (!strcmp(p
, ".") || !strcmp(p
, ".."))
312 run_err("%s: not a regular file", src
);
317 if ((last
= strrchr(src
, '/')) == NULL
)
321 if (strrchr(last
, '\\') != NULL
)
322 last
= strrchr(last
, '\\') + 1;
323 if (last
== src
&& strchr(src
, ':') != NULL
)
324 last
= strchr(src
, ':') + 1;
326 f
= CreateFile(src
, GENERIC_READ
, FILE_SHARE_READ
, NULL
,
327 OPEN_EXISTING
, 0, 0);
328 if (f
== INVALID_HANDLE_VALUE
) {
329 run_err("%s: Cannot open file", src
);
334 FILETIME actime
, wrtime
;
335 unsigned long mtime
, atime
;
336 GetFileTime(f
, NULL
, &actime
, &wrtime
);
337 TIME_WIN_TO_POSIX(actime
, atime
);
338 TIME_WIN_TO_POSIX(wrtime
, mtime
);
339 sprintf(buf
, "T%lu 0 %lu 0\n", mtime
, atime
);
340 ssh_scp_send(buf
, strlen(buf
));
345 size
= GetFileSize(f
, NULL
);
346 sprintf(buf
, "C0644 %lu %s\n", size
, last
);
348 fprintf(stderr
, "Sending file modes: %s", buf
);
349 ssh_scp_send(buf
, strlen(buf
));
355 stat_starttime
= time(NULL
);
359 for (i
= 0; i
< size
; i
+= 4096) {
362 if (i
+ k
> size
) k
= size
- i
;
363 if (! ReadFile(f
, transbuf
, k
, &j
, NULL
) || j
!= k
) {
364 if (statistics
) printf("\n");
365 bump("%s: Read error", src
);
367 ssh_scp_send(transbuf
, k
);
370 if (time(NULL
) != stat_lasttime
||
372 stat_lasttime
= time(NULL
);
373 print_stats(last
, size
, stat_bytes
,
374 stat_starttime
, stat_lasttime
);
385 * Recursively send the contents of a directory.
387 static void rsource(char *src
)
392 WIN32_FIND_DATA fdat
;
395 if ((last
= strrchr(src
, '/')) == NULL
)
399 if (strrchr(last
, '\\') != NULL
)
400 last
= strrchr(last
, '\\') + 1;
401 if (last
== src
&& strchr(src
, ':') != NULL
)
402 last
= strchr(src
, ':') + 1;
404 /* maybe send filetime */
406 sprintf(buf
, "D0755 0 %s\n", last
);
408 fprintf(stderr
, "Entering directory: %s", buf
);
409 ssh_scp_send(buf
, strlen(buf
));
413 sprintf(buf
, "%s/*", src
);
414 dir
= FindFirstFile(buf
, &fdat
);
415 ok
= (dir
!= INVALID_HANDLE_VALUE
);
417 if (strcmp(fdat
.cFileName
, ".") == 0 ||
418 strcmp(fdat
.cFileName
, "..") == 0) {
419 } else if (strlen(src
) + 1 + strlen(fdat
.cFileName
) >=
421 run_err("%s/%s: Name too long", src
, fdat
.cFileName
);
423 sprintf(buf
, "%s/%s", src
, fdat
.cFileName
);
426 ok
= FindNextFile(dir
, &fdat
);
431 ssh_scp_send(buf
, strlen(buf
));
436 * Execute the sink part of the SCP protocol.
438 static void sink(char *targ
)
448 unsigned long mtime
, atime
;
450 unsigned long size
, i
;
452 unsigned long stat_bytes
;
453 time_t stat_starttime
, stat_lasttime
;
456 attr
= GetFileAttributes(targ
);
457 if (attr
!= (DWORD
)-1 && (attr
& FILE_ATTRIBUTE_DIRECTORY
) != 0)
460 if (targetshouldbedirectory
&& !targisdir
)
461 bump("%s: Not a directory", targ
);
467 if (ssh_scp_recv(&ch
, 1) <= 0)
470 bump("Protocol error: Unexpected newline");
474 if (ssh_scp_recv(&ch
, 1) <= 0)
475 bump("Lost connection");
477 } while (i
< sizeof(buf
) && ch
!= '\n');
480 case '\01': /* error */
481 fprintf(stderr
, "%s\n", buf
+1);
484 case '\02': /* fatal error */
490 if (sscanf(buf
, "T%ld %*d %ld %*d",
491 &mtime
, &atime
) == 2) {
496 bump("Protocol error: Illegal time format");
501 bump("Protocol error: Expected control record");
504 if (sscanf(buf
+1, "%u %lu %[^\n]", &mode
, &size
, namebuf
) != 3)
505 bump("Protocol error: Illegal file descriptor format");
514 strcpy(namebuf
, targ
);
516 attr
= GetFileAttributes(namebuf
);
517 exists
= (attr
!= (DWORD
)-1);
520 if (exists
&& (attr
& FILE_ATTRIBUTE_DIRECTORY
) == 0) {
521 run_err("%s: Not a directory", namebuf
);
525 if (! CreateDirectory(namebuf
, NULL
)) {
526 run_err("%s: Cannot create directory",
532 /* can we set the timestamp for directories ? */
536 f
= CreateFile(namebuf
, GENERIC_WRITE
, 0, NULL
,
537 CREATE_ALWAYS
, FILE_ATTRIBUTE_NORMAL
, 0);
538 if (f
== INVALID_HANDLE_VALUE
) {
539 run_err("%s: Cannot create file", namebuf
);
547 stat_starttime
= time(NULL
);
549 if ((stat_name
= strrchr(namebuf
, '/')) == NULL
)
553 if (strrchr(stat_name
, '\\') != NULL
)
554 stat_name
= strrchr(stat_name
, '\\') + 1;
557 for (i
= 0; i
< size
; i
+= 4096) {
560 if (i
+ k
> size
) k
= size
- i
;
561 if (ssh_scp_recv(transbuf
, k
) == 0)
562 bump("Lost connection");
563 if (wrerror
) continue;
564 if (! WriteFile(f
, transbuf
, k
, &j
, NULL
) || j
!= k
) {
567 printf("\r%-25.25s | %50s\n",
569 "Write error.. waiting for end of file");
574 if (time(NULL
) > stat_lasttime
||
576 stat_lasttime
= time(NULL
);
577 print_stats(stat_name
, size
, stat_bytes
,
578 stat_starttime
, stat_lasttime
);
585 FILETIME actime
, wrtime
;
586 TIME_POSIX_TO_WIN(atime
, actime
);
587 TIME_POSIX_TO_WIN(mtime
, wrtime
);
588 SetFileTime(f
, NULL
, &actime
, &wrtime
);
593 run_err("%s: Write error", namebuf
);
601 * We will copy local files to a remote server.
603 static void toremote(int argc
, char *argv
[])
605 char *src
, *targ
, *host
, *user
;
611 /* Separate host from filename */
615 bump("targ == NULL in toremote()");
619 /* Substitute "." for emtpy target */
621 /* Separate host and username */
623 host
= strrchr(host
, '@');
634 /* Find out if the source filespec covers multiple files
635 if so, we should set the targetshouldbedirectory flag */
637 WIN32_FIND_DATA fdat
;
638 if (colon(argv
[0]) != NULL
)
639 bump("%s: Remote to remote not supported", argv
[0]);
640 fh
= FindFirstFile(argv
[0], &fdat
);
641 if (fh
== INVALID_HANDLE_VALUE
)
642 bump("%s: No such file or directory\n", argv
[0]);
643 if (FindNextFile(fh
, &fdat
))
644 targetshouldbedirectory
= 1;
648 cmd
= smalloc(strlen(targ
) + 100);
649 sprintf(cmd
, "scp%s%s%s%s -t %s",
650 verbose ?
" -v" : "",
651 recursive ?
" -r" : "",
652 preserve ?
" -p" : "",
653 targetshouldbedirectory ?
" -d" : "",
655 do_cmd(host
, user
, cmd
);
660 for (i
= 0; i
< argc
- 1; i
++) {
662 WIN32_FIND_DATA fdat
;
664 if (colon(src
) != NULL
) {
666 "%s: Remote to remote not supported\n", src
);
670 dir
= FindFirstFile(src
, &fdat
);
671 if (dir
== INVALID_HANDLE_VALUE
) {
672 run_err("%s: No such file or directory", src
);
678 if (strlen(src
) + strlen(fdat
.cFileName
) >=
680 fprintf(stderr
, "%s: Name too long", src
);
683 strcpy(namebuf
, src
);
684 if ((last
= strrchr(namebuf
, '/')) == NULL
)
688 if (strrchr(last
, '\\') != NULL
)
689 last
= strrchr(last
, '\\') + 1;
690 if (last
== namebuf
&& strrchr(namebuf
, ':') != NULL
)
691 last
= strchr(namebuf
, ':') + 1;
692 strcpy(last
, fdat
.cFileName
);
694 } while (FindNextFile(dir
, &fdat
));
700 * We will copy files from a remote server to the local machine.
702 static void tolocal(int argc
, char *argv
[])
704 char *src
, *targ
, *host
, *user
;
708 bump("More than one remote source not supported");
713 /* Separate host from filename */
717 bump("Local to local copy not supported");
721 /* Substitute "." for empty filename */
723 /* Separate username and hostname */
725 host
= strrchr(host
, '@');
735 cmd
= smalloc(strlen(src
) + 100);
736 sprintf(cmd
, "scp%s%s%s%s -f %s",
737 verbose ?
" -v" : "",
738 recursive ?
" -r" : "",
739 preserve ?
" -p" : "",
740 targetshouldbedirectory ?
" -d" : "",
742 do_cmd(host
, user
, cmd
);
749 * We will issue a list command to get a remote directory.
751 static void get_dir_list(int argc
, char *argv
[])
753 char *src
, *host
, *user
;
759 /* Separate host from filename */
763 bump("Local to local copy not supported");
767 /* Substitute "." for empty filename */
769 /* Separate username and hostname */
771 host
= strrchr(host
, '@');
781 cmd
= smalloc(4*strlen(src
) + 100);
782 strcpy(cmd
, "ls -la '");
783 p
= cmd
+ strlen(cmd
);
784 for (q
= src
; *q
; q
++) {
786 *p
++ = '\''; *p
++ = '\\'; *p
++ = '\''; *p
++ = '\'';
794 do_cmd(host
, user
, cmd
);
797 while (ssh_scp_recv(&c
, 1) > 0)
798 fputc(c
, stdout
); /* thank heavens for buffered I/O */
802 * Initialize the Win$ock driver.
804 static void init_winsock(void)
809 winsock_ver
= MAKEWORD(1, 1);
810 if (WSAStartup(winsock_ver
, &wsadata
))
811 bump("Unable to initialise WinSock");
812 if (LOBYTE(wsadata
.wVersion
) != 1 ||
813 HIBYTE(wsadata
.wVersion
) != 1)
814 bump("WinSock version is incompatible with 1.1");
818 * Short description of parameters.
820 static void usage(void)
822 printf("PuTTY Secure Copy client\n");
824 printf("Usage: pscp [options] [user@]host:source target\n");
825 printf(" pscp [options] source [source...] [user@]host:target\n");
826 printf(" pscp [options] -ls user@host:filespec\n");
827 printf("Options:\n");
828 printf(" -p preserve file attributes\n");
829 printf(" -q quiet, don't show statistics\n");
830 printf(" -r copy directories recursively\n");
831 printf(" -v show verbose messages\n");
832 printf(" -P port connect to specified port\n");
833 printf(" -pw passw login with specified password\n");
838 * Main program (no, really?)
840 int main(int argc
, char *argv
[])
845 default_protocol
= PROT_TELNET
;
848 ssh_get_password
= &get_password
;
851 for (i
= 1; i
< argc
; i
++) {
852 if (argv
[i
][0] != '-')
854 if (strcmp(argv
[i
], "-v") == 0)
855 verbose
= 1, flags
|= FLAG_VERBOSE
;
856 else if (strcmp(argv
[i
], "-r") == 0)
858 else if (strcmp(argv
[i
], "-p") == 0)
860 else if (strcmp(argv
[i
], "-q") == 0)
862 else if (strcmp(argv
[i
], "-h") == 0 ||
863 strcmp(argv
[i
], "-?") == 0)
865 else if (strcmp(argv
[i
], "-P") == 0 && i
+1 < argc
)
866 portnumber
= atoi(argv
[++i
]);
867 else if (strcmp(argv
[i
], "-pw") == 0 && i
+1 < argc
)
868 password
= argv
[++i
];
869 else if (strcmp(argv
[i
], "-ls") == 0)
871 else if (strcmp(argv
[i
], "--") == 0)
882 get_dir_list(argc
, argv
);
889 targetshouldbedirectory
= 1;
891 if (colon(argv
[argc
-1]) != NULL
)
892 toremote(argc
, argv
);
897 if (connection_open
) {
900 ssh_scp_recv(&ch
, 1);
905 return (errs
== 0 ?
0 : 1);