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;
74 int term_ldisc(Terminal *term, int mode)
78 void ldisc_update(void *frontend, int echo, int edit)
80 /* Update stdin read mode to reflect changes in line discipline. */
83 mode = ENABLE_PROCESSED_INPUT;
85 mode = mode | ENABLE_ECHO_INPUT;
87 mode = mode & ~ENABLE_ECHO_INPUT;
89 mode = mode | ENABLE_LINE_INPUT;
91 mode = mode & ~ENABLE_LINE_INPUT;
92 SetConsoleMode(inhandle, mode);
98 HANDLE event, eventback;
101 static DWORD WINAPI stdin_read_thread(void *param)
103 struct input_data *idata = (struct input_data *) param;
106 inhandle = GetStdHandle(STD_INPUT_HANDLE);
108 while (ReadFile(inhandle, idata->buffer, sizeof(idata->buffer),
109 &idata->len, NULL) && idata->len > 0) {
110 SetEvent(idata->event);
111 WaitForSingleObject(idata->eventback, INFINITE);
115 SetEvent(idata->event);
121 DWORD len, lenwritten;
125 HANDLE event, eventback;
129 static DWORD WINAPI stdout_write_thread(void *param)
131 struct output_data *odata = (struct output_data *) param;
132 HANDLE outhandle, errhandle;
134 outhandle = GetStdHandle(STD_OUTPUT_HANDLE);
135 errhandle = GetStdHandle(STD_ERROR_HANDLE);
138 WaitForSingleObject(odata->eventback, INFINITE);
142 WriteFile(odata->is_stderr ? errhandle : outhandle,
143 odata->buffer, odata->len, &odata->lenwritten, NULL);
144 SetEvent(odata->event);
150 bufchain stdout_data, stderr_data;
151 struct output_data odata, edata;
153 void try_output(int is_stderr)
155 struct output_data *data = (is_stderr ? &edata : &odata);
160 bufchain_prefix(is_stderr ? &stderr_data : &stdout_data,
161 &senddata, &sendlen);
162 data->buffer = senddata;
164 SetEvent(data->eventback);
169 int from_backend(void *frontend_handle, int is_stderr,
170 const char *data, int len)
177 bufchain_add(&stderr_data, data, len);
180 bufchain_add(&stdout_data, data, len);
184 osize = bufchain_size(&stdout_data);
185 esize = bufchain_size(&stderr_data);
187 return osize + esize;
191 * Short description of parameters.
193 static void usage(void)
195 printf("PuTTY Link: command-line connection utility\n");
197 printf("Usage: plink [options] [user@]host [command]\n");
198 printf(" (\"host\" can also be a PuTTY saved session name)\n");
199 printf("Options:\n");
200 printf(" -v show verbose messages\n");
201 printf(" -load sessname Load settings from saved session\n");
202 printf(" -ssh -telnet -rlogin -raw\n");
203 printf(" force use of a particular protocol (default SSH)\n");
204 printf(" -P port connect to specified port\n");
205 printf(" -l user connect with specified username\n");
206 printf(" -m file read remote command(s) from file\n");
207 printf(" -batch disable all interactive prompts\n");
208 printf("The following options only apply to SSH connections:\n");
209 printf(" -pw passw login with specified password\n");
210 printf(" -L listen-port:host:port Forward local port to "
212 printf(" -R listen-port:host:port Forward remote port to"
214 printf(" -X -x enable / disable X11 forwarding\n");
215 printf(" -A -a enable / disable agent forwarding\n");
216 printf(" -t -T enable / disable pty allocation\n");
217 printf(" -1 -2 force use of particular protocol version\n");
218 printf(" -C enable compression\n");
219 printf(" -i key private key file for authentication\n");
223 char *do_select(SOCKET skt, int startup)
227 events = (FD_CONNECT | FD_READ | FD_WRITE |
228 FD_OOB | FD_CLOSE | FD_ACCEPT);
232 if (WSAEventSelect(skt, netevent, events) == SOCKET_ERROR) {
233 switch (WSAGetLastError()) {
235 return "Network is down";
237 return "WSAAsyncSelect(): unknown error";
243 int main(int argc, char **argv)
247 WSAEVENT stdinevent, stdoutevent, stderrevent;
249 DWORD in_threadid, out_threadid, err_threadid;
250 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;
281 * Override the default protocol if PLINK_PROTOCOL is set.
283 char *p = getenv("PLINK_PROTOCOL");
286 for (i = 0; backends[i].backend != NULL; i++) {
287 if (!strcmp(backends[i].name, p)) {
288 default_protocol = cfg.protocol = backends[i].protocol;
289 default_port = cfg.port =
290 backends[i].backend->default_port;
299 int ret = cmdline_process_param(p, (argc > 1 ? argv[1] : NULL),
303 "plink: option \"%s\" requires an argument\n", p);
305 } else if (ret == 2) {
307 } else if (ret == 1) {
309 } else if (!strcmp(p, "-batch")) {
310 console_batch_mode = 1;
312 fprintf(stderr, "plink: unknown option \"%s\"\n", p);
319 * If the hostname starts with "telnet:", set the
320 * protocol to Telnet and process the string as a
323 if (!strncmp(q, "telnet:", 7)) {
327 if (q[0] == '/' && q[1] == '/')
329 cfg.protocol = PROT_TELNET;
331 while (*p && *p != ':' && *p != '/')
340 strncpy(cfg.host, q, sizeof(cfg.host) - 1);
341 cfg.host[sizeof(cfg.host) - 1] = '\0';
345 * Before we process the [user@]host string, we
346 * first check for the presence of a protocol
347 * prefix (a protocol name followed by ",").
352 for (i = 0; backends[i].backend != NULL; i++) {
353 j = strlen(backends[i].name);
355 !memcmp(backends[i].name, p, j)) {
356 default_protocol = cfg.protocol =
357 backends[i].protocol;
359 backends[i].backend->default_port;
367 * Three cases. Either (a) there's a nonzero
368 * length string followed by an @, in which
369 * case that's user and the remainder is host.
370 * Or (b) there's only one string, not counting
371 * a potential initial @, and it exists in the
372 * saved-sessions database. Or (c) only one
373 * string and it _doesn't_ exist in the
378 p++, r = NULL; /* discount initial @ */
384 do_defaults(p, &cfg2);
385 if (cfg2.host[0] == '\0') {
386 /* No settings for this host; use defaults */
387 strncpy(cfg.host, p, sizeof(cfg.host) - 1);
388 cfg.host[sizeof(cfg.host) - 1] = '\0';
389 cfg.port = default_port;
392 cfg.remote_cmd_ptr = cfg.remote_cmd;
396 strncpy(cfg.username, p, sizeof(cfg.username) - 1);
397 cfg.username[sizeof(cfg.username) - 1] = '\0';
398 strncpy(cfg.host, r, sizeof(cfg.host) - 1);
399 cfg.host[sizeof(cfg.host) - 1] = '\0';
400 cfg.port = default_port;
406 cmdlen = cmdsize = 0;
411 if (cmdlen >= cmdsize) {
412 cmdsize = cmdlen + 512;
413 command = srealloc(command, cmdsize);
415 command[cmdlen++]=*p++;
417 if (cmdlen >= cmdsize) {
418 cmdsize = cmdlen + 512;
419 command = srealloc(command, cmdsize);
421 command[cmdlen++]=' '; /* always add trailing space */
422 if (--argc) p = *++argv;
424 if (cmdlen) command[--cmdlen]='\0';
425 /* change trailing blank to NUL */
426 cfg.remote_cmd_ptr = command;
427 cfg.remote_cmd_ptr2 = NULL;
428 cfg.nopty = TRUE; /* command => no terminal */
430 break; /* done with cmdline */
443 * Trim leading whitespace off the hostname if it's there.
446 int space = strspn(cfg.host, " \t");
447 memmove(cfg.host, cfg.host+space, 1+strlen(cfg.host)-space);
450 /* See if host is of the form user@host */
451 if (cfg.host[0] != '\0') {
452 char *atsign = strchr(cfg.host, '@');
453 /* Make sure we're not overflowing the user field */
455 if (atsign - cfg.host < sizeof cfg.username) {
456 strncpy(cfg.username, cfg.host, atsign - cfg.host);
457 cfg.username[atsign - cfg.host] = '\0';
459 memmove(cfg.host, atsign + 1, 1 + strlen(atsign + 1));
464 * Perform command-line overrides on session configuration.
466 cmdline_run_saved(&cfg);
469 * Trim a colon suffix off the hostname if it's there.
471 cfg.host[strcspn(cfg.host, ":")] = '\0';
474 * Remove any remaining whitespace from the hostname.
478 while (cfg.host[p2] != '\0') {
479 if (cfg.host[p2] != ' ' && cfg.host[p2] != '\t') {
480 cfg.host[p1] = cfg.host[p2];
488 if (!*cfg.remote_cmd_ptr)
489 flags |= FLAG_INTERACTIVE;
492 * Select protocol. This is farmed out into a table in a
493 * separate file to enable an ssh-free variant.
498 for (i = 0; backends[i].backend != NULL; i++)
499 if (backends[i].protocol == cfg.protocol) {
500 back = backends[i].backend;
505 "Internal fault: Unsupported protocol found\n");
513 if (portnumber != -1)
514 cfg.port = portnumber;
517 * Initialise WinSock.
519 winsock_ver = MAKEWORD(2, 0);
520 if (WSAStartup(winsock_ver, &wsadata)) {
521 MessageBox(NULL, "Unable to initialise WinSock", "WinSock Error",
522 MB_OK | MB_ICONEXCLAMATION);
525 if (LOBYTE(wsadata.wVersion) != 2 || HIBYTE(wsadata.wVersion) != 0) {
526 MessageBox(NULL, "WinSock version is incompatible with 2.0",
527 "WinSock Error", MB_OK | MB_ICONEXCLAMATION);
534 * Start up the connection.
536 netevent = CreateEvent(NULL, FALSE, FALSE, NULL);
540 /* nodelay is only useful if stdin is a character device (console) */
541 int nodelay = cfg.tcp_nodelay &&
542 (GetFileType(GetStdHandle(STD_INPUT_HANDLE)) == FILE_TYPE_CHAR);
544 error = back->init(NULL, &backhandle, &cfg, cfg.host, cfg.port,
547 fprintf(stderr, "Unable to open connection:\n%s", error);
550 logctx = log_init(NULL, &cfg);
551 back->provide_logctx(backhandle, logctx);
552 console_provide_logctx(logctx);
557 stdinevent = CreateEvent(NULL, FALSE, FALSE, NULL);
558 stdoutevent = CreateEvent(NULL, FALSE, FALSE, NULL);
559 stderrevent = CreateEvent(NULL, FALSE, FALSE, NULL);
561 inhandle = GetStdHandle(STD_INPUT_HANDLE);
562 outhandle = GetStdHandle(STD_OUTPUT_HANDLE);
563 errhandle = GetStdHandle(STD_ERROR_HANDLE);
564 GetConsoleMode(inhandle, &orig_console_mode);
565 SetConsoleMode(inhandle, ENABLE_PROCESSED_INPUT);
568 * Turn off ECHO and LINE input modes. We don't care if this
569 * call fails, because we know we aren't necessarily running in
572 handles[0] = netevent;
573 handles[1] = stdinevent;
574 handles[2] = stdoutevent;
575 handles[3] = stderrevent;
579 * Create spare threads to write to stdout and stderr, so we
580 * can arrange asynchronous writes.
582 odata.event = stdoutevent;
583 odata.eventback = CreateEvent(NULL, FALSE, FALSE, NULL);
585 odata.busy = odata.done = 0;
586 if (!CreateThread(NULL, 0, stdout_write_thread,
587 &odata, 0, &out_threadid)) {
588 fprintf(stderr, "Unable to create output thread\n");
591 edata.event = stderrevent;
592 edata.eventback = CreateEvent(NULL, FALSE, FALSE, NULL);
594 edata.busy = edata.done = 0;
595 if (!CreateThread(NULL, 0, stdout_write_thread,
596 &edata, 0, &err_threadid)) {
597 fprintf(stderr, "Unable to create error output thread\n");
604 if (!sending && back->sendok(backhandle)) {
606 * Create a separate thread to read from stdin. This is
607 * a total pain, but I can't find another way to do it:
609 * - an overlapped ReadFile or ReadFileEx just doesn't
610 * happen; we get failure from ReadFileEx, and
611 * ReadFile blocks despite being given an OVERLAPPED
612 * structure. Perhaps we can't do overlapped reads
613 * on consoles. WHY THE HELL NOT?
615 * - WaitForMultipleObjects(netevent, console) doesn't
616 * work, because it signals the console when
617 * _anything_ happens, including mouse motions and
618 * other things that don't cause data to be readable
619 * - so we're back to ReadFile blocking.
621 idata.event = stdinevent;
622 idata.eventback = CreateEvent(NULL, FALSE, FALSE, NULL);
623 if (!CreateThread(NULL, 0, stdin_read_thread,
624 &idata, 0, &in_threadid)) {
625 fprintf(stderr, "Unable to create input thread\n");
631 n = WaitForMultipleObjects(4, handles, FALSE, INFINITE);
633 WSANETWORKEVENTS things;
635 extern SOCKET first_socket(int *), next_socket(int *);
636 extern int select_result(WPARAM, LPARAM);
640 * We must not call select_result() for any socket
641 * until we have finished enumerating within the tree.
642 * This is because select_result() may close the socket
643 * and modify the tree.
645 /* Count the active sockets. */
647 for (socket = first_socket(&socketstate);
648 socket != INVALID_SOCKET;
649 socket = next_socket(&socketstate)) i++;
651 /* Expand the buffer if necessary. */
654 sklist = srealloc(sklist, sksize * sizeof(*sklist));
657 /* Retrieve the sockets into sklist. */
659 for (socket = first_socket(&socketstate);
660 socket != INVALID_SOCKET;
661 socket = next_socket(&socketstate)) {
662 sklist[skcount++] = socket;
665 /* Now we're done enumerating; go through the list. */
666 for (i = 0; i < skcount; i++) {
669 wp = (WPARAM) socket;
670 if (!WSAEnumNetworkEvents(socket, NULL, &things)) {
671 static const struct { int bit, mask; } eventtypes[] = {
672 {FD_CONNECT_BIT, FD_CONNECT},
673 {FD_READ_BIT, FD_READ},
674 {FD_CLOSE_BIT, FD_CLOSE},
675 {FD_OOB_BIT, FD_OOB},
676 {FD_WRITE_BIT, FD_WRITE},
677 {FD_ACCEPT_BIT, FD_ACCEPT},
681 noise_ultralight(socket);
682 noise_ultralight(things.lNetworkEvents);
684 for (e = 0; e < lenof(eventtypes); e++)
685 if (things.lNetworkEvents & eventtypes[e].mask) {
687 int err = things.iErrorCode[eventtypes[e].bit];
688 lp = WSAMAKESELECTREPLY(eventtypes[e].mask, err);
689 connopen &= select_result(wp, lp);
695 noise_ultralight(idata.len);
696 if (connopen && back->socket(backhandle) != NULL) {
698 back->send(backhandle, idata.buffer, idata.len);
700 back->special(backhandle, TS_EOF);
705 if (!odata.writeret) {
706 fprintf(stderr, "Unable to write to standard output\n");
709 bufchain_consume(&stdout_data, odata.lenwritten);
710 if (bufchain_size(&stdout_data) > 0)
712 if (connopen && back->socket(backhandle) != NULL) {
713 back->unthrottle(backhandle, bufchain_size(&stdout_data) +
714 bufchain_size(&stderr_data));
718 if (!edata.writeret) {
719 fprintf(stderr, "Unable to write to standard output\n");
722 bufchain_consume(&stderr_data, edata.lenwritten);
723 if (bufchain_size(&stderr_data) > 0)
725 if (connopen && back->socket(backhandle) != NULL) {
726 back->unthrottle(backhandle, bufchain_size(&stdout_data) +
727 bufchain_size(&stderr_data));
730 if (!reading && back->sendbuffer(backhandle) < MAX_STDIN_BACKLOG) {
731 SetEvent(idata.eventback);
734 if ((!connopen || back->socket(backhandle) == NULL) &&
735 bufchain_size(&stdout_data) == 0 &&
736 bufchain_size(&stderr_data) == 0)
737 break; /* we closed the connection */
740 exitcode = back->exitcode(backhandle);
742 fprintf(stderr, "Remote process exit code unavailable\n");
743 exitcode = 1; /* this is an error condition */