]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - windows/winplink.c
Make get_user_sid() return the cached copy if one already exists.
[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 struct agent_callback {
18     void (*callback)(void *, void *, int);
19     void *callback_ctx;
20     void *data;
21     int len;
22 };
23
24 void fatalbox(char *p, ...)
25 {
26     va_list ap;
27     fprintf(stderr, "FATAL ERROR: ");
28     va_start(ap, p);
29     vfprintf(stderr, p, ap);
30     va_end(ap);
31     fputc('\n', stderr);
32     if (logctx) {
33         log_free(logctx);
34         logctx = NULL;
35     }
36     cleanup_exit(1);
37 }
38 void modalfatalbox(char *p, ...)
39 {
40     va_list ap;
41     fprintf(stderr, "FATAL ERROR: ");
42     va_start(ap, p);
43     vfprintf(stderr, p, ap);
44     va_end(ap);
45     fputc('\n', stderr);
46     if (logctx) {
47         log_free(logctx);
48         logctx = NULL;
49     }
50     cleanup_exit(1);
51 }
52 void nonfatal(char *p, ...)
53 {
54     va_list ap;
55     fprintf(stderr, "ERROR: ");
56     va_start(ap, p);
57     vfprintf(stderr, p, ap);
58     va_end(ap);
59     fputc('\n', stderr);
60 }
61 void connection_fatal(void *frontend, char *p, ...)
62 {
63     va_list ap;
64     fprintf(stderr, "FATAL ERROR: ");
65     va_start(ap, p);
66     vfprintf(stderr, p, ap);
67     va_end(ap);
68     fputc('\n', stderr);
69     if (logctx) {
70         log_free(logctx);
71         logctx = NULL;
72     }
73     cleanup_exit(1);
74 }
75 void cmdline_error(char *p, ...)
76 {
77     va_list ap;
78     fprintf(stderr, "plink: ");
79     va_start(ap, p);
80     vfprintf(stderr, p, ap);
81     va_end(ap);
82     fputc('\n', stderr);
83     exit(1);
84 }
85
86 HANDLE inhandle, outhandle, errhandle;
87 struct handle *stdin_handle, *stdout_handle, *stderr_handle;
88 DWORD orig_console_mode;
89 int connopen;
90
91 WSAEVENT netevent;
92
93 static Backend *back;
94 static void *backhandle;
95 static Conf *conf;
96
97 int term_ldisc(Terminal *term, int mode)
98 {
99     return FALSE;
100 }
101 void ldisc_update(void *frontend, int echo, int edit)
102 {
103     /* Update stdin read mode to reflect changes in line discipline. */
104     DWORD mode;
105
106     mode = ENABLE_PROCESSED_INPUT;
107     if (echo)
108         mode = mode | ENABLE_ECHO_INPUT;
109     else
110         mode = mode & ~ENABLE_ECHO_INPUT;
111     if (edit)
112         mode = mode | ENABLE_LINE_INPUT;
113     else
114         mode = mode & ~ENABLE_LINE_INPUT;
115     SetConsoleMode(inhandle, mode);
116 }
117
118 char *get_ttymode(void *frontend, const char *mode) { return NULL; }
119
120 int from_backend(void *frontend_handle, int is_stderr,
121                  const char *data, int len)
122 {
123     if (is_stderr) {
124         handle_write(stderr_handle, data, len);
125     } else {
126         handle_write(stdout_handle, data, len);
127     }
128
129     return handle_backlog(stdout_handle) + handle_backlog(stderr_handle);
130 }
131
132 int from_backend_untrusted(void *frontend_handle, const char *data, int len)
133 {
134     /*
135      * No "untrusted" output should get here (the way the code is
136      * currently, it's all diverted by FLAG_STDERR).
137      */
138     assert(!"Unexpected call to from_backend_untrusted()");
139     return 0; /* not reached */
140 }
141
142 int from_backend_eof(void *frontend_handle)
143 {
144     handle_write_eof(stdout_handle);
145     return FALSE;   /* do not respond to incoming EOF with outgoing */
146 }
147
148 int get_userpass_input(prompts_t *p, unsigned char *in, int inlen)
149 {
150     int ret;
151     ret = cmdline_get_passwd_input(p, in, inlen);
152     if (ret == -1)
153         ret = console_get_userpass_input(p, in, inlen);
154     return ret;
155 }
156
157 static DWORD main_thread_id;
158
159 void agent_schedule_callback(void (*callback)(void *, void *, int),
160                              void *callback_ctx, void *data, int len)
161 {
162     struct agent_callback *c = snew(struct agent_callback);
163     c->callback = callback;
164     c->callback_ctx = callback_ctx;
165     c->data = data;
166     c->len = len;
167     PostThreadMessage(main_thread_id, WM_AGENT_CALLBACK, 0, (LPARAM)c);
168 }
169
170 /*
171  *  Short description of parameters.
172  */
173 static void usage(void)
174 {
175     printf("Plink: command-line connection utility\n");
176     printf("%s\n", ver);
177     printf("Usage: plink [options] [user@]host [command]\n");
178     printf("       (\"host\" can also be a PuTTY saved session name)\n");
179     printf("Options:\n");
180     printf("  -V        print version information and exit\n");
181     printf("  -pgpfp    print PGP key fingerprints and exit\n");
182     printf("  -v        show verbose messages\n");
183     printf("  -load sessname  Load settings from saved session\n");
184     printf("  -ssh -telnet -rlogin -raw -serial\n");
185     printf("            force use of a particular protocol\n");
186     printf("  -P port   connect to specified port\n");
187     printf("  -l user   connect with specified username\n");
188     printf("  -batch    disable all interactive prompts\n");
189     printf("  -sercfg configuration-string (e.g. 19200,8,n,1,X)\n");
190     printf("            Specify the serial configuration (serial only)\n");
191     printf("The following options only apply to SSH connections:\n");
192     printf("  -pw passw login with specified password\n");
193     printf("  -D [listen-IP:]listen-port\n");
194     printf("            Dynamic SOCKS-based port forwarding\n");
195     printf("  -L [listen-IP:]listen-port:host:port\n");
196     printf("            Forward local port to remote address\n");
197     printf("  -R [listen-IP:]listen-port:host:port\n");
198     printf("            Forward remote port to local address\n");
199     printf("  -X -x     enable / disable X11 forwarding\n");
200     printf("  -A -a     enable / disable agent forwarding\n");
201     printf("  -t -T     enable / disable pty allocation\n");
202     printf("  -1 -2     force use of particular protocol version\n");
203     printf("  -4 -6     force use of IPv4 or IPv6\n");
204     printf("  -C        enable compression\n");
205     printf("  -i key    private key file for user authentication\n");
206     printf("  -noagent  disable use of Pageant\n");
207     printf("  -agent    enable use of Pageant\n");
208     printf("  -hostkey aa:bb:cc:...\n");
209     printf("            manually specify a host key (may be repeated)\n");
210     printf("  -m file   read remote command(s) from file\n");
211     printf("  -s        remote command is an SSH subsystem (SSH-2 only)\n");
212     printf("  -N        don't start a shell/command (SSH-2 only)\n");
213     printf("  -nc host:port\n");
214     printf("            open tunnel in place of session (SSH-2 only)\n");
215     printf("  -sshlog file\n");
216     printf("  -sshrawlog file\n");
217     printf("            log protocol details to a file\n");
218     exit(1);
219 }
220
221 static void version(void)
222 {
223     printf("plink: %s\n", ver);
224     exit(1);
225 }
226
227 char *do_select(SOCKET skt, int startup)
228 {
229     int events;
230     if (startup) {
231         events = (FD_CONNECT | FD_READ | FD_WRITE |
232                   FD_OOB | FD_CLOSE | FD_ACCEPT);
233     } else {
234         events = 0;
235     }
236     if (p_WSAEventSelect(skt, netevent, events) == SOCKET_ERROR) {
237         switch (p_WSAGetLastError()) {
238           case WSAENETDOWN:
239             return "Network is down";
240           default:
241             return "WSAEventSelect(): unknown error";
242         }
243     }
244     return NULL;
245 }
246
247 int stdin_gotdata(struct handle *h, void *data, int len)
248 {
249     if (len < 0) {
250         /*
251          * Special case: report read error.
252          */
253         char buf[4096];
254         FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, -len, 0,
255                       buf, lenof(buf), NULL);
256         buf[lenof(buf)-1] = '\0';
257         if (buf[strlen(buf)-1] == '\n')
258             buf[strlen(buf)-1] = '\0';
259         fprintf(stderr, "Unable to read from standard input: %s\n", buf);
260         cleanup_exit(0);
261     }
262     noise_ultralight(len);
263     if (connopen && back->connected(backhandle)) {
264         if (len > 0) {
265             return back->send(backhandle, data, len);
266         } else {
267             back->special(backhandle, TS_EOF);
268             return 0;
269         }
270     } else
271         return 0;
272 }
273
274 void stdouterr_sent(struct handle *h, int new_backlog)
275 {
276     if (new_backlog < 0) {
277         /*
278          * Special case: report write error.
279          */
280         char buf[4096];
281         FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, -new_backlog, 0,
282                       buf, lenof(buf), NULL);
283         buf[lenof(buf)-1] = '\0';
284         if (buf[strlen(buf)-1] == '\n')
285             buf[strlen(buf)-1] = '\0';
286         fprintf(stderr, "Unable to write to standard %s: %s\n",
287                 (h == stdout_handle ? "output" : "error"), buf);
288         cleanup_exit(0);
289     }
290     if (connopen && back->connected(backhandle)) {
291         back->unthrottle(backhandle, (handle_backlog(stdout_handle) +
292                                       handle_backlog(stderr_handle)));
293     }
294 }
295
296 const int share_can_be_downstream = TRUE;
297 const int share_can_be_upstream = TRUE;
298
299 int main(int argc, char **argv)
300 {
301     int sending;
302     int portnumber = -1;
303     SOCKET *sklist;
304     int skcount, sksize;
305     int exitcode;
306     int errors;
307     int got_host = FALSE;
308     int use_subsystem = 0;
309     unsigned long now, next, then;
310
311     sklist = NULL;
312     skcount = sksize = 0;
313     /*
314      * Initialise port and protocol to sensible defaults. (These
315      * will be overridden by more or less anything.)
316      */
317     default_protocol = PROT_SSH;
318     default_port = 22;
319
320     flags = FLAG_STDERR;
321     /*
322      * Process the command line.
323      */
324     conf = conf_new();
325     do_defaults(NULL, conf);
326     loaded_session = FALSE;
327     default_protocol = conf_get_int(conf, CONF_protocol);
328     default_port = conf_get_int(conf, CONF_port);
329     errors = 0;
330     {
331         /*
332          * Override the default protocol if PLINK_PROTOCOL is set.
333          */
334         char *p = getenv("PLINK_PROTOCOL");
335         if (p) {
336             const Backend *b = backend_from_name(p);
337             if (b) {
338                 default_protocol = b->protocol;
339                 default_port = b->default_port;
340                 conf_set_int(conf, CONF_protocol, default_protocol);
341                 conf_set_int(conf, CONF_port, default_port);
342             }
343         }
344     }
345     while (--argc) {
346         char *p = *++argv;
347         if (*p == '-') {
348             int ret = cmdline_process_param(p, (argc > 1 ? argv[1] : NULL),
349                                             1, conf);
350             if (ret == -2) {
351                 fprintf(stderr,
352                         "plink: option \"%s\" requires an argument\n", p);
353                 errors = 1;
354             } else if (ret == 2) {
355                 --argc, ++argv;
356             } else if (ret == 1) {
357                 continue;
358             } else if (!strcmp(p, "-batch")) {
359                 console_batch_mode = 1;
360             } else if (!strcmp(p, "-s")) {
361                 /* Save status to write to conf later. */
362                 use_subsystem = 1;
363             } else if (!strcmp(p, "-V") || !strcmp(p, "--version")) {
364                 version();
365             } else if (!strcmp(p, "--help")) {
366                 usage();
367             } else if (!strcmp(p, "-pgpfp")) {
368                 pgp_fingerprints();
369                 exit(1);
370             } else {
371                 fprintf(stderr, "plink: unknown option \"%s\"\n", p);
372                 errors = 1;
373             }
374         } else if (*p) {
375             if (!conf_launchable(conf) || !(got_host || loaded_session)) {
376                 char *q = p;
377                 /*
378                  * If the hostname starts with "telnet:", set the
379                  * protocol to Telnet and process the string as a
380                  * Telnet URL.
381                  */
382                 if (!strncmp(q, "telnet:", 7)) {
383                     char c;
384
385                     q += 7;
386                     if (q[0] == '/' && q[1] == '/')
387                         q += 2;
388                     conf_set_int(conf, CONF_protocol, PROT_TELNET);
389                     p = q;
390                     p += host_strcspn(p, ":/");
391                     c = *p;
392                     if (*p)
393                         *p++ = '\0';
394                     if (c == ':')
395                         conf_set_int(conf, CONF_port, atoi(p));
396                     else
397                         conf_set_int(conf, CONF_port, -1);
398                     conf_set_str(conf, CONF_host, q);
399                     got_host = TRUE;
400                 } else {
401                     char *r, *user, *host;
402                     /*
403                      * Before we process the [user@]host string, we
404                      * first check for the presence of a protocol
405                      * prefix (a protocol name followed by ",").
406                      */
407                     r = strchr(p, ',');
408                     if (r) {
409                         const Backend *b;
410                         *r = '\0';
411                         b = backend_from_name(p);
412                         if (b) {
413                             default_protocol = b->protocol;
414                             conf_set_int(conf, CONF_protocol,
415                                          default_protocol);
416                             portnumber = b->default_port;
417                         }
418                         p = r + 1;
419                     }
420
421                     /*
422                      * A nonzero length string followed by an @ is treated
423                      * as a username. (We discount an _initial_ @.) The
424                      * rest of the string (or the whole string if no @)
425                      * is treated as a session name and/or hostname.
426                      */
427                     r = strrchr(p, '@');
428                     if (r == p)
429                         p++, r = NULL; /* discount initial @ */
430                     if (r) {
431                         *r++ = '\0';
432                         user = p, host = r;
433                     } else {
434                         user = NULL, host = p;
435                     }
436
437                     /*
438                      * Now attempt to load a saved session with the
439                      * same name as the hostname.
440                      */
441                     {
442                         Conf *conf2 = conf_new();
443                         do_defaults(host, conf2);
444                         if (loaded_session || !conf_launchable(conf2)) {
445                             /* No settings for this host; use defaults */
446                             /* (or session was already loaded with -load) */
447                             conf_set_str(conf, CONF_host, host);
448                             conf_set_int(conf, CONF_port, default_port);
449                             got_host = TRUE;
450                         } else {
451                             conf_copy_into(conf, conf2);
452                             loaded_session = TRUE;
453                         }
454                         conf_free(conf2);
455                     }
456
457                     if (user) {
458                         /* Patch in specified username. */
459                         conf_set_str(conf, CONF_username, user);
460                     }
461
462                 }
463             } else {
464                 char *command;
465                 int cmdlen, cmdsize;
466                 cmdlen = cmdsize = 0;
467                 command = NULL;
468
469                 while (argc) {
470                     while (*p) {
471                         if (cmdlen >= cmdsize) {
472                             cmdsize = cmdlen + 512;
473                             command = sresize(command, cmdsize, char);
474                         }
475                         command[cmdlen++]=*p++;
476                     }
477                     if (cmdlen >= cmdsize) {
478                         cmdsize = cmdlen + 512;
479                         command = sresize(command, cmdsize, char);
480                     }
481                     command[cmdlen++]=' '; /* always add trailing space */
482                     if (--argc) p = *++argv;
483                 }
484                 if (cmdlen) command[--cmdlen]='\0';
485                                        /* change trailing blank to NUL */
486                 conf_set_str(conf, CONF_remote_cmd, command);
487                 conf_set_str(conf, CONF_remote_cmd2, "");
488                 conf_set_int(conf, CONF_nopty, TRUE);  /* command => no tty */
489
490                 break;                 /* done with cmdline */
491             }
492         }
493     }
494
495     if (errors)
496         return 1;
497
498     if (!conf_launchable(conf) || !(got_host || loaded_session)) {
499         usage();
500     }
501
502     /*
503      * Muck about with the hostname in various ways.
504      */
505     {
506         char *hostbuf = dupstr(conf_get_str(conf, CONF_host));
507         char *host = hostbuf;
508         char *p, *q;
509
510         /*
511          * Trim leading whitespace.
512          */
513         host += strspn(host, " \t");
514
515         /*
516          * See if host is of the form user@host, and separate out
517          * the username if so.
518          */
519         if (host[0] != '\0') {
520             char *atsign = strrchr(host, '@');
521             if (atsign) {
522                 *atsign = '\0';
523                 conf_set_str(conf, CONF_username, host);
524                 host = atsign + 1;
525             }
526         }
527
528         /*
529          * Trim a colon suffix off the hostname if it's there. In
530          * order to protect unbracketed IPv6 address literals
531          * against this treatment, we do not do this if there's
532          * _more_ than one colon.
533          */
534         {
535             char *c = host_strchr(host, ':');
536  
537             if (c) {
538                 char *d = host_strchr(c+1, ':');
539                 if (!d)
540                     *c = '\0';
541             }
542         }
543
544         /*
545          * Remove any remaining whitespace.
546          */
547         p = hostbuf;
548         q = host;
549         while (*q) {
550             if (*q != ' ' && *q != '\t')
551                 *p++ = *q;
552             q++;
553         }
554         *p = '\0';
555
556         conf_set_str(conf, CONF_host, hostbuf);
557         sfree(hostbuf);
558     }
559
560     /*
561      * Perform command-line overrides on session configuration.
562      */
563     cmdline_run_saved(conf);
564
565     /*
566      * Apply subsystem status.
567      */
568     if (use_subsystem)
569         conf_set_int(conf, CONF_ssh_subsys, TRUE);
570
571     if (!*conf_get_str(conf, CONF_remote_cmd) &&
572         !*conf_get_str(conf, CONF_remote_cmd2) &&
573         !*conf_get_str(conf, CONF_ssh_nc_host))
574         flags |= FLAG_INTERACTIVE;
575
576     /*
577      * Select protocol. This is farmed out into a table in a
578      * separate file to enable an ssh-free variant.
579      */
580     back = backend_from_proto(conf_get_int(conf, CONF_protocol));
581     if (back == NULL) {
582         fprintf(stderr,
583                 "Internal fault: Unsupported protocol found\n");
584         return 1;
585     }
586
587     /*
588      * Select port.
589      */
590     if (portnumber != -1)
591         conf_set_int(conf, CONF_port, portnumber);
592
593     sk_init();
594     if (p_WSAEventSelect == NULL) {
595         fprintf(stderr, "Plink requires WinSock 2\n");
596         return 1;
597     }
598
599     logctx = log_init(NULL, conf);
600     console_provide_logctx(logctx);
601
602     /*
603      * Start up the connection.
604      */
605     netevent = CreateEvent(NULL, FALSE, FALSE, NULL);
606     {
607         const char *error;
608         char *realhost;
609         /* nodelay is only useful if stdin is a character device (console) */
610         int nodelay = conf_get_int(conf, CONF_tcp_nodelay) &&
611             (GetFileType(GetStdHandle(STD_INPUT_HANDLE)) == FILE_TYPE_CHAR);
612
613         error = back->init(NULL, &backhandle, conf,
614                            conf_get_str(conf, CONF_host),
615                            conf_get_int(conf, CONF_port),
616                            &realhost, nodelay,
617                            conf_get_int(conf, CONF_tcp_keepalives));
618         if (error) {
619             fprintf(stderr, "Unable to open connection:\n%s", error);
620             return 1;
621         }
622         back->provide_logctx(backhandle, logctx);
623         sfree(realhost);
624     }
625     connopen = 1;
626
627     inhandle = GetStdHandle(STD_INPUT_HANDLE);
628     outhandle = GetStdHandle(STD_OUTPUT_HANDLE);
629     errhandle = GetStdHandle(STD_ERROR_HANDLE);
630
631     /*
632      * Turn off ECHO and LINE input modes. We don't care if this
633      * call fails, because we know we aren't necessarily running in
634      * a console.
635      */
636     GetConsoleMode(inhandle, &orig_console_mode);
637     SetConsoleMode(inhandle, ENABLE_PROCESSED_INPUT);
638
639     /*
640      * Pass the output handles to the handle-handling subsystem.
641      * (The input one we leave until we're through the
642      * authentication process.)
643      */
644     stdout_handle = handle_output_new(outhandle, stdouterr_sent, NULL, 0);
645     stderr_handle = handle_output_new(errhandle, stdouterr_sent, NULL, 0);
646
647     main_thread_id = GetCurrentThreadId();
648
649     sending = FALSE;
650
651     now = GETTICKCOUNT();
652
653     while (1) {
654         int nhandles;
655         HANDLE *handles;        
656         int n;
657         DWORD ticks;
658
659         if (!sending && back->sendok(backhandle)) {
660             stdin_handle = handle_input_new(inhandle, stdin_gotdata, NULL,
661                                             0);
662             sending = TRUE;
663         }
664
665         if (toplevel_callback_pending()) {
666             ticks = 0;
667             next = now;
668         } else if (run_timers(now, &next)) {
669             then = now;
670             now = GETTICKCOUNT();
671             if (now - then > next - then)
672                 ticks = 0;
673             else
674                 ticks = next - now;
675         } else {
676             ticks = INFINITE;
677             /* no need to initialise next here because we can never
678              * get WAIT_TIMEOUT */
679         }
680
681         handles = handle_get_events(&nhandles);
682         handles = sresize(handles, nhandles+1, HANDLE);
683         handles[nhandles] = netevent;
684         n = MsgWaitForMultipleObjects(nhandles+1, handles, FALSE, ticks,
685                                       QS_POSTMESSAGE);
686         if ((unsigned)(n - WAIT_OBJECT_0) < (unsigned)nhandles) {
687             handle_got_event(handles[n - WAIT_OBJECT_0]);
688         } else if (n == WAIT_OBJECT_0 + nhandles) {
689             WSANETWORKEVENTS things;
690             SOCKET socket;
691             extern SOCKET first_socket(int *), next_socket(int *);
692             extern int select_result(WPARAM, LPARAM);
693             int i, socketstate;
694
695             /*
696              * We must not call select_result() for any socket
697              * until we have finished enumerating within the tree.
698              * This is because select_result() may close the socket
699              * and modify the tree.
700              */
701             /* Count the active sockets. */
702             i = 0;
703             for (socket = first_socket(&socketstate);
704                  socket != INVALID_SOCKET;
705                  socket = next_socket(&socketstate)) i++;
706
707             /* Expand the buffer if necessary. */
708             if (i > sksize) {
709                 sksize = i + 16;
710                 sklist = sresize(sklist, sksize, SOCKET);
711             }
712
713             /* Retrieve the sockets into sklist. */
714             skcount = 0;
715             for (socket = first_socket(&socketstate);
716                  socket != INVALID_SOCKET;
717                  socket = next_socket(&socketstate)) {
718                 sklist[skcount++] = socket;
719             }
720
721             /* Now we're done enumerating; go through the list. */
722             for (i = 0; i < skcount; i++) {
723                 WPARAM wp;
724                 socket = sklist[i];
725                 wp = (WPARAM) socket;
726                 if (!p_WSAEnumNetworkEvents(socket, NULL, &things)) {
727                     static const struct { int bit, mask; } eventtypes[] = {
728                         {FD_CONNECT_BIT, FD_CONNECT},
729                         {FD_READ_BIT, FD_READ},
730                         {FD_CLOSE_BIT, FD_CLOSE},
731                         {FD_OOB_BIT, FD_OOB},
732                         {FD_WRITE_BIT, FD_WRITE},
733                         {FD_ACCEPT_BIT, FD_ACCEPT},
734                     };
735                     int e;
736
737                     noise_ultralight(socket);
738                     noise_ultralight(things.lNetworkEvents);
739
740                     for (e = 0; e < lenof(eventtypes); e++)
741                         if (things.lNetworkEvents & eventtypes[e].mask) {
742                             LPARAM lp;
743                             int err = things.iErrorCode[eventtypes[e].bit];
744                             lp = WSAMAKESELECTREPLY(eventtypes[e].mask, err);
745                             connopen &= select_result(wp, lp);
746                         }
747                 }
748             }
749         } else if (n == WAIT_OBJECT_0 + nhandles + 1) {
750             MSG msg;
751             while (PeekMessage(&msg, INVALID_HANDLE_VALUE,
752                                WM_AGENT_CALLBACK, WM_AGENT_CALLBACK,
753                                PM_REMOVE)) {
754                 struct agent_callback *c = (struct agent_callback *)msg.lParam;
755                 c->callback(c->callback_ctx, c->data, c->len);
756                 sfree(c);
757             }
758         }
759
760         run_toplevel_callbacks();
761
762         if (n == WAIT_TIMEOUT) {
763             now = next;
764         } else {
765             now = GETTICKCOUNT();
766         }
767
768         sfree(handles);
769
770         if (sending)
771             handle_unthrottle(stdin_handle, back->sendbuffer(backhandle));
772
773         if ((!connopen || !back->connected(backhandle)) &&
774             handle_backlog(stdout_handle) + handle_backlog(stderr_handle) == 0)
775             break;                     /* we closed the connection */
776     }
777     exitcode = back->exitcode(backhandle);
778     if (exitcode < 0) {
779         fprintf(stderr, "Remote process exit code unavailable\n");
780         exitcode = 1;                  /* this is an error condition */
781     }
782     cleanup_exit(exitcode);
783     return 0;                          /* placate compiler warning */
784 }