2 * scp.c - Scp (Secure Copy) client for PuTTY.
3 * Joris van Rantwijk, Simon Tatham
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))
25 static int verbose = 0;
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 * This function is needed to link with ssh.c, but it never gets called.
48 * Print an error message and perform a fatal exit.
50 void fatalbox(char *fmt, ...)
54 fprintf(stderr, "Fatal: ");
55 vfprintf(stderr, fmt, ap);
56 fprintf(stderr, "\n");
62 * Print an error message and exit after closing the SSH link.
64 static void bump(char *fmt, ...)
68 fprintf(stderr, "Fatal: ");
69 vfprintf(stderr, fmt, ap);
70 fprintf(stderr, "\n");
72 if (connection_open) {
80 static void get_password(const char *prompt, char *str, int maxlen)
86 strncpy(str, password, maxlen);
92 hin = GetStdHandle(STD_INPUT_HANDLE);
93 hout = GetStdHandle(STD_OUTPUT_HANDLE);
94 if (hin == INVALID_HANDLE_VALUE || hout == INVALID_HANDLE_VALUE)
95 bump("Cannot get standard input/output handles");
97 GetConsoleMode(hin, &savemode);
98 SetConsoleMode(hin, (savemode & (~ENABLE_ECHO_INPUT)) |
99 ENABLE_PROCESSED_INPUT | ENABLE_LINE_INPUT);
101 WriteFile(hout, prompt, strlen(prompt), &i, NULL);
102 ReadFile(hin, str, maxlen-1, &i, NULL);
104 SetConsoleMode(hin, savemode);
106 if ((int)i > maxlen) i = maxlen-1; else i = i - 2;
109 WriteFile(hout, "\r\n", 2, &i, NULL);
113 * Open an SSH connection to user@host and execute cmd.
115 static void do_cmd(char *host, char *user, char *cmd)
117 char *err, *realhost;
119 if (host == NULL || host[0] == '\0')
120 bump("Empty host name");
122 /* Try to load settings for this host */
124 if (cfg.host[0] == '\0') {
125 /* No settings for this host; use defaults */
126 strncpy(cfg.host, host, sizeof(cfg.host)-1);
127 cfg.host[sizeof(cfg.host)-1] = '\0';
132 if (user != NULL && user[0] != '\0') {
133 strncpy(cfg.username, user, sizeof(cfg.username)-1);
134 cfg.username[sizeof(cfg.username)-1] = '\0';
135 } else if (cfg.username[0] == '\0') {
136 bump("Empty user name");
139 if (cfg.protocol != PROT_SSH)
143 cfg.port = portnumber;
145 err = ssh_scp_init(cfg.host, cfg.port, cmd, &realhost);
147 bump("ssh_init: %s", err);
148 if (verbose && realhost != NULL)
149 fprintf(stderr, "Connected to %s\n", realhost);
155 * Update statistic information about current file.
157 static void print_stats(char *name, unsigned long size, unsigned long done,
158 time_t start, time_t now)
166 ratebs = (float) done / (now - start);
168 ratebs = (float) done;
173 eta = (unsigned long) ((size - done) / ratebs);
174 sprintf(etastr, "%02ld:%02ld:%02ld",
175 eta / 3600, (eta % 3600) / 60, eta % 60);
177 pct = (int) (100.0 * (float) done / size);
179 printf("\r%-25.25s | %10ld kB | %5.1f kB/s | ETA: %8s | %3d%%",
180 name, done / 1024, ratebs / 1024.0,
188 * Find a colon in str and return a pointer to the colon.
189 * This is used to separate hostname from filename.
191 static char * colon(char *str)
193 /* We ignore a leading colon, since the hostname cannot be
194 empty. We also ignore a colon as second character because
195 of filenames like f:myfile.txt. */
196 if (str[0] == '\0' ||
200 while (*str != '\0' &&
212 * Wait for a response from the other side.
213 * Return 0 if ok, -1 if error.
215 static int response(void)
217 char ch, resp, rbuf[2048];
220 if (ssh_scp_recv(&resp, 1) <= 0)
221 bump("Lost connection");
231 case 2: /* fatal error */
233 if (ssh_scp_recv(&ch, 1) <= 0)
234 bump("Protocol error: Lost connection");
236 } while (p < sizeof(rbuf) && ch != '\n');
239 fprintf(stderr, "%s\n", rbuf);
248 * Send an error message to the other side and to the screen.
249 * Increment error counter.
251 static void run_err(const char *fmt, ...)
257 strcpy(str, "\01scp: ");
258 vsprintf(str+strlen(str), fmt, ap);
260 ssh_scp_send(str, strlen(str));
261 vfprintf(stderr, fmt, ap);
262 fprintf(stderr, "\n");
267 * Execute the source part of the SCP protocol.
269 static void source(char *src)
277 unsigned long stat_bytes;
278 time_t stat_starttime, stat_lasttime;
280 attr = GetFileAttributes(src);
281 if (attr == (DWORD)-1) {
282 run_err("%s: No such file or directory", src);
286 if ((attr & FILE_ATTRIBUTE_DIRECTORY) != 0) {
289 * Avoid . and .. directories.
292 p = strrchr(src, '/');
294 p = strrchr(src, '\\');
299 if (!strcmp(p, ".") || !strcmp(p, ".."))
304 run_err("%s: not a regular file", src);
309 if ((last = strrchr(src, '/')) == NULL)
313 if (strrchr(last, '\\') != NULL)
314 last = strrchr(last, '\\') + 1;
315 if (last == src && strchr(src, ':') != NULL)
316 last = strchr(src, ':') + 1;
318 f = CreateFile(src, GENERIC_READ, FILE_SHARE_READ, NULL,
319 OPEN_EXISTING, 0, 0);
320 if (f == INVALID_HANDLE_VALUE) {
321 run_err("%s: Cannot open file", src);
326 FILETIME actime, wrtime;
327 unsigned long mtime, atime;
328 GetFileTime(f, NULL, &actime, &wrtime);
329 TIME_WIN_TO_POSIX(actime, atime);
330 TIME_WIN_TO_POSIX(wrtime, mtime);
331 sprintf(buf, "T%lu 0 %lu 0\n", mtime, atime);
332 ssh_scp_send(buf, strlen(buf));
337 size = GetFileSize(f, NULL);
338 sprintf(buf, "C0644 %lu %s\n", size, last);
340 fprintf(stderr, "Sending file modes: %s", buf);
341 ssh_scp_send(buf, strlen(buf));
347 stat_starttime = time(NULL);
351 for (i = 0; i < size; i += 4096) {
354 if (i + k > size) k = size - i;
355 if (! ReadFile(f, transbuf, k, &j, NULL) || j != k) {
356 if (statistics) printf("\n");
357 bump("%s: Read error", src);
359 ssh_scp_send(transbuf, k);
362 if (time(NULL) != stat_lasttime ||
364 stat_lasttime = time(NULL);
365 print_stats(last, size, stat_bytes,
366 stat_starttime, stat_lasttime);
377 * Recursively send the contents of a directory.
379 static void rsource(char *src)
384 WIN32_FIND_DATA fdat;
387 if ((last = strrchr(src, '/')) == NULL)
391 if (strrchr(last, '\\') != NULL)
392 last = strrchr(last, '\\') + 1;
393 if (last == src && strchr(src, ':') != NULL)
394 last = strchr(src, ':') + 1;
396 /* maybe send filetime */
398 sprintf(buf, "D0755 0 %s\n", last);
400 fprintf(stderr, "Entering directory: %s", buf);
401 ssh_scp_send(buf, strlen(buf));
405 sprintf(buf, "%s/*", src);
406 dir = FindFirstFile(buf, &fdat);
407 ok = (dir != INVALID_HANDLE_VALUE);
409 if (strcmp(fdat.cFileName, ".") == 0 ||
410 strcmp(fdat.cFileName, "..") == 0) {
411 } else if (strlen(src) + 1 + strlen(fdat.cFileName) >=
413 run_err("%s/%s: Name too long", src, fdat.cFileName);
415 sprintf(buf, "%s/%s", src, fdat.cFileName);
418 ok = FindNextFile(dir, &fdat);
423 ssh_scp_send(buf, strlen(buf));
428 * Execute the sink part of the SCP protocol.
430 static void sink(char *targ)
440 unsigned long mtime, atime;
442 unsigned long size, i;
444 unsigned long stat_bytes;
445 time_t stat_starttime, stat_lasttime;
448 attr = GetFileAttributes(targ);
449 if (attr != (DWORD)-1 && (attr & FILE_ATTRIBUTE_DIRECTORY) != 0)
452 if (targetshouldbedirectory && !targisdir)
453 bump("%s: Not a directory", targ);
459 if (ssh_scp_recv(&ch, 1) <= 0)
462 bump("Protocol error: Unexpected newline");
466 if (ssh_scp_recv(&ch, 1) <= 0)
467 bump("Lost connection");
469 } while (i < sizeof(buf) && ch != '\n');
472 case '\01': /* error */
473 fprintf(stderr, "%s\n", buf+1);
476 case '\02': /* fatal error */
482 if (sscanf(buf, "T%ld %*d %ld %*d",
483 &mtime, &atime) == 2) {
488 bump("Protocol error: Illegal time format");
493 bump("Protocol error: Expected control record");
496 if (sscanf(buf+1, "%u %lu %[^\n]", &mode, &size, namebuf) != 3)
497 bump("Protocol error: Illegal file descriptor format");
506 strcpy(namebuf, targ);
508 attr = GetFileAttributes(namebuf);
509 exists = (attr != (DWORD)-1);
512 if (exists && (attr & FILE_ATTRIBUTE_DIRECTORY) == 0) {
513 run_err("%s: Not a directory", namebuf);
517 if (! CreateDirectory(namebuf, NULL)) {
518 run_err("%s: Cannot create directory",
524 /* can we set the timestamp for directories ? */
528 f = CreateFile(namebuf, GENERIC_WRITE, 0, NULL,
529 CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
530 if (f == INVALID_HANDLE_VALUE) {
531 run_err("%s: Cannot create file", namebuf);
539 stat_starttime = time(NULL);
541 if ((stat_name = strrchr(namebuf, '/')) == NULL)
545 if (strrchr(stat_name, '\\') != NULL)
546 stat_name = strrchr(stat_name, '\\') + 1;
549 for (i = 0; i < size; i += 4096) {
552 if (i + k > size) k = size - i;
553 if (ssh_scp_recv(transbuf, k) == 0)
554 bump("Lost connection");
555 if (wrerror) continue;
556 if (! WriteFile(f, transbuf, k, &j, NULL) || j != k) {
559 printf("\r%-25.25s | %50s\n",
561 "Write error.. waiting for end of file");
566 if (time(NULL) > stat_lasttime ||
568 stat_lasttime = time(NULL);
569 print_stats(stat_name, size, stat_bytes,
570 stat_starttime, stat_lasttime);
577 FILETIME actime, wrtime;
578 TIME_POSIX_TO_WIN(atime, actime);
579 TIME_POSIX_TO_WIN(mtime, wrtime);
580 SetFileTime(f, NULL, &actime, &wrtime);
585 run_err("%s: Write error", namebuf);
593 * We will copy local files to a remote server.
595 static void toremote(int argc, char *argv[])
597 char *src, *targ, *host, *user;
603 /* Separate host from filename */
607 bump("targ == NULL in toremote()");
611 /* Substitute "." for emtpy target */
613 /* Separate host and username */
615 host = strrchr(host, '@');
626 /* Find out if the source filespec covers multiple files
627 if so, we should set the targetshouldbedirectory flag */
629 WIN32_FIND_DATA fdat;
630 if (colon(argv[0]) != NULL)
631 bump("%s: Remote to remote not supported", argv[0]);
632 fh = FindFirstFile(argv[0], &fdat);
633 if (fh == INVALID_HANDLE_VALUE)
634 bump("%s: No such file or directory\n", argv[0]);
635 if (FindNextFile(fh, &fdat))
636 targetshouldbedirectory = 1;
640 cmd = smalloc(strlen(targ) + 100);
641 sprintf(cmd, "scp%s%s%s%s -t %s",
642 verbose ? " -v" : "",
643 recursive ? " -r" : "",
644 preserve ? " -p" : "",
645 targetshouldbedirectory ? " -d" : "",
647 do_cmd(host, user, cmd);
652 for (i = 0; i < argc - 1; i++) {
654 WIN32_FIND_DATA fdat;
656 if (colon(src) != NULL) {
658 "%s: Remote to remote not supported\n", src);
662 dir = FindFirstFile(src, &fdat);
663 if (dir == INVALID_HANDLE_VALUE) {
664 run_err("%s: No such file or directory", src);
670 if (strlen(src) + strlen(fdat.cFileName) >=
672 fprintf(stderr, "%s: Name too long", src);
675 strcpy(namebuf, src);
676 if ((last = strrchr(namebuf, '/')) == NULL)
680 if (strrchr(last, '\\') != NULL)
681 last = strrchr(last, '\\') + 1;
682 if (last == namebuf && strrchr(namebuf, ':') != NULL)
683 last = strchr(namebuf, ':') + 1;
684 strcpy(last, fdat.cFileName);
686 } while (FindNextFile(dir, &fdat));
692 * We will copy files from a remote server to the local machine.
694 static void tolocal(int argc, char *argv[])
696 char *src, *targ, *host, *user;
700 bump("More than one remote source not supported");
705 /* Separate host from filename */
709 bump("Local to local copy not supported");
713 /* Substitute "." for empty filename */
715 /* Separate username and hostname */
717 host = strrchr(host, '@');
727 cmd = smalloc(strlen(src) + 100);
728 sprintf(cmd, "scp%s%s%s%s -f %s",
729 verbose ? " -v" : "",
730 recursive ? " -r" : "",
731 preserve ? " -p" : "",
732 targetshouldbedirectory ? " -d" : "",
734 do_cmd(host, user, cmd);
741 * We will issue a list command to get a remote directory.
743 static void get_dir_list(int argc, char *argv[])
745 char *src, *host, *user;
751 /* Separate host from filename */
755 bump("Local to local copy not supported");
759 /* Substitute "." for empty filename */
761 /* Separate username and hostname */
763 host = strrchr(host, '@');
773 cmd = smalloc(4*strlen(src) + 100);
774 strcpy(cmd, "ls -la '");
775 p = cmd + strlen(cmd);
776 for (q = src; *q; q++) {
778 *p++ = '\''; *p++ = '\\'; *p++ = '\''; *p++ = '\'';
786 do_cmd(host, user, cmd);
789 while (ssh_scp_recv(&c, 1) > 0)
790 fputc(c, stdout); /* thank heavens for buffered I/O */
794 * Initialize the Win$ock driver.
796 static void init_winsock(void)
801 winsock_ver = MAKEWORD(1, 1);
802 if (WSAStartup(winsock_ver, &wsadata))
803 bump("Unable to initialise WinSock");
804 if (LOBYTE(wsadata.wVersion) != 1 ||
805 HIBYTE(wsadata.wVersion) != 1)
806 bump("WinSock version is incompatible with 1.1");
810 * Short description of parameters.
812 static void usage(void)
814 printf("PuTTY Secure Copy client\n");
816 printf("Usage: pscp [options] [user@]host:source target\n");
817 printf(" pscp [options] source [source...] [user@]host:target\n");
818 printf(" pscp [options] -ls user@host:filespec\n");
819 printf("Options:\n");
820 printf(" -p preserve file attributes\n");
821 printf(" -q quiet, don't show statistics\n");
822 printf(" -r copy directories recursively\n");
823 printf(" -v show verbose messages\n");
824 printf(" -P port connect to specified port\n");
825 printf(" -pw passw login with specified password\n");
830 * Main program (no, really?)
832 int main(int argc, char *argv[])
837 default_protocol = PROT_TELNET;
839 scp_flags = SCP_FLAG;
840 ssh_get_password = &get_password;
843 for (i = 1; i < argc; i++) {
844 if (argv[i][0] != '-')
846 if (strcmp(argv[i], "-v") == 0)
847 verbose = 1, scp_flags |= SCP_VERBOSE;
848 else if (strcmp(argv[i], "-r") == 0)
850 else if (strcmp(argv[i], "-p") == 0)
852 else if (strcmp(argv[i], "-q") == 0)
854 else if (strcmp(argv[i], "-h") == 0 ||
855 strcmp(argv[i], "-?") == 0)
857 else if (strcmp(argv[i], "-P") == 0 && i+1 < argc)
858 portnumber = atoi(argv[++i]);
859 else if (strcmp(argv[i], "-pw") == 0 && i+1 < argc)
860 password = argv[++i];
861 else if (strcmp(argv[i], "-ls") == 0)
863 else if (strcmp(argv[i], "--") == 0)
874 get_dir_list(argc, argv);
881 targetshouldbedirectory = 1;
883 if (colon(argv[argc-1]) != NULL)
884 toremote(argc, argv);
889 if (connection_open) {
892 ssh_scp_recv(&ch, 1);
897 return (errs == 0 ? 0 : 1);