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 */
80 int connected; /* irrelevant for listening sockets */
82 int frozen; /* this causes readability notifications to be ignored */
83 int localhost_only; /* for listening sockets */
86 int oobpending; /* is there OOB data available to read? */
88 enum { EOF_NO, EOF_PENDING, EOF_SENT } outgoingeof;
90 int pending_error; /* in case send() returns error */
92 int nodelay, keepalive; /* for connect()-type sockets */
93 int privport, port; /* and again */
97 * We sometimes need pairs of Socket structures to be linked:
98 * if we are listening on the same IPv6 and v4 port, for
99 * example. So here we define `parent' and `child' pointers to
102 Actual_Socket parent, child;
105 struct SockAddr_tag {
108 enum { UNRESOLVED, UNIX, IP } superfamily;
110 struct addrinfo *ais; /* Addresses IPv6 style. */
112 unsigned long *addresses; /* Addresses IPv4 style. */
115 char hostname[512]; /* Store an unresolved host name. */
119 * Which address family this address belongs to. AF_INET for IPv4;
120 * AF_INET6 for IPv6; AF_UNSPEC indicates that name resolution has
121 * not been done and a simple host name is held in this SockAddr
125 #define SOCKADDR_FAMILY(addr, step) \
126 ((addr)->superfamily == UNRESOLVED ? AF_UNSPEC : \
127 (addr)->superfamily == UNIX ? AF_UNIX : \
128 (step).ai ? (step).ai->ai_family : AF_INET)
130 #define SOCKADDR_FAMILY(addr, step) \
131 ((addr)->superfamily == UNRESOLVED ? AF_UNSPEC : \
132 (addr)->superfamily == UNIX ? AF_UNIX : AF_INET)
136 * Start a SockAddrStep structure to step through multiple
140 #define START_STEP(addr, step) \
141 ((step).ai = (addr)->ais, (step).curraddr = 0)
143 #define START_STEP(addr, step) \
144 ((step).curraddr = 0)
147 static tree234 *sktree;
149 static void uxsel_tell(Actual_Socket s);
151 static int cmpfortree(void *av, void *bv)
153 Actual_Socket a = (Actual_Socket) av, b = (Actual_Socket) bv;
154 int as = a->s, bs = b->s;
166 static int cmpforsearch(void *av, void *bv)
168 Actual_Socket b = (Actual_Socket) bv;
169 int as = *(int *)av, bs = b->s;
179 sktree = newtree234(cmpfortree);
182 void sk_cleanup(void)
188 for (i = 0; (s = index234(sktree, i)) != NULL; i++) {
194 SockAddr sk_namelookup(const char *host, char **canonicalname, int address_family)
196 SockAddr ret = snew(struct SockAddr_tag);
198 struct addrinfo hints;
202 struct hostent *h = NULL;
207 /* Clear the structure and default to IPv4. */
208 memset(ret, 0, sizeof(struct SockAddr_tag));
209 ret->superfamily = UNRESOLVED;
215 hints.ai_flags = AI_CANONNAME;
216 hints.ai_family = (address_family == ADDRTYPE_IPV4 ? AF_INET :
217 address_family == ADDRTYPE_IPV6 ? AF_INET6 :
219 hints.ai_socktype = SOCK_STREAM;
220 hints.ai_protocol = 0;
221 hints.ai_addrlen = 0;
222 hints.ai_addr = NULL;
223 hints.ai_canonname = NULL;
224 hints.ai_next = NULL;
225 err = getaddrinfo(host, NULL, &hints, &ret->ais);
227 ret->error = gai_strerror(err);
230 ret->superfamily = IP;
232 if (ret->ais->ai_canonname != NULL)
233 strncat(realhost, ret->ais->ai_canonname, sizeof(realhost) - 1);
235 strncat(realhost, host, sizeof(realhost) - 1);
237 if ((a = inet_addr(host)) == (unsigned long)(in_addr_t)(-1)) {
239 * Otherwise use the IPv4-only gethostbyname... (NOTE:
240 * we don't use gethostbyname as a fallback!)
242 if (ret->superfamily == UNRESOLVED) {
243 /*debug(("Resolving \"%s\" with gethostbyname() (IPv4 only)...\n", host)); */
244 if ( (h = gethostbyname(host)) )
245 ret->superfamily = IP;
247 if (ret->superfamily == UNRESOLVED) {
248 ret->error = (h_errno == HOST_NOT_FOUND ||
249 h_errno == NO_DATA ||
250 h_errno == NO_ADDRESS ? "Host does not exist" :
251 h_errno == TRY_AGAIN ?
252 "Temporary name service failure" :
253 "gethostbyname: unknown error");
256 /* This way we are always sure the h->h_name is valid :) */
257 strncpy(realhost, h->h_name, sizeof(realhost));
258 for (n = 0; h->h_addr_list[n]; n++);
259 ret->addresses = snewn(n, unsigned long);
261 for (n = 0; n < ret->naddresses; n++) {
262 memcpy(&a, h->h_addr_list[n], sizeof(a));
263 ret->addresses[n] = ntohl(a);
267 * This must be a numeric IPv4 address because it caused a
268 * success return from inet_addr.
270 ret->superfamily = IP;
271 strncpy(realhost, host, sizeof(realhost));
272 ret->addresses = snew(unsigned long);
274 ret->addresses[0] = ntohl(a);
277 realhost[lenof(realhost)-1] = '\0';
278 *canonicalname = snewn(1+strlen(realhost), char);
279 strcpy(*canonicalname, realhost);
283 SockAddr sk_nonamelookup(const char *host)
285 SockAddr ret = snew(struct SockAddr_tag);
287 ret->superfamily = UNRESOLVED;
288 strncpy(ret->hostname, host, lenof(ret->hostname));
289 ret->hostname[lenof(ret->hostname)-1] = '\0';
293 ret->addresses = NULL;
299 static int sk_nextaddr(SockAddr addr, SockAddrStep *step)
302 if (step->ai && step->ai->ai_next) {
303 step->ai = step->ai->ai_next;
308 if (step->curraddr+1 < addr->naddresses) {
317 void sk_getaddr(SockAddr addr, char *buf, int buflen)
319 /* XXX not clear what we should return for Unix-domain sockets; let's
320 * hope the question never arises */
321 assert(addr->superfamily != UNIX);
322 if (addr->superfamily == UNRESOLVED) {
323 strncpy(buf, addr->hostname, buflen);
324 buf[buflen-1] = '\0';
327 if (getnameinfo(addr->ais->ai_addr, addr->ais->ai_addrlen, buf, buflen,
328 NULL, 0, NI_NUMERICHOST) != 0) {
330 strncat(buf, "<unknown>", buflen - 1);
335 START_STEP(addr, step);
336 assert(SOCKADDR_FAMILY(addr, step) == AF_INET);
337 a.s_addr = htonl(addr->addresses[0]);
338 strncpy(buf, inet_ntoa(a), buflen);
339 buf[buflen-1] = '\0';
344 int sk_hostname_is_local(const char *name)
346 return !strcmp(name, "localhost") ||
347 !strcmp(name, "::1") ||
348 !strncmp(name, "127.", 4);
351 #define ipv4_is_loopback(addr) \
352 (((addr).s_addr & htonl(0xff000000)) == htonl(0x7f000000))
354 static int sockaddr_is_loopback(struct sockaddr *sa)
356 union sockaddr_union *u = (union sockaddr_union *)sa;
357 switch (u->sa.sa_family) {
359 return ipv4_is_loopback(u->sin.sin_addr);
362 return IN6_IS_ADDR_LOOPBACK(&u->sin6.sin6_addr);
371 int sk_address_is_local(SockAddr addr)
373 if (addr->superfamily == UNRESOLVED)
374 return 0; /* we don't know; assume not */
375 else if (addr->superfamily == UNIX)
379 return sockaddr_is_loopback(addr->ais->ai_addr);
383 START_STEP(addr, step);
384 assert(SOCKADDR_FAMILY(addr, step) == AF_INET);
385 a.s_addr = htonl(addr->addresses[0]);
386 return ipv4_is_loopback(a);
391 int sk_address_is_special_local(SockAddr addr)
393 return addr->superfamily == UNIX;
396 int sk_addrtype(SockAddr addr)
400 START_STEP(addr, step);
401 family = SOCKADDR_FAMILY(addr, step);
403 return (family == AF_INET ? ADDRTYPE_IPV4 :
405 family == AF_INET6 ? ADDRTYPE_IPV6 :
410 void sk_addrcopy(SockAddr addr, char *buf)
414 START_STEP(addr, step);
415 family = SOCKADDR_FAMILY(addr, step);
418 if (family == AF_INET)
419 memcpy(buf, &((struct sockaddr_in *)step.ai->ai_addr)->sin_addr,
420 sizeof(struct in_addr));
421 else if (family == AF_INET6)
422 memcpy(buf, &((struct sockaddr_in6 *)step.ai->ai_addr)->sin6_addr,
423 sizeof(struct in6_addr));
429 assert(family == AF_INET);
430 a.s_addr = htonl(addr->addresses[step.curraddr]);
431 memcpy(buf, (char*) &a.s_addr, 4);
435 void sk_addr_free(SockAddr addr)
437 if (--addr->refcount > 0)
440 if (addr->ais != NULL)
441 freeaddrinfo(addr->ais);
443 sfree(addr->addresses);
448 SockAddr sk_addr_dup(SockAddr addr)
454 static Plug sk_tcp_plug(Socket sock, Plug p)
456 Actual_Socket s = (Actual_Socket) sock;
463 static void sk_tcp_flush(Socket s)
466 * We send data to the socket as soon as we can anyway,
467 * so we don't need to do anything here. :-)
471 static void sk_tcp_close(Socket s);
472 static int sk_tcp_write(Socket s, const char *data, int len);
473 static int sk_tcp_write_oob(Socket s, const char *data, int len);
474 static void sk_tcp_write_eof(Socket s);
475 static void sk_tcp_set_private_ptr(Socket s, void *ptr);
476 static void *sk_tcp_get_private_ptr(Socket s);
477 static void sk_tcp_set_frozen(Socket s, int is_frozen);
478 static const char *sk_tcp_socket_error(Socket s);
480 static struct socket_function_table tcp_fn_table = {
487 sk_tcp_set_private_ptr,
488 sk_tcp_get_private_ptr,
493 Socket sk_register(OSSocket sockfd, Plug plug)
498 * Create Socket structure.
500 ret = snew(struct Socket_tag);
501 ret->fn = &tcp_fn_table;
504 bufchain_init(&ret->output_data);
505 ret->writable = 1; /* to start with */
506 ret->sending_oob = 0;
508 ret->localhost_only = 0; /* unused, but best init anyway */
509 ret->pending_error = 0;
510 ret->oobpending = FALSE;
511 ret->outgoingeof = EOF_NO;
512 ret->incomingeof = FALSE;
514 ret->parent = ret->child = NULL;
521 ret->error = strerror(errno);
533 static int try_connect(Actual_Socket sock)
536 union sockaddr_union u;
537 const union sockaddr_union *sa;
543 * Remove the socket from the tree before we overwrite its
544 * internal socket id, because that forms part of the tree's
545 * sorting criterion. We'll add it back before exiting this
546 * function, whether we changed anything or not.
548 del234(sktree, sock);
553 plug_log(sock->plug, 0, sock->addr, sock->port, NULL, 0);
558 family = SOCKADDR_FAMILY(sock->addr, sock->step);
559 assert(family != AF_UNSPEC);
560 s = socket(family, SOCK_STREAM, 0);
570 if (sock->oobinline) {
572 if (setsockopt(s, SOL_SOCKET, SO_OOBINLINE,
573 (void *) &b, sizeof(b)) < 0) {
582 if (setsockopt(s, IPPROTO_TCP, TCP_NODELAY,
583 (void *) &b, sizeof(b)) < 0) {
590 if (sock->keepalive) {
592 if (setsockopt(s, SOL_SOCKET, SO_KEEPALIVE,
593 (void *) &b, sizeof(b)) < 0) {
601 * Bind to local address.
604 localport = 1023; /* count from 1023 downwards */
606 localport = 0; /* just use port 0 (ie kernel picks) */
608 /* BSD IP stacks need sockaddr_in zeroed before filling in */
609 memset(&u,'\0',sizeof(u));
611 /* We don't try to bind to a local address for UNIX domain sockets. (Why
612 * do we bother doing the bind when localport == 0 anyway?) */
613 if (family != AF_UNIX) {
614 /* Loop round trying to bind */
619 if (family == AF_INET6) {
620 /* XXX use getaddrinfo to get a local address? */
621 u.sin6.sin6_family = AF_INET6;
622 u.sin6.sin6_addr = in6addr_any;
623 u.sin6.sin6_port = htons(localport);
624 retcode = bind(s, &u.sa, sizeof(u.sin6));
628 assert(family == AF_INET);
629 u.sin.sin_family = AF_INET;
630 u.sin.sin_addr.s_addr = htonl(INADDR_ANY);
631 u.sin.sin_port = htons(localport);
632 retcode = bind(s, &u.sa, sizeof(u.sin));
639 if (err != EADDRINUSE) /* failed, for a bad reason */
644 break; /* we're only looping once */
647 break; /* we might have got to the end */
655 * Connect to remote address.
660 /* XXX would be better to have got getaddrinfo() to fill in the port. */
661 ((struct sockaddr_in *)sock->step.ai->ai_addr)->sin_port =
663 sa = (const union sockaddr_union *)sock->step.ai->ai_addr;
664 salen = sock->step.ai->ai_addrlen;
667 ((struct sockaddr_in *)sock->step.ai->ai_addr)->sin_port =
669 sa = (const union sockaddr_union *)sock->step.ai->ai_addr;
670 salen = sock->step.ai->ai_addrlen;
674 u.sin.sin_family = AF_INET;
675 u.sin.sin_addr.s_addr = htonl(sock->addr->addresses[sock->step.curraddr]);
676 u.sin.sin_port = htons((short) sock->port);
678 salen = sizeof u.sin;
682 assert(sock->port == 0); /* to catch confused people */
683 assert(strlen(sock->addr->hostname) < sizeof u.su.sun_path);
684 u.su.sun_family = AF_UNIX;
685 strcpy(u.su.sun_path, sock->addr->hostname);
691 assert(0 && "unknown address family");
692 exit(1); /* XXX: GCC doesn't understand assert() on some systems. */
697 if ((connect(s, &(sa->sa), salen)) < 0) {
698 if ( errno != EINPROGRESS ) {
704 * If we _don't_ get EWOULDBLOCK, the connect has completed
705 * and we should set the socket as connected and writable.
716 * No matter what happened, put the socket back in the tree.
718 add234(sktree, sock);
721 plug_log(sock->plug, 1, sock->addr, sock->port, strerror(err), err);
725 Socket sk_new(SockAddr addr, int port, int privport, int oobinline,
726 int nodelay, int keepalive, Plug plug)
732 * Create Socket structure.
734 ret = snew(struct Socket_tag);
735 ret->fn = &tcp_fn_table;
738 bufchain_init(&ret->output_data);
739 ret->connected = 0; /* to start with */
740 ret->writable = 0; /* to start with */
741 ret->sending_oob = 0;
743 ret->localhost_only = 0; /* unused, but best init anyway */
744 ret->pending_error = 0;
745 ret->parent = ret->child = NULL;
746 ret->oobpending = FALSE;
747 ret->outgoingeof = EOF_NO;
748 ret->incomingeof = FALSE;
751 START_STEP(ret->addr, ret->step);
753 ret->oobinline = oobinline;
754 ret->nodelay = nodelay;
755 ret->keepalive = keepalive;
756 ret->privport = privport;
761 err = try_connect(ret);
762 } while (err && sk_nextaddr(ret->addr, &ret->step));
765 ret->error = strerror(err);
770 Socket sk_newlistener(char *srcaddr, int port, Plug plug, int local_host_only, int orig_address_family)
774 struct addrinfo hints, *ai;
777 union sockaddr_union u;
778 union sockaddr_union *addr;
786 * Create Socket structure.
788 ret = snew(struct Socket_tag);
789 ret->fn = &tcp_fn_table;
792 bufchain_init(&ret->output_data);
793 ret->writable = 0; /* to start with */
794 ret->sending_oob = 0;
796 ret->localhost_only = local_host_only;
797 ret->pending_error = 0;
798 ret->parent = ret->child = NULL;
799 ret->oobpending = FALSE;
800 ret->outgoingeof = EOF_NO;
801 ret->incomingeof = FALSE;
806 * Translate address_family from platform-independent constants
807 * into local reality.
809 address_family = (orig_address_family == ADDRTYPE_IPV4 ? AF_INET :
811 orig_address_family == ADDRTYPE_IPV6 ? AF_INET6 :
816 /* Let's default to IPv6.
817 * If the stack doesn't support IPv6, we will fall back to IPv4. */
818 if (address_family == AF_UNSPEC) address_family = AF_INET6;
820 /* No other choice, default to IPv4 */
821 if (address_family == AF_UNSPEC) address_family = AF_INET;
827 s = socket(address_family, SOCK_STREAM, 0);
830 /* If the host doesn't support IPv6 try fallback to IPv4. */
831 if (s < 0 && address_family == AF_INET6) {
832 address_family = AF_INET;
833 s = socket(address_family, SOCK_STREAM, 0);
838 ret->error = strerror(errno);
846 if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR,
847 (const char *)&on, sizeof(on)) < 0) {
848 ret->error = strerror(errno);
854 addr = NULL; addrlen = -1; /* placate optimiser */
856 if (srcaddr != NULL) {
858 hints.ai_flags = AI_NUMERICHOST;
859 hints.ai_family = address_family;
860 hints.ai_socktype = SOCK_STREAM;
861 hints.ai_protocol = 0;
862 hints.ai_addrlen = 0;
863 hints.ai_addr = NULL;
864 hints.ai_canonname = NULL;
865 hints.ai_next = NULL;
866 assert(port >= 0 && port <= 99999);
867 sprintf(portstr, "%d", port);
868 retcode = getaddrinfo(srcaddr, portstr, &hints, &ai);
870 addr = (union sockaddr_union *)ai->ai_addr;
871 addrlen = ai->ai_addrlen;
874 memset(&u,'\0',sizeof u);
875 u.sin.sin_family = AF_INET;
876 u.sin.sin_port = htons(port);
877 u.sin.sin_addr.s_addr = inet_addr(srcaddr);
878 if (u.sin.sin_addr.s_addr != (in_addr_t)(-1)) {
879 /* Override localhost_only with specified listen addr. */
880 ret->localhost_only = ipv4_is_loopback(u.sin.sin_addr);
883 addrlen = sizeof(u.sin);
889 memset(&u,'\0',sizeof u);
891 if (address_family == AF_INET6) {
892 u.sin6.sin6_family = AF_INET6;
893 u.sin6.sin6_port = htons(port);
895 u.sin6.sin6_addr = in6addr_loopback;
897 u.sin6.sin6_addr = in6addr_any;
899 addrlen = sizeof(u.sin6);
903 u.sin.sin_family = AF_INET;
904 u.sin.sin_port = htons(port);
906 u.sin.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
908 u.sin.sin_addr.s_addr = htonl(INADDR_ANY);
910 addrlen = sizeof(u.sin);
914 retcode = bind(s, &addr->sa, addrlen);
917 ret->error = strerror(errno);
921 if (listen(s, SOMAXCONN) < 0) {
923 ret->error = strerror(errno);
929 * If we were given ADDRTYPE_UNSPEC, we must also create an
930 * IPv4 listening socket and link it to this one.
932 if (address_family == AF_INET6 && orig_address_family == ADDRTYPE_UNSPEC) {
935 other = (Actual_Socket) sk_newlistener(srcaddr, port, plug,
936 local_host_only, ADDRTYPE_IPV4);
943 /* If we couldn't create a listening socket on IPv4 as well
944 * as IPv6, we must return an error overall. */
947 return (Socket) other;
961 static void sk_tcp_close(Socket sock)
963 Actual_Socket s = (Actual_Socket) sock;
966 sk_tcp_close((Socket)s->child);
972 sk_addr_free(s->addr);
976 void *sk_getxdmdata(void *sock, int *lenp)
978 Actual_Socket s = (Actual_Socket) sock;
979 union sockaddr_union u;
982 static unsigned int unix_addr = 0xFFFFFFFF;
985 * We must check that this socket really _is_ an Actual_Socket.
987 if (s->fn != &tcp_fn_table)
988 return NULL; /* failure */
991 if (getsockname(s->s, &u.sa, &addrlen) < 0)
993 switch(u.sa.sa_family) {
996 buf = snewn(*lenp, char);
997 PUT_32BIT_MSB_FIRST(buf, ntohl(u.sin.sin_addr.s_addr));
998 PUT_16BIT_MSB_FIRST(buf+4, ntohs(u.sin.sin_port));
1003 buf = snewn(*lenp, char);
1004 if (IN6_IS_ADDR_V4MAPPED(&u.sin6.sin6_addr)) {
1005 memcpy(buf, u.sin6.sin6_addr.s6_addr + 12, 4);
1006 PUT_16BIT_MSB_FIRST(buf+4, ntohs(u.sin6.sin6_port));
1008 /* This is stupid, but it's what XLib does. */
1014 buf = snewn(*lenp, char);
1015 PUT_32BIT_MSB_FIRST(buf, unix_addr--);
1016 PUT_16BIT_MSB_FIRST(buf+4, getpid());
1029 * Deal with socket errors detected in try_send().
1031 static void socket_error_callback(void *vs)
1033 Actual_Socket s = (Actual_Socket)vs;
1036 * Just in case other socket work has caused this socket to vanish
1037 * or become somehow non-erroneous before this callback arrived...
1039 if (!find234(sktree, s, NULL) || !s->pending_error)
1043 * An error has occurred on this socket. Pass it to the plug.
1045 plug_closing(s->plug, strerror(s->pending_error), s->pending_error, 0);
1049 * The function which tries to send on a socket once it's deemed
1052 void try_send(Actual_Socket s)
1054 while (s->sending_oob || bufchain_size(&s->output_data) > 0) {
1058 int len, urgentflag;
1060 if (s->sending_oob) {
1061 urgentflag = MSG_OOB;
1062 len = s->sending_oob;
1066 bufchain_prefix(&s->output_data, &data, &len);
1068 nsent = send(s->s, data, len, urgentflag);
1069 noise_ultralight(nsent);
1071 err = (nsent < 0 ? errno : 0);
1072 if (err == EWOULDBLOCK) {
1074 * Perfectly normal: we've sent all we can for the moment.
1076 s->writable = FALSE;
1080 * We unfortunately can't just call plug_closing(),
1081 * because it's quite likely that we're currently
1082 * _in_ a call from the code we'd be calling back
1083 * to, so we'd have to make half the SSH code
1084 * reentrant. Instead we flag a pending error on
1085 * the socket, to be dealt with (by calling
1086 * plug_closing()) at some suitable future moment.
1088 s->pending_error = err;
1090 * Immediately cease selecting on this socket, so that
1091 * we don't tight-loop repeatedly trying to do
1092 * whatever it was that went wrong.
1096 * Arrange to be called back from the top level to
1097 * deal with the error condition on this socket.
1099 queue_toplevel_callback(socket_error_callback, s);
1103 if (s->sending_oob) {
1105 memmove(s->oobdata, s->oobdata+nsent, len-nsent);
1106 s->sending_oob = len - nsent;
1111 bufchain_consume(&s->output_data, nsent);
1117 * If we reach here, we've finished sending everything we might
1118 * have needed to send. Send EOF, if we need to.
1120 if (s->outgoingeof == EOF_PENDING) {
1121 shutdown(s->s, SHUT_WR);
1122 s->outgoingeof = EOF_SENT;
1126 * Also update the select status, because we don't need to select
1127 * for writing any more.
1132 static int sk_tcp_write(Socket sock, const char *buf, int len)
1134 Actual_Socket s = (Actual_Socket) sock;
1136 assert(s->outgoingeof == EOF_NO);
1139 * Add the data to the buffer list on the socket.
1141 bufchain_add(&s->output_data, buf, len);
1144 * Now try sending from the start of the buffer list.
1150 * Update the select() status to correctly reflect whether or
1151 * not we should be selecting for write.
1155 return bufchain_size(&s->output_data);
1158 static int sk_tcp_write_oob(Socket sock, const char *buf, int len)
1160 Actual_Socket s = (Actual_Socket) sock;
1162 assert(s->outgoingeof == EOF_NO);
1165 * Replace the buffer list on the socket with the data.
1167 bufchain_clear(&s->output_data);
1168 assert(len <= sizeof(s->oobdata));
1169 memcpy(s->oobdata, buf, len);
1170 s->sending_oob = len;
1173 * Now try sending from the start of the buffer list.
1179 * Update the select() status to correctly reflect whether or
1180 * not we should be selecting for write.
1184 return s->sending_oob;
1187 static void sk_tcp_write_eof(Socket sock)
1189 Actual_Socket s = (Actual_Socket) sock;
1191 assert(s->outgoingeof == EOF_NO);
1194 * Mark the socket as pending outgoing EOF.
1196 s->outgoingeof = EOF_PENDING;
1199 * Now try sending from the start of the buffer list.
1205 * Update the select() status to correctly reflect whether or
1206 * not we should be selecting for write.
1211 static int net_select_result(int fd, int event)
1214 char buf[20480]; /* nice big buffer for plenty of speed */
1218 /* Find the Socket structure */
1219 s = find234(sktree, &fd, cmpforsearch);
1221 return 1; /* boggle */
1223 noise_ultralight(event);
1226 case 4: /* exceptional */
1227 if (!s->oobinline) {
1229 * On a non-oobinline socket, this indicates that we
1230 * can immediately perform an OOB read and get back OOB
1231 * data, which we will send to the back end with
1232 * type==2 (urgent data).
1234 ret = recv(s->s, buf, sizeof(buf), MSG_OOB);
1235 noise_ultralight(ret);
1237 return plug_closing(s->plug,
1238 ret == 0 ? "Internal networking trouble" :
1239 strerror(errno), errno, 0);
1242 * Receiving actual data on a socket means we can
1243 * stop falling back through the candidate
1244 * addresses to connect to.
1247 sk_addr_free(s->addr);
1250 return plug_receive(s->plug, 2, buf, ret);
1256 * If we reach here, this is an oobinline socket, which
1257 * means we should set s->oobpending and then deal with it
1258 * when we get called for the readability event (which
1259 * should also occur).
1261 s->oobpending = TRUE;
1263 case 1: /* readable; also acceptance */
1266 * On a listening socket, the readability event means a
1267 * connection is ready to be accepted.
1269 union sockaddr_union su;
1270 socklen_t addrlen = sizeof(su);
1271 int t; /* socket of connection */
1273 memset(&su, 0, addrlen);
1274 t = accept(s->s, &su.sa, &addrlen);
1281 if (s->localhost_only &&
1282 !sockaddr_is_loopback(&su.sa)) {
1283 close(t); /* someone let nonlocal through?! */
1284 } else if (plug_accepting(s->plug, t)) {
1285 close(t); /* denied or error */
1291 * If we reach here, this is not a listening socket, so
1292 * readability really means readability.
1295 /* In the case the socket is still frozen, we don't even bother */
1300 * We have received data on the socket. For an oobinline
1301 * socket, this might be data _before_ an urgent pointer,
1302 * in which case we send it to the back end with type==1
1303 * (data prior to urgent).
1305 if (s->oobinline && s->oobpending) {
1307 if (ioctl(s->s, SIOCATMARK, &atmark) == 0 && atmark)
1308 s->oobpending = FALSE; /* clear this indicator */
1312 ret = recv(s->s, buf, s->oobpending ? 1 : sizeof(buf), 0);
1313 noise_ultralight(ret);
1315 if (errno == EWOULDBLOCK) {
1321 * An error at this point _might_ be an error reported
1322 * by a non-blocking connect(). So before we return a
1323 * panic status to the user, let's just see whether
1328 plug_log(s->plug, 1, s->addr, s->port, strerror(err), err);
1329 while (s->addr && sk_nextaddr(s->addr, &s->step)) {
1330 err = try_connect(s);
1334 return plug_closing(s->plug, strerror(err), err, 0);
1335 } else if (0 == ret) {
1336 s->incomingeof = TRUE; /* stop trying to read now */
1338 return plug_closing(s->plug, NULL, 0, 0);
1341 * Receiving actual data on a socket means we can
1342 * stop falling back through the candidate
1343 * addresses to connect to.
1346 sk_addr_free(s->addr);
1349 return plug_receive(s->plug, atmark ? 0 : 1, buf, ret);
1352 case 2: /* writable */
1353 if (!s->connected) {
1355 * select() reports a socket as _writable_ when an
1356 * asynchronous connection is completed.
1358 s->connected = s->writable = 1;
1362 int bufsize_before, bufsize_after;
1364 bufsize_before = s->sending_oob + bufchain_size(&s->output_data);
1366 bufsize_after = s->sending_oob + bufchain_size(&s->output_data);
1367 if (bufsize_after < bufsize_before)
1368 plug_sent(s->plug, bufsize_after);
1377 * Each socket abstraction contains a `void *' private field in
1378 * which the client can keep state.
1380 static void sk_tcp_set_private_ptr(Socket sock, void *ptr)
1382 Actual_Socket s = (Actual_Socket) sock;
1383 s->private_ptr = ptr;
1386 static void *sk_tcp_get_private_ptr(Socket sock)
1388 Actual_Socket s = (Actual_Socket) sock;
1389 return s->private_ptr;
1393 * Special error values are returned from sk_namelookup and sk_new
1394 * if there's a problem. These functions extract an error message,
1395 * or return NULL if there's no problem.
1397 const char *sk_addr_error(SockAddr addr)
1401 static const char *sk_tcp_socket_error(Socket sock)
1403 Actual_Socket s = (Actual_Socket) sock;
1407 static void sk_tcp_set_frozen(Socket sock, int is_frozen)
1409 Actual_Socket s = (Actual_Socket) sock;
1410 if (s->frozen == is_frozen)
1412 s->frozen = is_frozen;
1416 static void uxsel_tell(Actual_Socket s)
1419 if (!s->pending_error) {
1421 rwx |= 1; /* read == accept */
1424 rwx |= 2; /* write == connect */
1425 if (s->connected && !s->frozen && !s->incomingeof)
1426 rwx |= 1 | 4; /* read, except */
1427 if (bufchain_size(&s->output_data))
1428 rwx |= 2; /* write */
1431 uxsel_set(s->s, rwx, net_select_result);
1434 int net_service_lookup(char *service)
1437 se = getservbyname(service, NULL);
1439 return ntohs(se->s_port);
1444 char *get_hostname(void)
1447 char *hostname = NULL;
1450 hostname = sresize(hostname, len, char);
1451 if ((gethostname(hostname, len) < 0) &&
1452 (errno != ENAMETOOLONG)) {
1457 } while (strlen(hostname) >= len-1);
1461 SockAddr platform_get_x11_unix_address(const char *sockpath, int displaynum)
1463 SockAddr ret = snew(struct SockAddr_tag);
1466 memset(ret, 0, sizeof *ret);
1467 ret->superfamily = UNIX;
1469 * In special circumstances (notably Mac OS X Leopard), we'll
1470 * have been passed an explicit Unix socket path.
1473 n = snprintf(ret->hostname, sizeof ret->hostname,
1476 n = snprintf(ret->hostname, sizeof ret->hostname,
1477 "%s%d", X11_UNIX_PATH, displaynum);
1481 ret->error = "snprintf failed";
1482 else if (n >= sizeof ret->hostname)
1483 ret->error = "X11 UNIX name too long";
1488 ret->addresses = NULL;
1489 ret->naddresses = 0;