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
;
106 static int cmpforsearch(void *av
, void *bv
)
108 Actual_Socket b
= (Actual_Socket
) bv
;
109 unsigned long as
= (unsigned long) av
, bs
= (unsigned long) b
->s
;
118 #define DECL_WINSOCK_FUNCTION(linkage, rettype, name, params) \
119 typedef rettype (WINAPI *t_##name) params; \
120 linkage t_##name p_##name
121 #define GET_WINSOCK_FUNCTION(module, name) \
122 p_##name = module ? (t_##name) GetProcAddress(module, #name) : NULL
124 DECL_WINSOCK_FUNCTION(NOTHING
, int, WSAAsyncSelect
,
125 (SOCKET
, HWND
, u_int
, long));
126 DECL_WINSOCK_FUNCTION(NOTHING
, int, WSAEventSelect
, (SOCKET
, WSAEVENT
, long));
127 DECL_WINSOCK_FUNCTION(NOTHING
, int, select
,
128 (int, fd_set FAR
*, fd_set FAR
*,
129 fd_set FAR
*, const struct timeval FAR
*));
130 DECL_WINSOCK_FUNCTION(NOTHING
, int, WSAGetLastError
, (void));
131 DECL_WINSOCK_FUNCTION(NOTHING
, int, WSAEnumNetworkEvents
,
132 (SOCKET
, WSAEVENT
, LPWSANETWORKEVENTS
));
133 DECL_WINSOCK_FUNCTION(static, int, WSAStartup
, (WORD
, LPWSADATA
));
134 DECL_WINSOCK_FUNCTION(static, int, WSACleanup
, (void));
135 DECL_WINSOCK_FUNCTION(static, int, closesocket
, (SOCKET
));
136 DECL_WINSOCK_FUNCTION(static, u_long
, ntohl
, (u_long
));
137 DECL_WINSOCK_FUNCTION(static, u_long
, htonl
, (u_long
));
138 DECL_WINSOCK_FUNCTION(static, u_short
, htons
, (u_short
));
139 DECL_WINSOCK_FUNCTION(static, u_short
, ntohs
, (u_short
));
140 DECL_WINSOCK_FUNCTION(static, struct hostent FAR
*, gethostbyname
,
142 DECL_WINSOCK_FUNCTION(static, struct servent FAR
*, getservbyname
,
143 (const char FAR
*, const char FAR
*));
144 DECL_WINSOCK_FUNCTION(static, unsigned long, inet_addr
, (const char FAR
*));
145 DECL_WINSOCK_FUNCTION(static, char FAR
*, inet_ntoa
, (struct in_addr
));
146 DECL_WINSOCK_FUNCTION(static, int, connect
,
147 (SOCKET
, const struct sockaddr FAR
*, int));
148 DECL_WINSOCK_FUNCTION(static, int, bind
,
149 (SOCKET
, const struct sockaddr FAR
*, int));
150 DECL_WINSOCK_FUNCTION(static, int, setsockopt
,
151 (SOCKET
, int, int, const char FAR
*, int));
152 DECL_WINSOCK_FUNCTION(static, SOCKET
, socket
, (int, int, int));
153 DECL_WINSOCK_FUNCTION(static, int, listen
, (SOCKET
, int));
154 DECL_WINSOCK_FUNCTION(static, int, send
, (SOCKET
, const char FAR
*, int, int));
155 DECL_WINSOCK_FUNCTION(static, int, ioctlsocket
,
156 (SOCKET
, long, u_long FAR
*));
157 DECL_WINSOCK_FUNCTION(static, SOCKET
, accept
,
158 (SOCKET
, struct sockaddr FAR
*, int FAR
*));
159 DECL_WINSOCK_FUNCTION(static, int, recv
, (SOCKET
, char FAR
*, int, int));
160 DECL_WINSOCK_FUNCTION(static, int, WSAIoctl
,
161 (SOCKET
, DWORD
, LPVOID
, DWORD
, LPVOID
, DWORD
,
162 LPDWORD
, LPWSAOVERLAPPED
,
163 LPWSAOVERLAPPED_COMPLETION_ROUTINE
));
165 DECL_WINSOCK_FUNCTION(static, int, getaddrinfo
,
166 (const char *nodename
, const char *servname
,
167 const struct addrinfo
*hints
, struct addrinfo
**res
));
168 DECL_WINSOCK_FUNCTION(static, void, freeaddrinfo
, (struct addrinfo
*res
));
169 DECL_WINSOCK_FUNCTION(static, int, getnameinfo
,
170 (const struct sockaddr FAR
* sa
, socklen_t salen
,
171 char FAR
* host
, size_t hostlen
, char FAR
* serv
,
172 size_t servlen
, int flags
));
173 DECL_WINSOCK_FUNCTION(static, char *, gai_strerror
, (int ecode
));
174 DECL_WINSOCK_FUNCTION(static, int, WSAAddressToStringA
,
175 (LPSOCKADDR
, DWORD
, LPWSAPROTOCOL_INFO
,
179 static HMODULE winsock_module
= NULL
;
180 static WSADATA wsadata
;
182 static HMODULE winsock2_module
= NULL
;
183 static HMODULE wship6_module
= NULL
;
186 int sk_startup(int hi
, int lo
)
190 winsock_ver
= MAKEWORD(hi
, lo
);
192 if (p_WSAStartup(winsock_ver
, &wsadata
)) {
196 if (LOBYTE(wsadata
.wVersion
) != LOBYTE(winsock_ver
)) {
200 #ifdef NET_SETUP_DIAGNOSTICS
203 sprintf(buf
, "Using WinSock %d.%d", hi
, lo
);
215 winsock_module
= LoadLibrary("WS2_32.DLL");
216 if (!winsock_module
) {
217 winsock_module
= LoadLibrary("WSOCK32.DLL");
220 fatalbox("Unable to load any WinSock library");
223 /* Check if we have getaddrinfo in Winsock */
224 if (GetProcAddress(winsock_module
, "getaddrinfo") != NULL
) {
225 #ifdef NET_SETUP_DIAGNOSTICS
226 logevent(NULL
, "Native WinSock IPv6 support detected");
228 GET_WINSOCK_FUNCTION(winsock_module
, getaddrinfo
);
229 GET_WINSOCK_FUNCTION(winsock_module
, freeaddrinfo
);
230 GET_WINSOCK_FUNCTION(winsock_module
, getnameinfo
);
231 GET_WINSOCK_FUNCTION(winsock_module
, gai_strerror
);
233 /* Fall back to wship6.dll for Windows 2000 */
234 wship6_module
= LoadLibrary("wship6.dll");
236 #ifdef NET_SETUP_DIAGNOSTICS
237 logevent(NULL
, "WSH IPv6 support detected");
239 GET_WINSOCK_FUNCTION(wship6_module
, getaddrinfo
);
240 GET_WINSOCK_FUNCTION(wship6_module
, freeaddrinfo
);
241 GET_WINSOCK_FUNCTION(wship6_module
, getnameinfo
);
242 GET_WINSOCK_FUNCTION(wship6_module
, gai_strerror
);
244 #ifdef NET_SETUP_DIAGNOSTICS
245 logevent(NULL
, "No IPv6 support detected");
249 GET_WINSOCK_FUNCTION(winsock2_module
, WSAAddressToStringA
);
251 #ifdef NET_SETUP_DIAGNOSTICS
252 logevent(NULL
, "PuTTY was built without IPv6 support");
256 GET_WINSOCK_FUNCTION(winsock_module
, WSAAsyncSelect
);
257 GET_WINSOCK_FUNCTION(winsock_module
, WSAEventSelect
);
258 GET_WINSOCK_FUNCTION(winsock_module
, select
);
259 GET_WINSOCK_FUNCTION(winsock_module
, WSAGetLastError
);
260 GET_WINSOCK_FUNCTION(winsock_module
, WSAEnumNetworkEvents
);
261 GET_WINSOCK_FUNCTION(winsock_module
, WSAStartup
);
262 GET_WINSOCK_FUNCTION(winsock_module
, WSACleanup
);
263 GET_WINSOCK_FUNCTION(winsock_module
, closesocket
);
264 GET_WINSOCK_FUNCTION(winsock_module
, ntohl
);
265 GET_WINSOCK_FUNCTION(winsock_module
, htonl
);
266 GET_WINSOCK_FUNCTION(winsock_module
, htons
);
267 GET_WINSOCK_FUNCTION(winsock_module
, ntohs
);
268 GET_WINSOCK_FUNCTION(winsock_module
, gethostbyname
);
269 GET_WINSOCK_FUNCTION(winsock_module
, getservbyname
);
270 GET_WINSOCK_FUNCTION(winsock_module
, inet_addr
);
271 GET_WINSOCK_FUNCTION(winsock_module
, inet_ntoa
);
272 GET_WINSOCK_FUNCTION(winsock_module
, connect
);
273 GET_WINSOCK_FUNCTION(winsock_module
, bind
);
274 GET_WINSOCK_FUNCTION(winsock_module
, setsockopt
);
275 GET_WINSOCK_FUNCTION(winsock_module
, socket
);
276 GET_WINSOCK_FUNCTION(winsock_module
, listen
);
277 GET_WINSOCK_FUNCTION(winsock_module
, send
);
278 GET_WINSOCK_FUNCTION(winsock_module
, ioctlsocket
);
279 GET_WINSOCK_FUNCTION(winsock_module
, accept
);
280 GET_WINSOCK_FUNCTION(winsock_module
, recv
);
281 GET_WINSOCK_FUNCTION(winsock_module
, WSAIoctl
);
283 /* Try to get the best WinSock version we can get */
284 if (!sk_startup(2,2) &&
287 fatalbox("Unable to initialise WinSock");
290 sktree
= newtree234(cmpfortree
);
293 void sk_cleanup(void)
299 for (i
= 0; (s
= index234(sktree
, i
)) != NULL
; i
++) {
308 FreeLibrary(winsock_module
);
311 FreeLibrary(wship6_module
);
315 char *winsock_error_string(int error
)
319 return "Network error: Permission denied";
321 return "Network error: Address already in use";
322 case WSAEADDRNOTAVAIL
:
323 return "Network error: Cannot assign requested address";
324 case WSAEAFNOSUPPORT
:
326 "Network error: Address family not supported by protocol family";
328 return "Network error: Operation already in progress";
329 case WSAECONNABORTED
:
330 return "Network error: Software caused connection abort";
331 case WSAECONNREFUSED
:
332 return "Network error: Connection refused";
334 return "Network error: Connection reset by peer";
335 case WSAEDESTADDRREQ
:
336 return "Network error: Destination address required";
338 return "Network error: Bad address";
340 return "Network error: Host is down";
341 case WSAEHOSTUNREACH
:
342 return "Network error: No route to host";
344 return "Network error: Operation now in progress";
346 return "Network error: Interrupted function call";
348 return "Network error: Invalid argument";
350 return "Network error: Socket is already connected";
352 return "Network error: Too many open files";
354 return "Network error: Message too long";
356 return "Network error: Network is down";
358 return "Network error: Network dropped connection on reset";
360 return "Network error: Network is unreachable";
362 return "Network error: No buffer space available";
364 return "Network error: Bad protocol option";
366 return "Network error: Socket is not connected";
368 return "Network error: Socket operation on non-socket";
370 return "Network error: Operation not supported";
371 case WSAEPFNOSUPPORT
:
372 return "Network error: Protocol family not supported";
374 return "Network error: Too many processes";
375 case WSAEPROTONOSUPPORT
:
376 return "Network error: Protocol not supported";
378 return "Network error: Protocol wrong type for socket";
380 return "Network error: Cannot send after socket shutdown";
381 case WSAESOCKTNOSUPPORT
:
382 return "Network error: Socket type not supported";
384 return "Network error: Connection timed out";
386 return "Network error: Resource temporarily unavailable";
388 return "Network error: Graceful shutdown in progress";
390 return "Unknown network error";
394 SockAddr
sk_namelookup(const char *host
, char **canonicalname
,
397 SockAddr ret
= snew(struct SockAddr_tag
);
399 struct hostent
*h
= NULL
;
404 /* Clear the structure and default to IPv4. */
405 memset(ret
, 0, sizeof(struct SockAddr_tag
));
406 ret
->family
= (address_family
== ADDRTYPE_IPV4 ? AF_INET
:
408 address_family
== ADDRTYPE_IPV6 ? AF_INET6
:
412 ret
->ai
= ret
->ais
= NULL
;
414 ret
->addresses
= NULL
;
415 ret_family
= AF_UNSPEC
;
418 if ((a
= p_inet_addr(host
)) == (unsigned long) INADDR_NONE
) {
421 * Use getaddrinfo when it's available
424 struct addrinfo hints
;
425 #ifdef NET_SETUP_DIAGNOSTICS
426 logevent(NULL
, "Using getaddrinfo() for resolving");
428 memset(&hints
, 0, sizeof(hints
));
429 hints
.ai_family
= ret
->family
;
430 hints
.ai_flags
= AI_CANONNAME
;
431 if ((err
= p_getaddrinfo(host
, NULL
, &hints
, &ret
->ais
)) == 0)
432 ret_family
= ret
->ais
->ai_family
;
437 #ifdef NET_SETUP_DIAGNOSTICS
438 logevent(NULL
, "Using gethostbyname() for resolving");
441 * Otherwise use the IPv4-only gethostbyname...
442 * (NOTE: we don't use gethostbyname as a fallback!)
444 if ( (h
= p_gethostbyname(host
)) )
445 ret_family
= AF_INET
;
447 err
= p_WSAGetLastError();
450 if (ret_family
== AF_UNSPEC
) {
451 ret
->error
= (err
== WSAENETDOWN ?
"Network is down" :
452 err
== WSAHOST_NOT_FOUND ?
"Host does not exist" :
453 err
== WSATRY_AGAIN ?
"Host not found" :
455 p_getaddrinfo
&&p_gai_strerror ?
p_gai_strerror(err
) :
457 "gethostbyname: unknown error");
460 ret
->family
= ret_family
;
463 /* If we got an address info use that... */
465 /* Are we in IPv4 fallback mode? */
466 /* We put the IPv4 address into the a variable so we can further-on use the IPv4 code... */
467 if (ret
->family
== AF_INET
)
469 (char *) &((SOCKADDR_IN
*) ret
->ai
->
470 ai_addr
)->sin_addr
, sizeof(a
));
472 if (ret
->ai
->ai_canonname
)
473 strncpy(realhost
, ret
->ai
->ai_canonname
, lenof(realhost
));
475 strncpy(realhost
, host
, lenof(realhost
));
477 /* We used the IPv4-only gethostbyname()... */
482 for (n
= 0; h
->h_addr_list
[n
]; n
++);
483 ret
->addresses
= snewn(n
, unsigned long);
485 for (n
= 0; n
< ret
->naddresses
; n
++) {
486 memcpy(&a
, h
->h_addr_list
[n
], sizeof(a
));
487 ret
->addresses
[n
] = p_ntohl(a
);
490 memcpy(&a
, h
->h_addr
, sizeof(a
));
491 /* This way we are always sure the h->h_name is valid :) */
492 strncpy(realhost
, h
->h_name
, sizeof(realhost
));
497 * This must be a numeric IPv4 address because it caused a
498 * success return from inet_addr.
500 ret
->addresses
= snewn(1, unsigned long);
503 ret
->addresses
[0] = p_ntohl(a
);
504 ret
->family
= AF_INET
;
505 strncpy(realhost
, host
, sizeof(realhost
));
507 realhost
[lenof(realhost
)-1] = '\0';
508 *canonicalname
= snewn(1+strlen(realhost
), char);
509 strcpy(*canonicalname
, realhost
);
513 SockAddr
sk_nonamelookup(const char *host
)
515 SockAddr ret
= snew(struct SockAddr_tag
);
517 ret
->family
= AF_UNSPEC
;
519 ret
->ai
= ret
->ais
= NULL
;
521 ret
->addresses
= NULL
;
523 strncpy(ret
->hostname
, host
, lenof(ret
->hostname
));
524 ret
->hostname
[lenof(ret
->hostname
)-1] = '\0';
528 int sk_nextaddr(SockAddr addr
)
532 if (addr
->ai
->ai_next
) {
533 addr
->ai
= addr
->ai
->ai_next
;
534 addr
->family
= addr
->ai
->ai_family
;
540 if (addr
->curraddr
+1 < addr
->naddresses
) {
548 void sk_getaddr(SockAddr addr
, char *buf
, int buflen
)
552 if (p_WSAAddressToStringA
) {
553 p_WSAAddressToStringA(addr
->ai
->ai_addr
, addr
->ai
->ai_addrlen
,
556 strncpy(buf
, "IPv6", buflen
);
559 if (addr
->family
== AF_INET
) {
561 assert(addr
->addresses
&& addr
->curraddr
< addr
->naddresses
);
562 a
.s_addr
= p_htonl(addr
->addresses
[addr
->curraddr
]);
563 strncpy(buf
, p_inet_ntoa(a
), buflen
);
564 buf
[buflen
-1] = '\0';
566 strncpy(buf
, addr
->hostname
, buflen
);
567 buf
[buflen
-1] = '\0';
571 int sk_hostname_is_local(char *name
)
573 return !strcmp(name
, "localhost");
576 static INTERFACE_INFO local_interfaces
[16];
577 static int n_local_interfaces
; /* 0=not yet, -1=failed, >0=number */
579 static int ipv4_is_local_addr(struct in_addr addr
)
581 if (ipv4_is_loopback(addr
))
582 return 1; /* loopback addresses are local */
583 if (!n_local_interfaces
) {
584 SOCKET s
= p_socket(AF_INET
, SOCK_DGRAM
, 0);
588 p_WSAIoctl(s
, SIO_GET_INTERFACE_LIST
, NULL
, 0,
589 local_interfaces
, sizeof(local_interfaces
),
590 &retbytes
, NULL
, NULL
) == 0)
591 n_local_interfaces
= retbytes
/ sizeof(INTERFACE_INFO
);
593 logevent(NULL
, "Unable to get list of local IP addresses");
595 if (n_local_interfaces
> 0) {
597 for (i
= 0; i
< n_local_interfaces
; i
++) {
598 SOCKADDR_IN
*address
=
599 (SOCKADDR_IN
*)&local_interfaces
[i
].iiAddress
;
600 if (address
->sin_addr
.s_addr
== addr
.s_addr
)
601 return 1; /* this address is local */
604 return 0; /* this address is not local */
607 int sk_address_is_local(SockAddr addr
)
610 if (addr
->family
== AF_INET6
) {
611 return IN6_IS_ADDR_LOOPBACK((const struct in6_addr
*)addr
->ai
->ai_addr
);
614 if (addr
->family
== AF_INET
) {
617 return ipv4_is_local_addr(((struct sockaddr_in
*)addr
->ai
->ai_addr
)
623 assert(addr
->addresses
&& addr
->curraddr
< addr
->naddresses
);
624 a
.s_addr
= p_htonl(addr
->addresses
[addr
->curraddr
]);
625 return ipv4_is_local_addr(a
);
628 assert(addr
->family
== AF_UNSPEC
);
629 return 0; /* we don't know; assume not */
633 int sk_addrtype(SockAddr addr
)
635 return (addr
->family
== AF_INET ? ADDRTYPE_IPV4
:
637 addr
->family
== AF_INET6 ? ADDRTYPE_IPV6
:
642 void sk_addrcopy(SockAddr addr
, char *buf
)
644 assert(addr
->family
!= AF_UNSPEC
);
647 if (addr
->family
== AF_INET
)
648 memcpy(buf
, &((struct sockaddr_in
*)addr
->ai
->ai_addr
)->sin_addr
,
649 sizeof(struct in_addr
));
650 else if (addr
->family
== AF_INET6
)
651 memcpy(buf
, &((struct sockaddr_in6
*)addr
->ai
->ai_addr
)->sin6_addr
,
652 sizeof(struct in6_addr
));
657 if (addr
->family
== AF_INET
) {
659 assert(addr
->addresses
&& addr
->curraddr
< addr
->naddresses
);
660 a
.s_addr
= p_htonl(addr
->addresses
[addr
->curraddr
]);
661 memcpy(buf
, (char*) &a
.s_addr
, 4);
665 void sk_addr_free(SockAddr addr
)
668 if (addr
->ais
&& p_freeaddrinfo
)
669 p_freeaddrinfo(addr
->ais
);
672 sfree(addr
->addresses
);
676 static Plug
sk_tcp_plug(Socket sock
, Plug p
)
678 Actual_Socket s
= (Actual_Socket
) sock
;
685 static void sk_tcp_flush(Socket s
)
688 * We send data to the socket as soon as we can anyway,
689 * so we don't need to do anything here. :-)
693 static void sk_tcp_close(Socket s
);
694 static int sk_tcp_write(Socket s
, const char *data
, int len
);
695 static int sk_tcp_write_oob(Socket s
, const char *data
, int len
);
696 static void sk_tcp_set_private_ptr(Socket s
, void *ptr
);
697 static void *sk_tcp_get_private_ptr(Socket s
);
698 static void sk_tcp_set_frozen(Socket s
, int is_frozen
);
699 static const char *sk_tcp_socket_error(Socket s
);
701 extern char *do_select(SOCKET skt
, int startup
);
703 Socket
sk_register(void *sock
, Plug plug
)
705 static const struct socket_function_table fn_table
= {
711 sk_tcp_set_private_ptr
,
712 sk_tcp_get_private_ptr
,
722 * Create Socket structure.
724 ret
= snew(struct Socket_tag
);
728 bufchain_init(&ret
->output_data
);
729 ret
->writable
= 1; /* to start with */
730 ret
->sending_oob
= 0;
732 ret
->frozen_readable
= 0;
733 ret
->localhost_only
= 0; /* unused, but best init anyway */
734 ret
->pending_error
= 0;
735 ret
->parent
= ret
->child
= NULL
;
738 ret
->s
= (SOCKET
)sock
;
740 if (ret
->s
== INVALID_SOCKET
) {
741 err
= p_WSAGetLastError();
742 ret
->error
= winsock_error_string(err
);
748 /* Set up a select mechanism. This could be an AsyncSelect on a
749 * window, or an EventSelect on an event object. */
750 errstr
= do_select(ret
->s
, 1);
761 static DWORD
try_connect(Actual_Socket sock
)
773 if (sock
->s
!= INVALID_SOCKET
) {
774 do_select(sock
->s
, 0);
775 p_closesocket(sock
->s
);
778 plug_log(sock
->plug
, 0, sock
->addr
, sock
->port
, NULL
, 0);
784 /* Let's default to IPv6, this shouldn't hurt anybody
785 * If the stack supports IPv6 it will also allow IPv4 connections. */
786 if (sock
->addr
->ai
) {
787 family
= sock
->addr
->ai
->ai_family
;
791 /* Default to IPv4 */
796 * Remove the socket from the tree before we overwrite its
797 * internal socket id, because that forms part of the tree's
798 * sorting criterion. We'll add it back before exiting this
799 * function, whether we changed anything or not.
801 del234(sktree
, sock
);
803 s
= p_socket(family
, SOCK_STREAM
, 0);
806 if (s
== INVALID_SOCKET
) {
807 err
= p_WSAGetLastError();
808 sock
->error
= winsock_error_string(err
);
812 if (sock
->oobinline
) {
814 p_setsockopt(s
, SOL_SOCKET
, SO_OOBINLINE
, (void *) &b
, sizeof(b
));
819 p_setsockopt(s
, IPPROTO_TCP
, TCP_NODELAY
, (void *) &b
, sizeof(b
));
822 if (sock
->keepalive
) {
824 p_setsockopt(s
, SOL_SOCKET
, SO_KEEPALIVE
, (void *) &b
, sizeof(b
));
828 * Bind to local address.
831 localport
= 1023; /* count from 1023 downwards */
833 localport
= 0; /* just use port 0 (ie winsock picks) */
835 /* Loop round trying to bind */
840 if (family
== AF_INET6
) {
841 memset(&a6
, 0, sizeof(a6
));
842 a6
.sin6_family
= AF_INET6
;
843 /*a6.sin6_addr = in6addr_any; */ /* == 0 done by memset() */
844 a6
.sin6_port
= p_htons(localport
);
848 a
.sin_family
= AF_INET
;
849 a
.sin_addr
.s_addr
= p_htonl(INADDR_ANY
);
850 a
.sin_port
= p_htons(localport
);
853 sockcode
= p_bind(s
, (sock
->addr
->family
== AF_INET6 ?
854 (struct sockaddr
*) &a6
:
855 (struct sockaddr
*) &a
),
856 (sock
->addr
->family
==
857 AF_INET6 ?
sizeof(a6
) : sizeof(a
)));
859 sockcode
= p_bind(s
, (struct sockaddr
*) &a
, sizeof(a
));
861 if (sockcode
!= SOCKET_ERROR
) {
865 err
= p_WSAGetLastError();
866 if (err
!= WSAEADDRINUSE
) /* failed, for a bad reason */
871 break; /* we're only looping once */
874 break; /* we might have got to the end */
878 sock
->error
= winsock_error_string(err
);
883 * Connect to remote address.
886 if (sock
->addr
->ai
) {
887 if (family
== AF_INET6
) {
888 a6
.sin6_family
= AF_INET6
;
889 a6
.sin6_port
= p_htons((short) sock
->port
);
891 ((struct sockaddr_in6
*) sock
->addr
->ai
->ai_addr
)->sin6_addr
;
892 a6
.sin6_flowinfo
= ((struct sockaddr_in6
*) sock
->addr
->ai
->ai_addr
)->sin6_flowinfo
;
893 a6
.sin6_scope_id
= ((struct sockaddr_in6
*) sock
->addr
->ai
->ai_addr
)->sin6_scope_id
;
895 a
.sin_family
= AF_INET
;
897 ((struct sockaddr_in
*) sock
->addr
->ai
->ai_addr
)->sin_addr
;
898 a
.sin_port
= p_htons((short) sock
->port
);
903 assert(sock
->addr
->addresses
&& sock
->addr
->curraddr
< sock
->addr
->naddresses
);
904 a
.sin_family
= AF_INET
;
905 a
.sin_addr
.s_addr
= p_htonl(sock
->addr
->addresses
[sock
->addr
->curraddr
]);
906 a
.sin_port
= p_htons((short) sock
->port
);
909 /* Set up a select mechanism. This could be an AsyncSelect on a
910 * window, or an EventSelect on an event object. */
911 errstr
= do_select(s
, 1);
913 sock
->error
= errstr
;
921 ((family
== AF_INET6
) ?
(struct sockaddr
*) &a6
:
922 (struct sockaddr
*) &a
),
923 (family
== AF_INET6
) ?
sizeof(a6
) : sizeof(a
))
925 p_connect(s
, (struct sockaddr
*) &a
, sizeof(a
))
928 err
= p_WSAGetLastError();
930 * We expect a potential EWOULDBLOCK here, because the
931 * chances are the front end has done a select for
932 * FD_CONNECT, so that connect() will complete
935 if ( err
!= WSAEWOULDBLOCK
) {
936 sock
->error
= winsock_error_string(err
);
941 * If we _don't_ get EWOULDBLOCK, the connect has completed
942 * and we should set the socket as writable.
952 * No matter what happened, put the socket back in the tree.
954 add234(sktree
, sock
);
957 plug_log(sock
->plug
, 1, sock
->addr
, sock
->port
, sock
->error
, err
);
961 Socket
sk_new(SockAddr addr
, int port
, int privport
, int oobinline
,
962 int nodelay
, int keepalive
, Plug plug
)
964 static const struct socket_function_table fn_table
= {
970 sk_tcp_set_private_ptr
,
971 sk_tcp_get_private_ptr
,
980 * Create Socket structure.
982 ret
= snew(struct Socket_tag
);
986 bufchain_init(&ret
->output_data
);
987 ret
->connected
= 0; /* to start with */
988 ret
->writable
= 0; /* to start with */
989 ret
->sending_oob
= 0;
991 ret
->frozen_readable
= 0;
992 ret
->localhost_only
= 0; /* unused, but best init anyway */
993 ret
->pending_error
= 0;
994 ret
->parent
= ret
->child
= NULL
;
995 ret
->oobinline
= oobinline
;
996 ret
->nodelay
= nodelay
;
997 ret
->keepalive
= keepalive
;
998 ret
->privport
= privport
;
1001 ret
->s
= INVALID_SOCKET
;
1005 err
= try_connect(ret
);
1006 } while (err
&& sk_nextaddr(ret
->addr
));
1008 return (Socket
) ret
;
1011 Socket
sk_newlistener(char *srcaddr
, int port
, Plug plug
, int local_host_only
,
1012 int orig_address_family
)
1014 static const struct socket_function_table fn_table
= {
1020 sk_tcp_set_private_ptr
,
1021 sk_tcp_get_private_ptr
,
1041 * Create Socket structure.
1043 ret
= snew(struct Socket_tag
);
1044 ret
->fn
= &fn_table
;
1047 bufchain_init(&ret
->output_data
);
1048 ret
->writable
= 0; /* to start with */
1049 ret
->sending_oob
= 0;
1051 ret
->frozen_readable
= 0;
1052 ret
->localhost_only
= local_host_only
;
1053 ret
->pending_error
= 0;
1054 ret
->parent
= ret
->child
= NULL
;
1058 * Translate address_family from platform-independent constants
1059 * into local reality.
1061 address_family
= (orig_address_family
== ADDRTYPE_IPV4 ? AF_INET
:
1063 orig_address_family
== ADDRTYPE_IPV6 ? AF_INET6
:
1068 * Our default, if passed the `don't care' value
1069 * ADDRTYPE_UNSPEC, is to listen on IPv4. If IPv6 is supported,
1070 * we will also set up a second socket listening on IPv6, but
1071 * the v4 one is primary since that ought to work even on
1072 * non-v6-supporting systems.
1074 if (address_family
== AF_UNSPEC
) address_family
= AF_INET
;
1079 s
= p_socket(address_family
, SOCK_STREAM
, 0);
1082 if (s
== INVALID_SOCKET
) {
1083 err
= p_WSAGetLastError();
1084 ret
->error
= winsock_error_string(err
);
1085 return (Socket
) ret
;
1090 p_setsockopt(s
, SOL_SOCKET
, SO_REUSEADDR
, (const char *)&on
, sizeof(on
));
1093 if (address_family
== AF_INET6
) {
1094 memset(&a6
, 0, sizeof(a6
));
1095 a6
.sin6_family
= AF_INET6
;
1096 /* FIXME: srcaddr is ignored for IPv6, because I (SGT) don't
1097 * know how to do it. :-)
1098 * (jeroen:) saddr is specified as an address.. eg 2001:db8::1
1099 * Thus we need either a parser that understands [2001:db8::1]:80
1100 * style addresses and/or enhance this to understand hostnames too. */
1101 if (local_host_only
)
1102 a6
.sin6_addr
= in6addr_loopback
;
1104 a6
.sin6_addr
= in6addr_any
;
1105 a6
.sin6_port
= p_htons(port
);
1110 a
.sin_family
= AF_INET
;
1113 * Bind to source address. First try an explicitly
1117 a
.sin_addr
.s_addr
= p_inet_addr(srcaddr
);
1118 if (a
.sin_addr
.s_addr
!= INADDR_NONE
) {
1119 /* Override localhost_only with specified listen addr. */
1120 ret
->localhost_only
= ipv4_is_loopback(a
.sin_addr
);
1126 * ... and failing that, go with one of the standard ones.
1129 if (local_host_only
)
1130 a
.sin_addr
.s_addr
= p_htonl(INADDR_LOOPBACK
);
1132 a
.sin_addr
.s_addr
= p_htonl(INADDR_ANY
);
1135 a
.sin_port
= p_htons((short)port
);
1138 retcode
= p_bind(s
, (address_family
== AF_INET6 ?
1139 (struct sockaddr
*) &a6
:
1140 (struct sockaddr
*) &a
),
1142 AF_INET6 ?
sizeof(a6
) : sizeof(a
)));
1144 retcode
= p_bind(s
, (struct sockaddr
*) &a
, sizeof(a
));
1146 if (retcode
!= SOCKET_ERROR
) {
1149 err
= p_WSAGetLastError();
1154 ret
->error
= winsock_error_string(err
);
1155 return (Socket
) ret
;
1159 if (p_listen(s
, SOMAXCONN
) == SOCKET_ERROR
) {
1161 ret
->error
= winsock_error_string(err
);
1162 return (Socket
) ret
;
1165 /* Set up a select mechanism. This could be an AsyncSelect on a
1166 * window, or an EventSelect on an event object. */
1167 errstr
= do_select(s
, 1);
1170 ret
->error
= errstr
;
1171 return (Socket
) ret
;
1174 add234(sktree
, ret
);
1178 * If we were given ADDRTYPE_UNSPEC, we must also create an
1179 * IPv6 listening socket and link it to this one.
1181 if (address_family
== AF_INET
&& orig_address_family
== ADDRTYPE_UNSPEC
) {
1182 Actual_Socket other
;
1184 other
= (Actual_Socket
) sk_newlistener(srcaddr
, port
, plug
,
1185 local_host_only
, ADDRTYPE_IPV6
);
1188 if (!other
->error
) {
1189 other
->parent
= ret
;
1198 return (Socket
) ret
;
1201 static void sk_tcp_close(Socket sock
)
1203 extern char *do_select(SOCKET skt
, int startup
);
1204 Actual_Socket s
= (Actual_Socket
) sock
;
1207 sk_tcp_close((Socket
)s
->child
);
1211 p_closesocket(s
->s
);
1213 sk_addr_free(s
->addr
);
1218 * The function which tries to send on a socket once it's deemed
1221 void try_send(Actual_Socket s
)
1223 while (s
->sending_oob
|| bufchain_size(&s
->output_data
) > 0) {
1227 int len
, urgentflag
;
1229 if (s
->sending_oob
) {
1230 urgentflag
= MSG_OOB
;
1231 len
= s
->sending_oob
;
1235 bufchain_prefix(&s
->output_data
, &data
, &len
);
1237 nsent
= p_send(s
->s
, data
, len
, urgentflag
);
1238 noise_ultralight(nsent
);
1240 err
= (nsent
< 0 ?
p_WSAGetLastError() : 0);
1241 if ((err
< WSABASEERR
&& nsent
< 0) || err
== WSAEWOULDBLOCK
) {
1243 * Perfectly normal: we've sent all we can for the moment.
1245 * (Some WinSock send() implementations can return
1246 * <0 but leave no sensible error indication -
1247 * WSAGetLastError() is called but returns zero or
1248 * a small number - so we check that case and treat
1249 * it just like WSAEWOULDBLOCK.)
1251 s
->writable
= FALSE
;
1253 } else if (nsent
== 0 ||
1254 err
== WSAECONNABORTED
|| err
== WSAECONNRESET
) {
1256 * If send() returns CONNABORTED or CONNRESET, we
1257 * unfortunately can't just call plug_closing(),
1258 * because it's quite likely that we're currently
1259 * _in_ a call from the code we'd be calling back
1260 * to, so we'd have to make half the SSH code
1261 * reentrant. Instead we flag a pending error on
1262 * the socket, to be dealt with (by calling
1263 * plug_closing()) at some suitable future moment.
1265 s
->pending_error
= err
;
1268 /* We're inside the Windows frontend here, so we know
1269 * that the frontend handle is unnecessary. */
1270 logevent(NULL
, winsock_error_string(err
));
1271 fatalbox("%s", winsock_error_string(err
));
1274 if (s
->sending_oob
) {
1276 memmove(s
->oobdata
, s
->oobdata
+nsent
, len
-nsent
);
1277 s
->sending_oob
= len
- nsent
;
1282 bufchain_consume(&s
->output_data
, nsent
);
1288 static int sk_tcp_write(Socket sock
, const char *buf
, int len
)
1290 Actual_Socket s
= (Actual_Socket
) sock
;
1293 * Add the data to the buffer list on the socket.
1295 bufchain_add(&s
->output_data
, buf
, len
);
1298 * Now try sending from the start of the buffer list.
1303 return bufchain_size(&s
->output_data
);
1306 static int sk_tcp_write_oob(Socket sock
, const char *buf
, int len
)
1308 Actual_Socket s
= (Actual_Socket
) sock
;
1311 * Replace the buffer list on the socket with the data.
1313 bufchain_clear(&s
->output_data
);
1314 assert(len
<= sizeof(s
->oobdata
));
1315 memcpy(s
->oobdata
, buf
, len
);
1316 s
->sending_oob
= len
;
1319 * Now try sending from the start of the buffer list.
1324 return s
->sending_oob
;
1327 int select_result(WPARAM wParam
, LPARAM lParam
)
1331 char buf
[20480]; /* nice big buffer for plenty of speed */
1335 /* wParam is the socket itself */
1338 return 1; /* boggle */
1340 s
= find234(sktree
, (void *) wParam
, cmpforsearch
);
1342 return 1; /* boggle */
1344 if ((err
= WSAGETSELECTERROR(lParam
)) != 0) {
1346 * An error has occurred on this socket. Pass it to the
1350 plug_log(s
->plug
, 1, s
->addr
, s
->port
,
1351 winsock_error_string(err
), err
);
1352 while (s
->addr
&& sk_nextaddr(s
->addr
)) {
1353 err
= try_connect(s
);
1357 return plug_closing(s
->plug
, winsock_error_string(err
), err
, 0);
1362 noise_ultralight(lParam
);
1364 switch (WSAGETSELECTEVENT(lParam
)) {
1366 s
->connected
= s
->writable
= 1;
1368 * Once a socket is connected, we can stop falling
1369 * back through the candidate addresses to connect
1373 sk_addr_free(s
->addr
);
1378 /* In the case the socket is still frozen, we don't even bother */
1380 s
->frozen_readable
= 1;
1385 * We have received data on the socket. For an oobinline
1386 * socket, this might be data _before_ an urgent pointer,
1387 * in which case we send it to the back end with type==1
1388 * (data prior to urgent).
1392 p_ioctlsocket(s
->s
, SIOCATMARK
, &atmark
);
1394 * Avoid checking the return value from ioctlsocket(),
1395 * on the grounds that some WinSock wrappers don't
1396 * support it. If it does nothing, we get atmark==1,
1397 * which is equivalent to `no OOB pending', so the
1398 * effect will be to non-OOB-ify any OOB data.
1403 ret
= p_recv(s
->s
, buf
, sizeof(buf
), 0);
1404 noise_ultralight(ret
);
1406 err
= p_WSAGetLastError();
1407 if (err
== WSAEWOULDBLOCK
) {
1412 return plug_closing(s
->plug
, winsock_error_string(err
), err
,
1414 } else if (0 == ret
) {
1415 return plug_closing(s
->plug
, NULL
, 0, 0);
1417 return plug_receive(s
->plug
, atmark ?
0 : 1, buf
, ret
);
1422 * This will only happen on a non-oobinline socket. It
1423 * indicates that we can immediately perform an OOB read
1424 * and get back OOB data, which we will send to the back
1425 * end with type==2 (urgent data).
1427 ret
= p_recv(s
->s
, buf
, sizeof(buf
), MSG_OOB
);
1428 noise_ultralight(ret
);
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";