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