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