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