]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - windows/winnet.c
9875323744cda7ffbdf2377061231176debc848a
[PuTTY.git] / windows / winnet.c
1 /*
2  * Windows networking abstraction.
3  *
4  * For the IPv6 code in here I am indebted to Jeroen Massar and
5  * unfix.org.
6  */
7
8 #include <winsock2.h> /* need to put this first, for winelib builds */
9
10 #include <stdio.h>
11 #include <stdlib.h>
12 #include <assert.h>
13
14 #define DEFINE_PLUG_METHOD_MACROS
15 #define NEED_DECLARATION_OF_SELECT     /* in order to initialise it */
16
17 #include "putty.h"
18 #include "network.h"
19 #include "tree234.h"
20
21 #include <ws2tcpip.h>
22
23 #ifndef NO_IPV6
24 #ifdef __clang__
25 #pragma clang diagnostic push
26 #pragma clang diagnostic ignored "-Wmissing-braces"
27 #endif
28 const struct in6_addr in6addr_any = IN6ADDR_ANY_INIT;
29 const struct in6_addr in6addr_loopback = IN6ADDR_LOOPBACK_INIT;
30 #ifdef __clang__
31 #pragma clang diagnostic pop
32 #endif
33 #endif
34
35 #define ipv4_is_loopback(addr) \
36         ((p_ntohl(addr.s_addr) & 0xFF000000L) == 0x7F000000L)
37
38 /*
39  * We used to typedef struct Socket_tag *Socket.
40  *
41  * Since we have made the networking abstraction slightly more
42  * abstract, Socket no longer means a tcp socket (it could mean
43  * an ssl socket).  So now we must use Actual_Socket when we know
44  * we are talking about a tcp socket.
45  */
46 typedef struct Socket_tag *Actual_Socket;
47
48 /*
49  * Mutable state that goes with a SockAddr: stores information
50  * about where in the list of candidate IP(v*) addresses we've
51  * currently got to.
52  */
53 typedef struct SockAddrStep_tag SockAddrStep;
54 struct SockAddrStep_tag {
55 #ifndef NO_IPV6
56     struct addrinfo *ai;               /* steps along addr->ais */
57 #endif
58     int curraddr;
59 };
60
61 struct Socket_tag {
62     const struct socket_function_table *fn;
63     /* the above variable absolutely *must* be the first in this structure */
64     const char *error;
65     SOCKET s;
66     Plug plug;
67     bufchain output_data;
68     int connected;
69     int writable;
70     int frozen; /* this causes readability notifications to be ignored */
71     int frozen_readable; /* this means we missed at least one readability
72                           * notification while we were frozen */
73     int localhost_only;                /* for listening sockets */
74     char oobdata[1];
75     int sending_oob;
76     int oobinline, nodelay, keepalive, privport;
77     enum { EOF_NO, EOF_PENDING, EOF_SENT } outgoingeof;
78     SockAddr addr;
79     SockAddrStep step;
80     int port;
81     int pending_error;                 /* in case send() returns error */
82     /*
83      * We sometimes need pairs of Socket structures to be linked:
84      * if we are listening on the same IPv6 and v4 port, for
85      * example. So here we define `parent' and `child' pointers to
86      * track this link.
87      */
88     Actual_Socket parent, child;
89 };
90
91 struct SockAddr_tag {
92     int refcount;
93     char *error;
94     int resolved;
95     int namedpipe; /* indicates that this SockAddr is phony, holding a Windows
96                     * named pipe pathname instead of a network address */
97 #ifndef NO_IPV6
98     struct addrinfo *ais;              /* Addresses IPv6 style. */
99 #endif
100     unsigned long *addresses;          /* Addresses IPv4 style. */
101     int naddresses;
102     char hostname[512];                /* Store an unresolved host name. */
103 };
104
105 /*
106  * Which address family this address belongs to. AF_INET for IPv4;
107  * AF_INET6 for IPv6; AF_UNSPEC indicates that name resolution has
108  * not been done and a simple host name is held in this SockAddr
109  * structure.
110  */
111 #ifndef NO_IPV6
112 #define SOCKADDR_FAMILY(addr, step) \
113     (!(addr)->resolved ? AF_UNSPEC : \
114      (step).ai ? (step).ai->ai_family : AF_INET)
115 #else
116 #define SOCKADDR_FAMILY(addr, step) \
117     (!(addr)->resolved ? AF_UNSPEC : AF_INET)
118 #endif
119
120 /*
121  * Start a SockAddrStep structure to step through multiple
122  * addresses.
123  */
124 #ifndef NO_IPV6
125 #define START_STEP(addr, step) \
126     ((step).ai = (addr)->ais, (step).curraddr = 0)
127 #else
128 #define START_STEP(addr, step) \
129     ((step).curraddr = 0)
130 #endif
131
132 static tree234 *sktree;
133
134 static int cmpfortree(void *av, void *bv)
135 {
136     Actual_Socket a = (Actual_Socket) av, b = (Actual_Socket) bv;
137     unsigned long as = (unsigned long) a->s, bs = (unsigned long) b->s;
138     if (as < bs)
139         return -1;
140     if (as > bs)
141         return +1;
142     if (a < b)
143         return -1;
144     if (a > b)
145         return +1;
146     return 0;
147 }
148
149 static int cmpforsearch(void *av, void *bv)
150 {
151     Actual_Socket b = (Actual_Socket) bv;
152     uintptr_t as = (uintptr_t) av, bs = (uintptr_t) b->s;
153     if (as < bs)
154         return -1;
155     if (as > bs)
156         return +1;
157     return 0;
158 }
159
160 DECL_WINDOWS_FUNCTION(static, int, WSAStartup, (WORD, LPWSADATA));
161 DECL_WINDOWS_FUNCTION(static, int, WSACleanup, (void));
162 DECL_WINDOWS_FUNCTION(static, int, closesocket, (SOCKET));
163 DECL_WINDOWS_FUNCTION(static, u_long, ntohl, (u_long));
164 DECL_WINDOWS_FUNCTION(static, u_long, htonl, (u_long));
165 DECL_WINDOWS_FUNCTION(static, u_short, htons, (u_short));
166 DECL_WINDOWS_FUNCTION(static, u_short, ntohs, (u_short));
167 DECL_WINDOWS_FUNCTION(static, int, gethostname, (char *, int));
168 DECL_WINDOWS_FUNCTION(static, struct hostent FAR *, gethostbyname,
169                       (const char FAR *));
170 DECL_WINDOWS_FUNCTION(static, struct servent FAR *, getservbyname,
171                       (const char FAR *, const char FAR *));
172 DECL_WINDOWS_FUNCTION(static, unsigned long, inet_addr, (const char FAR *));
173 DECL_WINDOWS_FUNCTION(static, char FAR *, inet_ntoa, (struct in_addr));
174 DECL_WINDOWS_FUNCTION(static, const char FAR *, inet_ntop,
175                       (int, void FAR *, char *, size_t));
176 DECL_WINDOWS_FUNCTION(static, int, connect,
177                       (SOCKET, const struct sockaddr FAR *, int));
178 DECL_WINDOWS_FUNCTION(static, int, bind,
179                       (SOCKET, const struct sockaddr FAR *, int));
180 DECL_WINDOWS_FUNCTION(static, int, setsockopt,
181                       (SOCKET, int, int, const char FAR *, int));
182 DECL_WINDOWS_FUNCTION(static, SOCKET, socket, (int, int, int));
183 DECL_WINDOWS_FUNCTION(static, int, listen, (SOCKET, int));
184 DECL_WINDOWS_FUNCTION(static, int, send, (SOCKET, const char FAR *, int, int));
185 DECL_WINDOWS_FUNCTION(static, int, shutdown, (SOCKET, int));
186 DECL_WINDOWS_FUNCTION(static, int, ioctlsocket,
187                       (SOCKET, long, u_long FAR *));
188 DECL_WINDOWS_FUNCTION(static, SOCKET, accept,
189                       (SOCKET, struct sockaddr FAR *, int FAR *));
190 DECL_WINDOWS_FUNCTION(static, int, getpeername,
191                       (SOCKET, struct sockaddr FAR *, int FAR *));
192 DECL_WINDOWS_FUNCTION(static, int, recv, (SOCKET, char FAR *, int, int));
193 DECL_WINDOWS_FUNCTION(static, int, WSAIoctl,
194                       (SOCKET, DWORD, LPVOID, DWORD, LPVOID, DWORD,
195                        LPDWORD, LPWSAOVERLAPPED,
196                        LPWSAOVERLAPPED_COMPLETION_ROUTINE));
197 #ifndef NO_IPV6
198 DECL_WINDOWS_FUNCTION(static, int, getaddrinfo,
199                       (const char *nodename, const char *servname,
200                        const struct addrinfo *hints, struct addrinfo **res));
201 DECL_WINDOWS_FUNCTION(static, void, freeaddrinfo, (struct addrinfo *res));
202 DECL_WINDOWS_FUNCTION(static, int, getnameinfo,
203                       (const struct sockaddr FAR * sa, socklen_t salen,
204                        char FAR * host, size_t hostlen, char FAR * serv,
205                        size_t servlen, int flags));
206 DECL_WINDOWS_FUNCTION(static, char *, gai_strerror, (int ecode));
207 DECL_WINDOWS_FUNCTION(static, int, WSAAddressToStringA,
208                       (LPSOCKADDR, DWORD, LPWSAPROTOCOL_INFO,
209                        LPSTR, LPDWORD));
210 #endif
211
212 static HMODULE winsock_module = NULL;
213 static WSADATA wsadata;
214 #ifndef NO_IPV6
215 static HMODULE winsock2_module = NULL;
216 static HMODULE wship6_module = NULL;
217 #endif
218
219 int sk_startup(int hi, int lo)
220 {
221     WORD winsock_ver;
222
223     winsock_ver = MAKEWORD(hi, lo);
224
225     if (p_WSAStartup(winsock_ver, &wsadata)) {
226         return FALSE;
227     }
228
229     if (LOBYTE(wsadata.wVersion) != LOBYTE(winsock_ver)) {
230         return FALSE;
231     }
232
233 #ifdef NET_SETUP_DIAGNOSTICS
234     {
235         char buf[80];
236         sprintf(buf, "Using WinSock %d.%d", hi, lo);
237         logevent(NULL, buf);
238     }
239 #endif
240     return TRUE;
241 }
242
243 /* Actually define this function pointer, which won't have been
244  * defined alongside all the others by PUTTY_DO_GLOBALS because of the
245  * annoying winelib header-ordering issue. (See comment in winstuff.h.) */
246 DECL_WINDOWS_FUNCTION(/* empty */, int, select,
247                       (int, fd_set FAR *, fd_set FAR *,
248                        fd_set FAR *, const struct timeval FAR *));
249
250 void sk_init(void)
251 {
252 #ifndef NO_IPV6
253     winsock2_module =
254 #endif
255         winsock_module = load_system32_dll("ws2_32.dll");
256     if (!winsock_module) {
257         winsock_module = load_system32_dll("wsock32.dll");
258     }
259     if (!winsock_module)
260         fatalbox("Unable to load any WinSock library");
261
262 #ifndef NO_IPV6
263     /* Check if we have getaddrinfo in Winsock */
264     if (GetProcAddress(winsock_module, "getaddrinfo") != NULL) {
265 #ifdef NET_SETUP_DIAGNOSTICS
266         logevent(NULL, "Native WinSock IPv6 support detected");
267 #endif
268         GET_WINDOWS_FUNCTION(winsock_module, getaddrinfo);
269         GET_WINDOWS_FUNCTION(winsock_module, freeaddrinfo);
270         GET_WINDOWS_FUNCTION(winsock_module, getnameinfo);
271         GET_WINDOWS_FUNCTION(winsock_module, gai_strerror);
272     } else {
273         /* Fall back to wship6.dll for Windows 2000 */
274         wship6_module = load_system32_dll("wship6.dll");
275         if (wship6_module) {
276 #ifdef NET_SETUP_DIAGNOSTICS
277             logevent(NULL, "WSH IPv6 support detected");
278 #endif
279             GET_WINDOWS_FUNCTION(wship6_module, getaddrinfo);
280             GET_WINDOWS_FUNCTION(wship6_module, freeaddrinfo);
281             GET_WINDOWS_FUNCTION(wship6_module, getnameinfo);
282             GET_WINDOWS_FUNCTION(wship6_module, gai_strerror);
283         } else {
284 #ifdef NET_SETUP_DIAGNOSTICS
285             logevent(NULL, "No IPv6 support detected");
286 #endif
287         }
288     }
289     GET_WINDOWS_FUNCTION(winsock2_module, WSAAddressToStringA);
290 #else
291 #ifdef NET_SETUP_DIAGNOSTICS
292     logevent(NULL, "PuTTY was built without IPv6 support");
293 #endif
294 #endif
295
296     GET_WINDOWS_FUNCTION(winsock_module, WSAAsyncSelect);
297     GET_WINDOWS_FUNCTION(winsock_module, WSAEventSelect);
298     GET_WINDOWS_FUNCTION(winsock_module, select);
299     GET_WINDOWS_FUNCTION(winsock_module, WSAGetLastError);
300     GET_WINDOWS_FUNCTION(winsock_module, WSAEnumNetworkEvents);
301     GET_WINDOWS_FUNCTION(winsock_module, WSAStartup);
302     GET_WINDOWS_FUNCTION(winsock_module, WSACleanup);
303     GET_WINDOWS_FUNCTION(winsock_module, closesocket);
304     GET_WINDOWS_FUNCTION(winsock_module, ntohl);
305     GET_WINDOWS_FUNCTION(winsock_module, htonl);
306     GET_WINDOWS_FUNCTION(winsock_module, htons);
307     GET_WINDOWS_FUNCTION(winsock_module, ntohs);
308     GET_WINDOWS_FUNCTION(winsock_module, gethostname);
309     GET_WINDOWS_FUNCTION(winsock_module, gethostbyname);
310     GET_WINDOWS_FUNCTION(winsock_module, getservbyname);
311     GET_WINDOWS_FUNCTION(winsock_module, inet_addr);
312     GET_WINDOWS_FUNCTION(winsock_module, inet_ntoa);
313     GET_WINDOWS_FUNCTION(winsock_module, inet_ntop);
314     GET_WINDOWS_FUNCTION(winsock_module, connect);
315     GET_WINDOWS_FUNCTION(winsock_module, bind);
316     GET_WINDOWS_FUNCTION(winsock_module, setsockopt);
317     GET_WINDOWS_FUNCTION(winsock_module, socket);
318     GET_WINDOWS_FUNCTION(winsock_module, listen);
319     GET_WINDOWS_FUNCTION(winsock_module, send);
320     GET_WINDOWS_FUNCTION(winsock_module, shutdown);
321     GET_WINDOWS_FUNCTION(winsock_module, ioctlsocket);
322     GET_WINDOWS_FUNCTION(winsock_module, accept);
323     GET_WINDOWS_FUNCTION(winsock_module, getpeername);
324     GET_WINDOWS_FUNCTION(winsock_module, recv);
325     GET_WINDOWS_FUNCTION(winsock_module, WSAIoctl);
326
327     /* Try to get the best WinSock version we can get */
328     if (!sk_startup(2,2) &&
329         !sk_startup(2,0) &&
330         !sk_startup(1,1)) {
331         fatalbox("Unable to initialise WinSock");
332     }
333
334     sktree = newtree234(cmpfortree);
335 }
336
337 void sk_cleanup(void)
338 {
339     Actual_Socket s;
340     int i;
341
342     if (sktree) {
343         for (i = 0; (s = index234(sktree, i)) != NULL; i++) {
344             p_closesocket(s->s);
345         }
346         freetree234(sktree);
347         sktree = NULL;
348     }
349
350     if (p_WSACleanup)
351         p_WSACleanup();
352     if (winsock_module)
353         FreeLibrary(winsock_module);
354 #ifndef NO_IPV6
355     if (wship6_module)
356         FreeLibrary(wship6_module);
357 #endif
358 }
359
360 struct errstring {
361     int error;
362     char *text;
363 };
364
365 static int errstring_find(void *av, void *bv)
366 {
367     int *a = (int *)av;
368     struct errstring *b = (struct errstring *)bv;
369     if (*a < b->error)
370         return -1;
371     if (*a > b->error)
372         return +1;
373     return 0;
374 }
375 static int errstring_compare(void *av, void *bv)
376 {
377     struct errstring *a = (struct errstring *)av;
378     return errstring_find(&a->error, bv);
379 }
380
381 static tree234 *errstrings = NULL;
382
383 const char *winsock_error_string(int error)
384 {
385     const char prefix[] = "Network error: ";
386     struct errstring *es;
387
388     /*
389      * Error codes we know about and have historically had reasonably
390      * sensible error messages for.
391      */
392     switch (error) {
393       case WSAEACCES:
394         return "Network error: Permission denied";
395       case WSAEADDRINUSE:
396         return "Network error: Address already in use";
397       case WSAEADDRNOTAVAIL:
398         return "Network error: Cannot assign requested address";
399       case WSAEAFNOSUPPORT:
400         return
401             "Network error: Address family not supported by protocol family";
402       case WSAEALREADY:
403         return "Network error: Operation already in progress";
404       case WSAECONNABORTED:
405         return "Network error: Software caused connection abort";
406       case WSAECONNREFUSED:
407         return "Network error: Connection refused";
408       case WSAECONNRESET:
409         return "Network error: Connection reset by peer";
410       case WSAEDESTADDRREQ:
411         return "Network error: Destination address required";
412       case WSAEFAULT:
413         return "Network error: Bad address";
414       case WSAEHOSTDOWN:
415         return "Network error: Host is down";
416       case WSAEHOSTUNREACH:
417         return "Network error: No route to host";
418       case WSAEINPROGRESS:
419         return "Network error: Operation now in progress";
420       case WSAEINTR:
421         return "Network error: Interrupted function call";
422       case WSAEINVAL:
423         return "Network error: Invalid argument";
424       case WSAEISCONN:
425         return "Network error: Socket is already connected";
426       case WSAEMFILE:
427         return "Network error: Too many open files";
428       case WSAEMSGSIZE:
429         return "Network error: Message too long";
430       case WSAENETDOWN:
431         return "Network error: Network is down";
432       case WSAENETRESET:
433         return "Network error: Network dropped connection on reset";
434       case WSAENETUNREACH:
435         return "Network error: Network is unreachable";
436       case WSAENOBUFS:
437         return "Network error: No buffer space available";
438       case WSAENOPROTOOPT:
439         return "Network error: Bad protocol option";
440       case WSAENOTCONN:
441         return "Network error: Socket is not connected";
442       case WSAENOTSOCK:
443         return "Network error: Socket operation on non-socket";
444       case WSAEOPNOTSUPP:
445         return "Network error: Operation not supported";
446       case WSAEPFNOSUPPORT:
447         return "Network error: Protocol family not supported";
448       case WSAEPROCLIM:
449         return "Network error: Too many processes";
450       case WSAEPROTONOSUPPORT:
451         return "Network error: Protocol not supported";
452       case WSAEPROTOTYPE:
453         return "Network error: Protocol wrong type for socket";
454       case WSAESHUTDOWN:
455         return "Network error: Cannot send after socket shutdown";
456       case WSAESOCKTNOSUPPORT:
457         return "Network error: Socket type not supported";
458       case WSAETIMEDOUT:
459         return "Network error: Connection timed out";
460       case WSAEWOULDBLOCK:
461         return "Network error: Resource temporarily unavailable";
462       case WSAEDISCON:
463         return "Network error: Graceful shutdown in progress";
464     }
465
466     /*
467      * Generic code to handle any other error.
468      *
469      * Slightly nasty hack here: we want to return a static string
470      * which the caller will never have to worry about freeing, but on
471      * the other hand if we call FormatMessage to get it then it will
472      * want to either allocate a buffer or write into one we own.
473      *
474      * So what we do is to maintain a tree234 of error strings we've
475      * already used. New ones are allocated from the heap, but then
476      * put in this tree and kept forever.
477      */
478
479     if (!errstrings)
480         errstrings = newtree234(errstring_compare);
481
482     es = find234(errstrings, &error, errstring_find);
483
484     if (!es) {
485         int bufsize, bufused;
486
487         es = snew(struct errstring);
488         es->error = error;
489         /* maximum size for FormatMessage is 64K */
490         bufsize = 65535 + sizeof(prefix);
491         es->text = snewn(bufsize, char);
492         strcpy(es->text, prefix);
493         bufused = strlen(es->text);
494         if (!FormatMessage((FORMAT_MESSAGE_FROM_SYSTEM |
495                             FORMAT_MESSAGE_IGNORE_INSERTS), NULL, error,
496                            MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
497                            es->text + bufused, bufsize - bufused, NULL)) {
498             sprintf(es->text + bufused,
499                     "Windows error code %d (and FormatMessage returned %u)",
500                     error, (unsigned int)GetLastError());
501         } else {
502             int len = strlen(es->text);
503             if (len > 0 && es->text[len-1] == '\n')
504                 es->text[len-1] = '\0';
505         }
506         es->text = sresize(es->text, strlen(es->text) + 1, char);
507         add234(errstrings, es);
508     }
509
510     return es->text;
511 }
512
513 SockAddr sk_namelookup(const char *host, char **canonicalname,
514                        int address_family)
515 {
516     SockAddr ret = snew(struct SockAddr_tag);
517     unsigned long a;
518     char realhost[8192];
519     int hint_family;
520
521     /* Default to IPv4. */
522     hint_family = (address_family == ADDRTYPE_IPV4 ? AF_INET :
523 #ifndef NO_IPV6
524                    address_family == ADDRTYPE_IPV6 ? AF_INET6 :
525 #endif
526                    AF_UNSPEC);
527
528     /* Clear the structure and default to IPv4. */
529     memset(ret, 0, sizeof(struct SockAddr_tag));
530 #ifndef NO_IPV6
531     ret->ais = NULL;
532 #endif
533     ret->namedpipe = FALSE;
534     ret->addresses = NULL;
535     ret->resolved = FALSE;
536     ret->refcount = 1;
537     *realhost = '\0';
538
539     if ((a = p_inet_addr(host)) == (unsigned long) INADDR_NONE) {
540         struct hostent *h = NULL;
541         int err;
542 #ifndef NO_IPV6
543         /*
544          * Use getaddrinfo when it's available
545          */
546         if (p_getaddrinfo) {
547             struct addrinfo hints;
548 #ifdef NET_SETUP_DIAGNOSTICS
549             logevent(NULL, "Using getaddrinfo() for resolving");
550 #endif
551             memset(&hints, 0, sizeof(hints));
552             hints.ai_family = hint_family;
553             hints.ai_flags = AI_CANONNAME;
554             {
555                 /* strip [] on IPv6 address literals */
556                 char *trimmed_host = host_strduptrim(host);
557                 err = p_getaddrinfo(trimmed_host, NULL, &hints, &ret->ais);
558                 sfree(trimmed_host);
559             }
560             if (err == 0)
561                 ret->resolved = TRUE;
562         } else
563 #endif
564         {
565 #ifdef NET_SETUP_DIAGNOSTICS
566             logevent(NULL, "Using gethostbyname() for resolving");
567 #endif
568             /*
569              * Otherwise use the IPv4-only gethostbyname...
570              * (NOTE: we don't use gethostbyname as a fallback!)
571              */
572             if ( (h = p_gethostbyname(host)) )
573                 ret->resolved = TRUE;
574             else
575                 err = p_WSAGetLastError();
576         }
577
578         if (!ret->resolved) {
579             ret->error = (err == WSAENETDOWN ? "Network is down" :
580                           err == WSAHOST_NOT_FOUND ? "Host does not exist" :
581                           err == WSATRY_AGAIN ? "Host not found" :
582 #ifndef NO_IPV6
583                           p_getaddrinfo&&p_gai_strerror ? p_gai_strerror(err) :
584 #endif
585                           "gethostbyname: unknown error");
586         } else {
587             ret->error = NULL;
588
589 #ifndef NO_IPV6
590             /* If we got an address info use that... */
591             if (ret->ais) {
592                 /* Are we in IPv4 fallback mode? */
593                 /* We put the IPv4 address into the a variable so we can further-on use the IPv4 code... */
594                 if (ret->ais->ai_family == AF_INET)
595                     memcpy(&a,
596                            (char *) &((SOCKADDR_IN *) ret->ais->
597                                       ai_addr)->sin_addr, sizeof(a));
598
599                 if (ret->ais->ai_canonname)
600                     strncpy(realhost, ret->ais->ai_canonname, lenof(realhost));
601                 else
602                     strncpy(realhost, host, lenof(realhost));
603             }
604             /* We used the IPv4-only gethostbyname()... */
605             else
606 #endif
607             {
608                 int n;
609                 for (n = 0; h->h_addr_list[n]; n++);
610                 ret->addresses = snewn(n, unsigned long);
611                 ret->naddresses = n;
612                 for (n = 0; n < ret->naddresses; n++) {
613                     memcpy(&a, h->h_addr_list[n], sizeof(a));
614                     ret->addresses[n] = p_ntohl(a);
615                 }
616                 memcpy(&a, h->h_addr, sizeof(a));
617                 /* This way we are always sure the h->h_name is valid :) */
618                 strncpy(realhost, h->h_name, sizeof(realhost));
619             }
620         }
621     } else {
622         /*
623          * This must be a numeric IPv4 address because it caused a
624          * success return from inet_addr.
625          */
626         ret->addresses = snewn(1, unsigned long);
627         ret->naddresses = 1;
628         ret->addresses[0] = p_ntohl(a);
629         ret->resolved = TRUE;
630         strncpy(realhost, host, sizeof(realhost));
631     }
632     realhost[lenof(realhost)-1] = '\0';
633     *canonicalname = snewn(1+strlen(realhost), char);
634     strcpy(*canonicalname, realhost);
635     return ret;
636 }
637
638 SockAddr sk_nonamelookup(const char *host)
639 {
640     SockAddr ret = snew(struct SockAddr_tag);
641     ret->error = NULL;
642     ret->resolved = FALSE;
643 #ifndef NO_IPV6
644     ret->ais = NULL;
645 #endif
646     ret->namedpipe = FALSE;
647     ret->addresses = NULL;
648     ret->naddresses = 0;
649     ret->refcount = 1;
650     strncpy(ret->hostname, host, lenof(ret->hostname));
651     ret->hostname[lenof(ret->hostname)-1] = '\0';
652     return ret;
653 }
654
655 SockAddr sk_namedpipe_addr(const char *pipename)
656 {
657     SockAddr ret = snew(struct SockAddr_tag);
658     ret->error = NULL;
659     ret->resolved = FALSE;
660 #ifndef NO_IPV6
661     ret->ais = NULL;
662 #endif
663     ret->namedpipe = TRUE;
664     ret->addresses = NULL;
665     ret->naddresses = 0;
666     ret->refcount = 1;
667     strncpy(ret->hostname, pipename, lenof(ret->hostname));
668     ret->hostname[lenof(ret->hostname)-1] = '\0';
669     return ret;
670 }
671
672 int sk_nextaddr(SockAddr addr, SockAddrStep *step)
673 {
674 #ifndef NO_IPV6
675     if (step->ai) {
676         if (step->ai->ai_next) {
677             step->ai = step->ai->ai_next;
678             return TRUE;
679         } else
680             return FALSE;
681     }
682 #endif
683     if (step->curraddr+1 < addr->naddresses) {
684         step->curraddr++;
685         return TRUE;
686     } else {
687         return FALSE;
688     }
689 }
690
691 void sk_getaddr(SockAddr addr, char *buf, int buflen)
692 {
693     SockAddrStep step;
694     START_STEP(addr, step);
695
696 #ifndef NO_IPV6
697     if (step.ai) {
698         int err = 0;
699         if (p_WSAAddressToStringA) {
700             DWORD dwbuflen = buflen;
701             err = p_WSAAddressToStringA(step.ai->ai_addr, step.ai->ai_addrlen,
702                                         NULL, buf, &dwbuflen);
703         } else
704             err = -1;
705         if (err) {
706             strncpy(buf, addr->hostname, buflen);
707             if (!buf[0])
708                 strncpy(buf, "<unknown>", buflen);
709             buf[buflen-1] = '\0';
710         }
711     } else
712 #endif
713     if (SOCKADDR_FAMILY(addr, step) == AF_INET) {
714         struct in_addr a;
715         assert(addr->addresses && step.curraddr < addr->naddresses);
716         a.s_addr = p_htonl(addr->addresses[step.curraddr]);
717         strncpy(buf, p_inet_ntoa(a), buflen);
718         buf[buflen-1] = '\0';
719     } else {
720         strncpy(buf, addr->hostname, buflen);
721         buf[buflen-1] = '\0';
722     }
723 }
724
725 /*
726  * This constructs a SockAddr that points at one specific sub-address
727  * of a parent SockAddr. The returned SockAddr does not own all its
728  * own memory: it points into the old one's data structures, so it
729  * MUST NOT be used after the old one is freed, and it MUST NOT be
730  * passed to sk_addr_free. (The latter is why it's returned by value
731  * rather than dynamically allocated - that should clue in anyone
732  * writing a call to it that something is weird about it.)
733  */
734 static struct SockAddr_tag sk_extractaddr_tmp(
735     SockAddr addr, const SockAddrStep *step)
736 {
737     struct SockAddr_tag toret;
738     toret = *addr;                    /* structure copy */
739     toret.refcount = 1;
740
741 #ifndef NO_IPV6
742     toret.ais = step->ai;
743 #endif
744     if (SOCKADDR_FAMILY(addr, *step) == AF_INET
745 #ifndef NO_IPV6
746         && !toret.ais
747 #endif
748         )
749         toret.addresses += step->curraddr;
750
751     return toret;
752 }
753
754 int sk_addr_needs_port(SockAddr addr)
755 {
756     return addr->namedpipe ? FALSE : TRUE;
757 }
758
759 int sk_hostname_is_local(const char *name)
760 {
761     return !strcmp(name, "localhost") ||
762            !strcmp(name, "::1") ||
763            !strncmp(name, "127.", 4);
764 }
765
766 static INTERFACE_INFO local_interfaces[16];
767 static int n_local_interfaces;       /* 0=not yet, -1=failed, >0=number */
768
769 static int ipv4_is_local_addr(struct in_addr addr)
770 {
771     if (ipv4_is_loopback(addr))
772         return 1;                      /* loopback addresses are local */
773     if (!n_local_interfaces) {
774         SOCKET s = p_socket(AF_INET, SOCK_DGRAM, 0);
775         DWORD retbytes;
776
777         SetHandleInformation((HANDLE)s, HANDLE_FLAG_INHERIT, 0);
778
779         if (p_WSAIoctl &&
780             p_WSAIoctl(s, SIO_GET_INTERFACE_LIST, NULL, 0,
781                        local_interfaces, sizeof(local_interfaces),
782                        &retbytes, NULL, NULL) == 0)
783             n_local_interfaces = retbytes / sizeof(INTERFACE_INFO);
784         else
785             logevent(NULL, "Unable to get list of local IP addresses");
786     }
787     if (n_local_interfaces > 0) {
788         int i;
789         for (i = 0; i < n_local_interfaces; i++) {
790             SOCKADDR_IN *address =
791                 (SOCKADDR_IN *)&local_interfaces[i].iiAddress;
792             if (address->sin_addr.s_addr == addr.s_addr)
793                 return 1;              /* this address is local */
794         }
795     }
796     return 0;                  /* this address is not local */
797 }
798
799 int sk_address_is_local(SockAddr addr)
800 {
801     SockAddrStep step;
802     int family;
803     START_STEP(addr, step);
804     family = SOCKADDR_FAMILY(addr, step);
805
806 #ifndef NO_IPV6
807     if (family == AF_INET6) {
808         return IN6_IS_ADDR_LOOPBACK(&((const struct sockaddr_in6 *)step.ai->ai_addr)->sin6_addr);
809     } else
810 #endif
811     if (family == AF_INET) {
812 #ifndef NO_IPV6
813         if (step.ai) {
814             return ipv4_is_local_addr(((struct sockaddr_in *)step.ai->ai_addr)
815                                       ->sin_addr);
816         } else
817 #endif
818         {
819             struct in_addr a;
820             assert(addr->addresses && step.curraddr < addr->naddresses);
821             a.s_addr = p_htonl(addr->addresses[step.curraddr]);
822             return ipv4_is_local_addr(a);
823         }
824     } else {
825         assert(family == AF_UNSPEC);
826         return 0;                      /* we don't know; assume not */
827     }
828 }
829
830 int sk_address_is_special_local(SockAddr addr)
831 {
832     return 0;                /* no Unix-domain socket analogue here */
833 }
834
835 int sk_addrtype(SockAddr addr)
836 {
837     SockAddrStep step;
838     int family;
839     START_STEP(addr, step);
840     family = SOCKADDR_FAMILY(addr, step);
841
842     return (family == AF_INET ? ADDRTYPE_IPV4 :
843 #ifndef NO_IPV6
844             family == AF_INET6 ? ADDRTYPE_IPV6 :
845 #endif
846             ADDRTYPE_NAME);
847 }
848
849 void sk_addrcopy(SockAddr addr, char *buf)
850 {
851     SockAddrStep step;
852     int family;
853     START_STEP(addr, step);
854     family = SOCKADDR_FAMILY(addr, step);
855
856     assert(family != AF_UNSPEC);
857 #ifndef NO_IPV6
858     if (step.ai) {
859         if (family == AF_INET)
860             memcpy(buf, &((struct sockaddr_in *)step.ai->ai_addr)->sin_addr,
861                    sizeof(struct in_addr));
862         else if (family == AF_INET6)
863             memcpy(buf, &((struct sockaddr_in6 *)step.ai->ai_addr)->sin6_addr,
864                    sizeof(struct in6_addr));
865         else
866             assert(FALSE);
867     } else
868 #endif
869     if (family == AF_INET) {
870         struct in_addr a;
871         assert(addr->addresses && step.curraddr < addr->naddresses);
872         a.s_addr = p_htonl(addr->addresses[step.curraddr]);
873         memcpy(buf, (char*) &a.s_addr, 4);
874     }
875 }
876
877 void sk_addr_free(SockAddr addr)
878 {
879     if (--addr->refcount > 0)
880         return;
881 #ifndef NO_IPV6
882     if (addr->ais && p_freeaddrinfo)
883         p_freeaddrinfo(addr->ais);
884 #endif
885     if (addr->addresses)
886         sfree(addr->addresses);
887     sfree(addr);
888 }
889
890 SockAddr sk_addr_dup(SockAddr addr)
891 {
892     addr->refcount++;
893     return addr;
894 }
895
896 static Plug sk_tcp_plug(Socket sock, Plug p)
897 {
898     Actual_Socket s = (Actual_Socket) sock;
899     Plug ret = s->plug;
900     if (p)
901         s->plug = p;
902     return ret;
903 }
904
905 static void sk_tcp_flush(Socket s)
906 {
907     /*
908      * We send data to the socket as soon as we can anyway,
909      * so we don't need to do anything here.  :-)
910      */
911 }
912
913 static void sk_tcp_close(Socket s);
914 static int sk_tcp_write(Socket s, const char *data, int len);
915 static int sk_tcp_write_oob(Socket s, const char *data, int len);
916 static void sk_tcp_write_eof(Socket s);
917 static void sk_tcp_set_frozen(Socket s, int is_frozen);
918 static const char *sk_tcp_socket_error(Socket s);
919 static char *sk_tcp_peer_info(Socket s);
920
921 extern char *do_select(SOCKET skt, int startup);
922
923 static Socket sk_tcp_accept(accept_ctx_t ctx, Plug plug)
924 {
925     static const struct socket_function_table fn_table = {
926         sk_tcp_plug,
927         sk_tcp_close,
928         sk_tcp_write,
929         sk_tcp_write_oob,
930         sk_tcp_write_eof,
931         sk_tcp_flush,
932         sk_tcp_set_frozen,
933         sk_tcp_socket_error,
934         sk_tcp_peer_info,
935     };
936
937     DWORD err;
938     char *errstr;
939     Actual_Socket ret;
940
941     /*
942      * Create Socket structure.
943      */
944     ret = snew(struct Socket_tag);
945     ret->fn = &fn_table;
946     ret->error = NULL;
947     ret->plug = plug;
948     bufchain_init(&ret->output_data);
949     ret->writable = 1;                 /* to start with */
950     ret->sending_oob = 0;
951     ret->outgoingeof = EOF_NO;
952     ret->frozen = 1;
953     ret->frozen_readable = 0;
954     ret->localhost_only = 0;           /* unused, but best init anyway */
955     ret->pending_error = 0;
956     ret->parent = ret->child = NULL;
957     ret->addr = NULL;
958
959     ret->s = (SOCKET)ctx.p;
960
961     if (ret->s == INVALID_SOCKET) {
962         err = p_WSAGetLastError();
963         ret->error = winsock_error_string(err);
964         return (Socket) ret;
965     }
966
967     ret->oobinline = 0;
968
969     /* Set up a select mechanism. This could be an AsyncSelect on a
970      * window, or an EventSelect on an event object. */
971     errstr = do_select(ret->s, 1);
972     if (errstr) {
973         ret->error = errstr;
974         return (Socket) ret;
975     }
976
977     add234(sktree, ret);
978
979     return (Socket) ret;
980 }
981
982 static DWORD try_connect(Actual_Socket sock)
983 {
984     SOCKET s;
985 #ifndef NO_IPV6
986     SOCKADDR_IN6 a6;
987 #endif
988     SOCKADDR_IN a;
989     DWORD err;
990     char *errstr;
991     short localport;
992     int family;
993
994     if (sock->s != INVALID_SOCKET) {
995         do_select(sock->s, 0);
996         p_closesocket(sock->s);
997     }
998
999     {
1000         struct SockAddr_tag thisaddr = sk_extractaddr_tmp(
1001             sock->addr, &sock->step);
1002         plug_log(sock->plug, 0, &thisaddr, sock->port, NULL, 0);
1003     }
1004
1005     /*
1006      * Open socket.
1007      */
1008     family = SOCKADDR_FAMILY(sock->addr, sock->step);
1009
1010     /*
1011      * Remove the socket from the tree before we overwrite its
1012      * internal socket id, because that forms part of the tree's
1013      * sorting criterion. We'll add it back before exiting this
1014      * function, whether we changed anything or not.
1015      */
1016     del234(sktree, sock);
1017
1018     s = p_socket(family, SOCK_STREAM, 0);
1019     sock->s = s;
1020
1021     if (s == INVALID_SOCKET) {
1022         err = p_WSAGetLastError();
1023         sock->error = winsock_error_string(err);
1024         goto ret;
1025     }
1026
1027         SetHandleInformation((HANDLE)s, HANDLE_FLAG_INHERIT, 0);
1028
1029     if (sock->oobinline) {
1030         BOOL b = TRUE;
1031         p_setsockopt(s, SOL_SOCKET, SO_OOBINLINE, (void *) &b, sizeof(b));
1032     }
1033
1034     if (sock->nodelay) {
1035         BOOL b = TRUE;
1036         p_setsockopt(s, IPPROTO_TCP, TCP_NODELAY, (void *) &b, sizeof(b));
1037     }
1038
1039     if (sock->keepalive) {
1040         BOOL b = TRUE;
1041         p_setsockopt(s, SOL_SOCKET, SO_KEEPALIVE, (void *) &b, sizeof(b));
1042     }
1043
1044     /*
1045      * Bind to local address.
1046      */
1047     if (sock->privport)
1048         localport = 1023;              /* count from 1023 downwards */
1049     else
1050         localport = 0;                 /* just use port 0 (ie winsock picks) */
1051
1052     /* Loop round trying to bind */
1053     while (1) {
1054         int sockcode;
1055
1056 #ifndef NO_IPV6
1057         if (family == AF_INET6) {
1058             memset(&a6, 0, sizeof(a6));
1059             a6.sin6_family = AF_INET6;
1060           /*a6.sin6_addr = in6addr_any; */ /* == 0 done by memset() */
1061             a6.sin6_port = p_htons(localport);
1062         } else
1063 #endif
1064         {
1065             a.sin_family = AF_INET;
1066             a.sin_addr.s_addr = p_htonl(INADDR_ANY);
1067             a.sin_port = p_htons(localport);
1068         }
1069 #ifndef NO_IPV6
1070         sockcode = p_bind(s, (family == AF_INET6 ?
1071                               (struct sockaddr *) &a6 :
1072                               (struct sockaddr *) &a),
1073                           (family == AF_INET6 ? sizeof(a6) : sizeof(a)));
1074 #else
1075         sockcode = p_bind(s, (struct sockaddr *) &a, sizeof(a));
1076 #endif
1077         if (sockcode != SOCKET_ERROR) {
1078             err = 0;
1079             break;                     /* done */
1080         } else {
1081             err = p_WSAGetLastError();
1082             if (err != WSAEADDRINUSE)  /* failed, for a bad reason */
1083                 break;
1084         }
1085
1086         if (localport == 0)
1087             break;                     /* we're only looping once */
1088         localport--;
1089         if (localport == 0)
1090             break;                     /* we might have got to the end */
1091     }
1092
1093     if (err) {
1094         sock->error = winsock_error_string(err);
1095         goto ret;
1096     }
1097
1098     /*
1099      * Connect to remote address.
1100      */
1101 #ifndef NO_IPV6
1102     if (sock->step.ai) {
1103         if (family == AF_INET6) {
1104             a6.sin6_family = AF_INET6;
1105             a6.sin6_port = p_htons((short) sock->port);
1106             a6.sin6_addr =
1107                 ((struct sockaddr_in6 *) sock->step.ai->ai_addr)->sin6_addr;
1108             a6.sin6_flowinfo = ((struct sockaddr_in6 *) sock->step.ai->ai_addr)->sin6_flowinfo;
1109             a6.sin6_scope_id = ((struct sockaddr_in6 *) sock->step.ai->ai_addr)->sin6_scope_id;
1110         } else {
1111             a.sin_family = AF_INET;
1112             a.sin_addr =
1113                 ((struct sockaddr_in *) sock->step.ai->ai_addr)->sin_addr;
1114             a.sin_port = p_htons((short) sock->port);
1115         }
1116     } else
1117 #endif
1118     {
1119         assert(sock->addr->addresses && sock->step.curraddr < sock->addr->naddresses);
1120         a.sin_family = AF_INET;
1121         a.sin_addr.s_addr = p_htonl(sock->addr->addresses[sock->step.curraddr]);
1122         a.sin_port = p_htons((short) sock->port);
1123     }
1124
1125     /* Set up a select mechanism. This could be an AsyncSelect on a
1126      * window, or an EventSelect on an event object. */
1127     errstr = do_select(s, 1);
1128     if (errstr) {
1129         sock->error = errstr;
1130         err = 1;
1131         goto ret;
1132     }
1133
1134     if ((
1135 #ifndef NO_IPV6
1136             p_connect(s,
1137                       ((family == AF_INET6) ? (struct sockaddr *) &a6 :
1138                        (struct sockaddr *) &a),
1139                       (family == AF_INET6) ? sizeof(a6) : sizeof(a))
1140 #else
1141             p_connect(s, (struct sockaddr *) &a, sizeof(a))
1142 #endif
1143         ) == SOCKET_ERROR) {
1144         err = p_WSAGetLastError();
1145         /*
1146          * We expect a potential EWOULDBLOCK here, because the
1147          * chances are the front end has done a select for
1148          * FD_CONNECT, so that connect() will complete
1149          * asynchronously.
1150          */
1151         if ( err != WSAEWOULDBLOCK ) {
1152             sock->error = winsock_error_string(err);
1153             goto ret;
1154         }
1155     } else {
1156         /*
1157          * If we _don't_ get EWOULDBLOCK, the connect has completed
1158          * and we should set the socket as writable.
1159          */
1160         sock->writable = 1;
1161     }
1162
1163     err = 0;
1164
1165     ret:
1166
1167     /*
1168      * No matter what happened, put the socket back in the tree.
1169      */
1170     add234(sktree, sock);
1171
1172     if (err) {
1173         struct SockAddr_tag thisaddr = sk_extractaddr_tmp(
1174             sock->addr, &sock->step);
1175         plug_log(sock->plug, 1, &thisaddr, sock->port, sock->error, err);
1176     }
1177     return err;
1178 }
1179
1180 Socket sk_new(SockAddr addr, int port, int privport, int oobinline,
1181               int nodelay, int keepalive, Plug plug)
1182 {
1183     static const struct socket_function_table fn_table = {
1184         sk_tcp_plug,
1185         sk_tcp_close,
1186         sk_tcp_write,
1187         sk_tcp_write_oob,
1188         sk_tcp_write_eof,
1189         sk_tcp_flush,
1190         sk_tcp_set_frozen,
1191         sk_tcp_socket_error,
1192         sk_tcp_peer_info,
1193     };
1194
1195     Actual_Socket ret;
1196     DWORD err;
1197
1198     /*
1199      * Create Socket structure.
1200      */
1201     ret = snew(struct Socket_tag);
1202     ret->fn = &fn_table;
1203     ret->error = NULL;
1204     ret->plug = plug;
1205     bufchain_init(&ret->output_data);
1206     ret->connected = 0;                /* to start with */
1207     ret->writable = 0;                 /* to start with */
1208     ret->sending_oob = 0;
1209     ret->outgoingeof = EOF_NO;
1210     ret->frozen = 0;
1211     ret->frozen_readable = 0;
1212     ret->localhost_only = 0;           /* unused, but best init anyway */
1213     ret->pending_error = 0;
1214     ret->parent = ret->child = NULL;
1215     ret->oobinline = oobinline;
1216     ret->nodelay = nodelay;
1217     ret->keepalive = keepalive;
1218     ret->privport = privport;
1219     ret->port = port;
1220     ret->addr = addr;
1221     START_STEP(ret->addr, ret->step);
1222     ret->s = INVALID_SOCKET;
1223
1224     err = 0;
1225     do {
1226         err = try_connect(ret);
1227     } while (err && sk_nextaddr(ret->addr, &ret->step));
1228
1229     return (Socket) ret;
1230 }
1231
1232 Socket sk_newlistener(const char *srcaddr, int port, Plug plug,
1233                       int local_host_only, int orig_address_family)
1234 {
1235     static const struct socket_function_table fn_table = {
1236         sk_tcp_plug,
1237         sk_tcp_close,
1238         sk_tcp_write,
1239         sk_tcp_write_oob,
1240         sk_tcp_write_eof,
1241         sk_tcp_flush,
1242         sk_tcp_set_frozen,
1243         sk_tcp_socket_error,
1244         sk_tcp_peer_info,
1245     };
1246
1247     SOCKET s;
1248 #ifndef NO_IPV6
1249     SOCKADDR_IN6 a6;
1250 #endif
1251     SOCKADDR_IN a;
1252
1253     DWORD err;
1254     char *errstr;
1255     Actual_Socket ret;
1256     int retcode;
1257     int on = 1;
1258
1259     int address_family;
1260
1261     /*
1262      * Create Socket structure.
1263      */
1264     ret = snew(struct Socket_tag);
1265     ret->fn = &fn_table;
1266     ret->error = NULL;
1267     ret->plug = plug;
1268     bufchain_init(&ret->output_data);
1269     ret->writable = 0;                 /* to start with */
1270     ret->sending_oob = 0;
1271     ret->outgoingeof = EOF_NO;
1272     ret->frozen = 0;
1273     ret->frozen_readable = 0;
1274     ret->localhost_only = local_host_only;
1275     ret->pending_error = 0;
1276     ret->parent = ret->child = NULL;
1277     ret->addr = NULL;
1278
1279     /*
1280      * Translate address_family from platform-independent constants
1281      * into local reality.
1282      */
1283     address_family = (orig_address_family == ADDRTYPE_IPV4 ? AF_INET :
1284 #ifndef NO_IPV6
1285                       orig_address_family == ADDRTYPE_IPV6 ? AF_INET6 :
1286 #endif
1287                       AF_UNSPEC);
1288
1289     /*
1290      * Our default, if passed the `don't care' value
1291      * ADDRTYPE_UNSPEC, is to listen on IPv4. If IPv6 is supported,
1292      * we will also set up a second socket listening on IPv6, but
1293      * the v4 one is primary since that ought to work even on
1294      * non-v6-supporting systems.
1295      */
1296     if (address_family == AF_UNSPEC) address_family = AF_INET;
1297
1298     /*
1299      * Open socket.
1300      */
1301     s = p_socket(address_family, SOCK_STREAM, 0);
1302     ret->s = s;
1303
1304     if (s == INVALID_SOCKET) {
1305         err = p_WSAGetLastError();
1306         ret->error = winsock_error_string(err);
1307         return (Socket) ret;
1308     }
1309
1310         SetHandleInformation((HANDLE)s, HANDLE_FLAG_INHERIT, 0);
1311
1312     ret->oobinline = 0;
1313
1314     p_setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (const char *)&on, sizeof(on));
1315
1316 #ifndef NO_IPV6
1317         if (address_family == AF_INET6) {
1318             memset(&a6, 0, sizeof(a6));
1319             a6.sin6_family = AF_INET6;
1320             if (local_host_only)
1321                 a6.sin6_addr = in6addr_loopback;
1322             else
1323                 a6.sin6_addr = in6addr_any;
1324             if (srcaddr != NULL && p_getaddrinfo) {
1325                 struct addrinfo hints;
1326                 struct addrinfo *ai;
1327                 int err;
1328
1329                 memset(&hints, 0, sizeof(hints));
1330                 hints.ai_family = AF_INET6;
1331                 hints.ai_flags = 0;
1332                 {
1333                     /* strip [] on IPv6 address literals */
1334                     char *trimmed_addr = host_strduptrim(srcaddr);
1335                     err = p_getaddrinfo(trimmed_addr, NULL, &hints, &ai);
1336                     sfree(trimmed_addr);
1337                 }
1338                 if (err == 0 && ai->ai_family == AF_INET6) {
1339                     a6.sin6_addr =
1340                         ((struct sockaddr_in6 *)ai->ai_addr)->sin6_addr;
1341                 }
1342             }
1343             a6.sin6_port = p_htons(port);
1344         } else
1345 #endif
1346         {
1347             int got_addr = 0;
1348             a.sin_family = AF_INET;
1349
1350             /*
1351              * Bind to source address. First try an explicitly
1352              * specified one...
1353              */
1354             if (srcaddr) {
1355                 a.sin_addr.s_addr = p_inet_addr(srcaddr);
1356                 if (a.sin_addr.s_addr != INADDR_NONE) {
1357                     /* Override localhost_only with specified listen addr. */
1358                     ret->localhost_only = ipv4_is_loopback(a.sin_addr);
1359                     got_addr = 1;
1360                 }
1361             }
1362
1363             /*
1364              * ... and failing that, go with one of the standard ones.
1365              */
1366             if (!got_addr) {
1367                 if (local_host_only)
1368                     a.sin_addr.s_addr = p_htonl(INADDR_LOOPBACK);
1369                 else
1370                     a.sin_addr.s_addr = p_htonl(INADDR_ANY);
1371             }
1372
1373             a.sin_port = p_htons((short)port);
1374         }
1375 #ifndef NO_IPV6
1376         retcode = p_bind(s, (address_family == AF_INET6 ?
1377                            (struct sockaddr *) &a6 :
1378                            (struct sockaddr *) &a),
1379                        (address_family ==
1380                         AF_INET6 ? sizeof(a6) : sizeof(a)));
1381 #else
1382         retcode = p_bind(s, (struct sockaddr *) &a, sizeof(a));
1383 #endif
1384         if (retcode != SOCKET_ERROR) {
1385             err = 0;
1386         } else {
1387             err = p_WSAGetLastError();
1388         }
1389
1390     if (err) {
1391         p_closesocket(s);
1392         ret->error = winsock_error_string(err);
1393         return (Socket) ret;
1394     }
1395
1396
1397     if (p_listen(s, SOMAXCONN) == SOCKET_ERROR) {
1398         p_closesocket(s);
1399         ret->error = winsock_error_string(p_WSAGetLastError());
1400         return (Socket) ret;
1401     }
1402
1403     /* Set up a select mechanism. This could be an AsyncSelect on a
1404      * window, or an EventSelect on an event object. */
1405     errstr = do_select(s, 1);
1406     if (errstr) {
1407         p_closesocket(s);
1408         ret->error = errstr;
1409         return (Socket) ret;
1410     }
1411
1412     add234(sktree, ret);
1413
1414 #ifndef NO_IPV6
1415     /*
1416      * If we were given ADDRTYPE_UNSPEC, we must also create an
1417      * IPv6 listening socket and link it to this one.
1418      */
1419     if (address_family == AF_INET && orig_address_family == ADDRTYPE_UNSPEC) {
1420         Actual_Socket other;
1421
1422         other = (Actual_Socket) sk_newlistener(srcaddr, port, plug,
1423                                                local_host_only, ADDRTYPE_IPV6);
1424
1425         if (other) {
1426             if (!other->error) {
1427                 other->parent = ret;
1428                 ret->child = other;
1429             } else {
1430                 sfree(other);
1431             }
1432         }
1433     }
1434 #endif
1435
1436     return (Socket) ret;
1437 }
1438
1439 static void sk_tcp_close(Socket sock)
1440 {
1441     extern char *do_select(SOCKET skt, int startup);
1442     Actual_Socket s = (Actual_Socket) sock;
1443
1444     if (s->child)
1445         sk_tcp_close((Socket)s->child);
1446
1447     del234(sktree, s);
1448     do_select(s->s, 0);
1449     p_closesocket(s->s);
1450     if (s->addr)
1451         sk_addr_free(s->addr);
1452     sfree(s);
1453 }
1454
1455 /*
1456  * Deal with socket errors detected in try_send().
1457  */
1458 static void socket_error_callback(void *vs)
1459 {
1460     Actual_Socket s = (Actual_Socket)vs;
1461
1462     /*
1463      * Just in case other socket work has caused this socket to vanish
1464      * or become somehow non-erroneous before this callback arrived...
1465      */
1466     if (!find234(sktree, s, NULL) || !s->pending_error)
1467         return;
1468
1469     /*
1470      * An error has occurred on this socket. Pass it to the plug.
1471      */
1472     plug_closing(s->plug, winsock_error_string(s->pending_error),
1473                  s->pending_error, 0);
1474 }
1475
1476 /*
1477  * The function which tries to send on a socket once it's deemed
1478  * writable.
1479  */
1480 void try_send(Actual_Socket s)
1481 {
1482     while (s->sending_oob || bufchain_size(&s->output_data) > 0) {
1483         int nsent;
1484         DWORD err;
1485         void *data;
1486         int len, urgentflag;
1487
1488         if (s->sending_oob) {
1489             urgentflag = MSG_OOB;
1490             len = s->sending_oob;
1491             data = &s->oobdata;
1492         } else {
1493             urgentflag = 0;
1494             bufchain_prefix(&s->output_data, &data, &len);
1495         }
1496         nsent = p_send(s->s, data, len, urgentflag);
1497         noise_ultralight(nsent);
1498         if (nsent <= 0) {
1499             err = (nsent < 0 ? p_WSAGetLastError() : 0);
1500             if ((err < WSABASEERR && nsent < 0) || err == WSAEWOULDBLOCK) {
1501                 /*
1502                  * Perfectly normal: we've sent all we can for the moment.
1503                  * 
1504                  * (Some WinSock send() implementations can return
1505                  * <0 but leave no sensible error indication -
1506                  * WSAGetLastError() is called but returns zero or
1507                  * a small number - so we check that case and treat
1508                  * it just like WSAEWOULDBLOCK.)
1509                  */
1510                 s->writable = FALSE;
1511                 return;
1512             } else if (nsent == 0 ||
1513                        err == WSAECONNABORTED || err == WSAECONNRESET) {
1514                 /*
1515                  * If send() returns CONNABORTED or CONNRESET, we
1516                  * unfortunately can't just call plug_closing(),
1517                  * because it's quite likely that we're currently
1518                  * _in_ a call from the code we'd be calling back
1519                  * to, so we'd have to make half the SSH code
1520                  * reentrant. Instead we flag a pending error on
1521                  * the socket, to be dealt with (by calling
1522                  * plug_closing()) at some suitable future moment.
1523                  */
1524                 s->pending_error = err;
1525                 queue_toplevel_callback(socket_error_callback, s);
1526                 return;
1527             } else {
1528                 /* We're inside the Windows frontend here, so we know
1529                  * that the frontend handle is unnecessary. */
1530                 logevent(NULL, winsock_error_string(err));
1531                 fatalbox("%s", winsock_error_string(err));
1532             }
1533         } else {
1534             if (s->sending_oob) {
1535                 if (nsent < len) {
1536                     memmove(s->oobdata, s->oobdata+nsent, len-nsent);
1537                     s->sending_oob = len - nsent;
1538                 } else {
1539                     s->sending_oob = 0;
1540                 }
1541             } else {
1542                 bufchain_consume(&s->output_data, nsent);
1543             }
1544         }
1545     }
1546
1547     /*
1548      * If we reach here, we've finished sending everything we might
1549      * have needed to send. Send EOF, if we need to.
1550      */
1551     if (s->outgoingeof == EOF_PENDING) {
1552         p_shutdown(s->s, SD_SEND);
1553         s->outgoingeof = EOF_SENT;
1554     }
1555 }
1556
1557 static int sk_tcp_write(Socket sock, const char *buf, int len)
1558 {
1559     Actual_Socket s = (Actual_Socket) sock;
1560
1561     assert(s->outgoingeof == EOF_NO);
1562
1563     /*
1564      * Add the data to the buffer list on the socket.
1565      */
1566     bufchain_add(&s->output_data, buf, len);
1567
1568     /*
1569      * Now try sending from the start of the buffer list.
1570      */
1571     if (s->writable)
1572         try_send(s);
1573
1574     return bufchain_size(&s->output_data);
1575 }
1576
1577 static int sk_tcp_write_oob(Socket sock, const char *buf, int len)
1578 {
1579     Actual_Socket s = (Actual_Socket) sock;
1580
1581     assert(s->outgoingeof == EOF_NO);
1582
1583     /*
1584      * Replace the buffer list on the socket with the data.
1585      */
1586     bufchain_clear(&s->output_data);
1587     assert(len <= sizeof(s->oobdata));
1588     memcpy(s->oobdata, buf, len);
1589     s->sending_oob = len;
1590
1591     /*
1592      * Now try sending from the start of the buffer list.
1593      */
1594     if (s->writable)
1595         try_send(s);
1596
1597     return s->sending_oob;
1598 }
1599
1600 static void sk_tcp_write_eof(Socket sock)
1601 {
1602     Actual_Socket s = (Actual_Socket) sock;
1603
1604     assert(s->outgoingeof == EOF_NO);
1605
1606     /*
1607      * Mark the socket as pending outgoing EOF.
1608      */
1609     s->outgoingeof = EOF_PENDING;
1610
1611     /*
1612      * Now try sending from the start of the buffer list.
1613      */
1614     if (s->writable)
1615         try_send(s);
1616 }
1617
1618 int select_result(WPARAM wParam, LPARAM lParam)
1619 {
1620     int ret, open;
1621     DWORD err;
1622     char buf[20480];                   /* nice big buffer for plenty of speed */
1623     Actual_Socket s;
1624     u_long atmark;
1625
1626     /* wParam is the socket itself */
1627
1628     if (wParam == 0)
1629         return 1;                      /* boggle */
1630
1631     s = find234(sktree, (void *) wParam, cmpforsearch);
1632     if (!s)
1633         return 1;                      /* boggle */
1634
1635     if ((err = WSAGETSELECTERROR(lParam)) != 0) {
1636         /*
1637          * An error has occurred on this socket. Pass it to the
1638          * plug.
1639          */
1640         if (s->addr) {
1641             struct SockAddr_tag thisaddr = sk_extractaddr_tmp(
1642                 s->addr, &s->step);
1643             plug_log(s->plug, 1, &thisaddr, s->port,
1644                      winsock_error_string(err), err);
1645             while (err && s->addr && sk_nextaddr(s->addr, &s->step)) {
1646                 err = try_connect(s);
1647             }
1648         }
1649         if (err != 0)
1650             return plug_closing(s->plug, winsock_error_string(err), err, 0);
1651         else
1652             return 1;
1653     }
1654
1655     noise_ultralight(lParam);
1656
1657     switch (WSAGETSELECTEVENT(lParam)) {
1658       case FD_CONNECT:
1659         s->connected = s->writable = 1;
1660         /*
1661          * Once a socket is connected, we can stop falling
1662          * back through the candidate addresses to connect
1663          * to.
1664          */
1665         if (s->addr) {
1666             sk_addr_free(s->addr);
1667             s->addr = NULL;
1668         }
1669         break;
1670       case FD_READ:
1671         /* In the case the socket is still frozen, we don't even bother */
1672         if (s->frozen) {
1673             s->frozen_readable = 1;
1674             break;
1675         }
1676
1677         /*
1678          * We have received data on the socket. For an oobinline
1679          * socket, this might be data _before_ an urgent pointer,
1680          * in which case we send it to the back end with type==1
1681          * (data prior to urgent).
1682          */
1683         if (s->oobinline) {
1684             atmark = 1;
1685             p_ioctlsocket(s->s, SIOCATMARK, &atmark);
1686             /*
1687              * Avoid checking the return value from ioctlsocket(),
1688              * on the grounds that some WinSock wrappers don't
1689              * support it. If it does nothing, we get atmark==1,
1690              * which is equivalent to `no OOB pending', so the
1691              * effect will be to non-OOB-ify any OOB data.
1692              */
1693         } else
1694             atmark = 1;
1695
1696         ret = p_recv(s->s, buf, sizeof(buf), 0);
1697         noise_ultralight(ret);
1698         if (ret < 0) {
1699             err = p_WSAGetLastError();
1700             if (err == WSAEWOULDBLOCK) {
1701                 break;
1702             }
1703         }
1704         if (ret < 0) {
1705             return plug_closing(s->plug, winsock_error_string(err), err,
1706                                 0);
1707         } else if (0 == ret) {
1708             return plug_closing(s->plug, NULL, 0, 0);
1709         } else {
1710             return plug_receive(s->plug, atmark ? 0 : 1, buf, ret);
1711         }
1712         break;
1713       case FD_OOB:
1714         /*
1715          * This will only happen on a non-oobinline socket. It
1716          * indicates that we can immediately perform an OOB read
1717          * and get back OOB data, which we will send to the back
1718          * end with type==2 (urgent data).
1719          */
1720         ret = p_recv(s->s, buf, sizeof(buf), MSG_OOB);
1721         noise_ultralight(ret);
1722         if (ret <= 0) {
1723             const char *str = (ret == 0 ? "Internal networking trouble" :
1724                          winsock_error_string(p_WSAGetLastError()));
1725             /* We're inside the Windows frontend here, so we know
1726              * that the frontend handle is unnecessary. */
1727             logevent(NULL, str);
1728             fatalbox("%s", str);
1729         } else {
1730             return plug_receive(s->plug, 2, buf, ret);
1731         }
1732         break;
1733       case FD_WRITE:
1734         {
1735             int bufsize_before, bufsize_after;
1736             s->writable = 1;
1737             bufsize_before = s->sending_oob + bufchain_size(&s->output_data);
1738             try_send(s);
1739             bufsize_after = s->sending_oob + bufchain_size(&s->output_data);
1740             if (bufsize_after < bufsize_before)
1741                 plug_sent(s->plug, bufsize_after);
1742         }
1743         break;
1744       case FD_CLOSE:
1745         /* Signal a close on the socket. First read any outstanding data. */
1746         open = 1;
1747         do {
1748             ret = p_recv(s->s, buf, sizeof(buf), 0);
1749             if (ret < 0) {
1750                 err = p_WSAGetLastError();
1751                 if (err == WSAEWOULDBLOCK)
1752                     break;
1753                 return plug_closing(s->plug, winsock_error_string(err),
1754                                     err, 0);
1755             } else {
1756                 if (ret)
1757                     open &= plug_receive(s->plug, 0, buf, ret);
1758                 else
1759                     open &= plug_closing(s->plug, NULL, 0, 0);
1760             }
1761         } while (ret > 0);
1762         return open;
1763        case FD_ACCEPT:
1764         {
1765 #ifdef NO_IPV6
1766             struct sockaddr_in isa;
1767 #else
1768             struct sockaddr_storage isa;
1769 #endif
1770             int addrlen = sizeof(isa);
1771             SOCKET t;  /* socket of connection */
1772             accept_ctx_t actx;
1773
1774             memset(&isa, 0, sizeof(isa));
1775             err = 0;
1776             t = p_accept(s->s,(struct sockaddr *)&isa,&addrlen);
1777             if (t == INVALID_SOCKET)
1778             {
1779                 err = p_WSAGetLastError();
1780                 if (err == WSATRY_AGAIN)
1781                     break;
1782             }
1783
1784             actx.p = (void *)t;
1785
1786 #ifndef NO_IPV6
1787             if (isa.ss_family == AF_INET &&
1788                 s->localhost_only &&
1789                 !ipv4_is_local_addr(((struct sockaddr_in *)&isa)->sin_addr))
1790 #else
1791             if (s->localhost_only && !ipv4_is_local_addr(isa.sin_addr))
1792 #endif
1793             {
1794                 p_closesocket(t);      /* dodgy WinSock let nonlocal through */
1795             } else if (plug_accepting(s->plug, sk_tcp_accept, actx)) {
1796                 p_closesocket(t);      /* denied or error */
1797             }
1798         }
1799     }
1800
1801     return 1;
1802 }
1803
1804 /*
1805  * Special error values are returned from sk_namelookup and sk_new
1806  * if there's a problem. These functions extract an error message,
1807  * or return NULL if there's no problem.
1808  */
1809 const char *sk_addr_error(SockAddr addr)
1810 {
1811     return addr->error;
1812 }
1813 static const char *sk_tcp_socket_error(Socket sock)
1814 {
1815     Actual_Socket s = (Actual_Socket) sock;
1816     return s->error;
1817 }
1818
1819 static char *sk_tcp_peer_info(Socket sock)
1820 {
1821     Actual_Socket s = (Actual_Socket) sock;
1822 #ifdef NO_IPV6
1823     struct sockaddr_in addr;
1824 #else
1825     struct sockaddr_storage addr;
1826     char buf[INET6_ADDRSTRLEN];
1827 #endif
1828     int addrlen = sizeof(addr);
1829
1830     if (p_getpeername(s->s, (struct sockaddr *)&addr, &addrlen) < 0)
1831         return NULL;
1832
1833     if (((struct sockaddr *)&addr)->sa_family == AF_INET) {
1834         return dupprintf
1835             ("%s:%d",
1836              p_inet_ntoa(((struct sockaddr_in *)&addr)->sin_addr),
1837              (int)p_ntohs(((struct sockaddr_in *)&addr)->sin_port));
1838 #ifndef NO_IPV6
1839     } else if (((struct sockaddr *)&addr)->sa_family == AF_INET6) {
1840         return dupprintf
1841             ("[%s]:%d",
1842              p_inet_ntop(AF_INET6, &((struct sockaddr_in6 *)&addr)->sin6_addr,
1843                          buf, sizeof(buf)),
1844              (int)p_ntohs(((struct sockaddr_in6 *)&addr)->sin6_port));
1845 #endif
1846     } else {
1847         return NULL;
1848     }
1849 }
1850
1851 static void sk_tcp_set_frozen(Socket sock, int is_frozen)
1852 {
1853     Actual_Socket s = (Actual_Socket) sock;
1854     if (s->frozen == is_frozen)
1855         return;
1856     s->frozen = is_frozen;
1857     if (!is_frozen) {
1858         do_select(s->s, 1);
1859         if (s->frozen_readable) {
1860             char c;
1861             p_recv(s->s, &c, 1, MSG_PEEK);
1862         }
1863     }
1864     s->frozen_readable = 0;
1865 }
1866
1867 void socket_reselect_all(void)
1868 {
1869     Actual_Socket s;
1870     int i;
1871
1872     for (i = 0; (s = index234(sktree, i)) != NULL; i++) {
1873         if (!s->frozen)
1874             do_select(s->s, 1);
1875     }
1876 }
1877
1878 /*
1879  * For Plink: enumerate all sockets currently active.
1880  */
1881 SOCKET first_socket(int *state)
1882 {
1883     Actual_Socket s;
1884     *state = 0;
1885     s = index234(sktree, (*state)++);
1886     return s ? s->s : INVALID_SOCKET;
1887 }
1888
1889 SOCKET next_socket(int *state)
1890 {
1891     Actual_Socket s = index234(sktree, (*state)++);
1892     return s ? s->s : INVALID_SOCKET;
1893 }
1894
1895 extern int socket_writable(SOCKET skt)
1896 {
1897     Actual_Socket s = find234(sktree, (void *)skt, cmpforsearch);
1898
1899     if (s)
1900         return bufchain_size(&s->output_data) > 0;
1901     else
1902         return 0;
1903 }
1904
1905 int net_service_lookup(char *service)
1906 {
1907     struct servent *se;
1908     se = p_getservbyname(service, NULL);
1909     if (se != NULL)
1910         return p_ntohs(se->s_port);
1911     else
1912         return 0;
1913 }
1914
1915 char *get_hostname(void)
1916 {
1917     int len = 128;
1918     char *hostname = NULL;
1919     do {
1920         len *= 2;
1921         hostname = sresize(hostname, len, char);
1922         if (p_gethostname(hostname, len) < 0) {
1923             sfree(hostname);
1924             hostname = NULL;
1925             break;
1926         }
1927     } while (strlen(hostname) >= (size_t)(len-1));
1928     return hostname;
1929 }
1930
1931 SockAddr platform_get_x11_unix_address(const char *display, int displaynum,
1932                                        char **canonicalname)
1933 {
1934     SockAddr ret = snew(struct SockAddr_tag);
1935     memset(ret, 0, sizeof(struct SockAddr_tag));
1936     ret->error = "unix sockets not supported on this platform";
1937     ret->refcount = 1;
1938     return ret;
1939 }