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)
186 bufchain_add(&stderr_data, data, len);
189 bufchain_add(&stdout_data, data, len);
193 osize = bufchain_size(&stdout_data);
194 esize = bufchain_size(&stderr_data);
196 return osize + esize;
199 static DWORD main_thread_id;
201 void agent_schedule_callback(void (*callback)(void *, void *, int),
202 void *callback_ctx, void *data, int len)
204 struct agent_callback *c = snew(struct agent_callback);
205 c->callback = callback;
206 c->callback_ctx = callback_ctx;
209 PostThreadMessage(main_thread_id, WM_AGENT_CALLBACK, 0, (LPARAM)c);
213 * Short description of parameters.
215 static void usage(void)
217 printf("PuTTY Link: command-line connection utility\n");
219 printf("Usage: plink [options] [user@]host [command]\n");
220 printf(" (\"host\" can also be a PuTTY saved session name)\n");
221 printf("Options:\n");
222 printf(" -v show verbose messages\n");
223 printf(" -load sessname Load settings from saved session\n");
224 printf(" -ssh -telnet -rlogin -raw\n");
225 printf(" force use of a particular protocol (default SSH)\n");
226 printf(" -P port connect to specified port\n");
227 printf(" -l user connect with specified username\n");
228 printf(" -m file read remote command(s) from file\n");
229 printf(" -batch disable all interactive prompts\n");
230 printf("The following options only apply to SSH connections:\n");
231 printf(" -pw passw login with specified password\n");
232 printf(" -D listen-port Dynamic SOCKS-based port forwarding\n");
233 printf(" -L listen-port:host:port Forward local port to "
235 printf(" -R listen-port:host:port Forward remote port to"
237 printf(" -X -x enable / disable X11 forwarding\n");
238 printf(" -A -a enable / disable agent forwarding\n");
239 printf(" -t -T enable / disable pty allocation\n");
240 printf(" -1 -2 force use of particular protocol version\n");
241 printf(" -C enable compression\n");
242 printf(" -i key private key file for authentication\n");
243 printf(" -s remote command is an SSH subsystem (SSH-2 only)\n");
247 char *do_select(SOCKET skt, int startup)
251 events = (FD_CONNECT | FD_READ | FD_WRITE |
252 FD_OOB | FD_CLOSE | FD_ACCEPT);
256 if (WSAEventSelect(skt, netevent, events) == SOCKET_ERROR) {
257 switch (WSAGetLastError()) {
259 return "Network is down";
261 return "WSAAsyncSelect(): unknown error";
267 int main(int argc, char **argv)
271 WSAEVENT stdinevent, stdoutevent, stderrevent;
273 DWORD in_threadid, out_threadid, err_threadid;
274 struct input_data idata;
283 int use_subsystem = 0;
285 ssh_get_line = console_get_line;
288 skcount = sksize = 0;
290 * Initialise port and protocol to sensible defaults. (These
291 * will be overridden by more or less anything.)
293 default_protocol = PROT_SSH;
298 * Process the command line.
300 do_defaults(NULL, &cfg);
301 default_protocol = cfg.protocol;
302 default_port = cfg.port;
306 * Override the default protocol if PLINK_PROTOCOL is set.
308 char *p = getenv("PLINK_PROTOCOL");
311 for (i = 0; backends[i].backend != NULL; i++) {
312 if (!strcmp(backends[i].name, p)) {
313 default_protocol = cfg.protocol = backends[i].protocol;
314 default_port = cfg.port =
315 backends[i].backend->default_port;
324 int ret = cmdline_process_param(p, (argc > 1 ? argv[1] : NULL),
328 "plink: option \"%s\" requires an argument\n", p);
330 } else if (ret == 2) {
332 } else if (ret == 1) {
334 } else if (!strcmp(p, "-batch")) {
335 console_batch_mode = 1;
336 } else if (!strcmp(p, "-s")) {
337 /* Save status to write to cfg later. */
340 fprintf(stderr, "plink: unknown option \"%s\"\n", p);
347 * If the hostname starts with "telnet:", set the
348 * protocol to Telnet and process the string as a
351 if (!strncmp(q, "telnet:", 7)) {
355 if (q[0] == '/' && q[1] == '/')
357 cfg.protocol = PROT_TELNET;
359 while (*p && *p != ':' && *p != '/')
368 strncpy(cfg.host, q, sizeof(cfg.host) - 1);
369 cfg.host[sizeof(cfg.host) - 1] = '\0';
373 * Before we process the [user@]host string, we
374 * first check for the presence of a protocol
375 * prefix (a protocol name followed by ",").
380 for (i = 0; backends[i].backend != NULL; i++) {
381 j = strlen(backends[i].name);
383 !memcmp(backends[i].name, p, j)) {
384 default_protocol = cfg.protocol =
385 backends[i].protocol;
387 backends[i].backend->default_port;
395 * Three cases. Either (a) there's a nonzero
396 * length string followed by an @, in which
397 * case that's user and the remainder is host.
398 * Or (b) there's only one string, not counting
399 * a potential initial @, and it exists in the
400 * saved-sessions database. Or (c) only one
401 * string and it _doesn't_ exist in the
406 p++, r = NULL; /* discount initial @ */
412 do_defaults(p, &cfg2);
413 if (cfg2.host[0] == '\0') {
414 /* No settings for this host; use defaults */
415 strncpy(cfg.host, p, sizeof(cfg.host) - 1);
416 cfg.host[sizeof(cfg.host) - 1] = '\0';
417 cfg.port = default_port;
420 cfg.remote_cmd_ptr = cfg.remote_cmd;
424 strncpy(cfg.username, p, sizeof(cfg.username) - 1);
425 cfg.username[sizeof(cfg.username) - 1] = '\0';
426 strncpy(cfg.host, r, sizeof(cfg.host) - 1);
427 cfg.host[sizeof(cfg.host) - 1] = '\0';
428 cfg.port = default_port;
434 cmdlen = cmdsize = 0;
439 if (cmdlen >= cmdsize) {
440 cmdsize = cmdlen + 512;
441 command = sresize(command, cmdsize, char);
443 command[cmdlen++]=*p++;
445 if (cmdlen >= cmdsize) {
446 cmdsize = cmdlen + 512;
447 command = sresize(command, cmdsize, char);
449 command[cmdlen++]=' '; /* always add trailing space */
450 if (--argc) p = *++argv;
452 if (cmdlen) command[--cmdlen]='\0';
453 /* change trailing blank to NUL */
454 cfg.remote_cmd_ptr = command;
455 cfg.remote_cmd_ptr2 = NULL;
456 cfg.nopty = TRUE; /* command => no terminal */
458 break; /* done with cmdline */
471 * Trim leading whitespace off the hostname if it's there.
474 int space = strspn(cfg.host, " \t");
475 memmove(cfg.host, cfg.host+space, 1+strlen(cfg.host)-space);
478 /* See if host is of the form user@host */
479 if (cfg.host[0] != '\0') {
480 char *atsign = strchr(cfg.host, '@');
481 /* Make sure we're not overflowing the user field */
483 if (atsign - cfg.host < sizeof cfg.username) {
484 strncpy(cfg.username, cfg.host, atsign - cfg.host);
485 cfg.username[atsign - cfg.host] = '\0';
487 memmove(cfg.host, atsign + 1, 1 + strlen(atsign + 1));
492 * Perform command-line overrides on session configuration.
494 cmdline_run_saved(&cfg);
497 * Apply subsystem status.
500 cfg.ssh_subsys = TRUE;
503 * Trim a colon suffix off the hostname if it's there.
505 cfg.host[strcspn(cfg.host, ":")] = '\0';
508 * Remove any remaining whitespace from the hostname.
512 while (cfg.host[p2] != '\0') {
513 if (cfg.host[p2] != ' ' && cfg.host[p2] != '\t') {
514 cfg.host[p1] = cfg.host[p2];
522 if (!*cfg.remote_cmd_ptr)
523 flags |= FLAG_INTERACTIVE;
526 * Select protocol. This is farmed out into a table in a
527 * separate file to enable an ssh-free variant.
532 for (i = 0; backends[i].backend != NULL; i++)
533 if (backends[i].protocol == cfg.protocol) {
534 back = backends[i].backend;
539 "Internal fault: Unsupported protocol found\n");
547 if (portnumber != -1)
548 cfg.port = portnumber;
551 * Initialise WinSock.
553 winsock_ver = MAKEWORD(2, 0);
554 if (WSAStartup(winsock_ver, &wsadata)) {
555 MessageBox(NULL, "Unable to initialise WinSock", "WinSock Error",
556 MB_OK | MB_ICONEXCLAMATION);
559 if (LOBYTE(wsadata.wVersion) != 2 || HIBYTE(wsadata.wVersion) != 0) {
560 MessageBox(NULL, "WinSock version is incompatible with 2.0",
561 "WinSock Error", MB_OK | MB_ICONEXCLAMATION);
568 * Start up the connection.
570 netevent = CreateEvent(NULL, FALSE, FALSE, NULL);
574 /* nodelay is only useful if stdin is a character device (console) */
575 int nodelay = cfg.tcp_nodelay &&
576 (GetFileType(GetStdHandle(STD_INPUT_HANDLE)) == FILE_TYPE_CHAR);
578 error = back->init(NULL, &backhandle, &cfg, cfg.host, cfg.port,
581 fprintf(stderr, "Unable to open connection:\n%s", error);
584 logctx = log_init(NULL, &cfg);
585 back->provide_logctx(backhandle, logctx);
586 console_provide_logctx(logctx);
591 stdinevent = CreateEvent(NULL, FALSE, FALSE, NULL);
592 stdoutevent = CreateEvent(NULL, FALSE, FALSE, NULL);
593 stderrevent = CreateEvent(NULL, FALSE, FALSE, NULL);
595 inhandle = GetStdHandle(STD_INPUT_HANDLE);
596 outhandle = GetStdHandle(STD_OUTPUT_HANDLE);
597 errhandle = GetStdHandle(STD_ERROR_HANDLE);
598 GetConsoleMode(inhandle, &orig_console_mode);
599 SetConsoleMode(inhandle, ENABLE_PROCESSED_INPUT);
601 main_thread_id = GetCurrentThreadId();
604 * Turn off ECHO and LINE input modes. We don't care if this
605 * call fails, because we know we aren't necessarily running in
608 handles[0] = netevent;
609 handles[1] = stdinevent;
610 handles[2] = stdoutevent;
611 handles[3] = stderrevent;
615 * Create spare threads to write to stdout and stderr, so we
616 * can arrange asynchronous writes.
618 odata.event = stdoutevent;
619 odata.eventback = CreateEvent(NULL, FALSE, FALSE, NULL);
621 odata.busy = odata.done = 0;
622 if (!CreateThread(NULL, 0, stdout_write_thread,
623 &odata, 0, &out_threadid)) {
624 fprintf(stderr, "Unable to create output thread\n");
627 edata.event = stderrevent;
628 edata.eventback = CreateEvent(NULL, FALSE, FALSE, NULL);
630 edata.busy = edata.done = 0;
631 if (!CreateThread(NULL, 0, stdout_write_thread,
632 &edata, 0, &err_threadid)) {
633 fprintf(stderr, "Unable to create error output thread\n");
640 if (!sending && back->sendok(backhandle)) {
642 * Create a separate thread to read from stdin. This is
643 * a total pain, but I can't find another way to do it:
645 * - an overlapped ReadFile or ReadFileEx just doesn't
646 * happen; we get failure from ReadFileEx, and
647 * ReadFile blocks despite being given an OVERLAPPED
648 * structure. Perhaps we can't do overlapped reads
649 * on consoles. WHY THE HELL NOT?
651 * - WaitForMultipleObjects(netevent, console) doesn't
652 * work, because it signals the console when
653 * _anything_ happens, including mouse motions and
654 * other things that don't cause data to be readable
655 * - so we're back to ReadFile blocking.
657 idata.event = stdinevent;
658 idata.eventback = CreateEvent(NULL, FALSE, FALSE, NULL);
659 if (!CreateThread(NULL, 0, stdin_read_thread,
660 &idata, 0, &in_threadid)) {
661 fprintf(stderr, "Unable to create input thread\n");
667 n = MsgWaitForMultipleObjects(4, handles, FALSE, INFINITE,
670 WSANETWORKEVENTS things;
672 extern SOCKET first_socket(int *), next_socket(int *);
673 extern int select_result(WPARAM, LPARAM);
677 * We must not call select_result() for any socket
678 * until we have finished enumerating within the tree.
679 * This is because select_result() may close the socket
680 * and modify the tree.
682 /* Count the active sockets. */
684 for (socket = first_socket(&socketstate);
685 socket != INVALID_SOCKET;
686 socket = next_socket(&socketstate)) i++;
688 /* Expand the buffer if necessary. */
691 sklist = sresize(sklist, sksize, SOCKET);
694 /* Retrieve the sockets into sklist. */
696 for (socket = first_socket(&socketstate);
697 socket != INVALID_SOCKET;
698 socket = next_socket(&socketstate)) {
699 sklist[skcount++] = socket;
702 /* Now we're done enumerating; go through the list. */
703 for (i = 0; i < skcount; i++) {
706 wp = (WPARAM) socket;
707 if (!WSAEnumNetworkEvents(socket, NULL, &things)) {
708 static const struct { int bit, mask; } eventtypes[] = {
709 {FD_CONNECT_BIT, FD_CONNECT},
710 {FD_READ_BIT, FD_READ},
711 {FD_CLOSE_BIT, FD_CLOSE},
712 {FD_OOB_BIT, FD_OOB},
713 {FD_WRITE_BIT, FD_WRITE},
714 {FD_ACCEPT_BIT, FD_ACCEPT},
718 noise_ultralight(socket);
719 noise_ultralight(things.lNetworkEvents);
721 for (e = 0; e < lenof(eventtypes); e++)
722 if (things.lNetworkEvents & eventtypes[e].mask) {
724 int err = things.iErrorCode[eventtypes[e].bit];
725 lp = WSAMAKESELECTREPLY(eventtypes[e].mask, err);
726 connopen &= select_result(wp, lp);
732 noise_ultralight(idata.len);
733 if (connopen && back->socket(backhandle) != NULL) {
735 back->send(backhandle, idata.buffer, idata.len);
737 back->special(backhandle, TS_EOF);
742 if (!odata.writeret) {
743 fprintf(stderr, "Unable to write to standard output\n");
746 bufchain_consume(&stdout_data, odata.lenwritten);
747 if (bufchain_size(&stdout_data) > 0)
749 if (connopen && back->socket(backhandle) != NULL) {
750 back->unthrottle(backhandle, bufchain_size(&stdout_data) +
751 bufchain_size(&stderr_data));
755 if (!edata.writeret) {
756 fprintf(stderr, "Unable to write to standard output\n");
759 bufchain_consume(&stderr_data, edata.lenwritten);
760 if (bufchain_size(&stderr_data) > 0)
762 if (connopen && back->socket(backhandle) != NULL) {
763 back->unthrottle(backhandle, bufchain_size(&stdout_data) +
764 bufchain_size(&stderr_data));
768 while (PeekMessage(&msg, INVALID_HANDLE_VALUE,
769 WM_AGENT_CALLBACK, WM_AGENT_CALLBACK,
771 struct agent_callback *c = (struct agent_callback *)msg.lParam;
772 c->callback(c->callback_ctx, c->data, c->len);
776 if (!reading && back->sendbuffer(backhandle) < MAX_STDIN_BACKLOG) {
777 SetEvent(idata.eventback);
780 if ((!connopen || back->socket(backhandle) == NULL) &&
781 bufchain_size(&stdout_data) == 0 &&
782 bufchain_size(&stderr_data) == 0)
783 break; /* we closed the connection */
786 exitcode = back->exitcode(backhandle);
788 fprintf(stderr, "Remote process exit code unavailable\n");
789 exitcode = 1; /* this is an error condition */