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. */
95 char buf
[BUFFER_GRANULE
];
98 static tree234
*sktree
;
100 static int cmpfortree(void *av
, void *bv
)
102 Actual_Socket a
= (Actual_Socket
) av
, b
= (Actual_Socket
) bv
;
103 unsigned long as
= (unsigned long) a
->s
, bs
= (unsigned long) b
->s
;
111 static int cmpforsearch(void *av
, void *bv
)
113 Actual_Socket b
= (Actual_Socket
) bv
;
114 unsigned long as
= (unsigned long) av
, bs
= (unsigned long) b
->s
;
124 sktree
= newtree234(cmpfortree
);
127 char *winsock_error_string(int error
)
131 return "Network error: Permission denied";
133 return "Network error: Address already in use";
134 case WSAEADDRNOTAVAIL
:
135 return "Network error: Cannot assign requested address";
136 case WSAEAFNOSUPPORT
:
138 "Network error: Address family not supported by protocol family";
140 return "Network error: Operation already in progress";
141 case WSAECONNABORTED
:
142 return "Network error: Software caused connection abort";
143 case WSAECONNREFUSED
:
144 return "Network error: Connection refused";
146 return "Network error: Connection reset by peer";
147 case WSAEDESTADDRREQ
:
148 return "Network error: Destination address required";
150 return "Network error: Bad address";
152 return "Network error: Host is down";
153 case WSAEHOSTUNREACH
:
154 return "Network error: No route to host";
156 return "Network error: Operation now in progress";
158 return "Network error: Interrupted function call";
160 return "Network error: Invalid argument";
162 return "Network error: Socket is already connected";
164 return "Network error: Too many open files";
166 return "Network error: Message too long";
168 return "Network error: Network is down";
170 return "Network error: Network dropped connection on reset";
172 return "Network error: Network is unreachable";
174 return "Network error: No buffer space available";
176 return "Network error: Bad protocol option";
178 return "Network error: Socket is not connected";
180 return "Network error: Socket operation on non-socket";
182 return "Network error: Operation not supported";
183 case WSAEPFNOSUPPORT
:
184 return "Network error: Protocol family not supported";
186 return "Network error: Too many processes";
187 case WSAEPROTONOSUPPORT
:
188 return "Network error: Protocol not supported";
190 return "Network error: Protocol wrong type for socket";
192 return "Network error: Cannot send after socket shutdown";
193 case WSAESOCKTNOSUPPORT
:
194 return "Network error: Socket type not supported";
196 return "Network error: Connection timed out";
198 return "Network error: Resource temporarily unavailable";
200 return "Network error: Graceful shutdown in progress";
202 return "Unknown network error";
206 SockAddr
sk_namelookup(char *host
, char **canonicalname
)
208 SockAddr ret
= smalloc(sizeof(struct SockAddr_tag
));
210 struct hostent
*h
= NULL
;
213 /* Clear the structure and default to IPv4. */
214 memset(ret
, 0, sizeof(struct SockAddr_tag
));
215 ret
->family
= 0; /* We set this one when we have resolved the host. */
218 if ((a
= inet_addr(host
)) == (unsigned long) INADDR_NONE
) {
221 /* Try to get the getaddrinfo() function from wship6.dll */
222 /* This way one doesn't need to have IPv6 dll's to use PuTTY and
223 * it will fallback to IPv4. */
224 typedef int (CALLBACK
* FGETADDRINFO
) (const char *nodename
,
225 const char *servname
,
226 const struct addrinfo
*
228 struct addrinfo
** res
);
229 FGETADDRINFO fGetAddrInfo
= NULL
;
231 HINSTANCE dllWSHIP6
= LoadLibrary("wship6.dll");
233 fGetAddrInfo
= (FGETADDRINFO
) GetProcAddress(dllWSHIP6
,
237 * Use fGetAddrInfo when it's available (which usually also
238 * means IPv6 is installed...)
241 /*debug(("Resolving \"%s\" with getaddrinfo() (IPv4+IPv6 capable)...\n", host)); */
242 if (fGetAddrInfo(host
, NULL
, NULL
, &ret
->ai
) == 0)
243 ret
->family
= ret
->ai
->ai_family
;
248 * Otherwise use the IPv4-only gethostbyname...
249 * (NOTE: we don't use gethostbyname as a
252 if (ret
->family
== 0) {
253 /*debug(("Resolving \"%s\" with gethostbyname() (IPv4 only)...\n", host)); */
254 if ( (h
= gethostbyname(host
)) )
255 ret
->family
= AF_INET
;
258 /*debug(("Done resolving...(family is %d) AF_INET = %d, AF_INET6 = %d\n", ret->family, AF_INET, AF_INET6)); */
260 if (ret
->family
== 0) {
261 DWORD err
= WSAGetLastError();
262 ret
->error
= (err
== WSAENETDOWN ?
"Network is down" :
264 WSAHOST_NOT_FOUND ?
"Host does not exist" : err
265 == WSATRY_AGAIN ?
"Host not found" :
267 fGetAddrInfo ?
"getaddrinfo: unknown error" :
269 "gethostbyname: unknown error");
273 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER
|
274 FORMAT_MESSAGE_FROM_SYSTEM
|
275 FORMAT_MESSAGE_IGNORE_INSERTS
, NULL
, err
,
276 MAKELANGID(LANG_NEUTRAL
, SUBLANG_DEFAULT
),
277 (LPTSTR
) & lpMsgBuf
, 0, NULL
);
278 /*debug(("Error %ld: %s (h=%lx)\n", err, lpMsgBuf, h)); */
279 /* Free the buffer. */
287 /* If we got an address info use that... */
289 typedef int (CALLBACK
* FGETNAMEINFO
)
290 (const struct sockaddr FAR
* sa
, socklen_t salen
,
291 char FAR
* host
, size_t hostlen
, char FAR
* serv
,
292 size_t servlen
, int flags
);
293 FGETNAMEINFO fGetNameInfo
= NULL
;
295 /* Are we in IPv4 fallback mode? */
296 /* We put the IPv4 address into the a variable so we can further-on use the IPv4 code... */
297 if (ret
->family
== AF_INET
)
299 (char *) &((SOCKADDR_IN
*) ret
->ai
->
300 ai_addr
)->sin_addr
, sizeof(a
));
302 /* Now let's find that canonicalname... */
305 (FGETNAMEINFO
) GetProcAddress(dllWSHIP6
,
308 ((struct sockaddr
*) ret
->ai
->ai_addr
,
310 AF_INET ?
sizeof(SOCKADDR_IN
) :
311 sizeof(SOCKADDR_IN6
), realhost
,
312 sizeof(realhost
), NULL
, 0, 0) != 0) {
313 strncpy(realhost
, host
, sizeof(realhost
));
317 /* We used the IPv4-only gethostbyname()... */
321 memcpy(&a
, h
->h_addr
, sizeof(a
));
322 /* This way we are always sure the h->h_name is valid :) */
323 strncpy(realhost
, h
->h_name
, sizeof(realhost
));
327 FreeLibrary(dllWSHIP6
);
331 * This must be a numeric IPv4 address because it caused a
332 * success return from inet_addr.
334 ret
->family
= AF_INET
;
335 strncpy(realhost
, host
, sizeof(realhost
));
337 ret
->address
= ntohl(a
);
338 realhost
[lenof(realhost
)-1] = '\0';
339 *canonicalname
= smalloc(1+strlen(realhost
));
340 strcpy(*canonicalname
, realhost
);
344 void sk_addr_free(SockAddr addr
)
349 static Plug
sk_tcp_plug(Socket sock
, Plug p
)
351 Actual_Socket s
= (Actual_Socket
) sock
;
358 static void sk_tcp_flush(Socket s
)
361 * We send data to the socket as soon as we can anyway,
362 * so we don't need to do anything here. :-)
366 static void sk_tcp_close(Socket s
);
367 static void sk_tcp_write(Socket s
, char *data
, int len
);
368 static void sk_tcp_write_oob(Socket s
, char *data
, int len
);
369 static char *sk_tcp_socket_error(Socket s
);
371 Socket
sk_new(SockAddr addr
, int port
, int privport
, int oobinline
,
374 static struct socket_function_table fn_table
= {
391 extern char *do_select(SOCKET skt
, int startup
);
395 * Create Socket structure.
397 ret
= smalloc(sizeof(struct Socket_tag
));
401 ret
->head
= ret
->tail
= NULL
;
402 ret
->writable
= 1; /* to start with */
403 ret
->sending_oob
= 0;
408 s
= socket(addr
->family
, SOCK_STREAM
, 0);
411 if (s
== INVALID_SOCKET
) {
412 err
= WSAGetLastError();
413 ret
->error
= winsock_error_string(err
);
417 ret
->oobinline
= oobinline
;
420 setsockopt(s
, SOL_SOCKET
, SO_OOBINLINE
, (void *) &b
, sizeof(b
));
424 * Bind to local address.
427 localport
= 1023; /* count from 1023 downwards */
429 localport
= 0; /* just use port 0 (ie winsock picks) */
431 /* Loop round trying to bind */
436 if (addr
->family
== AF_INET6
) {
437 memset(&a6
, 0, sizeof(a6
));
438 a6
.sin6_family
= AF_INET6
;
439 /*a6.sin6_addr = in6addr_any; *//* == 0 */
440 a6
.sin6_port
= htons(localport
);
444 a
.sin_family
= AF_INET
;
445 a
.sin_addr
.s_addr
= htonl(INADDR_ANY
);
446 a
.sin_port
= htons(localport
);
449 retcode
= bind(s
, (addr
->family
== AF_INET6 ?
450 (struct sockaddr
*) &a6
:
451 (struct sockaddr
*) &a
),
453 AF_INET6 ?
sizeof(a6
) : sizeof(a
)));
455 retcode
= bind(s
, (struct sockaddr
*) &a
, sizeof(a
));
457 if (retcode
!= SOCKET_ERROR
) {
461 err
= WSAGetLastError();
462 if (err
!= WSAEADDRINUSE
) /* failed, for a bad reason */
467 break; /* we're only looping once */
470 break; /* we might have got to the end */
474 ret
->error
= winsock_error_string(err
);
479 * Connect to remote address.
482 if (addr
->family
== AF_INET6
) {
483 memset(&a
, 0, sizeof(a
));
484 a6
.sin6_family
= AF_INET6
;
485 a6
.sin6_port
= htons((short) port
);
487 ((struct sockaddr_in6
*) addr
->ai
->ai_addr
)->sin6_addr
;
491 a
.sin_family
= AF_INET
;
492 a
.sin_addr
.s_addr
= htonl(addr
->address
);
493 a
.sin_port
= htons((short) port
);
497 connect(s
, ((addr
->family
== AF_INET6
) ?
498 (struct sockaddr
*) &a6
: (struct sockaddr
*) &a
),
499 (addr
->family
== AF_INET6
) ?
sizeof(a6
) : sizeof(a
))
501 connect(s
, (struct sockaddr
*) &a
, sizeof(a
))
504 err
= WSAGetLastError();
505 ret
->error
= winsock_error_string(err
);
509 /* Set up a select mechanism. This could be an AsyncSelect on a
510 * window, or an EventSelect on an event object. */
511 errstr
= do_select(s
, 1);
522 static void sk_tcp_close(Socket sock
)
524 extern char *do_select(SOCKET skt
, int startup
);
525 Actual_Socket s
= (Actual_Socket
) sock
;
534 * The function which tries to send on a socket once it's deemed
537 void try_send(Actual_Socket s
)
544 if (s
->sending_oob
) {
545 urgentflag
= MSG_OOB
;
546 len
= s
->sending_oob
;
549 len
= s
->head
->buflen
- s
->head
->bufpos
;
553 send(s
->s
, s
->head
->buf
+ s
->head
->bufpos
, len
, urgentflag
);
554 noise_ultralight(nsent
);
556 err
= (nsent
< 0 ?
WSAGetLastError() : 0);
557 if ((err
== 0 && nsent
< 0) || err
== WSAEWOULDBLOCK
) {
559 * Perfectly normal: we've sent all we can for the moment.
561 * (Apparently some WinSocks can return <0 but
562 * leave no error indication - WSAGetLastError() is
563 * called but returns zero - so we check that case
564 * and treat it just like WSAEWOULDBLOCK.)
568 } else if (nsent
== 0 ||
569 err
== WSAECONNABORTED
|| err
== WSAECONNRESET
) {
571 * FIXME. This will have to be done better when we
572 * start managing multiple sockets (e.g. SSH port
573 * forwarding), because if we get CONNRESET while
574 * trying to write a particular forwarded socket
575 * then it isn't necessarily the end of the world.
576 * Ideally I'd like to pass the error code back to
577 * somewhere the next select_result() will see it,
578 * but that might be hard. Perhaps I should pass it
579 * back to be queued in the Windows front end bit.
581 fatalbox(winsock_error_string(err
));
583 fatalbox(winsock_error_string(err
));
586 s
->head
->bufpos
+= nsent
;
588 s
->sending_oob
-= nsent
;
589 if (s
->head
->bufpos
>= s
->head
->buflen
) {
590 struct buffer
*tmp
= s
->head
;
600 static void sk_tcp_write(Socket sock
, char *buf
, int len
)
602 Actual_Socket s
= (Actual_Socket
) sock
;
605 * Add the data to the buffer list on the socket.
607 if (s
->tail
&& s
->tail
->buflen
< BUFFER_GRANULE
) {
608 int copylen
= min(len
, BUFFER_GRANULE
- s
->tail
->buflen
);
609 memcpy(s
->tail
->buf
+ s
->tail
->buflen
, buf
, copylen
);
612 s
->tail
->buflen
+= copylen
;
615 int grainlen
= min(len
, BUFFER_GRANULE
);
616 struct buffer
*newbuf
;
617 newbuf
= smalloc(sizeof(struct buffer
));
619 newbuf
->buflen
= grainlen
;
620 memcpy(newbuf
->buf
, buf
, grainlen
);
624 s
->tail
->next
= newbuf
;
626 s
->head
= s
->tail
= newbuf
;
632 * Now try sending from the start of the buffer list.
638 static void sk_tcp_write_oob(Socket sock
, char *buf
, int len
)
640 Actual_Socket s
= (Actual_Socket
) sock
;
643 * Replace the buffer list on the socket with the data.
646 s
->head
= smalloc(sizeof(struct buffer
));
648 struct buffer
*walk
= s
->head
->next
;
650 struct buffer
*tmp
= walk
;
655 s
->head
->next
= NULL
;
657 s
->head
->buflen
= len
;
658 memcpy(s
->head
->buf
, buf
, len
);
661 * Set the Urgent marker.
663 s
->sending_oob
= len
;
666 * Now try sending from the start of the buffer list.
672 int select_result(WPARAM wParam
, LPARAM lParam
)
676 char buf
[20480]; /* nice big buffer for plenty of speed */
680 /* wParam is the socket itself */
681 s
= find234(sktree
, (void *) wParam
, cmpforsearch
);
683 return 1; /* boggle */
685 if ((err
= WSAGETSELECTERROR(lParam
)) != 0) {
687 * An error has occurred on this socket. Pass it to the
690 return plug_closing(s
->plug
, winsock_error_string(err
), err
, 0);
693 noise_ultralight(lParam
);
695 switch (WSAGETSELECTEVENT(lParam
)) {
698 * We have received data on the socket. For an oobinline
699 * socket, this might be data _before_ an urgent pointer,
700 * in which case we send it to the back end with type==1
701 * (data prior to urgent).
705 ioctlsocket(s
->s
, SIOCATMARK
, &atmark
);
707 * Avoid checking the return value from ioctlsocket(),
708 * on the grounds that some WinSock wrappers don't
709 * support it. If it does nothing, we get atmark==1,
710 * which is equivalent to `no OOB pending', so the
711 * effect will be to non-OOB-ify any OOB data.
716 ret
= recv(s
->s
, buf
, sizeof(buf
), 0);
717 noise_ultralight(ret
);
719 err
= WSAGetLastError();
720 if (err
== WSAEWOULDBLOCK
) {
725 return plug_closing(s
->plug
, winsock_error_string(err
), err
,
727 } else if (0 == ret
) {
728 return plug_closing(s
->plug
, NULL
, 0, 0);
730 return plug_receive(s
->plug
, atmark ?
0 : 1, buf
, ret
);
735 * This will only happen on a non-oobinline socket. It
736 * indicates that we can immediately perform an OOB read
737 * and get back OOB data, which we will send to the back
738 * end with type==2 (urgent data).
740 ret
= recv(s
->s
, buf
, sizeof(buf
), MSG_OOB
);
741 noise_ultralight(ret
);
743 fatalbox(ret
== 0 ?
"Internal networking trouble" :
744 winsock_error_string(WSAGetLastError()));
746 return plug_receive(s
->plug
, 2, buf
, ret
);
754 /* Signal a close on the socket. First read any outstanding data. */
757 ret
= recv(s
->s
, buf
, sizeof(buf
), 0);
759 err
= WSAGetLastError();
760 if (err
== WSAEWOULDBLOCK
)
762 return plug_closing(s
->plug
, winsock_error_string(err
),
766 open
&= plug_receive(s
->plug
, 0, buf
, ret
);
768 open
&= plug_closing(s
->plug
, NULL
, 0, 0);
778 * Each socket abstraction contains a `void *' private field in
779 * which the client can keep state.
781 void sk_set_private_ptr(Socket sock
, void *ptr
)
783 Actual_Socket s
= (Actual_Socket
) sock
;
784 s
->private_ptr
= ptr
;
787 void *sk_get_private_ptr(Socket sock
)
789 Actual_Socket s
= (Actual_Socket
) sock
;
790 return s
->private_ptr
;
794 * Special error values are returned from sk_namelookup and sk_new
795 * if there's a problem. These functions extract an error message,
796 * or return NULL if there's no problem.
798 char *sk_addr_error(SockAddr addr
)
802 static char *sk_tcp_socket_error(Socket sock
)
804 Actual_Socket s
= (Actual_Socket
) sock
;
809 * For Plink: enumerate all sockets currently active.
811 SOCKET
first_socket(int *state
)
815 s
= index234(sktree
, (*state
)++);
816 return s ? s
->s
: INVALID_SOCKET
;
819 SOCKET
next_socket(int *state
)
821 Actual_Socket s
= index234(sktree
, (*state
)++);
822 return s ? s
->s
: INVALID_SOCKET
;