2 * PLink - a Windows command-line (stdin/stdout) variant of PuTTY.
10 #define PUTTY_DO_GLOBALS /* actually _define_ globals */
15 #define WM_AGENT_CALLBACK (WM_XUSER + 4)
17 #define MAX_STDIN_BACKLOG 4096
19 struct agent_callback {
20 void (*callback)(void *, void *, int);
26 void fatalbox(char *p, ...)
29 fprintf(stderr, "FATAL ERROR: ");
31 vfprintf(stderr, p, ap);
36 void modalfatalbox(char *p, ...)
39 fprintf(stderr, "FATAL ERROR: ");
41 vfprintf(stderr, p, ap);
46 void connection_fatal(void *frontend, char *p, ...)
49 fprintf(stderr, "FATAL ERROR: ");
51 vfprintf(stderr, p, ap);
56 void cmdline_error(char *p, ...)
59 fprintf(stderr, "plink: ");
61 vfprintf(stderr, p, ap);
67 HANDLE inhandle, outhandle, errhandle;
68 DWORD orig_console_mode;
73 static void *backhandle;
76 int term_ldisc(Terminal *term, int mode)
80 void ldisc_update(void *frontend, int echo, int edit)
82 /* Update stdin read mode to reflect changes in line discipline. */
85 mode = ENABLE_PROCESSED_INPUT;
87 mode = mode | ENABLE_ECHO_INPUT;
89 mode = mode & ~ENABLE_ECHO_INPUT;
91 mode = mode | ENABLE_LINE_INPUT;
93 mode = mode & ~ENABLE_LINE_INPUT;
94 SetConsoleMode(inhandle, mode);
97 char *get_ttymode(void *frontend, const char *mode) { return NULL; }
102 HANDLE event, eventback;
105 static DWORD WINAPI stdin_read_thread(void *param)
107 struct input_data *idata = (struct input_data *) param;
110 inhandle = GetStdHandle(STD_INPUT_HANDLE);
112 while (ReadFile(inhandle, idata->buffer, sizeof(idata->buffer),
113 &idata->len, NULL) && idata->len > 0) {
114 SetEvent(idata->event);
115 WaitForSingleObject(idata->eventback, INFINITE);
119 SetEvent(idata->event);
125 DWORD len, lenwritten;
129 HANDLE event, eventback;
133 static DWORD WINAPI stdout_write_thread(void *param)
135 struct output_data *odata = (struct output_data *) param;
136 HANDLE outhandle, errhandle;
138 outhandle = GetStdHandle(STD_OUTPUT_HANDLE);
139 errhandle = GetStdHandle(STD_ERROR_HANDLE);
142 WaitForSingleObject(odata->eventback, INFINITE);
146 WriteFile(odata->is_stderr ? errhandle : outhandle,
147 odata->buffer, odata->len, &odata->lenwritten, NULL);
148 SetEvent(odata->event);
154 bufchain stdout_data, stderr_data;
155 struct output_data odata, edata;
157 void try_output(int is_stderr)
159 struct output_data *data = (is_stderr ? &edata : &odata);
164 bufchain_prefix(is_stderr ? &stderr_data : &stdout_data,
165 &senddata, &sendlen);
166 data->buffer = senddata;
168 SetEvent(data->eventback);
173 int from_backend(void *frontend_handle, int is_stderr,
174 const char *data, int len)
179 bufchain_add(&stderr_data, data, len);
182 bufchain_add(&stdout_data, data, len);
186 osize = bufchain_size(&stdout_data);
187 esize = bufchain_size(&stderr_data);
189 return osize + esize;
192 static DWORD main_thread_id;
194 void agent_schedule_callback(void (*callback)(void *, void *, int),
195 void *callback_ctx, void *data, int len)
197 struct agent_callback *c = snew(struct agent_callback);
198 c->callback = callback;
199 c->callback_ctx = callback_ctx;
202 PostThreadMessage(main_thread_id, WM_AGENT_CALLBACK, 0, (LPARAM)c);
206 * Short description of parameters.
208 static void usage(void)
210 printf("PuTTY Link: command-line connection utility\n");
212 printf("Usage: plink [options] [user@]host [command]\n");
213 printf(" (\"host\" can also be a PuTTY saved session name)\n");
214 printf("Options:\n");
215 printf(" -V print version information and exit\n");
216 printf(" -pgpfp print PGP key fingerprints and exit\n");
217 printf(" -v show verbose messages\n");
218 printf(" -load sessname Load settings from saved session\n");
219 printf(" -ssh -telnet -rlogin -raw\n");
220 printf(" force use of a particular protocol\n");
221 printf(" -P port connect to specified port\n");
222 printf(" -l user connect with specified username\n");
223 printf(" -batch disable all interactive prompts\n");
224 printf("The following options only apply to SSH connections:\n");
225 printf(" -pw passw login with specified password\n");
226 printf(" -D [listen-IP:]listen-port\n");
227 printf(" Dynamic SOCKS-based port forwarding\n");
228 printf(" -L [listen-IP:]listen-port:host:port\n");
229 printf(" Forward local port to remote address\n");
230 printf(" -R [listen-IP:]listen-port:host:port\n");
231 printf(" Forward remote port to local address\n");
232 printf(" -X -x enable / disable X11 forwarding\n");
233 printf(" -A -a enable / disable agent forwarding\n");
234 printf(" -t -T enable / disable pty allocation\n");
235 printf(" -1 -2 force use of particular protocol version\n");
236 printf(" -4 -6 force use of IPv4 or IPv6\n");
237 printf(" -C enable compression\n");
238 printf(" -i key private key file for authentication\n");
239 printf(" -m file read remote command(s) from file\n");
240 printf(" -s remote command is an SSH subsystem (SSH-2 only)\n");
241 printf(" -N don't start a shell/command (SSH-2 only)\n");
245 static void version(void)
247 printf("plink: %s\n", ver);
251 char *do_select(SOCKET skt, int startup)
255 events = (FD_CONNECT | FD_READ | FD_WRITE |
256 FD_OOB | FD_CLOSE | FD_ACCEPT);
260 if (p_WSAEventSelect(skt, netevent, events) == SOCKET_ERROR) {
261 switch (p_WSAGetLastError()) {
263 return "Network is down";
265 return "WSAEventSelect(): unknown error";
271 int main(int argc, char **argv)
273 WSAEVENT stdinevent, stdoutevent, stderrevent;
275 DWORD in_threadid, out_threadid, err_threadid;
276 struct input_data idata;
285 int use_subsystem = 0;
288 ssh_get_line = console_get_line;
291 skcount = sksize = 0;
293 * Initialise port and protocol to sensible defaults. (These
294 * will be overridden by more or less anything.)
296 default_protocol = PROT_SSH;
301 * Process the command line.
303 do_defaults(NULL, &cfg);
304 loaded_session = FALSE;
305 default_protocol = cfg.protocol;
306 default_port = cfg.port;
310 * Override the default protocol if PLINK_PROTOCOL is set.
312 char *p = getenv("PLINK_PROTOCOL");
315 for (i = 0; backends[i].backend != NULL; i++) {
316 if (!strcmp(backends[i].name, p)) {
317 default_protocol = cfg.protocol = backends[i].protocol;
318 default_port = cfg.port =
319 backends[i].backend->default_port;
328 int ret = cmdline_process_param(p, (argc > 1 ? argv[1] : NULL),
332 "plink: option \"%s\" requires an argument\n", p);
334 } else if (ret == 2) {
336 } else if (ret == 1) {
338 } else if (!strcmp(p, "-batch")) {
339 console_batch_mode = 1;
340 } else if (!strcmp(p, "-s")) {
341 /* Save status to write to cfg later. */
343 } else if (!strcmp(p, "-V")) {
345 } else if (!strcmp(p, "-pgpfp")) {
349 fprintf(stderr, "plink: unknown option \"%s\"\n", p);
356 * If the hostname starts with "telnet:", set the
357 * protocol to Telnet and process the string as a
360 if (!strncmp(q, "telnet:", 7)) {
364 if (q[0] == '/' && q[1] == '/')
366 cfg.protocol = PROT_TELNET;
368 while (*p && *p != ':' && *p != '/')
377 strncpy(cfg.host, q, sizeof(cfg.host) - 1);
378 cfg.host[sizeof(cfg.host) - 1] = '\0';
380 char *r, *user, *host;
382 * Before we process the [user@]host string, we
383 * first check for the presence of a protocol
384 * prefix (a protocol name followed by ",").
389 for (i = 0; backends[i].backend != NULL; i++) {
390 j = strlen(backends[i].name);
392 !memcmp(backends[i].name, p, j)) {
393 default_protocol = cfg.protocol =
394 backends[i].protocol;
396 backends[i].backend->default_port;
404 * A nonzero length string followed by an @ is treated
405 * as a username. (We discount an _initial_ @.) The
406 * rest of the string (or the whole string if no @)
407 * is treated as a session name and/or hostname.
411 p++, r = NULL; /* discount initial @ */
416 user = NULL, host = p;
420 * Now attempt to load a saved session with the
421 * same name as the hostname.
425 do_defaults(host, &cfg2);
426 if (loaded_session || cfg2.host[0] == '\0') {
427 /* No settings for this host; use defaults */
428 /* (or session was already loaded with -load) */
429 strncpy(cfg.host, host, sizeof(cfg.host) - 1);
430 cfg.host[sizeof(cfg.host) - 1] = '\0';
431 cfg.port = default_port;
438 /* Patch in specified username. */
439 strncpy(cfg.username, user,
440 sizeof(cfg.username) - 1);
441 cfg.username[sizeof(cfg.username) - 1] = '\0';
448 cmdlen = cmdsize = 0;
453 if (cmdlen >= cmdsize) {
454 cmdsize = cmdlen + 512;
455 command = sresize(command, cmdsize, char);
457 command[cmdlen++]=*p++;
459 if (cmdlen >= cmdsize) {
460 cmdsize = cmdlen + 512;
461 command = sresize(command, cmdsize, char);
463 command[cmdlen++]=' '; /* always add trailing space */
464 if (--argc) p = *++argv;
466 if (cmdlen) command[--cmdlen]='\0';
467 /* change trailing blank to NUL */
468 cfg.remote_cmd_ptr = command;
469 cfg.remote_cmd_ptr2 = NULL;
470 cfg.nopty = TRUE; /* command => no terminal */
472 break; /* done with cmdline */
485 * Trim leading whitespace off the hostname if it's there.
488 int space = strspn(cfg.host, " \t");
489 memmove(cfg.host, cfg.host+space, 1+strlen(cfg.host)-space);
492 /* See if host is of the form user@host */
493 if (cfg.host[0] != '\0') {
494 char *atsign = strrchr(cfg.host, '@');
495 /* Make sure we're not overflowing the user field */
497 if (atsign - cfg.host < sizeof cfg.username) {
498 strncpy(cfg.username, cfg.host, atsign - cfg.host);
499 cfg.username[atsign - cfg.host] = '\0';
501 memmove(cfg.host, atsign + 1, 1 + strlen(atsign + 1));
506 * Perform command-line overrides on session configuration.
508 cmdline_run_saved(&cfg);
511 * Apply subsystem status.
514 cfg.ssh_subsys = TRUE;
517 * Trim a colon suffix off the hostname if it's there.
519 cfg.host[strcspn(cfg.host, ":")] = '\0';
522 * Remove any remaining whitespace from the hostname.
526 while (cfg.host[p2] != '\0') {
527 if (cfg.host[p2] != ' ' && cfg.host[p2] != '\t') {
528 cfg.host[p1] = cfg.host[p2];
536 if (!cfg.remote_cmd_ptr && !*cfg.remote_cmd)
537 flags |= FLAG_INTERACTIVE;
540 * Select protocol. This is farmed out into a table in a
541 * separate file to enable an ssh-free variant.
546 for (i = 0; backends[i].backend != NULL; i++)
547 if (backends[i].protocol == cfg.protocol) {
548 back = backends[i].backend;
553 "Internal fault: Unsupported protocol found\n");
561 if (portnumber != -1)
562 cfg.port = portnumber;
565 if (p_WSAEventSelect == NULL) {
566 fprintf(stderr, "Plink requires WinSock 2\n");
571 * Start up the connection.
573 netevent = CreateEvent(NULL, FALSE, FALSE, NULL);
577 /* nodelay is only useful if stdin is a character device (console) */
578 int nodelay = cfg.tcp_nodelay &&
579 (GetFileType(GetStdHandle(STD_INPUT_HANDLE)) == FILE_TYPE_CHAR);
581 error = back->init(NULL, &backhandle, &cfg, cfg.host, cfg.port,
582 &realhost, nodelay, cfg.tcp_keepalives);
584 fprintf(stderr, "Unable to open connection:\n%s", error);
587 logctx = log_init(NULL, &cfg);
588 back->provide_logctx(backhandle, logctx);
589 console_provide_logctx(logctx);
594 stdinevent = CreateEvent(NULL, FALSE, FALSE, NULL);
595 stdoutevent = CreateEvent(NULL, FALSE, FALSE, NULL);
596 stderrevent = CreateEvent(NULL, FALSE, FALSE, NULL);
598 inhandle = GetStdHandle(STD_INPUT_HANDLE);
599 outhandle = GetStdHandle(STD_OUTPUT_HANDLE);
600 errhandle = GetStdHandle(STD_ERROR_HANDLE);
601 GetConsoleMode(inhandle, &orig_console_mode);
602 SetConsoleMode(inhandle, ENABLE_PROCESSED_INPUT);
604 main_thread_id = GetCurrentThreadId();
607 * Turn off ECHO and LINE input modes. We don't care if this
608 * call fails, because we know we aren't necessarily running in
611 handles[0] = netevent;
612 handles[1] = stdinevent;
613 handles[2] = stdoutevent;
614 handles[3] = stderrevent;
618 * Create spare threads to write to stdout and stderr, so we
619 * can arrange asynchronous writes.
621 odata.event = stdoutevent;
622 odata.eventback = CreateEvent(NULL, FALSE, FALSE, NULL);
624 odata.busy = odata.done = 0;
625 if (!CreateThread(NULL, 0, stdout_write_thread,
626 &odata, 0, &out_threadid)) {
627 fprintf(stderr, "Unable to create output thread\n");
630 edata.event = stderrevent;
631 edata.eventback = CreateEvent(NULL, FALSE, FALSE, NULL);
633 edata.busy = edata.done = 0;
634 if (!CreateThread(NULL, 0, stdout_write_thread,
635 &edata, 0, &err_threadid)) {
636 fprintf(stderr, "Unable to create error output thread\n");
640 now = GETTICKCOUNT();
646 if (!sending && back->sendok(backhandle)) {
648 * Create a separate thread to read from stdin. This is
649 * a total pain, but I can't find another way to do it:
651 * - an overlapped ReadFile or ReadFileEx just doesn't
652 * happen; we get failure from ReadFileEx, and
653 * ReadFile blocks despite being given an OVERLAPPED
654 * structure. Perhaps we can't do overlapped reads
655 * on consoles. WHY THE HELL NOT?
657 * - WaitForMultipleObjects(netevent, console) doesn't
658 * work, because it signals the console when
659 * _anything_ happens, including mouse motions and
660 * other things that don't cause data to be readable
661 * - so we're back to ReadFile blocking.
663 idata.event = stdinevent;
664 idata.eventback = CreateEvent(NULL, FALSE, FALSE, NULL);
665 if (!CreateThread(NULL, 0, stdin_read_thread,
666 &idata, 0, &in_threadid)) {
667 fprintf(stderr, "Unable to create input thread\n");
674 if (run_timers(now, &next)) {
675 ticks = next - GETTICKCOUNT();
676 if (ticks < 0) ticks = 0; /* just in case */
681 n = MsgWaitForMultipleObjects(4, handles, FALSE, ticks,
683 if (n == WAIT_OBJECT_0 + 0) {
684 WSANETWORKEVENTS things;
686 extern SOCKET first_socket(int *), next_socket(int *);
687 extern int select_result(WPARAM, LPARAM);
691 * We must not call select_result() for any socket
692 * until we have finished enumerating within the tree.
693 * This is because select_result() may close the socket
694 * and modify the tree.
696 /* Count the active sockets. */
698 for (socket = first_socket(&socketstate);
699 socket != INVALID_SOCKET;
700 socket = next_socket(&socketstate)) i++;
702 /* Expand the buffer if necessary. */
705 sklist = sresize(sklist, sksize, SOCKET);
708 /* Retrieve the sockets into sklist. */
710 for (socket = first_socket(&socketstate);
711 socket != INVALID_SOCKET;
712 socket = next_socket(&socketstate)) {
713 sklist[skcount++] = socket;
716 /* Now we're done enumerating; go through the list. */
717 for (i = 0; i < skcount; i++) {
720 wp = (WPARAM) socket;
721 if (!p_WSAEnumNetworkEvents(socket, NULL, &things)) {
722 static const struct { int bit, mask; } eventtypes[] = {
723 {FD_CONNECT_BIT, FD_CONNECT},
724 {FD_READ_BIT, FD_READ},
725 {FD_CLOSE_BIT, FD_CLOSE},
726 {FD_OOB_BIT, FD_OOB},
727 {FD_WRITE_BIT, FD_WRITE},
728 {FD_ACCEPT_BIT, FD_ACCEPT},
732 noise_ultralight(socket);
733 noise_ultralight(things.lNetworkEvents);
735 for (e = 0; e < lenof(eventtypes); e++)
736 if (things.lNetworkEvents & eventtypes[e].mask) {
738 int err = things.iErrorCode[eventtypes[e].bit];
739 lp = WSAMAKESELECTREPLY(eventtypes[e].mask, err);
740 connopen &= select_result(wp, lp);
744 } else if (n == WAIT_OBJECT_0 + 1) {
746 noise_ultralight(idata.len);
747 if (connopen && back->socket(backhandle) != NULL) {
749 back->send(backhandle, idata.buffer, idata.len);
751 back->special(backhandle, TS_EOF);
754 } else if (n == WAIT_OBJECT_0 + 2) {
756 if (!odata.writeret) {
757 fprintf(stderr, "Unable to write to standard output\n");
760 bufchain_consume(&stdout_data, odata.lenwritten);
761 if (bufchain_size(&stdout_data) > 0)
763 if (connopen && back->socket(backhandle) != NULL) {
764 back->unthrottle(backhandle, bufchain_size(&stdout_data) +
765 bufchain_size(&stderr_data));
767 } else if (n == WAIT_OBJECT_0 + 3) {
769 if (!edata.writeret) {
770 fprintf(stderr, "Unable to write to standard output\n");
773 bufchain_consume(&stderr_data, edata.lenwritten);
774 if (bufchain_size(&stderr_data) > 0)
776 if (connopen && back->socket(backhandle) != NULL) {
777 back->unthrottle(backhandle, bufchain_size(&stdout_data) +
778 bufchain_size(&stderr_data));
780 } else if (n == WAIT_OBJECT_0 + 4) {
782 while (PeekMessage(&msg, INVALID_HANDLE_VALUE,
783 WM_AGENT_CALLBACK, WM_AGENT_CALLBACK,
785 struct agent_callback *c = (struct agent_callback *)msg.lParam;
786 c->callback(c->callback_ctx, c->data, c->len);
791 if (n == WAIT_TIMEOUT) {
794 now = GETTICKCOUNT();
797 if (!reading && back->sendbuffer(backhandle) < MAX_STDIN_BACKLOG) {
798 SetEvent(idata.eventback);
801 if ((!connopen || back->socket(backhandle) == NULL) &&
802 bufchain_size(&stdout_data) == 0 &&
803 bufchain_size(&stderr_data) == 0)
804 break; /* we closed the connection */
806 exitcode = back->exitcode(backhandle);
808 fprintf(stderr, "Remote process exit code unavailable\n");
809 exitcode = 1; /* this is an error condition */
811 cleanup_exit(exitcode);
812 return 0; /* placate compiler warning */