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
, "%02ld:%02ld:%02ld",
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) {
282 * Avoid . and .. directories.
285 p
= strrchr(src
, '/');
287 p
= strrchr(src
, '\\');
292 if (!strcmp(p
, ".") || !strcmp(p
, ".."))
297 run_err("%s: not a regular file", src
);
302 if ((last
= strrchr(src
, '/')) == NULL
)
306 if (strrchr(last
, '\\') != NULL
)
307 last
= strrchr(last
, '\\') + 1;
308 if (last
== src
&& strchr(src
, ':') != NULL
)
309 last
= strchr(src
, ':') + 1;
311 f
= CreateFile(src
, GENERIC_READ
, FILE_SHARE_READ
, NULL
,
312 OPEN_EXISTING
, 0, 0);
313 if (f
== INVALID_HANDLE_VALUE
) {
314 run_err("%s: Cannot open file");
319 FILETIME actime
, wrtime
;
320 unsigned long mtime
, atime
;
321 GetFileTime(f
, NULL
, &actime
, &wrtime
);
322 TIME_WIN_TO_POSIX(actime
, atime
);
323 TIME_WIN_TO_POSIX(wrtime
, mtime
);
324 sprintf(buf
, "T%lu 0 %lu 0\n", mtime
, atime
);
325 ssh_send(buf
, strlen(buf
));
330 size
= GetFileSize(f
, NULL
);
331 sprintf(buf
, "C0644 %lu %s\n", size
, last
);
333 fprintf(stderr
, "Sending file modes: %s", buf
);
334 ssh_send(buf
, strlen(buf
));
340 stat_starttime
= time(NULL
);
344 for (i
= 0; i
< size
; i
+= 4096) {
347 if (i
+ k
> size
) k
= size
- i
;
348 if (! ReadFile(f
, transbuf
, k
, &j
, NULL
) || j
!= k
) {
349 if (statistics
) printf("\n");
350 bump("%s: Read error", src
);
352 ssh_send(transbuf
, k
);
355 if (time(NULL
) != stat_lasttime
||
357 stat_lasttime
= time(NULL
);
358 print_stats(last
, size
, stat_bytes
,
359 stat_starttime
, stat_lasttime
);
370 * Recursively send the contents of a directory.
372 static void rsource(char *src
)
377 WIN32_FIND_DATA fdat
;
380 if ((last
= strrchr(src
, '/')) == NULL
)
384 if (strrchr(last
, '\\') != NULL
)
385 last
= strrchr(last
, '\\') + 1;
386 if (last
== src
&& strchr(src
, ':') != NULL
)
387 last
= strchr(src
, ':') + 1;
389 /* maybe send filetime */
391 sprintf(buf
, "D0755 0 %s\n", last
);
393 fprintf(stderr
, "Entering directory: %s", buf
);
394 ssh_send(buf
, strlen(buf
));
398 sprintf(buf
, "%s/*", src
);
399 dir
= FindFirstFile(buf
, &fdat
);
400 ok
= (dir
!= INVALID_HANDLE_VALUE
);
402 if (strcmp(fdat
.cFileName
, ".") == 0 ||
403 strcmp(fdat
.cFileName
, "..") == 0) {
404 } else if (strlen(src
) + 1 + strlen(fdat
.cFileName
) >=
406 run_err("%s/%s: Name too long", src
, fdat
.cFileName
);
408 sprintf(buf
, "%s/%s", src
, fdat
.cFileName
);
411 ok
= FindNextFile(dir
, &fdat
);
416 ssh_send(buf
, strlen(buf
));
421 * Execute the sink part of the SCP protocol.
423 static void sink(char *targ
)
433 unsigned long mtime
, atime
;
435 unsigned long size
, i
;
437 unsigned long stat_bytes
;
438 time_t stat_starttime
, stat_lasttime
;
441 attr
= GetFileAttributes(targ
);
442 if (attr
!= -1 && (attr
& FILE_ATTRIBUTE_DIRECTORY
) != 0)
445 if (targetshouldbedirectory
&& !targisdir
)
446 bump("%s: Not a directory", targ
);
452 if (ssh_recv(&ch
, 1) <= 0)
455 bump("Protocol error: Unexpected newline");
459 if (ssh_recv(&ch
, 1) <= 0)
460 bump("Lost connection");
462 } while (i
< sizeof(buf
) && ch
!= '\n');
465 case '\01': /* error */
466 fprintf(stderr
, "%s\n", buf
+1);
469 case '\02': /* fatal error */
475 if (sscanf(buf
, "T%ld %*d %ld %*d",
476 &mtime
, &atime
) == 2) {
481 bump("Protocol error: Illegal time format");
486 bump("Protocol error: Expected control record");
489 if (sscanf(buf
+1, "%u %lu %[^\n]", &mode
, &size
, namebuf
) != 3)
490 bump("Protocol error: Illegal file descriptor format");
499 strcpy(namebuf
, targ
);
501 attr
= GetFileAttributes(namebuf
);
502 exists
= (attr
!= -1);
505 if (exists
&& (attr
& FILE_ATTRIBUTE_DIRECTORY
) == 0) {
506 run_err("%s: Not a directory", namebuf
);
510 if (! CreateDirectory(namebuf
, NULL
)) {
511 run_err("%s: Cannot create directory",
517 /* can we set the timestamp for directories ? */
521 f
= CreateFile(namebuf
, GENERIC_WRITE
, 0, NULL
,
522 CREATE_ALWAYS
, FILE_ATTRIBUTE_NORMAL
, 0);
523 if (f
== INVALID_HANDLE_VALUE
) {
524 run_err("%s: Cannot create file", namebuf
);
532 stat_starttime
= time(NULL
);
534 if ((stat_name
= strrchr(namebuf
, '/')) == NULL
)
538 if (strrchr(stat_name
, '\\') != NULL
)
539 stat_name
= strrchr(stat_name
, '\\') + 1;
542 for (i
= 0; i
< size
; i
+= 4096) {
545 if (i
+ k
> size
) k
= size
- i
;
546 if (ssh_recv(transbuf
, k
) == 0)
547 bump("Lost connection");
548 if (wrerror
) continue;
549 if (! WriteFile(f
, transbuf
, k
, &j
, NULL
) || j
!= k
) {
552 printf("\r%-25.25s | %50s\n",
554 "Write error.. waiting for end of file");
559 if (time(NULL
) > stat_lasttime
||
561 stat_lasttime
= time(NULL
);
562 print_stats(stat_name
, size
, stat_bytes
,
563 stat_starttime
, stat_lasttime
);
570 FILETIME actime
, wrtime
;
571 TIME_POSIX_TO_WIN(atime
, actime
);
572 TIME_POSIX_TO_WIN(mtime
, wrtime
);
573 SetFileTime(f
, NULL
, &actime
, &wrtime
);
578 run_err("%s: Write error", namebuf
);
586 * We will copy local files to a remote server.
588 static void toremote(int argc
, char *argv
[])
590 char *src
, *targ
, *host
, *user
;
596 /* Seperate host from filename */
600 bump("targ == NULL in toremote()");
604 /* Substitute "." for emtpy target */
606 /* Seperate host and username */
608 host
= strrchr(host
, '@');
619 /* Find out if the source filespec covers multiple files
620 if so, we should set the targetshouldbedirectory flag */
622 WIN32_FIND_DATA fdat
;
623 if (colon(argv
[0]) != NULL
)
624 bump("%s: Remote to remote not supported", argv
[0]);
625 fh
= FindFirstFile(argv
[0], &fdat
);
626 if (fh
== INVALID_HANDLE_VALUE
)
627 bump("%s: No such file or directory\n", argv
[0]);
628 if (FindNextFile(fh
, &fdat
))
629 targetshouldbedirectory
= 1;
633 cmd
= smalloc(strlen(targ
) + 100);
634 sprintf(cmd
, "scp%s%s%s%s -t %s",
635 verbose ?
" -v" : "",
636 recursive ?
" -r" : "",
637 preserve ?
" -p" : "",
638 targetshouldbedirectory ?
" -d" : "",
640 do_cmd(host
, user
, cmd
);
645 for (i
= 0; i
< argc
- 1; i
++) {
647 WIN32_FIND_DATA fdat
;
649 if (colon(src
) != NULL
) {
651 "%s: Remote to remote not supported\n", src
);
655 dir
= FindFirstFile(src
, &fdat
);
656 if (dir
== INVALID_HANDLE_VALUE
) {
657 run_err("%s: No such file or directory", src
);
663 if (strlen(src
) + strlen(fdat
.cFileName
) >=
665 fprintf(stderr
, "%s: Name too long", src
);
668 strcpy(namebuf
, src
);
669 if ((last
= strrchr(namebuf
, '/')) == NULL
)
673 if (strrchr(last
, '\\') != NULL
)
674 last
= strrchr(last
, '\\') + 1;
675 if (last
== namebuf
&& strrchr(namebuf
, ':') != NULL
)
676 last
= strchr(namebuf
, ':') + 1;
677 strcpy(last
, fdat
.cFileName
);
679 } while (FindNextFile(dir
, &fdat
));
685 * We will copy files from a remote server to the local machine.
687 static void tolocal(int argc
, char *argv
[])
689 char *src
, *targ
, *host
, *user
;
693 bump("More than one remote source not supported");
698 /* Seperate host from filename */
702 bump("Local to local copy not supported");
706 /* Substitute "." for empty filename */
708 /* Seperate username and hostname */
710 host
= strrchr(host
, '@');
720 cmd
= smalloc(strlen(src
) + 100);
721 sprintf(cmd
, "scp%s%s%s%s -f %s",
722 verbose ?
" -v" : "",
723 recursive ?
" -r" : "",
724 preserve ?
" -p" : "",
725 targetshouldbedirectory ?
" -d" : "",
727 do_cmd(host
, user
, cmd
);
734 * Initialize the Win$ock driver.
736 static void init_winsock()
741 winsock_ver
= MAKEWORD(1, 1);
742 if (WSAStartup(winsock_ver
, &wsadata
))
743 bump("Unable to initialise WinSock");
744 if (LOBYTE(wsadata
.wVersion
) != 1 ||
745 HIBYTE(wsadata
.wVersion
) != 1)
746 bump("WinSock version is incompatible with 1.1");
750 * Short description of parameters.
754 printf("PuTTY Secure Copy client\n");
756 printf("Usage: scp [options] [user@]host:source target\n");
757 printf(" scp [options] source [source...] [user@]host:target\n");
758 printf("Options:\n");
759 printf(" -p preserve file attributes\n");
760 printf(" -q quiet, don't show statistics\n");
761 printf(" -r copy directories recursively\n");
762 printf(" -v show verbose messages\n");
763 printf(" -P port connect to specified port\n");
764 printf(" -pw passw login with specified password\n");
769 * Main program (no, really?)
771 int main(int argc
, char *argv
[])
777 for (i
= 1; i
< argc
; i
++) {
778 if (argv
[i
][0] != '-')
780 if (strcmp(argv
[i
], "-v") == 0)
782 else if (strcmp(argv
[i
], "-r") == 0)
784 else if (strcmp(argv
[i
], "-p") == 0)
786 else if (strcmp(argv
[i
], "-q") == 0)
788 else if (strcmp(argv
[i
], "-h") == 0 ||
789 strcmp(argv
[i
], "-?") == 0)
791 else if (strcmp(argv
[i
], "-P") == 0 && i
+1 < argc
)
792 portnumber
= atoi(argv
[++i
]);
793 else if (strcmp(argv
[i
], "-pw") == 0 && i
+1 < argc
)
794 password
= argv
[++i
];
795 else if (strcmp(argv
[i
], "--") == 0)
806 targetshouldbedirectory
= 1;
808 if (colon(argv
[argc
-1]) != NULL
)
809 toremote(argc
, argv
);
813 if (connection_open
) {
821 return (errs
== 0 ?
0 : 1);