2 * PLink - a command-line (stdin/stdout) variant of PuTTY.
13 #define PUTTY_DO_GLOBALS /* actually _define_ globals */
18 #define MAX_STDIN_BACKLOG 4096
20 void fatalbox(char *p, ...)
23 fprintf(stderr, "FATAL ERROR: ");
25 vfprintf(stderr, p, ap);
31 void connection_fatal(char *p, ...)
34 fprintf(stderr, "FATAL ERROR: ");
36 vfprintf(stderr, p, ap);
43 static char *password = NULL;
45 void logevent(char *string)
49 void verify_ssh_host_key(char *host, int port, char *keytype,
50 char *keystr, char *fingerprint)
56 static const char absentmsg[] =
57 "The server's host key is not cached in the registry. You\n"
58 "have no guarantee that the server is the computer you\n"
60 "The server's key fingerprint is:\n"
62 "If you trust this host, enter \"y\" to add the key to\n"
63 "PuTTY's cache and carry on connecting.\n"
64 "If you want to carry on connecting just once, without\n"
65 "adding the key to the cache, enter \"n\".\n"
66 "If you do not trust this host, press Return to abandon the\n"
68 "Store key in cache? (y/n) ";
70 static const char wrongmsg[] =
71 "WARNING - POTENTIAL SECURITY BREACH!\n"
72 "The server's host key does not match the one PuTTY has\n"
73 "cached in the registry. This means that either the\n"
74 "server administrator has changed the host key, or you\n"
75 "have actually connected to another computer pretending\n"
77 "The new key fingerprint is:\n"
79 "If you were expecting this change and trust the new key,\n"
80 "enter \"y\" to update PuTTY's cache and continue connecting.\n"
81 "If you want to carry on connecting but without updating\n"
82 "the cache, enter \"n\".\n"
83 "If you want to abandon the connection completely, press\n"
84 "Return to cancel. Pressing Return is the ONLY guaranteed\n"
86 "Update cached key? (y/n, Return cancels connection) ";
88 static const char abandoned[] = "Connection abandoned.\n";
93 * Verify the key against the registry.
95 ret = verify_host_key(host, port, keytype, keystr);
97 if (ret == 0) /* success - key matched OK */
100 if (ret == 2) { /* key was different */
101 fprintf(stderr, wrongmsg, fingerprint);
104 if (ret == 1) { /* key was absent */
105 fprintf(stderr, absentmsg, fingerprint);
109 hin = GetStdHandle(STD_INPUT_HANDLE);
110 GetConsoleMode(hin, &savemode);
111 SetConsoleMode(hin, (savemode | ENABLE_ECHO_INPUT |
112 ENABLE_PROCESSED_INPUT | ENABLE_LINE_INPUT));
113 ReadFile(hin, line, sizeof(line) - 1, &i, NULL);
114 SetConsoleMode(hin, savemode);
116 if (line[0] != '\0' && line[0] != '\r' && line[0] != '\n') {
117 if (line[0] == 'y' || line[0] == 'Y')
118 store_host_key(host, port, keytype, keystr);
120 fprintf(stderr, abandoned);
126 * Ask whether the selected cipher is acceptable (since it was
127 * below the configured 'warn' threshold).
128 * cs: 0 = both ways, 1 = client->server, 2 = server->client
130 void askcipher(char *ciphername, int cs)
135 static const char msg[] =
136 "The first %scipher supported by the server is\n"
137 "%s, which is below the configured warning threshold.\n"
138 "Continue with connection? (y/n) ";
139 static const char abandoned[] = "Connection abandoned.\n";
145 (cs == 1) ? "client-to-server " :
150 hin = GetStdHandle(STD_INPUT_HANDLE);
151 GetConsoleMode(hin, &savemode);
152 SetConsoleMode(hin, (savemode | ENABLE_ECHO_INPUT |
153 ENABLE_PROCESSED_INPUT | ENABLE_LINE_INPUT));
154 ReadFile(hin, line, sizeof(line) - 1, &i, NULL);
155 SetConsoleMode(hin, savemode);
157 if (line[0] == 'y' || line[0] == 'Y') {
160 fprintf(stderr, abandoned);
165 HANDLE inhandle, outhandle, errhandle;
166 DWORD orig_console_mode;
170 int term_ldisc(int mode)
174 void ldisc_update(int echo, int edit)
176 /* Update stdin read mode to reflect changes in line discipline. */
179 mode = ENABLE_PROCESSED_INPUT;
181 mode = mode | ENABLE_ECHO_INPUT;
183 mode = mode & ~ENABLE_ECHO_INPUT;
185 mode = mode | ENABLE_LINE_INPUT;
187 mode = mode & ~ENABLE_LINE_INPUT;
188 SetConsoleMode(inhandle, mode);
191 static int get_line(const char *prompt, char *str, int maxlen, int is_pw)
194 DWORD savemode, newmode, i;
196 if (is_pw && password) {
197 static int tried_once = 0;
202 strncpy(str, password, maxlen);
203 str[maxlen - 1] = '\0';
209 hin = GetStdHandle(STD_INPUT_HANDLE);
210 hout = GetStdHandle(STD_OUTPUT_HANDLE);
211 if (hin == INVALID_HANDLE_VALUE || hout == INVALID_HANDLE_VALUE) {
212 fprintf(stderr, "Cannot get standard input/output handles");
216 GetConsoleMode(hin, &savemode);
217 newmode = savemode | ENABLE_PROCESSED_INPUT | ENABLE_LINE_INPUT;
219 newmode &= ~ENABLE_ECHO_INPUT;
221 newmode |= ENABLE_ECHO_INPUT;
222 SetConsoleMode(hin, newmode);
224 WriteFile(hout, prompt, strlen(prompt), &i, NULL);
225 ReadFile(hin, str, maxlen - 1, &i, NULL);
227 SetConsoleMode(hin, savemode);
229 if ((int) i > maxlen)
236 WriteFile(hout, "\r\n", 2, &i, NULL);
244 HANDLE event, eventback;
247 static DWORD WINAPI stdin_read_thread(void *param)
249 struct input_data *idata = (struct input_data *) param;
252 inhandle = GetStdHandle(STD_INPUT_HANDLE);
254 while (ReadFile(inhandle, idata->buffer, sizeof(idata->buffer),
255 &idata->len, NULL) && idata->len > 0) {
256 SetEvent(idata->event);
257 WaitForSingleObject(idata->eventback, INFINITE);
261 SetEvent(idata->event);
267 DWORD len, lenwritten;
271 HANDLE event, eventback;
275 static DWORD WINAPI stdout_write_thread(void *param)
277 struct output_data *odata = (struct output_data *) param;
278 HANDLE outhandle, errhandle;
280 outhandle = GetStdHandle(STD_OUTPUT_HANDLE);
281 errhandle = GetStdHandle(STD_ERROR_HANDLE);
284 WaitForSingleObject(odata->eventback, INFINITE);
288 WriteFile(odata->is_stderr ? errhandle : outhandle,
289 odata->buffer, odata->len, &odata->lenwritten, NULL);
290 SetEvent(odata->event);
296 bufchain stdout_data, stderr_data;
297 struct output_data odata, edata;
299 void try_output(int is_stderr)
301 struct output_data *data = (is_stderr ? &edata : &odata);
306 bufchain_prefix(is_stderr ? &stderr_data : &stdout_data,
307 &senddata, &sendlen);
308 data->buffer = senddata;
310 SetEvent(data->eventback);
315 int from_backend(int is_stderr, char *data, int len)
317 HANDLE h = (is_stderr ? errhandle : outhandle);
321 bufchain_add(&stderr_data, data, len);
324 bufchain_add(&stdout_data, data, len);
328 osize = bufchain_size(&stdout_data);
329 esize = bufchain_size(&stderr_data);
331 return osize + esize;
335 * Short description of parameters.
337 static void usage(void)
339 printf("PuTTY Link: command-line connection utility\n");
341 printf("Usage: plink [options] [user@]host [command]\n");
342 printf("Options:\n");
343 printf(" -v show verbose messages\n");
344 printf(" -ssh force use of ssh protocol\n");
345 printf(" -P port connect to specified port\n");
346 printf(" -pw passw login with specified password\n");
347 printf(" -m file read remote command(s) from file\n");
351 char *do_select(SOCKET skt, int startup)
355 events = FD_READ | FD_WRITE | FD_OOB | FD_CLOSE | FD_ACCEPT;
359 if (WSAEventSelect(skt, netevent, events) == SOCKET_ERROR) {
360 switch (WSAGetLastError()) {
362 return "Network is down";
364 return "WSAAsyncSelect(): unknown error";
370 int main(int argc, char **argv)
374 WSAEVENT stdinevent, stdoutevent, stderrevent;
376 DWORD in_threadid, out_threadid, err_threadid;
377 struct input_data idata;
385 ssh_get_line = get_line;
388 skcount = sksize = 0;
390 * Initialise port and protocol to sensible defaults. (These
391 * will be overridden by more or less anything.)
393 default_protocol = PROT_SSH;
398 * Process the command line.
400 do_defaults(NULL, &cfg);
401 default_protocol = cfg.protocol;
402 default_port = cfg.port;
405 * Override the default protocol if PLINK_PROTOCOL is set.
407 char *p = getenv("PLINK_PROTOCOL");
410 for (i = 0; backends[i].backend != NULL; i++) {
411 if (!strcmp(backends[i].name, p)) {
412 default_protocol = cfg.protocol = backends[i].protocol;
413 default_port = cfg.port =
414 backends[i].backend->default_port;
423 if (!strcmp(p, "-ssh")) {
424 default_protocol = cfg.protocol = PROT_SSH;
425 default_port = cfg.port = 22;
426 } else if (!strcmp(p, "-telnet")) {
427 default_protocol = cfg.protocol = PROT_TELNET;
428 default_port = cfg.port = 23;
429 } else if (!strcmp(p, "-raw")) {
430 default_protocol = cfg.protocol = PROT_RAW;
431 } else if (!strcmp(p, "-v")) {
432 flags |= FLAG_VERBOSE;
433 } else if (!strcmp(p, "-log")) {
434 logfile = "putty.log";
435 } else if (!strcmp(p, "-pw") && argc > 1) {
436 --argc, password = *++argv;
437 } else if (!strcmp(p, "-l") && argc > 1) {
439 --argc, username = *++argv;
440 strncpy(cfg.username, username, sizeof(cfg.username));
441 cfg.username[sizeof(cfg.username) - 1] = '\0';
442 } else if (!strcmp(p, "-m") && argc > 1) {
443 char *filename, *command;
448 --argc, filename = *++argv;
450 cmdlen = cmdsize = 0;
452 fp = fopen(filename, "r");
454 fprintf(stderr, "plink: unable to open command "
455 "file \"%s\"\n", filename);
463 if (cmdlen >= cmdsize) {
464 cmdsize = cmdlen + 512;
465 command = srealloc(command, cmdsize);
467 command[cmdlen++] = d;
469 cfg.remote_cmd_ptr = command;
470 cfg.remote_cmd_ptr2 = NULL;
471 cfg.nopty = TRUE; /* command => no terminal */
472 } else if (!strcmp(p, "-P") && argc > 1) {
473 --argc, portnumber = atoi(*++argv);
479 * If the hostname starts with "telnet:", set the
480 * protocol to Telnet and process the string as a
483 if (!strncmp(q, "telnet:", 7)) {
487 if (q[0] == '/' && q[1] == '/')
489 cfg.protocol = PROT_TELNET;
491 while (*p && *p != ':' && *p != '/')
500 strncpy(cfg.host, q, sizeof(cfg.host) - 1);
501 cfg.host[sizeof(cfg.host) - 1] = '\0';
505 * Before we process the [user@]host string, we
506 * first check for the presence of a protocol
507 * prefix (a protocol name followed by ",").
512 for (i = 0; backends[i].backend != NULL; i++) {
513 j = strlen(backends[i].name);
515 !memcmp(backends[i].name, p, j)) {
516 default_protocol = cfg.protocol =
517 backends[i].protocol;
519 backends[i].backend->default_port;
527 * Three cases. Either (a) there's a nonzero
528 * length string followed by an @, in which
529 * case that's user and the remainder is host.
530 * Or (b) there's only one string, not counting
531 * a potential initial @, and it exists in the
532 * saved-sessions database. Or (c) only one
533 * string and it _doesn't_ exist in the
538 p++, r = NULL; /* discount initial @ */
544 do_defaults(p, &cfg2);
545 if (cfg2.host[0] == '\0') {
546 /* No settings for this host; use defaults */
547 strncpy(cfg.host, p, sizeof(cfg.host) - 1);
548 cfg.host[sizeof(cfg.host) - 1] = '\0';
549 cfg.port = default_port;
552 cfg.remote_cmd_ptr = cfg.remote_cmd;
556 strncpy(cfg.username, p, sizeof(cfg.username) - 1);
557 cfg.username[sizeof(cfg.username) - 1] = '\0';
558 strncpy(cfg.host, r, sizeof(cfg.host) - 1);
559 cfg.host[sizeof(cfg.host) - 1] = '\0';
560 cfg.port = default_port;
564 int len = sizeof(cfg.remote_cmd) - 1;
565 char *cp = cfg.remote_cmd;
576 strncpy(cp, *++argv, len);
582 cfg.nopty = TRUE; /* command => no terminal */
583 break; /* done with cmdline */
592 if (!*cfg.remote_cmd_ptr)
593 flags |= FLAG_INTERACTIVE;
596 * Select protocol. This is farmed out into a table in a
597 * separate file to enable an ssh-free variant.
602 for (i = 0; backends[i].backend != NULL; i++)
603 if (backends[i].protocol == cfg.protocol) {
604 back = backends[i].backend;
609 "Internal fault: Unsupported protocol found\n");
617 if (portnumber != -1)
618 cfg.port = portnumber;
621 * Initialise WinSock.
623 winsock_ver = MAKEWORD(2, 0);
624 if (WSAStartup(winsock_ver, &wsadata)) {
625 MessageBox(NULL, "Unable to initialise WinSock", "WinSock Error",
626 MB_OK | MB_ICONEXCLAMATION);
629 if (LOBYTE(wsadata.wVersion) != 2 || HIBYTE(wsadata.wVersion) != 0) {
630 MessageBox(NULL, "WinSock version is incompatible with 2.0",
631 "WinSock Error", MB_OK | MB_ICONEXCLAMATION);
638 * Start up the connection.
640 netevent = CreateEvent(NULL, FALSE, FALSE, NULL);
645 error = back->init(cfg.host, cfg.port, &realhost);
647 fprintf(stderr, "Unable to open connection:\n%s", error);
654 stdinevent = CreateEvent(NULL, FALSE, FALSE, NULL);
655 stdoutevent = CreateEvent(NULL, FALSE, FALSE, NULL);
656 stderrevent = CreateEvent(NULL, FALSE, FALSE, NULL);
658 inhandle = GetStdHandle(STD_INPUT_HANDLE);
659 outhandle = GetStdHandle(STD_OUTPUT_HANDLE);
660 errhandle = GetStdHandle(STD_ERROR_HANDLE);
661 GetConsoleMode(inhandle, &orig_console_mode);
662 SetConsoleMode(inhandle, ENABLE_PROCESSED_INPUT);
665 * Turn off ECHO and LINE input modes. We don't care if this
666 * call fails, because we know we aren't necessarily running in
669 handles[0] = netevent;
670 handles[1] = stdinevent;
671 handles[2] = stdoutevent;
672 handles[3] = stderrevent;
676 * Create spare threads to write to stdout and stderr, so we
677 * can arrange asynchronous writes.
679 odata.event = stdoutevent;
680 odata.eventback = CreateEvent(NULL, FALSE, FALSE, NULL);
682 odata.busy = odata.done = 0;
683 if (!CreateThread(NULL, 0, stdout_write_thread,
684 &odata, 0, &out_threadid)) {
685 fprintf(stderr, "Unable to create output thread\n");
688 edata.event = stderrevent;
689 edata.eventback = CreateEvent(NULL, FALSE, FALSE, NULL);
691 edata.busy = edata.done = 0;
692 if (!CreateThread(NULL, 0, stdout_write_thread,
693 &edata, 0, &err_threadid)) {
694 fprintf(stderr, "Unable to create error output thread\n");
701 if (!sending && back->sendok()) {
703 * Create a separate thread to read from stdin. This is
704 * a total pain, but I can't find another way to do it:
706 * - an overlapped ReadFile or ReadFileEx just doesn't
707 * happen; we get failure from ReadFileEx, and
708 * ReadFile blocks despite being given an OVERLAPPED
709 * structure. Perhaps we can't do overlapped reads
710 * on consoles. WHY THE HELL NOT?
712 * - WaitForMultipleObjects(netevent, console) doesn't
713 * work, because it signals the console when
714 * _anything_ happens, including mouse motions and
715 * other things that don't cause data to be readable
716 * - so we're back to ReadFile blocking.
718 idata.event = stdinevent;
719 idata.eventback = CreateEvent(NULL, FALSE, FALSE, NULL);
720 if (!CreateThread(NULL, 0, stdin_read_thread,
721 &idata, 0, &in_threadid)) {
722 fprintf(stderr, "Unable to create input thread\n");
728 n = WaitForMultipleObjects(4, handles, FALSE, INFINITE);
730 WSANETWORKEVENTS things;
732 extern SOCKET first_socket(int *), next_socket(int *);
733 extern int select_result(WPARAM, LPARAM);
737 * We must not call select_result() for any socket
738 * until we have finished enumerating within the tree.
739 * This is because select_result() may close the socket
740 * and modify the tree.
742 /* Count the active sockets. */
744 for (socket = first_socket(&socketstate);
745 socket != INVALID_SOCKET;
746 socket = next_socket(&socketstate)) i++;
748 /* Expand the buffer if necessary. */
751 sklist = srealloc(sklist, sksize * sizeof(*sklist));
754 /* Retrieve the sockets into sklist. */
756 for (socket = first_socket(&socketstate);
757 socket != INVALID_SOCKET;
758 socket = next_socket(&socketstate)) {
759 sklist[skcount++] = socket;
762 /* Now we're done enumerating; go through the list. */
763 for (i = 0; i < skcount; i++) {
766 wp = (WPARAM) socket;
767 if (!WSAEnumNetworkEvents(socket, NULL, &things)) {
768 noise_ultralight(socket);
769 noise_ultralight(things.lNetworkEvents);
770 if (things.lNetworkEvents & FD_READ)
771 connopen &= select_result(wp, (LPARAM) FD_READ);
772 if (things.lNetworkEvents & FD_CLOSE)
773 connopen &= select_result(wp, (LPARAM) FD_CLOSE);
774 if (things.lNetworkEvents & FD_OOB)
775 connopen &= select_result(wp, (LPARAM) FD_OOB);
776 if (things.lNetworkEvents & FD_WRITE)
777 connopen &= select_result(wp, (LPARAM) FD_WRITE);
778 if (things.lNetworkEvents & FD_ACCEPT)
779 connopen &= select_result(wp, (LPARAM) FD_ACCEPT);
785 noise_ultralight(idata.len);
787 back->send(idata.buffer, idata.len);
789 back->special(TS_EOF);
793 if (!odata.writeret) {
794 fprintf(stderr, "Unable to write to standard output\n");
797 bufchain_consume(&stdout_data, odata.lenwritten);
798 if (bufchain_size(&stdout_data) > 0)
800 back->unthrottle(bufchain_size(&stdout_data) +
801 bufchain_size(&stderr_data));
804 if (!edata.writeret) {
805 fprintf(stderr, "Unable to write to standard output\n");
808 bufchain_consume(&stderr_data, edata.lenwritten);
809 if (bufchain_size(&stderr_data) > 0)
811 back->unthrottle(bufchain_size(&stdout_data) +
812 bufchain_size(&stderr_data));
814 if (!reading && back->sendbuffer() < MAX_STDIN_BACKLOG) {
815 SetEvent(idata.eventback);
818 if (!connopen || back->socket() == NULL)
819 break; /* we closed the connection */