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 {
40 struct sockaddr_storage storage;
42 struct sockaddr_in sin;
44 struct sockaddr_in6 sin6;
46 struct sockaddr_un su;
50 * We used to typedef struct Socket_tag *Socket.
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.
57 typedef struct Socket_tag *Actual_Socket;
60 * Mutable state that goes with a SockAddr: stores information
61 * about where in the list of candidate IP(v*) addresses we've
64 typedef struct SockAddrStep_tag SockAddrStep;
65 struct SockAddrStep_tag {
67 struct addrinfo *ai; /* steps along addr->ais */
73 struct socket_function_table *fn;
74 /* the above variable absolutely *must* be the first in this structure */
79 int connected; /* irrelevant for listening sockets */
81 int frozen; /* this causes readability notifications to be ignored */
82 int localhost_only; /* for listening sockets */
85 int oobpending; /* is there OOB data available to read? */
87 enum { EOF_NO, EOF_PENDING, EOF_SENT } outgoingeof;
89 int pending_error; /* in case send() returns error */
91 int nodelay, keepalive; /* for connect()-type sockets */
92 int privport, port; /* and again */
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
101 Actual_Socket parent, child;
104 struct SockAddr_tag {
107 enum { UNRESOLVED, UNIX, IP } superfamily;
109 struct addrinfo *ais; /* Addresses IPv6 style. */
111 unsigned long *addresses; /* Addresses IPv4 style. */
114 char hostname[512]; /* Store an unresolved host name. */
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
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)
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)
138 * Start a SockAddrStep structure to step through multiple
142 #define START_STEP(addr, step) \
143 ((step).ai = (addr)->ais, (step).curraddr = 0)
145 #define START_STEP(addr, step) \
146 ((step).curraddr = 0)
149 static tree234 *sktree;
151 static void uxsel_tell(Actual_Socket s);
153 static int cmpfortree(void *av, void *bv)
155 Actual_Socket a = (Actual_Socket) av, b = (Actual_Socket) bv;
156 int as = a->s, bs = b->s;
168 static int cmpforsearch(void *av, void *bv)
170 Actual_Socket b = (Actual_Socket) bv;
171 int as = *(int *)av, bs = b->s;
181 sktree = newtree234(cmpfortree);
184 void sk_cleanup(void)
190 for (i = 0; (s = index234(sktree, i)) != NULL; i++) {
196 SockAddr sk_namelookup(const char *host, char **canonicalname, int address_family)
198 SockAddr ret = snew(struct SockAddr_tag);
200 struct addrinfo hints;
204 struct hostent *h = NULL;
209 /* Clear the structure and default to IPv4. */
210 memset(ret, 0, sizeof(struct SockAddr_tag));
211 ret->superfamily = UNRESOLVED;
217 hints.ai_flags = AI_CANONNAME;
218 hints.ai_family = (address_family == ADDRTYPE_IPV4 ? AF_INET :
219 address_family == ADDRTYPE_IPV6 ? AF_INET6 :
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;
228 char *trimmed_host = host_strduptrim(host); /* strip [] on literals */
229 err = getaddrinfo(trimmed_host, NULL, &hints, &ret->ais);
233 ret->error = gai_strerror(err);
236 ret->superfamily = IP;
238 if (ret->ais->ai_canonname != NULL)
239 strncat(realhost, ret->ais->ai_canonname, sizeof(realhost) - 1);
241 strncat(realhost, host, sizeof(realhost) - 1);
243 if ((a = inet_addr(host)) == (unsigned long)(in_addr_t)(-1)) {
245 * Otherwise use the IPv4-only gethostbyname... (NOTE:
246 * we don't use gethostbyname as a fallback!)
248 if (ret->superfamily == UNRESOLVED) {
249 /*debug(("Resolving \"%s\" with gethostbyname() (IPv4 only)...\n", host)); */
250 if ( (h = gethostbyname(host)) )
251 ret->superfamily = IP;
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");
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);
267 for (n = 0; n < ret->naddresses; n++) {
268 memcpy(&a, h->h_addr_list[n], sizeof(a));
269 ret->addresses[n] = ntohl(a);
273 * This must be a numeric IPv4 address because it caused a
274 * success return from inet_addr.
276 ret->superfamily = IP;
277 strncpy(realhost, host, sizeof(realhost));
278 ret->addresses = snew(unsigned long);
280 ret->addresses[0] = ntohl(a);
283 realhost[lenof(realhost)-1] = '\0';
284 *canonicalname = snewn(1+strlen(realhost), char);
285 strcpy(*canonicalname, realhost);
289 SockAddr sk_nonamelookup(const char *host)
291 SockAddr ret = snew(struct SockAddr_tag);
293 ret->superfamily = UNRESOLVED;
294 strncpy(ret->hostname, host, lenof(ret->hostname));
295 ret->hostname[lenof(ret->hostname)-1] = '\0';
299 ret->addresses = NULL;
305 static int sk_nextaddr(SockAddr addr, SockAddrStep *step)
308 if (step->ai && step->ai->ai_next) {
309 step->ai = step->ai->ai_next;
314 if (step->curraddr+1 < addr->naddresses) {
323 void sk_getaddr(SockAddr addr, char *buf, int buflen)
325 if (addr->superfamily == UNRESOLVED || addr->superfamily == UNIX) {
326 strncpy(buf, addr->hostname, buflen);
327 buf[buflen-1] = '\0';
330 if (getnameinfo(addr->ais->ai_addr, addr->ais->ai_addrlen, buf, buflen,
331 NULL, 0, NI_NUMERICHOST) != 0) {
333 strncat(buf, "<unknown>", buflen - 1);
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';
347 int sk_addr_needs_port(SockAddr addr)
349 if (addr->superfamily == UNRESOLVED || addr->superfamily == UNIX) {
356 int sk_hostname_is_local(const char *name)
358 return !strcmp(name, "localhost") ||
359 !strcmp(name, "::1") ||
360 !strncmp(name, "127.", 4);
363 #define ipv4_is_loopback(addr) \
364 (((addr).s_addr & htonl(0xff000000)) == htonl(0x7f000000))
366 static int sockaddr_is_loopback(struct sockaddr *sa)
368 union sockaddr_union *u = (union sockaddr_union *)sa;
369 switch (u->sa.sa_family) {
371 return ipv4_is_loopback(u->sin.sin_addr);
374 return IN6_IS_ADDR_LOOPBACK(&u->sin6.sin6_addr);
383 int sk_address_is_local(SockAddr addr)
385 if (addr->superfamily == UNRESOLVED)
386 return 0; /* we don't know; assume not */
387 else if (addr->superfamily == UNIX)
391 return sockaddr_is_loopback(addr->ais->ai_addr);
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);
403 int sk_address_is_special_local(SockAddr addr)
405 return addr->superfamily == UNIX;
408 int sk_addrtype(SockAddr addr)
412 START_STEP(addr, step);
413 family = SOCKADDR_FAMILY(addr, step);
415 return (family == AF_INET ? ADDRTYPE_IPV4 :
417 family == AF_INET6 ? ADDRTYPE_IPV6 :
422 void sk_addrcopy(SockAddr addr, char *buf)
426 START_STEP(addr, step);
427 family = SOCKADDR_FAMILY(addr, step);
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));
441 assert(family == AF_INET);
442 a.s_addr = htonl(addr->addresses[step.curraddr]);
443 memcpy(buf, (char*) &a.s_addr, 4);
447 void sk_addr_free(SockAddr addr)
449 if (--addr->refcount > 0)
452 if (addr->ais != NULL)
453 freeaddrinfo(addr->ais);
455 sfree(addr->addresses);
460 SockAddr sk_addr_dup(SockAddr addr)
466 static Plug sk_tcp_plug(Socket sock, Plug p)
468 Actual_Socket s = (Actual_Socket) sock;
475 static void sk_tcp_flush(Socket s)
478 * We send data to the socket as soon as we can anyway,
479 * so we don't need to do anything here. :-)
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);
491 static struct socket_function_table tcp_fn_table = {
503 static Socket sk_tcp_accept(accept_ctx_t ctx, Plug plug)
509 * Create Socket structure.
511 ret = snew(struct Socket_tag);
512 ret->fn = &tcp_fn_table;
515 bufchain_init(&ret->output_data);
516 ret->writable = 1; /* to start with */
517 ret->sending_oob = 0;
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;
525 ret->parent = ret->child = NULL;
532 ret->error = strerror(errno);
544 static int try_connect(Actual_Socket sock)
547 union sockaddr_union u;
548 const union sockaddr_union *sa;
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.
559 del234(sktree, sock);
564 plug_log(sock->plug, 0, sock->addr, sock->port, NULL, 0);
569 family = SOCKADDR_FAMILY(sock->addr, sock->step);
570 assert(family != AF_UNSPEC);
571 s = socket(family, SOCK_STREAM, 0);
581 if (sock->oobinline) {
583 if (setsockopt(s, SOL_SOCKET, SO_OOBINLINE,
584 (void *) &b, sizeof(b)) < 0) {
593 if (setsockopt(s, IPPROTO_TCP, TCP_NODELAY,
594 (void *) &b, sizeof(b)) < 0) {
601 if (sock->keepalive) {
603 if (setsockopt(s, SOL_SOCKET, SO_KEEPALIVE,
604 (void *) &b, sizeof(b)) < 0) {
612 * Bind to local address.
615 localport = 1023; /* count from 1023 downwards */
617 localport = 0; /* just use port 0 (ie kernel picks) */
619 /* BSD IP stacks need sockaddr_in zeroed before filling in */
620 memset(&u,'\0',sizeof(u));
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 */
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));
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));
650 if (err != EADDRINUSE) /* failed, for a bad reason */
655 break; /* we're only looping once */
658 break; /* we might have got to the end */
666 * Connect to remote address.
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 =
674 sa = (const union sockaddr_union *)sock->step.ai->ai_addr;
675 salen = sock->step.ai->ai_addrlen;
678 ((struct sockaddr_in *)sock->step.ai->ai_addr)->sin_port =
680 sa = (const union sockaddr_union *)sock->step.ai->ai_addr;
681 salen = sock->step.ai->ai_addrlen;
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);
689 salen = sizeof u.sin;
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);
702 assert(0 && "unknown address family");
703 exit(1); /* XXX: GCC doesn't understand assert() on some systems. */
708 if ((connect(s, &(sa->sa), salen)) < 0) {
709 if ( errno != EINPROGRESS ) {
715 * If we _don't_ get EWOULDBLOCK, the connect has completed
716 * and we should set the socket as connected and writable.
727 * No matter what happened, put the socket back in the tree.
729 add234(sktree, sock);
732 plug_log(sock->plug, 1, sock->addr, sock->port, strerror(err), err);
736 Socket sk_new(SockAddr addr, int port, int privport, int oobinline,
737 int nodelay, int keepalive, Plug plug)
743 * Create Socket structure.
745 ret = snew(struct Socket_tag);
746 ret->fn = &tcp_fn_table;
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;
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;
762 START_STEP(ret->addr, ret->step);
764 ret->oobinline = oobinline;
765 ret->nodelay = nodelay;
766 ret->keepalive = keepalive;
767 ret->privport = privport;
772 err = try_connect(ret);
773 } while (err && sk_nextaddr(ret->addr, &ret->step));
776 ret->error = strerror(err);
781 Socket sk_newlistener(const char *srcaddr, int port, Plug plug,
782 int local_host_only, int orig_address_family)
786 struct addrinfo hints, *ai = NULL;
789 union sockaddr_union u;
790 union sockaddr_union *addr;
798 * Create Socket structure.
800 ret = snew(struct Socket_tag);
801 ret->fn = &tcp_fn_table;
804 bufchain_init(&ret->output_data);
805 ret->writable = 0; /* to start with */
806 ret->sending_oob = 0;
808 ret->localhost_only = local_host_only;
809 ret->pending_error = 0;
810 ret->parent = ret->child = NULL;
811 ret->oobpending = FALSE;
812 ret->outgoingeof = EOF_NO;
813 ret->incomingeof = FALSE;
819 * Translate address_family from platform-independent constants
820 * into local reality.
822 address_family = (orig_address_family == ADDRTYPE_IPV4 ? AF_INET :
824 orig_address_family == ADDRTYPE_IPV6 ? AF_INET6 :
829 /* Let's default to IPv6.
830 * If the stack doesn't support IPv6, we will fall back to IPv4. */
831 if (address_family == AF_UNSPEC) address_family = AF_INET6;
833 /* No other choice, default to IPv4 */
834 if (address_family == AF_UNSPEC) address_family = AF_INET;
840 s = socket(address_family, SOCK_STREAM, 0);
843 /* If the host doesn't support IPv6 try fallback to IPv4. */
844 if (s < 0 && address_family == AF_INET6) {
845 address_family = AF_INET;
846 s = socket(address_family, SOCK_STREAM, 0);
851 ret->error = strerror(errno);
859 if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR,
860 (const char *)&on, sizeof(on)) < 0) {
861 ret->error = strerror(errno);
867 addr = NULL; addrlen = -1; /* placate optimiser */
869 if (srcaddr != NULL) {
871 hints.ai_flags = AI_NUMERICHOST;
872 hints.ai_family = address_family;
873 hints.ai_socktype = SOCK_STREAM;
874 hints.ai_protocol = 0;
875 hints.ai_addrlen = 0;
876 hints.ai_addr = NULL;
877 hints.ai_canonname = NULL;
878 hints.ai_next = NULL;
879 assert(port >= 0 && port <= 99999);
880 sprintf(portstr, "%d", port);
882 char *trimmed_addr = host_strduptrim(srcaddr);
883 retcode = getaddrinfo(trimmed_addr, portstr, &hints, &ai);
887 addr = (union sockaddr_union *)ai->ai_addr;
888 addrlen = ai->ai_addrlen;
891 memset(&u,'\0',sizeof u);
892 u.sin.sin_family = AF_INET;
893 u.sin.sin_port = htons(port);
894 u.sin.sin_addr.s_addr = inet_addr(srcaddr);
895 if (u.sin.sin_addr.s_addr != (in_addr_t)(-1)) {
896 /* Override localhost_only with specified listen addr. */
897 ret->localhost_only = ipv4_is_loopback(u.sin.sin_addr);
900 addrlen = sizeof(u.sin);
906 memset(&u,'\0',sizeof u);
908 if (address_family == AF_INET6) {
909 u.sin6.sin6_family = AF_INET6;
910 u.sin6.sin6_port = htons(port);
912 u.sin6.sin6_addr = in6addr_loopback;
914 u.sin6.sin6_addr = in6addr_any;
916 addrlen = sizeof(u.sin6);
920 u.sin.sin_family = AF_INET;
921 u.sin.sin_port = htons(port);
923 u.sin.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
925 u.sin.sin_addr.s_addr = htonl(INADDR_ANY);
927 addrlen = sizeof(u.sin);
931 retcode = bind(s, &addr->sa, addrlen);
940 ret->error = strerror(errno);
944 if (listen(s, SOMAXCONN) < 0) {
946 ret->error = strerror(errno);
952 * If we were given ADDRTYPE_UNSPEC, we must also create an
953 * IPv4 listening socket and link it to this one.
955 if (address_family == AF_INET6 && orig_address_family == ADDRTYPE_UNSPEC) {
958 other = (Actual_Socket) sk_newlistener(srcaddr, port, plug,
959 local_host_only, ADDRTYPE_IPV4);
966 /* If we couldn't create a listening socket on IPv4 as well
967 * as IPv6, we must return an error overall. */
970 return (Socket) other;
984 static void sk_tcp_close(Socket sock)
986 Actual_Socket s = (Actual_Socket) sock;
989 sk_tcp_close((Socket)s->child);
995 sk_addr_free(s->addr);
999 void *sk_getxdmdata(void *sock, int *lenp)
1001 Actual_Socket s = (Actual_Socket) sock;
1002 union sockaddr_union u;
1005 static unsigned int unix_addr = 0xFFFFFFFF;
1008 * We must check that this socket really _is_ an Actual_Socket.
1010 if (s->fn != &tcp_fn_table)
1011 return NULL; /* failure */
1013 addrlen = sizeof(u);
1014 if (getsockname(s->s, &u.sa, &addrlen) < 0)
1016 switch(u.sa.sa_family) {
1019 buf = snewn(*lenp, char);
1020 PUT_32BIT_MSB_FIRST(buf, ntohl(u.sin.sin_addr.s_addr));
1021 PUT_16BIT_MSB_FIRST(buf+4, ntohs(u.sin.sin_port));
1026 buf = snewn(*lenp, char);
1027 if (IN6_IS_ADDR_V4MAPPED(&u.sin6.sin6_addr)) {
1028 memcpy(buf, u.sin6.sin6_addr.s6_addr + 12, 4);
1029 PUT_16BIT_MSB_FIRST(buf+4, ntohs(u.sin6.sin6_port));
1031 /* This is stupid, but it's what XLib does. */
1037 buf = snewn(*lenp, char);
1038 PUT_32BIT_MSB_FIRST(buf, unix_addr--);
1039 PUT_16BIT_MSB_FIRST(buf+4, getpid());
1052 * Deal with socket errors detected in try_send().
1054 static void socket_error_callback(void *vs)
1056 Actual_Socket s = (Actual_Socket)vs;
1059 * Just in case other socket work has caused this socket to vanish
1060 * or become somehow non-erroneous before this callback arrived...
1062 if (!find234(sktree, s, NULL) || !s->pending_error)
1066 * An error has occurred on this socket. Pass it to the plug.
1068 plug_closing(s->plug, strerror(s->pending_error), s->pending_error, 0);
1072 * The function which tries to send on a socket once it's deemed
1075 void try_send(Actual_Socket s)
1077 while (s->sending_oob || bufchain_size(&s->output_data) > 0) {
1081 int len, urgentflag;
1083 if (s->sending_oob) {
1084 urgentflag = MSG_OOB;
1085 len = s->sending_oob;
1089 bufchain_prefix(&s->output_data, &data, &len);
1091 nsent = send(s->s, data, len, urgentflag);
1092 noise_ultralight(nsent);
1094 err = (nsent < 0 ? errno : 0);
1095 if (err == EWOULDBLOCK) {
1097 * Perfectly normal: we've sent all we can for the moment.
1099 s->writable = FALSE;
1103 * We unfortunately can't just call plug_closing(),
1104 * because it's quite likely that we're currently
1105 * _in_ a call from the code we'd be calling back
1106 * to, so we'd have to make half the SSH code
1107 * reentrant. Instead we flag a pending error on
1108 * the socket, to be dealt with (by calling
1109 * plug_closing()) at some suitable future moment.
1111 s->pending_error = err;
1113 * Immediately cease selecting on this socket, so that
1114 * we don't tight-loop repeatedly trying to do
1115 * whatever it was that went wrong.
1119 * Arrange to be called back from the top level to
1120 * deal with the error condition on this socket.
1122 queue_toplevel_callback(socket_error_callback, s);
1126 if (s->sending_oob) {
1128 memmove(s->oobdata, s->oobdata+nsent, len-nsent);
1129 s->sending_oob = len - nsent;
1134 bufchain_consume(&s->output_data, nsent);
1140 * If we reach here, we've finished sending everything we might
1141 * have needed to send. Send EOF, if we need to.
1143 if (s->outgoingeof == EOF_PENDING) {
1144 shutdown(s->s, SHUT_WR);
1145 s->outgoingeof = EOF_SENT;
1149 * Also update the select status, because we don't need to select
1150 * for writing any more.
1155 static int sk_tcp_write(Socket sock, const char *buf, int len)
1157 Actual_Socket s = (Actual_Socket) sock;
1159 assert(s->outgoingeof == EOF_NO);
1162 * Add the data to the buffer list on the socket.
1164 bufchain_add(&s->output_data, buf, len);
1167 * Now try sending from the start of the buffer list.
1173 * Update the select() status to correctly reflect whether or
1174 * not we should be selecting for write.
1178 return bufchain_size(&s->output_data);
1181 static int sk_tcp_write_oob(Socket sock, const char *buf, int len)
1183 Actual_Socket s = (Actual_Socket) sock;
1185 assert(s->outgoingeof == EOF_NO);
1188 * Replace the buffer list on the socket with the data.
1190 bufchain_clear(&s->output_data);
1191 assert(len <= sizeof(s->oobdata));
1192 memcpy(s->oobdata, buf, len);
1193 s->sending_oob = len;
1196 * Now try sending from the start of the buffer list.
1202 * Update the select() status to correctly reflect whether or
1203 * not we should be selecting for write.
1207 return s->sending_oob;
1210 static void sk_tcp_write_eof(Socket sock)
1212 Actual_Socket s = (Actual_Socket) sock;
1214 assert(s->outgoingeof == EOF_NO);
1217 * Mark the socket as pending outgoing EOF.
1219 s->outgoingeof = EOF_PENDING;
1222 * Now try sending from the start of the buffer list.
1228 * Update the select() status to correctly reflect whether or
1229 * not we should be selecting for write.
1234 static int net_select_result(int fd, int event)
1237 char buf[20480]; /* nice big buffer for plenty of speed */
1241 /* Find the Socket structure */
1242 s = find234(sktree, &fd, cmpforsearch);
1244 return 1; /* boggle */
1246 noise_ultralight(event);
1249 case 4: /* exceptional */
1250 if (!s->oobinline) {
1252 * On a non-oobinline socket, this indicates that we
1253 * can immediately perform an OOB read and get back OOB
1254 * data, which we will send to the back end with
1255 * type==2 (urgent data).
1257 ret = recv(s->s, buf, sizeof(buf), MSG_OOB);
1258 noise_ultralight(ret);
1260 return plug_closing(s->plug,
1261 ret == 0 ? "Internal networking trouble" :
1262 strerror(errno), errno, 0);
1265 * Receiving actual data on a socket means we can
1266 * stop falling back through the candidate
1267 * addresses to connect to.
1270 sk_addr_free(s->addr);
1273 return plug_receive(s->plug, 2, buf, ret);
1279 * If we reach here, this is an oobinline socket, which
1280 * means we should set s->oobpending and then deal with it
1281 * when we get called for the readability event (which
1282 * should also occur).
1284 s->oobpending = TRUE;
1286 case 1: /* readable; also acceptance */
1289 * On a listening socket, the readability event means a
1290 * connection is ready to be accepted.
1292 union sockaddr_union su;
1293 socklen_t addrlen = sizeof(su);
1295 int t; /* socket of connection */
1297 memset(&su, 0, addrlen);
1298 t = accept(s->s, &su.sa, &addrlen);
1306 if ((!s->addr || s->addr->superfamily != UNIX) &&
1307 s->localhost_only && !sockaddr_is_loopback(&su.sa)) {
1308 close(t); /* someone let nonlocal through?! */
1309 } else if (plug_accepting(s->plug, sk_tcp_accept, actx)) {
1310 close(t); /* denied or error */
1316 * If we reach here, this is not a listening socket, so
1317 * readability really means readability.
1320 /* In the case the socket is still frozen, we don't even bother */
1325 * We have received data on the socket. For an oobinline
1326 * socket, this might be data _before_ an urgent pointer,
1327 * in which case we send it to the back end with type==1
1328 * (data prior to urgent).
1330 if (s->oobinline && s->oobpending) {
1332 if (ioctl(s->s, SIOCATMARK, &atmark) == 0 && atmark)
1333 s->oobpending = FALSE; /* clear this indicator */
1337 ret = recv(s->s, buf, s->oobpending ? 1 : sizeof(buf), 0);
1338 noise_ultralight(ret);
1340 if (errno == EWOULDBLOCK) {
1346 * An error at this point _might_ be an error reported
1347 * by a non-blocking connect(). So before we return a
1348 * panic status to the user, let's just see whether
1353 plug_log(s->plug, 1, s->addr, s->port, strerror(err), err);
1354 while (s->addr && sk_nextaddr(s->addr, &s->step)) {
1355 err = try_connect(s);
1359 return plug_closing(s->plug, strerror(err), err, 0);
1360 } else if (0 == ret) {
1361 s->incomingeof = TRUE; /* stop trying to read now */
1363 return plug_closing(s->plug, NULL, 0, 0);
1366 * Receiving actual data on a socket means we can
1367 * stop falling back through the candidate
1368 * addresses to connect to.
1371 sk_addr_free(s->addr);
1374 return plug_receive(s->plug, atmark ? 0 : 1, buf, ret);
1377 case 2: /* writable */
1378 if (!s->connected) {
1380 * select() reports a socket as _writable_ when an
1381 * asynchronous connection is completed.
1383 s->connected = s->writable = 1;
1387 int bufsize_before, bufsize_after;
1389 bufsize_before = s->sending_oob + bufchain_size(&s->output_data);
1391 bufsize_after = s->sending_oob + bufchain_size(&s->output_data);
1392 if (bufsize_after < bufsize_before)
1393 plug_sent(s->plug, bufsize_after);
1402 * Special error values are returned from sk_namelookup and sk_new
1403 * if there's a problem. These functions extract an error message,
1404 * or return NULL if there's no problem.
1406 const char *sk_addr_error(SockAddr addr)
1410 static const char *sk_tcp_socket_error(Socket sock)
1412 Actual_Socket s = (Actual_Socket) sock;
1416 static void sk_tcp_set_frozen(Socket sock, int is_frozen)
1418 Actual_Socket s = (Actual_Socket) sock;
1419 if (s->frozen == is_frozen)
1421 s->frozen = is_frozen;
1425 static char *sk_tcp_peer_info(Socket sock)
1427 Actual_Socket s = (Actual_Socket) sock;
1428 union sockaddr_union addr;
1429 socklen_t addrlen = sizeof(addr);
1431 char buf[INET6_ADDRSTRLEN];
1434 if (getpeername(s->s, &addr.sa, &addrlen) < 0)
1436 if (addr.storage.ss_family == AF_INET) {
1439 inet_ntoa(addr.sin.sin_addr),
1440 (int)ntohs(addr.sin.sin_port));
1442 } else if (addr.storage.ss_family == AF_INET6) {
1445 inet_ntop(AF_INET6, &addr.sin6.sin6_addr, buf, sizeof(buf)),
1446 (int)ntohs(addr.sin6.sin6_port));
1448 } else if (addr.storage.ss_family == AF_UNIX) {
1450 * For Unix sockets, the source address is unlikely to be
1451 * helpful. Instead, we try SO_PEERCRED and try to get the
1455 if (so_peercred(s->s, &pid, &uid, &gid)) {
1456 char uidbuf[64], gidbuf[64];
1457 sprintf(uidbuf, "%d", uid);
1458 sprintf(gidbuf, "%d", gid);
1459 struct passwd *pw = getpwuid(uid);
1460 struct group *gr = getgrgid(gid);
1461 return dupprintf("pid %d (%s:%s)", pid,
1462 pw ? pw->pw_name : uidbuf,
1463 gr ? gr->gr_name : gidbuf);
1471 static void uxsel_tell(Actual_Socket s)
1474 if (!s->pending_error) {
1476 rwx |= 1; /* read == accept */
1479 rwx |= 2; /* write == connect */
1480 if (s->connected && !s->frozen && !s->incomingeof)
1481 rwx |= 1 | 4; /* read, except */
1482 if (bufchain_size(&s->output_data))
1483 rwx |= 2; /* write */
1486 uxsel_set(s->s, rwx, net_select_result);
1489 int net_service_lookup(char *service)
1492 se = getservbyname(service, NULL);
1494 return ntohs(se->s_port);
1499 char *get_hostname(void)
1502 char *hostname = NULL;
1505 hostname = sresize(hostname, len, char);
1506 if ((gethostname(hostname, len) < 0) &&
1507 (errno != ENAMETOOLONG)) {
1512 } while (strlen(hostname) >= len-1);
1516 SockAddr platform_get_x11_unix_address(const char *sockpath, int displaynum)
1518 SockAddr ret = snew(struct SockAddr_tag);
1521 memset(ret, 0, sizeof *ret);
1522 ret->superfamily = UNIX;
1524 * In special circumstances (notably Mac OS X Leopard), we'll
1525 * have been passed an explicit Unix socket path.
1528 n = snprintf(ret->hostname, sizeof ret->hostname,
1531 n = snprintf(ret->hostname, sizeof ret->hostname,
1532 "%s%d", X11_UNIX_PATH, displaynum);
1536 ret->error = "snprintf failed";
1537 else if (n >= sizeof ret->hostname)
1538 ret->error = "X11 UNIX name too long";
1543 ret->addresses = NULL;
1544 ret->naddresses = 0;
1550 SockAddr unix_sock_addr(const char *path)
1552 SockAddr ret = snew(struct SockAddr_tag);
1555 memset(ret, 0, sizeof *ret);
1556 ret->superfamily = UNIX;
1557 n = snprintf(ret->hostname, sizeof ret->hostname, "%s", path);
1560 ret->error = "snprintf failed";
1561 else if (n >= sizeof ret->hostname)
1562 ret->error = "socket pathname too long";
1567 ret->addresses = NULL;
1568 ret->naddresses = 0;
1574 Socket new_unix_listener(SockAddr listenaddr, Plug plug)
1577 union sockaddr_union u;
1578 union sockaddr_union *addr;
1584 * Create Socket structure.
1586 ret = snew(struct Socket_tag);
1587 ret->fn = &tcp_fn_table;
1590 bufchain_init(&ret->output_data);
1591 ret->writable = 0; /* to start with */
1592 ret->sending_oob = 0;
1594 ret->localhost_only = TRUE;
1595 ret->pending_error = 0;
1596 ret->parent = ret->child = NULL;
1597 ret->oobpending = FALSE;
1598 ret->outgoingeof = EOF_NO;
1599 ret->incomingeof = FALSE;
1601 ret->addr = listenaddr;
1604 assert(listenaddr->superfamily == UNIX);
1609 s = socket(AF_UNIX, SOCK_STREAM, 0);
1611 ret->error = strerror(errno);
1612 return (Socket) ret;
1619 memset(&u, '\0', sizeof(u));
1620 u.su.sun_family = AF_UNIX;
1621 strncpy(u.su.sun_path, listenaddr->hostname, sizeof(u.su.sun_path)-1);
1623 addrlen = sizeof(u.su);
1625 if (unlink(u.su.sun_path) < 0 && errno != ENOENT) {
1627 ret->error = strerror(errno);
1628 return (Socket) ret;
1631 retcode = bind(s, &addr->sa, addrlen);
1634 ret->error = strerror(errno);
1635 return (Socket) ret;
1638 if (listen(s, SOMAXCONN) < 0) {
1640 ret->error = strerror(errno);
1641 return (Socket) ret;
1647 add234(sktree, ret);
1649 return (Socket) ret;