2 * PLink - a command-line (stdin/stdout) variant of PuTTY.
14 #define PUTTY_DO_GLOBALS /* actually _define_ globals */
19 #define MAX_STDIN_BACKLOG 4096
21 void fatalbox(char *p, ...)
24 fprintf(stderr, "FATAL ERROR: ");
26 vfprintf(stderr, p, ap);
32 void modalfatalbox(char *p, ...)
35 fprintf(stderr, "FATAL ERROR: ");
37 vfprintf(stderr, p, ap);
43 void connection_fatal(void *frontend, char *p, ...)
46 fprintf(stderr, "FATAL ERROR: ");
48 vfprintf(stderr, p, ap);
54 void cmdline_error(char *p, ...)
57 fprintf(stderr, "plink: ");
59 vfprintf(stderr, p, ap);
65 static char *password = NULL;
67 HANDLE inhandle, outhandle, errhandle;
68 DWORD orig_console_mode;
73 static void *backhandle;
75 int term_ldisc(Terminal *term, int mode)
79 void ldisc_update(void *frontend, int echo, int edit)
81 /* Update stdin read mode to reflect changes in line discipline. */
84 mode = ENABLE_PROCESSED_INPUT;
86 mode = mode | ENABLE_ECHO_INPUT;
88 mode = mode & ~ENABLE_ECHO_INPUT;
90 mode = mode | ENABLE_LINE_INPUT;
92 mode = mode & ~ENABLE_LINE_INPUT;
93 SetConsoleMode(inhandle, mode);
99 HANDLE event, eventback;
102 static DWORD WINAPI stdin_read_thread(void *param)
104 struct input_data *idata = (struct input_data *) param;
107 inhandle = GetStdHandle(STD_INPUT_HANDLE);
109 while (ReadFile(inhandle, idata->buffer, sizeof(idata->buffer),
110 &idata->len, NULL) && idata->len > 0) {
111 SetEvent(idata->event);
112 WaitForSingleObject(idata->eventback, INFINITE);
116 SetEvent(idata->event);
122 DWORD len, lenwritten;
126 HANDLE event, eventback;
130 static DWORD WINAPI stdout_write_thread(void *param)
132 struct output_data *odata = (struct output_data *) param;
133 HANDLE outhandle, errhandle;
135 outhandle = GetStdHandle(STD_OUTPUT_HANDLE);
136 errhandle = GetStdHandle(STD_ERROR_HANDLE);
139 WaitForSingleObject(odata->eventback, INFINITE);
143 WriteFile(odata->is_stderr ? errhandle : outhandle,
144 odata->buffer, odata->len, &odata->lenwritten, NULL);
145 SetEvent(odata->event);
151 bufchain stdout_data, stderr_data;
152 struct output_data odata, edata;
154 void try_output(int is_stderr)
156 struct output_data *data = (is_stderr ? &edata : &odata);
161 bufchain_prefix(is_stderr ? &stderr_data : &stdout_data,
162 &senddata, &sendlen);
163 data->buffer = senddata;
165 SetEvent(data->eventback);
170 int from_backend(void *frontend_handle, int is_stderr, char *data, int len)
172 HANDLE h = (is_stderr ? errhandle : outhandle);
178 bufchain_add(&stderr_data, data, len);
181 bufchain_add(&stdout_data, data, len);
185 osize = bufchain_size(&stdout_data);
186 esize = bufchain_size(&stderr_data);
188 return osize + esize;
192 * Short description of parameters.
194 static void usage(void)
196 printf("PuTTY Link: command-line connection utility\n");
198 printf("Usage: plink [options] [user@]host [command]\n");
199 printf(" (\"host\" can also be a PuTTY saved session name)\n");
200 printf("Options:\n");
201 printf(" -v show verbose messages\n");
202 printf(" -load sessname Load settings from saved session\n");
203 printf(" -ssh -telnet -rlogin -raw\n");
204 printf(" force use of a particular protocol (default SSH)\n");
205 printf(" -P port connect to specified port\n");
206 printf(" -l user connect with specified username\n");
207 printf(" -m file read remote command(s) from file\n");
208 printf(" -batch disable all interactive prompts\n");
209 printf("The following options only apply to SSH connections:\n");
210 printf(" -pw passw login with specified password\n");
211 printf(" -L listen-port:host:port Forward local port to "
213 printf(" -R listen-port:host:port Forward remote port to"
215 printf(" -X -x enable / disable X11 forwarding\n");
216 printf(" -A -a enable / disable agent forwarding\n");
217 printf(" -t -T enable / disable pty allocation\n");
218 printf(" -1 -2 force use of particular protocol version\n");
219 printf(" -C enable compression\n");
220 printf(" -i key private key file for authentication\n");
224 char *do_select(SOCKET skt, int startup)
228 events = (FD_CONNECT | FD_READ | FD_WRITE |
229 FD_OOB | FD_CLOSE | FD_ACCEPT);
233 if (WSAEventSelect(skt, netevent, events) == SOCKET_ERROR) {
234 switch (WSAGetLastError()) {
236 return "Network is down";
238 return "WSAAsyncSelect(): unknown error";
244 int main(int argc, char **argv)
248 WSAEVENT stdinevent, stdoutevent, stderrevent;
250 DWORD in_threadid, out_threadid, err_threadid;
251 struct input_data idata;
260 ssh_get_line = console_get_line;
263 skcount = sksize = 0;
265 * Initialise port and protocol to sensible defaults. (These
266 * will be overridden by more or less anything.)
268 default_protocol = PROT_SSH;
273 * Process the command line.
275 do_defaults(NULL, &cfg);
276 default_protocol = cfg.protocol;
277 default_port = cfg.port;
280 * Override the default protocol if PLINK_PROTOCOL is set.
282 char *p = getenv("PLINK_PROTOCOL");
285 for (i = 0; backends[i].backend != NULL; i++) {
286 if (!strcmp(backends[i].name, p)) {
287 default_protocol = cfg.protocol = backends[i].protocol;
288 default_port = cfg.port =
289 backends[i].backend->default_port;
298 int ret = cmdline_process_param(p, (argc > 1 ? argv[1] : NULL), 1);
301 "plink: option \"%s\" requires an argument\n", p);
302 } else if (ret == 2) {
304 } else if (ret == 1) {
306 } else if (!strcmp(p, "-batch")) {
307 console_batch_mode = 1;
313 * If the hostname starts with "telnet:", set the
314 * protocol to Telnet and process the string as a
317 if (!strncmp(q, "telnet:", 7)) {
321 if (q[0] == '/' && q[1] == '/')
323 cfg.protocol = PROT_TELNET;
325 while (*p && *p != ':' && *p != '/')
334 strncpy(cfg.host, q, sizeof(cfg.host) - 1);
335 cfg.host[sizeof(cfg.host) - 1] = '\0';
339 * Before we process the [user@]host string, we
340 * first check for the presence of a protocol
341 * prefix (a protocol name followed by ",").
346 for (i = 0; backends[i].backend != NULL; i++) {
347 j = strlen(backends[i].name);
349 !memcmp(backends[i].name, p, j)) {
350 default_protocol = cfg.protocol =
351 backends[i].protocol;
353 backends[i].backend->default_port;
361 * Three cases. Either (a) there's a nonzero
362 * length string followed by an @, in which
363 * case that's user and the remainder is host.
364 * Or (b) there's only one string, not counting
365 * a potential initial @, and it exists in the
366 * saved-sessions database. Or (c) only one
367 * string and it _doesn't_ exist in the
372 p++, r = NULL; /* discount initial @ */
378 do_defaults(p, &cfg2);
379 if (cfg2.host[0] == '\0') {
380 /* No settings for this host; use defaults */
381 strncpy(cfg.host, p, sizeof(cfg.host) - 1);
382 cfg.host[sizeof(cfg.host) - 1] = '\0';
383 cfg.port = default_port;
386 cfg.remote_cmd_ptr = cfg.remote_cmd;
390 strncpy(cfg.username, p, sizeof(cfg.username) - 1);
391 cfg.username[sizeof(cfg.username) - 1] = '\0';
392 strncpy(cfg.host, r, sizeof(cfg.host) - 1);
393 cfg.host[sizeof(cfg.host) - 1] = '\0';
394 cfg.port = default_port;
400 cmdlen = cmdsize = 0;
405 if (cmdlen >= cmdsize) {
406 cmdsize = cmdlen + 512;
407 command = srealloc(command, cmdsize);
409 command[cmdlen++]=*p++;
411 if (cmdlen >= cmdsize) {
412 cmdsize = cmdlen + 512;
413 command = srealloc(command, cmdsize);
415 command[cmdlen++]=' '; /* always add trailing space */
416 if (--argc) p = *++argv;
418 if (cmdlen) command[--cmdlen]='\0';
419 /* change trailing blank to NUL */
420 cfg.remote_cmd_ptr = command;
421 cfg.remote_cmd_ptr2 = NULL;
422 cfg.nopty = TRUE; /* command => no terminal */
424 break; /* done with cmdline */
434 * Trim leading whitespace off the hostname if it's there.
437 int space = strspn(cfg.host, " \t");
438 memmove(cfg.host, cfg.host+space, 1+strlen(cfg.host)-space);
441 /* See if host is of the form user@host */
442 if (cfg.host[0] != '\0') {
443 char *atsign = strchr(cfg.host, '@');
444 /* Make sure we're not overflowing the user field */
446 if (atsign - cfg.host < sizeof cfg.username) {
447 strncpy(cfg.username, cfg.host, atsign - cfg.host);
448 cfg.username[atsign - cfg.host] = '\0';
450 memmove(cfg.host, atsign + 1, 1 + strlen(atsign + 1));
455 * Perform command-line overrides on session configuration.
460 * Trim a colon suffix off the hostname if it's there.
462 cfg.host[strcspn(cfg.host, ":")] = '\0';
465 * Remove any remaining whitespace from the hostname.
469 while (cfg.host[p2] != '\0') {
470 if (cfg.host[p2] != ' ' && cfg.host[p2] != '\t') {
471 cfg.host[p1] = cfg.host[p2];
479 if (!*cfg.remote_cmd_ptr)
480 flags |= FLAG_INTERACTIVE;
483 * Select protocol. This is farmed out into a table in a
484 * separate file to enable an ssh-free variant.
489 for (i = 0; backends[i].backend != NULL; i++)
490 if (backends[i].protocol == cfg.protocol) {
491 back = backends[i].backend;
496 "Internal fault: Unsupported protocol found\n");
504 if (portnumber != -1)
505 cfg.port = portnumber;
508 * Initialise WinSock.
510 winsock_ver = MAKEWORD(2, 0);
511 if (WSAStartup(winsock_ver, &wsadata)) {
512 MessageBox(NULL, "Unable to initialise WinSock", "WinSock Error",
513 MB_OK | MB_ICONEXCLAMATION);
516 if (LOBYTE(wsadata.wVersion) != 2 || HIBYTE(wsadata.wVersion) != 0) {
517 MessageBox(NULL, "WinSock version is incompatible with 2.0",
518 "WinSock Error", MB_OK | MB_ICONEXCLAMATION);
525 * Start up the connection.
527 netevent = CreateEvent(NULL, FALSE, FALSE, NULL);
531 /* nodelay is only useful if stdin is a character device (console) */
532 int nodelay = cfg.tcp_nodelay &&
533 (GetFileType(GetStdHandle(STD_INPUT_HANDLE)) == FILE_TYPE_CHAR);
535 error = back->init(NULL, &backhandle, cfg.host, cfg.port,
538 fprintf(stderr, "Unable to open connection:\n%s", error);
541 logctx = log_init(NULL);
542 back->provide_logctx(backhandle, logctx);
547 stdinevent = CreateEvent(NULL, FALSE, FALSE, NULL);
548 stdoutevent = CreateEvent(NULL, FALSE, FALSE, NULL);
549 stderrevent = CreateEvent(NULL, FALSE, FALSE, NULL);
551 inhandle = GetStdHandle(STD_INPUT_HANDLE);
552 outhandle = GetStdHandle(STD_OUTPUT_HANDLE);
553 errhandle = GetStdHandle(STD_ERROR_HANDLE);
554 GetConsoleMode(inhandle, &orig_console_mode);
555 SetConsoleMode(inhandle, ENABLE_PROCESSED_INPUT);
558 * Turn off ECHO and LINE input modes. We don't care if this
559 * call fails, because we know we aren't necessarily running in
562 handles[0] = netevent;
563 handles[1] = stdinevent;
564 handles[2] = stdoutevent;
565 handles[3] = stderrevent;
569 * Create spare threads to write to stdout and stderr, so we
570 * can arrange asynchronous writes.
572 odata.event = stdoutevent;
573 odata.eventback = CreateEvent(NULL, FALSE, FALSE, NULL);
575 odata.busy = odata.done = 0;
576 if (!CreateThread(NULL, 0, stdout_write_thread,
577 &odata, 0, &out_threadid)) {
578 fprintf(stderr, "Unable to create output thread\n");
581 edata.event = stderrevent;
582 edata.eventback = CreateEvent(NULL, FALSE, FALSE, NULL);
584 edata.busy = edata.done = 0;
585 if (!CreateThread(NULL, 0, stdout_write_thread,
586 &edata, 0, &err_threadid)) {
587 fprintf(stderr, "Unable to create error output thread\n");
594 if (!sending && back->sendok(backhandle)) {
596 * Create a separate thread to read from stdin. This is
597 * a total pain, but I can't find another way to do it:
599 * - an overlapped ReadFile or ReadFileEx just doesn't
600 * happen; we get failure from ReadFileEx, and
601 * ReadFile blocks despite being given an OVERLAPPED
602 * structure. Perhaps we can't do overlapped reads
603 * on consoles. WHY THE HELL NOT?
605 * - WaitForMultipleObjects(netevent, console) doesn't
606 * work, because it signals the console when
607 * _anything_ happens, including mouse motions and
608 * other things that don't cause data to be readable
609 * - so we're back to ReadFile blocking.
611 idata.event = stdinevent;
612 idata.eventback = CreateEvent(NULL, FALSE, FALSE, NULL);
613 if (!CreateThread(NULL, 0, stdin_read_thread,
614 &idata, 0, &in_threadid)) {
615 fprintf(stderr, "Unable to create input thread\n");
621 n = WaitForMultipleObjects(4, handles, FALSE, INFINITE);
623 WSANETWORKEVENTS things;
625 extern SOCKET first_socket(int *), next_socket(int *);
626 extern int select_result(WPARAM, LPARAM);
630 * We must not call select_result() for any socket
631 * until we have finished enumerating within the tree.
632 * This is because select_result() may close the socket
633 * and modify the tree.
635 /* Count the active sockets. */
637 for (socket = first_socket(&socketstate);
638 socket != INVALID_SOCKET;
639 socket = next_socket(&socketstate)) i++;
641 /* Expand the buffer if necessary. */
644 sklist = srealloc(sklist, sksize * sizeof(*sklist));
647 /* Retrieve the sockets into sklist. */
649 for (socket = first_socket(&socketstate);
650 socket != INVALID_SOCKET;
651 socket = next_socket(&socketstate)) {
652 sklist[skcount++] = socket;
655 /* Now we're done enumerating; go through the list. */
656 for (i = 0; i < skcount; i++) {
659 wp = (WPARAM) socket;
660 if (!WSAEnumNetworkEvents(socket, NULL, &things)) {
661 static const struct { int bit, mask; } eventtypes[] = {
662 {FD_CONNECT_BIT, FD_CONNECT},
663 {FD_READ_BIT, FD_READ},
664 {FD_CLOSE_BIT, FD_CLOSE},
665 {FD_OOB_BIT, FD_OOB},
666 {FD_WRITE_BIT, FD_WRITE},
667 {FD_ACCEPT_BIT, FD_ACCEPT},
671 noise_ultralight(socket);
672 noise_ultralight(things.lNetworkEvents);
674 for (e = 0; e < lenof(eventtypes); e++)
675 if (things.lNetworkEvents & eventtypes[e].mask) {
677 int err = things.iErrorCode[eventtypes[e].bit];
678 lp = WSAMAKESELECTREPLY(eventtypes[e].mask, err);
679 connopen &= select_result(wp, lp);
685 noise_ultralight(idata.len);
686 if (connopen && back->socket(backhandle) != NULL) {
688 back->send(backhandle, idata.buffer, idata.len);
690 back->special(backhandle, TS_EOF);
695 if (!odata.writeret) {
696 fprintf(stderr, "Unable to write to standard output\n");
699 bufchain_consume(&stdout_data, odata.lenwritten);
700 if (bufchain_size(&stdout_data) > 0)
702 if (connopen && back->socket(backhandle) != NULL) {
703 back->unthrottle(backhandle, bufchain_size(&stdout_data) +
704 bufchain_size(&stderr_data));
708 if (!edata.writeret) {
709 fprintf(stderr, "Unable to write to standard output\n");
712 bufchain_consume(&stderr_data, edata.lenwritten);
713 if (bufchain_size(&stderr_data) > 0)
715 if (connopen && back->socket(backhandle) != NULL) {
716 back->unthrottle(backhandle, bufchain_size(&stdout_data) +
717 bufchain_size(&stderr_data));
720 if (!reading && back->sendbuffer(backhandle) < MAX_STDIN_BACKLOG) {
721 SetEvent(idata.eventback);
724 if ((!connopen || back->socket(backhandle) == NULL) &&
725 bufchain_size(&stdout_data) == 0 &&
726 bufchain_size(&stderr_data) == 0)
727 break; /* we closed the connection */
730 exitcode = back->exitcode(backhandle);
732 fprintf(stderr, "Remote process exit code unavailable\n");
733 exitcode = 1; /* this is an error condition */