Integrate unfix.org's IPv6 patches up to level 10, with rather a lot
[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
c44bf5bd 15#define WM_AGENT_CALLBACK (WM_XUSER + 4)
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
5471d09a 97struct input_data {
98 DWORD len;
99 char buffer[4096];
100 HANDLE event, eventback;
101};
102
32874aea 103static DWORD WINAPI stdin_read_thread(void *param)
104{
105 struct input_data *idata = (struct input_data *) param;
12dc4ec0 106 HANDLE inhandle;
107
108 inhandle = GetStdHandle(STD_INPUT_HANDLE);
109
110 while (ReadFile(inhandle, idata->buffer, sizeof(idata->buffer),
32874aea 111 &idata->len, NULL) && idata->len > 0) {
112 SetEvent(idata->event);
113 WaitForSingleObject(idata->eventback, INFINITE);
12dc4ec0 114 }
115
116 idata->len = 0;
117 SetEvent(idata->event);
118
119 return 0;
120}
121
5471d09a 122struct output_data {
123 DWORD len, lenwritten;
124 int writeret;
125 char *buffer;
126 int is_stderr, done;
127 HANDLE event, eventback;
128 int busy;
129};
130
131static DWORD WINAPI stdout_write_thread(void *param)
132{
133 struct output_data *odata = (struct output_data *) param;
134 HANDLE outhandle, errhandle;
135
136 outhandle = GetStdHandle(STD_OUTPUT_HANDLE);
137 errhandle = GetStdHandle(STD_ERROR_HANDLE);
138
139 while (1) {
140 WaitForSingleObject(odata->eventback, INFINITE);
141 if (odata->done)
142 break;
143 odata->writeret =
144 WriteFile(odata->is_stderr ? errhandle : outhandle,
145 odata->buffer, odata->len, &odata->lenwritten, NULL);
146 SetEvent(odata->event);
147 }
148
149 return 0;
150}
151
152bufchain stdout_data, stderr_data;
153struct output_data odata, edata;
154
155void try_output(int is_stderr)
156{
157 struct output_data *data = (is_stderr ? &edata : &odata);
158 void *senddata;
159 int sendlen;
160
161 if (!data->busy) {
162 bufchain_prefix(is_stderr ? &stderr_data : &stdout_data,
163 &senddata, &sendlen);
164 data->buffer = senddata;
165 data->len = sendlen;
166 SetEvent(data->eventback);
167 data->busy = 1;
168 }
169}
170
9fab77dc 171int from_backend(void *frontend_handle, int is_stderr,
172 const char *data, int len)
5471d09a 173{
5471d09a 174 int osize, esize;
175
176 if (is_stderr) {
177 bufchain_add(&stderr_data, data, len);
178 try_output(1);
179 } else {
180 bufchain_add(&stdout_data, data, len);
181 try_output(0);
182 }
183
184 osize = bufchain_size(&stdout_data);
185 esize = bufchain_size(&stderr_data);
186
187 return osize + esize;
188}
189
c44bf5bd 190static DWORD main_thread_id;
191
192void agent_schedule_callback(void (*callback)(void *, void *, int),
193 void *callback_ctx, void *data, int len)
194{
195 struct agent_callback *c = snew(struct agent_callback);
196 c->callback = callback;
197 c->callback_ctx = callback_ctx;
198 c->data = data;
199 c->len = len;
200 PostThreadMessage(main_thread_id, WM_AGENT_CALLBACK, 0, (LPARAM)c);
201}
202
d8426c54 203/*
204 * Short description of parameters.
205 */
206static void usage(void)
207{
208 printf("PuTTY Link: command-line connection utility\n");
209 printf("%s\n", ver);
210 printf("Usage: plink [options] [user@]host [command]\n");
e672967c 211 printf(" (\"host\" can also be a PuTTY saved session name)\n");
d8426c54 212 printf("Options:\n");
c9a13be6 213 printf(" -V print version information\n");
d8426c54 214 printf(" -v show verbose messages\n");
e2a197cf 215 printf(" -load sessname Load settings from saved session\n");
216 printf(" -ssh -telnet -rlogin -raw\n");
afd4d0d2 217 printf(" force use of a particular protocol\n");
d8426c54 218 printf(" -P port connect to specified port\n");
e2a197cf 219 printf(" -l user connect with specified username\n");
96621a84 220 printf(" -m file read remote command(s) from file\n");
e2a197cf 221 printf(" -batch disable all interactive prompts\n");
222 printf("The following options only apply to SSH connections:\n");
223 printf(" -pw passw login with specified password\n");
dbe6c525 224 printf(" -D [listen-IP:]listen-port\n");
225 printf(" Dynamic SOCKS-based port forwarding\n");
226 printf(" -L [listen-IP:]listen-port:host:port\n");
227 printf(" Forward local port to remote address\n");
228 printf(" -R [listen-IP:]listen-port:host:port\n");
229 printf(" Forward remote port to local address\n");
e2a197cf 230 printf(" -X -x enable / disable X11 forwarding\n");
231 printf(" -A -a enable / disable agent forwarding\n");
232 printf(" -t -T enable / disable pty allocation\n");
233 printf(" -1 -2 force use of particular protocol version\n");
05581745 234 printf(" -4 -6 force use of IPv4 or IPv6\n");
e2a197cf 235 printf(" -C enable compression\n");
236 printf(" -i key private key file for authentication\n");
4d1cdf5d 237 printf(" -s remote command is an SSH subsystem (SSH-2 only)\n");
b72c366d 238 printf(" -N don't start a shell/command (SSH-2 only)\n");
dc108ebc 239 exit(1);
240}
241
242static void version(void)
243{
244 printf("plink: %s\n", ver);
d8426c54 245 exit(1);
246}
247
32874aea 248char *do_select(SOCKET skt, int startup)
249{
8df7a775 250 int events;
251 if (startup) {
3ad9d396 252 events = (FD_CONNECT | FD_READ | FD_WRITE |
253 FD_OOB | FD_CLOSE | FD_ACCEPT);
8df7a775 254 } else {
255 events = 0;
256 }
7440fd44 257 if (p_WSAEventSelect(skt, netevent, events) == SOCKET_ERROR) {
258 switch (p_WSAGetLastError()) {
32874aea 259 case WSAENETDOWN:
260 return "Network is down";
261 default:
7440fd44 262 return "WSAEventSelect(): unknown error";
32874aea 263 }
8df7a775 264 }
265 return NULL;
266}
267
32874aea 268int main(int argc, char **argv)
269{
5471d09a 270 WSAEVENT stdinevent, stdoutevent, stderrevent;
271 HANDLE handles[4];
272 DWORD in_threadid, out_threadid, err_threadid;
12dc4ec0 273 struct input_data idata;
5471d09a 274 int reading;
12dc4ec0 275 int sending;
d8426c54 276 int portnumber = -1;
8df7a775 277 SOCKET *sklist;
278 int skcount, sksize;
279 int connopen;
d8d6c7e5 280 int exitcode;
86256dc6 281 int errors;
4d1cdf5d 282 int use_subsystem = 0;
39934deb 283 long now, next;
12dc4ec0 284
ff2ae367 285 ssh_get_line = console_get_line;
67779be7 286
32874aea 287 sklist = NULL;
288 skcount = sksize = 0;
c9bdcd96 289 /*
290 * Initialise port and protocol to sensible defaults. (These
291 * will be overridden by more or less anything.)
292 */
293 default_protocol = PROT_SSH;
294 default_port = 22;
8df7a775 295
67779be7 296 flags = FLAG_STDERR;
12dc4ec0 297 /*
298 * Process the command line.
299 */
a9422f39 300 do_defaults(NULL, &cfg);
18e62ad8 301 loaded_session = FALSE;
e7a7383f 302 default_protocol = cfg.protocol;
303 default_port = cfg.port;
86256dc6 304 errors = 0;
8cb9c947 305 {
32874aea 306 /*
307 * Override the default protocol if PLINK_PROTOCOL is set.
308 */
309 char *p = getenv("PLINK_PROTOCOL");
310 int i;
311 if (p) {
312 for (i = 0; backends[i].backend != NULL; i++) {
313 if (!strcmp(backends[i].name, p)) {
314 default_protocol = cfg.protocol = backends[i].protocol;
315 default_port = cfg.port =
316 backends[i].backend->default_port;
317 break;
318 }
319 }
320 }
8cb9c947 321 }
12dc4ec0 322 while (--argc) {
32874aea 323 char *p = *++argv;
324 if (*p == '-') {
5555d393 325 int ret = cmdline_process_param(p, (argc > 1 ? argv[1] : NULL),
326 1, &cfg);
c0a81592 327 if (ret == -2) {
328 fprintf(stderr,
329 "plink: option \"%s\" requires an argument\n", p);
86256dc6 330 errors = 1;
c0a81592 331 } else if (ret == 2) {
332 --argc, ++argv;
333 } else if (ret == 1) {
334 continue;
ff2ae367 335 } else if (!strcmp(p, "-batch")) {
c0a81592 336 console_batch_mode = 1;
4d1cdf5d 337 } else if (!strcmp(p, "-s")) {
338 /* Save status to write to cfg later. */
339 use_subsystem = 1;
dc108ebc 340 } else if (!strcmp(p, "-V")) {
341 version();
86256dc6 342 } else {
343 fprintf(stderr, "plink: unknown option \"%s\"\n", p);
344 errors = 1;
32874aea 345 }
12dc4ec0 346 } else if (*p) {
32874aea 347 if (!*cfg.host) {
348 char *q = p;
349 /*
350 * If the hostname starts with "telnet:", set the
351 * protocol to Telnet and process the string as a
352 * Telnet URL.
353 */
354 if (!strncmp(q, "telnet:", 7)) {
355 char c;
356
357 q += 7;
358 if (q[0] == '/' && q[1] == '/')
359 q += 2;
360 cfg.protocol = PROT_TELNET;
361 p = q;
362 while (*p && *p != ':' && *p != '/')
363 p++;
364 c = *p;
365 if (*p)
366 *p++ = '\0';
367 if (c == ':')
368 cfg.port = atoi(p);
369 else
370 cfg.port = -1;
371 strncpy(cfg.host, q, sizeof(cfg.host) - 1);
372 cfg.host[sizeof(cfg.host) - 1] = '\0';
373 } else {
3608528b 374 char *r, *user, *host;
32874aea 375 /*
376 * Before we process the [user@]host string, we
377 * first check for the presence of a protocol
378 * prefix (a protocol name followed by ",").
379 */
380 r = strchr(p, ',');
381 if (r) {
382 int i, j;
383 for (i = 0; backends[i].backend != NULL; i++) {
384 j = strlen(backends[i].name);
385 if (j == r - p &&
386 !memcmp(backends[i].name, p, j)) {
387 default_protocol = cfg.protocol =
388 backends[i].protocol;
389 portnumber =
390 backends[i].backend->default_port;
391 p = r + 1;
392 break;
393 }
394 }
395 }
396
397 /*
3608528b 398 * A nonzero length string followed by an @ is treated
399 * as a username. (We discount an _initial_ @.) The
400 * rest of the string (or the whole string if no @)
401 * is treated as a session name and/or hostname.
32874aea 402 */
403 r = strrchr(p, '@');
404 if (r == p)
405 p++, r = NULL; /* discount initial @ */
3608528b 406 if (r) {
407 *r++ = '\0';
408 user = p, host = r;
409 } else {
410 user = NULL, host = p;
411 }
412
413 /*
414 * Now attempt to load a saved session with the
415 * same name as the hostname.
416 */
417 {
32874aea 418 Config cfg2;
3608528b 419 do_defaults(host, &cfg2);
18e62ad8 420 if (loaded_session || cfg2.host[0] == '\0') {
32874aea 421 /* No settings for this host; use defaults */
18e62ad8 422 /* (or session was already loaded with -load) */
3608528b 423 strncpy(cfg.host, host, sizeof(cfg.host) - 1);
32874aea 424 cfg.host[sizeof(cfg.host) - 1] = '\0';
425 cfg.port = default_port;
426 } else {
427 cfg = cfg2;
18e62ad8 428 /* Ick: patch up internal pointer after copy */
32874aea 429 cfg.remote_cmd_ptr = cfg.remote_cmd;
430 }
3608528b 431 }
432
433 if (user) {
434 /* Patch in specified username. */
435 strncpy(cfg.username, user,
436 sizeof(cfg.username) - 1);
32874aea 437 cfg.username[sizeof(cfg.username) - 1] = '\0';
32874aea 438 }
3608528b 439
32874aea 440 }
441 } else {
385528da 442 char *command;
443 int cmdlen, cmdsize;
444 cmdlen = cmdsize = 0;
445 command = NULL;
446
447 while (argc) {
448 while (*p) {
449 if (cmdlen >= cmdsize) {
450 cmdsize = cmdlen + 512;
3d88e64d 451 command = sresize(command, cmdsize, char);
385528da 452 }
453 command[cmdlen++]=*p++;
454 }
455 if (cmdlen >= cmdsize) {
456 cmdsize = cmdlen + 512;
3d88e64d 457 command = sresize(command, cmdsize, char);
385528da 458 }
459 command[cmdlen++]=' '; /* always add trailing space */
460 if (--argc) p = *++argv;
32874aea 461 }
385528da 462 if (cmdlen) command[--cmdlen]='\0';
463 /* change trailing blank to NUL */
464 cfg.remote_cmd_ptr = command;
465 cfg.remote_cmd_ptr2 = NULL;
32874aea 466 cfg.nopty = TRUE; /* command => no terminal */
385528da 467
32874aea 468 break; /* done with cmdline */
469 }
12dc4ec0 470 }
471 }
472
86256dc6 473 if (errors)
474 return 1;
475
d8426c54 476 if (!*cfg.host) {
32874aea 477 usage();
d8426c54 478 }
d8426c54 479
449925a6 480 /*
481 * Trim leading whitespace off the hostname if it's there.
482 */
483 {
484 int space = strspn(cfg.host, " \t");
485 memmove(cfg.host, cfg.host+space, 1+strlen(cfg.host)-space);
486 }
487
488 /* See if host is of the form user@host */
489 if (cfg.host[0] != '\0') {
5dd103a8 490 char *atsign = strrchr(cfg.host, '@');
449925a6 491 /* Make sure we're not overflowing the user field */
492 if (atsign) {
493 if (atsign - cfg.host < sizeof cfg.username) {
494 strncpy(cfg.username, cfg.host, atsign - cfg.host);
495 cfg.username[atsign - cfg.host] = '\0';
496 }
497 memmove(cfg.host, atsign + 1, 1 + strlen(atsign + 1));
498 }
499 }
500
501 /*
c0a81592 502 * Perform command-line overrides on session configuration.
503 */
5555d393 504 cmdline_run_saved(&cfg);
c0a81592 505
506 /*
4d1cdf5d 507 * Apply subsystem status.
508 */
509 if (use_subsystem)
510 cfg.ssh_subsys = TRUE;
511
512 /*
449925a6 513 * Trim a colon suffix off the hostname if it's there.
514 */
515 cfg.host[strcspn(cfg.host, ":")] = '\0';
516
cae0c023 517 /*
518 * Remove any remaining whitespace from the hostname.
519 */
520 {
521 int p1 = 0, p2 = 0;
522 while (cfg.host[p2] != '\0') {
523 if (cfg.host[p2] != ' ' && cfg.host[p2] != '\t') {
524 cfg.host[p1] = cfg.host[p2];
525 p1++;
526 }
527 p2++;
528 }
529 cfg.host[p1] = '\0';
530 }
531
96621a84 532 if (!*cfg.remote_cmd_ptr)
32874aea 533 flags |= FLAG_INTERACTIVE;
67779be7 534
12dc4ec0 535 /*
536 * Select protocol. This is farmed out into a table in a
537 * separate file to enable an ssh-free variant.
538 */
539 {
32874aea 540 int i;
541 back = NULL;
542 for (i = 0; backends[i].backend != NULL; i++)
543 if (backends[i].protocol == cfg.protocol) {
544 back = backends[i].backend;
545 break;
546 }
547 if (back == NULL) {
548 fprintf(stderr,
549 "Internal fault: Unsupported protocol found\n");
550 return 1;
551 }
12dc4ec0 552 }
553
554 /*
8cb9c947 555 * Select port.
556 */
557 if (portnumber != -1)
32874aea 558 cfg.port = portnumber;
8cb9c947 559
7440fd44 560 sk_init();
561 if (p_WSAEventSelect == NULL) {
562 fprintf(stderr, "Plink requires WinSock 2\n");
12dc4ec0 563 return 1;
564 }
565
566 /*
567 * Start up the connection.
568 */
8df7a775 569 netevent = CreateEvent(NULL, FALSE, FALSE, NULL);
12dc4ec0 570 {
cbe2d68f 571 const char *error;
12dc4ec0 572 char *realhost;
2184a5d9 573 /* nodelay is only useful if stdin is a character device (console) */
574 int nodelay = cfg.tcp_nodelay &&
575 (GetFileType(GetStdHandle(STD_INPUT_HANDLE)) == FILE_TYPE_CHAR);
12dc4ec0 576
86916870 577 error = back->init(NULL, &backhandle, &cfg, cfg.host, cfg.port,
79bf227b 578 &realhost, nodelay, cfg.tcp_keepalives);
12dc4ec0 579 if (error) {
580 fprintf(stderr, "Unable to open connection:\n%s", error);
581 return 1;
582 }
c229ef97 583 logctx = log_init(NULL, &cfg);
a8327734 584 back->provide_logctx(backhandle, logctx);
d3fef4a5 585 console_provide_logctx(logctx);
6e1ebb76 586 sfree(realhost);
12dc4ec0 587 }
8df7a775 588 connopen = 1;
12dc4ec0 589
12dc4ec0 590 stdinevent = CreateEvent(NULL, FALSE, FALSE, NULL);
5471d09a 591 stdoutevent = CreateEvent(NULL, FALSE, FALSE, NULL);
592 stderrevent = CreateEvent(NULL, FALSE, FALSE, NULL);
12dc4ec0 593
0965bee0 594 inhandle = GetStdHandle(STD_INPUT_HANDLE);
12dc4ec0 595 outhandle = GetStdHandle(STD_OUTPUT_HANDLE);
fe50e814 596 errhandle = GetStdHandle(STD_ERROR_HANDLE);
0965bee0 597 GetConsoleMode(inhandle, &orig_console_mode);
598 SetConsoleMode(inhandle, ENABLE_PROCESSED_INPUT);
12dc4ec0 599
c44bf5bd 600 main_thread_id = GetCurrentThreadId();
601
12dc4ec0 602 /*
12dc4ec0 603 * Turn off ECHO and LINE input modes. We don't care if this
604 * call fails, because we know we aren't necessarily running in
605 * a console.
606 */
12dc4ec0 607 handles[0] = netevent;
608 handles[1] = stdinevent;
5471d09a 609 handles[2] = stdoutevent;
610 handles[3] = stderrevent;
12dc4ec0 611 sending = FALSE;
5471d09a 612
613 /*
614 * Create spare threads to write to stdout and stderr, so we
615 * can arrange asynchronous writes.
616 */
617 odata.event = stdoutevent;
618 odata.eventback = CreateEvent(NULL, FALSE, FALSE, NULL);
619 odata.is_stderr = 0;
620 odata.busy = odata.done = 0;
621 if (!CreateThread(NULL, 0, stdout_write_thread,
622 &odata, 0, &out_threadid)) {
623 fprintf(stderr, "Unable to create output thread\n");
93b581bd 624 cleanup_exit(1);
5471d09a 625 }
626 edata.event = stderrevent;
627 edata.eventback = CreateEvent(NULL, FALSE, FALSE, NULL);
628 edata.is_stderr = 1;
629 edata.busy = edata.done = 0;
630 if (!CreateThread(NULL, 0, stdout_write_thread,
631 &edata, 0, &err_threadid)) {
632 fprintf(stderr, "Unable to create error output thread\n");
93b581bd 633 cleanup_exit(1);
5471d09a 634 }
635
39934deb 636 now = GETTICKCOUNT();
637
12dc4ec0 638 while (1) {
32874aea 639 int n;
39934deb 640 DWORD ticks;
32874aea 641
51470298 642 if (!sending && back->sendok(backhandle)) {
32874aea 643 /*
644 * Create a separate thread to read from stdin. This is
645 * a total pain, but I can't find another way to do it:
646 *
647 * - an overlapped ReadFile or ReadFileEx just doesn't
648 * happen; we get failure from ReadFileEx, and
649 * ReadFile blocks despite being given an OVERLAPPED
650 * structure. Perhaps we can't do overlapped reads
651 * on consoles. WHY THE HELL NOT?
652 *
653 * - WaitForMultipleObjects(netevent, console) doesn't
654 * work, because it signals the console when
655 * _anything_ happens, including mouse motions and
656 * other things that don't cause data to be readable
657 * - so we're back to ReadFile blocking.
658 */
659 idata.event = stdinevent;
660 idata.eventback = CreateEvent(NULL, FALSE, FALSE, NULL);
661 if (!CreateThread(NULL, 0, stdin_read_thread,
5471d09a 662 &idata, 0, &in_threadid)) {
663 fprintf(stderr, "Unable to create input thread\n");
93b581bd 664 cleanup_exit(1);
32874aea 665 }
666 sending = TRUE;
667 }
668
39934deb 669 if (run_timers(now, &next)) {
670 ticks = next - GETTICKCOUNT();
671 if (ticks < 0) ticks = 0; /* just in case */
672 } else {
673 ticks = INFINITE;
674 }
675
676 n = MsgWaitForMultipleObjects(4, handles, FALSE, ticks,
c44bf5bd 677 QS_POSTMESSAGE);
39934deb 678 if (n == WAIT_OBJECT_0 + 0) {
32874aea 679 WSANETWORKEVENTS things;
8df7a775 680 SOCKET socket;
d2371c81 681 extern SOCKET first_socket(int *), next_socket(int *);
8df7a775 682 extern int select_result(WPARAM, LPARAM);
32874aea 683 int i, socketstate;
684
685 /*
686 * We must not call select_result() for any socket
687 * until we have finished enumerating within the tree.
688 * This is because select_result() may close the socket
689 * and modify the tree.
690 */
691 /* Count the active sockets. */
692 i = 0;
693 for (socket = first_socket(&socketstate);
694 socket != INVALID_SOCKET;
695 socket = next_socket(&socketstate)) i++;
696
697 /* Expand the buffer if necessary. */
698 if (i > sksize) {
699 sksize = i + 16;
3d88e64d 700 sklist = sresize(sklist, sksize, SOCKET);
32874aea 701 }
702
703 /* Retrieve the sockets into sklist. */
704 skcount = 0;
705 for (socket = first_socket(&socketstate);
706 socket != INVALID_SOCKET;
d2371c81 707 socket = next_socket(&socketstate)) {
32874aea 708 sklist[skcount++] = socket;
709 }
710
711 /* Now we're done enumerating; go through the list. */
712 for (i = 0; i < skcount; i++) {
713 WPARAM wp;
714 socket = sklist[i];
715 wp = (WPARAM) socket;
7440fd44 716 if (!p_WSAEnumNetworkEvents(socket, NULL, &things)) {
64cdd21b 717 static const struct { int bit, mask; } eventtypes[] = {
718 {FD_CONNECT_BIT, FD_CONNECT},
719 {FD_READ_BIT, FD_READ},
720 {FD_CLOSE_BIT, FD_CLOSE},
721 {FD_OOB_BIT, FD_OOB},
722 {FD_WRITE_BIT, FD_WRITE},
723 {FD_ACCEPT_BIT, FD_ACCEPT},
724 };
725 int e;
726
32874aea 727 noise_ultralight(socket);
728 noise_ultralight(things.lNetworkEvents);
d74d141c 729
64cdd21b 730 for (e = 0; e < lenof(eventtypes); e++)
731 if (things.lNetworkEvents & eventtypes[e].mask) {
732 LPARAM lp;
733 int err = things.iErrorCode[eventtypes[e].bit];
734 lp = WSAMAKESELECTREPLY(eventtypes[e].mask, err);
735 connopen &= select_result(wp, lp);
736 }
8df7a775 737 }
738 }
39934deb 739 } else if (n == WAIT_OBJECT_0 + 1) {
5471d09a 740 reading = 0;
32874aea 741 noise_ultralight(idata.len);
51470298 742 if (connopen && back->socket(backhandle) != NULL) {
42856df4 743 if (idata.len > 0) {
51470298 744 back->send(backhandle, idata.buffer, idata.len);
42856df4 745 } else {
51470298 746 back->special(backhandle, TS_EOF);
42856df4 747 }
32874aea 748 }
39934deb 749 } else if (n == WAIT_OBJECT_0 + 2) {
5471d09a 750 odata.busy = 0;
751 if (!odata.writeret) {
752 fprintf(stderr, "Unable to write to standard output\n");
93b581bd 753 cleanup_exit(0);
5471d09a 754 }
755 bufchain_consume(&stdout_data, odata.lenwritten);
756 if (bufchain_size(&stdout_data) > 0)
757 try_output(0);
51470298 758 if (connopen && back->socket(backhandle) != NULL) {
759 back->unthrottle(backhandle, bufchain_size(&stdout_data) +
42856df4 760 bufchain_size(&stderr_data));
761 }
39934deb 762 } else if (n == WAIT_OBJECT_0 + 3) {
5471d09a 763 edata.busy = 0;
764 if (!edata.writeret) {
765 fprintf(stderr, "Unable to write to standard output\n");
93b581bd 766 cleanup_exit(0);
5471d09a 767 }
768 bufchain_consume(&stderr_data, edata.lenwritten);
769 if (bufchain_size(&stderr_data) > 0)
770 try_output(1);
51470298 771 if (connopen && back->socket(backhandle) != NULL) {
772 back->unthrottle(backhandle, bufchain_size(&stdout_data) +
42856df4 773 bufchain_size(&stderr_data));
774 }
39934deb 775 } else if (n == WAIT_OBJECT_0 + 4) {
c44bf5bd 776 MSG msg;
777 while (PeekMessage(&msg, INVALID_HANDLE_VALUE,
778 WM_AGENT_CALLBACK, WM_AGENT_CALLBACK,
779 PM_REMOVE)) {
780 struct agent_callback *c = (struct agent_callback *)msg.lParam;
781 c->callback(c->callback_ctx, c->data, c->len);
782 sfree(c);
783 }
5471d09a 784 }
39934deb 785
786 if (n == WAIT_TIMEOUT) {
787 now = next;
788 } else {
789 now = GETTICKCOUNT();
790 }
791
51470298 792 if (!reading && back->sendbuffer(backhandle) < MAX_STDIN_BACKLOG) {
32874aea 793 SetEvent(idata.eventback);
5471d09a 794 reading = 1;
32874aea 795 }
51470298 796 if ((!connopen || back->socket(backhandle) == NULL) &&
42856df4 797 bufchain_size(&stdout_data) == 0 &&
798 bufchain_size(&stderr_data) == 0)
32874aea 799 break; /* we closed the connection */
12dc4ec0 800 }
51470298 801 exitcode = back->exitcode(backhandle);
d8d6c7e5 802 if (exitcode < 0) {
803 fprintf(stderr, "Remote process exit code unavailable\n");
804 exitcode = 1; /* this is an error condition */
805 }
7440fd44 806 cleanup_exit(exitcode);
807 return 0; /* placate compiler warning */
12dc4ec0 808}