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