2 * Unix networking abstraction.
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>
22 #define DEFINE_PLUG_METHOD_MACROS
27 /* Solaris needs <sys/sockio.h> for SIOCATMARK. */
29 #include <sys/sockio.h>
33 # define X11_UNIX_PATH "/tmp/.X11-unix/X"
37 * Access to sockaddr types without breaking C strict aliasing rules.
39 union sockaddr_union {
41 struct sockaddr_in storage;
43 struct sockaddr_storage storage;
44 struct sockaddr_in6 sin6;
47 struct sockaddr_in sin;
48 struct sockaddr_un su;
52 * We used to typedef struct Socket_tag *Socket.
54 * Since we have made the networking abstraction slightly more
55 * abstract, Socket no longer means a tcp socket (it could mean
56 * an ssl socket). So now we must use Actual_Socket when we know
57 * we are talking about a tcp socket.
59 typedef struct Socket_tag *Actual_Socket;
62 * Mutable state that goes with a SockAddr: stores information
63 * about where in the list of candidate IP(v*) addresses we've
66 typedef struct SockAddrStep_tag SockAddrStep;
67 struct SockAddrStep_tag {
69 struct addrinfo *ai; /* steps along addr->ais */
75 struct socket_function_table *fn;
76 /* the above variable absolutely *must* be the first in this structure */
81 int connected; /* irrelevant for listening sockets */
83 int frozen; /* this causes readability notifications to be ignored */
84 int localhost_only; /* for listening sockets */
87 int oobpending; /* is there OOB data available to read? */
89 enum { EOF_NO, EOF_PENDING, EOF_SENT } outgoingeof;
91 int pending_error; /* in case send() returns error */
93 int nodelay, keepalive; /* for connect()-type sockets */
94 int privport, port; /* and again */
98 * We sometimes need pairs of Socket structures to be linked:
99 * if we are listening on the same IPv6 and v4 port, for
100 * example. So here we define `parent' and `child' pointers to
103 Actual_Socket parent, child;
106 struct SockAddr_tag {
109 enum { UNRESOLVED, UNIX, IP } superfamily;
111 struct addrinfo *ais; /* Addresses IPv6 style. */
113 unsigned long *addresses; /* Addresses IPv4 style. */
116 char hostname[512]; /* Store an unresolved host name. */
120 * Which address family this address belongs to. AF_INET for IPv4;
121 * AF_INET6 for IPv6; AF_UNSPEC indicates that name resolution has
122 * not been done and a simple host name is held in this SockAddr
126 #define SOCKADDR_FAMILY(addr, step) \
127 ((addr)->superfamily == UNRESOLVED ? AF_UNSPEC : \
128 (addr)->superfamily == UNIX ? AF_UNIX : \
129 (step).ai ? (step).ai->ai_family : AF_INET)
131 /* Here we gratuitously reference 'step' to avoid gcc warnings about
132 * 'set but not used' when compiling -DNO_IPV6 */
133 #define SOCKADDR_FAMILY(addr, step) \
134 ((addr)->superfamily == UNRESOLVED ? AF_UNSPEC : \
135 (addr)->superfamily == UNIX ? AF_UNIX : \
136 (step).curraddr ? AF_INET : AF_INET)
140 * Start a SockAddrStep structure to step through multiple
144 #define START_STEP(addr, step) \
145 ((step).ai = (addr)->ais, (step).curraddr = 0)
147 #define START_STEP(addr, step) \
148 ((step).curraddr = 0)
151 static tree234 *sktree;
153 static void uxsel_tell(Actual_Socket s);
155 static int cmpfortree(void *av, void *bv)
157 Actual_Socket a = (Actual_Socket) av, b = (Actual_Socket) bv;
158 int as = a->s, bs = b->s;
170 static int cmpforsearch(void *av, void *bv)
172 Actual_Socket b = (Actual_Socket) bv;
173 int as = *(int *)av, bs = b->s;
183 sktree = newtree234(cmpfortree);
186 void sk_cleanup(void)
192 for (i = 0; (s = index234(sktree, i)) != NULL; i++) {
198 SockAddr sk_namelookup(const char *host, char **canonicalname, int address_family)
200 SockAddr ret = snew(struct SockAddr_tag);
202 struct addrinfo hints;
206 struct hostent *h = NULL;
211 /* Clear the structure and default to IPv4. */
212 memset(ret, 0, sizeof(struct SockAddr_tag));
213 ret->superfamily = UNRESOLVED;
219 hints.ai_flags = AI_CANONNAME;
220 hints.ai_family = (address_family == ADDRTYPE_IPV4 ? AF_INET :
221 address_family == ADDRTYPE_IPV6 ? AF_INET6 :
223 hints.ai_socktype = SOCK_STREAM;
224 hints.ai_protocol = 0;
225 hints.ai_addrlen = 0;
226 hints.ai_addr = NULL;
227 hints.ai_canonname = NULL;
228 hints.ai_next = NULL;
230 char *trimmed_host = host_strduptrim(host); /* strip [] on literals */
231 err = getaddrinfo(trimmed_host, NULL, &hints, &ret->ais);
235 ret->error = gai_strerror(err);
238 ret->superfamily = IP;
240 if (ret->ais->ai_canonname != NULL)
241 strncat(realhost, ret->ais->ai_canonname, sizeof(realhost) - 1);
243 strncat(realhost, host, sizeof(realhost) - 1);
245 if ((a = inet_addr(host)) == (unsigned long)(in_addr_t)(-1)) {
247 * Otherwise use the IPv4-only gethostbyname... (NOTE:
248 * we don't use gethostbyname as a fallback!)
250 if (ret->superfamily == UNRESOLVED) {
251 /*debug(("Resolving \"%s\" with gethostbyname() (IPv4 only)...\n", host)); */
252 if ( (h = gethostbyname(host)) )
253 ret->superfamily = IP;
255 if (ret->superfamily == UNRESOLVED) {
256 ret->error = (h_errno == HOST_NOT_FOUND ||
257 h_errno == NO_DATA ||
258 h_errno == NO_ADDRESS ? "Host does not exist" :
259 h_errno == TRY_AGAIN ?
260 "Temporary name service failure" :
261 "gethostbyname: unknown error");
264 /* This way we are always sure the h->h_name is valid :) */
265 strncpy(realhost, h->h_name, sizeof(realhost));
266 for (n = 0; h->h_addr_list[n]; n++);
267 ret->addresses = snewn(n, unsigned long);
269 for (n = 0; n < ret->naddresses; n++) {
270 memcpy(&a, h->h_addr_list[n], sizeof(a));
271 ret->addresses[n] = ntohl(a);
275 * This must be a numeric IPv4 address because it caused a
276 * success return from inet_addr.
278 ret->superfamily = IP;
279 strncpy(realhost, host, sizeof(realhost));
280 ret->addresses = snew(unsigned long);
282 ret->addresses[0] = ntohl(a);
285 realhost[lenof(realhost)-1] = '\0';
286 *canonicalname = snewn(1+strlen(realhost), char);
287 strcpy(*canonicalname, realhost);
291 SockAddr sk_nonamelookup(const char *host)
293 SockAddr ret = snew(struct SockAddr_tag);
295 ret->superfamily = UNRESOLVED;
296 strncpy(ret->hostname, host, lenof(ret->hostname));
297 ret->hostname[lenof(ret->hostname)-1] = '\0';
301 ret->addresses = NULL;
307 static int sk_nextaddr(SockAddr addr, SockAddrStep *step)
310 if (step->ai && step->ai->ai_next) {
311 step->ai = step->ai->ai_next;
316 if (step->curraddr+1 < addr->naddresses) {
325 void sk_getaddr(SockAddr addr, char *buf, int buflen)
327 if (addr->superfamily == UNRESOLVED || addr->superfamily == UNIX) {
328 strncpy(buf, addr->hostname, buflen);
329 buf[buflen-1] = '\0';
332 if (getnameinfo(addr->ais->ai_addr, addr->ais->ai_addrlen, buf, buflen,
333 NULL, 0, NI_NUMERICHOST) != 0) {
335 strncat(buf, "<unknown>", buflen - 1);
340 START_STEP(addr, step);
341 assert(SOCKADDR_FAMILY(addr, step) == AF_INET);
342 a.s_addr = htonl(addr->addresses[0]);
343 strncpy(buf, inet_ntoa(a), buflen);
344 buf[buflen-1] = '\0';
349 int sk_addr_needs_port(SockAddr addr)
351 if (addr->superfamily == UNRESOLVED || addr->superfamily == UNIX) {
358 int sk_hostname_is_local(const char *name)
360 return !strcmp(name, "localhost") ||
361 !strcmp(name, "::1") ||
362 !strncmp(name, "127.", 4);
365 #define ipv4_is_loopback(addr) \
366 (((addr).s_addr & htonl(0xff000000)) == htonl(0x7f000000))
368 static int sockaddr_is_loopback(struct sockaddr *sa)
370 union sockaddr_union *u = (union sockaddr_union *)sa;
371 switch (u->sa.sa_family) {
373 return ipv4_is_loopback(u->sin.sin_addr);
376 return IN6_IS_ADDR_LOOPBACK(&u->sin6.sin6_addr);
385 int sk_address_is_local(SockAddr addr)
387 if (addr->superfamily == UNRESOLVED)
388 return 0; /* we don't know; assume not */
389 else if (addr->superfamily == UNIX)
393 return sockaddr_is_loopback(addr->ais->ai_addr);
397 START_STEP(addr, step);
398 assert(SOCKADDR_FAMILY(addr, step) == AF_INET);
399 a.s_addr = htonl(addr->addresses[0]);
400 return ipv4_is_loopback(a);
405 int sk_address_is_special_local(SockAddr addr)
407 return addr->superfamily == UNIX;
410 int sk_addrtype(SockAddr addr)
414 START_STEP(addr, step);
415 family = SOCKADDR_FAMILY(addr, step);
417 return (family == AF_INET ? ADDRTYPE_IPV4 :
419 family == AF_INET6 ? ADDRTYPE_IPV6 :
424 void sk_addrcopy(SockAddr addr, char *buf)
428 START_STEP(addr, step);
429 family = SOCKADDR_FAMILY(addr, step);
432 if (family == AF_INET)
433 memcpy(buf, &((struct sockaddr_in *)step.ai->ai_addr)->sin_addr,
434 sizeof(struct in_addr));
435 else if (family == AF_INET6)
436 memcpy(buf, &((struct sockaddr_in6 *)step.ai->ai_addr)->sin6_addr,
437 sizeof(struct in6_addr));
443 assert(family == AF_INET);
444 a.s_addr = htonl(addr->addresses[step.curraddr]);
445 memcpy(buf, (char*) &a.s_addr, 4);
449 void sk_addr_free(SockAddr addr)
451 if (--addr->refcount > 0)
454 if (addr->ais != NULL)
455 freeaddrinfo(addr->ais);
457 sfree(addr->addresses);
462 SockAddr sk_addr_dup(SockAddr addr)
468 static Plug sk_tcp_plug(Socket sock, Plug p)
470 Actual_Socket s = (Actual_Socket) sock;
477 static void sk_tcp_flush(Socket s)
480 * We send data to the socket as soon as we can anyway,
481 * so we don't need to do anything here. :-)
485 static void sk_tcp_close(Socket s);
486 static int sk_tcp_write(Socket s, const char *data, int len);
487 static int sk_tcp_write_oob(Socket s, const char *data, int len);
488 static void sk_tcp_write_eof(Socket s);
489 static void sk_tcp_set_frozen(Socket s, int is_frozen);
490 static char *sk_tcp_peer_info(Socket s);
491 static const char *sk_tcp_socket_error(Socket s);
493 static struct socket_function_table tcp_fn_table = {
505 static Socket sk_tcp_accept(accept_ctx_t ctx, Plug plug)
511 * Create Socket structure.
513 ret = snew(struct Socket_tag);
514 ret->fn = &tcp_fn_table;
517 bufchain_init(&ret->output_data);
518 ret->writable = 1; /* to start with */
519 ret->sending_oob = 0;
521 ret->localhost_only = 0; /* unused, but best init anyway */
522 ret->pending_error = 0;
523 ret->oobpending = FALSE;
524 ret->outgoingeof = EOF_NO;
525 ret->incomingeof = FALSE;
527 ret->parent = ret->child = NULL;
534 ret->error = strerror(errno);
546 static int try_connect(Actual_Socket sock)
549 union sockaddr_union u;
550 const union sockaddr_union *sa;
556 * Remove the socket from the tree before we overwrite its
557 * internal socket id, because that forms part of the tree's
558 * sorting criterion. We'll add it back before exiting this
559 * function, whether we changed anything or not.
561 del234(sktree, sock);
566 plug_log(sock->plug, 0, sock->addr, sock->port, NULL, 0);
571 family = SOCKADDR_FAMILY(sock->addr, sock->step);
572 assert(family != AF_UNSPEC);
573 s = socket(family, SOCK_STREAM, 0);
583 if (sock->oobinline) {
585 if (setsockopt(s, SOL_SOCKET, SO_OOBINLINE,
586 (void *) &b, sizeof(b)) < 0) {
595 if (setsockopt(s, IPPROTO_TCP, TCP_NODELAY,
596 (void *) &b, sizeof(b)) < 0) {
603 if (sock->keepalive) {
605 if (setsockopt(s, SOL_SOCKET, SO_KEEPALIVE,
606 (void *) &b, sizeof(b)) < 0) {
614 * Bind to local address.
617 localport = 1023; /* count from 1023 downwards */
619 localport = 0; /* just use port 0 (ie kernel picks) */
621 /* BSD IP stacks need sockaddr_in zeroed before filling in */
622 memset(&u,'\0',sizeof(u));
624 /* We don't try to bind to a local address for UNIX domain sockets. (Why
625 * do we bother doing the bind when localport == 0 anyway?) */
626 if (family != AF_UNIX) {
627 /* Loop round trying to bind */
632 if (family == AF_INET6) {
633 /* XXX use getaddrinfo to get a local address? */
634 u.sin6.sin6_family = AF_INET6;
635 u.sin6.sin6_addr = in6addr_any;
636 u.sin6.sin6_port = htons(localport);
637 retcode = bind(s, &u.sa, sizeof(u.sin6));
641 assert(family == AF_INET);
642 u.sin.sin_family = AF_INET;
643 u.sin.sin_addr.s_addr = htonl(INADDR_ANY);
644 u.sin.sin_port = htons(localport);
645 retcode = bind(s, &u.sa, sizeof(u.sin));
652 if (err != EADDRINUSE) /* failed, for a bad reason */
657 break; /* we're only looping once */
660 break; /* we might have got to the end */
668 * Connect to remote address.
673 /* XXX would be better to have got getaddrinfo() to fill in the port. */
674 ((struct sockaddr_in *)sock->step.ai->ai_addr)->sin_port =
676 sa = (const union sockaddr_union *)sock->step.ai->ai_addr;
677 salen = sock->step.ai->ai_addrlen;
680 ((struct sockaddr_in *)sock->step.ai->ai_addr)->sin_port =
682 sa = (const union sockaddr_union *)sock->step.ai->ai_addr;
683 salen = sock->step.ai->ai_addrlen;
687 u.sin.sin_family = AF_INET;
688 u.sin.sin_addr.s_addr = htonl(sock->addr->addresses[sock->step.curraddr]);
689 u.sin.sin_port = htons((short) sock->port);
691 salen = sizeof u.sin;
695 assert(sock->port == 0); /* to catch confused people */
696 assert(strlen(sock->addr->hostname) < sizeof u.su.sun_path);
697 u.su.sun_family = AF_UNIX;
698 strcpy(u.su.sun_path, sock->addr->hostname);
704 assert(0 && "unknown address family");
705 exit(1); /* XXX: GCC doesn't understand assert() on some systems. */
710 if ((connect(s, &(sa->sa), salen)) < 0) {
711 if ( errno != EINPROGRESS ) {
717 * If we _don't_ get EWOULDBLOCK, the connect has completed
718 * and we should set the socket as connected and writable.
729 * No matter what happened, put the socket back in the tree.
731 add234(sktree, sock);
734 plug_log(sock->plug, 1, sock->addr, sock->port, strerror(err), err);
738 Socket sk_new(SockAddr addr, int port, int privport, int oobinline,
739 int nodelay, int keepalive, Plug plug)
745 * Create Socket structure.
747 ret = snew(struct Socket_tag);
748 ret->fn = &tcp_fn_table;
751 bufchain_init(&ret->output_data);
752 ret->connected = 0; /* to start with */
753 ret->writable = 0; /* to start with */
754 ret->sending_oob = 0;
756 ret->localhost_only = 0; /* unused, but best init anyway */
757 ret->pending_error = 0;
758 ret->parent = ret->child = NULL;
759 ret->oobpending = FALSE;
760 ret->outgoingeof = EOF_NO;
761 ret->incomingeof = FALSE;
764 START_STEP(ret->addr, ret->step);
766 ret->oobinline = oobinline;
767 ret->nodelay = nodelay;
768 ret->keepalive = keepalive;
769 ret->privport = privport;
774 err = try_connect(ret);
775 } while (err && sk_nextaddr(ret->addr, &ret->step));
778 ret->error = strerror(err);
783 Socket sk_newlistener(const char *srcaddr, int port, Plug plug,
784 int local_host_only, int orig_address_family)
788 struct addrinfo hints, *ai = NULL;
791 union sockaddr_union u;
792 union sockaddr_union *addr;
800 * Create Socket structure.
802 ret = snew(struct Socket_tag);
803 ret->fn = &tcp_fn_table;
806 bufchain_init(&ret->output_data);
807 ret->writable = 0; /* to start with */
808 ret->sending_oob = 0;
810 ret->localhost_only = local_host_only;
811 ret->pending_error = 0;
812 ret->parent = ret->child = NULL;
813 ret->oobpending = FALSE;
814 ret->outgoingeof = EOF_NO;
815 ret->incomingeof = FALSE;
821 * Translate address_family from platform-independent constants
822 * into local reality.
824 address_family = (orig_address_family == ADDRTYPE_IPV4 ? AF_INET :
826 orig_address_family == ADDRTYPE_IPV6 ? AF_INET6 :
831 /* Let's default to IPv6.
832 * If the stack doesn't support IPv6, we will fall back to IPv4. */
833 if (address_family == AF_UNSPEC) address_family = AF_INET6;
835 /* No other choice, default to IPv4 */
836 if (address_family == AF_UNSPEC) address_family = AF_INET;
842 s = socket(address_family, SOCK_STREAM, 0);
845 /* If the host doesn't support IPv6 try fallback to IPv4. */
846 if (s < 0 && address_family == AF_INET6) {
847 address_family = AF_INET;
848 s = socket(address_family, SOCK_STREAM, 0);
853 ret->error = strerror(errno);
861 if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR,
862 (const char *)&on, sizeof(on)) < 0) {
863 ret->error = strerror(errno);
869 addr = NULL; addrlen = -1; /* placate optimiser */
871 if (srcaddr != NULL) {
873 hints.ai_flags = AI_NUMERICHOST;
874 hints.ai_family = address_family;
875 hints.ai_socktype = SOCK_STREAM;
876 hints.ai_protocol = 0;
877 hints.ai_addrlen = 0;
878 hints.ai_addr = NULL;
879 hints.ai_canonname = NULL;
880 hints.ai_next = NULL;
881 assert(port >= 0 && port <= 99999);
882 sprintf(portstr, "%d", port);
884 char *trimmed_addr = host_strduptrim(srcaddr);
885 retcode = getaddrinfo(trimmed_addr, portstr, &hints, &ai);
889 addr = (union sockaddr_union *)ai->ai_addr;
890 addrlen = ai->ai_addrlen;
893 memset(&u,'\0',sizeof u);
894 u.sin.sin_family = AF_INET;
895 u.sin.sin_port = htons(port);
896 u.sin.sin_addr.s_addr = inet_addr(srcaddr);
897 if (u.sin.sin_addr.s_addr != (in_addr_t)(-1)) {
898 /* Override localhost_only with specified listen addr. */
899 ret->localhost_only = ipv4_is_loopback(u.sin.sin_addr);
902 addrlen = sizeof(u.sin);
908 memset(&u,'\0',sizeof u);
910 if (address_family == AF_INET6) {
911 u.sin6.sin6_family = AF_INET6;
912 u.sin6.sin6_port = htons(port);
914 u.sin6.sin6_addr = in6addr_loopback;
916 u.sin6.sin6_addr = in6addr_any;
918 addrlen = sizeof(u.sin6);
922 u.sin.sin_family = AF_INET;
923 u.sin.sin_port = htons(port);
925 u.sin.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
927 u.sin.sin_addr.s_addr = htonl(INADDR_ANY);
929 addrlen = sizeof(u.sin);
933 retcode = bind(s, &addr->sa, addrlen);
942 ret->error = strerror(errno);
946 if (listen(s, SOMAXCONN) < 0) {
948 ret->error = strerror(errno);
954 * If we were given ADDRTYPE_UNSPEC, we must also create an
955 * IPv4 listening socket and link it to this one.
957 if (address_family == AF_INET6 && orig_address_family == ADDRTYPE_UNSPEC) {
960 other = (Actual_Socket) sk_newlistener(srcaddr, port, plug,
961 local_host_only, ADDRTYPE_IPV4);
968 /* If we couldn't create a listening socket on IPv4 as well
969 * as IPv6, we must return an error overall. */
972 return (Socket) other;
986 static void sk_tcp_close(Socket sock)
988 Actual_Socket s = (Actual_Socket) sock;
991 sk_tcp_close((Socket)s->child);
997 sk_addr_free(s->addr);
1001 void *sk_getxdmdata(void *sock, int *lenp)
1003 Actual_Socket s = (Actual_Socket) sock;
1004 union sockaddr_union u;
1007 static unsigned int unix_addr = 0xFFFFFFFF;
1010 * We must check that this socket really _is_ an Actual_Socket.
1012 if (s->fn != &tcp_fn_table)
1013 return NULL; /* failure */
1015 addrlen = sizeof(u);
1016 if (getsockname(s->s, &u.sa, &addrlen) < 0)
1018 switch(u.sa.sa_family) {
1021 buf = snewn(*lenp, char);
1022 PUT_32BIT_MSB_FIRST(buf, ntohl(u.sin.sin_addr.s_addr));
1023 PUT_16BIT_MSB_FIRST(buf+4, ntohs(u.sin.sin_port));
1028 buf = snewn(*lenp, char);
1029 if (IN6_IS_ADDR_V4MAPPED(&u.sin6.sin6_addr)) {
1030 memcpy(buf, u.sin6.sin6_addr.s6_addr + 12, 4);
1031 PUT_16BIT_MSB_FIRST(buf+4, ntohs(u.sin6.sin6_port));
1033 /* This is stupid, but it's what XLib does. */
1039 buf = snewn(*lenp, char);
1040 PUT_32BIT_MSB_FIRST(buf, unix_addr--);
1041 PUT_16BIT_MSB_FIRST(buf+4, getpid());
1054 * Deal with socket errors detected in try_send().
1056 static void socket_error_callback(void *vs)
1058 Actual_Socket s = (Actual_Socket)vs;
1061 * Just in case other socket work has caused this socket to vanish
1062 * or become somehow non-erroneous before this callback arrived...
1064 if (!find234(sktree, s, NULL) || !s->pending_error)
1068 * An error has occurred on this socket. Pass it to the plug.
1070 plug_closing(s->plug, strerror(s->pending_error), s->pending_error, 0);
1074 * The function which tries to send on a socket once it's deemed
1077 void try_send(Actual_Socket s)
1079 while (s->sending_oob || bufchain_size(&s->output_data) > 0) {
1083 int len, urgentflag;
1085 if (s->sending_oob) {
1086 urgentflag = MSG_OOB;
1087 len = s->sending_oob;
1091 bufchain_prefix(&s->output_data, &data, &len);
1093 nsent = send(s->s, data, len, urgentflag);
1094 noise_ultralight(nsent);
1096 err = (nsent < 0 ? errno : 0);
1097 if (err == EWOULDBLOCK) {
1099 * Perfectly normal: we've sent all we can for the moment.
1101 s->writable = FALSE;
1105 * We unfortunately can't just call plug_closing(),
1106 * because it's quite likely that we're currently
1107 * _in_ a call from the code we'd be calling back
1108 * to, so we'd have to make half the SSH code
1109 * reentrant. Instead we flag a pending error on
1110 * the socket, to be dealt with (by calling
1111 * plug_closing()) at some suitable future moment.
1113 s->pending_error = err;
1115 * Immediately cease selecting on this socket, so that
1116 * we don't tight-loop repeatedly trying to do
1117 * whatever it was that went wrong.
1121 * Arrange to be called back from the top level to
1122 * deal with the error condition on this socket.
1124 queue_toplevel_callback(socket_error_callback, s);
1128 if (s->sending_oob) {
1130 memmove(s->oobdata, s->oobdata+nsent, len-nsent);
1131 s->sending_oob = len - nsent;
1136 bufchain_consume(&s->output_data, nsent);
1142 * If we reach here, we've finished sending everything we might
1143 * have needed to send. Send EOF, if we need to.
1145 if (s->outgoingeof == EOF_PENDING) {
1146 shutdown(s->s, SHUT_WR);
1147 s->outgoingeof = EOF_SENT;
1151 * Also update the select status, because we don't need to select
1152 * for writing any more.
1157 static int sk_tcp_write(Socket sock, const char *buf, int len)
1159 Actual_Socket s = (Actual_Socket) sock;
1161 assert(s->outgoingeof == EOF_NO);
1164 * Add the data to the buffer list on the socket.
1166 bufchain_add(&s->output_data, buf, len);
1169 * Now try sending from the start of the buffer list.
1175 * Update the select() status to correctly reflect whether or
1176 * not we should be selecting for write.
1180 return bufchain_size(&s->output_data);
1183 static int sk_tcp_write_oob(Socket sock, const char *buf, int len)
1185 Actual_Socket s = (Actual_Socket) sock;
1187 assert(s->outgoingeof == EOF_NO);
1190 * Replace the buffer list on the socket with the data.
1192 bufchain_clear(&s->output_data);
1193 assert(len <= sizeof(s->oobdata));
1194 memcpy(s->oobdata, buf, len);
1195 s->sending_oob = len;
1198 * Now try sending from the start of the buffer list.
1204 * Update the select() status to correctly reflect whether or
1205 * not we should be selecting for write.
1209 return s->sending_oob;
1212 static void sk_tcp_write_eof(Socket sock)
1214 Actual_Socket s = (Actual_Socket) sock;
1216 assert(s->outgoingeof == EOF_NO);
1219 * Mark the socket as pending outgoing EOF.
1221 s->outgoingeof = EOF_PENDING;
1224 * Now try sending from the start of the buffer list.
1230 * Update the select() status to correctly reflect whether or
1231 * not we should be selecting for write.
1236 static int net_select_result(int fd, int event)
1239 char buf[20480]; /* nice big buffer for plenty of speed */
1243 /* Find the Socket structure */
1244 s = find234(sktree, &fd, cmpforsearch);
1246 return 1; /* boggle */
1248 noise_ultralight(event);
1251 case 4: /* exceptional */
1252 if (!s->oobinline) {
1254 * On a non-oobinline socket, this indicates that we
1255 * can immediately perform an OOB read and get back OOB
1256 * data, which we will send to the back end with
1257 * type==2 (urgent data).
1259 ret = recv(s->s, buf, sizeof(buf), MSG_OOB);
1260 noise_ultralight(ret);
1262 return plug_closing(s->plug,
1263 ret == 0 ? "Internal networking trouble" :
1264 strerror(errno), errno, 0);
1267 * Receiving actual data on a socket means we can
1268 * stop falling back through the candidate
1269 * addresses to connect to.
1272 sk_addr_free(s->addr);
1275 return plug_receive(s->plug, 2, buf, ret);
1281 * If we reach here, this is an oobinline socket, which
1282 * means we should set s->oobpending and then deal with it
1283 * when we get called for the readability event (which
1284 * should also occur).
1286 s->oobpending = TRUE;
1288 case 1: /* readable; also acceptance */
1291 * On a listening socket, the readability event means a
1292 * connection is ready to be accepted.
1294 union sockaddr_union su;
1295 socklen_t addrlen = sizeof(su);
1297 int t; /* socket of connection */
1299 memset(&su, 0, addrlen);
1300 t = accept(s->s, &su.sa, &addrlen);
1308 if ((!s->addr || s->addr->superfamily != UNIX) &&
1309 s->localhost_only && !sockaddr_is_loopback(&su.sa)) {
1310 close(t); /* someone let nonlocal through?! */
1311 } else if (plug_accepting(s->plug, sk_tcp_accept, actx)) {
1312 close(t); /* denied or error */
1318 * If we reach here, this is not a listening socket, so
1319 * readability really means readability.
1322 /* In the case the socket is still frozen, we don't even bother */
1327 * We have received data on the socket. For an oobinline
1328 * socket, this might be data _before_ an urgent pointer,
1329 * in which case we send it to the back end with type==1
1330 * (data prior to urgent).
1332 if (s->oobinline && s->oobpending) {
1334 if (ioctl(s->s, SIOCATMARK, &atmark) == 0 && atmark)
1335 s->oobpending = FALSE; /* clear this indicator */
1339 ret = recv(s->s, buf, s->oobpending ? 1 : sizeof(buf), 0);
1340 noise_ultralight(ret);
1342 if (errno == EWOULDBLOCK) {
1348 * An error at this point _might_ be an error reported
1349 * by a non-blocking connect(). So before we return a
1350 * panic status to the user, let's just see whether
1355 plug_log(s->plug, 1, s->addr, s->port, strerror(err), err);
1356 while (s->addr && sk_nextaddr(s->addr, &s->step)) {
1357 err = try_connect(s);
1361 return plug_closing(s->plug, strerror(err), err, 0);
1362 } else if (0 == ret) {
1363 s->incomingeof = TRUE; /* stop trying to read now */
1365 return plug_closing(s->plug, NULL, 0, 0);
1368 * Receiving actual data on a socket means we can
1369 * stop falling back through the candidate
1370 * addresses to connect to.
1373 sk_addr_free(s->addr);
1376 return plug_receive(s->plug, atmark ? 0 : 1, buf, ret);
1379 case 2: /* writable */
1380 if (!s->connected) {
1382 * select() reports a socket as _writable_ when an
1383 * asynchronous connection is completed.
1385 s->connected = s->writable = 1;
1389 int bufsize_before, bufsize_after;
1391 bufsize_before = s->sending_oob + bufchain_size(&s->output_data);
1393 bufsize_after = s->sending_oob + bufchain_size(&s->output_data);
1394 if (bufsize_after < bufsize_before)
1395 plug_sent(s->plug, bufsize_after);
1404 * Special error values are returned from sk_namelookup and sk_new
1405 * if there's a problem. These functions extract an error message,
1406 * or return NULL if there's no problem.
1408 const char *sk_addr_error(SockAddr addr)
1412 static const char *sk_tcp_socket_error(Socket sock)
1414 Actual_Socket s = (Actual_Socket) sock;
1418 static void sk_tcp_set_frozen(Socket sock, int is_frozen)
1420 Actual_Socket s = (Actual_Socket) sock;
1421 if (s->frozen == is_frozen)
1423 s->frozen = is_frozen;
1427 static char *sk_tcp_peer_info(Socket sock)
1429 Actual_Socket s = (Actual_Socket) sock;
1430 struct sockaddr_storage addr;
1431 socklen_t addrlen = sizeof(addr);
1432 char buf[INET6_ADDRSTRLEN];
1434 if (getpeername(s->s, (struct sockaddr *)&addr, &addrlen) < 0)
1436 if (addr.ss_family == AF_INET) {
1439 inet_ntoa(((struct sockaddr_in *)&addr)->sin_addr),
1440 (int)ntohs(((struct sockaddr_in *)&addr)->sin_port));
1442 } else if (addr.ss_family == AF_INET6) {
1445 inet_ntop(AF_INET6, &((struct sockaddr_in6 *)&addr)->sin6_addr,
1447 (int)ntohs(((struct sockaddr_in6 *)&addr)->sin6_port));
1449 } else if (addr.ss_family == AF_UNIX) {
1451 * For Unix sockets, the source address is unlikely to be
1452 * helpful. Instead, we try SO_PEERCRED and try to get the
1456 if (so_peercred(s->s, &pid, &uid, &gid)) {
1457 char uidbuf[64], gidbuf[64];
1458 sprintf(uidbuf, "%d", uid);
1459 sprintf(gidbuf, "%d", gid);
1460 struct passwd *pw = getpwuid(uid);
1461 struct group *gr = getgrgid(gid);
1462 return dupprintf("pid %d (%s:%s)", pid,
1463 pw ? pw->pw_name : uidbuf,
1464 gr ? gr->gr_name : gidbuf);
1472 static void uxsel_tell(Actual_Socket s)
1475 if (!s->pending_error) {
1477 rwx |= 1; /* read == accept */
1480 rwx |= 2; /* write == connect */
1481 if (s->connected && !s->frozen && !s->incomingeof)
1482 rwx |= 1 | 4; /* read, except */
1483 if (bufchain_size(&s->output_data))
1484 rwx |= 2; /* write */
1487 uxsel_set(s->s, rwx, net_select_result);
1490 int net_service_lookup(char *service)
1493 se = getservbyname(service, NULL);
1495 return ntohs(se->s_port);
1500 char *get_hostname(void)
1503 char *hostname = NULL;
1506 hostname = sresize(hostname, len, char);
1507 if ((gethostname(hostname, len) < 0) &&
1508 (errno != ENAMETOOLONG)) {
1513 } while (strlen(hostname) >= len-1);
1517 SockAddr platform_get_x11_unix_address(const char *sockpath, int displaynum)
1519 SockAddr ret = snew(struct SockAddr_tag);
1522 memset(ret, 0, sizeof *ret);
1523 ret->superfamily = UNIX;
1525 * In special circumstances (notably Mac OS X Leopard), we'll
1526 * have been passed an explicit Unix socket path.
1529 n = snprintf(ret->hostname, sizeof ret->hostname,
1532 n = snprintf(ret->hostname, sizeof ret->hostname,
1533 "%s%d", X11_UNIX_PATH, displaynum);
1537 ret->error = "snprintf failed";
1538 else if (n >= sizeof ret->hostname)
1539 ret->error = "X11 UNIX name too long";
1544 ret->addresses = NULL;
1545 ret->naddresses = 0;
1551 SockAddr unix_sock_addr(const char *path)
1553 SockAddr ret = snew(struct SockAddr_tag);
1556 memset(ret, 0, sizeof *ret);
1557 ret->superfamily = UNIX;
1558 n = snprintf(ret->hostname, sizeof ret->hostname, "%s", path);
1561 ret->error = "snprintf failed";
1562 else if (n >= sizeof ret->hostname)
1563 ret->error = "socket pathname too long";
1568 ret->addresses = NULL;
1569 ret->naddresses = 0;
1575 Socket new_unix_listener(SockAddr listenaddr, Plug plug)
1578 union sockaddr_union u;
1579 union sockaddr_union *addr;
1585 * Create Socket structure.
1587 ret = snew(struct Socket_tag);
1588 ret->fn = &tcp_fn_table;
1591 bufchain_init(&ret->output_data);
1592 ret->writable = 0; /* to start with */
1593 ret->sending_oob = 0;
1595 ret->localhost_only = TRUE;
1596 ret->pending_error = 0;
1597 ret->parent = ret->child = NULL;
1598 ret->oobpending = FALSE;
1599 ret->outgoingeof = EOF_NO;
1600 ret->incomingeof = FALSE;
1602 ret->addr = listenaddr;
1605 assert(listenaddr->superfamily == UNIX);
1610 s = socket(AF_UNIX, SOCK_STREAM, 0);
1612 ret->error = strerror(errno);
1613 return (Socket) ret;
1620 memset(&u, '\0', sizeof(u));
1621 u.su.sun_family = AF_UNIX;
1622 strncpy(u.su.sun_path, listenaddr->hostname, sizeof(u.su.sun_path)-1);
1624 addrlen = sizeof(u.su);
1626 if (unlink(u.su.sun_path) < 0 && errno != ENOENT) {
1628 ret->error = strerror(errno);
1629 return (Socket) ret;
1632 retcode = bind(s, &addr->sa, addrlen);
1635 ret->error = strerror(errno);
1636 return (Socket) ret;
1639 if (listen(s, SOMAXCONN) < 0) {
1641 ret->error = strerror(errno);
1642 return (Socket) ret;
1648 add234(sktree, ret);
1650 return (Socket) ret;