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.
8 * Adaptations to enable connecting a GUI by L. Gunnarsson - Sept 2000
23 /* GUI Adaptation - Sept 2000 */
27 #define PUTTY_DO_GLOBALS
31 #define TIME_POSIX_TO_WIN(t, ft) (*(LONGLONG*)&(ft) = \
32 ((LONGLONG) (t) + (LONGLONG) 11644473600) * (LONGLONG) 10000000)
33 #define TIME_WIN_TO_POSIX(ft, t) ((t) = (unsigned long) \
34 ((*(LONGLONG*)&(ft)) / (LONGLONG) 10000000 - (LONGLONG) 11644473600))
36 /* GUI Adaptation - Sept 2000 */
37 #define WM_APP_BASE 0x8000
38 #define WM_STD_OUT_CHAR ( WM_APP_BASE+400 )
39 #define WM_STD_ERR_CHAR ( WM_APP_BASE+401 )
40 #define WM_STATS_CHAR ( WM_APP_BASE+402 )
41 #define WM_STATS_SIZE ( WM_APP_BASE+403 )
42 #define WM_STATS_PERCENT ( WM_APP_BASE+404 )
43 #define WM_STATS_ELAPSED ( WM_APP_BASE+405 )
44 #define WM_RET_ERR_CNT ( WM_APP_BASE+406 )
45 #define WM_LS_RET_ERR_CNT ( WM_APP_BASE+407 )
47 static int verbose = 0;
48 static int recursive = 0;
49 static int preserve = 0;
50 static int targetshouldbedirectory = 0;
51 static int statistics = 1;
52 static int portnumber = 0;
53 static char *password = NULL;
55 static int connection_open = 0;
56 /* GUI Adaptation - Sept 2000 */
57 #define NAME_STR_MAX 2048
58 static char statname[NAME_STR_MAX+1];
59 static unsigned long statsize = 0;
60 static int statperct = 0;
61 static time_t statelapsed = 0;
62 static int gui_mode = 0;
63 static char *gui_hwnd = NULL;
65 static void source(char *src);
66 static void rsource(char *src);
67 static void sink(char *targ);
68 /* GUI Adaptation - Sept 2000 */
69 static void tell_char(FILE *stream, char c);
70 static void tell_str(FILE *stream, char *str);
71 static void tell_user(FILE *stream, char *fmt, ...);
72 static void send_char_msg(unsigned int msg_id, char c);
73 static void send_str_msg(unsigned int msg_id, char *str);
74 static void gui_update_stats(char *name, unsigned long size, int percentage, time_t elapsed);
77 * These functions are needed to link with other modules, but
78 * (should) never get called.
80 void term_out(void) { abort(); }
81 void begin_session(void) { }
82 void write_clip (void *data, int len) { }
83 void term_deselect(void) { }
85 /* GUI Adaptation - Sept 2000 */
86 void send_msg(HWND h, UINT message, WPARAM wParam)
88 while (!PostMessage( h, message, wParam, 0))
92 void tell_char(FILE *stream, char c)
98 unsigned int msg_id = WM_STD_OUT_CHAR;
99 if (stream = stderr) msg_id = WM_STD_ERR_CHAR;
100 send_msg( (HWND)atoi(gui_hwnd), msg_id, (WPARAM)c );
104 void tell_str(FILE *stream, char *str)
108 for( i = 0; i < strlen(str); ++i )
109 tell_char(stream, str[i]);
112 void tell_user(FILE *stream, char *fmt, ...)
114 char str[0x100]; /* Make the size big enough */
117 vsprintf(str, fmt, ap);
120 tell_str(stream, str);
123 void gui_update_stats(char *name, unsigned long size, int percentage, time_t elapsed)
127 if (strcmp(name,statname) != 0)
129 for( i = 0; i < strlen(name); ++i )
130 send_msg( (HWND)atoi(gui_hwnd), WM_STATS_CHAR, (WPARAM)name[i]);
131 send_msg( (HWND)atoi(gui_hwnd), WM_STATS_CHAR, (WPARAM)'\n' );
132 strcpy(statname,name);
134 if (statsize != size)
136 send_msg( (HWND)atoi(gui_hwnd), WM_STATS_SIZE, (WPARAM)size );
139 if (statelapsed != elapsed)
141 send_msg( (HWND)atoi(gui_hwnd), WM_STATS_ELAPSED, (WPARAM)elapsed );
142 statelapsed = elapsed;
144 if (statperct != percentage)
146 send_msg( (HWND)atoi(gui_hwnd), WM_STATS_PERCENT, (WPARAM)percentage );
147 statperct = percentage;
152 * Print an error message and perform a fatal exit.
154 void fatalbox(char *fmt, ...)
156 char str[0x100]; /* Make the size big enough */
159 strcpy(str, "Fatal:");
160 vsprintf(str+strlen(str), fmt, ap);
163 tell_str(stderr, str);
167 void connection_fatal(char *fmt, ...)
169 char str[0x100]; /* Make the size big enough */
172 strcpy(str, "Fatal:");
173 vsprintf(str+strlen(str), fmt, ap);
176 tell_str(stderr, str);
182 * Print an error message and exit after closing the SSH link.
184 static void bump(char *fmt, ...)
186 char str[0x100]; /* Make the size big enough */
189 strcpy(str, "Fatal:");
190 vsprintf(str+strlen(str), fmt, ap);
193 tell_str(stderr, str);
195 if (connection_open) {
198 ssh_scp_recv(&ch, 1);
203 static int get_password(const char *prompt, char *str, int maxlen)
209 static int tried_once = 0;
214 strncpy(str, password, maxlen);
215 str[maxlen-1] = '\0';
221 /* GUI Adaptation - Sept 2000 */
223 if (maxlen>0) str[0] = '\0';
225 hin = GetStdHandle(STD_INPUT_HANDLE);
226 hout = GetStdHandle(STD_OUTPUT_HANDLE);
227 if (hin == INVALID_HANDLE_VALUE || hout == INVALID_HANDLE_VALUE)
228 bump("Cannot get standard input/output handles");
230 GetConsoleMode(hin, &savemode);
231 SetConsoleMode(hin, (savemode & (~ENABLE_ECHO_INPUT)) |
232 ENABLE_PROCESSED_INPUT | ENABLE_LINE_INPUT);
234 WriteFile(hout, prompt, strlen(prompt), &i, NULL);
235 ReadFile(hin, str, maxlen-1, &i, NULL);
237 SetConsoleMode(hin, savemode);
239 if ((int)i > maxlen) i = maxlen-1; else i = i - 2;
242 WriteFile(hout, "\r\n", 2, &i, NULL);
249 * Open an SSH connection to user@host and execute cmd.
251 static void do_cmd(char *host, char *user, char *cmd)
253 char *err, *realhost;
255 if (host == NULL || host[0] == '\0')
256 bump("Empty host name");
258 /* Try to load settings for this host */
260 if (cfg.host[0] == '\0') {
261 /* No settings for this host; use defaults */
262 strncpy(cfg.host, host, sizeof(cfg.host)-1);
263 cfg.host[sizeof(cfg.host)-1] = '\0';
268 if (user != NULL && user[0] != '\0') {
269 strncpy(cfg.username, user, sizeof(cfg.username)-1);
270 cfg.username[sizeof(cfg.username)-1] = '\0';
271 } else if (cfg.username[0] == '\0') {
272 bump("Empty user name");
275 if (cfg.protocol != PROT_SSH)
279 cfg.port = portnumber;
281 err = ssh_scp_init(cfg.host, cfg.port, cmd, &realhost);
283 bump("ssh_init: %s", err);
284 if (verbose && realhost != NULL)
285 tell_user(stderr, "Connected to %s\n", realhost);
291 * Update statistic information about current file.
293 static void print_stats(char *name, unsigned long size, unsigned long done,
294 time_t start, time_t now)
301 /* GUI Adaptation - Sept 2000 */
303 gui_update_stats(name, size, ((done *100) / size), now-start);
306 ratebs = (float) done / (now - start);
308 ratebs = (float) done;
313 eta = (unsigned long) ((size - done) / ratebs);
314 sprintf(etastr, "%02ld:%02ld:%02ld",
315 eta / 3600, (eta % 3600) / 60, eta % 60);
317 pct = (int) (100.0 * (float) done / size);
319 printf("\r%-25.25s | %10ld kB | %5.1f kB/s | ETA: %8s | %3d%%",
320 name, done / 1024, ratebs / 1024.0,
329 * Find a colon in str and return a pointer to the colon.
330 * This is used to separate hostname from filename.
332 static char * colon(char *str)
334 /* We ignore a leading colon, since the hostname cannot be
335 empty. We also ignore a colon as second character because
336 of filenames like f:myfile.txt. */
337 if (str[0] == '\0' ||
341 while (*str != '\0' &&
353 * Wait for a response from the other side.
354 * Return 0 if ok, -1 if error.
356 static int response(void)
358 char ch, resp, rbuf[2048];
361 if (ssh_scp_recv(&resp, 1) <= 0)
362 bump("Lost connection");
372 case 2: /* fatal error */
374 if (ssh_scp_recv(&ch, 1) <= 0)
375 bump("Protocol error: Lost connection");
377 } while (p < sizeof(rbuf) && ch != '\n');
380 tell_user(stderr, "%s\n", rbuf);
389 * Send an error message to the other side and to the screen.
390 * Increment error counter.
392 static void run_err(const char *fmt, ...)
398 strcpy(str, "\01scp: ");
399 vsprintf(str+strlen(str), fmt, ap);
401 ssh_scp_send(str, strlen(str));
402 tell_user(stderr, "%s",str);
407 * Execute the source part of the SCP protocol.
409 static void source(char *src)
417 unsigned long stat_bytes;
418 time_t stat_starttime, stat_lasttime;
420 attr = GetFileAttributes(src);
421 if (attr == (DWORD)-1) {
422 run_err("%s: No such file or directory", src);
426 if ((attr & FILE_ATTRIBUTE_DIRECTORY) != 0) {
429 * Avoid . and .. directories.
432 p = strrchr(src, '/');
434 p = strrchr(src, '\\');
439 if (!strcmp(p, ".") || !strcmp(p, ".."))
444 run_err("%s: not a regular file", src);
449 if ((last = strrchr(src, '/')) == NULL)
453 if (strrchr(last, '\\') != NULL)
454 last = strrchr(last, '\\') + 1;
455 if (last == src && strchr(src, ':') != NULL)
456 last = strchr(src, ':') + 1;
458 f = CreateFile(src, GENERIC_READ, FILE_SHARE_READ, NULL,
459 OPEN_EXISTING, 0, 0);
460 if (f == INVALID_HANDLE_VALUE) {
461 run_err("%s: Cannot open file", src);
466 FILETIME actime, wrtime;
467 unsigned long mtime, atime;
468 GetFileTime(f, NULL, &actime, &wrtime);
469 TIME_WIN_TO_POSIX(actime, atime);
470 TIME_WIN_TO_POSIX(wrtime, mtime);
471 sprintf(buf, "T%lu 0 %lu 0\n", mtime, atime);
472 ssh_scp_send(buf, strlen(buf));
477 size = GetFileSize(f, NULL);
478 sprintf(buf, "C0644 %lu %s\n", size, last);
480 tell_user(stderr, "Sending file modes: %s", buf);
481 ssh_scp_send(buf, strlen(buf));
487 stat_starttime = time(NULL);
491 for (i = 0; i < size; i += 4096) {
494 if (i + k > size) k = size - i;
495 if (! ReadFile(f, transbuf, k, &j, NULL) || j != k) {
496 if (statistics) printf("\n");
497 bump("%s: Read error", src);
499 ssh_scp_send(transbuf, k);
502 if (time(NULL) != stat_lasttime ||
504 stat_lasttime = time(NULL);
505 print_stats(last, size, stat_bytes,
506 stat_starttime, stat_lasttime);
517 * Recursively send the contents of a directory.
519 static void rsource(char *src)
524 WIN32_FIND_DATA fdat;
527 if ((last = strrchr(src, '/')) == NULL)
531 if (strrchr(last, '\\') != NULL)
532 last = strrchr(last, '\\') + 1;
533 if (last == src && strchr(src, ':') != NULL)
534 last = strchr(src, ':') + 1;
536 /* maybe send filetime */
538 sprintf(buf, "D0755 0 %s\n", last);
540 tell_user(stderr, "Entering directory: %s", buf);
541 ssh_scp_send(buf, strlen(buf));
545 sprintf(buf, "%s/*", src);
546 dir = FindFirstFile(buf, &fdat);
547 ok = (dir != INVALID_HANDLE_VALUE);
549 if (strcmp(fdat.cFileName, ".") == 0 ||
550 strcmp(fdat.cFileName, "..") == 0) {
551 } else if (strlen(src) + 1 + strlen(fdat.cFileName) >=
553 run_err("%s/%s: Name too long", src, fdat.cFileName);
555 sprintf(buf, "%s/%s", src, fdat.cFileName);
558 ok = FindNextFile(dir, &fdat);
563 ssh_scp_send(buf, strlen(buf));
568 * Execute the sink part of the SCP protocol.
570 static void sink(char *targ)
580 unsigned long mtime, atime;
582 unsigned long size, i;
584 unsigned long stat_bytes;
585 time_t stat_starttime, stat_lasttime;
588 attr = GetFileAttributes(targ);
589 if (attr != (DWORD)-1 && (attr & FILE_ATTRIBUTE_DIRECTORY) != 0)
592 if (targetshouldbedirectory && !targisdir)
593 bump("%s: Not a directory", targ);
599 if (ssh_scp_recv(&ch, 1) <= 0)
602 bump("Protocol error: Unexpected newline");
606 if (ssh_scp_recv(&ch, 1) <= 0)
607 bump("Lost connection");
609 } while (i < sizeof(buf) && ch != '\n');
612 case '\01': /* error */
613 tell_user(stderr, "%s\n", buf+1);
616 case '\02': /* fatal error */
622 if (sscanf(buf, "T%ld %*d %ld %*d",
623 &mtime, &atime) == 2) {
628 bump("Protocol error: Illegal time format");
633 bump("Protocol error: Expected control record");
636 if (sscanf(buf+1, "%u %lu %[^\n]", &mode, &size, namebuf) != 3)
637 bump("Protocol error: Illegal file descriptor format");
646 strcpy(namebuf, targ);
648 attr = GetFileAttributes(namebuf);
649 exists = (attr != (DWORD)-1);
652 if (exists && (attr & FILE_ATTRIBUTE_DIRECTORY) == 0) {
653 run_err("%s: Not a directory", namebuf);
657 if (! CreateDirectory(namebuf, NULL)) {
658 run_err("%s: Cannot create directory",
664 /* can we set the timestamp for directories ? */
668 f = CreateFile(namebuf, GENERIC_WRITE, 0, NULL,
669 CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
670 if (f == INVALID_HANDLE_VALUE) {
671 run_err("%s: Cannot create file", namebuf);
679 stat_starttime = time(NULL);
681 if ((stat_name = strrchr(namebuf, '/')) == NULL)
685 if (strrchr(stat_name, '\\') != NULL)
686 stat_name = strrchr(stat_name, '\\') + 1;
689 for (i = 0; i < size; i += 4096) {
692 if (i + k > size) k = size - i;
693 if (ssh_scp_recv(transbuf, k) == 0)
694 bump("Lost connection");
695 if (wrerror) continue;
696 if (! WriteFile(f, transbuf, k, &j, NULL) || j != k) {
699 printf("\r%-25.25s | %50s\n",
701 "Write error.. waiting for end of file");
706 if (time(NULL) > stat_lasttime ||
708 stat_lasttime = time(NULL);
709 print_stats(stat_name, size, stat_bytes,
710 stat_starttime, stat_lasttime);
717 FILETIME actime, wrtime;
718 TIME_POSIX_TO_WIN(atime, actime);
719 TIME_POSIX_TO_WIN(mtime, wrtime);
720 SetFileTime(f, NULL, &actime, &wrtime);
725 run_err("%s: Write error", namebuf);
733 * We will copy local files to a remote server.
735 static void toremote(int argc, char *argv[])
737 char *src, *targ, *host, *user;
743 /* Separate host from filename */
747 bump("targ == NULL in toremote()");
751 /* Substitute "." for emtpy target */
753 /* Separate host and username */
755 host = strrchr(host, '@');
766 /* Find out if the source filespec covers multiple files
767 if so, we should set the targetshouldbedirectory flag */
769 WIN32_FIND_DATA fdat;
770 if (colon(argv[0]) != NULL)
771 bump("%s: Remote to remote not supported", argv[0]);
772 fh = FindFirstFile(argv[0], &fdat);
773 if (fh == INVALID_HANDLE_VALUE)
774 bump("%s: No such file or directory\n", argv[0]);
775 if (FindNextFile(fh, &fdat))
776 targetshouldbedirectory = 1;
780 cmd = smalloc(strlen(targ) + 100);
781 sprintf(cmd, "scp%s%s%s%s -t %s",
782 verbose ? " -v" : "",
783 recursive ? " -r" : "",
784 preserve ? " -p" : "",
785 targetshouldbedirectory ? " -d" : "",
787 do_cmd(host, user, cmd);
792 for (i = 0; i < argc - 1; i++) {
794 WIN32_FIND_DATA fdat;
796 if (colon(src) != NULL) {
797 tell_user(stderr, "%s: Remote to remote not supported\n", src);
801 dir = FindFirstFile(src, &fdat);
802 if (dir == INVALID_HANDLE_VALUE) {
803 run_err("%s: No such file or directory", src);
809 if (strlen(src) + strlen(fdat.cFileName) >=
811 tell_user(stderr, "%s: Name too long", src);
814 strcpy(namebuf, src);
815 if ((last = strrchr(namebuf, '/')) == NULL)
819 if (strrchr(last, '\\') != NULL)
820 last = strrchr(last, '\\') + 1;
821 if (last == namebuf && strrchr(namebuf, ':') != NULL)
822 last = strchr(namebuf, ':') + 1;
823 strcpy(last, fdat.cFileName);
825 } while (FindNextFile(dir, &fdat));
831 * We will copy files from a remote server to the local machine.
833 static void tolocal(int argc, char *argv[])
835 char *src, *targ, *host, *user;
839 bump("More than one remote source not supported");
844 /* Separate host from filename */
848 bump("Local to local copy not supported");
852 /* Substitute "." for empty filename */
854 /* Separate username and hostname */
856 host = strrchr(host, '@');
866 cmd = smalloc(strlen(src) + 100);
867 sprintf(cmd, "scp%s%s%s%s -f %s",
868 verbose ? " -v" : "",
869 recursive ? " -r" : "",
870 preserve ? " -p" : "",
871 targetshouldbedirectory ? " -d" : "",
873 do_cmd(host, user, cmd);
880 * We will issue a list command to get a remote directory.
882 static void get_dir_list(int argc, char *argv[])
884 char *src, *host, *user;
890 /* Separate host from filename */
894 bump("Local to local copy not supported");
898 /* Substitute "." for empty filename */
900 /* Separate username and hostname */
902 host = strrchr(host, '@');
912 cmd = smalloc(4*strlen(src) + 100);
913 strcpy(cmd, "ls -la '");
914 p = cmd + strlen(cmd);
915 for (q = src; *q; q++) {
917 *p++ = '\''; *p++ = '\\'; *p++ = '\''; *p++ = '\'';
925 do_cmd(host, user, cmd);
928 while (ssh_scp_recv(&c, 1) > 0)
929 tell_char(stdout, c);
933 * Initialize the Win$ock driver.
935 static void init_winsock(void)
940 winsock_ver = MAKEWORD(1, 1);
941 if (WSAStartup(winsock_ver, &wsadata))
942 bump("Unable to initialise WinSock");
943 if (LOBYTE(wsadata.wVersion) != 1 ||
944 HIBYTE(wsadata.wVersion) != 1)
945 bump("WinSock version is incompatible with 1.1");
949 * Short description of parameters.
951 static void usage(void)
953 printf("PuTTY Secure Copy client\n");
955 printf("Usage: pscp [options] [user@]host:source target\n");
956 printf(" pscp [options] source [source...] [user@]host:target\n");
957 printf(" pscp [options] -ls user@host:filespec\n");
958 printf("Options:\n");
959 printf(" -p preserve file attributes\n");
960 printf(" -q quiet, don't show statistics\n");
961 printf(" -r copy directories recursively\n");
962 printf(" -v show verbose messages\n");
963 printf(" -P port connect to specified port\n");
964 printf(" -pw passw login with specified password\n");
965 /* GUI Adaptation - Sept 2000 */
966 printf(" -gui hWnd GUI mode with the windows handle for receiving messages\n");
971 * Main program (no, really?)
973 int main(int argc, char *argv[])
978 default_protocol = PROT_TELNET;
981 ssh_get_password = &get_password;
984 for (i = 1; i < argc; i++) {
985 if (argv[i][0] != '-')
987 if (strcmp(argv[i], "-v") == 0)
988 verbose = 1, flags |= FLAG_VERBOSE;
989 else if (strcmp(argv[i], "-r") == 0)
991 else if (strcmp(argv[i], "-p") == 0)
993 else if (strcmp(argv[i], "-q") == 0)
995 else if (strcmp(argv[i], "-h") == 0 ||
996 strcmp(argv[i], "-?") == 0)
998 else if (strcmp(argv[i], "-P") == 0 && i+1 < argc)
999 portnumber = atoi(argv[++i]);
1000 else if (strcmp(argv[i], "-pw") == 0 && i+1 < argc)
1001 password = argv[++i];
1002 else if (strcmp(argv[i], "-gui") == 0 && i+1 < argc) {
1003 gui_hwnd = argv[++i];
1005 } else if (strcmp(argv[i], "-ls") == 0)
1007 else if (strcmp(argv[i], "--") == 0)
1018 get_dir_list(argc, argv);
1025 targetshouldbedirectory = 1;
1027 if (colon(argv[argc-1]) != NULL)
1028 toremote(argc, argv);
1030 tolocal(argc, argv);
1033 if (connection_open) {
1036 ssh_scp_recv(&ch, 1);
1041 /* GUI Adaptation - August 2000 */
1043 unsigned int msg_id = WM_RET_ERR_CNT;
1044 if (list) msg_id = WM_LS_RET_ERR_CNT;
1045 while (!PostMessage( (HWND)atoi(gui_hwnd), msg_id, (WPARAM)errs, 0/*lParam*/ ) )
1048 return (errs == 0 ? 0 : 1);