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 connection_fatal(char *p, ...)
35 fprintf(stderr, "FATAL ERROR: ");
37 vfprintf(stderr, p, ap);
43 void cmdline_error(char *p, ...)
46 fprintf(stderr, "plink: ");
48 vfprintf(stderr, p, ap);
54 static char *password = NULL;
56 HANDLE inhandle, outhandle, errhandle;
57 DWORD orig_console_mode;
61 int term_ldisc(int mode)
65 void ldisc_update(int echo, int edit)
67 /* Update stdin read mode to reflect changes in line discipline. */
70 mode = ENABLE_PROCESSED_INPUT;
72 mode = mode | ENABLE_ECHO_INPUT;
74 mode = mode & ~ENABLE_ECHO_INPUT;
76 mode = mode | ENABLE_LINE_INPUT;
78 mode = mode & ~ENABLE_LINE_INPUT;
79 SetConsoleMode(inhandle, mode);
85 HANDLE event, eventback;
88 static DWORD WINAPI stdin_read_thread(void *param)
90 struct input_data *idata = (struct input_data *) param;
93 inhandle = GetStdHandle(STD_INPUT_HANDLE);
95 while (ReadFile(inhandle, idata->buffer, sizeof(idata->buffer),
96 &idata->len, NULL) && idata->len > 0) {
97 SetEvent(idata->event);
98 WaitForSingleObject(idata->eventback, INFINITE);
102 SetEvent(idata->event);
108 DWORD len, lenwritten;
112 HANDLE event, eventback;
116 static DWORD WINAPI stdout_write_thread(void *param)
118 struct output_data *odata = (struct output_data *) param;
119 HANDLE outhandle, errhandle;
121 outhandle = GetStdHandle(STD_OUTPUT_HANDLE);
122 errhandle = GetStdHandle(STD_ERROR_HANDLE);
125 WaitForSingleObject(odata->eventback, INFINITE);
129 WriteFile(odata->is_stderr ? errhandle : outhandle,
130 odata->buffer, odata->len, &odata->lenwritten, NULL);
131 SetEvent(odata->event);
137 bufchain stdout_data, stderr_data;
138 struct output_data odata, edata;
140 void try_output(int is_stderr)
142 struct output_data *data = (is_stderr ? &edata : &odata);
147 bufchain_prefix(is_stderr ? &stderr_data : &stdout_data,
148 &senddata, &sendlen);
149 data->buffer = senddata;
151 SetEvent(data->eventback);
156 int from_backend(int is_stderr, char *data, int len)
158 HANDLE h = (is_stderr ? errhandle : outhandle);
164 bufchain_add(&stderr_data, data, len);
167 bufchain_add(&stdout_data, data, len);
171 osize = bufchain_size(&stdout_data);
172 esize = bufchain_size(&stderr_data);
174 return osize + esize;
178 * Short description of parameters.
180 static void usage(void)
182 printf("PuTTY Link: command-line connection utility\n");
184 printf("Usage: plink [options] [user@]host [command]\n");
185 printf(" (\"host\" can also be a PuTTY saved session name)\n");
186 printf("Options:\n");
187 printf(" -v show verbose messages\n");
188 printf(" -load sessname Load settings from saved session\n");
189 printf(" -ssh -telnet -rlogin -raw\n");
190 printf(" force use of a particular protocol (default SSH)\n");
191 printf(" -P port connect to specified port\n");
192 printf(" -l user connect with specified username\n");
193 printf(" -m file read remote command(s) from file\n");
194 printf(" -batch disable all interactive prompts\n");
195 printf("The following options only apply to SSH connections:\n");
196 printf(" -pw passw login with specified password\n");
197 printf(" -L listen-port:host:port Forward local port to "
199 printf(" -R listen-port:host:port Forward remote port to"
201 printf(" -X -x enable / disable X11 forwarding\n");
202 printf(" -A -a enable / disable agent forwarding\n");
203 printf(" -t -T enable / disable pty allocation\n");
204 printf(" -1 -2 force use of particular protocol version\n");
205 printf(" -C enable compression\n");
206 printf(" -i key private key file for authentication\n");
210 char *do_select(SOCKET skt, int startup)
214 events = (FD_CONNECT | FD_READ | FD_WRITE |
215 FD_OOB | FD_CLOSE | FD_ACCEPT);
219 if (WSAEventSelect(skt, netevent, events) == SOCKET_ERROR) {
220 switch (WSAGetLastError()) {
222 return "Network is down";
224 return "WSAAsyncSelect(): unknown error";
230 int main(int argc, char **argv)
234 WSAEVENT stdinevent, stdoutevent, stderrevent;
236 DWORD in_threadid, out_threadid, err_threadid;
237 struct input_data idata;
246 ssh_get_line = console_get_line;
249 skcount = sksize = 0;
251 * Initialise port and protocol to sensible defaults. (These
252 * will be overridden by more or less anything.)
254 default_protocol = PROT_SSH;
259 * Process the command line.
261 do_defaults(NULL, &cfg);
262 default_protocol = cfg.protocol;
263 default_port = cfg.port;
266 * Override the default protocol if PLINK_PROTOCOL is set.
268 char *p = getenv("PLINK_PROTOCOL");
271 for (i = 0; backends[i].backend != NULL; i++) {
272 if (!strcmp(backends[i].name, p)) {
273 default_protocol = cfg.protocol = backends[i].protocol;
274 default_port = cfg.port =
275 backends[i].backend->default_port;
284 int ret = cmdline_process_param(p, (argc > 1 ? argv[1] : NULL), 1);
287 "plink: option \"%s\" requires an argument\n", p);
288 } else if (ret == 2) {
290 } else if (ret == 1) {
292 } else if (!strcmp(p, "-batch")) {
293 console_batch_mode = 1;
299 * If the hostname starts with "telnet:", set the
300 * protocol to Telnet and process the string as a
303 if (!strncmp(q, "telnet:", 7)) {
307 if (q[0] == '/' && q[1] == '/')
309 cfg.protocol = PROT_TELNET;
311 while (*p && *p != ':' && *p != '/')
320 strncpy(cfg.host, q, sizeof(cfg.host) - 1);
321 cfg.host[sizeof(cfg.host) - 1] = '\0';
325 * Before we process the [user@]host string, we
326 * first check for the presence of a protocol
327 * prefix (a protocol name followed by ",").
332 for (i = 0; backends[i].backend != NULL; i++) {
333 j = strlen(backends[i].name);
335 !memcmp(backends[i].name, p, j)) {
336 default_protocol = cfg.protocol =
337 backends[i].protocol;
339 backends[i].backend->default_port;
347 * Three cases. Either (a) there's a nonzero
348 * length string followed by an @, in which
349 * case that's user and the remainder is host.
350 * Or (b) there's only one string, not counting
351 * a potential initial @, and it exists in the
352 * saved-sessions database. Or (c) only one
353 * string and it _doesn't_ exist in the
358 p++, r = NULL; /* discount initial @ */
364 do_defaults(p, &cfg2);
365 if (cfg2.host[0] == '\0') {
366 /* No settings for this host; use defaults */
367 strncpy(cfg.host, p, sizeof(cfg.host) - 1);
368 cfg.host[sizeof(cfg.host) - 1] = '\0';
369 cfg.port = default_port;
372 cfg.remote_cmd_ptr = cfg.remote_cmd;
376 strncpy(cfg.username, p, sizeof(cfg.username) - 1);
377 cfg.username[sizeof(cfg.username) - 1] = '\0';
378 strncpy(cfg.host, r, sizeof(cfg.host) - 1);
379 cfg.host[sizeof(cfg.host) - 1] = '\0';
380 cfg.port = default_port;
386 cmdlen = cmdsize = 0;
391 if (cmdlen >= cmdsize) {
392 cmdsize = cmdlen + 512;
393 command = srealloc(command, cmdsize);
395 command[cmdlen++]=*p++;
397 if (cmdlen >= cmdsize) {
398 cmdsize = cmdlen + 512;
399 command = srealloc(command, cmdsize);
401 command[cmdlen++]=' '; /* always add trailing space */
402 if (--argc) p = *++argv;
404 if (cmdlen) command[--cmdlen]='\0';
405 /* change trailing blank to NUL */
406 cfg.remote_cmd_ptr = command;
407 cfg.remote_cmd_ptr2 = NULL;
408 cfg.nopty = TRUE; /* command => no terminal */
410 break; /* done with cmdline */
420 * Trim leading whitespace off the hostname if it's there.
423 int space = strspn(cfg.host, " \t");
424 memmove(cfg.host, cfg.host+space, 1+strlen(cfg.host)-space);
427 /* See if host is of the form user@host */
428 if (cfg.host[0] != '\0') {
429 char *atsign = strchr(cfg.host, '@');
430 /* Make sure we're not overflowing the user field */
432 if (atsign - cfg.host < sizeof cfg.username) {
433 strncpy(cfg.username, cfg.host, atsign - cfg.host);
434 cfg.username[atsign - cfg.host] = '\0';
436 memmove(cfg.host, atsign + 1, 1 + strlen(atsign + 1));
441 * Perform command-line overrides on session configuration.
446 * Trim a colon suffix off the hostname if it's there.
448 cfg.host[strcspn(cfg.host, ":")] = '\0';
450 if (!*cfg.remote_cmd_ptr)
451 flags |= FLAG_INTERACTIVE;
454 * Select protocol. This is farmed out into a table in a
455 * separate file to enable an ssh-free variant.
460 for (i = 0; backends[i].backend != NULL; i++)
461 if (backends[i].protocol == cfg.protocol) {
462 back = backends[i].backend;
467 "Internal fault: Unsupported protocol found\n");
475 if (portnumber != -1)
476 cfg.port = portnumber;
479 * Initialise WinSock.
481 winsock_ver = MAKEWORD(2, 0);
482 if (WSAStartup(winsock_ver, &wsadata)) {
483 MessageBox(NULL, "Unable to initialise WinSock", "WinSock Error",
484 MB_OK | MB_ICONEXCLAMATION);
487 if (LOBYTE(wsadata.wVersion) != 2 || HIBYTE(wsadata.wVersion) != 0) {
488 MessageBox(NULL, "WinSock version is incompatible with 2.0",
489 "WinSock Error", MB_OK | MB_ICONEXCLAMATION);
496 * Start up the connection.
498 netevent = CreateEvent(NULL, FALSE, FALSE, NULL);
502 /* nodelay is only useful if stdin is a character device (console) */
503 int nodelay = cfg.tcp_nodelay &&
504 (GetFileType(GetStdHandle(STD_INPUT_HANDLE)) == FILE_TYPE_CHAR);
506 error = back->init(cfg.host, cfg.port, &realhost, nodelay);
508 fprintf(stderr, "Unable to open connection:\n%s", error);
515 stdinevent = CreateEvent(NULL, FALSE, FALSE, NULL);
516 stdoutevent = CreateEvent(NULL, FALSE, FALSE, NULL);
517 stderrevent = CreateEvent(NULL, FALSE, FALSE, NULL);
519 inhandle = GetStdHandle(STD_INPUT_HANDLE);
520 outhandle = GetStdHandle(STD_OUTPUT_HANDLE);
521 errhandle = GetStdHandle(STD_ERROR_HANDLE);
522 GetConsoleMode(inhandle, &orig_console_mode);
523 SetConsoleMode(inhandle, ENABLE_PROCESSED_INPUT);
526 * Turn off ECHO and LINE input modes. We don't care if this
527 * call fails, because we know we aren't necessarily running in
530 handles[0] = netevent;
531 handles[1] = stdinevent;
532 handles[2] = stdoutevent;
533 handles[3] = stderrevent;
537 * Create spare threads to write to stdout and stderr, so we
538 * can arrange asynchronous writes.
540 odata.event = stdoutevent;
541 odata.eventback = CreateEvent(NULL, FALSE, FALSE, NULL);
543 odata.busy = odata.done = 0;
544 if (!CreateThread(NULL, 0, stdout_write_thread,
545 &odata, 0, &out_threadid)) {
546 fprintf(stderr, "Unable to create output thread\n");
549 edata.event = stderrevent;
550 edata.eventback = CreateEvent(NULL, FALSE, FALSE, NULL);
552 edata.busy = edata.done = 0;
553 if (!CreateThread(NULL, 0, stdout_write_thread,
554 &edata, 0, &err_threadid)) {
555 fprintf(stderr, "Unable to create error output thread\n");
562 if (!sending && back->sendok()) {
564 * Create a separate thread to read from stdin. This is
565 * a total pain, but I can't find another way to do it:
567 * - an overlapped ReadFile or ReadFileEx just doesn't
568 * happen; we get failure from ReadFileEx, and
569 * ReadFile blocks despite being given an OVERLAPPED
570 * structure. Perhaps we can't do overlapped reads
571 * on consoles. WHY THE HELL NOT?
573 * - WaitForMultipleObjects(netevent, console) doesn't
574 * work, because it signals the console when
575 * _anything_ happens, including mouse motions and
576 * other things that don't cause data to be readable
577 * - so we're back to ReadFile blocking.
579 idata.event = stdinevent;
580 idata.eventback = CreateEvent(NULL, FALSE, FALSE, NULL);
581 if (!CreateThread(NULL, 0, stdin_read_thread,
582 &idata, 0, &in_threadid)) {
583 fprintf(stderr, "Unable to create input thread\n");
589 n = WaitForMultipleObjects(4, handles, FALSE, INFINITE);
591 WSANETWORKEVENTS things;
593 extern SOCKET first_socket(int *), next_socket(int *);
594 extern int select_result(WPARAM, LPARAM);
598 * We must not call select_result() for any socket
599 * until we have finished enumerating within the tree.
600 * This is because select_result() may close the socket
601 * and modify the tree.
603 /* Count the active sockets. */
605 for (socket = first_socket(&socketstate);
606 socket != INVALID_SOCKET;
607 socket = next_socket(&socketstate)) i++;
609 /* Expand the buffer if necessary. */
612 sklist = srealloc(sklist, sksize * sizeof(*sklist));
615 /* Retrieve the sockets into sklist. */
617 for (socket = first_socket(&socketstate);
618 socket != INVALID_SOCKET;
619 socket = next_socket(&socketstate)) {
620 sklist[skcount++] = socket;
623 /* Now we're done enumerating; go through the list. */
624 for (i = 0; i < skcount; i++) {
627 wp = (WPARAM) socket;
628 if (!WSAEnumNetworkEvents(socket, NULL, &things)) {
629 static const struct { int bit, mask; } eventtypes[] = {
630 {FD_CONNECT_BIT, FD_CONNECT},
631 {FD_READ_BIT, FD_READ},
632 {FD_CLOSE_BIT, FD_CLOSE},
633 {FD_OOB_BIT, FD_OOB},
634 {FD_WRITE_BIT, FD_WRITE},
635 {FD_ACCEPT_BIT, FD_ACCEPT},
639 noise_ultralight(socket);
640 noise_ultralight(things.lNetworkEvents);
642 for (e = 0; e < lenof(eventtypes); e++)
643 if (things.lNetworkEvents & eventtypes[e].mask) {
645 int err = things.iErrorCode[eventtypes[e].bit];
646 lp = WSAMAKESELECTREPLY(eventtypes[e].mask, err);
647 connopen &= select_result(wp, lp);
653 noise_ultralight(idata.len);
654 if (connopen && back->socket() != NULL) {
656 back->send(idata.buffer, idata.len);
658 back->special(TS_EOF);
663 if (!odata.writeret) {
664 fprintf(stderr, "Unable to write to standard output\n");
667 bufchain_consume(&stdout_data, odata.lenwritten);
668 if (bufchain_size(&stdout_data) > 0)
670 if (connopen && back->socket() != NULL) {
671 back->unthrottle(bufchain_size(&stdout_data) +
672 bufchain_size(&stderr_data));
676 if (!edata.writeret) {
677 fprintf(stderr, "Unable to write to standard output\n");
680 bufchain_consume(&stderr_data, edata.lenwritten);
681 if (bufchain_size(&stderr_data) > 0)
683 if (connopen && back->socket() != NULL) {
684 back->unthrottle(bufchain_size(&stdout_data) +
685 bufchain_size(&stderr_data));
688 if (!reading && back->sendbuffer() < MAX_STDIN_BACKLOG) {
689 SetEvent(idata.eventback);
692 if ((!connopen || back->socket() == NULL) &&
693 bufchain_size(&stdout_data) == 0 &&
694 bufchain_size(&stderr_data) == 0)
695 break; /* we closed the connection */
698 exitcode = back->exitcode();
700 fprintf(stderr, "Remote process exit code unavailable\n");
701 exitcode = 1; /* this is an error condition */