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