2 * Windows networking abstraction.
4 * Due to this clean abstraction it was possible
5 * to easily implement IPv6 support :)
7 * IPv6 patch 1 (27 October 2000) Jeroen Massar <jeroen@unfix.org>
8 * - Preliminary hacked IPv6 support.
9 * - Connecting to IPv6 address (eg fec0:4242:4242:100:2d0:b7ff:fe8f:5d42) works.
10 * - Connecting to IPv6 hostname (eg heaven.ipv6.unfix.org) works.
11 * - Compiles as either IPv4 or IPv6.
13 * IPv6 patch 2 (29 October 2000) Jeroen Massar <jeroen@unfix.org>
14 * - When compiled as IPv6 it also allows connecting to IPv4 hosts.
15 * - Added some more documentation.
17 * IPv6 patch 3 (18 November 2000) Jeroen Massar <jeroen@unfix.org>
18 * - It now supports dynamically loading the IPv6 resolver dll's.
19 * This way we should be able to distribute one (1) binary
20 * which supports both IPv4 and IPv6.
21 * - getaddrinfo() and getnameinfo() are loaded dynamicaly if possible.
22 * - in6addr_any is defined in this file so we don't need to link to wship6.lib
23 * - The patch is now more unified so that we can still
24 * remove all IPv6 support by undef'ing IPV6.
25 * But where it fallsback to IPv4 it uses the IPv4 code which is already in place...
26 * - Canonical name resolving works.
28 * IPv6 patch 4 (07 January 2001) Jeroen Massar <jeroen@unfix.org>
29 * - patch against CVS of today, will be submitted to the bugs list
30 * as a 'cvs diff -u' on Simon's request...
35 * Define IPV6 to have IPv6 on-the-fly-loading support.
36 * This means that one doesn't have to have an IPv6 stack to use it.
37 * But if an IPv6 stack is found it is used with a fallback to IPv4.
45 #define DEFINE_PLUG_METHOD_MACROS
55 #define ipv4_is_loopback(addr) \
56 ((p_ntohl(addr.s_addr) & 0xFF000000L) == 0x7F000000L)
59 const struct socket_function_table
*fn
;
60 /* the above variable absolutely *must* be the first in this structure */
68 int frozen
; /* this causes readability notifications to be ignored */
69 int frozen_readable
; /* this means we missed at least one readability
70 * notification while we were frozen */
71 int localhost_only
; /* for listening sockets */
75 int pending_error
; /* in case send() returns error */
79 * We used to typedef struct Socket_tag *Socket.
81 * Since we have made the networking abstraction slightly more
82 * abstract, Socket no longer means a tcp socket (it could mean
83 * an ssl socket). So now we must use Actual_Socket when we know
84 * we are talking about a tcp socket.
86 typedef struct Socket_tag
*Actual_Socket
;
91 * Which address family this address belongs to. AF_INET for
92 * IPv4; AF_INET6 for IPv6; AF_UNSPEC indicates that name
93 * resolution has not been done and a simple host name is held
94 * in this SockAddr structure.
97 unsigned long address
; /* Address IPv4 style. */
99 struct addrinfo
*ai
; /* Address IPv6 style. */
101 char hostname
[512]; /* Store an unresolved host name. */
104 static tree234
*sktree
;
106 static int cmpfortree(void *av
, void *bv
)
108 Actual_Socket a
= (Actual_Socket
) av
, b
= (Actual_Socket
) bv
;
109 unsigned long as
= (unsigned long) a
->s
, bs
= (unsigned long) b
->s
;
117 static int cmpforsearch(void *av
, void *bv
)
119 Actual_Socket b
= (Actual_Socket
) bv
;
120 unsigned long as
= (unsigned long) av
, bs
= (unsigned long) b
->s
;
129 #define DECL_WINSOCK_FUNCTION(linkage, rettype, name, params) \
130 typedef rettype (WINAPI *t_##name) params; \
131 linkage t_##name p_##name
132 #define GET_WINSOCK_FUNCTION(name) \
133 p_##name = (t_##name) GetProcAddress(winsock_module, #name)
135 DECL_WINSOCK_FUNCTION(NOTHING
, int, WSAAsyncSelect
,
136 (SOCKET
, HWND
, u_int
, long));
137 DECL_WINSOCK_FUNCTION(NOTHING
, int, WSAEventSelect
, (SOCKET
, WSAEVENT
, long));
138 DECL_WINSOCK_FUNCTION(NOTHING
, int, select
,
139 (int, fd_set FAR
*, fd_set FAR
*,
140 fd_set FAR
*, const struct timeval FAR
*));
141 DECL_WINSOCK_FUNCTION(NOTHING
, int, WSAGetLastError
, (void));
142 DECL_WINSOCK_FUNCTION(NOTHING
, int, WSAEnumNetworkEvents
,
143 (SOCKET
, WSAEVENT
, LPWSANETWORKEVENTS
));
144 DECL_WINSOCK_FUNCTION(static, int, WSAStartup
, (WORD
, LPWSADATA
));
145 DECL_WINSOCK_FUNCTION(static, int, WSACleanup
, (void));
146 DECL_WINSOCK_FUNCTION(static, int, closesocket
, (SOCKET
));
147 DECL_WINSOCK_FUNCTION(static, u_long
, ntohl
, (u_long
));
148 DECL_WINSOCK_FUNCTION(static, u_long
, htonl
, (u_long
));
149 DECL_WINSOCK_FUNCTION(static, u_short
, htons
, (u_short
));
150 DECL_WINSOCK_FUNCTION(static, u_short
, ntohs
, (u_short
));
151 DECL_WINSOCK_FUNCTION(static, struct hostent FAR
*, gethostbyname
,
153 DECL_WINSOCK_FUNCTION(static, struct servent FAR
*, getservbyname
,
154 (const char FAR
*, const char FAR
*));
155 DECL_WINSOCK_FUNCTION(static, unsigned long, inet_addr
, (const char FAR
*));
156 DECL_WINSOCK_FUNCTION(static, char FAR
*, inet_ntoa
, (struct in_addr
));
157 DECL_WINSOCK_FUNCTION(static, int, connect
,
158 (SOCKET
, const struct sockaddr FAR
*, int));
159 DECL_WINSOCK_FUNCTION(static, int, bind
,
160 (SOCKET
, const struct sockaddr FAR
*, int));
161 DECL_WINSOCK_FUNCTION(static, int, setsockopt
,
162 (SOCKET
, int, int, const char FAR
*, int));
163 DECL_WINSOCK_FUNCTION(static, SOCKET
, socket
, (int, int, int));
164 DECL_WINSOCK_FUNCTION(static, int, listen
, (SOCKET
, int));
165 DECL_WINSOCK_FUNCTION(static, int, send
, (SOCKET
, const char FAR
*, int, int));
166 DECL_WINSOCK_FUNCTION(static, int, ioctlsocket
,
167 (SOCKET
, long, u_long FAR
*));
168 DECL_WINSOCK_FUNCTION(static, SOCKET
, accept
,
169 (SOCKET
, struct sockaddr FAR
*, int FAR
*));
170 DECL_WINSOCK_FUNCTION(static, int, recv
, (SOCKET
, char FAR
*, int, int));
171 DECL_WINSOCK_FUNCTION(static, int, WSAIoctl
,
172 (SOCKET
, DWORD
, LPVOID
, DWORD
, LPVOID
, DWORD
,
173 LPDWORD
, LPWSAOVERLAPPED
,
174 LPWSAOVERLAPPED_COMPLETION_ROUTINE
));
176 static HMODULE winsock_module
;
183 winsock_ver
= MAKEWORD(2, 0);
184 winsock_module
= LoadLibrary("WS2_32.DLL");
185 if (!winsock_module
) {
186 winsock_module
= LoadLibrary("WSOCK32.DLL");
187 winsock_ver
= MAKEWORD(1, 1);
190 fatalbox("Unable to load any WinSock library");
192 GET_WINSOCK_FUNCTION(WSAAsyncSelect
);
193 GET_WINSOCK_FUNCTION(WSAEventSelect
);
194 GET_WINSOCK_FUNCTION(select
);
195 GET_WINSOCK_FUNCTION(WSAGetLastError
);
196 GET_WINSOCK_FUNCTION(WSAEnumNetworkEvents
);
197 GET_WINSOCK_FUNCTION(WSAStartup
);
198 GET_WINSOCK_FUNCTION(WSACleanup
);
199 GET_WINSOCK_FUNCTION(closesocket
);
200 GET_WINSOCK_FUNCTION(ntohl
);
201 GET_WINSOCK_FUNCTION(htonl
);
202 GET_WINSOCK_FUNCTION(htons
);
203 GET_WINSOCK_FUNCTION(ntohs
);
204 GET_WINSOCK_FUNCTION(gethostbyname
);
205 GET_WINSOCK_FUNCTION(getservbyname
);
206 GET_WINSOCK_FUNCTION(inet_addr
);
207 GET_WINSOCK_FUNCTION(inet_ntoa
);
208 GET_WINSOCK_FUNCTION(connect
);
209 GET_WINSOCK_FUNCTION(bind
);
210 GET_WINSOCK_FUNCTION(setsockopt
);
211 GET_WINSOCK_FUNCTION(socket
);
212 GET_WINSOCK_FUNCTION(listen
);
213 GET_WINSOCK_FUNCTION(send
);
214 GET_WINSOCK_FUNCTION(ioctlsocket
);
215 GET_WINSOCK_FUNCTION(accept
);
216 GET_WINSOCK_FUNCTION(recv
);
217 GET_WINSOCK_FUNCTION(WSAIoctl
);
219 if (p_WSAStartup(winsock_ver
, &wsadata
)) {
220 fatalbox("Unable to initialise WinSock");
222 if (LOBYTE(wsadata
.wVersion
) != LOBYTE(winsock_ver
)) {
224 fatalbox("WinSock version is incompatible with %d.%d",
225 LOBYTE(winsock_ver
), HIBYTE(winsock_ver
));
228 sktree
= newtree234(cmpfortree
);
231 void sk_cleanup(void)
237 for (i
= 0; (s
= index234(sktree
, i
)) != NULL
; i
++) {
246 FreeLibrary(winsock_module
);
249 char *winsock_error_string(int error
)
253 return "Network error: Permission denied";
255 return "Network error: Address already in use";
256 case WSAEADDRNOTAVAIL
:
257 return "Network error: Cannot assign requested address";
258 case WSAEAFNOSUPPORT
:
260 "Network error: Address family not supported by protocol family";
262 return "Network error: Operation already in progress";
263 case WSAECONNABORTED
:
264 return "Network error: Software caused connection abort";
265 case WSAECONNREFUSED
:
266 return "Network error: Connection refused";
268 return "Network error: Connection reset by peer";
269 case WSAEDESTADDRREQ
:
270 return "Network error: Destination address required";
272 return "Network error: Bad address";
274 return "Network error: Host is down";
275 case WSAEHOSTUNREACH
:
276 return "Network error: No route to host";
278 return "Network error: Operation now in progress";
280 return "Network error: Interrupted function call";
282 return "Network error: Invalid argument";
284 return "Network error: Socket is already connected";
286 return "Network error: Too many open files";
288 return "Network error: Message too long";
290 return "Network error: Network is down";
292 return "Network error: Network dropped connection on reset";
294 return "Network error: Network is unreachable";
296 return "Network error: No buffer space available";
298 return "Network error: Bad protocol option";
300 return "Network error: Socket is not connected";
302 return "Network error: Socket operation on non-socket";
304 return "Network error: Operation not supported";
305 case WSAEPFNOSUPPORT
:
306 return "Network error: Protocol family not supported";
308 return "Network error: Too many processes";
309 case WSAEPROTONOSUPPORT
:
310 return "Network error: Protocol not supported";
312 return "Network error: Protocol wrong type for socket";
314 return "Network error: Cannot send after socket shutdown";
315 case WSAESOCKTNOSUPPORT
:
316 return "Network error: Socket type not supported";
318 return "Network error: Connection timed out";
320 return "Network error: Resource temporarily unavailable";
322 return "Network error: Graceful shutdown in progress";
324 return "Unknown network error";
328 SockAddr
sk_namelookup(const char *host
, char **canonicalname
)
330 SockAddr ret
= snew(struct SockAddr_tag
);
332 struct hostent
*h
= NULL
;
335 /* Clear the structure and default to IPv4. */
336 memset(ret
, 0, sizeof(struct SockAddr_tag
));
337 ret
->family
= 0; /* We set this one when we have resolved the host. */
340 if ((a
= p_inet_addr(host
)) == (unsigned long) INADDR_NONE
) {
343 /* Try to get the getaddrinfo() function from wship6.dll */
344 /* This way one doesn't need to have IPv6 dll's to use PuTTY and
345 * it will fallback to IPv4. */
346 typedef int (CALLBACK
* FGETADDRINFO
) (const char *nodename
,
347 const char *servname
,
348 const struct addrinfo
*
350 struct addrinfo
** res
);
351 FGETADDRINFO fGetAddrInfo
= NULL
;
353 HINSTANCE dllWSHIP6
= LoadLibrary("wship6.dll");
355 fGetAddrInfo
= (FGETADDRINFO
) GetProcAddress(dllWSHIP6
,
359 * Use fGetAddrInfo when it's available (which usually also
360 * means IPv6 is installed...)
363 /*debug(("Resolving \"%s\" with getaddrinfo() (IPv4+IPv6 capable)...\n", host)); */
364 if (fGetAddrInfo(host
, NULL
, NULL
, &ret
->ai
) == 0)
365 ret
->family
= ret
->ai
->ai_family
;
370 * Otherwise use the IPv4-only gethostbyname...
371 * (NOTE: we don't use gethostbyname as a
374 if (ret
->family
== 0) {
375 /*debug(("Resolving \"%s\" with gethostbyname() (IPv4 only)...\n", host)); */
376 if ( (h
= p_gethostbyname(host
)) )
377 ret
->family
= AF_INET
;
380 /*debug(("Done resolving...(family is %d) AF_INET = %d, AF_INET6 = %d\n", ret->family, AF_INET, AF_INET6)); */
382 if (ret
->family
== 0) {
383 DWORD err
= p_WSAGetLastError();
384 ret
->error
= (err
== WSAENETDOWN ?
"Network is down" :
386 WSAHOST_NOT_FOUND ?
"Host does not exist" : err
387 == WSATRY_AGAIN ?
"Host not found" :
389 fGetAddrInfo ?
"getaddrinfo: unknown error" :
391 "gethostbyname: unknown error");
395 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER
|
396 FORMAT_MESSAGE_FROM_SYSTEM
|
397 FORMAT_MESSAGE_IGNORE_INSERTS
, NULL
, err
,
398 MAKELANGID(LANG_NEUTRAL
, SUBLANG_DEFAULT
),
399 (LPTSTR
) & lpMsgBuf
, 0, NULL
);
400 /*debug(("Error %ld: %s (h=%lx)\n", err, lpMsgBuf, h)); */
401 /* Free the buffer. */
409 /* If we got an address info use that... */
411 typedef int (CALLBACK
* FGETNAMEINFO
)
412 (const struct sockaddr FAR
* sa
, socklen_t salen
,
413 char FAR
* host
, size_t hostlen
, char FAR
* serv
,
414 size_t servlen
, int flags
);
415 FGETNAMEINFO fGetNameInfo
= NULL
;
417 /* Are we in IPv4 fallback mode? */
418 /* We put the IPv4 address into the a variable so we can further-on use the IPv4 code... */
419 if (ret
->family
== AF_INET
)
421 (char *) &((SOCKADDR_IN
*) ret
->ai
->
422 ai_addr
)->sin_addr
, sizeof(a
));
424 /* Now let's find that canonicalname... */
427 (FGETNAMEINFO
) GetProcAddress(dllWSHIP6
,
430 ((struct sockaddr
*) ret
->ai
->ai_addr
,
432 AF_INET ?
sizeof(SOCKADDR_IN
) :
433 sizeof(SOCKADDR_IN6
), realhost
,
434 sizeof(realhost
), NULL
, 0, 0) != 0) {
435 strncpy(realhost
, host
, sizeof(realhost
));
439 /* We used the IPv4-only gethostbyname()... */
443 memcpy(&a
, h
->h_addr
, sizeof(a
));
444 /* This way we are always sure the h->h_name is valid :) */
445 strncpy(realhost
, h
->h_name
, sizeof(realhost
));
449 FreeLibrary(dllWSHIP6
);
453 * This must be a numeric IPv4 address because it caused a
454 * success return from inet_addr.
456 ret
->family
= AF_INET
;
457 strncpy(realhost
, host
, sizeof(realhost
));
459 ret
->address
= p_ntohl(a
);
460 realhost
[lenof(realhost
)-1] = '\0';
461 *canonicalname
= snewn(1+strlen(realhost
), char);
462 strcpy(*canonicalname
, realhost
);
466 SockAddr
sk_nonamelookup(const char *host
)
468 SockAddr ret
= snew(struct SockAddr_tag
);
470 ret
->family
= AF_UNSPEC
;
471 strncpy(ret
->hostname
, host
, lenof(ret
->hostname
));
472 ret
->hostname
[lenof(ret
->hostname
)-1] = '\0';
476 void sk_getaddr(SockAddr addr
, char *buf
, int buflen
)
479 if (addr
->family
== AF_INET6
) {
480 FIXME
; /* I don't know how to get a text form of an IPv6 address. */
483 if (addr
->family
== AF_INET
) {
485 a
.s_addr
= p_htonl(addr
->address
);
486 strncpy(buf
, p_inet_ntoa(a
), buflen
);
487 buf
[buflen
-1] = '\0';
489 assert(addr
->family
== AF_UNSPEC
);
490 strncpy(buf
, addr
->hostname
, buflen
);
491 buf
[buflen
-1] = '\0';
495 int sk_hostname_is_local(char *name
)
497 return !strcmp(name
, "localhost");
500 static INTERFACE_INFO local_interfaces
[16];
501 static int n_local_interfaces
; /* 0=not yet, -1=failed, >0=number */
503 static int ipv4_is_local_addr(struct in_addr addr
)
505 if (ipv4_is_loopback(addr
))
506 return 1; /* loopback addresses are local */
507 if (!n_local_interfaces
) {
508 SOCKET s
= p_socket(AF_INET
, SOCK_DGRAM
, 0);
512 p_WSAIoctl(s
, SIO_GET_INTERFACE_LIST
, NULL
, 0,
513 local_interfaces
, sizeof(local_interfaces
),
514 &retbytes
, NULL
, NULL
) == 0)
515 n_local_interfaces
= retbytes
/ sizeof(INTERFACE_INFO
);
517 logevent(NULL
, "Unable to get list of local IP addresses");
519 if (n_local_interfaces
> 0) {
521 for (i
= 0; i
< n_local_interfaces
; i
++) {
522 SOCKADDR_IN
*address
=
523 (SOCKADDR_IN
*)&local_interfaces
[i
].iiAddress
;
524 if (address
->sin_addr
.s_addr
== addr
.s_addr
)
525 return 1; /* this address is local */
528 return 0; /* this address is not local */
531 int sk_address_is_local(SockAddr addr
)
534 if (addr
->family
== AF_INET6
) {
535 FIXME
; /* someone who can compile for IPV6 had better do this bit */
538 if (addr
->family
== AF_INET
) {
540 a
.s_addr
= p_htonl(addr
->address
);
541 return ipv4_is_local_addr(a
);
543 assert(addr
->family
== AF_UNSPEC
);
544 return 0; /* we don't know; assume not */
548 int sk_addrtype(SockAddr addr
)
550 return (addr
->family
== AF_INET ? ADDRTYPE_IPV4
:
552 addr
->family
== AF_INET6 ? ADDRTYPE_IPV6
:
557 void sk_addrcopy(SockAddr addr
, char *buf
)
559 assert(addr
->family
!= AF_UNSPEC
);
561 if (addr
->family
== AF_INET6
) {
562 memcpy(buf
, (char*) addr
->ai
, 16);
565 if (addr
->family
== AF_INET
) {
567 a
.s_addr
= p_htonl(addr
->address
);
568 memcpy(buf
, (char*) &a
.s_addr
, 4);
572 void sk_addr_free(SockAddr addr
)
577 static Plug
sk_tcp_plug(Socket sock
, Plug p
)
579 Actual_Socket s
= (Actual_Socket
) sock
;
586 static void sk_tcp_flush(Socket s
)
589 * We send data to the socket as soon as we can anyway,
590 * so we don't need to do anything here. :-)
594 static void sk_tcp_close(Socket s
);
595 static int sk_tcp_write(Socket s
, const char *data
, int len
);
596 static int sk_tcp_write_oob(Socket s
, const char *data
, int len
);
597 static void sk_tcp_set_private_ptr(Socket s
, void *ptr
);
598 static void *sk_tcp_get_private_ptr(Socket s
);
599 static void sk_tcp_set_frozen(Socket s
, int is_frozen
);
600 static const char *sk_tcp_socket_error(Socket s
);
602 extern char *do_select(SOCKET skt
, int startup
);
604 Socket
sk_register(void *sock
, Plug plug
)
606 static const struct socket_function_table fn_table
= {
612 sk_tcp_set_private_ptr
,
613 sk_tcp_get_private_ptr
,
623 * Create Socket structure.
625 ret
= snew(struct Socket_tag
);
629 bufchain_init(&ret
->output_data
);
630 ret
->writable
= 1; /* to start with */
631 ret
->sending_oob
= 0;
633 ret
->frozen_readable
= 0;
634 ret
->localhost_only
= 0; /* unused, but best init anyway */
635 ret
->pending_error
= 0;
637 ret
->s
= (SOCKET
)sock
;
639 if (ret
->s
== INVALID_SOCKET
) {
640 err
= p_WSAGetLastError();
641 ret
->error
= winsock_error_string(err
);
647 /* Set up a select mechanism. This could be an AsyncSelect on a
648 * window, or an EventSelect on an event object. */
649 errstr
= do_select(ret
->s
, 1);
660 Socket
sk_new(SockAddr addr
, int port
, int privport
, int oobinline
,
661 int nodelay
, int keepalive
, Plug plug
)
663 static const struct socket_function_table fn_table
= {
669 sk_tcp_set_private_ptr
,
670 sk_tcp_get_private_ptr
,
686 * Create Socket structure.
688 ret
= snew(struct Socket_tag
);
692 bufchain_init(&ret
->output_data
);
693 ret
->connected
= 0; /* to start with */
694 ret
->writable
= 0; /* to start with */
695 ret
->sending_oob
= 0;
697 ret
->frozen_readable
= 0;
698 ret
->localhost_only
= 0; /* unused, but best init anyway */
699 ret
->pending_error
= 0;
704 assert(addr
->family
!= AF_UNSPEC
);
705 s
= p_socket(addr
->family
, SOCK_STREAM
, 0);
708 if (s
== INVALID_SOCKET
) {
709 err
= p_WSAGetLastError();
710 ret
->error
= winsock_error_string(err
);
714 ret
->oobinline
= oobinline
;
717 p_setsockopt(s
, SOL_SOCKET
, SO_OOBINLINE
, (void *) &b
, sizeof(b
));
722 p_setsockopt(s
, IPPROTO_TCP
, TCP_NODELAY
, (void *) &b
, sizeof(b
));
727 p_setsockopt(s
, SOL_SOCKET
, SO_KEEPALIVE
, (void *) &b
, sizeof(b
));
731 * Bind to local address.
734 localport
= 1023; /* count from 1023 downwards */
736 localport
= 0; /* just use port 0 (ie winsock picks) */
738 /* Loop round trying to bind */
743 if (addr
->family
== AF_INET6
) {
744 memset(&a6
, 0, sizeof(a6
));
745 a6
.sin6_family
= AF_INET6
;
746 /*a6.sin6_addr = in6addr_any; *//* == 0 */
747 a6
.sin6_port
= p_htons(localport
);
751 a
.sin_family
= AF_INET
;
752 a
.sin_addr
.s_addr
= p_htonl(INADDR_ANY
);
753 a
.sin_port
= p_htons(localport
);
756 retcode
= p_bind(s
, (addr
->family
== AF_INET6 ?
757 (struct sockaddr
*) &a6
:
758 (struct sockaddr
*) &a
),
760 AF_INET6 ?
sizeof(a6
) : sizeof(a
)));
762 retcode
= p_bind(s
, (struct sockaddr
*) &a
, sizeof(a
));
764 if (retcode
!= SOCKET_ERROR
) {
768 err
= p_WSAGetLastError();
769 if (err
!= WSAEADDRINUSE
) /* failed, for a bad reason */
774 break; /* we're only looping once */
777 break; /* we might have got to the end */
781 ret
->error
= winsock_error_string(err
);
786 * Connect to remote address.
789 if (addr
->family
== AF_INET6
) {
790 memset(&a
, 0, sizeof(a
));
791 a6
.sin6_family
= AF_INET6
;
792 a6
.sin6_port
= p_htons((short) port
);
794 ((struct sockaddr_in6
*) addr
->ai
->ai_addr
)->sin6_addr
;
798 a
.sin_family
= AF_INET
;
799 a
.sin_addr
.s_addr
= p_htonl(addr
->address
);
800 a
.sin_port
= p_htons((short) port
);
803 /* Set up a select mechanism. This could be an AsyncSelect on a
804 * window, or an EventSelect on an event object. */
805 errstr
= do_select(s
, 1);
813 p_connect(s
, ((addr
->family
== AF_INET6
) ?
814 (struct sockaddr
*) &a6
: (struct sockaddr
*) &a
),
815 (addr
->family
== AF_INET6
) ?
sizeof(a6
) : sizeof(a
))
817 p_connect(s
, (struct sockaddr
*) &a
, sizeof(a
))
820 err
= p_WSAGetLastError();
822 * We expect a potential EWOULDBLOCK here, because the
823 * chances are the front end has done a select for
824 * FD_CONNECT, so that connect() will complete
827 if ( err
!= WSAEWOULDBLOCK
) {
828 ret
->error
= winsock_error_string(err
);
833 * If we _don't_ get EWOULDBLOCK, the connect has completed
834 * and we should set the socket as writable.
841 /* We're done with 'addr' now. */
847 Socket
sk_newlistener(char *srcaddr
, int port
, Plug plug
, int local_host_only
)
849 static const struct socket_function_table fn_table
= {
855 sk_tcp_set_private_ptr
,
856 sk_tcp_get_private_ptr
,
873 * Create Socket structure.
875 ret
= snew(struct Socket_tag
);
879 bufchain_init(&ret
->output_data
);
880 ret
->writable
= 0; /* to start with */
881 ret
->sending_oob
= 0;
883 ret
->frozen_readable
= 0;
884 ret
->localhost_only
= local_host_only
;
885 ret
->pending_error
= 0;
890 s
= p_socket(AF_INET
, SOCK_STREAM
, 0);
893 if (s
== INVALID_SOCKET
) {
894 err
= p_WSAGetLastError();
895 ret
->error
= winsock_error_string(err
);
901 p_setsockopt(s
, SOL_SOCKET
, SO_REUSEADDR
, (const char *)&on
, sizeof(on
));
904 if (addr
->family
== AF_INET6
) {
905 memset(&a6
, 0, sizeof(a6
));
906 a6
.sin6_family
= AF_INET6
;
907 /* FIXME: srcaddr is ignored for IPv6, because I (SGT) don't
908 * know how to do it. :-) */
910 a6
.sin6_addr
= in6addr_loopback
;
912 a6
.sin6_addr
= in6addr_any
;
913 a6
.sin6_port
= p_htons(port
);
918 a
.sin_family
= AF_INET
;
921 * Bind to source address. First try an explicitly
925 a
.sin_addr
.s_addr
= p_inet_addr(srcaddr
);
926 if (a
.sin_addr
.s_addr
!= INADDR_NONE
) {
927 /* Override localhost_only with specified listen addr. */
928 ret
->localhost_only
= ipv4_is_loopback(a
.sin_addr
);
934 * ... and failing that, go with one of the standard ones.
938 a
.sin_addr
.s_addr
= p_htonl(INADDR_LOOPBACK
);
940 a
.sin_addr
.s_addr
= p_htonl(INADDR_ANY
);
943 a
.sin_port
= p_htons((short)port
);
946 retcode
= p_bind(s
, (addr
->family
== AF_INET6 ?
947 (struct sockaddr
*) &a6
:
948 (struct sockaddr
*) &a
),
950 AF_INET6 ?
sizeof(a6
) : sizeof(a
)));
952 retcode
= p_bind(s
, (struct sockaddr
*) &a
, sizeof(a
));
954 if (retcode
!= SOCKET_ERROR
) {
957 err
= p_WSAGetLastError();
961 ret
->error
= winsock_error_string(err
);
966 if (p_listen(s
, SOMAXCONN
) == SOCKET_ERROR
) {
968 ret
->error
= winsock_error_string(err
);
972 /* Set up a select mechanism. This could be an AsyncSelect on a
973 * window, or an EventSelect on an event object. */
974 errstr
= do_select(s
, 1);
985 static void sk_tcp_close(Socket sock
)
987 extern char *do_select(SOCKET skt
, int startup
);
988 Actual_Socket s
= (Actual_Socket
) sock
;
997 * The function which tries to send on a socket once it's deemed
1000 void try_send(Actual_Socket s
)
1002 while (s
->sending_oob
|| bufchain_size(&s
->output_data
) > 0) {
1006 int len
, urgentflag
;
1008 if (s
->sending_oob
) {
1009 urgentflag
= MSG_OOB
;
1010 len
= s
->sending_oob
;
1014 bufchain_prefix(&s
->output_data
, &data
, &len
);
1016 nsent
= p_send(s
->s
, data
, len
, urgentflag
);
1017 noise_ultralight(nsent
);
1019 err
= (nsent
< 0 ?
p_WSAGetLastError() : 0);
1020 if ((err
< WSABASEERR
&& nsent
< 0) || err
== WSAEWOULDBLOCK
) {
1022 * Perfectly normal: we've sent all we can for the moment.
1024 * (Some WinSock send() implementations can return
1025 * <0 but leave no sensible error indication -
1026 * WSAGetLastError() is called but returns zero or
1027 * a small number - so we check that case and treat
1028 * it just like WSAEWOULDBLOCK.)
1030 s
->writable
= FALSE
;
1032 } else if (nsent
== 0 ||
1033 err
== WSAECONNABORTED
|| err
== WSAECONNRESET
) {
1035 * If send() returns CONNABORTED or CONNRESET, we
1036 * unfortunately can't just call plug_closing(),
1037 * because it's quite likely that we're currently
1038 * _in_ a call from the code we'd be calling back
1039 * to, so we'd have to make half the SSH code
1040 * reentrant. Instead we flag a pending error on
1041 * the socket, to be dealt with (by calling
1042 * plug_closing()) at some suitable future moment.
1044 s
->pending_error
= err
;
1047 /* We're inside the Windows frontend here, so we know
1048 * that the frontend handle is unnecessary. */
1049 logevent(NULL
, winsock_error_string(err
));
1050 fatalbox("%s", winsock_error_string(err
));
1053 if (s
->sending_oob
) {
1055 memmove(s
->oobdata
, s
->oobdata
+nsent
, len
-nsent
);
1056 s
->sending_oob
= len
- nsent
;
1061 bufchain_consume(&s
->output_data
, nsent
);
1067 static int sk_tcp_write(Socket sock
, const char *buf
, int len
)
1069 Actual_Socket s
= (Actual_Socket
) sock
;
1072 * Add the data to the buffer list on the socket.
1074 bufchain_add(&s
->output_data
, buf
, len
);
1077 * Now try sending from the start of the buffer list.
1082 return bufchain_size(&s
->output_data
);
1085 static int sk_tcp_write_oob(Socket sock
, const char *buf
, int len
)
1087 Actual_Socket s
= (Actual_Socket
) sock
;
1090 * Replace the buffer list on the socket with the data.
1092 bufchain_clear(&s
->output_data
);
1093 assert(len
<= sizeof(s
->oobdata
));
1094 memcpy(s
->oobdata
, buf
, len
);
1095 s
->sending_oob
= len
;
1098 * Now try sending from the start of the buffer list.
1103 return s
->sending_oob
;
1106 int select_result(WPARAM wParam
, LPARAM lParam
)
1110 char buf
[20480]; /* nice big buffer for plenty of speed */
1114 /* wParam is the socket itself */
1117 return 1; /* boggle */
1119 s
= find234(sktree
, (void *) wParam
, cmpforsearch
);
1121 return 1; /* boggle */
1123 if ((err
= WSAGETSELECTERROR(lParam
)) != 0) {
1125 * An error has occurred on this socket. Pass it to the
1128 return plug_closing(s
->plug
, winsock_error_string(err
), err
, 0);
1131 noise_ultralight(lParam
);
1133 switch (WSAGETSELECTEVENT(lParam
)) {
1135 s
->connected
= s
->writable
= 1;
1138 /* In the case the socket is still frozen, we don't even bother */
1140 s
->frozen_readable
= 1;
1145 * We have received data on the socket. For an oobinline
1146 * socket, this might be data _before_ an urgent pointer,
1147 * in which case we send it to the back end with type==1
1148 * (data prior to urgent).
1152 p_ioctlsocket(s
->s
, SIOCATMARK
, &atmark
);
1154 * Avoid checking the return value from ioctlsocket(),
1155 * on the grounds that some WinSock wrappers don't
1156 * support it. If it does nothing, we get atmark==1,
1157 * which is equivalent to `no OOB pending', so the
1158 * effect will be to non-OOB-ify any OOB data.
1163 ret
= p_recv(s
->s
, buf
, sizeof(buf
), 0);
1164 noise_ultralight(ret
);
1166 err
= p_WSAGetLastError();
1167 if (err
== WSAEWOULDBLOCK
) {
1172 return plug_closing(s
->plug
, winsock_error_string(err
), err
,
1174 } else if (0 == ret
) {
1175 return plug_closing(s
->plug
, NULL
, 0, 0);
1177 return plug_receive(s
->plug
, atmark ?
0 : 1, buf
, ret
);
1182 * This will only happen on a non-oobinline socket. It
1183 * indicates that we can immediately perform an OOB read
1184 * and get back OOB data, which we will send to the back
1185 * end with type==2 (urgent data).
1187 ret
= p_recv(s
->s
, buf
, sizeof(buf
), MSG_OOB
);
1188 noise_ultralight(ret
);
1190 char *str
= (ret
== 0 ?
"Internal networking trouble" :
1191 winsock_error_string(p_WSAGetLastError()));
1192 /* We're inside the Windows frontend here, so we know
1193 * that the frontend handle is unnecessary. */
1194 logevent(NULL
, str
);
1195 fatalbox("%s", str
);
1197 return plug_receive(s
->plug
, 2, buf
, ret
);
1202 int bufsize_before
, bufsize_after
;
1204 bufsize_before
= s
->sending_oob
+ bufchain_size(&s
->output_data
);
1206 bufsize_after
= s
->sending_oob
+ bufchain_size(&s
->output_data
);
1207 if (bufsize_after
< bufsize_before
)
1208 plug_sent(s
->plug
, bufsize_after
);
1212 /* Signal a close on the socket. First read any outstanding data. */
1215 ret
= p_recv(s
->s
, buf
, sizeof(buf
), 0);
1217 err
= p_WSAGetLastError();
1218 if (err
== WSAEWOULDBLOCK
)
1220 return plug_closing(s
->plug
, winsock_error_string(err
),
1224 open
&= plug_receive(s
->plug
, 0, buf
, ret
);
1226 open
&= plug_closing(s
->plug
, NULL
, 0, 0);
1232 struct sockaddr_in isa
;
1233 int addrlen
= sizeof(struct sockaddr_in
);
1234 SOCKET t
; /* socket of connection */
1236 memset(&isa
, 0, sizeof(struct sockaddr_in
));
1238 t
= p_accept(s
->s
,(struct sockaddr
*)&isa
,&addrlen
);
1239 if (t
== INVALID_SOCKET
)
1241 err
= p_WSAGetLastError();
1242 if (err
== WSATRY_AGAIN
)
1246 if (s
->localhost_only
&& !ipv4_is_local_addr(isa
.sin_addr
)) {
1247 p_closesocket(t
); /* dodgy WinSock let nonlocal through */
1248 } else if (plug_accepting(s
->plug
, (void*)t
)) {
1249 p_closesocket(t
); /* denied or error */
1258 * Deal with socket errors detected in try_send().
1260 void net_pending_errors(void)
1266 * This might be a fiddly business, because it's just possible
1267 * that handling a pending error on one socket might cause
1268 * others to be closed. (I can't think of any reason this might
1269 * happen in current SSH implementation, but to maintain
1270 * generality of this network layer I'll assume the worst.)
1272 * So what we'll do is search the socket list for _one_ socket
1273 * with a pending error, and then handle it, and then search
1274 * the list again _from the beginning_. Repeat until we make a
1275 * pass with no socket errors present. That way we are
1276 * protected against the socket list changing under our feet.
1280 for (i
= 0; (s
= index234(sktree
, i
)) != NULL
; i
++) {
1281 if (s
->pending_error
) {
1283 * An error has occurred on this socket. Pass it to the
1286 plug_closing(s
->plug
,
1287 winsock_error_string(s
->pending_error
),
1288 s
->pending_error
, 0);
1296 * Each socket abstraction contains a `void *' private field in
1297 * which the client can keep state.
1299 static void sk_tcp_set_private_ptr(Socket sock
, void *ptr
)
1301 Actual_Socket s
= (Actual_Socket
) sock
;
1302 s
->private_ptr
= ptr
;
1305 static void *sk_tcp_get_private_ptr(Socket sock
)
1307 Actual_Socket s
= (Actual_Socket
) sock
;
1308 return s
->private_ptr
;
1312 * Special error values are returned from sk_namelookup and sk_new
1313 * if there's a problem. These functions extract an error message,
1314 * or return NULL if there's no problem.
1316 const char *sk_addr_error(SockAddr addr
)
1320 static const char *sk_tcp_socket_error(Socket sock
)
1322 Actual_Socket s
= (Actual_Socket
) sock
;
1326 static void sk_tcp_set_frozen(Socket sock
, int is_frozen
)
1328 Actual_Socket s
= (Actual_Socket
) sock
;
1329 if (s
->frozen
== is_frozen
)
1331 s
->frozen
= is_frozen
;
1332 if (!is_frozen
&& s
->frozen_readable
) {
1334 p_recv(s
->s
, &c
, 1, MSG_PEEK
);
1336 s
->frozen_readable
= 0;
1340 * For Plink: enumerate all sockets currently active.
1342 SOCKET
first_socket(int *state
)
1346 s
= index234(sktree
, (*state
)++);
1347 return s ? s
->s
: INVALID_SOCKET
;
1350 SOCKET
next_socket(int *state
)
1352 Actual_Socket s
= index234(sktree
, (*state
)++);
1353 return s ? s
->s
: INVALID_SOCKET
;
1356 int net_service_lookup(char *service
)
1359 se
= p_getservbyname(service
, NULL
);
1361 return p_ntohs(se
->s_port
);
1366 SockAddr
platform_get_x11_unix_address(int displaynum
, char **canonicalname
)
1368 SockAddr ret
= snew(struct SockAddr_tag
);
1369 memset(ret
, 0, sizeof(struct SockAddr_tag
));
1370 ret
->error
= "unix sockets not supported on this platform";