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