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