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