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