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 */
59 int frozen; /* this causes readability notifications to be ignored */
60 int frozen_readable; /* this means we missed at least one readability
61 * notification while we were frozen */
62 int localhost_only; /* for listening sockets */
65 int oobinline, nodelay, keepalive, privport;
66 enum { EOF_NO, EOF_PENDING, EOF_SENT } outgoingeof;
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;
84 int namedpipe; /* indicates that this SockAddr is phony, holding a Windows
85 * named pipe pathname instead of a network address */
87 struct addrinfo *ais; /* Addresses IPv6 style. */
89 unsigned long *addresses; /* Addresses IPv4 style. */
91 char hostname[512]; /* Store an unresolved host name. */
95 * Which address family this address belongs to. AF_INET for IPv4;
96 * AF_INET6 for IPv6; AF_UNSPEC indicates that name resolution has
97 * not been done and a simple host name is held in this SockAddr
101 #define SOCKADDR_FAMILY(addr, step) \
102 (!(addr)->resolved ? AF_UNSPEC : \
103 (step).ai ? (step).ai->ai_family : AF_INET)
105 #define SOCKADDR_FAMILY(addr, step) \
106 (!(addr)->resolved ? AF_UNSPEC : AF_INET)
110 * Start a SockAddrStep structure to step through multiple
114 #define START_STEP(addr, step) \
115 ((step).ai = (addr)->ais, (step).curraddr = 0)
117 #define START_STEP(addr, step) \
118 ((step).curraddr = 0)
121 static tree234 *sktree;
123 static int cmpfortree(void *av, void *bv)
125 Actual_Socket a = (Actual_Socket) av, b = (Actual_Socket) bv;
126 unsigned long as = (unsigned long) a->s, bs = (unsigned long) b->s;
138 static int cmpforsearch(void *av, void *bv)
140 Actual_Socket b = (Actual_Socket) bv;
141 uintptr_t as = (uintptr_t) av, bs = (uintptr_t) b->s;
149 DECL_WINDOWS_FUNCTION(static, int, WSAStartup, (WORD, LPWSADATA));
150 DECL_WINDOWS_FUNCTION(static, int, WSACleanup, (void));
151 DECL_WINDOWS_FUNCTION(static, int, closesocket, (SOCKET));
152 DECL_WINDOWS_FUNCTION(static, u_long, ntohl, (u_long));
153 DECL_WINDOWS_FUNCTION(static, u_long, htonl, (u_long));
154 DECL_WINDOWS_FUNCTION(static, u_short, htons, (u_short));
155 DECL_WINDOWS_FUNCTION(static, u_short, ntohs, (u_short));
156 DECL_WINDOWS_FUNCTION(static, int, gethostname, (char *, int));
157 DECL_WINDOWS_FUNCTION(static, struct hostent FAR *, gethostbyname,
159 DECL_WINDOWS_FUNCTION(static, struct servent FAR *, getservbyname,
160 (const char FAR *, const char FAR *));
161 DECL_WINDOWS_FUNCTION(static, unsigned long, inet_addr, (const char FAR *));
162 DECL_WINDOWS_FUNCTION(static, char FAR *, inet_ntoa, (struct in_addr));
163 DECL_WINDOWS_FUNCTION(static, const char FAR *, inet_ntop,
164 (int, void FAR *, char *, size_t));
165 DECL_WINDOWS_FUNCTION(static, int, connect,
166 (SOCKET, const struct sockaddr FAR *, int));
167 DECL_WINDOWS_FUNCTION(static, int, bind,
168 (SOCKET, const struct sockaddr FAR *, int));
169 DECL_WINDOWS_FUNCTION(static, int, setsockopt,
170 (SOCKET, int, int, const char FAR *, int));
171 DECL_WINDOWS_FUNCTION(static, SOCKET, socket, (int, int, int));
172 DECL_WINDOWS_FUNCTION(static, int, listen, (SOCKET, int));
173 DECL_WINDOWS_FUNCTION(static, int, send, (SOCKET, const char FAR *, int, int));
174 DECL_WINDOWS_FUNCTION(static, int, shutdown, (SOCKET, int));
175 DECL_WINDOWS_FUNCTION(static, int, ioctlsocket,
176 (SOCKET, long, u_long FAR *));
177 DECL_WINDOWS_FUNCTION(static, SOCKET, accept,
178 (SOCKET, struct sockaddr FAR *, int FAR *));
179 DECL_WINDOWS_FUNCTION(static, int, getpeername,
180 (SOCKET, struct sockaddr FAR *, int FAR *));
181 DECL_WINDOWS_FUNCTION(static, int, recv, (SOCKET, char FAR *, int, int));
182 DECL_WINDOWS_FUNCTION(static, int, WSAIoctl,
183 (SOCKET, DWORD, LPVOID, DWORD, LPVOID, DWORD,
184 LPDWORD, LPWSAOVERLAPPED,
185 LPWSAOVERLAPPED_COMPLETION_ROUTINE));
187 DECL_WINDOWS_FUNCTION(static, int, getaddrinfo,
188 (const char *nodename, const char *servname,
189 const struct addrinfo *hints, struct addrinfo **res));
190 DECL_WINDOWS_FUNCTION(static, void, freeaddrinfo, (struct addrinfo *res));
191 DECL_WINDOWS_FUNCTION(static, int, getnameinfo,
192 (const struct sockaddr FAR * sa, socklen_t salen,
193 char FAR * host, size_t hostlen, char FAR * serv,
194 size_t servlen, int flags));
195 DECL_WINDOWS_FUNCTION(static, char *, gai_strerror, (int ecode));
196 DECL_WINDOWS_FUNCTION(static, int, WSAAddressToStringA,
197 (LPSOCKADDR, DWORD, LPWSAPROTOCOL_INFO,
201 static HMODULE winsock_module = NULL;
202 static WSADATA wsadata;
204 static HMODULE winsock2_module = NULL;
205 static HMODULE wship6_module = NULL;
208 int sk_startup(int hi, int lo)
212 winsock_ver = MAKEWORD(hi, lo);
214 if (p_WSAStartup(winsock_ver, &wsadata)) {
218 if (LOBYTE(wsadata.wVersion) != LOBYTE(winsock_ver)) {
222 #ifdef NET_SETUP_DIAGNOSTICS
225 sprintf(buf, "Using WinSock %d.%d", hi, lo);
237 winsock_module = load_system32_dll("ws2_32.dll");
238 if (!winsock_module) {
239 winsock_module = load_system32_dll("wsock32.dll");
242 fatalbox("Unable to load any WinSock library");
245 /* Check if we have getaddrinfo in Winsock */
246 if (GetProcAddress(winsock_module, "getaddrinfo") != NULL) {
247 #ifdef NET_SETUP_DIAGNOSTICS
248 logevent(NULL, "Native WinSock IPv6 support detected");
250 GET_WINDOWS_FUNCTION(winsock_module, getaddrinfo);
251 GET_WINDOWS_FUNCTION(winsock_module, freeaddrinfo);
252 GET_WINDOWS_FUNCTION(winsock_module, getnameinfo);
253 GET_WINDOWS_FUNCTION(winsock_module, gai_strerror);
255 /* Fall back to wship6.dll for Windows 2000 */
256 wship6_module = load_system32_dll("wship6.dll");
258 #ifdef NET_SETUP_DIAGNOSTICS
259 logevent(NULL, "WSH IPv6 support detected");
261 GET_WINDOWS_FUNCTION(wship6_module, getaddrinfo);
262 GET_WINDOWS_FUNCTION(wship6_module, freeaddrinfo);
263 GET_WINDOWS_FUNCTION(wship6_module, getnameinfo);
264 GET_WINDOWS_FUNCTION(wship6_module, gai_strerror);
266 #ifdef NET_SETUP_DIAGNOSTICS
267 logevent(NULL, "No IPv6 support detected");
271 GET_WINDOWS_FUNCTION(winsock2_module, WSAAddressToStringA);
273 #ifdef NET_SETUP_DIAGNOSTICS
274 logevent(NULL, "PuTTY was built without IPv6 support");
278 GET_WINDOWS_FUNCTION(winsock_module, WSAAsyncSelect);
279 GET_WINDOWS_FUNCTION(winsock_module, WSAEventSelect);
280 GET_WINDOWS_FUNCTION(winsock_module, select);
281 GET_WINDOWS_FUNCTION(winsock_module, WSAGetLastError);
282 GET_WINDOWS_FUNCTION(winsock_module, WSAEnumNetworkEvents);
283 GET_WINDOWS_FUNCTION(winsock_module, WSAStartup);
284 GET_WINDOWS_FUNCTION(winsock_module, WSACleanup);
285 GET_WINDOWS_FUNCTION(winsock_module, closesocket);
286 GET_WINDOWS_FUNCTION(winsock_module, ntohl);
287 GET_WINDOWS_FUNCTION(winsock_module, htonl);
288 GET_WINDOWS_FUNCTION(winsock_module, htons);
289 GET_WINDOWS_FUNCTION(winsock_module, ntohs);
290 GET_WINDOWS_FUNCTION(winsock_module, gethostname);
291 GET_WINDOWS_FUNCTION(winsock_module, gethostbyname);
292 GET_WINDOWS_FUNCTION(winsock_module, getservbyname);
293 GET_WINDOWS_FUNCTION(winsock_module, inet_addr);
294 GET_WINDOWS_FUNCTION(winsock_module, inet_ntoa);
295 GET_WINDOWS_FUNCTION(winsock_module, inet_ntop);
296 GET_WINDOWS_FUNCTION(winsock_module, connect);
297 GET_WINDOWS_FUNCTION(winsock_module, bind);
298 GET_WINDOWS_FUNCTION(winsock_module, setsockopt);
299 GET_WINDOWS_FUNCTION(winsock_module, socket);
300 GET_WINDOWS_FUNCTION(winsock_module, listen);
301 GET_WINDOWS_FUNCTION(winsock_module, send);
302 GET_WINDOWS_FUNCTION(winsock_module, shutdown);
303 GET_WINDOWS_FUNCTION(winsock_module, ioctlsocket);
304 GET_WINDOWS_FUNCTION(winsock_module, accept);
305 GET_WINDOWS_FUNCTION(winsock_module, getpeername);
306 GET_WINDOWS_FUNCTION(winsock_module, recv);
307 GET_WINDOWS_FUNCTION(winsock_module, WSAIoctl);
309 /* Try to get the best WinSock version we can get */
310 if (!sk_startup(2,2) &&
313 fatalbox("Unable to initialise WinSock");
316 sktree = newtree234(cmpfortree);
319 void sk_cleanup(void)
325 for (i = 0; (s = index234(sktree, i)) != NULL; i++) {
335 FreeLibrary(winsock_module);
338 FreeLibrary(wship6_module);
347 static int errstring_find(void *av, void *bv)
350 struct errstring *b = (struct errstring *)bv;
357 static int errstring_compare(void *av, void *bv)
359 struct errstring *a = (struct errstring *)av;
360 return errstring_find(&a->error, bv);
363 static tree234 *errstrings = NULL;
365 const char *winsock_error_string(int error)
367 const char prefix[] = "Network error: ";
368 struct errstring *es;
371 * Error codes we know about and have historically had reasonably
372 * sensible error messages for.
376 return "Network error: Permission denied";
378 return "Network error: Address already in use";
379 case WSAEADDRNOTAVAIL:
380 return "Network error: Cannot assign requested address";
381 case WSAEAFNOSUPPORT:
383 "Network error: Address family not supported by protocol family";
385 return "Network error: Operation already in progress";
386 case WSAECONNABORTED:
387 return "Network error: Software caused connection abort";
388 case WSAECONNREFUSED:
389 return "Network error: Connection refused";
391 return "Network error: Connection reset by peer";
392 case WSAEDESTADDRREQ:
393 return "Network error: Destination address required";
395 return "Network error: Bad address";
397 return "Network error: Host is down";
398 case WSAEHOSTUNREACH:
399 return "Network error: No route to host";
401 return "Network error: Operation now in progress";
403 return "Network error: Interrupted function call";
405 return "Network error: Invalid argument";
407 return "Network error: Socket is already connected";
409 return "Network error: Too many open files";
411 return "Network error: Message too long";
413 return "Network error: Network is down";
415 return "Network error: Network dropped connection on reset";
417 return "Network error: Network is unreachable";
419 return "Network error: No buffer space available";
421 return "Network error: Bad protocol option";
423 return "Network error: Socket is not connected";
425 return "Network error: Socket operation on non-socket";
427 return "Network error: Operation not supported";
428 case WSAEPFNOSUPPORT:
429 return "Network error: Protocol family not supported";
431 return "Network error: Too many processes";
432 case WSAEPROTONOSUPPORT:
433 return "Network error: Protocol not supported";
435 return "Network error: Protocol wrong type for socket";
437 return "Network error: Cannot send after socket shutdown";
438 case WSAESOCKTNOSUPPORT:
439 return "Network error: Socket type not supported";
441 return "Network error: Connection timed out";
443 return "Network error: Resource temporarily unavailable";
445 return "Network error: Graceful shutdown in progress";
449 * Generic code to handle any other error.
451 * Slightly nasty hack here: we want to return a static string
452 * which the caller will never have to worry about freeing, but on
453 * the other hand if we call FormatMessage to get it then it will
454 * want to either allocate a buffer or write into one we own.
456 * So what we do is to maintain a tree234 of error strings we've
457 * already used. New ones are allocated from the heap, but then
458 * put in this tree and kept forever.
462 errstrings = newtree234(errstring_compare);
464 es = find234(errstrings, &error, errstring_find);
467 int bufsize, bufused;
469 es = snew(struct errstring);
471 /* maximum size for FormatMessage is 64K */
472 bufsize = 65535 + sizeof(prefix);
473 es->text = snewn(bufsize, char);
474 strcpy(es->text, prefix);
475 bufused = strlen(es->text);
476 if (!FormatMessage((FORMAT_MESSAGE_FROM_SYSTEM |
477 FORMAT_MESSAGE_IGNORE_INSERTS), NULL, error,
478 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
479 es->text + bufused, bufsize - bufused, NULL)) {
480 sprintf(es->text + bufused,
481 "Windows error code %d (and FormatMessage returned %u)",
482 error, (unsigned int)GetLastError());
484 int len = strlen(es->text);
485 if (len > 0 && es->text[len-1] == '\n')
486 es->text[len-1] = '\0';
488 es->text = sresize(es->text, strlen(es->text) + 1, char);
489 add234(errstrings, es);
495 SockAddr sk_namelookup(const char *host, char **canonicalname,
498 SockAddr ret = snew(struct SockAddr_tag);
503 /* Default to IPv4. */
504 hint_family = (address_family == ADDRTYPE_IPV4 ? AF_INET :
506 address_family == ADDRTYPE_IPV6 ? AF_INET6 :
510 /* Clear the structure and default to IPv4. */
511 memset(ret, 0, sizeof(struct SockAddr_tag));
515 ret->namedpipe = FALSE;
516 ret->addresses = NULL;
517 ret->resolved = FALSE;
521 if ((a = p_inet_addr(host)) == (unsigned long) INADDR_NONE) {
522 struct hostent *h = NULL;
526 * Use getaddrinfo when it's available
529 struct addrinfo hints;
530 #ifdef NET_SETUP_DIAGNOSTICS
531 logevent(NULL, "Using getaddrinfo() for resolving");
533 memset(&hints, 0, sizeof(hints));
534 hints.ai_family = hint_family;
535 hints.ai_flags = AI_CANONNAME;
537 /* strip [] on IPv6 address literals */
538 char *trimmed_host = host_strduptrim(host);
539 err = p_getaddrinfo(trimmed_host, NULL, &hints, &ret->ais);
543 ret->resolved = TRUE;
547 #ifdef NET_SETUP_DIAGNOSTICS
548 logevent(NULL, "Using gethostbyname() for resolving");
551 * Otherwise use the IPv4-only gethostbyname...
552 * (NOTE: we don't use gethostbyname as a fallback!)
554 if ( (h = p_gethostbyname(host)) )
555 ret->resolved = TRUE;
557 err = p_WSAGetLastError();
560 if (!ret->resolved) {
561 ret->error = (err == WSAENETDOWN ? "Network is down" :
562 err == WSAHOST_NOT_FOUND ? "Host does not exist" :
563 err == WSATRY_AGAIN ? "Host not found" :
565 p_getaddrinfo&&p_gai_strerror ? p_gai_strerror(err) :
567 "gethostbyname: unknown error");
572 /* If we got an address info use that... */
574 /* Are we in IPv4 fallback mode? */
575 /* We put the IPv4 address into the a variable so we can further-on use the IPv4 code... */
576 if (ret->ais->ai_family == AF_INET)
578 (char *) &((SOCKADDR_IN *) ret->ais->
579 ai_addr)->sin_addr, sizeof(a));
581 if (ret->ais->ai_canonname)
582 strncpy(realhost, ret->ais->ai_canonname, lenof(realhost));
584 strncpy(realhost, host, lenof(realhost));
586 /* We used the IPv4-only gethostbyname()... */
591 for (n = 0; h->h_addr_list[n]; n++);
592 ret->addresses = snewn(n, unsigned long);
594 for (n = 0; n < ret->naddresses; n++) {
595 memcpy(&a, h->h_addr_list[n], sizeof(a));
596 ret->addresses[n] = p_ntohl(a);
598 memcpy(&a, h->h_addr, sizeof(a));
599 /* This way we are always sure the h->h_name is valid :) */
600 strncpy(realhost, h->h_name, sizeof(realhost));
605 * This must be a numeric IPv4 address because it caused a
606 * success return from inet_addr.
608 ret->addresses = snewn(1, unsigned long);
610 ret->addresses[0] = p_ntohl(a);
611 ret->resolved = TRUE;
612 strncpy(realhost, host, sizeof(realhost));
614 realhost[lenof(realhost)-1] = '\0';
615 *canonicalname = snewn(1+strlen(realhost), char);
616 strcpy(*canonicalname, realhost);
620 SockAddr sk_nonamelookup(const char *host)
622 SockAddr ret = snew(struct SockAddr_tag);
624 ret->resolved = FALSE;
628 ret->namedpipe = FALSE;
629 ret->addresses = NULL;
632 strncpy(ret->hostname, host, lenof(ret->hostname));
633 ret->hostname[lenof(ret->hostname)-1] = '\0';
637 SockAddr sk_namedpipe_addr(const char *pipename)
639 SockAddr ret = snew(struct SockAddr_tag);
641 ret->resolved = FALSE;
645 ret->namedpipe = TRUE;
646 ret->addresses = NULL;
649 strncpy(ret->hostname, pipename, lenof(ret->hostname));
650 ret->hostname[lenof(ret->hostname)-1] = '\0';
654 int sk_nextaddr(SockAddr addr, SockAddrStep *step)
658 if (step->ai->ai_next) {
659 step->ai = step->ai->ai_next;
665 if (step->curraddr+1 < addr->naddresses) {
673 void sk_getaddr(SockAddr addr, char *buf, int buflen)
676 START_STEP(addr, step);
681 if (p_WSAAddressToStringA) {
682 DWORD dwbuflen = buflen;
683 err = p_WSAAddressToStringA(step.ai->ai_addr, step.ai->ai_addrlen,
684 NULL, buf, &dwbuflen);
688 strncpy(buf, addr->hostname, buflen);
690 strncpy(buf, "<unknown>", buflen);
691 buf[buflen-1] = '\0';
695 if (SOCKADDR_FAMILY(addr, step) == AF_INET) {
697 assert(addr->addresses && step.curraddr < addr->naddresses);
698 a.s_addr = p_htonl(addr->addresses[step.curraddr]);
699 strncpy(buf, p_inet_ntoa(a), buflen);
700 buf[buflen-1] = '\0';
702 strncpy(buf, addr->hostname, buflen);
703 buf[buflen-1] = '\0';
707 int sk_addr_needs_port(SockAddr addr)
709 return addr->namedpipe ? FALSE : TRUE;
712 int sk_hostname_is_local(const char *name)
714 return !strcmp(name, "localhost") ||
715 !strcmp(name, "::1") ||
716 !strncmp(name, "127.", 4);
719 static INTERFACE_INFO local_interfaces[16];
720 static int n_local_interfaces; /* 0=not yet, -1=failed, >0=number */
722 static int ipv4_is_local_addr(struct in_addr addr)
724 if (ipv4_is_loopback(addr))
725 return 1; /* loopback addresses are local */
726 if (!n_local_interfaces) {
727 SOCKET s = p_socket(AF_INET, SOCK_DGRAM, 0);
731 p_WSAIoctl(s, SIO_GET_INTERFACE_LIST, NULL, 0,
732 local_interfaces, sizeof(local_interfaces),
733 &retbytes, NULL, NULL) == 0)
734 n_local_interfaces = retbytes / sizeof(INTERFACE_INFO);
736 logevent(NULL, "Unable to get list of local IP addresses");
738 if (n_local_interfaces > 0) {
740 for (i = 0; i < n_local_interfaces; i++) {
741 SOCKADDR_IN *address =
742 (SOCKADDR_IN *)&local_interfaces[i].iiAddress;
743 if (address->sin_addr.s_addr == addr.s_addr)
744 return 1; /* this address is local */
747 return 0; /* this address is not local */
750 int sk_address_is_local(SockAddr addr)
754 START_STEP(addr, step);
755 family = SOCKADDR_FAMILY(addr, step);
758 if (family == AF_INET6) {
759 return IN6_IS_ADDR_LOOPBACK(&((const struct sockaddr_in6 *)step.ai->ai_addr)->sin6_addr);
762 if (family == AF_INET) {
765 return ipv4_is_local_addr(((struct sockaddr_in *)step.ai->ai_addr)
771 assert(addr->addresses && step.curraddr < addr->naddresses);
772 a.s_addr = p_htonl(addr->addresses[step.curraddr]);
773 return ipv4_is_local_addr(a);
776 assert(family == AF_UNSPEC);
777 return 0; /* we don't know; assume not */
781 int sk_address_is_special_local(SockAddr addr)
783 return 0; /* no Unix-domain socket analogue here */
786 int sk_addrtype(SockAddr addr)
790 START_STEP(addr, step);
791 family = SOCKADDR_FAMILY(addr, step);
793 return (family == AF_INET ? ADDRTYPE_IPV4 :
795 family == AF_INET6 ? ADDRTYPE_IPV6 :
800 void sk_addrcopy(SockAddr addr, char *buf)
804 START_STEP(addr, step);
805 family = SOCKADDR_FAMILY(addr, step);
807 assert(family != AF_UNSPEC);
810 if (family == AF_INET)
811 memcpy(buf, &((struct sockaddr_in *)step.ai->ai_addr)->sin_addr,
812 sizeof(struct in_addr));
813 else if (family == AF_INET6)
814 memcpy(buf, &((struct sockaddr_in6 *)step.ai->ai_addr)->sin6_addr,
815 sizeof(struct in6_addr));
820 if (family == AF_INET) {
822 assert(addr->addresses && step.curraddr < addr->naddresses);
823 a.s_addr = p_htonl(addr->addresses[step.curraddr]);
824 memcpy(buf, (char*) &a.s_addr, 4);
828 void sk_addr_free(SockAddr addr)
830 if (--addr->refcount > 0)
833 if (addr->ais && p_freeaddrinfo)
834 p_freeaddrinfo(addr->ais);
837 sfree(addr->addresses);
841 SockAddr sk_addr_dup(SockAddr addr)
847 static Plug sk_tcp_plug(Socket sock, Plug p)
849 Actual_Socket s = (Actual_Socket) sock;
856 static void sk_tcp_flush(Socket s)
859 * We send data to the socket as soon as we can anyway,
860 * so we don't need to do anything here. :-)
864 static void sk_tcp_close(Socket s);
865 static int sk_tcp_write(Socket s, const char *data, int len);
866 static int sk_tcp_write_oob(Socket s, const char *data, int len);
867 static void sk_tcp_write_eof(Socket s);
868 static void sk_tcp_set_frozen(Socket s, int is_frozen);
869 static const char *sk_tcp_socket_error(Socket s);
870 static char *sk_tcp_peer_info(Socket s);
872 extern char *do_select(SOCKET skt, int startup);
874 static Socket sk_tcp_accept(accept_ctx_t ctx, Plug plug)
876 static const struct socket_function_table fn_table = {
893 * Create Socket structure.
895 ret = snew(struct Socket_tag);
899 bufchain_init(&ret->output_data);
900 ret->writable = 1; /* to start with */
901 ret->sending_oob = 0;
902 ret->outgoingeof = EOF_NO;
904 ret->frozen_readable = 0;
905 ret->localhost_only = 0; /* unused, but best init anyway */
906 ret->pending_error = 0;
907 ret->parent = ret->child = NULL;
910 ret->s = (SOCKET)ctx.p;
912 if (ret->s == INVALID_SOCKET) {
913 err = p_WSAGetLastError();
914 ret->error = winsock_error_string(err);
920 /* Set up a select mechanism. This could be an AsyncSelect on a
921 * window, or an EventSelect on an event object. */
922 errstr = do_select(ret->s, 1);
933 static DWORD try_connect(Actual_Socket sock)
945 if (sock->s != INVALID_SOCKET) {
946 do_select(sock->s, 0);
947 p_closesocket(sock->s);
950 plug_log(sock->plug, 0, sock->addr, sock->port, NULL, 0);
955 family = SOCKADDR_FAMILY(sock->addr, sock->step);
958 * Remove the socket from the tree before we overwrite its
959 * internal socket id, because that forms part of the tree's
960 * sorting criterion. We'll add it back before exiting this
961 * function, whether we changed anything or not.
963 del234(sktree, sock);
965 s = p_socket(family, SOCK_STREAM, 0);
968 if (s == INVALID_SOCKET) {
969 err = p_WSAGetLastError();
970 sock->error = winsock_error_string(err);
974 if (sock->oobinline) {
976 p_setsockopt(s, SOL_SOCKET, SO_OOBINLINE, (void *) &b, sizeof(b));
981 p_setsockopt(s, IPPROTO_TCP, TCP_NODELAY, (void *) &b, sizeof(b));
984 if (sock->keepalive) {
986 p_setsockopt(s, SOL_SOCKET, SO_KEEPALIVE, (void *) &b, sizeof(b));
990 * Bind to local address.
993 localport = 1023; /* count from 1023 downwards */
995 localport = 0; /* just use port 0 (ie winsock picks) */
997 /* Loop round trying to bind */
1002 if (family == AF_INET6) {
1003 memset(&a6, 0, sizeof(a6));
1004 a6.sin6_family = AF_INET6;
1005 /*a6.sin6_addr = in6addr_any; */ /* == 0 done by memset() */
1006 a6.sin6_port = p_htons(localport);
1010 a.sin_family = AF_INET;
1011 a.sin_addr.s_addr = p_htonl(INADDR_ANY);
1012 a.sin_port = p_htons(localport);
1015 sockcode = p_bind(s, (family == AF_INET6 ?
1016 (struct sockaddr *) &a6 :
1017 (struct sockaddr *) &a),
1018 (family == AF_INET6 ? sizeof(a6) : sizeof(a)));
1020 sockcode = p_bind(s, (struct sockaddr *) &a, sizeof(a));
1022 if (sockcode != SOCKET_ERROR) {
1026 err = p_WSAGetLastError();
1027 if (err != WSAEADDRINUSE) /* failed, for a bad reason */
1032 break; /* we're only looping once */
1035 break; /* we might have got to the end */
1039 sock->error = winsock_error_string(err);
1044 * Connect to remote address.
1047 if (sock->step.ai) {
1048 if (family == AF_INET6) {
1049 a6.sin6_family = AF_INET6;
1050 a6.sin6_port = p_htons((short) sock->port);
1052 ((struct sockaddr_in6 *) sock->step.ai->ai_addr)->sin6_addr;
1053 a6.sin6_flowinfo = ((struct sockaddr_in6 *) sock->step.ai->ai_addr)->sin6_flowinfo;
1054 a6.sin6_scope_id = ((struct sockaddr_in6 *) sock->step.ai->ai_addr)->sin6_scope_id;
1056 a.sin_family = AF_INET;
1058 ((struct sockaddr_in *) sock->step.ai->ai_addr)->sin_addr;
1059 a.sin_port = p_htons((short) sock->port);
1064 assert(sock->addr->addresses && sock->step.curraddr < sock->addr->naddresses);
1065 a.sin_family = AF_INET;
1066 a.sin_addr.s_addr = p_htonl(sock->addr->addresses[sock->step.curraddr]);
1067 a.sin_port = p_htons((short) sock->port);
1070 /* Set up a select mechanism. This could be an AsyncSelect on a
1071 * window, or an EventSelect on an event object. */
1072 errstr = do_select(s, 1);
1074 sock->error = errstr;
1082 ((family == AF_INET6) ? (struct sockaddr *) &a6 :
1083 (struct sockaddr *) &a),
1084 (family == AF_INET6) ? sizeof(a6) : sizeof(a))
1086 p_connect(s, (struct sockaddr *) &a, sizeof(a))
1088 ) == SOCKET_ERROR) {
1089 err = p_WSAGetLastError();
1091 * We expect a potential EWOULDBLOCK here, because the
1092 * chances are the front end has done a select for
1093 * FD_CONNECT, so that connect() will complete
1096 if ( err != WSAEWOULDBLOCK ) {
1097 sock->error = winsock_error_string(err);
1102 * If we _don't_ get EWOULDBLOCK, the connect has completed
1103 * and we should set the socket as writable.
1113 * No matter what happened, put the socket back in the tree.
1115 add234(sktree, sock);
1118 plug_log(sock->plug, 1, sock->addr, sock->port, sock->error, err);
1122 Socket sk_new(SockAddr addr, int port, int privport, int oobinline,
1123 int nodelay, int keepalive, Plug plug)
1125 static const struct socket_function_table fn_table = {
1133 sk_tcp_socket_error,
1141 * Create Socket structure.
1143 ret = snew(struct Socket_tag);
1144 ret->fn = &fn_table;
1147 bufchain_init(&ret->output_data);
1148 ret->connected = 0; /* to start with */
1149 ret->writable = 0; /* to start with */
1150 ret->sending_oob = 0;
1151 ret->outgoingeof = EOF_NO;
1153 ret->frozen_readable = 0;
1154 ret->localhost_only = 0; /* unused, but best init anyway */
1155 ret->pending_error = 0;
1156 ret->parent = ret->child = NULL;
1157 ret->oobinline = oobinline;
1158 ret->nodelay = nodelay;
1159 ret->keepalive = keepalive;
1160 ret->privport = privport;
1163 START_STEP(ret->addr, ret->step);
1164 ret->s = INVALID_SOCKET;
1168 err = try_connect(ret);
1169 } while (err && sk_nextaddr(ret->addr, &ret->step));
1171 return (Socket) ret;
1174 Socket sk_newlistener(const char *srcaddr, int port, Plug plug,
1175 int local_host_only, int orig_address_family)
1177 static const struct socket_function_table fn_table = {
1185 sk_tcp_socket_error,
1204 * Create Socket structure.
1206 ret = snew(struct Socket_tag);
1207 ret->fn = &fn_table;
1210 bufchain_init(&ret->output_data);
1211 ret->writable = 0; /* to start with */
1212 ret->sending_oob = 0;
1213 ret->outgoingeof = EOF_NO;
1215 ret->frozen_readable = 0;
1216 ret->localhost_only = local_host_only;
1217 ret->pending_error = 0;
1218 ret->parent = ret->child = NULL;
1222 * Translate address_family from platform-independent constants
1223 * into local reality.
1225 address_family = (orig_address_family == ADDRTYPE_IPV4 ? AF_INET :
1227 orig_address_family == ADDRTYPE_IPV6 ? AF_INET6 :
1232 * Our default, if passed the `don't care' value
1233 * ADDRTYPE_UNSPEC, is to listen on IPv4. If IPv6 is supported,
1234 * we will also set up a second socket listening on IPv6, but
1235 * the v4 one is primary since that ought to work even on
1236 * non-v6-supporting systems.
1238 if (address_family == AF_UNSPEC) address_family = AF_INET;
1243 s = p_socket(address_family, SOCK_STREAM, 0);
1246 if (s == INVALID_SOCKET) {
1247 err = p_WSAGetLastError();
1248 ret->error = winsock_error_string(err);
1249 return (Socket) ret;
1254 p_setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (const char *)&on, sizeof(on));
1257 if (address_family == AF_INET6) {
1258 memset(&a6, 0, sizeof(a6));
1259 a6.sin6_family = AF_INET6;
1260 if (local_host_only)
1261 a6.sin6_addr = in6addr_loopback;
1263 a6.sin6_addr = in6addr_any;
1264 if (srcaddr != NULL && p_getaddrinfo) {
1265 struct addrinfo hints;
1266 struct addrinfo *ai;
1269 memset(&hints, 0, sizeof(hints));
1270 hints.ai_family = AF_INET6;
1273 /* strip [] on IPv6 address literals */
1274 char *trimmed_addr = host_strduptrim(srcaddr);
1275 err = p_getaddrinfo(trimmed_addr, NULL, &hints, &ai);
1276 sfree(trimmed_addr);
1278 if (err == 0 && ai->ai_family == AF_INET6) {
1280 ((struct sockaddr_in6 *)ai->ai_addr)->sin6_addr;
1283 a6.sin6_port = p_htons(port);
1288 a.sin_family = AF_INET;
1291 * Bind to source address. First try an explicitly
1295 a.sin_addr.s_addr = p_inet_addr(srcaddr);
1296 if (a.sin_addr.s_addr != INADDR_NONE) {
1297 /* Override localhost_only with specified listen addr. */
1298 ret->localhost_only = ipv4_is_loopback(a.sin_addr);
1304 * ... and failing that, go with one of the standard ones.
1307 if (local_host_only)
1308 a.sin_addr.s_addr = p_htonl(INADDR_LOOPBACK);
1310 a.sin_addr.s_addr = p_htonl(INADDR_ANY);
1313 a.sin_port = p_htons((short)port);
1316 retcode = p_bind(s, (address_family == AF_INET6 ?
1317 (struct sockaddr *) &a6 :
1318 (struct sockaddr *) &a),
1320 AF_INET6 ? sizeof(a6) : sizeof(a)));
1322 retcode = p_bind(s, (struct sockaddr *) &a, sizeof(a));
1324 if (retcode != SOCKET_ERROR) {
1327 err = p_WSAGetLastError();
1332 ret->error = winsock_error_string(err);
1333 return (Socket) ret;
1337 if (p_listen(s, SOMAXCONN) == SOCKET_ERROR) {
1339 ret->error = winsock_error_string(p_WSAGetLastError());
1340 return (Socket) ret;
1343 /* Set up a select mechanism. This could be an AsyncSelect on a
1344 * window, or an EventSelect on an event object. */
1345 errstr = do_select(s, 1);
1348 ret->error = errstr;
1349 return (Socket) ret;
1352 add234(sktree, ret);
1356 * If we were given ADDRTYPE_UNSPEC, we must also create an
1357 * IPv6 listening socket and link it to this one.
1359 if (address_family == AF_INET && orig_address_family == ADDRTYPE_UNSPEC) {
1360 Actual_Socket other;
1362 other = (Actual_Socket) sk_newlistener(srcaddr, port, plug,
1363 local_host_only, ADDRTYPE_IPV6);
1366 if (!other->error) {
1367 other->parent = ret;
1376 return (Socket) ret;
1379 static void sk_tcp_close(Socket sock)
1381 extern char *do_select(SOCKET skt, int startup);
1382 Actual_Socket s = (Actual_Socket) sock;
1385 sk_tcp_close((Socket)s->child);
1389 p_closesocket(s->s);
1391 sk_addr_free(s->addr);
1396 * Deal with socket errors detected in try_send().
1398 static void socket_error_callback(void *vs)
1400 Actual_Socket s = (Actual_Socket)vs;
1403 * Just in case other socket work has caused this socket to vanish
1404 * or become somehow non-erroneous before this callback arrived...
1406 if (!find234(sktree, s, NULL) || !s->pending_error)
1410 * An error has occurred on this socket. Pass it to the plug.
1412 plug_closing(s->plug, winsock_error_string(s->pending_error),
1413 s->pending_error, 0);
1417 * The function which tries to send on a socket once it's deemed
1420 void try_send(Actual_Socket s)
1422 while (s->sending_oob || bufchain_size(&s->output_data) > 0) {
1426 int len, urgentflag;
1428 if (s->sending_oob) {
1429 urgentflag = MSG_OOB;
1430 len = s->sending_oob;
1434 bufchain_prefix(&s->output_data, &data, &len);
1436 nsent = p_send(s->s, data, len, urgentflag);
1437 noise_ultralight(nsent);
1439 err = (nsent < 0 ? p_WSAGetLastError() : 0);
1440 if ((err < WSABASEERR && nsent < 0) || err == WSAEWOULDBLOCK) {
1442 * Perfectly normal: we've sent all we can for the moment.
1444 * (Some WinSock send() implementations can return
1445 * <0 but leave no sensible error indication -
1446 * WSAGetLastError() is called but returns zero or
1447 * a small number - so we check that case and treat
1448 * it just like WSAEWOULDBLOCK.)
1450 s->writable = FALSE;
1452 } else if (nsent == 0 ||
1453 err == WSAECONNABORTED || err == WSAECONNRESET) {
1455 * If send() returns CONNABORTED or CONNRESET, we
1456 * unfortunately can't just call plug_closing(),
1457 * because it's quite likely that we're currently
1458 * _in_ a call from the code we'd be calling back
1459 * to, so we'd have to make half the SSH code
1460 * reentrant. Instead we flag a pending error on
1461 * the socket, to be dealt with (by calling
1462 * plug_closing()) at some suitable future moment.
1464 s->pending_error = err;
1465 queue_toplevel_callback(socket_error_callback, s);
1468 /* We're inside the Windows frontend here, so we know
1469 * that the frontend handle is unnecessary. */
1470 logevent(NULL, winsock_error_string(err));
1471 fatalbox("%s", winsock_error_string(err));
1474 if (s->sending_oob) {
1476 memmove(s->oobdata, s->oobdata+nsent, len-nsent);
1477 s->sending_oob = len - nsent;
1482 bufchain_consume(&s->output_data, nsent);
1488 * If we reach here, we've finished sending everything we might
1489 * have needed to send. Send EOF, if we need to.
1491 if (s->outgoingeof == EOF_PENDING) {
1492 p_shutdown(s->s, SD_SEND);
1493 s->outgoingeof = EOF_SENT;
1497 static int sk_tcp_write(Socket sock, const char *buf, int len)
1499 Actual_Socket s = (Actual_Socket) sock;
1501 assert(s->outgoingeof == EOF_NO);
1504 * Add the data to the buffer list on the socket.
1506 bufchain_add(&s->output_data, buf, len);
1509 * Now try sending from the start of the buffer list.
1514 return bufchain_size(&s->output_data);
1517 static int sk_tcp_write_oob(Socket sock, const char *buf, int len)
1519 Actual_Socket s = (Actual_Socket) sock;
1521 assert(s->outgoingeof == EOF_NO);
1524 * Replace the buffer list on the socket with the data.
1526 bufchain_clear(&s->output_data);
1527 assert(len <= sizeof(s->oobdata));
1528 memcpy(s->oobdata, buf, len);
1529 s->sending_oob = len;
1532 * Now try sending from the start of the buffer list.
1537 return s->sending_oob;
1540 static void sk_tcp_write_eof(Socket sock)
1542 Actual_Socket s = (Actual_Socket) sock;
1544 assert(s->outgoingeof == EOF_NO);
1547 * Mark the socket as pending outgoing EOF.
1549 s->outgoingeof = EOF_PENDING;
1552 * Now try sending from the start of the buffer list.
1558 int select_result(WPARAM wParam, LPARAM lParam)
1562 char buf[20480]; /* nice big buffer for plenty of speed */
1566 /* wParam is the socket itself */
1569 return 1; /* boggle */
1571 s = find234(sktree, (void *) wParam, cmpforsearch);
1573 return 1; /* boggle */
1575 if ((err = WSAGETSELECTERROR(lParam)) != 0) {
1577 * An error has occurred on this socket. Pass it to the
1581 plug_log(s->plug, 1, s->addr, s->port,
1582 winsock_error_string(err), err);
1583 while (s->addr && sk_nextaddr(s->addr, &s->step)) {
1584 err = try_connect(s);
1588 return plug_closing(s->plug, winsock_error_string(err), err, 0);
1593 noise_ultralight(lParam);
1595 switch (WSAGETSELECTEVENT(lParam)) {
1597 s->connected = s->writable = 1;
1599 * Once a socket is connected, we can stop falling
1600 * back through the candidate addresses to connect
1604 sk_addr_free(s->addr);
1609 /* In the case the socket is still frozen, we don't even bother */
1611 s->frozen_readable = 1;
1616 * We have received data on the socket. For an oobinline
1617 * socket, this might be data _before_ an urgent pointer,
1618 * in which case we send it to the back end with type==1
1619 * (data prior to urgent).
1623 p_ioctlsocket(s->s, SIOCATMARK, &atmark);
1625 * Avoid checking the return value from ioctlsocket(),
1626 * on the grounds that some WinSock wrappers don't
1627 * support it. If it does nothing, we get atmark==1,
1628 * which is equivalent to `no OOB pending', so the
1629 * effect will be to non-OOB-ify any OOB data.
1634 ret = p_recv(s->s, buf, sizeof(buf), 0);
1635 noise_ultralight(ret);
1637 err = p_WSAGetLastError();
1638 if (err == WSAEWOULDBLOCK) {
1643 return plug_closing(s->plug, winsock_error_string(err), err,
1645 } else if (0 == ret) {
1646 return plug_closing(s->plug, NULL, 0, 0);
1648 return plug_receive(s->plug, atmark ? 0 : 1, buf, ret);
1653 * This will only happen on a non-oobinline socket. It
1654 * indicates that we can immediately perform an OOB read
1655 * and get back OOB data, which we will send to the back
1656 * end with type==2 (urgent data).
1658 ret = p_recv(s->s, buf, sizeof(buf), MSG_OOB);
1659 noise_ultralight(ret);
1661 const char *str = (ret == 0 ? "Internal networking trouble" :
1662 winsock_error_string(p_WSAGetLastError()));
1663 /* We're inside the Windows frontend here, so we know
1664 * that the frontend handle is unnecessary. */
1665 logevent(NULL, str);
1666 fatalbox("%s", str);
1668 return plug_receive(s->plug, 2, buf, ret);
1673 int bufsize_before, bufsize_after;
1675 bufsize_before = s->sending_oob + bufchain_size(&s->output_data);
1677 bufsize_after = s->sending_oob + bufchain_size(&s->output_data);
1678 if (bufsize_after < bufsize_before)
1679 plug_sent(s->plug, bufsize_after);
1683 /* Signal a close on the socket. First read any outstanding data. */
1686 ret = p_recv(s->s, buf, sizeof(buf), 0);
1688 err = p_WSAGetLastError();
1689 if (err == WSAEWOULDBLOCK)
1691 return plug_closing(s->plug, winsock_error_string(err),
1695 open &= plug_receive(s->plug, 0, buf, ret);
1697 open &= plug_closing(s->plug, NULL, 0, 0);
1704 struct sockaddr_in isa;
1706 struct sockaddr_storage isa;
1708 int addrlen = sizeof(isa);
1709 SOCKET t; /* socket of connection */
1712 memset(&isa, 0, sizeof(isa));
1714 t = p_accept(s->s,(struct sockaddr *)&isa,&addrlen);
1715 if (t == INVALID_SOCKET)
1717 err = p_WSAGetLastError();
1718 if (err == WSATRY_AGAIN)
1725 if (isa.ss_family == AF_INET &&
1726 s->localhost_only &&
1727 !ipv4_is_local_addr(((struct sockaddr_in *)&isa)->sin_addr))
1729 if (s->localhost_only && !ipv4_is_local_addr(isa.sin_addr))
1732 p_closesocket(t); /* dodgy WinSock let nonlocal through */
1733 } else if (plug_accepting(s->plug, sk_tcp_accept, actx)) {
1734 p_closesocket(t); /* denied or error */
1743 * Special error values are returned from sk_namelookup and sk_new
1744 * if there's a problem. These functions extract an error message,
1745 * or return NULL if there's no problem.
1747 const char *sk_addr_error(SockAddr addr)
1751 static const char *sk_tcp_socket_error(Socket sock)
1753 Actual_Socket s = (Actual_Socket) sock;
1757 static char *sk_tcp_peer_info(Socket sock)
1759 Actual_Socket s = (Actual_Socket) sock;
1761 struct sockaddr_in addr;
1763 struct sockaddr_storage addr;
1765 int addrlen = sizeof(addr);
1766 char buf[INET6_ADDRSTRLEN];
1768 if (p_getpeername(s->s, (struct sockaddr *)&addr, &addrlen) < 0)
1771 if (((struct sockaddr *)&addr)->sa_family == AF_INET) {
1774 p_inet_ntoa(((struct sockaddr_in *)&addr)->sin_addr),
1775 (int)p_ntohs(((struct sockaddr_in *)&addr)->sin_port));
1777 } else if (((struct sockaddr *)&addr)->sa_family == AF_INET6) {
1780 p_inet_ntop(AF_INET6, &((struct sockaddr_in6 *)&addr)->sin6_addr,
1782 (int)p_ntohs(((struct sockaddr_in6 *)&addr)->sin6_port));
1789 static void sk_tcp_set_frozen(Socket sock, int is_frozen)
1791 Actual_Socket s = (Actual_Socket) sock;
1792 if (s->frozen == is_frozen)
1794 s->frozen = is_frozen;
1797 if (s->frozen_readable) {
1799 p_recv(s->s, &c, 1, MSG_PEEK);
1802 s->frozen_readable = 0;
1805 void socket_reselect_all(void)
1810 for (i = 0; (s = index234(sktree, i)) != NULL; i++) {
1817 * For Plink: enumerate all sockets currently active.
1819 SOCKET first_socket(int *state)
1823 s = index234(sktree, (*state)++);
1824 return s ? s->s : INVALID_SOCKET;
1827 SOCKET next_socket(int *state)
1829 Actual_Socket s = index234(sktree, (*state)++);
1830 return s ? s->s : INVALID_SOCKET;
1833 extern int socket_writable(SOCKET skt)
1835 Actual_Socket s = find234(sktree, (void *)skt, cmpforsearch);
1838 return bufchain_size(&s->output_data) > 0;
1843 int net_service_lookup(char *service)
1846 se = p_getservbyname(service, NULL);
1848 return p_ntohs(se->s_port);
1853 char *get_hostname(void)
1856 char *hostname = NULL;
1859 hostname = sresize(hostname, len, char);
1860 if (p_gethostname(hostname, len) < 0) {
1865 } while (strlen(hostname) >= (size_t)(len-1));
1869 SockAddr platform_get_x11_unix_address(const char *display, int displaynum,
1870 char **canonicalname)
1872 SockAddr ret = snew(struct SockAddr_tag);
1873 memset(ret, 0, sizeof(struct SockAddr_tag));
1874 ret->error = "unix sockets not supported on this platform";