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 const struct socket_function_table
*fn
;
29 /* the above variable absolutely *must* be the first in this structure */
37 int frozen
; /* this causes readability notifications to be ignored */
38 int frozen_readable
; /* this means we missed at least one readability
39 * notification while we were frozen */
40 int localhost_only
; /* for listening sockets */
44 int pending_error
; /* in case send() returns error */
48 * We used to typedef struct Socket_tag *Socket.
50 * Since we have made the networking abstraction slightly more
51 * abstract, Socket no longer means a tcp socket (it could mean
52 * an ssl socket). So now we must use Actual_Socket when we know
53 * we are talking about a tcp socket.
55 typedef struct Socket_tag
*Actual_Socket
;
60 * Which address family this address belongs to. AF_INET for
61 * IPv4; AF_INET6 for IPv6; AF_UNSPEC indicates that name
62 * resolution has not been done and a simple host name is held
63 * in this SockAddr structure.
64 * The hostname field is also used when the hostname has both
65 * an IPv6 and IPv4 address and the IPv6 connection attempt
66 * fails. We then try the IPv4 address.
67 * This 'family' should become an option in the GUI and
68 * on the commandline for selecting a default protocol.
71 unsigned long address
; /* Address IPv4 style. */
73 struct addrinfo
*ai
; /* Address AF-independent (IPv4+IPv6) style. */
75 char hostname
[512]; /* Store an unresolved host name. */
78 static tree234
*sktree
;
80 static int cmpfortree(void *av
, void *bv
)
82 Actual_Socket a
= (Actual_Socket
) av
, b
= (Actual_Socket
) bv
;
83 unsigned long as
= (unsigned long) a
->s
, bs
= (unsigned long) b
->s
;
91 static int cmpforsearch(void *av
, void *bv
)
93 Actual_Socket b
= (Actual_Socket
) bv
;
94 unsigned long as
= (unsigned long) av
, bs
= (unsigned long) b
->s
;
103 #define DECL_WINSOCK_FUNCTION(linkage, rettype, name, params) \
104 typedef rettype (WINAPI *t_##name) params; \
105 linkage t_##name p_##name
106 #define GET_WINSOCK_FUNCTION(name) \
107 p_##name = (t_##name) GetProcAddress(winsock_module, #name)
109 DECL_WINSOCK_FUNCTION(NOTHING
, int, WSAAsyncSelect
,
110 (SOCKET
, HWND
, u_int
, long));
111 DECL_WINSOCK_FUNCTION(NOTHING
, int, WSAEventSelect
, (SOCKET
, WSAEVENT
, long));
112 DECL_WINSOCK_FUNCTION(NOTHING
, int, select
,
113 (int, fd_set FAR
*, fd_set FAR
*,
114 fd_set FAR
*, const struct timeval FAR
*));
115 DECL_WINSOCK_FUNCTION(NOTHING
, int, WSAGetLastError
, (void));
116 DECL_WINSOCK_FUNCTION(NOTHING
, int, WSAEnumNetworkEvents
,
117 (SOCKET
, WSAEVENT
, LPWSANETWORKEVENTS
));
118 DECL_WINSOCK_FUNCTION(static, int, WSAStartup
, (WORD
, LPWSADATA
));
119 DECL_WINSOCK_FUNCTION(static, int, WSACleanup
, (void));
120 DECL_WINSOCK_FUNCTION(static, int, closesocket
, (SOCKET
));
121 DECL_WINSOCK_FUNCTION(static, u_long
, ntohl
, (u_long
));
122 DECL_WINSOCK_FUNCTION(static, u_long
, htonl
, (u_long
));
123 DECL_WINSOCK_FUNCTION(static, u_short
, htons
, (u_short
));
124 DECL_WINSOCK_FUNCTION(static, u_short
, ntohs
, (u_short
));
125 DECL_WINSOCK_FUNCTION(static, struct hostent FAR
*, gethostbyname
,
127 DECL_WINSOCK_FUNCTION(static, struct servent FAR
*, getservbyname
,
128 (const char FAR
*, const char FAR
*));
129 DECL_WINSOCK_FUNCTION(static, unsigned long, inet_addr
, (const char FAR
*));
130 DECL_WINSOCK_FUNCTION(static, char FAR
*, inet_ntoa
, (struct in_addr
));
131 DECL_WINSOCK_FUNCTION(static, int, connect
,
132 (SOCKET
, const struct sockaddr FAR
*, int));
133 DECL_WINSOCK_FUNCTION(static, int, bind
,
134 (SOCKET
, const struct sockaddr FAR
*, int));
135 DECL_WINSOCK_FUNCTION(static, int, setsockopt
,
136 (SOCKET
, int, int, const char FAR
*, int));
137 DECL_WINSOCK_FUNCTION(static, SOCKET
, socket
, (int, int, int));
138 DECL_WINSOCK_FUNCTION(static, int, listen
, (SOCKET
, int));
139 DECL_WINSOCK_FUNCTION(static, int, send
, (SOCKET
, const char FAR
*, int, int));
140 DECL_WINSOCK_FUNCTION(static, int, ioctlsocket
,
141 (SOCKET
, long, u_long FAR
*));
142 DECL_WINSOCK_FUNCTION(static, SOCKET
, accept
,
143 (SOCKET
, struct sockaddr FAR
*, int FAR
*));
144 DECL_WINSOCK_FUNCTION(static, int, recv
, (SOCKET
, char FAR
*, int, int));
145 DECL_WINSOCK_FUNCTION(static, int, WSAIoctl
,
146 (SOCKET
, DWORD
, LPVOID
, DWORD
, LPVOID
, DWORD
,
147 LPDWORD
, LPWSAOVERLAPPED
,
148 LPWSAOVERLAPPED_COMPLETION_ROUTINE
));
150 static HMODULE winsock_module
;
157 winsock_ver
= MAKEWORD(2, 0);
158 winsock_module
= LoadLibrary("WS2_32.DLL");
159 if (!winsock_module
) {
160 winsock_module
= LoadLibrary("WSOCK32.DLL");
161 winsock_ver
= MAKEWORD(1, 1);
164 fatalbox("Unable to load any WinSock library");
166 GET_WINSOCK_FUNCTION(WSAAsyncSelect
);
167 GET_WINSOCK_FUNCTION(WSAEventSelect
);
168 GET_WINSOCK_FUNCTION(select
);
169 GET_WINSOCK_FUNCTION(WSAGetLastError
);
170 GET_WINSOCK_FUNCTION(WSAEnumNetworkEvents
);
171 GET_WINSOCK_FUNCTION(WSAStartup
);
172 GET_WINSOCK_FUNCTION(WSACleanup
);
173 GET_WINSOCK_FUNCTION(closesocket
);
174 GET_WINSOCK_FUNCTION(ntohl
);
175 GET_WINSOCK_FUNCTION(htonl
);
176 GET_WINSOCK_FUNCTION(htons
);
177 GET_WINSOCK_FUNCTION(ntohs
);
178 GET_WINSOCK_FUNCTION(gethostbyname
);
179 GET_WINSOCK_FUNCTION(getservbyname
);
180 GET_WINSOCK_FUNCTION(inet_addr
);
181 GET_WINSOCK_FUNCTION(inet_ntoa
);
182 GET_WINSOCK_FUNCTION(connect
);
183 GET_WINSOCK_FUNCTION(bind
);
184 GET_WINSOCK_FUNCTION(setsockopt
);
185 GET_WINSOCK_FUNCTION(socket
);
186 GET_WINSOCK_FUNCTION(listen
);
187 GET_WINSOCK_FUNCTION(send
);
188 GET_WINSOCK_FUNCTION(ioctlsocket
);
189 GET_WINSOCK_FUNCTION(accept
);
190 GET_WINSOCK_FUNCTION(recv
);
191 GET_WINSOCK_FUNCTION(WSAIoctl
);
193 if (p_WSAStartup(winsock_ver
, &wsadata
)) {
194 fatalbox("Unable to initialise WinSock");
196 if (LOBYTE(wsadata
.wVersion
) != LOBYTE(winsock_ver
)) {
198 fatalbox("WinSock version is incompatible with %d.%d",
199 LOBYTE(winsock_ver
), HIBYTE(winsock_ver
));
202 sktree
= newtree234(cmpfortree
);
205 void sk_cleanup(void)
211 for (i
= 0; (s
= index234(sktree
, i
)) != NULL
; i
++) {
220 FreeLibrary(winsock_module
);
223 char *winsock_error_string(int error
)
227 return "Network error: Permission denied";
229 return "Network error: Address already in use";
230 case WSAEADDRNOTAVAIL
:
231 return "Network error: Cannot assign requested address";
232 case WSAEAFNOSUPPORT
:
234 "Network error: Address family not supported by protocol family";
236 return "Network error: Operation already in progress";
237 case WSAECONNABORTED
:
238 return "Network error: Software caused connection abort";
239 case WSAECONNREFUSED
:
240 return "Network error: Connection refused";
242 return "Network error: Connection reset by peer";
243 case WSAEDESTADDRREQ
:
244 return "Network error: Destination address required";
246 return "Network error: Bad address";
248 return "Network error: Host is down";
249 case WSAEHOSTUNREACH
:
250 return "Network error: No route to host";
252 return "Network error: Operation now in progress";
254 return "Network error: Interrupted function call";
256 return "Network error: Invalid argument";
258 return "Network error: Socket is already connected";
260 return "Network error: Too many open files";
262 return "Network error: Message too long";
264 return "Network error: Network is down";
266 return "Network error: Network dropped connection on reset";
268 return "Network error: Network is unreachable";
270 return "Network error: No buffer space available";
272 return "Network error: Bad protocol option";
274 return "Network error: Socket is not connected";
276 return "Network error: Socket operation on non-socket";
278 return "Network error: Operation not supported";
279 case WSAEPFNOSUPPORT
:
280 return "Network error: Protocol family not supported";
282 return "Network error: Too many processes";
283 case WSAEPROTONOSUPPORT
:
284 return "Network error: Protocol not supported";
286 return "Network error: Protocol wrong type for socket";
288 return "Network error: Cannot send after socket shutdown";
289 case WSAESOCKTNOSUPPORT
:
290 return "Network error: Socket type not supported";
292 return "Network error: Connection timed out";
294 return "Network error: Resource temporarily unavailable";
296 return "Network error: Graceful shutdown in progress";
298 return "Unknown network error";
302 SockAddr
sk_namelookup(const char *host
, char **canonicalname
,
305 SockAddr ret
= snew(struct SockAddr_tag
);
307 struct hostent
*h
= NULL
;
312 /* Clear the structure and default to IPv4. */
313 memset(ret
, 0, sizeof(struct SockAddr_tag
));
314 ret
->family
= (address_family
== ADDRTYPE_IPV4 ? AF_INET
:
316 address_family
== ADDRTYPE_IPV6 ? AF_INET6
:
319 ret_family
= AF_UNSPEC
;
322 if ((a
= p_inet_addr(host
)) == (unsigned long) INADDR_NONE
) {
325 /* Try to get the getaddrinfo() function from wship6.dll */
326 /* This way one doesn't need to have IPv6 dll's to use PuTTY and
327 * it will fallback to IPv4. */
328 typedef int (CALLBACK
* FGETADDRINFO
) (const char *nodename
,
329 const char *servname
,
330 const struct addrinfo
*hints
,
331 struct addrinfo
**res
);
332 FGETADDRINFO fGetAddrInfo
= NULL
;
334 HINSTANCE dllWSHIP6
= LoadLibrary("wship6.dll");
336 fGetAddrInfo
= (FGETADDRINFO
) GetProcAddress(dllWSHIP6
,
340 * Use fGetAddrInfo when it's available
343 struct addrinfo hints
;
344 memset(&hints
, 0, sizeof(hints
));
345 hints
.ai_family
= ret
->family
;
346 if ((err
= fGetAddrInfo(host
, NULL
, &hints
, &ret
->ai
)) == 0)
347 ret_family
= ret
->ai
->ai_family
;
352 * Otherwise use the IPv4-only gethostbyname...
353 * (NOTE: we don't use gethostbyname as a fallback!)
355 if ( (h
= p_gethostbyname(host
)) )
356 ret_family
= AF_INET
;
358 err
= p_WSAGetLastError();
361 if (ret_family
== AF_UNSPEC
) {
362 ret
->error
= (err
== WSAENETDOWN ?
"Network is down" :
363 err
== WSAHOST_NOT_FOUND ?
"Host does not exist" :
364 err
== WSATRY_AGAIN ?
"Host not found" :
366 fGetAddrInfo ?
"getaddrinfo: unknown error" :
368 "gethostbyname: unknown error");
371 ret
->family
= ret_family
;
374 /* If we got an address info use that... */
376 typedef int (CALLBACK
* FGETNAMEINFO
)
377 (const struct sockaddr FAR
* sa
, socklen_t salen
,
378 char FAR
* host
, size_t hostlen
, char FAR
* serv
,
379 size_t servlen
, int flags
);
380 FGETNAMEINFO fGetNameInfo
= NULL
;
382 /* Are we in IPv4 fallback mode? */
383 /* We put the IPv4 address into the a variable so we can further-on use the IPv4 code... */
384 if (ret
->family
== AF_INET
)
386 (char *) &((SOCKADDR_IN
*) ret
->ai
->
387 ai_addr
)->sin_addr
, sizeof(a
));
389 /* Now let's find that canonicalname... */
392 (FGETNAMEINFO
) GetProcAddress(dllWSHIP6
,
395 ((struct sockaddr
*) ret
->ai
->ai_addr
,
397 AF_INET ?
sizeof(SOCKADDR_IN
) :
398 sizeof(SOCKADDR_IN6
), realhost
,
399 sizeof(realhost
), NULL
, 0, 0) != 0) {
400 strncpy(realhost
, host
, sizeof(realhost
));
404 /* We used the IPv4-only gethostbyname()... */
408 memcpy(&a
, h
->h_addr
, sizeof(a
));
409 /* This way we are always sure the h->h_name is valid :) */
410 strncpy(realhost
, h
->h_name
, sizeof(realhost
));
414 FreeLibrary(dllWSHIP6
);
418 * This must be a numeric IPv4 address because it caused a
419 * success return from inet_addr.
421 ret
->family
= AF_INET
;
422 strncpy(realhost
, host
, sizeof(realhost
));
424 ret
->address
= p_ntohl(a
);
425 realhost
[lenof(realhost
)-1] = '\0';
426 *canonicalname
= snewn(1+strlen(realhost
), char);
427 strcpy(*canonicalname
, realhost
);
431 SockAddr
sk_nonamelookup(const char *host
)
433 SockAddr ret
= snew(struct SockAddr_tag
);
435 ret
->family
= AF_UNSPEC
;
436 strncpy(ret
->hostname
, host
, lenof(ret
->hostname
));
437 ret
->hostname
[lenof(ret
->hostname
)-1] = '\0';
441 void sk_getaddr(SockAddr addr
, char *buf
, int buflen
)
444 if (addr
->family
== AF_INET6
) {
445 /* Try to get the WSAAddressToStringA() function from wship6.dll */
446 /* This way one doesn't need to have IPv6 dll's to use PuTTY and
447 * it will fallback to IPv4. */
448 typedef int (CALLBACK
* FADDRTOSTR
) (LPSOCKADDR lpsaAddress
,
449 DWORD dwAddressLength
,
450 LPWSAPROTOCOL_INFO lpProtocolInfo
,
451 OUT LPTSTR lpszAddressString
,
452 IN OUT LPDWORD lpdwAddressStringLength
454 FADDRTOSTR fAddrToStr
= NULL
;
456 HINSTANCE dllWS2
= LoadLibrary("ws2_32.dll");
458 fAddrToStr
= (FADDRTOSTR
)GetProcAddress(dllWS2
,
459 "WSAAddressToStringA");
461 fAddrToStr(addr
->ai
->ai_addr
, addr
->ai
->ai_addrlen
,
464 else strncpy(buf
, "IPv6", buflen
);
469 if (addr
->family
== AF_INET
) {
471 a
.s_addr
= p_htonl(addr
->address
);
472 strncpy(buf
, p_inet_ntoa(a
), buflen
);
473 buf
[buflen
-1] = '\0';
475 strncpy(buf
, addr
->hostname
, buflen
);
476 buf
[buflen
-1] = '\0';
480 int sk_hostname_is_local(char *name
)
482 return !strcmp(name
, "localhost");
485 static INTERFACE_INFO local_interfaces
[16];
486 static int n_local_interfaces
; /* 0=not yet, -1=failed, >0=number */
488 static int ipv4_is_local_addr(struct in_addr addr
)
490 if (ipv4_is_loopback(addr
))
491 return 1; /* loopback addresses are local */
492 if (!n_local_interfaces
) {
493 SOCKET s
= p_socket(AF_INET
, SOCK_DGRAM
, 0);
497 p_WSAIoctl(s
, SIO_GET_INTERFACE_LIST
, NULL
, 0,
498 local_interfaces
, sizeof(local_interfaces
),
499 &retbytes
, NULL
, NULL
) == 0)
500 n_local_interfaces
= retbytes
/ sizeof(INTERFACE_INFO
);
502 logevent(NULL
, "Unable to get list of local IP addresses");
504 if (n_local_interfaces
> 0) {
506 for (i
= 0; i
< n_local_interfaces
; i
++) {
507 SOCKADDR_IN
*address
=
508 (SOCKADDR_IN
*)&local_interfaces
[i
].iiAddress
;
509 if (address
->sin_addr
.s_addr
== addr
.s_addr
)
510 return 1; /* this address is local */
513 return 0; /* this address is not local */
516 int sk_address_is_local(SockAddr addr
)
519 if (addr
->family
== AF_INET6
) {
520 return IN6_IS_ADDR_LOOPBACK((const struct in6_addr
*)addr
->ai
->ai_addr
);
523 if (addr
->family
== AF_INET
) {
525 a
.s_addr
= p_htonl(addr
->address
);
526 return ipv4_is_local_addr(a
);
528 assert(addr
->family
== AF_UNSPEC
);
529 return 0; /* we don't know; assume not */
533 int sk_addrtype(SockAddr addr
)
535 return (addr
->family
== AF_INET ? ADDRTYPE_IPV4
:
537 addr
->family
== AF_INET6 ? ADDRTYPE_IPV6
:
542 void sk_addrcopy(SockAddr addr
, char *buf
)
544 assert(addr
->family
!= AF_UNSPEC
);
546 if (addr
->family
== AF_INET6
) {
547 memcpy(buf
, (char*) addr
->ai
, 16);
550 if (addr
->family
== AF_INET
) {
552 a
.s_addr
= p_htonl(addr
->address
);
553 memcpy(buf
, (char*) &a
.s_addr
, 4);
557 void sk_addr_free(SockAddr addr
)
562 static Plug
sk_tcp_plug(Socket sock
, Plug p
)
564 Actual_Socket s
= (Actual_Socket
) sock
;
571 static void sk_tcp_flush(Socket s
)
574 * We send data to the socket as soon as we can anyway,
575 * so we don't need to do anything here. :-)
579 static void sk_tcp_close(Socket s
);
580 static int sk_tcp_write(Socket s
, const char *data
, int len
);
581 static int sk_tcp_write_oob(Socket s
, const char *data
, int len
);
582 static void sk_tcp_set_private_ptr(Socket s
, void *ptr
);
583 static void *sk_tcp_get_private_ptr(Socket s
);
584 static void sk_tcp_set_frozen(Socket s
, int is_frozen
);
585 static const char *sk_tcp_socket_error(Socket s
);
587 extern char *do_select(SOCKET skt
, int startup
);
589 Socket
sk_register(void *sock
, Plug plug
)
591 static const struct socket_function_table fn_table
= {
597 sk_tcp_set_private_ptr
,
598 sk_tcp_get_private_ptr
,
608 * Create Socket structure.
610 ret
= snew(struct Socket_tag
);
614 bufchain_init(&ret
->output_data
);
615 ret
->writable
= 1; /* to start with */
616 ret
->sending_oob
= 0;
618 ret
->frozen_readable
= 0;
619 ret
->localhost_only
= 0; /* unused, but best init anyway */
620 ret
->pending_error
= 0;
622 ret
->s
= (SOCKET
)sock
;
624 if (ret
->s
== INVALID_SOCKET
) {
625 err
= p_WSAGetLastError();
626 ret
->error
= winsock_error_string(err
);
632 /* Set up a select mechanism. This could be an AsyncSelect on a
633 * window, or an EventSelect on an event object. */
634 errstr
= do_select(ret
->s
, 1);
645 Socket
sk_new(SockAddr addr
, int port
, int privport
, int oobinline
,
646 int nodelay
, int keepalive
, Plug plug
)
648 static const struct socket_function_table fn_table
= {
654 sk_tcp_set_private_ptr
,
655 sk_tcp_get_private_ptr
,
671 * Create Socket structure.
673 ret
= snew(struct Socket_tag
);
677 bufchain_init(&ret
->output_data
);
678 ret
->connected
= 0; /* to start with */
679 ret
->writable
= 0; /* to start with */
680 ret
->sending_oob
= 0;
682 ret
->frozen_readable
= 0;
683 ret
->localhost_only
= 0; /* unused, but best init anyway */
684 ret
->pending_error
= 0;
690 /* Let's default to IPv6, this shouldn't hurt anybody
691 * If the stack supports IPv6 it will also allow IPv4 connections. */
692 if (addr
->family
== AF_UNSPEC
) addr
->family
= AF_INET6
;
694 /* No other choice, default to IPv4 */
695 if (addr
->family
== AF_UNSPEC
) addr
->family
= AF_INET
;
697 s
= p_socket(addr
->family
, SOCK_STREAM
, 0);
700 if (s
== INVALID_SOCKET
) {
701 err
= p_WSAGetLastError();
702 ret
->error
= winsock_error_string(err
);
706 ret
->oobinline
= oobinline
;
709 p_setsockopt(s
, SOL_SOCKET
, SO_OOBINLINE
, (void *) &b
, sizeof(b
));
714 p_setsockopt(s
, IPPROTO_TCP
, TCP_NODELAY
, (void *) &b
, sizeof(b
));
719 p_setsockopt(s
, SOL_SOCKET
, SO_KEEPALIVE
, (void *) &b
, sizeof(b
));
723 * Bind to local address.
726 localport
= 1023; /* count from 1023 downwards */
728 localport
= 0; /* just use port 0 (ie winsock picks) */
730 /* Loop round trying to bind */
735 if (addr
->family
== AF_INET6
) {
736 memset(&a6
, 0, sizeof(a6
));
737 a6
.sin6_family
= AF_INET6
;
738 /*a6.sin6_addr = in6addr_any; */ /* == 0 done by memset() */
739 a6
.sin6_port
= p_htons(localport
);
743 a
.sin_family
= AF_INET
;
744 a
.sin_addr
.s_addr
= p_htonl(INADDR_ANY
);
745 a
.sin_port
= p_htons(localport
);
748 retcode
= p_bind(s
, (addr
->family
== AF_INET6 ?
749 (struct sockaddr
*) &a6
:
750 (struct sockaddr
*) &a
),
752 AF_INET6 ?
sizeof(a6
) : sizeof(a
)));
754 retcode
= p_bind(s
, (struct sockaddr
*) &a
, sizeof(a
));
756 if (retcode
!= SOCKET_ERROR
) {
760 err
= p_WSAGetLastError();
761 if (err
!= WSAEADDRINUSE
) /* failed, for a bad reason */
766 break; /* we're only looping once */
769 break; /* we might have got to the end */
773 ret
->error
= winsock_error_string(err
);
778 * Connect to remote address.
781 if (addr
->family
== AF_INET6
) {
782 memset(&a
, 0, sizeof(a
));
783 a6
.sin6_family
= AF_INET6
;
784 a6
.sin6_port
= p_htons((short) port
);
786 ((struct sockaddr_in6
*) addr
->ai
->ai_addr
)->sin6_addr
;
790 a
.sin_family
= AF_INET
;
791 a
.sin_addr
.s_addr
= p_htonl(addr
->address
);
792 a
.sin_port
= p_htons((short) port
);
795 /* Set up a select mechanism. This could be an AsyncSelect on a
796 * window, or an EventSelect on an event object. */
797 errstr
= do_select(s
, 1);
805 p_connect(s
, ((addr
->family
== AF_INET6
) ?
806 (struct sockaddr
*) &a6
: (struct sockaddr
*) &a
),
807 (addr
->family
== AF_INET6
) ?
sizeof(a6
) : sizeof(a
))
809 p_connect(s
, (struct sockaddr
*) &a
, sizeof(a
))
812 err
= p_WSAGetLastError();
814 * We expect a potential EWOULDBLOCK here, because the
815 * chances are the front end has done a select for
816 * FD_CONNECT, so that connect() will complete
819 if ( err
!= WSAEWOULDBLOCK
) {
820 ret
->error
= winsock_error_string(err
);
825 * If we _don't_ get EWOULDBLOCK, the connect has completed
826 * and we should set the socket as writable.
833 /* We're done with 'addr' now. */
839 Socket
sk_newlistener(char *srcaddr
, int port
, Plug plug
, int local_host_only
,
842 static const struct socket_function_table fn_table
= {
848 sk_tcp_set_private_ptr
,
849 sk_tcp_get_private_ptr
,
867 * Create Socket structure.
869 ret
= snew(struct Socket_tag
);
873 bufchain_init(&ret
->output_data
);
874 ret
->writable
= 0; /* to start with */
875 ret
->sending_oob
= 0;
877 ret
->frozen_readable
= 0;
878 ret
->localhost_only
= local_host_only
;
879 ret
->pending_error
= 0;
882 * Translate address_family from platform-independent constants
883 * into local reality.
885 address_family
= (address_family
== ADDRTYPE_IPV4 ? AF_INET
:
887 address_family
== ADDRTYPE_IPV6 ? AF_INET6
:
892 /* Let's default to IPv6, this shouldn't hurt anybody
893 * If the stack supports IPv6 it will also allow IPv4 connections. */
894 if (address_family
== AF_UNSPEC
) address_family
= AF_INET6
;
896 /* No other choice, default to IPv4 */
897 if (address_family
== AF_UNSPEC
) address_family
= AF_INET
;
903 s
= p_socket(address_family
, SOCK_STREAM
, 0);
906 if (s
== INVALID_SOCKET
) {
907 err
= p_WSAGetLastError();
908 ret
->error
= winsock_error_string(err
);
914 p_setsockopt(s
, SOL_SOCKET
, SO_REUSEADDR
, (const char *)&on
, sizeof(on
));
917 if (address_family
== AF_INET6
) {
918 memset(&a6
, 0, sizeof(a6
));
919 a6
.sin6_family
= AF_INET6
;
920 /* FIXME: srcaddr is ignored for IPv6, because I (SGT) don't
921 * know how to do it. :-)
922 * (jeroen:) saddr is specified as an address.. eg 2001:db8::1
923 * Thus we need either a parser that understands [2001:db8::1]:80
924 * style addresses and/or enhance this to understand hostnames too. */
926 a6
.sin6_addr
= in6addr_loopback
;
928 a6
.sin6_addr
= in6addr_any
;
929 a6
.sin6_port
= p_htons(port
);
934 a
.sin_family
= AF_INET
;
937 * Bind to source address. First try an explicitly
941 a
.sin_addr
.s_addr
= p_inet_addr(srcaddr
);
942 if (a
.sin_addr
.s_addr
!= INADDR_NONE
) {
943 /* Override localhost_only with specified listen addr. */
944 ret
->localhost_only
= ipv4_is_loopback(a
.sin_addr
);
950 * ... and failing that, go with one of the standard ones.
954 a
.sin_addr
.s_addr
= p_htonl(INADDR_LOOPBACK
);
956 a
.sin_addr
.s_addr
= p_htonl(INADDR_ANY
);
959 a
.sin_port
= p_htons((short)port
);
962 retcode
= p_bind(s
, (address_family
== AF_INET6 ?
963 (struct sockaddr
*) &a6
:
964 (struct sockaddr
*) &a
),
966 AF_INET6 ?
sizeof(a6
) : sizeof(a
)));
968 retcode
= p_bind(s
, (struct sockaddr
*) &a
, sizeof(a
));
970 if (retcode
!= SOCKET_ERROR
) {
973 err
= p_WSAGetLastError();
977 ret
->error
= winsock_error_string(err
);
982 if (p_listen(s
, SOMAXCONN
) == SOCKET_ERROR
) {
984 ret
->error
= winsock_error_string(err
);
988 /* Set up a select mechanism. This could be an AsyncSelect on a
989 * window, or an EventSelect on an event object. */
990 errstr
= do_select(s
, 1);
1001 static void sk_tcp_close(Socket sock
)
1003 extern char *do_select(SOCKET skt
, int startup
);
1004 Actual_Socket s
= (Actual_Socket
) sock
;
1008 p_closesocket(s
->s
);
1013 * The function which tries to send on a socket once it's deemed
1016 void try_send(Actual_Socket s
)
1018 while (s
->sending_oob
|| bufchain_size(&s
->output_data
) > 0) {
1022 int len
, urgentflag
;
1024 if (s
->sending_oob
) {
1025 urgentflag
= MSG_OOB
;
1026 len
= s
->sending_oob
;
1030 bufchain_prefix(&s
->output_data
, &data
, &len
);
1032 nsent
= p_send(s
->s
, data
, len
, urgentflag
);
1033 noise_ultralight(nsent
);
1035 err
= (nsent
< 0 ?
p_WSAGetLastError() : 0);
1036 if ((err
< WSABASEERR
&& nsent
< 0) || err
== WSAEWOULDBLOCK
) {
1038 * Perfectly normal: we've sent all we can for the moment.
1040 * (Some WinSock send() implementations can return
1041 * <0 but leave no sensible error indication -
1042 * WSAGetLastError() is called but returns zero or
1043 * a small number - so we check that case and treat
1044 * it just like WSAEWOULDBLOCK.)
1046 s
->writable
= FALSE
;
1048 } else if (nsent
== 0 ||
1049 err
== WSAECONNABORTED
|| err
== WSAECONNRESET
) {
1051 * If send() returns CONNABORTED or CONNRESET, we
1052 * unfortunately can't just call plug_closing(),
1053 * because it's quite likely that we're currently
1054 * _in_ a call from the code we'd be calling back
1055 * to, so we'd have to make half the SSH code
1056 * reentrant. Instead we flag a pending error on
1057 * the socket, to be dealt with (by calling
1058 * plug_closing()) at some suitable future moment.
1060 s
->pending_error
= err
;
1063 /* We're inside the Windows frontend here, so we know
1064 * that the frontend handle is unnecessary. */
1065 logevent(NULL
, winsock_error_string(err
));
1066 fatalbox("%s", winsock_error_string(err
));
1069 if (s
->sending_oob
) {
1071 memmove(s
->oobdata
, s
->oobdata
+nsent
, len
-nsent
);
1072 s
->sending_oob
= len
- nsent
;
1077 bufchain_consume(&s
->output_data
, nsent
);
1083 static int sk_tcp_write(Socket sock
, const char *buf
, int len
)
1085 Actual_Socket s
= (Actual_Socket
) sock
;
1088 * Add the data to the buffer list on the socket.
1090 bufchain_add(&s
->output_data
, buf
, len
);
1093 * Now try sending from the start of the buffer list.
1098 return bufchain_size(&s
->output_data
);
1101 static int sk_tcp_write_oob(Socket sock
, const char *buf
, int len
)
1103 Actual_Socket s
= (Actual_Socket
) sock
;
1106 * Replace the buffer list on the socket with the data.
1108 bufchain_clear(&s
->output_data
);
1109 assert(len
<= sizeof(s
->oobdata
));
1110 memcpy(s
->oobdata
, buf
, len
);
1111 s
->sending_oob
= len
;
1114 * Now try sending from the start of the buffer list.
1119 return s
->sending_oob
;
1122 int select_result(WPARAM wParam
, LPARAM lParam
)
1126 char buf
[20480]; /* nice big buffer for plenty of speed */
1130 /* wParam is the socket itself */
1133 return 1; /* boggle */
1135 s
= find234(sktree
, (void *) wParam
, cmpforsearch
);
1137 return 1; /* boggle */
1139 if ((err
= WSAGETSELECTERROR(lParam
)) != 0) {
1141 * An error has occurred on this socket. Pass it to the
1144 return plug_closing(s
->plug
, winsock_error_string(err
), err
, 0);
1147 noise_ultralight(lParam
);
1149 switch (WSAGETSELECTEVENT(lParam
)) {
1151 s
->connected
= s
->writable
= 1;
1154 /* In the case the socket is still frozen, we don't even bother */
1156 s
->frozen_readable
= 1;
1161 * We have received data on the socket. For an oobinline
1162 * socket, this might be data _before_ an urgent pointer,
1163 * in which case we send it to the back end with type==1
1164 * (data prior to urgent).
1168 p_ioctlsocket(s
->s
, SIOCATMARK
, &atmark
);
1170 * Avoid checking the return value from ioctlsocket(),
1171 * on the grounds that some WinSock wrappers don't
1172 * support it. If it does nothing, we get atmark==1,
1173 * which is equivalent to `no OOB pending', so the
1174 * effect will be to non-OOB-ify any OOB data.
1179 ret
= p_recv(s
->s
, buf
, sizeof(buf
), 0);
1180 noise_ultralight(ret
);
1182 err
= p_WSAGetLastError();
1183 if (err
== WSAEWOULDBLOCK
) {
1188 return plug_closing(s
->plug
, winsock_error_string(err
), err
,
1190 } else if (0 == ret
) {
1191 return plug_closing(s
->plug
, NULL
, 0, 0);
1193 return plug_receive(s
->plug
, atmark ?
0 : 1, buf
, ret
);
1198 * This will only happen on a non-oobinline socket. It
1199 * indicates that we can immediately perform an OOB read
1200 * and get back OOB data, which we will send to the back
1201 * end with type==2 (urgent data).
1203 ret
= p_recv(s
->s
, buf
, sizeof(buf
), MSG_OOB
);
1204 noise_ultralight(ret
);
1206 char *str
= (ret
== 0 ?
"Internal networking trouble" :
1207 winsock_error_string(p_WSAGetLastError()));
1208 /* We're inside the Windows frontend here, so we know
1209 * that the frontend handle is unnecessary. */
1210 logevent(NULL
, str
);
1211 fatalbox("%s", str
);
1213 return plug_receive(s
->plug
, 2, buf
, ret
);
1218 int bufsize_before
, bufsize_after
;
1220 bufsize_before
= s
->sending_oob
+ bufchain_size(&s
->output_data
);
1222 bufsize_after
= s
->sending_oob
+ bufchain_size(&s
->output_data
);
1223 if (bufsize_after
< bufsize_before
)
1224 plug_sent(s
->plug
, bufsize_after
);
1228 /* Signal a close on the socket. First read any outstanding data. */
1231 ret
= p_recv(s
->s
, buf
, sizeof(buf
), 0);
1233 err
= p_WSAGetLastError();
1234 if (err
== WSAEWOULDBLOCK
)
1236 return plug_closing(s
->plug
, winsock_error_string(err
),
1240 open
&= plug_receive(s
->plug
, 0, buf
, ret
);
1242 open
&= plug_closing(s
->plug
, NULL
, 0, 0);
1249 struct sockaddr_in isa
;
1251 struct sockaddr_storage isa
;
1253 int addrlen
= sizeof(isa
);
1254 SOCKET t
; /* socket of connection */
1256 memset(&isa
, 0, sizeof(isa
));
1258 t
= p_accept(s
->s
,(struct sockaddr
*)&isa
,&addrlen
);
1259 if (t
== INVALID_SOCKET
)
1261 err
= p_WSAGetLastError();
1262 if (err
== WSATRY_AGAIN
)
1266 if (isa
.ss_family
== AF_INET
&&
1267 s
->localhost_only
&&
1268 !ipv4_is_local_addr(((struct sockaddr_in
*)&isa
)->sin_addr
)) {
1270 if (s
->localhost_only
&& !ipv4_is_local_addr(isa
.sin_addr
)) {
1272 p_closesocket(t
); /* dodgy WinSock let nonlocal through */
1273 } else if (plug_accepting(s
->plug
, (void*)t
)) {
1274 p_closesocket(t
); /* denied or error */
1283 * Deal with socket errors detected in try_send().
1285 void net_pending_errors(void)
1291 * This might be a fiddly business, because it's just possible
1292 * that handling a pending error on one socket might cause
1293 * others to be closed. (I can't think of any reason this might
1294 * happen in current SSH implementation, but to maintain
1295 * generality of this network layer I'll assume the worst.)
1297 * So what we'll do is search the socket list for _one_ socket
1298 * with a pending error, and then handle it, and then search
1299 * the list again _from the beginning_. Repeat until we make a
1300 * pass with no socket errors present. That way we are
1301 * protected against the socket list changing under our feet.
1305 for (i
= 0; (s
= index234(sktree
, i
)) != NULL
; i
++) {
1306 if (s
->pending_error
) {
1308 * An error has occurred on this socket. Pass it to the
1311 plug_closing(s
->plug
,
1312 winsock_error_string(s
->pending_error
),
1313 s
->pending_error
, 0);
1321 * Each socket abstraction contains a `void *' private field in
1322 * which the client can keep state.
1324 static void sk_tcp_set_private_ptr(Socket sock
, void *ptr
)
1326 Actual_Socket s
= (Actual_Socket
) sock
;
1327 s
->private_ptr
= ptr
;
1330 static void *sk_tcp_get_private_ptr(Socket sock
)
1332 Actual_Socket s
= (Actual_Socket
) sock
;
1333 return s
->private_ptr
;
1337 * Special error values are returned from sk_namelookup and sk_new
1338 * if there's a problem. These functions extract an error message,
1339 * or return NULL if there's no problem.
1341 const char *sk_addr_error(SockAddr addr
)
1345 static const char *sk_tcp_socket_error(Socket sock
)
1347 Actual_Socket s
= (Actual_Socket
) sock
;
1351 static void sk_tcp_set_frozen(Socket sock
, int is_frozen
)
1353 Actual_Socket s
= (Actual_Socket
) sock
;
1354 if (s
->frozen
== is_frozen
)
1356 s
->frozen
= is_frozen
;
1357 if (!is_frozen
&& s
->frozen_readable
) {
1359 p_recv(s
->s
, &c
, 1, MSG_PEEK
);
1361 s
->frozen_readable
= 0;
1365 * For Plink: enumerate all sockets currently active.
1367 SOCKET
first_socket(int *state
)
1371 s
= index234(sktree
, (*state
)++);
1372 return s ? s
->s
: INVALID_SOCKET
;
1375 SOCKET
next_socket(int *state
)
1377 Actual_Socket s
= index234(sktree
, (*state
)++);
1378 return s ? s
->s
: INVALID_SOCKET
;
1381 extern int socket_writable(SOCKET skt
)
1383 Actual_Socket s
= find234(sktree
, (void *)skt
, cmpforsearch
);
1386 return bufchain_size(&s
->output_data
) > 0;
1391 int net_service_lookup(char *service
)
1394 se
= p_getservbyname(service
, NULL
);
1396 return p_ntohs(se
->s_port
);
1401 SockAddr
platform_get_x11_unix_address(int displaynum
, char **canonicalname
)
1403 SockAddr ret
= snew(struct SockAddr_tag
);
1404 memset(ret
, 0, sizeof(struct SockAddr_tag
));
1405 ret
->error
= "unix sockets not supported on this platform";