]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - windows/winplink.c
Inaugural merge from branch 'pre-0.65'.
[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(const 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(const 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(const 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, const 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(const 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 frontend_echoedit_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, const 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     exit(1);
216 }
217
218 static void version(void)
219 {
220     printf("plink: %s\n", ver);
221     exit(1);
222 }
223
224 char *do_select(SOCKET skt, int startup)
225 {
226     int events;
227     if (startup) {
228         events = (FD_CONNECT | FD_READ | FD_WRITE |
229                   FD_OOB | FD_CLOSE | FD_ACCEPT);
230     } else {
231         events = 0;
232     }
233     if (p_WSAEventSelect(skt, netevent, events) == SOCKET_ERROR) {
234         switch (p_WSAGetLastError()) {
235           case WSAENETDOWN:
236             return "Network is down";
237           default:
238             return "WSAEventSelect(): unknown error";
239         }
240     }
241     return NULL;
242 }
243
244 int stdin_gotdata(struct handle *h, void *data, int len)
245 {
246     if (len < 0) {
247         /*
248          * Special case: report read error.
249          */
250         char buf[4096];
251         FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, -len, 0,
252                       buf, lenof(buf), NULL);
253         buf[lenof(buf)-1] = '\0';
254         if (buf[strlen(buf)-1] == '\n')
255             buf[strlen(buf)-1] = '\0';
256         fprintf(stderr, "Unable to read from standard input: %s\n", buf);
257         cleanup_exit(0);
258     }
259     noise_ultralight(len);
260     if (connopen && back->connected(backhandle)) {
261         if (len > 0) {
262             return back->send(backhandle, data, len);
263         } else {
264             back->special(backhandle, TS_EOF);
265             return 0;
266         }
267     } else
268         return 0;
269 }
270
271 void stdouterr_sent(struct handle *h, int new_backlog)
272 {
273     if (new_backlog < 0) {
274         /*
275          * Special case: report write error.
276          */
277         char buf[4096];
278         FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, -new_backlog, 0,
279                       buf, lenof(buf), NULL);
280         buf[lenof(buf)-1] = '\0';
281         if (buf[strlen(buf)-1] == '\n')
282             buf[strlen(buf)-1] = '\0';
283         fprintf(stderr, "Unable to write to standard %s: %s\n",
284                 (h == stdout_handle ? "output" : "error"), buf);
285         cleanup_exit(0);
286     }
287     if (connopen && back->connected(backhandle)) {
288         back->unthrottle(backhandle, (handle_backlog(stdout_handle) +
289                                       handle_backlog(stderr_handle)));
290     }
291 }
292
293 const int share_can_be_downstream = TRUE;
294 const int share_can_be_upstream = TRUE;
295
296 int main(int argc, char **argv)
297 {
298     int sending;
299     int portnumber = -1;
300     SOCKET *sklist;
301     int skcount, sksize;
302     int exitcode;
303     int errors;
304     int got_host = FALSE;
305     int use_subsystem = 0;
306     unsigned long now, next, then;
307
308     sklist = NULL;
309     skcount = sksize = 0;
310     /*
311      * Initialise port and protocol to sensible defaults. (These
312      * will be overridden by more or less anything.)
313      */
314     default_protocol = PROT_SSH;
315     default_port = 22;
316
317     flags = FLAG_STDERR;
318     /*
319      * Process the command line.
320      */
321     conf = conf_new();
322     do_defaults(NULL, conf);
323     loaded_session = FALSE;
324     default_protocol = conf_get_int(conf, CONF_protocol);
325     default_port = conf_get_int(conf, CONF_port);
326     errors = 0;
327     {
328         /*
329          * Override the default protocol if PLINK_PROTOCOL is set.
330          */
331         char *p = getenv("PLINK_PROTOCOL");
332         if (p) {
333             const Backend *b = backend_from_name(p);
334             if (b) {
335                 default_protocol = b->protocol;
336                 default_port = b->default_port;
337                 conf_set_int(conf, CONF_protocol, default_protocol);
338                 conf_set_int(conf, CONF_port, default_port);
339             }
340         }
341     }
342     while (--argc) {
343         char *p = *++argv;
344         if (*p == '-') {
345             int ret = cmdline_process_param(p, (argc > 1 ? argv[1] : NULL),
346                                             1, conf);
347             if (ret == -2) {
348                 fprintf(stderr,
349                         "plink: option \"%s\" requires an argument\n", p);
350                 errors = 1;
351             } else if (ret == 2) {
352                 --argc, ++argv;
353             } else if (ret == 1) {
354                 continue;
355             } else if (!strcmp(p, "-batch")) {
356                 console_batch_mode = 1;
357             } else if (!strcmp(p, "-s")) {
358                 /* Save status to write to conf later. */
359                 use_subsystem = 1;
360             } else if (!strcmp(p, "-V") || !strcmp(p, "--version")) {
361                 version();
362             } else if (!strcmp(p, "--help")) {
363                 usage();
364             } else if (!strcmp(p, "-pgpfp")) {
365                 pgp_fingerprints();
366                 exit(1);
367             } else {
368                 fprintf(stderr, "plink: unknown option \"%s\"\n", p);
369                 errors = 1;
370             }
371         } else if (*p) {
372             if (!conf_launchable(conf) || !(got_host || loaded_session)) {
373                 char *q = p;
374                 /*
375                  * If the hostname starts with "telnet:", set the
376                  * protocol to Telnet and process the string as a
377                  * Telnet URL.
378                  */
379                 if (!strncmp(q, "telnet:", 7)) {
380                     char c;
381
382                     q += 7;
383                     if (q[0] == '/' && q[1] == '/')
384                         q += 2;
385                     conf_set_int(conf, CONF_protocol, PROT_TELNET);
386                     p = q;
387                     p += host_strcspn(p, ":/");
388                     c = *p;
389                     if (*p)
390                         *p++ = '\0';
391                     if (c == ':')
392                         conf_set_int(conf, CONF_port, atoi(p));
393                     else
394                         conf_set_int(conf, CONF_port, -1);
395                     conf_set_str(conf, CONF_host, q);
396                     got_host = TRUE;
397                 } else {
398                     char *r, *user, *host;
399                     /*
400                      * Before we process the [user@]host string, we
401                      * first check for the presence of a protocol
402                      * prefix (a protocol name followed by ",").
403                      */
404                     r = strchr(p, ',');
405                     if (r) {
406                         const Backend *b;
407                         *r = '\0';
408                         b = backend_from_name(p);
409                         if (b) {
410                             default_protocol = b->protocol;
411                             conf_set_int(conf, CONF_protocol,
412                                          default_protocol);
413                             portnumber = b->default_port;
414                         }
415                         p = r + 1;
416                     }
417
418                     /*
419                      * A nonzero length string followed by an @ is treated
420                      * as a username. (We discount an _initial_ @.) The
421                      * rest of the string (or the whole string if no @)
422                      * is treated as a session name and/or hostname.
423                      */
424                     r = strrchr(p, '@');
425                     if (r == p)
426                         p++, r = NULL; /* discount initial @ */
427                     if (r) {
428                         *r++ = '\0';
429                         user = p, host = r;
430                     } else {
431                         user = NULL, host = p;
432                     }
433
434                     /*
435                      * Now attempt to load a saved session with the
436                      * same name as the hostname.
437                      */
438                     {
439                         Conf *conf2 = conf_new();
440                         do_defaults(host, conf2);
441                         if (loaded_session || !conf_launchable(conf2)) {
442                             /* No settings for this host; use defaults */
443                             /* (or session was already loaded with -load) */
444                             conf_set_str(conf, CONF_host, host);
445                             conf_set_int(conf, CONF_port, default_port);
446                             got_host = TRUE;
447                         } else {
448                             conf_copy_into(conf, conf2);
449                             loaded_session = TRUE;
450                         }
451                         conf_free(conf2);
452                     }
453
454                     if (user) {
455                         /* Patch in specified username. */
456                         conf_set_str(conf, CONF_username, user);
457                     }
458
459                 }
460             } else {
461                 char *command;
462                 int cmdlen, cmdsize;
463                 cmdlen = cmdsize = 0;
464                 command = NULL;
465
466                 while (argc) {
467                     while (*p) {
468                         if (cmdlen >= cmdsize) {
469                             cmdsize = cmdlen + 512;
470                             command = sresize(command, cmdsize, char);
471                         }
472                         command[cmdlen++]=*p++;
473                     }
474                     if (cmdlen >= cmdsize) {
475                         cmdsize = cmdlen + 512;
476                         command = sresize(command, cmdsize, char);
477                     }
478                     command[cmdlen++]=' '; /* always add trailing space */
479                     if (--argc) p = *++argv;
480                 }
481                 if (cmdlen) command[--cmdlen]='\0';
482                                        /* change trailing blank to NUL */
483                 conf_set_str(conf, CONF_remote_cmd, command);
484                 conf_set_str(conf, CONF_remote_cmd2, "");
485                 conf_set_int(conf, CONF_nopty, TRUE);  /* command => no tty */
486
487                 break;                 /* done with cmdline */
488             }
489         }
490     }
491
492     if (errors)
493         return 1;
494
495     if (!conf_launchable(conf) || !(got_host || loaded_session)) {
496         usage();
497     }
498
499     /*
500      * Muck about with the hostname in various ways.
501      */
502     {
503         char *hostbuf = dupstr(conf_get_str(conf, CONF_host));
504         char *host = hostbuf;
505         char *p, *q;
506
507         /*
508          * Trim leading whitespace.
509          */
510         host += strspn(host, " \t");
511
512         /*
513          * See if host is of the form user@host, and separate out
514          * the username if so.
515          */
516         if (host[0] != '\0') {
517             char *atsign = strrchr(host, '@');
518             if (atsign) {
519                 *atsign = '\0';
520                 conf_set_str(conf, CONF_username, host);
521                 host = atsign + 1;
522             }
523         }
524
525         /*
526          * Trim a colon suffix off the hostname if it's there. In
527          * order to protect unbracketed IPv6 address literals
528          * against this treatment, we do not do this if there's
529          * _more_ than one colon.
530          */
531         {
532             char *c = host_strchr(host, ':');
533  
534             if (c) {
535                 char *d = host_strchr(c+1, ':');
536                 if (!d)
537                     *c = '\0';
538             }
539         }
540
541         /*
542          * Remove any remaining whitespace.
543          */
544         p = hostbuf;
545         q = host;
546         while (*q) {
547             if (*q != ' ' && *q != '\t')
548                 *p++ = *q;
549             q++;
550         }
551         *p = '\0';
552
553         conf_set_str(conf, CONF_host, hostbuf);
554         sfree(hostbuf);
555     }
556
557     /*
558      * Perform command-line overrides on session configuration.
559      */
560     cmdline_run_saved(conf);
561
562     /*
563      * Apply subsystem status.
564      */
565     if (use_subsystem)
566         conf_set_int(conf, CONF_ssh_subsys, TRUE);
567
568     if (!*conf_get_str(conf, CONF_remote_cmd) &&
569         !*conf_get_str(conf, CONF_remote_cmd2) &&
570         !*conf_get_str(conf, CONF_ssh_nc_host))
571         flags |= FLAG_INTERACTIVE;
572
573     /*
574      * Select protocol. This is farmed out into a table in a
575      * separate file to enable an ssh-free variant.
576      */
577     back = backend_from_proto(conf_get_int(conf, CONF_protocol));
578     if (back == NULL) {
579         fprintf(stderr,
580                 "Internal fault: Unsupported protocol found\n");
581         return 1;
582     }
583
584     /*
585      * Select port.
586      */
587     if (portnumber != -1)
588         conf_set_int(conf, CONF_port, portnumber);
589
590     sk_init();
591     if (p_WSAEventSelect == NULL) {
592         fprintf(stderr, "Plink requires WinSock 2\n");
593         return 1;
594     }
595
596     logctx = log_init(NULL, conf);
597     console_provide_logctx(logctx);
598
599     /*
600      * Start up the connection.
601      */
602     netevent = CreateEvent(NULL, FALSE, FALSE, NULL);
603     {
604         const char *error;
605         char *realhost;
606         /* nodelay is only useful if stdin is a character device (console) */
607         int nodelay = conf_get_int(conf, CONF_tcp_nodelay) &&
608             (GetFileType(GetStdHandle(STD_INPUT_HANDLE)) == FILE_TYPE_CHAR);
609
610         error = back->init(NULL, &backhandle, conf,
611                            conf_get_str(conf, CONF_host),
612                            conf_get_int(conf, CONF_port),
613                            &realhost, nodelay,
614                            conf_get_int(conf, CONF_tcp_keepalives));
615         if (error) {
616             fprintf(stderr, "Unable to open connection:\n%s", error);
617             return 1;
618         }
619         back->provide_logctx(backhandle, logctx);
620         sfree(realhost);
621     }
622     connopen = 1;
623
624     inhandle = GetStdHandle(STD_INPUT_HANDLE);
625     outhandle = GetStdHandle(STD_OUTPUT_HANDLE);
626     errhandle = GetStdHandle(STD_ERROR_HANDLE);
627
628     /*
629      * Turn off ECHO and LINE input modes. We don't care if this
630      * call fails, because we know we aren't necessarily running in
631      * a console.
632      */
633     GetConsoleMode(inhandle, &orig_console_mode);
634     SetConsoleMode(inhandle, ENABLE_PROCESSED_INPUT);
635
636     /*
637      * Pass the output handles to the handle-handling subsystem.
638      * (The input one we leave until we're through the
639      * authentication process.)
640      */
641     stdout_handle = handle_output_new(outhandle, stdouterr_sent, NULL, 0);
642     stderr_handle = handle_output_new(errhandle, stdouterr_sent, NULL, 0);
643
644     main_thread_id = GetCurrentThreadId();
645
646     sending = FALSE;
647
648     now = GETTICKCOUNT();
649
650     while (1) {
651         int nhandles;
652         HANDLE *handles;        
653         int n;
654         DWORD ticks;
655
656         if (!sending && back->sendok(backhandle)) {
657             stdin_handle = handle_input_new(inhandle, stdin_gotdata, NULL,
658                                             0);
659             sending = TRUE;
660         }
661
662         if (toplevel_callback_pending()) {
663             ticks = 0;
664             next = now;
665         } else if (run_timers(now, &next)) {
666             then = now;
667             now = GETTICKCOUNT();
668             if (now - then > next - then)
669                 ticks = 0;
670             else
671                 ticks = next - now;
672         } else {
673             ticks = INFINITE;
674             /* no need to initialise next here because we can never
675              * get WAIT_TIMEOUT */
676         }
677
678         handles = handle_get_events(&nhandles);
679         handles = sresize(handles, nhandles+1, HANDLE);
680         handles[nhandles] = netevent;
681         n = MsgWaitForMultipleObjects(nhandles+1, handles, FALSE, ticks,
682                                       QS_POSTMESSAGE);
683         if ((unsigned)(n - WAIT_OBJECT_0) < (unsigned)nhandles) {
684             handle_got_event(handles[n - WAIT_OBJECT_0]);
685         } else if (n == WAIT_OBJECT_0 + nhandles) {
686             WSANETWORKEVENTS things;
687             SOCKET socket;
688             extern SOCKET first_socket(int *), next_socket(int *);
689             extern int select_result(WPARAM, LPARAM);
690             int i, socketstate;
691
692             /*
693              * We must not call select_result() for any socket
694              * until we have finished enumerating within the tree.
695              * This is because select_result() may close the socket
696              * and modify the tree.
697              */
698             /* Count the active sockets. */
699             i = 0;
700             for (socket = first_socket(&socketstate);
701                  socket != INVALID_SOCKET;
702                  socket = next_socket(&socketstate)) i++;
703
704             /* Expand the buffer if necessary. */
705             if (i > sksize) {
706                 sksize = i + 16;
707                 sklist = sresize(sklist, sksize, SOCKET);
708             }
709
710             /* Retrieve the sockets into sklist. */
711             skcount = 0;
712             for (socket = first_socket(&socketstate);
713                  socket != INVALID_SOCKET;
714                  socket = next_socket(&socketstate)) {
715                 sklist[skcount++] = socket;
716             }
717
718             /* Now we're done enumerating; go through the list. */
719             for (i = 0; i < skcount; i++) {
720                 WPARAM wp;
721                 socket = sklist[i];
722                 wp = (WPARAM) socket;
723                 if (!p_WSAEnumNetworkEvents(socket, NULL, &things)) {
724                     static const struct { int bit, mask; } eventtypes[] = {
725                         {FD_CONNECT_BIT, FD_CONNECT},
726                         {FD_READ_BIT, FD_READ},
727                         {FD_CLOSE_BIT, FD_CLOSE},
728                         {FD_OOB_BIT, FD_OOB},
729                         {FD_WRITE_BIT, FD_WRITE},
730                         {FD_ACCEPT_BIT, FD_ACCEPT},
731                     };
732                     int e;
733
734                     noise_ultralight(socket);
735                     noise_ultralight(things.lNetworkEvents);
736
737                     for (e = 0; e < lenof(eventtypes); e++)
738                         if (things.lNetworkEvents & eventtypes[e].mask) {
739                             LPARAM lp;
740                             int err = things.iErrorCode[eventtypes[e].bit];
741                             lp = WSAMAKESELECTREPLY(eventtypes[e].mask, err);
742                             connopen &= select_result(wp, lp);
743                         }
744                 }
745             }
746         } else if (n == WAIT_OBJECT_0 + nhandles + 1) {
747             MSG msg;
748             while (PeekMessage(&msg, INVALID_HANDLE_VALUE,
749                                WM_AGENT_CALLBACK, WM_AGENT_CALLBACK,
750                                PM_REMOVE)) {
751                 struct agent_callback *c = (struct agent_callback *)msg.lParam;
752                 c->callback(c->callback_ctx, c->data, c->len);
753                 sfree(c);
754             }
755         }
756
757         run_toplevel_callbacks();
758
759         if (n == WAIT_TIMEOUT) {
760             now = next;
761         } else {
762             now = GETTICKCOUNT();
763         }
764
765         sfree(handles);
766
767         if (sending)
768             handle_unthrottle(stdin_handle, back->sendbuffer(backhandle));
769
770         if ((!connopen || !back->connected(backhandle)) &&
771             handle_backlog(stdout_handle) + handle_backlog(stderr_handle) == 0)
772             break;                     /* we closed the connection */
773     }
774     exitcode = back->exitcode(backhandle);
775     if (exitcode < 0) {
776         fprintf(stderr, "Remote process exit code unavailable\n");
777         exitcode = 1;                  /* this is an error condition */
778     }
779     cleanup_exit(exitcode);
780     return 0;                          /* placate compiler warning */
781 }