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(" -noagent disable use of Pageant\n");
259 printf(" -agent enable use of Pageant\n");
260 printf(" -m file read remote command(s) from file\n");
261 printf(" -s remote command is an SSH subsystem (SSH-2 only)\n");
262 printf(" -N don't start a shell/command (SSH-2 only)\n");
266 static void version(void)
268 printf("plink: %s\n", ver);
272 char *do_select(SOCKET skt, int startup)
276 events = (FD_CONNECT | FD_READ | FD_WRITE |
277 FD_OOB | FD_CLOSE | FD_ACCEPT);
281 if (p_WSAEventSelect(skt, netevent, events) == SOCKET_ERROR) {
282 switch (p_WSAGetLastError()) {
284 return "Network is down";
286 return "WSAEventSelect(): unknown error";
292 int main(int argc, char **argv)
294 WSAEVENT stdinevent, stdoutevent, stderrevent;
296 DWORD in_threadid, out_threadid, err_threadid;
297 struct input_data idata;
306 int use_subsystem = 0;
310 skcount = sksize = 0;
312 * Initialise port and protocol to sensible defaults. (These
313 * will be overridden by more or less anything.)
315 default_protocol = PROT_SSH;
320 * Process the command line.
322 do_defaults(NULL, &cfg);
323 loaded_session = FALSE;
324 default_protocol = cfg.protocol;
325 default_port = cfg.port;
329 * Override the default protocol if PLINK_PROTOCOL is set.
331 char *p = getenv("PLINK_PROTOCOL");
334 for (i = 0; backends[i].backend != NULL; i++) {
335 if (!strcmp(backends[i].name, p)) {
336 default_protocol = cfg.protocol = backends[i].protocol;
337 default_port = cfg.port =
338 backends[i].backend->default_port;
347 int ret = cmdline_process_param(p, (argc > 1 ? argv[1] : NULL),
351 "plink: option \"%s\" requires an argument\n", p);
353 } else if (ret == 2) {
355 } else if (ret == 1) {
357 } else if (!strcmp(p, "-batch")) {
358 console_batch_mode = 1;
359 } else if (!strcmp(p, "-s")) {
360 /* Save status to write to cfg later. */
362 } else if (!strcmp(p, "-V")) {
364 } else if (!strcmp(p, "-pgpfp")) {
368 fprintf(stderr, "plink: unknown option \"%s\"\n", p);
375 * If the hostname starts with "telnet:", set the
376 * protocol to Telnet and process the string as a
379 if (!strncmp(q, "telnet:", 7)) {
383 if (q[0] == '/' && q[1] == '/')
385 cfg.protocol = PROT_TELNET;
387 while (*p && *p != ':' && *p != '/')
396 strncpy(cfg.host, q, sizeof(cfg.host) - 1);
397 cfg.host[sizeof(cfg.host) - 1] = '\0';
399 char *r, *user, *host;
401 * Before we process the [user@]host string, we
402 * first check for the presence of a protocol
403 * prefix (a protocol name followed by ",").
408 for (i = 0; backends[i].backend != NULL; i++) {
409 j = strlen(backends[i].name);
411 !memcmp(backends[i].name, p, j)) {
412 default_protocol = cfg.protocol =
413 backends[i].protocol;
415 backends[i].backend->default_port;
423 * A nonzero length string followed by an @ is treated
424 * as a username. (We discount an _initial_ @.) The
425 * rest of the string (or the whole string if no @)
426 * is treated as a session name and/or hostname.
430 p++, r = NULL; /* discount initial @ */
435 user = NULL, host = p;
439 * Now attempt to load a saved session with the
440 * same name as the hostname.
444 do_defaults(host, &cfg2);
445 if (loaded_session || cfg2.host[0] == '\0') {
446 /* No settings for this host; use defaults */
447 /* (or session was already loaded with -load) */
448 strncpy(cfg.host, host, sizeof(cfg.host) - 1);
449 cfg.host[sizeof(cfg.host) - 1] = '\0';
450 cfg.port = default_port;
457 /* Patch in specified username. */
458 strncpy(cfg.username, user,
459 sizeof(cfg.username) - 1);
460 cfg.username[sizeof(cfg.username) - 1] = '\0';
467 cmdlen = cmdsize = 0;
472 if (cmdlen >= cmdsize) {
473 cmdsize = cmdlen + 512;
474 command = sresize(command, cmdsize, char);
476 command[cmdlen++]=*p++;
478 if (cmdlen >= cmdsize) {
479 cmdsize = cmdlen + 512;
480 command = sresize(command, cmdsize, char);
482 command[cmdlen++]=' '; /* always add trailing space */
483 if (--argc) p = *++argv;
485 if (cmdlen) command[--cmdlen]='\0';
486 /* change trailing blank to NUL */
487 cfg.remote_cmd_ptr = command;
488 cfg.remote_cmd_ptr2 = NULL;
489 cfg.nopty = TRUE; /* command => no terminal */
491 break; /* done with cmdline */
504 * Trim leading whitespace off the hostname if it's there.
507 int space = strspn(cfg.host, " \t");
508 memmove(cfg.host, cfg.host+space, 1+strlen(cfg.host)-space);
511 /* See if host is of the form user@host */
512 if (cfg.host[0] != '\0') {
513 char *atsign = strrchr(cfg.host, '@');
514 /* Make sure we're not overflowing the user field */
516 if (atsign - cfg.host < sizeof cfg.username) {
517 strncpy(cfg.username, cfg.host, atsign - cfg.host);
518 cfg.username[atsign - cfg.host] = '\0';
520 memmove(cfg.host, atsign + 1, 1 + strlen(atsign + 1));
525 * Perform command-line overrides on session configuration.
527 cmdline_run_saved(&cfg);
530 * Apply subsystem status.
533 cfg.ssh_subsys = TRUE;
536 * Trim a colon suffix off the hostname if it's there.
538 cfg.host[strcspn(cfg.host, ":")] = '\0';
541 * Remove any remaining whitespace from the hostname.
545 while (cfg.host[p2] != '\0') {
546 if (cfg.host[p2] != ' ' && cfg.host[p2] != '\t') {
547 cfg.host[p1] = cfg.host[p2];
555 if (!cfg.remote_cmd_ptr && !*cfg.remote_cmd)
556 flags |= FLAG_INTERACTIVE;
559 * Select protocol. This is farmed out into a table in a
560 * separate file to enable an ssh-free variant.
565 for (i = 0; backends[i].backend != NULL; i++)
566 if (backends[i].protocol == cfg.protocol) {
567 back = backends[i].backend;
572 "Internal fault: Unsupported protocol found\n");
580 if (portnumber != -1)
581 cfg.port = portnumber;
584 if (p_WSAEventSelect == NULL) {
585 fprintf(stderr, "Plink requires WinSock 2\n");
590 * Start up the connection.
592 netevent = CreateEvent(NULL, FALSE, FALSE, NULL);
596 /* nodelay is only useful if stdin is a character device (console) */
597 int nodelay = cfg.tcp_nodelay &&
598 (GetFileType(GetStdHandle(STD_INPUT_HANDLE)) == FILE_TYPE_CHAR);
600 error = back->init(NULL, &backhandle, &cfg, cfg.host, cfg.port,
601 &realhost, nodelay, cfg.tcp_keepalives);
603 fprintf(stderr, "Unable to open connection:\n%s", error);
606 logctx = log_init(NULL, &cfg);
607 back->provide_logctx(backhandle, logctx);
608 console_provide_logctx(logctx);
613 stdinevent = CreateEvent(NULL, FALSE, FALSE, NULL);
614 stdoutevent = CreateEvent(NULL, FALSE, FALSE, NULL);
615 stderrevent = CreateEvent(NULL, FALSE, FALSE, NULL);
617 inhandle = GetStdHandle(STD_INPUT_HANDLE);
618 outhandle = GetStdHandle(STD_OUTPUT_HANDLE);
619 errhandle = GetStdHandle(STD_ERROR_HANDLE);
621 * Turn off ECHO and LINE input modes. We don't care if this
622 * call fails, because we know we aren't necessarily running in
625 GetConsoleMode(inhandle, &orig_console_mode);
626 SetConsoleMode(inhandle, ENABLE_PROCESSED_INPUT);
628 main_thread_id = GetCurrentThreadId();
630 handles[0] = netevent;
631 handles[1] = stdinevent;
632 handles[2] = stdoutevent;
633 handles[3] = stderrevent;
637 * Create spare threads to write to stdout and stderr, so we
638 * can arrange asynchronous writes.
640 odata.event = stdoutevent;
641 odata.eventback = CreateEvent(NULL, FALSE, FALSE, NULL);
643 odata.busy = odata.done = 0;
644 if (!CreateThread(NULL, 0, stdout_write_thread,
645 &odata, 0, &out_threadid)) {
646 fprintf(stderr, "Unable to create output thread\n");
649 edata.event = stderrevent;
650 edata.eventback = CreateEvent(NULL, FALSE, FALSE, NULL);
652 edata.busy = edata.done = 0;
653 if (!CreateThread(NULL, 0, stdout_write_thread,
654 &edata, 0, &err_threadid)) {
655 fprintf(stderr, "Unable to create error output thread\n");
659 now = GETTICKCOUNT();
665 if (!sending && back->sendok(backhandle)) {
667 * Create a separate thread to read from stdin. This is
668 * a total pain, but I can't find another way to do it:
670 * - an overlapped ReadFile or ReadFileEx just doesn't
671 * happen; we get failure from ReadFileEx, and
672 * ReadFile blocks despite being given an OVERLAPPED
673 * structure. Perhaps we can't do overlapped reads
674 * on consoles. WHY THE HELL NOT?
676 * - WaitForMultipleObjects(netevent, console) doesn't
677 * work, because it signals the console when
678 * _anything_ happens, including mouse motions and
679 * other things that don't cause data to be readable
680 * - so we're back to ReadFile blocking.
682 idata.event = stdinevent;
683 idata.eventback = CreateEvent(NULL, FALSE, FALSE, NULL);
684 if (!CreateThread(NULL, 0, stdin_read_thread,
685 &idata, 0, &in_threadid)) {
686 fprintf(stderr, "Unable to create input thread\n");
693 if (run_timers(now, &next)) {
694 ticks = next - GETTICKCOUNT();
695 if (ticks < 0) ticks = 0; /* just in case */
700 n = MsgWaitForMultipleObjects(4, handles, FALSE, ticks,
702 if (n == WAIT_OBJECT_0 + 0) {
703 WSANETWORKEVENTS things;
705 extern SOCKET first_socket(int *), next_socket(int *);
706 extern int select_result(WPARAM, LPARAM);
710 * We must not call select_result() for any socket
711 * until we have finished enumerating within the tree.
712 * This is because select_result() may close the socket
713 * and modify the tree.
715 /* Count the active sockets. */
717 for (socket = first_socket(&socketstate);
718 socket != INVALID_SOCKET;
719 socket = next_socket(&socketstate)) i++;
721 /* Expand the buffer if necessary. */
724 sklist = sresize(sklist, sksize, SOCKET);
727 /* Retrieve the sockets into sklist. */
729 for (socket = first_socket(&socketstate);
730 socket != INVALID_SOCKET;
731 socket = next_socket(&socketstate)) {
732 sklist[skcount++] = socket;
735 /* Now we're done enumerating; go through the list. */
736 for (i = 0; i < skcount; i++) {
739 wp = (WPARAM) socket;
740 if (!p_WSAEnumNetworkEvents(socket, NULL, &things)) {
741 static const struct { int bit, mask; } eventtypes[] = {
742 {FD_CONNECT_BIT, FD_CONNECT},
743 {FD_READ_BIT, FD_READ},
744 {FD_CLOSE_BIT, FD_CLOSE},
745 {FD_OOB_BIT, FD_OOB},
746 {FD_WRITE_BIT, FD_WRITE},
747 {FD_ACCEPT_BIT, FD_ACCEPT},
751 noise_ultralight(socket);
752 noise_ultralight(things.lNetworkEvents);
754 for (e = 0; e < lenof(eventtypes); e++)
755 if (things.lNetworkEvents & eventtypes[e].mask) {
757 int err = things.iErrorCode[eventtypes[e].bit];
758 lp = WSAMAKESELECTREPLY(eventtypes[e].mask, err);
759 connopen &= select_result(wp, lp);
763 } else if (n == WAIT_OBJECT_0 + 1) {
765 noise_ultralight(idata.len);
766 if (connopen && back->socket(backhandle) != NULL) {
768 back->send(backhandle, idata.buffer, idata.len);
770 back->special(backhandle, TS_EOF);
773 } else if (n == WAIT_OBJECT_0 + 2) {
775 if (!odata.writeret) {
776 fprintf(stderr, "Unable to write to standard output\n");
779 bufchain_consume(&stdout_data, odata.lenwritten);
780 if (bufchain_size(&stdout_data) > 0)
782 if (connopen && back->socket(backhandle) != NULL) {
783 back->unthrottle(backhandle, bufchain_size(&stdout_data) +
784 bufchain_size(&stderr_data));
786 } else if (n == WAIT_OBJECT_0 + 3) {
788 if (!edata.writeret) {
789 fprintf(stderr, "Unable to write to standard output\n");
792 bufchain_consume(&stderr_data, edata.lenwritten);
793 if (bufchain_size(&stderr_data) > 0)
795 if (connopen && back->socket(backhandle) != NULL) {
796 back->unthrottle(backhandle, bufchain_size(&stdout_data) +
797 bufchain_size(&stderr_data));
799 } else if (n == WAIT_OBJECT_0 + 4) {
801 while (PeekMessage(&msg, INVALID_HANDLE_VALUE,
802 WM_AGENT_CALLBACK, WM_AGENT_CALLBACK,
804 struct agent_callback *c = (struct agent_callback *)msg.lParam;
805 c->callback(c->callback_ctx, c->data, c->len);
810 if (n == WAIT_TIMEOUT) {
813 now = GETTICKCOUNT();
816 if (!reading && back->sendbuffer(backhandle) < MAX_STDIN_BACKLOG) {
817 SetEvent(idata.eventback);
820 if ((!connopen || back->socket(backhandle) == NULL) &&
821 bufchain_size(&stdout_data) == 0 &&
822 bufchain_size(&stderr_data) == 0)
823 break; /* we closed the connection */
825 exitcode = back->exitcode(backhandle);
827 fprintf(stderr, "Remote process exit code unavailable\n");
828 exitcode = 1; /* this is an error condition */
830 cleanup_exit(exitcode);
831 return 0; /* placate compiler warning */