cc0b080c63c76148b31ddf91fc4f7e4a22efc624
[u/mdw/putty] / winnet.c
1 /*
2 * Windows networking abstraction.
3 *
4 * Due to this clean abstraction it was possible
5 * to easily implement IPv6 support :)
6 *
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.
12 *
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.
16 *
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.
27 *
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...
31 *
32 */
33
34 /*
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.
38 */
39 /* #define IPV6 1 */
40
41 #ifdef IPV6
42 #include <winsock2.h>
43 #include <ws2tcpip.h>
44 #include <tpipv6.h>
45 #else
46 #include <winsock.h>
47 #endif
48 #include <windows.h>
49 #include <stdio.h>
50 #include <stdlib.h>
51
52 #include "putty.h"
53 #include "network.h"
54 #include "tree234.h"
55
56 #define BUFFER_GRANULE 512
57
58 struct Socket_tag {
59 char *error;
60 SOCKET s;
61 sk_receiver_t receiver;
62 void *private_ptr;
63 struct buffer *head, *tail;
64 int writable;
65 int sending_oob;
66 };
67
68 struct SockAddr_tag {
69 char *error;
70 /* address family this belongs to, AF_INET for IPv4, AF_INET6 for IPv6. */
71 int family;
72 unsigned long address; /* Address IPv4 style. */
73 #ifdef IPV6
74 struct addrinfo *ai; /* Address IPv6 style. */
75 #endif
76 /*
77 * We need to have this lengthy enough to hold *any* hostname
78 * (including IPv6 reverse...)
79 */
80 char realhost[8192];
81 };
82
83 struct buffer {
84 struct buffer *next;
85 int buflen, bufpos;
86 char buf[BUFFER_GRANULE];
87 };
88
89 static tree234 *sktree;
90
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;
96 return 0;
97 }
98
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;
104 return 0;
105 }
106
107 void sk_init(void) {
108 sktree = newtree234(cmpfortree);
109 }
110
111 char *winsock_error_string(int error) {
112 switch (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";
149 }
150 }
151
152 SockAddr sk_namelookup(char *host, char **canonicalname)
153 {
154 SockAddr ret = smalloc(sizeof(struct SockAddr_tag));
155 unsigned long a;
156 struct hostent *h = NULL;
157
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. */
162
163 if ( (a = inet_addr(host)) == (unsigned long) INADDR_NONE)
164 {
165 #ifdef IPV6
166
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;
175
176 HINSTANCE dllWSHIP6 = LoadLibrary("wship6.dll");
177 if (dllWSHIP6)
178 fGetAddrInfo = (FGETADDRINFO)GetProcAddress(dllWSHIP6,
179 "getaddrinfo");
180
181 /*
182 * Use fGetAddrInfo when it's available (which usually also
183 * means IPv6 is installed...)
184 */
185 if (fGetAddrInfo)
186 {
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;
190 }
191 else
192 #endif
193 /*
194 * Otherwise use the IPv4-only gethostbyname...
195 * (NOTE: we don't use gethostbyname as a
196 * fallback!)
197 */
198 if (ret->family == 0)
199 {
200 /*debug(("Resolving \"%s\" with gethostbyname() (IPv4 only)...\n", host)); */
201 if (h = gethostbyname(host)) ret->family = AF_INET;
202 }
203 /*debug(("Done resolving...(family is %d) AF_INET = %d, AF_INET6 = %d\n", ret->family, AF_INET, AF_INET6)); */
204
205 if (ret->family == 0)
206 {
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" :
211 #ifdef IPV6
212 fGetAddrInfo ? "getaddrinfo: unknown error" :
213 #endif
214 "gethostbyname: unknown error");
215 #ifdef DEBUG
216 {
217 LPVOID lpMsgBuf;
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. */
221 LocalFree(lpMsgBuf);
222 }
223 #endif
224 }
225 else
226 {
227 ret->error = NULL;
228
229 #ifdef IPV6
230 /* If we got an address info use that... */
231 if (ret->ai)
232 {
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;
238
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));
243
244 /* Now let's find that canonicalname... */
245 if ((dllWSHIP6) && (fGetNameInfo = (FGETNAMEINFO)GetProcAddress(dllWSHIP6, "getnameinfo")))
246 {
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,
252 0, 0) != 0)
253 {
254 strncpy(ret->realhost, host,
255 sizeof(ret->realhost));
256 }
257 }
258 }
259 /* We used the IPv4-only gethostbyname()... */
260 else
261 {
262 #endif
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));
266 #ifdef IPV6
267 }
268 #endif
269 }
270 #ifdef IPV6
271 FreeLibrary(dllWSHIP6);
272 #endif
273 }
274 else
275 {
276 /*
277 * Hack inserted to deal with problems with numeric IPs.
278 * FIXME: how will this work in IPv6?
279 */
280 ret->family = AF_INET;
281 *canonicalname = host;
282 }
283 ret->address = ntohl(a);
284 return ret;
285 }
286
287 void sk_addr_free(SockAddr addr) {
288 sfree(addr);
289 }
290
291 Socket sk_new(SockAddr addr, int port, int privport, sk_receiver_t receiver) {
292 SOCKET s;
293 #ifdef IPV6
294 SOCKADDR_IN6 a6;
295 #endif
296 SOCKADDR_IN a;
297 DWORD err;
298 char *errstr;
299 Socket ret;
300 extern char *do_select(SOCKET skt, int startup);
301 short localport;
302
303 /*
304 * Create Socket structure.
305 */
306 ret = smalloc(sizeof(struct Socket_tag));
307 ret->error = NULL;
308 ret->receiver = receiver;
309 ret->head = ret->tail = NULL;
310 ret->writable = 1; /* to start with */
311 ret->sending_oob = 0;
312
313 /*
314 * Open socket.
315 */
316 s = socket(addr->family, SOCK_STREAM, 0);
317 ret->s = s;
318
319 if (s == INVALID_SOCKET) {
320 err = WSAGetLastError();
321 ret->error = winsock_error_string(err);
322 return ret;
323 }
324 {
325 BOOL b = TRUE;
326 setsockopt (s, SOL_SOCKET, SO_OOBINLINE, (void *)&b, sizeof(b));
327 }
328
329 /*
330 * Bind to local address.
331 */
332 if (privport)
333 localport = 1023; /* count from 1023 downwards */
334 else
335 localport = 0; /* just use port 0 (ie winsock picks) */
336
337 /* Loop round trying to bind */
338 while (1) {
339 int retcode;
340
341 #ifdef IPV6
342 if (addr->family == AF_INET6)
343 {
344 memset(&a6,0,sizeof(a6));
345 a6.sin6_family = AF_INET6;
346 /*a6.sin6_addr = in6addr_any;*/ /* == 0 */
347 a6.sin6_port = htons(localport);
348 }
349 else
350 {
351 #endif
352 a.sin_family = AF_INET;
353 a.sin_addr.s_addr = htonl(INADDR_ANY);
354 a.sin_port = htons(localport);
355 #ifdef IPV6
356 }
357 retcode = bind (s, (addr->family == AF_INET6 ?
358 (struct sockaddr *)&a6 :
359 (struct sockaddr *)&a),
360 (addr->family == AF_INET6 ? sizeof(a6) : sizeof(a)));
361 #else
362 retcode = bind (s, (struct sockaddr *)&a, sizeof(a));
363 #endif
364 if (retcode != SOCKET_ERROR) {
365 err = 0;
366 break; /* done */
367 } else {
368 err = WSAGetLastError();
369 if (err != WSAEADDRINUSE) /* failed, for a bad reason */
370 break;
371 }
372
373 if (localport == 0)
374 break; /* we're only looping once */
375 localport--;
376 if (localport == 0)
377 break; /* we might have got to the end */
378 }
379
380 if (err)
381 {
382 ret->error = winsock_error_string(err);
383 return ret;
384 }
385
386 /*
387 * Connect to remote address.
388 */
389 #ifdef IPV6
390 if (addr->family == AF_INET6)
391 {
392 memset(&a,0,sizeof(a));
393 a6.sin6_family = AF_INET6;
394 a6.sin6_port = htons((short)port);
395 a6.sin6_addr = ((struct sockaddr_in6 *)addr->ai->ai_addr)->sin6_addr;
396 }
397 else
398 {
399 #endif
400 a.sin_family = AF_INET;
401 a.sin_addr.s_addr = htonl(addr->address);
402 a.sin_port = htons((short)port);
403 #ifdef IPV6
404 }
405 if (connect (s, (addr->family == AF_INET6) ? (struct sockaddr *)&a6 : (struct sockaddr *)&a, (addr->family == AF_INET6) ? sizeof(a6) : sizeof(a)) == SOCKET_ERROR)
406 #else
407 if (connect (s, (struct sockaddr *)&a, sizeof(a)) == SOCKET_ERROR)
408 #endif
409 {
410 err = WSAGetLastError();
411 ret->error = winsock_error_string(err);
412 return ret;
413 }
414
415 /* Set up a select mechanism. This could be an AsyncSelect on a
416 * window, or an EventSelect on an event object. */
417 errstr = do_select(s, 1);
418 if (errstr) {
419 ret->error = errstr;
420 return ret;
421 }
422
423 add234(sktree, ret);
424
425 return ret;
426 }
427
428 void sk_close(Socket s) {
429 extern char *do_select(SOCKET skt, int startup);
430
431 del234(sktree, s);
432 do_select(s->s, 0);
433 closesocket(s->s);
434 sfree(s);
435 }
436
437 /*
438 * The function which tries to send on a socket once it's deemed
439 * writable.
440 */
441 void try_send(Socket s) {
442 while (s->head) {
443 int nsent;
444 DWORD err;
445 int len, urgentflag;
446
447 if (s->sending_oob) {
448 urgentflag = MSG_OOB;
449 len = s->sending_oob;
450 } else {
451 urgentflag = 0;
452 len = s->head->buflen - s->head->bufpos;
453 }
454
455 nsent = send(s->s, s->head->buf + s->head->bufpos, len, urgentflag);
456 noise_ultralight(nsent);
457 if (nsent <= 0) {
458 err = (nsent < 0 ? WSAGetLastError() : 0);
459 if (err == WSAEWOULDBLOCK) {
460 /* Perfectly normal: we've sent all we can for the moment. */
461 s->writable = FALSE;
462 return;
463 } else if (nsent == 0 ||
464 err == WSAECONNABORTED ||
465 err == WSAECONNRESET) {
466 /*
467 * FIXME. This will have to be done better when we
468 * start managing multiple sockets (e.g. SSH port
469 * forwarding), because if we get CONNRESET while
470 * trying to write a particular forwarded socket
471 * then it isn't necessarily the end of the world.
472 * Ideally I'd like to pass the error code back to
473 * somewhere the next select_result() will see it,
474 * but that might be hard. Perhaps I should pass it
475 * back to be queued in the Windows front end bit.
476 */
477 fatalbox(winsock_error_string(err));
478 } else {
479 fatalbox(winsock_error_string(err));
480 }
481 } else {
482 s->head->bufpos += nsent;
483 if (s->sending_oob)
484 s->sending_oob -= nsent;
485 if (s->head->bufpos >= s->head->buflen) {
486 struct buffer *tmp = s->head;
487 s->head = tmp->next;
488 sfree(tmp);
489 if (!s->head)
490 s->tail = NULL;
491 }
492 }
493 }
494 }
495
496 void sk_write(Socket s, char *buf, int len) {
497 /*
498 * Add the data to the buffer list on the socket.
499 */
500 if (s->tail && s->tail->buflen < BUFFER_GRANULE) {
501 int copylen = min(len, BUFFER_GRANULE - s->tail->buflen);
502 memcpy(s->tail->buf + s->tail->buflen, buf, copylen);
503 buf += copylen;
504 len -= copylen;
505 s->tail->buflen += copylen;
506 }
507 while (len > 0) {
508 int grainlen = min(len, BUFFER_GRANULE);
509 struct buffer *newbuf;
510 newbuf = smalloc(sizeof(struct buffer));
511 newbuf->bufpos = 0;
512 newbuf->buflen = grainlen;
513 memcpy(newbuf->buf, buf, grainlen);
514 buf += grainlen;
515 len -= grainlen;
516 if (s->tail)
517 s->tail->next = newbuf;
518 else
519 s->head = s->tail = newbuf;
520 newbuf->next = NULL;
521 s->tail = newbuf;
522 }
523
524 /*
525 * Now try sending from the start of the buffer list.
526 */
527 if (s->writable)
528 try_send(s);
529 }
530
531 void sk_write_oob(Socket s, char *buf, int len) {
532 /*
533 * Replace the buffer list on the socket with the data.
534 */
535 if (!s->head) {
536 s->head = smalloc(sizeof(struct buffer));
537 } else {
538 struct buffer *walk = s->head->next;
539 while (walk) {
540 struct buffer *tmp = walk;
541 walk = tmp->next;
542 sfree(tmp);
543 }
544 }
545 s->head->next = NULL;
546 s->tail = s->head;
547 s->head->buflen = len;
548 memcpy(s->head->buf, buf, len);
549
550 /*
551 * Set the Urgent marker.
552 */
553 s->sending_oob = len;
554
555 /*
556 * Now try sending from the start of the buffer list.
557 */
558 if (s->writable)
559 try_send(s);
560 }
561
562 int select_result(WPARAM wParam, LPARAM lParam) {
563 int ret, open;
564 DWORD err;
565 char buf[BUFFER_GRANULE];
566 Socket s;
567 u_long atmark;
568
569 /* wParam is the socket itself */
570 s = find234(sktree, (void *)wParam, cmpforsearch);
571 if (!s)
572 return 1; /* boggle */
573
574 if ((err = WSAGETSELECTERROR(lParam)) != 0) {
575 /*
576 * An error has occurred on this socket. Pass it to the
577 * receiver function.
578 */
579 return s->receiver(s, 3, winsock_error_string(err), err);
580 }
581
582 noise_ultralight(lParam);
583
584 switch (WSAGETSELECTEVENT(lParam)) {
585 case FD_READ:
586 atmark = 1;
587 /* Some WinSock wrappers don't support this call, so we
588 * deliberately don't check the return value. If the call
589 * fails and does nothing, we will get back atmark==1,
590 * which is good enough to keep going at least. */
591 ioctlsocket(s->s, SIOCATMARK, &atmark);
592 ret = recv(s->s, buf, sizeof(buf), 0);
593 if (ret < 0) {
594 err = WSAGetLastError();
595 if (err == WSAEWOULDBLOCK) {
596 break;
597 }
598 }
599 if (ret < 0) {
600 return s->receiver(s, 3, winsock_error_string(err), err);
601 } else {
602 int type = 0;
603 if (atmark==0) {
604 ioctlsocket(s->s, SIOCATMARK, &atmark);
605 if(atmark) type = 2; else type = 1;
606 }
607 return s->receiver(s, type, buf, ret);
608 }
609 break;
610 case FD_OOB:
611 /*
612 * Read all data up to the OOB marker, and send it to the
613 * receiver with urgent==1 (OOB pending).
614 */
615 ret = recv(s->s, buf, sizeof(buf), MSG_OOB);
616 noise_ultralight(ret);
617 if (ret <= 0) {
618 fatalbox(ret == 0 ? "Internal networking trouble" :
619 winsock_error_string(WSAGetLastError()));
620 } else {
621 return s->receiver(s, 2, buf, ret);
622 }
623 break;
624 case FD_WRITE:
625 s->writable = 1;
626 try_send(s);
627 break;
628 case FD_CLOSE:
629 /* Signal a close on the socket. First read any outstanding data. */
630 open = 1;
631 do {
632 ret = recv(s->s, buf, sizeof(buf), 0);
633 if (ret < 0) {
634 err = WSAGetLastError();
635 if (err == WSAEWOULDBLOCK)
636 break;
637 return s->receiver(s, 3, winsock_error_string(err), err);
638 } else
639 open &= s->receiver(s, 0, buf, ret);
640 } while (ret > 0);
641 return open;
642 }
643
644 return 1;
645 }
646
647 /*
648 * Each socket abstraction contains a `void *' private field in
649 * which the client can keep state.
650 */
651 void sk_set_private_ptr(Socket s, void *ptr) {
652 s->private_ptr = ptr;
653 }
654 void *sk_get_private_ptr(Socket s) {
655 return s->private_ptr;
656 }
657
658 /*
659 * Special error values are returned from sk_namelookup and sk_new
660 * if there's a problem. These functions extract an error message,
661 * or return NULL if there's no problem.
662 */
663 char *sk_addr_error(SockAddr addr) {
664 return addr->error;
665 }
666 char *sk_socket_error(Socket s) {
667 return s->error;
668 }
669
670 /*
671 * For Plink: enumerate all sockets currently active.
672 */
673 SOCKET first_socket(enum234 *e) {
674 Socket s = first234(sktree, e);
675 return s ? s->s : INVALID_SOCKET;
676 }
677 SOCKET next_socket(enum234 *e) {
678 Socket s = next234(e);
679 return s ? s->s : INVALID_SOCKET;
680 }