Ensure our network layer is properly cleaned up before PuTTY exits.
[u/mdw/putty] / plink.c
CommitLineData
12dc4ec0 1/*
2 * PLink - a command-line (stdin/stdout) variant of PuTTY.
3 */
4
4d331a77 5#ifndef AUTO_WINSOCK
12dc4ec0 6#include <winsock2.h>
4d331a77 7#endif
12dc4ec0 8#include <windows.h>
9#include <stdio.h>
49bad831 10#include <stdlib.h>
2b0c045b 11#include <assert.h>
12dc4ec0 12#include <stdarg.h>
13
32874aea 14#define PUTTY_DO_GLOBALS /* actually _define_ globals */
12dc4ec0 15#include "putty.h"
a9422f39 16#include "storage.h"
8df7a775 17#include "tree234.h"
12dc4ec0 18
5471d09a 19#define MAX_STDIN_BACKLOG 4096
20
32874aea 21void fatalbox(char *p, ...)
22{
12dc4ec0 23 va_list ap;
49bad831 24 fprintf(stderr, "FATAL ERROR: ");
12dc4ec0 25 va_start(ap, p);
26 vfprintf(stderr, p, ap);
27 va_end(ap);
28 fputc('\n', stderr);
29 WSACleanup();
93b581bd 30 cleanup_exit(1);
12dc4ec0 31}
32874aea 32void connection_fatal(char *p, ...)
33{
8d5de777 34 va_list ap;
49bad831 35 fprintf(stderr, "FATAL ERROR: ");
8d5de777 36 va_start(ap, p);
37 vfprintf(stderr, p, ap);
38 va_end(ap);
39 fputc('\n', stderr);
40 WSACleanup();
93b581bd 41 cleanup_exit(1);
8d5de777 42}
12dc4ec0 43
d8426c54 44static char *password = NULL;
45
0965bee0 46HANDLE inhandle, outhandle, errhandle;
6f34e365 47DWORD orig_console_mode;
48
8df7a775 49WSAEVENT netevent;
50
32874aea 51int term_ldisc(int mode)
52{
53 return FALSE;
54}
55void ldisc_update(int echo, int edit)
56{
0965bee0 57 /* Update stdin read mode to reflect changes in line discipline. */
58 DWORD mode;
59
60 mode = ENABLE_PROCESSED_INPUT;
61 if (echo)
32874aea 62 mode = mode | ENABLE_ECHO_INPUT;
0965bee0 63 else
32874aea 64 mode = mode & ~ENABLE_ECHO_INPUT;
0965bee0 65 if (edit)
32874aea 66 mode = mode | ENABLE_LINE_INPUT;
0965bee0 67 else
32874aea 68 mode = mode & ~ENABLE_LINE_INPUT;
0965bee0 69 SetConsoleMode(inhandle, mode);
70}
71
5471d09a 72struct input_data {
73 DWORD len;
74 char buffer[4096];
75 HANDLE event, eventback;
76};
77
32874aea 78static DWORD WINAPI stdin_read_thread(void *param)
79{
80 struct input_data *idata = (struct input_data *) param;
12dc4ec0 81 HANDLE inhandle;
82
83 inhandle = GetStdHandle(STD_INPUT_HANDLE);
84
85 while (ReadFile(inhandle, idata->buffer, sizeof(idata->buffer),
32874aea 86 &idata->len, NULL) && idata->len > 0) {
87 SetEvent(idata->event);
88 WaitForSingleObject(idata->eventback, INFINITE);
12dc4ec0 89 }
90
91 idata->len = 0;
92 SetEvent(idata->event);
93
94 return 0;
95}
96
5471d09a 97struct output_data {
98 DWORD len, lenwritten;
99 int writeret;
100 char *buffer;
101 int is_stderr, done;
102 HANDLE event, eventback;
103 int busy;
104};
105
106static DWORD WINAPI stdout_write_thread(void *param)
107{
108 struct output_data *odata = (struct output_data *) param;
109 HANDLE outhandle, errhandle;
110
111 outhandle = GetStdHandle(STD_OUTPUT_HANDLE);
112 errhandle = GetStdHandle(STD_ERROR_HANDLE);
113
114 while (1) {
115 WaitForSingleObject(odata->eventback, INFINITE);
116 if (odata->done)
117 break;
118 odata->writeret =
119 WriteFile(odata->is_stderr ? errhandle : outhandle,
120 odata->buffer, odata->len, &odata->lenwritten, NULL);
121 SetEvent(odata->event);
122 }
123
124 return 0;
125}
126
127bufchain stdout_data, stderr_data;
128struct output_data odata, edata;
129
130void try_output(int is_stderr)
131{
132 struct output_data *data = (is_stderr ? &edata : &odata);
133 void *senddata;
134 int sendlen;
135
136 if (!data->busy) {
137 bufchain_prefix(is_stderr ? &stderr_data : &stdout_data,
138 &senddata, &sendlen);
139 data->buffer = senddata;
140 data->len = sendlen;
141 SetEvent(data->eventback);
142 data->busy = 1;
143 }
144}
145
146int from_backend(int is_stderr, char *data, int len)
147{
5471d09a 148 HANDLE h = (is_stderr ? errhandle : outhandle);
5471d09a 149 int osize, esize;
150
2b0c045b 151 assert(len > 0);
152
5471d09a 153 if (is_stderr) {
154 bufchain_add(&stderr_data, data, len);
155 try_output(1);
156 } else {
157 bufchain_add(&stdout_data, data, len);
158 try_output(0);
159 }
160
161 osize = bufchain_size(&stdout_data);
162 esize = bufchain_size(&stderr_data);
163
164 return osize + esize;
165}
166
d8426c54 167/*
168 * Short description of parameters.
169 */
170static void usage(void)
171{
172 printf("PuTTY Link: command-line connection utility\n");
173 printf("%s\n", ver);
174 printf("Usage: plink [options] [user@]host [command]\n");
e672967c 175 printf(" (\"host\" can also be a PuTTY saved session name)\n");
d8426c54 176 printf("Options:\n");
177 printf(" -v show verbose messages\n");
178 printf(" -ssh force use of ssh protocol\n");
179 printf(" -P port connect to specified port\n");
180 printf(" -pw passw login with specified password\n");
96621a84 181 printf(" -m file read remote command(s) from file\n");
e7aabca4 182 printf(" -L listen-port:host:port Forward local port to "
183 "remote address\n");
184 printf(" -R listen-port:host:port Forward remote port to"
185 " local address\n");
d8426c54 186 exit(1);
187}
188
32874aea 189char *do_select(SOCKET skt, int startup)
190{
8df7a775 191 int events;
192 if (startup) {
3ad9d396 193 events = (FD_CONNECT | FD_READ | FD_WRITE |
194 FD_OOB | FD_CLOSE | FD_ACCEPT);
8df7a775 195 } else {
196 events = 0;
197 }
32874aea 198 if (WSAEventSelect(skt, netevent, events) == SOCKET_ERROR) {
199 switch (WSAGetLastError()) {
200 case WSAENETDOWN:
201 return "Network is down";
202 default:
203 return "WSAAsyncSelect(): unknown error";
204 }
8df7a775 205 }
206 return NULL;
207}
208
32874aea 209int main(int argc, char **argv)
210{
12dc4ec0 211 WSADATA wsadata;
212 WORD winsock_ver;
5471d09a 213 WSAEVENT stdinevent, stdoutevent, stderrevent;
214 HANDLE handles[4];
215 DWORD in_threadid, out_threadid, err_threadid;
12dc4ec0 216 struct input_data idata;
5471d09a 217 int reading;
12dc4ec0 218 int sending;
d8426c54 219 int portnumber = -1;
8df7a775 220 SOCKET *sklist;
221 int skcount, sksize;
222 int connopen;
d8d6c7e5 223 int exitcode;
e7aabca4 224 char extra_portfwd[sizeof(cfg.portfwd)];
12dc4ec0 225
ff2ae367 226 ssh_get_line = console_get_line;
67779be7 227
32874aea 228 sklist = NULL;
229 skcount = sksize = 0;
c9bdcd96 230 /*
231 * Initialise port and protocol to sensible defaults. (These
232 * will be overridden by more or less anything.)
233 */
234 default_protocol = PROT_SSH;
235 default_port = 22;
8df7a775 236
67779be7 237 flags = FLAG_STDERR;
12dc4ec0 238 /*
239 * Process the command line.
240 */
a9422f39 241 do_defaults(NULL, &cfg);
e7a7383f 242 default_protocol = cfg.protocol;
243 default_port = cfg.port;
8cb9c947 244 {
32874aea 245 /*
246 * Override the default protocol if PLINK_PROTOCOL is set.
247 */
248 char *p = getenv("PLINK_PROTOCOL");
249 int i;
250 if (p) {
251 for (i = 0; backends[i].backend != NULL; i++) {
252 if (!strcmp(backends[i].name, p)) {
253 default_protocol = cfg.protocol = backends[i].protocol;
254 default_port = cfg.port =
255 backends[i].backend->default_port;
256 break;
257 }
258 }
259 }
8cb9c947 260 }
12dc4ec0 261 while (--argc) {
32874aea 262 char *p = *++argv;
263 if (*p == '-') {
264 if (!strcmp(p, "-ssh")) {
12dc4ec0 265 default_protocol = cfg.protocol = PROT_SSH;
266 default_port = cfg.port = 22;
32874aea 267 } else if (!strcmp(p, "-telnet")) {
9d33ebdd 268 default_protocol = cfg.protocol = PROT_TELNET;
269 default_port = cfg.port = 23;
66a3d938 270 } else if (!strcmp(p, "-rlogin")) {
271 default_protocol = cfg.protocol = PROT_RLOGIN;
272 default_port = cfg.port = 513;
32874aea 273 } else if (!strcmp(p, "-raw")) {
9d33ebdd 274 default_protocol = cfg.protocol = PROT_RAW;
ff2ae367 275 } else if (!strcmp(p, "-batch")) {
276 console_batch_mode = TRUE;
67779be7 277 } else if (!strcmp(p, "-v")) {
32874aea 278 flags |= FLAG_VERBOSE;
12dc4ec0 279 } else if (!strcmp(p, "-log")) {
32874aea 280 logfile = "putty.log";
281 } else if (!strcmp(p, "-pw") && argc > 1) {
ff2ae367 282 --argc, console_password = *++argv;
32874aea 283 } else if (!strcmp(p, "-l") && argc > 1) {
284 char *username;
285 --argc, username = *++argv;
286 strncpy(cfg.username, username, sizeof(cfg.username));
287 cfg.username[sizeof(cfg.username) - 1] = '\0';
e7aabca4 288 } else if ((!strcmp(p, "-L") || !strcmp(p, "-R")) && argc > 1) {
41ff4658 289 char *fwd, *ptr, *q;
e7aabca4 290 int i=0;
291 --argc, fwd = *++argv;
292 ptr = extra_portfwd;
293 /* if multiple forwards, find end of list */
294 if (ptr[0]=='R' || ptr[0]=='L') {
295 for (i = 0; i < sizeof(extra_portfwd) - 2; i++)
296 if (ptr[i]=='\000' && ptr[i+1]=='\000')
297 break;
298 ptr = ptr + i + 1; /* point to next forward slot */
299 }
300 ptr[0] = p[1]; /* insert a 'L' or 'R' at the start */
301 strncpy(ptr+1, fwd, sizeof(extra_portfwd) - i);
41ff4658 302 q = strchr(ptr, ':');
303 if (q) *q = '\t'; /* replace first : with \t */
e7aabca4 304 ptr[strlen(ptr)+1] = '\000'; /* append two '\000' */
305 extra_portfwd[sizeof(extra_portfwd) - 1] = '\0';
32874aea 306 } else if (!strcmp(p, "-m") && argc > 1) {
307 char *filename, *command;
308 int cmdlen, cmdsize;
309 FILE *fp;
310 int c, d;
311
312 --argc, filename = *++argv;
313
314 cmdlen = cmdsize = 0;
315 command = NULL;
316 fp = fopen(filename, "r");
317 if (!fp) {
318 fprintf(stderr, "plink: unable to open command "
319 "file \"%s\"\n", filename);
320 return 1;
321 }
322 do {
323 c = fgetc(fp);
324 d = c;
325 if (c == EOF)
326 d = 0;
327 if (cmdlen >= cmdsize) {
328 cmdsize = cmdlen + 512;
329 command = srealloc(command, cmdsize);
330 }
331 command[cmdlen++] = d;
332 } while (c != EOF);
333 cfg.remote_cmd_ptr = command;
fd5e5847 334 cfg.remote_cmd_ptr2 = NULL;
32874aea 335 cfg.nopty = TRUE; /* command => no terminal */
336 } else if (!strcmp(p, "-P") && argc > 1) {
337 --argc, portnumber = atoi(*++argv);
338 }
12dc4ec0 339 } else if (*p) {
32874aea 340 if (!*cfg.host) {
341 char *q = p;
342 /*
343 * If the hostname starts with "telnet:", set the
344 * protocol to Telnet and process the string as a
345 * Telnet URL.
346 */
347 if (!strncmp(q, "telnet:", 7)) {
348 char c;
349
350 q += 7;
351 if (q[0] == '/' && q[1] == '/')
352 q += 2;
353 cfg.protocol = PROT_TELNET;
354 p = q;
355 while (*p && *p != ':' && *p != '/')
356 p++;
357 c = *p;
358 if (*p)
359 *p++ = '\0';
360 if (c == ':')
361 cfg.port = atoi(p);
362 else
363 cfg.port = -1;
364 strncpy(cfg.host, q, sizeof(cfg.host) - 1);
365 cfg.host[sizeof(cfg.host) - 1] = '\0';
366 } else {
367 char *r;
368 /*
369 * Before we process the [user@]host string, we
370 * first check for the presence of a protocol
371 * prefix (a protocol name followed by ",").
372 */
373 r = strchr(p, ',');
374 if (r) {
375 int i, j;
376 for (i = 0; backends[i].backend != NULL; i++) {
377 j = strlen(backends[i].name);
378 if (j == r - p &&
379 !memcmp(backends[i].name, p, j)) {
380 default_protocol = cfg.protocol =
381 backends[i].protocol;
382 portnumber =
383 backends[i].backend->default_port;
384 p = r + 1;
385 break;
386 }
387 }
388 }
389
390 /*
391 * Three cases. Either (a) there's a nonzero
392 * length string followed by an @, in which
393 * case that's user and the remainder is host.
394 * Or (b) there's only one string, not counting
395 * a potential initial @, and it exists in the
396 * saved-sessions database. Or (c) only one
397 * string and it _doesn't_ exist in the
398 * database.
399 */
400 r = strrchr(p, '@');
401 if (r == p)
402 p++, r = NULL; /* discount initial @ */
403 if (r == NULL) {
404 /*
405 * One string.
406 */
407 Config cfg2;
408 do_defaults(p, &cfg2);
409 if (cfg2.host[0] == '\0') {
410 /* No settings for this host; use defaults */
411 strncpy(cfg.host, p, sizeof(cfg.host) - 1);
412 cfg.host[sizeof(cfg.host) - 1] = '\0';
413 cfg.port = default_port;
414 } else {
415 cfg = cfg2;
416 cfg.remote_cmd_ptr = cfg.remote_cmd;
417 }
418 } else {
419 *r++ = '\0';
420 strncpy(cfg.username, p, sizeof(cfg.username) - 1);
421 cfg.username[sizeof(cfg.username) - 1] = '\0';
422 strncpy(cfg.host, r, sizeof(cfg.host) - 1);
423 cfg.host[sizeof(cfg.host) - 1] = '\0';
424 cfg.port = default_port;
425 }
426 }
427 } else {
385528da 428 char *command;
429 int cmdlen, cmdsize;
430 cmdlen = cmdsize = 0;
431 command = NULL;
432
433 while (argc) {
434 while (*p) {
435 if (cmdlen >= cmdsize) {
436 cmdsize = cmdlen + 512;
437 command = srealloc(command, cmdsize);
438 }
439 command[cmdlen++]=*p++;
440 }
441 if (cmdlen >= cmdsize) {
442 cmdsize = cmdlen + 512;
443 command = srealloc(command, cmdsize);
444 }
445 command[cmdlen++]=' '; /* always add trailing space */
446 if (--argc) p = *++argv;
32874aea 447 }
385528da 448 if (cmdlen) command[--cmdlen]='\0';
449 /* change trailing blank to NUL */
450 cfg.remote_cmd_ptr = command;
451 cfg.remote_cmd_ptr2 = NULL;
32874aea 452 cfg.nopty = TRUE; /* command => no terminal */
385528da 453
32874aea 454 break; /* done with cmdline */
455 }
12dc4ec0 456 }
457 }
458
d8426c54 459 if (!*cfg.host) {
32874aea 460 usage();
d8426c54 461 }
d8426c54 462
449925a6 463 /*
464 * Trim leading whitespace off the hostname if it's there.
465 */
466 {
467 int space = strspn(cfg.host, " \t");
468 memmove(cfg.host, cfg.host+space, 1+strlen(cfg.host)-space);
469 }
470
471 /* See if host is of the form user@host */
472 if (cfg.host[0] != '\0') {
473 char *atsign = strchr(cfg.host, '@');
474 /* Make sure we're not overflowing the user field */
475 if (atsign) {
476 if (atsign - cfg.host < sizeof cfg.username) {
477 strncpy(cfg.username, cfg.host, atsign - cfg.host);
478 cfg.username[atsign - cfg.host] = '\0';
479 }
480 memmove(cfg.host, atsign + 1, 1 + strlen(atsign + 1));
481 }
482 }
483
484 /*
485 * Trim a colon suffix off the hostname if it's there.
486 */
487 cfg.host[strcspn(cfg.host, ":")] = '\0';
488
96621a84 489 if (!*cfg.remote_cmd_ptr)
32874aea 490 flags |= FLAG_INTERACTIVE;
67779be7 491
12dc4ec0 492 /*
493 * Select protocol. This is farmed out into a table in a
494 * separate file to enable an ssh-free variant.
495 */
496 {
32874aea 497 int i;
498 back = NULL;
499 for (i = 0; backends[i].backend != NULL; i++)
500 if (backends[i].protocol == cfg.protocol) {
501 back = backends[i].backend;
502 break;
503 }
504 if (back == NULL) {
505 fprintf(stderr,
506 "Internal fault: Unsupported protocol found\n");
507 return 1;
508 }
12dc4ec0 509 }
510
511 /*
e7aabca4 512 * Add extra port forwardings (accumulated on command line) to
513 * cfg.
514 */
515 {
516 int i;
517 char *p;
518 p = extra_portfwd;
519 i = 0;
520 while (cfg.portfwd[i])
521 i += strlen(cfg.portfwd+i) + 1;
522 while (*p) {
523 if (strlen(p)+2 > sizeof(cfg.portfwd)-i) {
524 fprintf(stderr, "Internal fault: not enough space for all"
525 " port forwardings\n");
526 break;
527 }
528 strncpy(cfg.portfwd+i, p, sizeof(cfg.portfwd)-i-1);
529 i += strlen(cfg.portfwd+i) + 1;
530 cfg.portfwd[i] = '\0';
531 p += strlen(p)+1;
532 }
533 }
534
535 /*
8cb9c947 536 * Select port.
537 */
538 if (portnumber != -1)
32874aea 539 cfg.port = portnumber;
8cb9c947 540
541 /*
12dc4ec0 542 * Initialise WinSock.
543 */
544 winsock_ver = MAKEWORD(2, 0);
545 if (WSAStartup(winsock_ver, &wsadata)) {
546 MessageBox(NULL, "Unable to initialise WinSock", "WinSock Error",
547 MB_OK | MB_ICONEXCLAMATION);
548 return 1;
549 }
550 if (LOBYTE(wsadata.wVersion) != 2 || HIBYTE(wsadata.wVersion) != 0) {
551 MessageBox(NULL, "WinSock version is incompatible with 2.0",
552 "WinSock Error", MB_OK | MB_ICONEXCLAMATION);
553 WSACleanup();
554 return 1;
555 }
8df7a775 556 sk_init();
12dc4ec0 557
558 /*
559 * Start up the connection.
560 */
8df7a775 561 netevent = CreateEvent(NULL, FALSE, FALSE, NULL);
12dc4ec0 562 {
563 char *error;
564 char *realhost;
2184a5d9 565 /* nodelay is only useful if stdin is a character device (console) */
566 int nodelay = cfg.tcp_nodelay &&
567 (GetFileType(GetStdHandle(STD_INPUT_HANDLE)) == FILE_TYPE_CHAR);
12dc4ec0 568
2184a5d9 569 error = back->init(cfg.host, cfg.port, &realhost, nodelay);
12dc4ec0 570 if (error) {
571 fprintf(stderr, "Unable to open connection:\n%s", error);
572 return 1;
573 }
6e1ebb76 574 sfree(realhost);
12dc4ec0 575 }
8df7a775 576 connopen = 1;
12dc4ec0 577
12dc4ec0 578 stdinevent = CreateEvent(NULL, FALSE, FALSE, NULL);
5471d09a 579 stdoutevent = CreateEvent(NULL, FALSE, FALSE, NULL);
580 stderrevent = CreateEvent(NULL, FALSE, FALSE, NULL);
12dc4ec0 581
0965bee0 582 inhandle = GetStdHandle(STD_INPUT_HANDLE);
12dc4ec0 583 outhandle = GetStdHandle(STD_OUTPUT_HANDLE);
fe50e814 584 errhandle = GetStdHandle(STD_ERROR_HANDLE);
0965bee0 585 GetConsoleMode(inhandle, &orig_console_mode);
586 SetConsoleMode(inhandle, ENABLE_PROCESSED_INPUT);
12dc4ec0 587
588 /*
12dc4ec0 589 * Turn off ECHO and LINE input modes. We don't care if this
590 * call fails, because we know we aren't necessarily running in
591 * a console.
592 */
12dc4ec0 593 handles[0] = netevent;
594 handles[1] = stdinevent;
5471d09a 595 handles[2] = stdoutevent;
596 handles[3] = stderrevent;
12dc4ec0 597 sending = FALSE;
5471d09a 598
599 /*
600 * Create spare threads to write to stdout and stderr, so we
601 * can arrange asynchronous writes.
602 */
603 odata.event = stdoutevent;
604 odata.eventback = CreateEvent(NULL, FALSE, FALSE, NULL);
605 odata.is_stderr = 0;
606 odata.busy = odata.done = 0;
607 if (!CreateThread(NULL, 0, stdout_write_thread,
608 &odata, 0, &out_threadid)) {
609 fprintf(stderr, "Unable to create output thread\n");
93b581bd 610 cleanup_exit(1);
5471d09a 611 }
612 edata.event = stderrevent;
613 edata.eventback = CreateEvent(NULL, FALSE, FALSE, NULL);
614 edata.is_stderr = 1;
615 edata.busy = edata.done = 0;
616 if (!CreateThread(NULL, 0, stdout_write_thread,
617 &edata, 0, &err_threadid)) {
618 fprintf(stderr, "Unable to create error output thread\n");
93b581bd 619 cleanup_exit(1);
5471d09a 620 }
621
12dc4ec0 622 while (1) {
32874aea 623 int n;
624
625 if (!sending && back->sendok()) {
626 /*
627 * Create a separate thread to read from stdin. This is
628 * a total pain, but I can't find another way to do it:
629 *
630 * - an overlapped ReadFile or ReadFileEx just doesn't
631 * happen; we get failure from ReadFileEx, and
632 * ReadFile blocks despite being given an OVERLAPPED
633 * structure. Perhaps we can't do overlapped reads
634 * on consoles. WHY THE HELL NOT?
635 *
636 * - WaitForMultipleObjects(netevent, console) doesn't
637 * work, because it signals the console when
638 * _anything_ happens, including mouse motions and
639 * other things that don't cause data to be readable
640 * - so we're back to ReadFile blocking.
641 */
642 idata.event = stdinevent;
643 idata.eventback = CreateEvent(NULL, FALSE, FALSE, NULL);
644 if (!CreateThread(NULL, 0, stdin_read_thread,
5471d09a 645 &idata, 0, &in_threadid)) {
646 fprintf(stderr, "Unable to create input thread\n");
93b581bd 647 cleanup_exit(1);
32874aea 648 }
649 sending = TRUE;
650 }
651
5471d09a 652 n = WaitForMultipleObjects(4, handles, FALSE, INFINITE);
32874aea 653 if (n == 0) {
654 WSANETWORKEVENTS things;
8df7a775 655 SOCKET socket;
d2371c81 656 extern SOCKET first_socket(int *), next_socket(int *);
8df7a775 657 extern int select_result(WPARAM, LPARAM);
32874aea 658 int i, socketstate;
659
660 /*
661 * We must not call select_result() for any socket
662 * until we have finished enumerating within the tree.
663 * This is because select_result() may close the socket
664 * and modify the tree.
665 */
666 /* Count the active sockets. */
667 i = 0;
668 for (socket = first_socket(&socketstate);
669 socket != INVALID_SOCKET;
670 socket = next_socket(&socketstate)) i++;
671
672 /* Expand the buffer if necessary. */
673 if (i > sksize) {
674 sksize = i + 16;
675 sklist = srealloc(sklist, sksize * sizeof(*sklist));
676 }
677
678 /* Retrieve the sockets into sklist. */
679 skcount = 0;
680 for (socket = first_socket(&socketstate);
681 socket != INVALID_SOCKET;
d2371c81 682 socket = next_socket(&socketstate)) {
32874aea 683 sklist[skcount++] = socket;
684 }
685
686 /* Now we're done enumerating; go through the list. */
687 for (i = 0; i < skcount; i++) {
688 WPARAM wp;
689 socket = sklist[i];
690 wp = (WPARAM) socket;
ffb959c7 691 if (!WSAEnumNetworkEvents(socket, NULL, &things)) {
64cdd21b 692 static const struct { int bit, mask; } eventtypes[] = {
693 {FD_CONNECT_BIT, FD_CONNECT},
694 {FD_READ_BIT, FD_READ},
695 {FD_CLOSE_BIT, FD_CLOSE},
696 {FD_OOB_BIT, FD_OOB},
697 {FD_WRITE_BIT, FD_WRITE},
698 {FD_ACCEPT_BIT, FD_ACCEPT},
699 };
700 int e;
701
32874aea 702 noise_ultralight(socket);
703 noise_ultralight(things.lNetworkEvents);
d74d141c 704
64cdd21b 705 for (e = 0; e < lenof(eventtypes); e++)
706 if (things.lNetworkEvents & eventtypes[e].mask) {
707 LPARAM lp;
708 int err = things.iErrorCode[eventtypes[e].bit];
709 lp = WSAMAKESELECTREPLY(eventtypes[e].mask, err);
710 connopen &= select_result(wp, lp);
711 }
8df7a775 712 }
713 }
32874aea 714 } else if (n == 1) {
5471d09a 715 reading = 0;
32874aea 716 noise_ultralight(idata.len);
42856df4 717 if (connopen && back->socket() != NULL) {
718 if (idata.len > 0) {
719 back->send(idata.buffer, idata.len);
720 } else {
721 back->special(TS_EOF);
722 }
32874aea 723 }
5471d09a 724 } else if (n == 2) {
725 odata.busy = 0;
726 if (!odata.writeret) {
727 fprintf(stderr, "Unable to write to standard output\n");
93b581bd 728 cleanup_exit(0);
5471d09a 729 }
730 bufchain_consume(&stdout_data, odata.lenwritten);
731 if (bufchain_size(&stdout_data) > 0)
732 try_output(0);
42856df4 733 if (connopen && back->socket() != NULL) {
734 back->unthrottle(bufchain_size(&stdout_data) +
735 bufchain_size(&stderr_data));
736 }
5471d09a 737 } else if (n == 3) {
738 edata.busy = 0;
739 if (!edata.writeret) {
740 fprintf(stderr, "Unable to write to standard output\n");
93b581bd 741 cleanup_exit(0);
5471d09a 742 }
743 bufchain_consume(&stderr_data, edata.lenwritten);
744 if (bufchain_size(&stderr_data) > 0)
745 try_output(1);
42856df4 746 if (connopen && back->socket() != NULL) {
747 back->unthrottle(bufchain_size(&stdout_data) +
748 bufchain_size(&stderr_data));
749 }
5471d09a 750 }
751 if (!reading && back->sendbuffer() < MAX_STDIN_BACKLOG) {
32874aea 752 SetEvent(idata.eventback);
5471d09a 753 reading = 1;
32874aea 754 }
42856df4 755 if ((!connopen || back->socket() == NULL) &&
756 bufchain_size(&stdout_data) == 0 &&
757 bufchain_size(&stderr_data) == 0)
32874aea 758 break; /* we closed the connection */
12dc4ec0 759 }
760 WSACleanup();
d8d6c7e5 761 exitcode = back->exitcode();
762 if (exitcode < 0) {
763 fprintf(stderr, "Remote process exit code unavailable\n");
764 exitcode = 1; /* this is an error condition */
765 }
766 return exitcode;
12dc4ec0 767}