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