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