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
;
60 /* address family this belongs to, AF_INET for IPv4, AF_INET6 for IPv6. */
62 unsigned long address
; /* Address IPv4 style. */
64 struct addrinfo
*ai
; /* Address IPv6 style. */
68 static tree234
*sktree
;
70 static int cmpfortree(void *av
, void *bv
)
72 Actual_Socket a
= (Actual_Socket
) av
, b
= (Actual_Socket
) bv
;
73 int as
= a
->s
, bs
= b
->s
;
81 static int cmpforsearch(void *av
, void *bv
)
83 Actual_Socket b
= (Actual_Socket
) bv
;
84 int as
= (int) av
, bs
= b
->s
;
94 sktree
= newtree234(cmpfortree
);
103 for (i
= 0; (s
= index234(sktree
, i
)) != NULL
; i
++) {
109 char *error_string(int error
)
111 return strerror(error
);
114 SockAddr
sk_namelookup(char *host
, char **canonicalname
)
116 SockAddr ret
= smalloc(sizeof(struct SockAddr_tag
));
118 struct hostent
*h
= NULL
;
121 /* Clear the structure and default to IPv4. */
122 memset(ret
, 0, sizeof(struct SockAddr_tag
));
123 ret
->family
= 0; /* We set this one when we have resolved the host. */
127 if ((a
= inet_addr(host
)) == (unsigned long) INADDR_NONE
) {
129 if (getaddrinfo(host
, NULL
, NULL
, &ret
->ai
) == 0) {
130 ret
->family
= ret
->ai
->ai_family
;
135 * Otherwise use the IPv4-only gethostbyname... (NOTE:
136 * we don't use gethostbyname as a fallback!)
138 if (ret
->family
== 0) {
139 /*debug(("Resolving \"%s\" with gethostbyname() (IPv4 only)...\n", host)); */
140 if ( (h
= gethostbyname(host
)) )
141 ret
->family
= AF_INET
;
143 if (ret
->family
== 0) {
144 ret
->error
= (h_errno
== HOST_NOT_FOUND
||
145 h_errno
== NO_DATA
||
146 h_errno
== NO_ADDRESS ?
"Host does not exist" :
147 h_errno
== TRY_AGAIN ?
148 "Temporary name service failure" :
149 "gethostbyname: unknown error");
155 /* If we got an address info use that... */
158 /* Are we in IPv4 fallback mode? */
159 /* We put the IPv4 address into the a variable so we can further-on use the IPv4 code... */
160 if (ret
->family
== AF_INET
)
162 (char *) &((struct sockaddr_in
*) ret
->ai
->
163 ai_addr
)->sin_addr
, sizeof(a
));
165 /* Now let's find that canonicalname... */
166 if (getnameinfo((struct sockaddr
*) ret
->ai
->ai_addr
,
168 AF_INET ?
sizeof(struct sockaddr_in
) :
169 sizeof(struct sockaddr_in6
), realhost
,
170 sizeof(realhost
), NULL
, 0, 0) != 0) {
171 strncpy(realhost
, host
, sizeof(realhost
));
174 /* We used the IPv4-only gethostbyname()... */
178 memcpy(&a
, h
->h_addr
, sizeof(a
));
179 /* This way we are always sure the h->h_name is valid :) */
180 strncpy(realhost
, h
->h_name
, sizeof(realhost
));
184 * This must be a numeric IPv4 address because it caused a
185 * success return from inet_addr.
187 ret
->family
= AF_INET
;
188 strncpy(realhost
, host
, sizeof(realhost
));
190 ret
->address
= ntohl(a
);
191 realhost
[lenof(realhost
)-1] = '\0';
192 *canonicalname
= smalloc(1+strlen(realhost
));
193 strcpy(*canonicalname
, realhost
);
197 void sk_getaddr(SockAddr addr
, char *buf
, int buflen
)
200 if (addr
->family
== AF_INET
) {
203 a
.s_addr
= htonl(addr
->address
);
204 strncpy(buf
, inet_ntoa(a
), buflen
);
207 FIXME
; /* I don't know how to get a text form of an IPv6 address. */
212 int sk_hostname_is_local(char *name
)
214 return !strcmp(name
, "localhost");
217 int sk_address_is_local(SockAddr addr
)
220 if (addr
->family
== AF_INET
) {
223 a
.s_addr
= htonl(addr
->address
);
224 return ipv4_is_loopback(a
);
227 FIXME
; /* someone who can compile for IPV6 had better do this bit */
232 int sk_addrtype(SockAddr addr
)
234 return (addr
->family
== AF_INET ? ADDRTYPE_IPV4
: ADDRTYPE_IPV6
);
237 void sk_addrcopy(SockAddr addr
, char *buf
)
240 if (addr
->family
== AF_INET
) {
243 a
.s_addr
= htonl(addr
->address
);
244 memcpy(buf
, (char*) &a
.s_addr
, 4);
247 memcpy(buf
, (char*) addr
->ai
, 16);
252 void sk_addr_free(SockAddr addr
)
257 static Plug
sk_tcp_plug(Socket sock
, Plug p
)
259 Actual_Socket s
= (Actual_Socket
) sock
;
266 static void sk_tcp_flush(Socket s
)
269 * We send data to the socket as soon as we can anyway,
270 * so we don't need to do anything here. :-)
274 static void sk_tcp_close(Socket s
);
275 static int sk_tcp_write(Socket s
, char *data
, int len
);
276 static int sk_tcp_write_oob(Socket s
, char *data
, int len
);
277 static void sk_tcp_set_private_ptr(Socket s
, void *ptr
);
278 static void *sk_tcp_get_private_ptr(Socket s
);
279 static void sk_tcp_set_frozen(Socket s
, int is_frozen
);
280 static char *sk_tcp_socket_error(Socket s
);
282 Socket
sk_register(void *sock
, Plug plug
)
284 static struct socket_function_table fn_table
= {
290 sk_tcp_set_private_ptr
,
291 sk_tcp_get_private_ptr
,
299 * Create Socket structure.
301 ret
= smalloc(sizeof(struct Socket_tag
));
305 bufchain_init(&ret
->output_data
);
306 ret
->writable
= 1; /* to start with */
307 ret
->sending_oob
= 0;
309 ret
->frozen_readable
= 0;
310 ret
->localhost_only
= 0; /* unused, but best init anyway */
311 ret
->pending_error
= 0;
312 ret
->oobpending
= FALSE
;
318 ret
->error
= error_string(errno
);
329 Socket
sk_new(SockAddr addr
, int port
, int privport
, int oobinline
,
330 int nodelay
, Plug plug
)
332 static struct socket_function_table fn_table
= {
338 sk_tcp_set_private_ptr
,
339 sk_tcp_get_private_ptr
,
346 struct sockaddr_in6 a6
;
348 struct sockaddr_in a
;
354 * Create Socket structure.
356 ret
= smalloc(sizeof(struct Socket_tag
));
360 bufchain_init(&ret
->output_data
);
361 ret
->connected
= 0; /* to start with */
362 ret
->writable
= 0; /* to start with */
363 ret
->sending_oob
= 0;
365 ret
->frozen_readable
= 0;
366 ret
->localhost_only
= 0; /* unused, but best init anyway */
367 ret
->pending_error
= 0;
368 ret
->oobpending
= FALSE
;
374 s
= socket(addr
->family
, SOCK_STREAM
, 0);
378 ret
->error
= error_string(errno
);
382 ret
->oobinline
= oobinline
;
385 setsockopt(s
, SOL_SOCKET
, SO_OOBINLINE
, (void *) &b
, sizeof(b
));
390 setsockopt(s
, IPPROTO_TCP
, TCP_NODELAY
, (void *) &b
, sizeof(b
));
394 * Bind to local address.
397 localport
= 1023; /* count from 1023 downwards */
399 localport
= 0; /* just use port 0 (ie kernel picks) */
401 /* Loop round trying to bind */
406 if (addr
->family
== AF_INET6
) {
407 memset(&a6
, 0, sizeof(a6
));
408 a6
.sin6_family
= AF_INET6
;
409 /*a6.sin6_addr = in6addr_any; *//* == 0 */
410 a6
.sin6_port
= htons(localport
);
414 a
.sin_family
= AF_INET
;
415 a
.sin_addr
.s_addr
= htonl(INADDR_ANY
);
416 a
.sin_port
= htons(localport
);
419 retcode
= bind(s
, (addr
->family
== AF_INET6 ?
420 (struct sockaddr
*) &a6
:
421 (struct sockaddr
*) &a
),
423 AF_INET6 ?
sizeof(a6
) : sizeof(a
)));
425 retcode
= bind(s
, (struct sockaddr
*) &a
, sizeof(a
));
432 if (err
!= EADDRINUSE
) /* failed, for a bad reason */
437 break; /* we're only looping once */
440 break; /* we might have got to the end */
444 ret
->error
= error_string(err
);
449 * Connect to remote address.
452 if (addr
->family
== AF_INET6
) {
453 memset(&a
, 0, sizeof(a
));
454 a6
.sin6_family
= AF_INET6
;
455 a6
.sin6_port
= htons((short) port
);
457 ((struct sockaddr_in6
*) addr
->ai
->ai_addr
)->sin6_addr
;
461 a
.sin_family
= AF_INET
;
462 a
.sin_addr
.s_addr
= htonl(addr
->address
);
463 a
.sin_port
= htons((short) port
);
468 connect(s
, ((addr
->family
== AF_INET6
) ?
469 (struct sockaddr
*) &a6
: (struct sockaddr
*) &a
),
470 (addr
->family
== AF_INET6
) ?
sizeof(a6
) : sizeof(a
))
472 connect(s
, (struct sockaddr
*) &a
, sizeof(a
))
476 * FIXME: We are prepared to receive EWOULDBLOCK here,
477 * because we might want the connection to be made
478 * asynchronously; but how do we actually arrange this in
481 if ( errno
!= EWOULDBLOCK
) {
482 ret
->error
= error_string(errno
);
487 * If we _don't_ get EWOULDBLOCK, the connect has completed
488 * and we should set the socket as connected and writable.
499 Socket
sk_newlistener(char *srcaddr
, int port
, Plug plug
, int local_host_only
)
501 static struct socket_function_table fn_table
= {
507 sk_tcp_set_private_ptr
,
508 sk_tcp_get_private_ptr
,
515 struct sockaddr_in6 a6
;
517 struct sockaddr_in a
;
524 * Create Socket structure.
526 ret
= smalloc(sizeof(struct Socket_tag
));
530 bufchain_init(&ret
->output_data
);
531 ret
->writable
= 0; /* to start with */
532 ret
->sending_oob
= 0;
534 ret
->frozen_readable
= 0;
535 ret
->localhost_only
= local_host_only
;
536 ret
->pending_error
= 0;
537 ret
->oobpending
= FALSE
;
543 s
= socket(AF_INET
, SOCK_STREAM
, 0);
547 ret
->error
= error_string(errno
);
553 setsockopt(s
, SOL_SOCKET
, SO_REUSEADDR
, (const char *)&on
, sizeof(on
));
556 if (addr
->family
== AF_INET6
) {
557 memset(&a6
, 0, sizeof(a6
));
558 a6
.sin6_family
= AF_INET6
;
559 /* FIXME: srcaddr is ignored for IPv6, because I (SGT) don't
560 * know how to do it. :-) */
562 a6
.sin6_addr
= in6addr_loopback
;
564 a6
.sin6_addr
= in6addr_any
;
565 a6
.sin6_port
= htons(port
);
570 a
.sin_family
= AF_INET
;
573 * Bind to source address. First try an explicitly
577 a
.sin_addr
.s_addr
= inet_addr(srcaddr
);
578 if (a
.sin_addr
.s_addr
!= INADDR_NONE
) {
579 /* Override localhost_only with specified listen addr. */
580 ret
->localhost_only
= ipv4_is_loopback(a
.sin_addr
);
586 * ... and failing that, go with one of the standard ones.
590 a
.sin_addr
.s_addr
= htonl(INADDR_LOOPBACK
);
592 a
.sin_addr
.s_addr
= htonl(INADDR_ANY
);
595 a
.sin_port
= htons((short)port
);
598 retcode
= bind(s
, (addr
->family
== AF_INET6 ?
599 (struct sockaddr
*) &a6
:
600 (struct sockaddr
*) &a
),
602 AF_INET6 ?
sizeof(a6
) : sizeof(a
)));
604 retcode
= bind(s
, (struct sockaddr
*) &a
, sizeof(a
));
613 ret
->error
= error_string(err
);
618 if (listen(s
, SOMAXCONN
) < 0) {
620 ret
->error
= error_string(errno
);
629 static void sk_tcp_close(Socket sock
)
631 Actual_Socket s
= (Actual_Socket
) sock
;
639 * The function which tries to send on a socket once it's deemed
642 void try_send(Actual_Socket s
)
644 while (s
->sending_oob
|| bufchain_size(&s
->output_data
) > 0) {
650 if (s
->sending_oob
) {
651 urgentflag
= MSG_OOB
;
652 len
= s
->sending_oob
;
656 bufchain_prefix(&s
->output_data
, &data
, &len
);
658 nsent
= send(s
->s
, data
, len
, urgentflag
);
659 noise_ultralight(nsent
);
661 err
= (nsent
< 0 ? errno
: 0);
662 if (err
== EWOULDBLOCK
) {
664 * Perfectly normal: we've sent all we can for the moment.
668 } else if (nsent
== 0 ||
669 err
== ECONNABORTED
|| err
== ECONNRESET
) {
671 * If send() returns CONNABORTED or CONNRESET, we
672 * unfortunately can't just call plug_closing(),
673 * because it's quite likely that we're currently
674 * _in_ a call from the code we'd be calling back
675 * to, so we'd have to make half the SSH code
676 * reentrant. Instead we flag a pending error on
677 * the socket, to be dealt with (by calling
678 * plug_closing()) at some suitable future moment.
680 s
->pending_error
= err
;
683 /* We're inside the Unix frontend here, so we know
684 * that the frontend handle is unnecessary. */
685 logevent(NULL
, error_string(err
));
686 fatalbox("%s", error_string(err
));
689 if (s
->sending_oob
) {
691 memmove(s
->oobdata
, s
->oobdata
+nsent
, len
-nsent
);
692 s
->sending_oob
= len
- nsent
;
697 bufchain_consume(&s
->output_data
, nsent
);
703 static int sk_tcp_write(Socket sock
, char *buf
, int len
)
705 Actual_Socket s
= (Actual_Socket
) sock
;
708 * Add the data to the buffer list on the socket.
710 bufchain_add(&s
->output_data
, buf
, len
);
713 * Now try sending from the start of the buffer list.
718 return bufchain_size(&s
->output_data
);
721 static int sk_tcp_write_oob(Socket sock
, char *buf
, int len
)
723 Actual_Socket s
= (Actual_Socket
) sock
;
726 * Replace the buffer list on the socket with the data.
728 bufchain_clear(&s
->output_data
);
729 assert(len
<= sizeof(s
->oobdata
));
730 memcpy(s
->oobdata
, buf
, len
);
731 s
->sending_oob
= len
;
734 * Now try sending from the start of the buffer list.
739 return s
->sending_oob
;
742 int select_result(int fd
, int event
)
746 char buf
[20480]; /* nice big buffer for plenty of speed */
750 /* Find the Socket structure */
751 s
= find234(sktree
, (void *) fd
, cmpforsearch
);
753 return 1; /* boggle */
755 noise_ultralight(event
);
758 #ifdef FIXME_NONBLOCKING_CONNECTIONS
759 case FIXME
: /* connected */
760 s
->connected
= s
->writable
= 1;
763 case 4: /* exceptional */
766 * On a non-oobinline socket, this indicates that we
767 * can immediately perform an OOB read and get back OOB
768 * data, which we will send to the back end with
769 * type==2 (urgent data).
771 ret
= recv(s
->s
, buf
, sizeof(buf
), MSG_OOB
);
772 noise_ultralight(ret
);
774 char *str
= (ret
== 0 ?
"Internal networking trouble" :
775 error_string(errno
));
776 /* We're inside the Unix frontend here, so we know
777 * that the frontend handle is unnecessary. */
781 return plug_receive(s
->plug
, 2, buf
, ret
);
787 * If we reach here, this is an oobinline socket, which
788 * means we should set s->oobpending and then deal with it
789 * when we get called for the readability event (which
790 * should also occur).
792 s
->oobpending
= TRUE
;
794 case 1: /* readable; also acceptance */
797 * On a listening socket, the readability event means a
798 * connection is ready to be accepted.
800 struct sockaddr_in isa
;
801 int addrlen
= sizeof(struct sockaddr_in
);
802 int t
; /* socket of connection */
804 memset(&isa
, 0, sizeof(struct sockaddr_in
));
806 t
= accept(s
->s
,(struct sockaddr
*)&isa
,&addrlen
);
811 if (s
->localhost_only
&& !ipv4_is_loopback(isa
.sin_addr
)) {
812 close(t
); /* someone let nonlocal through?! */
813 } else if (plug_accepting(s
->plug
, (void*)t
)) {
814 close(t
); /* denied or error */
820 * If we reach here, this is not a listening socket, so
821 * readability really means readability.
824 /* In the case the socket is still frozen, we don't even bother */
826 s
->frozen_readable
= 1;
831 * We have received data on the socket. For an oobinline
832 * socket, this might be data _before_ an urgent pointer,
833 * in which case we send it to the back end with type==1
834 * (data prior to urgent).
836 if (s
->oobinline
&& s
->oobpending
) {
838 if (ioctl(s
->s
, SIOCATMARK
, &atmark
) == 0 && atmark
)
839 s
->oobpending
= FALSE
; /* clear this indicator */
843 ret
= recv(s
->s
, buf
, s
->oobpending ?
1 : sizeof(buf
), 0);
844 noise_ultralight(ret
);
846 if (errno
== EWOULDBLOCK
) {
851 return plug_closing(s
->plug
, error_string(errno
), errno
, 0);
852 } else if (0 == ret
) {
853 return plug_closing(s
->plug
, NULL
, 0, 0);
855 return plug_receive(s
->plug
, atmark ?
0 : 1, buf
, ret
);
858 case 2: /* writable */
860 int bufsize_before
, bufsize_after
;
862 bufsize_before
= s
->sending_oob
+ bufchain_size(&s
->output_data
);
864 bufsize_after
= s
->sending_oob
+ bufchain_size(&s
->output_data
);
865 if (bufsize_after
< bufsize_before
)
866 plug_sent(s
->plug
, bufsize_after
);
875 * Deal with socket errors detected in try_send().
877 void net_pending_errors(void)
883 * This might be a fiddly business, because it's just possible
884 * that handling a pending error on one socket might cause
885 * others to be closed. (I can't think of any reason this might
886 * happen in current SSH implementation, but to maintain
887 * generality of this network layer I'll assume the worst.)
889 * So what we'll do is search the socket list for _one_ socket
890 * with a pending error, and then handle it, and then search
891 * the list again _from the beginning_. Repeat until we make a
892 * pass with no socket errors present. That way we are
893 * protected against the socket list changing under our feet.
897 for (i
= 0; (s
= index234(sktree
, i
)) != NULL
; i
++) {
898 if (s
->pending_error
) {
900 * An error has occurred on this socket. Pass it to the
903 plug_closing(s
->plug
, error_string(s
->pending_error
),
904 s
->pending_error
, 0);
912 * Each socket abstraction contains a `void *' private field in
913 * which the client can keep state.
915 static void sk_tcp_set_private_ptr(Socket sock
, void *ptr
)
917 Actual_Socket s
= (Actual_Socket
) sock
;
918 s
->private_ptr
= ptr
;
921 static void *sk_tcp_get_private_ptr(Socket sock
)
923 Actual_Socket s
= (Actual_Socket
) sock
;
924 return s
->private_ptr
;
928 * Special error values are returned from sk_namelookup and sk_new
929 * if there's a problem. These functions extract an error message,
930 * or return NULL if there's no problem.
932 char *sk_addr_error(SockAddr addr
)
936 static char *sk_tcp_socket_error(Socket sock
)
938 Actual_Socket s
= (Actual_Socket
) sock
;
942 static void sk_tcp_set_frozen(Socket sock
, int is_frozen
)
944 Actual_Socket s
= (Actual_Socket
) sock
;
945 if (s
->frozen
== is_frozen
)
947 s
->frozen
= is_frozen
;
948 if (!is_frozen
&& s
->frozen_readable
) {
950 recv(s
->s
, &c
, 1, MSG_PEEK
);
952 s
->frozen_readable
= 0;
956 * For Unix select()-based frontends: enumerate all sockets
957 * currently active, and state whether we currently wish to receive
958 * select events on them for reading, writing and exceptional
961 static void set_rwx(Actual_Socket s
, int *rwx
)
964 if (s
->connected
&& !s
->frozen
)
965 val
|= 1 | 4; /* read, except */
966 if (bufchain_size(&s
->output_data
))
967 val
|= 2; /* write */
969 val
|= 1; /* read == accept */
973 int first_socket(int *state
, int *rwx
)
977 s
= index234(sktree
, (*state
)++);
980 return s ? s
->s
: -1;
983 int next_socket(int *state
, int *rwx
)
985 Actual_Socket s
= index234(sktree
, (*state
)++);
988 return s ? s
->s
: -1;
991 int net_service_lookup(char *service
)
994 se
= getservbyname(service
, NULL
);
996 return ntohs(se
->s_port
);