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