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
;
46 struct sockaddr_un su
;
50 * We used to typedef struct Socket_tag *Socket.
52 * Since we have made the networking abstraction slightly more
53 * abstract, Socket no longer means a tcp socket (it could mean
54 * an ssl socket). So now we must use Actual_Socket when we know
55 * we are talking about a tcp socket.
57 typedef struct Socket_tag
*Actual_Socket
;
60 * Mutable state that goes with a SockAddr: stores information
61 * about where in the list of candidate IP(v*) addresses we've
64 typedef struct SockAddrStep_tag SockAddrStep
;
65 struct SockAddrStep_tag
{
67 struct addrinfo
*ai
; /* steps along addr->ais */
73 struct socket_function_table
*fn
;
74 /* the above variable absolutely *must* be the first in this structure */
80 int connected
; /* irrelevant for listening sockets */
82 int frozen
; /* this causes readability notifications to be ignored */
83 int frozen_readable
; /* this means we missed at least one readability
84 * notification while we were frozen */
85 int localhost_only
; /* for listening sockets */
88 int oobpending
; /* is there OOB data available to read? */
90 enum { EOF_NO
, EOF_PENDING
, EOF_SENT
} outgoingeof
;
92 int pending_error
; /* in case send() returns error */
94 int nodelay
, keepalive
; /* for connect()-type sockets */
95 int privport
, port
; /* and again */
99 * We sometimes need pairs of Socket structures to be linked:
100 * if we are listening on the same IPv6 and v4 port, for
101 * example. So here we define `parent' and `child' pointers to
104 Actual_Socket parent
, child
;
107 struct SockAddr_tag
{
110 enum { UNRESOLVED
, UNIX
, IP
} superfamily
;
112 struct addrinfo
*ais
; /* Addresses IPv6 style. */
114 unsigned long *addresses
; /* Addresses IPv4 style. */
117 char hostname
[512]; /* Store an unresolved host name. */
121 * Which address family this address belongs to. AF_INET for IPv4;
122 * AF_INET6 for IPv6; AF_UNSPEC indicates that name resolution has
123 * not been done and a simple host name is held in this SockAddr
127 #define SOCKADDR_FAMILY(addr, step) \
128 ((addr)->superfamily == UNRESOLVED ? AF_UNSPEC : \
129 (addr)->superfamily == UNIX ? AF_UNIX : \
130 (step).ai ? (step).ai->ai_family : AF_INET)
132 #define SOCKADDR_FAMILY(addr, step) \
133 ((addr)->superfamily == UNRESOLVED ? AF_UNSPEC : \
134 (addr)->superfamily == UNIX ? AF_UNIX : AF_INET)
138 * Start a SockAddrStep structure to step through multiple
142 #define START_STEP(addr, step) \
143 ((step).ai = (addr)->ais, (step).curraddr = 0)
145 #define START_STEP(addr, step) \
146 ((step).curraddr = 0)
149 static tree234
*sktree
;
151 static void uxsel_tell(Actual_Socket s
);
153 static int cmpfortree(void *av
, void *bv
)
155 Actual_Socket a
= (Actual_Socket
) av
, b
= (Actual_Socket
) bv
;
156 int as
= a
->s
, bs
= b
->s
;
168 static int cmpforsearch(void *av
, void *bv
)
170 Actual_Socket b
= (Actual_Socket
) bv
;
171 int as
= *(int *)av
, bs
= b
->s
;
181 sktree
= newtree234(cmpfortree
);
184 void sk_cleanup(void)
190 for (i
= 0; (s
= index234(sktree
, i
)) != NULL
; i
++) {
196 SockAddr
sk_namelookup(const char *host
, char **canonicalname
, int address_family
)
198 SockAddr ret
= snew(struct SockAddr_tag
);
200 struct addrinfo hints
;
204 struct hostent
*h
= NULL
;
209 /* Clear the structure and default to IPv4. */
210 memset(ret
, 0, sizeof(struct SockAddr_tag
));
211 ret
->superfamily
= UNRESOLVED
;
217 hints
.ai_flags
= AI_CANONNAME
;
218 hints
.ai_family
= (address_family
== ADDRTYPE_IPV4 ? AF_INET
:
219 address_family
== ADDRTYPE_IPV6 ? AF_INET6
:
221 hints
.ai_socktype
= SOCK_STREAM
;
222 hints
.ai_protocol
= 0;
223 hints
.ai_addrlen
= 0;
224 hints
.ai_addr
= NULL
;
225 hints
.ai_canonname
= NULL
;
226 hints
.ai_next
= NULL
;
227 err
= getaddrinfo(host
, NULL
, &hints
, &ret
->ais
);
229 ret
->error
= gai_strerror(err
);
232 ret
->superfamily
= IP
;
234 if (ret
->ais
->ai_canonname
!= NULL
)
235 strncat(realhost
, ret
->ais
->ai_canonname
, sizeof(realhost
) - 1);
237 strncat(realhost
, host
, sizeof(realhost
) - 1);
239 if ((a
= inet_addr(host
)) == (unsigned long)(in_addr_t
)(-1)) {
241 * Otherwise use the IPv4-only gethostbyname... (NOTE:
242 * we don't use gethostbyname as a fallback!)
244 if (ret
->superfamily
== UNRESOLVED
) {
245 /*debug(("Resolving \"%s\" with gethostbyname() (IPv4 only)...\n", host)); */
246 if ( (h
= gethostbyname(host
)) )
247 ret
->superfamily
= IP
;
249 if (ret
->superfamily
== UNRESOLVED
) {
250 ret
->error
= (h_errno
== HOST_NOT_FOUND
||
251 h_errno
== NO_DATA
||
252 h_errno
== NO_ADDRESS ?
"Host does not exist" :
253 h_errno
== TRY_AGAIN ?
254 "Temporary name service failure" :
255 "gethostbyname: unknown error");
258 /* This way we are always sure the h->h_name is valid :) */
259 strncpy(realhost
, h
->h_name
, sizeof(realhost
));
260 for (n
= 0; h
->h_addr_list
[n
]; n
++);
261 ret
->addresses
= snewn(n
, unsigned long);
263 for (n
= 0; n
< ret
->naddresses
; n
++) {
264 memcpy(&a
, h
->h_addr_list
[n
], sizeof(a
));
265 ret
->addresses
[n
] = ntohl(a
);
269 * This must be a numeric IPv4 address because it caused a
270 * success return from inet_addr.
272 ret
->superfamily
= IP
;
273 strncpy(realhost
, host
, sizeof(realhost
));
274 ret
->addresses
= snew(unsigned long);
276 ret
->addresses
[0] = ntohl(a
);
279 realhost
[lenof(realhost
)-1] = '\0';
280 *canonicalname
= snewn(1+strlen(realhost
), char);
281 strcpy(*canonicalname
, realhost
);
285 SockAddr
sk_nonamelookup(const char *host
)
287 SockAddr ret
= snew(struct SockAddr_tag
);
289 ret
->superfamily
= UNRESOLVED
;
290 strncpy(ret
->hostname
, host
, lenof(ret
->hostname
));
291 ret
->hostname
[lenof(ret
->hostname
)-1] = '\0';
295 ret
->addresses
= NULL
;
301 static int sk_nextaddr(SockAddr addr
, SockAddrStep
*step
)
304 if (step
->ai
&& step
->ai
->ai_next
) {
305 step
->ai
= step
->ai
->ai_next
;
310 if (step
->curraddr
+1 < addr
->naddresses
) {
319 void sk_getaddr(SockAddr addr
, char *buf
, int buflen
)
321 /* XXX not clear what we should return for Unix-domain sockets; let's
322 * hope the question never arises */
323 assert(addr
->superfamily
!= UNIX
);
324 if (addr
->superfamily
== UNRESOLVED
) {
325 strncpy(buf
, addr
->hostname
, buflen
);
326 buf
[buflen
-1] = '\0';
329 if (getnameinfo(addr
->ais
->ai_addr
, addr
->ais
->ai_addrlen
, buf
, buflen
,
330 NULL
, 0, NI_NUMERICHOST
) != 0) {
332 strncat(buf
, "<unknown>", buflen
- 1);
337 START_STEP(addr
, step
);
338 assert(SOCKADDR_FAMILY(addr
, step
) == AF_INET
);
339 a
.s_addr
= htonl(addr
->addresses
[0]);
340 strncpy(buf
, inet_ntoa(a
), buflen
);
341 buf
[buflen
-1] = '\0';
346 int sk_hostname_is_local(char *name
)
348 return !strcmp(name
, "localhost") ||
349 !strcmp(name
, "::1") ||
350 !strncmp(name
, "127.", 4);
353 #define ipv4_is_loopback(addr) \
354 (((addr).s_addr & htonl(0xff000000)) == htonl(0x7f000000))
356 static int sockaddr_is_loopback(struct sockaddr
*sa
)
358 union sockaddr_union
*u
= (union sockaddr_union
*)sa
;
359 switch (u
->sa
.sa_family
) {
361 return ipv4_is_loopback(u
->sin
.sin_addr
);
364 return IN6_IS_ADDR_LOOPBACK(&u
->sin6
.sin6_addr
);
373 int sk_address_is_local(SockAddr addr
)
375 if (addr
->superfamily
== UNRESOLVED
)
376 return 0; /* we don't know; assume not */
377 else if (addr
->superfamily
== UNIX
)
381 return sockaddr_is_loopback(addr
->ais
->ai_addr
);
385 START_STEP(addr
, step
);
386 assert(SOCKADDR_FAMILY(addr
, step
) == AF_INET
);
387 a
.s_addr
= htonl(addr
->addresses
[0]);
388 return ipv4_is_loopback(a
);
393 int sk_address_is_special_local(SockAddr addr
)
395 return addr
->superfamily
== UNIX
;
398 int sk_addrtype(SockAddr addr
)
402 START_STEP(addr
, step
);
403 family
= SOCKADDR_FAMILY(addr
, step
);
405 return (family
== AF_INET ? ADDRTYPE_IPV4
:
407 family
== AF_INET6 ? ADDRTYPE_IPV6
:
412 void sk_addrcopy(SockAddr addr
, char *buf
)
416 START_STEP(addr
, step
);
417 family
= SOCKADDR_FAMILY(addr
, step
);
420 if (family
== AF_INET
)
421 memcpy(buf
, &((struct sockaddr_in
*)step
.ai
->ai_addr
)->sin_addr
,
422 sizeof(struct in_addr
));
423 else if (family
== AF_INET6
)
424 memcpy(buf
, &((struct sockaddr_in6
*)step
.ai
->ai_addr
)->sin6_addr
,
425 sizeof(struct in6_addr
));
431 assert(family
== AF_INET
);
432 a
.s_addr
= htonl(addr
->addresses
[step
.curraddr
]);
433 memcpy(buf
, (char*) &a
.s_addr
, 4);
437 void sk_addr_free(SockAddr addr
)
439 if (--addr
->refcount
> 0)
442 if (addr
->ais
!= NULL
)
443 freeaddrinfo(addr
->ais
);
445 sfree(addr
->addresses
);
450 SockAddr
sk_addr_dup(SockAddr addr
)
456 static Plug
sk_tcp_plug(Socket sock
, Plug p
)
458 Actual_Socket s
= (Actual_Socket
) sock
;
465 static void sk_tcp_flush(Socket s
)
468 * We send data to the socket as soon as we can anyway,
469 * so we don't need to do anything here. :-)
473 static void sk_tcp_close(Socket s
);
474 static int sk_tcp_write(Socket s
, const char *data
, int len
);
475 static int sk_tcp_write_oob(Socket s
, const char *data
, int len
);
476 static void sk_tcp_write_eof(Socket s
);
477 static void sk_tcp_set_private_ptr(Socket s
, void *ptr
);
478 static void *sk_tcp_get_private_ptr(Socket s
);
479 static void sk_tcp_set_frozen(Socket s
, int is_frozen
);
480 static const char *sk_tcp_socket_error(Socket s
);
482 static struct socket_function_table tcp_fn_table
= {
489 sk_tcp_set_private_ptr
,
490 sk_tcp_get_private_ptr
,
495 Socket
sk_register(OSSocket sockfd
, Plug plug
)
500 * Create Socket structure.
502 ret
= snew(struct Socket_tag
);
503 ret
->fn
= &tcp_fn_table
;
506 bufchain_init(&ret
->output_data
);
507 ret
->writable
= 1; /* to start with */
508 ret
->sending_oob
= 0;
510 ret
->frozen_readable
= 0;
511 ret
->localhost_only
= 0; /* unused, but best init anyway */
512 ret
->pending_error
= 0;
513 ret
->oobpending
= FALSE
;
514 ret
->outgoingeof
= EOF_NO
;
515 ret
->incomingeof
= FALSE
;
517 ret
->parent
= ret
->child
= NULL
;
524 ret
->error
= strerror(errno
);
536 static int try_connect(Actual_Socket sock
)
539 union sockaddr_union u
;
540 const union sockaddr_union
*sa
;
543 int fl
, salen
, family
;
546 * Remove the socket from the tree before we overwrite its
547 * internal socket id, because that forms part of the tree's
548 * sorting criterion. We'll add it back before exiting this
549 * function, whether we changed anything or not.
551 del234(sktree
, sock
);
556 plug_log(sock
->plug
, 0, sock
->addr
, sock
->port
, NULL
, 0);
561 family
= SOCKADDR_FAMILY(sock
->addr
, sock
->step
);
562 assert(family
!= AF_UNSPEC
);
563 s
= socket(family
, SOCK_STREAM
, 0);
573 if (sock
->oobinline
) {
575 setsockopt(s
, SOL_SOCKET
, SO_OOBINLINE
, (void *) &b
, sizeof(b
));
580 setsockopt(s
, IPPROTO_TCP
, TCP_NODELAY
, (void *) &b
, sizeof(b
));
583 if (sock
->keepalive
) {
585 setsockopt(s
, SOL_SOCKET
, SO_KEEPALIVE
, (void *) &b
, sizeof(b
));
589 * Bind to local address.
592 localport
= 1023; /* count from 1023 downwards */
594 localport
= 0; /* just use port 0 (ie kernel picks) */
596 /* BSD IP stacks need sockaddr_in zeroed before filling in */
597 memset(&u
,'\0',sizeof(u
));
599 /* We don't try to bind to a local address for UNIX domain sockets. (Why
600 * do we bother doing the bind when localport == 0 anyway?) */
601 if (family
!= AF_UNIX
) {
602 /* Loop round trying to bind */
607 if (family
== AF_INET6
) {
608 /* XXX use getaddrinfo to get a local address? */
609 u
.sin6
.sin6_family
= AF_INET6
;
610 u
.sin6
.sin6_addr
= in6addr_any
;
611 u
.sin6
.sin6_port
= htons(localport
);
612 retcode
= bind(s
, &u
.sa
, sizeof(u
.sin6
));
616 assert(family
== AF_INET
);
617 u
.sin
.sin_family
= AF_INET
;
618 u
.sin
.sin_addr
.s_addr
= htonl(INADDR_ANY
);
619 u
.sin
.sin_port
= htons(localport
);
620 retcode
= bind(s
, &u
.sa
, sizeof(u
.sin
));
627 if (err
!= EADDRINUSE
) /* failed, for a bad reason */
632 break; /* we're only looping once */
635 break; /* we might have got to the end */
643 * Connect to remote address.
648 /* XXX would be better to have got getaddrinfo() to fill in the port. */
649 ((struct sockaddr_in
*)sock
->step
.ai
->ai_addr
)->sin_port
=
651 sa
= (const union sockaddr_union
*)sock
->step
.ai
->ai_addr
;
652 salen
= sock
->step
.ai
->ai_addrlen
;
655 ((struct sockaddr_in
*)sock
->step
.ai
->ai_addr
)->sin_port
=
657 sa
= (const union sockaddr_union
*)sock
->step
.ai
->ai_addr
;
658 salen
= sock
->step
.ai
->ai_addrlen
;
662 u
.sin
.sin_family
= AF_INET
;
663 u
.sin
.sin_addr
.s_addr
= htonl(sock
->addr
->addresses
[sock
->step
.curraddr
]);
664 u
.sin
.sin_port
= htons((short) sock
->port
);
666 salen
= sizeof u
.sin
;
670 assert(sock
->port
== 0); /* to catch confused people */
671 assert(strlen(sock
->addr
->hostname
) < sizeof u
.su
.sun_path
);
672 u
.su
.sun_family
= AF_UNIX
;
673 strcpy(u
.su
.sun_path
, sock
->addr
->hostname
);
679 assert(0 && "unknown address family");
680 exit(1); /* XXX: GCC doesn't understand assert() on some systems. */
683 fl
= fcntl(s
, F_GETFL
);
685 fcntl(s
, F_SETFL
, fl
| O_NONBLOCK
);
687 if ((connect(s
, &(sa
->sa
), salen
)) < 0) {
688 if ( errno
!= EINPROGRESS
) {
694 * If we _don't_ get EWOULDBLOCK, the connect has completed
695 * and we should set the socket as connected and writable.
706 * No matter what happened, put the socket back in the tree.
708 add234(sktree
, sock
);
711 plug_log(sock
->plug
, 1, sock
->addr
, sock
->port
, strerror(err
), err
);
715 Socket
sk_new(SockAddr addr
, int port
, int privport
, int oobinline
,
716 int nodelay
, int keepalive
, Plug plug
)
722 * Create Socket structure.
724 ret
= snew(struct Socket_tag
);
725 ret
->fn
= &tcp_fn_table
;
728 bufchain_init(&ret
->output_data
);
729 ret
->connected
= 0; /* to start with */
730 ret
->writable
= 0; /* to start with */
731 ret
->sending_oob
= 0;
733 ret
->frozen_readable
= 0;
734 ret
->localhost_only
= 0; /* unused, but best init anyway */
735 ret
->pending_error
= 0;
736 ret
->parent
= ret
->child
= NULL
;
737 ret
->oobpending
= FALSE
;
738 ret
->outgoingeof
= EOF_NO
;
739 ret
->incomingeof
= FALSE
;
742 START_STEP(ret
->addr
, ret
->step
);
744 ret
->oobinline
= oobinline
;
745 ret
->nodelay
= nodelay
;
746 ret
->keepalive
= keepalive
;
747 ret
->privport
= privport
;
752 err
= try_connect(ret
);
753 } while (err
&& sk_nextaddr(ret
->addr
, &ret
->step
));
756 ret
->error
= strerror(err
);
761 Socket
sk_newlistener(char *srcaddr
, int port
, Plug plug
, int local_host_only
, int orig_address_family
)
765 struct addrinfo hints
, *ai
;
768 union sockaddr_union u
;
769 union sockaddr_union
*addr
;
777 * Create Socket structure.
779 ret
= snew(struct Socket_tag
);
780 ret
->fn
= &tcp_fn_table
;
783 bufchain_init(&ret
->output_data
);
784 ret
->writable
= 0; /* to start with */
785 ret
->sending_oob
= 0;
787 ret
->frozen_readable
= 0;
788 ret
->localhost_only
= local_host_only
;
789 ret
->pending_error
= 0;
790 ret
->parent
= ret
->child
= NULL
;
791 ret
->oobpending
= FALSE
;
792 ret
->outgoingeof
= EOF_NO
;
793 ret
->incomingeof
= FALSE
;
798 * Translate address_family from platform-independent constants
799 * into local reality.
801 address_family
= (orig_address_family
== ADDRTYPE_IPV4 ? AF_INET
:
803 orig_address_family
== ADDRTYPE_IPV6 ? AF_INET6
:
808 /* Let's default to IPv6.
809 * If the stack doesn't support IPv6, we will fall back to IPv4. */
810 if (address_family
== AF_UNSPEC
) address_family
= AF_INET6
;
812 /* No other choice, default to IPv4 */
813 if (address_family
== AF_UNSPEC
) address_family
= AF_INET
;
819 s
= socket(address_family
, SOCK_STREAM
, 0);
822 /* If the host doesn't support IPv6 try fallback to IPv4. */
823 if (s
< 0 && address_family
== AF_INET6
) {
824 address_family
= AF_INET
;
825 s
= socket(address_family
, SOCK_STREAM
, 0);
830 ret
->error
= strerror(errno
);
838 setsockopt(s
, SOL_SOCKET
, SO_REUSEADDR
, (const char *)&on
, sizeof(on
));
841 addr
= NULL
; addrlen
= -1; /* placate optimiser */
843 if (srcaddr
!= NULL
) {
845 hints
.ai_flags
= AI_NUMERICHOST
;
846 hints
.ai_family
= address_family
;
847 hints
.ai_socktype
= SOCK_STREAM
;
848 hints
.ai_protocol
= 0;
849 hints
.ai_addrlen
= 0;
850 hints
.ai_addr
= NULL
;
851 hints
.ai_canonname
= NULL
;
852 hints
.ai_next
= NULL
;
853 assert(port
>= 0 && port
<= 99999);
854 sprintf(portstr
, "%d", port
);
855 retcode
= getaddrinfo(srcaddr
, portstr
, &hints
, &ai
);
857 addr
= (union sockaddr_union
*)ai
->ai_addr
;
858 addrlen
= ai
->ai_addrlen
;
861 memset(&u
,'\0',sizeof u
);
862 u
.sin
.sin_family
= AF_INET
;
863 u
.sin
.sin_port
= htons(port
);
864 u
.sin
.sin_addr
.s_addr
= inet_addr(srcaddr
);
865 if (u
.sin
.sin_addr
.s_addr
!= (in_addr_t
)(-1)) {
866 /* Override localhost_only with specified listen addr. */
867 ret
->localhost_only
= ipv4_is_loopback(u
.sin
.sin_addr
);
870 addrlen
= sizeof(u
.sin
);
876 memset(&u
,'\0',sizeof u
);
878 if (address_family
== AF_INET6
) {
879 u
.sin6
.sin6_family
= AF_INET6
;
880 u
.sin6
.sin6_port
= htons(port
);
882 u
.sin6
.sin6_addr
= in6addr_loopback
;
884 u
.sin6
.sin6_addr
= in6addr_any
;
886 addrlen
= sizeof(u
.sin6
);
890 u
.sin
.sin_family
= AF_INET
;
891 u
.sin
.sin_port
= htons(port
);
893 u
.sin
.sin_addr
.s_addr
= htonl(INADDR_LOOPBACK
);
895 u
.sin
.sin_addr
.s_addr
= htonl(INADDR_ANY
);
897 addrlen
= sizeof(u
.sin
);
901 retcode
= bind(s
, &addr
->sa
, addrlen
);
904 ret
->error
= strerror(errno
);
908 if (listen(s
, SOMAXCONN
) < 0) {
910 ret
->error
= strerror(errno
);
916 * If we were given ADDRTYPE_UNSPEC, we must also create an
917 * IPv4 listening socket and link it to this one.
919 if (address_family
== AF_INET6
&& orig_address_family
== ADDRTYPE_UNSPEC
) {
922 other
= (Actual_Socket
) sk_newlistener(srcaddr
, port
, plug
,
923 local_host_only
, ADDRTYPE_IPV4
);
930 /* If we couldn't create a listening socket on IPv4 as well
931 * as IPv6, we must return an error overall. */
934 return (Socket
) other
;
948 static void sk_tcp_close(Socket sock
)
950 Actual_Socket s
= (Actual_Socket
) sock
;
953 sk_tcp_close((Socket
)s
->child
);
959 sk_addr_free(s
->addr
);
963 void *sk_getxdmdata(void *sock
, int *lenp
)
965 Actual_Socket s
= (Actual_Socket
) sock
;
966 union sockaddr_union u
;
969 static unsigned int unix_addr
= 0xFFFFFFFF;
972 * We must check that this socket really _is_ an Actual_Socket.
974 if (s
->fn
!= &tcp_fn_table
)
975 return NULL
; /* failure */
978 if (getsockname(s
->s
, &u
.sa
, &addrlen
) < 0)
980 switch(u
.sa
.sa_family
) {
983 buf
= snewn(*lenp
, char);
984 PUT_32BIT_MSB_FIRST(buf
, ntohl(u
.sin
.sin_addr
.s_addr
));
985 PUT_16BIT_MSB_FIRST(buf
+4, ntohs(u
.sin
.sin_port
));
990 buf
= snewn(*lenp
, char);
991 if (IN6_IS_ADDR_V4MAPPED(&u
.sin6
.sin6_addr
)) {
992 memcpy(buf
, u
.sin6
.sin6_addr
.s6_addr
+ 12, 4);
993 PUT_16BIT_MSB_FIRST(buf
+4, ntohs(u
.sin6
.sin6_port
));
995 /* This is stupid, but it's what XLib does. */
1001 buf
= snewn(*lenp
, char);
1002 PUT_32BIT_MSB_FIRST(buf
, unix_addr
--);
1003 PUT_16BIT_MSB_FIRST(buf
+4, getpid());
1016 * The function which tries to send on a socket once it's deemed
1019 void try_send(Actual_Socket s
)
1021 while (s
->sending_oob
|| bufchain_size(&s
->output_data
) > 0) {
1025 int len
, urgentflag
;
1027 if (s
->sending_oob
) {
1028 urgentflag
= MSG_OOB
;
1029 len
= s
->sending_oob
;
1033 bufchain_prefix(&s
->output_data
, &data
, &len
);
1035 nsent
= send(s
->s
, data
, len
, urgentflag
);
1036 noise_ultralight(nsent
);
1038 err
= (nsent
< 0 ? errno
: 0);
1039 if (err
== EWOULDBLOCK
) {
1041 * Perfectly normal: we've sent all we can for the moment.
1043 s
->writable
= FALSE
;
1047 * We unfortunately can't just call plug_closing(),
1048 * because it's quite likely that we're currently
1049 * _in_ a call from the code we'd be calling back
1050 * to, so we'd have to make half the SSH code
1051 * reentrant. Instead we flag a pending error on
1052 * the socket, to be dealt with (by calling
1053 * plug_closing()) at some suitable future moment.
1055 s
->pending_error
= err
;
1057 * Immediately cease selecting on this socket, so that
1058 * we don't tight-loop repeatedly trying to do
1059 * whatever it was that went wrong.
1063 * Notify the front end that it might want to call us.
1065 frontend_net_error_pending();
1069 if (s
->sending_oob
) {
1071 memmove(s
->oobdata
, s
->oobdata
+nsent
, len
-nsent
);
1072 s
->sending_oob
= len
- nsent
;
1077 bufchain_consume(&s
->output_data
, nsent
);
1083 * If we reach here, we've finished sending everything we might
1084 * have needed to send. Send EOF, if we need to.
1086 if (s
->outgoingeof
== EOF_PENDING
) {
1087 shutdown(s
->s
, SHUT_WR
);
1088 s
->outgoingeof
= EOF_SENT
;
1092 * Also update the select status, because we don't need to select
1093 * for writing any more.
1098 static int sk_tcp_write(Socket sock
, const char *buf
, int len
)
1100 Actual_Socket s
= (Actual_Socket
) sock
;
1102 assert(s
->outgoingeof
== EOF_NO
);
1105 * Add the data to the buffer list on the socket.
1107 bufchain_add(&s
->output_data
, buf
, len
);
1110 * Now try sending from the start of the buffer list.
1116 * Update the select() status to correctly reflect whether or
1117 * not we should be selecting for write.
1121 return bufchain_size(&s
->output_data
);
1124 static int sk_tcp_write_oob(Socket sock
, const char *buf
, int len
)
1126 Actual_Socket s
= (Actual_Socket
) sock
;
1128 assert(s
->outgoingeof
== EOF_NO
);
1131 * Replace the buffer list on the socket with the data.
1133 bufchain_clear(&s
->output_data
);
1134 assert(len
<= sizeof(s
->oobdata
));
1135 memcpy(s
->oobdata
, buf
, len
);
1136 s
->sending_oob
= len
;
1139 * Now try sending from the start of the buffer list.
1145 * Update the select() status to correctly reflect whether or
1146 * not we should be selecting for write.
1150 return s
->sending_oob
;
1153 static void sk_tcp_write_eof(Socket sock
)
1155 Actual_Socket s
= (Actual_Socket
) sock
;
1157 assert(s
->outgoingeof
== EOF_NO
);
1160 * Mark the socket as pending outgoing EOF.
1162 s
->outgoingeof
= EOF_PENDING
;
1165 * Now try sending from the start of the buffer list.
1171 * Update the select() status to correctly reflect whether or
1172 * not we should be selecting for write.
1177 static int net_select_result(int fd
, int event
)
1180 char buf
[20480]; /* nice big buffer for plenty of speed */
1184 /* Find the Socket structure */
1185 s
= find234(sktree
, &fd
, cmpforsearch
);
1187 return 1; /* boggle */
1189 noise_ultralight(event
);
1192 case 4: /* exceptional */
1193 if (!s
->oobinline
) {
1195 * On a non-oobinline socket, this indicates that we
1196 * can immediately perform an OOB read and get back OOB
1197 * data, which we will send to the back end with
1198 * type==2 (urgent data).
1200 ret
= recv(s
->s
, buf
, sizeof(buf
), MSG_OOB
);
1201 noise_ultralight(ret
);
1203 return plug_closing(s
->plug
,
1204 ret
== 0 ?
"Internal networking trouble" :
1205 strerror(errno
), errno
, 0);
1208 * Receiving actual data on a socket means we can
1209 * stop falling back through the candidate
1210 * addresses to connect to.
1213 sk_addr_free(s
->addr
);
1216 return plug_receive(s
->plug
, 2, buf
, ret
);
1222 * If we reach here, this is an oobinline socket, which
1223 * means we should set s->oobpending and then deal with it
1224 * when we get called for the readability event (which
1225 * should also occur).
1227 s
->oobpending
= TRUE
;
1229 case 1: /* readable; also acceptance */
1232 * On a listening socket, the readability event means a
1233 * connection is ready to be accepted.
1235 union sockaddr_union su
;
1236 socklen_t addrlen
= sizeof(su
);
1237 int t
; /* socket of connection */
1240 memset(&su
, 0, addrlen
);
1241 t
= accept(s
->s
, &su
.sa
, &addrlen
);
1246 fl
= fcntl(t
, F_GETFL
);
1248 fcntl(t
, F_SETFL
, fl
| O_NONBLOCK
);
1250 if (s
->localhost_only
&&
1251 !sockaddr_is_loopback(&su
.sa
)) {
1252 close(t
); /* someone let nonlocal through?! */
1253 } else if (plug_accepting(s
->plug
, t
)) {
1254 close(t
); /* denied or error */
1260 * If we reach here, this is not a listening socket, so
1261 * readability really means readability.
1264 /* In the case the socket is still frozen, we don't even bother */
1266 s
->frozen_readable
= 1;
1271 * We have received data on the socket. For an oobinline
1272 * socket, this might be data _before_ an urgent pointer,
1273 * in which case we send it to the back end with type==1
1274 * (data prior to urgent).
1276 if (s
->oobinline
&& s
->oobpending
) {
1278 if (ioctl(s
->s
, SIOCATMARK
, &atmark
) == 0 && atmark
)
1279 s
->oobpending
= FALSE
; /* clear this indicator */
1283 ret
= recv(s
->s
, buf
, s
->oobpending ?
1 : sizeof(buf
), 0);
1284 noise_ultralight(ret
);
1286 if (errno
== EWOULDBLOCK
) {
1292 * An error at this point _might_ be an error reported
1293 * by a non-blocking connect(). So before we return a
1294 * panic status to the user, let's just see whether
1299 plug_log(s
->plug
, 1, s
->addr
, s
->port
, strerror(err
), err
);
1300 while (s
->addr
&& sk_nextaddr(s
->addr
, &s
->step
)) {
1301 err
= try_connect(s
);
1305 return plug_closing(s
->plug
, strerror(err
), err
, 0);
1306 } else if (0 == ret
) {
1307 s
->incomingeof
= TRUE
; /* stop trying to read now */
1309 return plug_closing(s
->plug
, NULL
, 0, 0);
1312 * Receiving actual data on a socket means we can
1313 * stop falling back through the candidate
1314 * addresses to connect to.
1317 sk_addr_free(s
->addr
);
1320 return plug_receive(s
->plug
, atmark ?
0 : 1, buf
, ret
);
1323 case 2: /* writable */
1324 if (!s
->connected
) {
1326 * select() reports a socket as _writable_ when an
1327 * asynchronous connection is completed.
1329 s
->connected
= s
->writable
= 1;
1333 int bufsize_before
, bufsize_after
;
1335 bufsize_before
= s
->sending_oob
+ bufchain_size(&s
->output_data
);
1337 bufsize_after
= s
->sending_oob
+ bufchain_size(&s
->output_data
);
1338 if (bufsize_after
< bufsize_before
)
1339 plug_sent(s
->plug
, bufsize_after
);
1348 * Deal with socket errors detected in try_send().
1350 void net_pending_errors(void)
1356 * This might be a fiddly business, because it's just possible
1357 * that handling a pending error on one socket might cause
1358 * others to be closed. (I can't think of any reason this might
1359 * happen in current SSH implementation, but to maintain
1360 * generality of this network layer I'll assume the worst.)
1362 * So what we'll do is search the socket list for _one_ socket
1363 * with a pending error, and then handle it, and then search
1364 * the list again _from the beginning_. Repeat until we make a
1365 * pass with no socket errors present. That way we are
1366 * protected against the socket list changing under our feet.
1370 for (i
= 0; (s
= index234(sktree
, i
)) != NULL
; i
++) {
1371 if (s
->pending_error
) {
1373 * An error has occurred on this socket. Pass it to the
1376 plug_closing(s
->plug
, strerror(s
->pending_error
),
1377 s
->pending_error
, 0);
1385 * Each socket abstraction contains a `void *' private field in
1386 * which the client can keep state.
1388 static void sk_tcp_set_private_ptr(Socket sock
, void *ptr
)
1390 Actual_Socket s
= (Actual_Socket
) sock
;
1391 s
->private_ptr
= ptr
;
1394 static void *sk_tcp_get_private_ptr(Socket sock
)
1396 Actual_Socket s
= (Actual_Socket
) sock
;
1397 return s
->private_ptr
;
1401 * Special error values are returned from sk_namelookup and sk_new
1402 * if there's a problem. These functions extract an error message,
1403 * or return NULL if there's no problem.
1405 const char *sk_addr_error(SockAddr addr
)
1409 static const char *sk_tcp_socket_error(Socket sock
)
1411 Actual_Socket s
= (Actual_Socket
) sock
;
1415 static void sk_tcp_set_frozen(Socket sock
, int is_frozen
)
1417 Actual_Socket s
= (Actual_Socket
) sock
;
1418 if (s
->frozen
== is_frozen
)
1420 s
->frozen
= is_frozen
;
1421 if (!is_frozen
&& s
->frozen_readable
) {
1423 recv(s
->s
, &c
, 1, MSG_PEEK
);
1425 s
->frozen_readable
= 0;
1429 static void uxsel_tell(Actual_Socket s
)
1432 if (!s
->pending_error
) {
1434 rwx
|= 1; /* read == accept */
1437 rwx
|= 2; /* write == connect */
1438 if (s
->connected
&& !s
->frozen
&& !s
->incomingeof
)
1439 rwx
|= 1 | 4; /* read, except */
1440 if (bufchain_size(&s
->output_data
))
1441 rwx
|= 2; /* write */
1444 uxsel_set(s
->s
, rwx
, net_select_result
);
1447 int net_service_lookup(char *service
)
1450 se
= getservbyname(service
, NULL
);
1452 return ntohs(se
->s_port
);
1457 char *get_hostname(void)
1460 char *hostname
= NULL
;
1463 hostname
= sresize(hostname
, len
, char);
1464 if ((gethostname(hostname
, len
) < 0) &&
1465 (errno
!= ENAMETOOLONG
)) {
1470 } while (strlen(hostname
) >= len
-1);
1474 SockAddr
platform_get_x11_unix_address(const char *sockpath
, int displaynum
)
1476 SockAddr ret
= snew(struct SockAddr_tag
);
1479 memset(ret
, 0, sizeof *ret
);
1480 ret
->superfamily
= UNIX
;
1482 * In special circumstances (notably Mac OS X Leopard), we'll
1483 * have been passed an explicit Unix socket path.
1486 n
= snprintf(ret
->hostname
, sizeof ret
->hostname
,
1489 n
= snprintf(ret
->hostname
, sizeof ret
->hostname
,
1490 "%s%d", X11_UNIX_PATH
, displaynum
);
1494 ret
->error
= "snprintf failed";
1495 else if (n
>= sizeof ret
->hostname
)
1496 ret
->error
= "X11 UNIX name too long";
1501 ret
->addresses
= NULL
;
1502 ret
->naddresses
= 0;