Two related changes to timing code:
[sgt/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
c44bf5bd 17struct agent_callback {
18 void (*callback)(void *, void *, int);
19 void *callback_ctx;
20 void *data;
21 int len;
22};
23
32874aea 24void fatalbox(char *p, ...)
25{
12dc4ec0 26 va_list ap;
49bad831 27 fprintf(stderr, "FATAL ERROR: ");
1709795f 28 va_start(ap, p);
29 vfprintf(stderr, p, ap);
30 va_end(ap);
31 fputc('\n', stderr);
7bfc5fd0 32 if (logctx) {
33 log_free(logctx);
34 logctx = NULL;
35 }
1709795f 36 cleanup_exit(1);
37}
38void modalfatalbox(char *p, ...)
39{
40 va_list ap;
41 fprintf(stderr, "FATAL ERROR: ");
12dc4ec0 42 va_start(ap, p);
43 vfprintf(stderr, p, ap);
44 va_end(ap);
45 fputc('\n', stderr);
7bfc5fd0 46 if (logctx) {
47 log_free(logctx);
48 logctx = NULL;
49 }
93b581bd 50 cleanup_exit(1);
12dc4ec0 51}
a8327734 52void connection_fatal(void *frontend, char *p, ...)
32874aea 53{
8d5de777 54 va_list ap;
49bad831 55 fprintf(stderr, "FATAL ERROR: ");
8d5de777 56 va_start(ap, p);
57 vfprintf(stderr, p, ap);
58 va_end(ap);
59 fputc('\n', stderr);
7bfc5fd0 60 if (logctx) {
61 log_free(logctx);
62 logctx = NULL;
63 }
93b581bd 64 cleanup_exit(1);
8d5de777 65}
c0a81592 66void cmdline_error(char *p, ...)
67{
68 va_list ap;
69 fprintf(stderr, "plink: ");
70 va_start(ap, p);
71 vfprintf(stderr, p, ap);
72 va_end(ap);
73 fputc('\n', stderr);
74 exit(1);
75}
12dc4ec0 76
0965bee0 77HANDLE inhandle, outhandle, errhandle;
34292b1d 78struct handle *stdin_handle, *stdout_handle, *stderr_handle;
6f34e365 79DWORD orig_console_mode;
34292b1d 80int connopen;
6f34e365 81
8df7a775 82WSAEVENT netevent;
83
6b78788a 84static Backend *back;
85static void *backhandle;
4a693cfc 86static Conf *conf;
6b78788a 87
887035a5 88int term_ldisc(Terminal *term, int mode)
32874aea 89{
90 return FALSE;
91}
b9d7bcad 92void ldisc_update(void *frontend, int echo, int edit)
32874aea 93{
0965bee0 94 /* Update stdin read mode to reflect changes in line discipline. */
95 DWORD mode;
96
97 mode = ENABLE_PROCESSED_INPUT;
98 if (echo)
32874aea 99 mode = mode | ENABLE_ECHO_INPUT;
0965bee0 100 else
32874aea 101 mode = mode & ~ENABLE_ECHO_INPUT;
0965bee0 102 if (edit)
32874aea 103 mode = mode | ENABLE_LINE_INPUT;
0965bee0 104 else
32874aea 105 mode = mode & ~ENABLE_LINE_INPUT;
0965bee0 106 SetConsoleMode(inhandle, mode);
107}
108
c6ccd5c2 109char *get_ttymode(void *frontend, const char *mode) { return NULL; }
110
9fab77dc 111int from_backend(void *frontend_handle, int is_stderr,
112 const char *data, int len)
5471d09a 113{
5471d09a 114 if (is_stderr) {
34292b1d 115 handle_write(stderr_handle, data, len);
5471d09a 116 } else {
34292b1d 117 handle_write(stdout_handle, data, len);
5471d09a 118 }
119
34292b1d 120 return handle_backlog(stdout_handle) + handle_backlog(stderr_handle);
5471d09a 121}
122
edd0cb8a 123int from_backend_untrusted(void *frontend_handle, const char *data, int len)
124{
125 /*
126 * No "untrusted" output should get here (the way the code is
127 * currently, it's all diverted by FLAG_STDERR).
128 */
129 assert(!"Unexpected call to from_backend_untrusted()");
130 return 0; /* not reached */
131}
132
bc06669b 133int from_backend_eof(void *frontend_handle)
134{
135 handle_write_eof(stdout_handle);
136 return FALSE; /* do not respond to incoming EOF with outgoing */
137}
138
edd0cb8a 139int get_userpass_input(prompts_t *p, unsigned char *in, int inlen)
140{
141 int ret;
142 ret = cmdline_get_passwd_input(p, in, inlen);
143 if (ret == -1)
144 ret = console_get_userpass_input(p, in, inlen);
145 return ret;
146}
147
c44bf5bd 148static DWORD main_thread_id;
149
150void agent_schedule_callback(void (*callback)(void *, void *, int),
151 void *callback_ctx, void *data, int len)
152{
153 struct agent_callback *c = snew(struct agent_callback);
154 c->callback = callback;
155 c->callback_ctx = callback_ctx;
156 c->data = data;
157 c->len = len;
158 PostThreadMessage(main_thread_id, WM_AGENT_CALLBACK, 0, (LPARAM)c);
159}
160
d8426c54 161/*
162 * Short description of parameters.
163 */
164static void usage(void)
165{
166 printf("PuTTY Link: command-line connection utility\n");
167 printf("%s\n", ver);
168 printf("Usage: plink [options] [user@]host [command]\n");
e672967c 169 printf(" (\"host\" can also be a PuTTY saved session name)\n");
d8426c54 170 printf("Options:\n");
2285d016 171 printf(" -V print version information and exit\n");
172 printf(" -pgpfp print PGP key fingerprints and exit\n");
d8426c54 173 printf(" -v show verbose messages\n");
e2a197cf 174 printf(" -load sessname Load settings from saved session\n");
f41f07bc 175 printf(" -ssh -telnet -rlogin -raw -serial\n");
afd4d0d2 176 printf(" force use of a particular protocol\n");
d8426c54 177 printf(" -P port connect to specified port\n");
e2a197cf 178 printf(" -l user connect with specified username\n");
e2a197cf 179 printf(" -batch disable all interactive prompts\n");
180 printf("The following options only apply to SSH connections:\n");
181 printf(" -pw passw login with specified password\n");
dbe6c525 182 printf(" -D [listen-IP:]listen-port\n");
183 printf(" Dynamic SOCKS-based port forwarding\n");
184 printf(" -L [listen-IP:]listen-port:host:port\n");
185 printf(" Forward local port to remote address\n");
186 printf(" -R [listen-IP:]listen-port:host:port\n");
187 printf(" Forward remote port to local address\n");
e2a197cf 188 printf(" -X -x enable / disable X11 forwarding\n");
189 printf(" -A -a enable / disable agent forwarding\n");
190 printf(" -t -T enable / disable pty allocation\n");
191 printf(" -1 -2 force use of particular protocol version\n");
05581745 192 printf(" -4 -6 force use of IPv4 or IPv6\n");
e2a197cf 193 printf(" -C enable compression\n");
194 printf(" -i key private key file for authentication\n");
e5708bc7 195 printf(" -noagent disable use of Pageant\n");
196 printf(" -agent enable use of Pageant\n");
54018d95 197 printf(" -m file read remote command(s) from file\n");
4d1cdf5d 198 printf(" -s remote command is an SSH subsystem (SSH-2 only)\n");
b72c366d 199 printf(" -N don't start a shell/command (SSH-2 only)\n");
23828b7e 200 printf(" -nc host:port\n");
201 printf(" open tunnel in place of session (SSH-2 only)\n");
9621bbab 202 printf(" -sercfg configuration-string (e.g. 19200,8,n,1,X)\n");
203 printf(" Specify the serial configuration (serial only)\n");
dc108ebc 204 exit(1);
205}
206
207static void version(void)
208{
209 printf("plink: %s\n", ver);
d8426c54 210 exit(1);
211}
212
32874aea 213char *do_select(SOCKET skt, int startup)
214{
8df7a775 215 int events;
216 if (startup) {
3ad9d396 217 events = (FD_CONNECT | FD_READ | FD_WRITE |
218 FD_OOB | FD_CLOSE | FD_ACCEPT);
8df7a775 219 } else {
220 events = 0;
221 }
7440fd44 222 if (p_WSAEventSelect(skt, netevent, events) == SOCKET_ERROR) {
223 switch (p_WSAGetLastError()) {
32874aea 224 case WSAENETDOWN:
225 return "Network is down";
226 default:
7440fd44 227 return "WSAEventSelect(): unknown error";
32874aea 228 }
8df7a775 229 }
230 return NULL;
231}
232
34292b1d 233int stdin_gotdata(struct handle *h, void *data, int len)
234{
235 if (len < 0) {
236 /*
237 * Special case: report read error.
238 */
21ae394f 239 char buf[4096];
240 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, -len, 0,
241 buf, lenof(buf), NULL);
242 buf[lenof(buf)-1] = '\0';
243 if (buf[strlen(buf)-1] == '\n')
244 buf[strlen(buf)-1] = '\0';
245 fprintf(stderr, "Unable to read from standard input: %s\n", buf);
34292b1d 246 cleanup_exit(0);
247 }
248 noise_ultralight(len);
6226c939 249 if (connopen && back->connected(backhandle)) {
34292b1d 250 if (len > 0) {
251 return back->send(backhandle, data, len);
252 } else {
253 back->special(backhandle, TS_EOF);
254 return 0;
255 }
256 } else
257 return 0;
258}
259
260void stdouterr_sent(struct handle *h, int new_backlog)
261{
262 if (new_backlog < 0) {
263 /*
264 * Special case: report write error.
265 */
21ae394f 266 char buf[4096];
267 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, -new_backlog, 0,
268 buf, lenof(buf), NULL);
269 buf[lenof(buf)-1] = '\0';
270 if (buf[strlen(buf)-1] == '\n')
271 buf[strlen(buf)-1] = '\0';
272 fprintf(stderr, "Unable to write to standard %s: %s\n",
273 (h == stdout_handle ? "output" : "error"), buf);
34292b1d 274 cleanup_exit(0);
275 }
6226c939 276 if (connopen && back->connected(backhandle)) {
34292b1d 277 back->unthrottle(backhandle, (handle_backlog(stdout_handle) +
278 handle_backlog(stderr_handle)));
279 }
280}
281
32874aea 282int main(int argc, char **argv)
283{
12dc4ec0 284 int sending;
d8426c54 285 int portnumber = -1;
8df7a775 286 SOCKET *sklist;
287 int skcount, sksize;
d8d6c7e5 288 int exitcode;
86256dc6 289 int errors;
f0f51e90 290 int got_host = FALSE;
4d1cdf5d 291 int use_subsystem = 0;
d719927e 292 unsigned long now, next, then;
12dc4ec0 293
32874aea 294 sklist = NULL;
295 skcount = sksize = 0;
c9bdcd96 296 /*
297 * Initialise port and protocol to sensible defaults. (These
298 * will be overridden by more or less anything.)
299 */
300 default_protocol = PROT_SSH;
301 default_port = 22;
8df7a775 302
67779be7 303 flags = FLAG_STDERR;
12dc4ec0 304 /*
305 * Process the command line.
306 */
4a693cfc 307 conf = conf_new();
308 do_defaults(NULL, conf);
18e62ad8 309 loaded_session = FALSE;
4a693cfc 310 default_protocol = conf_get_int(conf, CONF_protocol);
311 default_port = conf_get_int(conf, CONF_port);
86256dc6 312 errors = 0;
8cb9c947 313 {
32874aea 314 /*
315 * Override the default protocol if PLINK_PROTOCOL is set.
316 */
317 char *p = getenv("PLINK_PROTOCOL");
32874aea 318 if (p) {
9e164d82 319 const Backend *b = backend_from_name(p);
320 if (b) {
4a693cfc 321 default_protocol = b->protocol;
322 default_port = b->default_port;
323 conf_set_int(conf, CONF_protocol, default_protocol);
324 conf_set_int(conf, CONF_port, default_port);
32874aea 325 }
326 }
8cb9c947 327 }
12dc4ec0 328 while (--argc) {
32874aea 329 char *p = *++argv;
330 if (*p == '-') {
5555d393 331 int ret = cmdline_process_param(p, (argc > 1 ? argv[1] : NULL),
4a693cfc 332 1, conf);
c0a81592 333 if (ret == -2) {
334 fprintf(stderr,
335 "plink: option \"%s\" requires an argument\n", p);
86256dc6 336 errors = 1;
c0a81592 337 } else if (ret == 2) {
338 --argc, ++argv;
339 } else if (ret == 1) {
340 continue;
ff2ae367 341 } else if (!strcmp(p, "-batch")) {
c0a81592 342 console_batch_mode = 1;
4d1cdf5d 343 } else if (!strcmp(p, "-s")) {
4a693cfc 344 /* Save status to write to conf later. */
4d1cdf5d 345 use_subsystem = 1;
dc108ebc 346 } else if (!strcmp(p, "-V")) {
347 version();
2285d016 348 } else if (!strcmp(p, "-pgpfp")) {
349 pgp_fingerprints();
350 exit(1);
86256dc6 351 } else {
352 fprintf(stderr, "plink: unknown option \"%s\"\n", p);
353 errors = 1;
32874aea 354 }
12dc4ec0 355 } else if (*p) {
4a693cfc 356 if (!conf_launchable(conf) || !(got_host || loaded_session)) {
32874aea 357 char *q = p;
358 /*
359 * If the hostname starts with "telnet:", set the
360 * protocol to Telnet and process the string as a
361 * Telnet URL.
362 */
363 if (!strncmp(q, "telnet:", 7)) {
364 char c;
365
366 q += 7;
367 if (q[0] == '/' && q[1] == '/')
368 q += 2;
4a693cfc 369 conf_set_int(conf, CONF_protocol, PROT_TELNET);
32874aea 370 p = q;
371 while (*p && *p != ':' && *p != '/')
372 p++;
373 c = *p;
374 if (*p)
375 *p++ = '\0';
376 if (c == ':')
4a693cfc 377 conf_set_int(conf, CONF_port, atoi(p));
32874aea 378 else
4a693cfc 379 conf_set_int(conf, CONF_port, -1);
380 conf_set_str(conf, CONF_host, q);
f0f51e90 381 got_host = TRUE;
32874aea 382 } else {
3608528b 383 char *r, *user, *host;
32874aea 384 /*
385 * Before we process the [user@]host string, we
386 * first check for the presence of a protocol
387 * prefix (a protocol name followed by ",").
388 */
389 r = strchr(p, ',');
390 if (r) {
9e164d82 391 const Backend *b;
392 *r = '\0';
393 b = backend_from_name(p);
394 if (b) {
4a693cfc 395 default_protocol = b->protocol;
396 conf_set_int(conf, CONF_protocol,
397 default_protocol);
9e164d82 398 portnumber = b->default_port;
32874aea 399 }
9e164d82 400 p = r + 1;
32874aea 401 }
402
403 /*
3608528b 404 * A nonzero length string followed by an @ is treated
405 * as a username. (We discount an _initial_ @.) The
406 * rest of the string (or the whole string if no @)
407 * is treated as a session name and/or hostname.
32874aea 408 */
409 r = strrchr(p, '@');
410 if (r == p)
411 p++, r = NULL; /* discount initial @ */
3608528b 412 if (r) {
413 *r++ = '\0';
414 user = p, host = r;
415 } else {
416 user = NULL, host = p;
417 }
418
419 /*
420 * Now attempt to load a saved session with the
421 * same name as the hostname.
422 */
423 {
4a693cfc 424 Conf *conf2 = conf_new();
425 do_defaults(host, conf2);
426 if (loaded_session || !conf_launchable(conf2)) {
32874aea 427 /* No settings for this host; use defaults */
18e62ad8 428 /* (or session was already loaded with -load) */
4a693cfc 429 conf_set_str(conf, CONF_host, host);
430 conf_set_int(conf, CONF_port, default_port);
f0f51e90 431 got_host = TRUE;
32874aea 432 } else {
4a693cfc 433 conf_copy_into(conf, conf2);
f0f51e90 434 loaded_session = TRUE;
32874aea 435 }
4a693cfc 436 conf_free(conf2);
3608528b 437 }
438
439 if (user) {
440 /* Patch in specified username. */
4a693cfc 441 conf_set_str(conf, CONF_username, user);
32874aea 442 }
3608528b 443
32874aea 444 }
445 } else {
385528da 446 char *command;
447 int cmdlen, cmdsize;
448 cmdlen = cmdsize = 0;
449 command = NULL;
450
451 while (argc) {
452 while (*p) {
453 if (cmdlen >= cmdsize) {
454 cmdsize = cmdlen + 512;
3d88e64d 455 command = sresize(command, cmdsize, char);
385528da 456 }
457 command[cmdlen++]=*p++;
458 }
459 if (cmdlen >= cmdsize) {
460 cmdsize = cmdlen + 512;
3d88e64d 461 command = sresize(command, cmdsize, char);
385528da 462 }
463 command[cmdlen++]=' '; /* always add trailing space */
464 if (--argc) p = *++argv;
32874aea 465 }
385528da 466 if (cmdlen) command[--cmdlen]='\0';
467 /* change trailing blank to NUL */
4a693cfc 468 conf_set_str(conf, CONF_remote_cmd, command);
469 conf_set_str(conf, CONF_remote_cmd2, "");
470 conf_set_int(conf, CONF_nopty, TRUE); /* command => no tty */
385528da 471
32874aea 472 break; /* done with cmdline */
473 }
12dc4ec0 474 }
475 }
476
86256dc6 477 if (errors)
478 return 1;
479
4a693cfc 480 if (!conf_launchable(conf) || !(got_host || loaded_session)) {
32874aea 481 usage();
d8426c54 482 }
d8426c54 483
449925a6 484 /*
4a693cfc 485 * Muck about with the hostname in various ways.
449925a6 486 */
487 {
4a693cfc 488 char *hostbuf = dupstr(conf_get_str(conf, CONF_host));
489 char *host = hostbuf;
490 char *p, *q;
491
492 /*
493 * Trim leading whitespace.
494 */
495 host += strspn(host, " \t");
449925a6 496
4a693cfc 497 /*
498 * See if host is of the form user@host, and separate out
499 * the username if so.
500 */
501 if (host[0] != '\0') {
502 char *atsign = strrchr(host, '@');
503 if (atsign) {
504 *atsign = '\0';
505 conf_set_str(conf, CONF_username, host);
506 host = atsign + 1;
449925a6 507 }
449925a6 508 }
4a693cfc 509
510 /*
511 * Trim off a colon suffix if it's there.
512 */
513 host[strcspn(host, ":")] = '\0';
514
515 /*
516 * Remove any remaining whitespace.
517 */
518 p = hostbuf;
519 q = host;
520 while (*q) {
521 if (*q != ' ' && *q != '\t')
522 *p++ = *q;
523 q++;
524 }
525 *p = '\0';
526
527 conf_set_str(conf, CONF_host, hostbuf);
528 sfree(hostbuf);
449925a6 529 }
530
531 /*
c0a81592 532 * Perform command-line overrides on session configuration.
533 */
4a693cfc 534 cmdline_run_saved(conf);
c0a81592 535
536 /*
4d1cdf5d 537 * Apply subsystem status.
538 */
539 if (use_subsystem)
4a693cfc 540 conf_set_int(conf, CONF_ssh_subsys, TRUE);
cae0c023 541
4a693cfc 542 if (!*conf_get_str(conf, CONF_remote_cmd) &&
543 !*conf_get_str(conf, CONF_remote_cmd2) &&
544 !*conf_get_str(conf, CONF_ssh_nc_host))
32874aea 545 flags |= FLAG_INTERACTIVE;
67779be7 546
12dc4ec0 547 /*
548 * Select protocol. This is farmed out into a table in a
549 * separate file to enable an ssh-free variant.
550 */
4a693cfc 551 back = backend_from_proto(conf_get_int(conf, CONF_protocol));
9e164d82 552 if (back == NULL) {
553 fprintf(stderr,
554 "Internal fault: Unsupported protocol found\n");
555 return 1;
12dc4ec0 556 }
557
558 /*
8cb9c947 559 * Select port.
560 */
561 if (portnumber != -1)
4a693cfc 562 conf_set_int(conf, CONF_port, portnumber);
8cb9c947 563
7440fd44 564 sk_init();
565 if (p_WSAEventSelect == NULL) {
566 fprintf(stderr, "Plink requires WinSock 2\n");
12dc4ec0 567 return 1;
568 }
569
4a693cfc 570 logctx = log_init(NULL, conf);
1626d169 571 console_provide_logctx(logctx);
572
12dc4ec0 573 /*
574 * Start up the connection.
575 */
8df7a775 576 netevent = CreateEvent(NULL, FALSE, FALSE, NULL);
12dc4ec0 577 {
cbe2d68f 578 const char *error;
12dc4ec0 579 char *realhost;
2184a5d9 580 /* nodelay is only useful if stdin is a character device (console) */
4a693cfc 581 int nodelay = conf_get_int(conf, CONF_tcp_nodelay) &&
2184a5d9 582 (GetFileType(GetStdHandle(STD_INPUT_HANDLE)) == FILE_TYPE_CHAR);
12dc4ec0 583
4a693cfc 584 error = back->init(NULL, &backhandle, conf,
585 conf_get_str(conf, CONF_host),
586 conf_get_int(conf, CONF_port),
587 &realhost, nodelay,
588 conf_get_int(conf, CONF_tcp_keepalives));
12dc4ec0 589 if (error) {
590 fprintf(stderr, "Unable to open connection:\n%s", error);
591 return 1;
592 }
a8327734 593 back->provide_logctx(backhandle, logctx);
6e1ebb76 594 sfree(realhost);
12dc4ec0 595 }
8df7a775 596 connopen = 1;
12dc4ec0 597
0965bee0 598 inhandle = GetStdHandle(STD_INPUT_HANDLE);
12dc4ec0 599 outhandle = GetStdHandle(STD_OUTPUT_HANDLE);
fe50e814 600 errhandle = GetStdHandle(STD_ERROR_HANDLE);
34292b1d 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 */
f8efb0d5 607 GetConsoleMode(inhandle, &orig_console_mode);
608 SetConsoleMode(inhandle, ENABLE_PROCESSED_INPUT);
609
34292b1d 610 /*
611 * Pass the output handles to the handle-handling subsystem.
612 * (The input one we leave until we're through the
613 * authentication process.)
614 */
bdebd7e9 615 stdout_handle = handle_output_new(outhandle, stdouterr_sent, NULL, 0);
616 stderr_handle = handle_output_new(errhandle, stdouterr_sent, NULL, 0);
34292b1d 617
f8efb0d5 618 main_thread_id = GetCurrentThreadId();
619
12dc4ec0 620 sending = FALSE;
5471d09a 621
39934deb 622 now = GETTICKCOUNT();
623
12dc4ec0 624 while (1) {
34292b1d 625 int nhandles;
626 HANDLE *handles;
32874aea 627 int n;
39934deb 628 DWORD ticks;
32874aea 629
51470298 630 if (!sending && back->sendok(backhandle)) {
bdebd7e9 631 stdin_handle = handle_input_new(inhandle, stdin_gotdata, NULL,
632 0);
32874aea 633 sending = TRUE;
634 }
635
39934deb 636 if (run_timers(now, &next)) {
d719927e 637 then = now;
638 now = GETTICKCOUNT();
639 if (now - then > next - then)
640 ticks = 0;
641 else
642 ticks = next - now;
39934deb 643 } else {
644 ticks = INFINITE;
645 }
646
34292b1d 647 handles = handle_get_events(&nhandles);
648 handles = sresize(handles, nhandles+1, HANDLE);
649 handles[nhandles] = netevent;
650 n = MsgWaitForMultipleObjects(nhandles+1, handles, FALSE, ticks,
c44bf5bd 651 QS_POSTMESSAGE);
34292b1d 652 if ((unsigned)(n - WAIT_OBJECT_0) < (unsigned)nhandles) {
653 handle_got_event(handles[n - WAIT_OBJECT_0]);
654 } else if (n == WAIT_OBJECT_0 + nhandles) {
32874aea 655 WSANETWORKEVENTS things;
8df7a775 656 SOCKET socket;
d2371c81 657 extern SOCKET first_socket(int *), next_socket(int *);
8df7a775 658 extern int select_result(WPARAM, LPARAM);
32874aea 659 int i, socketstate;
660
661 /*
662 * We must not call select_result() for any socket
663 * until we have finished enumerating within the tree.
664 * This is because select_result() may close the socket
665 * and modify the tree.
666 */
667 /* Count the active sockets. */
668 i = 0;
669 for (socket = first_socket(&socketstate);
670 socket != INVALID_SOCKET;
671 socket = next_socket(&socketstate)) i++;
672
673 /* Expand the buffer if necessary. */
674 if (i > sksize) {
675 sksize = i + 16;
3d88e64d 676 sklist = sresize(sklist, sksize, SOCKET);
32874aea 677 }
678
679 /* Retrieve the sockets into sklist. */
680 skcount = 0;
681 for (socket = first_socket(&socketstate);
682 socket != INVALID_SOCKET;
d2371c81 683 socket = next_socket(&socketstate)) {
32874aea 684 sklist[skcount++] = socket;
685 }
686
687 /* Now we're done enumerating; go through the list. */
688 for (i = 0; i < skcount; i++) {
689 WPARAM wp;
690 socket = sklist[i];
691 wp = (WPARAM) socket;
7440fd44 692 if (!p_WSAEnumNetworkEvents(socket, NULL, &things)) {
64cdd21b 693 static const struct { int bit, mask; } eventtypes[] = {
694 {FD_CONNECT_BIT, FD_CONNECT},
695 {FD_READ_BIT, FD_READ},
696 {FD_CLOSE_BIT, FD_CLOSE},
697 {FD_OOB_BIT, FD_OOB},
698 {FD_WRITE_BIT, FD_WRITE},
699 {FD_ACCEPT_BIT, FD_ACCEPT},
700 };
701 int e;
702
32874aea 703 noise_ultralight(socket);
704 noise_ultralight(things.lNetworkEvents);
d74d141c 705
64cdd21b 706 for (e = 0; e < lenof(eventtypes); e++)
707 if (things.lNetworkEvents & eventtypes[e].mask) {
708 LPARAM lp;
709 int err = things.iErrorCode[eventtypes[e].bit];
710 lp = WSAMAKESELECTREPLY(eventtypes[e].mask, err);
711 connopen &= select_result(wp, lp);
712 }
8df7a775 713 }
714 }
34292b1d 715 } else if (n == WAIT_OBJECT_0 + nhandles + 1) {
c44bf5bd 716 MSG msg;
717 while (PeekMessage(&msg, INVALID_HANDLE_VALUE,
718 WM_AGENT_CALLBACK, WM_AGENT_CALLBACK,
719 PM_REMOVE)) {
720 struct agent_callback *c = (struct agent_callback *)msg.lParam;
721 c->callback(c->callback_ctx, c->data, c->len);
722 sfree(c);
723 }
5471d09a 724 }
39934deb 725
726 if (n == WAIT_TIMEOUT) {
727 now = next;
728 } else {
729 now = GETTICKCOUNT();
730 }
731
34292b1d 732 sfree(handles);
733
734 if (sending)
735 handle_unthrottle(stdin_handle, back->sendbuffer(backhandle));
736
6226c939 737 if ((!connopen || !back->connected(backhandle)) &&
34292b1d 738 handle_backlog(stdout_handle) + handle_backlog(stderr_handle) == 0)
32874aea 739 break; /* we closed the connection */
12dc4ec0 740 }
51470298 741 exitcode = back->exitcode(backhandle);
d8d6c7e5 742 if (exitcode < 0) {
743 fprintf(stderr, "Remote process exit code unavailable\n");
744 exitcode = 1; /* this is an error condition */
745 }
7440fd44 746 cleanup_exit(exitcode);
747 return 0; /* placate compiler warning */
12dc4ec0 748}