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