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