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