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