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