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
;
73 * We used to typedef struct Socket_tag *Socket.
75 * Since we have made the networking abstraction slightly more
76 * abstract, Socket no longer means a tcp socket (it could mean
77 * an ssl socket). So now we must use Actual_Socket when we know
78 * we are talking about a tcp socket.
80 typedef struct Socket_tag
*Actual_Socket
;
84 /* address family this belongs to, AF_INET for IPv4, AF_INET6 for IPv6. */
86 unsigned long address
; /* Address IPv4 style. */
88 struct addrinfo
*ai
; /* Address IPv6 style. */
91 * We need to have this lengthy enough to hold *any* hostname
92 * (including IPv6 reverse...)
100 char buf
[BUFFER_GRANULE
];
103 static tree234
*sktree
;
105 static int cmpfortree(void *av
, void *bv
)
107 Actual_Socket a
= (Actual_Socket
) av
, b
= (Actual_Socket
) bv
;
108 unsigned long as
= (unsigned long) a
->s
, bs
= (unsigned long) b
->s
;
116 static int cmpforsearch(void *av
, void *bv
)
118 Actual_Socket b
= (Actual_Socket
) bv
;
119 unsigned long as
= (unsigned long) av
, bs
= (unsigned long) b
->s
;
129 sktree
= newtree234(cmpfortree
);
132 char *winsock_error_string(int error
)
136 return "Network error: Permission denied";
138 return "Network error: Address already in use";
139 case WSAEADDRNOTAVAIL
:
140 return "Network error: Cannot assign requested address";
141 case WSAEAFNOSUPPORT
:
143 "Network error: Address family not supported by protocol family";
145 return "Network error: Operation already in progress";
146 case WSAECONNABORTED
:
147 return "Network error: Software caused connection abort";
148 case WSAECONNREFUSED
:
149 return "Network error: Connection refused";
151 return "Network error: Connection reset by peer";
152 case WSAEDESTADDRREQ
:
153 return "Network error: Destination address required";
155 return "Network error: Bad address";
157 return "Network error: Host is down";
158 case WSAEHOSTUNREACH
:
159 return "Network error: No route to host";
161 return "Network error: Operation now in progress";
163 return "Network error: Interrupted function call";
165 return "Network error: Invalid argument";
167 return "Network error: Socket is already connected";
169 return "Network error: Too many open files";
171 return "Network error: Message too long";
173 return "Network error: Network is down";
175 return "Network error: Network dropped connection on reset";
177 return "Network error: Network is unreachable";
179 return "Network error: No buffer space available";
181 return "Network error: Bad protocol option";
183 return "Network error: Socket is not connected";
185 return "Network error: Socket operation on non-socket";
187 return "Network error: Operation not supported";
188 case WSAEPFNOSUPPORT
:
189 return "Network error: Protocol family not supported";
191 return "Network error: Too many processes";
192 case WSAEPROTONOSUPPORT
:
193 return "Network error: Protocol not supported";
195 return "Network error: Protocol wrong type for socket";
197 return "Network error: Cannot send after socket shutdown";
198 case WSAESOCKTNOSUPPORT
:
199 return "Network error: Socket type not supported";
201 return "Network error: Connection timed out";
203 return "Network error: Resource temporarily unavailable";
205 return "Network error: Graceful shutdown in progress";
207 return "Unknown network error";
211 SockAddr
sk_namelookup(char *host
, char **canonicalname
)
213 SockAddr ret
= smalloc(sizeof(struct SockAddr_tag
));
215 struct hostent
*h
= NULL
;
217 /* Clear the structure and default to IPv4. */
218 memset(ret
, 0, sizeof(struct SockAddr_tag
));
219 ret
->family
= 0; /* We set this one when we have resolved the host. */
220 *canonicalname
= ret
->realhost
; /* This makes sure we always have a hostname to return. */
222 if ((a
= inet_addr(host
)) == (unsigned long) INADDR_NONE
) {
225 /* Try to get the getaddrinfo() function from wship6.dll */
226 /* This way one doesn't need to have IPv6 dll's to use PuTTY and
227 * it will fallback to IPv4. */
228 typedef int (CALLBACK
* FGETADDRINFO
) (const char *nodename
,
229 const char *servname
,
230 const struct addrinfo
*
232 struct addrinfo
** res
);
233 FGETADDRINFO fGetAddrInfo
= NULL
;
235 HINSTANCE dllWSHIP6
= LoadLibrary("wship6.dll");
237 fGetAddrInfo
= (FGETADDRINFO
) GetProcAddress(dllWSHIP6
,
241 * Use fGetAddrInfo when it's available (which usually also
242 * means IPv6 is installed...)
245 /*debug(("Resolving \"%s\" with getaddrinfo() (IPv4+IPv6 capable)...\n", host)); */
246 if (fGetAddrInfo(host
, NULL
, NULL
, &ret
->ai
) == 0)
247 ret
->family
= ret
->ai
->ai_family
;
252 * Otherwise use the IPv4-only gethostbyname...
253 * (NOTE: we don't use gethostbyname as a
256 if (ret
->family
== 0) {
257 /*debug(("Resolving \"%s\" with gethostbyname() (IPv4 only)...\n", host)); */
258 if (h
= gethostbyname(host
))
259 ret
->family
= AF_INET
;
262 /*debug(("Done resolving...(family is %d) AF_INET = %d, AF_INET6 = %d\n", ret->family, AF_INET, AF_INET6)); */
264 if (ret
->family
== 0) {
265 DWORD err
= WSAGetLastError();
266 ret
->error
= (err
== WSAENETDOWN ?
"Network is down" :
268 WSAHOST_NOT_FOUND ?
"Host does not exist" : err
269 == WSATRY_AGAIN ?
"Host not found" :
271 fGetAddrInfo ?
"getaddrinfo: unknown error" :
273 "gethostbyname: unknown error");
277 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER
|
278 FORMAT_MESSAGE_FROM_SYSTEM
|
279 FORMAT_MESSAGE_IGNORE_INSERTS
, NULL
, err
,
280 MAKELANGID(LANG_NEUTRAL
, SUBLANG_DEFAULT
),
281 (LPTSTR
) & lpMsgBuf
, 0, NULL
);
282 /*debug(("Error %ld: %s (h=%lx)\n", err, lpMsgBuf, h)); */
283 /* Free the buffer. */
291 /* If we got an address info use that... */
293 typedef int (CALLBACK
* FGETNAMEINFO
)
294 (const struct sockaddr FAR
* sa
, socklen_t salen
,
295 char FAR
* host
, size_t hostlen
, char FAR
* serv
,
296 size_t servlen
, int flags
);
297 FGETNAMEINFO fGetNameInfo
= NULL
;
299 /* Are we in IPv4 fallback mode? */
300 /* We put the IPv4 address into the a variable so we can further-on use the IPv4 code... */
301 if (ret
->family
== AF_INET
)
303 (char *) &((SOCKADDR_IN
*) ret
->ai
->
304 ai_addr
)->sin_addr
, sizeof(a
));
306 /* Now let's find that canonicalname... */
309 (FGETNAMEINFO
) GetProcAddress(dllWSHIP6
,
312 ((struct sockaddr
*) ret
->ai
->ai_addr
,
314 AF_INET ?
sizeof(SOCKADDR_IN
) :
315 sizeof(SOCKADDR_IN6
), ret
->realhost
,
316 sizeof(ret
->realhost
), NULL
, 0, 0) != 0) {
317 strncpy(ret
->realhost
, host
,
318 sizeof(ret
->realhost
));
322 /* We used the IPv4-only gethostbyname()... */
326 memcpy(&a
, h
->h_addr
, sizeof(a
));
327 /* This way we are always sure the h->h_name is valid :) */
328 strncpy(ret
->realhost
, h
->h_name
, sizeof(ret
->realhost
));
332 FreeLibrary(dllWSHIP6
);
336 * This must be a numeric IPv4 address because it caused a
337 * success return from inet_addr.
339 ret
->family
= AF_INET
;
340 *canonicalname
= host
;
342 ret
->address
= ntohl(a
);
346 void sk_addr_free(SockAddr addr
)
351 static Plug
sk_tcp_plug(Socket sock
, Plug p
)
353 Actual_Socket s
= (Actual_Socket
) sock
;
360 static void sk_tcp_flush(Socket s
)
363 * We send data to the socket as soon as we can anyway,
364 * so we don't need to do anything here. :-)
368 void sk_tcp_close(Socket s
);
369 void sk_tcp_write(Socket s
, char *data
, int len
);
370 void sk_tcp_write_oob(Socket s
, char *data
, int len
);
371 char *sk_tcp_socket_error(Socket s
);
373 Socket
sk_new(SockAddr addr
, int port
, int privport
, int oobinline
,
376 static struct socket_function_table fn_table
= {
393 extern char *do_select(SOCKET skt
, int startup
);
397 * Create Socket structure.
399 ret
= smalloc(sizeof(struct Socket_tag
));
403 ret
->head
= ret
->tail
= NULL
;
404 ret
->writable
= 1; /* to start with */
405 ret
->sending_oob
= 0;
410 s
= socket(addr
->family
, SOCK_STREAM
, 0);
413 if (s
== INVALID_SOCKET
) {
414 err
= WSAGetLastError();
415 ret
->error
= winsock_error_string(err
);
419 ret
->oobinline
= oobinline
;
422 setsockopt(s
, SOL_SOCKET
, SO_OOBINLINE
, (void *) &b
, sizeof(b
));
426 * Bind to local address.
429 localport
= 1023; /* count from 1023 downwards */
431 localport
= 0; /* just use port 0 (ie winsock picks) */
433 /* Loop round trying to bind */
438 if (addr
->family
== AF_INET6
) {
439 memset(&a6
, 0, sizeof(a6
));
440 a6
.sin6_family
= AF_INET6
;
441 /*a6.sin6_addr = in6addr_any; *//* == 0 */
442 a6
.sin6_port
= htons(localport
);
446 a
.sin_family
= AF_INET
;
447 a
.sin_addr
.s_addr
= htonl(INADDR_ANY
);
448 a
.sin_port
= htons(localport
);
451 retcode
= bind(s
, (addr
->family
== AF_INET6 ?
452 (struct sockaddr
*) &a6
:
453 (struct sockaddr
*) &a
),
455 AF_INET6 ?
sizeof(a6
) : sizeof(a
)));
457 retcode
= bind(s
, (struct sockaddr
*) &a
, sizeof(a
));
459 if (retcode
!= SOCKET_ERROR
) {
463 err
= WSAGetLastError();
464 if (err
!= WSAEADDRINUSE
) /* failed, for a bad reason */
469 break; /* we're only looping once */
472 break; /* we might have got to the end */
476 ret
->error
= winsock_error_string(err
);
481 * Connect to remote address.
484 if (addr
->family
== AF_INET6
) {
485 memset(&a
, 0, sizeof(a
));
486 a6
.sin6_family
= AF_INET6
;
487 a6
.sin6_port
= htons((short) port
);
489 ((struct sockaddr_in6
*) addr
->ai
->ai_addr
)->sin6_addr
;
493 a
.sin_family
= AF_INET
;
494 a
.sin_addr
.s_addr
= htonl(addr
->address
);
495 a
.sin_port
= htons((short) port
);
499 connect(s
, ((addr
->family
== AF_INET6
) ?
500 (struct sockaddr
*) &a6
: (struct sockaddr
*) &a
),
501 (addr
->family
== AF_INET6
) ?
sizeof(a6
) : sizeof(a
))
503 connect(s
, (struct sockaddr
*) &a
, sizeof(a
))
506 err
= WSAGetLastError();
507 ret
->error
= winsock_error_string(err
);
511 /* Set up a select mechanism. This could be an AsyncSelect on a
512 * window, or an EventSelect on an event object. */
513 errstr
= do_select(s
, 1);
524 static void sk_tcp_close(Socket sock
)
526 extern char *do_select(SOCKET skt
, int startup
);
527 Actual_Socket s
= (Actual_Socket
) sock
;
536 * The function which tries to send on a socket once it's deemed
539 void try_send(Actual_Socket s
)
546 if (s
->sending_oob
) {
547 urgentflag
= MSG_OOB
;
548 len
= s
->sending_oob
;
551 len
= s
->head
->buflen
- s
->head
->bufpos
;
555 send(s
->s
, s
->head
->buf
+ s
->head
->bufpos
, len
, urgentflag
);
556 noise_ultralight(nsent
);
558 err
= (nsent
< 0 ?
WSAGetLastError() : 0);
559 if ((err
== 0 && nsent
< 0) || err
== WSAEWOULDBLOCK
) {
561 * Perfectly normal: we've sent all we can for the moment.
563 * (Apparently some WinSocks can return <0 but
564 * leave no error indication - WSAGetLastError() is
565 * called but returns zero - so we check that case
566 * and treat it just like WSAEWOULDBLOCK.)
570 } else if (nsent
== 0 ||
571 err
== WSAECONNABORTED
|| err
== WSAECONNRESET
) {
573 * FIXME. This will have to be done better when we
574 * start managing multiple sockets (e.g. SSH port
575 * forwarding), because if we get CONNRESET while
576 * trying to write a particular forwarded socket
577 * then it isn't necessarily the end of the world.
578 * Ideally I'd like to pass the error code back to
579 * somewhere the next select_result() will see it,
580 * but that might be hard. Perhaps I should pass it
581 * back to be queued in the Windows front end bit.
583 fatalbox(winsock_error_string(err
));
585 fatalbox(winsock_error_string(err
));
588 s
->head
->bufpos
+= nsent
;
590 s
->sending_oob
-= nsent
;
591 if (s
->head
->bufpos
>= s
->head
->buflen
) {
592 struct buffer
*tmp
= s
->head
;
602 static void sk_tcp_write(Socket sock
, char *buf
, int len
)
604 Actual_Socket s
= (Actual_Socket
) sock
;
607 * Add the data to the buffer list on the socket.
609 if (s
->tail
&& s
->tail
->buflen
< BUFFER_GRANULE
) {
610 int copylen
= min(len
, BUFFER_GRANULE
- s
->tail
->buflen
);
611 memcpy(s
->tail
->buf
+ s
->tail
->buflen
, buf
, copylen
);
614 s
->tail
->buflen
+= copylen
;
617 int grainlen
= min(len
, BUFFER_GRANULE
);
618 struct buffer
*newbuf
;
619 newbuf
= smalloc(sizeof(struct buffer
));
621 newbuf
->buflen
= grainlen
;
622 memcpy(newbuf
->buf
, buf
, grainlen
);
626 s
->tail
->next
= newbuf
;
628 s
->head
= s
->tail
= newbuf
;
634 * Now try sending from the start of the buffer list.
640 static void sk_tcp_write_oob(Socket sock
, char *buf
, int len
)
642 Actual_Socket s
= (Actual_Socket
) sock
;
645 * Replace the buffer list on the socket with the data.
648 s
->head
= smalloc(sizeof(struct buffer
));
650 struct buffer
*walk
= s
->head
->next
;
652 struct buffer
*tmp
= walk
;
657 s
->head
->next
= NULL
;
659 s
->head
->buflen
= len
;
660 memcpy(s
->head
->buf
, buf
, len
);
663 * Set the Urgent marker.
665 s
->sending_oob
= len
;
668 * Now try sending from the start of the buffer list.
674 int select_result(WPARAM wParam
, LPARAM lParam
)
678 char buf
[20480]; /* nice big buffer for plenty of speed */
682 /* wParam is the socket itself */
683 s
= find234(sktree
, (void *) wParam
, cmpforsearch
);
685 return 1; /* boggle */
687 if ((err
= WSAGETSELECTERROR(lParam
)) != 0) {
689 * An error has occurred on this socket. Pass it to the
692 return plug_closing(s
->plug
, winsock_error_string(err
), err
, 0);
695 noise_ultralight(lParam
);
697 switch (WSAGETSELECTEVENT(lParam
)) {
700 * We have received data on the socket. For an oobinline
701 * socket, this might be data _before_ an urgent pointer,
702 * in which case we send it to the back end with type==1
703 * (data prior to urgent).
707 ioctlsocket(s
->s
, SIOCATMARK
, &atmark
);
709 * Avoid checking the return value from ioctlsocket(),
710 * on the grounds that some WinSock wrappers don't
711 * support it. If it does nothing, we get atmark==1,
712 * which is equivalent to `no OOB pending', so the
713 * effect will be to non-OOB-ify any OOB data.
718 ret
= recv(s
->s
, buf
, sizeof(buf
), 0);
719 noise_ultralight(ret
);
721 err
= WSAGetLastError();
722 if (err
== WSAEWOULDBLOCK
) {
727 return plug_closing(s
->plug
, winsock_error_string(err
), err
,
729 } else if (0 == ret
) {
730 return plug_closing(s
->plug
, NULL
, 0, 0);
732 return plug_receive(s
->plug
, atmark ?
0 : 1, buf
, ret
);
737 * This will only happen on a non-oobinline socket. It
738 * indicates that we can immediately perform an OOB read
739 * and get back OOB data, which we will send to the back
740 * end with type==2 (urgent data).
742 ret
= recv(s
->s
, buf
, sizeof(buf
), MSG_OOB
);
743 noise_ultralight(ret
);
745 fatalbox(ret
== 0 ?
"Internal networking trouble" :
746 winsock_error_string(WSAGetLastError()));
748 return plug_receive(s
->plug
, 2, buf
, ret
);
756 /* Signal a close on the socket. First read any outstanding data. */
759 ret
= recv(s
->s
, buf
, sizeof(buf
), 0);
761 err
= WSAGetLastError();
762 if (err
== WSAEWOULDBLOCK
)
764 return plug_closing(s
->plug
, winsock_error_string(err
),
768 open
&= plug_receive(s
->plug
, 0, buf
, ret
);
770 open
&= plug_closing(s
->plug
, NULL
, 0, 0);
780 * Each socket abstraction contains a `void *' private field in
781 * which the client can keep state.
783 void sk_set_private_ptr(Socket sock
, void *ptr
)
785 Actual_Socket s
= (Actual_Socket
) sock
;
786 s
->private_ptr
= ptr
;
789 void *sk_get_private_ptr(Socket sock
)
791 Actual_Socket s
= (Actual_Socket
) sock
;
792 return s
->private_ptr
;
796 * Special error values are returned from sk_namelookup and sk_new
797 * if there's a problem. These functions extract an error message,
798 * or return NULL if there's no problem.
800 char *sk_addr_error(SockAddr addr
)
804 static char *sk_tcp_socket_error(Socket sock
)
806 Actual_Socket s
= (Actual_Socket
) sock
;
811 * For Plink: enumerate all sockets currently active.
813 SOCKET
first_socket(int *state
)
817 s
= index234(sktree
, (*state
)++);
818 return s ? s
->s
: INVALID_SOCKET
;
821 SOCKET
next_socket(int *state
)
823 Actual_Socket s
= index234(sktree
, (*state
)++);
824 return s ? s
->s
: INVALID_SOCKET
;