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_APP + 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 int from_backend_untrusted(void *frontend_handle, const char *data, int len)
195 * No "untrusted" output should get here (the way the code is
196 * currently, it's all diverted by FLAG_STDERR).
198 assert(!"Unexpected call to from_backend_untrusted()");
199 return 0; /* not reached */
202 int get_userpass_input(prompts_t *p, unsigned char *in, int inlen)
205 ret = cmdline_get_passwd_input(p, in, inlen);
207 ret = console_get_userpass_input(p, in, inlen);
211 static DWORD main_thread_id;
213 void agent_schedule_callback(void (*callback)(void *, void *, int),
214 void *callback_ctx, void *data, int len)
216 struct agent_callback *c = snew(struct agent_callback);
217 c->callback = callback;
218 c->callback_ctx = callback_ctx;
221 PostThreadMessage(main_thread_id, WM_AGENT_CALLBACK, 0, (LPARAM)c);
225 * Short description of parameters.
227 static void usage(void)
229 printf("PuTTY Link: command-line connection utility\n");
231 printf("Usage: plink [options] [user@]host [command]\n");
232 printf(" (\"host\" can also be a PuTTY saved session name)\n");
233 printf("Options:\n");
234 printf(" -V print version information and exit\n");
235 printf(" -pgpfp print PGP key fingerprints and exit\n");
236 printf(" -v show verbose messages\n");
237 printf(" -load sessname Load settings from saved session\n");
238 printf(" -ssh -telnet -rlogin -raw\n");
239 printf(" force use of a particular protocol\n");
240 printf(" -P port connect to specified port\n");
241 printf(" -l user connect with specified username\n");
242 printf(" -batch disable all interactive prompts\n");
243 printf("The following options only apply to SSH connections:\n");
244 printf(" -pw passw login with specified password\n");
245 printf(" -D [listen-IP:]listen-port\n");
246 printf(" Dynamic SOCKS-based port forwarding\n");
247 printf(" -L [listen-IP:]listen-port:host:port\n");
248 printf(" Forward local port to remote address\n");
249 printf(" -R [listen-IP:]listen-port:host:port\n");
250 printf(" Forward remote port to local address\n");
251 printf(" -X -x enable / disable X11 forwarding\n");
252 printf(" -A -a enable / disable agent forwarding\n");
253 printf(" -t -T enable / disable pty allocation\n");
254 printf(" -1 -2 force use of particular protocol version\n");
255 printf(" -4 -6 force use of IPv4 or IPv6\n");
256 printf(" -C enable compression\n");
257 printf(" -i key private key file for authentication\n");
258 printf(" -m file read remote command(s) from file\n");
259 printf(" -s remote command is an SSH subsystem (SSH-2 only)\n");
260 printf(" -N don't start a shell/command (SSH-2 only)\n");
264 static void version(void)
266 printf("plink: %s\n", ver);
270 char *do_select(SOCKET skt, int startup)
274 events = (FD_CONNECT | FD_READ | FD_WRITE |
275 FD_OOB | FD_CLOSE | FD_ACCEPT);
279 if (p_WSAEventSelect(skt, netevent, events) == SOCKET_ERROR) {
280 switch (p_WSAGetLastError()) {
282 return "Network is down";
284 return "WSAEventSelect(): unknown error";
290 int main(int argc, char **argv)
292 WSAEVENT stdinevent, stdoutevent, stderrevent;
294 DWORD in_threadid, out_threadid, err_threadid;
295 struct input_data idata;
304 int use_subsystem = 0;
308 skcount = sksize = 0;
310 * Initialise port and protocol to sensible defaults. (These
311 * will be overridden by more or less anything.)
313 default_protocol = PROT_SSH;
318 * Process the command line.
320 do_defaults(NULL, &cfg);
321 loaded_session = FALSE;
322 default_protocol = cfg.protocol;
323 default_port = cfg.port;
327 * Override the default protocol if PLINK_PROTOCOL is set.
329 char *p = getenv("PLINK_PROTOCOL");
332 for (i = 0; backends[i].backend != NULL; i++) {
333 if (!strcmp(backends[i].name, p)) {
334 default_protocol = cfg.protocol = backends[i].protocol;
335 default_port = cfg.port =
336 backends[i].backend->default_port;
345 int ret = cmdline_process_param(p, (argc > 1 ? argv[1] : NULL),
349 "plink: option \"%s\" requires an argument\n", p);
351 } else if (ret == 2) {
353 } else if (ret == 1) {
355 } else if (!strcmp(p, "-batch")) {
356 console_batch_mode = 1;
357 } else if (!strcmp(p, "-s")) {
358 /* Save status to write to cfg later. */
360 } else if (!strcmp(p, "-V")) {
362 } else if (!strcmp(p, "-pgpfp")) {
366 fprintf(stderr, "plink: unknown option \"%s\"\n", p);
373 * If the hostname starts with "telnet:", set the
374 * protocol to Telnet and process the string as a
377 if (!strncmp(q, "telnet:", 7)) {
381 if (q[0] == '/' && q[1] == '/')
383 cfg.protocol = PROT_TELNET;
385 while (*p && *p != ':' && *p != '/')
394 strncpy(cfg.host, q, sizeof(cfg.host) - 1);
395 cfg.host[sizeof(cfg.host) - 1] = '\0';
397 char *r, *user, *host;
399 * Before we process the [user@]host string, we
400 * first check for the presence of a protocol
401 * prefix (a protocol name followed by ",").
406 for (i = 0; backends[i].backend != NULL; i++) {
407 j = strlen(backends[i].name);
409 !memcmp(backends[i].name, p, j)) {
410 default_protocol = cfg.protocol =
411 backends[i].protocol;
413 backends[i].backend->default_port;
421 * A nonzero length string followed by an @ is treated
422 * as a username. (We discount an _initial_ @.) The
423 * rest of the string (or the whole string if no @)
424 * is treated as a session name and/or hostname.
428 p++, r = NULL; /* discount initial @ */
433 user = NULL, host = p;
437 * Now attempt to load a saved session with the
438 * same name as the hostname.
442 do_defaults(host, &cfg2);
443 if (loaded_session || cfg2.host[0] == '\0') {
444 /* No settings for this host; use defaults */
445 /* (or session was already loaded with -load) */
446 strncpy(cfg.host, host, sizeof(cfg.host) - 1);
447 cfg.host[sizeof(cfg.host) - 1] = '\0';
448 cfg.port = default_port;
455 /* Patch in specified username. */
456 strncpy(cfg.username, user,
457 sizeof(cfg.username) - 1);
458 cfg.username[sizeof(cfg.username) - 1] = '\0';
465 cmdlen = cmdsize = 0;
470 if (cmdlen >= cmdsize) {
471 cmdsize = cmdlen + 512;
472 command = sresize(command, cmdsize, char);
474 command[cmdlen++]=*p++;
476 if (cmdlen >= cmdsize) {
477 cmdsize = cmdlen + 512;
478 command = sresize(command, cmdsize, char);
480 command[cmdlen++]=' '; /* always add trailing space */
481 if (--argc) p = *++argv;
483 if (cmdlen) command[--cmdlen]='\0';
484 /* change trailing blank to NUL */
485 cfg.remote_cmd_ptr = command;
486 cfg.remote_cmd_ptr2 = NULL;
487 cfg.nopty = TRUE; /* command => no terminal */
489 break; /* done with cmdline */
502 * Trim leading whitespace off the hostname if it's there.
505 int space = strspn(cfg.host, " \t");
506 memmove(cfg.host, cfg.host+space, 1+strlen(cfg.host)-space);
509 /* See if host is of the form user@host */
510 if (cfg.host[0] != '\0') {
511 char *atsign = strrchr(cfg.host, '@');
512 /* Make sure we're not overflowing the user field */
514 if (atsign - cfg.host < sizeof cfg.username) {
515 strncpy(cfg.username, cfg.host, atsign - cfg.host);
516 cfg.username[atsign - cfg.host] = '\0';
518 memmove(cfg.host, atsign + 1, 1 + strlen(atsign + 1));
523 * Perform command-line overrides on session configuration.
525 cmdline_run_saved(&cfg);
528 * Apply subsystem status.
531 cfg.ssh_subsys = TRUE;
534 * Trim a colon suffix off the hostname if it's there.
536 cfg.host[strcspn(cfg.host, ":")] = '\0';
539 * Remove any remaining whitespace from the hostname.
543 while (cfg.host[p2] != '\0') {
544 if (cfg.host[p2] != ' ' && cfg.host[p2] != '\t') {
545 cfg.host[p1] = cfg.host[p2];
553 if (!cfg.remote_cmd_ptr && !*cfg.remote_cmd)
554 flags |= FLAG_INTERACTIVE;
557 * Select protocol. This is farmed out into a table in a
558 * separate file to enable an ssh-free variant.
563 for (i = 0; backends[i].backend != NULL; i++)
564 if (backends[i].protocol == cfg.protocol) {
565 back = backends[i].backend;
570 "Internal fault: Unsupported protocol found\n");
578 if (portnumber != -1)
579 cfg.port = portnumber;
582 if (p_WSAEventSelect == NULL) {
583 fprintf(stderr, "Plink requires WinSock 2\n");
588 * Start up the connection.
590 netevent = CreateEvent(NULL, FALSE, FALSE, NULL);
594 /* nodelay is only useful if stdin is a character device (console) */
595 int nodelay = cfg.tcp_nodelay &&
596 (GetFileType(GetStdHandle(STD_INPUT_HANDLE)) == FILE_TYPE_CHAR);
598 error = back->init(NULL, &backhandle, &cfg, cfg.host, cfg.port,
599 &realhost, nodelay, cfg.tcp_keepalives);
601 fprintf(stderr, "Unable to open connection:\n%s", error);
604 logctx = log_init(NULL, &cfg);
605 back->provide_logctx(backhandle, logctx);
606 console_provide_logctx(logctx);
611 stdinevent = CreateEvent(NULL, FALSE, FALSE, NULL);
612 stdoutevent = CreateEvent(NULL, FALSE, FALSE, NULL);
613 stderrevent = CreateEvent(NULL, FALSE, FALSE, NULL);
615 inhandle = GetStdHandle(STD_INPUT_HANDLE);
616 outhandle = GetStdHandle(STD_OUTPUT_HANDLE);
617 errhandle = GetStdHandle(STD_ERROR_HANDLE);
619 * Turn off ECHO and LINE input modes. We don't care if this
620 * call fails, because we know we aren't necessarily running in
623 GetConsoleMode(inhandle, &orig_console_mode);
624 SetConsoleMode(inhandle, ENABLE_PROCESSED_INPUT);
626 main_thread_id = GetCurrentThreadId();
628 handles[0] = netevent;
629 handles[1] = stdinevent;
630 handles[2] = stdoutevent;
631 handles[3] = stderrevent;
635 * Create spare threads to write to stdout and stderr, so we
636 * can arrange asynchronous writes.
638 odata.event = stdoutevent;
639 odata.eventback = CreateEvent(NULL, FALSE, FALSE, NULL);
641 odata.busy = odata.done = 0;
642 if (!CreateThread(NULL, 0, stdout_write_thread,
643 &odata, 0, &out_threadid)) {
644 fprintf(stderr, "Unable to create output thread\n");
647 edata.event = stderrevent;
648 edata.eventback = CreateEvent(NULL, FALSE, FALSE, NULL);
650 edata.busy = edata.done = 0;
651 if (!CreateThread(NULL, 0, stdout_write_thread,
652 &edata, 0, &err_threadid)) {
653 fprintf(stderr, "Unable to create error output thread\n");
657 now = GETTICKCOUNT();
663 if (!sending && back->sendok(backhandle)) {
665 * Create a separate thread to read from stdin. This is
666 * a total pain, but I can't find another way to do it:
668 * - an overlapped ReadFile or ReadFileEx just doesn't
669 * happen; we get failure from ReadFileEx, and
670 * ReadFile blocks despite being given an OVERLAPPED
671 * structure. Perhaps we can't do overlapped reads
672 * on consoles. WHY THE HELL NOT?
674 * - WaitForMultipleObjects(netevent, console) doesn't
675 * work, because it signals the console when
676 * _anything_ happens, including mouse motions and
677 * other things that don't cause data to be readable
678 * - so we're back to ReadFile blocking.
680 idata.event = stdinevent;
681 idata.eventback = CreateEvent(NULL, FALSE, FALSE, NULL);
682 if (!CreateThread(NULL, 0, stdin_read_thread,
683 &idata, 0, &in_threadid)) {
684 fprintf(stderr, "Unable to create input thread\n");
691 if (run_timers(now, &next)) {
692 ticks = next - GETTICKCOUNT();
693 if (ticks < 0) ticks = 0; /* just in case */
698 n = MsgWaitForMultipleObjects(4, handles, FALSE, ticks,
700 if (n == WAIT_OBJECT_0 + 0) {
701 WSANETWORKEVENTS things;
703 extern SOCKET first_socket(int *), next_socket(int *);
704 extern int select_result(WPARAM, LPARAM);
708 * We must not call select_result() for any socket
709 * until we have finished enumerating within the tree.
710 * This is because select_result() may close the socket
711 * and modify the tree.
713 /* Count the active sockets. */
715 for (socket = first_socket(&socketstate);
716 socket != INVALID_SOCKET;
717 socket = next_socket(&socketstate)) i++;
719 /* Expand the buffer if necessary. */
722 sklist = sresize(sklist, sksize, SOCKET);
725 /* Retrieve the sockets into sklist. */
727 for (socket = first_socket(&socketstate);
728 socket != INVALID_SOCKET;
729 socket = next_socket(&socketstate)) {
730 sklist[skcount++] = socket;
733 /* Now we're done enumerating; go through the list. */
734 for (i = 0; i < skcount; i++) {
737 wp = (WPARAM) socket;
738 if (!p_WSAEnumNetworkEvents(socket, NULL, &things)) {
739 static const struct { int bit, mask; } eventtypes[] = {
740 {FD_CONNECT_BIT, FD_CONNECT},
741 {FD_READ_BIT, FD_READ},
742 {FD_CLOSE_BIT, FD_CLOSE},
743 {FD_OOB_BIT, FD_OOB},
744 {FD_WRITE_BIT, FD_WRITE},
745 {FD_ACCEPT_BIT, FD_ACCEPT},
749 noise_ultralight(socket);
750 noise_ultralight(things.lNetworkEvents);
752 for (e = 0; e < lenof(eventtypes); e++)
753 if (things.lNetworkEvents & eventtypes[e].mask) {
755 int err = things.iErrorCode[eventtypes[e].bit];
756 lp = WSAMAKESELECTREPLY(eventtypes[e].mask, err);
757 connopen &= select_result(wp, lp);
761 } else if (n == WAIT_OBJECT_0 + 1) {
763 noise_ultralight(idata.len);
764 if (connopen && back->socket(backhandle) != NULL) {
766 back->send(backhandle, idata.buffer, idata.len);
768 back->special(backhandle, TS_EOF);
771 } else if (n == WAIT_OBJECT_0 + 2) {
773 if (!odata.writeret) {
774 fprintf(stderr, "Unable to write to standard output\n");
777 bufchain_consume(&stdout_data, odata.lenwritten);
778 if (bufchain_size(&stdout_data) > 0)
780 if (connopen && back->socket(backhandle) != NULL) {
781 back->unthrottle(backhandle, bufchain_size(&stdout_data) +
782 bufchain_size(&stderr_data));
784 } else if (n == WAIT_OBJECT_0 + 3) {
786 if (!edata.writeret) {
787 fprintf(stderr, "Unable to write to standard output\n");
790 bufchain_consume(&stderr_data, edata.lenwritten);
791 if (bufchain_size(&stderr_data) > 0)
793 if (connopen && back->socket(backhandle) != NULL) {
794 back->unthrottle(backhandle, bufchain_size(&stdout_data) +
795 bufchain_size(&stderr_data));
797 } else if (n == WAIT_OBJECT_0 + 4) {
799 while (PeekMessage(&msg, INVALID_HANDLE_VALUE,
800 WM_AGENT_CALLBACK, WM_AGENT_CALLBACK,
802 struct agent_callback *c = (struct agent_callback *)msg.lParam;
803 c->callback(c->callback_ctx, c->data, c->len);
808 if (n == WAIT_TIMEOUT) {
811 now = GETTICKCOUNT();
814 if (!reading && back->sendbuffer(backhandle) < MAX_STDIN_BACKLOG) {
815 SetEvent(idata.eventback);
818 if ((!connopen || back->socket(backhandle) == NULL) &&
819 bufchain_size(&stdout_data) == 0 &&
820 bufchain_size(&stderr_data) == 0)
821 break; /* we closed the connection */
823 exitcode = back->exitcode(backhandle);
825 fprintf(stderr, "Remote process exit code unavailable\n");
826 exitcode = 1; /* this is an error condition */
828 cleanup_exit(exitcode);
829 return 0; /* placate compiler warning */