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