Add a configuration option for TCP keepalives (SO_KEEPALIVE), default off.
[u/mdw/putty] / plink.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");
217 printf(" force use of a particular protocol (default SSH)\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");
234 printf(" -C enable compression\n");
235 printf(" -i key private key file for authentication\n");
4d1cdf5d 236 printf(" -s remote command is an SSH subsystem (SSH-2 only)\n");
dc108ebc 237 exit(1);
238}
239
240static void version(void)
241{
242 printf("plink: %s\n", ver);
d8426c54 243 exit(1);
244}
245
32874aea 246char *do_select(SOCKET skt, int startup)
247{
8df7a775 248 int events;
249 if (startup) {
3ad9d396 250 events = (FD_CONNECT | FD_READ | FD_WRITE |
251 FD_OOB | FD_CLOSE | FD_ACCEPT);
8df7a775 252 } else {
253 events = 0;
254 }
7440fd44 255 if (p_WSAEventSelect(skt, netevent, events) == SOCKET_ERROR) {
256 switch (p_WSAGetLastError()) {
32874aea 257 case WSAENETDOWN:
258 return "Network is down";
259 default:
7440fd44 260 return "WSAEventSelect(): unknown error";
32874aea 261 }
8df7a775 262 }
263 return NULL;
264}
265
32874aea 266int main(int argc, char **argv)
267{
5471d09a 268 WSAEVENT stdinevent, stdoutevent, stderrevent;
269 HANDLE handles[4];
270 DWORD in_threadid, out_threadid, err_threadid;
12dc4ec0 271 struct input_data idata;
5471d09a 272 int reading;
12dc4ec0 273 int sending;
d8426c54 274 int portnumber = -1;
8df7a775 275 SOCKET *sklist;
276 int skcount, sksize;
277 int connopen;
d8d6c7e5 278 int exitcode;
86256dc6 279 int errors;
4d1cdf5d 280 int use_subsystem = 0;
12dc4ec0 281
ff2ae367 282 ssh_get_line = console_get_line;
67779be7 283
32874aea 284 sklist = NULL;
285 skcount = sksize = 0;
c9bdcd96 286 /*
287 * Initialise port and protocol to sensible defaults. (These
288 * will be overridden by more or less anything.)
289 */
290 default_protocol = PROT_SSH;
291 default_port = 22;
8df7a775 292
67779be7 293 flags = FLAG_STDERR;
12dc4ec0 294 /*
295 * Process the command line.
296 */
a9422f39 297 do_defaults(NULL, &cfg);
e7a7383f 298 default_protocol = cfg.protocol;
299 default_port = cfg.port;
86256dc6 300 errors = 0;
8cb9c947 301 {
32874aea 302 /*
303 * Override the default protocol if PLINK_PROTOCOL is set.
304 */
305 char *p = getenv("PLINK_PROTOCOL");
306 int i;
307 if (p) {
308 for (i = 0; backends[i].backend != NULL; i++) {
309 if (!strcmp(backends[i].name, p)) {
310 default_protocol = cfg.protocol = backends[i].protocol;
311 default_port = cfg.port =
312 backends[i].backend->default_port;
313 break;
314 }
315 }
316 }
8cb9c947 317 }
12dc4ec0 318 while (--argc) {
32874aea 319 char *p = *++argv;
320 if (*p == '-') {
5555d393 321 int ret = cmdline_process_param(p, (argc > 1 ? argv[1] : NULL),
322 1, &cfg);
c0a81592 323 if (ret == -2) {
324 fprintf(stderr,
325 "plink: option \"%s\" requires an argument\n", p);
86256dc6 326 errors = 1;
c0a81592 327 } else if (ret == 2) {
328 --argc, ++argv;
329 } else if (ret == 1) {
330 continue;
ff2ae367 331 } else if (!strcmp(p, "-batch")) {
c0a81592 332 console_batch_mode = 1;
4d1cdf5d 333 } else if (!strcmp(p, "-s")) {
334 /* Save status to write to cfg later. */
335 use_subsystem = 1;
dc108ebc 336 } else if (!strcmp(p, "-V")) {
337 version();
86256dc6 338 } else {
339 fprintf(stderr, "plink: unknown option \"%s\"\n", p);
340 errors = 1;
32874aea 341 }
12dc4ec0 342 } else if (*p) {
32874aea 343 if (!*cfg.host) {
344 char *q = p;
345 /*
346 * If the hostname starts with "telnet:", set the
347 * protocol to Telnet and process the string as a
348 * Telnet URL.
349 */
350 if (!strncmp(q, "telnet:", 7)) {
351 char c;
352
353 q += 7;
354 if (q[0] == '/' && q[1] == '/')
355 q += 2;
356 cfg.protocol = PROT_TELNET;
357 p = q;
358 while (*p && *p != ':' && *p != '/')
359 p++;
360 c = *p;
361 if (*p)
362 *p++ = '\0';
363 if (c == ':')
364 cfg.port = atoi(p);
365 else
366 cfg.port = -1;
367 strncpy(cfg.host, q, sizeof(cfg.host) - 1);
368 cfg.host[sizeof(cfg.host) - 1] = '\0';
369 } else {
370 char *r;
371 /*
372 * Before we process the [user@]host string, we
373 * first check for the presence of a protocol
374 * prefix (a protocol name followed by ",").
375 */
376 r = strchr(p, ',');
377 if (r) {
378 int i, j;
379 for (i = 0; backends[i].backend != NULL; i++) {
380 j = strlen(backends[i].name);
381 if (j == r - p &&
382 !memcmp(backends[i].name, p, j)) {
383 default_protocol = cfg.protocol =
384 backends[i].protocol;
385 portnumber =
386 backends[i].backend->default_port;
387 p = r + 1;
388 break;
389 }
390 }
391 }
392
393 /*
394 * Three cases. Either (a) there's a nonzero
395 * length string followed by an @, in which
396 * case that's user and the remainder is host.
397 * Or (b) there's only one string, not counting
398 * a potential initial @, and it exists in the
399 * saved-sessions database. Or (c) only one
400 * string and it _doesn't_ exist in the
401 * database.
402 */
403 r = strrchr(p, '@');
404 if (r == p)
405 p++, r = NULL; /* discount initial @ */
406 if (r == NULL) {
407 /*
408 * One string.
409 */
410 Config cfg2;
411 do_defaults(p, &cfg2);
412 if (cfg2.host[0] == '\0') {
413 /* No settings for this host; use defaults */
414 strncpy(cfg.host, p, sizeof(cfg.host) - 1);
415 cfg.host[sizeof(cfg.host) - 1] = '\0';
416 cfg.port = default_port;
417 } else {
418 cfg = cfg2;
419 cfg.remote_cmd_ptr = cfg.remote_cmd;
420 }
421 } else {
422 *r++ = '\0';
423 strncpy(cfg.username, p, sizeof(cfg.username) - 1);
424 cfg.username[sizeof(cfg.username) - 1] = '\0';
425 strncpy(cfg.host, r, sizeof(cfg.host) - 1);
426 cfg.host[sizeof(cfg.host) - 1] = '\0';
427 cfg.port = default_port;
428 }
429 }
430 } else {
385528da 431 char *command;
432 int cmdlen, cmdsize;
433 cmdlen = cmdsize = 0;
434 command = NULL;
435
436 while (argc) {
437 while (*p) {
438 if (cmdlen >= cmdsize) {
439 cmdsize = cmdlen + 512;
3d88e64d 440 command = sresize(command, cmdsize, char);
385528da 441 }
442 command[cmdlen++]=*p++;
443 }
444 if (cmdlen >= cmdsize) {
445 cmdsize = cmdlen + 512;
3d88e64d 446 command = sresize(command, cmdsize, char);
385528da 447 }
448 command[cmdlen++]=' '; /* always add trailing space */
449 if (--argc) p = *++argv;
32874aea 450 }
385528da 451 if (cmdlen) command[--cmdlen]='\0';
452 /* change trailing blank to NUL */
453 cfg.remote_cmd_ptr = command;
454 cfg.remote_cmd_ptr2 = NULL;
32874aea 455 cfg.nopty = TRUE; /* command => no terminal */
385528da 456
32874aea 457 break; /* done with cmdline */
458 }
12dc4ec0 459 }
460 }
461
86256dc6 462 if (errors)
463 return 1;
464
d8426c54 465 if (!*cfg.host) {
32874aea 466 usage();
d8426c54 467 }
d8426c54 468
449925a6 469 /*
470 * Trim leading whitespace off the hostname if it's there.
471 */
472 {
473 int space = strspn(cfg.host, " \t");
474 memmove(cfg.host, cfg.host+space, 1+strlen(cfg.host)-space);
475 }
476
477 /* See if host is of the form user@host */
478 if (cfg.host[0] != '\0') {
479 char *atsign = strchr(cfg.host, '@');
480 /* Make sure we're not overflowing the user field */
481 if (atsign) {
482 if (atsign - cfg.host < sizeof cfg.username) {
483 strncpy(cfg.username, cfg.host, atsign - cfg.host);
484 cfg.username[atsign - cfg.host] = '\0';
485 }
486 memmove(cfg.host, atsign + 1, 1 + strlen(atsign + 1));
487 }
488 }
489
490 /*
c0a81592 491 * Perform command-line overrides on session configuration.
492 */
5555d393 493 cmdline_run_saved(&cfg);
c0a81592 494
495 /*
4d1cdf5d 496 * Apply subsystem status.
497 */
498 if (use_subsystem)
499 cfg.ssh_subsys = TRUE;
500
501 /*
449925a6 502 * Trim a colon suffix off the hostname if it's there.
503 */
504 cfg.host[strcspn(cfg.host, ":")] = '\0';
505
cae0c023 506 /*
507 * Remove any remaining whitespace from the hostname.
508 */
509 {
510 int p1 = 0, p2 = 0;
511 while (cfg.host[p2] != '\0') {
512 if (cfg.host[p2] != ' ' && cfg.host[p2] != '\t') {
513 cfg.host[p1] = cfg.host[p2];
514 p1++;
515 }
516 p2++;
517 }
518 cfg.host[p1] = '\0';
519 }
520
96621a84 521 if (!*cfg.remote_cmd_ptr)
32874aea 522 flags |= FLAG_INTERACTIVE;
67779be7 523
12dc4ec0 524 /*
525 * Select protocol. This is farmed out into a table in a
526 * separate file to enable an ssh-free variant.
527 */
528 {
32874aea 529 int i;
530 back = NULL;
531 for (i = 0; backends[i].backend != NULL; i++)
532 if (backends[i].protocol == cfg.protocol) {
533 back = backends[i].backend;
534 break;
535 }
536 if (back == NULL) {
537 fprintf(stderr,
538 "Internal fault: Unsupported protocol found\n");
539 return 1;
540 }
12dc4ec0 541 }
542
543 /*
8cb9c947 544 * Select port.
545 */
546 if (portnumber != -1)
32874aea 547 cfg.port = portnumber;
8cb9c947 548
7440fd44 549 sk_init();
550 if (p_WSAEventSelect == NULL) {
551 fprintf(stderr, "Plink requires WinSock 2\n");
12dc4ec0 552 return 1;
553 }
554
555 /*
556 * Start up the connection.
557 */
8df7a775 558 netevent = CreateEvent(NULL, FALSE, FALSE, NULL);
12dc4ec0 559 {
cbe2d68f 560 const char *error;
12dc4ec0 561 char *realhost;
2184a5d9 562 /* nodelay is only useful if stdin is a character device (console) */
563 int nodelay = cfg.tcp_nodelay &&
564 (GetFileType(GetStdHandle(STD_INPUT_HANDLE)) == FILE_TYPE_CHAR);
12dc4ec0 565
86916870 566 error = back->init(NULL, &backhandle, &cfg, cfg.host, cfg.port,
79bf227b 567 &realhost, nodelay, cfg.tcp_keepalives);
12dc4ec0 568 if (error) {
569 fprintf(stderr, "Unable to open connection:\n%s", error);
570 return 1;
571 }
c229ef97 572 logctx = log_init(NULL, &cfg);
a8327734 573 back->provide_logctx(backhandle, logctx);
d3fef4a5 574 console_provide_logctx(logctx);
6e1ebb76 575 sfree(realhost);
12dc4ec0 576 }
8df7a775 577 connopen = 1;
12dc4ec0 578
12dc4ec0 579 stdinevent = CreateEvent(NULL, FALSE, FALSE, NULL);
5471d09a 580 stdoutevent = CreateEvent(NULL, FALSE, FALSE, NULL);
581 stderrevent = CreateEvent(NULL, FALSE, FALSE, NULL);
12dc4ec0 582
0965bee0 583 inhandle = GetStdHandle(STD_INPUT_HANDLE);
12dc4ec0 584 outhandle = GetStdHandle(STD_OUTPUT_HANDLE);
fe50e814 585 errhandle = GetStdHandle(STD_ERROR_HANDLE);
0965bee0 586 GetConsoleMode(inhandle, &orig_console_mode);
587 SetConsoleMode(inhandle, ENABLE_PROCESSED_INPUT);
12dc4ec0 588
c44bf5bd 589 main_thread_id = GetCurrentThreadId();
590
12dc4ec0 591 /*
12dc4ec0 592 * Turn off ECHO and LINE input modes. We don't care if this
593 * call fails, because we know we aren't necessarily running in
594 * a console.
595 */
12dc4ec0 596 handles[0] = netevent;
597 handles[1] = stdinevent;
5471d09a 598 handles[2] = stdoutevent;
599 handles[3] = stderrevent;
12dc4ec0 600 sending = FALSE;
5471d09a 601
602 /*
603 * Create spare threads to write to stdout and stderr, so we
604 * can arrange asynchronous writes.
605 */
606 odata.event = stdoutevent;
607 odata.eventback = CreateEvent(NULL, FALSE, FALSE, NULL);
608 odata.is_stderr = 0;
609 odata.busy = odata.done = 0;
610 if (!CreateThread(NULL, 0, stdout_write_thread,
611 &odata, 0, &out_threadid)) {
612 fprintf(stderr, "Unable to create output thread\n");
93b581bd 613 cleanup_exit(1);
5471d09a 614 }
615 edata.event = stderrevent;
616 edata.eventback = CreateEvent(NULL, FALSE, FALSE, NULL);
617 edata.is_stderr = 1;
618 edata.busy = edata.done = 0;
619 if (!CreateThread(NULL, 0, stdout_write_thread,
620 &edata, 0, &err_threadid)) {
621 fprintf(stderr, "Unable to create error output thread\n");
93b581bd 622 cleanup_exit(1);
5471d09a 623 }
624
12dc4ec0 625 while (1) {
32874aea 626 int n;
627
51470298 628 if (!sending && back->sendok(backhandle)) {
32874aea 629 /*
630 * Create a separate thread to read from stdin. This is
631 * a total pain, but I can't find another way to do it:
632 *
633 * - an overlapped ReadFile or ReadFileEx just doesn't
634 * happen; we get failure from ReadFileEx, and
635 * ReadFile blocks despite being given an OVERLAPPED
636 * structure. Perhaps we can't do overlapped reads
637 * on consoles. WHY THE HELL NOT?
638 *
639 * - WaitForMultipleObjects(netevent, console) doesn't
640 * work, because it signals the console when
641 * _anything_ happens, including mouse motions and
642 * other things that don't cause data to be readable
643 * - so we're back to ReadFile blocking.
644 */
645 idata.event = stdinevent;
646 idata.eventback = CreateEvent(NULL, FALSE, FALSE, NULL);
647 if (!CreateThread(NULL, 0, stdin_read_thread,
5471d09a 648 &idata, 0, &in_threadid)) {
649 fprintf(stderr, "Unable to create input thread\n");
93b581bd 650 cleanup_exit(1);
32874aea 651 }
652 sending = TRUE;
653 }
654
c44bf5bd 655 n = MsgWaitForMultipleObjects(4, handles, FALSE, INFINITE,
656 QS_POSTMESSAGE);
32874aea 657 if (n == 0) {
658 WSANETWORKEVENTS things;
8df7a775 659 SOCKET socket;
d2371c81 660 extern SOCKET first_socket(int *), next_socket(int *);
8df7a775 661 extern int select_result(WPARAM, LPARAM);
32874aea 662 int i, socketstate;
663
664 /*
665 * We must not call select_result() for any socket
666 * until we have finished enumerating within the tree.
667 * This is because select_result() may close the socket
668 * and modify the tree.
669 */
670 /* Count the active sockets. */
671 i = 0;
672 for (socket = first_socket(&socketstate);
673 socket != INVALID_SOCKET;
674 socket = next_socket(&socketstate)) i++;
675
676 /* Expand the buffer if necessary. */
677 if (i > sksize) {
678 sksize = i + 16;
3d88e64d 679 sklist = sresize(sklist, sksize, SOCKET);
32874aea 680 }
681
682 /* Retrieve the sockets into sklist. */
683 skcount = 0;
684 for (socket = first_socket(&socketstate);
685 socket != INVALID_SOCKET;
d2371c81 686 socket = next_socket(&socketstate)) {
32874aea 687 sklist[skcount++] = socket;
688 }
689
690 /* Now we're done enumerating; go through the list. */
691 for (i = 0; i < skcount; i++) {
692 WPARAM wp;
693 socket = sklist[i];
694 wp = (WPARAM) socket;
7440fd44 695 if (!p_WSAEnumNetworkEvents(socket, NULL, &things)) {
64cdd21b 696 static const struct { int bit, mask; } eventtypes[] = {
697 {FD_CONNECT_BIT, FD_CONNECT},
698 {FD_READ_BIT, FD_READ},
699 {FD_CLOSE_BIT, FD_CLOSE},
700 {FD_OOB_BIT, FD_OOB},
701 {FD_WRITE_BIT, FD_WRITE},
702 {FD_ACCEPT_BIT, FD_ACCEPT},
703 };
704 int e;
705
32874aea 706 noise_ultralight(socket);
707 noise_ultralight(things.lNetworkEvents);
d74d141c 708
64cdd21b 709 for (e = 0; e < lenof(eventtypes); e++)
710 if (things.lNetworkEvents & eventtypes[e].mask) {
711 LPARAM lp;
712 int err = things.iErrorCode[eventtypes[e].bit];
713 lp = WSAMAKESELECTREPLY(eventtypes[e].mask, err);
714 connopen &= select_result(wp, lp);
715 }
8df7a775 716 }
717 }
32874aea 718 } else if (n == 1) {
5471d09a 719 reading = 0;
32874aea 720 noise_ultralight(idata.len);
51470298 721 if (connopen && back->socket(backhandle) != NULL) {
42856df4 722 if (idata.len > 0) {
51470298 723 back->send(backhandle, idata.buffer, idata.len);
42856df4 724 } else {
51470298 725 back->special(backhandle, TS_EOF);
42856df4 726 }
32874aea 727 }
5471d09a 728 } else if (n == 2) {
729 odata.busy = 0;
730 if (!odata.writeret) {
731 fprintf(stderr, "Unable to write to standard output\n");
93b581bd 732 cleanup_exit(0);
5471d09a 733 }
734 bufchain_consume(&stdout_data, odata.lenwritten);
735 if (bufchain_size(&stdout_data) > 0)
736 try_output(0);
51470298 737 if (connopen && back->socket(backhandle) != NULL) {
738 back->unthrottle(backhandle, bufchain_size(&stdout_data) +
42856df4 739 bufchain_size(&stderr_data));
740 }
5471d09a 741 } else if (n == 3) {
742 edata.busy = 0;
743 if (!edata.writeret) {
744 fprintf(stderr, "Unable to write to standard output\n");
93b581bd 745 cleanup_exit(0);
5471d09a 746 }
747 bufchain_consume(&stderr_data, edata.lenwritten);
748 if (bufchain_size(&stderr_data) > 0)
749 try_output(1);
51470298 750 if (connopen && back->socket(backhandle) != NULL) {
751 back->unthrottle(backhandle, bufchain_size(&stdout_data) +
42856df4 752 bufchain_size(&stderr_data));
753 }
c44bf5bd 754 } else if (n == 4) {
755 MSG msg;
756 while (PeekMessage(&msg, INVALID_HANDLE_VALUE,
757 WM_AGENT_CALLBACK, WM_AGENT_CALLBACK,
758 PM_REMOVE)) {
759 struct agent_callback *c = (struct agent_callback *)msg.lParam;
760 c->callback(c->callback_ctx, c->data, c->len);
761 sfree(c);
762 }
5471d09a 763 }
51470298 764 if (!reading && back->sendbuffer(backhandle) < MAX_STDIN_BACKLOG) {
32874aea 765 SetEvent(idata.eventback);
5471d09a 766 reading = 1;
32874aea 767 }
51470298 768 if ((!connopen || back->socket(backhandle) == NULL) &&
42856df4 769 bufchain_size(&stdout_data) == 0 &&
770 bufchain_size(&stderr_data) == 0)
32874aea 771 break; /* we closed the connection */
12dc4ec0 772 }
51470298 773 exitcode = back->exitcode(backhandle);
d8d6c7e5 774 if (exitcode < 0) {
775 fprintf(stderr, "Remote process exit code unavailable\n");
776 exitcode = 1; /* this is an error condition */
777 }
7440fd44 778 cleanup_exit(exitcode);
779 return 0; /* placate compiler warning */
12dc4ec0 780}