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