2 * scp.c - Scp (Secure Copy) client for PuTTY.
3 * Joris van Rantwijk, Aug 1999, Nov 1999.
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))
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 * Print an error message and perform a fatal exit.
42 void fatalbox(char *fmt
, ...)
46 fprintf(stderr
, "Fatal: ");
47 vfprintf(stderr
, fmt
, ap
);
48 fprintf(stderr
, "\n");
54 * Print an error message and exit after closing the SSH link.
56 static void bump(char *fmt
, ...)
60 fprintf(stderr
, "Fatal: ");
61 vfprintf(stderr
, fmt
, ap
);
62 fprintf(stderr
, "\n");
64 if (connection_open
) {
72 void ssh_get_password(char *prompt
, char *str
, int maxlen
)
78 strncpy(str
, password
, maxlen
);
84 hin
= GetStdHandle(STD_INPUT_HANDLE
);
85 hout
= GetStdHandle(STD_OUTPUT_HANDLE
);
86 if (hin
== INVALID_HANDLE_VALUE
|| hout
== INVALID_HANDLE_VALUE
)
87 bump("Cannot get standard input/output handles");
89 GetConsoleMode(hin
, &savemode
);
90 SetConsoleMode(hin
, (savemode
& (~ENABLE_ECHO_INPUT
)) |
91 ENABLE_PROCESSED_INPUT
| ENABLE_LINE_INPUT
);
93 WriteFile(hout
, prompt
, strlen(prompt
), &i
, NULL
);
94 ReadFile(hin
, str
, maxlen
-1, &i
, NULL
);
96 SetConsoleMode(hin
, savemode
);
98 if ((int)i
> maxlen
) i
= maxlen
-1; else i
= i
- 2;
101 WriteFile(hout
, "\r\n", 2, &i
, NULL
);
105 * Open an SSH connection to user@host and execute cmd.
107 static void do_cmd(char *host
, char *user
, char *cmd
)
109 char *err
, *realhost
;
111 if (host
== NULL
|| host
[0] == '\0')
112 bump("Empty host name");
114 /* Try to load settings for this host */
116 if (cfg
.host
[0] == '\0') {
117 /* No settings for this host; use defaults */
118 strncpy(cfg
.host
, host
, sizeof(cfg
.host
)-1);
119 cfg
.host
[sizeof(cfg
.host
)-1] = '\0';
124 if (user
!= NULL
&& user
[0] != '\0') {
125 strncpy(cfg
.username
, user
, sizeof(cfg
.username
)-1);
126 cfg
.username
[sizeof(cfg
.username
)-1] = '\0';
127 } else if (cfg
.username
[0] == '\0') {
128 bump("Empty user name");
131 if (cfg
.protocol
!= PROT_SSH
)
135 cfg
.port
= portnumber
;
137 err
= ssh_init(cfg
.host
, cfg
.port
, cmd
, &realhost
);
139 bump("ssh_init: %s", err
);
140 if (verbose
&& realhost
!= NULL
)
141 fprintf(stderr
, "Connected to %s\n", realhost
);
147 * Update statistic information about current file.
149 static void print_stats(char *name
, unsigned long size
, unsigned long done
,
150 time_t start
, time_t now
)
158 ratebs
= (float) done
/ (now
- start
);
160 ratebs
= (float) done
;
165 eta
= (unsigned long) ((size
- done
) / ratebs
);
166 sprintf(etastr
, "%02ld:%02ld:%02ld",
167 eta
/ 3600, (eta
% 3600) / 60, eta
% 60);
169 pct
= (int) (100.0 * (float) done
/ size
);
171 printf("\r%-25.25s | %10ld kB | %5.1f kB/s | ETA: %8s | %3d%%",
172 name
, done
/ 1024, ratebs
/ 1024.0,
180 * Find a colon in str and return a pointer to the colon.
181 * This is used to separate hostname from filename.
183 static char * colon(char *str
)
185 /* We ignore a leading colon, since the hostname cannot be
186 empty. We also ignore a colon as second character because
187 of filenames like f:myfile.txt. */
188 if (str
[0] == '\0' ||
192 while (*str
!= '\0' &&
204 * Wait for a response from the other side.
205 * Return 0 if ok, -1 if error.
207 static int response(void)
209 char ch
, resp
, rbuf
[2048];
212 if (ssh_recv(&resp
, 1) <= 0)
213 bump("Lost connection");
223 case 2: /* fatal error */
225 if (ssh_recv(&ch
, 1) <= 0)
226 bump("Protocol error: Lost connection");
228 } while (p
< sizeof(rbuf
) && ch
!= '\n');
231 fprintf(stderr
, "%s\n", rbuf
);
240 * Send an error message to the other side and to the screen.
241 * Increment error counter.
243 static void run_err(const char *fmt
, ...)
249 strcpy(str
, "\01scp: ");
250 vsprintf(str
+strlen(str
), fmt
, ap
);
252 ssh_send(str
, strlen(str
));
253 vfprintf(stderr
, fmt
, ap
);
254 fprintf(stderr
, "\n");
259 * Execute the source part of the SCP protocol.
261 static void source(char *src
)
269 unsigned long stat_bytes
;
270 time_t stat_starttime
, stat_lasttime
;
272 attr
= GetFileAttributes(src
);
273 if (attr
== (DWORD
)-1) {
274 run_err("%s: No such file or directory", src
);
278 if ((attr
& FILE_ATTRIBUTE_DIRECTORY
) != 0) {
281 * Avoid . and .. directories.
284 p
= strrchr(src
, '/');
286 p
= strrchr(src
, '\\');
291 if (!strcmp(p
, ".") || !strcmp(p
, ".."))
296 run_err("%s: not a regular file", src
);
301 if ((last
= strrchr(src
, '/')) == NULL
)
305 if (strrchr(last
, '\\') != NULL
)
306 last
= strrchr(last
, '\\') + 1;
307 if (last
== src
&& strchr(src
, ':') != NULL
)
308 last
= strchr(src
, ':') + 1;
310 f
= CreateFile(src
, GENERIC_READ
, FILE_SHARE_READ
, NULL
,
311 OPEN_EXISTING
, 0, 0);
312 if (f
== INVALID_HANDLE_VALUE
) {
313 run_err("%s: Cannot open file", src
);
318 FILETIME actime
, wrtime
;
319 unsigned long mtime
, atime
;
320 GetFileTime(f
, NULL
, &actime
, &wrtime
);
321 TIME_WIN_TO_POSIX(actime
, atime
);
322 TIME_WIN_TO_POSIX(wrtime
, mtime
);
323 sprintf(buf
, "T%lu 0 %lu 0\n", mtime
, atime
);
324 ssh_send(buf
, strlen(buf
));
329 size
= GetFileSize(f
, NULL
);
330 sprintf(buf
, "C0644 %lu %s\n", size
, last
);
332 fprintf(stderr
, "Sending file modes: %s", buf
);
333 ssh_send(buf
, strlen(buf
));
339 stat_starttime
= time(NULL
);
343 for (i
= 0; i
< size
; i
+= 4096) {
346 if (i
+ k
> size
) k
= size
- i
;
347 if (! ReadFile(f
, transbuf
, k
, &j
, NULL
) || j
!= k
) {
348 if (statistics
) printf("\n");
349 bump("%s: Read error", src
);
351 ssh_send(transbuf
, k
);
354 if (time(NULL
) != stat_lasttime
||
356 stat_lasttime
= time(NULL
);
357 print_stats(last
, size
, stat_bytes
,
358 stat_starttime
, stat_lasttime
);
369 * Recursively send the contents of a directory.
371 static void rsource(char *src
)
376 WIN32_FIND_DATA fdat
;
379 if ((last
= strrchr(src
, '/')) == NULL
)
383 if (strrchr(last
, '\\') != NULL
)
384 last
= strrchr(last
, '\\') + 1;
385 if (last
== src
&& strchr(src
, ':') != NULL
)
386 last
= strchr(src
, ':') + 1;
388 /* maybe send filetime */
390 sprintf(buf
, "D0755 0 %s\n", last
);
392 fprintf(stderr
, "Entering directory: %s", buf
);
393 ssh_send(buf
, strlen(buf
));
397 sprintf(buf
, "%s/*", src
);
398 dir
= FindFirstFile(buf
, &fdat
);
399 ok
= (dir
!= INVALID_HANDLE_VALUE
);
401 if (strcmp(fdat
.cFileName
, ".") == 0 ||
402 strcmp(fdat
.cFileName
, "..") == 0) {
403 } else if (strlen(src
) + 1 + strlen(fdat
.cFileName
) >=
405 run_err("%s/%s: Name too long", src
, fdat
.cFileName
);
407 sprintf(buf
, "%s/%s", src
, fdat
.cFileName
);
410 ok
= FindNextFile(dir
, &fdat
);
415 ssh_send(buf
, strlen(buf
));
420 * Execute the sink part of the SCP protocol.
422 static void sink(char *targ
)
432 unsigned long mtime
, atime
;
434 unsigned long size
, i
;
436 unsigned long stat_bytes
;
437 time_t stat_starttime
, stat_lasttime
;
440 attr
= GetFileAttributes(targ
);
441 if (attr
!= (DWORD
)-1 && (attr
& FILE_ATTRIBUTE_DIRECTORY
) != 0)
444 if (targetshouldbedirectory
&& !targisdir
)
445 bump("%s: Not a directory", targ
);
451 if (ssh_recv(&ch
, 1) <= 0)
454 bump("Protocol error: Unexpected newline");
458 if (ssh_recv(&ch
, 1) <= 0)
459 bump("Lost connection");
461 } while (i
< sizeof(buf
) && ch
!= '\n');
464 case '\01': /* error */
465 fprintf(stderr
, "%s\n", buf
+1);
468 case '\02': /* fatal error */
474 if (sscanf(buf
, "T%ld %*d %ld %*d",
475 &mtime
, &atime
) == 2) {
480 bump("Protocol error: Illegal time format");
485 bump("Protocol error: Expected control record");
488 if (sscanf(buf
+1, "%u %lu %[^\n]", &mode
, &size
, namebuf
) != 3)
489 bump("Protocol error: Illegal file descriptor format");
498 strcpy(namebuf
, targ
);
500 attr
= GetFileAttributes(namebuf
);
501 exists
= (attr
!= (DWORD
)-1);
504 if (exists
&& (attr
& FILE_ATTRIBUTE_DIRECTORY
) == 0) {
505 run_err("%s: Not a directory", namebuf
);
509 if (! CreateDirectory(namebuf
, NULL
)) {
510 run_err("%s: Cannot create directory",
516 /* can we set the timestamp for directories ? */
520 f
= CreateFile(namebuf
, GENERIC_WRITE
, 0, NULL
,
521 CREATE_ALWAYS
, FILE_ATTRIBUTE_NORMAL
, 0);
522 if (f
== INVALID_HANDLE_VALUE
) {
523 run_err("%s: Cannot create file", namebuf
);
531 stat_starttime
= time(NULL
);
533 if ((stat_name
= strrchr(namebuf
, '/')) == NULL
)
537 if (strrchr(stat_name
, '\\') != NULL
)
538 stat_name
= strrchr(stat_name
, '\\') + 1;
541 for (i
= 0; i
< size
; i
+= 4096) {
544 if (i
+ k
> size
) k
= size
- i
;
545 if (ssh_recv(transbuf
, k
) == 0)
546 bump("Lost connection");
547 if (wrerror
) continue;
548 if (! WriteFile(f
, transbuf
, k
, &j
, NULL
) || j
!= k
) {
551 printf("\r%-25.25s | %50s\n",
553 "Write error.. waiting for end of file");
558 if (time(NULL
) > stat_lasttime
||
560 stat_lasttime
= time(NULL
);
561 print_stats(stat_name
, size
, stat_bytes
,
562 stat_starttime
, stat_lasttime
);
569 FILETIME actime
, wrtime
;
570 TIME_POSIX_TO_WIN(atime
, actime
);
571 TIME_POSIX_TO_WIN(mtime
, wrtime
);
572 SetFileTime(f
, NULL
, &actime
, &wrtime
);
577 run_err("%s: Write error", namebuf
);
585 * We will copy local files to a remote server.
587 static void toremote(int argc
, char *argv
[])
589 char *src
, *targ
, *host
, *user
;
595 /* Separate host from filename */
599 bump("targ == NULL in toremote()");
603 /* Substitute "." for emtpy target */
605 /* Separate host and username */
607 host
= strrchr(host
, '@');
618 /* Find out if the source filespec covers multiple files
619 if so, we should set the targetshouldbedirectory flag */
621 WIN32_FIND_DATA fdat
;
622 if (colon(argv
[0]) != NULL
)
623 bump("%s: Remote to remote not supported", argv
[0]);
624 fh
= FindFirstFile(argv
[0], &fdat
);
625 if (fh
== INVALID_HANDLE_VALUE
)
626 bump("%s: No such file or directory\n", argv
[0]);
627 if (FindNextFile(fh
, &fdat
))
628 targetshouldbedirectory
= 1;
632 cmd
= smalloc(strlen(targ
) + 100);
633 sprintf(cmd
, "scp%s%s%s%s -t %s",
634 verbose ?
" -v" : "",
635 recursive ?
" -r" : "",
636 preserve ?
" -p" : "",
637 targetshouldbedirectory ?
" -d" : "",
639 do_cmd(host
, user
, cmd
);
644 for (i
= 0; i
< argc
- 1; i
++) {
646 WIN32_FIND_DATA fdat
;
648 if (colon(src
) != NULL
) {
650 "%s: Remote to remote not supported\n", src
);
654 dir
= FindFirstFile(src
, &fdat
);
655 if (dir
== INVALID_HANDLE_VALUE
) {
656 run_err("%s: No such file or directory", src
);
662 if (strlen(src
) + strlen(fdat
.cFileName
) >=
664 fprintf(stderr
, "%s: Name too long", src
);
667 strcpy(namebuf
, src
);
668 if ((last
= strrchr(namebuf
, '/')) == NULL
)
672 if (strrchr(last
, '\\') != NULL
)
673 last
= strrchr(last
, '\\') + 1;
674 if (last
== namebuf
&& strrchr(namebuf
, ':') != NULL
)
675 last
= strchr(namebuf
, ':') + 1;
676 strcpy(last
, fdat
.cFileName
);
678 } while (FindNextFile(dir
, &fdat
));
684 * We will copy files from a remote server to the local machine.
686 static void tolocal(int argc
, char *argv
[])
688 char *src
, *targ
, *host
, *user
;
692 bump("More than one remote source not supported");
697 /* Separate host from filename */
701 bump("Local to local copy not supported");
705 /* Substitute "." for empty filename */
707 /* Separate username and hostname */
709 host
= strrchr(host
, '@');
719 cmd
= smalloc(strlen(src
) + 100);
720 sprintf(cmd
, "scp%s%s%s%s -f %s",
721 verbose ?
" -v" : "",
722 recursive ?
" -r" : "",
723 preserve ?
" -p" : "",
724 targetshouldbedirectory ?
" -d" : "",
726 do_cmd(host
, user
, cmd
);
733 * We will issue a list command to get a remote directory.
735 static void get_dir_list(int argc
, char *argv
[])
737 char *src
, *host
, *user
;
743 /* Separate host from filename */
747 bump("Local to local copy not supported");
751 /* Substitute "." for empty filename */
753 /* Separate username and hostname */
755 host
= strrchr(host
, '@');
765 cmd
= smalloc(4*strlen(src
) + 100);
766 strcpy(cmd
, "ls -la '");
767 p
= cmd
+ strlen(cmd
);
768 for (q
= src
; *q
; q
++) {
770 *p
++ = '\''; *p
++ = '\\'; *p
++ = '\''; *p
++ = '\'';
778 do_cmd(host
, user
, cmd
);
781 while (ssh_recv(&c
, 1) > 0)
782 fputc(c
, stdout
); /* thank heavens for buffered I/O */
786 * Initialize the Win$ock driver.
788 static void init_winsock(void)
793 winsock_ver
= MAKEWORD(1, 1);
794 if (WSAStartup(winsock_ver
, &wsadata
))
795 bump("Unable to initialise WinSock");
796 if (LOBYTE(wsadata
.wVersion
) != 1 ||
797 HIBYTE(wsadata
.wVersion
) != 1)
798 bump("WinSock version is incompatible with 1.1");
802 * Short description of parameters.
804 static void usage(void)
806 printf("PuTTY Secure Copy client\n");
808 printf("Usage: scp [options] [user@]host:source target\n");
809 printf(" scp [options] source [source...] [user@]host:target\n");
810 printf(" scp [options] -ls user@host:filespec\n");
811 printf("Options:\n");
812 printf(" -p preserve file attributes\n");
813 printf(" -q quiet, don't show statistics\n");
814 printf(" -r copy directories recursively\n");
815 printf(" -v show verbose messages\n");
816 printf(" -P port connect to specified port\n");
817 printf(" -pw passw login with specified password\n");
822 * Main program (no, really?)
824 int main(int argc
, char *argv
[])
831 for (i
= 1; i
< argc
; i
++) {
832 if (argv
[i
][0] != '-')
834 if (strcmp(argv
[i
], "-v") == 0)
836 else if (strcmp(argv
[i
], "-r") == 0)
838 else if (strcmp(argv
[i
], "-p") == 0)
840 else if (strcmp(argv
[i
], "-q") == 0)
842 else if (strcmp(argv
[i
], "-h") == 0 ||
843 strcmp(argv
[i
], "-?") == 0)
845 else if (strcmp(argv
[i
], "-P") == 0 && i
+1 < argc
)
846 portnumber
= atoi(argv
[++i
]);
847 else if (strcmp(argv
[i
], "-pw") == 0 && i
+1 < argc
)
848 password
= argv
[++i
];
849 else if (strcmp(argv
[i
], "-ls") == 0)
851 else if (strcmp(argv
[i
], "--") == 0)
862 get_dir_list(argc
, argv
);
869 targetshouldbedirectory
= 1;
871 if (colon(argv
[argc
-1]) != NULL
)
872 toremote(argc
, argv
);
877 if (connection_open
) {
885 return (errs
== 0 ?
0 : 1);