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