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 cfg
.port
= portnumber
;
127 if (user
!= NULL
&& user
[0] != '\0') {
128 strncpy(cfg
.username
, user
, sizeof(cfg
.username
)-1);
129 cfg
.username
[sizeof(cfg
.username
)-1] = '\0';
131 } else if (cfg
.username
[0] == '\0') {
132 bump("Empty user name");
135 if (cfg
.protocol
!= PROT_SSH
)
138 err
= ssh_init(cfg
.host
, cfg
.port
, cmd
, &realhost
);
140 bump("ssh_init: %s", err
);
141 if (verbose
&& realhost
!= NULL
)
142 fprintf(stderr
, "Connected to %s\n", realhost
);
148 * Update statistic information about current file.
150 static void print_stats(char *name
, unsigned long size
, unsigned long done
,
151 time_t start
, time_t now
)
159 ratebs
= (float) done
/ (now
- start
);
161 ratebs
= (float) done
;
166 eta
= (unsigned long) ((size
- done
) / ratebs
);
167 sprintf(etastr
, "%02d:%02d:%02d",
168 eta
/ 3600, (eta
% 3600) / 60, eta
% 60);
170 pct
= (int) (100.0 * (float) done
/ size
);
172 printf("\r%-25.25s | %10ld kB | %5.1f kB/s | ETA: %8s | %3d%%",
173 name
, done
/ 1024, ratebs
/ 1024.0,
181 * Find a colon in str and return a pointer to the colon.
182 * This is used to seperate hostname from filename.
184 static char * colon(char *str
)
186 /* We ignore a leading colon, since the hostname cannot be
187 empty. We also ignore a colon as second character because
188 of filenames like f:myfile.txt. */
189 if (str
[0] == '\0' ||
193 while (*str
!= '\0' &&
205 * Wait for a response from the other side.
206 * Return 0 if ok, -1 if error.
208 static int response(void)
210 char ch
, resp
, rbuf
[2048];
213 if (ssh_recv(&resp
, 1) <= 0)
214 bump("Lost connection");
224 case 2: /* fatal error */
226 if (ssh_recv(&ch
, 1) <= 0)
227 bump("Protocol error: Lost connection");
229 } while (p
< sizeof(rbuf
) && ch
!= '\n');
232 fprintf(stderr
, "%s\n", rbuf
);
241 * Send an error message to the other side and to the screen.
242 * Increment error counter.
244 static void run_err(const char *fmt
, ...)
250 strcpy(str
, "\01scp: ");
251 vsprintf(str
+strlen(str
), fmt
, ap
);
253 ssh_send(str
, strlen(str
));
254 vfprintf(stderr
, fmt
, ap
);
255 fprintf(stderr
, "\n");
260 * Execute the source part of the SCP protocol.
262 static void source(char *src
)
270 unsigned long stat_bytes
;
271 time_t stat_starttime
, stat_lasttime
;
273 attr
= GetFileAttributes(src
);
275 run_err("%s: No such file or directory", src
);
279 if ((attr
& FILE_ATTRIBUTE_DIRECTORY
) != 0) {
283 run_err("%s: not a regular file", src
);
287 if ((last
= strrchr(src
, '/')) == NULL
)
291 if (strrchr(last
, '\\') != NULL
)
292 last
= strrchr(last
, '\\') + 1;
293 if (last
== src
&& strchr(src
, ':') != NULL
)
294 last
= strchr(src
, ':') + 1;
296 f
= CreateFile(src
, GENERIC_READ
, FILE_SHARE_READ
, NULL
,
297 OPEN_EXISTING
, 0, 0);
298 if (f
== INVALID_HANDLE_VALUE
) {
299 run_err("%s: Cannot open file");
304 FILETIME actime
, wrtime
;
305 unsigned long mtime
, atime
;
306 GetFileTime(f
, NULL
, &actime
, &wrtime
);
307 TIME_WIN_TO_POSIX(actime
, atime
);
308 TIME_WIN_TO_POSIX(wrtime
, mtime
);
309 sprintf(buf
, "T%lu 0 %lu 0\n", mtime
, atime
);
310 ssh_send(buf
, strlen(buf
));
315 size
= GetFileSize(f
, NULL
);
316 sprintf(buf
, "C0644 %lu %s\n", size
, last
);
318 fprintf(stderr
, "Sending file modes: %s", buf
);
319 ssh_send(buf
, strlen(buf
));
325 stat_starttime
= time(NULL
);
329 for (i
= 0; i
< size
; i
+= 4096) {
332 if (i
+ k
> size
) k
= size
- i
;
333 if (! ReadFile(f
, transbuf
, k
, &j
, NULL
) || j
!= k
) {
334 if (statistics
) printf("\n");
335 bump("%s: Read error", src
);
337 ssh_send(transbuf
, k
);
340 if (time(NULL
) != stat_lasttime
||
342 stat_lasttime
= time(NULL
);
343 print_stats(last
, size
, stat_bytes
,
344 stat_starttime
, stat_lasttime
);
355 * Recursively send the contents of a directory.
357 static void rsource(char *src
)
362 WIN32_FIND_DATA fdat
;
365 if ((last
= strrchr(src
, '/')) == NULL
)
369 if (strrchr(last
, '\\') != NULL
)
370 last
= strrchr(last
, '\\') + 1;
371 if (last
== src
&& strchr(src
, ':') != NULL
)
372 last
= strchr(src
, ':') + 1;
374 /* maybe send filetime */
376 sprintf(buf
, "D0755 0 %s\n", last
);
378 fprintf(stderr
, "Entering directory: %s", buf
);
379 ssh_send(buf
, strlen(buf
));
383 sprintf(buf
, "%s/*", src
);
384 dir
= FindFirstFile(buf
, &fdat
);
385 ok
= (dir
!= INVALID_HANDLE_VALUE
);
387 if (strcmp(fdat
.cFileName
, ".") == 0 ||
388 strcmp(fdat
.cFileName
, "..") == 0) {
389 } else if (strlen(src
) + 1 + strlen(fdat
.cFileName
) >=
391 run_err("%s/%s: Name too long", src
, fdat
.cFileName
);
393 sprintf(buf
, "%s/%s", src
, fdat
.cFileName
);
396 ok
= FindNextFile(dir
, &fdat
);
401 ssh_send(buf
, strlen(buf
));
406 * Execute the sink part of the SCP protocol.
408 static void sink(char *targ
)
418 unsigned long mtime
, atime
;
420 unsigned long size
, i
;
422 unsigned long stat_bytes
;
423 time_t stat_starttime
, stat_lasttime
;
426 attr
= GetFileAttributes(targ
);
427 if (attr
!= -1 && (attr
& FILE_ATTRIBUTE_DIRECTORY
) != 0)
430 if (targetshouldbedirectory
&& !targisdir
)
431 bump("%s: Not a directory", targ
);
437 if (ssh_recv(&ch
, 1) <= 0)
440 bump("Protocol error: Unexpected newline");
444 if (ssh_recv(&ch
, 1) <= 0)
445 bump("Lost connection");
447 } while (i
< sizeof(buf
) && ch
!= '\n');
450 case '\01': /* error */
451 fprintf(stderr
, "%s\n", buf
+1);
454 case '\02': /* fatal error */
460 if (sscanf(buf
, "T%d %*d %d %*d",
461 &mtime
, &atime
) == 2) {
466 bump("Protocol error: Illegal time format");
471 bump("Protocol error: Expected control record");
474 if (sscanf(buf
+1, "%u %u %[^\n]", &mode
, &size
, namebuf
) != 3)
475 bump("Protocol error: Illegal file descriptor format");
484 strcpy(namebuf
, targ
);
486 attr
= GetFileAttributes(namebuf
);
487 exists
= (attr
!= -1);
490 if (exists
&& (attr
& FILE_ATTRIBUTE_DIRECTORY
) == 0) {
491 run_err("%s: Not a directory", namebuf
);
495 if (! CreateDirectory(namebuf
, NULL
)) {
496 run_err("%s: Cannot create directory",
502 /* can we set the timestamp for directories ? */
506 f
= CreateFile(namebuf
, GENERIC_WRITE
, 0, NULL
,
507 CREATE_ALWAYS
, FILE_ATTRIBUTE_NORMAL
, 0);
508 if (f
== INVALID_HANDLE_VALUE
) {
509 run_err("%s: Cannot create file", namebuf
);
517 stat_starttime
= time(NULL
);
519 if ((stat_name
= strrchr(namebuf
, '/')) == NULL
)
523 if (strrchr(stat_name
, '\\') != NULL
)
524 stat_name
= strrchr(stat_name
, '\\') + 1;
527 for (i
= 0; i
< size
; i
+= 4096) {
530 if (i
+ k
> size
) k
= size
- i
;
531 if (ssh_recv(transbuf
, k
) == 0)
532 bump("Lost connection");
533 if (wrerror
) continue;
534 if (! WriteFile(f
, transbuf
, k
, &j
, NULL
) || j
!= k
) {
537 printf("\r%-25.25s | %50s\n",
539 "Write error.. waiting for end of file");
544 if (time(NULL
) > stat_lasttime
||
546 stat_lasttime
= time(NULL
);
547 print_stats(stat_name
, size
, stat_bytes
,
548 stat_starttime
, stat_lasttime
);
555 FILETIME actime
, wrtime
;
556 TIME_POSIX_TO_WIN(atime
, actime
);
557 TIME_POSIX_TO_WIN(mtime
, wrtime
);
558 SetFileTime(f
, NULL
, &actime
, &wrtime
);
563 run_err("%s: Write error", namebuf
);
571 * We will copy local files to a remote server.
573 static void toremote(int argc
, char *argv
[])
575 char *src
, *targ
, *host
, *user
;
581 /* Seperate host from filename */
585 bump("targ == NULL in toremote()");
589 /* Substitute "." for emtpy target */
591 /* Seperate host and username */
593 host
= strrchr(host
, '@');
604 /* Find out if the source filespec covers multiple files
605 if so, we should set the targetshouldbedirectory flag */
607 WIN32_FIND_DATA fdat
;
608 if (colon(argv
[0]) != NULL
)
609 bump("%s: Remote to remote not supported", argv
[0]);
610 fh
= FindFirstFile(argv
[0], &fdat
);
611 if (fh
== INVALID_HANDLE_VALUE
)
612 bump("%s: No such file or directory\n", argv
[0]);
613 if (FindNextFile(fh
, &fdat
))
614 targetshouldbedirectory
= 1;
618 cmd
= smalloc(strlen(targ
) + 100);
619 sprintf(cmd
, "scp%s%s%s%s -t %s",
620 verbose ?
" -v" : "",
621 recursive ?
" -r" : "",
622 preserve ?
" -p" : "",
623 targetshouldbedirectory ?
" -d" : "",
625 do_cmd(host
, user
, cmd
);
630 for (i
= 0; i
< argc
- 1; i
++) {
632 WIN32_FIND_DATA fdat
;
634 if (colon(src
) != NULL
) {
636 "%s: Remote to remote not supported\n", src
);
640 dir
= FindFirstFile(src
, &fdat
);
641 if (dir
== INVALID_HANDLE_VALUE
) {
642 run_err("%s: No such file or directory", src
);
648 if (strlen(src
) + strlen(fdat
.cFileName
) >=
650 fprintf(stderr
, "%s: Name too long", src
);
653 strcpy(namebuf
, src
);
654 if ((last
= strrchr(namebuf
, '/')) == NULL
)
658 if (strrchr(last
, '\\') != NULL
)
659 last
= strrchr(last
, '\\') + 1;
660 if (last
== namebuf
&& strrchr(namebuf
, ':') != NULL
)
661 last
= strchr(namebuf
, ':') + 1;
662 strcpy(last
, fdat
.cFileName
);
664 } while (FindNextFile(dir
, &fdat
));
670 * We will copy files from a remote server to the local machine.
672 static void tolocal(int argc
, char *argv
[])
674 char *src
, *targ
, *host
, *user
;
678 bump("More than one remote source not supported");
683 /* Seperate host from filename */
687 bump("Local to local copy not supported");
691 /* Substitute "." for empty filename */
693 /* Seperate username and hostname */
695 host
= strrchr(host
, '@');
705 cmd
= smalloc(strlen(src
) + 100);
706 sprintf(cmd
, "scp%s%s%s%s -f %s",
707 verbose ?
" -v" : "",
708 recursive ?
" -r" : "",
709 preserve ?
" -p" : "",
710 targetshouldbedirectory ?
" -d" : "",
712 do_cmd(host
, user
, cmd
);
719 * Initialize the Win$ock driver.
721 static void init_winsock()
726 winsock_ver
= MAKEWORD(1, 1);
727 if (WSAStartup(winsock_ver
, &wsadata
))
728 bump("Unable to initialise WinSock");
729 if (LOBYTE(wsadata
.wVersion
) != 1 ||
730 HIBYTE(wsadata
.wVersion
) != 1)
731 bump("WinSock version is incompatible with 1.1");
735 * Short description of parameters.
739 printf("PuTTY Secure Copy client\n");
741 printf("Usage: scp [options] [user@]host:source target\n");
742 printf(" scp [options] source [source...] [user@]host:target\n");
743 printf("Options:\n");
744 printf(" -p preserve file attributes\n");
745 printf(" -q quiet, don't show statistics\n");
746 printf(" -r copy directories recursively\n");
747 printf(" -v show verbose messages\n");
748 printf(" -P port connect to specified port\n");
749 printf(" -pw passw login with specified password\n");
754 * Main program (no, really?)
756 int main(int argc
, char *argv
[])
762 for (i
= 1; i
< argc
; i
++) {
763 if (argv
[i
][0] != '-')
765 if (strcmp(argv
[i
], "-v") == 0)
767 else if (strcmp(argv
[i
], "-r") == 0)
769 else if (strcmp(argv
[i
], "-p") == 0)
771 else if (strcmp(argv
[i
], "-q") == 0)
773 else if (strcmp(argv
[i
], "-h") == 0 ||
774 strcmp(argv
[i
], "-?") == 0)
776 else if (strcmp(argv
[i
], "-P") == 0 && i
+1 < argc
)
777 portnumber
= atoi(argv
[++i
]);
778 else if (strcmp(argv
[i
], "-pw") == 0 && i
+1 < argc
)
779 password
= argv
[++i
];
780 else if (strcmp(argv
[i
], "--") == 0)
791 targetshouldbedirectory
= 1;
793 if (colon(argv
[argc
-1]) != NULL
)
794 toremote(argc
, argv
);
798 if (connection_open
) {
806 return (errs
== 0 ?
0 : 1);