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