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