Update README.md
[puttycyg-ng.git] / windows / winnet.c
blob820468cafe9a13be889667259977493d5e090b25
1 /*
2 * Windows networking abstraction.
4 * For the IPv6 code in here I am indebted to Jeroen Massar and
5 * unfix.org.
6 */
8 #include <stdio.h>
9 #include <stdlib.h>
10 #include <assert.h>
12 #define DEFINE_PLUG_METHOD_MACROS
13 #include "putty.h"
14 #include "network.h"
15 #include "tree234.h"
17 #include <ws2tcpip.h>
19 #ifndef NO_IPV6
20 const struct in6_addr in6addr_any = IN6ADDR_ANY_INIT;
21 const struct in6_addr in6addr_loopback = IN6ADDR_LOOPBACK_INIT;
22 #endif
24 #define ipv4_is_loopback(addr) \
25 ((p_ntohl(addr.s_addr) & 0xFF000000L) == 0x7F000000L)
28 * We used to typedef struct Socket_tag *Socket.
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.
35 typedef struct Socket_tag *Actual_Socket;
37 struct Socket_tag {
38 const struct socket_function_table *fn;
39 /* the above variable absolutely *must* be the first in this structure */
40 char *error;
41 SOCKET s;
42 Plug plug;
43 void *private_ptr;
44 bufchain output_data;
45 int connected;
46 int writable;
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 */
50 int localhost_only; /* for listening sockets */
51 char oobdata[1];
52 int sending_oob;
53 int oobinline, nodelay, keepalive, privport;
54 SockAddr addr;
55 int port;
56 int pending_error; /* in case send() returns error */
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.
63 Actual_Socket parent, child;
66 struct SockAddr_tag {
67 char *error;
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.
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.
79 int family;
80 #ifndef NO_IPV6
81 struct addrinfo *ais; /* Addresses IPv6 style. */
82 struct addrinfo *ai; /* steps along the linked list */
83 #endif
84 unsigned long *addresses; /* Addresses IPv4 style. */
85 int naddresses, curraddr;
86 char hostname[512]; /* Store an unresolved host name. */
89 static tree234 *sktree;
91 static int cmpfortree(void *av, void *bv)
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;
99 return 0;
102 static int cmpforsearch(void *av, void *bv)
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;
110 return 0;
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
117 #define GET_WINSOCK_FUNCTION(module, name) \
118 p_##name = module ? (t_##name) GetProcAddress(module, #name) : NULL
120 DECL_WINSOCK_FUNCTION(NOTHING, int, WSAAsyncSelect,
121 (SOCKET, HWND, u_int, long));
122 DECL_WINSOCK_FUNCTION(NOTHING, int, WSAEventSelect, (SOCKET, WSAEVENT, long));
123 DECL_WINSOCK_FUNCTION(NOTHING, int, select,
124 (int, fd_set FAR *, fd_set FAR *,
125 fd_set FAR *, const struct timeval FAR *));
126 DECL_WINSOCK_FUNCTION(NOTHING, int, WSAGetLastError, (void));
127 DECL_WINSOCK_FUNCTION(NOTHING, int, WSAEnumNetworkEvents,
128 (SOCKET, WSAEVENT, LPWSANETWORKEVENTS));
129 DECL_WINSOCK_FUNCTION(static, int, WSAStartup, (WORD, LPWSADATA));
130 DECL_WINSOCK_FUNCTION(static, int, WSACleanup, (void));
131 DECL_WINSOCK_FUNCTION(static, int, closesocket, (SOCKET));
132 DECL_WINSOCK_FUNCTION(static, u_long, ntohl, (u_long));
133 DECL_WINSOCK_FUNCTION(static, u_long, htonl, (u_long));
134 DECL_WINSOCK_FUNCTION(static, u_short, htons, (u_short));
135 DECL_WINSOCK_FUNCTION(static, u_short, ntohs, (u_short));
136 DECL_WINSOCK_FUNCTION(static, struct hostent FAR *, gethostbyname,
137 (const char FAR *));
138 DECL_WINSOCK_FUNCTION(static, struct servent FAR *, getservbyname,
139 (const char FAR *, const char FAR *));
140 DECL_WINSOCK_FUNCTION(static, unsigned long, inet_addr, (const char FAR *));
141 DECL_WINSOCK_FUNCTION(static, char FAR *, inet_ntoa, (struct in_addr));
142 DECL_WINSOCK_FUNCTION(static, int, connect,
143 (SOCKET, const struct sockaddr FAR *, int));
144 DECL_WINSOCK_FUNCTION(static, int, bind,
145 (SOCKET, const struct sockaddr FAR *, int));
146 DECL_WINSOCK_FUNCTION(static, int, setsockopt,
147 (SOCKET, int, int, const char FAR *, int));
148 DECL_WINSOCK_FUNCTION(static, SOCKET, socket, (int, int, int));
149 DECL_WINSOCK_FUNCTION(static, int, listen, (SOCKET, int));
150 DECL_WINSOCK_FUNCTION(static, int, send, (SOCKET, const char FAR *, int, int));
151 DECL_WINSOCK_FUNCTION(static, int, ioctlsocket,
152 (SOCKET, long, u_long FAR *));
153 DECL_WINSOCK_FUNCTION(static, SOCKET, accept,
154 (SOCKET, struct sockaddr FAR *, int FAR *));
155 DECL_WINSOCK_FUNCTION(static, int, recv, (SOCKET, char FAR *, int, int));
156 DECL_WINSOCK_FUNCTION(static, int, WSAIoctl,
157 (SOCKET, DWORD, LPVOID, DWORD, LPVOID, DWORD,
158 LPDWORD, LPWSAOVERLAPPED,
159 LPWSAOVERLAPPED_COMPLETION_ROUTINE));
160 DECL_WINSOCK_FUNCTION(static, int, getsockname,
161 (SOCKET, const struct sockaddr FAR *, int FAR *));
162 #ifndef NO_IPV6
163 DECL_WINSOCK_FUNCTION(static, int, getaddrinfo,
164 (const char *nodename, const char *servname,
165 const struct addrinfo *hints, struct addrinfo **res));
166 DECL_WINSOCK_FUNCTION(static, void, freeaddrinfo, (struct addrinfo *res));
167 DECL_WINSOCK_FUNCTION(static, int, getnameinfo,
168 (const struct sockaddr FAR * sa, socklen_t salen,
169 char FAR * host, size_t hostlen, char FAR * serv,
170 size_t servlen, int flags));
171 DECL_WINSOCK_FUNCTION(static, char *, gai_strerror, (int ecode));
172 DECL_WINSOCK_FUNCTION(static, int, WSAAddressToStringA,
173 (LPSOCKADDR, DWORD, LPWSAPROTOCOL_INFO,
174 LPTSTR, LPDWORD));
175 #endif
177 static HMODULE winsock_module = NULL;
178 static WSADATA wsadata;
179 #ifndef NO_IPV6
180 static HMODULE winsock2_module = NULL;
181 static HMODULE wship6_module = NULL;
182 #endif
184 int sk_startup(int hi, int lo)
186 WORD winsock_ver;
188 winsock_ver = MAKEWORD(hi, lo);
190 if (p_WSAStartup(winsock_ver, &wsadata)) {
191 return FALSE;
194 if (LOBYTE(wsadata.wVersion) != LOBYTE(winsock_ver)) {
195 return FALSE;
198 #ifdef NET_SETUP_DIAGNOSTICS
200 char buf[80];
201 sprintf(buf, "Using WinSock %d.%d", hi, lo);
202 logevent(NULL, buf);
204 #endif
205 return TRUE;
208 void sk_init(void)
210 #ifndef NO_IPV6
211 winsock2_module =
212 #endif
213 winsock_module = LoadLibrary("WS2_32.DLL");
214 if (!winsock_module) {
215 winsock_module = LoadLibrary("WSOCK32.DLL");
217 if (!winsock_module)
218 fatalbox("Unable to load any WinSock library");
220 #ifndef NO_IPV6
221 /* Check if we have getaddrinfo in Winsock */
222 if (GetProcAddress(winsock_module, "getaddrinfo") != NULL) {
223 #ifdef NET_SETUP_DIAGNOSTICS
224 logevent(NULL, "Native WinSock IPv6 support detected");
225 #endif
226 GET_WINSOCK_FUNCTION(winsock_module, getaddrinfo);
227 GET_WINSOCK_FUNCTION(winsock_module, freeaddrinfo);
228 GET_WINSOCK_FUNCTION(winsock_module, getnameinfo);
229 GET_WINSOCK_FUNCTION(winsock_module, gai_strerror);
230 } else {
231 /* Fall back to wship6.dll for Windows 2000 */
232 wship6_module = LoadLibrary("wship6.dll");
233 if (wship6_module) {
234 #ifdef NET_SETUP_DIAGNOSTICS
235 logevent(NULL, "WSH IPv6 support detected");
236 #endif
237 GET_WINSOCK_FUNCTION(wship6_module, getaddrinfo);
238 GET_WINSOCK_FUNCTION(wship6_module, freeaddrinfo);
239 GET_WINSOCK_FUNCTION(wship6_module, getnameinfo);
240 GET_WINSOCK_FUNCTION(wship6_module, gai_strerror);
241 } else {
242 #ifdef NET_SETUP_DIAGNOSTICS
243 logevent(NULL, "No IPv6 support detected");
244 #endif
247 GET_WINSOCK_FUNCTION(winsock2_module, WSAAddressToStringA);
248 #else
249 #ifdef NET_SETUP_DIAGNOSTICS
250 logevent(NULL, "PuTTY was built without IPv6 support");
251 #endif
252 #endif
254 GET_WINSOCK_FUNCTION(winsock_module, WSAAsyncSelect);
255 GET_WINSOCK_FUNCTION(winsock_module, WSAEventSelect);
256 GET_WINSOCK_FUNCTION(winsock_module, select);
257 GET_WINSOCK_FUNCTION(winsock_module, WSAGetLastError);
258 GET_WINSOCK_FUNCTION(winsock_module, WSAEnumNetworkEvents);
259 GET_WINSOCK_FUNCTION(winsock_module, WSAStartup);
260 GET_WINSOCK_FUNCTION(winsock_module, WSACleanup);
261 GET_WINSOCK_FUNCTION(winsock_module, closesocket);
262 GET_WINSOCK_FUNCTION(winsock_module, ntohl);
263 GET_WINSOCK_FUNCTION(winsock_module, htonl);
264 GET_WINSOCK_FUNCTION(winsock_module, htons);
265 GET_WINSOCK_FUNCTION(winsock_module, ntohs);
266 GET_WINSOCK_FUNCTION(winsock_module, gethostbyname);
267 GET_WINSOCK_FUNCTION(winsock_module, getservbyname);
268 GET_WINSOCK_FUNCTION(winsock_module, inet_addr);
269 GET_WINSOCK_FUNCTION(winsock_module, inet_ntoa);
270 GET_WINSOCK_FUNCTION(winsock_module, connect);
271 GET_WINSOCK_FUNCTION(winsock_module, bind);
272 GET_WINSOCK_FUNCTION(winsock_module, setsockopt);
273 GET_WINSOCK_FUNCTION(winsock_module, socket);
274 GET_WINSOCK_FUNCTION(winsock_module, listen);
275 GET_WINSOCK_FUNCTION(winsock_module, send);
276 GET_WINSOCK_FUNCTION(winsock_module, ioctlsocket);
277 GET_WINSOCK_FUNCTION(winsock_module, accept);
278 GET_WINSOCK_FUNCTION(winsock_module, recv);
279 GET_WINSOCK_FUNCTION(winsock_module, WSAIoctl);
280 GET_WINSOCK_FUNCTION(winsock_module, getsockname);
282 /* Try to get the best WinSock version we can get */
283 if (!sk_startup(2,2) &&
284 !sk_startup(2,0) &&
285 !sk_startup(1,1)) {
286 fatalbox("Unable to initialise WinSock");
289 sktree = newtree234(cmpfortree);
292 void sk_cleanup(void)
294 Actual_Socket s;
295 int i;
297 if (sktree) {
298 for (i = 0; (s = index234(sktree, i)) != NULL; i++) {
299 p_closesocket(s->s);
301 freetree234(sktree);
302 sktree = NULL;
305 p_WSACleanup();
306 if (winsock_module)
307 FreeLibrary(winsock_module);
308 #ifndef NO_IPV6
309 if (wship6_module)
310 FreeLibrary(wship6_module);
311 #endif
314 char *winsock_error_string(int error)
316 switch (error) {
317 case WSAEACCES:
318 return "Network error: Permission denied";
319 case WSAEADDRINUSE:
320 return "Network error: Address already in use";
321 case WSAEADDRNOTAVAIL:
322 return "Network error: Cannot assign requested address";
323 case WSAEAFNOSUPPORT:
324 return
325 "Network error: Address family not supported by protocol family";
326 case WSAEALREADY:
327 return "Network error: Operation already in progress";
328 case WSAECONNABORTED:
329 return "Network error: Software caused connection abort";
330 case WSAECONNREFUSED:
331 return "Network error: Connection refused";
332 case WSAECONNRESET:
333 return "Network error: Connection reset by peer";
334 case WSAEDESTADDRREQ:
335 return "Network error: Destination address required";
336 case WSAEFAULT:
337 return "Network error: Bad address";
338 case WSAEHOSTDOWN:
339 return "Network error: Host is down";
340 case WSAEHOSTUNREACH:
341 return "Network error: No route to host";
342 case WSAEINPROGRESS:
343 return "Network error: Operation now in progress";
344 case WSAEINTR:
345 return "Network error: Interrupted function call";
346 case WSAEINVAL:
347 return "Network error: Invalid argument";
348 case WSAEISCONN:
349 return "Network error: Socket is already connected";
350 case WSAEMFILE:
351 return "Network error: Too many open files";
352 case WSAEMSGSIZE:
353 return "Network error: Message too long";
354 case WSAENETDOWN:
355 return "Network error: Network is down";
356 case WSAENETRESET:
357 return "Network error: Network dropped connection on reset";
358 case WSAENETUNREACH:
359 return "Network error: Network is unreachable";
360 case WSAENOBUFS:
361 return "Network error: No buffer space available";
362 case WSAENOPROTOOPT:
363 return "Network error: Bad protocol option";
364 case WSAENOTCONN:
365 return "Network error: Socket is not connected";
366 case WSAENOTSOCK:
367 return "Network error: Socket operation on non-socket";
368 case WSAEOPNOTSUPP:
369 return "Network error: Operation not supported";
370 case WSAEPFNOSUPPORT:
371 return "Network error: Protocol family not supported";
372 case WSAEPROCLIM:
373 return "Network error: Too many processes";
374 case WSAEPROTONOSUPPORT:
375 return "Network error: Protocol not supported";
376 case WSAEPROTOTYPE:
377 return "Network error: Protocol wrong type for socket";
378 case WSAESHUTDOWN:
379 return "Network error: Cannot send after socket shutdown";
380 case WSAESOCKTNOSUPPORT:
381 return "Network error: Socket type not supported";
382 case WSAETIMEDOUT:
383 return "Network error: Connection timed out";
384 case WSAEWOULDBLOCK:
385 return "Network error: Resource temporarily unavailable";
386 case WSAEDISCON:
387 return "Network error: Graceful shutdown in progress";
388 default:
389 return "Unknown network error";
393 SockAddr sk_namelookup(const char *host, char **canonicalname,
394 int address_family)
396 SockAddr ret = snew(struct SockAddr_tag);
397 unsigned long a;
398 struct hostent *h = NULL;
399 char realhost[8192];
400 int ret_family;
401 int err;
403 /* Clear the structure and default to IPv4. */
404 memset(ret, 0, sizeof(struct SockAddr_tag));
405 ret->family = (address_family == ADDRTYPE_IPV4 ? AF_INET :
406 #ifndef NO_IPV6
407 address_family == ADDRTYPE_IPV6 ? AF_INET6 :
408 #endif
409 AF_UNSPEC);
410 #ifndef NO_IPV6
411 ret->ai = ret->ais = NULL;
412 #endif
413 ret->addresses = NULL;
414 ret_family = AF_UNSPEC;
415 *realhost = '\0';
417 if ((a = p_inet_addr(host)) == (unsigned long) INADDR_NONE) {
418 #ifndef NO_IPV6
420 * Use getaddrinfo when it's available
422 if (p_getaddrinfo) {
423 struct addrinfo hints;
424 #ifdef NET_SETUP_DIAGNOSTICS
425 logevent(NULL, "Using getaddrinfo() for resolving");
426 #endif
427 memset(&hints, 0, sizeof(hints));
428 hints.ai_family = ret->family;
429 hints.ai_flags = AI_CANONNAME;
430 if ((err = p_getaddrinfo(host, NULL, &hints, &ret->ais)) == 0)
431 ret_family = ret->ais->ai_family;
432 ret->ai = ret->ais;
433 } else
434 #endif
436 #ifdef NET_SETUP_DIAGNOSTICS
437 logevent(NULL, "Using gethostbyname() for resolving");
438 #endif
440 * Otherwise use the IPv4-only gethostbyname...
441 * (NOTE: we don't use gethostbyname as a fallback!)
443 if ( (h = p_gethostbyname(host)) )
444 ret_family = AF_INET;
445 else
446 err = p_WSAGetLastError();
449 if (ret_family == AF_UNSPEC) {
450 ret->error = (err == WSAENETDOWN ? "Network is down" :
451 err == WSAHOST_NOT_FOUND ? "Host does not exist" :
452 err == WSATRY_AGAIN ? "Host not found" :
453 #ifndef NO_IPV6
454 p_getaddrinfo&&p_gai_strerror ? p_gai_strerror(err) :
455 #endif
456 "gethostbyname: unknown error");
457 } else {
458 ret->error = NULL;
459 ret->family = ret_family;
461 #ifndef NO_IPV6
462 /* If we got an address info use that... */
463 if (ret->ai) {
464 /* Are we in IPv4 fallback mode? */
465 /* We put the IPv4 address into the a variable so we can further-on use the IPv4 code... */
466 if (ret->family == AF_INET)
467 memcpy(&a,
468 (char *) &((SOCKADDR_IN *) ret->ai->
469 ai_addr)->sin_addr, sizeof(a));
471 if (ret->ai->ai_canonname)
472 strncpy(realhost, ret->ai->ai_canonname, lenof(realhost));
473 else
474 strncpy(realhost, host, lenof(realhost));
476 /* We used the IPv4-only gethostbyname()... */
477 else
478 #endif
480 int n;
481 for (n = 0; h->h_addr_list[n]; n++);
482 ret->addresses = snewn(n, unsigned long);
483 ret->naddresses = n;
484 for (n = 0; n < ret->naddresses; n++) {
485 memcpy(&a, h->h_addr_list[n], sizeof(a));
486 ret->addresses[n] = p_ntohl(a);
488 ret->curraddr = 0;
489 memcpy(&a, h->h_addr, sizeof(a));
490 /* This way we are always sure the h->h_name is valid :) */
491 strncpy(realhost, h->h_name, sizeof(realhost));
494 } else {
496 * This must be a numeric IPv4 address because it caused a
497 * success return from inet_addr.
499 ret->addresses = snewn(1, unsigned long);
500 ret->naddresses = 1;
501 ret->curraddr = 0;
502 ret->addresses[0] = p_ntohl(a);
503 ret->family = AF_INET;
504 strncpy(realhost, host, sizeof(realhost));
506 realhost[lenof(realhost)-1] = '\0';
507 *canonicalname = snewn(1+strlen(realhost), char);
508 strcpy(*canonicalname, realhost);
509 return ret;
512 SockAddr sk_nonamelookup(const char *host)
514 SockAddr ret = snew(struct SockAddr_tag);
515 ret->error = NULL;
516 ret->family = AF_UNSPEC;
517 #ifndef NO_IPV6
518 ret->ai = ret->ais = NULL;
519 #endif
520 ret->addresses = NULL;
521 ret->naddresses = 0;
522 strncpy(ret->hostname, host, lenof(ret->hostname));
523 ret->hostname[lenof(ret->hostname)-1] = '\0';
524 return ret;
527 int sk_nextaddr(SockAddr addr)
529 #ifndef NO_IPV6
530 if (addr->ai) {
531 if (addr->ai->ai_next) {
532 addr->ai = addr->ai->ai_next;
533 addr->family = addr->ai->ai_family;
534 return TRUE;
535 } else
536 return FALSE;
538 #endif
539 if (addr->curraddr+1 < addr->naddresses) {
540 addr->curraddr++;
541 return TRUE;
542 } else {
543 return FALSE;
547 void sk_getaddr(SockAddr addr, char *buf, int buflen)
549 #ifndef NO_IPV6
550 if (addr->ai) {
551 if (p_WSAAddressToStringA) {
552 p_WSAAddressToStringA(addr->ai->ai_addr, addr->ai->ai_addrlen,
553 NULL, buf, &buflen);
554 } else
555 strncpy(buf, "IPv6", buflen);
556 } else
557 #endif
558 if (addr->family == AF_INET) {
559 struct in_addr a;
560 assert(addr->addresses && addr->curraddr < addr->naddresses);
561 a.s_addr = p_htonl(addr->addresses[addr->curraddr]);
562 strncpy(buf, p_inet_ntoa(a), buflen);
563 buf[buflen-1] = '\0';
564 } else {
565 strncpy(buf, addr->hostname, buflen);
566 buf[buflen-1] = '\0';
570 int sk_hostname_is_local(char *name)
572 return !strcmp(name, "localhost");
575 static INTERFACE_INFO local_interfaces[16];
576 static int n_local_interfaces; /* 0=not yet, -1=failed, >0=number */
578 static int ipv4_is_local_addr(struct in_addr addr)
580 if (ipv4_is_loopback(addr))
581 return 1; /* loopback addresses are local */
582 if (!n_local_interfaces) {
583 SOCKET s = p_socket(AF_INET, SOCK_DGRAM, 0);
584 DWORD retbytes;
586 if (p_WSAIoctl &&
587 p_WSAIoctl(s, SIO_GET_INTERFACE_LIST, NULL, 0,
588 local_interfaces, sizeof(local_interfaces),
589 &retbytes, NULL, NULL) == 0)
590 n_local_interfaces = retbytes / sizeof(INTERFACE_INFO);
591 else
592 logevent(NULL, "Unable to get list of local IP addresses");
594 if (n_local_interfaces > 0) {
595 int i;
596 for (i = 0; i < n_local_interfaces; i++) {
597 SOCKADDR_IN *address =
598 (SOCKADDR_IN *)&local_interfaces[i].iiAddress;
599 if (address->sin_addr.s_addr == addr.s_addr)
600 return 1; /* this address is local */
603 return 0; /* this address is not local */
606 int sk_address_is_local(SockAddr addr)
608 #ifndef NO_IPV6
609 if (addr->family == AF_INET6) {
610 return IN6_IS_ADDR_LOOPBACK((const struct in6_addr *)addr->ai->ai_addr);
611 } else
612 #endif
613 if (addr->family == AF_INET) {
614 #ifndef NO_IPV6
615 if (addr->ai) {
616 return ipv4_is_local_addr(((struct sockaddr_in *)addr->ai->ai_addr)
617 ->sin_addr);
618 } else
619 #endif
621 struct in_addr a;
622 assert(addr->addresses && addr->curraddr < addr->naddresses);
623 a.s_addr = p_htonl(addr->addresses[addr->curraddr]);
624 return ipv4_is_local_addr(a);
626 } else {
627 assert(addr->family == AF_UNSPEC);
628 return 0; /* we don't know; assume not */
632 int sk_addrtype(SockAddr addr)
634 return (addr->family == AF_INET ? ADDRTYPE_IPV4 :
635 #ifndef NO_IPV6
636 addr->family == AF_INET6 ? ADDRTYPE_IPV6 :
637 #endif
638 ADDRTYPE_NAME);
641 void sk_addrcopy(SockAddr addr, char *buf)
643 assert(addr->family != AF_UNSPEC);
644 #ifndef NO_IPV6
645 if (addr->ai) {
646 if (addr->family == AF_INET)
647 memcpy(buf, &((struct sockaddr_in *)addr->ai->ai_addr)->sin_addr,
648 sizeof(struct in_addr));
649 else if (addr->family == AF_INET6)
650 memcpy(buf, &((struct sockaddr_in6 *)addr->ai->ai_addr)->sin6_addr,
651 sizeof(struct in6_addr));
652 else
653 assert(FALSE);
654 } else
655 #endif
656 if (addr->family == AF_INET) {
657 struct in_addr a;
658 assert(addr->addresses && addr->curraddr < addr->naddresses);
659 a.s_addr = p_htonl(addr->addresses[addr->curraddr]);
660 memcpy(buf, (char*) &a.s_addr, 4);
664 void sk_addr_free(SockAddr addr)
666 #ifndef NO_IPV6
667 if (addr->ais && p_freeaddrinfo)
668 p_freeaddrinfo(addr->ais);
669 #endif
670 if (addr->addresses)
671 sfree(addr->addresses);
672 sfree(addr);
675 static Plug sk_tcp_plug(Socket sock, Plug p)
677 Actual_Socket s = (Actual_Socket) sock;
678 Plug ret = s->plug;
679 if (p)
680 s->plug = p;
681 return ret;
684 static void sk_tcp_flush(Socket s)
687 * We send data to the socket as soon as we can anyway,
688 * so we don't need to do anything here. :-)
692 static void sk_tcp_close(Socket s);
693 static int sk_tcp_write(Socket s, const char *data, int len);
694 static int sk_tcp_write_oob(Socket s, const char *data, int len);
695 static void sk_tcp_set_private_ptr(Socket s, void *ptr);
696 static void *sk_tcp_get_private_ptr(Socket s);
697 static void sk_tcp_set_frozen(Socket s, int is_frozen);
698 static const char *sk_tcp_socket_error(Socket s);
700 extern char *do_select(SOCKET skt, int startup);
702 Socket sk_register(void *sock, Plug plug)
704 static const struct socket_function_table fn_table = {
705 sk_tcp_plug,
706 sk_tcp_close,
707 sk_tcp_write,
708 sk_tcp_write_oob,
709 sk_tcp_flush,
710 sk_tcp_set_private_ptr,
711 sk_tcp_get_private_ptr,
712 sk_tcp_set_frozen,
713 sk_tcp_socket_error
716 DWORD err;
717 char *errstr;
718 Actual_Socket ret;
721 * Create Socket structure.
723 ret = snew(struct Socket_tag);
724 ret->fn = &fn_table;
725 ret->error = NULL;
726 ret->plug = plug;
727 bufchain_init(&ret->output_data);
728 ret->writable = 1; /* to start with */
729 ret->sending_oob = 0;
730 ret->frozen = 1;
731 ret->frozen_readable = 0;
732 ret->localhost_only = 0; /* unused, but best init anyway */
733 ret->pending_error = 0;
734 ret->parent = ret->child = NULL;
735 ret->addr = NULL;
737 ret->s = (SOCKET)sock;
739 if (ret->s == INVALID_SOCKET) {
740 err = p_WSAGetLastError();
741 ret->error = winsock_error_string(err);
742 return (Socket) ret;
745 ret->oobinline = 0;
747 /* Set up a select mechanism. This could be an AsyncSelect on a
748 * window, or an EventSelect on an event object. */
749 errstr = do_select(ret->s, 1);
750 if (errstr) {
751 ret->error = errstr;
752 return (Socket) ret;
755 add234(sktree, ret);
757 return (Socket) ret;
760 static DWORD try_connect(Actual_Socket sock)
762 SOCKET s;
763 #ifndef NO_IPV6
764 SOCKADDR_IN6 a6;
765 #endif
766 SOCKADDR_IN a;
767 DWORD err;
768 char *errstr;
769 short localport;
770 int family;
772 if (sock->s != INVALID_SOCKET) {
773 do_select(sock->s, 0);
774 p_closesocket(sock->s);
777 plug_log(sock->plug, 0, sock->addr, sock->port, NULL, 0);
780 * Open socket.
782 #ifndef NO_IPV6
783 /* Let's default to IPv6, this shouldn't hurt anybody
784 * If the stack supports IPv6 it will also allow IPv4 connections. */
785 if (sock->addr->ai) {
786 family = sock->addr->ai->ai_family;
787 } else
788 #endif
790 /* Default to IPv4 */
791 family = AF_INET;
794 s = p_socket(family, SOCK_STREAM, 0);
795 sock->s = s;
797 if (s == INVALID_SOCKET) {
798 err = p_WSAGetLastError();
799 sock->error = winsock_error_string(err);
800 goto ret;
803 if (sock->oobinline) {
804 BOOL b = TRUE;
805 p_setsockopt(s, SOL_SOCKET, SO_OOBINLINE, (void *) &b, sizeof(b));
808 if (sock->nodelay) {
809 BOOL b = TRUE;
810 p_setsockopt(s, IPPROTO_TCP, TCP_NODELAY, (void *) &b, sizeof(b));
813 if (sock->keepalive) {
814 BOOL b = TRUE;
815 p_setsockopt(s, SOL_SOCKET, SO_KEEPALIVE, (void *) &b, sizeof(b));
819 * Bind to local address.
821 if (sock->privport)
822 localport = 1023; /* count from 1023 downwards */
823 else
824 localport = 0; /* just use port 0 (ie winsock picks) */
826 /* Loop round trying to bind */
827 while (1) {
828 int sockcode;
830 #ifndef NO_IPV6
831 if (family == AF_INET6) {
832 memset(&a6, 0, sizeof(a6));
833 a6.sin6_family = AF_INET6;
834 /*a6.sin6_addr = in6addr_any; */ /* == 0 done by memset() */
835 a6.sin6_port = p_htons(localport);
836 } else
837 #endif
839 a.sin_family = AF_INET;
840 a.sin_addr.s_addr = p_htonl(INADDR_ANY);
841 a.sin_port = p_htons(localport);
843 #ifndef NO_IPV6
844 sockcode = p_bind(s, (sock->addr->family == AF_INET6 ?
845 (struct sockaddr *) &a6 :
846 (struct sockaddr *) &a),
847 (sock->addr->family ==
848 AF_INET6 ? sizeof(a6) : sizeof(a)));
849 #else
850 sockcode = p_bind(s, (struct sockaddr *) &a, sizeof(a));
851 #endif
852 if (sockcode != SOCKET_ERROR) {
853 err = 0;
854 break; /* done */
855 } else {
856 err = p_WSAGetLastError();
857 if (err != WSAEADDRINUSE) /* failed, for a bad reason */
858 break;
861 if (localport == 0)
862 break; /* we're only looping once */
863 localport--;
864 if (localport == 0)
865 break; /* we might have got to the end */
868 if (err) {
869 sock->error = winsock_error_string(err);
870 goto ret;
874 * Connect to remote address.
876 #ifndef NO_IPV6
877 if (sock->addr->ai) {
878 if (family == AF_INET6) {
879 a6.sin6_family = AF_INET6;
880 a6.sin6_port = p_htons((short) sock->port);
881 a6.sin6_addr =
882 ((struct sockaddr_in6 *) sock->addr->ai->ai_addr)->sin6_addr;
883 a6.sin6_flowinfo = ((struct sockaddr_in6 *) sock->addr->ai->ai_addr)->sin6_flowinfo;
884 a6.sin6_scope_id = ((struct sockaddr_in6 *) sock->addr->ai->ai_addr)->sin6_scope_id;
885 } else {
886 a.sin_family = AF_INET;
887 a.sin_addr =
888 ((struct sockaddr_in *) sock->addr->ai->ai_addr)->sin_addr;
889 a.sin_port = p_htons((short) sock->port);
891 } else
892 #endif
894 assert(sock->addr->addresses && sock->addr->curraddr < sock->addr->naddresses);
895 a.sin_family = AF_INET;
896 a.sin_addr.s_addr = p_htonl(sock->addr->addresses[sock->addr->curraddr]);
897 a.sin_port = p_htons((short) sock->port);
900 /* Set up a select mechanism. This could be an AsyncSelect on a
901 * window, or an EventSelect on an event object. */
902 errstr = do_select(s, 1);
903 if (errstr) {
904 sock->error = errstr;
905 err = 1;
906 goto ret;
909 if ((
910 #ifndef NO_IPV6
911 p_connect(s,
912 ((family == AF_INET6) ? (struct sockaddr *) &a6 :
913 (struct sockaddr *) &a),
914 (family == AF_INET6) ? sizeof(a6) : sizeof(a))
915 #else
916 p_connect(s, (struct sockaddr *) &a, sizeof(a))
917 #endif
918 ) == SOCKET_ERROR) {
919 err = p_WSAGetLastError();
921 * We expect a potential EWOULDBLOCK here, because the
922 * chances are the front end has done a select for
923 * FD_CONNECT, so that connect() will complete
924 * asynchronously.
926 if ( err != WSAEWOULDBLOCK ) {
927 sock->error = winsock_error_string(err);
928 goto ret;
930 } else {
932 * If we _don't_ get EWOULDBLOCK, the connect has completed
933 * and we should set the socket as writable.
935 sock->writable = 1;
938 add234(sktree, sock);
940 err = 0;
942 ret:
943 if (err)
944 plug_log(sock->plug, 1, sock->addr, sock->port, sock->error, err);
945 return err;
948 Socket sk_new(SockAddr addr, int port, int privport, int oobinline,
949 int nodelay, int keepalive, Plug plug)
951 static const struct socket_function_table fn_table = {
952 sk_tcp_plug,
953 sk_tcp_close,
954 sk_tcp_write,
955 sk_tcp_write_oob,
956 sk_tcp_flush,
957 sk_tcp_set_private_ptr,
958 sk_tcp_get_private_ptr,
959 sk_tcp_set_frozen,
960 sk_tcp_socket_error
963 Actual_Socket ret;
964 DWORD err;
967 * Create Socket structure.
969 ret = snew(struct Socket_tag);
970 ret->fn = &fn_table;
971 ret->error = NULL;
972 ret->plug = plug;
973 bufchain_init(&ret->output_data);
974 ret->connected = 0; /* to start with */
975 ret->writable = 0; /* to start with */
976 ret->sending_oob = 0;
977 ret->frozen = 0;
978 ret->frozen_readable = 0;
979 ret->localhost_only = 0; /* unused, but best init anyway */
980 ret->pending_error = 0;
981 ret->parent = ret->child = NULL;
982 ret->oobinline = oobinline;
983 ret->nodelay = nodelay;
984 ret->keepalive = keepalive;
985 ret->privport = privport;
986 ret->port = port;
987 ret->addr = addr;
988 ret->s = INVALID_SOCKET;
990 err = 0;
991 do {
992 err = try_connect(ret);
993 } while (err && sk_nextaddr(ret->addr));
995 return (Socket) ret;
998 Socket sk_newlistener(char *srcaddr, int port, Plug plug, int local_host_only,
999 int orig_address_family)
1001 static const struct socket_function_table fn_table = {
1002 sk_tcp_plug,
1003 sk_tcp_close,
1004 sk_tcp_write,
1005 sk_tcp_write_oob,
1006 sk_tcp_flush,
1007 sk_tcp_set_private_ptr,
1008 sk_tcp_get_private_ptr,
1009 sk_tcp_set_frozen,
1010 sk_tcp_socket_error
1013 SOCKET s;
1014 #ifndef NO_IPV6
1015 SOCKADDR_IN6 a6;
1016 #endif
1017 SOCKADDR_IN a;
1019 DWORD err;
1020 char *errstr;
1021 Actual_Socket ret;
1022 int retcode;
1023 int on = 1;
1025 int address_family;
1028 * Create Socket structure.
1030 ret = snew(struct Socket_tag);
1031 ret->fn = &fn_table;
1032 ret->error = NULL;
1033 ret->plug = plug;
1034 bufchain_init(&ret->output_data);
1035 ret->writable = 0; /* to start with */
1036 ret->sending_oob = 0;
1037 ret->frozen = 0;
1038 ret->frozen_readable = 0;
1039 ret->localhost_only = local_host_only;
1040 ret->pending_error = 0;
1041 ret->parent = ret->child = NULL;
1042 ret->addr = NULL;
1045 * Translate address_family from platform-independent constants
1046 * into local reality.
1048 address_family = (orig_address_family == ADDRTYPE_IPV4 ? AF_INET :
1049 #ifndef NO_IPV6
1050 orig_address_family == ADDRTYPE_IPV6 ? AF_INET6 :
1051 #endif
1052 AF_UNSPEC);
1055 * Our default, if passed the `don't care' value
1056 * ADDRTYPE_UNSPEC, is to listen on IPv4. If IPv6 is supported,
1057 * we will also set up a second socket listening on IPv6, but
1058 * the v4 one is primary since that ought to work even on
1059 * non-v6-supporting systems.
1061 if (address_family == AF_UNSPEC) address_family = AF_INET;
1064 * Open socket.
1066 s = p_socket(address_family, SOCK_STREAM, 0);
1067 ret->s = s;
1069 if (s == INVALID_SOCKET) {
1070 err = p_WSAGetLastError();
1071 ret->error = winsock_error_string(err);
1072 return (Socket) ret;
1075 ret->oobinline = 0;
1077 p_setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (const char *)&on, sizeof(on));
1079 #ifndef NO_IPV6
1080 if (address_family == AF_INET6) {
1081 memset(&a6, 0, sizeof(a6));
1082 a6.sin6_family = AF_INET6;
1083 /* FIXME: srcaddr is ignored for IPv6, because I (SGT) don't
1084 * know how to do it. :-)
1085 * (jeroen:) saddr is specified as an address.. eg 2001:db8::1
1086 * Thus we need either a parser that understands [2001:db8::1]:80
1087 * style addresses and/or enhance this to understand hostnames too. */
1088 if (local_host_only)
1089 a6.sin6_addr = in6addr_loopback;
1090 else
1091 a6.sin6_addr = in6addr_any;
1092 a6.sin6_port = p_htons(port);
1093 } else
1094 #endif
1096 int got_addr = 0;
1097 a.sin_family = AF_INET;
1100 * Bind to source address. First try an explicitly
1101 * specified one...
1103 if (srcaddr) {
1104 a.sin_addr.s_addr = p_inet_addr(srcaddr);
1105 if (a.sin_addr.s_addr != INADDR_NONE) {
1106 /* Override localhost_only with specified listen addr. */
1107 ret->localhost_only = ipv4_is_loopback(a.sin_addr);
1108 got_addr = 1;
1113 * ... and failing that, go with one of the standard ones.
1115 if (!got_addr) {
1116 if (local_host_only)
1117 a.sin_addr.s_addr = p_htonl(INADDR_LOOPBACK);
1118 else
1119 a.sin_addr.s_addr = p_htonl(INADDR_ANY);
1122 a.sin_port = p_htons((short)port);
1124 #ifndef NO_IPV6
1125 retcode = p_bind(s, (address_family == AF_INET6 ?
1126 (struct sockaddr *) &a6 :
1127 (struct sockaddr *) &a),
1128 (address_family ==
1129 AF_INET6 ? sizeof(a6) : sizeof(a)));
1130 #else
1131 retcode = p_bind(s, (struct sockaddr *) &a, sizeof(a));
1132 #endif
1133 if (retcode != SOCKET_ERROR) {
1134 err = 0;
1135 } else {
1136 err = p_WSAGetLastError();
1139 if (err) {
1140 p_closesocket(s);
1141 ret->error = winsock_error_string(err);
1142 return (Socket) ret;
1146 if (p_listen(s, SOMAXCONN) == SOCKET_ERROR) {
1147 p_closesocket(s);
1148 ret->error = winsock_error_string(err);
1149 return (Socket) ret;
1152 /* Set up a select mechanism. This could be an AsyncSelect on a
1153 * window, or an EventSelect on an event object. */
1154 errstr = do_select(s, 1);
1155 if (errstr) {
1156 p_closesocket(s);
1157 ret->error = errstr;
1158 return (Socket) ret;
1161 add234(sktree, ret);
1163 #ifndef NO_IPV6
1165 * If we were given ADDRTYPE_UNSPEC, we must also create an
1166 * IPv6 listening socket and link it to this one.
1168 if (address_family == AF_INET && orig_address_family == ADDRTYPE_UNSPEC) {
1169 Actual_Socket other;
1171 other = (Actual_Socket) sk_newlistener(srcaddr, port, plug,
1172 local_host_only, ADDRTYPE_IPV6);
1174 if (other) {
1175 if (!other->error) {
1176 other->parent = ret;
1177 ret->child = other;
1178 } else {
1179 sfree(other);
1183 #endif
1185 return (Socket) ret;
1188 int sk_getport(Socket sock)
1190 /* I won't even try to get IPv6 working here since it is apparently borken
1191 * in this release of PuTTY */
1192 SOCKADDR_IN a;
1193 socklen_t salen;
1194 int retcode;
1195 Actual_Socket s = (Actual_Socket)sock;
1197 salen = sizeof(a);
1198 retcode = p_getsockname(s->s, (struct sockaddr *) &a, &salen);
1200 if (retcode != 0)
1201 return -1;
1203 return p_ntohs(a.sin_port);
1206 static void sk_tcp_close(Socket sock)
1208 extern char *do_select(SOCKET skt, int startup);
1209 Actual_Socket s = (Actual_Socket) sock;
1211 if (s->child)
1212 sk_tcp_close((Socket)s->child);
1214 del234(sktree, s);
1215 do_select(s->s, 0);
1216 p_closesocket(s->s);
1217 if (s->addr)
1218 sk_addr_free(s->addr);
1219 sfree(s);
1223 * The function which tries to send on a socket once it's deemed
1224 * writable.
1226 void try_send(Actual_Socket s)
1228 while (s->sending_oob || bufchain_size(&s->output_data) > 0) {
1229 int nsent;
1230 DWORD err;
1231 void *data;
1232 int len, urgentflag;
1234 if (s->sending_oob) {
1235 urgentflag = MSG_OOB;
1236 len = s->sending_oob;
1237 data = &s->oobdata;
1238 } else {
1239 urgentflag = 0;
1240 bufchain_prefix(&s->output_data, &data, &len);
1242 nsent = p_send(s->s, data, len, urgentflag);
1243 if (nsent <= 0) {
1244 err = (nsent < 0 ? p_WSAGetLastError() : 0);
1245 if ((err < WSABASEERR && nsent < 0) || err == WSAEWOULDBLOCK) {
1247 * Perfectly normal: we've sent all we can for the moment.
1249 * (Some WinSock send() implementations can return
1250 * <0 but leave no sensible error indication -
1251 * WSAGetLastError() is called but returns zero or
1252 * a small number - so we check that case and treat
1253 * it just like WSAEWOULDBLOCK.)
1255 s->writable = FALSE;
1256 return;
1257 } else if (nsent == 0 ||
1258 err == WSAECONNABORTED || err == WSAECONNRESET) {
1260 * If send() returns CONNABORTED or CONNRESET, we
1261 * unfortunately can't just call plug_closing(),
1262 * because it's quite likely that we're currently
1263 * _in_ a call from the code we'd be calling back
1264 * to, so we'd have to make half the SSH code
1265 * reentrant. Instead we flag a pending error on
1266 * the socket, to be dealt with (by calling
1267 * plug_closing()) at some suitable future moment.
1269 s->pending_error = err;
1270 return;
1271 } else {
1272 /* We're inside the Windows frontend here, so we know
1273 * that the frontend handle is unnecessary. */
1274 logevent(NULL, winsock_error_string(err));
1275 fatalbox("%s", winsock_error_string(err));
1277 } else {
1278 if (s->sending_oob) {
1279 if (nsent < len) {
1280 memmove(s->oobdata, s->oobdata+nsent, len-nsent);
1281 s->sending_oob = len - nsent;
1282 } else {
1283 s->sending_oob = 0;
1285 } else {
1286 bufchain_consume(&s->output_data, nsent);
1292 static int sk_tcp_write(Socket sock, const char *buf, int len)
1294 Actual_Socket s = (Actual_Socket) sock;
1297 * Add the data to the buffer list on the socket.
1299 bufchain_add(&s->output_data, buf, len);
1302 * Now try sending from the start of the buffer list.
1304 if (s->writable)
1305 try_send(s);
1307 return bufchain_size(&s->output_data);
1310 static int sk_tcp_write_oob(Socket sock, const char *buf, int len)
1312 Actual_Socket s = (Actual_Socket) sock;
1315 * Replace the buffer list on the socket with the data.
1317 bufchain_clear(&s->output_data);
1318 assert(len <= sizeof(s->oobdata));
1319 memcpy(s->oobdata, buf, len);
1320 s->sending_oob = len;
1323 * Now try sending from the start of the buffer list.
1325 if (s->writable)
1326 try_send(s);
1328 return s->sending_oob;
1331 int select_result(WPARAM wParam, LPARAM lParam)
1333 int ret, open;
1334 DWORD err;
1335 char buf[20480]; /* nice big buffer for plenty of speed */
1336 Actual_Socket s;
1337 u_long atmark;
1339 /* wParam is the socket itself */
1341 if (wParam == 0)
1342 return 1; /* boggle */
1344 s = find234(sktree, (void *) wParam, cmpforsearch);
1345 if (!s)
1346 return 1; /* boggle */
1348 if ((err = WSAGETSELECTERROR(lParam)) != 0) {
1350 * An error has occurred on this socket. Pass it to the
1351 * plug.
1353 if (s->addr) {
1354 plug_log(s->plug, 1, s->addr, s->port,
1355 winsock_error_string(err), err);
1356 while (s->addr && sk_nextaddr(s->addr)) {
1357 err = try_connect(s);
1360 if (err != 0)
1361 return plug_closing(s->plug, winsock_error_string(err), err, 0);
1362 else
1363 return 1;
1366 switch (WSAGETSELECTEVENT(lParam)) {
1367 case FD_CONNECT:
1368 s->connected = s->writable = 1;
1370 * Once a socket is connected, we can stop falling
1371 * back through the candidate addresses to connect
1372 * to.
1374 if (s->addr) {
1375 sk_addr_free(s->addr);
1376 s->addr = NULL;
1378 break;
1379 case FD_READ:
1380 /* In the case the socket is still frozen, we don't even bother */
1381 if (s->frozen) {
1382 s->frozen_readable = 1;
1383 break;
1387 * We have received data on the socket. For an oobinline
1388 * socket, this might be data _before_ an urgent pointer,
1389 * in which case we send it to the back end with type==1
1390 * (data prior to urgent).
1392 if (s->oobinline) {
1393 atmark = 1;
1394 p_ioctlsocket(s->s, SIOCATMARK, &atmark);
1396 * Avoid checking the return value from ioctlsocket(),
1397 * on the grounds that some WinSock wrappers don't
1398 * support it. If it does nothing, we get atmark==1,
1399 * which is equivalent to `no OOB pending', so the
1400 * effect will be to non-OOB-ify any OOB data.
1402 } else
1403 atmark = 1;
1405 ret = p_recv(s->s, buf, sizeof(buf), 0);
1406 if (ret < 0) {
1407 err = p_WSAGetLastError();
1408 if (err == WSAEWOULDBLOCK) {
1409 break;
1412 if (ret < 0) {
1413 return plug_closing(s->plug, winsock_error_string(err), err,
1415 } else if (0 == ret) {
1416 return plug_closing(s->plug, NULL, 0, 0);
1417 } else {
1418 return plug_receive(s->plug, atmark ? 0 : 1, buf, ret);
1420 break;
1421 case FD_OOB:
1423 * This will only happen on a non-oobinline socket. It
1424 * indicates that we can immediately perform an OOB read
1425 * and get back OOB data, which we will send to the back
1426 * end with type==2 (urgent data).
1428 ret = p_recv(s->s, buf, sizeof(buf), MSG_OOB);
1429 if (ret <= 0) {
1430 char *str = (ret == 0 ? "Internal networking trouble" :
1431 winsock_error_string(p_WSAGetLastError()));
1432 /* We're inside the Windows frontend here, so we know
1433 * that the frontend handle is unnecessary. */
1434 logevent(NULL, str);
1435 fatalbox("%s", str);
1436 } else {
1437 return plug_receive(s->plug, 2, buf, ret);
1439 break;
1440 case FD_WRITE:
1442 int bufsize_before, bufsize_after;
1443 s->writable = 1;
1444 bufsize_before = s->sending_oob + bufchain_size(&s->output_data);
1445 try_send(s);
1446 bufsize_after = s->sending_oob + bufchain_size(&s->output_data);
1447 if (bufsize_after < bufsize_before)
1448 plug_sent(s->plug, bufsize_after);
1450 break;
1451 case FD_CLOSE:
1452 /* Signal a close on the socket. First read any outstanding data. */
1453 open = 1;
1454 do {
1455 ret = p_recv(s->s, buf, sizeof(buf), 0);
1456 if (ret < 0) {
1457 err = p_WSAGetLastError();
1458 if (err == WSAEWOULDBLOCK)
1459 break;
1460 return plug_closing(s->plug, winsock_error_string(err),
1461 err, 0);
1462 } else {
1463 if (ret)
1464 open &= plug_receive(s->plug, 0, buf, ret);
1465 else
1466 open &= plug_closing(s->plug, NULL, 0, 0);
1468 } while (ret > 0);
1469 return open;
1470 case FD_ACCEPT:
1472 #ifdef NO_IPV6
1473 struct sockaddr_in isa;
1474 #else
1475 struct sockaddr_storage isa;
1476 #endif
1477 int addrlen = sizeof(isa);
1478 SOCKET t; /* socket of connection */
1480 memset(&isa, 0, sizeof(isa));
1481 err = 0;
1482 t = p_accept(s->s,(struct sockaddr *)&isa,&addrlen);
1483 if (t == INVALID_SOCKET)
1485 err = p_WSAGetLastError();
1486 if (err == WSATRY_AGAIN)
1487 break;
1489 #ifndef NO_IPV6
1490 if (isa.ss_family == AF_INET &&
1491 s->localhost_only &&
1492 !ipv4_is_local_addr(((struct sockaddr_in *)&isa)->sin_addr))
1493 #else
1494 if (s->localhost_only && !ipv4_is_local_addr(isa.sin_addr))
1495 #endif
1497 p_closesocket(t); /* dodgy WinSock let nonlocal through */
1498 } else if (plug_accepting(s->plug, (void*)t)) {
1499 p_closesocket(t); /* denied or error */
1504 return 1;
1508 * Deal with socket errors detected in try_send().
1510 void net_pending_errors(void)
1512 int i;
1513 Actual_Socket s;
1516 * This might be a fiddly business, because it's just possible
1517 * that handling a pending error on one socket might cause
1518 * others to be closed. (I can't think of any reason this might
1519 * happen in current SSH implementation, but to maintain
1520 * generality of this network layer I'll assume the worst.)
1522 * So what we'll do is search the socket list for _one_ socket
1523 * with a pending error, and then handle it, and then search
1524 * the list again _from the beginning_. Repeat until we make a
1525 * pass with no socket errors present. That way we are
1526 * protected against the socket list changing under our feet.
1529 do {
1530 for (i = 0; (s = index234(sktree, i)) != NULL; i++) {
1531 if (s->pending_error) {
1533 * An error has occurred on this socket. Pass it to the
1534 * plug.
1536 plug_closing(s->plug,
1537 winsock_error_string(s->pending_error),
1538 s->pending_error, 0);
1539 break;
1542 } while (s);
1546 * Each socket abstraction contains a `void *' private field in
1547 * which the client can keep state.
1549 static void sk_tcp_set_private_ptr(Socket sock, void *ptr)
1551 Actual_Socket s = (Actual_Socket) sock;
1552 s->private_ptr = ptr;
1555 static void *sk_tcp_get_private_ptr(Socket sock)
1557 Actual_Socket s = (Actual_Socket) sock;
1558 return s->private_ptr;
1562 * Special error values are returned from sk_namelookup and sk_new
1563 * if there's a problem. These functions extract an error message,
1564 * or return NULL if there's no problem.
1566 const char *sk_addr_error(SockAddr addr)
1568 return addr->error;
1570 static const char *sk_tcp_socket_error(Socket sock)
1572 Actual_Socket s = (Actual_Socket) sock;
1573 return s->error;
1576 static void sk_tcp_set_frozen(Socket sock, int is_frozen)
1578 Actual_Socket s = (Actual_Socket) sock;
1579 if (s->frozen == is_frozen)
1580 return;
1581 s->frozen = is_frozen;
1582 if (!is_frozen) {
1583 do_select(s->s, 1);
1584 if (s->frozen_readable) {
1585 char c;
1586 p_recv(s->s, &c, 1, MSG_PEEK);
1589 s->frozen_readable = 0;
1592 void socket_reselect_all(void)
1594 Actual_Socket s;
1595 int i;
1597 for (i = 0; (s = index234(sktree, i)) != NULL; i++) {
1598 if (!s->frozen)
1599 do_select(s->s, 1);
1604 * For Plink: enumerate all sockets currently active.
1606 SOCKET first_socket(int *state)
1608 Actual_Socket s;
1609 *state = 0;
1610 s = index234(sktree, (*state)++);
1611 return s ? s->s : INVALID_SOCKET;
1614 SOCKET next_socket(int *state)
1616 Actual_Socket s = index234(sktree, (*state)++);
1617 return s ? s->s : INVALID_SOCKET;
1620 extern int socket_writable(SOCKET skt)
1622 Actual_Socket s = find234(sktree, (void *)skt, cmpforsearch);
1624 if (s)
1625 return bufchain_size(&s->output_data) > 0;
1626 else
1627 return 0;
1630 int net_service_lookup(char *service)
1632 struct servent *se;
1633 se = p_getservbyname(service, NULL);
1634 if (se != NULL)
1635 return p_ntohs(se->s_port);
1636 else
1637 return 0;
1640 SockAddr platform_get_x11_unix_address(int displaynum, char **canonicalname)
1642 SockAddr ret = snew(struct SockAddr_tag);
1643 memset(ret, 0, sizeof(struct SockAddr_tag));
1644 ret->error = "unix sockets not supported on this platform";
1645 return ret;