]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - unix/uxnet.c
Support for falling back through the list of addresses returned from
[PuTTY.git] / unix / uxnet.c
1 /*
2  * Unix networking abstraction.
3  */
4
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <assert.h>
8 #include <errno.h>
9 #include <fcntl.h>
10 #include <unistd.h>
11 #include <sys/types.h>
12 #include <sys/socket.h>
13 #include <sys/ioctl.h>
14 #include <arpa/inet.h>
15 #include <netinet/in.h>
16 #include <netinet/tcp.h>
17 #include <netdb.h>
18 #include <sys/un.h>
19
20 #define DEFINE_PLUG_METHOD_MACROS
21 #include "putty.h"
22 #include "network.h"
23 #include "tree234.h"
24
25 #ifndef X11_UNIX_PATH
26 # define X11_UNIX_PATH "/tmp/.X11-unix/X"
27 #endif
28
29 #define ipv4_is_loopback(addr) (inet_netof(addr) == IN_LOOPBACKNET)
30
31 struct Socket_tag {
32     struct socket_function_table *fn;
33     /* the above variable absolutely *must* be the first in this structure */
34     const char *error;
35     int s;
36     Plug plug;
37     void *private_ptr;
38     bufchain output_data;
39     int connected;
40     int writable;
41     int frozen; /* this causes readability notifications to be ignored */
42     int frozen_readable; /* this means we missed at least one readability
43                           * notification while we were frozen */
44     int localhost_only;                /* for listening sockets */
45     char oobdata[1];
46     int sending_oob;
47     int oobpending;                    /* is there OOB data available to read? */
48     int oobinline;
49     int pending_error;                 /* in case send() returns error */
50     int listener;
51     int nodelay, keepalive;            /* for connect()-type sockets */
52     int privport, port;                /* and again */
53     SockAddr addr;
54 };
55
56 /*
57  * We used to typedef struct Socket_tag *Socket.
58  *
59  * Since we have made the networking abstraction slightly more
60  * abstract, Socket no longer means a tcp socket (it could mean
61  * an ssl socket).  So now we must use Actual_Socket when we know
62  * we are talking about a tcp socket.
63  */
64 typedef struct Socket_tag *Actual_Socket;
65
66 struct SockAddr_tag {
67     const char *error;
68     /*
69      * Which address family this address belongs to. AF_INET for
70      * IPv4; AF_INET6 for IPv6; AF_UNSPEC indicates that name
71      * resolution has not been done and a simple host name is held
72      * in this SockAddr structure.
73      */
74     int family;
75 #ifndef NO_IPV6
76     struct addrinfo *ais;              /* Addresses IPv6 style. */
77     struct addrinfo *ai;               /* steps along the linked list */
78 #else
79     unsigned long *addresses;          /* Addresses IPv4 style. */
80     int naddresses, curraddr;
81 #endif
82     char hostname[512];                /* Store an unresolved host name. */
83 };
84
85 static tree234 *sktree;
86
87 static void uxsel_tell(Actual_Socket s);
88
89 static int cmpfortree(void *av, void *bv)
90 {
91     Actual_Socket a = (Actual_Socket) av, b = (Actual_Socket) bv;
92     int as = a->s, bs = b->s;
93     if (as < bs)
94         return -1;
95     if (as > bs)
96         return +1;
97     return 0;
98 }
99
100 static int cmpforsearch(void *av, void *bv)
101 {
102     Actual_Socket b = (Actual_Socket) bv;
103     int as = *(int *)av, bs = b->s;
104     if (as < bs)
105         return -1;
106     if (as > bs)
107         return +1;
108     return 0;
109 }
110
111 void sk_init(void)
112 {
113     sktree = newtree234(cmpfortree);
114 }
115
116 void sk_cleanup(void)
117 {
118     Actual_Socket s;
119     int i;
120
121     if (sktree) {
122         for (i = 0; (s = index234(sktree, i)) != NULL; i++) {
123             close(s->s);
124         }
125     }
126 }
127
128 SockAddr sk_namelookup(const char *host, char **canonicalname, int address_family)
129 {
130     SockAddr ret = snew(struct SockAddr_tag);
131 #ifndef NO_IPV6
132     struct addrinfo hints;
133     int err;
134 #else
135     unsigned long a;
136     struct hostent *h = NULL;
137     int n;
138 #endif
139     char realhost[8192];
140
141     /* Clear the structure and default to IPv4. */
142     memset(ret, 0, sizeof(struct SockAddr_tag));
143     ret->family = 0;                   /* We set this one when we have resolved the host. */
144     *realhost = '\0';
145     ret->error = NULL;
146
147 #ifndef NO_IPV6
148     hints.ai_flags = AI_CANONNAME;
149     hints.ai_family = (address_family == ADDRTYPE_IPV4 ? AF_INET :
150                        address_family == ADDRTYPE_IPV6 ? AF_INET6 :
151                        AF_UNSPEC);
152     hints.ai_socktype = SOCK_STREAM;
153     hints.ai_protocol = 0;
154     hints.ai_addrlen = 0;
155     hints.ai_addr = NULL;
156     hints.ai_canonname = NULL;
157     hints.ai_next = NULL;
158     err = getaddrinfo(host, NULL, &hints, &ret->ais);
159     ret->ai = ret->ais;
160     if (err != 0) {
161         ret->error = gai_strerror(err);
162         return ret;
163     }
164     ret->family = ret->ai->ai_family;
165     *realhost = '\0';
166     if (ret->ai->ai_canonname != NULL)
167         strncat(realhost, ret->ai->ai_canonname, sizeof(realhost) - 1);
168     else
169         strncat(realhost, host, sizeof(realhost) - 1);
170 #else
171     if ((a = inet_addr(host)) == (unsigned long)(in_addr_t)(-1)) {
172         /*
173          * Otherwise use the IPv4-only gethostbyname... (NOTE:
174          * we don't use gethostbyname as a fallback!)
175          */
176         if (ret->family == 0) {
177             /*debug(("Resolving \"%s\" with gethostbyname() (IPv4 only)...\n", host)); */
178             if ( (h = gethostbyname(host)) )
179                 ret->family = AF_INET;
180         }
181         if (ret->family == 0) {
182             ret->error = (h_errno == HOST_NOT_FOUND ||
183                           h_errno == NO_DATA ||
184                           h_errno == NO_ADDRESS ? "Host does not exist" :
185                           h_errno == TRY_AGAIN ?
186                           "Temporary name service failure" :
187                           "gethostbyname: unknown error");
188             return ret;
189         }
190         /* This way we are always sure the h->h_name is valid :) */
191         strncpy(realhost, h->h_name, sizeof(realhost));
192         for (n = 0; h->h_addr_list[n]; n++);
193         ret->addresses = snewn(n, unsigned long);
194         ret->naddresses = n;
195         for (n = 0; n < ret->naddresses; n++) {
196             memcpy(&a, h->h_addr_list[n], sizeof(a));
197             ret->addresses[n] = ntohl(a);
198         }
199     } else {
200         /*
201          * This must be a numeric IPv4 address because it caused a
202          * success return from inet_addr.
203          */
204         ret->family = AF_INET;
205         strncpy(realhost, host, sizeof(realhost));
206         ret->addresses = snew(unsigned long);
207         ret->naddresses = 1;
208         ret->addresses[0] = ntohl(a);
209         ret->curraddr = 0;
210     }
211 #endif
212     realhost[lenof(realhost)-1] = '\0';
213     *canonicalname = snewn(1+strlen(realhost), char);
214     strcpy(*canonicalname, realhost);
215     return ret;
216 }
217
218 SockAddr sk_nonamelookup(const char *host)
219 {
220     SockAddr ret = snew(struct SockAddr_tag);
221     ret->error = NULL;
222     ret->family = AF_UNSPEC;
223     strncpy(ret->hostname, host, lenof(ret->hostname));
224     ret->hostname[lenof(ret->hostname)-1] = '\0';
225 #ifndef NO_IPV6
226     ret->ais = NULL;
227 #else
228     ret->addresses = NULL;
229 #endif
230     return ret;
231 }
232
233 static int sk_nextaddr(SockAddr addr)
234 {
235 #ifndef NO_IPV6
236     if (addr->ai->ai_next) {
237         addr->ai = addr->ai->ai_next;
238         addr->family = addr->ai->ai_family;
239         return TRUE;
240     } else
241         return FALSE;
242 #else
243     if (addr->curraddr+1 < addr->naddresses) {
244         addr->curraddr++;
245         return TRUE;
246     } else {
247         return FALSE;
248     }
249 #endif    
250 }
251
252 void sk_getaddr(SockAddr addr, char *buf, int buflen)
253 {
254
255     if (addr->family == AF_UNSPEC) {
256         strncpy(buf, addr->hostname, buflen);
257         buf[buflen-1] = '\0';
258     } else {
259 #ifndef NO_IPV6
260         if (getnameinfo(addr->ai->ai_addr, addr->ai->ai_addrlen, buf, buflen,
261                         NULL, 0, NI_NUMERICHOST) != 0) {
262             buf[0] = '\0';
263             strncat(buf, "<unknown>", buflen - 1);
264         }
265 #else
266         struct in_addr a;
267         assert(addr->family == AF_INET);
268         a.s_addr = htonl(addr->addresses[addr->curraddr]);
269         strncpy(buf, inet_ntoa(a), buflen);
270         buf[buflen-1] = '\0';
271 #endif
272     }
273 }
274
275 int sk_hostname_is_local(char *name)
276 {
277     return !strcmp(name, "localhost");
278 }
279
280 int sk_address_is_local(SockAddr addr)
281 {
282
283     if (addr->family == AF_UNSPEC)
284         return 0;                      /* we don't know; assume not */
285     else {
286 #ifndef NO_IPV6
287         if (addr->family == AF_INET)
288             return ipv4_is_loopback(
289                 ((struct sockaddr_in *)addr->ai->ai_addr)->sin_addr);
290         else if (addr->family == AF_INET6)
291             return IN6_IS_ADDR_LOOPBACK(
292                 &((struct sockaddr_in6 *)addr->ai->ai_addr)->sin6_addr);
293         else
294             return 0;
295 #else
296         struct in_addr a;
297         assert(addr->family == AF_INET);
298         a.s_addr = htonl(addr->addresses[addr->curraddr]);
299         return ipv4_is_loopback(a);
300 #endif
301     }
302 }
303
304 int sk_addrtype(SockAddr addr)
305 {
306     return (addr->family == AF_INET ? ADDRTYPE_IPV4 :
307 #ifndef NO_IPV6
308             addr->family == AF_INET6 ? ADDRTYPE_IPV6 :
309 #endif
310             ADDRTYPE_NAME);
311 }
312
313 void sk_addrcopy(SockAddr addr, char *buf)
314 {
315
316 #ifndef NO_IPV6
317     if (addr->family == AF_INET)
318         memcpy(buf, &((struct sockaddr_in *)addr->ai->ai_addr)->sin_addr,
319                sizeof(struct in_addr));
320     else if (addr->family == AF_INET6)
321         memcpy(buf, &((struct sockaddr_in6 *)addr->ai->ai_addr)->sin6_addr,
322                sizeof(struct in6_addr));
323     else
324         assert(FALSE);
325 #else
326     struct in_addr a;
327
328     assert(addr->family == AF_INET);
329     a.s_addr = htonl(addr->addresses[addr->curraddr]);
330     memcpy(buf, (char*) &a.s_addr, 4);
331 #endif
332 }
333
334 void sk_addr_free(SockAddr addr)
335 {
336
337 #ifndef NO_IPV6
338     if (addr->ais != NULL)
339         freeaddrinfo(addr->ais);
340 #else
341     sfree(addr->addresses);
342 #endif
343     sfree(addr);
344 }
345
346 static Plug sk_tcp_plug(Socket sock, Plug p)
347 {
348     Actual_Socket s = (Actual_Socket) sock;
349     Plug ret = s->plug;
350     if (p)
351         s->plug = p;
352     return ret;
353 }
354
355 static void sk_tcp_flush(Socket s)
356 {
357     /*
358      * We send data to the socket as soon as we can anyway,
359      * so we don't need to do anything here.  :-)
360      */
361 }
362
363 static void sk_tcp_close(Socket s);
364 static int sk_tcp_write(Socket s, const char *data, int len);
365 static int sk_tcp_write_oob(Socket s, const char *data, int len);
366 static void sk_tcp_set_private_ptr(Socket s, void *ptr);
367 static void *sk_tcp_get_private_ptr(Socket s);
368 static void sk_tcp_set_frozen(Socket s, int is_frozen);
369 static const char *sk_tcp_socket_error(Socket s);
370
371 static struct socket_function_table tcp_fn_table = {
372     sk_tcp_plug,
373     sk_tcp_close,
374     sk_tcp_write,
375     sk_tcp_write_oob,
376     sk_tcp_flush,
377     sk_tcp_set_private_ptr,
378     sk_tcp_get_private_ptr,
379     sk_tcp_set_frozen,
380     sk_tcp_socket_error
381 };
382
383 Socket sk_register(OSSocket sockfd, Plug plug)
384 {
385     Actual_Socket ret;
386
387     /*
388      * Create Socket structure.
389      */
390     ret = snew(struct Socket_tag);
391     ret->fn = &tcp_fn_table;
392     ret->error = NULL;
393     ret->plug = plug;
394     bufchain_init(&ret->output_data);
395     ret->writable = 1;                 /* to start with */
396     ret->sending_oob = 0;
397     ret->frozen = 1;
398     ret->frozen_readable = 0;
399     ret->localhost_only = 0;           /* unused, but best init anyway */
400     ret->pending_error = 0;
401     ret->oobpending = FALSE;
402     ret->listener = 0;
403     ret->addr = NULL;
404
405     ret->s = sockfd;
406
407     if (ret->s < 0) {
408         ret->error = strerror(errno);
409         return (Socket) ret;
410     }
411
412     ret->oobinline = 0;
413
414     uxsel_tell(ret);
415     add234(sktree, ret);
416
417     return (Socket) ret;
418 }
419
420 static int try_connect(Actual_Socket sock)
421 {
422     int s;
423 #ifndef NO_IPV6
424     struct sockaddr_in6 a6;
425 #endif
426     struct sockaddr_in a;
427     struct sockaddr_un au;
428     const struct sockaddr *sa;
429     int err = 0;
430     short localport;
431     int fl, salen;
432
433     if (sock->s >= 0)
434         close(sock->s);
435
436     plug_log(sock->plug, 0, sock->addr, sock->port, NULL, 0);
437
438     /*
439      * Open socket.
440      */
441     assert(sock->addr->family != AF_UNSPEC);
442     s = socket(sock->addr->family, SOCK_STREAM, 0);
443     sock->s = s;
444
445     if (s < 0) {
446         err = errno;
447         goto ret;
448     }
449
450     if (sock->oobinline) {
451         int b = TRUE;
452         setsockopt(s, SOL_SOCKET, SO_OOBINLINE, (void *) &b, sizeof(b));
453     }
454
455     if (sock->nodelay) {
456         int b = TRUE;
457         setsockopt(s, IPPROTO_TCP, TCP_NODELAY, (void *) &b, sizeof(b));
458     }
459
460     if (sock->keepalive) {
461         int b = TRUE;
462         setsockopt(s, SOL_SOCKET, SO_KEEPALIVE, (void *) &b, sizeof(b));
463     }
464
465     /*
466      * Bind to local address.
467      */
468     if (sock->privport)
469         localport = 1023;              /* count from 1023 downwards */
470     else
471         localport = 0;                 /* just use port 0 (ie kernel picks) */
472
473     /* BSD IP stacks need sockaddr_in zeroed before filling in */
474     memset(&a,'\0',sizeof(struct sockaddr_in));
475 #ifndef NO_IPV6
476     memset(&a6,'\0',sizeof(struct sockaddr_in6));
477 #endif
478
479     /* We don't try to bind to a local address for UNIX domain sockets.  (Why
480      * do we bother doing the bind when localport == 0 anyway?) */
481     if(sock->addr->family != AF_UNIX) {
482         /* Loop round trying to bind */
483         while (1) {
484             int retcode;
485
486 #ifndef NO_IPV6
487             if (sock->addr->family == AF_INET6) {
488                 /* XXX use getaddrinfo to get a local address? */
489                 a6.sin6_family = AF_INET6;
490                 a6.sin6_addr = in6addr_any;
491                 a6.sin6_port = htons(localport);
492                 retcode = bind(s, (struct sockaddr *) &a6, sizeof(a6));
493             } else
494 #endif
495             {
496                 assert(sock->addr->family == AF_INET);
497                 a.sin_family = AF_INET;
498                 a.sin_addr.s_addr = htonl(INADDR_ANY);
499                 a.sin_port = htons(localport);
500                 retcode = bind(s, (struct sockaddr *) &a, sizeof(a));
501             }
502             if (retcode >= 0) {
503                 err = 0;
504                 break;                 /* done */
505             } else {
506                 err = errno;
507                 if (err != EADDRINUSE) /* failed, for a bad reason */
508                   break;
509             }
510             
511             if (localport == 0)
512               break;                   /* we're only looping once */
513             localport--;
514             if (localport == 0)
515               break;                   /* we might have got to the end */
516         }
517         
518         if (err)
519             goto ret;
520     }
521
522     /*
523      * Connect to remote address.
524      */
525     switch(sock->addr->family) {
526 #ifndef NO_IPV6
527       case AF_INET:
528         /* XXX would be better to have got getaddrinfo() to fill in the port. */
529         ((struct sockaddr_in *)sock->addr->ai->ai_addr)->sin_port =
530             htons(sock->port);
531         sa = (const struct sockaddr *)sock->addr->ai->ai_addr;
532         salen = sock->addr->ai->ai_addrlen;
533         break;
534       case AF_INET6:
535         ((struct sockaddr_in *)sock->addr->ai->ai_addr)->sin_port =
536             htons(sock->port);
537         sa = (const struct sockaddr *)sock->addr->ai->ai_addr;
538         salen = sock->addr->ai->ai_addrlen;
539         break;
540 #else
541       case AF_INET:
542         a.sin_family = AF_INET;
543         a.sin_addr.s_addr = htonl(sock->addr->addresses[sock->addr->curraddr]);
544         a.sin_port = htons((short) sock->port);
545         sa = (const struct sockaddr *)&a;
546         salen = sizeof a;
547         break;
548 #endif
549       case AF_UNIX:
550         assert(sock->port == 0);       /* to catch confused people */
551         assert(strlen(sock->addr->hostname) < sizeof au.sun_path);
552         memset(&au, 0, sizeof au);
553         au.sun_family = AF_UNIX;
554         strcpy(au.sun_path, sock->addr->hostname);
555         sa = (const struct sockaddr *)&au;
556         salen = sizeof au;
557         break;
558
559       default:
560         assert(0 && "unknown address family");
561     }
562
563     fl = fcntl(s, F_GETFL);
564     if (fl != -1)
565         fcntl(s, F_SETFL, fl | O_NONBLOCK);
566
567     if ((connect(s, sa, salen)) < 0) {
568         if ( errno != EINPROGRESS ) {
569             err = errno;
570             goto ret;
571         }
572     } else {
573         /*
574          * If we _don't_ get EWOULDBLOCK, the connect has completed
575          * and we should set the socket as connected and writable.
576          */
577         sock->connected = 1;
578         sock->writable = 1;
579     }
580
581     uxsel_tell(sock);
582     add234(sktree, sock);
583
584     ret:
585     if (err)
586         plug_log(sock->plug, 1, sock->addr, sock->port, strerror(err), err);
587     return err;
588 }
589
590 Socket sk_new(SockAddr addr, int port, int privport, int oobinline,
591               int nodelay, int keepalive, Plug plug)
592 {
593     Actual_Socket ret;
594     int err;
595
596     /*
597      * Create Socket structure.
598      */
599     ret = snew(struct Socket_tag);
600     ret->fn = &tcp_fn_table;
601     ret->error = NULL;
602     ret->plug = plug;
603     bufchain_init(&ret->output_data);
604     ret->connected = 0;                /* to start with */
605     ret->writable = 0;                 /* to start with */
606     ret->sending_oob = 0;
607     ret->frozen = 0;
608     ret->frozen_readable = 0;
609     ret->localhost_only = 0;           /* unused, but best init anyway */
610     ret->pending_error = 0;
611     ret->oobpending = FALSE;
612     ret->listener = 0;
613     ret->addr = addr;
614     ret->s = -1;
615     ret->oobinline = oobinline;
616     ret->nodelay = nodelay;
617     ret->keepalive = keepalive;
618     ret->privport = privport;
619     ret->port = port;
620
621     err = 0;
622     do {
623         err = try_connect(ret);
624     } while (err && sk_nextaddr(ret->addr));
625
626     if (err)
627         ret->error = strerror(err);
628
629     return (Socket) ret;
630 }
631
632 Socket sk_newlistener(char *srcaddr, int port, Plug plug, int local_host_only, int address_family)
633 {
634     int s;
635 #ifndef NO_IPV6
636     struct addrinfo hints, *ai;
637     char portstr[6];
638     struct sockaddr_in6 a6;
639 #endif
640     struct sockaddr *addr;
641     int addrlen;
642     struct sockaddr_in a;
643     Actual_Socket ret;
644     int retcode;
645     int on = 1;
646
647     /*
648      * Create Socket structure.
649      */
650     ret = snew(struct Socket_tag);
651     ret->fn = &tcp_fn_table;
652     ret->error = NULL;
653     ret->plug = plug;
654     bufchain_init(&ret->output_data);
655     ret->writable = 0;                 /* to start with */
656     ret->sending_oob = 0;
657     ret->frozen = 0;
658     ret->frozen_readable = 0;
659     ret->localhost_only = local_host_only;
660     ret->pending_error = 0;
661     ret->oobpending = FALSE;
662     ret->listener = 1;
663     ret->addr = NULL;
664
665     /*
666      * Translate address_family from platform-independent constants
667      * into local reality.
668      */
669     address_family = (address_family == ADDRTYPE_IPV4 ? AF_INET :
670                       address_family == ADDRTYPE_IPV6 ? AF_INET6 : AF_UNSPEC);
671
672 #ifndef NO_IPV6
673     /* Let's default to IPv6.
674      * If the stack doesn't support IPv6, we will fall back to IPv4. */
675     if (address_family == AF_UNSPEC) address_family = AF_INET6;
676 #else
677     /* No other choice, default to IPv4 */
678     if (address_family == AF_UNSPEC)  address_family = AF_INET;
679 #endif
680
681     /*
682      * Open socket.
683      */
684     s = socket(address_family, SOCK_STREAM, 0);
685
686     /* If the host doesn't support IPv6 try fallback to IPv4. */
687     if (s < 0 && address_family == AF_INET6) {
688         address_family = AF_INET;
689         s = socket(address_family, SOCK_STREAM, 0);
690     }
691
692     if (s < 0) {
693         ret->error = strerror(errno);
694         return (Socket) ret;
695     }
696
697     ret->oobinline = 0;
698
699     setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (const char *)&on, sizeof(on));
700
701     retcode = -1;
702     addr = NULL; addrlen = -1;         /* placate optimiser */
703
704     if (srcaddr != NULL) {
705 #ifndef NO_IPV6
706         hints.ai_flags = AI_NUMERICHOST;
707         hints.ai_family = address_family;
708         hints.ai_socktype = 0;
709         hints.ai_protocol = 0;
710         hints.ai_addrlen = 0;
711         hints.ai_addr = NULL;
712         hints.ai_canonname = NULL;
713         hints.ai_next = NULL;
714         sprintf(portstr, "%d", port);
715         retcode = getaddrinfo(srcaddr, portstr, &hints, &ai);
716         addr = ai->ai_addr;
717         addrlen = ai->ai_addrlen;
718 #else
719         memset(&a,'\0',sizeof(struct sockaddr_in));
720         a.sin_family = AF_INET;
721         a.sin_port = htons(port);
722         a.sin_addr.s_addr = inet_addr(srcaddr);
723         if (a.sin_addr.s_addr != (in_addr_t)(-1)) {
724             /* Override localhost_only with specified listen addr. */
725             ret->localhost_only = ipv4_is_loopback(a.sin_addr);
726             got_addr = 1;
727         }
728         addr = (struct sockaddr *)a;
729         addrlen = sizeof(a);
730         retcode = 0;
731 #endif
732     }
733
734     if (retcode != 0) {
735 #ifndef NO_IPV6
736         if (address_family == AF_INET6) {
737             memset(&a6,'\0',sizeof(struct sockaddr_in6));
738             a6.sin6_family = AF_INET6;
739             a6.sin6_port = htons(port);
740             if (local_host_only)
741                 a6.sin6_addr = in6addr_loopback;
742             else
743                 a6.sin6_addr = in6addr_any;
744             addr = (struct sockaddr *)&a6;
745             addrlen = sizeof(a6);
746         } else
747 #endif
748         {
749             memset(&a,'\0',sizeof(struct sockaddr_in));
750             a.sin_family = AF_INET;
751             a.sin_port = htons(port);
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             addr = (struct sockaddr *)&a;
757             addrlen = sizeof(a);
758         }
759     }
760
761     retcode = bind(s, addr, addrlen);
762     if (retcode < 0) {
763         close(s);
764         ret->error = strerror(errno);
765         return (Socket) ret;
766     }
767
768     if (listen(s, SOMAXCONN) < 0) {
769         close(s);
770         ret->error = strerror(errno);
771         return (Socket) ret;
772     }
773
774     ret->s = s;
775
776     uxsel_tell(ret);
777     add234(sktree, ret);
778
779     return (Socket) ret;
780 }
781
782 static void sk_tcp_close(Socket sock)
783 {
784     Actual_Socket s = (Actual_Socket) sock;
785
786     uxsel_del(s->s);
787     del234(sktree, s);
788     close(s->s);
789     if (s->addr)
790         sk_addr_free(s->addr);
791     sfree(s);
792 }
793
794 int sk_getxdmdata(void *sock, unsigned long *ip, int *port)
795 {
796     Actual_Socket s = (Actual_Socket) sock;
797     struct sockaddr_in addr;
798     socklen_t addrlen;
799
800     /*
801      * We must check that this socket really _is_ an Actual_Socket.
802      */
803     if (s->fn != &tcp_fn_table)
804         return 0;                      /* failure */
805
806     addrlen = sizeof(addr);
807     if (getsockname(s->s, (struct sockaddr *)&addr, &addrlen) < 0)
808         return 0;
809     switch(addr.sin_family) {
810       case AF_INET:
811         *ip = ntohl(addr.sin_addr.s_addr);
812         *port = ntohs(addr.sin_port);
813         break;
814       case AF_UNIX:
815         /*
816          * For a Unix socket, we return 0xFFFFFFFF for the IP address and
817          * our current pid for the port. Bizarre, but such is life.
818          */
819         *ip = ntohl(0xFFFFFFFF);
820         *port = getpid();
821         break;
822
823         /* XXX IPV6 */
824
825       default:
826         return 0;
827     }
828
829     return 1;
830 }
831
832 /*
833  * The function which tries to send on a socket once it's deemed
834  * writable.
835  */
836 void try_send(Actual_Socket s)
837 {
838     while (s->sending_oob || bufchain_size(&s->output_data) > 0) {
839         int nsent;
840         int err;
841         void *data;
842         int len, urgentflag;
843
844         if (s->sending_oob) {
845             urgentflag = MSG_OOB;
846             len = s->sending_oob;
847             data = &s->oobdata;
848         } else {
849             urgentflag = 0;
850             bufchain_prefix(&s->output_data, &data, &len);
851         }
852         nsent = send(s->s, data, len, urgentflag);
853         noise_ultralight(nsent);
854         if (nsent <= 0) {
855             err = (nsent < 0 ? errno : 0);
856             if (err == EWOULDBLOCK) {
857                 /*
858                  * Perfectly normal: we've sent all we can for the moment.
859                  */
860                 s->writable = FALSE;
861                 return;
862             } else if (nsent == 0 ||
863                        err == ECONNABORTED || err == ECONNRESET) {
864                 /*
865                  * If send() returns CONNABORTED or CONNRESET, we
866                  * unfortunately can't just call plug_closing(),
867                  * because it's quite likely that we're currently
868                  * _in_ a call from the code we'd be calling back
869                  * to, so we'd have to make half the SSH code
870                  * reentrant. Instead we flag a pending error on
871                  * the socket, to be dealt with (by calling
872                  * plug_closing()) at some suitable future moment.
873                  */
874                 s->pending_error = err;
875                 return;
876             } else {
877                 /* We're inside the Unix frontend here, so we know
878                  * that the frontend handle is unnecessary. */
879                 logevent(NULL, strerror(err));
880                 fatalbox("%s", strerror(err));
881             }
882         } else {
883             if (s->sending_oob) {
884                 if (nsent < len) {
885                     memmove(s->oobdata, s->oobdata+nsent, len-nsent);
886                     s->sending_oob = len - nsent;
887                 } else {
888                     s->sending_oob = 0;
889                 }
890             } else {
891                 bufchain_consume(&s->output_data, nsent);
892             }
893         }
894     }
895     uxsel_tell(s);
896 }
897
898 static int sk_tcp_write(Socket sock, const char *buf, int len)
899 {
900     Actual_Socket s = (Actual_Socket) sock;
901
902     /*
903      * Add the data to the buffer list on the socket.
904      */
905     bufchain_add(&s->output_data, buf, len);
906
907     /*
908      * Now try sending from the start of the buffer list.
909      */
910     if (s->writable)
911         try_send(s);
912
913     /*
914      * Update the select() status to correctly reflect whether or
915      * not we should be selecting for write.
916      */
917     uxsel_tell(s);
918
919     return bufchain_size(&s->output_data);
920 }
921
922 static int sk_tcp_write_oob(Socket sock, const char *buf, int len)
923 {
924     Actual_Socket s = (Actual_Socket) sock;
925
926     /*
927      * Replace the buffer list on the socket with the data.
928      */
929     bufchain_clear(&s->output_data);
930     assert(len <= sizeof(s->oobdata));
931     memcpy(s->oobdata, buf, len);
932     s->sending_oob = len;
933
934     /*
935      * Now try sending from the start of the buffer list.
936      */
937     if (s->writable)
938         try_send(s);
939
940     /*
941      * Update the select() status to correctly reflect whether or
942      * not we should be selecting for write.
943      */
944     uxsel_tell(s);
945
946     return s->sending_oob;
947 }
948
949 static int net_select_result(int fd, int event)
950 {
951     int ret;
952     int err;
953     char buf[20480];                   /* nice big buffer for plenty of speed */
954     Actual_Socket s;
955     u_long atmark;
956
957     /* Find the Socket structure */
958     s = find234(sktree, &fd, cmpforsearch);
959     if (!s)
960         return 1;                      /* boggle */
961
962     noise_ultralight(event);
963
964     switch (event) {
965       case 4:                          /* exceptional */
966         if (!s->oobinline) {
967             /*
968              * On a non-oobinline socket, this indicates that we
969              * can immediately perform an OOB read and get back OOB
970              * data, which we will send to the back end with
971              * type==2 (urgent data).
972              */
973             ret = recv(s->s, buf, sizeof(buf), MSG_OOB);
974             noise_ultralight(ret);
975             if (ret <= 0) {
976                 const char *str = (ret == 0 ? "Internal networking trouble" :
977                                    strerror(errno));
978                 /* We're inside the Unix frontend here, so we know
979                  * that the frontend handle is unnecessary. */
980                 logevent(NULL, str);
981                 fatalbox("%s", str);
982             } else {
983                 /*
984                  * Receiving actual data on a socket means we can
985                  * stop falling back through the candidate
986                  * addresses to connect to.
987                  */
988                 if (s->addr) {
989                     sk_addr_free(s->addr);
990                     s->addr = NULL;
991                 }
992                 return plug_receive(s->plug, 2, buf, ret);
993             }
994             break;
995         }
996
997         /*
998          * If we reach here, this is an oobinline socket, which
999          * means we should set s->oobpending and then deal with it
1000          * when we get called for the readability event (which
1001          * should also occur).
1002          */
1003         s->oobpending = TRUE;
1004         break;
1005       case 1:                          /* readable; also acceptance */
1006         if (s->listener) {
1007             /*
1008              * On a listening socket, the readability event means a
1009              * connection is ready to be accepted.
1010              */
1011             struct sockaddr_in isa;
1012             int addrlen = sizeof(struct sockaddr_in);
1013             int t;  /* socket of connection */
1014
1015             memset(&isa, 0, sizeof(struct sockaddr_in));
1016             err = 0;
1017             t = accept(s->s,(struct sockaddr *)&isa,(socklen_t *) &addrlen);
1018             if (t < 0) {
1019                 break;
1020             }
1021
1022             if (s->localhost_only && !ipv4_is_loopback(isa.sin_addr)) {
1023                 close(t);              /* someone let nonlocal through?! */
1024             } else if (plug_accepting(s->plug, t)) {
1025                 close(t);              /* denied or error */
1026             }
1027             break;
1028         }
1029
1030         /*
1031          * If we reach here, this is not a listening socket, so
1032          * readability really means readability.
1033          */
1034
1035         /* In the case the socket is still frozen, we don't even bother */
1036         if (s->frozen) {
1037             s->frozen_readable = 1;
1038             break;
1039         }
1040
1041         /*
1042          * We have received data on the socket. For an oobinline
1043          * socket, this might be data _before_ an urgent pointer,
1044          * in which case we send it to the back end with type==1
1045          * (data prior to urgent).
1046          */
1047         if (s->oobinline && s->oobpending) {
1048             atmark = 1;
1049             if (ioctl(s->s, SIOCATMARK, &atmark) == 0 && atmark)
1050                 s->oobpending = FALSE; /* clear this indicator */
1051         } else
1052             atmark = 1;
1053
1054         ret = recv(s->s, buf, s->oobpending ? 1 : sizeof(buf), 0);
1055         noise_ultralight(ret);
1056         if (ret < 0) {
1057             if (errno == EWOULDBLOCK) {
1058                 break;
1059             }
1060         }
1061         if (ret < 0) {
1062             /*
1063              * An error at this point _might_ be an error reported
1064              * by a non-blocking connect(). So before we return a
1065              * panic status to the user, let's just see whether
1066              * that's the case.
1067              */
1068             int err = errno;
1069             if (s->addr) {
1070                 plug_log(s->plug, 1, s->addr, s->port, strerror(err), err);
1071                 while (s->addr && sk_nextaddr(s->addr)) {
1072                     err = try_connect(s);
1073                 }
1074             }
1075             if (err != 0)
1076                 return plug_closing(s->plug, strerror(err), err, 0);
1077         } else if (0 == ret) {
1078             return plug_closing(s->plug, NULL, 0, 0);
1079         } else {
1080             /*
1081              * Receiving actual data on a socket means we can
1082              * stop falling back through the candidate
1083              * addresses to connect to.
1084              */
1085             if (s->addr) {
1086                 sk_addr_free(s->addr);
1087                 s->addr = NULL;
1088             }
1089             return plug_receive(s->plug, atmark ? 0 : 1, buf, ret);
1090         }
1091         break;
1092       case 2:                          /* writable */
1093         if (!s->connected) {
1094             /*
1095              * select() reports a socket as _writable_ when an
1096              * asynchronous connection is completed.
1097              */
1098             s->connected = s->writable = 1;
1099             uxsel_tell(s);
1100             break;
1101         } else {
1102             int bufsize_before, bufsize_after;
1103             s->writable = 1;
1104             bufsize_before = s->sending_oob + bufchain_size(&s->output_data);
1105             try_send(s);
1106             bufsize_after = s->sending_oob + bufchain_size(&s->output_data);
1107             if (bufsize_after < bufsize_before)
1108                 plug_sent(s->plug, bufsize_after);
1109         }
1110         break;
1111     }
1112
1113     return 1;
1114 }
1115
1116 /*
1117  * Deal with socket errors detected in try_send().
1118  */
1119 void net_pending_errors(void)
1120 {
1121     int i;
1122     Actual_Socket s;
1123
1124     /*
1125      * This might be a fiddly business, because it's just possible
1126      * that handling a pending error on one socket might cause
1127      * others to be closed. (I can't think of any reason this might
1128      * happen in current SSH implementation, but to maintain
1129      * generality of this network layer I'll assume the worst.)
1130      * 
1131      * So what we'll do is search the socket list for _one_ socket
1132      * with a pending error, and then handle it, and then search
1133      * the list again _from the beginning_. Repeat until we make a
1134      * pass with no socket errors present. That way we are
1135      * protected against the socket list changing under our feet.
1136      */
1137
1138     do {
1139         for (i = 0; (s = index234(sktree, i)) != NULL; i++) {
1140             if (s->pending_error) {
1141                 /*
1142                  * An error has occurred on this socket. Pass it to the
1143                  * plug.
1144                  */
1145                 plug_closing(s->plug, strerror(s->pending_error),
1146                              s->pending_error, 0);
1147                 break;
1148             }
1149         }
1150     } while (s);
1151 }
1152
1153 /*
1154  * Each socket abstraction contains a `void *' private field in
1155  * which the client can keep state.
1156  */
1157 static void sk_tcp_set_private_ptr(Socket sock, void *ptr)
1158 {
1159     Actual_Socket s = (Actual_Socket) sock;
1160     s->private_ptr = ptr;
1161 }
1162
1163 static void *sk_tcp_get_private_ptr(Socket sock)
1164 {
1165     Actual_Socket s = (Actual_Socket) sock;
1166     return s->private_ptr;
1167 }
1168
1169 /*
1170  * Special error values are returned from sk_namelookup and sk_new
1171  * if there's a problem. These functions extract an error message,
1172  * or return NULL if there's no problem.
1173  */
1174 const char *sk_addr_error(SockAddr addr)
1175 {
1176     return addr->error;
1177 }
1178 static const char *sk_tcp_socket_error(Socket sock)
1179 {
1180     Actual_Socket s = (Actual_Socket) sock;
1181     return s->error;
1182 }
1183
1184 static void sk_tcp_set_frozen(Socket sock, int is_frozen)
1185 {
1186     Actual_Socket s = (Actual_Socket) sock;
1187     if (s->frozen == is_frozen)
1188         return;
1189     s->frozen = is_frozen;
1190     if (!is_frozen && s->frozen_readable) {
1191         char c;
1192         recv(s->s, &c, 1, MSG_PEEK);
1193     }
1194     s->frozen_readable = 0;
1195     uxsel_tell(s);
1196 }
1197
1198 static void uxsel_tell(Actual_Socket s)
1199 {
1200     int rwx = 0;
1201     if (!s->connected)
1202         rwx |= 2;                      /* write == connect */
1203     if (s->connected && !s->frozen)
1204         rwx |= 1 | 4;                  /* read, except */
1205     if (bufchain_size(&s->output_data))
1206         rwx |= 2;                      /* write */
1207     if (s->listener)
1208         rwx |= 1;                      /* read == accept */
1209     uxsel_set(s->s, rwx, net_select_result);
1210 }
1211
1212 int net_service_lookup(char *service)
1213 {
1214     struct servent *se;
1215     se = getservbyname(service, NULL);
1216     if (se != NULL)
1217         return ntohs(se->s_port);
1218     else
1219         return 0;
1220 }
1221
1222 SockAddr platform_get_x11_unix_address(int displaynum, char **canonicalname)
1223 {
1224     SockAddr ret = snew(struct SockAddr_tag);
1225     int n;
1226
1227     memset(ret, 0, sizeof *ret);
1228     ret->family = AF_UNIX;
1229     n = snprintf(ret->hostname, sizeof ret->hostname,
1230                  "%s%d", X11_UNIX_PATH, displaynum);
1231     if(n < 0)
1232         ret->error = "snprintf failed";
1233     else if(n >= sizeof ret->hostname)
1234         ret->error = "X11 UNIX name too long";
1235     else
1236         *canonicalname = dupstr(ret->hostname);
1237 #ifndef NO_IPV6
1238     ret->ais = NULL;
1239 #else
1240     ret->addresses = NULL;
1241 #endif
1242     return ret;
1243 }