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