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.
56 #define BUFFER_GRANULE 512
61 sk_receiver_t receiver
;
63 struct buffer
*head
, *tail
;
65 int in_oob
, sending_oob
;
70 /* address family this belongs to, AF_INET for IPv4, AF_INET6 for IPv6. */
72 unsigned long address
; /* Address IPv4 style. */
74 struct addrinfo
*ai
; /* Address IPv6 style. */
77 * We need to have this lengthy enough to hold *any* hostname
78 * (including IPv6 reverse...)
86 char buf
[BUFFER_GRANULE
];
89 static tree234
*sktree
;
91 static int cmpfortree(void *av
, void *bv
) {
92 Socket a
= (Socket
)av
, b
= (Socket
)bv
;
93 unsigned long as
= (unsigned long)a
->s
, bs
= (unsigned long)b
->s
;
94 if (as
< bs
) return -1;
95 if (as
> bs
) return +1;
99 static int cmpforsearch(void *av
, void *bv
) {
100 Socket b
= (Socket
)bv
;
101 unsigned long as
= (unsigned long)av
, bs
= (unsigned long)b
->s
;
102 if (as
< bs
) return -1;
103 if (as
> bs
) return +1;
108 sktree
= newtree234(cmpfortree
);
111 char *winsock_error_string(int error
) {
113 case WSAEACCES
: return "Network error: Permission denied";
114 case WSAEADDRINUSE
: return "Network error: Address already in use";
115 case WSAEADDRNOTAVAIL
: return "Network error: Cannot assign requested address";
116 case WSAEAFNOSUPPORT
: return "Network error: Address family not supported by protocol family";
117 case WSAEALREADY
: return "Network error: Operation already in progress";
118 case WSAECONNABORTED
: return "Network error: Software caused connection abort";
119 case WSAECONNREFUSED
: return "Network error: Connection refused";
120 case WSAECONNRESET
: return "Network error: Connection reset by peer";
121 case WSAEDESTADDRREQ
: return "Network error: Destination address required";
122 case WSAEFAULT
: return "Network error: Bad address";
123 case WSAEHOSTDOWN
: return "Network error: Host is down";
124 case WSAEHOSTUNREACH
: return "Network error: No route to host";
125 case WSAEINPROGRESS
: return "Network error: Operation now in progress";
126 case WSAEINTR
: return "Network error: Interrupted function call";
127 case WSAEINVAL
: return "Network error: Invalid argument";
128 case WSAEISCONN
: return "Network error: Socket is already connected";
129 case WSAEMFILE
: return "Network error: Too many open files";
130 case WSAEMSGSIZE
: return "Network error: Message too long";
131 case WSAENETDOWN
: return "Network error: Network is down";
132 case WSAENETRESET
: return "Network error: Network dropped connection on reset";
133 case WSAENETUNREACH
: return "Network error: Network is unreachable";
134 case WSAENOBUFS
: return "Network error: No buffer space available";
135 case WSAENOPROTOOPT
: return "Network error: Bad protocol option";
136 case WSAENOTCONN
: return "Network error: Socket is not connected";
137 case WSAENOTSOCK
: return "Network error: Socket operation on non-socket";
138 case WSAEOPNOTSUPP
: return "Network error: Operation not supported";
139 case WSAEPFNOSUPPORT
: return "Network error: Protocol family not supported";
140 case WSAEPROCLIM
: return "Network error: Too many processes";
141 case WSAEPROTONOSUPPORT
: return "Network error: Protocol not supported";
142 case WSAEPROTOTYPE
: return "Network error: Protocol wrong type for socket";
143 case WSAESHUTDOWN
: return "Network error: Cannot send after socket shutdown";
144 case WSAESOCKTNOSUPPORT
: return "Network error: Socket type not supported";
145 case WSAETIMEDOUT
: return "Network error: Connection timed out";
146 case WSAEWOULDBLOCK
: return "Network error: Resource temporarily unavailable";
147 case WSAEDISCON
: return "Network error: Graceful shutdown in progress";
148 default: return "Unknown network error";
152 SockAddr
sk_namelookup(char *host
, char **canonicalname
)
154 SockAddr ret
= smalloc(sizeof(struct SockAddr_tag
));
156 struct hostent
*h
= NULL
;
158 /* Clear the structure and default to IPv4. */
159 memset(ret
, 0, sizeof(struct SockAddr_tag
));
160 ret
->family
= 0; /* We set this one when we have resolved the host. */
161 *canonicalname
= ret
->realhost
; /* This makes sure we always have a hostname to return. */
163 if ( (a
= inet_addr(host
)) == (unsigned long) INADDR_NONE
)
167 /* Try to get the getaddrinfo() function from wship6.dll */
168 /* This way one doesn't need to have IPv6 dll's to use PuTTY and
169 * it will fallback to IPv4. */
170 typedef int (CALLBACK
* FGETADDRINFO
)(const char *nodename
,
171 const char *servname
,
172 const struct addrinfo
*hints
,
173 struct addrinfo
**res
);
174 FGETADDRINFO fGetAddrInfo
= NULL
;
176 HINSTANCE dllWSHIP6
= LoadLibrary("wship6.dll");
178 fGetAddrInfo
= (FGETADDRINFO
)GetProcAddress(dllWSHIP6
,
182 * Use fGetAddrInfo when it's available (which usually also
183 * means IPv6 is installed...)
187 /*debug(("Resolving \"%s\" with getaddrinfo() (IPv4+IPv6 capable)...\n", host)); */
188 if (fGetAddrInfo(host
, NULL
, NULL
, &ret
->ai
) == 0)
189 ret
->family
= ret
->ai
->ai_family
;
194 * Otherwise use the IPv4-only gethostbyname...
195 * (NOTE: we don't use gethostbyname as a
198 if (ret
->family
== 0)
200 /*debug(("Resolving \"%s\" with gethostbyname() (IPv4 only)...\n", host)); */
201 if (h
= gethostbyname(host
)) ret
->family
= AF_INET
;
203 /*debug(("Done resolving...(family is %d) AF_INET = %d, AF_INET6 = %d\n", ret->family, AF_INET, AF_INET6)); */
205 if (ret
->family
== 0)
207 DWORD err
= WSAGetLastError();
208 ret
->error
= (err
== WSAENETDOWN ?
"Network is down" :
209 err
== WSAHOST_NOT_FOUND ?
"Host does not exist" :
210 err
== WSATRY_AGAIN ?
"Host not found" :
212 fGetAddrInfo ?
"getaddrinfo: unknown error" :
214 "gethostbyname: unknown error");
218 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER
| FORMAT_MESSAGE_FROM_SYSTEM
| FORMAT_MESSAGE_IGNORE_INSERTS
, NULL
, err
, MAKELANGID(LANG_NEUTRAL
, SUBLANG_DEFAULT
), (LPTSTR
)&lpMsgBuf
, 0, NULL
);
219 /*debug(("Error %ld: %s (h=%lx)\n", err, lpMsgBuf, h));*/
220 /* Free the buffer. */
230 /* If we got an address info use that... */
233 typedef int (CALLBACK
* FGETNAMEINFO
)
234 (const struct sockaddr FAR
*sa
, socklen_t salen
,
235 char FAR
* host
, size_t hostlen
, char FAR
* serv
,
236 size_t servlen
, int flags
);
237 FGETNAMEINFO fGetNameInfo
= NULL
;
239 /* Are we in IPv4 fallback mode? */
240 /* We put the IPv4 address into the a variable so we can further-on use the IPv4 code... */
241 if (ret
->family
== AF_INET
)
242 memcpy(&a
, (char *)&((SOCKADDR_IN
*)ret
->ai
->ai_addr
)->sin_addr
, sizeof(a
));
244 /* Now let's find that canonicalname... */
245 if ((dllWSHIP6
) && (fGetNameInfo
= (FGETNAMEINFO
)GetProcAddress(dllWSHIP6
, "getnameinfo")))
247 if (fGetNameInfo((struct sockaddr
*)ret
->ai
->ai_addr
,
248 ret
->family
== AF_INET ?
249 sizeof(SOCKADDR_IN
) :
250 sizeof(SOCKADDR_IN6
), ret
->realhost
,
251 sizeof(ret
->realhost
), NULL
,
254 strncpy(ret
->realhost
, host
,
255 sizeof(ret
->realhost
));
259 /* We used the IPv4-only gethostbyname()... */
263 memcpy(&a
, h
->h_addr
, sizeof(a
));
264 /* This way we are always sure the h->h_name is valid :) */
265 strncpy(ret
->realhost
, h
->h_name
, sizeof(ret
->realhost
));
271 FreeLibrary(dllWSHIP6
);
277 * Hack inserted to deal with problems with numeric IPs.
278 * FIXME: how will this work in IPv6?
280 ret
->family
= AF_INET
;
281 *canonicalname
= host
;
283 ret
->address
= ntohl(a
);
287 void sk_addr_free(SockAddr addr
) {
291 Socket
sk_new(SockAddr addr
, int port
, int privport
, sk_receiver_t receiver
) {
300 extern char *do_select(SOCKET skt
, int startup
);
304 * Create Socket structure.
306 ret
= smalloc(sizeof(struct Socket_tag
));
308 ret
->receiver
= receiver
;
309 ret
->head
= ret
->tail
= NULL
;
310 ret
->writable
= 1; /* to start with */
312 ret
->sending_oob
= 0;
317 s
= socket(addr
->family
, SOCK_STREAM
, 0);
320 if (s
== INVALID_SOCKET
) {
321 err
= WSAGetLastError();
322 ret
->error
= winsock_error_string(err
);
327 * Bind to local address.
330 localport
= 1023; /* count from 1023 downwards */
332 localport
= 0; /* just use port 0 (ie winsock picks) */
334 /* Loop round trying to bind */
339 if (addr
->family
== AF_INET6
)
341 memset(&a6
,0,sizeof(a6
));
342 a6
.sin6_family
= AF_INET6
;
343 /*a6.sin6_addr = in6addr_any;*/ /* == 0 */
344 a6
.sin6_port
= htons(localport
);
349 a
.sin_family
= AF_INET
;
350 a
.sin_addr
.s_addr
= htonl(INADDR_ANY
);
351 a
.sin_port
= htons(localport
);
354 retcode
= bind (s
, (addr
->family
== AF_INET6 ?
355 (struct sockaddr
*)&a6
:
356 (struct sockaddr
*)&a
),
357 (addr
->family
== AF_INET6 ?
sizeof(a6
) : sizeof(a
)));
359 retcode
= bind (s
, (struct sockaddr
*)&a
, sizeof(a
));
361 if (retcode
!= SOCKET_ERROR
) {
365 err
= WSAGetLastError();
366 if (err
!= WSAEADDRINUSE
) /* failed, for a bad reason */
371 break; /* we're only looping once */
374 break; /* we might have got to the end */
379 ret
->error
= winsock_error_string(err
);
384 * Connect to remote address.
387 if (addr
->family
== AF_INET6
)
389 memset(&a
,0,sizeof(a
));
390 a6
.sin6_family
= AF_INET6
;
391 a6
.sin6_port
= htons((short)port
);
392 a6
.sin6_addr
= ((struct sockaddr_in6
*)addr
->ai
->ai_addr
)->sin6_addr
;
397 a
.sin_family
= AF_INET
;
398 a
.sin_addr
.s_addr
= htonl(addr
->address
);
399 a
.sin_port
= htons((short)port
);
402 if (connect (s
, (addr
->family
== AF_INET6
) ?
(struct sockaddr
*)&a6
: (struct sockaddr
*)&a
, (addr
->family
== AF_INET6
) ?
sizeof(a6
) : sizeof(a
)) == SOCKET_ERROR
)
404 if (connect (s
, (struct sockaddr
*)&a
, sizeof(a
)) == SOCKET_ERROR
)
407 err
= WSAGetLastError();
408 ret
->error
= winsock_error_string(err
);
412 /* Set up a select mechanism. This could be an AsyncSelect on a
413 * window, or an EventSelect on an event object. */
414 errstr
= do_select(s
, 1);
425 void sk_close(Socket s
) {
426 extern char *do_select(SOCKET skt
, int startup
);
435 * The function which tries to send on a socket once it's deemed
438 void try_send(Socket s
) {
444 if (s
->sending_oob
) {
445 urgentflag
= MSG_OOB
;
446 len
= s
->sending_oob
;
449 len
= s
->head
->buflen
- s
->head
->bufpos
;
452 nsent
= send(s
->s
, s
->head
->buf
+ s
->head
->bufpos
, len
, urgentflag
);
453 noise_ultralight(nsent
);
455 err
= (nsent
< 0 ?
WSAGetLastError() : 0);
456 if (err
== WSAEWOULDBLOCK
) {
457 /* Perfectly normal: we've sent all we can for the moment. */
460 } else if (nsent
== 0 ||
461 err
== WSAECONNABORTED
||
462 err
== WSAECONNRESET
) {
464 * FIXME. This will have to be done better when we
465 * start managing multiple sockets (e.g. SSH port
466 * forwarding), because if we get CONNRESET while
467 * trying to write a particular forwarded socket
468 * then it isn't necessarily the end of the world.
469 * Ideally I'd like to pass the error code back to
470 * somewhere the next select_result() will see it,
471 * but that might be hard. Perhaps I should pass it
472 * back to be queued in the Windows front end bit.
474 fatalbox(winsock_error_string(err
));
476 fatalbox(winsock_error_string(err
));
479 s
->head
->bufpos
+= nsent
;
481 s
->sending_oob
-= nsent
;
482 if (s
->head
->bufpos
>= s
->head
->buflen
) {
483 struct buffer
*tmp
= s
->head
;
493 void sk_write(Socket s
, char *buf
, int len
) {
495 * Add the data to the buffer list on the socket.
497 if (s
->tail
&& s
->tail
->buflen
< BUFFER_GRANULE
) {
498 int copylen
= min(len
, BUFFER_GRANULE
- s
->tail
->buflen
);
499 memcpy(s
->tail
->buf
+ s
->tail
->buflen
, buf
, copylen
);
502 s
->tail
->buflen
+= copylen
;
505 int grainlen
= min(len
, BUFFER_GRANULE
);
506 struct buffer
*newbuf
;
507 newbuf
= smalloc(sizeof(struct buffer
));
509 newbuf
->buflen
= grainlen
;
510 memcpy(newbuf
->buf
, buf
, grainlen
);
514 s
->tail
->next
= newbuf
;
516 s
->head
= s
->tail
= newbuf
;
522 * Now try sending from the start of the buffer list.
528 void sk_write_oob(Socket s
, char *buf
, int len
) {
530 * Replace the buffer list on the socket with the data.
533 s
->head
= smalloc(sizeof(struct buffer
));
535 struct buffer
*walk
= s
->head
->next
;
537 struct buffer
*tmp
= walk
;
542 s
->head
->next
= NULL
;
544 s
->head
->buflen
= len
;
545 memcpy(s
->head
->buf
, buf
, len
);
548 * Set the Urgent marker.
550 s
->sending_oob
= len
;
553 * Now try sending from the start of the buffer list.
559 int select_result(WPARAM wParam
, LPARAM lParam
) {
562 char buf
[BUFFER_GRANULE
];
566 /* wParam is the socket itself */
567 s
= find234(sktree
, (void *)wParam
, cmpforsearch
);
569 return 1; /* boggle */
571 if ((err
= WSAGETSELECTERROR(lParam
)) != 0) {
573 * An error has occurred on this socket. Pass it to the
576 return s
->receiver(s
, 3, winsock_error_string(err
), err
);
579 noise_ultralight(lParam
);
581 switch (WSAGETSELECTEVENT(lParam
)) {
583 ret
= recv(s
->s
, buf
, sizeof(buf
), 0);
585 err
= WSAGetLastError();
586 if (err
== WSAEWOULDBLOCK
) {
591 return s
->receiver(s
, 3, winsock_error_string(err
), err
);
593 int type
= s
->in_oob ?
2 : 0;
595 return s
->receiver(s
, type
, buf
, ret
);
600 * Read all data up to the OOB marker, and send it to the
601 * receiver with urgent==1 (OOB pending).
605 /* Some WinSock wrappers don't support this call, so we
606 * deliberately don't check the return value. If the call
607 * fails and does nothing, we will get back atmark==1,
608 * which is good enough to keep going at least. */
609 ioctlsocket(s
->s
, SIOCATMARK
, &atmark
);
610 ret
= recv(s
->s
, buf
, sizeof(buf
), MSG_OOB
);
611 noise_ultralight(ret
);
613 fatalbox(ret
== 0 ?
"Internal networking trouble" :
614 winsock_error_string(WSAGetLastError()));
616 return s
->receiver(s
, atmark ?
2 : 1, buf
, ret
);
624 /* Signal a close on the socket. */
625 return s
->receiver(s
, 0, NULL
, 0);
633 * Each socket abstraction contains a `void *' private field in
634 * which the client can keep state.
636 void sk_set_private_ptr(Socket s
, void *ptr
) {
637 s
->private_ptr
= ptr
;
639 void *sk_get_private_ptr(Socket s
) {
640 return s
->private_ptr
;
644 * Special error values are returned from sk_namelookup and sk_new
645 * if there's a problem. These functions extract an error message,
646 * or return NULL if there's no problem.
648 char *sk_addr_error(SockAddr addr
) {
651 char *sk_socket_error(Socket s
) {
656 * For Plink: enumerate all sockets currently active.
658 SOCKET
first_socket(enum234
*e
) {
659 Socket s
= first234(sktree
, e
);
660 return s ? s
->s
: INVALID_SOCKET
;
662 SOCKET
next_socket(enum234
*e
) {
663 Socket s
= next234(e
);
664 return s ? s
->s
: INVALID_SOCKET
;