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;
310 /* Clear the structure and default to IPv4. */
311 memset(ret, 0, sizeof(struct SockAddr_tag));
312 ret->family = (address_family == ADDRTYPE_IPV4 ? AF_INET :
314 address_family == ADDRTYPE_IPV6 ? AF_INET6 :
319 if ((a = p_inet_addr(host)) == (unsigned long) INADDR_NONE) {
322 /* Try to get the getaddrinfo() function from wship6.dll */
323 /* This way one doesn't need to have IPv6 dll's to use PuTTY and
324 * it will fallback to IPv4. */
325 typedef int (CALLBACK * FGETADDRINFO) (const char *nodename,
326 const char *servname,
327 const struct addrinfo *
329 struct addrinfo ** res);
330 FGETADDRINFO fGetAddrInfo = NULL;
332 HINSTANCE dllWSHIP6 = LoadLibrary("wship6.dll");
334 fGetAddrInfo = (FGETADDRINFO) GetProcAddress(dllWSHIP6,
338 * Use fGetAddrInfo when it's available
341 struct addrinfo hints;
342 memset(&hints, 0, sizeof(hints));
343 hints.ai_family = ret->family;
344 if (fGetAddrInfo(host, NULL, &hints, &ret->ai) == 0)
345 ret->family = ret->ai->ai_family;
350 * Otherwise use the IPv4-only gethostbyname...
351 * (NOTE: we don't use gethostbyname as a fallback!)
353 if (ret->family == 0) {
354 if ( (h = p_gethostbyname(host)) )
355 ret->family = AF_INET;
359 if (ret->family == AF_UNSPEC) {
360 DWORD err = p_WSAGetLastError();
361 ret->error = (err == WSAENETDOWN ? "Network is down" :
363 WSAHOST_NOT_FOUND ? "Host does not exist" : err
364 == WSATRY_AGAIN ? "Host not found" :
366 fGetAddrInfo ? "getaddrinfo: unknown error" :
368 "gethostbyname: unknown error");
373 /* If we got an address info use that... */
375 typedef int (CALLBACK * FGETNAMEINFO)
376 (const struct sockaddr FAR * sa, socklen_t salen,
377 char FAR * host, size_t hostlen, char FAR * serv,
378 size_t servlen, int flags);
379 FGETNAMEINFO fGetNameInfo = NULL;
381 /* Are we in IPv4 fallback mode? */
382 /* We put the IPv4 address into the a variable so we can further-on use the IPv4 code... */
383 if (ret->family == AF_INET)
385 (char *) &((SOCKADDR_IN *) ret->ai->
386 ai_addr)->sin_addr, sizeof(a));
388 /* Now let's find that canonicalname... */
391 (FGETNAMEINFO) GetProcAddress(dllWSHIP6,
394 ((struct sockaddr *) ret->ai->ai_addr,
396 AF_INET ? sizeof(SOCKADDR_IN) :
397 sizeof(SOCKADDR_IN6), realhost,
398 sizeof(realhost), NULL, 0, 0) != 0) {
399 strncpy(realhost, host, sizeof(realhost));
403 /* We used the IPv4-only gethostbyname()... */
407 memcpy(&a, h->h_addr, sizeof(a));
408 /* This way we are always sure the h->h_name is valid :) */
409 strncpy(realhost, h->h_name, sizeof(realhost));
413 FreeLibrary(dllWSHIP6);
417 * This must be a numeric IPv4 address because it caused a
418 * success return from inet_addr.
420 ret->family = AF_INET;
421 strncpy(realhost, host, sizeof(realhost));
423 ret->address = p_ntohl(a);
424 realhost[lenof(realhost)-1] = '\0';
425 *canonicalname = snewn(1+strlen(realhost), char);
426 strcpy(*canonicalname, realhost);
430 SockAddr sk_nonamelookup(const char *host)
432 SockAddr ret = snew(struct SockAddr_tag);
434 ret->family = AF_UNSPEC;
435 strncpy(ret->hostname, host, lenof(ret->hostname));
436 ret->hostname[lenof(ret->hostname)-1] = '\0';
440 void sk_getaddr(SockAddr addr, char *buf, int buflen)
443 if (addr->family == AF_INET6) {
444 /* Try to get the WSAAddressToStringA() function from wship6.dll */
445 /* This way one doesn't need to have IPv6 dll's to use PuTTY and
446 * it will fallback to IPv4. */
447 typedef int (CALLBACK * FADDRTOSTR) (LPSOCKADDR lpsaAddress,
448 DWORD dwAddressLength,
449 LPWSAPROTOCOL_INFO lpProtocolInfo,
450 OUT LPTSTR lpszAddressString,
451 IN OUT LPDWORD lpdwAddressStringLength
453 FADDRTOSTR fAddrToStr = NULL;
455 HINSTANCE dllWS2 = LoadLibrary("ws2_32.dll");
457 fAddrToStr = (FADDRTOSTR)GetProcAddress(dllWS2,
458 "WSAAddressToStringA");
460 fAddrToStr(addr->ai->ai_addr, addr->ai->ai_addrlen,
463 else strncpy(buf, "IPv6", buflen);
468 if (addr->family == AF_INET) {
470 a.s_addr = p_htonl(addr->address);
471 strncpy(buf, p_inet_ntoa(a), buflen);
472 buf[buflen-1] = '\0';
474 strncpy(buf, addr->hostname, buflen);
475 buf[buflen-1] = '\0';
479 int sk_hostname_is_local(char *name)
481 return !strcmp(name, "localhost");
484 static INTERFACE_INFO local_interfaces[16];
485 static int n_local_interfaces; /* 0=not yet, -1=failed, >0=number */
487 static int ipv4_is_local_addr(struct in_addr addr)
489 if (ipv4_is_loopback(addr))
490 return 1; /* loopback addresses are local */
491 if (!n_local_interfaces) {
492 SOCKET s = p_socket(AF_INET, SOCK_DGRAM, 0);
496 p_WSAIoctl(s, SIO_GET_INTERFACE_LIST, NULL, 0,
497 local_interfaces, sizeof(local_interfaces),
498 &retbytes, NULL, NULL) == 0)
499 n_local_interfaces = retbytes / sizeof(INTERFACE_INFO);
501 logevent(NULL, "Unable to get list of local IP addresses");
503 if (n_local_interfaces > 0) {
505 for (i = 0; i < n_local_interfaces; i++) {
506 SOCKADDR_IN *address =
507 (SOCKADDR_IN *)&local_interfaces[i].iiAddress;
508 if (address->sin_addr.s_addr == addr.s_addr)
509 return 1; /* this address is local */
512 return 0; /* this address is not local */
515 int sk_address_is_local(SockAddr addr)
518 if (addr->family == AF_INET6) {
519 return IN6_IS_ADDR_LOOPBACK((const struct in6_addr *)addr->ai->ai_addr);
522 if (addr->family == AF_INET) {
524 a.s_addr = p_htonl(addr->address);
525 return ipv4_is_local_addr(a);
527 assert(addr->family == AF_UNSPEC);
528 return 0; /* we don't know; assume not */
532 int sk_addrtype(SockAddr addr)
534 return (addr->family == AF_INET ? ADDRTYPE_IPV4 :
536 addr->family == AF_INET6 ? ADDRTYPE_IPV6 :
541 void sk_addrcopy(SockAddr addr, char *buf)
543 assert(addr->family != AF_UNSPEC);
545 if (addr->family == AF_INET6) {
546 memcpy(buf, (char*) addr->ai, 16);
549 if (addr->family == AF_INET) {
551 a.s_addr = p_htonl(addr->address);
552 memcpy(buf, (char*) &a.s_addr, 4);
556 void sk_addr_free(SockAddr addr)
561 static Plug sk_tcp_plug(Socket sock, Plug p)
563 Actual_Socket s = (Actual_Socket) sock;
570 static void sk_tcp_flush(Socket s)
573 * We send data to the socket as soon as we can anyway,
574 * so we don't need to do anything here. :-)
578 static void sk_tcp_close(Socket s);
579 static int sk_tcp_write(Socket s, const char *data, int len);
580 static int sk_tcp_write_oob(Socket s, const char *data, int len);
581 static void sk_tcp_set_private_ptr(Socket s, void *ptr);
582 static void *sk_tcp_get_private_ptr(Socket s);
583 static void sk_tcp_set_frozen(Socket s, int is_frozen);
584 static const char *sk_tcp_socket_error(Socket s);
586 extern char *do_select(SOCKET skt, int startup);
588 Socket sk_register(void *sock, Plug plug)
590 static const struct socket_function_table fn_table = {
596 sk_tcp_set_private_ptr,
597 sk_tcp_get_private_ptr,
607 * Create Socket structure.
609 ret = snew(struct Socket_tag);
613 bufchain_init(&ret->output_data);
614 ret->writable = 1; /* to start with */
615 ret->sending_oob = 0;
617 ret->frozen_readable = 0;
618 ret->localhost_only = 0; /* unused, but best init anyway */
619 ret->pending_error = 0;
621 ret->s = (SOCKET)sock;
623 if (ret->s == INVALID_SOCKET) {
624 err = p_WSAGetLastError();
625 ret->error = winsock_error_string(err);
631 /* Set up a select mechanism. This could be an AsyncSelect on a
632 * window, or an EventSelect on an event object. */
633 errstr = do_select(ret->s, 1);
644 Socket sk_new(SockAddr addr, int port, int privport, int oobinline,
645 int nodelay, int keepalive, Plug plug)
647 static const struct socket_function_table fn_table = {
653 sk_tcp_set_private_ptr,
654 sk_tcp_get_private_ptr,
670 * Create Socket structure.
672 ret = snew(struct Socket_tag);
676 bufchain_init(&ret->output_data);
677 ret->connected = 0; /* to start with */
678 ret->writable = 0; /* to start with */
679 ret->sending_oob = 0;
681 ret->frozen_readable = 0;
682 ret->localhost_only = 0; /* unused, but best init anyway */
683 ret->pending_error = 0;
689 /* Let's default to IPv6, this shouldn't hurt anybody
690 * If the stack supports IPv6 it will also allow IPv4 connections. */
691 if (addr->family == AF_UNSPEC) addr->family = AF_INET6;
693 /* No other choice, default to IPv4 */
694 if (addr->family == AF_UNSPEC) addr->family = AF_INET;
696 s = p_socket(addr->family, SOCK_STREAM, 0);
699 if (s == INVALID_SOCKET) {
700 err = p_WSAGetLastError();
701 ret->error = winsock_error_string(err);
705 ret->oobinline = oobinline;
708 p_setsockopt(s, SOL_SOCKET, SO_OOBINLINE, (void *) &b, sizeof(b));
713 p_setsockopt(s, IPPROTO_TCP, TCP_NODELAY, (void *) &b, sizeof(b));
718 p_setsockopt(s, SOL_SOCKET, SO_KEEPALIVE, (void *) &b, sizeof(b));
722 * Bind to local address.
725 localport = 1023; /* count from 1023 downwards */
727 localport = 0; /* just use port 0 (ie winsock picks) */
729 /* Loop round trying to bind */
734 if (addr->family == AF_INET6) {
735 memset(&a6, 0, sizeof(a6));
736 a6.sin6_family = AF_INET6;
737 /*a6.sin6_addr = in6addr_any; */ /* == 0 done by memset() */
738 a6.sin6_port = p_htons(localport);
742 a.sin_family = AF_INET;
743 a.sin_addr.s_addr = p_htonl(INADDR_ANY);
744 a.sin_port = p_htons(localport);
747 retcode = p_bind(s, (addr->family == AF_INET6 ?
748 (struct sockaddr *) &a6 :
749 (struct sockaddr *) &a),
751 AF_INET6 ? sizeof(a6) : sizeof(a)));
753 retcode = p_bind(s, (struct sockaddr *) &a, sizeof(a));
755 if (retcode != SOCKET_ERROR) {
759 err = p_WSAGetLastError();
760 if (err != WSAEADDRINUSE) /* failed, for a bad reason */
765 break; /* we're only looping once */
768 break; /* we might have got to the end */
772 ret->error = winsock_error_string(err);
777 * Connect to remote address.
780 if (addr->family == AF_INET6) {
781 memset(&a, 0, sizeof(a));
782 a6.sin6_family = AF_INET6;
783 a6.sin6_port = p_htons((short) port);
785 ((struct sockaddr_in6 *) addr->ai->ai_addr)->sin6_addr;
789 a.sin_family = AF_INET;
790 a.sin_addr.s_addr = p_htonl(addr->address);
791 a.sin_port = p_htons((short) port);
794 /* Set up a select mechanism. This could be an AsyncSelect on a
795 * window, or an EventSelect on an event object. */
796 errstr = do_select(s, 1);
804 p_connect(s, ((addr->family == AF_INET6) ?
805 (struct sockaddr *) &a6 : (struct sockaddr *) &a),
806 (addr->family == AF_INET6) ? sizeof(a6) : sizeof(a))
808 p_connect(s, (struct sockaddr *) &a, sizeof(a))
811 err = p_WSAGetLastError();
813 * We expect a potential EWOULDBLOCK here, because the
814 * chances are the front end has done a select for
815 * FD_CONNECT, so that connect() will complete
818 if ( err != WSAEWOULDBLOCK ) {
819 ret->error = winsock_error_string(err);
824 * If we _don't_ get EWOULDBLOCK, the connect has completed
825 * and we should set the socket as writable.
832 /* We're done with 'addr' now. */
838 Socket sk_newlistener(char *srcaddr, int port, Plug plug, int local_host_only,
841 static const struct socket_function_table fn_table = {
847 sk_tcp_set_private_ptr,
848 sk_tcp_get_private_ptr,
866 * Create Socket structure.
868 ret = snew(struct Socket_tag);
872 bufchain_init(&ret->output_data);
873 ret->writable = 0; /* to start with */
874 ret->sending_oob = 0;
876 ret->frozen_readable = 0;
877 ret->localhost_only = local_host_only;
878 ret->pending_error = 0;
881 * Translate address_family from platform-independent constants
882 * into local reality.
884 address_family = (address_family == ADDRTYPE_IPV4 ? AF_INET :
886 address_family == ADDRTYPE_IPV6 ? AF_INET6 :
891 /* Let's default to IPv6, this shouldn't hurt anybody
892 * If the stack supports IPv6 it will also allow IPv4 connections. */
893 if (address_family == AF_UNSPEC) address_family = AF_INET6;
895 /* No other choice, default to IPv4 */
896 if (address_family == AF_UNSPEC) address_family = AF_INET;
902 s = p_socket(address_family, SOCK_STREAM, 0);
905 if (s == INVALID_SOCKET) {
906 err = p_WSAGetLastError();
907 ret->error = winsock_error_string(err);
913 p_setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (const char *)&on, sizeof(on));
916 if (address_family == AF_INET6) {
917 memset(&a6, 0, sizeof(a6));
918 a6.sin6_family = AF_INET6;
919 /* FIXME: srcaddr is ignored for IPv6, because I (SGT) don't
920 * know how to do it. :-)
921 * (jeroen:) saddr is specified as an address.. eg 2001:db8::1
922 * Thus we need either a parser that understands [2001:db8::1]:80
923 * style addresses and/or enhance this to understand hostnames too. */
925 a6.sin6_addr = in6addr_loopback;
927 a6.sin6_addr = in6addr_any;
928 a6.sin6_port = p_htons(port);
933 a.sin_family = AF_INET;
936 * Bind to source address. First try an explicitly
940 a.sin_addr.s_addr = p_inet_addr(srcaddr);
941 if (a.sin_addr.s_addr != INADDR_NONE) {
942 /* Override localhost_only with specified listen addr. */
943 ret->localhost_only = ipv4_is_loopback(a.sin_addr);
949 * ... and failing that, go with one of the standard ones.
953 a.sin_addr.s_addr = p_htonl(INADDR_LOOPBACK);
955 a.sin_addr.s_addr = p_htonl(INADDR_ANY);
958 a.sin_port = p_htons((short)port);
961 retcode = p_bind(s, (address_family == AF_INET6 ?
962 (struct sockaddr *) &a6 :
963 (struct sockaddr *) &a),
965 AF_INET6 ? sizeof(a6) : sizeof(a)));
967 retcode = p_bind(s, (struct sockaddr *) &a, sizeof(a));
969 if (retcode != SOCKET_ERROR) {
972 err = p_WSAGetLastError();
976 ret->error = winsock_error_string(err);
981 if (p_listen(s, SOMAXCONN) == SOCKET_ERROR) {
983 ret->error = winsock_error_string(err);
987 /* Set up a select mechanism. This could be an AsyncSelect on a
988 * window, or an EventSelect on an event object. */
989 errstr = do_select(s, 1);
1000 static void sk_tcp_close(Socket sock)
1002 extern char *do_select(SOCKET skt, int startup);
1003 Actual_Socket s = (Actual_Socket) sock;
1007 p_closesocket(s->s);
1012 * The function which tries to send on a socket once it's deemed
1015 void try_send(Actual_Socket s)
1017 while (s->sending_oob || bufchain_size(&s->output_data) > 0) {
1021 int len, urgentflag;
1023 if (s->sending_oob) {
1024 urgentflag = MSG_OOB;
1025 len = s->sending_oob;
1029 bufchain_prefix(&s->output_data, &data, &len);
1031 nsent = p_send(s->s, data, len, urgentflag);
1032 noise_ultralight(nsent);
1034 err = (nsent < 0 ? p_WSAGetLastError() : 0);
1035 if ((err < WSABASEERR && nsent < 0) || err == WSAEWOULDBLOCK) {
1037 * Perfectly normal: we've sent all we can for the moment.
1039 * (Some WinSock send() implementations can return
1040 * <0 but leave no sensible error indication -
1041 * WSAGetLastError() is called but returns zero or
1042 * a small number - so we check that case and treat
1043 * it just like WSAEWOULDBLOCK.)
1045 s->writable = FALSE;
1047 } else if (nsent == 0 ||
1048 err == WSAECONNABORTED || err == WSAECONNRESET) {
1050 * If send() returns CONNABORTED or CONNRESET, we
1051 * unfortunately can't just call plug_closing(),
1052 * because it's quite likely that we're currently
1053 * _in_ a call from the code we'd be calling back
1054 * to, so we'd have to make half the SSH code
1055 * reentrant. Instead we flag a pending error on
1056 * the socket, to be dealt with (by calling
1057 * plug_closing()) at some suitable future moment.
1059 s->pending_error = err;
1062 /* We're inside the Windows frontend here, so we know
1063 * that the frontend handle is unnecessary. */
1064 logevent(NULL, winsock_error_string(err));
1065 fatalbox("%s", winsock_error_string(err));
1068 if (s->sending_oob) {
1070 memmove(s->oobdata, s->oobdata+nsent, len-nsent);
1071 s->sending_oob = len - nsent;
1076 bufchain_consume(&s->output_data, nsent);
1082 static int sk_tcp_write(Socket sock, const char *buf, int len)
1084 Actual_Socket s = (Actual_Socket) sock;
1087 * Add the data to the buffer list on the socket.
1089 bufchain_add(&s->output_data, buf, len);
1092 * Now try sending from the start of the buffer list.
1097 return bufchain_size(&s->output_data);
1100 static int sk_tcp_write_oob(Socket sock, const char *buf, int len)
1102 Actual_Socket s = (Actual_Socket) sock;
1105 * Replace the buffer list on the socket with the data.
1107 bufchain_clear(&s->output_data);
1108 assert(len <= sizeof(s->oobdata));
1109 memcpy(s->oobdata, buf, len);
1110 s->sending_oob = len;
1113 * Now try sending from the start of the buffer list.
1118 return s->sending_oob;
1121 int select_result(WPARAM wParam, LPARAM lParam)
1125 char buf[20480]; /* nice big buffer for plenty of speed */
1129 /* wParam is the socket itself */
1132 return 1; /* boggle */
1134 s = find234(sktree, (void *) wParam, cmpforsearch);
1136 return 1; /* boggle */
1138 if ((err = WSAGETSELECTERROR(lParam)) != 0) {
1140 * An error has occurred on this socket. Pass it to the
1143 return plug_closing(s->plug, winsock_error_string(err), err, 0);
1146 noise_ultralight(lParam);
1148 switch (WSAGETSELECTEVENT(lParam)) {
1150 s->connected = s->writable = 1;
1153 /* In the case the socket is still frozen, we don't even bother */
1155 s->frozen_readable = 1;
1160 * We have received data on the socket. For an oobinline
1161 * socket, this might be data _before_ an urgent pointer,
1162 * in which case we send it to the back end with type==1
1163 * (data prior to urgent).
1167 p_ioctlsocket(s->s, SIOCATMARK, &atmark);
1169 * Avoid checking the return value from ioctlsocket(),
1170 * on the grounds that some WinSock wrappers don't
1171 * support it. If it does nothing, we get atmark==1,
1172 * which is equivalent to `no OOB pending', so the
1173 * effect will be to non-OOB-ify any OOB data.
1178 ret = p_recv(s->s, buf, sizeof(buf), 0);
1179 noise_ultralight(ret);
1181 err = p_WSAGetLastError();
1182 if (err == WSAEWOULDBLOCK) {
1187 return plug_closing(s->plug, winsock_error_string(err), err,
1189 } else if (0 == ret) {
1190 return plug_closing(s->plug, NULL, 0, 0);
1192 return plug_receive(s->plug, atmark ? 0 : 1, buf, ret);
1197 * This will only happen on a non-oobinline socket. It
1198 * indicates that we can immediately perform an OOB read
1199 * and get back OOB data, which we will send to the back
1200 * end with type==2 (urgent data).
1202 ret = p_recv(s->s, buf, sizeof(buf), MSG_OOB);
1203 noise_ultralight(ret);
1205 char *str = (ret == 0 ? "Internal networking trouble" :
1206 winsock_error_string(p_WSAGetLastError()));
1207 /* We're inside the Windows frontend here, so we know
1208 * that the frontend handle is unnecessary. */
1209 logevent(NULL, str);
1210 fatalbox("%s", str);
1212 return plug_receive(s->plug, 2, buf, ret);
1217 int bufsize_before, bufsize_after;
1219 bufsize_before = s->sending_oob + bufchain_size(&s->output_data);
1221 bufsize_after = s->sending_oob + bufchain_size(&s->output_data);
1222 if (bufsize_after < bufsize_before)
1223 plug_sent(s->plug, bufsize_after);
1227 /* Signal a close on the socket. First read any outstanding data. */
1230 ret = p_recv(s->s, buf, sizeof(buf), 0);
1232 err = p_WSAGetLastError();
1233 if (err == WSAEWOULDBLOCK)
1235 return plug_closing(s->plug, winsock_error_string(err),
1239 open &= plug_receive(s->plug, 0, buf, ret);
1241 open &= plug_closing(s->plug, NULL, 0, 0);
1248 struct sockaddr_in isa;
1250 struct sockaddr_storage isa;
1252 int addrlen = sizeof(isa);
1253 SOCKET t; /* socket of connection */
1255 memset(&isa, 0, sizeof(isa));
1257 t = p_accept(s->s,(struct sockaddr *)&isa,&addrlen);
1258 if (t == INVALID_SOCKET)
1260 err = p_WSAGetLastError();
1261 if (err == WSATRY_AGAIN)
1265 if (isa.ss_family == AF_INET &&
1266 s->localhost_only &&
1267 !ipv4_is_local_addr(((struct sockaddr_in *)&isa)->sin_addr)) {
1269 if (s->localhost_only && !ipv4_is_local_addr(isa.sin_addr)) {
1271 p_closesocket(t); /* dodgy WinSock let nonlocal through */
1272 } else if (plug_accepting(s->plug, (void*)t)) {
1273 p_closesocket(t); /* denied or error */
1282 * Deal with socket errors detected in try_send().
1284 void net_pending_errors(void)
1290 * This might be a fiddly business, because it's just possible
1291 * that handling a pending error on one socket might cause
1292 * others to be closed. (I can't think of any reason this might
1293 * happen in current SSH implementation, but to maintain
1294 * generality of this network layer I'll assume the worst.)
1296 * So what we'll do is search the socket list for _one_ socket
1297 * with a pending error, and then handle it, and then search
1298 * the list again _from the beginning_. Repeat until we make a
1299 * pass with no socket errors present. That way we are
1300 * protected against the socket list changing under our feet.
1304 for (i = 0; (s = index234(sktree, i)) != NULL; i++) {
1305 if (s->pending_error) {
1307 * An error has occurred on this socket. Pass it to the
1310 plug_closing(s->plug,
1311 winsock_error_string(s->pending_error),
1312 s->pending_error, 0);
1320 * Each socket abstraction contains a `void *' private field in
1321 * which the client can keep state.
1323 static void sk_tcp_set_private_ptr(Socket sock, void *ptr)
1325 Actual_Socket s = (Actual_Socket) sock;
1326 s->private_ptr = ptr;
1329 static void *sk_tcp_get_private_ptr(Socket sock)
1331 Actual_Socket s = (Actual_Socket) sock;
1332 return s->private_ptr;
1336 * Special error values are returned from sk_namelookup and sk_new
1337 * if there's a problem. These functions extract an error message,
1338 * or return NULL if there's no problem.
1340 const char *sk_addr_error(SockAddr addr)
1344 static const char *sk_tcp_socket_error(Socket sock)
1346 Actual_Socket s = (Actual_Socket) sock;
1350 static void sk_tcp_set_frozen(Socket sock, int is_frozen)
1352 Actual_Socket s = (Actual_Socket) sock;
1353 if (s->frozen == is_frozen)
1355 s->frozen = is_frozen;
1356 if (!is_frozen && s->frozen_readable) {
1358 p_recv(s->s, &c, 1, MSG_PEEK);
1360 s->frozen_readable = 0;
1364 * For Plink: enumerate all sockets currently active.
1366 SOCKET first_socket(int *state)
1370 s = index234(sktree, (*state)++);
1371 return s ? s->s : INVALID_SOCKET;
1374 SOCKET next_socket(int *state)
1376 Actual_Socket s = index234(sktree, (*state)++);
1377 return s ? s->s : INVALID_SOCKET;
1380 extern int socket_writable(SOCKET skt)
1382 Actual_Socket s = find234(sktree, (void *)skt, cmpforsearch);
1385 return bufchain_size(&s->output_data) > 0;
1390 int net_service_lookup(char *service)
1393 se = p_getservbyname(service, NULL);
1395 return p_ntohs(se->s_port);
1400 SockAddr platform_get_x11_unix_address(int displaynum, char **canonicalname)
1402 SockAddr ret = snew(struct SockAddr_tag);
1403 memset(ret, 0, sizeof(struct SockAddr_tag));
1404 ret->error = "unix sockets not supported on this platform";