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-2018 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"
47 const int proto_overhead
[] = { /* indexed by PROTO_x */
49 IPv4_UDP_HEADER_SIZE
, /* IPv4 */
52 IPv6_UDP_HEADER_SIZE
, /* IPv6 */
59 * Convert sockflags/getaddr_flags into getaddr_flags
62 sf2gaf(const unsigned int getaddr_flags
,
63 const unsigned int sockflags
)
65 if (sockflags
& SF_HOST_RANDOMIZE
)
67 return getaddr_flags
| GETADDR_RANDOMIZE
;
76 * Functions related to the translation of DNS names to IP addresses.
79 get_addr_generic(sa_family_t af
, unsigned int flags
, const char *hostname
,
80 void *network
, unsigned int *netbits
,
81 int resolve_retry_seconds
, volatile int *signal_received
,
84 char *endp
, *sep
, *var_host
= NULL
;
85 struct addrinfo
*ai
= NULL
;
92 msg(M_NONFATAL
, "Can't resolve null hostname!");
96 /* assign family specific default values */
101 max_bits
= sizeof(in_addr_t
) * 8;
106 max_bits
= sizeof(struct in6_addr
) * 8;
111 "Unsupported AF family passed to getaddrinfo for %s (%d)",
116 /* we need to modify the hostname received as input, but we don't want to
117 * touch it directly as it might be a constant string.
119 * Therefore, we clone the string here and free it at the end of the
121 var_host
= strdup(hostname
);
124 msg(M_NONFATAL
| M_ERRNO
,
125 "Can't allocate hostname buffer for getaddrinfo");
129 /* check if this hostname has a /bits suffix */
130 sep
= strchr(var_host
, '/');
133 bits
= strtoul(sep
+ 1, &endp
, 10);
134 if ((*endp
!= '\0') || (bits
> max_bits
))
136 msg(msglevel
, "IP prefix '%s': invalid '/bits' spec (%s)", hostname
,
143 ret
= openvpn_getaddrinfo(flags
& ~GETADDR_HOST_ORDER
, var_host
, NULL
,
144 resolve_retry_seconds
, signal_received
, af
, &ai
);
145 if ((ret
== 0) && network
)
147 struct in6_addr
*ip6
;
154 *ip4
= ((struct sockaddr_in
*)ai
->ai_addr
)->sin_addr
.s_addr
;
156 if (flags
& GETADDR_HOST_ORDER
)
164 *ip6
= ((struct sockaddr_in6
*)ai
->ai_addr
)->sin6_addr
;
168 /* can't get here because 'af' was previously checked */
170 "Unsupported AF family for %s (%d)", var_host
, af
);
180 /* restore '/' separator, if any */
193 getaddr(unsigned int flags
,
194 const char *hostname
,
195 int resolve_retry_seconds
,
197 volatile int *signal_received
)
202 status
= get_addr_generic(AF_INET
, flags
, hostname
, &addr
, NULL
,
203 resolve_retry_seconds
, signal_received
,
224 get_ipv6_addr(const char *hostname
, struct in6_addr
*network
,
225 unsigned int *netbits
, int msglevel
)
227 if (get_addr_generic(AF_INET6
, GETADDR_RESOLVE
, hostname
, network
, netbits
,
228 0, NULL
, msglevel
) < 0)
233 return true; /* parsing OK, values set */
237 streqnull(const char *a
, const char *b
)
239 if (a
== NULL
&& b
== NULL
)
243 else if (a
== NULL
|| b
== NULL
)
254 * get_cached_dns_entry return 0 on success and -1
255 * otherwise. (like getaddrinfo)
258 get_cached_dns_entry(struct cached_dns_entry
*dns_cache
,
259 const char *hostname
,
260 const char *servname
,
263 struct addrinfo
**ai
)
265 struct cached_dns_entry
*ph
;
268 /* Only use flags that are relevant for the structure */
269 flags
= resolve_flags
& GETADDR_CACHE_MASK
;
271 for (ph
= dns_cache
; ph
; ph
= ph
->next
)
273 if (streqnull(ph
->hostname
, hostname
)
274 && streqnull(ph
->servname
, servname
)
275 && ph
->ai_family
== ai_family
276 && ph
->flags
== flags
)
287 do_preresolve_host(struct context
*c
,
288 const char *hostname
,
289 const char *servname
,
296 if (get_cached_dns_entry(c
->c1
.dns_cache
,
303 /* entry already cached, return success */
307 status
= openvpn_getaddrinfo(flags
, hostname
, servname
,
308 c
->options
.resolve_retry_seconds
, NULL
,
312 struct cached_dns_entry
*ph
;
314 ALLOC_OBJ_CLEAR_GC(ph
, struct cached_dns_entry
, &c
->gc
);
316 ph
->hostname
= hostname
;
317 ph
->servname
= servname
;
318 ph
->flags
= flags
& GETADDR_CACHE_MASK
;
320 if (!c
->c1
.dns_cache
)
322 c
->c1
.dns_cache
= ph
;
326 struct cached_dns_entry
*prev
= c
->c1
.dns_cache
;
334 gc_addspecial(ai
, &gc_freeaddrinfo_callback
, &c
->gc
);
341 do_preresolve(struct context
*c
)
344 struct connection_list
*l
= c
->options
.connection_list
;
345 const unsigned int preresolve_flags
= GETADDR_RESOLVE
346 |GETADDR_UPDATE_MANAGEMENT_STATE
347 |GETADDR_MENTION_RESOLVE_RETRY
351 for (i
= 0; i
< l
->len
; ++i
)
355 int flags
= preresolve_flags
;
357 struct connection_entry
*ce
= c
->options
.connection_list
->array
[i
];
359 if (proto_is_dgram(ce
->proto
))
361 flags
|= GETADDR_DATAGRAM
;
364 if (c
->options
.sockflags
& SF_HOST_RANDOMIZE
)
366 flags
|= GETADDR_RANDOMIZE
;
369 if (c
->options
.ip_remote_hint
)
371 remote
= c
->options
.ip_remote_hint
;
378 /* HTTP remote hostname does not need to be resolved */
379 if (!ce
->http_proxy_options
)
381 status
= do_preresolve_host(c
, remote
, ce
->remote_port
,
389 /* Preresolve proxy */
390 if (ce
->http_proxy_options
)
392 status
= do_preresolve_host(c
,
393 ce
->http_proxy_options
->server
,
394 ce
->http_proxy_options
->port
,
404 if (ce
->socks_proxy_server
)
406 status
= do_preresolve_host(c
,
407 ce
->socks_proxy_server
,
408 ce
->socks_proxy_port
,
419 flags
|= GETADDR_PASSIVE
;
420 flags
&= ~GETADDR_RANDOMIZE
;
421 status
= do_preresolve_host(c
, ce
->local
, ce
->local_port
,
434 throw_signal_soft(SIGHUP
, "Preresolving failed");
438 * Translate IPv4/IPv6 addr or hostname into struct addrinfo
439 * If resolve error, try again for resolve_retry_seconds seconds.
442 openvpn_getaddrinfo(unsigned int flags
,
443 const char *hostname
,
444 const char *servname
,
445 int resolve_retry_seconds
,
446 volatile int *signal_received
,
448 struct addrinfo
**res
)
450 struct addrinfo hints
;
453 int msglevel
= (flags
& GETADDR_FATAL
) ? M_FATAL
: D_RESOLVE_ERRORS
;
454 struct gc_arena gc
= gc_new();
455 const char *print_hostname
;
456 const char *print_servname
;
460 ASSERT(hostname
|| servname
);
461 ASSERT(!(flags
& GETADDR_HOST_ORDER
));
465 print_servname
= servname
;
472 if (flags
& GETADDR_MSG_VIRT_OUT
)
474 msglevel
|= M_MSG_VIRT_OUT
;
477 if ((flags
& (GETADDR_FATAL_ON_SIGNAL
|GETADDR_WARN_ON_SIGNAL
))
480 signal_received
= &sigrec
;
483 /* try numeric ipv6 addr first */
485 hints
.ai_family
= ai_family
;
486 hints
.ai_flags
= AI_NUMERICHOST
;
488 if (flags
& GETADDR_PASSIVE
)
490 hints
.ai_flags
|= AI_PASSIVE
;
493 if (flags
& GETADDR_DATAGRAM
)
495 hints
.ai_socktype
= SOCK_DGRAM
;
499 hints
.ai_socktype
= SOCK_STREAM
;
502 status
= getaddrinfo(hostname
, servname
, &hints
, res
);
504 if (status
!= 0) /* parse as numeric address failed? */
506 const int fail_wait_interval
= 5; /* seconds */
507 /* Add +4 to cause integer division rounding up (1 + 4) = 5, (0+4)/5=0 */
508 int resolve_retries
= (flags
& GETADDR_TRY_ONCE
) ? 1 :
509 ((resolve_retry_seconds
+ 4)/ fail_wait_interval
);
513 if (hostname
&& (flags
& GETADDR_RANDOMIZE
))
515 hostname
= hostname_randomize(hostname
, &gc
);
520 print_hostname
= hostname
;
524 print_hostname
= "undefined";
527 fmt
= "RESOLVE: Cannot resolve host address: %s:%s (%s)";
528 if ((flags
& GETADDR_MENTION_RESOLVE_RETRY
)
529 && !resolve_retry_seconds
)
531 fmt
= "RESOLVE: Cannot resolve host address: %s:%s (%s) "
532 "(I would have retried this name query if you had "
533 "specified the --resolv-retry option.)";
536 if (!(flags
& GETADDR_RESOLVE
) || status
== EAI_FAIL
)
538 msg(msglevel
, "RESOLVE: Cannot parse IP address: %s:%s (%s)",
539 print_hostname
,print_servname
, gai_strerror(status
));
543 #ifdef ENABLE_MANAGEMENT
544 if (flags
& GETADDR_UPDATE_MANAGEMENT_STATE
)
548 management_set_state(management
,
549 OPENVPN_STATE_RESOLVE
,
565 /* force resolv.conf reload */
568 /* try hostname lookup */
569 hints
.ai_flags
&= ~AI_NUMERICHOST
;
571 "GETADDRINFO flags=0x%04x ai_family=%d ai_socktype=%d",
572 flags
, hints
.ai_family
, hints
.ai_socktype
);
573 status
= getaddrinfo(hostname
, servname
, &hints
, res
);
577 get_signal(signal_received
);
578 if (*signal_received
) /* were we interrupted by a signal? */
580 if (*signal_received
== SIGUSR1
) /* ignore SIGUSR1 */
583 "RESOLVE: Ignored SIGUSR1 signal received during "
584 "DNS resolution attempt");
585 *signal_received
= 0;
589 /* turn success into failure (interrupted syscall) */
595 status
= EAI_AGAIN
; /* = temporary failure */
609 /* resolve lookup failed, should we
610 * continue or fail? */
612 if (resolve_retries
> 0)
614 level
= D_RESOLVE_ERRORS
;
621 gai_strerror(status
));
623 if (--resolve_retries
<= 0)
628 management_sleep(fail_wait_interval
);
633 /* hostname resolve succeeded */
636 * Do not choose an IP Addresse by random or change the order *
637 * of IP addresses, doing so will break RFC 3484 address selection *
642 /* IP address parse succeeded */
643 if (flags
& GETADDR_RANDOMIZE
)
646 "WARNING: ignoring --remote-random-hostname because the "
647 "hostname is an IP address");
652 if (signal_received
&& *signal_received
)
655 if (flags
& GETADDR_FATAL_ON_SIGNAL
)
659 else if (flags
& GETADDR_WARN_ON_SIGNAL
)
663 msg(level
, "RESOLVE: signal received during DNS resolution attempt");
671 * We do our own inet_aton because the glibc function
672 * isn't very good about error checking.
675 openvpn_inet_aton(const char *dotted_quad
, struct in_addr
*addr
)
677 unsigned int a
, b
, c
, d
;
680 if (sscanf(dotted_quad
, "%u.%u.%u.%u", &a
, &b
, &c
, &d
) == 4)
682 if (a
< 256 && b
< 256 && c
< 256 && d
< 256)
684 addr
->s_addr
= htonl(a
<<24 | b
<<16 | c
<<8 | d
);
685 return OIA_IP
; /* good dotted quad */
688 if (string_class(dotted_quad
, CC_DIGIT
|CC_DOT
, 0))
690 return OIA_ERROR
; /* probably a badly formatted dotted quad */
694 return OIA_HOSTNAME
; /* probably a hostname */
699 ip_addr_dotted_quad_safe(const char *dotted_quad
)
701 /* verify non-NULL */
707 /* verify length is within limits */
708 if (strlen(dotted_quad
) > 15)
713 /* verify that all chars are either numeric or '.' and that no numeric
714 * substring is greater than 3 chars */
717 const char *p
= dotted_quad
;
722 if (c
>= '0' && c
<= '9')
741 /* verify that string will convert to IP address */
744 return openvpn_inet_aton(dotted_quad
, &a
) == OIA_IP
;
749 ipv6_addr_safe(const char *ipv6_text_addr
)
751 /* verify non-NULL */
757 /* verify length is within limits */
758 if (strlen(ipv6_text_addr
) > INET6_ADDRSTRLEN
)
763 /* verify that string will convert to IPv6 address */
766 return inet_pton( AF_INET6
, ipv6_text_addr
, &a6
) == 1;
771 dns_addr_safe(const char *addr
)
775 const size_t len
= strlen(addr
);
776 return len
> 0 && len
<= 255 && string_class(addr
, CC_ALNUM
|CC_DASH
|CC_DOT
, 0);
785 ip_or_dns_addr_safe(const char *addr
, const bool allow_fqdn
)
787 if (ip_addr_dotted_quad_safe(addr
))
793 return dns_addr_safe(addr
);
802 mac_addr_safe(const char *mac_addr
)
804 /* verify non-NULL */
810 /* verify length is within limits */
811 if (strlen(mac_addr
) > 17)
816 /* verify that all chars are either alphanumeric or ':' and that no
817 * alphanumeric substring is greater than 2 chars */
820 const char *p
= mac_addr
;
825 if ( (c
>= '0' && c
<= '9') || (c
>= 'a' && c
<= 'f') || (c
>= 'A' && c
<= 'F') )
844 /* error-checking is left to script invoked in lladdr.c */
849 socket_get_sndbuf(int sd
)
851 #if defined(HAVE_GETSOCKOPT) && defined(SOL_SOCKET) && defined(SO_SNDBUF)
856 if (getsockopt(sd
, SOL_SOCKET
, SO_SNDBUF
, (void *) &val
, &len
) == 0
857 && len
== sizeof(val
))
866 socket_set_sndbuf(int sd
, int size
)
868 #if defined(HAVE_SETSOCKOPT) && defined(SOL_SOCKET) && defined(SO_SNDBUF)
869 if (setsockopt(sd
, SOL_SOCKET
, SO_SNDBUF
, (void *) &size
, sizeof(size
)) != 0)
871 msg(M_WARN
, "NOTE: setsockopt SO_SNDBUF=%d failed", size
);
877 socket_get_rcvbuf(int sd
)
879 #if defined(HAVE_GETSOCKOPT) && defined(SOL_SOCKET) && defined(SO_RCVBUF)
884 if (getsockopt(sd
, SOL_SOCKET
, SO_RCVBUF
, (void *) &val
, &len
) == 0
885 && len
== sizeof(val
))
894 socket_set_rcvbuf(int sd
, int size
)
896 #if defined(HAVE_SETSOCKOPT) && defined(SOL_SOCKET) && defined(SO_RCVBUF)
897 if (setsockopt(sd
, SOL_SOCKET
, SO_RCVBUF
, (void *) &size
, sizeof(size
)) != 0)
899 msg(M_WARN
, "NOTE: setsockopt SO_RCVBUF=%d failed", size
);
907 socket_set_buffers(int fd
, const struct socket_buffer_size
*sbs
)
911 const int sndbuf_old
= socket_get_sndbuf(fd
);
912 const int rcvbuf_old
= socket_get_rcvbuf(fd
);
916 socket_set_sndbuf(fd
, sbs
->sndbuf
);
921 socket_set_rcvbuf(fd
, sbs
->rcvbuf
);
924 msg(D_OSBUF
, "Socket Buffers: R=[%d->%d] S=[%d->%d]",
926 socket_get_rcvbuf(fd
),
928 socket_get_sndbuf(fd
));
933 * Set other socket options
937 socket_set_tcp_nodelay(int sd
, int state
)
939 #if defined(_WIN32) || (defined(HAVE_SETSOCKOPT) && defined(IPPROTO_TCP) && defined(TCP_NODELAY))
940 if (setsockopt(sd
, IPPROTO_TCP
, TCP_NODELAY
, (void *) &state
, sizeof(state
)) != 0)
942 msg(M_WARN
, "NOTE: setsockopt TCP_NODELAY=%d failed", state
);
947 dmsg(D_OSBUF
, "Socket flags: TCP_NODELAY=%d succeeded", state
);
950 #else /* if defined(_WIN32) || (defined(HAVE_SETSOCKOPT) && defined(IPPROTO_TCP) && defined(TCP_NODELAY)) */
951 msg(M_WARN
, "NOTE: setsockopt TCP_NODELAY=%d failed (No kernel support)", state
);
957 socket_set_mark(int sd
, int mark
)
959 #if defined(TARGET_LINUX) && HAVE_DECL_SO_MARK
960 if (mark
&& setsockopt(sd
, SOL_SOCKET
, SO_MARK
, (void *) &mark
, sizeof(mark
)) != 0)
962 msg(M_WARN
, "NOTE: setsockopt SO_MARK=%d failed", mark
);
968 socket_set_flags(int sd
, unsigned int sockflags
)
970 if (sockflags
& SF_TCP_NODELAY
)
972 return socket_set_tcp_nodelay(sd
, 1);
981 link_socket_update_flags(struct link_socket
*ls
, unsigned int sockflags
)
983 if (ls
&& socket_defined(ls
->sd
))
985 return socket_set_flags(ls
->sd
, ls
->sockflags
= sockflags
);
994 link_socket_update_buffer_sizes(struct link_socket
*ls
, int rcvbuf
, int sndbuf
)
996 if (ls
&& socket_defined(ls
->sd
))
998 ls
->socket_buffer_sizes
.sndbuf
= sndbuf
;
999 ls
->socket_buffer_sizes
.rcvbuf
= rcvbuf
;
1000 socket_set_buffers(ls
->sd
, &ls
->socket_buffer_sizes
);
1005 * SOCKET INITIALIZATION CODE.
1006 * Create a TCP/UDP socket
1010 create_socket_tcp(struct addrinfo
*addrinfo
)
1012 socket_descriptor_t sd
;
1015 ASSERT(addrinfo
->ai_socktype
== SOCK_STREAM
);
1017 if ((sd
= socket(addrinfo
->ai_family
, addrinfo
->ai_socktype
, addrinfo
->ai_protocol
)) < 0)
1019 msg(M_ERR
, "Cannot create TCP socket");
1022 #ifndef _WIN32 /* using SO_REUSEADDR on Windows will cause bind to succeed on port conflicts! */
1023 /* set SO_REUSEADDR on socket */
1026 if (setsockopt(sd
, SOL_SOCKET
, SO_REUSEADDR
,
1027 (void *) &on
, sizeof(on
)) < 0)
1029 msg(M_ERR
, "TCP: Cannot setsockopt SO_REUSEADDR on TCP socket");
1034 /* set socket file descriptor to not pass across execs, so that
1035 * scripts don't have access to it */
1041 static socket_descriptor_t
1042 create_socket_udp(struct addrinfo
*addrinfo
, const unsigned int flags
)
1044 socket_descriptor_t sd
;
1047 ASSERT(addrinfo
->ai_socktype
== SOCK_DGRAM
);
1049 if ((sd
= socket(addrinfo
->ai_family
, addrinfo
->ai_socktype
, addrinfo
->ai_protocol
)) < 0)
1051 msg(M_ERR
, "UDP: Cannot create UDP/UDP6 socket");
1053 #if ENABLE_IP_PKTINFO
1054 else if (flags
& SF_USE_IP_PKTINFO
)
1057 if (addrinfo
->ai_family
== AF_INET
)
1059 #if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST)
1060 if (setsockopt(sd
, SOL_IP
, IP_PKTINFO
,
1061 (void *)&pad
, sizeof(pad
)) < 0)
1063 msg(M_ERR
, "UDP: failed setsockopt for IP_PKTINFO");
1065 #elif defined(IP_RECVDSTADDR)
1066 if (setsockopt(sd
, IPPROTO_IP
, IP_RECVDSTADDR
,
1067 (void *)&pad
, sizeof(pad
)) < 0)
1069 msg(M_ERR
, "UDP: failed setsockopt for IP_RECVDSTADDR");
1071 #else /* if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST) */
1072 #error ENABLE_IP_PKTINFO is set without IP_PKTINFO xor IP_RECVDSTADDR (fix syshead.h)
1075 else if (addrinfo
->ai_family
== AF_INET6
)
1077 #ifndef IPV6_RECVPKTINFO /* Some older Darwin platforms require this */
1078 if (setsockopt(sd
, IPPROTO_IPV6
, IPV6_PKTINFO
,
1079 (void *)&pad
, sizeof(pad
)) < 0)
1081 if (setsockopt(sd
, IPPROTO_IPV6
, IPV6_RECVPKTINFO
,
1082 (void *)&pad
, sizeof(pad
)) < 0)
1084 { msg(M_ERR
, "UDP: failed setsockopt for IPV6_RECVPKTINFO");}
1087 #endif /* if ENABLE_IP_PKTINFO */
1089 /* set socket file descriptor to not pass across execs, so that
1090 * scripts don't have access to it */
1097 bind_local(struct link_socket
*sock
, const sa_family_t ai_family
)
1099 /* bind to local address/port */
1100 if (sock
->bind_local
)
1102 if (sock
->socks_proxy
&& sock
->info
.proto
== PROTO_UDP
)
1104 socket_bind(sock
->ctrl_sd
, sock
->info
.lsa
->bind_local
,
1105 ai_family
, "SOCKS", false);
1109 socket_bind(sock
->sd
, sock
->info
.lsa
->bind_local
,
1111 "TCP/UDP", sock
->info
.bind_ipv6_only
);
1117 create_socket(struct link_socket
*sock
, struct addrinfo
*addr
)
1119 if (addr
->ai_protocol
== IPPROTO_UDP
|| addr
->ai_socktype
== SOCK_DGRAM
)
1121 sock
->sd
= create_socket_udp(addr
, sock
->sockflags
);
1122 sock
->sockflags
|= SF_GETADDRINFO_DGRAM
;
1124 /* Assume that control socket and data socket to the socks proxy
1125 * are using the same IP family */
1126 if (sock
->socks_proxy
)
1128 /* Construct a temporary addrinfo to create the socket,
1129 * currently resolve two remote addresses is not supported,
1130 * TODO: Rewrite the whole resolve_remote */
1131 struct addrinfo addrinfo_tmp
= *addr
;
1132 addrinfo_tmp
.ai_socktype
= SOCK_STREAM
;
1133 addrinfo_tmp
.ai_protocol
= IPPROTO_TCP
;
1134 sock
->ctrl_sd
= create_socket_tcp(&addrinfo_tmp
);
1137 else if (addr
->ai_protocol
== IPPROTO_TCP
|| addr
->ai_socktype
== SOCK_STREAM
)
1139 sock
->sd
= create_socket_tcp(addr
);
1145 /* set socket buffers based on --sndbuf and --rcvbuf options */
1146 socket_set_buffers(sock
->sd
, &sock
->socket_buffer_sizes
);
1148 /* set socket to --mark packets with given value */
1149 socket_set_mark(sock
->sd
, sock
->mark
);
1151 #if defined(TARGET_LINUX)
1154 msg(M_INFO
, "Using bind-dev %s", sock
->bind_dev
);
1155 if (setsockopt(sock
->sd
, SOL_SOCKET
, SO_BINDTODEVICE
, sock
->bind_dev
, strlen(sock
->bind_dev
) + 1) != 0)
1157 msg(M_WARN
|M_ERRNO
, "WARN: setsockopt SO_BINDTODEVICE=%s failed", sock
->bind_dev
);
1163 bind_local(sock
, addr
->ai_family
);
1166 #ifdef TARGET_ANDROID
1168 protect_fd_nonlocal(int fd
, const struct sockaddr
*addr
)
1170 /* pass socket FD to management interface to pass on to VPNService API
1171 * as "protected socket" (exempt from being routed into tunnel)
1173 if (addr_local(addr
))
1175 msg(D_SOCKET_DEBUG
, "Address is local, not protecting socket fd %d", fd
);
1179 msg(D_SOCKET_DEBUG
, "Protecting socket fd %d", fd
);
1180 management
->connection
.fdtosend
= fd
;
1181 management_android_control(management
, "PROTECTFD", __func__
);
1186 * Functions used for establishing a TCP stream connection.
1189 socket_do_listen(socket_descriptor_t sd
,
1190 const struct addrinfo
*local
,
1192 bool do_set_nonblock
)
1194 struct gc_arena gc
= gc_new();
1198 msg(M_INFO
, "Listening for incoming TCP connection on %s",
1199 print_sockaddr(local
->ai_addr
, &gc
));
1202 msg(M_ERR
, "TCP: listen() failed");
1206 /* set socket to non-blocking mode */
1207 if (do_set_nonblock
)
1216 socket_do_accept(socket_descriptor_t sd
,
1217 struct link_socket_actual
*act
,
1220 /* af_addr_size WILL return 0 in this case if AFs other than AF_INET
1221 * are compiled because act is empty here.
1222 * could use getsockname() to support later remote_len check
1224 socklen_t remote_len_af
= af_addr_size(act
->dest
.addr
.sa
.sa_family
);
1225 socklen_t remote_len
= sizeof(act
->dest
.addr
);
1226 socket_descriptor_t new_sd
= SOCKET_UNDEFINED
;
1230 #ifdef HAVE_GETPEERNAME
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");
1244 #else /* ifdef HAVE_GETPEERNAME */
1247 msg(M_WARN
, "TCP: this OS does not provide the getpeername() function");
1252 new_sd
= accept(sd
, &act
->dest
.addr
.sa
, &remote_len
);
1255 #if 0 /* For debugging only, test the effect of accept() failures */
1266 if (!socket_defined(new_sd
))
1268 msg(D_LINK_ERRORS
| M_ERRNO
, "TCP: accept(%d) failed", (int)sd
);
1270 /* only valid if we have remote_len_af!=0 */
1271 else if (remote_len_af
&& remote_len
!= remote_len_af
)
1273 msg(D_LINK_ERRORS
, "TCP: Received strange incoming connection with unknown address length=%d", remote_len
);
1274 openvpn_close_socket(new_sd
);
1275 new_sd
= SOCKET_UNDEFINED
;
1279 /* set socket file descriptor to not pass across execs, so that
1280 * scripts don't have access to it */
1287 tcp_connection_established(const struct link_socket_actual
*act
)
1289 struct gc_arena gc
= gc_new();
1290 msg(M_INFO
, "TCP connection established with %s",
1291 print_link_socket_actual(act
, &gc
));
1295 static socket_descriptor_t
1296 socket_listen_accept(socket_descriptor_t sd
,
1297 struct link_socket_actual
*act
,
1298 const char *remote_dynamic
,
1299 const struct addrinfo
*local
,
1302 volatile int *signal_received
)
1304 struct gc_arena gc
= gc_new();
1305 /* struct openvpn_sockaddr *remote = &act->dest; */
1306 struct openvpn_sockaddr remote_verify
= act
->dest
;
1307 socket_descriptor_t new_sd
= SOCKET_UNDEFINED
;
1310 socket_do_listen(sd
, local
, do_listen
, true);
1319 openvpn_fd_set(sd
, &reads
);
1323 status
= select(sd
+ 1, &reads
, NULL
, NULL
, &tv
);
1325 get_signal(signal_received
);
1326 if (*signal_received
)
1334 msg(D_LINK_ERRORS
| M_ERRNO
, "TCP: select() failed");
1339 management_sleep(1);
1343 new_sd
= socket_do_accept(sd
, act
, nowait
);
1345 if (socket_defined(new_sd
))
1347 struct addrinfo
*ai
= NULL
;
1350 openvpn_getaddrinfo(0, remote_dynamic
, NULL
, 1, NULL
,
1351 remote_verify
.addr
.sa
.sa_family
, &ai
);
1354 if (ai
&& !addrlist_match(&remote_verify
, ai
))
1357 "TCP NOTE: Rejected connection attempt from %s due to --remote setting",
1358 print_link_socket_actual(act
, &gc
));
1359 if (openvpn_close_socket(new_sd
))
1361 msg(M_ERR
, "TCP: close socket failed (new_sd)");
1374 management_sleep(1);
1377 if (!nowait
&& openvpn_close_socket(sd
))
1379 msg(M_ERR
, "TCP: close socket failed (sd)");
1382 tcp_connection_established(act
);
1388 /* older mingw versions and WinXP do not have this define,
1389 * but Vista and up support the functionality - just define it here
1393 #define IPV6_V6ONLY 27
1397 socket_bind(socket_descriptor_t sd
,
1398 struct addrinfo
*local
,
1403 struct gc_arena gc
= gc_new();
1406 * getaddrinfo for the bind address might return multiple AF_INET/AF_INET6
1407 * entries for the requested protocol.
1408 * For example if an address has multiple A records
1409 * What is the correct way to deal with it?
1412 struct addrinfo
*cur
;
1417 /* find the first addrinfo with correct ai_family */
1418 for (cur
= local
; cur
; cur
= cur
->ai_next
)
1420 if (cur
->ai_family
== ai_family
)
1427 msg(M_FATAL
, "%s: Socket bind failed: Addr to bind has no %s record",
1428 prefix
, addr_family_name(ai_family
));
1431 if (ai_family
== AF_INET6
)
1433 int v6only
= ipv6only
? 1 : 0; /* setsockopt must have an "int" */
1435 msg(M_INFO
, "setsockopt(IPV6_V6ONLY=%d)", v6only
);
1436 if (setsockopt(sd
, IPPROTO_IPV6
, IPV6_V6ONLY
, (void *) &v6only
, sizeof(v6only
)))
1438 msg(M_NONFATAL
|M_ERRNO
, "Setting IPV6_V6ONLY=%d failed", v6only
);
1441 if (bind(sd
, cur
->ai_addr
, cur
->ai_addrlen
))
1443 msg(M_FATAL
| M_ERRNO
, "%s: Socket bind failed on local address %s",
1445 print_sockaddr_ex(local
->ai_addr
, ":", PS_SHOW_PORT
, &gc
));
1451 openvpn_connect(socket_descriptor_t sd
,
1452 const struct sockaddr
*remote
,
1453 int connect_timeout
,
1454 volatile int *signal_received
)
1458 #ifdef TARGET_ANDROID
1459 protect_fd_nonlocal(sd
, remote
);
1462 #ifdef CONNECT_NONBLOCK
1464 status
= connect(sd
, remote
, af_addr_size(remote
->sa_family
));
1467 status
= openvpn_errno();
1471 status
== WSAEWOULDBLOCK
1473 status
== EINPROGRESS
1480 struct pollfd fds
[1];
1482 fds
[0].events
= POLLOUT
;
1483 status
= poll(fds
, 1, 0);
1489 openvpn_fd_set(sd
, &writes
);
1493 status
= select(sd
+ 1, NULL
, &writes
, NULL
, &tv
);
1495 if (signal_received
)
1497 get_signal(signal_received
);
1498 if (*signal_received
)
1506 status
= openvpn_errno();
1511 if (--connect_timeout
< 0)
1514 status
= WSAETIMEDOUT
;
1520 management_sleep(1);
1530 if (getsockopt(sd
, SOL_SOCKET
, SO_ERROR
, (void *) &val
, &len
) == 0
1531 && len
== sizeof(val
))
1537 status
= openvpn_errno();
1543 #else /* ifdef CONNECT_NONBLOCK */
1544 status
= connect(sd
, remote
, af_addr_size(remote
->sa_family
));
1547 status
= openvpn_errno();
1549 #endif /* ifdef CONNECT_NONBLOCK */
1555 set_actual_address(struct link_socket_actual
*actual
, struct addrinfo
*ai
)
1560 if (ai
->ai_family
== AF_INET
)
1562 actual
->dest
.addr
.in4
=
1563 *((struct sockaddr_in
*) ai
->ai_addr
);
1565 else if (ai
->ai_family
== AF_INET6
)
1567 actual
->dest
.addr
.in6
=
1568 *((struct sockaddr_in6
*) ai
->ai_addr
);
1578 socket_connect(socket_descriptor_t
*sd
,
1579 const struct sockaddr
*dest
,
1580 const int connect_timeout
,
1581 struct signal_info
*sig_info
)
1583 struct gc_arena gc
= gc_new();
1586 #ifdef CONNECT_NONBLOCK
1587 msg(M_INFO
, "Attempting to establish TCP connection with %s [nonblock]",
1588 print_sockaddr(dest
, &gc
));
1590 msg(M_INFO
, "Attempting to establish TCP connection with %s",
1591 print_sockaddr(dest
, &gc
));
1594 #ifdef ENABLE_MANAGEMENT
1597 management_set_state(management
,
1598 OPENVPN_STATE_TCP_CONNECT
,
1607 /* Set the actual address */
1608 status
= openvpn_connect(*sd
, dest
, connect_timeout
, &sig_info
->signal_received
);
1610 get_signal(&sig_info
->signal_received
);
1611 if (sig_info
->signal_received
)
1619 msg(D_LINK_ERRORS
, "TCP: connect to %s failed: %s",
1620 print_sockaddr(dest
, &gc
), strerror(status
));
1622 openvpn_close_socket(*sd
);
1623 *sd
= SOCKET_UNDEFINED
;
1624 sig_info
->signal_received
= SIGUSR1
;
1625 sig_info
->source
= SIG_SOURCE_CONNECTION_FAILED
;
1629 msg(M_INFO
, "TCP connection established with %s",
1630 print_sockaddr(dest
, &gc
));
1638 * Stream buffer handling prototypes -- stream_buf is a helper class
1639 * to assist in the packetization of stream transport protocols
1644 stream_buf_init(struct stream_buf
*sb
, struct buffer
*buf
,
1645 const unsigned int sockflags
, const int proto
);
1648 stream_buf_close(struct stream_buf
*sb
);
1651 stream_buf_added(struct stream_buf
*sb
, int length_added
);
1653 /* For stream protocols, allocate a buffer to build up packet.
1654 * Called after frame has been finalized. */
1657 socket_frame_init(const struct frame
*frame
, struct link_socket
*sock
)
1660 overlapped_io_init(&sock
->reads
, frame
, FALSE
, false);
1661 overlapped_io_init(&sock
->writes
, frame
, TRUE
, false);
1662 sock
->rw_handle
.read
= sock
->reads
.overlapped
.hEvent
;
1663 sock
->rw_handle
.write
= sock
->writes
.overlapped
.hEvent
;
1666 if (link_socket_connection_oriented(sock
))
1669 stream_buf_init(&sock
->stream_buf
,
1670 &sock
->reads
.buf_init
,
1674 alloc_buf_sock_tun(&sock
->stream_buf_data
,
1677 FRAME_HEADROOM_MARKER_READ_STREAM
);
1679 stream_buf_init(&sock
->stream_buf
,
1680 &sock
->stream_buf_data
,
1688 * Adjust frame structure based on a Path MTU value given
1692 frame_adjust_path_mtu(struct frame
*frame
, int pmtu
, int proto
)
1694 frame_set_mtu_dynamic(frame
, pmtu
- datagram_overhead(proto
), SET_MTU_UPPER_BOUND
);
1698 resolve_bind_local(struct link_socket
*sock
, const sa_family_t af
)
1700 struct gc_arena gc
= gc_new();
1702 /* resolve local address if undefined */
1703 if (!sock
->info
.lsa
->bind_local
)
1705 int flags
= GETADDR_RESOLVE
| GETADDR_WARN_ON_SIGNAL
1706 |GETADDR_FATAL
| GETADDR_PASSIVE
;
1709 if (proto_is_dgram(sock
->info
.proto
))
1711 flags
|= GETADDR_DATAGRAM
;
1714 /* will return AF_{INET|INET6}from local_host */
1715 status
= get_cached_dns_entry(sock
->dns_cache
,
1720 &sock
->info
.lsa
->bind_local
);
1724 status
= openvpn_getaddrinfo(flags
, sock
->local_host
, sock
->local_port
, 0,
1725 NULL
, af
, &sock
->info
.lsa
->bind_local
);
1730 msg(M_FATAL
, "getaddrinfo() failed for local \"%s:%s\": %s",
1731 sock
->local_host
, sock
->local_port
,
1732 gai_strerror(status
));
1740 resolve_remote(struct link_socket
*sock
,
1742 const char **remote_dynamic
,
1743 volatile int *signal_received
)
1745 struct gc_arena gc
= gc_new();
1747 /* resolve remote address if undefined */
1748 if (!sock
->info
.lsa
->remote_list
)
1750 if (sock
->remote_host
)
1752 unsigned int flags
= sf2gaf(GETADDR_RESOLVE
|GETADDR_UPDATE_MANAGEMENT_STATE
, sock
->sockflags
);
1755 struct addrinfo
*ai
;
1756 if (proto_is_dgram(sock
->info
.proto
))
1758 flags
|= GETADDR_DATAGRAM
;
1761 if (sock
->resolve_retry_seconds
== RESOLV_RETRY_INFINITE
)
1765 flags
|= (GETADDR_TRY_ONCE
| GETADDR_FATAL
);
1769 else if (phase
== 1)
1771 if (sock
->resolve_retry_seconds
)
1777 flags
|= (GETADDR_FATAL
| GETADDR_MENTION_RESOLVE_RETRY
);
1781 else if (phase
== 2)
1783 if (sock
->resolve_retry_seconds
)
1785 flags
|= GETADDR_FATAL
;
1786 retry
= sock
->resolve_retry_seconds
;
1799 status
= get_cached_dns_entry(sock
->dns_cache
,
1806 status
= openvpn_getaddrinfo(flags
, sock
->remote_host
, sock
->remote_port
,
1807 retry
, signal_received
, sock
->info
.af
, &ai
);
1812 sock
->info
.lsa
->remote_list
= ai
;
1813 sock
->info
.lsa
->current_remote
= ai
;
1815 dmsg(D_SOCKET_DEBUG
,
1816 "RESOLVE_REMOTE flags=0x%04x phase=%d rrs=%d sig=%d status=%d",
1820 signal_received
? *signal_received
: -1,
1823 if (signal_received
)
1825 if (*signal_received
)
1832 if (signal_received
)
1834 *signal_received
= SIGUSR1
;
1841 /* should we re-use previous active remote address? */
1842 if (link_socket_actual_defined(&sock
->info
.lsa
->actual
))
1844 msg(M_INFO
, "TCP/UDP: Preserving recently used remote address: %s",
1845 print_link_socket_actual(&sock
->info
.lsa
->actual
, &gc
));
1848 *remote_dynamic
= NULL
;
1853 CLEAR(sock
->info
.lsa
->actual
);
1854 if (sock
->info
.lsa
->current_remote
)
1856 set_actual_address(&sock
->info
.lsa
->actual
,
1857 sock
->info
.lsa
->current_remote
);
1867 struct link_socket
*
1868 link_socket_new(void)
1870 struct link_socket
*sock
;
1872 ALLOC_OBJ_CLEAR(sock
, struct link_socket
);
1873 sock
->sd
= SOCKET_UNDEFINED
;
1874 sock
->ctrl_sd
= SOCKET_UNDEFINED
;
1879 link_socket_init_phase1(struct link_socket
*sock
,
1880 const char *local_host
,
1881 const char *local_port
,
1882 const char *remote_host
,
1883 const char *remote_port
,
1884 struct cached_dns_entry
*dns_cache
,
1887 bool bind_ipv6_only
,
1889 const struct link_socket
*accept_from
,
1890 struct http_proxy_info
*http_proxy
,
1891 struct socks_proxy_info
*socks_proxy
,
1898 struct link_socket_addr
*lsa
,
1899 const char *ipchange_command
,
1900 const struct plugin_list
*plugins
,
1901 int resolve_retry_seconds
,
1902 int mtu_discover_type
,
1906 const char *bind_dev
,
1907 struct event_timeout
*server_poll_timeout
,
1908 unsigned int sockflags
)
1912 sock
->local_host
= local_host
;
1913 sock
->local_port
= local_port
;
1914 sock
->remote_host
= remote_host
;
1915 sock
->remote_port
= remote_port
;
1916 sock
->dns_cache
= dns_cache
;
1917 sock
->http_proxy
= http_proxy
;
1918 sock
->socks_proxy
= socks_proxy
;
1919 sock
->bind_local
= bind_local
;
1920 sock
->inetd
= inetd
;
1921 sock
->resolve_retry_seconds
= resolve_retry_seconds
;
1922 sock
->mtu_discover_type
= mtu_discover_type
;
1925 sock
->gremlin
= gremlin
;
1928 sock
->socket_buffer_sizes
.rcvbuf
= rcvbuf
;
1929 sock
->socket_buffer_sizes
.sndbuf
= sndbuf
;
1931 sock
->sockflags
= sockflags
;
1933 sock
->bind_dev
= bind_dev
;
1935 sock
->info
.proto
= proto
;
1937 sock
->info
.remote_float
= remote_float
;
1938 sock
->info
.lsa
= lsa
;
1939 sock
->info
.bind_ipv6_only
= bind_ipv6_only
;
1940 sock
->info
.ipchange_command
= ipchange_command
;
1941 sock
->info
.plugins
= plugins
;
1942 sock
->server_poll_timeout
= server_poll_timeout
;
1945 if (mode
== LS_MODE_TCP_ACCEPT_FROM
)
1947 ASSERT(accept_from
);
1948 ASSERT(sock
->info
.proto
== PROTO_TCP_SERVER
);
1949 ASSERT(!sock
->inetd
);
1950 sock
->sd
= accept_from
->sd
;
1951 /* inherit (possibly guessed) info AF from parent context */
1952 sock
->info
.af
= accept_from
->info
.af
;
1955 /* are we running in HTTP proxy mode? */
1956 if (sock
->http_proxy
)
1958 ASSERT(sock
->info
.proto
== PROTO_TCP_CLIENT
);
1959 ASSERT(!sock
->inetd
);
1961 /* the proxy server */
1962 sock
->remote_host
= http_proxy
->options
.server
;
1963 sock
->remote_port
= http_proxy
->options
.port
;
1965 /* the OpenVPN server we will use the proxy to connect to */
1966 sock
->proxy_dest_host
= remote_host
;
1967 sock
->proxy_dest_port
= remote_port
;
1969 /* or in Socks proxy mode? */
1970 else if (sock
->socks_proxy
)
1972 ASSERT(!sock
->inetd
);
1974 /* the proxy server */
1975 sock
->remote_host
= socks_proxy
->server
;
1976 sock
->remote_port
= socks_proxy
->port
;
1978 /* the OpenVPN server we will use the proxy to connect to */
1979 sock
->proxy_dest_host
= remote_host
;
1980 sock
->proxy_dest_port
= remote_port
;
1984 sock
->remote_host
= remote_host
;
1985 sock
->remote_port
= remote_port
;
1988 /* bind behavior for TCP server vs. client */
1989 if (sock
->info
.proto
== PROTO_TCP_SERVER
)
1991 if (sock
->mode
== LS_MODE_TCP_ACCEPT_FROM
)
1993 sock
->bind_local
= false;
1997 sock
->bind_local
= true;
2001 /* were we started by inetd or xinetd? */
2004 ASSERT(sock
->info
.proto
!= PROTO_TCP_CLIENT
);
2005 ASSERT(socket_defined(inetd_socket_descriptor
));
2006 sock
->sd
= inetd_socket_descriptor
;
2007 set_cloexec(sock
->sd
); /* not created by create_socket*() */
2009 else if (mode
!= LS_MODE_TCP_ACCEPT_FROM
)
2011 if (sock
->bind_local
)
2013 resolve_bind_local(sock
, sock
->info
.af
);
2015 resolve_remote(sock
, 1, NULL
, NULL
);
2021 phase2_inetd(struct link_socket
*sock
, const struct frame
*frame
,
2022 const char *remote_dynamic
, volatile int *signal_received
)
2024 bool remote_changed
= false;
2026 if (sock
->info
.proto
== PROTO_TCP_SERVER
)
2028 /* AF_INET as default (and fallback) for inetd */
2029 sock
->info
.lsa
->actual
.dest
.addr
.sa
.sa_family
= AF_INET
;
2030 #ifdef HAVE_GETSOCKNAME
2032 /* inetd: hint family type for dest = local's */
2033 struct openvpn_sockaddr local_addr
;
2034 socklen_t addrlen
= sizeof(local_addr
);
2035 if (getsockname(sock
->sd
, &local_addr
.addr
.sa
, &addrlen
) == 0)
2037 sock
->info
.lsa
->actual
.dest
.addr
.sa
.sa_family
= local_addr
.addr
.sa
.sa_family
;
2038 dmsg(D_SOCKET_DEBUG
, "inetd(%s): using sa_family=%d from getsockname(%d)",
2039 proto2ascii(sock
->info
.proto
, sock
->info
.af
, false),
2040 local_addr
.addr
.sa
.sa_family
, (int)sock
->sd
);
2044 int saved_errno
= errno
;
2045 msg(M_WARN
|M_ERRNO
, "inetd(%s): getsockname(%d) failed, using AF_INET",
2046 proto2ascii(sock
->info
.proto
, sock
->info
.af
, false), (int)sock
->sd
);
2047 /* if not called with a socket on stdin, --inetd cannot work */
2048 if (saved_errno
== ENOTSOCK
)
2050 msg(M_FATAL
, "ERROR: socket required for --inetd operation");
2054 #else /* ifdef HAVE_GETSOCKNAME */
2055 msg(M_WARN
, "inetd(%s): this OS does not provide the getsockname() "
2056 "function, using AF_INET",
2057 proto2ascii(sock
->info
.proto
, false));
2058 #endif /* ifdef HAVE_GETSOCKNAME */
2060 socket_listen_accept(sock
->sd
,
2061 &sock
->info
.lsa
->actual
,
2063 sock
->info
.lsa
->bind_local
,
2065 sock
->inetd
== INETD_NOWAIT
,
2068 ASSERT(!remote_changed
);
2072 phase2_set_socket_flags(struct link_socket
*sock
)
2074 /* set misc socket parameters */
2075 socket_set_flags(sock
->sd
, sock
->sockflags
);
2077 /* set socket to non-blocking mode */
2078 set_nonblock(sock
->sd
);
2080 /* set Path MTU discovery options on the socket */
2081 set_mtu_discover_type(sock
->sd
, sock
->mtu_discover_type
, sock
->info
.af
);
2083 #if EXTENDED_SOCKET_ERROR_CAPABILITY
2084 /* if the OS supports it, enable extended error passing on the socket */
2085 set_sock_extended_error_passing(sock
->sd
);
2091 linksock_print_addr(struct link_socket
*sock
)
2093 struct gc_arena gc
= gc_new();
2094 const int msglevel
= (sock
->mode
== LS_MODE_TCP_ACCEPT_FROM
) ? D_INIT_MEDIUM
: M_INFO
;
2096 /* print local address */
2099 msg(msglevel
, "%s link local: [inetd]", proto2ascii(sock
->info
.proto
, sock
->info
.af
, true));
2101 else if (sock
->bind_local
)
2103 sa_family_t ai_family
= sock
->info
.lsa
->actual
.dest
.addr
.sa
.sa_family
;
2104 /* Socket is always bound on the first matching address,
2105 * For bound sockets with no remote addr this is the element of
2107 struct addrinfo
*cur
;
2108 for (cur
= sock
->info
.lsa
->bind_local
; cur
; cur
= cur
->ai_next
)
2110 if (!ai_family
|| ai_family
== cur
->ai_family
)
2116 msg(msglevel
, "%s link local (bound): %s",
2117 proto2ascii(sock
->info
.proto
, sock
->info
.af
, true),
2118 print_sockaddr(cur
->ai_addr
,&gc
));
2122 msg(msglevel
, "%s link local: (not bound)",
2123 proto2ascii(sock
->info
.proto
, sock
->info
.af
, true));
2126 /* print active remote address */
2127 msg(msglevel
, "%s link remote: %s",
2128 proto2ascii(sock
->info
.proto
, sock
->info
.af
, true),
2129 print_link_socket_actual_ex(&sock
->info
.lsa
->actual
,
2131 PS_SHOW_PORT_IF_DEFINED
,
2137 phase2_tcp_server(struct link_socket
*sock
, const char *remote_dynamic
,
2138 volatile int *signal_received
)
2142 case LS_MODE_DEFAULT
:
2143 sock
->sd
= socket_listen_accept(sock
->sd
,
2144 &sock
->info
.lsa
->actual
,
2146 sock
->info
.lsa
->bind_local
,
2152 case LS_MODE_TCP_LISTEN
:
2153 socket_do_listen(sock
->sd
,
2154 sock
->info
.lsa
->bind_local
,
2159 case LS_MODE_TCP_ACCEPT_FROM
:
2160 sock
->sd
= socket_do_accept(sock
->sd
,
2161 &sock
->info
.lsa
->actual
,
2163 if (!socket_defined(sock
->sd
))
2165 *signal_received
= SIGTERM
;
2168 tcp_connection_established(&sock
->info
.lsa
->actual
);
2178 phase2_tcp_client(struct link_socket
*sock
, struct signal_info
*sig_info
)
2180 bool proxy_retry
= false;
2183 socket_connect(&sock
->sd
,
2184 sock
->info
.lsa
->current_remote
->ai_addr
,
2185 get_server_poll_remaining_time(sock
->server_poll_timeout
),
2188 if (sig_info
->signal_received
)
2193 if (sock
->http_proxy
)
2195 proxy_retry
= establish_http_proxy_passthru(sock
->http_proxy
,
2197 sock
->proxy_dest_host
,
2198 sock
->proxy_dest_port
,
2199 sock
->server_poll_timeout
,
2200 &sock
->stream_buf
.residual
,
2201 &sig_info
->signal_received
);
2203 else if (sock
->socks_proxy
)
2205 establish_socks_proxy_passthru(sock
->socks_proxy
,
2207 sock
->proxy_dest_host
,
2208 sock
->proxy_dest_port
,
2209 &sig_info
->signal_received
);
2213 openvpn_close_socket(sock
->sd
);
2214 sock
->sd
= create_socket_tcp(sock
->info
.lsa
->current_remote
);
2217 } while (proxy_retry
);
2222 phase2_socks_client(struct link_socket
*sock
, struct signal_info
*sig_info
)
2224 socket_connect(&sock
->ctrl_sd
,
2225 sock
->info
.lsa
->current_remote
->ai_addr
,
2226 get_server_poll_remaining_time(sock
->server_poll_timeout
),
2229 if (sig_info
->signal_received
)
2234 establish_socks_proxy_udpassoc(sock
->socks_proxy
,
2237 &sock
->socks_relay
.dest
,
2238 &sig_info
->signal_received
);
2240 if (sig_info
->signal_received
)
2245 sock
->remote_host
= sock
->proxy_dest_host
;
2246 sock
->remote_port
= sock
->proxy_dest_port
;
2248 addr_zero_host(&sock
->info
.lsa
->actual
.dest
);
2249 if (sock
->info
.lsa
->remote_list
)
2251 freeaddrinfo(sock
->info
.lsa
->remote_list
);
2252 sock
->info
.lsa
->current_remote
= NULL
;
2253 sock
->info
.lsa
->remote_list
= NULL
;
2256 resolve_remote(sock
, 1, NULL
, &sig_info
->signal_received
);
2259 /* finalize socket initialization */
2261 link_socket_init_phase2(struct link_socket
*sock
,
2262 const struct frame
*frame
,
2263 struct signal_info
*sig_info
)
2265 const char *remote_dynamic
= NULL
;
2271 if (sig_info
->signal_received
)
2273 sig_save
= sig_info
->signal_received
;
2274 sig_info
->signal_received
= 0;
2277 /* initialize buffers */
2278 socket_frame_init(frame
, sock
);
2281 * Pass a remote name to connect/accept so that
2282 * they can test for dynamic IP address changes
2283 * and throw a SIGUSR1 if appropriate.
2285 if (sock
->resolve_retry_seconds
)
2287 remote_dynamic
= sock
->remote_host
;
2290 /* were we started by inetd or xinetd? */
2293 phase2_inetd(sock
, frame
, remote_dynamic
, &sig_info
->signal_received
);
2294 if (sig_info
->signal_received
)
2302 /* Second chance to resolv/create socket */
2303 resolve_remote(sock
, 2, &remote_dynamic
, &sig_info
->signal_received
);
2305 /* If a valid remote has been found, create the socket with its addrinfo */
2306 if (sock
->info
.lsa
->current_remote
)
2308 create_socket(sock
, sock
->info
.lsa
->current_remote
);
2311 /* If socket has not already been created create it now */
2312 if (sock
->sd
== SOCKET_UNDEFINED
)
2314 /* If we have no --remote and have still not figured out the
2315 * protocol family to use we will use the first of the bind */
2317 if (sock
->bind_local
&& !sock
->remote_host
&& sock
->info
.lsa
->bind_local
)
2319 /* Warn if this is because neither v4 or v6 was specified
2320 * and we should not connect a remote */
2321 if (sock
->info
.af
== AF_UNSPEC
)
2323 msg(M_WARN
, "Could not determine IPv4/IPv6 protocol. Using %s",
2324 addr_family_name(sock
->info
.lsa
->bind_local
->ai_family
));
2325 sock
->info
.af
= sock
->info
.lsa
->bind_local
->ai_family
;
2328 create_socket(sock
, sock
->info
.lsa
->bind_local
);
2332 /* Socket still undefined, give a warning and abort connection */
2333 if (sock
->sd
== SOCKET_UNDEFINED
)
2335 msg(M_WARN
, "Could not determine IPv4/IPv6 protocol");
2336 sig_info
->signal_received
= SIGUSR1
;
2340 if (sig_info
->signal_received
)
2345 if (sock
->info
.proto
== PROTO_TCP_SERVER
)
2347 phase2_tcp_server(sock
, remote_dynamic
,
2348 &sig_info
->signal_received
);
2350 else if (sock
->info
.proto
== PROTO_TCP_CLIENT
)
2352 phase2_tcp_client(sock
, sig_info
);
2355 else if (sock
->info
.proto
== PROTO_UDP
&& sock
->socks_proxy
)
2357 phase2_socks_client(sock
, sig_info
);
2359 #ifdef TARGET_ANDROID
2362 protect_fd_nonlocal(sock
->sd
, &sock
->info
.lsa
->actual
.dest
.addr
.sa
);
2365 if (sig_info
->signal_received
)
2371 phase2_set_socket_flags(sock
);
2372 linksock_print_addr(sock
);
2377 if (!sig_info
->signal_received
)
2379 sig_info
->signal_received
= sig_save
;
2385 link_socket_close(struct link_socket
*sock
)
2390 const int gremlin
= GREMLIN_CONNECTION_FLOOD_LEVEL(sock
->gremlin
);
2392 const int gremlin
= 0;
2395 if (socket_defined(sock
->sd
))
2398 close_net_event_win32(&sock
->listen_handle
, sock
->sd
, 0);
2402 msg(D_LOW
, "TCP/UDP: Closing socket");
2403 if (openvpn_close_socket(sock
->sd
))
2405 msg(M_WARN
| M_ERRNO
, "TCP/UDP: Close Socket failed");
2408 sock
->sd
= SOCKET_UNDEFINED
;
2412 overlapped_io_close(&sock
->reads
);
2413 overlapped_io_close(&sock
->writes
);
2418 if (socket_defined(sock
->ctrl_sd
))
2420 if (openvpn_close_socket(sock
->ctrl_sd
))
2422 msg(M_WARN
| M_ERRNO
, "TCP/UDP: Close Socket (ctrl_sd) failed");
2424 sock
->ctrl_sd
= SOCKET_UNDEFINED
;
2427 stream_buf_close(&sock
->stream_buf
);
2428 free_buf(&sock
->stream_buf_data
);
2436 /* for stream protocols, allow for packet length prefix */
2438 socket_adjust_frame_parameters(struct frame
*frame
, int proto
)
2440 if (link_socket_proto_connection_oriented(proto
))
2442 frame_add_to_extra_frame(frame
, sizeof(packet_size_type
));
2447 setenv_trusted(struct env_set
*es
, const struct link_socket_info
*info
)
2449 setenv_link_socket_actual(es
, "trusted", &info
->lsa
->actual
, SA_IP_PORT
);
2453 ipchange_fmt(const bool include_cmd
, struct argv
*argv
, const struct link_socket_info
*info
, struct gc_arena
*gc
)
2455 const char *host
= print_sockaddr_ex(&info
->lsa
->actual
.dest
.addr
.sa
, " ", PS_SHOW_PORT
, gc
);
2458 argv_parse_cmd(argv
, info
->ipchange_command
);
2459 argv_printf_cat(argv
, "%s", host
);
2463 argv_printf(argv
, "%s", host
);
2469 link_socket_connection_initiated(struct link_socket_info
*info
,
2470 const struct link_socket_actual
*act
,
2471 const char *common_name
,
2474 struct gc_arena gc
= gc_new();
2476 info
->lsa
->actual
= *act
; /* Note: skip this line for --force-dest */
2477 setenv_trusted(es
, info
);
2478 info
->connection_established
= true;
2480 /* Print connection initiated message, with common name if available */
2482 struct buffer out
= alloc_buf_gc(256, &gc
);
2485 buf_printf(&out
, "[%s] ", common_name
);
2487 buf_printf(&out
, "Peer Connection Initiated with %s", print_link_socket_actual(&info
->lsa
->actual
, &gc
));
2488 msg(M_INFO
, "%s", BSTR(&out
));
2491 /* set environmental vars */
2492 setenv_str(es
, "common_name", common_name
);
2494 /* Process --ipchange plugin */
2495 if (plugin_defined(info
->plugins
, OPENVPN_PLUGIN_IPCHANGE
))
2497 struct argv argv
= argv_new();
2498 ipchange_fmt(false, &argv
, info
, &gc
);
2499 if (plugin_call(info
->plugins
, OPENVPN_PLUGIN_IPCHANGE
, &argv
, NULL
, es
) != OPENVPN_PLUGIN_FUNC_SUCCESS
)
2501 msg(M_WARN
, "WARNING: ipchange plugin call failed");
2506 /* Process --ipchange option */
2507 if (info
->ipchange_command
)
2509 struct argv argv
= argv_new();
2510 setenv_str(es
, "script_type", "ipchange");
2511 ipchange_fmt(true, &argv
, info
, &gc
);
2512 openvpn_run_script(&argv
, es
, 0, "--ipchange");
2520 link_socket_bad_incoming_addr(struct buffer
*buf
,
2521 const struct link_socket_info
*info
,
2522 const struct link_socket_actual
*from_addr
)
2524 struct gc_arena gc
= gc_new();
2525 struct addrinfo
*ai
;
2527 switch (from_addr
->dest
.addr
.sa
.sa_family
)
2532 "TCP/UDP: Incoming packet rejected from %s[%d], expected peer address: %s (allow this incoming source address/port by removing --remote or adding --float)",
2533 print_link_socket_actual(from_addr
, &gc
),
2534 (int)from_addr
->dest
.addr
.sa
.sa_family
,
2535 print_sockaddr_ex(info
->lsa
->remote_list
->ai_addr
,":",PS_SHOW_PORT
, &gc
));
2536 /* print additional remote addresses */
2537 for (ai
= info
->lsa
->remote_list
->ai_next
; ai
; ai
= ai
->ai_next
)
2539 msg(D_LINK_ERRORS
,"or from peer address: %s",
2540 print_sockaddr_ex(ai
->ai_addr
,":",PS_SHOW_PORT
, &gc
));
2549 link_socket_bad_outgoing_addr(void)
2551 dmsg(D_READ_WRITE
, "TCP/UDP: No outgoing address to send packet");
2555 link_socket_current_remote(const struct link_socket_info
*info
)
2557 const struct link_socket_addr
*lsa
= info
->lsa
;
2560 * This logic supports "redirect-gateway" semantic, which
2561 * makes sense only for PF_INET routes over PF_INET endpoints
2563 * Maybe in the future consider PF_INET6 endpoints also ...
2564 * by now just ignore it
2566 * For --remote entries with multiple addresses this
2567 * only return the actual endpoint we have successfully connected to
2569 if (lsa
->actual
.dest
.addr
.sa
.sa_family
!= AF_INET
)
2571 return IPV4_INVALID_ADDR
;
2574 if (link_socket_actual_defined(&lsa
->actual
))
2576 return ntohl(lsa
->actual
.dest
.addr
.in4
.sin_addr
.s_addr
);
2578 else if (lsa
->current_remote
)
2580 return ntohl(((struct sockaddr_in
*)lsa
->current_remote
->ai_addr
)
2589 const struct in6_addr
*
2590 link_socket_current_remote_ipv6(const struct link_socket_info
*info
)
2592 const struct link_socket_addr
*lsa
= info
->lsa
;
2594 /* This logic supports "redirect-gateway" semantic,
2595 * for PF_INET6 routes over PF_INET6 endpoints
2597 * For --remote entries with multiple addresses this
2598 * only return the actual endpoint we have successfully connected to
2600 if (lsa
->actual
.dest
.addr
.sa
.sa_family
!= AF_INET6
)
2605 if (link_socket_actual_defined(&lsa
->actual
))
2607 return &(lsa
->actual
.dest
.addr
.in6
.sin6_addr
);
2609 else if (lsa
->current_remote
)
2611 return &(((struct sockaddr_in6
*)lsa
->current_remote
->ai_addr
)->sin6_addr
);
2620 * Return a status string describing socket state.
2623 socket_stat(const struct link_socket
*s
, unsigned int rwflags
, struct gc_arena
*gc
)
2625 struct buffer out
= alloc_buf_gc(64, gc
);
2628 if (rwflags
& EVENT_READ
)
2630 buf_printf(&out
, "S%s",
2631 (s
->rwflags_debug
& EVENT_READ
) ? "R" : "r");
2633 buf_printf(&out
, "%s",
2634 overlapped_io_state_ascii(&s
->reads
));
2637 if (rwflags
& EVENT_WRITE
)
2639 buf_printf(&out
, "S%s",
2640 (s
->rwflags_debug
& EVENT_WRITE
) ? "W" : "w");
2642 buf_printf(&out
, "%s",
2643 overlapped_io_state_ascii(&s
->writes
));
2649 buf_printf(&out
, "S?");
2655 * Stream buffer functions, used to packetize a TCP
2656 * stream connection.
2660 stream_buf_reset(struct stream_buf
*sb
)
2662 dmsg(D_STREAM_DEBUG
, "STREAM: RESET");
2663 sb
->residual_fully_formed
= false;
2664 sb
->buf
= sb
->buf_init
;
2665 buf_reset(&sb
->next
);
2670 stream_buf_init(struct stream_buf
*sb
,
2672 const unsigned int sockflags
,
2675 sb
->buf_init
= *buf
;
2676 sb
->maxlen
= sb
->buf_init
.len
;
2677 sb
->buf_init
.len
= 0;
2678 sb
->residual
= alloc_buf(sb
->maxlen
);
2681 sb
->port_share_state
= ((sockflags
& SF_PORT_SHARE
) && (proto
== PROTO_TCP_SERVER
))
2685 stream_buf_reset(sb
);
2687 dmsg(D_STREAM_DEBUG
, "STREAM: INIT maxlen=%d", sb
->maxlen
);
2691 stream_buf_set_next(struct stream_buf
*sb
)
2693 /* set up 'next' for next i/o read */
2695 sb
->next
.offset
= sb
->buf
.offset
+ sb
->buf
.len
;
2696 sb
->next
.len
= (sb
->len
>= 0 ? sb
->len
: sb
->maxlen
) - sb
->buf
.len
;
2697 dmsg(D_STREAM_DEBUG
, "STREAM: SET NEXT, buf=[%d,%d] next=[%d,%d] len=%d maxlen=%d",
2698 sb
->buf
.offset
, sb
->buf
.len
,
2699 sb
->next
.offset
, sb
->next
.len
,
2700 sb
->len
, sb
->maxlen
);
2701 ASSERT(sb
->next
.len
> 0);
2702 ASSERT(buf_safe(&sb
->buf
, sb
->next
.len
));
2706 stream_buf_get_final(struct stream_buf
*sb
, struct buffer
*buf
)
2708 dmsg(D_STREAM_DEBUG
, "STREAM: GET FINAL len=%d",
2709 buf_defined(&sb
->buf
) ? sb
->buf
.len
: -1);
2710 ASSERT(buf_defined(&sb
->buf
));
2715 stream_buf_get_next(struct stream_buf
*sb
, struct buffer
*buf
)
2717 dmsg(D_STREAM_DEBUG
, "STREAM: GET NEXT len=%d",
2718 buf_defined(&sb
->next
) ? sb
->next
.len
: -1);
2719 ASSERT(buf_defined(&sb
->next
));
2724 stream_buf_read_setup_dowork(struct link_socket
*sock
)
2726 if (sock
->stream_buf
.residual
.len
&& !sock
->stream_buf
.residual_fully_formed
)
2728 ASSERT(buf_copy(&sock
->stream_buf
.buf
, &sock
->stream_buf
.residual
));
2729 ASSERT(buf_init(&sock
->stream_buf
.residual
, 0));
2730 sock
->stream_buf
.residual_fully_formed
= stream_buf_added(&sock
->stream_buf
, 0);
2731 dmsg(D_STREAM_DEBUG
, "STREAM: RESIDUAL FULLY FORMED [%s], len=%d",
2732 sock
->stream_buf
.residual_fully_formed
? "YES" : "NO",
2733 sock
->stream_buf
.residual
.len
);
2736 if (!sock
->stream_buf
.residual_fully_formed
)
2738 stream_buf_set_next(&sock
->stream_buf
);
2740 return !sock
->stream_buf
.residual_fully_formed
;
2744 stream_buf_added(struct stream_buf
*sb
,
2747 dmsg(D_STREAM_DEBUG
, "STREAM: ADD length_added=%d", length_added
);
2748 if (length_added
> 0)
2750 sb
->buf
.len
+= length_added
;
2753 /* if length unknown, see if we can get the length prefix from
2754 * the head of the buffer */
2755 if (sb
->len
< 0 && sb
->buf
.len
>= (int) sizeof(packet_size_type
))
2757 packet_size_type net_size
;
2760 if (sb
->port_share_state
== PS_ENABLED
)
2762 if (!is_openvpn_protocol(&sb
->buf
))
2764 msg(D_STREAM_ERRORS
, "Non-OpenVPN client protocol detected");
2765 sb
->port_share_state
= PS_FOREIGN
;
2771 sb
->port_share_state
= PS_DISABLED
;
2776 ASSERT(buf_read(&sb
->buf
, &net_size
, sizeof(net_size
)));
2777 sb
->len
= ntohps(net_size
);
2779 if (sb
->len
< 1 || sb
->len
> sb
->maxlen
)
2781 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
);
2782 stream_buf_reset(sb
);
2788 /* is our incoming packet fully read? */
2789 if (sb
->len
> 0 && sb
->buf
.len
>= sb
->len
)
2791 /* save any residual data that's part of the next packet */
2792 ASSERT(buf_init(&sb
->residual
, 0));
2793 if (sb
->buf
.len
> sb
->len
)
2795 ASSERT(buf_copy_excess(&sb
->residual
, &sb
->buf
, sb
->len
));
2797 dmsg(D_STREAM_DEBUG
, "STREAM: ADD returned TRUE, buf_len=%d, residual_len=%d",
2799 BLEN(&sb
->residual
));
2804 dmsg(D_STREAM_DEBUG
, "STREAM: ADD returned FALSE (have=%d need=%d)", sb
->buf
.len
, sb
->len
);
2805 stream_buf_set_next(sb
);
2811 stream_buf_close(struct stream_buf
*sb
)
2813 free_buf(&sb
->residual
);
2817 * The listen event is a special event whose sole purpose is
2818 * to tell us that there's a new incoming connection on a
2819 * TCP socket, for use in server mode.
2822 socket_listen_event_handle(struct link_socket
*s
)
2825 if (!defined_net_event_win32(&s
->listen_handle
))
2827 init_net_event_win32(&s
->listen_handle
, FD_ACCEPT
, s
->sd
, 0);
2829 return &s
->listen_handle
;
2830 #else /* ifdef _WIN32 */
2836 * Format IP addresses in ascii
2840 print_sockaddr_ex(const struct sockaddr
*sa
,
2841 const char *separator
,
2842 const unsigned int flags
,
2843 struct gc_arena
*gc
)
2845 struct buffer out
= alloc_buf_gc(128, gc
);
2846 bool addr_is_defined
= false;
2847 char hostaddr
[NI_MAXHOST
] = "";
2848 char servname
[NI_MAXSERV
] = "";
2851 socklen_t salen
= 0;
2852 switch (sa
->sa_family
)
2855 if (!(flags
& PS_DONT_SHOW_FAMILY
))
2857 buf_puts(&out
, "[AF_INET]");
2859 salen
= sizeof(struct sockaddr_in
);
2860 addr_is_defined
= ((struct sockaddr_in
*) sa
)->sin_addr
.s_addr
!= 0;
2864 if (!(flags
& PS_DONT_SHOW_FAMILY
))
2866 buf_puts(&out
, "[AF_INET6]");
2868 salen
= sizeof(struct sockaddr_in6
);
2869 addr_is_defined
= !IN6_IS_ADDR_UNSPECIFIED(&((struct sockaddr_in6
*) sa
)->sin6_addr
);
2873 if (!(flags
& PS_DONT_SHOW_FAMILY
))
2875 return "[AF_UNSPEC]";
2886 status
= getnameinfo(sa
, salen
, hostaddr
, sizeof(hostaddr
),
2887 servname
, sizeof(servname
), NI_NUMERICHOST
| NI_NUMERICSERV
);
2891 buf_printf(&out
,"[nameinfo() err: %s]",gai_strerror(status
));
2895 if (!(flags
& PS_DONT_SHOW_ADDR
))
2897 if (addr_is_defined
)
2899 buf_puts(&out
, hostaddr
);
2903 buf_puts(&out
, "[undef]");
2907 if ((flags
& PS_SHOW_PORT
) || (flags
& PS_SHOW_PORT_IF_DEFINED
))
2911 buf_puts(&out
, separator
);
2914 buf_puts(&out
, servname
);
2921 print_link_socket_actual(const struct link_socket_actual
*act
, struct gc_arena
*gc
)
2923 return print_link_socket_actual_ex(act
, ":", PS_SHOW_PORT
|PS_SHOW_PKTINFO
, gc
);
2927 #define IF_NAMESIZE 16
2931 print_link_socket_actual_ex(const struct link_socket_actual
*act
,
2932 const char *separator
,
2933 const unsigned int flags
,
2934 struct gc_arena
*gc
)
2938 char ifname
[IF_NAMESIZE
] = "[undef]";
2939 struct buffer out
= alloc_buf_gc(128, gc
);
2940 buf_printf(&out
, "%s", print_sockaddr_ex(&act
->dest
.addr
.sa
, separator
, flags
, gc
));
2941 #if ENABLE_IP_PKTINFO
2942 if ((flags
& PS_SHOW_PKTINFO
) && addr_defined_ipi(act
))
2944 switch (act
->dest
.addr
.sa
.sa_family
)
2948 struct openvpn_sockaddr sa
;
2950 sa
.addr
.in4
.sin_family
= AF_INET
;
2951 #if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST)
2952 sa
.addr
.in4
.sin_addr
= act
->pi
.in4
.ipi_spec_dst
;
2953 if_indextoname(act
->pi
.in4
.ipi_ifindex
, ifname
);
2954 #elif defined(IP_RECVDSTADDR)
2955 sa
.addr
.in4
.sin_addr
= act
->pi
.in4
;
2957 #else /* if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST) */
2958 #error ENABLE_IP_PKTINFO is set without IP_PKTINFO xor IP_RECVDSTADDR (fix syshead.h)
2960 buf_printf(&out
, " (via %s%%%s)",
2961 print_sockaddr_ex(&sa
.addr
.sa
, separator
, 0, gc
),
2968 struct sockaddr_in6 sin6
;
2969 char buf
[INET6_ADDRSTRLEN
] = "[undef]";
2971 sin6
.sin6_family
= AF_INET6
;
2972 sin6
.sin6_addr
= act
->pi
.in6
.ipi6_addr
;
2973 if_indextoname(act
->pi
.in6
.ipi6_ifindex
, ifname
);
2974 if (getnameinfo((struct sockaddr
*)&sin6
, sizeof(struct sockaddr_in6
),
2975 buf
, sizeof(buf
), NULL
, 0, NI_NUMERICHOST
) == 0)
2977 buf_printf(&out
, " (via %s%%%s)", buf
, ifname
);
2981 buf_printf(&out
, " (via [getnameinfo() err]%%%s)", ifname
);
2987 #endif /* if ENABLE_IP_PKTINFO */
2997 * Convert an in_addr_t in host byte order
2998 * to an ascii dotted quad.
3001 print_in_addr_t(in_addr_t addr
, unsigned int flags
, struct gc_arena
*gc
)
3004 struct buffer out
= alloc_buf_gc(64, gc
);
3006 if (addr
|| !(flags
& IA_EMPTY_IF_UNDEF
))
3009 ia
.s_addr
= (flags
& IA_NET_ORDER
) ? addr
: htonl(addr
);
3011 buf_printf(&out
, "%s", inet_ntoa(ia
));
3017 * Convert an in6_addr in host byte order
3018 * to an ascii representation of an IPv6 address
3021 print_in6_addr(struct in6_addr a6
, unsigned int flags
, struct gc_arena
*gc
)
3023 struct buffer out
= alloc_buf_gc(64, gc
);
3024 char tmp_out_buf
[64]; /* inet_ntop wants pointer to buffer */
3026 if (memcmp(&a6
, &in6addr_any
, sizeof(a6
)) != 0
3027 || !(flags
& IA_EMPTY_IF_UNDEF
))
3029 inet_ntop(AF_INET6
, &a6
, tmp_out_buf
, sizeof(tmp_out_buf
)-1);
3030 buf_printf(&out
, "%s", tmp_out_buf
);
3036 #define UINT8_MAX 0xff
3039 /* add some offset to an ipv6 address
3040 * (add in steps of 8 bits, taking overflow into next round)
3043 add_in6_addr( struct in6_addr base
, uint32_t add
)
3047 for (i
= 15; i
>=0 && add
> 0; i
--)
3050 register uint32_t h
;
3052 h
= (unsigned char) base
.s6_addr
[i
];
3053 base
.s6_addr
[i
] = (h
+add
) & UINT8_MAX
;
3055 /* using explicit carry for the 8-bit additions will catch
3056 * 8-bit and(!) 32-bit overruns nicely
3058 carry
= ((h
& 0xff) + (add
& 0xff)) >> 8;
3059 add
= (add
>>8) + carry
;
3064 /* set environmental variables for ip/port in *addr */
3066 setenv_sockaddr(struct env_set
*es
, const char *name_prefix
, const struct openvpn_sockaddr
*addr
, const unsigned int flags
)
3071 switch (addr
->addr
.sa
.sa_family
)
3074 if (flags
& SA_IP_PORT
)
3076 openvpn_snprintf(name_buf
, sizeof(name_buf
), "%s_ip", name_prefix
);
3080 openvpn_snprintf(name_buf
, sizeof(name_buf
), "%s", name_prefix
);
3083 setenv_str(es
, name_buf
, inet_ntoa(addr
->addr
.in4
.sin_addr
));
3085 if ((flags
& SA_IP_PORT
) && addr
->addr
.in4
.sin_port
)
3087 openvpn_snprintf(name_buf
, sizeof(name_buf
), "%s_port", name_prefix
);
3088 setenv_int(es
, name_buf
, ntohs(addr
->addr
.in4
.sin_port
));
3093 if (IN6_IS_ADDR_V4MAPPED( &addr
->addr
.in6
.sin6_addr
))
3096 memcpy(&ia
.s_addr
, &addr
->addr
.in6
.sin6_addr
.s6_addr
[12],
3098 openvpn_snprintf(name_buf
, sizeof(name_buf
), "%s_ip", name_prefix
);
3099 openvpn_snprintf(buf
, sizeof(buf
), "%s", inet_ntoa(ia
) );
3103 openvpn_snprintf(name_buf
, sizeof(name_buf
), "%s_ip6", name_prefix
);
3104 getnameinfo(&addr
->addr
.sa
, sizeof(struct sockaddr_in6
),
3105 buf
, sizeof(buf
), NULL
, 0, NI_NUMERICHOST
);
3107 setenv_str(es
, name_buf
, buf
);
3109 if ((flags
& SA_IP_PORT
) && addr
->addr
.in6
.sin6_port
)
3111 openvpn_snprintf(name_buf
, sizeof(name_buf
), "%s_port", name_prefix
);
3112 setenv_int(es
, name_buf
, ntohs(addr
->addr
.in6
.sin6_port
));
3119 setenv_in_addr_t(struct env_set
*es
, const char *name_prefix
, in_addr_t addr
, const unsigned int flags
)
3121 if (addr
|| !(flags
& SA_SET_IF_NONZERO
))
3123 struct openvpn_sockaddr si
;
3125 si
.addr
.in4
.sin_family
= AF_INET
;
3126 si
.addr
.in4
.sin_addr
.s_addr
= htonl(addr
);
3127 setenv_sockaddr(es
, name_prefix
, &si
, flags
);
3132 setenv_in6_addr(struct env_set
*es
,
3133 const char *name_prefix
,
3134 const struct in6_addr
*addr
,
3135 const unsigned int flags
)
3137 if (!IN6_IS_ADDR_UNSPECIFIED(addr
) || !(flags
& SA_SET_IF_NONZERO
))
3139 struct openvpn_sockaddr si
;
3141 si
.addr
.in6
.sin6_family
= AF_INET6
;
3142 si
.addr
.in6
.sin6_addr
= *addr
;
3143 setenv_sockaddr(es
, name_prefix
, &si
, flags
);
3148 setenv_link_socket_actual(struct env_set
*es
,
3149 const char *name_prefix
,
3150 const struct link_socket_actual
*act
,
3151 const unsigned int flags
)
3153 setenv_sockaddr(es
, name_prefix
, &act
->dest
, flags
);
3157 * Convert protocol names between index and ascii form.
3160 struct proto_names
{
3161 const char *short_form
;
3162 const char *display_form
;
3163 sa_family_t proto_af
;
3167 /* Indexed by PROTO_x */
3168 static const struct proto_names proto_names
[] = {
3169 {"proto-uninitialized", "proto-NONE", AF_UNSPEC
, PROTO_NONE
},
3170 /* try IPv4 and IPv6 (client), bind dual-stack (server) */
3171 {"udp", "UDP", AF_UNSPEC
, PROTO_UDP
},
3172 {"tcp-server", "TCP_SERVER", AF_UNSPEC
, PROTO_TCP_SERVER
},
3173 {"tcp-client", "TCP_CLIENT", AF_UNSPEC
, PROTO_TCP_CLIENT
},
3174 {"tcp", "TCP", AF_UNSPEC
, PROTO_TCP
},
3176 {"udp4", "UDPv4", AF_INET
, PROTO_UDP
},
3177 {"tcp4-server", "TCPv4_SERVER", AF_INET
, PROTO_TCP_SERVER
},
3178 {"tcp4-client", "TCPv4_CLIENT", AF_INET
, PROTO_TCP_CLIENT
},
3179 {"tcp4", "TCPv4", AF_INET
, PROTO_TCP
},
3181 {"udp6", "UDPv6", AF_INET6
, PROTO_UDP
},
3182 {"tcp6-server", "TCPv6_SERVER", AF_INET6
, PROTO_TCP_SERVER
},
3183 {"tcp6-client", "TCPv6_CLIENT", AF_INET6
, PROTO_TCP_CLIENT
},
3184 {"tcp6", "TCPv6", AF_INET6
, PROTO_TCP
},
3188 proto_is_net(int proto
)
3190 if (proto
< 0 || proto
>= PROTO_N
)
3194 return proto
!= PROTO_NONE
;
3198 proto_is_dgram(int proto
)
3200 return proto_is_udp(proto
);
3204 proto_is_udp(int proto
)
3206 if (proto
< 0 || proto
>= PROTO_N
)
3210 return proto
== PROTO_UDP
;
3214 proto_is_tcp(int proto
)
3216 if (proto
< 0 || proto
>= PROTO_N
)
3220 return proto
== PROTO_TCP_CLIENT
|| proto
== PROTO_TCP_SERVER
;
3224 ascii2proto(const char *proto_name
)
3227 for (i
= 0; i
< SIZE(proto_names
); ++i
)
3229 if (!strcmp(proto_name
, proto_names
[i
].short_form
))
3231 return proto_names
[i
].proto
;
3238 ascii2af(const char *proto_name
)
3241 for (i
= 0; i
< SIZE(proto_names
); ++i
)
3243 if (!strcmp(proto_name
, proto_names
[i
].short_form
))
3245 return proto_names
[i
].proto_af
;
3252 proto2ascii(int proto
, sa_family_t af
, bool display_form
)
3255 for (i
= 0; i
< SIZE(proto_names
); ++i
)
3257 if (proto_names
[i
].proto_af
== af
&& proto_names
[i
].proto
== proto
)
3261 return proto_names
[i
].display_form
;
3265 return proto_names
[i
].short_form
;
3270 return "[unknown protocol]";
3274 proto2ascii_all(struct gc_arena
*gc
)
3276 struct buffer out
= alloc_buf_gc(256, gc
);
3279 for (i
= 0; i
< SIZE(proto_names
); ++i
)
3283 buf_printf(&out
, " ");
3285 buf_printf(&out
, "[%s]", proto_names
[i
].short_form
);
3291 addr_family_name(int af
)
3295 case AF_INET
: return "AF_INET";
3297 case AF_INET6
: return "AF_INET6";
3303 * Given a local proto, return local proto
3304 * if !remote, or compatible remote proto
3307 * This is used for options compatibility
3310 * IPv6 and IPv4 protocols are comptabile but OpenVPN
3311 * has always sent UDPv4, TCPv4 over the wire. Keep these
3312 * strings for backward compatibility
3315 proto_remote(int proto
, bool remote
)
3317 ASSERT(proto
>= 0 && proto
< PROTO_N
);
3318 if (proto
== PROTO_UDP
)
3323 if ( (remote
&& proto
== PROTO_TCP_CLIENT
)
3324 || (!remote
&& proto
== PROTO_TCP_SERVER
))
3326 return "TCPv4_SERVER";
3328 if ( (remote
&& proto
== PROTO_TCP_SERVER
)
3329 || (!remote
&& proto
== PROTO_TCP_CLIENT
))
3331 return "TCPv4_CLIENT";
3335 return ""; /* Make the compiler happy */
3339 * Bad incoming address lengths that differ from what
3340 * we expect are considered to be fatal errors.
3343 bad_address_length(int actual
, int expected
)
3345 msg(M_FATAL
, "ERROR: received strange incoming packet with an address length of %d -- we only accept address lengths of %d.",
3351 * Socket Read Routines
3355 link_socket_read_tcp(struct link_socket
*sock
,
3360 if (!sock
->stream_buf
.residual_fully_formed
)
3363 len
= socket_finalize(sock
->sd
, &sock
->reads
, buf
, NULL
);
3366 stream_buf_get_next(&sock
->stream_buf
, &frag
);
3367 len
= recv(sock
->sd
, BPTR(&frag
), BLEN(&frag
), MSG_NOSIGNAL
);
3372 sock
->stream_reset
= true;
3376 return buf
->len
= len
;
3380 if (sock
->stream_buf
.residual_fully_formed
3381 || stream_buf_added(&sock
->stream_buf
, len
)) /* packet complete? */
3383 stream_buf_get_final(&sock
->stream_buf
, buf
);
3384 stream_buf_reset(&sock
->stream_buf
);
3389 return buf
->len
= 0; /* no error, but packet is still incomplete */
3395 #if ENABLE_IP_PKTINFO
3397 /* make the buffer large enough to handle ancillary socket data for
3398 * both IPv4 and IPv6 destination addresses, plus padding (see RFC 2292)
3400 #if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST)
3401 #define PKTINFO_BUF_SIZE max_int( CMSG_SPACE(sizeof(struct in6_pktinfo)), \
3402 CMSG_SPACE(sizeof(struct in_pktinfo)) )
3404 #define PKTINFO_BUF_SIZE max_int( CMSG_SPACE(sizeof(struct in6_pktinfo)), \
3405 CMSG_SPACE(sizeof(struct in_addr)) )
3409 link_socket_read_udp_posix_recvmsg(struct link_socket
*sock
,
3411 struct link_socket_actual
*from
)
3414 uint8_t pktinfo_buf
[PKTINFO_BUF_SIZE
];
3416 socklen_t fromlen
= sizeof(from
->dest
.addr
);
3418 iov
.iov_base
= BPTR(buf
);
3419 iov
.iov_len
= buf_forward_capacity_total(buf
);
3420 mesg
.msg_iov
= &iov
;
3421 mesg
.msg_iovlen
= 1;
3422 mesg
.msg_name
= &from
->dest
.addr
;
3423 mesg
.msg_namelen
= fromlen
;
3424 mesg
.msg_control
= pktinfo_buf
;
3425 mesg
.msg_controllen
= sizeof pktinfo_buf
;
3426 buf
->len
= recvmsg(sock
->sd
, &mesg
, 0);
3429 struct cmsghdr
*cmsg
;
3430 fromlen
= mesg
.msg_namelen
;
3431 cmsg
= CMSG_FIRSTHDR(&mesg
);
3433 && CMSG_NXTHDR(&mesg
, cmsg
) == NULL
3434 #if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST)
3435 && cmsg
->cmsg_level
== SOL_IP
3436 && cmsg
->cmsg_type
== IP_PKTINFO
3437 && cmsg
->cmsg_len
>= CMSG_LEN(sizeof(struct in_pktinfo
)) )
3438 #elif defined(IP_RECVDSTADDR)
3439 && cmsg
->cmsg_level
== IPPROTO_IP
3440 && cmsg
->cmsg_type
== IP_RECVDSTADDR
3441 && cmsg
->cmsg_len
>= CMSG_LEN(sizeof(struct in_addr
)) )
3442 #else /* if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST) */
3443 #error ENABLE_IP_PKTINFO is set without IP_PKTINFO xor IP_RECVDSTADDR (fix syshead.h)
3446 #if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST)
3447 struct in_pktinfo
*pkti
= (struct in_pktinfo
*) CMSG_DATA(cmsg
);
3448 from
->pi
.in4
.ipi_ifindex
= pkti
->ipi_ifindex
;
3449 from
->pi
.in4
.ipi_spec_dst
= pkti
->ipi_spec_dst
;
3450 #elif defined(IP_RECVDSTADDR)
3451 from
->pi
.in4
= *(struct in_addr
*) CMSG_DATA(cmsg
);
3452 #else /* if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST) */
3453 #error ENABLE_IP_PKTINFO is set without IP_PKTINFO xor IP_RECVDSTADDR (fix syshead.h)
3456 else if (cmsg
!= NULL
3457 && CMSG_NXTHDR(&mesg
, cmsg
) == NULL
3458 && cmsg
->cmsg_level
== IPPROTO_IPV6
3459 && cmsg
->cmsg_type
== IPV6_PKTINFO
3460 && cmsg
->cmsg_len
>= CMSG_LEN(sizeof(struct in6_pktinfo
)) )
3462 struct in6_pktinfo
*pkti6
= (struct in6_pktinfo
*) CMSG_DATA(cmsg
);
3463 from
->pi
.in6
.ipi6_ifindex
= pkti6
->ipi6_ifindex
;
3464 from
->pi
.in6
.ipi6_addr
= pkti6
->ipi6_addr
;
3466 else if (cmsg
!= NULL
)
3468 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
);
3474 #endif /* if ENABLE_IP_PKTINFO */
3477 link_socket_read_udp_posix(struct link_socket
*sock
,
3479 struct link_socket_actual
*from
)
3481 socklen_t fromlen
= sizeof(from
->dest
.addr
);
3482 socklen_t expectedlen
= af_addr_size(sock
->info
.af
);
3483 addr_zero_host(&from
->dest
);
3484 #if ENABLE_IP_PKTINFO
3485 /* Both PROTO_UDPv4 and PROTO_UDPv6 */
3486 if (sock
->info
.proto
== PROTO_UDP
&& sock
->sockflags
& SF_USE_IP_PKTINFO
)
3488 fromlen
= link_socket_read_udp_posix_recvmsg(sock
, buf
, from
);
3492 buf
->len
= recvfrom(sock
->sd
, BPTR(buf
), buf_forward_capacity(buf
), 0,
3493 &from
->dest
.addr
.sa
, &fromlen
);
3494 /* FIXME: won't do anything when sock->info.af == AF_UNSPEC */
3495 if (buf
->len
>= 0 && expectedlen
&& fromlen
!= expectedlen
)
3497 bad_address_length(fromlen
, expectedlen
);
3502 #endif /* ifndef _WIN32 */
3505 * Socket Write Routines
3509 link_socket_write_tcp(struct link_socket
*sock
,
3511 struct link_socket_actual
*to
)
3513 packet_size_type len
= BLEN(buf
);
3514 dmsg(D_STREAM_DEBUG
, "STREAM: WRITE %d offset=%d", (int)len
, buf
->offset
);
3515 ASSERT(len
<= sock
->stream_buf
.maxlen
);
3517 ASSERT(buf_write_prepend(buf
, &len
, sizeof(len
)));
3519 return link_socket_write_win32(sock
, buf
, to
);
3521 return link_socket_write_tcp_posix(sock
, buf
, to
);
3525 #if ENABLE_IP_PKTINFO
3528 link_socket_write_udp_posix_sendmsg(struct link_socket
*sock
,
3530 struct link_socket_actual
*to
)
3534 struct cmsghdr
*cmsg
;
3535 uint8_t pktinfo_buf
[PKTINFO_BUF_SIZE
];
3537 iov
.iov_base
= BPTR(buf
);
3538 iov
.iov_len
= BLEN(buf
);
3539 mesg
.msg_iov
= &iov
;
3540 mesg
.msg_iovlen
= 1;
3541 switch (to
->dest
.addr
.sa
.sa_family
)
3545 mesg
.msg_name
= &to
->dest
.addr
.sa
;
3546 mesg
.msg_namelen
= sizeof(struct sockaddr_in
);
3547 mesg
.msg_control
= pktinfo_buf
;
3549 #if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST)
3550 mesg
.msg_controllen
= CMSG_SPACE(sizeof(struct in_pktinfo
));
3551 cmsg
= CMSG_FIRSTHDR(&mesg
);
3552 cmsg
->cmsg_len
= CMSG_LEN(sizeof(struct in_pktinfo
));
3553 cmsg
->cmsg_level
= SOL_IP
;
3554 cmsg
->cmsg_type
= IP_PKTINFO
;
3556 struct in_pktinfo
*pkti
;
3557 pkti
= (struct in_pktinfo
*) CMSG_DATA(cmsg
);
3558 pkti
->ipi_ifindex
= to
->pi
.in4
.ipi_ifindex
;
3559 pkti
->ipi_spec_dst
= to
->pi
.in4
.ipi_spec_dst
;
3560 pkti
->ipi_addr
.s_addr
= 0;
3562 #elif defined(IP_RECVDSTADDR)
3563 ASSERT( CMSG_SPACE(sizeof(struct in_addr
)) <= sizeof(pktinfo_buf
) );
3564 mesg
.msg_controllen
= CMSG_SPACE(sizeof(struct in_addr
));
3565 cmsg
= CMSG_FIRSTHDR(&mesg
);
3566 cmsg
->cmsg_len
= CMSG_LEN(sizeof(struct in_addr
));
3567 cmsg
->cmsg_level
= IPPROTO_IP
;
3568 cmsg
->cmsg_type
= IP_RECVDSTADDR
;
3569 *(struct in_addr
*) CMSG_DATA(cmsg
) = to
->pi
.in4
;
3570 #else /* if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST) */
3571 #error ENABLE_IP_PKTINFO is set without IP_PKTINFO xor IP_RECVDSTADDR (fix syshead.h)
3572 #endif /* if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST) */
3578 struct in6_pktinfo
*pkti6
;
3579 mesg
.msg_name
= &to
->dest
.addr
.sa
;
3580 mesg
.msg_namelen
= sizeof(struct sockaddr_in6
);
3582 ASSERT( CMSG_SPACE(sizeof(struct in6_pktinfo
)) <= sizeof(pktinfo_buf
) );
3583 mesg
.msg_control
= pktinfo_buf
;
3584 mesg
.msg_controllen
= CMSG_SPACE(sizeof(struct in6_pktinfo
));
3586 cmsg
= CMSG_FIRSTHDR(&mesg
);
3587 cmsg
->cmsg_len
= CMSG_LEN(sizeof(struct in6_pktinfo
));
3588 cmsg
->cmsg_level
= IPPROTO_IPV6
;
3589 cmsg
->cmsg_type
= IPV6_PKTINFO
;
3591 pkti6
= (struct in6_pktinfo
*) CMSG_DATA(cmsg
);
3592 pkti6
->ipi6_ifindex
= to
->pi
.in6
.ipi6_ifindex
;
3593 pkti6
->ipi6_addr
= to
->pi
.in6
.ipi6_addr
;
3599 return sendmsg(sock
->sd
, &mesg
, 0);
3602 #endif /* if ENABLE_IP_PKTINFO */
3605 * Win32 overlapped socket I/O functions.
3611 socket_recv_queue(struct link_socket
*sock
, int maxsize
)
3613 if (sock
->reads
.iostate
== IOSTATE_INITIAL
)
3618 /* reset buf to its initial state */
3619 if (proto_is_udp(sock
->info
.proto
))
3621 sock
->reads
.buf
= sock
->reads
.buf_init
;
3623 else if (proto_is_tcp(sock
->info
.proto
))
3625 stream_buf_get_next(&sock
->stream_buf
, &sock
->reads
.buf
);
3632 /* Win32 docs say it's okay to allocate the wsabuf on the stack */
3633 wsabuf
[0].buf
= BPTR(&sock
->reads
.buf
);
3634 wsabuf
[0].len
= maxsize
? maxsize
: BLEN(&sock
->reads
.buf
);
3636 /* check for buffer overflow */
3637 ASSERT(wsabuf
[0].len
<= BLEN(&sock
->reads
.buf
));
3639 /* the overlapped read will signal this event on I/O completion */
3640 ASSERT(ResetEvent(sock
->reads
.overlapped
.hEvent
));
3641 sock
->reads
.flags
= 0;
3643 if (proto_is_udp(sock
->info
.proto
))
3645 sock
->reads
.addr_defined
= true;
3646 sock
->reads
.addrlen
= sizeof(sock
->reads
.addr6
);
3647 status
= WSARecvFrom(
3653 (struct sockaddr
*) &sock
->reads
.addr
,
3654 &sock
->reads
.addrlen
,
3655 &sock
->reads
.overlapped
,
3658 else if (proto_is_tcp(sock
->info
.proto
))
3660 sock
->reads
.addr_defined
= false;
3667 &sock
->reads
.overlapped
,
3676 if (!status
) /* operation completed immediately? */
3678 /* FIXME: won't do anything when sock->info.af == AF_UNSPEC */
3679 int af_len
= af_addr_size(sock
->info
.af
);
3680 if (sock
->reads
.addr_defined
&& af_len
&& sock
->reads
.addrlen
!= af_len
)
3682 bad_address_length(sock
->reads
.addrlen
, af_len
);
3684 sock
->reads
.iostate
= IOSTATE_IMMEDIATE_RETURN
;
3686 /* since we got an immediate return, we must signal the event object ourselves */
3687 ASSERT(SetEvent(sock
->reads
.overlapped
.hEvent
));
3688 sock
->reads
.status
= 0;
3690 dmsg(D_WIN32_IO
, "WIN32 I/O: Socket Receive immediate return [%d,%d]",
3691 (int) wsabuf
[0].len
,
3692 (int) sock
->reads
.size
);
3696 status
= WSAGetLastError();
3697 if (status
== WSA_IO_PENDING
) /* operation queued? */
3699 sock
->reads
.iostate
= IOSTATE_QUEUED
;
3700 sock
->reads
.status
= status
;
3701 dmsg(D_WIN32_IO
, "WIN32 I/O: Socket Receive queued [%d]",
3702 (int) wsabuf
[0].len
);
3704 else /* error occurred */
3706 struct gc_arena gc
= gc_new();
3707 ASSERT(SetEvent(sock
->reads
.overlapped
.hEvent
));
3708 sock
->reads
.iostate
= IOSTATE_IMMEDIATE_RETURN
;
3709 sock
->reads
.status
= status
;
3710 dmsg(D_WIN32_IO
, "WIN32 I/O: Socket Receive error [%d]: %s",
3711 (int) wsabuf
[0].len
,
3712 strerror_win32(status
, &gc
));
3717 return sock
->reads
.iostate
;
3721 socket_send_queue(struct link_socket
*sock
, struct buffer
*buf
, const struct link_socket_actual
*to
)
3723 if (sock
->writes
.iostate
== IOSTATE_INITIAL
)
3728 /* make a private copy of buf */
3729 sock
->writes
.buf
= sock
->writes
.buf_init
;
3730 sock
->writes
.buf
.len
= 0;
3731 ASSERT(buf_copy(&sock
->writes
.buf
, buf
));
3733 /* Win32 docs say it's okay to allocate the wsabuf on the stack */
3734 wsabuf
[0].buf
= BPTR(&sock
->writes
.buf
);
3735 wsabuf
[0].len
= BLEN(&sock
->writes
.buf
);
3737 /* the overlapped write will signal this event on I/O completion */
3738 ASSERT(ResetEvent(sock
->writes
.overlapped
.hEvent
));
3739 sock
->writes
.flags
= 0;
3741 if (proto_is_udp(sock
->info
.proto
))
3743 /* set destination address for UDP writes */
3744 sock
->writes
.addr_defined
= true;
3745 if (to
->dest
.addr
.sa
.sa_family
== AF_INET6
)
3747 sock
->writes
.addr6
= to
->dest
.addr
.in6
;
3748 sock
->writes
.addrlen
= sizeof(sock
->writes
.addr6
);
3752 sock
->writes
.addr
= to
->dest
.addr
.in4
;
3753 sock
->writes
.addrlen
= sizeof(sock
->writes
.addr
);
3762 (struct sockaddr
*) &sock
->writes
.addr
,
3763 sock
->writes
.addrlen
,
3764 &sock
->writes
.overlapped
,
3767 else if (proto_is_tcp(sock
->info
.proto
))
3769 /* destination address for TCP writes was established on connection initiation */
3770 sock
->writes
.addr_defined
= false;
3778 &sock
->writes
.overlapped
,
3787 if (!status
) /* operation completed immediately? */
3789 sock
->writes
.iostate
= IOSTATE_IMMEDIATE_RETURN
;
3791 /* since we got an immediate return, we must signal the event object ourselves */
3792 ASSERT(SetEvent(sock
->writes
.overlapped
.hEvent
));
3794 sock
->writes
.status
= 0;
3796 dmsg(D_WIN32_IO
, "WIN32 I/O: Socket Send immediate return [%d,%d]",
3797 (int) wsabuf
[0].len
,
3798 (int) sock
->writes
.size
);
3802 status
= WSAGetLastError();
3803 if (status
== WSA_IO_PENDING
) /* operation queued? */
3805 sock
->writes
.iostate
= IOSTATE_QUEUED
;
3806 sock
->writes
.status
= status
;
3807 dmsg(D_WIN32_IO
, "WIN32 I/O: Socket Send queued [%d]",
3808 (int) wsabuf
[0].len
);
3810 else /* error occurred */
3812 struct gc_arena gc
= gc_new();
3813 ASSERT(SetEvent(sock
->writes
.overlapped
.hEvent
));
3814 sock
->writes
.iostate
= IOSTATE_IMMEDIATE_RETURN
;
3815 sock
->writes
.status
= status
;
3817 dmsg(D_WIN32_IO
, "WIN32 I/O: Socket Send error [%d]: %s",
3818 (int) wsabuf
[0].len
,
3819 strerror_win32(status
, &gc
));
3825 return sock
->writes
.iostate
;
3829 socket_finalize(SOCKET s
,
3830 struct overlapped_io
*io
,
3832 struct link_socket_actual
*from
)
3837 switch (io
->iostate
)
3839 case IOSTATE_QUEUED
:
3840 status
= WSAGetOverlappedResult(
3849 /* successful return for a queued operation */
3855 io
->iostate
= IOSTATE_INITIAL
;
3856 ASSERT(ResetEvent(io
->overlapped
.hEvent
));
3858 dmsg(D_WIN32_IO
, "WIN32 I/O: Socket Completion success [%d]", ret
);
3862 /* error during a queued operation */
3864 if (WSAGetLastError() != WSA_IO_INCOMPLETE
)
3866 /* if no error (i.e. just not finished yet), then DON'T execute this code */
3867 io
->iostate
= IOSTATE_INITIAL
;
3868 ASSERT(ResetEvent(io
->overlapped
.hEvent
));
3869 msg(D_WIN32_IO
| M_ERRNO
, "WIN32 I/O: Socket Completion error");
3874 case IOSTATE_IMMEDIATE_RETURN
:
3875 io
->iostate
= IOSTATE_INITIAL
;
3876 ASSERT(ResetEvent(io
->overlapped
.hEvent
));
3879 /* error return for a non-queued operation */
3880 WSASetLastError(io
->status
);
3882 msg(D_WIN32_IO
| M_ERRNO
, "WIN32 I/O: Socket Completion non-queued error");
3886 /* successful return for a non-queued operation */
3892 dmsg(D_WIN32_IO
, "WIN32 I/O: Socket Completion non-queued success [%d]", ret
);
3896 case IOSTATE_INITIAL
: /* were we called without proper queueing? */
3897 WSASetLastError(WSAEINVAL
);
3899 dmsg(D_WIN32_IO
, "WIN32 I/O: Socket Completion BAD STATE");
3906 /* return from address if requested */
3909 if (ret
>= 0 && io
->addr_defined
)
3911 /* TODO(jjo): streamline this mess */
3912 /* in this func we don't have relevant info about the PF_ of this
3913 * endpoint, as link_socket_actual will be zero for the 1st received packet
3915 * Test for inets PF_ possible sizes
3917 switch (io
->addrlen
)
3919 case sizeof(struct sockaddr_in
):
3920 case sizeof(struct sockaddr_in6
):
3921 /* TODO(jjo): for some reason (?) I'm getting 24,28 for AF_INET6
3923 case sizeof(struct sockaddr_in6
)-4:
3927 bad_address_length(io
->addrlen
, af_addr_size(io
->addr
.sin_family
));
3930 switch (io
->addr
.sin_family
)
3933 from
->dest
.addr
.in4
= io
->addr
;
3937 from
->dest
.addr
.in6
= io
->addr6
;
3943 CLEAR(from
->dest
.addr
);
3957 * Socket event notification
3961 socket_set(struct link_socket
*s
,
3962 struct event_set
*es
,
3963 unsigned int rwflags
,
3965 unsigned int *persistent
)
3969 if ((rwflags
& EVENT_READ
) && !stream_buf_read_setup(s
))
3971 ASSERT(!persistent
);
3972 rwflags
&= ~EVENT_READ
;
3976 if (rwflags
& EVENT_READ
)
3978 socket_recv_queue(s
, 0);
3982 /* if persistent is defined, call event_ctl only if rwflags has changed since last call */
3983 if (!persistent
|| *persistent
!= rwflags
)
3985 event_ctl(es
, socket_event_handle(s
), rwflags
, arg
);
3988 *persistent
= rwflags
;
3992 s
->rwflags_debug
= rwflags
;
3998 sd_close(socket_descriptor_t
*sd
)
4000 if (sd
&& socket_defined(*sd
))
4002 openvpn_close_socket(*sd
);
4003 *sd
= SOCKET_UNDEFINED
;
4007 #if UNIX_SOCK_SUPPORT
4010 * code for unix domain sockets
4014 sockaddr_unix_name(const struct sockaddr_un
*local
, const char *null
)
4016 if (local
&& local
->sun_family
== PF_UNIX
)
4018 return local
->sun_path
;
4027 create_socket_unix(void)
4029 socket_descriptor_t sd
;
4031 if ((sd
= socket(PF_UNIX
, SOCK_STREAM
, 0)) < 0)
4033 msg(M_ERR
, "Cannot create unix domain socket");
4036 /* set socket file descriptor to not pass across execs, so that
4037 * scripts don't have access to it */
4044 socket_bind_unix(socket_descriptor_t sd
,
4045 struct sockaddr_un
*local
,
4048 struct gc_arena gc
= gc_new();
4051 const mode_t orig_umask
= umask(0);
4054 if (bind(sd
, (struct sockaddr
*) local
, sizeof(struct sockaddr_un
)))
4056 msg(M_FATAL
| M_ERRNO
,
4057 "%s: Socket bind[%d] failed on unix domain socket %s",
4060 sockaddr_unix_name(local
, "NULL"));
4071 socket_accept_unix(socket_descriptor_t sd
,
4072 struct sockaddr_un
*remote
)
4074 socklen_t remote_len
= sizeof(struct sockaddr_un
);
4075 socket_descriptor_t ret
;
4078 ret
= accept(sd
, (struct sockaddr
*) remote
, &remote_len
);
4081 /* set socket file descriptor to not pass across execs, so that
4082 * scripts don't have access to it */
4089 socket_connect_unix(socket_descriptor_t sd
,
4090 struct sockaddr_un
*remote
)
4092 int status
= connect(sd
, (struct sockaddr
*) remote
, sizeof(struct sockaddr_un
));
4095 status
= openvpn_errno();
4101 sockaddr_unix_init(struct sockaddr_un
*local
, const char *path
)
4103 local
->sun_family
= PF_UNIX
;
4104 strncpynt(local
->sun_path
, path
, sizeof(local
->sun_path
));
4108 socket_delete_unix(const struct sockaddr_un
*local
)
4110 const char *name
= sockaddr_unix_name(local
, NULL
);
4112 if (name
&& strlen(name
))
4120 unix_socket_get_peer_uid_gid(const socket_descriptor_t sd
, int *uid
, int *gid
)
4122 #ifdef HAVE_GETPEEREID
4125 if (getpeereid(sd
, &u
, &g
) == -1)
4138 #elif defined(SO_PEERCRED)
4139 struct ucred peercred
;
4140 socklen_t so_len
= sizeof(peercred
);
4141 if (getsockopt(sd
, SOL_SOCKET
, SO_PEERCRED
, &peercred
, &so_len
) == -1)
4147 *uid
= peercred
.uid
;
4151 *gid
= peercred
.gid
;
4154 #else /* ifdef HAVE_GETPEEREID */
4156 #endif /* ifdef HAVE_GETPEEREID */
4159 #endif /* if UNIX_SOCK_SUPPORT */