2 * scp.c - Scp (Secure Copy) client for PuTTY.
3 * Joris van Rantwijk, Aug 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.
17 #define PUTTY_DO_GLOBALS
22 #define TIME_POSIX_TO_WIN(t, ft) (*(LONGLONG*)&(ft) = \
23 ((LONGLONG) (t) + (LONGLONG) 11644473600) * (LONGLONG) 10000000)
24 #define TIME_WIN_TO_POSIX(ft, t) ((t) = (unsigned long) \
25 ((*(LONGLONG*)&(ft)) / (LONGLONG) 10000000 - (LONGLONG) 11644473600))
29 static int recursive
= 0;
30 static int preserve
= 0;
31 static int targetshouldbedirectory
= 0;
32 static int statistics
= 1;
34 static int connection_open
= 0;
36 static void source(char *src
);
37 static void rsource(char *src
);
38 static void sink(char *targ
);
42 * Print an error message and perform a fatal exit.
44 void fatalbox(char *fmt
, ...)
48 fprintf(stderr
, "Fatal: ");
49 vfprintf(stderr
, fmt
, ap
);
50 fprintf(stderr
, "\n");
57 * Print an error message and exit after closing the SSH link.
59 static void bump(char *fmt
, ...)
63 fprintf(stderr
, "Fatal: ");
64 vfprintf(stderr
, fmt
, ap
);
65 fprintf(stderr
, "\n");
67 if (connection_open
) {
76 void ssh_get_password(char *prompt
, char *str
, int maxlen
)
81 hin
= GetStdHandle(STD_INPUT_HANDLE
);
82 hout
= GetStdHandle(STD_OUTPUT_HANDLE
);
83 if (hin
== INVALID_HANDLE_VALUE
|| hout
== INVALID_HANDLE_VALUE
)
84 bump("Cannot get standard input/output handles");
86 GetConsoleMode(hin
, &savemode
);
87 SetConsoleMode(hin
, (savemode
& (~ENABLE_ECHO_INPUT
)) |
88 ENABLE_PROCESSED_INPUT
| ENABLE_LINE_INPUT
);
90 WriteFile(hout
, prompt
, strlen(prompt
), &i
, NULL
);
91 ReadFile(hin
, str
, maxlen
-1, &i
, NULL
);
93 SetConsoleMode(hin
, savemode
);
95 if (i
> maxlen
) i
= maxlen
-1; else i
= i
- 2;
98 WriteFile(hout
, "\r\n", 2, &i
, NULL
);
103 * Open an SSH connection to user@host and execute cmd.
105 static void do_cmd(char *host
, char *user
, char *cmd
)
107 char *err
, *realhost
;
109 if (host
== NULL
|| host
[0] == '\0')
110 bump("Empty host name");
112 /* Try to load settings for this host */
114 if (cfg
.host
[0] == '\0') {
115 /* No settings for this host; use defaults */
116 strncpy(cfg
.host
, host
, sizeof(cfg
.host
)-1);
117 cfg
.host
[sizeof(cfg
.host
)-1] = '\0';
122 if (user
!= NULL
&& user
[0] != '\0') {
123 strncpy(cfg
.username
, user
, sizeof(cfg
.username
)-1);
124 cfg
.username
[sizeof(cfg
.username
)-1] = '\0';
126 } else if (cfg
.username
[0] == '\0') {
127 bump("Empty user name");
130 if (cfg
.protocol
!= PROT_SSH
)
133 err
= ssh_init(cfg
.host
, cfg
.port
, cmd
, &realhost
);
135 bump("ssh_init: %s", err
);
136 if (verbose
&& realhost
!= NULL
)
137 fprintf(stderr
, "Connected to %s\n", realhost
);
144 * Update statistic information about current file.
146 static void print_stats(char *name
, unsigned long size
, unsigned long done
,
147 unsigned long start
, unsigned long now
)
155 ratebs
= (float) done
/ (now
- start
);
157 ratebs
= (float) done
;
162 eta
= (size
- done
) / ratebs
;
163 sprintf(etastr
, "%02d:%02d:%02d",
164 eta
/ 3600, (eta
% 3600) / 60, eta
% 60);
166 pct
= 100.0 * (float) done
/ size
;
168 printf("\r%-25.25s | %10ld kB | %5.1f kB/s | ETA: %8s | %3d%%",
169 name
, done
/ 1024, ratebs
/ 1024.0,
178 * Find a colon in str and return a pointer to the colon.
179 * This is used to seperate hostname from filename.
181 static char * colon(char *str
)
183 /* We ignore a leading colon, since the hostname cannot be
184 empty. We also ignore a colon as second character because
185 of filenames like f:myfile.txt. */
186 if (str
[0] == '\0' ||
190 while (*str
!= '\0' &&
203 * Wait for a response from the other side.
204 * Return 0 if ok, -1 if error.
206 static int response(void)
208 char ch
, resp
, rbuf
[2048];
211 if (ssh_recv(&resp
, 1) <= 0)
212 bump("Lost connection");
222 case 2: /* fatal error */
224 if (ssh_recv(&ch
, 1) <= 0)
225 bump("Protocol error: Lost connection");
227 } while (p
< sizeof(rbuf
) && ch
!= '\n');
230 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");
260 * Execute the source part of the SCP protocol.
262 static void source(char *src
)
270 unsigned long stat_bytes
;
271 unsigned long 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
);
356 * Recursively send the contents of a directory.
358 static void rsource(char *src
)
363 WIN32_FIND_DATA fdat
;
366 if ((last
= strrchr(src
, '/')) == NULL
)
370 if (strrchr(last
, '\\') != NULL
)
371 last
= strrchr(last
, '\\') + 1;
372 if (last
== src
&& strchr(src
, ':') != NULL
)
373 last
= strchr(src
, ':') + 1;
375 /* maybe send filetime */
377 sprintf(buf
, "D0755 0 %s\n", last
);
379 fprintf(stderr
, "Entering directory: %s", buf
);
380 ssh_send(buf
, strlen(buf
));
384 sprintf(buf
, "%s/*", src
);
385 dir
= FindFirstFile(buf
, &fdat
);
386 ok
= (dir
!= INVALID_HANDLE_VALUE
);
388 if (strcmp(fdat
.cFileName
, ".") == 0 ||
389 strcmp(fdat
.cFileName
, "..") == 0) {
390 } else if (strlen(src
) + 1 + strlen(fdat
.cFileName
) >=
392 run_err("%s/%s: Name too long", src
, fdat
.cFileName
);
394 sprintf(buf
, "%s/%s", src
, fdat
.cFileName
);
397 ok
= FindNextFile(dir
, &fdat
);
402 ssh_send(buf
, strlen(buf
));
408 * Execute the sink part of the SCP protocol.
410 static void sink(char *targ
)
420 unsigned long mtime
, atime
;
422 unsigned long size
, i
;
424 unsigned long stat_bytes
;
425 unsigned long stat_starttime
, stat_lasttime
;
428 attr
= GetFileAttributes(targ
);
429 if (attr
!= -1 && (attr
& FILE_ATTRIBUTE_DIRECTORY
) != 0)
432 if (targetshouldbedirectory
&& !targisdir
)
433 bump("%s: Not a directory", targ
);
439 if (ssh_recv(&ch
, 1) <= 0)
442 bump("Protocol error: Unexpected newline");
446 if (ssh_recv(&ch
, 1) <= 0)
447 bump("Lost connection");
449 } while (i
< sizeof(buf
) && ch
!= '\n');
452 case '\01': /* error */
453 fprintf(stderr
, "%s\n", buf
+1);
456 case '\02': /* fatal error */
462 if (sscanf(buf
, "T%d %*d %d %*d",
463 &mtime
, &atime
) == 2) {
468 bump("Protocol error: Illegal time format");
473 bump("Protocol error: Expected control record");
476 if (sscanf(buf
+1, "%u %u %[^\n]", &mode
, &size
, namebuf
) != 3)
477 bump("Protocol error: Illegal file descriptor format");
486 strcpy(namebuf
, targ
);
488 attr
= GetFileAttributes(namebuf
);
489 exists
= (attr
!= -1);
492 if (exists
&& (attr
& FILE_ATTRIBUTE_DIRECTORY
) == 0) {
493 run_err("%s: Not a directory", namebuf
);
497 if (! CreateDirectory(namebuf
, NULL
)) {
498 run_err("%s: Cannot create directory",
504 /* can we set the timestamp for directories ? */
508 f
= CreateFile(namebuf
, GENERIC_WRITE
, 0, NULL
,
509 CREATE_ALWAYS
, FILE_ATTRIBUTE_NORMAL
, 0);
510 if (f
== INVALID_HANDLE_VALUE
) {
511 run_err("%s: Cannot create file", namebuf
);
519 stat_starttime
= time(NULL
);
521 if ((stat_name
= strrchr(namebuf
, '/')) == NULL
)
525 if (strrchr(stat_name
, '\\') != NULL
)
526 stat_name
= strrchr(stat_name
, '\\') + 1;
529 for (i
= 0; i
< size
; i
+= 4096) {
532 if (i
+ k
> size
) k
= size
- i
;
533 if (ssh_recv(transbuf
, k
) == 0)
534 bump("Lost connection");
535 if (wrerror
) continue;
536 if (! WriteFile(f
, transbuf
, k
, &j
, NULL
) || j
!= k
) {
539 printf("\r%-25.25s | %50s\n",
541 "Write error.. waiting for end of file");
546 if (time(NULL
) > stat_lasttime
||
548 stat_lasttime
= time(NULL
);
549 print_stats(stat_name
, size
, stat_bytes
,
550 stat_starttime
, stat_lasttime
);
557 FILETIME actime
, wrtime
;
558 TIME_POSIX_TO_WIN(atime
, actime
);
559 TIME_POSIX_TO_WIN(mtime
, wrtime
);
560 SetFileTime(f
, NULL
, &actime
, &wrtime
);
565 run_err("%s: Write error", namebuf
);
574 * We will copy local files to a remote server.
576 static void toremote(int argc
, char *argv
[])
578 char *src
, *targ
, *host
, *user
;
584 /* Seperate host from filename */
588 bump("targ == NULL in toremote()");
592 /* Substitute "." for emtpy target */
594 /* Seperate host and username */
596 host
= strrchr(host
, '@');
607 /* Find out if the source filespec covers multiple files
608 if so, we should set the targetshouldbedirectory flag */
610 WIN32_FIND_DATA fdat
;
611 if (colon(argv
[0]) != NULL
)
612 bump("%s: Remote to remote not supported", argv
[0]);
613 fh
= FindFirstFile(argv
[0], &fdat
);
614 if (fh
== INVALID_HANDLE_VALUE
)
615 bump("%s: No such file or directory\n", argv
[0]);
616 if (FindNextFile(fh
, &fdat
))
617 targetshouldbedirectory
= 1;
621 cmd
= smalloc(strlen(targ
) + 100);
622 sprintf(cmd
, "scp%s%s%s%s -t %s",
623 verbose ?
" -v" : "",
624 recursive ?
" -r" : "",
625 preserve ?
" -p" : "",
626 targetshouldbedirectory ?
" -d" : "",
628 do_cmd(host
, user
, cmd
);
633 for (i
= 0; i
< argc
- 1; i
++) {
635 WIN32_FIND_DATA fdat
;
637 if (colon(src
) != NULL
) {
639 "%s: Remote to remote not supported\n", src
);
643 dir
= FindFirstFile(src
, &fdat
);
644 if (dir
== INVALID_HANDLE_VALUE
) {
645 run_err("%s: No such file or directory", src
);
651 if (strlen(src
) + strlen(fdat
.cFileName
) >=
653 fprintf(stderr
, "%s: Name too long", src
);
656 strcpy(namebuf
, src
);
657 if ((last
= strrchr(namebuf
, '/')) == NULL
)
661 if (strrchr(last
, '\\') != NULL
)
662 last
= strrchr(last
, '\\') + 1;
663 if (last
== namebuf
&& strrchr(namebuf
, ':') != NULL
)
664 last
= strchr(namebuf
, ':') + 1;
665 strcpy(last
, fdat
.cFileName
);
667 } while (FindNextFile(dir
, &fdat
));
674 * We will copy files from a remote server to the local machine.
676 static void tolocal(int argc
, char *argv
[])
678 char *src
, *targ
, *host
, *user
;
682 bump("More than one remote source not supported");
687 /* Seperate host from filename */
691 bump("Local to local copy not supported");
695 /* Substitute "." for empty filename */
697 /* Seperate username and hostname */
699 host
= strrchr(host
, '@');
709 cmd
= smalloc(strlen(src
) + 100);
710 sprintf(cmd
, "scp%s%s%s%s -f %s",
711 verbose ?
" -v" : "",
712 recursive ?
" -r" : "",
713 preserve ?
" -p" : "",
714 targetshouldbedirectory ?
" -d" : "",
716 do_cmd(host
, user
, cmd
);
724 * Initialize the Win$ock driver.
726 static void init_winsock()
731 winsock_ver
= MAKEWORD(1, 1);
732 if (WSAStartup(winsock_ver
, &wsadata
))
733 bump("Unable to initialise WinSock");
734 if (LOBYTE(wsadata
.wVersion
) != 1 ||
735 HIBYTE(wsadata
.wVersion
) != 1)
736 bump("WinSock version is incompatible with 1.1");
741 * Short description of parameters.
745 printf("PuTTY Secure Copy client\n");
747 printf("usage: scp [-p] [-q] [-r] [-v] [user@]host:source target\n");
748 printf(" scp [-p] [-q] [-r] [-v] source [source..]"
749 " [user@]host:target\n");
755 * Main program (no, really?)
757 int main(int argc
, char *argv
[])
763 for (i
= 1; i
< argc
; i
++) {
764 if (argv
[i
][0] != '-')
766 if (strcmp(argv
[i
], "-v") == 0)
768 else if (strcmp(argv
[i
], "-r") == 0)
770 else if (strcmp(argv
[i
], "-p") == 0)
772 else if (strcmp(argv
[i
], "-q") == 0)
774 else if (strcmp(argv
[i
], "-h") == 0 ||
775 strcmp(argv
[i
], "-?") == 0)
777 else if (strcmp(argv
[i
], "--") == 0)
788 targetshouldbedirectory
= 1;
790 if (colon(argv
[argc
-1]) != NULL
)
791 toremote(argc
, argv
);
795 if (connection_open
) {
803 return (errs
== 0 ?
0 : 1);