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;
71 /* address family this belongs to, AF_INET for IPv4, AF_INET6 for IPv6. */
73 unsigned long address; /* Address IPv4 style. */
75 struct addrinfo *ai; /* Address IPv6 style. */
78 * We need to have this lengthy enough to hold *any* hostname
79 * (including IPv6 reverse...)
87 char buf[BUFFER_GRANULE];
90 static tree234 *sktree;
92 static int cmpfortree(void *av, void *bv) {
93 Socket a = (Socket)av, b = (Socket)bv;
94 unsigned long as = (unsigned long)a->s, bs = (unsigned long)b->s;
95 if (as < bs) return -1;
96 if (as > bs) return +1;
100 static int cmpforsearch(void *av, void *bv) {
101 Socket b = (Socket)bv;
102 unsigned long as = (unsigned long)av, bs = (unsigned long)b->s;
103 if (as < bs) return -1;
104 if (as > bs) return +1;
109 sktree = newtree234(cmpfortree);
112 char *winsock_error_string(int error) {
114 case WSAEACCES: return "Network error: Permission denied";
115 case WSAEADDRINUSE: return "Network error: Address already in use";
116 case WSAEADDRNOTAVAIL: return "Network error: Cannot assign requested address";
117 case WSAEAFNOSUPPORT: return "Network error: Address family not supported by protocol family";
118 case WSAEALREADY: return "Network error: Operation already in progress";
119 case WSAECONNABORTED: return "Network error: Software caused connection abort";
120 case WSAECONNREFUSED: return "Network error: Connection refused";
121 case WSAECONNRESET: return "Network error: Connection reset by peer";
122 case WSAEDESTADDRREQ: return "Network error: Destination address required";
123 case WSAEFAULT: return "Network error: Bad address";
124 case WSAEHOSTDOWN: return "Network error: Host is down";
125 case WSAEHOSTUNREACH: return "Network error: No route to host";
126 case WSAEINPROGRESS: return "Network error: Operation now in progress";
127 case WSAEINTR: return "Network error: Interrupted function call";
128 case WSAEINVAL: return "Network error: Invalid argument";
129 case WSAEISCONN: return "Network error: Socket is already connected";
130 case WSAEMFILE: return "Network error: Too many open files";
131 case WSAEMSGSIZE: return "Network error: Message too long";
132 case WSAENETDOWN: return "Network error: Network is down";
133 case WSAENETRESET: return "Network error: Network dropped connection on reset";
134 case WSAENETUNREACH: return "Network error: Network is unreachable";
135 case WSAENOBUFS: return "Network error: No buffer space available";
136 case WSAENOPROTOOPT: return "Network error: Bad protocol option";
137 case WSAENOTCONN: return "Network error: Socket is not connected";
138 case WSAENOTSOCK: return "Network error: Socket operation on non-socket";
139 case WSAEOPNOTSUPP: return "Network error: Operation not supported";
140 case WSAEPFNOSUPPORT: return "Network error: Protocol family not supported";
141 case WSAEPROCLIM: return "Network error: Too many processes";
142 case WSAEPROTONOSUPPORT: return "Network error: Protocol not supported";
143 case WSAEPROTOTYPE: return "Network error: Protocol wrong type for socket";
144 case WSAESHUTDOWN: return "Network error: Cannot send after socket shutdown";
145 case WSAESOCKTNOSUPPORT: return "Network error: Socket type not supported";
146 case WSAETIMEDOUT: return "Network error: Connection timed out";
147 case WSAEWOULDBLOCK: return "Network error: Resource temporarily unavailable";
148 case WSAEDISCON: return "Network error: Graceful shutdown in progress";
149 default: return "Unknown network error";
153 SockAddr sk_namelookup(char *host, char **canonicalname)
155 SockAddr ret = smalloc(sizeof(struct SockAddr_tag));
157 struct hostent *h = NULL;
159 /* Clear the structure and default to IPv4. */
160 memset(ret, 0, sizeof(struct SockAddr_tag));
161 ret->family = 0; /* We set this one when we have resolved the host. */
162 *canonicalname = ret->realhost; /* This makes sure we always have a hostname to return. */
164 if ( (a = inet_addr(host)) == (unsigned long) INADDR_NONE)
168 /* Try to get the getaddrinfo() function from wship6.dll */
169 /* This way one doesn't need to have IPv6 dll's to use PuTTY and
170 * it will fallback to IPv4. */
171 typedef int (CALLBACK* FGETADDRINFO)(const char *nodename,
172 const char *servname,
173 const struct addrinfo *hints,
174 struct addrinfo **res);
175 FGETADDRINFO fGetAddrInfo = NULL;
177 HINSTANCE dllWSHIP6 = LoadLibrary("wship6.dll");
179 fGetAddrInfo = (FGETADDRINFO)GetProcAddress(dllWSHIP6,
183 * Use fGetAddrInfo when it's available (which usually also
184 * means IPv6 is installed...)
188 /*debug(("Resolving \"%s\" with getaddrinfo() (IPv4+IPv6 capable)...\n", host)); */
189 if (fGetAddrInfo(host, NULL, NULL, &ret->ai) == 0)
190 ret->family = ret->ai->ai_family;
195 * Otherwise use the IPv4-only gethostbyname...
196 * (NOTE: we don't use gethostbyname as a
199 if (ret->family == 0)
201 /*debug(("Resolving \"%s\" with gethostbyname() (IPv4 only)...\n", host)); */
202 if (h = gethostbyname(host)) ret->family = AF_INET;
204 /*debug(("Done resolving...(family is %d) AF_INET = %d, AF_INET6 = %d\n", ret->family, AF_INET, AF_INET6)); */
206 if (ret->family == 0)
208 DWORD err = WSAGetLastError();
209 ret->error = (err == WSAENETDOWN ? "Network is down" :
210 err == WSAHOST_NOT_FOUND ? "Host does not exist" :
211 err == WSATRY_AGAIN ? "Host not found" :
213 fGetAddrInfo ? "getaddrinfo: unknown error" :
215 "gethostbyname: unknown error");
219 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&lpMsgBuf, 0, NULL);
220 /*debug(("Error %ld: %s (h=%lx)\n", err, lpMsgBuf, h));*/
221 /* Free the buffer. */
231 /* If we got an address info use that... */
234 typedef int (CALLBACK* FGETNAMEINFO)
235 (const struct sockaddr FAR *sa, socklen_t salen,
236 char FAR * host, size_t hostlen, char FAR * serv,
237 size_t servlen, int flags);
238 FGETNAMEINFO fGetNameInfo = NULL;
240 /* Are we in IPv4 fallback mode? */
241 /* We put the IPv4 address into the a variable so we can further-on use the IPv4 code... */
242 if (ret->family == AF_INET)
243 memcpy(&a, (char *)&((SOCKADDR_IN *)ret->ai->ai_addr)->sin_addr, sizeof(a));
245 /* Now let's find that canonicalname... */
246 if ((dllWSHIP6) && (fGetNameInfo = (FGETNAMEINFO)GetProcAddress(dllWSHIP6, "getnameinfo")))
248 if (fGetNameInfo((struct sockaddr *)ret->ai->ai_addr,
249 ret->family == AF_INET ?
250 sizeof(SOCKADDR_IN) :
251 sizeof(SOCKADDR_IN6), ret->realhost,
252 sizeof(ret->realhost), NULL,
255 strncpy(ret->realhost, host,
256 sizeof(ret->realhost));
260 /* We used the IPv4-only gethostbyname()... */
264 memcpy(&a, h->h_addr, sizeof(a));
265 /* This way we are always sure the h->h_name is valid :) */
266 strncpy(ret->realhost, h->h_name, sizeof(ret->realhost));
272 FreeLibrary(dllWSHIP6);
278 * Hack inserted to deal with problems with numeric IPs.
279 * FIXME: how will this work in IPv6?
281 ret->family = AF_INET;
282 *canonicalname = host;
284 ret->address = ntohl(a);
288 void sk_addr_free(SockAddr addr) {
292 Socket sk_new(SockAddr addr, int port, int privport, int oobinline,
293 sk_receiver_t receiver) {
302 extern char *do_select(SOCKET skt, int startup);
306 * Create Socket structure.
308 ret = smalloc(sizeof(struct Socket_tag));
310 ret->receiver = receiver;
311 ret->head = ret->tail = NULL;
312 ret->writable = 1; /* to start with */
313 ret->sending_oob = 0;
318 s = socket(addr->family, SOCK_STREAM, 0);
321 if (s == INVALID_SOCKET) {
322 err = WSAGetLastError();
323 ret->error = winsock_error_string(err);
327 ret->oobinline = oobinline;
330 setsockopt (s, SOL_SOCKET, SO_OOBINLINE, (void *)&b, sizeof(b));
334 * Bind to local address.
337 localport = 1023; /* count from 1023 downwards */
339 localport = 0; /* just use port 0 (ie winsock picks) */
341 /* Loop round trying to bind */
346 if (addr->family == AF_INET6)
348 memset(&a6,0,sizeof(a6));
349 a6.sin6_family = AF_INET6;
350 /*a6.sin6_addr = in6addr_any;*/ /* == 0 */
351 a6.sin6_port = htons(localport);
356 a.sin_family = AF_INET;
357 a.sin_addr.s_addr = htonl(INADDR_ANY);
358 a.sin_port = htons(localport);
361 retcode = bind (s, (addr->family == AF_INET6 ?
362 (struct sockaddr *)&a6 :
363 (struct sockaddr *)&a),
364 (addr->family == AF_INET6 ? sizeof(a6) : sizeof(a)));
366 retcode = bind (s, (struct sockaddr *)&a, sizeof(a));
368 if (retcode != SOCKET_ERROR) {
372 err = WSAGetLastError();
373 if (err != WSAEADDRINUSE) /* failed, for a bad reason */
378 break; /* we're only looping once */
381 break; /* we might have got to the end */
386 ret->error = winsock_error_string(err);
391 * Connect to remote address.
394 if (addr->family == AF_INET6)
396 memset(&a,0,sizeof(a));
397 a6.sin6_family = AF_INET6;
398 a6.sin6_port = htons((short)port);
399 a6.sin6_addr = ((struct sockaddr_in6 *)addr->ai->ai_addr)->sin6_addr;
404 a.sin_family = AF_INET;
405 a.sin_addr.s_addr = htonl(addr->address);
406 a.sin_port = htons((short)port);
409 if (connect (s, (addr->family == AF_INET6) ? (struct sockaddr *)&a6 : (struct sockaddr *)&a, (addr->family == AF_INET6) ? sizeof(a6) : sizeof(a)) == SOCKET_ERROR)
411 if (connect (s, (struct sockaddr *)&a, sizeof(a)) == SOCKET_ERROR)
414 err = WSAGetLastError();
415 ret->error = winsock_error_string(err);
419 /* Set up a select mechanism. This could be an AsyncSelect on a
420 * window, or an EventSelect on an event object. */
421 errstr = do_select(s, 1);
432 void sk_close(Socket s) {
433 extern char *do_select(SOCKET skt, int startup);
442 * The function which tries to send on a socket once it's deemed
445 void try_send(Socket s) {
451 if (s->sending_oob) {
452 urgentflag = MSG_OOB;
453 len = s->sending_oob;
456 len = s->head->buflen - s->head->bufpos;
459 nsent = send(s->s, s->head->buf + s->head->bufpos, len, urgentflag);
460 noise_ultralight(nsent);
462 err = (nsent < 0 ? WSAGetLastError() : 0);
463 if (err == WSAEWOULDBLOCK) {
464 /* Perfectly normal: we've sent all we can for the moment. */
467 } else if (nsent == 0 ||
468 err == WSAECONNABORTED ||
469 err == WSAECONNRESET) {
471 * FIXME. This will have to be done better when we
472 * start managing multiple sockets (e.g. SSH port
473 * forwarding), because if we get CONNRESET while
474 * trying to write a particular forwarded socket
475 * then it isn't necessarily the end of the world.
476 * Ideally I'd like to pass the error code back to
477 * somewhere the next select_result() will see it,
478 * but that might be hard. Perhaps I should pass it
479 * back to be queued in the Windows front end bit.
481 fatalbox(winsock_error_string(err));
483 fatalbox(winsock_error_string(err));
486 s->head->bufpos += nsent;
488 s->sending_oob -= nsent;
489 if (s->head->bufpos >= s->head->buflen) {
490 struct buffer *tmp = s->head;
500 void sk_write(Socket s, char *buf, int len) {
502 * Add the data to the buffer list on the socket.
504 if (s->tail && s->tail->buflen < BUFFER_GRANULE) {
505 int copylen = min(len, BUFFER_GRANULE - s->tail->buflen);
506 memcpy(s->tail->buf + s->tail->buflen, buf, copylen);
509 s->tail->buflen += copylen;
512 int grainlen = min(len, BUFFER_GRANULE);
513 struct buffer *newbuf;
514 newbuf = smalloc(sizeof(struct buffer));
516 newbuf->buflen = grainlen;
517 memcpy(newbuf->buf, buf, grainlen);
521 s->tail->next = newbuf;
523 s->head = s->tail = newbuf;
529 * Now try sending from the start of the buffer list.
535 void sk_write_oob(Socket s, char *buf, int len) {
537 * Replace the buffer list on the socket with the data.
540 s->head = smalloc(sizeof(struct buffer));
542 struct buffer *walk = s->head->next;
544 struct buffer *tmp = walk;
549 s->head->next = NULL;
551 s->head->buflen = len;
552 memcpy(s->head->buf, buf, len);
555 * Set the Urgent marker.
557 s->sending_oob = len;
560 * Now try sending from the start of the buffer list.
566 int select_result(WPARAM wParam, LPARAM lParam) {
569 char buf[BUFFER_GRANULE];
573 /* wParam is the socket itself */
574 s = find234(sktree, (void *)wParam, cmpforsearch);
576 return 1; /* boggle */
578 if ((err = WSAGETSELECTERROR(lParam)) != 0) {
580 * An error has occurred on this socket. Pass it to the
583 return s->receiver(s, 3, winsock_error_string(err), err);
586 noise_ultralight(lParam);
588 switch (WSAGETSELECTEVENT(lParam)) {
591 * We have received data on the socket. For an oobinline
592 * socket, this might be data _before_ an urgent pointer,
593 * in which case we send it to the back end with type==1
594 * (data prior to urgent).
598 ioctlsocket(s->s, SIOCATMARK, &atmark);
600 * Avoid checking the return value from ioctlsocket(),
601 * on the grounds that some WinSock wrappers don't
602 * support it. If it does nothing, we get atmark==1,
603 * which is equivalent to `no OOB pending', so the
604 * effect will be to non-OOB-ify any OOB data.
609 ret = recv(s->s, buf, sizeof(buf), 0);
610 noise_ultralight(ret);
612 err = WSAGetLastError();
613 if (err == WSAEWOULDBLOCK) {
618 return s->receiver(s, 3, winsock_error_string(err), err);
620 return s->receiver(s, atmark ? 0 : 1, buf, ret);
625 * This will only happen on a non-oobinline socket. It
626 * indicates that we can immediately perform an OOB read
627 * and get back OOB data, which we will send to the back
628 * end with type==2 (urgent data).
630 ret = recv(s->s, buf, sizeof(buf), MSG_OOB);
631 noise_ultralight(ret);
633 fatalbox(ret == 0 ? "Internal networking trouble" :
634 winsock_error_string(WSAGetLastError()));
636 return s->receiver(s, 2, buf, ret);
644 /* Signal a close on the socket. First read any outstanding data. */
647 ret = recv(s->s, buf, sizeof(buf), 0);
649 err = WSAGetLastError();
650 if (err == WSAEWOULDBLOCK)
652 return s->receiver(s, 3, winsock_error_string(err), err);
654 open &= s->receiver(s, 0, buf, ret);
663 * Each socket abstraction contains a `void *' private field in
664 * which the client can keep state.
666 void sk_set_private_ptr(Socket s, void *ptr) {
667 s->private_ptr = ptr;
669 void *sk_get_private_ptr(Socket s) {
670 return s->private_ptr;
674 * Special error values are returned from sk_namelookup and sk_new
675 * if there's a problem. These functions extract an error message,
676 * or return NULL if there's no problem.
678 char *sk_addr_error(SockAddr addr) {
681 char *sk_socket_error(Socket s) {
686 * For Plink: enumerate all sockets currently active.
688 SOCKET first_socket(enum234 *e) {
689 Socket s = first234(sktree, e);
690 return s ? s->s : INVALID_SOCKET;
692 SOCKET next_socket(enum234 *e) {
693 Socket s = next234(e);
694 return s ? s->s : INVALID_SOCKET;