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