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 * Mutable state that goes with a SockAddr: stores information
39 * about where in the list of candidate IP(v*) addresses we've
42 typedef struct SockAddrStep_tag SockAddrStep
;
43 struct SockAddrStep_tag
{
45 struct addrinfo
*ai
; /* steps along addr->ais */
51 const struct socket_function_table
*fn
;
52 /* the above variable absolutely *must* be the first in this structure */
60 int frozen
; /* this causes readability notifications to be ignored */
61 int frozen_readable
; /* this means we missed at least one readability
62 * notification while we were frozen */
63 int localhost_only
; /* for listening sockets */
66 int oobinline
, nodelay
, keepalive
, privport
;
70 int pending_error
; /* in case send() returns error */
72 * We sometimes need pairs of Socket structures to be linked:
73 * if we are listening on the same IPv6 and v4 port, for
74 * example. So here we define `parent' and `child' pointers to
77 Actual_Socket parent
, child
;
85 struct addrinfo
*ais
; /* Addresses IPv6 style. */
87 unsigned long *addresses
; /* Addresses IPv4 style. */
89 char hostname
[512]; /* Store an unresolved host name. */
93 * Which address family this address belongs to. AF_INET for IPv4;
94 * AF_INET6 for IPv6; AF_UNSPEC indicates that name resolution has
95 * not been done and a simple host name is held in this SockAddr
99 #define SOCKADDR_FAMILY(addr, step) \
100 (!(addr)->resolved ? AF_UNSPEC : \
101 (step).ai ? (step).ai->ai_family : AF_INET)
103 #define SOCKADDR_FAMILY(addr, step) \
104 (!(addr)->resolved ? AF_UNSPEC : AF_INET)
108 * Start a SockAddrStep structure to step through multiple
112 #define START_STEP(addr, step) \
113 ((step).ai = (addr)->ais, (step).curraddr = 0)
115 #define START_STEP(addr, step) \
116 ((step).curraddr = 0)
119 static tree234
*sktree
;
121 static int cmpfortree(void *av
, void *bv
)
123 Actual_Socket a
= (Actual_Socket
) av
, b
= (Actual_Socket
) bv
;
124 unsigned long as
= (unsigned long) a
->s
, bs
= (unsigned long) b
->s
;
136 static int cmpforsearch(void *av
, void *bv
)
138 Actual_Socket b
= (Actual_Socket
) bv
;
139 unsigned long as
= (unsigned long) av
, bs
= (unsigned long) b
->s
;
148 #define DECL_WINSOCK_FUNCTION(linkage, rettype, name, params) \
149 typedef rettype (WINAPI *t_##name) params; \
150 linkage t_##name p_##name
151 #define GET_WINSOCK_FUNCTION(module, name) \
152 p_##name = module ? (t_##name) GetProcAddress(module, #name) : NULL
154 DECL_WINSOCK_FUNCTION(NOTHING
, int, WSAAsyncSelect
,
155 (SOCKET
, HWND
, u_int
, long));
156 DECL_WINSOCK_FUNCTION(NOTHING
, int, WSAEventSelect
, (SOCKET
, WSAEVENT
, long));
157 DECL_WINSOCK_FUNCTION(NOTHING
, int, select
,
158 (int, fd_set FAR
*, fd_set FAR
*,
159 fd_set FAR
*, const struct timeval FAR
*));
160 DECL_WINSOCK_FUNCTION(NOTHING
, int, WSAGetLastError
, (void));
161 DECL_WINSOCK_FUNCTION(NOTHING
, int, WSAEnumNetworkEvents
,
162 (SOCKET
, WSAEVENT
, LPWSANETWORKEVENTS
));
163 DECL_WINSOCK_FUNCTION(static, int, WSAStartup
, (WORD
, LPWSADATA
));
164 DECL_WINSOCK_FUNCTION(static, int, WSACleanup
, (void));
165 DECL_WINSOCK_FUNCTION(static, int, closesocket
, (SOCKET
));
166 DECL_WINSOCK_FUNCTION(static, u_long
, ntohl
, (u_long
));
167 DECL_WINSOCK_FUNCTION(static, u_long
, htonl
, (u_long
));
168 DECL_WINSOCK_FUNCTION(static, u_short
, htons
, (u_short
));
169 DECL_WINSOCK_FUNCTION(static, u_short
, ntohs
, (u_short
));
170 DECL_WINSOCK_FUNCTION(static, int, gethostname
, (char *, int));
171 DECL_WINSOCK_FUNCTION(static, struct hostent FAR
*, gethostbyname
,
173 DECL_WINSOCK_FUNCTION(static, struct servent FAR
*, getservbyname
,
174 (const char FAR
*, const char FAR
*));
175 DECL_WINSOCK_FUNCTION(static, unsigned long, inet_addr
, (const char FAR
*));
176 DECL_WINSOCK_FUNCTION(static, char FAR
*, inet_ntoa
, (struct in_addr
));
177 DECL_WINSOCK_FUNCTION(static, int, connect
,
178 (SOCKET
, const struct sockaddr FAR
*, int));
179 DECL_WINSOCK_FUNCTION(static, int, bind
,
180 (SOCKET
, const struct sockaddr FAR
*, int));
181 DECL_WINSOCK_FUNCTION(static, int, setsockopt
,
182 (SOCKET
, int, int, const char FAR
*, int));
183 DECL_WINSOCK_FUNCTION(static, SOCKET
, socket
, (int, int, int));
184 DECL_WINSOCK_FUNCTION(static, int, listen
, (SOCKET
, int));
185 DECL_WINSOCK_FUNCTION(static, int, send
, (SOCKET
, const char FAR
*, int, int));
186 DECL_WINSOCK_FUNCTION(static, int, ioctlsocket
,
187 (SOCKET
, long, u_long FAR
*));
188 DECL_WINSOCK_FUNCTION(static, SOCKET
, accept
,
189 (SOCKET
, struct sockaddr FAR
*, int FAR
*));
190 DECL_WINSOCK_FUNCTION(static, int, recv
, (SOCKET
, char FAR
*, int, int));
191 DECL_WINSOCK_FUNCTION(static, int, WSAIoctl
,
192 (SOCKET
, DWORD
, LPVOID
, DWORD
, LPVOID
, DWORD
,
193 LPDWORD
, LPWSAOVERLAPPED
,
194 LPWSAOVERLAPPED_COMPLETION_ROUTINE
));
196 DECL_WINSOCK_FUNCTION(static, int, getaddrinfo
,
197 (const char *nodename
, const char *servname
,
198 const struct addrinfo
*hints
, struct addrinfo
**res
));
199 DECL_WINSOCK_FUNCTION(static, void, freeaddrinfo
, (struct addrinfo
*res
));
200 DECL_WINSOCK_FUNCTION(static, int, getnameinfo
,
201 (const struct sockaddr FAR
* sa
, socklen_t salen
,
202 char FAR
* host
, size_t hostlen
, char FAR
* serv
,
203 size_t servlen
, int flags
));
204 DECL_WINSOCK_FUNCTION(static, char *, gai_strerror
, (int ecode
));
205 DECL_WINSOCK_FUNCTION(static, int, WSAAddressToStringA
,
206 (LPSOCKADDR
, DWORD
, LPWSAPROTOCOL_INFO
,
210 static HMODULE winsock_module
= NULL
;
211 static WSADATA wsadata
;
213 static HMODULE winsock2_module
= NULL
;
214 static HMODULE wship6_module
= NULL
;
217 int sk_startup(int hi
, int lo
)
221 winsock_ver
= MAKEWORD(hi
, lo
);
223 if (p_WSAStartup(winsock_ver
, &wsadata
)) {
227 if (LOBYTE(wsadata
.wVersion
) != LOBYTE(winsock_ver
)) {
231 #ifdef NET_SETUP_DIAGNOSTICS
234 sprintf(buf
, "Using WinSock %d.%d", hi
, lo
);
246 winsock_module
= LoadLibrary("WS2_32.DLL");
247 if (!winsock_module
) {
248 winsock_module
= LoadLibrary("WSOCK32.DLL");
251 fatalbox("Unable to load any WinSock library");
254 /* Check if we have getaddrinfo in Winsock */
255 if (GetProcAddress(winsock_module
, "getaddrinfo") != NULL
) {
256 #ifdef NET_SETUP_DIAGNOSTICS
257 logevent(NULL
, "Native WinSock IPv6 support detected");
259 GET_WINSOCK_FUNCTION(winsock_module
, getaddrinfo
);
260 GET_WINSOCK_FUNCTION(winsock_module
, freeaddrinfo
);
261 GET_WINSOCK_FUNCTION(winsock_module
, getnameinfo
);
262 GET_WINSOCK_FUNCTION(winsock_module
, gai_strerror
);
264 /* Fall back to wship6.dll for Windows 2000 */
265 wship6_module
= LoadLibrary("wship6.dll");
267 #ifdef NET_SETUP_DIAGNOSTICS
268 logevent(NULL
, "WSH IPv6 support detected");
270 GET_WINSOCK_FUNCTION(wship6_module
, getaddrinfo
);
271 GET_WINSOCK_FUNCTION(wship6_module
, freeaddrinfo
);
272 GET_WINSOCK_FUNCTION(wship6_module
, getnameinfo
);
273 GET_WINSOCK_FUNCTION(wship6_module
, gai_strerror
);
275 #ifdef NET_SETUP_DIAGNOSTICS
276 logevent(NULL
, "No IPv6 support detected");
280 GET_WINSOCK_FUNCTION(winsock2_module
, WSAAddressToStringA
);
282 #ifdef NET_SETUP_DIAGNOSTICS
283 logevent(NULL
, "PuTTY was built without IPv6 support");
287 GET_WINSOCK_FUNCTION(winsock_module
, WSAAsyncSelect
);
288 GET_WINSOCK_FUNCTION(winsock_module
, WSAEventSelect
);
289 GET_WINSOCK_FUNCTION(winsock_module
, select
);
290 GET_WINSOCK_FUNCTION(winsock_module
, WSAGetLastError
);
291 GET_WINSOCK_FUNCTION(winsock_module
, WSAEnumNetworkEvents
);
292 GET_WINSOCK_FUNCTION(winsock_module
, WSAStartup
);
293 GET_WINSOCK_FUNCTION(winsock_module
, WSACleanup
);
294 GET_WINSOCK_FUNCTION(winsock_module
, closesocket
);
295 GET_WINSOCK_FUNCTION(winsock_module
, ntohl
);
296 GET_WINSOCK_FUNCTION(winsock_module
, htonl
);
297 GET_WINSOCK_FUNCTION(winsock_module
, htons
);
298 GET_WINSOCK_FUNCTION(winsock_module
, ntohs
);
299 GET_WINSOCK_FUNCTION(winsock_module
, gethostname
);
300 GET_WINSOCK_FUNCTION(winsock_module
, gethostbyname
);
301 GET_WINSOCK_FUNCTION(winsock_module
, getservbyname
);
302 GET_WINSOCK_FUNCTION(winsock_module
, inet_addr
);
303 GET_WINSOCK_FUNCTION(winsock_module
, inet_ntoa
);
304 GET_WINSOCK_FUNCTION(winsock_module
, connect
);
305 GET_WINSOCK_FUNCTION(winsock_module
, bind
);
306 GET_WINSOCK_FUNCTION(winsock_module
, setsockopt
);
307 GET_WINSOCK_FUNCTION(winsock_module
, socket
);
308 GET_WINSOCK_FUNCTION(winsock_module
, listen
);
309 GET_WINSOCK_FUNCTION(winsock_module
, send
);
310 GET_WINSOCK_FUNCTION(winsock_module
, ioctlsocket
);
311 GET_WINSOCK_FUNCTION(winsock_module
, accept
);
312 GET_WINSOCK_FUNCTION(winsock_module
, recv
);
313 GET_WINSOCK_FUNCTION(winsock_module
, WSAIoctl
);
315 /* Try to get the best WinSock version we can get */
316 if (!sk_startup(2,2) &&
319 fatalbox("Unable to initialise WinSock");
322 sktree
= newtree234(cmpfortree
);
325 void sk_cleanup(void)
331 for (i
= 0; (s
= index234(sktree
, i
)) != NULL
; i
++) {
341 FreeLibrary(winsock_module
);
344 FreeLibrary(wship6_module
);
348 char *winsock_error_string(int error
)
352 return "Network error: Permission denied";
354 return "Network error: Address already in use";
355 case WSAEADDRNOTAVAIL
:
356 return "Network error: Cannot assign requested address";
357 case WSAEAFNOSUPPORT
:
359 "Network error: Address family not supported by protocol family";
361 return "Network error: Operation already in progress";
362 case WSAECONNABORTED
:
363 return "Network error: Software caused connection abort";
364 case WSAECONNREFUSED
:
365 return "Network error: Connection refused";
367 return "Network error: Connection reset by peer";
368 case WSAEDESTADDRREQ
:
369 return "Network error: Destination address required";
371 return "Network error: Bad address";
373 return "Network error: Host is down";
374 case WSAEHOSTUNREACH
:
375 return "Network error: No route to host";
377 return "Network error: Operation now in progress";
379 return "Network error: Interrupted function call";
381 return "Network error: Invalid argument";
383 return "Network error: Socket is already connected";
385 return "Network error: Too many open files";
387 return "Network error: Message too long";
389 return "Network error: Network is down";
391 return "Network error: Network dropped connection on reset";
393 return "Network error: Network is unreachable";
395 return "Network error: No buffer space available";
397 return "Network error: Bad protocol option";
399 return "Network error: Socket is not connected";
401 return "Network error: Socket operation on non-socket";
403 return "Network error: Operation not supported";
404 case WSAEPFNOSUPPORT
:
405 return "Network error: Protocol family not supported";
407 return "Network error: Too many processes";
408 case WSAEPROTONOSUPPORT
:
409 return "Network error: Protocol not supported";
411 return "Network error: Protocol wrong type for socket";
413 return "Network error: Cannot send after socket shutdown";
414 case WSAESOCKTNOSUPPORT
:
415 return "Network error: Socket type not supported";
417 return "Network error: Connection timed out";
419 return "Network error: Resource temporarily unavailable";
421 return "Network error: Graceful shutdown in progress";
423 return "Unknown network error";
427 SockAddr
sk_namelookup(const char *host
, char **canonicalname
,
430 SockAddr ret
= snew(struct SockAddr_tag
);
432 struct hostent
*h
= NULL
;
437 /* Default to IPv4. */
438 hint_family
= (address_family
== ADDRTYPE_IPV4 ? AF_INET
:
440 address_family
== ADDRTYPE_IPV6 ? AF_INET6
:
444 /* Clear the structure and default to IPv4. */
445 memset(ret
, 0, sizeof(struct SockAddr_tag
));
449 ret
->addresses
= NULL
;
450 ret
->resolved
= FALSE
;
454 if ((a
= p_inet_addr(host
)) == (unsigned long) INADDR_NONE
) {
457 * Use getaddrinfo when it's available
460 struct addrinfo hints
;
461 #ifdef NET_SETUP_DIAGNOSTICS
462 logevent(NULL
, "Using getaddrinfo() for resolving");
464 memset(&hints
, 0, sizeof(hints
));
465 hints
.ai_family
= hint_family
;
466 hints
.ai_flags
= AI_CANONNAME
;
467 if ((err
= p_getaddrinfo(host
, NULL
, &hints
, &ret
->ais
)) == 0)
468 ret
->resolved
= TRUE
;
472 #ifdef NET_SETUP_DIAGNOSTICS
473 logevent(NULL
, "Using gethostbyname() for resolving");
476 * Otherwise use the IPv4-only gethostbyname...
477 * (NOTE: we don't use gethostbyname as a fallback!)
479 if ( (h
= p_gethostbyname(host
)) )
480 ret
->resolved
= TRUE
;
482 err
= p_WSAGetLastError();
485 if (!ret
->resolved
) {
486 ret
->error
= (err
== WSAENETDOWN ?
"Network is down" :
487 err
== WSAHOST_NOT_FOUND ?
"Host does not exist" :
488 err
== WSATRY_AGAIN ?
"Host not found" :
490 p_getaddrinfo
&&p_gai_strerror ?
p_gai_strerror(err
) :
492 "gethostbyname: unknown error");
497 /* If we got an address info use that... */
499 /* Are we in IPv4 fallback mode? */
500 /* We put the IPv4 address into the a variable so we can further-on use the IPv4 code... */
501 if (ret
->ais
->ai_family
== AF_INET
)
503 (char *) &((SOCKADDR_IN
*) ret
->ais
->
504 ai_addr
)->sin_addr
, sizeof(a
));
506 if (ret
->ais
->ai_canonname
)
507 strncpy(realhost
, ret
->ais
->ai_canonname
, lenof(realhost
));
509 strncpy(realhost
, host
, lenof(realhost
));
511 /* We used the IPv4-only gethostbyname()... */
516 for (n
= 0; h
->h_addr_list
[n
]; n
++);
517 ret
->addresses
= snewn(n
, unsigned long);
519 for (n
= 0; n
< ret
->naddresses
; n
++) {
520 memcpy(&a
, h
->h_addr_list
[n
], sizeof(a
));
521 ret
->addresses
[n
] = p_ntohl(a
);
523 memcpy(&a
, h
->h_addr
, sizeof(a
));
524 /* This way we are always sure the h->h_name is valid :) */
525 strncpy(realhost
, h
->h_name
, sizeof(realhost
));
530 * This must be a numeric IPv4 address because it caused a
531 * success return from inet_addr.
533 ret
->addresses
= snewn(1, unsigned long);
535 ret
->addresses
[0] = p_ntohl(a
);
536 ret
->resolved
= TRUE
;
537 strncpy(realhost
, host
, sizeof(realhost
));
539 realhost
[lenof(realhost
)-1] = '\0';
540 *canonicalname
= snewn(1+strlen(realhost
), char);
541 strcpy(*canonicalname
, realhost
);
545 SockAddr
sk_nonamelookup(const char *host
)
547 SockAddr ret
= snew(struct SockAddr_tag
);
549 ret
->resolved
= FALSE
;
553 ret
->addresses
= NULL
;
556 strncpy(ret
->hostname
, host
, lenof(ret
->hostname
));
557 ret
->hostname
[lenof(ret
->hostname
)-1] = '\0';
561 int sk_nextaddr(SockAddr addr
, SockAddrStep
*step
)
565 if (step
->ai
->ai_next
) {
566 step
->ai
= step
->ai
->ai_next
;
572 if (step
->curraddr
+1 < addr
->naddresses
) {
580 void sk_getaddr(SockAddr addr
, char *buf
, int buflen
)
583 START_STEP(addr
, step
);
587 if (p_WSAAddressToStringA
) {
588 p_WSAAddressToStringA(step
.ai
->ai_addr
, step
.ai
->ai_addrlen
,
591 strncpy(buf
, "IPv6", buflen
);
594 if (SOCKADDR_FAMILY(addr
, step
) == AF_INET
) {
596 assert(addr
->addresses
&& step
.curraddr
< addr
->naddresses
);
597 a
.s_addr
= p_htonl(addr
->addresses
[step
.curraddr
]);
598 strncpy(buf
, p_inet_ntoa(a
), buflen
);
599 buf
[buflen
-1] = '\0';
601 strncpy(buf
, addr
->hostname
, buflen
);
602 buf
[buflen
-1] = '\0';
606 int sk_hostname_is_local(char *name
)
608 return !strcmp(name
, "localhost") ||
609 !strcmp(name
, "::1") ||
610 !strncmp(name
, "127.", 4);
613 static INTERFACE_INFO local_interfaces
[16];
614 static int n_local_interfaces
; /* 0=not yet, -1=failed, >0=number */
616 static int ipv4_is_local_addr(struct in_addr addr
)
618 if (ipv4_is_loopback(addr
))
619 return 1; /* loopback addresses are local */
620 if (!n_local_interfaces
) {
621 SOCKET s
= p_socket(AF_INET
, SOCK_DGRAM
, 0);
625 p_WSAIoctl(s
, SIO_GET_INTERFACE_LIST
, NULL
, 0,
626 local_interfaces
, sizeof(local_interfaces
),
627 &retbytes
, NULL
, NULL
) == 0)
628 n_local_interfaces
= retbytes
/ sizeof(INTERFACE_INFO
);
630 logevent(NULL
, "Unable to get list of local IP addresses");
632 if (n_local_interfaces
> 0) {
634 for (i
= 0; i
< n_local_interfaces
; i
++) {
635 SOCKADDR_IN
*address
=
636 (SOCKADDR_IN
*)&local_interfaces
[i
].iiAddress
;
637 if (address
->sin_addr
.s_addr
== addr
.s_addr
)
638 return 1; /* this address is local */
641 return 0; /* this address is not local */
644 int sk_address_is_local(SockAddr addr
)
648 START_STEP(addr
, step
);
649 family
= SOCKADDR_FAMILY(addr
, step
);
652 if (family
== AF_INET6
) {
653 return IN6_IS_ADDR_LOOPBACK((const struct in6_addr
*)step
.ai
->ai_addr
);
656 if (family
== AF_INET
) {
659 return ipv4_is_local_addr(((struct sockaddr_in
*)step
.ai
->ai_addr
)
665 assert(addr
->addresses
&& step
.curraddr
< addr
->naddresses
);
666 a
.s_addr
= p_htonl(addr
->addresses
[step
.curraddr
]);
667 return ipv4_is_local_addr(a
);
670 assert(family
== AF_UNSPEC
);
671 return 0; /* we don't know; assume not */
675 int sk_addrtype(SockAddr addr
)
679 START_STEP(addr
, step
);
680 family
= SOCKADDR_FAMILY(addr
, step
);
682 return (family
== AF_INET ? ADDRTYPE_IPV4
:
684 family
== AF_INET6 ? ADDRTYPE_IPV6
:
689 void sk_addrcopy(SockAddr addr
, char *buf
)
693 START_STEP(addr
, step
);
694 family
= SOCKADDR_FAMILY(addr
, step
);
696 assert(family
!= AF_UNSPEC
);
699 if (family
== AF_INET
)
700 memcpy(buf
, &((struct sockaddr_in
*)step
.ai
->ai_addr
)->sin_addr
,
701 sizeof(struct in_addr
));
702 else if (family
== AF_INET6
)
703 memcpy(buf
, &((struct sockaddr_in6
*)step
.ai
->ai_addr
)->sin6_addr
,
704 sizeof(struct in6_addr
));
709 if (family
== AF_INET
) {
711 assert(addr
->addresses
&& step
.curraddr
< addr
->naddresses
);
712 a
.s_addr
= p_htonl(addr
->addresses
[step
.curraddr
]);
713 memcpy(buf
, (char*) &a
.s_addr
, 4);
717 void sk_addr_free(SockAddr addr
)
719 if (--addr
->refcount
> 0)
722 if (addr
->ais
&& p_freeaddrinfo
)
723 p_freeaddrinfo(addr
->ais
);
726 sfree(addr
->addresses
);
730 SockAddr
sk_addr_dup(SockAddr addr
)
736 static Plug
sk_tcp_plug(Socket sock
, Plug p
)
738 Actual_Socket s
= (Actual_Socket
) sock
;
745 static void sk_tcp_flush(Socket s
)
748 * We send data to the socket as soon as we can anyway,
749 * so we don't need to do anything here. :-)
753 static void sk_tcp_close(Socket s
);
754 static int sk_tcp_write(Socket s
, const char *data
, int len
);
755 static int sk_tcp_write_oob(Socket s
, const char *data
, int len
);
756 static void sk_tcp_set_private_ptr(Socket s
, void *ptr
);
757 static void *sk_tcp_get_private_ptr(Socket s
);
758 static void sk_tcp_set_frozen(Socket s
, int is_frozen
);
759 static const char *sk_tcp_socket_error(Socket s
);
761 extern char *do_select(SOCKET skt
, int startup
);
763 Socket
sk_register(void *sock
, Plug plug
)
765 static const struct socket_function_table fn_table
= {
771 sk_tcp_set_private_ptr
,
772 sk_tcp_get_private_ptr
,
782 * Create Socket structure.
784 ret
= snew(struct Socket_tag
);
788 bufchain_init(&ret
->output_data
);
789 ret
->writable
= 1; /* to start with */
790 ret
->sending_oob
= 0;
792 ret
->frozen_readable
= 0;
793 ret
->localhost_only
= 0; /* unused, but best init anyway */
794 ret
->pending_error
= 0;
795 ret
->parent
= ret
->child
= NULL
;
798 ret
->s
= (SOCKET
)sock
;
800 if (ret
->s
== INVALID_SOCKET
) {
801 err
= p_WSAGetLastError();
802 ret
->error
= winsock_error_string(err
);
808 /* Set up a select mechanism. This could be an AsyncSelect on a
809 * window, or an EventSelect on an event object. */
810 errstr
= do_select(ret
->s
, 1);
821 static DWORD
try_connect(Actual_Socket sock
)
833 if (sock
->s
!= INVALID_SOCKET
) {
834 do_select(sock
->s
, 0);
835 p_closesocket(sock
->s
);
838 plug_log(sock
->plug
, 0, sock
->addr
, sock
->port
, NULL
, 0);
843 family
= SOCKADDR_FAMILY(sock
->addr
, sock
->step
);
846 * Remove the socket from the tree before we overwrite its
847 * internal socket id, because that forms part of the tree's
848 * sorting criterion. We'll add it back before exiting this
849 * function, whether we changed anything or not.
851 del234(sktree
, sock
);
853 s
= p_socket(family
, SOCK_STREAM
, 0);
856 if (s
== INVALID_SOCKET
) {
857 err
= p_WSAGetLastError();
858 sock
->error
= winsock_error_string(err
);
862 if (sock
->oobinline
) {
864 p_setsockopt(s
, SOL_SOCKET
, SO_OOBINLINE
, (void *) &b
, sizeof(b
));
869 p_setsockopt(s
, IPPROTO_TCP
, TCP_NODELAY
, (void *) &b
, sizeof(b
));
872 if (sock
->keepalive
) {
874 p_setsockopt(s
, SOL_SOCKET
, SO_KEEPALIVE
, (void *) &b
, sizeof(b
));
878 * Bind to local address.
881 localport
= 1023; /* count from 1023 downwards */
883 localport
= 0; /* just use port 0 (ie winsock picks) */
885 /* Loop round trying to bind */
890 if (family
== AF_INET6
) {
891 memset(&a6
, 0, sizeof(a6
));
892 a6
.sin6_family
= AF_INET6
;
893 /*a6.sin6_addr = in6addr_any; */ /* == 0 done by memset() */
894 a6
.sin6_port
= p_htons(localport
);
898 a
.sin_family
= AF_INET
;
899 a
.sin_addr
.s_addr
= p_htonl(INADDR_ANY
);
900 a
.sin_port
= p_htons(localport
);
903 sockcode
= p_bind(s
, (family
== AF_INET6 ?
904 (struct sockaddr
*) &a6
:
905 (struct sockaddr
*) &a
),
906 (family
== AF_INET6 ?
sizeof(a6
) : sizeof(a
)));
908 sockcode
= p_bind(s
, (struct sockaddr
*) &a
, sizeof(a
));
910 if (sockcode
!= SOCKET_ERROR
) {
914 err
= p_WSAGetLastError();
915 if (err
!= WSAEADDRINUSE
) /* failed, for a bad reason */
920 break; /* we're only looping once */
923 break; /* we might have got to the end */
927 sock
->error
= winsock_error_string(err
);
932 * Connect to remote address.
936 if (family
== AF_INET6
) {
937 a6
.sin6_family
= AF_INET6
;
938 a6
.sin6_port
= p_htons((short) sock
->port
);
940 ((struct sockaddr_in6
*) sock
->step
.ai
->ai_addr
)->sin6_addr
;
941 a6
.sin6_flowinfo
= ((struct sockaddr_in6
*) sock
->step
.ai
->ai_addr
)->sin6_flowinfo
;
942 a6
.sin6_scope_id
= ((struct sockaddr_in6
*) sock
->step
.ai
->ai_addr
)->sin6_scope_id
;
944 a
.sin_family
= AF_INET
;
946 ((struct sockaddr_in
*) sock
->step
.ai
->ai_addr
)->sin_addr
;
947 a
.sin_port
= p_htons((short) sock
->port
);
952 assert(sock
->addr
->addresses
&& sock
->step
.curraddr
< sock
->addr
->naddresses
);
953 a
.sin_family
= AF_INET
;
954 a
.sin_addr
.s_addr
= p_htonl(sock
->addr
->addresses
[sock
->step
.curraddr
]);
955 a
.sin_port
= p_htons((short) sock
->port
);
958 /* Set up a select mechanism. This could be an AsyncSelect on a
959 * window, or an EventSelect on an event object. */
960 errstr
= do_select(s
, 1);
962 sock
->error
= errstr
;
970 ((family
== AF_INET6
) ?
(struct sockaddr
*) &a6
:
971 (struct sockaddr
*) &a
),
972 (family
== AF_INET6
) ?
sizeof(a6
) : sizeof(a
))
974 p_connect(s
, (struct sockaddr
*) &a
, sizeof(a
))
977 err
= p_WSAGetLastError();
979 * We expect a potential EWOULDBLOCK here, because the
980 * chances are the front end has done a select for
981 * FD_CONNECT, so that connect() will complete
984 if ( err
!= WSAEWOULDBLOCK
) {
985 sock
->error
= winsock_error_string(err
);
990 * If we _don't_ get EWOULDBLOCK, the connect has completed
991 * and we should set the socket as writable.
1001 * No matter what happened, put the socket back in the tree.
1003 add234(sktree
, sock
);
1006 plug_log(sock
->plug
, 1, sock
->addr
, sock
->port
, sock
->error
, err
);
1010 Socket
sk_new(SockAddr addr
, int port
, int privport
, int oobinline
,
1011 int nodelay
, int keepalive
, Plug plug
)
1013 static const struct socket_function_table fn_table
= {
1019 sk_tcp_set_private_ptr
,
1020 sk_tcp_get_private_ptr
,
1029 * Create Socket structure.
1031 ret
= snew(struct Socket_tag
);
1032 ret
->fn
= &fn_table
;
1035 bufchain_init(&ret
->output_data
);
1036 ret
->connected
= 0; /* to start with */
1037 ret
->writable
= 0; /* to start with */
1038 ret
->sending_oob
= 0;
1040 ret
->frozen_readable
= 0;
1041 ret
->localhost_only
= 0; /* unused, but best init anyway */
1042 ret
->pending_error
= 0;
1043 ret
->parent
= ret
->child
= NULL
;
1044 ret
->oobinline
= oobinline
;
1045 ret
->nodelay
= nodelay
;
1046 ret
->keepalive
= keepalive
;
1047 ret
->privport
= privport
;
1050 START_STEP(ret
->addr
, ret
->step
);
1051 ret
->s
= INVALID_SOCKET
;
1055 err
= try_connect(ret
);
1056 } while (err
&& sk_nextaddr(ret
->addr
, &ret
->step
));
1058 return (Socket
) ret
;
1061 Socket
sk_newlistener(char *srcaddr
, int port
, Plug plug
, int local_host_only
,
1062 int orig_address_family
)
1064 static const struct socket_function_table fn_table
= {
1070 sk_tcp_set_private_ptr
,
1071 sk_tcp_get_private_ptr
,
1091 * Create Socket structure.
1093 ret
= snew(struct Socket_tag
);
1094 ret
->fn
= &fn_table
;
1097 bufchain_init(&ret
->output_data
);
1098 ret
->writable
= 0; /* to start with */
1099 ret
->sending_oob
= 0;
1101 ret
->frozen_readable
= 0;
1102 ret
->localhost_only
= local_host_only
;
1103 ret
->pending_error
= 0;
1104 ret
->parent
= ret
->child
= NULL
;
1108 * Translate address_family from platform-independent constants
1109 * into local reality.
1111 address_family
= (orig_address_family
== ADDRTYPE_IPV4 ? AF_INET
:
1113 orig_address_family
== ADDRTYPE_IPV6 ? AF_INET6
:
1118 * Our default, if passed the `don't care' value
1119 * ADDRTYPE_UNSPEC, is to listen on IPv4. If IPv6 is supported,
1120 * we will also set up a second socket listening on IPv6, but
1121 * the v4 one is primary since that ought to work even on
1122 * non-v6-supporting systems.
1124 if (address_family
== AF_UNSPEC
) address_family
= AF_INET
;
1129 s
= p_socket(address_family
, SOCK_STREAM
, 0);
1132 if (s
== INVALID_SOCKET
) {
1133 err
= p_WSAGetLastError();
1134 ret
->error
= winsock_error_string(err
);
1135 return (Socket
) ret
;
1140 p_setsockopt(s
, SOL_SOCKET
, SO_REUSEADDR
, (const char *)&on
, sizeof(on
));
1143 if (address_family
== AF_INET6
) {
1144 memset(&a6
, 0, sizeof(a6
));
1145 a6
.sin6_family
= AF_INET6
;
1146 /* FIXME: srcaddr is ignored for IPv6, because I (SGT) don't
1147 * know how to do it. :-)
1148 * (jeroen:) saddr is specified as an address.. eg 2001:db8::1
1149 * Thus we need either a parser that understands [2001:db8::1]:80
1150 * style addresses and/or enhance this to understand hostnames too. */
1151 if (local_host_only
)
1152 a6
.sin6_addr
= in6addr_loopback
;
1154 a6
.sin6_addr
= in6addr_any
;
1155 a6
.sin6_port
= p_htons(port
);
1160 a
.sin_family
= AF_INET
;
1163 * Bind to source address. First try an explicitly
1167 a
.sin_addr
.s_addr
= p_inet_addr(srcaddr
);
1168 if (a
.sin_addr
.s_addr
!= INADDR_NONE
) {
1169 /* Override localhost_only with specified listen addr. */
1170 ret
->localhost_only
= ipv4_is_loopback(a
.sin_addr
);
1176 * ... and failing that, go with one of the standard ones.
1179 if (local_host_only
)
1180 a
.sin_addr
.s_addr
= p_htonl(INADDR_LOOPBACK
);
1182 a
.sin_addr
.s_addr
= p_htonl(INADDR_ANY
);
1185 a
.sin_port
= p_htons((short)port
);
1188 retcode
= p_bind(s
, (address_family
== AF_INET6 ?
1189 (struct sockaddr
*) &a6
:
1190 (struct sockaddr
*) &a
),
1192 AF_INET6 ?
sizeof(a6
) : sizeof(a
)));
1194 retcode
= p_bind(s
, (struct sockaddr
*) &a
, sizeof(a
));
1196 if (retcode
!= SOCKET_ERROR
) {
1199 err
= p_WSAGetLastError();
1204 ret
->error
= winsock_error_string(err
);
1205 return (Socket
) ret
;
1209 if (p_listen(s
, SOMAXCONN
) == SOCKET_ERROR
) {
1211 ret
->error
= winsock_error_string(err
);
1212 return (Socket
) ret
;
1215 /* Set up a select mechanism. This could be an AsyncSelect on a
1216 * window, or an EventSelect on an event object. */
1217 errstr
= do_select(s
, 1);
1220 ret
->error
= errstr
;
1221 return (Socket
) ret
;
1224 add234(sktree
, ret
);
1228 * If we were given ADDRTYPE_UNSPEC, we must also create an
1229 * IPv6 listening socket and link it to this one.
1231 if (address_family
== AF_INET
&& orig_address_family
== ADDRTYPE_UNSPEC
) {
1232 Actual_Socket other
;
1234 other
= (Actual_Socket
) sk_newlistener(srcaddr
, port
, plug
,
1235 local_host_only
, ADDRTYPE_IPV6
);
1238 if (!other
->error
) {
1239 other
->parent
= ret
;
1248 return (Socket
) ret
;
1251 static void sk_tcp_close(Socket sock
)
1253 extern char *do_select(SOCKET skt
, int startup
);
1254 Actual_Socket s
= (Actual_Socket
) sock
;
1257 sk_tcp_close((Socket
)s
->child
);
1261 p_closesocket(s
->s
);
1263 sk_addr_free(s
->addr
);
1268 * The function which tries to send on a socket once it's deemed
1271 void try_send(Actual_Socket s
)
1273 while (s
->sending_oob
|| bufchain_size(&s
->output_data
) > 0) {
1277 int len
, urgentflag
;
1279 if (s
->sending_oob
) {
1280 urgentflag
= MSG_OOB
;
1281 len
= s
->sending_oob
;
1285 bufchain_prefix(&s
->output_data
, &data
, &len
);
1287 nsent
= p_send(s
->s
, data
, len
, urgentflag
);
1288 noise_ultralight(nsent
);
1290 err
= (nsent
< 0 ?
p_WSAGetLastError() : 0);
1291 if ((err
< WSABASEERR
&& nsent
< 0) || err
== WSAEWOULDBLOCK
) {
1293 * Perfectly normal: we've sent all we can for the moment.
1295 * (Some WinSock send() implementations can return
1296 * <0 but leave no sensible error indication -
1297 * WSAGetLastError() is called but returns zero or
1298 * a small number - so we check that case and treat
1299 * it just like WSAEWOULDBLOCK.)
1301 s
->writable
= FALSE
;
1303 } else if (nsent
== 0 ||
1304 err
== WSAECONNABORTED
|| err
== WSAECONNRESET
) {
1306 * If send() returns CONNABORTED or CONNRESET, we
1307 * unfortunately can't just call plug_closing(),
1308 * because it's quite likely that we're currently
1309 * _in_ a call from the code we'd be calling back
1310 * to, so we'd have to make half the SSH code
1311 * reentrant. Instead we flag a pending error on
1312 * the socket, to be dealt with (by calling
1313 * plug_closing()) at some suitable future moment.
1315 s
->pending_error
= err
;
1318 /* We're inside the Windows frontend here, so we know
1319 * that the frontend handle is unnecessary. */
1320 logevent(NULL
, winsock_error_string(err
));
1321 fatalbox("%s", winsock_error_string(err
));
1324 if (s
->sending_oob
) {
1326 memmove(s
->oobdata
, s
->oobdata
+nsent
, len
-nsent
);
1327 s
->sending_oob
= len
- nsent
;
1332 bufchain_consume(&s
->output_data
, nsent
);
1338 static int sk_tcp_write(Socket sock
, const char *buf
, int len
)
1340 Actual_Socket s
= (Actual_Socket
) sock
;
1343 * Add the data to the buffer list on the socket.
1345 bufchain_add(&s
->output_data
, buf
, len
);
1348 * Now try sending from the start of the buffer list.
1353 return bufchain_size(&s
->output_data
);
1356 static int sk_tcp_write_oob(Socket sock
, const char *buf
, int len
)
1358 Actual_Socket s
= (Actual_Socket
) sock
;
1361 * Replace the buffer list on the socket with the data.
1363 bufchain_clear(&s
->output_data
);
1364 assert(len
<= sizeof(s
->oobdata
));
1365 memcpy(s
->oobdata
, buf
, len
);
1366 s
->sending_oob
= len
;
1369 * Now try sending from the start of the buffer list.
1374 return s
->sending_oob
;
1377 int select_result(WPARAM wParam
, LPARAM lParam
)
1381 char buf
[20480]; /* nice big buffer for plenty of speed */
1385 /* wParam is the socket itself */
1388 return 1; /* boggle */
1390 s
= find234(sktree
, (void *) wParam
, cmpforsearch
);
1392 return 1; /* boggle */
1394 if ((err
= WSAGETSELECTERROR(lParam
)) != 0) {
1396 * An error has occurred on this socket. Pass it to the
1400 plug_log(s
->plug
, 1, s
->addr
, s
->port
,
1401 winsock_error_string(err
), err
);
1402 while (s
->addr
&& sk_nextaddr(s
->addr
, &s
->step
)) {
1403 err
= try_connect(s
);
1407 return plug_closing(s
->plug
, winsock_error_string(err
), err
, 0);
1412 noise_ultralight(lParam
);
1414 switch (WSAGETSELECTEVENT(lParam
)) {
1416 s
->connected
= s
->writable
= 1;
1418 * Once a socket is connected, we can stop falling
1419 * back through the candidate addresses to connect
1423 sk_addr_free(s
->addr
);
1428 /* In the case the socket is still frozen, we don't even bother */
1430 s
->frozen_readable
= 1;
1435 * We have received data on the socket. For an oobinline
1436 * socket, this might be data _before_ an urgent pointer,
1437 * in which case we send it to the back end with type==1
1438 * (data prior to urgent).
1442 p_ioctlsocket(s
->s
, SIOCATMARK
, &atmark
);
1444 * Avoid checking the return value from ioctlsocket(),
1445 * on the grounds that some WinSock wrappers don't
1446 * support it. If it does nothing, we get atmark==1,
1447 * which is equivalent to `no OOB pending', so the
1448 * effect will be to non-OOB-ify any OOB data.
1453 ret
= p_recv(s
->s
, buf
, sizeof(buf
), 0);
1454 noise_ultralight(ret
);
1456 err
= p_WSAGetLastError();
1457 if (err
== WSAEWOULDBLOCK
) {
1462 return plug_closing(s
->plug
, winsock_error_string(err
), err
,
1464 } else if (0 == ret
) {
1465 return plug_closing(s
->plug
, NULL
, 0, 0);
1467 return plug_receive(s
->plug
, atmark ?
0 : 1, buf
, ret
);
1472 * This will only happen on a non-oobinline socket. It
1473 * indicates that we can immediately perform an OOB read
1474 * and get back OOB data, which we will send to the back
1475 * end with type==2 (urgent data).
1477 ret
= p_recv(s
->s
, buf
, sizeof(buf
), MSG_OOB
);
1478 noise_ultralight(ret
);
1480 char *str
= (ret
== 0 ?
"Internal networking trouble" :
1481 winsock_error_string(p_WSAGetLastError()));
1482 /* We're inside the Windows frontend here, so we know
1483 * that the frontend handle is unnecessary. */
1484 logevent(NULL
, str
);
1485 fatalbox("%s", str
);
1487 return plug_receive(s
->plug
, 2, buf
, ret
);
1492 int bufsize_before
, bufsize_after
;
1494 bufsize_before
= s
->sending_oob
+ bufchain_size(&s
->output_data
);
1496 bufsize_after
= s
->sending_oob
+ bufchain_size(&s
->output_data
);
1497 if (bufsize_after
< bufsize_before
)
1498 plug_sent(s
->plug
, bufsize_after
);
1502 /* Signal a close on the socket. First read any outstanding data. */
1505 ret
= p_recv(s
->s
, buf
, sizeof(buf
), 0);
1507 err
= p_WSAGetLastError();
1508 if (err
== WSAEWOULDBLOCK
)
1510 return plug_closing(s
->plug
, winsock_error_string(err
),
1514 open
&= plug_receive(s
->plug
, 0, buf
, ret
);
1516 open
&= plug_closing(s
->plug
, NULL
, 0, 0);
1523 struct sockaddr_in isa
;
1525 struct sockaddr_storage isa
;
1527 int addrlen
= sizeof(isa
);
1528 SOCKET t
; /* socket of connection */
1530 memset(&isa
, 0, sizeof(isa
));
1532 t
= p_accept(s
->s
,(struct sockaddr
*)&isa
,&addrlen
);
1533 if (t
== INVALID_SOCKET
)
1535 err
= p_WSAGetLastError();
1536 if (err
== WSATRY_AGAIN
)
1540 if (isa
.ss_family
== AF_INET
&&
1541 s
->localhost_only
&&
1542 !ipv4_is_local_addr(((struct sockaddr_in
*)&isa
)->sin_addr
))
1544 if (s
->localhost_only
&& !ipv4_is_local_addr(isa
.sin_addr
))
1547 p_closesocket(t
); /* dodgy WinSock let nonlocal through */
1548 } else if (plug_accepting(s
->plug
, (void*)t
)) {
1549 p_closesocket(t
); /* denied or error */
1558 * Deal with socket errors detected in try_send().
1560 void net_pending_errors(void)
1566 * This might be a fiddly business, because it's just possible
1567 * that handling a pending error on one socket might cause
1568 * others to be closed. (I can't think of any reason this might
1569 * happen in current SSH implementation, but to maintain
1570 * generality of this network layer I'll assume the worst.)
1572 * So what we'll do is search the socket list for _one_ socket
1573 * with a pending error, and then handle it, and then search
1574 * the list again _from the beginning_. Repeat until we make a
1575 * pass with no socket errors present. That way we are
1576 * protected against the socket list changing under our feet.
1580 for (i
= 0; (s
= index234(sktree
, i
)) != NULL
; i
++) {
1581 if (s
->pending_error
) {
1583 * An error has occurred on this socket. Pass it to the
1586 plug_closing(s
->plug
,
1587 winsock_error_string(s
->pending_error
),
1588 s
->pending_error
, 0);
1596 * Each socket abstraction contains a `void *' private field in
1597 * which the client can keep state.
1599 static void sk_tcp_set_private_ptr(Socket sock
, void *ptr
)
1601 Actual_Socket s
= (Actual_Socket
) sock
;
1602 s
->private_ptr
= ptr
;
1605 static void *sk_tcp_get_private_ptr(Socket sock
)
1607 Actual_Socket s
= (Actual_Socket
) sock
;
1608 return s
->private_ptr
;
1612 * Special error values are returned from sk_namelookup and sk_new
1613 * if there's a problem. These functions extract an error message,
1614 * or return NULL if there's no problem.
1616 const char *sk_addr_error(SockAddr addr
)
1620 static const char *sk_tcp_socket_error(Socket sock
)
1622 Actual_Socket s
= (Actual_Socket
) sock
;
1626 static void sk_tcp_set_frozen(Socket sock
, int is_frozen
)
1628 Actual_Socket s
= (Actual_Socket
) sock
;
1629 if (s
->frozen
== is_frozen
)
1631 s
->frozen
= is_frozen
;
1634 if (s
->frozen_readable
) {
1636 p_recv(s
->s
, &c
, 1, MSG_PEEK
);
1639 s
->frozen_readable
= 0;
1642 void socket_reselect_all(void)
1647 for (i
= 0; (s
= index234(sktree
, i
)) != NULL
; i
++) {
1654 * For Plink: enumerate all sockets currently active.
1656 SOCKET
first_socket(int *state
)
1660 s
= index234(sktree
, (*state
)++);
1661 return s ? s
->s
: INVALID_SOCKET
;
1664 SOCKET
next_socket(int *state
)
1666 Actual_Socket s
= index234(sktree
, (*state
)++);
1667 return s ? s
->s
: INVALID_SOCKET
;
1670 extern int socket_writable(SOCKET skt
)
1672 Actual_Socket s
= find234(sktree
, (void *)skt
, cmpforsearch
);
1675 return bufchain_size(&s
->output_data
) > 0;
1680 int net_service_lookup(char *service
)
1683 se
= p_getservbyname(service
, NULL
);
1685 return p_ntohs(se
->s_port
);
1690 char *get_hostname(void)
1693 char *hostname
= NULL
;
1696 hostname
= sresize(hostname
, len
, char);
1697 if (p_gethostname(hostname
, len
) < 0) {
1702 } while (strlen(hostname
) >= len
-1);
1706 SockAddr
platform_get_x11_unix_address(const char *display
, int displaynum
,
1707 char **canonicalname
)
1709 SockAddr ret
= snew(struct SockAddr_tag
);
1710 memset(ret
, 0, sizeof(struct SockAddr_tag
));
1711 ret
->error
= "unix sockets not supported on this platform";