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