Revamp SSH authentication code so that user interaction is more
[u/mdw/putty] / windows / winplink.c
CommitLineData
12dc4ec0 1/*
f4ff9455 2 * PLink - a Windows command-line (stdin/stdout) variant of PuTTY.
12dc4ec0 3 */
4
12dc4ec0 5#include <stdio.h>
49bad831 6#include <stdlib.h>
2b0c045b 7#include <assert.h>
12dc4ec0 8#include <stdarg.h>
9
32874aea 10#define PUTTY_DO_GLOBALS /* actually _define_ globals */
12dc4ec0 11#include "putty.h"
a9422f39 12#include "storage.h"
8df7a775 13#include "tree234.h"
12dc4ec0 14
604fab0c 15#define WM_AGENT_CALLBACK (WM_APP + 4)
c44bf5bd 16
5471d09a 17#define MAX_STDIN_BACKLOG 4096
18
c44bf5bd 19struct agent_callback {
20 void (*callback)(void *, void *, int);
21 void *callback_ctx;
22 void *data;
23 int len;
24};
25
32874aea 26void fatalbox(char *p, ...)
27{
12dc4ec0 28 va_list ap;
49bad831 29 fprintf(stderr, "FATAL ERROR: ");
1709795f 30 va_start(ap, p);
31 vfprintf(stderr, p, ap);
32 va_end(ap);
33 fputc('\n', stderr);
1709795f 34 cleanup_exit(1);
35}
36void modalfatalbox(char *p, ...)
37{
38 va_list ap;
39 fprintf(stderr, "FATAL ERROR: ");
12dc4ec0 40 va_start(ap, p);
41 vfprintf(stderr, p, ap);
42 va_end(ap);
43 fputc('\n', stderr);
93b581bd 44 cleanup_exit(1);
12dc4ec0 45}
a8327734 46void connection_fatal(void *frontend, char *p, ...)
32874aea 47{
8d5de777 48 va_list ap;
49bad831 49 fprintf(stderr, "FATAL ERROR: ");
8d5de777 50 va_start(ap, p);
51 vfprintf(stderr, p, ap);
52 va_end(ap);
53 fputc('\n', stderr);
93b581bd 54 cleanup_exit(1);
8d5de777 55}
c0a81592 56void cmdline_error(char *p, ...)
57{
58 va_list ap;
59 fprintf(stderr, "plink: ");
60 va_start(ap, p);
61 vfprintf(stderr, p, ap);
62 va_end(ap);
63 fputc('\n', stderr);
64 exit(1);
65}
12dc4ec0 66
0965bee0 67HANDLE inhandle, outhandle, errhandle;
6f34e365 68DWORD orig_console_mode;
69
8df7a775 70WSAEVENT netevent;
71
6b78788a 72static Backend *back;
73static void *backhandle;
3ea863a3 74static Config cfg;
6b78788a 75
887035a5 76int term_ldisc(Terminal *term, int mode)
32874aea 77{
78 return FALSE;
79}
b9d7bcad 80void ldisc_update(void *frontend, int echo, int edit)
32874aea 81{
0965bee0 82 /* Update stdin read mode to reflect changes in line discipline. */
83 DWORD mode;
84
85 mode = ENABLE_PROCESSED_INPUT;
86 if (echo)
32874aea 87 mode = mode | ENABLE_ECHO_INPUT;
0965bee0 88 else
32874aea 89 mode = mode & ~ENABLE_ECHO_INPUT;
0965bee0 90 if (edit)
32874aea 91 mode = mode | ENABLE_LINE_INPUT;
0965bee0 92 else
32874aea 93 mode = mode & ~ENABLE_LINE_INPUT;
0965bee0 94 SetConsoleMode(inhandle, mode);
95}
96
c6ccd5c2 97char *get_ttymode(void *frontend, const char *mode) { return NULL; }
98
5471d09a 99struct input_data {
100 DWORD len;
101 char buffer[4096];
102 HANDLE event, eventback;
103};
104
32874aea 105static DWORD WINAPI stdin_read_thread(void *param)
106{
107 struct input_data *idata = (struct input_data *) param;
12dc4ec0 108 HANDLE inhandle;
109
110 inhandle = GetStdHandle(STD_INPUT_HANDLE);
111
112 while (ReadFile(inhandle, idata->buffer, sizeof(idata->buffer),
32874aea 113 &idata->len, NULL) && idata->len > 0) {
114 SetEvent(idata->event);
115 WaitForSingleObject(idata->eventback, INFINITE);
12dc4ec0 116 }
117
118 idata->len = 0;
119 SetEvent(idata->event);
120
121 return 0;
122}
123
5471d09a 124struct output_data {
125 DWORD len, lenwritten;
126 int writeret;
127 char *buffer;
128 int is_stderr, done;
129 HANDLE event, eventback;
130 int busy;
131};
132
133static DWORD WINAPI stdout_write_thread(void *param)
134{
135 struct output_data *odata = (struct output_data *) param;
136 HANDLE outhandle, errhandle;
137
138 outhandle = GetStdHandle(STD_OUTPUT_HANDLE);
139 errhandle = GetStdHandle(STD_ERROR_HANDLE);
140
141 while (1) {
142 WaitForSingleObject(odata->eventback, INFINITE);
143 if (odata->done)
144 break;
145 odata->writeret =
146 WriteFile(odata->is_stderr ? errhandle : outhandle,
147 odata->buffer, odata->len, &odata->lenwritten, NULL);
148 SetEvent(odata->event);
149 }
150
151 return 0;
152}
153
154bufchain stdout_data, stderr_data;
155struct output_data odata, edata;
156
157void try_output(int is_stderr)
158{
159 struct output_data *data = (is_stderr ? &edata : &odata);
160 void *senddata;
161 int sendlen;
162
163 if (!data->busy) {
164 bufchain_prefix(is_stderr ? &stderr_data : &stdout_data,
165 &senddata, &sendlen);
166 data->buffer = senddata;
167 data->len = sendlen;
168 SetEvent(data->eventback);
169 data->busy = 1;
170 }
171}
172
9fab77dc 173int from_backend(void *frontend_handle, int is_stderr,
174 const char *data, int len)
5471d09a 175{
5471d09a 176 int osize, esize;
177
178 if (is_stderr) {
179 bufchain_add(&stderr_data, data, len);
180 try_output(1);
181 } else {
182 bufchain_add(&stdout_data, data, len);
183 try_output(0);
184 }
185
186 osize = bufchain_size(&stdout_data);
187 esize = bufchain_size(&stderr_data);
188
189 return osize + esize;
190}
191
edd0cb8a 192int from_backend_untrusted(void *frontend_handle, const char *data, int len)
193{
194 /*
195 * No "untrusted" output should get here (the way the code is
196 * currently, it's all diverted by FLAG_STDERR).
197 */
198 assert(!"Unexpected call to from_backend_untrusted()");
199 return 0; /* not reached */
200}
201
202int get_userpass_input(prompts_t *p, unsigned char *in, int inlen)
203{
204 int ret;
205 ret = cmdline_get_passwd_input(p, in, inlen);
206 if (ret == -1)
207 ret = console_get_userpass_input(p, in, inlen);
208 return ret;
209}
210
c44bf5bd 211static DWORD main_thread_id;
212
213void agent_schedule_callback(void (*callback)(void *, void *, int),
214 void *callback_ctx, void *data, int len)
215{
216 struct agent_callback *c = snew(struct agent_callback);
217 c->callback = callback;
218 c->callback_ctx = callback_ctx;
219 c->data = data;
220 c->len = len;
221 PostThreadMessage(main_thread_id, WM_AGENT_CALLBACK, 0, (LPARAM)c);
222}
223
d8426c54 224/*
225 * Short description of parameters.
226 */
227static void usage(void)
228{
229 printf("PuTTY Link: command-line connection utility\n");
230 printf("%s\n", ver);
231 printf("Usage: plink [options] [user@]host [command]\n");
e672967c 232 printf(" (\"host\" can also be a PuTTY saved session name)\n");
d8426c54 233 printf("Options:\n");
2285d016 234 printf(" -V print version information and exit\n");
235 printf(" -pgpfp print PGP key fingerprints and exit\n");
d8426c54 236 printf(" -v show verbose messages\n");
e2a197cf 237 printf(" -load sessname Load settings from saved session\n");
238 printf(" -ssh -telnet -rlogin -raw\n");
afd4d0d2 239 printf(" force use of a particular protocol\n");
d8426c54 240 printf(" -P port connect to specified port\n");
e2a197cf 241 printf(" -l user connect with specified username\n");
e2a197cf 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");
dbe6c525 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");
e2a197cf 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");
05581745 255 printf(" -4 -6 force use of IPv4 or IPv6\n");
e2a197cf 256 printf(" -C enable compression\n");
257 printf(" -i key private key file for authentication\n");
54018d95 258 printf(" -m file read remote command(s) from file\n");
4d1cdf5d 259 printf(" -s remote command is an SSH subsystem (SSH-2 only)\n");
b72c366d 260 printf(" -N don't start a shell/command (SSH-2 only)\n");
dc108ebc 261 exit(1);
262}
263
264static void version(void)
265{
266 printf("plink: %s\n", ver);
d8426c54 267 exit(1);
268}
269
32874aea 270char *do_select(SOCKET skt, int startup)
271{
8df7a775 272 int events;
273 if (startup) {
3ad9d396 274 events = (FD_CONNECT | FD_READ | FD_WRITE |
275 FD_OOB | FD_CLOSE | FD_ACCEPT);
8df7a775 276 } else {
277 events = 0;
278 }
7440fd44 279 if (p_WSAEventSelect(skt, netevent, events) == SOCKET_ERROR) {
280 switch (p_WSAGetLastError()) {
32874aea 281 case WSAENETDOWN:
282 return "Network is down";
283 default:
7440fd44 284 return "WSAEventSelect(): unknown error";
32874aea 285 }
8df7a775 286 }
287 return NULL;
288}
289
32874aea 290int main(int argc, char **argv)
291{
5471d09a 292 WSAEVENT stdinevent, stdoutevent, stderrevent;
293 HANDLE handles[4];
294 DWORD in_threadid, out_threadid, err_threadid;
12dc4ec0 295 struct input_data idata;
5fc71a3d 296 int reading = FALSE;
12dc4ec0 297 int sending;
d8426c54 298 int portnumber = -1;
8df7a775 299 SOCKET *sklist;
300 int skcount, sksize;
301 int connopen;
d8d6c7e5 302 int exitcode;
86256dc6 303 int errors;
4d1cdf5d 304 int use_subsystem = 0;
39934deb 305 long now, next;
12dc4ec0 306
32874aea 307 sklist = NULL;
308 skcount = sksize = 0;
c9bdcd96 309 /*
310 * Initialise port and protocol to sensible defaults. (These
311 * will be overridden by more or less anything.)
312 */
313 default_protocol = PROT_SSH;
314 default_port = 22;
8df7a775 315
67779be7 316 flags = FLAG_STDERR;
12dc4ec0 317 /*
318 * Process the command line.
319 */
a9422f39 320 do_defaults(NULL, &cfg);
18e62ad8 321 loaded_session = FALSE;
e7a7383f 322 default_protocol = cfg.protocol;
323 default_port = cfg.port;
86256dc6 324 errors = 0;
8cb9c947 325 {
32874aea 326 /*
327 * Override the default protocol if PLINK_PROTOCOL is set.
328 */
329 char *p = getenv("PLINK_PROTOCOL");
330 int i;
331 if (p) {
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;
337 break;
338 }
339 }
340 }
8cb9c947 341 }
12dc4ec0 342 while (--argc) {
32874aea 343 char *p = *++argv;
344 if (*p == '-') {
5555d393 345 int ret = cmdline_process_param(p, (argc > 1 ? argv[1] : NULL),
346 1, &cfg);
c0a81592 347 if (ret == -2) {
348 fprintf(stderr,
349 "plink: option \"%s\" requires an argument\n", p);
86256dc6 350 errors = 1;
c0a81592 351 } else if (ret == 2) {
352 --argc, ++argv;
353 } else if (ret == 1) {
354 continue;
ff2ae367 355 } else if (!strcmp(p, "-batch")) {
c0a81592 356 console_batch_mode = 1;
4d1cdf5d 357 } else if (!strcmp(p, "-s")) {
358 /* Save status to write to cfg later. */
359 use_subsystem = 1;
dc108ebc 360 } else if (!strcmp(p, "-V")) {
361 version();
2285d016 362 } else if (!strcmp(p, "-pgpfp")) {
363 pgp_fingerprints();
364 exit(1);
86256dc6 365 } else {
366 fprintf(stderr, "plink: unknown option \"%s\"\n", p);
367 errors = 1;
32874aea 368 }
12dc4ec0 369 } else if (*p) {
32874aea 370 if (!*cfg.host) {
371 char *q = p;
372 /*
373 * If the hostname starts with "telnet:", set the
374 * protocol to Telnet and process the string as a
375 * Telnet URL.
376 */
377 if (!strncmp(q, "telnet:", 7)) {
378 char c;
379
380 q += 7;
381 if (q[0] == '/' && q[1] == '/')
382 q += 2;
383 cfg.protocol = PROT_TELNET;
384 p = q;
385 while (*p && *p != ':' && *p != '/')
386 p++;
387 c = *p;
388 if (*p)
389 *p++ = '\0';
390 if (c == ':')
391 cfg.port = atoi(p);
392 else
393 cfg.port = -1;
394 strncpy(cfg.host, q, sizeof(cfg.host) - 1);
395 cfg.host[sizeof(cfg.host) - 1] = '\0';
396 } else {
3608528b 397 char *r, *user, *host;
32874aea 398 /*
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 ",").
402 */
403 r = strchr(p, ',');
404 if (r) {
405 int i, j;
406 for (i = 0; backends[i].backend != NULL; i++) {
407 j = strlen(backends[i].name);
408 if (j == r - p &&
409 !memcmp(backends[i].name, p, j)) {
410 default_protocol = cfg.protocol =
411 backends[i].protocol;
412 portnumber =
413 backends[i].backend->default_port;
414 p = r + 1;
415 break;
416 }
417 }
418 }
419
420 /*
3608528b 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.
32874aea 425 */
426 r = strrchr(p, '@');
427 if (r == p)
428 p++, r = NULL; /* discount initial @ */
3608528b 429 if (r) {
430 *r++ = '\0';
431 user = p, host = r;
432 } else {
433 user = NULL, host = p;
434 }
435
436 /*
437 * Now attempt to load a saved session with the
438 * same name as the hostname.
439 */
440 {
32874aea 441 Config cfg2;
3608528b 442 do_defaults(host, &cfg2);
18e62ad8 443 if (loaded_session || cfg2.host[0] == '\0') {
32874aea 444 /* No settings for this host; use defaults */
18e62ad8 445 /* (or session was already loaded with -load) */
3608528b 446 strncpy(cfg.host, host, sizeof(cfg.host) - 1);
32874aea 447 cfg.host[sizeof(cfg.host) - 1] = '\0';
448 cfg.port = default_port;
449 } else {
450 cfg = cfg2;
32874aea 451 }
3608528b 452 }
453
454 if (user) {
455 /* Patch in specified username. */
456 strncpy(cfg.username, user,
457 sizeof(cfg.username) - 1);
32874aea 458 cfg.username[sizeof(cfg.username) - 1] = '\0';
32874aea 459 }
3608528b 460
32874aea 461 }
462 } else {
385528da 463 char *command;
464 int cmdlen, cmdsize;
465 cmdlen = cmdsize = 0;
466 command = NULL;
467
468 while (argc) {
469 while (*p) {
470 if (cmdlen >= cmdsize) {
471 cmdsize = cmdlen + 512;
3d88e64d 472 command = sresize(command, cmdsize, char);
385528da 473 }
474 command[cmdlen++]=*p++;
475 }
476 if (cmdlen >= cmdsize) {
477 cmdsize = cmdlen + 512;
3d88e64d 478 command = sresize(command, cmdsize, char);
385528da 479 }
480 command[cmdlen++]=' '; /* always add trailing space */
481 if (--argc) p = *++argv;
32874aea 482 }
385528da 483 if (cmdlen) command[--cmdlen]='\0';
484 /* change trailing blank to NUL */
485 cfg.remote_cmd_ptr = command;
486 cfg.remote_cmd_ptr2 = NULL;
32874aea 487 cfg.nopty = TRUE; /* command => no terminal */
385528da 488
32874aea 489 break; /* done with cmdline */
490 }
12dc4ec0 491 }
492 }
493
86256dc6 494 if (errors)
495 return 1;
496
d8426c54 497 if (!*cfg.host) {
32874aea 498 usage();
d8426c54 499 }
d8426c54 500
449925a6 501 /*
502 * Trim leading whitespace off the hostname if it's there.
503 */
504 {
505 int space = strspn(cfg.host, " \t");
506 memmove(cfg.host, cfg.host+space, 1+strlen(cfg.host)-space);
507 }
508
509 /* See if host is of the form user@host */
510 if (cfg.host[0] != '\0') {
5dd103a8 511 char *atsign = strrchr(cfg.host, '@');
449925a6 512 /* Make sure we're not overflowing the user field */
513 if (atsign) {
514 if (atsign - cfg.host < sizeof cfg.username) {
515 strncpy(cfg.username, cfg.host, atsign - cfg.host);
516 cfg.username[atsign - cfg.host] = '\0';
517 }
518 memmove(cfg.host, atsign + 1, 1 + strlen(atsign + 1));
519 }
520 }
521
522 /*
c0a81592 523 * Perform command-line overrides on session configuration.
524 */
5555d393 525 cmdline_run_saved(&cfg);
c0a81592 526
527 /*
4d1cdf5d 528 * Apply subsystem status.
529 */
530 if (use_subsystem)
531 cfg.ssh_subsys = TRUE;
532
533 /*
449925a6 534 * Trim a colon suffix off the hostname if it's there.
535 */
536 cfg.host[strcspn(cfg.host, ":")] = '\0';
537
cae0c023 538 /*
539 * Remove any remaining whitespace from the hostname.
540 */
541 {
542 int p1 = 0, p2 = 0;
543 while (cfg.host[p2] != '\0') {
544 if (cfg.host[p2] != ' ' && cfg.host[p2] != '\t') {
545 cfg.host[p1] = cfg.host[p2];
546 p1++;
547 }
548 p2++;
549 }
550 cfg.host[p1] = '\0';
551 }
552
a79e1969 553 if (!cfg.remote_cmd_ptr && !*cfg.remote_cmd)
32874aea 554 flags |= FLAG_INTERACTIVE;
67779be7 555
12dc4ec0 556 /*
557 * Select protocol. This is farmed out into a table in a
558 * separate file to enable an ssh-free variant.
559 */
560 {
32874aea 561 int i;
562 back = NULL;
563 for (i = 0; backends[i].backend != NULL; i++)
564 if (backends[i].protocol == cfg.protocol) {
565 back = backends[i].backend;
566 break;
567 }
568 if (back == NULL) {
569 fprintf(stderr,
570 "Internal fault: Unsupported protocol found\n");
571 return 1;
572 }
12dc4ec0 573 }
574
575 /*
8cb9c947 576 * Select port.
577 */
578 if (portnumber != -1)
32874aea 579 cfg.port = portnumber;
8cb9c947 580
7440fd44 581 sk_init();
582 if (p_WSAEventSelect == NULL) {
583 fprintf(stderr, "Plink requires WinSock 2\n");
12dc4ec0 584 return 1;
585 }
586
587 /*
588 * Start up the connection.
589 */
8df7a775 590 netevent = CreateEvent(NULL, FALSE, FALSE, NULL);
12dc4ec0 591 {
cbe2d68f 592 const char *error;
12dc4ec0 593 char *realhost;
2184a5d9 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);
12dc4ec0 597
86916870 598 error = back->init(NULL, &backhandle, &cfg, cfg.host, cfg.port,
79bf227b 599 &realhost, nodelay, cfg.tcp_keepalives);
12dc4ec0 600 if (error) {
601 fprintf(stderr, "Unable to open connection:\n%s", error);
602 return 1;
603 }
c229ef97 604 logctx = log_init(NULL, &cfg);
a8327734 605 back->provide_logctx(backhandle, logctx);
d3fef4a5 606 console_provide_logctx(logctx);
6e1ebb76 607 sfree(realhost);
12dc4ec0 608 }
8df7a775 609 connopen = 1;
12dc4ec0 610
12dc4ec0 611 stdinevent = CreateEvent(NULL, FALSE, FALSE, NULL);
5471d09a 612 stdoutevent = CreateEvent(NULL, FALSE, FALSE, NULL);
613 stderrevent = CreateEvent(NULL, FALSE, FALSE, NULL);
12dc4ec0 614
0965bee0 615 inhandle = GetStdHandle(STD_INPUT_HANDLE);
12dc4ec0 616 outhandle = GetStdHandle(STD_OUTPUT_HANDLE);
fe50e814 617 errhandle = GetStdHandle(STD_ERROR_HANDLE);
12dc4ec0 618 /*
12dc4ec0 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
621 * a console.
622 */
f8efb0d5 623 GetConsoleMode(inhandle, &orig_console_mode);
624 SetConsoleMode(inhandle, ENABLE_PROCESSED_INPUT);
625
626 main_thread_id = GetCurrentThreadId();
627
12dc4ec0 628 handles[0] = netevent;
629 handles[1] = stdinevent;
5471d09a 630 handles[2] = stdoutevent;
631 handles[3] = stderrevent;
12dc4ec0 632 sending = FALSE;
5471d09a 633
634 /*
635 * Create spare threads to write to stdout and stderr, so we
636 * can arrange asynchronous writes.
637 */
638 odata.event = stdoutevent;
639 odata.eventback = CreateEvent(NULL, FALSE, FALSE, NULL);
640 odata.is_stderr = 0;
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");
93b581bd 645 cleanup_exit(1);
5471d09a 646 }
647 edata.event = stderrevent;
648 edata.eventback = CreateEvent(NULL, FALSE, FALSE, NULL);
649 edata.is_stderr = 1;
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");
93b581bd 654 cleanup_exit(1);
5471d09a 655 }
656
39934deb 657 now = GETTICKCOUNT();
658
12dc4ec0 659 while (1) {
32874aea 660 int n;
39934deb 661 DWORD ticks;
32874aea 662
51470298 663 if (!sending && back->sendok(backhandle)) {
32874aea 664 /*
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:
667 *
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?
673 *
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.
679 */
680 idata.event = stdinevent;
681 idata.eventback = CreateEvent(NULL, FALSE, FALSE, NULL);
682 if (!CreateThread(NULL, 0, stdin_read_thread,
5471d09a 683 &idata, 0, &in_threadid)) {
684 fprintf(stderr, "Unable to create input thread\n");
93b581bd 685 cleanup_exit(1);
32874aea 686 }
687 sending = TRUE;
5fc71a3d 688 reading = TRUE;
32874aea 689 }
690
39934deb 691 if (run_timers(now, &next)) {
692 ticks = next - GETTICKCOUNT();
693 if (ticks < 0) ticks = 0; /* just in case */
694 } else {
695 ticks = INFINITE;
696 }
697
698 n = MsgWaitForMultipleObjects(4, handles, FALSE, ticks,
c44bf5bd 699 QS_POSTMESSAGE);
39934deb 700 if (n == WAIT_OBJECT_0 + 0) {
32874aea 701 WSANETWORKEVENTS things;
8df7a775 702 SOCKET socket;
d2371c81 703 extern SOCKET first_socket(int *), next_socket(int *);
8df7a775 704 extern int select_result(WPARAM, LPARAM);
32874aea 705 int i, socketstate;
706
707 /*
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.
712 */
713 /* Count the active sockets. */
714 i = 0;
715 for (socket = first_socket(&socketstate);
716 socket != INVALID_SOCKET;
717 socket = next_socket(&socketstate)) i++;
718
719 /* Expand the buffer if necessary. */
720 if (i > sksize) {
721 sksize = i + 16;
3d88e64d 722 sklist = sresize(sklist, sksize, SOCKET);
32874aea 723 }
724
725 /* Retrieve the sockets into sklist. */
726 skcount = 0;
727 for (socket = first_socket(&socketstate);
728 socket != INVALID_SOCKET;
d2371c81 729 socket = next_socket(&socketstate)) {
32874aea 730 sklist[skcount++] = socket;
731 }
732
733 /* Now we're done enumerating; go through the list. */
734 for (i = 0; i < skcount; i++) {
735 WPARAM wp;
736 socket = sklist[i];
737 wp = (WPARAM) socket;
7440fd44 738 if (!p_WSAEnumNetworkEvents(socket, NULL, &things)) {
64cdd21b 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},
746 };
747 int e;
748
32874aea 749 noise_ultralight(socket);
750 noise_ultralight(things.lNetworkEvents);
d74d141c 751
64cdd21b 752 for (e = 0; e < lenof(eventtypes); e++)
753 if (things.lNetworkEvents & eventtypes[e].mask) {
754 LPARAM lp;
755 int err = things.iErrorCode[eventtypes[e].bit];
756 lp = WSAMAKESELECTREPLY(eventtypes[e].mask, err);
757 connopen &= select_result(wp, lp);
758 }
8df7a775 759 }
760 }
39934deb 761 } else if (n == WAIT_OBJECT_0 + 1) {
5471d09a 762 reading = 0;
32874aea 763 noise_ultralight(idata.len);
51470298 764 if (connopen && back->socket(backhandle) != NULL) {
42856df4 765 if (idata.len > 0) {
51470298 766 back->send(backhandle, idata.buffer, idata.len);
42856df4 767 } else {
51470298 768 back->special(backhandle, TS_EOF);
42856df4 769 }
32874aea 770 }
39934deb 771 } else if (n == WAIT_OBJECT_0 + 2) {
5471d09a 772 odata.busy = 0;
773 if (!odata.writeret) {
774 fprintf(stderr, "Unable to write to standard output\n");
93b581bd 775 cleanup_exit(0);
5471d09a 776 }
777 bufchain_consume(&stdout_data, odata.lenwritten);
778 if (bufchain_size(&stdout_data) > 0)
779 try_output(0);
51470298 780 if (connopen && back->socket(backhandle) != NULL) {
781 back->unthrottle(backhandle, bufchain_size(&stdout_data) +
42856df4 782 bufchain_size(&stderr_data));
783 }
39934deb 784 } else if (n == WAIT_OBJECT_0 + 3) {
5471d09a 785 edata.busy = 0;
786 if (!edata.writeret) {
787 fprintf(stderr, "Unable to write to standard output\n");
93b581bd 788 cleanup_exit(0);
5471d09a 789 }
790 bufchain_consume(&stderr_data, edata.lenwritten);
791 if (bufchain_size(&stderr_data) > 0)
792 try_output(1);
51470298 793 if (connopen && back->socket(backhandle) != NULL) {
794 back->unthrottle(backhandle, bufchain_size(&stdout_data) +
42856df4 795 bufchain_size(&stderr_data));
796 }
39934deb 797 } else if (n == WAIT_OBJECT_0 + 4) {
c44bf5bd 798 MSG msg;
799 while (PeekMessage(&msg, INVALID_HANDLE_VALUE,
800 WM_AGENT_CALLBACK, WM_AGENT_CALLBACK,
801 PM_REMOVE)) {
802 struct agent_callback *c = (struct agent_callback *)msg.lParam;
803 c->callback(c->callback_ctx, c->data, c->len);
804 sfree(c);
805 }
5471d09a 806 }
39934deb 807
808 if (n == WAIT_TIMEOUT) {
809 now = next;
810 } else {
811 now = GETTICKCOUNT();
812 }
813
51470298 814 if (!reading && back->sendbuffer(backhandle) < MAX_STDIN_BACKLOG) {
32874aea 815 SetEvent(idata.eventback);
5471d09a 816 reading = 1;
32874aea 817 }
51470298 818 if ((!connopen || back->socket(backhandle) == NULL) &&
42856df4 819 bufchain_size(&stdout_data) == 0 &&
820 bufchain_size(&stderr_data) == 0)
32874aea 821 break; /* we closed the connection */
12dc4ec0 822 }
51470298 823 exitcode = back->exitcode(backhandle);
d8d6c7e5 824 if (exitcode < 0) {
825 fprintf(stderr, "Remote process exit code unavailable\n");
826 exitcode = 1; /* this is an error condition */
827 }
7440fd44 828 cleanup_exit(exitcode);
829 return 0; /* placate compiler warning */
12dc4ec0 830}