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 HANDLE inhandle, outhandle, errhandle;
66 DWORD orig_console_mode;
71 static void *backhandle;
73 int term_ldisc(Terminal *term, int mode)
77 void ldisc_update(void *frontend, int echo, int edit)
79 /* Update stdin read mode to reflect changes in line discipline. */
82 mode = ENABLE_PROCESSED_INPUT;
84 mode = mode | ENABLE_ECHO_INPUT;
86 mode = mode & ~ENABLE_ECHO_INPUT;
88 mode = mode | ENABLE_LINE_INPUT;
90 mode = mode & ~ENABLE_LINE_INPUT;
91 SetConsoleMode(inhandle, mode);
97 HANDLE event, eventback;
100 static DWORD WINAPI stdin_read_thread(void *param)
102 struct input_data *idata = (struct input_data *) param;
105 inhandle = GetStdHandle(STD_INPUT_HANDLE);
107 while (ReadFile(inhandle, idata->buffer, sizeof(idata->buffer),
108 &idata->len, NULL) && idata->len > 0) {
109 SetEvent(idata->event);
110 WaitForSingleObject(idata->eventback, INFINITE);
114 SetEvent(idata->event);
120 DWORD len, lenwritten;
124 HANDLE event, eventback;
128 static DWORD WINAPI stdout_write_thread(void *param)
130 struct output_data *odata = (struct output_data *) param;
131 HANDLE outhandle, errhandle;
133 outhandle = GetStdHandle(STD_OUTPUT_HANDLE);
134 errhandle = GetStdHandle(STD_ERROR_HANDLE);
137 WaitForSingleObject(odata->eventback, INFINITE);
141 WriteFile(odata->is_stderr ? errhandle : outhandle,
142 odata->buffer, odata->len, &odata->lenwritten, NULL);
143 SetEvent(odata->event);
149 bufchain stdout_data, stderr_data;
150 struct output_data odata, edata;
152 void try_output(int is_stderr)
154 struct output_data *data = (is_stderr ? &edata : &odata);
159 bufchain_prefix(is_stderr ? &stderr_data : &stdout_data,
160 &senddata, &sendlen);
161 data->buffer = senddata;
163 SetEvent(data->eventback);
168 int from_backend(void *frontend_handle, int is_stderr, char *data, int len)
175 bufchain_add(&stderr_data, data, len);
178 bufchain_add(&stdout_data, data, len);
182 osize = bufchain_size(&stdout_data);
183 esize = bufchain_size(&stderr_data);
185 return osize + esize;
189 * Short description of parameters.
191 static void usage(void)
193 printf("PuTTY Link: command-line connection utility\n");
195 printf("Usage: plink [options] [user@]host [command]\n");
196 printf(" (\"host\" can also be a PuTTY saved session name)\n");
197 printf("Options:\n");
198 printf(" -v show verbose messages\n");
199 printf(" -load sessname Load settings from saved session\n");
200 printf(" -ssh -telnet -rlogin -raw\n");
201 printf(" force use of a particular protocol (default SSH)\n");
202 printf(" -P port connect to specified port\n");
203 printf(" -l user connect with specified username\n");
204 printf(" -m file read remote command(s) from file\n");
205 printf(" -batch disable all interactive prompts\n");
206 printf("The following options only apply to SSH connections:\n");
207 printf(" -pw passw login with specified password\n");
208 printf(" -L listen-port:host:port Forward local port to "
210 printf(" -R listen-port:host:port Forward remote port to"
212 printf(" -X -x enable / disable X11 forwarding\n");
213 printf(" -A -a enable / disable agent forwarding\n");
214 printf(" -t -T enable / disable pty allocation\n");
215 printf(" -1 -2 force use of particular protocol version\n");
216 printf(" -C enable compression\n");
217 printf(" -i key private key file for authentication\n");
221 char *do_select(SOCKET skt, int startup)
225 events = (FD_CONNECT | FD_READ | FD_WRITE |
226 FD_OOB | FD_CLOSE | FD_ACCEPT);
230 if (WSAEventSelect(skt, netevent, events) == SOCKET_ERROR) {
231 switch (WSAGetLastError()) {
233 return "Network is down";
235 return "WSAAsyncSelect(): unknown error";
241 int main(int argc, char **argv)
245 WSAEVENT stdinevent, stdoutevent, stderrevent;
247 DWORD in_threadid, out_threadid, err_threadid;
248 struct input_data idata;
258 ssh_get_line = console_get_line;
261 skcount = sksize = 0;
263 * Initialise port and protocol to sensible defaults. (These
264 * will be overridden by more or less anything.)
266 default_protocol = PROT_SSH;
271 * Process the command line.
273 do_defaults(NULL, &cfg);
274 default_protocol = cfg.protocol;
275 default_port = cfg.port;
279 * Override the default protocol if PLINK_PROTOCOL is set.
281 char *p = getenv("PLINK_PROTOCOL");
284 for (i = 0; backends[i].backend != NULL; i++) {
285 if (!strcmp(backends[i].name, p)) {
286 default_protocol = cfg.protocol = backends[i].protocol;
287 default_port = cfg.port =
288 backends[i].backend->default_port;
297 int ret = cmdline_process_param(p, (argc > 1 ? argv[1] : NULL),
301 "plink: option \"%s\" requires an argument\n", p);
303 } else if (ret == 2) {
305 } else if (ret == 1) {
307 } else if (!strcmp(p, "-batch")) {
308 console_batch_mode = 1;
310 fprintf(stderr, "plink: unknown option \"%s\"\n", p);
317 * If the hostname starts with "telnet:", set the
318 * protocol to Telnet and process the string as a
321 if (!strncmp(q, "telnet:", 7)) {
325 if (q[0] == '/' && q[1] == '/')
327 cfg.protocol = PROT_TELNET;
329 while (*p && *p != ':' && *p != '/')
338 strncpy(cfg.host, q, sizeof(cfg.host) - 1);
339 cfg.host[sizeof(cfg.host) - 1] = '\0';
343 * Before we process the [user@]host string, we
344 * first check for the presence of a protocol
345 * prefix (a protocol name followed by ",").
350 for (i = 0; backends[i].backend != NULL; i++) {
351 j = strlen(backends[i].name);
353 !memcmp(backends[i].name, p, j)) {
354 default_protocol = cfg.protocol =
355 backends[i].protocol;
357 backends[i].backend->default_port;
365 * Three cases. Either (a) there's a nonzero
366 * length string followed by an @, in which
367 * case that's user and the remainder is host.
368 * Or (b) there's only one string, not counting
369 * a potential initial @, and it exists in the
370 * saved-sessions database. Or (c) only one
371 * string and it _doesn't_ exist in the
376 p++, r = NULL; /* discount initial @ */
382 do_defaults(p, &cfg2);
383 if (cfg2.host[0] == '\0') {
384 /* No settings for this host; use defaults */
385 strncpy(cfg.host, p, sizeof(cfg.host) - 1);
386 cfg.host[sizeof(cfg.host) - 1] = '\0';
387 cfg.port = default_port;
390 cfg.remote_cmd_ptr = cfg.remote_cmd;
394 strncpy(cfg.username, p, sizeof(cfg.username) - 1);
395 cfg.username[sizeof(cfg.username) - 1] = '\0';
396 strncpy(cfg.host, r, sizeof(cfg.host) - 1);
397 cfg.host[sizeof(cfg.host) - 1] = '\0';
398 cfg.port = default_port;
404 cmdlen = cmdsize = 0;
409 if (cmdlen >= cmdsize) {
410 cmdsize = cmdlen + 512;
411 command = srealloc(command, cmdsize);
413 command[cmdlen++]=*p++;
415 if (cmdlen >= cmdsize) {
416 cmdsize = cmdlen + 512;
417 command = srealloc(command, cmdsize);
419 command[cmdlen++]=' '; /* always add trailing space */
420 if (--argc) p = *++argv;
422 if (cmdlen) command[--cmdlen]='\0';
423 /* change trailing blank to NUL */
424 cfg.remote_cmd_ptr = command;
425 cfg.remote_cmd_ptr2 = NULL;
426 cfg.nopty = TRUE; /* command => no terminal */
428 break; /* done with cmdline */
441 * Trim leading whitespace off the hostname if it's there.
444 int space = strspn(cfg.host, " \t");
445 memmove(cfg.host, cfg.host+space, 1+strlen(cfg.host)-space);
448 /* See if host is of the form user@host */
449 if (cfg.host[0] != '\0') {
450 char *atsign = strchr(cfg.host, '@');
451 /* Make sure we're not overflowing the user field */
453 if (atsign - cfg.host < sizeof cfg.username) {
454 strncpy(cfg.username, cfg.host, atsign - cfg.host);
455 cfg.username[atsign - cfg.host] = '\0';
457 memmove(cfg.host, atsign + 1, 1 + strlen(atsign + 1));
462 * Perform command-line overrides on session configuration.
464 cmdline_run_saved(&cfg);
467 * Trim a colon suffix off the hostname if it's there.
469 cfg.host[strcspn(cfg.host, ":")] = '\0';
472 * Remove any remaining whitespace from the hostname.
476 while (cfg.host[p2] != '\0') {
477 if (cfg.host[p2] != ' ' && cfg.host[p2] != '\t') {
478 cfg.host[p1] = cfg.host[p2];
486 if (!*cfg.remote_cmd_ptr)
487 flags |= FLAG_INTERACTIVE;
490 * Select protocol. This is farmed out into a table in a
491 * separate file to enable an ssh-free variant.
496 for (i = 0; backends[i].backend != NULL; i++)
497 if (backends[i].protocol == cfg.protocol) {
498 back = backends[i].backend;
503 "Internal fault: Unsupported protocol found\n");
511 if (portnumber != -1)
512 cfg.port = portnumber;
515 * Initialise WinSock.
517 winsock_ver = MAKEWORD(2, 0);
518 if (WSAStartup(winsock_ver, &wsadata)) {
519 MessageBox(NULL, "Unable to initialise WinSock", "WinSock Error",
520 MB_OK | MB_ICONEXCLAMATION);
523 if (LOBYTE(wsadata.wVersion) != 2 || HIBYTE(wsadata.wVersion) != 0) {
524 MessageBox(NULL, "WinSock version is incompatible with 2.0",
525 "WinSock Error", MB_OK | MB_ICONEXCLAMATION);
532 * Start up the connection.
534 netevent = CreateEvent(NULL, FALSE, FALSE, NULL);
538 /* nodelay is only useful if stdin is a character device (console) */
539 int nodelay = cfg.tcp_nodelay &&
540 (GetFileType(GetStdHandle(STD_INPUT_HANDLE)) == FILE_TYPE_CHAR);
542 error = back->init(NULL, &backhandle, cfg.host, cfg.port,
545 fprintf(stderr, "Unable to open connection:\n%s", error);
548 logctx = log_init(NULL);
549 back->provide_logctx(backhandle, logctx);
554 stdinevent = CreateEvent(NULL, FALSE, FALSE, NULL);
555 stdoutevent = CreateEvent(NULL, FALSE, FALSE, NULL);
556 stderrevent = CreateEvent(NULL, FALSE, FALSE, NULL);
558 inhandle = GetStdHandle(STD_INPUT_HANDLE);
559 outhandle = GetStdHandle(STD_OUTPUT_HANDLE);
560 errhandle = GetStdHandle(STD_ERROR_HANDLE);
561 GetConsoleMode(inhandle, &orig_console_mode);
562 SetConsoleMode(inhandle, ENABLE_PROCESSED_INPUT);
565 * Turn off ECHO and LINE input modes. We don't care if this
566 * call fails, because we know we aren't necessarily running in
569 handles[0] = netevent;
570 handles[1] = stdinevent;
571 handles[2] = stdoutevent;
572 handles[3] = stderrevent;
576 * Create spare threads to write to stdout and stderr, so we
577 * can arrange asynchronous writes.
579 odata.event = stdoutevent;
580 odata.eventback = CreateEvent(NULL, FALSE, FALSE, NULL);
582 odata.busy = odata.done = 0;
583 if (!CreateThread(NULL, 0, stdout_write_thread,
584 &odata, 0, &out_threadid)) {
585 fprintf(stderr, "Unable to create output thread\n");
588 edata.event = stderrevent;
589 edata.eventback = CreateEvent(NULL, FALSE, FALSE, NULL);
591 edata.busy = edata.done = 0;
592 if (!CreateThread(NULL, 0, stdout_write_thread,
593 &edata, 0, &err_threadid)) {
594 fprintf(stderr, "Unable to create error output thread\n");
601 if (!sending && back->sendok(backhandle)) {
603 * Create a separate thread to read from stdin. This is
604 * a total pain, but I can't find another way to do it:
606 * - an overlapped ReadFile or ReadFileEx just doesn't
607 * happen; we get failure from ReadFileEx, and
608 * ReadFile blocks despite being given an OVERLAPPED
609 * structure. Perhaps we can't do overlapped reads
610 * on consoles. WHY THE HELL NOT?
612 * - WaitForMultipleObjects(netevent, console) doesn't
613 * work, because it signals the console when
614 * _anything_ happens, including mouse motions and
615 * other things that don't cause data to be readable
616 * - so we're back to ReadFile blocking.
618 idata.event = stdinevent;
619 idata.eventback = CreateEvent(NULL, FALSE, FALSE, NULL);
620 if (!CreateThread(NULL, 0, stdin_read_thread,
621 &idata, 0, &in_threadid)) {
622 fprintf(stderr, "Unable to create input thread\n");
628 n = WaitForMultipleObjects(4, handles, FALSE, INFINITE);
630 WSANETWORKEVENTS things;
632 extern SOCKET first_socket(int *), next_socket(int *);
633 extern int select_result(WPARAM, LPARAM);
637 * We must not call select_result() for any socket
638 * until we have finished enumerating within the tree.
639 * This is because select_result() may close the socket
640 * and modify the tree.
642 /* Count the active sockets. */
644 for (socket = first_socket(&socketstate);
645 socket != INVALID_SOCKET;
646 socket = next_socket(&socketstate)) i++;
648 /* Expand the buffer if necessary. */
651 sklist = srealloc(sklist, sksize * sizeof(*sklist));
654 /* Retrieve the sockets into sklist. */
656 for (socket = first_socket(&socketstate);
657 socket != INVALID_SOCKET;
658 socket = next_socket(&socketstate)) {
659 sklist[skcount++] = socket;
662 /* Now we're done enumerating; go through the list. */
663 for (i = 0; i < skcount; i++) {
666 wp = (WPARAM) socket;
667 if (!WSAEnumNetworkEvents(socket, NULL, &things)) {
668 static const struct { int bit, mask; } eventtypes[] = {
669 {FD_CONNECT_BIT, FD_CONNECT},
670 {FD_READ_BIT, FD_READ},
671 {FD_CLOSE_BIT, FD_CLOSE},
672 {FD_OOB_BIT, FD_OOB},
673 {FD_WRITE_BIT, FD_WRITE},
674 {FD_ACCEPT_BIT, FD_ACCEPT},
678 noise_ultralight(socket);
679 noise_ultralight(things.lNetworkEvents);
681 for (e = 0; e < lenof(eventtypes); e++)
682 if (things.lNetworkEvents & eventtypes[e].mask) {
684 int err = things.iErrorCode[eventtypes[e].bit];
685 lp = WSAMAKESELECTREPLY(eventtypes[e].mask, err);
686 connopen &= select_result(wp, lp);
692 noise_ultralight(idata.len);
693 if (connopen && back->socket(backhandle) != NULL) {
695 back->send(backhandle, idata.buffer, idata.len);
697 back->special(backhandle, TS_EOF);
702 if (!odata.writeret) {
703 fprintf(stderr, "Unable to write to standard output\n");
706 bufchain_consume(&stdout_data, odata.lenwritten);
707 if (bufchain_size(&stdout_data) > 0)
709 if (connopen && back->socket(backhandle) != NULL) {
710 back->unthrottle(backhandle, bufchain_size(&stdout_data) +
711 bufchain_size(&stderr_data));
715 if (!edata.writeret) {
716 fprintf(stderr, "Unable to write to standard output\n");
719 bufchain_consume(&stderr_data, edata.lenwritten);
720 if (bufchain_size(&stderr_data) > 0)
722 if (connopen && back->socket(backhandle) != NULL) {
723 back->unthrottle(backhandle, bufchain_size(&stdout_data) +
724 bufchain_size(&stderr_data));
727 if (!reading && back->sendbuffer(backhandle) < MAX_STDIN_BACKLOG) {
728 SetEvent(idata.eventback);
731 if ((!connopen || back->socket(backhandle) == NULL) &&
732 bufchain_size(&stdout_data) == 0 &&
733 bufchain_size(&stderr_data) == 0)
734 break; /* we closed the connection */
737 exitcode = back->exitcode(backhandle);
739 fprintf(stderr, "Remote process exit code unavailable\n");
740 exitcode = 1; /* this is an error condition */