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 char *ret
= smalloc(strlen(strerror(error
)) +
110 strlen("Network error: "));
111 sprintf(ret
, "Network error: %s",strerror(error
));
115 SockAddr
sk_namelookup(char *host
, char **canonicalname
)
117 SockAddr ret
= smalloc(sizeof(struct SockAddr_tag
));
119 struct hostent
*h
= NULL
;
122 /* Clear the structure and default to IPv4. */
123 memset(ret
, 0, sizeof(struct SockAddr_tag
));
124 ret
->family
= 0; /* We set this one when we have resolved the host. */
128 if ((a
= inet_addr(host
)) == (unsigned long) INADDR_NONE
) {
130 if (getaddrinfo(host
, NULL
, NULL
, &ret
->ai
) == 0) {
131 ret
->family
= ret
->ai
->ai_family
;
136 * Otherwise use the IPv4-only gethostbyname... (NOTE:
137 * we don't use gethostbyname as a fallback!)
139 if (ret
->family
== 0) {
140 /*debug(("Resolving \"%s\" with gethostbyname() (IPv4 only)...\n", host)); */
141 if ( (h
= gethostbyname(host
)) )
142 ret
->family
= AF_INET
;
144 if (ret
->family
== 0) {
145 ret
->error
= (h_errno
== HOST_NOT_FOUND
||
146 h_errno
== NO_DATA
||
147 h_errno
== NO_ADDRESS ?
"Host does not exist" :
148 h_errno
== TRY_AGAIN ?
149 "Temporary name service failure" :
150 "gethostbyname: unknown error");
156 /* If we got an address info use that... */
159 /* Are we in IPv4 fallback mode? */
160 /* We put the IPv4 address into the a variable so we can further-on use the IPv4 code... */
161 if (ret
->family
== AF_INET
)
163 (char *) &((struct sockaddr_in
*) ret
->ai
->
164 ai_addr
)->sin_addr
, sizeof(a
));
166 /* Now let's find that canonicalname... */
167 if (getnameinfo((struct sockaddr
*) ret
->ai
->ai_addr
,
169 AF_INET ?
sizeof(struct sockaddr_in
) :
170 sizeof(struct sockaddr_in6
), realhost
,
171 sizeof(realhost
), NULL
, 0, 0) != 0) {
172 strncpy(realhost
, host
, sizeof(realhost
));
175 /* We used the IPv4-only gethostbyname()... */
179 memcpy(&a
, h
->h_addr
, sizeof(a
));
180 /* This way we are always sure the h->h_name is valid :) */
181 strncpy(realhost
, h
->h_name
, sizeof(realhost
));
185 * This must be a numeric IPv4 address because it caused a
186 * success return from inet_addr.
188 ret
->family
= AF_INET
;
189 strncpy(realhost
, host
, sizeof(realhost
));
191 ret
->address
= ntohl(a
);
192 realhost
[lenof(realhost
)-1] = '\0';
193 *canonicalname
= smalloc(1+strlen(realhost
));
194 strcpy(*canonicalname
, realhost
);
198 void sk_getaddr(SockAddr addr
, char *buf
, int buflen
)
201 if (addr
->family
== AF_INET
) {
204 a
.s_addr
= htonl(addr
->address
);
205 strncpy(buf
, inet_ntoa(a
), buflen
);
208 FIXME
; /* I don't know how to get a text form of an IPv6 address. */
213 int sk_addrtype(SockAddr addr
)
215 return (addr
->family
== AF_INET ? ADDRTYPE_IPV4
: ADDRTYPE_IPV6
);
218 void sk_addrcopy(SockAddr addr
, char *buf
)
221 if (addr
->family
== AF_INET
) {
224 a
.s_addr
= htonl(addr
->address
);
225 memcpy(buf
, (char*) &a
.s_addr
, 4);
228 memcpy(buf
, (char*) addr
->ai
, 16);
233 void sk_addr_free(SockAddr addr
)
238 static Plug
sk_tcp_plug(Socket sock
, Plug p
)
240 Actual_Socket s
= (Actual_Socket
) sock
;
247 static void sk_tcp_flush(Socket s
)
250 * We send data to the socket as soon as we can anyway,
251 * so we don't need to do anything here. :-)
255 static void sk_tcp_close(Socket s
);
256 static int sk_tcp_write(Socket s
, char *data
, int len
);
257 static int sk_tcp_write_oob(Socket s
, char *data
, int len
);
258 static void sk_tcp_set_private_ptr(Socket s
, void *ptr
);
259 static void *sk_tcp_get_private_ptr(Socket s
);
260 static void sk_tcp_set_frozen(Socket s
, int is_frozen
);
261 static char *sk_tcp_socket_error(Socket s
);
263 Socket
sk_register(void *sock
, Plug plug
)
265 static struct socket_function_table fn_table
= {
271 sk_tcp_set_private_ptr
,
272 sk_tcp_get_private_ptr
,
280 * Create Socket structure.
282 ret
= smalloc(sizeof(struct Socket_tag
));
286 bufchain_init(&ret
->output_data
);
287 ret
->writable
= 1; /* to start with */
288 ret
->sending_oob
= 0;
290 ret
->frozen_readable
= 0;
291 ret
->localhost_only
= 0; /* unused, but best init anyway */
292 ret
->pending_error
= 0;
293 ret
->oobpending
= FALSE
;
299 ret
->error
= error_string(errno
);
310 Socket
sk_new(SockAddr addr
, int port
, int privport
, int oobinline
,
311 int nodelay
, Plug plug
)
313 static struct socket_function_table fn_table
= {
319 sk_tcp_set_private_ptr
,
320 sk_tcp_get_private_ptr
,
327 struct sockaddr_in6 a6
;
329 struct sockaddr_in a
;
335 * Create Socket structure.
337 ret
= smalloc(sizeof(struct Socket_tag
));
341 bufchain_init(&ret
->output_data
);
342 ret
->connected
= 0; /* to start with */
343 ret
->writable
= 0; /* to start with */
344 ret
->sending_oob
= 0;
346 ret
->frozen_readable
= 0;
347 ret
->localhost_only
= 0; /* unused, but best init anyway */
348 ret
->pending_error
= 0;
349 ret
->oobpending
= FALSE
;
355 s
= socket(addr
->family
, SOCK_STREAM
, 0);
359 ret
->error
= error_string(errno
);
363 ret
->oobinline
= oobinline
;
366 setsockopt(s
, SOL_SOCKET
, SO_OOBINLINE
, (void *) &b
, sizeof(b
));
371 setsockopt(s
, IPPROTO_TCP
, TCP_NODELAY
, (void *) &b
, sizeof(b
));
375 * Bind to local address.
378 localport
= 1023; /* count from 1023 downwards */
380 localport
= 0; /* just use port 0 (ie kernel picks) */
382 /* Loop round trying to bind */
387 if (addr
->family
== AF_INET6
) {
388 memset(&a6
, 0, sizeof(a6
));
389 a6
.sin6_family
= AF_INET6
;
390 /*a6.sin6_addr = in6addr_any; *//* == 0 */
391 a6
.sin6_port
= htons(localport
);
395 a
.sin_family
= AF_INET
;
396 a
.sin_addr
.s_addr
= htonl(INADDR_ANY
);
397 a
.sin_port
= htons(localport
);
400 retcode
= bind(s
, (addr
->family
== AF_INET6 ?
401 (struct sockaddr
*) &a6
:
402 (struct sockaddr
*) &a
),
404 AF_INET6 ?
sizeof(a6
) : sizeof(a
)));
406 retcode
= bind(s
, (struct sockaddr
*) &a
, sizeof(a
));
413 if (err
!= EADDRINUSE
) /* failed, for a bad reason */
418 break; /* we're only looping once */
421 break; /* we might have got to the end */
425 ret
->error
= error_string(err
);
430 * Connect to remote address.
433 if (addr
->family
== AF_INET6
) {
434 memset(&a
, 0, sizeof(a
));
435 a6
.sin6_family
= AF_INET6
;
436 a6
.sin6_port
= htons((short) port
);
438 ((struct sockaddr_in6
*) addr
->ai
->ai_addr
)->sin6_addr
;
442 a
.sin_family
= AF_INET
;
443 a
.sin_addr
.s_addr
= htonl(addr
->address
);
444 a
.sin_port
= htons((short) port
);
449 connect(s
, ((addr
->family
== AF_INET6
) ?
450 (struct sockaddr
*) &a6
: (struct sockaddr
*) &a
),
451 (addr
->family
== AF_INET6
) ?
sizeof(a6
) : sizeof(a
))
453 connect(s
, (struct sockaddr
*) &a
, sizeof(a
))
457 * FIXME: We are prepared to receive EWOULDBLOCK here,
458 * because we might want the connection to be made
459 * asynchronously; but how do we actually arrange this in
462 if ( errno
!= EWOULDBLOCK
) {
463 ret
->error
= error_string(errno
);
468 * If we _don't_ get EWOULDBLOCK, the connect has completed
469 * and we should set the socket as connected and writable.
480 Socket
sk_newlistener(int port
, Plug plug
, int local_host_only
)
482 static struct socket_function_table fn_table
= {
488 sk_tcp_set_private_ptr
,
489 sk_tcp_get_private_ptr
,
496 struct sockaddr_in6 a6
;
498 struct sockaddr_in a
;
505 * Create Socket structure.
507 ret
= smalloc(sizeof(struct Socket_tag
));
511 bufchain_init(&ret
->output_data
);
512 ret
->writable
= 0; /* to start with */
513 ret
->sending_oob
= 0;
515 ret
->frozen_readable
= 0;
516 ret
->localhost_only
= local_host_only
;
517 ret
->pending_error
= 0;
518 ret
->oobpending
= FALSE
;
524 s
= socket(AF_INET
, SOCK_STREAM
, 0);
528 ret
->error
= error_string(errno
);
534 setsockopt(s
, SOL_SOCKET
, SO_REUSEADDR
, (const char *)&on
, sizeof(on
));
537 if (addr
->family
== AF_INET6
) {
538 memset(&a6
, 0, sizeof(a6
));
539 a6
.sin6_family
= AF_INET6
;
541 a6
.sin6_addr
= in6addr_loopback
;
543 a6
.sin6_addr
= in6addr_any
;
544 a6
.sin6_port
= htons(port
);
548 a
.sin_family
= AF_INET
;
550 a
.sin_addr
.s_addr
= htonl(INADDR_LOOPBACK
);
552 a
.sin_addr
.s_addr
= htonl(INADDR_ANY
);
553 a
.sin_port
= htons((short)port
);
556 retcode
= bind(s
, (addr
->family
== AF_INET6 ?
557 (struct sockaddr
*) &a6
:
558 (struct sockaddr
*) &a
),
560 AF_INET6 ?
sizeof(a6
) : sizeof(a
)));
562 retcode
= bind(s
, (struct sockaddr
*) &a
, sizeof(a
));
571 ret
->error
= error_string(err
);
576 if (listen(s
, SOMAXCONN
) < 0) {
578 ret
->error
= error_string(errno
);
587 static void sk_tcp_close(Socket sock
)
589 Actual_Socket s
= (Actual_Socket
) sock
;
597 * The function which tries to send on a socket once it's deemed
600 void try_send(Actual_Socket s
)
602 while (s
->sending_oob
|| bufchain_size(&s
->output_data
) > 0) {
608 if (s
->sending_oob
) {
609 urgentflag
= MSG_OOB
;
610 len
= s
->sending_oob
;
614 bufchain_prefix(&s
->output_data
, &data
, &len
);
616 nsent
= send(s
->s
, data
, len
, urgentflag
);
617 noise_ultralight(nsent
);
619 err
= (nsent
< 0 ? errno
: 0);
620 if (err
== EWOULDBLOCK
) {
622 * Perfectly normal: we've sent all we can for the moment.
626 } else if (nsent
== 0 ||
627 err
== ECONNABORTED
|| err
== ECONNRESET
) {
629 * If send() returns CONNABORTED or CONNRESET, we
630 * unfortunately can't just call plug_closing(),
631 * because it's quite likely that we're currently
632 * _in_ a call from the code we'd be calling back
633 * to, so we'd have to make half the SSH code
634 * reentrant. Instead we flag a pending error on
635 * the socket, to be dealt with (by calling
636 * plug_closing()) at some suitable future moment.
638 s
->pending_error
= err
;
641 /* We're inside the Unix frontend here, so we know
642 * that the frontend handle is unnecessary. */
643 logevent(NULL
, error_string(err
));
644 fatalbox("%s", error_string(err
));
647 if (s
->sending_oob
) {
649 memmove(s
->oobdata
, s
->oobdata
+nsent
, len
-nsent
);
650 s
->sending_oob
= len
- nsent
;
655 bufchain_consume(&s
->output_data
, nsent
);
661 static int sk_tcp_write(Socket sock
, char *buf
, int len
)
663 Actual_Socket s
= (Actual_Socket
) sock
;
666 * Add the data to the buffer list on the socket.
668 bufchain_add(&s
->output_data
, buf
, len
);
671 * Now try sending from the start of the buffer list.
676 return bufchain_size(&s
->output_data
);
679 static int sk_tcp_write_oob(Socket sock
, char *buf
, int len
)
681 Actual_Socket s
= (Actual_Socket
) sock
;
684 * Replace the buffer list on the socket with the data.
686 bufchain_clear(&s
->output_data
);
687 assert(len
<= sizeof(s
->oobdata
));
688 memcpy(s
->oobdata
, buf
, len
);
689 s
->sending_oob
= len
;
692 * Now try sending from the start of the buffer list.
697 return s
->sending_oob
;
700 int select_result(int fd
, int event
)
704 char buf
[20480]; /* nice big buffer for plenty of speed */
708 /* Find the Socket structure */
709 s
= find234(sktree
, (void *) fd
, cmpforsearch
);
711 return 1; /* boggle */
713 noise_ultralight(event
);
716 #ifdef FIXME_NONBLOCKING_CONNECTIONS
717 case FIXME
: /* connected */
718 s
->connected
= s
->writable
= 1;
721 case 4: /* exceptional */
724 * On a non-oobinline socket, this indicates that we
725 * can immediately perform an OOB read and get back OOB
726 * data, which we will send to the back end with
727 * type==2 (urgent data).
729 ret
= recv(s
->s
, buf
, sizeof(buf
), MSG_OOB
);
730 noise_ultralight(ret
);
732 char *str
= (ret
== 0 ?
"Internal networking trouble" :
733 error_string(errno
));
734 /* We're inside the Unix frontend here, so we know
735 * that the frontend handle is unnecessary. */
739 return plug_receive(s
->plug
, 2, buf
, ret
);
745 * If we reach here, this is an oobinline socket, which
746 * means we should set s->oobpending and then deal with it
747 * when we get called for the readability event (which
748 * should also occur).
750 s
->oobpending
= TRUE
;
752 case 1: /* readable; also acceptance */
755 * On a listening socket, the readability event means a
756 * connection is ready to be accepted.
758 struct sockaddr_in isa
;
759 int addrlen
= sizeof(struct sockaddr_in
);
760 int t
; /* socket of connection */
762 memset(&isa
, 0, sizeof(struct sockaddr_in
));
764 t
= accept(s
->s
,(struct sockaddr
*)&isa
,&addrlen
);
769 if (s
->localhost_only
&&
770 ntohl(isa
.sin_addr
.s_addr
) != INADDR_LOOPBACK
) {
771 close(t
); /* someone let nonlocal through?! */
772 } else if (plug_accepting(s
->plug
, (void*)t
)) {
773 close(t
); /* denied or error */
779 * If we reach here, this is not a listening socket, so
780 * readability really means readability.
783 /* In the case the socket is still frozen, we don't even bother */
785 s
->frozen_readable
= 1;
790 * We have received data on the socket. For an oobinline
791 * socket, this might be data _before_ an urgent pointer,
792 * in which case we send it to the back end with type==1
793 * (data prior to urgent).
795 if (s
->oobinline
&& s
->oobpending
) {
797 if (ioctl(s
->s
, SIOCATMARK
, &atmark
) == 0 && atmark
)
798 s
->oobpending
= FALSE
; /* clear this indicator */
802 ret
= recv(s
->s
, buf
, s
->oobpending ?
1 : sizeof(buf
), 0);
803 noise_ultralight(ret
);
805 if (errno
== EWOULDBLOCK
) {
810 return plug_closing(s
->plug
, error_string(errno
), errno
, 0);
811 } else if (0 == ret
) {
812 return plug_closing(s
->plug
, NULL
, 0, 0);
814 return plug_receive(s
->plug
, atmark ?
0 : 1, buf
, ret
);
817 case 2: /* writable */
819 int bufsize_before
, bufsize_after
;
821 bufsize_before
= s
->sending_oob
+ bufchain_size(&s
->output_data
);
823 bufsize_after
= s
->sending_oob
+ bufchain_size(&s
->output_data
);
824 if (bufsize_after
< bufsize_before
)
825 plug_sent(s
->plug
, bufsize_after
);
834 * Deal with socket errors detected in try_send().
836 void net_pending_errors(void)
842 * This might be a fiddly business, because it's just possible
843 * that handling a pending error on one socket might cause
844 * others to be closed. (I can't think of any reason this might
845 * happen in current SSH implementation, but to maintain
846 * generality of this network layer I'll assume the worst.)
848 * So what we'll do is search the socket list for _one_ socket
849 * with a pending error, and then handle it, and then search
850 * the list again _from the beginning_. Repeat until we make a
851 * pass with no socket errors present. That way we are
852 * protected against the socket list changing under our feet.
856 for (i
= 0; (s
= index234(sktree
, i
)) != NULL
; i
++) {
857 if (s
->pending_error
) {
859 * An error has occurred on this socket. Pass it to the
862 plug_closing(s
->plug
, error_string(s
->pending_error
),
863 s
->pending_error
, 0);
871 * Each socket abstraction contains a `void *' private field in
872 * which the client can keep state.
874 static void sk_tcp_set_private_ptr(Socket sock
, void *ptr
)
876 Actual_Socket s
= (Actual_Socket
) sock
;
877 s
->private_ptr
= ptr
;
880 static void *sk_tcp_get_private_ptr(Socket sock
)
882 Actual_Socket s
= (Actual_Socket
) sock
;
883 return s
->private_ptr
;
887 * Special error values are returned from sk_namelookup and sk_new
888 * if there's a problem. These functions extract an error message,
889 * or return NULL if there's no problem.
891 char *sk_addr_error(SockAddr addr
)
895 static char *sk_tcp_socket_error(Socket sock
)
897 Actual_Socket s
= (Actual_Socket
) sock
;
901 static void sk_tcp_set_frozen(Socket sock
, int is_frozen
)
903 Actual_Socket s
= (Actual_Socket
) sock
;
904 if (s
->frozen
== is_frozen
)
906 s
->frozen
= is_frozen
;
907 if (!is_frozen
&& s
->frozen_readable
) {
909 recv(s
->s
, &c
, 1, MSG_PEEK
);
911 s
->frozen_readable
= 0;
915 * For Unix select()-based frontends: enumerate all sockets
916 * currently active, and state whether we currently wish to receive
917 * select events on them for reading, writing and exceptional
920 static void set_rwx(Actual_Socket s
, int *rwx
)
923 if (s
->connected
&& !s
->frozen
)
924 val
|= 1 | 4; /* read, except */
925 if (bufchain_size(&s
->output_data
))
926 val
|= 2; /* write */
928 val
|= 1; /* read == accept */
932 int first_socket(int *state
, int *rwx
)
936 s
= index234(sktree
, (*state
)++);
939 return s ? s
->s
: -1;
942 int next_socket(int *state
, int *rwx
)
944 Actual_Socket s
= index234(sktree
, (*state
)++);
947 return s ? s
->s
: -1;
950 int net_service_lookup(char *service
)
953 se
= getservbyname(service
, NULL
);
955 return ntohs(se
->s_port
);