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