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