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