2 * Windows networking abstraction.
4 * For the IPv6 code in here I am indebted to Jeroen Massar and
12 #define DEFINE_PLUG_METHOD_MACROS
20 const struct in6_addr in6addr_any
= IN6ADDR_ANY_INIT
;
21 const struct in6_addr in6addr_loopback
= IN6ADDR_LOOPBACK_INIT
;
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
;
38 const struct socket_function_table
*fn
;
39 /* the above variable absolutely *must* be the first in this structure */
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 */
53 int oobinline
, nodelay
, keepalive
, privport
;
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
63 Actual_Socket parent
, child
;
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.
81 struct addrinfo
*ais
; /* Addresses IPv6 style. */
82 struct addrinfo
*ai
; /* steps along the linked list */
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
;
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
;
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
,
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
*));
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
,
177 static HMODULE winsock_module
= NULL
;
178 static WSADATA wsadata
;
180 static HMODULE winsock2_module
= NULL
;
181 static HMODULE wship6_module
= NULL
;
184 int sk_startup(int hi
, int lo
)
188 winsock_ver
= MAKEWORD(hi
, lo
);
190 if (p_WSAStartup(winsock_ver
, &wsadata
)) {
194 if (LOBYTE(wsadata
.wVersion
) != LOBYTE(winsock_ver
)) {
198 #ifdef NET_SETUP_DIAGNOSTICS
201 sprintf(buf
, "Using WinSock %d.%d", hi
, lo
);
213 winsock_module
= LoadLibrary("WS2_32.DLL");
214 if (!winsock_module
) {
215 winsock_module
= LoadLibrary("WSOCK32.DLL");
218 fatalbox("Unable to load any WinSock library");
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");
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
);
231 /* Fall back to wship6.dll for Windows 2000 */
232 wship6_module
= LoadLibrary("wship6.dll");
234 #ifdef NET_SETUP_DIAGNOSTICS
235 logevent(NULL
, "WSH IPv6 support detected");
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
);
242 #ifdef NET_SETUP_DIAGNOSTICS
243 logevent(NULL
, "No IPv6 support detected");
247 GET_WINSOCK_FUNCTION(winsock2_module
, WSAAddressToStringA
);
249 #ifdef NET_SETUP_DIAGNOSTICS
250 logevent(NULL
, "PuTTY was built without IPv6 support");
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) &&
286 fatalbox("Unable to initialise WinSock");
289 sktree
= newtree234(cmpfortree
);
292 void sk_cleanup(void)
298 for (i
= 0; (s
= index234(sktree
, i
)) != NULL
; i
++) {
307 FreeLibrary(winsock_module
);
310 FreeLibrary(wship6_module
);
314 char *winsock_error_string(int error
)
318 return "Network error: Permission denied";
320 return "Network error: Address already in use";
321 case WSAEADDRNOTAVAIL
:
322 return "Network error: Cannot assign requested address";
323 case WSAEAFNOSUPPORT
:
325 "Network error: Address family not supported by protocol family";
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";
333 return "Network error: Connection reset by peer";
334 case WSAEDESTADDRREQ
:
335 return "Network error: Destination address required";
337 return "Network error: Bad address";
339 return "Network error: Host is down";
340 case WSAEHOSTUNREACH
:
341 return "Network error: No route to host";
343 return "Network error: Operation now in progress";
345 return "Network error: Interrupted function call";
347 return "Network error: Invalid argument";
349 return "Network error: Socket is already connected";
351 return "Network error: Too many open files";
353 return "Network error: Message too long";
355 return "Network error: Network is down";
357 return "Network error: Network dropped connection on reset";
359 return "Network error: Network is unreachable";
361 return "Network error: No buffer space available";
363 return "Network error: Bad protocol option";
365 return "Network error: Socket is not connected";
367 return "Network error: Socket operation on non-socket";
369 return "Network error: Operation not supported";
370 case WSAEPFNOSUPPORT
:
371 return "Network error: Protocol family not supported";
373 return "Network error: Too many processes";
374 case WSAEPROTONOSUPPORT
:
375 return "Network error: Protocol not supported";
377 return "Network error: Protocol wrong type for socket";
379 return "Network error: Cannot send after socket shutdown";
380 case WSAESOCKTNOSUPPORT
:
381 return "Network error: Socket type not supported";
383 return "Network error: Connection timed out";
385 return "Network error: Resource temporarily unavailable";
387 return "Network error: Graceful shutdown in progress";
389 return "Unknown network error";
393 SockAddr
sk_namelookup(const char *host
, char **canonicalname
,
396 SockAddr ret
= snew(struct SockAddr_tag
);
398 struct hostent
*h
= NULL
;
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
:
407 address_family
== ADDRTYPE_IPV6
? AF_INET6
:
411 ret
->ai
= ret
->ais
= NULL
;
413 ret
->addresses
= NULL
;
414 ret_family
= AF_UNSPEC
;
417 if ((a
= p_inet_addr(host
)) == (unsigned long) INADDR_NONE
) {
420 * Use getaddrinfo when it's available
423 struct addrinfo hints
;
424 #ifdef NET_SETUP_DIAGNOSTICS
425 logevent(NULL
, "Using getaddrinfo() for resolving");
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
;
436 #ifdef NET_SETUP_DIAGNOSTICS
437 logevent(NULL
, "Using gethostbyname() for resolving");
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
;
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" :
454 p_getaddrinfo
&&p_gai_strerror
? p_gai_strerror(err
) :
456 "gethostbyname: unknown error");
459 ret
->family
= ret_family
;
462 /* If we got an address info use that... */
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
)
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
));
474 strncpy(realhost
, host
, lenof(realhost
));
476 /* We used the IPv4-only gethostbyname()... */
481 for (n
= 0; h
->h_addr_list
[n
]; n
++);
482 ret
->addresses
= snewn(n
, unsigned long);
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
);
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
));
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);
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
);
512 SockAddr
sk_nonamelookup(const char *host
)
514 SockAddr ret
= snew(struct SockAddr_tag
);
516 ret
->family
= AF_UNSPEC
;
518 ret
->ai
= ret
->ais
= NULL
;
520 ret
->addresses
= NULL
;
522 strncpy(ret
->hostname
, host
, lenof(ret
->hostname
));
523 ret
->hostname
[lenof(ret
->hostname
)-1] = '\0';
527 int sk_nextaddr(SockAddr addr
)
531 if (addr
->ai
->ai_next
) {
532 addr
->ai
= addr
->ai
->ai_next
;
533 addr
->family
= addr
->ai
->ai_family
;
539 if (addr
->curraddr
+1 < addr
->naddresses
) {
547 void sk_getaddr(SockAddr addr
, char *buf
, int buflen
)
551 if (p_WSAAddressToStringA
) {
552 p_WSAAddressToStringA(addr
->ai
->ai_addr
, addr
->ai
->ai_addrlen
,
555 strncpy(buf
, "IPv6", buflen
);
558 if (addr
->family
== AF_INET
) {
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';
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);
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
);
592 logevent(NULL
, "Unable to get list of local IP addresses");
594 if (n_local_interfaces
> 0) {
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
)
609 if (addr
->family
== AF_INET6
) {
610 return IN6_IS_ADDR_LOOPBACK((const struct in6_addr
*)addr
->ai
->ai_addr
);
613 if (addr
->family
== AF_INET
) {
616 return ipv4_is_local_addr(((struct sockaddr_in
*)addr
->ai
->ai_addr
)
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
);
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
:
636 addr
->family
== AF_INET6
? ADDRTYPE_IPV6
:
641 void sk_addrcopy(SockAddr addr
, char *buf
)
643 assert(addr
->family
!= AF_UNSPEC
);
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
));
656 if (addr
->family
== AF_INET
) {
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
)
667 if (addr
->ais
&& p_freeaddrinfo
)
668 p_freeaddrinfo(addr
->ais
);
671 sfree(addr
->addresses
);
675 static Plug
sk_tcp_plug(Socket sock
, Plug p
)
677 Actual_Socket s
= (Actual_Socket
) sock
;
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
= {
710 sk_tcp_set_private_ptr
,
711 sk_tcp_get_private_ptr
,
721 * Create Socket structure.
723 ret
= snew(struct Socket_tag
);
727 bufchain_init(&ret
->output_data
);
728 ret
->writable
= 1; /* to start with */
729 ret
->sending_oob
= 0;
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
;
737 ret
->s
= (SOCKET
)sock
;
739 if (ret
->s
== INVALID_SOCKET
) {
740 err
= p_WSAGetLastError();
741 ret
->error
= winsock_error_string(err
);
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);
760 static DWORD
try_connect(Actual_Socket sock
)
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);
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
;
790 /* Default to IPv4 */
794 s
= p_socket(family
, SOCK_STREAM
, 0);
797 if (s
== INVALID_SOCKET
) {
798 err
= p_WSAGetLastError();
799 sock
->error
= winsock_error_string(err
);
803 if (sock
->oobinline
) {
805 p_setsockopt(s
, SOL_SOCKET
, SO_OOBINLINE
, (void *) &b
, sizeof(b
));
810 p_setsockopt(s
, IPPROTO_TCP
, TCP_NODELAY
, (void *) &b
, sizeof(b
));
813 if (sock
->keepalive
) {
815 p_setsockopt(s
, SOL_SOCKET
, SO_KEEPALIVE
, (void *) &b
, sizeof(b
));
819 * Bind to local address.
822 localport
= 1023; /* count from 1023 downwards */
824 localport
= 0; /* just use port 0 (ie winsock picks) */
826 /* Loop round trying to bind */
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
);
839 a
.sin_family
= AF_INET
;
840 a
.sin_addr
.s_addr
= p_htonl(INADDR_ANY
);
841 a
.sin_port
= p_htons(localport
);
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
)));
850 sockcode
= p_bind(s
, (struct sockaddr
*) &a
, sizeof(a
));
852 if (sockcode
!= SOCKET_ERROR
) {
856 err
= p_WSAGetLastError();
857 if (err
!= WSAEADDRINUSE
) /* failed, for a bad reason */
862 break; /* we're only looping once */
865 break; /* we might have got to the end */
869 sock
->error
= winsock_error_string(err
);
874 * Connect to remote address.
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
);
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
;
886 a
.sin_family
= AF_INET
;
888 ((struct sockaddr_in
*) sock
->addr
->ai
->ai_addr
)->sin_addr
;
889 a
.sin_port
= p_htons((short) sock
->port
);
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);
904 sock
->error
= errstr
;
912 ((family
== AF_INET6
) ? (struct sockaddr
*) &a6
:
913 (struct sockaddr
*) &a
),
914 (family
== AF_INET6
) ? sizeof(a6
) : sizeof(a
))
916 p_connect(s
, (struct sockaddr
*) &a
, sizeof(a
))
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
926 if ( err
!= WSAEWOULDBLOCK
) {
927 sock
->error
= winsock_error_string(err
);
932 * If we _don't_ get EWOULDBLOCK, the connect has completed
933 * and we should set the socket as writable.
938 add234(sktree
, sock
);
944 plug_log(sock
->plug
, 1, sock
->addr
, sock
->port
, sock
->error
, 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
= {
957 sk_tcp_set_private_ptr
,
958 sk_tcp_get_private_ptr
,
967 * Create Socket structure.
969 ret
= snew(struct Socket_tag
);
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;
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
;
988 ret
->s
= INVALID_SOCKET
;
992 err
= try_connect(ret
);
993 } while (err
&& sk_nextaddr(ret
->addr
));
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
= {
1007 sk_tcp_set_private_ptr
,
1008 sk_tcp_get_private_ptr
,
1028 * Create Socket structure.
1030 ret
= snew(struct Socket_tag
);
1031 ret
->fn
= &fn_table
;
1034 bufchain_init(&ret
->output_data
);
1035 ret
->writable
= 0; /* to start with */
1036 ret
->sending_oob
= 0;
1038 ret
->frozen_readable
= 0;
1039 ret
->localhost_only
= local_host_only
;
1040 ret
->pending_error
= 0;
1041 ret
->parent
= ret
->child
= NULL
;
1045 * Translate address_family from platform-independent constants
1046 * into local reality.
1048 address_family
= (orig_address_family
== ADDRTYPE_IPV4
? AF_INET
:
1050 orig_address_family
== ADDRTYPE_IPV6
? AF_INET6
:
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
;
1066 s
= p_socket(address_family
, SOCK_STREAM
, 0);
1069 if (s
== INVALID_SOCKET
) {
1070 err
= p_WSAGetLastError();
1071 ret
->error
= winsock_error_string(err
);
1072 return (Socket
) ret
;
1077 p_setsockopt(s
, SOL_SOCKET
, SO_REUSEADDR
, (const char *)&on
, sizeof(on
));
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
;
1091 a6
.sin6_addr
= in6addr_any
;
1092 a6
.sin6_port
= p_htons(port
);
1097 a
.sin_family
= AF_INET
;
1100 * Bind to source address. First try an explicitly
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
);
1113 * ... and failing that, go with one of the standard ones.
1116 if (local_host_only
)
1117 a
.sin_addr
.s_addr
= p_htonl(INADDR_LOOPBACK
);
1119 a
.sin_addr
.s_addr
= p_htonl(INADDR_ANY
);
1122 a
.sin_port
= p_htons((short)port
);
1125 retcode
= p_bind(s
, (address_family
== AF_INET6
?
1126 (struct sockaddr
*) &a6
:
1127 (struct sockaddr
*) &a
),
1129 AF_INET6
? sizeof(a6
) : sizeof(a
)));
1131 retcode
= p_bind(s
, (struct sockaddr
*) &a
, sizeof(a
));
1133 if (retcode
!= SOCKET_ERROR
) {
1136 err
= p_WSAGetLastError();
1141 ret
->error
= winsock_error_string(err
);
1142 return (Socket
) ret
;
1146 if (p_listen(s
, SOMAXCONN
) == SOCKET_ERROR
) {
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);
1157 ret
->error
= errstr
;
1158 return (Socket
) ret
;
1161 add234(sktree
, ret
);
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
);
1175 if (!other
->error
) {
1176 other
->parent
= ret
;
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 */
1195 Actual_Socket s
= (Actual_Socket
)sock
;
1198 retcode
= p_getsockname(s
->s
, (struct sockaddr
*) &a
, &salen
);
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
;
1212 sk_tcp_close((Socket
)s
->child
);
1216 p_closesocket(s
->s
);
1218 sk_addr_free(s
->addr
);
1223 * The function which tries to send on a socket once it's deemed
1226 void try_send(Actual_Socket s
)
1228 while (s
->sending_oob
|| bufchain_size(&s
->output_data
) > 0) {
1232 int len
, urgentflag
;
1234 if (s
->sending_oob
) {
1235 urgentflag
= MSG_OOB
;
1236 len
= s
->sending_oob
;
1240 bufchain_prefix(&s
->output_data
, &data
, &len
);
1242 nsent
= p_send(s
->s
, data
, len
, urgentflag
);
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
;
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
;
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
));
1278 if (s
->sending_oob
) {
1280 memmove(s
->oobdata
, s
->oobdata
+nsent
, len
-nsent
);
1281 s
->sending_oob
= len
- nsent
;
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.
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.
1328 return s
->sending_oob
;
1331 int select_result(WPARAM wParam
, LPARAM lParam
)
1335 char buf
[20480]; /* nice big buffer for plenty of speed */
1339 /* wParam is the socket itself */
1342 return 1; /* boggle */
1344 s
= find234(sktree
, (void *) wParam
, cmpforsearch
);
1346 return 1; /* boggle */
1348 if ((err
= WSAGETSELECTERROR(lParam
)) != 0) {
1350 * An error has occurred on this socket. Pass it to the
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
);
1361 return plug_closing(s
->plug
, winsock_error_string(err
), err
, 0);
1366 switch (WSAGETSELECTEVENT(lParam
)) {
1368 s
->connected
= s
->writable
= 1;
1370 * Once a socket is connected, we can stop falling
1371 * back through the candidate addresses to connect
1375 sk_addr_free(s
->addr
);
1380 /* In the case the socket is still frozen, we don't even bother */
1382 s
->frozen_readable
= 1;
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).
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.
1405 ret
= p_recv(s
->s
, buf
, sizeof(buf
), 0);
1407 err
= p_WSAGetLastError();
1408 if (err
== WSAEWOULDBLOCK
) {
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);
1418 return plug_receive(s
->plug
, atmark
? 0 : 1, buf
, ret
);
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
);
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
);
1437 return plug_receive(s
->plug
, 2, buf
, ret
);
1442 int bufsize_before
, bufsize_after
;
1444 bufsize_before
= s
->sending_oob
+ bufchain_size(&s
->output_data
);
1446 bufsize_after
= s
->sending_oob
+ bufchain_size(&s
->output_data
);
1447 if (bufsize_after
< bufsize_before
)
1448 plug_sent(s
->plug
, bufsize_after
);
1452 /* Signal a close on the socket. First read any outstanding data. */
1455 ret
= p_recv(s
->s
, buf
, sizeof(buf
), 0);
1457 err
= p_WSAGetLastError();
1458 if (err
== WSAEWOULDBLOCK
)
1460 return plug_closing(s
->plug
, winsock_error_string(err
),
1464 open
&= plug_receive(s
->plug
, 0, buf
, ret
);
1466 open
&= plug_closing(s
->plug
, NULL
, 0, 0);
1473 struct sockaddr_in isa
;
1475 struct sockaddr_storage isa
;
1477 int addrlen
= sizeof(isa
);
1478 SOCKET t
; /* socket of connection */
1480 memset(&isa
, 0, sizeof(isa
));
1482 t
= p_accept(s
->s
,(struct sockaddr
*)&isa
,&addrlen
);
1483 if (t
== INVALID_SOCKET
)
1485 err
= p_WSAGetLastError();
1486 if (err
== WSATRY_AGAIN
)
1490 if (isa
.ss_family
== AF_INET
&&
1491 s
->localhost_only
&&
1492 !ipv4_is_local_addr(((struct sockaddr_in
*)&isa
)->sin_addr
))
1494 if (s
->localhost_only
&& !ipv4_is_local_addr(isa
.sin_addr
))
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 */
1508 * Deal with socket errors detected in try_send().
1510 void net_pending_errors(void)
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.
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
1536 plug_closing(s
->plug
,
1537 winsock_error_string(s
->pending_error
),
1538 s
->pending_error
, 0);
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
)
1570 static const char *sk_tcp_socket_error(Socket sock
)
1572 Actual_Socket s
= (Actual_Socket
) sock
;
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
)
1581 s
->frozen
= is_frozen
;
1584 if (s
->frozen_readable
) {
1586 p_recv(s
->s
, &c
, 1, MSG_PEEK
);
1589 s
->frozen_readable
= 0;
1592 void socket_reselect_all(void)
1597 for (i
= 0; (s
= index234(sktree
, i
)) != NULL
; i
++) {
1604 * For Plink: enumerate all sockets currently active.
1606 SOCKET
first_socket(int *state
)
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
);
1625 return bufchain_size(&s
->output_data
) > 0;
1630 int net_service_lookup(char *service
)
1633 se
= p_getservbyname(service
, NULL
);
1635 return p_ntohs(se
->s_port
);
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";