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