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.
26 #elif defined(_MSC_VER)
27 #include "config-msvc.h"
38 #include "run_command.h"
48 * Convert sockflags/getaddr_flags into getaddr_flags
51 sf2gaf(const unsigned int getaddr_flags
,
52 const unsigned int sockflags
)
54 if (sockflags
& SF_HOST_RANDOMIZE
)
56 return getaddr_flags
| GETADDR_RANDOMIZE
;
65 * Functions related to the translation of DNS names to IP addresses.
68 get_addr_generic(sa_family_t af
, unsigned int flags
, const char *hostname
,
69 void *network
, unsigned int *netbits
,
70 int resolve_retry_seconds
, struct signal_info
*sig_info
,
73 char *endp
, *sep
, *var_host
= NULL
;
74 struct addrinfo
*ai
= NULL
;
81 msg(M_NONFATAL
, "Can't resolve null hostname!");
85 /* assign family specific default values */
90 max_bits
= sizeof(in_addr_t
) * 8;
95 max_bits
= sizeof(struct in6_addr
) * 8;
100 "Unsupported AF family passed to getaddrinfo for %s (%d)",
105 /* we need to modify the hostname received as input, but we don't want to
106 * touch it directly as it might be a constant string.
108 * Therefore, we clone the string here and free it at the end of the
110 var_host
= strdup(hostname
);
113 msg(M_NONFATAL
| M_ERRNO
,
114 "Can't allocate hostname buffer for getaddrinfo");
118 /* check if this hostname has a /bits suffix */
119 sep
= strchr(var_host
, '/');
122 bits
= strtoul(sep
+ 1, &endp
, 10);
123 if ((*endp
!= '\0') || (bits
> max_bits
))
125 msg(msglevel
, "IP prefix '%s': invalid '/bits' spec (%s)", hostname
,
132 ret
= openvpn_getaddrinfo(flags
& ~GETADDR_HOST_ORDER
, var_host
, NULL
,
133 resolve_retry_seconds
, sig_info
, af
, &ai
);
134 if ((ret
== 0) && network
)
136 struct in6_addr
*ip6
;
143 *ip4
= ((struct sockaddr_in
*)ai
->ai_addr
)->sin_addr
.s_addr
;
145 if (flags
& GETADDR_HOST_ORDER
)
153 *ip6
= ((struct sockaddr_in6
*)ai
->ai_addr
)->sin6_addr
;
157 /* can't get here because 'af' was previously checked */
159 "Unsupported AF family for %s (%d)", var_host
, af
);
169 /* restore '/' separator, if any */
182 getaddr(unsigned int flags
,
183 const char *hostname
,
184 int resolve_retry_seconds
,
186 struct signal_info
*sig_info
)
191 status
= get_addr_generic(AF_INET
, flags
, hostname
, &addr
, NULL
,
192 resolve_retry_seconds
, sig_info
,
213 get_ipv6_addr(const char *hostname
, struct in6_addr
*network
,
214 unsigned int *netbits
, int msglevel
)
216 if (get_addr_generic(AF_INET6
, GETADDR_RESOLVE
, hostname
, network
, netbits
,
217 0, NULL
, msglevel
) < 0)
222 return true; /* parsing OK, values set */
226 streqnull(const char *a
, const char *b
)
228 if (a
== NULL
&& b
== NULL
)
232 else if (a
== NULL
|| b
== NULL
)
243 * get_cached_dns_entry return 0 on success and -1
244 * otherwise. (like getaddrinfo)
247 get_cached_dns_entry(struct cached_dns_entry
*dns_cache
,
248 const char *hostname
,
249 const char *servname
,
252 struct addrinfo
**ai
)
254 struct cached_dns_entry
*ph
;
257 /* Only use flags that are relevant for the structure */
258 flags
= resolve_flags
& GETADDR_CACHE_MASK
;
260 for (ph
= dns_cache
; ph
; ph
= ph
->next
)
262 if (streqnull(ph
->hostname
, hostname
)
263 && streqnull(ph
->servname
, servname
)
264 && ph
->ai_family
== ai_family
265 && ph
->flags
== flags
)
276 do_preresolve_host(struct context
*c
,
277 const char *hostname
,
278 const char *servname
,
285 if (get_cached_dns_entry(c
->c1
.dns_cache
,
292 /* entry already cached, return success */
296 status
= openvpn_getaddrinfo(flags
, hostname
, servname
,
297 c
->options
.resolve_retry_seconds
, NULL
,
301 struct cached_dns_entry
*ph
;
303 ALLOC_OBJ_CLEAR_GC(ph
, struct cached_dns_entry
, &c
->gc
);
305 ph
->hostname
= hostname
;
306 ph
->servname
= servname
;
307 ph
->flags
= flags
& GETADDR_CACHE_MASK
;
309 if (!c
->c1
.dns_cache
)
311 c
->c1
.dns_cache
= ph
;
315 struct cached_dns_entry
*prev
= c
->c1
.dns_cache
;
323 gc_addspecial(ai
, &gc_freeaddrinfo_callback
, &c
->gc
);
330 do_preresolve(struct context
*c
)
333 struct connection_list
*l
= c
->options
.connection_list
;
334 const unsigned int preresolve_flags
= GETADDR_RESOLVE
335 |GETADDR_UPDATE_MANAGEMENT_STATE
336 |GETADDR_MENTION_RESOLVE_RETRY
340 for (i
= 0; i
< l
->len
; ++i
)
344 int flags
= preresolve_flags
;
346 struct connection_entry
*ce
= c
->options
.connection_list
->array
[i
];
348 if (proto_is_dgram(ce
->proto
))
350 flags
|= GETADDR_DATAGRAM
;
353 if (c
->options
.sockflags
& SF_HOST_RANDOMIZE
)
355 flags
|= GETADDR_RANDOMIZE
;
358 if (c
->options
.ip_remote_hint
)
360 remote
= c
->options
.ip_remote_hint
;
367 /* HTTP remote hostname does not need to be resolved */
368 if (!ce
->http_proxy_options
)
370 status
= do_preresolve_host(c
, remote
, ce
->remote_port
,
378 /* Preresolve proxy */
379 if (ce
->http_proxy_options
)
381 status
= do_preresolve_host(c
,
382 ce
->http_proxy_options
->server
,
383 ce
->http_proxy_options
->port
,
393 if (ce
->socks_proxy_server
)
395 status
= do_preresolve_host(c
,
396 ce
->socks_proxy_server
,
397 ce
->socks_proxy_port
,
408 flags
|= GETADDR_PASSIVE
;
409 flags
&= ~GETADDR_RANDOMIZE
;
410 status
= do_preresolve_host(c
, ce
->local
, ce
->local_port
,
423 throw_signal_soft(SIGHUP
, "Preresolving failed");
427 * Translate IPv4/IPv6 addr or hostname into struct addrinfo
428 * If resolve error, try again for resolve_retry_seconds seconds.
431 openvpn_getaddrinfo(unsigned int flags
,
432 const char *hostname
,
433 const char *servname
,
434 int resolve_retry_seconds
,
435 struct signal_info
*sig_info
,
437 struct addrinfo
**res
)
439 struct addrinfo hints
;
441 struct signal_info sigrec
= {0};
442 int msglevel
= (flags
& GETADDR_FATAL
) ? M_FATAL
: D_RESOLVE_ERRORS
;
443 struct gc_arena gc
= gc_new();
444 const char *print_hostname
;
445 const char *print_servname
;
449 ASSERT(hostname
|| servname
);
450 ASSERT(!(flags
& GETADDR_HOST_ORDER
));
454 print_servname
= servname
;
461 if (flags
& GETADDR_MSG_VIRT_OUT
)
463 msglevel
|= M_MSG_VIRT_OUT
;
466 if ((flags
& (GETADDR_FATAL_ON_SIGNAL
|GETADDR_WARN_ON_SIGNAL
))
472 /* try numeric ipv6 addr first */
474 hints
.ai_family
= ai_family
;
475 hints
.ai_flags
= AI_NUMERICHOST
;
477 if (flags
& GETADDR_PASSIVE
)
479 hints
.ai_flags
|= AI_PASSIVE
;
482 if (flags
& GETADDR_DATAGRAM
)
484 hints
.ai_socktype
= SOCK_DGRAM
;
488 hints
.ai_socktype
= SOCK_STREAM
;
491 status
= getaddrinfo(hostname
, servname
, &hints
, res
);
493 if (status
!= 0) /* parse as numeric address failed? */
495 const int fail_wait_interval
= 5; /* seconds */
496 /* Add +4 to cause integer division rounding up (1 + 4) = 5, (0+4)/5=0 */
497 int resolve_retries
= (flags
& GETADDR_TRY_ONCE
) ? 1 :
498 ((resolve_retry_seconds
+ 4)/ fail_wait_interval
);
502 if (hostname
&& (flags
& GETADDR_RANDOMIZE
))
504 hostname
= hostname_randomize(hostname
, &gc
);
509 print_hostname
= hostname
;
513 print_hostname
= "undefined";
516 fmt
= "RESOLVE: Cannot resolve host address: %s:%s (%s)";
517 if ((flags
& GETADDR_MENTION_RESOLVE_RETRY
)
518 && !resolve_retry_seconds
)
520 fmt
= "RESOLVE: Cannot resolve host address: %s:%s (%s) "
521 "(I would have retried this name query if you had "
522 "specified the --resolv-retry option.)";
525 if (!(flags
& GETADDR_RESOLVE
) || status
== EAI_FAIL
)
527 msg(msglevel
, "RESOLVE: Cannot parse IP address: %s:%s (%s)",
528 print_hostname
, print_servname
, gai_strerror(status
));
532 #ifdef ENABLE_MANAGEMENT
533 if (flags
& GETADDR_UPDATE_MANAGEMENT_STATE
)
537 management_set_state(management
,
538 OPENVPN_STATE_RESOLVE
,
554 /* force resolv.conf reload */
557 /* try hostname lookup */
558 hints
.ai_flags
&= ~AI_NUMERICHOST
;
560 "GETADDRINFO flags=0x%04x ai_family=%d ai_socktype=%d",
561 flags
, hints
.ai_family
, hints
.ai_socktype
);
562 status
= getaddrinfo(hostname
, servname
, &hints
, res
);
566 get_signal(&sig_info
->signal_received
);
567 if (sig_info
->signal_received
) /* were we interrupted by a signal? */
569 /* why are we overwriting SIGUSR1 ? */
570 if (sig_info
->signal_received
== SIGUSR1
) /* ignore SIGUSR1 */
573 "RESOLVE: Ignored SIGUSR1 signal received during "
574 "DNS resolution attempt");
575 signal_reset(sig_info
);
579 /* turn success into failure (interrupted syscall) */
585 status
= EAI_AGAIN
; /* = temporary failure */
599 /* resolve lookup failed, should we
600 * continue or fail? */
602 if (resolve_retries
> 0)
604 level
= D_RESOLVE_ERRORS
;
611 gai_strerror(status
));
613 if (--resolve_retries
<= 0)
618 management_sleep(fail_wait_interval
);
623 /* hostname resolve succeeded */
626 * Do not choose an IP Addresse by random or change the order *
627 * of IP addresses, doing so will break RFC 3484 address selection *
632 /* IP address parse succeeded */
633 if (flags
& GETADDR_RANDOMIZE
)
636 "WARNING: ignoring --remote-random-hostname because the "
637 "hostname is an IP address");
642 if (sig_info
&& sig_info
->signal_received
)
645 if (flags
& GETADDR_FATAL_ON_SIGNAL
)
649 else if (flags
& GETADDR_WARN_ON_SIGNAL
)
653 msg(level
, "RESOLVE: signal received during DNS resolution attempt");
661 * We do our own inet_aton because the glibc function
662 * isn't very good about error checking.
665 openvpn_inet_aton(const char *dotted_quad
, struct in_addr
*addr
)
667 unsigned int a
, b
, c
, d
;
670 if (sscanf(dotted_quad
, "%u.%u.%u.%u", &a
, &b
, &c
, &d
) == 4)
672 if (a
< 256 && b
< 256 && c
< 256 && d
< 256)
674 addr
->s_addr
= htonl(a
<<24 | b
<<16 | c
<<8 | d
);
675 return OIA_IP
; /* good dotted quad */
678 if (string_class(dotted_quad
, CC_DIGIT
|CC_DOT
, 0))
680 return OIA_ERROR
; /* probably a badly formatted dotted quad */
684 return OIA_HOSTNAME
; /* probably a hostname */
689 ip_addr_dotted_quad_safe(const char *dotted_quad
)
691 /* verify non-NULL */
697 /* verify length is within limits */
698 if (strlen(dotted_quad
) > 15)
703 /* verify that all chars are either numeric or '.' and that no numeric
704 * substring is greater than 3 chars */
707 const char *p
= dotted_quad
;
712 if (c
>= '0' && c
<= '9')
731 /* verify that string will convert to IP address */
734 return openvpn_inet_aton(dotted_quad
, &a
) == OIA_IP
;
739 ipv6_addr_safe(const char *ipv6_text_addr
)
741 /* verify non-NULL */
747 /* verify length is within limits */
748 if (strlen(ipv6_text_addr
) > INET6_ADDRSTRLEN
)
753 /* verify that string will convert to IPv6 address */
756 return inet_pton( AF_INET6
, ipv6_text_addr
, &a6
) == 1;
761 dns_addr_safe(const char *addr
)
765 const size_t len
= strlen(addr
);
766 return len
> 0 && len
<= 255 && string_class(addr
, CC_ALNUM
|CC_DASH
|CC_DOT
, 0);
775 ip_or_dns_addr_safe(const char *addr
, const bool allow_fqdn
)
777 if (ip_addr_dotted_quad_safe(addr
))
783 return dns_addr_safe(addr
);
792 mac_addr_safe(const char *mac_addr
)
794 /* verify non-NULL */
800 /* verify length is within limits */
801 if (strlen(mac_addr
) > 17)
806 /* verify that all chars are either alphanumeric or ':' and that no
807 * alphanumeric substring is greater than 2 chars */
810 const char *p
= mac_addr
;
815 if ( (c
>= '0' && c
<= '9') || (c
>= 'a' && c
<= 'f') || (c
>= 'A' && c
<= 'F') )
834 /* error-checking is left to script invoked in lladdr.c */
839 socket_get_sndbuf(socket_descriptor_t sd
)
841 #if defined(SOL_SOCKET) && defined(SO_SNDBUF)
846 if (getsockopt(sd
, SOL_SOCKET
, SO_SNDBUF
, (void *) &val
, &len
) == 0
847 && len
== sizeof(val
))
856 socket_set_sndbuf(socket_descriptor_t sd
, int size
)
858 #if defined(SOL_SOCKET) && defined(SO_SNDBUF)
859 if (setsockopt(sd
, SOL_SOCKET
, SO_SNDBUF
, (void *) &size
, sizeof(size
)) != 0)
861 msg(M_WARN
, "NOTE: setsockopt SO_SNDBUF=%d failed", size
);
867 socket_get_rcvbuf(socket_descriptor_t sd
)
869 #if defined(SOL_SOCKET) && defined(SO_RCVBUF)
874 if (getsockopt(sd
, SOL_SOCKET
, SO_RCVBUF
, (void *) &val
, &len
) == 0
875 && len
== sizeof(val
))
884 socket_set_rcvbuf(socket_descriptor_t sd
, int size
)
886 #if defined(SOL_SOCKET) && defined(SO_RCVBUF)
887 if (setsockopt(sd
, SOL_SOCKET
, SO_RCVBUF
, (void *) &size
, sizeof(size
)) != 0)
889 msg(M_WARN
, "NOTE: setsockopt SO_RCVBUF=%d failed", size
);
897 socket_set_buffers(socket_descriptor_t fd
, const struct socket_buffer_size
*sbs
)
901 const int sndbuf_old
= socket_get_sndbuf(fd
);
902 const int rcvbuf_old
= socket_get_rcvbuf(fd
);
906 socket_set_sndbuf(fd
, sbs
->sndbuf
);
911 socket_set_rcvbuf(fd
, sbs
->rcvbuf
);
914 msg(D_OSBUF
, "Socket Buffers: R=[%d->%d] S=[%d->%d]",
916 socket_get_rcvbuf(fd
),
918 socket_get_sndbuf(fd
));
923 * Set other socket options
927 socket_set_tcp_nodelay(socket_descriptor_t sd
, int state
)
929 #if defined(_WIN32) || (defined(IPPROTO_TCP) && defined(TCP_NODELAY))
930 if (setsockopt(sd
, IPPROTO_TCP
, TCP_NODELAY
, (void *) &state
, sizeof(state
)) != 0)
932 msg(M_WARN
, "NOTE: setsockopt TCP_NODELAY=%d failed", state
);
937 dmsg(D_OSBUF
, "Socket flags: TCP_NODELAY=%d succeeded", state
);
940 #else /* if defined(_WIN32) || (defined(IPPROTO_TCP) && defined(TCP_NODELAY)) */
941 msg(M_WARN
, "NOTE: setsockopt TCP_NODELAY=%d failed (No kernel support)", state
);
947 socket_set_mark(socket_descriptor_t sd
, int mark
)
949 #if defined(TARGET_LINUX) && HAVE_DECL_SO_MARK
950 if (mark
&& setsockopt(sd
, SOL_SOCKET
, SO_MARK
, (void *) &mark
, sizeof(mark
)) != 0)
952 msg(M_WARN
, "NOTE: setsockopt SO_MARK=%d failed", mark
);
958 socket_set_flags(socket_descriptor_t sd
, unsigned int sockflags
)
960 /* SF_TCP_NODELAY doesn't make sense for dco-win */
961 if ((sockflags
& SF_TCP_NODELAY
) && (!(sockflags
& SF_DCO_WIN
)))
963 return socket_set_tcp_nodelay(sd
, 1);
972 link_socket_update_flags(struct link_socket
*ls
, unsigned int sockflags
)
974 if (ls
&& socket_defined(ls
->sd
))
976 ls
->sockflags
|= sockflags
;
977 return socket_set_flags(ls
->sd
, ls
->sockflags
);
986 link_socket_update_buffer_sizes(struct link_socket
*ls
, int rcvbuf
, int sndbuf
)
988 if (ls
&& socket_defined(ls
->sd
))
990 ls
->socket_buffer_sizes
.sndbuf
= sndbuf
;
991 ls
->socket_buffer_sizes
.rcvbuf
= rcvbuf
;
992 socket_set_buffers(ls
->sd
, &ls
->socket_buffer_sizes
);
997 * SOCKET INITIALIZATION CODE.
998 * Create a TCP/UDP socket
1002 create_socket_tcp(struct addrinfo
*addrinfo
)
1004 socket_descriptor_t sd
;
1007 ASSERT(addrinfo
->ai_socktype
== SOCK_STREAM
);
1009 if ((sd
= socket(addrinfo
->ai_family
, addrinfo
->ai_socktype
, addrinfo
->ai_protocol
)) < 0)
1011 msg(M_ERR
, "Cannot create TCP socket");
1014 #ifndef _WIN32 /* using SO_REUSEADDR on Windows will cause bind to succeed on port conflicts! */
1015 /* set SO_REUSEADDR on socket */
1018 if (setsockopt(sd
, SOL_SOCKET
, SO_REUSEADDR
,
1019 (void *) &on
, sizeof(on
)) < 0)
1021 msg(M_ERR
, "TCP: Cannot setsockopt SO_REUSEADDR on TCP socket");
1026 /* set socket file descriptor to not pass across execs, so that
1027 * scripts don't have access to it */
1033 static socket_descriptor_t
1034 create_socket_udp(struct addrinfo
*addrinfo
, const unsigned int flags
)
1036 socket_descriptor_t sd
;
1039 ASSERT(addrinfo
->ai_socktype
== SOCK_DGRAM
);
1041 if ((sd
= socket(addrinfo
->ai_family
, addrinfo
->ai_socktype
, addrinfo
->ai_protocol
)) < 0)
1043 msg(M_ERR
, "UDP: Cannot create UDP/UDP6 socket");
1045 #if ENABLE_IP_PKTINFO
1046 else if (flags
& SF_USE_IP_PKTINFO
)
1049 if (addrinfo
->ai_family
== AF_INET
)
1051 #if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST)
1052 if (setsockopt(sd
, SOL_IP
, IP_PKTINFO
,
1053 (void *)&pad
, sizeof(pad
)) < 0)
1055 msg(M_ERR
, "UDP: failed setsockopt for IP_PKTINFO");
1057 #elif defined(IP_RECVDSTADDR)
1058 if (setsockopt(sd
, IPPROTO_IP
, IP_RECVDSTADDR
,
1059 (void *)&pad
, sizeof(pad
)) < 0)
1061 msg(M_ERR
, "UDP: failed setsockopt for IP_RECVDSTADDR");
1063 #else /* if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST) */
1064 #error ENABLE_IP_PKTINFO is set without IP_PKTINFO xor IP_RECVDSTADDR (fix syshead.h)
1067 else if (addrinfo
->ai_family
== AF_INET6
)
1069 #ifndef IPV6_RECVPKTINFO /* Some older Darwin platforms require this */
1070 if (setsockopt(sd
, IPPROTO_IPV6
, IPV6_PKTINFO
,
1071 (void *)&pad
, sizeof(pad
)) < 0)
1073 if (setsockopt(sd
, IPPROTO_IPV6
, IPV6_RECVPKTINFO
,
1074 (void *)&pad
, sizeof(pad
)) < 0)
1076 { msg(M_ERR
, "UDP: failed setsockopt for IPV6_RECVPKTINFO");}
1079 #endif /* if ENABLE_IP_PKTINFO */
1081 /* set socket file descriptor to not pass across execs, so that
1082 * scripts don't have access to it */
1089 bind_local(struct link_socket
*sock
, const sa_family_t ai_family
)
1091 /* bind to local address/port */
1092 if (sock
->bind_local
)
1094 if (sock
->socks_proxy
&& sock
->info
.proto
== PROTO_UDP
)
1096 socket_bind(sock
->ctrl_sd
, sock
->info
.lsa
->bind_local
,
1097 ai_family
, "SOCKS", false);
1101 socket_bind(sock
->sd
, sock
->info
.lsa
->bind_local
,
1103 "TCP/UDP", sock
->info
.bind_ipv6_only
);
1109 create_socket(struct link_socket
*sock
, struct addrinfo
*addr
)
1111 if (addr
->ai_protocol
== IPPROTO_UDP
|| addr
->ai_socktype
== SOCK_DGRAM
)
1113 sock
->sd
= create_socket_udp(addr
, sock
->sockflags
);
1114 sock
->sockflags
|= SF_GETADDRINFO_DGRAM
;
1116 /* Assume that control socket and data socket to the socks proxy
1117 * are using the same IP family */
1118 if (sock
->socks_proxy
)
1120 /* Construct a temporary addrinfo to create the socket,
1121 * currently resolve two remote addresses is not supported,
1122 * TODO: Rewrite the whole resolve_remote */
1123 struct addrinfo addrinfo_tmp
= *addr
;
1124 addrinfo_tmp
.ai_socktype
= SOCK_STREAM
;
1125 addrinfo_tmp
.ai_protocol
= IPPROTO_TCP
;
1126 sock
->ctrl_sd
= create_socket_tcp(&addrinfo_tmp
);
1129 else if (addr
->ai_protocol
== IPPROTO_TCP
|| addr
->ai_socktype
== SOCK_STREAM
)
1131 sock
->sd
= create_socket_tcp(addr
);
1137 /* Set af field of sock->info, so it always reflects the address family
1138 * of the created socket */
1139 sock
->info
.af
= addr
->ai_family
;
1141 /* set socket buffers based on --sndbuf and --rcvbuf options */
1142 socket_set_buffers(sock
->sd
, &sock
->socket_buffer_sizes
);
1144 /* set socket to --mark packets with given value */
1145 socket_set_mark(sock
->sd
, sock
->mark
);
1147 #if defined(TARGET_LINUX)
1150 msg(M_INFO
, "Using bind-dev %s", sock
->bind_dev
);
1151 if (setsockopt(sock
->sd
, SOL_SOCKET
, SO_BINDTODEVICE
, sock
->bind_dev
, strlen(sock
->bind_dev
) + 1) != 0)
1153 msg(M_WARN
|M_ERRNO
, "WARN: setsockopt SO_BINDTODEVICE=%s failed", sock
->bind_dev
);
1159 bind_local(sock
, addr
->ai_family
);
1162 #ifdef TARGET_ANDROID
1164 protect_fd_nonlocal(int fd
, const struct sockaddr
*addr
)
1168 msg(M_FATAL
, "Required management interface not available.");
1171 /* pass socket FD to management interface to pass on to VPNService API
1172 * as "protected socket" (exempt from being routed into tunnel)
1174 if (addr_local(addr
))
1176 msg(D_SOCKET_DEBUG
, "Address is local, not protecting socket fd %d", fd
);
1180 msg(D_SOCKET_DEBUG
, "Protecting socket fd %d", fd
);
1181 management
->connection
.fdtosend
= fd
;
1182 management_android_control(management
, "PROTECTFD", __func__
);
1187 * Functions used for establishing a TCP stream connection.
1190 socket_do_listen(socket_descriptor_t sd
,
1191 const struct addrinfo
*local
,
1193 bool do_set_nonblock
)
1195 struct gc_arena gc
= gc_new();
1199 msg(M_INFO
, "Listening for incoming TCP connection on %s",
1200 print_sockaddr(local
->ai_addr
, &gc
));
1203 msg(M_ERR
, "TCP: listen() failed");
1207 /* set socket to non-blocking mode */
1208 if (do_set_nonblock
)
1217 socket_do_accept(socket_descriptor_t sd
,
1218 struct link_socket_actual
*act
,
1221 /* af_addr_size WILL return 0 in this case if AFs other than AF_INET
1222 * are compiled because act is empty here.
1223 * could use getsockname() to support later remote_len check
1225 socklen_t remote_len_af
= af_addr_size(act
->dest
.addr
.sa
.sa_family
);
1226 socklen_t remote_len
= sizeof(act
->dest
.addr
);
1227 socket_descriptor_t new_sd
= SOCKET_UNDEFINED
;
1233 new_sd
= getpeername(sd
, &act
->dest
.addr
.sa
, &remote_len
);
1235 if (!socket_defined(new_sd
))
1237 msg(D_LINK_ERRORS
| M_ERRNO
, "TCP: getpeername() failed");
1246 new_sd
= accept(sd
, &act
->dest
.addr
.sa
, &remote_len
);
1249 #if 0 /* For debugging only, test the effect of accept() failures */
1260 if (!socket_defined(new_sd
))
1262 msg(D_LINK_ERRORS
| M_ERRNO
, "TCP: accept(%d) failed", (int)sd
);
1264 /* only valid if we have remote_len_af!=0 */
1265 else if (remote_len_af
&& remote_len
!= remote_len_af
)
1267 msg(D_LINK_ERRORS
, "TCP: Received strange incoming connection with unknown address length=%d", remote_len
);
1268 openvpn_close_socket(new_sd
);
1269 new_sd
= SOCKET_UNDEFINED
;
1273 /* set socket file descriptor to not pass across execs, so that
1274 * scripts don't have access to it */
1281 tcp_connection_established(const struct link_socket_actual
*act
)
1283 struct gc_arena gc
= gc_new();
1284 msg(M_INFO
, "TCP connection established with %s",
1285 print_link_socket_actual(act
, &gc
));
1289 static socket_descriptor_t
1290 socket_listen_accept(socket_descriptor_t sd
,
1291 struct link_socket_actual
*act
,
1292 const char *remote_dynamic
,
1293 const struct addrinfo
*local
,
1296 volatile int *signal_received
)
1298 struct gc_arena gc
= gc_new();
1299 /* struct openvpn_sockaddr *remote = &act->dest; */
1300 struct openvpn_sockaddr remote_verify
= act
->dest
;
1301 socket_descriptor_t new_sd
= SOCKET_UNDEFINED
;
1304 socket_do_listen(sd
, local
, do_listen
, true);
1313 openvpn_fd_set(sd
, &reads
);
1317 status
= select(sd
+ 1, &reads
, NULL
, NULL
, &tv
);
1319 get_signal(signal_received
);
1320 if (*signal_received
)
1328 msg(D_LINK_ERRORS
| M_ERRNO
, "TCP: select() failed");
1333 management_sleep(1);
1337 new_sd
= socket_do_accept(sd
, act
, nowait
);
1339 if (socket_defined(new_sd
))
1341 struct addrinfo
*ai
= NULL
;
1344 openvpn_getaddrinfo(0, remote_dynamic
, NULL
, 1, NULL
,
1345 remote_verify
.addr
.sa
.sa_family
, &ai
);
1348 if (ai
&& !addrlist_match(&remote_verify
, ai
))
1351 "TCP NOTE: Rejected connection attempt from %s due to --remote setting",
1352 print_link_socket_actual(act
, &gc
));
1353 if (openvpn_close_socket(new_sd
))
1355 msg(M_ERR
, "TCP: close socket failed (new_sd)");
1368 management_sleep(1);
1371 if (!nowait
&& openvpn_close_socket(sd
))
1373 msg(M_ERR
, "TCP: close socket failed (sd)");
1376 tcp_connection_established(act
);
1383 socket_bind(socket_descriptor_t sd
,
1384 struct addrinfo
*local
,
1389 struct gc_arena gc
= gc_new();
1392 * getaddrinfo for the bind address might return multiple AF_INET/AF_INET6
1393 * entries for the requested protocol.
1394 * For example if an address has multiple A records
1395 * What is the correct way to deal with it?
1398 struct addrinfo
*cur
;
1403 /* find the first addrinfo with correct ai_family */
1404 for (cur
= local
; cur
; cur
= cur
->ai_next
)
1406 if (cur
->ai_family
== ai_family
)
1413 msg(M_FATAL
, "%s: Socket bind failed: Addr to bind has no %s record",
1414 prefix
, addr_family_name(ai_family
));
1417 if (ai_family
== AF_INET6
)
1419 int v6only
= ipv6only
? 1 : 0; /* setsockopt must have an "int" */
1421 msg(M_INFO
, "setsockopt(IPV6_V6ONLY=%d)", v6only
);
1422 if (setsockopt(sd
, IPPROTO_IPV6
, IPV6_V6ONLY
, (void *) &v6only
, sizeof(v6only
)))
1424 msg(M_NONFATAL
|M_ERRNO
, "Setting IPV6_V6ONLY=%d failed", v6only
);
1427 if (bind(sd
, cur
->ai_addr
, cur
->ai_addrlen
))
1429 msg(M_FATAL
| M_ERRNO
, "%s: Socket bind failed on local address %s",
1431 print_sockaddr_ex(local
->ai_addr
, ":", PS_SHOW_PORT
, &gc
));
1437 openvpn_connect(socket_descriptor_t sd
,
1438 const struct sockaddr
*remote
,
1439 int connect_timeout
,
1440 volatile int *signal_received
)
1444 #ifdef TARGET_ANDROID
1445 protect_fd_nonlocal(sd
, remote
);
1449 status
= connect(sd
, remote
, af_addr_size(remote
->sa_family
));
1452 status
= openvpn_errno();
1456 status
== WSAEWOULDBLOCK
1458 status
== EINPROGRESS
1465 struct pollfd fds
[1];
1467 fds
[0].events
= POLLOUT
;
1468 status
= poll(fds
, 1, (connect_timeout
> 0) ? 1000 : 0);
1474 openvpn_fd_set(sd
, &writes
);
1475 tv
.tv_sec
= (connect_timeout
> 0) ? 1 : 0;
1478 status
= select(sd
+ 1, NULL
, &writes
, NULL
, &tv
);
1480 if (signal_received
)
1482 get_signal(signal_received
);
1483 if (*signal_received
)
1491 status
= openvpn_errno();
1496 if (--connect_timeout
< 0)
1499 status
= WSAETIMEDOUT
;
1505 management_sleep(0);
1515 if (getsockopt(sd
, SOL_SOCKET
, SO_ERROR
, (void *) &val
, &len
) == 0
1516 && len
== sizeof(val
))
1522 status
= openvpn_errno();
1533 set_actual_address(struct link_socket_actual
*actual
, struct addrinfo
*ai
)
1538 if (ai
->ai_family
== AF_INET
)
1540 actual
->dest
.addr
.in4
=
1541 *((struct sockaddr_in
*) ai
->ai_addr
);
1543 else if (ai
->ai_family
== AF_INET6
)
1545 actual
->dest
.addr
.in6
=
1546 *((struct sockaddr_in6
*) ai
->ai_addr
);
1556 socket_connect(socket_descriptor_t
*sd
,
1557 const struct sockaddr
*dest
,
1558 const int connect_timeout
,
1559 struct signal_info
*sig_info
)
1561 struct gc_arena gc
= gc_new();
1564 msg(M_INFO
, "Attempting to establish TCP connection with %s",
1565 print_sockaddr(dest
, &gc
));
1567 #ifdef ENABLE_MANAGEMENT
1570 management_set_state(management
,
1571 OPENVPN_STATE_TCP_CONNECT
,
1580 /* Set the actual address */
1581 status
= openvpn_connect(*sd
, dest
, connect_timeout
, &sig_info
->signal_received
);
1583 get_signal(&sig_info
->signal_received
);
1584 if (sig_info
->signal_received
)
1592 msg(D_LINK_ERRORS
, "TCP: connect to %s failed: %s",
1593 print_sockaddr(dest
, &gc
), strerror(status
));
1595 openvpn_close_socket(*sd
);
1596 *sd
= SOCKET_UNDEFINED
;
1597 register_signal(sig_info
, SIGUSR1
, "connection-failed");
1598 sig_info
->source
= SIG_SOURCE_CONNECTION_FAILED
;
1602 msg(M_INFO
, "TCP connection established with %s",
1603 print_sockaddr(dest
, &gc
));
1611 * Stream buffer handling prototypes -- stream_buf is a helper class
1612 * to assist in the packetization of stream transport protocols
1617 stream_buf_init(struct stream_buf
*sb
, struct buffer
*buf
,
1618 const unsigned int sockflags
, const int proto
);
1621 stream_buf_close(struct stream_buf
*sb
);
1624 stream_buf_added(struct stream_buf
*sb
, int length_added
);
1626 /* For stream protocols, allocate a buffer to build up packet.
1627 * Called after frame has been finalized. */
1630 socket_frame_init(const struct frame
*frame
, struct link_socket
*sock
)
1633 overlapped_io_init(&sock
->reads
, frame
, FALSE
);
1634 overlapped_io_init(&sock
->writes
, frame
, TRUE
);
1635 sock
->rw_handle
.read
= sock
->reads
.overlapped
.hEvent
;
1636 sock
->rw_handle
.write
= sock
->writes
.overlapped
.hEvent
;
1639 if (link_socket_connection_oriented(sock
))
1642 stream_buf_init(&sock
->stream_buf
,
1643 &sock
->reads
.buf_init
,
1647 alloc_buf_sock_tun(&sock
->stream_buf_data
, frame
);
1649 stream_buf_init(&sock
->stream_buf
,
1650 &sock
->stream_buf_data
,
1658 resolve_bind_local(struct link_socket
*sock
, const sa_family_t af
)
1660 struct gc_arena gc
= gc_new();
1662 /* resolve local address if undefined */
1663 if (!sock
->info
.lsa
->bind_local
)
1665 int flags
= GETADDR_RESOLVE
| GETADDR_WARN_ON_SIGNAL
1666 |GETADDR_FATAL
| GETADDR_PASSIVE
;
1669 if (proto_is_dgram(sock
->info
.proto
))
1671 flags
|= GETADDR_DATAGRAM
;
1674 /* will return AF_{INET|INET6}from local_host */
1675 status
= get_cached_dns_entry(sock
->dns_cache
,
1680 &sock
->info
.lsa
->bind_local
);
1684 status
= openvpn_getaddrinfo(flags
, sock
->local_host
, sock
->local_port
, 0,
1685 NULL
, af
, &sock
->info
.lsa
->bind_local
);
1690 msg(M_FATAL
, "getaddrinfo() failed for local \"%s:%s\": %s",
1691 sock
->local_host
, sock
->local_port
,
1692 gai_strerror(status
));
1700 resolve_remote(struct link_socket
*sock
,
1702 const char **remote_dynamic
,
1703 struct signal_info
*sig_info
)
1705 volatile int *signal_received
= sig_info
? &sig_info
->signal_received
: NULL
;
1706 struct gc_arena gc
= gc_new();
1708 /* resolve remote address if undefined */
1709 if (!sock
->info
.lsa
->remote_list
)
1711 if (sock
->remote_host
)
1713 unsigned int flags
= sf2gaf(GETADDR_RESOLVE
|GETADDR_UPDATE_MANAGEMENT_STATE
, sock
->sockflags
);
1716 struct addrinfo
*ai
;
1717 if (proto_is_dgram(sock
->info
.proto
))
1719 flags
|= GETADDR_DATAGRAM
;
1722 if (sock
->resolve_retry_seconds
== RESOLV_RETRY_INFINITE
)
1726 flags
|= (GETADDR_TRY_ONCE
| GETADDR_FATAL
);
1730 else if (phase
== 1)
1732 if (sock
->resolve_retry_seconds
)
1738 flags
|= (GETADDR_FATAL
| GETADDR_MENTION_RESOLVE_RETRY
);
1742 else if (phase
== 2)
1744 if (sock
->resolve_retry_seconds
)
1746 flags
|= GETADDR_FATAL
;
1747 retry
= sock
->resolve_retry_seconds
;
1760 status
= get_cached_dns_entry(sock
->dns_cache
,
1767 status
= openvpn_getaddrinfo(flags
, sock
->remote_host
, sock
->remote_port
,
1768 retry
, sig_info
, sock
->info
.af
, &ai
);
1773 sock
->info
.lsa
->remote_list
= ai
;
1774 sock
->info
.lsa
->current_remote
= ai
;
1776 dmsg(D_SOCKET_DEBUG
,
1777 "RESOLVE_REMOTE flags=0x%04x phase=%d rrs=%d sig=%d status=%d",
1781 signal_received
? *signal_received
: -1,
1784 if (signal_received
&& *signal_received
)
1790 if (signal_received
)
1792 /* potential overwrite of signal */
1793 register_signal(sig_info
, SIGUSR1
, "socks-resolve-failure");
1800 /* should we re-use previous active remote address? */
1801 if (link_socket_actual_defined(&sock
->info
.lsa
->actual
))
1803 msg(M_INFO
, "TCP/UDP: Preserving recently used remote address: %s",
1804 print_link_socket_actual(&sock
->info
.lsa
->actual
, &gc
));
1807 *remote_dynamic
= NULL
;
1812 CLEAR(sock
->info
.lsa
->actual
);
1813 if (sock
->info
.lsa
->current_remote
)
1815 set_actual_address(&sock
->info
.lsa
->actual
,
1816 sock
->info
.lsa
->current_remote
);
1826 struct link_socket
*
1827 link_socket_new(void)
1829 struct link_socket
*sock
;
1831 ALLOC_OBJ_CLEAR(sock
, struct link_socket
);
1832 sock
->sd
= SOCKET_UNDEFINED
;
1833 sock
->ctrl_sd
= SOCKET_UNDEFINED
;
1838 link_socket_init_phase1(struct context
*c
, int mode
)
1840 struct link_socket
*sock
= c
->c2
.link_socket
;
1841 struct options
*o
= &c
->options
;
1844 const char *remote_host
= o
->ce
.remote
;
1845 const char *remote_port
= o
->ce
.remote_port
;
1847 sock
->local_host
= o
->ce
.local
;
1848 sock
->local_port
= o
->ce
.local_port
;
1849 sock
->remote_host
= remote_host
;
1850 sock
->remote_port
= remote_port
;
1851 sock
->dns_cache
= c
->c1
.dns_cache
;
1852 sock
->http_proxy
= c
->c1
.http_proxy
;
1853 sock
->socks_proxy
= c
->c1
.socks_proxy
;
1854 sock
->bind_local
= o
->ce
.bind_local
;
1855 sock
->resolve_retry_seconds
= o
->resolve_retry_seconds
;
1856 sock
->mtu_discover_type
= o
->ce
.mtu_discover_type
;
1859 sock
->gremlin
= o
->gremlin
;
1862 sock
->socket_buffer_sizes
.rcvbuf
= o
->rcvbuf
;
1863 sock
->socket_buffer_sizes
.sndbuf
= o
->sndbuf
;
1865 sock
->sockflags
= o
->sockflags
;
1867 if (o
->port_share_host
&& o
->port_share_port
)
1869 sock
->sockflags
|= SF_PORT_SHARE
;
1872 sock
->mark
= o
->mark
;
1873 sock
->bind_dev
= o
->bind_dev
;
1875 sock
->info
.proto
= o
->ce
.proto
;
1876 sock
->info
.af
= o
->ce
.af
;
1877 sock
->info
.remote_float
= o
->ce
.remote_float
;
1878 sock
->info
.lsa
= &c
->c1
.link_socket_addr
;
1879 sock
->info
.bind_ipv6_only
= o
->ce
.bind_ipv6_only
;
1880 sock
->info
.ipchange_command
= o
->ipchange
;
1881 sock
->info
.plugins
= c
->plugins
;
1882 sock
->server_poll_timeout
= &c
->c2
.server_poll_interval
;
1885 if (mode
== LS_MODE_TCP_ACCEPT_FROM
)
1887 ASSERT(c
->c2
.accept_from
);
1888 ASSERT(sock
->info
.proto
== PROTO_TCP_SERVER
);
1889 sock
->sd
= c
->c2
.accept_from
->sd
;
1890 /* inherit (possibly guessed) info AF from parent context */
1891 sock
->info
.af
= c
->c2
.accept_from
->info
.af
;
1894 /* are we running in HTTP proxy mode? */
1895 if (sock
->http_proxy
)
1897 ASSERT(sock
->info
.proto
== PROTO_TCP_CLIENT
);
1899 /* the proxy server */
1900 sock
->remote_host
= c
->c1
.http_proxy
->options
.server
;
1901 sock
->remote_port
= c
->c1
.http_proxy
->options
.port
;
1903 /* the OpenVPN server we will use the proxy to connect to */
1904 sock
->proxy_dest_host
= remote_host
;
1905 sock
->proxy_dest_port
= remote_port
;
1907 /* or in Socks proxy mode? */
1908 else if (sock
->socks_proxy
)
1910 /* the proxy server */
1911 sock
->remote_host
= c
->c1
.socks_proxy
->server
;
1912 sock
->remote_port
= c
->c1
.socks_proxy
->port
;
1914 /* the OpenVPN server we will use the proxy to connect to */
1915 sock
->proxy_dest_host
= remote_host
;
1916 sock
->proxy_dest_port
= remote_port
;
1920 sock
->remote_host
= remote_host
;
1921 sock
->remote_port
= remote_port
;
1924 /* bind behavior for TCP server vs. client */
1925 if (sock
->info
.proto
== PROTO_TCP_SERVER
)
1927 if (sock
->mode
== LS_MODE_TCP_ACCEPT_FROM
)
1929 sock
->bind_local
= false;
1933 sock
->bind_local
= true;
1937 if (mode
!= LS_MODE_TCP_ACCEPT_FROM
)
1939 if (sock
->bind_local
)
1941 resolve_bind_local(sock
, sock
->info
.af
);
1943 resolve_remote(sock
, 1, NULL
, NULL
);
1948 phase2_set_socket_flags(struct link_socket
*sock
)
1950 /* set misc socket parameters */
1951 socket_set_flags(sock
->sd
, sock
->sockflags
);
1953 /* set socket to non-blocking mode */
1954 set_nonblock(sock
->sd
);
1956 /* set Path MTU discovery options on the socket */
1957 set_mtu_discover_type(sock
->sd
, sock
->mtu_discover_type
, sock
->info
.af
);
1959 #if EXTENDED_SOCKET_ERROR_CAPABILITY
1960 /* if the OS supports it, enable extended error passing on the socket */
1961 set_sock_extended_error_passing(sock
->sd
, sock
->info
.af
);
1967 linksock_print_addr(struct link_socket
*sock
)
1969 struct gc_arena gc
= gc_new();
1970 const int msglevel
= (sock
->mode
== LS_MODE_TCP_ACCEPT_FROM
) ? D_INIT_MEDIUM
: M_INFO
;
1972 /* print local address */
1973 if (sock
->bind_local
)
1975 sa_family_t ai_family
= sock
->info
.lsa
->actual
.dest
.addr
.sa
.sa_family
;
1976 /* Socket is always bound on the first matching address,
1977 * For bound sockets with no remote addr this is the element of
1979 struct addrinfo
*cur
;
1980 for (cur
= sock
->info
.lsa
->bind_local
; cur
; cur
= cur
->ai_next
)
1982 if (!ai_family
|| ai_family
== cur
->ai_family
)
1988 msg(msglevel
, "%s link local (bound): %s",
1989 proto2ascii(sock
->info
.proto
, sock
->info
.af
, true),
1990 print_sockaddr(cur
->ai_addr
, &gc
));
1994 msg(msglevel
, "%s link local: (not bound)",
1995 proto2ascii(sock
->info
.proto
, sock
->info
.af
, true));
1998 /* print active remote address */
1999 msg(msglevel
, "%s link remote: %s",
2000 proto2ascii(sock
->info
.proto
, sock
->info
.af
, true),
2001 print_link_socket_actual_ex(&sock
->info
.lsa
->actual
,
2003 PS_SHOW_PORT_IF_DEFINED
,
2009 phase2_tcp_server(struct link_socket
*sock
, const char *remote_dynamic
,
2010 struct signal_info
*sig_info
)
2012 volatile int *signal_received
= sig_info
? &sig_info
->signal_received
: NULL
;
2015 case LS_MODE_DEFAULT
:
2016 sock
->sd
= socket_listen_accept(sock
->sd
,
2017 &sock
->info
.lsa
->actual
,
2019 sock
->info
.lsa
->bind_local
,
2025 case LS_MODE_TCP_LISTEN
:
2026 socket_do_listen(sock
->sd
,
2027 sock
->info
.lsa
->bind_local
,
2032 case LS_MODE_TCP_ACCEPT_FROM
:
2033 sock
->sd
= socket_do_accept(sock
->sd
,
2034 &sock
->info
.lsa
->actual
,
2036 if (!socket_defined(sock
->sd
))
2038 register_signal(sig_info
, SIGTERM
, "socket-undefiled");
2041 tcp_connection_established(&sock
->info
.lsa
->actual
);
2051 phase2_tcp_client(struct link_socket
*sock
, struct signal_info
*sig_info
)
2053 bool proxy_retry
= false;
2056 socket_connect(&sock
->sd
,
2057 sock
->info
.lsa
->current_remote
->ai_addr
,
2058 get_server_poll_remaining_time(sock
->server_poll_timeout
),
2061 if (sig_info
->signal_received
)
2066 if (sock
->http_proxy
)
2068 proxy_retry
= establish_http_proxy_passthru(sock
->http_proxy
,
2070 sock
->proxy_dest_host
,
2071 sock
->proxy_dest_port
,
2072 sock
->server_poll_timeout
,
2073 &sock
->stream_buf
.residual
,
2076 else if (sock
->socks_proxy
)
2078 establish_socks_proxy_passthru(sock
->socks_proxy
,
2080 sock
->proxy_dest_host
,
2081 sock
->proxy_dest_port
,
2086 openvpn_close_socket(sock
->sd
);
2087 sock
->sd
= create_socket_tcp(sock
->info
.lsa
->current_remote
);
2090 } while (proxy_retry
);
2095 phase2_socks_client(struct link_socket
*sock
, struct signal_info
*sig_info
)
2097 socket_connect(&sock
->ctrl_sd
,
2098 sock
->info
.lsa
->current_remote
->ai_addr
,
2099 get_server_poll_remaining_time(sock
->server_poll_timeout
),
2102 if (sig_info
->signal_received
)
2107 establish_socks_proxy_udpassoc(sock
->socks_proxy
,
2110 &sock
->socks_relay
.dest
,
2113 if (sig_info
->signal_received
)
2118 sock
->remote_host
= sock
->proxy_dest_host
;
2119 sock
->remote_port
= sock
->proxy_dest_port
;
2121 addr_zero_host(&sock
->info
.lsa
->actual
.dest
);
2122 if (sock
->info
.lsa
->remote_list
)
2124 freeaddrinfo(sock
->info
.lsa
->remote_list
);
2125 sock
->info
.lsa
->current_remote
= NULL
;
2126 sock
->info
.lsa
->remote_list
= NULL
;
2129 resolve_remote(sock
, 1, NULL
, sig_info
);
2134 create_socket_dco_win(struct context
*c
, struct link_socket
*sock
,
2135 struct signal_info
*sig_info
)
2140 ALLOC_OBJ(tt
, struct tuntap
);
2142 *tt
= create_dco_handle(c
->options
.dev_node
, &c
->gc
);
2144 /* Ensure we can "safely" cast the handle to a socket */
2145 static_assert(sizeof(sock
->sd
) == sizeof(tt
->hand
), "HANDLE and SOCKET size differs");
2150 dco_create_socket(c
->c1
.tuntap
->hand
,
2151 sock
->info
.lsa
->current_remote
,
2152 sock
->bind_local
, sock
->info
.lsa
->bind_local
,
2153 get_server_poll_remaining_time(sock
->server_poll_timeout
),
2156 sock
->sockflags
|= SF_DCO_WIN
;
2158 if (sig_info
->signal_received
)
2163 sock
->sd
= (SOCKET
)c
->c1
.tuntap
->hand
;
2164 linksock_print_addr(sock
);
2166 #endif /* if defined(_WIN32) */
2168 /* finalize socket initialization */
2170 link_socket_init_phase2(struct context
*c
)
2172 struct link_socket
*sock
= c
->c2
.link_socket
;
2173 const struct frame
*frame
= &c
->c2
.frame
;
2174 struct signal_info
*sig_info
= c
->sig
;
2176 const char *remote_dynamic
= NULL
;
2177 struct signal_info sig_save
= {0};
2182 if (sig_info
->signal_received
)
2184 sig_save
= *sig_info
;
2185 signal_reset(sig_info
);
2188 /* initialize buffers */
2189 socket_frame_init(frame
, sock
);
2192 * Pass a remote name to connect/accept so that
2193 * they can test for dynamic IP address changes
2194 * and throw a SIGUSR1 if appropriate.
2196 if (sock
->resolve_retry_seconds
)
2198 remote_dynamic
= sock
->remote_host
;
2201 /* Second chance to resolv/create socket */
2202 resolve_remote(sock
, 2, &remote_dynamic
, sig_info
);
2204 /* If a valid remote has been found, create the socket with its addrinfo */
2205 if (sock
->info
.lsa
->current_remote
)
2208 if (dco_enabled(&c
->options
))
2210 create_socket_dco_win(c
, sock
, sig_info
);
2216 create_socket(sock
, sock
->info
.lsa
->current_remote
);
2221 /* If socket has not already been created create it now */
2222 if (sock
->sd
== SOCKET_UNDEFINED
)
2224 /* If we have no --remote and have still not figured out the
2225 * protocol family to use we will use the first of the bind */
2227 if (sock
->bind_local
&& !sock
->remote_host
&& sock
->info
.lsa
->bind_local
)
2229 /* Warn if this is because neither v4 or v6 was specified
2230 * and we should not connect a remote */
2231 if (sock
->info
.af
== AF_UNSPEC
)
2233 msg(M_WARN
, "Could not determine IPv4/IPv6 protocol. Using %s",
2234 addr_family_name(sock
->info
.lsa
->bind_local
->ai_family
));
2235 sock
->info
.af
= sock
->info
.lsa
->bind_local
->ai_family
;
2238 create_socket(sock
, sock
->info
.lsa
->bind_local
);
2242 /* Socket still undefined, give a warning and abort connection */
2243 if (sock
->sd
== SOCKET_UNDEFINED
)
2245 msg(M_WARN
, "Could not determine IPv4/IPv6 protocol");
2246 register_signal(sig_info
, SIGUSR1
, "Could not determine IPv4/IPv6 protocol");
2250 if (sig_info
->signal_received
)
2255 if (sock
->info
.proto
== PROTO_TCP_SERVER
)
2257 phase2_tcp_server(sock
, remote_dynamic
, sig_info
);
2259 else if (sock
->info
.proto
== PROTO_TCP_CLIENT
)
2261 phase2_tcp_client(sock
, sig_info
);
2264 else if (sock
->info
.proto
== PROTO_UDP
&& sock
->socks_proxy
)
2266 phase2_socks_client(sock
, sig_info
);
2268 #ifdef TARGET_ANDROID
2271 protect_fd_nonlocal(sock
->sd
, &sock
->info
.lsa
->actual
.dest
.addr
.sa
);
2274 if (sig_info
->signal_received
)
2279 phase2_set_socket_flags(sock
);
2280 linksock_print_addr(sock
);
2283 if (sig_save
.signal_received
)
2285 /* Always restore the saved signal -- register/throw_signal will handle priority */
2286 if (sig_save
.source
== SIG_SOURCE_HARD
&& sig_info
== &siginfo_static
)
2288 throw_signal(sig_save
.signal_received
);
2292 register_signal(sig_info
, sig_save
.signal_received
, sig_save
.signal_text
);
2298 link_socket_close(struct link_socket
*sock
)
2303 const int gremlin
= GREMLIN_CONNECTION_FLOOD_LEVEL(sock
->gremlin
);
2305 const int gremlin
= 0;
2308 if (socket_defined(sock
->sd
))
2311 close_net_event_win32(&sock
->listen_handle
, sock
->sd
, 0);
2315 msg(D_LOW
, "TCP/UDP: Closing socket");
2316 if (openvpn_close_socket(sock
->sd
))
2318 msg(M_WARN
| M_ERRNO
, "TCP/UDP: Close Socket failed");
2321 sock
->sd
= SOCKET_UNDEFINED
;
2325 overlapped_io_close(&sock
->reads
);
2326 overlapped_io_close(&sock
->writes
);
2331 if (socket_defined(sock
->ctrl_sd
))
2333 if (openvpn_close_socket(sock
->ctrl_sd
))
2335 msg(M_WARN
| M_ERRNO
, "TCP/UDP: Close Socket (ctrl_sd) failed");
2337 sock
->ctrl_sd
= SOCKET_UNDEFINED
;
2340 stream_buf_close(&sock
->stream_buf
);
2341 free_buf(&sock
->stream_buf_data
);
2350 setenv_trusted(struct env_set
*es
, const struct link_socket_info
*info
)
2352 setenv_link_socket_actual(es
, "trusted", &info
->lsa
->actual
, SA_IP_PORT
);
2356 ipchange_fmt(const bool include_cmd
, struct argv
*argv
, const struct link_socket_info
*info
, struct gc_arena
*gc
)
2358 const char *host
= print_sockaddr_ex(&info
->lsa
->actual
.dest
.addr
.sa
, " ", PS_SHOW_PORT
, gc
);
2361 argv_parse_cmd(argv
, info
->ipchange_command
);
2362 argv_printf_cat(argv
, "%s", host
);
2366 argv_printf(argv
, "%s", host
);
2372 link_socket_connection_initiated(struct link_socket_info
*info
,
2373 const struct link_socket_actual
*act
,
2374 const char *common_name
,
2377 struct gc_arena gc
= gc_new();
2379 info
->lsa
->actual
= *act
; /* Note: skip this line for --force-dest */
2380 setenv_trusted(es
, info
);
2381 info
->connection_established
= true;
2383 /* Print connection initiated message, with common name if available */
2385 struct buffer out
= alloc_buf_gc(256, &gc
);
2388 buf_printf(&out
, "[%s] ", common_name
);
2390 buf_printf(&out
, "Peer Connection Initiated with %s", print_link_socket_actual(&info
->lsa
->actual
, &gc
));
2391 msg(M_INFO
, "%s", BSTR(&out
));
2394 /* set environmental vars */
2395 setenv_str(es
, "common_name", common_name
);
2397 /* Process --ipchange plugin */
2398 if (plugin_defined(info
->plugins
, OPENVPN_PLUGIN_IPCHANGE
))
2400 struct argv argv
= argv_new();
2401 ipchange_fmt(false, &argv
, info
, &gc
);
2402 if (plugin_call(info
->plugins
, OPENVPN_PLUGIN_IPCHANGE
, &argv
, NULL
, es
) != OPENVPN_PLUGIN_FUNC_SUCCESS
)
2404 msg(M_WARN
, "WARNING: ipchange plugin call failed");
2409 /* Process --ipchange option */
2410 if (info
->ipchange_command
)
2412 struct argv argv
= argv_new();
2413 setenv_str(es
, "script_type", "ipchange");
2414 ipchange_fmt(true, &argv
, info
, &gc
);
2415 openvpn_run_script(&argv
, es
, 0, "--ipchange");
2423 link_socket_bad_incoming_addr(struct buffer
*buf
,
2424 const struct link_socket_info
*info
,
2425 const struct link_socket_actual
*from_addr
)
2427 struct gc_arena gc
= gc_new();
2428 struct addrinfo
*ai
;
2430 switch (from_addr
->dest
.addr
.sa
.sa_family
)
2435 "TCP/UDP: Incoming packet rejected from %s[%d], expected peer address: %s (allow this incoming source address/port by removing --remote or adding --float)",
2436 print_link_socket_actual(from_addr
, &gc
),
2437 (int)from_addr
->dest
.addr
.sa
.sa_family
,
2438 print_sockaddr_ex(info
->lsa
->remote_list
->ai_addr
, ":", PS_SHOW_PORT
, &gc
));
2439 /* print additional remote addresses */
2440 for (ai
= info
->lsa
->remote_list
->ai_next
; ai
; ai
= ai
->ai_next
)
2442 msg(D_LINK_ERRORS
, "or from peer address: %s",
2443 print_sockaddr_ex(ai
->ai_addr
, ":", PS_SHOW_PORT
, &gc
));
2452 link_socket_bad_outgoing_addr(void)
2454 dmsg(D_READ_WRITE
, "TCP/UDP: No outgoing address to send packet");
2458 link_socket_current_remote(const struct link_socket_info
*info
)
2460 const struct link_socket_addr
*lsa
= info
->lsa
;
2463 * This logic supports "redirect-gateway" semantic, which
2464 * makes sense only for PF_INET routes over PF_INET endpoints
2466 * Maybe in the future consider PF_INET6 endpoints also ...
2467 * by now just ignore it
2469 * For --remote entries with multiple addresses this
2470 * only return the actual endpoint we have successfully connected to
2472 if (lsa
->actual
.dest
.addr
.sa
.sa_family
!= AF_INET
)
2474 return IPV4_INVALID_ADDR
;
2477 if (link_socket_actual_defined(&lsa
->actual
))
2479 return ntohl(lsa
->actual
.dest
.addr
.in4
.sin_addr
.s_addr
);
2481 else if (lsa
->current_remote
)
2483 return ntohl(((struct sockaddr_in
*)lsa
->current_remote
->ai_addr
)
2492 const struct in6_addr
*
2493 link_socket_current_remote_ipv6(const struct link_socket_info
*info
)
2495 const struct link_socket_addr
*lsa
= info
->lsa
;
2497 /* This logic supports "redirect-gateway" semantic,
2498 * for PF_INET6 routes over PF_INET6 endpoints
2500 * For --remote entries with multiple addresses this
2501 * only return the actual endpoint we have successfully connected to
2503 if (lsa
->actual
.dest
.addr
.sa
.sa_family
!= AF_INET6
)
2508 if (link_socket_actual_defined(&lsa
->actual
))
2510 return &(lsa
->actual
.dest
.addr
.in6
.sin6_addr
);
2512 else if (lsa
->current_remote
)
2514 return &(((struct sockaddr_in6
*)lsa
->current_remote
->ai_addr
)->sin6_addr
);
2523 * Return a status string describing socket state.
2526 socket_stat(const struct link_socket
*s
, unsigned int rwflags
, struct gc_arena
*gc
)
2528 struct buffer out
= alloc_buf_gc(64, gc
);
2531 if (rwflags
& EVENT_READ
)
2533 buf_printf(&out
, "S%s",
2534 (s
->rwflags_debug
& EVENT_READ
) ? "R" : "r");
2536 buf_printf(&out
, "%s",
2537 overlapped_io_state_ascii(&s
->reads
));
2540 if (rwflags
& EVENT_WRITE
)
2542 buf_printf(&out
, "S%s",
2543 (s
->rwflags_debug
& EVENT_WRITE
) ? "W" : "w");
2545 buf_printf(&out
, "%s",
2546 overlapped_io_state_ascii(&s
->writes
));
2552 buf_printf(&out
, "S?");
2558 * Stream buffer functions, used to packetize a TCP
2559 * stream connection.
2563 stream_buf_reset(struct stream_buf
*sb
)
2565 dmsg(D_STREAM_DEBUG
, "STREAM: RESET");
2566 sb
->residual_fully_formed
= false;
2567 sb
->buf
= sb
->buf_init
;
2568 buf_reset(&sb
->next
);
2573 stream_buf_init(struct stream_buf
*sb
,
2575 const unsigned int sockflags
,
2578 sb
->buf_init
= *buf
;
2579 sb
->maxlen
= sb
->buf_init
.len
;
2580 sb
->buf_init
.len
= 0;
2581 sb
->residual
= alloc_buf(sb
->maxlen
);
2584 sb
->port_share_state
= ((sockflags
& SF_PORT_SHARE
) && (proto
== PROTO_TCP_SERVER
))
2588 stream_buf_reset(sb
);
2590 dmsg(D_STREAM_DEBUG
, "STREAM: INIT maxlen=%d", sb
->maxlen
);
2594 stream_buf_set_next(struct stream_buf
*sb
)
2596 /* set up 'next' for next i/o read */
2598 sb
->next
.offset
= sb
->buf
.offset
+ sb
->buf
.len
;
2599 sb
->next
.len
= (sb
->len
>= 0 ? sb
->len
: sb
->maxlen
) - sb
->buf
.len
;
2600 dmsg(D_STREAM_DEBUG
, "STREAM: SET NEXT, buf=[%d,%d] next=[%d,%d] len=%d maxlen=%d",
2601 sb
->buf
.offset
, sb
->buf
.len
,
2602 sb
->next
.offset
, sb
->next
.len
,
2603 sb
->len
, sb
->maxlen
);
2604 ASSERT(sb
->next
.len
> 0);
2605 ASSERT(buf_safe(&sb
->buf
, sb
->next
.len
));
2609 stream_buf_get_final(struct stream_buf
*sb
, struct buffer
*buf
)
2611 dmsg(D_STREAM_DEBUG
, "STREAM: GET FINAL len=%d",
2612 buf_defined(&sb
->buf
) ? sb
->buf
.len
: -1);
2613 ASSERT(buf_defined(&sb
->buf
));
2618 stream_buf_get_next(struct stream_buf
*sb
, struct buffer
*buf
)
2620 dmsg(D_STREAM_DEBUG
, "STREAM: GET NEXT len=%d",
2621 buf_defined(&sb
->next
) ? sb
->next
.len
: -1);
2622 ASSERT(buf_defined(&sb
->next
));
2627 stream_buf_read_setup_dowork(struct link_socket
*sock
)
2629 if (sock
->stream_buf
.residual
.len
&& !sock
->stream_buf
.residual_fully_formed
)
2631 ASSERT(buf_copy(&sock
->stream_buf
.buf
, &sock
->stream_buf
.residual
));
2632 ASSERT(buf_init(&sock
->stream_buf
.residual
, 0));
2633 sock
->stream_buf
.residual_fully_formed
= stream_buf_added(&sock
->stream_buf
, 0);
2634 dmsg(D_STREAM_DEBUG
, "STREAM: RESIDUAL FULLY FORMED [%s], len=%d",
2635 sock
->stream_buf
.residual_fully_formed
? "YES" : "NO",
2636 sock
->stream_buf
.residual
.len
);
2639 if (!sock
->stream_buf
.residual_fully_formed
)
2641 stream_buf_set_next(&sock
->stream_buf
);
2643 return !sock
->stream_buf
.residual_fully_formed
;
2647 stream_buf_added(struct stream_buf
*sb
,
2650 dmsg(D_STREAM_DEBUG
, "STREAM: ADD length_added=%d", length_added
);
2651 if (length_added
> 0)
2653 sb
->buf
.len
+= length_added
;
2656 /* if length unknown, see if we can get the length prefix from
2657 * the head of the buffer */
2658 if (sb
->len
< 0 && sb
->buf
.len
>= (int) sizeof(packet_size_type
))
2660 packet_size_type net_size
;
2663 if (sb
->port_share_state
== PS_ENABLED
)
2665 if (!is_openvpn_protocol(&sb
->buf
))
2667 msg(D_STREAM_ERRORS
, "Non-OpenVPN client protocol detected");
2668 sb
->port_share_state
= PS_FOREIGN
;
2674 sb
->port_share_state
= PS_DISABLED
;
2679 ASSERT(buf_read(&sb
->buf
, &net_size
, sizeof(net_size
)));
2680 sb
->len
= ntohps(net_size
);
2682 if (sb
->len
< 1 || sb
->len
> sb
->maxlen
)
2684 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
);
2685 stream_buf_reset(sb
);
2691 /* is our incoming packet fully read? */
2692 if (sb
->len
> 0 && sb
->buf
.len
>= sb
->len
)
2694 /* save any residual data that's part of the next packet */
2695 ASSERT(buf_init(&sb
->residual
, 0));
2696 if (sb
->buf
.len
> sb
->len
)
2698 ASSERT(buf_copy_excess(&sb
->residual
, &sb
->buf
, sb
->len
));
2700 dmsg(D_STREAM_DEBUG
, "STREAM: ADD returned TRUE, buf_len=%d, residual_len=%d",
2702 BLEN(&sb
->residual
));
2707 dmsg(D_STREAM_DEBUG
, "STREAM: ADD returned FALSE (have=%d need=%d)", sb
->buf
.len
, sb
->len
);
2708 stream_buf_set_next(sb
);
2714 stream_buf_close(struct stream_buf
*sb
)
2716 free_buf(&sb
->residual
);
2720 * The listen event is a special event whose sole purpose is
2721 * to tell us that there's a new incoming connection on a
2722 * TCP socket, for use in server mode.
2725 socket_listen_event_handle(struct link_socket
*s
)
2728 if (!defined_net_event_win32(&s
->listen_handle
))
2730 init_net_event_win32(&s
->listen_handle
, FD_ACCEPT
, s
->sd
, 0);
2732 return &s
->listen_handle
;
2733 #else /* ifdef _WIN32 */
2739 * Format IP addresses in ascii
2743 print_sockaddr_ex(const struct sockaddr
*sa
,
2744 const char *separator
,
2745 const unsigned int flags
,
2746 struct gc_arena
*gc
)
2748 struct buffer out
= alloc_buf_gc(128, gc
);
2749 bool addr_is_defined
= false;
2750 char hostaddr
[NI_MAXHOST
] = "";
2751 char servname
[NI_MAXSERV
] = "";
2754 socklen_t salen
= 0;
2755 switch (sa
->sa_family
)
2758 if (!(flags
& PS_DONT_SHOW_FAMILY
))
2760 buf_puts(&out
, "[AF_INET]");
2762 salen
= sizeof(struct sockaddr_in
);
2763 addr_is_defined
= ((struct sockaddr_in
*) sa
)->sin_addr
.s_addr
!= 0;
2767 if (!(flags
& PS_DONT_SHOW_FAMILY
))
2769 buf_puts(&out
, "[AF_INET6]");
2771 salen
= sizeof(struct sockaddr_in6
);
2772 addr_is_defined
= !IN6_IS_ADDR_UNSPECIFIED(&((struct sockaddr_in6
*) sa
)->sin6_addr
);
2776 if (!(flags
& PS_DONT_SHOW_FAMILY
))
2778 return "[AF_UNSPEC]";
2789 status
= getnameinfo(sa
, salen
, hostaddr
, sizeof(hostaddr
),
2790 servname
, sizeof(servname
), NI_NUMERICHOST
| NI_NUMERICSERV
);
2794 buf_printf(&out
, "[nameinfo() err: %s]", gai_strerror(status
));
2798 if (!(flags
& PS_DONT_SHOW_ADDR
))
2800 if (addr_is_defined
)
2802 buf_puts(&out
, hostaddr
);
2806 buf_puts(&out
, "[undef]");
2810 if ((flags
& PS_SHOW_PORT
) || (flags
& PS_SHOW_PORT_IF_DEFINED
))
2814 buf_puts(&out
, separator
);
2817 buf_puts(&out
, servname
);
2824 print_link_socket_actual(const struct link_socket_actual
*act
, struct gc_arena
*gc
)
2826 return print_link_socket_actual_ex(act
, ":", PS_SHOW_PORT
|PS_SHOW_PKTINFO
, gc
);
2830 #define IF_NAMESIZE 16
2834 print_link_socket_actual_ex(const struct link_socket_actual
*act
,
2835 const char *separator
,
2836 const unsigned int flags
,
2837 struct gc_arena
*gc
)
2841 struct buffer out
= alloc_buf_gc(128, gc
);
2842 buf_printf(&out
, "%s", print_sockaddr_ex(&act
->dest
.addr
.sa
, separator
, flags
, gc
));
2843 #if ENABLE_IP_PKTINFO
2844 char ifname
[IF_NAMESIZE
] = "[undef]";
2846 if ((flags
& PS_SHOW_PKTINFO
) && addr_defined_ipi(act
))
2848 switch (act
->dest
.addr
.sa
.sa_family
)
2852 struct openvpn_sockaddr sa
;
2854 sa
.addr
.in4
.sin_family
= AF_INET
;
2855 #if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST)
2856 sa
.addr
.in4
.sin_addr
= act
->pi
.in4
.ipi_spec_dst
;
2857 if_indextoname(act
->pi
.in4
.ipi_ifindex
, ifname
);
2858 #elif defined(IP_RECVDSTADDR)
2859 sa
.addr
.in4
.sin_addr
= act
->pi
.in4
;
2861 #else /* if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST) */
2862 #error ENABLE_IP_PKTINFO is set without IP_PKTINFO xor IP_RECVDSTADDR (fix syshead.h)
2864 buf_printf(&out
, " (via %s%%%s)",
2865 print_sockaddr_ex(&sa
.addr
.sa
, separator
, 0, gc
),
2872 struct sockaddr_in6 sin6
;
2873 char buf
[INET6_ADDRSTRLEN
] = "[undef]";
2875 sin6
.sin6_family
= AF_INET6
;
2876 sin6
.sin6_addr
= act
->pi
.in6
.ipi6_addr
;
2877 if_indextoname(act
->pi
.in6
.ipi6_ifindex
, ifname
);
2878 if (getnameinfo((struct sockaddr
*)&sin6
, sizeof(struct sockaddr_in6
),
2879 buf
, sizeof(buf
), NULL
, 0, NI_NUMERICHOST
) == 0)
2881 buf_printf(&out
, " (via %s%%%s)", buf
, ifname
);
2885 buf_printf(&out
, " (via [getnameinfo() err]%%%s)", ifname
);
2891 #endif /* if ENABLE_IP_PKTINFO */
2901 * Convert an in_addr_t in host byte order
2902 * to an ascii dotted quad.
2905 print_in_addr_t(in_addr_t addr
, unsigned int flags
, struct gc_arena
*gc
)
2908 struct buffer out
= alloc_buf_gc(64, gc
);
2910 if (addr
|| !(flags
& IA_EMPTY_IF_UNDEF
))
2913 ia
.s_addr
= (flags
& IA_NET_ORDER
) ? addr
: htonl(addr
);
2915 buf_printf(&out
, "%s", inet_ntoa(ia
));
2921 * Convert an in6_addr in host byte order
2922 * to an ascii representation of an IPv6 address
2925 print_in6_addr(struct in6_addr a6
, unsigned int flags
, struct gc_arena
*gc
)
2927 struct buffer out
= alloc_buf_gc(64, gc
);
2928 char tmp_out_buf
[64]; /* inet_ntop wants pointer to buffer */
2930 if (memcmp(&a6
, &in6addr_any
, sizeof(a6
)) != 0
2931 || !(flags
& IA_EMPTY_IF_UNDEF
))
2933 inet_ntop(AF_INET6
, &a6
, tmp_out_buf
, sizeof(tmp_out_buf
)-1);
2934 buf_printf(&out
, "%s", tmp_out_buf
);
2940 * Convert an in_port_t in host byte order to a string
2943 print_in_port_t(in_port_t port
, struct gc_arena
*gc
)
2945 struct buffer buffer
= alloc_buf_gc(8, gc
);
2946 buf_printf(&buffer
, "%hu", port
);
2947 return BSTR(&buffer
);
2951 #define UINT8_MAX 0xff
2954 /* add some offset to an ipv6 address
2955 * (add in steps of 8 bits, taking overflow into next round)
2958 add_in6_addr( struct in6_addr base
, uint32_t add
)
2962 for (i
= 15; i
>=0 && add
> 0; i
--)
2965 register uint32_t h
;
2967 h
= (unsigned char) base
.s6_addr
[i
];
2968 base
.s6_addr
[i
] = (h
+add
) & UINT8_MAX
;
2970 /* using explicit carry for the 8-bit additions will catch
2971 * 8-bit and(!) 32-bit overruns nicely
2973 carry
= ((h
& 0xff) + (add
& 0xff)) >> 8;
2974 add
= (add
>>8) + carry
;
2979 /* set environmental variables for ip/port in *addr */
2981 setenv_sockaddr(struct env_set
*es
, const char *name_prefix
, const struct openvpn_sockaddr
*addr
, const unsigned int flags
)
2986 switch (addr
->addr
.sa
.sa_family
)
2989 if (flags
& SA_IP_PORT
)
2991 openvpn_snprintf(name_buf
, sizeof(name_buf
), "%s_ip", name_prefix
);
2995 openvpn_snprintf(name_buf
, sizeof(name_buf
), "%s", name_prefix
);
2998 setenv_str(es
, name_buf
, inet_ntoa(addr
->addr
.in4
.sin_addr
));
3000 if ((flags
& SA_IP_PORT
) && addr
->addr
.in4
.sin_port
)
3002 openvpn_snprintf(name_buf
, sizeof(name_buf
), "%s_port", name_prefix
);
3003 setenv_int(es
, name_buf
, ntohs(addr
->addr
.in4
.sin_port
));
3008 if (IN6_IS_ADDR_V4MAPPED( &addr
->addr
.in6
.sin6_addr
))
3011 memcpy(&ia
.s_addr
, &addr
->addr
.in6
.sin6_addr
.s6_addr
[12],
3013 openvpn_snprintf(name_buf
, sizeof(name_buf
), "%s_ip", name_prefix
);
3014 openvpn_snprintf(buf
, sizeof(buf
), "%s", inet_ntoa(ia
) );
3018 openvpn_snprintf(name_buf
, sizeof(name_buf
), "%s_ip6", name_prefix
);
3019 getnameinfo(&addr
->addr
.sa
, sizeof(struct sockaddr_in6
),
3020 buf
, sizeof(buf
), NULL
, 0, NI_NUMERICHOST
);
3022 setenv_str(es
, name_buf
, buf
);
3024 if ((flags
& SA_IP_PORT
) && addr
->addr
.in6
.sin6_port
)
3026 openvpn_snprintf(name_buf
, sizeof(name_buf
), "%s_port", name_prefix
);
3027 setenv_int(es
, name_buf
, ntohs(addr
->addr
.in6
.sin6_port
));
3034 setenv_in_addr_t(struct env_set
*es
, const char *name_prefix
, in_addr_t addr
, const unsigned int flags
)
3036 if (addr
|| !(flags
& SA_SET_IF_NONZERO
))
3038 struct openvpn_sockaddr si
;
3040 si
.addr
.in4
.sin_family
= AF_INET
;
3041 si
.addr
.in4
.sin_addr
.s_addr
= htonl(addr
);
3042 setenv_sockaddr(es
, name_prefix
, &si
, flags
);
3047 setenv_in6_addr(struct env_set
*es
,
3048 const char *name_prefix
,
3049 const struct in6_addr
*addr
,
3050 const unsigned int flags
)
3052 if (!IN6_IS_ADDR_UNSPECIFIED(addr
) || !(flags
& SA_SET_IF_NONZERO
))
3054 struct openvpn_sockaddr si
;
3056 si
.addr
.in6
.sin6_family
= AF_INET6
;
3057 si
.addr
.in6
.sin6_addr
= *addr
;
3058 setenv_sockaddr(es
, name_prefix
, &si
, flags
);
3063 setenv_link_socket_actual(struct env_set
*es
,
3064 const char *name_prefix
,
3065 const struct link_socket_actual
*act
,
3066 const unsigned int flags
)
3068 setenv_sockaddr(es
, name_prefix
, &act
->dest
, flags
);
3072 * Convert protocol names between index and ascii form.
3075 struct proto_names
{
3076 const char *short_form
;
3077 const char *display_form
;
3078 sa_family_t proto_af
;
3082 /* Indexed by PROTO_x */
3083 static const struct proto_names proto_names
[] = {
3084 {"proto-uninitialized", "proto-NONE", AF_UNSPEC
, PROTO_NONE
},
3085 /* try IPv4 and IPv6 (client), bind dual-stack (server) */
3086 {"udp", "UDP", AF_UNSPEC
, PROTO_UDP
},
3087 {"tcp-server", "TCP_SERVER", AF_UNSPEC
, PROTO_TCP_SERVER
},
3088 {"tcp-client", "TCP_CLIENT", AF_UNSPEC
, PROTO_TCP_CLIENT
},
3089 {"tcp", "TCP", AF_UNSPEC
, PROTO_TCP
},
3091 {"udp4", "UDPv4", AF_INET
, PROTO_UDP
},
3092 {"tcp4-server", "TCPv4_SERVER", AF_INET
, PROTO_TCP_SERVER
},
3093 {"tcp4-client", "TCPv4_CLIENT", AF_INET
, PROTO_TCP_CLIENT
},
3094 {"tcp4", "TCPv4", AF_INET
, PROTO_TCP
},
3096 {"udp6", "UDPv6", AF_INET6
, PROTO_UDP
},
3097 {"tcp6-server", "TCPv6_SERVER", AF_INET6
, PROTO_TCP_SERVER
},
3098 {"tcp6-client", "TCPv6_CLIENT", AF_INET6
, PROTO_TCP_CLIENT
},
3099 {"tcp6", "TCPv6", AF_INET6
, PROTO_TCP
},
3103 ascii2proto(const char *proto_name
)
3106 for (i
= 0; i
< SIZE(proto_names
); ++i
)
3108 if (!strcmp(proto_name
, proto_names
[i
].short_form
))
3110 return proto_names
[i
].proto
;
3117 ascii2af(const char *proto_name
)
3120 for (i
= 0; i
< SIZE(proto_names
); ++i
)
3122 if (!strcmp(proto_name
, proto_names
[i
].short_form
))
3124 return proto_names
[i
].proto_af
;
3131 proto2ascii(int proto
, sa_family_t af
, bool display_form
)
3134 for (i
= 0; i
< SIZE(proto_names
); ++i
)
3136 if (proto_names
[i
].proto_af
== af
&& proto_names
[i
].proto
== proto
)
3140 return proto_names
[i
].display_form
;
3144 return proto_names
[i
].short_form
;
3149 return "[unknown protocol]";
3153 proto2ascii_all(struct gc_arena
*gc
)
3155 struct buffer out
= alloc_buf_gc(256, gc
);
3158 for (i
= 0; i
< SIZE(proto_names
); ++i
)
3162 buf_printf(&out
, " ");
3164 buf_printf(&out
, "[%s]", proto_names
[i
].short_form
);
3170 addr_family_name(int af
)
3174 case AF_INET
: return "AF_INET";
3176 case AF_INET6
: return "AF_INET6";
3182 * Given a local proto, return local proto
3183 * if !remote, or compatible remote proto
3186 * This is used for options compatibility
3189 * IPv6 and IPv4 protocols are comptabile but OpenVPN
3190 * has always sent UDPv4, TCPv4 over the wire. Keep these
3191 * strings for backward compatibility
3194 proto_remote(int proto
, bool remote
)
3196 ASSERT(proto
>= 0 && proto
< PROTO_N
);
3197 if (proto
== PROTO_UDP
)
3202 if ( (remote
&& proto
== PROTO_TCP_CLIENT
)
3203 || (!remote
&& proto
== PROTO_TCP_SERVER
))
3205 return "TCPv4_SERVER";
3207 if ( (remote
&& proto
== PROTO_TCP_SERVER
)
3208 || (!remote
&& proto
== PROTO_TCP_CLIENT
))
3210 return "TCPv4_CLIENT";
3214 return ""; /* Make the compiler happy */
3218 * Bad incoming address lengths that differ from what
3219 * we expect are considered to be fatal errors.
3222 bad_address_length(int actual
, int expected
)
3224 msg(M_FATAL
, "ERROR: received strange incoming packet with an address length of %d -- we only accept address lengths of %d.",
3230 * Socket Read Routines
3234 link_socket_read_tcp(struct link_socket
*sock
,
3239 if (!sock
->stream_buf
.residual_fully_formed
)
3241 /* with Linux-DCO, we sometimes try to access a socket that is
3242 * already installed in the kernel and has no valid file descriptor
3243 * anymore. This is a bug.
3244 * Handle by resetting client instance instead of crashing.
3246 if (sock
->sd
== SOCKET_UNDEFINED
)
3248 msg(M_INFO
, "BUG: link_socket_read_tcp(): sock->sd==-1, reset client instance" );
3249 sock
->stream_reset
= true; /* reset client instance */
3250 return buf
->len
= 0; /* nothing to read */
3254 sockethandle_t sh
= { .s
= sock
->sd
};
3255 len
= sockethandle_finalize(sh
, &sock
->reads
, buf
, NULL
);
3258 stream_buf_get_next(&sock
->stream_buf
, &frag
);
3259 len
= recv(sock
->sd
, BPTR(&frag
), BLEN(&frag
), MSG_NOSIGNAL
);
3264 sock
->stream_reset
= true;
3268 return buf
->len
= len
;
3272 if (sock
->stream_buf
.residual_fully_formed
3273 || stream_buf_added(&sock
->stream_buf
, len
)) /* packet complete? */
3275 stream_buf_get_final(&sock
->stream_buf
, buf
);
3276 stream_buf_reset(&sock
->stream_buf
);
3281 return buf
->len
= 0; /* no error, but packet is still incomplete */
3287 #if ENABLE_IP_PKTINFO
3289 /* make the buffer large enough to handle ancillary socket data for
3290 * both IPv4 and IPv6 destination addresses, plus padding (see RFC 2292)
3292 #if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST)
3293 #define PKTINFO_BUF_SIZE max_int( CMSG_SPACE(sizeof(struct in6_pktinfo)), \
3294 CMSG_SPACE(sizeof(struct in_pktinfo)) )
3296 #define PKTINFO_BUF_SIZE max_int( CMSG_SPACE(sizeof(struct in6_pktinfo)), \
3297 CMSG_SPACE(sizeof(struct in_addr)) )
3301 link_socket_read_udp_posix_recvmsg(struct link_socket
*sock
,
3303 struct link_socket_actual
*from
)
3306 uint8_t pktinfo_buf
[PKTINFO_BUF_SIZE
];
3308 socklen_t fromlen
= sizeof(from
->dest
.addr
);
3310 ASSERT(sock
->sd
>= 0); /* can't happen */
3312 iov
.iov_base
= BPTR(buf
);
3313 iov
.iov_len
= buf_forward_capacity_total(buf
);
3314 mesg
.msg_iov
= &iov
;
3315 mesg
.msg_iovlen
= 1;
3316 mesg
.msg_name
= &from
->dest
.addr
;
3317 mesg
.msg_namelen
= fromlen
;
3318 mesg
.msg_control
= pktinfo_buf
;
3319 mesg
.msg_controllen
= sizeof pktinfo_buf
;
3320 buf
->len
= recvmsg(sock
->sd
, &mesg
, 0);
3323 struct cmsghdr
*cmsg
;
3324 fromlen
= mesg
.msg_namelen
;
3325 cmsg
= CMSG_FIRSTHDR(&mesg
);
3327 && CMSG_NXTHDR(&mesg
, cmsg
) == NULL
3328 #if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST)
3329 && cmsg
->cmsg_level
== SOL_IP
3330 && cmsg
->cmsg_type
== IP_PKTINFO
3331 && cmsg
->cmsg_len
>= CMSG_LEN(sizeof(struct in_pktinfo
)) )
3332 #elif defined(IP_RECVDSTADDR)
3333 && cmsg
->cmsg_level
== IPPROTO_IP
3334 && cmsg
->cmsg_type
== IP_RECVDSTADDR
3335 && cmsg
->cmsg_len
>= CMSG_LEN(sizeof(struct in_addr
)) )
3336 #else /* if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST) */
3337 #error ENABLE_IP_PKTINFO is set without IP_PKTINFO xor IP_RECVDSTADDR (fix syshead.h)
3340 #if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST)
3341 struct in_pktinfo
*pkti
= (struct in_pktinfo
*) CMSG_DATA(cmsg
);
3342 from
->pi
.in4
.ipi_ifindex
= pkti
->ipi_ifindex
;
3343 from
->pi
.in4
.ipi_spec_dst
= pkti
->ipi_spec_dst
;
3344 #elif defined(IP_RECVDSTADDR)
3345 from
->pi
.in4
= *(struct in_addr
*) CMSG_DATA(cmsg
);
3346 #else /* if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST) */
3347 #error ENABLE_IP_PKTINFO is set without IP_PKTINFO xor IP_RECVDSTADDR (fix syshead.h)
3350 else if (cmsg
!= NULL
3351 && CMSG_NXTHDR(&mesg
, cmsg
) == NULL
3352 && cmsg
->cmsg_level
== IPPROTO_IPV6
3353 && cmsg
->cmsg_type
== IPV6_PKTINFO
3354 && cmsg
->cmsg_len
>= CMSG_LEN(sizeof(struct in6_pktinfo
)) )
3356 struct in6_pktinfo
*pkti6
= (struct in6_pktinfo
*) CMSG_DATA(cmsg
);
3357 from
->pi
.in6
.ipi6_ifindex
= pkti6
->ipi6_ifindex
;
3358 from
->pi
.in6
.ipi6_addr
= pkti6
->ipi6_addr
;
3360 else if (cmsg
!= NULL
)
3362 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
);
3368 #endif /* if ENABLE_IP_PKTINFO */
3371 link_socket_read_udp_posix(struct link_socket
*sock
,
3373 struct link_socket_actual
*from
)
3375 socklen_t fromlen
= sizeof(from
->dest
.addr
);
3376 socklen_t expectedlen
= af_addr_size(sock
->info
.af
);
3377 addr_zero_host(&from
->dest
);
3379 ASSERT(sock
->sd
>= 0); /* can't happen */
3381 #if ENABLE_IP_PKTINFO
3382 /* Both PROTO_UDPv4 and PROTO_UDPv6 */
3383 if (sock
->info
.proto
== PROTO_UDP
&& sock
->sockflags
& SF_USE_IP_PKTINFO
)
3385 fromlen
= link_socket_read_udp_posix_recvmsg(sock
, buf
, from
);
3389 buf
->len
= recvfrom(sock
->sd
, BPTR(buf
), buf_forward_capacity(buf
), 0,
3390 &from
->dest
.addr
.sa
, &fromlen
);
3391 /* FIXME: won't do anything when sock->info.af == AF_UNSPEC */
3392 if (buf
->len
>= 0 && expectedlen
&& fromlen
!= expectedlen
)
3394 bad_address_length(fromlen
, expectedlen
);
3399 #endif /* ifndef _WIN32 */
3402 * Socket Write Routines
3406 link_socket_write_tcp(struct link_socket
*sock
,
3408 struct link_socket_actual
*to
)
3410 packet_size_type len
= BLEN(buf
);
3411 dmsg(D_STREAM_DEBUG
, "STREAM: WRITE %d offset=%d", (int)len
, buf
->offset
);
3412 ASSERT(len
<= sock
->stream_buf
.maxlen
);
3414 ASSERT(buf_write_prepend(buf
, &len
, sizeof(len
)));
3416 return link_socket_write_win32(sock
, buf
, to
);
3418 return link_socket_write_tcp_posix(sock
, buf
, to
);
3422 #if ENABLE_IP_PKTINFO
3425 link_socket_write_udp_posix_sendmsg(struct link_socket
*sock
,
3427 struct link_socket_actual
*to
)
3431 struct cmsghdr
*cmsg
;
3432 uint8_t pktinfo_buf
[PKTINFO_BUF_SIZE
];
3434 iov
.iov_base
= BPTR(buf
);
3435 iov
.iov_len
= BLEN(buf
);
3436 mesg
.msg_iov
= &iov
;
3437 mesg
.msg_iovlen
= 1;
3438 switch (to
->dest
.addr
.sa
.sa_family
)
3442 mesg
.msg_name
= &to
->dest
.addr
.sa
;
3443 mesg
.msg_namelen
= sizeof(struct sockaddr_in
);
3444 mesg
.msg_control
= pktinfo_buf
;
3446 #if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST)
3447 mesg
.msg_controllen
= CMSG_SPACE(sizeof(struct in_pktinfo
));
3448 cmsg
= CMSG_FIRSTHDR(&mesg
);
3449 cmsg
->cmsg_len
= CMSG_LEN(sizeof(struct in_pktinfo
));
3450 cmsg
->cmsg_level
= SOL_IP
;
3451 cmsg
->cmsg_type
= IP_PKTINFO
;
3453 struct in_pktinfo
*pkti
;
3454 pkti
= (struct in_pktinfo
*) CMSG_DATA(cmsg
);
3455 pkti
->ipi_ifindex
= to
->pi
.in4
.ipi_ifindex
;
3456 pkti
->ipi_spec_dst
= to
->pi
.in4
.ipi_spec_dst
;
3457 pkti
->ipi_addr
.s_addr
= 0;
3459 #elif defined(IP_RECVDSTADDR)
3460 ASSERT( CMSG_SPACE(sizeof(struct in_addr
)) <= sizeof(pktinfo_buf
) );
3461 mesg
.msg_controllen
= CMSG_SPACE(sizeof(struct in_addr
));
3462 cmsg
= CMSG_FIRSTHDR(&mesg
);
3463 cmsg
->cmsg_len
= CMSG_LEN(sizeof(struct in_addr
));
3464 cmsg
->cmsg_level
= IPPROTO_IP
;
3465 cmsg
->cmsg_type
= IP_RECVDSTADDR
;
3466 *(struct in_addr
*) CMSG_DATA(cmsg
) = to
->pi
.in4
;
3467 #else /* if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST) */
3468 #error ENABLE_IP_PKTINFO is set without IP_PKTINFO xor IP_RECVDSTADDR (fix syshead.h)
3469 #endif /* if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST) */
3475 struct in6_pktinfo
*pkti6
;
3476 mesg
.msg_name
= &to
->dest
.addr
.sa
;
3477 mesg
.msg_namelen
= sizeof(struct sockaddr_in6
);
3479 ASSERT( CMSG_SPACE(sizeof(struct in6_pktinfo
)) <= sizeof(pktinfo_buf
) );
3480 mesg
.msg_control
= pktinfo_buf
;
3481 mesg
.msg_controllen
= CMSG_SPACE(sizeof(struct in6_pktinfo
));
3483 cmsg
= CMSG_FIRSTHDR(&mesg
);
3484 cmsg
->cmsg_len
= CMSG_LEN(sizeof(struct in6_pktinfo
));
3485 cmsg
->cmsg_level
= IPPROTO_IPV6
;
3486 cmsg
->cmsg_type
= IPV6_PKTINFO
;
3488 pkti6
= (struct in6_pktinfo
*) CMSG_DATA(cmsg
);
3489 pkti6
->ipi6_ifindex
= to
->pi
.in6
.ipi6_ifindex
;
3490 pkti6
->ipi6_addr
= to
->pi
.in6
.ipi6_addr
;
3496 return sendmsg(sock
->sd
, &mesg
, 0);
3499 #endif /* if ENABLE_IP_PKTINFO */
3502 * Win32 overlapped socket I/O functions.
3508 socket_get_last_error(const struct link_socket
*sock
)
3510 if (socket_is_dco_win(sock
))
3512 return GetLastError();
3515 return WSAGetLastError();
3519 socket_recv_queue(struct link_socket
*sock
, int maxsize
)
3521 if (sock
->reads
.iostate
== IOSTATE_INITIAL
)
3526 /* reset buf to its initial state */
3527 if (proto_is_udp(sock
->info
.proto
))
3529 sock
->reads
.buf
= sock
->reads
.buf_init
;
3531 else if (proto_is_tcp(sock
->info
.proto
))
3533 stream_buf_get_next(&sock
->stream_buf
, &sock
->reads
.buf
);
3540 /* Win32 docs say it's okay to allocate the wsabuf on the stack */
3541 wsabuf
[0].buf
= BSTR(&sock
->reads
.buf
);
3542 wsabuf
[0].len
= maxsize
? maxsize
: BLEN(&sock
->reads
.buf
);
3544 /* check for buffer overflow */
3545 ASSERT(wsabuf
[0].len
<= BLEN(&sock
->reads
.buf
));
3547 /* the overlapped read will signal this event on I/O completion */
3548 ASSERT(ResetEvent(sock
->reads
.overlapped
.hEvent
));
3549 sock
->reads
.flags
= 0;
3551 if (socket_is_dco_win(sock
))
3553 status
= ReadFile((HANDLE
)sock
->sd
, wsabuf
[0].buf
, wsabuf
[0].len
,
3554 &sock
->reads
.size
, &sock
->reads
.overlapped
);
3555 /* Readfile status is inverted from WSARecv */
3558 else if (proto_is_udp(sock
->info
.proto
))
3560 sock
->reads
.addr_defined
= true;
3561 sock
->reads
.addrlen
= sizeof(sock
->reads
.addr6
);
3562 status
= WSARecvFrom(
3568 (struct sockaddr
*) &sock
->reads
.addr
,
3569 &sock
->reads
.addrlen
,
3570 &sock
->reads
.overlapped
,
3573 else if (proto_is_tcp(sock
->info
.proto
))
3575 sock
->reads
.addr_defined
= false;
3582 &sock
->reads
.overlapped
,
3591 if (!status
) /* operation completed immediately? */
3593 /* FIXME: won't do anything when sock->info.af == AF_UNSPEC */
3594 int af_len
= af_addr_size(sock
->info
.af
);
3595 if (sock
->reads
.addr_defined
&& af_len
&& sock
->reads
.addrlen
!= af_len
)
3597 bad_address_length(sock
->reads
.addrlen
, af_len
);
3599 sock
->reads
.iostate
= IOSTATE_IMMEDIATE_RETURN
;
3601 /* since we got an immediate return, we must signal the event object ourselves */
3602 ASSERT(SetEvent(sock
->reads
.overlapped
.hEvent
));
3603 sock
->reads
.status
= 0;
3605 dmsg(D_WIN32_IO
, "WIN32 I/O: Socket Receive immediate return [%d,%d]",
3606 (int) wsabuf
[0].len
,
3607 (int) sock
->reads
.size
);
3611 status
= socket_get_last_error(sock
);
3612 if (status
== WSA_IO_PENDING
) /* operation queued? */
3614 sock
->reads
.iostate
= IOSTATE_QUEUED
;
3615 sock
->reads
.status
= status
;
3616 dmsg(D_WIN32_IO
, "WIN32 I/O: Socket Receive queued [%d]",
3617 (int) wsabuf
[0].len
);
3619 else /* error occurred */
3621 struct gc_arena gc
= gc_new();
3622 ASSERT(SetEvent(sock
->reads
.overlapped
.hEvent
));
3623 sock
->reads
.iostate
= IOSTATE_IMMEDIATE_RETURN
;
3624 sock
->reads
.status
= status
;
3625 dmsg(D_WIN32_IO
, "WIN32 I/O: Socket Receive error [%d]: %s",
3626 (int) wsabuf
[0].len
,
3627 strerror_win32(status
, &gc
));
3632 return sock
->reads
.iostate
;
3636 socket_send_queue(struct link_socket
*sock
, struct buffer
*buf
, const struct link_socket_actual
*to
)
3638 if (sock
->writes
.iostate
== IOSTATE_INITIAL
)
3643 /* make a private copy of buf */
3644 sock
->writes
.buf
= sock
->writes
.buf_init
;
3645 sock
->writes
.buf
.len
= 0;
3646 ASSERT(buf_copy(&sock
->writes
.buf
, buf
));
3648 /* Win32 docs say it's okay to allocate the wsabuf on the stack */
3649 wsabuf
[0].buf
= BSTR(&sock
->writes
.buf
);
3650 wsabuf
[0].len
= BLEN(&sock
->writes
.buf
);
3652 /* the overlapped write will signal this event on I/O completion */
3653 ASSERT(ResetEvent(sock
->writes
.overlapped
.hEvent
));
3654 sock
->writes
.flags
= 0;
3656 if (socket_is_dco_win(sock
))
3658 status
= WriteFile((HANDLE
)sock
->sd
, wsabuf
[0].buf
, wsabuf
[0].len
,
3659 &sock
->writes
.size
, &sock
->writes
.overlapped
);
3661 /* WriteFile status is inverted from WSASendTo */
3665 else if (proto_is_udp(sock
->info
.proto
))
3667 /* set destination address for UDP writes */
3668 sock
->writes
.addr_defined
= true;
3669 if (to
->dest
.addr
.sa
.sa_family
== AF_INET6
)
3671 sock
->writes
.addr6
= to
->dest
.addr
.in6
;
3672 sock
->writes
.addrlen
= sizeof(sock
->writes
.addr6
);
3676 sock
->writes
.addr
= to
->dest
.addr
.in4
;
3677 sock
->writes
.addrlen
= sizeof(sock
->writes
.addr
);
3686 (struct sockaddr
*) &sock
->writes
.addr
,
3687 sock
->writes
.addrlen
,
3688 &sock
->writes
.overlapped
,
3691 else if (proto_is_tcp(sock
->info
.proto
))
3693 /* destination address for TCP writes was established on connection initiation */
3694 sock
->writes
.addr_defined
= false;
3702 &sock
->writes
.overlapped
,
3711 if (!status
) /* operation completed immediately? */
3713 sock
->writes
.iostate
= IOSTATE_IMMEDIATE_RETURN
;
3715 /* since we got an immediate return, we must signal the event object ourselves */
3716 ASSERT(SetEvent(sock
->writes
.overlapped
.hEvent
));
3718 sock
->writes
.status
= 0;
3720 dmsg(D_WIN32_IO
, "WIN32 I/O: Socket Send immediate return [%d,%d]",
3721 (int) wsabuf
[0].len
,
3722 (int) sock
->writes
.size
);
3726 status
= socket_get_last_error(sock
);
3727 /* both status code have the identical value */
3728 if (status
== WSA_IO_PENDING
|| status
== ERROR_IO_PENDING
) /* operation queued? */
3730 sock
->writes
.iostate
= IOSTATE_QUEUED
;
3731 sock
->writes
.status
= status
;
3732 dmsg(D_WIN32_IO
, "WIN32 I/O: Socket Send queued [%d]",
3733 (int) wsabuf
[0].len
);
3735 else /* error occurred */
3737 struct gc_arena gc
= gc_new();
3738 ASSERT(SetEvent(sock
->writes
.overlapped
.hEvent
));
3739 sock
->writes
.iostate
= IOSTATE_IMMEDIATE_RETURN
;
3740 sock
->writes
.status
= status
;
3742 dmsg(D_WIN32_IO
, "WIN32 I/O: Socket Send error [%d]: %s",
3743 (int) wsabuf
[0].len
,
3744 strerror_win32(status
, &gc
));
3750 return sock
->writes
.iostate
;
3753 /* Returns the number of bytes successfully read */
3755 sockethandle_finalize(sockethandle_t sh
,
3756 struct overlapped_io
*io
,
3758 struct link_socket_actual
*from
)
3763 switch (io
->iostate
)
3765 case IOSTATE_QUEUED
:
3766 status
= SocketHandleGetOverlappedResult(sh
, io
);
3769 /* successful return for a queued operation */
3775 io
->iostate
= IOSTATE_INITIAL
;
3776 ASSERT(ResetEvent(io
->overlapped
.hEvent
));
3778 dmsg(D_WIN32_IO
, "WIN32 I/O: Completion success [%d]", ret
);
3782 /* error during a queued operation */
3784 if (SocketHandleGetLastError(sh
) != ERROR_IO_INCOMPLETE
)
3786 /* if no error (i.e. just not finished yet), then DON'T execute this code */
3787 io
->iostate
= IOSTATE_INITIAL
;
3788 ASSERT(ResetEvent(io
->overlapped
.hEvent
));
3789 msg(D_WIN32_IO
| M_ERRNO
, "WIN32 I/O: Completion error");
3794 case IOSTATE_IMMEDIATE_RETURN
:
3795 io
->iostate
= IOSTATE_INITIAL
;
3796 ASSERT(ResetEvent(io
->overlapped
.hEvent
));
3799 /* error return for a non-queued operation */
3800 SocketHandleSetLastError(sh
, io
->status
);
3802 msg(D_WIN32_IO
| M_ERRNO
, "WIN32 I/O: Completion non-queued error");
3806 /* successful return for a non-queued operation */
3812 dmsg(D_WIN32_IO
, "WIN32 I/O: Completion non-queued success [%d]", ret
);
3816 case IOSTATE_INITIAL
: /* were we called without proper queueing? */
3817 SocketHandleSetInvalError(sh
);
3819 dmsg(D_WIN32_IO
, "WIN32 I/O: Completion BAD STATE");
3826 /* return from address if requested */
3827 if (!sh
.is_handle
&& from
)
3829 if (ret
>= 0 && io
->addr_defined
)
3831 /* TODO(jjo): streamline this mess */
3832 /* in this func we don't have relevant info about the PF_ of this
3833 * endpoint, as link_socket_actual will be zero for the 1st received packet
3835 * Test for inets PF_ possible sizes
3837 switch (io
->addrlen
)
3839 case sizeof(struct sockaddr_in
):
3840 case sizeof(struct sockaddr_in6
):
3841 /* TODO(jjo): for some reason (?) I'm getting 24,28 for AF_INET6
3843 case sizeof(struct sockaddr_in6
)-4:
3847 bad_address_length(io
->addrlen
, af_addr_size(io
->addr
.sin_family
));
3850 switch (io
->addr
.sin_family
)
3853 from
->dest
.addr
.in4
= io
->addr
;
3857 from
->dest
.addr
.in6
= io
->addr6
;
3863 CLEAR(from
->dest
.addr
);
3877 * Socket event notification
3881 socket_set(struct link_socket
*s
,
3882 struct event_set
*es
,
3883 unsigned int rwflags
,
3885 unsigned int *persistent
)
3889 if ((rwflags
& EVENT_READ
) && !stream_buf_read_setup(s
))
3891 ASSERT(!persistent
);
3892 rwflags
&= ~EVENT_READ
;
3896 if (rwflags
& EVENT_READ
)
3898 socket_recv_queue(s
, 0);
3902 /* if persistent is defined, call event_ctl only if rwflags has changed since last call */
3903 if (!persistent
|| *persistent
!= rwflags
)
3905 event_ctl(es
, socket_event_handle(s
), rwflags
, arg
);
3908 *persistent
= rwflags
;
3912 s
->rwflags_debug
= rwflags
;
3918 sd_close(socket_descriptor_t
*sd
)
3920 if (sd
&& socket_defined(*sd
))
3922 openvpn_close_socket(*sd
);
3923 *sd
= SOCKET_UNDEFINED
;
3927 #if UNIX_SOCK_SUPPORT
3930 * code for unix domain sockets
3934 sockaddr_unix_name(const struct sockaddr_un
*local
, const char *null
)
3936 if (local
&& local
->sun_family
== PF_UNIX
)
3938 return local
->sun_path
;
3947 create_socket_unix(void)
3949 socket_descriptor_t sd
;
3951 if ((sd
= socket(PF_UNIX
, SOCK_STREAM
, 0)) < 0)
3953 msg(M_ERR
, "Cannot create unix domain socket");
3956 /* set socket file descriptor to not pass across execs, so that
3957 * scripts don't have access to it */
3964 socket_bind_unix(socket_descriptor_t sd
,
3965 struct sockaddr_un
*local
,
3968 struct gc_arena gc
= gc_new();
3969 const mode_t orig_umask
= umask(0);
3971 if (bind(sd
, (struct sockaddr
*) local
, sizeof(struct sockaddr_un
)))
3973 msg(M_FATAL
| M_ERRNO
,
3974 "%s: Socket bind[%d] failed on unix domain socket %s",
3977 sockaddr_unix_name(local
, "NULL"));
3985 socket_accept_unix(socket_descriptor_t sd
,
3986 struct sockaddr_un
*remote
)
3988 socklen_t remote_len
= sizeof(struct sockaddr_un
);
3989 socket_descriptor_t ret
;
3992 ret
= accept(sd
, (struct sockaddr
*) remote
, &remote_len
);
3995 /* set socket file descriptor to not pass across execs, so that
3996 * scripts don't have access to it */
4003 socket_connect_unix(socket_descriptor_t sd
,
4004 struct sockaddr_un
*remote
)
4006 int status
= connect(sd
, (struct sockaddr
*) remote
, sizeof(struct sockaddr_un
));
4009 status
= openvpn_errno();
4015 sockaddr_unix_init(struct sockaddr_un
*local
, const char *path
)
4017 local
->sun_family
= PF_UNIX
;
4018 strncpynt(local
->sun_path
, path
, sizeof(local
->sun_path
));
4022 socket_delete_unix(const struct sockaddr_un
*local
)
4024 const char *name
= sockaddr_unix_name(local
, NULL
);
4025 if (name
&& strlen(name
))
4032 unix_socket_get_peer_uid_gid(const socket_descriptor_t sd
, int *uid
, int *gid
)
4034 #ifdef HAVE_GETPEEREID
4037 if (getpeereid(sd
, &u
, &g
) == -1)
4050 #elif defined(SO_PEERCRED)
4051 struct ucred peercred
;
4052 socklen_t so_len
= sizeof(peercred
);
4053 if (getsockopt(sd
, SOL_SOCKET
, SO_PEERCRED
, &peercred
, &so_len
) == -1)
4059 *uid
= peercred
.uid
;
4063 *gid
= peercred
.gid
;
4066 #else /* ifdef HAVE_GETPEEREID */
4068 #endif /* ifdef HAVE_GETPEEREID */
4071 #endif /* if UNIX_SOCK_SUPPORT */