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