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