Introduced wrapper macros snew(), snewn() and sresize() for the
[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 #include <assert.h>
52
53 #define DEFINE_PLUG_METHOD_MACROS
54 #include "putty.h"
55 #include "network.h"
56 #include "tree234.h"
57
58 #define ipv4_is_loopback(addr) \
59 ((ntohl(addr.s_addr) & 0xFF000000L) == 0x7F000000L)
60
61 struct Socket_tag {
62 const struct socket_function_table *fn;
63 /* the above variable absolutely *must* be the first in this structure */
64 char *error;
65 SOCKET s;
66 Plug plug;
67 void *private_ptr;
68 bufchain output_data;
69 int connected;
70 int writable;
71 int frozen; /* this causes readability notifications to be ignored */
72 int frozen_readable; /* this means we missed at least one readability
73 * notification while we were frozen */
74 int localhost_only; /* for listening sockets */
75 char oobdata[1];
76 int sending_oob;
77 int oobinline;
78 int pending_error; /* in case send() returns error */
79 };
80
81 /*
82 * We used to typedef struct Socket_tag *Socket.
83 *
84 * Since we have made the networking abstraction slightly more
85 * abstract, Socket no longer means a tcp socket (it could mean
86 * an ssl socket). So now we must use Actual_Socket when we know
87 * we are talking about a tcp socket.
88 */
89 typedef struct Socket_tag *Actual_Socket;
90
91 struct SockAddr_tag {
92 char *error;
93 /*
94 * Which address family this address belongs to. AF_INET for
95 * IPv4; AF_INET6 for IPv6; AF_UNSPEC indicates that name
96 * resolution has not been done and a simple host name is held
97 * in this SockAddr structure.
98 */
99 int family;
100 unsigned long address; /* Address IPv4 style. */
101 #ifdef IPV6
102 struct addrinfo *ai; /* Address IPv6 style. */
103 #endif
104 char hostname[512]; /* Store an unresolved host name. */
105 };
106
107 static tree234 *sktree;
108
109 static int cmpfortree(void *av, void *bv)
110 {
111 Actual_Socket a = (Actual_Socket) av, b = (Actual_Socket) bv;
112 unsigned long as = (unsigned long) a->s, bs = (unsigned long) b->s;
113 if (as < bs)
114 return -1;
115 if (as > bs)
116 return +1;
117 return 0;
118 }
119
120 static int cmpforsearch(void *av, void *bv)
121 {
122 Actual_Socket b = (Actual_Socket) bv;
123 unsigned long as = (unsigned long) av, bs = (unsigned long) b->s;
124 if (as < bs)
125 return -1;
126 if (as > bs)
127 return +1;
128 return 0;
129 }
130
131 void sk_init(void)
132 {
133 sktree = newtree234(cmpfortree);
134 }
135
136 void sk_cleanup(void)
137 {
138 Actual_Socket s;
139 int i;
140
141 if (sktree) {
142 for (i = 0; (s = index234(sktree, i)) != NULL; i++) {
143 closesocket(s->s);
144 }
145 }
146 }
147
148 char *winsock_error_string(int error)
149 {
150 switch (error) {
151 case WSAEACCES:
152 return "Network error: Permission denied";
153 case WSAEADDRINUSE:
154 return "Network error: Address already in use";
155 case WSAEADDRNOTAVAIL:
156 return "Network error: Cannot assign requested address";
157 case WSAEAFNOSUPPORT:
158 return
159 "Network error: Address family not supported by protocol family";
160 case WSAEALREADY:
161 return "Network error: Operation already in progress";
162 case WSAECONNABORTED:
163 return "Network error: Software caused connection abort";
164 case WSAECONNREFUSED:
165 return "Network error: Connection refused";
166 case WSAECONNRESET:
167 return "Network error: Connection reset by peer";
168 case WSAEDESTADDRREQ:
169 return "Network error: Destination address required";
170 case WSAEFAULT:
171 return "Network error: Bad address";
172 case WSAEHOSTDOWN:
173 return "Network error: Host is down";
174 case WSAEHOSTUNREACH:
175 return "Network error: No route to host";
176 case WSAEINPROGRESS:
177 return "Network error: Operation now in progress";
178 case WSAEINTR:
179 return "Network error: Interrupted function call";
180 case WSAEINVAL:
181 return "Network error: Invalid argument";
182 case WSAEISCONN:
183 return "Network error: Socket is already connected";
184 case WSAEMFILE:
185 return "Network error: Too many open files";
186 case WSAEMSGSIZE:
187 return "Network error: Message too long";
188 case WSAENETDOWN:
189 return "Network error: Network is down";
190 case WSAENETRESET:
191 return "Network error: Network dropped connection on reset";
192 case WSAENETUNREACH:
193 return "Network error: Network is unreachable";
194 case WSAENOBUFS:
195 return "Network error: No buffer space available";
196 case WSAENOPROTOOPT:
197 return "Network error: Bad protocol option";
198 case WSAENOTCONN:
199 return "Network error: Socket is not connected";
200 case WSAENOTSOCK:
201 return "Network error: Socket operation on non-socket";
202 case WSAEOPNOTSUPP:
203 return "Network error: Operation not supported";
204 case WSAEPFNOSUPPORT:
205 return "Network error: Protocol family not supported";
206 case WSAEPROCLIM:
207 return "Network error: Too many processes";
208 case WSAEPROTONOSUPPORT:
209 return "Network error: Protocol not supported";
210 case WSAEPROTOTYPE:
211 return "Network error: Protocol wrong type for socket";
212 case WSAESHUTDOWN:
213 return "Network error: Cannot send after socket shutdown";
214 case WSAESOCKTNOSUPPORT:
215 return "Network error: Socket type not supported";
216 case WSAETIMEDOUT:
217 return "Network error: Connection timed out";
218 case WSAEWOULDBLOCK:
219 return "Network error: Resource temporarily unavailable";
220 case WSAEDISCON:
221 return "Network error: Graceful shutdown in progress";
222 default:
223 return "Unknown network error";
224 }
225 }
226
227 SockAddr sk_namelookup(const char *host, char **canonicalname)
228 {
229 SockAddr ret = snew(struct SockAddr_tag);
230 unsigned long a;
231 struct hostent *h = NULL;
232 char realhost[8192];
233
234 /* Clear the structure and default to IPv4. */
235 memset(ret, 0, sizeof(struct SockAddr_tag));
236 ret->family = 0; /* We set this one when we have resolved the host. */
237 *realhost = '\0';
238
239 if ((a = inet_addr(host)) == (unsigned long) INADDR_NONE) {
240 #ifdef IPV6
241
242 /* Try to get the getaddrinfo() function from wship6.dll */
243 /* This way one doesn't need to have IPv6 dll's to use PuTTY and
244 * it will fallback to IPv4. */
245 typedef int (CALLBACK * FGETADDRINFO) (const char *nodename,
246 const char *servname,
247 const struct addrinfo *
248 hints,
249 struct addrinfo ** res);
250 FGETADDRINFO fGetAddrInfo = NULL;
251
252 HINSTANCE dllWSHIP6 = LoadLibrary("wship6.dll");
253 if (dllWSHIP6)
254 fGetAddrInfo = (FGETADDRINFO) GetProcAddress(dllWSHIP6,
255 "getaddrinfo");
256
257 /*
258 * Use fGetAddrInfo when it's available (which usually also
259 * means IPv6 is installed...)
260 */
261 if (fGetAddrInfo) {
262 /*debug(("Resolving \"%s\" with getaddrinfo() (IPv4+IPv6 capable)...\n", host)); */
263 if (fGetAddrInfo(host, NULL, NULL, &ret->ai) == 0)
264 ret->family = ret->ai->ai_family;
265 } else
266 #endif
267 {
268 /*
269 * Otherwise use the IPv4-only gethostbyname...
270 * (NOTE: we don't use gethostbyname as a
271 * fallback!)
272 */
273 if (ret->family == 0) {
274 /*debug(("Resolving \"%s\" with gethostbyname() (IPv4 only)...\n", host)); */
275 if ( (h = gethostbyname(host)) )
276 ret->family = AF_INET;
277 }
278 }
279 /*debug(("Done resolving...(family is %d) AF_INET = %d, AF_INET6 = %d\n", ret->family, AF_INET, AF_INET6)); */
280
281 if (ret->family == 0) {
282 DWORD err = WSAGetLastError();
283 ret->error = (err == WSAENETDOWN ? "Network is down" :
284 err ==
285 WSAHOST_NOT_FOUND ? "Host does not exist" : err
286 == WSATRY_AGAIN ? "Host not found" :
287 #ifdef IPV6
288 fGetAddrInfo ? "getaddrinfo: unknown error" :
289 #endif
290 "gethostbyname: unknown error");
291 #ifdef DEBUG
292 {
293 LPVOID lpMsgBuf;
294 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
295 FORMAT_MESSAGE_FROM_SYSTEM |
296 FORMAT_MESSAGE_IGNORE_INSERTS, NULL, err,
297 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
298 (LPTSTR) & lpMsgBuf, 0, NULL);
299 /*debug(("Error %ld: %s (h=%lx)\n", err, lpMsgBuf, h)); */
300 /* Free the buffer. */
301 LocalFree(lpMsgBuf);
302 }
303 #endif
304 } else {
305 ret->error = NULL;
306
307 #ifdef IPV6
308 /* If we got an address info use that... */
309 if (ret->ai) {
310 typedef int (CALLBACK * FGETNAMEINFO)
311 (const struct sockaddr FAR * sa, socklen_t salen,
312 char FAR * host, size_t hostlen, char FAR * serv,
313 size_t servlen, int flags);
314 FGETNAMEINFO fGetNameInfo = NULL;
315
316 /* Are we in IPv4 fallback mode? */
317 /* We put the IPv4 address into the a variable so we can further-on use the IPv4 code... */
318 if (ret->family == AF_INET)
319 memcpy(&a,
320 (char *) &((SOCKADDR_IN *) ret->ai->
321 ai_addr)->sin_addr, sizeof(a));
322
323 /* Now let's find that canonicalname... */
324 if ((dllWSHIP6)
325 && (fGetNameInfo =
326 (FGETNAMEINFO) GetProcAddress(dllWSHIP6,
327 "getnameinfo"))) {
328 if (fGetNameInfo
329 ((struct sockaddr *) ret->ai->ai_addr,
330 ret->family ==
331 AF_INET ? sizeof(SOCKADDR_IN) :
332 sizeof(SOCKADDR_IN6), realhost,
333 sizeof(realhost), NULL, 0, 0) != 0) {
334 strncpy(realhost, host, sizeof(realhost));
335 }
336 }
337 }
338 /* We used the IPv4-only gethostbyname()... */
339 else
340 #endif
341 {
342 memcpy(&a, h->h_addr, sizeof(a));
343 /* This way we are always sure the h->h_name is valid :) */
344 strncpy(realhost, h->h_name, sizeof(realhost));
345 }
346 }
347 #ifdef IPV6
348 FreeLibrary(dllWSHIP6);
349 #endif
350 } else {
351 /*
352 * This must be a numeric IPv4 address because it caused a
353 * success return from inet_addr.
354 */
355 ret->family = AF_INET;
356 strncpy(realhost, host, sizeof(realhost));
357 }
358 ret->address = ntohl(a);
359 realhost[lenof(realhost)-1] = '\0';
360 *canonicalname = snewn(1+strlen(realhost), char);
361 strcpy(*canonicalname, realhost);
362 return ret;
363 }
364
365 SockAddr sk_nonamelookup(const char *host)
366 {
367 SockAddr ret = snew(struct SockAddr_tag);
368 ret->error = NULL;
369 ret->family = AF_UNSPEC;
370 strncpy(ret->hostname, host, lenof(ret->hostname));
371 ret->hostname[lenof(ret->hostname)-1] = '\0';
372 return ret;
373 }
374
375 void sk_getaddr(SockAddr addr, char *buf, int buflen)
376 {
377 #ifdef IPV6
378 if (addr->family == AF_INET6) {
379 FIXME; /* I don't know how to get a text form of an IPv6 address. */
380 } else
381 #endif
382 if (addr->family == AF_INET) {
383 struct in_addr a;
384 a.s_addr = htonl(addr->address);
385 strncpy(buf, inet_ntoa(a), buflen);
386 buf[buflen-1] = '\0';
387 } else {
388 assert(addr->family == AF_UNSPEC);
389 strncpy(buf, addr->hostname, buflen);
390 buf[buflen-1] = '\0';
391 }
392 }
393
394 int sk_hostname_is_local(char *name)
395 {
396 return !strcmp(name, "localhost");
397 }
398
399 int sk_address_is_local(SockAddr addr)
400 {
401 #ifdef IPV6
402 if (addr->family == AF_INET6) {
403 FIXME; /* someone who can compile for IPV6 had better do this bit */
404 } else
405 #endif
406 if (addr->family == AF_INET) {
407 struct in_addr a;
408 a.s_addr = htonl(addr->address);
409 return ipv4_is_loopback(a);
410 } else {
411 assert(addr->family == AF_UNSPEC);
412 return 0; /* we don't know; assume not */
413 }
414 }
415
416 int sk_addrtype(SockAddr addr)
417 {
418 return (addr->family == AF_INET ? ADDRTYPE_IPV4 :
419 #ifdef IPV6
420 addr->family == AF_INET6 ? ADDRTYPE_IPV6 :
421 #endif
422 ADDRTYPE_NAME);
423 }
424
425 void sk_addrcopy(SockAddr addr, char *buf)
426 {
427 assert(addr->family != AF_UNSPEC);
428 #ifdef IPV6
429 if (addr->family == AF_INET6) {
430 memcpy(buf, (char*) addr->ai, 16);
431 } else
432 #endif
433 if (addr->family == AF_INET) {
434 struct in_addr a;
435 a.s_addr = htonl(addr->address);
436 memcpy(buf, (char*) &a.s_addr, 4);
437 }
438 }
439
440 void sk_addr_free(SockAddr addr)
441 {
442 sfree(addr);
443 }
444
445 static Plug sk_tcp_plug(Socket sock, Plug p)
446 {
447 Actual_Socket s = (Actual_Socket) sock;
448 Plug ret = s->plug;
449 if (p)
450 s->plug = p;
451 return ret;
452 }
453
454 static void sk_tcp_flush(Socket s)
455 {
456 /*
457 * We send data to the socket as soon as we can anyway,
458 * so we don't need to do anything here. :-)
459 */
460 }
461
462 static void sk_tcp_close(Socket s);
463 static int sk_tcp_write(Socket s, const char *data, int len);
464 static int sk_tcp_write_oob(Socket s, const char *data, int len);
465 static void sk_tcp_set_private_ptr(Socket s, void *ptr);
466 static void *sk_tcp_get_private_ptr(Socket s);
467 static void sk_tcp_set_frozen(Socket s, int is_frozen);
468 static char *sk_tcp_socket_error(Socket s);
469
470 extern char *do_select(SOCKET skt, int startup);
471
472 Socket sk_register(void *sock, Plug plug)
473 {
474 static const struct socket_function_table fn_table = {
475 sk_tcp_plug,
476 sk_tcp_close,
477 sk_tcp_write,
478 sk_tcp_write_oob,
479 sk_tcp_flush,
480 sk_tcp_set_private_ptr,
481 sk_tcp_get_private_ptr,
482 sk_tcp_set_frozen,
483 sk_tcp_socket_error
484 };
485
486 DWORD err;
487 char *errstr;
488 Actual_Socket ret;
489
490 /*
491 * Create Socket structure.
492 */
493 ret = snew(struct Socket_tag);
494 ret->fn = &fn_table;
495 ret->error = NULL;
496 ret->plug = plug;
497 bufchain_init(&ret->output_data);
498 ret->writable = 1; /* to start with */
499 ret->sending_oob = 0;
500 ret->frozen = 1;
501 ret->frozen_readable = 0;
502 ret->localhost_only = 0; /* unused, but best init anyway */
503 ret->pending_error = 0;
504
505 ret->s = (SOCKET)sock;
506
507 if (ret->s == INVALID_SOCKET) {
508 err = WSAGetLastError();
509 ret->error = winsock_error_string(err);
510 return (Socket) ret;
511 }
512
513 ret->oobinline = 0;
514
515 /* Set up a select mechanism. This could be an AsyncSelect on a
516 * window, or an EventSelect on an event object. */
517 errstr = do_select(ret->s, 1);
518 if (errstr) {
519 ret->error = errstr;
520 return (Socket) ret;
521 }
522
523 add234(sktree, ret);
524
525 return (Socket) ret;
526 }
527
528 Socket sk_new(SockAddr addr, int port, int privport, int oobinline,
529 int nodelay, Plug plug)
530 {
531 static const struct socket_function_table fn_table = {
532 sk_tcp_plug,
533 sk_tcp_close,
534 sk_tcp_write,
535 sk_tcp_write_oob,
536 sk_tcp_flush,
537 sk_tcp_set_private_ptr,
538 sk_tcp_get_private_ptr,
539 sk_tcp_set_frozen,
540 sk_tcp_socket_error
541 };
542
543 SOCKET s;
544 #ifdef IPV6
545 SOCKADDR_IN6 a6;
546 #endif
547 SOCKADDR_IN a;
548 DWORD err;
549 char *errstr;
550 Actual_Socket ret;
551 short localport;
552
553 /*
554 * Create Socket structure.
555 */
556 ret = snew(struct Socket_tag);
557 ret->fn = &fn_table;
558 ret->error = NULL;
559 ret->plug = plug;
560 bufchain_init(&ret->output_data);
561 ret->connected = 0; /* to start with */
562 ret->writable = 0; /* to start with */
563 ret->sending_oob = 0;
564 ret->frozen = 0;
565 ret->frozen_readable = 0;
566 ret->localhost_only = 0; /* unused, but best init anyway */
567 ret->pending_error = 0;
568
569 /*
570 * Open socket.
571 */
572 assert(addr->family != AF_UNSPEC);
573 s = socket(addr->family, SOCK_STREAM, 0);
574 ret->s = s;
575
576 if (s == INVALID_SOCKET) {
577 err = WSAGetLastError();
578 ret->error = winsock_error_string(err);
579 return (Socket) ret;
580 }
581
582 ret->oobinline = oobinline;
583 if (oobinline) {
584 BOOL b = TRUE;
585 setsockopt(s, SOL_SOCKET, SO_OOBINLINE, (void *) &b, sizeof(b));
586 }
587
588 if (nodelay) {
589 BOOL b = TRUE;
590 setsockopt(s, IPPROTO_TCP, TCP_NODELAY, (void *) &b, sizeof(b));
591 }
592
593 /*
594 * Bind to local address.
595 */
596 if (privport)
597 localport = 1023; /* count from 1023 downwards */
598 else
599 localport = 0; /* just use port 0 (ie winsock picks) */
600
601 /* Loop round trying to bind */
602 while (1) {
603 int retcode;
604
605 #ifdef IPV6
606 if (addr->family == AF_INET6) {
607 memset(&a6, 0, sizeof(a6));
608 a6.sin6_family = AF_INET6;
609 /*a6.sin6_addr = in6addr_any; *//* == 0 */
610 a6.sin6_port = htons(localport);
611 } else
612 #endif
613 {
614 a.sin_family = AF_INET;
615 a.sin_addr.s_addr = htonl(INADDR_ANY);
616 a.sin_port = htons(localport);
617 }
618 #ifdef IPV6
619 retcode = bind(s, (addr->family == AF_INET6 ?
620 (struct sockaddr *) &a6 :
621 (struct sockaddr *) &a),
622 (addr->family ==
623 AF_INET6 ? sizeof(a6) : sizeof(a)));
624 #else
625 retcode = bind(s, (struct sockaddr *) &a, sizeof(a));
626 #endif
627 if (retcode != SOCKET_ERROR) {
628 err = 0;
629 break; /* done */
630 } else {
631 err = WSAGetLastError();
632 if (err != WSAEADDRINUSE) /* failed, for a bad reason */
633 break;
634 }
635
636 if (localport == 0)
637 break; /* we're only looping once */
638 localport--;
639 if (localport == 0)
640 break; /* we might have got to the end */
641 }
642
643 if (err) {
644 ret->error = winsock_error_string(err);
645 return (Socket) ret;
646 }
647
648 /*
649 * Connect to remote address.
650 */
651 #ifdef IPV6
652 if (addr->family == AF_INET6) {
653 memset(&a, 0, sizeof(a));
654 a6.sin6_family = AF_INET6;
655 a6.sin6_port = htons((short) port);
656 a6.sin6_addr =
657 ((struct sockaddr_in6 *) addr->ai->ai_addr)->sin6_addr;
658 } else
659 #endif
660 {
661 a.sin_family = AF_INET;
662 a.sin_addr.s_addr = htonl(addr->address);
663 a.sin_port = htons((short) port);
664 }
665
666 /* Set up a select mechanism. This could be an AsyncSelect on a
667 * window, or an EventSelect on an event object. */
668 errstr = do_select(s, 1);
669 if (errstr) {
670 ret->error = errstr;
671 return (Socket) ret;
672 }
673
674 if ((
675 #ifdef IPV6
676 connect(s, ((addr->family == AF_INET6) ?
677 (struct sockaddr *) &a6 : (struct sockaddr *) &a),
678 (addr->family == AF_INET6) ? sizeof(a6) : sizeof(a))
679 #else
680 connect(s, (struct sockaddr *) &a, sizeof(a))
681 #endif
682 ) == SOCKET_ERROR) {
683 err = WSAGetLastError();
684 /*
685 * We expect a potential EWOULDBLOCK here, because the
686 * chances are the front end has done a select for
687 * FD_CONNECT, so that connect() will complete
688 * asynchronously.
689 */
690 if ( err != WSAEWOULDBLOCK ) {
691 ret->error = winsock_error_string(err);
692 return (Socket) ret;
693 }
694 } else {
695 /*
696 * If we _don't_ get EWOULDBLOCK, the connect has completed
697 * and we should set the socket as writable.
698 */
699 ret->writable = 1;
700 }
701
702 add234(sktree, ret);
703
704 return (Socket) ret;
705 }
706
707 Socket sk_newlistener(char *srcaddr, int port, Plug plug, int local_host_only)
708 {
709 static const struct socket_function_table fn_table = {
710 sk_tcp_plug,
711 sk_tcp_close,
712 sk_tcp_write,
713 sk_tcp_write_oob,
714 sk_tcp_flush,
715 sk_tcp_set_private_ptr,
716 sk_tcp_get_private_ptr,
717 sk_tcp_set_frozen,
718 sk_tcp_socket_error
719 };
720
721 SOCKET s;
722 #ifdef IPV6
723 SOCKADDR_IN6 a6;
724 #endif
725 SOCKADDR_IN a;
726 DWORD err;
727 char *errstr;
728 Actual_Socket ret;
729 int retcode;
730 int on = 1;
731
732 /*
733 * Create Socket structure.
734 */
735 ret = snew(struct Socket_tag);
736 ret->fn = &fn_table;
737 ret->error = NULL;
738 ret->plug = plug;
739 bufchain_init(&ret->output_data);
740 ret->writable = 0; /* to start with */
741 ret->sending_oob = 0;
742 ret->frozen = 0;
743 ret->frozen_readable = 0;
744 ret->localhost_only = local_host_only;
745 ret->pending_error = 0;
746
747 /*
748 * Open socket.
749 */
750 s = socket(AF_INET, SOCK_STREAM, 0);
751 ret->s = s;
752
753 if (s == INVALID_SOCKET) {
754 err = WSAGetLastError();
755 ret->error = winsock_error_string(err);
756 return (Socket) ret;
757 }
758
759 ret->oobinline = 0;
760
761 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (const char *)&on, sizeof(on));
762
763 #ifdef IPV6
764 if (addr->family == AF_INET6) {
765 memset(&a6, 0, sizeof(a6));
766 a6.sin6_family = AF_INET6;
767 /* FIXME: srcaddr is ignored for IPv6, because I (SGT) don't
768 * know how to do it. :-) */
769 if (local_host_only)
770 a6.sin6_addr = in6addr_loopback;
771 else
772 a6.sin6_addr = in6addr_any;
773 a6.sin6_port = htons(port);
774 } else
775 #endif
776 {
777 int got_addr = 0;
778 a.sin_family = AF_INET;
779
780 /*
781 * Bind to source address. First try an explicitly
782 * specified one...
783 */
784 if (srcaddr) {
785 a.sin_addr.s_addr = inet_addr(srcaddr);
786 if (a.sin_addr.s_addr != INADDR_NONE) {
787 /* Override localhost_only with specified listen addr. */
788 ret->localhost_only = ipv4_is_loopback(a.sin_addr);
789 got_addr = 1;
790 }
791 }
792
793 /*
794 * ... and failing that, go with one of the standard ones.
795 */
796 if (!got_addr) {
797 if (local_host_only)
798 a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
799 else
800 a.sin_addr.s_addr = htonl(INADDR_ANY);
801 }
802
803 a.sin_port = htons((short)port);
804 }
805 #ifdef IPV6
806 retcode = bind(s, (addr->family == AF_INET6 ?
807 (struct sockaddr *) &a6 :
808 (struct sockaddr *) &a),
809 (addr->family ==
810 AF_INET6 ? sizeof(a6) : sizeof(a)));
811 #else
812 retcode = bind(s, (struct sockaddr *) &a, sizeof(a));
813 #endif
814 if (retcode != SOCKET_ERROR) {
815 err = 0;
816 } else {
817 err = WSAGetLastError();
818 }
819
820 if (err) {
821 ret->error = winsock_error_string(err);
822 return (Socket) ret;
823 }
824
825
826 if (listen(s, SOMAXCONN) == SOCKET_ERROR) {
827 closesocket(s);
828 ret->error = winsock_error_string(err);
829 return (Socket) ret;
830 }
831
832 /* Set up a select mechanism. This could be an AsyncSelect on a
833 * window, or an EventSelect on an event object. */
834 errstr = do_select(s, 1);
835 if (errstr) {
836 ret->error = errstr;
837 return (Socket) ret;
838 }
839
840 add234(sktree, ret);
841
842 return (Socket) ret;
843 }
844
845 static void sk_tcp_close(Socket sock)
846 {
847 extern char *do_select(SOCKET skt, int startup);
848 Actual_Socket s = (Actual_Socket) sock;
849
850 del234(sktree, s);
851 do_select(s->s, 0);
852 closesocket(s->s);
853 sfree(s);
854 }
855
856 /*
857 * The function which tries to send on a socket once it's deemed
858 * writable.
859 */
860 void try_send(Actual_Socket s)
861 {
862 while (s->sending_oob || bufchain_size(&s->output_data) > 0) {
863 int nsent;
864 DWORD err;
865 void *data;
866 int len, urgentflag;
867
868 if (s->sending_oob) {
869 urgentflag = MSG_OOB;
870 len = s->sending_oob;
871 data = &s->oobdata;
872 } else {
873 urgentflag = 0;
874 bufchain_prefix(&s->output_data, &data, &len);
875 }
876 nsent = send(s->s, data, len, urgentflag);
877 noise_ultralight(nsent);
878 if (nsent <= 0) {
879 err = (nsent < 0 ? WSAGetLastError() : 0);
880 if ((err < WSABASEERR && nsent < 0) || err == WSAEWOULDBLOCK) {
881 /*
882 * Perfectly normal: we've sent all we can for the moment.
883 *
884 * (Some WinSock send() implementations can return
885 * <0 but leave no sensible error indication -
886 * WSAGetLastError() is called but returns zero or
887 * a small number - so we check that case and treat
888 * it just like WSAEWOULDBLOCK.)
889 */
890 s->writable = FALSE;
891 return;
892 } else if (nsent == 0 ||
893 err == WSAECONNABORTED || err == WSAECONNRESET) {
894 /*
895 * If send() returns CONNABORTED or CONNRESET, we
896 * unfortunately can't just call plug_closing(),
897 * because it's quite likely that we're currently
898 * _in_ a call from the code we'd be calling back
899 * to, so we'd have to make half the SSH code
900 * reentrant. Instead we flag a pending error on
901 * the socket, to be dealt with (by calling
902 * plug_closing()) at some suitable future moment.
903 */
904 s->pending_error = err;
905 return;
906 } else {
907 /* We're inside the Windows frontend here, so we know
908 * that the frontend handle is unnecessary. */
909 logevent(NULL, winsock_error_string(err));
910 fatalbox("%s", winsock_error_string(err));
911 }
912 } else {
913 if (s->sending_oob) {
914 if (nsent < len) {
915 memmove(s->oobdata, s->oobdata+nsent, len-nsent);
916 s->sending_oob = len - nsent;
917 } else {
918 s->sending_oob = 0;
919 }
920 } else {
921 bufchain_consume(&s->output_data, nsent);
922 }
923 }
924 }
925 }
926
927 static int sk_tcp_write(Socket sock, const char *buf, int len)
928 {
929 Actual_Socket s = (Actual_Socket) sock;
930
931 /*
932 * Add the data to the buffer list on the socket.
933 */
934 bufchain_add(&s->output_data, buf, len);
935
936 /*
937 * Now try sending from the start of the buffer list.
938 */
939 if (s->writable)
940 try_send(s);
941
942 return bufchain_size(&s->output_data);
943 }
944
945 static int sk_tcp_write_oob(Socket sock, const char *buf, int len)
946 {
947 Actual_Socket s = (Actual_Socket) sock;
948
949 /*
950 * Replace the buffer list on the socket with the data.
951 */
952 bufchain_clear(&s->output_data);
953 assert(len <= sizeof(s->oobdata));
954 memcpy(s->oobdata, buf, len);
955 s->sending_oob = len;
956
957 /*
958 * Now try sending from the start of the buffer list.
959 */
960 if (s->writable)
961 try_send(s);
962
963 return s->sending_oob;
964 }
965
966 int select_result(WPARAM wParam, LPARAM lParam)
967 {
968 int ret, open;
969 DWORD err;
970 char buf[20480]; /* nice big buffer for plenty of speed */
971 Actual_Socket s;
972 u_long atmark;
973
974 /* wParam is the socket itself */
975
976 if (wParam == 0)
977 return 1; /* boggle */
978
979 s = find234(sktree, (void *) wParam, cmpforsearch);
980 if (!s)
981 return 1; /* boggle */
982
983 if ((err = WSAGETSELECTERROR(lParam)) != 0) {
984 /*
985 * An error has occurred on this socket. Pass it to the
986 * plug.
987 */
988 return plug_closing(s->plug, winsock_error_string(err), err, 0);
989 }
990
991 noise_ultralight(lParam);
992
993 switch (WSAGETSELECTEVENT(lParam)) {
994 case FD_CONNECT:
995 s->connected = s->writable = 1;
996 break;
997 case FD_READ:
998 /* In the case the socket is still frozen, we don't even bother */
999 if (s->frozen) {
1000 s->frozen_readable = 1;
1001 break;
1002 }
1003
1004 /*
1005 * We have received data on the socket. For an oobinline
1006 * socket, this might be data _before_ an urgent pointer,
1007 * in which case we send it to the back end with type==1
1008 * (data prior to urgent).
1009 */
1010 if (s->oobinline) {
1011 atmark = 1;
1012 ioctlsocket(s->s, SIOCATMARK, &atmark);
1013 /*
1014 * Avoid checking the return value from ioctlsocket(),
1015 * on the grounds that some WinSock wrappers don't
1016 * support it. If it does nothing, we get atmark==1,
1017 * which is equivalent to `no OOB pending', so the
1018 * effect will be to non-OOB-ify any OOB data.
1019 */
1020 } else
1021 atmark = 1;
1022
1023 ret = recv(s->s, buf, sizeof(buf), 0);
1024 noise_ultralight(ret);
1025 if (ret < 0) {
1026 err = WSAGetLastError();
1027 if (err == WSAEWOULDBLOCK) {
1028 break;
1029 }
1030 }
1031 if (ret < 0) {
1032 return plug_closing(s->plug, winsock_error_string(err), err,
1033 0);
1034 } else if (0 == ret) {
1035 return plug_closing(s->plug, NULL, 0, 0);
1036 } else {
1037 return plug_receive(s->plug, atmark ? 0 : 1, buf, ret);
1038 }
1039 break;
1040 case FD_OOB:
1041 /*
1042 * This will only happen on a non-oobinline socket. It
1043 * indicates that we can immediately perform an OOB read
1044 * and get back OOB data, which we will send to the back
1045 * end with type==2 (urgent data).
1046 */
1047 ret = recv(s->s, buf, sizeof(buf), MSG_OOB);
1048 noise_ultralight(ret);
1049 if (ret <= 0) {
1050 char *str = (ret == 0 ? "Internal networking trouble" :
1051 winsock_error_string(WSAGetLastError()));
1052 /* We're inside the Windows frontend here, so we know
1053 * that the frontend handle is unnecessary. */
1054 logevent(NULL, str);
1055 fatalbox("%s", str);
1056 } else {
1057 return plug_receive(s->plug, 2, buf, ret);
1058 }
1059 break;
1060 case FD_WRITE:
1061 {
1062 int bufsize_before, bufsize_after;
1063 s->writable = 1;
1064 bufsize_before = s->sending_oob + bufchain_size(&s->output_data);
1065 try_send(s);
1066 bufsize_after = s->sending_oob + bufchain_size(&s->output_data);
1067 if (bufsize_after < bufsize_before)
1068 plug_sent(s->plug, bufsize_after);
1069 }
1070 break;
1071 case FD_CLOSE:
1072 /* Signal a close on the socket. First read any outstanding data. */
1073 open = 1;
1074 do {
1075 ret = recv(s->s, buf, sizeof(buf), 0);
1076 if (ret < 0) {
1077 err = WSAGetLastError();
1078 if (err == WSAEWOULDBLOCK)
1079 break;
1080 return plug_closing(s->plug, winsock_error_string(err),
1081 err, 0);
1082 } else {
1083 if (ret)
1084 open &= plug_receive(s->plug, 0, buf, ret);
1085 else
1086 open &= plug_closing(s->plug, NULL, 0, 0);
1087 }
1088 } while (ret > 0);
1089 return open;
1090 case FD_ACCEPT:
1091 {
1092 struct sockaddr_in isa;
1093 int addrlen = sizeof(struct sockaddr_in);
1094 SOCKET t; /* socket of connection */
1095
1096 memset(&isa, 0, sizeof(struct sockaddr_in));
1097 err = 0;
1098 t = accept(s->s,(struct sockaddr *)&isa,&addrlen);
1099 if (t == INVALID_SOCKET)
1100 {
1101 err = WSAGetLastError();
1102 if (err == WSATRY_AGAIN)
1103 break;
1104 }
1105
1106 if (s->localhost_only && !ipv4_is_loopback(isa.sin_addr)) {
1107 closesocket(t); /* dodgy WinSock let nonlocal through */
1108 } else if (plug_accepting(s->plug, (void*)t)) {
1109 closesocket(t); /* denied or error */
1110 }
1111 }
1112 }
1113
1114 return 1;
1115 }
1116
1117 /*
1118 * Deal with socket errors detected in try_send().
1119 */
1120 void net_pending_errors(void)
1121 {
1122 int i;
1123 Actual_Socket s;
1124
1125 /*
1126 * This might be a fiddly business, because it's just possible
1127 * that handling a pending error on one socket might cause
1128 * others to be closed. (I can't think of any reason this might
1129 * happen in current SSH implementation, but to maintain
1130 * generality of this network layer I'll assume the worst.)
1131 *
1132 * So what we'll do is search the socket list for _one_ socket
1133 * with a pending error, and then handle it, and then search
1134 * the list again _from the beginning_. Repeat until we make a
1135 * pass with no socket errors present. That way we are
1136 * protected against the socket list changing under our feet.
1137 */
1138
1139 do {
1140 for (i = 0; (s = index234(sktree, i)) != NULL; i++) {
1141 if (s->pending_error) {
1142 /*
1143 * An error has occurred on this socket. Pass it to the
1144 * plug.
1145 */
1146 plug_closing(s->plug,
1147 winsock_error_string(s->pending_error),
1148 s->pending_error, 0);
1149 break;
1150 }
1151 }
1152 } while (s);
1153 }
1154
1155 /*
1156 * Each socket abstraction contains a `void *' private field in
1157 * which the client can keep state.
1158 */
1159 static void sk_tcp_set_private_ptr(Socket sock, void *ptr)
1160 {
1161 Actual_Socket s = (Actual_Socket) sock;
1162 s->private_ptr = ptr;
1163 }
1164
1165 static void *sk_tcp_get_private_ptr(Socket sock)
1166 {
1167 Actual_Socket s = (Actual_Socket) sock;
1168 return s->private_ptr;
1169 }
1170
1171 /*
1172 * Special error values are returned from sk_namelookup and sk_new
1173 * if there's a problem. These functions extract an error message,
1174 * or return NULL if there's no problem.
1175 */
1176 char *sk_addr_error(SockAddr addr)
1177 {
1178 return addr->error;
1179 }
1180 static char *sk_tcp_socket_error(Socket sock)
1181 {
1182 Actual_Socket s = (Actual_Socket) sock;
1183 return s->error;
1184 }
1185
1186 static void sk_tcp_set_frozen(Socket sock, int is_frozen)
1187 {
1188 Actual_Socket s = (Actual_Socket) sock;
1189 if (s->frozen == is_frozen)
1190 return;
1191 s->frozen = is_frozen;
1192 if (!is_frozen && s->frozen_readable) {
1193 char c;
1194 recv(s->s, &c, 1, MSG_PEEK);
1195 }
1196 s->frozen_readable = 0;
1197 }
1198
1199 /*
1200 * For Plink: enumerate all sockets currently active.
1201 */
1202 SOCKET first_socket(int *state)
1203 {
1204 Actual_Socket s;
1205 *state = 0;
1206 s = index234(sktree, (*state)++);
1207 return s ? s->s : INVALID_SOCKET;
1208 }
1209
1210 SOCKET next_socket(int *state)
1211 {
1212 Actual_Socket s = index234(sktree, (*state)++);
1213 return s ? s->s : INVALID_SOCKET;
1214 }
1215
1216 int net_service_lookup(char *service)
1217 {
1218 struct servent *se;
1219 se = getservbyname(service, NULL);
1220 if (se != NULL)
1221 return ntohs(se->s_port);
1222 else
1223 return 0;
1224 }