Control of 'addr' is now handed over to {platform_,}new_connection() and
[u/mdw/putty] / winnet.c
CommitLineData
2f75bae1 1/*
2 * Windows networking abstraction.
c4d8e107 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 *
2f75bae1 32 */
33
c4d8e107 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
2f75bae1 46#include <winsock.h>
c4d8e107 47#endif
48#include <windows.h>
2f75bae1 49#include <stdio.h>
49bad831 50#include <stdlib.h>
5471d09a 51#include <assert.h>
2f75bae1 52
7e78000d 53#define DEFINE_PLUG_METHOD_MACROS
2f75bae1 54#include "putty.h"
55#include "network.h"
56#include "tree234.h"
57
6ee9b735 58#define ipv4_is_loopback(addr) \
59 ((ntohl(addr.s_addr) & 0xFF000000L) == 0x7F000000L)
60
2f75bae1 61struct Socket_tag {
c85623f9 62 const struct socket_function_table *fn;
7e78000d 63 /* the above variable absolutely *must* be the first in this structure */
2f75bae1 64 char *error;
65 SOCKET s;
7e78000d 66 Plug plug;
2f75bae1 67 void *private_ptr;
5471d09a 68 bufchain output_data;
3ad9d396 69 int connected;
2f75bae1 70 int writable;
5471d09a 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 */
bc4802a1 74 int localhost_only; /* for listening sockets */
5471d09a 75 char oobdata[1];
1ad4eb6f 76 int sending_oob;
4b1e8acc 77 int oobinline;
7732d38a 78 int pending_error; /* in case send() returns error */
2f75bae1 79};
80
7e78000d 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 */
89typedef struct Socket_tag *Actual_Socket;
90
2f75bae1 91struct SockAddr_tag {
92 char *error;
b7a189f3 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 */
32874aea 99 int family;
c4d8e107 100 unsigned long address; /* Address IPv4 style. */
101#ifdef IPV6
102 struct addrinfo *ai; /* Address IPv6 style. */
103#endif
b7a189f3 104 char hostname[512]; /* Store an unresolved host name. */
2f75bae1 105};
106
2f75bae1 107static tree234 *sktree;
108
32874aea 109static 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;
2f75bae1 117 return 0;
118}
119
32874aea 120static 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;
2f75bae1 128 return 0;
129}
130
32874aea 131void sk_init(void)
132{
2f75bae1 133 sktree = newtree234(cmpfortree);
134}
135
93b581bd 136void 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
32874aea 148char *winsock_error_string(int error)
149{
e74fbad9 150 switch (error) {
32874aea 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";
e74fbad9 224 }
225}
226
e8fa8f62 227SockAddr sk_namelookup(const char *host, char **canonicalname)
c4d8e107 228{
3d88e64d 229 SockAddr ret = snew(struct SockAddr_tag);
2f75bae1 230 unsigned long a;
c4d8e107 231 struct hostent *h = NULL;
6e1ebb76 232 char realhost[8192];
2f75bae1 233
c4d8e107 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. */
6e1ebb76 237 *realhost = '\0';
c4d8e107 238
32874aea 239 if ((a = inet_addr(host)) == (unsigned long) INADDR_NONE) {
c4d8e107 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. */
32874aea 245 typedef int (CALLBACK * FGETADDRINFO) (const char *nodename,
246 const char *servname,
247 const struct addrinfo *
248 hints,
249 struct addrinfo ** res);
c4d8e107 250 FGETADDRINFO fGetAddrInfo = NULL;
251
252 HINSTANCE dllWSHIP6 = LoadLibrary("wship6.dll");
253 if (dllWSHIP6)
32874aea 254 fGetAddrInfo = (FGETADDRINFO) GetProcAddress(dllWSHIP6,
255 "getaddrinfo");
c4d8e107 256
257 /*
258 * Use fGetAddrInfo when it's available (which usually also
259 * means IPv6 is installed...)
260 */
32874aea 261 if (fGetAddrInfo) {
c4d8e107 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;
32874aea 265 } else
c4d8e107 266#endif
32874aea 267 {
c4d8e107 268 /*
269 * Otherwise use the IPv4-only gethostbyname...
270 * (NOTE: we don't use gethostbyname as a
271 * fallback!)
272 */
32874aea 273 if (ret->family == 0) {
274 /*debug(("Resolving \"%s\" with gethostbyname() (IPv4 only)...\n", host)); */
2d466ffd 275 if ( (h = gethostbyname(host)) )
32874aea 276 ret->family = AF_INET;
277 }
c4d8e107 278 }
279 /*debug(("Done resolving...(family is %d) AF_INET = %d, AF_INET6 = %d\n", ret->family, AF_INET, AF_INET6)); */
280
32874aea 281 if (ret->family == 0) {
2f75bae1 282 DWORD err = WSAGetLastError();
c4d8e107 283 ret->error = (err == WSAENETDOWN ? "Network is down" :
32874aea 284 err ==
285 WSAHOST_NOT_FOUND ? "Host does not exist" : err
286 == WSATRY_AGAIN ? "Host not found" :
c4d8e107 287#ifdef IPV6
288 fGetAddrInfo ? "getaddrinfo: unknown error" :
289#endif
290 "gethostbyname: unknown error");
291#ifdef DEBUG
292 {
293 LPVOID lpMsgBuf;
32874aea 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)); */
c4d8e107 300 /* Free the buffer. */
301 LocalFree(lpMsgBuf);
302 }
303#endif
32874aea 304 } else {
c4d8e107 305 ret->error = NULL;
306
307#ifdef IPV6
308 /* If we got an address info use that... */
32874aea 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);
c4d8e107 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)
32874aea 319 memcpy(&a,
320 (char *) &((SOCKADDR_IN *) ret->ai->
321 ai_addr)->sin_addr, sizeof(a));
c4d8e107 322
323 /* Now let's find that canonicalname... */
32874aea 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) :
6e1ebb76 332 sizeof(SOCKADDR_IN6), realhost,
333 sizeof(realhost), NULL, 0, 0) != 0) {
334 strncpy(realhost, host, sizeof(realhost));
c4d8e107 335 }
336 }
337 }
338 /* We used the IPv4-only gethostbyname()... */
339 else
c4d8e107 340#endif
32874aea 341 {
c4d8e107 342 memcpy(&a, h->h_addr, sizeof(a));
343 /* This way we are always sure the h->h_name is valid :) */
6e1ebb76 344 strncpy(realhost, h->h_name, sizeof(realhost));
c4d8e107 345 }
c4d8e107 346 }
347#ifdef IPV6
348 FreeLibrary(dllWSHIP6);
349#endif
32874aea 350 } else {
87ed061f 351 /*
352 * This must be a numeric IPv4 address because it caused a
353 * success return from inet_addr.
354 */
32874aea 355 ret->family = AF_INET;
6e1ebb76 356 strncpy(realhost, host, sizeof(realhost));
2f75bae1 357 }
358 ret->address = ntohl(a);
6e1ebb76 359 realhost[lenof(realhost)-1] = '\0';
3d88e64d 360 *canonicalname = snewn(1+strlen(realhost), char);
6e1ebb76 361 strcpy(*canonicalname, realhost);
2f75bae1 362 return ret;
363}
364
e8fa8f62 365SockAddr sk_nonamelookup(const char *host)
b7a189f3 366{
3d88e64d 367 SockAddr ret = snew(struct SockAddr_tag);
ab0873ab 368 ret->error = NULL;
b7a189f3 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
3ad9d396 375void sk_getaddr(SockAddr addr, char *buf, int buflen)
376{
377#ifdef IPV6
b7a189f3 378 if (addr->family == AF_INET6) {
379 FIXME; /* I don't know how to get a text form of an IPv6 address. */
380 } else
3ad9d396 381#endif
b7a189f3 382 if (addr->family == AF_INET) {
3ad9d396 383 struct in_addr a;
384 a.s_addr = htonl(addr->address);
385 strncpy(buf, inet_ntoa(a), buflen);
b7a189f3 386 buf[buflen-1] = '\0';
3ad9d396 387 } else {
b7a189f3 388 assert(addr->family == AF_UNSPEC);
389 strncpy(buf, addr->hostname, buflen);
390 buf[buflen-1] = '\0';
3ad9d396 391 }
3ad9d396 392}
393
b804e1e5 394int sk_hostname_is_local(char *name)
395{
396 return !strcmp(name, "localhost");
397}
398
399int sk_address_is_local(SockAddr addr)
400{
401#ifdef IPV6
b7a189f3 402 if (addr->family == AF_INET6) {
403 FIXME; /* someone who can compile for IPV6 had better do this bit */
404 } else
b804e1e5 405#endif
b7a189f3 406 if (addr->family == AF_INET) {
b804e1e5 407 struct in_addr a;
408 a.s_addr = htonl(addr->address);
409 return ipv4_is_loopback(a);
b804e1e5 410 } else {
b7a189f3 411 assert(addr->family == AF_UNSPEC);
412 return 0; /* we don't know; assume not */
b804e1e5 413 }
b804e1e5 414}
415
6971bbe7 416int sk_addrtype(SockAddr addr)
417{
b7a189f3 418 return (addr->family == AF_INET ? ADDRTYPE_IPV4 :
419#ifdef IPV6
420 addr->family == AF_INET6 ? ADDRTYPE_IPV6 :
421#endif
422 ADDRTYPE_NAME);
6971bbe7 423}
424
425void sk_addrcopy(SockAddr addr, char *buf)
426{
b7a189f3 427 assert(addr->family != AF_UNSPEC);
6971bbe7 428#ifdef IPV6
b7a189f3 429 if (addr->family == AF_INET6) {
430 memcpy(buf, (char*) addr->ai, 16);
431 } else
6971bbe7 432#endif
b7a189f3 433 if (addr->family == AF_INET) {
6971bbe7 434 struct in_addr a;
435 a.s_addr = htonl(addr->address);
96d9eb89 436 memcpy(buf, (char*) &a.s_addr, 4);
6971bbe7 437 }
6971bbe7 438}
439
32874aea 440void sk_addr_free(SockAddr addr)
441{
2f75bae1 442 sfree(addr);
443}
444
32874aea 445static Plug sk_tcp_plug(Socket sock, Plug p)
446{
7e78000d 447 Actual_Socket s = (Actual_Socket) sock;
448 Plug ret = s->plug;
32874aea 449 if (p)
450 s->plug = p;
7e78000d 451 return ret;
452}
453
32874aea 454static void sk_tcp_flush(Socket s)
455{
7e78000d 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
2d466ffd 462static void sk_tcp_close(Socket s);
e0e7dff8 463static int sk_tcp_write(Socket s, const char *data, int len);
464static int sk_tcp_write_oob(Socket s, const char *data, int len);
8eebd221 465static void sk_tcp_set_private_ptr(Socket s, void *ptr);
466static void *sk_tcp_get_private_ptr(Socket s);
467static void sk_tcp_set_frozen(Socket s, int is_frozen);
cbe2d68f 468static const char *sk_tcp_socket_error(Socket s);
7e78000d 469
d74d141c 470extern char *do_select(SOCKET skt, int startup);
471
472Socket sk_register(void *sock, Plug plug)
473{
c85623f9 474 static const struct socket_function_table fn_table = {
d74d141c 475 sk_tcp_plug,
476 sk_tcp_close,
477 sk_tcp_write,
478 sk_tcp_write_oob,
479 sk_tcp_flush,
8eebd221 480 sk_tcp_set_private_ptr,
481 sk_tcp_get_private_ptr,
482 sk_tcp_set_frozen,
d74d141c 483 sk_tcp_socket_error
484 };
485
486 DWORD err;
487 char *errstr;
488 Actual_Socket ret;
489
490 /*
491 * Create Socket structure.
492 */
3d88e64d 493 ret = snew(struct Socket_tag);
d74d141c 494 ret->fn = &fn_table;
495 ret->error = NULL;
496 ret->plug = plug;
5471d09a 497 bufchain_init(&ret->output_data);
d74d141c 498 ret->writable = 1; /* to start with */
499 ret->sending_oob = 0;
500 ret->frozen = 1;
5471d09a 501 ret->frozen_readable = 0;
bc4802a1 502 ret->localhost_only = 0; /* unused, but best init anyway */
7732d38a 503 ret->pending_error = 0;
d74d141c 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
4b1e8acc 528Socket sk_new(SockAddr addr, int port, int privport, int oobinline,
2184a5d9 529 int nodelay, Plug plug)
7e78000d 530{
c85623f9 531 static const struct socket_function_table fn_table = {
7e78000d 532 sk_tcp_plug,
533 sk_tcp_close,
534 sk_tcp_write,
535 sk_tcp_write_oob,
536 sk_tcp_flush,
8eebd221 537 sk_tcp_set_private_ptr,
538 sk_tcp_get_private_ptr,
539 sk_tcp_set_frozen,
7e78000d 540 sk_tcp_socket_error
541 };
542
2f75bae1 543 SOCKET s;
c4d8e107 544#ifdef IPV6
545 SOCKADDR_IN6 a6;
546#endif
2f75bae1 547 SOCKADDR_IN a;
548 DWORD err;
549 char *errstr;
7e78000d 550 Actual_Socket ret;
c91409da 551 short localport;
2f75bae1 552
553 /*
554 * Create Socket structure.
555 */
3d88e64d 556 ret = snew(struct Socket_tag);
7e78000d 557 ret->fn = &fn_table;
2f75bae1 558 ret->error = NULL;
7e78000d 559 ret->plug = plug;
5471d09a 560 bufchain_init(&ret->output_data);
3ad9d396 561 ret->connected = 0; /* to start with */
562 ret->writable = 0; /* to start with */
33232c8f 563 ret->sending_oob = 0;
d74d141c 564 ret->frozen = 0;
5471d09a 565 ret->frozen_readable = 0;
bc4802a1 566 ret->localhost_only = 0; /* unused, but best init anyway */
7732d38a 567 ret->pending_error = 0;
2f75bae1 568
569 /*
570 * Open socket.
571 */
b7a189f3 572 assert(addr->family != AF_UNSPEC);
c4d8e107 573 s = socket(addr->family, SOCK_STREAM, 0);
2f75bae1 574 ret->s = s;
575
576 if (s == INVALID_SOCKET) {
577 err = WSAGetLastError();
32874aea 578 ret->error = winsock_error_string(err);
7e78000d 579 return (Socket) ret;
2f75bae1 580 }
4b1e8acc 581
582 ret->oobinline = oobinline;
583 if (oobinline) {
1ad4eb6f 584 BOOL b = TRUE;
32874aea 585 setsockopt(s, SOL_SOCKET, SO_OOBINLINE, (void *) &b, sizeof(b));
1ad4eb6f 586 }
2f75bae1 587
2184a5d9 588 if (nodelay) {
589 BOOL b = TRUE;
590 setsockopt(s, IPPROTO_TCP, TCP_NODELAY, (void *) &b, sizeof(b));
591 }
592
2f75bae1 593 /*
594 * Bind to local address.
595 */
c91409da 596 if (privport)
32874aea 597 localport = 1023; /* count from 1023 downwards */
c4d8e107 598 else
32874aea 599 localport = 0; /* just use port 0 (ie winsock picks) */
c91409da 600
601 /* Loop round trying to bind */
602 while (1) {
32874aea 603 int retcode;
c91409da 604
605#ifdef IPV6
32874aea 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
c4d8e107 612#endif
32874aea 613 {
614 a.sin_family = AF_INET;
615 a.sin_addr.s_addr = htonl(INADDR_ANY);
616 a.sin_port = htons(localport);
617 }
c4d8e107 618#ifdef IPV6
32874aea 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)));
c4d8e107 624#else
32874aea 625 retcode = bind(s, (struct sockaddr *) &a, sizeof(a));
c4d8e107 626#endif
32874aea 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 */
c91409da 641 }
642
32874aea 643 if (err) {
c4d8e107 644 ret->error = winsock_error_string(err);
7e78000d 645 return (Socket) ret;
2f75bae1 646 }
647
648 /*
649 * Connect to remote address.
650 */
c4d8e107 651#ifdef IPV6
32874aea 652 if (addr->family == AF_INET6) {
653 memset(&a, 0, sizeof(a));
c4d8e107 654 a6.sin6_family = AF_INET6;
32874aea 655 a6.sin6_port = htons((short) port);
656 a6.sin6_addr =
657 ((struct sockaddr_in6 *) addr->ai->ai_addr)->sin6_addr;
658 } else
c4d8e107 659#endif
32874aea 660 {
c4d8e107 661 a.sin_family = AF_INET;
662 a.sin_addr.s_addr = htonl(addr->address);
32874aea 663 a.sin_port = htons((short) port);
c4d8e107 664 }
3ad9d396 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
32874aea 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))
c4d8e107 679#else
32874aea 680 connect(s, (struct sockaddr *) &a, sizeof(a))
c4d8e107 681#endif
32874aea 682 ) == SOCKET_ERROR) {
2f75bae1 683 err = WSAGetLastError();
3ad9d396 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;
2f75bae1 700 }
701
702 add234(sktree, ret);
703
f85e6f6e 704 /* We're done with 'addr' now. */
705 sk_addr_free(addr);
706
7e78000d 707 return (Socket) ret;
2f75bae1 708}
709
6ee9b735 710Socket sk_newlistener(char *srcaddr, int port, Plug plug, int local_host_only)
d74d141c 711{
c85623f9 712 static const struct socket_function_table fn_table = {
d74d141c 713 sk_tcp_plug,
714 sk_tcp_close,
715 sk_tcp_write,
716 sk_tcp_write_oob,
717 sk_tcp_flush,
8eebd221 718 sk_tcp_set_private_ptr,
719 sk_tcp_get_private_ptr,
720 sk_tcp_set_frozen,
d74d141c 721 sk_tcp_socket_error
722 };
723
724 SOCKET s;
725#ifdef IPV6
726 SOCKADDR_IN6 a6;
727#endif
728 SOCKADDR_IN a;
729 DWORD err;
730 char *errstr;
731 Actual_Socket ret;
732 int retcode;
733 int on = 1;
734
735 /*
736 * Create Socket structure.
737 */
3d88e64d 738 ret = snew(struct Socket_tag);
d74d141c 739 ret->fn = &fn_table;
740 ret->error = NULL;
741 ret->plug = plug;
5471d09a 742 bufchain_init(&ret->output_data);
d74d141c 743 ret->writable = 0; /* to start with */
744 ret->sending_oob = 0;
745 ret->frozen = 0;
5471d09a 746 ret->frozen_readable = 0;
bc4802a1 747 ret->localhost_only = local_host_only;
7732d38a 748 ret->pending_error = 0;
d74d141c 749
750 /*
751 * Open socket.
752 */
753 s = socket(AF_INET, SOCK_STREAM, 0);
754 ret->s = s;
755
756 if (s == INVALID_SOCKET) {
757 err = WSAGetLastError();
758 ret->error = winsock_error_string(err);
759 return (Socket) ret;
760 }
761
762 ret->oobinline = 0;
763
d74d141c 764 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (const char *)&on, sizeof(on));
765
d74d141c 766#ifdef IPV6
767 if (addr->family == AF_INET6) {
768 memset(&a6, 0, sizeof(a6));
769 a6.sin6_family = AF_INET6;
6ee9b735 770 /* FIXME: srcaddr is ignored for IPv6, because I (SGT) don't
771 * know how to do it. :-) */
bcce45ed 772 if (local_host_only)
773 a6.sin6_addr = in6addr_loopback;
774 else
775 a6.sin6_addr = in6addr_any;
d74d141c 776 a6.sin6_port = htons(port);
777 } else
778#endif
779 {
6ee9b735 780 int got_addr = 0;
d74d141c 781 a.sin_family = AF_INET;
6ee9b735 782
783 /*
784 * Bind to source address. First try an explicitly
785 * specified one...
786 */
787 if (srcaddr) {
788 a.sin_addr.s_addr = inet_addr(srcaddr);
789 if (a.sin_addr.s_addr != INADDR_NONE) {
790 /* Override localhost_only with specified listen addr. */
791 ret->localhost_only = ipv4_is_loopback(a.sin_addr);
792 got_addr = 1;
793 }
794 }
795
796 /*
797 * ... and failing that, go with one of the standard ones.
798 */
799 if (!got_addr) {
800 if (local_host_only)
801 a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
802 else
803 a.sin_addr.s_addr = htonl(INADDR_ANY);
804 }
805
d74d141c 806 a.sin_port = htons((short)port);
807 }
808#ifdef IPV6
809 retcode = bind(s, (addr->family == AF_INET6 ?
810 (struct sockaddr *) &a6 :
811 (struct sockaddr *) &a),
812 (addr->family ==
813 AF_INET6 ? sizeof(a6) : sizeof(a)));
814#else
815 retcode = bind(s, (struct sockaddr *) &a, sizeof(a));
816#endif
817 if (retcode != SOCKET_ERROR) {
818 err = 0;
819 } else {
820 err = WSAGetLastError();
821 }
822
823 if (err) {
824 ret->error = winsock_error_string(err);
825 return (Socket) ret;
826 }
827
828
829 if (listen(s, SOMAXCONN) == SOCKET_ERROR) {
830 closesocket(s);
831 ret->error = winsock_error_string(err);
832 return (Socket) ret;
833 }
834
835 /* Set up a select mechanism. This could be an AsyncSelect on a
836 * window, or an EventSelect on an event object. */
837 errstr = do_select(s, 1);
838 if (errstr) {
839 ret->error = errstr;
840 return (Socket) ret;
841 }
842
843 add234(sktree, ret);
844
845 return (Socket) ret;
846}
847
32874aea 848static void sk_tcp_close(Socket sock)
849{
9c964e85 850 extern char *do_select(SOCKET skt, int startup);
7e78000d 851 Actual_Socket s = (Actual_Socket) sock;
9c964e85 852
2f75bae1 853 del234(sktree, s);
854 do_select(s->s, 0);
855 closesocket(s->s);
dcbde236 856 sfree(s);
2f75bae1 857}
858
2f75bae1 859/*
860 * The function which tries to send on a socket once it's deemed
861 * writable.
862 */
32874aea 863void try_send(Actual_Socket s)
864{
5471d09a 865 while (s->sending_oob || bufchain_size(&s->output_data) > 0) {
2f75bae1 866 int nsent;
867 DWORD err;
5471d09a 868 void *data;
32874aea 869 int len, urgentflag;
870
871 if (s->sending_oob) {
872 urgentflag = MSG_OOB;
873 len = s->sending_oob;
5471d09a 874 data = &s->oobdata;
32874aea 875 } else {
876 urgentflag = 0;
5471d09a 877 bufchain_prefix(&s->output_data, &data, &len);
32874aea 878 }
5471d09a 879 nsent = send(s->s, data, len, urgentflag);
32874aea 880 noise_ultralight(nsent);
2f75bae1 881 if (nsent <= 0) {
882 err = (nsent < 0 ? WSAGetLastError() : 0);
e5eb3a1c 883 if ((err < WSABASEERR && nsent < 0) || err == WSAEWOULDBLOCK) {
d40a94b9 884 /*
885 * Perfectly normal: we've sent all we can for the moment.
886 *
e5eb3a1c 887 * (Some WinSock send() implementations can return
888 * <0 but leave no sensible error indication -
889 * WSAGetLastError() is called but returns zero or
890 * a small number - so we check that case and treat
891 * it just like WSAEWOULDBLOCK.)
d40a94b9 892 */
2f75bae1 893 s->writable = FALSE;
32874aea 894 return;
2f75bae1 895 } else if (nsent == 0 ||
32874aea 896 err == WSAECONNABORTED || err == WSAECONNRESET) {
897 /*
7732d38a 898 * If send() returns CONNABORTED or CONNRESET, we
899 * unfortunately can't just call plug_closing(),
900 * because it's quite likely that we're currently
901 * _in_ a call from the code we'd be calling back
902 * to, so we'd have to make half the SSH code
903 * reentrant. Instead we flag a pending error on
904 * the socket, to be dealt with (by calling
905 * plug_closing()) at some suitable future moment.
32874aea 906 */
7732d38a 907 s->pending_error = err;
908 return;
2f75bae1 909 } else {
a8327734 910 /* We're inside the Windows frontend here, so we know
911 * that the frontend handle is unnecessary. */
912 logevent(NULL, winsock_error_string(err));
247308b5 913 fatalbox("%s", winsock_error_string(err));
2f75bae1 914 }
915 } else {
5471d09a 916 if (s->sending_oob) {
917 if (nsent < len) {
918 memmove(s->oobdata, s->oobdata+nsent, len-nsent);
919 s->sending_oob = len - nsent;
920 } else {
921 s->sending_oob = 0;
922 }
923 } else {
924 bufchain_consume(&s->output_data, nsent);
2f75bae1 925 }
926 }
927 }
928}
929
e0e7dff8 930static int sk_tcp_write(Socket sock, const char *buf, int len)
32874aea 931{
7e78000d 932 Actual_Socket s = (Actual_Socket) sock;
933
2f75bae1 934 /*
935 * Add the data to the buffer list on the socket.
936 */
5471d09a 937 bufchain_add(&s->output_data, buf, len);
2f75bae1 938
939 /*
940 * Now try sending from the start of the buffer list.
941 */
942 if (s->writable)
943 try_send(s);
5471d09a 944
945 return bufchain_size(&s->output_data);
2f75bae1 946}
947
e0e7dff8 948static int sk_tcp_write_oob(Socket sock, const char *buf, int len)
32874aea 949{
7e78000d 950 Actual_Socket s = (Actual_Socket) sock;
951
2f75bae1 952 /*
953 * Replace the buffer list on the socket with the data.
954 */
5471d09a 955 bufchain_clear(&s->output_data);
956 assert(len <= sizeof(s->oobdata));
957 memcpy(s->oobdata, buf, len);
2f75bae1 958 s->sending_oob = len;
959
960 /*
961 * Now try sending from the start of the buffer list.
962 */
963 if (s->writable)
964 try_send(s);
5471d09a 965
966 return s->sending_oob;
2f75bae1 967}
968
32874aea 969int select_result(WPARAM wParam, LPARAM lParam)
970{
f9d3f227 971 int ret, open;
2f75bae1 972 DWORD err;
b675c612 973 char buf[20480]; /* nice big buffer for plenty of speed */
7e78000d 974 Actual_Socket s;
49bad831 975 u_long atmark;
2f75bae1 976
977 /* wParam is the socket itself */
cc8b0ee9 978
ce6fcfa5 979 if (wParam == 0)
980 return 1; /* boggle */
cc8b0ee9 981
32874aea 982 s = find234(sktree, (void *) wParam, cmpforsearch);
2f75bae1 983 if (!s)
984 return 1; /* boggle */
985
986 if ((err = WSAGETSELECTERROR(lParam)) != 0) {
32874aea 987 /*
988 * An error has occurred on this socket. Pass it to the
989 * plug.
990 */
991 return plug_closing(s->plug, winsock_error_string(err), err, 0);
2f75bae1 992 }
993
7d6ee6ff 994 noise_ultralight(lParam);
995
2f75bae1 996 switch (WSAGETSELECTEVENT(lParam)) {
3ad9d396 997 case FD_CONNECT:
998 s->connected = s->writable = 1;
999 break;
2f75bae1 1000 case FD_READ:
d74d141c 1001 /* In the case the socket is still frozen, we don't even bother */
5471d09a 1002 if (s->frozen) {
1003 s->frozen_readable = 1;
d74d141c 1004 break;
5471d09a 1005 }
d74d141c 1006
32874aea 1007 /*
1008 * We have received data on the socket. For an oobinline
1009 * socket, this might be data _before_ an urgent pointer,
1010 * in which case we send it to the back end with type==1
1011 * (data prior to urgent).
1012 */
1013 if (s->oobinline) {
1014 atmark = 1;
1015 ioctlsocket(s->s, SIOCATMARK, &atmark);
1016 /*
1017 * Avoid checking the return value from ioctlsocket(),
1018 * on the grounds that some WinSock wrappers don't
1019 * support it. If it does nothing, we get atmark==1,
1020 * which is equivalent to `no OOB pending', so the
1021 * effect will be to non-OOB-ify any OOB data.
1022 */
1023 } else
1024 atmark = 1;
4b1e8acc 1025
2f75bae1 1026 ret = recv(s->s, buf, sizeof(buf), 0);
32874aea 1027 noise_ultralight(ret);
2f75bae1 1028 if (ret < 0) {
1029 err = WSAGetLastError();
1030 if (err == WSAEWOULDBLOCK) {
1031 break;
1032 }
1033 }
1034 if (ret < 0) {
32874aea 1035 return plug_closing(s->plug, winsock_error_string(err), err,
1036 0);
7e78000d 1037 } else if (0 == ret) {
32874aea 1038 return plug_closing(s->plug, NULL, 0, 0);
2f75bae1 1039 } else {
32874aea 1040 return plug_receive(s->plug, atmark ? 0 : 1, buf, ret);
2f75bae1 1041 }
1042 break;
1043 case FD_OOB:
32874aea 1044 /*
1045 * This will only happen on a non-oobinline socket. It
1046 * indicates that we can immediately perform an OOB read
1047 * and get back OOB data, which we will send to the back
1048 * end with type==2 (urgent data).
1049 */
1050 ret = recv(s->s, buf, sizeof(buf), MSG_OOB);
1051 noise_ultralight(ret);
1052 if (ret <= 0) {
247308b5 1053 char *str = (ret == 0 ? "Internal networking trouble" :
1054 winsock_error_string(WSAGetLastError()));
a8327734 1055 /* We're inside the Windows frontend here, so we know
1056 * that the frontend handle is unnecessary. */
1057 logevent(NULL, str);
247308b5 1058 fatalbox("%s", str);
32874aea 1059 } else {
1060 return plug_receive(s->plug, 2, buf, ret);
1061 }
1062 break;
2f75bae1 1063 case FD_WRITE:
5471d09a 1064 {
1065 int bufsize_before, bufsize_after;
1066 s->writable = 1;
1067 bufsize_before = s->sending_oob + bufchain_size(&s->output_data);
1068 try_send(s);
1069 bufsize_after = s->sending_oob + bufchain_size(&s->output_data);
1070 if (bufsize_after < bufsize_before)
1071 plug_sent(s->plug, bufsize_after);
1072 }
2f75bae1 1073 break;
1074 case FD_CLOSE:
f9d3f227 1075 /* Signal a close on the socket. First read any outstanding data. */
32874aea 1076 open = 1;
1077 do {
1078 ret = recv(s->s, buf, sizeof(buf), 0);
1079 if (ret < 0) {
1080 err = WSAGetLastError();
1081 if (err == WSAEWOULDBLOCK)
1082 break;
1083 return plug_closing(s->plug, winsock_error_string(err),
1084 err, 0);
1085 } else {
1086 if (ret)
1087 open &= plug_receive(s->plug, 0, buf, ret);
1088 else
1089 open &= plug_closing(s->plug, NULL, 0, 0);
7e78000d 1090 }
f9d3f227 1091 } while (ret > 0);
32874aea 1092 return open;
d74d141c 1093 case FD_ACCEPT:
1094 {
bc4802a1 1095 struct sockaddr_in isa;
1096 int addrlen = sizeof(struct sockaddr_in);
bcce45ed 1097 SOCKET t; /* socket of connection */
1098
bc4802a1 1099 memset(&isa, 0, sizeof(struct sockaddr_in));
bcce45ed 1100 err = 0;
0e5e7f46 1101 t = accept(s->s,(struct sockaddr *)&isa,&addrlen);
bcce45ed 1102 if (t == INVALID_SOCKET)
1103 {
1104 err = WSAGetLastError();
1105 if (err == WSATRY_AGAIN)
1106 break;
1107 }
1108
6ee9b735 1109 if (s->localhost_only && !ipv4_is_loopback(isa.sin_addr)) {
bc4802a1 1110 closesocket(t); /* dodgy WinSock let nonlocal through */
1111 } else if (plug_accepting(s->plug, (void*)t)) {
bcce45ed 1112 closesocket(t); /* denied or error */
1113 }
d74d141c 1114 }
2f75bae1 1115 }
1116
1117 return 1;
1118}
1119
1120/*
7732d38a 1121 * Deal with socket errors detected in try_send().
1122 */
1123void net_pending_errors(void)
1124{
1125 int i;
1126 Actual_Socket s;
1127
1128 /*
1129 * This might be a fiddly business, because it's just possible
1130 * that handling a pending error on one socket might cause
1131 * others to be closed. (I can't think of any reason this might
1132 * happen in current SSH implementation, but to maintain
1133 * generality of this network layer I'll assume the worst.)
1134 *
1135 * So what we'll do is search the socket list for _one_ socket
1136 * with a pending error, and then handle it, and then search
1137 * the list again _from the beginning_. Repeat until we make a
1138 * pass with no socket errors present. That way we are
1139 * protected against the socket list changing under our feet.
1140 */
1141
1142 do {
1143 for (i = 0; (s = index234(sktree, i)) != NULL; i++) {
1144 if (s->pending_error) {
1145 /*
1146 * An error has occurred on this socket. Pass it to the
1147 * plug.
1148 */
1149 plug_closing(s->plug,
1150 winsock_error_string(s->pending_error),
1151 s->pending_error, 0);
1152 break;
1153 }
1154 }
1155 } while (s);
1156}
1157
1158/*
2f75bae1 1159 * Each socket abstraction contains a `void *' private field in
1160 * which the client can keep state.
1161 */
8eebd221 1162static void sk_tcp_set_private_ptr(Socket sock, void *ptr)
32874aea 1163{
7e78000d 1164 Actual_Socket s = (Actual_Socket) sock;
2f75bae1 1165 s->private_ptr = ptr;
1166}
32874aea 1167
8eebd221 1168static void *sk_tcp_get_private_ptr(Socket sock)
32874aea 1169{
7e78000d 1170 Actual_Socket s = (Actual_Socket) sock;
2f75bae1 1171 return s->private_ptr;
1172}
1173
1174/*
1175 * Special error values are returned from sk_namelookup and sk_new
1176 * if there's a problem. These functions extract an error message,
1177 * or return NULL if there's no problem.
1178 */
cbe2d68f 1179const char *sk_addr_error(SockAddr addr)
32874aea 1180{
2f75bae1 1181 return addr->error;
1182}
cbe2d68f 1183static const char *sk_tcp_socket_error(Socket sock)
32874aea 1184{
7e78000d 1185 Actual_Socket s = (Actual_Socket) sock;
2f75bae1 1186 return s->error;
1187}
1188
8eebd221 1189static void sk_tcp_set_frozen(Socket sock, int is_frozen)
d74d141c 1190{
1191 Actual_Socket s = (Actual_Socket) sock;
5471d09a 1192 if (s->frozen == is_frozen)
1193 return;
d74d141c 1194 s->frozen = is_frozen;
5471d09a 1195 if (!is_frozen && s->frozen_readable) {
d74d141c 1196 char c;
1197 recv(s->s, &c, 1, MSG_PEEK);
1198 }
5471d09a 1199 s->frozen_readable = 0;
d74d141c 1200}
1201
2f75bae1 1202/*
1203 * For Plink: enumerate all sockets currently active.
1204 */
32874aea 1205SOCKET first_socket(int *state)
1206{
d2371c81 1207 Actual_Socket s;
1208 *state = 0;
1209 s = index234(sktree, (*state)++);
2f75bae1 1210 return s ? s->s : INVALID_SOCKET;
1211}
32874aea 1212
1213SOCKET next_socket(int *state)
1214{
d2371c81 1215 Actual_Socket s = index234(sktree, (*state)++);
2f75bae1 1216 return s ? s->s : INVALID_SOCKET;
1217}
68a49acb 1218
1219int net_service_lookup(char *service)
1220{
1221 struct servent *se;
1222 se = getservbyname(service, NULL);
1223 if (se != NULL)
1224 return ntohs(se->s_port);
1225 else
1226 return 0;
1227}