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