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