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;
49 * We used to typedef struct Socket_tag *Socket.
51 * Since we have made the networking abstraction slightly more
52 * abstract, Socket no longer means a tcp socket (it could mean
53 * an ssl socket). So now we must use Actual_Socket when we know
54 * we are talking about a tcp socket.
56 typedef struct Socket_tag *Actual_Socket;
59 * Mutable state that goes with a SockAddr: stores information
60 * about where in the list of candidate IP(v*) addresses we've
63 typedef struct SockAddrStep_tag SockAddrStep;
64 struct SockAddrStep_tag {
66 struct addrinfo *ai; /* steps along addr->ais */
72 struct socket_function_table *fn;
73 /* 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 frozen_readable; /* this means we missed at least one readability
83 * notification while we were frozen */
84 int localhost_only; /* for listening sockets */
87 int oobpending; /* is there OOB data available to read? */
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 /* XXX not clear what we should return for Unix-domain sockets; let's
319 * hope the question never arises */
320 assert(addr->superfamily != UNIX);
321 if (addr->superfamily == UNRESOLVED) {
322 strncpy(buf, addr->hostname, buflen);
323 buf[buflen-1] = '\0';
326 if (getnameinfo(addr->ais->ai_addr, addr->ais->ai_addrlen, buf, buflen,
327 NULL, 0, NI_NUMERICHOST) != 0) {
329 strncat(buf, "<unknown>", buflen - 1);
334 START_STEP(addr, step);
335 assert(SOCKADDR_FAMILY(addr, step) == AF_INET);
336 a.s_addr = htonl(addr->addresses[0]);
337 strncpy(buf, inet_ntoa(a), buflen);
338 buf[buflen-1] = '\0';
343 int sk_hostname_is_local(char *name)
345 return !strcmp(name, "localhost") ||
346 !strcmp(name, "::1") ||
347 !strncmp(name, "127.", 4);
350 #define ipv4_is_loopback(addr) \
351 (((addr).s_addr & htonl(0xff000000)) == htonl(0x7f000000))
353 static int sockaddr_is_loopback(struct sockaddr *sa)
355 union sockaddr_union *u = (union sockaddr_union *)sa;
356 switch (u->sa.sa_family) {
358 return ipv4_is_loopback(u->sin.sin_addr);
361 return IN6_IS_ADDR_LOOPBACK(&u->sin6.sin6_addr);
370 int sk_address_is_local(SockAddr addr)
372 if (addr->superfamily == UNRESOLVED)
373 return 0; /* we don't know; assume not */
374 else if (addr->superfamily == UNIX)
378 return sockaddr_is_loopback(addr->ais->ai_addr);
382 START_STEP(addr, step);
383 assert(SOCKADDR_FAMILY(addr, step) == AF_INET);
384 a.s_addr = htonl(addr->addresses[0]);
385 return ipv4_is_loopback(a);
390 int sk_addrtype(SockAddr addr)
394 START_STEP(addr, step);
395 family = SOCKADDR_FAMILY(addr, step);
397 return (family == AF_INET ? ADDRTYPE_IPV4 :
399 family == AF_INET6 ? ADDRTYPE_IPV6 :
404 void sk_addrcopy(SockAddr addr, char *buf)
408 START_STEP(addr, step);
409 family = SOCKADDR_FAMILY(addr, step);
412 if (family == AF_INET)
413 memcpy(buf, &((struct sockaddr_in *)step.ai->ai_addr)->sin_addr,
414 sizeof(struct in_addr));
415 else if (family == AF_INET6)
416 memcpy(buf, &((struct sockaddr_in6 *)step.ai->ai_addr)->sin6_addr,
417 sizeof(struct in6_addr));
423 assert(family == AF_INET);
424 a.s_addr = htonl(addr->addresses[step.curraddr]);
425 memcpy(buf, (char*) &a.s_addr, 4);
429 void sk_addr_free(SockAddr addr)
431 if (--addr->refcount > 0)
434 if (addr->ais != NULL)
435 freeaddrinfo(addr->ais);
437 sfree(addr->addresses);
442 SockAddr sk_addr_dup(SockAddr addr)
448 static Plug sk_tcp_plug(Socket sock, Plug p)
450 Actual_Socket s = (Actual_Socket) sock;
457 static void sk_tcp_flush(Socket s)
460 * We send data to the socket as soon as we can anyway,
461 * so we don't need to do anything here. :-)
465 static void sk_tcp_close(Socket s);
466 static int sk_tcp_write(Socket s, const char *data, int len);
467 static int sk_tcp_write_oob(Socket s, const char *data, int len);
468 static void sk_tcp_set_private_ptr(Socket s, void *ptr);
469 static void *sk_tcp_get_private_ptr(Socket s);
470 static void sk_tcp_set_frozen(Socket s, int is_frozen);
471 static const char *sk_tcp_socket_error(Socket s);
473 static struct socket_function_table tcp_fn_table = {
479 sk_tcp_set_private_ptr,
480 sk_tcp_get_private_ptr,
485 Socket sk_register(OSSocket sockfd, Plug plug)
490 * Create Socket structure.
492 ret = snew(struct Socket_tag);
493 ret->fn = &tcp_fn_table;
496 bufchain_init(&ret->output_data);
497 ret->writable = 1; /* to start with */
498 ret->sending_oob = 0;
500 ret->frozen_readable = 0;
501 ret->localhost_only = 0; /* unused, but best init anyway */
502 ret->pending_error = 0;
503 ret->oobpending = FALSE;
505 ret->parent = ret->child = NULL;
512 ret->error = strerror(errno);
524 static int try_connect(Actual_Socket sock)
528 struct sockaddr_in6 a6;
530 struct sockaddr_in a;
531 struct sockaddr_un au;
532 const struct sockaddr *sa;
535 int fl, salen, family;
538 * Remove the socket from the tree before we overwrite its
539 * internal socket id, because that forms part of the tree's
540 * sorting criterion. We'll add it back before exiting this
541 * function, whether we changed anything or not.
543 del234(sktree, sock);
548 plug_log(sock->plug, 0, sock->addr, sock->port, NULL, 0);
553 family = SOCKADDR_FAMILY(sock->addr, sock->step);
554 assert(family != AF_UNSPEC);
555 s = socket(family, SOCK_STREAM, 0);
565 if (sock->oobinline) {
567 setsockopt(s, SOL_SOCKET, SO_OOBINLINE, (void *) &b, sizeof(b));
572 setsockopt(s, IPPROTO_TCP, TCP_NODELAY, (void *) &b, sizeof(b));
575 if (sock->keepalive) {
577 setsockopt(s, SOL_SOCKET, SO_KEEPALIVE, (void *) &b, sizeof(b));
581 * Bind to local address.
584 localport = 1023; /* count from 1023 downwards */
586 localport = 0; /* just use port 0 (ie kernel picks) */
588 /* BSD IP stacks need sockaddr_in zeroed before filling in */
589 memset(&a,'\0',sizeof(struct sockaddr_in));
591 memset(&a6,'\0',sizeof(struct sockaddr_in6));
594 /* We don't try to bind to a local address for UNIX domain sockets. (Why
595 * do we bother doing the bind when localport == 0 anyway?) */
596 if (family != AF_UNIX) {
597 /* Loop round trying to bind */
602 if (family == AF_INET6) {
603 /* XXX use getaddrinfo to get a local address? */
604 a6.sin6_family = AF_INET6;
605 a6.sin6_addr = in6addr_any;
606 a6.sin6_port = htons(localport);
607 retcode = bind(s, (struct sockaddr *) &a6, sizeof(a6));
611 assert(family == AF_INET);
612 a.sin_family = AF_INET;
613 a.sin_addr.s_addr = htonl(INADDR_ANY);
614 a.sin_port = htons(localport);
615 retcode = bind(s, (struct sockaddr *) &a, sizeof(a));
622 if (err != EADDRINUSE) /* failed, for a bad reason */
627 break; /* we're only looping once */
630 break; /* we might have got to the end */
638 * Connect to remote address.
643 /* XXX would be better to have got getaddrinfo() to fill in the port. */
644 ((struct sockaddr_in *)sock->step.ai->ai_addr)->sin_port =
646 sa = (const struct sockaddr *)sock->step.ai->ai_addr;
647 salen = sock->step.ai->ai_addrlen;
650 ((struct sockaddr_in *)sock->step.ai->ai_addr)->sin_port =
652 sa = (const struct sockaddr *)sock->step.ai->ai_addr;
653 salen = sock->step.ai->ai_addrlen;
657 a.sin_family = AF_INET;
658 a.sin_addr.s_addr = htonl(sock->addr->addresses[sock->step.curraddr]);
659 a.sin_port = htons((short) sock->port);
660 sa = (const struct sockaddr *)&a;
665 assert(sock->port == 0); /* to catch confused people */
666 assert(strlen(sock->addr->hostname) < sizeof au.sun_path);
667 memset(&au, 0, sizeof au);
668 au.sun_family = AF_UNIX;
669 strcpy(au.sun_path, sock->addr->hostname);
670 sa = (const struct sockaddr *)&au;
675 assert(0 && "unknown address family");
676 exit(1); /* XXX: GCC doesn't understand assert() on some systems. */
679 fl = fcntl(s, F_GETFL);
681 fcntl(s, F_SETFL, fl | O_NONBLOCK);
683 if ((connect(s, sa, salen)) < 0) {
684 if ( errno != EINPROGRESS ) {
690 * If we _don't_ get EWOULDBLOCK, the connect has completed
691 * and we should set the socket as connected and writable.
702 * No matter what happened, put the socket back in the tree.
704 add234(sktree, sock);
707 plug_log(sock->plug, 1, sock->addr, sock->port, strerror(err), err);
711 Socket sk_new(SockAddr addr, int port, int privport, int oobinline,
712 int nodelay, int keepalive, Plug plug)
718 * Create Socket structure.
720 ret = snew(struct Socket_tag);
721 ret->fn = &tcp_fn_table;
724 bufchain_init(&ret->output_data);
725 ret->connected = 0; /* to start with */
726 ret->writable = 0; /* to start with */
727 ret->sending_oob = 0;
729 ret->frozen_readable = 0;
730 ret->localhost_only = 0; /* unused, but best init anyway */
731 ret->pending_error = 0;
732 ret->parent = ret->child = NULL;
733 ret->oobpending = FALSE;
736 START_STEP(ret->addr, ret->step);
738 ret->oobinline = oobinline;
739 ret->nodelay = nodelay;
740 ret->keepalive = keepalive;
741 ret->privport = privport;
746 err = try_connect(ret);
747 } while (err && sk_nextaddr(ret->addr, &ret->step));
750 ret->error = strerror(err);
755 Socket sk_newlistener(char *srcaddr, int port, Plug plug, int local_host_only, int orig_address_family)
759 struct addrinfo hints, *ai;
761 struct sockaddr_in6 a6;
763 struct sockaddr *addr;
765 struct sockaddr_in a;
772 * Create Socket structure.
774 ret = snew(struct Socket_tag);
775 ret->fn = &tcp_fn_table;
778 bufchain_init(&ret->output_data);
779 ret->writable = 0; /* to start with */
780 ret->sending_oob = 0;
782 ret->frozen_readable = 0;
783 ret->localhost_only = local_host_only;
784 ret->pending_error = 0;
785 ret->parent = ret->child = NULL;
786 ret->oobpending = FALSE;
791 * Translate address_family from platform-independent constants
792 * into local reality.
794 address_family = (orig_address_family == ADDRTYPE_IPV4 ? AF_INET :
796 orig_address_family == ADDRTYPE_IPV6 ? AF_INET6 :
801 /* Let's default to IPv6.
802 * If the stack doesn't support IPv6, we will fall back to IPv4. */
803 if (address_family == AF_UNSPEC) address_family = AF_INET6;
805 /* No other choice, default to IPv4 */
806 if (address_family == AF_UNSPEC) address_family = AF_INET;
812 s = socket(address_family, SOCK_STREAM, 0);
815 /* If the host doesn't support IPv6 try fallback to IPv4. */
816 if (s < 0 && address_family == AF_INET6) {
817 address_family = AF_INET;
818 s = socket(address_family, SOCK_STREAM, 0);
823 ret->error = strerror(errno);
831 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (const char *)&on, sizeof(on));
834 addr = NULL; addrlen = -1; /* placate optimiser */
836 if (srcaddr != NULL) {
838 hints.ai_flags = AI_NUMERICHOST;
839 hints.ai_family = address_family;
840 hints.ai_socktype = SOCK_STREAM;
841 hints.ai_protocol = 0;
842 hints.ai_addrlen = 0;
843 hints.ai_addr = NULL;
844 hints.ai_canonname = NULL;
845 hints.ai_next = NULL;
846 assert(port >= 0 && port <= 99999);
847 sprintf(portstr, "%d", port);
848 retcode = getaddrinfo(srcaddr, portstr, &hints, &ai);
851 addrlen = ai->ai_addrlen;
854 memset(&a,'\0',sizeof(struct sockaddr_in));
855 a.sin_family = AF_INET;
856 a.sin_port = htons(port);
857 a.sin_addr.s_addr = inet_addr(srcaddr);
858 if (a.sin_addr.s_addr != (in_addr_t)(-1)) {
859 /* Override localhost_only with specified listen addr. */
860 ret->localhost_only = ipv4_is_loopback(a.sin_addr);
862 addr = (struct sockaddr *)&a;
870 if (address_family == AF_INET6) {
871 memset(&a6,'\0',sizeof(struct sockaddr_in6));
872 a6.sin6_family = AF_INET6;
873 a6.sin6_port = htons(port);
875 a6.sin6_addr = in6addr_loopback;
877 a6.sin6_addr = in6addr_any;
878 addr = (struct sockaddr *)&a6;
879 addrlen = sizeof(a6);
883 memset(&a,'\0',sizeof(struct sockaddr_in));
884 a.sin_family = AF_INET;
885 a.sin_port = htons(port);
887 a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
889 a.sin_addr.s_addr = htonl(INADDR_ANY);
890 addr = (struct sockaddr *)&a;
895 retcode = bind(s, addr, addrlen);
898 ret->error = strerror(errno);
902 if (listen(s, SOMAXCONN) < 0) {
904 ret->error = strerror(errno);
910 * If we were given ADDRTYPE_UNSPEC, we must also create an
911 * IPv4 listening socket and link it to this one.
913 if (address_family == AF_INET6 && orig_address_family == ADDRTYPE_UNSPEC) {
916 other = (Actual_Socket) sk_newlistener(srcaddr, port, plug,
917 local_host_only, ADDRTYPE_IPV4);
924 /* If we couldn't create a listening socket on IPv4 as well
925 * as IPv6, we must return an error overall. */
928 return (Socket) other;
942 static void sk_tcp_close(Socket sock)
944 Actual_Socket s = (Actual_Socket) sock;
947 sk_tcp_close((Socket)s->child);
953 sk_addr_free(s->addr);
957 void *sk_getxdmdata(void *sock, int *lenp)
959 Actual_Socket s = (Actual_Socket) sock;
960 union sockaddr_union u;
963 static unsigned int unix_addr = 0xFFFFFFFF;
966 * We must check that this socket really _is_ an Actual_Socket.
968 if (s->fn != &tcp_fn_table)
969 return NULL; /* failure */
972 if (getsockname(s->s, &u.sa, &addrlen) < 0)
974 switch(u.sa.sa_family) {
977 buf = snewn(*lenp, char);
978 PUT_32BIT_MSB_FIRST(buf, ntohl(u.sin.sin_addr.s_addr));
979 PUT_16BIT_MSB_FIRST(buf+4, ntohs(u.sin.sin_port));
984 buf = snewn(*lenp, char);
985 if (IN6_IS_ADDR_V4MAPPED(&u.sin6.sin6_addr)) {
986 memcpy(buf, u.sin6.sin6_addr.s6_addr + 12, 4);
987 PUT_16BIT_MSB_FIRST(buf+4, ntohs(u.sin6.sin6_port));
989 /* This is stupid, but it's what XLib does. */
995 buf = snewn(*lenp, char);
996 PUT_32BIT_MSB_FIRST(buf, unix_addr--);
997 PUT_16BIT_MSB_FIRST(buf+4, getpid());
1010 * The function which tries to send on a socket once it's deemed
1013 void try_send(Actual_Socket s)
1015 while (s->sending_oob || bufchain_size(&s->output_data) > 0) {
1019 int len, urgentflag;
1021 if (s->sending_oob) {
1022 urgentflag = MSG_OOB;
1023 len = s->sending_oob;
1027 bufchain_prefix(&s->output_data, &data, &len);
1029 nsent = send(s->s, data, len, urgentflag);
1030 noise_ultralight(nsent);
1032 err = (nsent < 0 ? errno : 0);
1033 if (err == EWOULDBLOCK) {
1035 * Perfectly normal: we've sent all we can for the moment.
1037 s->writable = FALSE;
1041 * We unfortunately can't just call plug_closing(),
1042 * because it's quite likely that we're currently
1043 * _in_ a call from the code we'd be calling back
1044 * to, so we'd have to make half the SSH code
1045 * reentrant. Instead we flag a pending error on
1046 * the socket, to be dealt with (by calling
1047 * plug_closing()) at some suitable future moment.
1049 s->pending_error = err;
1053 if (s->sending_oob) {
1055 memmove(s->oobdata, s->oobdata+nsent, len-nsent);
1056 s->sending_oob = len - nsent;
1061 bufchain_consume(&s->output_data, nsent);
1068 static int sk_tcp_write(Socket sock, const char *buf, int len)
1070 Actual_Socket s = (Actual_Socket) sock;
1073 * Add the data to the buffer list on the socket.
1075 bufchain_add(&s->output_data, buf, len);
1078 * Now try sending from the start of the buffer list.
1084 * Update the select() status to correctly reflect whether or
1085 * not we should be selecting for write.
1089 return bufchain_size(&s->output_data);
1092 static int sk_tcp_write_oob(Socket sock, const char *buf, int len)
1094 Actual_Socket s = (Actual_Socket) sock;
1097 * Replace the buffer list on the socket with the data.
1099 bufchain_clear(&s->output_data);
1100 assert(len <= sizeof(s->oobdata));
1101 memcpy(s->oobdata, buf, len);
1102 s->sending_oob = len;
1105 * Now try sending from the start of the buffer list.
1111 * Update the select() status to correctly reflect whether or
1112 * not we should be selecting for write.
1116 return s->sending_oob;
1119 static int net_select_result(int fd, int event)
1122 char buf[20480]; /* nice big buffer for plenty of speed */
1126 /* Find the Socket structure */
1127 s = find234(sktree, &fd, cmpforsearch);
1129 return 1; /* boggle */
1131 noise_ultralight(event);
1134 case 4: /* exceptional */
1135 if (!s->oobinline) {
1137 * On a non-oobinline socket, this indicates that we
1138 * can immediately perform an OOB read and get back OOB
1139 * data, which we will send to the back end with
1140 * type==2 (urgent data).
1142 ret = recv(s->s, buf, sizeof(buf), MSG_OOB);
1143 noise_ultralight(ret);
1145 return plug_closing(s->plug,
1146 ret == 0 ? "Internal networking trouble" :
1147 strerror(errno), errno, 0);
1150 * Receiving actual data on a socket means we can
1151 * stop falling back through the candidate
1152 * addresses to connect to.
1155 sk_addr_free(s->addr);
1158 return plug_receive(s->plug, 2, buf, ret);
1164 * If we reach here, this is an oobinline socket, which
1165 * means we should set s->oobpending and then deal with it
1166 * when we get called for the readability event (which
1167 * should also occur).
1169 s->oobpending = TRUE;
1171 case 1: /* readable; also acceptance */
1174 * On a listening socket, the readability event means a
1175 * connection is ready to be accepted.
1178 struct sockaddr_in ss;
1180 struct sockaddr_storage ss;
1182 socklen_t addrlen = sizeof(ss);
1183 int t; /* socket of connection */
1186 memset(&ss, 0, addrlen);
1187 t = accept(s->s, (struct sockaddr *)&ss, &addrlen);
1192 fl = fcntl(t, F_GETFL);
1194 fcntl(t, F_SETFL, fl | O_NONBLOCK);
1196 if (s->localhost_only &&
1197 !sockaddr_is_loopback((struct sockaddr *)&ss)) {
1198 close(t); /* someone let nonlocal through?! */
1199 } else if (plug_accepting(s->plug, t)) {
1200 close(t); /* denied or error */
1206 * If we reach here, this is not a listening socket, so
1207 * readability really means readability.
1210 /* In the case the socket is still frozen, we don't even bother */
1212 s->frozen_readable = 1;
1217 * We have received data on the socket. For an oobinline
1218 * socket, this might be data _before_ an urgent pointer,
1219 * in which case we send it to the back end with type==1
1220 * (data prior to urgent).
1222 if (s->oobinline && s->oobpending) {
1224 if (ioctl(s->s, SIOCATMARK, &atmark) == 0 && atmark)
1225 s->oobpending = FALSE; /* clear this indicator */
1229 ret = recv(s->s, buf, s->oobpending ? 1 : sizeof(buf), 0);
1230 noise_ultralight(ret);
1232 if (errno == EWOULDBLOCK) {
1238 * An error at this point _might_ be an error reported
1239 * by a non-blocking connect(). So before we return a
1240 * panic status to the user, let's just see whether
1245 plug_log(s->plug, 1, s->addr, s->port, strerror(err), err);
1246 while (s->addr && sk_nextaddr(s->addr, &s->step)) {
1247 err = try_connect(s);
1251 return plug_closing(s->plug, strerror(err), err, 0);
1252 } else if (0 == ret) {
1253 return plug_closing(s->plug, NULL, 0, 0);
1256 * Receiving actual data on a socket means we can
1257 * stop falling back through the candidate
1258 * addresses to connect to.
1261 sk_addr_free(s->addr);
1264 return plug_receive(s->plug, atmark ? 0 : 1, buf, ret);
1267 case 2: /* writable */
1268 if (!s->connected) {
1270 * select() reports a socket as _writable_ when an
1271 * asynchronous connection is completed.
1273 s->connected = s->writable = 1;
1277 int bufsize_before, bufsize_after;
1279 bufsize_before = s->sending_oob + bufchain_size(&s->output_data);
1281 bufsize_after = s->sending_oob + bufchain_size(&s->output_data);
1282 if (bufsize_after < bufsize_before)
1283 plug_sent(s->plug, bufsize_after);
1292 * Deal with socket errors detected in try_send().
1294 void net_pending_errors(void)
1300 * This might be a fiddly business, because it's just possible
1301 * that handling a pending error on one socket might cause
1302 * others to be closed. (I can't think of any reason this might
1303 * happen in current SSH implementation, but to maintain
1304 * generality of this network layer I'll assume the worst.)
1306 * So what we'll do is search the socket list for _one_ socket
1307 * with a pending error, and then handle it, and then search
1308 * the list again _from the beginning_. Repeat until we make a
1309 * pass with no socket errors present. That way we are
1310 * protected against the socket list changing under our feet.
1314 for (i = 0; (s = index234(sktree, i)) != NULL; i++) {
1315 if (s->pending_error) {
1317 * An error has occurred on this socket. Pass it to the
1320 plug_closing(s->plug, strerror(s->pending_error),
1321 s->pending_error, 0);
1329 * Each socket abstraction contains a `void *' private field in
1330 * which the client can keep state.
1332 static void sk_tcp_set_private_ptr(Socket sock, void *ptr)
1334 Actual_Socket s = (Actual_Socket) sock;
1335 s->private_ptr = ptr;
1338 static void *sk_tcp_get_private_ptr(Socket sock)
1340 Actual_Socket s = (Actual_Socket) sock;
1341 return s->private_ptr;
1345 * Special error values are returned from sk_namelookup and sk_new
1346 * if there's a problem. These functions extract an error message,
1347 * or return NULL if there's no problem.
1349 const char *sk_addr_error(SockAddr addr)
1353 static const char *sk_tcp_socket_error(Socket sock)
1355 Actual_Socket s = (Actual_Socket) sock;
1359 static void sk_tcp_set_frozen(Socket sock, int is_frozen)
1361 Actual_Socket s = (Actual_Socket) sock;
1362 if (s->frozen == is_frozen)
1364 s->frozen = is_frozen;
1365 if (!is_frozen && s->frozen_readable) {
1367 recv(s->s, &c, 1, MSG_PEEK);
1369 s->frozen_readable = 0;
1373 static void uxsel_tell(Actual_Socket s)
1377 rwx |= 1; /* read == accept */
1380 rwx |= 2; /* write == connect */
1381 if (s->connected && !s->frozen)
1382 rwx |= 1 | 4; /* read, except */
1383 if (bufchain_size(&s->output_data))
1384 rwx |= 2; /* write */
1386 uxsel_set(s->s, rwx, net_select_result);
1389 int net_service_lookup(char *service)
1392 se = getservbyname(service, NULL);
1394 return ntohs(se->s_port);
1399 char *get_hostname(void)
1402 char *hostname = NULL;
1405 hostname = sresize(hostname, len, char);
1406 if ((gethostname(hostname, len) < 0) &&
1407 (errno != ENAMETOOLONG)) {
1412 } while (strlen(hostname) >= len-1);
1416 SockAddr platform_get_x11_unix_address(const char *sockpath, int displaynum)
1418 SockAddr ret = snew(struct SockAddr_tag);
1421 memset(ret, 0, sizeof *ret);
1422 ret->superfamily = UNIX;
1424 * In special circumstances (notably Mac OS X Leopard), we'll
1425 * have been passed an explicit Unix socket path.
1428 n = snprintf(ret->hostname, sizeof ret->hostname,
1431 n = snprintf(ret->hostname, sizeof ret->hostname,
1432 "%s%d", X11_UNIX_PATH, displaynum);
1436 ret->error = "snprintf failed";
1437 else if (n >= sizeof ret->hostname)
1438 ret->error = "X11 UNIX name too long";
1443 ret->addresses = NULL;
1444 ret->naddresses = 0;