2 * PLink - a command-line (stdin/stdout) variant of PuTTY.
14 #define PUTTY_DO_GLOBALS /* actually _define_ globals */
19 #define WM_AGENT_CALLBACK (WM_XUSER + 4)
21 #define MAX_STDIN_BACKLOG 4096
23 struct agent_callback {
24 void (*callback)(void *, void *, int);
30 void fatalbox(char *p, ...)
33 fprintf(stderr, "FATAL ERROR: ");
35 vfprintf(stderr, p, ap);
41 void modalfatalbox(char *p, ...)
44 fprintf(stderr, "FATAL ERROR: ");
46 vfprintf(stderr, p, ap);
52 void connection_fatal(void *frontend, char *p, ...)
55 fprintf(stderr, "FATAL ERROR: ");
57 vfprintf(stderr, p, ap);
63 void cmdline_error(char *p, ...)
66 fprintf(stderr, "plink: ");
68 vfprintf(stderr, p, ap);
74 HANDLE inhandle, outhandle, errhandle;
75 DWORD orig_console_mode;
80 static void *backhandle;
83 int term_ldisc(Terminal *term, int mode)
87 void ldisc_update(void *frontend, int echo, int edit)
89 /* Update stdin read mode to reflect changes in line discipline. */
92 mode = ENABLE_PROCESSED_INPUT;
94 mode = mode | ENABLE_ECHO_INPUT;
96 mode = mode & ~ENABLE_ECHO_INPUT;
98 mode = mode | ENABLE_LINE_INPUT;
100 mode = mode & ~ENABLE_LINE_INPUT;
101 SetConsoleMode(inhandle, mode);
107 HANDLE event, eventback;
110 static DWORD WINAPI stdin_read_thread(void *param)
112 struct input_data *idata = (struct input_data *) param;
115 inhandle = GetStdHandle(STD_INPUT_HANDLE);
117 while (ReadFile(inhandle, idata->buffer, sizeof(idata->buffer),
118 &idata->len, NULL) && idata->len > 0) {
119 SetEvent(idata->event);
120 WaitForSingleObject(idata->eventback, INFINITE);
124 SetEvent(idata->event);
130 DWORD len, lenwritten;
134 HANDLE event, eventback;
138 static DWORD WINAPI stdout_write_thread(void *param)
140 struct output_data *odata = (struct output_data *) param;
141 HANDLE outhandle, errhandle;
143 outhandle = GetStdHandle(STD_OUTPUT_HANDLE);
144 errhandle = GetStdHandle(STD_ERROR_HANDLE);
147 WaitForSingleObject(odata->eventback, INFINITE);
151 WriteFile(odata->is_stderr ? errhandle : outhandle,
152 odata->buffer, odata->len, &odata->lenwritten, NULL);
153 SetEvent(odata->event);
159 bufchain stdout_data, stderr_data;
160 struct output_data odata, edata;
162 void try_output(int is_stderr)
164 struct output_data *data = (is_stderr ? &edata : &odata);
169 bufchain_prefix(is_stderr ? &stderr_data : &stdout_data,
170 &senddata, &sendlen);
171 data->buffer = senddata;
173 SetEvent(data->eventback);
178 int from_backend(void *frontend_handle, int is_stderr,
179 const char *data, int len)
184 bufchain_add(&stderr_data, data, len);
187 bufchain_add(&stdout_data, data, len);
191 osize = bufchain_size(&stdout_data);
192 esize = bufchain_size(&stderr_data);
194 return osize + esize;
197 static DWORD main_thread_id;
199 void agent_schedule_callback(void (*callback)(void *, void *, int),
200 void *callback_ctx, void *data, int len)
202 struct agent_callback *c = snew(struct agent_callback);
203 c->callback = callback;
204 c->callback_ctx = callback_ctx;
207 PostThreadMessage(main_thread_id, WM_AGENT_CALLBACK, 0, (LPARAM)c);
211 * Short description of parameters.
213 static void usage(void)
215 printf("PuTTY Link: command-line connection utility\n");
217 printf("Usage: plink [options] [user@]host [command]\n");
218 printf(" (\"host\" can also be a PuTTY saved session name)\n");
219 printf("Options:\n");
220 printf(" -v show verbose messages\n");
221 printf(" -load sessname Load settings from saved session\n");
222 printf(" -ssh -telnet -rlogin -raw\n");
223 printf(" force use of a particular protocol (default SSH)\n");
224 printf(" -P port connect to specified port\n");
225 printf(" -l user connect with specified username\n");
226 printf(" -m file read remote command(s) from file\n");
227 printf(" -batch disable all interactive prompts\n");
228 printf("The following options only apply to SSH connections:\n");
229 printf(" -pw passw login with specified password\n");
230 printf(" -D listen-port Dynamic SOCKS-based port forwarding\n");
231 printf(" -L listen-port:host:port Forward local port to "
233 printf(" -R listen-port:host:port Forward remote port to"
235 printf(" -X -x enable / disable X11 forwarding\n");
236 printf(" -A -a enable / disable agent forwarding\n");
237 printf(" -t -T enable / disable pty allocation\n");
238 printf(" -1 -2 force use of particular protocol version\n");
239 printf(" -C enable compression\n");
240 printf(" -i key private key file for authentication\n");
241 printf(" -s remote command is an SSH subsystem (SSH-2 only)\n");
245 char *do_select(SOCKET skt, int startup)
249 events = (FD_CONNECT | FD_READ | FD_WRITE |
250 FD_OOB | FD_CLOSE | FD_ACCEPT);
254 if (WSAEventSelect(skt, netevent, events) == SOCKET_ERROR) {
255 switch (WSAGetLastError()) {
257 return "Network is down";
259 return "WSAAsyncSelect(): unknown error";
265 int main(int argc, char **argv)
269 WSAEVENT stdinevent, stdoutevent, stderrevent;
271 DWORD in_threadid, out_threadid, err_threadid;
272 struct input_data idata;
281 int use_subsystem = 0;
283 ssh_get_line = console_get_line;
286 skcount = sksize = 0;
288 * Initialise port and protocol to sensible defaults. (These
289 * will be overridden by more or less anything.)
291 default_protocol = PROT_SSH;
296 * Process the command line.
298 do_defaults(NULL, &cfg);
299 default_protocol = cfg.protocol;
300 default_port = cfg.port;
304 * Override the default protocol if PLINK_PROTOCOL is set.
306 char *p = getenv("PLINK_PROTOCOL");
309 for (i = 0; backends[i].backend != NULL; i++) {
310 if (!strcmp(backends[i].name, p)) {
311 default_protocol = cfg.protocol = backends[i].protocol;
312 default_port = cfg.port =
313 backends[i].backend->default_port;
322 int ret = cmdline_process_param(p, (argc > 1 ? argv[1] : NULL),
326 "plink: option \"%s\" requires an argument\n", p);
328 } else if (ret == 2) {
330 } else if (ret == 1) {
332 } else if (!strcmp(p, "-batch")) {
333 console_batch_mode = 1;
334 } else if (!strcmp(p, "-s")) {
335 /* Save status to write to cfg later. */
338 fprintf(stderr, "plink: unknown option \"%s\"\n", p);
345 * If the hostname starts with "telnet:", set the
346 * protocol to Telnet and process the string as a
349 if (!strncmp(q, "telnet:", 7)) {
353 if (q[0] == '/' && q[1] == '/')
355 cfg.protocol = PROT_TELNET;
357 while (*p && *p != ':' && *p != '/')
366 strncpy(cfg.host, q, sizeof(cfg.host) - 1);
367 cfg.host[sizeof(cfg.host) - 1] = '\0';
371 * Before we process the [user@]host string, we
372 * first check for the presence of a protocol
373 * prefix (a protocol name followed by ",").
378 for (i = 0; backends[i].backend != NULL; i++) {
379 j = strlen(backends[i].name);
381 !memcmp(backends[i].name, p, j)) {
382 default_protocol = cfg.protocol =
383 backends[i].protocol;
385 backends[i].backend->default_port;
393 * Three cases. Either (a) there's a nonzero
394 * length string followed by an @, in which
395 * case that's user and the remainder is host.
396 * Or (b) there's only one string, not counting
397 * a potential initial @, and it exists in the
398 * saved-sessions database. Or (c) only one
399 * string and it _doesn't_ exist in the
404 p++, r = NULL; /* discount initial @ */
410 do_defaults(p, &cfg2);
411 if (cfg2.host[0] == '\0') {
412 /* No settings for this host; use defaults */
413 strncpy(cfg.host, p, sizeof(cfg.host) - 1);
414 cfg.host[sizeof(cfg.host) - 1] = '\0';
415 cfg.port = default_port;
418 cfg.remote_cmd_ptr = cfg.remote_cmd;
422 strncpy(cfg.username, p, sizeof(cfg.username) - 1);
423 cfg.username[sizeof(cfg.username) - 1] = '\0';
424 strncpy(cfg.host, r, sizeof(cfg.host) - 1);
425 cfg.host[sizeof(cfg.host) - 1] = '\0';
426 cfg.port = default_port;
432 cmdlen = cmdsize = 0;
437 if (cmdlen >= cmdsize) {
438 cmdsize = cmdlen + 512;
439 command = sresize(command, cmdsize, char);
441 command[cmdlen++]=*p++;
443 if (cmdlen >= cmdsize) {
444 cmdsize = cmdlen + 512;
445 command = sresize(command, cmdsize, char);
447 command[cmdlen++]=' '; /* always add trailing space */
448 if (--argc) p = *++argv;
450 if (cmdlen) command[--cmdlen]='\0';
451 /* change trailing blank to NUL */
452 cfg.remote_cmd_ptr = command;
453 cfg.remote_cmd_ptr2 = NULL;
454 cfg.nopty = TRUE; /* command => no terminal */
456 break; /* done with cmdline */
469 * Trim leading whitespace off the hostname if it's there.
472 int space = strspn(cfg.host, " \t");
473 memmove(cfg.host, cfg.host+space, 1+strlen(cfg.host)-space);
476 /* See if host is of the form user@host */
477 if (cfg.host[0] != '\0') {
478 char *atsign = strchr(cfg.host, '@');
479 /* Make sure we're not overflowing the user field */
481 if (atsign - cfg.host < sizeof cfg.username) {
482 strncpy(cfg.username, cfg.host, atsign - cfg.host);
483 cfg.username[atsign - cfg.host] = '\0';
485 memmove(cfg.host, atsign + 1, 1 + strlen(atsign + 1));
490 * Perform command-line overrides on session configuration.
492 cmdline_run_saved(&cfg);
495 * Apply subsystem status.
498 cfg.ssh_subsys = TRUE;
501 * Trim a colon suffix off the hostname if it's there.
503 cfg.host[strcspn(cfg.host, ":")] = '\0';
506 * Remove any remaining whitespace from the hostname.
510 while (cfg.host[p2] != '\0') {
511 if (cfg.host[p2] != ' ' && cfg.host[p2] != '\t') {
512 cfg.host[p1] = cfg.host[p2];
520 if (!*cfg.remote_cmd_ptr)
521 flags |= FLAG_INTERACTIVE;
524 * Select protocol. This is farmed out into a table in a
525 * separate file to enable an ssh-free variant.
530 for (i = 0; backends[i].backend != NULL; i++)
531 if (backends[i].protocol == cfg.protocol) {
532 back = backends[i].backend;
537 "Internal fault: Unsupported protocol found\n");
545 if (portnumber != -1)
546 cfg.port = portnumber;
549 * Initialise WinSock.
551 winsock_ver = MAKEWORD(2, 0);
552 if (WSAStartup(winsock_ver, &wsadata)) {
553 MessageBox(NULL, "Unable to initialise WinSock", "WinSock Error",
554 MB_OK | MB_ICONEXCLAMATION);
557 if (LOBYTE(wsadata.wVersion) != 2 || HIBYTE(wsadata.wVersion) != 0) {
558 MessageBox(NULL, "WinSock version is incompatible with 2.0",
559 "WinSock Error", MB_OK | MB_ICONEXCLAMATION);
566 * Start up the connection.
568 netevent = CreateEvent(NULL, FALSE, FALSE, NULL);
572 /* nodelay is only useful if stdin is a character device (console) */
573 int nodelay = cfg.tcp_nodelay &&
574 (GetFileType(GetStdHandle(STD_INPUT_HANDLE)) == FILE_TYPE_CHAR);
576 error = back->init(NULL, &backhandle, &cfg, cfg.host, cfg.port,
579 fprintf(stderr, "Unable to open connection:\n%s", error);
582 logctx = log_init(NULL, &cfg);
583 back->provide_logctx(backhandle, logctx);
584 console_provide_logctx(logctx);
589 stdinevent = CreateEvent(NULL, FALSE, FALSE, NULL);
590 stdoutevent = CreateEvent(NULL, FALSE, FALSE, NULL);
591 stderrevent = CreateEvent(NULL, FALSE, FALSE, NULL);
593 inhandle = GetStdHandle(STD_INPUT_HANDLE);
594 outhandle = GetStdHandle(STD_OUTPUT_HANDLE);
595 errhandle = GetStdHandle(STD_ERROR_HANDLE);
596 GetConsoleMode(inhandle, &orig_console_mode);
597 SetConsoleMode(inhandle, ENABLE_PROCESSED_INPUT);
599 main_thread_id = GetCurrentThreadId();
602 * Turn off ECHO and LINE input modes. We don't care if this
603 * call fails, because we know we aren't necessarily running in
606 handles[0] = netevent;
607 handles[1] = stdinevent;
608 handles[2] = stdoutevent;
609 handles[3] = stderrevent;
613 * Create spare threads to write to stdout and stderr, so we
614 * can arrange asynchronous writes.
616 odata.event = stdoutevent;
617 odata.eventback = CreateEvent(NULL, FALSE, FALSE, NULL);
619 odata.busy = odata.done = 0;
620 if (!CreateThread(NULL, 0, stdout_write_thread,
621 &odata, 0, &out_threadid)) {
622 fprintf(stderr, "Unable to create output thread\n");
625 edata.event = stderrevent;
626 edata.eventback = CreateEvent(NULL, FALSE, FALSE, NULL);
628 edata.busy = edata.done = 0;
629 if (!CreateThread(NULL, 0, stdout_write_thread,
630 &edata, 0, &err_threadid)) {
631 fprintf(stderr, "Unable to create error output thread\n");
638 if (!sending && back->sendok(backhandle)) {
640 * Create a separate thread to read from stdin. This is
641 * a total pain, but I can't find another way to do it:
643 * - an overlapped ReadFile or ReadFileEx just doesn't
644 * happen; we get failure from ReadFileEx, and
645 * ReadFile blocks despite being given an OVERLAPPED
646 * structure. Perhaps we can't do overlapped reads
647 * on consoles. WHY THE HELL NOT?
649 * - WaitForMultipleObjects(netevent, console) doesn't
650 * work, because it signals the console when
651 * _anything_ happens, including mouse motions and
652 * other things that don't cause data to be readable
653 * - so we're back to ReadFile blocking.
655 idata.event = stdinevent;
656 idata.eventback = CreateEvent(NULL, FALSE, FALSE, NULL);
657 if (!CreateThread(NULL, 0, stdin_read_thread,
658 &idata, 0, &in_threadid)) {
659 fprintf(stderr, "Unable to create input thread\n");
665 n = MsgWaitForMultipleObjects(4, handles, FALSE, INFINITE,
668 WSANETWORKEVENTS things;
670 extern SOCKET first_socket(int *), next_socket(int *);
671 extern int select_result(WPARAM, LPARAM);
675 * We must not call select_result() for any socket
676 * until we have finished enumerating within the tree.
677 * This is because select_result() may close the socket
678 * and modify the tree.
680 /* Count the active sockets. */
682 for (socket = first_socket(&socketstate);
683 socket != INVALID_SOCKET;
684 socket = next_socket(&socketstate)) i++;
686 /* Expand the buffer if necessary. */
689 sklist = sresize(sklist, sksize, SOCKET);
692 /* Retrieve the sockets into sklist. */
694 for (socket = first_socket(&socketstate);
695 socket != INVALID_SOCKET;
696 socket = next_socket(&socketstate)) {
697 sklist[skcount++] = socket;
700 /* Now we're done enumerating; go through the list. */
701 for (i = 0; i < skcount; i++) {
704 wp = (WPARAM) socket;
705 if (!WSAEnumNetworkEvents(socket, NULL, &things)) {
706 static const struct { int bit, mask; } eventtypes[] = {
707 {FD_CONNECT_BIT, FD_CONNECT},
708 {FD_READ_BIT, FD_READ},
709 {FD_CLOSE_BIT, FD_CLOSE},
710 {FD_OOB_BIT, FD_OOB},
711 {FD_WRITE_BIT, FD_WRITE},
712 {FD_ACCEPT_BIT, FD_ACCEPT},
716 noise_ultralight(socket);
717 noise_ultralight(things.lNetworkEvents);
719 for (e = 0; e < lenof(eventtypes); e++)
720 if (things.lNetworkEvents & eventtypes[e].mask) {
722 int err = things.iErrorCode[eventtypes[e].bit];
723 lp = WSAMAKESELECTREPLY(eventtypes[e].mask, err);
724 connopen &= select_result(wp, lp);
730 noise_ultralight(idata.len);
731 if (connopen && back->socket(backhandle) != NULL) {
733 back->send(backhandle, idata.buffer, idata.len);
735 back->special(backhandle, TS_EOF);
740 if (!odata.writeret) {
741 fprintf(stderr, "Unable to write to standard output\n");
744 bufchain_consume(&stdout_data, odata.lenwritten);
745 if (bufchain_size(&stdout_data) > 0)
747 if (connopen && back->socket(backhandle) != NULL) {
748 back->unthrottle(backhandle, bufchain_size(&stdout_data) +
749 bufchain_size(&stderr_data));
753 if (!edata.writeret) {
754 fprintf(stderr, "Unable to write to standard output\n");
757 bufchain_consume(&stderr_data, edata.lenwritten);
758 if (bufchain_size(&stderr_data) > 0)
760 if (connopen && back->socket(backhandle) != NULL) {
761 back->unthrottle(backhandle, bufchain_size(&stdout_data) +
762 bufchain_size(&stderr_data));
766 while (PeekMessage(&msg, INVALID_HANDLE_VALUE,
767 WM_AGENT_CALLBACK, WM_AGENT_CALLBACK,
769 struct agent_callback *c = (struct agent_callback *)msg.lParam;
770 c->callback(c->callback_ctx, c->data, c->len);
774 if (!reading && back->sendbuffer(backhandle) < MAX_STDIN_BACKLOG) {
775 SetEvent(idata.eventback);
778 if ((!connopen || back->socket(backhandle) == NULL) &&
779 bufchain_size(&stdout_data) == 0 &&
780 bufchain_size(&stderr_data) == 0)
781 break; /* we closed the connection */
784 exitcode = back->exitcode(backhandle);
786 fprintf(stderr, "Remote process exit code unavailable\n");
787 exitcode = 1; /* this is an error condition */