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