2 * OpenVPN -- An application to securely tunnel IP networks
3 * over a single TCP/UDP port, with support for SSL/TLS-based
4 * session authentication and key exchange,
5 * packet encryption, packet authentication, and
8 * Copyright (C) 2002-2010 OpenVPN Technologies, Inc. <sales@openvpn.net>
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License version 2
12 * as published by the Free Software Foundation.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License
20 * along with this program (see the file COPYING included with this
21 * distribution); if not, write to the Free Software Foundation, Inc.,
22 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
27 #elif defined(_MSC_VER)
28 #include "config-msvc.h"
47 const int proto_overhead
[] = { /* indexed by PROTO_x */
49 IPv4_UDP_HEADER_SIZE
, /* IPv4 */
52 IPv6_UDP_HEADER_SIZE
, /* IPv6 */
59 * Convert sockflags/getaddr_flags into getaddr_flags
62 sf2gaf(const unsigned int getaddr_flags
,
63 const unsigned int sockflags
)
65 if (sockflags
& SF_HOST_RANDOMIZE
)
67 return getaddr_flags
| GETADDR_RANDOMIZE
;
76 * Functions related to the translation of DNS names to IP addresses.
80 * Translate IP addr or hostname to in_addr_t.
81 * If resolve error, try again for
82 * resolve_retry_seconds seconds.
85 getaddr(unsigned int flags
,
87 int resolve_retry_seconds
,
89 volatile int *signal_received
)
93 status
= openvpn_getaddrinfo(flags
& ~GETADDR_HOST_ORDER
, hostname
, NULL
,
94 resolve_retry_seconds
, signal_received
, AF_INET
, &ai
);
102 ia
= ((struct sockaddr_in
*)ai
->ai_addr
)->sin_addr
;
104 return (flags
& GETADDR_HOST_ORDER
) ? ntohl(ia
.s_addr
) : ia
.s_addr
;
117 streqnull(const char *a
, const char *b
)
119 if (a
== NULL
&& b
== NULL
)
123 else if (a
== NULL
|| b
== NULL
)
134 * get_cached_dns_entry return 0 on success and -1
135 * otherwise. (like getaddrinfo)
138 get_cached_dns_entry(struct cached_dns_entry
*dns_cache
,
139 const char *hostname
,
140 const char *servname
,
143 struct addrinfo
**ai
)
145 struct cached_dns_entry
*ph
;
148 /* Only use flags that are relevant for the structure */
149 flags
= resolve_flags
& GETADDR_CACHE_MASK
;
151 for (ph
= dns_cache
; ph
; ph
= ph
->next
)
153 if (streqnull(ph
->hostname
, hostname
)
154 && streqnull(ph
->servname
, servname
)
155 && ph
->ai_family
== ai_family
156 && ph
->flags
== flags
)
167 do_preresolve_host(struct context
*c
,
168 const char *hostname
,
169 const char *servname
,
176 if (get_cached_dns_entry(c
->c1
.dns_cache
,
183 /* entry already cached, return success */
187 status
= openvpn_getaddrinfo(flags
, hostname
, servname
,
188 c
->options
.resolve_retry_seconds
, NULL
,
192 struct cached_dns_entry
*ph
;
194 ALLOC_OBJ_CLEAR_GC(ph
, struct cached_dns_entry
, &c
->gc
);
196 ph
->hostname
= hostname
;
197 ph
->servname
= servname
;
198 ph
->flags
= flags
& GETADDR_CACHE_MASK
;
200 if (!c
->c1
.dns_cache
)
202 c
->c1
.dns_cache
= ph
;
206 struct cached_dns_entry
*prev
= c
->c1
.dns_cache
;
212 gc_addspecial(ai
, &gc_freeaddrinfo_callback
, &c
->gc
);
219 do_preresolve(struct context
*c
)
222 struct connection_list
*l
= c
->options
.connection_list
;
223 const unsigned int preresolve_flags
= GETADDR_RESOLVE
224 |GETADDR_UPDATE_MANAGEMENT_STATE
225 |GETADDR_MENTION_RESOLVE_RETRY
229 for (i
= 0; i
< l
->len
; ++i
)
233 int flags
= preresolve_flags
;
235 struct connection_entry
*ce
= c
->options
.connection_list
->array
[i
];
237 if (proto_is_dgram(ce
->proto
))
239 flags
|= GETADDR_DATAGRAM
;
242 if (c
->options
.sockflags
& SF_HOST_RANDOMIZE
)
244 flags
|= GETADDR_RANDOMIZE
;
247 if (c
->options
.ip_remote_hint
)
249 remote
= c
->options
.ip_remote_hint
;
256 /* HTTP remote hostname does not need to be resolved */
257 if (!ce
->http_proxy_options
)
259 status
= do_preresolve_host(c
, remote
, ce
->remote_port
, ce
->af
, flags
);
266 /* Preresolve proxy */
267 if (ce
->http_proxy_options
)
269 status
= do_preresolve_host(c
,
270 ce
->http_proxy_options
->server
,
271 ce
->http_proxy_options
->port
,
281 if (ce
->socks_proxy_server
)
283 status
= do_preresolve_host(c
,
284 ce
->socks_proxy_server
,
285 ce
->socks_proxy_port
,
296 flags
|= GETADDR_PASSIVE
;
297 flags
&= ~GETADDR_RANDOMIZE
;
298 status
= do_preresolve_host(c
, ce
->local
, ce
->local_port
, ce
->af
, flags
);
310 throw_signal_soft(SIGHUP
, "Preresolving failed");
314 * Translate IPv4/IPv6 addr or hostname into struct addrinfo
315 * If resolve error, try again for resolve_retry_seconds seconds.
318 openvpn_getaddrinfo(unsigned int flags
,
319 const char *hostname
,
320 const char *servname
,
321 int resolve_retry_seconds
,
322 volatile int *signal_received
,
324 struct addrinfo
**res
)
326 struct addrinfo hints
;
329 int msglevel
= (flags
& GETADDR_FATAL
) ? M_FATAL
: D_RESOLVE_ERRORS
;
330 struct gc_arena gc
= gc_new();
331 const char *print_hostname
;
332 const char *print_servname
;
336 ASSERT(hostname
|| servname
);
337 ASSERT(!(flags
& GETADDR_HOST_ORDER
));
339 if (hostname
&& (flags
& GETADDR_RANDOMIZE
))
341 hostname
= hostname_randomize(hostname
, &gc
);
346 print_hostname
= hostname
;
350 print_hostname
= "undefined";
355 print_servname
= servname
;
362 if (flags
& GETADDR_MSG_VIRT_OUT
)
364 msglevel
|= M_MSG_VIRT_OUT
;
367 if ((flags
& (GETADDR_FATAL_ON_SIGNAL
|GETADDR_WARN_ON_SIGNAL
))
370 signal_received
= &sigrec
;
373 /* try numeric ipv6 addr first */
375 hints
.ai_family
= ai_family
;
376 hints
.ai_flags
= AI_NUMERICHOST
;
378 if (flags
& GETADDR_PASSIVE
)
380 hints
.ai_flags
|= AI_PASSIVE
;
383 if (flags
& GETADDR_DATAGRAM
)
385 hints
.ai_socktype
= SOCK_DGRAM
;
389 hints
.ai_socktype
= SOCK_STREAM
;
392 status
= getaddrinfo(hostname
, servname
, &hints
, res
);
394 if (status
!= 0) /* parse as numeric address failed? */
396 const int fail_wait_interval
= 5; /* seconds */
397 /* Add +4 to cause integer division rounding up (1 + 4) = 5, (0+4)/5=0 */
398 int resolve_retries
= (flags
& GETADDR_TRY_ONCE
) ? 1 :
399 ((resolve_retry_seconds
+ 4)/ fail_wait_interval
);
403 fmt
= "RESOLVE: Cannot resolve host address: %s:%s (%s)";
404 if ((flags
& GETADDR_MENTION_RESOLVE_RETRY
)
405 && !resolve_retry_seconds
)
407 fmt
= "RESOLVE: Cannot resolve host address: %s:%s (%s) (I would have retried this name query if you had specified the --resolv-retry option.)";
410 if (!(flags
& GETADDR_RESOLVE
) || status
== EAI_FAIL
)
412 msg(msglevel
, "RESOLVE: Cannot parse IP address: %s:%s (%s)",
413 print_hostname
,print_servname
, gai_strerror(status
));
417 #ifdef ENABLE_MANAGEMENT
418 if (flags
& GETADDR_UPDATE_MANAGEMENT_STATE
)
422 management_set_state(management
,
423 OPENVPN_STATE_RESOLVE
,
441 /* try hostname lookup */
442 hints
.ai_flags
&= ~AI_NUMERICHOST
;
443 dmsg(D_SOCKET_DEBUG
, "GETADDRINFO flags=0x%04x ai_family=%d ai_socktype=%d",
444 flags
, hints
.ai_family
, hints
.ai_socktype
);
445 status
= getaddrinfo(hostname
, servname
, &hints
, res
);
449 get_signal(signal_received
);
450 if (*signal_received
) /* were we interrupted by a signal? */
452 if (*signal_received
== SIGUSR1
) /* ignore SIGUSR1 */
454 msg(level
, "RESOLVE: Ignored SIGUSR1 signal received during DNS resolution attempt");
455 *signal_received
= 0;
459 /* turn success into failure (interrupted syscall) */
465 status
= EAI_AGAIN
; /* = temporary failure */
479 /* resolve lookup failed, should we
480 * continue or fail? */
482 if (resolve_retries
> 0)
484 level
= D_RESOLVE_ERRORS
;
491 gai_strerror(status
));
493 if (--resolve_retries
<= 0)
498 openvpn_sleep(fail_wait_interval
);
503 /* hostname resolve succeeded */
506 * Do not choose an IP Addresse by random or change the order *
507 * of IP addresses, doing so will break RFC 3484 address selection *
512 /* IP address parse succeeded */
516 if (signal_received
&& *signal_received
)
519 if (flags
& GETADDR_FATAL_ON_SIGNAL
)
523 else if (flags
& GETADDR_WARN_ON_SIGNAL
)
527 msg(level
, "RESOLVE: signal received during DNS resolution attempt");
535 * We do our own inet_aton because the glibc function
536 * isn't very good about error checking.
539 openvpn_inet_aton(const char *dotted_quad
, struct in_addr
*addr
)
541 unsigned int a
, b
, c
, d
;
544 if (sscanf(dotted_quad
, "%u.%u.%u.%u", &a
, &b
, &c
, &d
) == 4)
546 if (a
< 256 && b
< 256 && c
< 256 && d
< 256)
548 addr
->s_addr
= htonl(a
<<24 | b
<<16 | c
<<8 | d
);
549 return OIA_IP
; /* good dotted quad */
552 if (string_class(dotted_quad
, CC_DIGIT
|CC_DOT
, 0))
554 return OIA_ERROR
; /* probably a badly formatted dotted quad */
558 return OIA_HOSTNAME
; /* probably a hostname */
563 ip_addr_dotted_quad_safe(const char *dotted_quad
)
565 /* verify non-NULL */
571 /* verify length is within limits */
572 if (strlen(dotted_quad
) > 15)
577 /* verify that all chars are either numeric or '.' and that no numeric
578 * substring is greater than 3 chars */
581 const char *p
= dotted_quad
;
586 if (c
>= '0' && c
<= '9')
605 /* verify that string will convert to IP address */
608 return openvpn_inet_aton(dotted_quad
, &a
) == OIA_IP
;
613 ipv6_addr_safe(const char *ipv6_text_addr
)
615 /* verify non-NULL */
621 /* verify length is within limits */
622 if (strlen(ipv6_text_addr
) > INET6_ADDRSTRLEN
)
627 /* verify that string will convert to IPv6 address */
630 return inet_pton( AF_INET6
, ipv6_text_addr
, &a6
) == 1;
635 dns_addr_safe(const char *addr
)
639 const size_t len
= strlen(addr
);
640 return len
> 0 && len
<= 255 && string_class(addr
, CC_ALNUM
|CC_DASH
|CC_DOT
, 0);
649 ip_or_dns_addr_safe(const char *addr
, const bool allow_fqdn
)
651 if (ip_addr_dotted_quad_safe(addr
))
657 return dns_addr_safe(addr
);
666 mac_addr_safe(const char *mac_addr
)
668 /* verify non-NULL */
674 /* verify length is within limits */
675 if (strlen(mac_addr
) > 17)
680 /* verify that all chars are either alphanumeric or ':' and that no
681 * alphanumeric substring is greater than 2 chars */
684 const char *p
= mac_addr
;
689 if ( (c
>= '0' && c
<= '9') || (c
>= 'a' && c
<= 'f') || (c
>= 'A' && c
<= 'F') )
708 /* error-checking is left to script invoked in lladdr.c */
713 socket_get_sndbuf(int sd
)
715 #if defined(HAVE_GETSOCKOPT) && defined(SOL_SOCKET) && defined(SO_SNDBUF)
720 if (getsockopt(sd
, SOL_SOCKET
, SO_SNDBUF
, (void *) &val
, &len
) == 0
721 && len
== sizeof(val
))
730 socket_set_sndbuf(int sd
, int size
)
732 #if defined(HAVE_SETSOCKOPT) && defined(SOL_SOCKET) && defined(SO_SNDBUF)
733 if (setsockopt(sd
, SOL_SOCKET
, SO_SNDBUF
, (void *) &size
, sizeof(size
)) != 0)
735 msg(M_WARN
, "NOTE: setsockopt SO_SNDBUF=%d failed", size
);
741 socket_get_rcvbuf(int sd
)
743 #if defined(HAVE_GETSOCKOPT) && defined(SOL_SOCKET) && defined(SO_RCVBUF)
748 if (getsockopt(sd
, SOL_SOCKET
, SO_RCVBUF
, (void *) &val
, &len
) == 0
749 && len
== sizeof(val
))
758 socket_set_rcvbuf(int sd
, int size
)
760 #if defined(HAVE_SETSOCKOPT) && defined(SOL_SOCKET) && defined(SO_RCVBUF)
761 if (setsockopt(sd
, SOL_SOCKET
, SO_RCVBUF
, (void *) &size
, sizeof(size
)) != 0)
763 msg(M_WARN
, "NOTE: setsockopt SO_RCVBUF=%d failed", size
);
771 socket_set_buffers(int fd
, const struct socket_buffer_size
*sbs
)
775 const int sndbuf_old
= socket_get_sndbuf(fd
);
776 const int rcvbuf_old
= socket_get_rcvbuf(fd
);
780 socket_set_sndbuf(fd
, sbs
->sndbuf
);
785 socket_set_rcvbuf(fd
, sbs
->rcvbuf
);
788 msg(D_OSBUF
, "Socket Buffers: R=[%d->%d] S=[%d->%d]",
790 socket_get_rcvbuf(fd
),
792 socket_get_sndbuf(fd
));
797 * Set other socket options
801 socket_set_tcp_nodelay(int sd
, int state
)
803 #if defined(_WIN32) || (defined(HAVE_SETSOCKOPT) && defined(IPPROTO_TCP) && defined(TCP_NODELAY))
804 if (setsockopt(sd
, IPPROTO_TCP
, TCP_NODELAY
, (void *) &state
, sizeof(state
)) != 0)
806 msg(M_WARN
, "NOTE: setsockopt TCP_NODELAY=%d failed", state
);
811 dmsg(D_OSBUF
, "Socket flags: TCP_NODELAY=%d succeeded", state
);
814 #else /* if defined(_WIN32) || (defined(HAVE_SETSOCKOPT) && defined(IPPROTO_TCP) && defined(TCP_NODELAY)) */
815 msg(M_WARN
, "NOTE: setsockopt TCP_NODELAY=%d failed (No kernel support)", state
);
821 socket_set_mark(int sd
, int mark
)
823 #if defined(TARGET_LINUX) && HAVE_DECL_SO_MARK
824 if (mark
&& setsockopt(sd
, SOL_SOCKET
, SO_MARK
, (void *) &mark
, sizeof(mark
)) != 0)
826 msg(M_WARN
, "NOTE: setsockopt SO_MARK=%d failed", mark
);
832 socket_set_flags(int sd
, unsigned int sockflags
)
834 if (sockflags
& SF_TCP_NODELAY
)
836 return socket_set_tcp_nodelay(sd
, 1);
845 link_socket_update_flags(struct link_socket
*ls
, unsigned int sockflags
)
847 if (ls
&& socket_defined(ls
->sd
))
849 return socket_set_flags(ls
->sd
, ls
->sockflags
= sockflags
);
858 link_socket_update_buffer_sizes(struct link_socket
*ls
, int rcvbuf
, int sndbuf
)
860 if (ls
&& socket_defined(ls
->sd
))
862 ls
->socket_buffer_sizes
.sndbuf
= sndbuf
;
863 ls
->socket_buffer_sizes
.rcvbuf
= rcvbuf
;
864 socket_set_buffers(ls
->sd
, &ls
->socket_buffer_sizes
);
869 * SOCKET INITALIZATION CODE.
870 * Create a TCP/UDP socket
874 create_socket_tcp(struct addrinfo
*addrinfo
)
876 socket_descriptor_t sd
;
879 ASSERT(addrinfo
->ai_socktype
== SOCK_STREAM
);
881 if ((sd
= socket(addrinfo
->ai_family
, addrinfo
->ai_socktype
, addrinfo
->ai_protocol
)) < 0)
883 msg(M_ERR
, "Cannot create TCP socket");
886 #ifndef _WIN32 /* using SO_REUSEADDR on Windows will cause bind to succeed on port conflicts! */
887 /* set SO_REUSEADDR on socket */
890 if (setsockopt(sd
, SOL_SOCKET
, SO_REUSEADDR
,
891 (void *) &on
, sizeof(on
)) < 0)
893 msg(M_ERR
, "TCP: Cannot setsockopt SO_REUSEADDR on TCP socket");
898 /* set socket file descriptor to not pass across execs, so that
899 * scripts don't have access to it */
905 static socket_descriptor_t
906 create_socket_udp(struct addrinfo
*addrinfo
, const unsigned int flags
)
908 socket_descriptor_t sd
;
911 ASSERT(addrinfo
->ai_socktype
== SOCK_DGRAM
);
913 if ((sd
= socket(addrinfo
->ai_family
, addrinfo
->ai_socktype
, addrinfo
->ai_protocol
)) < 0)
915 msg(M_ERR
, "UDP: Cannot create UDP/UDP6 socket");
917 #if ENABLE_IP_PKTINFO
918 else if (flags
& SF_USE_IP_PKTINFO
)
921 if (addrinfo
->ai_family
== AF_INET
)
923 #if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST)
924 if (setsockopt(sd
, SOL_IP
, IP_PKTINFO
,
925 (void *)&pad
, sizeof(pad
)) < 0)
927 msg(M_ERR
, "UDP: failed setsockopt for IP_PKTINFO");
929 #elif defined(IP_RECVDSTADDR)
930 if (setsockopt(sd
, IPPROTO_IP
, IP_RECVDSTADDR
,
931 (void *)&pad
, sizeof(pad
)) < 0)
933 msg(M_ERR
, "UDP: failed setsockopt for IP_RECVDSTADDR");
935 #else /* if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST) */
936 #error ENABLE_IP_PKTINFO is set without IP_PKTINFO xor IP_RECVDSTADDR (fix syshead.h)
939 else if (addrinfo
->ai_family
== AF_INET6
)
941 #ifndef IPV6_RECVPKTINFO /* Some older Darwin platforms require this */
942 if (setsockopt(sd
, IPPROTO_IPV6
, IPV6_PKTINFO
,
943 (void *)&pad
, sizeof(pad
)) < 0)
945 if (setsockopt(sd
, IPPROTO_IPV6
, IPV6_RECVPKTINFO
,
946 (void *)&pad
, sizeof(pad
)) < 0)
948 { msg(M_ERR
, "UDP: failed setsockopt for IPV6_RECVPKTINFO");}
951 #endif /* if ENABLE_IP_PKTINFO */
953 /* set socket file descriptor to not pass across execs, so that
954 * scripts don't have access to it */
961 bind_local(struct link_socket
*sock
, const sa_family_t ai_family
)
963 /* bind to local address/port */
964 if (sock
->bind_local
)
966 if (sock
->socks_proxy
&& sock
->info
.proto
== PROTO_UDP
)
968 socket_bind(sock
->ctrl_sd
, sock
->info
.lsa
->bind_local
,
969 ai_family
, "SOCKS", false);
973 socket_bind(sock
->sd
, sock
->info
.lsa
->bind_local
,
975 "TCP/UDP", sock
->info
.bind_ipv6_only
);
981 create_socket(struct link_socket
*sock
, struct addrinfo
*addr
)
983 if (addr
->ai_protocol
== IPPROTO_UDP
|| addr
->ai_socktype
== SOCK_DGRAM
)
985 sock
->sd
= create_socket_udp(addr
, sock
->sockflags
);
986 sock
->sockflags
|= SF_GETADDRINFO_DGRAM
;
988 /* Assume that control socket and data socket to the socks proxy
989 * are using the same IP family */
990 if (sock
->socks_proxy
)
992 /* Construct a temporary addrinfo to create the socket,
993 * currently resolve two remote addresses is not supported,
994 * TODO: Rewrite the whole resolve_remote */
995 struct addrinfo addrinfo_tmp
= *addr
;
996 addrinfo_tmp
.ai_socktype
= SOCK_STREAM
;
997 addrinfo_tmp
.ai_protocol
= IPPROTO_TCP
;
998 sock
->ctrl_sd
= create_socket_tcp(&addrinfo_tmp
);
1001 else if (addr
->ai_protocol
== IPPROTO_TCP
|| addr
->ai_socktype
== SOCK_STREAM
)
1003 sock
->sd
= create_socket_tcp(addr
);
1009 /* set socket buffers based on --sndbuf and --rcvbuf options */
1010 socket_set_buffers(sock
->sd
, &sock
->socket_buffer_sizes
);
1012 /* set socket to --mark packets with given value */
1013 socket_set_mark(sock
->sd
, sock
->mark
);
1015 bind_local(sock
, addr
->ai_family
);
1018 #ifdef TARGET_ANDROID
1020 protect_fd_nonlocal(int fd
, const struct sockaddr
*addr
)
1022 /* pass socket FD to management interface to pass on to VPNService API
1023 * as "protected socket" (exempt from being routed into tunnel)
1025 if (addr_local(addr
))
1027 msg(D_SOCKET_DEBUG
, "Address is local, not protecting socket fd %d", fd
);
1031 msg(D_SOCKET_DEBUG
, "Protecting socket fd %d", fd
);
1032 management
->connection
.fdtosend
= fd
;
1033 management_android_control(management
, "PROTECTFD", __func__
);
1038 * Functions used for establishing a TCP stream connection.
1041 socket_do_listen(socket_descriptor_t sd
,
1042 const struct addrinfo
*local
,
1044 bool do_set_nonblock
)
1046 struct gc_arena gc
= gc_new();
1050 msg(M_INFO
, "Listening for incoming TCP connection on %s",
1051 print_sockaddr(local
->ai_addr
, &gc
));
1054 msg(M_ERR
, "TCP: listen() failed");
1058 /* set socket to non-blocking mode */
1059 if (do_set_nonblock
)
1068 socket_do_accept(socket_descriptor_t sd
,
1069 struct link_socket_actual
*act
,
1072 /* af_addr_size WILL return 0 in this case if AFs other than AF_INET
1073 * are compiled because act is empty here.
1074 * could use getsockname() to support later remote_len check
1076 socklen_t remote_len_af
= af_addr_size(act
->dest
.addr
.sa
.sa_family
);
1077 socklen_t remote_len
= sizeof(act
->dest
.addr
);
1078 socket_descriptor_t new_sd
= SOCKET_UNDEFINED
;
1082 #ifdef HAVE_GETPEERNAME
1085 new_sd
= getpeername(sd
, &act
->dest
.addr
.sa
, &remote_len
);
1087 if (!socket_defined(new_sd
))
1089 msg(D_LINK_ERRORS
| M_ERRNO
, "TCP: getpeername() failed");
1096 #else /* ifdef HAVE_GETPEERNAME */
1099 msg(M_WARN
, "TCP: this OS does not provide the getpeername() function");
1104 new_sd
= accept(sd
, &act
->dest
.addr
.sa
, &remote_len
);
1107 #if 0 /* For debugging only, test the effect of accept() failures */
1118 if (!socket_defined(new_sd
))
1120 msg(D_LINK_ERRORS
| M_ERRNO
, "TCP: accept(%d) failed", sd
);
1122 /* only valid if we have remote_len_af!=0 */
1123 else if (remote_len_af
&& remote_len
!= remote_len_af
)
1125 msg(D_LINK_ERRORS
, "TCP: Received strange incoming connection with unknown address length=%d", remote_len
);
1126 openvpn_close_socket(new_sd
);
1127 new_sd
= SOCKET_UNDEFINED
;
1131 /* set socket file descriptor to not pass across execs, so that
1132 * scripts don't have access to it */
1139 tcp_connection_established(const struct link_socket_actual
*act
)
1141 struct gc_arena gc
= gc_new();
1142 msg(M_INFO
, "TCP connection established with %s",
1143 print_link_socket_actual(act
, &gc
));
1148 socket_listen_accept(socket_descriptor_t sd
,
1149 struct link_socket_actual
*act
,
1150 const char *remote_dynamic
,
1151 const struct addrinfo
*local
,
1154 volatile int *signal_received
)
1156 struct gc_arena gc
= gc_new();
1157 /* struct openvpn_sockaddr *remote = &act->dest; */
1158 struct openvpn_sockaddr remote_verify
= act
->dest
;
1159 int new_sd
= SOCKET_UNDEFINED
;
1162 socket_do_listen(sd
, local
, do_listen
, true);
1171 openvpn_fd_set(sd
, &reads
);
1175 status
= select(sd
+ 1, &reads
, NULL
, NULL
, &tv
);
1177 get_signal(signal_received
);
1178 if (*signal_received
)
1186 msg(D_LINK_ERRORS
| M_ERRNO
, "TCP: select() failed");
1195 new_sd
= socket_do_accept(sd
, act
, nowait
);
1197 if (socket_defined(new_sd
))
1199 struct addrinfo
*ai
= NULL
;
1202 openvpn_getaddrinfo(0, remote_dynamic
, NULL
, 1, NULL
,
1203 remote_verify
.addr
.sa
.sa_family
, &ai
);
1206 if (ai
&& !addrlist_match(&remote_verify
, ai
))
1209 "TCP NOTE: Rejected connection attempt from %s due to --remote setting",
1210 print_link_socket_actual(act
, &gc
));
1211 if (openvpn_close_socket(new_sd
))
1213 msg(M_ERR
, "TCP: close socket failed (new_sd)");
1229 if (!nowait
&& openvpn_close_socket(sd
))
1231 msg(M_ERR
, "TCP: close socket failed (sd)");
1234 tcp_connection_established(act
);
1240 /* older mingw versions and WinXP do not have this define,
1241 * but Vista and up support the functionality - just define it here
1245 #define IPV6_V6ONLY 27
1249 socket_bind(socket_descriptor_t sd
,
1250 struct addrinfo
*local
,
1255 struct gc_arena gc
= gc_new();
1258 * getaddrinfo for the bind address might return multiple AF_INET/AF_INET6
1259 * entries for the requested protocol.
1260 * For example if an address has multiple A records
1261 * What is the correct way to deal with it?
1264 struct addrinfo
*cur
;
1269 /* find the first addrinfo with correct ai_family */
1270 for (cur
= local
; cur
; cur
= cur
->ai_next
)
1272 if (cur
->ai_family
== ai_family
)
1279 msg(M_FATAL
, "%s: Socket bind failed: Addr to bind has no %s record",
1280 prefix
, addr_family_name(ai_family
));
1283 if (ai_family
== AF_INET6
)
1285 int v6only
= ipv6only
? 1 : 0; /* setsockopt must have an "int" */
1287 msg(M_INFO
, "setsockopt(IPV6_V6ONLY=%d)", v6only
);
1288 if (setsockopt(sd
, IPPROTO_IPV6
, IPV6_V6ONLY
, (void *) &v6only
, sizeof(v6only
)))
1290 msg(M_NONFATAL
|M_ERRNO
, "Setting IPV6_V6ONLY=%d failed", v6only
);
1293 if (bind(sd
, cur
->ai_addr
, cur
->ai_addrlen
))
1295 const int errnum
= openvpn_errno();
1296 msg(M_FATAL
, "%s: Socket bind failed on local address %s: %s",
1298 print_sockaddr_ex(local
->ai_addr
, ":", PS_SHOW_PORT
, &gc
),
1299 strerror_ts(errnum
, &gc
));
1305 openvpn_connect(socket_descriptor_t sd
,
1306 const struct sockaddr
*remote
,
1307 int connect_timeout
,
1308 volatile int *signal_received
)
1312 #ifdef TARGET_ANDROID
1313 protect_fd_nonlocal(sd
, remote
);
1316 #ifdef CONNECT_NONBLOCK
1318 status
= connect(sd
, remote
, af_addr_size(remote
->sa_family
));
1321 status
= openvpn_errno();
1325 status
== WSAEWOULDBLOCK
1327 status
== EINPROGRESS
1334 struct pollfd fds
[1];
1336 fds
[0].events
= POLLOUT
;
1337 status
= poll(fds
, 1, 0);
1343 openvpn_fd_set(sd
, &writes
);
1347 status
= select(sd
+ 1, NULL
, &writes
, NULL
, &tv
);
1349 if (signal_received
)
1351 get_signal(signal_received
);
1352 if (*signal_received
)
1360 status
= openvpn_errno();
1365 if (--connect_timeout
< 0)
1368 status
= WSAETIMEDOUT
;
1384 if (getsockopt(sd
, SOL_SOCKET
, SO_ERROR
, (void *) &val
, &len
) == 0
1385 && len
== sizeof(val
))
1391 status
= openvpn_errno();
1397 #else /* ifdef CONNECT_NONBLOCK */
1398 status
= connect(sd
, remote
, af_addr_size(remote
->sa_family
));
1401 status
= openvpn_errno();
1403 #endif /* ifdef CONNECT_NONBLOCK */
1409 set_actual_address(struct link_socket_actual
*actual
, struct addrinfo
*ai
)
1414 if (ai
->ai_family
== AF_INET
)
1416 actual
->dest
.addr
.in4
=
1417 *((struct sockaddr_in
*) ai
->ai_addr
);
1419 else if (ai
->ai_family
== AF_INET6
)
1421 actual
->dest
.addr
.in6
=
1422 *((struct sockaddr_in6
*) ai
->ai_addr
);
1432 socket_connect(socket_descriptor_t
*sd
,
1433 const struct sockaddr
*dest
,
1434 const int connect_timeout
,
1435 struct signal_info
*sig_info
)
1437 struct gc_arena gc
= gc_new();
1440 #ifdef CONNECT_NONBLOCK
1441 msg(M_INFO
, "Attempting to establish TCP connection with %s [nonblock]",
1442 print_sockaddr(dest
, &gc
));
1444 msg(M_INFO
, "Attempting to establish TCP connection with %s",
1445 print_sockaddr(dest
, &gc
));
1448 #ifdef ENABLE_MANAGEMENT
1451 management_set_state(management
,
1452 OPENVPN_STATE_TCP_CONNECT
,
1461 /* Set the actual address */
1462 status
= openvpn_connect(*sd
, dest
, connect_timeout
, &sig_info
->signal_received
);
1464 get_signal(&sig_info
->signal_received
);
1465 if (sig_info
->signal_received
)
1474 "TCP: connect to %s failed: %s",
1475 print_sockaddr(dest
, &gc
),
1476 strerror_ts(status
, &gc
));
1478 openvpn_close_socket(*sd
);
1479 *sd
= SOCKET_UNDEFINED
;
1480 sig_info
->signal_received
= SIGUSR1
;
1481 sig_info
->source
= SIG_SOURCE_CONNECTION_FAILED
;
1485 msg(M_INFO
, "TCP connection established with %s",
1486 print_sockaddr(dest
, &gc
));
1493 /* For stream protocols, allocate a buffer to build up packet.
1494 * Called after frame has been finalized. */
1497 socket_frame_init(const struct frame
*frame
, struct link_socket
*sock
)
1500 overlapped_io_init(&sock
->reads
, frame
, FALSE
, false);
1501 overlapped_io_init(&sock
->writes
, frame
, TRUE
, false);
1502 sock
->rw_handle
.read
= sock
->reads
.overlapped
.hEvent
;
1503 sock
->rw_handle
.write
= sock
->writes
.overlapped
.hEvent
;
1506 if (link_socket_connection_oriented(sock
))
1509 stream_buf_init(&sock
->stream_buf
,
1510 &sock
->reads
.buf_init
,
1514 alloc_buf_sock_tun(&sock
->stream_buf_data
,
1517 FRAME_HEADROOM_MARKER_READ_STREAM
);
1519 stream_buf_init(&sock
->stream_buf
,
1520 &sock
->stream_buf_data
,
1528 * Adjust frame structure based on a Path MTU value given
1532 frame_adjust_path_mtu(struct frame
*frame
, int pmtu
, int proto
)
1534 frame_set_mtu_dynamic(frame
, pmtu
- datagram_overhead(proto
), SET_MTU_UPPER_BOUND
);
1538 resolve_bind_local(struct link_socket
*sock
, const sa_family_t af
)
1540 struct gc_arena gc
= gc_new();
1542 /* resolve local address if undefined */
1543 if (!sock
->info
.lsa
->bind_local
)
1545 int flags
= GETADDR_RESOLVE
| GETADDR_WARN_ON_SIGNAL
1546 |GETADDR_FATAL
| GETADDR_PASSIVE
;
1549 if (proto_is_dgram(sock
->info
.proto
))
1551 flags
|= GETADDR_DATAGRAM
;
1554 /* will return AF_{INET|INET6}from local_host */
1555 status
= get_cached_dns_entry(sock
->dns_cache
,
1560 &sock
->info
.lsa
->bind_local
);
1564 status
= openvpn_getaddrinfo(flags
, sock
->local_host
, sock
->local_port
, 0,
1565 NULL
, af
, &sock
->info
.lsa
->bind_local
);
1570 msg(M_FATAL
, "getaddrinfo() failed for local \"%s:%s\": %s",
1571 sock
->local_host
, sock
->local_port
,
1572 gai_strerror(status
));
1580 resolve_remote(struct link_socket
*sock
,
1582 const char **remote_dynamic
,
1583 volatile int *signal_received
)
1585 struct gc_arena gc
= gc_new();
1587 /* resolve remote address if undefined */
1588 if (!sock
->info
.lsa
->remote_list
)
1590 if (sock
->remote_host
)
1592 unsigned int flags
= sf2gaf(GETADDR_RESOLVE
|GETADDR_UPDATE_MANAGEMENT_STATE
, sock
->sockflags
);
1595 struct addrinfo
*ai
;
1596 if (proto_is_dgram(sock
->info
.proto
))
1598 flags
|= GETADDR_DATAGRAM
;
1601 if (sock
->resolve_retry_seconds
== RESOLV_RETRY_INFINITE
)
1605 flags
|= (GETADDR_TRY_ONCE
| GETADDR_FATAL
);
1609 else if (phase
== 1)
1611 if (sock
->resolve_retry_seconds
)
1617 flags
|= (GETADDR_FATAL
| GETADDR_MENTION_RESOLVE_RETRY
);
1621 else if (phase
== 2)
1623 if (sock
->resolve_retry_seconds
)
1625 flags
|= GETADDR_FATAL
;
1626 retry
= sock
->resolve_retry_seconds
;
1639 status
= get_cached_dns_entry(sock
->dns_cache
,
1646 status
= openvpn_getaddrinfo(flags
, sock
->remote_host
, sock
->remote_port
,
1647 retry
, signal_received
, sock
->info
.af
, &ai
);
1652 sock
->info
.lsa
->remote_list
= ai
;
1653 sock
->info
.lsa
->current_remote
= ai
;
1655 dmsg(D_SOCKET_DEBUG
, "RESOLVE_REMOTE flags=0x%04x phase=%d rrs=%d sig=%d status=%d",
1659 signal_received
? *signal_received
: -1,
1662 if (signal_received
)
1664 if (*signal_received
)
1671 if (signal_received
)
1673 *signal_received
= SIGUSR1
;
1680 /* should we re-use previous active remote address? */
1681 if (link_socket_actual_defined(&sock
->info
.lsa
->actual
))
1683 msg(M_INFO
, "TCP/UDP: Preserving recently used remote address: %s",
1684 print_link_socket_actual(&sock
->info
.lsa
->actual
, &gc
));
1687 *remote_dynamic
= NULL
;
1692 CLEAR(sock
->info
.lsa
->actual
);
1693 if (sock
->info
.lsa
->current_remote
)
1695 set_actual_address(&sock
->info
.lsa
->actual
,
1696 sock
->info
.lsa
->current_remote
);
1706 struct link_socket
*
1707 link_socket_new(void)
1709 struct link_socket
*sock
;
1711 ALLOC_OBJ_CLEAR(sock
, struct link_socket
);
1712 sock
->sd
= SOCKET_UNDEFINED
;
1713 sock
->ctrl_sd
= SOCKET_UNDEFINED
;
1718 link_socket_init_phase1(struct link_socket
*sock
,
1719 const char *local_host
,
1720 const char *local_port
,
1721 const char *remote_host
,
1722 const char *remote_port
,
1723 struct cached_dns_entry
*dns_cache
,
1726 bool bind_ipv6_only
,
1728 const struct link_socket
*accept_from
,
1729 struct http_proxy_info
*http_proxy
,
1730 struct socks_proxy_info
*socks_proxy
,
1737 struct link_socket_addr
*lsa
,
1738 const char *ipchange_command
,
1739 const struct plugin_list
*plugins
,
1740 int resolve_retry_seconds
,
1741 int mtu_discover_type
,
1745 struct event_timeout
*server_poll_timeout
,
1746 unsigned int sockflags
)
1750 sock
->local_host
= local_host
;
1751 sock
->local_port
= local_port
;
1752 sock
->remote_host
= remote_host
;
1753 sock
->remote_port
= remote_port
;
1754 sock
->dns_cache
= dns_cache
;
1755 sock
->http_proxy
= http_proxy
;
1756 sock
->socks_proxy
= socks_proxy
;
1757 sock
->bind_local
= bind_local
;
1758 sock
->inetd
= inetd
;
1759 sock
->resolve_retry_seconds
= resolve_retry_seconds
;
1760 sock
->mtu_discover_type
= mtu_discover_type
;
1763 sock
->gremlin
= gremlin
;
1766 sock
->socket_buffer_sizes
.rcvbuf
= rcvbuf
;
1767 sock
->socket_buffer_sizes
.sndbuf
= sndbuf
;
1769 sock
->sockflags
= sockflags
;
1772 sock
->info
.proto
= proto
;
1774 sock
->info
.remote_float
= remote_float
;
1775 sock
->info
.lsa
= lsa
;
1776 sock
->info
.bind_ipv6_only
= bind_ipv6_only
;
1777 sock
->info
.ipchange_command
= ipchange_command
;
1778 sock
->info
.plugins
= plugins
;
1779 sock
->server_poll_timeout
= server_poll_timeout
;
1782 if (mode
== LS_MODE_TCP_ACCEPT_FROM
)
1784 ASSERT(accept_from
);
1785 ASSERT(sock
->info
.proto
== PROTO_TCP_SERVER
);
1786 ASSERT(!sock
->inetd
);
1787 sock
->sd
= accept_from
->sd
;
1790 /* are we running in HTTP proxy mode? */
1791 if (sock
->http_proxy
)
1793 ASSERT(sock
->info
.proto
== PROTO_TCP_CLIENT
);
1794 ASSERT(!sock
->inetd
);
1796 /* the proxy server */
1797 sock
->remote_host
= http_proxy
->options
.server
;
1798 sock
->remote_port
= http_proxy
->options
.port
;
1800 /* the OpenVPN server we will use the proxy to connect to */
1801 sock
->proxy_dest_host
= remote_host
;
1802 sock
->proxy_dest_port
= remote_port
;
1804 /* or in Socks proxy mode? */
1805 else if (sock
->socks_proxy
)
1807 ASSERT(!sock
->inetd
);
1809 /* the proxy server */
1810 sock
->remote_host
= socks_proxy
->server
;
1811 sock
->remote_port
= socks_proxy
->port
;
1813 /* the OpenVPN server we will use the proxy to connect to */
1814 sock
->proxy_dest_host
= remote_host
;
1815 sock
->proxy_dest_port
= remote_port
;
1819 sock
->remote_host
= remote_host
;
1820 sock
->remote_port
= remote_port
;
1823 /* bind behavior for TCP server vs. client */
1824 if (sock
->info
.proto
== PROTO_TCP_SERVER
)
1826 if (sock
->mode
== LS_MODE_TCP_ACCEPT_FROM
)
1828 sock
->bind_local
= false;
1832 sock
->bind_local
= true;
1836 /* were we started by inetd or xinetd? */
1839 ASSERT(sock
->info
.proto
!= PROTO_TCP_CLIENT
);
1840 ASSERT(socket_defined(inetd_socket_descriptor
));
1841 sock
->sd
= inetd_socket_descriptor
;
1842 set_cloexec(sock
->sd
); /* not created by create_socket*() */
1844 else if (mode
!= LS_MODE_TCP_ACCEPT_FROM
)
1846 if (sock
->bind_local
)
1848 resolve_bind_local(sock
, sock
->info
.af
);
1850 resolve_remote(sock
, 1, NULL
, NULL
);
1856 phase2_inetd(struct link_socket
*sock
, const struct frame
*frame
,
1857 const char *remote_dynamic
, volatile int *signal_received
)
1859 bool remote_changed
= false;
1861 if (sock
->info
.proto
== PROTO_TCP_SERVER
)
1863 /* AF_INET as default (and fallback) for inetd */
1864 sock
->info
.lsa
->actual
.dest
.addr
.sa
.sa_family
= AF_INET
;
1865 #ifdef HAVE_GETSOCKNAME
1867 /* inetd: hint family type for dest = local's */
1868 struct openvpn_sockaddr local_addr
;
1869 socklen_t addrlen
= sizeof(local_addr
);
1870 if (getsockname(sock
->sd
, &local_addr
.addr
.sa
, &addrlen
) == 0)
1872 sock
->info
.lsa
->actual
.dest
.addr
.sa
.sa_family
= local_addr
.addr
.sa
.sa_family
;
1873 dmsg(D_SOCKET_DEBUG
, "inetd(%s): using sa_family=%d from getsockname(%d)",
1874 proto2ascii(sock
->info
.proto
, sock
->info
.af
, false),
1875 local_addr
.addr
.sa
.sa_family
, sock
->sd
);
1879 msg(M_WARN
, "inetd(%s): getsockname(%d) failed, using AF_INET",
1880 proto2ascii(sock
->info
.proto
, sock
->info
.af
, false), sock
->sd
);
1883 #else /* ifdef HAVE_GETSOCKNAME */
1884 msg(M_WARN
, "inetd(%s): this OS does not provide the getsockname() "
1885 "function, using AF_INET",
1886 proto2ascii(sock
->info
.proto
, false));
1887 #endif /* ifdef HAVE_GETSOCKNAME */
1889 socket_listen_accept(sock
->sd
,
1890 &sock
->info
.lsa
->actual
,
1892 sock
->info
.lsa
->bind_local
,
1894 sock
->inetd
== INETD_NOWAIT
,
1898 ASSERT(!remote_changed
);
1902 phase2_set_socket_flags(struct link_socket
*sock
)
1904 /* set misc socket parameters */
1905 socket_set_flags(sock
->sd
, sock
->sockflags
);
1907 /* set socket to non-blocking mode */
1908 set_nonblock(sock
->sd
);
1910 /* set Path MTU discovery options on the socket */
1911 set_mtu_discover_type(sock
->sd
, sock
->mtu_discover_type
, sock
->info
.af
);
1913 #if EXTENDED_SOCKET_ERROR_CAPABILITY
1914 /* if the OS supports it, enable extended error passing on the socket */
1915 set_sock_extended_error_passing(sock
->sd
);
1921 linksock_print_addr(struct link_socket
*sock
)
1923 struct gc_arena gc
= gc_new();
1924 const int msglevel
= (sock
->mode
== LS_MODE_TCP_ACCEPT_FROM
) ? D_INIT_MEDIUM
: M_INFO
;
1926 /* print local address */
1929 msg(msglevel
, "%s link local: [inetd]", proto2ascii(sock
->info
.proto
, sock
->info
.af
, true));
1931 else if (sock
->bind_local
)
1933 sa_family_t ai_family
= sock
->info
.lsa
->actual
.dest
.addr
.sa
.sa_family
;
1934 /* Socket is always bound on the first matching address,
1935 * For bound sockets with no remote addr this is the element of
1937 struct addrinfo
*cur
;
1938 for (cur
= sock
->info
.lsa
->bind_local
; cur
; cur
= cur
->ai_next
)
1940 if (!ai_family
|| ai_family
== cur
->ai_family
)
1946 msg(msglevel
, "%s link local (bound): %s",
1947 proto2ascii(sock
->info
.proto
, sock
->info
.af
, true),
1948 print_sockaddr(cur
->ai_addr
,&gc
));
1952 msg(msglevel
, "%s link local: (not bound)",
1953 proto2ascii(sock
->info
.proto
, sock
->info
.af
, true));
1956 /* print active remote address */
1957 msg(msglevel
, "%s link remote: %s",
1958 proto2ascii(sock
->info
.proto
, sock
->info
.af
, true),
1959 print_link_socket_actual_ex(&sock
->info
.lsa
->actual
,
1961 PS_SHOW_PORT_IF_DEFINED
,
1967 phase2_tcp_server(struct link_socket
*sock
, const char *remote_dynamic
,
1968 volatile int *signal_received
)
1972 case LS_MODE_DEFAULT
:
1973 sock
->sd
= socket_listen_accept(sock
->sd
,
1974 &sock
->info
.lsa
->actual
,
1976 sock
->info
.lsa
->bind_local
,
1982 case LS_MODE_TCP_LISTEN
:
1983 socket_do_listen(sock
->sd
,
1984 sock
->info
.lsa
->bind_local
,
1989 case LS_MODE_TCP_ACCEPT_FROM
:
1990 sock
->sd
= socket_do_accept(sock
->sd
,
1991 &sock
->info
.lsa
->actual
,
1993 if (!socket_defined(sock
->sd
))
1995 *signal_received
= SIGTERM
;
1998 tcp_connection_established(&sock
->info
.lsa
->actual
);
2008 phase2_tcp_client(struct link_socket
*sock
, struct signal_info
*sig_info
)
2010 bool proxy_retry
= false;
2012 socket_connect(&sock
->sd
,
2013 sock
->info
.lsa
->current_remote
->ai_addr
,
2014 get_server_poll_remaining_time(sock
->server_poll_timeout
),
2017 if (sig_info
->signal_received
)
2022 if (sock
->http_proxy
)
2024 proxy_retry
= establish_http_proxy_passthru(sock
->http_proxy
,
2026 sock
->proxy_dest_host
,
2027 sock
->proxy_dest_port
,
2028 sock
->server_poll_timeout
,
2029 &sock
->stream_buf
.residual
,
2030 &sig_info
->signal_received
);
2032 else if (sock
->socks_proxy
)
2034 establish_socks_proxy_passthru(sock
->socks_proxy
,
2036 sock
->proxy_dest_host
,
2037 sock
->proxy_dest_port
,
2038 &sig_info
->signal_received
);
2042 openvpn_close_socket(sock
->sd
);
2043 sock
->sd
= create_socket_tcp(sock
->info
.lsa
->current_remote
);
2046 } while (proxy_retry
);
2051 phase2_socks_client(struct link_socket
*sock
, struct signal_info
*sig_info
)
2053 socket_connect(&sock
->ctrl_sd
,
2054 sock
->info
.lsa
->current_remote
->ai_addr
,
2055 get_server_poll_remaining_time(sock
->server_poll_timeout
),
2058 if (sig_info
->signal_received
)
2063 establish_socks_proxy_udpassoc(sock
->socks_proxy
,
2066 &sock
->socks_relay
.dest
,
2067 &sig_info
->signal_received
);
2069 if (sig_info
->signal_received
)
2074 sock
->remote_host
= sock
->proxy_dest_host
;
2075 sock
->remote_port
= sock
->proxy_dest_port
;
2077 addr_zero_host(&sock
->info
.lsa
->actual
.dest
);
2078 if (sock
->info
.lsa
->remote_list
)
2080 freeaddrinfo(sock
->info
.lsa
->remote_list
);
2081 sock
->info
.lsa
->current_remote
= NULL
;
2082 sock
->info
.lsa
->remote_list
= NULL
;
2085 resolve_remote(sock
, 1, NULL
, &sig_info
->signal_received
);
2088 /* finalize socket initialization */
2090 link_socket_init_phase2(struct link_socket
*sock
,
2091 const struct frame
*frame
,
2092 struct signal_info
*sig_info
)
2094 const char *remote_dynamic
= NULL
;
2100 if (sig_info
->signal_received
)
2102 sig_save
= sig_info
->signal_received
;
2103 sig_info
->signal_received
= 0;
2106 /* initialize buffers */
2107 socket_frame_init(frame
, sock
);
2110 * Pass a remote name to connect/accept so that
2111 * they can test for dynamic IP address changes
2112 * and throw a SIGUSR1 if appropriate.
2114 if (sock
->resolve_retry_seconds
)
2116 remote_dynamic
= sock
->remote_host
;
2119 /* were we started by inetd or xinetd? */
2122 phase2_inetd(sock
, frame
, remote_dynamic
, &sig_info
->signal_received
);
2123 if (sig_info
->signal_received
)
2131 /* Second chance to resolv/create socket */
2132 resolve_remote(sock
, 2, &remote_dynamic
, &sig_info
->signal_received
);
2134 /* If a valid remote has been found, create the socket with its addrinfo */
2135 if (sock
->info
.lsa
->current_remote
)
2137 create_socket(sock
, sock
->info
.lsa
->current_remote
);
2140 /* If socket has not already been created create it now */
2141 if (sock
->sd
== SOCKET_UNDEFINED
)
2143 /* If we have no --remote and have still not figured out the
2144 * protocol family to use we will use the first of the bind */
2146 if (sock
->bind_local
&& !sock
->remote_host
&& sock
->info
.lsa
->bind_local
)
2148 /* Warn if this is because neither v4 or v6 was specified
2149 * and we should not connect a remote */
2150 if (sock
->info
.af
== AF_UNSPEC
)
2152 msg(M_WARN
, "Could not determine IPv4/IPv6 protocol. Using %s",
2153 addr_family_name(sock
->info
.lsa
->bind_local
->ai_family
));
2154 sock
->info
.af
= sock
->info
.lsa
->bind_local
->ai_family
;
2157 create_socket(sock
, sock
->info
.lsa
->bind_local
);
2161 /* Socket still undefined, give a warning and abort connection */
2162 if (sock
->sd
== SOCKET_UNDEFINED
)
2164 msg(M_WARN
, "Could not determine IPv4/IPv6 protocol");
2165 sig_info
->signal_received
= SIGUSR1
;
2169 if (sig_info
->signal_received
)
2174 if (sock
->info
.proto
== PROTO_TCP_SERVER
)
2176 phase2_tcp_server(sock
, remote_dynamic
,
2177 &sig_info
->signal_received
);
2179 else if (sock
->info
.proto
== PROTO_TCP_CLIENT
)
2181 phase2_tcp_client(sock
, sig_info
);
2184 else if (sock
->info
.proto
== PROTO_UDP
&& sock
->socks_proxy
)
2186 phase2_socks_client(sock
, sig_info
);
2188 #ifdef TARGET_ANDROID
2191 protect_fd_nonlocal(sock
->sd
, &sock
->info
.lsa
->actual
.dest
.addr
.sa
);
2194 if (sig_info
->signal_received
)
2200 phase2_set_socket_flags(sock
);
2201 linksock_print_addr(sock
);
2206 if (!sig_info
->signal_received
)
2208 sig_info
->signal_received
= sig_save
;
2214 link_socket_close(struct link_socket
*sock
)
2219 const int gremlin
= GREMLIN_CONNECTION_FLOOD_LEVEL(sock
->gremlin
);
2221 const int gremlin
= 0;
2224 if (socket_defined(sock
->sd
))
2227 close_net_event_win32(&sock
->listen_handle
, sock
->sd
, 0);
2231 msg(D_LOW
, "TCP/UDP: Closing socket");
2232 if (openvpn_close_socket(sock
->sd
))
2234 msg(M_WARN
| M_ERRNO
, "TCP/UDP: Close Socket failed");
2237 sock
->sd
= SOCKET_UNDEFINED
;
2241 overlapped_io_close(&sock
->reads
);
2242 overlapped_io_close(&sock
->writes
);
2247 if (socket_defined(sock
->ctrl_sd
))
2249 if (openvpn_close_socket(sock
->ctrl_sd
))
2251 msg(M_WARN
| M_ERRNO
, "TCP/UDP: Close Socket (ctrl_sd) failed");
2253 sock
->ctrl_sd
= SOCKET_UNDEFINED
;
2256 stream_buf_close(&sock
->stream_buf
);
2257 free_buf(&sock
->stream_buf_data
);
2265 /* for stream protocols, allow for packet length prefix */
2267 socket_adjust_frame_parameters(struct frame
*frame
, int proto
)
2269 if (link_socket_proto_connection_oriented(proto
))
2271 frame_add_to_extra_frame(frame
, sizeof(packet_size_type
));
2276 setenv_trusted(struct env_set
*es
, const struct link_socket_info
*info
)
2278 setenv_link_socket_actual(es
, "trusted", &info
->lsa
->actual
, SA_IP_PORT
);
2282 ipchange_fmt(const bool include_cmd
, struct argv
*argv
, const struct link_socket_info
*info
, struct gc_arena
*gc
)
2284 const char *host
= print_sockaddr_ex(&info
->lsa
->actual
.dest
.addr
.sa
, " ", PS_SHOW_PORT
, gc
);
2287 argv_parse_cmd(argv
, info
->ipchange_command
);
2288 argv_printf_cat(argv
, "%s", host
);
2292 argv_printf(argv
, "%s", host
);
2298 link_socket_connection_initiated(const struct buffer
*buf
,
2299 struct link_socket_info
*info
,
2300 const struct link_socket_actual
*act
,
2301 const char *common_name
,
2304 struct gc_arena gc
= gc_new();
2306 info
->lsa
->actual
= *act
; /* Note: skip this line for --force-dest */
2307 setenv_trusted(es
, info
);
2308 info
->connection_established
= true;
2310 /* Print connection initiated message, with common name if available */
2312 struct buffer out
= alloc_buf_gc(256, &gc
);
2315 buf_printf(&out
, "[%s] ", common_name
);
2317 buf_printf(&out
, "Peer Connection Initiated with %s", print_link_socket_actual(&info
->lsa
->actual
, &gc
));
2318 msg(M_INFO
, "%s", BSTR(&out
));
2321 /* set environmental vars */
2322 setenv_str(es
, "common_name", common_name
);
2324 /* Process --ipchange plugin */
2325 if (plugin_defined(info
->plugins
, OPENVPN_PLUGIN_IPCHANGE
))
2327 struct argv argv
= argv_new();
2328 ipchange_fmt(false, &argv
, info
, &gc
);
2329 if (plugin_call(info
->plugins
, OPENVPN_PLUGIN_IPCHANGE
, &argv
, NULL
, es
) != OPENVPN_PLUGIN_FUNC_SUCCESS
)
2331 msg(M_WARN
, "WARNING: ipchange plugin call failed");
2336 /* Process --ipchange option */
2337 if (info
->ipchange_command
)
2339 struct argv argv
= argv_new();
2340 setenv_str(es
, "script_type", "ipchange");
2341 ipchange_fmt(true, &argv
, info
, &gc
);
2342 openvpn_run_script(&argv
, es
, 0, "--ipchange");
2350 link_socket_bad_incoming_addr(struct buffer
*buf
,
2351 const struct link_socket_info
*info
,
2352 const struct link_socket_actual
*from_addr
)
2354 struct gc_arena gc
= gc_new();
2355 struct addrinfo
*ai
;
2357 switch (from_addr
->dest
.addr
.sa
.sa_family
)
2362 "TCP/UDP: Incoming packet rejected from %s[%d], expected peer address: %s (allow this incoming source address/port by removing --remote or adding --float)",
2363 print_link_socket_actual(from_addr
, &gc
),
2364 (int)from_addr
->dest
.addr
.sa
.sa_family
,
2365 print_sockaddr_ex(info
->lsa
->remote_list
->ai_addr
,":",PS_SHOW_PORT
, &gc
));
2366 /* print additional remote addresses */
2367 for (ai
= info
->lsa
->remote_list
->ai_next
; ai
; ai
= ai
->ai_next
) {
2368 msg(D_LINK_ERRORS
,"or from peer address: %s",
2369 print_sockaddr_ex(ai
->ai_addr
,":",PS_SHOW_PORT
, &gc
));
2378 link_socket_bad_outgoing_addr(void)
2380 dmsg(D_READ_WRITE
, "TCP/UDP: No outgoing address to send packet");
2384 link_socket_current_remote(const struct link_socket_info
*info
)
2386 const struct link_socket_addr
*lsa
= info
->lsa
;
2389 * This logic supports "redirect-gateway" semantic, which
2390 * makes sense only for PF_INET routes over PF_INET endpoints
2392 * Maybe in the future consider PF_INET6 endpoints also ...
2393 * by now just ignore it
2395 * For --remote entries with multiple addresses this
2396 * only return the actual endpoint we have sucessfully connected to
2398 if (lsa
->actual
.dest
.addr
.sa
.sa_family
!= AF_INET
)
2400 return IPV4_INVALID_ADDR
;
2403 if (link_socket_actual_defined(&lsa
->actual
))
2405 return ntohl(lsa
->actual
.dest
.addr
.in4
.sin_addr
.s_addr
);
2407 else if (lsa
->current_remote
)
2409 return ntohl(((struct sockaddr_in
*)lsa
->current_remote
->ai_addr
)
2418 const struct in6_addr
*
2419 link_socket_current_remote_ipv6(const struct link_socket_info
*info
)
2421 const struct link_socket_addr
*lsa
= info
->lsa
;
2423 /* This logic supports "redirect-gateway" semantic,
2424 * for PF_INET6 routes over PF_INET6 endpoints
2426 * For --remote entries with multiple addresses this
2427 * only return the actual endpoint we have sucessfully connected to
2429 if (lsa
->actual
.dest
.addr
.sa
.sa_family
!= AF_INET6
)
2434 if (link_socket_actual_defined(&lsa
->actual
))
2436 return &(lsa
->actual
.dest
.addr
.in6
.sin6_addr
);
2438 else if (lsa
->current_remote
)
2440 return &(((struct sockaddr_in6
*)lsa
->current_remote
->ai_addr
)->sin6_addr
);
2449 * Return a status string describing socket state.
2452 socket_stat(const struct link_socket
*s
, unsigned int rwflags
, struct gc_arena
*gc
)
2454 struct buffer out
= alloc_buf_gc(64, gc
);
2457 if (rwflags
& EVENT_READ
)
2459 buf_printf(&out
, "S%s",
2460 (s
->rwflags_debug
& EVENT_READ
) ? "R" : "r");
2462 buf_printf(&out
, "%s",
2463 overlapped_io_state_ascii(&s
->reads
));
2466 if (rwflags
& EVENT_WRITE
)
2468 buf_printf(&out
, "S%s",
2469 (s
->rwflags_debug
& EVENT_WRITE
) ? "W" : "w");
2471 buf_printf(&out
, "%s",
2472 overlapped_io_state_ascii(&s
->writes
));
2478 buf_printf(&out
, "S?");
2484 * Stream buffer functions, used to packetize a TCP
2485 * stream connection.
2489 stream_buf_reset(struct stream_buf
*sb
)
2491 dmsg(D_STREAM_DEBUG
, "STREAM: RESET");
2492 sb
->residual_fully_formed
= false;
2493 sb
->buf
= sb
->buf_init
;
2494 buf_reset(&sb
->next
);
2499 stream_buf_init(struct stream_buf
*sb
,
2501 const unsigned int sockflags
,
2504 sb
->buf_init
= *buf
;
2505 sb
->maxlen
= sb
->buf_init
.len
;
2506 sb
->buf_init
.len
= 0;
2507 sb
->residual
= alloc_buf(sb
->maxlen
);
2510 sb
->port_share_state
= ((sockflags
& SF_PORT_SHARE
) && (proto
== PROTO_TCP_SERVER
))
2514 stream_buf_reset(sb
);
2516 dmsg(D_STREAM_DEBUG
, "STREAM: INIT maxlen=%d", sb
->maxlen
);
2520 stream_buf_set_next(struct stream_buf
*sb
)
2522 /* set up 'next' for next i/o read */
2524 sb
->next
.offset
= sb
->buf
.offset
+ sb
->buf
.len
;
2525 sb
->next
.len
= (sb
->len
>= 0 ? sb
->len
: sb
->maxlen
) - sb
->buf
.len
;
2526 dmsg(D_STREAM_DEBUG
, "STREAM: SET NEXT, buf=[%d,%d] next=[%d,%d] len=%d maxlen=%d",
2527 sb
->buf
.offset
, sb
->buf
.len
,
2528 sb
->next
.offset
, sb
->next
.len
,
2529 sb
->len
, sb
->maxlen
);
2530 ASSERT(sb
->next
.len
> 0);
2531 ASSERT(buf_safe(&sb
->buf
, sb
->next
.len
));
2535 stream_buf_get_final(struct stream_buf
*sb
, struct buffer
*buf
)
2537 dmsg(D_STREAM_DEBUG
, "STREAM: GET FINAL len=%d",
2538 buf_defined(&sb
->buf
) ? sb
->buf
.len
: -1);
2539 ASSERT(buf_defined(&sb
->buf
));
2544 stream_buf_get_next(struct stream_buf
*sb
, struct buffer
*buf
)
2546 dmsg(D_STREAM_DEBUG
, "STREAM: GET NEXT len=%d",
2547 buf_defined(&sb
->next
) ? sb
->next
.len
: -1);
2548 ASSERT(buf_defined(&sb
->next
));
2553 stream_buf_read_setup_dowork(struct link_socket
*sock
)
2555 if (sock
->stream_buf
.residual
.len
&& !sock
->stream_buf
.residual_fully_formed
)
2557 ASSERT(buf_copy(&sock
->stream_buf
.buf
, &sock
->stream_buf
.residual
));
2558 ASSERT(buf_init(&sock
->stream_buf
.residual
, 0));
2559 sock
->stream_buf
.residual_fully_formed
= stream_buf_added(&sock
->stream_buf
, 0);
2560 dmsg(D_STREAM_DEBUG
, "STREAM: RESIDUAL FULLY FORMED [%s], len=%d",
2561 sock
->stream_buf
.residual_fully_formed
? "YES" : "NO",
2562 sock
->stream_buf
.residual
.len
);
2565 if (!sock
->stream_buf
.residual_fully_formed
)
2567 stream_buf_set_next(&sock
->stream_buf
);
2569 return !sock
->stream_buf
.residual_fully_formed
;
2573 stream_buf_added(struct stream_buf
*sb
,
2576 dmsg(D_STREAM_DEBUG
, "STREAM: ADD length_added=%d", length_added
);
2577 if (length_added
> 0)
2579 sb
->buf
.len
+= length_added
;
2582 /* if length unknown, see if we can get the length prefix from
2583 * the head of the buffer */
2584 if (sb
->len
< 0 && sb
->buf
.len
>= (int) sizeof(packet_size_type
))
2586 packet_size_type net_size
;
2589 if (sb
->port_share_state
== PS_ENABLED
)
2591 if (!is_openvpn_protocol(&sb
->buf
))
2593 msg(D_STREAM_ERRORS
, "Non-OpenVPN client protocol detected");
2594 sb
->port_share_state
= PS_FOREIGN
;
2600 sb
->port_share_state
= PS_DISABLED
;
2605 ASSERT(buf_read(&sb
->buf
, &net_size
, sizeof(net_size
)));
2606 sb
->len
= ntohps(net_size
);
2608 if (sb
->len
< 1 || sb
->len
> sb
->maxlen
)
2610 msg(M_WARN
, "WARNING: Bad encapsulated packet length from peer (%d), which must be > 0 and <= %d -- please ensure that --tun-mtu or --link-mtu is equal on both peers -- this condition could also indicate a possible active attack on the TCP link -- [Attempting restart...]", sb
->len
, sb
->maxlen
);
2611 stream_buf_reset(sb
);
2617 /* is our incoming packet fully read? */
2618 if (sb
->len
> 0 && sb
->buf
.len
>= sb
->len
)
2620 /* save any residual data that's part of the next packet */
2621 ASSERT(buf_init(&sb
->residual
, 0));
2622 if (sb
->buf
.len
> sb
->len
)
2624 ASSERT(buf_copy_excess(&sb
->residual
, &sb
->buf
, sb
->len
));
2626 dmsg(D_STREAM_DEBUG
, "STREAM: ADD returned TRUE, buf_len=%d, residual_len=%d",
2628 BLEN(&sb
->residual
));
2633 dmsg(D_STREAM_DEBUG
, "STREAM: ADD returned FALSE (have=%d need=%d)", sb
->buf
.len
, sb
->len
);
2634 stream_buf_set_next(sb
);
2640 stream_buf_close(struct stream_buf
*sb
)
2642 free_buf(&sb
->residual
);
2646 * The listen event is a special event whose sole purpose is
2647 * to tell us that there's a new incoming connection on a
2648 * TCP socket, for use in server mode.
2651 socket_listen_event_handle(struct link_socket
*s
)
2654 if (!defined_net_event_win32(&s
->listen_handle
))
2656 init_net_event_win32(&s
->listen_handle
, FD_ACCEPT
, s
->sd
, 0);
2658 return &s
->listen_handle
;
2659 #else /* ifdef _WIN32 */
2665 * Format IP addresses in ascii
2669 print_sockaddr_ex(const struct sockaddr
*sa
,
2670 const char *separator
,
2671 const unsigned int flags
,
2672 struct gc_arena
*gc
)
2674 struct buffer out
= alloc_buf_gc(128, gc
);
2675 bool addr_is_defined
= false;
2676 char hostaddr
[NI_MAXHOST
] = "";
2677 char servname
[NI_MAXSERV
] = "";
2680 socklen_t salen
= 0;
2681 switch (sa
->sa_family
)
2684 if (!(flags
& PS_DONT_SHOW_FAMILY
))
2686 buf_puts(&out
, "[AF_INET]");
2688 salen
= sizeof(struct sockaddr_in
);
2689 addr_is_defined
= ((struct sockaddr_in
*) sa
)->sin_addr
.s_addr
!= 0;
2693 if (!(flags
& PS_DONT_SHOW_FAMILY
))
2695 buf_puts(&out
, "[AF_INET6]");
2697 salen
= sizeof(struct sockaddr_in6
);
2698 addr_is_defined
= !IN6_IS_ADDR_UNSPECIFIED(&((struct sockaddr_in6
*) sa
)->sin6_addr
);
2702 if (!(flags
& PS_DONT_SHOW_FAMILY
))
2704 return "[AF_UNSPEC]";
2715 status
= getnameinfo(sa
, salen
, hostaddr
, sizeof(hostaddr
),
2716 servname
, sizeof(servname
), NI_NUMERICHOST
| NI_NUMERICSERV
);
2720 buf_printf(&out
,"[nameinfo() err: %s]",gai_strerror(status
));
2724 if (!(flags
& PS_DONT_SHOW_ADDR
))
2726 if (addr_is_defined
)
2728 buf_puts(&out
, hostaddr
);
2732 buf_puts(&out
, "[undef]");
2736 if ((flags
& PS_SHOW_PORT
) || (flags
& PS_SHOW_PORT_IF_DEFINED
))
2740 buf_puts(&out
, separator
);
2743 buf_puts(&out
, servname
);
2750 print_link_socket_actual(const struct link_socket_actual
*act
, struct gc_arena
*gc
)
2752 return print_link_socket_actual_ex(act
, ":", PS_SHOW_PORT
|PS_SHOW_PKTINFO
, gc
);
2756 #define IF_NAMESIZE 16
2760 print_link_socket_actual_ex(const struct link_socket_actual
*act
,
2761 const char *separator
,
2762 const unsigned int flags
,
2763 struct gc_arena
*gc
)
2767 char ifname
[IF_NAMESIZE
] = "[undef]";
2768 struct buffer out
= alloc_buf_gc(128, gc
);
2769 buf_printf(&out
, "%s", print_sockaddr_ex(&act
->dest
.addr
.sa
, separator
, flags
, gc
));
2770 #if ENABLE_IP_PKTINFO
2771 if ((flags
& PS_SHOW_PKTINFO
) && addr_defined_ipi(act
))
2773 switch (act
->dest
.addr
.sa
.sa_family
)
2777 struct openvpn_sockaddr sa
;
2779 sa
.addr
.in4
.sin_family
= AF_INET
;
2780 #if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST)
2781 sa
.addr
.in4
.sin_addr
= act
->pi
.in4
.ipi_spec_dst
;
2782 if_indextoname(act
->pi
.in4
.ipi_ifindex
, ifname
);
2783 #elif defined(IP_RECVDSTADDR)
2784 sa
.addr
.in4
.sin_addr
= act
->pi
.in4
;
2786 #else /* if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST) */
2787 #error ENABLE_IP_PKTINFO is set without IP_PKTINFO xor IP_RECVDSTADDR (fix syshead.h)
2789 buf_printf(&out
, " (via %s%%%s)",
2790 print_sockaddr_ex(&sa
.addr
.sa
, separator
, 0, gc
),
2797 struct sockaddr_in6 sin6
;
2798 char buf
[INET6_ADDRSTRLEN
] = "[undef]";
2800 sin6
.sin6_family
= AF_INET6
;
2801 sin6
.sin6_addr
= act
->pi
.in6
.ipi6_addr
;
2802 if_indextoname(act
->pi
.in6
.ipi6_ifindex
, ifname
);
2803 if (getnameinfo((struct sockaddr
*)&sin6
, sizeof(struct sockaddr_in6
),
2804 buf
, sizeof(buf
), NULL
, 0, NI_NUMERICHOST
) == 0)
2806 buf_printf(&out
, " (via %s%%%s)", buf
, ifname
);
2810 buf_printf(&out
, " (via [getnameinfo() err]%%%s)", ifname
);
2816 #endif /* if ENABLE_IP_PKTINFO */
2826 * Convert an in_addr_t in host byte order
2827 * to an ascii dotted quad.
2830 print_in_addr_t(in_addr_t addr
, unsigned int flags
, struct gc_arena
*gc
)
2833 struct buffer out
= alloc_buf_gc(64, gc
);
2835 if (addr
|| !(flags
& IA_EMPTY_IF_UNDEF
))
2838 ia
.s_addr
= (flags
& IA_NET_ORDER
) ? addr
: htonl(addr
);
2840 buf_printf(&out
, "%s", inet_ntoa(ia
));
2846 * Convert an in6_addr in host byte order
2847 * to an ascii representation of an IPv6 address
2850 print_in6_addr(struct in6_addr a6
, unsigned int flags
, struct gc_arena
*gc
)
2852 struct buffer out
= alloc_buf_gc(64, gc
);
2853 char tmp_out_buf
[64]; /* inet_ntop wants pointer to buffer */
2855 if (memcmp(&a6
, &in6addr_any
, sizeof(a6
)) != 0
2856 || !(flags
& IA_EMPTY_IF_UNDEF
))
2858 inet_ntop(AF_INET6
, &a6
, tmp_out_buf
, sizeof(tmp_out_buf
)-1);
2859 buf_printf(&out
, "%s", tmp_out_buf
);
2865 #define UINT8_MAX 0xff
2868 /* add some offset to an ipv6 address
2869 * (add in steps of 8 bits, taking overflow into next round)
2872 add_in6_addr( struct in6_addr base
, uint32_t add
)
2876 for (i
= 15; i
>=0 && add
> 0; i
--)
2879 register uint32_t h
;
2881 h
= (unsigned char) base
.s6_addr
[i
];
2882 base
.s6_addr
[i
] = (h
+add
) & UINT8_MAX
;
2884 /* using explicit carry for the 8-bit additions will catch
2885 * 8-bit and(!) 32-bit overruns nicely
2887 carry
= ((h
& 0xff) + (add
& 0xff)) >> 8;
2888 add
= (add
>>8) + carry
;
2893 /* set environmental variables for ip/port in *addr */
2895 setenv_sockaddr(struct env_set
*es
, const char *name_prefix
, const struct openvpn_sockaddr
*addr
, const unsigned int flags
)
2900 switch (addr
->addr
.sa
.sa_family
)
2903 if (flags
& SA_IP_PORT
)
2905 openvpn_snprintf(name_buf
, sizeof(name_buf
), "%s_ip", name_prefix
);
2909 openvpn_snprintf(name_buf
, sizeof(name_buf
), "%s", name_prefix
);
2912 setenv_str(es
, name_buf
, inet_ntoa(addr
->addr
.in4
.sin_addr
));
2914 if ((flags
& SA_IP_PORT
) && addr
->addr
.in4
.sin_port
)
2916 openvpn_snprintf(name_buf
, sizeof(name_buf
), "%s_port", name_prefix
);
2917 setenv_int(es
, name_buf
, ntohs(addr
->addr
.in4
.sin_port
));
2922 if (IN6_IS_ADDR_V4MAPPED( &addr
->addr
.in6
.sin6_addr
))
2925 memcpy(&ia
.s_addr
, &addr
->addr
.in6
.sin6_addr
.s6_addr
[12],
2927 openvpn_snprintf(name_buf
, sizeof(name_buf
), "%s_ip", name_prefix
);
2928 openvpn_snprintf(buf
, sizeof(buf
), "%s", inet_ntoa(ia
) );
2932 openvpn_snprintf(name_buf
, sizeof(name_buf
), "%s_ip6", name_prefix
);
2933 getnameinfo(&addr
->addr
.sa
, sizeof(struct sockaddr_in6
),
2934 buf
, sizeof(buf
), NULL
, 0, NI_NUMERICHOST
);
2936 setenv_str(es
, name_buf
, buf
);
2938 if ((flags
& SA_IP_PORT
) && addr
->addr
.in6
.sin6_port
)
2940 openvpn_snprintf(name_buf
, sizeof(name_buf
), "%s_port", name_prefix
);
2941 setenv_int(es
, name_buf
, ntohs(addr
->addr
.in6
.sin6_port
));
2948 setenv_in_addr_t(struct env_set
*es
, const char *name_prefix
, in_addr_t addr
, const unsigned int flags
)
2950 if (addr
|| !(flags
& SA_SET_IF_NONZERO
))
2952 struct openvpn_sockaddr si
;
2954 si
.addr
.in4
.sin_family
= AF_INET
;
2955 si
.addr
.in4
.sin_addr
.s_addr
= htonl(addr
);
2956 setenv_sockaddr(es
, name_prefix
, &si
, flags
);
2961 setenv_in6_addr(struct env_set
*es
,
2962 const char *name_prefix
,
2963 const struct in6_addr
*addr
,
2964 const unsigned int flags
)
2966 if (!IN6_IS_ADDR_UNSPECIFIED(addr
) || !(flags
& SA_SET_IF_NONZERO
))
2968 struct openvpn_sockaddr si
;
2970 si
.addr
.in6
.sin6_family
= AF_INET6
;
2971 si
.addr
.in6
.sin6_addr
= *addr
;
2972 setenv_sockaddr(es
, name_prefix
, &si
, flags
);
2977 setenv_link_socket_actual(struct env_set
*es
,
2978 const char *name_prefix
,
2979 const struct link_socket_actual
*act
,
2980 const unsigned int flags
)
2982 setenv_sockaddr(es
, name_prefix
, &act
->dest
, flags
);
2986 * Convert protocol names between index and ascii form.
2989 struct proto_names
{
2990 const char *short_form
;
2991 const char *display_form
;
2992 sa_family_t proto_af
;
2996 /* Indexed by PROTO_x */
2997 static const struct proto_names proto_names
[] = {
2998 {"proto-uninitialized", "proto-NONE", AF_UNSPEC
, PROTO_NONE
},
2999 /* try IPv4 and IPv6 (client), bind dual-stack (server) */
3000 {"udp", "UDP", AF_UNSPEC
, PROTO_UDP
},
3001 {"tcp-server", "TCP_SERVER", AF_UNSPEC
, PROTO_TCP_SERVER
},
3002 {"tcp-client", "TCP_CLIENT", AF_UNSPEC
, PROTO_TCP_CLIENT
},
3003 {"tcp", "TCP", AF_UNSPEC
, PROTO_TCP
},
3005 {"udp4", "UDPv4", AF_INET
, PROTO_UDP
},
3006 {"tcp4-server","TCPv4_SERVER", AF_INET
, PROTO_TCP_SERVER
},
3007 {"tcp4-client","TCPv4_CLIENT", AF_INET
, PROTO_TCP_CLIENT
},
3008 {"tcp4", "TCPv4", AF_INET
, PROTO_TCP
},
3010 {"udp6","UDPv6", AF_INET6
, PROTO_UDP
},
3011 {"tcp6-server","TCPv6_SERVER", AF_INET6
, PROTO_TCP_SERVER
},
3012 {"tcp6-client","TCPv6_CLIENT", AF_INET6
, PROTO_TCP_CLIENT
},
3013 {"tcp6","TCPv6", AF_INET6
, PROTO_TCP
},
3017 proto_is_net(int proto
)
3019 if (proto
< 0 || proto
>= PROTO_N
)
3023 return proto
!= PROTO_NONE
;
3026 proto_is_dgram(int proto
)
3028 return proto_is_udp(proto
);
3032 proto_is_udp(int proto
)
3034 if (proto
< 0 || proto
>= PROTO_N
)
3038 return proto
== PROTO_UDP
;
3042 proto_is_tcp(int proto
)
3044 if (proto
< 0 || proto
>= PROTO_N
)
3048 return proto
== PROTO_TCP_CLIENT
|| proto
== PROTO_TCP_SERVER
;
3052 ascii2proto(const char *proto_name
)
3055 for (i
= 0; i
< SIZE(proto_names
); ++i
)
3056 if (!strcmp(proto_name
, proto_names
[i
].short_form
))
3058 return proto_names
[i
].proto
;
3064 ascii2af(const char *proto_name
)
3067 for (i
= 0; i
< SIZE(proto_names
); ++i
)
3068 if (!strcmp(proto_name
, proto_names
[i
].short_form
))
3070 return proto_names
[i
].proto_af
;
3076 proto2ascii(int proto
, sa_family_t af
, bool display_form
)
3079 for (i
= 0; i
< SIZE(proto_names
); ++i
)
3081 if (proto_names
[i
].proto_af
== af
&& proto_names
[i
].proto
== proto
)
3085 return proto_names
[i
].display_form
;
3089 return proto_names
[i
].short_form
;
3094 return "[unknown protocol]";
3098 proto2ascii_all(struct gc_arena
*gc
)
3100 struct buffer out
= alloc_buf_gc(256, gc
);
3103 for (i
= 0; i
< SIZE(proto_names
); ++i
)
3107 buf_printf(&out
, " ");
3109 buf_printf(&out
, "[%s]", proto_names
[i
].short_form
);
3115 addr_family_name(int af
)
3119 case AF_INET
: return "AF_INET";
3121 case AF_INET6
: return "AF_INET6";
3127 * Given a local proto, return local proto
3128 * if !remote, or compatible remote proto
3131 * This is used for options compatibility
3134 * IPv6 and IPv4 protocols are comptabile but OpenVPN
3135 * has always sent UDPv4, TCPv4 over the wire. Keep these
3136 * strings for backward compatbility
3139 proto_remote(int proto
, bool remote
)
3141 ASSERT(proto
>= 0 && proto
< PROTO_N
);
3142 if (proto
== PROTO_UDP
)
3147 if ( (remote
&& proto
== PROTO_TCP_CLIENT
)
3148 || (!remote
&& proto
== PROTO_TCP_SERVER
))
3150 return "TCPv4_SERVER";
3152 if ( (remote
&& proto
== PROTO_TCP_SERVER
)
3153 || (!remote
&& proto
== PROTO_TCP_CLIENT
))
3155 return "TCPv4_CLIENT";
3159 return ""; /* Make the compiler happy */
3163 * Bad incoming address lengths that differ from what
3164 * we expect are considered to be fatal errors.
3167 bad_address_length(int actual
, int expected
)
3169 msg(M_FATAL
, "ERROR: received strange incoming packet with an address length of %d -- we only accept address lengths of %d.",
3175 * Socket Read Routines
3179 link_socket_read_tcp(struct link_socket
*sock
,
3184 if (!sock
->stream_buf
.residual_fully_formed
)
3187 len
= socket_finalize(sock
->sd
, &sock
->reads
, buf
, NULL
);
3190 stream_buf_get_next(&sock
->stream_buf
, &frag
);
3191 len
= recv(sock
->sd
, BPTR(&frag
), BLEN(&frag
), MSG_NOSIGNAL
);
3196 sock
->stream_reset
= true;
3200 return buf
->len
= len
;
3204 if (sock
->stream_buf
.residual_fully_formed
3205 || stream_buf_added(&sock
->stream_buf
, len
)) /* packet complete? */
3207 stream_buf_get_final(&sock
->stream_buf
, buf
);
3208 stream_buf_reset(&sock
->stream_buf
);
3213 return buf
->len
= 0; /* no error, but packet is still incomplete */
3219 #if ENABLE_IP_PKTINFO
3221 /* make the buffer large enough to handle ancilliary socket data for
3222 * both IPv4 and IPv6 destination addresses, plus padding (see RFC 2292)
3224 #if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST)
3225 #define PKTINFO_BUF_SIZE max_int( CMSG_SPACE(sizeof(struct in6_pktinfo)), \
3226 CMSG_SPACE(sizeof(struct in_pktinfo)) )
3228 #define PKTINFO_BUF_SIZE max_int( CMSG_SPACE(sizeof(struct in6_pktinfo)), \
3229 CMSG_SPACE(sizeof(struct in_addr)) )
3233 link_socket_read_udp_posix_recvmsg(struct link_socket
*sock
,
3235 struct link_socket_actual
*from
)
3238 uint8_t pktinfo_buf
[PKTINFO_BUF_SIZE
];
3240 socklen_t fromlen
= sizeof(from
->dest
.addr
);
3242 iov
.iov_base
= BPTR(buf
);
3243 iov
.iov_len
= buf_forward_capacity_total(buf
);
3244 mesg
.msg_iov
= &iov
;
3245 mesg
.msg_iovlen
= 1;
3246 mesg
.msg_name
= &from
->dest
.addr
;
3247 mesg
.msg_namelen
= fromlen
;
3248 mesg
.msg_control
= pktinfo_buf
;
3249 mesg
.msg_controllen
= sizeof pktinfo_buf
;
3250 buf
->len
= recvmsg(sock
->sd
, &mesg
, 0);
3253 struct cmsghdr
*cmsg
;
3254 fromlen
= mesg
.msg_namelen
;
3255 cmsg
= CMSG_FIRSTHDR(&mesg
);
3257 && CMSG_NXTHDR(&mesg
, cmsg
) == NULL
3258 #if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST)
3259 && cmsg
->cmsg_level
== SOL_IP
3260 && cmsg
->cmsg_type
== IP_PKTINFO
3261 && cmsg
->cmsg_len
>= CMSG_LEN(sizeof(struct in_pktinfo
)) )
3262 #elif defined(IP_RECVDSTADDR)
3263 && cmsg
->cmsg_level
== IPPROTO_IP
3264 && cmsg
->cmsg_type
== IP_RECVDSTADDR
3265 && cmsg
->cmsg_len
>= CMSG_LEN(sizeof(struct in_addr
)) )
3266 #else /* if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST) */
3267 #error ENABLE_IP_PKTINFO is set without IP_PKTINFO xor IP_RECVDSTADDR (fix syshead.h)
3270 #if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST)
3271 struct in_pktinfo
*pkti
= (struct in_pktinfo
*) CMSG_DATA(cmsg
);
3272 from
->pi
.in4
.ipi_ifindex
= pkti
->ipi_ifindex
;
3273 from
->pi
.in4
.ipi_spec_dst
= pkti
->ipi_spec_dst
;
3274 #elif defined(IP_RECVDSTADDR)
3275 from
->pi
.in4
= *(struct in_addr
*) CMSG_DATA(cmsg
);
3276 #else /* if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST) */
3277 #error ENABLE_IP_PKTINFO is set without IP_PKTINFO xor IP_RECVDSTADDR (fix syshead.h)
3280 else if (cmsg
!= NULL
3281 && CMSG_NXTHDR(&mesg
, cmsg
) == NULL
3282 && cmsg
->cmsg_level
== IPPROTO_IPV6
3283 && cmsg
->cmsg_type
== IPV6_PKTINFO
3284 && cmsg
->cmsg_len
>= CMSG_LEN(sizeof(struct in6_pktinfo
)) )
3286 struct in6_pktinfo
*pkti6
= (struct in6_pktinfo
*) CMSG_DATA(cmsg
);
3287 from
->pi
.in6
.ipi6_ifindex
= pkti6
->ipi6_ifindex
;
3288 from
->pi
.in6
.ipi6_addr
= pkti6
->ipi6_addr
;
3290 else if (cmsg
!= NULL
)
3292 msg(M_WARN
, "CMSG received that cannot be parsed (cmsg_level=%d, cmsg_type=%d, cmsg=len=%d)", (int)cmsg
->cmsg_level
, (int)cmsg
->cmsg_type
, (int)cmsg
->cmsg_len
);
3298 #endif /* if ENABLE_IP_PKTINFO */
3301 link_socket_read_udp_posix(struct link_socket
*sock
,
3303 struct link_socket_actual
*from
)
3305 socklen_t fromlen
= sizeof(from
->dest
.addr
);
3306 socklen_t expectedlen
= af_addr_size(sock
->info
.af
);
3307 addr_zero_host(&from
->dest
);
3308 #if ENABLE_IP_PKTINFO
3309 /* Both PROTO_UDPv4 and PROTO_UDPv6 */
3310 if (sock
->info
.proto
== PROTO_UDP
&& sock
->sockflags
& SF_USE_IP_PKTINFO
)
3312 fromlen
= link_socket_read_udp_posix_recvmsg(sock
, buf
, from
);
3316 buf
->len
= recvfrom(sock
->sd
, BPTR(buf
), buf_forward_capacity(buf
), 0,
3317 &from
->dest
.addr
.sa
, &fromlen
);
3318 /* FIXME: won't do anything when sock->info.af == AF_UNSPEC */
3319 if (buf
->len
>= 0 && expectedlen
&& fromlen
!= expectedlen
)
3321 bad_address_length(fromlen
, expectedlen
);
3326 #endif /* ifndef _WIN32 */
3329 * Socket Write Routines
3333 link_socket_write_tcp(struct link_socket
*sock
,
3335 struct link_socket_actual
*to
)
3337 packet_size_type len
= BLEN(buf
);
3338 dmsg(D_STREAM_DEBUG
, "STREAM: WRITE %d offset=%d", (int)len
, buf
->offset
);
3339 ASSERT(len
<= sock
->stream_buf
.maxlen
);
3341 ASSERT(buf_write_prepend(buf
, &len
, sizeof(len
)));
3343 return link_socket_write_win32(sock
, buf
, to
);
3345 return link_socket_write_tcp_posix(sock
, buf
, to
);
3349 #if ENABLE_IP_PKTINFO
3352 link_socket_write_udp_posix_sendmsg(struct link_socket
*sock
,
3354 struct link_socket_actual
*to
)
3358 struct cmsghdr
*cmsg
;
3359 uint8_t pktinfo_buf
[PKTINFO_BUF_SIZE
];
3361 iov
.iov_base
= BPTR(buf
);
3362 iov
.iov_len
= BLEN(buf
);
3363 mesg
.msg_iov
= &iov
;
3364 mesg
.msg_iovlen
= 1;
3365 switch (to
->dest
.addr
.sa
.sa_family
)
3369 mesg
.msg_name
= &to
->dest
.addr
.sa
;
3370 mesg
.msg_namelen
= sizeof(struct sockaddr_in
);
3371 mesg
.msg_control
= pktinfo_buf
;
3373 #if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST)
3374 mesg
.msg_controllen
= CMSG_SPACE(sizeof(struct in_pktinfo
));
3375 cmsg
= CMSG_FIRSTHDR(&mesg
);
3376 cmsg
->cmsg_len
= CMSG_LEN(sizeof(struct in_pktinfo
));
3377 cmsg
->cmsg_level
= SOL_IP
;
3378 cmsg
->cmsg_type
= IP_PKTINFO
;
3380 struct in_pktinfo
*pkti
;
3381 pkti
= (struct in_pktinfo
*) CMSG_DATA(cmsg
);
3382 pkti
->ipi_ifindex
= to
->pi
.in4
.ipi_ifindex
;
3383 pkti
->ipi_spec_dst
= to
->pi
.in4
.ipi_spec_dst
;
3384 pkti
->ipi_addr
.s_addr
= 0;
3386 #elif defined(IP_RECVDSTADDR)
3387 ASSERT( CMSG_SPACE(sizeof(struct in_addr
)) <= sizeof(pktinfo_buf
) );
3388 mesg
.msg_controllen
= CMSG_SPACE(sizeof(struct in_addr
));
3389 cmsg
= CMSG_FIRSTHDR(&mesg
);
3390 cmsg
->cmsg_len
= CMSG_LEN(sizeof(struct in_addr
));
3391 cmsg
->cmsg_level
= IPPROTO_IP
;
3392 cmsg
->cmsg_type
= IP_RECVDSTADDR
;
3393 *(struct in_addr
*) CMSG_DATA(cmsg
) = to
->pi
.in4
;
3394 #else /* if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST) */
3395 #error ENABLE_IP_PKTINFO is set without IP_PKTINFO xor IP_RECVDSTADDR (fix syshead.h)
3396 #endif /* if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST) */
3402 struct in6_pktinfo
*pkti6
;
3403 mesg
.msg_name
= &to
->dest
.addr
.sa
;
3404 mesg
.msg_namelen
= sizeof(struct sockaddr_in6
);
3406 ASSERT( CMSG_SPACE(sizeof(struct in6_pktinfo
)) <= sizeof(pktinfo_buf
) );
3407 mesg
.msg_control
= pktinfo_buf
;
3408 mesg
.msg_controllen
= CMSG_SPACE(sizeof(struct in6_pktinfo
));
3410 cmsg
= CMSG_FIRSTHDR(&mesg
);
3411 cmsg
->cmsg_len
= CMSG_LEN(sizeof(struct in6_pktinfo
));
3412 cmsg
->cmsg_level
= IPPROTO_IPV6
;
3413 cmsg
->cmsg_type
= IPV6_PKTINFO
;
3415 pkti6
= (struct in6_pktinfo
*) CMSG_DATA(cmsg
);
3416 pkti6
->ipi6_ifindex
= to
->pi
.in6
.ipi6_ifindex
;
3417 pkti6
->ipi6_addr
= to
->pi
.in6
.ipi6_addr
;
3423 return sendmsg(sock
->sd
, &mesg
, 0);
3426 #endif /* if ENABLE_IP_PKTINFO */
3429 * Win32 overlapped socket I/O functions.
3435 socket_recv_queue(struct link_socket
*sock
, int maxsize
)
3437 if (sock
->reads
.iostate
== IOSTATE_INITIAL
)
3442 /* reset buf to its initial state */
3443 if (proto_is_udp(sock
->info
.proto
))
3445 sock
->reads
.buf
= sock
->reads
.buf_init
;
3447 else if (proto_is_tcp(sock
->info
.proto
))
3449 stream_buf_get_next(&sock
->stream_buf
, &sock
->reads
.buf
);
3456 /* Win32 docs say it's okay to allocate the wsabuf on the stack */
3457 wsabuf
[0].buf
= BPTR(&sock
->reads
.buf
);
3458 wsabuf
[0].len
= maxsize
? maxsize
: BLEN(&sock
->reads
.buf
);
3460 /* check for buffer overflow */
3461 ASSERT(wsabuf
[0].len
<= BLEN(&sock
->reads
.buf
));
3463 /* the overlapped read will signal this event on I/O completion */
3464 ASSERT(ResetEvent(sock
->reads
.overlapped
.hEvent
));
3465 sock
->reads
.flags
= 0;
3467 if (proto_is_udp(sock
->info
.proto
))
3469 sock
->reads
.addr_defined
= true;
3470 sock
->reads
.addrlen
= sizeof(sock
->reads
.addr6
);
3471 status
= WSARecvFrom(
3477 (struct sockaddr
*) &sock
->reads
.addr
,
3478 &sock
->reads
.addrlen
,
3479 &sock
->reads
.overlapped
,
3482 else if (proto_is_tcp(sock
->info
.proto
))
3484 sock
->reads
.addr_defined
= false;
3491 &sock
->reads
.overlapped
,
3500 if (!status
) /* operation completed immediately? */
3502 /* FIXME: won't do anything when sock->info.af == AF_UNSPEC */
3503 int af_len
= af_addr_size(sock
->info
.af
);
3504 if (sock
->reads
.addr_defined
&& af_len
&& sock
->reads
.addrlen
!= af_len
)
3506 bad_address_length(sock
->reads
.addrlen
, af_len
);
3508 sock
->reads
.iostate
= IOSTATE_IMMEDIATE_RETURN
;
3510 /* since we got an immediate return, we must signal the event object ourselves */
3511 ASSERT(SetEvent(sock
->reads
.overlapped
.hEvent
));
3512 sock
->reads
.status
= 0;
3514 dmsg(D_WIN32_IO
, "WIN32 I/O: Socket Receive immediate return [%d,%d]",
3515 (int) wsabuf
[0].len
,
3516 (int) sock
->reads
.size
);
3520 status
= WSAGetLastError();
3521 if (status
== WSA_IO_PENDING
) /* operation queued? */
3523 sock
->reads
.iostate
= IOSTATE_QUEUED
;
3524 sock
->reads
.status
= status
;
3525 dmsg(D_WIN32_IO
, "WIN32 I/O: Socket Receive queued [%d]",
3526 (int) wsabuf
[0].len
);
3528 else /* error occurred */
3530 struct gc_arena gc
= gc_new();
3531 ASSERT(SetEvent(sock
->reads
.overlapped
.hEvent
));
3532 sock
->reads
.iostate
= IOSTATE_IMMEDIATE_RETURN
;
3533 sock
->reads
.status
= status
;
3534 dmsg(D_WIN32_IO
, "WIN32 I/O: Socket Receive error [%d]: %s",
3535 (int) wsabuf
[0].len
,
3536 strerror_win32(status
, &gc
));
3541 return sock
->reads
.iostate
;
3545 socket_send_queue(struct link_socket
*sock
, struct buffer
*buf
, const struct link_socket_actual
*to
)
3547 if (sock
->writes
.iostate
== IOSTATE_INITIAL
)
3552 /* make a private copy of buf */
3553 sock
->writes
.buf
= sock
->writes
.buf_init
;
3554 sock
->writes
.buf
.len
= 0;
3555 ASSERT(buf_copy(&sock
->writes
.buf
, buf
));
3557 /* Win32 docs say it's okay to allocate the wsabuf on the stack */
3558 wsabuf
[0].buf
= BPTR(&sock
->writes
.buf
);
3559 wsabuf
[0].len
= BLEN(&sock
->writes
.buf
);
3561 /* the overlapped write will signal this event on I/O completion */
3562 ASSERT(ResetEvent(sock
->writes
.overlapped
.hEvent
));
3563 sock
->writes
.flags
= 0;
3565 if (proto_is_udp(sock
->info
.proto
))
3567 /* set destination address for UDP writes */
3568 sock
->writes
.addr_defined
= true;
3569 if (to
->dest
.addr
.sa
.sa_family
== AF_INET6
)
3571 sock
->writes
.addr6
= to
->dest
.addr
.in6
;
3572 sock
->writes
.addrlen
= sizeof(sock
->writes
.addr6
);
3576 sock
->writes
.addr
= to
->dest
.addr
.in4
;
3577 sock
->writes
.addrlen
= sizeof(sock
->writes
.addr
);
3586 (struct sockaddr
*) &sock
->writes
.addr
,
3587 sock
->writes
.addrlen
,
3588 &sock
->writes
.overlapped
,
3591 else if (proto_is_tcp(sock
->info
.proto
))
3593 /* destination address for TCP writes was established on connection initiation */
3594 sock
->writes
.addr_defined
= false;
3602 &sock
->writes
.overlapped
,
3611 if (!status
) /* operation completed immediately? */
3613 sock
->writes
.iostate
= IOSTATE_IMMEDIATE_RETURN
;
3615 /* since we got an immediate return, we must signal the event object ourselves */
3616 ASSERT(SetEvent(sock
->writes
.overlapped
.hEvent
));
3618 sock
->writes
.status
= 0;
3620 dmsg(D_WIN32_IO
, "WIN32 I/O: Socket Send immediate return [%d,%d]",
3621 (int) wsabuf
[0].len
,
3622 (int) sock
->writes
.size
);
3626 status
= WSAGetLastError();
3627 if (status
== WSA_IO_PENDING
) /* operation queued? */
3629 sock
->writes
.iostate
= IOSTATE_QUEUED
;
3630 sock
->writes
.status
= status
;
3631 dmsg(D_WIN32_IO
, "WIN32 I/O: Socket Send queued [%d]",
3632 (int) wsabuf
[0].len
);
3634 else /* error occurred */
3636 struct gc_arena gc
= gc_new();
3637 ASSERT(SetEvent(sock
->writes
.overlapped
.hEvent
));
3638 sock
->writes
.iostate
= IOSTATE_IMMEDIATE_RETURN
;
3639 sock
->writes
.status
= status
;
3641 dmsg(D_WIN32_IO
, "WIN32 I/O: Socket Send error [%d]: %s",
3642 (int) wsabuf
[0].len
,
3643 strerror_win32(status
, &gc
));
3649 return sock
->writes
.iostate
;
3653 socket_finalize(SOCKET s
,
3654 struct overlapped_io
*io
,
3656 struct link_socket_actual
*from
)
3661 switch (io
->iostate
)
3663 case IOSTATE_QUEUED
:
3664 status
= WSAGetOverlappedResult(
3673 /* successful return for a queued operation */
3679 io
->iostate
= IOSTATE_INITIAL
;
3680 ASSERT(ResetEvent(io
->overlapped
.hEvent
));
3682 dmsg(D_WIN32_IO
, "WIN32 I/O: Socket Completion success [%d]", ret
);
3686 /* error during a queued operation */
3688 if (WSAGetLastError() != WSA_IO_INCOMPLETE
)
3690 /* if no error (i.e. just not finished yet), then DON'T execute this code */
3691 io
->iostate
= IOSTATE_INITIAL
;
3692 ASSERT(ResetEvent(io
->overlapped
.hEvent
));
3693 msg(D_WIN32_IO
| M_ERRNO
, "WIN32 I/O: Socket Completion error");
3698 case IOSTATE_IMMEDIATE_RETURN
:
3699 io
->iostate
= IOSTATE_INITIAL
;
3700 ASSERT(ResetEvent(io
->overlapped
.hEvent
));
3703 /* error return for a non-queued operation */
3704 WSASetLastError(io
->status
);
3706 msg(D_WIN32_IO
| M_ERRNO
, "WIN32 I/O: Socket Completion non-queued error");
3710 /* successful return for a non-queued operation */
3716 dmsg(D_WIN32_IO
, "WIN32 I/O: Socket Completion non-queued success [%d]", ret
);
3720 case IOSTATE_INITIAL
: /* were we called without proper queueing? */
3721 WSASetLastError(WSAEINVAL
);
3723 dmsg(D_WIN32_IO
, "WIN32 I/O: Socket Completion BAD STATE");
3730 /* return from address if requested */
3733 if (ret
>= 0 && io
->addr_defined
)
3735 /* TODO(jjo): streamline this mess */
3736 /* in this func we dont have relevant info about the PF_ of this
3737 * endpoint, as link_socket_actual will be zero for the 1st received packet
3739 * Test for inets PF_ possible sizes
3741 switch (io
->addrlen
)
3743 case sizeof(struct sockaddr_in
):
3744 case sizeof(struct sockaddr_in6
):
3745 /* TODO(jjo): for some reason (?) I'm getting 24,28 for AF_INET6
3747 case sizeof(struct sockaddr_in6
)-4:
3751 bad_address_length(io
->addrlen
, af_addr_size(io
->addr
.sin_family
));
3754 switch (io
->addr
.sin_family
)
3757 from
->dest
.addr
.in4
= io
->addr
;
3761 from
->dest
.addr
.in6
= io
->addr6
;
3767 CLEAR(from
->dest
.addr
);
3781 * Socket event notification
3785 socket_set(struct link_socket
*s
,
3786 struct event_set
*es
,
3787 unsigned int rwflags
,
3789 unsigned int *persistent
)
3793 if ((rwflags
& EVENT_READ
) && !stream_buf_read_setup(s
))
3795 ASSERT(!persistent
);
3796 rwflags
&= ~EVENT_READ
;
3800 if (rwflags
& EVENT_READ
)
3802 socket_recv_queue(s
, 0);
3806 /* if persistent is defined, call event_ctl only if rwflags has changed since last call */
3807 if (!persistent
|| *persistent
!= rwflags
)
3809 event_ctl(es
, socket_event_handle(s
), rwflags
, arg
);
3812 *persistent
= rwflags
;
3816 s
->rwflags_debug
= rwflags
;
3822 sd_close(socket_descriptor_t
*sd
)
3824 if (sd
&& socket_defined(*sd
))
3826 openvpn_close_socket(*sd
);
3827 *sd
= SOCKET_UNDEFINED
;
3831 #if UNIX_SOCK_SUPPORT
3834 * code for unix domain sockets
3838 sockaddr_unix_name(const struct sockaddr_un
*local
, const char *null
)
3840 if (local
&& local
->sun_family
== PF_UNIX
)
3842 return local
->sun_path
;
3851 create_socket_unix(void)
3853 socket_descriptor_t sd
;
3855 if ((sd
= socket(PF_UNIX
, SOCK_STREAM
, 0)) < 0)
3857 msg(M_ERR
, "Cannot create unix domain socket");
3860 /* set socket file descriptor to not pass across execs, so that
3861 * scripts don't have access to it */
3868 socket_bind_unix(socket_descriptor_t sd
,
3869 struct sockaddr_un
*local
,
3872 struct gc_arena gc
= gc_new();
3875 const mode_t orig_umask
= umask(0);
3878 if (bind(sd
, (struct sockaddr
*) local
, sizeof(struct sockaddr_un
)))
3880 const int errnum
= openvpn_errno();
3881 msg(M_FATAL
, "%s: Socket bind[%d] failed on unix domain socket %s: %s",
3884 sockaddr_unix_name(local
, "NULL"),
3885 strerror_ts(errnum
, &gc
));
3896 socket_accept_unix(socket_descriptor_t sd
,
3897 struct sockaddr_un
*remote
)
3899 socklen_t remote_len
= sizeof(struct sockaddr_un
);
3900 socket_descriptor_t ret
;
3903 ret
= accept(sd
, (struct sockaddr
*) remote
, &remote_len
);
3906 /* set socket file descriptor to not pass across execs, so that
3907 * scripts don't have access to it */
3914 socket_connect_unix(socket_descriptor_t sd
,
3915 struct sockaddr_un
*remote
)
3917 int status
= connect(sd
, (struct sockaddr
*) remote
, sizeof(struct sockaddr_un
));
3920 status
= openvpn_errno();
3926 sockaddr_unix_init(struct sockaddr_un
*local
, const char *path
)
3928 local
->sun_family
= PF_UNIX
;
3929 strncpynt(local
->sun_path
, path
, sizeof(local
->sun_path
));
3933 socket_delete_unix(const struct sockaddr_un
*local
)
3935 const char *name
= sockaddr_unix_name(local
, NULL
);
3937 if (name
&& strlen(name
))
3945 unix_socket_get_peer_uid_gid(const socket_descriptor_t sd
, int *uid
, int *gid
)
3947 #ifdef HAVE_GETPEEREID
3950 if (getpeereid(sd
, &u
, &g
) == -1)
3963 #elif defined(SO_PEERCRED)
3964 struct ucred peercred
;
3965 socklen_t so_len
= sizeof(peercred
);
3966 if (getsockopt(sd
, SOL_SOCKET
, SO_PEERCRED
, &peercred
, &so_len
) == -1)
3972 *uid
= peercred
.uid
;
3976 *gid
= peercred
.gid
;
3979 #else /* ifdef HAVE_GETPEEREID */
3981 #endif /* ifdef HAVE_GETPEEREID */
3984 #endif /* if UNIX_SOCK_SUPPORT */