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