2 * Windows networking abstraction.
4 * Due to this clean abstraction it was possible
5 * to easily implement IPv6 support :)
7 * IPv6 patch 1 (27 October 2000) Jeroen Massar <jeroen@unfix.org>
8 * - Preliminary hacked IPv6 support.
9 * - Connecting to IPv6 address (eg fec0:4242:4242:100:2d0:b7ff:fe8f:5d42) works.
10 * - Connecting to IPv6 hostname (eg heaven.ipv6.unfix.org) works.
11 * - Compiles as either IPv4 or IPv6.
13 * IPv6 patch 2 (29 October 2000) Jeroen Massar <jeroen@unfix.org>
14 * - When compiled as IPv6 it also allows connecting to IPv4 hosts.
15 * - Added some more documentation.
17 * IPv6 patch 3 (18 November 2000) Jeroen Massar <jeroen@unfix.org>
18 * - It now supports dynamically loading the IPv6 resolver dll's.
19 * This way we should be able to distribute one (1) binary
20 * which supports both IPv4 and IPv6.
21 * - getaddrinfo() and getnameinfo() are loaded dynamicaly if possible.
22 * - in6addr_any is defined in this file so we don't need to link to wship6.lib
23 * - The patch is now more unified so that we can still
24 * remove all IPv6 support by undef'ing IPV6.
25 * But where it fallsback to IPv4 it uses the IPv4 code which is already in place...
26 * - Canonical name resolving works.
28 * IPv6 patch 4 (07 January 2001) Jeroen Massar <jeroen@unfix.org>
29 * - patch against CVS of today, will be submitted to the bugs list
30 * as a 'cvs diff -u' on Simon's request...
35 * Define IPV6 to have IPv6 on-the-fly-loading support.
36 * This means that one doesn't have to have an IPv6 stack to use it.
37 * But if an IPv6 stack is found it is used with a fallback to IPv4.
53 #define DEFINE_PLUG_METHOD_MACROS
59 struct socket_function_table *fn;
60 /* the above variable absolutely *must* be the first in this structure */
68 int frozen; /* this causes readability notifications to be ignored */
69 int frozen_readable; /* this means we missed at least one readability
70 * notification while we were frozen */
71 int localhost_only; /* for listening sockets */
78 * We used to typedef struct Socket_tag *Socket.
80 * Since we have made the networking abstraction slightly more
81 * abstract, Socket no longer means a tcp socket (it could mean
82 * an ssl socket). So now we must use Actual_Socket when we know
83 * we are talking about a tcp socket.
85 typedef struct Socket_tag *Actual_Socket;
89 /* address family this belongs to, AF_INET for IPv4, AF_INET6 for IPv6. */
91 unsigned long address; /* Address IPv4 style. */
93 struct addrinfo *ai; /* Address IPv6 style. */
97 static tree234 *sktree;
99 static int cmpfortree(void *av, void *bv)
101 Actual_Socket a = (Actual_Socket) av, b = (Actual_Socket) bv;
102 unsigned long as = (unsigned long) a->s, bs = (unsigned long) b->s;
110 static int cmpforsearch(void *av, void *bv)
112 Actual_Socket b = (Actual_Socket) bv;
113 unsigned long as = (unsigned long) av, bs = (unsigned long) b->s;
123 sktree = newtree234(cmpfortree);
126 char *winsock_error_string(int error)
130 return "Network error: Permission denied";
132 return "Network error: Address already in use";
133 case WSAEADDRNOTAVAIL:
134 return "Network error: Cannot assign requested address";
135 case WSAEAFNOSUPPORT:
137 "Network error: Address family not supported by protocol family";
139 return "Network error: Operation already in progress";
140 case WSAECONNABORTED:
141 return "Network error: Software caused connection abort";
142 case WSAECONNREFUSED:
143 return "Network error: Connection refused";
145 return "Network error: Connection reset by peer";
146 case WSAEDESTADDRREQ:
147 return "Network error: Destination address required";
149 return "Network error: Bad address";
151 return "Network error: Host is down";
152 case WSAEHOSTUNREACH:
153 return "Network error: No route to host";
155 return "Network error: Operation now in progress";
157 return "Network error: Interrupted function call";
159 return "Network error: Invalid argument";
161 return "Network error: Socket is already connected";
163 return "Network error: Too many open files";
165 return "Network error: Message too long";
167 return "Network error: Network is down";
169 return "Network error: Network dropped connection on reset";
171 return "Network error: Network is unreachable";
173 return "Network error: No buffer space available";
175 return "Network error: Bad protocol option";
177 return "Network error: Socket is not connected";
179 return "Network error: Socket operation on non-socket";
181 return "Network error: Operation not supported";
182 case WSAEPFNOSUPPORT:
183 return "Network error: Protocol family not supported";
185 return "Network error: Too many processes";
186 case WSAEPROTONOSUPPORT:
187 return "Network error: Protocol not supported";
189 return "Network error: Protocol wrong type for socket";
191 return "Network error: Cannot send after socket shutdown";
192 case WSAESOCKTNOSUPPORT:
193 return "Network error: Socket type not supported";
195 return "Network error: Connection timed out";
197 return "Network error: Resource temporarily unavailable";
199 return "Network error: Graceful shutdown in progress";
201 return "Unknown network error";
205 SockAddr sk_namelookup(char *host, char **canonicalname)
207 SockAddr ret = smalloc(sizeof(struct SockAddr_tag));
209 struct hostent *h = NULL;
212 /* Clear the structure and default to IPv4. */
213 memset(ret, 0, sizeof(struct SockAddr_tag));
214 ret->family = 0; /* We set this one when we have resolved the host. */
217 if ((a = inet_addr(host)) == (unsigned long) INADDR_NONE) {
220 /* Try to get the getaddrinfo() function from wship6.dll */
221 /* This way one doesn't need to have IPv6 dll's to use PuTTY and
222 * it will fallback to IPv4. */
223 typedef int (CALLBACK * FGETADDRINFO) (const char *nodename,
224 const char *servname,
225 const struct addrinfo *
227 struct addrinfo ** res);
228 FGETADDRINFO fGetAddrInfo = NULL;
230 HINSTANCE dllWSHIP6 = LoadLibrary("wship6.dll");
232 fGetAddrInfo = (FGETADDRINFO) GetProcAddress(dllWSHIP6,
236 * Use fGetAddrInfo when it's available (which usually also
237 * means IPv6 is installed...)
240 /*debug(("Resolving \"%s\" with getaddrinfo() (IPv4+IPv6 capable)...\n", host)); */
241 if (fGetAddrInfo(host, NULL, NULL, &ret->ai) == 0)
242 ret->family = ret->ai->ai_family;
247 * Otherwise use the IPv4-only gethostbyname...
248 * (NOTE: we don't use gethostbyname as a
251 if (ret->family == 0) {
252 /*debug(("Resolving \"%s\" with gethostbyname() (IPv4 only)...\n", host)); */
253 if ( (h = gethostbyname(host)) )
254 ret->family = AF_INET;
257 /*debug(("Done resolving...(family is %d) AF_INET = %d, AF_INET6 = %d\n", ret->family, AF_INET, AF_INET6)); */
259 if (ret->family == 0) {
260 DWORD err = WSAGetLastError();
261 ret->error = (err == WSAENETDOWN ? "Network is down" :
263 WSAHOST_NOT_FOUND ? "Host does not exist" : err
264 == WSATRY_AGAIN ? "Host not found" :
266 fGetAddrInfo ? "getaddrinfo: unknown error" :
268 "gethostbyname: unknown error");
272 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
273 FORMAT_MESSAGE_FROM_SYSTEM |
274 FORMAT_MESSAGE_IGNORE_INSERTS, NULL, err,
275 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
276 (LPTSTR) & lpMsgBuf, 0, NULL);
277 /*debug(("Error %ld: %s (h=%lx)\n", err, lpMsgBuf, h)); */
278 /* Free the buffer. */
286 /* If we got an address info use that... */
288 typedef int (CALLBACK * FGETNAMEINFO)
289 (const struct sockaddr FAR * sa, socklen_t salen,
290 char FAR * host, size_t hostlen, char FAR * serv,
291 size_t servlen, int flags);
292 FGETNAMEINFO fGetNameInfo = NULL;
294 /* Are we in IPv4 fallback mode? */
295 /* We put the IPv4 address into the a variable so we can further-on use the IPv4 code... */
296 if (ret->family == AF_INET)
298 (char *) &((SOCKADDR_IN *) ret->ai->
299 ai_addr)->sin_addr, sizeof(a));
301 /* Now let's find that canonicalname... */
304 (FGETNAMEINFO) GetProcAddress(dllWSHIP6,
307 ((struct sockaddr *) ret->ai->ai_addr,
309 AF_INET ? sizeof(SOCKADDR_IN) :
310 sizeof(SOCKADDR_IN6), realhost,
311 sizeof(realhost), NULL, 0, 0) != 0) {
312 strncpy(realhost, host, sizeof(realhost));
316 /* We used the IPv4-only gethostbyname()... */
320 memcpy(&a, h->h_addr, sizeof(a));
321 /* This way we are always sure the h->h_name is valid :) */
322 strncpy(realhost, h->h_name, sizeof(realhost));
326 FreeLibrary(dllWSHIP6);
330 * This must be a numeric IPv4 address because it caused a
331 * success return from inet_addr.
333 ret->family = AF_INET;
334 strncpy(realhost, host, sizeof(realhost));
336 ret->address = ntohl(a);
337 realhost[lenof(realhost)-1] = '\0';
338 *canonicalname = smalloc(1+strlen(realhost));
339 strcpy(*canonicalname, realhost);
343 void sk_getaddr(SockAddr addr, char *buf, int buflen)
346 if (addr->family == AF_INET) {
349 a.s_addr = htonl(addr->address);
350 strncpy(buf, inet_ntoa(a), buflen);
353 FIXME; /* I don't know how to get a text form of an IPv6 address. */
358 void sk_addr_free(SockAddr addr)
363 static Plug sk_tcp_plug(Socket sock, Plug p)
365 Actual_Socket s = (Actual_Socket) sock;
372 static void sk_tcp_flush(Socket s)
375 * We send data to the socket as soon as we can anyway,
376 * so we don't need to do anything here. :-)
380 static void sk_tcp_close(Socket s);
381 static int sk_tcp_write(Socket s, char *data, int len);
382 static int sk_tcp_write_oob(Socket s, char *data, int len);
383 static char *sk_tcp_socket_error(Socket s);
385 extern char *do_select(SOCKET skt, int startup);
387 Socket sk_register(void *sock, Plug plug)
389 static struct socket_function_table fn_table = {
403 * Create Socket structure.
405 ret = smalloc(sizeof(struct Socket_tag));
409 bufchain_init(&ret->output_data);
410 ret->writable = 1; /* to start with */
411 ret->sending_oob = 0;
413 ret->frozen_readable = 0;
414 ret->localhost_only = 0; /* unused, but best init anyway */
416 ret->s = (SOCKET)sock;
418 if (ret->s == INVALID_SOCKET) {
419 err = WSAGetLastError();
420 ret->error = winsock_error_string(err);
426 /* Set up a select mechanism. This could be an AsyncSelect on a
427 * window, or an EventSelect on an event object. */
428 errstr = do_select(ret->s, 1);
439 Socket sk_new(SockAddr addr, int port, int privport, int oobinline,
442 static struct socket_function_table fn_table = {
462 * Create Socket structure.
464 ret = smalloc(sizeof(struct Socket_tag));
468 bufchain_init(&ret->output_data);
469 ret->connected = 0; /* to start with */
470 ret->writable = 0; /* to start with */
471 ret->sending_oob = 0;
473 ret->frozen_readable = 0;
474 ret->localhost_only = 0; /* unused, but best init anyway */
479 s = socket(addr->family, SOCK_STREAM, 0);
482 if (s == INVALID_SOCKET) {
483 err = WSAGetLastError();
484 ret->error = winsock_error_string(err);
488 ret->oobinline = oobinline;
491 setsockopt(s, SOL_SOCKET, SO_OOBINLINE, (void *) &b, sizeof(b));
495 * Bind to local address.
498 localport = 1023; /* count from 1023 downwards */
500 localport = 0; /* just use port 0 (ie winsock picks) */
502 /* Loop round trying to bind */
507 if (addr->family == AF_INET6) {
508 memset(&a6, 0, sizeof(a6));
509 a6.sin6_family = AF_INET6;
510 /*a6.sin6_addr = in6addr_any; *//* == 0 */
511 a6.sin6_port = htons(localport);
515 a.sin_family = AF_INET;
516 a.sin_addr.s_addr = htonl(INADDR_ANY);
517 a.sin_port = htons(localport);
520 retcode = bind(s, (addr->family == AF_INET6 ?
521 (struct sockaddr *) &a6 :
522 (struct sockaddr *) &a),
524 AF_INET6 ? sizeof(a6) : sizeof(a)));
526 retcode = bind(s, (struct sockaddr *) &a, sizeof(a));
528 if (retcode != SOCKET_ERROR) {
532 err = WSAGetLastError();
533 if (err != WSAEADDRINUSE) /* failed, for a bad reason */
538 break; /* we're only looping once */
541 break; /* we might have got to the end */
545 ret->error = winsock_error_string(err);
550 * Connect to remote address.
553 if (addr->family == AF_INET6) {
554 memset(&a, 0, sizeof(a));
555 a6.sin6_family = AF_INET6;
556 a6.sin6_port = htons((short) port);
558 ((struct sockaddr_in6 *) addr->ai->ai_addr)->sin6_addr;
562 a.sin_family = AF_INET;
563 a.sin_addr.s_addr = htonl(addr->address);
564 a.sin_port = htons((short) port);
567 /* Set up a select mechanism. This could be an AsyncSelect on a
568 * window, or an EventSelect on an event object. */
569 errstr = do_select(s, 1);
577 connect(s, ((addr->family == AF_INET6) ?
578 (struct sockaddr *) &a6 : (struct sockaddr *) &a),
579 (addr->family == AF_INET6) ? sizeof(a6) : sizeof(a))
581 connect(s, (struct sockaddr *) &a, sizeof(a))
584 err = WSAGetLastError();
586 * We expect a potential EWOULDBLOCK here, because the
587 * chances are the front end has done a select for
588 * FD_CONNECT, so that connect() will complete
591 if ( err != WSAEWOULDBLOCK ) {
592 ret->error = winsock_error_string(err);
597 * If we _don't_ get EWOULDBLOCK, the connect has completed
598 * and we should set the socket as writable.
608 Socket sk_newlistener(int port, Plug plug, int local_host_only)
610 static struct socket_function_table fn_table = {
631 * Create Socket structure.
633 ret = smalloc(sizeof(struct Socket_tag));
637 bufchain_init(&ret->output_data);
638 ret->writable = 0; /* to start with */
639 ret->sending_oob = 0;
641 ret->frozen_readable = 0;
642 ret->localhost_only = local_host_only;
647 s = socket(AF_INET, SOCK_STREAM, 0);
650 if (s == INVALID_SOCKET) {
651 err = WSAGetLastError();
652 ret->error = winsock_error_string(err);
659 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (const char *)&on, sizeof(on));
663 if (addr->family == AF_INET6) {
664 memset(&a6, 0, sizeof(a6));
665 a6.sin6_family = AF_INET6;
667 a6.sin6_addr = in6addr_loopback;
669 a6.sin6_addr = in6addr_any;
670 a6.sin6_port = htons(port);
674 a.sin_family = AF_INET;
676 a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
678 a.sin_addr.s_addr = htonl(INADDR_ANY);
679 a.sin_port = htons((short)port);
682 retcode = bind(s, (addr->family == AF_INET6 ?
683 (struct sockaddr *) &a6 :
684 (struct sockaddr *) &a),
686 AF_INET6 ? sizeof(a6) : sizeof(a)));
688 retcode = bind(s, (struct sockaddr *) &a, sizeof(a));
690 if (retcode != SOCKET_ERROR) {
693 err = WSAGetLastError();
697 ret->error = winsock_error_string(err);
702 if (listen(s, SOMAXCONN) == SOCKET_ERROR) {
704 ret->error = winsock_error_string(err);
708 /* Set up a select mechanism. This could be an AsyncSelect on a
709 * window, or an EventSelect on an event object. */
710 errstr = do_select(s, 1);
721 static void sk_tcp_close(Socket sock)
723 extern char *do_select(SOCKET skt, int startup);
724 Actual_Socket s = (Actual_Socket) sock;
733 * The function which tries to send on a socket once it's deemed
736 void try_send(Actual_Socket s)
738 while (s->sending_oob || bufchain_size(&s->output_data) > 0) {
744 if (s->sending_oob) {
745 urgentflag = MSG_OOB;
746 len = s->sending_oob;
750 bufchain_prefix(&s->output_data, &data, &len);
752 nsent = send(s->s, data, len, urgentflag);
753 noise_ultralight(nsent);
755 err = (nsent < 0 ? WSAGetLastError() : 0);
756 if ((err < WSABASEERR && nsent < 0) || err == WSAEWOULDBLOCK) {
758 * Perfectly normal: we've sent all we can for the moment.
760 * (Some WinSock send() implementations can return
761 * <0 but leave no sensible error indication -
762 * WSAGetLastError() is called but returns zero or
763 * a small number - so we check that case and treat
764 * it just like WSAEWOULDBLOCK.)
768 } else if (nsent == 0 ||
769 err == WSAECONNABORTED || err == WSAECONNRESET) {
773 * I'm assuming here that if a TCP connection is
774 * reset or aborted once established, we will be
775 * notified by a select event rather than a
776 * CONNABORTED or CONNRESET from send(). In other
777 * words, I'm assuming CONNABORTED and CONNRESET
778 * don't come back from a _nonblocking_ send(),
779 * because the local side doesn't know they've
780 * happened until it waits for a response to its
781 * TCP segment - so the error will arrive
784 * If I'm wrong, this will be a really nasty case,
785 * because we can't necessarily call plug_closing()
786 * without having to make half the SSH code
787 * reentrant; so instead we'll have to schedule a
788 * call to plug_closing() for some suitable future
791 fatalbox("SERIOUS NETWORK INTERNAL ERROR: %s\n"
792 "Please report this immediately to "
793 "<putty@projects.tartarus.org>.",
794 winsock_error_string(err));
796 fatalbox(winsock_error_string(err));
799 if (s->sending_oob) {
801 memmove(s->oobdata, s->oobdata+nsent, len-nsent);
802 s->sending_oob = len - nsent;
807 bufchain_consume(&s->output_data, nsent);
813 static int sk_tcp_write(Socket sock, char *buf, int len)
815 Actual_Socket s = (Actual_Socket) sock;
818 * Add the data to the buffer list on the socket.
820 bufchain_add(&s->output_data, buf, len);
823 * Now try sending from the start of the buffer list.
828 return bufchain_size(&s->output_data);
831 static int sk_tcp_write_oob(Socket sock, char *buf, int len)
833 Actual_Socket s = (Actual_Socket) sock;
836 * Replace the buffer list on the socket with the data.
838 bufchain_clear(&s->output_data);
839 assert(len <= sizeof(s->oobdata));
840 memcpy(s->oobdata, buf, len);
841 s->sending_oob = len;
844 * Now try sending from the start of the buffer list.
849 return s->sending_oob;
852 int select_result(WPARAM wParam, LPARAM lParam)
856 char buf[20480]; /* nice big buffer for plenty of speed */
860 /* wParam is the socket itself */
861 s = find234(sktree, (void *) wParam, cmpforsearch);
863 return 1; /* boggle */
865 if ((err = WSAGETSELECTERROR(lParam)) != 0) {
867 * An error has occurred on this socket. Pass it to the
870 return plug_closing(s->plug, winsock_error_string(err), err, 0);
873 noise_ultralight(lParam);
875 switch (WSAGETSELECTEVENT(lParam)) {
877 s->connected = s->writable = 1;
880 /* In the case the socket is still frozen, we don't even bother */
882 s->frozen_readable = 1;
887 * We have received data on the socket. For an oobinline
888 * socket, this might be data _before_ an urgent pointer,
889 * in which case we send it to the back end with type==1
890 * (data prior to urgent).
894 ioctlsocket(s->s, SIOCATMARK, &atmark);
896 * Avoid checking the return value from ioctlsocket(),
897 * on the grounds that some WinSock wrappers don't
898 * support it. If it does nothing, we get atmark==1,
899 * which is equivalent to `no OOB pending', so the
900 * effect will be to non-OOB-ify any OOB data.
905 ret = recv(s->s, buf, sizeof(buf), 0);
906 noise_ultralight(ret);
908 err = WSAGetLastError();
909 if (err == WSAEWOULDBLOCK) {
914 return plug_closing(s->plug, winsock_error_string(err), err,
916 } else if (0 == ret) {
917 return plug_closing(s->plug, NULL, 0, 0);
919 return plug_receive(s->plug, atmark ? 0 : 1, buf, ret);
924 * This will only happen on a non-oobinline socket. It
925 * indicates that we can immediately perform an OOB read
926 * and get back OOB data, which we will send to the back
927 * end with type==2 (urgent data).
929 ret = recv(s->s, buf, sizeof(buf), MSG_OOB);
930 noise_ultralight(ret);
932 fatalbox(ret == 0 ? "Internal networking trouble" :
933 winsock_error_string(WSAGetLastError()));
935 return plug_receive(s->plug, 2, buf, ret);
940 int bufsize_before, bufsize_after;
942 bufsize_before = s->sending_oob + bufchain_size(&s->output_data);
944 bufsize_after = s->sending_oob + bufchain_size(&s->output_data);
945 if (bufsize_after < bufsize_before)
946 plug_sent(s->plug, bufsize_after);
950 /* Signal a close on the socket. First read any outstanding data. */
953 ret = recv(s->s, buf, sizeof(buf), 0);
955 err = WSAGetLastError();
956 if (err == WSAEWOULDBLOCK)
958 return plug_closing(s->plug, winsock_error_string(err),
962 open &= plug_receive(s->plug, 0, buf, ret);
964 open &= plug_closing(s->plug, NULL, 0, 0);
970 struct sockaddr_in isa;
971 int addrlen = sizeof(struct sockaddr_in);
972 SOCKET t; /* socket of connection */
974 memset(&isa, 0, sizeof(struct sockaddr_in));
976 t = accept(s->s,&isa,&addrlen);
977 if (t == INVALID_SOCKET)
979 err = WSAGetLastError();
980 if (err == WSATRY_AGAIN)
984 if (s->localhost_only &&
985 ntohl(isa.sin_addr.s_addr) != INADDR_LOOPBACK) {
986 closesocket(t); /* dodgy WinSock let nonlocal through */
987 } else if (plug_accepting(s->plug, (void*)t)) {
988 closesocket(t); /* denied or error */
997 * Each socket abstraction contains a `void *' private field in
998 * which the client can keep state.
1000 void sk_set_private_ptr(Socket sock, void *ptr)
1002 Actual_Socket s = (Actual_Socket) sock;
1003 s->private_ptr = ptr;
1006 void *sk_get_private_ptr(Socket sock)
1008 Actual_Socket s = (Actual_Socket) sock;
1009 return s->private_ptr;
1013 * Special error values are returned from sk_namelookup and sk_new
1014 * if there's a problem. These functions extract an error message,
1015 * or return NULL if there's no problem.
1017 char *sk_addr_error(SockAddr addr)
1021 static char *sk_tcp_socket_error(Socket sock)
1023 Actual_Socket s = (Actual_Socket) sock;
1027 void sk_set_frozen(Socket sock, int is_frozen)
1029 Actual_Socket s = (Actual_Socket) sock;
1030 if (s->frozen == is_frozen)
1032 s->frozen = is_frozen;
1033 if (!is_frozen && s->frozen_readable) {
1035 recv(s->s, &c, 1, MSG_PEEK);
1037 s->frozen_readable = 0;
1041 * For Plink: enumerate all sockets currently active.
1043 SOCKET first_socket(int *state)
1047 s = index234(sktree, (*state)++);
1048 return s ? s->s : INVALID_SOCKET;
1051 SOCKET next_socket(int *state)
1053 Actual_Socket s = index234(sktree, (*state)++);
1054 return s ? s->s : INVALID_SOCKET;