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
25 struct socket_function_table *fn;
26 /* the above variable absolutely *must* be the first in this structure */
34 int frozen; /* this causes readability notifications to be ignored */
35 int frozen_readable; /* this means we missed at least one readability
36 * notification while we were frozen */
37 int localhost_only; /* for listening sockets */
40 int oobpending; /* is there OOB data available to read? */
42 int pending_error; /* in case send() returns error */
47 * We used to typedef struct Socket_tag *Socket.
49 * Since we have made the networking abstraction slightly more
50 * abstract, Socket no longer means a tcp socket (it could mean
51 * an ssl socket). So now we must use Actual_Socket when we know
52 * we are talking about a tcp socket.
54 typedef struct Socket_tag *Actual_Socket;
58 /* address family this belongs to, AF_INET for IPv4, AF_INET6 for IPv6. */
60 unsigned long address; /* Address IPv4 style. */
62 struct addrinfo *ai; /* Address IPv6 style. */
66 static tree234 *sktree;
68 static int cmpfortree(void *av, void *bv)
70 Actual_Socket a = (Actual_Socket) av, b = (Actual_Socket) bv;
71 int as = a->s, bs = b->s;
79 static int cmpforsearch(void *av, void *bv)
81 Actual_Socket b = (Actual_Socket) bv;
82 int as = (int) av, bs = b->s;
92 sktree = newtree234(cmpfortree);
101 for (i = 0; (s = index234(sktree, i)) != NULL; i++) {
107 char *error_string(int error)
109 return strerror(error);
112 SockAddr sk_namelookup(char *host, char **canonicalname)
114 SockAddr ret = smalloc(sizeof(struct SockAddr_tag));
116 struct hostent *h = NULL;
119 /* Clear the structure and default to IPv4. */
120 memset(ret, 0, sizeof(struct SockAddr_tag));
121 ret->family = 0; /* We set this one when we have resolved the host. */
125 if ((a = inet_addr(host)) == (unsigned long) INADDR_NONE) {
127 if (getaddrinfo(host, NULL, NULL, &ret->ai) == 0) {
128 ret->family = ret->ai->ai_family;
133 * Otherwise use the IPv4-only gethostbyname... (NOTE:
134 * we don't use gethostbyname as a fallback!)
136 if (ret->family == 0) {
137 /*debug(("Resolving \"%s\" with gethostbyname() (IPv4 only)...\n", host)); */
138 if ( (h = gethostbyname(host)) )
139 ret->family = AF_INET;
141 if (ret->family == 0) {
142 ret->error = (h_errno == HOST_NOT_FOUND ||
143 h_errno == NO_DATA ||
144 h_errno == NO_ADDRESS ? "Host does not exist" :
145 h_errno == TRY_AGAIN ?
146 "Temporary name service failure" :
147 "gethostbyname: unknown error");
153 /* If we got an address info use that... */
156 /* Are we in IPv4 fallback mode? */
157 /* We put the IPv4 address into the a variable so we can further-on use the IPv4 code... */
158 if (ret->family == AF_INET)
160 (char *) &((struct sockaddr_in *) ret->ai->
161 ai_addr)->sin_addr, sizeof(a));
163 /* Now let's find that canonicalname... */
164 if (getnameinfo((struct sockaddr *) ret->ai->ai_addr,
166 AF_INET ? sizeof(struct sockaddr_in) :
167 sizeof(struct sockaddr_in6), realhost,
168 sizeof(realhost), NULL, 0, 0) != 0) {
169 strncpy(realhost, host, sizeof(realhost));
172 /* We used the IPv4-only gethostbyname()... */
176 memcpy(&a, h->h_addr, sizeof(a));
177 /* This way we are always sure the h->h_name is valid :) */
178 strncpy(realhost, h->h_name, sizeof(realhost));
182 * This must be a numeric IPv4 address because it caused a
183 * success return from inet_addr.
185 ret->family = AF_INET;
186 strncpy(realhost, host, sizeof(realhost));
188 ret->address = ntohl(a);
189 realhost[lenof(realhost)-1] = '\0';
190 *canonicalname = smalloc(1+strlen(realhost));
191 strcpy(*canonicalname, realhost);
195 void sk_getaddr(SockAddr addr, char *buf, int buflen)
198 if (addr->family == AF_INET) {
201 a.s_addr = htonl(addr->address);
202 strncpy(buf, inet_ntoa(a), buflen);
205 FIXME; /* I don't know how to get a text form of an IPv6 address. */
210 int sk_addrtype(SockAddr addr)
212 return (addr->family == AF_INET ? ADDRTYPE_IPV4 : ADDRTYPE_IPV6);
215 void sk_addrcopy(SockAddr addr, char *buf)
218 if (addr->family == AF_INET) {
221 a.s_addr = htonl(addr->address);
222 memcpy(buf, (char*) &a.s_addr, 4);
225 memcpy(buf, (char*) addr->ai, 16);
230 void sk_addr_free(SockAddr addr)
235 static Plug sk_tcp_plug(Socket sock, Plug p)
237 Actual_Socket s = (Actual_Socket) sock;
244 static void sk_tcp_flush(Socket s)
247 * We send data to the socket as soon as we can anyway,
248 * so we don't need to do anything here. :-)
252 static void sk_tcp_close(Socket s);
253 static int sk_tcp_write(Socket s, char *data, int len);
254 static int sk_tcp_write_oob(Socket s, char *data, int len);
255 static void sk_tcp_set_private_ptr(Socket s, void *ptr);
256 static void *sk_tcp_get_private_ptr(Socket s);
257 static void sk_tcp_set_frozen(Socket s, int is_frozen);
258 static char *sk_tcp_socket_error(Socket s);
260 Socket sk_register(void *sock, Plug plug)
262 static struct socket_function_table fn_table = {
268 sk_tcp_set_private_ptr,
269 sk_tcp_get_private_ptr,
277 * Create Socket structure.
279 ret = smalloc(sizeof(struct Socket_tag));
283 bufchain_init(&ret->output_data);
284 ret->writable = 1; /* to start with */
285 ret->sending_oob = 0;
287 ret->frozen_readable = 0;
288 ret->localhost_only = 0; /* unused, but best init anyway */
289 ret->pending_error = 0;
290 ret->oobpending = FALSE;
296 ret->error = error_string(errno);
307 Socket sk_new(SockAddr addr, int port, int privport, int oobinline,
308 int nodelay, Plug plug)
310 static struct socket_function_table fn_table = {
316 sk_tcp_set_private_ptr,
317 sk_tcp_get_private_ptr,
324 struct sockaddr_in6 a6;
326 struct sockaddr_in a;
332 * Create Socket structure.
334 ret = smalloc(sizeof(struct Socket_tag));
338 bufchain_init(&ret->output_data);
339 ret->connected = 0; /* to start with */
340 ret->writable = 0; /* to start with */
341 ret->sending_oob = 0;
343 ret->frozen_readable = 0;
344 ret->localhost_only = 0; /* unused, but best init anyway */
345 ret->pending_error = 0;
346 ret->oobpending = FALSE;
352 s = socket(addr->family, SOCK_STREAM, 0);
356 ret->error = error_string(errno);
360 ret->oobinline = oobinline;
363 setsockopt(s, SOL_SOCKET, SO_OOBINLINE, (void *) &b, sizeof(b));
368 setsockopt(s, IPPROTO_TCP, TCP_NODELAY, (void *) &b, sizeof(b));
372 * Bind to local address.
375 localport = 1023; /* count from 1023 downwards */
377 localport = 0; /* just use port 0 (ie kernel picks) */
379 /* Loop round trying to bind */
384 if (addr->family == AF_INET6) {
385 memset(&a6, 0, sizeof(a6));
386 a6.sin6_family = AF_INET6;
387 /*a6.sin6_addr = in6addr_any; *//* == 0 */
388 a6.sin6_port = htons(localport);
392 a.sin_family = AF_INET;
393 a.sin_addr.s_addr = htonl(INADDR_ANY);
394 a.sin_port = htons(localport);
397 retcode = bind(s, (addr->family == AF_INET6 ?
398 (struct sockaddr *) &a6 :
399 (struct sockaddr *) &a),
401 AF_INET6 ? sizeof(a6) : sizeof(a)));
403 retcode = bind(s, (struct sockaddr *) &a, sizeof(a));
410 if (err != EADDRINUSE) /* failed, for a bad reason */
415 break; /* we're only looping once */
418 break; /* we might have got to the end */
422 ret->error = error_string(err);
427 * Connect to remote address.
430 if (addr->family == AF_INET6) {
431 memset(&a, 0, sizeof(a));
432 a6.sin6_family = AF_INET6;
433 a6.sin6_port = htons((short) port);
435 ((struct sockaddr_in6 *) addr->ai->ai_addr)->sin6_addr;
439 a.sin_family = AF_INET;
440 a.sin_addr.s_addr = htonl(addr->address);
441 a.sin_port = htons((short) port);
446 connect(s, ((addr->family == AF_INET6) ?
447 (struct sockaddr *) &a6 : (struct sockaddr *) &a),
448 (addr->family == AF_INET6) ? sizeof(a6) : sizeof(a))
450 connect(s, (struct sockaddr *) &a, sizeof(a))
454 * FIXME: We are prepared to receive EWOULDBLOCK here,
455 * because we might want the connection to be made
456 * asynchronously; but how do we actually arrange this in
459 if ( errno != EWOULDBLOCK ) {
460 ret->error = error_string(errno);
465 * If we _don't_ get EWOULDBLOCK, the connect has completed
466 * and we should set the socket as connected and writable.
477 Socket sk_newlistener(int port, Plug plug, int local_host_only)
479 static struct socket_function_table fn_table = {
485 sk_tcp_set_private_ptr,
486 sk_tcp_get_private_ptr,
493 struct sockaddr_in6 a6;
495 struct sockaddr_in a;
502 * Create Socket structure.
504 ret = smalloc(sizeof(struct Socket_tag));
508 bufchain_init(&ret->output_data);
509 ret->writable = 0; /* to start with */
510 ret->sending_oob = 0;
512 ret->frozen_readable = 0;
513 ret->localhost_only = local_host_only;
514 ret->pending_error = 0;
515 ret->oobpending = FALSE;
521 s = socket(AF_INET, SOCK_STREAM, 0);
525 ret->error = error_string(errno);
531 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (const char *)&on, sizeof(on));
534 if (addr->family == AF_INET6) {
535 memset(&a6, 0, sizeof(a6));
536 a6.sin6_family = AF_INET6;
538 a6.sin6_addr = in6addr_loopback;
540 a6.sin6_addr = in6addr_any;
541 a6.sin6_port = htons(port);
545 a.sin_family = AF_INET;
547 a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
549 a.sin_addr.s_addr = htonl(INADDR_ANY);
550 a.sin_port = htons((short)port);
553 retcode = bind(s, (addr->family == AF_INET6 ?
554 (struct sockaddr *) &a6 :
555 (struct sockaddr *) &a),
557 AF_INET6 ? sizeof(a6) : sizeof(a)));
559 retcode = bind(s, (struct sockaddr *) &a, sizeof(a));
568 ret->error = error_string(err);
573 if (listen(s, SOMAXCONN) < 0) {
575 ret->error = error_string(errno);
584 static void sk_tcp_close(Socket sock)
586 Actual_Socket s = (Actual_Socket) sock;
594 * The function which tries to send on a socket once it's deemed
597 void try_send(Actual_Socket s)
599 while (s->sending_oob || bufchain_size(&s->output_data) > 0) {
605 if (s->sending_oob) {
606 urgentflag = MSG_OOB;
607 len = s->sending_oob;
611 bufchain_prefix(&s->output_data, &data, &len);
613 nsent = send(s->s, data, len, urgentflag);
614 noise_ultralight(nsent);
616 err = (nsent < 0 ? errno : 0);
617 if (err == EWOULDBLOCK) {
619 * Perfectly normal: we've sent all we can for the moment.
623 } else if (nsent == 0 ||
624 err == ECONNABORTED || err == ECONNRESET) {
626 * If send() returns CONNABORTED or CONNRESET, we
627 * unfortunately can't just call plug_closing(),
628 * because it's quite likely that we're currently
629 * _in_ a call from the code we'd be calling back
630 * to, so we'd have to make half the SSH code
631 * reentrant. Instead we flag a pending error on
632 * the socket, to be dealt with (by calling
633 * plug_closing()) at some suitable future moment.
635 s->pending_error = err;
638 /* We're inside the Unix frontend here, so we know
639 * that the frontend handle is unnecessary. */
640 logevent(NULL, error_string(err));
641 fatalbox("%s", error_string(err));
644 if (s->sending_oob) {
646 memmove(s->oobdata, s->oobdata+nsent, len-nsent);
647 s->sending_oob = len - nsent;
652 bufchain_consume(&s->output_data, nsent);
658 static int sk_tcp_write(Socket sock, char *buf, int len)
660 Actual_Socket s = (Actual_Socket) sock;
663 * Add the data to the buffer list on the socket.
665 bufchain_add(&s->output_data, buf, len);
668 * Now try sending from the start of the buffer list.
673 return bufchain_size(&s->output_data);
676 static int sk_tcp_write_oob(Socket sock, char *buf, int len)
678 Actual_Socket s = (Actual_Socket) sock;
681 * Replace the buffer list on the socket with the data.
683 bufchain_clear(&s->output_data);
684 assert(len <= sizeof(s->oobdata));
685 memcpy(s->oobdata, buf, len);
686 s->sending_oob = len;
689 * Now try sending from the start of the buffer list.
694 return s->sending_oob;
697 int select_result(int fd, int event)
701 char buf[20480]; /* nice big buffer for plenty of speed */
705 /* Find the Socket structure */
706 s = find234(sktree, (void *) fd, cmpforsearch);
708 return 1; /* boggle */
710 noise_ultralight(event);
713 #ifdef FIXME_NONBLOCKING_CONNECTIONS
714 case FIXME: /* connected */
715 s->connected = s->writable = 1;
718 case 4: /* exceptional */
721 * On a non-oobinline socket, this indicates that we
722 * can immediately perform an OOB read and get back OOB
723 * data, which we will send to the back end with
724 * type==2 (urgent data).
726 ret = recv(s->s, buf, sizeof(buf), MSG_OOB);
727 noise_ultralight(ret);
729 char *str = (ret == 0 ? "Internal networking trouble" :
730 error_string(errno));
731 /* We're inside the Unix frontend here, so we know
732 * that the frontend handle is unnecessary. */
736 return plug_receive(s->plug, 2, buf, ret);
742 * If we reach here, this is an oobinline socket, which
743 * means we should set s->oobpending and then deal with it
744 * when we get called for the readability event (which
745 * should also occur).
747 s->oobpending = TRUE;
749 case 1: /* readable; also acceptance */
752 * On a listening socket, the readability event means a
753 * connection is ready to be accepted.
755 struct sockaddr_in isa;
756 int addrlen = sizeof(struct sockaddr_in);
757 int t; /* socket of connection */
759 memset(&isa, 0, sizeof(struct sockaddr_in));
761 t = accept(s->s,(struct sockaddr *)&isa,&addrlen);
766 if (s->localhost_only &&
767 ntohl(isa.sin_addr.s_addr) != INADDR_LOOPBACK) {
768 close(t); /* someone let nonlocal through?! */
769 } else if (plug_accepting(s->plug, (void*)t)) {
770 close(t); /* denied or error */
776 * If we reach here, this is not a listening socket, so
777 * readability really means readability.
780 /* In the case the socket is still frozen, we don't even bother */
782 s->frozen_readable = 1;
787 * We have received data on the socket. For an oobinline
788 * socket, this might be data _before_ an urgent pointer,
789 * in which case we send it to the back end with type==1
790 * (data prior to urgent).
792 if (s->oobinline && s->oobpending) {
794 if (ioctl(s->s, SIOCATMARK, &atmark) == 0 && atmark)
795 s->oobpending = FALSE; /* clear this indicator */
799 ret = recv(s->s, buf, s->oobpending ? 1 : sizeof(buf), 0);
800 noise_ultralight(ret);
802 if (errno == EWOULDBLOCK) {
807 return plug_closing(s->plug, error_string(errno), errno, 0);
808 } else if (0 == ret) {
809 return plug_closing(s->plug, NULL, 0, 0);
811 return plug_receive(s->plug, atmark ? 0 : 1, buf, ret);
814 case 2: /* writable */
816 int bufsize_before, bufsize_after;
818 bufsize_before = s->sending_oob + bufchain_size(&s->output_data);
820 bufsize_after = s->sending_oob + bufchain_size(&s->output_data);
821 if (bufsize_after < bufsize_before)
822 plug_sent(s->plug, bufsize_after);
831 * Deal with socket errors detected in try_send().
833 void net_pending_errors(void)
839 * This might be a fiddly business, because it's just possible
840 * that handling a pending error on one socket might cause
841 * others to be closed. (I can't think of any reason this might
842 * happen in current SSH implementation, but to maintain
843 * generality of this network layer I'll assume the worst.)
845 * So what we'll do is search the socket list for _one_ socket
846 * with a pending error, and then handle it, and then search
847 * the list again _from the beginning_. Repeat until we make a
848 * pass with no socket errors present. That way we are
849 * protected against the socket list changing under our feet.
853 for (i = 0; (s = index234(sktree, i)) != NULL; i++) {
854 if (s->pending_error) {
856 * An error has occurred on this socket. Pass it to the
859 plug_closing(s->plug, error_string(s->pending_error),
860 s->pending_error, 0);
868 * Each socket abstraction contains a `void *' private field in
869 * which the client can keep state.
871 static void sk_tcp_set_private_ptr(Socket sock, void *ptr)
873 Actual_Socket s = (Actual_Socket) sock;
874 s->private_ptr = ptr;
877 static void *sk_tcp_get_private_ptr(Socket sock)
879 Actual_Socket s = (Actual_Socket) sock;
880 return s->private_ptr;
884 * Special error values are returned from sk_namelookup and sk_new
885 * if there's a problem. These functions extract an error message,
886 * or return NULL if there's no problem.
888 char *sk_addr_error(SockAddr addr)
892 static char *sk_tcp_socket_error(Socket sock)
894 Actual_Socket s = (Actual_Socket) sock;
898 static void sk_tcp_set_frozen(Socket sock, int is_frozen)
900 Actual_Socket s = (Actual_Socket) sock;
901 if (s->frozen == is_frozen)
903 s->frozen = is_frozen;
904 if (!is_frozen && s->frozen_readable) {
906 recv(s->s, &c, 1, MSG_PEEK);
908 s->frozen_readable = 0;
912 * For Unix select()-based frontends: enumerate all sockets
913 * currently active, and state whether we currently wish to receive
914 * select events on them for reading, writing and exceptional
917 static void set_rwx(Actual_Socket s, int *rwx)
920 if (s->connected && !s->frozen)
921 val |= 1 | 4; /* read, except */
922 if (bufchain_size(&s->output_data))
923 val |= 2; /* write */
925 val |= 1; /* read == accept */
929 int first_socket(int *state, int *rwx)
933 s = index234(sktree, (*state)++);
936 return s ? s->s : -1;
939 int next_socket(int *state, int *rwx)
941 Actual_Socket s = index234(sktree, (*state)++);
944 return s ? s->s : -1;
947 int net_service_lookup(char *service)
950 se = getservbyname(service, NULL);
952 return ntohs(se->s_port);