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.
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;
31 static int connection_open = 0;
33 static void source(char *src);
34 static void rsource(char *src);
35 static void sink(char *targ);
38 * Print an error message and perform a fatal exit.
40 void fatalbox(char *fmt, ...)
44 fprintf(stderr, "Fatal: ");
45 vfprintf(stderr, fmt, ap);
46 fprintf(stderr, "\n");
52 * Print an error message and exit after closing the SSH link.
54 static void bump(char *fmt, ...)
58 fprintf(stderr, "Fatal: ");
59 vfprintf(stderr, fmt, ap);
60 fprintf(stderr, "\n");
62 if (connection_open) {
70 void ssh_get_password(char *prompt, char *str, int maxlen)
76 hin = GetStdHandle(STD_INPUT_HANDLE);
77 hout = GetStdHandle(STD_OUTPUT_HANDLE);
78 if (hin == INVALID_HANDLE_VALUE || hout == INVALID_HANDLE_VALUE)
79 bump("Cannot get standard input/output handles");
81 GetConsoleMode(hin, &savemode);
82 SetConsoleMode(hin, (savemode & (~ENABLE_ECHO_INPUT)) |
83 ENABLE_PROCESSED_INPUT | ENABLE_LINE_INPUT);
85 WriteFile(hout, prompt, strlen(prompt), &i, NULL);
86 ReadFile(hin, str, maxlen-1, &i, NULL);
88 SetConsoleMode(hin, savemode);
90 if (i > maxlen) i = maxlen-1; else i = i - 2;
93 WriteFile(hout, "\r\n", 2, &i, NULL);
97 * Open an SSH connection to user@host and execute cmd.
99 static void do_cmd(char *host, char *user, char *cmd)
101 char *err, *realhost;
103 if (host == NULL || host[0] == '\0')
104 bump("Empty host name");
106 /* Try to load settings for this host */
108 if (cfg.host[0] == '\0') {
109 /* No settings for this host; use defaults */
110 strncpy(cfg.host, host, sizeof(cfg.host)-1);
111 cfg.host[sizeof(cfg.host)-1] = '\0';
116 if (user != NULL && user[0] != '\0') {
117 strncpy(cfg.username, user, sizeof(cfg.username)-1);
118 cfg.username[sizeof(cfg.username)-1] = '\0';
120 } else if (cfg.username[0] == '\0') {
121 bump("Empty user name");
124 if (cfg.protocol != PROT_SSH)
127 err = ssh_init(cfg.host, cfg.port, cmd, &realhost);
129 bump("ssh_init: %s", err);
130 if (verbose && realhost != NULL)
131 fprintf(stderr, "Connected to %s\n", realhost);
137 * Update statistic information about current file.
139 static void print_stats(char *name, unsigned long size, unsigned long done,
140 time_t start, time_t now)
148 ratebs = (float) done / (now - start);
150 ratebs = (float) done;
155 eta = (unsigned long) ((size - done) / ratebs);
156 sprintf(etastr, "%02d:%02d:%02d",
157 eta / 3600, (eta % 3600) / 60, eta % 60);
159 pct = (int) (100.0 * (float) done / size);
161 printf("\r%-25.25s | %10ld kB | %5.1f kB/s | ETA: %8s | %3d%%",
162 name, done / 1024, ratebs / 1024.0,
170 * Find a colon in str and return a pointer to the colon.
171 * This is used to seperate hostname from filename.
173 static char * colon(char *str)
175 /* We ignore a leading colon, since the hostname cannot be
176 empty. We also ignore a colon as second character because
177 of filenames like f:myfile.txt. */
178 if (str[0] == '\0' ||
182 while (*str != '\0' &&
194 * Wait for a response from the other side.
195 * Return 0 if ok, -1 if error.
197 static int response(void)
199 char ch, resp, rbuf[2048];
202 if (ssh_recv(&resp, 1) <= 0)
203 bump("Lost connection");
213 case 2: /* fatal error */
215 if (ssh_recv(&ch, 1) <= 0)
216 bump("Protocol error: Lost connection");
218 } while (p < sizeof(rbuf) && ch != '\n');
221 fprintf(stderr, "%s\n", rbuf);
230 * Send an error message to the other side and to the screen.
231 * Increment error counter.
233 static void run_err(const char *fmt, ...)
239 strcpy(str, "\01scp: ");
240 vsprintf(str+strlen(str), fmt, ap);
242 ssh_send(str, strlen(str));
243 vfprintf(stderr, fmt, ap);
244 fprintf(stderr, "\n");
249 * Execute the source part of the SCP protocol.
251 static void source(char *src)
259 unsigned long stat_bytes;
260 time_t stat_starttime, stat_lasttime;
262 attr = GetFileAttributes(src);
264 run_err("%s: No such file or directory", src);
268 if ((attr & FILE_ATTRIBUTE_DIRECTORY) != 0) {
272 run_err("%s: not a regular file", src);
276 if ((last = strrchr(src, '/')) == NULL)
280 if (strrchr(last, '\\') != NULL)
281 last = strrchr(last, '\\') + 1;
282 if (last == src && strchr(src, ':') != NULL)
283 last = strchr(src, ':') + 1;
285 f = CreateFile(src, GENERIC_READ, FILE_SHARE_READ, NULL,
286 OPEN_EXISTING, 0, 0);
287 if (f == INVALID_HANDLE_VALUE) {
288 run_err("%s: Cannot open file");
293 FILETIME actime, wrtime;
294 unsigned long mtime, atime;
295 GetFileTime(f, NULL, &actime, &wrtime);
296 TIME_WIN_TO_POSIX(actime, atime);
297 TIME_WIN_TO_POSIX(wrtime, mtime);
298 sprintf(buf, "T%lu 0 %lu 0\n", mtime, atime);
299 ssh_send(buf, strlen(buf));
304 size = GetFileSize(f, NULL);
305 sprintf(buf, "C0644 %lu %s\n", size, last);
307 fprintf(stderr, "Sending file modes: %s", buf);
308 ssh_send(buf, strlen(buf));
314 stat_starttime = time(NULL);
318 for (i = 0; i < size; i += 4096) {
321 if (i + k > size) k = size - i;
322 if (! ReadFile(f, transbuf, k, &j, NULL) || j != k) {
323 if (statistics) printf("\n");
324 bump("%s: Read error", src);
326 ssh_send(transbuf, k);
329 if (time(NULL) != stat_lasttime ||
331 stat_lasttime = time(NULL);
332 print_stats(last, size, stat_bytes,
333 stat_starttime, stat_lasttime);
344 * Recursively send the contents of a directory.
346 static void rsource(char *src)
351 WIN32_FIND_DATA fdat;
354 if ((last = strrchr(src, '/')) == NULL)
358 if (strrchr(last, '\\') != NULL)
359 last = strrchr(last, '\\') + 1;
360 if (last == src && strchr(src, ':') != NULL)
361 last = strchr(src, ':') + 1;
363 /* maybe send filetime */
365 sprintf(buf, "D0755 0 %s\n", last);
367 fprintf(stderr, "Entering directory: %s", buf);
368 ssh_send(buf, strlen(buf));
372 sprintf(buf, "%s/*", src);
373 dir = FindFirstFile(buf, &fdat);
374 ok = (dir != INVALID_HANDLE_VALUE);
376 if (strcmp(fdat.cFileName, ".") == 0 ||
377 strcmp(fdat.cFileName, "..") == 0) {
378 } else if (strlen(src) + 1 + strlen(fdat.cFileName) >=
380 run_err("%s/%s: Name too long", src, fdat.cFileName);
382 sprintf(buf, "%s/%s", src, fdat.cFileName);
385 ok = FindNextFile(dir, &fdat);
390 ssh_send(buf, strlen(buf));
395 * Execute the sink part of the SCP protocol.
397 static void sink(char *targ)
407 unsigned long mtime, atime;
409 unsigned long size, i;
411 unsigned long stat_bytes;
412 time_t stat_starttime, stat_lasttime;
415 attr = GetFileAttributes(targ);
416 if (attr != -1 && (attr & FILE_ATTRIBUTE_DIRECTORY) != 0)
419 if (targetshouldbedirectory && !targisdir)
420 bump("%s: Not a directory", targ);
426 if (ssh_recv(&ch, 1) <= 0)
429 bump("Protocol error: Unexpected newline");
433 if (ssh_recv(&ch, 1) <= 0)
434 bump("Lost connection");
436 } while (i < sizeof(buf) && ch != '\n');
439 case '\01': /* error */
440 fprintf(stderr, "%s\n", buf+1);
443 case '\02': /* fatal error */
449 if (sscanf(buf, "T%d %*d %d %*d",
450 &mtime, &atime) == 2) {
455 bump("Protocol error: Illegal time format");
460 bump("Protocol error: Expected control record");
463 if (sscanf(buf+1, "%u %u %[^\n]", &mode, &size, namebuf) != 3)
464 bump("Protocol error: Illegal file descriptor format");
473 strcpy(namebuf, targ);
475 attr = GetFileAttributes(namebuf);
476 exists = (attr != -1);
479 if (exists && (attr & FILE_ATTRIBUTE_DIRECTORY) == 0) {
480 run_err("%s: Not a directory", namebuf);
484 if (! CreateDirectory(namebuf, NULL)) {
485 run_err("%s: Cannot create directory",
491 /* can we set the timestamp for directories ? */
495 f = CreateFile(namebuf, GENERIC_WRITE, 0, NULL,
496 CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
497 if (f == INVALID_HANDLE_VALUE) {
498 run_err("%s: Cannot create file", namebuf);
506 stat_starttime = time(NULL);
508 if ((stat_name = strrchr(namebuf, '/')) == NULL)
512 if (strrchr(stat_name, '\\') != NULL)
513 stat_name = strrchr(stat_name, '\\') + 1;
516 for (i = 0; i < size; i += 4096) {
519 if (i + k > size) k = size - i;
520 if (ssh_recv(transbuf, k) == 0)
521 bump("Lost connection");
522 if (wrerror) continue;
523 if (! WriteFile(f, transbuf, k, &j, NULL) || j != k) {
526 printf("\r%-25.25s | %50s\n",
528 "Write error.. waiting for end of file");
533 if (time(NULL) > stat_lasttime ||
535 stat_lasttime = time(NULL);
536 print_stats(stat_name, size, stat_bytes,
537 stat_starttime, stat_lasttime);
544 FILETIME actime, wrtime;
545 TIME_POSIX_TO_WIN(atime, actime);
546 TIME_POSIX_TO_WIN(mtime, wrtime);
547 SetFileTime(f, NULL, &actime, &wrtime);
552 run_err("%s: Write error", namebuf);
560 * We will copy local files to a remote server.
562 static void toremote(int argc, char *argv[])
564 char *src, *targ, *host, *user;
570 /* Seperate host from filename */
574 bump("targ == NULL in toremote()");
578 /* Substitute "." for emtpy target */
580 /* Seperate host and username */
582 host = strrchr(host, '@');
593 /* Find out if the source filespec covers multiple files
594 if so, we should set the targetshouldbedirectory flag */
596 WIN32_FIND_DATA fdat;
597 if (colon(argv[0]) != NULL)
598 bump("%s: Remote to remote not supported", argv[0]);
599 fh = FindFirstFile(argv[0], &fdat);
600 if (fh == INVALID_HANDLE_VALUE)
601 bump("%s: No such file or directory\n", argv[0]);
602 if (FindNextFile(fh, &fdat))
603 targetshouldbedirectory = 1;
607 cmd = smalloc(strlen(targ) + 100);
608 sprintf(cmd, "scp%s%s%s%s -t %s",
609 verbose ? " -v" : "",
610 recursive ? " -r" : "",
611 preserve ? " -p" : "",
612 targetshouldbedirectory ? " -d" : "",
614 do_cmd(host, user, cmd);
619 for (i = 0; i < argc - 1; i++) {
621 WIN32_FIND_DATA fdat;
623 if (colon(src) != NULL) {
625 "%s: Remote to remote not supported\n", src);
629 dir = FindFirstFile(src, &fdat);
630 if (dir == INVALID_HANDLE_VALUE) {
631 run_err("%s: No such file or directory", src);
637 if (strlen(src) + strlen(fdat.cFileName) >=
639 fprintf(stderr, "%s: Name too long", src);
642 strcpy(namebuf, src);
643 if ((last = strrchr(namebuf, '/')) == NULL)
647 if (strrchr(last, '\\') != NULL)
648 last = strrchr(last, '\\') + 1;
649 if (last == namebuf && strrchr(namebuf, ':') != NULL)
650 last = strchr(namebuf, ':') + 1;
651 strcpy(last, fdat.cFileName);
653 } while (FindNextFile(dir, &fdat));
659 * We will copy files from a remote server to the local machine.
661 static void tolocal(int argc, char *argv[])
663 char *src, *targ, *host, *user;
667 bump("More than one remote source not supported");
672 /* Seperate host from filename */
676 bump("Local to local copy not supported");
680 /* Substitute "." for empty filename */
682 /* Seperate username and hostname */
684 host = strrchr(host, '@');
694 cmd = smalloc(strlen(src) + 100);
695 sprintf(cmd, "scp%s%s%s%s -f %s",
696 verbose ? " -v" : "",
697 recursive ? " -r" : "",
698 preserve ? " -p" : "",
699 targetshouldbedirectory ? " -d" : "",
701 do_cmd(host, user, cmd);
708 * Initialize the Win$ock driver.
710 static void init_winsock()
715 winsock_ver = MAKEWORD(1, 1);
716 if (WSAStartup(winsock_ver, &wsadata))
717 bump("Unable to initialise WinSock");
718 if (LOBYTE(wsadata.wVersion) != 1 ||
719 HIBYTE(wsadata.wVersion) != 1)
720 bump("WinSock version is incompatible with 1.1");
724 * Short description of parameters.
728 printf("PuTTY Secure Copy client\n");
730 printf("usage: scp [-p] [-q] [-r] [-v] [user@]host:source target\n");
731 printf(" scp [-p] [-q] [-r] [-v] source [source..]"
732 " [user@]host:target\n");
737 * Main program (no, really?)
739 int main(int argc, char *argv[])
745 for (i = 1; i < argc; i++) {
746 if (argv[i][0] != '-')
748 if (strcmp(argv[i], "-v") == 0)
750 else if (strcmp(argv[i], "-r") == 0)
752 else if (strcmp(argv[i], "-p") == 0)
754 else if (strcmp(argv[i], "-q") == 0)
756 else if (strcmp(argv[i], "-h") == 0 ||
757 strcmp(argv[i], "-?") == 0)
759 else if (strcmp(argv[i], "--") == 0)
770 targetshouldbedirectory = 1;
772 if (colon(argv[argc-1]) != NULL)
773 toremote(argc, argv);
777 if (connection_open) {
785 return (errs == 0 ? 0 : 1);