]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - unix/uxnet.c
Fix warnings when compiling with -DNO_IPV6.
[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 /* Solaris needs <sys/sockio.h> for SIOCATMARK. */
26 #ifndef SIOCATMARK
27 #include <sys/sockio.h>
28 #endif
29
30 #ifndef X11_UNIX_PATH
31 # define X11_UNIX_PATH "/tmp/.X11-unix/X"
32 #endif
33
34 /* 
35  * Access to sockaddr types without breaking C strict aliasing rules.
36  */
37 union sockaddr_union {
38 #ifdef NO_IPV6
39     struct sockaddr_in storage;
40 #else
41     struct sockaddr_storage storage;
42     struct sockaddr_in6 sin6;
43 #endif
44     struct sockaddr sa;
45     struct sockaddr_in sin;
46     struct sockaddr_un su;
47 };
48
49 /*
50  * We used to typedef struct Socket_tag *Socket.
51  *
52  * Since we have made the networking abstraction slightly more
53  * abstract, Socket no longer means a tcp socket (it could mean
54  * an ssl socket).  So now we must use Actual_Socket when we know
55  * we are talking about a tcp socket.
56  */
57 typedef struct Socket_tag *Actual_Socket;
58
59 /*
60  * Mutable state that goes with a SockAddr: stores information
61  * about where in the list of candidate IP(v*) addresses we've
62  * currently got to.
63  */
64 typedef struct SockAddrStep_tag SockAddrStep;
65 struct SockAddrStep_tag {
66 #ifndef NO_IPV6
67     struct addrinfo *ai;               /* steps along addr->ais */
68 #endif
69     int curraddr;
70 };
71
72 struct Socket_tag {
73     struct socket_function_table *fn;
74     /* the above variable absolutely *must* be the first in this structure */
75     const char *error;
76     int s;
77     Plug plug;
78     bufchain output_data;
79     int connected;                     /* irrelevant for listening sockets */
80     int writable;
81     int frozen; /* this causes readability notifications to be ignored */
82     int localhost_only;                /* for listening sockets */
83     char oobdata[1];
84     int sending_oob;
85     int oobpending;                    /* is there OOB data available to read? */
86     int oobinline;
87     enum { EOF_NO, EOF_PENDING, EOF_SENT } outgoingeof;
88     int incomingeof;
89     int pending_error;                 /* in case send() returns error */
90     int listener;
91     int nodelay, keepalive;            /* for connect()-type sockets */
92     int privport, port;                /* and again */
93     SockAddr addr;
94     SockAddrStep step;
95     /*
96      * We sometimes need pairs of Socket structures to be linked:
97      * if we are listening on the same IPv6 and v4 port, for
98      * example. So here we define `parent' and `child' pointers to
99      * track this link.
100      */
101     Actual_Socket parent, child;
102 };
103
104 struct SockAddr_tag {
105     int refcount;
106     const char *error;
107     enum { UNRESOLVED, UNIX, IP } superfamily;
108 #ifndef NO_IPV6
109     struct addrinfo *ais;              /* Addresses IPv6 style. */
110 #else
111     unsigned long *addresses;          /* Addresses IPv4 style. */
112     int naddresses;
113 #endif
114     char hostname[512];                /* Store an unresolved host name. */
115 };
116
117 /*
118  * Which address family this address belongs to. AF_INET for IPv4;
119  * AF_INET6 for IPv6; AF_UNSPEC indicates that name resolution has
120  * not been done and a simple host name is held in this SockAddr
121  * structure.
122  */
123 #ifndef NO_IPV6
124 #define SOCKADDR_FAMILY(addr, step) \
125     ((addr)->superfamily == UNRESOLVED ? AF_UNSPEC : \
126      (addr)->superfamily == UNIX ? AF_UNIX : \
127      (step).ai ? (step).ai->ai_family : AF_INET)
128 #else
129 #define SOCKADDR_FAMILY(addr, step) \
130     ((addr)->superfamily == UNRESOLVED ? AF_UNSPEC : \
131      (addr)->superfamily == UNIX ? AF_UNIX : AF_INET)
132 #endif
133
134 /*
135  * Start a SockAddrStep structure to step through multiple
136  * addresses.
137  */
138 #ifndef NO_IPV6
139 #define START_STEP(addr, step) \
140     ((step).ai = (addr)->ais, (step).curraddr = 0)
141 #else
142 #define START_STEP(addr, step) \
143     ((step).curraddr = 0)
144 #endif
145
146 static tree234 *sktree;
147
148 static void uxsel_tell(Actual_Socket s);
149
150 static int cmpfortree(void *av, void *bv)
151 {
152     Actual_Socket a = (Actual_Socket) av, b = (Actual_Socket) bv;
153     int as = a->s, bs = b->s;
154     if (as < bs)
155         return -1;
156     if (as > bs)
157         return +1;
158     if (a < b)
159        return -1;
160     if (a > b)
161        return +1;
162     return 0;
163 }
164
165 static int cmpforsearch(void *av, void *bv)
166 {
167     Actual_Socket b = (Actual_Socket) bv;
168     int as = *(int *)av, bs = b->s;
169     if (as < bs)
170         return -1;
171     if (as > bs)
172         return +1;
173     return 0;
174 }
175
176 void sk_init(void)
177 {
178     sktree = newtree234(cmpfortree);
179 }
180
181 void sk_cleanup(void)
182 {
183     Actual_Socket s;
184     int i;
185
186     if (sktree) {
187         for (i = 0; (s = index234(sktree, i)) != NULL; i++) {
188             close(s->s);
189         }
190     }
191 }
192
193 SockAddr sk_namelookup(const char *host, char **canonicalname, int address_family)
194 {
195     SockAddr ret = snew(struct SockAddr_tag);
196 #ifndef NO_IPV6
197     struct addrinfo hints;
198     int err;
199 #else
200     unsigned long a;
201     struct hostent *h = NULL;
202     int n;
203 #endif
204     char realhost[8192];
205
206     /* Clear the structure and default to IPv4. */
207     memset(ret, 0, sizeof(struct SockAddr_tag));
208     ret->superfamily = UNRESOLVED;
209     *realhost = '\0';
210     ret->error = NULL;
211     ret->refcount = 1;
212
213 #ifndef NO_IPV6
214     hints.ai_flags = AI_CANONNAME;
215     hints.ai_family = (address_family == ADDRTYPE_IPV4 ? AF_INET :
216                        address_family == ADDRTYPE_IPV6 ? AF_INET6 :
217                        AF_UNSPEC);
218     hints.ai_socktype = SOCK_STREAM;
219     hints.ai_protocol = 0;
220     hints.ai_addrlen = 0;
221     hints.ai_addr = NULL;
222     hints.ai_canonname = NULL;
223     hints.ai_next = NULL;
224     {
225         char *trimmed_host = host_strduptrim(host); /* strip [] on literals */
226         err = getaddrinfo(trimmed_host, NULL, &hints, &ret->ais);
227         sfree(trimmed_host);
228     }
229     if (err != 0) {
230         ret->error = gai_strerror(err);
231         return ret;
232     }
233     ret->superfamily = IP;
234     *realhost = '\0';
235     if (ret->ais->ai_canonname != NULL)
236         strncat(realhost, ret->ais->ai_canonname, sizeof(realhost) - 1);
237     else
238         strncat(realhost, host, sizeof(realhost) - 1);
239 #else
240     if ((a = inet_addr(host)) == (unsigned long)(in_addr_t)(-1)) {
241         /*
242          * Otherwise use the IPv4-only gethostbyname... (NOTE:
243          * we don't use gethostbyname as a fallback!)
244          */
245         if (ret->superfamily == UNRESOLVED) {
246             /*debug(("Resolving \"%s\" with gethostbyname() (IPv4 only)...\n", host)); */
247             if ( (h = gethostbyname(host)) )
248                 ret->superfamily = IP;
249         }
250         if (ret->superfamily == UNRESOLVED) {
251             ret->error = (h_errno == HOST_NOT_FOUND ||
252                           h_errno == NO_DATA ||
253                           h_errno == NO_ADDRESS ? "Host does not exist" :
254                           h_errno == TRY_AGAIN ?
255                           "Temporary name service failure" :
256                           "gethostbyname: unknown error");
257             return ret;
258         }
259         /* This way we are always sure the h->h_name is valid :) */
260         strncpy(realhost, h->h_name, sizeof(realhost));
261         for (n = 0; h->h_addr_list[n]; n++);
262         ret->addresses = snewn(n, unsigned long);
263         ret->naddresses = n;
264         for (n = 0; n < ret->naddresses; n++) {
265             memcpy(&a, h->h_addr_list[n], sizeof(a));
266             ret->addresses[n] = ntohl(a);
267         }
268     } else {
269         /*
270          * This must be a numeric IPv4 address because it caused a
271          * success return from inet_addr.
272          */
273         ret->superfamily = IP;
274         strncpy(realhost, host, sizeof(realhost));
275         ret->addresses = snew(unsigned long);
276         ret->naddresses = 1;
277         ret->addresses[0] = ntohl(a);
278     }
279 #endif
280     realhost[lenof(realhost)-1] = '\0';
281     *canonicalname = snewn(1+strlen(realhost), char);
282     strcpy(*canonicalname, realhost);
283     return ret;
284 }
285
286 SockAddr sk_nonamelookup(const char *host)
287 {
288     SockAddr ret = snew(struct SockAddr_tag);
289     ret->error = NULL;
290     ret->superfamily = UNRESOLVED;
291     strncpy(ret->hostname, host, lenof(ret->hostname));
292     ret->hostname[lenof(ret->hostname)-1] = '\0';
293 #ifndef NO_IPV6
294     ret->ais = NULL;
295 #else
296     ret->addresses = NULL;
297 #endif
298     ret->refcount = 1;
299     return ret;
300 }
301
302 static int sk_nextaddr(SockAddr addr, SockAddrStep *step)
303 {
304 #ifndef NO_IPV6
305     if (step->ai && step->ai->ai_next) {
306         step->ai = step->ai->ai_next;
307         return TRUE;
308     } else
309         return FALSE;
310 #else
311     if (step->curraddr+1 < addr->naddresses) {
312         step->curraddr++;
313         return TRUE;
314     } else {
315         return FALSE;
316     }
317 #endif    
318 }
319
320 void sk_getaddr(SockAddr addr, char *buf, int buflen)
321 {
322     if (addr->superfamily == UNRESOLVED || addr->superfamily == UNIX) {
323         strncpy(buf, addr->hostname, buflen);
324         buf[buflen-1] = '\0';
325     } else {
326 #ifndef NO_IPV6
327         if (getnameinfo(addr->ais->ai_addr, addr->ais->ai_addrlen, buf, buflen,
328                         NULL, 0, NI_NUMERICHOST) != 0) {
329             buf[0] = '\0';
330             strncat(buf, "<unknown>", buflen - 1);
331         }
332 #else
333         struct in_addr a;
334         assert(SOCKADDR_FAMILY(addr, ignored_macro_parameter) == AF_INET);
335         a.s_addr = htonl(addr->addresses[0]);
336         strncpy(buf, inet_ntoa(a), buflen);
337         buf[buflen-1] = '\0';
338 #endif
339     }
340 }
341
342 int sk_addr_needs_port(SockAddr addr)
343 {
344     if (addr->superfamily == UNRESOLVED || addr->superfamily == UNIX) {
345         return FALSE;
346     } else {
347         return TRUE;
348     }
349 }
350
351 int sk_hostname_is_local(const char *name)
352 {
353     return !strcmp(name, "localhost") ||
354            !strcmp(name, "::1") ||
355            !strncmp(name, "127.", 4);
356 }
357
358 #define ipv4_is_loopback(addr) \
359     (((addr).s_addr & htonl(0xff000000)) == htonl(0x7f000000))
360
361 static int sockaddr_is_loopback(struct sockaddr *sa)
362 {
363     union sockaddr_union *u = (union sockaddr_union *)sa;
364     switch (u->sa.sa_family) {
365       case AF_INET:
366         return ipv4_is_loopback(u->sin.sin_addr);
367 #ifndef NO_IPV6
368       case AF_INET6:
369         return IN6_IS_ADDR_LOOPBACK(&u->sin6.sin6_addr);
370 #endif
371       case AF_UNIX:
372         return TRUE;
373       default:
374         return FALSE;
375     }
376 }
377
378 int sk_address_is_local(SockAddr addr)
379 {
380     if (addr->superfamily == UNRESOLVED)
381         return 0;                      /* we don't know; assume not */
382     else if (addr->superfamily == UNIX)
383         return 1;
384     else {
385 #ifndef NO_IPV6
386         return sockaddr_is_loopback(addr->ais->ai_addr);
387 #else
388         struct in_addr a;
389         assert(SOCKADDR_FAMILY(addr, ignored_macro_parameter) == AF_INET);
390         a.s_addr = htonl(addr->addresses[0]);
391         return ipv4_is_loopback(a);
392 #endif
393     }
394 }
395
396 int sk_address_is_special_local(SockAddr addr)
397 {
398     return addr->superfamily == UNIX;
399 }
400
401 int sk_addrtype(SockAddr addr)
402 {
403     int family;
404     family = SOCKADDR_FAMILY(addr, ignored_macro_parameter);
405
406     return (family == AF_INET ? ADDRTYPE_IPV4 :
407 #ifndef NO_IPV6
408             family == AF_INET6 ? ADDRTYPE_IPV6 :
409 #endif
410             ADDRTYPE_NAME);
411 }
412
413 void sk_addrcopy(SockAddr addr, char *buf)
414 {
415     SockAddrStep step;
416     int family;
417     START_STEP(addr, step);
418     family = SOCKADDR_FAMILY(addr, step);
419
420 #ifndef NO_IPV6
421     if (family == AF_INET)
422         memcpy(buf, &((struct sockaddr_in *)step.ai->ai_addr)->sin_addr,
423                sizeof(struct in_addr));
424     else if (family == AF_INET6)
425         memcpy(buf, &((struct sockaddr_in6 *)step.ai->ai_addr)->sin6_addr,
426                sizeof(struct in6_addr));
427     else
428         assert(FALSE);
429 #else
430     struct in_addr a;
431
432     assert(family == AF_INET);
433     a.s_addr = htonl(addr->addresses[step.curraddr]);
434     memcpy(buf, (char*) &a.s_addr, 4);
435 #endif
436 }
437
438 void sk_addr_free(SockAddr addr)
439 {
440     if (--addr->refcount > 0)
441         return;
442 #ifndef NO_IPV6
443     if (addr->ais != NULL)
444         freeaddrinfo(addr->ais);
445 #else
446     sfree(addr->addresses);
447 #endif
448     sfree(addr);
449 }
450
451 SockAddr sk_addr_dup(SockAddr addr)
452 {
453     addr->refcount++;
454     return addr;
455 }
456
457 static Plug sk_tcp_plug(Socket sock, Plug p)
458 {
459     Actual_Socket s = (Actual_Socket) sock;
460     Plug ret = s->plug;
461     if (p)
462         s->plug = p;
463     return ret;
464 }
465
466 static void sk_tcp_flush(Socket s)
467 {
468     /*
469      * We send data to the socket as soon as we can anyway,
470      * so we don't need to do anything here.  :-)
471      */
472 }
473
474 static void sk_tcp_close(Socket s);
475 static int sk_tcp_write(Socket s, const char *data, int len);
476 static int sk_tcp_write_oob(Socket s, const char *data, int len);
477 static void sk_tcp_write_eof(Socket s);
478 static void sk_tcp_set_frozen(Socket s, int is_frozen);
479 static const char *sk_tcp_socket_error(Socket s);
480
481 static struct socket_function_table tcp_fn_table = {
482     sk_tcp_plug,
483     sk_tcp_close,
484     sk_tcp_write,
485     sk_tcp_write_oob,
486     sk_tcp_write_eof,
487     sk_tcp_flush,
488     sk_tcp_set_frozen,
489     sk_tcp_socket_error
490 };
491
492 static Socket sk_tcp_accept(accept_ctx_t ctx, Plug plug)
493 {
494     int sockfd = ctx.i;
495     Actual_Socket ret;
496
497     /*
498      * Create Socket structure.
499      */
500     ret = snew(struct Socket_tag);
501     ret->fn = &tcp_fn_table;
502     ret->error = NULL;
503     ret->plug = plug;
504     bufchain_init(&ret->output_data);
505     ret->writable = 1;                 /* to start with */
506     ret->sending_oob = 0;
507     ret->frozen = 1;
508     ret->localhost_only = 0;           /* unused, but best init anyway */
509     ret->pending_error = 0;
510     ret->oobpending = FALSE;
511     ret->outgoingeof = EOF_NO;
512     ret->incomingeof = FALSE;
513     ret->listener = 0;
514     ret->parent = ret->child = NULL;
515     ret->addr = NULL;
516     ret->connected = 1;
517
518     ret->s = sockfd;
519
520     if (ret->s < 0) {
521         ret->error = strerror(errno);
522         return (Socket) ret;
523     }
524
525     ret->oobinline = 0;
526
527     uxsel_tell(ret);
528     add234(sktree, ret);
529
530     return (Socket) ret;
531 }
532
533 static int try_connect(Actual_Socket sock)
534 {
535     int s;
536     union sockaddr_union u;
537     const union sockaddr_union *sa;
538     int err = 0;
539     short localport;
540     int salen, family;
541
542     /*
543      * Remove the socket from the tree before we overwrite its
544      * internal socket id, because that forms part of the tree's
545      * sorting criterion. We'll add it back before exiting this
546      * function, whether we changed anything or not.
547      */
548     del234(sktree, sock);
549
550     if (sock->s >= 0)
551         close(sock->s);
552
553     plug_log(sock->plug, 0, sock->addr, sock->port, NULL, 0);
554
555     /*
556      * Open socket.
557      */
558     family = SOCKADDR_FAMILY(sock->addr, sock->step);
559     assert(family != AF_UNSPEC);
560     s = socket(family, SOCK_STREAM, 0);
561     sock->s = s;
562
563     if (s < 0) {
564         err = errno;
565         goto ret;
566     }
567
568     cloexec(s);
569
570     if (sock->oobinline) {
571         int b = TRUE;
572         if (setsockopt(s, SOL_SOCKET, SO_OOBINLINE,
573                        (void *) &b, sizeof(b)) < 0) {
574             err = errno;
575             close(s);
576             goto ret;
577         }
578     }
579
580     if (sock->nodelay) {
581         int b = TRUE;
582         if (setsockopt(s, IPPROTO_TCP, TCP_NODELAY,
583                        (void *) &b, sizeof(b)) < 0) {
584             err = errno;
585             close(s);
586             goto ret;
587         }
588     }
589
590     if (sock->keepalive) {
591         int b = TRUE;
592         if (setsockopt(s, SOL_SOCKET, SO_KEEPALIVE,
593                        (void *) &b, sizeof(b)) < 0) {
594             err = errno;
595             close(s);
596             goto ret;
597         }
598     }
599
600     /*
601      * Bind to local address.
602      */
603     if (sock->privport)
604         localport = 1023;              /* count from 1023 downwards */
605     else
606         localport = 0;                 /* just use port 0 (ie kernel picks) */
607
608     /* BSD IP stacks need sockaddr_in zeroed before filling in */
609     memset(&u,'\0',sizeof(u));
610
611     /* We don't try to bind to a local address for UNIX domain sockets.  (Why
612      * do we bother doing the bind when localport == 0 anyway?) */
613     if (family != AF_UNIX) {
614         /* Loop round trying to bind */
615         while (1) {
616             int retcode;
617
618 #ifndef NO_IPV6
619             if (family == AF_INET6) {
620                 /* XXX use getaddrinfo to get a local address? */
621                 u.sin6.sin6_family = AF_INET6;
622                 u.sin6.sin6_addr = in6addr_any;
623                 u.sin6.sin6_port = htons(localport);
624                 retcode = bind(s, &u.sa, sizeof(u.sin6));
625             } else
626 #endif
627             {
628                 assert(family == AF_INET);
629                 u.sin.sin_family = AF_INET;
630                 u.sin.sin_addr.s_addr = htonl(INADDR_ANY);
631                 u.sin.sin_port = htons(localport);
632                 retcode = bind(s, &u.sa, sizeof(u.sin));
633             }
634             if (retcode >= 0) {
635                 err = 0;
636                 break;                 /* done */
637             } else {
638                 err = errno;
639                 if (err != EADDRINUSE) /* failed, for a bad reason */
640                   break;
641             }
642             
643             if (localport == 0)
644               break;                   /* we're only looping once */
645             localport--;
646             if (localport == 0)
647               break;                   /* we might have got to the end */
648         }
649         
650         if (err)
651             goto ret;
652     }
653
654     /*
655      * Connect to remote address.
656      */
657     switch(family) {
658 #ifndef NO_IPV6
659       case AF_INET:
660         /* XXX would be better to have got getaddrinfo() to fill in the port. */
661         ((struct sockaddr_in *)sock->step.ai->ai_addr)->sin_port =
662             htons(sock->port);
663         sa = (const union sockaddr_union *)sock->step.ai->ai_addr;
664         salen = sock->step.ai->ai_addrlen;
665         break;
666       case AF_INET6:
667         ((struct sockaddr_in *)sock->step.ai->ai_addr)->sin_port =
668             htons(sock->port);
669         sa = (const union sockaddr_union *)sock->step.ai->ai_addr;
670         salen = sock->step.ai->ai_addrlen;
671         break;
672 #else
673       case AF_INET:
674         u.sin.sin_family = AF_INET;
675         u.sin.sin_addr.s_addr = htonl(sock->addr->addresses[sock->step.curraddr]);
676         u.sin.sin_port = htons((short) sock->port);
677         sa = &u;
678         salen = sizeof u.sin;
679         break;
680 #endif
681       case AF_UNIX:
682         assert(sock->port == 0);       /* to catch confused people */
683         assert(strlen(sock->addr->hostname) < sizeof u.su.sun_path);
684         u.su.sun_family = AF_UNIX;
685         strcpy(u.su.sun_path, sock->addr->hostname);
686         sa = &u;
687         salen = sizeof u.su;
688         break;
689
690       default:
691         assert(0 && "unknown address family");
692         exit(1); /* XXX: GCC doesn't understand assert() on some systems. */
693     }
694
695     nonblock(s);
696
697     if ((connect(s, &(sa->sa), salen)) < 0) {
698         if ( errno != EINPROGRESS ) {
699             err = errno;
700             goto ret;
701         }
702     } else {
703         /*
704          * If we _don't_ get EWOULDBLOCK, the connect has completed
705          * and we should set the socket as connected and writable.
706          */
707         sock->connected = 1;
708         sock->writable = 1;
709     }
710
711     uxsel_tell(sock);
712
713     ret:
714
715     /*
716      * No matter what happened, put the socket back in the tree.
717      */
718     add234(sktree, sock);
719
720     if (err)
721         plug_log(sock->plug, 1, sock->addr, sock->port, strerror(err), err);
722     return err;
723 }
724
725 Socket sk_new(SockAddr addr, int port, int privport, int oobinline,
726               int nodelay, int keepalive, Plug plug)
727 {
728     Actual_Socket ret;
729     int err;
730
731     /*
732      * Create Socket structure.
733      */
734     ret = snew(struct Socket_tag);
735     ret->fn = &tcp_fn_table;
736     ret->error = NULL;
737     ret->plug = plug;
738     bufchain_init(&ret->output_data);
739     ret->connected = 0;                /* to start with */
740     ret->writable = 0;                 /* to start with */
741     ret->sending_oob = 0;
742     ret->frozen = 0;
743     ret->localhost_only = 0;           /* unused, but best init anyway */
744     ret->pending_error = 0;
745     ret->parent = ret->child = NULL;
746     ret->oobpending = FALSE;
747     ret->outgoingeof = EOF_NO;
748     ret->incomingeof = FALSE;
749     ret->listener = 0;
750     ret->addr = addr;
751     START_STEP(ret->addr, ret->step);
752     ret->s = -1;
753     ret->oobinline = oobinline;
754     ret->nodelay = nodelay;
755     ret->keepalive = keepalive;
756     ret->privport = privport;
757     ret->port = port;
758
759     err = 0;
760     do {
761         err = try_connect(ret);
762     } while (err && sk_nextaddr(ret->addr, &ret->step));
763
764     if (err)
765         ret->error = strerror(err);
766
767     return (Socket) ret;
768 }
769
770 Socket sk_newlistener(char *srcaddr, int port, Plug plug, int local_host_only, int orig_address_family)
771 {
772     int s;
773 #ifndef NO_IPV6
774     struct addrinfo hints, *ai;
775     char portstr[6];
776 #endif
777     union sockaddr_union u;
778     union sockaddr_union *addr;
779     int addrlen;
780     Actual_Socket ret;
781     int retcode;
782     int address_family;
783     int on = 1;
784
785     /*
786      * Create Socket structure.
787      */
788     ret = snew(struct Socket_tag);
789     ret->fn = &tcp_fn_table;
790     ret->error = NULL;
791     ret->plug = plug;
792     bufchain_init(&ret->output_data);
793     ret->writable = 0;                 /* to start with */
794     ret->sending_oob = 0;
795     ret->frozen = 0;
796     ret->localhost_only = local_host_only;
797     ret->pending_error = 0;
798     ret->parent = ret->child = NULL;
799     ret->oobpending = FALSE;
800     ret->outgoingeof = EOF_NO;
801     ret->incomingeof = FALSE;
802     ret->listener = 1;
803     ret->addr = NULL;
804     ret->s = -1;
805
806     /*
807      * Translate address_family from platform-independent constants
808      * into local reality.
809      */
810     address_family = (orig_address_family == ADDRTYPE_IPV4 ? AF_INET :
811 #ifndef NO_IPV6
812                       orig_address_family == ADDRTYPE_IPV6 ? AF_INET6 :
813 #endif
814                       AF_UNSPEC);
815
816 #ifndef NO_IPV6
817     /* Let's default to IPv6.
818      * If the stack doesn't support IPv6, we will fall back to IPv4. */
819     if (address_family == AF_UNSPEC) address_family = AF_INET6;
820 #else
821     /* No other choice, default to IPv4 */
822     if (address_family == AF_UNSPEC)  address_family = AF_INET;
823 #endif
824
825     /*
826      * Open socket.
827      */
828     s = socket(address_family, SOCK_STREAM, 0);
829
830 #ifndef NO_IPV6
831     /* If the host doesn't support IPv6 try fallback to IPv4. */
832     if (s < 0 && address_family == AF_INET6) {
833         address_family = AF_INET;
834         s = socket(address_family, SOCK_STREAM, 0);
835     }
836 #endif
837
838     if (s < 0) {
839         ret->error = strerror(errno);
840         return (Socket) ret;
841     }
842
843     cloexec(s);
844
845     ret->oobinline = 0;
846
847     if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR,
848                    (const char *)&on, sizeof(on)) < 0) {
849         ret->error = strerror(errno);
850         close(s);
851         return (Socket) ret;
852     }
853
854     retcode = -1;
855     addr = NULL; addrlen = -1;         /* placate optimiser */
856
857     if (srcaddr != NULL) {
858 #ifndef NO_IPV6
859         hints.ai_flags = AI_NUMERICHOST;
860         hints.ai_family = address_family;
861         hints.ai_socktype = SOCK_STREAM;
862         hints.ai_protocol = 0;
863         hints.ai_addrlen = 0;
864         hints.ai_addr = NULL;
865         hints.ai_canonname = NULL;
866         hints.ai_next = NULL;
867         assert(port >= 0 && port <= 99999);
868         sprintf(portstr, "%d", port);
869         {
870             char *trimmed_addr = host_strduptrim(srcaddr);
871             retcode = getaddrinfo(trimmed_addr, portstr, &hints, &ai);
872             sfree(trimmed_addr);
873         }
874         if (retcode == 0) {
875             addr = (union sockaddr_union *)ai->ai_addr;
876             addrlen = ai->ai_addrlen;
877         }
878 #else
879         memset(&u,'\0',sizeof u);
880         u.sin.sin_family = AF_INET;
881         u.sin.sin_port = htons(port);
882         u.sin.sin_addr.s_addr = inet_addr(srcaddr);
883         if (u.sin.sin_addr.s_addr != (in_addr_t)(-1)) {
884             /* Override localhost_only with specified listen addr. */
885             ret->localhost_only = ipv4_is_loopback(u.sin.sin_addr);
886         }
887         addr = &u;
888         addrlen = sizeof(u.sin);
889         retcode = 0;
890 #endif
891     }
892
893     if (retcode != 0) {
894         memset(&u,'\0',sizeof u);
895 #ifndef NO_IPV6
896         if (address_family == AF_INET6) {
897             u.sin6.sin6_family = AF_INET6;
898             u.sin6.sin6_port = htons(port);
899             if (local_host_only)
900                 u.sin6.sin6_addr = in6addr_loopback;
901             else
902                 u.sin6.sin6_addr = in6addr_any;
903             addr = &u;
904             addrlen = sizeof(u.sin6);
905         } else
906 #endif
907         {
908             u.sin.sin_family = AF_INET;
909             u.sin.sin_port = htons(port);
910             if (local_host_only)
911                 u.sin.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
912             else
913                 u.sin.sin_addr.s_addr = htonl(INADDR_ANY);
914             addr = &u;
915             addrlen = sizeof(u.sin);
916         }
917     }
918
919     retcode = bind(s, &addr->sa, addrlen);
920     if (retcode < 0) {
921         close(s);
922         ret->error = strerror(errno);
923         return (Socket) ret;
924     }
925
926     if (listen(s, SOMAXCONN) < 0) {
927         close(s);
928         ret->error = strerror(errno);
929         return (Socket) ret;
930     }
931
932 #ifndef NO_IPV6
933     /*
934      * If we were given ADDRTYPE_UNSPEC, we must also create an
935      * IPv4 listening socket and link it to this one.
936      */
937     if (address_family == AF_INET6 && orig_address_family == ADDRTYPE_UNSPEC) {
938         Actual_Socket other;
939
940         other = (Actual_Socket) sk_newlistener(srcaddr, port, plug,
941                                                local_host_only, ADDRTYPE_IPV4);
942
943         if (other) {
944             if (!other->error) {
945                 other->parent = ret;
946                 ret->child = other;
947             } else {
948                 /* If we couldn't create a listening socket on IPv4 as well
949                  * as IPv6, we must return an error overall. */
950                 close(s);
951                 sfree(ret);
952                 return (Socket) other;
953             }
954         }
955     }
956 #endif
957
958     ret->s = s;
959
960     uxsel_tell(ret);
961     add234(sktree, ret);
962
963     return (Socket) ret;
964 }
965
966 static void sk_tcp_close(Socket sock)
967 {
968     Actual_Socket s = (Actual_Socket) sock;
969
970     if (s->child)
971         sk_tcp_close((Socket)s->child);
972
973     uxsel_del(s->s);
974     del234(sktree, s);
975     close(s->s);
976     if (s->addr)
977         sk_addr_free(s->addr);
978     sfree(s);
979 }
980
981 void *sk_getxdmdata(void *sock, int *lenp)
982 {
983     Actual_Socket s = (Actual_Socket) sock;
984     union sockaddr_union u;
985     socklen_t addrlen;
986     char *buf;
987     static unsigned int unix_addr = 0xFFFFFFFF;
988
989     /*
990      * We must check that this socket really _is_ an Actual_Socket.
991      */
992     if (s->fn != &tcp_fn_table)
993         return NULL;                   /* failure */
994
995     addrlen = sizeof(u);
996     if (getsockname(s->s, &u.sa, &addrlen) < 0)
997         return NULL;
998     switch(u.sa.sa_family) {
999       case AF_INET:
1000         *lenp = 6;
1001         buf = snewn(*lenp, char);
1002         PUT_32BIT_MSB_FIRST(buf, ntohl(u.sin.sin_addr.s_addr));
1003         PUT_16BIT_MSB_FIRST(buf+4, ntohs(u.sin.sin_port));
1004         break;
1005 #ifndef NO_IPV6
1006     case AF_INET6:
1007         *lenp = 6;
1008         buf = snewn(*lenp, char);
1009         if (IN6_IS_ADDR_V4MAPPED(&u.sin6.sin6_addr)) {
1010             memcpy(buf, u.sin6.sin6_addr.s6_addr + 12, 4);
1011             PUT_16BIT_MSB_FIRST(buf+4, ntohs(u.sin6.sin6_port));
1012         } else
1013             /* This is stupid, but it's what XLib does. */
1014             memset(buf, 0, 6);
1015         break;
1016 #endif
1017       case AF_UNIX:
1018         *lenp = 6;
1019         buf = snewn(*lenp, char);
1020         PUT_32BIT_MSB_FIRST(buf, unix_addr--);
1021         PUT_16BIT_MSB_FIRST(buf+4, getpid());
1022         break;
1023
1024         /* XXX IPV6 */
1025
1026       default:
1027         return NULL;
1028     }
1029
1030     return buf;
1031 }
1032
1033 /*
1034  * Deal with socket errors detected in try_send().
1035  */
1036 static void socket_error_callback(void *vs)
1037 {
1038     Actual_Socket s = (Actual_Socket)vs;
1039
1040     /*
1041      * Just in case other socket work has caused this socket to vanish
1042      * or become somehow non-erroneous before this callback arrived...
1043      */
1044     if (!find234(sktree, s, NULL) || !s->pending_error)
1045         return;
1046
1047     /*
1048      * An error has occurred on this socket. Pass it to the plug.
1049      */
1050     plug_closing(s->plug, strerror(s->pending_error), s->pending_error, 0);
1051 }
1052
1053 /*
1054  * The function which tries to send on a socket once it's deemed
1055  * writable.
1056  */
1057 void try_send(Actual_Socket s)
1058 {
1059     while (s->sending_oob || bufchain_size(&s->output_data) > 0) {
1060         int nsent;
1061         int err;
1062         void *data;
1063         int len, urgentflag;
1064
1065         if (s->sending_oob) {
1066             urgentflag = MSG_OOB;
1067             len = s->sending_oob;
1068             data = &s->oobdata;
1069         } else {
1070             urgentflag = 0;
1071             bufchain_prefix(&s->output_data, &data, &len);
1072         }
1073         nsent = send(s->s, data, len, urgentflag);
1074         noise_ultralight(nsent);
1075         if (nsent <= 0) {
1076             err = (nsent < 0 ? errno : 0);
1077             if (err == EWOULDBLOCK) {
1078                 /*
1079                  * Perfectly normal: we've sent all we can for the moment.
1080                  */
1081                 s->writable = FALSE;
1082                 return;
1083             } else {
1084                 /*
1085                  * We unfortunately can't just call plug_closing(),
1086                  * because it's quite likely that we're currently
1087                  * _in_ a call from the code we'd be calling back
1088                  * to, so we'd have to make half the SSH code
1089                  * reentrant. Instead we flag a pending error on
1090                  * the socket, to be dealt with (by calling
1091                  * plug_closing()) at some suitable future moment.
1092                  */
1093                 s->pending_error = err;
1094                 /*
1095                  * Immediately cease selecting on this socket, so that
1096                  * we don't tight-loop repeatedly trying to do
1097                  * whatever it was that went wrong.
1098                  */
1099                 uxsel_tell(s);
1100                 /*
1101                  * Arrange to be called back from the top level to
1102                  * deal with the error condition on this socket.
1103                  */
1104                 queue_toplevel_callback(socket_error_callback, s);
1105                 return;
1106             }
1107         } else {
1108             if (s->sending_oob) {
1109                 if (nsent < len) {
1110                     memmove(s->oobdata, s->oobdata+nsent, len-nsent);
1111                     s->sending_oob = len - nsent;
1112                 } else {
1113                     s->sending_oob = 0;
1114                 }
1115             } else {
1116                 bufchain_consume(&s->output_data, nsent);
1117             }
1118         }
1119     }
1120
1121     /*
1122      * If we reach here, we've finished sending everything we might
1123      * have needed to send. Send EOF, if we need to.
1124      */
1125     if (s->outgoingeof == EOF_PENDING) {
1126         shutdown(s->s, SHUT_WR);
1127         s->outgoingeof = EOF_SENT;
1128     }
1129
1130     /*
1131      * Also update the select status, because we don't need to select
1132      * for writing any more.
1133      */
1134     uxsel_tell(s);
1135 }
1136
1137 static int sk_tcp_write(Socket sock, const char *buf, int len)
1138 {
1139     Actual_Socket s = (Actual_Socket) sock;
1140
1141     assert(s->outgoingeof == EOF_NO);
1142
1143     /*
1144      * Add the data to the buffer list on the socket.
1145      */
1146     bufchain_add(&s->output_data, buf, len);
1147
1148     /*
1149      * Now try sending from the start of the buffer list.
1150      */
1151     if (s->writable)
1152         try_send(s);
1153
1154     /*
1155      * Update the select() status to correctly reflect whether or
1156      * not we should be selecting for write.
1157      */
1158     uxsel_tell(s);
1159
1160     return bufchain_size(&s->output_data);
1161 }
1162
1163 static int sk_tcp_write_oob(Socket sock, const char *buf, int len)
1164 {
1165     Actual_Socket s = (Actual_Socket) sock;
1166
1167     assert(s->outgoingeof == EOF_NO);
1168
1169     /*
1170      * Replace the buffer list on the socket with the data.
1171      */
1172     bufchain_clear(&s->output_data);
1173     assert(len <= sizeof(s->oobdata));
1174     memcpy(s->oobdata, buf, len);
1175     s->sending_oob = len;
1176
1177     /*
1178      * Now try sending from the start of the buffer list.
1179      */
1180     if (s->writable)
1181         try_send(s);
1182
1183     /*
1184      * Update the select() status to correctly reflect whether or
1185      * not we should be selecting for write.
1186      */
1187     uxsel_tell(s);
1188
1189     return s->sending_oob;
1190 }
1191
1192 static void sk_tcp_write_eof(Socket sock)
1193 {
1194     Actual_Socket s = (Actual_Socket) sock;
1195
1196     assert(s->outgoingeof == EOF_NO);
1197
1198     /*
1199      * Mark the socket as pending outgoing EOF.
1200      */
1201     s->outgoingeof = EOF_PENDING;
1202
1203     /*
1204      * Now try sending from the start of the buffer list.
1205      */
1206     if (s->writable)
1207         try_send(s);
1208
1209     /*
1210      * Update the select() status to correctly reflect whether or
1211      * not we should be selecting for write.
1212      */
1213     uxsel_tell(s);
1214 }
1215
1216 static int net_select_result(int fd, int event)
1217 {
1218     int ret;
1219     char buf[20480];                   /* nice big buffer for plenty of speed */
1220     Actual_Socket s;
1221     u_long atmark;
1222
1223     /* Find the Socket structure */
1224     s = find234(sktree, &fd, cmpforsearch);
1225     if (!s)
1226         return 1;                      /* boggle */
1227
1228     noise_ultralight(event);
1229
1230     switch (event) {
1231       case 4:                          /* exceptional */
1232         if (!s->oobinline) {
1233             /*
1234              * On a non-oobinline socket, this indicates that we
1235              * can immediately perform an OOB read and get back OOB
1236              * data, which we will send to the back end with
1237              * type==2 (urgent data).
1238              */
1239             ret = recv(s->s, buf, sizeof(buf), MSG_OOB);
1240             noise_ultralight(ret);
1241             if (ret <= 0) {
1242                 return plug_closing(s->plug,
1243                                     ret == 0 ? "Internal networking trouble" :
1244                                     strerror(errno), errno, 0);
1245             } else {
1246                 /*
1247                  * Receiving actual data on a socket means we can
1248                  * stop falling back through the candidate
1249                  * addresses to connect to.
1250                  */
1251                 if (s->addr) {
1252                     sk_addr_free(s->addr);
1253                     s->addr = NULL;
1254                 }
1255                 return plug_receive(s->plug, 2, buf, ret);
1256             }
1257             break;
1258         }
1259
1260         /*
1261          * If we reach here, this is an oobinline socket, which
1262          * means we should set s->oobpending and then deal with it
1263          * when we get called for the readability event (which
1264          * should also occur).
1265          */
1266         s->oobpending = TRUE;
1267         break;
1268       case 1:                          /* readable; also acceptance */
1269         if (s->listener) {
1270             /*
1271              * On a listening socket, the readability event means a
1272              * connection is ready to be accepted.
1273              */
1274             union sockaddr_union su;
1275             socklen_t addrlen = sizeof(su);
1276             accept_ctx_t actx;
1277             int t;  /* socket of connection */
1278
1279             memset(&su, 0, addrlen);
1280             t = accept(s->s, &su.sa, &addrlen);
1281             if (t < 0) {
1282                 break;
1283             }
1284
1285             nonblock(t);
1286             actx.i = t;
1287
1288             if ((!s->addr || s->addr->superfamily != UNIX) &&
1289                 s->localhost_only && !sockaddr_is_loopback(&su.sa)) {
1290                 close(t);              /* someone let nonlocal through?! */
1291             } else if (plug_accepting(s->plug, sk_tcp_accept, actx)) {
1292                 close(t);              /* denied or error */
1293             }
1294             break;
1295         }
1296
1297         /*
1298          * If we reach here, this is not a listening socket, so
1299          * readability really means readability.
1300          */
1301
1302         /* In the case the socket is still frozen, we don't even bother */
1303         if (s->frozen)
1304             break;
1305
1306         /*
1307          * We have received data on the socket. For an oobinline
1308          * socket, this might be data _before_ an urgent pointer,
1309          * in which case we send it to the back end with type==1
1310          * (data prior to urgent).
1311          */
1312         if (s->oobinline && s->oobpending) {
1313             atmark = 1;
1314             if (ioctl(s->s, SIOCATMARK, &atmark) == 0 && atmark)
1315                 s->oobpending = FALSE; /* clear this indicator */
1316         } else
1317             atmark = 1;
1318
1319         ret = recv(s->s, buf, s->oobpending ? 1 : sizeof(buf), 0);
1320         noise_ultralight(ret);
1321         if (ret < 0) {
1322             if (errno == EWOULDBLOCK) {
1323                 break;
1324             }
1325         }
1326         if (ret < 0) {
1327             /*
1328              * An error at this point _might_ be an error reported
1329              * by a non-blocking connect(). So before we return a
1330              * panic status to the user, let's just see whether
1331              * that's the case.
1332              */
1333             int err = errno;
1334             if (s->addr) {
1335                 plug_log(s->plug, 1, s->addr, s->port, strerror(err), err);
1336                 while (s->addr && sk_nextaddr(s->addr, &s->step)) {
1337                     err = try_connect(s);
1338                 }
1339             }
1340             if (err != 0)
1341                 return plug_closing(s->plug, strerror(err), err, 0);
1342         } else if (0 == ret) {
1343             s->incomingeof = TRUE;     /* stop trying to read now */
1344             uxsel_tell(s);
1345             return plug_closing(s->plug, NULL, 0, 0);
1346         } else {
1347             /*
1348              * Receiving actual data on a socket means we can
1349              * stop falling back through the candidate
1350              * addresses to connect to.
1351              */
1352             if (s->addr) {
1353                 sk_addr_free(s->addr);
1354                 s->addr = NULL;
1355             }
1356             return plug_receive(s->plug, atmark ? 0 : 1, buf, ret);
1357         }
1358         break;
1359       case 2:                          /* writable */
1360         if (!s->connected) {
1361             /*
1362              * select() reports a socket as _writable_ when an
1363              * asynchronous connection is completed.
1364              */
1365             s->connected = s->writable = 1;
1366             uxsel_tell(s);
1367             break;
1368         } else {
1369             int bufsize_before, bufsize_after;
1370             s->writable = 1;
1371             bufsize_before = s->sending_oob + bufchain_size(&s->output_data);
1372             try_send(s);
1373             bufsize_after = s->sending_oob + bufchain_size(&s->output_data);
1374             if (bufsize_after < bufsize_before)
1375                 plug_sent(s->plug, bufsize_after);
1376         }
1377         break;
1378     }
1379
1380     return 1;
1381 }
1382
1383 /*
1384  * Special error values are returned from sk_namelookup and sk_new
1385  * if there's a problem. These functions extract an error message,
1386  * or return NULL if there's no problem.
1387  */
1388 const char *sk_addr_error(SockAddr addr)
1389 {
1390     return addr->error;
1391 }
1392 static const char *sk_tcp_socket_error(Socket sock)
1393 {
1394     Actual_Socket s = (Actual_Socket) sock;
1395     return s->error;
1396 }
1397
1398 static void sk_tcp_set_frozen(Socket sock, int is_frozen)
1399 {
1400     Actual_Socket s = (Actual_Socket) sock;
1401     if (s->frozen == is_frozen)
1402         return;
1403     s->frozen = is_frozen;
1404     uxsel_tell(s);
1405 }
1406
1407 static void uxsel_tell(Actual_Socket s)
1408 {
1409     int rwx = 0;
1410     if (!s->pending_error) {
1411         if (s->listener) {
1412             rwx |= 1;                  /* read == accept */
1413         } else {
1414             if (!s->connected)
1415                 rwx |= 2;              /* write == connect */
1416             if (s->connected && !s->frozen && !s->incomingeof)
1417                 rwx |= 1 | 4;          /* read, except */
1418             if (bufchain_size(&s->output_data))
1419                 rwx |= 2;              /* write */
1420         }
1421     }
1422     uxsel_set(s->s, rwx, net_select_result);
1423 }
1424
1425 int net_service_lookup(char *service)
1426 {
1427     struct servent *se;
1428     se = getservbyname(service, NULL);
1429     if (se != NULL)
1430         return ntohs(se->s_port);
1431     else
1432         return 0;
1433 }
1434
1435 char *get_hostname(void)
1436 {
1437     int len = 128;
1438     char *hostname = NULL;
1439     do {
1440         len *= 2;
1441         hostname = sresize(hostname, len, char);
1442         if ((gethostname(hostname, len) < 0) &&
1443             (errno != ENAMETOOLONG)) {
1444             sfree(hostname);
1445             hostname = NULL;
1446             break;
1447         }
1448     } while (strlen(hostname) >= len-1);
1449     return hostname;
1450 }
1451
1452 SockAddr platform_get_x11_unix_address(const char *sockpath, int displaynum)
1453 {
1454     SockAddr ret = snew(struct SockAddr_tag);
1455     int n;
1456
1457     memset(ret, 0, sizeof *ret);
1458     ret->superfamily = UNIX;
1459     /*
1460      * In special circumstances (notably Mac OS X Leopard), we'll
1461      * have been passed an explicit Unix socket path.
1462      */
1463     if (sockpath) {
1464         n = snprintf(ret->hostname, sizeof ret->hostname,
1465                      "%s", sockpath);
1466     } else {
1467         n = snprintf(ret->hostname, sizeof ret->hostname,
1468                      "%s%d", X11_UNIX_PATH, displaynum);
1469     }
1470
1471     if (n < 0)
1472         ret->error = "snprintf failed";
1473     else if (n >= sizeof ret->hostname)
1474         ret->error = "X11 UNIX name too long";
1475
1476 #ifndef NO_IPV6
1477     ret->ais = NULL;
1478 #else
1479     ret->addresses = NULL;
1480     ret->naddresses = 0;
1481 #endif
1482     ret->refcount = 1;
1483     return ret;
1484 }
1485
1486 SockAddr unix_sock_addr(const char *path)
1487 {
1488     SockAddr ret = snew(struct SockAddr_tag);
1489     int n;
1490
1491     memset(ret, 0, sizeof *ret);
1492     ret->superfamily = UNIX;
1493     n = snprintf(ret->hostname, sizeof ret->hostname, "%s", path);
1494
1495     if (n < 0)
1496         ret->error = "snprintf failed";
1497     else if (n >= sizeof ret->hostname)
1498         ret->error = "socket pathname too long";
1499
1500 #ifndef NO_IPV6
1501     ret->ais = NULL;
1502 #else
1503     ret->addresses = NULL;
1504     ret->naddresses = 0;
1505 #endif
1506     ret->refcount = 1;
1507     return ret;
1508 }
1509
1510 Socket new_unix_listener(SockAddr listenaddr, Plug plug)
1511 {
1512     int s;
1513     union sockaddr_union u;
1514     union sockaddr_union *addr;
1515     int addrlen;
1516     Actual_Socket ret;
1517     int retcode;
1518
1519     /*
1520      * Create Socket structure.
1521      */
1522     ret = snew(struct Socket_tag);
1523     ret->fn = &tcp_fn_table;
1524     ret->error = NULL;
1525     ret->plug = plug;
1526     bufchain_init(&ret->output_data);
1527     ret->writable = 0;                 /* to start with */
1528     ret->sending_oob = 0;
1529     ret->frozen = 0;
1530     ret->localhost_only = TRUE;
1531     ret->pending_error = 0;
1532     ret->parent = ret->child = NULL;
1533     ret->oobpending = FALSE;
1534     ret->outgoingeof = EOF_NO;
1535     ret->incomingeof = FALSE;
1536     ret->listener = 1;
1537     ret->addr = listenaddr;
1538     ret->s = -1;
1539
1540     assert(listenaddr->superfamily == UNIX);
1541
1542     /*
1543      * Open socket.
1544      */
1545     s = socket(AF_UNIX, SOCK_STREAM, 0);
1546     if (s < 0) {
1547         ret->error = strerror(errno);
1548         return (Socket) ret;
1549     }
1550
1551     cloexec(s);
1552
1553     ret->oobinline = 0;
1554
1555     memset(&u, '\0', sizeof(u));
1556     u.su.sun_family = AF_UNIX;
1557     strncpy(u.su.sun_path, listenaddr->hostname, sizeof(u.su.sun_path)-1);
1558     addr = &u;
1559     addrlen = sizeof(u.su);
1560
1561     if (unlink(u.su.sun_path) < 0 && errno != ENOENT) {
1562         close(s);
1563         ret->error = strerror(errno);
1564         return (Socket) ret;
1565     }
1566
1567     retcode = bind(s, &addr->sa, addrlen);
1568     if (retcode < 0) {
1569         close(s);
1570         ret->error = strerror(errno);
1571         return (Socket) ret;
1572     }
1573
1574     if (listen(s, SOMAXCONN) < 0) {
1575         close(s);
1576         ret->error = strerror(errno);
1577         return (Socket) ret;
1578     }
1579
1580     ret->s = s;
1581
1582     uxsel_tell(ret);
1583     add234(sktree, ret);
1584
1585     return (Socket) ret;
1586 }