2 * PLink - a 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);
100 HANDLE event, eventback;
103 static DWORD WINAPI stdin_read_thread(void *param)
105 struct input_data *idata = (struct input_data *) param;
108 inhandle = GetStdHandle(STD_INPUT_HANDLE);
110 while (ReadFile(inhandle, idata->buffer, sizeof(idata->buffer),
111 &idata->len, NULL) && idata->len > 0) {
112 SetEvent(idata->event);
113 WaitForSingleObject(idata->eventback, INFINITE);
117 SetEvent(idata->event);
123 DWORD len, lenwritten;
127 HANDLE event, eventback;
131 static DWORD WINAPI stdout_write_thread(void *param)
133 struct output_data *odata = (struct output_data *) param;
134 HANDLE outhandle, errhandle;
136 outhandle = GetStdHandle(STD_OUTPUT_HANDLE);
137 errhandle = GetStdHandle(STD_ERROR_HANDLE);
140 WaitForSingleObject(odata->eventback, INFINITE);
144 WriteFile(odata->is_stderr ? errhandle : outhandle,
145 odata->buffer, odata->len, &odata->lenwritten, NULL);
146 SetEvent(odata->event);
152 bufchain stdout_data, stderr_data;
153 struct output_data odata, edata;
155 void try_output(int is_stderr)
157 struct output_data *data = (is_stderr ? &edata : &odata);
162 bufchain_prefix(is_stderr ? &stderr_data : &stdout_data,
163 &senddata, &sendlen);
164 data->buffer = senddata;
166 SetEvent(data->eventback);
171 int from_backend(void *frontend_handle, int is_stderr,
172 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;
190 static DWORD main_thread_id;
192 void agent_schedule_callback(void (*callback)(void *, void *, int),
193 void *callback_ctx, void *data, int len)
195 struct agent_callback *c = snew(struct agent_callback);
196 c->callback = callback;
197 c->callback_ctx = callback_ctx;
200 PostThreadMessage(main_thread_id, WM_AGENT_CALLBACK, 0, (LPARAM)c);
204 * Short description of parameters.
206 static void usage(void)
208 printf("PuTTY Link: command-line connection utility\n");
210 printf("Usage: plink [options] [user@]host [command]\n");
211 printf(" (\"host\" can also be a PuTTY saved session name)\n");
212 printf("Options:\n");
213 printf(" -v show verbose messages\n");
214 printf(" -load sessname Load settings from saved session\n");
215 printf(" -ssh -telnet -rlogin -raw\n");
216 printf(" force use of a particular protocol (default SSH)\n");
217 printf(" -P port connect to specified port\n");
218 printf(" -l user connect with specified username\n");
219 printf(" -m file read remote command(s) from file\n");
220 printf(" -batch disable all interactive prompts\n");
221 printf("The following options only apply to SSH connections:\n");
222 printf(" -pw passw login with specified password\n");
223 printf(" -D listen-port Dynamic SOCKS-based port forwarding\n");
224 printf(" -L listen-port:host:port Forward local port to "
226 printf(" -R listen-port:host:port Forward remote port to"
228 printf(" -X -x enable / disable X11 forwarding\n");
229 printf(" -A -a enable / disable agent forwarding\n");
230 printf(" -t -T enable / disable pty allocation\n");
231 printf(" -1 -2 force use of particular protocol version\n");
232 printf(" -C enable compression\n");
233 printf(" -i key private key file for authentication\n");
234 printf(" -s remote command is an SSH subsystem (SSH-2 only)\n");
238 char *do_select(SOCKET skt, int startup)
242 events = (FD_CONNECT | FD_READ | FD_WRITE |
243 FD_OOB | FD_CLOSE | FD_ACCEPT);
247 if (p_WSAEventSelect(skt, netevent, events) == SOCKET_ERROR) {
248 switch (p_WSAGetLastError()) {
250 return "Network is down";
252 return "WSAEventSelect(): unknown error";
258 int main(int argc, char **argv)
260 WSAEVENT stdinevent, stdoutevent, stderrevent;
262 DWORD in_threadid, out_threadid, err_threadid;
263 struct input_data idata;
272 int use_subsystem = 0;
274 ssh_get_line = console_get_line;
277 skcount = sksize = 0;
279 * Initialise port and protocol to sensible defaults. (These
280 * will be overridden by more or less anything.)
282 default_protocol = PROT_SSH;
287 * Process the command line.
289 do_defaults(NULL, &cfg);
290 default_protocol = cfg.protocol;
291 default_port = cfg.port;
295 * Override the default protocol if PLINK_PROTOCOL is set.
297 char *p = getenv("PLINK_PROTOCOL");
300 for (i = 0; backends[i].backend != NULL; i++) {
301 if (!strcmp(backends[i].name, p)) {
302 default_protocol = cfg.protocol = backends[i].protocol;
303 default_port = cfg.port =
304 backends[i].backend->default_port;
313 int ret = cmdline_process_param(p, (argc > 1 ? argv[1] : NULL),
317 "plink: option \"%s\" requires an argument\n", p);
319 } else if (ret == 2) {
321 } else if (ret == 1) {
323 } else if (!strcmp(p, "-batch")) {
324 console_batch_mode = 1;
325 } else if (!strcmp(p, "-s")) {
326 /* Save status to write to cfg later. */
329 fprintf(stderr, "plink: unknown option \"%s\"\n", p);
336 * If the hostname starts with "telnet:", set the
337 * protocol to Telnet and process the string as a
340 if (!strncmp(q, "telnet:", 7)) {
344 if (q[0] == '/' && q[1] == '/')
346 cfg.protocol = PROT_TELNET;
348 while (*p && *p != ':' && *p != '/')
357 strncpy(cfg.host, q, sizeof(cfg.host) - 1);
358 cfg.host[sizeof(cfg.host) - 1] = '\0';
362 * Before we process the [user@]host string, we
363 * first check for the presence of a protocol
364 * prefix (a protocol name followed by ",").
369 for (i = 0; backends[i].backend != NULL; i++) {
370 j = strlen(backends[i].name);
372 !memcmp(backends[i].name, p, j)) {
373 default_protocol = cfg.protocol =
374 backends[i].protocol;
376 backends[i].backend->default_port;
384 * Three cases. Either (a) there's a nonzero
385 * length string followed by an @, in which
386 * case that's user and the remainder is host.
387 * Or (b) there's only one string, not counting
388 * a potential initial @, and it exists in the
389 * saved-sessions database. Or (c) only one
390 * string and it _doesn't_ exist in the
395 p++, r = NULL; /* discount initial @ */
401 do_defaults(p, &cfg2);
402 if (cfg2.host[0] == '\0') {
403 /* No settings for this host; use defaults */
404 strncpy(cfg.host, p, sizeof(cfg.host) - 1);
405 cfg.host[sizeof(cfg.host) - 1] = '\0';
406 cfg.port = default_port;
409 cfg.remote_cmd_ptr = cfg.remote_cmd;
413 strncpy(cfg.username, p, sizeof(cfg.username) - 1);
414 cfg.username[sizeof(cfg.username) - 1] = '\0';
415 strncpy(cfg.host, r, sizeof(cfg.host) - 1);
416 cfg.host[sizeof(cfg.host) - 1] = '\0';
417 cfg.port = default_port;
423 cmdlen = cmdsize = 0;
428 if (cmdlen >= cmdsize) {
429 cmdsize = cmdlen + 512;
430 command = sresize(command, cmdsize, char);
432 command[cmdlen++]=*p++;
434 if (cmdlen >= cmdsize) {
435 cmdsize = cmdlen + 512;
436 command = sresize(command, cmdsize, char);
438 command[cmdlen++]=' '; /* always add trailing space */
439 if (--argc) p = *++argv;
441 if (cmdlen) command[--cmdlen]='\0';
442 /* change trailing blank to NUL */
443 cfg.remote_cmd_ptr = command;
444 cfg.remote_cmd_ptr2 = NULL;
445 cfg.nopty = TRUE; /* command => no terminal */
447 break; /* done with cmdline */
460 * Trim leading whitespace off the hostname if it's there.
463 int space = strspn(cfg.host, " \t");
464 memmove(cfg.host, cfg.host+space, 1+strlen(cfg.host)-space);
467 /* See if host is of the form user@host */
468 if (cfg.host[0] != '\0') {
469 char *atsign = strchr(cfg.host, '@');
470 /* Make sure we're not overflowing the user field */
472 if (atsign - cfg.host < sizeof cfg.username) {
473 strncpy(cfg.username, cfg.host, atsign - cfg.host);
474 cfg.username[atsign - cfg.host] = '\0';
476 memmove(cfg.host, atsign + 1, 1 + strlen(atsign + 1));
481 * Perform command-line overrides on session configuration.
483 cmdline_run_saved(&cfg);
486 * Apply subsystem status.
489 cfg.ssh_subsys = TRUE;
492 * Trim a colon suffix off the hostname if it's there.
494 cfg.host[strcspn(cfg.host, ":")] = '\0';
497 * Remove any remaining whitespace from the hostname.
501 while (cfg.host[p2] != '\0') {
502 if (cfg.host[p2] != ' ' && cfg.host[p2] != '\t') {
503 cfg.host[p1] = cfg.host[p2];
511 if (!*cfg.remote_cmd_ptr)
512 flags |= FLAG_INTERACTIVE;
515 * Select protocol. This is farmed out into a table in a
516 * separate file to enable an ssh-free variant.
521 for (i = 0; backends[i].backend != NULL; i++)
522 if (backends[i].protocol == cfg.protocol) {
523 back = backends[i].backend;
528 "Internal fault: Unsupported protocol found\n");
536 if (portnumber != -1)
537 cfg.port = portnumber;
540 if (p_WSAEventSelect == NULL) {
541 fprintf(stderr, "Plink requires WinSock 2\n");
546 * Start up the connection.
548 netevent = CreateEvent(NULL, FALSE, FALSE, NULL);
552 /* nodelay is only useful if stdin is a character device (console) */
553 int nodelay = cfg.tcp_nodelay &&
554 (GetFileType(GetStdHandle(STD_INPUT_HANDLE)) == FILE_TYPE_CHAR);
556 error = back->init(NULL, &backhandle, &cfg, cfg.host, cfg.port,
559 fprintf(stderr, "Unable to open connection:\n%s", error);
562 logctx = log_init(NULL, &cfg);
563 back->provide_logctx(backhandle, logctx);
564 console_provide_logctx(logctx);
569 stdinevent = CreateEvent(NULL, FALSE, FALSE, NULL);
570 stdoutevent = CreateEvent(NULL, FALSE, FALSE, NULL);
571 stderrevent = CreateEvent(NULL, FALSE, FALSE, NULL);
573 inhandle = GetStdHandle(STD_INPUT_HANDLE);
574 outhandle = GetStdHandle(STD_OUTPUT_HANDLE);
575 errhandle = GetStdHandle(STD_ERROR_HANDLE);
576 GetConsoleMode(inhandle, &orig_console_mode);
577 SetConsoleMode(inhandle, ENABLE_PROCESSED_INPUT);
579 main_thread_id = GetCurrentThreadId();
582 * Turn off ECHO and LINE input modes. We don't care if this
583 * call fails, because we know we aren't necessarily running in
586 handles[0] = netevent;
587 handles[1] = stdinevent;
588 handles[2] = stdoutevent;
589 handles[3] = stderrevent;
593 * Create spare threads to write to stdout and stderr, so we
594 * can arrange asynchronous writes.
596 odata.event = stdoutevent;
597 odata.eventback = CreateEvent(NULL, FALSE, FALSE, NULL);
599 odata.busy = odata.done = 0;
600 if (!CreateThread(NULL, 0, stdout_write_thread,
601 &odata, 0, &out_threadid)) {
602 fprintf(stderr, "Unable to create output thread\n");
605 edata.event = stderrevent;
606 edata.eventback = CreateEvent(NULL, FALSE, FALSE, NULL);
608 edata.busy = edata.done = 0;
609 if (!CreateThread(NULL, 0, stdout_write_thread,
610 &edata, 0, &err_threadid)) {
611 fprintf(stderr, "Unable to create error output thread\n");
618 if (!sending && back->sendok(backhandle)) {
620 * Create a separate thread to read from stdin. This is
621 * a total pain, but I can't find another way to do it:
623 * - an overlapped ReadFile or ReadFileEx just doesn't
624 * happen; we get failure from ReadFileEx, and
625 * ReadFile blocks despite being given an OVERLAPPED
626 * structure. Perhaps we can't do overlapped reads
627 * on consoles. WHY THE HELL NOT?
629 * - WaitForMultipleObjects(netevent, console) doesn't
630 * work, because it signals the console when
631 * _anything_ happens, including mouse motions and
632 * other things that don't cause data to be readable
633 * - so we're back to ReadFile blocking.
635 idata.event = stdinevent;
636 idata.eventback = CreateEvent(NULL, FALSE, FALSE, NULL);
637 if (!CreateThread(NULL, 0, stdin_read_thread,
638 &idata, 0, &in_threadid)) {
639 fprintf(stderr, "Unable to create input thread\n");
645 n = MsgWaitForMultipleObjects(4, handles, FALSE, INFINITE,
648 WSANETWORKEVENTS things;
650 extern SOCKET first_socket(int *), next_socket(int *);
651 extern int select_result(WPARAM, LPARAM);
655 * We must not call select_result() for any socket
656 * until we have finished enumerating within the tree.
657 * This is because select_result() may close the socket
658 * and modify the tree.
660 /* Count the active sockets. */
662 for (socket = first_socket(&socketstate);
663 socket != INVALID_SOCKET;
664 socket = next_socket(&socketstate)) i++;
666 /* Expand the buffer if necessary. */
669 sklist = sresize(sklist, sksize, SOCKET);
672 /* Retrieve the sockets into sklist. */
674 for (socket = first_socket(&socketstate);
675 socket != INVALID_SOCKET;
676 socket = next_socket(&socketstate)) {
677 sklist[skcount++] = socket;
680 /* Now we're done enumerating; go through the list. */
681 for (i = 0; i < skcount; i++) {
684 wp = (WPARAM) socket;
685 if (!p_WSAEnumNetworkEvents(socket, NULL, &things)) {
686 static const struct { int bit, mask; } eventtypes[] = {
687 {FD_CONNECT_BIT, FD_CONNECT},
688 {FD_READ_BIT, FD_READ},
689 {FD_CLOSE_BIT, FD_CLOSE},
690 {FD_OOB_BIT, FD_OOB},
691 {FD_WRITE_BIT, FD_WRITE},
692 {FD_ACCEPT_BIT, FD_ACCEPT},
696 noise_ultralight(socket);
697 noise_ultralight(things.lNetworkEvents);
699 for (e = 0; e < lenof(eventtypes); e++)
700 if (things.lNetworkEvents & eventtypes[e].mask) {
702 int err = things.iErrorCode[eventtypes[e].bit];
703 lp = WSAMAKESELECTREPLY(eventtypes[e].mask, err);
704 connopen &= select_result(wp, lp);
710 noise_ultralight(idata.len);
711 if (connopen && back->socket(backhandle) != NULL) {
713 back->send(backhandle, idata.buffer, idata.len);
715 back->special(backhandle, TS_EOF);
720 if (!odata.writeret) {
721 fprintf(stderr, "Unable to write to standard output\n");
724 bufchain_consume(&stdout_data, odata.lenwritten);
725 if (bufchain_size(&stdout_data) > 0)
727 if (connopen && back->socket(backhandle) != NULL) {
728 back->unthrottle(backhandle, bufchain_size(&stdout_data) +
729 bufchain_size(&stderr_data));
733 if (!edata.writeret) {
734 fprintf(stderr, "Unable to write to standard output\n");
737 bufchain_consume(&stderr_data, edata.lenwritten);
738 if (bufchain_size(&stderr_data) > 0)
740 if (connopen && back->socket(backhandle) != NULL) {
741 back->unthrottle(backhandle, bufchain_size(&stdout_data) +
742 bufchain_size(&stderr_data));
746 while (PeekMessage(&msg, INVALID_HANDLE_VALUE,
747 WM_AGENT_CALLBACK, WM_AGENT_CALLBACK,
749 struct agent_callback *c = (struct agent_callback *)msg.lParam;
750 c->callback(c->callback_ctx, c->data, c->len);
754 if (!reading && back->sendbuffer(backhandle) < MAX_STDIN_BACKLOG) {
755 SetEvent(idata.eventback);
758 if ((!connopen || back->socket(backhandle) == NULL) &&
759 bufchain_size(&stdout_data) == 0 &&
760 bufchain_size(&stderr_data) == 0)
761 break; /* we closed the connection */
763 exitcode = back->exitcode(backhandle);
765 fprintf(stderr, "Remote process exit code unavailable\n");
766 exitcode = 1; /* this is an error condition */
768 cleanup_exit(exitcode);
769 return 0; /* placate compiler warning */