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 */
67 int frozen
; /* this causes readability notifications to be ignored */
68 int frozen_readable
; /* this means we missed at least one readability
69 * notification while we were frozen */
76 * We used to typedef struct Socket_tag *Socket.
78 * Since we have made the networking abstraction slightly more
79 * abstract, Socket no longer means a tcp socket (it could mean
80 * an ssl socket). So now we must use Actual_Socket when we know
81 * we are talking about a tcp socket.
83 typedef struct Socket_tag
*Actual_Socket
;
87 /* address family this belongs to, AF_INET for IPv4, AF_INET6 for IPv6. */
89 unsigned long address
; /* Address IPv4 style. */
91 struct addrinfo
*ai
; /* Address IPv6 style. */
95 static tree234
*sktree
;
97 static int cmpfortree(void *av
, void *bv
)
99 Actual_Socket a
= (Actual_Socket
) av
, b
= (Actual_Socket
) bv
;
100 unsigned long as
= (unsigned long) a
->s
, bs
= (unsigned long) b
->s
;
108 static int cmpforsearch(void *av
, void *bv
)
110 Actual_Socket b
= (Actual_Socket
) bv
;
111 unsigned long as
= (unsigned long) av
, bs
= (unsigned long) b
->s
;
121 sktree
= newtree234(cmpfortree
);
124 char *winsock_error_string(int error
)
128 return "Network error: Permission denied";
130 return "Network error: Address already in use";
131 case WSAEADDRNOTAVAIL
:
132 return "Network error: Cannot assign requested address";
133 case WSAEAFNOSUPPORT
:
135 "Network error: Address family not supported by protocol family";
137 return "Network error: Operation already in progress";
138 case WSAECONNABORTED
:
139 return "Network error: Software caused connection abort";
140 case WSAECONNREFUSED
:
141 return "Network error: Connection refused";
143 return "Network error: Connection reset by peer";
144 case WSAEDESTADDRREQ
:
145 return "Network error: Destination address required";
147 return "Network error: Bad address";
149 return "Network error: Host is down";
150 case WSAEHOSTUNREACH
:
151 return "Network error: No route to host";
153 return "Network error: Operation now in progress";
155 return "Network error: Interrupted function call";
157 return "Network error: Invalid argument";
159 return "Network error: Socket is already connected";
161 return "Network error: Too many open files";
163 return "Network error: Message too long";
165 return "Network error: Network is down";
167 return "Network error: Network dropped connection on reset";
169 return "Network error: Network is unreachable";
171 return "Network error: No buffer space available";
173 return "Network error: Bad protocol option";
175 return "Network error: Socket is not connected";
177 return "Network error: Socket operation on non-socket";
179 return "Network error: Operation not supported";
180 case WSAEPFNOSUPPORT
:
181 return "Network error: Protocol family not supported";
183 return "Network error: Too many processes";
184 case WSAEPROTONOSUPPORT
:
185 return "Network error: Protocol not supported";
187 return "Network error: Protocol wrong type for socket";
189 return "Network error: Cannot send after socket shutdown";
190 case WSAESOCKTNOSUPPORT
:
191 return "Network error: Socket type not supported";
193 return "Network error: Connection timed out";
195 return "Network error: Resource temporarily unavailable";
197 return "Network error: Graceful shutdown in progress";
199 return "Unknown network error";
203 SockAddr
sk_namelookup(char *host
, char **canonicalname
)
205 SockAddr ret
= smalloc(sizeof(struct SockAddr_tag
));
207 struct hostent
*h
= NULL
;
210 /* Clear the structure and default to IPv4. */
211 memset(ret
, 0, sizeof(struct SockAddr_tag
));
212 ret
->family
= 0; /* We set this one when we have resolved the host. */
215 if ((a
= inet_addr(host
)) == (unsigned long) INADDR_NONE
) {
218 /* Try to get the getaddrinfo() function from wship6.dll */
219 /* This way one doesn't need to have IPv6 dll's to use PuTTY and
220 * it will fallback to IPv4. */
221 typedef int (CALLBACK
* FGETADDRINFO
) (const char *nodename
,
222 const char *servname
,
223 const struct addrinfo
*
225 struct addrinfo
** res
);
226 FGETADDRINFO fGetAddrInfo
= NULL
;
228 HINSTANCE dllWSHIP6
= LoadLibrary("wship6.dll");
230 fGetAddrInfo
= (FGETADDRINFO
) GetProcAddress(dllWSHIP6
,
234 * Use fGetAddrInfo when it's available (which usually also
235 * means IPv6 is installed...)
238 /*debug(("Resolving \"%s\" with getaddrinfo() (IPv4+IPv6 capable)...\n", host)); */
239 if (fGetAddrInfo(host
, NULL
, NULL
, &ret
->ai
) == 0)
240 ret
->family
= ret
->ai
->ai_family
;
245 * Otherwise use the IPv4-only gethostbyname...
246 * (NOTE: we don't use gethostbyname as a
249 if (ret
->family
== 0) {
250 /*debug(("Resolving \"%s\" with gethostbyname() (IPv4 only)...\n", host)); */
251 if ( (h
= gethostbyname(host
)) )
252 ret
->family
= AF_INET
;
255 /*debug(("Done resolving...(family is %d) AF_INET = %d, AF_INET6 = %d\n", ret->family, AF_INET, AF_INET6)); */
257 if (ret
->family
== 0) {
258 DWORD err
= WSAGetLastError();
259 ret
->error
= (err
== WSAENETDOWN ?
"Network is down" :
261 WSAHOST_NOT_FOUND ?
"Host does not exist" : err
262 == WSATRY_AGAIN ?
"Host not found" :
264 fGetAddrInfo ?
"getaddrinfo: unknown error" :
266 "gethostbyname: unknown error");
270 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER
|
271 FORMAT_MESSAGE_FROM_SYSTEM
|
272 FORMAT_MESSAGE_IGNORE_INSERTS
, NULL
, err
,
273 MAKELANGID(LANG_NEUTRAL
, SUBLANG_DEFAULT
),
274 (LPTSTR
) & lpMsgBuf
, 0, NULL
);
275 /*debug(("Error %ld: %s (h=%lx)\n", err, lpMsgBuf, h)); */
276 /* Free the buffer. */
284 /* If we got an address info use that... */
286 typedef int (CALLBACK
* FGETNAMEINFO
)
287 (const struct sockaddr FAR
* sa
, socklen_t salen
,
288 char FAR
* host
, size_t hostlen
, char FAR
* serv
,
289 size_t servlen
, int flags
);
290 FGETNAMEINFO fGetNameInfo
= NULL
;
292 /* Are we in IPv4 fallback mode? */
293 /* We put the IPv4 address into the a variable so we can further-on use the IPv4 code... */
294 if (ret
->family
== AF_INET
)
296 (char *) &((SOCKADDR_IN
*) ret
->ai
->
297 ai_addr
)->sin_addr
, sizeof(a
));
299 /* Now let's find that canonicalname... */
302 (FGETNAMEINFO
) GetProcAddress(dllWSHIP6
,
305 ((struct sockaddr
*) ret
->ai
->ai_addr
,
307 AF_INET ?
sizeof(SOCKADDR_IN
) :
308 sizeof(SOCKADDR_IN6
), realhost
,
309 sizeof(realhost
), NULL
, 0, 0) != 0) {
310 strncpy(realhost
, host
, sizeof(realhost
));
314 /* We used the IPv4-only gethostbyname()... */
318 memcpy(&a
, h
->h_addr
, sizeof(a
));
319 /* This way we are always sure the h->h_name is valid :) */
320 strncpy(realhost
, h
->h_name
, sizeof(realhost
));
324 FreeLibrary(dllWSHIP6
);
328 * This must be a numeric IPv4 address because it caused a
329 * success return from inet_addr.
331 ret
->family
= AF_INET
;
332 strncpy(realhost
, host
, sizeof(realhost
));
334 ret
->address
= ntohl(a
);
335 realhost
[lenof(realhost
)-1] = '\0';
336 *canonicalname
= smalloc(1+strlen(realhost
));
337 strcpy(*canonicalname
, realhost
);
341 void sk_addr_free(SockAddr addr
)
346 static Plug
sk_tcp_plug(Socket sock
, Plug p
)
348 Actual_Socket s
= (Actual_Socket
) sock
;
355 static void sk_tcp_flush(Socket s
)
358 * We send data to the socket as soon as we can anyway,
359 * so we don't need to do anything here. :-)
363 static void sk_tcp_close(Socket s
);
364 static int sk_tcp_write(Socket s
, char *data
, int len
);
365 static int sk_tcp_write_oob(Socket s
, char *data
, int len
);
366 static char *sk_tcp_socket_error(Socket s
);
368 extern char *do_select(SOCKET skt
, int startup
);
370 Socket
sk_register(void *sock
, Plug plug
)
372 static struct socket_function_table fn_table
= {
386 * Create Socket structure.
388 ret
= smalloc(sizeof(struct Socket_tag
));
392 bufchain_init(&ret
->output_data
);
393 ret
->writable
= 1; /* to start with */
394 ret
->sending_oob
= 0;
396 ret
->frozen_readable
= 0;
398 ret
->s
= (SOCKET
)sock
;
400 if (ret
->s
== INVALID_SOCKET
) {
401 err
= WSAGetLastError();
402 ret
->error
= winsock_error_string(err
);
408 /* Set up a select mechanism. This could be an AsyncSelect on a
409 * window, or an EventSelect on an event object. */
410 errstr
= do_select(ret
->s
, 1);
421 Socket
sk_new(SockAddr addr
, int port
, int privport
, int oobinline
,
424 static struct socket_function_table fn_table
= {
444 * Create Socket structure.
446 ret
= smalloc(sizeof(struct Socket_tag
));
450 bufchain_init(&ret
->output_data
);
451 ret
->writable
= 1; /* to start with */
452 ret
->sending_oob
= 0;
454 ret
->frozen_readable
= 0;
459 s
= socket(addr
->family
, SOCK_STREAM
, 0);
462 if (s
== INVALID_SOCKET
) {
463 err
= WSAGetLastError();
464 ret
->error
= winsock_error_string(err
);
468 ret
->oobinline
= oobinline
;
471 setsockopt(s
, SOL_SOCKET
, SO_OOBINLINE
, (void *) &b
, sizeof(b
));
475 * Bind to local address.
478 localport
= 1023; /* count from 1023 downwards */
480 localport
= 0; /* just use port 0 (ie winsock picks) */
482 /* Loop round trying to bind */
487 if (addr
->family
== AF_INET6
) {
488 memset(&a6
, 0, sizeof(a6
));
489 a6
.sin6_family
= AF_INET6
;
490 /*a6.sin6_addr = in6addr_any; *//* == 0 */
491 a6
.sin6_port
= htons(localport
);
495 a
.sin_family
= AF_INET
;
496 a
.sin_addr
.s_addr
= htonl(INADDR_ANY
);
497 a
.sin_port
= htons(localport
);
500 retcode
= bind(s
, (addr
->family
== AF_INET6 ?
501 (struct sockaddr
*) &a6
:
502 (struct sockaddr
*) &a
),
504 AF_INET6 ?
sizeof(a6
) : sizeof(a
)));
506 retcode
= bind(s
, (struct sockaddr
*) &a
, sizeof(a
));
508 if (retcode
!= SOCKET_ERROR
) {
512 err
= WSAGetLastError();
513 if (err
!= WSAEADDRINUSE
) /* failed, for a bad reason */
518 break; /* we're only looping once */
521 break; /* we might have got to the end */
525 ret
->error
= winsock_error_string(err
);
530 * Connect to remote address.
533 if (addr
->family
== AF_INET6
) {
534 memset(&a
, 0, sizeof(a
));
535 a6
.sin6_family
= AF_INET6
;
536 a6
.sin6_port
= htons((short) port
);
538 ((struct sockaddr_in6
*) addr
->ai
->ai_addr
)->sin6_addr
;
542 a
.sin_family
= AF_INET
;
543 a
.sin_addr
.s_addr
= htonl(addr
->address
);
544 a
.sin_port
= htons((short) port
);
548 connect(s
, ((addr
->family
== AF_INET6
) ?
549 (struct sockaddr
*) &a6
: (struct sockaddr
*) &a
),
550 (addr
->family
== AF_INET6
) ?
sizeof(a6
) : sizeof(a
))
552 connect(s
, (struct sockaddr
*) &a
, sizeof(a
))
555 err
= WSAGetLastError();
556 ret
->error
= winsock_error_string(err
);
560 /* Set up a select mechanism. This could be an AsyncSelect on a
561 * window, or an EventSelect on an event object. */
562 errstr
= do_select(s
, 1);
573 Socket
sk_newlistenner(int port
, Plug plug
)
575 static struct socket_function_table fn_table
= {
596 * Create Socket structure.
598 ret
= smalloc(sizeof(struct Socket_tag
));
602 bufchain_init(&ret
->output_data
);
603 ret
->writable
= 0; /* to start with */
604 ret
->sending_oob
= 0;
606 ret
->frozen_readable
= 0;
611 s
= socket(AF_INET
, SOCK_STREAM
, 0);
614 if (s
== INVALID_SOCKET
) {
615 err
= WSAGetLastError();
616 ret
->error
= winsock_error_string(err
);
623 setsockopt(s
, SOL_SOCKET
, SO_REUSEADDR
, (const char *)&on
, sizeof(on
));
627 if (addr
->family
== AF_INET6
) {
628 memset(&a6
, 0, sizeof(a6
));
629 a6
.sin6_family
= AF_INET6
;
630 /*a6.sin6_addr = in6addr_any; *//* == 0 */
631 a6
.sin6_port
= htons(port
);
635 a
.sin_family
= AF_INET
;
636 a
.sin_addr
.s_addr
= htonl(INADDR_ANY
);
637 a
.sin_port
= htons((short)port
);
640 retcode
= bind(s
, (addr
->family
== AF_INET6 ?
641 (struct sockaddr
*) &a6
:
642 (struct sockaddr
*) &a
),
644 AF_INET6 ?
sizeof(a6
) : sizeof(a
)));
646 retcode
= bind(s
, (struct sockaddr
*) &a
, sizeof(a
));
648 if (retcode
!= SOCKET_ERROR
) {
651 err
= WSAGetLastError();
655 ret
->error
= winsock_error_string(err
);
660 if (listen(s
, SOMAXCONN
) == SOCKET_ERROR
) {
662 ret
->error
= winsock_error_string(err
);
666 /* Set up a select mechanism. This could be an AsyncSelect on a
667 * window, or an EventSelect on an event object. */
668 errstr
= do_select(s
, 1);
679 static void sk_tcp_close(Socket sock
)
681 extern char *do_select(SOCKET skt
, int startup
);
682 Actual_Socket s
= (Actual_Socket
) sock
;
691 * The function which tries to send on a socket once it's deemed
694 void try_send(Actual_Socket s
)
696 while (s
->sending_oob
|| bufchain_size(&s
->output_data
) > 0) {
702 if (s
->sending_oob
) {
703 urgentflag
= MSG_OOB
;
704 len
= s
->sending_oob
;
708 bufchain_prefix(&s
->output_data
, &data
, &len
);
711 nsent
= send(s
->s
, data
, len
, urgentflag
);
712 noise_ultralight(nsent
);
714 err
= (nsent
< 0 ?
WSAGetLastError() : 0);
715 if ((err
== 0 && nsent
< 0) || err
== WSAEWOULDBLOCK
) {
717 * Perfectly normal: we've sent all we can for the moment.
719 * (Apparently some WinSocks can return <0 but
720 * leave no error indication - WSAGetLastError() is
721 * called but returns zero - so we check that case
722 * and treat it just like WSAEWOULDBLOCK.)
726 } else if (nsent
== 0 ||
727 err
== WSAECONNABORTED
|| err
== WSAECONNRESET
) {
729 * FIXME. This will have to be done better when we
730 * start managing multiple sockets (e.g. SSH port
731 * forwarding), because if we get CONNRESET while
732 * trying to write a particular forwarded socket
733 * then it isn't necessarily the end of the world.
734 * Ideally I'd like to pass the error code back to
735 * somewhere the next select_result() will see it,
736 * but that might be hard. Perhaps I should pass it
737 * back to be queued in the Windows front end bit.
739 fatalbox(winsock_error_string(err
));
741 fatalbox(winsock_error_string(err
));
744 if (s
->sending_oob
) {
746 memmove(s
->oobdata
, s
->oobdata
+nsent
, len
-nsent
);
747 s
->sending_oob
= len
- nsent
;
752 bufchain_consume(&s
->output_data
, nsent
);
758 static int sk_tcp_write(Socket sock
, char *buf
, int len
)
760 Actual_Socket s
= (Actual_Socket
) sock
;
763 * Add the data to the buffer list on the socket.
765 bufchain_add(&s
->output_data
, buf
, len
);
768 * Now try sending from the start of the buffer list.
773 return bufchain_size(&s
->output_data
);
776 static int sk_tcp_write_oob(Socket sock
, char *buf
, int len
)
778 Actual_Socket s
= (Actual_Socket
) sock
;
781 * Replace the buffer list on the socket with the data.
783 bufchain_clear(&s
->output_data
);
784 assert(len
<= sizeof(s
->oobdata
));
785 memcpy(s
->oobdata
, buf
, len
);
786 s
->sending_oob
= len
;
789 * Now try sending from the start of the buffer list.
794 return s
->sending_oob
;
797 int select_result(WPARAM wParam
, LPARAM lParam
)
801 char buf
[20480]; /* nice big buffer for plenty of speed */
805 /* wParam is the socket itself */
806 s
= find234(sktree
, (void *) wParam
, cmpforsearch
);
808 return 1; /* boggle */
810 if ((err
= WSAGETSELECTERROR(lParam
)) != 0) {
812 * An error has occurred on this socket. Pass it to the
815 return plug_closing(s
->plug
, winsock_error_string(err
), err
, 0);
818 noise_ultralight(lParam
);
820 switch (WSAGETSELECTEVENT(lParam
)) {
822 /* In the case the socket is still frozen, we don't even bother */
824 s
->frozen_readable
= 1;
829 * We have received data on the socket. For an oobinline
830 * socket, this might be data _before_ an urgent pointer,
831 * in which case we send it to the back end with type==1
832 * (data prior to urgent).
836 ioctlsocket(s
->s
, SIOCATMARK
, &atmark
);
838 * Avoid checking the return value from ioctlsocket(),
839 * on the grounds that some WinSock wrappers don't
840 * support it. If it does nothing, we get atmark==1,
841 * which is equivalent to `no OOB pending', so the
842 * effect will be to non-OOB-ify any OOB data.
847 ret
= recv(s
->s
, buf
, sizeof(buf
), 0);
848 noise_ultralight(ret
);
850 err
= WSAGetLastError();
851 if (err
== WSAEWOULDBLOCK
) {
856 return plug_closing(s
->plug
, winsock_error_string(err
), err
,
858 } else if (0 == ret
) {
859 return plug_closing(s
->plug
, NULL
, 0, 0);
861 return plug_receive(s
->plug
, atmark ?
0 : 1, buf
, ret
);
866 * This will only happen on a non-oobinline socket. It
867 * indicates that we can immediately perform an OOB read
868 * and get back OOB data, which we will send to the back
869 * end with type==2 (urgent data).
871 ret
= recv(s
->s
, buf
, sizeof(buf
), MSG_OOB
);
872 noise_ultralight(ret
);
874 fatalbox(ret
== 0 ?
"Internal networking trouble" :
875 winsock_error_string(WSAGetLastError()));
877 return plug_receive(s
->plug
, 2, buf
, ret
);
882 int bufsize_before
, bufsize_after
;
884 bufsize_before
= s
->sending_oob
+ bufchain_size(&s
->output_data
);
886 bufsize_after
= s
->sending_oob
+ bufchain_size(&s
->output_data
);
887 if (bufsize_after
< bufsize_before
)
888 plug_sent(s
->plug
, bufsize_after
);
892 /* Signal a close on the socket. First read any outstanding data. */
895 ret
= recv(s
->s
, buf
, sizeof(buf
), 0);
897 err
= WSAGetLastError();
898 if (err
== WSAEWOULDBLOCK
)
900 return plug_closing(s
->plug
, winsock_error_string(err
),
904 open
&= plug_receive(s
->plug
, 0, buf
, ret
);
906 open
&= plug_closing(s
->plug
, NULL
, 0, 0);
913 int addrlen
= sizeof(struct sockaddr
);
914 SOCKET t
; /* socket of connection */
916 memset(&isa
, 0, sizeof(struct sockaddr
));
918 t
= accept(s
->s
,&isa
,&addrlen
);
919 if (t
== INVALID_SOCKET
)
921 err
= WSAGetLastError();
922 if (err
== WSATRY_AGAIN
)
926 if (plug_accepting(s
->plug
, &isa
, (void*)t
)) {
927 closesocket(t
); // denied or error
936 * Each socket abstraction contains a `void *' private field in
937 * which the client can keep state.
939 void sk_set_private_ptr(Socket sock
, void *ptr
)
941 Actual_Socket s
= (Actual_Socket
) sock
;
942 s
->private_ptr
= ptr
;
945 void *sk_get_private_ptr(Socket sock
)
947 Actual_Socket s
= (Actual_Socket
) sock
;
948 return s
->private_ptr
;
952 * Special error values are returned from sk_namelookup and sk_new
953 * if there's a problem. These functions extract an error message,
954 * or return NULL if there's no problem.
956 char *sk_addr_error(SockAddr addr
)
960 static char *sk_tcp_socket_error(Socket sock
)
962 Actual_Socket s
= (Actual_Socket
) sock
;
966 void sk_set_frozen(Socket sock
, int is_frozen
)
968 Actual_Socket s
= (Actual_Socket
) sock
;
969 if (s
->frozen
== is_frozen
)
971 s
->frozen
= is_frozen
;
972 if (!is_frozen
&& s
->frozen_readable
) {
974 recv(s
->s
, &c
, 1, MSG_PEEK
);
976 s
->frozen_readable
= 0;
980 * For Plink: enumerate all sockets currently active.
982 SOCKET
first_socket(int *state
)
986 s
= index234(sktree
, (*state
)++);
987 return s ? s
->s
: INVALID_SOCKET
;
990 SOCKET
next_socket(int *state
)
992 Actual_Socket s
= index234(sktree
, (*state
)++);
993 return s ? s
->s
: INVALID_SOCKET
;