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>
19 #define DEFINE_PLUG_METHOD_MACROS
24 #define ipv4_is_loopback(addr) (inet_netof(addr) == IN_LOOPBACKNET)
27 struct socket_function_table *fn;
28 /* the above variable absolutely *must* be the first in this structure */
36 int frozen; /* this causes readability notifications to be ignored */
37 int frozen_readable; /* this means we missed at least one readability
38 * notification while we were frozen */
39 int localhost_only; /* for listening sockets */
42 int oobpending; /* is there OOB data available to read? */
44 int pending_error; /* in case send() returns error */
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;
61 * Which address family this address belongs to. AF_INET for
62 * IPv4; AF_INET6 for IPv6; AF_UNSPEC indicates that name
63 * resolution has not been done and a simple host name is held
64 * in this SockAddr structure.
68 struct addrinfo *ai; /* Address IPv6 style. */
70 unsigned long address; /* Address IPv4 style. */
72 char hostname[512]; /* Store an unresolved host name. */
75 static tree234 *sktree;
77 static void uxsel_tell(Actual_Socket s);
79 static int cmpfortree(void *av, void *bv)
81 Actual_Socket a = (Actual_Socket) av, b = (Actual_Socket) bv;
82 int as = a->s, bs = b->s;
90 static int cmpforsearch(void *av, void *bv)
92 Actual_Socket b = (Actual_Socket) bv;
93 int as = *(int *)av, bs = b->s;
103 sktree = newtree234(cmpfortree);
106 void sk_cleanup(void)
112 for (i = 0; (s = index234(sktree, i)) != NULL; i++) {
118 const char *error_string(int error)
120 return strerror(error);
123 SockAddr sk_namelookup(const char *host, char **canonicalname)
125 SockAddr ret = snew(struct SockAddr_tag);
127 struct addrinfo hints;
131 struct hostent *h = NULL;
135 /* Clear the structure and default to IPv4. */
136 memset(ret, 0, sizeof(struct SockAddr_tag));
137 ret->family = 0; /* We set this one when we have resolved the host. */
142 hints.ai_flags = AI_CANONNAME;
143 hints.ai_family = AF_UNSPEC;
144 hints.ai_socktype = 0;
145 hints.ai_protocol = 0;
146 hints.ai_addrlen = 0;
147 hints.ai_addr = NULL;
148 hints.ai_canonname = NULL;
149 hints.ai_next = NULL;
150 err = getaddrinfo(host, NULL, NULL, &ret->ai);
152 ret->error = gai_strerror(err);
155 ret->family = ret->ai->ai_family;
157 if (ret->ai->ai_canonname != NULL)
158 strncat(realhost, ret->ai->ai_canonname, sizeof(realhost) - 1);
160 strncat(realhost, host, sizeof(realhost) - 1);
162 if ((a = inet_addr(host)) == (unsigned long) INADDR_NONE) {
164 * Otherwise use the IPv4-only gethostbyname... (NOTE:
165 * we don't use gethostbyname as a fallback!)
167 if (ret->family == 0) {
168 /*debug(("Resolving \"%s\" with gethostbyname() (IPv4 only)...\n", host)); */
169 if ( (h = gethostbyname(host)) )
170 ret->family = AF_INET;
172 if (ret->family == 0) {
173 ret->error = (h_errno == HOST_NOT_FOUND ||
174 h_errno == NO_DATA ||
175 h_errno == NO_ADDRESS ? "Host does not exist" :
176 h_errno == TRY_AGAIN ?
177 "Temporary name service failure" :
178 "gethostbyname: unknown error");
181 memcpy(&a, h->h_addr, sizeof(a));
182 /* This way we are always sure the h->h_name is valid :) */
183 strncpy(realhost, h->h_name, sizeof(realhost));
186 * This must be a numeric IPv4 address because it caused a
187 * success return from inet_addr.
189 ret->family = AF_INET;
190 strncpy(realhost, host, sizeof(realhost));
192 ret->address = ntohl(a);
194 realhost[lenof(realhost)-1] = '\0';
195 *canonicalname = snewn(1+strlen(realhost), char);
196 strcpy(*canonicalname, realhost);
200 SockAddr sk_nonamelookup(const char *host)
202 SockAddr ret = snew(struct SockAddr_tag);
204 ret->family = AF_UNSPEC;
205 strncpy(ret->hostname, host, lenof(ret->hostname));
206 ret->hostname[lenof(ret->hostname)-1] = '\0';
210 void sk_getaddr(SockAddr addr, char *buf, int buflen)
213 if (addr->family == AF_UNSPEC) {
214 strncpy(buf, addr->hostname, buflen);
215 buf[buflen-1] = '\0';
218 if (getnameinfo(addr->ai->ai_addr, addr->ai->ai_addrlen, buf, buflen,
219 NULL, 0, NI_NUMERICHOST) != 0) {
221 strncat(buf, "<unknown>", buflen - 1);
225 assert(addr->family == AF_INET);
226 a.s_addr = htonl(addr->address);
227 strncpy(buf, inet_ntoa(a), buflen);
228 buf[buflen-1] = '\0';
233 int sk_hostname_is_local(char *name)
235 return !strcmp(name, "localhost");
238 int sk_address_is_local(SockAddr addr)
241 if (addr->family == AF_UNSPEC)
242 return 0; /* we don't know; assume not */
245 if (addr->family == AF_INET)
246 return ipv4_is_loopback(
247 ((struct sockaddr_in *)addr->ai->ai_addr)->sin_addr);
248 else if (addr->family == AF_INET6)
249 return IN6_IS_ADDR_LOOPBACK(
250 &((struct sockaddr_in6 *)addr->ai->ai_addr)->sin6_addr);
255 assert(addr->family == AF_INET);
256 a.s_addr = htonl(addr->address);
257 return ipv4_is_loopback(a);
262 int sk_addrtype(SockAddr addr)
264 return (addr->family == AF_INET ? ADDRTYPE_IPV4 :
266 addr->family == AF_INET6 ? ADDRTYPE_IPV6 :
271 void sk_addrcopy(SockAddr addr, char *buf)
275 if (addr->family == AF_INET)
276 memcpy(buf, &((struct sockaddr_in *)addr->ai->ai_addr)->sin_addr,
277 sizeof(struct in_addr));
278 else if (addr->family == AF_INET6)
279 memcpy(buf, &((struct sockaddr_in6 *)addr->ai->ai_addr)->sin6_addr,
280 sizeof(struct in6_addr));
286 assert(addr->family == AF_INET);
287 a.s_addr = htonl(addr->address);
288 memcpy(buf, (char*) &a.s_addr, 4);
292 void sk_addr_free(SockAddr addr)
296 if (addr->ai != NULL)
297 freeaddrinfo(addr->ai);
302 static Plug sk_tcp_plug(Socket sock, Plug p)
304 Actual_Socket s = (Actual_Socket) sock;
311 static void sk_tcp_flush(Socket s)
314 * We send data to the socket as soon as we can anyway,
315 * so we don't need to do anything here. :-)
319 static void sk_tcp_close(Socket s);
320 static int sk_tcp_write(Socket s, const char *data, int len);
321 static int sk_tcp_write_oob(Socket s, const char *data, int len);
322 static void sk_tcp_set_private_ptr(Socket s, void *ptr);
323 static void *sk_tcp_get_private_ptr(Socket s);
324 static void sk_tcp_set_frozen(Socket s, int is_frozen);
325 static const char *sk_tcp_socket_error(Socket s);
327 static struct socket_function_table tcp_fn_table = {
333 sk_tcp_set_private_ptr,
334 sk_tcp_get_private_ptr,
339 Socket sk_register(OSSocket sockfd, Plug plug)
344 * Create Socket structure.
346 ret = snew(struct Socket_tag);
347 ret->fn = &tcp_fn_table;
350 bufchain_init(&ret->output_data);
351 ret->writable = 1; /* to start with */
352 ret->sending_oob = 0;
354 ret->frozen_readable = 0;
355 ret->localhost_only = 0; /* unused, but best init anyway */
356 ret->pending_error = 0;
357 ret->oobpending = FALSE;
363 ret->error = error_string(errno);
375 Socket sk_new(SockAddr addr, int port, int privport, int oobinline,
376 int nodelay, Plug plug)
380 struct sockaddr_in6 a6;
382 struct sockaddr_in a;
389 * Create Socket structure.
391 ret = snew(struct Socket_tag);
392 ret->fn = &tcp_fn_table;
395 bufchain_init(&ret->output_data);
396 ret->connected = 0; /* to start with */
397 ret->writable = 0; /* to start with */
398 ret->sending_oob = 0;
400 ret->frozen_readable = 0;
401 ret->localhost_only = 0; /* unused, but best init anyway */
402 ret->pending_error = 0;
403 ret->oobpending = FALSE;
409 assert(addr->family != AF_UNSPEC);
410 s = socket(addr->family, SOCK_STREAM, 0);
414 ret->error = error_string(errno);
418 ret->oobinline = oobinline;
421 setsockopt(s, SOL_SOCKET, SO_OOBINLINE, (void *) &b, sizeof(b));
426 setsockopt(s, IPPROTO_TCP, TCP_NODELAY, (void *) &b, sizeof(b));
430 * Bind to local address.
433 localport = 1023; /* count from 1023 downwards */
435 localport = 0; /* just use port 0 (ie kernel picks) */
437 /* Loop round trying to bind */
442 if (addr->family == AF_INET6) {
443 /* XXX use getaddrinfo to get a local address? */
444 a6.sin6_family = AF_INET6;
445 a6.sin6_addr = in6addr_any;
446 a6.sin6_port = htons(localport);
447 retcode = bind(s, (struct sockaddr *) &a6, sizeof(a6));
451 assert(addr->family == AF_INET);
452 a.sin_family = AF_INET;
453 a.sin_addr.s_addr = htonl(INADDR_ANY);
454 a.sin_port = htons(localport);
455 retcode = bind(s, (struct sockaddr *) &a, sizeof(a));
462 if (err != EADDRINUSE) /* failed, for a bad reason */
467 break; /* we're only looping once */
470 break; /* we might have got to the end */
474 ret->error = error_string(err);
479 * Connect to remote address.
482 /* XXX would be better to have got getaddrinfo() to fill in the port. */
483 if (addr->family == AF_INET)
484 ((struct sockaddr_in *)addr->ai->ai_addr)->sin_port =
487 assert(addr->family == AF_INET6);
488 ((struct sockaddr_in *)addr->ai->ai_addr)->sin_port =
492 a.sin_family = AF_INET;
493 a.sin_addr.s_addr = htonl(addr->address);
494 a.sin_port = htons((short) port);
497 fl = fcntl(s, F_GETFL);
499 fcntl(s, F_SETFL, fl | O_NONBLOCK);
503 connect(s, addr->ai->ai_addr, addr->ai->ai_addrlen)
505 connect(s, (struct sockaddr *) &a, sizeof(a))
508 if ( errno != EINPROGRESS ) {
509 ret->error = error_string(errno);
514 * If we _don't_ get EWOULDBLOCK, the connect has completed
515 * and we should set the socket as connected and writable.
529 Socket sk_newlistener(char *srcaddr, int port, Plug plug, int local_host_only)
534 struct sockaddr_in6 a6;
536 struct addrinfo hints, *ai;
539 struct sockaddr_in a;
546 * Create Socket structure.
548 ret = snew(struct Socket_tag);
549 ret->fn = &tcp_fn_table;
552 bufchain_init(&ret->output_data);
553 ret->writable = 0; /* to start with */
554 ret->sending_oob = 0;
556 ret->frozen_readable = 0;
557 ret->localhost_only = local_host_only;
558 ret->pending_error = 0;
559 ret->oobpending = FALSE;
565 s = socket(AF_INET, SOCK_STREAM, 0);
569 ret->error = error_string(errno);
575 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (const char *)&on, sizeof(on));
578 hints.ai_flags = AI_NUMERICHOST;
579 hints.ai_family = AF_UNSPEC;
580 hints.ai_socktype = 0;
581 hints.ai_protocol = 0;
582 hints.ai_addrlen = 0;
583 hints.ai_addr = NULL;
584 hints.ai_canonname = NULL;
585 hints.ai_next = NULL;
586 sprintf(portstr, "%d", port);
587 if (srcaddr != NULL && getaddrinfo(srcaddr, portstr, &hints, &ai) == 0)
588 retcode = bind(s, ai->ai_addr, ai->ai_addrlen);
593 * FIXME: Need two listening sockets, in principle, one for v4
597 a6.sin6_addr = in6addr_loopback;
599 a6.sin6_addr = in6addr_any;
600 a6.sin6_port = htons(port);
606 a.sin_family = AF_INET;
609 * Bind to source address. First try an explicitly
613 a.sin_addr.s_addr = inet_addr(srcaddr);
614 if (a.sin_addr.s_addr != INADDR_NONE) {
615 /* Override localhost_only with specified listen addr. */
616 ret->localhost_only = ipv4_is_loopback(a.sin_addr);
622 * ... and failing that, go with one of the standard ones.
626 a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
628 a.sin_addr.s_addr = htonl(INADDR_ANY);
631 a.sin_port = htons((short)port);
632 retcode = bind(s, (struct sockaddr *) &a, sizeof(a));
642 ret->error = error_string(err);
647 if (listen(s, SOMAXCONN) < 0) {
649 ret->error = error_string(errno);
659 static void sk_tcp_close(Socket sock)
661 Actual_Socket s = (Actual_Socket) sock;
669 int sk_getxdmdata(void *sock, unsigned long *ip, int *port)
671 Actual_Socket s = (Actual_Socket) sock;
672 struct sockaddr_in addr;
676 * We must check that this socket really _is_ an Actual_Socket.
678 if (s->fn != &tcp_fn_table)
679 return 0; /* failure */
682 * If we ever implement connecting to a local X server through
683 * a Unix socket, we return 0xFFFFFFFF for the IP address and
684 * our current pid for the port. Bizarre, but such is life.
687 addrlen = sizeof(addr);
688 if (getsockname(s->s, (struct sockaddr *)&addr, &addrlen) < 0 ||
689 addr.sin_family != AF_INET)
692 *ip = ntohl(addr.sin_addr.s_addr);
693 *port = ntohs(addr.sin_port);
699 * The function which tries to send on a socket once it's deemed
702 void try_send(Actual_Socket s)
704 while (s->sending_oob || bufchain_size(&s->output_data) > 0) {
710 if (s->sending_oob) {
711 urgentflag = MSG_OOB;
712 len = s->sending_oob;
716 bufchain_prefix(&s->output_data, &data, &len);
718 nsent = send(s->s, data, len, urgentflag);
719 noise_ultralight(nsent);
721 err = (nsent < 0 ? errno : 0);
722 if (err == EWOULDBLOCK) {
724 * Perfectly normal: we've sent all we can for the moment.
728 } else if (nsent == 0 ||
729 err == ECONNABORTED || err == ECONNRESET) {
731 * If send() returns CONNABORTED or CONNRESET, we
732 * unfortunately can't just call plug_closing(),
733 * because it's quite likely that we're currently
734 * _in_ a call from the code we'd be calling back
735 * to, so we'd have to make half the SSH code
736 * reentrant. Instead we flag a pending error on
737 * the socket, to be dealt with (by calling
738 * plug_closing()) at some suitable future moment.
740 s->pending_error = err;
743 /* We're inside the Unix frontend here, so we know
744 * that the frontend handle is unnecessary. */
745 logevent(NULL, error_string(err));
746 fatalbox("%s", error_string(err));
749 if (s->sending_oob) {
751 memmove(s->oobdata, s->oobdata+nsent, len-nsent);
752 s->sending_oob = len - nsent;
757 bufchain_consume(&s->output_data, nsent);
764 static int sk_tcp_write(Socket sock, const char *buf, int len)
766 Actual_Socket s = (Actual_Socket) sock;
769 * Add the data to the buffer list on the socket.
771 bufchain_add(&s->output_data, buf, len);
774 * Now try sending from the start of the buffer list.
780 * Update the select() status to correctly reflect whether or
781 * not we should be selecting for write.
785 return bufchain_size(&s->output_data);
788 static int sk_tcp_write_oob(Socket sock, const char *buf, int len)
790 Actual_Socket s = (Actual_Socket) sock;
793 * Replace the buffer list on the socket with the data.
795 bufchain_clear(&s->output_data);
796 assert(len <= sizeof(s->oobdata));
797 memcpy(s->oobdata, buf, len);
798 s->sending_oob = len;
801 * Now try sending from the start of the buffer list.
807 * Update the select() status to correctly reflect whether or
808 * not we should be selecting for write.
812 return s->sending_oob;
815 static int net_select_result(int fd, int event)
819 char buf[20480]; /* nice big buffer for plenty of speed */
823 /* Find the Socket structure */
824 s = find234(sktree, &fd, cmpforsearch);
826 return 1; /* boggle */
828 noise_ultralight(event);
831 case 4: /* exceptional */
834 * On a non-oobinline socket, this indicates that we
835 * can immediately perform an OOB read and get back OOB
836 * data, which we will send to the back end with
837 * type==2 (urgent data).
839 ret = recv(s->s, buf, sizeof(buf), MSG_OOB);
840 noise_ultralight(ret);
842 const char *str = (ret == 0 ? "Internal networking trouble" :
843 error_string(errno));
844 /* We're inside the Unix frontend here, so we know
845 * that the frontend handle is unnecessary. */
849 return plug_receive(s->plug, 2, buf, ret);
855 * If we reach here, this is an oobinline socket, which
856 * means we should set s->oobpending and then deal with it
857 * when we get called for the readability event (which
858 * should also occur).
860 s->oobpending = TRUE;
862 case 1: /* readable; also acceptance */
865 * On a listening socket, the readability event means a
866 * connection is ready to be accepted.
868 struct sockaddr_in isa;
869 int addrlen = sizeof(struct sockaddr_in);
870 int t; /* socket of connection */
872 memset(&isa, 0, sizeof(struct sockaddr_in));
874 t = accept(s->s,(struct sockaddr *)&isa,(socklen_t *) &addrlen);
879 if (s->localhost_only && !ipv4_is_loopback(isa.sin_addr)) {
880 close(t); /* someone let nonlocal through?! */
881 } else if (plug_accepting(s->plug, t)) {
882 close(t); /* denied or error */
888 * If we reach here, this is not a listening socket, so
889 * readability really means readability.
892 /* In the case the socket is still frozen, we don't even bother */
894 s->frozen_readable = 1;
899 * We have received data on the socket. For an oobinline
900 * socket, this might be data _before_ an urgent pointer,
901 * in which case we send it to the back end with type==1
902 * (data prior to urgent).
904 if (s->oobinline && s->oobpending) {
906 if (ioctl(s->s, SIOCATMARK, &atmark) == 0 && atmark)
907 s->oobpending = FALSE; /* clear this indicator */
911 ret = recv(s->s, buf, s->oobpending ? 1 : sizeof(buf), 0);
912 noise_ultralight(ret);
914 if (errno == EWOULDBLOCK) {
919 return plug_closing(s->plug, error_string(errno), errno, 0);
920 } else if (0 == ret) {
921 return plug_closing(s->plug, NULL, 0, 0);
923 return plug_receive(s->plug, atmark ? 0 : 1, buf, ret);
926 case 2: /* writable */
929 * select() reports a socket as _writable_ when an
930 * asynchronous connection is completed.
932 s->connected = s->writable = 1;
936 int bufsize_before, bufsize_after;
938 bufsize_before = s->sending_oob + bufchain_size(&s->output_data);
940 bufsize_after = s->sending_oob + bufchain_size(&s->output_data);
941 if (bufsize_after < bufsize_before)
942 plug_sent(s->plug, bufsize_after);
951 * Deal with socket errors detected in try_send().
953 void net_pending_errors(void)
959 * This might be a fiddly business, because it's just possible
960 * that handling a pending error on one socket might cause
961 * others to be closed. (I can't think of any reason this might
962 * happen in current SSH implementation, but to maintain
963 * generality of this network layer I'll assume the worst.)
965 * So what we'll do is search the socket list for _one_ socket
966 * with a pending error, and then handle it, and then search
967 * the list again _from the beginning_. Repeat until we make a
968 * pass with no socket errors present. That way we are
969 * protected against the socket list changing under our feet.
973 for (i = 0; (s = index234(sktree, i)) != NULL; i++) {
974 if (s->pending_error) {
976 * An error has occurred on this socket. Pass it to the
979 plug_closing(s->plug, error_string(s->pending_error),
980 s->pending_error, 0);
988 * Each socket abstraction contains a `void *' private field in
989 * which the client can keep state.
991 static void sk_tcp_set_private_ptr(Socket sock, void *ptr)
993 Actual_Socket s = (Actual_Socket) sock;
994 s->private_ptr = ptr;
997 static void *sk_tcp_get_private_ptr(Socket sock)
999 Actual_Socket s = (Actual_Socket) sock;
1000 return s->private_ptr;
1004 * Special error values are returned from sk_namelookup and sk_new
1005 * if there's a problem. These functions extract an error message,
1006 * or return NULL if there's no problem.
1008 const char *sk_addr_error(SockAddr addr)
1012 static const char *sk_tcp_socket_error(Socket sock)
1014 Actual_Socket s = (Actual_Socket) sock;
1018 static void sk_tcp_set_frozen(Socket sock, int is_frozen)
1020 Actual_Socket s = (Actual_Socket) sock;
1021 if (s->frozen == is_frozen)
1023 s->frozen = is_frozen;
1024 if (!is_frozen && s->frozen_readable) {
1026 recv(s->s, &c, 1, MSG_PEEK);
1028 s->frozen_readable = 0;
1032 static void uxsel_tell(Actual_Socket s)
1036 rwx |= 2; /* write == connect */
1037 if (s->connected && !s->frozen)
1038 rwx |= 1 | 4; /* read, except */
1039 if (bufchain_size(&s->output_data))
1040 rwx |= 2; /* write */
1042 rwx |= 1; /* read == accept */
1043 uxsel_set(s->s, rwx, net_select_result);
1046 int net_service_lookup(char *service)
1049 se = getservbyname(service, NULL);
1051 return ntohs(se->s_port);