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