Skip to contentSkip to conversation

Add DNS SRV remote host discovery support

PATCH Superseded Vladislav Grishenko 6 participants 41 messages Sep 14, 2020 – Jan 31, 2023 1 message not in the archive

lore
Share & tools
lore

A message that is not in the archive (sent off-list or not yet received): 02ba01d686b31a11ef0yandex-team.ru

#1 lore raw

PATCH v3 1/1 Add DNS SRV remote host discovery support

DNS SRV host discovery allows to have multiple OpenVPN servers for a single domain w/o explicit profile enumeration, to move services from host to host with little fuss, and to designate hosts as primary servers for a service and others as backups.
Feature has been asked several times already, useful in case of huge ammount of clients & servers deployed.

Patch introduces "--remote-srv domain [service] [proto]" option, which enables DNS SRV discovery and optionally allows to change default "openvpn" service and default "auto" protocol to the specified values. Client will try to resolve "_service._proto.domain" name via DNS and use returned DNS SRV records as OpenVPN remote server list ordered by server selection mechanism defined in RFC 2782:

A client MUST attempt to contact the target host with the lowest-numbered priority field value it can reach, target hosts with the same priority SHOULD be tried in an order defined by the weight field.
The weight field specifies a relative weight for entries with the same priority. Larger weights SHOULD be given a proportionately higher probability of being selected.
Domain administrators SHOULD use Weight 0 when there isn't any server selection to do. In the presence of records containing weights greater than 0, records with weight 0 SHOULD have a very small chance of being selected.

Example: instead of multiple remotes in order:
remote s1.example.net 1194 udp
remote s2.example.net 1194 udp
remote s3.example.net 1194 udp
remote s4.example.net 1194 tcp

now it's possible to specify just one remote-srv:
remote-srv example.net

and configure following DNS SRV records:

name prio weight port host
_openvpn._udp.example.net IN SRV 10 60 1194 s1.example.net
_openvpn._udp.example.net IN SRV 10 40 1194 s2.example.net
_openvpn._udp.example.net IN SRV 10 0 1194 s3.example.net
_openvpn._tcp.example.net IN SRV 20 0 443 s4.example.net

Client will first try to resolve "_openvpn._udp.example.net" and "_openvpn._tcp.example.net" names.
Next, "s1.example.net", "s2.example.net" and "s3.example.net" will be ordered before "s4.example.net" as their priority 10 is smaller than 20. Next, "s1.example.net", "s2.example.net" and "s3.example.net" will be randomly ordered with weight probability - first will be either "s1.example.net" with probability 60% or "s2.example.net" with 40% or "s3.example.net" with almost zero probability.
Next, if "s1.example.net" is picked as first, second server will be either "s2.example.net" with almost 100% probability or "s3.example.net" instead. Next, if "s2.example.net" is picked as second, "s3.example.net" will be skipped due zero weight.
"s4.example.net" will be the last one as the only server with priority 20. Finally, servers will be resolved and accessed in this order.

If "_openvpn._udp.example.net" and "_openvpn._udp.example.net" can't be resolved or no valid records were returned, client will move on to the next connection entry.

Tested on Linux & Windows 10.

v2: use DNS SRV for feature naming
change option name to --remote-service-discovery
add --remote-service-discovery [service] optional parameter support rewrite man, add algo/prio/weight description and examples
fix random weight selection was not implicit
remove pulled REMOTE_DISCOVERY support, not needed
split windows/unix-specific parts into extra functions
rename functions into servinfo scope, add doxygen comments when appropriate remove addrinfo hack, use servinfo containers of addrinfo list instead better proxy support (tcp mode not supported so far)
log discovery attempts and results, if enabled

v3: complete logic rewrite
use separate --remote-srv [service] [proto] option
remove fallback, same is achieved with additiona --remote/--remote-srv add "auto" protocol support to allow both udp & tcp hosts be discovered add support for tcp / http proxy (natively)
man update

---
 configure.ac                        |   2 +-
 doc/man-sections/client-options.rst |  88 ++-
 doc/management-notes.txt            |   6 +
 src/openvpn/Makefile.am             |   2 +-
 src/openvpn/buffer.h                |   5 -
 src/openvpn/errlevel.h              |   1 +
 src/openvpn/init.c                  |  57 +-
 src/openvpn/openvpn.vcxproj         |   8 +-
 src/openvpn/options.c               | 238 ++++++--
 src/openvpn/options.h               |   4 +
 src/openvpn/socket.c                | 836 +++++++++++++++++++++++++++-
 src/openvpn/socket.h                |  56 +-
 src/openvpn/syshead.h               |   5 +
 13 files changed, 1231 insertions(+), 77 deletions(-)
configure.ac +1 -1
index f8279924..67251bed 100644
@@ -477,7 +477,7 @@ SOCKET_INCLUDES="
 "
 
 AC_CHECK_HEADERS(
-	[net/if.h netinet/ip.h resolv.h sys/un.h net/if_utun.h sys/kern_control.h],
+	[net/if.h netinet/ip.h arpa/nameser.h resolv.h sys/un.h net/if_utun.h sys/kern_control.h],
 	,
 	,
 	[[${SOCKET_INCLUDES}]]
doc/man-sections/client-options.rst +83 -5

101 lines not on this page · raw message

doc/management-notes.txt +6 -0
index 61daaf07..d06a4782 100644
@@ -851,6 +851,12 @@ the above notification, use this command:
 
   remote MOD vpn.otherexample.com 1234
 
+DNS SRV discovery domain and service name with protocol code:`auto`
+can't be overriden, but either acceted or skipped only.
+Example of such notification:
+
+  >REMOTE:example.com,openvpn,auto
+
 To accept the same host and port as the client would ordinarily
 have connected to, use this command:
 
src/openvpn/Makefile.am +1 -1
index 37b002c6..f7632047 100644
@@ -143,5 +143,5 @@ openvpn_LDADD = \
 	$(OPTIONAL_INOTIFY_LIBS)
 if WIN32
 openvpn_SOURCES += openvpn_win32_resources.rc block_dns.c block_dns.h ring_buffer.h
-openvpn_LDADD += -lgdi32 -lws2_32 -lwininet -lcrypt32 -liphlpapi -lwinmm -lfwpuclnt -lrpcrt4 -lncrypt -lsetupapi
+openvpn_LDADD += -lgdi32 -lws2_32 -lwininet -lcrypt32 -liphlpapi -lwinmm -lfwpuclnt -lrpcrt4 -lncrypt -lsetupapi -ldnsapi
 endif
src/openvpn/buffer.h +0 -5
index 1722ffd5..ae0cf0eb 100644
@@ -198,11 +198,6 @@ bool buf_init_debug(struct buffer *buf, int offset, const char *file, int line);
 
 
 /* inline functions */
-inline static void
-gc_freeaddrinfo_callback(void *addr)
-{
-    freeaddrinfo((struct addrinfo *) addr);
-}
 
 /** Return an empty struct buffer */
 static inline struct buffer
src/openvpn/errlevel.h +1 -0
index e448fc37..c77dc76c 100644
@@ -91,6 +91,7 @@
 #define D_OSBUF              LOGLEV(3, 43, 0)        /* show socket/tun/tap buffer sizes */
 #define D_PS_PROXY           LOGLEV(3, 44, 0)        /* messages related to --port-share option */
 #define D_PF_INFO            LOGLEV(3, 45, 0)        /* packet filter informational messages */
+#define D_RESOLVE_INFO       LOGLEV(3, 46, 0)        /* show hostname resolve info */
 
 #define D_SHOW_PARMS         LOGLEV(4, 50, 0)        /* show all parameters on program initiation */
 #define D_SHOW_OCC           LOGLEV(4, 51, 0)        /* show options compatibility string */
src/openvpn/init.c +54 -3

105 lines not on this page · raw message

src/openvpn/openvpn.vcxproj +4 -4
index 5367979d..996c0160 100644
@@ -92,7 +92,7 @@
     </ClCompile>
     <ResourceCompile />
     <Link>
-      <AdditionalDependencies>legacy_stdio_definitions.lib;Ncrypt.lib;libssl.lib;libcrypto.lib;lzo2.lib;pkcs11-helper.dll.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;%(AdditionalDependencies)</AdditionalDependencies>
+      <AdditionalDependencies>legacy_stdio_definitions.lib;Ncrypt.lib;libssl.lib;libcrypto.lib;lzo2.lib;pkcs11-helper.dll.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;dnsapi.lib;%(AdditionalDependencies)</AdditionalDependencies>
       <AdditionalLibraryDirectories>$(OPENSSL_HOME)/lib;$(LZO_HOME)/lib;$(PKCS11H_HOME)/lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
       <SubSystem>Console</SubSystem>
     </Link>
@@ -107,7 +107,7 @@
     </ClCompile>
     <ResourceCompile />
     <Link>
-      <AdditionalDependencies>legacy_stdio_definitions.lib;Ncrypt.lib;libssl.lib;libcrypto.lib;lzo2.lib;pkcs11-helper.dll.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;%(AdditionalDependencies)</AdditionalDependencies>
+      <AdditionalDependencies>legacy_stdio_definitions.lib;Ncrypt.lib;libssl.lib;libcrypto.lib;lzo2.lib;pkcs11-helper.dll.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;dnsapi.lib;%(AdditionalDependencies)</AdditionalDependencies>
       <AdditionalLibraryDirectories>$(OPENSSL_HOME)/lib;$(LZO_HOME)/lib;$(PKCS11H_HOME)/lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
       <SubSystem>Console</SubSystem>
     </Link>
@@ -122,7 +122,7 @@
     </ClCompile>
     <ResourceCompile />
     <Link>
-      <AdditionalDependencies>legacy_stdio_definitions.lib;Ncrypt.lib;libssl.lib;libcrypto.lib;lzo2.lib;pkcs11-helper.dll.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;%(AdditionalDependencies)</AdditionalDependencies>
+      <AdditionalDependencies>legacy_stdio_definitions.lib;Ncrypt.lib;libssl.lib;libcrypto.lib;lzo2.lib;pkcs11-helper.dll.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;dnsapi.lib;%(AdditionalDependencies)</AdditionalDependencies>
       <AdditionalLibraryDirectories>$(OPENSSL_HOME)/lib;$(LZO_HOME)/lib;$(PKCS11H_HOME)/lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
       <SubSystem>Console</SubSystem>
     </Link>
@@ -137,7 +137,7 @@
     </ClCompile>
     <ResourceCompile />
     <Link>
-      <AdditionalDependencies>legacy_stdio_definitions.lib;Ncrypt.lib;libssl.lib;libcrypto.lib;lzo2.lib;pkcs11-helper.dll.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;%(AdditionalDependencies)</AdditionalDependencies>
+      <AdditionalDependencies>legacy_stdio_definitions.lib;Ncrypt.lib;libssl.lib;libcrypto.lib;lzo2.lib;pkcs11-helper.dll.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;dnsapi.lib;%(AdditionalDependencies)</AdditionalDependencies>
       <AdditionalLibraryDirectories>$(OPENSSL_HOME)/lib;$(LZO_HOME)/lib;$(PKCS11H_HOME)/lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
       <SubSystem>Console</SubSystem>
     </Link>
src/openvpn/options.c +196 -42

347 lines not on this page · raw message

src/openvpn/options.h +4 -0
index 877e9396..cf22ffea 100644
@@ -92,6 +92,7 @@ struct connection_entry
     const char *remote_port;
     const char *local;
     const char *remote;
+    bool remote_srv;
     bool remote_float;
     bool bind_defined;
     bool bind_ipv6_only;
@@ -152,6 +153,7 @@ struct remote_entry
     const char *remote_port;
     int proto;
     sa_family_t af;
+    bool remote_srv;
 };
 
 #define CONNECTION_LIST_SIZE 64
@@ -787,6 +789,8 @@ char *options_string_extract_option(const char *options_string,
 
 void options_postprocess(struct options *options);
 
+bool options_mutate_ce_servinfo(struct options *o, struct servinfo *si);
+
 void pre_pull_save(struct options *o);
 
 void pre_pull_restore(struct options *o, struct gc_arena *gc);
src/openvpn/socket.c +821 -15

952 lines not on this page · raw message

src/openvpn/socket.h +55 -1

112 lines not on this page · raw message

src/openvpn/syshead.h +5 -0
index 8342eae0..e5852753 100644
@@ -38,6 +38,7 @@
 
 #ifdef _WIN32
 #include <windows.h>
+#include <windns.h>
 #include <winsock2.h>
 #include <tlhelp32.h>
 #define sleep(x) Sleep((x)*1000)
@@ -176,6 +177,10 @@
 #include <netinet/in.h>
 #endif
 
+#ifdef HAVE_ARPA_NAMESER_H
+#include <arpa/nameser.h>
+#endif
+
 #ifdef HAVE_RESOLV_H
 #include <resolv.h>
 #endif
Signature · 1 line
2.17.1
#2 lore raw

PATCH v4 1/1 Add DNS SRV remote host discovery support

DNS SRV remote host discovery allows to have multiple OpenVPN servers for a single domain w/o explicit profile enumeration, to move services from host to host with little fuss, and to designate hosts as primary servers for a service and others as backups.
Feature has been asked several times already, useful in case of huge number of clients & servers deployed.

Patch introduces "--remote-srv domain [service] [proto]" option. The "service" and "proto" arguments are optional. Client will try to resolve DNS SRV record "_service._proto.domain" and use returned DNS SRV records as remote server list ordered by server selection mechanism defined in RFC2782 (https://tools.ietf.org/html/rfc2782):

A client MUST attempt to contact the target host with the lowest-numbered priority field value it can reach, target hosts with the same priority SHOULD be tried in an order defined by the weight field.
The weight field specifies a relative weight for entries with the same priority. Larger weights SHOULD be given a proportionately higher probability of being selected.
Domain administrators SHOULD use Weight 0 when there isn't any server selection to do. In the presence of records containing weights greater than 0, records with Weight 0 SHOULD have a very small chance of being selected.

Note: OpenVPN server selection mechanism implementation indeed will give records with weight of zero a very small chance of being selected first, but never skip them.

Example: instead of multiple --remote in order:
remote server1.example.net 1194 udp
remote server2.example.net 1194 udp
remote server3.example.net 1194 udp
remote server4.example.net 443 tcp

now it's possible to specify just one --remote-srv:
remote-srv example.net

and configure following DNS SRV records:
name prio weight port target
_openvpn._udp.example.net IN SRV 10 60 1194 server1.example.net
_openvpn._udp.example.net IN SRV 10 40 1194 server2.example.net
_openvpn._udp.example.net IN SRV 10 0 1194 server3.example.net
_openvpn._tcp.example.net IN SRV 20 0 443 server4.example.net

For "--remote-srv example.net" following will happen in order:
1. The client will first try to resolve "_openvpn._udp.example.net" and "_openvpn._tcp.example.net".
2. Records "server1.example.net:1194", "server2.example.net:1194" and "server3.example.net:1194" will be selected before record "server4.example.net:443" as their priority 10 is smaller than 20.
3. Records "server1.example.net:1194", "server2.example.net:1194" and "server3.example.net:1194" will be randomly selected with weight probability: first will be either "server1.example.net:1194" with 60% probability or "server2.example.net:1194" with 40% or "server3.example.net:1194" with almost zero probability.
4. If "server1.example.net:1194" was selected, the second record will be either "server2.example.net:1194" with almost 100% probability or "server3.example.net:1194" with almost 0%.
5. If "server2.example.net:1194" was selected, the third record will be the only last record of priority 10 - "server3.example.net:1194".
6. Record "server4.example.net:443" will be the last one selected as the only record with priority 20.
7. Each of the resulting "target:port" remote hosts will be resolved and accessed if its protocol has no conflict with the rest of the OpenVPN options.

If DNS SRV name can't be resolved or no valid records were returned, client will move on to the next connection entry.

Tested on Linux/Glibc & Windows 10.

v2: use DNS SRV for feature naming
change option name to --remote-service-discovery
add --remote-service-discovery [service] optional parameter support rewrite man, add algo/prio/weight description and examples
fix random weight selection was not implicit
remove pulled REMOTE_DISCOVERY support, not needed
split windows/unix-specific parts into extra functions
rename functions into servinfo scope, add doxygen comments when appropriate remove addrinfo hack, use servinfo containers of addrinfo list instead better proxy support (tcp mode not supported so far)
log discovery attempts and results, if enabled

v3: complete logic rewrite
use separate --remote-srv [service] [proto] option
remove fallback, same is achieved with additiona --remote/--remote-srv add "auto" protocol support to allow both udp & tcp hosts be discovered add support for tcp / http proxy (natively)
man update

v4: due RFC 2782 ambiguity, prefer to use all resolved DNS SRV records, even
ones with weight 0 after the records containing weights greater than 0 were all selected, keep related code disabled for historical reasons. man update

---
 configure.ac                        |   2 +-
 doc/man-sections/client-options.rst | 117 +++-
 doc/management-notes.txt            |   6 +
 src/openvpn/Makefile.am             |   2 +-
 src/openvpn/buffer.h                |   5 -
 src/openvpn/errlevel.h              |   1 +
 src/openvpn/init.c                  |  57 +-
 src/openvpn/openvpn.vcxproj         |   8 +-
 src/openvpn/options.c               | 238 ++++++--
 src/openvpn/options.h               |   4 +
 src/openvpn/socket.c                | 855 +++++++++++++++++++++++++++-
 src/openvpn/socket.h                |  56 +-
 src/openvpn/syshead.h               |   5 +
 13 files changed, 1279 insertions(+), 77 deletions(-)
configure.ac +1 -1
index f8279924..67251bed 100644
@@ -477,7 +477,7 @@ SOCKET_INCLUDES="
 "
 
 AC_CHECK_HEADERS(
-	[net/if.h netinet/ip.h resolv.h sys/un.h net/if_utun.h sys/kern_control.h],
+	[net/if.h netinet/ip.h arpa/nameser.h resolv.h sys/un.h net/if_utun.h sys/kern_control.h],
 	,
 	,
 	[[${SOCKET_INCLUDES}]]
doc/man-sections/client-options.rst +112 -5

130 lines not on this page · raw message

doc/management-notes.txt +6 -0
index 61daaf07..d06a4782 100644
@@ -851,6 +851,12 @@ the above notification, use this command:
 
   remote MOD vpn.otherexample.com 1234
 
+DNS SRV discovery domain and service name with protocol code:`auto`
+can't be overriden, but either acceted or skipped only.
+Example of such notification:
+
+  >REMOTE:example.com,openvpn,auto
+
 To accept the same host and port as the client would ordinarily
 have connected to, use this command:
 
src/openvpn/Makefile.am +1 -1
index 37b002c6..f7632047 100644
@@ -143,5 +143,5 @@ openvpn_LDADD = \
 	$(OPTIONAL_INOTIFY_LIBS)
 if WIN32
 openvpn_SOURCES += openvpn_win32_resources.rc block_dns.c block_dns.h ring_buffer.h
-openvpn_LDADD += -lgdi32 -lws2_32 -lwininet -lcrypt32 -liphlpapi -lwinmm -lfwpuclnt -lrpcrt4 -lncrypt -lsetupapi
+openvpn_LDADD += -lgdi32 -lws2_32 -lwininet -lcrypt32 -liphlpapi -lwinmm -lfwpuclnt -lrpcrt4 -lncrypt -lsetupapi -ldnsapi
 endif
src/openvpn/buffer.h +0 -5
index 1722ffd5..ae0cf0eb 100644
@@ -198,11 +198,6 @@ bool buf_init_debug(struct buffer *buf, int offset, const char *file, int line);
 
 
 /* inline functions */
-inline static void
-gc_freeaddrinfo_callback(void *addr)
-{
-    freeaddrinfo((struct addrinfo *) addr);
-}
 
 /** Return an empty struct buffer */
 static inline struct buffer
src/openvpn/errlevel.h +1 -0
index e448fc37..c77dc76c 100644
@@ -91,6 +91,7 @@
 #define D_OSBUF              LOGLEV(3, 43, 0)        /* show socket/tun/tap buffer sizes */
 #define D_PS_PROXY           LOGLEV(3, 44, 0)        /* messages related to --port-share option */
 #define D_PF_INFO            LOGLEV(3, 45, 0)        /* packet filter informational messages */
+#define D_RESOLVE_INFO       LOGLEV(3, 46, 0)        /* show hostname resolve info */
 
 #define D_SHOW_PARMS         LOGLEV(4, 50, 0)        /* show all parameters on program initiation */
 #define D_SHOW_OCC           LOGLEV(4, 51, 0)        /* show options compatibility string */
src/openvpn/init.c +54 -3

105 lines not on this page · raw message

src/openvpn/openvpn.vcxproj +4 -4
index 3863854b..1f317fb0 100644
@@ -92,7 +92,7 @@
     </ClCompile>
     <ResourceCompile />
     <Link>
-      <AdditionalDependencies>legacy_stdio_definitions.lib;Ncrypt.lib;libssl.lib;libcrypto.lib;lzo2.lib;pkcs11-helper.dll.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;%(AdditionalDependencies)</AdditionalDependencies>
+      <AdditionalDependencies>legacy_stdio_definitions.lib;Ncrypt.lib;libssl.lib;libcrypto.lib;lzo2.lib;pkcs11-helper.dll.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;dnsapi.lib;%(AdditionalDependencies)</AdditionalDependencies>
       <AdditionalLibraryDirectories>$(OPENSSL_HOME)/lib;$(LZO_HOME)/lib;$(PKCS11H_HOME)/lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
       <SubSystem>Console</SubSystem>
     </Link>
@@ -107,7 +107,7 @@
     </ClCompile>
     <ResourceCompile />
     <Link>
-      <AdditionalDependencies>legacy_stdio_definitions.lib;Ncrypt.lib;libssl.lib;libcrypto.lib;lzo2.lib;pkcs11-helper.dll.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;%(AdditionalDependencies)</AdditionalDependencies>
+      <AdditionalDependencies>legacy_stdio_definitions.lib;Ncrypt.lib;libssl.lib;libcrypto.lib;lzo2.lib;pkcs11-helper.dll.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;dnsapi.lib;%(AdditionalDependencies)</AdditionalDependencies>
       <AdditionalLibraryDirectories>$(OPENSSL_HOME)/lib;$(LZO_HOME)/lib;$(PKCS11H_HOME)/lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
       <SubSystem>Console</SubSystem>
     </Link>
@@ -122,7 +122,7 @@
     </ClCompile>
     <ResourceCompile />
     <Link>
-      <AdditionalDependencies>legacy_stdio_definitions.lib;Ncrypt.lib;libssl.lib;libcrypto.lib;lzo2.lib;pkcs11-helper.dll.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;%(AdditionalDependencies)</AdditionalDependencies>
+      <AdditionalDependencies>legacy_stdio_definitions.lib;Ncrypt.lib;libssl.lib;libcrypto.lib;lzo2.lib;pkcs11-helper.dll.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;dnsapi.lib;%(AdditionalDependencies)</AdditionalDependencies>
       <AdditionalLibraryDirectories>$(OPENSSL_HOME)/lib;$(LZO_HOME)/lib;$(PKCS11H_HOME)/lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
       <SubSystem>Console</SubSystem>
     </Link>
@@ -137,7 +137,7 @@
     </ClCompile>
     <ResourceCompile />
     <Link>
-      <AdditionalDependencies>legacy_stdio_definitions.lib;Ncrypt.lib;libssl.lib;libcrypto.lib;lzo2.lib;pkcs11-helper.dll.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;%(AdditionalDependencies)</AdditionalDependencies>
+      <AdditionalDependencies>legacy_stdio_definitions.lib;Ncrypt.lib;libssl.lib;libcrypto.lib;lzo2.lib;pkcs11-helper.dll.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;dnsapi.lib;%(AdditionalDependencies)</AdditionalDependencies>
       <AdditionalLibraryDirectories>$(OPENSSL_HOME)/lib;$(LZO_HOME)/lib;$(PKCS11H_HOME)/lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
       <SubSystem>Console</SubSystem>
     </Link>
src/openvpn/options.c +196 -42

347 lines not on this page · raw message

src/openvpn/options.h +4 -0
index 877e9396..cf22ffea 100644
@@ -92,6 +92,7 @@ struct connection_entry
     const char *remote_port;
     const char *local;
     const char *remote;
+    bool remote_srv;
     bool remote_float;
     bool bind_defined;
     bool bind_ipv6_only;
@@ -152,6 +153,7 @@ struct remote_entry
     const char *remote_port;
     int proto;
     sa_family_t af;
+    bool remote_srv;
 };
 
 #define CONNECTION_LIST_SIZE 64
@@ -787,6 +789,8 @@ char *options_string_extract_option(const char *options_string,
 
 void options_postprocess(struct options *options);
 
+bool options_mutate_ce_servinfo(struct options *o, struct servinfo *si);
+
 void pre_pull_save(struct options *o);
 
 void pre_pull_restore(struct options *o, struct gc_arena *gc);
src/openvpn/socket.c +840 -15

971 lines not on this page · raw message

src/openvpn/socket.h +55 -1

112 lines not on this page · raw message

src/openvpn/syshead.h +5 -0
index 8342eae0..e5852753 100644
@@ -38,6 +38,7 @@
 
 #ifdef _WIN32
 #include <windows.h>
+#include <windns.h>
 #include <winsock2.h>
 #include <tlhelp32.h>
 #define sleep(x) Sleep((x)*1000)
@@ -176,6 +177,10 @@
 #include <netinet/in.h>
 #endif
 
+#ifdef HAVE_ARPA_NAMESER_H
+#include <arpa/nameser.h>
+#endif
+
 #ifdef HAVE_RESOLV_H
 #include <resolv.h>
 #endif
Signature · 1 line
2.17.1
#3 lore raw

PATCH v5 1/1 Add DNS SRV remote host discovery support

DNS SRV remote host discovery allows to have multiple OpenVPN servers for a single domain w/o explicit profile enumeration, to move services from host to host with little fuss, and to designate hosts as primary servers for a service and others as backups.
Feature has been asked several times already, should be useful in case of substantial number of clients & servers deployed.

Patch introduces "--remote-srv domain [service] [proto]" option. The "service" and "proto" arguments are optional. Client will try to resolve DNS SRV record "_service._proto.domain" and use returned DNS SRV records as remote server list ordered by server selection mechanism defined in RFC2782 (https://tools.ietf.org/html/rfc2782):

A client MUST attempt to contact the target host with the lowest-numbered priority field value it can reach, target hosts with the same priority SHOULD be tried in an order defined by the weight field.
The weight field specifies a relative weight for entries with the same priority. Larger weights SHOULD be given a proportionately higher probability of being selected.
Domain administrators SHOULD use Weight 0 when there isn't any server selection to do. In the presence of records containing weights greater than 0, records with Weight 0 SHOULD have a very small chance of being selected.

Note: OpenVPN server selection mechanism implementation indeed will give records with weight of zero a very small chance of being selected first, but never skip them.

Example: instead of multiple --remote in order:
remote server1.example.net 1194 udp
remote server2.example.net 1194 udp
remote server3.example.net 1194 udp
remote server4.example.net 443 tcp

now it's possible to specify just one --remote-srv:
remote-srv example.net

and configure following DNS SRV records:
name prio weight port target
_openvpn._udp.example.net IN SRV 10 60 1194 server1.example.net
_openvpn._udp.example.net IN SRV 10 40 1194 server2.example.net
_openvpn._udp.example.net IN SRV 10 0 1194 server3.example.net
_openvpn._tcp.example.net IN SRV 20 0 443 server4.example.net

For "--remote-srv example.net" following will happen in order:
1. The client will first try to resolve "_openvpn._udp.example.net" and "_openvpn._tcp.example.net".
2. Records "server1.example.net:1194", "server2.example.net:1194" and "server3.example.net:1194" will be selected before record "server4.example.net:443" as their priority 10 is smaller than 20.
3. Records "server1.example.net:1194", "server2.example.net:1194" and "server3.example.net:1194" will be randomly selected with weight probability: first will be either "server1.example.net:1194" with 60% probability or "server2.example.net:1194" with 40% or "server3.example.net:1194" with almost zero probability.
4. If "server1.example.net:1194" was selected, the second record will be either "server2.example.net:1194" with almost 100% probability or "server3.example.net:1194" with almost 0%.
5. If "server2.example.net:1194" was selected, the third record will be the only last record of priority 10 - "server3.example.net:1194".
6. Record "server4.example.net:443" will be the last one selected as the only record with priority 20.
7. Each of the resulting "target:port" remote hosts will be resolved and accessed if its protocol has no conflict with the rest of the OpenVPN options.

If DNS SRV name can't be resolved or no valid records were returned, client will move on to the next connection entry.

Tested on Linux/Glibc & Windows 10.

v2: use DNS SRV for feature naming
change option name to --remote-service-discovery
add --remote-service-discovery [service] optional parameter support rewrite man, add algo/prio/weight description and examples
fix random weight selection was not implicit
remove pulled REMOTE_DISCOVERY support, not needed
split windows/unix-specific parts into extra functions
rename functions into servinfo scope, add doxygen comments when appropriate remove addrinfo hack, use servinfo containers of addrinfo list instead better proxy support (tcp mode not supported so far)
log discovery attempts and results, if enabled

v3: complete logic rewrite
use separate --remote-srv [service] [proto] option
remove fallback, same is achieved with additiona --remote/--remote-srv add "auto" protocol support to allow both udp & tcp hosts be discovered add support for tcp / http proxy (natively)
man update

v4: due RFC 2782 ambiguity, prefer to use all resolved DNS SRV records, even
ones with weight 0 after the records containing weights greater than 0 were all selected, keep related code disabled for historical reasons. man update

v5: rebase against upstream with connection advancing fix
allow management skip/accept for exact remote service hosts as for --remote improve compability with a way "--persist-remote-ip" is handled ensure max line length is 80

---
 configure.ac                        |   2 +-
 doc/man-sections/client-options.rst | 117 +++-
 doc/management-notes.txt            |   6 +
 src/openvpn/Makefile.am             |   2 +-
 src/openvpn/buffer.h                |   5 -
 src/openvpn/errlevel.h              |   1 +
 src/openvpn/init.c                  |  69 ++-
 src/openvpn/openvpn.vcxproj         |   8 +-
 src/openvpn/options.c               | 252 ++++++--
 src/openvpn/options.h               |   4 +
 src/openvpn/socket.c                | 881 +++++++++++++++++++++++++++-
 src/openvpn/socket.h                |  56 +-
 src/openvpn/syshead.h               |   5 +
 13 files changed, 1324 insertions(+), 84 deletions(-)
configure.ac +1 -1
index ebb32204..22088aaf 100644
@@ -477,7 +477,7 @@ SOCKET_INCLUDES="
 "
 
 AC_CHECK_HEADERS(
-	[net/if.h netinet/ip.h resolv.h sys/un.h net/if_utun.h sys/kern_control.h],
+	[net/if.h netinet/ip.h arpa/nameser.h resolv.h sys/un.h net/if_utun.h sys/kern_control.h],
 	,
 	,
 	[[${SOCKET_INCLUDES}]]
doc/man-sections/client-options.rst +112 -5

130 lines not on this page · raw message

doc/management-notes.txt +6 -0
index 61daaf07..d06a4782 100644
@@ -851,6 +851,12 @@ the above notification, use this command:
 
   remote MOD vpn.otherexample.com 1234
 
+DNS SRV discovery domain and service name with protocol code:`auto`
+can't be overriden, but either acceted or skipped only.
+Example of such notification:
+
+  >REMOTE:example.com,openvpn,auto
+
 To accept the same host and port as the client would ordinarily
 have connected to, use this command:
 
src/openvpn/Makefile.am +1 -1
index 37b002c6..f7632047 100644
@@ -143,5 +143,5 @@ openvpn_LDADD = \
 	$(OPTIONAL_INOTIFY_LIBS)
 if WIN32
 openvpn_SOURCES += openvpn_win32_resources.rc block_dns.c block_dns.h ring_buffer.h
-openvpn_LDADD += -lgdi32 -lws2_32 -lwininet -lcrypt32 -liphlpapi -lwinmm -lfwpuclnt -lrpcrt4 -lncrypt -lsetupapi
+openvpn_LDADD += -lgdi32 -lws2_32 -lwininet -lcrypt32 -liphlpapi -lwinmm -lfwpuclnt -lrpcrt4 -lncrypt -lsetupapi -ldnsapi
 endif
src/openvpn/buffer.h +0 -5
index 1722ffd5..ae0cf0eb 100644
@@ -198,11 +198,6 @@ bool buf_init_debug(struct buffer *buf, int offset, const char *file, int line);
 
 
 /* inline functions */
-inline static void
-gc_freeaddrinfo_callback(void *addr)
-{
-    freeaddrinfo((struct addrinfo *) addr);
-}
 
 /** Return an empty struct buffer */
 static inline struct buffer
src/openvpn/errlevel.h +1 -0
index 5663f841..39f96e7d 100644
@@ -92,6 +92,7 @@
 #define D_PS_PROXY           LOGLEV(3, 44, 0)        /* messages related to --port-share option */
 #define D_PF_INFO            LOGLEV(3, 45, 0)        /* packet filter informational messages */
 #define D_IFCONFIG           LOGLEV(3, 0,  0)        /* show ifconfig info (don't mute) */
+#define D_RESOLVE            LOGLEV(3, 46, 0)        /* show hostname resolve info */
 
 #define D_SHOW_PARMS         LOGLEV(4, 50, 0)        /* show all parameters on program initiation */
 #define D_SHOW_OCC           LOGLEV(4, 51, 0)        /* show options compatibility string */
src/openvpn/init.c +63 -6

129 lines not on this page · raw message

src/openvpn/openvpn.vcxproj +4 -4
index 3863854b..1f317fb0 100644
@@ -92,7 +92,7 @@
     </ClCompile>
     <ResourceCompile />
     <Link>
-      <AdditionalDependencies>legacy_stdio_definitions.lib;Ncrypt.lib;libssl.lib;libcrypto.lib;lzo2.lib;pkcs11-helper.dll.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;%(AdditionalDependencies)</AdditionalDependencies>
+      <AdditionalDependencies>legacy_stdio_definitions.lib;Ncrypt.lib;libssl.lib;libcrypto.lib;lzo2.lib;pkcs11-helper.dll.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;dnsapi.lib;%(AdditionalDependencies)</AdditionalDependencies>
       <AdditionalLibraryDirectories>$(OPENSSL_HOME)/lib;$(LZO_HOME)/lib;$(PKCS11H_HOME)/lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
       <SubSystem>Console</SubSystem>
     </Link>
@@ -107,7 +107,7 @@
     </ClCompile>
     <ResourceCompile />
     <Link>
-      <AdditionalDependencies>legacy_stdio_definitions.lib;Ncrypt.lib;libssl.lib;libcrypto.lib;lzo2.lib;pkcs11-helper.dll.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;%(AdditionalDependencies)</AdditionalDependencies>
+      <AdditionalDependencies>legacy_stdio_definitions.lib;Ncrypt.lib;libssl.lib;libcrypto.lib;lzo2.lib;pkcs11-helper.dll.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;dnsapi.lib;%(AdditionalDependencies)</AdditionalDependencies>
       <AdditionalLibraryDirectories>$(OPENSSL_HOME)/lib;$(LZO_HOME)/lib;$(PKCS11H_HOME)/lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
       <SubSystem>Console</SubSystem>
     </Link>
@@ -122,7 +122,7 @@
     </ClCompile>
     <ResourceCompile />
     <Link>
-      <AdditionalDependencies>legacy_stdio_definitions.lib;Ncrypt.lib;libssl.lib;libcrypto.lib;lzo2.lib;pkcs11-helper.dll.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;%(AdditionalDependencies)</AdditionalDependencies>
+      <AdditionalDependencies>legacy_stdio_definitions.lib;Ncrypt.lib;libssl.lib;libcrypto.lib;lzo2.lib;pkcs11-helper.dll.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;dnsapi.lib;%(AdditionalDependencies)</AdditionalDependencies>
       <AdditionalLibraryDirectories>$(OPENSSL_HOME)/lib;$(LZO_HOME)/lib;$(PKCS11H_HOME)/lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
       <SubSystem>Console</SubSystem>
     </Link>
@@ -137,7 +137,7 @@
     </ClCompile>
     <ResourceCompile />
     <Link>
-      <AdditionalDependencies>legacy_stdio_definitions.lib;Ncrypt.lib;libssl.lib;libcrypto.lib;lzo2.lib;pkcs11-helper.dll.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;%(AdditionalDependencies)</AdditionalDependencies>
+      <AdditionalDependencies>legacy_stdio_definitions.lib;Ncrypt.lib;libssl.lib;libcrypto.lib;lzo2.lib;pkcs11-helper.dll.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;dnsapi.lib;%(AdditionalDependencies)</AdditionalDependencies>
       <AdditionalLibraryDirectories>$(OPENSSL_HOME)/lib;$(LZO_HOME)/lib;$(PKCS11H_HOME)/lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
       <SubSystem>Console</SubSystem>
     </Link>
src/openvpn/options.c +209 -43

363 lines not on this page · raw message

src/openvpn/options.h +4 -0
index 877e9396..cf22ffea 100644
@@ -92,6 +92,7 @@ struct connection_entry
     const char *remote_port;
     const char *local;
     const char *remote;
+    bool remote_srv;
     bool remote_float;
     bool bind_defined;
     bool bind_ipv6_only;
@@ -152,6 +153,7 @@ struct remote_entry
     const char *remote_port;
     int proto;
     sa_family_t af;
+    bool remote_srv;
 };
 
 #define CONNECTION_LIST_SIZE 64
@@ -787,6 +789,8 @@ char *options_string_extract_option(const char *options_string,
 
 void options_postprocess(struct options *options);
 
+bool options_mutate_ce_servinfo(struct options *o, struct servinfo *si);
+
 void pre_pull_save(struct options *o);
 
 void pre_pull_restore(struct options *o, struct gc_arena *gc);
src/openvpn/socket.c +863 -18

1,019 lines not on this page · raw message

src/openvpn/socket.h +55 -1

112 lines not on this page · raw message

src/openvpn/syshead.h +5 -0
index 8342eae0..e5852753 100644
@@ -38,6 +38,7 @@
 
 #ifdef _WIN32
 #include <windows.h>
+#include <windns.h>
 #include <winsock2.h>
 #include <tlhelp32.h>
 #define sleep(x) Sleep((x)*1000)
@@ -176,6 +177,10 @@
 #include <netinet/in.h>
 #endif
 
+#ifdef HAVE_ARPA_NAMESER_H
+#include <arpa/nameser.h>
+#endif
+
 #ifdef HAVE_RESOLV_H
 #include <resolv.h>
 #endif
Signature · 1 line
2.17.1
#4 lore raw

PATCH v6 1/2 Selectively reformat too long lines

Per https://community.openvpn.net/openvpn/wiki/CodeStyle the maximum line length is 80 characters. This patch allows to split upcoming changes into CodeStyle-conformant (w/o real code change) and more feature-specific.

---
 src/openvpn/init.c    |  3 ++-
 src/openvpn/options.c | 44 +++++++++++++++++++++++++++++--------------
 src/openvpn/socket.c  | 26 +++++++++++++++++--------
 3 files changed, 50 insertions(+), 23 deletions(-)
src/openvpn/init.c +2 -1
index d1ad5c8f..31ecadcc 100644
@@ -3646,7 +3646,8 @@ do_close_link_socket(struct context *c)
           && ( (c->options.persist_remote_ip)
                ||
                ( c->sig->source != SIG_SOURCE_HARD
-                 && ((c->c1.link_socket_addr.current_remote && c->c1.link_socket_addr.current_remote->ai_next)
+                 && ((c->c1.link_socket_addr.current_remote
+                      && c->c1.link_socket_addr.current_remote->ai_next)
                      || c->options.no_advance))
                )))
     {
src/openvpn/options.c +30 -14

113 lines not on this page · raw message

src/openvpn/socket.c +18 -8
index 76bdbfc5..296fb294 100644
@@ -378,7 +378,8 @@ do_preresolve(struct context *c)
         /* HTTP remote hostname does not need to be resolved */
         if (!ce->http_proxy_options)
         {
-            status = do_preresolve_host(c, remote, ce->remote_port, ce->af, flags);
+            status = do_preresolve_host(c, remote, ce->remote_port,
+                                        ce->af, flags);
             if (status != 0)
             {
                 goto err;
@@ -417,7 +418,8 @@ do_preresolve(struct context *c)
         {
             flags |= GETADDR_PASSIVE;
             flags &= ~GETADDR_RANDOMIZE;
-            status = do_preresolve_host(c, ce->local, ce->local_port, ce->af, flags);
+            status = do_preresolve_host(c, ce->local, ce->local_port,
+                                        ce->af, flags);
             if (status != 0)
             {
                 goto err;
@@ -526,7 +528,9 @@ openvpn_getaddrinfo(unsigned int flags,
         if ((flags & GETADDR_MENTION_RESOLVE_RETRY)
             && !resolve_retry_seconds)
         {
-            fmt = "RESOLVE: Cannot resolve host address: %s:%s (%s) (I would have retried this name query if you had specified the --resolv-retry option.)";
+            fmt = "RESOLVE: Cannot resolve host address: %s:%s (%s) "
+                  "(I would have retried this name query if you had "
+                  "specified the --resolv-retry option.)";
         }
 
         if (!(flags & GETADDR_RESOLVE) || status == EAI_FAIL)
@@ -558,11 +562,13 @@ openvpn_getaddrinfo(unsigned int flags,
         while (true)
         {
 #ifndef _WIN32
+            /* force resolv.conf reload */
             res_init();
 #endif
             /* try hostname lookup */
             hints.ai_flags &= ~AI_NUMERICHOST;
-            dmsg(D_SOCKET_DEBUG, "GETADDRINFO flags=0x%04x ai_family=%d ai_socktype=%d",
+            dmsg(D_SOCKET_DEBUG,
+                 "GETADDRINFO flags=0x%04x ai_family=%d ai_socktype=%d",
                  flags, hints.ai_family, hints.ai_socktype);
             status = getaddrinfo(hostname, servname, &hints, res);
 
@@ -573,7 +579,8 @@ openvpn_getaddrinfo(unsigned int flags,
                 {
                     if (*signal_received == SIGUSR1) /* ignore SIGUSR1 */
                     {
-                        msg(level, "RESOLVE: Ignored SIGUSR1 signal received during DNS resolution attempt");
+                        msg(level, "RESOLVE: Ignored SIGUSR1 signal received "
+                            "during DNS resolution attempt");
                         *signal_received = 0;
                     }
                     else
@@ -634,7 +641,8 @@ openvpn_getaddrinfo(unsigned int flags,
         /* IP address parse succeeded */
         if (flags & GETADDR_RANDOMIZE)
         {
-            msg(M_WARN, "WARNING: ignoring --remote-random-hostname because the hostname is an IP address");
+            msg(M_WARN, "WARNING: ignoring --remote-random-hostname "
+                "because the hostname is an IP address");
         }
     }
 
@@ -1802,7 +1810,8 @@ resolve_remote(struct link_socket *sock,
                 sock->info.lsa->remote_list = ai;
                 sock->info.lsa->current_remote = ai;
 
-                dmsg(D_SOCKET_DEBUG, "RESOLVE_REMOTE flags=0x%04x phase=%d rrs=%d sig=%d status=%d",
+                dmsg(D_SOCKET_DEBUG,
+                     "RESOLVE_REMOTE flags=0x%04x phase=%d rrs=%d sig=%d status=%d",
                      flags,
                      phase,
                      retry,
@@ -3170,7 +3179,7 @@ static const struct proto_names proto_names[] = {
     {"udp6","UDPv6", AF_INET6, PROTO_UDP},
     {"tcp6-server","TCPv6_SERVER", AF_INET6, PROTO_TCP_SERVER},
     {"tcp6-client","TCPv6_CLIENT", AF_INET6, PROTO_TCP_CLIENT},
-    {"tcp6","TCPv6", AF_INET6, PROTO_TCP},
+    {"tcp6",       "TCPv6", AF_INET6, PROTO_TCP},
 };
 
 bool
@@ -3182,6 +3191,7 @@ proto_is_net(int proto)
     }
     return proto != PROTO_NONE;
 }
+
 bool
 proto_is_dgram(int proto)
 {
Signature · 1 line
2.17.1
#5 lore raw

PATCH v6 2/2 Add DNS SRV remote host discovery support

DNS SRV remote host discovery allows to have multiple OpenVPN servers for a single domain w/o explicit profile enumeration, to move services from host to host with little fuss, and to designate hosts as primary servers for a service and others as backups.
Feature has been asked several times already, should be useful in case of substantial number of clients & servers deployed.

Patch introduces "--remote-srv domain [service] [proto]" option. The "service" and "proto" arguments are optional. Client will try to resolve DNS SRV record "_service._proto.domain" and use returned DNS SRV records as remote server list ordered by server selection mechanism defined in RFC2782 (https://tools.ietf.org/html/rfc2782):

A client MUST attempt to contact the target host with the lowest-numbered priority field value it can reach, target hosts with the same priority SHOULD be tried in an order defined by the weight field.
The weight field specifies a relative weight for entries with the same priority. Larger weights SHOULD be given a proportionately higher probability of being selected.
Domain administrators SHOULD use Weight 0 when there isn't any server selection to do. In the presence of records containing weights greater than 0, records with Weight 0 SHOULD have a very small chance of being selected.

Note: OpenVPN server selection mechanism implementation indeed will give records with weight of zero a very small chance of being selected first, but never skip them.

Example: instead of multiple --remote in order:
remote server1.example.net 1194 udp
remote server2.example.net 1194 udp
remote server3.example.net 1194 udp
remote server4.example.net 443 tcp

now it's possible to specify just one --remote-srv:
remote-srv example.net

and configure following DNS SRV records:
name prio weight port target
_openvpn._udp.example.net IN SRV 10 60 1194 server1.example.net
_openvpn._udp.example.net IN SRV 10 40 1194 server2.example.net
_openvpn._udp.example.net IN SRV 10 0 1194 server3.example.net
_openvpn._tcp.example.net IN SRV 20 0 443 server4.example.net

For "--remote-srv example.net" following will happen in order:
1. The client will first try to resolve "_openvpn._udp.example.net" and "_openvpn._tcp.example.net".
2. Records "server1.example.net:1194", "server2.example.net:1194" and "server3.example.net:1194" will be selected before record "server4.example.net:443" as their priority 10 is smaller than 20.
3. Records "server1.example.net:1194", "server2.example.net:1194" and "server3.example.net:1194" will be randomly selected with weight probability: first will be either "server1.example.net:1194" with 60% probability or "server2.example.net:1194" with 40% or "server3.example.net:1194" with almost zero probability.
4. If "server1.example.net:1194" was selected, the second record will be either "server2.example.net:1194" with almost 100% probability or "server3.example.net:1194" with almost 0%.
5. If "server2.example.net:1194" was selected, the third record will be the only last record of priority 10 - "server3.example.net:1194".
6. Record "server4.example.net:443" will be the last one selected as the only record with priority 20.
7. Each of the resulting "target:port" remote hosts will be resolved and accessed if its protocol has no conflict with the rest of the OpenVPN options.

If DNS SRV name can't be resolved or no valid records were returned, client will move on to the next connection entry.

Tested on Linux/Glibc & Windows 10.

v2: use DNS SRV for feature naming
change option name to --remote-service-discovery
add --remote-service-discovery [service] optional parameter support rewrite man, add algo/prio/weight description and examples
fix random weight selection was not implicit
remove pulled REMOTE_DISCOVERY support, not needed
split windows/unix-specific parts into extra functions
rename functions into servinfo scope, add doxygen comments when appropriate remove addrinfo hack, use servinfo containers of addrinfo list instead better proxy support (tcp mode not supported so far)
log discovery attempts and results, if enabled

v3: complete logic rewrite
use separate --remote-srv [service] [proto] option
remove fallback, same is achieved with additional --remote/--remote-srv add "auto" protocol support to allow both udp & tcp hosts be discovered add support for tcp / http proxy (natively)
man update

v4: due RFC 2782 ambiguity, prefer to use all resolved DNS SRV records, even
ones with weight 0 after the records containing weights greater than 0 were all selected, keep related code disabled for historical reasons. man update

v5: rebase against upstream with connection advancing fix
allow management skip/accept for exact remote service hosts as for --remote improve compatibility with a way "--persist-remote-ip" is handled ensure max line length is 80

v6: pick out code-style conformant changes into separate patch
add more options checks and comments
fix typos

---
 configure.ac                        |   2 +-
 doc/man-sections/client-options.rst | 117 +++-
 doc/management-notes.txt            |   6 +
 src/openvpn/Makefile.am             |   2 +-
 src/openvpn/buffer.h                |   5 -
 src/openvpn/errlevel.h              |   1 +
 src/openvpn/init.c                  |  66 ++-
 src/openvpn/openvpn.vcxproj         |   8 +-
 src/openvpn/options.c               | 262 +++++++--
 src/openvpn/options.h               |   4 +
 src/openvpn/socket.c                | 857 +++++++++++++++++++++++++++-
 src/openvpn/socket.h                |  56 +-
 src/openvpn/syshead.h               |   5 +
 13 files changed, 1312 insertions(+), 79 deletions(-)
configure.ac +1 -1
index ebb32204..22088aaf 100644
@@ -477,7 +477,7 @@ SOCKET_INCLUDES="
 "
 
 AC_CHECK_HEADERS(
-	[net/if.h netinet/ip.h resolv.h sys/un.h net/if_utun.h sys/kern_control.h],
+	[net/if.h netinet/ip.h arpa/nameser.h resolv.h sys/un.h net/if_utun.h sys/kern_control.h],
 	,
 	,
 	[[${SOCKET_INCLUDES}]]
doc/man-sections/client-options.rst +112 -5

130 lines not on this page · raw message

doc/management-notes.txt +6 -0
index 61daaf07..d9d7394d 100644
@@ -851,6 +851,12 @@ the above notification, use this command:
 
   remote MOD vpn.otherexample.com 1234
 
+DNS SRV discovery domain and service name with protocol code:`auto`
+can't be overriden, but either accepted or skipped only.
+Example of such notification:
+
+  >REMOTE:example.com,openvpn,auto
+
 To accept the same host and port as the client would ordinarily
 have connected to, use this command:
 
src/openvpn/Makefile.am +1 -1
index 37b002c6..f7632047 100644
@@ -143,5 +143,5 @@ openvpn_LDADD = \
 	$(OPTIONAL_INOTIFY_LIBS)
 if WIN32
 openvpn_SOURCES += openvpn_win32_resources.rc block_dns.c block_dns.h ring_buffer.h
-openvpn_LDADD += -lgdi32 -lws2_32 -lwininet -lcrypt32 -liphlpapi -lwinmm -lfwpuclnt -lrpcrt4 -lncrypt -lsetupapi
+openvpn_LDADD += -lgdi32 -lws2_32 -lwininet -lcrypt32 -liphlpapi -lwinmm -lfwpuclnt -lrpcrt4 -lncrypt -lsetupapi -ldnsapi
 endif
src/openvpn/buffer.h +0 -5
index 1722ffd5..ae0cf0eb 100644
@@ -198,11 +198,6 @@ bool buf_init_debug(struct buffer *buf, int offset, const char *file, int line);
 
 
 /* inline functions */
-inline static void
-gc_freeaddrinfo_callback(void *addr)
-{
-    freeaddrinfo((struct addrinfo *) addr);
-}
 
 /** Return an empty struct buffer */
 static inline struct buffer
src/openvpn/errlevel.h +1 -0
index 5663f841..39f96e7d 100644
@@ -92,6 +92,7 @@
 #define D_PS_PROXY           LOGLEV(3, 44, 0)        /* messages related to --port-share option */
 #define D_PF_INFO            LOGLEV(3, 45, 0)        /* packet filter informational messages */
 #define D_IFCONFIG           LOGLEV(3, 0,  0)        /* show ifconfig info (don't mute) */
+#define D_RESOLVE            LOGLEV(3, 46, 0)        /* show hostname resolve info */
 
 #define D_SHOW_PARMS         LOGLEV(4, 50, 0)        /* show all parameters on program initiation */
 #define D_SHOW_OCC           LOGLEV(4, 51, 0)        /* show options compatibility string */
src/openvpn/init.c +61 -5

126 lines not on this page · raw message

src/openvpn/openvpn.vcxproj +4 -4
index 3863854b..1f317fb0 100644
@@ -92,7 +92,7 @@
     </ClCompile>
     <ResourceCompile />
     <Link>
-      <AdditionalDependencies>legacy_stdio_definitions.lib;Ncrypt.lib;libssl.lib;libcrypto.lib;lzo2.lib;pkcs11-helper.dll.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;%(AdditionalDependencies)</AdditionalDependencies>
+      <AdditionalDependencies>legacy_stdio_definitions.lib;Ncrypt.lib;libssl.lib;libcrypto.lib;lzo2.lib;pkcs11-helper.dll.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;dnsapi.lib;%(AdditionalDependencies)</AdditionalDependencies>
       <AdditionalLibraryDirectories>$(OPENSSL_HOME)/lib;$(LZO_HOME)/lib;$(PKCS11H_HOME)/lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
       <SubSystem>Console</SubSystem>
     </Link>
@@ -107,7 +107,7 @@
     </ClCompile>
     <ResourceCompile />
     <Link>
-      <AdditionalDependencies>legacy_stdio_definitions.lib;Ncrypt.lib;libssl.lib;libcrypto.lib;lzo2.lib;pkcs11-helper.dll.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;%(AdditionalDependencies)</AdditionalDependencies>
+      <AdditionalDependencies>legacy_stdio_definitions.lib;Ncrypt.lib;libssl.lib;libcrypto.lib;lzo2.lib;pkcs11-helper.dll.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;dnsapi.lib;%(AdditionalDependencies)</AdditionalDependencies>
       <AdditionalLibraryDirectories>$(OPENSSL_HOME)/lib;$(LZO_HOME)/lib;$(PKCS11H_HOME)/lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
       <SubSystem>Console</SubSystem>
     </Link>
@@ -122,7 +122,7 @@
     </ClCompile>
     <ResourceCompile />
     <Link>
-      <AdditionalDependencies>legacy_stdio_definitions.lib;Ncrypt.lib;libssl.lib;libcrypto.lib;lzo2.lib;pkcs11-helper.dll.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;%(AdditionalDependencies)</AdditionalDependencies>
+      <AdditionalDependencies>legacy_stdio_definitions.lib;Ncrypt.lib;libssl.lib;libcrypto.lib;lzo2.lib;pkcs11-helper.dll.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;dnsapi.lib;%(AdditionalDependencies)</AdditionalDependencies>
       <AdditionalLibraryDirectories>$(OPENSSL_HOME)/lib;$(LZO_HOME)/lib;$(PKCS11H_HOME)/lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
       <SubSystem>Console</SubSystem>
     </Link>
@@ -137,7 +137,7 @@
     </ClCompile>
     <ResourceCompile />
     <Link>
-      <AdditionalDependencies>legacy_stdio_definitions.lib;Ncrypt.lib;libssl.lib;libcrypto.lib;lzo2.lib;pkcs11-helper.dll.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;%(AdditionalDependencies)</AdditionalDependencies>
+      <AdditionalDependencies>legacy_stdio_definitions.lib;Ncrypt.lib;libssl.lib;libcrypto.lib;lzo2.lib;pkcs11-helper.dll.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;dnsapi.lib;%(AdditionalDependencies)</AdditionalDependencies>
       <AdditionalLibraryDirectories>$(OPENSSL_HOME)/lib;$(LZO_HOME)/lib;$(PKCS11H_HOME)/lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
       <SubSystem>Console</SubSystem>
     </Link>
src/openvpn/options.c +216 -46

372 lines not on this page · raw message

src/openvpn/options.h +4 -0
index 877e9396..cf22ffea 100644
@@ -92,6 +92,7 @@ struct connection_entry
     const char *remote_port;
     const char *local;
     const char *remote;
+    bool remote_srv;
     bool remote_float;
     bool bind_defined;
     bool bind_ipv6_only;
@@ -152,6 +153,7 @@ struct remote_entry
     const char *remote_port;
     int proto;
     sa_family_t af;
+    bool remote_srv;
 };
 
 #define CONNECTION_LIST_SIZE 64
@@ -787,6 +789,8 @@ char *options_string_extract_option(const char *options_string,
 
 void options_postprocess(struct options *options);
 
+bool options_mutate_ce_servinfo(struct options *o, struct servinfo *si);
+
 void pre_pull_save(struct options *o);
 
 void pre_pull_restore(struct options *o, struct gc_arena *gc);
src/openvpn/socket.c +846 -11

965 lines not on this page · raw message

src/openvpn/socket.h +55 -1

112 lines not on this page · raw message

src/openvpn/syshead.h +5 -0
index 8342eae0..e5852753 100644
@@ -38,6 +38,7 @@
 
 #ifdef _WIN32
 #include <windows.h>
+#include <windns.h>
 #include <winsock2.h>
 #include <tlhelp32.h>
 #define sleep(x) Sleep((x)*1000)
@@ -176,6 +177,10 @@
 #include <netinet/in.h>
 #endif
 
+#ifdef HAVE_ARPA_NAMESER_H
+#include <arpa/nameser.h>
+#endif
+
 #ifdef HAVE_RESOLV_H
 #include <resolv.h>
 #endif
Signature · 1 line
2.17.1
#6 lore raw

PATCH v7 1/1 Add DNS SRV remote host discovery support

DNS SRV remote host discovery allows to have multiple OpenVPN servers for a single domain w/o explicit profile enumeration, to move services from host to host with little fuss, and to designate hosts as primary servers for a service and others as backups.
Feature has been asked several times already, should be useful in case of substantial number of clients & servers deployed.

Patch introduces "--remote-srv domain [service] [proto]" option. The "service" and "proto" arguments are optional. Client will try to resolve DNS SRV record "_service._proto.domain" and use returned DNS SRV records as remote server list ordered by server selection mechanism defined in RFC2782 (https://tools.ietf.org/html/rfc2782):

A client MUST attempt to contact the target host with the lowest-numbered priority field value it can reach, target hosts with the same priority SHOULD be tried in an order defined by the weight field.
The weight field specifies a relative weight for entries with the same priority. Larger weights SHOULD be given a proportionately higher probability of being selected.
Domain administrators SHOULD use Weight 0 when there isn't any server selection to do. In the presence of records containing weights greater than 0, records with Weight 0 SHOULD have a very small chance of being selected.

Note: OpenVPN server selection mechanism implementation indeed will give records with weight of zero a very small chance of being selected first, but never skip them.

Example: instead of multiple --remote in order:
remote server1.example.net 1194 udp
remote server2.example.net 1194 udp
remote server3.example.net 1194 udp
remote server4.example.net 443 tcp

now it's possible to specify just one --remote-srv:
remote-srv example.net

and configure following DNS SRV records:
name prio weight port target
_openvpn._udp.example.net IN SRV 10 60 1194 server1.example.net
_openvpn._udp.example.net IN SRV 10 40 1194 server2.example.net
_openvpn._udp.example.net IN SRV 10 0 1194 server3.example.net
_openvpn._tcp.example.net IN SRV 20 0 443 server4.example.net

For "--remote-srv example.net" following will happen in order:
1. The client will first try to resolve "_openvpn._udp.example.net" and "_openvpn._tcp.example.net".
2. Records "server1.example.net:1194", "server2.example.net:1194" and "server3.example.net:1194" will be selected before record "server4.example.net:443" as their priority 10 is smaller than 20.
3. Records "server1.example.net:1194", "server2.example.net:1194" and "server3.example.net:1194" will be randomly selected with weight probability: first will be either "server1.example.net:1194" with 60% probability or "server2.example.net:1194" with 40% or "server3.example.net:1194" with almost zero probability.
4. If "server1.example.net:1194" was selected, the second record will be either "server2.example.net:1194" with almost 100% probability or "server3.example.net:1194" with almost 0%.
5. If "server2.example.net:1194" was selected, the third record will be the only last record of priority 10 - "server3.example.net:1194".
6. Record "server4.example.net:443" will be the last one selected as the only record with priority 20.
7. Each of the resulting "target:port" remote hosts will be resolved and accessed if its protocol has no conflict with the rest of the OpenVPN options.

If DNS SRV name can't be resolved or no valid records were returned, client will move on to the next connection entry.

v2: use DNS SRV for feature naming
change option name to --remote-service-discovery
add --remote-service-discovery [service] optional parameter support rewrite man, add algo/prio/weight description and examples
fix random weight selection was not implicit
remove pulled REMOTE_DISCOVERY support, not needed
split windows/unix-specific parts into extra functions
rename functions into servinfo scope, add doxygen comments when appropriate remove addrinfo hack, use servinfo containers of addrinfo list instead better proxy support (tcp mode not supported so far)
log discovery attempts and results, if enabled

v3: complete logic rewrite
use separate --remote-srv [service] [proto] option
remove fallback, same is achieved with additional --remote/--remote-srv add "auto" protocol support to allow both udp & tcp hosts be discovered add support for tcp / http proxy (natively)
man update

v4: due RFC 2782 ambiguity, prefer to use all resolved DNS SRV records, even
ones with weight 0 after the records containing weights greater than 0 were all selected, keep related code disabled for historical reasons. man update

v5: rebase against upstream with connection advancing fix
allow management skip/accept for exact remote service hosts as for --remote improve compatibility with a way "--persist-remote-ip" is handled ensure max line length is 80

v6: pick out code-style conformant changes into separate patch
add more options checks and comments
fix typos

v7: prefer line breaks before long string parameters
use win32/posix suffixes for query_servinfo

---
 configure.ac                        |   2 +-
 doc/man-sections/client-options.rst | 117 +++-
 doc/management-notes.txt            |   6 +
 src/openvpn/Makefile.am             |   2 +-
 src/openvpn/buffer.h                |   5 -
 src/openvpn/errlevel.h              |   1 +
 src/openvpn/init.c                  |  66 ++-
 src/openvpn/openvpn.vcxproj         |   8 +-
 src/openvpn/options.c               | 268 +++++++--
 src/openvpn/options.h               |   4 +
 src/openvpn/socket.c                | 859 +++++++++++++++++++++++++++-
 src/openvpn/socket.h                |  56 +-
 src/openvpn/syshead.h               |   5 +
 13 files changed, 1320 insertions(+), 79 deletions(-)
configure.ac +1 -1
index ebb32204..22088aaf 100644
@@ -477,7 +477,7 @@ SOCKET_INCLUDES="
 "
 
 AC_CHECK_HEADERS(
-	[net/if.h netinet/ip.h resolv.h sys/un.h net/if_utun.h sys/kern_control.h],
+	[net/if.h netinet/ip.h arpa/nameser.h resolv.h sys/un.h net/if_utun.h sys/kern_control.h],
 	,
 	,
 	[[${SOCKET_INCLUDES}]]
doc/man-sections/client-options.rst +112 -5

130 lines not on this page · raw message

doc/management-notes.txt +6 -0
index 61daaf07..d9d7394d 100644
@@ -851,6 +851,12 @@ the above notification, use this command:
 
   remote MOD vpn.otherexample.com 1234
 
+DNS SRV discovery domain and service name with protocol code:`auto`
+can't be overriden, but either accepted or skipped only.
+Example of such notification:
+
+  >REMOTE:example.com,openvpn,auto
+
 To accept the same host and port as the client would ordinarily
 have connected to, use this command:
 
src/openvpn/Makefile.am +1 -1
index 37b002c6..f7632047 100644
@@ -143,5 +143,5 @@ openvpn_LDADD = \
 	$(OPTIONAL_INOTIFY_LIBS)
 if WIN32
 openvpn_SOURCES += openvpn_win32_resources.rc block_dns.c block_dns.h ring_buffer.h
-openvpn_LDADD += -lgdi32 -lws2_32 -lwininet -lcrypt32 -liphlpapi -lwinmm -lfwpuclnt -lrpcrt4 -lncrypt -lsetupapi
+openvpn_LDADD += -lgdi32 -lws2_32 -lwininet -lcrypt32 -liphlpapi -lwinmm -lfwpuclnt -lrpcrt4 -lncrypt -lsetupapi -ldnsapi
 endif
src/openvpn/buffer.h +0 -5
index 1722ffd5..ae0cf0eb 100644
@@ -198,11 +198,6 @@ bool buf_init_debug(struct buffer *buf, int offset, const char *file, int line);
 
 
 /* inline functions */
-inline static void
-gc_freeaddrinfo_callback(void *addr)
-{
-    freeaddrinfo((struct addrinfo *) addr);
-}
 
 /** Return an empty struct buffer */
 static inline struct buffer
src/openvpn/errlevel.h +1 -0
index 5663f841..39f96e7d 100644
@@ -92,6 +92,7 @@
 #define D_PS_PROXY           LOGLEV(3, 44, 0)        /* messages related to --port-share option */
 #define D_PF_INFO            LOGLEV(3, 45, 0)        /* packet filter informational messages */
 #define D_IFCONFIG           LOGLEV(3, 0,  0)        /* show ifconfig info (don't mute) */
+#define D_RESOLVE            LOGLEV(3, 46, 0)        /* show hostname resolve info */
 
 #define D_SHOW_PARMS         LOGLEV(4, 50, 0)        /* show all parameters on program initiation */
 #define D_SHOW_OCC           LOGLEV(4, 51, 0)        /* show options compatibility string */
src/openvpn/init.c +61 -5

126 lines not on this page · raw message

src/openvpn/openvpn.vcxproj +4 -4
index 3863854b..1f317fb0 100644
@@ -92,7 +92,7 @@
     </ClCompile>
     <ResourceCompile />
     <Link>
-      <AdditionalDependencies>legacy_stdio_definitions.lib;Ncrypt.lib;libssl.lib;libcrypto.lib;lzo2.lib;pkcs11-helper.dll.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;%(AdditionalDependencies)</AdditionalDependencies>
+      <AdditionalDependencies>legacy_stdio_definitions.lib;Ncrypt.lib;libssl.lib;libcrypto.lib;lzo2.lib;pkcs11-helper.dll.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;dnsapi.lib;%(AdditionalDependencies)</AdditionalDependencies>
       <AdditionalLibraryDirectories>$(OPENSSL_HOME)/lib;$(LZO_HOME)/lib;$(PKCS11H_HOME)/lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
       <SubSystem>Console</SubSystem>
     </Link>
@@ -107,7 +107,7 @@
     </ClCompile>
     <ResourceCompile />
     <Link>
-      <AdditionalDependencies>legacy_stdio_definitions.lib;Ncrypt.lib;libssl.lib;libcrypto.lib;lzo2.lib;pkcs11-helper.dll.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;%(AdditionalDependencies)</AdditionalDependencies>
+      <AdditionalDependencies>legacy_stdio_definitions.lib;Ncrypt.lib;libssl.lib;libcrypto.lib;lzo2.lib;pkcs11-helper.dll.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;dnsapi.lib;%(AdditionalDependencies)</AdditionalDependencies>
       <AdditionalLibraryDirectories>$(OPENSSL_HOME)/lib;$(LZO_HOME)/lib;$(PKCS11H_HOME)/lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
       <SubSystem>Console</SubSystem>
     </Link>
@@ -122,7 +122,7 @@
     </ClCompile>
     <ResourceCompile />
     <Link>
-      <AdditionalDependencies>legacy_stdio_definitions.lib;Ncrypt.lib;libssl.lib;libcrypto.lib;lzo2.lib;pkcs11-helper.dll.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;%(AdditionalDependencies)</AdditionalDependencies>
+      <AdditionalDependencies>legacy_stdio_definitions.lib;Ncrypt.lib;libssl.lib;libcrypto.lib;lzo2.lib;pkcs11-helper.dll.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;dnsapi.lib;%(AdditionalDependencies)</AdditionalDependencies>
       <AdditionalLibraryDirectories>$(OPENSSL_HOME)/lib;$(LZO_HOME)/lib;$(PKCS11H_HOME)/lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
       <SubSystem>Console</SubSystem>
     </Link>
@@ -137,7 +137,7 @@
     </ClCompile>
     <ResourceCompile />
     <Link>
-      <AdditionalDependencies>legacy_stdio_definitions.lib;Ncrypt.lib;libssl.lib;libcrypto.lib;lzo2.lib;pkcs11-helper.dll.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;%(AdditionalDependencies)</AdditionalDependencies>
+      <AdditionalDependencies>legacy_stdio_definitions.lib;Ncrypt.lib;libssl.lib;libcrypto.lib;lzo2.lib;pkcs11-helper.dll.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;dnsapi.lib;%(AdditionalDependencies)</AdditionalDependencies>
       <AdditionalLibraryDirectories>$(OPENSSL_HOME)/lib;$(LZO_HOME)/lib;$(PKCS11H_HOME)/lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
       <SubSystem>Console</SubSystem>
     </Link>
src/openvpn/options.c +222 -46

376 lines not on this page · raw message

src/openvpn/options.h +4 -0
index 877e9396..cf22ffea 100644
@@ -92,6 +92,7 @@ struct connection_entry
     const char *remote_port;
     const char *local;
     const char *remote;
+    bool remote_srv;
     bool remote_float;
     bool bind_defined;
     bool bind_ipv6_only;
@@ -152,6 +153,7 @@ struct remote_entry
     const char *remote_port;
     int proto;
     sa_family_t af;
+    bool remote_srv;
 };
 
 #define CONNECTION_LIST_SIZE 64
@@ -787,6 +789,8 @@ char *options_string_extract_option(const char *options_string,
 
 void options_postprocess(struct options *options);
 
+bool options_mutate_ce_servinfo(struct options *o, struct servinfo *si);
+
 void pre_pull_save(struct options *o);
 
 void pre_pull_restore(struct options *o, struct gc_arena *gc);
src/openvpn/socket.c +848 -11

967 lines not on this page · raw message

src/openvpn/socket.h +55 -1

112 lines not on this page · raw message

src/openvpn/syshead.h +5 -0
index 8342eae0..e5852753 100644
@@ -38,6 +38,7 @@
 
 #ifdef _WIN32
 #include <windows.h>
+#include <windns.h>
 #include <winsock2.h>
 #include <tlhelp32.h>
 #define sleep(x) Sleep((x)*1000)
@@ -176,6 +177,10 @@
 #include <netinet/in.h>
 #endif
 
+#ifdef HAVE_ARPA_NAMESER_H
+#include <arpa/nameser.h>
+#endif
+
 #ifdef HAVE_RESOLV_H
 #include <resolv.h>
 #endif
Signature · 1 line
2.17.1
#7 lore raw

PATCH v8 1/1 Add DNS SRV remote host discovery support

DNS SRV remote host discovery allows to have multiple OpenVPN servers for a single domain w/o explicit profile enumeration, to move services from host to host with little fuss, and to designate hosts as primary servers for a service and others as backups.
Feature has been asked several times already, should be useful in case of substantial number of clients & servers deployed.

Patch introduces "--remote-srv domain [service] [proto]" option. The "service" and "proto" arguments are optional. Client will try to resolve DNS SRV record "_service._proto.domain" and use returned DNS SRV records as remote server list ordered by server selection mechanism defined in RFC2782 (https://tools.ietf.org/html/rfc2782):

A client MUST attempt to contact the target host with the lowest-numbered priority field value it can reach, target hosts with the same priority SHOULD be tried in an order defined by the weight field.
The weight field specifies a relative weight for entries with the same priority. Larger weights SHOULD be given a proportionately higher probability of being selected.
Domain administrators SHOULD use Weight 0 when there isn't any server selection to do. In the presence of records containing weights greater than 0, records with Weight 0 SHOULD have a very small chance of being selected.

Note: OpenVPN server selection mechanism implementation indeed will give records with weight of zero a very small chance of being selected first, but never skip them.

Example: instead of multiple --remote in order:
remote server1.example.net 1194 udp
remote server2.example.net 1194 udp
remote server3.example.net 1194 udp
remote server4.example.net 443 tcp

now it's possible to specify just one --remote-srv:
remote-srv example.net

and configure following DNS SRV records:
name prio weight port target
_openvpn._udp.example.net IN SRV 10 60 1194 server1.example.net
_openvpn._udp.example.net IN SRV 10 40 1194 server2.example.net
_openvpn._udp.example.net IN SRV 10 0 1194 server3.example.net
_openvpn._tcp.example.net IN SRV 20 0 443 server4.example.net

For "--remote-srv example.net" following will happen in order:
1. The client will first try to resolve "_openvpn._udp.example.net" and "_openvpn._tcp.example.net".
2. Records "server1.example.net:1194", "server2.example.net:1194" and "server3.example.net:1194" will be selected before record "server4.example.net:443" as their priority 10 is smaller than 20.
3. Records "server1.example.net:1194", "server2.example.net:1194" and "server3.example.net:1194" will be randomly selected with weight probability: first will be either "server1.example.net:1194" with 60% probability or "server2.example.net:1194" with 40% or "server3.example.net:1194" with almost zero probability.
4. If "server1.example.net:1194" was selected, the second record will be either "server2.example.net:1194" with almost 100% probability or "server3.example.net:1194" with almost 0%.
5. If "server2.example.net:1194" was selected, the third record will be the only last record of priority 10 - "server3.example.net:1194".
6. Record "server4.example.net:443" will be the last one selected as the only record with priority 20.
7. Each of the resulting "target:port" remote hosts will be resolved and accessed if its protocol has no conflict with the rest of the OpenVPN options.

If DNS SRV name can't be resolved or no valid records were returned, client will move on to the next connection entry.

v2:
- use DNS SRV for feature naming
- change option name to --remote-service-discovery
- add --remote-service-discovery [service] optional parameter support
- rewrite man, add algo/prio/weight description and examples
- fix random weight selection was not implicit
- remove pulled REMOTE_DISCOVERY support, not needed
- split windows/unix-specific parts into extra functions
- put functions into servinfo scope, add doxygen comments
- remove addrinfo hack, use servinfo containers of addrinfo list
- better proxy support (tcp mode not supported so far)
- log discovery attempts and results, if enabled

v3:
- complete logic rewrite
- use separate --remote-srv [service] [proto] option
- remove fallback, additional --remote/--remote-srv does the same
- add "auto" protocol support to allow both udp & tcp discoverery
- add support for tcp / http proxy (natively)
- man update

v4:
- due RFC 2782 ambiguity, prefer to use all resolved DNS SRV records, even ones with weight 0 after the records containing weights greater than 0 were all selected, keep related code disabled for historical reasons.
- man update

v5: rebase against upstream with connection advancing fix
- allow management skip/accept for remote service hosts as for --remote
- improve compatibility with a way "--persist-remote-ip" is handled
- ensure max line length is 80

v6:
- pick out code-style conformant changes into separate patch
- add more options checks and comments

v7:
- prefer line breaks before long string parameters
- use win32/posix suffixes for query_servinfo

v8:
- rework compatibility with --preresolve and --persist-remote-ip
- fix dns data structures leak on wine/win32
- add priority and weight logging

---
 configure.ac                        |   2 +-
 doc/man-sections/client-options.rst | 117 +++-
 doc/management-notes.txt            |   6 +
 src/openvpn/Makefile.am             |   2 +-
 src/openvpn/buffer.h                |   5 -
 src/openvpn/errlevel.h              |   1 +
 src/openvpn/init.c                  |  79 ++-
 src/openvpn/openvpn.vcxproj         |   8 +-
 src/openvpn/options.c               | 268 +++++++--
 src/openvpn/options.h               |   4 +
 src/openvpn/socket.c                | 854 +++++++++++++++++++++++++++-
 src/openvpn/socket.h                |  58 +-
 src/openvpn/syshead.h               |   5 +
 13 files changed, 1328 insertions(+), 81 deletions(-)
configure.ac +1 -1
index ebb32204..22088aaf 100644
@@ -477,7 +477,7 @@ SOCKET_INCLUDES="
 "
 
 AC_CHECK_HEADERS(
-	[net/if.h netinet/ip.h resolv.h sys/un.h net/if_utun.h sys/kern_control.h],
+	[net/if.h netinet/ip.h arpa/nameser.h resolv.h sys/un.h net/if_utun.h sys/kern_control.h],
 	,
 	,
 	[[${SOCKET_INCLUDES}]]
doc/man-sections/client-options.rst +112 -5

130 lines not on this page · raw message

doc/management-notes.txt +6 -0
index 61daaf07..d9d7394d 100644
@@ -851,6 +851,12 @@ the above notification, use this command:
 
   remote MOD vpn.otherexample.com 1234
 
+DNS SRV discovery domain and service name with protocol code:`auto`
+can't be overriden, but either accepted or skipped only.
+Example of such notification:
+
+  >REMOTE:example.com,openvpn,auto
+
 To accept the same host and port as the client would ordinarily
 have connected to, use this command:
 
src/openvpn/Makefile.am +1 -1
index 37b002c6..f7632047 100644
@@ -143,5 +143,5 @@ openvpn_LDADD = \
 	$(OPTIONAL_INOTIFY_LIBS)
 if WIN32
 openvpn_SOURCES += openvpn_win32_resources.rc block_dns.c block_dns.h ring_buffer.h
-openvpn_LDADD += -lgdi32 -lws2_32 -lwininet -lcrypt32 -liphlpapi -lwinmm -lfwpuclnt -lrpcrt4 -lncrypt -lsetupapi
+openvpn_LDADD += -lgdi32 -lws2_32 -lwininet -lcrypt32 -liphlpapi -lwinmm -lfwpuclnt -lrpcrt4 -lncrypt -lsetupapi -ldnsapi
 endif
src/openvpn/buffer.h +0 -5
index 1722ffd5..ae0cf0eb 100644
@@ -198,11 +198,6 @@ bool buf_init_debug(struct buffer *buf, int offset, const char *file, int line);
 
 
 /* inline functions */
-inline static void
-gc_freeaddrinfo_callback(void *addr)
-{
-    freeaddrinfo((struct addrinfo *) addr);
-}
 
 /** Return an empty struct buffer */
 static inline struct buffer
src/openvpn/errlevel.h +1 -0
index 5663f841..39f96e7d 100644
@@ -92,6 +92,7 @@
 #define D_PS_PROXY           LOGLEV(3, 44, 0)        /* messages related to --port-share option */
 #define D_PF_INFO            LOGLEV(3, 45, 0)        /* packet filter informational messages */
 #define D_IFCONFIG           LOGLEV(3, 0,  0)        /* show ifconfig info (don't mute) */
+#define D_RESOLVE            LOGLEV(3, 46, 0)        /* show hostname resolve info */
 
 #define D_SHOW_PARMS         LOGLEV(4, 50, 0)        /* show all parameters on program initiation */
 #define D_SHOW_OCC           LOGLEV(4, 51, 0)        /* show options compatibility string */
src/openvpn/init.c +72 -7

139 lines not on this page · raw message

src/openvpn/openvpn.vcxproj +4 -4
index 3863854b..1f317fb0 100644
@@ -92,7 +92,7 @@
     </ClCompile>
     <ResourceCompile />
     <Link>
-      <AdditionalDependencies>legacy_stdio_definitions.lib;Ncrypt.lib;libssl.lib;libcrypto.lib;lzo2.lib;pkcs11-helper.dll.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;%(AdditionalDependencies)</AdditionalDependencies>
+      <AdditionalDependencies>legacy_stdio_definitions.lib;Ncrypt.lib;libssl.lib;libcrypto.lib;lzo2.lib;pkcs11-helper.dll.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;dnsapi.lib;%(AdditionalDependencies)</AdditionalDependencies>
       <AdditionalLibraryDirectories>$(OPENSSL_HOME)/lib;$(LZO_HOME)/lib;$(PKCS11H_HOME)/lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
       <SubSystem>Console</SubSystem>
     </Link>
@@ -107,7 +107,7 @@
     </ClCompile>
     <ResourceCompile />
     <Link>
-      <AdditionalDependencies>legacy_stdio_definitions.lib;Ncrypt.lib;libssl.lib;libcrypto.lib;lzo2.lib;pkcs11-helper.dll.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;%(AdditionalDependencies)</AdditionalDependencies>
+      <AdditionalDependencies>legacy_stdio_definitions.lib;Ncrypt.lib;libssl.lib;libcrypto.lib;lzo2.lib;pkcs11-helper.dll.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;dnsapi.lib;%(AdditionalDependencies)</AdditionalDependencies>
       <AdditionalLibraryDirectories>$(OPENSSL_HOME)/lib;$(LZO_HOME)/lib;$(PKCS11H_HOME)/lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
       <SubSystem>Console</SubSystem>
     </Link>
@@ -122,7 +122,7 @@
     </ClCompile>
     <ResourceCompile />
     <Link>
-      <AdditionalDependencies>legacy_stdio_definitions.lib;Ncrypt.lib;libssl.lib;libcrypto.lib;lzo2.lib;pkcs11-helper.dll.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;%(AdditionalDependencies)</AdditionalDependencies>
+      <AdditionalDependencies>legacy_stdio_definitions.lib;Ncrypt.lib;libssl.lib;libcrypto.lib;lzo2.lib;pkcs11-helper.dll.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;dnsapi.lib;%(AdditionalDependencies)</AdditionalDependencies>
       <AdditionalLibraryDirectories>$(OPENSSL_HOME)/lib;$(LZO_HOME)/lib;$(PKCS11H_HOME)/lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
       <SubSystem>Console</SubSystem>
     </Link>
@@ -137,7 +137,7 @@
     </ClCompile>
     <ResourceCompile />
     <Link>
-      <AdditionalDependencies>legacy_stdio_definitions.lib;Ncrypt.lib;libssl.lib;libcrypto.lib;lzo2.lib;pkcs11-helper.dll.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;%(AdditionalDependencies)</AdditionalDependencies>
+      <AdditionalDependencies>legacy_stdio_definitions.lib;Ncrypt.lib;libssl.lib;libcrypto.lib;lzo2.lib;pkcs11-helper.dll.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;dnsapi.lib;%(AdditionalDependencies)</AdditionalDependencies>
       <AdditionalLibraryDirectories>$(OPENSSL_HOME)/lib;$(LZO_HOME)/lib;$(PKCS11H_HOME)/lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
       <SubSystem>Console</SubSystem>
     </Link>
src/openvpn/options.c +222 -46

376 lines not on this page · raw message

src/openvpn/options.h +4 -0
index 877e9396..cf22ffea 100644
@@ -92,6 +92,7 @@ struct connection_entry
     const char *remote_port;
     const char *local;
     const char *remote;
+    bool remote_srv;
     bool remote_float;
     bool bind_defined;
     bool bind_ipv6_only;
@@ -152,6 +153,7 @@ struct remote_entry
     const char *remote_port;
     int proto;
     sa_family_t af;
+    bool remote_srv;
 };
 
 #define CONNECTION_LIST_SIZE 64
@@ -787,6 +789,8 @@ char *options_string_extract_option(const char *options_string,
 
 void options_postprocess(struct options *options);
 
+bool options_mutate_ce_servinfo(struct options *o, struct servinfo *si);
+
 void pre_pull_save(struct options *o);
 
 void pre_pull_restore(struct options *o, struct gc_arena *gc);
src/openvpn/socket.c +843 -11

956 lines not on this page · raw message

src/openvpn/socket.h +57 -1

114 lines not on this page · raw message

src/openvpn/syshead.h +5 -0
index 8342eae0..e5852753 100644
@@ -38,6 +38,7 @@
 
 #ifdef _WIN32
 #include <windows.h>
+#include <windns.h>
 #include <winsock2.h>
 #include <tlhelp32.h>
 #define sleep(x) Sleep((x)*1000)
@@ -176,6 +177,10 @@
 #include <netinet/in.h>
 #endif
 
+#ifdef HAVE_ARPA_NAMESER_H
+#include <arpa/nameser.h>
+#endif
+
 #ifdef HAVE_RESOLV_H
 #include <resolv.h>
 #endif
Signature · 1 line
2.17.1
#8 lore raw

Am 05.10.20 um 00:36 schrieb Vladislav Grishenko:

Quoted 38 lines

DNS SRV remote host discovery allows to have multiple OpenVPN servers for a single domain w/o explicit profile enumeration, to move services from host to host with little fuss, and to designate hosts as primary servers for a service and others as backups.
Feature has been asked several times already, should be useful in case of substantial number of clients & servers deployed.

Patch introduces "--remote-srv domain [service] [proto]" option. The "service" and "proto" arguments are optional. Client will try to resolve DNS SRV record "_service._proto.domain" and use returned DNS SRV records as remote server list ordered by server selection mechanism defined in RFC2782 (https://tools.ietf.org/html/rfc2782):

A client MUST attempt to contact the target host with the lowest-numbered priority field value it can reach, target hosts with the same priority SHOULD be tried in an order defined by the weight field.
The weight field specifies a relative weight for entries with the same priority. Larger weights SHOULD be given a proportionately higher probability of being selected.
Domain administrators SHOULD use Weight 0 when there isn't any server selection to do. In the presence of records containing weights greater than 0, records with Weight 0 SHOULD have a very small chance of being selected.

Note: OpenVPN server selection mechanism implementation indeed will give records with weight of zero a very small chance of being selected first, but never skip them.

Example: instead of multiple --remote in order:
remote server1.example.net 1194 udp
remote server2.example.net 1194 udp
remote server3.example.net 1194 udp
remote server4.example.net 443 tcp

now it's possible to specify just one --remote-srv:
remote-srv example.net

Quoted 6 lines

and configure following DNS SRV records:
name prio weight port target
_openvpn._udp.example.net IN SRV 10 60 1194 server1.example.net
_openvpn._udp.example.net IN SRV 10 40 1194 server2.example.net
_openvpn._udp.example.net IN SRV 10 0 1194 server3.example.net
_openvpn._tcp.example.net IN SRV 20 0 443 server4.example.net

Missing . at the end at least if it should be in a bind zone file:

_openvpn._udp.example.net. IN SRV 10 60 1194 server1.example.net.

or

_openvpn._udp IN SRV 10 60 1194 server1.example.net.

Quoted 135 lines

For "--remote-srv example.net" following will happen in order:
1. The client will first try to resolve "_openvpn._udp.example.net" and "_openvpn._tcp.example.net".
2. Records "server1.example.net:1194", "server2.example.net:1194" and "server3.example.net:1194" will be selected before record "server4.example.net:443" as their priority 10 is smaller than 20.
3. Records "server1.example.net:1194", "server2.example.net:1194" and "server3.example.net:1194" will be randomly selected with weight probability: first will be either "server1.example.net:1194" with 60% probability or "server2.example.net:1194" with 40% or "server3.example.net:1194" with almost zero probability.
4. If "server1.example.net:1194" was selected, the second record will be either "server2.example.net:1194" with almost 100% probability or "server3.example.net:1194" with almost 0%.
5. If "server2.example.net:1194" was selected, the third record will be the only last record of priority 10 - "server3.example.net:1194".
6. Record "server4.example.net:443" will be the last one selected as the only record with priority 20.
7. Each of the resulting "target:port" remote hosts will be resolved and accessed if its protocol has no conflict with the rest of the OpenVPN options.

If DNS SRV name can't be resolved or no valid records were returned, client will move on to the next connection entry.

v2:
- use DNS SRV for feature naming
- change option name to --remote-service-discovery
- add --remote-service-discovery [service] optional parameter support
- rewrite man, add algo/prio/weight description and examples
- fix random weight selection was not implicit
- remove pulled REMOTE_DISCOVERY support, not needed
- split windows/unix-specific parts into extra functions
- put functions into servinfo scope, add doxygen comments
- remove addrinfo hack, use servinfo containers of addrinfo list
- better proxy support (tcp mode not supported so far)
- log discovery attempts and results, if enabled

v3:
- complete logic rewrite
- use separate --remote-srv [service] [proto] option
- remove fallback, additional --remote/--remote-srv does the same
- add "auto" protocol support to allow both udp & tcp discoverery
- add support for tcp / http proxy (natively)
- man update

v4:
- due RFC 2782 ambiguity, prefer to use all resolved DNS SRV records, even ones with weight 0 after the records containing weights greater than 0 were all selected, keep related code disabled for historical reasons.
- man update

v5: rebase against upstream with connection advancing fix
- allow management skip/accept for remote service hosts as for --remote
- improve compatibility with a way "--persist-remote-ip" is handled
- ensure max line length is 80

v6:
- pick out code-style conformant changes into separate patch
- add more options checks and comments

v7:
- prefer line breaks before long string parameters
- use win32/posix suffixes for query_servinfo

v8:
- rework compatibility with --preresolve and --persist-remote-ip
- fix dns data structures leak on wine/win32
- add priority and weight logging

---
 configure.ac                        |   2 +-
 doc/man-sections/client-options.rst | 117 +++-
 doc/management-notes.txt            |   6 +
 src/openvpn/Makefile.am             |   2 +-
 src/openvpn/buffer.h                |   5 -
 src/openvpn/errlevel.h              |   1 +
 src/openvpn/init.c                  |  79 ++-
 src/openvpn/openvpn.vcxproj         |   8 +-
 src/openvpn/options.c               | 268 +++++++--
 src/openvpn/options.h               |   4 +
 src/openvpn/socket.c                | 854 +++++++++++++++++++++++++++-
 src/openvpn/socket.h                |  58 +-
 src/openvpn/syshead.h               |   5 +
 13 files changed, 1328 insertions(+), 81 deletions(-)
configure.ac +1 -1
index ebb32204..22088aaf 100644
@@ -477,7 +477,7 @@ SOCKET_INCLUDES="
 "
 
 AC_CHECK_HEADERS(
-	[net/if.h netinet/ip.h resolv.h sys/un.h net/if_utun.h sys/kern_control.h],
+	[net/if.h netinet/ip.h arpa/nameser.h resolv.h sys/un.h net/if_utun.h sys/kern_control.h],
 	,
 	,
 	[[${SOCKET_INCLUDES}]]
doc/man-sections/client-options.rst +25 -0
index af21fbcd..2ed9655d 100644
@@ -307,10 +307,117 @@ configuration.
   specification (4/6 suffix), OpenVPN will try both IPv4 and IPv6
   addresses, in the order getaddrinfo() returns them.
 
+--remote-srv args
+  Remote DNS SRV domain, service name and protocol.
+
+  Valid syntaxes:
+  ::
+
+     remote-srv domain
+     remote-srv domain service
+     remote-srv domain service proto
+
+  The ``service`` and ``proto`` arguments are optional. Client will try
+  to resolve DNS SRV record ``_service._proto.domain`` and use returned
+  DNS SRV records as remote server list ordered by server selection
+  mechanism defined in `RFC 2782 <https://tools.ietf.org/html/rfc2782>`_:
+  ::
+
+    A client MUST attempt to contact the target host with the
+    lowest-numbered priority field value it can reach, target hosts
+    with the same priority SHOULD be tried in an order defined by the
+    weight field.
+    The weight field specifies a relative weight for entries with the
+    same priority. Larger weights SHOULD be given a proportionately
+    higher probability of being selected.
+    Domain administrators SHOULD use Weight 0 when there isn't any
+    server selection to do. In the presence of records containing

doc/man-sections/client-options.rst configuration. · line 344

Quoted 10 lines
doc/man-sections/client-options.rst +10 -0
+    weights greater than 0, records with Weight 0 SHOULD have a very
+    small chance of being selected.
+
+  *Note:*
+    OpenVPN server selection mechanism implementation indeed will give
+    records with weight of zero a very small chance of being selected
+    first, but never skip them.
+
+  The ``service`` argument indicates the symbolic name of the desired
+  service. By default it is :code:`openvpn` registered service name.

The last sentenced feels odd to me. But I am no native speaker I would word that as:

By default service is the registered service name :code:openvpn.

Quoted 34 lines
doc/man-sections/client-options.rst +34 -0
+
+  The ``proto`` argument indicates the symbolic name of the desired
+  protocol and the protocol to use when connecting with the remote, and
+  may either be :code:`tcp`, :code:`udp` or special value :code:`auto`
+  used by default to try both. In this case all the discovered remote
+  hosts will be ordered by server selection mechanism regardless their
+  protocol. To enforce IPv4 or IPv6 connections add a :code:`4` or
+  :code:`6` suffix; like :code:`udp4` / :code:`udp6` / :code:`tcp4` /
+  :code:`tcp6` / :code:`auto4` / :code:`auto6`.
+
+  On the client, multiple ``--remote-srv`` options may be specified for
+  redundancy, each referring to a different DNS SRV record name, in the
+  order specified by the list of ``--remote-srv`` options. Specifying
+  multiple ``--remote-srv`` options for this purpose is a special case
+  of the more general connection-profile feature. See the
+  ``<connection>`` documentation below.
+
+  The client will move on to the next DNS SRV record in the ordered list,
+  in the event of connection failure. Note that at any given time, the
+  OpenVPN client will at most be connected to one server.
+
+  If particular DNS SRV record next resolves to multiple IP addresses,
+  OpenVPN will try them in the order that the system getaddrinfo()
+  presents them, so prioritization and DNS randomization is done by the
+  system library. Unless an IP version is forced by the protocol
+  specification (4/6 suffix), OpenVPN will try both IPv4 and IPv6
+  addresses, in the order getaddrinfo() returns them.
+
+  Examples:
+  ::
+
+     remote-srv example.net
+     remote-srv example.net openvpn
+     remote-srv example.net openvpn tcp

doc/man-sections/client-options.rst configuration. · line 388

Quoted 10 lines
doc/man-sections/client-options.rst +10 -0
+
+  Example of DNS SRV records:
+  ::
+
+     name                             prio weight port target
+     _openvpn._udp.example.net IN SRV 10   60     1194 server1.example.net
+     _openvpn._udp.example.net IN SRV 10   40     1194 server2.example.net
+     _openvpn._udp.example.net IN SRV 10   0      1194 server3.example.net
+     _openvpn._tcp.example.net IN SRV 20   0       443 server4.example.net
+

Same problem with missing . at the end of the domain. I ended up with:

2020-10-19 17:43:16 Resolved remote service host:

openpvn.blinkt.de.blinkt.de:1198,udp prio 10 weight 60

which is semi helpful.

Quoted 14 lines
doc/man-sections/client-options.rst +14 -0
+  For ``--remote-srv example.net`` following will happen in order:
+
+  1. The client will first try to resolve ``_openvpn._udp.example.net``
+     and ``_openvpn._tcp.example.net``.
+  2. Records ``server1.example.net:1194``, ``server2.example.net:1194``
+     and ``server3.example.net:1194`` will be selected before record
+     ``server4.example.net:443`` as their priority 10 is smaller than 20.
+  3. Records ``server1.example.net:1194``, ``server2.example.net:1194``
+     and ``server3.example.net:1194`` will be randomly selected with
+     weight probability: first will be either ``server1.example.net:1194``
+     with 60% probability or ``server2.example.net:1194`` with 40% or
+     ``server3.example.net:1194`` with almost zero probability.
+  4. If ``server1.example.net:1194`` was selected, the second record will
+     be either ``server2.example.net:1194`` with almost 100% probability

doc/man-sections/client-options.rst configuration. · line 412

Quoted 10 lines
doc/man-sections/client-options.rst +10 -0
+     or ``server3.example.net:1194`` with almost 0%.
+  5. If ``server2.example.net:1194`` was selected, the third record will
+     be the only last record of priority 10 - ``server3.example.net:1194``.
+  6. Record ``server4.example.net:443`` will be the last one selected as
+     the only record with priority 20.
+  7. Each of the resulting ```target:port`` remote hosts will be resolved
+     and accessed if its protocol has no conflict with the rest of the
+     OpenVPN options.
+
+  If DNS SRV name can't be resolved or no valid records were returned,

If /a/ DNS SRV name.

Use cannot rather than the informal "can't".
Also are instead of were to keep tenses the same in both sentences.

doc/man-sections/client-options.rst configuration. · line 414

Quoted 2 lines
doc/man-sections/client-options.rst +2 -0
+  client will move on to the next connection entry.
+

the client

doc/man-sections/client-options.rst configuration. · line 420

Quoted 9 lines
doc/man-sections/client-options.rst +5 -3
+  For more information on DNS SRV see https://tools.ietf.org/html/rfc2782
+
 --remote-random
-  When multiple ``--remote`` address/ports are specified, or if connection
-  profiles are being used, initially randomize the order of the list as a
-  kind of basic load-balancing measure.
+  When multiple ``--remote`` address/ports or ``--remote-srv`` records are
+  specified, or if connection profiles are being used, initially randomize
+  the order of the list as a kind of basic load-balancing measure.

This is now even more confusing. I would completely rewrite it and not that remote-srv is better.

--remote-random
Randomises the order of ``--remote-srv``, ``remote-srv`` and
connection profiles on start. This randomisationof these entries as a kind of basic load-balancing measure. Note that implementing DNS SRV entries (with a short TTL if it should be dynamic) and remote-srv is a better alternative for client-side load balancing.

doc/man-sections/client-options.rst configuration.

Quoted 13 lines
doc/man-sections/client-options.rst +13 -0
+}
+
+#else
+/*
+ * Queries DNS SRV records for specified DNS domain.
+ * Returns EAI_* status and service list on success in order of receive.
+ */
+static int
+query_servinfo_posix(const char *domain, int proto,
+                     struct servinfo *next, struct servinfo **res)
+{
+    unsigned char answer[NS_MAXMSG];
+    int status;

on macOS:

../../../openvpn-git/src/openvpn/socket.c:672:26: error: use of undeclared

      identifier 'NS_MAXMSG'
    unsigned char answer[NS_MAXMSG];

I used

#ifndef NS_MAXMSG
#define NS_MAXMSG 65335
#endif

for my testing in that function

Quoted 105 lines
doc/man-sections/client-options.rst +105 -0
+
+    int n = res_query(domain, ns_c_in, ns_t_srv, answer, NS_MAXMSG);
+    dmsg(D_SOCKET_DEBUG, "RES_QUERY class=%d type=%d domain=%s result=%d",
+         ns_c_in, ns_t_srv, domain, n);
+    if (n < 0)
+    {
+        switch (h_errno)
+        {
+            case HOST_NOT_FOUND:
+                return EAI_NONAME;
+
+            case NO_ADDRESS:
+#if NO_ADDRESS != NO_DATA
+            case NO_DATA:
+#endif
+                return EAI_NODATA;
+
+            case NO_RECOVERY:
+                return EAI_FAIL;
+
+            case TRY_AGAIN:
+                return EAI_AGAIN;
+        }
+        return EAI_SYSTEM;
+    }
+
+    ns_msg msg;
+    if (ns_initparse(answer, n, &msg) < 0)
+    {
+        return EAI_FAIL;
+    }
+
+    struct servinfo *list = NULL, *first = NULL;
+    for (int i = 0; i < ns_msg_count(msg, ns_s_an); i++)
+    {
+        ns_rr rr;
+
+        if (ns_parserr(&msg, ns_s_an, i, &rr) == 0
+            && ns_rr_type(rr) == ns_t_srv)
+        {
+            const unsigned char *rdata = ns_rr_rdata(rr);
+            char name[NS_MAXDNAME];
+
+            if (ns_rr_rdlen(rr) > 6
+                && dn_expand(ns_msg_base(msg), ns_msg_end(msg),
+                             rdata + 6, name, sizeof(name)) > 0 && *name)
+            {
+                struct servinfo *si = alloc_servinfo(name,
+                                                     ns_get16(rdata + 4),
+                                                     proto);
+                if (!si)
+                {
+                    freeservinfo(list);
+                    status = EAI_MEMORY;
+                    goto done;
+                }
+                si->prio = ns_get16(rdata);
+                si->weight = ns_get16(rdata + 2);
+                si->next = list, list = si;
+                if (!first)
+                {
+                    first = si;
+                }
+            }
+        }
+    }
+    if (list)
+    {
+        first->next = next;
+        *res = list;
+        status = 0;
+    }
+    else
+    {
+        status = EAI_NODATA;
+    }
+
+done:
+    return status;
+}
+#endif
+
+/*
+ * Service structure compare function for server selection
+ * mechanism, defined in RFC 2782.
+ */
+static int
+servinfo_cmp(const void *a, const void *b)
+{
+    const struct servinfo *ae = *(struct servinfo **)a;
+    const struct servinfo *be = *(struct servinfo **)b;
+
+    /* lowest-numbered priority first */
+    if (ae->prio != be->prio)
+    {
+        return ae->prio < be->prio ? -1 : 1;
+    }
+
+    /* zero-weighted first */
+    if ((ae->weight == 0 && be->weight)
+        || (ae->weight && be->weight == 0))
+    {
+        return ae->weight < be->weight ? -1 : 1;
+    }
+

doc/man-sections/client-options.rst

Quoted 10 lines
doc/man-sections/client-options.rst +10 -0
+    /* else keep received order, can't be equal */
+    return ae->order > be->order ? -1 : 1;
+}
+
+/*
+ * Sort & order service list according server selection mechanism,
+ * defined in RFC 2782.
+ * Returns service list. Although specific elements can be freed,
+ * non-empty list can never become empty.
+ */

The comment about freed elements only applies if the #if 0 block is enabled, right? I would remove this. And in general it is better to have the function comments as doxygen style comments.

Quoted 76 lines
doc/man-sections/client-options.rst +76 -0
+static struct servinfo *
+sort_servinfo(struct servinfo *list)
+{
+    struct servinfo ordered, *tail = &ordered;
+    int count = 0;
+    struct gc_arena gc = gc_new();
+
+    ASSERT(list);
+
+    /* count and number entries in reverse order */
+    for (struct servinfo *si = list; si; si = si->next)
+    {
+        si->order = count++;
+    }
+
+    struct servinfo **sorted;
+    ALLOC_ARRAY_CLEAR_GC(sorted, struct servinfo *, count, &gc);
+    for (struct servinfo *si = list; si; si = si->next)
+    {
+        sorted[si->order] = si;
+    }
+
+    /* sort records by priority and zero weight */
+    qsort(sorted, count, sizeof(sorted[0]), servinfo_cmp);
+
+    /* apply weighted selection mechanism */
+    ordered.next = NULL;
+    for (int i = 0; i < count;)
+    {
+        struct servinfo unordered;
+
+        /* compute the sum of the weights of records of the same
+         * priority and put them in the unordered list */
+        unordered.prio = sorted[i]->prio;
+        unordered.weight = 0;
+        unordered.next = NULL;
+        for (struct servinfo *prev = &unordered;
+             i < count && sorted[i]->prio == unordered.prio; i++)
+        {
+            unordered.weight += sorted[i]->weight;
+
+            /* add entry to the tail of unordered list */
+            sorted[i]->next = NULL;
+            prev->next = sorted[i], prev = sorted[i];
+        }
+
+        /* process the unordered list */
+        while (unordered.next)
+        {
+            /* choose a uniform random number between 0 and the sum
+             * computed (inclusive) */
+            int weight = get_random() % (unordered.weight + 1);
+
+            /* select the entries whose running sum value is the first
+             * in the selected order which is greater than or equal
+             * to the random number selected */
+            for (struct servinfo *si = unordered.next, *prev = &unordered;
+                 si; prev = si, si = si->next)
+            {
+                /* selected entry is the next one to be contacted */
+                if (si->weight >= weight)
+                {
+                    unordered.weight -= si->weight;
+
+                    /* move entry to the ordered list */
+                    prev->next = si->next;
+                    si->next = NULL;
+                    tail->next = si, tail = si;
+
+                    /*
+                     * RFC 2782 is ambiguous, it says:
+                     *   In the presence of records containing weights greater
+                     *   than 0, records with weight 0 should have a very
+                     *   small chance of being selected.
+                     * According that, within the same priority, after all
+                     * records containing weights greater than 0 were selected,

doc/man-sections/client-options.rst

Quoted 10 lines
doc/man-sections/client-options.rst +10 -0
+                     * the rest of records with weight 0 should be skipped.
+                     * At the same time, it says:
+                     *   The following algorithm SHOULD be used to order the
+                     *   SRV RRs of the same priority:
+                     *   ...
+                     *   Continue the ordering process until there are no
+                     *   unordered SRV RRs.
+                     * This means records with wight 0 should always be
+                     * selected, as last ones in worst case.
+                     */

.... We implement the second option.

doc/man-sections/client-options.rst

Quoted 12 lines
doc/man-sections/client-options.rst +12 -0
+#if 0
+                    /*
+                     * Skip all the rest records with weight 0 after the last
+                     * one with weight greater than 0.
+                     */
+                    if (unordered.weight == 0 && si->weight)
+                    {
+                        freeservinfo(unordered.next);
+                        unordered.next = NULL;
+                    }
+                    break;
+#endif

Lets not add a #if 0 here

rather use a comment here that notes that we never skip records or something like that.

Quoted 54 lines
doc/man-sections/client-options.rst +54 -0
+                }
+                weight -= si->weight;
+            }
+        }
+    }
+
+    gc_free(&gc);
+    return ordered.next;
+}
+
+
+/*
+ * Resolves DNS SRV records for specified domain and service.
+ * Returns EAI_* status (like getaddrinfo) and service list, ordered
+ * according server selection mechanism, defined in RFC 2782.
+ */
+static int
+getservinfo(const char *domain,
+            const char *service,
+            int flags,
+            struct servinfo **res)
+{
+    static const struct {
+        int flags;
+        int proto;
+        const char *name;
+    } proto[] = {
+        { GETADDR_DATAGRAM, PROTO_UDP, "udp" },
+        { GETADDR_STREAM, PROTO_TCP_CLIENT, "tcp" }
+    };
+    struct servinfo *list = NULL;
+    int status = EAI_SOCKTYPE;
+
+    ASSERT(res);
+
+    if (!domain)
+    {
+        return EAI_NONAME;
+    }
+    if (!service)
+    {
+        return EAI_SERVICE;
+    }
+
+    int proto_flags = flags & GETADDR_PROTO_MASK;
+    for (int i = 0; i < SIZE(proto); i++)
+    {
+        if (proto_flags & proto[i].flags)
+        {
+            proto_flags &= ~proto[i].flags;
+
+            char qname[256];
+            if (!openvpn_snprintf(qname, sizeof(qname), "_%s._%s.%s",
+                                  service, proto[i].name, domain))

doc/man-sections/client-options.rst

Quoted 10 lines
doc/man-sections/client-options.rst +10 -0
+            {
+                freeservinfo(list);
+                return EAI_MEMORY;
+            }
+
+#ifdef _WIN32
+            status = query_servinfo_win32(qname, proto[i].proto, list, &list);
+#else
+            status = query_servinfo_posix(qname, proto[i].proto, list, &list);
+#endif

I think we should name those two function identical. They are doing identical stuff, so need for this ifdef and different function names.

Quoted 16 lines

bool

doc/man-sections/client-options.rst +13 -0
+/* struct to hold resolved service targets */
+struct servinfo
+{
+    const char *hostname;
+    const char *servname;
+    int proto;
+    int order;
+    unsigned short prio;
+    unsigned short weight;
+    struct addrinfo *ai;
+    struct servinfo *next;
+};
+
 /* struct to hold preresolved host names */

doc/man-sections/client-options.rst

Quoted 10 lines
doc/man-sections/client-options.rst +4 -1
 struct cached_dns_entry {
     const char *hostname;
     const char *servname;
     int ai_family;
     int flags;
-    struct addrinfo *ai;
+    union {
+        struct addrinfo *ai;
+        struct servinfo *si;
+    };

Is saving the space for one pointer really worth the potential danger of accidentially using an addrinfo as servinfo or vice versa?

I tested the patch and it works as expected (apart from things mentioned here).

But this should not be a legal config:

<connection>
remote foo.bar
remote-srv blinkt.de ovpn
</connection>

In a connection entry there should be only one of remote or remote-srv be allowed.

Arne

#9 lore raw

Hi Arne,

Thank you for the review and please refer v9 where all the mentioned parts are handled.

--
Best Regards, Vladislav Grishenko

Quoted 708 lines

-----Original Message-----
From: Arne Schwabe <[email protected]...>
Sent: Tuesday, October 20, 2020 11:58 AM
To: Vladislav Grishenko <[email protected]...>; openvpn- [email protected]
Subject: Re: [Openvpn-devel] [PATCH v8] Add DNS SRV remote host discovery support

Am 05.10.20 um 00:36 schrieb Vladislav Grishenko:

Quoted 38 lines

DNS SRV remote host discovery allows to have multiple OpenVPN servers for a single domain w/o explicit profile enumeration, to move services from host to host with little fuss, and to designate hosts as primary servers for a service and others as backups.
Feature has been asked several times already, should be useful in case of substantial number of clients & servers deployed.

Patch introduces "--remote-srv domain [service] [proto]" option. The "service" and "proto" arguments are optional. Client will try to resolve DNS SRV record "_service._proto.domain" and use returned DNS SRV records as remote server list ordered by server selection mechanism defined in RFC2782 (https://tools.ietf.org/html/rfc2782):

A client MUST attempt to contact the target host with the lowest-numbered priority field value it can reach, target hosts with the same priority SHOULD be tried in an order defined by the weight field.
The weight field specifies a relative weight for entries with the same priority. Larger weights SHOULD be given a proportionately higher probability of being selected.
Domain administrators SHOULD use Weight 0 when there isn't any server selection to do. In the presence of records containing weights greater than 0, records with Weight 0 SHOULD have a very small chance of being selected.

Note: OpenVPN server selection mechanism implementation indeed will give records with weight of zero a very small chance of being selected first, but never skip them.

Example: instead of multiple --remote in order:
remote server1.example.net 1194 udp
remote server2.example.net 1194 udp
remote server3.example.net 1194 udp
remote server4.example.net 443 tcp

now it's possible to specify just one --remote-srv:
remote-srv example.net

Quoted 6 lines

and configure following DNS SRV records:
name prio weight port target
_openvpn._udp.example.net IN SRV 10 60 1194 server1.example.net
_openvpn._udp.example.net IN SRV 10 40 1194 server2.example.net
_openvpn._udp.example.net IN SRV 10 0 1194 server3.example.net
_openvpn._tcp.example.net IN SRV 20 0 443 server4.example.net

Missing . at the end at least if it should be in a bind zone file:

_openvpn._udp.example.net. IN SRV 10 60 1194 server1.example.net.

or

_openvpn._udp IN SRV 10 60 1194 server1.example.net.

Quoted 94 lines

For "--remote-srv example.net" following will happen in order:
1. The client will first try to resolve "_openvpn._udp.example.net" and "_openvpn._tcp.example.net".
2. Records "server1.example.net:1194", "server2.example.net:1194" and "server3.example.net:1194" will be selected before record "server4.example.net:443" as their priority 10 is smaller than 20.
3. Records "server1.example.net:1194", "server2.example.net:1194" and "server3.example.net:1194" will be randomly selected with weight probability: first will be either "server1.example.net:1194" with 60% probability or "server2.example.net:1194" with 40% or "server3.example.net:1194" with almost zero probability.
4. If "server1.example.net:1194" was selected, the second record will be either "server2.example.net:1194" with almost 100% probability or "server3.example.net:1194" with almost 0%.
5. If "server2.example.net:1194" was selected, the third record will be the only last record of priority 10 - "server3.example.net:1194".
6. Record "server4.example.net:443" will be the last one selected as the only record with priority 20.
7. Each of the resulting "target:port" remote hosts will be resolved and accessed if its protocol has no conflict with the rest of the OpenVPN options.

If DNS SRV name can't be resolved or no valid records were returned, client will move on to the next connection entry.

v2:
- use DNS SRV for feature naming
- change option name to --remote-service-discovery
- add --remote-service-discovery [service] optional parameter support
- rewrite man, add algo/prio/weight description and examples
- fix random weight selection was not implicit
- remove pulled REMOTE_DISCOVERY support, not needed
- split windows/unix-specific parts into extra functions
- put functions into servinfo scope, add doxygen comments
- remove addrinfo hack, use servinfo containers of addrinfo list
- better proxy support (tcp mode not supported so far)
- log discovery attempts and results, if enabled

v3:
- complete logic rewrite
- use separate --remote-srv [service] [proto] option
- remove fallback, additional --remote/--remote-srv does the same
- add "auto" protocol support to allow both udp & tcp discoverery
- add support for tcp / http proxy (natively)
- man update

v4:
- due RFC 2782 ambiguity, prefer to use all resolved DNS SRV records, even ones with weight 0 after the records containing weights greater than 0 were all selected, keep related code disabled for historical reasons.
- man update

v5: rebase against upstream with connection advancing fix
- allow management skip/accept for remote service hosts as for --remote
- improve compatibility with a way "--persist-remote-ip" is handled
- ensure max line length is 80

v6:
- pick out code-style conformant changes into separate patch
- add more options checks and comments

v7:
- prefer line breaks before long string parameters
- use win32/posix suffixes for query_servinfo

v8:
- rework compatibility with --preresolve and --persist-remote-ip
- fix dns data structures leak on wine/win32
- add priority and weight logging

---
 configure.ac                        |   2 +-
 doc/man-sections/client-options.rst | 117 +++-
 doc/management-notes.txt            |   6 +
 src/openvpn/Makefile.am             |   2 +-
 src/openvpn/buffer.h                |   5 -
 src/openvpn/errlevel.h              |   1 +
 src/openvpn/init.c                  |  79 ++-
 src/openvpn/openvpn.vcxproj         |   8 +-
 src/openvpn/options.c               | 268 +++++++--
 src/openvpn/options.h               |   4 +
 src/openvpn/socket.c                | 854 +++++++++++++++++++++++++++-
 src/openvpn/socket.h                |  58 +-
 src/openvpn/syshead.h               |   5 +
 13 files changed, 1328 insertions(+), 81 deletions(-)
configure.ac index ebb32204..22088aaf renamed from configure.ac +0 -0

100644

configure.ac SOCKET_INCLUDES=" · line 480

Quoted 4 lines
configure.ac +0 -1
@@ -477,7 +477,7 @@ SOCKET_INCLUDES="
 "
 
 AC_CHECK_HEADERS(
-	[net/if.h netinet/ip.h resolv.h sys/un.h net/if_utun.h

sys/kern_control.h],

Quoted 18 lines
configure.ac +2 -0
+	[net/if.h netinet/ip.h arpa/nameser.h resolv.h sys/un.h
+net/if_utun.h sys/kern_control.h],
 	,
 	,
 	[[${SOCKET_INCLUDES}]]
doc/man-sections/client-options.rst +4 -0
index af21fbcd..2ed9655d 100644
@@ -307,10 +307,117 @@ configuration.
   specification (4/6 suffix), OpenVPN will try both IPv4 and IPv6
   addresses, in the order getaddrinfo() returns them.
 
+--remote-srv args
+  Remote DNS SRV domain, service name and protocol.
+
+  Valid syntaxes:

doc/man-sections/client-options.rst configuration. · line 323

Quoted 10 lines
doc/man-sections/client-options.rst +10 -0
+  ::
+
+     remote-srv domain
+     remote-srv domain service
+     remote-srv domain service proto
+
+  The ``service`` and ``proto`` arguments are optional. Client will
+ try  to resolve DNS SRV record ``_service._proto.domain`` and use
+ returned  DNS SRV records as remote server list ordered by server
+ selection  mechanism defined in `RFC 2782

<https://tools.ietf.org/html/rfc2782>`_:

Quoted 11 lines
doc/man-sections/client-options.rst +11 -0
+  ::
+
+    A client MUST attempt to contact the target host with the
+    lowest-numbered priority field value it can reach, target hosts
+    with the same priority SHOULD be tried in an order defined by the
+    weight field.
+    The weight field specifies a relative weight for entries with the
+    same priority. Larger weights SHOULD be given a proportionately
+    higher probability of being selected.
+    Domain administrators SHOULD use Weight 0 when there isn't any
+    server selection to do. In the presence of records containing

doc/man-sections/client-options.rst configuration. · line 344

Quoted 10 lines
doc/man-sections/client-options.rst +10 -0
+    weights greater than 0, records with Weight 0 SHOULD have a very
+    small chance of being selected.
+
+  *Note:*
+    OpenVPN server selection mechanism implementation indeed will give
+    records with weight of zero a very small chance of being selected
+    first, but never skip them.
+
+  The ``service`` argument indicates the symbolic name of the desired
+ service. By default it is :code:`openvpn` registered service name.

The last sentenced feels odd to me. But I am no native speaker I would word that as:

By default service is the registered service name :code:openvpn.

Quoted 34 lines
doc/man-sections/client-options.rst +34 -0
+
+  The ``proto`` argument indicates the symbolic name of the desired
+ protocol and the protocol to use when connecting with the remote,
+ and  may either be :code:`tcp`, :code:`udp` or special value
+ :code:`auto`  used by default to try both. In this case all the
+ discovered remote  hosts will be ordered by server selection
+ mechanism regardless their  protocol. To enforce IPv4 or IPv6
+ connections add a :code:`4` or  :code:`6` suffix; like :code:`udp4`
+ / :code:`udp6` / :code:`tcp4` /  :code:`tcp6` / :code:`auto4` / :code:`auto6`.
+
+  On the client, multiple ``--remote-srv`` options may be specified
+ for  redundancy, each referring to a different DNS SRV record name,
+ in the  order specified by the list of ``--remote-srv`` options.
+ Specifying  multiple ``--remote-srv`` options for this purpose is a
+ special case  of the more general connection-profile feature. See
+ the  ``<connection>`` documentation below.
+
+  The client will move on to the next DNS SRV record in the ordered
+ list,  in the event of connection failure. Note that at any given
+ time, the  OpenVPN client will at most be connected to one server.
+
+  If particular DNS SRV record next resolves to multiple IP
+ addresses,  OpenVPN will try them in the order that the system
+ getaddrinfo()  presents them, so prioritization and DNS
+ randomization is done by the  system library. Unless an IP version
+ is forced by the protocol  specification (4/6 suffix), OpenVPN will
+ try both IPv4 and IPv6  addresses, in the order getaddrinfo() returns them.
+
+  Examples:
+  ::
+
+     remote-srv example.net
+     remote-srv example.net openvpn
+     remote-srv example.net openvpn tcp

doc/man-sections/client-options.rst configuration. · line 388

Quoted 10 lines
doc/man-sections/client-options.rst +10 -0
+
+  Example of DNS SRV records:
+  ::
+
+     name                             prio weight port target
+     _openvpn._udp.example.net IN SRV 10   60     1194 server1.example.net
+     _openvpn._udp.example.net IN SRV 10   40     1194 server2.example.net
+     _openvpn._udp.example.net IN SRV 10   0      1194 server3.example.net
+     _openvpn._tcp.example.net IN SRV 20   0       443 server4.example.net
+

Same problem with missing . at the end of the domain. I ended up with:

2020-10-19 17:43:16 Resolved remote service host:

openpvn.blinkt.de.blinkt.de:1198,udp prio 10 weight 60

which is semi helpful.

Quoted 15 lines
doc/man-sections/client-options.rst +15 -0
+  For ``--remote-srv example.net`` following will happen in order:
+
+  1. The client will first try to resolve ``_openvpn._udp.example.net``
+     and ``_openvpn._tcp.example.net``.
+  2. Records ``server1.example.net:1194``, ``server2.example.net:1194``
+     and ``server3.example.net:1194`` will be selected before record
+     ``server4.example.net:443`` as their priority 10 is smaller than 20.
+  3. Records ``server1.example.net:1194``, ``server2.example.net:1194``
+     and ``server3.example.net:1194`` will be randomly selected with
+     weight probability: first will be either ``server1.example.net:1194``
+     with 60% probability or ``server2.example.net:1194`` with 40% or
+     ``server3.example.net:1194`` with almost zero probability.
+  4. If ``server1.example.net:1194`` was selected, the second record will
+     be either ``server2.example.net:1194`` with almost 100% probability
+     or ``server3.example.net:1194`` with almost 0%.

doc/man-sections/client-options.rst configuration.

Quoted 10 lines
doc/man-sections/client-options.rst +10 -0
+  5. If ``server2.example.net:1194`` was selected, the third record will
+     be the only last record of priority 10 - ``server3.example.net:1194``.
+  6. Record ``server4.example.net:443`` will be the last one selected as
+     the only record with priority 20.
+  7. Each of the resulting ```target:port`` remote hosts will be resolved
+     and accessed if its protocol has no conflict with the rest of the
+     OpenVPN options.
+
+  If DNS SRV name can't be resolved or no valid records were
+ returned,

If /a/ DNS SRV name.

Use cannot rather than the informal "can't".
Also are instead of were to keep tenses the same in both sentences.

doc/man-sections/client-options.rst configuration. · line 415

Quoted 2 lines
doc/man-sections/client-options.rst +2 -0
+  client will move on to the next connection entry.
+

the client

doc/man-sections/client-options.rst

Quoted 12 lines
doc/man-sections/client-options.rst +3 -1
+  For more information on DNS SRV see
+ https://tools.ietf.org/html/rfc2782
+
 --remote-random
-  When multiple ``--remote`` address/ports are specified, or if

connection
- profiles are being used, initially randomize the order of the list as a

doc/man-sections/client-options.rst +3 -1
-  kind of basic load-balancing measure.
+  When multiple ``--remote`` address/ports or ``--remote-srv``
+ records are  specified, or if connection profiles are being used,
+ initially randomize  the order of the list as a kind of basic load-balancing

measure.

This is now even more confusing. I would completely rewrite it and not that remote-srv is better.

--remote-random
Randomises the order of ``--remote-srv``, ``remote-srv`` and connection
profiles on start. This randomisationof these entries as a kind of basic load- balancing measure. Note that implementing DNS SRV entries (with a short TTL if it should be dynamic) and remote-srv is a better alternative for client-side load balancing.

doc/man-sections/client-options.rst

Quoted 12 lines
doc/man-sections/client-options.rst +12 -0
+}
+
+#else
+/*
+ * Queries DNS SRV records for specified DNS domain.
+ * Returns EAI_* status and service list on success in order of receive.
+ */
+static int
+query_servinfo_posix(const char *domain, int proto,
+                     struct servinfo *next, struct servinfo **res) {
+    unsigned char answer[NS_MAXMSG];
+    int status;

on macOS:

../../../openvpn-git/src/openvpn/socket.c:672:26: error: use of undeclared

      identifier 'NS_MAXMSG'
    unsigned char answer[NS_MAXMSG];

I used

#ifndef NS_MAXMSG
#define NS_MAXMSG 65335
#endif

for my testing in that function

doc/man-sections/client-options.rst

Quoted 3 lines
doc/man-sections/client-options.rst +3 -0
+
+    int n = res_query(domain, ns_c_in, ns_t_srv, answer, NS_MAXMSG);
+    dmsg(D_SOCKET_DEBUG, "RES_QUERY class=%d type=%d domain=%s

result=%d",

Quoted 100 lines
doc/man-sections/client-options.rst +100 -0
+         ns_c_in, ns_t_srv, domain, n);
+    if (n < 0)
+    {
+        switch (h_errno)
+        {
+            case HOST_NOT_FOUND:
+                return EAI_NONAME;
+
+            case NO_ADDRESS:
+#if NO_ADDRESS != NO_DATA
+            case NO_DATA:
+#endif
+                return EAI_NODATA;
+
+            case NO_RECOVERY:
+                return EAI_FAIL;
+
+            case TRY_AGAIN:
+                return EAI_AGAIN;
+        }
+        return EAI_SYSTEM;
+    }
+
+    ns_msg msg;
+    if (ns_initparse(answer, n, &msg) < 0)
+    {
+        return EAI_FAIL;
+    }
+
+    struct servinfo *list = NULL, *first = NULL;
+    for (int i = 0; i < ns_msg_count(msg, ns_s_an); i++)
+    {
+        ns_rr rr;
+
+        if (ns_parserr(&msg, ns_s_an, i, &rr) == 0
+            && ns_rr_type(rr) == ns_t_srv)
+        {
+            const unsigned char *rdata = ns_rr_rdata(rr);
+            char name[NS_MAXDNAME];
+
+            if (ns_rr_rdlen(rr) > 6
+                && dn_expand(ns_msg_base(msg), ns_msg_end(msg),
+                             rdata + 6, name, sizeof(name)) > 0 && *name)
+            {
+                struct servinfo *si = alloc_servinfo(name,
+                                                     ns_get16(rdata + 4),
+                                                     proto);
+                if (!si)
+                {
+                    freeservinfo(list);
+                    status = EAI_MEMORY;
+                    goto done;
+                }
+                si->prio = ns_get16(rdata);
+                si->weight = ns_get16(rdata + 2);
+                si->next = list, list = si;
+                if (!first)
+                {
+                    first = si;
+                }
+            }
+        }
+    }
+    if (list)
+    {
+        first->next = next;
+        *res = list;
+        status = 0;
+    }
+    else
+    {
+        status = EAI_NODATA;
+    }
+
+done:
+    return status;
+}
+#endif
+
+/*
+ * Service structure compare function for server selection
+ * mechanism, defined in RFC 2782.
+ */
+static int
+servinfo_cmp(const void *a, const void *b) {
+    const struct servinfo *ae = *(struct servinfo **)a;
+    const struct servinfo *be = *(struct servinfo **)b;
+
+    /* lowest-numbered priority first */
+    if (ae->prio != be->prio)
+    {
+        return ae->prio < be->prio ? -1 : 1;
+    }
+
+    /* zero-weighted first */
+    if ((ae->weight == 0 && be->weight)
+        || (ae->weight && be->weight == 0))
+    {
+        return ae->weight < be->weight ? -1 : 1;
+    }

doc/man-sections/client-options.rst

Quoted 10 lines
doc/man-sections/client-options.rst +10 -0
+
+    /* else keep received order, can't be equal */
+    return ae->order > be->order ? -1 : 1; }
+
+/*
+ * Sort & order service list according server selection mechanism,
+ * defined in RFC 2782.
+ * Returns service list. Although specific elements can be freed,
+ * non-empty list can never become empty.
+ */

The comment about freed elements only applies if the #if 0 block is enabled, right? I would remove this. And in general it is better to have the function comments as doxygen style comments.

Quoted 76 lines
doc/man-sections/client-options.rst +76 -0
+static struct servinfo *
+sort_servinfo(struct servinfo *list)
+{
+    struct servinfo ordered, *tail = &ordered;
+    int count = 0;
+    struct gc_arena gc = gc_new();
+
+    ASSERT(list);
+
+    /* count and number entries in reverse order */
+    for (struct servinfo *si = list; si; si = si->next)
+    {
+        si->order = count++;
+    }
+
+    struct servinfo **sorted;
+    ALLOC_ARRAY_CLEAR_GC(sorted, struct servinfo *, count, &gc);
+    for (struct servinfo *si = list; si; si = si->next)
+    {
+        sorted[si->order] = si;
+    }
+
+    /* sort records by priority and zero weight */
+    qsort(sorted, count, sizeof(sorted[0]), servinfo_cmp);
+
+    /* apply weighted selection mechanism */
+    ordered.next = NULL;
+    for (int i = 0; i < count;)
+    {
+        struct servinfo unordered;
+
+        /* compute the sum of the weights of records of the same
+         * priority and put them in the unordered list */
+        unordered.prio = sorted[i]->prio;
+        unordered.weight = 0;
+        unordered.next = NULL;
+        for (struct servinfo *prev = &unordered;
+             i < count && sorted[i]->prio == unordered.prio; i++)
+        {
+            unordered.weight += sorted[i]->weight;
+
+            /* add entry to the tail of unordered list */
+            sorted[i]->next = NULL;
+            prev->next = sorted[i], prev = sorted[i];
+        }
+
+        /* process the unordered list */
+        while (unordered.next)
+        {
+            /* choose a uniform random number between 0 and the sum
+             * computed (inclusive) */
+            int weight = get_random() % (unordered.weight + 1);
+
+            /* select the entries whose running sum value is the first
+             * in the selected order which is greater than or equal
+             * to the random number selected */
+            for (struct servinfo *si = unordered.next, *prev = &unordered;
+                 si; prev = si, si = si->next)
+            {
+                /* selected entry is the next one to be contacted */
+                if (si->weight >= weight)
+                {
+                    unordered.weight -= si->weight;
+
+                    /* move entry to the ordered list */
+                    prev->next = si->next;
+                    si->next = NULL;
+                    tail->next = si, tail = si;
+
+                    /*
+                     * RFC 2782 is ambiguous, it says:
+                     *   In the presence of records containing weights greater
+                     *   than 0, records with weight 0 should have a very
+                     *   small chance of being selected.
+                     * According that, within the same priority, after all
+                     * records containing weights greater than 0 were selected,

doc/man-sections/client-options.rst

Quoted 10 lines
doc/man-sections/client-options.rst +10 -0
+                     * the rest of records with weight 0 should be skipped.
+                     * At the same time, it says:
+                     *   The following algorithm SHOULD be used to order the
+                     *   SRV RRs of the same priority:
+                     *   ...
+                     *   Continue the ordering process until there are no
+                     *   unordered SRV RRs.
+                     * This means records with wight 0 should always be
+                     * selected, as last ones in worst case.
+                     */

.... We implement the second option.

doc/man-sections/client-options.rst

Quoted 12 lines
doc/man-sections/client-options.rst +12 -0
+#if 0
+                    /*
+                     * Skip all the rest records with weight 0 after the last
+                     * one with weight greater than 0.
+                     */
+                    if (unordered.weight == 0 && si->weight)
+                    {
+                        freeservinfo(unordered.next);
+                        unordered.next = NULL;
+                    }
+                    break;
+#endif

Lets not add a #if 0 here

rather use a comment here that notes that we never skip records or something like that.

Quoted 54 lines
doc/man-sections/client-options.rst +54 -0
+                }
+                weight -= si->weight;
+            }
+        }
+    }
+
+    gc_free(&gc);
+    return ordered.next;
+}
+
+
+/*
+ * Resolves DNS SRV records for specified domain and service.
+ * Returns EAI_* status (like getaddrinfo) and service list, ordered
+ * according server selection mechanism, defined in RFC 2782.
+ */
+static int
+getservinfo(const char *domain,
+            const char *service,
+            int flags,
+            struct servinfo **res)
+{
+    static const struct {
+        int flags;
+        int proto;
+        const char *name;
+    } proto[] = {
+        { GETADDR_DATAGRAM, PROTO_UDP, "udp" },
+        { GETADDR_STREAM, PROTO_TCP_CLIENT, "tcp" }
+    };
+    struct servinfo *list = NULL;
+    int status = EAI_SOCKTYPE;
+
+    ASSERT(res);
+
+    if (!domain)
+    {
+        return EAI_NONAME;
+    }
+    if (!service)
+    {
+        return EAI_SERVICE;
+    }
+
+    int proto_flags = flags & GETADDR_PROTO_MASK;
+    for (int i = 0; i < SIZE(proto); i++)
+    {
+        if (proto_flags & proto[i].flags)
+        {
+            proto_flags &= ~proto[i].flags;
+
+            char qname[256];
+            if (!openvpn_snprintf(qname, sizeof(qname), "_%s._%s.%s",
+                                  service, proto[i].name, domain))

doc/man-sections/client-options.rst

Quoted 10 lines
doc/man-sections/client-options.rst +10 -0
+            {
+                freeservinfo(list);
+                return EAI_MEMORY;
+            }
+
+#ifdef _WIN32
+            status = query_servinfo_win32(qname, proto[i].proto,
+list, &list); #else
+            status = query_servinfo_posix(qname, proto[i].proto,
+list, &list); #endif

I think we should name those two function identical. They are doing identical stuff, so need for this ifdef and different function names.

Quoted 19 lines

bool

doc/man-sections/client-options.rst +11 -0
+/* struct to hold resolved service targets */ struct servinfo {
+    const char *hostname;
+    const char *servname;
+    int proto;
+    int order;
+    unsigned short prio;
+    unsigned short weight;
+    struct addrinfo *ai;
+    struct servinfo *next;
+};
+
 /* struct to hold preresolved host names */  struct cached_dns_entry
{
     const char *hostname;
     const char *servname;
     int ai_family;
     int flags;

doc/man-sections/client-options.rst

Quoted 5 lines
doc/man-sections/client-options.rst +4 -1
-    struct addrinfo *ai;
+    union {
+        struct addrinfo *ai;
+        struct servinfo *si;
+    };

Is saving the space for one pointer really worth the potential danger of accidentially using an addrinfo as servinfo or vice versa?

I tested the patch and it works as expected (apart from things mentioned here).

But this should not be a legal config:

<connection>
remote foo.bar
remote-srv blinkt.de ovpn
</connection>

In a connection entry there should be only one of remote or remote-srv be allowed.

Arne

#10 lore raw

PATCH v9 1/1 Add DNS SRV remote host discovery support

In reply to Vladislav Grishenko

DNS SRV remote host discovery allows to have multiple OpenVPN servers for a single domain w/o explicit profile enumeration, to move services from host to host with little fuss, and to designate hosts as primary servers for a service and others as backups.
Feature has been asked several times already, should be useful in case of substantial number of clients & servers deployed.

Patch introduces "--remote-srv domain [service] [proto]" option. The "service" and "proto" arguments are optional. Client will try to resolve DNS SRV record "_service._proto.domain" and use returned DNS SRV records as remote server list ordered by server selection mechanism defined in RFC2782 (https://tools.ietf.org/html/rfc2782):

A client MUST attempt to contact the target host with the lowest-numbered priority field value it can reach, target hosts with the same priority SHOULD be tried in an order defined by the weight field.
The weight field specifies a relative weight for entries with the same priority. Larger weights SHOULD be given a proportionately higher probability of being selected.
Domain administrators SHOULD use Weight 0 when there isn't any server selection to do. In the presence of records containing weights greater than 0, records with Weight 0 SHOULD have a very small chance of being selected.

Note: OpenVPN server selection mechanism implementation indeed will give records with weight of zero a very small chance of being selected first, but never skip them.

Example: instead of multiple --remote in order, now it's possible to specify just one --remote-srv and configure DNS SRV records:

remote-srv example.net

name prio weight port target
$ORIGIN example.net.
_openvpn._udp IN SRV 10 60 1194 server1.example.net.
_openvpn._udp IN SRV 10 40 1194 server2.example.net.
_openvpn._udp IN SRV 10 0 1194 server3.example.net.
_openvpn._tcp IN SRV 20 0 443 server4.example.net.

For "--remote-srv example.net" following will happen in order:
1. The client will first try to resolve "_openvpn._udp.example.net" and "_openvpn._tcp.example.net".
2. Records "server1.example.net:1194", "server2.example.net:1194" and "server3.example.net:1194" will be selected before record "server4.example.net:443" as their priority 10 is smaller than 20.
3. Records "server1.example.net:1194", "server2.example.net:1194" and "server3.example.net:1194" will be randomly selected with weight probability: first will be either "server1.example.net:1194" with 60% probability or "server2.example.net:1194" with 40% or "server3.example.net:1194" with almost zero probability.
4. If "server1.example.net:1194" was selected, the second record will be either "server2.example.net:1194" with almost 100% probability or "server3.example.net:1194" with almost 0%.
5. If "server2.example.net:1194" was selected, the third record will be the only last record of priority 10 - "server3.example.net:1194".
6. Record "server4.example.net:443" will be the last one selected as the only record with priority 20.
7. Each of the resulting "target:port" remote hosts will be resolved and accessed if its protocol has no conflict with the rest of the OpenVPN options.

If DNS SRV name can't be resolved or no valid records were returned, client will move on to the next connection entry.

v9:
add get_cached_srv_entry() for servinfo vs addrinfo cache split add check for mixed --remote and --remote-srv
add doxygen dns srv functions comments
use query_servinfo() for both unix and windows
fix undefined NS_MAXMSG issue on macOS
fix man

---
 configure.ac                        |   2 +-
 doc/man-sections/client-options.rst | 121 +++-
 doc/management-notes.txt            |   6 +
 src/openvpn/Makefile.am             |   2 +-
 src/openvpn/buffer.h                |   5 -
 src/openvpn/errlevel.h              |   1 +
 src/openvpn/init.c                  |  79 ++-
 src/openvpn/openvpn.vcxproj         |   8 +-
 src/openvpn/options.c               | 286 +++++++--
 src/openvpn/options.h               |   4 +
 src/openvpn/socket.c                | 879 +++++++++++++++++++++++++++-
 src/openvpn/socket.h                |  54 ++
 src/openvpn/syshead.h               |   5 +
 13 files changed, 1378 insertions(+), 74 deletions(-)
configure.ac +1 -1
index 1ab8fe59..d110ba98 100644
@@ -470,7 +470,7 @@ SOCKET_INCLUDES="
 "
 
 AC_CHECK_HEADERS(
-	[net/if.h netinet/ip.h resolv.h sys/un.h net/if_utun.h sys/kern_control.h],
+	[net/if.h netinet/ip.h arpa/nameser.h resolv.h sys/un.h net/if_utun.h sys/kern_control.h],
 	,
 	,
 	[[${SOCKET_INCLUDES}]]
doc/man-sections/client-options.rst +116 -5

134 lines not on this page · raw message

doc/management-notes.txt +6 -0
index 61daaf07..d9d7394d 100644
@@ -851,6 +851,12 @@ the above notification, use this command:
 
   remote MOD vpn.otherexample.com 1234
 
+DNS SRV discovery domain and service name with protocol code:`auto`
+can't be overriden, but either accepted or skipped only.
+Example of such notification:
+
+  >REMOTE:example.com,openvpn,auto
+
 To accept the same host and port as the client would ordinarily
 have connected to, use this command:
 
src/openvpn/Makefile.am +1 -1
index 37b002c6..f7632047 100644
@@ -143,5 +143,5 @@ openvpn_LDADD = \
 	$(OPTIONAL_INOTIFY_LIBS)
 if WIN32
 openvpn_SOURCES += openvpn_win32_resources.rc block_dns.c block_dns.h ring_buffer.h
-openvpn_LDADD += -lgdi32 -lws2_32 -lwininet -lcrypt32 -liphlpapi -lwinmm -lfwpuclnt -lrpcrt4 -lncrypt -lsetupapi
+openvpn_LDADD += -lgdi32 -lws2_32 -lwininet -lcrypt32 -liphlpapi -lwinmm -lfwpuclnt -lrpcrt4 -lncrypt -lsetupapi -ldnsapi
 endif
src/openvpn/buffer.h +0 -5
index 1722ffd5..ae0cf0eb 100644
@@ -198,11 +198,6 @@ bool buf_init_debug(struct buffer *buf, int offset, const char *file, int line);
 
 
 /* inline functions */
-inline static void
-gc_freeaddrinfo_callback(void *addr)
-{
-    freeaddrinfo((struct addrinfo *) addr);
-}
 
 /** Return an empty struct buffer */
 static inline struct buffer
src/openvpn/errlevel.h +1 -0
index 5663f841..39f96e7d 100644
@@ -92,6 +92,7 @@
 #define D_PS_PROXY           LOGLEV(3, 44, 0)        /* messages related to --port-share option */
 #define D_PF_INFO            LOGLEV(3, 45, 0)        /* packet filter informational messages */
 #define D_IFCONFIG           LOGLEV(3, 0,  0)        /* show ifconfig info (don't mute) */
+#define D_RESOLVE            LOGLEV(3, 46, 0)        /* show hostname resolve info */
 
 #define D_SHOW_PARMS         LOGLEV(4, 50, 0)        /* show all parameters on program initiation */
 #define D_SHOW_OCC           LOGLEV(4, 51, 0)        /* show options compatibility string */
src/openvpn/init.c +72 -7

139 lines not on this page · raw message

src/openvpn/openvpn.vcxproj +4 -4
index 3863854b..1f317fb0 100644
@@ -92,7 +92,7 @@
     </ClCompile>
     <ResourceCompile />
     <Link>
-      <AdditionalDependencies>legacy_stdio_definitions.lib;Ncrypt.lib;libssl.lib;libcrypto.lib;lzo2.lib;pkcs11-helper.dll.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;%(AdditionalDependencies)</AdditionalDependencies>
+      <AdditionalDependencies>legacy_stdio_definitions.lib;Ncrypt.lib;libssl.lib;libcrypto.lib;lzo2.lib;pkcs11-helper.dll.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;dnsapi.lib;%(AdditionalDependencies)</AdditionalDependencies>
       <AdditionalLibraryDirectories>$(OPENSSL_HOME)/lib;$(LZO_HOME)/lib;$(PKCS11H_HOME)/lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
       <SubSystem>Console</SubSystem>
     </Link>
@@ -107,7 +107,7 @@
     </ClCompile>
     <ResourceCompile />
     <Link>
-      <AdditionalDependencies>legacy_stdio_definitions.lib;Ncrypt.lib;libssl.lib;libcrypto.lib;lzo2.lib;pkcs11-helper.dll.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;%(AdditionalDependencies)</AdditionalDependencies>
+      <AdditionalDependencies>legacy_stdio_definitions.lib;Ncrypt.lib;libssl.lib;libcrypto.lib;lzo2.lib;pkcs11-helper.dll.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;dnsapi.lib;%(AdditionalDependencies)</AdditionalDependencies>
       <AdditionalLibraryDirectories>$(OPENSSL_HOME)/lib;$(LZO_HOME)/lib;$(PKCS11H_HOME)/lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
       <SubSystem>Console</SubSystem>
     </Link>
@@ -122,7 +122,7 @@
     </ClCompile>
     <ResourceCompile />
     <Link>
-      <AdditionalDependencies>legacy_stdio_definitions.lib;Ncrypt.lib;libssl.lib;libcrypto.lib;lzo2.lib;pkcs11-helper.dll.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;%(AdditionalDependencies)</AdditionalDependencies>
+      <AdditionalDependencies>legacy_stdio_definitions.lib;Ncrypt.lib;libssl.lib;libcrypto.lib;lzo2.lib;pkcs11-helper.dll.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;dnsapi.lib;%(AdditionalDependencies)</AdditionalDependencies>
       <AdditionalLibraryDirectories>$(OPENSSL_HOME)/lib;$(LZO_HOME)/lib;$(PKCS11H_HOME)/lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
       <SubSystem>Console</SubSystem>
     </Link>
@@ -137,7 +137,7 @@
     </ClCompile>
     <ResourceCompile />
     <Link>
-      <AdditionalDependencies>legacy_stdio_definitions.lib;Ncrypt.lib;libssl.lib;libcrypto.lib;lzo2.lib;pkcs11-helper.dll.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;%(AdditionalDependencies)</AdditionalDependencies>
+      <AdditionalDependencies>legacy_stdio_definitions.lib;Ncrypt.lib;libssl.lib;libcrypto.lib;lzo2.lib;pkcs11-helper.dll.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;dnsapi.lib;%(AdditionalDependencies)</AdditionalDependencies>
       <AdditionalLibraryDirectories>$(OPENSSL_HOME)/lib;$(LZO_HOME)/lib;$(PKCS11H_HOME)/lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
       <SubSystem>Console</SubSystem>
     </Link>
src/openvpn/options.c +239 -47

400 lines not on this page · raw message

src/openvpn/options.h +4 -0
index 5b6d9441..51432a26 100644
@@ -92,6 +92,7 @@ struct connection_entry
     const char *remote_port;
     const char *local;
     const char *remote;
+    bool remote_srv;
     bool remote_float;
     bool bind_defined;
     bool bind_ipv6_only;
@@ -152,6 +153,7 @@ struct remote_entry
     const char *remote_port;
     int proto;
     sa_family_t af;
+    bool remote_srv;
 };
 
 #define CONNECTION_LIST_SIZE 64
@@ -790,6 +792,8 @@ char *options_string_extract_option(const char *options_string,
 
 void options_postprocess(struct options *options);
 
+bool options_mutate_ce_servinfo(struct options *o, struct servinfo *si);
+
 void pre_pull_save(struct options *o);
 
 void pre_pull_restore(struct options *o, struct gc_arena *gc);
src/openvpn/socket.c +875 -4

951 lines not on this page · raw message

src/openvpn/socket.h +54 -0

110 lines not on this page · raw message

src/openvpn/syshead.h +5 -0
index 2ad5afc2..bec4a8a5 100644
@@ -38,6 +38,7 @@
 
 #ifdef _WIN32
 #include <windows.h>
+#include <windns.h>
 #include <winsock2.h>
 #include <tlhelp32.h>
 #define sleep(x) Sleep((x)*1000)
@@ -176,6 +177,10 @@
 #include <netinet/in.h>
 #endif
 
+#ifdef HAVE_ARPA_NAMESER_H
+#include <arpa/nameser.h>
+#endif
+
 #ifdef HAVE_RESOLV_H
 #include <resolv.h>
 #endif
Signature · 1 line
2.17.1
Acked-by on v9 1/1
#11 lore raw

Am 15.11.20 um 23:08 schrieb Vladislav Grishenko:

Quoted 66 lines

DNS SRV remote host discovery allows to have multiple OpenVPN servers for a single domain w/o explicit profile enumeration, to move services from host to host with little fuss, and to designate hosts as primary servers for a service and others as backups.
Feature has been asked several times already, should be useful in case of substantial number of clients & servers deployed.

Patch introduces "--remote-srv domain [service] [proto]" option. The "service" and "proto" arguments are optional. Client will try to resolve DNS SRV record "_service._proto.domain" and use returned DNS SRV records as remote server list ordered by server selection mechanism defined in RFC2782 (https://tools.ietf.org/html/rfc2782):

A client MUST attempt to contact the target host with the lowest-numbered priority field value it can reach, target hosts with the same priority SHOULD be tried in an order defined by the weight field.
The weight field specifies a relative weight for entries with the same priority. Larger weights SHOULD be given a proportionately higher probability of being selected.
Domain administrators SHOULD use Weight 0 when there isn't any server selection to do. In the presence of records containing weights greater than 0, records with Weight 0 SHOULD have a very small chance of being selected.

Note: OpenVPN server selection mechanism implementation indeed will give records with weight of zero a very small chance of being selected first, but never skip them.

Example: instead of multiple --remote in order, now it's possible to specify just one --remote-srv and configure DNS SRV records:

remote-srv example.net

name prio weight port target
$ORIGIN example.net.
_openvpn._udp IN SRV 10 60 1194 server1.example.net.
_openvpn._udp IN SRV 10 40 1194 server2.example.net.
_openvpn._udp IN SRV 10 0 1194 server3.example.net.
_openvpn._tcp IN SRV 20 0 443 server4.example.net.

For "--remote-srv example.net" following will happen in order:
1. The client will first try to resolve "_openvpn._udp.example.net" and "_openvpn._tcp.example.net".
2. Records "server1.example.net:1194", "server2.example.net:1194" and "server3.example.net:1194" will be selected before record "server4.example.net:443" as their priority 10 is smaller than 20.
3. Records "server1.example.net:1194", "server2.example.net:1194" and "server3.example.net:1194" will be randomly selected with weight probability: first will be either "server1.example.net:1194" with 60% probability or "server2.example.net:1194" with 40% or "server3.example.net:1194" with almost zero probability.
4. If "server1.example.net:1194" was selected, the second record will be either "server2.example.net:1194" with almost 100% probability or "server3.example.net:1194" with almost 0%.
5. If "server2.example.net:1194" was selected, the third record will be the only last record of priority 10 - "server3.example.net:1194".
6. Record "server4.example.net:443" will be the last one selected as the only record with priority 20.
7. Each of the resulting "target:port" remote hosts will be resolved and accessed if its protocol has no conflict with the rest of the OpenVPN options.

If DNS SRV name can't be resolved or no valid records were returned, client will move on to the next connection entry.

Quoted 9 lines

v9:
add get_cached_srv_entry() for servinfo vs addrinfo cache split add check for mixed --remote and --remote-srv
add doxygen dns srv functions comments
use query_servinfo() for both unix and windows
fix undefined NS_MAXMSG issue on macOS
fix man

This addresses the concerns that I had with the last version.

Arne

#12 lore raw
In reply to Vladislav Grishenko

Hi,

Quoted 6 lines · Vladislav Grishenko

DNS SRV remote host discovery allows to have multiple OpenVPN servers for a single domain w/o explicit profile enumeration, to move services from host to host with little fuss, and to designate hosts as primary servers for a service and others as backups.
Feature has been asked several times already, should be useful in case of substantial number of clients & servers deployed.

So, Arne has ACKed it, and I went work on it today. One problem showed up on FreeBSD - the code uses EAI_NODATA, which is found in <netdb.h> on FreeBSD, but with this comment:

#if 0
/* obsoleted */
#define EAI_NODATA 7 /* no address associated with hostname */
#endif

I'm not sure what to make out of this, but as it stands, the patchset does not work.

If I just add

  #define EAI_NODATA 7

to socket.c, it compiles and passes my regular client tests (no SRV tests yet), but I do not think this is the correct solution.

(I have no idea *why* FreeBSD considers this "obsoleted", or what this define is used for - have not yet investigated in any way)

If you need to test on FreeBSD, openvpn-vagrant has boxes that get installed with all prerequisites (or I can give you access to one of my buildslaves).

gert

Signature · 6 lines
"If was one thing all people took for granted, was conviction that if you 
 feed honest figures into a computer, honest figures come out. Never doubted 
 it myself till I met a computer with a sense of humor."
                             Robert A. Heinlein, The Moon is a Harsh Mistress

Gert Doering - Munich, Germany                             [email protected]...
#13 lore raw

PATCH 1/1 Drop EAI_NODATA, absent on FreeBSD and obsoleted by RFC3493

---
 src/openvpn/socket.c | 14 +++++---------
 1 file changed, 5 insertions(+), 9 deletions(-)
src/openvpn/socket.c +5 -9
index bd085e8f..31e8fe9a 100644
@@ -625,10 +625,8 @@ query_servinfo(const char *domain, int proto,
             break;
 
         case DNS_ERROR_RCODE_NAME_ERROR:
-            return EAI_NONAME; /* HOST_NOT_FOUND */
-
         case DNS_INFO_NO_RECORDS:
-            return EAI_NODATA; /* NO_DATA */
+            return EAI_NONAME; /* HOST_NOT_FOUND */
 
         case DNS_ERROR_NO_DNS_SERVERS:
         case DNS_ERROR_RCODE_FORMAT_ERROR:
@@ -642,7 +640,7 @@ query_servinfo(const char *domain, int proto,
             return EAI_AGAIN; /* TRY_AGAIN */
 
         default:
-            return EAI_NODATA;
+            return EAI_FAIL;
     }
 
     struct servinfo *list = NULL, *first = NULL;
@@ -682,7 +680,7 @@ query_servinfo(const char *domain, int proto,
     }
     else
     {
-        status = EAI_NODATA;
+        status = EAI_FAIL;
     }
 
 done:
@@ -717,13 +715,11 @@ query_servinfo(const char *domain, int proto,
         switch (h_errno)
         {
             case HOST_NOT_FOUND:
-                return EAI_NONAME;
-
             case NO_ADDRESS:
 #if NO_ADDRESS != NO_DATA
             case NO_DATA:
 #endif
-                return EAI_NODATA;
+                return EAI_NONAME;
 
             case NO_RECOVERY:
                 return EAI_FAIL;
@@ -782,7 +778,7 @@ query_servinfo(const char *domain, int proto,
     }
     else
     {
-        status = EAI_NODATA;
+        status = EAI_FAIL;
     }
 
 done:
Signature · 1 line
2.17.1
#14 lore raw

PATCH 1/1 Add DNS SRV remote host discovery support

In reply to Gert Doering

DNS SRV remote host discovery allows to have multiple OpenVPN servers for a single domain w/o explicit profile enumeration, to move services from host to host with little fuss, and to designate hosts as primary servers for a service and others as backups.
Feature has been asked several times already, should be useful in case of substantial number of clients & servers deployed.

Patch introduces "--remote-srv domain [service] [proto]" option. The "service" and "proto" arguments are optional. Client will try to resolve DNS SRV record "_service._proto.domain" and use returned DNS SRV records as remote server list ordered by server selection mechanism defined in RFC2782 (https://tools.ietf.org/html/rfc2782):

A client MUST attempt to contact the target host with the lowest-numbered priority field value it can reach, target hosts with the same priority SHOULD be tried in an order defined by the weight field.
The weight field specifies a relative weight for entries with the same priority. Larger weights SHOULD be given a proportionately higher probability of being selected.
Domain administrators SHOULD use Weight 0 when there isn't any server selection to do. In the presence of records containing weights greater than 0, records with Weight 0 SHOULD have a very small chance of being selected.

Note: OpenVPN server selection mechanism implementation indeed will give records with weight of zero a very small chance of being selected first, but never skip them.

Example: instead of multiple --remote in order, now it's possible to specify just one --remote-srv and configure DNS SRV records:

remote-srv example.net

name prio weight port target
$ORIGIN example.net.
_openvpn._udp IN SRV 10 60 1194 server1.example.net.
_openvpn._udp IN SRV 10 40 1194 server2.example.net.
_openvpn._udp IN SRV 10 0 1194 server3.example.net.
_openvpn._tcp IN SRV 20 0 443 server4.example.net.

For "--remote-srv example.net" following will happen in order:
1. The client will first try to resolve "_openvpn._udp.example.net" and "_openvpn._tcp.example.net".
2. Records "server1.example.net:1194", "server2.example.net:1194" and "server3.example.net:1194" will be selected before record "server4.example.net:443" as their priority 10 is smaller than 20.
3. Records "server1.example.net:1194", "server2.example.net:1194" and "server3.example.net:1194" will be randomly selected with weight probability: first will be either "server1.example.net:1194" with 60% probability or "server2.example.net:1194" with 40% or "server3.example.net:1194" with almost zero probability.
4. If "server1.example.net:1194" was selected, the second record will be either "server2.example.net:1194" with almost 100% probability or "server3.example.net:1194" with almost 0%.
5. If "server2.example.net:1194" was selected, the third record will be the only last record of priority 10 - "server3.example.net:1194".
6. Record "server4.example.net:443" will be the last one selected as the only record with priority 20.
7. Each of the resulting "target:port" remote hosts will be resolved and accessed if its protocol has no conflict with the rest of the OpenVPN options.

If DNS SRV name can't be resolved or no valid records were returned, client will move on to the next connection entry.

v10:
add get_cached_srv_entry() for servinfo vs addrinfo cache split add check for mixed --remote and --remote-srv
add doxygen dns srv functions comments
use query_servinfo() for both unix and windows
fix undefined NS_MAXMSG issue on macOS
fix undefined EAI_NODATA issue on FreeBSD
fix man

---
 configure.ac                        |   2 +-
 doc/man-sections/client-options.rst | 121 +++-
 doc/management-notes.txt            |   6 +
 src/openvpn/Makefile.am             |   2 +-
 src/openvpn/buffer.h                |   5 -
 src/openvpn/errlevel.h              |   1 +
 src/openvpn/init.c                  |  79 ++-
 src/openvpn/openvpn.vcxproj         |   8 +-
 src/openvpn/options.c               | 286 +++++++--
 src/openvpn/options.h               |   4 +
 src/openvpn/socket.c                | 875 +++++++++++++++++++++++++++-
 src/openvpn/socket.h                |  54 ++
 src/openvpn/syshead.h               |   5 +
 13 files changed, 1374 insertions(+), 74 deletions(-)
configure.ac +1 -1
index 1ab8fe59..d110ba98 100644
@@ -470,7 +470,7 @@ SOCKET_INCLUDES="
 "
 
 AC_CHECK_HEADERS(
-	[net/if.h netinet/ip.h resolv.h sys/un.h net/if_utun.h sys/kern_control.h],
+	[net/if.h netinet/ip.h arpa/nameser.h resolv.h sys/un.h net/if_utun.h sys/kern_control.h],
 	,
 	,
 	[[${SOCKET_INCLUDES}]]
doc/man-sections/client-options.rst +116 -5

134 lines not on this page · raw message

doc/management-notes.txt +6 -0
index 61daaf07..d9d7394d 100644
@@ -851,6 +851,12 @@ the above notification, use this command:
 
   remote MOD vpn.otherexample.com 1234
 
+DNS SRV discovery domain and service name with protocol code:`auto`
+can't be overriden, but either accepted or skipped only.
+Example of such notification:
+
+  >REMOTE:example.com,openvpn,auto
+
 To accept the same host and port as the client would ordinarily
 have connected to, use this command:
 
src/openvpn/Makefile.am +1 -1
index 37b002c6..f7632047 100644
@@ -143,5 +143,5 @@ openvpn_LDADD = \
 	$(OPTIONAL_INOTIFY_LIBS)
 if WIN32
 openvpn_SOURCES += openvpn_win32_resources.rc block_dns.c block_dns.h ring_buffer.h
-openvpn_LDADD += -lgdi32 -lws2_32 -lwininet -lcrypt32 -liphlpapi -lwinmm -lfwpuclnt -lrpcrt4 -lncrypt -lsetupapi
+openvpn_LDADD += -lgdi32 -lws2_32 -lwininet -lcrypt32 -liphlpapi -lwinmm -lfwpuclnt -lrpcrt4 -lncrypt -lsetupapi -ldnsapi
 endif
src/openvpn/buffer.h +0 -5
index 1722ffd5..ae0cf0eb 100644
@@ -198,11 +198,6 @@ bool buf_init_debug(struct buffer *buf, int offset, const char *file, int line);
 
 
 /* inline functions */
-inline static void
-gc_freeaddrinfo_callback(void *addr)
-{
-    freeaddrinfo((struct addrinfo *) addr);
-}
 
 /** Return an empty struct buffer */
 static inline struct buffer
src/openvpn/errlevel.h +1 -0
index 5663f841..39f96e7d 100644
@@ -92,6 +92,7 @@
 #define D_PS_PROXY           LOGLEV(3, 44, 0)        /* messages related to --port-share option */
 #define D_PF_INFO            LOGLEV(3, 45, 0)        /* packet filter informational messages */
 #define D_IFCONFIG           LOGLEV(3, 0,  0)        /* show ifconfig info (don't mute) */
+#define D_RESOLVE            LOGLEV(3, 46, 0)        /* show hostname resolve info */
 
 #define D_SHOW_PARMS         LOGLEV(4, 50, 0)        /* show all parameters on program initiation */
 #define D_SHOW_OCC           LOGLEV(4, 51, 0)        /* show options compatibility string */
src/openvpn/init.c +72 -7

139 lines not on this page · raw message

src/openvpn/openvpn.vcxproj +4 -4
index 3863854b..1f317fb0 100644
@@ -92,7 +92,7 @@
     </ClCompile>
     <ResourceCompile />
     <Link>
-      <AdditionalDependencies>legacy_stdio_definitions.lib;Ncrypt.lib;libssl.lib;libcrypto.lib;lzo2.lib;pkcs11-helper.dll.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;%(AdditionalDependencies)</AdditionalDependencies>
+      <AdditionalDependencies>legacy_stdio_definitions.lib;Ncrypt.lib;libssl.lib;libcrypto.lib;lzo2.lib;pkcs11-helper.dll.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;dnsapi.lib;%(AdditionalDependencies)</AdditionalDependencies>
       <AdditionalLibraryDirectories>$(OPENSSL_HOME)/lib;$(LZO_HOME)/lib;$(PKCS11H_HOME)/lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
       <SubSystem>Console</SubSystem>
     </Link>
@@ -107,7 +107,7 @@
     </ClCompile>
     <ResourceCompile />
     <Link>
-      <AdditionalDependencies>legacy_stdio_definitions.lib;Ncrypt.lib;libssl.lib;libcrypto.lib;lzo2.lib;pkcs11-helper.dll.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;%(AdditionalDependencies)</AdditionalDependencies>
+      <AdditionalDependencies>legacy_stdio_definitions.lib;Ncrypt.lib;libssl.lib;libcrypto.lib;lzo2.lib;pkcs11-helper.dll.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;dnsapi.lib;%(AdditionalDependencies)</AdditionalDependencies>
       <AdditionalLibraryDirectories>$(OPENSSL_HOME)/lib;$(LZO_HOME)/lib;$(PKCS11H_HOME)/lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
       <SubSystem>Console</SubSystem>
     </Link>
@@ -122,7 +122,7 @@
     </ClCompile>
     <ResourceCompile />
     <Link>
-      <AdditionalDependencies>legacy_stdio_definitions.lib;Ncrypt.lib;libssl.lib;libcrypto.lib;lzo2.lib;pkcs11-helper.dll.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;%(AdditionalDependencies)</AdditionalDependencies>
+      <AdditionalDependencies>legacy_stdio_definitions.lib;Ncrypt.lib;libssl.lib;libcrypto.lib;lzo2.lib;pkcs11-helper.dll.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;dnsapi.lib;%(AdditionalDependencies)</AdditionalDependencies>
       <AdditionalLibraryDirectories>$(OPENSSL_HOME)/lib;$(LZO_HOME)/lib;$(PKCS11H_HOME)/lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
       <SubSystem>Console</SubSystem>
     </Link>
@@ -137,7 +137,7 @@
     </ClCompile>
     <ResourceCompile />
     <Link>
-      <AdditionalDependencies>legacy_stdio_definitions.lib;Ncrypt.lib;libssl.lib;libcrypto.lib;lzo2.lib;pkcs11-helper.dll.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;%(AdditionalDependencies)</AdditionalDependencies>
+      <AdditionalDependencies>legacy_stdio_definitions.lib;Ncrypt.lib;libssl.lib;libcrypto.lib;lzo2.lib;pkcs11-helper.dll.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;dnsapi.lib;%(AdditionalDependencies)</AdditionalDependencies>
       <AdditionalLibraryDirectories>$(OPENSSL_HOME)/lib;$(LZO_HOME)/lib;$(PKCS11H_HOME)/lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
       <SubSystem>Console</SubSystem>
     </Link>
src/openvpn/options.c +239 -47

400 lines not on this page · raw message

src/openvpn/options.h +4 -0
index 5b6d9441..51432a26 100644
@@ -92,6 +92,7 @@ struct connection_entry
     const char *remote_port;
     const char *local;
     const char *remote;
+    bool remote_srv;
     bool remote_float;
     bool bind_defined;
     bool bind_ipv6_only;
@@ -152,6 +153,7 @@ struct remote_entry
     const char *remote_port;
     int proto;
     sa_family_t af;
+    bool remote_srv;
 };
 
 #define CONNECTION_LIST_SIZE 64
@@ -790,6 +792,8 @@ char *options_string_extract_option(const char *options_string,
 
 void options_postprocess(struct options *options);
 
+bool options_mutate_ce_servinfo(struct options *o, struct servinfo *si);
+
 void pre_pull_save(struct options *o);
 
 void pre_pull_restore(struct options *o, struct gc_arena *gc);
src/openvpn/socket.c +871 -4

947 lines not on this page · raw message

src/openvpn/socket.h +54 -0

110 lines not on this page · raw message

src/openvpn/syshead.h +5 -0
index 2ad5afc2..bec4a8a5 100644
@@ -38,6 +38,7 @@
 
 #ifdef _WIN32
 #include <windows.h>
+#include <windns.h>
 #include <winsock2.h>
 #include <tlhelp32.h>
 #define sleep(x) Sleep((x)*1000)
@@ -176,6 +177,10 @@
 #include <netinet/in.h>
 #endif
 
+#ifdef HAVE_ARPA_NAMESER_H
+#include <arpa/nameser.h>
+#endif
+
 #ifdef HAVE_RESOLV_H
 #include <resolv.h>
 #endif
Signature · 1 line
2.17.1
#15 lore raw

PATCH v10 1/1 Add DNS SRV remote host discovery support

In reply to Gert Doering

DNS SRV remote host discovery allows to have multiple OpenVPN servers for a single domain w/o explicit profile enumeration, to move services from host to host with little fuss, and to designate hosts as primary servers for a service and others as backups.
Feature has been asked several times already, should be useful in case of substantial number of clients & servers deployed.

Patch introduces "--remote-srv domain [service] [proto]" option. The "service" and "proto" arguments are optional. Client will try to resolve DNS SRV record "_service._proto.domain" and use returned DNS SRV records as remote server list ordered by server selection mechanism defined in RFC2782 (https://tools.ietf.org/html/rfc2782):

A client MUST attempt to contact the target host with the lowest-numbered priority field value it can reach, target hosts with the same priority SHOULD be tried in an order defined by the weight field.
The weight field specifies a relative weight for entries with the same priority. Larger weights SHOULD be given a proportionately higher probability of being selected.
Domain administrators SHOULD use Weight 0 when there isn't any server selection to do. In the presence of records containing weights greater than 0, records with Weight 0 SHOULD have a very small chance of being selected.

Note: OpenVPN server selection mechanism implementation indeed will give records with weight of zero a very small chance of being selected first, but never skip them.

Example: instead of multiple --remote in order, now it's possible to specify just one --remote-srv and configure DNS SRV records:

remote-srv example.net

name prio weight port target
$ORIGIN example.net.
_openvpn._udp IN SRV 10 60 1194 server1.example.net.
_openvpn._udp IN SRV 10 40 1194 server2.example.net.
_openvpn._udp IN SRV 10 0 1194 server3.example.net.
_openvpn._tcp IN SRV 20 0 443 server4.example.net.

For "--remote-srv example.net" following will happen in order:
1. The client will first try to resolve "_openvpn._udp.example.net" and "_openvpn._tcp.example.net".
2. Records "server1.example.net:1194", "server2.example.net:1194" and "server3.example.net:1194" will be selected before record "server4.example.net:443" as their priority 10 is smaller than 20.
3. Records "server1.example.net:1194", "server2.example.net:1194" and "server3.example.net:1194" will be randomly selected with weight probability: first will be either "server1.example.net:1194" with 60% probability or "server2.example.net:1194" with 40% or "server3.example.net:1194" with almost zero probability.
4. If "server1.example.net:1194" was selected, the second record will be either "server2.example.net:1194" with almost 100% probability or "server3.example.net:1194" with almost 0%.
5. If "server2.example.net:1194" was selected, the third record will be the only last record of priority 10 - "server3.example.net:1194".
6. Record "server4.example.net:443" will be the last one selected as the only record with priority 20.
7. Each of the resulting "target:port" remote hosts will be resolved and accessed if its protocol has no conflict with the rest of the OpenVPN options.

If DNS SRV name can't be resolved or no valid records were returned, client will move on to the next connection entry.

v10:
add get_cached_srv_entry() for servinfo vs addrinfo cache split add check for mixed --remote and --remote-srv
add doxygen dns srv functions comments
use query_servinfo() for both unix and windows
fix undefined NS_MAXMSG issue on macOS
fix undefined EAI_NODATA issue on FreeBSD
fix man

---
 configure.ac                        |   2 +-
 doc/man-sections/client-options.rst | 121 +++-
 doc/management-notes.txt            |   6 +
 src/openvpn/Makefile.am             |   2 +-
 src/openvpn/buffer.h                |   5 -
 src/openvpn/errlevel.h              |   1 +
 src/openvpn/init.c                  |  79 ++-
 src/openvpn/openvpn.vcxproj         |   8 +-
 src/openvpn/options.c               | 286 +++++++--
 src/openvpn/options.h               |   4 +
 src/openvpn/socket.c                | 875 +++++++++++++++++++++++++++-
 src/openvpn/socket.h                |  54 ++
 src/openvpn/syshead.h               |   5 +
 13 files changed, 1374 insertions(+), 74 deletions(-)
configure.ac +1 -1
index 1ab8fe59..d110ba98 100644
@@ -470,7 +470,7 @@ SOCKET_INCLUDES="
 "
 
 AC_CHECK_HEADERS(
-	[net/if.h netinet/ip.h resolv.h sys/un.h net/if_utun.h sys/kern_control.h],
+	[net/if.h netinet/ip.h arpa/nameser.h resolv.h sys/un.h net/if_utun.h sys/kern_control.h],
 	,
 	,
 	[[${SOCKET_INCLUDES}]]
doc/man-sections/client-options.rst +116 -5

134 lines not on this page · raw message

doc/management-notes.txt +6 -0
index 61daaf07..d9d7394d 100644
@@ -851,6 +851,12 @@ the above notification, use this command:
 
   remote MOD vpn.otherexample.com 1234
 
+DNS SRV discovery domain and service name with protocol code:`auto`
+can't be overriden, but either accepted or skipped only.
+Example of such notification:
+
+  >REMOTE:example.com,openvpn,auto
+
 To accept the same host and port as the client would ordinarily
 have connected to, use this command:
 
src/openvpn/Makefile.am +1 -1
index 37b002c6..f7632047 100644
@@ -143,5 +143,5 @@ openvpn_LDADD = \
 	$(OPTIONAL_INOTIFY_LIBS)
 if WIN32
 openvpn_SOURCES += openvpn_win32_resources.rc block_dns.c block_dns.h ring_buffer.h
-openvpn_LDADD += -lgdi32 -lws2_32 -lwininet -lcrypt32 -liphlpapi -lwinmm -lfwpuclnt -lrpcrt4 -lncrypt -lsetupapi
+openvpn_LDADD += -lgdi32 -lws2_32 -lwininet -lcrypt32 -liphlpapi -lwinmm -lfwpuclnt -lrpcrt4 -lncrypt -lsetupapi -ldnsapi
 endif
src/openvpn/buffer.h +0 -5
index 1722ffd5..ae0cf0eb 100644
@@ -198,11 +198,6 @@ bool buf_init_debug(struct buffer *buf, int offset, const char *file, int line);
 
 
 /* inline functions */
-inline static void
-gc_freeaddrinfo_callback(void *addr)
-{
-    freeaddrinfo((struct addrinfo *) addr);
-}
 
 /** Return an empty struct buffer */
 static inline struct buffer
src/openvpn/errlevel.h +1 -0
index 5663f841..39f96e7d 100644
@@ -92,6 +92,7 @@
 #define D_PS_PROXY           LOGLEV(3, 44, 0)        /* messages related to --port-share option */
 #define D_PF_INFO            LOGLEV(3, 45, 0)        /* packet filter informational messages */
 #define D_IFCONFIG           LOGLEV(3, 0,  0)        /* show ifconfig info (don't mute) */
+#define D_RESOLVE            LOGLEV(3, 46, 0)        /* show hostname resolve info */
 
 #define D_SHOW_PARMS         LOGLEV(4, 50, 0)        /* show all parameters on program initiation */
 #define D_SHOW_OCC           LOGLEV(4, 51, 0)        /* show options compatibility string */
src/openvpn/init.c +72 -7

139 lines not on this page · raw message

src/openvpn/openvpn.vcxproj +4 -4
index 3863854b..1f317fb0 100644
@@ -92,7 +92,7 @@
     </ClCompile>
     <ResourceCompile />
     <Link>
-      <AdditionalDependencies>legacy_stdio_definitions.lib;Ncrypt.lib;libssl.lib;libcrypto.lib;lzo2.lib;pkcs11-helper.dll.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;%(AdditionalDependencies)</AdditionalDependencies>
+      <AdditionalDependencies>legacy_stdio_definitions.lib;Ncrypt.lib;libssl.lib;libcrypto.lib;lzo2.lib;pkcs11-helper.dll.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;dnsapi.lib;%(AdditionalDependencies)</AdditionalDependencies>
       <AdditionalLibraryDirectories>$(OPENSSL_HOME)/lib;$(LZO_HOME)/lib;$(PKCS11H_HOME)/lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
       <SubSystem>Console</SubSystem>
     </Link>
@@ -107,7 +107,7 @@
     </ClCompile>
     <ResourceCompile />
     <Link>
-      <AdditionalDependencies>legacy_stdio_definitions.lib;Ncrypt.lib;libssl.lib;libcrypto.lib;lzo2.lib;pkcs11-helper.dll.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;%(AdditionalDependencies)</AdditionalDependencies>
+      <AdditionalDependencies>legacy_stdio_definitions.lib;Ncrypt.lib;libssl.lib;libcrypto.lib;lzo2.lib;pkcs11-helper.dll.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;dnsapi.lib;%(AdditionalDependencies)</AdditionalDependencies>
       <AdditionalLibraryDirectories>$(OPENSSL_HOME)/lib;$(LZO_HOME)/lib;$(PKCS11H_HOME)/lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
       <SubSystem>Console</SubSystem>
     </Link>
@@ -122,7 +122,7 @@
     </ClCompile>
     <ResourceCompile />
     <Link>
-      <AdditionalDependencies>legacy_stdio_definitions.lib;Ncrypt.lib;libssl.lib;libcrypto.lib;lzo2.lib;pkcs11-helper.dll.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;%(AdditionalDependencies)</AdditionalDependencies>
+      <AdditionalDependencies>legacy_stdio_definitions.lib;Ncrypt.lib;libssl.lib;libcrypto.lib;lzo2.lib;pkcs11-helper.dll.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;dnsapi.lib;%(AdditionalDependencies)</AdditionalDependencies>
       <AdditionalLibraryDirectories>$(OPENSSL_HOME)/lib;$(LZO_HOME)/lib;$(PKCS11H_HOME)/lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
       <SubSystem>Console</SubSystem>
     </Link>
@@ -137,7 +137,7 @@
     </ClCompile>
     <ResourceCompile />
     <Link>
-      <AdditionalDependencies>legacy_stdio_definitions.lib;Ncrypt.lib;libssl.lib;libcrypto.lib;lzo2.lib;pkcs11-helper.dll.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;%(AdditionalDependencies)</AdditionalDependencies>
+      <AdditionalDependencies>legacy_stdio_definitions.lib;Ncrypt.lib;libssl.lib;libcrypto.lib;lzo2.lib;pkcs11-helper.dll.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;dnsapi.lib;%(AdditionalDependencies)</AdditionalDependencies>
       <AdditionalLibraryDirectories>$(OPENSSL_HOME)/lib;$(LZO_HOME)/lib;$(PKCS11H_HOME)/lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
       <SubSystem>Console</SubSystem>
     </Link>
src/openvpn/options.c +239 -47

400 lines not on this page · raw message

src/openvpn/options.h +4 -0
index 5b6d9441..51432a26 100644
@@ -92,6 +92,7 @@ struct connection_entry
     const char *remote_port;
     const char *local;
     const char *remote;
+    bool remote_srv;
     bool remote_float;
     bool bind_defined;
     bool bind_ipv6_only;
@@ -152,6 +153,7 @@ struct remote_entry
     const char *remote_port;
     int proto;
     sa_family_t af;
+    bool remote_srv;
 };
 
 #define CONNECTION_LIST_SIZE 64
@@ -790,6 +792,8 @@ char *options_string_extract_option(const char *options_string,
 
 void options_postprocess(struct options *options);
 
+bool options_mutate_ce_servinfo(struct options *o, struct servinfo *si);
+
 void pre_pull_save(struct options *o);
 
 void pre_pull_restore(struct options *o, struct gc_arena *gc);
src/openvpn/socket.c +871 -4

947 lines not on this page · raw message

src/openvpn/socket.h +54 -0

110 lines not on this page · raw message

src/openvpn/syshead.h +5 -0
index 2ad5afc2..bec4a8a5 100644
@@ -38,6 +38,7 @@
 
 #ifdef _WIN32
 #include <windows.h>
+#include <windns.h>
 #include <winsock2.h>
 #include <tlhelp32.h>
 #define sleep(x) Sleep((x)*1000)
@@ -176,6 +177,10 @@
 #include <netinet/in.h>
 #endif
 
+#ifdef HAVE_ARPA_NAMESER_H
+#include <arpa/nameser.h>
+#endif
+
 #ifdef HAVE_RESOLV_H
 #include <resolv.h>
 #endif
Signature · 1 line
2.17.1
#16 lore raw

Hello and happy holidays,
Is there a chance to get back to this patch since v9 was acked and minor fix for undefined EAI_NODATA on FreeBSD was applied?

--
Best Regards, Vladislav Grishenko

Quoted 105 lines

-----Original Message-----
From: Vladislav Grishenko <[email protected]...>
Sent: Friday, December 4, 2020 9:15 PM
To: [email protected]
Cc: [email protected]...
Subject: [Openvpn-devel] [PATCH v10] Add DNS SRV remote host discovery support

DNS SRV remote host discovery allows to have multiple OpenVPN servers for a single domain w/o explicit profile enumeration, to move services from host to host with little fuss, and to designate hosts as primary servers for a service and others as backups.
Feature has been asked several times already, should be useful in case of substantial number of clients & servers deployed.

Patch introduces "--remote-srv domain [service] [proto]" option. The "service" and "proto" arguments are optional. Client will try to resolve DNS SRV record "_service._proto.domain" and use returned DNS SRV records as remote server list ordered by server selection mechanism defined in RFC2782 (https://tools.ietf.org/html/rfc2782):

A client MUST attempt to contact the target host with the lowest-numbered priority field value it can reach, target hosts with the same priority SHOULD be tried in an order defined by the weight field.
The weight field specifies a relative weight for entries with the same priority. Larger weights SHOULD be given a proportionately higher probability of being selected.
Domain administrators SHOULD use Weight 0 when there isn't any server selection to do. In the presence of records containing weights greater than 0, records with Weight 0 SHOULD have a very small chance of being selected.

Note: OpenVPN server selection mechanism implementation indeed will give records with weight of zero a very small chance of being selected first, but never skip them.

Example: instead of multiple --remote in order, now it's possible to specify just one --remote-srv and configure DNS SRV records:

remote-srv example.net

name prio weight port target
$ORIGIN example.net.
_openvpn._udp IN SRV 10 60 1194 server1.example.net.
_openvpn._udp IN SRV 10 40 1194 server2.example.net.
_openvpn._udp IN SRV 10 0 1194 server3.example.net.
_openvpn._tcp IN SRV 20 0 443 server4.example.net.

For "--remote-srv example.net" following will happen in order:
1. The client will first try to resolve "_openvpn._udp.example.net" and "_openvpn._tcp.example.net".
2. Records "server1.example.net:1194", "server2.example.net:1194" and "server3.example.net:1194" will be selected before record "server4.example.net:443" as their priority 10 is smaller than 20.
3. Records "server1.example.net:1194", "server2.example.net:1194" and "server3.example.net:1194" will be randomly selected with weight probability: first will be either "server1.example.net:1194" with 60% probability or "server2.example.net:1194" with 40% or "server3.example.net:1194" with almost zero probability.
4. If "server1.example.net:1194" was selected, the second record will be either "server2.example.net:1194" with almost 100% probability or "server3.example.net:1194" with almost 0%.
5. If "server2.example.net:1194" was selected, the third record will be the only last record of priority 10 - "server3.example.net:1194".
6. Record "server4.example.net:443" will be the last one selected as the only record with priority 20.
7. Each of the resulting "target:port" remote hosts will be resolved and accessed if its protocol has no conflict with the rest of the OpenVPN options.

If DNS SRV name can't be resolved or no valid records were returned, client will move on to the next connection entry.

v10:
add get_cached_srv_entry() for servinfo vs addrinfo cache split add check for mixed --remote and --remote-srv
add doxygen dns srv functions comments
use query_servinfo() for both unix and windows
fix undefined NS_MAXMSG issue on macOS
fix undefined EAI_NODATA issue on FreeBSD
fix man

---
 configure.ac                        |   2 +-
 doc/man-sections/client-options.rst | 121 +++-
 doc/management-notes.txt            |   6 +
 src/openvpn/Makefile.am             |   2 +-
 src/openvpn/buffer.h                |   5 -
 src/openvpn/errlevel.h              |   1 +
 src/openvpn/init.c                  |  79 ++-
 src/openvpn/openvpn.vcxproj         |   8 +-
 src/openvpn/options.c               | 286 +++++++--
 src/openvpn/options.h               |   4 +
 src/openvpn/socket.c                | 875 +++++++++++++++++++++++++++-
 src/openvpn/socket.h                |  54 ++
 src/openvpn/syshead.h               |   5 +
 13 files changed, 1374 insertions(+), 74 deletions(-)
configure.ac +0 -0
index 1ab8fe59..d110ba98 100644

configure.ac SOCKET_INCLUDES=" · line 474

Quoted 6 lines
configure.ac +1 -1
@@ -470,7 +470,7 @@ SOCKET_INCLUDES="
 "
 
 AC_CHECK_HEADERS(
-	[net/if.h netinet/ip.h resolv.h sys/un.h net/if_utun.h
 sys/kern_control.h],
+	[net/if.h netinet/ip.h arpa/nameser.h resolv.h sys/un.h

net/if_utun.h

Review

Quoted 5 lines
configure.ac +0 -0
 sys/kern_control.h],
 	,
configure.ac +0 -0
 	,
 	[[${SOCKET_INCLUDES}]]
(quoted diff) +0 -0

b/doc/man-sections/client-

Quoted 89 lines

options.rst
index af21fbcd..d2cafd00 100644

doc/man-sections/client-options.rst +81 -0
@@ -307,10 +307,121 @@ configuration.
   specification (4/6 suffix), OpenVPN will try both IPv4 and IPv6
   addresses, in the order getaddrinfo() returns them.
 
+--remote-srv args
+  Remote DNS SRV domain, service name and protocol.
+
+  Valid syntaxes:
+  ::
+
+     remote-srv domain
+     remote-srv domain service
+     remote-srv domain service proto
+
+  The ``service`` and ``proto`` arguments are optional. Client will try
+  to resolve DNS SRV record ``_service._proto.domain`` and use returned
+  DNS SRV records as remote server list ordered by server selection
+  mechanism defined in `RFC 2782 <https://tools.ietf.org/html/rfc2782>`_:
+  ::
+
+    A client MUST attempt to contact the target host with the
+    lowest-numbered priority field value it can reach, target hosts
+    with the same priority SHOULD be tried in an order defined by the
+    weight field.
+    The weight field specifies a relative weight for entries with the
+    same priority. Larger weights SHOULD be given a proportionately
+    higher probability of being selected.
+    Domain administrators SHOULD use Weight 0 when there isn't any
+    server selection to do. In the presence of records containing
+    weights greater than 0, records with Weight 0 SHOULD have a very
+    small chance of being selected.
+
+  *Note:*
+    OpenVPN server selection mechanism implementation indeed will give
+    records with weight of zero a very small chance of being selected
+    first, but never skip them.
+
+  The ``service`` argument indicates the symbolic name of the desired
+  service. By default service is the registered service name
+  :code:`openvpn`.
+
+  The ``proto`` argument indicates the symbolic name of the desired
+  protocol and the protocol to use when connecting with the remote, and
+  may either be :code:`tcp`, :code:`udp` or special value :code:`auto`
+  used by default to try both. In this case all the discovered remote
+  hosts will be ordered by server selection mechanism regardless their
+  protocol. To enforce IPv4 or IPv6 connections add a :code:`4` or
+  :code:`6` suffix; like :code:`udp4` / :code:`udp6` / :code:`tcp4` /
+  :code:`tcp6` / :code:`auto4` / :code:`auto6`.
+
+  On the client, multiple ``--remote-srv`` options may be specified for
+  redundancy, each referring to a different DNS SRV record name, in the
+  order specified by the list of ``--remote-srv`` options. Specifying
+  multiple ``--remote-srv`` options for this purpose is a special case
+  of the more general connection-profile feature. See the
+  ``<connection>`` documentation below.
+
+  The client will move on to the next DNS SRV record in the ordered list,
+  in the event of connection failure. Note that at any given time, the
+  OpenVPN client will at most be connected to one server.
+
+  If particular DNS SRV record next resolves to multiple IP addresses,
+  OpenVPN will try them in the order that the system getaddrinfo()
+  presents them, so prioritization and DNS randomization is done by the
+  system library. Unless an IP version is forced by the protocol
+  specification (4/6 suffix), OpenVPN will try both IPv4 and IPv6
+  addresses, in the order getaddrinfo() returns them.
+
+  Examples:
+  ::
+
+     remote-srv example.net
+     remote-srv example.net openvpn
+     remote-srv example.net openvpn tcp
+
+  Example of DNS SRV records:
+  ::
+
+     name                 prio weight port target
+     $ORIGIN example.net.
+     _openvpn._udp IN SRV 10   60     1194 server1.example.net.
+     _openvpn._udp IN SRV 10   40     1194 server2.example.net.
+     _openvpn._udp IN SRV 10   0      1194 server3.example.net.
+     _openvpn._tcp IN SRV 20   0       443 server4.example.net.
+

doc/man-sections/client-options.rst configuration. · line 400

Quoted 10 lines
doc/man-sections/client-options.rst +10 -0
+  For ``--remote-srv example.net`` following will happen in order:
+
+  1. The client will first try to resolve ``_openvpn._udp.example.net``
+     and ``_openvpn._tcp.example.net``.
+  2. Records ``server1.example.net:1194``, ``server2.example.net:1194``
+     and ``server3.example.net:1194`` will be selected before record
+     ``server4.example.net:443`` as their priority 10 is smaller than 20.
+  3. Records ``server1.example.net:1194``, ``server2.example.net:1194``
+     and ``server3.example.net:1194`` will be randomly selected with
+     weight probability: first will be either

``server1.example.net:1194``

doc/man-sections/client-options.rst configuration.

Quoted 7 lines
doc/man-sections/client-options.rst +7 -0
+     with 60% probability or ``server2.example.net:1194`` with 40% or
+     ``server3.example.net:1194`` with almost zero probability.
+  4. If ``server1.example.net:1194`` was selected, the second record will
+     be either ``server2.example.net:1194`` with almost 100% probability
+     or ``server3.example.net:1194`` with almost 0%.
+  5. If ``server2.example.net:1194`` was selected, the third record will
+     be the only last record of priority 10 -

``server3.example.net:1194``.

doc/man-sections/client-options.rst configuration.

Quoted 13 lines
doc/man-sections/client-options.rst +11 -1
+  6. Record ``server4.example.net:443`` will be the last one selected as
+     the only record with priority 20.
+  7. Each of the resulting ```target:port`` remote hosts will be resolved
+     and accessed if its protocol has no conflict with the rest of the
+     OpenVPN options.
+
+  If a DNS SRV name cannot be resolved or no valid records are returned,
+  the client will move on to the next connection entry.
+
+  For more information on DNS SRV see https://tools.ietf.org/html/rfc2782
+
 --remote-random
-  When multiple ``--remote`` address/ports are specified, or if

connection

doc/man-sections/client-options.rst configuration.

Quoted 4 lines
doc/man-sections/client-options.rst +2 -2
-  profiles are being used, initially randomize the order of the list as a
-  kind of basic load-balancing measure.
+  Randomises the order of ``--remote-srv``, ``remote-srv`` and connection
+  profiles on start. This randomisation of these entries is a kind of

basic

doc/man-sections/client-options.rst configuration. · line 423

Quoted 2 lines
doc/man-sections/client-options.rst +2 -0
+  load-balancing measure. Note that implementing DNS SRV entries (with a
+  short TTL if it should be dynamic) and using ``--remote-srv`` is a

better

Quoted 40 lines
doc/man-sections/client-options.rst +3 -2
+  alternative for client-side load balancing.
 
 --remote-random-hostname
   Prepend a random string (6 bytes, 12 hex characters) to hostname to
@@ -318,8 +429,8 @@ configuration.
   "<random-chars>.foo.bar.gov".
 
 --resolv-retry n
-  If hostname resolve fails for ``--remote``, retry resolve for ``n``
-  seconds before failing.
+  If hostname resolve fails for ``--remote`` or ``--remote-srv``, retry
+  resolve for ``n`` seconds before failing.
 
   Set ``n`` to "infinite" to retry indefinitely.
 
doc/management-notes.txt +6 -0
index 61daaf07..d9d7394d 100644
@@ -851,6 +851,12 @@ the above notification, use this command:
 
   remote MOD vpn.otherexample.com 1234
 
+DNS SRV discovery domain and service name with protocol code:`auto`
+can't be overriden, but either accepted or skipped only.
+Example of such notification:
+
+  >REMOTE:example.com,openvpn,auto
+
 To accept the same host and port as the client would ordinarily
 have connected to, use this command:
 
src/openvpn/Makefile.am +0 -0
index 37b002c6..f7632047 100644
@@ -143,5 +143,5 @@ openvpn_LDADD = \
 	$(OPTIONAL_INOTIFY_LIBS)
 if WIN32
 openvpn_SOURCES += openvpn_win32_resources.rc block_dns.c block_dns.h
Quoted 2 lines

ring_buffer.h
-openvpn_LDADD += -lgdi32 -lws2_32 -lwininet -lcrypt32 -liphlpapi -lwinmm

-

Quoted 2 lines

lfwpuclnt -lrpcrt4 -lncrypt -lsetupapi
+openvpn_LDADD += -lgdi32 -lws2_32 -lwininet -lcrypt32 -liphlpapi -lwinmm

-

Quoted 24 lines

lfwpuclnt -lrpcrt4 -lncrypt -lsetupapi -ldnsapi
endif

src/openvpn/buffer.h +0 -5
index 1722ffd5..ae0cf0eb 100644
@@ -198,11 +198,6 @@ bool buf_init_debug(struct buffer *buf, int offset,
 const char *file, int line);
 
 
 /* inline functions */
-inline static void
-gc_freeaddrinfo_callback(void *addr)
-{
-    freeaddrinfo((struct addrinfo *) addr);
-}
 
 /** Return an empty struct buffer */

static inline struct buffer

src/openvpn/errlevel.h +0 -0
index 5663f841..39f96e7d 100644

src/openvpn/errlevel.h line 92

Quoted 1 line
src/openvpn/errlevel.h +0 -0
@@ -92,6 +92,7 @@
 #define D_PS_PROXY           LOGLEV(3, 44, 0)        /* messages related

to --port-

Quoted 2 lines

share option */
#define D_PF_INFO LOGLEV(3, 45, 0) /* packet filter

informational

Quoted 2 lines

messages */
#define D_IFCONFIG LOGLEV(3, 0, 0) /* show ifconfig

info (don't

Quoted 2 lines

mute) */
+#define D_RESOLVE LOGLEV(3, 46, 0) /* show hostname

resolve info

Quoted 3 lines

*/

#define D_SHOW_PARMS LOGLEV(4, 50, 0) /* show all

parameters on

Quoted 2 lines

program initiation */
#define D_SHOW_OCC LOGLEV(4, 51, 0) /* show options

compatibility

Quoted 6 lines

string */

src/openvpn/init.c +0 -0
index 2291a89a..34873cf4 100644

src/openvpn/init.c management_callback_remote_cmd(void *arg, const · line 358

Quoted 8 lines
src/openvpn/init.c +3 -1
@@ -352,7 +352,12 @@ management_callback_remote_cmd(void *arg, const
 char **p)
         }
         else if (!strcmp(p[1], "MOD") && p[2] && p[3])
         {
-            if (strlen(p[2]) < RH_HOST_LEN && strlen(p[3]) < RH_PORT_LEN)
+            if (ce->remote_srv && ce->proto == PROTO_AUTO)
+            {
+                /* can't mutate --remote-srv into --remote without

protocol */

src/openvpn/init.c management_callback_remote_cmd(void *arg, const char **p)

Quoted 3 lines
src/openvpn/init.c +3 -0
+                ret = false;
+            }
+            else if (strlen(p[2]) < RH_HOST_LEN && strlen(p[3]) <

RH_PORT_LEN)

Quoted 47 lines
src/openvpn/init.c +0 -0
             {
                 struct remote_host_store *rhs = c->options.rh_store;
                 if (!rhs)
src/openvpn/init.c +1 -0
@@ -365,6 +370,7 @@ management_callback_remote_cmd(void *arg, const
 char **p)
 
                 ce->remote = rhs->host;
                 ce->remote_port = rhs->port;
+                ce->remote_srv = false;
                 flags = CE_MAN_QUERY_REMOTE_MOD;
                 ret = true;
             }
src/openvpn/init.c +17 -0
@@ -464,6 +470,23 @@ clear_remote_addrlist(struct link_socket_addr *lsa,
 bool free)
     lsa->current_remote = NULL;
 }
 
+/*
+ * Clear the remote service list
+ */
+static void
+clear_remote_servlist(struct link_socket_addr *lsa, bool free)
+{
+    if (lsa->service_list && free)
+    {
+        freeservinfo(lsa->service_list);
+    }
+    lsa->service_list = NULL;
+    lsa->current_service = NULL;
+
+    /* clear addrinfo objects as well */
+    clear_remote_addrlist(lsa, free);
+}
+
 /*
  * Increment to next connection entry

*/

src/openvpn/init.c +6 -0
@@ -492,6 +515,24 @@ next_connection_entry(struct context *c)
                 c->c1.link_socket_addr.current_remote =
                     c->c1.link_socket_addr.current_remote->ai_next;
             }
+            /* Check if there is another resolved service to try for
+             * the current connection unless persist-remote-ip was
+             * requested and current service already has an address */
+            else if (c->c1.link_socket_addr.current_service
+                     && c->c1.link_socket_addr.current_service->next
+                     && !(c->options.persist_remote_ip

src/openvpn/init.c next_connection_entry(struct context *c) · line 533

Quoted 10 lines
src/openvpn/init.c +10 -0
+                          && c->c1.link_socket_addr.remote_list))
+            {
+                c->c1.link_socket_addr.current_service =
+                    c->c1.link_socket_addr.current_service->next;
+
+                /* Clear addrinfo object of the previous service */
+                if (c->c1.link_socket_addr.remote_list)
+                {
+                    clear_remote_addrlist(&c->c1.link_socket_addr,
+

!c->options.resolve_in_advance);

src/openvpn/init.c next_connection_entry(struct context *c)

Quoted 5 lines
src/openvpn/init.c +2 -0
+                }
+            }
             else
             {
                 /* FIXME (schwabe) fix the persist-remote-ip option for

real,

src/openvpn/init.c next_connection_entry(struct context *c) · line 544

Quoted 6 lines
src/openvpn/init.c +1 -1
@@ -500,20 +541,24 @@ next_connection_entry(struct context *c)
                  */
                 if (!c->options.persist_remote_ip)
                 {
-                    /* Connection entry addrinfo objects might have been
+                    /* Connection entry addr/servinfo objects might have

been

src/openvpn/init.c next_connection_entry(struct context *c) · line 545

Quoted 1 line
src/openvpn/init.c +0 -0
                      * resolved earlier but the entry itself might have

been

src/openvpn/init.c next_connection_entry(struct context *c) · line 506

Quoted 2 lines
src/openvpn/init.c +0 -2
-                     * skipped by management on the previous loop.
-                     * If so, clear the addrinfo objects as

close_instance does

src/openvpn/init.c next_connection_entry(struct context *c) · line 546

Quoted 1 line
src/openvpn/init.c +1 -0
+                     * skipped on the previous loop either by management

or

src/openvpn/init.c next_connection_entry(struct context *c) · line 548

Quoted 2 lines
src/openvpn/init.c +2 -0
+                     * due inappropriate service protocol.
+                     * Clear the addr/servinfo objects as close_instance

does.

src/openvpn/init.c next_connection_entry(struct context *c) · line 556

Quoted 8 lines
src/openvpn/init.c +3 -2
                      */
-                    if (c->c1.link_socket_addr.remote_list)
+                    if (c->c1.link_socket_addr.remote_list
+                        || c->c1.link_socket_addr.service_list)
                     {
-                        clear_remote_addrlist(&c->c1.link_socket_addr,
+                        clear_remote_servlist(&c->c1.link_socket_addr,
 

!c->options.resolve_in_advance);

src/openvpn/init.c next_connection_entry(struct context *c) · line 557

Quoted 3 lines
src/openvpn/init.c +0 -0
                     }
 
                     /* close_instance should have cleared the addrinfo

objects */

src/openvpn/init.c next_connection_entry(struct context *c) · line 558

Quoted 1 line
src/openvpn/init.c +0 -0
                     ASSERT(c->c1.link_socket_addr.current_remote ==

NULL);

src/openvpn/init.c next_connection_entry(struct context *c) · line 560

Quoted 2 lines
src/openvpn/init.c +1 -0
                     ASSERT(c->c1.link_socket_addr.remote_list == NULL);
+                    ASSERT(c->c1.link_socket_addr.current_service ==

NULL);

Quoted 33 lines
src/openvpn/init.c +7 -0
+                    ASSERT(c->c1.link_socket_addr.service_list == NULL);
                 }
                 else
                 {
@@ -549,6 +594,12 @@ next_connection_entry(struct context *c)
         }
 
         c->options.ce = *ce;
+        if (ce_defined && c->c1.link_socket_addr.current_service)
+        {
+            /* map in current service */
+            struct servinfo *si = c->c1.link_socket_addr.current_service;
+            ce_defined = options_mutate_ce_servinfo(&c->options, si);
+        }
 #ifdef ENABLE_MANAGEMENT
         if (ce_defined && management &&
 management_query_remote_enabled(management))
         {
src/openvpn/init.c +4 -1
@@ -3652,10 +3703,13 @@ do_close_link_socket(struct context *c)
                ( c->sig->source != SIG_SOURCE_HARD
                  && ((c->c1.link_socket_addr.current_remote
                       && c->c1.link_socket_addr.current_remote->ai_next)
+                     || (c->c1.link_socket_addr.current_service
+                         && c->c1.link_socket_addr.current_service->next)
                      || c->options.no_advance))
                )))
     {
-        clear_remote_addrlist(&c->c1.link_socket_addr, !c-
 >options.resolve_in_advance);
+        clear_remote_servlist(&c->c1.link_socket_addr,
+                              !c->options.resolve_in_advance);
     }
 
Quoted 1 line
     /* Clear the remote actual address when persist_remote_ip is not in

use */

src/openvpn/init.c init_instance(struct context *c, const struct

Quoted 1 line
src/openvpn/init.c +0 -0
@@ -4187,6 +4241,17 @@ init_instance(struct context *c, const struct

env_set

Quoted 23 lines
src/openvpn/init.c +11 -0
 *env, const unsigned int f
     /* map in current connection entry */
     next_connection_entry(c);
 
+    /* map in current remote service */
+    if (c->options.ce.remote_srv)
+    {
+        do_resolve_service(c);
+        if (IS_SIG(c))
+        {
+             goto sig;
+        }
+        update_options_ce_post(&c->options);
+    }
+
     /* link_socket_mode allows CM_CHILD_TCP
      * instances to inherit acceptable fds

* from a top-level parent */

src/openvpn/openvpn.vcxproj +0 -0
index 3863854b..1f317fb0 100644

src/openvpn/openvpn.vcxproj line 95

Quoted 5 lines
src/openvpn/openvpn.vcxproj +0 -1
@@ -92,7 +92,7 @@
     </ClCompile>
     <ResourceCompile />
     <Link>
-
 

<AdditionalDependencies>legacy_stdio_definitions.lib;Ncrypt.lib;libssl.lib;l ibcryp

Quoted 2 lines

to.lib;lzo2.lib;pkcs11-

helper.dll.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;win mm.lib;F

Quoted 1 line

wpuclnt.lib;Rpcrt4.lib;setupapi.lib;%(AdditionalDependencies)</AdditionalDep en

Quoted 3 lines

dencies>
+

<AdditionalDependencies>legacy_stdio_definitions.lib;Ncrypt.lib;libssl.lib;l ibcryp

Quoted 2 lines

to.lib;lzo2.lib;pkcs11-

helper.dll.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;win mm.lib;F

Quoted 1 line

wpuclnt.lib;Rpcrt4.lib;setupapi.lib;dnsapi.lib;%(AdditionalDependencies)</Ad diti

Quoted 4 lines

onalDependencies>

<AdditionalLibraryDirectories>$(OPENSSL_HOME)/lib;$(LZO_HOME)/lib;$(PKCS1

1H_HOME)/lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>

src/openvpn/openvpn.vcxproj line 110

Quoted 8 lines
       <SubSystem>Console</SubSystem>
     </Link>
src/openvpn/openvpn.vcxproj +0 -1
@@ -107,7 +107,7 @@
     </ClCompile>
     <ResourceCompile />
     <Link>
-
 

<AdditionalDependencies>legacy_stdio_definitions.lib;Ncrypt.lib;libssl.lib;l ibcryp

Quoted 2 lines

to.lib;lzo2.lib;pkcs11-

helper.dll.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;win mm.lib;F

Quoted 1 line

wpuclnt.lib;Rpcrt4.lib;setupapi.lib;%(AdditionalDependencies)</AdditionalDep en

Quoted 3 lines

dencies>
+

<AdditionalDependencies>legacy_stdio_definitions.lib;Ncrypt.lib;libssl.lib;l ibcryp

Quoted 2 lines

to.lib;lzo2.lib;pkcs11-

helper.dll.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;win mm.lib;F

Quoted 1 line

wpuclnt.lib;Rpcrt4.lib;setupapi.lib;dnsapi.lib;%(AdditionalDependencies)</Ad diti

Quoted 4 lines

onalDependencies>

<AdditionalLibraryDirectories>$(OPENSSL_HOME)/lib;$(LZO_HOME)/lib;$(PKCS1

1H_HOME)/lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>

src/openvpn/openvpn.vcxproj line 125

Quoted 8 lines
       <SubSystem>Console</SubSystem>
     </Link>
src/openvpn/openvpn.vcxproj +0 -1
@@ -122,7 +122,7 @@
     </ClCompile>
     <ResourceCompile />
     <Link>
-
 

<AdditionalDependencies>legacy_stdio_definitions.lib;Ncrypt.lib;libssl.lib;l ibcryp

Quoted 2 lines

to.lib;lzo2.lib;pkcs11-

helper.dll.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;win mm.lib;F

Quoted 1 line

wpuclnt.lib;Rpcrt4.lib;setupapi.lib;%(AdditionalDependencies)</AdditionalDep en

Quoted 3 lines

dencies>
+

<AdditionalDependencies>legacy_stdio_definitions.lib;Ncrypt.lib;libssl.lib;l ibcryp

Quoted 2 lines

to.lib;lzo2.lib;pkcs11-

helper.dll.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;win mm.lib;F

Quoted 1 line

wpuclnt.lib;Rpcrt4.lib;setupapi.lib;dnsapi.lib;%(AdditionalDependencies)</Ad diti

Quoted 4 lines

onalDependencies>

<AdditionalLibraryDirectories>$(OPENSSL_HOME)/lib;$(LZO_HOME)/lib;$(PKCS1

1H_HOME)/lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>

src/openvpn/openvpn.vcxproj line 140

Quoted 8 lines
       <SubSystem>Console</SubSystem>
     </Link>
src/openvpn/openvpn.vcxproj +0 -1
@@ -137,7 +137,7 @@
     </ClCompile>
     <ResourceCompile />
     <Link>
-
 

<AdditionalDependencies>legacy_stdio_definitions.lib;Ncrypt.lib;libssl.lib;l ibcryp

Quoted 2 lines

to.lib;lzo2.lib;pkcs11-

helper.dll.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;win mm.lib;F

Quoted 1 line

wpuclnt.lib;Rpcrt4.lib;setupapi.lib;%(AdditionalDependencies)</AdditionalDep en

Quoted 3 lines

dencies>
+

<AdditionalDependencies>legacy_stdio_definitions.lib;Ncrypt.lib;libssl.lib;l ibcryp

Quoted 2 lines

to.lib;lzo2.lib;pkcs11-

helper.dll.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;win mm.lib;F

Quoted 1 line

wpuclnt.lib;Rpcrt4.lib;setupapi.lib;dnsapi.lib;%(AdditionalDependencies)</Ad diti

Quoted 4 lines

onalDependencies>

<AdditionalLibraryDirectories>$(OPENSSL_HOME)/lib;$(LZO_HOME)/lib;$(PKCS1

1H_HOME)/lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>

src/openvpn/options.c static const char usage_message[] = · line 124

Quoted 11 lines
       <SubSystem>Console</SubSystem>
     </Link>
src/openvpn/options.c +1 -0
index 21f8d494..edb73f16 100644
@@ -121,6 +121,7 @@ static const char usage_message[] =
     "Tunnel Options:\n"
     "--local host    : Local host name or ip address. Implies --bind.\n"
     "--remote host [port] : Remote host name or ip address.\n"
+    "--remote-srv domain [service] : Perform DNS SRV remote host

discovery.\n"

Quoted 3 lines
src/openvpn/options.c +0 -0
     "--remote-random : If multiple --remote options specified, choose one

randomly.\n"
"--remote-random-hostname : Add a random string to remote DNS

name.\n"

Quoted 32 lines

"--mode m : Major mode, m = 'p2p' (default, point-to-point) or
'server'.\n"

src/openvpn/options.c +1 -0
@@ -1444,6 +1445,7 @@ show_connection_entry(const struct
 connection_entry *o)
     SHOW_STR(local_port);
     SHOW_STR(remote);
     SHOW_STR(remote_port);
+    SHOW_BOOL(remote_srv);
     SHOW_BOOL(remote_float);
     SHOW_BOOL(bind_defined);
     SHOW_BOOL(bind_local);
src/openvpn/options.c +16 -0
@@ -1978,6 +1980,67 @@ connection_entry_load_re(struct connection_entry
 *ce, const struct remote_entry
     {
         ce->af = re->af;
     }
+    ce->remote_srv = re->remote_srv;
+}
+
+/* Part of options_postprocess_verify_ce that can be used
+ * in runtime after connection entry proto/hostname change.
+ */
+static bool
+options_postprocess_verify_ce_proto(const struct options *options,
+                                    const struct connection_entry *ce)
+{
+    int msglevel = M_WARN|M_NOPREFIX|M_OPTERR;
+
+    /*
+     * Sanity check on --local, --remote, and --ifconfig
+     */
+

src/openvpn/options.c connection_entry_load_re(struct connection_entry · line 2009

Quoted 10 lines
src/openvpn/options.c +10 -0
+    if (proto_is_net(ce->proto)
+        && string_defined_equal(ce->local, ce->remote)
+        && string_defined_equal(ce->local_port, ce->remote_port))
+    {
+        msg(msglevel, "--remote and --local addresses are the same");
+        return false;
+    }
+
+    if (string_defined_equal(ce->remote, options->ifconfig_local)
+        || string_defined_equal(ce->remote,

options->ifconfig_remote_netmask))

src/openvpn/options.c connection_entry_load_re(struct connection_entry *ce, const struct remote_entry

Quoted 3 lines
src/openvpn/options.c +3 -0
+    {
+        msg(msglevel,
+            "--local and --remote addresses must be distinct from

--ifconfig "

Quoted 49 lines
src/openvpn/options.c +32 -0
+            "addresses");
+        return false;
+    }
+
+    /*
+     * Check that protocol options make sense.
+     */
+
+#ifdef ENABLE_FRAGMENT
+    if (!proto_is_udp(ce->proto) && ce->fragment)
+    {
+        msg(msglevel, "--fragment can only be used with --proto udp");
+        return false;
+    }
+#endif
+
+    if (!proto_is_udp(ce->proto) && ce->explicit_exit_notification)
+    {
+        msg(msglevel,
+            "--explicit-exit-notify can only be used with --proto udp");
+        return false;
+    }
+
+    if ((ce->http_proxy_options) && ce->proto != PROTO_TCP_CLIENT)
+    {
+        msg(msglevel,
+            "--http-proxy MUST be used in TCP Client mode (i.e. --proto "
+            "tcp-client)");
+        return false;
+    }
+
+    return true;
 }
 

static void

src/openvpn/options.c +5 -0
@@ -2015,6 +2078,11 @@ options_postprocess_verify_ce(const struct options
 *options,
             "--proto tcp-server or --proto tcp-client");
     }
 
+    if (ce->proto == PROTO_AUTO && !ce->remote_srv)
+    {
+        msg(M_USAGE, "--proto auto can be only used with --remote-srv");
+    }
+
     /*
      * Sanity check on daemon/inetd modes
      */

src/openvpn/options.c options_postprocess_verify_ce(const struct options · line 2099

Quoted 10 lines
src/openvpn/options.c +3 -2
@@ -2024,9 +2092,10 @@ options_postprocess_verify_ce(const struct options
 *options,
         msg(M_USAGE, "only one of --daemon or --inetd may be specified");
     }
 
-    if (options->inetd && (ce->local || ce->remote))
+    if (options->inetd && (ce->local || ce->remote || ce->remote_srv))
     {
-        msg(M_USAGE, "--local or --remote cannot be used with --inetd");
+        msg(M_USAGE,
+            "--local or --remote or --remote_srv cannot be used with

--inetd");

Quoted 62 lines
src/openvpn/options.c +0 -0
     }
 
     if (options->inetd && ce->proto == PROTO_TCP_CLIENT)
src/openvpn/options.c +3 -1
@@ -2072,7 +2141,9 @@ options_postprocess_verify_ce(const struct options
 *options,
             "--ifconfig implies --link-mtu %d)", LINK_MTU_DEFAULT);
     }
 
-    if (!proto_is_udp(ce->proto) && options->mtu_test)
+    /* Defer validation for --remote-srv with auto protocol */
+    if (!proto_is_udp(ce->proto) && options->mtu_test
+        && !(ce->remote_srv && ce->proto == PROTO_AUTO))
     {
         msg(M_USAGE, "--mtu-test only makes sense with --proto udp");
     }
src/openvpn/options.c +5 -0
@@ -2086,6 +2157,11 @@ options_postprocess_verify_ce(const struct options
 *options,
      * Sanity check on --local, --remote, and --ifconfig
      */
 
+    if (ce->remote_srv && options->ip_remote_hint)
+    {
+        msg(M_USAGE, "--ip-remote-hint can't be used with --remote-srv");
+    }
+
     if (proto_is_net(ce->proto)
         && string_defined_equal(ce->local, ce->remote)
         && string_defined_equal(ce->local_port, ce->remote_port))
src/openvpn/options.c +6 -2
@@ -2210,13 +2286,17 @@ options_postprocess_verify_ce(const struct
 options *options,
      */
 
 #ifdef ENABLE_FRAGMENT
-    if (!proto_is_udp(ce->proto) && ce->fragment)
+    /* Defer validation for --remote-srv with auto protocol */
+    if (!proto_is_udp(ce->proto) && ce->fragment
+        && !(ce->remote_srv && ce->proto == PROTO_AUTO))
     {
         msg(M_USAGE, "--fragment can only be used with --proto udp");
     }
 #endif
 
-    if (!proto_is_udp(ce->proto) && ce->explicit_exit_notification)
+    /* Defer validation for --remote-srv with auto protocol */
+    if (!proto_is_udp(ce->proto) && ce->explicit_exit_notification
+        && !(ce->remote_srv && ce->proto == PROTO_AUTO))
     {
         msg(M_USAGE,
             "--explicit-exit-notify can only be used with --proto udp");
src/openvpn/options.c +3 -1
@@ -2227,7 +2307,9 @@ options_postprocess_verify_ce(const struct options
 *options,
         msg(M_USAGE, "--remote MUST be used in TCP Client mode");
     }
 
-    if ((ce->http_proxy_options) && ce->proto != PROTO_TCP_CLIENT)
+    /* Defer validation for --remote-srv with auto protocol */
+    if ((ce->http_proxy_options) && ce->proto != PROTO_TCP_CLIENT
+        && !(ce->remote_srv && ce->proto == PROTO_AUTO))
     {
         msg(M_USAGE,

"--http-proxy MUST be used in TCP Client mode (i.e. --proto "

src/openvpn/options.c options_postprocess_verify_ce(const struct options · line 2385

Quoted 7 lines
src/openvpn/options.c +3 -0
@@ -2297,6 +2379,10 @@ options_postprocess_verify_ce(const struct options
 *options,
         {
             msg(M_USAGE, "--remote cannot be used with --mode server");
         }
+        if (ce->remote_srv)
+        {
+            msg(M_USAGE, "--remote-srv cannot be used with --mode

server");

Quoted 44 lines
src/openvpn/options.c +1 -0
+        }
         if (!ce->bind_local)
         {
             msg(M_USAGE, "--nobind cannot be used with --mode server");
src/openvpn/options.c +35 -0
@@ -2815,6 +2901,64 @@ options_postprocess_verify_ce(const struct options
 *options,
     uninit_options(&defaults);
 }
 
+/* Part of options_postprocess_mutate_ce that can be used
+ * in runtime after connection entry proto/hostname change.
+ */
+static bool
+options_postprocess_mutate_ce_proto(struct options *o,
+                                    struct connection_entry *ce)
+{
+    bool result = true;
+
+    if (ce->proto == PROTO_TCP_CLIENT && !ce->local
+        && !ce->local_port_defined && !ce->bind_defined)
+    {
+        ce->bind_local = false;
+    }
+
+    if (ce->proto == PROTO_UDP && ce->socks_proxy_server && !ce->local
+        && !ce->local_port_defined && !ce->bind_defined)
+    {
+        ce->bind_local = false;
+    }
+
+    if (!ce->bind_local)
+    {
+        ce->local_port = NULL;
+    }
+
+    /* if protocol forcing is enabled, disable all protocols
+     * except for the forced one
+     */
+    if (o->proto_force >= 0 && o->proto_force != ce->proto
+        && !(ce->remote_srv && ce->proto == PROTO_AUTO))
+    {
+        result = false;
+    }
+

src/openvpn/options.c options_postprocess_verify_ce(const struct options · line 2949

Quoted 10 lines
src/openvpn/options.c +9 -0
+    /* our socks code is not fully IPv6 enabled yet (TCP works, UDP not)
+     * so fall back to IPv4-only (trac #1221)
+     */
+    if (ce->socks_proxy_server && proto_is_udp(ce->proto) && ce->af !=
 AF_INET)
+    {
+        if (ce->af == AF_INET6)
+        {
+            msg(M_INFO,
+                "WARNING: --proto udp6 is not compatible with

--socks-proxy "

Quoted 57 lines
src/openvpn/options.c +14 -0
+                "today. Forcing IPv4 mode.");
+        }
+        else
+        {
+            msg(M_INFO,
+                "NOTICE: dual-stack mode for --proto udp does not work "
+                "correctly with '--socks-proxy' today.  Forcing IPv4.");
+        }
+        ce->af = AF_INET;
+    }
+
+    return result;
+}
+
 static void

options_postprocess_mutate_ce(struct options *o, struct connection_entry
*ce)
{

src/openvpn/options.c +1 -21
@@ -2838,27 +2982,7 @@ options_postprocess_mutate_ce(struct options *o,
 struct connection_entry *ce)
     }
 #endif
 
-    if (ce->proto == PROTO_TCP_CLIENT && !ce->local
-        && !ce->local_port_defined && !ce->bind_defined)
-    {
-        ce->bind_local = false;
-    }
-
-    if (ce->proto == PROTO_UDP && ce->socks_proxy_server && !ce->local
-        && !ce->local_port_defined && !ce->bind_defined)
-    {
-        ce->bind_local = false;
-    }
-
-    if (!ce->bind_local)
-    {
-        ce->local_port = NULL;
-    }
-
-    /* if protocol forcing is enabled, disable all protocols
-     * except for the forced one
-     */
-    if (o->proto_force >= 0 && o->proto_force != ce->proto)
+    if (!options_postprocess_mutate_ce_proto(o, ce))
     {
         ce->flags |= CE_DISABLED;
     }
src/openvpn/options.c +0 -4
@@ -2879,24 +3003,6 @@ options_postprocess_mutate_ce(struct options *o,
 struct connection_entry *ce)
 #endif
     }
 
-    /* our socks code is not fully IPv6 enabled yet (TCP works, UDP not)
-     * so fall back to IPv4-only (trac #1221)
-     */
-    if (ce->socks_proxy_server && proto_is_udp(ce->proto) && ce->af !=

src/openvpn/options.c options_postprocess_mutate_ce(struct options *o, · line 2896

Quoted 10 lines
src/openvpn/options.c +0 -9
 AF_INET)
-    {
-        if (ce->af == AF_INET6)
-        {
-            msg(M_INFO, "WARNING: '--proto udp6' is not compatible with "
-                "'--socks-proxy' today.  Forcing IPv4 mode." );
-        }
-        else
-        {
-            msg(M_INFO, "NOTICE: dual-stack mode for '--proto udp' does

not "

src/openvpn/options.c options_postprocess_mutate_ce(struct options *o, · line 2897

Quoted 1 line
src/openvpn/options.c +0 -1
-                "work correctly with '--socks-proxy' today.  Forcing

IPv4." );

Quoted 42 lines
src/openvpn/options.c +0 -4
-        }
-        ce->af = AF_INET;
-    }
-
     /*

* Set MTU defaults
*/

src/openvpn/options.c +26 -0
@@ -2964,6 +3070,32 @@ options_postprocess_mutate_ce(struct options *o,
 struct connection_entry *ce)
     }
 }
 
+/*
+ * Merges servinfo's hostname, servname and proto into current connection
+ * entry if possible and doesn't conflict with the options.
+ * Used by runtime DNS SRV discovery.
+ */
+bool
+options_mutate_ce_servinfo(struct options *o, struct servinfo *si)
+{
+    struct connection_entry ce = o->ce;
+
+    ASSERT(ce.remote_srv);
+
+    ce.remote = si->hostname;
+    ce.remote_port = si->servname;
+    ce.proto = si->proto;
+
+    if (options_postprocess_mutate_ce_proto(o, &ce)
+        && options_postprocess_verify_ce_proto(o, &ce))
+    {
+        o->ce = ce;
+        return true;
+    }
+
+    return false;
+}
+
 #ifdef _WIN32
 /* If iservice is in use, we need def1 method for redirect-gateway */

static void

src/openvpn/options.c add_option(struct options *options, · line 5624

Quoted 4 lines
src/openvpn/options.c +0 -1
@@ -5621,7 +5753,9 @@ add_option(struct options *options,
                                OPT_P_CONNECTION, option_types_found, es);
             if (!sub.ce.remote)
             {
-                msg(msglevel, "Each 'connection' block must contain

exactly one

Quoted 41 lines
src/openvpn/options.c +3 -0
 'remote' directive");
+                msg(msglevel,
+                    "Each 'connection' block must contain exactly one "
+                    "'remote' or 'remote-srv' directive");
                 uninit_options(&sub);
                 goto err;
             }
src/openvpn/options.c +23 -0
@@ -5699,6 +5833,7 @@ add_option(struct options *options,
     {
         struct remote_entry re;
         re.remote = re.remote_port = NULL;
+        re.remote_srv = false;
         re.proto = -1;
         re.af = 0;
 
@@ -5733,6 +5868,63 @@ add_option(struct options *options,
         }
         else if (permission_mask & OPT_P_CONNECTION)
         {
+            if (options->ce.remote && options->ce.remote_srv)
+            {
+                msg(msglevel,
+                    "Each 'connection' block must contain exactly one "
+                    "'remote' or 'remote-srv' directive");
+                goto err;
+            }
+            connection_entry_load_re(&options->ce, &re);
+        }
+    }
+    else if (streq(p[0], "remote-srv") && p[1] && !p[4])
+    {
+        struct remote_entry re;
+        re.remote = NULL;
+        re.remote_port = OPENVPN_SERVICE;
+        re.remote_srv = true;
+        re.proto = PROTO_AUTO;
+        re.af = 0;
+
+        VERIFY_PERMISSION(OPT_P_GENERAL|OPT_P_CONNECTION);
+        re.remote = p[1];
+        if (p[2])

src/openvpn/options.c add_option(struct options *options, · line 5902

Quoted 10 lines
src/openvpn/options.c +10 -0
+        {
+            re.remote_port = p[2];
+            if (p[3])
+            {
+                const int proto = ascii2proto(p[3]);
+                const sa_family_t af = ascii2af(p[3]);
+                if (proto < 0)
+                {
+                    msg(msglevel,
+                        "remote-srv: bad protocol associated with domain

%s: "

src/openvpn/options.c add_option(struct options *options,

Quoted 10 lines
src/openvpn/options.c +10 -0
+                        "'%s'", p[1], p[3]);
+                    goto err;
+                }
+                re.proto = proto;
+                re.af = af;
+            }
+        }
+        if (permission_mask & OPT_P_GENERAL)
+        {
+            struct remote_entry *e = alloc_remote_entry(options,

msglevel);

Quoted 534 lines
src/openvpn/options.c +16 -1
+            if (!e)
+            {
+                goto err;
+            }
+            *e = re;
+        }
+        else if (permission_mask & OPT_P_CONNECTION)
+        {
+            if (options->ce.remote && !options->ce.remote_srv)
+            {
+                msg(msglevel,
+                    "Each 'connection' block must contain exactly one "
+                    "'remote' or 'remote-srv' directive");
+                goto err;
+            }
             connection_entry_load_re(&options->ce, &re);
         }
     }
@@ -6249,7 +6441,7 @@ add_option(struct options *options,
         int proto_force;
         VERIFY_PERMISSION(OPT_P_GENERAL);
         proto_force = ascii2proto(p[1]);
-        if (proto_force < 0)
+        if (proto_force < 0 || proto_force == PROTO_AUTO)
         {
             msg(msglevel, "Bad --proto-force protocol: '%s'", p[1]);
             goto err;
src/openvpn/options.h +4 -0
index 5b6d9441..51432a26 100644
@@ -92,6 +92,7 @@ struct connection_entry
     const char *remote_port;
     const char *local;
     const char *remote;
+    bool remote_srv;
     bool remote_float;
     bool bind_defined;
     bool bind_ipv6_only;
@@ -152,6 +153,7 @@ struct remote_entry
     const char *remote_port;
     int proto;
     sa_family_t af;
+    bool remote_srv;
 };
 
 #define CONNECTION_LIST_SIZE 64
@@ -790,6 +792,8 @@ char *options_string_extract_option(const char
 *options_string,
 
 void options_postprocess(struct options *options);
 
+bool options_mutate_ce_servinfo(struct options *o, struct servinfo *si);
+
 void pre_pull_save(struct options *o);
 

void pre_pull_restore(struct options *o, struct gc_arena *gc);

src/openvpn/socket.c +31 -0
index 97750681..31e8fe9a 100644
@@ -282,6 +282,37 @@ get_cached_dns_entry(struct cached_dns_entry
 *dns_cache,
     return -1;
 }
 
+/*
+ * get_cached_srv_entry return 0 on success and -1
+ * otherwise. (like getservinfo)
+ */
+static int
+get_cached_srv_entry(struct cached_dns_entry *dns_cache,
+                     const char *hostname,
+                     const char *servname,
+                     int ai_family,
+                     int resolve_flags,
+                     struct servinfo **si)
+{
+    struct cached_dns_entry *ph;
+    int flags;
+
+    /* Only use flags that are relevant for the structure */
+    flags = resolve_flags & GETADDR_CACHE_SERVICE_MASK;
+    flags |= GETADDR_SERVICE;
+
+    for (ph = dns_cache; ph; ph = ph->next)
+    {
+        if (streqnull(ph->hostname, hostname)
+            && streqnull(ph->servname, servname)
+            && ph->flags == flags)
+        {
+            *si = ph->si;
+            return 0;
+        }
+    }
+    return -1;
+}
 
 static int

do_preresolve_host(struct context *c,

src/openvpn/socket.c +412 -1
@@ -337,6 +368,77 @@ do_preresolve_host(struct context *c,
     return status;
 }
 
+static int
+do_preresolve_service(struct context *c,
+                      const char *hostname,
+                      const char *servname,
+                      const int af,
+                      const int flags,
+                      bool preresolve_host)
+{
+    struct servinfo *si;
+    int status;
+
+    if (get_cached_srv_entry(c->c1.dns_cache,
+                             hostname,
+                             servname,
+                             af,
+                             flags,
+                             &si) == 0)
+    {
+        /* entry already cached, return success */
+        return 0;
+    }
+
+    status = openvpn_getservinfo(flags, hostname, servname,
+                                 c->options.resolve_retry_seconds, NULL,
+                                 af, &si);
+    if (status == 0)
+    {
+        struct cached_dns_entry *ph;
+
+        ALLOC_OBJ_CLEAR_GC(ph, struct cached_dns_entry, &c->gc);
+        ph->si = si;
+        ph->hostname = hostname;
+        ph->servname = servname;
+        ph->flags = flags & GETADDR_CACHE_SERVICE_MASK;
+
+        if (!c->c1.dns_cache)
+        {
+            c->c1.dns_cache = ph;
+        }
+        else
+        {
+            struct cached_dns_entry *prev = c->c1.dns_cache;
+            while (prev->next)
+            {
+                prev = prev->next;
+            }
+            prev->next = ph;
+        }
+
+        gc_addspecial(si, &gc_freeservinfo_callback, &c->gc);
+
+        /* preresolve service targets unless disabled */
+        if (preresolve_host)
+        {
+            while (si)
+            {
+                int host_flags = flags & ~GETADDR_PROTO_MASK;
+                if (proto_is_dgram(si->proto))
+                {
+                    host_flags |= GETADDR_DATAGRAM;
+                }
+                /* ignore errors */
+                do_preresolve_host(c, si->hostname, si->servname,
+                                   af, host_flags);
+                si = si->next;
+            }
+        }
+    }
+    return status;
+}
+
 void
 do_preresolve(struct context *c)
 {
@@ -375,8 +477,31 @@ do_preresolve(struct context *c)
             remote = ce->remote;
         }
 
+        /* Preresolve remote services */
+        if (ce->remote_srv)
+        {
+            int service_flags = flags|GETADDR_SERVICE;
+
+            if (proto_is_dgram(ce->proto) || ce->proto == PROTO_AUTO)
+            {
+                service_flags |= GETADDR_DATAGRAM;
+            }
+            if (proto_is_stream(ce->proto) || ce->proto == PROTO_AUTO)
+            {
+                service_flags |= GETADDR_STREAM;
+            }
+
+            /* HTTP remote hostnames does not need to be resolved */
+            status = do_preresolve_service(c, remote, ce->remote_port,
+                                           ce->af, service_flags,
+                                           !ce->http_proxy_options);
+            if (status != 0)
+            {
+                goto err;
+            }
+        }
         /* HTTP remote hostname does not need to be resolved */
-        if (!ce->http_proxy_options)
+        else if (!ce->http_proxy_options)
         {
             status = do_preresolve_host(c, remote, ce->remote_port,
                                         ce->af, flags);
@@ -434,6 +559,630 @@ err:
     throw_signal_soft(SIGHUP, "Preresolving failed");
 }
 
+/**
+ * Allocates new service structure on heap and stores
+ * its initial values.
+ *
+ * @param hostname - The peer host name or ip address
+ * @param port     - The peer TCP/UDP port
+ * @param proto    - Protocol for communicating with the peer
+ *
+ * @return A pointer to servinfo structure or NULL in case of
+ *     allocation error.
+ */
+static struct servinfo *
+alloc_servinfo(const char *hostname, uint16_t port, int proto)
+{
+    size_t namesize = hostname ? strlen(hostname) + 1 : 0;
+
+    char servname[sizeof("65535")];
+    openvpn_snprintf(servname, sizeof(servname), "%u", port);
+    size_t servsize = strlen(servname) + 1;
+
+    struct servinfo *si = calloc(1, sizeof(*si) + namesize + servsize);
+    if (si)
+    {
+        if (hostname)
+        {
+            si->hostname = (char *)(si + 1);
+            memcpy((char *)si->hostname, hostname, namesize);
+        }
+        si->servname = (char *)(si + 1) + namesize;
+        memcpy((char *)si->servname, servname, servsize);
+        si->proto = proto;
+    }
+    return si;
+}
+
+#ifdef _WIN32
+/**
+ * Queries DNS SRV records for specified DNS domain.
+ *
+ * @param domain - The DNS domain name
+ * @param proto  - TCP/UDP protocol for communicating with the peer
+ * @param next   - The servinfo structure list to be chained to
+ *                 the resulting servinfo list
+ * @param res    - The pointer to the resulting servinfo list
+ *
+ * @return 0 on success, a EAI-* status code otherwise
+ */
+static int
+query_servinfo(const char *domain, int proto,
+               struct servinfo *next, struct servinfo **res)
+{
+    PDNS_RECORD pDnsRecord;
+    int status;
+
+    ASSERT(res);
+
+    DNS_STATUS DnsStatus = DnsQuery(domain, DNS_TYPE_SRV,
 DNS_QUERY_STANDARD,
+                                    NULL, &pDnsRecord, NULL);
+    dmsg(D_SOCKET_DEBUG, "DNSQUERY type=%d domain=%s result=%d",
+         DNS_TYPE_SRV, domain, DnsStatus);
+    switch (DnsStatus)
+    {
+        case ERROR_SUCCESS:
+            break;
+
+        case DNS_ERROR_RCODE_NAME_ERROR:
+        case DNS_INFO_NO_RECORDS:
+            return EAI_NONAME; /* HOST_NOT_FOUND */
+
+        case DNS_ERROR_NO_DNS_SERVERS:
+        case DNS_ERROR_RCODE_FORMAT_ERROR:
+        case DNS_ERROR_RCODE_NOT_IMPLEMENTED:
+        case DNS_ERROR_RCODE_REFUSED:
+            return EAI_FAIL; /* NO_RECOVERY */
+
+        case ERROR_TIMEOUT:
+        case DNS_ERROR_RCODE_SERVER_FAILURE:
+        case DNS_ERROR_TRY_AGAIN_LATER:
+            return EAI_AGAIN; /* TRY_AGAIN */
+
+        default:
+            return EAI_FAIL;
+    }
+
+    struct servinfo *list = NULL, *first = NULL;
+    for (PDNS_RECORD rr = pDnsRecord; rr; rr = rr->pNext)
+    {
+        if (rr->wType == DNS_TYPE_SRV)
+        {
+            PDNS_SRV_DATA rdata = &rr->Data.Srv;
+
+            if (rr->wDataLength >= sizeof(DNS_SRV_DATA)
+                && *rdata->pNameTarget)
+            {
+                struct servinfo *si = alloc_servinfo(rdata->pNameTarget,
+                                                     rdata->wPort,
+                                                     proto);
+                if (!si)
+                {
+                    freeservinfo(list);
+                    status = EAI_MEMORY;
+                    goto done;
+                }
+                si->prio = rdata->wPriority;
+                si->weight = rdata->wWeight;
+                si->next = list, list = si;
+                if (!first)
+                {
+                    first = si;
+                }
+            }
+        }
+    }
+    if (list)
+    {
+        first->next = next;
+        *res = list;
+        status = 0;
+    }
+    else
+    {
+        status = EAI_FAIL;
+    }
+
+done:
+    DnsRecordListFree(pDnsRecord, DnsFreeRecordList);
+    return status;
+}
+
+#else
+/**
+ * Queries DNS SRV records for specified DNS domain.
+ *
+ * @param domain - The DNS domain name
+ * @param proto  - TCP/UDP protocol for communicating with the peer
+ * @param next   - The servinfo structure list to be chained to
+ *                 the resulting servinfo list
+ * @param res    - The pointer to the resulting servinfo list
+ *
+ * @return 0 on success, a EAI-* status code otherwise
+ */
+static int
+query_servinfo(const char *domain, int proto,
+               struct servinfo *next, struct servinfo **res)
+{
+    unsigned char answer[65535];
+    int status;
+
+    int n = res_query(domain, ns_c_in, ns_t_srv, answer, sizeof(answer));
+    dmsg(D_SOCKET_DEBUG, "RES_QUERY class=%d type=%d domain=%s
 result=%d",
+         ns_c_in, ns_t_srv, domain, n);
+    if (n < 0)
+    {
+        switch (h_errno)
+        {
+            case HOST_NOT_FOUND:
+            case NO_ADDRESS:
+#if NO_ADDRESS != NO_DATA
+            case NO_DATA:
+#endif
+                return EAI_NONAME;
+
+            case NO_RECOVERY:
+                return EAI_FAIL;
+
+            case TRY_AGAIN:
+                return EAI_AGAIN;
+        }
+        return EAI_SYSTEM;
+    }
+
+    ns_msg msg;
+    if (ns_initparse(answer, n, &msg) < 0)
+    {
+        return EAI_FAIL;
+    }
+
+    struct servinfo *list = NULL, *first = NULL;
+    for (int i = 0; i < ns_msg_count(msg, ns_s_an); i++)
+    {
+        ns_rr rr;
+
+        if (ns_parserr(&msg, ns_s_an, i, &rr) == 0
+            && ns_rr_type(rr) == ns_t_srv)
+        {
+            const unsigned char *rdata = ns_rr_rdata(rr);
+            char name[NS_MAXDNAME];
+
+            if (ns_rr_rdlen(rr) > 6
+                && dn_expand(ns_msg_base(msg), ns_msg_end(msg),
+                             rdata + 6, name, sizeof(name)) > 0 && *name)
+            {
+                struct servinfo *si = alloc_servinfo(name,
+                                                     ns_get16(rdata + 4),
+                                                     proto);
+                if (!si)
+                {
+                    freeservinfo(list);
+                    status = EAI_MEMORY;
+                    goto done;
+                }
+                si->prio = ns_get16(rdata);
+                si->weight = ns_get16(rdata + 2);
+                si->next = list, list = si;
+                if (!first)
+                {
+                    first = si;
+                }
+            }
+        }
+    }
+    if (list)
+    {
+        first->next = next;
+        *res = list;
+        status = 0;
+    }
+    else
+    {
+        status = EAI_FAIL;
+    }
+
+done:
+    return status;
+}
+#endif
+
+/**
+ * Servinfo qsort compare function for the server selection
+ * mechanism, defined in RFC 2782.
+ *
+ * @param a - Pointer to first servinfo structure
+ * @param b - Pointer to second servinfo structure
+ *
+ * @return
+ * @li 0, if equal
+ * @li 1, if "a" should be ordered after "b"
+ * @li -1, if "a" should be ordered before "b"
+ */
+static int
+servinfo_cmp(const void *a, const void *b)
+{
+    const struct servinfo *ae = *(struct servinfo **)a;
+    const struct servinfo *be = *(struct servinfo **)b;
+
+    /* lowest-numbered priority first */
+    if (ae->prio != be->prio)
+    {
+        return ae->prio < be->prio ? -1 : 1;
+    }
+
+    /* zero-weighted first */
+    if ((ae->weight == 0 && be->weight)
+        || (ae->weight && be->weight == 0))
+    {
+        return ae->weight < be->weight ? -1 : 1;
+    }
+
+    /* else keep received order, can't be equal */
+    return ae->order > be->order ? -1 : 1;
+}
+
+/**
+ * Sorts service list according the server selection mechanism,
+ * defined in RFC 2782.
+ *
+ * @param list - The pointer to servinfo list
+ *
+ * @return A pointer to the sorted servinfo list
+ */
+static struct servinfo *
+sort_servinfo(struct servinfo *list)
+{
+    struct servinfo ordered, *tail = &ordered;
+    int count = 0;
+    struct gc_arena gc = gc_new();
+
+    ASSERT(list);
+
+    /* count and number entries in reverse order */
+    for (struct servinfo *si = list; si; si = si->next)
+    {
+        si->order = count++;
+    }
+
+    struct servinfo **sorted;
+    ALLOC_ARRAY_CLEAR_GC(sorted, struct servinfo *, count, &gc);
+    for (struct servinfo *si = list; si; si = si->next)
+    {
+        sorted[si->order] = si;
+    }
+
+    /* sort records by priority and zero weight */
+    qsort(sorted, count, sizeof(sorted[0]), servinfo_cmp);
+
+    /* apply weighted selection mechanism */
+    ordered.next = NULL;
+    for (int i = 0; i < count;)
+    {
+        struct servinfo unordered;
+
+        /* compute the sum of the weights of records of the same
+         * priority and put them in the unordered list */
+        unordered.prio = sorted[i]->prio;
+        unordered.weight = 0;
+        unordered.next = NULL;
+        for (struct servinfo *prev = &unordered;
+             i < count && sorted[i]->prio == unordered.prio; i++)
+        {
+            unordered.weight += sorted[i]->weight;
+
+            /* add entry to the tail of unordered list */
+            sorted[i]->next = NULL;
+            prev->next = sorted[i], prev = sorted[i];
+        }
+
+        /* process the unordered list */

src/openvpn/socket.c err: · line 890

Quoted 10 lines
src/openvpn/socket.c +10 -0
+        while (unordered.next)
+        {
+            /* choose a uniform random number between 0 and the sum
+             * computed (inclusive) */
+            int weight = get_random() % (unordered.weight + 1);
+
+            /* select the entries whose running sum value is the first
+             * in the selected order which is greater than or equal
+             * to the random number selected */
+            for (struct servinfo *si = unordered.next, *prev =

&unordered;

Quoted 5 lines
src/openvpn/socket.c +5 -0
+                 si; prev = si, si = si->next)
+            {
+                /* selected entry is the next one to be contacted */
+                if (si->weight >= weight)
+                {

src/openvpn/socket.c err:

Quoted 10 lines
src/openvpn/socket.c +10 -0
+                    unordered.weight -= si->weight;
+
+                    /* move entry to the ordered list */
+                    prev->next = si->next;
+                    si->next = NULL;
+                    tail->next = si, tail = si;
+
+                    /*
+                     * RFC 2782 is ambiguous, it says:
+                     *   In the presence of records containing weights

greater

src/openvpn/socket.c err:

Quoted 3 lines
src/openvpn/socket.c +3 -0
+                     *   than 0, records with weight 0 should have a very
+                     *   small chance of being selected.
+                     * According that, within the same priority, after

all

src/openvpn/socket.c err: · line 909

Quoted 1 line
src/openvpn/socket.c +1 -0
+                     * records containing weights greater than 0 were

selected,

Quoted 1 line
src/openvpn/socket.c +1 -0
+                     * the rest of records with weight 0 should be

skipped.

src/openvpn/socket.c

Quoted 2 lines
src/openvpn/socket.c +2 -0
+                     * At the same time, it says:
+                     *   The following algorithm SHOULD be used to order

the

src/openvpn/socket.c err:

Quoted 8 lines
src/openvpn/socket.c +8 -0
+                     *   SRV RRs of the same priority:
+                     *   ...
+                     *   Continue the ordering process until there are no
+                     *   unordered SRV RRs.
+                     * This means records with wight 0 should always be
+                     * selected, as last ones in worst case.
+                     *
+                     * We implement the second option and do not skip any

of

Quoted 1 line

+ * the records with unordered.weight == 0 after the

last

Quoted 135 lines
src/openvpn/socket.c +135 -0
+                     * one with weight greater than 0.
+                     */
+                }
+                weight -= si->weight;
+            }
+        }
+    }
+
+    gc_free(&gc);
+    return ordered.next;
+}
+
+/**
+ * Resolves DNS SRV records for given domain and service names.
+ *
+ * @param domain  - The DNS SRV domain name
+ * @param service - The DNS SRV service name
+ * @param flags   - GETADDR_* DNS resultion flags
+ * @param res     - The pointer to the resulting servinfo list
+ *
+ * @return 0 on success, a EAI-* status code otherwise
+ */
+static int
+getservinfo(const char *domain,
+            const char *service,
+            int flags,
+            struct servinfo **res)
+{
+    static const struct {
+        int flags;
+        int proto;
+        const char *name;
+    } proto[] = {
+        { GETADDR_DATAGRAM, PROTO_UDP, "udp" },
+        { GETADDR_STREAM, PROTO_TCP_CLIENT, "tcp" }
+    };
+    struct servinfo *list = NULL;
+    int status = EAI_SOCKTYPE;
+
+    ASSERT(res);
+
+    if (!domain)
+    {
+        return EAI_NONAME;
+    }
+    if (!service)
+    {
+        return EAI_SERVICE;
+    }
+
+    int proto_flags = flags & GETADDR_PROTO_MASK;
+    for (int i = 0; i < SIZE(proto); i++)
+    {
+        if (proto_flags & proto[i].flags)
+        {
+            proto_flags &= ~proto[i].flags;
+
+            char qname[256];
+            if (!openvpn_snprintf(qname, sizeof(qname), "_%s._%s.%s",
+                                  service, proto[i].name, domain))
+            {
+                freeservinfo(list);
+                return EAI_MEMORY;
+            }
+
+            status = query_servinfo(qname, proto[i].proto, list, &list);
+        }
+    }
+
+    if (list)
+    {
+        *res = sort_servinfo(list);
+        status = 0;
+    }
+
+    return status;
+}
+
+void
+freeservinfo(struct servinfo *res)
+{
+    while (res)
+    {
+        struct servinfo *si = res;
+        res = res->next;
+        free(si);
+    }
+}
+
+/*
+ * Translate IPv4/IPv6 hostname and service name into struct servinfo
+ * If resolve error, try again for resolve_retry_seconds seconds.
+ */
+int
+openvpn_getservinfo(unsigned int flags,
+                    const char *hostname,
+                    const char *servname,
+                    int resolve_retry_seconds,
+                    volatile int *signal_received,
+                    int family,
+                    struct servinfo **res)
+{
+    int status;
+    int sigrec = 0;
+    int msglevel = (flags & GETADDR_FATAL) ? M_FATAL : D_RESOLVE_ERRORS;
+    struct gc_arena gc = gc_new();
+    const char *print_hostname;
+    const char *print_servname;
+
+    ASSERT(res);
+
+    ASSERT(hostname || servname);
+    ASSERT(!(flags & GETADDR_HOST_ORDER));
+
+    if (hostname)
+    {
+        print_hostname = hostname;
+    }
+    else
+    {
+        print_hostname = "undefined";
+    }
+
+    if (servname)
+    {
+        print_servname = servname;
+    }
+    else
+    {
+        print_servname = "";
+    }
+
+    if (flags & GETADDR_MSG_VIRT_OUT)
+    {
+        msglevel |= M_MSG_VIRT_OUT;

src/openvpn/socket.c err:

Quoted 10 lines
src/openvpn/socket.c +10 -0
+    }
+
+    if ((flags & (GETADDR_FATAL_ON_SIGNAL|GETADDR_WARN_ON_SIGNAL))
+        && !signal_received)
+    {
+        signal_received = &sigrec;
+    }
+
+    const int fail_wait_interval = 5; /* seconds */
+    /* Add +4 to cause integer division rounding up (1 + 4) = 5,

(0+4)/5=0 */

src/openvpn/socket.c

Quoted 2 lines
src/openvpn/socket.c +2 -0
+    int resolve_retries = (flags & GETADDR_TRY_ONCE) ? 1 :
+                          ((resolve_retry_seconds + 4)/

fail_wait_interval);

Quoted 39 lines
src/openvpn/socket.c +39 -0
+    const char *fmt;
+    int level = 0;
+
+    fmt = "RESOLVE: Cannot resolve remote service: %s:%s (%s)";
+    if ((flags & GETADDR_MENTION_RESOLVE_RETRY)
+        && !resolve_retry_seconds)
+    {
+        fmt = "RESOLVE: Cannot resolve remote service: %s:%s (%s) "
+              "(I would have retried this name query if you had "
+              "specified the --resolv-retry option.)";
+    }
+
+#ifdef ENABLE_MANAGEMENT
+    if (flags & GETADDR_UPDATE_MANAGEMENT_STATE)
+    {
+        if (management)
+        {
+            management_set_state(management,
+                                 OPENVPN_STATE_RESOLVE,
+                                 NULL,
+                                 NULL,
+                                 NULL,
+                                 NULL,
+                                 NULL);
+        }
+    }
+#endif
+
+    /*
+     * Resolve service
+     */
+    while (true)
+    {
+#ifndef _WIN32
+        /* force resolv.conf reload */
+        res_init();
+#endif
+        dmsg(D_SOCKET_DEBUG, "GETSERVINFO flags=0x%04x family=%d %s:%s",
+             flags, family, print_hostname, print_servname);

src/openvpn/socket.c err:

Quoted 10 lines
src/openvpn/socket.c +10 -0
+        status = getservinfo(hostname, servname, flags, res);
+
+        if (signal_received)
+        {
+            get_signal(signal_received);
+            if (*signal_received) /* were we interrupted by a signal? */
+            {
+                if (*signal_received == SIGUSR1) /* ignore SIGUSR1 */
+                {
+                    msg(level, "RESOLVE: Ignored SIGUSR1 signal received

"

Quoted 54 lines
src/openvpn/socket.c +54 -0
+                        "during DNS resolution attempt");
+                    *signal_received = 0;
+                }
+                else
+                {
+                    /* turn success into failure (interrupted syscall) */
+                    if (0 == status)
+                    {
+                        ASSERT(res);
+                        freeservinfo(*res);
+                        *res = NULL;
+                        status = EAI_AGAIN; /* = temporary failure */
+                        errno = EINTR;
+                    }
+                    goto done;
+                }
+            }
+        }
+
+        /* success? */
+        if (0 == status)
+        {
+            break;
+        }
+
+        /* resolve lookup failed, should we
+         * continue or fail? */
+        level = msglevel;
+        if (resolve_retries > 0)
+        {
+            level = D_RESOLVE_ERRORS;
+        }
+
+        msg(level,
+            fmt,
+            print_hostname,
+            print_servname,
+            gai_strerror(status));
+
+        if (--resolve_retries <= 0)
+        {
+            goto done;
+        }
+
+        management_sleep(fail_wait_interval);
+    }
+
+    ASSERT(res);
+
+    /* service resolve succeeded */
+
+done:
+    if (signal_received && *signal_received)
+    {

src/openvpn/socket.c err:

Quoted 10 lines
src/openvpn/socket.c +10 -0
+        int level = 0;
+        if (flags & GETADDR_FATAL_ON_SIGNAL)
+        {
+            level = M_FATAL;
+        }
+        else if (flags & GETADDR_WARN_ON_SIGNAL)
+        {
+            level = M_WARN;
+        }
+        msg(level, "RESOLVE: signal received during DNS resolution

attempt");

Quoted 10 lines
src/openvpn/socket.c +6 -0
+    }
+
+    gc_free(&gc);
+    return status;
+}
+
 /*
  * Translate IPv4/IPv6 addr or hostname into struct addrinfo
  * If resolve error, try again for resolve_retry_seconds seconds.

src/openvpn/socket.c openvpn_getaddrinfo(unsigned int flags, · line 1320

Quoted 6 lines
src/openvpn/socket.c +1 -2
@@ -568,8 +1317,9 @@ openvpn_getaddrinfo(unsigned int flags,
             /* try hostname lookup */
             hints.ai_flags &= ~AI_NUMERICHOST;
             dmsg(D_SOCKET_DEBUG,
-                 "GETADDRINFO flags=0x%04x ai_family=%d ai_socktype=%d",
-                 flags, hints.ai_family, hints.ai_socktype);
+                 "GETADDRINFO flags=0x%04x ai_family=%d ai_socktype=%d

%s:%s",

Quoted 32 lines
src/openvpn/socket.c +25 -0
+                 flags, hints.ai_family, hints.ai_socktype,
+                 print_hostname, print_servname);
             status = getaddrinfo(hostname, servname, &hints, res);
 
             if (signal_received)
@@ -1862,7 +2612,110 @@ done:
     gc_free(&gc);
 }
 
+void
+do_resolve_service(struct context *c)
+{
+    struct connection_entry *ce = &c->options.ce;
+
+    if (ce->remote_srv
+        && !c->c1.link_socket_addr.service_list)
+    {
+        if (ce->remote)
+        {
+            unsigned int flags = sf2gaf(GETADDR_RESOLVE|
+                                        GETADDR_UPDATE_MANAGEMENT_STATE|
+                                        GETADDR_SERVICE,
+                                        c->options.sockflags);
+            int retry = 0;
+            int status = -1;
+            struct servinfo *si;
+
+            if (proto_is_dgram(ce->proto) || ce->proto == PROTO_AUTO)
+            {
+                flags |= GETADDR_DATAGRAM;
+            }
+            if (proto_is_stream(ce->proto) || ce->proto == PROTO_AUTO)

src/openvpn/socket.c done: · line 2647

Quoted 10 lines
src/openvpn/socket.c +10 -0
+            {
+                flags |= GETADDR_STREAM;
+            }
+
+            if (c->options.sockflags & SF_HOST_RANDOMIZE)
+            {
+                flags |= GETADDR_RANDOMIZE;
+            }
+
+            if (c->options.resolve_retry_seconds ==

RESOLV_RETRY_INFINITE)

Quoted 13 lines
src/openvpn/socket.c +13 -0
+            {
+                flags |= (GETADDR_TRY_ONCE | GETADDR_FATAL);
+                retry = 0;
+            }
+            else if (c->options.resolve_retry_seconds)
+            {
+                flags |= GETADDR_FATAL;
+                retry = c->options.resolve_retry_seconds;
+            }
+            else
+            {
+                flags |= (GETADDR_FATAL | GETADDR_MENTION_RESOLVE_RETRY);
+                retry = 0;

src/openvpn/socket.c done:

Quoted 10 lines
src/openvpn/socket.c +10 -0
+            }
+
+            status = get_cached_srv_entry(c->c1.dns_cache,
+                                          ce->remote,
+                                          ce->remote_port,
+                                          ce->af,
+                                          flags, &si);
+            if (status)
+            {
+                status = openvpn_getservinfo(flags, ce->remote,

ce->remote_port,

src/openvpn/socket.c done: · line 2707

Quoted 1 line
src/openvpn/socket.c +1 -0
+                                             retry,

&c->sig->signal_received,

Quoted 11 lines
src/openvpn/socket.c +11 -0
+                                             ce->af, &si);
+            }
+
+            if (status == 0)
+            {
+                c->c1.link_socket_addr.service_list = si;
+                c->c1.link_socket_addr.current_service = NULL;
+
+                /* advance to the first appropriate service */
+                while (si)
+                {

src/openvpn/socket.c done:

Quoted 10 lines
src/openvpn/socket.c +10 -0
+                    /* map in current service */
+                    if (!c->c1.link_socket_addr.current_service
+                        && options_mutate_ce_servinfo(&c->options, si))
+                    {
+                        c->c1.link_socket_addr.current_service = si;
+                    }
+
+                    /* log discovered service hosts */
+                    msg(D_RESOLVE,
+                        "Resolved remote service host: %s:%s,%s prio %u

weight %u",

src/openvpn/socket.c done:

Quoted 13 lines
src/openvpn/socket.c +12 -0
+                        np(si->hostname), np(si->servname),
+                        proto2ascii(si->proto, ce->af, false),
+                        si->prio, si->weight);
+
+                    si = si->next;
+                }
+                if (!c->c1.link_socket_addr.current_service)
+                {
+                    status = EAI_NODATA;
+                }
 
+                dmsg(D_SOCKET_DEBUG,
+                     "RESOLVE_SERVICE flags=0x%04x rrs=%d sig=%d

status=%d",

Quoted 230 lines
src/openvpn/socket.c +28 -1
+                     flags,
+                     retry,
+                     c->sig->signal_received,
+                     status);
+            }
+
+            if (!c->sig->signal_received && status != 0)
+            {
+                c->sig->signal_received = SIGUSR1;
+            }
+        }
+    }
+}
 
 struct link_socket *
 link_socket_new(void)
@@ -3172,16 +4025,19 @@ static const struct proto_names proto_names[] = {
     {"tcp-server",  "TCP_SERVER", AF_UNSPEC, PROTO_TCP_SERVER},
     {"tcp-client",  "TCP_CLIENT", AF_UNSPEC, PROTO_TCP_CLIENT},
     {"tcp",         "TCP", AF_UNSPEC, PROTO_TCP},
+    {"auto",        "AUTO", AF_UNSPEC, PROTO_AUTO},
     /* force IPv4 */
     {"udp4",        "UDPv4", AF_INET, PROTO_UDP},
     {"tcp4-server", "TCPv4_SERVER", AF_INET, PROTO_TCP_SERVER},
     {"tcp4-client", "TCPv4_CLIENT", AF_INET, PROTO_TCP_CLIENT},
     {"tcp4",        "TCPv4", AF_INET, PROTO_TCP},
+    {"auto4",       "AUTOv4", AF_INET, PROTO_AUTO},
     /* force IPv6 */
     {"udp6",        "UDPv6", AF_INET6, PROTO_UDP},
     {"tcp6-server", "TCPv6_SERVER", AF_INET6, PROTO_TCP_SERVER},
     {"tcp6-client", "TCPv6_CLIENT", AF_INET6, PROTO_TCP_CLIENT},
     {"tcp6",        "TCPv6", AF_INET6, PROTO_TCP},
+    {"auto6",       "AUTOv6", AF_INET6, PROTO_AUTO},
 };
 
 bool
@@ -3191,7 +4047,7 @@ proto_is_net(int proto)
     {
         ASSERT(0);
     }
-    return proto != PROTO_NONE;
+    return proto != PROTO_NONE && proto != PROTO_AUTO;
 }
 
 bool
@@ -3200,6 +4056,12 @@ proto_is_dgram(int proto)
     return proto_is_udp(proto);
 }
 
+bool
+proto_is_stream(int proto)
+{
+    return proto_is_tcp(proto);
+}
+
 bool
 proto_is_udp(int proto)
 {
@@ -3278,6 +4140,11 @@ proto2ascii_all(struct gc_arena *gc)
 
     for (i = 0; i < SIZE(proto_names); ++i)
     {
+        if (proto_names[i].proto == PROTO_NONE
+            || proto_names[i].proto == PROTO_AUTO)
+        {
+            continue;
+        }
         if (i)
         {
             buf_printf(&out, " ");
src/openvpn/socket.h +25 -0
index 7aeae527..fa55a4b6 100644
@@ -40,6 +40,11 @@
  */
 #define OPENVPN_PORT "1194"
 
+/*
+ * OpenVPN's default service name for DNS SRV discovery.
+ */
+#define OPENVPN_SERVICE "openvpn"
+
 /*
  * Number of seconds that "resolv-retry infinite"
  * represents.
@@ -71,6 +76,19 @@ struct openvpn_sockaddr
     } addr;
 };
 
+/* struct to hold resolved service targets */
+struct servinfo
+{
+    const char *hostname;
+    const char *servname;
+    int proto;
+    int order;
+    unsigned short prio;
+    unsigned short weight;
+    struct addrinfo *ai;
+    struct servinfo *next;
+};
+
 /* struct to hold preresolved host names */
 struct cached_dns_entry {
     const char *hostname;
@@ -78,6 +96,7 @@ struct cached_dns_entry {
     int ai_family;
     int flags;
     struct addrinfo *ai;
+    struct servinfo *si;
     struct cached_dns_entry *next;
 };
 
@@ -106,6 +125,9 @@ struct link_socket_addr
     struct addrinfo *remote_list; /* complete remote list */
     struct addrinfo *current_remote; /* remote used in the
                                       * current connection attempt */
+    struct servinfo *service_list; /* complete service list */
+    struct servinfo *current_service; /* service used in the
+                                       * current connection attempt */
     struct link_socket_actual actual; /* reply to this address */
 };
 
@@ -338,6 +360,8 @@ void link_socket_init_phase2(struct link_socket *sock,
 
 void do_preresolve(struct context *c);
 
+void do_resolve_service(struct context *c);
+
 void socket_adjust_frame_parameters(struct frame *frame, int proto);
 
 void frame_adjust_path_mtu(struct frame *frame, int pmtu, int proto);
@@ -486,6 +510,7 @@ socket_descriptor_t
 socket_do_accept(socket_descriptor_t sd,
 bool proto_is_net(int proto);
 
 bool proto_is_dgram(int proto);
+bool proto_is_stream(int proto);
 
 bool proto_is_udp(int proto);
@@ -532,8 +557,12 @@ bool unix_socket_get_peer_uid_gid(const

socket_descriptor_t sd, int *uid, int *g

 #define GETADDR_RANDOMIZE             (1<<9)
 #define GETADDR_PASSIVE               (1<<10)
 #define GETADDR_DATAGRAM              (1<<11)
src/openvpn/socket.h +3 -0
+#define GETADDR_STREAM                (1<<12)
+#define GETADDR_SERVICE               (1<<13)
 
+#define GETADDR_PROTO_MASK

(GETADDR_DATAGRAM|GETADDR_STREAM)
#define GETADDR_CACHE_MASK
(GETADDR_DATAGRAM|GETADDR_PASSIVE)
+#define GETADDR_CACHE_SERVICE_MASK
(GETADDR_PROTO_MASK|GETADDR_SERVICE)

/**
* Translate an IPv4 addr or hostname from string form to in_addr_t

src/openvpn/socket.h +25 -0
@@ -561,6 +590,30 @@ int openvpn_getaddrinfo(unsigned int flags,
                         int ai_family,
                         struct addrinfo **res);
 
+int openvpn_getservinfo(unsigned int flags,
+                        const char *hostname,
+                        const char *servname,
+                        int resolve_retry_seconds,
+                        volatile int *signal_received,
+                        int family,
+                        struct servinfo **res);
+
+void freeservinfo(struct servinfo *res);
+
+/* Inline functions */
+
+inline static void
+gc_freeaddrinfo_callback(void *addr)
+{
+    freeaddrinfo((struct addrinfo *) addr);
+}
+
+inline static void
+gc_freeservinfo_callback(void *addr)
+{
+    freeservinfo((struct servinfo *) addr);
+}
+
 /*
  * Transport protocol naming and other details.
  */
@@ -575,6 +628,7 @@ enum proto_num {
     PROTO_TCP,
     PROTO_TCP_SERVER,
     PROTO_TCP_CLIENT,
+    PROTO_AUTO,
     PROTO_N
 };
 
src/openvpn/syshead.h +5 -1
index 2ad5afc2..bec4a8a5 100644
@@ -38,6 +38,7 @@
 
 #ifdef _WIN32
 #include <windows.h>
+#include <windns.h>
 #include <winsock2.h>
 #include <tlhelp32.h>
 #define sleep(x) Sleep((x)*1000)
@@ -176,6 +177,10 @@
 #include <netinet/in.h>
 #endif
 
+#ifdef HAVE_ARPA_NAMESER_H
+#include <arpa/nameser.h>
+#endif
+
 #ifdef HAVE_RESOLV_H
 #include <resolv.h>
 #endif
--

2.17.1

_______________________________________________
Openvpn-devel mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/openvpn-devel

#17 lore raw

PATCH v11 1/1 Add DNS SRV remote host discovery support

In reply to Vladislav Grishenko

DNS SRV remote host discovery allows to have multiple OpenVPN servers for a single domain w/o explicit profile enumeration, to move services from host to host with little fuss, and to designate hosts as primary servers for a service and others as backups.
Feature has been asked several times already, should be useful in case of substantial number of clients & servers deployed.

Patch introduces "--remote-srv domain [service] [proto]" option. The "service" and "proto" arguments are optional. Client will try to resolve DNS SRV record "_service._proto.domain" and use returned DNS SRV records as remote server list ordered by server selection mechanism defined in RFC2782 (https://tools.ietf.org/html/rfc2782):

A client MUST attempt to contact the target host with the lowest-numbered priority field value it can reach, target hosts with the same priority SHOULD be tried in an order defined by the weight field.
The weight field specifies a relative weight for entries with the same priority. Larger weights SHOULD be given a proportionately higher probability of being selected.
Domain administrators SHOULD use Weight 0 when there isn't any server selection to do. In the presence of records containing weights greater than 0, records with Weight 0 SHOULD have a very small chance of being selected.

Note: OpenVPN server selection mechanism implementation indeed will give records with weight of zero a very small chance of being selected first, but never skip them.

Example: instead of multiple --remote in order, now it's possible to specify just one --remote-srv and configure DNS SRV records:

remote-srv example.net

name prio weight port target
$ORIGIN example.net.
_openvpn._udp IN SRV 10 60 1194 server1.example.net.
_openvpn._udp IN SRV 10 40 1194 server2.example.net.
_openvpn._udp IN SRV 10 0 1194 server3.example.net.
_openvpn._tcp IN SRV 20 0 443 server4.example.net.

For "--remote-srv example.net" following will happen in order:
1. The client will first try to resolve "_openvpn._udp.example.net" and "_openvpn._tcp.example.net".
2. Records "server1.example.net:1194", "server2.example.net:1194" and "server3.example.net:1194" will be selected before record "server4.example.net:443" as their priority 10 is smaller than 20.
3. Records "server1.example.net:1194", "server2.example.net:1194" and "server3.example.net:1194" will be randomly selected with weight probability: first will be either "server1.example.net:1194" with 60% probability or "server2.example.net:1194" with 40% or "server3.example.net:1194" with almost zero probability.
4. If "server1.example.net:1194" was selected, the second record will be either "server2.example.net:1194" with almost 100% probability or "server3.example.net:1194" with almost 0%.
5. If "server2.example.net:1194" was selected, the third record will be the only last record of priority 10 - "server3.example.net:1194".
6. Record "server4.example.net:443" will be the last one selected as the only record with priority 20.
7. Each of the resulting "target:port" remote hosts will be resolved and accessed if its protocol has no conflict with the rest of the OpenVPN options.

If DNS SRV name can't be resolved or no valid records were returned, client will move on to the next connection entry.

v11:
add get_cached_srv_entry() for servinfo vs addrinfo cache split add check for mixed --remote and --remote-srv
add doxygen dns srv functions comments
use query_servinfo() for both unix and windows
fix undefined NS_MAXMSG issue on macOS
fix undefined EAI_NODATA issue on FreeBSD
fix man
rebase against master

---
 configure.ac                        |   2 +-
 doc/man-sections/client-options.rst | 121 +++-
 doc/management-notes.txt            |   6 +
 src/openvpn/Makefile.am             |   2 +-
 src/openvpn/buffer.h                |   5 -
 src/openvpn/errlevel.h              |   1 +
 src/openvpn/init.c                  |  79 ++-
 src/openvpn/openvpn.vcxproj         |   8 +-
 src/openvpn/options.c               | 281 +++++++--
 src/openvpn/options.h               |   4 +
 src/openvpn/socket.c                | 875 +++++++++++++++++++++++++++-
 src/openvpn/socket.h                |  54 ++
 src/openvpn/syshead.h               |   5 +
 13 files changed, 1371 insertions(+), 72 deletions(-)
configure.ac +1 -1
index 8e31dcb2..dcb0db0d 100644
@@ -474,7 +474,7 @@ SOCKET_INCLUDES="
 "
 
 AC_CHECK_HEADERS(
-	[net/if.h netinet/ip.h resolv.h sys/un.h net/if_utun.h sys/kern_control.h],
+	[net/if.h netinet/ip.h arpa/nameser.h resolv.h sys/un.h net/if_utun.h sys/kern_control.h],
 	,
 	,
 	[[${SOCKET_INCLUDES}]]
doc/man-sections/client-options.rst +116 -5

134 lines not on this page · raw message

doc/management-notes.txt +6 -0
index 3aff6eb6..3b84da10 100644
@@ -882,6 +882,12 @@ the above notification, use this command:
 
   remote MOD vpn.otherexample.com 1234
 
+DNS SRV discovery domain and service name with protocol code:`auto`
+can't be overriden, but either accepted or skipped only.
+Example of such notification:
+
+  >REMOTE:example.com,openvpn,auto
+
 To accept the same host and port as the client would ordinarily
 have connected to, use this command:
 
src/openvpn/Makefile.am +1 -1
index ec84929b..3454a98b 100644
@@ -144,5 +144,5 @@ openvpn_LDADD = \
 	$(OPTIONAL_INOTIFY_LIBS)
 if WIN32
 openvpn_SOURCES += openvpn_win32_resources.rc block_dns.c block_dns.h ring_buffer.h
-openvpn_LDADD += -lgdi32 -lws2_32 -lwininet -lcrypt32 -liphlpapi -lwinmm -lfwpuclnt -lrpcrt4 -lncrypt -lsetupapi
+openvpn_LDADD += -lgdi32 -lws2_32 -lwininet -lcrypt32 -liphlpapi -lwinmm -lfwpuclnt -lrpcrt4 -lncrypt -lsetupapi -ldnsapi
 endif
src/openvpn/buffer.h +0 -5
index 9ea70284..68192a5e 100644
@@ -198,11 +198,6 @@ bool buf_init_debug(struct buffer *buf, int offset, const char *file, int line);
 
 
 /* inline functions */
-inline static void
-gc_freeaddrinfo_callback(void *addr)
-{
-    freeaddrinfo((struct addrinfo *) addr);
-}
 
 /** Return an empty struct buffer */
 static inline struct buffer
src/openvpn/errlevel.h +1 -0
index 5663f841..39f96e7d 100644
@@ -92,6 +92,7 @@
 #define D_PS_PROXY           LOGLEV(3, 44, 0)        /* messages related to --port-share option */
 #define D_PF_INFO            LOGLEV(3, 45, 0)        /* packet filter informational messages */
 #define D_IFCONFIG           LOGLEV(3, 0,  0)        /* show ifconfig info (don't mute) */
+#define D_RESOLVE            LOGLEV(3, 46, 0)        /* show hostname resolve info */
 
 #define D_SHOW_PARMS         LOGLEV(4, 50, 0)        /* show all parameters on program initiation */
 #define D_SHOW_OCC           LOGLEV(4, 51, 0)        /* show options compatibility string */
src/openvpn/init.c +72 -7

139 lines not on this page · raw message

src/openvpn/openvpn.vcxproj +4 -4
index cf31940c..a6396793 100644
@@ -92,7 +92,7 @@
     </ClCompile>
     <ResourceCompile />
     <Link>
-      <AdditionalDependencies>legacy_stdio_definitions.lib;Ncrypt.lib;libssl.lib;libcrypto.lib;lzo2.lib;pkcs11-helper.dll.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;%(AdditionalDependencies)</AdditionalDependencies>
+      <AdditionalDependencies>legacy_stdio_definitions.lib;Ncrypt.lib;libssl.lib;libcrypto.lib;lzo2.lib;pkcs11-helper.dll.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;dnsapi.lib;%(AdditionalDependencies)</AdditionalDependencies>
       <AdditionalLibraryDirectories>$(OPENSSL_HOME)/lib;$(LZO_HOME)/lib;$(PKCS11H_HOME)/lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
       <SubSystem>Console</SubSystem>
     </Link>
@@ -107,7 +107,7 @@
     </ClCompile>
     <ResourceCompile />
     <Link>
-      <AdditionalDependencies>legacy_stdio_definitions.lib;Ncrypt.lib;libssl.lib;libcrypto.lib;lzo2.lib;pkcs11-helper.dll.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;%(AdditionalDependencies)</AdditionalDependencies>
+      <AdditionalDependencies>legacy_stdio_definitions.lib;Ncrypt.lib;libssl.lib;libcrypto.lib;lzo2.lib;pkcs11-helper.dll.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;dnsapi.lib;%(AdditionalDependencies)</AdditionalDependencies>
       <AdditionalLibraryDirectories>$(OPENSSL_HOME)/lib;$(LZO_HOME)/lib;$(PKCS11H_HOME)/lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
       <SubSystem>Console</SubSystem>
     </Link>
@@ -122,7 +122,7 @@
     </ClCompile>
     <ResourceCompile />
     <Link>
-      <AdditionalDependencies>legacy_stdio_definitions.lib;Ncrypt.lib;libssl.lib;libcrypto.lib;lzo2.lib;pkcs11-helper.dll.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;%(AdditionalDependencies)</AdditionalDependencies>
+      <AdditionalDependencies>legacy_stdio_definitions.lib;Ncrypt.lib;libssl.lib;libcrypto.lib;lzo2.lib;pkcs11-helper.dll.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;dnsapi.lib;%(AdditionalDependencies)</AdditionalDependencies>
       <AdditionalLibraryDirectories>$(OPENSSL_HOME)/lib;$(LZO_HOME)/lib;$(PKCS11H_HOME)/lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
       <SubSystem>Console</SubSystem>
     </Link>
@@ -137,7 +137,7 @@
     </ClCompile>
     <ResourceCompile />
     <Link>
-      <AdditionalDependencies>legacy_stdio_definitions.lib;Ncrypt.lib;libssl.lib;libcrypto.lib;lzo2.lib;pkcs11-helper.dll.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;%(AdditionalDependencies)</AdditionalDependencies>
+      <AdditionalDependencies>legacy_stdio_definitions.lib;Ncrypt.lib;libssl.lib;libcrypto.lib;lzo2.lib;pkcs11-helper.dll.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;dnsapi.lib;%(AdditionalDependencies)</AdditionalDependencies>
       <AdditionalLibraryDirectories>$(OPENSSL_HOME)/lib;$(LZO_HOME)/lib;$(PKCS11H_HOME)/lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
       <SubSystem>Console</SubSystem>
     </Link>
src/openvpn/options.c +236 -45

388 lines not on this page · raw message

src/openvpn/options.h +4 -0
index f3208c71..aacc61c0 100644
@@ -100,6 +100,7 @@ struct connection_entry
     const char *remote_port;
     const char *local;
     const char *remote;
+    bool remote_srv;
     bool remote_float;
     bool bind_defined;
     bool bind_ipv6_only;
@@ -160,6 +161,7 @@ struct remote_entry
     const char *remote_port;
     int proto;
     sa_family_t af;
+    bool remote_srv;
 };
 
 #define CONNECTION_LIST_SIZE 64
@@ -805,6 +807,8 @@ char *options_string_extract_option(const char *options_string,
 
 void options_postprocess(struct options *options);
 
+bool options_mutate_ce_servinfo(struct options *o, struct servinfo *si);
+
 void pre_pull_save(struct options *o);
 
 void pre_pull_restore(struct options *o, struct gc_arena *gc);
src/openvpn/socket.c +871 -4

947 lines not on this page · raw message

src/openvpn/socket.h +54 -0

110 lines not on this page · raw message

src/openvpn/syshead.h +5 -0
index cf971459..35703350 100644
@@ -38,6 +38,7 @@
 
 #ifdef _WIN32
 #include <windows.h>
+#include <windns.h>
 #include <winsock2.h>
 #include <tlhelp32.h>
 #define sleep(x) Sleep((x)*1000)
@@ -176,6 +177,10 @@
 #include <netinet/in.h>
 #endif
 
+#ifdef HAVE_ARPA_NAMESER_H
+#include <arpa/nameser.h>
+#endif
+
 #ifdef HAVE_RESOLV_H
 #include <resolv.h>
 #endif
Signature · 1 line
2.17.1
#18 lore raw

Hi,

As discussed, rebased against git master with one change vs v10 - dead inetd code removal.
Tested on Windows 10 and Linux, FreeBSD should be fine as well since previous v10.

We talked about the OpenVPN usage experience at NextHop 2020 conference last fall and got interested external feedback regarding the SRV feature. Would be great, if you could kindly suggest when re-review/merge can be scheduled if no issue found.

--
Best Regards, Vladislav Grishenko

#19 lore raw

PATCH v12 1/1 Add DNS SRV remote host discovery support

DNS SRV remote host discovery allows to have multiple OpenVPN servers for a single domain w/o explicit profile enumeration, to move services from host to host with little fuss, and to designate hosts as primary servers for a service and others as backups.
Feature has been asked several times already, should be useful in case of substantial number of clients & servers deployed.

Patch introduces "--remote-srv domain [service] [proto]" option. The "service" and "proto" arguments are optional. Client will try to resolve DNS SRV record "_service._proto.domain" and use returned DNS SRV records as remote server list ordered by server selection mechanism defined in RFC2782 (https://tools.ietf.org/html/rfc2782):

A client MUST attempt to contact the target host with the lowest-numbered priority field value it can reach, target hosts with the same priority SHOULD be tried in an order defined by the weight field.
The weight field specifies a relative weight for entries with the same priority. Larger weights SHOULD be given a proportionately higher probability of being selected.
Domain administrators SHOULD use Weight 0 when there isn't any server selection to do. In the presence of records containing weights greater than 0, records with Weight 0 SHOULD have a very small chance of being selected.

Note: OpenVPN server selection mechanism implementation indeed will give records with weight of zero a very small chance of being selected first, but never skip them.

Example: instead of multiple --remote in order, now it's possible to specify just one --remote-srv and configure DNS SRV records:

remote-srv example.net

name prio weight port target
$ORIGIN example.net.
_openvpn._udp IN SRV 10 60 1194 server1.example.net.
_openvpn._udp IN SRV 10 40 1194 server2.example.net.
_openvpn._udp IN SRV 10 0 1194 server3.example.net.
_openvpn._tcp IN SRV 20 0 443 server4.example.net.

For "--remote-srv example.net" following will happen in order:
1. The client will first try to resolve "_openvpn._udp.example.net" and "_openvpn._tcp.example.net".
2. Records "server1.example.net:1194", "server2.example.net:1194" and "server3.example.net:1194" will be selected before record "server4.example.net:443" as their priority 10 is smaller than 20.
3. Records "server1.example.net:1194", "server2.example.net:1194" and "server3.example.net:1194" will be randomly selected with weight probability: first will be either "server1.example.net:1194" with 60% probability or "server2.example.net:1194" with 40% or "server3.example.net:1194" with almost zero probability.
4. If "server1.example.net:1194" was selected, the second record will be either "server2.example.net:1194" with almost 100% probability or "server3.example.net:1194" with almost 0%.
5. If "server2.example.net:1194" was selected, the third record will be the only last record of priority 10 - "server3.example.net:1194".
6. Record "server4.example.net:443" will be the last one selected as the only record with priority 20.
7. Each of the resulting "target:port" remote hosts will be resolved and accessed if its protocol has no conflict with the rest of the OpenVPN options.

If DNS SRV name can't be resolved or no valid records were returned, client will move on to the next connection entry.

v12:
add get_cached_srv_entry() for servinfo vs addrinfo cache split add check for mixed --remote and --remote-srv
add doxygen dns srv functions comments
use query_servinfo() for both unix and windows
fix undefined NS_MAXMSG issue on macOS
fix undefined EAI_NODATA issue on FreeBSD
fix man and msg() indents
rebase against master

---
 configure.ac                        |   2 +-
 doc/man-sections/client-options.rst | 121 +++-
 doc/management-notes.txt            |   6 +
 src/openvpn/Makefile.am             |   2 +-
 src/openvpn/buffer.h                |   5 -
 src/openvpn/errlevel.h              |   1 +
 src/openvpn/init.c                  |  79 ++-
 src/openvpn/openvpn.vcxproj         |   8 +-
 src/openvpn/options.c               | 281 +++++++--
 src/openvpn/options.h               |   4 +
 src/openvpn/socket.c                | 867 +++++++++++++++++++++++++++-
 src/openvpn/socket.h                |  65 ++-
 src/openvpn/syshead.h               |   5 +
 13 files changed, 1368 insertions(+), 78 deletions(-)
configure.ac +1 -1
index f05faf99..da5e1723 100644
@@ -455,7 +455,7 @@ SOCKET_INCLUDES="
 "
 
 AC_CHECK_HEADERS(
-	[net/if.h netinet/ip.h resolv.h sys/un.h net/if_utun.h sys/kern_control.h],
+	[net/if.h netinet/ip.h arpa/nameser.h resolv.h sys/un.h net/if_utun.h sys/kern_control.h],
 	,
 	,
 	[[${SOCKET_INCLUDES}]]
doc/man-sections/client-options.rst +116 -5

134 lines not on this page · raw message

doc/management-notes.txt +6 -0
index 3aff6eb6..3b84da10 100644
@@ -882,6 +882,12 @@ the above notification, use this command:
 
   remote MOD vpn.otherexample.com 1234
 
+DNS SRV discovery domain and service name with protocol code:`auto`
+can't be overriden, but either accepted or skipped only.
+Example of such notification:
+
+  >REMOTE:example.com,openvpn,auto
+
 To accept the same host and port as the client would ordinarily
 have connected to, use this command:
 
src/openvpn/Makefile.am +1 -1
index ec84929b..3454a98b 100644
@@ -144,5 +144,5 @@ openvpn_LDADD = \
 	$(OPTIONAL_INOTIFY_LIBS)
 if WIN32
 openvpn_SOURCES += openvpn_win32_resources.rc block_dns.c block_dns.h ring_buffer.h
-openvpn_LDADD += -lgdi32 -lws2_32 -lwininet -lcrypt32 -liphlpapi -lwinmm -lfwpuclnt -lrpcrt4 -lncrypt -lsetupapi
+openvpn_LDADD += -lgdi32 -lws2_32 -lwininet -lcrypt32 -liphlpapi -lwinmm -lfwpuclnt -lrpcrt4 -lncrypt -lsetupapi -ldnsapi
 endif
src/openvpn/buffer.h +0 -5
index 9ea70284..68192a5e 100644
@@ -198,11 +198,6 @@ bool buf_init_debug(struct buffer *buf, int offset, const char *file, int line);
 
 
 /* inline functions */
-inline static void
-gc_freeaddrinfo_callback(void *addr)
-{
-    freeaddrinfo((struct addrinfo *) addr);
-}
 
 /** Return an empty struct buffer */
 static inline struct buffer
src/openvpn/errlevel.h +1 -0
index 5663f841..39f96e7d 100644
@@ -92,6 +92,7 @@
 #define D_PS_PROXY           LOGLEV(3, 44, 0)        /* messages related to --port-share option */
 #define D_PF_INFO            LOGLEV(3, 45, 0)        /* packet filter informational messages */
 #define D_IFCONFIG           LOGLEV(3, 0,  0)        /* show ifconfig info (don't mute) */
+#define D_RESOLVE            LOGLEV(3, 46, 0)        /* show hostname resolve info */
 
 #define D_SHOW_PARMS         LOGLEV(4, 50, 0)        /* show all parameters on program initiation */
 #define D_SHOW_OCC           LOGLEV(4, 51, 0)        /* show options compatibility string */
src/openvpn/init.c +72 -7

139 lines not on this page · raw message

src/openvpn/openvpn.vcxproj +4 -4
index cf31940c..a6396793 100644
@@ -92,7 +92,7 @@
     </ClCompile>
     <ResourceCompile />
     <Link>
-      <AdditionalDependencies>legacy_stdio_definitions.lib;Ncrypt.lib;libssl.lib;libcrypto.lib;lzo2.lib;pkcs11-helper.dll.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;%(AdditionalDependencies)</AdditionalDependencies>
+      <AdditionalDependencies>legacy_stdio_definitions.lib;Ncrypt.lib;libssl.lib;libcrypto.lib;lzo2.lib;pkcs11-helper.dll.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;dnsapi.lib;%(AdditionalDependencies)</AdditionalDependencies>
       <AdditionalLibraryDirectories>$(OPENSSL_HOME)/lib;$(LZO_HOME)/lib;$(PKCS11H_HOME)/lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
       <SubSystem>Console</SubSystem>
     </Link>
@@ -107,7 +107,7 @@
     </ClCompile>
     <ResourceCompile />
     <Link>
-      <AdditionalDependencies>legacy_stdio_definitions.lib;Ncrypt.lib;libssl.lib;libcrypto.lib;lzo2.lib;pkcs11-helper.dll.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;%(AdditionalDependencies)</AdditionalDependencies>
+      <AdditionalDependencies>legacy_stdio_definitions.lib;Ncrypt.lib;libssl.lib;libcrypto.lib;lzo2.lib;pkcs11-helper.dll.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;dnsapi.lib;%(AdditionalDependencies)</AdditionalDependencies>
       <AdditionalLibraryDirectories>$(OPENSSL_HOME)/lib;$(LZO_HOME)/lib;$(PKCS11H_HOME)/lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
       <SubSystem>Console</SubSystem>
     </Link>
@@ -122,7 +122,7 @@
     </ClCompile>
     <ResourceCompile />
     <Link>
-      <AdditionalDependencies>legacy_stdio_definitions.lib;Ncrypt.lib;libssl.lib;libcrypto.lib;lzo2.lib;pkcs11-helper.dll.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;%(AdditionalDependencies)</AdditionalDependencies>
+      <AdditionalDependencies>legacy_stdio_definitions.lib;Ncrypt.lib;libssl.lib;libcrypto.lib;lzo2.lib;pkcs11-helper.dll.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;dnsapi.lib;%(AdditionalDependencies)</AdditionalDependencies>
       <AdditionalLibraryDirectories>$(OPENSSL_HOME)/lib;$(LZO_HOME)/lib;$(PKCS11H_HOME)/lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
       <SubSystem>Console</SubSystem>
     </Link>
@@ -137,7 +137,7 @@
     </ClCompile>
     <ResourceCompile />
     <Link>
-      <AdditionalDependencies>legacy_stdio_definitions.lib;Ncrypt.lib;libssl.lib;libcrypto.lib;lzo2.lib;pkcs11-helper.dll.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;%(AdditionalDependencies)</AdditionalDependencies>
+      <AdditionalDependencies>legacy_stdio_definitions.lib;Ncrypt.lib;libssl.lib;libcrypto.lib;lzo2.lib;pkcs11-helper.dll.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;dnsapi.lib;%(AdditionalDependencies)</AdditionalDependencies>
       <AdditionalLibraryDirectories>$(OPENSSL_HOME)/lib;$(LZO_HOME)/lib;$(PKCS11H_HOME)/lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
       <SubSystem>Console</SubSystem>
     </Link>
src/openvpn/options.c +230 -51

397 lines not on this page · raw message

src/openvpn/options.h +4 -0
index 41e84f7e..fbf21d10 100644
@@ -102,6 +102,7 @@ struct connection_entry
     const char *remote_port;
     const char *local;
     const char *remote;
+    bool remote_srv;
     bool remote_float;
     bool bind_defined;
     bool bind_ipv6_only;
@@ -162,6 +163,7 @@ struct remote_entry
     const char *remote_port;
     int proto;
     sa_family_t af;
+    bool remote_srv;
 };
 
 #define CONNECTION_LIST_SIZE 64
@@ -792,6 +794,8 @@ char *options_string_extract_option(const char *options_string,
 
 void options_postprocess(struct options *options);
 
+bool options_mutate_ce_servinfo(struct options *o, struct servinfo *si);
+
 void pre_connect_save(struct options *o);
 
 void pre_connect_restore(struct options *o, struct gc_arena *gc);
src/openvpn/socket.c +864 -3

927 lines not on this page · raw message

src/openvpn/socket.h +64 -1

127 lines not on this page · raw message

src/openvpn/syshead.h +5 -0
index a9680f72..e3794c97 100644
@@ -38,6 +38,7 @@
 
 #ifdef _WIN32
 #include <windows.h>
+#include <windns.h>
 #include <winsock2.h>
 #include <tlhelp32.h>
 #define sleep(x) Sleep((x)*1000)
@@ -143,6 +144,10 @@
 #include <netinet/in.h>
 #endif
 
+#ifdef HAVE_ARPA_NAMESER_H
+#include <arpa/nameser.h>
+#endif
+
 #ifdef HAVE_RESOLV_H
 #include <resolv.h>
 #endif
Signature · 1 line
2.17.1
#20 lore raw

Hi,

Quoted 6 lines · Vladislav Grishenko

DNS SRV remote host discovery allows to have multiple OpenVPN servers for a single domain w/o explicit profile enumeration, to move services from host to host with little fuss, and to designate hosts as primary servers for a service and others as backups.
Feature has been asked several times already, should be useful in case of substantial number of clients & servers deployed.

[..]

Quoted 9 lines

v12:
add get_cached_srv_entry() for servinfo vs addrinfo cache split add check for mixed --remote and --remote-srv
add doxygen dns srv functions comments
use query_servinfo() for both unix and windows
fix undefined NS_MAXMSG issue on macOS
fix undefined EAI_NODATA issue on FreeBSD
fix man and msg() indents
rebase against master

It has taken us way too long to properly look into this patch, and with 2.6_alpha looming, it's "now or 2.7".

As expected, this no longer applies due to conflicts all over the place - this is easily fixed, and I've done so (and will send a v13 based on current master in the next mail).

There are other changes related to intermediate commits, like the removal of "--explicit-exit-notify & TCP is not allowed" check, also adjusted, extra projects in openvpn.vcproj, etc. - I think I have covered all of them.

The crucial issue right now is that the whole resolver stuff does not build on OpenBSD, because there is no ns_initparse() and friends - but there *is* an getrrsetbyname(), which seems to do the same thing, except "not available on Linux". There are various posts online that describe the problem, and the possible solution space - like this one

https://fossil-users.fossil-scm.narkive.com/wEIH279H/smtp-c-build-failures

so you could basically do

- add private ns_initparse() function, as they do in "vlmcsd" (whatever that is) - https://github.com/sunflyer/vlmcsd/blob/master/dns_srv.c

- use getrrsetbyname(), and add that via "compat" source if a target platform does not have it - this is what OpenSSH does

- add #ifdefs to disable --srv functionality on OpenBSD (which is not really where we want to go)

- require libbind on OpenBSD, and ensure includes & libraries are handled in the proper order (<arpa/nameser.h> etc. needs to be pulled from /usr/local/include/bind/ etc.)
(this is also not really what we want, adding extra prerequisites)

Unfortunately, without someone actually doing this work, this patch can not be applied - it will break a fully supported platform.

I'm sorry that it took me over a year to get to the "fix this or it can't go in" point - I thought that this was all sorted out already in the EAI_NODATA round, and all I had to do was "come up with some test scenario and then merge".

gert

Signature · 6 lines
"If was one thing all people took for granted, was conviction that if you 
 feed honest figures into a computer, honest figures come out. Never doubted 
 it myself till I met a computer with a sense of humor."
                             Robert A. Heinlein, The Moon is a Harsh Mistress

Gert Doering - Munich, Germany                             [email protected]...
#21 lore raw

PATCH v13 1/1 Add DNS SRV remote host discovery support

From: Vladislav Grishenko <[email protected]...>

DNS SRV remote host discovery allows to have multiple OpenVPN servers for a single domain w/o explicit profile enumeration, to move services from host to host with little fuss, and to designate hosts as primary servers for a service and others as backups.
Feature has been asked several times already, should be useful in case of substantial number of clients & servers deployed.

Patch introduces "--remote-srv domain [service] [proto]" option. The "service" and "proto" arguments are optional. Client will try to resolve DNS SRV record "_service._proto.domain" and use returned DNS SRV records as remote server list ordered by server selection mechanism defined in RFC2782 (https://tools.ietf.org/html/rfc2782):

A client MUST attempt to contact the target host with the lowest-numbered priority field value it can reach, target hosts with the same priority SHOULD be tried in an order defined by the weight field.
The weight field specifies a relative weight for entries with the same priority. Larger weights SHOULD be given a proportionately higher probability of being selected.
Domain administrators SHOULD use Weight 0 when there isn't any server selection to do. In the presence of records containing weights greater than 0, records with Weight 0 SHOULD have a very small chance of being selected.

Note: OpenVPN server selection mechanism implementation indeed will give records with weight of zero a very small chance of being selected first, but never skip them.

Example: instead of multiple --remote in order, now it's possible to specify just one --remote-srv and configure DNS SRV records:

remote-srv example.net

name prio weight port target
$ORIGIN example.net.
_openvpn._udp IN SRV 10 60 1194 server1.example.net.
_openvpn._udp IN SRV 10 40 1194 server2.example.net.
_openvpn._udp IN SRV 10 0 1194 server3.example.net.
_openvpn._tcp IN SRV 20 0 443 server4.example.net.

For "--remote-srv example.net" following will happen in order:
1. The client will first try to resolve "_openvpn._udp.example.net" and "_openvpn._tcp.example.net".
2. Records "server1.example.net:1194", "server2.example.net:1194" and "server3.example.net:1194" will be selected before record "server4.example.net:443" as their priority 10 is smaller than 20.
3. Records "server1.example.net:1194", "server2.example.net:1194" and "server3.example.net:1194" will be randomly selected with weight probability: first will be either "server1.example.net:1194" with 60% probability or "server2.example.net:1194" with 40% or "server3.example.net:1194" with almost zero probability.
4. If "server1.example.net:1194" was selected, the second record will be either "server2.example.net:1194" with almost 100% probability or "server3.example.net:1194" with almost 0%.
5. If "server2.example.net:1194" was selected, the third record will be the only last record of priority 10 - "server3.example.net:1194".
6. Record "server4.example.net:443" will be the last one selected as the only record with priority 20.
7. Each of the resulting "target:port" remote hosts will be resolved and accessed if its protocol has no conflict with the rest of the OpenVPN options.

If DNS SRV name can't be resolved or no valid records were returned, client will move on to the next connection entry.

v13:
rebase to master (Nov 2022)
apply "'static inline', not 'inline static' style guide" include --explicit-exit-notify logic from commit 7953b07bf56c1df0 formatting changes required by uncrustify
replace last occurance of EAI_NODATA with EAI_NONAME OpenBSD does not have ns_c_in/ns_t_srv, need to use C_IN/T_SRV instead

v12:
add get_cached_srv_entry() for servinfo vs addrinfo cache split add check for mixed --remote and --remote-srv
add doxygen dns srv functions comments
use query_servinfo() for both unix and windows
fix undefined NS_MAXMSG issue on macOS
fix undefined EAI_NODATA issue on FreeBSD
fix man and msg() indents
rebase against master

---
 configure.ac                        |   2 +-
 doc/man-sections/client-options.rst | 121 +++-
 doc/management-notes.txt            |   6 +
 src/openvpn/Makefile.am             |   2 +-
 src/openvpn/buffer.h                |   5 -
 src/openvpn/errlevel.h              |   1 +
 src/openvpn/init.c                  |  79 ++-
 src/openvpn/openvpn.vcxproj         |  15 +-
 src/openvpn/options.c               | 256 ++++++--
 src/openvpn/options.h               |   4 +
 src/openvpn/socket.c                | 874 +++++++++++++++++++++++++++-
 src/openvpn/socket.h                |  65 ++-
 src/openvpn/syshead.h               |   5 +
 13 files changed, 1372 insertions(+), 63 deletions(-)
configure.ac +1 -1
index be31889e..27bd2eae 100644
@@ -468,7 +468,7 @@ SOCKET_INCLUDES="
 "
 
 AC_CHECK_HEADERS(
-	[net/if.h netinet/ip.h resolv.h sys/un.h net/if_utun.h sys/kern_control.h],
+	[net/if.h netinet/ip.h arpa/nameser.h resolv.h sys/un.h net/if_utun.h sys/kern_control.h],
 	,
 	,
 	[[${SOCKET_INCLUDES}]]
doc/man-sections/client-options.rst +116 -5

134 lines not on this page · raw message

doc/management-notes.txt +6 -0
index 7bb10c24..f4095cee 100644
@@ -807,6 +807,12 @@ the above notification, use this command:
 
   remote MOD vpn.otherexample.com 1234
 
+DNS SRV discovery domain and service name with protocol code:`auto`
+can't be overriden, but either accepted or skipped only.
+Example of such notification:
+
+  >REMOTE:example.com,openvpn,auto
+
 To accept the same host and port as the client would ordinarily
 have connected to, use this command:
 
src/openvpn/Makefile.am +1 -1
index e80a35ab..faf8fea0 100644
@@ -155,5 +155,5 @@ openvpn_LDADD = \
 	$(OPTIONAL_INOTIFY_LIBS)
 if WIN32
 openvpn_SOURCES += openvpn_win32_resources.rc block_dns.c block_dns.h ring_buffer.h
-openvpn_LDADD += -lgdi32 -lws2_32 -lwininet -lcrypt32 -liphlpapi -lwinmm -lfwpuclnt -lrpcrt4 -lncrypt -lsetupapi -lbcrypt
+openvpn_LDADD += -lgdi32 -lws2_32 -lwininet -lcrypt32 -liphlpapi -lwinmm -lfwpuclnt -lrpcrt4 -lncrypt -lsetupapi -lbcrypt -ldnsapi
 endif
src/openvpn/buffer.h +0 -5
index fece6336..0a96e3b5 100644
@@ -198,11 +198,6 @@ bool buf_init_debug(struct buffer *buf, int offset, const char *file, int line);
 
 
 /* inline functions */
-static inline void
-gc_freeaddrinfo_callback(void *addr)
-{
-    freeaddrinfo((struct addrinfo *) addr);
-}
 
 /** Return an empty struct buffer */
 static inline struct buffer
src/openvpn/errlevel.h +1 -0
index 5bb1e65e..3b8a7c30 100644
@@ -90,6 +90,7 @@
 #define D_ROUTE_QUOTA        LOGLEV(3, 42, 0)        /* show route quota exceeded messages */
 #define D_OSBUF              LOGLEV(3, 43, 0)        /* show socket/tun/tap buffer sizes */
 #define D_PS_PROXY           LOGLEV(3, 44, 0)        /* messages related to --port-share option */
+#define D_RESOLVE            LOGLEV(3, 46, 0)        /* show hostname resolve info */
 #define D_IFCONFIG           LOGLEV(3, 0,  0)        /* show ifconfig info (don't mute) */
 #define D_DCO                LOGLEV(3, 0, 0)         /* show DCO related messages */
 
src/openvpn/init.c +72 -7

139 lines not on this page · raw message

src/openvpn/openvpn.vcxproj +8 -7
index 9b5e416f..43e4dcd6 100644
@@ -166,7 +166,7 @@
     </ClCompile>
     <ResourceCompile />
     <Link>
-      <AdditionalDependencies>Ncrypt.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;Advapi32.lib</AdditionalDependencies>
+      <AdditionalDependencies>Ncrypt.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;dnsapi.lib;Advapi32.lib</AdditionalDependencies>
       <AdditionalLibraryDirectories>$(OPENSSL_HOME)/lib;$(LZO_HOME)/lib;$(PKCS11H_HOME)/lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
       <SubSystem>Console</SubSystem>
     </Link>
@@ -183,7 +183,7 @@
     </ClCompile>
     <ResourceCompile />
     <Link>
-      <AdditionalDependencies>Ncrypt.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;Advapi32.lib</AdditionalDependencies>
+      <AdditionalDependencies>Ncrypt.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;dnsapi.lib;Advapi32.lib</AdditionalDependencies>
       <AdditionalLibraryDirectories>$(OPENSSL_HOME)/lib;$(LZO_HOME)/lib;$(PKCS11H_HOME)/lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
       <SubSystem>Console</SubSystem>
     </Link>
@@ -200,7 +200,7 @@
     </ClCompile>
     <ResourceCompile />
     <Link>
-      <AdditionalDependencies>Ncrypt.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;Advapi32.lib</AdditionalDependencies>
+      <AdditionalDependencies>Ncrypt.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;dnsapi.lib;Advapi32.lib</AdditionalDependencies>
       <AdditionalLibraryDirectories>$(OPENSSL_HOME)/lib;$(LZO_HOME)/lib;$(PKCS11H_HOME)/lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
       <SubSystem>Console</SubSystem>
     </Link>
@@ -218,7 +218,8 @@
     </ClCompile>
     <ResourceCompile />
     <Link>
-      <AdditionalDependencies>Ncrypt.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;Advapi32.lib</AdditionalDependencies>
+      <AdditionalDependencies>Ncrypt.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;dnsapi.lib;Advapi32.lib</AdditionalDependencies>
+      <AdditionalDependencies>legacy_stdio_definitions.lib;Ncrypt.lib;libssl.lib;libcrypto.lib;lzo2.lib;pkcs11-helper.dll.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;dnsapi.lib;%(AdditionalDependencies)</AdditionalDependencies>
       <AdditionalLibraryDirectories>$(OPENSSL_HOME)/lib;$(LZO_HOME)/lib;$(PKCS11H_HOME)/lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
       <SubSystem>Console</SubSystem>
       <CETCompat>true</CETCompat>
@@ -237,7 +238,7 @@
     </ClCompile>
     <ResourceCompile />
     <Link>
-      <AdditionalDependencies>Ncrypt.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;Advapi32.lib</AdditionalDependencies>
+      <AdditionalDependencies>Ncrypt.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;dnsapi.lib;Advapi32.lib</AdditionalDependencies>
       <AdditionalLibraryDirectories>$(OPENSSL_HOME)/lib;$(LZO_HOME)/lib;$(PKCS11H_HOME)/lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
       <SubSystem>Console</SubSystem>
       <CETCompat>true</CETCompat>
@@ -256,7 +257,7 @@
     </ClCompile>
     <ResourceCompile />
     <Link>
-      <AdditionalDependencies>Ncrypt.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;Advapi32.lib</AdditionalDependencies>
+      <AdditionalDependencies>Ncrypt.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;dnsapi.lib;Advapi32.lib</AdditionalDependencies>
       <AdditionalLibraryDirectories>$(OPENSSL_HOME)/lib;$(LZO_HOME)/lib;$(PKCS11H_HOME)/lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
       <SubSystem>Console</SubSystem>
     </Link>
@@ -465,4 +466,4 @@
   <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
   <ImportGroup Label="ExtensionTargets">
   </ImportGroup>
-</Project>
\ No newline at end of file
+</Project>
src/openvpn/options.c +223 -33

363 lines not on this page · raw message

src/openvpn/options.h +4 -0
index 68ad0cac..6f79eb07 100644
@@ -105,6 +105,7 @@ struct connection_entry
     const char *remote_port;
     const char *local;
     const char *remote;
+    bool remote_srv;
     bool remote_float;
     bool bind_defined;
     bool bind_ipv6_only;
@@ -177,6 +178,7 @@ struct remote_entry
     const char *remote_port;
     int proto;
     sa_family_t af;
+    bool remote_srv;
 };
 
 #define CONNECTION_LIST_SIZE 64
@@ -832,6 +834,8 @@ void options_postprocess(struct options *options, struct env_set *es);
 
 bool options_postprocess_pull(struct options *o, struct env_set *es);
 
+bool options_mutate_ce_servinfo(struct options *o, struct servinfo *si);
+
 void pre_connect_restore(struct options *o, struct gc_arena *gc);
 
 bool apply_push_options(struct options *options,
src/openvpn/socket.c +871 -3

934 lines not on this page · raw message

src/openvpn/socket.h +64 -1

127 lines not on this page · raw message

src/openvpn/syshead.h +5 -0
index 5a673a7b..484c4474 100644
@@ -38,6 +38,7 @@
 
 #ifdef _WIN32
 #include <windows.h>
+#include <windns.h>
 #include <winsock2.h>
 #include <tlhelp32.h>
 #define sleep(x) Sleep((x)*1000)
@@ -143,6 +144,10 @@
 #include <netinet/in.h>
 #endif
 
+#ifdef HAVE_ARPA_NAMESER_H
+#include <arpa/nameser.h>
+#endif
+
 #ifdef HAVE_RESOLV_H
 #include <resolv.h>
 #endif
Signature · 1 line
2.35.1
#22 lore raw

PATCH v14 1/1 Add DNS SRV remote host discovery support

From: Vladislav Grishenko <[email protected]...>

DNS SRV remote host discovery allows to have multiple OpenVPN servers for a single domain w/o explicit profile enumeration, to move services from host to host with little fuss, and to designate hosts as primary servers for a service and others as backups.
Feature has been asked several times already, should be useful in case of substantial number of clients & servers deployed.

Patch introduces "--remote-srv domain [service] [proto]" option. The "service" and "proto" arguments are optional. Client will try to resolve DNS SRV record "_service._proto.domain" and use returned DNS SRV records as remote server list ordered by server selection mechanism defined in RFC2782 (https://tools.ietf.org/html/rfc2782):

A client MUST attempt to contact the target host with the lowest-numbered priority field value it can reach, target hosts with the same priority SHOULD be tried in an order defined by the weight field.
The weight field specifies a relative weight for entries with the same priority. Larger weights SHOULD be given a proportionately higher probability of being selected.
Domain administrators SHOULD use Weight 0 when there isn't any server selection to do. In the presence of records containing weights greater than 0, records with Weight 0 SHOULD have a very small chance of being selected.

Note: OpenVPN server selection mechanism implementation indeed will give records with weight of zero a very small chance of being selected first, but never skip them.

Example: instead of multiple --remote in order, now it's possible to specify just one --remote-srv and configure DNS SRV records:

remote-srv example.net

name prio weight port target
$ORIGIN example.net.
_openvpn._udp IN SRV 10 60 1194 server1.example.net.
_openvpn._udp IN SRV 10 40 1194 server2.example.net.
_openvpn._udp IN SRV 10 0 1194 server3.example.net.
_openvpn._tcp IN SRV 20 0 443 server4.example.net.

For "--remote-srv example.net" following will happen in order:
1. The client will first try to resolve "_openvpn._udp.example.net" and "_openvpn._tcp.example.net".
2. Records "server1.example.net:1194", "server2.example.net:1194" and "server3.example.net:1194" will be selected before record "server4.example.net:443" as their priority 10 is smaller than 20.
3. Records "server1.example.net:1194", "server2.example.net:1194" and "server3.example.net:1194" will be randomly selected with weight probability: first will be either "server1.example.net:1194" with 60% probability or "server2.example.net:1194" with 40% or "server3.example.net:1194" with almost zero probability.
4. If "server1.example.net:1194" was selected, the second record will be either "server2.example.net:1194" with almost 100% probability or "server3.example.net:1194" with almost 0%.
5. If "server2.example.net:1194" was selected, the third record will be the only last record of priority 10 - "server3.example.net:1194".
6. Record "server4.example.net:443" will be the last one selected as the only record with priority 20.
7. Each of the resulting "target:port" remote hosts will be resolved and accessed if its protocol has no conflict with the rest of the OpenVPN options.

If DNS SRV name can't be resolved or no valid records were returned, client will move on to the next connection entry.

v14:
disable SRV handling on OpenBSD due to resolver library differences

v13:
rebase to master (Nov 2022)
apply "'static inline', not 'inline static' style guide" include --explicit-exit-notify logic from commit 7953b07bf56c1df0 formatting changes required by uncrustify
replace last occurance of EAI_NODATA with EAI_NONAME OpenBSD does not have ns_c_in/ns_t_srv, need to use C_IN/T_SRV instead

v12:
add get_cached_srv_entry() for servinfo vs addrinfo cache split add check for mixed --remote and --remote-srv
add doxygen dns srv functions comments
use query_servinfo() for both unix and windows
fix undefined NS_MAXMSG issue on macOS
fix undefined EAI_NODATA issue on FreeBSD
fix man and msg() indents
rebase against master

---
 configure.ac                        |   2 +-
 doc/man-sections/client-options.rst | 121 +++-
 doc/management-notes.txt            |   6 +
 src/openvpn/Makefile.am             |   2 +-
 src/openvpn/buffer.h                |   5 -
 src/openvpn/errlevel.h              |   1 +
 src/openvpn/init.c                  |  79 ++-
 src/openvpn/openvpn.vcxproj         |  15 +-
 src/openvpn/options.c               | 258 ++++++--
 src/openvpn/options.h               |   4 +
 src/openvpn/socket.c                | 875 +++++++++++++++++++++++++++-
 src/openvpn/socket.h                |  65 ++-
 src/openvpn/syshead.h               |   5 +
 13 files changed, 1375 insertions(+), 63 deletions(-)
configure.ac +1 -1
index be31889e..27bd2eae 100644
@@ -468,7 +468,7 @@ SOCKET_INCLUDES="
 "
 
 AC_CHECK_HEADERS(
-	[net/if.h netinet/ip.h resolv.h sys/un.h net/if_utun.h sys/kern_control.h],
+	[net/if.h netinet/ip.h arpa/nameser.h resolv.h sys/un.h net/if_utun.h sys/kern_control.h],
 	,
 	,
 	[[${SOCKET_INCLUDES}]]
doc/man-sections/client-options.rst +116 -5

134 lines not on this page · raw message

doc/management-notes.txt +6 -0
index 7bb10c24..f4095cee 100644
@@ -807,6 +807,12 @@ the above notification, use this command:
 
   remote MOD vpn.otherexample.com 1234
 
+DNS SRV discovery domain and service name with protocol code:`auto`
+can't be overriden, but either accepted or skipped only.
+Example of such notification:
+
+  >REMOTE:example.com,openvpn,auto
+
 To accept the same host and port as the client would ordinarily
 have connected to, use this command:
 
src/openvpn/Makefile.am +1 -1
index e80a35ab..faf8fea0 100644
@@ -155,5 +155,5 @@ openvpn_LDADD = \
 	$(OPTIONAL_INOTIFY_LIBS)
 if WIN32
 openvpn_SOURCES += openvpn_win32_resources.rc block_dns.c block_dns.h ring_buffer.h
-openvpn_LDADD += -lgdi32 -lws2_32 -lwininet -lcrypt32 -liphlpapi -lwinmm -lfwpuclnt -lrpcrt4 -lncrypt -lsetupapi -lbcrypt
+openvpn_LDADD += -lgdi32 -lws2_32 -lwininet -lcrypt32 -liphlpapi -lwinmm -lfwpuclnt -lrpcrt4 -lncrypt -lsetupapi -lbcrypt -ldnsapi
 endif
src/openvpn/buffer.h +0 -5
index fece6336..0a96e3b5 100644
@@ -198,11 +198,6 @@ bool buf_init_debug(struct buffer *buf, int offset, const char *file, int line);
 
 
 /* inline functions */
-static inline void
-gc_freeaddrinfo_callback(void *addr)
-{
-    freeaddrinfo((struct addrinfo *) addr);
-}
 
 /** Return an empty struct buffer */
 static inline struct buffer
src/openvpn/errlevel.h +1 -0
index 5bb1e65e..3b8a7c30 100644
@@ -90,6 +90,7 @@
 #define D_ROUTE_QUOTA        LOGLEV(3, 42, 0)        /* show route quota exceeded messages */
 #define D_OSBUF              LOGLEV(3, 43, 0)        /* show socket/tun/tap buffer sizes */
 #define D_PS_PROXY           LOGLEV(3, 44, 0)        /* messages related to --port-share option */
+#define D_RESOLVE            LOGLEV(3, 46, 0)        /* show hostname resolve info */
 #define D_IFCONFIG           LOGLEV(3, 0,  0)        /* show ifconfig info (don't mute) */
 #define D_DCO                LOGLEV(3, 0, 0)         /* show DCO related messages */
 
src/openvpn/init.c +72 -7

139 lines not on this page · raw message

src/openvpn/openvpn.vcxproj +8 -7
index 9b5e416f..43e4dcd6 100644
@@ -166,7 +166,7 @@
     </ClCompile>
     <ResourceCompile />
     <Link>
-      <AdditionalDependencies>Ncrypt.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;Advapi32.lib</AdditionalDependencies>
+      <AdditionalDependencies>Ncrypt.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;dnsapi.lib;Advapi32.lib</AdditionalDependencies>
       <AdditionalLibraryDirectories>$(OPENSSL_HOME)/lib;$(LZO_HOME)/lib;$(PKCS11H_HOME)/lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
       <SubSystem>Console</SubSystem>
     </Link>
@@ -183,7 +183,7 @@
     </ClCompile>
     <ResourceCompile />
     <Link>
-      <AdditionalDependencies>Ncrypt.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;Advapi32.lib</AdditionalDependencies>
+      <AdditionalDependencies>Ncrypt.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;dnsapi.lib;Advapi32.lib</AdditionalDependencies>
       <AdditionalLibraryDirectories>$(OPENSSL_HOME)/lib;$(LZO_HOME)/lib;$(PKCS11H_HOME)/lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
       <SubSystem>Console</SubSystem>
     </Link>
@@ -200,7 +200,7 @@
     </ClCompile>
     <ResourceCompile />
     <Link>
-      <AdditionalDependencies>Ncrypt.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;Advapi32.lib</AdditionalDependencies>
+      <AdditionalDependencies>Ncrypt.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;dnsapi.lib;Advapi32.lib</AdditionalDependencies>
       <AdditionalLibraryDirectories>$(OPENSSL_HOME)/lib;$(LZO_HOME)/lib;$(PKCS11H_HOME)/lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
       <SubSystem>Console</SubSystem>
     </Link>
@@ -218,7 +218,8 @@
     </ClCompile>
     <ResourceCompile />
     <Link>
-      <AdditionalDependencies>Ncrypt.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;Advapi32.lib</AdditionalDependencies>
+      <AdditionalDependencies>Ncrypt.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;dnsapi.lib;Advapi32.lib</AdditionalDependencies>
+      <AdditionalDependencies>legacy_stdio_definitions.lib;Ncrypt.lib;libssl.lib;libcrypto.lib;lzo2.lib;pkcs11-helper.dll.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;dnsapi.lib;%(AdditionalDependencies)</AdditionalDependencies>
       <AdditionalLibraryDirectories>$(OPENSSL_HOME)/lib;$(LZO_HOME)/lib;$(PKCS11H_HOME)/lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
       <SubSystem>Console</SubSystem>
       <CETCompat>true</CETCompat>
@@ -237,7 +238,7 @@
     </ClCompile>
     <ResourceCompile />
     <Link>
-      <AdditionalDependencies>Ncrypt.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;Advapi32.lib</AdditionalDependencies>
+      <AdditionalDependencies>Ncrypt.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;dnsapi.lib;Advapi32.lib</AdditionalDependencies>
       <AdditionalLibraryDirectories>$(OPENSSL_HOME)/lib;$(LZO_HOME)/lib;$(PKCS11H_HOME)/lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
       <SubSystem>Console</SubSystem>
       <CETCompat>true</CETCompat>
@@ -256,7 +257,7 @@
     </ClCompile>
     <ResourceCompile />
     <Link>
-      <AdditionalDependencies>Ncrypt.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;Advapi32.lib</AdditionalDependencies>
+      <AdditionalDependencies>Ncrypt.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;dnsapi.lib;Advapi32.lib</AdditionalDependencies>
       <AdditionalLibraryDirectories>$(OPENSSL_HOME)/lib;$(LZO_HOME)/lib;$(PKCS11H_HOME)/lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
       <SubSystem>Console</SubSystem>
     </Link>
@@ -465,4 +466,4 @@
   <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
   <ImportGroup Label="ExtensionTargets">
   </ImportGroup>
-</Project>
\ No newline at end of file
+</Project>
src/openvpn/options.c +225 -33

368 lines not on this page · raw message

src/openvpn/options.h +4 -0
index 68ad0cac..6f79eb07 100644
@@ -105,6 +105,7 @@ struct connection_entry
     const char *remote_port;
     const char *local;
     const char *remote;
+    bool remote_srv;
     bool remote_float;
     bool bind_defined;
     bool bind_ipv6_only;
@@ -177,6 +178,7 @@ struct remote_entry
     const char *remote_port;
     int proto;
     sa_family_t af;
+    bool remote_srv;
 };
 
 #define CONNECTION_LIST_SIZE 64
@@ -832,6 +834,8 @@ void options_postprocess(struct options *options, struct env_set *es);
 
 bool options_postprocess_pull(struct options *o, struct env_set *es);
 
+bool options_mutate_ce_servinfo(struct options *o, struct servinfo *si);
+
 void pre_connect_restore(struct options *o, struct gc_arena *gc);
 
 bool apply_push_options(struct options *options,
src/openvpn/socket.c +872 -3

935 lines not on this page · raw message

src/openvpn/socket.h +64 -1

127 lines not on this page · raw message

src/openvpn/syshead.h +5 -0
index 5a673a7b..484c4474 100644
@@ -38,6 +38,7 @@
 
 #ifdef _WIN32
 #include <windows.h>
+#include <windns.h>
 #include <winsock2.h>
 #include <tlhelp32.h>
 #define sleep(x) Sleep((x)*1000)
@@ -143,6 +144,10 @@
 #include <netinet/in.h>
 #endif
 
+#ifdef HAVE_ARPA_NAMESER_H
+#include <arpa/nameser.h>
+#endif
+
 #ifdef HAVE_RESOLV_H
 #include <resolv.h>
 #endif
Signature · 1 line
2.35.1
#23 lore raw

I have several nitpicks with this patch which I can enumerate later, but there is at least one critical issue which prevents me from ACKing this:

# src/openvpn/openvpn --client --tls-cert-profile insecure --ca ../ca.crt       --cert ../t_client.c\
rt --key ../t_client.key    --remote-cert-tls server --comp-lzo --verb 3  --dev tun --proto tcp4 --r\
emote-srv lichtenheld.net --writepid ../tests/t_client-flichtenheld-TUXEDO-InfinityBook-S-15-17-Gen7\
-20221201-141818/openvpn-1.pid --setenv TESTNUM 1 --setenv TOP_BUILDDIR .. --script-security 2 --up \
./update_t_client_ips.sh
2022-12-01 14:18:20 WARNING: Compression for receiving enabled. Compression has been used in the pas\
t to break encryption. Sent packets are not compressed unless "allow-compression yes" is also set.
2022-12-01 14:18:20 Note: --cipher is not set. OpenVPN versions before 2.5 defaulted to BF-CBC as fa\
llback when cipher negotiation failed in this case. If you need this fallback please add '--data-cip\
hers-fallback BF-CBC' to your configuration and/or add BF-CBC to --data-ciphers.
2022-12-01 14:18:20 OpenVPN 2.6_git [git:master/c98fe8b90271df5c] x86_64-pc-linux-gnu [SSL (OpenSSL)\
] [LZO] [LZ4] [EPOLL] [MH/PKTINFO] [AEAD] built on Dec  1 2022
2022-12-01 14:18:20 library versions: OpenSSL 3.0.2 15 Mar 2022, LZO 2.10
2022-12-01 14:18:21 Resolved remote service host: conn-test-server.openvpn.org:51194,udp4 prio 0 wei\
ght 0
2022-12-01 14:18:21 Resolved remote service host: conn-test-server.openvpn.org:51194,tcp4-client pri\
o 0 weight 0
2022-12-01 14:18:21 NOTE: the current --script-security setting may allow this configuration to call\
 user-defined scripts
2022-12-01 14:18:21 TCP/UDP: Preserving recently used remote address: [AF_INET]199.102.77.82:51194
2022-12-01 14:18:21 Socket Buffers: R=[212992->212992] S=[212992->212992]
2022-12-01 14:18:21 UDPv4 link local: (not bound)
2022-12-01 14:18:21 UDPv4 link remote: [AF_INET]199.102.77.82:51194

As you can see it ignores the "--proto tcp4" if no proto was specified in --remote-srv. This is inconsistent with how --remote works. I don't think this can be the desired behaviour.

Regards,

Signature · 1 line
  Frank Lichtenheld
#24 lore raw

Hi, Frank
Observing behavior is not desired, indeed. I'll look into

--
Best Regards, Vladislav Grishenko

Quoted 9 lines

-----Original Message-----
From: Frank Lichtenheld <[email protected]...>
Sent: Thursday, December 1, 2022 6:37 PM
To: Gert Doering <[email protected]...>
Cc: [email protected]
Subject: Re: [Openvpn-devel] [PATCH v14] Add DNS SRV remote host discovery support

I have several nitpicks with this patch which I can enumerate later, but

there is at

Quoted 3 lines

least one critical issue which prevents me from ACKing this:

# src/openvpn/openvpn --client --tls-cert-profile insecure --ca ../ca.crt

--cert

Quoted 2 lines

../t_client.c\
rt --key ../t_client.key --remote-cert-tls server --comp-lzo --verb 3

--dev tun --

Quoted 2 lines

proto tcp4 --r\
emote-srv lichtenheld.net --writepid

../tests/t_client-flichtenheld-TUXEDO-

Quoted 5 lines

InfinityBook-S-15-17-Gen7\
-20221201-141818/openvpn-1.pid --setenv TESTNUM 1 --setenv TOP_BUILDDIR .. --script-security 2 --up \ ./update_t_client_ips.sh

2022-12-01 14:18:20 WARNING: Compression for receiving enabled.

Compression has been used in the pas\ t to break encryption. Sent packets

are

Quoted 3 lines

not compressed unless "allow-compression yes" is also set.

2022-12-01 14:18:20 Note: --cipher is not set. OpenVPN versions before 2.5

defaulted to BF-CBC as fa\ llback when cipher negotiation failed in this

case. If

Quoted 1 line

you need this fallback please add '--data-cip\ hers-fallback BF-CBC' to

your

Quoted 3 lines

configuration and/or add BF-CBC to --data-ciphers.

2022-12-01 14:18:20 OpenVPN 2.6_git [git:master/c98fe8b90271df5c] x86_64-

pc-linux-gnu [SSL (OpenSSL)\ ] [LZO] [LZ4] [EPOLL] [MH/PKTINFO] [AEAD]

built

Quoted 7 lines

on Dec 1 2022

2022-12-01 14:18:20 library versions: OpenSSL 3.0.2 15 Mar 2022, LZO 2.10
2022-12-01 14:18:21 Resolved remote service host: conn-test-
server.openvpn.org:51194,udp4 prio 0 wei\ ght 0
2022-12-01 14:18:21 Resolved remote service host: conn-test-
server.openvpn.org:51194,tcp4-client pri\ o 0 weight 0
2022-12-01 14:18:21 NOTE: the current --script-security setting may allow

this

Quoted 8 lines

configuration to call\ user-defined scripts

2022-12-01 14:18:21 TCP/UDP: Preserving recently used remote address:
[AF_INET]199.102.77.82:51194
2022-12-01 14:18:21 Socket Buffers: R=[212992->212992] S=[212992->212992]
2022-12-01 14:18:21 UDPv4 link local: (not bound)
2022-12-01 14:18:21 UDPv4 link remote: [AF_INET]199.102.77.82:51194

As you can see it ignores the "--proto tcp4" if no proto was specified in

--

Quoted 2 lines

remote-srv.
This is inconsistent with how --remote works. I don't think this can be

the

Quoted 11 lines

desired behaviour.

Regards,
--
Frank Lichtenheld

_______________________________________________
Openvpn-devel mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/openvpn-devel

#25 lore raw
In reply to Gert Doering

Smaller nitpicks:

Quoted 1 line · Gert Doering

From: Vladislav Grishenko <[email protected]...>

[...]

Quoted 151 lines
src/openvpn/init.c +72 -7
index c2154b8d..3a70748e 100644
@@ -350,7 +350,12 @@ management_callback_remote_cmd(void *arg, const char **p)
         }
         else if (!strcmp(p[1], "MOD") && p[2] && p[3])
         {
-            if (strlen(p[2]) < RH_HOST_LEN && strlen(p[3]) < RH_PORT_LEN)
+            if (ce->remote_srv && ce->proto == PROTO_AUTO)
+            {
+                /* can't mutate --remote-srv into --remote without protocol */
+                ret = false;
+            }
+            else if (strlen(p[2]) < RH_HOST_LEN && strlen(p[3]) < RH_PORT_LEN)
             {
                 struct remote_host_store *rhs = c->options.rh_store;
                 if (!rhs)
@@ -363,6 +368,7 @@ management_callback_remote_cmd(void *arg, const char **p)
 
                 ce->remote = rhs->host;
                 ce->remote_port = rhs->port;
+                ce->remote_srv = false;
                 flags = CE_MAN_QUERY_REMOTE_MOD;
                 ret = true;
             }
@@ -462,6 +468,23 @@ clear_remote_addrlist(struct link_socket_addr *lsa, bool free)
     lsa->current_remote = NULL;
 }
 
+/*
+ * Clear the remote service list
+ */
+static void
+clear_remote_servlist(struct link_socket_addr *lsa, bool free)
+{
+    if (lsa->service_list && free)
+    {
+        freeservinfo(lsa->service_list);
+    }
+    lsa->service_list = NULL;
+    lsa->current_service = NULL;
+
+    /* clear addrinfo objects as well */
+    clear_remote_addrlist(lsa, free);
+}
+
 /*
  * Increment to next connection entry
  */
@@ -491,6 +514,24 @@ next_connection_entry(struct context *c)
                 c->c1.link_socket_addr.current_remote =
                     c->c1.link_socket_addr.current_remote->ai_next;
             }
+            /* Check if there is another resolved service to try for
+             * the current connection unless persist-remote-ip was
+             * requested and current service already has an address */
+            else if (c->c1.link_socket_addr.current_service
+                     && c->c1.link_socket_addr.current_service->next
+                     && !(c->options.persist_remote_ip
+                          && c->c1.link_socket_addr.remote_list))
+            {
+                c->c1.link_socket_addr.current_service =
+                    c->c1.link_socket_addr.current_service->next;
+
+                /* Clear addrinfo object of the previous service */
+                if (c->c1.link_socket_addr.remote_list)
+                {
+                    clear_remote_addrlist(&c->c1.link_socket_addr,
+                                          !c->options.resolve_in_advance);
+                }
+            }
             else
             {
                 c->options.advance_next_remote = false;
@@ -500,20 +541,24 @@ next_connection_entry(struct context *c)
                  */
                 if (!c->options.persist_remote_ip)
                 {
-                    /* Connection entry addrinfo objects might have been
+                    /* Connection entry addr/servinfo objects might have been
                      * resolved earlier but the entry itself might have been
-                     * skipped by management on the previous loop.
-                     * If so, clear the addrinfo objects as close_instance does
+                     * skipped on the previous loop either by management or
+                     * due inappropriate service protocol.
+                     * Clear the addr/servinfo objects as close_instance does.
                      */
-                    if (c->c1.link_socket_addr.remote_list)
+                    if (c->c1.link_socket_addr.remote_list
+                        || c->c1.link_socket_addr.service_list)
                     {
-                        clear_remote_addrlist(&c->c1.link_socket_addr,
+                        clear_remote_servlist(&c->c1.link_socket_addr,
                                               !c->options.resolve_in_advance);
                     }
 
                     /* close_instance should have cleared the addrinfo objects */
                     ASSERT(c->c1.link_socket_addr.current_remote == NULL);
                     ASSERT(c->c1.link_socket_addr.remote_list == NULL);
+                    ASSERT(c->c1.link_socket_addr.current_service == NULL);
+                    ASSERT(c->c1.link_socket_addr.service_list == NULL);
                 }
                 else
                 {
@@ -549,6 +594,12 @@ next_connection_entry(struct context *c)
         }
 
         c->options.ce = *ce;
+        if (ce_defined && c->c1.link_socket_addr.current_service)
+        {
+            /* map in current service */
+            struct servinfo *si = c->c1.link_socket_addr.current_service;
+            ce_defined = options_mutate_ce_servinfo(&c->options, si);
+        }
 #ifdef ENABLE_MANAGEMENT
         if (ce_defined && management && management_query_remote_enabled(management))
         {
@@ -3699,10 +3750,13 @@ do_close_link_socket(struct context *c)
                ( c->sig->source != SIG_SOURCE_HARD
                  && ((c->c1.link_socket_addr.current_remote
                       && c->c1.link_socket_addr.current_remote->ai_next)
+                     || (c->c1.link_socket_addr.current_service
+                         && c->c1.link_socket_addr.current_service->next)
                      || c->options.no_advance))
                )))
     {
-        clear_remote_addrlist(&c->c1.link_socket_addr, !c->options.resolve_in_advance);
+        clear_remote_servlist(&c->c1.link_socket_addr,
+                              !c->options.resolve_in_advance);
     }
 
     /* Clear the remote actual address when persist_remote_ip is not in use */
@@ -4234,6 +4288,17 @@ init_instance(struct context *c, const struct env_set *env, const unsigned int f
     /* map in current connection entry */
     next_connection_entry(c);
 
+    /* map in current remote service */
+    if (c->options.ce.remote_srv)
+    {
+        do_resolve_service(c);
+        if (IS_SIG(c))
+        {
+            goto sig;
+        }
+        update_options_ce_post(&c->options);
+    }
+
     /* link_socket_mode allows CM_CHILD_TCP
      * instances to inherit acceptable fds
      * from a top-level parent */

[...]

src/openvpn/options.c static const char usage_message[] = · line 131

Quoted 10 lines
src/openvpn/options.c +1 -1
index b7b34c9c..897f1db4 100644
@@ -128,7 +128,9 @@ static const char usage_message[] =
     "Tunnel Options:\n"
     "--local host    : Local host name or ip address. Implies --bind.\n"
     "--remote host [port] : Remote host name or ip address.\n"
-    "--remote-random : If multiple --remote options specified, choose one randomly.\n"
+    "--remote-srv domain [service] : Perform DNS SRV remote host discovery.\n"

Missing [proto]

Quoted 92 lines
src/openvpn/options.c +59 -1
+    "--remote-random : If multiple --remote or --remote-srv options specified,\n"
+    "                  choose one randomly.\n"
     "--remote-random-hostname : Add a random string to remote DNS name.\n"
     "--mode m        : Major mode, m = 'p2p' (default, point-to-point) or 'server'.\n"
     "--proto p       : Use protocol p for communicating with peer.\n"
@@ -161,7 +163,7 @@ static const char usage_message[] =
     "                  up is a file containing username/password on 2 lines, or\n"
     "                  'stdin' to prompt for console.\n"
     "--socks-proxy-retry : Retry indefinitely on Socks proxy errors.\n"
-    "--resolv-retry n: If hostname resolve fails for --remote, retry\n"
+    "--resolv-retry n: If hostname resolve fails for --remote or --remote-srv, retry\n"
     "                  resolve for n seconds before failing (disabled by default).\n"
     "                  Set n=\"infinite\" to retry indefinitely.\n"
     "--float         : Allow remote to change its IP address/port, such as through\n"
@@ -1695,6 +1697,7 @@ show_connection_entry(const struct connection_entry *o)
     SHOW_STR(local_port);
     SHOW_STR(remote);
     SHOW_STR(remote_port);
+    SHOW_BOOL(remote_srv);
     SHOW_BOOL(remote_float);
     SHOW_BOOL(bind_defined);
     SHOW_BOOL(bind_local);
@@ -2246,6 +2249,56 @@ connection_entry_load_re(struct connection_entry *ce, const struct remote_entry
     {
         ce->af = re->af;
     }
+    ce->remote_srv = re->remote_srv;
+}
+
+/* Part of options_postprocess_verify_ce that can be used
+ * in runtime after connection entry proto/hostname change.
+ */
+static bool
+options_postprocess_verify_ce_proto(const struct options *options,
+                                    const struct connection_entry *ce)
+{
+    int msglevel = M_WARN|M_NOPREFIX|M_OPTERR;
+
+    /*
+     * Sanity check on --local, --remote, and --ifconfig
+     */
+
+    if (proto_is_net(ce->proto)
+        && string_defined_equal(ce->local, ce->remote)
+        && string_defined_equal(ce->local_port, ce->remote_port))
+    {
+        msg(msglevel, "--remote and --local addresses are the same");
+        return false;
+    }
+
+    if (string_defined_equal(ce->remote, options->ifconfig_local)
+        || string_defined_equal(ce->remote, options->ifconfig_remote_netmask))
+    {
+        msg(msglevel, "--local and --remote addresses must be distinct from --ifconfig addresses");
+        return false;
+    }
+
+    /*
+     * Check that protocol options make sense.
+     */
+
+#ifdef ENABLE_FRAGMENT
+    if (!proto_is_udp(ce->proto) && ce->fragment)
+    {
+        msg(msglevel, "--fragment can only be used with --proto udp");
+        return false;
+    }
+#endif
+
+    if ((ce->http_proxy_options) && ce->proto != PROTO_TCP_CLIENT)
+    {
+        msg(msglevel, "--http-proxy MUST be used in TCP Client mode (i.e. --proto tcp-client)");
+        return false;
+    }
+
+    return true;
 }
 
 static void
@@ -2322,6 +2375,11 @@ options_postprocess_verify_ce(const struct options *options,
             "--proto tcp-server or --proto tcp-client");
     }
 
+    if (ce->proto == PROTO_AUTO && !ce->remote_srv)
+    {
+        msg(M_USAGE, "--proto auto can be only used with --remote-srv");
+    }
+
     if (options->lladdr && dev != DEV_TYPE_TAP)
     {
         msg(M_USAGE, "--lladdr can only be used in --dev tap mode");

src/openvpn/options.c options_postprocess_verify_ce(const struct options *options, · line 2400

Quoted 9 lines
src/openvpn/options.c +3 -1
@@ -2335,7 +2393,9 @@ options_postprocess_verify_ce(const struct options *options,
         msg(M_USAGE, "only one of --tun-mtu or --link-mtu may be defined");
     }
 
-    if (!proto_is_udp(ce->proto) && options->mtu_test)
+    /* Defer validation for --remote-srv with auto protocol */
+    if (!proto_is_udp(ce->proto) && options->mtu_test
+        && !(ce->remote_srv && ce->proto == PROTO_AUTO))
     {
         msg(M_USAGE, "--mtu-test only makes sense with --proto udp");

You disable this test here, but you don't add this in any of the later checks. So it seems this test is just completely removed when using remote-srv?

Quoted 278 lines
src/openvpn/options.c +162 -30
     }
@@ -2347,6 +2407,11 @@ options_postprocess_verify_ce(const struct options *options,
      * Sanity check on --local, --remote, and --ifconfig
      */
 
+    if (ce->remote_srv && options->ip_remote_hint)
+    {
+        msg(M_USAGE, "--ip-remote-hint can't be used with --remote-srv");
+    }
+
     if (proto_is_net(ce->proto)
         && string_defined_equal(ce->local, ce->remote)
         && string_defined_equal(ce->local_port, ce->remote_port))
@@ -2470,7 +2535,9 @@ options_postprocess_verify_ce(const struct options *options,
      */
 
 #ifdef ENABLE_FRAGMENT
-    if (!proto_is_udp(ce->proto) && ce->fragment)
+    /* Defer validation for --remote-srv with auto protocol */
+    if (!proto_is_udp(ce->proto) && ce->fragment
+        && !(ce->remote_srv && ce->proto == PROTO_AUTO))
     {
         msg(M_USAGE, "--fragment can only be used with --proto udp");
     }
@@ -2481,11 +2548,11 @@ options_postprocess_verify_ce(const struct options *options,
         msg(M_USAGE, "--remote MUST be used in TCP Client mode");
     }
 
-    if ((ce->http_proxy_options) && ce->proto != PROTO_TCP_CLIENT)
+    /* Defer validation for --remote-srv with auto protocol */
+    if ((ce->http_proxy_options) && ce->proto != PROTO_TCP_CLIENT
+        && !(ce->remote_srv && ce->proto == PROTO_AUTO))
     {
-        msg(M_USAGE,
-            "--http-proxy MUST be used in TCP Client mode (i.e. --proto "
-            "tcp-client)");
+        msg(M_USAGE, "--http-proxy MUST be used in TCP Client mode (i.e. --proto tcp-client)");
     }
 
     if ((ce->http_proxy_options) && !ce->http_proxy_options->server)
@@ -2552,6 +2619,10 @@ options_postprocess_verify_ce(const struct options *options,
         {
             msg(M_USAGE, "--remote cannot be used with --mode server");
         }
+        if (ce->remote_srv)
+        {
+            msg(M_USAGE, "--remote-srv cannot be used with --mode server");
+        }
         if (!ce->bind_local)
         {
             msg(M_USAGE, "--nobind cannot be used with --mode server");
@@ -3067,26 +3138,14 @@ options_postprocess_verify_ce(const struct options *options,
     uninit_options(&defaults);
 }
 
-static void
-options_postprocess_mutate_ce(struct options *o, struct connection_entry *ce)
+/* Part of options_postprocess_mutate_ce that can be used
+ * in runtime after connection entry proto/hostname change.
+ */
+static bool
+options_postprocess_mutate_ce_proto(struct options *o,
+                                    struct connection_entry *ce)
 {
-    const int dev = dev_type_enum(o->dev, o->dev_type);
-
-    if (o->server_defined || o->server_bridge_defined || o->server_bridge_proxy_dhcp)
-    {
-        if (ce->proto == PROTO_TCP)
-        {
-            ce->proto = PROTO_TCP_SERVER;
-        }
-    }
-
-    if (o->client)
-    {
-        if (ce->proto == PROTO_TCP)
-        {
-            ce->proto = PROTO_TCP_CLIENT;
-        }
-    }
+    bool result = true;
 
     /* an option is present that requires local bind to enabled */
     bool need_bind = ce->local || ce->local_port_defined || ce->bind_defined;
@@ -3110,7 +3169,61 @@ options_postprocess_mutate_ce(struct options *o, struct connection_entry *ce)
     /* if protocol forcing is enabled, disable all protocols
      * except for the forced one
      */
-    if (o->proto_force >= 0 && o->proto_force != ce->proto)
+    if (o->proto_force >= 0 && o->proto_force != ce->proto
+        && !(ce->remote_srv && ce->proto == PROTO_AUTO))
+    {
+        result = false;
+    }
+
+    /* our socks code is not fully IPv6 enabled yet (TCP works, UDP not)
+     * so fall back to IPv4-only (trac #1221)
+     */
+    if (ce->socks_proxy_server && proto_is_udp(ce->proto) && ce->af != AF_INET)
+    {
+        if (ce->af == AF_INET6)
+        {
+            msg(M_INFO, "WARNING: '--proto udp6' is not compatible with "
+                "'--socks-proxy' today. Forcing IPv4 mode.");
+        }
+        else
+        {
+            msg(M_INFO, "NOTICE: dual-stack mode for '--proto udp' does not "
+                "work correctly with '--socks-proxy' today. Forcing IPv4.");
+        }
+        ce->af = AF_INET;
+    }
+
+    if (!proto_is_udp(ce->proto) && ce->explicit_exit_notification)
+    {
+        msg(M_WARN, "NOTICE: --explicit-exit-notify ignored for --proto tcp");
+        ce->explicit_exit_notification = 0;
+    }
+
+    return result;
+}
+
+static void
+options_postprocess_mutate_ce(struct options *o, struct connection_entry *ce)
+{
+    const int dev = dev_type_enum(o->dev, o->dev_type);
+
+    if (o->server_defined || o->server_bridge_defined || o->server_bridge_proxy_dhcp)
+    {
+        if (ce->proto == PROTO_TCP)
+        {
+            ce->proto = PROTO_TCP_SERVER;
+        }
+    }
+
+    if (o->client)
+    {
+        if (ce->proto == PROTO_TCP)
+        {
+            ce->proto = PROTO_TCP_CLIENT;
+        }
+    }
+
+    if (!options_postprocess_mutate_ce_proto(o, ce))
     {
         ce->flags |= CE_DISABLED;
     }
@@ -3214,12 +3327,32 @@ options_postprocess_mutate_ce(struct options *o, struct connection_entry *ce)
         connection_entry_preload_key(&ce->tls_crypt_v2_file,
                                      &ce->tls_crypt_v2_file_inline, &o->gc);
     }
+}
 
-    if (!proto_is_udp(ce->proto) && ce->explicit_exit_notification)
+/*
+ * Merges servinfo's hostname, servname and proto into current connection
+ * entry if possible and doesn't conflict with the options.
+ * Used by runtime DNS SRV discovery.
+ */
+bool
+options_mutate_ce_servinfo(struct options *o, struct servinfo *si)
+{
+    struct connection_entry ce = o->ce;
+
+    ASSERT(ce.remote_srv);
+
+    ce.remote = si->hostname;
+    ce.remote_port = si->servname;
+    ce.proto = si->proto;
+
+    if (options_postprocess_mutate_ce_proto(o, &ce)
+        && options_postprocess_verify_ce_proto(o, &ce))
     {
-        msg(M_WARN, "NOTICE: --explicit-exit-notify ignored for --proto tcp");
-        ce->explicit_exit_notification = 0;
+        o->ce = ce;
+        return true;
     }
+
+    return false;
 }
 
 #ifdef _WIN32
@@ -6062,7 +6195,8 @@ add_option(struct options *options,
                                OPT_P_CONNECTION, option_types_found, es);
             if (!sub.ce.remote)
             {
-                msg(msglevel, "Each 'connection' block must contain exactly one 'remote' directive");
+                msg(msglevel, "Each 'connection' block must contain exactly one 'remote' "
+                    "or 'remote-srv' directive");
                 uninit_options(&sub);
                 goto err;
             }
@@ -6140,6 +6274,7 @@ add_option(struct options *options,
     {
         struct remote_entry re;
         re.remote = re.remote_port = NULL;
+        re.remote_srv = false;
         re.proto = -1;
         re.af = 0;
 
@@ -6174,9 +6309,66 @@ add_option(struct options *options,
         }
         else if (permission_mask & OPT_P_CONNECTION)
         {
+            if (options->ce.remote && options->ce.remote_srv)
+            {
+                msg(msglevel, "Each 'connection' block must contain exactly one 'remote' "
+                    "or 'remote-srv' directive");
+                goto err;
+            }
+            connection_entry_load_re(&options->ce, &re);
+        }
+    }
+#if !defined(TARGET_OPENBSD)
+    else if (streq(p[0], "remote-srv") && p[1] && !p[4])
+    {
+        struct remote_entry re;
+        re.remote = NULL;
+        re.remote_port = OPENVPN_SERVICE;
+        re.remote_srv = true;
+        re.proto = PROTO_AUTO;
+        re.af = 0;
+
+        VERIFY_PERMISSION(OPT_P_GENERAL|OPT_P_CONNECTION);
+        re.remote = p[1];
+        if (p[2])
+        {
+            re.remote_port = p[2];
+            if (p[3])
+            {
+                const int proto = ascii2proto(p[3]);
+                const sa_family_t af = ascii2af(p[3]);
+                if (proto < 0)
+                {
+                    msg(msglevel,
+                        "remote-srv: bad protocol associated with domain %s: "
+                        "'%s'", p[1], p[3]);
+                    goto err;
+                }
+                re.proto = proto;
+                re.af = af;
+            }
+        }
+        if (permission_mask & OPT_P_GENERAL)
+        {
+            struct remote_entry *e = alloc_remote_entry(options, msglevel);
+            if (!e)
+            {
+                goto err;
+            }
+            *e = re;
+        }
+        else if (permission_mask & OPT_P_CONNECTION)
+        {
+            if (options->ce.remote && !options->ce.remote_srv)
+            {
+                msg(msglevel, "Each 'connection' block must contain exactly one 'remote' "
+                    "or 'remote-srv' directive");
+                goto err;
+            }
             connection_entry_load_re(&options->ce, &re);
         }
     }
+#endif /* if !defined(TARGET_OPENBSD) */
     else if (streq(p[0], "resolv-retry") && p[1] && !p[2])
     {
         VERIFY_PERMISSION(OPT_P_GENERAL);
@@ -6691,7 +6883,7 @@ add_option(struct options *options,
         int proto_force;
         VERIFY_PERMISSION(OPT_P_GENERAL);
         proto_force = ascii2proto(p[1]);
-        if (proto_force < 0)
+        if (proto_force < 0 || proto_force == PROTO_AUTO)
         {
             msg(msglevel, "Bad --proto-force protocol: '%s'", p[1]);
             goto err;

[...]

src/openvpn/socket.c get_cached_dns_entry(struct cached_dns_entry *dns_cache, · line 275

Quoted 10 lines
src/openvpn/socket.c +2 -0
index 4a982561..aa057f61 100644
@@ -271,6 +271,37 @@ get_cached_dns_entry(struct cached_dns_entry *dns_cache,
     return -1;
 }
 
+/*
+ * get_cached_srv_entry return 0 on success and -1

"returns"

Quoted 937 lines
src/openvpn/socket.c +870 -3
+ * otherwise. (like getservinfo)
+ */
+static int
+get_cached_srv_entry(struct cached_dns_entry *dns_cache,
+                     const char *hostname,
+                     const char *servname,
+                     int ai_family,
+                     int resolve_flags,
+                     struct servinfo **si)
+{
+    struct cached_dns_entry *ph;
+    int flags;
+
+    /* Only use flags that are relevant for the structure */
+    flags = resolve_flags & GETADDR_CACHE_SERVICE_MASK;
+    flags |= GETADDR_SERVICE;
+
+    for (ph = dns_cache; ph; ph = ph->next)
+    {
+        if (streqnull(ph->hostname, hostname)
+            && streqnull(ph->servname, servname)
+            && ph->flags == flags)
+        {
+            *si = ph->si;
+            return 0;
+        }
+    }
+    return -1;
+}
 
 static int
 do_preresolve_host(struct context *c,
@@ -326,6 +357,77 @@ do_preresolve_host(struct context *c,
     return status;
 }
 
+static int
+do_preresolve_service(struct context *c,
+                      const char *hostname,
+                      const char *servname,
+                      const int af,
+                      const int flags,
+                      bool preresolve_host)
+{
+    struct servinfo *si;
+    int status;
+
+    if (get_cached_srv_entry(c->c1.dns_cache,
+                             hostname,
+                             servname,
+                             af,
+                             flags,
+                             &si) == 0)
+    {
+        /* entry already cached, return success */
+        return 0;
+    }
+
+    status = openvpn_getservinfo(flags, hostname, servname,
+                                 c->options.resolve_retry_seconds, NULL,
+                                 af, &si);
+    if (status == 0)
+    {
+        struct cached_dns_entry *ph;
+
+        ALLOC_OBJ_CLEAR_GC(ph, struct cached_dns_entry, &c->gc);
+        ph->si = si;
+        ph->hostname = hostname;
+        ph->servname = servname;
+        ph->flags = flags & GETADDR_CACHE_SERVICE_MASK;
+
+        if (!c->c1.dns_cache)
+        {
+            c->c1.dns_cache = ph;
+        }
+        else
+        {
+            struct cached_dns_entry *prev = c->c1.dns_cache;
+            while (prev->next)
+            {
+                prev = prev->next;
+            }
+            prev->next = ph;
+        }
+
+        gc_addspecial(si, &gc_freeservinfo_callback, &c->gc);
+
+        /* preresolve service targets unless disabled */
+        if (preresolve_host)
+        {
+            while (si)
+            {
+                int host_flags = flags & ~GETADDR_PROTO_MASK;
+                if (proto_is_dgram(si->proto))
+                {
+                    host_flags |= GETADDR_DATAGRAM;
+                }
+                /* ignore errors */
+                do_preresolve_host(c, si->hostname, si->servname,
+                                   af, host_flags);
+                si = si->next;
+            }
+        }
+    }
+    return status;
+}
+
 void
 do_preresolve(struct context *c)
 {
@@ -364,8 +466,31 @@ do_preresolve(struct context *c)
             remote = ce->remote;
         }
 
+        /* Preresolve remote services */
+        if (ce->remote_srv)
+        {
+            int service_flags = flags|GETADDR_SERVICE;
+
+            if (proto_is_dgram(ce->proto) || ce->proto == PROTO_AUTO)
+            {
+                service_flags |= GETADDR_DATAGRAM;
+            }
+            if (proto_is_stream(ce->proto) || ce->proto == PROTO_AUTO)
+            {
+                service_flags |= GETADDR_STREAM;
+            }
+
+            /* HTTP remote hostnames does not need to be resolved */
+            status = do_preresolve_service(c, remote, ce->remote_port,
+                                           ce->af, service_flags,
+                                           !ce->http_proxy_options);
+            if (status != 0)
+            {
+                goto err;
+            }
+        }
         /* HTTP remote hostname does not need to be resolved */
-        if (!ce->http_proxy_options)
+        else if (!ce->http_proxy_options)
         {
             status = do_preresolve_host(c, remote, ce->remote_port,
                                         ce->af, flags);
@@ -423,6 +548,638 @@ err:
     throw_signal_soft(SIGHUP, "Preresolving failed");
 }
 
+/**
+ * Allocates new service structure on heap and stores
+ * its initial values.
+ *
+ * @param hostname - The peer host name or ip address
+ * @param port     - The peer TCP/UDP port
+ * @param proto    - Protocol for communicating with the peer
+ *
+ * @return A pointer to servinfo structure or NULL in case of
+ *     allocation error.
+ */
+static struct servinfo *
+alloc_servinfo(const char *hostname, uint16_t port, int proto)
+{
+    size_t namesize = hostname ? strlen(hostname) + 1 : 0;
+
+    char servname[sizeof("65535")];
+    openvpn_snprintf(servname, sizeof(servname), "%u", port);
+    size_t servsize = strlen(servname) + 1;
+
+    struct servinfo *si = calloc(1, sizeof(*si) + namesize + servsize);
+    if (si)
+    {
+        if (hostname)
+        {
+            si->hostname = (char *)(si + 1);
+            memcpy((char *)si->hostname, hostname, namesize);
+        }
+        si->servname = (char *)(si + 1) + namesize;
+        memcpy((char *)si->servname, servname, servsize);
+        si->proto = proto;
+    }
+    return si;
+}
+
+#ifdef _WIN32
+/**
+ * Queries DNS SRV records for specified DNS domain.
+ *
+ * @param domain - The DNS domain name
+ * @param proto  - TCP/UDP protocol for communicating with the peer
+ * @param next   - The servinfo structure list to be chained to
+ *                 the resulting servinfo list
+ * @param res    - The pointer to the resulting servinfo list
+ *
+ * @return 0 on success, a EAI-* status code otherwise
+ */
+static int
+query_servinfo(const char *domain, int proto,
+               struct servinfo *next, struct servinfo **res)
+{
+    PDNS_RECORD pDnsRecord;
+    int status;
+
+    ASSERT(res);
+
+    DNS_STATUS DnsStatus = DnsQuery(domain, DNS_TYPE_SRV, DNS_QUERY_STANDARD,
+                                    NULL, &pDnsRecord, NULL);
+    dmsg(D_SOCKET_DEBUG, "DNSQUERY type=%d domain=%s result=%d",
+         DNS_TYPE_SRV, domain, DnsStatus);
+    switch (DnsStatus)
+    {
+        case ERROR_SUCCESS:
+            break;
+
+        case DNS_ERROR_RCODE_NAME_ERROR:
+        case DNS_INFO_NO_RECORDS:
+            return EAI_NONAME; /* HOST_NOT_FOUND */
+
+        case DNS_ERROR_NO_DNS_SERVERS:
+        case DNS_ERROR_RCODE_FORMAT_ERROR:
+        case DNS_ERROR_RCODE_NOT_IMPLEMENTED:
+        case DNS_ERROR_RCODE_REFUSED:
+            return EAI_FAIL; /* NO_RECOVERY */
+
+        case ERROR_TIMEOUT:
+        case DNS_ERROR_RCODE_SERVER_FAILURE:
+        case DNS_ERROR_TRY_AGAIN_LATER:
+            return EAI_AGAIN; /* TRY_AGAIN */
+
+        default:
+            return EAI_FAIL;
+    }
+
+    struct servinfo *list = NULL, *first = NULL;
+    for (PDNS_RECORD rr = pDnsRecord; rr; rr = rr->pNext)
+    {
+        if (rr->wType == DNS_TYPE_SRV)
+        {
+            PDNS_SRV_DATA rdata = &rr->Data.Srv;
+
+            if (rr->wDataLength >= sizeof(DNS_SRV_DATA)
+                && *rdata->pNameTarget)
+            {
+                struct servinfo *si = alloc_servinfo(rdata->pNameTarget,
+                                                     rdata->wPort,
+                                                     proto);
+                if (!si)
+                {
+                    freeservinfo(list);
+                    status = EAI_MEMORY;
+                    goto done;
+                }
+                si->prio = rdata->wPriority;
+                si->weight = rdata->wWeight;
+                si->next = list, list = si;
+                if (!first)
+                {
+                    first = si;
+                }
+            }
+        }
+    }
+    if (list)
+    {
+        first->next = next;
+        *res = list;
+        status = 0;
+    }
+    else
+    {
+        status = EAI_FAIL;
+    }
+
+done:
+    DnsRecordListFree(pDnsRecord, DnsFreeRecordList);
+    return status;
+}
+
+#else  /* ifdef _WIN32 */
+/**
+ * Queries DNS SRV records for specified DNS domain.
+ *
+ * @param domain - The DNS domain name
+ * @param proto  - TCP/UDP protocol for communicating with the peer
+ * @param next   - The servinfo structure list to be chained to
+ *                 the resulting servinfo list
+ * @param res    - The pointer to the resulting servinfo list
+ *
+ * @return 0 on success, a EAI-* status code otherwise
+ */
+
+static int
+query_servinfo(const char *domain, int proto,
+               struct servinfo *next, struct servinfo **res)
+{
+#if !defined(TARGET_OPENBSD)
+    unsigned char answer[65535];
+    int status;
+
+    int n = res_query(domain, ns_c_in, ns_t_srv, answer, sizeof(answer));
+    dmsg(D_SOCKET_DEBUG, "RES_QUERY class=%d type=%d domain=%s result=%d",
+         ns_c_in, ns_t_srv, domain, n);
+    if (n < 0)
+    {
+        switch (h_errno)
+        {
+            case HOST_NOT_FOUND:
+            case NO_ADDRESS:
+#if NO_ADDRESS != NO_DATA
+            case NO_DATA:
+#endif
+                return EAI_NONAME;
+
+            case NO_RECOVERY:
+                return EAI_FAIL;
+
+            case TRY_AGAIN:
+                return EAI_AGAIN;
+        }
+        return EAI_SYSTEM;
+    }
+
+    ns_msg msg;
+    if (ns_initparse(answer, n, &msg) < 0)
+    {
+        return EAI_FAIL;
+    }
+
+    struct servinfo *list = NULL, *first = NULL;
+    for (int i = 0; i < ns_msg_count(msg, ns_s_an); i++)
+    {
+        ns_rr rr;
+
+        if (ns_parserr(&msg, ns_s_an, i, &rr) == 0
+            && ns_rr_type(rr) == ns_t_srv)
+        {
+            const unsigned char *rdata = ns_rr_rdata(rr);
+            char name[NS_MAXDNAME];
+
+            if (ns_rr_rdlen(rr) > 6
+                && dn_expand(ns_msg_base(msg), ns_msg_end(msg),
+                             rdata + 6, name, sizeof(name)) > 0 && *name)
+            {
+                struct servinfo *si = alloc_servinfo(name,
+                                                     ns_get16(rdata + 4),
+                                                     proto);
+                if (!si)
+                {
+                    freeservinfo(list);
+                    status = EAI_MEMORY;
+                    goto done;
+                }
+                si->prio = ns_get16(rdata);
+                si->weight = ns_get16(rdata + 2);
+                si->next = list, list = si;
+                if (!first)
+                {
+                    first = si;
+                }
+            }
+        }
+    }
+    if (list)
+    {
+        first->next = next;
+        *res = list;
+        status = 0;
+    }
+    else
+    {
+        status = EAI_FAIL;
+    }
+
+done:
+    return status;
+#else   /* defined(TARGET_OPENBSD) */
+    /* OpenBSD's native resolver library has a better API - getrrsetbyname() -
+     * but this is not implemented yet
+     */
+    return EAI_FAIL;
+#endif  /* defined(TARGET_OPENBSD) */
+}
+#endif /* ifdef _WIN32 */
+
+/**
+ * Servinfo qsort compare function for the server selection
+ * mechanism, defined in RFC 2782.
+ *
+ * @param a - Pointer to first servinfo structure
+ * @param b - Pointer to second servinfo structure
+ *
+ * @return
+ * @li 0, if equal
+ * @li 1, if "a" should be ordered after "b"
+ * @li -1, if "a" should be ordered before "b"
+ */
+static int
+servinfo_cmp(const void *a, const void *b)
+{
+    const struct servinfo *ae = *(struct servinfo **)a;
+    const struct servinfo *be = *(struct servinfo **)b;
+
+    /* lowest-numbered priority first */
+    if (ae->prio != be->prio)
+    {
+        return ae->prio < be->prio ? -1 : 1;
+    }
+
+    /* zero-weighted first */
+    if ((ae->weight == 0 && be->weight)
+        || (ae->weight && be->weight == 0))
+    {
+        return ae->weight < be->weight ? -1 : 1;
+    }
+
+    /* else keep received order, can't be equal */
+    return ae->order > be->order ? -1 : 1;
+}
+
+/**
+ * Sorts service list according the server selection mechanism,
+ * defined in RFC 2782.
+ *
+ * @param list - The pointer to servinfo list
+ *
+ * @return A pointer to the sorted servinfo list
+ */
+static struct servinfo *
+sort_servinfo(struct servinfo *list)
+{
+    struct servinfo ordered, *tail = &ordered;
+    int count = 0;
+    struct gc_arena gc = gc_new();
+
+    ASSERT(list);
+
+    /* count and number entries in reverse order */
+    for (struct servinfo *si = list; si; si = si->next)
+    {
+        si->order = count++;
+    }
+
+    struct servinfo **sorted;
+    ALLOC_ARRAY_CLEAR_GC(sorted, struct servinfo *, count, &gc);
+    for (struct servinfo *si = list; si; si = si->next)
+    {
+        sorted[si->order] = si;
+    }
+
+    /* sort records by priority and zero weight */
+    qsort(sorted, count, sizeof(sorted[0]), servinfo_cmp);
+
+    /* apply weighted selection mechanism */
+    ordered.next = NULL;
+    for (int i = 0; i < count; )
+    {
+        struct servinfo unordered;
+
+        /* compute the sum of the weights of records of the same
+         * priority and put them in the unordered list */
+        unordered.prio = sorted[i]->prio;
+        unordered.weight = 0;
+        unordered.next = NULL;
+        for (struct servinfo *prev = &unordered;
+             i < count && sorted[i]->prio == unordered.prio; i++)
+        {
+            unordered.weight += sorted[i]->weight;
+
+            /* add entry to the tail of unordered list */
+            sorted[i]->next = NULL;
+            prev->next = sorted[i], prev = sorted[i];
+        }
+
+        /* process the unordered list */
+        while (unordered.next)
+        {
+            /* choose a uniform random number between 0 and the sum
+             * computed (inclusive) */
+            int weight = get_random() % (unordered.weight + 1);
+
+            /* select the entries whose running sum value is the first
+             * in the selected order which is greater than or equal
+             * to the random number selected */
+            for (struct servinfo *si = unordered.next, *prev = &unordered;
+                 si; prev = si, si = si->next)
+            {
+                /* selected entry is the next one to be contacted */
+                if (si->weight >= weight)
+                {
+                    unordered.weight -= si->weight;
+
+                    /* move entry to the ordered list */
+                    prev->next = si->next;
+                    si->next = NULL;
+                    tail->next = si, tail = si;
+
+                    /*
+                     * RFC 2782 is ambiguous, it says:
+                     *   In the presence of records containing weights greater
+                     *   than 0, records with weight 0 should have a very
+                     *   small chance of being selected.
+                     * According that, within the same priority, after all
+                     * records containing weights greater than 0 were selected,
+                     * the rest of records with weight 0 should be skipped.
+                     * At the same time, it says:
+                     *   The following algorithm SHOULD be used to order the
+                     *   SRV RRs of the same priority:
+                     *   ...
+                     *   Continue the ordering process until there are no
+                     *   unordered SRV RRs.
+                     * This means records with wight 0 should always be
+                     * selected, as last ones in worst case.
+                     *
+                     * We implement the second option and do not skip any of
+                     * the records with unordered.weight == 0 after the last
+                     * one with weight greater than 0.
+                     */
+                }
+                weight -= si->weight;
+            }
+        }
+    }
+
+    gc_free(&gc);
+    return ordered.next;
+}
+
+/**
+ * Resolves DNS SRV records for given domain and service names.
+ *
+ * @param domain  - The DNS SRV domain name
+ * @param service - The DNS SRV service name
+ * @param flags   - GETADDR_* DNS resultion flags
+ * @param res     - The pointer to the resulting servinfo list
+ *
+ * @return 0 on success, a EAI-* status code otherwise
+ */
+static int
+getservinfo(const char *domain,
+            const char *service,
+            int flags,
+            struct servinfo **res)
+{
+    static const struct {
+        int flags;
+        int proto;
+        const char *name;
+    } proto[] = {
+        { GETADDR_DATAGRAM, PROTO_UDP, "udp" },
+        { GETADDR_STREAM, PROTO_TCP_CLIENT, "tcp" }
+    };
+    struct servinfo *list = NULL;
+    int status = EAI_SOCKTYPE;
+
+    ASSERT(res);
+
+    if (!domain)
+    {
+        return EAI_NONAME;
+    }
+    if (!service)
+    {
+        return EAI_SERVICE;
+    }
+
+    int proto_flags = flags & GETADDR_PROTO_MASK;
+    for (int i = 0; i < SIZE(proto); i++)
+    {
+        if (proto_flags & proto[i].flags)
+        {
+            proto_flags &= ~proto[i].flags;
+
+            char qname[256];
+            if (!openvpn_snprintf(qname, sizeof(qname), "_%s._%s.%s",
+                                  service, proto[i].name, domain))
+            {
+                freeservinfo(list);
+                return EAI_MEMORY;
+            }
+
+            status = query_servinfo(qname, proto[i].proto, list, &list);
+        }
+    }
+
+    if (list)
+    {
+        *res = sort_servinfo(list);
+        status = 0;
+    }
+
+    return status;
+}
+
+void
+freeservinfo(struct servinfo *res)
+{
+    while (res)
+    {
+        struct servinfo *si = res;
+        res = res->next;
+        free(si);
+    }
+}
+
+/*
+ * Translate IPv4/IPv6 hostname and service name into struct servinfo
+ * If resolve error, try again for resolve_retry_seconds seconds.
+ */
+int
+openvpn_getservinfo(unsigned int flags,
+                    const char *hostname,
+                    const char *servname,
+                    int resolve_retry_seconds,
+                    volatile int *signal_received,
+                    int family,
+                    struct servinfo **res)
+{
+    int status;
+    int sigrec = 0;
+    int msglevel = (flags & GETADDR_FATAL) ? M_FATAL : D_RESOLVE_ERRORS;
+    struct gc_arena gc = gc_new();
+    const char *print_hostname;
+    const char *print_servname;
+
+    ASSERT(res);
+
+    ASSERT(hostname || servname);
+    ASSERT(!(flags & GETADDR_HOST_ORDER));
+
+    if (hostname)
+    {
+        print_hostname = hostname;
+    }
+    else
+    {
+        print_hostname = "undefined";
+    }
+
+    if (servname)
+    {
+        print_servname = servname;
+    }
+    else
+    {
+        print_servname = "";
+    }
+
+    if (flags & GETADDR_MSG_VIRT_OUT)
+    {
+        msglevel |= M_MSG_VIRT_OUT;
+    }
+
+    if ((flags & (GETADDR_FATAL_ON_SIGNAL|GETADDR_WARN_ON_SIGNAL))
+        && !signal_received)
+    {
+        signal_received = &sigrec;
+    }
+
+    const int fail_wait_interval = 5; /* seconds */
+    /* Add +4 to cause integer division rounding up (1 + 4) = 5, (0+4)/5=0 */
+    int resolve_retries = (flags & GETADDR_TRY_ONCE) ? 1 :
+                          ((resolve_retry_seconds + 4)/ fail_wait_interval);
+    const char *fmt;
+    int level = 0;
+
+    fmt = "RESOLVE: Cannot resolve remote service: %s:%s (%s)";
+    if ((flags & GETADDR_MENTION_RESOLVE_RETRY)
+        && !resolve_retry_seconds)
+    {
+        fmt = "RESOLVE: Cannot resolve remote service: %s:%s (%s) "
+              "(I would have retried this name query if you had "
+              "specified the --resolv-retry option.)";
+    }
+
+#ifdef ENABLE_MANAGEMENT
+    if (flags & GETADDR_UPDATE_MANAGEMENT_STATE)
+    {
+        if (management)
+        {
+            management_set_state(management,
+                                 OPENVPN_STATE_RESOLVE,
+                                 NULL,
+                                 NULL,
+                                 NULL,
+                                 NULL,
+                                 NULL);
+        }
+    }
+#endif
+
+    /*
+     * Resolve service
+     */
+    while (true)
+    {
+#ifndef _WIN32
+        /* force resolv.conf reload */
+        res_init();
+#endif
+        dmsg(D_SOCKET_DEBUG, "GETSERVINFO flags=0x%04x family=%d %s:%s",
+             flags, family, print_hostname, print_servname);
+        status = getservinfo(hostname, servname, flags, res);
+
+        if (signal_received)
+        {
+            get_signal(signal_received);
+            if (*signal_received) /* were we interrupted by a signal? */
+            {
+                if (*signal_received == SIGUSR1) /* ignore SIGUSR1 */
+                {
+                    msg(level, "RESOLVE: Ignored SIGUSR1 signal received "
+                        "during DNS resolution attempt");
+                    *signal_received = 0;
+                }
+                else
+                {
+                    /* turn success into failure (interrupted syscall) */
+                    if (0 == status)
+                    {
+                        ASSERT(res);
+                        freeservinfo(*res);
+                        *res = NULL;
+                        status = EAI_AGAIN; /* = temporary failure */
+                        errno = EINTR;
+                    }
+                    goto done;
+                }
+            }
+        }
+
+        /* success? */
+        if (0 == status)
+        {
+            break;
+        }
+
+        /* resolve lookup failed, should we
+         * continue or fail? */
+        level = msglevel;
+        if (resolve_retries > 0)
+        {
+            level = D_RESOLVE_ERRORS;
+        }
+
+        msg(level,
+            fmt,
+            print_hostname,
+            print_servname,
+            gai_strerror(status));
+
+        if (--resolve_retries <= 0)
+        {
+            goto done;
+        }
+
+        management_sleep(fail_wait_interval);
+    }
+
+    ASSERT(res);
+
+    /* service resolve succeeded */
+
+done:
+    if (signal_received && *signal_received)
+    {
+        int level = 0;
+        if (flags & GETADDR_FATAL_ON_SIGNAL)
+        {
+            level = M_FATAL;
+        }
+        else if (flags & GETADDR_WARN_ON_SIGNAL)
+        {
+            level = M_WARN;
+        }
+        msg(level, "RESOLVE: signal received during DNS resolution attempt");
+    }
+
+    gc_free(&gc);
+    return status;
+}
+
 /*
  * Translate IPv4/IPv6 addr or hostname into struct addrinfo
  * If resolve error, try again for resolve_retry_seconds seconds.
@@ -557,8 +1314,9 @@ openvpn_getaddrinfo(unsigned int flags,
             /* try hostname lookup */
             hints.ai_flags &= ~AI_NUMERICHOST;
             dmsg(D_SOCKET_DEBUG,
-                 "GETADDRINFO flags=0x%04x ai_family=%d ai_socktype=%d",
-                 flags, hints.ai_family, hints.ai_socktype);
+                 "GETADDRINFO flags=0x%04x ai_family=%d ai_socktype=%d %s:%s",
+                 flags, hints.ai_family, hints.ai_socktype,
+                 print_hostname, print_servname);
             status = getaddrinfo(hostname, servname, &hints, res);
 
             if (signal_received)
@@ -1816,7 +2574,110 @@ done:
     gc_free(&gc);
 }
 
+void
+do_resolve_service(struct context *c)
+{
+    struct connection_entry *ce = &c->options.ce;
 
+    if (ce->remote_srv
+        && !c->c1.link_socket_addr.service_list)
+    {
+        if (ce->remote)
+        {
+            unsigned int flags = sf2gaf(GETADDR_RESOLVE
+                                        |GETADDR_UPDATE_MANAGEMENT_STATE
+                                        |GETADDR_SERVICE,
+                                        c->options.sockflags);
+            int retry = 0;
+            int status = -1;
+            struct servinfo *si;
+
+            if (proto_is_dgram(ce->proto) || ce->proto == PROTO_AUTO)
+            {
+                flags |= GETADDR_DATAGRAM;
+            }
+            if (proto_is_stream(ce->proto) || ce->proto == PROTO_AUTO)
+            {
+                flags |= GETADDR_STREAM;
+            }
+
+            if (c->options.sockflags & SF_HOST_RANDOMIZE)
+            {
+                flags |= GETADDR_RANDOMIZE;
+            }
+
+            if (c->options.resolve_retry_seconds == RESOLV_RETRY_INFINITE)
+            {
+                flags |= (GETADDR_TRY_ONCE | GETADDR_FATAL);
+                retry = 0;
+            }
+            else if (c->options.resolve_retry_seconds)
+            {
+                flags |= GETADDR_FATAL;
+                retry = c->options.resolve_retry_seconds;
+            }
+            else
+            {
+                flags |= (GETADDR_FATAL | GETADDR_MENTION_RESOLVE_RETRY);
+                retry = 0;
+            }
+
+            status = get_cached_srv_entry(c->c1.dns_cache,
+                                          ce->remote,
+                                          ce->remote_port,
+                                          ce->af,
+                                          flags, &si);
+            if (status)
+            {
+                status = openvpn_getservinfo(flags, ce->remote, ce->remote_port,
+                                             retry, &c->sig->signal_received,
+                                             ce->af, &si);
+            }
+
+            if (status == 0)
+            {
+                c->c1.link_socket_addr.service_list = si;
+                c->c1.link_socket_addr.current_service = NULL;
+
+                /* advance to the first appropriate service */
+                while (si)
+                {
+                    /* map in current service */
+                    if (!c->c1.link_socket_addr.current_service
+                        && options_mutate_ce_servinfo(&c->options, si))
+                    {
+                        c->c1.link_socket_addr.current_service = si;
+                    }
+
+                    /* log discovered service hosts */
+                    msg(D_RESOLVE,
+                        "Resolved remote service host: %s:%s,%s prio %u weight %u",
+                        np(si->hostname), np(si->servname),
+                        proto2ascii(si->proto, ce->af, false),
+                        si->prio, si->weight);
+
+                    si = si->next;
+                }
+                if (!c->c1.link_socket_addr.current_service)
+                {
+                    status = EAI_NONAME;
+                }
+
+                dmsg(D_SOCKET_DEBUG,
+                     "RESOLVE_SERVICE flags=0x%04x rrs=%d sig=%d status=%d",
+                     flags,
+                     retry,
+                     c->sig->signal_received,
+                     status);
+            }
+
+            if (!c->sig->signal_received && status != 0)
+            {
+                c->sig->signal_received = SIGUSR1;
+            }
+        }
+    }
+}
 
 struct link_socket *
 link_socket_new(void)
@@ -3077,16 +3938,19 @@ static const struct proto_names proto_names[] = {
     {"tcp-server",  "TCP_SERVER", AF_UNSPEC, PROTO_TCP_SERVER},
     {"tcp-client",  "TCP_CLIENT", AF_UNSPEC, PROTO_TCP_CLIENT},
     {"tcp",         "TCP", AF_UNSPEC, PROTO_TCP},
+    {"auto",        "AUTO", AF_UNSPEC, PROTO_AUTO},
     /* force IPv4 */
     {"udp4",        "UDPv4", AF_INET, PROTO_UDP},
     {"tcp4-server", "TCPv4_SERVER", AF_INET, PROTO_TCP_SERVER},
     {"tcp4-client", "TCPv4_CLIENT", AF_INET, PROTO_TCP_CLIENT},
     {"tcp4",        "TCPv4", AF_INET, PROTO_TCP},
+    {"auto4",       "AUTOv4", AF_INET, PROTO_AUTO},
     /* force IPv6 */
     {"udp6",        "UDPv6", AF_INET6, PROTO_UDP},
     {"tcp6-server", "TCPv6_SERVER", AF_INET6, PROTO_TCP_SERVER},
     {"tcp6-client", "TCPv6_CLIENT", AF_INET6, PROTO_TCP_CLIENT},
     {"tcp6",        "TCPv6", AF_INET6, PROTO_TCP},
+    {"auto6",       "AUTOv6", AF_INET6, PROTO_AUTO},
 };
 
 int
@@ -3147,6 +4011,11 @@ proto2ascii_all(struct gc_arena *gc)
 
     for (i = 0; i < SIZE(proto_names); ++i)
     {
+        if (proto_names[i].proto == PROTO_NONE
+            || proto_names[i].proto == PROTO_AUTO)
+        {
+            continue;
+        }
         if (i)
         {
             buf_printf(&out, " ");

[...]

Signature · 1 line
  Frank Lichtenheld
#26 lore raw

Hi Frank,

Quoted 4 lines
Quoted 1 line

+ "--remote-srv domain [service] : Perform DNS SRV remote host

discovery.\n"

Missing [proto]

Sure, will add

Quoted 10 lines

src/openvpn/options.c options_postprocess_verify_ce(const struct options *options, · line 2400

Quoted 6 lines
src/openvpn/options.c +3 -1
-    if (!proto_is_udp(ce->proto) && options->mtu_test)
+    /* Defer validation for --remote-srv with auto protocol */
+    if (!proto_is_udp(ce->proto) && options->mtu_test
+        && !(ce->remote_srv && ce->proto == PROTO_AUTO))
     {
         msg(M_USAGE, "--mtu-test only makes sense with --proto udp");

You disable this test here, but you don't add this in any of the later checks. So it seems this test is just completely removed when using remote-srv?

Right, this check should be moved into options_postprocess_verify_ce_proto() and seems forgotten, will add it too. Thank you

Quoted 3 lines
Quoted 1 line

+ * get_cached_srv_entry return 0 on success and -1

"returns"

Ok, sure

--
Best Regards, Vladislav Grishenko

#27 lore raw

PATCH v15 1/1 Add DNS SRV remote host discovery support

In reply to Gert Doering

DNS SRV remote host discovery allows to have multiple OpenVPN servers for a single domain w/o explicit profile enumeration, to move services from host to host with little fuss, and to designate hosts as primary servers for a service and others as backups.
Feature has been asked several times already, should be useful in case of substantial number of clients & servers deployed.

Patch introduces "--remote-srv domain [service] [proto]" option. The "service" and "proto" arguments are optional. Client will try to resolve DNS SRV record "_service._proto.domain" and use returned DNS SRV records as remote server list ordered by server selection mechanism defined in RFC2782 (https://tools.ietf.org/html/rfc2782):

A client MUST attempt to contact the target host with the lowest-numbered priority field value it can reach, target hosts with the same priority SHOULD be tried in an order defined by the weight field.
The weight field specifies a relative weight for entries with the same priority. Larger weights SHOULD be given a proportionately higher probability of being selected.
Domain administrators SHOULD use Weight 0 when there isn't any server selection to do. In the presence of records containing weights greater than 0, records with Weight 0 SHOULD have a very small chance of being selected.

Note: OpenVPN server selection mechanism implementation indeed will give records with weight of zero a very small chance of being selected first, but never skip them.

Example: instead of multiple --remote in order, now it's possible to specify just one --remote-srv and configure DNS SRV records:

remote-srv example.net

name prio weight port target
$ORIGIN example.net.
_openvpn._udp IN SRV 10 60 1194 server1.example.net.
_openvpn._udp IN SRV 10 40 1194 server2.example.net.
_openvpn._udp IN SRV 10 0 1194 server3.example.net.
_openvpn._tcp IN SRV 20 0 443 server4.example.net.

For "--remote-srv example.net" following will happen in order:
1. The client will first try to resolve "_openvpn._udp.example.net" and "_openvpn._tcp.example.net".
2. Records "server1.example.net:1194", "server2.example.net:1194" and "server3.example.net:1194" will be selected before record "server4.example.net:443" as their priority 10 is smaller than 20.
3. Records "server1.example.net:1194", "server2.example.net:1194" and "server3.example.net:1194" will be randomly selected with weight probability: first will be either "server1.example.net:1194" with 60% probability or "server2.example.net:1194" with 40% or "server3.example.net:1194" with almost zero probability.
4. If "server1.example.net:1194" was selected, the second record will be either "server2.example.net:1194" with almost 100% probability or "server3.example.net:1194" with almost 0%.
5. If "server2.example.net:1194" was selected, the third record will be the only last record of priority 10 - "server3.example.net:1194".
6. Record "server4.example.net:443" will be the last one selected as the only record with priority 20.
7. Each of the resulting "target:port" remote hosts will be resolved and accessed if its protocol has no conflict with the rest of the OpenVPN options.

If DNS SRV name can't be resolved or no valid records were returned, client will move on to the next connection entry.

v15:
rebase to master (Dec 2022)
add optional port argument to --remote and --remote-srv usage message fix --proto option coexisting with --remote-srv
fix --nobind option coexisting with --remote-srv
fix options postprocess mutation lost in v13/v14
recover --mtu-test handling with --remote-srv
use explicit srv resolve stub for openbsd for the future fix comments

v14:
disable SRV handling on OpenBSD due to resolver library differences

v13:
rebase to master (Nov 2022)
apply "'static inline', not 'inline static' style guide" include --explicit-exit-notify logic from commit 7953b07bf56c1df0 formatting changes required by uncrustify
replace last occurance of EAI_NODATA with EAI_NONAME OpenBSD does not have ns_c_in/ns_t_srv, need to use C_IN/T_SRV instead

v12:
add get_cached_srv_entry() for servinfo vs addrinfo cache split add check for mixed --remote and --remote-srv
add doxygen dns srv functions comments
use query_servinfo() for both unix and windows
fix undefined NS_MAXMSG issue on macOS
fix undefined EAI_NODATA issue on FreeBSD
fix man and msg() indents
rebase against master

---
 configure.ac                        |   2 +-
 doc/man-sections/client-options.rst | 121 +++-
 doc/management-notes.txt            |   6 +
 src/openvpn/Makefile.am             |   2 +-
 src/openvpn/buffer.h                |   5 -
 src/openvpn/errlevel.h              |   1 +
 src/openvpn/init.c                  |  79 ++-
 src/openvpn/openvpn.vcxproj         |  12 +-
 src/openvpn/options.c               | 249 +++++++-
 src/openvpn/options.h               |   4 +
 src/openvpn/socket.c                | 868 +++++++++++++++++++++++++++-
 src/openvpn/socket.h                |  67 ++-
 src/openvpn/syshead.h               |   5 +
 13 files changed, 1366 insertions(+), 55 deletions(-)
configure.ac +1 -1
index be31889e..27bd2eae 100644
@@ -468,7 +468,7 @@ SOCKET_INCLUDES="
 "
 
 AC_CHECK_HEADERS(
-	[net/if.h netinet/ip.h resolv.h sys/un.h net/if_utun.h sys/kern_control.h],
+	[net/if.h netinet/ip.h arpa/nameser.h resolv.h sys/un.h net/if_utun.h sys/kern_control.h],
 	,
 	,
 	[[${SOCKET_INCLUDES}]]
doc/man-sections/client-options.rst +116 -5

134 lines not on this page · raw message

doc/management-notes.txt +6 -0
index 6daa811a..487d38b4 100644
@@ -867,6 +867,12 @@ the above notification, use this command:
 
   remote MOD vpn.otherexample.com 1234
 
+DNS SRV discovery domain and service name with protocol code:`auto`
+can't be overriden, but either accepted or skipped only.
+Example of such notification:
+
+  >REMOTE:example.com,openvpn,auto
+
 To accept the same host and port as the client would ordinarily
 have connected to, use this command:
 
src/openvpn/Makefile.am +1 -1
index e80a35ab..faf8fea0 100644
@@ -155,5 +155,5 @@ openvpn_LDADD = \
 	$(OPTIONAL_INOTIFY_LIBS)
 if WIN32
 openvpn_SOURCES += openvpn_win32_resources.rc block_dns.c block_dns.h ring_buffer.h
-openvpn_LDADD += -lgdi32 -lws2_32 -lwininet -lcrypt32 -liphlpapi -lwinmm -lfwpuclnt -lrpcrt4 -lncrypt -lsetupapi -lbcrypt
+openvpn_LDADD += -lgdi32 -lws2_32 -lwininet -lcrypt32 -liphlpapi -lwinmm -lfwpuclnt -lrpcrt4 -lncrypt -lsetupapi -lbcrypt -ldnsapi
 endif
src/openvpn/buffer.h +0 -5
index 185226f7..f4ea6ced 100644
@@ -211,11 +211,6 @@ bool buf_init_debug(struct buffer *buf, int offset, const char *file, int line);
 
 
 /* inline functions */
-static inline void
-gc_freeaddrinfo_callback(void *addr)
-{
-    freeaddrinfo((struct addrinfo *) addr);
-}
 
 /** Return an empty struct buffer */
 static inline struct buffer
src/openvpn/errlevel.h +1 -0
index 5bb1e65e..3b8a7c30 100644
@@ -90,6 +90,7 @@
 #define D_ROUTE_QUOTA        LOGLEV(3, 42, 0)        /* show route quota exceeded messages */
 #define D_OSBUF              LOGLEV(3, 43, 0)        /* show socket/tun/tap buffer sizes */
 #define D_PS_PROXY           LOGLEV(3, 44, 0)        /* messages related to --port-share option */
+#define D_RESOLVE            LOGLEV(3, 46, 0)        /* show hostname resolve info */
 #define D_IFCONFIG           LOGLEV(3, 0,  0)        /* show ifconfig info (don't mute) */
 #define D_DCO                LOGLEV(3, 0, 0)         /* show DCO related messages */
 
src/openvpn/init.c +72 -7

139 lines not on this page · raw message

src/openvpn/openvpn.vcxproj +6 -6
index 13755dae..970de3f3 100644
@@ -166,7 +166,7 @@
     </ClCompile>
     <ResourceCompile />
     <Link>
-      <AdditionalDependencies>Ncrypt.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;Advapi32.lib</AdditionalDependencies>
+      <AdditionalDependencies>Ncrypt.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;dnsapi.lib;Advapi32.lib</AdditionalDependencies>
       <AdditionalLibraryDirectories>$(OPENSSL_HOME)/lib;$(LZO_HOME)/lib;$(PKCS11H_HOME)/lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
       <SubSystem>Console</SubSystem>
     </Link>
@@ -183,7 +183,7 @@
     </ClCompile>
     <ResourceCompile />
     <Link>
-      <AdditionalDependencies>Ncrypt.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;Advapi32.lib</AdditionalDependencies>
+      <AdditionalDependencies>Ncrypt.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;dnsapi.lib;Advapi32.lib</AdditionalDependencies>
       <AdditionalLibraryDirectories>$(OPENSSL_HOME)/lib;$(LZO_HOME)/lib;$(PKCS11H_HOME)/lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
       <SubSystem>Console</SubSystem>
     </Link>
@@ -200,7 +200,7 @@
     </ClCompile>
     <ResourceCompile />
     <Link>
-      <AdditionalDependencies>Ncrypt.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;Advapi32.lib</AdditionalDependencies>
+      <AdditionalDependencies>Ncrypt.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;dnsapi.lib;Advapi32.lib</AdditionalDependencies>
       <AdditionalLibraryDirectories>$(OPENSSL_HOME)/lib;$(LZO_HOME)/lib;$(PKCS11H_HOME)/lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
       <SubSystem>Console</SubSystem>
     </Link>
@@ -218,7 +218,7 @@
     </ClCompile>
     <ResourceCompile />
     <Link>
-      <AdditionalDependencies>Ncrypt.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;Advapi32.lib</AdditionalDependencies>
+      <AdditionalDependencies>Ncrypt.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;dnsapi.lib;Advapi32.lib</AdditionalDependencies>
       <AdditionalLibraryDirectories>$(OPENSSL_HOME)/lib;$(LZO_HOME)/lib;$(PKCS11H_HOME)/lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
       <SubSystem>Console</SubSystem>
       <CETCompat>true</CETCompat>
@@ -237,7 +237,7 @@
     </ClCompile>
     <ResourceCompile />
     <Link>
-      <AdditionalDependencies>Ncrypt.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;Advapi32.lib</AdditionalDependencies>
+      <AdditionalDependencies>Ncrypt.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;dnsapi.lib;Advapi32.lib</AdditionalDependencies>
       <AdditionalLibraryDirectories>$(OPENSSL_HOME)/lib;$(LZO_HOME)/lib;$(PKCS11H_HOME)/lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
       <SubSystem>Console</SubSystem>
       <CETCompat>true</CETCompat>
@@ -256,7 +256,7 @@
     </ClCompile>
     <ResourceCompile />
     <Link>
-      <AdditionalDependencies>Ncrypt.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;Advapi32.lib</AdditionalDependencies>
+      <AdditionalDependencies>Ncrypt.lib;gdi32.lib;ws2_32.lib;wininet.lib;crypt32.lib;iphlpapi.lib;winmm.lib;Fwpuclnt.lib;Rpcrt4.lib;setupapi.lib;dnsapi.lib;Advapi32.lib</AdditionalDependencies>
       <AdditionalLibraryDirectories>$(OPENSSL_HOME)/lib;$(LZO_HOME)/lib;$(PKCS11H_HOME)/lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
       <SubSystem>Console</SubSystem>
     </Link>
src/openvpn/options.c +225 -24

389 lines not on this page · raw message

src/openvpn/options.h +4 -0
index fec1eace..10b59e13 100644
@@ -105,6 +105,7 @@ struct connection_entry
     const char *remote_port;
     const char *local;
     const char *remote;
+    bool remote_srv;
     bool remote_float;
     bool bind_defined;
     bool bind_ipv6_only;
@@ -177,6 +178,7 @@ struct remote_entry
     const char *remote_port;
     int proto;
     sa_family_t af;
+    bool remote_srv;
 };
 
 #define CONNECTION_LIST_SIZE 64
@@ -836,6 +838,8 @@ void options_postprocess(struct options *options, struct env_set *es);
 
 bool options_postprocess_pull(struct options *o, struct env_set *es);
 
+bool options_mutate_ce_servinfo(struct options *o, struct servinfo *si);
+
 void pre_connect_restore(struct options *o, struct gc_arena *gc);
 
 bool apply_push_options(struct options *options,
src/openvpn/socket.c +864 -4

934 lines not on this page · raw message

src/openvpn/socket.h +65 -2

135 lines not on this page · raw message

src/openvpn/syshead.h +5 -0
index 5a673a7b..484c4474 100644
@@ -38,6 +38,7 @@
 
 #ifdef _WIN32
 #include <windows.h>
+#include <windns.h>
 #include <winsock2.h>
 #include <tlhelp32.h>
 #define sleep(x) Sleep((x)*1000)
@@ -143,6 +144,10 @@
 #include <netinet/in.h>
 #endif
 
+#ifdef HAVE_ARPA_NAMESER_H
+#include <arpa/nameser.h>
+#endif
+
 #ifdef HAVE_RESOLV_H
 #include <resolv.h>
 #endif
Signature · 1 line
2.17.1
#29 lore raw
In reply to Vladislav Grishenko

On Thu, Dec 29, 2022 at 12:27:46PM +0500, Vladislav Grishenko wrote:
[...]

Quoted 9 lines

v15:
rebase to master (Dec 2022)
add optional port argument to --remote and --remote-srv usage message fix --proto option coexisting with --remote-srv
fix --nobind option coexisting with --remote-srv
fix options postprocess mutation lost in v13/v14
recover --mtu-test handling with --remote-srv
use explicit srv resolve stub for openbsd for the future fix comments

I don't really have time today to review this completely, but a quick test seems to confirm the issue I identified last time is indeed fixed. Tested by replacing --remote in t_client tests 1 and 2 with --remote-srv lichtenheld.net

SRV setup for lichtenheld.net:
_openvpn._tcp 60 IN SRV 0 0 51194 conn-test-server.openvpn.org.
_openvpn._udp 60 IN SRV 0 0 51194 conn-test-server.openvpn.org.

Regards,

Signature · 1 line
  Frank Lichtenheld
#30 lore raw
Quoted 12 lines · Frank Lichtenheld

On Thu, Dec 29, 2022 at 12:27:46PM +0500, Vladislav Grishenko wrote:
[...]

Quoted 9 lines

v15:
rebase to master (Dec 2022)
add optional port argument to --remote and --remote-srv usage message fix --proto option coexisting with --remote-srv
fix --nobind option coexisting with --remote-srv
fix options postprocess mutation lost in v13/v14
recover --mtu-test handling with --remote-srv
use explicit srv resolve stub for openbsd for the future fix comments

Quoted 7 lines

I don't really have time today to review this completely, but a quick test seems to confirm the issue I identified last time is indeed fixed. Tested by replacing --remote in t_client tests 1 and 2 with --remote-srv lichtenheld.net

SRV setup for lichtenheld.net:
_openvpn._tcp 60 IN SRV 0 0 51194 conn-test-server.openvpn.org.
_openvpn._udp 60 IN SRV 0 0 51194 conn-test-server.openvpn.org.

Also put this through the buildbot tests. No build/test failures.

Regards,

Signature · 1 line
  Frank Lichtenheld
#31 lore raw
In reply to Vladislav Grishenko

Hi,

Quoted 11 lines · Vladislav Grishenko

client will move on to the next connection entry.

v15:
rebase to master (Dec 2022)
add optional port argument to --remote and --remote-srv usage message fix --proto option coexisting with --remote-srv
fix --nobind option coexisting with --remote-srv
fix options postprocess mutation lost in v13/v14
recover --mtu-test handling with --remote-srv
use explicit srv resolve stub for openbsd for the future fix comments

Getting close... but, alas, we need another rebase - the signal handling fixes from Selva cause conflicts. Can you do a v16, please?

Also, please have a very close look at the code now - it looks like the previous rebase is now creating quite a bit of (undesired!) code duplication. For example, this new hunk:

+static bool
+options_postprocess_verify_ce_proto(const struct options *options,
+ const struct connection_entry *ce)
+{
+ int msglevel = M_WARN|M_NOPREFIX|M_OPTERR;
+
+ /*
+ * Sanity check on --local, --remote, and --ifconfig
+ */
+
+ if (proto_is_net(ce->proto)
+ && string_defined_equal(ce->local, ce->remote)
+ && string_defined_equal(ce->local_port, ce->remote_port))
+ {
+ msg(msglevel, "--remote and --local addresses are the same");
+ return false;
+ }
+
+ if (string_defined_equal(ce->remote, options->ifconfig_local)
+ || string_defined_equal(ce->remote, options->ifconfig_remote_netmask))
+ {
+ msg(msglevel,
+ "--local and --remote addresses must be distinct from --ifconfig "
+ "addresses");
+ return false;
+ }

... these checks are existing today, in options_postprocess_verify_ce(), but your patch is not *moving* them to the new function, but *duplicating* them. This can happen if "git --rebase" gets confused by too many unrelated changes, but is not the desired end state.

gert

Signature · 6 lines
"If was one thing all people took for granted, was conviction that if you 
 feed honest figures into a computer, honest figures come out. Never doubted 
 it myself till I met a computer with a sense of humor."
                             Robert A. Heinlein, The Moon is a Harsh Mistress

Gert Doering - Munich, Germany                             [email protected]...
#32 lore raw

Hi, sure, will do.
Yes, I’ve noticed undesired code dup in v14 and have fixed everything found in v15 rebase, same will be rechecked in v16 of course.
Thanks!

Ср, 11 янв. 2023 г. в 01:05, Gert Doering <[email protected]...>:

Quoted 73 lines

Hi,

Quoted 11 lines · Vladislav Grishenko

client will move on to the next connection entry.

v15:
rebase to master (Dec 2022)
add optional port argument to --remote and --remote-srv usage message fix --proto option coexisting with --remote-srv
fix --nobind option coexisting with --remote-srv
fix options postprocess mutation lost in v13/v14
recover --mtu-test handling with --remote-srv
use explicit srv resolve stub for openbsd for the future fix comments

Getting close... but, alas, we need another rebase - the signal handling fixes from Selva cause conflicts. Can you do a v16, please?

Also, please have a very close look at the code now - it looks like the previous rebase is now creating quite a bit of (undesired!) code duplication. For example, this new hunk:

src/openvpn/options.c +20 -0
+static bool
+options_postprocess_verify_ce_proto(const struct options *options,
+                                    const struct connection_entry *ce)
+{
+    int msglevel = M_WARN|M_NOPREFIX|M_OPTERR;
+
+    /*
+     * Sanity check on --local, --remote, and --ifconfig
+     */
+
+    if (proto_is_net(ce->proto)
+        && string_defined_equal(ce->local, ce->remote)
+        && string_defined_equal(ce->local_port, ce->remote_port))
+    {
+        msg(msglevel, "--remote and --local addresses are the same");
+        return false;
+    }
+
+    if (string_defined_equal(ce->remote, options->ifconfig_local)
+        || string_defined_equal(ce->remote,

options->ifconfig_remote_netmask))

src/openvpn/options.c +6 -1
+    {
+        msg(msglevel,
+            "--local and --remote addresses must be distinct from
--ifconfig "
+            "addresses");
+        return false;
+    }

... these checks are existing today, in options_postprocess_verify_ce(), but your patch is not *moving* them to the new function, but *duplicating* them. This can happen if "git --rebase" gets confused by too many unrelated changes, but is not the desired end state.

gert
--
"If was one thing all people took for granted, was conviction that if you
feed honest figures into a computer, honest figures come out. Never
doubted
it myself till I met a computer with a sense of humor."
Robert A. Heinlein, The Moon is a Harsh
Mistress

Gert Doering - Munich, Germany
[email protected]...
_______________________________________________
Openvpn-devel mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/openvpn-devel

Signature · 1 line
Best regards, Vladislav Grishenko
#33 lore raw

Hi,

Quoted 3 lines · Vladislav Grishenko

Hi, sure, will do.
Yes, I???ve noticed undesired code dup in v14 and have fixed everything found in v15 rebase, same will be rechecked in v16 of course.

Did you find time to have a look into this?

2.6.0 is out, but since there is demand for the SRV patch, we've agreed to do an exceptional feature merge for 2.6.1 for SRV and dynamic tls-crypt
- but that means "we need to have a fully reviewed v16"...

gert

Signature · 6 lines
"If was one thing all people took for granted, was conviction that if you 
 feed honest figures into a computer, honest figures come out. Never doubted 
 it myself till I met a computer with a sense of humor."
                             Robert A. Heinlein, The Moon is a Harsh Mistress

Gert Doering - Munich, Germany                             [email protected]...
#34 lore raw
In reply to Gert Doering

Hi,

Quoted 5 lines · Gert Doering

- use getrrsetbyname(), and add that via "compat" source if a target platform does not have it - this is what OpenSSH does

- add #ifdefs to disable --srv functionality on OpenBSD (which is not really where we want to go)

I think these two options are the most realistic to move forward here.

getrrsetbyname() looks like a good API, and taking the compat functions from OpenSSH (I think we can, license-wise) would bring it to the other platforms. But that's more work.

"Just pretending that there are no SRV records" would be the quick and dirty approach for OpenBSD otherwise, #ifdef'ing out the whole problematic function.

In any case, since I've been working on the code now, someone else needs to volunteer to review the v13/v14 patches.

gert

Signature · 6 lines
"If was one thing all people took for granted, was conviction that if you 
 feed honest figures into a computer, honest figures come out. Never doubted 
 it myself till I met a computer with a sense of humor."
                             Robert A. Heinlein, The Moon is a Harsh Mistress

Gert Doering - Munich, Germany                             [email protected]...
#35 lore raw
In reply to Gert Doering

Hi, Gert

Indeed, early platform-related code was tested on FreeBSD w/o EAI_NODATA return results used.
Since that changes were not related to low-level resolving code, and therefore was tested on Linux with _GNU and Windows only. Unfortunately at some time point usage of EAI_NODATA return result was introduced and I've missed FreeBSD testing thought it was still not necessary, sorry.

Please refer v10 version sent and additional separate v9->v10 patch to see exact changes.
It address all the places with EAI_NODATA and keeps windows logic consistent as well.

Quoted 1 line

I have no idea *why* FreeBSD considers this "obsoleted", or what this

define is used for - have not yet investigated in any way

https://lists.freebsd.org/pipermail/freebsd-ports/2003-October/005757.html

Quoted 1 line

It was depricated in RFC3493 (aka RFC2553bis). Now, getaddrinfo(3)

returns EAI_NONAME instead of EAI_NODATA.

--
Best Regards, Vladislav Grishenko

Quoted 11 lines

-----Original Message-----
From: Gert Doering <[email protected]...>
Sent: Friday, December 4, 2020 7:02 PM
To: Vladislav Grishenko <[email protected]...>
Cc: [email protected]
Subject: Re: [Openvpn-devel] [PATCH v9] Add DNS SRV remote host discovery support

Hi,

On Mon, Nov 16, 2020 at 03:08:57AM +0500, Vladislav Grishenko wrote:

Quoted 8 lines
Quoted 6 lines

DNS SRV remote host discovery allows to have multiple OpenVPN servers for a single domain w/o explicit profile enumeration, to move services from host to host with little fuss, and to designate hosts as primary servers for a service and others as backups.
Feature has been asked several times already, should be useful in case of substantial number of clients & servers deployed.

So, Arne has ACKed it, and I went work on it today. One problem showed up

on

Quoted 1 line

FreeBSD - the code uses EAI_NODATA, which is found in <netdb.h> on

FreeBSD,

Quoted 8 lines

but with this comment:

#if 0
/* obsoleted */
#define EAI_NODATA 7 /* no address associated with hostname */
#endif

I'm not sure what to make out of this, but as it stands, the patchset does

not

Quoted 7 lines

work.

If I just add

  #define EAI_NODATA 7

to socket.c, it compiles and passes my regular client tests (no SRV tests

yet), but

Quoted 3 lines

I do not think this is the correct solution.

(I have no idea *why* FreeBSD considers this "obsoleted", or what this

define is

Quoted 4 lines

used for - have not yet investigated in any way)

If you need to test on FreeBSD, openvpn-vagrant has boxes that get

installed

Quoted 1 line

with all prerequisites (or I can give you access to one of my

buildslaves).

Quoted 5 lines

gert

--
"If was one thing all people took for granted, was conviction that if you

feed

Quoted 3 lines

honest figures into a computer, honest figures come out. Never doubted it myself till I met a computer with a sense of humor."
Robert A. Heinlein, The Moon is a Harsh

Mistress

Quoted 2 lines

Gert Doering - Munich, Germany

[email protected]...

#36 lore raw

Re: [Openvpn-devel] [PATCH v6 1/2] Selectively reformat too long lines

In reply to Vladislav Grishenko

Hi,

src/openvpn/socket.c static const struct proto_names proto_names[] = { · line 3182

Quoted 6 lines · Vladislav Grishenko
src/openvpn/socket.c +1 -1
@@ -3170,7 +3179,7 @@ static const struct proto_names proto_names[] = {
     {"udp6","UDPv6", AF_INET6, PROTO_UDP},
     {"tcp6-server","TCPv6_SERVER", AF_INET6, PROTO_TCP_SERVER},
     {"tcp6-client","TCPv6_CLIENT", AF_INET6, PROTO_TCP_CLIENT},
-    {"tcp6","TCPv6", AF_INET6, PROTO_TCP},
+    {"tcp6",       "TCPv6", AF_INET6, PROTO_TCP},

What are you actually fixing here? Adding a tab?
I feel there should be a space after each ',', but that is probably out of the scope of this patch?

Signature · 1 line
Antonio Quartulli
#37 lore raw

PATCH v7 1/1 Selectively reformat too long lines

Per https://community.openvpn.net/openvpn/wiki/CodeStyle the maximum line length is 80 characters. This patch allows to split upcoming changes into CodeStyle-conformant (w/o real code change) and more feature-specific. Upcoming changes adds new PROTO_AUTO, so existing proto_names array is reformatted as well.

v7: prefer line breaks before long string parameters
reformat proto_names array

---
 src/openvpn/init.c    |  3 +-
 src/openvpn/options.c | 80 +++++++++++++++++++++++++++++--------------
 src/openvpn/socket.c  | 52 +++++++++++++++++-----------
 3 files changed, 89 insertions(+), 46 deletions(-)
src/openvpn/init.c +2 -1
index d1ad5c8f..31ecadcc 100644
@@ -3646,7 +3646,8 @@ do_close_link_socket(struct context *c)
           && ( (c->options.persist_remote_ip)
                ||
                ( c->sig->source != SIG_SOURCE_HARD
-                 && ((c->c1.link_socket_addr.current_remote && c->c1.link_socket_addr.current_remote->ai_next)
+                 && ((c->c1.link_socket_addr.current_remote
+                      && c->c1.link_socket_addr.current_remote->ai_next)
                      || c->options.no_advance))
                )))
     {
src/openvpn/options.c +55 -25

190 lines not on this page · raw message

src/openvpn/socket.c +32 -20

113 lines not on this page · raw message

Signature · 1 line
2.17.1
Acked-by on v7 1/1
#38 lore raw

Re: [Openvpn-devel] [PATCH v7] Selectively reformat too long lines

Am 24.09.20 um 11:10 schrieb Vladislav Grishenko:

Quoted 9 lines

Per https://community.openvpn.net/openvpn/wiki/CodeStyle the maximum line length is 80 characters. This patch allows to split upcoming changes into CodeStyle-conformant (w/o real code change) and more feature-specific. Upcoming changes adds new PROTO_AUTO, so existing proto_names array is reformatted as well.

v7: prefer line breaks before long string parameters
reformat proto_names array

Also Antonio has no further concerns.

#39 lore raw

[Openvpn-devel] [PATCH applied] Re: Selectively reformat too long lines

In reply to Vladislav Grishenko

Your patch has been applied to the master and release/2.5 branch.

I am not particularily happy about merging this sort of "cleanup" patch so late before 2.5 release - *but* I have very carefully checked that it's really all just re-wrapping long function calls, or long text strings, so the danger to 2.5 stability is minimal. OTOH, not merging this to release/2.5 means more work for all future bugfixes that happen to be close enough to one of these changes so the "diff context" is changed. So, in it goes.

As a side note - but too late to stop it, as Arne and Antonio have spoken - I do not think this sort of change is actually making the code *more* readable:

- msg(M_WARN, "DEPRECATED OPTION: --inetd mode is deprecated "
- "and will be removed in OpenVPN 2.6");
+ msg(M_WARN,
+ "DEPRECATED OPTION: --inetd mode is deprecated and will be removed "
+ "in OpenVPN 2.6");

it's basically making 3 lines out of two, while the text still needs to be wrapped. So instead of "two lengthy" lines, we now have "one very short line, one very long line, and one short line again" - I find that *less* readable, and since the old code conformed to the 80 character limit, it's commit noise which makes "git blame" harder to follow, with questionable benefit.

We need to cover this in the style guide, to make clear which variant is preferred (if the text fits into one line if putting it onto its own line, this is a different story).

commit a5409c0d34bf02cacdee61d61ba7b3e1f72e132f (master) commit c055e28654f340c617a2b0eece7fa28c79c1a9fc (release/2.5)

Author: Vladislav Grishenko
Date:   Thu Sep 24 14:10:04 2020 +0500
     Selectively reformat too long lines

     Signed-off-by: Vladislav Grishenko <[email protected]...>
     Acked-by: Arne Schwabe <[email protected]...>
     Message-Id: <[email protected]...>
     URL: https://www.mail-archive.com/[email protected]/msg21083.html
     Signed-off-by: Gert Doering <[email protected]...>

--
kind regards,

Gert Doering

#40 lore raw

Re: [Openvpn-devel] [PATCH applied] Re: Selectively reformat too long lines

Gert, thank you

Quoted 1 line

We need to cover this in the style guide, to make clear which variant is

preferred

Quoted 1 line

(if the text fits into one line if putting it onto its own line, this is a

different

Quoted 1 line

story).

Indeed, it needs to be written down, including what to do with existing code on changes near around.
In this case I had to follow Antonio suggestion about the breaks, previous version w/o them hasn't pass review.
As for blame, most of git ui tools allows to traverse blame in depth, incl. tig - console git shell, anyway any refactoring brings the same issue.

--
Best Regards, Vladislav Grishenko

Quoted 11 lines

-----Original Message-----
From: Gert Doering <[email protected]...>
Sent: Saturday, October 3, 2020 12:33 AM
To: Vladislav Grishenko <[email protected]...>
Cc: [email protected]
Subject: [PATCH applied] Re: Selectively reformat too long lines

Your patch has been applied to the master and release/2.5 branch.

I am not particularily happy about merging this sort of "cleanup" patch so late before 2.5 release - *but* I have very carefully checked

that it's

Quoted 1 line

really all just re-wrapping long function calls, or long text strings, so

the danger

Quoted 1 line

to 2.5 stability is minimal. OTOH, not merging this to release/2.5 means

more

Quoted 1 line

work for all future bugfixes that happen to be close enough to one of

these

Quoted 3 lines

changes so the "diff context" is changed. So, in it goes.

As a side note - but too late to stop it, as Arne and Antonio have spoken

- I do

src/openvpn/options.c options_postprocess_verify_ce(const struct options *options, const struct connec

Quoted 6 lines

not think this sort of change is actually making the code *more* readable:

src/openvpn/options.c +2 -2
-        msg(M_WARN, "DEPRECATED OPTION: --inetd mode is deprecated "
-            "and will be removed in OpenVPN 2.6");
+        msg(M_WARN,
+            "DEPRECATED OPTION: --inetd mode is deprecated and will be

removed

Quoted 4 lines

"
+ "in OpenVPN 2.6");

it's basically making 3 lines out of two, while the text still needs to be

wrapped.

Quoted 1 line

So instead of "two lengthy" lines, we now have "one very short line, one

very

Quoted 1 line

long line, and one short line again" - I find that *less* readable, and

since the old

Quoted 1 line

code conformed to the 80 character limit, it's commit noise which makes

"git

Quoted 3 lines

blame" harder to follow, with questionable benefit.

We need to cover this in the style guide, to make clear which variant is

preferred

Quoted 1 line

(if the text fits into one line if putting it onto its own line, this is a

different

Quoted 22 lines

story).

commit a5409c0d34bf02cacdee61d61ba7b3e1f72e132f (master) commit c055e28654f340c617a2b0eece7fa28c79c1a9fc (release/2.5)

Author: Vladislav Grishenko
Date:   Thu Sep 24 14:10:04 2020 +0500
     Selectively reformat too long lines

     Signed-off-by: Vladislav Grishenko <[email protected]...>
     Acked-by: Arne Schwabe <[email protected]...>
     Message-Id: <[email protected]...>
     URL: https://www.mail-archive.com/openvpn-
[email protected]/msg21083.html
     Signed-off-by: Gert Doering <[email protected]...>

--
kind regards,

Gert Doering

#41 lore raw

Re: [Openvpn-devel] [PATCH v6 1/2] Selectively reformat too long lines

In reply to Antonio Quartulli

Hi Antonio,

Here's I have aligned the last line to add next new proto, already aligned.

Yes, you’re right “UDPv6” also needs to be aligned, and space needs to be added for all lines, thank you.

V7 is sent

--

Best Regards, Vladislav Grishenko

Quoted 47 lines

-----Original Message-----

From: Antonio Quartulli <[email protected]...>

Sent: Thursday, September 24, 2020 1:12 PM

To: Vladislav Grishenko <[email protected]...>; openvpn-

[email protected]

Subject: Re: [Openvpn-devel] [PATCH v6 1/2] Selectively reformat too long lines

Hi,

src/openvpn/socket.c static const struct proto_names proto_names[] = {

Quoted 11 lines · Vladislav Grishenko
src/openvpn/socket.c +1 -1
@@ -3170,7 +3179,7 @@ static const struct proto_names proto_names[] = {
 
     {"udp6","UDPv6", AF_INET6, PROTO_UDP},
 
     {"tcp6-server","TCPv6_SERVER", AF_INET6, PROTO_TCP_SERVER},
 
     {"tcp6-client","TCPv6_CLIENT", AF_INET6, PROTO_TCP_CLIENT},
 
-    {"tcp6","TCPv6", AF_INET6, PROTO_TCP},
 
+    {"tcp6",       "TCPv6", AF_INET6, PROTO_TCP},

What are you actually fixing here? Adding a tab?

I feel there should be a space after each ',', but that is probably out of the scope

of this patch?

--

Antonio Quartulli