Support for doing DNS at the proxy end. I've invented a new type of
[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 {
7e78000d 62 struct socket_function_table *fn;
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
c4d8e107 227SockAddr sk_namelookup(char *host, char **canonicalname)
228{
2f75bae1 229 SockAddr ret = smalloc(sizeof(struct SockAddr_tag));
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';
360 *canonicalname = smalloc(1+strlen(realhost));
361 strcpy(*canonicalname, realhost);
2f75bae1 362 return ret;
363}
364
b7a189f3 365SockAddr sk_nonamelookup(char *host)
366{
367 SockAddr ret = smalloc(sizeof(struct SockAddr_tag));
368 ret->family = AF_UNSPEC;
369 strncpy(ret->hostname, host, lenof(ret->hostname));
370 ret->hostname[lenof(ret->hostname)-1] = '\0';
371 return ret;
372}
373
3ad9d396 374void sk_getaddr(SockAddr addr, char *buf, int buflen)
375{
376#ifdef IPV6
b7a189f3 377 if (addr->family == AF_INET6) {
378 FIXME; /* I don't know how to get a text form of an IPv6 address. */
379 } else
3ad9d396 380#endif
b7a189f3 381 if (addr->family == AF_INET) {
3ad9d396 382 struct in_addr a;
383 a.s_addr = htonl(addr->address);
384 strncpy(buf, inet_ntoa(a), buflen);
b7a189f3 385 buf[buflen-1] = '\0';
3ad9d396 386 } else {
b7a189f3 387 assert(addr->family == AF_UNSPEC);
388 strncpy(buf, addr->hostname, buflen);
389 buf[buflen-1] = '\0';
3ad9d396 390 }
3ad9d396 391}
392
b804e1e5 393int sk_hostname_is_local(char *name)
394{
395 return !strcmp(name, "localhost");
396}
397
398int sk_address_is_local(SockAddr addr)
399{
400#ifdef IPV6
b7a189f3 401 if (addr->family == AF_INET6) {
402 FIXME; /* someone who can compile for IPV6 had better do this bit */
403 } else
b804e1e5 404#endif
b7a189f3 405 if (addr->family == AF_INET) {
b804e1e5 406 struct in_addr a;
407 a.s_addr = htonl(addr->address);
408 return ipv4_is_loopback(a);
b804e1e5 409 } else {
b7a189f3 410 assert(addr->family == AF_UNSPEC);
411 return 0; /* we don't know; assume not */
b804e1e5 412 }
b804e1e5 413}
414
6971bbe7 415int sk_addrtype(SockAddr addr)
416{
b7a189f3 417 return (addr->family == AF_INET ? ADDRTYPE_IPV4 :
418#ifdef IPV6
419 addr->family == AF_INET6 ? ADDRTYPE_IPV6 :
420#endif
421 ADDRTYPE_NAME);
6971bbe7 422}
423
424void sk_addrcopy(SockAddr addr, char *buf)
425{
b7a189f3 426 assert(addr->family != AF_UNSPEC);
6971bbe7 427#ifdef IPV6
b7a189f3 428 if (addr->family == AF_INET6) {
429 memcpy(buf, (char*) addr->ai, 16);
430 } else
6971bbe7 431#endif
b7a189f3 432 if (addr->family == AF_INET) {
6971bbe7 433 struct in_addr a;
434 a.s_addr = htonl(addr->address);
96d9eb89 435 memcpy(buf, (char*) &a.s_addr, 4);
6971bbe7 436 }
6971bbe7 437}
438
32874aea 439void sk_addr_free(SockAddr addr)
440{
2f75bae1 441 sfree(addr);
442}
443
32874aea 444static Plug sk_tcp_plug(Socket sock, Plug p)
445{
7e78000d 446 Actual_Socket s = (Actual_Socket) sock;
447 Plug ret = s->plug;
32874aea 448 if (p)
449 s->plug = p;
7e78000d 450 return ret;
451}
452
32874aea 453static void sk_tcp_flush(Socket s)
454{
7e78000d 455 /*
456 * We send data to the socket as soon as we can anyway,
457 * so we don't need to do anything here. :-)
458 */
459}
460
2d466ffd 461static void sk_tcp_close(Socket s);
5471d09a 462static int sk_tcp_write(Socket s, char *data, int len);
463static int sk_tcp_write_oob(Socket s, char *data, int len);
8eebd221 464static void sk_tcp_set_private_ptr(Socket s, void *ptr);
465static void *sk_tcp_get_private_ptr(Socket s);
466static void sk_tcp_set_frozen(Socket s, int is_frozen);
2d466ffd 467static char *sk_tcp_socket_error(Socket s);
7e78000d 468
d74d141c 469extern char *do_select(SOCKET skt, int startup);
470
471Socket sk_register(void *sock, Plug plug)
472{
473 static struct socket_function_table fn_table = {
474 sk_tcp_plug,
475 sk_tcp_close,
476 sk_tcp_write,
477 sk_tcp_write_oob,
478 sk_tcp_flush,
8eebd221 479 sk_tcp_set_private_ptr,
480 sk_tcp_get_private_ptr,
481 sk_tcp_set_frozen,
d74d141c 482 sk_tcp_socket_error
483 };
484
485 DWORD err;
486 char *errstr;
487 Actual_Socket ret;
488
489 /*
490 * Create Socket structure.
491 */
492 ret = smalloc(sizeof(struct Socket_tag));
493 ret->fn = &fn_table;
494 ret->error = NULL;
495 ret->plug = plug;
5471d09a 496 bufchain_init(&ret->output_data);
d74d141c 497 ret->writable = 1; /* to start with */
498 ret->sending_oob = 0;
499 ret->frozen = 1;
5471d09a 500 ret->frozen_readable = 0;
bc4802a1 501 ret->localhost_only = 0; /* unused, but best init anyway */
7732d38a 502 ret->pending_error = 0;
d74d141c 503
504 ret->s = (SOCKET)sock;
505
506 if (ret->s == INVALID_SOCKET) {
507 err = WSAGetLastError();
508 ret->error = winsock_error_string(err);
509 return (Socket) ret;
510 }
511
512 ret->oobinline = 0;
513
514 /* Set up a select mechanism. This could be an AsyncSelect on a
515 * window, or an EventSelect on an event object. */
516 errstr = do_select(ret->s, 1);
517 if (errstr) {
518 ret->error = errstr;
519 return (Socket) ret;
520 }
521
522 add234(sktree, ret);
523
524 return (Socket) ret;
525}
526
4b1e8acc 527Socket sk_new(SockAddr addr, int port, int privport, int oobinline,
2184a5d9 528 int nodelay, Plug plug)
7e78000d 529{
530 static struct socket_function_table fn_table = {
531 sk_tcp_plug,
532 sk_tcp_close,
533 sk_tcp_write,
534 sk_tcp_write_oob,
535 sk_tcp_flush,
8eebd221 536 sk_tcp_set_private_ptr,
537 sk_tcp_get_private_ptr,
538 sk_tcp_set_frozen,
7e78000d 539 sk_tcp_socket_error
540 };
541
2f75bae1 542 SOCKET s;
c4d8e107 543#ifdef IPV6
544 SOCKADDR_IN6 a6;
545#endif
2f75bae1 546 SOCKADDR_IN a;
547 DWORD err;
548 char *errstr;
7e78000d 549 Actual_Socket ret;
c91409da 550 short localport;
2f75bae1 551
552 /*
553 * Create Socket structure.
554 */
555 ret = smalloc(sizeof(struct Socket_tag));
7e78000d 556 ret->fn = &fn_table;
2f75bae1 557 ret->error = NULL;
7e78000d 558 ret->plug = plug;
5471d09a 559 bufchain_init(&ret->output_data);
3ad9d396 560 ret->connected = 0; /* to start with */
561 ret->writable = 0; /* to start with */
33232c8f 562 ret->sending_oob = 0;
d74d141c 563 ret->frozen = 0;
5471d09a 564 ret->frozen_readable = 0;
bc4802a1 565 ret->localhost_only = 0; /* unused, but best init anyway */
7732d38a 566 ret->pending_error = 0;
2f75bae1 567
568 /*
569 * Open socket.
570 */
b7a189f3 571 assert(addr->family != AF_UNSPEC);
c4d8e107 572 s = socket(addr->family, SOCK_STREAM, 0);
2f75bae1 573 ret->s = s;
574
575 if (s == INVALID_SOCKET) {
576 err = WSAGetLastError();
32874aea 577 ret->error = winsock_error_string(err);
7e78000d 578 return (Socket) ret;
2f75bae1 579 }
4b1e8acc 580
581 ret->oobinline = oobinline;
582 if (oobinline) {
1ad4eb6f 583 BOOL b = TRUE;
32874aea 584 setsockopt(s, SOL_SOCKET, SO_OOBINLINE, (void *) &b, sizeof(b));
1ad4eb6f 585 }
2f75bae1 586
2184a5d9 587 if (nodelay) {
588 BOOL b = TRUE;
589 setsockopt(s, IPPROTO_TCP, TCP_NODELAY, (void *) &b, sizeof(b));
590 }
591
2f75bae1 592 /*
593 * Bind to local address.
594 */
c91409da 595 if (privport)
32874aea 596 localport = 1023; /* count from 1023 downwards */
c4d8e107 597 else
32874aea 598 localport = 0; /* just use port 0 (ie winsock picks) */
c91409da 599
600 /* Loop round trying to bind */
601 while (1) {
32874aea 602 int retcode;
c91409da 603
604#ifdef IPV6
32874aea 605 if (addr->family == AF_INET6) {
606 memset(&a6, 0, sizeof(a6));
607 a6.sin6_family = AF_INET6;
608/*a6.sin6_addr = in6addr_any; *//* == 0 */
609 a6.sin6_port = htons(localport);
610 } else
c4d8e107 611#endif
32874aea 612 {
613 a.sin_family = AF_INET;
614 a.sin_addr.s_addr = htonl(INADDR_ANY);
615 a.sin_port = htons(localport);
616 }
c4d8e107 617#ifdef IPV6
32874aea 618 retcode = bind(s, (addr->family == AF_INET6 ?
619 (struct sockaddr *) &a6 :
620 (struct sockaddr *) &a),
621 (addr->family ==
622 AF_INET6 ? sizeof(a6) : sizeof(a)));
c4d8e107 623#else
32874aea 624 retcode = bind(s, (struct sockaddr *) &a, sizeof(a));
c4d8e107 625#endif
32874aea 626 if (retcode != SOCKET_ERROR) {
627 err = 0;
628 break; /* done */
629 } else {
630 err = WSAGetLastError();
631 if (err != WSAEADDRINUSE) /* failed, for a bad reason */
632 break;
633 }
634
635 if (localport == 0)
636 break; /* we're only looping once */
637 localport--;
638 if (localport == 0)
639 break; /* we might have got to the end */
c91409da 640 }
641
32874aea 642 if (err) {
c4d8e107 643 ret->error = winsock_error_string(err);
7e78000d 644 return (Socket) ret;
2f75bae1 645 }
646
647 /*
648 * Connect to remote address.
649 */
c4d8e107 650#ifdef IPV6
32874aea 651 if (addr->family == AF_INET6) {
652 memset(&a, 0, sizeof(a));
c4d8e107 653 a6.sin6_family = AF_INET6;
32874aea 654 a6.sin6_port = htons((short) port);
655 a6.sin6_addr =
656 ((struct sockaddr_in6 *) addr->ai->ai_addr)->sin6_addr;
657 } else
c4d8e107 658#endif
32874aea 659 {
c4d8e107 660 a.sin_family = AF_INET;
661 a.sin_addr.s_addr = htonl(addr->address);
32874aea 662 a.sin_port = htons((short) port);
c4d8e107 663 }
3ad9d396 664
665 /* Set up a select mechanism. This could be an AsyncSelect on a
666 * window, or an EventSelect on an event object. */
667 errstr = do_select(s, 1);
668 if (errstr) {
669 ret->error = errstr;
670 return (Socket) ret;
671 }
672
32874aea 673 if ((
674#ifdef IPV6
675 connect(s, ((addr->family == AF_INET6) ?
676 (struct sockaddr *) &a6 : (struct sockaddr *) &a),
677 (addr->family == AF_INET6) ? sizeof(a6) : sizeof(a))
c4d8e107 678#else
32874aea 679 connect(s, (struct sockaddr *) &a, sizeof(a))
c4d8e107 680#endif
32874aea 681 ) == SOCKET_ERROR) {
2f75bae1 682 err = WSAGetLastError();
3ad9d396 683 /*
684 * We expect a potential EWOULDBLOCK here, because the
685 * chances are the front end has done a select for
686 * FD_CONNECT, so that connect() will complete
687 * asynchronously.
688 */
689 if ( err != WSAEWOULDBLOCK ) {
690 ret->error = winsock_error_string(err);
691 return (Socket) ret;
692 }
693 } else {
694 /*
695 * If we _don't_ get EWOULDBLOCK, the connect has completed
696 * and we should set the socket as writable.
697 */
698 ret->writable = 1;
2f75bae1 699 }
700
701 add234(sktree, ret);
702
7e78000d 703 return (Socket) ret;
2f75bae1 704}
705
6ee9b735 706Socket sk_newlistener(char *srcaddr, int port, Plug plug, int local_host_only)
d74d141c 707{
708 static struct socket_function_table fn_table = {
709 sk_tcp_plug,
710 sk_tcp_close,
711 sk_tcp_write,
712 sk_tcp_write_oob,
713 sk_tcp_flush,
8eebd221 714 sk_tcp_set_private_ptr,
715 sk_tcp_get_private_ptr,
716 sk_tcp_set_frozen,
d74d141c 717 sk_tcp_socket_error
718 };
719
720 SOCKET s;
721#ifdef IPV6
722 SOCKADDR_IN6 a6;
723#endif
724 SOCKADDR_IN a;
725 DWORD err;
726 char *errstr;
727 Actual_Socket ret;
728 int retcode;
729 int on = 1;
730
731 /*
732 * Create Socket structure.
733 */
734 ret = smalloc(sizeof(struct Socket_tag));
735 ret->fn = &fn_table;
736 ret->error = NULL;
737 ret->plug = plug;
5471d09a 738 bufchain_init(&ret->output_data);
d74d141c 739 ret->writable = 0; /* to start with */
740 ret->sending_oob = 0;
741 ret->frozen = 0;
5471d09a 742 ret->frozen_readable = 0;
bc4802a1 743 ret->localhost_only = local_host_only;
7732d38a 744 ret->pending_error = 0;
d74d141c 745
746 /*
747 * Open socket.
748 */
749 s = socket(AF_INET, SOCK_STREAM, 0);
750 ret->s = s;
751
752 if (s == INVALID_SOCKET) {
753 err = WSAGetLastError();
754 ret->error = winsock_error_string(err);
755 return (Socket) ret;
756 }
757
758 ret->oobinline = 0;
759
d74d141c 760 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (const char *)&on, sizeof(on));
761
d74d141c 762#ifdef IPV6
763 if (addr->family == AF_INET6) {
764 memset(&a6, 0, sizeof(a6));
765 a6.sin6_family = AF_INET6;
6ee9b735 766 /* FIXME: srcaddr is ignored for IPv6, because I (SGT) don't
767 * know how to do it. :-) */
bcce45ed 768 if (local_host_only)
769 a6.sin6_addr = in6addr_loopback;
770 else
771 a6.sin6_addr = in6addr_any;
d74d141c 772 a6.sin6_port = htons(port);
773 } else
774#endif
775 {
6ee9b735 776 int got_addr = 0;
d74d141c 777 a.sin_family = AF_INET;
6ee9b735 778
779 /*
780 * Bind to source address. First try an explicitly
781 * specified one...
782 */
783 if (srcaddr) {
784 a.sin_addr.s_addr = inet_addr(srcaddr);
785 if (a.sin_addr.s_addr != INADDR_NONE) {
786 /* Override localhost_only with specified listen addr. */
787 ret->localhost_only = ipv4_is_loopback(a.sin_addr);
788 got_addr = 1;
789 }
790 }
791
792 /*
793 * ... and failing that, go with one of the standard ones.
794 */
795 if (!got_addr) {
796 if (local_host_only)
797 a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
798 else
799 a.sin_addr.s_addr = htonl(INADDR_ANY);
800 }
801
d74d141c 802 a.sin_port = htons((short)port);
803 }
804#ifdef IPV6
805 retcode = bind(s, (addr->family == AF_INET6 ?
806 (struct sockaddr *) &a6 :
807 (struct sockaddr *) &a),
808 (addr->family ==
809 AF_INET6 ? sizeof(a6) : sizeof(a)));
810#else
811 retcode = bind(s, (struct sockaddr *) &a, sizeof(a));
812#endif
813 if (retcode != SOCKET_ERROR) {
814 err = 0;
815 } else {
816 err = WSAGetLastError();
817 }
818
819 if (err) {
820 ret->error = winsock_error_string(err);
821 return (Socket) ret;
822 }
823
824
825 if (listen(s, SOMAXCONN) == SOCKET_ERROR) {
826 closesocket(s);
827 ret->error = winsock_error_string(err);
828 return (Socket) ret;
829 }
830
831 /* Set up a select mechanism. This could be an AsyncSelect on a
832 * window, or an EventSelect on an event object. */
833 errstr = do_select(s, 1);
834 if (errstr) {
835 ret->error = errstr;
836 return (Socket) ret;
837 }
838
839 add234(sktree, ret);
840
841 return (Socket) ret;
842}
843
32874aea 844static void sk_tcp_close(Socket sock)
845{
9c964e85 846 extern char *do_select(SOCKET skt, int startup);
7e78000d 847 Actual_Socket s = (Actual_Socket) sock;
9c964e85 848
2f75bae1 849 del234(sktree, s);
850 do_select(s->s, 0);
851 closesocket(s->s);
dcbde236 852 sfree(s);
2f75bae1 853}
854
2f75bae1 855/*
856 * The function which tries to send on a socket once it's deemed
857 * writable.
858 */
32874aea 859void try_send(Actual_Socket s)
860{
5471d09a 861 while (s->sending_oob || bufchain_size(&s->output_data) > 0) {
2f75bae1 862 int nsent;
863 DWORD err;
5471d09a 864 void *data;
32874aea 865 int len, urgentflag;
866
867 if (s->sending_oob) {
868 urgentflag = MSG_OOB;
869 len = s->sending_oob;
5471d09a 870 data = &s->oobdata;
32874aea 871 } else {
872 urgentflag = 0;
5471d09a 873 bufchain_prefix(&s->output_data, &data, &len);
32874aea 874 }
5471d09a 875 nsent = send(s->s, data, len, urgentflag);
32874aea 876 noise_ultralight(nsent);
2f75bae1 877 if (nsent <= 0) {
878 err = (nsent < 0 ? WSAGetLastError() : 0);
e5eb3a1c 879 if ((err < WSABASEERR && nsent < 0) || err == WSAEWOULDBLOCK) {
d40a94b9 880 /*
881 * Perfectly normal: we've sent all we can for the moment.
882 *
e5eb3a1c 883 * (Some WinSock send() implementations can return
884 * <0 but leave no sensible error indication -
885 * WSAGetLastError() is called but returns zero or
886 * a small number - so we check that case and treat
887 * it just like WSAEWOULDBLOCK.)
d40a94b9 888 */
2f75bae1 889 s->writable = FALSE;
32874aea 890 return;
2f75bae1 891 } else if (nsent == 0 ||
32874aea 892 err == WSAECONNABORTED || err == WSAECONNRESET) {
893 /*
7732d38a 894 * If send() returns CONNABORTED or CONNRESET, we
895 * unfortunately can't just call plug_closing(),
896 * because it's quite likely that we're currently
897 * _in_ a call from the code we'd be calling back
898 * to, so we'd have to make half the SSH code
899 * reentrant. Instead we flag a pending error on
900 * the socket, to be dealt with (by calling
901 * plug_closing()) at some suitable future moment.
32874aea 902 */
7732d38a 903 s->pending_error = err;
904 return;
2f75bae1 905 } else {
a8327734 906 /* We're inside the Windows frontend here, so we know
907 * that the frontend handle is unnecessary. */
908 logevent(NULL, winsock_error_string(err));
247308b5 909 fatalbox("%s", winsock_error_string(err));
2f75bae1 910 }
911 } else {
5471d09a 912 if (s->sending_oob) {
913 if (nsent < len) {
914 memmove(s->oobdata, s->oobdata+nsent, len-nsent);
915 s->sending_oob = len - nsent;
916 } else {
917 s->sending_oob = 0;
918 }
919 } else {
920 bufchain_consume(&s->output_data, nsent);
2f75bae1 921 }
922 }
923 }
924}
925
5471d09a 926static int sk_tcp_write(Socket sock, char *buf, int len)
32874aea 927{
7e78000d 928 Actual_Socket s = (Actual_Socket) sock;
929
2f75bae1 930 /*
931 * Add the data to the buffer list on the socket.
932 */
5471d09a 933 bufchain_add(&s->output_data, buf, len);
2f75bae1 934
935 /*
936 * Now try sending from the start of the buffer list.
937 */
938 if (s->writable)
939 try_send(s);
5471d09a 940
941 return bufchain_size(&s->output_data);
2f75bae1 942}
943
5471d09a 944static int sk_tcp_write_oob(Socket sock, char *buf, int len)
32874aea 945{
7e78000d 946 Actual_Socket s = (Actual_Socket) sock;
947
2f75bae1 948 /*
949 * Replace the buffer list on the socket with the data.
950 */
5471d09a 951 bufchain_clear(&s->output_data);
952 assert(len <= sizeof(s->oobdata));
953 memcpy(s->oobdata, buf, len);
2f75bae1 954 s->sending_oob = len;
955
956 /*
957 * Now try sending from the start of the buffer list.
958 */
959 if (s->writable)
960 try_send(s);
5471d09a 961
962 return s->sending_oob;
2f75bae1 963}
964
32874aea 965int select_result(WPARAM wParam, LPARAM lParam)
966{
f9d3f227 967 int ret, open;
2f75bae1 968 DWORD err;
b675c612 969 char buf[20480]; /* nice big buffer for plenty of speed */
7e78000d 970 Actual_Socket s;
49bad831 971 u_long atmark;
2f75bae1 972
973 /* wParam is the socket itself */
cc8b0ee9 974
975 /*
976 * One user has reported an assertion failure in tree234 which
977 * indicates a null element pointer has been passed to a
978 * find*234 function. The following find234 is the only one in
979 * the whole program that I can see being capable of doing
980 * this, hence I'm forced to conclude that WinSock is capable
981 * of sending me netevent messages with wParam==0. I want to
982 * know what the rest of the message is if it does so!
983 */
984 if (wParam == 0) {
985 char *str;
986 str = dupprintf("Strange WinSock message: wp=%08x lp=%08x",
987 (int)wParam, (int)lParam);
988 logevent(NULL, str);
989 connection_fatal(NULL, str);
990 sfree(str);
991 }
992
32874aea 993 s = find234(sktree, (void *) wParam, cmpforsearch);
2f75bae1 994 if (!s)
995 return 1; /* boggle */
996
997 if ((err = WSAGETSELECTERROR(lParam)) != 0) {
32874aea 998 /*
999 * An error has occurred on this socket. Pass it to the
1000 * plug.
1001 */
1002 return plug_closing(s->plug, winsock_error_string(err), err, 0);
2f75bae1 1003 }
1004
7d6ee6ff 1005 noise_ultralight(lParam);
1006
2f75bae1 1007 switch (WSAGETSELECTEVENT(lParam)) {
3ad9d396 1008 case FD_CONNECT:
1009 s->connected = s->writable = 1;
1010 break;
2f75bae1 1011 case FD_READ:
d74d141c 1012 /* In the case the socket is still frozen, we don't even bother */
5471d09a 1013 if (s->frozen) {
1014 s->frozen_readable = 1;
d74d141c 1015 break;
5471d09a 1016 }
d74d141c 1017
32874aea 1018 /*
1019 * We have received data on the socket. For an oobinline
1020 * socket, this might be data _before_ an urgent pointer,
1021 * in which case we send it to the back end with type==1
1022 * (data prior to urgent).
1023 */
1024 if (s->oobinline) {
1025 atmark = 1;
1026 ioctlsocket(s->s, SIOCATMARK, &atmark);
1027 /*
1028 * Avoid checking the return value from ioctlsocket(),
1029 * on the grounds that some WinSock wrappers don't
1030 * support it. If it does nothing, we get atmark==1,
1031 * which is equivalent to `no OOB pending', so the
1032 * effect will be to non-OOB-ify any OOB data.
1033 */
1034 } else
1035 atmark = 1;
4b1e8acc 1036
2f75bae1 1037 ret = recv(s->s, buf, sizeof(buf), 0);
32874aea 1038 noise_ultralight(ret);
2f75bae1 1039 if (ret < 0) {
1040 err = WSAGetLastError();
1041 if (err == WSAEWOULDBLOCK) {
1042 break;
1043 }
1044 }
1045 if (ret < 0) {
32874aea 1046 return plug_closing(s->plug, winsock_error_string(err), err,
1047 0);
7e78000d 1048 } else if (0 == ret) {
32874aea 1049 return plug_closing(s->plug, NULL, 0, 0);
2f75bae1 1050 } else {
32874aea 1051 return plug_receive(s->plug, atmark ? 0 : 1, buf, ret);
2f75bae1 1052 }
1053 break;
1054 case FD_OOB:
32874aea 1055 /*
1056 * This will only happen on a non-oobinline socket. It
1057 * indicates that we can immediately perform an OOB read
1058 * and get back OOB data, which we will send to the back
1059 * end with type==2 (urgent data).
1060 */
1061 ret = recv(s->s, buf, sizeof(buf), MSG_OOB);
1062 noise_ultralight(ret);
1063 if (ret <= 0) {
247308b5 1064 char *str = (ret == 0 ? "Internal networking trouble" :
1065 winsock_error_string(WSAGetLastError()));
a8327734 1066 /* We're inside the Windows frontend here, so we know
1067 * that the frontend handle is unnecessary. */
1068 logevent(NULL, str);
247308b5 1069 fatalbox("%s", str);
32874aea 1070 } else {
1071 return plug_receive(s->plug, 2, buf, ret);
1072 }
1073 break;
2f75bae1 1074 case FD_WRITE:
5471d09a 1075 {
1076 int bufsize_before, bufsize_after;
1077 s->writable = 1;
1078 bufsize_before = s->sending_oob + bufchain_size(&s->output_data);
1079 try_send(s);
1080 bufsize_after = s->sending_oob + bufchain_size(&s->output_data);
1081 if (bufsize_after < bufsize_before)
1082 plug_sent(s->plug, bufsize_after);
1083 }
2f75bae1 1084 break;
1085 case FD_CLOSE:
f9d3f227 1086 /* Signal a close on the socket. First read any outstanding data. */
32874aea 1087 open = 1;
1088 do {
1089 ret = recv(s->s, buf, sizeof(buf), 0);
1090 if (ret < 0) {
1091 err = WSAGetLastError();
1092 if (err == WSAEWOULDBLOCK)
1093 break;
1094 return plug_closing(s->plug, winsock_error_string(err),
1095 err, 0);
1096 } else {
1097 if (ret)
1098 open &= plug_receive(s->plug, 0, buf, ret);
1099 else
1100 open &= plug_closing(s->plug, NULL, 0, 0);
7e78000d 1101 }
f9d3f227 1102 } while (ret > 0);
32874aea 1103 return open;
d74d141c 1104 case FD_ACCEPT:
1105 {
bc4802a1 1106 struct sockaddr_in isa;
1107 int addrlen = sizeof(struct sockaddr_in);
bcce45ed 1108 SOCKET t; /* socket of connection */
1109
bc4802a1 1110 memset(&isa, 0, sizeof(struct sockaddr_in));
bcce45ed 1111 err = 0;
0e5e7f46 1112 t = accept(s->s,(struct sockaddr *)&isa,&addrlen);
bcce45ed 1113 if (t == INVALID_SOCKET)
1114 {
1115 err = WSAGetLastError();
1116 if (err == WSATRY_AGAIN)
1117 break;
1118 }
1119
6ee9b735 1120 if (s->localhost_only && !ipv4_is_loopback(isa.sin_addr)) {
bc4802a1 1121 closesocket(t); /* dodgy WinSock let nonlocal through */
1122 } else if (plug_accepting(s->plug, (void*)t)) {
bcce45ed 1123 closesocket(t); /* denied or error */
1124 }
d74d141c 1125 }
2f75bae1 1126 }
1127
1128 return 1;
1129}
1130
1131/*
7732d38a 1132 * Deal with socket errors detected in try_send().
1133 */
1134void net_pending_errors(void)
1135{
1136 int i;
1137 Actual_Socket s;
1138
1139 /*
1140 * This might be a fiddly business, because it's just possible
1141 * that handling a pending error on one socket might cause
1142 * others to be closed. (I can't think of any reason this might
1143 * happen in current SSH implementation, but to maintain
1144 * generality of this network layer I'll assume the worst.)
1145 *
1146 * So what we'll do is search the socket list for _one_ socket
1147 * with a pending error, and then handle it, and then search
1148 * the list again _from the beginning_. Repeat until we make a
1149 * pass with no socket errors present. That way we are
1150 * protected against the socket list changing under our feet.
1151 */
1152
1153 do {
1154 for (i = 0; (s = index234(sktree, i)) != NULL; i++) {
1155 if (s->pending_error) {
1156 /*
1157 * An error has occurred on this socket. Pass it to the
1158 * plug.
1159 */
1160 plug_closing(s->plug,
1161 winsock_error_string(s->pending_error),
1162 s->pending_error, 0);
1163 break;
1164 }
1165 }
1166 } while (s);
1167}
1168
1169/*
2f75bae1 1170 * Each socket abstraction contains a `void *' private field in
1171 * which the client can keep state.
1172 */
8eebd221 1173static void sk_tcp_set_private_ptr(Socket sock, void *ptr)
32874aea 1174{
7e78000d 1175 Actual_Socket s = (Actual_Socket) sock;
2f75bae1 1176 s->private_ptr = ptr;
1177}
32874aea 1178
8eebd221 1179static void *sk_tcp_get_private_ptr(Socket sock)
32874aea 1180{
7e78000d 1181 Actual_Socket s = (Actual_Socket) sock;
2f75bae1 1182 return s->private_ptr;
1183}
1184
1185/*
1186 * Special error values are returned from sk_namelookup and sk_new
1187 * if there's a problem. These functions extract an error message,
1188 * or return NULL if there's no problem.
1189 */
32874aea 1190char *sk_addr_error(SockAddr addr)
1191{
2f75bae1 1192 return addr->error;
1193}
32874aea 1194static char *sk_tcp_socket_error(Socket sock)
1195{
7e78000d 1196 Actual_Socket s = (Actual_Socket) sock;
2f75bae1 1197 return s->error;
1198}
1199
8eebd221 1200static void sk_tcp_set_frozen(Socket sock, int is_frozen)
d74d141c 1201{
1202 Actual_Socket s = (Actual_Socket) sock;
5471d09a 1203 if (s->frozen == is_frozen)
1204 return;
d74d141c 1205 s->frozen = is_frozen;
5471d09a 1206 if (!is_frozen && s->frozen_readable) {
d74d141c 1207 char c;
1208 recv(s->s, &c, 1, MSG_PEEK);
1209 }
5471d09a 1210 s->frozen_readable = 0;
d74d141c 1211}
1212
2f75bae1 1213/*
1214 * For Plink: enumerate all sockets currently active.
1215 */
32874aea 1216SOCKET first_socket(int *state)
1217{
d2371c81 1218 Actual_Socket s;
1219 *state = 0;
1220 s = index234(sktree, (*state)++);
2f75bae1 1221 return s ? s->s : INVALID_SOCKET;
1222}
32874aea 1223
1224SOCKET next_socket(int *state)
1225{
d2371c81 1226 Actual_Socket s = index234(sktree, (*state)++);
2f75bae1 1227 return s ? s->s : INVALID_SOCKET;
1228}
68a49acb 1229
1230int net_service_lookup(char *service)
1231{
1232 struct servent *se;
1233 se = getservbyname(service, NULL);
1234 if (se != NULL)
1235 return ntohs(se->s_port);
1236 else
1237 return 0;
1238}