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-2023 OpenVPN 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 along
20 * with this program; if not, write to the Free Software Foundation, Inc.,
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
36 #include "run_command.h"
46 * Convert sockflags/getaddr_flags into getaddr_flags
49 sf2gaf(const unsigned int getaddr_flags
,
50 const unsigned int sockflags
)
52 if (sockflags
& SF_HOST_RANDOMIZE
)
54 return getaddr_flags
| GETADDR_RANDOMIZE
;
63 * Functions related to the translation of DNS names to IP addresses.
66 get_addr_generic(sa_family_t af
, unsigned int flags
, const char *hostname
,
67 void *network
, unsigned int *netbits
,
68 int resolve_retry_seconds
, struct signal_info
*sig_info
,
71 char *endp
, *sep
, *var_host
= NULL
;
72 struct addrinfo
*ai
= NULL
;
79 msg(M_NONFATAL
, "Can't resolve null hostname!");
83 /* assign family specific default values */
88 max_bits
= sizeof(in_addr_t
) * 8;
93 max_bits
= sizeof(struct in6_addr
) * 8;
98 "Unsupported AF family passed to getaddrinfo for %s (%d)",
103 /* we need to modify the hostname received as input, but we don't want to
104 * touch it directly as it might be a constant string.
106 * Therefore, we clone the string here and free it at the end of the
108 var_host
= strdup(hostname
);
111 msg(M_NONFATAL
| M_ERRNO
,
112 "Can't allocate hostname buffer for getaddrinfo");
116 /* check if this hostname has a /bits suffix */
117 sep
= strchr(var_host
, '/');
120 bits
= strtoul(sep
+ 1, &endp
, 10);
121 if ((*endp
!= '\0') || (bits
> max_bits
))
123 msg(msglevel
, "IP prefix '%s': invalid '/bits' spec (%s)", hostname
,
130 ret
= openvpn_getaddrinfo(flags
& ~GETADDR_HOST_ORDER
, var_host
, NULL
,
131 resolve_retry_seconds
, sig_info
, af
, &ai
);
132 if ((ret
== 0) && network
)
134 struct in6_addr
*ip6
;
141 *ip4
= ((struct sockaddr_in
*)ai
->ai_addr
)->sin_addr
.s_addr
;
143 if (flags
& GETADDR_HOST_ORDER
)
151 *ip6
= ((struct sockaddr_in6
*)ai
->ai_addr
)->sin6_addr
;
155 /* can't get here because 'af' was previously checked */
157 "Unsupported AF family for %s (%d)", var_host
, af
);
167 /* restore '/' separator, if any */
180 getaddr(unsigned int flags
,
181 const char *hostname
,
182 int resolve_retry_seconds
,
184 struct signal_info
*sig_info
)
189 status
= get_addr_generic(AF_INET
, flags
, hostname
, &addr
, NULL
,
190 resolve_retry_seconds
, sig_info
,
211 get_ipv6_addr(const char *hostname
, struct in6_addr
*network
,
212 unsigned int *netbits
, int msglevel
)
214 if (get_addr_generic(AF_INET6
, GETADDR_RESOLVE
, hostname
, network
, netbits
,
215 0, NULL
, msglevel
) < 0)
220 return true; /* parsing OK, values set */
224 streqnull(const char *a
, const char *b
)
226 if (a
== NULL
&& b
== NULL
)
230 else if (a
== NULL
|| b
== NULL
)
241 * get_cached_dns_entry return 0 on success and -1
242 * otherwise. (like getaddrinfo)
245 get_cached_dns_entry(struct cached_dns_entry
*dns_cache
,
246 const char *hostname
,
247 const char *servname
,
250 struct addrinfo
**ai
)
252 struct cached_dns_entry
*ph
;
255 /* Only use flags that are relevant for the structure */
256 flags
= resolve_flags
& GETADDR_CACHE_MASK
;
258 for (ph
= dns_cache
; ph
; ph
= ph
->next
)
260 if (streqnull(ph
->hostname
, hostname
)
261 && streqnull(ph
->servname
, servname
)
262 && ph
->ai_family
== ai_family
263 && ph
->flags
== flags
)
274 do_preresolve_host(struct context
*c
,
275 const char *hostname
,
276 const char *servname
,
283 if (get_cached_dns_entry(c
->c1
.dns_cache
,
290 /* entry already cached, return success */
294 status
= openvpn_getaddrinfo(flags
, hostname
, servname
,
295 c
->options
.resolve_retry_seconds
, NULL
,
299 struct cached_dns_entry
*ph
;
301 ALLOC_OBJ_CLEAR_GC(ph
, struct cached_dns_entry
, &c
->gc
);
303 ph
->hostname
= hostname
;
304 ph
->servname
= servname
;
305 ph
->flags
= flags
& GETADDR_CACHE_MASK
;
307 if (!c
->c1
.dns_cache
)
309 c
->c1
.dns_cache
= ph
;
313 struct cached_dns_entry
*prev
= c
->c1
.dns_cache
;
321 gc_addspecial(ai
, &gc_freeaddrinfo_callback
, &c
->gc
);
328 do_preresolve(struct context
*c
)
331 struct connection_list
*l
= c
->options
.connection_list
;
332 const unsigned int preresolve_flags
= GETADDR_RESOLVE
333 |GETADDR_UPDATE_MANAGEMENT_STATE
334 |GETADDR_MENTION_RESOLVE_RETRY
338 for (i
= 0; i
< l
->len
; ++i
)
342 int flags
= preresolve_flags
;
344 struct connection_entry
*ce
= c
->options
.connection_list
->array
[i
];
346 if (proto_is_dgram(ce
->proto
))
348 flags
|= GETADDR_DATAGRAM
;
351 if (c
->options
.sockflags
& SF_HOST_RANDOMIZE
)
353 flags
|= GETADDR_RANDOMIZE
;
356 if (c
->options
.ip_remote_hint
)
358 remote
= c
->options
.ip_remote_hint
;
365 /* HTTP remote hostname does not need to be resolved */
366 if (!ce
->http_proxy_options
)
368 status
= do_preresolve_host(c
, remote
, ce
->remote_port
,
376 /* Preresolve proxy */
377 if (ce
->http_proxy_options
)
379 status
= do_preresolve_host(c
,
380 ce
->http_proxy_options
->server
,
381 ce
->http_proxy_options
->port
,
391 if (ce
->socks_proxy_server
)
393 status
= do_preresolve_host(c
,
394 ce
->socks_proxy_server
,
395 ce
->socks_proxy_port
,
406 flags
|= GETADDR_PASSIVE
;
407 flags
&= ~GETADDR_RANDOMIZE
;
408 status
= do_preresolve_host(c
, ce
->local
, ce
->local_port
,
421 throw_signal_soft(SIGHUP
, "Preresolving failed");
425 * Translate IPv4/IPv6 addr or hostname into struct addrinfo
426 * If resolve error, try again for resolve_retry_seconds seconds.
429 openvpn_getaddrinfo(unsigned int flags
,
430 const char *hostname
,
431 const char *servname
,
432 int resolve_retry_seconds
,
433 struct signal_info
*sig_info
,
435 struct addrinfo
**res
)
437 struct addrinfo hints
;
439 struct signal_info sigrec
= {0};
440 int msglevel
= (flags
& GETADDR_FATAL
) ? M_FATAL
: D_RESOLVE_ERRORS
;
441 struct gc_arena gc
= gc_new();
442 const char *print_hostname
;
443 const char *print_servname
;
447 ASSERT(hostname
|| servname
);
448 ASSERT(!(flags
& GETADDR_HOST_ORDER
));
452 print_servname
= servname
;
459 if (flags
& GETADDR_MSG_VIRT_OUT
)
461 msglevel
|= M_MSG_VIRT_OUT
;
464 if ((flags
& (GETADDR_FATAL_ON_SIGNAL
|GETADDR_WARN_ON_SIGNAL
))
470 /* try numeric ipv6 addr first */
472 hints
.ai_family
= ai_family
;
473 hints
.ai_flags
= AI_NUMERICHOST
;
475 if (flags
& GETADDR_PASSIVE
)
477 hints
.ai_flags
|= AI_PASSIVE
;
480 if (flags
& GETADDR_DATAGRAM
)
482 hints
.ai_socktype
= SOCK_DGRAM
;
486 hints
.ai_socktype
= SOCK_STREAM
;
489 status
= getaddrinfo(hostname
, servname
, &hints
, res
);
491 if (status
!= 0) /* parse as numeric address failed? */
493 const int fail_wait_interval
= 5; /* seconds */
494 /* Add +4 to cause integer division rounding up (1 + 4) = 5, (0+4)/5=0 */
495 int resolve_retries
= (flags
& GETADDR_TRY_ONCE
) ? 1 :
496 ((resolve_retry_seconds
+ 4)/ fail_wait_interval
);
500 if (hostname
&& (flags
& GETADDR_RANDOMIZE
))
502 hostname
= hostname_randomize(hostname
, &gc
);
507 print_hostname
= hostname
;
511 print_hostname
= "undefined";
514 fmt
= "RESOLVE: Cannot resolve host address: %s:%s (%s)";
515 if ((flags
& GETADDR_MENTION_RESOLVE_RETRY
)
516 && !resolve_retry_seconds
)
518 fmt
= "RESOLVE: Cannot resolve host address: %s:%s (%s) "
519 "(I would have retried this name query if you had "
520 "specified the --resolv-retry option.)";
523 if (!(flags
& GETADDR_RESOLVE
) || status
== EAI_FAIL
)
525 msg(msglevel
, "RESOLVE: Cannot parse IP address: %s:%s (%s)",
526 print_hostname
, print_servname
, gai_strerror(status
));
530 #ifdef ENABLE_MANAGEMENT
531 if (flags
& GETADDR_UPDATE_MANAGEMENT_STATE
)
535 management_set_state(management
,
536 OPENVPN_STATE_RESOLVE
,
552 /* force resolv.conf reload */
555 /* try hostname lookup */
556 hints
.ai_flags
&= ~AI_NUMERICHOST
;
558 "GETADDRINFO flags=0x%04x ai_family=%d ai_socktype=%d",
559 flags
, hints
.ai_family
, hints
.ai_socktype
);
560 status
= getaddrinfo(hostname
, servname
, &hints
, res
);
564 get_signal(&sig_info
->signal_received
);
565 if (sig_info
->signal_received
) /* were we interrupted by a signal? */
567 /* why are we overwriting SIGUSR1 ? */
568 if (sig_info
->signal_received
== SIGUSR1
) /* ignore SIGUSR1 */
571 "RESOLVE: Ignored SIGUSR1 signal received during "
572 "DNS resolution attempt");
573 signal_reset(sig_info
);
577 /* turn success into failure (interrupted syscall) */
583 status
= EAI_AGAIN
; /* = temporary failure */
597 /* resolve lookup failed, should we
598 * continue or fail? */
600 if (resolve_retries
> 0)
602 level
= D_RESOLVE_ERRORS
;
609 gai_strerror(status
));
611 if (--resolve_retries
<= 0)
616 management_sleep(fail_wait_interval
);
621 /* hostname resolve succeeded */
624 * Do not choose an IP Addresse by random or change the order *
625 * of IP addresses, doing so will break RFC 3484 address selection *
630 /* IP address parse succeeded */
631 if (flags
& GETADDR_RANDOMIZE
)
634 "WARNING: ignoring --remote-random-hostname because the "
635 "hostname is an IP address");
640 if (sig_info
&& sig_info
->signal_received
)
643 if (flags
& GETADDR_FATAL_ON_SIGNAL
)
647 else if (flags
& GETADDR_WARN_ON_SIGNAL
)
651 msg(level
, "RESOLVE: signal received during DNS resolution attempt");
659 * We do our own inet_aton because the glibc function
660 * isn't very good about error checking.
663 openvpn_inet_aton(const char *dotted_quad
, struct in_addr
*addr
)
665 unsigned int a
, b
, c
, d
;
668 if (sscanf(dotted_quad
, "%u.%u.%u.%u", &a
, &b
, &c
, &d
) == 4)
670 if (a
< 256 && b
< 256 && c
< 256 && d
< 256)
672 addr
->s_addr
= htonl(a
<<24 | b
<<16 | c
<<8 | d
);
673 return OIA_IP
; /* good dotted quad */
676 if (string_class(dotted_quad
, CC_DIGIT
|CC_DOT
, 0))
678 return OIA_ERROR
; /* probably a badly formatted dotted quad */
682 return OIA_HOSTNAME
; /* probably a hostname */
687 ip_addr_dotted_quad_safe(const char *dotted_quad
)
689 /* verify non-NULL */
695 /* verify length is within limits */
696 if (strlen(dotted_quad
) > 15)
701 /* verify that all chars are either numeric or '.' and that no numeric
702 * substring is greater than 3 chars */
705 const char *p
= dotted_quad
;
710 if (c
>= '0' && c
<= '9')
729 /* verify that string will convert to IP address */
732 return openvpn_inet_aton(dotted_quad
, &a
) == OIA_IP
;
737 ipv6_addr_safe(const char *ipv6_text_addr
)
739 /* verify non-NULL */
745 /* verify length is within limits */
746 if (strlen(ipv6_text_addr
) > INET6_ADDRSTRLEN
)
751 /* verify that string will convert to IPv6 address */
754 return inet_pton( AF_INET6
, ipv6_text_addr
, &a6
) == 1;
759 dns_addr_safe(const char *addr
)
763 const size_t len
= strlen(addr
);
764 return len
> 0 && len
<= 255 && string_class(addr
, CC_ALNUM
|CC_DASH
|CC_DOT
, 0);
773 ip_or_dns_addr_safe(const char *addr
, const bool allow_fqdn
)
775 if (ip_addr_dotted_quad_safe(addr
))
781 return dns_addr_safe(addr
);
790 mac_addr_safe(const char *mac_addr
)
792 /* verify non-NULL */
798 /* verify length is within limits */
799 if (strlen(mac_addr
) > 17)
804 /* verify that all chars are either alphanumeric or ':' and that no
805 * alphanumeric substring is greater than 2 chars */
808 const char *p
= mac_addr
;
813 if ( (c
>= '0' && c
<= '9') || (c
>= 'a' && c
<= 'f') || (c
>= 'A' && c
<= 'F') )
832 /* error-checking is left to script invoked in lladdr.c */
837 socket_get_sndbuf(socket_descriptor_t sd
)
839 #if defined(SOL_SOCKET) && defined(SO_SNDBUF)
844 if (getsockopt(sd
, SOL_SOCKET
, SO_SNDBUF
, (void *) &val
, &len
) == 0
845 && len
== sizeof(val
))
854 socket_set_sndbuf(socket_descriptor_t sd
, int size
)
856 #if defined(SOL_SOCKET) && defined(SO_SNDBUF)
857 if (setsockopt(sd
, SOL_SOCKET
, SO_SNDBUF
, (void *) &size
, sizeof(size
)) != 0)
859 msg(M_WARN
, "NOTE: setsockopt SO_SNDBUF=%d failed", size
);
865 socket_get_rcvbuf(socket_descriptor_t sd
)
867 #if defined(SOL_SOCKET) && defined(SO_RCVBUF)
872 if (getsockopt(sd
, SOL_SOCKET
, SO_RCVBUF
, (void *) &val
, &len
) == 0
873 && len
== sizeof(val
))
882 socket_set_rcvbuf(socket_descriptor_t sd
, int size
)
884 #if defined(SOL_SOCKET) && defined(SO_RCVBUF)
885 if (setsockopt(sd
, SOL_SOCKET
, SO_RCVBUF
, (void *) &size
, sizeof(size
)) != 0)
887 msg(M_WARN
, "NOTE: setsockopt SO_RCVBUF=%d failed", size
);
895 socket_set_buffers(socket_descriptor_t fd
, const struct socket_buffer_size
*sbs
)
899 const int sndbuf_old
= socket_get_sndbuf(fd
);
900 const int rcvbuf_old
= socket_get_rcvbuf(fd
);
904 socket_set_sndbuf(fd
, sbs
->sndbuf
);
909 socket_set_rcvbuf(fd
, sbs
->rcvbuf
);
912 msg(D_OSBUF
, "Socket Buffers: R=[%d->%d] S=[%d->%d]",
914 socket_get_rcvbuf(fd
),
916 socket_get_sndbuf(fd
));
921 * Set other socket options
925 socket_set_tcp_nodelay(socket_descriptor_t sd
, int state
)
927 #if defined(_WIN32) || (defined(IPPROTO_TCP) && defined(TCP_NODELAY))
928 if (setsockopt(sd
, IPPROTO_TCP
, TCP_NODELAY
, (void *) &state
, sizeof(state
)) != 0)
930 msg(M_WARN
, "NOTE: setsockopt TCP_NODELAY=%d failed", state
);
935 dmsg(D_OSBUF
, "Socket flags: TCP_NODELAY=%d succeeded", state
);
938 #else /* if defined(_WIN32) || (defined(IPPROTO_TCP) && defined(TCP_NODELAY)) */
939 msg(M_WARN
, "NOTE: setsockopt TCP_NODELAY=%d failed (No kernel support)", state
);
945 socket_set_mark(socket_descriptor_t sd
, int mark
)
947 #if defined(TARGET_LINUX) && HAVE_DECL_SO_MARK
948 if (mark
&& setsockopt(sd
, SOL_SOCKET
, SO_MARK
, (void *) &mark
, sizeof(mark
)) != 0)
950 msg(M_WARN
, "NOTE: setsockopt SO_MARK=%d failed", mark
);
956 socket_set_flags(socket_descriptor_t sd
, unsigned int sockflags
)
958 /* SF_TCP_NODELAY doesn't make sense for dco-win */
959 if ((sockflags
& SF_TCP_NODELAY
) && (!(sockflags
& SF_DCO_WIN
)))
961 return socket_set_tcp_nodelay(sd
, 1);
970 link_socket_update_flags(struct link_socket
*ls
, unsigned int sockflags
)
972 if (ls
&& socket_defined(ls
->sd
))
974 ls
->sockflags
|= sockflags
;
975 return socket_set_flags(ls
->sd
, ls
->sockflags
);
984 link_socket_update_buffer_sizes(struct link_socket
*ls
, int rcvbuf
, int sndbuf
)
986 if (ls
&& socket_defined(ls
->sd
))
988 ls
->socket_buffer_sizes
.sndbuf
= sndbuf
;
989 ls
->socket_buffer_sizes
.rcvbuf
= rcvbuf
;
990 socket_set_buffers(ls
->sd
, &ls
->socket_buffer_sizes
);
995 * SOCKET INITIALIZATION CODE.
996 * Create a TCP/UDP socket
1000 create_socket_tcp(struct addrinfo
*addrinfo
)
1002 socket_descriptor_t sd
;
1005 ASSERT(addrinfo
->ai_socktype
== SOCK_STREAM
);
1007 if ((sd
= socket(addrinfo
->ai_family
, addrinfo
->ai_socktype
, addrinfo
->ai_protocol
)) < 0)
1009 msg(M_ERR
, "Cannot create TCP socket");
1012 #ifndef _WIN32 /* using SO_REUSEADDR on Windows will cause bind to succeed on port conflicts! */
1013 /* set SO_REUSEADDR on socket */
1016 if (setsockopt(sd
, SOL_SOCKET
, SO_REUSEADDR
,
1017 (void *) &on
, sizeof(on
)) < 0)
1019 msg(M_ERR
, "TCP: Cannot setsockopt SO_REUSEADDR on TCP socket");
1024 /* set socket file descriptor to not pass across execs, so that
1025 * scripts don't have access to it */
1031 static socket_descriptor_t
1032 create_socket_udp(struct addrinfo
*addrinfo
, const unsigned int flags
)
1034 socket_descriptor_t sd
;
1037 ASSERT(addrinfo
->ai_socktype
== SOCK_DGRAM
);
1039 if ((sd
= socket(addrinfo
->ai_family
, addrinfo
->ai_socktype
, addrinfo
->ai_protocol
)) < 0)
1041 msg(M_ERR
, "UDP: Cannot create UDP/UDP6 socket");
1043 #if ENABLE_IP_PKTINFO
1044 else if (flags
& SF_USE_IP_PKTINFO
)
1047 if (addrinfo
->ai_family
== AF_INET
)
1049 #if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST)
1050 if (setsockopt(sd
, SOL_IP
, IP_PKTINFO
,
1051 (void *)&pad
, sizeof(pad
)) < 0)
1053 msg(M_ERR
, "UDP: failed setsockopt for IP_PKTINFO");
1055 #elif defined(IP_RECVDSTADDR)
1056 if (setsockopt(sd
, IPPROTO_IP
, IP_RECVDSTADDR
,
1057 (void *)&pad
, sizeof(pad
)) < 0)
1059 msg(M_ERR
, "UDP: failed setsockopt for IP_RECVDSTADDR");
1061 #else /* if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST) */
1062 #error ENABLE_IP_PKTINFO is set without IP_PKTINFO xor IP_RECVDSTADDR (fix syshead.h)
1065 else if (addrinfo
->ai_family
== AF_INET6
)
1067 #ifndef IPV6_RECVPKTINFO /* Some older Darwin platforms require this */
1068 if (setsockopt(sd
, IPPROTO_IPV6
, IPV6_PKTINFO
,
1069 (void *)&pad
, sizeof(pad
)) < 0)
1071 if (setsockopt(sd
, IPPROTO_IPV6
, IPV6_RECVPKTINFO
,
1072 (void *)&pad
, sizeof(pad
)) < 0)
1074 { msg(M_ERR
, "UDP: failed setsockopt for IPV6_RECVPKTINFO");}
1077 #endif /* if ENABLE_IP_PKTINFO */
1079 /* set socket file descriptor to not pass across execs, so that
1080 * scripts don't have access to it */
1087 bind_local(struct link_socket
*sock
, const sa_family_t ai_family
)
1089 /* bind to local address/port */
1090 if (sock
->bind_local
)
1092 if (sock
->socks_proxy
&& sock
->info
.proto
== PROTO_UDP
)
1094 socket_bind(sock
->ctrl_sd
, sock
->info
.lsa
->bind_local
,
1095 ai_family
, "SOCKS", false);
1099 socket_bind(sock
->sd
, sock
->info
.lsa
->bind_local
,
1101 "TCP/UDP", sock
->info
.bind_ipv6_only
);
1107 create_socket(struct link_socket
*sock
, struct addrinfo
*addr
)
1109 if (addr
->ai_protocol
== IPPROTO_UDP
|| addr
->ai_socktype
== SOCK_DGRAM
)
1111 sock
->sd
= create_socket_udp(addr
, sock
->sockflags
);
1112 sock
->sockflags
|= SF_GETADDRINFO_DGRAM
;
1114 /* Assume that control socket and data socket to the socks proxy
1115 * are using the same IP family */
1116 if (sock
->socks_proxy
)
1118 /* Construct a temporary addrinfo to create the socket,
1119 * currently resolve two remote addresses is not supported,
1120 * TODO: Rewrite the whole resolve_remote */
1121 struct addrinfo addrinfo_tmp
= *addr
;
1122 addrinfo_tmp
.ai_socktype
= SOCK_STREAM
;
1123 addrinfo_tmp
.ai_protocol
= IPPROTO_TCP
;
1124 sock
->ctrl_sd
= create_socket_tcp(&addrinfo_tmp
);
1127 else if (addr
->ai_protocol
== IPPROTO_TCP
|| addr
->ai_socktype
== SOCK_STREAM
)
1129 sock
->sd
= create_socket_tcp(addr
);
1135 /* Set af field of sock->info, so it always reflects the address family
1136 * of the created socket */
1137 sock
->info
.af
= addr
->ai_family
;
1139 /* set socket buffers based on --sndbuf and --rcvbuf options */
1140 socket_set_buffers(sock
->sd
, &sock
->socket_buffer_sizes
);
1142 /* set socket to --mark packets with given value */
1143 socket_set_mark(sock
->sd
, sock
->mark
);
1145 #if defined(TARGET_LINUX)
1148 msg(M_INFO
, "Using bind-dev %s", sock
->bind_dev
);
1149 if (setsockopt(sock
->sd
, SOL_SOCKET
, SO_BINDTODEVICE
, sock
->bind_dev
, strlen(sock
->bind_dev
) + 1) != 0)
1151 msg(M_WARN
|M_ERRNO
, "WARN: setsockopt SO_BINDTODEVICE=%s failed", sock
->bind_dev
);
1157 bind_local(sock
, addr
->ai_family
);
1160 #ifdef TARGET_ANDROID
1162 protect_fd_nonlocal(int fd
, const struct sockaddr
*addr
)
1166 msg(M_FATAL
, "Required management interface not available.");
1169 /* pass socket FD to management interface to pass on to VPNService API
1170 * as "protected socket" (exempt from being routed into tunnel)
1172 if (addr_local(addr
))
1174 msg(D_SOCKET_DEBUG
, "Address is local, not protecting socket fd %d", fd
);
1178 msg(D_SOCKET_DEBUG
, "Protecting socket fd %d", fd
);
1179 management
->connection
.fdtosend
= fd
;
1180 management_android_control(management
, "PROTECTFD", __func__
);
1185 * Functions used for establishing a TCP stream connection.
1188 socket_do_listen(socket_descriptor_t sd
,
1189 const struct addrinfo
*local
,
1191 bool do_set_nonblock
)
1193 struct gc_arena gc
= gc_new();
1197 msg(M_INFO
, "Listening for incoming TCP connection on %s",
1198 print_sockaddr(local
->ai_addr
, &gc
));
1201 msg(M_ERR
, "TCP: listen() failed");
1205 /* set socket to non-blocking mode */
1206 if (do_set_nonblock
)
1215 socket_do_accept(socket_descriptor_t sd
,
1216 struct link_socket_actual
*act
,
1219 /* af_addr_size WILL return 0 in this case if AFs other than AF_INET
1220 * are compiled because act is empty here.
1221 * could use getsockname() to support later remote_len check
1223 socklen_t remote_len_af
= af_addr_size(act
->dest
.addr
.sa
.sa_family
);
1224 socklen_t remote_len
= sizeof(act
->dest
.addr
);
1225 socket_descriptor_t new_sd
= SOCKET_UNDEFINED
;
1231 new_sd
= getpeername(sd
, &act
->dest
.addr
.sa
, &remote_len
);
1233 if (!socket_defined(new_sd
))
1235 msg(D_LINK_ERRORS
| M_ERRNO
, "TCP: getpeername() failed");
1244 new_sd
= accept(sd
, &act
->dest
.addr
.sa
, &remote_len
);
1247 #if 0 /* For debugging only, test the effect of accept() failures */
1258 if (!socket_defined(new_sd
))
1260 msg(D_LINK_ERRORS
| M_ERRNO
, "TCP: accept(%d) failed", (int)sd
);
1262 /* only valid if we have remote_len_af!=0 */
1263 else if (remote_len_af
&& remote_len
!= remote_len_af
)
1265 msg(D_LINK_ERRORS
, "TCP: Received strange incoming connection with unknown address length=%d", remote_len
);
1266 openvpn_close_socket(new_sd
);
1267 new_sd
= SOCKET_UNDEFINED
;
1271 /* set socket file descriptor to not pass across execs, so that
1272 * scripts don't have access to it */
1279 tcp_connection_established(const struct link_socket_actual
*act
)
1281 struct gc_arena gc
= gc_new();
1282 msg(M_INFO
, "TCP connection established with %s",
1283 print_link_socket_actual(act
, &gc
));
1287 static socket_descriptor_t
1288 socket_listen_accept(socket_descriptor_t sd
,
1289 struct link_socket_actual
*act
,
1290 const char *remote_dynamic
,
1291 const struct addrinfo
*local
,
1294 volatile int *signal_received
)
1296 struct gc_arena gc
= gc_new();
1297 /* struct openvpn_sockaddr *remote = &act->dest; */
1298 struct openvpn_sockaddr remote_verify
= act
->dest
;
1299 socket_descriptor_t new_sd
= SOCKET_UNDEFINED
;
1302 socket_do_listen(sd
, local
, do_listen
, true);
1311 openvpn_fd_set(sd
, &reads
);
1315 status
= select(sd
+ 1, &reads
, NULL
, NULL
, &tv
);
1317 get_signal(signal_received
);
1318 if (*signal_received
)
1326 msg(D_LINK_ERRORS
| M_ERRNO
, "TCP: select() failed");
1331 management_sleep(1);
1335 new_sd
= socket_do_accept(sd
, act
, nowait
);
1337 if (socket_defined(new_sd
))
1339 struct addrinfo
*ai
= NULL
;
1342 openvpn_getaddrinfo(0, remote_dynamic
, NULL
, 1, NULL
,
1343 remote_verify
.addr
.sa
.sa_family
, &ai
);
1346 if (ai
&& !addrlist_match(&remote_verify
, ai
))
1349 "TCP NOTE: Rejected connection attempt from %s due to --remote setting",
1350 print_link_socket_actual(act
, &gc
));
1351 if (openvpn_close_socket(new_sd
))
1353 msg(M_ERR
, "TCP: close socket failed (new_sd)");
1366 management_sleep(1);
1369 if (!nowait
&& openvpn_close_socket(sd
))
1371 msg(M_ERR
, "TCP: close socket failed (sd)");
1374 tcp_connection_established(act
);
1381 socket_bind(socket_descriptor_t sd
,
1382 struct addrinfo
*local
,
1387 struct gc_arena gc
= gc_new();
1390 * getaddrinfo for the bind address might return multiple AF_INET/AF_INET6
1391 * entries for the requested protocol.
1392 * For example if an address has multiple A records
1393 * What is the correct way to deal with it?
1396 struct addrinfo
*cur
;
1401 /* find the first addrinfo with correct ai_family */
1402 for (cur
= local
; cur
; cur
= cur
->ai_next
)
1404 if (cur
->ai_family
== ai_family
)
1411 msg(M_FATAL
, "%s: Socket bind failed: Addr to bind has no %s record",
1412 prefix
, addr_family_name(ai_family
));
1415 if (ai_family
== AF_INET6
)
1417 int v6only
= ipv6only
? 1 : 0; /* setsockopt must have an "int" */
1419 msg(M_INFO
, "setsockopt(IPV6_V6ONLY=%d)", v6only
);
1420 if (setsockopt(sd
, IPPROTO_IPV6
, IPV6_V6ONLY
, (void *) &v6only
, sizeof(v6only
)))
1422 msg(M_NONFATAL
|M_ERRNO
, "Setting IPV6_V6ONLY=%d failed", v6only
);
1425 if (bind(sd
, cur
->ai_addr
, cur
->ai_addrlen
))
1427 msg(M_FATAL
| M_ERRNO
, "%s: Socket bind failed on local address %s",
1429 print_sockaddr_ex(local
->ai_addr
, ":", PS_SHOW_PORT
, &gc
));
1435 openvpn_connect(socket_descriptor_t sd
,
1436 const struct sockaddr
*remote
,
1437 int connect_timeout
,
1438 volatile int *signal_received
)
1442 #ifdef TARGET_ANDROID
1443 protect_fd_nonlocal(sd
, remote
);
1447 status
= connect(sd
, remote
, af_addr_size(remote
->sa_family
));
1450 status
= openvpn_errno();
1454 status
== WSAEWOULDBLOCK
1456 status
== EINPROGRESS
1463 struct pollfd fds
[1];
1465 fds
[0].events
= POLLOUT
;
1466 status
= poll(fds
, 1, (connect_timeout
> 0) ? 1000 : 0);
1472 openvpn_fd_set(sd
, &writes
);
1473 tv
.tv_sec
= (connect_timeout
> 0) ? 1 : 0;
1476 status
= select(sd
+ 1, NULL
, &writes
, NULL
, &tv
);
1478 if (signal_received
)
1480 get_signal(signal_received
);
1481 if (*signal_received
)
1489 status
= openvpn_errno();
1494 if (--connect_timeout
< 0)
1497 status
= WSAETIMEDOUT
;
1503 management_sleep(0);
1513 if (getsockopt(sd
, SOL_SOCKET
, SO_ERROR
, (void *) &val
, &len
) == 0
1514 && len
== sizeof(val
))
1520 status
= openvpn_errno();
1531 set_actual_address(struct link_socket_actual
*actual
, struct addrinfo
*ai
)
1536 if (ai
->ai_family
== AF_INET
)
1538 actual
->dest
.addr
.in4
=
1539 *((struct sockaddr_in
*) ai
->ai_addr
);
1541 else if (ai
->ai_family
== AF_INET6
)
1543 actual
->dest
.addr
.in6
=
1544 *((struct sockaddr_in6
*) ai
->ai_addr
);
1554 socket_connect(socket_descriptor_t
*sd
,
1555 const struct sockaddr
*dest
,
1556 const int connect_timeout
,
1557 struct signal_info
*sig_info
)
1559 struct gc_arena gc
= gc_new();
1562 msg(M_INFO
, "Attempting to establish TCP connection with %s",
1563 print_sockaddr(dest
, &gc
));
1565 #ifdef ENABLE_MANAGEMENT
1568 management_set_state(management
,
1569 OPENVPN_STATE_TCP_CONNECT
,
1578 /* Set the actual address */
1579 status
= openvpn_connect(*sd
, dest
, connect_timeout
, &sig_info
->signal_received
);
1581 get_signal(&sig_info
->signal_received
);
1582 if (sig_info
->signal_received
)
1590 msg(D_LINK_ERRORS
, "TCP: connect to %s failed: %s",
1591 print_sockaddr(dest
, &gc
), strerror(status
));
1593 openvpn_close_socket(*sd
);
1594 *sd
= SOCKET_UNDEFINED
;
1595 register_signal(sig_info
, SIGUSR1
, "connection-failed");
1596 sig_info
->source
= SIG_SOURCE_CONNECTION_FAILED
;
1600 msg(M_INFO
, "TCP connection established with %s",
1601 print_sockaddr(dest
, &gc
));
1609 * Stream buffer handling prototypes -- stream_buf is a helper class
1610 * to assist in the packetization of stream transport protocols
1615 stream_buf_init(struct stream_buf
*sb
, struct buffer
*buf
,
1616 const unsigned int sockflags
, const int proto
);
1619 stream_buf_close(struct stream_buf
*sb
);
1622 stream_buf_added(struct stream_buf
*sb
, int length_added
);
1624 /* For stream protocols, allocate a buffer to build up packet.
1625 * Called after frame has been finalized. */
1628 socket_frame_init(const struct frame
*frame
, struct link_socket
*sock
)
1631 overlapped_io_init(&sock
->reads
, frame
, FALSE
);
1632 overlapped_io_init(&sock
->writes
, frame
, TRUE
);
1633 sock
->rw_handle
.read
= sock
->reads
.overlapped
.hEvent
;
1634 sock
->rw_handle
.write
= sock
->writes
.overlapped
.hEvent
;
1637 if (link_socket_connection_oriented(sock
))
1640 stream_buf_init(&sock
->stream_buf
,
1641 &sock
->reads
.buf_init
,
1645 alloc_buf_sock_tun(&sock
->stream_buf_data
, frame
);
1647 stream_buf_init(&sock
->stream_buf
,
1648 &sock
->stream_buf_data
,
1656 resolve_bind_local(struct link_socket
*sock
, const sa_family_t af
)
1658 struct gc_arena gc
= gc_new();
1660 /* resolve local address if undefined */
1661 if (!sock
->info
.lsa
->bind_local
)
1663 int flags
= GETADDR_RESOLVE
| GETADDR_WARN_ON_SIGNAL
1664 |GETADDR_FATAL
| GETADDR_PASSIVE
;
1667 if (proto_is_dgram(sock
->info
.proto
))
1669 flags
|= GETADDR_DATAGRAM
;
1672 /* will return AF_{INET|INET6}from local_host */
1673 status
= get_cached_dns_entry(sock
->dns_cache
,
1678 &sock
->info
.lsa
->bind_local
);
1682 status
= openvpn_getaddrinfo(flags
, sock
->local_host
, sock
->local_port
, 0,
1683 NULL
, af
, &sock
->info
.lsa
->bind_local
);
1688 msg(M_FATAL
, "getaddrinfo() failed for local \"%s:%s\": %s",
1689 sock
->local_host
, sock
->local_port
,
1690 gai_strerror(status
));
1698 resolve_remote(struct link_socket
*sock
,
1700 const char **remote_dynamic
,
1701 struct signal_info
*sig_info
)
1703 volatile int *signal_received
= sig_info
? &sig_info
->signal_received
: NULL
;
1704 struct gc_arena gc
= gc_new();
1706 /* resolve remote address if undefined */
1707 if (!sock
->info
.lsa
->remote_list
)
1709 if (sock
->remote_host
)
1711 unsigned int flags
= sf2gaf(GETADDR_RESOLVE
|GETADDR_UPDATE_MANAGEMENT_STATE
, sock
->sockflags
);
1714 struct addrinfo
*ai
;
1715 if (proto_is_dgram(sock
->info
.proto
))
1717 flags
|= GETADDR_DATAGRAM
;
1720 if (sock
->resolve_retry_seconds
== RESOLV_RETRY_INFINITE
)
1724 flags
|= (GETADDR_TRY_ONCE
| GETADDR_FATAL
);
1728 else if (phase
== 1)
1730 if (sock
->resolve_retry_seconds
)
1736 flags
|= (GETADDR_FATAL
| GETADDR_MENTION_RESOLVE_RETRY
);
1740 else if (phase
== 2)
1742 if (sock
->resolve_retry_seconds
)
1744 flags
|= GETADDR_FATAL
;
1745 retry
= sock
->resolve_retry_seconds
;
1758 status
= get_cached_dns_entry(sock
->dns_cache
,
1765 status
= openvpn_getaddrinfo(flags
, sock
->remote_host
, sock
->remote_port
,
1766 retry
, sig_info
, sock
->info
.af
, &ai
);
1771 sock
->info
.lsa
->remote_list
= ai
;
1772 sock
->info
.lsa
->current_remote
= ai
;
1774 dmsg(D_SOCKET_DEBUG
,
1775 "RESOLVE_REMOTE flags=0x%04x phase=%d rrs=%d sig=%d status=%d",
1779 signal_received
? *signal_received
: -1,
1782 if (signal_received
&& *signal_received
)
1788 if (signal_received
)
1790 /* potential overwrite of signal */
1791 register_signal(sig_info
, SIGUSR1
, "socks-resolve-failure");
1798 /* should we re-use previous active remote address? */
1799 if (link_socket_actual_defined(&sock
->info
.lsa
->actual
))
1801 msg(M_INFO
, "TCP/UDP: Preserving recently used remote address: %s",
1802 print_link_socket_actual(&sock
->info
.lsa
->actual
, &gc
));
1805 *remote_dynamic
= NULL
;
1810 CLEAR(sock
->info
.lsa
->actual
);
1811 if (sock
->info
.lsa
->current_remote
)
1813 set_actual_address(&sock
->info
.lsa
->actual
,
1814 sock
->info
.lsa
->current_remote
);
1824 struct link_socket
*
1825 link_socket_new(void)
1827 struct link_socket
*sock
;
1829 ALLOC_OBJ_CLEAR(sock
, struct link_socket
);
1830 sock
->sd
= SOCKET_UNDEFINED
;
1831 sock
->ctrl_sd
= SOCKET_UNDEFINED
;
1836 link_socket_init_phase1(struct context
*c
, int mode
)
1838 struct link_socket
*sock
= c
->c2
.link_socket
;
1839 struct options
*o
= &c
->options
;
1842 const char *remote_host
= o
->ce
.remote
;
1843 const char *remote_port
= o
->ce
.remote_port
;
1845 sock
->local_host
= o
->ce
.local
;
1846 sock
->local_port
= o
->ce
.local_port
;
1847 sock
->remote_host
= remote_host
;
1848 sock
->remote_port
= remote_port
;
1849 sock
->dns_cache
= c
->c1
.dns_cache
;
1850 sock
->http_proxy
= c
->c1
.http_proxy
;
1851 sock
->socks_proxy
= c
->c1
.socks_proxy
;
1852 sock
->bind_local
= o
->ce
.bind_local
;
1853 sock
->resolve_retry_seconds
= o
->resolve_retry_seconds
;
1854 sock
->mtu_discover_type
= o
->ce
.mtu_discover_type
;
1857 sock
->gremlin
= o
->gremlin
;
1860 sock
->socket_buffer_sizes
.rcvbuf
= o
->rcvbuf
;
1861 sock
->socket_buffer_sizes
.sndbuf
= o
->sndbuf
;
1863 sock
->sockflags
= o
->sockflags
;
1865 if (o
->port_share_host
&& o
->port_share_port
)
1867 sock
->sockflags
|= SF_PORT_SHARE
;
1870 sock
->mark
= o
->mark
;
1871 sock
->bind_dev
= o
->bind_dev
;
1873 sock
->info
.proto
= o
->ce
.proto
;
1874 sock
->info
.af
= o
->ce
.af
;
1875 sock
->info
.remote_float
= o
->ce
.remote_float
;
1876 sock
->info
.lsa
= &c
->c1
.link_socket_addr
;
1877 sock
->info
.bind_ipv6_only
= o
->ce
.bind_ipv6_only
;
1878 sock
->info
.ipchange_command
= o
->ipchange
;
1879 sock
->info
.plugins
= c
->plugins
;
1880 sock
->server_poll_timeout
= &c
->c2
.server_poll_interval
;
1883 if (mode
== LS_MODE_TCP_ACCEPT_FROM
)
1885 ASSERT(c
->c2
.accept_from
);
1886 ASSERT(sock
->info
.proto
== PROTO_TCP_SERVER
);
1887 sock
->sd
= c
->c2
.accept_from
->sd
;
1888 /* inherit (possibly guessed) info AF from parent context */
1889 sock
->info
.af
= c
->c2
.accept_from
->info
.af
;
1892 /* are we running in HTTP proxy mode? */
1893 if (sock
->http_proxy
)
1895 ASSERT(sock
->info
.proto
== PROTO_TCP_CLIENT
);
1897 /* the proxy server */
1898 sock
->remote_host
= c
->c1
.http_proxy
->options
.server
;
1899 sock
->remote_port
= c
->c1
.http_proxy
->options
.port
;
1901 /* the OpenVPN server we will use the proxy to connect to */
1902 sock
->proxy_dest_host
= remote_host
;
1903 sock
->proxy_dest_port
= remote_port
;
1905 /* or in Socks proxy mode? */
1906 else if (sock
->socks_proxy
)
1908 /* the proxy server */
1909 sock
->remote_host
= c
->c1
.socks_proxy
->server
;
1910 sock
->remote_port
= c
->c1
.socks_proxy
->port
;
1912 /* the OpenVPN server we will use the proxy to connect to */
1913 sock
->proxy_dest_host
= remote_host
;
1914 sock
->proxy_dest_port
= remote_port
;
1918 sock
->remote_host
= remote_host
;
1919 sock
->remote_port
= remote_port
;
1922 /* bind behavior for TCP server vs. client */
1923 if (sock
->info
.proto
== PROTO_TCP_SERVER
)
1925 if (sock
->mode
== LS_MODE_TCP_ACCEPT_FROM
)
1927 sock
->bind_local
= false;
1931 sock
->bind_local
= true;
1935 if (mode
!= LS_MODE_TCP_ACCEPT_FROM
)
1937 if (sock
->bind_local
)
1939 resolve_bind_local(sock
, sock
->info
.af
);
1941 resolve_remote(sock
, 1, NULL
, NULL
);
1946 phase2_set_socket_flags(struct link_socket
*sock
)
1948 /* set misc socket parameters */
1949 socket_set_flags(sock
->sd
, sock
->sockflags
);
1951 /* set socket to non-blocking mode */
1952 set_nonblock(sock
->sd
);
1954 /* set Path MTU discovery options on the socket */
1955 set_mtu_discover_type(sock
->sd
, sock
->mtu_discover_type
, sock
->info
.af
);
1957 #if EXTENDED_SOCKET_ERROR_CAPABILITY
1958 /* if the OS supports it, enable extended error passing on the socket */
1959 set_sock_extended_error_passing(sock
->sd
, sock
->info
.af
);
1965 linksock_print_addr(struct link_socket
*sock
)
1967 struct gc_arena gc
= gc_new();
1968 const int msglevel
= (sock
->mode
== LS_MODE_TCP_ACCEPT_FROM
) ? D_INIT_MEDIUM
: M_INFO
;
1970 /* print local address */
1971 if (sock
->bind_local
)
1973 sa_family_t ai_family
= sock
->info
.lsa
->actual
.dest
.addr
.sa
.sa_family
;
1974 /* Socket is always bound on the first matching address,
1975 * For bound sockets with no remote addr this is the element of
1977 struct addrinfo
*cur
;
1978 for (cur
= sock
->info
.lsa
->bind_local
; cur
; cur
= cur
->ai_next
)
1980 if (!ai_family
|| ai_family
== cur
->ai_family
)
1986 msg(msglevel
, "%s link local (bound): %s",
1987 proto2ascii(sock
->info
.proto
, sock
->info
.af
, true),
1988 print_sockaddr(cur
->ai_addr
, &gc
));
1992 msg(msglevel
, "%s link local: (not bound)",
1993 proto2ascii(sock
->info
.proto
, sock
->info
.af
, true));
1996 /* print active remote address */
1997 msg(msglevel
, "%s link remote: %s",
1998 proto2ascii(sock
->info
.proto
, sock
->info
.af
, true),
1999 print_link_socket_actual_ex(&sock
->info
.lsa
->actual
,
2001 PS_SHOW_PORT_IF_DEFINED
,
2007 phase2_tcp_server(struct link_socket
*sock
, const char *remote_dynamic
,
2008 struct signal_info
*sig_info
)
2010 volatile int *signal_received
= sig_info
? &sig_info
->signal_received
: NULL
;
2013 case LS_MODE_DEFAULT
:
2014 sock
->sd
= socket_listen_accept(sock
->sd
,
2015 &sock
->info
.lsa
->actual
,
2017 sock
->info
.lsa
->bind_local
,
2023 case LS_MODE_TCP_LISTEN
:
2024 socket_do_listen(sock
->sd
,
2025 sock
->info
.lsa
->bind_local
,
2030 case LS_MODE_TCP_ACCEPT_FROM
:
2031 sock
->sd
= socket_do_accept(sock
->sd
,
2032 &sock
->info
.lsa
->actual
,
2034 if (!socket_defined(sock
->sd
))
2036 register_signal(sig_info
, SIGTERM
, "socket-undefiled");
2039 tcp_connection_established(&sock
->info
.lsa
->actual
);
2049 phase2_tcp_client(struct link_socket
*sock
, struct signal_info
*sig_info
)
2051 bool proxy_retry
= false;
2054 socket_connect(&sock
->sd
,
2055 sock
->info
.lsa
->current_remote
->ai_addr
,
2056 get_server_poll_remaining_time(sock
->server_poll_timeout
),
2059 if (sig_info
->signal_received
)
2064 if (sock
->http_proxy
)
2066 proxy_retry
= establish_http_proxy_passthru(sock
->http_proxy
,
2068 sock
->proxy_dest_host
,
2069 sock
->proxy_dest_port
,
2070 sock
->server_poll_timeout
,
2071 &sock
->stream_buf
.residual
,
2074 else if (sock
->socks_proxy
)
2076 establish_socks_proxy_passthru(sock
->socks_proxy
,
2078 sock
->proxy_dest_host
,
2079 sock
->proxy_dest_port
,
2084 openvpn_close_socket(sock
->sd
);
2085 sock
->sd
= create_socket_tcp(sock
->info
.lsa
->current_remote
);
2088 } while (proxy_retry
);
2093 phase2_socks_client(struct link_socket
*sock
, struct signal_info
*sig_info
)
2095 socket_connect(&sock
->ctrl_sd
,
2096 sock
->info
.lsa
->current_remote
->ai_addr
,
2097 get_server_poll_remaining_time(sock
->server_poll_timeout
),
2100 if (sig_info
->signal_received
)
2105 establish_socks_proxy_udpassoc(sock
->socks_proxy
,
2108 &sock
->socks_relay
.dest
,
2111 if (sig_info
->signal_received
)
2116 sock
->remote_host
= sock
->proxy_dest_host
;
2117 sock
->remote_port
= sock
->proxy_dest_port
;
2119 addr_zero_host(&sock
->info
.lsa
->actual
.dest
);
2120 if (sock
->info
.lsa
->remote_list
)
2122 freeaddrinfo(sock
->info
.lsa
->remote_list
);
2123 sock
->info
.lsa
->current_remote
= NULL
;
2124 sock
->info
.lsa
->remote_list
= NULL
;
2127 resolve_remote(sock
, 1, NULL
, sig_info
);
2132 create_socket_dco_win(struct context
*c
, struct link_socket
*sock
,
2133 struct signal_info
*sig_info
)
2138 ALLOC_OBJ(tt
, struct tuntap
);
2140 *tt
= create_dco_handle(c
->options
.dev_node
, &c
->gc
);
2142 /* Ensure we can "safely" cast the handle to a socket */
2143 static_assert(sizeof(sock
->sd
) == sizeof(tt
->hand
), "HANDLE and SOCKET size differs");
2148 dco_create_socket(c
->c1
.tuntap
->hand
,
2149 sock
->info
.lsa
->current_remote
,
2150 sock
->bind_local
, sock
->info
.lsa
->bind_local
,
2151 get_server_poll_remaining_time(sock
->server_poll_timeout
),
2154 sock
->sockflags
|= SF_DCO_WIN
;
2156 if (sig_info
->signal_received
)
2161 sock
->sd
= (SOCKET
)c
->c1
.tuntap
->hand
;
2162 linksock_print_addr(sock
);
2164 #endif /* if defined(_WIN32) */
2166 /* finalize socket initialization */
2168 link_socket_init_phase2(struct context
*c
)
2170 struct link_socket
*sock
= c
->c2
.link_socket
;
2171 const struct frame
*frame
= &c
->c2
.frame
;
2172 struct signal_info
*sig_info
= c
->sig
;
2174 const char *remote_dynamic
= NULL
;
2175 struct signal_info sig_save
= {0};
2180 if (sig_info
->signal_received
)
2182 sig_save
= *sig_info
;
2183 signal_reset(sig_info
);
2186 /* initialize buffers */
2187 socket_frame_init(frame
, sock
);
2190 * Pass a remote name to connect/accept so that
2191 * they can test for dynamic IP address changes
2192 * and throw a SIGUSR1 if appropriate.
2194 if (sock
->resolve_retry_seconds
)
2196 remote_dynamic
= sock
->remote_host
;
2199 /* Second chance to resolv/create socket */
2200 resolve_remote(sock
, 2, &remote_dynamic
, sig_info
);
2202 /* If a valid remote has been found, create the socket with its addrinfo */
2203 if (sock
->info
.lsa
->current_remote
)
2206 if (dco_enabled(&c
->options
))
2208 create_socket_dco_win(c
, sock
, sig_info
);
2214 create_socket(sock
, sock
->info
.lsa
->current_remote
);
2219 /* If socket has not already been created create it now */
2220 if (sock
->sd
== SOCKET_UNDEFINED
)
2222 /* If we have no --remote and have still not figured out the
2223 * protocol family to use we will use the first of the bind */
2225 if (sock
->bind_local
&& !sock
->remote_host
&& sock
->info
.lsa
->bind_local
)
2227 /* Warn if this is because neither v4 or v6 was specified
2228 * and we should not connect a remote */
2229 if (sock
->info
.af
== AF_UNSPEC
)
2231 msg(M_WARN
, "Could not determine IPv4/IPv6 protocol. Using %s",
2232 addr_family_name(sock
->info
.lsa
->bind_local
->ai_family
));
2233 sock
->info
.af
= sock
->info
.lsa
->bind_local
->ai_family
;
2236 create_socket(sock
, sock
->info
.lsa
->bind_local
);
2240 /* Socket still undefined, give a warning and abort connection */
2241 if (sock
->sd
== SOCKET_UNDEFINED
)
2243 msg(M_WARN
, "Could not determine IPv4/IPv6 protocol");
2244 register_signal(sig_info
, SIGUSR1
, "Could not determine IPv4/IPv6 protocol");
2248 if (sig_info
->signal_received
)
2253 if (sock
->info
.proto
== PROTO_TCP_SERVER
)
2255 phase2_tcp_server(sock
, remote_dynamic
, sig_info
);
2257 else if (sock
->info
.proto
== PROTO_TCP_CLIENT
)
2259 phase2_tcp_client(sock
, sig_info
);
2262 else if (sock
->info
.proto
== PROTO_UDP
&& sock
->socks_proxy
)
2264 phase2_socks_client(sock
, sig_info
);
2266 #ifdef TARGET_ANDROID
2269 protect_fd_nonlocal(sock
->sd
, &sock
->info
.lsa
->actual
.dest
.addr
.sa
);
2272 if (sig_info
->signal_received
)
2277 phase2_set_socket_flags(sock
);
2278 linksock_print_addr(sock
);
2281 if (sig_save
.signal_received
)
2283 /* Always restore the saved signal -- register/throw_signal will handle priority */
2284 if (sig_save
.source
== SIG_SOURCE_HARD
&& sig_info
== &siginfo_static
)
2286 throw_signal(sig_save
.signal_received
);
2290 register_signal(sig_info
, sig_save
.signal_received
, sig_save
.signal_text
);
2296 link_socket_close(struct link_socket
*sock
)
2301 const int gremlin
= GREMLIN_CONNECTION_FLOOD_LEVEL(sock
->gremlin
);
2303 const int gremlin
= 0;
2306 if (socket_defined(sock
->sd
))
2309 close_net_event_win32(&sock
->listen_handle
, sock
->sd
, 0);
2313 msg(D_LOW
, "TCP/UDP: Closing socket");
2314 if (openvpn_close_socket(sock
->sd
))
2316 msg(M_WARN
| M_ERRNO
, "TCP/UDP: Close Socket failed");
2319 sock
->sd
= SOCKET_UNDEFINED
;
2323 overlapped_io_close(&sock
->reads
);
2324 overlapped_io_close(&sock
->writes
);
2329 if (socket_defined(sock
->ctrl_sd
))
2331 if (openvpn_close_socket(sock
->ctrl_sd
))
2333 msg(M_WARN
| M_ERRNO
, "TCP/UDP: Close Socket (ctrl_sd) failed");
2335 sock
->ctrl_sd
= SOCKET_UNDEFINED
;
2338 stream_buf_close(&sock
->stream_buf
);
2339 free_buf(&sock
->stream_buf_data
);
2348 setenv_trusted(struct env_set
*es
, const struct link_socket_info
*info
)
2350 setenv_link_socket_actual(es
, "trusted", &info
->lsa
->actual
, SA_IP_PORT
);
2354 ipchange_fmt(const bool include_cmd
, struct argv
*argv
, const struct link_socket_info
*info
, struct gc_arena
*gc
)
2356 const char *host
= print_sockaddr_ex(&info
->lsa
->actual
.dest
.addr
.sa
, " ", PS_SHOW_PORT
, gc
);
2359 argv_parse_cmd(argv
, info
->ipchange_command
);
2360 argv_printf_cat(argv
, "%s", host
);
2364 argv_printf(argv
, "%s", host
);
2370 link_socket_connection_initiated(struct link_socket_info
*info
,
2371 const struct link_socket_actual
*act
,
2372 const char *common_name
,
2375 struct gc_arena gc
= gc_new();
2377 info
->lsa
->actual
= *act
; /* Note: skip this line for --force-dest */
2378 setenv_trusted(es
, info
);
2379 info
->connection_established
= true;
2381 /* Print connection initiated message, with common name if available */
2383 struct buffer out
= alloc_buf_gc(256, &gc
);
2386 buf_printf(&out
, "[%s] ", common_name
);
2388 buf_printf(&out
, "Peer Connection Initiated with %s", print_link_socket_actual(&info
->lsa
->actual
, &gc
));
2389 msg(M_INFO
, "%s", BSTR(&out
));
2392 /* set environmental vars */
2393 setenv_str(es
, "common_name", common_name
);
2395 /* Process --ipchange plugin */
2396 if (plugin_defined(info
->plugins
, OPENVPN_PLUGIN_IPCHANGE
))
2398 struct argv argv
= argv_new();
2399 ipchange_fmt(false, &argv
, info
, &gc
);
2400 if (plugin_call(info
->plugins
, OPENVPN_PLUGIN_IPCHANGE
, &argv
, NULL
, es
) != OPENVPN_PLUGIN_FUNC_SUCCESS
)
2402 msg(M_WARN
, "WARNING: ipchange plugin call failed");
2407 /* Process --ipchange option */
2408 if (info
->ipchange_command
)
2410 struct argv argv
= argv_new();
2411 setenv_str(es
, "script_type", "ipchange");
2412 ipchange_fmt(true, &argv
, info
, &gc
);
2413 openvpn_run_script(&argv
, es
, 0, "--ipchange");
2421 link_socket_bad_incoming_addr(struct buffer
*buf
,
2422 const struct link_socket_info
*info
,
2423 const struct link_socket_actual
*from_addr
)
2425 struct gc_arena gc
= gc_new();
2426 struct addrinfo
*ai
;
2428 switch (from_addr
->dest
.addr
.sa
.sa_family
)
2433 "TCP/UDP: Incoming packet rejected from %s[%d], expected peer address: %s (allow this incoming source address/port by removing --remote or adding --float)",
2434 print_link_socket_actual(from_addr
, &gc
),
2435 (int)from_addr
->dest
.addr
.sa
.sa_family
,
2436 print_sockaddr_ex(info
->lsa
->remote_list
->ai_addr
, ":", PS_SHOW_PORT
, &gc
));
2437 /* print additional remote addresses */
2438 for (ai
= info
->lsa
->remote_list
->ai_next
; ai
; ai
= ai
->ai_next
)
2440 msg(D_LINK_ERRORS
, "or from peer address: %s",
2441 print_sockaddr_ex(ai
->ai_addr
, ":", PS_SHOW_PORT
, &gc
));
2450 link_socket_bad_outgoing_addr(void)
2452 dmsg(D_READ_WRITE
, "TCP/UDP: No outgoing address to send packet");
2456 link_socket_current_remote(const struct link_socket_info
*info
)
2458 const struct link_socket_addr
*lsa
= info
->lsa
;
2461 * This logic supports "redirect-gateway" semantic, which
2462 * makes sense only for PF_INET routes over PF_INET endpoints
2464 * Maybe in the future consider PF_INET6 endpoints also ...
2465 * by now just ignore it
2467 * For --remote entries with multiple addresses this
2468 * only return the actual endpoint we have successfully connected to
2470 if (lsa
->actual
.dest
.addr
.sa
.sa_family
!= AF_INET
)
2472 return IPV4_INVALID_ADDR
;
2475 if (link_socket_actual_defined(&lsa
->actual
))
2477 return ntohl(lsa
->actual
.dest
.addr
.in4
.sin_addr
.s_addr
);
2479 else if (lsa
->current_remote
)
2481 return ntohl(((struct sockaddr_in
*)lsa
->current_remote
->ai_addr
)
2490 const struct in6_addr
*
2491 link_socket_current_remote_ipv6(const struct link_socket_info
*info
)
2493 const struct link_socket_addr
*lsa
= info
->lsa
;
2495 /* This logic supports "redirect-gateway" semantic,
2496 * for PF_INET6 routes over PF_INET6 endpoints
2498 * For --remote entries with multiple addresses this
2499 * only return the actual endpoint we have successfully connected to
2501 if (lsa
->actual
.dest
.addr
.sa
.sa_family
!= AF_INET6
)
2506 if (link_socket_actual_defined(&lsa
->actual
))
2508 return &(lsa
->actual
.dest
.addr
.in6
.sin6_addr
);
2510 else if (lsa
->current_remote
)
2512 return &(((struct sockaddr_in6
*)lsa
->current_remote
->ai_addr
)->sin6_addr
);
2521 * Return a status string describing socket state.
2524 socket_stat(const struct link_socket
*s
, unsigned int rwflags
, struct gc_arena
*gc
)
2526 struct buffer out
= alloc_buf_gc(64, gc
);
2529 if (rwflags
& EVENT_READ
)
2531 buf_printf(&out
, "S%s",
2532 (s
->rwflags_debug
& EVENT_READ
) ? "R" : "r");
2534 buf_printf(&out
, "%s",
2535 overlapped_io_state_ascii(&s
->reads
));
2538 if (rwflags
& EVENT_WRITE
)
2540 buf_printf(&out
, "S%s",
2541 (s
->rwflags_debug
& EVENT_WRITE
) ? "W" : "w");
2543 buf_printf(&out
, "%s",
2544 overlapped_io_state_ascii(&s
->writes
));
2550 buf_printf(&out
, "S?");
2556 * Stream buffer functions, used to packetize a TCP
2557 * stream connection.
2561 stream_buf_reset(struct stream_buf
*sb
)
2563 dmsg(D_STREAM_DEBUG
, "STREAM: RESET");
2564 sb
->residual_fully_formed
= false;
2565 sb
->buf
= sb
->buf_init
;
2566 buf_reset(&sb
->next
);
2571 stream_buf_init(struct stream_buf
*sb
,
2573 const unsigned int sockflags
,
2576 sb
->buf_init
= *buf
;
2577 sb
->maxlen
= sb
->buf_init
.len
;
2578 sb
->buf_init
.len
= 0;
2579 sb
->residual
= alloc_buf(sb
->maxlen
);
2582 sb
->port_share_state
= ((sockflags
& SF_PORT_SHARE
) && (proto
== PROTO_TCP_SERVER
))
2586 stream_buf_reset(sb
);
2588 dmsg(D_STREAM_DEBUG
, "STREAM: INIT maxlen=%d", sb
->maxlen
);
2592 stream_buf_set_next(struct stream_buf
*sb
)
2594 /* set up 'next' for next i/o read */
2596 sb
->next
.offset
= sb
->buf
.offset
+ sb
->buf
.len
;
2597 sb
->next
.len
= (sb
->len
>= 0 ? sb
->len
: sb
->maxlen
) - sb
->buf
.len
;
2598 dmsg(D_STREAM_DEBUG
, "STREAM: SET NEXT, buf=[%d,%d] next=[%d,%d] len=%d maxlen=%d",
2599 sb
->buf
.offset
, sb
->buf
.len
,
2600 sb
->next
.offset
, sb
->next
.len
,
2601 sb
->len
, sb
->maxlen
);
2602 ASSERT(sb
->next
.len
> 0);
2603 ASSERT(buf_safe(&sb
->buf
, sb
->next
.len
));
2607 stream_buf_get_final(struct stream_buf
*sb
, struct buffer
*buf
)
2609 dmsg(D_STREAM_DEBUG
, "STREAM: GET FINAL len=%d",
2610 buf_defined(&sb
->buf
) ? sb
->buf
.len
: -1);
2611 ASSERT(buf_defined(&sb
->buf
));
2616 stream_buf_get_next(struct stream_buf
*sb
, struct buffer
*buf
)
2618 dmsg(D_STREAM_DEBUG
, "STREAM: GET NEXT len=%d",
2619 buf_defined(&sb
->next
) ? sb
->next
.len
: -1);
2620 ASSERT(buf_defined(&sb
->next
));
2625 stream_buf_read_setup_dowork(struct link_socket
*sock
)
2627 if (sock
->stream_buf
.residual
.len
&& !sock
->stream_buf
.residual_fully_formed
)
2629 ASSERT(buf_copy(&sock
->stream_buf
.buf
, &sock
->stream_buf
.residual
));
2630 ASSERT(buf_init(&sock
->stream_buf
.residual
, 0));
2631 sock
->stream_buf
.residual_fully_formed
= stream_buf_added(&sock
->stream_buf
, 0);
2632 dmsg(D_STREAM_DEBUG
, "STREAM: RESIDUAL FULLY FORMED [%s], len=%d",
2633 sock
->stream_buf
.residual_fully_formed
? "YES" : "NO",
2634 sock
->stream_buf
.residual
.len
);
2637 if (!sock
->stream_buf
.residual_fully_formed
)
2639 stream_buf_set_next(&sock
->stream_buf
);
2641 return !sock
->stream_buf
.residual_fully_formed
;
2645 stream_buf_added(struct stream_buf
*sb
,
2648 dmsg(D_STREAM_DEBUG
, "STREAM: ADD length_added=%d", length_added
);
2649 if (length_added
> 0)
2651 sb
->buf
.len
+= length_added
;
2654 /* if length unknown, see if we can get the length prefix from
2655 * the head of the buffer */
2656 if (sb
->len
< 0 && sb
->buf
.len
>= (int) sizeof(packet_size_type
))
2658 packet_size_type net_size
;
2661 if (sb
->port_share_state
== PS_ENABLED
)
2663 if (!is_openvpn_protocol(&sb
->buf
))
2665 msg(D_STREAM_ERRORS
, "Non-OpenVPN client protocol detected");
2666 sb
->port_share_state
= PS_FOREIGN
;
2672 sb
->port_share_state
= PS_DISABLED
;
2677 ASSERT(buf_read(&sb
->buf
, &net_size
, sizeof(net_size
)));
2678 sb
->len
= ntohps(net_size
);
2680 if (sb
->len
< 1 || sb
->len
> sb
->maxlen
)
2682 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
);
2683 stream_buf_reset(sb
);
2689 /* is our incoming packet fully read? */
2690 if (sb
->len
> 0 && sb
->buf
.len
>= sb
->len
)
2692 /* save any residual data that's part of the next packet */
2693 ASSERT(buf_init(&sb
->residual
, 0));
2694 if (sb
->buf
.len
> sb
->len
)
2696 ASSERT(buf_copy_excess(&sb
->residual
, &sb
->buf
, sb
->len
));
2698 dmsg(D_STREAM_DEBUG
, "STREAM: ADD returned TRUE, buf_len=%d, residual_len=%d",
2700 BLEN(&sb
->residual
));
2705 dmsg(D_STREAM_DEBUG
, "STREAM: ADD returned FALSE (have=%d need=%d)", sb
->buf
.len
, sb
->len
);
2706 stream_buf_set_next(sb
);
2712 stream_buf_close(struct stream_buf
*sb
)
2714 free_buf(&sb
->residual
);
2718 * The listen event is a special event whose sole purpose is
2719 * to tell us that there's a new incoming connection on a
2720 * TCP socket, for use in server mode.
2723 socket_listen_event_handle(struct link_socket
*s
)
2726 if (!defined_net_event_win32(&s
->listen_handle
))
2728 init_net_event_win32(&s
->listen_handle
, FD_ACCEPT
, s
->sd
, 0);
2730 return &s
->listen_handle
;
2731 #else /* ifdef _WIN32 */
2737 * Format IP addresses in ascii
2741 print_sockaddr_ex(const struct sockaddr
*sa
,
2742 const char *separator
,
2743 const unsigned int flags
,
2744 struct gc_arena
*gc
)
2746 struct buffer out
= alloc_buf_gc(128, gc
);
2747 bool addr_is_defined
= false;
2748 char hostaddr
[NI_MAXHOST
] = "";
2749 char servname
[NI_MAXSERV
] = "";
2752 socklen_t salen
= 0;
2753 switch (sa
->sa_family
)
2756 if (!(flags
& PS_DONT_SHOW_FAMILY
))
2758 buf_puts(&out
, "[AF_INET]");
2760 salen
= sizeof(struct sockaddr_in
);
2761 addr_is_defined
= ((struct sockaddr_in
*) sa
)->sin_addr
.s_addr
!= 0;
2765 if (!(flags
& PS_DONT_SHOW_FAMILY
))
2767 buf_puts(&out
, "[AF_INET6]");
2769 salen
= sizeof(struct sockaddr_in6
);
2770 addr_is_defined
= !IN6_IS_ADDR_UNSPECIFIED(&((struct sockaddr_in6
*) sa
)->sin6_addr
);
2774 if (!(flags
& PS_DONT_SHOW_FAMILY
))
2776 return "[AF_UNSPEC]";
2787 status
= getnameinfo(sa
, salen
, hostaddr
, sizeof(hostaddr
),
2788 servname
, sizeof(servname
), NI_NUMERICHOST
| NI_NUMERICSERV
);
2792 buf_printf(&out
, "[nameinfo() err: %s]", gai_strerror(status
));
2796 if (!(flags
& PS_DONT_SHOW_ADDR
))
2798 if (addr_is_defined
)
2800 buf_puts(&out
, hostaddr
);
2804 buf_puts(&out
, "[undef]");
2808 if ((flags
& PS_SHOW_PORT
) || (flags
& PS_SHOW_PORT_IF_DEFINED
))
2812 buf_puts(&out
, separator
);
2815 buf_puts(&out
, servname
);
2822 print_link_socket_actual(const struct link_socket_actual
*act
, struct gc_arena
*gc
)
2824 return print_link_socket_actual_ex(act
, ":", PS_SHOW_PORT
|PS_SHOW_PKTINFO
, gc
);
2828 #define IF_NAMESIZE 16
2832 print_link_socket_actual_ex(const struct link_socket_actual
*act
,
2833 const char *separator
,
2834 const unsigned int flags
,
2835 struct gc_arena
*gc
)
2839 struct buffer out
= alloc_buf_gc(128, gc
);
2840 buf_printf(&out
, "%s", print_sockaddr_ex(&act
->dest
.addr
.sa
, separator
, flags
, gc
));
2841 #if ENABLE_IP_PKTINFO
2842 char ifname
[IF_NAMESIZE
] = "[undef]";
2844 if ((flags
& PS_SHOW_PKTINFO
) && addr_defined_ipi(act
))
2846 switch (act
->dest
.addr
.sa
.sa_family
)
2850 struct openvpn_sockaddr sa
;
2852 sa
.addr
.in4
.sin_family
= AF_INET
;
2853 #if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST)
2854 sa
.addr
.in4
.sin_addr
= act
->pi
.in4
.ipi_spec_dst
;
2855 if_indextoname(act
->pi
.in4
.ipi_ifindex
, ifname
);
2856 #elif defined(IP_RECVDSTADDR)
2857 sa
.addr
.in4
.sin_addr
= act
->pi
.in4
;
2859 #else /* if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST) */
2860 #error ENABLE_IP_PKTINFO is set without IP_PKTINFO xor IP_RECVDSTADDR (fix syshead.h)
2862 buf_printf(&out
, " (via %s%%%s)",
2863 print_sockaddr_ex(&sa
.addr
.sa
, separator
, 0, gc
),
2870 struct sockaddr_in6 sin6
;
2871 char buf
[INET6_ADDRSTRLEN
] = "[undef]";
2873 sin6
.sin6_family
= AF_INET6
;
2874 sin6
.sin6_addr
= act
->pi
.in6
.ipi6_addr
;
2875 if_indextoname(act
->pi
.in6
.ipi6_ifindex
, ifname
);
2876 if (getnameinfo((struct sockaddr
*)&sin6
, sizeof(struct sockaddr_in6
),
2877 buf
, sizeof(buf
), NULL
, 0, NI_NUMERICHOST
) == 0)
2879 buf_printf(&out
, " (via %s%%%s)", buf
, ifname
);
2883 buf_printf(&out
, " (via [getnameinfo() err]%%%s)", ifname
);
2889 #endif /* if ENABLE_IP_PKTINFO */
2899 * Convert an in_addr_t in host byte order
2900 * to an ascii dotted quad.
2903 print_in_addr_t(in_addr_t addr
, unsigned int flags
, struct gc_arena
*gc
)
2906 struct buffer out
= alloc_buf_gc(64, gc
);
2908 if (addr
|| !(flags
& IA_EMPTY_IF_UNDEF
))
2911 ia
.s_addr
= (flags
& IA_NET_ORDER
) ? addr
: htonl(addr
);
2913 buf_printf(&out
, "%s", inet_ntoa(ia
));
2919 * Convert an in6_addr in host byte order
2920 * to an ascii representation of an IPv6 address
2923 print_in6_addr(struct in6_addr a6
, unsigned int flags
, struct gc_arena
*gc
)
2925 struct buffer out
= alloc_buf_gc(64, gc
);
2926 char tmp_out_buf
[64]; /* inet_ntop wants pointer to buffer */
2928 if (memcmp(&a6
, &in6addr_any
, sizeof(a6
)) != 0
2929 || !(flags
& IA_EMPTY_IF_UNDEF
))
2931 inet_ntop(AF_INET6
, &a6
, tmp_out_buf
, sizeof(tmp_out_buf
)-1);
2932 buf_printf(&out
, "%s", tmp_out_buf
);
2938 * Convert an in_port_t in host byte order to a string
2941 print_in_port_t(in_port_t port
, struct gc_arena
*gc
)
2943 struct buffer buffer
= alloc_buf_gc(8, gc
);
2944 buf_printf(&buffer
, "%hu", port
);
2945 return BSTR(&buffer
);
2949 #define UINT8_MAX 0xff
2952 /* add some offset to an ipv6 address
2953 * (add in steps of 8 bits, taking overflow into next round)
2956 add_in6_addr( struct in6_addr base
, uint32_t add
)
2960 for (i
= 15; i
>=0 && add
> 0; i
--)
2963 register uint32_t h
;
2965 h
= (unsigned char) base
.s6_addr
[i
];
2966 base
.s6_addr
[i
] = (h
+add
) & UINT8_MAX
;
2968 /* using explicit carry for the 8-bit additions will catch
2969 * 8-bit and(!) 32-bit overruns nicely
2971 carry
= ((h
& 0xff) + (add
& 0xff)) >> 8;
2972 add
= (add
>>8) + carry
;
2977 /* set environmental variables for ip/port in *addr */
2979 setenv_sockaddr(struct env_set
*es
, const char *name_prefix
, const struct openvpn_sockaddr
*addr
, const unsigned int flags
)
2984 switch (addr
->addr
.sa
.sa_family
)
2987 if (flags
& SA_IP_PORT
)
2989 openvpn_snprintf(name_buf
, sizeof(name_buf
), "%s_ip", name_prefix
);
2993 openvpn_snprintf(name_buf
, sizeof(name_buf
), "%s", name_prefix
);
2996 setenv_str(es
, name_buf
, inet_ntoa(addr
->addr
.in4
.sin_addr
));
2998 if ((flags
& SA_IP_PORT
) && addr
->addr
.in4
.sin_port
)
3000 openvpn_snprintf(name_buf
, sizeof(name_buf
), "%s_port", name_prefix
);
3001 setenv_int(es
, name_buf
, ntohs(addr
->addr
.in4
.sin_port
));
3006 if (IN6_IS_ADDR_V4MAPPED( &addr
->addr
.in6
.sin6_addr
))
3009 memcpy(&ia
.s_addr
, &addr
->addr
.in6
.sin6_addr
.s6_addr
[12],
3011 openvpn_snprintf(name_buf
, sizeof(name_buf
), "%s_ip", name_prefix
);
3012 openvpn_snprintf(buf
, sizeof(buf
), "%s", inet_ntoa(ia
) );
3016 openvpn_snprintf(name_buf
, sizeof(name_buf
), "%s_ip6", name_prefix
);
3017 getnameinfo(&addr
->addr
.sa
, sizeof(struct sockaddr_in6
),
3018 buf
, sizeof(buf
), NULL
, 0, NI_NUMERICHOST
);
3020 setenv_str(es
, name_buf
, buf
);
3022 if ((flags
& SA_IP_PORT
) && addr
->addr
.in6
.sin6_port
)
3024 openvpn_snprintf(name_buf
, sizeof(name_buf
), "%s_port", name_prefix
);
3025 setenv_int(es
, name_buf
, ntohs(addr
->addr
.in6
.sin6_port
));
3032 setenv_in_addr_t(struct env_set
*es
, const char *name_prefix
, in_addr_t addr
, const unsigned int flags
)
3034 if (addr
|| !(flags
& SA_SET_IF_NONZERO
))
3036 struct openvpn_sockaddr si
;
3038 si
.addr
.in4
.sin_family
= AF_INET
;
3039 si
.addr
.in4
.sin_addr
.s_addr
= htonl(addr
);
3040 setenv_sockaddr(es
, name_prefix
, &si
, flags
);
3045 setenv_in6_addr(struct env_set
*es
,
3046 const char *name_prefix
,
3047 const struct in6_addr
*addr
,
3048 const unsigned int flags
)
3050 if (!IN6_IS_ADDR_UNSPECIFIED(addr
) || !(flags
& SA_SET_IF_NONZERO
))
3052 struct openvpn_sockaddr si
;
3054 si
.addr
.in6
.sin6_family
= AF_INET6
;
3055 si
.addr
.in6
.sin6_addr
= *addr
;
3056 setenv_sockaddr(es
, name_prefix
, &si
, flags
);
3061 setenv_link_socket_actual(struct env_set
*es
,
3062 const char *name_prefix
,
3063 const struct link_socket_actual
*act
,
3064 const unsigned int flags
)
3066 setenv_sockaddr(es
, name_prefix
, &act
->dest
, flags
);
3070 * Convert protocol names between index and ascii form.
3073 struct proto_names
{
3074 const char *short_form
;
3075 const char *display_form
;
3076 sa_family_t proto_af
;
3080 /* Indexed by PROTO_x */
3081 static const struct proto_names proto_names
[] = {
3082 {"proto-uninitialized", "proto-NONE", AF_UNSPEC
, PROTO_NONE
},
3083 /* try IPv4 and IPv6 (client), bind dual-stack (server) */
3084 {"udp", "UDP", AF_UNSPEC
, PROTO_UDP
},
3085 {"tcp-server", "TCP_SERVER", AF_UNSPEC
, PROTO_TCP_SERVER
},
3086 {"tcp-client", "TCP_CLIENT", AF_UNSPEC
, PROTO_TCP_CLIENT
},
3087 {"tcp", "TCP", AF_UNSPEC
, PROTO_TCP
},
3089 {"udp4", "UDPv4", AF_INET
, PROTO_UDP
},
3090 {"tcp4-server", "TCPv4_SERVER", AF_INET
, PROTO_TCP_SERVER
},
3091 {"tcp4-client", "TCPv4_CLIENT", AF_INET
, PROTO_TCP_CLIENT
},
3092 {"tcp4", "TCPv4", AF_INET
, PROTO_TCP
},
3094 {"udp6", "UDPv6", AF_INET6
, PROTO_UDP
},
3095 {"tcp6-server", "TCPv6_SERVER", AF_INET6
, PROTO_TCP_SERVER
},
3096 {"tcp6-client", "TCPv6_CLIENT", AF_INET6
, PROTO_TCP_CLIENT
},
3097 {"tcp6", "TCPv6", AF_INET6
, PROTO_TCP
},
3101 ascii2proto(const char *proto_name
)
3104 for (i
= 0; i
< SIZE(proto_names
); ++i
)
3106 if (!strcmp(proto_name
, proto_names
[i
].short_form
))
3108 return proto_names
[i
].proto
;
3115 ascii2af(const char *proto_name
)
3118 for (i
= 0; i
< SIZE(proto_names
); ++i
)
3120 if (!strcmp(proto_name
, proto_names
[i
].short_form
))
3122 return proto_names
[i
].proto_af
;
3129 proto2ascii(int proto
, sa_family_t af
, bool display_form
)
3132 for (i
= 0; i
< SIZE(proto_names
); ++i
)
3134 if (proto_names
[i
].proto_af
== af
&& proto_names
[i
].proto
== proto
)
3138 return proto_names
[i
].display_form
;
3142 return proto_names
[i
].short_form
;
3147 return "[unknown protocol]";
3151 proto2ascii_all(struct gc_arena
*gc
)
3153 struct buffer out
= alloc_buf_gc(256, gc
);
3156 for (i
= 0; i
< SIZE(proto_names
); ++i
)
3160 buf_printf(&out
, " ");
3162 buf_printf(&out
, "[%s]", proto_names
[i
].short_form
);
3168 addr_family_name(int af
)
3172 case AF_INET
: return "AF_INET";
3174 case AF_INET6
: return "AF_INET6";
3180 * Given a local proto, return local proto
3181 * if !remote, or compatible remote proto
3184 * This is used for options compatibility
3187 * IPv6 and IPv4 protocols are comptabile but OpenVPN
3188 * has always sent UDPv4, TCPv4 over the wire. Keep these
3189 * strings for backward compatibility
3192 proto_remote(int proto
, bool remote
)
3194 ASSERT(proto
>= 0 && proto
< PROTO_N
);
3195 if (proto
== PROTO_UDP
)
3200 if ( (remote
&& proto
== PROTO_TCP_CLIENT
)
3201 || (!remote
&& proto
== PROTO_TCP_SERVER
))
3203 return "TCPv4_SERVER";
3205 if ( (remote
&& proto
== PROTO_TCP_SERVER
)
3206 || (!remote
&& proto
== PROTO_TCP_CLIENT
))
3208 return "TCPv4_CLIENT";
3212 return ""; /* Make the compiler happy */
3216 * Bad incoming address lengths that differ from what
3217 * we expect are considered to be fatal errors.
3220 bad_address_length(int actual
, int expected
)
3222 msg(M_FATAL
, "ERROR: received strange incoming packet with an address length of %d -- we only accept address lengths of %d.",
3228 * Socket Read Routines
3232 link_socket_read_tcp(struct link_socket
*sock
,
3237 if (!sock
->stream_buf
.residual_fully_formed
)
3239 /* with Linux-DCO, we sometimes try to access a socket that is
3240 * already installed in the kernel and has no valid file descriptor
3241 * anymore. This is a bug.
3242 * Handle by resetting client instance instead of crashing.
3244 if (sock
->sd
== SOCKET_UNDEFINED
)
3246 msg(M_INFO
, "BUG: link_socket_read_tcp(): sock->sd==-1, reset client instance" );
3247 sock
->stream_reset
= true; /* reset client instance */
3248 return buf
->len
= 0; /* nothing to read */
3252 sockethandle_t sh
= { .s
= sock
->sd
};
3253 len
= sockethandle_finalize(sh
, &sock
->reads
, buf
, NULL
);
3256 stream_buf_get_next(&sock
->stream_buf
, &frag
);
3257 len
= recv(sock
->sd
, BPTR(&frag
), BLEN(&frag
), MSG_NOSIGNAL
);
3262 sock
->stream_reset
= true;
3266 return buf
->len
= len
;
3270 if (sock
->stream_buf
.residual_fully_formed
3271 || stream_buf_added(&sock
->stream_buf
, len
)) /* packet complete? */
3273 stream_buf_get_final(&sock
->stream_buf
, buf
);
3274 stream_buf_reset(&sock
->stream_buf
);
3279 return buf
->len
= 0; /* no error, but packet is still incomplete */
3285 #if ENABLE_IP_PKTINFO
3287 /* make the buffer large enough to handle ancillary socket data for
3288 * both IPv4 and IPv6 destination addresses, plus padding (see RFC 2292)
3290 #if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST)
3291 #define PKTINFO_BUF_SIZE max_int( CMSG_SPACE(sizeof(struct in6_pktinfo)), \
3292 CMSG_SPACE(sizeof(struct in_pktinfo)) )
3294 #define PKTINFO_BUF_SIZE max_int( CMSG_SPACE(sizeof(struct in6_pktinfo)), \
3295 CMSG_SPACE(sizeof(struct in_addr)) )
3299 link_socket_read_udp_posix_recvmsg(struct link_socket
*sock
,
3301 struct link_socket_actual
*from
)
3304 uint8_t pktinfo_buf
[PKTINFO_BUF_SIZE
];
3306 socklen_t fromlen
= sizeof(from
->dest
.addr
);
3308 ASSERT(sock
->sd
>= 0); /* can't happen */
3310 iov
.iov_base
= BPTR(buf
);
3311 iov
.iov_len
= buf_forward_capacity_total(buf
);
3312 mesg
.msg_iov
= &iov
;
3313 mesg
.msg_iovlen
= 1;
3314 mesg
.msg_name
= &from
->dest
.addr
;
3315 mesg
.msg_namelen
= fromlen
;
3316 mesg
.msg_control
= pktinfo_buf
;
3317 mesg
.msg_controllen
= sizeof pktinfo_buf
;
3318 buf
->len
= recvmsg(sock
->sd
, &mesg
, 0);
3321 struct cmsghdr
*cmsg
;
3322 fromlen
= mesg
.msg_namelen
;
3323 cmsg
= CMSG_FIRSTHDR(&mesg
);
3325 && CMSG_NXTHDR(&mesg
, cmsg
) == NULL
3326 #if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST)
3327 && cmsg
->cmsg_level
== SOL_IP
3328 && cmsg
->cmsg_type
== IP_PKTINFO
3329 && cmsg
->cmsg_len
>= CMSG_LEN(sizeof(struct in_pktinfo
)) )
3330 #elif defined(IP_RECVDSTADDR)
3331 && cmsg
->cmsg_level
== IPPROTO_IP
3332 && cmsg
->cmsg_type
== IP_RECVDSTADDR
3333 && cmsg
->cmsg_len
>= CMSG_LEN(sizeof(struct in_addr
)) )
3334 #else /* if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST) */
3335 #error ENABLE_IP_PKTINFO is set without IP_PKTINFO xor IP_RECVDSTADDR (fix syshead.h)
3338 #if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST)
3339 struct in_pktinfo
*pkti
= (struct in_pktinfo
*) CMSG_DATA(cmsg
);
3340 from
->pi
.in4
.ipi_ifindex
= pkti
->ipi_ifindex
;
3341 from
->pi
.in4
.ipi_spec_dst
= pkti
->ipi_spec_dst
;
3342 #elif defined(IP_RECVDSTADDR)
3343 from
->pi
.in4
= *(struct in_addr
*) CMSG_DATA(cmsg
);
3344 #else /* if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST) */
3345 #error ENABLE_IP_PKTINFO is set without IP_PKTINFO xor IP_RECVDSTADDR (fix syshead.h)
3348 else if (cmsg
!= NULL
3349 && CMSG_NXTHDR(&mesg
, cmsg
) == NULL
3350 && cmsg
->cmsg_level
== IPPROTO_IPV6
3351 && cmsg
->cmsg_type
== IPV6_PKTINFO
3352 && cmsg
->cmsg_len
>= CMSG_LEN(sizeof(struct in6_pktinfo
)) )
3354 struct in6_pktinfo
*pkti6
= (struct in6_pktinfo
*) CMSG_DATA(cmsg
);
3355 from
->pi
.in6
.ipi6_ifindex
= pkti6
->ipi6_ifindex
;
3356 from
->pi
.in6
.ipi6_addr
= pkti6
->ipi6_addr
;
3358 else if (cmsg
!= NULL
)
3360 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
);
3366 #endif /* if ENABLE_IP_PKTINFO */
3369 link_socket_read_udp_posix(struct link_socket
*sock
,
3371 struct link_socket_actual
*from
)
3373 socklen_t fromlen
= sizeof(from
->dest
.addr
);
3374 socklen_t expectedlen
= af_addr_size(sock
->info
.af
);
3375 addr_zero_host(&from
->dest
);
3377 ASSERT(sock
->sd
>= 0); /* can't happen */
3379 #if ENABLE_IP_PKTINFO
3380 /* Both PROTO_UDPv4 and PROTO_UDPv6 */
3381 if (sock
->info
.proto
== PROTO_UDP
&& sock
->sockflags
& SF_USE_IP_PKTINFO
)
3383 fromlen
= link_socket_read_udp_posix_recvmsg(sock
, buf
, from
);
3387 buf
->len
= recvfrom(sock
->sd
, BPTR(buf
), buf_forward_capacity(buf
), 0,
3388 &from
->dest
.addr
.sa
, &fromlen
);
3389 /* FIXME: won't do anything when sock->info.af == AF_UNSPEC */
3390 if (buf
->len
>= 0 && expectedlen
&& fromlen
!= expectedlen
)
3392 bad_address_length(fromlen
, expectedlen
);
3397 #endif /* ifndef _WIN32 */
3400 * Socket Write Routines
3404 link_socket_write_tcp(struct link_socket
*sock
,
3406 struct link_socket_actual
*to
)
3408 packet_size_type len
= BLEN(buf
);
3409 dmsg(D_STREAM_DEBUG
, "STREAM: WRITE %d offset=%d", (int)len
, buf
->offset
);
3410 ASSERT(len
<= sock
->stream_buf
.maxlen
);
3412 ASSERT(buf_write_prepend(buf
, &len
, sizeof(len
)));
3414 return link_socket_write_win32(sock
, buf
, to
);
3416 return link_socket_write_tcp_posix(sock
, buf
, to
);
3420 #if ENABLE_IP_PKTINFO
3423 link_socket_write_udp_posix_sendmsg(struct link_socket
*sock
,
3425 struct link_socket_actual
*to
)
3429 struct cmsghdr
*cmsg
;
3430 uint8_t pktinfo_buf
[PKTINFO_BUF_SIZE
];
3432 iov
.iov_base
= BPTR(buf
);
3433 iov
.iov_len
= BLEN(buf
);
3434 mesg
.msg_iov
= &iov
;
3435 mesg
.msg_iovlen
= 1;
3436 switch (to
->dest
.addr
.sa
.sa_family
)
3440 mesg
.msg_name
= &to
->dest
.addr
.sa
;
3441 mesg
.msg_namelen
= sizeof(struct sockaddr_in
);
3442 mesg
.msg_control
= pktinfo_buf
;
3444 #if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST)
3445 mesg
.msg_controllen
= CMSG_SPACE(sizeof(struct in_pktinfo
));
3446 cmsg
= CMSG_FIRSTHDR(&mesg
);
3447 cmsg
->cmsg_len
= CMSG_LEN(sizeof(struct in_pktinfo
));
3448 cmsg
->cmsg_level
= SOL_IP
;
3449 cmsg
->cmsg_type
= IP_PKTINFO
;
3451 struct in_pktinfo
*pkti
;
3452 pkti
= (struct in_pktinfo
*) CMSG_DATA(cmsg
);
3453 pkti
->ipi_ifindex
= to
->pi
.in4
.ipi_ifindex
;
3454 pkti
->ipi_spec_dst
= to
->pi
.in4
.ipi_spec_dst
;
3455 pkti
->ipi_addr
.s_addr
= 0;
3457 #elif defined(IP_RECVDSTADDR)
3458 ASSERT( CMSG_SPACE(sizeof(struct in_addr
)) <= sizeof(pktinfo_buf
) );
3459 mesg
.msg_controllen
= CMSG_SPACE(sizeof(struct in_addr
));
3460 cmsg
= CMSG_FIRSTHDR(&mesg
);
3461 cmsg
->cmsg_len
= CMSG_LEN(sizeof(struct in_addr
));
3462 cmsg
->cmsg_level
= IPPROTO_IP
;
3463 cmsg
->cmsg_type
= IP_RECVDSTADDR
;
3464 *(struct in_addr
*) CMSG_DATA(cmsg
) = to
->pi
.in4
;
3465 #else /* if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST) */
3466 #error ENABLE_IP_PKTINFO is set without IP_PKTINFO xor IP_RECVDSTADDR (fix syshead.h)
3467 #endif /* if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST) */
3473 struct in6_pktinfo
*pkti6
;
3474 mesg
.msg_name
= &to
->dest
.addr
.sa
;
3475 mesg
.msg_namelen
= sizeof(struct sockaddr_in6
);
3477 ASSERT( CMSG_SPACE(sizeof(struct in6_pktinfo
)) <= sizeof(pktinfo_buf
) );
3478 mesg
.msg_control
= pktinfo_buf
;
3479 mesg
.msg_controllen
= CMSG_SPACE(sizeof(struct in6_pktinfo
));
3481 cmsg
= CMSG_FIRSTHDR(&mesg
);
3482 cmsg
->cmsg_len
= CMSG_LEN(sizeof(struct in6_pktinfo
));
3483 cmsg
->cmsg_level
= IPPROTO_IPV6
;
3484 cmsg
->cmsg_type
= IPV6_PKTINFO
;
3486 pkti6
= (struct in6_pktinfo
*) CMSG_DATA(cmsg
);
3487 pkti6
->ipi6_ifindex
= to
->pi
.in6
.ipi6_ifindex
;
3488 pkti6
->ipi6_addr
= to
->pi
.in6
.ipi6_addr
;
3494 return sendmsg(sock
->sd
, &mesg
, 0);
3497 #endif /* if ENABLE_IP_PKTINFO */
3500 * Win32 overlapped socket I/O functions.
3506 socket_get_last_error(const struct link_socket
*sock
)
3508 if (socket_is_dco_win(sock
))
3510 return GetLastError();
3513 return WSAGetLastError();
3517 socket_recv_queue(struct link_socket
*sock
, int maxsize
)
3519 if (sock
->reads
.iostate
== IOSTATE_INITIAL
)
3524 /* reset buf to its initial state */
3525 if (proto_is_udp(sock
->info
.proto
))
3527 sock
->reads
.buf
= sock
->reads
.buf_init
;
3529 else if (proto_is_tcp(sock
->info
.proto
))
3531 stream_buf_get_next(&sock
->stream_buf
, &sock
->reads
.buf
);
3538 /* Win32 docs say it's okay to allocate the wsabuf on the stack */
3539 wsabuf
[0].buf
= BSTR(&sock
->reads
.buf
);
3540 wsabuf
[0].len
= maxsize
? maxsize
: BLEN(&sock
->reads
.buf
);
3542 /* check for buffer overflow */
3543 ASSERT(wsabuf
[0].len
<= BLEN(&sock
->reads
.buf
));
3545 /* the overlapped read will signal this event on I/O completion */
3546 ASSERT(ResetEvent(sock
->reads
.overlapped
.hEvent
));
3547 sock
->reads
.flags
= 0;
3549 if (socket_is_dco_win(sock
))
3551 status
= ReadFile((HANDLE
)sock
->sd
, wsabuf
[0].buf
, wsabuf
[0].len
,
3552 &sock
->reads
.size
, &sock
->reads
.overlapped
);
3553 /* Readfile status is inverted from WSARecv */
3556 else if (proto_is_udp(sock
->info
.proto
))
3558 sock
->reads
.addr_defined
= true;
3559 sock
->reads
.addrlen
= sizeof(sock
->reads
.addr6
);
3560 status
= WSARecvFrom(
3566 (struct sockaddr
*) &sock
->reads
.addr
,
3567 &sock
->reads
.addrlen
,
3568 &sock
->reads
.overlapped
,
3571 else if (proto_is_tcp(sock
->info
.proto
))
3573 sock
->reads
.addr_defined
= false;
3580 &sock
->reads
.overlapped
,
3589 if (!status
) /* operation completed immediately? */
3591 /* FIXME: won't do anything when sock->info.af == AF_UNSPEC */
3592 int af_len
= af_addr_size(sock
->info
.af
);
3593 if (sock
->reads
.addr_defined
&& af_len
&& sock
->reads
.addrlen
!= af_len
)
3595 bad_address_length(sock
->reads
.addrlen
, af_len
);
3597 sock
->reads
.iostate
= IOSTATE_IMMEDIATE_RETURN
;
3599 /* since we got an immediate return, we must signal the event object ourselves */
3600 ASSERT(SetEvent(sock
->reads
.overlapped
.hEvent
));
3601 sock
->reads
.status
= 0;
3603 dmsg(D_WIN32_IO
, "WIN32 I/O: Socket Receive immediate return [%d,%d]",
3604 (int) wsabuf
[0].len
,
3605 (int) sock
->reads
.size
);
3609 status
= socket_get_last_error(sock
);
3610 if (status
== WSA_IO_PENDING
) /* operation queued? */
3612 sock
->reads
.iostate
= IOSTATE_QUEUED
;
3613 sock
->reads
.status
= status
;
3614 dmsg(D_WIN32_IO
, "WIN32 I/O: Socket Receive queued [%d]",
3615 (int) wsabuf
[0].len
);
3617 else /* error occurred */
3619 struct gc_arena gc
= gc_new();
3620 ASSERT(SetEvent(sock
->reads
.overlapped
.hEvent
));
3621 sock
->reads
.iostate
= IOSTATE_IMMEDIATE_RETURN
;
3622 sock
->reads
.status
= status
;
3623 dmsg(D_WIN32_IO
, "WIN32 I/O: Socket Receive error [%d]: %s",
3624 (int) wsabuf
[0].len
,
3625 strerror_win32(status
, &gc
));
3630 return sock
->reads
.iostate
;
3634 socket_send_queue(struct link_socket
*sock
, struct buffer
*buf
, const struct link_socket_actual
*to
)
3636 if (sock
->writes
.iostate
== IOSTATE_INITIAL
)
3641 /* make a private copy of buf */
3642 sock
->writes
.buf
= sock
->writes
.buf_init
;
3643 sock
->writes
.buf
.len
= 0;
3644 ASSERT(buf_copy(&sock
->writes
.buf
, buf
));
3646 /* Win32 docs say it's okay to allocate the wsabuf on the stack */
3647 wsabuf
[0].buf
= BSTR(&sock
->writes
.buf
);
3648 wsabuf
[0].len
= BLEN(&sock
->writes
.buf
);
3650 /* the overlapped write will signal this event on I/O completion */
3651 ASSERT(ResetEvent(sock
->writes
.overlapped
.hEvent
));
3652 sock
->writes
.flags
= 0;
3654 if (socket_is_dco_win(sock
))
3656 status
= WriteFile((HANDLE
)sock
->sd
, wsabuf
[0].buf
, wsabuf
[0].len
,
3657 &sock
->writes
.size
, &sock
->writes
.overlapped
);
3659 /* WriteFile status is inverted from WSASendTo */
3663 else if (proto_is_udp(sock
->info
.proto
))
3665 /* set destination address for UDP writes */
3666 sock
->writes
.addr_defined
= true;
3667 if (to
->dest
.addr
.sa
.sa_family
== AF_INET6
)
3669 sock
->writes
.addr6
= to
->dest
.addr
.in6
;
3670 sock
->writes
.addrlen
= sizeof(sock
->writes
.addr6
);
3674 sock
->writes
.addr
= to
->dest
.addr
.in4
;
3675 sock
->writes
.addrlen
= sizeof(sock
->writes
.addr
);
3684 (struct sockaddr
*) &sock
->writes
.addr
,
3685 sock
->writes
.addrlen
,
3686 &sock
->writes
.overlapped
,
3689 else if (proto_is_tcp(sock
->info
.proto
))
3691 /* destination address for TCP writes was established on connection initiation */
3692 sock
->writes
.addr_defined
= false;
3700 &sock
->writes
.overlapped
,
3709 if (!status
) /* operation completed immediately? */
3711 sock
->writes
.iostate
= IOSTATE_IMMEDIATE_RETURN
;
3713 /* since we got an immediate return, we must signal the event object ourselves */
3714 ASSERT(SetEvent(sock
->writes
.overlapped
.hEvent
));
3716 sock
->writes
.status
= 0;
3718 dmsg(D_WIN32_IO
, "WIN32 I/O: Socket Send immediate return [%d,%d]",
3719 (int) wsabuf
[0].len
,
3720 (int) sock
->writes
.size
);
3724 status
= socket_get_last_error(sock
);
3725 /* both status code have the identical value */
3726 if (status
== WSA_IO_PENDING
|| status
== ERROR_IO_PENDING
) /* operation queued? */
3728 sock
->writes
.iostate
= IOSTATE_QUEUED
;
3729 sock
->writes
.status
= status
;
3730 dmsg(D_WIN32_IO
, "WIN32 I/O: Socket Send queued [%d]",
3731 (int) wsabuf
[0].len
);
3733 else /* error occurred */
3735 struct gc_arena gc
= gc_new();
3736 ASSERT(SetEvent(sock
->writes
.overlapped
.hEvent
));
3737 sock
->writes
.iostate
= IOSTATE_IMMEDIATE_RETURN
;
3738 sock
->writes
.status
= status
;
3740 dmsg(D_WIN32_IO
, "WIN32 I/O: Socket Send error [%d]: %s",
3741 (int) wsabuf
[0].len
,
3742 strerror_win32(status
, &gc
));
3748 return sock
->writes
.iostate
;
3751 /* Returns the number of bytes successfully read */
3753 sockethandle_finalize(sockethandle_t sh
,
3754 struct overlapped_io
*io
,
3756 struct link_socket_actual
*from
)
3761 switch (io
->iostate
)
3763 case IOSTATE_QUEUED
:
3764 status
= SocketHandleGetOverlappedResult(sh
, io
);
3767 /* successful return for a queued operation */
3773 io
->iostate
= IOSTATE_INITIAL
;
3774 ASSERT(ResetEvent(io
->overlapped
.hEvent
));
3776 dmsg(D_WIN32_IO
, "WIN32 I/O: Completion success [%d]", ret
);
3780 /* error during a queued operation */
3782 if (SocketHandleGetLastError(sh
) != ERROR_IO_INCOMPLETE
)
3784 /* if no error (i.e. just not finished yet), then DON'T execute this code */
3785 io
->iostate
= IOSTATE_INITIAL
;
3786 ASSERT(ResetEvent(io
->overlapped
.hEvent
));
3787 msg(D_WIN32_IO
| M_ERRNO
, "WIN32 I/O: Completion error");
3792 case IOSTATE_IMMEDIATE_RETURN
:
3793 io
->iostate
= IOSTATE_INITIAL
;
3794 ASSERT(ResetEvent(io
->overlapped
.hEvent
));
3797 /* error return for a non-queued operation */
3798 SocketHandleSetLastError(sh
, io
->status
);
3800 msg(D_WIN32_IO
| M_ERRNO
, "WIN32 I/O: Completion non-queued error");
3804 /* successful return for a non-queued operation */
3810 dmsg(D_WIN32_IO
, "WIN32 I/O: Completion non-queued success [%d]", ret
);
3814 case IOSTATE_INITIAL
: /* were we called without proper queueing? */
3815 SocketHandleSetInvalError(sh
);
3817 dmsg(D_WIN32_IO
, "WIN32 I/O: Completion BAD STATE");
3824 /* return from address if requested */
3825 if (!sh
.is_handle
&& from
)
3827 if (ret
>= 0 && io
->addr_defined
)
3829 /* TODO(jjo): streamline this mess */
3830 /* in this func we don't have relevant info about the PF_ of this
3831 * endpoint, as link_socket_actual will be zero for the 1st received packet
3833 * Test for inets PF_ possible sizes
3835 switch (io
->addrlen
)
3837 case sizeof(struct sockaddr_in
):
3838 case sizeof(struct sockaddr_in6
):
3839 /* TODO(jjo): for some reason (?) I'm getting 24,28 for AF_INET6
3841 case sizeof(struct sockaddr_in6
)-4:
3845 bad_address_length(io
->addrlen
, af_addr_size(io
->addr
.sin_family
));
3848 switch (io
->addr
.sin_family
)
3851 from
->dest
.addr
.in4
= io
->addr
;
3855 from
->dest
.addr
.in6
= io
->addr6
;
3861 CLEAR(from
->dest
.addr
);
3875 * Socket event notification
3879 socket_set(struct link_socket
*s
,
3880 struct event_set
*es
,
3881 unsigned int rwflags
,
3883 unsigned int *persistent
)
3887 if ((rwflags
& EVENT_READ
) && !stream_buf_read_setup(s
))
3889 ASSERT(!persistent
);
3890 rwflags
&= ~EVENT_READ
;
3894 if (rwflags
& EVENT_READ
)
3896 socket_recv_queue(s
, 0);
3900 /* if persistent is defined, call event_ctl only if rwflags has changed since last call */
3901 if (!persistent
|| *persistent
!= rwflags
)
3903 event_ctl(es
, socket_event_handle(s
), rwflags
, arg
);
3906 *persistent
= rwflags
;
3910 s
->rwflags_debug
= rwflags
;
3916 sd_close(socket_descriptor_t
*sd
)
3918 if (sd
&& socket_defined(*sd
))
3920 openvpn_close_socket(*sd
);
3921 *sd
= SOCKET_UNDEFINED
;
3925 #if UNIX_SOCK_SUPPORT
3928 * code for unix domain sockets
3932 sockaddr_unix_name(const struct sockaddr_un
*local
, const char *null
)
3934 if (local
&& local
->sun_family
== PF_UNIX
)
3936 return local
->sun_path
;
3945 create_socket_unix(void)
3947 socket_descriptor_t sd
;
3949 if ((sd
= socket(PF_UNIX
, SOCK_STREAM
, 0)) < 0)
3951 msg(M_ERR
, "Cannot create unix domain socket");
3954 /* set socket file descriptor to not pass across execs, so that
3955 * scripts don't have access to it */
3962 socket_bind_unix(socket_descriptor_t sd
,
3963 struct sockaddr_un
*local
,
3966 struct gc_arena gc
= gc_new();
3967 const mode_t orig_umask
= umask(0);
3969 if (bind(sd
, (struct sockaddr
*) local
, sizeof(struct sockaddr_un
)))
3971 msg(M_FATAL
| M_ERRNO
,
3972 "%s: Socket bind[%d] failed on unix domain socket %s",
3975 sockaddr_unix_name(local
, "NULL"));
3983 socket_accept_unix(socket_descriptor_t sd
,
3984 struct sockaddr_un
*remote
)
3986 socklen_t remote_len
= sizeof(struct sockaddr_un
);
3987 socket_descriptor_t ret
;
3990 ret
= accept(sd
, (struct sockaddr
*) remote
, &remote_len
);
3993 /* set socket file descriptor to not pass across execs, so that
3994 * scripts don't have access to it */
4001 socket_connect_unix(socket_descriptor_t sd
,
4002 struct sockaddr_un
*remote
)
4004 int status
= connect(sd
, (struct sockaddr
*) remote
, sizeof(struct sockaddr_un
));
4007 status
= openvpn_errno();
4013 sockaddr_unix_init(struct sockaddr_un
*local
, const char *path
)
4015 local
->sun_family
= PF_UNIX
;
4016 strncpynt(local
->sun_path
, path
, sizeof(local
->sun_path
));
4020 socket_delete_unix(const struct sockaddr_un
*local
)
4022 const char *name
= sockaddr_unix_name(local
, NULL
);
4023 if (name
&& strlen(name
))
4030 unix_socket_get_peer_uid_gid(const socket_descriptor_t sd
, int *uid
, int *gid
)
4032 #ifdef HAVE_GETPEEREID
4035 if (getpeereid(sd
, &u
, &g
) == -1)
4048 #elif defined(SO_PEERCRED)
4049 struct ucred peercred
;
4050 socklen_t so_len
= sizeof(peercred
);
4051 if (getsockopt(sd
, SOL_SOCKET
, SO_PEERCRED
, &peercred
, &so_len
) == -1)
4057 *uid
= peercred
.uid
;
4061 *gid
= peercred
.gid
;
4064 #else /* ifdef HAVE_GETPEEREID */
4066 #endif /* ifdef HAVE_GETPEEREID */
4069 #endif /* if UNIX_SOCK_SUPPORT */