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.
52 #define DEFINE_PLUG_METHOD_MACROS
57 #define BUFFER_GRANULE 512
60 struct socket_function_table *fn;
61 /* the above variable absolutely *must* be the first in this structure */
66 struct buffer *head, *tail;
68 int frozen; /* this tells the write stuff not to even bother trying to send at this point */
74 * We used to typedef struct Socket_tag *Socket.
76 * Since we have made the networking abstraction slightly more
77 * abstract, Socket no longer means a tcp socket (it could mean
78 * an ssl socket). So now we must use Actual_Socket when we know
79 * we are talking about a tcp socket.
81 typedef struct Socket_tag *Actual_Socket;
85 /* address family this belongs to, AF_INET for IPv4, AF_INET6 for IPv6. */
87 unsigned long address; /* Address IPv4 style. */
89 struct addrinfo *ai; /* Address IPv6 style. */
96 char buf[BUFFER_GRANULE];
99 static tree234 *sktree;
101 static int cmpfortree(void *av, void *bv)
103 Actual_Socket a = (Actual_Socket) av, b = (Actual_Socket) bv;
104 unsigned long as = (unsigned long) a->s, bs = (unsigned long) b->s;
112 static int cmpforsearch(void *av, void *bv)
114 Actual_Socket b = (Actual_Socket) bv;
115 unsigned long as = (unsigned long) av, bs = (unsigned long) b->s;
125 sktree = newtree234(cmpfortree);
128 char *winsock_error_string(int error)
132 return "Network error: Permission denied";
134 return "Network error: Address already in use";
135 case WSAEADDRNOTAVAIL:
136 return "Network error: Cannot assign requested address";
137 case WSAEAFNOSUPPORT:
139 "Network error: Address family not supported by protocol family";
141 return "Network error: Operation already in progress";
142 case WSAECONNABORTED:
143 return "Network error: Software caused connection abort";
144 case WSAECONNREFUSED:
145 return "Network error: Connection refused";
147 return "Network error: Connection reset by peer";
148 case WSAEDESTADDRREQ:
149 return "Network error: Destination address required";
151 return "Network error: Bad address";
153 return "Network error: Host is down";
154 case WSAEHOSTUNREACH:
155 return "Network error: No route to host";
157 return "Network error: Operation now in progress";
159 return "Network error: Interrupted function call";
161 return "Network error: Invalid argument";
163 return "Network error: Socket is already connected";
165 return "Network error: Too many open files";
167 return "Network error: Message too long";
169 return "Network error: Network is down";
171 return "Network error: Network dropped connection on reset";
173 return "Network error: Network is unreachable";
175 return "Network error: No buffer space available";
177 return "Network error: Bad protocol option";
179 return "Network error: Socket is not connected";
181 return "Network error: Socket operation on non-socket";
183 return "Network error: Operation not supported";
184 case WSAEPFNOSUPPORT:
185 return "Network error: Protocol family not supported";
187 return "Network error: Too many processes";
188 case WSAEPROTONOSUPPORT:
189 return "Network error: Protocol not supported";
191 return "Network error: Protocol wrong type for socket";
193 return "Network error: Cannot send after socket shutdown";
194 case WSAESOCKTNOSUPPORT:
195 return "Network error: Socket type not supported";
197 return "Network error: Connection timed out";
199 return "Network error: Resource temporarily unavailable";
201 return "Network error: Graceful shutdown in progress";
203 return "Unknown network error";
207 SockAddr sk_namelookup(char *host, char **canonicalname)
209 SockAddr ret = smalloc(sizeof(struct SockAddr_tag));
211 struct hostent *h = NULL;
214 /* Clear the structure and default to IPv4. */
215 memset(ret, 0, sizeof(struct SockAddr_tag));
216 ret->family = 0; /* We set this one when we have resolved the host. */
219 if ((a = inet_addr(host)) == (unsigned long) INADDR_NONE) {
222 /* Try to get the getaddrinfo() function from wship6.dll */
223 /* This way one doesn't need to have IPv6 dll's to use PuTTY and
224 * it will fallback to IPv4. */
225 typedef int (CALLBACK * FGETADDRINFO) (const char *nodename,
226 const char *servname,
227 const struct addrinfo *
229 struct addrinfo ** res);
230 FGETADDRINFO fGetAddrInfo = NULL;
232 HINSTANCE dllWSHIP6 = LoadLibrary("wship6.dll");
234 fGetAddrInfo = (FGETADDRINFO) GetProcAddress(dllWSHIP6,
238 * Use fGetAddrInfo when it's available (which usually also
239 * means IPv6 is installed...)
242 /*debug(("Resolving \"%s\" with getaddrinfo() (IPv4+IPv6 capable)...\n", host)); */
243 if (fGetAddrInfo(host, NULL, NULL, &ret->ai) == 0)
244 ret->family = ret->ai->ai_family;
249 * Otherwise use the IPv4-only gethostbyname...
250 * (NOTE: we don't use gethostbyname as a
253 if (ret->family == 0) {
254 /*debug(("Resolving \"%s\" with gethostbyname() (IPv4 only)...\n", host)); */
255 if ( (h = gethostbyname(host)) )
256 ret->family = AF_INET;
259 /*debug(("Done resolving...(family is %d) AF_INET = %d, AF_INET6 = %d\n", ret->family, AF_INET, AF_INET6)); */
261 if (ret->family == 0) {
262 DWORD err = WSAGetLastError();
263 ret->error = (err == WSAENETDOWN ? "Network is down" :
265 WSAHOST_NOT_FOUND ? "Host does not exist" : err
266 == WSATRY_AGAIN ? "Host not found" :
268 fGetAddrInfo ? "getaddrinfo: unknown error" :
270 "gethostbyname: unknown error");
274 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
275 FORMAT_MESSAGE_FROM_SYSTEM |
276 FORMAT_MESSAGE_IGNORE_INSERTS, NULL, err,
277 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
278 (LPTSTR) & lpMsgBuf, 0, NULL);
279 /*debug(("Error %ld: %s (h=%lx)\n", err, lpMsgBuf, h)); */
280 /* Free the buffer. */
288 /* If we got an address info use that... */
290 typedef int (CALLBACK * FGETNAMEINFO)
291 (const struct sockaddr FAR * sa, socklen_t salen,
292 char FAR * host, size_t hostlen, char FAR * serv,
293 size_t servlen, int flags);
294 FGETNAMEINFO fGetNameInfo = NULL;
296 /* Are we in IPv4 fallback mode? */
297 /* We put the IPv4 address into the a variable so we can further-on use the IPv4 code... */
298 if (ret->family == AF_INET)
300 (char *) &((SOCKADDR_IN *) ret->ai->
301 ai_addr)->sin_addr, sizeof(a));
303 /* Now let's find that canonicalname... */
306 (FGETNAMEINFO) GetProcAddress(dllWSHIP6,
309 ((struct sockaddr *) ret->ai->ai_addr,
311 AF_INET ? sizeof(SOCKADDR_IN) :
312 sizeof(SOCKADDR_IN6), realhost,
313 sizeof(realhost), NULL, 0, 0) != 0) {
314 strncpy(realhost, host, sizeof(realhost));
318 /* We used the IPv4-only gethostbyname()... */
322 memcpy(&a, h->h_addr, sizeof(a));
323 /* This way we are always sure the h->h_name is valid :) */
324 strncpy(realhost, h->h_name, sizeof(realhost));
328 FreeLibrary(dllWSHIP6);
332 * This must be a numeric IPv4 address because it caused a
333 * success return from inet_addr.
335 ret->family = AF_INET;
336 strncpy(realhost, host, sizeof(realhost));
338 ret->address = ntohl(a);
339 realhost[lenof(realhost)-1] = '\0';
340 *canonicalname = smalloc(1+strlen(realhost));
341 strcpy(*canonicalname, realhost);
345 void sk_addr_free(SockAddr addr)
350 static Plug sk_tcp_plug(Socket sock, Plug p)
352 Actual_Socket s = (Actual_Socket) sock;
359 static void sk_tcp_flush(Socket s)
362 * We send data to the socket as soon as we can anyway,
363 * so we don't need to do anything here. :-)
367 static void sk_tcp_close(Socket s);
368 static void sk_tcp_write(Socket s, char *data, int len);
369 static void sk_tcp_write_oob(Socket s, char *data, int len);
370 static char *sk_tcp_socket_error(Socket s);
372 extern char *do_select(SOCKET skt, int startup);
374 Socket sk_register(void *sock, Plug plug)
376 static struct socket_function_table fn_table = {
390 * Create Socket structure.
392 ret = smalloc(sizeof(struct Socket_tag));
396 ret->head = ret->tail = NULL;
397 ret->writable = 1; /* to start with */
398 ret->sending_oob = 0;
401 ret->s = (SOCKET)sock;
403 if (ret->s == INVALID_SOCKET) {
404 err = WSAGetLastError();
405 ret->error = winsock_error_string(err);
411 /* Set up a select mechanism. This could be an AsyncSelect on a
412 * window, or an EventSelect on an event object. */
413 errstr = do_select(ret->s, 1);
424 Socket sk_new(SockAddr addr, int port, int privport, int oobinline,
427 static struct socket_function_table fn_table = {
447 * Create Socket structure.
449 ret = smalloc(sizeof(struct Socket_tag));
453 ret->head = ret->tail = NULL;
454 ret->writable = 1; /* to start with */
455 ret->sending_oob = 0;
461 s = socket(addr->family, SOCK_STREAM, 0);
464 if (s == INVALID_SOCKET) {
465 err = WSAGetLastError();
466 ret->error = winsock_error_string(err);
470 ret->oobinline = oobinline;
473 setsockopt(s, SOL_SOCKET, SO_OOBINLINE, (void *) &b, sizeof(b));
477 * Bind to local address.
480 localport = 1023; /* count from 1023 downwards */
482 localport = 0; /* just use port 0 (ie winsock picks) */
484 /* Loop round trying to bind */
489 if (addr->family == AF_INET6) {
490 memset(&a6, 0, sizeof(a6));
491 a6.sin6_family = AF_INET6;
492 /*a6.sin6_addr = in6addr_any; *//* == 0 */
493 a6.sin6_port = htons(localport);
497 a.sin_family = AF_INET;
498 a.sin_addr.s_addr = htonl(INADDR_ANY);
499 a.sin_port = htons(localport);
502 retcode = bind(s, (addr->family == AF_INET6 ?
503 (struct sockaddr *) &a6 :
504 (struct sockaddr *) &a),
506 AF_INET6 ? sizeof(a6) : sizeof(a)));
508 retcode = bind(s, (struct sockaddr *) &a, sizeof(a));
510 if (retcode != SOCKET_ERROR) {
514 err = WSAGetLastError();
515 if (err != WSAEADDRINUSE) /* failed, for a bad reason */
520 break; /* we're only looping once */
523 break; /* we might have got to the end */
527 ret->error = winsock_error_string(err);
532 * Connect to remote address.
535 if (addr->family == AF_INET6) {
536 memset(&a, 0, sizeof(a));
537 a6.sin6_family = AF_INET6;
538 a6.sin6_port = htons((short) port);
540 ((struct sockaddr_in6 *) addr->ai->ai_addr)->sin6_addr;
544 a.sin_family = AF_INET;
545 a.sin_addr.s_addr = htonl(addr->address);
546 a.sin_port = htons((short) port);
550 connect(s, ((addr->family == AF_INET6) ?
551 (struct sockaddr *) &a6 : (struct sockaddr *) &a),
552 (addr->family == AF_INET6) ? sizeof(a6) : sizeof(a))
554 connect(s, (struct sockaddr *) &a, sizeof(a))
557 err = WSAGetLastError();
558 ret->error = winsock_error_string(err);
562 /* Set up a select mechanism. This could be an AsyncSelect on a
563 * window, or an EventSelect on an event object. */
564 errstr = do_select(s, 1);
575 Socket sk_newlistenner(int port, Plug plug)
577 static struct socket_function_table fn_table = {
598 * Create Socket structure.
600 ret = smalloc(sizeof(struct Socket_tag));
604 ret->head = ret->tail = NULL;
605 ret->writable = 0; /* to start with */
606 ret->sending_oob = 0;
612 s = socket(AF_INET, SOCK_STREAM, 0);
615 if (s == INVALID_SOCKET) {
616 err = WSAGetLastError();
617 ret->error = winsock_error_string(err);
624 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (const char *)&on, sizeof(on));
628 if (addr->family == AF_INET6) {
629 memset(&a6, 0, sizeof(a6));
630 a6.sin6_family = AF_INET6;
631 /*a6.sin6_addr = in6addr_any; *//* == 0 */
632 a6.sin6_port = htons(port);
636 a.sin_family = AF_INET;
637 a.sin_addr.s_addr = htonl(INADDR_ANY);
638 a.sin_port = htons((short)port);
641 retcode = bind(s, (addr->family == AF_INET6 ?
642 (struct sockaddr *) &a6 :
643 (struct sockaddr *) &a),
645 AF_INET6 ? sizeof(a6) : sizeof(a)));
647 retcode = bind(s, (struct sockaddr *) &a, sizeof(a));
649 if (retcode != SOCKET_ERROR) {
652 err = WSAGetLastError();
656 ret->error = winsock_error_string(err);
661 if (listen(s, SOMAXCONN) == SOCKET_ERROR) {
663 ret->error = winsock_error_string(err);
667 /* Set up a select mechanism. This could be an AsyncSelect on a
668 * window, or an EventSelect on an event object. */
669 errstr = do_select(s, 1);
680 static void sk_tcp_close(Socket sock)
682 extern char *do_select(SOCKET skt, int startup);
683 Actual_Socket s = (Actual_Socket) sock;
692 * The function which tries to send on a socket once it's deemed
695 void try_send(Actual_Socket s)
697 if (s->frozen) return;
703 if (s->sending_oob) {
704 urgentflag = MSG_OOB;
705 len = s->sending_oob;
708 len = s->head->buflen - s->head->bufpos;
712 send(s->s, s->head->buf + s->head->bufpos, len, urgentflag);
713 noise_ultralight(nsent);
715 err = (nsent < 0 ? WSAGetLastError() : 0);
716 if ((err == 0 && nsent < 0) || err == WSAEWOULDBLOCK) {
718 * Perfectly normal: we've sent all we can for the moment.
720 * (Apparently some WinSocks can return <0 but
721 * leave no error indication - WSAGetLastError() is
722 * called but returns zero - so we check that case
723 * and treat it just like WSAEWOULDBLOCK.)
727 } else if (nsent == 0 ||
728 err == WSAECONNABORTED || err == WSAECONNRESET) {
730 * FIXME. This will have to be done better when we
731 * start managing multiple sockets (e.g. SSH port
732 * forwarding), because if we get CONNRESET while
733 * trying to write a particular forwarded socket
734 * then it isn't necessarily the end of the world.
735 * Ideally I'd like to pass the error code back to
736 * somewhere the next select_result() will see it,
737 * but that might be hard. Perhaps I should pass it
738 * back to be queued in the Windows front end bit.
740 fatalbox(winsock_error_string(err));
742 fatalbox(winsock_error_string(err));
745 s->head->bufpos += nsent;
747 s->sending_oob -= nsent;
748 if (s->head->bufpos >= s->head->buflen) {
749 struct buffer *tmp = s->head;
759 static void sk_tcp_write(Socket sock, char *buf, int len)
761 Actual_Socket s = (Actual_Socket) sock;
764 * Add the data to the buffer list on the socket.
766 if (s->tail && s->tail->buflen < BUFFER_GRANULE) {
767 int copylen = min(len, BUFFER_GRANULE - s->tail->buflen);
768 memcpy(s->tail->buf + s->tail->buflen, buf, copylen);
771 s->tail->buflen += copylen;
774 int grainlen = min(len, BUFFER_GRANULE);
775 struct buffer *newbuf;
776 newbuf = smalloc(sizeof(struct buffer));
778 newbuf->buflen = grainlen;
779 memcpy(newbuf->buf, buf, grainlen);
783 s->tail->next = newbuf;
785 s->head = s->tail = newbuf;
791 * Now try sending from the start of the buffer list.
797 static void sk_tcp_write_oob(Socket sock, char *buf, int len)
799 Actual_Socket s = (Actual_Socket) sock;
802 * Replace the buffer list on the socket with the data.
805 s->head = smalloc(sizeof(struct buffer));
807 struct buffer *walk = s->head->next;
809 struct buffer *tmp = walk;
814 s->head->next = NULL;
816 s->head->buflen = len;
817 memcpy(s->head->buf, buf, len);
820 * Set the Urgent marker.
822 s->sending_oob = len;
825 * Now try sending from the start of the buffer list.
831 int select_result(WPARAM wParam, LPARAM lParam)
835 char buf[20480]; /* nice big buffer for plenty of speed */
839 /* wParam is the socket itself */
840 s = find234(sktree, (void *) wParam, cmpforsearch);
842 return 1; /* boggle */
844 if ((err = WSAGETSELECTERROR(lParam)) != 0) {
846 * An error has occurred on this socket. Pass it to the
849 return plug_closing(s->plug, winsock_error_string(err), err, 0);
852 noise_ultralight(lParam);
854 switch (WSAGETSELECTEVENT(lParam)) {
857 /* In the case the socket is still frozen, we don't even bother */
862 * We have received data on the socket. For an oobinline
863 * socket, this might be data _before_ an urgent pointer,
864 * in which case we send it to the back end with type==1
865 * (data prior to urgent).
869 ioctlsocket(s->s, SIOCATMARK, &atmark);
871 * Avoid checking the return value from ioctlsocket(),
872 * on the grounds that some WinSock wrappers don't
873 * support it. If it does nothing, we get atmark==1,
874 * which is equivalent to `no OOB pending', so the
875 * effect will be to non-OOB-ify any OOB data.
880 ret = recv(s->s, buf, sizeof(buf), 0);
881 noise_ultralight(ret);
883 err = WSAGetLastError();
884 if (err == WSAEWOULDBLOCK) {
889 return plug_closing(s->plug, winsock_error_string(err), err,
891 } else if (0 == ret) {
892 return plug_closing(s->plug, NULL, 0, 0);
894 return plug_receive(s->plug, atmark ? 0 : 1, buf, ret);
899 * This will only happen on a non-oobinline socket. It
900 * indicates that we can immediately perform an OOB read
901 * and get back OOB data, which we will send to the back
902 * end with type==2 (urgent data).
904 ret = recv(s->s, buf, sizeof(buf), MSG_OOB);
905 noise_ultralight(ret);
907 fatalbox(ret == 0 ? "Internal networking trouble" :
908 winsock_error_string(WSAGetLastError()));
910 return plug_receive(s->plug, 2, buf, ret);
918 /* Signal a close on the socket. First read any outstanding data. */
921 ret = recv(s->s, buf, sizeof(buf), 0);
923 err = WSAGetLastError();
924 if (err == WSAEWOULDBLOCK)
926 return plug_closing(s->plug, winsock_error_string(err),
930 open &= plug_receive(s->plug, 0, buf, ret);
932 open &= plug_closing(s->plug, NULL, 0, 0);
939 int addrlen = sizeof(struct sockaddr);
940 SOCKET t; /* socket of connection */
942 memset(&isa, 0, sizeof(struct sockaddr));
944 t = accept(s->s,&isa,&addrlen);
945 if (t == INVALID_SOCKET)
947 err = WSAGetLastError();
948 if (err == WSATRY_AGAIN)
952 if (plug_accepting(s->plug, &isa, (void*)t)) {
953 closesocket(t); // denied or error
962 * Each socket abstraction contains a `void *' private field in
963 * which the client can keep state.
965 void sk_set_private_ptr(Socket sock, void *ptr)
967 Actual_Socket s = (Actual_Socket) sock;
968 s->private_ptr = ptr;
971 void *sk_get_private_ptr(Socket sock)
973 Actual_Socket s = (Actual_Socket) sock;
974 return s->private_ptr;
978 * Special error values are returned from sk_namelookup and sk_new
979 * if there's a problem. These functions extract an error message,
980 * or return NULL if there's no problem.
982 char *sk_addr_error(SockAddr addr)
986 static char *sk_tcp_socket_error(Socket sock)
988 Actual_Socket s = (Actual_Socket) sock;
992 void sk_set_frozen(Socket sock, int is_frozen)
994 Actual_Socket s = (Actual_Socket) sock;
995 s->frozen = is_frozen;
998 recv(s->s, &c, 1, MSG_PEEK);
1003 * For Plink: enumerate all sockets currently active.
1005 SOCKET first_socket(int *state)
1009 s = index234(sktree, (*state)++);
1010 return s ? s->s : INVALID_SOCKET;
1013 SOCKET next_socket(int *state)
1015 Actual_Socket s = index234(sktree, (*state)++);
1016 return s ? s->s : INVALID_SOCKET;