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>
20 #define DEFINE_PLUG_METHOD_MACROS
25 /* Solaris needs <sys/sockio.h> for SIOCATMARK. */
27 #include <sys/sockio.h>
31 # define X11_UNIX_PATH "/tmp/.X11-unix/X"
35 * Access to sockaddr types without breaking C strict aliasing rules.
37 union sockaddr_union {
39 struct sockaddr_in storage;
41 struct sockaddr_storage storage;
42 struct sockaddr_in6 sin6;
45 struct sockaddr_in sin;
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 #define SOCKADDR_FAMILY(addr, step) \
130 ((addr)->superfamily == UNRESOLVED ? AF_UNSPEC : \
131 (addr)->superfamily == UNIX ? AF_UNIX : AF_INET)
135 * Start a SockAddrStep structure to step through multiple
139 #define START_STEP(addr, step) \
140 ((step).ai = (addr)->ais, (step).curraddr = 0)
142 #define START_STEP(addr, step) \
143 ((step).curraddr = 0)
146 static tree234 *sktree;
148 static void uxsel_tell(Actual_Socket s);
150 static int cmpfortree(void *av, void *bv)
152 Actual_Socket a = (Actual_Socket) av, b = (Actual_Socket) bv;
153 int as = a->s, bs = b->s;
165 static int cmpforsearch(void *av, void *bv)
167 Actual_Socket b = (Actual_Socket) bv;
168 int as = *(int *)av, bs = b->s;
178 sktree = newtree234(cmpfortree);
181 void sk_cleanup(void)
187 for (i = 0; (s = index234(sktree, i)) != NULL; i++) {
193 SockAddr sk_namelookup(const char *host, char **canonicalname, int address_family)
195 SockAddr ret = snew(struct SockAddr_tag);
197 struct addrinfo hints;
201 struct hostent *h = NULL;
206 /* Clear the structure and default to IPv4. */
207 memset(ret, 0, sizeof(struct SockAddr_tag));
208 ret->superfamily = UNRESOLVED;
214 hints.ai_flags = AI_CANONNAME;
215 hints.ai_family = (address_family == ADDRTYPE_IPV4 ? AF_INET :
216 address_family == ADDRTYPE_IPV6 ? AF_INET6 :
218 hints.ai_socktype = SOCK_STREAM;
219 hints.ai_protocol = 0;
220 hints.ai_addrlen = 0;
221 hints.ai_addr = NULL;
222 hints.ai_canonname = NULL;
223 hints.ai_next = NULL;
224 err = getaddrinfo(host, NULL, &hints, &ret->ais);
226 ret->error = gai_strerror(err);
229 ret->superfamily = IP;
231 if (ret->ais->ai_canonname != NULL)
232 strncat(realhost, ret->ais->ai_canonname, sizeof(realhost) - 1);
234 strncat(realhost, host, sizeof(realhost) - 1);
236 if ((a = inet_addr(host)) == (unsigned long)(in_addr_t)(-1)) {
238 * Otherwise use the IPv4-only gethostbyname... (NOTE:
239 * we don't use gethostbyname as a fallback!)
241 if (ret->superfamily == UNRESOLVED) {
242 /*debug(("Resolving \"%s\" with gethostbyname() (IPv4 only)...\n", host)); */
243 if ( (h = gethostbyname(host)) )
244 ret->superfamily = IP;
246 if (ret->superfamily == UNRESOLVED) {
247 ret->error = (h_errno == HOST_NOT_FOUND ||
248 h_errno == NO_DATA ||
249 h_errno == NO_ADDRESS ? "Host does not exist" :
250 h_errno == TRY_AGAIN ?
251 "Temporary name service failure" :
252 "gethostbyname: unknown error");
255 /* This way we are always sure the h->h_name is valid :) */
256 strncpy(realhost, h->h_name, sizeof(realhost));
257 for (n = 0; h->h_addr_list[n]; n++);
258 ret->addresses = snewn(n, unsigned long);
260 for (n = 0; n < ret->naddresses; n++) {
261 memcpy(&a, h->h_addr_list[n], sizeof(a));
262 ret->addresses[n] = ntohl(a);
266 * This must be a numeric IPv4 address because it caused a
267 * success return from inet_addr.
269 ret->superfamily = IP;
270 strncpy(realhost, host, sizeof(realhost));
271 ret->addresses = snew(unsigned long);
273 ret->addresses[0] = ntohl(a);
276 realhost[lenof(realhost)-1] = '\0';
277 *canonicalname = snewn(1+strlen(realhost), char);
278 strcpy(*canonicalname, realhost);
282 SockAddr sk_nonamelookup(const char *host)
284 SockAddr ret = snew(struct SockAddr_tag);
286 ret->superfamily = UNRESOLVED;
287 strncpy(ret->hostname, host, lenof(ret->hostname));
288 ret->hostname[lenof(ret->hostname)-1] = '\0';
292 ret->addresses = NULL;
298 static int sk_nextaddr(SockAddr addr, SockAddrStep *step)
301 if (step->ai && step->ai->ai_next) {
302 step->ai = step->ai->ai_next;
307 if (step->curraddr+1 < addr->naddresses) {
316 void sk_getaddr(SockAddr addr, char *buf, int buflen)
318 if (addr->superfamily == UNRESOLVED || addr->superfamily == UNIX) {
319 strncpy(buf, addr->hostname, buflen);
320 buf[buflen-1] = '\0';
323 if (getnameinfo(addr->ais->ai_addr, addr->ais->ai_addrlen, buf, buflen,
324 NULL, 0, NI_NUMERICHOST) != 0) {
326 strncat(buf, "<unknown>", buflen - 1);
331 START_STEP(addr, step);
332 assert(SOCKADDR_FAMILY(addr, step) == AF_INET);
333 a.s_addr = htonl(addr->addresses[0]);
334 strncpy(buf, inet_ntoa(a), buflen);
335 buf[buflen-1] = '\0';
340 int sk_hostname_is_local(const char *name)
342 return !strcmp(name, "localhost") ||
343 !strcmp(name, "::1") ||
344 !strncmp(name, "127.", 4);
347 #define ipv4_is_loopback(addr) \
348 (((addr).s_addr & htonl(0xff000000)) == htonl(0x7f000000))
350 static int sockaddr_is_loopback(struct sockaddr *sa)
352 union sockaddr_union *u = (union sockaddr_union *)sa;
353 switch (u->sa.sa_family) {
355 return ipv4_is_loopback(u->sin.sin_addr);
358 return IN6_IS_ADDR_LOOPBACK(&u->sin6.sin6_addr);
367 int sk_address_is_local(SockAddr addr)
369 if (addr->superfamily == UNRESOLVED)
370 return 0; /* we don't know; assume not */
371 else if (addr->superfamily == UNIX)
375 return sockaddr_is_loopback(addr->ais->ai_addr);
379 START_STEP(addr, step);
380 assert(SOCKADDR_FAMILY(addr, step) == AF_INET);
381 a.s_addr = htonl(addr->addresses[0]);
382 return ipv4_is_loopback(a);
387 int sk_address_is_special_local(SockAddr addr)
389 return addr->superfamily == UNIX;
392 int sk_addrtype(SockAddr addr)
396 START_STEP(addr, step);
397 family = SOCKADDR_FAMILY(addr, step);
399 return (family == AF_INET ? ADDRTYPE_IPV4 :
401 family == AF_INET6 ? ADDRTYPE_IPV6 :
406 void sk_addrcopy(SockAddr addr, char *buf)
410 START_STEP(addr, step);
411 family = SOCKADDR_FAMILY(addr, step);
414 if (family == AF_INET)
415 memcpy(buf, &((struct sockaddr_in *)step.ai->ai_addr)->sin_addr,
416 sizeof(struct in_addr));
417 else if (family == AF_INET6)
418 memcpy(buf, &((struct sockaddr_in6 *)step.ai->ai_addr)->sin6_addr,
419 sizeof(struct in6_addr));
425 assert(family == AF_INET);
426 a.s_addr = htonl(addr->addresses[step.curraddr]);
427 memcpy(buf, (char*) &a.s_addr, 4);
431 void sk_addr_free(SockAddr addr)
433 if (--addr->refcount > 0)
436 if (addr->ais != NULL)
437 freeaddrinfo(addr->ais);
439 sfree(addr->addresses);
444 SockAddr sk_addr_dup(SockAddr addr)
450 static Plug sk_tcp_plug(Socket sock, Plug p)
452 Actual_Socket s = (Actual_Socket) sock;
459 static void sk_tcp_flush(Socket s)
462 * We send data to the socket as soon as we can anyway,
463 * so we don't need to do anything here. :-)
467 static void sk_tcp_close(Socket s);
468 static int sk_tcp_write(Socket s, const char *data, int len);
469 static int sk_tcp_write_oob(Socket s, const char *data, int len);
470 static void sk_tcp_write_eof(Socket s);
471 static void sk_tcp_set_frozen(Socket s, int is_frozen);
472 static const char *sk_tcp_socket_error(Socket s);
474 static struct socket_function_table tcp_fn_table = {
485 static Socket sk_tcp_accept(accept_ctx_t ctx, Plug plug)
491 * Create Socket structure.
493 ret = snew(struct Socket_tag);
494 ret->fn = &tcp_fn_table;
497 bufchain_init(&ret->output_data);
498 ret->writable = 1; /* to start with */
499 ret->sending_oob = 0;
501 ret->localhost_only = 0; /* unused, but best init anyway */
502 ret->pending_error = 0;
503 ret->oobpending = FALSE;
504 ret->outgoingeof = EOF_NO;
505 ret->incomingeof = FALSE;
507 ret->parent = ret->child = NULL;
514 ret->error = strerror(errno);
526 static int try_connect(Actual_Socket sock)
529 union sockaddr_union u;
530 const union sockaddr_union *sa;
536 * Remove the socket from the tree before we overwrite its
537 * internal socket id, because that forms part of the tree's
538 * sorting criterion. We'll add it back before exiting this
539 * function, whether we changed anything or not.
541 del234(sktree, sock);
546 plug_log(sock->plug, 0, sock->addr, sock->port, NULL, 0);
551 family = SOCKADDR_FAMILY(sock->addr, sock->step);
552 assert(family != AF_UNSPEC);
553 s = socket(family, SOCK_STREAM, 0);
563 if (sock->oobinline) {
565 if (setsockopt(s, SOL_SOCKET, SO_OOBINLINE,
566 (void *) &b, sizeof(b)) < 0) {
575 if (setsockopt(s, IPPROTO_TCP, TCP_NODELAY,
576 (void *) &b, sizeof(b)) < 0) {
583 if (sock->keepalive) {
585 if (setsockopt(s, SOL_SOCKET, SO_KEEPALIVE,
586 (void *) &b, sizeof(b)) < 0) {
594 * Bind to local address.
597 localport = 1023; /* count from 1023 downwards */
599 localport = 0; /* just use port 0 (ie kernel picks) */
601 /* BSD IP stacks need sockaddr_in zeroed before filling in */
602 memset(&u,'\0',sizeof(u));
604 /* We don't try to bind to a local address for UNIX domain sockets. (Why
605 * do we bother doing the bind when localport == 0 anyway?) */
606 if (family != AF_UNIX) {
607 /* Loop round trying to bind */
612 if (family == AF_INET6) {
613 /* XXX use getaddrinfo to get a local address? */
614 u.sin6.sin6_family = AF_INET6;
615 u.sin6.sin6_addr = in6addr_any;
616 u.sin6.sin6_port = htons(localport);
617 retcode = bind(s, &u.sa, sizeof(u.sin6));
621 assert(family == AF_INET);
622 u.sin.sin_family = AF_INET;
623 u.sin.sin_addr.s_addr = htonl(INADDR_ANY);
624 u.sin.sin_port = htons(localport);
625 retcode = bind(s, &u.sa, sizeof(u.sin));
632 if (err != EADDRINUSE) /* failed, for a bad reason */
637 break; /* we're only looping once */
640 break; /* we might have got to the end */
648 * Connect to remote address.
653 /* XXX would be better to have got getaddrinfo() to fill in the port. */
654 ((struct sockaddr_in *)sock->step.ai->ai_addr)->sin_port =
656 sa = (const union sockaddr_union *)sock->step.ai->ai_addr;
657 salen = sock->step.ai->ai_addrlen;
660 ((struct sockaddr_in *)sock->step.ai->ai_addr)->sin_port =
662 sa = (const union sockaddr_union *)sock->step.ai->ai_addr;
663 salen = sock->step.ai->ai_addrlen;
667 u.sin.sin_family = AF_INET;
668 u.sin.sin_addr.s_addr = htonl(sock->addr->addresses[sock->step.curraddr]);
669 u.sin.sin_port = htons((short) sock->port);
671 salen = sizeof u.sin;
675 assert(sock->port == 0); /* to catch confused people */
676 assert(strlen(sock->addr->hostname) < sizeof u.su.sun_path);
677 u.su.sun_family = AF_UNIX;
678 strcpy(u.su.sun_path, sock->addr->hostname);
684 assert(0 && "unknown address family");
685 exit(1); /* XXX: GCC doesn't understand assert() on some systems. */
690 if ((connect(s, &(sa->sa), salen)) < 0) {
691 if ( errno != EINPROGRESS ) {
697 * If we _don't_ get EWOULDBLOCK, the connect has completed
698 * and we should set the socket as connected and writable.
709 * No matter what happened, put the socket back in the tree.
711 add234(sktree, sock);
714 plug_log(sock->plug, 1, sock->addr, sock->port, strerror(err), err);
718 Socket sk_new(SockAddr addr, int port, int privport, int oobinline,
719 int nodelay, int keepalive, Plug plug)
725 * Create Socket structure.
727 ret = snew(struct Socket_tag);
728 ret->fn = &tcp_fn_table;
731 bufchain_init(&ret->output_data);
732 ret->connected = 0; /* to start with */
733 ret->writable = 0; /* to start with */
734 ret->sending_oob = 0;
736 ret->localhost_only = 0; /* unused, but best init anyway */
737 ret->pending_error = 0;
738 ret->parent = ret->child = NULL;
739 ret->oobpending = FALSE;
740 ret->outgoingeof = EOF_NO;
741 ret->incomingeof = FALSE;
744 START_STEP(ret->addr, ret->step);
746 ret->oobinline = oobinline;
747 ret->nodelay = nodelay;
748 ret->keepalive = keepalive;
749 ret->privport = privport;
754 err = try_connect(ret);
755 } while (err && sk_nextaddr(ret->addr, &ret->step));
758 ret->error = strerror(err);
763 Socket sk_newlistener(char *srcaddr, int port, Plug plug, int local_host_only, int orig_address_family)
767 struct addrinfo hints, *ai;
770 union sockaddr_union u;
771 union sockaddr_union *addr;
779 * Create Socket structure.
781 ret = snew(struct Socket_tag);
782 ret->fn = &tcp_fn_table;
785 bufchain_init(&ret->output_data);
786 ret->writable = 0; /* to start with */
787 ret->sending_oob = 0;
789 ret->localhost_only = local_host_only;
790 ret->pending_error = 0;
791 ret->parent = ret->child = NULL;
792 ret->oobpending = FALSE;
793 ret->outgoingeof = EOF_NO;
794 ret->incomingeof = FALSE;
800 * Translate address_family from platform-independent constants
801 * into local reality.
803 address_family = (orig_address_family == ADDRTYPE_IPV4 ? AF_INET :
805 orig_address_family == ADDRTYPE_IPV6 ? AF_INET6 :
810 /* Let's default to IPv6.
811 * If the stack doesn't support IPv6, we will fall back to IPv4. */
812 if (address_family == AF_UNSPEC) address_family = AF_INET6;
814 /* No other choice, default to IPv4 */
815 if (address_family == AF_UNSPEC) address_family = AF_INET;
821 s = socket(address_family, SOCK_STREAM, 0);
824 /* If the host doesn't support IPv6 try fallback to IPv4. */
825 if (s < 0 && address_family == AF_INET6) {
826 address_family = AF_INET;
827 s = socket(address_family, SOCK_STREAM, 0);
832 ret->error = strerror(errno);
840 if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR,
841 (const char *)&on, sizeof(on)) < 0) {
842 ret->error = strerror(errno);
848 addr = NULL; addrlen = -1; /* placate optimiser */
850 if (srcaddr != NULL) {
852 hints.ai_flags = AI_NUMERICHOST;
853 hints.ai_family = address_family;
854 hints.ai_socktype = SOCK_STREAM;
855 hints.ai_protocol = 0;
856 hints.ai_addrlen = 0;
857 hints.ai_addr = NULL;
858 hints.ai_canonname = NULL;
859 hints.ai_next = NULL;
860 assert(port >= 0 && port <= 99999);
861 sprintf(portstr, "%d", port);
862 retcode = getaddrinfo(srcaddr, portstr, &hints, &ai);
864 addr = (union sockaddr_union *)ai->ai_addr;
865 addrlen = ai->ai_addrlen;
868 memset(&u,'\0',sizeof u);
869 u.sin.sin_family = AF_INET;
870 u.sin.sin_port = htons(port);
871 u.sin.sin_addr.s_addr = inet_addr(srcaddr);
872 if (u.sin.sin_addr.s_addr != (in_addr_t)(-1)) {
873 /* Override localhost_only with specified listen addr. */
874 ret->localhost_only = ipv4_is_loopback(u.sin.sin_addr);
877 addrlen = sizeof(u.sin);
883 memset(&u,'\0',sizeof u);
885 if (address_family == AF_INET6) {
886 u.sin6.sin6_family = AF_INET6;
887 u.sin6.sin6_port = htons(port);
889 u.sin6.sin6_addr = in6addr_loopback;
891 u.sin6.sin6_addr = in6addr_any;
893 addrlen = sizeof(u.sin6);
897 u.sin.sin_family = AF_INET;
898 u.sin.sin_port = htons(port);
900 u.sin.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
902 u.sin.sin_addr.s_addr = htonl(INADDR_ANY);
904 addrlen = sizeof(u.sin);
908 retcode = bind(s, &addr->sa, addrlen);
911 ret->error = strerror(errno);
915 if (listen(s, SOMAXCONN) < 0) {
917 ret->error = strerror(errno);
923 * If we were given ADDRTYPE_UNSPEC, we must also create an
924 * IPv4 listening socket and link it to this one.
926 if (address_family == AF_INET6 && orig_address_family == ADDRTYPE_UNSPEC) {
929 other = (Actual_Socket) sk_newlistener(srcaddr, port, plug,
930 local_host_only, ADDRTYPE_IPV4);
937 /* If we couldn't create a listening socket on IPv4 as well
938 * as IPv6, we must return an error overall. */
941 return (Socket) other;
955 static void sk_tcp_close(Socket sock)
957 Actual_Socket s = (Actual_Socket) sock;
960 sk_tcp_close((Socket)s->child);
966 sk_addr_free(s->addr);
970 void *sk_getxdmdata(void *sock, int *lenp)
972 Actual_Socket s = (Actual_Socket) sock;
973 union sockaddr_union u;
976 static unsigned int unix_addr = 0xFFFFFFFF;
979 * We must check that this socket really _is_ an Actual_Socket.
981 if (s->fn != &tcp_fn_table)
982 return NULL; /* failure */
985 if (getsockname(s->s, &u.sa, &addrlen) < 0)
987 switch(u.sa.sa_family) {
990 buf = snewn(*lenp, char);
991 PUT_32BIT_MSB_FIRST(buf, ntohl(u.sin.sin_addr.s_addr));
992 PUT_16BIT_MSB_FIRST(buf+4, ntohs(u.sin.sin_port));
997 buf = snewn(*lenp, char);
998 if (IN6_IS_ADDR_V4MAPPED(&u.sin6.sin6_addr)) {
999 memcpy(buf, u.sin6.sin6_addr.s6_addr + 12, 4);
1000 PUT_16BIT_MSB_FIRST(buf+4, ntohs(u.sin6.sin6_port));
1002 /* This is stupid, but it's what XLib does. */
1008 buf = snewn(*lenp, char);
1009 PUT_32BIT_MSB_FIRST(buf, unix_addr--);
1010 PUT_16BIT_MSB_FIRST(buf+4, getpid());
1023 * Deal with socket errors detected in try_send().
1025 static void socket_error_callback(void *vs)
1027 Actual_Socket s = (Actual_Socket)vs;
1030 * Just in case other socket work has caused this socket to vanish
1031 * or become somehow non-erroneous before this callback arrived...
1033 if (!find234(sktree, s, NULL) || !s->pending_error)
1037 * An error has occurred on this socket. Pass it to the plug.
1039 plug_closing(s->plug, strerror(s->pending_error), s->pending_error, 0);
1043 * The function which tries to send on a socket once it's deemed
1046 void try_send(Actual_Socket s)
1048 while (s->sending_oob || bufchain_size(&s->output_data) > 0) {
1052 int len, urgentflag;
1054 if (s->sending_oob) {
1055 urgentflag = MSG_OOB;
1056 len = s->sending_oob;
1060 bufchain_prefix(&s->output_data, &data, &len);
1062 nsent = send(s->s, data, len, urgentflag);
1063 noise_ultralight(nsent);
1065 err = (nsent < 0 ? errno : 0);
1066 if (err == EWOULDBLOCK) {
1068 * Perfectly normal: we've sent all we can for the moment.
1070 s->writable = FALSE;
1074 * We unfortunately can't just call plug_closing(),
1075 * because it's quite likely that we're currently
1076 * _in_ a call from the code we'd be calling back
1077 * to, so we'd have to make half the SSH code
1078 * reentrant. Instead we flag a pending error on
1079 * the socket, to be dealt with (by calling
1080 * plug_closing()) at some suitable future moment.
1082 s->pending_error = err;
1084 * Immediately cease selecting on this socket, so that
1085 * we don't tight-loop repeatedly trying to do
1086 * whatever it was that went wrong.
1090 * Arrange to be called back from the top level to
1091 * deal with the error condition on this socket.
1093 queue_toplevel_callback(socket_error_callback, s);
1097 if (s->sending_oob) {
1099 memmove(s->oobdata, s->oobdata+nsent, len-nsent);
1100 s->sending_oob = len - nsent;
1105 bufchain_consume(&s->output_data, nsent);
1111 * If we reach here, we've finished sending everything we might
1112 * have needed to send. Send EOF, if we need to.
1114 if (s->outgoingeof == EOF_PENDING) {
1115 shutdown(s->s, SHUT_WR);
1116 s->outgoingeof = EOF_SENT;
1120 * Also update the select status, because we don't need to select
1121 * for writing any more.
1126 static int sk_tcp_write(Socket sock, const char *buf, int len)
1128 Actual_Socket s = (Actual_Socket) sock;
1130 assert(s->outgoingeof == EOF_NO);
1133 * Add the data to the buffer list on the socket.
1135 bufchain_add(&s->output_data, buf, len);
1138 * Now try sending from the start of the buffer list.
1144 * Update the select() status to correctly reflect whether or
1145 * not we should be selecting for write.
1149 return bufchain_size(&s->output_data);
1152 static int sk_tcp_write_oob(Socket sock, const char *buf, int len)
1154 Actual_Socket s = (Actual_Socket) sock;
1156 assert(s->outgoingeof == EOF_NO);
1159 * Replace the buffer list on the socket with the data.
1161 bufchain_clear(&s->output_data);
1162 assert(len <= sizeof(s->oobdata));
1163 memcpy(s->oobdata, buf, len);
1164 s->sending_oob = 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 s->sending_oob;
1181 static void sk_tcp_write_eof(Socket sock)
1183 Actual_Socket s = (Actual_Socket) sock;
1185 assert(s->outgoingeof == EOF_NO);
1188 * Mark the socket as pending outgoing EOF.
1190 s->outgoingeof = EOF_PENDING;
1193 * Now try sending from the start of the buffer list.
1199 * Update the select() status to correctly reflect whether or
1200 * not we should be selecting for write.
1205 static int net_select_result(int fd, int event)
1208 char buf[20480]; /* nice big buffer for plenty of speed */
1212 /* Find the Socket structure */
1213 s = find234(sktree, &fd, cmpforsearch);
1215 return 1; /* boggle */
1217 noise_ultralight(event);
1220 case 4: /* exceptional */
1221 if (!s->oobinline) {
1223 * On a non-oobinline socket, this indicates that we
1224 * can immediately perform an OOB read and get back OOB
1225 * data, which we will send to the back end with
1226 * type==2 (urgent data).
1228 ret = recv(s->s, buf, sizeof(buf), MSG_OOB);
1229 noise_ultralight(ret);
1231 return plug_closing(s->plug,
1232 ret == 0 ? "Internal networking trouble" :
1233 strerror(errno), errno, 0);
1236 * Receiving actual data on a socket means we can
1237 * stop falling back through the candidate
1238 * addresses to connect to.
1241 sk_addr_free(s->addr);
1244 return plug_receive(s->plug, 2, buf, ret);
1250 * If we reach here, this is an oobinline socket, which
1251 * means we should set s->oobpending and then deal with it
1252 * when we get called for the readability event (which
1253 * should also occur).
1255 s->oobpending = TRUE;
1257 case 1: /* readable; also acceptance */
1260 * On a listening socket, the readability event means a
1261 * connection is ready to be accepted.
1263 union sockaddr_union su;
1264 socklen_t addrlen = sizeof(su);
1266 int t; /* socket of connection */
1268 memset(&su, 0, addrlen);
1269 t = accept(s->s, &su.sa, &addrlen);
1277 if ((!s->addr || s->addr->superfamily != UNIX) &&
1278 s->localhost_only && !sockaddr_is_loopback(&su.sa)) {
1279 close(t); /* someone let nonlocal through?! */
1280 } else if (plug_accepting(s->plug, sk_tcp_accept, actx)) {
1281 close(t); /* denied or error */
1287 * If we reach here, this is not a listening socket, so
1288 * readability really means readability.
1291 /* In the case the socket is still frozen, we don't even bother */
1296 * We have received data on the socket. For an oobinline
1297 * socket, this might be data _before_ an urgent pointer,
1298 * in which case we send it to the back end with type==1
1299 * (data prior to urgent).
1301 if (s->oobinline && s->oobpending) {
1303 if (ioctl(s->s, SIOCATMARK, &atmark) == 0 && atmark)
1304 s->oobpending = FALSE; /* clear this indicator */
1308 ret = recv(s->s, buf, s->oobpending ? 1 : sizeof(buf), 0);
1309 noise_ultralight(ret);
1311 if (errno == EWOULDBLOCK) {
1317 * An error at this point _might_ be an error reported
1318 * by a non-blocking connect(). So before we return a
1319 * panic status to the user, let's just see whether
1324 plug_log(s->plug, 1, s->addr, s->port, strerror(err), err);
1325 while (s->addr && sk_nextaddr(s->addr, &s->step)) {
1326 err = try_connect(s);
1330 return plug_closing(s->plug, strerror(err), err, 0);
1331 } else if (0 == ret) {
1332 s->incomingeof = TRUE; /* stop trying to read now */
1334 return plug_closing(s->plug, NULL, 0, 0);
1337 * Receiving actual data on a socket means we can
1338 * stop falling back through the candidate
1339 * addresses to connect to.
1342 sk_addr_free(s->addr);
1345 return plug_receive(s->plug, atmark ? 0 : 1, buf, ret);
1348 case 2: /* writable */
1349 if (!s->connected) {
1351 * select() reports a socket as _writable_ when an
1352 * asynchronous connection is completed.
1354 s->connected = s->writable = 1;
1358 int bufsize_before, bufsize_after;
1360 bufsize_before = s->sending_oob + bufchain_size(&s->output_data);
1362 bufsize_after = s->sending_oob + bufchain_size(&s->output_data);
1363 if (bufsize_after < bufsize_before)
1364 plug_sent(s->plug, bufsize_after);
1373 * Special error values are returned from sk_namelookup and sk_new
1374 * if there's a problem. These functions extract an error message,
1375 * or return NULL if there's no problem.
1377 const char *sk_addr_error(SockAddr addr)
1381 static const char *sk_tcp_socket_error(Socket sock)
1383 Actual_Socket s = (Actual_Socket) sock;
1387 static void sk_tcp_set_frozen(Socket sock, int is_frozen)
1389 Actual_Socket s = (Actual_Socket) sock;
1390 if (s->frozen == is_frozen)
1392 s->frozen = is_frozen;
1396 static void uxsel_tell(Actual_Socket s)
1399 if (!s->pending_error) {
1401 rwx |= 1; /* read == accept */
1404 rwx |= 2; /* write == connect */
1405 if (s->connected && !s->frozen && !s->incomingeof)
1406 rwx |= 1 | 4; /* read, except */
1407 if (bufchain_size(&s->output_data))
1408 rwx |= 2; /* write */
1411 uxsel_set(s->s, rwx, net_select_result);
1414 int net_service_lookup(char *service)
1417 se = getservbyname(service, NULL);
1419 return ntohs(se->s_port);
1424 char *get_hostname(void)
1427 char *hostname = NULL;
1430 hostname = sresize(hostname, len, char);
1431 if ((gethostname(hostname, len) < 0) &&
1432 (errno != ENAMETOOLONG)) {
1437 } while (strlen(hostname) >= len-1);
1441 SockAddr platform_get_x11_unix_address(const char *sockpath, int displaynum)
1443 SockAddr ret = snew(struct SockAddr_tag);
1446 memset(ret, 0, sizeof *ret);
1447 ret->superfamily = UNIX;
1449 * In special circumstances (notably Mac OS X Leopard), we'll
1450 * have been passed an explicit Unix socket path.
1453 n = snprintf(ret->hostname, sizeof ret->hostname,
1456 n = snprintf(ret->hostname, sizeof ret->hostname,
1457 "%s%d", X11_UNIX_PATH, displaynum);
1461 ret->error = "snprintf failed";
1462 else if (n >= sizeof ret->hostname)
1463 ret->error = "X11 UNIX name too long";
1468 ret->addresses = NULL;
1469 ret->naddresses = 0;
1475 SockAddr unix_sock_addr(const char *path)
1477 SockAddr ret = snew(struct SockAddr_tag);
1480 memset(ret, 0, sizeof *ret);
1481 ret->superfamily = UNIX;
1482 n = snprintf(ret->hostname, sizeof ret->hostname, "%s", path);
1485 ret->error = "snprintf failed";
1486 else if (n >= sizeof ret->hostname)
1487 ret->error = "socket pathname too long";
1492 ret->addresses = NULL;
1493 ret->naddresses = 0;
1499 Socket new_unix_listener(SockAddr listenaddr, Plug plug)
1502 union sockaddr_union u;
1503 union sockaddr_union *addr;
1509 * Create Socket structure.
1511 ret = snew(struct Socket_tag);
1512 ret->fn = &tcp_fn_table;
1515 bufchain_init(&ret->output_data);
1516 ret->writable = 0; /* to start with */
1517 ret->sending_oob = 0;
1519 ret->localhost_only = TRUE;
1520 ret->pending_error = 0;
1521 ret->parent = ret->child = NULL;
1522 ret->oobpending = FALSE;
1523 ret->outgoingeof = EOF_NO;
1524 ret->incomingeof = FALSE;
1526 ret->addr = listenaddr;
1529 assert(listenaddr->superfamily == UNIX);
1534 s = socket(AF_UNIX, SOCK_STREAM, 0);
1536 ret->error = strerror(errno);
1537 return (Socket) ret;
1544 memset(&u, '\0', sizeof(u));
1545 u.su.sun_family = AF_UNIX;
1546 strncpy(u.su.sun_path, listenaddr->hostname, sizeof(u.su.sun_path)-1);
1548 addrlen = sizeof(u.su);
1550 if (unlink(u.su.sun_path) < 0 && errno != ENOENT) {
1552 ret->error = strerror(errno);
1553 return (Socket) ret;
1556 retcode = bind(s, &addr->sa, addrlen);
1559 ret->error = strerror(errno);
1560 return (Socket) ret;
1563 if (listen(s, SOMAXCONN) < 0) {
1565 ret->error = strerror(errno);
1566 return (Socket) ret;
1572 add234(sktree, ret);
1574 return (Socket) ret;