From: "flichtenheld (Code Review)" Date: Mon, 4 Aug 2025 11:18:31 +0000 In-Reply-To: References: Reply-To: frank@...2641..., arne-openvpn@...1227..., openvpn-devel@lists.sourceforge.net, antonio@...2726..., gert@...1296... Message-ID: <49ee44bf7c2eed06c79fd5c0d51ef49d6981b505-EmailReplacePatchSet-HTML@...2715...> MIME-Version: 1.0 Content-Transfer-Encoding: 8bit Content-Disposition: inline Content-Type: multipart/alternative; boundary="aFNSkfgjrpU="; charset=UTF-8 Subject: [Openvpn-devel] [XL] Change in openvpn[master]: Reformat the whole project with clang-format List-Id: List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , To: plaisthos Cc: openvpn-devel --aFNSkfgjrpU= Content-Type: text/plain; charset="UTF-8" Content-Transfer-Encoding: quoted-printable Attention is currently required from: cron2, ordex, plaisthos. Hello plaisthos, I'd like you to reexamine a change. Please visit http://gerrit.openvpn.net/c/openvpn/+/791?usp=3Demail to look at the new patch set (#23). Change subject: Reformat the whole project with clang-format ...................................................................... Reformat the whole project with clang-format Done with pre-commit run -a, so the version defined in pre-commit config is used. This also changes the Github workflow so that there is no commit that fails GHA. Change-Id: I2566ad493629e1f5fdfa6f6483b8973463404e3e Signed-off-by: Frank Lichtenheld --- M .github/workflows/build.yaml M include/openvpn-msg.h M sample/sample-plugins/client-connect/sample-client-connect.c M sample/sample-plugins/defer/multi-auth.c M sample/sample-plugins/keying-material-exporter-demo/keyingmaterialexporte= r.c M sample/sample-plugins/log/log.c M sample/sample-plugins/log/log_v3.c M sample/sample-plugins/simple/base64.c M sample/sample-plugins/simple/simple.c M src/compat/compat-basename.c M src/compat/compat-dirname.c M src/compat/compat-gettimeofday.c M src/openvpn/argv.c M src/openvpn/argv.h M src/openvpn/auth_token.c M src/openvpn/auth_token.h M src/openvpn/base64.c M src/openvpn/base64.h M src/openvpn/basic.h M src/openvpn/buffer.c M src/openvpn/buffer.h M src/openvpn/circ_list.h M src/openvpn/clinat.c M src/openvpn/clinat.h M src/openvpn/common.h M src/openvpn/comp-lz4.c M src/openvpn/comp.c M src/openvpn/comp.h M src/openvpn/compstub.c M src/openvpn/console.c M src/openvpn/console.h M src/openvpn/console_builtin.c M src/openvpn/console_systemd.c M src/openvpn/crypto.c M src/openvpn/crypto.h M src/openvpn/crypto_backend.h M src/openvpn/crypto_epoch.c M src/openvpn/crypto_epoch.h M src/openvpn/crypto_mbedtls.c M src/openvpn/crypto_mbedtls.h M src/openvpn/crypto_openssl.c M src/openvpn/crypto_openssl.h M src/openvpn/cryptoapi.c M src/openvpn/dco.c M src/openvpn/dco.h M src/openvpn/dco_freebsd.c M src/openvpn/dco_freebsd.h M src/openvpn/dco_internal.h M src/openvpn/dco_linux.c M src/openvpn/dco_linux.h M src/openvpn/dco_win.c M src/openvpn/dco_win.h M src/openvpn/dhcp.c M src/openvpn/dhcp.h M src/openvpn/dns.c M src/openvpn/dns.h M src/openvpn/env_set.c M src/openvpn/env_set.h M src/openvpn/errlevel.h M src/openvpn/error.c M src/openvpn/error.h M src/openvpn/event.c M src/openvpn/event.h M src/openvpn/fdmisc.c M src/openvpn/fdmisc.h M src/openvpn/forward.c M src/openvpn/forward.h M src/openvpn/fragment.c M src/openvpn/fragment.h M src/openvpn/gremlin.c M src/openvpn/gremlin.h M src/openvpn/helper.c M src/openvpn/httpdigest.c M src/openvpn/httpdigest.h M src/openvpn/init.c M src/openvpn/init.h M src/openvpn/integer.h M src/openvpn/interval.c M src/openvpn/interval.h M src/openvpn/list.c M src/openvpn/list.h M src/openvpn/lladdr.c M src/openvpn/lzo.c M src/openvpn/lzo.h M src/openvpn/manage.c M src/openvpn/manage.h M src/openvpn/mbedtls_compat.h M src/openvpn/mbuf.c M src/openvpn/mbuf.h M src/openvpn/memdbg.h M src/openvpn/misc.c M src/openvpn/misc.h M src/openvpn/mroute.c M src/openvpn/mroute.h M src/openvpn/mss.c M src/openvpn/mss.h M src/openvpn/mstats.c M src/openvpn/mstats.h M src/openvpn/mtcp.c M src/openvpn/mtcp.h M src/openvpn/mtu.c M src/openvpn/mtu.h M src/openvpn/mudp.c M src/openvpn/multi.c M src/openvpn/multi.h M src/openvpn/multi_io.c M src/openvpn/networking.h M src/openvpn/networking_freebsd.c M src/openvpn/networking_iproute2.c M src/openvpn/networking_sitnl.c M src/openvpn/ntlm.c M src/openvpn/occ.c M src/openvpn/occ.h M src/openvpn/openssl_compat.h M src/openvpn/openvpn.c M src/openvpn/openvpn.h M src/openvpn/options.c M src/openvpn/options.h M src/openvpn/options_util.c M src/openvpn/options_util.h M src/openvpn/otime.c M src/openvpn/otime.h M src/openvpn/ovpn_dco_freebsd.h M src/openvpn/packet_id.c M src/openvpn/packet_id.h M src/openvpn/perf.c M src/openvpn/perf.h M src/openvpn/ping.c M src/openvpn/ping.h M src/openvpn/pkcs11.c M src/openvpn/pkcs11.h M src/openvpn/pkcs11_backend.h M src/openvpn/pkcs11_mbedtls.c M src/openvpn/pkcs11_openssl.c M src/openvpn/platform.c M src/openvpn/platform.h M src/openvpn/plugin.c M src/openvpn/plugin.h M src/openvpn/pool.c M src/openvpn/pool.h M src/openvpn/proto.c M src/openvpn/proto.h M src/openvpn/proxy.c M src/openvpn/proxy.h M src/openvpn/ps.c M src/openvpn/ps.h M src/openvpn/push.c M src/openvpn/push.h M src/openvpn/push_util.c M src/openvpn/pushlist.h M src/openvpn/reflect_filter.c M src/openvpn/reflect_filter.h M src/openvpn/reliable.c M src/openvpn/reliable.h A src/openvpn/ring_buffer.h M src/openvpn/route.c M src/openvpn/route.h M src/openvpn/run_command.c M src/openvpn/run_command.h M src/openvpn/schedule.c M src/openvpn/schedule.h M src/openvpn/session_id.h M src/openvpn/shaper.c M src/openvpn/shaper.h M src/openvpn/sig.c M src/openvpn/sig.h M src/openvpn/socket.c M src/openvpn/socket.h M src/openvpn/socks.c M src/openvpn/socks.h M src/openvpn/ssl.c M src/openvpn/ssl.h M src/openvpn/ssl_backend.h M src/openvpn/ssl_common.h M src/openvpn/ssl_mbedtls.c M src/openvpn/ssl_mbedtls.h M src/openvpn/ssl_ncp.c M src/openvpn/ssl_ncp.h M src/openvpn/ssl_openssl.c M src/openvpn/ssl_openssl.h M src/openvpn/ssl_pkt.c M src/openvpn/ssl_pkt.h M src/openvpn/ssl_util.c M src/openvpn/ssl_util.h M src/openvpn/ssl_verify.c M src/openvpn/ssl_verify.h M src/openvpn/ssl_verify_backend.h M src/openvpn/ssl_verify_mbedtls.c M src/openvpn/ssl_verify_mbedtls.h M src/openvpn/ssl_verify_openssl.c M src/openvpn/status.c M src/openvpn/status.h M src/openvpn/syshead.h M src/openvpn/tls_crypt.c M src/openvpn/tls_crypt.h M src/openvpn/tun.c M src/openvpn/tun.h M src/openvpn/tun_afunix.c M src/openvpn/tun_afunix.h M src/openvpn/vlan.c M src/openvpn/vlan.h M src/openvpn/wfp_block.c M src/openvpn/wfp_block.h M src/openvpn/win32-util.c M src/openvpn/win32.c M src/openvpn/win32.h M src/openvpn/xkey_common.h M src/openvpn/xkey_helper.c M src/openvpn/xkey_provider.c M src/openvpnmsica/dllmain.c M src/openvpnmsica/msica_arg.c M src/openvpnmsica/msica_arg.h M src/openvpnmsica/msiex.c M src/openvpnmsica/msiex.h M src/openvpnmsica/openvpnmsica.c M src/openvpnmsica/openvpnmsica.h M src/openvpnserv/common.c M src/openvpnserv/interactive.c M src/openvpnserv/service.c M src/openvpnserv/service.h M src/openvpnserv/validate.c M src/openvpnserv/validate.h M src/plugins/auth-pam/auth-pam.c M src/plugins/auth-pam/pamdl.c M src/plugins/auth-pam/utils.c M src/plugins/auth-pam/utils.h M src/plugins/down-root/down-root.c M src/tapctl/basic.h M src/tapctl/error.h M src/tapctl/main.c M src/tapctl/tap.c M src/tapctl/tap.h M tests/ntlm_support.c M tests/unit_tests/example_test/test.c M tests/unit_tests/example_test/test2.c M tests/unit_tests/openvpn/cert_data.h M tests/unit_tests/openvpn/mock_management.c M tests/unit_tests/openvpn/mock_msg.c M tests/unit_tests/openvpn/mock_msg.h M tests/unit_tests/openvpn/mock_ssl_dependencies.c M tests/unit_tests/openvpn/pkey_test_utils.c M tests/unit_tests/openvpn/test_argv.c M tests/unit_tests/openvpn/test_auth_token.c M tests/unit_tests/openvpn/test_buffer.c M tests/unit_tests/openvpn/test_crypto.c M tests/unit_tests/openvpn/test_cryptoapi.c M tests/unit_tests/openvpn/test_misc.c M tests/unit_tests/openvpn/test_ncp.c M tests/unit_tests/openvpn/test_networking.c M tests/unit_tests/openvpn/test_packet_id.c M tests/unit_tests/openvpn/test_pkcs11.c M tests/unit_tests/openvpn/test_pkt.c M tests/unit_tests/openvpn/test_provider.c M tests/unit_tests/openvpn/test_push_update_msg.c M tests/unit_tests/openvpn/test_ssl.c M tests/unit_tests/openvpn/test_tls_crypt.c M tests/unit_tests/openvpn/test_user_pass.c M tests/unit_tests/plugins/auth-pam/test_search_and_replace.c 258 files changed, 12,008 insertions(+), 15,234 deletions(-) git pull ssh://gerrit.openvpn.net:29418/openvpn refs/changes/91/791/23 diff --git a/.github/workflows/build.yaml b/.github/workflows/build.yaml index bd5895b..ba7f64b 100644 --- a/.github/workflows/build.yaml +++ b/.github/workflows/build.yaml @@ -5,35 +5,26 @@ pull_request: jobs: - checkuncrustify: - name: "Check code style with Uncrustify" - # Ubuntu 22.04 has uncrustify 0.72_f - runs-on: ubuntu-22.04 + clang-format: + name: Check code style with clang-format + runs-on: ubuntu-24.04 steps: - name: Install dependencies - run: sudo apt update && sudo apt install -y uncrustify + run: | + sudo apt update && sudo apt install -y python3-pip + pip3 install pre-commit - name: Checkout OpenVPN uses: actions/checkout@...2844... # v4.2.2 - with: - path: openvpn - - name: Show uncrustify version - run: uncrustify --version - - name: Run uncrustify - run: ./dev-tools/reformat-all.sh - working-directory: openvpn + - name: Run clang-format + run: pre-commit run -a --show-diff-on-failure || true - name: Check for changes - run: git diff --output=3Duncrustify-changes.patch - working-directory: openvpn - - name: Show changes on standard output - run: git diff - working-directory: openvpn + run: git diff --output=3Dformat-changes.patch - uses: actions/upload-artifact@...2868... # v4.6.2 with: - name: uncrustify-changes.patch - path: 'openvpn/uncrustify-changes.patch' + name: format-changes.patch + path: format-changes.patch - name: Set job status - run: test ! -s uncrustify-changes.patch - working-directory: openvpn + run: test ! -s format-changes.patch android: strategy: diff --git a/include/openvpn-msg.h b/include/openvpn-msg.h index 106a274..a692137 100644 --- a/include/openvpn-msg.h +++ b/include/openvpn-msg.h @@ -26,7 +26,8 @@ #include #include -typedef enum { +typedef enum +{ msg_acknowledgement, msg_add_address, msg_del_address, @@ -50,28 +51,33 @@ msg_create_adapter } message_type_t; -typedef struct { +typedef struct +{ message_type_t type; size_t size; int message_id; } message_header_t; -typedef union { +typedef union +{ struct in_addr ipv4; struct in6_addr ipv6; } inet_address_t; -typedef struct { +typedef struct +{ int index; char name[256]; } interface_t; -typedef enum { - wfp_block_local =3D 1<<0, - wfp_block_dns =3D 1<<1 +typedef enum +{ + wfp_block_local =3D 1 << 0, + wfp_block_dns =3D 1 << 1 } wfp_block_flags_t; -typedef struct { +typedef struct +{ message_header_t header; short family; inet_address_t address; @@ -79,7 +85,8 @@ interface_t iface; } address_message_t; -typedef struct { +typedef struct +{ message_header_t header; short family; inet_address_t prefix; @@ -89,7 +96,8 @@ int metric; } route_message_t; -typedef struct { +typedef struct +{ message_header_t header; interface_t iface; char domains[512]; @@ -99,14 +107,16 @@ } dns_cfg_message_t; -typedef enum { +typedef enum +{ nrpt_dnssec } nrpt_flags_t; -#define NRPT_ADDR_NUM 8 /* Max. number of addresses */ +#define NRPT_ADDR_NUM 8 /* Max. number of addresses */ #define NRPT_ADDR_SIZE 48 /* Max. address strlen + some */ typedef char nrpt_address_t[NRPT_ADDR_SIZE]; -typedef struct { +typedef struct +{ message_header_t header; interface_t iface; nrpt_address_t addresses[NRPT_ADDR_NUM]; @@ -115,14 +125,16 @@ nrpt_flags_t flags; } nrpt_dns_cfg_message_t; -typedef struct { +typedef struct +{ message_header_t header; interface_t iface; int addr_len; inet_address_t addr[4]; /* support up to 4 dns addresses */ } wins_cfg_message_t; -typedef struct { +typedef struct +{ message_header_t header; interface_t iface; int disable_nbt; @@ -134,41 +146,48 @@ /* TODO: NTP */ -typedef struct { +typedef struct +{ message_header_t header; short family; interface_t iface; } flush_neighbors_message_t; -typedef struct { +typedef struct +{ message_header_t header; int error_number; } ack_message_t; -typedef struct { +typedef struct +{ message_header_t header; wfp_block_flags_t flags; interface_t iface; } wfp_block_message_t; -typedef struct { +typedef struct +{ message_header_t header; interface_t iface; } enable_dhcp_message_t; -typedef struct { +typedef struct +{ message_header_t header; interface_t iface; short family; int mtu; } set_mtu_message_t; -typedef enum { +typedef enum +{ ADAPTER_TYPE_DCO, ADAPTER_TYPE_TAP, } adapter_type_t; -typedef struct { +typedef struct +{ message_header_t header; adapter_type_t adapter_type; } create_adapter_message_t; diff --git a/sample/sample-plugins/client-connect/sample-client-connect.c b= /sample/sample-plugins/client-connect/sample-client-connect.c index 3dda782..7e3b5a9 100644 --- a/sample/sample-plugins/client-connect/sample-client-connect.c +++ b/sample/sample-plugins/client-connect/sample-client-connect.c @@ -58,8 +58,9 @@ * Our context, where we keep our state. */ -struct plugin_context { - int verb; /* logging verbosity */ +struct plugin_context +{ + int verb; /* logging verbosity */ }; /* this is used for the CLIENT_CONNECT_V2 async/deferred handler @@ -68,8 +69,9 @@ * this, and the "CLIENT_CONNECT_DEFER_V2" handler looks at it to see * if it's time yet to succeed/fail */ -struct plugin_per_client_context { - time_t sleep_until; /* wakeup time (time() + sleep) */ +struct plugin_per_client_context +{ + time_t sleep_until; /* wakeup time (time() + sleep) */ bool want_fail; bool want_disable; const char *client_config; @@ -117,8 +119,7 @@ /* use v3 functions so we can use openvpn's logging and base64 etc. */ OPENVPN_EXPORT int -openvpn_plugin_open_v3(const int v3structver, - struct openvpn_plugin_args_open_in const *args, +openvpn_plugin_open_v3(const int v3structver, struct openvpn_plugin_args_o= pen_in const *args, struct openvpn_plugin_args_open_return *ret) { /* const char **argv =3D args->argv; */ /* command line arguments (unu= sed) */ @@ -127,7 +128,9 @@ /* Check API compatibility -- struct version 5 or higher needed */ if (v3structver < 5) { - fprintf(stderr, "sample-client-connect: this plugin is incompatibl= e with the running version of OpenVPN\n"); + fprintf( + stderr, + "sample-client-connect: this plugin is incompatible with the r= unning version of OpenVPN\n"); return OPENVPN_PLUGIN_FUNC_ERROR; } @@ -143,18 +146,17 @@ /* * Intercept just about everything... */ - ret->type_mask =3D - OPENVPN_PLUGIN_MASK(OPENVPN_PLUGIN_UP) - |OPENVPN_PLUGIN_MASK(OPENVPN_PLUGIN_DOWN) - |OPENVPN_PLUGIN_MASK(OPENVPN_PLUGIN_ROUTE_UP) - |OPENVPN_PLUGIN_MASK(OPENVPN_PLUGIN_IPCHANGE) - |OPENVPN_PLUGIN_MASK(OPENVPN_PLUGIN_TLS_VERIFY) - |OPENVPN_PLUGIN_MASK(OPENVPN_PLUGIN_CLIENT_CONNECT) - |OPENVPN_PLUGIN_MASK(OPENVPN_PLUGIN_CLIENT_CONNECT_V2) - |OPENVPN_PLUGIN_MASK(OPENVPN_PLUGIN_CLIENT_CONNECT_DEFER_V2) - |OPENVPN_PLUGIN_MASK(OPENVPN_PLUGIN_CLIENT_DISCONNECT) - |OPENVPN_PLUGIN_MASK(OPENVPN_PLUGIN_LEARN_ADDRESS) - |OPENVPN_PLUGIN_MASK(OPENVPN_PLUGIN_TLS_FINAL); + ret->type_mask =3D OPENVPN_PLUGIN_MASK(OPENVPN_PLUGIN_UP) + | OPENVPN_PLUGIN_MASK(OPENVPN_PLUGIN_DOWN) + | OPENVPN_PLUGIN_MASK(OPENVPN_PLUGIN_ROUTE_UP) + | OPENVPN_PLUGIN_MASK(OPENVPN_PLUGIN_IPCHANGE) + | OPENVPN_PLUGIN_MASK(OPENVPN_PLUGIN_TLS_VERIFY) + | OPENVPN_PLUGIN_MASK(OPENVPN_PLUGIN_CLIENT_CONNECT) + | OPENVPN_PLUGIN_MASK(OPENVPN_PLUGIN_CLIENT_CONNECT_V= 2) + | OPENVPN_PLUGIN_MASK(OPENVPN_PLUGIN_CLIENT_CONNECT_D= EFER_V2) + | OPENVPN_PLUGIN_MASK(OPENVPN_PLUGIN_CLIENT_DISCONNEC= T) + | OPENVPN_PLUGIN_MASK(OPENVPN_PLUGIN_LEARN_ADDRESS) + | OPENVPN_PLUGIN_MASK(OPENVPN_PLUGIN_TLS_FINAL); /* Save global pointers to functions exported from openvpn */ plugin_log =3D args->callbacks->plugin_log; @@ -166,7 +168,7 @@ */ context->verb =3D atoi_null0(get_env("verb", envp)); - ret->handle =3D (openvpn_plugin_handle_t *) context; + ret->handle =3D (openvpn_plugin_handle_t *)context; plugin_log(PLOG_NOTE, MODULE, "initialization succeeded"); return OPENVPN_PLUGIN_FUNC_SUCCESS; @@ -242,8 +244,10 @@ const char *ccd_file =3D get_env("client_connect_deferred_file", envp); if (!ccd_file) { - plugin_log(PLOG_NOTE, MODULE, "env has UV_WANT_CC_ASYNC=3D%d, but " - "'client_connect_deferred_file' not set -> fail", secon= ds); + plugin_log(PLOG_NOTE, MODULE, + "env has UV_WANT_CC_ASYNC=3D%d, but " + "'client_connect_deferred_file' not set -> fail", + seconds); return OPENVPN_PLUGIN_FUNC_ERROR; } @@ -257,13 +261,13 @@ int fd =3D open(ccd_file, O_WRONLY); if (fd < 0) { - plugin_log(PLOG_ERR|PLOG_ERRNO, MODULE, "open('%s') failed", ccd_f= ile); + plugin_log(PLOG_ERR | PLOG_ERRNO, MODULE, "open('%s') failed", ccd= _file); return OPENVPN_PLUGIN_FUNC_ERROR; } if (write(fd, "2", 1) !=3D 1) { - plugin_log(PLOG_ERR|PLOG_ERRNO, MODULE, "write to '%s' failed", cc= d_file ); + plugin_log(PLOG_ERR | PLOG_ERRNO, MODULE, "write to '%s' failed", = ccd_file); close(fd); return OPENVPN_PLUGIN_FUNC_ERROR; } @@ -277,11 +281,11 @@ /* fork, sleep, succeed/fail according to env vars */ pid_t p1 =3D fork(); - if (p1 < 0) /* Fork failed */ + if (p1 < 0) /* Fork failed */ { return OPENVPN_PLUGIN_FUNC_ERROR; } - if (p1 > 0) /* parent process */ + if (p1 > 0) /* parent process */ { waitpid(p1, NULL, 0); return OPENVPN_PLUGIN_FUNC_DEFERRED; @@ -291,10 +295,10 @@ pid_t p2 =3D fork(); if (p2 < 0) { - plugin_log(PLOG_ERR|PLOG_ERRNO, MODULE, "BACKGROUND: fork(2) faile= d"); + plugin_log(PLOG_ERR | PLOG_ERRNO, MODULE, "BACKGROUND: fork(2) fai= led"); exit(1); } - if (p2 > 0) /* new parent: exit right away */ + if (p2 > 0) /* new parent: exit right away */ { exit(0); } @@ -324,16 +328,16 @@ fd =3D open(ccd_file, O_WRONLY); if (fd < 0) { - plugin_log(PLOG_ERR|PLOG_ERRNO, MODULE, "open('%s') failed", ccd_f= ile); + plugin_log(PLOG_ERR | PLOG_ERRNO, MODULE, "open('%s') failed", ccd= _file); exit(1); } plugin_log(PLOG_NOTE, MODULE, "cc_handle_deferred_v1: done, signalling= %s", - (ret =3D=3D OPENVPN_PLUGIN_FUNC_SUCCESS) ? "success" : "fai= l" ); + (ret =3D=3D OPENVPN_PLUGIN_FUNC_SUCCESS) ? "success" : "fai= l"); if (write(fd, (ret =3D=3D OPENVPN_PLUGIN_FUNC_SUCCESS) ? "1" : "0", 1)= !=3D 1) { - plugin_log(PLOG_ERR|PLOG_ERRNO, MODULE, "write to '%s' failed", cc= d_file ); + plugin_log(PLOG_ERR | PLOG_ERRNO, MODULE, "write to '%s' failed", = ccd_file); } close(fd); @@ -341,14 +345,12 @@ } int -openvpn_plugin_client_connect(struct plugin_context *context, - const char **argv, - const char **envp) +openvpn_plugin_client_connect(struct plugin_context *context, const char *= *argv, const char **envp) { /* log environment variables handed to us by OpenVPN, but * only if "setenv verb" is 3 or higher (arbitrary number) */ - if (context->verb>=3D3) + if (context->verb >=3D 3) { for (int i =3D 0; argv[i]; i++) { @@ -389,8 +391,7 @@ int openvpn_plugin_client_connect_v2(struct plugin_context *context, - struct plugin_per_client_context *pcc, - const char **envp, + struct plugin_per_client_context *pcc, co= nst char **envp, struct openvpn_plugin_string_list **retur= n_list) { /* by setting "UV_WANT_CC2_ASYNC" we go to async/deferred mode */ @@ -420,7 +421,8 @@ pcc->want_fail =3D (want_fail !=3D NULL); pcc->want_disable =3D (want_disable !=3D NULL); pcc->client_config =3D client_config; - plugin_log(PLOG_NOTE, MODULE, "env has UV_WANT_CC2_ASYNC=3D%s -> s= et up deferred handler", want_async); + plugin_log(PLOG_NOTE, MODULE, "env has UV_WANT_CC2_ASYNC=3D%s -> s= et up deferred handler", + want_async); return OPENVPN_PLUGIN_FUNC_DEFERRED; } @@ -431,8 +433,7 @@ return OPENVPN_PLUGIN_FUNC_ERROR; } - struct openvpn_plugin_string_list *rl =3D - calloc(1, sizeof(struct openvpn_plugin_string_list)); + struct openvpn_plugin_string_list *rl =3D calloc(1, sizeof(struct open= vpn_plugin_string_list)); if (!rl) { plugin_log(PLOG_ERR, MODULE, "malloc(return_list) failed"); @@ -466,12 +467,10 @@ int openvpn_plugin_client_connect_defer_v2(struct plugin_context *context, struct plugin_per_client_context *p= cc, - struct openvpn_plugin_string_list - **return_list) + struct openvpn_plugin_string_list *= *return_list) { time_t time_left =3D pcc->sleep_until - time(NULL); - plugin_log(PLOG_NOTE, MODULE, "defer_v2: seconds left=3D%d", - (int) time_left); + plugin_log(PLOG_NOTE, MODULE, "defer_v2: seconds left=3D%d", (int)time= _left); /* not yet due? */ if (time_left > 0) @@ -482,15 +481,14 @@ /* client wants fail? */ if (pcc->want_fail) { - plugin_log(PLOG_NOTE, MODULE, "env has UV_WANT_CC2_FAIL -> fail" ); + plugin_log(PLOG_NOTE, MODULE, "env has UV_WANT_CC2_FAIL -> fail"); return OPENVPN_PLUGIN_FUNC_ERROR; } /* fill in RL according to with-disable / without-disable */ /* TODO: unify this with non-deferred case */ - struct openvpn_plugin_string_list *rl =3D - calloc(1, sizeof(struct openvpn_plugin_string_list)); + struct openvpn_plugin_string_list *rl =3D calloc(1, sizeof(struct open= vpn_plugin_string_list)); if (!rl) { plugin_log(PLOG_ERR, MODULE, "malloc(return_list) failed"); @@ -522,15 +520,12 @@ } OPENVPN_EXPORT int -openvpn_plugin_func_v2(openvpn_plugin_handle_t handle, - const int type, - const char *argv[], - const char *envp[], - void *per_client_context, +openvpn_plugin_func_v2(openvpn_plugin_handle_t handle, const int type, con= st char *argv[], + const char *envp[], void *per_client_context, struct openvpn_plugin_string_list **return_list) { - struct plugin_context *context =3D (struct plugin_context *) handle; - struct plugin_per_client_context *pcc =3D (struct plugin_per_client_co= ntext *) per_client_context; + struct plugin_context *context =3D (struct plugin_context *)handle; + struct plugin_per_client_context *pcc =3D (struct plugin_per_client_co= ntext *)per_client_context; /* for most functions, we just "don't do anything" but log the * event received (so one can follow it in the log and understand @@ -564,13 +559,11 @@ case OPENVPN_PLUGIN_CLIENT_CONNECT_V2: plugin_log(PLOG_NOTE, MODULE, "OPENVPN_PLUGIN_CLIENT_CONNECT_V= 2"); - return openvpn_plugin_client_connect_v2(context, pcc, envp, - return_list); + return openvpn_plugin_client_connect_v2(context, pcc, envp, re= turn_list); case OPENVPN_PLUGIN_CLIENT_CONNECT_DEFER_V2: plugin_log(PLOG_NOTE, MODULE, "OPENVPN_PLUGIN_CLIENT_CONNECT_D= EFER_V2"); - return openvpn_plugin_client_connect_defer_v2(context, pcc, - return_list); + return openvpn_plugin_client_connect_defer_v2(context, pcc, re= turn_list); case OPENVPN_PLUGIN_CLIENT_DISCONNECT: plugin_log(PLOG_NOTE, MODULE, "OPENVPN_PLUGIN_CLIENT_DISCONNEC= T"); @@ -607,7 +600,7 @@ OPENVPN_EXPORT void openvpn_plugin_close_v1(openvpn_plugin_handle_t handle) { - struct plugin_context *context =3D (struct plugin_context *) handle; + struct plugin_context *context =3D (struct plugin_context *)handle; printf("FUNC: openvpn_plugin_close_v1\n"); free(context); } diff --git a/sample/sample-plugins/defer/multi-auth.c b/sample/sample-plugi= ns/defer/multi-auth.c index 9a2cb13..3c9c9c6 100644 --- a/sample/sample-plugins/defer/multi-auth.c +++ b/sample/sample-plugins/defer/multi-auth.c @@ -62,7 +62,8 @@ * Our context, where we keep our state. */ -struct plugin_context { +struct plugin_context +{ int test_deferred_auth; char *authid; char *test_valid_user; @@ -103,11 +104,12 @@ * structver '5' here to indicate a desire for modern openvpn, rather * than a need for any particular feature found in structver beyond '1'. */ -#define OPENVPN_PLUGIN_VERSION_MIN 3 +#define OPENVPN_PLUGIN_VERSION_MIN 3 #define OPENVPN_PLUGIN_STRUCTVER_MIN 5 -struct plugin_per_client_context { +struct plugin_per_client_context +{ int n_calls; bool generated_pf_file; }; @@ -175,13 +177,13 @@ /* use v3 functions so we can use openvpn's logging and base64 etc. */ OPENVPN_EXPORT int -openvpn_plugin_open_v3(const int v3structver, - struct openvpn_plugin_args_open_in const *args, +openvpn_plugin_open_v3(const int v3structver, struct openvpn_plugin_args_o= pen_in const *args, struct openvpn_plugin_args_open_return *ret) { if (v3structver < OPENVPN_PLUGIN_STRUCTVER_MIN) { - fprintf(stderr, "%s: this plugin is incompatible with the running = version of OpenVPN\n", MODULE); + fprintf(stderr, "%s: this plugin is incompatible with the running = version of OpenVPN\n", + MODULE); return OPENVPN_PLUGIN_FUNC_ERROR; } @@ -194,7 +196,7 @@ * Allocate our context */ struct plugin_context *context =3D NULL; - context =3D (struct plugin_context *) calloc(1, sizeof(struct plugin_c= ontext)); + context =3D (struct plugin_context *)calloc(1, sizeof(struct plugin_co= ntext)); if (!context) { goto error; @@ -238,7 +240,7 @@ * Which callbacks to intercept. */ ret->type_mask =3D OPENVPN_PLUGIN_MASK(OPENVPN_PLUGIN_AUTH_USER_PASS_V= ERIFY); - ret->handle =3D (openvpn_plugin_handle_t *) context; + ret->handle =3D (openvpn_plugin_handle_t *)context; plog(context, PLOG_NOTE, "initialization succeeded"); return OPENVPN_PLUGIN_FUNC_SUCCESS; @@ -253,29 +255,22 @@ } static bool -do_auth_user_pass(struct plugin_context *context, - const char *username, const char *password) +do_auth_user_pass(struct plugin_context *context, const char *username, co= nst char *password) { - plog(context, PLOG_NOTE, - "expect_user=3D%s, received_user=3D%s, expect_passw=3D%s, receive= d_passw=3D%s", - np(context->test_valid_user), - np(username), - np(context->test_valid_pass), - np(password)); + plog(context, PLOG_NOTE, "expect_user=3D%s, received_user=3D%s, expect= _passw=3D%s, received_passw=3D%s", + np(context->test_valid_user), np(username), np(context->test_vali= d_pass), np(password)); if (context->test_valid_user && context->test_valid_pass) { if ((strcmp(context->test_valid_user, username) !=3D 0) || (strcmp(context->test_valid_pass, password) !=3D 0)) { - plog(context, PLOG_ERR, - "User/Password auth result: FAIL"); + plog(context, PLOG_ERR, "User/Password auth result: FAIL"); return false; } else { - plog(context, PLOG_NOTE, - "User/Password auth result: PASS"); + plog(context, PLOG_NOTE, "User/Password auth result: PASS"); return true; } } @@ -284,8 +279,7 @@ static int -auth_user_pass_verify(struct plugin_context *context, - struct plugin_per_client_context *pcc, +auth_user_pass_verify(struct plugin_context *context, struct plugin_per_cl= ient_context *pcc, const char *argv[], const char *envp[]) { /* get username/password from envp string array */ @@ -295,8 +289,8 @@ if (!context->test_deferred_auth) { plog(context, PLOG_NOTE, "Direct authentication"); - return do_auth_user_pass(context, username, password) ? - OPENVPN_PLUGIN_FUNC_SUCCESS : OPENVPN_PLUGIN_FUNC_ERROR; + return do_auth_user_pass(context, username, password) ? OPENVPN_PL= UGIN_FUNC_SUCCESS + : OPENVPN_PL= UGIN_FUNC_ERROR; } /* get auth_control_file filename from envp string array*/ @@ -317,11 +311,11 @@ /* fork, sleep, succeed (no "real" auth done =3D always succeed) */ pid_t p1 =3D fork(); - if (p1 < 0) /* Fork failed */ + if (p1 < 0) /* Fork failed */ { return OPENVPN_PLUGIN_FUNC_ERROR; } - if (p1 > 0) /* parent process */ + if (p1 > 0) /* parent process */ { waitpid(p1, NULL, 0); return OPENVPN_PLUGIN_FUNC_DEFERRED; @@ -331,11 +325,11 @@ pid_t p2 =3D fork(); if (p2 < 0) { - plog(context, PLOG_ERR|PLOG_ERRNO, "BACKGROUND: fork(2) failed"); + plog(context, PLOG_ERR | PLOG_ERRNO, "BACKGROUND: fork(2) failed"); exit(1); } - if (p2 !=3D 0) /* new parent: exit right aw= ay */ + if (p2 !=3D 0) /* new parent: exit right away */ { exit(0); } @@ -347,7 +341,7 @@ */ /* do mighty complicated work that will really take time here... */ - useconds_t wait_time =3D (useconds_t)context->test_deferred_auth*1000; + useconds_t wait_time =3D (useconds_t)context->test_deferred_auth * 100= 0; plog(context, PLOG_NOTE, "in async/deferred handler, usleep(%u)", wait= _time); usleep(wait_time); @@ -355,8 +349,7 @@ int fd =3D open(auth_control_file, O_WRONLY); if (fd < 0) { - plog(context, PLOG_ERR|PLOG_ERRNO, - "open('%s') failed", auth_control_file); + plog(context, PLOG_ERR | PLOG_ERRNO, "open('%s') failed", auth_con= trol_file); exit(1); } @@ -368,7 +361,7 @@ if (write(fd, result, 1) !=3D 1) { - plog(context, PLOG_ERR|PLOG_ERRNO, "write to '%s' failed", auth_co= ntrol_file ); + plog(context, PLOG_ERR | PLOG_ERRNO, "write to '%s' failed", auth_= control_file); } close(fd); @@ -377,19 +370,20 @@ OPENVPN_EXPORT int -openvpn_plugin_func_v3(const int v3structver, - struct openvpn_plugin_args_func_in const *args, +openvpn_plugin_func_v3(const int v3structver, struct openvpn_plugin_args_f= unc_in const *args, struct openvpn_plugin_args_func_return *ret) { if (v3structver < OPENVPN_PLUGIN_STRUCTVER_MIN) { - fprintf(stderr, "%s: this plugin is incompatible with the running = version of OpenVPN\n", MODULE); + fprintf(stderr, "%s: this plugin is incompatible with the running = version of OpenVPN\n", + MODULE); return OPENVPN_PLUGIN_FUNC_ERROR; } const char **argv =3D args->argv; const char **envp =3D args->envp; - struct plugin_context *context =3D (struct plugin_context *) args->han= dle; - struct plugin_per_client_context *pcc =3D (struct plugin_per_client_co= ntext *) args->per_client_context; + struct plugin_context *context =3D (struct plugin_context *)args->hand= le; + struct plugin_per_client_context *pcc =3D + (struct plugin_per_client_context *)args->per_client_context; switch (args->type) { case OPENVPN_PLUGIN_AUTH_USER_PASS_VERIFY: @@ -405,7 +399,7 @@ OPENVPN_EXPORT void * openvpn_plugin_client_constructor_v1(openvpn_plugin_handle_t handle) { - struct plugin_context *context =3D (struct plugin_context *) handle; + struct plugin_context *context =3D (struct plugin_context *)handle; plog(context, PLOG_NOTE, "FUNC: openvpn_plugin_client_constructor_v1"); return calloc(1, sizeof(struct plugin_per_client_context)); } @@ -413,7 +407,7 @@ OPENVPN_EXPORT void openvpn_plugin_client_destructor_v1(openvpn_plugin_handle_t handle, void *= per_client_context) { - struct plugin_context *context =3D (struct plugin_context *) handle; + struct plugin_context *context =3D (struct plugin_context *)handle; plog(context, PLOG_NOTE, "FUNC: openvpn_plugin_client_destructor_v1"); free(per_client_context); } @@ -421,7 +415,7 @@ OPENVPN_EXPORT void openvpn_plugin_close_v1(openvpn_plugin_handle_t handle) { - struct plugin_context *context =3D (struct plugin_context *) handle; + struct plugin_context *context =3D (struct plugin_context *)handle; plog(context, PLOG_NOTE, "FUNC: openvpn_plugin_close_v1"); free(context); } diff --git a/sample/sample-plugins/keying-material-exporter-demo/keyingmate= rialexporter.c b/sample/sample-plugins/keying-material-exporter-demo/keying= materialexporter.c index b73144f..e7556a1 100644 --- a/sample/sample-plugins/keying-material-exporter-demo/keyingmaterialexp= orter.c +++ b/sample/sample-plugins/keying-material-exporter-demo/keyingmaterialexp= orter.c @@ -37,22 +37,25 @@ #define MAXPATH 1024 #endif -#define ovpn_err(fmt, ...) \ - plugin->log(PLOG_ERR, "SSO", fmt, ## __VA_ARGS__) -#define ovpn_dbg(fmt, ...) \ - plugin->log(PLOG_DEBUG, "SSO", fmt, ## __VA_ARGS__) -#define ovpn_note(fmt, ...) \ - plugin->log(PLOG_NOTE, "SSO", fmt, ## __VA_ARGS__) +#define ovpn_err(fmt, ...) plugin->log(PLOG_ERR, "SSO", fmt, ##__VA_ARGS_= _) +#define ovpn_dbg(fmt, ...) plugin->log(PLOG_DEBUG, "SSO", fmt, ##__VA_ARG= S__) +#define ovpn_note(fmt, ...) plugin->log(PLOG_NOTE, "SSO", fmt, ##__VA_ARGS= __) -enum endpoint { CLIENT =3D 1, SERVER =3D 2 }; +enum endpoint +{ + CLIENT =3D 1, + SERVER =3D 2 +}; =20 -struct plugin { +struct plugin +{ plugin_log_t log; enum endpoint type; int mask; }; -struct session { +struct session +{ char user[48]; char key[48]; }; @@ -85,8 +88,7 @@ } OPENVPN_EXPORT int -openvpn_plugin_open_v3(const int version, - struct openvpn_plugin_args_open_in const *args, +openvpn_plugin_open_v3(const int version, struct openvpn_plugin_args_open_= in const *args, struct openvpn_plugin_args_open_return *rv) { struct plugin *plugin =3D calloc(1, sizeof(*plugin)); @@ -98,9 +100,9 @@ } plugin->type =3D get_env("remote_1", args->envp) ? CLIENT : SERVER; - plugin->log =3D args->callbacks->plugin_log; + plugin->log =3D args->callbacks->plugin_log; - plugin->mask =3D OPENVPN_PLUGIN_MASK(OPENVPN_PLUGIN_TLS_FINAL); + plugin->mask =3D OPENVPN_PLUGIN_MASK(OPENVPN_PLUGIN_TLS_FINAL); plugin->mask |=3D OPENVPN_PLUGIN_MASK(OPENVPN_PLUGIN_TLS_VERIFY); ovpn_note("vpn endpoint type=3D%s", plugin->type =3D=3D CLIENT ? "clie= nt" : "server"); @@ -163,8 +165,8 @@ static int tls_verify(struct openvpn_plugin_args_func_in const *args) { - struct plugin *plugin =3D (struct plugin *)args->handle; - struct session *sess =3D (struct session *)args->per_client_context; + struct plugin *plugin =3D (struct plugin *)args->handle; + struct session *sess =3D (struct session *)args->per_client_context; /* we store cert subject for the server end point only */ if (plugin->type !=3D SERVER) @@ -199,8 +201,8 @@ static void server_store(struct openvpn_plugin_args_func_in const *args) { - struct plugin *plugin =3D (struct plugin *)args->handle; - struct session *sess =3D (struct session *)args->per_client_context; + struct plugin *plugin =3D (struct plugin *)args->handle; + struct session *sess =3D (struct session *)args->per_client_context; char file[MAXPATH]; snprintf(file, sizeof(file) - 1, "/tmp/openvpn_sso_%s", sess->key); @@ -211,8 +213,8 @@ static void client_store(struct openvpn_plugin_args_func_in const *args) { - struct plugin *plugin =3D (struct plugin *)args->handle; - struct session *sess =3D (struct session *)args->per_client_context; + struct plugin *plugin =3D (struct plugin *)args->handle; + struct session *sess =3D (struct session *)args->per_client_context; char *file =3D "/tmp/openvpn_sso_user"; ovpn_note("app session file: %s", file); @@ -223,8 +225,8 @@ tls_final(struct openvpn_plugin_args_func_in const *args, struct openvpn_plugin_args_func_return *rv) { - struct plugin *plugin =3D (struct plugin *)args->handle; - struct session *sess =3D (struct session *)args->per_client_context; + struct plugin *plugin =3D (struct plugin *)args->handle; + struct session *sess =3D (struct session *)args->per_client_context; const char *key; if (!(key =3D get_env("exported_keying_material", args->envp))) @@ -251,8 +253,7 @@ } OPENVPN_EXPORT int -openvpn_plugin_func_v3(const int version, - struct openvpn_plugin_args_func_in const *args, +openvpn_plugin_func_v3(const int version, struct openvpn_plugin_args_func_= in const *args, struct openvpn_plugin_args_func_return *rv) { switch (args->type) @@ -270,7 +271,7 @@ openvpn_plugin_client_constructor_v1(openvpn_plugin_handle_t handle) { struct plugin *plugin =3D (struct plugin *)handle; - struct session *sess =3D calloc(1, sizeof(*sess)); + struct session *sess =3D calloc(1, sizeof(*sess)); ovpn_note("app session created"); @@ -281,7 +282,7 @@ openvpn_plugin_client_destructor_v1(openvpn_plugin_handle_t handle, void *= ctx) { struct plugin *plugin =3D (struct plugin *)handle; - struct session *sess =3D (struct session *)ctx; + struct session *sess =3D (struct session *)ctx; ovpn_note("app session key: %s", sess->key); ovpn_note("app session destroyed"); diff --git a/sample/sample-plugins/log/log.c b/sample/sample-plugins/log/lo= g.c index 63d714f..70fa60d 100644 --- a/sample/sample-plugins/log/log.c +++ b/sample/sample-plugins/log/log.c @@ -36,7 +36,8 @@ /* * Our context, where we keep our state. */ -struct plugin_context { +struct plugin_context +{ const char *username; const char *password; }; @@ -75,7 +76,7 @@ /* * Allocate our context */ - context =3D (struct plugin_context *) calloc(1, sizeof(struct plugin_c= ontext)); + context =3D (struct plugin_context *)calloc(1, sizeof(struct plugin_co= ntext)); if (context =3D=3D NULL) { printf("PLUGIN: allocating memory for context failed\n"); @@ -91,19 +92,17 @@ /* * Which callbacks to intercept. */ - *type_mask =3D - OPENVPN_PLUGIN_MASK(OPENVPN_PLUGIN_UP) - |OPENVPN_PLUGIN_MASK(OPENVPN_PLUGIN_DOWN) - |OPENVPN_PLUGIN_MASK(OPENVPN_PLUGIN_ROUTE_UP) - |OPENVPN_PLUGIN_MASK(OPENVPN_PLUGIN_IPCHANGE) - |OPENVPN_PLUGIN_MASK(OPENVPN_PLUGIN_TLS_VERIFY) - |OPENVPN_PLUGIN_MASK(OPENVPN_PLUGIN_AUTH_USER_PASS_VERIFY) - |OPENVPN_PLUGIN_MASK(OPENVPN_PLUGIN_CLIENT_CONNECT_V2) - |OPENVPN_PLUGIN_MASK(OPENVPN_PLUGIN_CLIENT_DISCONNECT) - |OPENVPN_PLUGIN_MASK(OPENVPN_PLUGIN_LEARN_ADDRESS) - |OPENVPN_PLUGIN_MASK(OPENVPN_PLUGIN_TLS_FINAL); + *type_mask =3D OPENVPN_PLUGIN_MASK(OPENVPN_PLUGIN_UP) | OPENVPN_PLUGIN= _MASK(OPENVPN_PLUGIN_DOWN) + | OPENVPN_PLUGIN_MASK(OPENVPN_PLUGIN_ROUTE_UP) + | OPENVPN_PLUGIN_MASK(OPENVPN_PLUGIN_IPCHANGE) + | OPENVPN_PLUGIN_MASK(OPENVPN_PLUGIN_TLS_VERIFY) + | OPENVPN_PLUGIN_MASK(OPENVPN_PLUGIN_AUTH_USER_PASS_VERIF= Y) + | OPENVPN_PLUGIN_MASK(OPENVPN_PLUGIN_CLIENT_CONNECT_V2) + | OPENVPN_PLUGIN_MASK(OPENVPN_PLUGIN_CLIENT_DISCONNECT) + | OPENVPN_PLUGIN_MASK(OPENVPN_PLUGIN_LEARN_ADDRESS) + | OPENVPN_PLUGIN_MASK(OPENVPN_PLUGIN_TLS_FINAL); - return (openvpn_plugin_handle_t) context; + return (openvpn_plugin_handle_t)context; } void @@ -171,9 +170,10 @@ } OPENVPN_EXPORT int -openvpn_plugin_func_v1(openvpn_plugin_handle_t handle, const int type, con= st char *argv[], const char *envp[]) +openvpn_plugin_func_v1(openvpn_plugin_handle_t handle, const int type, con= st char *argv[], + const char *envp[]) { - struct plugin_context *context =3D (struct plugin_context *) handle; + struct plugin_context *context =3D (struct plugin_context *)handle; show(type, argv, envp); @@ -184,8 +184,8 @@ const char *username =3D get_env("username", envp); const char *password =3D get_env("password", envp); - if (username && !strcmp(username, context->username) - && password && !strcmp(password, context->password)) + if (username && !strcmp(username, context->username) && password + && !strcmp(password, context->password)) { return OPENVPN_PLUGIN_FUNC_SUCCESS; } @@ -203,6 +203,6 @@ OPENVPN_EXPORT void openvpn_plugin_close_v1(openvpn_plugin_handle_t handle) { - struct plugin_context *context =3D (struct plugin_context *) handle; + struct plugin_context *context =3D (struct plugin_context *)handle; free(context); } diff --git a/sample/sample-plugins/log/log_v3.c b/sample/sample-plugins/log= /log_v3.c index 02cdda8..cef22cf 100644 --- a/sample/sample-plugins/log/log_v3.c +++ b/sample/sample-plugins/log/log_v3.c @@ -39,7 +39,8 @@ /* * Our context, where we keep our state. */ -struct plugin_context { +struct plugin_context +{ const char *username; const char *password; }; @@ -71,8 +72,7 @@ } OPENVPN_EXPORT int -openvpn_plugin_open_v3(const int v3structver, - struct openvpn_plugin_args_open_in const *args, +openvpn_plugin_open_v3(const int v3structver, struct openvpn_plugin_args_o= pen_in const *args, struct openvpn_plugin_args_open_return *ret) { struct plugin_context *context =3D NULL; @@ -80,7 +80,8 @@ /* Check that we are API compatible */ if (v3structver !=3D OPENVPN_PLUGINv3_STRUCTVER) { - printf("log_v3: ** ERROR ** Incompatible plug-in interface between= this plug-in and OpenVPN\n"); + printf( + "log_v3: ** ERROR ** Incompatible plug-in interface between th= is plug-in and OpenVPN\n"); return OPENVPN_PLUGIN_FUNC_ERROR; } @@ -91,26 +92,24 @@ } /* Print some version information about the OpenVPN process using this= plug-in */ - printf("log_v3: OpenVPN %s (Major: %i, Minor: %i, Patch: %s)\n", - args->ovpn_version, args->ovpn_version_major, - args->ovpn_version_minor, args->ovpn_version_patch); + printf("log_v3: OpenVPN %s (Major: %i, Minor: %i, Patch: %s)\n", args= ->ovpn_version, + args->ovpn_version_major, args->ovpn_version_minor, args->ovpn_= version_patch); /* Which callbacks to intercept. */ - ret->type_mask =3D - OPENVPN_PLUGIN_MASK(OPENVPN_PLUGIN_UP) - |OPENVPN_PLUGIN_MASK(OPENVPN_PLUGIN_DOWN) - |OPENVPN_PLUGIN_MASK(OPENVPN_PLUGIN_ROUTE_UP) - |OPENVPN_PLUGIN_MASK(OPENVPN_PLUGIN_IPCHANGE) - |OPENVPN_PLUGIN_MASK(OPENVPN_PLUGIN_TLS_VERIFY) - |OPENVPN_PLUGIN_MASK(OPENVPN_PLUGIN_AUTH_USER_PASS_VERIFY) - |OPENVPN_PLUGIN_MASK(OPENVPN_PLUGIN_CLIENT_CONNECT_V2) - |OPENVPN_PLUGIN_MASK(OPENVPN_PLUGIN_CLIENT_DISCONNECT) - |OPENVPN_PLUGIN_MASK(OPENVPN_PLUGIN_LEARN_ADDRESS) - |OPENVPN_PLUGIN_MASK(OPENVPN_PLUGIN_TLS_FINAL); + ret->type_mask =3D OPENVPN_PLUGIN_MASK(OPENVPN_PLUGIN_UP) + | OPENVPN_PLUGIN_MASK(OPENVPN_PLUGIN_DOWN) + | OPENVPN_PLUGIN_MASK(OPENVPN_PLUGIN_ROUTE_UP) + | OPENVPN_PLUGIN_MASK(OPENVPN_PLUGIN_IPCHANGE) + | OPENVPN_PLUGIN_MASK(OPENVPN_PLUGIN_TLS_VERIFY) + | OPENVPN_PLUGIN_MASK(OPENVPN_PLUGIN_AUTH_USER_PASS_V= ERIFY) + | OPENVPN_PLUGIN_MASK(OPENVPN_PLUGIN_CLIENT_CONNECT_V= 2) + | OPENVPN_PLUGIN_MASK(OPENVPN_PLUGIN_CLIENT_DISCONNEC= T) + | OPENVPN_PLUGIN_MASK(OPENVPN_PLUGIN_LEARN_ADDRESS) + | OPENVPN_PLUGIN_MASK(OPENVPN_PLUGIN_TLS_FINAL); /* Allocate our context */ - context =3D (struct plugin_context *) calloc(1, sizeof(struct plugin_c= ontext)); + context =3D (struct plugin_context *)calloc(1, sizeof(struct plugin_co= ntext)); if (context =3D=3D NULL) { printf("PLUGIN: allocating memory for context failed\n"); @@ -122,7 +121,7 @@ context->password =3D "bar"; /* Point the global context handle to our newly created context */ - ret->handle =3D (void *) context; + ret->handle =3D (void *)context; return OPENVPN_PLUGIN_FUNC_SUCCESS; } @@ -243,13 +242,11 @@ } - OPENVPN_EXPORT int -openvpn_plugin_func_v3(const int version, - struct openvpn_plugin_args_func_in const *args, +openvpn_plugin_func_v3(const int version, struct openvpn_plugin_args_func_= in const *args, struct openvpn_plugin_args_func_return *retptr) { - struct plugin_context *context =3D (struct plugin_context *) args->han= dle; + struct plugin_context *context =3D (struct plugin_context *)args->hand= le; printf("\nopenvpn_plugin_func_v3() :::::>> "); show(args->type, args->argv, args->envp); @@ -270,8 +267,8 @@ const char *username =3D get_env("username", args->envp); const char *password =3D get_env("password", args->envp); - if (username && !strcmp(username, context->username) - && password && !strcmp(password, context->password)) + if (username && !strcmp(username, context->username) && password + && !strcmp(password, context->password)) { return OPENVPN_PLUGIN_FUNC_SUCCESS; } @@ -289,6 +286,6 @@ OPENVPN_EXPORT void openvpn_plugin_close_v1(openvpn_plugin_handle_t handle) { - struct plugin_context *context =3D (struct plugin_context *) handle; + struct plugin_context *context =3D (struct plugin_context *)handle; free(context); } diff --git a/sample/sample-plugins/simple/base64.c b/sample/sample-plugins/= simple/base64.c index b6c0c97..8a1dedd 100644 --- a/sample/sample-plugins/simple/base64.c +++ b/sample/sample-plugins/simple/base64.c @@ -98,21 +98,20 @@ * */ OPENVPN_EXPORT int -openvpn_plugin_open_v3(const int v3structver, - struct openvpn_plugin_args_open_in const *args, +openvpn_plugin_open_v3(const int v3structver, struct openvpn_plugin_args_o= pen_in const *args, struct openvpn_plugin_args_open_return *ret) { /* Check that we are API compatible */ if (v3structver !=3D OPENVPN_PLUGINv3_STRUCTVER) { - printf("base64.c: ** ERROR ** Incompatible plug-in interface betwe= en this plug-in and OpenVPN\n"); + printf( + "base64.c: ** ERROR ** Incompatible plug-in interface between = this plug-in and OpenVPN\n"); return OPENVPN_PLUGIN_FUNC_ERROR; } /* Which callbacks to intercept. */ - ret->type_mask =3D - OPENVPN_PLUGIN_MASK(OPENVPN_PLUGIN_TLS_VERIFY) - |OPENVPN_PLUGIN_MASK(OPENVPN_PLUGIN_CLIENT_CONNECT_V2); + ret->type_mask =3D OPENVPN_PLUGIN_MASK(OPENVPN_PLUGIN_TLS_VERIFY) + | OPENVPN_PLUGIN_MASK(OPENVPN_PLUGIN_CLIENT_CONNECT_V= 2); /* we don't need a plug-in context in this example, but OpenVPN expect= s "something" */ ret->handle =3D calloc(1, 1); @@ -125,8 +124,8 @@ /* Print some version information about the OpenVPN process using this= plug-in */ ovpn_log(PLOG_NOTE, PLUGIN_NAME, "OpenVPN %s (Major: %i, Minor: %i, P= atch: %s)\n", - args->ovpn_version, args->ovpn_version_major, - args->ovpn_version_minor, args->ovpn_version_patch); + args->ovpn_version, args->ovpn_version_major, args->ovpn_vers= ion_minor, + args->ovpn_version_patch); return OPENVPN_PLUGIN_FUNC_SUCCESS; } @@ -154,10 +153,10 @@ */ OPENVPN_EXPORT int -openvpn_plugin_func_v1(openvpn_plugin_handle_t handle, const int type, con= st char *argv[], const char *envp[]) +openvpn_plugin_func_v1(openvpn_plugin_handle_t handle, const int type, con= st char *argv[], + const char *envp[]) { - if (type !=3D OPENVPN_PLUGIN_TLS_VERIFY - && type !=3D OPENVPN_PLUGIN_CLIENT_CONNECT_V2) + if (type !=3D OPENVPN_PLUGIN_TLS_VERIFY && type !=3D OPENVPN_PLUGIN_CL= IENT_CONNECT_V2) { ovpn_log(PLOG_ERR, PLUGIN_NAME, "Unsupported plug-in hook call att= empted"); return OPENVPN_PLUGIN_FUNC_ERROR; @@ -174,14 +173,13 @@ /* test the BASE64 encode function */ char *buf =3D NULL; int r =3D ovpn_base64_encode(clcert_cn, (int)strlen(clcert_cn), &buf); - ovpn_log(PLOG_NOTE, PLUGIN_NAME, "BASE64 encoded '%s' (return value %i= ): '%s'", - clcert_cn, r, buf); + ovpn_log(PLOG_NOTE, PLUGIN_NAME, "BASE64 encoded '%s' (return value %i= ): '%s'", clcert_cn, r, + buf); /* test the BASE64 decode function */ - char buf2[256] =3D {0}; + char buf2[256] =3D { 0 }; r =3D ovpn_base64_decode(buf, &buf2, 255); - ovpn_log(PLOG_NOTE, PLUGIN_NAME, "BASE64 decoded '%s' (return value %i= ): '%s'", - buf, r, buf2); + ovpn_log(PLOG_NOTE, PLUGIN_NAME, "BASE64 decoded '%s' (return value %i= ): '%s'", buf, r, buf2); /* Verify the result, and free the buffer allocated by ovpn_base64_enc= ode() */ r =3D strcmp(clcert_cn, buf2); @@ -201,6 +199,6 @@ OPENVPN_EXPORT void openvpn_plugin_close_v1(openvpn_plugin_handle_t handle) { - struct plugin_context *context =3D (struct plugin_context *) handle; + struct plugin_context *context =3D (struct plugin_context *)handle; free(context); } diff --git a/sample/sample-plugins/simple/simple.c b/sample/sample-plugins/= simple/simple.c index ed5bce5..8b2b793 100644 --- a/sample/sample-plugins/simple/simple.c +++ b/sample/sample-plugins/simple/simple.c @@ -38,7 +38,8 @@ /* * Our context, where we keep our state. */ -struct plugin_context { +struct plugin_context +{ const char *username; const char *password; }; @@ -77,7 +78,7 @@ /* * Allocate our context */ - context =3D (struct plugin_context *) calloc(1, sizeof(struct plugin_c= ontext)); + context =3D (struct plugin_context *)calloc(1, sizeof(struct plugin_co= ntext)); if (context =3D=3D NULL) { printf("PLUGIN: allocating memory for context failed\n"); @@ -96,21 +97,22 @@ */ *type_mask =3D OPENVPN_PLUGIN_MASK(OPENVPN_PLUGIN_AUTH_USER_PASS_VERIF= Y); - return (openvpn_plugin_handle_t) context; + return (openvpn_plugin_handle_t)context; } OPENVPN_EXPORT int -openvpn_plugin_func_v1(openvpn_plugin_handle_t handle, const int type, con= st char *argv[], const char *envp[]) +openvpn_plugin_func_v1(openvpn_plugin_handle_t handle, const int type, con= st char *argv[], + const char *envp[]) { - struct plugin_context *context =3D (struct plugin_context *) handle; + struct plugin_context *context =3D (struct plugin_context *)handle; /* get username/password from envp string array */ const char *username =3D get_env("username", envp); const char *password =3D get_env("password", envp); /* check entered username/password against what we require */ - if (username && !strcmp(username, context->username) - && password && !strcmp(password, context->password)) + if (username && !strcmp(username, context->username) && password + && !strcmp(password, context->password)) { return OPENVPN_PLUGIN_FUNC_SUCCESS; } @@ -123,6 +125,6 @@ OPENVPN_EXPORT void openvpn_plugin_close_v1(openvpn_plugin_handle_t handle) { - struct plugin_context *context =3D (struct plugin_context *) handle; + struct plugin_context *context =3D (struct plugin_context *)handle; free(context); } diff --git a/src/compat/compat-basename.c b/src/compat/compat-basename.c index 18944f6..24f5af7 100644 --- a/src/compat/compat-basename.c +++ b/src/compat/compat-basename.c @@ -41,7 +41,7 @@ /* If NULL, check for \ instead ... might be Windows a path */ p =3D strrchr(filename, '\\'); } - return p ? p + 1 : (char *) filename; + return p ? p + 1 : (char *)filename; } #endif /* HAVE_BASENAME */ diff --git a/src/compat/compat-dirname.c b/src/compat/compat-dirname.c index 17de8ad..a432bae 100644 --- a/src/compat/compat-dirname.c +++ b/src/compat/compat-dirname.c @@ -89,7 +89,7 @@ /* The '/' is the last character, we have to look further. */ if (runp !=3D path) { - last_slash =3D (char *) __memrchr(path, separator, runp - path= ); + last_slash =3D (char *)__memrchr(path, separator, runp - path); } } =20 @@ -134,7 +134,7 @@ /* This assignment is ill-designed but the XPG specs require to * return a string containing "." in any case no directory part is * found and so a static and constant string is required. */ - path =3D (char *) dot; + path =3D (char *)dot; } return path; diff --git a/src/compat/compat-gettimeofday.c b/src/compat/compat-gettimeof= day.c index de53cb5..29ded6c 100644 --- a/src/compat/compat-gettimeofday.c +++ b/src/compat/compat-gettimeofday.c @@ -48,7 +48,7 @@ { const time_t t =3D time(NULL); const DWORD gtc =3D GetTickCount(); - gtc_base =3D t - gtc/1000; + gtc_base =3D t - gtc / 1000; gtc_last =3D gtc; } @@ -112,7 +112,7 @@ return 0; } -#else /* ifdef _WIN32 */ +#else /* ifdef _WIN32 */ #include diff --git a/src/openvpn/argv.c b/src/openvpn/argv.c index 34266d4..903fc0a 100644 --- a/src/openvpn/argv.c +++ b/src/openvpn/argv.c @@ -284,8 +284,7 @@ * free()d to avoid memory leaks. */ static char * -argv_prep_format(const char *format, const char delim, size_t *count, - struct gc_arena *gc) +argv_prep_format(const char *format, const char delim, size_t *count, stru= ct gc_arena *gc) { if (format =3D=3D NULL) { @@ -311,7 +310,7 @@ * the string is empty; the resulting format string * will never start with a delimiter. */ - if (j > 0) /* Has anything been written to the output string?= */ + if (j > 0) /* Has anything been written to the output string? = */ { f[j++] =3D delim; } @@ -347,7 +346,7 @@ static bool argv_printf_arglist(struct argv *argres, const char *format, va_list argli= st) { - const char delim =3D 0x1D; /* ASCII Group Separator (GS) */ + const char delim =3D 0x1D; /* ASCII Group Separator (GS) */ bool res =3D false; /* @@ -484,8 +483,8 @@ argv_reset(argres); =20 char *parms[MAX_PARMS + 1] =3D { 0 }; - int nparms =3D parse_line(cmdstr, parms, MAX_PARMS, "SCRIPT-ARGV", 0, - D_ARGV_PARSE_CMD, &argres->gc); + int nparms =3D + parse_line(cmdstr, parms, MAX_PARMS, "SCRIPT-ARGV", 0, D_ARGV_PARS= E_CMD, &argres->gc); if (nparms) { int i; diff --git a/src/openvpn/argv.h b/src/openvpn/argv.h index f694760..056fe31 100644 --- a/src/openvpn/argv.h +++ b/src/openvpn/argv.h @@ -31,7 +31,8 @@ #include "buffer.h" -struct argv { +struct argv +{ struct gc_arena gc; size_t capacity; size_t argc; @@ -55,21 +56,21 @@ bool argv_printf(struct argv *a, const char *format, ...) #ifdef __GNUC__ #if __USE_MINGW_ANSI_STDIO -__attribute__ ((format(gnu_printf, 2, 3))) + __attribute__((format(gnu_printf, 2, 3))) #else -__attribute__ ((format(__printf__, 2, 3))) + __attribute__((format(__printf__, 2, 3))) #endif #endif -; + ; bool argv_printf_cat(struct argv *a, const char *format, ...) #ifdef __GNUC__ #if __USE_MINGW_ANSI_STDIO -__attribute__ ((format(gnu_printf, 2, 3))) + __attribute__((format(gnu_printf, 2, 3))) #else -__attribute__ ((format(__printf__, 2, 3))) + __attribute__((format(__printf__, 2, 3))) #endif #endif -; + ; #endif /* ifndef ARGV_H */ diff --git a/src/openvpn/auth_token.c b/src/openvpn/auth_token.c index 3cf55e8..a694e81 100644 --- a/src/openvpn/auth_token.c +++ b/src/openvpn/auth_token.c @@ -18,7 +18,7 @@ const char *auth_token_pem_name =3D "OpenVPN auth-token server key"; -#define AUTH_TOKEN_SESSION_ID_LEN 12 +#define AUTH_TOKEN_SESSION_ID_LEN 12 #define AUTH_TOKEN_SESSION_ID_BASE64_LEN (AUTH_TOKEN_SESSION_ID_LEN * 8 / = 6) #if AUTH_TOKEN_SESSION_ID_LEN % 3 @@ -53,7 +53,7 @@ } else if (auth_token_state_flags & AUTH_TOKEN_HMAC_OK) { - switch (auth_token_state_flags & (AUTH_TOKEN_VALID_EMPTYUSER|AUTH_= TOKEN_EXPIRED)) + switch (auth_token_state_flags & (AUTH_TOKEN_VALID_EMPTYUSER | AUT= H_TOKEN_EXPIRED)) { case 0: state =3D "Authenticated"; @@ -107,9 +107,9 @@ * in the encoding */ - char session_id[AUTH_TOKEN_SESSION_ID_LEN*2] =3D {0}; + char session_id[AUTH_TOKEN_SESSION_ID_LEN * 2] =3D { 0 }; memcpy(session_id, session_id_source + strlen(SESSION_ID_PREFIX), - AUTH_TOKEN_SESSION_ID_LEN*8/6); + AUTH_TOKEN_SESSION_ID_LEN * 8 / 6); setenv_str(session->opt->es, "session_id", session_id); } @@ -121,8 +121,7 @@ } void -auth_token_init_secret(struct key_ctx *key_ctx, const char *key_file, - bool key_inline) +auth_token_init_secret(struct key_ctx *key_ctx, const char *key_file, bool= key_inline) { struct key_type kt =3D auth_token_kt(); @@ -131,14 +130,12 @@ bool key_loaded =3D false; if (key_file) { - key_loaded =3D read_pem_key_file(&server_secret_key, - auth_token_pem_name, - key_file, key_inline); + key_loaded =3D + read_pem_key_file(&server_secret_key, auth_token_pem_name, key= _file, key_inline); } else { - key_loaded =3D generate_ephemeral_key(&server_secret_key, - auth_token_pem_name); + key_loaded =3D generate_ephemeral_key(&server_secret_key, auth_tok= en_pem_name); } if (!key_loaded) @@ -169,7 +166,7 @@ int64_t initial_timestamp =3D timestamp; hmac_ctx_t *ctx =3D multi->opt.auth_token_key.hmac; - ASSERT(hmac_ctx_size(ctx) =3D=3D 256/8); + ASSERT(hmac_ctx_size(ctx) =3D=3D 256 / 8); uint8_t sessid[AUTH_TOKEN_SESSION_ID_LEN]; @@ -185,7 +182,7 @@ char *initial_token_copy =3D string_alloc(multi->auth_token_initia= l, &gc); char *old_sessid =3D initial_token_copy + strlen(SESSION_ID_PREFIX= ); - char *old_tstamp_initial =3D old_sessid + AUTH_TOKEN_SESSION_ID_LE= N*8/6; + char *old_tstamp_initial =3D old_sessid + AUTH_TOKEN_SESSION_ID_LE= N * 8 / 6; /* * We null terminate the old token just after the session ID to let @@ -197,12 +194,13 @@ memcpy(&initial_timestamp, &old_tstamp_decode, sizeof(initial_time= stamp)); old_tstamp_initial[0] =3D '\0'; - ASSERT(openvpn_base64_decode(old_sessid, sessid, AUTH_TOKEN_SESSIO= N_ID_LEN) =3D=3D AUTH_TOKEN_SESSION_ID_LEN); + ASSERT(openvpn_base64_decode(old_sessid, sessid, AUTH_TOKEN_SESSIO= N_ID_LEN) + =3D=3D AUTH_TOKEN_SESSION_ID_LEN); } else if (!rand_bytes(sessid, AUTH_TOKEN_SESSION_ID_LEN)) { - msg( M_FATAL, "Failed to get enough randomness for " - "authentication token"); + msg(M_FATAL, "Failed to get enough randomness for " + "authentication token"); } /* Calculate the HMAC */ @@ -210,7 +208,7 @@ * with \0 in them is asking for troubles in so many ways anyway that = we * ignore that corner case here */ - uint8_t hmac_output[256/8]; + uint8_t hmac_output[256 / 8]; hmac_ctx_reset(ctx); @@ -222,20 +220,20 @@ struct key_state *ks =3D &multi->session[TM_ACTIVE].key[KS_PRIMARY]; if (ks->auth_token_state_flags & AUTH_TOKEN_VALID_EMPTYUSER) { - hmac_ctx_update(ctx, (const uint8_t *) "", 0); + hmac_ctx_update(ctx, (const uint8_t *)"", 0); } else { - hmac_ctx_update(ctx, (uint8_t *) up->username, (int) strlen(up->us= ername)); + hmac_ctx_update(ctx, (uint8_t *)up->username, (int)strlen(up->user= name)); } hmac_ctx_update(ctx, sessid, AUTH_TOKEN_SESSION_ID_LEN); - hmac_ctx_update(ctx, (uint8_t *) &initial_timestamp, sizeof(initial_ti= mestamp)); - hmac_ctx_update(ctx, (uint8_t *) ×tamp, sizeof(timestamp)); + hmac_ctx_update(ctx, (uint8_t *)&initial_timestamp, sizeof(initial_tim= estamp)); + hmac_ctx_update(ctx, (uint8_t *)×tamp, sizeof(timestamp)); hmac_ctx_final(ctx, hmac_output); /* Construct the unencoded session token */ - struct buffer token =3D alloc_buf_gc( - 2*sizeof(uint64_t) + AUTH_TOKEN_SESSION_ID_LEN + 256/8, &gc); + struct buffer token =3D + alloc_buf_gc(2 * sizeof(uint64_t) + AUTH_TOKEN_SESSION_ID_LEN + 25= 6 / 8, &gc); ASSERT(buf_write(&token, sessid, sizeof(sessid))); ASSERT(buf_write(&token, &initial_timestamp, sizeof(initial_timestamp)= )); @@ -245,8 +243,8 @@ char *b64output =3D NULL; openvpn_base64_encode(BPTR(&token), BLEN(&token), &b64output); - struct buffer session_token =3D alloc_buf_gc( - strlen(SESSION_ID_PREFIX) + strlen(b64output) + 1, &gc); + struct buffer session_token =3D + alloc_buf_gc(strlen(SESSION_ID_PREFIX) + strlen(b64output) + 1, &g= c); ASSERT(buf_write(&session_token, SESSION_ID_PREFIX, strlen(SESSION_ID_= PREFIX))); ASSERT(buf_write(&session_token, b64output, (int)strlen(b64output))); @@ -258,8 +256,7 @@ free(multi->auth_token); multi->auth_token =3D strdup((char *)BPTR(&session_token)); - dmsg(D_SHOW_KEYS, "Generated token for client: %s (%s)", - multi->auth_token, up->username); + dmsg(D_SHOW_KEYS, "Generated token for client: %s (%s)", multi->auth_t= oken, up->username); if (!multi->auth_token_initial) { @@ -277,22 +274,21 @@ static bool check_hmac_token(hmac_ctx_t *ctx, const uint8_t *b64decoded, const char *u= sername) { - ASSERT(hmac_ctx_size(ctx) =3D=3D 256/8); + ASSERT(hmac_ctx_size(ctx) =3D=3D 256 / 8); - uint8_t hmac_output[256/8]; + uint8_t hmac_output[256 / 8]; hmac_ctx_reset(ctx); - hmac_ctx_update(ctx, (uint8_t *) username, (int)strlen(username)); - hmac_ctx_update(ctx, b64decoded, TOKEN_DATA_LEN - 256/8); + hmac_ctx_update(ctx, (uint8_t *)username, (int)strlen(username)); + hmac_ctx_update(ctx, b64decoded, TOKEN_DATA_LEN - 256 / 8); hmac_ctx_final(ctx, hmac_output); - const uint8_t *hmac =3D b64decoded + TOKEN_DATA_LEN - 256/8; + const uint8_t *hmac =3D b64decoded + TOKEN_DATA_LEN - 256 / 8; return memcmp_constant_time(&hmac_output, hmac, 32) =3D=3D 0; } unsigned int -verify_auth_token(struct user_pass *up, struct tls_multi *multi, - struct tls_session *session) +verify_auth_token(struct user_pass *up, struct tls_multi *multi, struct tl= s_session *session) { /* * Base64 is <=3D input and input is < USER_PASS_LEN, so using USER_PA= SS_LEN @@ -300,8 +296,8 @@ */ ASSERT(up && !up->protected); uint8_t b64decoded[USER_PASS_LEN]; - int decoded_len =3D openvpn_base64_decode(up->password + strlen(SESSIO= N_ID_PREFIX), - b64decoded, USER_PASS_LEN); + int decoded_len =3D + openvpn_base64_decode(up->password + strlen(SESSION_ID_PREFIX), b6= 4decoded, USER_PASS_LEN); /* * Ensure that the decoded data is the size of the @@ -309,8 +305,7 @@ */ if (decoded_len !=3D TOKEN_DATA_LEN) { - msg(M_WARN, "ERROR: --auth-token wrong size (%d!=3D%d)", - decoded_len, (int) TOKEN_DATA_LEN); + msg(M_WARN, "ERROR: --auth-token wrong size (%d!=3D%d)", decoded_l= en, (int)TOKEN_DATA_LEN); return 0; } @@ -343,15 +338,14 @@ } else { - msg(M_WARN, "--auth-gen-token: HMAC on token from client failed (%= s)", - up->username); + msg(M_WARN, "--auth-gen-token: HMAC on token from client failed (%= s)", up->username); return 0; } /* Accept session tokens only if their timestamp is in the acceptable = range * for renegotiations */ - bool in_renegotiation_time =3D now >=3D timestamp - && now < timestamp + 2 * session->opt->au= th_token_renewal; + bool in_renegotiation_time =3D + now >=3D timestamp && now < timestamp + 2 * session->opt->auth_tok= en_renewal; if (!in_renegotiation_time) { @@ -363,14 +357,14 @@ /* Sanity check the initial timestamp */ if (timestamp < timestamp_initial) { - msg(M_WARN, "Initial timestamp (%" PRIu64 ") in token from client = earlier than " + msg(M_WARN, + "Initial timestamp (%" PRIu64 ") in token from client earlier = than " "current timestamp %" PRIu64 ". Broken/unsynchronised clock?", timestamp_initial, timestamp); ret |=3D AUTH_TOKEN_EXPIRED; } - if (multi->opt.auth_token_lifetime - && now > timestamp_initial + multi->opt.auth_token_lifetime) + if (multi->opt.auth_token_lifetime && now > timestamp_initial + multi-= >opt.auth_token_lifetime) { ret |=3D AUTH_TOKEN_EXPIRED; } @@ -391,7 +385,7 @@ strlen(SESSION_ID_PREFIX) + AUTH_TOKEN_SES= SION_ID_BASE64_LEN)) { msg(M_WARN, "--auth-gen-token: session id in token changed (Reject= ing " - "token."); + "token."); ret =3D 0; } return ret; @@ -409,8 +403,7 @@ } if (multi->auth_token_initial) { - secure_memzero(multi->auth_token_initial, - strlen(multi->auth_token_initial)); + secure_memzero(multi->auth_token_initial, strlen(multi->auth_t= oken_initial)); free(multi->auth_token_initial); } multi->auth_token =3D NULL; @@ -438,7 +431,7 @@ if (!multi->auth_token_initial) { msg(D_SHOW_KEYS, "initial auth-token not generated yet, skipping " - "auth-token renewal."); + "auth-token renewal."); return; } diff --git a/src/openvpn/auth_token.h b/src/openvpn/auth_token.h index 3d56ee6..1e4a413 100644 --- a/src/openvpn/auth_token.h +++ b/src/openvpn/auth_token.h @@ -58,27 +58,22 @@ * This function will free() an existing multi->auth_token and keep the * existing initial timestamp and session id contained in that token. */ -void -generate_auth_token(const struct user_pass *up, struct tls_multi *multi); +void generate_auth_token(const struct user_pass *up, struct tls_multi *mul= ti); /** * Verifies the auth token to be in the format that generate_auth_token * create and checks if the token is valid. * */ -unsigned -verify_auth_token(struct user_pass *up, struct tls_multi *multi, - struct tls_session *session); - +unsigned verify_auth_token(struct user_pass *up, struct tls_multi *multi, + struct tls_session *session); /** * Loads an HMAC secret from a file or if no file is present generates a * epheremal secret for the run time of the server and stores it into ctx */ -void -auth_token_init_secret(struct key_ctx *key_ctx, const char *key_file, - bool key_inline); +void auth_token_init_secret(struct key_ctx *key_ctx, const char *key_file,= bool key_inline); /** @@ -125,8 +120,7 @@ static inline bool is_auth_token(const char *password) { - return (memcmp_constant_time(SESSION_ID_PREFIX, password, - strlen(SESSION_ID_PREFIX)) =3D=3D 0); + return (memcmp_constant_time(SESSION_ID_PREFIX, password, strlen(SESSI= ON_ID_PREFIX)) =3D=3D 0); } /** * Checks if a client should be sent a new auth token to update its @@ -134,15 +128,13 @@ * @param multi Pointer the multi object of the TLS session * @param session Pointer to the TLS session itself */ -void -resend_auth_token_renegotiation(struct tls_multi *multi, struct tls_sessio= n *session); +void resend_auth_token_renegotiation(struct tls_multi *multi, struct tls_s= ession *session); /** * Checks if the timer to resend the auth-token has expired and if a new * auth-token should be send to the client and triggers the resending */ -void -check_send_auth_token(struct context *c); +void check_send_auth_token(struct context *c); #endif /* AUTH_TOKEN_H */ diff --git a/src/openvpn/base64.c b/src/openvpn/base64.c index a9c2f4c..54d5b79 100644 --- a/src/openvpn/base64.c +++ b/src/openvpn/base64.c @@ -41,8 +41,7 @@ #include "memdbg.h" -static char base64_chars[] =3D - "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; +static char base64_chars[] =3D "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnop= qrstuvwxyz0123456789+/"; /* * base64 encode input data of length size to malloced * buffer which is returned as *str. Returns string @@ -60,14 +59,14 @@ { return -1; } - p =3D s =3D (char *) malloc(size * 4 / 3 + 4); + p =3D s =3D (char *)malloc(size * 4 / 3 + 4); if (p =3D=3D NULL) { return -1; } - q =3D (const unsigned char *) data; + q =3D (const unsigned char *)data; i =3D 0; - for (i =3D 0; i < size; ) + for (i =3D 0; i < size;) { c =3D q[i++]; c *=3D 256; @@ -196,5 +195,5 @@ *q++ =3D val & 0xff; } } - return q - (unsigned char *) data; + return q - (unsigned char *)data; } diff --git a/src/openvpn/base64.h b/src/openvpn/base64.h index 7b4224a..be7aa64 100644 --- a/src/openvpn/base64.h +++ b/src/openvpn/base64.h @@ -35,12 +35,10 @@ #define _BASE64_H_ /** Compute resulting base64 length. 6 bits per byte, padded to 4 bytes. = */ -#define OPENVPN_BASE64_LENGTH(binary_length) \ - ((((8 * binary_length) / 6) + 3) & ~3) +#define OPENVPN_BASE64_LENGTH(binary_length) ((((8 * binary_length) / 6) += 3) & ~3) /** Compute the maximal number of bytes encoded in a base64 string. */ -#define OPENVPN_BASE64_DECODED_LENGTH(base64_length) \ - ((base64_length / 4) * 3) +#define OPENVPN_BASE64_DECODED_LENGTH(base64_length) ((base64_length / 4) = * 3) int openvpn_base64_encode(const void *data, int size, char **str); diff --git a/src/openvpn/basic.h b/src/openvpn/basic.h index 47a86d9..aae84f5 100644 --- a/src/openvpn/basic.h +++ b/src/openvpn/basic.h @@ -26,7 +26,7 @@ #define BOOL_CAST(x) ((x) ? (true) : (false)) /* size of an array */ -#define SIZE(x) (sizeof(x)/sizeof(x[0])) +#define SIZE(x) (sizeof(x) / sizeof(x[0])) /* clear an object (may be optimized away, use secure_memzero() to erase s= ecrets) */ #define CLEAR(x) memset(&(x), 0, sizeof(x)) diff --git a/src/openvpn/buffer.c b/src/openvpn/buffer.c index 5940ad9..0f0d17e 100644 --- a/src/openvpn/buffer.c +++ b/src/openvpn/buffer.c @@ -40,12 +40,14 @@ array_mult_safe(const size_t m1, const size_t m2, const size_t extra) { const size_t limit =3D 0xFFFFFFFF; - unsigned long long res =3D (unsigned long long)m1 * (unsigned long lon= g)m2 + (unsigned long long)extra; - if (unlikely(m1 > limit) || unlikely(m2 > limit) || unlikely(extra > l= imit) || unlikely(res > (unsigned long long)limit)) + unsigned long long res =3D + (unsigned long long)m1 * (unsigned long long)m2 + (unsigned long l= ong)extra; + if (unlikely(m1 > limit) || unlikely(m2 > limit) || unlikely(extra > l= imit) + || unlikely(res > (unsigned long long)limit)) { msg(M_FATAL, "attempted allocation of excessively large array"); } - return (size_t) res; + return (size_t)res; } void @@ -96,9 +98,9 @@ buf.offset =3D 0; buf.len =3D 0; #ifdef DMALLOC - buf.data =3D (uint8_t *) gc_malloc_debug(size, false, gc, file, line); + buf.data =3D (uint8_t *)gc_malloc_debug(size, false, gc, file, line); #else - buf.data =3D (uint8_t *) gc_malloc(size, false, gc); + buf.data =3D (uint8_t *)gc_malloc(size, false, gc); #endif if (size) { @@ -119,9 +121,9 @@ ret.offset =3D buf->offset; ret.len =3D buf->len; #ifdef DMALLOC - ret.data =3D (uint8_t *) openvpn_dmalloc(file, line, buf->capacity); + ret.data =3D (uint8_t *)openvpn_dmalloc(file, line, buf->capacity); #else - ret.data =3D (uint8_t *) malloc(buf->capacity); + ret.data =3D (uint8_t *)malloc(buf->capacity); #endif check_malloc_return(ret.data); memcpy(BPTR(&ret), BPTR(buf), BLEN(buf)); @@ -150,7 +152,7 @@ return buf->debug_file; } -#else /* ifdef BUF_INIT_TRACKING */ +#else /* ifdef BUF_INIT_TRACKING */ #define buf_debug_line(buf) 0 #define buf_debug_file(buf) "[UNDEF]" @@ -252,7 +254,7 @@ stat =3D vsnprintf((char *)ptr, cap, format, arglist); va_end(arglist); *(buf->data + buf->capacity - 1) =3D 0; /* windows vsnprintf n= eeds this */ - buf->len +=3D (int) strlen((char *)ptr); + buf->len +=3D (int)strlen((char *)ptr); if (stat >=3D 0 && stat < cap) { ret =3D true; @@ -272,7 +274,7 @@ { strncpynt((char *)ptr, str, cap); *(buf->data + buf->capacity - 1) =3D 0; /* windows vsnprintf needs= this */ - buf->len +=3D (int) strlen((char *)ptr); + buf->len +=3D (int)strlen((char *)ptr); ret =3D true; } return ret; @@ -299,8 +301,7 @@ buffer_write_file(const char *filename, const struct buffer *buf) { bool ret =3D false; - int fd =3D platform_open(filename, O_CREAT | O_TRUNC | O_WRONLY, - S_IRUSR | S_IWUSR); + int fd =3D platform_open(filename, O_CREAT | O_TRUNC | O_WRONLY, S_IRU= SR | S_IWUSR); if (fd =3D=3D -1) { msg(M_ERRNO, "Cannot open file '%s' for write", filename); @@ -340,12 +341,12 @@ { struct gc_entry *e; #ifdef DMALLOC - e =3D (struct gc_entry *) openvpn_dmalloc(file, line, size + sizeo= f(struct gc_entry)); + e =3D (struct gc_entry *)openvpn_dmalloc(file, line, size + sizeof= (struct gc_entry)); #else - e =3D (struct gc_entry *) malloc(size + sizeof(struct gc_entry)); + e =3D (struct gc_entry *)malloc(size + sizeof(struct gc_entry)); #endif check_malloc_return(e); - ret =3D (char *) e + sizeof(struct gc_entry); + ret =3D (char *)e + sizeof(struct gc_entry); e->next =3D a->list; a->list =3D e; } @@ -361,7 +362,7 @@ #ifndef ZERO_BUFFER_ON_ALLOC if (clear) #endif - memset(ret, 0, size); + memset(ret, 0, size); return ret; } @@ -439,9 +440,9 @@ ASSERT(a); struct gc_entry_special *e; #ifdef DMALLOC - e =3D (struct gc_entry_special *) openvpn_dmalloc(file, line, sizeof(s= truct gc_entry_special)); + e =3D (struct gc_entry_special *)openvpn_dmalloc(file, line, sizeof(st= ruct gc_entry_special)); #else - e =3D (struct gc_entry_special *) malloc(sizeof(struct gc_entry_specia= l)); + e =3D (struct gc_entry_special *)malloc(sizeof(struct gc_entry_special= )); #endif check_malloc_return(e); e->free_fnc =3D free_function; @@ -479,15 +480,15 @@ */ char * -format_hex_ex(const uint8_t *data, int size, int maxoutput, - unsigned int space_break_flags, const char *separator, - struct gc_arena *gc) +format_hex_ex(const uint8_t *data, int size, int maxoutput, unsigned int s= pace_break_flags, + const char *separator, struct gc_arena *gc) { const size_t bytes_per_hexblock =3D space_break_flags & FHE_SPACE_BREA= K_MASK; const size_t separator_len =3D separator ? strlen(separator) : 0; static_assert(INT_MAX <=3D SIZE_MAX, "Code assumes INT_MAX <=3D SIZE_M= AX"); - const size_t out_len =3D maxoutput > 0 ? maxoutput : - ((size * 2) + ((size / bytes_per_hexblock) * se= parator_len) + 2); + const size_t out_len =3D maxoutput > 0 + ? maxoutput + : ((size * 2) + ((size / bytes_per_hexblock= ) * separator_len) + 2); struct buffer out =3D alloc_buf_gc(out_len, gc); for (int i =3D 0; i < size; ++i) @@ -531,13 +532,13 @@ void buf_null_terminate(struct buffer *buf) { - char *last =3D (char *) BLAST(buf); + char *last =3D (char *)BLAST(buf); if (last && *last =3D=3D '\0') /* already terminated? */ { return; } - if (!buf_safe(buf, 1)) /* make space for trailing null */ + if (!buf_safe(buf, 1)) /* make space for trailing null */ { buf_inc_len(buf, -1); } @@ -554,12 +555,12 @@ { while (true) { - char *last =3D (char *) BLAST(buf); + char *last =3D (char *)BLAST(buf); if (!last) { break; } - if (char_class(*last, CC_CRLF|CC_NULL)) + if (char_class(*last, CC_CRLF | CC_NULL)) { if (!buf_inc_len(buf, -1)) { @@ -656,9 +657,9 @@ if (gc) { #ifdef DMALLOC - ret =3D (char *) gc_malloc_debug(n, false, gc, file, line); + ret =3D (char *)gc_malloc_debug(n, false, gc, file, line); #else - ret =3D (char *) gc_malloc(n, false, gc); + ret =3D (char *)gc_malloc(n, false, gc); #endif } else @@ -717,7 +718,7 @@ { struct buffer out =3D alloc_buf_gc(256, gc); int i =3D 0; - for (;; ) + for (;;) { const char *cp =3D *p++; if (!cp) @@ -756,9 +757,9 @@ ASSERT(str); #ifdef DMALLOC - buf_set_read(&buf, (uint8_t *) string_alloc_debug(str, gc, file, line)= , strlen(str) + 1); + buf_set_read(&buf, (uint8_t *)string_alloc_debug(str, gc, file, line),= strlen(str) + 1); #else - buf_set_read(&buf, (uint8_t *) string_alloc(str, gc), strlen(str) + 1); + buf_set_read(&buf, (uint8_t *)string_alloc(str, gc), strlen(str) + 1); #endif if (buf.len > 0) /* Don't count trailing '\0' as part of length */ @@ -845,10 +846,9 @@ break; } line[n++] =3D (char)c; - } - while (c); + } while (c); - line[size-1] =3D '\0'; + line[size - 1] =3D '\0'; return !(eol && !strlen(line)); } @@ -1038,7 +1038,8 @@ * Guaranteed to not increase string length. */ bool -string_mod(char *str, const unsigned int inclusive, const unsigned int exc= lusive, const char replace) +string_mod(char *str, const unsigned int inclusive, const unsigned int exc= lusive, + const char replace) { const char *in =3D str; bool ret =3D true; @@ -1087,11 +1088,8 @@ } const char * -string_mod_const(const char *str, - const unsigned int inclusive, - const unsigned int exclusive, - const char replace, - struct gc_arena *gc) +string_mod_const(const char *str, const unsigned int inclusive, const unsi= gned int exclusive, + const char replace, struct gc_arena *gc) { if (str) { @@ -1130,23 +1128,16 @@ if (buf && buf->len) { int msglevel =3D D_ALIGN_DEBUG; - const unsigned int u =3D (unsigned int) BPTR(buf); + const unsigned int u =3D (unsigned int)BPTR(buf); - if (u & (PAYLOAD_ALIGN-1)) + if (u & (PAYLOAD_ALIGN - 1)) { msglevel =3D D_ALIGN_ERRORS; } msg(msglevel, "%sAlignment at %s/%d ptr=3D" ptr_format " OLC=3D%d/= %d/%d I=3D%s/%d", - (msglevel =3D=3D D_ALIGN_ERRORS) ? "ERROR: " : "", - file, - line, - (ptr_type)buf->data, - buf->offset, - buf->len, - buf->capacity, - buf_debug_file(buf), - buf_debug_line(buf)); + (msglevel =3D=3D D_ALIGN_ERRORS) ? "ERROR: " : "", file, line,= (ptr_type)buf->data, + buf->offset, buf->len, buf->capacity, buf_debug_file(buf), buf= _debug_line(buf)); } } #endif /* ifdef VERIFY_ALIGNMENT */ @@ -1200,7 +1191,7 @@ if (str) { const size_t len =3D strlen((const char *)str); - struct buffer_entry *e =3D buffer_list_push_data(ol, str, len+1); + struct buffer_entry *e =3D buffer_list_push_data(ol, str, len + 1); if (e) { e->buf.len =3D (int)len; /* Don't count trailing '\0' as part = of length */ @@ -1249,8 +1240,7 @@ } void -buffer_list_aggregate_separator(struct buffer_list *bl, const size_t max_l= en, - const char *sep) +buffer_list_aggregate_separator(struct buffer_list *bl, const size_t max_l= en, const char *sep) { const size_t sep_len =3D strlen(sep); struct buffer_entry *more =3D bl->head; @@ -1339,7 +1329,7 @@ if (fp) { - char *line =3D (char *) malloc(max_line_len); + char *line =3D (char *)malloc(max_line_len); if (line) { bl =3D buffer_list_new(); diff --git a/src/openvpn/buffer.h b/src/openvpn/buffer.h index 0d5c30d..ae783c6 100644 --- a/src/openvpn/buffer.h +++ b/src/openvpn/buffer.h @@ -58,13 +58,13 @@ */ struct buffer { - int capacity; /**< Size in bytes of memory allocated by - * \c malloc(). */ - int offset; /**< Offset in bytes of the actual content - * within the allocated memory. */ - int len; /**< Length in bytes of the actual content - * within the allocated memory. */ - uint8_t *data; /**< Pointer to the allocated memory. */ + int capacity; /**< Size in bytes of memory allocated by + * \c malloc(). */ + int offset; /**< Offset in bytes of the actual content + * within the allocated memory. */ + int len; /**< Length in bytes of the actual content + * within the allocated memory. */ + uint8_t *data; /**< Pointer to the allocated memory. */ #ifdef BUF_INIT_TRACKING const char *debug_file; @@ -85,8 +85,8 @@ */ struct gc_entry { - struct gc_entry *next; /**< Pointer to the next item in the - * linked list. */ + struct gc_entry *next; /**< Pointer to the next item in the + * linked list. */ }; /** @@ -114,8 +114,8 @@ */ struct gc_arena { - struct gc_entry *list; /**< First element of the linked list of - * \c gc_entry structures. */ + struct gc_entry *list; /**< First element of the linked list of + * \c gc_entry structures. */ struct gc_entry_special *list_special; }; @@ -140,7 +140,7 @@ size_t array_mult_safe(const size_t m1, const size_t m2, const size_t extr= a); -#define PA_BRACKET (1<<0) +#define PA_BRACKET (1 << 0) char *print_argv(const char **p, struct gc_arena *gc, const unsigned int f= lags); void buf_size_error(const size_t size); @@ -166,13 +166,15 @@ char *string_alloc_debug(const char *str, struct gc_arena *gc, const char = *file, int line); -struct buffer string_alloc_buf_debug(const char *str, struct gc_arena *gc,= const char *file, int line); +struct buffer string_alloc_buf_debug(const char *str, struct gc_arena *gc,= const char *file, + int line); #else /* ifdef DMALLOC */ struct buffer alloc_buf(size_t size); -struct buffer alloc_buf_gc(size_t size, struct gc_arena *gc); /* allocate= buffer with garbage collection */ +struct buffer alloc_buf_gc(size_t size, + struct gc_arena *gc); /* allocate buffer with g= arbage collection */ struct buffer clone_buf(const struct buffer *buf); @@ -197,8 +199,7 @@ * @param a gc_arena to use * @return new pointer */ -void * -gc_realloc(void *ptr, size_t size, struct gc_arena *a); +void *gc_realloc(void *ptr, size_t size, struct gc_arena *a); #ifdef BUF_INIT_TRACKING #define buf_init(buf, offset) buf_init_debug(buf, offset, __FILE__, __LINE= __) @@ -213,14 +214,14 @@ static inline void gc_freeaddrinfo_callback(void *addr) { - freeaddrinfo((struct addrinfo *) addr); + freeaddrinfo((struct addrinfo *)addr); } /** Return an empty struct buffer */ static inline struct buffer clear_buf(void) { - return (struct buffer) { 0 }; + return (struct buffer){ 0 }; } static inline bool @@ -361,7 +362,7 @@ { if (maxlen > 0) { - strncpy(dest, src, maxlen-1); + strncpy(dest, src, maxlen - 1); dest[maxlen - 1] =3D 0; } } @@ -416,9 +417,9 @@ SecureZeroMemory(data, len); #elif defined(__GNUC__) || defined(__clang__) memset(data, 0, len); - __asm__ __volatile__ ("" : : "r" (data) : "memory"); + __asm__ __volatile__("" : : "r"(data) : "memory"); #else - volatile char *p =3D (volatile char *) data; + volatile char *p =3D (volatile char *)data; while (len--) { *p++ =3D 0; @@ -435,12 +436,12 @@ bool buf_printf(struct buffer *buf, const char *format, ...) #ifdef __GNUC__ #if __USE_MINGW_ANSI_STDIO -__attribute__ ((format(gnu_printf, 2, 3))) + __attribute__((format(gnu_printf, 2, 3))) #else -__attribute__ ((format(__printf__, 2, 3))) + __attribute__((format(__printf__, 2, 3))) #endif #endif -; + ; /* * puts append to a buffer with overflow check @@ -493,12 +494,10 @@ /* * Hex dump -- Output a binary buffer to a hex string and return it. */ -#define FHE_SPACE_BREAK_MASK 0xFF /* space_break parameter in lower 8 bits= */ -#define FHE_CAPS 0x100 /* output hex in caps */ -char * -format_hex_ex(const uint8_t *data, int size, int maxoutput, - unsigned int space_break_flags, const char *separator, - struct gc_arena *gc); +#define FHE_SPACE_BREAK_MASK 0xFF /* space_break parameter in lower 8 bit= s */ +#define FHE_CAPS 0x100 /* output hex in caps */ +char *format_hex_ex(const uint8_t *data, int size, int maxoutput, unsigned= int space_break_flags, + const char *separator, struct gc_arena *gc); static inline char * format_hex(const uint8_t *data, int size, int maxoutput, struct gc_arena *= gc) @@ -725,16 +724,10 @@ } static inline bool -buf_copy_range(struct buffer *dest, - int dest_index, - const struct buffer *src, - int src_index, +buf_copy_range(struct buffer *dest, int dest_index, const struct buffer *s= rc, int src_index, int src_len) { - if (src_index < 0 - || src_len < 0 - || src_index + src_len > src->len - || dest_index < 0 + if (src_index < 0 || src_len < 0 || src_index + src_len > src->len || = dest_index < 0 || dest->offset + dest_index + src_len > dest->capacity) { return false; @@ -749,9 +742,7 @@ /* truncate src to len, copy excess data beyond len to dest */ static inline bool -buf_copy_excess(struct buffer *dest, - struct buffer *src, - int len) +buf_copy_excess(struct buffer *dest, struct buffer *src, int len) { if (len < 0) { @@ -879,44 +870,44 @@ /* character classes */ -#define CC_ANY (1<<0) /**< any character */ -#define CC_NULL (1<<1) /**< null character \0 */ +#define CC_ANY (1 << 0) /**< any character */ +#define CC_NULL (1 << 1) /**< null character \0 */ -#define CC_ALNUM (1<<2) /**< alphanumeric isalnum() */ -#define CC_ALPHA (1<<3) /**< alphabetic isalpha() */ -#define CC_ASCII (1<<4) /**< ASCII character */ -#define CC_CNTRL (1<<5) /**< control character iscntrl() */ -#define CC_DIGIT (1<<6) /**< digit isdigit() */ -#define CC_PRINT (1<<7) /**< printable (>=3D 32, !=3D 127) */ -#define CC_PUNCT (1<<8) /**< punctuation ispunct() */ -#define CC_SPACE (1<<9) /**< whitespace isspace() */ -#define CC_XDIGIT (1<<10) /**< hex digit isxdigit() */ +#define CC_ALNUM (1 << 2) /**< alphanumeric isalnum() */ +#define CC_ALPHA (1 << 3) /**< alphabetic isalpha() */ +#define CC_ASCII (1 << 4) /**< ASCII character */ +#define CC_CNTRL (1 << 5) /**< control character iscntrl() */ +#define CC_DIGIT (1 << 6) /**< digit isdigit() */ +#define CC_PRINT (1 << 7) /**< printable (>=3D 32, !=3D 127) */ +#define CC_PUNCT (1 << 8) /**< punctuation ispunct() */ +#define CC_SPACE (1 << 9) /**< whitespace isspace() */ +#define CC_XDIGIT (1 << 10) /**< hex digit isxdigit() */ -#define CC_BLANK (1<<11) /**< space or tab */ -#define CC_NEWLINE (1<<12) /**< newline */ -#define CC_CR (1<<13) /**< carriage return */ +#define CC_BLANK (1 << 11) /**< space or tab */ +#define CC_NEWLINE (1 << 12) /**< newline */ +#define CC_CR (1 << 13) /**< carriage return */ -#define CC_BACKSLASH (1<<14) /**< backslash */ -#define CC_UNDERBAR (1<<15) /**< underscore */ -#define CC_DASH (1<<16) /**< dash */ -#define CC_DOT (1<<17) /**< dot */ -#define CC_COMMA (1<<18) /**< comma */ -#define CC_COLON (1<<19) /**< colon */ -#define CC_SLASH (1<<20) /**< slash */ -#define CC_SINGLE_QUOTE (1<<21) /**< single quote */ -#define CC_DOUBLE_QUOTE (1<<22) /**< double quote */ -#define CC_REVERSE_QUOTE (1<<23) /**< reverse quote */ -#define CC_AT (1<<24) /**< at sign */ -#define CC_EQUAL (1<<25) /**< equal sign */ -#define CC_LESS_THAN (1<<26) /**< less than sign */ -#define CC_GREATER_THAN (1<<27) /**< greater than sign */ -#define CC_PIPE (1<<28) /**< pipe */ -#define CC_QUESTION_MARK (1<<29) /**< question mark */ -#define CC_ASTERISK (1<<30) /**< asterisk */ +#define CC_BACKSLASH (1 << 14) /**< backslash */ +#define CC_UNDERBAR (1 << 15) /**< underscore */ +#define CC_DASH (1 << 16) /**< dash */ +#define CC_DOT (1 << 17) /**< dot */ +#define CC_COMMA (1 << 18) /**< comma */ +#define CC_COLON (1 << 19) /**< colon */ +#define CC_SLASH (1 << 20) /**< slash */ +#define CC_SINGLE_QUOTE (1 << 21) /**< single quote */ +#define CC_DOUBLE_QUOTE (1 << 22) /**< double quote */ +#define CC_REVERSE_QUOTE (1 << 23) /**< reverse quote */ +#define CC_AT (1 << 24) /**< at sign */ +#define CC_EQUAL (1 << 25) /**< equal sign */ +#define CC_LESS_THAN (1 << 26) /**< less than sign */ +#define CC_GREATER_THAN (1 << 27) /**< greater than sign */ +#define CC_PIPE (1 << 28) /**< pipe */ +#define CC_QUESTION_MARK (1 << 29) /**< question mark */ +#define CC_ASTERISK (1 << 30) /**< asterisk */ /* macro classes */ -#define CC_NAME (CC_ALNUM|CC_UNDERBAR) /**< alphanumeric plu= s underscore */ -#define CC_CRLF (CC_CR|CC_NEWLINE) /**< carriage return or n= ewline */ +#define CC_NAME (CC_ALNUM | CC_UNDERBAR) /**< alphanumeric plus underscore= */ +#define CC_CRLF (CC_CR | CC_NEWLINE) /**< carriage return or newline */ bool char_class(const unsigned char c, const unsigned int flags); @@ -935,7 +926,8 @@ * @param replace The character to replace the specified character classes= with. * @return True if the string was not modified, false otherwise. */ -bool string_mod(char *str, const unsigned int inclusive, const unsigned in= t exclusive, const char replace); +bool string_mod(char *str, const unsigned int inclusive, const unsigned in= t exclusive, + const char replace); /** @@ -946,8 +938,8 @@ * @param exclusive Character classes that are not allowed even if they ar= e also in inclusive. * @return True if the string consists only of allowed characters, false o= therwise. */ -bool -string_check_buf(struct buffer *buf, const unsigned int inclusive, const u= nsigned int exclusive); +bool string_check_buf(struct buffer *buf, const unsigned int inclusive, + const unsigned int exclusive); /** * Returns a copy of a string with certain classes of characters of it rep= laced with a specified @@ -963,11 +955,8 @@ * * @return The modified string with characters replaced within the specifi= ed range. */ -const char *string_mod_const(const char *str, - const unsigned int inclusive, - const unsigned int exclusive, - const char replace, - struct gc_arena *gc); +const char *string_mod_const(const char *str, const unsigned int inclusive, + const unsigned int exclusive, const char repl= ace, struct gc_arena *gc); void string_replace_leading(char *str, const char match, const char replac= e); @@ -1051,51 +1040,51 @@ * Allocate memory to hold a structure */ -#define ALLOC_OBJ(dptr, type) \ - { \ - check_malloc_return((dptr) =3D (type *) malloc(sizeof(type))); \ +#define ALLOC_OBJ(dptr, type) \ + { \ + check_malloc_return((dptr) =3D (type *)malloc(sizeof(type))); \ } -#define ALLOC_OBJ_CLEAR(dptr, type) \ - { \ - ALLOC_OBJ(dptr, type); \ +#define ALLOC_OBJ_CLEAR(dptr, type) \ + { \ + ALLOC_OBJ(dptr, type); \ memset((dptr), 0, sizeof(type)); \ } -#define ALLOC_ARRAY(dptr, type, n) \ - { \ - check_malloc_return((dptr) =3D (type *) malloc(array_mult_safe(siz= eof(type), (n), 0))); \ +#define ALLOC_ARRAY(dptr, type, n) = \ + { = \ + check_malloc_return((dptr) =3D (type *)malloc(array_mult_safe(size= of(type), (n), 0))); \ } -#define ALLOC_ARRAY_GC(dptr, type, n, gc) \ - { \ - (dptr) =3D (type *) gc_malloc(array_mult_safe(sizeof(type), (n), 0= ), false, (gc)); \ +#define ALLOC_ARRAY_GC(dptr, type, n, gc) = \ + { = \ + (dptr) =3D (type *)gc_malloc(array_mult_safe(sizeof(type), (n), 0)= , false, (gc)); \ } -#define ALLOC_ARRAY_CLEAR(dptr, type, n) \ - { \ - ALLOC_ARRAY(dptr, type, n); \ +#define ALLOC_ARRAY_CLEAR(dptr, type, n) \ + { \ + ALLOC_ARRAY(dptr, type, n); \ memset((dptr), 0, (array_mult_safe(sizeof(type), (n), 0))); \ } -#define ALLOC_ARRAY_CLEAR_GC(dptr, type, n, gc) \ - { \ - (dptr) =3D (type *) gc_malloc(array_mult_safe(sizeof(type), (n), 0= ), true, (gc)); \ +#define ALLOC_ARRAY_CLEAR_GC(dptr, type, n, gc) = \ + { = \ + (dptr) =3D (type *)gc_malloc(array_mult_safe(sizeof(type), (n), 0)= , true, (gc)); \ } -#define ALLOC_VAR_ARRAY_CLEAR_GC(dptr, type, atype, n, gc) \ - { \ - (dptr) =3D (type *) gc_malloc(array_mult_safe(sizeof(atype), (n), = sizeof(type)), true, (gc)); \ +#define ALLOC_VAR_ARRAY_CLEAR_GC(dptr, type, atype, n, gc) = \ + { = \ + (dptr) =3D (type *)gc_malloc(array_mult_safe(sizeof(atype), (n), s= izeof(type)), true, (gc)); \ } -#define ALLOC_OBJ_GC(dptr, type, gc) \ - { \ - (dptr) =3D (type *) gc_malloc(sizeof(type), false, (gc)); \ +#define ALLOC_OBJ_GC(dptr, type, gc) \ + { \ + (dptr) =3D (type *)gc_malloc(sizeof(type), false, (gc)); \ } -#define ALLOC_OBJ_CLEAR_GC(dptr, type, gc) \ - { \ - (dptr) =3D (type *) gc_malloc(sizeof(type), true, (gc)); \ +#define ALLOC_OBJ_CLEAR_GC(dptr, type, gc) \ + { \ + (dptr) =3D (type *)gc_malloc(sizeof(type), true, (gc)); \ } static inline void @@ -1120,8 +1109,8 @@ { struct buffer_entry *head; /* next item to pop/peek */ struct buffer_entry *tail; /* last item pushed */ - int size; /* current number of entries */ - int max_size; /* maximum size list should grow to */ + int size; /* current number of entries */ + int max_size; /* maximum size list should grow to */ }; /** @@ -1209,8 +1198,7 @@ * @param max_len the maximum length of the aggregated buffer * @param sep the separator to put between buffers during aggregation */ -void buffer_list_aggregate_separator(struct buffer_list *bl, - const size_t max_len, const char *sep= ); +void buffer_list_aggregate_separator(struct buffer_list *bl, const size_t = max_len, const char *sep); struct buffer_list *buffer_list_file(const char *fn, int max_line_len); diff --git a/src/openvpn/circ_list.h b/src/openvpn/circ_list.h index cdbc8ef..eebf087 100644 --- a/src/openvpn/circ_list.h +++ b/src/openvpn/circ_list.h @@ -28,49 +28,46 @@ #include "error.h" #define CIRC_LIST(name, type) \ - struct name { \ - int x_head; \ - int x_size; \ - int x_cap; \ - int x_sizeof; \ - type x_list[]; \ + struct name \ + { \ + int x_head; \ + int x_size; \ + int x_cap; \ + int x_sizeof; \ + type x_list[]; \ } -#define CIRC_LIST_PUSH(obj, item) \ - { \ +#define CIRC_LIST_PUSH(obj, item) \ + { \ (obj)->x_head =3D modulo_add((obj)->x_head, -1, (obj)->x_cap); \ - (obj)->x_list[(obj)->x_head] =3D (item); \ - (obj)->x_size =3D min_int((obj)->x_size + 1, (obj)->x_cap); \ + (obj)->x_list[(obj)->x_head] =3D (item); \ + (obj)->x_size =3D min_int((obj)->x_size + 1, (obj)->x_cap); \ } -#define CIRC_LIST_SIZE(obj) \ - ((obj)->x_size) +#define CIRC_LIST_SIZE(obj) ((obj)->x_size) -#define CIRC_LIST_INDEX(obj, index) \ - modulo_add((obj)->x_head, \ - index_verify((index), (obj)->x_size, __FILE__, __LINE__), \ +#define CIRC_LIST_INDEX(obj, index) = \ + modulo_add((obj)->x_head, index_verify((index), (obj)->x_size, __FILE_= _, __LINE__), \ (obj)->x_cap) =20 -#define CIRC_LIST_ITEM(obj, index) \ - ((obj)->x_list[CIRC_LIST_INDEX((obj), (index))]) +#define CIRC_LIST_ITEM(obj, index) ((obj)->x_list[CIRC_LIST_INDEX((obj), (= index))]) #define CIRC_LIST_RESET(obj) \ - { \ - (obj)->x_head =3D 0; \ - (obj)->x_size =3D 0; \ + { \ + (obj)->x_head =3D 0; \ + (obj)->x_size =3D 0; \ } -#define CIRC_LIST_ALLOC(dest, list_type, size) \ - { \ +#define CIRC_LIST_ALLOC(dest, list_type, size) = \ + { = \ const int so =3D sizeof(list_type) + sizeof((dest)->x_list[0]) * (= size); \ - (dest) =3D (list_type *) malloc(so); \ - check_malloc_return(dest); \ - memset((dest), 0, so); \ - (dest)->x_cap =3D size; \ - (dest)->x_sizeof =3D so; \ + (dest) =3D (list_type *)malloc(so); = \ + check_malloc_return(dest); = \ + memset((dest), 0, so); = \ + (dest)->x_cap =3D size; = \ + (dest)->x_sizeof =3D so; = \ } -#define CIRC_LIST_FREE(dest) \ - free(dest) +#define CIRC_LIST_FREE(dest) free(dest) #endif /* ifndef CIRC_LIST_H */ diff --git a/src/openvpn/clinat.c b/src/openvpn/clinat.c index f120a54..a303285 100644 --- a/src/openvpn/clinat.c +++ b/src/openvpn/clinat.c @@ -32,8 +32,7 @@ #include "memdbg.h" static bool -add_entry(struct client_nat_option_list *dest, - const struct client_nat_entry *e) +add_entry(struct client_nat_option_list *dest, const struct client_nat_ent= ry *e) { if (dest->n >=3D MAX_CLIENT_NAT) { @@ -59,9 +58,7 @@ for (i =3D 0; i < list->n; ++i) { const struct client_nat_entry *e =3D &list->entries[i]; - msg(msglevel, " CNAT[%d] t=3D%d %s/%s/%s", - i, - e->type, + msg(msglevel, " CNAT[%d] t=3D%d %s/%s/%s", i, e->type, print_in_addr_t(e->network, IA_NET_ORDER, &gc), print_in_addr_t(e->netmask, IA_NET_ORDER, &gc), print_in_addr_t(e->foreign_network, IA_NET_ORDER, &gc)); @@ -102,11 +99,8 @@ } void -add_client_nat_to_option_list(struct client_nat_option_list *dest, - const char *type, - const char *network, - const char *netmask, - const char *foreign_network, +add_client_nat_to_option_list(struct client_nat_option_list *dest, const c= har *type, + const char *network, const char *netmask, co= nst char *foreign_network, int msglevel) { struct client_nat_entry e; @@ -179,9 +173,7 @@ dirstr =3D "IN"; } - msg(msglevel, "** CNAT %s %s %s -> %s", - dirstr, - prefix, + msg(msglevel, "** CNAT %s %s %s -> %s", dirstr, prefix, print_in_addr_t(iph->saddr, IA_NET_ORDER, &gc), print_in_addr_t(iph->daddr, IA_NET_ORDER, &gc)); @@ -189,11 +181,10 @@ } void -client_nat_transform(const struct client_nat_option_list *list, - struct buffer *ipbuf, +client_nat_transform(const struct client_nat_option_list *list, struct buf= fer *ipbuf, const int direction) { - struct ip_tcp_udp_hdr *h =3D (struct ip_tcp_udp_hdr *) BPTR(ipbuf); + struct ip_tcp_udp_hdr *h =3D (struct ip_tcp_udp_hdr *)BPTR(ipbuf); int i; uint32_t addr, *addr_ptr; const uint32_t *from, *to; diff --git a/src/openvpn/clinat.h b/src/openvpn/clinat.h index d565a49..abfa0b7 100644 --- a/src/openvpn/clinat.h +++ b/src/openvpn/clinat.h @@ -30,7 +30,8 @@ #define CN_OUTGOING 0 #define CN_INCOMING 1 -struct client_nat_entry { +struct client_nat_entry +{ #define CN_SNAT 0 #define CN_DNAT 1 int type; @@ -39,28 +40,27 @@ in_addr_t foreign_network; }; -struct client_nat_option_list { +struct client_nat_option_list +{ int n; struct client_nat_entry entries[MAX_CLIENT_NAT]; }; struct client_nat_option_list *new_client_nat_list(struct gc_arena *gc); -struct client_nat_option_list *clone_client_nat_option_list(const struct c= lient_nat_option_list *src, struct gc_arena *gc); +struct client_nat_option_list *clone_client_nat_option_list( + const struct client_nat_option_list *src, struct gc_arena *gc); -void copy_client_nat_option_list(struct client_nat_option_list *dest, cons= t struct client_nat_option_list *src); +void copy_client_nat_option_list(struct client_nat_option_list *dest, + const struct client_nat_option_list *src); void print_client_nat_list(const struct client_nat_option_list *list, int = msglevel); -void add_client_nat_to_option_list(struct client_nat_option_list *dest, - const char *type, - const char *network, - const char *netmask, - const char *foreign_network, - int msglevel); +void add_client_nat_to_option_list(struct client_nat_option_list *dest, co= nst char *type, + const char *network, const char *netmas= k, + const char *foreign_network, int msglev= el); -void client_nat_transform(const struct client_nat_option_list *list, - struct buffer *ipbuf, +void client_nat_transform(const struct client_nat_option_list *list, struc= t buffer *ipbuf, const int direction); #endif /* if !defined(CLINAT_H) */ diff --git a/src/openvpn/common.h b/src/openvpn/common.h index d7f5d959..c0947da 100644 --- a/src/openvpn/common.h +++ b/src/openvpn/common.h @@ -27,7 +27,7 @@ * Statistics counters and associated printf format. */ typedef uint64_t counter_type; -#define counter_format "%" PRIu64 +#define counter_format "%" PRIu64 /* * Time intervals @@ -37,17 +37,17 @@ /* * Used as an upper bound for timeouts. */ -#define BIG_TIMEOUT (60*60*24*7) /* one week (in seconds) */ +#define BIG_TIMEOUT (60 * 60 * 24 * 7) /* one week (in seconds) */ /* * Printf formats for special types */ #ifdef _WIN64 -#define ptr_format "0x%016" PRIx64 +#define ptr_format "0x%016" PRIx64 #else -#define ptr_format "0x%08lx" +#define ptr_format "0x%08lx" #endif -#define fragment_header_format "0x%08x" +#define fragment_header_format "0x%08x" /* these are used to cast the arguments * and MUST match the formats above */ @@ -94,6 +94,7 @@ /* * Script security warning */ -#define SCRIPT_SECURITY_WARNING "WARNING: External program may not be call= ed unless '--script-security 2' or higher is enabled. See --help text or ma= n page for detailed info." +#define SCRIPT_SECURITY_WARNING \ + "WARNING: External program may not be called unless '--script-security= 2' or higher is enabled. See --help text or man page for detailed info." #endif /* ifndef COMMON_H */ diff --git a/src/openvpn/comp-lz4.c b/src/openvpn/comp-lz4.c index 425b1d9..6736469 100644 --- a/src/openvpn/comp-lz4.c +++ b/src/openvpn/comp-lz4.c @@ -56,8 +56,7 @@ /* Doesn't do any actual compression anymore */ static void -lz4_compress(struct buffer *buf, struct buffer work, - struct compress_context *compctx, +lz4_compress(struct buffer *buf, struct buffer work, struct compress_conte= xt *compctx, const struct frame *frame) { if (buf->len <=3D 0) @@ -78,8 +77,7 @@ /* Doesn't do any actual compression anymore */ static void -lz4v2_compress(struct buffer *buf, struct buffer work, - struct compress_context *compctx, +lz4v2_compress(struct buffer *buf, struct buffer work, struct compress_con= text *compctx, const struct frame *frame) { if (buf->len <=3D 0) @@ -91,14 +89,13 @@ } static void -do_lz4_decompress(size_t zlen_max, - struct buffer *work, - struct buffer *buf, +do_lz4_decompress(size_t zlen_max, struct buffer *work, struct buffer *buf, struct compress_context *compctx) { int uncomp_len; ASSERT(buf_safe(work, zlen_max)); - uncomp_len =3D LZ4_decompress_safe((const char *)BPTR(buf), (char *)BP= TR(work), (size_t)BLEN(buf), zlen_max); + uncomp_len =3D LZ4_decompress_safe((const char *)BPTR(buf), (char *)BP= TR(work), (size_t)BLEN(buf), + zlen_max); if (uncomp_len <=3D 0) { dmsg(D_COMP_ERRORS, "LZ4 decompression error: %d", uncomp_len); @@ -117,12 +114,11 @@ } static void -lz4_decompress(struct buffer *buf, struct buffer work, - struct compress_context *compctx, +lz4_decompress(struct buffer *buf, struct buffer work, struct compress_con= text *compctx, const struct frame *frame) { size_t zlen_max =3D frame->buf.payload_size; - uint8_t c; /* flag indicating whether or not our peer compres= sed */ + uint8_t c; /* flag indicating whether or not our peer compressed */ if (buf->len <=3D 0) { @@ -155,12 +151,11 @@ } static void -lz4v2_decompress(struct buffer *buf, struct buffer work, - struct compress_context *compctx, +lz4v2_decompress(struct buffer *buf, struct buffer work, struct compress_c= ontext *compctx, const struct frame *frame) { size_t zlen_max =3D frame->buf.payload_size; - uint8_t c; /* flag indicating whether or not our peer compres= sed */ + uint8_t c; /* flag indicating whether or not our peer compressed */ if (buf->len <=3D 0) { @@ -203,19 +198,9 @@ } } -const struct compress_alg lz4_alg =3D { - "lz4", - lz4_compress_init, - lz4_compress_uninit, - lz4_compress, - lz4_decompress -}; +const struct compress_alg lz4_alg =3D { "lz4", lz4_compress_init, lz4_comp= ress_uninit, lz4_compress, + lz4_decompress }; -const struct compress_alg lz4v2_alg =3D { - "lz4v2", - lz4v2_compress_init, - lz4_compress_uninit, - lz4v2_compress, - lz4v2_decompress -}; +const struct compress_alg lz4v2_alg =3D { "lz4v2", lz4v2_compress_init, lz= 4_compress_uninit, + lz4v2_compress, lz4v2_decompress }; #endif /* ENABLE_LZ4 */ diff --git a/src/openvpn/comp.c b/src/openvpn/comp.c index afea948..1a2e775 100644 --- a/src/openvpn/comp.c +++ b/src/openvpn/comp.c @@ -171,10 +171,10 @@ { #ifdef USE_COMP msg(msglevel, "Compression or compression stub framing is not allo= wed " - "since data-channel offloading is enabled."); + "since data-channel offloading is enabled."); #else msg(msglevel, "Compression or compression stub framing is not allo= wed " - "since OpenVPN was built without compression support."); + "since OpenVPN was built without compression support= ."); #endif return false; } @@ -182,14 +182,14 @@ if ((info->flags & COMP_F_ALLOW_STUB_ONLY) && comp_non_stub_enabled(in= fo)) { msg(msglevel, "Compression is not allowed since allow-compression = is " - "set to 'stub-only'"); + "set to 'stub-only'"); return false; } #ifndef ENABLE_LZ4 if (info->alg =3D=3D COMP_ALGV2_LZ4 || info->alg =3D=3D COMP_ALG_LZ4) { msg(msglevel, "OpenVPN is compiled without LZ4 support. Requested " - "compression cannot be enabled."); + "compression cannot be enabled."); return false; } #endif @@ -197,7 +197,7 @@ if (info->alg =3D=3D COMP_ALG_LZO) { msg(msglevel, "OpenVPN is compiled without LZO support. Requested " - "compression cannot be enabled."); + "compression cannot be enabled."); return false; } #endif diff --git a/src/openvpn/comp.h b/src/openvpn/comp.h index a1c885b..265e15d 100644 --- a/src/openvpn/comp.h +++ b/src/openvpn/comp.h @@ -33,21 +33,22 @@ /* Compression flags */ /* Removed #define COMP_F_ADAPTIVE (1<<0) / * COMP_ALG_LZO only * / - #define COMP_F_ALLOW_COMPRESS (1<<1) / * not only incoming is compr= essed but also outgoing * / + #define COMP_F_ALLOW_COMPRESS (1<<1) / * not only incoming is compr= essed but also outgoing * + / */ /** initial command byte is swapped with last byte in buffer to preserve p= ayload alignment */ -#define COMP_F_SWAP (1<<2) +#define COMP_F_SWAP (1 << 2) /** tell server that we only support compression stubs */ -#define COMP_F_ADVERTISE_STUBS_ONLY (1<<3) +#define COMP_F_ADVERTISE_STUBS_ONLY (1 << 3) /** Only accept stub compression, even with COMP_F_ADVERTISE_STUBS_ONLY * we still accept other compressions to be pushed */ -#define COMP_F_ALLOW_STUB_ONLY (1<<4) +#define COMP_F_ALLOW_STUB_ONLY (1 << 4) /** push stub-v2 or comp-lzo no when we see a client with comp-lzo in occ = */ -#define COMP_F_MIGRATE (1<<5) +#define COMP_F_MIGRATE (1 << 5) /** Compression was explicitly set to allow asymetric compression */ -#define COMP_F_ALLOW_ASYM (1<<6) +#define COMP_F_ALLOW_ASYM (1 << 6) /** Do not allow compression framing (breaks DCO) */ -#define COMP_F_ALLOW_NOCOMP_ONLY (1<<7) +#define COMP_F_ALLOW_NOCOMP_ONLY (1 << 7) /* algorithms */ #define COMP_ALG_UNDEF 0 @@ -60,7 +61,7 @@ /* algorithm v2 */ #define COMP_ALGV2_UNCOMPRESSED 10 -#define COMP_ALGV2_LZ4 11 +#define COMP_ALGV2_LZ4 11 /* #define COMP_ALGV2_LZO 12 #define COMP_ALGV2_SNAPPY 13 @@ -79,8 +80,7 @@ static inline bool comp_non_stub_enabled(const struct compress_options *info) { - return info->alg !=3D COMP_ALGV2_UNCOMPRESSED - && info->alg !=3D COMP_ALG_STUB + return info->alg !=3D COMP_ALGV2_UNCOMPRESSED && info->alg !=3D COMP_A= LG_STUB && info->alg !=3D COMP_ALG_UNDEF; } @@ -89,8 +89,7 @@ * flags of allow-compression and also the whether algorithms are compiled * in */ -bool -check_compression_settings_valid(struct compress_options *info, int msglev= el); +bool check_compression_settings_valid(struct compress_options *info, int m= sglevel); #ifdef USE_COMP #include "buffer.h" @@ -109,18 +108,18 @@ /* V1 on wire codes */ /* Initial command byte to tell our peer if we compressed */ -#define LZO_COMPRESS_BYTE 0x66 -#define LZ4_COMPRESS_BYTE 0x69 +#define LZO_COMPRESS_BYTE 0x66 +#define LZ4_COMPRESS_BYTE 0x69 #define NO_COMPRESS_BYTE 0xFA /** to maintain payload alignment, replace this byte with last byte of pac= ket */ #define NO_COMPRESS_BYTE_SWAP 0xFB /* V2 on wire code */ -#define COMP_ALGV2_INDICATOR_BYTE 0x50 -#define COMP_ALGV2_UNCOMPRESSED_BYTE 0 -#define COMP_ALGV2_LZ4_BYTE 1 -#define COMP_ALGV2_LZO_BYTE 2 -#define COMP_ALGV2_SNAPPY_BYTE 3 +#define COMP_ALGV2_INDICATOR_BYTE 0x50 +#define COMP_ALGV2_UNCOMPRESSED_BYTE 0 +#define COMP_ALGV2_LZ4_BYTE 1 +#define COMP_ALGV2_LZO_BYTE 2 +#define COMP_ALGV2_SNAPPY_BYTE 3 /* * Compress worst case size expansion (for any algorithm) @@ -129,7 +128,7 @@ * Snappy: len + len/6 + 32 * LZ4: len + len/255 + 16 (LZ4_COMPRESSBOUND(len)) */ -#define COMP_EXTRA_BUFFER(len) ((len)/6 + 128 + 3 + COMP_PREFIX_LEN) +#define COMP_EXTRA_BUFFER(len) ((len) / 6 + 128 + 3 + COMP_PREFIX_LEN) /* * Don't try to compress any packet smaller than this. @@ -147,12 +146,10 @@ const char *name; void (*compress_init)(struct compress_context *compctx); void (*compress_uninit)(struct compress_context *compctx); - void (*compress)(struct buffer *buf, struct buffer work, - struct compress_context *compctx, + void (*compress)(struct buffer *buf, struct buffer work, struct compre= ss_context *compctx, const struct frame *frame); - void (*decompress)(struct buffer *buf, struct buffer work, - struct compress_context *compctx, + void (*decompress)(struct buffer *buf, struct buffer work, struct comp= ress_context *compctx, const struct frame *frame); }; diff --git a/src/openvpn/compstub.c b/src/openvpn/compstub.c index 853e9ee..bf709df 100644 --- a/src/openvpn/compstub.c +++ b/src/openvpn/compstub.c @@ -45,8 +45,7 @@ } static void -stub_compress(struct buffer *buf, struct buffer work, - struct compress_context *compctx, +stub_compress(struct buffer *buf, struct buffer work, struct compress_cont= ext *compctx, const struct frame *frame) { if (buf->len <=3D 0) @@ -56,7 +55,7 @@ if (compctx->flags & COMP_F_SWAP) { uint8_t *head =3D BPTR(buf); - uint8_t *tail =3D BEND(buf); + uint8_t *tail =3D BEND(buf); ASSERT(buf_safe(buf, 1)); ++buf->len; @@ -72,8 +71,7 @@ } static void -stub_decompress(struct buffer *buf, struct buffer work, - struct compress_context *compctx, +stub_decompress(struct buffer *buf, struct buffer work, struct compress_co= ntext *compctx, const struct frame *frame) { uint8_t c; @@ -107,8 +105,7 @@ static void -stubv2_compress(struct buffer *buf, struct buffer work, - struct compress_context *compctx, +stubv2_compress(struct buffer *buf, struct buffer work, struct compress_co= ntext *compctx, const struct frame *frame) { if (buf->len <=3D 0) @@ -120,8 +117,7 @@ } static void -stubv2_decompress(struct buffer *buf, struct buffer work, - struct compress_context *compctx, +stubv2_decompress(struct buffer *buf, struct buffer work, struct compress_= context *compctx, const struct frame *frame) { if (buf->len <=3D 0) @@ -157,19 +153,9 @@ } } -const struct compress_alg compv2_stub_alg =3D { - "stubv2", - stub_compress_init, - stub_compress_uninit, - stubv2_compress, - stubv2_decompress -}; +const struct compress_alg compv2_stub_alg =3D { "stubv2", stub_compress_in= it, stub_compress_uninit, + stubv2_compress, stubv2_deco= mpress }; -const struct compress_alg comp_stub_alg =3D { - "stub", - stub_compress_init, - stub_compress_uninit, - stub_compress, - stub_decompress -}; +const struct compress_alg comp_stub_alg =3D { "stub", stub_compress_init, = stub_compress_uninit, + stub_compress, stub_decompress= }; #endif /* USE_STUB */ diff --git a/src/openvpn/console.c b/src/openvpn/console.c index 7cc4fff..bdceaf2 100644 --- a/src/openvpn/console.c +++ b/src/openvpn/console.c @@ -37,7 +37,7 @@ #endif -struct _query_user query_user[QUERY_USER_NUMSLOTS]; /* GLOBAL */ +struct _query_user query_user[QUERY_USER_NUMSLOTS]; /* GLOBAL */ void @@ -53,16 +53,14 @@ void -query_user_add(char *prompt, size_t prompt_len, - char *resp, size_t resp_len, - bool echo) +query_user_add(char *prompt, size_t prompt_len, char *resp, size_t resp_le= n, bool echo) { int i; /* Ensure input is sane. All these must be present otherwise it is * a programming error. */ - ASSERT( prompt_len > 0 && prompt !=3D NULL && resp_len > 0 && resp != =3D NULL ); + ASSERT(prompt_len > 0 && prompt !=3D NULL && resp_len > 0 && resp !=3D= NULL); /* Seek to the last unused slot */ for (i =3D 0; i < QUERY_USER_NUMSLOTS; i++) @@ -72,7 +70,7 @@ break; } } - ASSERT( i < QUERY_USER_NUMSLOTS ); /* Unlikely, but we want to panic = if it happens */ + ASSERT(i < QUERY_USER_NUMSLOTS); /* Unlikely, but we want to panic if = it happens */ /* Save the information needed for the user interaction */ query_user[i].prompt =3D prompt; diff --git a/src/openvpn/console.h b/src/openvpn/console.h index 3e99776..14b6116 100644 --- a/src/openvpn/console.h +++ b/src/openvpn/console.h @@ -30,16 +30,17 @@ /** * Configuration setup for declaring what kind of information to ask a us= er for */ -struct _query_user { - char *prompt; /**< Prompt to present to the user */ - size_t prompt_len; /**< Length of the prompt string */ - char *response; /**< The user's response */ - size_t response_len; /**< Length the of the user response */ - bool echo; /**< True: The user should see what is being= typed, otherwise mask it */ +struct _query_user +{ + char *prompt; /**< Prompt to present to the user */ + size_t prompt_len; /**< Length of the prompt string */ + char *response; /**< The user's response */ + size_t response_len; /**< Length the of the user response */ + bool echo; /**< True: The user should see what is being type= d, otherwise mask it */ }; #define QUERY_USER_NUMSLOTS 10 -extern struct _query_user query_user[]; /**< Global variable, declared in= console.c */ +extern struct _query_user query_user[]; /**< Global variable, declared in = console.c */ /** * Wipes all data put into all of the query_user structs @@ -58,9 +59,7 @@ * @param echo Should the user input be echoed to the user? If Fals= e, input will be masked * */ -void query_user_add(char *prompt, size_t prompt_len, - char *resp, size_t resp_len, - bool echo); +void query_user_add(char *prompt, size_t prompt_len, char *resp, size_t re= sp_len, bool echo); /** @@ -107,7 +106,7 @@ { return query_user_exec_builtin(); } -#endif /* defined(ENABLE_SYSTEMD) */ +#endif /* defined(ENABLE_SYSTEMD) */ /** @@ -118,9 +117,7 @@ * */ static inline bool -query_user_SINGLE(char *prompt, size_t prompt_len, - char *resp, size_t resp_len, - bool echo) +query_user_SINGLE(char *prompt, size_t prompt_len, char *resp, size_t resp= _len, bool echo) { query_user_clear(); query_user_add(prompt, prompt_len, resp, resp_len, echo); diff --git a/src/openvpn/console_builtin.c b/src/openvpn/console_builtin.c index b6db701..b0228dd 100644 --- a/src/openvpn/console_builtin.c +++ b/src/openvpn/console_builtin.c @@ -67,11 +67,10 @@ HANDLE in =3D GetStdHandle(STD_INPUT_HANDLE); int orig_stderr =3D get_orig_stderr(); /* guaranteed to be always vali= d */ - if ((in =3D=3D INVALID_HANDLE_VALUE) - || win32_service_interrupt(&win32_signal) + if ((in =3D=3D INVALID_HANDLE_VALUE) || win32_service_interrupt(&win32= _signal) || (_write(orig_stderr, prompt, strlen(prompt)) =3D=3D -1)) { - msg(M_WARN|M_ERRNO, "get_console_input_win32(): unexpected error"); + msg(M_WARN | M_ERRNO, "get_console_input_win32(): unexpected error= "); return false; } @@ -135,7 +134,7 @@ return false; } -#endif /* _WIN32 */ +#endif /* _WIN32 */ #ifdef HAVE_TERMIOS_H @@ -177,7 +176,7 @@ } } -#endif /* HAVE_TERMIOS_H */ +#endif /* HAVE_TERMIOS_H */ /** @@ -209,15 +208,17 @@ * (in which case neither stdin or stderr are connected to a tty and * /dev/tty can not be open()ed anymore) */ - if (!isatty(0) && !isatty(2) ) + if (!isatty(0) && !isatty(2)) { - int fd =3D open( "/dev/tty", O_RDWR ); + int fd =3D open("/dev/tty", O_RDWR); if (fd < 0) { - msg(M_FATAL, "neither stdin nor stderr are a tty device and yo= u have neither a " + msg(M_FATAL, + "neither stdin nor stderr are a tty device and you have ne= ither a " "controlling tty nor systemd - can't ask for '%s'. If you= used --daemon, " "you need to use --askpass to make passphrase-protected ke= ys work, and you " - "can not use --auth-nocache.", prompt ); + "can not use --auth-nocache.", + prompt); } close(fd); } @@ -285,8 +286,8 @@ /* Loop through configured query_user slots */ for (i =3D 0; i < QUERY_USER_NUMSLOTS && query_user[i].response !=3D N= ULL; i++) { - if (!get_console_input(query_user[i].prompt, query_user[i].echo, - query_user[i].response, query_user[i].respo= nse_len) ) + if (!get_console_input(query_user[i].prompt, query_user[i].echo, q= uery_user[i].response, + query_user[i].response_len)) { /* Force the final result state to failed on failure */ ret =3D false; diff --git a/src/openvpn/console_systemd.c b/src/openvpn/console_systemd.c index 36103b2..d277bd4 100644 --- a/src/openvpn/console_systemd.c +++ b/src/openvpn/console_systemd.c @@ -50,9 +50,7 @@ * mounted, as well as the systemd-ask-password executable * being available */ - return (sd_booted() > 0) - && (stat(SYSTEMD_ASK_PASSWORD_PATH, &c) =3D=3D 0); - + return (sd_booted() > 0) && (stat(SYSTEMD_ASK_PASSWORD_PATH, &c) =3D= =3D 0); } static bool @@ -79,7 +77,7 @@ return false; } memset(input, 0, capacity); - if (read(std_out, input, capacity-1) !=3D 0) + if (read(std_out, input, capacity - 1) !=3D 0) { chomp(input); ret =3D true; @@ -99,7 +97,7 @@ bool query_user_exec_systemd(void) { - bool ret =3D true; /* Presume everything goes okay */ + bool ret =3D true; /* Presume everything goes okay */ int i; /* If systemd is not available, use the default built-in mechanism */ @@ -112,7 +110,7 @@ for (i =3D 0; i < QUERY_USER_NUMSLOTS && query_user[i].response !=3D N= ULL; i++) { if (!get_console_input_systemd(query_user[i].prompt, query_user[i]= .echo, - query_user[i].response, query_user[= i].response_len) ) + query_user[i].response, query_user[= i].response_len)) { /* Force the final result state to failed on failure */ ret =3D false; diff --git a/src/openvpn/crypto.c b/src/openvpn/crypto.c index 1c1be46..af7583a 100644 --- a/src/openvpn/crypto.c +++ b/src/openvpn/crypto.c @@ -63,8 +63,7 @@ */ static void -openvpn_encrypt_aead(struct buffer *buf, struct buffer work, - struct crypto_options *opt) +openvpn_encrypt_aead(struct buffer *buf, struct buffer work, struct crypto= _options *opt) { struct gc_arena gc; int outlen =3D 0; @@ -88,7 +87,7 @@ /* Prepare IV */ { struct buffer iv_buffer; - uint8_t iv[OPENVPN_MAX_IV_LENGTH] =3D {0}; + uint8_t iv[OPENVPN_MAX_IV_LENGTH] =3D { 0 }; const int iv_len =3D cipher_ctx_iv_length(ctx->cipher); ASSERT(iv_len >=3D OPENVPN_AEAD_MIN_IV_LEN && iv_len <=3D OPENVPN_= MAX_IV_LENGTH); @@ -133,17 +132,14 @@ /* Buffer overflow check */ if (!buf_safe(&work, buf->len + mac_len + cipher_ctx_block_size(ctx->c= ipher))) { - msg(D_CRYPT_ERRORS, - "ENCRYPT: buffer size error, bc=3D%d bo=3D%d bl=3D%d wc=3D%d w= o=3D%d wl=3D%d", - buf->capacity, buf->offset, buf->len, work.capacity, work.offs= et, - work.len); + msg(D_CRYPT_ERRORS, "ENCRYPT: buffer size error, bc=3D%d bo=3D%d b= l=3D%d wc=3D%d wo=3D%d wl=3D%d", + buf->capacity, buf->offset, buf->len, work.capacity, work.offs= et, work.len); goto err; } /* For AEAD ciphers, authenticate Additional Data, including opcode */ ASSERT(cipher_ctx_update_ad(ctx->cipher, BPTR(&work), BLEN(&work))); - dmsg(D_PACKET_CONTENT, "ENCRYPT AD: %s", - format_hex(BPTR(&work), BLEN(&work), 0, &gc)); + dmsg(D_PACKET_CONTENT, "ENCRYPT AD: %s", format_hex(BPTR(&work), BLEN(= &work), 0, &gc)); if (!use_epoch_data_format) { @@ -159,7 +155,7 @@ /* update number of plaintext blocks encrypted. Use the (x + (n-1))/n = trick * to round up the result to the number of blocks used */ const int blocksize =3D AEAD_LIMIT_BLOCKSIZE; - opt->key_ctx_bi.encrypt.plaintext_blocks +=3D (outlen + (blocksize - 1= ))/blocksize; + opt->key_ctx_bi.encrypt.plaintext_blocks +=3D (outlen + (blocksize - 1= )) / blocksize; /* Flush the encryption buffer */ ASSERT(cipher_ctx_final(ctx->cipher, BEND(&work), &outlen)); @@ -191,8 +187,7 @@ } static void -openvpn_encrypt_v1(struct buffer *buf, struct buffer work, - struct crypto_options *opt) +openvpn_encrypt_v1(struct buffer *buf, struct buffer work, struct crypto_o= ptions *opt) { struct gc_arena gc; gc_init(&gc); @@ -206,7 +201,7 @@ /* Do Encrypt from buf -> work */ if (ctx->cipher) { - uint8_t iv_buf[OPENVPN_MAX_IV_LENGTH] =3D {0}; + uint8_t iv_buf[OPENVPN_MAX_IV_LENGTH] =3D { 0 }; const int iv_size =3D cipher_ctx_iv_length(ctx->cipher); int outlen; @@ -226,8 +221,7 @@ /* Put packet ID in plaintext buffer */ if (packet_id_initialized(&opt->packet_id) && !packet_id_write(&opt->packet_id.send, buf, - opt->flags & CO_PACKET_ID_LONG_FOR= M, - true)) + opt->flags & CO_PACKET_ID_LONG_FOR= M, true)) { msg(D_CRYPT_ERRORS, "ENCRYPT ERROR: packet ID roll ove= r"); goto err; @@ -252,8 +246,7 @@ ASSERT(buf_write(&work, iv_buf, iv_size)); dmsg(D_PACKET_CONTENT, "ENCRYPT IV: %s", format_hex(iv_buf, iv= _size, 0, &gc)); - dmsg(D_PACKET_CONTENT, "ENCRYPT FROM: %s", - format_hex(BPTR(buf), BLEN(buf), 80, &gc)); + dmsg(D_PACKET_CONTENT, "ENCRYPT FROM: %s", format_hex(BPTR(buf= ), BLEN(buf), 80, &gc)); /* cipher_ctx was already initialized with key & keylen */ ASSERT(cipher_ctx_reset(ctx->cipher, iv_buf)); @@ -261,13 +254,9 @@ /* Buffer overflow check */ if (!buf_safe(&work, buf->len + cipher_ctx_block_size(ctx->cip= her))) { - msg(D_CRYPT_ERRORS, "ENCRYPT: buffer size error, bc=3D%d b= o=3D%d bl=3D%d wc=3D%d wo=3D%d wl=3D%d cbs=3D%d", - buf->capacity, - buf->offset, - buf->len, - work.capacity, - work.offset, - work.len, + msg(D_CRYPT_ERRORS, + "ENCRYPT: buffer size error, bc=3D%d bo=3D%d bl=3D%d w= c=3D%d wo=3D%d wl=3D%d cbs=3D%d", + buf->capacity, buf->offset, buf->len, work.capacity, w= ork.offset, work.len, cipher_ctx_block_size(ctx->cipher)); goto err; } @@ -281,14 +270,13 @@ ASSERT(buf_inc_len(&work, outlen)); /* For all CBC mode ciphers, check the last block is complete = */ - ASSERT(cipher_ctx_mode(ctx->cipher) !=3D OPENVPN_MODE_CBC - || outlen =3D=3D iv_size); + ASSERT(cipher_ctx_mode(ctx->cipher) !=3D OPENVPN_MODE_CBC || o= utlen =3D=3D iv_size); } - else /* No Encryption */ + else /* No Encryption */ { if (packet_id_initialized(&opt->packet_id) - && !packet_id_write(&opt->packet_id.send, buf, - opt->flags & CO_PACKET_ID_LONG_FORM, t= rue)) + && !packet_id_write(&opt->packet_id.send, buf, opt->flags = & CO_PACKET_ID_LONG_FORM, + true)) { msg(D_CRYPT_ERRORS, "ENCRYPT ERROR: packet ID roll over"); goto err; @@ -317,8 +305,7 @@ *buf =3D work; - dmsg(D_PACKET_CONTENT, "ENCRYPT TO: %s", - format_hex(BPTR(&work), BLEN(&work), 80, &gc)); + dmsg(D_PACKET_CONTENT, "ENCRYPT TO: %s", format_hex(BPTR(&work), B= LEN(&work), 80, &gc)); } gc_free(&gc); @@ -332,8 +319,7 @@ } void -openvpn_encrypt(struct buffer *buf, struct buffer work, - struct crypto_options *opt) +openvpn_encrypt(struct buffer *buf, struct buffer work, struct crypto_opti= ons *opt) { if (buf->len > 0 && opt) { @@ -380,10 +366,8 @@ } bool -crypto_check_replay(struct crypto_options *opt, - const struct packet_id_net *pin, uint16_t epoch, - const char *error_prefix, - struct gc_arena *gc) +crypto_check_replay(struct crypto_options *opt, const struct packet_id_net= *pin, uint16_t epoch, + const char *error_prefix, struct gc_arena *gc) { bool ret =3D false; struct packet_id_rec *recv; @@ -400,8 +384,10 @@ { /* We have an epoch that is neither current or old recv key but * is authenticated, ie we need to move to a new current recv key = */ - msg(D_GENKEY, "Received data packet with new epoch %d. Updating " - "receive key", epoch); + msg(D_GENKEY, + "Received data packet with new epoch %d. Updating " + "receive key", + epoch); epoch_replace_update_recv_key(opt, epoch); recv =3D &opt->packet_id.rec; } @@ -420,7 +406,8 @@ { if (!(opt->flags & CO_MUTE_REPLAY_WARNINGS)) { - msg(D_REPLAY_ERRORS, "%s: bad packet ID (may be a replay): %s = -- " + msg(D_REPLAY_ERRORS, + "%s: bad packet ID (may be a replay): %s -- " "see the man page entry for --replay-window for " "more info or silence this warning with --mute-replay-warn= ings", error_prefix, packet_id_net_print(pin, true, gc)); @@ -438,9 +425,8 @@ * On success, buf is set to point to plaintext, true is returned. */ static bool -openvpn_decrypt_aead(struct buffer *buf, struct buffer work, - struct crypto_options *opt, const struct frame *frame, - const uint8_t *ad_start) +openvpn_decrypt_aead(struct buffer *buf, struct buffer work, struct crypto= _options *opt, + const struct frame *frame, const uint8_t *ad_start) { static const char error_prefix[] =3D "AEAD Decrypt error"; struct packet_id_net pin =3D { 0 }; @@ -462,8 +448,7 @@ ASSERT(buf->len > 0); ASSERT(ctx->cipher); - dmsg(D_PACKET_CONTENT, "DECRYPT FROM: %s", - format_hex(BPTR(buf), BLEN(buf), 80, &gc)); + dmsg(D_PACKET_CONTENT, "DECRYPT FROM: %s", format_hex(BPTR(buf), BLEN(= buf), 80, &gc)); ASSERT(ad_start >=3D buf->data && ad_start <=3D BPTR(buf)); @@ -571,28 +556,24 @@ /* feed in tag and the authenticated data */ ASSERT(cipher_ctx_update_ad(ctx->cipher, ad_start, ad_size)); - dmsg(D_PACKET_CONTENT, "DECRYPT AD: %s", - format_hex(ad_start, ad_size, 0, &gc)); + dmsg(D_PACKET_CONTENT, "DECRYPT AD: %s", format_hex(ad_start, ad_size,= 0, &gc)); /* Decrypt and authenticate packet */ int outlen; - if (!cipher_ctx_update(ctx->cipher, BPTR(&work), &outlen, BPTR(buf), - data_len)) + if (!cipher_ctx_update(ctx->cipher, BPTR(&work), &outlen, BPTR(buf), d= ata_len)) { CRYPT_ERROR("packet decryption failed"); } ASSERT(buf_inc_len(&work, outlen)); - if (!cipher_ctx_final_check_tag(ctx->cipher, BPTR(&work) + outlen, - &outlen, tag_ptr, tag_size)) + if (!cipher_ctx_final_check_tag(ctx->cipher, BPTR(&work) + outlen, &ou= tlen, tag_ptr, tag_size)) { ctx->failed_verifications++; CRYPT_DROP("packet tag authentication failed"); } ASSERT(buf_inc_len(&work, outlen)); - dmsg(D_PACKET_CONTENT, "DECRYPT TO: %s", - format_hex(BPTR(&work), BLEN(&work), 80, &gc)); + dmsg(D_PACKET_CONTENT, "DECRYPT TO: %s", format_hex(BPTR(&work), BLEN(= &work), 80, &gc)); if (!crypto_check_replay(opt, &pin, epoch, error_prefix, &gc)) { @@ -603,7 +584,7 @@ /* update number of plaintext blocks decrypted. Use the (x + (n-1))/n = trick * to round up the result to the number of blocks used. */ const int blocksize =3D AEAD_LIMIT_BLOCKSIZE; - opt->key_ctx_bi.decrypt.plaintext_blocks +=3D (outlen + (blocksize - 1= ))/blocksize; + opt->key_ctx_bi.decrypt.plaintext_blocks +=3D (outlen + (blocksize - 1= )) / blocksize; *buf =3D work; @@ -626,8 +607,8 @@ * On success, buf is set to point to plaintext, true is returned. */ static bool -openvpn_decrypt_v1(struct buffer *buf, struct buffer work, - struct crypto_options *opt, const struct frame *frame) +openvpn_decrypt_v1(struct buffer *buf, struct buffer work, struct crypto_o= ptions *opt, + const struct frame *frame) { static const char error_prefix[] =3D "Authenticate/Decrypt packet erro= r"; struct gc_arena gc; @@ -639,8 +620,7 @@ struct packet_id_net pin; bool have_pin =3D false; - dmsg(D_PACKET_CONTENT, "DECRYPT FROM: %s", - format_hex(BPTR(buf), BLEN(buf), 80, &gc)); + dmsg(D_PACKET_CONTENT, "DECRYPT FROM: %s", format_hex(BPTR(buf), B= LEN(buf), 80, &gc)); /* Verify the HMAC */ if (ctx->hmac) @@ -722,8 +702,7 @@ } ASSERT(buf_inc_len(&work, outlen)); - dmsg(D_PACKET_CONTENT, "DECRYPT TO: %s", - format_hex(BPTR(&work), BLEN(&work), 80, &gc)); + dmsg(D_PACKET_CONTENT, "DECRYPT TO: %s", format_hex(BPTR(&work= ), BLEN(&work), 80, &gc)); /* Get packet ID from plaintext buffer or IV, depending on cip= her mode */ { @@ -731,7 +710,8 @@ { if (packet_id_initialized(&opt->packet_id)) { - if (!packet_id_read(&pin, &work, BOOL_CAST(opt->fl= ags & CO_PACKET_ID_LONG_FORM))) + if (!packet_id_read(&pin, &work, + BOOL_CAST(opt->flags & CO_PACK= ET_ID_LONG_FORM))) { CRYPT_ERROR("error reading CBC packet-id"); } @@ -790,9 +770,8 @@ bool -openvpn_decrypt(struct buffer *buf, struct buffer work, - struct crypto_options *opt, const struct frame *frame, - const uint8_t *ad_start) +openvpn_decrypt(struct buffer *buf, struct buffer work, struct crypto_opti= ons *opt, + const struct frame *frame, const uint8_t *ad_start) { bool ret =3D false; @@ -815,9 +794,7 @@ } unsigned int -calculate_crypto_overhead(const struct key_type *kt, - unsigned int pkt_id_size, - bool occ) +calculate_crypto_overhead(const struct key_type *kt, unsigned int pkt_id_s= ize, bool occ) { unsigned int crypto_overhead =3D 0; @@ -866,9 +843,8 @@ unsigned int crypto_max_overhead(void) { - return packet_id_size(true) + OPENVPN_MAX_IV_LENGTH - +OPENVPN_MAX_CIPHER_BLOCK_SIZE - +max_int(OPENVPN_MAX_HMAC_SIZE, OPENVPN_AEAD_TAG_LENGTH); + return packet_id_size(true) + OPENVPN_MAX_IV_LENGTH + OPENVPN_MAX_CIPH= ER_BLOCK_SIZE + + max_int(OPENVPN_MAX_HMAC_SIZE, OPENVPN_AEAD_TAG_LENGTH); } static void @@ -876,12 +852,13 @@ { if (cipher_kt_insecure(ciphername)) { - msg(M_WARN, "WARNING: INSECURE cipher (%s) with block size less th= an 128" + msg(M_WARN, + "WARNING: INSECURE cipher (%s) with block size less than 128" " bit (%d bit). This allows attacks like SWEET32. Mitigate b= y " "using a --cipher with a larger block size (e.g. AES-256-CBC).= " "Support for these insecure ciphers will be removed in " "OpenVPN 2.7.", - ciphername, cipher_kt_block_size(ciphername)*8); + ciphername, cipher_kt_block_size(ciphername) * 8); } } @@ -889,8 +866,8 @@ * Build a struct key_type. */ void -init_key_type(struct key_type *kt, const char *ciphername, - const char *authname, bool tls_mode, bool warn) +init_key_type(struct key_type *kt, const char *ciphername, const char *aut= hname, bool tls_mode, + bool warn) { bool aead_cipher =3D false; @@ -908,12 +885,11 @@ /* check legal cipher mode */ aead_cipher =3D cipher_kt_mode_aead(kt->cipher); - if (!(cipher_kt_mode_cbc(kt->cipher) - || (tls_mode && aead_cipher) + if (!(cipher_kt_mode_cbc(kt->cipher) || (tls_mode && aead_cipher) #ifdef ENABLE_OFB_CFB_MODE || (tls_mode && cipher_kt_mode_ofb_cfb(kt->cipher)) #endif - )) + )) { msg(M_FATAL, "Cipher '%s' mode not supported", ciphername); } @@ -932,9 +908,9 @@ if (warn) { msg(M_WARN, "******* WARNING *******: '--cipher none' was spec= ified. " - "This means NO encryption will be performed and tunnelled " - "data WILL be transmitted in clear text over the network! " - "PLEASE DO RECONSIDER THIS SETTING!"); + "This means NO encryption will be performed and tu= nnelled " + "data WILL be transmitted in clear text over the n= etwork! " + "PLEASE DO RECONSIDER THIS SETTING!"); } } kt->digest =3D authname; @@ -959,10 +935,10 @@ if (warn) { msg(M_WARN, "******* WARNING *******: '--auth none' was specif= ied. " - "This means no authentication will be performed on receive= d " - "packets, meaning you CANNOT trust that the data received = by " - "the remote side have NOT been manipulated. " - "PLEASE DO RECONSIDER THIS SETTING!"); + "This means no authentication will be performed on= received " + "packets, meaning you CANNOT trust that the data r= eceived by " + "the remote side have NOT been manipulated. " + "PLEASE DO RECONSIDER THIS SETTING!"); } } } @@ -1011,9 +987,8 @@ /* given a key and key_type, build a key_ctx */ void -init_key_ctx(struct key_ctx *ctx, const struct key_parameters *key, - const struct key_type *kt, int enc, - const char *prefix) +init_key_ctx(struct key_ctx *ctx, const struct key_parameters *key, const = struct key_type *kt, + int enc, const char *prefix) { struct gc_arena gc =3D gc_new(); CLEAR(*ctx); @@ -1024,14 +999,13 @@ cipher_ctx_init(ctx->cipher, key->cipher, kt->cipher, enc); const char *ciphername =3D cipher_kt_name(kt->cipher); - msg(D_CIPHER_INIT, "%s: Cipher '%s' initialized with %d bit key", - prefix, ciphername, cipher_kt_key_size(kt->cipher) * 8); + msg(D_CIPHER_INIT, "%s: Cipher '%s' initialized with %d bit key", = prefix, ciphername, + cipher_kt_key_size(kt->cipher) * 8); dmsg(D_SHOW_KEYS, "%s: CIPHER KEY: %s", prefix, format_hex(key->cipher, cipher_kt_key_size(kt->cipher), 0, &g= c)); - dmsg(D_CRYPTO_DEBUG, "%s: CIPHER block_size=3D%d iv_size=3D%d", - prefix, cipher_kt_block_size(kt->cipher), - cipher_kt_iv_size(kt->cipher)); + dmsg(D_CRYPTO_DEBUG, "%s: CIPHER block_size=3D%d iv_size=3D%d", pr= efix, + cipher_kt_block_size(kt->cipher), cipher_kt_iv_size(kt->ciphe= r)); warn_insecure_key_type(ciphername); } @@ -1041,18 +1015,14 @@ ctx->hmac =3D hmac_ctx_new(); hmac_ctx_init(ctx->hmac, key->hmac, kt->digest); - msg(D_CIPHER_INIT, - "%s: Using %d bit message hash '%s' for HMAC authentication", - prefix, md_kt_size(kt->digest) * 8, md_kt_name(kt->digest)); + msg(D_CIPHER_INIT, "%s: Using %d bit message hash '%s' for HMAC au= thentication", prefix, + md_kt_size(kt->digest) * 8, md_kt_name(kt->digest)); dmsg(D_SHOW_KEYS, "%s: HMAC KEY: %s", prefix, format_hex(key->hmac, md_kt_size(kt->digest), 0, &gc)); - dmsg(D_CRYPTO_DEBUG, "%s: HMAC size=3D%d block_size=3D%d", - prefix, - md_kt_size(kt->digest), + dmsg(D_CRYPTO_DEBUG, "%s: HMAC size=3D%d block_size=3D%d", prefix,= md_kt_size(kt->digest), hmac_ctx_size(ctx->hmac)); - } ctx->epoch =3D key->epoch; gc_free(&gc); @@ -1083,8 +1053,8 @@ } void -init_key_ctx_bi(struct key_ctx_bi *ctx, const struct key2 *key2, - int key_direction, const struct key_type *kt, const char *= name) +init_key_ctx_bi(struct key_ctx_bi *ctx, const struct key2 *key2, int key_d= irection, + const struct key_type *kt, const char *name) { struct key_direction_state kds; @@ -1174,39 +1144,34 @@ struct gc_arena gc =3D gc_new(); CLEAR(*key); - if (!rand_bytes(key->cipher, cipher_len) - || !rand_bytes(key->hmac, hmac_len)) + if (!rand_bytes(key->cipher, cipher_len) || !rand_bytes(key->hmac, hma= c_len)) { msg(M_FATAL, "ERROR: Random number generator cannot obtain entropy= for key generation"); } - dmsg(D_SHOW_KEY_SOURCE, "Cipher source entropy: %s", format_hex(key->c= ipher, cipher_len, 0, &gc)); + dmsg(D_SHOW_KEY_SOURCE, "Cipher source entropy: %s", + format_hex(key->cipher, cipher_len, 0, &gc)); dmsg(D_SHOW_KEY_SOURCE, "HMAC source entropy: %s", format_hex(key->hma= c, hmac_len, 0, &gc)); gc_free(&gc); } static void -key_print(const struct key *key, - const struct key_type *kt, - const char *prefix) +key_print(const struct key *key, const struct key_type *kt, const char *pr= efix) { struct gc_arena gc =3D gc_new(); - dmsg(D_SHOW_KEY_SOURCE, "%s (cipher, %s, %d bits): %s", - prefix, cipher_kt_name(kt->cipher), cipher_kt_key_size(kt->cipher= ) * 8, + dmsg(D_SHOW_KEY_SOURCE, "%s (cipher, %s, %d bits): %s", prefix, cipher= _kt_name(kt->cipher), + cipher_kt_key_size(kt->cipher) * 8, format_hex(key->cipher, cipher_kt_key_size(kt->cipher), 0, &gc)); - dmsg(D_SHOW_KEY_SOURCE, "%s (hmac, %s, %d bits): %s", - prefix, md_kt_name(kt->digest), md_kt_size(kt->digest) * 8, - format_hex(key->hmac, md_kt_size(kt->digest), 0, &gc)); + dmsg(D_SHOW_KEY_SOURCE, "%s (hmac, %s, %d bits): %s", prefix, md_kt_na= me(kt->digest), + md_kt_size(kt->digest) * 8, format_hex(key->hmac, md_kt_size(kt->= digest), 0, &gc)); gc_free(&gc); } /** * Prints the keys in a key2 structure. */ void -key2_print(const struct key2 *k, - const struct key_type *kt, - const char *prefix0, +key2_print(const struct key2 *k, const struct key_type *kt, const char *pr= efix0, const char *prefix1) { ASSERT(k->n =3D=3D 2); @@ -1248,11 +1213,10 @@ ASSERT(cipher_ctx_iv_length(cipher) >=3D OPENVPN_AEAD_MIN_IV_L= EN); /* Generate dummy implicit IV */ - ASSERT(rand_bytes(co->key_ctx_bi.encrypt.implicit_iv, - OPENVPN_MAX_IV_LENGTH)); + ASSERT(rand_bytes(co->key_ctx_bi.encrypt.implicit_iv, OPENVPN_= MAX_IV_LENGTH)); - memcpy(co->key_ctx_bi.decrypt.implicit_iv, - co->key_ctx_bi.encrypt.implicit_iv, OPENVPN_MAX_IV_LENG= TH); + memcpy(co->key_ctx_bi.decrypt.implicit_iv, co->key_ctx_bi.encr= ypt.implicit_iv, + OPENVPN_MAX_IV_LENGTH); } } @@ -1317,11 +1281,9 @@ } void -crypto_read_openvpn_key(const struct key_type *key_type, - struct key_ctx_bi *ctx, const char *key_file, - bool key_inline, const int key_direction, - const char *key_name, const char *opt_name, - struct key2 *keydata) +crypto_read_openvpn_key(const struct key_type *key_type, struct key_ctx_bi= *ctx, + const char *key_file, bool key_inline, const int k= ey_direction, + const char *key_name, const char *opt_name, struct= key2 *keydata) { struct key2 key2; struct key_direction_state kds; @@ -1335,7 +1297,8 @@ if (key2.n !=3D 2) { - msg(M_ERR, "File '%s' does not have OpenVPN Static Key format. Us= ing " + msg(M_ERR, + "File '%s' does not have OpenVPN Static Key format. Using " "free-form passphrase file is not supported anymore.", print_key_filename(key_file, key_inline)); } @@ -1374,7 +1337,7 @@ struct gc_arena gc =3D gc_new(); struct buffer in; int size; - uint8_t hex_byte[3] =3D {0, 0, 0}; + uint8_t hex_byte[3] =3D { 0, 0, 0 }; /* parse info */ const unsigned char *cp; @@ -1384,17 +1347,17 @@ int match =3D 0; /* output */ - uint8_t *out =3D (uint8_t *) &key2->keys; + uint8_t *out =3D (uint8_t *)&key2->keys; const int keylen =3D sizeof(key2->keys); int count =3D 0; /* parse states */ -#define PARSE_INITIAL 0 -#define PARSE_HEAD 1 -#define PARSE_DATA 2 -#define PARSE_DATA_COMPLETE 3 -#define PARSE_FOOT 4 -#define PARSE_FINISHED 5 +#define PARSE_INITIAL 0 +#define PARSE_HEAD 1 +#define PARSE_DATA 2 +#define PARSE_DATA_COMPLETE 3 +#define PARSE_FOOT 4 +#define PARSE_FINISHED 5 int state =3D PARSE_INITIAL; /* constants */ @@ -1506,11 +1469,9 @@ } else { - msg(M_FATAL, - (isprint(c) ? printable_char_fmt : unprintable_cha= r_fmt), - c, line_num, - print_key_filename(file, flags & RKF_INLINE), coun= t, - onekeylen, keylen); + msg(M_FATAL, (isprint(c) ? printable_char_fmt : unprin= table_char_fmt), c, + line_num, print_key_filename(file, flags & RKF_INL= INE), count, onekeylen, + keylen); } } ++line_index; @@ -1524,22 +1485,21 @@ */ key2->n =3D count / onekeylen; - ASSERT(key2->n >=3D 0 && key2->n <=3D (int) SIZE(key2->keys)); + ASSERT(key2->n >=3D 0 && key2->n <=3D (int)SIZE(key2->keys)); if (flags & RKF_MUST_SUCCEED) { if (!key2->n) { - msg(M_FATAL, "Insufficient key material or header text not fou= nd in file '%s' (%d/%d/%d bytes found/min/max)", - print_key_filename(file, flags & RKF_INLINE), count, oneke= ylen, - keylen); + msg(M_FATAL, + "Insufficient key material or header text not found in fil= e '%s' (%d/%d/%d bytes found/min/max)", + print_key_filename(file, flags & RKF_INLINE), count, oneke= ylen, keylen); } if (state !=3D PARSE_FINISHED) { msg(M_FATAL, "Footer text not found in file '%s' (%d/%d/%d byt= es found/min/max)", - print_key_filename(file, flags & RKF_INLINE), count, oneke= ylen, - keylen); + print_key_filename(file, flags & RKF_INLINE), count, oneke= ylen, keylen); } } @@ -1598,12 +1558,7 @@ generate_key_random(&key); /* format key as ascii */ - fmt =3D format_hex_ex((const uint8_t *)&key, - sizeof(key), - 0, - bytes_per_line, - "\n", - &gc); + fmt =3D format_hex_ex((const uint8_t *)&key, sizeof(key), 0, bytes= _per_line, "\n", &gc); /* write to holding buffer */ buf_printf(&out, "%s\n", fmt); @@ -1616,7 +1571,7 @@ buf_printf(&out, "%s\n", static_key_foot); /* write key file to stdout if no filename given */ - if (!filename || strcmp(filename, "")=3D=3D0) + if (!filename || strcmp(filename, "") =3D=3D 0) { printf("%.*s\n", BLEN(&out), BPTR(&out)); } @@ -1641,9 +1596,14 @@ if (key2->n < n) { #ifdef ENABLE_SMALL - msg(M_FATAL, "Key file '%s' used in --%s contains insufficient key= material [keys found=3D%d required=3D%d]", filename, option, key2->n, n); + msg(M_FATAL, + "Key file '%s' used in --%s contains insufficient key material= [keys found=3D%d required=3D%d]", + filename, option, key2->n, n); #else - msg(M_FATAL, "Key file '%s' used in --%s contains insufficient key= material [keys found=3D%d required=3D%d] -- try generating a new key file = with '" PACKAGE " --genkey secret [file]', or use the existing key file in = bidirectional mode by specifying --%s without a key direction parameter", f= ilename, option, key2->n, n, option); + msg(M_FATAL, + "Key file '%s' used in --%s contains insufficient key material= [keys found=3D%d required=3D%d] -- try generating a new key file with '" P= ACKAGE + " --genkey secret [file]', or use the existing key file in bid= irectional mode by specifying --%s without a key direction parameter", + filename, option, key2->n, n, option); #endif } } @@ -1739,8 +1699,8 @@ /* This should be a very improbable failure */ if (!check_key(&key2->keys[i], kt)) { - msg(M_FATAL, "Key #%d in '%s' is bad. Try making a new key wi= th --genkey.", - i+1, shared_secret_file); + msg(M_FATAL, "Key #%d in '%s' is bad. Try making a new key wi= th --genkey.", i + 1, + shared_secret_file); } } } @@ -1767,9 +1727,7 @@ void print_cipher(const char *ciphername) { - printf("%s (%d bit key, ", - cipher_kt_name(ciphername), - cipher_kt_key_size(ciphername) * 8); + printf("%s (%d bit key, ", cipher_kt_name(ciphername), cipher_kt_key_= size(ciphername) * 8); if (cipher_kt_block_size(ciphername) =3D=3D 1) { @@ -1855,14 +1813,13 @@ goto cleanup; } buf_set_read(&server_key_buf, (void *)&server_key, sizeof(server_key)); - if (!crypto_pem_encode(pem_name, &server_key_pem, - &server_key_buf, &gc)) + if (!crypto_pem_encode(pem_name, &server_key_pem, &server_key_buf, &gc= )) { msg(M_WARN, "ERROR: could not PEM-encode key"); goto cleanup; } - if (!filename || strcmp(filename, "")=3D=3D0) + if (!filename || strcmp(filename, "") =3D=3D 0) { printf("%.*s", BLEN(&server_key_pem), BPTR(&server_key_pem)); } @@ -1898,8 +1855,7 @@ } bool -read_pem_key_file(struct buffer *key, const char *pem_name, - const char *key_file, bool key_inline) +read_pem_key_file(struct buffer *key, const char *pem_name, const char *ke= y_file, bool key_inline) { bool ret =3D false; struct buffer key_pem =3D { 0 }; @@ -1910,8 +1866,7 @@ key_pem =3D buffer_read_from_file(key_file, &gc); if (!buf_valid(&key_pem)) { - msg(M_WARN, "ERROR: failed to read %s file (%s)", - pem_name, key_file); + msg(M_WARN, "ERROR: failed to read %s file (%s)", pem_name, ke= y_file); goto cleanup; } } @@ -1948,9 +1903,8 @@ uint8_t out[8]; uint8_t expected_out[] =3D { 'q', 'D', '\xfe', '%', '@', 's', 'u', '\x= 95' }; - int ret =3D ssl_tls1_PRF((uint8_t *)seed, (int) strlen(seed), - (uint8_t *)secret, (int) strlen(secret), - out, sizeof(out)); + int ret =3D ssl_tls1_PRF((uint8_t *)seed, (int)strlen(seed), (uint8_t = *)secret, + (int)strlen(secret), out, sizeof(out)); return (ret && memcmp(out, expected_out, sizeof(out)) =3D=3D 0); } diff --git a/src/openvpn/crypto.h b/src/openvpn/crypto.h index b6f3549..cee4145 100644 --- a/src/openvpn/crypto.h +++ b/src/openvpn/crypto.h @@ -129,7 +129,8 @@ #include "mtu.h" /** Wrapper struct to pass around SHA256 digests */ -struct sha256_digest { +struct sha256_digest +{ uint8_t digest[SHA256_DIGEST_LENGTH]; }; @@ -138,8 +139,8 @@ */ struct key_type { - const char *cipher; /**< const name of the cipher */ - const char *digest; /**< Message digest static parameters */ + const char *cipher; /**< const name of the cipher */ + const char *digest; /**< Message digest static parameters */ }; /** @@ -158,7 +159,8 @@ /** internal structure similar to struct key that holds key information * but is not represented on wire and can be changed/extended */ -struct key_parameters { +struct key_parameters +{ /** %Key material for cipher operations. */ uint8_t cipher[MAX_CIPHER_KEY_LENGTH]; @@ -184,10 +186,10 @@ * @param key_params destination for the converted struct * @param key source of the conversion */ -void -key_parameters_from_key(struct key_parameters *key_params, const struct ke= y *key); +void key_parameters_from_key(struct key_parameters *key_params, const stru= ct key *key); -struct epoch_key { +struct epoch_key +{ uint8_t epoch_key[SHA256_DIGEST_LENGTH]; uint16_t epoch; }; @@ -198,8 +200,8 @@ */ struct key_ctx { - cipher_ctx_t *cipher; /**< Generic cipher %context. */ - hmac_ctx_t *hmac; /**< Generic HMAC %context. */ + cipher_ctx_t *cipher; /**< Generic cipher %context. */ + hmac_ctx_t *hmac; /**< Generic HMAC %context. */ /** * This implicit IV will be always XORed with the packet id that is se= nt on * the wire to get the IV. For the common AEAD ciphers of AES-GCM and @@ -213,7 +215,7 @@ */ uint8_t implicit_iv[OPENVPN_MAX_IV_LENGTH]; /**< The implicit part of the IV */ - size_t implicit_iv_len; /**< The length of implicit_iv */ + size_t implicit_iv_len; /**< The length of implicit_iv */ /** Counter for the number of plaintext block encrypted using this cip= her * with the current key in number of 128 bit blocks (only used for * AEAD ciphers) */ @@ -236,12 +238,12 @@ */ struct key2 { - int n; /**< The number of \c key objects stored - * in the \c key2.keys array. */ - struct key keys[2]; /**< Two unidirectional sets of %key - * material. The first key is the client - * (encrypts) to server (decrypts), the - * second the server to client key. */ + int n; /**< The number of \c key objects stored + * in the \c key2.keys array. */ + struct key keys[2]; /**< Two unidirectional sets of %key + * material. The first key is the client + * (encrypts) to server (decrypts), the + * second the server to client key. */ }; /** @@ -255,18 +257,18 @@ */ struct key_direction_state { - int out_key; /**< Index into the \c key2.keys array for - * the sending direction. */ - int in_key; /**< Index into the \c key2.keys array for - * the receiving direction. */ - int need_keys; /**< The number of key objects necessary - * to support both sending and - * receiving. - * - * This will be 1 if the same keys are - * used in both directions, or 2 if - * there are two sets of unidirectional - * keys. */ + int out_key; /**< Index into the \c key2.keys array for + * the sending direction. */ + int in_key; /**< Index into the \c key2.keys array for + * the receiving direction. */ + int need_keys; /**< The number of key objects necessary + * to support both sending and + * receiving. + * + * This will be 1 if the same keys are + * used in both directions, or 2 if + * there are two sets of unidirectional + * keys. */ }; /** @@ -276,10 +278,10 @@ */ struct key_ctx_bi { - struct key_ctx encrypt; /**< Cipher and/or HMAC contexts for sendi= ng - * direction. */ - struct key_ctx decrypt; /**< cipher and/or HMAC contexts for - * receiving direction. */ + struct key_ctx encrypt; /**< Cipher and/or HMAC contexts for sending + * direction. */ + struct key_ctx decrypt; /**< cipher and/or HMAC contexts for + * receiving direction. */ bool initialized; }; @@ -340,54 +342,58 @@ * keeping state between successive * OpenVPN process startups. */ -#define CO_PACKET_ID_LONG_FORM (1<<0) +#define CO_PACKET_ID_LONG_FORM (1 << 0) /**< Bit-flag indicating whether to use - * OpenVPN's long packet ID format. */ -#define CO_IGNORE_PACKET_ID (1<<1) + * OpenVPN's long packet ID format. */ +#define CO_IGNORE_PACKET_ID (1 << 1) /**< Bit-flag indicating whether to ignore * the packet ID of a received packet. * This flag is used during processing * of the first packet received from a * client. */ -#define CO_MUTE_REPLAY_WARNINGS (1<<2) +#define CO_MUTE_REPLAY_WARNINGS (1 << 2) /**< Bit-flag indicating not to display * replay warnings. */ -#define CO_USE_TLS_KEY_MATERIAL_EXPORT (1<<3) +#define CO_USE_TLS_KEY_MATERIAL_EXPORT (1 << 3) /**< Bit-flag indicating that data channel key derivation * is done using TLS keying material export [RFC5705] */ -#define CO_RESEND_WKC (1<<4) +#define CO_RESEND_WKC (1 << 4) /**< Bit-flag indicating that the client is expected to * resend the wrapped client key with the 2nd packet (packet-id 1) * like with the HARD_RESET_CLIENT_V3 packet */ -#define CO_FORCE_TLSCRYPTV2_COOKIE (1<<5) +#define CO_FORCE_TLSCRYPTV2_COOKIE (1 << 5) /**< Bit-flag indicating that we do not allow clients that do * not support resending the wrapped client key (WKc) with the * third packet of the three-way handshake */ -#define CO_USE_CC_EXIT_NOTIFY (1<<6) +#define CO_USE_CC_EXIT_NOTIFY (1 << 6) /**< Bit-flag indicating that explicit exit notifies should be * sent via the control channel instead of using an OCC message */ -#define CO_USE_DYNAMIC_TLS_CRYPT (1<<7) +#define CO_USE_DYNAMIC_TLS_CRYPT (1 << 7) /**< Bit-flag indicating that renegotiations are using tls-crypt * with a TLS-EKM derived key. */ -#define CO_EPOCH_DATA_KEY_FORMAT (1<<8) +#define CO_EPOCH_DATA_KEY_FORMAT (1 << 8) /**< Bit-flag indicating the epoch the data format. This format * has the AEAD tag at the end of the packet and is using a longer * 64-bit packet id that is split into a 16 bit epoch and 48 bit * epoch counter */ - unsigned int flags; /**< Bit-flags determining behavior of - * security operation functions. */ + unsigned int flags; /**< Bit-flags determining behavior of + * security operation functions. */ }; -#define CRYPT_ERROR_EXIT(flags, format) \ - do { msg(flags, "%s: " format, error_prefix); goto error_exit; } while= (false) +#define CRYPT_ERROR_EXIT(flags, format) \ + do \ + { \ + msg(flags, "%s: " format, error_prefix); \ + goto error_exit; \ + } while (false) #define CRYPT_ERROR(format) CRYPT_ERROR_EXIT(D_CRYPT_ERRORS, format) -#define CRYPT_DROP(format) CRYPT_ERROR_EXIT(D_MULTI_DROPPED, format) +#define CRYPT_DROP(format) CRYPT_ERROR_EXIT(D_MULTI_DROPPED, format) /** * Minimal IV length for AEAD mode ciphers (in bytes): @@ -395,8 +401,8 @@ */ #define OPENVPN_AEAD_MIN_IV_LEN (sizeof(packet_id_type) + 8) -#define RKF_MUST_SUCCEED (1<<0) -#define RKF_INLINE (1<<1) +#define RKF_MUST_SUCCEED (1 << 0) +#define RKF_INLINE (1 << 1) void read_key_file(struct key2 *key2, const char *file, const unsigned int= flags); /** @@ -418,30 +424,26 @@ * more ciphers than static key mode. * @param warn Print warnings when null cipher / auth is used. */ -void init_key_type(struct key_type *kt, const char *ciphername, - const char *authname, bool tls_mode, bool warn); +void init_key_type(struct key_type *kt, const char *ciphername, const char= *authname, bool tls_mode, + bool warn); /* * Key context functions */ -void init_key_ctx(struct key_ctx *ctx, const struct key_parameters *key, - const struct key_type *kt, int enc, - const char *prefix); +void init_key_ctx(struct key_ctx *ctx, const struct key_parameters *key, c= onst struct key_type *kt, + int enc, const char *prefix); -void -init_key_bi_ctx_send(struct key_ctx *ctx, const struct key_parameters *key, - const struct key_type *kt, const char *name); +void init_key_bi_ctx_send(struct key_ctx *ctx, const struct key_parameters= *key, + const struct key_type *kt, const char *name); -void -init_key_bi_ctx_recv(struct key_ctx *ctx, const struct key_parameters *key, - const struct key_type *kt, const char *name); +void init_key_bi_ctx_recv(struct key_ctx *ctx, const struct key_parameters= *key, + const struct key_type *kt, const char *name); void free_key_ctx(struct key_ctx *ctx); -void init_key_ctx_bi(struct key_ctx_bi *ctx, const struct key2 *key2, - int key_direction, const struct key_type *kt, - const char *name); +void init_key_ctx_bi(struct key_ctx_bi *ctx, const struct key2 *key2, int = key_direction, + const struct key_type *kt, const char *name); void free_key_ctx_bi(struct key_ctx_bi *ctx); @@ -476,8 +478,7 @@ * contain the processed packet ready for sending, or be empty if an * error occurred. */ -void openvpn_encrypt(struct buffer *buf, struct buffer work, - struct crypto_options *opt); +void openvpn_encrypt(struct buffer *buf, struct buffer work, struct crypto= _options *opt); /** @@ -513,9 +514,8 @@ * the plaintext packet ready for further processing, or be empty if * an error occurred. */ -bool openvpn_decrypt(struct buffer *buf, struct buffer work, - struct crypto_options *opt, const struct frame *frame, - const uint8_t *ad_start); +bool openvpn_decrypt(struct buffer *buf, struct buffer work, struct crypto= _options *opt, + const struct frame *frame, const uint8_t *ad_start); /** @} name Functions for performing security operations on data channel p= ackets */ @@ -530,11 +530,8 @@ * * @return true if packet ID is validated to be not a replay, false otherw= ise. */ -bool crypto_check_replay(struct crypto_options *opt, - const struct packet_id_net *pin, - uint16_t epoch, - const char *error_prefix, - struct gc_arena *gc); +bool crypto_check_replay(struct crypto_options *opt, const struct packet_i= d_net *pin, + uint16_t epoch, const char *error_prefix, struct = gc_arena *gc); /** Calculate the maximum overhead that our encryption has @@ -550,10 +547,8 @@ * incorrect way as all previous OpenVPN versions did= , to * end up with identical numbers for OCC compatibility */ -unsigned int -calculate_crypto_overhead(const struct key_type *kt, - unsigned int pkt_id_size, - bool occ); +unsigned int calculate_crypto_overhead(const struct key_type *kt, unsigned= int pkt_id_size, + bool occ); /** Return the worst-case OpenVPN crypto overhead (in bytes) */ unsigned int crypto_max_overhead(void); @@ -565,8 +560,7 @@ * @param filename Filename of the server key file to create. * @param key_name The name to use in the PEM header/footer. */ -void -write_pem_key_file(const char *filename, const char *key_name); +void write_pem_key_file(const char *filename, const char *key_name); /** * Generate ephermal key material into the key structure @@ -575,8 +569,7 @@ * @param pem_name the name used for logging * @return true if key generation was successful */ -bool -generate_ephemeral_key(struct buffer *key, const char *pem_name); +bool generate_ephemeral_key(struct buffer *key, const char *pem_name); /** * Read key material from a PEM encoded files into the key structure @@ -588,9 +581,8 @@ * otherwise. * @return true if reading into key was successful */ -bool -read_pem_key_file(struct buffer *key, const char *pem_name, - const char *key_file, bool key_inline); +bool read_pem_key_file(struct buffer *key, const char *pem_name, const cha= r *key_file, + bool key_inline); /* * Message digest-based pseudo random number generator. @@ -631,16 +623,12 @@ const char *keydirection2ascii(int kd, bool remote, bool humanreadable); /* print keys */ -void key2_print(const struct key2 *k, - const struct key_type *kt, - const char *prefix0, +void key2_print(const struct key2 *k, const struct key_type *kt, const cha= r *prefix0, const char *prefix1); -void crypto_read_openvpn_key(const struct key_type *key_type, - struct key_ctx_bi *ctx, const char *key_file, - bool key_inline, const int key_direction, - const char *key_name, const char *opt_name, - struct key2 *keydata); +void crypto_read_openvpn_key(const struct key_type *key_type, struct key_c= tx_bi *ctx, + const char *key_file, bool key_inline, const = int key_direction, + const char *key_name, const char *opt_name, s= truct key2 *keydata); /* * Inline functions @@ -690,12 +678,12 @@ if (cipher_defined(kt.cipher) && !cipher_valid(kt.cipher)) { msg(M_WARN, "ERROR: --%s requires %s support.", optname, kt.cipher= ); - return (struct key_type) { 0 }; + return (struct key_type){ 0 }; } if (md_defined(kt.digest) && !md_valid(kt.digest)) { msg(M_WARN, "ERROR: --%s requires %s support.", optname, kt.digest= ); - return (struct key_type) { 0 }; + return (struct key_type){ 0 }; } return kt; @@ -710,8 +698,7 @@ * For reference see the OpenVPN RFC draft and * https://www.ietf.org/archive/id/draft-irtf-cfrg-aead-limits-08.html */ -uint64_t -cipher_get_aead_limits(const char *ciphername); +uint64_t cipher_get_aead_limits(const char *ciphername); /** * Check if the number of failed decryption is over the acceptable limit. @@ -724,7 +711,7 @@ * but we accept slightly lower security bound for the edge * of Chacha20-Poly1305 and packets over 16k as MTUs over 16k are * extremely rarely used */ - return ctx->failed_verifications > (1ull << 36); + return ctx->failed_verifications > (1ull << 36); } /** @@ -735,7 +722,7 @@ cipher_decrypt_verify_fail_warn(const struct key_ctx *ctx) { /* Use 2**35, half the amount after which we refuse to decrypt */ - return ctx->failed_verifications > (1ull << 35); + return ctx->failed_verifications > (1ull << 35); } @@ -744,7 +731,7 @@ * * Since cipher_ctx_block_size() is not reliable and will return 1 in many * cases use a hardcoded blocksize instead */ -#define AEAD_LIMIT_BLOCKSIZE 16 +#define AEAD_LIMIT_BLOCKSIZE 16 /** * Checks if the current TLS library supports the TLS 1.0 PRF with MD5+SHA1 @@ -761,13 +748,12 @@ * to read. */ static inline bool -aead_usage_limit_reached(const uint64_t limit, const struct key_ctx *key_c= tx, - int64_t higest_pid) +aead_usage_limit_reached(const uint64_t limit, const struct key_ctx *key_c= tx, int64_t higest_pid) { /* This is the q + s <=3D p^(1/2) * 2^(129/2) - 1 calculation where * q is the number of protected messages (highest_pid) * s Total plaintext length in all messages (in blocks) */ - return (limit > 0 && key_ctx->plaintext_blocks + (uint64_t) higest_pid= > limit); + return (limit > 0 && key_ctx->plaintext_blocks + (uint64_t)higest_pid = > limit); } #endif /* CRYPTO_H */ diff --git a/src/openvpn/crypto_backend.h b/src/openvpn/crypto_backend.h index df5bc4d..59418f6 100644 --- a/src/openvpn/crypto_backend.h +++ b/src/openvpn/crypto_backend.h @@ -45,18 +45,20 @@ #define OPENVPN_MAX_CIPHER_BLOCK_SIZE 32 /* Maximum HMAC digest size (bytes) */ -#define OPENVPN_MAX_HMAC_SIZE 64 +#define OPENVPN_MAX_HMAC_SIZE 64 /** Types referencing specific message digest hashing algorithms */ -typedef enum { +typedef enum +{ MD_SHA1, MD_SHA256 } hash_algo_type; /** Struct used in cipher name translation table */ -typedef struct { - const char *openvpn_name; /**< Cipher name used by OpenVPN */ - const char *lib_name; /**< Cipher name used by crypto library */ +typedef struct +{ + const char *openvpn_name; /**< Cipher name used by OpenVPN */ + const char *lib_name; /**< Cipher name used by crypto library */ } cipher_name_pair; /** Cipher name translation table */ @@ -122,8 +124,8 @@ * * @return true iff PEM encode succeeded. */ -bool crypto_pem_encode(const char *name, struct buffer *dst, - const struct buffer *src, struct gc_arena *gc); +bool crypto_pem_encode(const char *name, struct buffer *dst, const struct = buffer *src, + struct gc_arena *gc); /** * Decode a PEM buffer to binary data. @@ -134,8 +136,7 @@ * * @return true iff PEM decode succeeded. */ -bool crypto_pem_decode(const char *name, struct buffer *dst, - const struct buffer *src); +bool crypto_pem_decode(const char *name, struct buffer *dst, const struct = buffer *src); /* * @@ -338,8 +339,8 @@ * @param enc Whether to encrypt or decrypt (either * \c OPENVPN_OP_ENCRYPT or \c OPENVPN_OP_DECRYPT). */ -void cipher_ctx_init(cipher_ctx_t *ctx, const uint8_t *key, - const char *ciphername, crypto_operation_t enc); +void cipher_ctx_init(cipher_ctx_t *ctx, const uint8_t *key, const char *ci= phername, + crypto_operation_t enc); /** * Returns the size of the IV used by the cipher, in bytes, or 0 if no IV = is @@ -447,8 +448,7 @@ * * @return \c 0 on failure, \c 1 on success. */ -int cipher_ctx_update(cipher_ctx_t *ctx, uint8_t *dst, int *dst_len, - uint8_t *src, int src_len); +int cipher_ctx_update(cipher_ctx_t *ctx, uint8_t *dst, int *dst_len, uint8= _t *src, int src_len); /** * Pads the final cipher block using PKCS padding, and output to the desti= nation @@ -475,8 +475,8 @@ * * @return \c 0 on failure, \c 1 on success. */ -int cipher_ctx_final_check_tag(cipher_ctx_t *ctx, uint8_t *dst, int *dst_l= en, - uint8_t *tag, size_t tag_len); +int cipher_ctx_final_check_tag(cipher_ctx_t *ctx, uint8_t *dst, int *dst_l= en, uint8_t *tag, + size_t tag_len); /* @@ -716,7 +716,7 @@ * * @return true if successful, false on any error */ -bool ssl_tls1_PRF(const uint8_t *seed, int seed_len, const uint8_t *secret, - int secret_len, uint8_t *output, int output_len); +bool ssl_tls1_PRF(const uint8_t *seed, int seed_len, const uint8_t *secret= , int secret_len, + uint8_t *output, int output_len); #endif /* CRYPTO_BACKEND_H_ */ diff --git a/src/openvpn/crypto_epoch.c b/src/openvpn/crypto_epoch.c index 741ad23..b5cbc8d 100644 --- a/src/openvpn/crypto_epoch.c +++ b/src/openvpn/crypto_epoch.c @@ -39,9 +39,8 @@ #include "integer.h" void -ovpn_hkdf_expand(const uint8_t *secret, - const uint8_t *info, int info_len, - uint8_t *out, int out_len) +ovpn_hkdf_expand(const uint8_t *secret, const uint8_t *info, int info_len,= uint8_t *out, + int out_len) { hmac_ctx_t *hmac_ctx =3D hmac_ctx_new(); hmac_ctx_init(hmac_ctx, secret, "SHA256"); @@ -74,13 +73,10 @@ } bool -ovpn_expand_label(const uint8_t *secret, size_t secret_len, - const uint8_t *label, size_t label_len, - const uint8_t *context, size_t context_len, - uint8_t *out, uint16_t out_len) +ovpn_expand_label(const uint8_t *secret, size_t secret_len, const uint8_t = *label, size_t label_len, + const uint8_t *context, size_t context_len, uint8_t *out= , uint16_t out_len) { - if (secret_len !=3D 32 || label_len > 250 || context_len > 255 - || label_len < 1) + if (secret_len !=3D 32 || label_len > 250 || context_len > 255 || labe= l_len < 1) { /* Our current implementation is not a general purpose one * and assumes that the secret size matches the size of the @@ -92,7 +88,7 @@ struct gc_arena gc =3D gc_new(); /* 2 byte for the outlen encoded as uint16, 5 bytes for "ovpn ", * 1 byte for context len byte and 1 byte for label len byte */ - const uint8_t *label_prefix =3D (const uint8_t *) ("ovpn "); + const uint8_t *label_prefix =3D (const uint8_t *)("ovpn "); int prefix_len =3D 5; int hkdf_label_len =3D 2 + prefix_len + 1 + label_len + 1 + context_le= n; @@ -111,8 +107,7 @@ ASSERT(buf_len(&hkdf_label) =3D=3D hkdf_label_len); - ovpn_hkdf_expand(secret, buf_bptr(&hkdf_label), - buf_len(&hkdf_label), out, out_len); + ovpn_hkdf_expand(secret, buf_bptr(&hkdf_label), buf_len(&hkdf_label), = out, out_len); gc_free(&gc); return true; @@ -133,16 +128,14 @@ const size_t epoch_update_label_len =3D sizeof(epoch_update_label) - 1; /* E_N+1 =3D OVPN-Expand-Label(E_N, "datakey upd", "", 32) */ - ovpn_expand_label(epoch_key->epoch_key, sizeof(epoch_key->epoch_key), - epoch_update_label, epoch_update_label_len, - NULL, 0, - new_epoch_key.epoch_key, sizeof(new_epoch_key.epoch_= key)); + ovpn_expand_label(epoch_key->epoch_key, sizeof(epoch_key->epoch_key), = epoch_update_label, + epoch_update_label_len, NULL, 0, new_epoch_key.epoch= _key, + sizeof(new_epoch_key.epoch_key)); *epoch_key =3D new_epoch_key; } void -epoch_data_key_derive(struct key_parameters *key, - const struct epoch_key *epoch_key, +epoch_data_key_derive(struct key_parameters *key, const struct epoch_key *= epoch_key, const struct key_type *kt) { key->hmac_size =3D cipher_kt_iv_size(kt->cipher); @@ -157,19 +150,16 @@ /* length of the array without extra \0 byte from the string */ const size_t epoch_data_key_label_len =3D sizeof(epoch_data_key_label)= - 1; - ovpn_expand_label(epoch_key->epoch_key, sizeof(epoch_key->epoch_key), - epoch_data_key_label, epoch_data_key_label_len, - NULL, 0, - (uint8_t *)(&key->cipher), key->cipher_size); + ovpn_expand_label(epoch_key->epoch_key, sizeof(epoch_key->epoch_key), = epoch_data_key_label, + epoch_data_key_label_len, NULL, 0, (uint8_t *)(&key-= >cipher), + key->cipher_size); const uint8_t epoch_data_iv_label[] =3D "data_iv"; /* length of the array without extra \0 byte from the string */ const size_t epoch_data_iv_label_len =3D sizeof(epoch_data_iv_label) -= 1; - ovpn_expand_label(epoch_key->epoch_key, sizeof(epoch_key->epoch_key), - epoch_data_iv_label, epoch_data_iv_label_len, - NULL, 0, - (uint8_t *)(&key->hmac), key->hmac_size); + ovpn_expand_label(epoch_key->epoch_key, sizeof(epoch_key->epoch_key), = epoch_data_iv_label, + epoch_data_iv_label_len, NULL, 0, (uint8_t *)(&key->= hmac), key->hmac_size); key->epoch =3D epoch_key->epoch; } @@ -187,8 +177,7 @@ epoch_data_key_derive(&send_key, &co->epoch_key_send, &co->epoch_key_t= ype); - init_key_bi_ctx_send(&co->key_ctx_bi.encrypt, &send_key, - &co->epoch_key_type, name); + init_key_bi_ctx_send(&co->key_ctx_bi.encrypt, &send_key, &co->epoch_ke= y_type, name); reset_packet_id_send(&co->packet_id.send); CLEAR(send_key); } @@ -219,10 +208,10 @@ /* Either we have not generated any future keys yet (first initialisat= ion) * or the last index is the same as our current epoch key * (last generated receive epoch key should match the epoch key) */ - struct key_ctx *highest_future_key =3D &co->epoch_data_keys_future[co-= >epoch_data_keys_future_count - 1]; + struct key_ctx *highest_future_key =3D + &co->epoch_data_keys_future[co->epoch_data_keys_future_count - 1]; - ASSERT(co->epoch_key_recv.epoch =3D=3D 1 - || highest_future_key->epoch =3D=3D co->epoch_key_recv.epoch); + ASSERT(co->epoch_key_recv.epoch =3D=3D 1 || highest_future_key->epoch = =3D=3D co->epoch_key_recv.epoch); /* free the keys that are not used anymore */ for (uint16_t i =3D 0; i < co->epoch_data_keys_future_count; i++) @@ -250,12 +239,12 @@ { ASSERT(co->epoch_data_keys_future[i].epoch =3D=3D 0); } - memmove(co->epoch_data_keys_future, - co->epoch_data_keys_future + num_keys_generate, + memmove(co->epoch_data_keys_future, co->epoch_data_keys_future + num_k= eys_generate, (co->epoch_data_keys_future_count - num_keys_generate) * sizeo= f(struct key_ctx)); /* Clear and regenerate the array elements at the end */ - for (uint16_t i =3D co->epoch_data_keys_future_count - num_keys_genera= te; i < co->epoch_data_keys_future_count; i++) + for (uint16_t i =3D co->epoch_data_keys_future_count - num_keys_genera= te; + i < co->epoch_data_keys_future_count; i++) { CLEAR(co->epoch_data_keys_future[i]); epoch_key_iterate(&co->epoch_key_recv); @@ -280,8 +269,7 @@ } void -epoch_replace_update_recv_key(struct crypto_options *co, - uint16_t new_epoch) +epoch_replace_update_recv_key(struct crypto_options *co, uint16_t new_epoc= h) { /* Find the key of the new epoch in future keys */ uint16_t fki; @@ -350,8 +338,7 @@ void epoch_init_key_ctx(struct crypto_options *co, const struct key_type *key_t= ype, - const struct epoch_key *e1_send, - const struct epoch_key *e1_recv, + const struct epoch_key *e1_send, const struct epoch_key= *e1_recv, uint16_t future_key_count) { ASSERT(e1_send->epoch =3D=3D 1 && e1_recv->epoch =3D=3D 1); @@ -441,11 +428,9 @@ * decryption fail warn limit. * */ else if (opt->key_ctx_bi.encrypt.epoch =3D=3D opt->key_ctx_bi.decr= ypt.epoch - && (aead_usage_limit_reached(opt->aead_usage_limit, - &opt->key_ctx_bi.decrypt, + && (aead_usage_limit_reached(opt->aead_usage_limit, &opt-= >key_ctx_bi.decrypt, opt->packet_id.rec.id) - || cipher_decrypt_verify_fail_warn(&opt->key_ctx_bi.d= ecrypt) - )) + || cipher_decrypt_verify_fail_warn(&opt->key_ctx_bi.d= ecrypt))) { /* Receive key limit reached. Increase our own send key to sig= nal * that we want to use a new epoch. Peer should then also move= its @@ -458,5 +443,4 @@ { epoch_iterate_send_key(opt); } - } diff --git a/src/openvpn/crypto_epoch.h b/src/openvpn/crypto_epoch.h index ff5974e..33ca741 100644 --- a/src/openvpn/crypto_epoch.h +++ b/src/openvpn/crypto_epoch.h @@ -38,10 +38,8 @@ * @param out output keying material * @param out_len length of output keying material */ -void -ovpn_hkdf_expand(const uint8_t *secret, - const uint8_t *info, int info_len, - uint8_t *out, int out_len); +void ovpn_hkdf_expand(const uint8_t *secret, const uint8_t *info, int info= _len, uint8_t *out, + int out_len); /** * Variant of the RFC 8446 TLS 1.3 HKDF-Expand-Label function with the @@ -60,11 +58,9 @@ * @param out_len length of output keying material * @return */ -bool -ovpn_expand_label(const uint8_t *secret, size_t secret_len, - const uint8_t *label, size_t label_len, - const uint8_t *context, size_t context_len, - uint8_t *out, uint16_t out_len); +bool ovpn_expand_label(const uint8_t *secret, size_t secret_len, const uin= t8_t *label, + size_t label_len, const uint8_t *context, size_t co= ntext_len, uint8_t *out, + uint16_t out_len); /** * Generate a data channel key pair from the epoch key @@ -72,10 +68,8 @@ * @param epoch_key Epoch key to be used * @param kt Cipher information to generate the data channel ke= y for */ -void -epoch_data_key_derive(struct key_parameters *key, - const struct epoch_key *epoch_key, - const struct key_type *kt); +void epoch_data_key_derive(struct key_parameters *key, const struct epoch_= key *epoch_key, + const struct key_type *kt); /** * Generates and fills the epoch_data_keys_future with next valid @@ -90,8 +84,7 @@ * free the ones that are older than the crypto_options.key_ctx_bi.decrypt= and * generate the keys from the newer epoch. */ -void -epoch_generate_future_receive_keys(struct crypto_options *co); +void epoch_generate_future_receive_keys(struct crypto_options *co); /** This is called when the peer uses a new send key that is not the defau= lt @@ -102,21 +95,17 @@ * @param co crypto_options to update * @param new_epoch the new epoch to use for the receive key */ -void -epoch_replace_update_recv_key(struct crypto_options *co, - uint16_t new_epoch); +void epoch_replace_update_recv_key(struct crypto_options *co, uint16_t new= _epoch); /** * Updates the send key and send_epoch_key in cryptio_options->key_ctx_bi = to * use the next epoch */ -void -epoch_iterate_send_key(struct crypto_options *co); +void epoch_iterate_send_key(struct crypto_options *co); /** * Frees the extra data structures used by epoch keys in \c crypto_options */ -void -free_epoch_key_ctx(struct crypto_options *co); +void free_epoch_key_ctx(struct crypto_options *co); =20 /** * Initialises data channel keys and internal structures for epoch data ke= ys @@ -131,10 +120,9 @@ * @param future_key_count the number of future epoch keys that should be * considered valid when receiving data from the = peer */ -void -epoch_init_key_ctx(struct crypto_options *co, const struct key_type *key_t= ype, - const struct epoch_key *e1_send, const struct epoch_key= *e1_recv, - uint16_t future_key_count); +void epoch_init_key_ctx(struct crypto_options *co, const struct key_type *= key_type, + const struct epoch_key *e1_send, const struct epoc= h_key *e1_recv, + uint16_t future_key_count); /** * Using an epoch, this function will try to retrieve a decryption @@ -143,8 +131,7 @@ * @param epoch epoch of the key to lookup * @return the key context with */ -struct key_ctx * -epoch_lookup_decrypt_key(struct crypto_options *opt, uint16_t epoch); +struct key_ctx *epoch_lookup_decrypt_key(struct crypto_options *opt, uint1= 6_t epoch); /** * Checks if we need to iterate the send epoch key. This needs to be in one @@ -153,8 +140,7 @@ * - send key aead usage limit reached (for AES-GCM and similar ciphers) * - recv key usage limit reached */ -void -epoch_check_send_iterate(struct crypto_options *opt); +void epoch_check_send_iterate(struct crypto_options *opt); =20 #endif /* ifndef CRYPTO_EPOCH_H */ diff --git a/src/openvpn/crypto_mbedtls.c b/src/openvpn/crypto_mbedtls.c index 0950f6b..86317dd 100644 --- a/src/openvpn/crypto_mbedtls.c +++ b/src/openvpn/crypto_mbedtls.c @@ -65,7 +65,7 @@ crypto_init_lib_engine(const char *engine_name) { msg(M_WARN, "Note: mbed TLS hardware crypto engine functionality is no= t " - "available"); + "available"); } provider_t * @@ -123,8 +123,7 @@ } bool -mbed_log_func_line(unsigned int flags, int errval, const char *func, - int line) +mbed_log_func_line(unsigned int flags, int errval, const char *func, int l= ine) { char prefix[256]; @@ -203,8 +202,8 @@ const int *digests =3D mbedtls_md_list(); #ifndef ENABLE_SMALL - printf("The following message digests are available for use with\n" - PACKAGE_NAME ". A message digest is used in conjunction with\n" + printf("The following message digests are available for use with\n" PA= CKAGE_NAME + ". A message digest is used in conjunction with\n" "the HMAC function, to authenticate received packets.\n" "You can specify a message digest as parameter to\n" "the --auth option.\n\n"); @@ -232,12 +231,12 @@ } bool -crypto_pem_encode(const char *name, struct buffer *dst, - const struct buffer *src, struct gc_arena *gc) +crypto_pem_encode(const char *name, struct buffer *dst, const struct buffe= r *src, + struct gc_arena *gc) { /* 1000 chars is the PEM line length limit (+1 for tailing NUL) */ - char header[1000+1] =3D { 0 }; - char footer[1000+1] =3D { 0 }; + char header[1000 + 1] =3D { 0 }; + char footer[1000 + 1] =3D { 0 }; if (!snprintf(header, sizeof(header), "-----BEGIN %s-----\n", name)) { @@ -249,9 +248,8 @@ } size_t out_len =3D 0; - if (MBEDTLS_ERR_BASE64_BUFFER_TOO_SMALL !=3D - mbedtls_pem_write_buffer(header, footer, BPTR(src), BLEN(src), - NULL, 0, &out_len)) + if (MBEDTLS_ERR_BASE64_BUFFER_TOO_SMALL + !=3D mbedtls_pem_write_buffer(header, footer, BPTR(src), BLEN(src)= , NULL, 0, &out_len)) { return false; } @@ -259,9 +257,9 @@ /* We set the size buf to out_len-1 to NOT include the 0 byte that * mbedtls_pem_write_buffer in its length calculation */ *dst =3D alloc_buf_gc(out_len, gc); - if (!mbed_ok(mbedtls_pem_write_buffer(header, footer, BPTR(src), BLEN(= src), - BPTR(dst), BCAP(dst), &out_len)) - || !buf_inc_len(dst, out_len-1)) + if (!mbed_ok(mbedtls_pem_write_buffer(header, footer, BPTR(src), BLEN(= src), BPTR(dst), + BCAP(dst), &out_len)) + || !buf_inc_len(dst, out_len - 1)) { CLEAR(*dst); return false; @@ -271,12 +269,11 @@ } bool -crypto_pem_decode(const char *name, struct buffer *dst, - const struct buffer *src) +crypto_pem_decode(const char *name, struct buffer *dst, const struct buffe= r *src) { /* 1000 chars is the PEM line length limit (+1 for tailing NUL) */ - char header[1000+1] =3D { 0 }; - char footer[1000+1] =3D { 0 }; + char header[1000 + 1] =3D { 0 }; + char footer[1000 + 1] =3D { 0 }; if (!snprintf(header, sizeof(header), "-----BEGIN %s-----", name)) { @@ -296,8 +293,8 @@ size_t use_len =3D 0; mbedtls_pem_context ctx =3D { 0 }; - bool ret =3D mbed_ok(mbedtls_pem_read_buffer(&ctx, header, footer, BPT= R(&input), - NULL, 0, &use_len)); + bool ret =3D + mbed_ok(mbedtls_pem_read_buffer(&ctx, header, footer, BPTR(&input)= , NULL, 0, &use_len)); size_t buf_size =3D 0; const unsigned char *buf =3D mbedtls_pem_get_buffer(&ctx, &buf_size); if (ret && !buf_write(dst, buf, buf_size)) @@ -327,8 +324,8 @@ mbedtls_ctr_drbg_context * rand_ctx_get(void) { - static mbedtls_entropy_context ec =3D {0}; - static mbedtls_ctr_drbg_context cd_ctx =3D {0}; + static mbedtls_entropy_context ec =3D { 0 }; + static mbedtls_ctr_drbg_context cd_ctx =3D { 0 }; static bool rand_initialised =3D false; if (!rand_initialised) @@ -341,14 +338,15 @@ * 800-90 section 8.7.1). We have very little information at this = stage. * Include Program Name, memory address of the context and PID. */ - buf_printf(&pers_string, "OpenVPN %0u %p %s", platform_getpid(), &= cd_ctx, time_string(0, 0, 0, &gc)); + buf_printf(&pers_string, "OpenVPN %0u %p %s", platform_getpid(), &= cd_ctx, + time_string(0, 0, 0, &gc)); /* Initialise mbed TLS RNG, and built-in entropy sources */ mbedtls_entropy_init(&ec); mbedtls_ctr_drbg_init(&cd_ctx); - if (!mbed_ok(mbedtls_ctr_drbg_seed(&cd_ctx, mbedtls_entropy_func, = &ec, - BPTR(&pers_string), BLEN(&pers_= string)))) + if (!mbed_ok(mbedtls_ctr_drbg_seed(&cd_ctx, mbedtls_entropy_func, = &ec, BPTR(&pers_string), + BLEN(&pers_string)))) { msg(M_FATAL, "Failed to initialize random generator"); } @@ -421,12 +419,14 @@ return false; } - const size_t key_bytelen =3D mbedtls_cipher_info_get_key_bitlen(cipher= )/8; + const size_t key_bytelen =3D mbedtls_cipher_info_get_key_bitlen(cipher= ) / 8; if (key_bytelen > MAX_CIPHER_KEY_LENGTH) { - msg(D_LOW, "Cipher algorithm '%s' uses a default key size (%zu byt= es) " + msg(D_LOW, + "Cipher algorithm '%s' uses a default key size (%zu bytes) " "which is larger than " PACKAGE_NAME "'s current maximum key s= ize " - "(%d bytes)", ciphername, key_bytelen, MAX_CIPHER_KEY_LENGTH); + "(%d bytes)", + ciphername, key_bytelen, MAX_CIPHER_KEY_LENGTH); *reason =3D "disabled due to key size too large"; return false; } @@ -457,7 +457,7 @@ return 0; } - return (int)mbedtls_cipher_info_get_key_bitlen(cipher_kt)/8; + return (int)mbedtls_cipher_info_get_key_bitlen(cipher_kt) / 8; } int @@ -506,7 +506,7 @@ #ifdef MBEDTLS_CHACHAPOLY_C || mbedtls_cipher_info_get_type(cipher_kt) =3D=3D MBEDTLS_CIP= HER_CHACHA20_POLY1305 #endif - ); + ); } static mbedtls_cipher_mode_t @@ -527,19 +527,21 @@ cipher_kt_mode_ofb_cfb(const char *ciphername) { const mbedtls_cipher_info_t *cipher =3D cipher_get(ciphername); - return cipher && (cipher_kt_mode(cipher) =3D=3D OPENVPN_MODE_OFB - || cipher_kt_mode(cipher) =3D=3D OPENVPN_MODE_CFB); + return cipher + && (cipher_kt_mode(cipher) =3D=3D OPENVPN_MODE_OFB + || cipher_kt_mode(cipher) =3D=3D OPENVPN_MODE_CFB); } bool cipher_kt_mode_aead(const char *ciphername) { const mbedtls_cipher_info_t *cipher =3D cipher_get(ciphername); - return cipher && (cipher_kt_mode(cipher) =3D=3D OPENVPN_MODE_GCM + return cipher + && (cipher_kt_mode(cipher) =3D=3D OPENVPN_MODE_GCM #ifdef MBEDTLS_CHACHAPOLY_C - || cipher_kt_mode(cipher) =3D=3D MBEDTLS_MODE_CHACHA= POLY + || cipher_kt_mode(cipher) =3D=3D MBEDTLS_MODE_CHACHAPOLY #endif - ); + ); } @@ -565,8 +567,8 @@ } void -cipher_ctx_init(mbedtls_cipher_context_t *ctx, const uint8_t *key, - const char *ciphername, crypto_operation_t enc) +cipher_ctx_init(mbedtls_cipher_context_t *ctx, const uint8_t *key, const c= har *ciphername, + crypto_operation_t enc) { ASSERT(NULL !=3D ciphername && NULL !=3D ctx); CLEAR(*ctx); @@ -611,7 +613,7 @@ return 0; } - if (!mbed_ok(mbedtls_cipher_write_tag(ctx, (unsigned char *) tag, tag_= len))) + if (!mbed_ok(mbedtls_cipher_write_tag(ctx, (unsigned char *)tag, tag_l= en))) { return 0; } @@ -643,18 +645,20 @@ bool cipher_ctx_mode_ofb_cfb(const cipher_ctx_t *ctx) { - return ctx && (cipher_ctx_mode(ctx) =3D=3D OPENVPN_MODE_OFB - || cipher_ctx_mode(ctx) =3D=3D OPENVPN_MODE_CFB); + return ctx + && (cipher_ctx_mode(ctx) =3D=3D OPENVPN_MODE_OFB + || cipher_ctx_mode(ctx) =3D=3D OPENVPN_MODE_CFB); } bool cipher_ctx_mode_aead(const cipher_ctx_t *ctx) { - return ctx && (cipher_ctx_mode(ctx) =3D=3D OPENVPN_MODE_GCM + return ctx + && (cipher_ctx_mode(ctx) =3D=3D OPENVPN_MODE_GCM #ifdef MBEDTLS_CHACHAPOLY_C - || cipher_ctx_mode(ctx) =3D=3D MBEDTLS_MODE_CHACHAPOLY + || cipher_ctx_mode(ctx) =3D=3D MBEDTLS_MODE_CHACHAPOLY #endif - ); + ); } int @@ -690,13 +694,12 @@ } int -cipher_ctx_update(mbedtls_cipher_context_t *ctx, uint8_t *dst, - int *dst_len, uint8_t *src, int src_len) +cipher_ctx_update(mbedtls_cipher_context_t *ctx, uint8_t *dst, int *dst_le= n, uint8_t *src, + int src_len) { size_t s_dst_len =3D *dst_len; - if (!mbed_ok(mbedtls_cipher_update(ctx, src, (size_t) src_len, dst, - &s_dst_len))) + if (!mbed_ok(mbedtls_cipher_update(ctx, src, (size_t)src_len, dst, &s_= dst_len))) { return 0; } @@ -722,8 +725,8 @@ } int -cipher_ctx_final_check_tag(mbedtls_cipher_context_t *ctx, uint8_t *dst, - int *dst_len, uint8_t *tag, size_t tag_len) +cipher_ctx_final_check_tag(mbedtls_cipher_context_t *ctx, uint8_t *dst, in= t *dst_len, uint8_t *tag, + size_t tag_len) { size_t olen =3D 0; @@ -749,8 +752,7 @@ } *dst_len =3D olen; - if (!mbed_ok(mbedtls_cipher_check_tag(ctx, (const unsigned char *) tag, - tag_len))) + if (!mbed_ok(mbedtls_cipher_check_tag(ctx, (const unsigned char *)tag,= tag_len))) { return 0; } @@ -759,7 +761,6 @@ } - /* * * Generic message digest information functions @@ -780,10 +781,10 @@ } if (mbedtls_md_get_size(md) > MAX_HMAC_KEY_LENGTH) { - msg(M_FATAL, "Message hash algorithm '%s' uses a default hash size= (%d bytes) which is larger than " PACKAGE_NAME "'s current maximum hash si= ze (%d bytes)", - digest, - mbedtls_md_get_size(md), - MAX_HMAC_KEY_LENGTH); + msg(M_FATAL, + "Message hash algorithm '%s' uses a default hash size (%d byte= s) which is larger than " PACKAGE_NAME + "'s current maximum hash size (%d bytes)", + digest, mbedtls_md_get_size(md), MAX_HMAC_KEY_LENGTH); } return md; } @@ -791,7 +792,7 @@ bool md_valid(const char *digest) { - const mbedtls_md_info_t *md =3D mbedtls_md_info_from_string(digest); + const mbedtls_md_info_t *md =3D mbedtls_md_info_from_string(digest); return md !=3D NULL; } @@ -966,8 +967,8 @@ * via its APIs like OpenSSL does with CRYPTO_memcmp * Adapt the function that mbedtls itself uses in * mbedtls_safer_memcmp as it considers that to be safe */ - volatile const unsigned char *A =3D (volatile const unsigned char *) a; - volatile const unsigned char *B =3D (volatile const unsigned char *) b; + volatile const unsigned char *A =3D (volatile const unsigned char *)a; + volatile const unsigned char *B =3D (volatile const unsigned char *)b; volatile unsigned char diff =3D 0; for (size_t i =3D 0; i < size; i++) @@ -982,12 +983,11 @@ * from recent versions, so we use our own implementation if necessary. */ #if defined(HAVE_MBEDTLS_SSL_TLS_PRF) && defined(MBEDTLS_SSL_TLS_PRF_TLS1) bool -ssl_tls1_PRF(const uint8_t *seed, int seed_len, const uint8_t *secret, - int secret_len, uint8_t *output, int output_len) +ssl_tls1_PRF(const uint8_t *seed, int seed_len, const uint8_t *secret, int= secret_len, + uint8_t *output, int output_len) { - return mbed_ok(mbedtls_ssl_tls_prf(MBEDTLS_SSL_TLS_PRF_TLS1, secret, - secret_len, "", seed, seed_len, out= put, - output_len)); + return mbed_ok(mbedtls_ssl_tls_prf(MBEDTLS_SSL_TLS_PRF_TLS1, secret, s= ecret_len, "", seed, + seed_len, output, output_len)); } #else /* defined(HAVE_MBEDTLS_SSL_TLS_PRF) && defined(MBEDTLS_SSL_TLS_PRF_= TLS1) */ /* @@ -1002,8 +1002,8 @@ * @param olen Length of the output buffer */ static void -tls1_P_hash(const mbedtls_md_info_t *md_kt, const uint8_t *sec, int sec_le= n, - const uint8_t *seed, int seed_len, uint8_t *out, int olen) +tls1_P_hash(const mbedtls_md_info_t *md_kt, const uint8_t *sec, int sec_le= n, const uint8_t *seed, + int seed_len, uint8_t *out, int olen) { struct gc_arena gc =3D gc_new(); uint8_t A1[MAX_HMAC_KEY_LENGTH]; @@ -1037,7 +1037,7 @@ hmac_ctx_update(ctx, seed, seed_len); hmac_ctx_final(ctx, A1); - for (;; ) + for (;;) { hmac_ctx_reset(ctx); hmac_ctx_reset(ctx_tmp); @@ -1052,7 +1052,7 @@ olen -=3D chunk; hmac_ctx_final(ctx_tmp, A1); /* calc the next A1 value */ } - else /* last one */ + else /* last one */ { hmac_ctx_final(ctx, A1); memcpy(out, A1, olen); @@ -1089,8 +1089,8 @@ * (2) The pre-master secret is generated by the client. */ bool -ssl_tls1_PRF(const uint8_t *label, int label_len, const uint8_t *sec, - int slen, uint8_t *out1, int olen) +ssl_tls1_PRF(const uint8_t *label, int label_len, const uint8_t *sec, int = slen, uint8_t *out1, + int olen) { struct gc_arena gc =3D gc_new(); const md_kt_t *md5 =3D md_get("MD5"); @@ -1098,15 +1098,15 @@ uint8_t *out2 =3D (uint8_t *)gc_malloc(olen, false, &gc); - int len =3D slen/2; + int len =3D slen / 2; const uint8_t *S1 =3D sec; const uint8_t *S2 =3D &(sec[len]); - len +=3D (slen&1); /* add for odd, make longer */ + len +=3D (slen & 1); /* add for odd, make longer */ tls1_P_hash(md5, S1, len, label, label_len, out1, olen); tls1_P_hash(sha1, S2, len, label, label_len, out2, olen); - for (int i =3D 0; i=3D 0x30000000L */ +#else /* OPENSSL_VERSION_NUMBER >=3D 0x30000000L */ msg(M_WARN, "Note: OpenSSL provider functionality is not available"); return NULL; #endif @@ -249,12 +244,13 @@ if (ERR_GET_REASON(err) =3D=3D SSL_R_NO_SHARED_CIPHER) { msg(D_CRYPT_ERRORS, "TLS error: The server has no TLS ciphersu= ites " - "in common with the client. Your --tls-cipher setting migh= t be " - "too restrictive."); + "in common with the client. Your --tls-cip= her setting might be " + "too restrictive."); } else if (ERR_GET_REASON(err) =3D=3D SSL_R_UNSUPPORTED_PROTOCOL) { - msg(D_CRYPT_ERRORS, "TLS error: Unsupported protocol. This typ= ically " + msg(D_CRYPT_ERRORS, + "TLS error: Unsupported protocol. This typically " "indicates that client and server have no common TLS versi= on enabled. " "This can be caused by mismatched tls-version-min and tls-= version-max " "options on client and server. " @@ -270,8 +266,8 @@ } else { - msg(flags, "OpenSSL: %s:%s:%s:%d:%s", ERR_error_string(err, NU= LL), - data, file, line, func); + msg(flags, "OpenSSL: %s:%s:%s:%d:%s", ERR_error_string(err, NU= LL), data, file, line, + func); } } } @@ -307,9 +303,7 @@ void crypto_init_dmalloc(void) { - CRYPTO_set_mem_ex_functions(crypto_malloc, - crypto_realloc, - crypto_free); + CRYPTO_set_mem_ex_functions(crypto_malloc, crypto_realloc, crypto_free= ); } #endif /* DMALLOC */ @@ -332,7 +326,8 @@ return strcmp(EVP_CIPHER_get0_name(*cipher_a), EVP_CIPHER_get0_name(*c= ipher_b)); } -struct collect_ciphers { +struct collect_ciphers +{ /* If we ever exceed this, we must be more selective */ const EVP_CIPHER *list[1000]; size_t num; @@ -354,12 +349,12 @@ const char *ciphername =3D EVP_CIPHER_get0_name(cipher); - if (ciphername && (cipher_kt_mode_cbc(ciphername) + if (ciphername + && (cipher_kt_mode_cbc(ciphername) #ifdef ENABLE_OFB_CFB_MODE - || cipher_kt_mode_ofb_cfb(ciphername) + || cipher_kt_mode_ofb_cfb(ciphername) #endif - || cipher_kt_mode_aead(ciphername) - )) + || cipher_kt_mode_aead(ciphername))) { cipher_list->list[cipher_list->num++] =3D cipher; } @@ -393,17 +388,18 @@ { cipher =3D EVP_get_cipherbyname(name); } -#else /* if defined(LIBRESSL_VERSION_NUMBER) */ +#else /* if defined(LIBRESSL_VERSION_NUMBER) */ const EVP_CIPHER *cipher =3D EVP_get_cipherbynid(nid); #endif /* We cast the const away so we can keep the function prototype * compatible with EVP_CIPHER_do_all_provided */ - collect_ciphers((EVP_CIPHER *) cipher, &cipher_list); + collect_ciphers((EVP_CIPHER *)cipher, &cipher_list); } #endif /* cast to non-const to prevent warning */ - qsort((EVP_CIPHER *)cipher_list.list, cipher_list.num, sizeof(*cipher_= list.list), cipher_name_cmp); + qsort((EVP_CIPHER *)cipher_list.list, cipher_list.num, sizeof(*cipher_= list.list), + cipher_name_cmp); for (size_t i =3D 0; i < cipher_list.num; i++) { @@ -436,8 +432,8 @@ show_available_digests(void) { #ifndef ENABLE_SMALL - printf("The following message digests are available for use with\n" - PACKAGE_NAME ". A message digest is used in conjunction with\n" + printf("The following message digests are available for use with\n" PA= CKAGE_NAME + ". A message digest is used in conjunction with\n" "the HMAC function, to authenticate received packets.\n" "You can specify a message digest as parameter to\n" "the --auth option.\n"); @@ -486,21 +482,19 @@ e =3D ENGINE_get_first(); while (e) { - printf("%s [%s]\n", - ENGINE_get_name(e), - ENGINE_get_id(e)); + printf("%s [%s]\n", ENGINE_get_name(e), ENGINE_get_id(e)); e =3D ENGINE_get_next(e); } ENGINE_cleanup(); -#else /* if HAVE_OPENSSL_ENGINE */ +#else /* if HAVE_OPENSSL_ENGINE */ printf("Sorry, OpenSSL hardware crypto engine functionality is not ava= ilable.\n"); #endif } bool -crypto_pem_encode(const char *name, struct buffer *dst, - const struct buffer *src, struct gc_arena *gc) +crypto_pem_encode(const char *name, struct buffer *dst, const struct buffe= r *src, + struct gc_arena *gc) { bool ret =3D false; BIO *bio =3D BIO_new(BIO_s_mem()); @@ -527,8 +521,7 @@ } bool -crypto_pem_decode(const char *name, struct buffer *dst, - const struct buffer *src) +crypto_pem_decode(const char *name, struct buffer *dst, const struct buffe= r *src) { bool ret =3D false; @@ -542,8 +535,7 @@ char *header_read =3D NULL; uint8_t *data_read =3D NULL; long data_read_len =3D 0; - if (!PEM_read_bio(bio, &name_read, &header_read, &data_read, - &data_read_len)) + if (!PEM_read_bio(bio, &name_read, &header_read, &data_read, &data_rea= d_len)) { dmsg(D_CRYPT_ERRORS, "%s: PEM decode failed", __func__); goto cleanup; @@ -551,17 +543,16 @@ if (strcmp(name, name_read)) { - dmsg(D_CRYPT_ERRORS, - "%s: unexpected PEM name (got '%s', expected '%s')", - __func__, name_read, name); + dmsg(D_CRYPT_ERRORS, "%s: unexpected PEM name (got '%s', expected = '%s')", __func__, + name_read, name); goto cleanup; } uint8_t *dst_data =3D buf_write_alloc(dst, data_read_len); if (!dst_data) { - dmsg(D_CRYPT_ERRORS, "%s: dst too small (%i, needs %li)", __func__, - BCAP(dst), data_read_len); + dmsg(D_CRYPT_ERRORS, "%s: dst too small (%i, needs %li)", __func__= , BCAP(dst), + data_read_len); goto cleanup; } memcpy(dst_data, data_read, data_read_len); @@ -632,18 +623,21 @@ if (FIPS_mode() && !(EVP_CIPHER_flags(cipher) & EVP_CIPH_FLAG_FIPS)) { - msg(D_LOW, "Cipher algorithm '%s' is known by OpenSSL library but " - "currently disabled by running in FIPS mode.", ciphername); + msg(D_LOW, + "Cipher algorithm '%s' is known by OpenSSL library but " + "currently disabled by running in FIPS mode.", + ciphername); *reason =3D "disabled by FIPS mode"; goto out; } #endif if (EVP_CIPHER_key_length(cipher) > MAX_CIPHER_KEY_LENGTH) { - msg(D_LOW, "Cipher algorithm '%s' uses a default key size (%d byte= s) " + msg(D_LOW, + "Cipher algorithm '%s' uses a default key size (%d bytes) " "which is larger than " PACKAGE_NAME "'s current maximum key s= ize " - "(%d bytes)", ciphername, EVP_CIPHER_key_length(cipher), - MAX_CIPHER_KEY_LENGTH); + "(%d bytes)", + ciphername, EVP_CIPHER_key_length(cipher), MAX_CIPHER_KEY_LENG= TH); *reason =3D "disabled due to key size too large"; goto out; } @@ -758,7 +752,6 @@ bool cipher_kt_insecure(const char *ciphername) { - if (cipher_kt_block_size(ciphername) >=3D 128 / 8) { return false; @@ -790,12 +783,13 @@ { evp_cipher_type *cipher =3D cipher_get(ciphername); - bool ret =3D cipher && (cipher_kt_mode(cipher) =3D=3D OPENVPN_MODE_CBC - /* Exclude AEAD cipher modes, they require a dif= ferent API */ + bool ret =3D cipher + && (cipher_kt_mode(cipher) =3D=3D OPENVPN_MODE_CBC + /* Exclude AEAD cipher modes, they require a different API */ #ifdef EVP_CIPH_FLAG_CTS - && !(EVP_CIPHER_flags(cipher) & EVP_CIPH_FLAG_CT= S) + && !(EVP_CIPHER_flags(cipher) & EVP_CIPH_FLAG_CTS) #endif - && !(EVP_CIPHER_flags(cipher) & EVP_CIPH_FLAG_AE= AD_CIPHER)); + && !(EVP_CIPHER_flags(cipher) & EVP_CIPH_FLAG_AEAD_CIPH= ER)); EVP_CIPHER_free(cipher); return ret; } @@ -804,8 +798,9 @@ cipher_kt_mode_ofb_cfb(const char *ciphername) { evp_cipher_type *cipher =3D cipher_get(ciphername); - bool ofb_cfb =3D cipher && (cipher_kt_mode(cipher) =3D=3D OPENVPN_MODE= _OFB - || cipher_kt_mode(cipher) =3D=3D OPENVPN_MOD= E_CFB) + bool ofb_cfb =3D cipher + && (cipher_kt_mode(cipher) =3D=3D OPENVPN_MODE_OFB + || cipher_kt_mode(cipher) =3D=3D OPENVPN_MODE_CFB) /* Exclude AEAD cipher modes, they require a different = API */ && !(EVP_CIPHER_flags(cipher) & EVP_CIPH_FLAG_AEAD_CIPH= ER); EVP_CIPHER_free(cipher); @@ -828,7 +823,7 @@ #ifdef NID_chacha20_poly1305 if (EVP_CIPHER_nid(cipher) =3D=3D NID_chacha20_poly1305) { - isaead =3D true; + isaead =3D true; } #endif } @@ -859,8 +854,8 @@ } void -cipher_ctx_init(EVP_CIPHER_CTX *ctx, const uint8_t *key, - const char *ciphername, crypto_operation_t enc) +cipher_ctx_init(EVP_CIPHER_CTX *ctx, const uint8_t *key, const char *ciphe= rname, + crypto_operation_t enc) { ASSERT(NULL !=3D ciphername && NULL !=3D ctx); evp_cipher_type *kt =3D cipher_get(ciphername); @@ -913,7 +908,7 @@ int mode =3D EVP_CIPHER_CTX_mode(ctx); return mode =3D=3D EVP_CIPH_CBC_MODE - /* Exclude AEAD cipher modes, they require a different API */ + /* Exclude AEAD cipher modes, they require a different API */ #ifdef EVP_CIPH_FLAG_CTS && !(flags & EVP_CIPH_FLAG_CTS) #endif @@ -976,8 +971,7 @@ } int -cipher_ctx_update(EVP_CIPHER_CTX *ctx, uint8_t *dst, int *dst_len, - uint8_t *src, int src_len) +cipher_ctx_update(EVP_CIPHER_CTX *ctx, uint8_t *dst, int *dst_len, uint8_t= *src, int src_len) { if (!EVP_CipherUpdate(ctx, dst, dst_len, src, src_len)) { @@ -993,8 +987,8 @@ } int -cipher_ctx_final_check_tag(EVP_CIPHER_CTX *ctx, uint8_t *dst, int *dst_len, - uint8_t *tag, size_t tag_len) +cipher_ctx_final_check_tag(EVP_CIPHER_CTX *ctx, uint8_t *dst, int *dst_len= , uint8_t *tag, + size_t tag_len) { ASSERT(tag_len < SIZE_MAX); if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_TAG, tag_len, tag)) @@ -1025,7 +1019,8 @@ } if (EVP_MD_size(md) > MAX_HMAC_KEY_LENGTH) { - crypto_msg(M_FATAL, "Message hash algorithm '%s' uses a default ha= sh " + crypto_msg(M_FATAL, + "Message hash algorithm '%s' uses a default hash " "size (%d bytes) which is larger than " PACKAGE_NAME "'= s current " "maximum hash size (%d bytes)", digest, EVP_MD_size(md), MAX_HMAC_KEY_LENGTH); @@ -1051,17 +1046,12 @@ * this translation table for forward lookup, only for returning the name * with md_kt_name() */ const cipher_name_pair digest_name_translation_table[] =3D { - { "BLAKE2s256", "BLAKE2S-256"}, - { "BLAKE2b512", "BLAKE2B-512"}, - { "RIPEMD160", "RIPEMD-160" }, - { "SHA224", "SHA2-224"}, - { "SHA256", "SHA2-256"}, - { "SHA384", "SHA2-384"}, - { "SHA512", "SHA2-512"}, - { "SHA512-224", "SHA2-512/224"}, - { "SHA512-256", "SHA2-512/256"}, - { "SHAKE128", "SHAKE-128"}, - { "SHAKE256", "SHAKE-256"}, + { "BLAKE2s256", "BLAKE2S-256" }, { "BLAKE2b512", "BLAKE2B-512" }, + { "RIPEMD160", "RIPEMD-160" }, { "SHA224", "SHA2-224" }, + { "SHA256", "SHA2-256" }, { "SHA384", "SHA2-384" }, + { "SHA512", "SHA2-512" }, { "SHA512-224", "SHA2-512/224" }, + { "SHA512-256", "SHA2-512/256" }, { "SHAKE128", "SHAKE-128" }, + { "SHAKE256", "SHAKE-256" }, }; const size_t digest_name_translation_table_count =3D sizeof(digest_name_translation_table) / sizeof(*digest_name_translatio= n_table); @@ -1098,7 +1088,7 @@ return 0; } evp_md_type *kt =3D md_get(mdname); - unsigned char size =3D (unsigned char)EVP_MD_size(kt); + unsigned char size =3D (unsigned char)EVP_MD_size(kt); EVP_MD_free(kt); return size; } @@ -1286,10 +1276,8 @@ * only used for lookup so we cast (as OpenSSL also does internally) * the constness away here. */ - ctx->params[0] =3D OSSL_PARAM_construct_utf8_string("digest", - (char *) EVP_MD_get0= _name(kt), 0); - ctx->params[1] =3D OSSL_PARAM_construct_octet_string("key", - ctx->key, EVP_MD_si= ze(kt)); + ctx->params[0] =3D OSSL_PARAM_construct_utf8_string("digest", (char *)= EVP_MD_get0_name(kt), 0); + ctx->params[1] =3D OSSL_PARAM_construct_octet_string("key", ctx->key, = EVP_MD_size(kt)); ctx->params[2] =3D OSSL_PARAM_construct_end(); if (!EVP_MAC_init(ctx->ctx, NULL, 0, ctx->params)) @@ -1348,8 +1336,8 @@ } #if (OPENSSL_VERSION_NUMBER >=3D 0x30000000L) && !defined(LIBRESSL_VERSION= _NUMBER) bool -ssl_tls1_PRF(const uint8_t *seed, int seed_len, const uint8_t *secret, - int secret_len, uint8_t *output, int output_len) +ssl_tls1_PRF(const uint8_t *seed, int seed_len, const uint8_t *secret, int= secret_len, + uint8_t *output, int output_len) { bool ret =3D true; EVP_KDF_CTX *kctx =3D NULL; @@ -1372,18 +1360,18 @@ /* The OpenSSL APIs require us to cast the const aways even though the * strings are never changed and only read */ - params[0] =3D OSSL_PARAM_construct_utf8_string(OSSL_KDF_PARAM_DIGEST, - SN_md5_sha1, strlen(SN_md= 5_sha1)); - params[1] =3D OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_SECRET, - (uint8_t *) secret, (siz= e_t) secret_len); - params[2] =3D OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_SEED, - (uint8_t *) seed, (size_= t) seed_len); + params[0] =3D + OSSL_PARAM_construct_utf8_string(OSSL_KDF_PARAM_DIGEST, SN_md5_sha= 1, strlen(SN_md5_sha1)); + params[1] =3D OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_SECRET,= (uint8_t *)secret, + (size_t)secret_len); + params[2] =3D + OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_SEED, (uint8_t *)= seed, (size_t)seed_len); params[3] =3D OSSL_PARAM_construct_end(); if (EVP_KDF_derive(kctx, output, output_len, params) <=3D 0) { crypto_msg(D_TLS_DEBUG_LOW, "Generating TLS 1.0 PRF using " - "EVP_KDF_derive failed"); + "EVP_KDF_derive failed"); goto err; } @@ -1399,15 +1387,15 @@ } #elif defined(OPENSSL_IS_AWSLC) bool -ssl_tls1_PRF(const uint8_t *label, int label_len, const uint8_t *sec, - int slen, uint8_t *out1, int olen) +ssl_tls1_PRF(const uint8_t *label, int label_len, const uint8_t *sec, int = slen, uint8_t *out1, + int olen) { CRYPTO_tls1_prf(EVP_md5_sha1(), out1, olen, sec, slen, label, label_le= n, NULL, 0, NULL, 0); } #elif !defined(LIBRESSL_VERSION_NUMBER) && !defined(ENABLE_CRYPTO_WOLFSSL) bool -ssl_tls1_PRF(const uint8_t *seed, int seed_len, const uint8_t *secret, - int secret_len, uint8_t *output, int output_len) +ssl_tls1_PRF(const uint8_t *seed, int seed_len, const uint8_t *secret, int= secret_len, + uint8_t *output, int output_len) { EVP_PKEY_CTX *pctx =3D EVP_PKEY_CTX_new_id(EVP_PKEY_TLS1_PRF, NULL); if (!pctx) @@ -1455,8 +1443,8 @@ * OpenSSL does. As result they will only be able to support * peers that support TLS EKM like when running with OpenSSL 3.x FIPS */ bool -ssl_tls1_PRF(const uint8_t *label, int label_len, const uint8_t *sec, - int slen, uint8_t *out1, int olen) +ssl_tls1_PRF(const uint8_t *label, int label_len, const uint8_t *sec, int = slen, uint8_t *out1, + int olen) { return false; } diff --git a/src/openvpn/crypto_openssl.h b/src/openvpn/crypto_openssl.h index 9680c18..6218b39 100644 --- a/src/openvpn/crypto_openssl.h +++ b/src/openvpn/crypto_openssl.h @@ -50,7 +50,8 @@ /* Use a dummy type for the provider */ typedef void provider_t; #else -typedef struct { +typedef struct +{ OSSL_PARAM params[3]; uint8_t key[EVP_MAX_KEY_LENGTH]; EVP_MAC_CTX *ctx; @@ -71,29 +72,29 @@ #endif /** Maximum length of an IV */ -#define OPENVPN_MAX_IV_LENGTH EVP_MAX_IV_LENGTH +#define OPENVPN_MAX_IV_LENGTH EVP_MAX_IV_LENGTH /** Cipher is in CBC mode */ -#define OPENVPN_MODE_CBC EVP_CIPH_CBC_MODE +#define OPENVPN_MODE_CBC EVP_CIPH_CBC_MODE /** Cipher is in OFB mode */ -#define OPENVPN_MODE_OFB EVP_CIPH_OFB_MODE +#define OPENVPN_MODE_OFB EVP_CIPH_OFB_MODE /** Cipher is in CFB mode */ -#define OPENVPN_MODE_CFB EVP_CIPH_CFB_MODE +#define OPENVPN_MODE_CFB EVP_CIPH_CFB_MODE /** Cipher is in GCM mode */ -#define OPENVPN_MODE_GCM EVP_CIPH_GCM_MODE +#define OPENVPN_MODE_GCM EVP_CIPH_GCM_MODE typedef int crypto_operation_t; /** Cipher should encrypt */ -#define OPENVPN_OP_ENCRYPT 1 +#define OPENVPN_OP_ENCRYPT 1 /** Cipher should decrypt */ -#define OPENVPN_OP_DECRYPT 0 +#define OPENVPN_OP_DECRYPT 0 -#define MD4_DIGEST_LENGTH 16 +#define MD4_DIGEST_LENGTH 16 /** * Retrieve any occurred OpenSSL errors and print those errors. @@ -112,10 +113,11 @@ * @param flags Flags to indicate error type and priority. * @param ... Format string and optional format arguments */ -#define crypto_msg(flags, ...) \ - do { \ +#define crypto_msg(flags, ...) \ + do \ + { \ crypto_print_openssl_errors(nonfatal(flags)); \ - msg((flags), __VA_ARGS__); \ + msg((flags), __VA_ARGS__); \ } while (false) #endif /* CRYPTO_OPENSSL_H_ */ diff --git a/src/openvpn/cryptoapi.c b/src/openvpn/cryptoapi.c index 67dc382..d91d9a1 100644 --- a/src/openvpn/cryptoapi.c +++ b/src/openvpn/cryptoapi.c @@ -62,11 +62,12 @@ return 0; } -#else /* HAVE_XKEY_PROVIDER */ +#else /* HAVE_XKEY_PROVIDER */ static XKEY_EXTERNAL_SIGN_fn xkey_cng_sign; -typedef struct _CAPI_DATA { +typedef struct _CAPI_DATA +{ const CERT_CONTEXT *cert_context; HCRYPTPROV_OR_NCRYPT_KEY_HANDLE crypt_prov; EVP_PKEY *pubkey; @@ -112,7 +113,7 @@ break; default: - msg(M_WARN|M_INFO, "cryptoapicert: Unknown hash type NID=3D0x%= x", md_type); + msg(M_WARN | M_INFO, "cryptoapicert: Unknown hash type NID=3D0= x%x", md_type); break; } return alg; @@ -157,7 +158,7 @@ parse_hexstring(const char *p, unsigned char *arr, size_t capacity) { int i =3D 0; - for ( ; *p && i < capacity; p +=3D 2) + for (; *p && i < capacity; p +=3D 2) { /* skip spaces */ while (*p =3D=3D ' ') @@ -169,8 +170,7 @@ break; } - if (!isxdigit(p[0]) || !isxdigit(p[1]) - || sscanf(p, "%2hhx", &arr[i++]) !=3D 1) + if (!isxdigit(p[0]) || !isxdigit(p[1]) || sscanf(p, "%2hhx", &arr[= i++]) !=3D 1) { return 0; } @@ -179,21 +179,21 @@ } static void * -decode_object(struct gc_arena *gc, LPCSTR struct_type, - const CRYPT_OBJID_BLOB *val, DWORD flags, DWORD *cb) +decode_object(struct gc_arena *gc, LPCSTR struct_type, const CRYPT_OBJID_B= LOB *val, DWORD flags, + DWORD *cb) { /* get byte count for decoding */ BYTE *buf; - if (!CryptDecodeObject(X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, struct= _type, - val->pbData, val->cbData, flags, NULL, cb)) + if (!CryptDecodeObject(X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, struct= _type, val->pbData, + val->cbData, flags, NULL, cb)) { return NULL; } /* do the actual decode */ buf =3D gc_malloc(*cb, false, gc); - if (!CryptDecodeObject(X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, struct= _type, - val->pbData, val->cbData, flags, buf, cb)) + if (!CryptDecodeObject(X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, struct= _type, val->pbData, + val->cbData, flags, buf, cb)) { return NULL; } @@ -243,8 +243,8 @@ return true; } - const CRYPT_OID_INFO *tmpl_oid =3D find_oid(CRYPT_OID_INFO_NAM= E_KEY, tmpl_name, - CRYPT_TEMPLATE_OID_G= ROUP_ID); + const CRYPT_OID_INFO *tmpl_oid =3D + find_oid(CRYPT_OID_INFO_NAME_KEY, tmpl_name, CRYPT_TEMPLAT= E_OID_GROUP_ID); if (tmpl_oid && !stricmp(tmpl_oid->pszOID, cte->pszObjId)) { /* found OID match in extension against resolved key */ @@ -274,7 +274,7 @@ DWORD find_type; const void *find_param; unsigned char hash[255]; - CRYPT_HASH_BLOB blob =3D {.cbData =3D 0, .pbData =3D hash}; + CRYPT_HASH_BLOB blob =3D { .cbData =3D 0, .pbData =3D hash }; struct gc_arena gc =3D gc_new(); if (!strncmp(cert_prop, "SUBJ:", 5)) @@ -296,7 +296,7 @@ blob.cbData =3D parse_hexstring(cert_prop + 6, hash, sizeof(hash)); if (blob.cbData =3D=3D 0) { - msg(M_WARN|M_INFO, "WARNING: cryptoapicert: error parsing <%s>= .", cert_prop); + msg(M_WARN | M_INFO, "WARNING: cryptoapicert: error parsing <%= s>.", cert_prop); goto out; } } @@ -308,7 +308,8 @@ } else { - msg(M_NONFATAL, "Error in cryptoapicert: unsupported certificate s= pecification <%s>", cert_prop); + msg(M_NONFATAL, "Error in cryptoapicert: unsupported certificate s= pecification <%s>", + cert_prop); goto out; } @@ -316,15 +317,14 @@ { int validity =3D 1; /* this frees previous rv, if not NULL */ - rv =3D CertFindCertificateInStore(cert_store, X509_ASN_ENCODING | = PKCS_7_ASN_ENCODING, - 0, find_type, find_param, rv); + rv =3D CertFindCertificateInStore(cert_store, X509_ASN_ENCODING | = PKCS_7_ASN_ENCODING, 0, + find_type, find_param, rv); if (!rv) { break; } /* if searching by template name, check now if it matches */ - if (find_type =3D=3D CERT_FIND_HAS_PRIVATE_KEY - && !test_certificate_template(cert_prop, rv)) + if (find_type =3D=3D CERT_FIND_HAS_PRIVATE_KEY && !test_certificat= e_template(cert_prop, rv)) { continue; } @@ -333,7 +333,7 @@ { break; } - msg(M_WARN|M_INFO, "WARNING: cryptoapicert: ignoring certificate i= n store %s.", + msg(M_WARN | M_INFO, "WARNING: cryptoapicert: ignoring certificate= in store %s.", validity < 0 ? "not yet valid" : "that has expired"); } @@ -356,12 +356,12 @@ if (status !=3D ERROR_SUCCESS) { SetLastError(status); - msg(M_NONFATAL|M_ERRNO, "Error in cryptoapicert: ECDSA signature u= sing CNG failed."); + msg(M_NONFATAL | M_ERRNO, "Error in cryptoapicert: ECDSA signature= using CNG failed."); return 0; } /* NCryptSignHash returns r|s -- convert to DER encoded buffer expecte= d by OpenSSL */ - int derlen =3D ecdsa_bin2der(sig, (int) len, *siglen); + int derlen =3D ecdsa_bin2der(sig, (int)len, *siglen); if (derlen <=3D 0) { return 0; @@ -396,9 +396,9 @@ { msg(D_LOW, "Signing using NCryptSignHash with PKCS1 padding: hasha= lg <%s>", sigalg.mdname); - BCRYPT_PKCS1_PADDING_INFO padinfo =3D {hashalg}; - status =3D NCryptSignHash(cd->crypt_prov, &padinfo, (BYTE *)tbs, (= DWORD)tbslen, - sig, (DWORD)*siglen, &len, BCRYPT_PAD_PKCS= 1); + BCRYPT_PKCS1_PADDING_INFO padinfo =3D { hashalg }; + status =3D NCryptSignHash(cd->crypt_prov, &padinfo, (BYTE *)tbs, (= DWORD)tbslen, sig, + (DWORD)*siglen, &len, BCRYPT_PAD_PKCS1); } else if (!strcmp(sigalg.padmode, "pss")) { @@ -416,9 +416,10 @@ msg(D_LOW, "Signing using NCryptSignHash with PSS padding: hashalg= <%s>, saltlen <%d>", sigalg.mdname, saltlen); - BCRYPT_PSS_PADDING_INFO padinfo =3D {hashalg, (DWORD) saltlen}; /*= cast is safe as saltlen >=3D 0 */ - status =3D NCryptSignHash(cd->crypt_prov, &padinfo, (BYTE *)tbs, (= DWORD) tbslen, - sig, (DWORD)*siglen, &len, BCRYPT_PAD_PSS); + BCRYPT_PSS_PADDING_INFO padinfo =3D { hashalg, + (DWORD)saltlen }; /* cast is s= afe as saltlen >=3D 0 */ + status =3D NCryptSignHash(cd->crypt_prov, &padinfo, (BYTE *)tbs, (= DWORD)tbslen, sig, + (DWORD)*siglen, &len, BCRYPT_PAD_PSS); } else { @@ -429,7 +430,7 @@ if (status !=3D ERROR_SUCCESS) { SetLastError(status); - msg(M_NONFATAL|M_ERRNO, "Error in cryptoapicert: RSA signature usi= ng CNG failed."); + msg(M_NONFATAL | M_ERRNO, "Error in cryptoapicert: RSA signature u= sing CNG failed."); return 0; } @@ -484,7 +485,7 @@ char *name =3D NULL; if (len) { - wchar_t *wname =3D gc_malloc(len*sizeof(wchar_t), false, gc); + wchar_t *wname =3D gc_malloc(len * sizeof(wchar_t), false, gc); if (!wname || CertGetNameStringW(cc, CERT_NAME_FRIENDLY_DISPLAY_TYPE, 0, = NULL, wname, len) =3D=3D 0) { @@ -504,7 +505,6 @@ static int Load_CryptoAPI_certificate(const char *cert_prop, X509 **cert, EVP_PKEY **= privkey) { - HCERTSTORE cs; CAPI_DATA *cd =3D calloc(1, sizeof(*cd)); struct gc_arena gc =3D gc_new(); @@ -515,29 +515,35 @@ goto err; } /* search CURRENT_USER first, then LOCAL_MACHINE */ - cs =3D CertOpenStore((LPCSTR) CERT_STORE_PROV_SYSTEM, 0, 0, CERT_SYSTE= M_STORE_CURRENT_USER - |CERT_STORE_OPEN_EXISTING_FLAG | CERT_STORE_READONL= Y_FLAG, L"MY"); + cs =3D CertOpenStore((LPCSTR)CERT_STORE_PROV_SYSTEM, 0, 0, + CERT_SYSTEM_STORE_CURRENT_USER | CERT_STORE_OPEN_EX= ISTING_FLAG + | CERT_STORE_READONLY_FLAG, + L"MY"); if (cs =3D=3D NULL) { - msg(M_NONFATAL|M_ERRNO, "Error in cryptoapicert: failed to open us= er certficate store"); + msg(M_NONFATAL | M_ERRNO, "Error in cryptoapicert: failed to open = user certficate store"); goto err; } cd->cert_context =3D find_certificate_in_store(cert_prop, cs); CertCloseStore(cs, 0); if (!cd->cert_context) { - cs =3D CertOpenStore((LPCSTR) CERT_STORE_PROV_SYSTEM, 0, 0, CERT_S= YSTEM_STORE_LOCAL_MACHINE - |CERT_STORE_OPEN_EXISTING_FLAG | CERT_STORE_REA= DONLY_FLAG, L"MY"); + cs =3D CertOpenStore((LPCSTR)CERT_STORE_PROV_SYSTEM, 0, 0, + CERT_SYSTEM_STORE_LOCAL_MACHINE | CERT_STORE_OP= EN_EXISTING_FLAG + | CERT_STORE_READONLY_FLAG, + L"MY"); if (cs =3D=3D NULL) { - msg(M_NONFATAL|M_ERRNO, "Error in cryptoapicert: failed to ope= n machine certficate store"); + msg(M_NONFATAL | M_ERRNO, + "Error in cryptoapicert: failed to open machine certficate= store"); goto err; } cd->cert_context =3D find_certificate_in_store(cert_prop, cs); CertCloseStore(cs, 0); if (cd->cert_context =3D=3D NULL) { - msg(M_NONFATAL, "Error in cryptoapicert: certificate matching = <%s> not found", cert_prop); + msg(M_NONFATAL, "Error in cryptoapicert: certificate matching = <%s> not found", + cert_prop); goto err; } } @@ -550,7 +556,7 @@ } /* cert_context->pbCertEncoded is the cert X509 DER encoded. */ - *cert =3D d2i_X509(NULL, (const unsigned char **) &cd->cert_context->p= bCertEncoded, + *cert =3D d2i_X509(NULL, (const unsigned char **)&cd->cert_context->pb= CertEncoded, cd->cert_context->cbCertEncoded); if (*cert =3D=3D NULL) { @@ -560,13 +566,13 @@ /* set up stuff to use the private key */ /* We support NCRYPT key handles only */ - DWORD flags =3D CRYPT_ACQUIRE_COMPARE_KEY_FLAG - | CRYPT_ACQUIRE_ONLY_NCRYPT_KEY_FLAG; - if (!CryptAcquireCertificatePrivateKey(cd->cert_context, flags, NULL, - &cd->crypt_prov, &cd->key_spec,= &cd->free_crypt_prov)) + DWORD flags =3D CRYPT_ACQUIRE_COMPARE_KEY_FLAG | CRYPT_ACQUIRE_ONLY_NC= RYPT_KEY_FLAG; + if (!CryptAcquireCertificatePrivateKey(cd->cert_context, flags, NULL, = &cd->crypt_prov, + &cd->key_spec, &cd->free_crypt_= prov)) { /* private key may be in a token not available, or incompatible wi= th CNG */ - msg(M_NONFATAL|M_ERRNO, "Error in cryptoapicert: failed to acquire= key. Key not present or " + msg(M_NONFATAL | M_ERRNO, + "Error in cryptoapicert: failed to acquire key. Key not presen= t or " "is in a legacy token not supported by Windows CNG API"); X509_free(*cert); goto err; @@ -576,8 +582,8 @@ EVP_PKEY *pkey =3D X509_get_pubkey(*cert); cd->pubkey =3D pkey; /* will be freed with cd */ - *privkey =3D xkey_load_generic_key(tls_libctx, cd, pkey, - xkey_cng_sign, (XKEY_PRIVKEY_FREE_fn = *) CAPI_DATA_free); + *privkey =3D xkey_load_generic_key(tls_libctx, cd, pkey, xkey_cng_sign, + (XKEY_PRIVKEY_FREE_fn *)CAPI_DATA_fre= e); gc_free(&gc); return 1; /* do not free cd -- its kept by xkey provider */ @@ -598,8 +604,7 @@ { return ret; } - if (SSL_CTX_use_certificate(ssl_ctx, cert) - && SSL_CTX_use_PrivateKey(ssl_ctx, privkey)) + if (SSL_CTX_use_certificate(ssl_ctx, cert) && SSL_CTX_use_PrivateKey(s= sl_ctx, privkey)) { crypto_print_openssl_errors(M_WARN); ret =3D 1; @@ -612,5 +617,5 @@ return ret; } -#endif /* HAVE_XKEY_PROVIDER */ -#endif /* _WIN32 */ +#endif /* HAVE_XKEY_PROVIDER */ +#endif /* _WIN32 */ diff --git a/src/openvpn/dco.c b/src/openvpn/dco.c index df70e87..1abebbb 100644 --- a/src/openvpn/dco.c +++ b/src/openvpn/dco.c @@ -51,14 +51,13 @@ #endif static int -dco_install_key(struct tls_multi *multi, struct key_state *ks, - const uint8_t *encrypt_key, const uint8_t *encrypt_iv, - const uint8_t *decrypt_key, const uint8_t *decrypt_iv, +dco_install_key(struct tls_multi *multi, struct key_state *ks, const uint8= _t *encrypt_key, + const uint8_t *encrypt_iv, const uint8_t *decrypt_key, con= st uint8_t *decrypt_iv, const char *ciphername) { - msg(D_DCO_DEBUG, "%s: peer_id=3D%d keyid=3D%d, currently %d keys insta= lled", - __func__, multi->dco_peer_id, ks->key_id, multi->dco_keys_installe= d); + msg(D_DCO_DEBUG, "%s: peer_id=3D%d keyid=3D%d, currently %d keys insta= lled", __func__, + multi->dco_peer_id, ks->key_id, multi->dco_keys_installed); /* Install a key in the PRIMARY slot only when no other key exist. * From that moment on, any new key will be installed in the SECONDARY @@ -71,33 +70,27 @@ slot =3D OVPN_KEY_SLOT_SECONDARY; } - int ret =3D dco_new_key(multi->dco, multi->dco_peer_id, ks->key_id, sl= ot, - encrypt_key, encrypt_iv, - decrypt_key, decrypt_iv, - ciphername); + int ret =3D dco_new_key(multi->dco, multi->dco_peer_id, ks->key_id, sl= ot, encrypt_key, encrypt_iv, + decrypt_key, decrypt_iv, ciphername); if ((ret =3D=3D 0) && (multi->dco_keys_installed < 2)) { multi->dco_keys_installed++; - ks->dco_status =3D (slot =3D=3D OVPN_KEY_SLOT_PRIMARY) ? DCO_INSTA= LLED_PRIMARY : - DCO_INSTALLED_SECONDARY; + ks->dco_status =3D + (slot =3D=3D OVPN_KEY_SLOT_PRIMARY) ? DCO_INSTALLED_PRIMARY : = DCO_INSTALLED_SECONDARY; } return ret; } int -init_key_dco_bi(struct tls_multi *multi, struct key_state *ks, - const struct key2 *key2, int key_direction, - const char *ciphername, bool server) +init_key_dco_bi(struct tls_multi *multi, struct key_state *ks, const struc= t key2 *key2, + int key_direction, const char *ciphername, bool server) { struct key_direction_state kds; key_direction_state_init(&kds, key_direction); - return dco_install_key(multi, ks, - key2->keys[kds.out_key].cipher, - key2->keys[(int)server].hmac, - key2->keys[kds.in_key].cipher, - key2->keys[1 - (int)server].hmac, + return dco_install_key(multi, ks, key2->keys[kds.out_key].cipher, key2= ->keys[(int)server].hmac, + key2->keys[kds.in_key].cipher, key2->keys[1 - (= int)server].hmac, ciphername); } @@ -183,13 +176,15 @@ { if (secondary) { - msg(D_DCO_DEBUG, "Swapping primary and secondary keys to " + msg(D_DCO_DEBUG, + "Swapping primary and secondary keys to " "primary-id=3D%d secondary-id=3D%d", primary->key_id, secondary->key_id); } else { - msg(D_DCO_DEBUG, "Swapping primary and secondary keys to " + msg(D_DCO_DEBUG, + "Swapping primary and secondary keys to " "primary-id=3D%d secondary-id=3D(to be deleted)", primary->key_id); } @@ -275,13 +270,15 @@ #if defined(_WIN32) if (!proto_is_udp(ce->proto) && mode =3D=3D MODE_SERVER) { - msg(msglevel, "NOTE: TCP transport disables data channel offload o= n Windows in server mode."); + msg(msglevel, + "NOTE: TCP transport disables data channel offload on Windows = in server mode."); return false; } if (!ce->remote && !dco_win_supports_multipeer()) { - msg(msglevel, "NOTE: --remote is not defined. This DCO version doe= sn't support multipeer. Disabling Data Channel Offload"); + msg(msglevel, + "NOTE: --remote is not defined. This DCO version doesn't suppo= rt multipeer. Disabling Data Channel Offload"); return false; } @@ -310,7 +307,7 @@ if (!o->tls_client && !o->tls_server) { msg(msglevel, "No tls-client or tls-server option in configuration= " - "detected. Disabling data channel offload."); + "detected. Disabling data channel offload."); return false; } @@ -354,7 +351,8 @@ #if defined(_WIN32) if ((o->mode =3D=3D MODE_SERVER) && !dco_win_supports_multipeer()) { - msg(msglevel, "--mode server is set. This DCO version doesn't supp= ort multipeer. Disabling Data Channel Offload"); + msg(msglevel, + "--mode server is set. This DCO version doesn't support multip= eer. Disabling Data Channel Offload"); return false; } @@ -385,8 +383,8 @@ } else if ((ret < 0) && (ret !=3D -ENODEV)) { - msg(msglevel, "Cannot retrieve type of device %s: %s (%d)", o-= >dev, - strerror(-ret), ret); + msg(msglevel, "Cannot retrieve type of device %s: %s (%d)", o-= >dev, strerror(-ret), + ret); } } #endif /* if defined(_WIN32) */ @@ -401,13 +399,13 @@ if (!capng_have_capability(CAPNG_EFFECTIVE, CAP_SETPCAP)) { msg(msglevel, "--user specified but lacking CAP_SETPCAP. " - "Cannot retain CAP_NET_ADMIN. Disabling data channel offlo= ad"); + "Cannot retain CAP_NET_ADMIN. Disabling data cha= nnel offload"); return false; } if (!capng_have_capability(CAPNG_PERMITTED, CAP_NET_ADMIN)) { msg(msglevel, "--user specified but not permitted to retain CA= P_NET_ADMIN. " - "Disabling data channel offload"); + "Disabling data channel offload"); return false; } } @@ -438,16 +436,18 @@ if (o->enable_ncp_fallback && !tls_item_in_cipher_list(o->ciphername, dco_get_supported_ciphe= rs())) { - msg(msglevel, "Note: --data-ciphers-fallback with cipher '%s' " - "disables data channel offload.", o->ciphername); + msg(msglevel, + "Note: --data-ciphers-fallback with cipher '%s' " + "disables data channel offload.", + o->ciphername); return false; } #if defined(USE_COMP) - if (o->comp.alg !=3D COMP_ALG_UNDEF - || o->comp.flags & COMP_F_ALLOW_ASYM) + if (o->comp.alg !=3D COMP_ALG_UNDEF || o->comp.flags & COMP_F_ALLOW_AS= YM) { - msg(msglevel, "Note: '--allow-compression' is not set to 'no', dis= abling data channel offload."); + msg(msglevel, + "Note: '--allow-compression' is not set to 'no', disabling dat= a channel offload."); if (o->mode =3D=3D MODE_SERVER && !(o->comp.flags & COMP_F_MIGRATE= )) { @@ -466,8 +466,10 @@ { if (!tls_item_in_cipher_list(token, dco_get_supported_ciphers())) { - msg(msglevel, "Note: cipher '%s' in --data-ciphers is not supp= orted " - "by ovpn-dco, disabling data channel offload.", token); + msg(msglevel, + "Note: cipher '%s' in --data-ciphers is not supported " + "by ovpn-dco, disabling data channel offload.", + token); gc_free(&gc); return false; } @@ -483,7 +485,7 @@ if (!o->use_peer_id) { msg(msglevel, "OPTIONS IMPORT: Server did not request DATA_V2 pack= et " - "format required for data channel offload"); + "format required for data channel offload"); return false; } return true; @@ -513,8 +515,7 @@ } #endif int ret =3D dco_new_peer(&c->c1.tuntap->dco, multi->peer_id, sock->sd,= NULL, - proto_is_dgram(sock->info.proto) ? remoteaddr := NULL, - NULL, NULL); + proto_is_dgram(sock->info.proto) ? remoteaddr := NULL, NULL, NULL); if (ret < 0) { return ret; @@ -547,7 +548,8 @@ #if ENABLE_IP_PKTINFO struct context *c =3D &mi->context; - if (!proto_is_udp(c->c2.link_sockets[0]->info.proto) || !(c->options.s= ockflags & SF_USE_IP_PKTINFO)) + if (!proto_is_udp(c->c2.link_sockets[0]->info.proto) + || !(c->options.sockflags & SF_USE_IP_PKTINFO)) { return false; } @@ -631,8 +633,8 @@ localaddr =3D (struct sockaddr *)&local; } - int ret =3D dco_new_peer(&c->c1.tuntap->dco, peer_id, sd, localaddr, - remoteaddr, vpn_addr4, vpn_addr6); + int ret =3D + dco_new_peer(&c->c1.tuntap->dco, peer_id, sd, localaddr, remoteadd= r, vpn_addr4, vpn_addr6); if (ret < 0) { return ret; @@ -644,8 +646,7 @@ } void -dco_install_iroute(struct multi_context *m, struct multi_instance *mi, - struct mroute_addr *addr) +dco_install_iroute(struct multi_context *m, struct multi_instance *mi, str= uct mroute_addr *addr) { #if defined(TARGET_LINUX) || defined(TARGET_FREEBSD) || defined(_WIN32) if (!dco_enabled(&m->top.options)) @@ -666,7 +667,8 @@ if (addrtype =3D=3D MR_ADDR_IPV6) { #if defined(_WIN32) - dco_win_add_iroute_ipv6(&c->c1.tuntap->dco, addr->v6.addr, addr->n= etbits, c->c2.tls_multi->peer_id); + dco_win_add_iroute_ipv6(&c->c1.tuntap->dco, addr->v6.addr, addr->n= etbits, + c->c2.tls_multi->peer_id); #else net_route_v6_add(&m->top.net_ctx, &addr->v6.addr, addr->netbits, &mi->context.c2.push_ifconfig_ipv6_local, c->c1.t= untap->actual_name, 0, @@ -676,12 +678,12 @@ else if (addrtype =3D=3D MR_ADDR_IPV4) { #if defined(_WIN32) - dco_win_add_iroute_ipv4(&c->c1.tuntap->dco, addr->v4.addr, addr->n= etbits, c->c2.tls_multi->peer_id); + dco_win_add_iroute_ipv4(&c->c1.tuntap->dco, addr->v4.addr, addr->n= etbits, + c->c2.tls_multi->peer_id); #else in_addr_t dest =3D htonl(addr->v4.addr); - net_route_v4_add(&m->top.net_ctx, &dest, addr->netbits, - &mi->context.c2.push_ifconfig_local, c->c1.tuntap= ->actual_name, 0, - DCO_IROUTE_METRIC); + net_route_v4_add(&m->top.net_ctx, &dest, addr->netbits, &mi->conte= xt.c2.push_ifconfig_local, + c->c1.tuntap->actual_name, 0, DCO_IROUTE_METRIC); #endif } #endif /* if defined(TARGET_LINUX) || defined(TARGET_FREEBSD) || defined(_= WIN32) */ @@ -701,32 +703,28 @@ if (mi->context.c2.push_ifconfig_defined) { - for (const struct iroute *ir =3D c->options.iroutes; - ir; - ir =3D ir->next) + for (const struct iroute *ir =3D c->options.iroutes; ir; ir =3D ir= ->next) { #if defined(_WIN32) dco_win_del_iroute_ipv4(&c->c1.tuntap->dco, htonl(ir->network)= , ir->netbits); #else net_route_v4_del(&m->top.net_ctx, &ir->network, ir->netbits, - &mi->context.c2.push_ifconfig_local, c->c1.tu= ntap->actual_name, - 0, DCO_IROUTE_METRIC); + &mi->context.c2.push_ifconfig_local, c->c1.tu= ntap->actual_name, 0, + DCO_IROUTE_METRIC); #endif } } if (mi->context.c2.push_ifconfig_ipv6_defined) { - for (const struct iroute_ipv6 *ir6 =3D c->options.iroutes_ipv6; - ir6; - ir6 =3D ir6->next) + for (const struct iroute_ipv6 *ir6 =3D c->options.iroutes_ipv6; ir= 6; ir6 =3D ir6->next) { #if defined(_WIN32) dco_win_del_iroute_ipv6(&c->c1.tuntap->dco, ir6->network, ir6-= >netbits); #else net_route_v6_del(&m->top.net_ctx, &ir6->network, ir6->netbits, - &mi->context.c2.push_ifconfig_ipv6_local, c->= c1.tuntap->actual_name, - 0, DCO_IROUTE_METRIC); + &mi->context.c2.push_ifconfig_ipv6_local, c->= c1.tuntap->actual_name, 0, + DCO_IROUTE_METRIC); #endif } } diff --git a/src/openvpn/dco.h b/src/openvpn/dco.h index 95abf71..59acb18 100644 --- a/src/openvpn/dco.h +++ b/src/openvpn/dco.h @@ -43,8 +43,8 @@ struct tls_multi; struct tuntap; -#define DCO_IROUTE_METRIC 100 -#define DCO_DEFAULT_METRIC 200 +#define DCO_IROUTE_METRIC 100 +#define DCO_DEFAULT_METRIC 200 #if defined(ENABLE_DCO) @@ -153,9 +153,8 @@ * * @return 0 on success or a negative error code otherwise */ -int init_key_dco_bi(struct tls_multi *multi, struct key_state *ks, - const struct key2 *key2, int key_direction, - const char *ciphername, bool server); +int init_key_dco_bi(struct tls_multi *multi, struct key_state *ks, const s= truct key2 *key2, + int key_direction, const char *ciphername, bool server= ); /** * Possibly swap or wipe keys from DCO @@ -187,8 +186,8 @@ * * @return 0 on success or a negative error code otherwi= se */ -int dco_set_peer(dco_context_t *dco, unsigned int peerid, - int keepalive_interval, int keepalive_timeout, int mss); +int dco_set_peer(dco_context_t *dco, unsigned int peerid, int keepalive_in= terval, + int keepalive_timeout, int mss); /** * Remove a peer from DCO @@ -257,7 +256,7 @@ { return false; } -#else /* if defined(ENABLE_DCO) */ +#else /* if defined(ENABLE_DCO) */ typedef void *dco_context_t; @@ -321,9 +320,8 @@ } static inline int -init_key_dco_bi(struct tls_multi *multi, struct key_state *ks, - const struct key2 *key2, int key_direction, - const char *ciphername, bool server) +init_key_dco_bi(struct tls_multi *multi, struct key_state *ks, const struc= t key2 *key2, + int key_direction, const char *ciphername, bool server) { return 0; } @@ -342,8 +340,8 @@ } static inline int -dco_set_peer(dco_context_t *dco, unsigned int peerid, - int keepalive_interval, int keepalive_timeout, int mss) +dco_set_peer(dco_context_t *dco, unsigned int peerid, int keepalive_interv= al, int keepalive_timeout, + int mss) { return 0; } @@ -360,8 +358,7 @@ } static inline void -dco_install_iroute(struct multi_context *m, struct multi_instance *mi, - struct mroute_addr *addr) +dco_install_iroute(struct multi_context *m, struct multi_instance *mi, str= uct mroute_addr *addr) { } diff --git a/src/openvpn/dco_freebsd.c b/src/openvpn/dco_freebsd.c index 04c1e3d..931f9f6 100644 --- a/src/openvpn/dco_freebsd.c +++ b/src/openvpn/dco_freebsd.c @@ -133,9 +133,8 @@ } int -dco_new_peer(dco_context_t *dco, unsigned int peerid, int sd, - struct sockaddr *localaddr, struct sockaddr *remoteaddr, - struct in_addr *vpn_ipv4, struct in6_addr *vpn_ipv6) +dco_new_peer(dco_context_t *dco, unsigned int peerid, int sd, struct socka= ddr *localaddr, + struct sockaddr *remoteaddr, struct in_addr *vpn_ipv4, struct= in6_addr *vpn_ipv6) { struct ifdrv drv; nvlist_t *nvl, *local_nvl, *remote_nvl; @@ -159,8 +158,7 @@ if (vpn_ipv4) { - nvlist_add_binary(nvl, "vpn_ipv4", &vpn_ipv4->s_addr, - sizeof(vpn_ipv4->s_addr)); + nvlist_add_binary(nvl, "vpn_ipv4", &vpn_ipv4->s_addr, sizeof(vpn_i= pv4->s_addr)); } if (vpn_ipv6) @@ -278,7 +276,7 @@ if (ret) { ret =3D -errno; - msg(M_WARN|M_ERRNO, "Failed to create interface %s (SIOCIFCREATE2)= ", ifr.ifr_name); + msg(M_WARN | M_ERRNO, "Failed to create interface %s (SIOCIFCREATE= 2)", ifr.ifr_name); return ret; } @@ -300,7 +298,7 @@ ret =3D -errno; /* Delete the created interface again. */ (void)ioctl(tt->dco.fd, SIOCIFDESTROY, &ifr); - msg(M_WARN|M_ERRNO, "Failed to create interface %s (SIOCSIFNAME)",= ifr.ifr_data); + msg(M_WARN | M_ERRNO, "Failed to create interface %s (SIOCSIFNAME)= ", ifr.ifr_data); return ret; } @@ -412,8 +410,7 @@ } int -dco_del_key(dco_context_t *dco, unsigned int peerid, - dco_key_slot_t slot) +dco_del_key(dco_context_t *dco, unsigned int peerid, dco_key_slot_t slot) { struct ifdrv drv; nvlist_t *nvl; @@ -483,18 +480,16 @@ } int -dco_new_key(dco_context_t *dco, unsigned int peerid, int keyid, - dco_key_slot_t slot, - const uint8_t *encrypt_key, const uint8_t *encrypt_iv, - const uint8_t *decrypt_key, const uint8_t *decrypt_iv, - const char *ciphername) +dco_new_key(dco_context_t *dco, unsigned int peerid, int keyid, dco_key_sl= ot_t slot, + const uint8_t *encrypt_key, const uint8_t *encrypt_iv, const u= int8_t *decrypt_key, + const uint8_t *decrypt_iv, const char *ciphername) { struct ifdrv drv; nvlist_t *nvl, *encrypt_nvl, *decrypt_nvl; int ret; - msg(D_DCO_DEBUG, "%s: slot %d, key-id %d, peer-id %d, cipher %s", - __func__, slot, keyid, peerid, ciphername); + msg(D_DCO_DEBUG, "%s: slot %d, key-id %d, peer-id %d, cipher %s", __fu= nc__, slot, keyid, peerid, + ciphername); nvl =3D nvlist_create(0); @@ -532,16 +527,15 @@ } int -dco_set_peer(dco_context_t *dco, unsigned int peerid, - int keepalive_interval, int keepalive_timeout, +dco_set_peer(dco_context_t *dco, unsigned int peerid, int keepalive_interv= al, int keepalive_timeout, int mss) { struct ifdrv drv; nvlist_t *nvl; int ret; - msg(D_DCO_DEBUG, "%s: peer-id %d, ping interval %d, ping timeout %d", - __func__, peerid, keepalive_interval, keepalive_timeout); + msg(D_DCO_DEBUG, "%s: peer-id %d, ping interval %d, ping timeout %d", = __func__, peerid, + keepalive_interval, keepalive_timeout); nvl =3D nvlist_create(0); nvlist_add_number(nvl, "peerid", peerid); @@ -633,7 +627,8 @@ dco->dco_message_type =3D OVPN_CMD_SWAP_KEYS; break; - case OVPN_NOTIF_FLOAT: { + case OVPN_NOTIF_FLOAT: + { const nvlist_t *address; if (!nvlist_exists_nvlist(nvl, "address")) @@ -780,7 +775,6 @@ static void dco_update_peer_stat(struct multi_context *m, uint32_t peerid, const nvlis= t_t *nvl) { - if (peerid >=3D m->max_clients || !m->instances[peerid]) { msg(M_WARN, "dco_update_peer_stat: invalid peer ID %d returned by = kernel", peerid); @@ -796,7 +790,6 @@ int dco_get_peer_stats_multi(dco_context_t *dco, const bool raise_sigusr1_on_e= rr) { - struct ifdrv drv; uint8_t *buf =3D NULL; size_t buf_size =3D 4096; diff --git a/src/openvpn/dco_freebsd.h b/src/openvpn/dco_freebsd.h index cbb1dda..2f486f0 100644 --- a/src/openvpn/dco_freebsd.h +++ b/src/openvpn/dco_freebsd.h @@ -26,26 +26,29 @@ #include "ovpn_dco_freebsd.h" -#define DCO_IROUTE_METRIC 100 +#define DCO_IROUTE_METRIC 100 typedef enum ovpn_key_slot dco_key_slot_t; typedef enum ovpn_key_cipher dco_cipher_t; -enum ovpn_message_type_t { +enum ovpn_message_type_t +{ OVPN_CMD_DEL_PEER, OVPN_CMD_PACKET, OVPN_CMD_SWAP_KEYS, OVPN_CMD_FLOAT_PEER, }; -enum ovpn_del_reason_t { +enum ovpn_del_reason_t +{ OVPN_DEL_PEER_REASON_EXPIRED, OVPN_DEL_PEER_REASON_TRANSPORT_ERROR, OVPN_DEL_PEER_REASON_USERSPACE, OVPN_DEL_PEER_REASON_TRANSPORT_DISCONNECT, }; -typedef struct dco_context { +typedef struct dco_context +{ bool open; int fd; int pipefd[2]; diff --git a/src/openvpn/dco_internal.h b/src/openvpn/dco_internal.h index 96aa281..83013ef 100644 --- a/src/openvpn/dco_internal.h +++ b/src/openvpn/dco_internal.h @@ -59,17 +59,14 @@ * They are implemented by dco_linux.c */ -int dco_new_peer(dco_context_t *dco, unsigned int peerid, int sd, - struct sockaddr *localaddr, struct sockaddr *remoteaddr, - struct in_addr *vpn_ipv4, struct in6_addr *vpn_ipv6); +int dco_new_peer(dco_context_t *dco, unsigned int peerid, int sd, struct s= ockaddr *localaddr, + struct sockaddr *remoteaddr, struct in_addr *vpn_ipv4, st= ruct in6_addr *vpn_ipv6); int dco_del_peer(dco_context_t *dco, unsigned int peerid); -int dco_new_key(dco_context_t *dco, unsigned int peerid, int keyid, - dco_key_slot_t slot, - const uint8_t *encrypt_key, const uint8_t *encrypt_iv, - const uint8_t *decrypt_key, const uint8_t *decrypt_iv, - const char *ciphername); +int dco_new_key(dco_context_t *dco, unsigned int peerid, int keyid, dco_ke= y_slot_t slot, + const uint8_t *encrypt_key, const uint8_t *encrypt_iv, con= st uint8_t *decrypt_key, + const uint8_t *decrypt_iv, const char *ciphername); int dco_del_key(dco_context_t *dco, unsigned int peerid, dco_key_slot_t sl= ot); diff --git a/src/openvpn/dco_linux.c b/src/openvpn/dco_linux.c index ab59e3e..a3907fe 100644 --- a/src/openvpn/dco_linux.c +++ b/src/openvpn/dco_linux.c @@ -54,8 +54,7 @@ * have to explicitly do it to prevent the kernel from failing upon * parsing of the message */ -#define nla_nest_start(_msg, _type) \ - nla_nest_start(_msg, (_type) | NLA_F_NESTED) +#define nla_nest_start(_msg, _type) nla_nest_start(_msg, (_type) | NLA_F_N= ESTED) static int ovpn_get_mcast_id(dco_context_t *dco); @@ -89,8 +88,7 @@ ret =3D genl_connect(nl_sock); if (ret) { - msg(msglevel, "Cannot connect to generic netlink: %s", - nl_geterror(ret)); + msg(msglevel, "Cannot connect to generic netlink: %s", nl_geterror= (ret)); goto err_sock; } set_cloexec(nl_socket_get_fd(nl_sock)); @@ -98,8 +96,7 @@ ret =3D genl_ctrl_resolve(nl_sock, OVPN_FAMILY_NAME); if (ret < 0) { - msg(msglevel, "Cannot find ovpn_dco netlink component: %s", - nl_geterror(ret)); + msg(msglevel, "Cannot find ovpn_dco netlink component: %s", nl_get= error(ret)); } err_sock: @@ -157,7 +154,8 @@ default: if (ret) { - msg(M_NONFATAL, "%s: netlink reports error (%d): %s", pref= ix, ret, nl_geterror(-ret)); + msg(M_NONFATAL, "%s: netlink reports error (%d): %s", pref= ix, ret, + nl_geterror(-ret)); } break; } @@ -188,8 +186,8 @@ if (dco->status < 0) { - msg(M_INFO, "%s: failed to send netlink message: %s (%d)", - prefix, strerror(-dco->status), dco->status); + msg(M_INFO, "%s: failed to send netlink message: %s (%d)", prefix,= strerror(-dco->status), + dco->status); } return dco->status; @@ -201,7 +199,6 @@ struct sockaddr_in6 *sock6 =3D (struct sockaddr_in6 *)sock; if (sock->sa_family =3D=3D AF_INET6 && IN6_IS_ADDR_V4MAPPED(&sock6->si= n6_addr)) { - struct sockaddr_in *sock4; ALLOC_OBJ_CLEAR_GC(sock4, struct sockaddr_in, gc); memcpy(&sock4->sin_addr, sock6->sin6_addr.s6_addr + 12, 4); @@ -213,9 +210,8 @@ } int -dco_new_peer(dco_context_t *dco, unsigned int peerid, int sd, - struct sockaddr *localaddr, struct sockaddr *remoteaddr, - struct in_addr *vpn_ipv4, struct in6_addr *vpn_ipv6) +dco_new_peer(dco_context_t *dco, unsigned int peerid, int sd, struct socka= ddr *localaddr, + struct sockaddr *remoteaddr, struct in_addr *vpn_ipv4, struct= in6_addr *vpn_ipv6) { struct gc_arena gc =3D gc_new(); const char *remotestr =3D "[undefined]"; @@ -223,8 +219,7 @@ { remotestr =3D print_sockaddr(remoteaddr, &gc); } - msg(D_DCO_DEBUG, "%s: peer-id %d, fd %d, remote addr: %s", __func__, - peerid, sd, remotestr); + msg(D_DCO_DEBUG, "%s: peer-id %d, fd %d, remote addr: %s", __func__, p= eerid, sd, remotestr); struct nl_msg *nl_msg =3D ovpn_dco_nlmsg_create(dco, OVPN_CMD_PEER_NEW= ); struct nlattr *attr =3D nla_nest_start(nl_msg, OVPN_A_PEER); @@ -242,14 +237,17 @@ { NLA_PUT(nl_msg, OVPN_A_PEER_REMOTE_IPV4, sizeof(struct in_addr= ), &((struct sockaddr_in *)remoteaddr)->sin_addr); - NLA_PUT_U16(nl_msg, OVPN_A_PEER_REMOTE_PORT, ((struct sockaddr= _in *)remoteaddr)->sin_port); + NLA_PUT_U16(nl_msg, OVPN_A_PEER_REMOTE_PORT, + ((struct sockaddr_in *)remoteaddr)->sin_port); } else if (remoteaddr->sa_family =3D=3D AF_INET6) { NLA_PUT(nl_msg, OVPN_A_PEER_REMOTE_IPV6, sizeof(struct in6_add= r), &((struct sockaddr_in6 *)remoteaddr)->sin6_addr); - NLA_PUT_U16(nl_msg, OVPN_A_PEER_REMOTE_PORT, ((struct sockaddr= _in6 *)remoteaddr)->sin6_port); - NLA_PUT_U32(nl_msg, OVPN_A_PEER_REMOTE_IPV6_SCOPE_ID, ((struct= sockaddr_in6 *)remoteaddr)->sin6_scope_id); + NLA_PUT_U16(nl_msg, OVPN_A_PEER_REMOTE_PORT, + ((struct sockaddr_in6 *)remoteaddr)->sin6_port); + NLA_PUT_U32(nl_msg, OVPN_A_PEER_REMOTE_IPV6_SCOPE_ID, + ((struct sockaddr_in6 *)remoteaddr)->sin6_scope_id= ); } } @@ -275,8 +273,7 @@ } if (vpn_ipv6) { - NLA_PUT(nl_msg, OVPN_A_PEER_VPN_IPV6, sizeof(struct in6_addr), - vpn_ipv6); + NLA_PUT(nl_msg, OVPN_A_PEER_VPN_IPV6, sizeof(struct in6_addr), vpn= _ipv6); } nla_nest_end(nl_msg, attr); @@ -289,7 +286,7 @@ } static int -ovpn_nl_cb_finish(struct nl_msg (*msg) __attribute__ ((unused)), void *arg) +ovpn_nl_cb_finish(struct nl_msg(*msg) __attribute__((unused)), void *arg) { int *status =3D arg; @@ -310,7 +307,8 @@ * missing at the message level * @NLMSGERR_ATTR_MISS_NEST: offset of the nest where attribute was missing */ -enum ovpn_nlmsgerr_attrs { +enum ovpn_nlmsgerr_attrs +{ OVPN_NLMSGERR_ATTR_MISS_TYPE =3D 5, OVPN_NLMSGERR_ATTR_MISS_NEST =3D 6, OVPN_NLMSGERR_ATTR_MAX =3D 6, @@ -325,8 +323,7 @@ * reply to see if it contains a human-readable error. If found, it is pri= nted. */ static int -ovpn_nl_cb_error(struct sockaddr_nl (*nla) __attribute__ ((unused)), - struct nlmsgerr *err, void *arg) +ovpn_nl_cb_error(struct sockaddr_nl(*nla) __attribute__((unused)), struct = nlmsgerr *err, void *arg) { struct nlmsghdr *nlh =3D (struct nlmsghdr *)err - 1; struct nlattr *tb_msg[OVPN_NLMSGERR_ATTR_MAX + 1]; @@ -360,8 +357,7 @@ { len =3D strnlen((char *)nla_data(tb_msg[NLMSGERR_ATTR_MSG]), nla_len(tb_msg[NLMSGERR_ATTR_MSG])); - msg(M_WARN, "kernel error: %*s", len, - (char *)nla_data(tb_msg[NLMSGERR_ATTR_MSG])); + msg(M_WARN, "kernel error: %*s", len, (char *)nla_data(tb_msg[NLMS= GERR_ATTR_MSG])); } if (tb_msg[OVPN_NLMSGERR_ATTR_MISS_NEST]) @@ -387,7 +383,7 @@ if (dco->ovpn_dco_mcast_id < 0) { - msg(M_FATAL, "cannot get mcast group: %s", nl_geterror(dco->ovpn_= dco_mcast_id)); + msg(M_FATAL, "cannot get mcast group: %s", nl_geterror(dco->ovpn_d= co_mcast_id)); } /* Register for ovpn-dco specific multicast messages that the kernel m= ay @@ -417,14 +413,12 @@ int ret =3D genl_connect(dco->nl_sock); if (ret) { - msg(M_FATAL, "Cannot connect to generic netlink: %s", - nl_geterror(ret)); + msg(M_FATAL, "Cannot connect to generic netlink: %s", nl_geterror(= ret)); } /* enable Extended ACK for detailed error reporting */ ret =3D 1; - setsockopt(nl_socket_get_fd(dco->nl_sock), SOL_NETLINK, NETLINK_EXT_AC= K, - &ret, sizeof(ret)); + setsockopt(nl_socket_get_fd(dco->nl_sock), SOL_NETLINK, NETLINK_EXT_AC= K, &ret, sizeof(ret)); /* set close on exec and non-block on the netlink socket */ set_cloexec(nl_socket_get_fd(dco->nl_sock)); @@ -440,10 +434,8 @@ dco->dco_message_peer_id =3D -1; nl_cb_err(dco->nl_cb, NL_CB_CUSTOM, ovpn_nl_cb_error, &dco->status); - nl_cb_set(dco->nl_cb, NL_CB_FINISH, NL_CB_CUSTOM, ovpn_nl_cb_finish, - &dco->status); - nl_cb_set(dco->nl_cb, NL_CB_ACK, NL_CB_CUSTOM, ovpn_nl_cb_finish, - &dco->status); + nl_cb_set(dco->nl_cb, NL_CB_FINISH, NL_CB_CUSTOM, ovpn_nl_cb_finish, &= dco->status); + nl_cb_set(dco->nl_cb, NL_CB_ACK, NL_CB_CUSTOM, ovpn_nl_cb_finish, &dco= ->status); nl_cb_set(dco->nl_cb, NL_CB_VALID, NL_CB_CUSTOM, ovpn_handle_msg, dco); ovpn_dco_register(dco); @@ -456,7 +448,7 @@ /* nl library sets the buffer size to 32k/32k by default which is some= times * overrun with very fast connecting/disconnecting clients. * TODO: fix this in a better and more reliable way */ - ASSERT(!nl_socket_set_buffer_size(dco->nl_sock, 1024*1024, 1024*1024)); + ASSERT(!nl_socket_set_buffer_size(dco->nl_sock, 1024 * 1024, 1024 * 10= 24)); } bool @@ -578,8 +570,7 @@ int -dco_del_key(dco_context_t *dco, unsigned int peerid, - dco_key_slot_t slot) +dco_del_key(dco_context_t *dco, unsigned int peerid, dco_key_slot_t slot) { int ret =3D -EMSGSIZE; msg(D_DCO_DEBUG, "%s: peer-id %d, slot %d", __func__, peerid, slot); @@ -603,14 +594,12 @@ } int -dco_new_key(dco_context_t *dco, unsigned int peerid, int keyid, - dco_key_slot_t slot, - const uint8_t *encrypt_key, const uint8_t *encrypt_iv, - const uint8_t *decrypt_key, const uint8_t *decrypt_iv, - const char *ciphername) +dco_new_key(dco_context_t *dco, unsigned int peerid, int keyid, dco_key_sl= ot_t slot, + const uint8_t *encrypt_key, const uint8_t *encrypt_iv, const u= int8_t *decrypt_key, + const uint8_t *decrypt_iv, const char *ciphername) { - msg(D_DCO_DEBUG, "%s: slot %d, key-id %d, peer-id %d, cipher %s", - __func__, slot, keyid, peerid, ciphername); + msg(D_DCO_DEBUG, "%s: slot %d, key-id %d, peer-id %d, cipher %s", __fu= nc__, slot, keyid, peerid, + ciphername); const size_t key_len =3D cipher_kt_key_size(ciphername); const int nonce_tail_len =3D 8; @@ -631,23 +620,19 @@ NLA_PUT_U32(nl_msg, OVPN_A_KEYCONF_KEY_ID, keyid); NLA_PUT_U32(nl_msg, OVPN_A_KEYCONF_CIPHER_ALG, dco_cipher); - struct nlattr *key_enc =3D nla_nest_start(nl_msg, - OVPN_A_KEYCONF_ENCRYPT_DIR); + struct nlattr *key_enc =3D nla_nest_start(nl_msg, OVPN_A_KEYCONF_ENCRY= PT_DIR); if (dco_cipher !=3D OVPN_CIPHER_ALG_NONE) { NLA_PUT(nl_msg, OVPN_A_KEYDIR_CIPHER_KEY, key_len, encrypt_key); - NLA_PUT(nl_msg, OVPN_A_KEYDIR_NONCE_TAIL, nonce_tail_len, - encrypt_iv); + NLA_PUT(nl_msg, OVPN_A_KEYDIR_NONCE_TAIL, nonce_tail_len, encrypt_= iv); } nla_nest_end(nl_msg, key_enc); - struct nlattr *key_dec =3D nla_nest_start(nl_msg, - OVPN_A_KEYCONF_DECRYPT_DIR); + struct nlattr *key_dec =3D nla_nest_start(nl_msg, OVPN_A_KEYCONF_DECRY= PT_DIR); if (dco_cipher !=3D OVPN_CIPHER_ALG_NONE) { NLA_PUT(nl_msg, OVPN_A_KEYDIR_CIPHER_KEY, key_len, decrypt_key); - NLA_PUT(nl_msg, OVPN_A_KEYDIR_NONCE_TAIL, nonce_tail_len, - decrypt_iv); + NLA_PUT(nl_msg, OVPN_A_KEYDIR_NONCE_TAIL, nonce_tail_len, decrypt_= iv); } nla_nest_end(nl_msg, key_dec); @@ -662,11 +647,11 @@ } int -dco_set_peer(dco_context_t *dco, unsigned int peerid, - int keepalive_interval, int keepalive_timeout, int mss) +dco_set_peer(dco_context_t *dco, unsigned int peerid, int keepalive_interv= al, int keepalive_timeout, + int mss) { - msg(D_DCO_DEBUG, "%s: peer-id %d, keepalive %d/%d, mss %d", __func__, - peerid, keepalive_interval, keepalive_timeout, mss); + msg(D_DCO_DEBUG, "%s: peer-id %d, keepalive %d/%d, mss %d", __func__, = peerid, + keepalive_interval, keepalive_timeout, mss); struct nl_msg *nl_msg =3D ovpn_dco_nlmsg_create(dco, OVPN_CMD_PEER_SET= ); if (!nl_msg) @@ -677,10 +662,8 @@ struct nlattr *attr =3D nla_nest_start(nl_msg, OVPN_A_PEER); int ret =3D -EMSGSIZE; NLA_PUT_U32(nl_msg, OVPN_A_PEER_ID, peerid); - NLA_PUT_U32(nl_msg, OVPN_A_PEER_KEEPALIVE_INTERVAL, - keepalive_interval); - NLA_PUT_U32(nl_msg, OVPN_A_PEER_KEEPALIVE_TIMEOUT, - keepalive_timeout); + NLA_PUT_U32(nl_msg, OVPN_A_PEER_KEEPALIVE_INTERVAL, keepalive_interval= ); + NLA_PUT_U32(nl_msg, OVPN_A_PEER_KEEPALIVE_TIMEOUT, keepalive_timeout); nla_nest_end(nl_msg, attr); ret =3D ovpn_nl_msg_send(dco, nl_msg, __func__); @@ -704,8 +687,7 @@ struct nlattr *tb[CTRL_ATTR_MAX + 1]; struct genlmsghdr *gnlh =3D nlmsg_data(nlmsg_hdr(msg)); - nla_parse(tb, CTRL_ATTR_MAX, genlmsg_attrdata(gnlh, 0), - genlmsg_attrlen(gnlh, 0), NULL); + nla_parse(tb, CTRL_ATTR_MAX, genlmsg_attrdata(gnlh, 0), genlmsg_attrle= n(gnlh, 0), NULL); if (!tb[CTRL_ATTR_MCAST_GROUPS]) { @@ -718,18 +700,16 @@ { struct nlattr *tb_mcgrp[CTRL_ATTR_MCAST_GRP_MAX + 1]; - nla_parse(tb_mcgrp, CTRL_ATTR_MCAST_GRP_MAX, - nla_data(mcgrp), nla_len(mcgrp), NULL); + nla_parse(tb_mcgrp, CTRL_ATTR_MCAST_GRP_MAX, nla_data(mcgrp), nla_= len(mcgrp), NULL); - if (!tb_mcgrp[CTRL_ATTR_MCAST_GRP_NAME] - || !tb_mcgrp[CTRL_ATTR_MCAST_GRP_ID]) + if (!tb_mcgrp[CTRL_ATTR_MCAST_GRP_NAME] || !tb_mcgrp[CTRL_ATTR_MCA= ST_GRP_ID]) { continue; } - if (strncmp(nla_data(tb_mcgrp[CTRL_ATTR_MCAST_GRP_NAME]), - OVPN_MCGRP_PEERS, - nla_len(tb_mcgrp[CTRL_ATTR_MCAST_GRP_NAME])) !=3D 0) + if (strncmp(nla_data(tb_mcgrp[CTRL_ATTR_MCAST_GRP_NAME]), OVPN_MCG= RP_PEERS, + nla_len(tb_mcgrp[CTRL_ATTR_MCAST_GRP_NAME])) + !=3D 0) { continue; } @@ -829,49 +809,41 @@ if (tb[OVPN_A_PEER_LINK_RX_BYTES]) { c2->dco_read_bytes =3D ovpn_nla_get_uint(tb[OVPN_A_PEER_LINK_RX_BY= TES]); - msg(D_DCO_DEBUG, "%s / dco_read_bytes: " counter_format, __func__, - c2->dco_read_bytes); + msg(D_DCO_DEBUG, "%s / dco_read_bytes: " counter_format, __func__,= c2->dco_read_bytes); } else { - msg(M_WARN, "%s: no link RX bytes provided in reply for peer %u", - __func__, id); + msg(M_WARN, "%s: no link RX bytes provided in reply for peer %u", = __func__, id); } if (tb[OVPN_A_PEER_LINK_TX_BYTES]) { c2->dco_write_bytes =3D ovpn_nla_get_uint(tb[OVPN_A_PEER_LINK_TX_B= YTES]); - msg(D_DCO_DEBUG, "%s / dco_write_bytes: " counter_format, __func__, - c2->dco_write_bytes); + msg(D_DCO_DEBUG, "%s / dco_write_bytes: " counter_format, __func__= , c2->dco_write_bytes); } else { - msg(M_WARN, "%s: no link TX bytes provided in reply for peer %u", - __func__, id); + msg(M_WARN, "%s: no link TX bytes provided in reply for peer %u", = __func__, id); } if (tb[OVPN_A_PEER_VPN_RX_BYTES]) { c2->tun_read_bytes =3D ovpn_nla_get_uint(tb[OVPN_A_PEER_VPN_RX_BYT= ES]); - msg(D_DCO_DEBUG, "%s / tun_read_bytes: " counter_format, __func__, - c2->tun_read_bytes); + msg(D_DCO_DEBUG, "%s / tun_read_bytes: " counter_format, __func__,= c2->tun_read_bytes); } else { - msg(M_WARN, "%s: no VPN RX bytes provided in reply for peer %u", - __func__, id); + msg(M_WARN, "%s: no VPN RX bytes provided in reply for peer %u", _= _func__, id); } if (tb[OVPN_A_PEER_VPN_TX_BYTES]) { c2->tun_write_bytes =3D ovpn_nla_get_uint(tb[OVPN_A_PEER_VPN_TX_BY= TES]); - msg(D_DCO_DEBUG, "%s / tun_write_bytes: " counter_format, __func__, - c2->tun_write_bytes); + msg(D_DCO_DEBUG, "%s / tun_write_bytes: " counter_format, __func__= , c2->tun_write_bytes); } else { - msg(M_WARN, "%s: no VPN TX bytes provided in reply for peer %u", - __func__, id); + msg(M_WARN, "%s: no VPN TX bytes provided in reply for peer %u", _= _func__, id); } } @@ -945,8 +917,7 @@ uint32_t ifindex =3D nla_get_u32(attrs[OVPN_A_IFINDEX]); if (ifindex !=3D dco->ifindex) { - msg(D_DCO_DEBUG, - "ovpn-dco: ignoring message for foreign ifindex %d", ifindex); + msg(D_DCO_DEBUG, "ovpn-dco: ignoring message for foreign ifindex %= d", ifindex); return false; } @@ -968,8 +939,7 @@ } struct nlattr *dp_attrs[OVPN_A_PEER_MAX + 1]; - if (nla_parse_nested(dp_attrs, OVPN_A_PEER_MAX, attrs[OVPN_A_PEER], - NULL)) + if (nla_parse_nested(dp_attrs, OVPN_A_PEER_MAX, attrs[OVPN_A_PEER], NU= LL)) { msg(D_DCO, "ovpn-dco: can't parse peer in PEER_DEL_NTF messsage"); return NL_STOP; @@ -1013,8 +983,7 @@ } struct nlattr *fp_attrs[OVPN_A_PEER_MAX + 1]; - if (nla_parse_nested(fp_attrs, OVPN_A_PEER_MAX, attrs[OVPN_A_PEER], - NULL)) + if (nla_parse_nested(fp_attrs, OVPN_A_PEER_MAX, attrs[OVPN_A_PEER], NU= LL)) { msg(D_DCO, "ovpn-dco: can't parse peer in PEER_FLOAT_NTF messsage"= ); return NL_STOP; @@ -1033,8 +1002,7 @@ } struct gc_arena gc =3D gc_new(); - msg(D_DCO_DEBUG, - "ovpn-dco: received CMD_PEER_FLOAT_NTF, ifindex: %u, peer-id %u, a= ddress: %s", + msg(D_DCO_DEBUG, "ovpn-dco: received CMD_PEER_FLOAT_NTF, ifindex: %u, = peer-id %u, address: %s", dco->ifindex, peerid, print_sockaddr((struct sockaddr *)&dco->dco_= float_peer_ss, &gc)); dco->dco_message_peer_id =3D (int)peerid; dco->dco_message_type =3D OVPN_CMD_PEER_FLOAT_NTF; @@ -1059,8 +1027,7 @@ } struct nlattr *dp_attrs[OVPN_A_KEYCONF_MAX + 1]; - if (nla_parse_nested(dp_attrs, OVPN_A_KEYCONF_MAX, - attrs[OVPN_A_KEYCONF], NULL)) + if (nla_parse_nested(dp_attrs, OVPN_A_KEYCONF_MAX, attrs[OVPN_A_KEYCON= F], NULL)) { msg(D_DCO, "ovpn-dco: can't parse keyconf in KEY_SWAP_NTF message"= ); return NL_STOP; @@ -1117,8 +1084,7 @@ return NL_STOP; } - if (nla_parse(attrs, OVPN_A_MAX, genlmsg_attrdata(gnlh, 0), - genlmsg_attrlen(gnlh, 0), NULL)) + if (nla_parse(attrs, OVPN_A_MAX, genlmsg_attrdata(gnlh, 0), genlmsg_at= trlen(gnlh, 0), NULL)) { msg(D_DCO, "received bogus data from ovpn-dco"); return NL_STOP; @@ -1206,8 +1172,8 @@ if (raise_sigusr1_on_err && ret < 0) { msg(M_WARN, "Error retrieving DCO peer stats: the underlying DCO p= eer" - "may have been deleted from the kernel without notifying " - "userspace. Restarting the session"); + "may have been deleted from the kernel without notifyi= ng " + "userspace. Restarting the session"); register_signal(dco->c->sig, SIGUSR1, "dco peer stats error"); } return ret; @@ -1230,8 +1196,7 @@ { if (resolve_ovpn_netlink_id(D_DCO_DEBUG) < 0) { - msg(msglevel, - "Note: Kernel support for ovpn-dco missing, disabling data cha= nnel offload."); + msg(msglevel, "Note: Kernel support for ovpn-dco missing, disablin= g data channel offload."); return false; } diff --git a/src/openvpn/dco_linux.h b/src/openvpn/dco_linux.h index 9f15199..310d433 100644 --- a/src/openvpn/dco_linux.h +++ b/src/openvpn/dco_linux.h @@ -31,8 +31,8 @@ #include /* Defines to avoid mismatching with other platforms */ -#define OVPN_CMD_DEL_PEER OVPN_CMD_PEER_DEL_NTF -#define OVPN_CMD_SWAP_KEYS OVPN_CMD_KEY_SWAP_NTF +#define OVPN_CMD_DEL_PEER OVPN_CMD_PEER_DEL_NTF +#define OVPN_CMD_SWAP_KEYS OVPN_CMD_KEY_SWAP_NTF #define OVPN_CMD_FLOAT_PEER OVPN_CMD_PEER_FLOAT_NTF typedef enum ovpn_key_slot dco_key_slot_t; @@ -42,12 +42,14 @@ #ifndef IFLA_OVPN_MAX -enum ovpn_mode { +enum ovpn_mode +{ OVPN_MODE_P2P, OVPN_MODE_MP, }; -enum ovpn_ifla_attrs { +enum ovpn_ifla_attrs +{ IFLA_OVPN_UNSPEC =3D 0, IFLA_OVPN_MODE, diff --git a/src/openvpn/dco_win.c b/src/openvpn/dco_win.c index d227965..5317ac1 100644 --- a/src/openvpn/dco_win.c +++ b/src/openvpn/dco_win.c @@ -75,14 +75,12 @@ bool res =3D false; - HANDLE h =3D CreateFile("\\\\.\\ovpn-dco-ver", GENERIC_READ, - 0, NULL, OPEN_EXISTING, 0, NULL); + HANDLE h =3D CreateFile("\\\\.\\ovpn-dco-ver", GENERIC_READ, 0, NULL, = OPEN_EXISTING, 0, NULL); if (h =3D=3D INVALID_HANDLE_VALUE) { /* fallback to a "normal" device, this will fail if device is alre= ady in use */ - h =3D CreateFile("\\\\.\\ovpn-dco", GENERIC_READ, - 0, NULL, OPEN_EXISTING, 0, NULL); + h =3D CreateFile("\\\\.\\ovpn-dco", GENERIC_READ, 0, NULL, OPEN_EX= ISTING, 0, NULL); } if (h =3D=3D INVALID_HANDLE_VALUE) @@ -91,8 +89,8 @@ } DWORD bytes_returned =3D 0; - if (!DeviceIoControl(h, OVPN_IOCTL_GET_VERSION, NULL, 0, - version, sizeof(*version), &bytes_returned, NULL)) + if (!DeviceIoControl(h, OVPN_IOCTL_GET_VERSION, NULL, 0, version, size= of(*version), + &bytes_returned, NULL)) { goto done; } @@ -145,7 +143,8 @@ /* set mp mode */ OVPN_MODE m =3D OVPN_MODE_MP; DWORD bytes_returned =3D 0; - if (!DeviceIoControl(dco->tt->hand, OVPN_IOCTL_SET_MODE, &m, sizeof(m)= , NULL, 0, &bytes_returned, NULL)) + if (!DeviceIoControl(dco->tt->hand, OVPN_IOCTL_SET_MODE, &m, sizeof(m)= , NULL, 0, + &bytes_returned, NULL)) { msg(M_ERR, "DeviceIoControl(OVPN_IOCTL_SET_MODE) failed"); } @@ -221,7 +220,7 @@ { volatile int *signal_received =3D &sig_info->signal_received; /* GetOverlappedResultEx is available starting from Windows 8 */ - typedef BOOL (WINAPI *get_overlapped_result_ex_t)(HANDLE, LPOVERLAPPED= , LPDWORD, DWORD, BOOL); + typedef BOOL(WINAPI * get_overlapped_result_ex_t)(HANDLE, LPOVERLAPPED= , LPDWORD, DWORD, BOOL); get_overlapped_result_ex_t get_overlapped_result_ex =3D (get_overlapped_result_ex_t)GetProcAddress(GetModuleHandle("Kernel= 32.dll"), "GetOverlappedResultEx"= ); @@ -295,8 +294,8 @@ } if (!cur) { - msg(M_FATAL, "%s: Socket bind failed: Addr to bind has no %s recor= d", - __func__, addr_family_name(ai_family)); + msg(M_FATAL, "%s: Socket bind failed: Addr to bind has no %s recor= d", __func__, + addr_family_name(ai_family)); } OVPN_MP_START_VPN in, out; @@ -322,7 +321,8 @@ } void -dco_p2p_new_peer(HANDLE handle, OVERLAPPED *ov, struct link_socket *sock, = struct signal_info *sig_info) +dco_p2p_new_peer(HANDLE handle, OVERLAPPED *ov, struct link_socket *sock, + struct signal_info *sig_info) { msg(D_DCO_DEBUG, "%s", __func__); @@ -333,8 +333,7 @@ struct sockaddr *local =3D NULL; struct sockaddr *remote =3D remoteaddr->ai_addr; - if (remoteaddr->ai_protocol =3D=3D IPPROTO_TCP - || remoteaddr->ai_socktype =3D=3D SOCK_STREAM) + if (remoteaddr->ai_protocol =3D=3D IPPROTO_TCP || remoteaddr->ai_sockt= ype =3D=3D SOCK_STREAM) { peer.Proto =3D OVPN_PROTO_TCP; } @@ -406,15 +405,15 @@ } else { - dco_connect_wait(handle, ov, get_server_poll_remaining_time(so= ck->server_poll_timeout), sig_info); + dco_connect_wait(handle, ov, get_server_poll_remaining_time(so= ck->server_poll_timeout), + sig_info); } } } int -dco_new_peer(dco_context_t *dco, unsigned int peerid, int sd, - struct sockaddr *localaddr, struct sockaddr *remoteaddr, - struct in_addr *vpn_ipv4, struct in6_addr *vpn_ipv6) +dco_new_peer(dco_context_t *dco, unsigned int peerid, int sd, struct socka= ddr *localaddr, + struct sockaddr *remoteaddr, struct in_addr *vpn_ipv4, struct= in6_addr *vpn_ipv6) { msg(D_DCO_DEBUG, "%s: peer-id %d, fd %d", __func__, peerid, sd); @@ -424,7 +423,7 @@ return 0; } - OVPN_MP_NEW_PEER newPeer =3D {0}; + OVPN_MP_NEW_PEER newPeer =3D { 0 }; if (remoteaddr) { @@ -454,7 +453,8 @@ newPeer.PeerId =3D peerid; DWORD bytesReturned; - if (!DeviceIoControl(dco->tt->hand, OVPN_IOCTL_MP_NEW_PEER, &newPeer, = sizeof(newPeer), NULL, 0, &bytesReturned, NULL)) + if (!DeviceIoControl(dco->tt->hand, OVPN_IOCTL_MP_NEW_PEER, &newPeer, = sizeof(newPeer), NULL, 0, + &bytesReturned, NULL)) { msg(M_ERR, "DeviceIoControl(OVPN_IOCTL_MP_NEW_PEER) failed"); } @@ -489,11 +489,11 @@ } int -dco_set_peer(dco_context_t *dco, unsigned int peerid, - int keepalive_interval, int keepalive_timeout, int mss) +dco_set_peer(dco_context_t *dco, unsigned int peerid, int keepalive_interv= al, int keepalive_timeout, + int mss) { - msg(D_DCO_DEBUG, "%s: peer-id %d, keepalive %d/%d, mss %d", __func__, - peerid, keepalive_interval, keepalive_timeout, mss); + msg(D_DCO_DEBUG, "%s: peer-id %d, keepalive %d/%d, mss %d", __func__, = peerid, + keepalive_interval, keepalive_timeout, mss); OVPN_MP_SET_PEER mp_peer =3D { peerid, keepalive_interval, keepalive_t= imeout, mss }; OVPN_SET_PEER peer =3D { keepalive_interval, keepalive_timeout, mss }; @@ -523,14 +523,12 @@ } int -dco_new_key(dco_context_t *dco, unsigned int peerid, int keyid, - dco_key_slot_t slot, - const uint8_t *encrypt_key, const uint8_t *encrypt_iv, - const uint8_t *decrypt_key, const uint8_t *decrypt_iv, - const char *ciphername) +dco_new_key(dco_context_t *dco, unsigned int peerid, int keyid, dco_key_sl= ot_t slot, + const uint8_t *encrypt_key, const uint8_t *encrypt_iv, const u= int8_t *decrypt_key, + const uint8_t *decrypt_iv, const char *ciphername) { - msg(D_DCO_DEBUG, "%s: slot %d, key-id %d, peer-id %d, cipher %s", - __func__, slot, keyid, peerid, ciphername); + msg(D_DCO_DEBUG, "%s: slot %d, key-id %d, peer-id %d, cipher %s", __fu= nc__, slot, keyid, peerid, + ciphername); const int nonce_len =3D 8; size_t key_len =3D cipher_kt_key_size(ciphername); @@ -555,8 +553,8 @@ DWORD bytes_returned =3D 0; - if (!DeviceIoControl(dco->tt->hand, OVPN_IOCTL_NEW_KEY, &crypto_data, - sizeof(crypto_data), NULL, 0, &bytes_returned, NU= LL)) + if (!DeviceIoControl(dco->tt->hand, OVPN_IOCTL_NEW_KEY, &crypto_data, = sizeof(crypto_data), NULL, + 0, &bytes_returned, NULL)) { msg(M_ERR, "DeviceIoControl(OVPN_IOCTL_NEW_KEY) failed"); return -1; @@ -566,8 +564,7 @@ int dco_del_key(dco_context_t *dco, unsigned int peerid, dco_key_slot_t slot) { - msg(D_DCO, "%s: peer-id %d, slot %d called but ignored", __func__, pee= rid, - slot); + msg(D_DCO, "%s: peer-id %d, slot %d called but ignored", __func__, pee= rid, slot); /* FIXME: Implement in driver first */ return 0; } @@ -577,7 +574,7 @@ { msg(D_DCO_DEBUG, "%s: peer-id %d", __func__, peer_id); - OVPN_MP_SWAP_KEYS swap =3D {peer_id}; + OVPN_MP_SWAP_KEYS swap =3D { peer_id }; DWORD ioctl =3D OVPN_IOCTL_SWAP_KEYS; VOID *buf =3D NULL; DWORD len =3D 0; @@ -602,8 +599,8 @@ dco_available(int msglevel) { /* try to open device by symbolic name */ - HANDLE h =3D CreateFile("\\\\.\\ovpn-dco", GENERIC_READ | GENERIC_WRIT= E, - 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_SYSTEM | = FILE_FLAG_OVERLAPPED, NULL); + HANDLE h =3D CreateFile("\\\\.\\ovpn-dco", GENERIC_READ | GENERIC_WRIT= E, 0, NULL, OPEN_EXISTING, + FILE_ATTRIBUTE_SYSTEM | FILE_FLAG_OVERLAPPED, NU= LL); if (h !=3D INVALID_HANDLE_VALUE) { @@ -628,7 +625,7 @@ const char * dco_version_string(struct gc_arena *gc) { - OVPN_VERSION version =3D {0}; + OVPN_VERSION version =3D { 0 }; if (dco_get_version(&version)) { struct buffer out =3D alloc_buf_gc(256, gc); @@ -659,7 +656,8 @@ BOOL res =3D GetOverlappedResult(dco->tt->hand, &dco->ov, &bytes_read,= FALSE); if (res) { - msg(D_DCO_DEBUG, "%s: completion%s success [%ld]", __func__, queue= d ? "" : " non-queued", bytes_read); + msg(D_DCO_DEBUG, "%s: completion%s success [%ld]", __func__, queue= d ? "" : " non-queued", + bytes_read); dco->dco_message_peer_id =3D dco->notif_buf.PeerId; dco->dco_message_type =3D dco->notif_buf.Cmd; @@ -734,8 +732,8 @@ ZeroMemory(&stats, sizeof(OVPN_STATS)); DWORD bytes_returned =3D 0; - if (!DeviceIoControl(tt->hand, OVPN_IOCTL_GET_STATS, NULL, 0, - &stats, sizeof(stats), &bytes_returned, NULL)) + if (!DeviceIoControl(tt->hand, OVPN_IOCTL_GET_STATS, NULL, 0, &stats, = sizeof(stats), + &bytes_returned, NULL)) { msg(M_WARN | M_ERRNO, "DeviceIoControl(OVPN_IOCTL_GET_STATS) faile= d"); return -1; @@ -765,7 +763,8 @@ /* the overlapped IOCTL will signal this event on I/O completion */ ASSERT(ResetEvent(dco->ov.hEvent)); - if (!DeviceIoControl(dco->tt->hand, OVPN_IOCTL_NOTIFY_EVENT, NULL,= 0, &dco->notif_buf, sizeof(dco->notif_buf), NULL, &dco->ov)) + if (!DeviceIoControl(dco->tt->hand, OVPN_IOCTL_NOTIFY_EVENT, NULL,= 0, &dco->notif_buf, + sizeof(dco->notif_buf), NULL, &dco->ov)) { DWORD err =3D GetLastError(); if (err =3D=3D ERROR_IO_PENDING) /* operation queued? */ @@ -826,17 +825,21 @@ } void -dco_win_add_iroute_ipv4(dco_context_t *dco, in_addr_t dst, unsigned int ne= tbits, unsigned int peer_id) +dco_win_add_iroute_ipv4(dco_context_t *dco, in_addr_t dst, unsigned int ne= tbits, + unsigned int peer_id) { struct gc_arena gc =3D gc_new(); - OVPN_MP_IROUTE route =3D {.Addr.Addr4.S_un.S_addr =3D dst, .Netbits = =3D netbits, .PeerId =3D peer_id, .IPv6 =3D 0}; + OVPN_MP_IROUTE route =3D { + .Addr.Addr4.S_un.S_addr =3D dst, .Netbits =3D netbits, .PeerId =3D= peer_id, .IPv6 =3D 0 + }; - msg(D_DCO_DEBUG, "%s: %s/%d -> peer %d", __func__, print_in_addr_t(dst= , IA_NET_ORDER, &gc), netbits, peer_id); + msg(D_DCO_DEBUG, "%s: %s/%d -> peer %d", __func__, print_in_addr_t(dst= , IA_NET_ORDER, &gc), + netbits, peer_id); DWORD bytes_returned =3D 0; - if (!DeviceIoControl(dco->tt->hand, OVPN_IOCTL_MP_ADD_IROUTE, &route, - sizeof(route), NULL, 0, &bytes_returned, NULL)) + if (!DeviceIoControl(dco->tt->hand, OVPN_IOCTL_MP_ADD_IROUTE, &route, = sizeof(route), NULL, 0, + &bytes_returned, NULL)) { msg(M_WARN | M_ERRNO, "DeviceIoControl(OVPN_IOCTL_MP_ADD_IROUTE) f= ailed"); } @@ -845,17 +848,19 @@ } void -dco_win_add_iroute_ipv6(dco_context_t *dco, struct in6_addr dst, unsigned = int netbits, unsigned int peer_id) +dco_win_add_iroute_ipv6(dco_context_t *dco, struct in6_addr dst, unsigned = int netbits, + unsigned int peer_id) { struct gc_arena gc =3D gc_new(); OVPN_MP_IROUTE route =3D { .Addr.Addr6 =3D dst, .Netbits =3D netbits, = .PeerId =3D peer_id, .IPv6 =3D 1 }; - msg(D_DCO_DEBUG, "%s: %s/%d -> peer %d", __func__, print_in6_addr(dst,= IA_NET_ORDER, &gc), netbits, peer_id); + msg(D_DCO_DEBUG, "%s: %s/%d -> peer %d", __func__, print_in6_addr(dst,= IA_NET_ORDER, &gc), + netbits, peer_id); DWORD bytes_returned =3D 0; - if (!DeviceIoControl(dco->tt->hand, OVPN_IOCTL_MP_ADD_IROUTE, &route, - sizeof(route), NULL, 0, &bytes_returned, NULL)) + if (!DeviceIoControl(dco->tt->hand, OVPN_IOCTL_MP_ADD_IROUTE, &route, = sizeof(route), NULL, 0, + &bytes_returned, NULL)) { msg(M_WARN | M_ERRNO, "DeviceIoControl(OVPN_IOCTL_MP_ADD_IROUTE) f= ailed"); } @@ -868,13 +873,15 @@ { struct gc_arena gc =3D gc_new(); - OVPN_MP_IROUTE route =3D { .Addr.Addr4.S_un.S_addr =3D dst, .Netbits = =3D netbits, .PeerId =3D -1, .IPv6 =3D 0 }; + OVPN_MP_IROUTE route =3D { + .Addr.Addr4.S_un.S_addr =3D dst, .Netbits =3D netbits, .PeerId =3D= -1, .IPv6 =3D 0 + }; msg(D_DCO_DEBUG, "%s: %s/%d", __func__, print_in_addr_t(dst, IA_NET_OR= DER, &gc), netbits); DWORD bytes_returned =3D 0; - if (!DeviceIoControl(dco->tt->hand, OVPN_IOCTL_MP_DEL_IROUTE, &route, - sizeof(route), NULL, 0, &bytes_returned, NULL)) + if (!DeviceIoControl(dco->tt->hand, OVPN_IOCTL_MP_DEL_IROUTE, &route, = sizeof(route), NULL, 0, + &bytes_returned, NULL)) { msg(M_WARN | M_ERRNO, "DeviceIoControl(OVPN_IOCTL_MP_DEL_IROUTE) f= ailed"); } @@ -892,8 +899,8 @@ msg(D_DCO_DEBUG, "%s: %s/%d", __func__, print_in6_addr(dst, IA_NET_ORD= ER, &gc), netbits); DWORD bytes_returned =3D 0; - if (!DeviceIoControl(dco->tt->hand, OVPN_IOCTL_MP_DEL_IROUTE, &route, - sizeof(route), NULL, 0, &bytes_returned, NULL)) + if (!DeviceIoControl(dco->tt->hand, OVPN_IOCTL_MP_DEL_IROUTE, &route, = sizeof(route), NULL, 0, + &bytes_returned, NULL)) { msg(M_WARN | M_ERRNO, "DeviceIoControl(OVPN_IOCTL_MP_DEL_IROUTE) f= ailed"); } diff --git a/src/openvpn/dco_win.h b/src/openvpn/dco_win.h index 7311de8..a7f4865 100644 --- a/src/openvpn/dco_win.h +++ b/src/openvpn/dco_win.h @@ -32,21 +32,23 @@ typedef OVPN_KEY_SLOT dco_key_slot_t; typedef OVPN_CIPHER_ALG dco_cipher_t; -typedef enum { +typedef enum +{ DCO_MODE_UNINIT, DCO_MODE_P2P, DCO_MODE_MP } dco_mode_type; -struct dco_context { +struct dco_context +{ struct tuntap *tt; dco_mode_type ifmode; OVPN_NOTIFY_EVENT notif_buf; /**< Buffer for incoming notifications. */ - OVERLAPPED ov; /**< Used by overlapped I/O for async IOCTL. */ - int iostate; /**< State of overlapped I/O; see definitions in win32.h.= */ - struct rw_handle rwhandle; /**< Used to hook async I/O to the OpenVPN = event loop. */ - int ov_ret; /**< Win32 error code for overlapped operation, 0 for succ= ess */ + OVERLAPPED ov; /**< Used by overlapped I/O for async IOC= TL. */ + int iostate; /**< State of overlapped I/O; see definit= ions in win32.h. */ + struct rw_handle rwhandle; /**< Used to hook async I/O to the OpenVP= N event loop. */ + int ov_ret; /**< Win32 error code for overlapped oper= ation, 0 for success */ int dco_message_peer_id; int dco_message_type; @@ -59,31 +61,26 @@ typedef struct dco_context dco_context_t; -void -dco_mp_start_vpn(HANDLE handle, struct link_socket *sock); +void dco_mp_start_vpn(HANDLE handle, struct link_socket *sock); -void -dco_p2p_new_peer(HANDLE handle, OVERLAPPED *ov, struct link_socket *sock, = struct signal_info *sig_info); +void dco_p2p_new_peer(HANDLE handle, OVERLAPPED *ov, struct link_socket *s= ock, + struct signal_info *sig_info); -void -dco_start_tun(struct tuntap *tt); +void dco_start_tun(struct tuntap *tt); -bool -dco_win_supports_multipeer(void); +bool dco_win_supports_multipeer(void); -void -dco_win_add_iroute_ipv4(dco_context_t *dco, in_addr_t dst, unsigned int ne= tbits, unsigned int peer_id); +void dco_win_add_iroute_ipv4(dco_context_t *dco, in_addr_t dst, unsigned i= nt netbits, + unsigned int peer_id); -void -dco_win_add_iroute_ipv6(dco_context_t *dco, struct in6_addr dst, unsigned = int netbits, unsigned int peer_id); +void dco_win_add_iroute_ipv6(dco_context_t *dco, struct in6_addr dst, unsi= gned int netbits, + unsigned int peer_id); -void -dco_win_del_iroute_ipv4(dco_context_t *dco, in_addr_t dst, unsigned int ne= tbits); +void dco_win_del_iroute_ipv4(dco_context_t *dco, in_addr_t dst, unsigned i= nt netbits); -void -dco_win_del_iroute_ipv6(dco_context_t *dco, struct in6_addr dst, unsigned = int netbits); +void dco_win_del_iroute_ipv6(dco_context_t *dco, struct in6_addr dst, unsi= gned int netbits); -#else /* if defined(ENABLE_DCO) && defined(_WIN32) */ +#else /* if defined(ENABLE_DCO) && defined(_WIN32) */ static inline void dco_start_tun(struct tuntap *tt) diff --git a/src/openvpn/dhcp.c b/src/openvpn/dhcp.c index df01412..0a7689f 100644 --- a/src/openvpn/dhcp.c +++ b/src/openvpn/dhcp.c @@ -35,37 +35,37 @@ static int get_dhcp_message_type(const struct dhcp *dhcp, const int optlen) { - const uint8_t *p =3D (uint8_t *) (dhcp + 1); + const uint8_t *p =3D (uint8_t *)(dhcp + 1); int i; for (i =3D 0; i < optlen; ++i) { const uint8_t type =3D p[i]; const int room =3D optlen - i; - if (type =3D=3D DHCP_END) /* didn't find what we were look= ing for */ + if (type =3D=3D DHCP_END) /* didn't find what we were looking for = */ { return -1; } - else if (type =3D=3D DHCP_PAD) /* no-operation */ + else if (type =3D=3D DHCP_PAD) /* no-operation */ { } else if (type =3D=3D DHCP_MSG_TYPE) /* what we are looking for */ { if (room >=3D 3) { - if (p[i+1] =3D=3D 1) /* option length should be 1 */ + if (p[i + 1] =3D=3D 1) /* option length should be 1 */ { - return p[i+2]; /* return message type */ + return p[i + 2]; /* return message type */ } } return -1; } - else /* some other option */ + else /* some other option */ { if (room >=3D 2) { - const int len =3D p[i+1]; /* get option length */ - i +=3D (len + 1); /* advance to next option */ + const int len =3D p[i + 1]; /* get option length */ + i +=3D (len + 1); /* advance to next option */ } } } @@ -75,11 +75,11 @@ static in_addr_t do_extract(struct dhcp *dhcp, int optlen) { - uint8_t *p =3D (uint8_t *) (dhcp + 1); + uint8_t *p =3D (uint8_t *)(dhcp + 1); int i; in_addr_t ret =3D 0; - for (i =3D 0; i < optlen; ) + for (i =3D 0; i < optlen;) { const uint8_t type =3D p[i]; const int room =3D optlen - i; @@ -95,25 +95,25 @@ { if (room >=3D 2) { - const int len =3D p[i+1]; /* get option length */ - if (len <=3D (room-2)) + const int len =3D p[i + 1]; /* get option length */ + if (len <=3D (room - 2)) { /* get router IP address */ if (!ret && len >=3D 4 && (len & 3) =3D=3D 0) { - memcpy(&ret, p+i+2, 4); + memcpy(&ret, p + i + 2, 4); ret =3D ntohl(ret); } { /* delete the router option */ uint8_t *dest =3D p + i; - const int owlen =3D len + 2; /* len of data= to overwrite */ + const int owlen =3D len + 2; /* len of data to ove= rwrite */ uint8_t *src =3D dest + owlen; uint8_t *end =3D p + optlen; const int movlen =3D end - src; if (movlen > 0) { - memmove(dest, src, movlen); /* overwrite rou= ter option */ + memmove(dest, src, movlen); /* overwrite= router option */ } memset(end - owlen, DHCP_PAD, owlen); /* pad tail = */ } @@ -128,12 +128,12 @@ break; } } - else /* some other option */ + else /* some other option */ { if (room >=3D 2) { - const int len =3D p[i+1]; /* get option length */ - i +=3D (len + 2); /* advance to next option */ + const int len =3D p[i + 1]; /* get option length */ + i +=3D (len + 2); /* advance to next option */ } else { @@ -147,13 +147,13 @@ in_addr_t dhcp_extract_router_msg(struct buffer *ipbuf) { - struct dhcp_full *df =3D (struct dhcp_full *) BPTR(ipbuf); - const int optlen =3D BLEN(ipbuf) - (sizeof(struct openvpn_iphdr) + siz= eof(struct openvpn_udphdr) + sizeof(struct dhcp)); + struct dhcp_full *df =3D (struct dhcp_full *)BPTR(ipbuf); + const int optlen =3D + BLEN(ipbuf) + - (sizeof(struct openvpn_iphdr) + sizeof(struct openvpn_udphdr) + = sizeof(struct dhcp)); - if (optlen >=3D 0 - && df->ip.protocol =3D=3D OPENVPN_IPPROTO_UDP - && df->udp.source =3D=3D htons(BOOTPS_PORT) - && df->udp.dest =3D=3D htons(BOOTPC_PORT) + if (optlen >=3D 0 && df->ip.protocol =3D=3D OPENVPN_IPPROTO_UDP + && df->udp.source =3D=3D htons(BOOTPS_PORT) && df->udp.dest =3D=3D= htons(BOOTPC_PORT) && df->dhcp.op =3D=3D BOOTREPLY) { const int message_type =3D get_dhcp_message_type(&df->dhcp, optlen= ); @@ -164,10 +164,10 @@ /* recompute the UDP checksum */ df->udp.check =3D 0; - df->udp.check =3D htons(ip_checksum(AF_INET, (uint8_t *)&df->u= dp, - sizeof(struct openvpn_udphdr= ) + sizeof(struct dhcp) + optlen, - (uint8_t *)&df->ip.saddr, (u= int8_t *)&df->ip.daddr, - OPENVPN_IPPROTO_UDP)); + df->udp.check =3D htons(ip_checksum( + AF_INET, (uint8_t *)&df->udp, + sizeof(struct openvpn_udphdr) + sizeof(struct dhcp) + optl= en, + (uint8_t *)&df->ip.saddr, (uint8_t *)&df->ip.daddr, OPENVP= N_IPPROTO_UDP)); /* only return the extracted Router address if DHCPACK */ if (message_type =3D=3D DHCPACK) diff --git a/src/openvpn/dhcp.h b/src/openvpn/dhcp.h index 34f4513..af5c2c4 100644 --- a/src/openvpn/dhcp.h +++ b/src/openvpn/dhcp.h @@ -30,10 +30,10 @@ #pragma pack(1) /* DHCP Option types */ -#define DHCP_PAD 0 -#define DHCP_ROUTER 3 -#define DHCP_MSG_TYPE 53 /* message type (u8) */ -#define DHCP_END 255 +#define DHCP_PAD 0 +#define DHCP_ROUTER 3 +#define DHCP_MSG_TYPE 53 /* message type (u8) */ +#define DHCP_END 255 /* DHCP Messages types */ #define DHCPDISCOVER 1 @@ -49,28 +49,30 @@ #define BOOTPS_PORT 67 #define BOOTPC_PORT 68 -struct dhcp { +struct dhcp +{ #define BOOTREQUEST 1 #define BOOTREPLY 2 - uint8_t op; /* message op */ + uint8_t op; /* message op */ - uint8_t htype; /* hardware address type (e.g. '1' =3D 10Mb Etherne= t) */ - uint8_t hlen; /* hardware address length (e.g. '6' for 10Mb Ether= net) */ - uint8_t hops; /* client sets to 0, may be used by relay agents */ - uint32_t xid; /* transaction ID, chosen by client */ - uint16_t secs; /* seconds since request process began, set by clie= nt */ + uint8_t htype; /* hardware address type (e.g. '1' =3D 10Mb Ethern= et) */ + uint8_t hlen; /* hardware address length (e.g. '6' for 10Mb Ethe= rnet) */ + uint8_t hops; /* client sets to 0, may be used by relay agents */ + uint32_t xid; /* transaction ID, chosen by client */ + uint16_t secs; /* seconds since request process began, set by cli= ent */ uint16_t flags; - uint32_t ciaddr; /* client IP address, client sets if known */ - uint32_t yiaddr; /* 'your' IP address -- server's response to client= */ - uint32_t siaddr; /* server IP address */ - uint32_t giaddr; /* relay agent IP address */ + uint32_t ciaddr; /* client IP address, client sets if known */ + uint32_t yiaddr; /* 'your' IP address -- server's response to clien= t */ + uint32_t siaddr; /* server IP address */ + uint32_t giaddr; /* relay agent IP address */ uint8_t chaddr[16]; /* client hardware address */ - uint8_t sname[64]; /* optional server host name */ - uint8_t file[128]; /* boot file name */ - uint32_t magic; /* must be 0x63825363 (network order) */ + uint8_t sname[64]; /* optional server host name */ + uint8_t file[128]; /* boot file name */ + uint32_t magic; /* must be 0x63825363 (network order) */ }; -struct dhcp_full { +struct dhcp_full +{ struct openvpn_iphdr ip; struct openvpn_udphdr udp; struct dhcp dhcp; diff --git a/src/openvpn/dns.c b/src/openvpn/dns.c index 22f4cec..8e28c2b 100644 --- a/src/openvpn/dns.c +++ b/src/openvpn/dns.c @@ -65,7 +65,7 @@ return false; } - char addrcopy[INET6_ADDRSTRLEN] =3D {0}; + char addrcopy[INET6_ADDRSTRLEN] =3D { 0 }; size_t copylen =3D 0; in_port_t port =3D 0; sa_family_t af; @@ -202,13 +202,13 @@ bool dns_options_verify(int msglevel, const struct dns_options *o) { - const struct dns_server *server =3D - o->servers ? o->servers : o->servers_prepull; + const struct dns_server *server =3D o->servers ? o->servers : o->serve= rs_prepull; while (server) { if (server->addr_count =3D=3D 0) { - msg(msglevel, "ERROR: dns server %ld does not have an address = assigned", server->priority); + msg(msglevel, "ERROR: dns server %ld does not have an address = assigned", + server->priority); return false; } server =3D server->next; @@ -352,8 +352,8 @@ #ifdef _WIN32 static void -make_domain_list(const char *what, const struct dns_domain *src, - bool nrpt_domains, char *dst, size_t dst_size) +make_domain_list(const char *what, const struct dns_domain *src, bool nrpt= _domains, char *dst, + size_t dst_size) { /* NRPT domains need two \0 at the end for REG_MULTI_SZ * and a leading '.' added in front of the domain name */ @@ -429,11 +429,8 @@ ack_message_t ack; nrpt_dns_cfg_message_t nrpt =3D { - .header =3D { - (add ? msg_add_nrpt_cfg : msg_del_nrpt_cfg), - sizeof(nrpt_dns_cfg_message_t), - 0 - }, + .header =3D { (add ? msg_add_nrpt_cfg : msg_del_nrpt_cfg), sizeof(= nrpt_dns_cfg_message_t), + 0 }, .iface =3D { .index =3D tt->adapter_index, .name =3D "" }, .flags =3D server->dnssec =3D=3D DNS_SECURITY_NO ? 0 : nrpt_dnssec, }; @@ -447,33 +444,31 @@ break; } - if (inet_ntop(server->addr[i].family, &server->addr[i].in, - nrpt.addresses[i], NRPT_ADDR_SIZE) =3D=3D NULL) + if (inet_ntop(server->addr[i].family, &server->addr[i].in, nrpt.ad= dresses[i], + NRPT_ADDR_SIZE) + =3D=3D NULL) { msg(M_WARN, "WARNING: could not convert dns server address"); } } - make_domain_list("dns server resolve domains", server->domains, true, - nrpt.resolve_domains, sizeof(nrpt.resolve_domains)); + make_domain_list("dns server resolve domains", server->domains, true, = nrpt.resolve_domains, + sizeof(nrpt.resolve_domains)); - make_domain_list("dns search domains", search_domains, false, - nrpt.search_domains, sizeof(nrpt.search_domains)); + make_domain_list("dns search domains", search_domains, false, nrpt.sea= rch_domains, + sizeof(nrpt.search_domains)); msg(D_LOW, "%s NRPT DNS%s%s on '%s' (if_index =3D %d) using service", (add ? "Setting" : "Deleting"), nrpt.resolve_domains[0] !=3D 0 ? "= , resolve domains" : "", - nrpt.search_domains[0] !=3D 0 ? ", search domains" : "", - nrpt.iface.name, nrpt.iface.index); + nrpt.search_domains[0] !=3D 0 ? ", search domains" : "", nrpt.ifac= e.name, nrpt.iface.index); send_msg_iservice(o->msg_channel, &nrpt, sizeof(nrpt), &ack, "DNS"); } -#else /* ifdef _WIN32 */ +#else /* ifdef _WIN32 */ static void -setenv_dns_option(struct env_set *es, - const char *format, int i, int j, - const char *value) +setenv_dns_option(struct env_set *es, const char *format, int i, int j, co= nst char *value) { char name[64]; bool name_ok =3D false; @@ -539,14 +534,12 @@ if (s->dnssec) { - setenv_dns_option(es, "dns_server_%d_dnssec", i, -1, - dnssec_value(s->dnssec)); + setenv_dns_option(es, "dns_server_%d_dnssec", i, -1, dnssec_va= lue(s->dnssec)); } if (s->transport) { - setenv_dns_option(es, "dns_server_%d_transport", i, -1, - transport_value(s->transport)); + setenv_dns_option(es, "dns_server_%d_transport", i, -1, transp= ort_value(s->transport)); } if (s->sni) { @@ -566,7 +559,8 @@ } static int -do_run_up_down_command(bool up, const char *vars_file, const struct dns_op= tions *o, const struct tuntap *tt) +do_run_up_down_command(bool up, const char *vars_file, const struct dns_op= tions *o, + const struct tuntap *tt) { struct gc_arena gc =3D gc_new(); struct argv argv =3D argv_new(); @@ -598,12 +592,12 @@ } static bool -run_updown_runner(bool up, struct options *o, const struct tuntap *tt, str= uct dns_updown_runner_info *updown_runner) +run_updown_runner(bool up, struct options *o, const struct tuntap *tt, + struct dns_updown_runner_info *updown_runner) { int dns_pipe_fd[2]; int ack_pipe_fd[2]; - if (pipe(dns_pipe_fd) !=3D 0 - || pipe(ack_pipe_fd) !=3D 0) + if (pipe(dns_pipe_fd) !=3D 0 || pipe(ack_pipe_fd) !=3D 0) { msg(M_ERR | M_ERRNO, "run_dns_up_down: unable to create pipes"); return false; @@ -631,8 +625,7 @@ /* Script runner process, close unused FDs */ for (int fd =3D 3; fd < 100; ++fd) { - if (fd !=3D dns_pipe_fd[0] - && fd !=3D ack_pipe_fd[1]) + if (fd !=3D dns_pipe_fd[0] && fd !=3D ack_pipe_fd[1]) { close(fd); } @@ -693,7 +686,8 @@ } static void -run_up_down_command(bool up, struct options *o, const struct tuntap *tt, s= truct dns_updown_runner_info *updown_runner) +run_up_down_command(bool up, struct options *o, const struct tuntap *tt, + struct dns_updown_runner_info *updown_runner) { struct dns_options *dns =3D &o->dns_options; if (!dns->updown || (o->up_script && !dns_updown_user_set(dns) && !dns= _updown_forced(dns))) @@ -851,7 +845,8 @@ } void -run_dns_up_down(bool up, struct options *o, const struct tuntap *tt, struc= t dns_updown_runner_info *duri) +run_dns_up_down(bool up, struct options *o, const struct tuntap *tt, + struct dns_updown_runner_info *duri) { if (!o->dns_options.servers) { @@ -881,14 +876,17 @@ } if (bad_count =3D=3D s->addr_count) { - msg(M_WARN, "DNS server %ld only has address(es) from a family= " + msg(M_WARN, + "DNS server %ld only has address(es) from a family " "the tunnel is not configured for - it will not be reachab= le", s->priority); } else if (bad_count) { - msg(M_WARN, "DNS server %ld has address(es) from a family " - "the tunnel is not configured for", s->priority); + msg(M_WARN, + "DNS server %ld has address(es) from a family " + "the tunnel is not configured for", + s->priority); } s =3D s->next; } diff --git a/src/openvpn/dns.h b/src/openvpn/dns.h index 94c76e5..6d97b40 100644 --- a/src/openvpn/dns.h +++ b/src/openvpn/dns.h @@ -27,33 +27,39 @@ #include "env_set.h" #include "tun.h" -enum dns_security { +enum dns_security +{ DNS_SECURITY_UNSET, DNS_SECURITY_NO, DNS_SECURITY_YES, DNS_SECURITY_OPTIONAL }; -enum dns_server_transport { +enum dns_server_transport +{ DNS_TRANSPORT_UNSET, DNS_TRANSPORT_PLAIN, DNS_TRANSPORT_HTTPS, DNS_TRANSPORT_TLS }; -enum dns_updown_flags { +enum dns_updown_flags +{ DNS_UPDOWN_NO_FLAGS, DNS_UPDOWN_USER_SET, DNS_UPDOWN_FORCED }; -struct dns_domain { +struct dns_domain +{ struct dns_domain *next; const char *name; }; -struct dns_server_addr { - union { +struct dns_server_addr +{ + union + { struct in_addr a4; struct in6_addr a6; } in; @@ -61,7 +67,8 @@ in_port_t port; }; -struct dns_server { +struct dns_server +{ struct dns_server *next; long priority; size_t addr_count; @@ -72,7 +79,8 @@ const char *sni; }; -struct dns_updown_runner_info { +struct dns_updown_runner_info +{ bool required; int fds[2]; #if !defined(_WIN32) @@ -88,7 +96,8 @@ #define N_SEARCH_LIST_LEN 10 #endif -struct dhcp_options { +struct dhcp_options +{ in_addr_t dns[N_DHCP_ADDR]; int dns_len; @@ -100,7 +109,8 @@ int domain_search_list_len; }; -struct dns_options { +struct dns_options +{ struct dhcp_options from_dhcp; struct dns_domain *search_domains; struct dns_server *servers_prepull; @@ -165,8 +175,7 @@ * @param gc Pointer to the gc_arena to use for the clone * @return The dns_options clone */ -struct dns_options clone_dns_options(const struct dns_options *o, - struct gc_arena *gc); +struct dns_options clone_dns_options(const struct dns_options *o, struct g= c_arena *gc); /** * Saves and resets the server options, so that pulled ones don't mix in. diff --git a/src/openvpn/env_set.c b/src/openvpn/env_set.c index 7809237..6c7df8e 100644 --- a/src/openvpn/env_set.c +++ b/src/openvpn/env_set.c @@ -246,7 +246,7 @@ if (es) { - const struct env_item *item =3D es->list; + const struct env_item *item =3D es->list; while (item) { fputs(item->string, fp); @@ -356,15 +356,10 @@ } void -setenv_str_ex(struct env_set *es, - const char *name, - const char *value, - const unsigned int name_include, - const unsigned int name_exclude, - const char name_replace, - const unsigned int value_include, - const unsigned int value_exclude, - const char value_replace) +setenv_str_ex(struct env_set *es, const char *name, const char *value, + const unsigned int name_include, const unsigned int name_exc= lude, + const char name_replace, const unsigned int value_include, + const unsigned int value_exclude, const char value_replace) { struct gc_arena gc =3D gc_new(); const char *name_tmp; @@ -442,9 +437,7 @@ /* Make arrays of strings */ const char ** -make_env_array(const struct env_set *es, - const bool check_allowed, - struct gc_arena *gc) +make_env_array(const struct env_set *es, const bool check_allowed, struct = gc_arena *gc) { char **ret =3D NULL; struct env_item *e =3D NULL; @@ -460,7 +453,7 @@ } /* alloc return array */ - ALLOC_ARRAY_CLEAR_GC(ret, char *, n+1, gc); + ALLOC_ARRAY_CLEAR_GC(ret, char *, n + 1, gc); /* fill return array */ if (es) diff --git a/src/openvpn/env_set.h b/src/openvpn/env_set.h index 63237a7..3973a4e 100644 --- a/src/openvpn/env_set.h +++ b/src/openvpn/env_set.h @@ -33,26 +33,23 @@ * Handle environmental variable lists */ -struct env_item { +struct env_item +{ char *string; struct env_item *next; }; -struct env_set { +struct env_set +{ struct gc_arena *gc; struct env_item *list; }; /* set/delete environmental variable */ -void setenv_str_ex(struct env_set *es, - const char *name, - const char *value, - const unsigned int name_include, - const unsigned int name_exclude, - const char name_replace, - const unsigned int value_include, - const unsigned int value_exclude, - const char value_replace); +void setenv_str_ex(struct env_set *es, const char *name, const char *value, + const unsigned int name_include, const unsigned int nam= e_exclude, + const char name_replace, const unsigned int value_inclu= de, + const unsigned int value_exclude, const char value_repl= ace); void setenv_counter(struct env_set *es, const char *name, counter_type val= ue); @@ -123,8 +120,7 @@ /* returns true if environmental variable may be passed to an external pro= gram */ bool env_allowed(const char *str); -const char **make_env_array(const struct env_set *es, - const bool check_allowed, +const char **make_env_array(const struct env_set *es, const bool check_all= owed, struct gc_arena *gc); #endif /* ifndef ENV_SET_H */ diff --git a/src/openvpn/errlevel.h b/src/openvpn/errlevel.h index e5e5b48..2d33d55 100644 --- a/src/openvpn/errlevel.h +++ b/src/openvpn/errlevel.h @@ -49,134 +49,134 @@ * of output. */ -#define M_VERB0 LOGLEV(0, 0, 0) /* Messages displayed= even at --verb 0 (fatal errors only) */ +#define M_VERB0 LOGLEV(0, 0, 0) /* Messages displayed even at --verb 0 (fa= tal errors only) */ -#define M_INFO LOGLEV(1, 0, 0) /* default informatio= nal messages */ +#define M_INFO LOGLEV(1, 0, 0) /* default informational messages */ -#define D_LINK_ERRORS LOGLEV(1, 1, M_NONFATAL) /* show link error= s from main event loop */ -#define D_CRYPT_ERRORS LOGLEV(1, 2, M_NONFATAL) /* show errors fro= m encrypt/decrypt */ -#define D_TLS_ERRORS LOGLEV(1, 3, M_NONFATAL) /* show TLS contro= l channel errors */ -#define D_RESOLVE_ERRORS LOGLEV(1, 4, M_NONFATAL) /* show hostname r= esolve errors */ -#define D_COMP_ERRORS LOGLEV(1, 5, M_NONFATAL) /* show compressio= n errors */ -#define D_REPLAY_ERRORS LOGLEV(1, 6, M_NONFATAL) /* show packet rep= lay errors */ -#define D_STREAM_ERRORS LOGLEV(1, 7, M_NONFATAL) /* TCP stream err= or requiring restart */ -#define D_IMPORT_ERRORS LOGLEV(1, 8, M_NONFATAL) /* show server im= port option errors */ -#define D_MULTI_ERRORS LOGLEV(1, 9, M_NONFATAL) /* show multi-cli= ent server errors */ -#define D_EVENT_ERRORS LOGLEV(1, 10, M_NONFATAL) /* show event.[ch= ] errors */ -#define D_PUSH_ERRORS LOGLEV(1, 11, M_NONFATAL) /* show push/pull= errors */ -#define D_PID_PERSIST LOGLEV(1, 12, M_NONFATAL) /* show packet_id= persist errors */ -#define D_FRAG_ERRORS LOGLEV(1, 13, M_NONFATAL) /* show fragmenta= tion errors */ -#define D_ALIGN_ERRORS LOGLEV(1, 14, M_NONFATAL) /* show bad struc= t alignments */ +#define D_LINK_ERRORS LOGLEV(1, 1, M_NONFATAL) /* show link errors fro= m main event loop */ +#define D_CRYPT_ERRORS LOGLEV(1, 2, M_NONFATAL) /* show errors from enc= rypt/decrypt */ +#define D_TLS_ERRORS LOGLEV(1, 3, M_NONFATAL) /* show TLS control cha= nnel errors */ +#define D_RESOLVE_ERRORS LOGLEV(1, 4, M_NONFATAL) /* show hostname resolv= e errors */ +#define D_COMP_ERRORS LOGLEV(1, 5, M_NONFATAL) /* show compression err= ors */ +#define D_REPLAY_ERRORS LOGLEV(1, 6, M_NONFATAL) /* show packet replay e= rrors */ +#define D_STREAM_ERRORS LOGLEV(1, 7, M_NONFATAL) /* TCP stream error req= uiring restart */ +#define D_IMPORT_ERRORS LOGLEV(1, 8, M_NONFATAL) /* show server import o= ption errors */ +#define D_MULTI_ERRORS LOGLEV(1, 9, M_NONFATAL) /* show multi-client se= rver errors */ +#define D_EVENT_ERRORS LOGLEV(1, 10, M_NONFATAL) /* show event.[ch] erro= rs */ +#define D_PUSH_ERRORS LOGLEV(1, 11, M_NONFATAL) /* show push/pull error= s */ +#define D_PID_PERSIST LOGLEV(1, 12, M_NONFATAL) /* show packet_id persi= st errors */ +#define D_FRAG_ERRORS LOGLEV(1, 13, M_NONFATAL) /* show fragmentation e= rrors */ +#define D_ALIGN_ERRORS LOGLEV(1, 14, M_NONFATAL) /* show bad struct alig= nments */ -#define D_HANDSHAKE LOGLEV(2, 20, 0) /* show data & contro= l channel handshakes */ -#define D_CLOSE LOGLEV(2, 22, 0) /* show socket and TU= N/TAP close */ -#define D_PROXY LOGLEV(2, 24, 0) /* show http proxy co= ntrol packets */ -#define D_ARGV LOGLEV(2, 25, 0) /* show struct argv e= rrors */ +#define D_HANDSHAKE LOGLEV(2, 20, 0) /* show data & control = channel handshakes */ +#define D_CLOSE LOGLEV(2, 22, 0) /* show socket and TUN/= TAP close */ +#define D_PROXY LOGLEV(2, 24, 0) /* show http proxy cont= rol packets */ +#define D_ARGV LOGLEV(2, 25, 0) /* show struct argv err= ors */ -#define D_TLS_DEBUG_LOW LOGLEV(3, 20, 0) /* low frequency info= from tls_session routines */ -#define D_GREMLIN LOGLEV(3, 30, 0) /* show simulated out= age info from gremlin module */ -#define D_GENKEY LOGLEV(3, 31, 0) /* print message afte= r key generation */ -#define D_ROUTE LOGLEV(3, 0, 0) /* show routes added = and deleted (don't mute) */ -#define D_TUNTAP_INFO LOGLEV(3, 32, 0) /* show debugging inf= o from TUN/TAP driver */ -#define D_RESTART LOGLEV(3, 33, 0) /* show certain resta= rt messages */ -#define D_PUSH LOGLEV(3, 34, 0) /* show push/pull inf= o */ -#define D_IFCONFIG_POOL LOGLEV(3, 35, 0) /* show ifconfig pool= info */ -#define D_AUTH LOGLEV(3, 37, 0) /* show user/pass aut= h info */ -#define D_MULTI_LOW LOGLEV(3, 38, 0) /* show point-to-mult= ipoint low-freq debug info */ -#define D_PLUGIN LOGLEV(3, 39, 0) /* show plugin calls = */ -#define D_MANAGEMENT LOGLEV(3, 40, 0) /* show --management = info */ -#define D_SCHED_EXIT LOGLEV(3, 41, 0) /* show arming of sch= eduled exit */ -#define D_ROUTE_QUOTA LOGLEV(3, 42, 0) /* show route quota e= xceeded messages */ -#define D_OSBUF LOGLEV(3, 43, 0) /* show socket/tun/ta= p buffer sizes */ -#define D_PS_PROXY LOGLEV(3, 44, 0) /* messages related t= o --port-share option */ -#define D_IFCONFIG LOGLEV(3, 0, 0) /* show ifconfig info= (don't mute) */ -#define D_DCO LOGLEV(3, 0, 0) /* show DCO related m= essages */ +#define D_TLS_DEBUG_LOW LOGLEV(3, 20, 0) /* low frequency info from = tls_session routines */ +#define D_GREMLIN LOGLEV(3, 30, 0) /* show simulated outage in= fo from gremlin module */ +#define D_GENKEY LOGLEV(3, 31, 0) /* print message after key = generation */ +#define D_ROUTE LOGLEV(3, 0, 0) /* show routes added and de= leted (don't mute) */ +#define D_TUNTAP_INFO LOGLEV(3, 32, 0) /* show debugging info from= TUN/TAP driver */ +#define D_RESTART LOGLEV(3, 33, 0) /* show certain restart mes= sages */ +#define D_PUSH LOGLEV(3, 34, 0) /* show push/pull info */ +#define D_IFCONFIG_POOL LOGLEV(3, 35, 0) /* show ifconfig pool info = */ +#define D_AUTH LOGLEV(3, 37, 0) /* show user/pass auth info= */ +#define D_MULTI_LOW LOGLEV(3, 38, 0) /* show point-to-multipoint= low-freq debug info */ +#define D_PLUGIN LOGLEV(3, 39, 0) /* show plugin calls */ +#define D_MANAGEMENT LOGLEV(3, 40, 0) /* show --management info */ +#define D_SCHED_EXIT LOGLEV(3, 41, 0) /* show arming of scheduled= exit */ +#define D_ROUTE_QUOTA LOGLEV(3, 42, 0) /* show route quota exceede= d messages */ +#define D_OSBUF LOGLEV(3, 43, 0) /* show socket/tun/tap buff= er sizes */ +#define D_PS_PROXY LOGLEV(3, 44, 0) /* messages related to --po= rt-share option */ +#define D_IFCONFIG LOGLEV(3, 0, 0) /* show ifconfig info (don'= t mute) */ +#define D_DCO LOGLEV(3, 0, 0) /* show DCO related message= s */ -#define D_SHOW_PARMS LOGLEV(4, 50, 0) /* show all parameter= s on program initiation */ -#define D_LOW LOGLEV(4, 52, 0) /* miscellaneous low-= frequency debug info */ -#define D_DHCP_OPT LOGLEV(4, 53, 0) /* show DHCP options = binary string */ -#define D_MBUF LOGLEV(4, 54, 0) /* mbuf.[ch] routines= */ -#define D_PACKET_TRUNC_ERR LOGLEV(4, 55, 0) /* PACKET_TRUNCATION_= CHECK */ -#define D_MULTI_DROPPED LOGLEV(4, 57, 0) /* show point-to-mult= ipoint packet drops */ -#define D_MULTI_MEDIUM LOGLEV(4, 58, 0) /* show medium freque= ncy multi messages */ -#define D_X509_ATTR LOGLEV(4, 59, 0) /* show x509-track at= tributes on connection */ -#define D_INIT_MEDIUM LOGLEV(4, 60, 0) /* show medium freque= ncy init messages */ -#define D_MTU_INFO LOGLEV(4, 61, 0) /* show terse MTU inf= o */ -#define D_PID_DEBUG_LOW LOGLEV(4, 63, 0) /* show low-freq pack= et-id debugging info */ -#define D_PID_DEBUG_MEDIUM LOGLEV(4, 64, 0) /* show medium-freq p= acket-id debugging info */ -#define D_CIPHER_INIT LOGLEV(4, 65, 0) /* show messages abou= t cipher init */ +#define D_SHOW_PARMS LOGLEV(4, 50, 0) /* show all parameters on p= rogram initiation */ +#define D_LOW LOGLEV(4, 52, 0) /* miscellaneous low-freque= ncy debug info */ +#define D_DHCP_OPT LOGLEV(4, 53, 0) /* show DHCP options binary= string */ +#define D_MBUF LOGLEV(4, 54, 0) /* mbuf.[ch] routines */ +#define D_PACKET_TRUNC_ERR LOGLEV(4, 55, 0) /* PACKET_TRUNCATION_CHECK = */ +#define D_MULTI_DROPPED LOGLEV(4, 57, 0) /* show point-to-multipoint= packet drops */ +#define D_MULTI_MEDIUM LOGLEV(4, 58, 0) /* show medium frequency mu= lti messages */ +#define D_X509_ATTR LOGLEV(4, 59, 0) /* show x509-track attribut= es on connection */ +#define D_INIT_MEDIUM LOGLEV(4, 60, 0) /* show medium frequency in= it messages */ +#define D_MTU_INFO LOGLEV(4, 61, 0) /* show terse MTU info */ +#define D_PID_DEBUG_LOW LOGLEV(4, 63, 0) /* show low-freq packet-id = debugging info */ +#define D_PID_DEBUG_MEDIUM LOGLEV(4, 64, 0) /* show medium-freq packet-= id debugging info */ +#define D_CIPHER_INIT LOGLEV(4, 65, 0) /* show messages about ciph= er init */ -#define D_LOG_RW LOGLEV(5, 0, 0) /* Print 'R' or 'W' t= o stdout for read/write */ +#define D_LOG_RW LOGLEV(5, 0, 0) /* Print 'R' or 'W' to stdo= ut for read/write */ -#define D_RTNL LOGLEV(6, 68, M_DEBUG) /* show RTNL low leve= l operations */ -#define D_LINK_RW LOGLEV(6, 69, M_DEBUG) /* show TCP/UDP reads= /writes (terse) */ -#define D_TUN_RW LOGLEV(6, 69, M_DEBUG) /* show TUN/TAP reads= /writes */ -#define D_TAP_WIN_DEBUG LOGLEV(6, 69, M_DEBUG) /* show TAP-Windows d= river debug info */ -#define D_CLIENT_NAT LOGLEV(6, 69, M_DEBUG) /* show client NAT de= bug info */ -#define D_XKEY LOGLEV(6, 69, M_DEBUG) /* show xkey-provider= debug info */ -#define D_DCO_DEBUG LOGLEV(6, 69, M_DEBUG) /* show DCO related l= owlevel debug messages */ -#define D_SIGNAL_DEBUG LOGLEV(6, 69, M_DEBUG) /* show signal relate= d debug messages */ +#define D_RTNL LOGLEV(6, 68, M_DEBUG) /* show RTNL low level oper= ations */ +#define D_LINK_RW LOGLEV(6, 69, M_DEBUG) /* show TCP/UDP reads/write= s (terse) */ +#define D_TUN_RW LOGLEV(6, 69, M_DEBUG) /* show TUN/TAP reads/write= s */ +#define D_TAP_WIN_DEBUG LOGLEV(6, 69, M_DEBUG) /* show TAP-Windows driver = debug info */ +#define D_CLIENT_NAT LOGLEV(6, 69, M_DEBUG) /* show client NAT debug in= fo */ +#define D_XKEY LOGLEV(6, 69, M_DEBUG) /* show xkey-provider debug= info */ +#define D_DCO_DEBUG LOGLEV(6, 69, M_DEBUG) /* show DCO related lowleve= l debug messages */ +#define D_SIGNAL_DEBUG LOGLEV(6, 69, M_DEBUG) /* show signal related debu= g messages */ -#define D_SHOW_KEYS LOGLEV(7, 70, M_DEBUG) /* show data channel = encryption keys */ -#define D_SHOW_KEY_SOURCE LOGLEV(7, 70, M_DEBUG) /* show data channel = key source entropy */ -#define D_REL_LOW LOGLEV(7, 70, M_DEBUG) /* show low frequency= info from reliable layer */ -#define D_FRAG_DEBUG LOGLEV(7, 70, M_DEBUG) /* show fragment debu= gging info */ -#define D_WIN32_IO_LOW LOGLEV(7, 70, M_DEBUG) /* low freq win32 I/O= debugging info */ -#define D_MTU_DEBUG LOGLEV(7, 70, M_DEBUG) /* show MTU debugging= info */ -#define D_MULTI_DEBUG LOGLEV(7, 70, M_DEBUG) /* show medium-freq m= ulti debugging info */ -#define D_MSS LOGLEV(7, 70, M_DEBUG) /* show MSS adjustmen= ts */ -#define D_COMP_LOW LOGLEV(7, 70, M_DEBUG) /* show adaptive comp= ression state changes */ -#define D_CONNECTION_LIST LOGLEV(7, 70, M_DEBUG) /* show = list info */ -#define D_SCRIPT LOGLEV(7, 70, M_DEBUG) /* show parms & env v= ars passed to scripts */ -#define D_SHOW_NET LOGLEV(7, 70, M_DEBUG) /* show routing table= and adapter list */ -#define D_ROUTE_DEBUG LOGLEV(7, 70, M_DEBUG) /* show verbose route= .[ch] output */ -#define D_TLS_STATE_ERRORS LOGLEV(7, 70, M_DEBUG) /* no TLS state for c= lient */ -#define D_SEMAPHORE_LOW LOGLEV(7, 70, M_DEBUG) /* show Win32 semapho= re waits (low freq) */ -#define D_SEMAPHORE LOGLEV(7, 70, M_DEBUG) /* show Win32 semapho= re waits */ -#define D_TEST_FILE LOGLEV(7, 70, M_DEBUG) /* show test_file() c= alls */ -#define D_MANAGEMENT_DEBUG LOGLEV(3, 70, M_DEBUG) /* show --management = debug info */ -#define D_PLUGIN_DEBUG LOGLEV(7, 70, M_DEBUG) /* show verbose plugi= n calls */ -#define D_SOCKET_DEBUG LOGLEV(7, 70, M_DEBUG) /* show socket.[ch] d= ebugging info */ -#define D_SHOW_PKCS11 LOGLEV(7, 70, M_DEBUG) /* show PKCS#11 actio= ns */ -#define D_ALIGN_DEBUG LOGLEV(7, 70, M_DEBUG) /* show verbose struc= t alignment info */ -#define D_PACKET_TRUNC_DEBUG LOGLEV(7, 70, M_DEBUG) /* PACKET_TRUNCATION_= CHECK verbose */ -#define D_PING LOGLEV(7, 70, M_DEBUG) /* PING send/receive = messages */ -#define D_PS_PROXY_DEBUG LOGLEV(7, 70, M_DEBUG) /* port share proxy d= ebug */ -#define D_TLS_KEYSELECT LOGLEV(7, 70, M_DEBUG) /* show key selection= for data channel */ -#define D_ARGV_PARSE_CMD LOGLEV(7, 70, M_DEBUG) /* show parse_line() = errors in argv_parse_cmd */ -#define D_CRYPTO_DEBUG LOGLEV(7, 70, M_DEBUG) /* show detailed info= from crypto.c routines */ -#define D_PID_DEBUG LOGLEV(7, 70, M_DEBUG) /* show packet-id deb= ugging info */ -#define D_PUSH_DEBUG LOGLEV(7, 73, M_DEBUG) /* show push/pull deb= ugging info */ -#define D_SHOW_OCC LOGLEV(7, 74, M_DEBUG) /* show options compa= tibility string */ +#define D_SHOW_KEYS LOGLEV(7, 70, M_DEBUG) /* show data channel e= ncryption keys */ +#define D_SHOW_KEY_SOURCE LOGLEV(7, 70, M_DEBUG) /* show data channel k= ey source entropy */ +#define D_REL_LOW LOGLEV(7, 70, M_DEBUG) /* show low frequency = info from reliable layer */ +#define D_FRAG_DEBUG LOGLEV(7, 70, M_DEBUG) /* show fragment debug= ging info */ +#define D_WIN32_IO_LOW LOGLEV(7, 70, M_DEBUG) /* low freq win32 I/O = debugging info */ +#define D_MTU_DEBUG LOGLEV(7, 70, M_DEBUG) /* show MTU debugging = info */ +#define D_MULTI_DEBUG LOGLEV(7, 70, M_DEBUG) /* show medium-freq mu= lti debugging info */ +#define D_MSS LOGLEV(7, 70, M_DEBUG) /* show MSS adjustment= s */ +#define D_COMP_LOW LOGLEV(7, 70, M_DEBUG) /* show adaptive compr= ession state changes */ +#define D_CONNECTION_LIST LOGLEV(7, 70, M_DEBUG) /* show l= ist info */ +#define D_SCRIPT LOGLEV(7, 70, M_DEBUG) /* show parms & env va= rs passed to scripts */ +#define D_SHOW_NET LOGLEV(7, 70, M_DEBUG) /* show routing table = and adapter list */ +#define D_ROUTE_DEBUG LOGLEV(7, 70, M_DEBUG) /* show verbose route.= [ch] output */ +#define D_TLS_STATE_ERRORS LOGLEV(7, 70, M_DEBUG) /* no TLS state for cl= ient */ +#define D_SEMAPHORE_LOW LOGLEV(7, 70, M_DEBUG) /* show Win32 semaphor= e waits (low freq) */ +#define D_SEMAPHORE LOGLEV(7, 70, M_DEBUG) /* show Win32 semaphor= e waits */ +#define D_TEST_FILE LOGLEV(7, 70, M_DEBUG) /* show test_file() ca= lls */ +#define D_MANAGEMENT_DEBUG LOGLEV(3, 70, M_DEBUG) /* show --management d= ebug info */ +#define D_PLUGIN_DEBUG LOGLEV(7, 70, M_DEBUG) /* show verbose plugin= calls */ +#define D_SOCKET_DEBUG LOGLEV(7, 70, M_DEBUG) /* show socket.[ch] de= bugging info */ +#define D_SHOW_PKCS11 LOGLEV(7, 70, M_DEBUG) /* show PKCS#11 action= s */ +#define D_ALIGN_DEBUG LOGLEV(7, 70, M_DEBUG) /* show verbose struct= alignment info */ +#define D_PACKET_TRUNC_DEBUG LOGLEV(7, 70, M_DEBUG) /* PACKET_TRUNCATION_C= HECK verbose */ +#define D_PING LOGLEV(7, 70, M_DEBUG) /* PING send/receive m= essages */ +#define D_PS_PROXY_DEBUG LOGLEV(7, 70, M_DEBUG) /* port share proxy de= bug */ +#define D_TLS_KEYSELECT LOGLEV(7, 70, M_DEBUG) /* show key selection = for data channel */ +#define D_ARGV_PARSE_CMD LOGLEV(7, 70, M_DEBUG) /* show parse_line() e= rrors in argv_parse_cmd */ +#define D_CRYPTO_DEBUG LOGLEV(7, 70, M_DEBUG) /* show detailed info = from crypto.c routines */ +#define D_PID_DEBUG LOGLEV(7, 70, M_DEBUG) /* show packet-id debu= gging info */ +#define D_PUSH_DEBUG LOGLEV(7, 73, M_DEBUG) /* show push/pull debu= gging info */ +#define D_SHOW_OCC LOGLEV(7, 74, M_DEBUG) /* show options compat= ibility string */ -#define D_VLAN_DEBUG LOGLEV(7, 74, M_DEBUG) /* show VLAN tagging/= untagging debug info */ +#define D_VLAN_DEBUG LOGLEV(7, 74, M_DEBUG) /* show VLAN tagging/un= tagging debug info */ -#define D_HANDSHAKE_VERBOSE LOGLEV(8, 70, M_DEBUG) /* show detailed desc= ription of handshake */ -#define D_TLS_DEBUG_MED LOGLEV(8, 70, M_DEBUG) /* limited info from = tls_session routines */ -#define D_INTERVAL LOGLEV(8, 70, M_DEBUG) /* show interval.h de= bugging info */ -#define D_SCHEDULER LOGLEV(8, 70, M_DEBUG) /* show scheduler deb= ugging info */ -#define D_GREMLIN_VERBOSE LOGLEV(8, 70, M_DEBUG) /* show verbose info = from gremlin module */ -#define D_REL_DEBUG LOGLEV(8, 70, M_DEBUG) /* show detailed info= from reliable routines */ -#define D_EVENT_WAIT LOGLEV(8, 70, M_DEBUG) /* show detailed info= from event waits */ -#define D_MULTI_TCP LOGLEV(8, 70, M_DEBUG) /* show debug info fr= om mtcp.c */ +#define D_HANDSHAKE_VERBOSE LOGLEV(8, 70, M_DEBUG) /* show detailed descri= ption of handshake */ +#define D_TLS_DEBUG_MED LOGLEV(8, 70, M_DEBUG) /* limited info from tl= s_session routines */ +#define D_INTERVAL LOGLEV(8, 70, M_DEBUG) /* show interval.h debu= gging info */ +#define D_SCHEDULER LOGLEV(8, 70, M_DEBUG) /* show scheduler debug= ging info */ +#define D_GREMLIN_VERBOSE LOGLEV(8, 70, M_DEBUG) /* show verbose info fr= om gremlin module */ +#define D_REL_DEBUG LOGLEV(8, 70, M_DEBUG) /* show detailed info f= rom reliable routines */ +#define D_EVENT_WAIT LOGLEV(8, 70, M_DEBUG) /* show detailed info f= rom event waits */ +#define D_MULTI_TCP LOGLEV(8, 70, M_DEBUG) /* show debug info from= mtcp.c */ -#define D_TLS_DEBUG LOGLEV(9, 70, M_DEBUG) /* show detailed info= from TLS routines */ -#define D_COMP LOGLEV(9, 70, M_DEBUG) /* show compression i= nfo */ -#define D_READ_WRITE LOGLEV(9, 70, M_DEBUG) /* show all tun/tcp/u= dp reads/writes/opens */ -#define D_PACKET_CONTENT LOGLEV(9, 70, M_DEBUG) /* show before/after = encryption packet content */ -#define D_TLS_NO_SEND_KEY LOGLEV(9, 70, M_DEBUG) /* show when no data = channel send-key exists */ -#define D_PID_PERSIST_DEBUG LOGLEV(9, 70, M_DEBUG) /* show packet-id per= sist debugging info */ -#define D_LINK_RW_VERBOSE LOGLEV(9, 70, M_DEBUG) /* increase link read= s/writes verbosity */ -#define D_STREAM_DEBUG LOGLEV(9, 70, M_DEBUG) /* show TCP stream de= bug info */ -#define D_WIN32_IO LOGLEV(9, 70, M_DEBUG) /* win32 I/O debuggin= g info */ -#define D_PKCS11_DEBUG LOGLEV(9, 70, M_DEBUG) /* show PKCS#11 debug= ging */ +#define D_TLS_DEBUG LOGLEV(9, 70, M_DEBUG) /* show detailed info f= rom TLS routines */ +#define D_COMP LOGLEV(9, 70, M_DEBUG) /* show compression inf= o */ +#define D_READ_WRITE LOGLEV(9, 70, M_DEBUG) /* show all tun/tcp/udp= reads/writes/opens */ +#define D_PACKET_CONTENT LOGLEV(9, 70, M_DEBUG) /* show before/after en= cryption packet content */ +#define D_TLS_NO_SEND_KEY LOGLEV(9, 70, M_DEBUG) /* show when no data ch= annel send-key exists */ +#define D_PID_PERSIST_DEBUG LOGLEV(9, 70, M_DEBUG) /* show packet-id persi= st debugging info */ +#define D_LINK_RW_VERBOSE LOGLEV(9, 70, M_DEBUG) /* increase link reads/= writes verbosity */ +#define D_STREAM_DEBUG LOGLEV(9, 70, M_DEBUG) /* show TCP stream debu= g info */ +#define D_WIN32_IO LOGLEV(9, 70, M_DEBUG) /* win32 I/O debugging = info */ +#define D_PKCS11_DEBUG LOGLEV(9, 70, M_DEBUG) /* show PKCS#11 debuggi= ng */ -#define D_SHAPER_DEBUG LOGLEV(10, 70, M_DEBUG) /* show traffic shape= r info */ +#define D_SHAPER_DEBUG LOGLEV(10, 70, M_DEBUG) /* show traffic shaper = info */ -#define D_REGISTRY LOGLEV(11, 70, M_DEBUG) /* win32 registry deb= ugging info */ -#define D_OPENSSL_LOCK LOGLEV(11, 70, M_DEBUG) /* show OpenSSL locks= */ +#define D_REGISTRY LOGLEV(11, 70, M_DEBUG) /* win32 registry debug= ging info */ +#define D_OPENSSL_LOCK LOGLEV(11, 70, M_DEBUG) /* show OpenSSL locks */ -/*#define D_THREAD_DEBUG LOGLEV(4, 70, M_DEBUG)*/ /* show pthread d= ebug information */ +/*#define D_THREAD_DEBUG LOGLEV(4, 70, M_DEBUG)*/ /* show pthread de= bug information */ -#endif /* ifndef ERRLEVEL_H */ +#endif /* ifndef ERRLEVEL= _H */ diff --git a/src/openvpn/error.c b/src/openvpn/error.c index 22c339f..dacfa8f 100644 --- a/src/openvpn/error.c +++ b/src/openvpn/error.c @@ -51,9 +51,9 @@ unsigned int x_debug_level; /* GLOBAL */ /* Mute state */ -static int mute_cutoff; /* GLOBAL */ -static int mute_count; /* GLOBAL */ -static int mute_category; /* GLOBAL */ +static int mute_cutoff; /* GLOBAL */ +static int mute_count; /* GLOBAL */ +static int mute_category; /* GLOBAL */ /* * Output mode priorities are as follows: @@ -67,28 +67,28 @@ /* If true, indicates that stdin/stdout/stderr * have been redirected due to --log */ -static bool std_redir; /* GLOBAL */ +static bool std_redir; /* GLOBAL */ /* Should messages be written to the syslog? */ -static bool use_syslog; /* GLOBAL */ +static bool use_syslog; /* GLOBAL */ /* Should stdout/stderr be be parsable and always be prefixed with time * and message flags */ -static bool machine_readable_output; /* GLOBAL */ +static bool machine_readable_output; /* GLOBAL */ /* Should timestamps be included on messages to stdout/stderr? */ static bool suppress_timestamps; /* GLOBAL */ /* The program name passed to syslog */ #if SYSLOG_CAPABILITY -static char *pgmname_syslog; /* GLOBAL */ +static char *pgmname_syslog; /* GLOBAL */ #endif /* If non-null, messages should be written here (used for debugging only) = */ -static FILE *msgfp; /* GLOBAL */ +static FILE *msgfp; /* GLOBAL */ /* If true, we forked from main OpenVPN process */ -static bool forked; /* GLOBAL */ +static bool forked; /* GLOBAL */ /* our default output targets */ static FILE *default_out; /* GLOBAL */ @@ -175,7 +175,7 @@ { openvpn_exit(OPENVPN_EXIT_STATUS_CANNOT_OPEN_DEBUG_FILE); /* exit = point */ } -#else /* ifdef OPENVPN_DEBUG_COMMAND_LINE */ +#else /* ifdef OPENVPN_DEBUG_COMMAND_LINE */ msgfp =3D NULL; #endif } @@ -195,7 +195,7 @@ FILE *fp =3D msgfp; if (!fp) { - fp =3D (flags & (M_FATAL|M_USAGE_SMALL)) ? default_err : default_o= ut; + fp =3D (flags & (M_FATAL | M_USAGE_SMALL)) ? default_err : default= _out; } if (!fp) { @@ -204,7 +204,12 @@ return fp; } -#define SWAP { tmp =3D m1; m1 =3D m2; m2 =3D tmp; } +#define SWAP \ + { \ + tmp =3D m1; \ + m1 =3D m2; \ + m2 =3D tmp; \ + } int x_msg_line_num; /* GLOBAL */ @@ -265,16 +270,15 @@ gc_init(&gc); - m1 =3D (char *) gc_malloc(ERR_BUF_SIZE, false, &gc); - m2 =3D (char *) gc_malloc(ERR_BUF_SIZE, false, &gc); + m1 =3D (char *)gc_malloc(ERR_BUF_SIZE, false, &gc); + m2 =3D (char *)gc_malloc(ERR_BUF_SIZE, false, &gc); vsnprintf(m1, ERR_BUF_SIZE, format, arglist); m1[ERR_BUF_SIZE - 1] =3D 0; /* windows vsnprintf needs this */ if ((flags & M_ERRNO) && e) { - snprintf(m2, ERR_BUF_SIZE, "%s: %s (errno=3D%d)", - m1, openvpn_strerror(e, crt_error, &gc), e); + snprintf(m2, ERR_BUF_SIZE, "%s: %s (errno=3D%d)", m1, openvpn_stre= rror(e, crt_error, &gc), e); SWAP; } @@ -285,7 +289,7 @@ } #if SYSLOG_CAPABILITY - if (flags & (M_FATAL|M_NONFATAL|M_USAGE_SMALL)) + if (flags & (M_FATAL | M_NONFATAL | M_USAGE_SMALL)) { level =3D LOG_ERR; } @@ -320,10 +324,7 @@ const struct virtual_output *vo =3D msg_get_virtual_output(); if (vo) { - snprintf(m2, ERR_BUF_SIZE, "%s%s%s", - prefix, - prefix_sep, - m1); + snprintf(m2, ERR_BUF_SIZE, "%s%s%s", prefix, prefix_sep, m1); virtual_output_print(vo, flags, m2); } } @@ -333,10 +334,7 @@ if (use_syslog && !std_redir && !forked) { #if SYSLOG_CAPABILITY - syslog(level, "%s%s%s", - prefix, - prefix_sep, - m1); + syslog(level, "%s%s%s", prefix, prefix_sep, m1); #endif } else @@ -349,32 +347,17 @@ struct timeval tv; gettimeofday(&tv, NULL); - fprintf(fp, "%" PRIi64 ".%06ld %x %s%s%s%s", - (int64_t)tv.tv_sec, - (long)tv.tv_usec, - flags, - prefix, - prefix_sep, - m1, - "\n"); - + fprintf(fp, "%" PRIi64 ".%06ld %x %s%s%s%s", (int64_t)tv.t= v_sec, (long)tv.tv_usec, + flags, prefix, prefix_sep, m1, "\n"); } else if ((flags & M_NOPREFIX) || suppress_timestamps) { - fprintf(fp, "%s%s%s%s", - prefix, - prefix_sep, - m1, - (flags&M_NOLF) ? "" : "\n"); + fprintf(fp, "%s%s%s%s", prefix, prefix_sep, m1, (flags & M= _NOLF) ? "" : "\n"); } else { - fprintf(fp, "%s %s%s%s%s", - time_string(0, 0, show_usec, &gc), - prefix, - prefix_sep, - m1, - (flags&M_NOLF) ? "" : "\n"); + fprintf(fp, "%s %s%s%s%s", time_string(0, 0, show_usec, &g= c), prefix, prefix_sep, + m1, (flags & M_NOLF) ? "" : "\n"); } fflush(fp); ++x_msg_line_num; @@ -389,7 +372,6 @@ if (flags & M_FATAL) { openvpn_exit(OPENVPN_EXIT_STATUS_ERROR); /* exit point */ - } if (flags & M_USAGE_SMALL) { @@ -426,8 +408,7 @@ if (suppressed > 0) { msg(M_INFO | M_NOMUTE, - "%d variation(s) on previous %d message(s) suppressed = by --mute", - suppressed, + "%d variation(s) on previous %d message(s) suppressed = by --mute", suppressed, mute_cutoff); } mute_count =3D 1; @@ -481,8 +462,9 @@ } } } -#else /* if SYSLOG_CAPABILITY */ - msg(M_WARN, "Warning on use of --daemon: this operating system lacks d= aemon logging features, therefore when I become a daemon, I won't be able t= o log status or error messages"); +#else /* if SYSLOG_CAPABILITY */ + msg(M_WARN, + "Warning on use of --daemon: this operating system lacks daemon lo= gging features, therefore when I become a daemon, I won't be able to log st= atus or error messages"); #endif } @@ -525,19 +507,14 @@ saAttr.bInheritHandle =3D TRUE; saAttr.lpSecurityDescriptor =3D NULL; - log_handle =3D CreateFileW(wide_string(file, &gc), - GENERIC_WRITE, - FILE_SHARE_READ, - &saAttr, - append ? OPEN_ALWAYS : CREATE_ALWAYS, - FILE_ATTRIBUTE_NORMAL, - NULL); + log_handle =3D CreateFileW(wide_string(file, &gc), GENERIC_WRITE, = FILE_SHARE_READ, &saAttr, + append ? OPEN_ALWAYS : CREATE_ALWAYS, FIL= E_ATTRIBUTE_NORMAL, NULL); gc_free(&gc); if (log_handle =3D=3D INVALID_HANDLE_VALUE) { - msg(M_WARN|M_ERRNO, "Warning: cannot open --log file: %s", fil= e); + msg(M_WARN | M_ERRNO, "Warning: cannot open --log file: %s", f= ile); return; } @@ -554,7 +531,8 @@ orig_stderr =3D _dup(_fileno(stderr)); if (orig_stderr =3D=3D -1) { - msg(M_WARN | M_ERRNO, "Warning: cannot duplicate stderr, passw= ord prompts will appear in log file instead of console."); + msg(M_WARN | M_ERRNO, + "Warning: cannot duplicate stderr, password prompts will a= ppear in log file instead of console."); orig_stderr =3D _fileno(stderr); } @@ -584,13 +562,12 @@ #elif defined(HAVE_DUP2) if (!std_redir) { - int out =3D open(file, - O_CREAT | O_WRONLY | (append ? O_APPEND : O_TRUNC), - S_IRUSR | S_IWUSR); + int out =3D open(file, O_CREAT | O_WRONLY | (append ? O_APPEND : O= _TRUNC), S_IRUSR | S_IWUSR); if (out < 0) { - msg(M_WARN|M_ERRNO, "Warning: Error redirecting stdout/stderr = to --log file: %s", file); + msg(M_WARN | M_ERRNO, "Warning: Error redirecting stdout/stder= r to --log file: %s", + file); return; } @@ -612,7 +589,8 @@ } #else /* if defined(_WIN32) */ - msg(M_WARN, "WARNING: The --log option is not supported on this OS bec= ause it lacks the dup2 function"); + msg(M_WARN, + "WARNING: The --log option is not supported on this OS because it = lacks the dup2 function"); #endif /* if defined(_WIN32) */ } @@ -648,10 +626,7 @@ * from the OS. */ void -x_check_status(int status, - const char *description, - struct link_socket *sock, - struct tuntap *tt) +x_check_status(int status, const char *description, struct link_socket *so= ck, struct tuntap *tt) { const char *extended_msg =3D NULL; @@ -659,9 +634,7 @@ int my_errno =3D openvpn_errno_maybe_crt(&crt_error); msg(x_cs_verbose_level, "%s %s returned %d", - sock ? proto2ascii(sock->info.proto, sock->info.af, true) : "", - description, - status); + sock ? proto2ascii(sock->info.proto, sock->info.af, true) : "", de= scription, status); if (status < 0) { @@ -693,16 +666,14 @@ if (extended_msg) { msg(x_cs_info_level, "%s %s [%s]: %s (fd=3D" SOCKET_PRINTF= ",code=3D%d)", description, - sock ? proto2ascii(sock->info.proto, sock->info.af, tr= ue) : "", - extended_msg, openvpn_strerror(my_errno, crt_error, &g= c), - sock ? sock->sd : -1, my_errno); + sock ? proto2ascii(sock->info.proto, sock->info.af, tr= ue) : "", extended_msg, + openvpn_strerror(my_errno, crt_error, &gc), sock ? soc= k->sd : -1, my_errno); } else { msg(x_cs_info_level, "%s %s: %s (fd=3D" SOCKET_PRINTF ",co= de=3D%d)", description, sock ? proto2ascii(sock->info.proto, sock->info.af, tr= ue) : "", - openvpn_strerror(my_errno, crt_error, &gc), - sock ? sock->sd : -1, my_errno); + openvpn_strerror(my_errno, crt_error, &gc), sock ? soc= k->sd : -1, my_errno); } if (x_cs_err_delay_ms) @@ -970,16 +941,10 @@ wchar_t wmessage[256]; char *message =3D NULL; struct buffer out =3D alloc_buf_gc(256, gc); - const DWORD status =3D FormatMessageW( - FORMAT_MESSAGE_IGNORE_INSERTS - | FORMAT_MESSAGE_FROM_SYSTEM - | FORMAT_MESSAGE_ARGUMENT_ARRAY, - NULL, - errnum, - 0, - wmessage, - SIZE(wmessage), - NULL); + const DWORD status =3D + FormatMessageW(FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_= FROM_SYSTEM + | FORMAT_MESSAGE_ARGUMENT_ARRAY, + NULL, errnum, 0, wmessage, SIZE(wmessage), NULL= ); if (status) { message =3D utf16to8(wmessage, gc); diff --git a/src/openvpn/error.h b/src/openvpn/error.h index cd0cac3..8388f82 100644 --- a/src/openvpn/error.h +++ b/src/openvpn/error.h @@ -49,10 +49,10 @@ * Exit status codes */ -#define OPENVPN_EXIT_STATUS_GOOD 0 -#define OPENVPN_EXIT_STATUS_ERROR 1 -#define OPENVPN_EXIT_STATUS_USAGE 1 -#define OPENVPN_EXIT_STATUS_CANNOT_OPEN_DEBUG_FILE 1 +#define OPENVPN_EXIT_STATUS_GOOD 0 +#define OPENVPN_EXIT_STATUS_ERROR 1 +#define OPENVPN_EXIT_STATUS_USAGE 1 +#define OPENVPN_EXIT_STATUS_CANNOT_OPEN_DEBUG_FILE 1 /* * Special command line debugging mode. @@ -83,27 +83,27 @@ /* msg() flags */ -#define M_DEBUG_LEVEL (0x0F) /* debug level mask */ +#define M_DEBUG_LEVEL (0x0F) /* debug level mask */ -#define M_FATAL (1<<4) /* exit program */ -#define M_NONFATAL (1<<5) /* non-fatal error */ -#define M_WARN (1<<6) /* call syslog with LOG_WARNING */ -#define M_DEBUG (1<<7) +#define M_FATAL (1 << 4) /* exit program */ +#define M_NONFATAL (1 << 5) /* non-fatal error */ +#define M_WARN (1 << 6) /* call syslog with LOG_WARNING */ +#define M_DEBUG (1 << 7) -#define M_ERRNO (1<<8) /* show errno description */ +#define M_ERRNO (1 << 8) /* show errno description */ -#define M_NOMUTE (1<<11) /* don't do mute processing */ -#define M_NOPREFIX (1<<12) /* don't show date/time prefix */ -#define M_USAGE_SMALL (1<<13) /* fatal options error, call usag= e_small */ -#define M_MSG_VIRT_OUT (1<<14) /* output message through msg_sta= tus_output callback */ -#define M_OPTERR (1<<15) /* print "Options error:" prefix = */ -#define M_NOLF (1<<16) /* don't print new line */ -#define M_NOIPREFIX (1<<17) /* don't print instance prefix */ +#define M_NOMUTE (1 << 11) /* don't do mute processing */ +#define M_NOPREFIX (1 << 12) /* don't show date/time prefix */ +#define M_USAGE_SMALL (1 << 13) /* fatal options error, call usage_small = */ +#define M_MSG_VIRT_OUT (1 << 14) /* output message through msg_status_outp= ut callback */ +#define M_OPTERR (1 << 15) /* print "Options error:" prefix */ +#define M_NOLF (1 << 16) /* don't print new line */ +#define M_NOIPREFIX (1 << 17) /* don't print instance prefix */ /* flag combinations which are frequently used */ -#define M_ERR (M_FATAL | M_ERRNO) -#define M_USAGE (M_USAGE_SMALL | M_NOPREFIX | M_OPTERR) -#define M_CLIENT (M_MSG_VIRT_OUT | M_NOMUTE | M_NOIPREFIX) +#define M_ERR (M_FATAL | M_ERRNO) +#define M_USAGE (M_USAGE_SMALL | M_NOPREFIX | M_OPTERR) +#define M_CLIENT (M_MSG_VIRT_OUT | M_NOMUTE | M_NOIPREFIX) /* * Mute levels are designed to avoid large numbers of @@ -112,10 +112,10 @@ * A mute level of 0 is always printed. */ #define MUTE_LEVEL_SHIFT 24 -#define MUTE_LEVEL_MASK 0xFF +#define MUTE_LEVEL_MASK 0xFF #define ENCODE_MUTE_LEVEL(mute_level) (((mute_level) & MUTE_LEVEL_MASK) <<= MUTE_LEVEL_SHIFT) -#define DECODE_MUTE_LEVEL(flags) (((flags) >> MUTE_LEVEL_SHIFT) & MUTE_LEV= EL_MASK) +#define DECODE_MUTE_LEVEL(flags) (((flags) >> MUTE_LEVEL_SHIFT) & MUT= E_LEVEL_MASK) /* * log_level: verbosity level n (--verb n) must be >=3D log_level to prin= t. @@ -138,11 +138,34 @@ bool dont_mute(unsigned int flags); /* Macro to ensure (and teach static analysis tools) we exit on fatal erro= rs */ -#define EXIT_FATAL(flags) do { if ((flags) & M_FATAL) {_exit(1);}} while (= false) +#define EXIT_FATAL(flags) \ + do \ + { \ + if ((flags) & M_FATAL) \ + { \ + _exit(1); \ + } \ + } while (false) -#define msg(flags, ...) do { if (msg_test(flags)) {x_msg((flags), __VA_ARG= S__);} EXIT_FATAL(flags); } while (false) +#define msg(flags, ...) \ + do \ + { \ + if (msg_test(flags)) \ + { \ + x_msg((flags), __VA_ARGS__); \ + } \ + EXIT_FATAL(flags); \ + } while (false) #ifdef ENABLE_DEBUG -#define dmsg(flags, ...) do { if (msg_test(flags)) {x_msg((flags), __VA_AR= GS__);} EXIT_FATAL(flags); } while (false) +#define dmsg(flags, ...) \ + do \ + { \ + if (msg_test(flags)) \ + { \ + x_msg((flags), __VA_ARGS__); \ + } \ + EXIT_FATAL(flags); \ + } while (false) #else #define dmsg(flags, ...) #endif @@ -150,12 +173,12 @@ void x_msg(const unsigned int flags, const char *format, ...) #ifdef __GNUC__ #if __USE_MINGW_ANSI_STDIO -__attribute__ ((format(gnu_printf, 2, 3))) + __attribute__((format(gnu_printf, 2, 3))) #else -__attribute__ ((format(__printf__, 2, 3))) + __attribute__((format(__printf__, 2, 3))) #endif #endif -; /* should be called via msg above */ + ; /* should be called via msg above */ void x_msg_va(const unsigned int flags, const char *format, va_list arglis= t); @@ -173,7 +196,7 @@ void set_machine_readable_output(bool parsable); -#define SDL_CONSTRAIN (1<<0) +#define SDL_CONSTRAIN (1 << 0) bool set_debug_level(const int level, const unsigned int flags); bool set_mute_cutoff(const int cutoff); @@ -191,26 +214,41 @@ /* Fatal logic errors */ #ifndef ENABLE_SMALL -#define ASSERT(x) do { if (!(x)) {assert_failed(__FILE__, __LINE__, #x);}}= while (false) +#define ASSERT(x) \ + do \ + { \ + if (!(x)) \ + { \ + assert_failed(__FILE__, __LINE__, #x); \ + } \ + } while (false) #else -#define ASSERT(x) do { if (!(x)) {assert_failed(__FILE__, __LINE__, NULL);= }} while (false) +#define ASSERT(x) \ + do \ + { \ + if (!(x)) \ + { \ + assert_failed(__FILE__, __LINE__, NULL); \ + } \ + } while (false) #endif #ifdef _MSC_VER __declspec(noreturn) #endif -void assert_failed(const char *filename, int line, const char *condition) +void +assert_failed(const char *filename, int line, const char *condition) #ifndef _MSC_VER -__attribute__((__noreturn__)) + __attribute__((__noreturn__)) #endif -; + ; /* Poor-man's static_assert() for when not supplied by assert.h, taken from * Linux's sys/cdefs.h under GPLv2 */ #ifndef static_assert -#define static_assert(expr, diagnostic) \ - extern int (*__OpenVPN_static_assert_function(void)) \ - [!!sizeof(struct { int __error_if_negative : (expr) ? 2 : -1; })] +#define static_assert(expr, diagnostic) \ + extern int (*__OpenVPN_static_assert_function( \ + void))[!!sizeof(struct { int __error_if_negative : (expr) ? 2 : -1= ; })] #endif /* Inline functions */ @@ -267,9 +305,7 @@ void set_check_status(unsigned int info_level, unsigned int verbose_level); -void x_check_status(int status, - const char *description, - struct link_socket *sock, +void x_check_status(int status, const char *description, struct link_socke= t *sock, struct tuntap *tt); static inline void @@ -383,7 +419,7 @@ *crt_error =3D true; err =3D errno; } -#else /* ifdef _WIN32 */ +#else /* ifdef _WIN32 */ *crt_error =3D true; err =3D errno; #endif diff --git a/src/openvpn/event.c b/src/openvpn/event.c index c773783..581bdbb 100644 --- a/src/openvpn/event.c +++ b/src/openvpn/event.c @@ -176,8 +176,8 @@ ASSERT(index >=3D 0 && index < wes->n_events); for (i =3D index; i < wes->n_events - 1; ++i) { - wes->events[i] =3D wes->events[i+1]; - wes->esr[i] =3D wes->esr[i+1]; + wes->events[i] =3D wes->events[i + 1]; + wes->esr[i] =3D wes->esr[i + 1]; } --wes->n_events; } @@ -206,7 +206,7 @@ static void we_free(struct event_set *es) { - struct we_set *wes =3D (struct we_set *) es; + struct we_set *wes =3D (struct we_set *)es; free(wes->events); free(wes->esr); free(wes); @@ -215,7 +215,7 @@ static void we_reset(struct event_set *es) { - struct we_set *wes =3D (struct we_set *) es; + struct we_set *wes =3D (struct we_set *)es; ASSERT(wes->fast); wes->n_events =3D 0; } @@ -223,7 +223,7 @@ static void we_del(struct event_set *es, event_t event) { - struct we_set *wes =3D (struct we_set *) es; + struct we_set *wes =3D (struct we_set *)es; ASSERT(!wes->fast); we_del_event(wes, event); } @@ -231,13 +231,10 @@ static void we_ctl(struct event_set *es, event_t event, unsigned int rwflags, void *ar= g) { - struct we_set *wes =3D (struct we_set *) es; + struct we_set *wes =3D (struct we_set *)es; - dmsg(D_EVENT_WAIT, "WE_CTL n=3D%d ev=3D%p rwflags=3D0x%04x arg=3D" ptr= _format, - wes->n_events, - event, - rwflags, - (ptr_type)arg); + dmsg(D_EVENT_WAIT, "WE_CTL n=3D%d ev=3D%p rwflags=3D0x%04x arg=3D" ptr= _format, wes->n_events, event, + rwflags, (ptr_type)arg); =20 if (wes->fast) { @@ -330,11 +327,11 @@ } break; - case EVENT_READ|EVENT_WRITE: + case EVENT_READ | EVENT_WRITE: switch (n) { case 0: - if (!we_append_event(wes, event, EVENT_READ|EVENT_= WRITE, arg)) + if (!we_append_event(wes, event, EVENT_READ | EVEN= T_WRITE, arg)) { goto err; } @@ -377,13 +374,15 @@ return; err: - msg(D_EVENT_ERRORS, "Error: Windows resource limit WSA_MAXIMUM_WAIT_EV= ENTS (%d) has been exceeded", WSA_MAXIMUM_WAIT_EVENTS); + msg(D_EVENT_ERRORS, + "Error: Windows resource limit WSA_MAXIMUM_WAIT_EVENTS (%d) has be= en exceeded", + WSA_MAXIMUM_WAIT_EVENTS); } static int we_wait(struct event_set *es, const struct timeval *tv, struct event_set_r= eturn *out, int outlen) { - struct we_set *wes =3D (struct we_set *) es; + struct we_set *wes =3D (struct we_set *)es; const int timeout =3D tv_to_ms_timeout(tv); DWORD status; @@ -395,11 +394,8 @@ int i; for (i =3D 0; i < wes->n_events; ++i) { - dmsg(D_EVENT_WAIT, "[%d] ev=3D%p rwflags=3D0x%04x arg=3D" ptr_= format, - i, - wes->events[i], - wes->esr[i].rwflags, - (ptr_type)wes->esr[i].arg); + dmsg(D_EVENT_WAIT, "[%d] ev=3D%p rwflags=3D0x%04x arg=3D" ptr_= format, i, wes->events[i], + wes->esr[i].rwflags, (ptr_type)wes->esr[i].arg); } } #endif @@ -407,18 +403,13 @@ /* * First poll our event list with 0 timeout */ - status =3D WSAWaitForMultipleEvents( - (DWORD) wes->n_events, - wes->events, - FALSE, - (DWORD) 0, - FALSE); + status =3D WSAWaitForMultipleEvents((DWORD)wes->n_events, wes->events,= FALSE, (DWORD)0, FALSE); /* * If at least one event is already set, we must * individually poll the whole list. */ - if (status >=3D WSA_WAIT_EVENT_0 && status < WSA_WAIT_EVENT_0 + (DWORD= ) wes->n_events) + if (status >=3D WSA_WAIT_EVENT_0 && status < WSA_WAIT_EVENT_0 + (DWORD= )wes->n_events) { int i; int j =3D 0; @@ -431,8 +422,8 @@ if (WaitForSingleObject(wes->events[i], 0) =3D=3D WAIT_OBJECT_= 0) { *out =3D wes->esr[i]; - dmsg(D_EVENT_WAIT, "WE_WAIT leave [%d,%d] rwflags=3D0x%04x= arg=3D" ptr_format, - i, j, out->rwflags, (ptr_type)out->arg); + dmsg(D_EVENT_WAIT, "WE_WAIT leave [%d,%d] rwflags=3D0x%04x= arg=3D" ptr_format, i, j, + out->rwflags, (ptr_type)out->arg); ++j; ++out; } @@ -452,19 +443,16 @@ */ if (timeout > 0) { - status =3D WSAWaitForMultipleEvents( - (DWORD) wes->n_events, - wes->events, - FALSE, - (DWORD) timeout, - FALSE); + status =3D WSAWaitForMultipleEvents((DWORD)wes->n_events, wes-= >events, FALSE, + (DWORD)timeout, FALSE); } - if (outlen >=3D 1 && status >=3D WSA_WAIT_EVENT_0 && status < WSA_= WAIT_EVENT_0 + (DWORD) wes->n_events) + if (outlen >=3D 1 && status >=3D WSA_WAIT_EVENT_0 + && status < WSA_WAIT_EVENT_0 + (DWORD)wes->n_events) { *out =3D wes->esr[status - WSA_WAIT_EVENT_0]; - dmsg(D_EVENT_WAIT, "WE_WAIT leave rwflags=3D0x%04x arg=3D" ptr= _format, - out->rwflags, (ptr_type)out->arg); + dmsg(D_EVENT_WAIT, "WE_WAIT leave rwflags=3D0x%04x arg=3D" ptr= _format, out->rwflags, + (ptr_type)out->arg); return 1; } else if (status =3D=3D WSA_WAIT_TIMEOUT) @@ -511,10 +499,9 @@ /* Allocate space for event_set_return objects */ ALLOC_ARRAY_CLEAR(wes->esr, struct event_set_return, wes->capacity); - dmsg(D_EVENT_WAIT, "WE_INIT maxevents=3D%d capacity=3D%d", - *maxevents, wes->capacity); + dmsg(D_EVENT_WAIT, "WE_INIT maxevents=3D%d capacity=3D%d", *maxevents,= wes->capacity); - return (struct event_set *) wes; + return (struct event_set *)wes; } #endif /* _WIN32 */ @@ -533,7 +520,7 @@ static void ep_free(struct event_set *es) { - struct ep_set *eps =3D (struct ep_set *) es; + struct ep_set *eps =3D (struct ep_set *)es; close(eps->epfd); free(eps->events); free(eps); @@ -542,7 +529,7 @@ static void ep_reset(struct event_set *es) { - const struct ep_set *eps =3D (struct ep_set *) es; + const struct ep_set *eps =3D (struct ep_set *)es; ASSERT(eps->fast); } @@ -550,7 +537,7 @@ ep_del(struct event_set *es, event_t event) { struct epoll_event ev; - struct ep_set *eps =3D (struct ep_set *) es; + struct ep_set *eps =3D (struct ep_set *)es; dmsg(D_EVENT_WAIT, "EP_DEL ev=3D%d", (int)event); @@ -558,14 +545,14 @@ CLEAR(ev); if (epoll_ctl(eps->epfd, EPOLL_CTL_DEL, event, &ev) < 0) { - msg(M_WARN|M_ERRNO, "EVENT: epoll_ctl EPOLL_CTL_DEL failed, sd=3D%= d", (int)event); + msg(M_WARN | M_ERRNO, "EVENT: epoll_ctl EPOLL_CTL_DEL failed, sd= =3D%d", (int)event); } } static void ep_ctl(struct event_set *es, event_t event, unsigned int rwflags, void *ar= g) { - struct ep_set *eps =3D (struct ep_set *) es; + struct ep_set *eps =3D (struct ep_set *)es; struct epoll_event ev; CLEAR(ev); @@ -580,11 +567,8 @@ ev.events |=3D EPOLLOUT; } - dmsg(D_EVENT_WAIT, "EP_CTL fd=3D%d rwflags=3D0x%04x ev=3D0x%08x arg=3D= " ptr_format, - (int)event, - rwflags, - (unsigned int)ev.events, - (ptr_type)ev.data.ptr); + dmsg(D_EVENT_WAIT, "EP_CTL fd=3D%d rwflags=3D0x%04x ev=3D0x%08x arg=3D= " ptr_format, (int)event, rwflags, + (unsigned int)ev.events, (ptr_type)ev.data.ptr); if (epoll_ctl(eps->epfd, EPOLL_CTL_MOD, event, &ev) < 0) { @@ -605,7 +589,7 @@ static int ep_wait(struct event_set *es, const struct timeval *tv, struct event_set_r= eturn *out, int outlen) { - struct ep_set *eps =3D (struct ep_set *) es; + struct ep_set *eps =3D (struct ep_set *)es; int stat; if (outlen > eps->maxevents) @@ -624,7 +608,7 @@ for (i =3D 0; i < stat; ++i) { esr->rwflags =3D 0; - if (ev->events & (EPOLLIN|EPOLLPRI|EPOLLERR|EPOLLHUP)) + if (ev->events & (EPOLLIN | EPOLLPRI | EPOLLERR | EPOLLHUP)) { esr->rwflags |=3D EVENT_READ; } @@ -633,8 +617,8 @@ esr->rwflags |=3D EVENT_WRITE; } esr->arg =3D ev->data.ptr; - dmsg(D_EVENT_WAIT, "EP_WAIT[%d] rwflags=3D0x%04x ev=3D0x%08x a= rg=3D" ptr_format, - i, esr->rwflags, ev->events, (ptr_type)ev->data.ptr); + dmsg(D_EVENT_WAIT, "EP_WAIT[%d] rwflags=3D0x%04x ev=3D0x%08x a= rg=3D" ptr_format, i, + esr->rwflags, ev->events, (ptr_type)ev->data.ptr); ++ev; ++esr; } @@ -682,7 +666,7 @@ /* set epoll control fd */ eps->epfd =3D fd; - return (struct event_set *) eps; + return (struct event_set *)eps; } #endif /* EPOLL */ @@ -701,7 +685,7 @@ static void po_free(struct event_set *es) { - struct po_set *pos =3D (struct po_set *) es; + struct po_set *pos =3D (struct po_set *)es; free(pos->events); free(pos->args); free(pos); @@ -710,7 +694,7 @@ static void po_reset(struct event_set *es) { - struct po_set *pos =3D (struct po_set *) es; + struct po_set *pos =3D (struct po_set *)es; ASSERT(pos->fast); pos->n_events =3D 0; } @@ -718,7 +702,7 @@ static void po_del(struct event_set *es, event_t event) { - struct po_set *pos =3D (struct po_set *) es; + struct po_set *pos =3D (struct po_set *)es; int i; dmsg(D_EVENT_WAIT, "PO_DEL ev=3D%d", (int)event); @@ -731,8 +715,8 @@ int j; for (j =3D i; j < pos->n_events - 1; ++j) { - pos->events[j] =3D pos->events[j+1]; - pos->args[j] =3D pos->args[j+1]; + pos->events[j] =3D pos->events[j + 1]; + pos->args[j] =3D pos->args[j + 1]; } --pos->n_events; break; @@ -750,7 +734,7 @@ } if (rwflags & EVENT_READ) { - pfdp->events |=3D (POLLIN|POLLPRI); + pfdp->events |=3D (POLLIN | POLLPRI); } } @@ -775,10 +759,10 @@ static void po_ctl(struct event_set *es, event_t event, unsigned int rwflags, void *ar= g) { - struct po_set *pos =3D (struct po_set *) es; + struct po_set *pos =3D (struct po_set *)es; - dmsg(D_EVENT_WAIT, "PO_CTL rwflags=3D0x%04x ev=3D%d arg=3D" ptr_format, - rwflags, (int)event, (ptr_type)arg); + dmsg(D_EVENT_WAIT, "PO_CTL rwflags=3D0x%04x ev=3D%d arg=3D" ptr_format= , rwflags, (int)event, + (ptr_type)arg); if (pos->fast) { @@ -816,7 +800,7 @@ static int po_wait(struct event_set *es, const struct timeval *tv, struct event_set_r= eturn *out, int outlen) { - struct po_set *pos =3D (struct po_set *) es; + struct po_set *pos =3D (struct po_set *)es; int stat; stat =3D poll(pos->events, pos->n_events, tv_to_ms_timeout(tv)); @@ -829,10 +813,10 @@ const struct pollfd *pfdp =3D pos->events; for (i =3D 0; i < pos->n_events && j < outlen; ++i) { - if (pfdp->revents & (POLLIN|POLLPRI|POLLERR|POLLHUP|POLLOUT)) + if (pfdp->revents & (POLLIN | POLLPRI | POLLERR | POLLHUP | PO= LLOUT)) { out->rwflags =3D 0; - if (pfdp->revents & (POLLIN|POLLPRI|POLLERR|POLLHUP)) + if (pfdp->revents & (POLLIN | POLLPRI | POLLERR | POLLHUP)) { out->rwflags |=3D EVENT_READ; } @@ -841,8 +825,10 @@ out->rwflags |=3D EVENT_WRITE; } out->arg =3D pos->args[i]; - dmsg(D_EVENT_WAIT, "PO_WAIT[%d,%d] fd=3D%d rev=3D0x%08x rw= flags=3D0x%04x arg=3D" ptr_format " %s", - i, j, pfdp->fd, pfdp->revents, out->rwflags, (ptr_typ= e)out->arg, pos->fast ? "" : "[scalable]"); + dmsg(D_EVENT_WAIT, + "PO_WAIT[%d,%d] fd=3D%d rev=3D0x%08x rwflags=3D0x%04x= arg=3D" ptr_format " %s", i, j, + pfdp->fd, pfdp->revents, out->rwflags, (ptr_type)out-= >arg, + pos->fast ? "" : "[scalable]"); ++out; ++j; } @@ -891,7 +877,7 @@ /* Allocate space for event_set_return objects */ ALLOC_ARRAY_CLEAR(pos->args, void *, pos->capacity); - return (struct event_set *) pos; + return (struct event_set *)pos; } #endif /* POLL */ @@ -903,15 +889,15 @@ bool fast; fd_set readfds; fd_set writefds; - void **args; /* allocated to capacity size */ - int maxfd; /* largest fd seen so far, always < capacity */ + void **args; /* allocated to capacity size */ + int maxfd; /* largest fd seen so far, always < capacity */ int capacity; /* fixed largest fd + 1 */ }; static void se_free(struct event_set *es) { - struct se_set *ses =3D (struct se_set *) es; + struct se_set *ses =3D (struct se_set *)es; free(ses->args); free(ses); } @@ -919,7 +905,7 @@ static void se_reset(struct event_set *es) { - struct se_set *ses =3D (struct se_set *) es; + struct se_set *ses =3D (struct se_set *)es; int i; ASSERT(ses->fast); =20 @@ -937,7 +923,7 @@ static void se_del(struct event_set *es, event_t event) { - struct se_set *ses =3D (struct se_set *) es; + struct se_set *ses =3D (struct se_set *)es; ASSERT(!ses->fast); dmsg(D_EVENT_WAIT, "SE_DEL ev=3D%d", (int)event); @@ -958,7 +944,7 @@ static void se_ctl(struct event_set *es, event_t event, unsigned int rwflags, void *ar= g) { - struct se_set *ses =3D (struct se_set *) es; + struct se_set *ses =3D (struct se_set *)es; dmsg(D_EVENT_WAIT, "SE_CTL rwflags=3D0x%04x ev=3D%d fast=3D%d cap=3D%d= maxfd=3D%d arg=3D" ptr_format, rwflags, (int)event, (int)ses->fast, ses->capacity, ses->maxfd, (= ptr_type)arg); @@ -1000,17 +986,13 @@ } else { - msg(D_EVENT_ERRORS, "Error: select: too many I/O wait events, fd= =3D%d cap=3D%d", - (int) event, + msg(D_EVENT_ERRORS, "Error: select: too many I/O wait events, fd= =3D%d cap=3D%d", (int)event, ses->capacity); } } static int -se_wait_return(struct se_set *ses, - fd_set *read, - fd_set *write, - struct event_set_return *out, +se_wait_return(struct se_set *ses, fd_set *read, fd_set *write, struct eve= nt_set_return *out, int outlen) { int i, j =3D 0; @@ -1030,8 +1012,8 @@ out->rwflags |=3D EVENT_WRITE; } out->arg =3D ses->args[i]; - dmsg(D_EVENT_WAIT, "SE_WAIT[%d,%d] rwflags=3D0x%04x arg=3D" pt= r_format, - i, j, out->rwflags, (ptr_type)out->arg); + dmsg(D_EVENT_WAIT, "SE_WAIT[%d,%d] rwflags=3D0x%04x arg=3D" pt= r_format, i, j, out->rwflags, + (ptr_type)out->arg); ++out; ++j; } @@ -1040,16 +1022,15 @@ } static int -se_wait_fast(struct event_set *es, const struct timeval *tv, struct event_= set_return *out, int outlen) +se_wait_fast(struct event_set *es, const struct timeval *tv, struct event_= set_return *out, + int outlen) { - struct se_set *ses =3D (struct se_set *) es; + struct se_set *ses =3D (struct se_set *)es; struct timeval tv_tmp =3D *tv; int stat; - dmsg(D_EVENT_WAIT, "SE_WAIT_FAST maxfd=3D%d tv=3D%" PRIi64 "/%ld", - ses->maxfd, - (int64_t)tv_tmp.tv_sec, - (long)tv_tmp.tv_usec); + dmsg(D_EVENT_WAIT, "SE_WAIT_FAST maxfd=3D%d tv=3D%" PRIi64 "/%ld", ses= ->maxfd, + (int64_t)tv_tmp.tv_sec, (long)tv_tmp.tv_usec); stat =3D select(ses->maxfd + 1, &ses->readfds, &ses->writefds, NULL, &= tv_tmp); @@ -1062,16 +1043,17 @@ } static int -se_wait_scalable(struct event_set *es, const struct timeval *tv, struct ev= ent_set_return *out, int outlen) +se_wait_scalable(struct event_set *es, const struct timeval *tv, struct ev= ent_set_return *out, + int outlen) { - struct se_set *ses =3D (struct se_set *) es; + struct se_set *ses =3D (struct se_set *)es; struct timeval tv_tmp =3D *tv; fd_set read =3D ses->readfds; fd_set write =3D ses->writefds; int stat; - dmsg(D_EVENT_WAIT, "SE_WAIT_SCALEABLE maxfd=3D%d tv=3D%" PRIi64 "/%ld", - ses->maxfd, (int64_t)tv_tmp.tv_sec, (long)tv_tmp.tv_usec); + dmsg(D_EVENT_WAIT, "SE_WAIT_SCALEABLE maxfd=3D%d tv=3D%" PRIi64 "/%ld"= , ses->maxfd, + (int64_t)tv_tmp.tv_sec, (long)tv_tmp.tv_usec); stat =3D select(ses->maxfd + 1, &read, &write, NULL, &tv_tmp); @@ -1116,7 +1098,7 @@ /* Allocate space for event_set_return void * args */ ALLOC_ARRAY_CLEAR(ses->args, void *, ses->capacity); - return (struct event_set *) ses; + return (struct event_set *)ses; } #endif /* SELECT */ @@ -1142,7 +1124,7 @@ { ret =3D po_init(maxevents, flags); } -#else /* ifdef SELECT_PREFERRED_OVER_POLL */ +#else /* ifdef SELECT_PREFERRED_OVER_POLL */ if (!ret) { ret =3D po_init(maxevents, flags); @@ -1174,7 +1156,7 @@ msg(M_WARN, "Note: sys_epoll API is unavailable, falling back to p= oll/select API"); ret =3D event_set_init_simple(maxevents, flags); } -#else /* if EPOLL */ +#else /* if EPOLL */ ret =3D event_set_init_simple(maxevents, flags); #endif ASSERT(ret); diff --git a/src/openvpn/event.h b/src/openvpn/event.h index 38178fc..8422996 100644 --- a/src/openvpn/event.h +++ b/src/openvpn/event.h @@ -31,12 +31,12 @@ * rwflags passed to event_ctl and returned by * struct event_set_return. */ -#define READ_SHIFT 0 -#define WRITE_SHIFT 1 +#define READ_SHIFT 0 +#define WRITE_SHIFT 1 =20 -#define EVENT_UNDEF 4 -#define EVENT_READ (1 << READ_SHIFT) -#define EVENT_WRITE (1 << WRITE_SHIFT) +#define EVENT_UNDEF 4 +#define EVENT_READ (1 << READ_SHIFT) +#define EVENT_WRITE (1 << WRITE_SHIFT) /* event flags returned by io_wait. * @@ -57,35 +57,35 @@ * signals. */ -#define SOCKET_SHIFT 0 -#define SOCKET_READ (1 << (SOCKET_SHIFT + READ_SHIFT)) -#define SOCKET_WRITE (1 << (SOCKET_SHIFT + WRITE_SHIFT)) -#define TUN_SHIFT 2 -#define TUN_READ (1 << (TUN_SHIFT + READ_SHIFT)) -#define TUN_WRITE (1 << (TUN_SHIFT + WRITE_SHIFT)) -#define ERR_SHIFT 4 -#define ES_ERROR (1 << (ERR_SHIFT + READ_SHIFT)) -#define ES_TIMEOUT (1 << (ERR_SHIFT + WRITE_SHIFT)) -#define MANAGEMENT_SHIFT 6 -#define MANAGEMENT_READ (1 << (MANAGEMENT_SHIFT + READ_SHIFT)) -#define MANAGEMENT_WRITE (1 << (MANAGEMENT_SHIFT + WRITE_SHIFT)) -#define FILE_SHIFT 8 -#define FILE_CLOSED (1 << (FILE_SHIFT + READ_SHIFT)) -#define DCO_SHIFT 10 -#define DCO_READ (1 << (DCO_SHIFT + READ_SHIFT)) -#define DCO_WRITE (1 << (DCO_SHIFT + WRITE_SHIFT)) +#define SOCKET_SHIFT 0 +#define SOCKET_READ (1 << (SOCKET_SHIFT + READ_SHIFT)) +#define SOCKET_WRITE (1 << (SOCKET_SHIFT + WRITE_SHIFT)) +#define TUN_SHIFT 2 +#define TUN_READ (1 << (TUN_SHIFT + READ_SHIFT)) +#define TUN_WRITE (1 << (TUN_SHIFT + WRITE_SHIFT)) +#define ERR_SHIFT 4 +#define ES_ERROR (1 << (ERR_SHIFT + READ_SHIFT)) +#define ES_TIMEOUT (1 << (ERR_SHIFT + WRITE_SHIFT)) +#define MANAGEMENT_SHIFT 6 +#define MANAGEMENT_READ (1 << (MANAGEMENT_SHIFT + READ_SHIFT)) +#define MANAGEMENT_WRITE (1 << (MANAGEMENT_SHIFT + WRITE_SHIFT)) +#define FILE_SHIFT 8 +#define FILE_CLOSED (1 << (FILE_SHIFT + READ_SHIFT)) +#define DCO_SHIFT 10 +#define DCO_READ (1 << (DCO_SHIFT + READ_SHIFT)) +#define DCO_WRITE (1 << (DCO_SHIFT + WRITE_SHIFT)) /* * Initialization flags passed to event_set_init */ -#define EVENT_METHOD_US_TIMEOUT (1<<0) -#define EVENT_METHOD_FAST (1<<1) +#define EVENT_METHOD_US_TIMEOUT (1 << 0) +#define EVENT_METHOD_FAST (1 << 1) /* * The following constant is used as boundary between integer value * and real addresses when passing arguments to event handlers as (void *) */ -#define MULTI_N ((void *)16) /* upper bound on MTCP_x */ +#define MULTI_N ((void *)16) /* upper bound on MTCP_x */ #ifdef _WIN32 =20 @@ -93,7 +93,7 @@ #define UNDEFINED_EVENT (NULL) -#else /* ifdef _WIN32 */ +#else /* ifdef _WIN32 */ typedef int event_t; @@ -117,7 +117,8 @@ * 0 on timeout * length of event_set_return if at least 1 event is returned */ - int (*wait)(struct event_set *es, const struct timeval *tv, struct eve= nt_set_return *out, int outlen); + int (*wait)(struct event_set *es, const struct timeval *tv, struct eve= nt_set_return *out, + int outlen); }; struct event_set_return @@ -131,7 +132,8 @@ struct event_set_functions func; }; -typedef enum { +typedef enum +{ EVENT_ARG_MULTI_INSTANCE =3D 0, EVENT_ARG_LINK_SOCKET, } event_arg_t; @@ -140,9 +142,10 @@ struct event_arg { event_arg_t type; - union { + union + { struct multi_instance *mi; /* if type =3D EVENT_ARG_MULTI_INSTANCE= */ - struct link_socket *sock; /* if type =3D EVENT_ARG_LINK_SOCKET */ + struct link_socket *sock; /* if type =3D EVENT_ARG_LINK_SOCKET */ } u; }; @@ -210,7 +213,7 @@ } } -#else /* ifdef _WIN32 */ +#else /* ifdef _WIN32 */ static inline void wait_signal(struct event_set *es, void *arg) diff --git a/src/openvpn/fdmisc.c b/src/openvpn/fdmisc.c index b8d9334..2c6525b 100644 --- a/src/openvpn/fdmisc.c +++ b/src/openvpn/fdmisc.c @@ -41,7 +41,7 @@ { return false; } -#else /* ifdef _WIN32 */ +#else /* ifdef _WIN32 */ if (fcntl(fd, F_SETFL, O_NONBLOCK) < 0) { return false; diff --git a/src/openvpn/fdmisc.h b/src/openvpn/fdmisc.h index de0007a..4c0ab65 100644 --- a/src/openvpn/fdmisc.h +++ b/src/openvpn/fdmisc.h @@ -45,4 +45,4 @@ } #undef FD_SET /* prevent direct use of FD_SET() */ -#endif /* FD_MISC_H */ +#endif /* FD_MISC_H */ diff --git a/src/openvpn/forward.c b/src/openvpn/forward.c index d750ebf..75ca9d5 100644 --- a/src/openvpn/forward.c +++ b/src/openvpn/forward.c @@ -58,14 +58,11 @@ { struct buffer out =3D alloc_buf_gc(64, gc); - buf_printf(&out, "I/O WAIT %s|%s| %s", - tun_stat(c->c1.tuntap, EVENT_READ, gc), - tun_stat(c->c1.tuntap, EVENT_WRITE, gc), - tv_string(&c->c2.timeval, gc)); + buf_printf(&out, "I/O WAIT %s|%s| %s", tun_stat(c->c1.tuntap, EVENT_RE= AD, gc), + tun_stat(c->c1.tuntap, EVENT_WRITE, gc), tv_string(&c->c2.t= imeval, gc)); for (int i =3D 0; i < c->c1.link_sockets_num; i++) { - buf_printf(&out, "\n %s|%s", - socket_stat(c->c2.link_sockets[i], EVENT_READ, gc), + buf_printf(&out, "\n %s|%s", socket_stat(c->c2.link_sockets[i], EV= ENT_READ, gc), socket_stat(c->c2.link_sockets[i], EVENT_WRITE, gc)); } return BSTR(&out); @@ -127,7 +124,7 @@ static inline void context_immediate_reschedule(struct context *c) { - c->c2.timeval.tv_sec =3D 0; /* ZERO-TIMEOUT */ + c->c2.timeval.tv_sec =3D 0; /* ZERO-TIMEOUT */ c->c2.timeval.tv_usec =3D 0; } @@ -185,9 +182,8 @@ if (interval_test(&c->c2.tmp_int)) { - const int tmp_status =3D tls_multi_process - (c->c2.tls_multi, &c->c2.to_link, &c->c= 2.to_link_addr, - get_link_socket_info(c), &wakeup); + const int tmp_status =3D tls_multi_process( + c->c2.tls_multi, &c->c2.to_link, &c->c2.to_link_addr, get_link= _socket_info(c), &wakeup); if (tmp_status =3D=3D TLSMP_RECONNECT) { @@ -345,12 +341,7 @@ #ifdef ENABLE_MANAGEMENT if (management) { - management_set_state(management, - OPENVPN_STATE_GET_CONFIG, - NULL, - NULL, - NULL, - NULL, + management_set_state(management, OPENVPN_STATE_GET_CONFIG,= NULL, NULL, NULL, NULL, NULL); } #endif @@ -377,8 +368,7 @@ } bool -send_control_channel_string_dowork(struct tls_session *session, - const char *str, int msglevel) +send_control_channel_string_dowork(struct tls_session *session, const char= *str, int msglevel) { struct gc_arena gc =3D gc_new(); bool stat; @@ -387,12 +377,11 @@ struct key_state *ks =3D &session->key[KS_PRIMARY]; /* buffered cleartext write onto TLS control channel */ - stat =3D tls_send_payload(ks, (uint8_t *) str, strlen(str) + 1); + stat =3D tls_send_payload(ks, (uint8_t *)str, strlen(str) + 1); msg(msglevel, "SENT CONTROL [%s]: '%s' (status=3D%d)", - session->common_name ? session->common_name : "UNDEF", - sanitize_control_message(str, &gc), - (int) stat); + session->common_name ? session->common_name : "UNDEF", sanitize_co= ntrol_message(str, &gc), + (int)stat); gc_free(&gc); return stat; @@ -425,8 +414,8 @@ static void check_add_routes_action(struct context *c, const bool errors) { - bool route_status =3D do_route(&c->options, c->c1.route_list, c->c1.ro= ute_ipv6_list, - c->c1.tuntap, c->plugins, c->c2.es, &c->n= et_ctx); + bool route_status =3D do_route(&c->options, c->c1.route_list, c->c1.ro= ute_ipv6_list, c->c1.tuntap, + c->plugins, c->c2.es, &c->net_ctx); int flags =3D (errors ? ISC_ERRORS : 0); flags |=3D (!route_status ? ISC_ROUTE_ERRORS : 0); @@ -458,8 +447,8 @@ register_signal(c->sig, SIGHUP, "ip-fail"); c->persist.restart_sleep_seconds =3D 10; #ifdef _WIN32 - show_routes(M_INFO|M_NOPREFIX); - show_adapters(M_INFO|M_NOPREFIX); + show_routes(M_INFO | M_NOPREFIX); + show_adapters(M_INFO | M_NOPREFIX); #endif } } @@ -602,7 +591,8 @@ * Buffer reallocation, for use with null encryption. */ static inline void -buffer_turnover(const uint8_t *orig_buf, struct buffer *dest_stub, struct = buffer *src_stub, struct buffer *storage) +buffer_turnover(const uint8_t *orig_buf, struct buffer *dest_stub, struct = buffer *src_stub, + struct buffer *storage) { if (orig_buf =3D=3D src_stub->data && src_stub->data !=3D storage->dat= a) { @@ -630,7 +620,7 @@ if (dco_enabled(&c->options)) { msg(M_WARN, "Attempting to send data packet while data channel off= load is in use. " - "Dropping packet"); + "Dropping packet"); c->c2.buf.len =3D 0; } @@ -650,7 +640,8 @@ /* Compress the packet. */ if (c->c2.comp_context) { - (*c->c2.comp_context->alg.compress)(&c->c2.buf, b->compress_bu= f, c->c2.comp_context, &c->c2.frame); + (*c->c2.comp_context->alg.compress)(&c->c2.buf, b->compress_bu= f, c->c2.comp_context, + &c->c2.frame); } #endif #ifdef ENABLE_FRAGMENT @@ -697,8 +688,7 @@ /* * Get the address we will be sending the packet to. */ - link_socket_get_outgoing_addr(&c->c2.buf, get_link_socket_info(c), - &c->c2.to_link_addr); + link_socket_get_outgoing_addr(&c->c2.buf, get_link_socket_info(c), &c-= >c2.to_link_addr); /* if null encryption, copy result to read_tun_buf */ buffer_turnover(orig_buf, &c->c2.to_link, &c->c2.buf, &b->read_tun_buf= ); @@ -711,8 +701,7 @@ check_session_timeout(struct context *c) { if (c->options.session_timeout - && event_timeout_trigger(&c->c2.session_interval, &c->c2.timeval, - ETT_DEFAULT)) + && event_timeout_trigger(&c->c2.session_interval, &c->c2.timeval, = ETT_DEFAULT)) { msg(M_INFO, "Session timeout, exiting"); register_signal(c->sig, SIGTERM, "session-timeout"); @@ -726,7 +715,7 @@ process_coarse_timers(struct context *c) { /* flush current packet-id to file once per 60 - * seconds if --replay-persist was specified */ + * seconds if --replay-persist was specified */ if (packet_id_persist_enabled(&c->c1.pid_persist) && event_timeout_trigger(&c->c2.packet_id_persist_interval, &c->c2= .timeval, ETT_DEFAULT)) { @@ -849,7 +838,8 @@ process_coarse_timers(c); c->c2.coarse_timer_wakeup =3D now + c->c2.timeval.tv_sec; - dmsg(D_INTERVAL, "TIMER: coarse timer wakeup %" PRIi64 " seconds", (in= t64_t)c->c2.timeval.tv_sec); + dmsg(D_INTERVAL, "TIMER: coarse timer wakeup %" PRIi64 " seconds", + (int64_t)c->c2.timeval.tv_sec); /* Is the coarse timeout NOT the earliest one? */ if (c->c2.timeval.tv_sec > save.tv_sec) @@ -863,10 +853,10 @@ { const int update_interval =3D 10; /* seconds */ c->c2.update_timeout_random_component =3D now + update_interval; - c->c2.timeout_random_component.tv_usec =3D (time_t) get_random() & 0x0= 003FFFF; + c->c2.timeout_random_component.tv_usec =3D (time_t)get_random() & 0x00= 03FFFF; c->c2.timeout_random_component.tv_sec =3D 0; - dmsg(D_INTERVAL, "RANDOM USEC=3D%ld", (long) c->c2.timeout_random_comp= onent.tv_usec); + dmsg(D_INTERVAL, "RANDOM USEC=3D%ld", (long)c->c2.timeout_random_compo= nent.tv_usec); } static inline void @@ -897,10 +887,8 @@ } static inline void -socks_preprocess_outgoing_link(struct context *c, - struct link_socket *sock, - struct link_socket_actual **to_addr, - int *size_delta) +socks_preprocess_outgoing_link(struct context *c, struct link_socket *sock, + struct link_socket_actual **to_addr, int *s= ize_delta) { if (sock->socks_proxy && sock->info.proto =3D=3D PROTO_UDP) { @@ -911,9 +899,7 @@ /* undo effect of socks_preprocess_outgoing_link */ static inline void -link_socket_write_post_size_adjust(int *size, - int size_delta, - struct buffer *buf) +link_socket_write_post_size_adjust(int *size, int size_delta, struct buffe= r *buf) { if (size_delta > 0 && *size > size_delta) { @@ -945,9 +931,7 @@ c->c2.buf =3D c->c2.buffers->read_link_buf; ASSERT(buf_init(&c->c2.buf, c->c2.frame.buf.headroom)); - status =3D link_socket_read(sock, - &c->c2.buf, - &c->c2.from); + status =3D link_socket_read(sock, &c->c2.buf, &c->c2.from); if (socket_connection_reset(sock, status)) { @@ -965,12 +949,14 @@ /* received a disconnect from a connection-oriented protocol */ if (event_timeout_defined(&c->c2.explicit_exit_notification_in= terval)) { - msg(D_STREAM_ERRORS, "Connection reset during exit notific= ation period, ignoring [%d]", status); + msg(D_STREAM_ERRORS, + "Connection reset during exit notification period, ign= oring [%d]", status); management_sleep(1); } else { - register_signal(c->sig, SIGUSR1, "connection-reset"); /* S= OFT-SIGUSR1 -- TCP connection reset */ + register_signal(c->sig, SIGUSR1, + "connection-reset"); /* SOFT-SIGUSR1 -- TC= P connection reset */ msg(D_STREAM_ERRORS, "Connection reset, restarting [%d]", = status); } } @@ -1016,7 +1002,8 @@ if (management) { management_bytes_client(management, c->c2.buf.len, 0); - management_bytes_server(management, &c->c2.link_read_bytes, &c= ->c2.link_write_bytes, &c->c2.mda_context); + management_bytes_server(management, &c->c2.link_read_bytes, &c= ->c2.link_write_bytes, + &c->c2.mda_context); } #endif } @@ -1044,11 +1031,8 @@ fprintf(stderr, "R"); } #endif - msg(D_LINK_RW, "%s READ [%d] from %s: %s", - proto2ascii(lsi->proto, lsi->af, true), - BLEN(&c->c2.buf), - print_link_socket_actual(&c->c2.from, &gc), - PROTO_DUMP(&c->c2.buf, &gc)); + msg(D_LINK_RW, "%s READ [%d] from %s: %s", proto2ascii(lsi->proto, lsi= ->af, true), + BLEN(&c->c2.buf), print_link_socket_actual(&c->c2.from, &gc), PROT= O_DUMP(&c->c2.buf, &gc)); /* * Good, non-zero length packet received. @@ -1080,9 +1064,8 @@ */ if ((opcode =3D=3D P_DATA_V1) && dco_enabled(&c->options)) { - msg(D_LINK_ERRORS, - "Data Channel Offload doesn't support DATA_V1 packets.= " - "Upgrade your server to 2.4.5 or newer."); + msg(D_LINK_ERRORS, "Data Channel Offload doesn't support D= ATA_V1 packets. " + "Upgrade your server to 2.4.5 or newer.= "); c->c2.buf.len =3D 0; } @@ -1096,8 +1079,7 @@ * will load crypto_options with the correct encryption key * and return false. */ - if (tls_pre_decrypt(c->c2.tls_multi, &c->c2.from, &c->c2.buf, = &co, - floated, &ad_start)) + if (tls_pre_decrypt(c->c2.tls_multi, &c->c2.from, &c->c2.buf, = &co, floated, &ad_start)) { interval_action(&c->c2.tmp_int); @@ -1124,15 +1106,16 @@ } /* authenticate and decrypt the incoming packet */ - decrypt_status =3D openvpn_decrypt(&c->c2.buf, c->c2.buffers->decr= ypt_buf, - co, &c->c2.frame, ad_start); + decrypt_status =3D + openvpn_decrypt(&c->c2.buf, c->c2.buffers->decrypt_buf, co, &c= ->c2.frame, ad_start); if (!decrypt_status /* on the instance context we have only one socket, so just ch= eck the first one */ && link_socket_connection_oriented(c->c2.link_sockets[0])) { /* decryption errors are fatal in TCP mode */ - register_signal(c->sig, SIGUSR1, "decryption-error"); /* SOFT-= SIGUSR1 -- decryption error in TCP mode */ + register_signal(c->sig, SIGUSR1, + "decryption-error"); /* SOFT-SIGUSR1 -- decryp= tion error in TCP mode */ msg(D_STREAM_ERRORS, "Fatal decryption error (process_incoming= _link), restarting"); } } @@ -1146,7 +1129,8 @@ } void -process_incoming_link_part2(struct context *c, struct link_socket_info *ls= i, const uint8_t *orig_buf) +process_incoming_link_part2(struct context *c, struct link_socket_info *ls= i, + const uint8_t *orig_buf) { if (c->c2.buf.len > 0) { @@ -1161,17 +1145,15 @@ /* decompress the incoming packet */ if (c->c2.comp_context) { - (*c->c2.comp_context->alg.decompress)(&c->c2.buf, c->c2.buffer= s->decompress_buf, c->c2.comp_context, &c->c2.frame); + (*c->c2.comp_context->alg.decompress)(&c->c2.buf, c->c2.buffer= s->decompress_buf, + c->c2.comp_context, &c->= c2.frame); } #endif #ifdef PACKET_TRUNCATION_CHECK /* if (c->c2.buf.len > 1) --c->c2.buf.len; */ - ipv4_packet_size_verify(BPTR(&c->c2.buf), - BLEN(&c->c2.buf), - TUNNEL_TYPE(c->c1.tuntap), - "POST_DECRYPT", - &c->c2.n_trunc_post_decrypt); + ipv4_packet_size_verify(BPTR(&c->c2.buf), BLEN(&c->c2.buf), TUNNEL= _TYPE(c->c1.tuntap), + "POST_DECRYPT", &c->c2.n_trunc_post_decryp= t); #endif /* @@ -1198,7 +1180,8 @@ if (c->c2.buf.len > 0) { c->c2.link_read_bytes_auth +=3D c->c2.buf.len; - c->c2.max_recv_size_local =3D max_int(c->c2.original_recv_size= , c->c2.max_recv_size_local); + c->c2.max_recv_size_local =3D + max_int(c->c2.original_recv_size, c->c2.max_recv_size_loca= l); } /* Did we just receive an openvpn ping packet? */ @@ -1243,8 +1226,7 @@ } void -extract_dco_float_peer_addr(const sa_family_t socket_family, - struct openvpn_sockaddr *out_osaddr, +extract_dco_float_peer_addr(const sa_family_t socket_family, struct openvp= n_sockaddr *out_osaddr, const struct sockaddr *float_sa) { if (float_sa->sa_family =3D=3D AF_INET) @@ -1262,8 +1244,8 @@ memset(&out_osaddr->addr.in6.sin6_addr.s6_addr, 0, 10); out_osaddr->addr.in6.sin6_addr.s6_addr[10] =3D 0xff; out_osaddr->addr.in6.sin6_addr.s6_addr[11] =3D 0xff; - memcpy(&out_osaddr->addr.in6.sin6_addr.s6_addr[12], - &float4->sin_addr.s_addr, sizeof(in_addr_t)); + memcpy(&out_osaddr->addr.in6.sin6_addr.s6_addr[12], &float4->s= in_addr.s_addr, + sizeof(in_addr_t)); } else { @@ -1296,9 +1278,10 @@ * ourselves in the foot and removing the just established session */ if (dco->dco_message_peer_id !=3D c->c2.tls_multi->dco_peer_id) { - msg(D_DCO_DEBUG, "%s: received message for mismatching peer-id %d,= " - "expected %d", __func__, dco->dco_message_peer_id, - c->c2.tls_multi->dco_peer_id); + msg(D_DCO_DEBUG, + "%s: received message for mismatching peer-id %d, " + "expected %d", + __func__, dco->dco_message_peer_id, c->c2.tls_multi->dco_peer_= id); return; } @@ -1309,16 +1292,18 @@ c->c2.tls_multi->dco_peer_id =3D -1; if (dco->dco_del_peer_reason =3D=3D OVPN_DEL_PEER_REASON_EXPIR= ED) { - msg(D_DCO_DEBUG, "%s: received peer expired notification o= f for peer-id " - "%d", __func__, dco->dco_message_peer_id); + msg(D_DCO_DEBUG, + "%s: received peer expired notification of for peer-id= " + "%d", + __func__, dco->dco_message_peer_id); trigger_ping_timeout_signal(c); return; } break; case OVPN_CMD_SWAP_KEYS: - msg(D_DCO_DEBUG, "%s: received key rotation notification for p= eer-id %d", - __func__, dco->dco_message_peer_id); + msg(D_DCO_DEBUG, "%s: received key rotation notification for p= eer-id %d", __func__, + dco->dco_message_peer_id); tls_session_soft_reset(c->c2.tls_multi); break; @@ -1358,7 +1343,8 @@ ASSERT(buf_safe(&c->c2.buf, c->c2.frame.buf.payload_size)); if (c->c1.tuntap->backend_driver =3D=3D DRIVER_AFUNIX) { - c->c2.buf.len =3D read_tun_afunix(c->c1.tuntap, BPTR(&c->c2.buf), = c->c2.frame.buf.payload_size); + c->c2.buf.len =3D + read_tun_afunix(c->c1.tuntap, BPTR(&c->c2.buf), c->c2.frame.bu= f.payload_size); } else { @@ -1367,11 +1353,8 @@ #endif /* ifdef _WIN32 */ #ifdef PACKET_TRUNCATION_CHECK - ipv4_packet_size_verify(BPTR(&c->c2.buf), - BLEN(&c->c2.buf), - TUNNEL_TYPE(c->c1.tuntap), - "READ_TUN", - &c->c2.n_trunc_tun_read); + ipv4_packet_size_verify(BPTR(&c->c2.buf), BLEN(&c->c2.buf), TUNNEL_TYP= E(c->c1.tuntap), + "READ_TUN", &c->c2.n_trunc_tun_read); #endif /* Was TUN/TAP interface stopped? */ @@ -1426,7 +1409,7 @@ if (proto_ver =3D=3D 4) { /* make sure we got whole IP header */ - if (BLEN(buf) < ((int) sizeof(struct openvpn_iphdr) + ip_hdr_offse= t)) + if (BLEN(buf) < ((int)sizeof(struct openvpn_iphdr) + ip_hdr_offset= )) { return; } @@ -1437,7 +1420,7 @@ return; } - struct openvpn_iphdr *pip =3D (struct openvpn_iphdr *) (BPTR(buf) = + ip_hdr_offset); + struct openvpn_iphdr *pip =3D (struct openvpn_iphdr *)(BPTR(buf) += ip_hdr_offset); /* drop packets with same dest addr as gateway */ if (memcmp(&tun_sa.addr.in4.sin_addr.s_addr, &pip->daddr, sizeof(p= ip->daddr)) =3D=3D 0) @@ -1448,7 +1431,7 @@ else if (proto_ver =3D=3D 6) { /* make sure we got whole IPv6 header */ - if (BLEN(buf) < ((int) sizeof(struct openvpn_ipv6hdr) + ip_hdr_off= set)) + if (BLEN(buf) < ((int)sizeof(struct openvpn_ipv6hdr) + ip_hdr_offs= et)) { return; } @@ -1459,7 +1442,7 @@ return; } - struct openvpn_ipv6hdr *pip6 =3D (struct openvpn_ipv6hdr *) (BPTR(= buf) + ip_hdr_offset); + struct openvpn_ipv6hdr *pip6 =3D (struct openvpn_ipv6hdr *)(BPTR(b= uf) + ip_hdr_offset); /* drop packets with same dest addr as gateway */ if (OPENVPN_IN6_ARE_ADDR_EQUAL(&tun_sa.addr.in6.sin6_addr, &pip6->= daddr)) @@ -1517,19 +1500,15 @@ * The --passtos and --mssfix options require * us to examine the IP header (IPv4 or IPv6). */ - unsigned int flags =3D PIPV4_PASSTOS | PIP_MSSFIX | PIPV4_CLIENT_N= AT - | PIPV6_ICMP_NOHOST_CLIENT; + unsigned int flags =3D + PIPV4_PASSTOS | PIP_MSSFIX | PIPV4_CLIENT_NAT | PIPV6_ICMP_NOH= OST_CLIENT; process_ip_header(c, flags, &c->c2.buf, out_sock); #ifdef PACKET_TRUNCATION_CHECK /* if (c->c2.buf.len > 1) --c->c2.buf.len; */ - ipv4_packet_size_verify(BPTR(&c->c2.buf), - BLEN(&c->c2.buf), - TUNNEL_TYPE(c->c1.tuntap), - "PRE_ENCRYPT", - &c->c2.n_trunc_pre_encrypt); + ipv4_packet_size_verify(BPTR(&c->c2.buf), BLEN(&c->c2.buf), TUNNEL= _TYPE(c->c1.tuntap), + "PRE_ENCRYPT", &c->c2.n_trunc_pre_encrypt); #endif - } if (c->c2.buf.len > 0) { @@ -1605,8 +1584,7 @@ icmp6out.icmp6_type =3D OPENVPN_ICMP6_DESTINATION_UNREACHABLE; icmp6out.icmp6_code =3D OPENVPN_ICMP6_DU_NOROUTE; - int icmpheader_len =3D sizeof(struct openvpn_ipv6hdr) - + sizeof(struct openvpn_icmp6hdr); + int icmpheader_len =3D sizeof(struct openvpn_ipv6hdr) + sizeof(struct = openvpn_icmp6hdr); int totalheader_len =3D icmpheader_len; if (TUNNEL_TYPE(c->c1.tuntap) =3D=3D DEV_TYPE_TAP) @@ -1619,8 +1597,7 @@ * frame should be <=3D 1280 and have as much as possible of the origi= nal * packet */ - int max_payload_size =3D min_int(MAX_ICMPV6LEN, - c->c2.frame.tun_mtu - icmpheader_len); + int max_payload_size =3D min_int(MAX_ICMPV6LEN, c->c2.frame.tun_mtu - = icmpheader_len); int payload_len =3D min_int(max_payload_size, BLEN(&inputipbuf)); pip6out.payload_len =3D htons(sizeof(struct openvpn_icmp6hdr) + payloa= d_len); @@ -1648,10 +1625,10 @@ /* Calculate checksum over the packet and write to header */ - uint16_t new_csum =3D ip_checksum(AF_INET6, BPTR(outbuf), BLEN(outbuf), - (const uint8_t *)&pip6out.saddr, - (uint8_t *)&pip6out.daddr, OPENVPN_IPP= ROTO_ICMPV6); - ((struct openvpn_icmp6hdr *) BPTR(outbuf))->icmp6_cksum =3D htons(new_= csum); + uint16_t new_csum =3D + ip_checksum(AF_INET6, BPTR(outbuf), BLEN(outbuf), (const uint8_t *= )&pip6out.saddr, + (uint8_t *)&pip6out.daddr, OPENVPN_IPPROTO_ICMPV6); + ((struct openvpn_icmp6hdr *)BPTR(outbuf))->icmp6_cksum =3D htons(new_c= sum); /* IPv6 Header */ @@ -1667,7 +1644,7 @@ return; } - const struct openvpn_ethhdr *orig_ethhdr =3D (struct openvpn_ethhd= r *) BPTR(buf); + const struct openvpn_ethhdr *orig_ethhdr =3D (struct openvpn_ethhd= r *)BPTR(buf); /* Copy frametype and reverse source/destination for the response = */ struct openvpn_ethhdr ethhdr; @@ -1748,15 +1725,13 @@ { mss_fixup_ipv6(&ipbuf, c->c2.frame.mss_fix); } - if (!(flags & PIP_OUTGOING) && (flags - &(PIPV6_ICMP_NOHOST_CLIENT | P= IPV6_ICMP_NOHOST_SERVER))) + if (!(flags & PIP_OUTGOING) + && (flags & (PIPV6_ICMP_NOHOST_CLIENT | PIPV6_ICMP_NOHOST_= SERVER))) { - ipv6_send_icmp_unreachable(c, buf, - (bool)(flags & PIPV6_ICMP_NOHOS= T_CLIENT)); + ipv6_send_icmp_unreachable(c, buf, (bool)(flags & PIPV6_IC= MP_NOHOST_CLIENT)); /* Drop the IPv6 packet */ buf->len =3D 0; } - } } } @@ -1793,10 +1768,9 @@ */ if (c->options.shaper) { - int overhead =3D datagram_overhead(c->c2.to_link_addr->des= t.addr.sa.sa_family, - sock->info.proto); - shaper_wrote_bytes(&c->c2.shaper, - BLEN(&c->c2.to_link) + overhead); + int overhead =3D + datagram_overhead(c->c2.to_link_addr->dest.addr.sa.sa_= family, sock->info.proto); + shaper_wrote_bytes(&c->c2.shaper, BLEN(&c->c2.to_link) + o= verhead); } /* @@ -1820,10 +1794,8 @@ } #endif msg(D_LINK_RW, "%s WRITE [%d] to %s: %s", - proto2ascii(sock->info.proto, sock->info.af, true), - BLEN(&c->c2.to_link), - print_link_socket_actual(c->c2.to_link_addr, &gc), - PROTO_DUMP(&c->c2.to_link, &gc)); + proto2ascii(sock->info.proto, sock->info.af, true), BLEN(&= c->c2.to_link), + print_link_socket_actual(c->c2.to_link_addr, &gc), PROTO_D= UMP(&c->c2.to_link, &gc)); /* Packet send complexified by possible Socks5 usage */ { @@ -1834,9 +1806,7 @@ socks_preprocess_outgoing_link(c, sock, &to_addr, &size_de= lta); /* Send packet */ - size =3D (int)link_socket_write(sock, - &c->c2.to_link, - to_addr); + size =3D (int)link_socket_write(sock, &c->c2.to_link, to_a= ddr); /* Undo effect of prepend */ link_socket_write_post_size_adjust(&size, size_delta, &c->= c2.to_link); @@ -1857,7 +1827,8 @@ if (management) { management_bytes_client(management, 0, size); - management_bytes_server(management, &c->c2.link_read_b= ytes, &c->c2.link_write_bytes, &c->c2.mda_context); + management_bytes_server(management, &c->c2.link_read_b= ytes, + &c->c2.link_write_bytes, &c->c= 2.mda_context); } #endif } @@ -1874,9 +1845,7 @@ { msg(D_LINK_ERRORS, "TCP/UDP packet was truncated/expanded on write to %s = (tried=3D%d,actual=3D%d)", - print_link_socket_actual(c->c2.to_link_addr, &gc), - BLEN(&c->c2.to_link), - size); + print_link_socket_actual(c->c2.to_link_addr, &gc), BLE= N(&c->c2.to_link), size); } } @@ -1895,7 +1864,8 @@ ENETUNREACH; #endif if (size < 0 && unreachable && c->c2.tls_multi - && !tls_initial_packet_received(c->c2.tls_multi) && c->options= .mode =3D=3D MODE_POINT_TO_POINT) + && !tls_initial_packet_received(c->c2.tls_multi) + && c->options.mode =3D=3D MODE_POINT_TO_POINT) { msg(M_INFO, "Network unreachable, restarting"); register_signal(c->sig, SIGUSR1, "network-unreachable"); @@ -1906,8 +1876,7 @@ if (c->c2.to_link.len > 0) { msg(D_LINK_ERRORS, "TCP/UDP packet too large on write to %s (t= ried=3D%d,max=3D%d)", - print_link_socket_actual(c->c2.to_link_addr, &gc), - c->c2.to_link.len, + print_link_socket_actual(c->c2.to_link_addr, &gc), c->c2.t= o_link.len, c->c2.frame.buf.payload_size); } } @@ -1940,8 +1909,8 @@ * The --mssfix option requires * us to examine the IP header (IPv4 or IPv6). */ - process_ip_header(c, PIP_MSSFIX|PIPV4_EXTRACT_DHCP_ROUTER|PIPV4_CLIENT= _NAT|PIP_OUTGOING, &c->c2.to_tun, - in_sock); + process_ip_header(c, PIP_MSSFIX | PIPV4_EXTRACT_DHCP_ROUTER | PIPV4_CL= IENT_NAT | PIP_OUTGOING, + &c->c2.to_tun, in_sock); if (c->c2.to_tun.len <=3D c->c2.frame.buf.payload_size) { @@ -1959,11 +1928,8 @@ dmsg(D_TUN_RW, "TUN WRITE [%d]", BLEN(&c->c2.to_tun)); #ifdef PACKET_TRUNCATION_CHECK - ipv4_packet_size_verify(BPTR(&c->c2.to_tun), - BLEN(&c->c2.to_tun), - TUNNEL_TYPE(c->c1.tuntap), - "WRITE_TUN", - &c->c2.n_trunc_tun_write); + ipv4_packet_size_verify(BPTR(&c->c2.to_tun), BLEN(&c->c2.to_tun), = TUNNEL_TYPE(c->c1.tuntap), + "WRITE_TUN", &c->c2.n_trunc_tun_write); #endif #ifdef _WIN32 @@ -1993,9 +1959,7 @@ { msg(D_LINK_ERRORS, "TUN/TAP packet was destructively fragmented on write = to %s (tried=3D%d,actual=3D%d)", - c->c1.tuntap->actual_name, - BLEN(&c->c2.to_tun), - size); + c->c1.tuntap->actual_name, BLEN(&c->c2.to_tun), size); } /* indicate activity regarding --inactive parameter */ @@ -2008,8 +1972,7 @@ * This should never happen, probably indicates some kind * of MTU mismatch. */ - msg(D_LINK_ERRORS, "tun packet too large on write (tried=3D%d,max= =3D%d)", - c->c2.to_tun.len, + msg(D_LINK_ERRORS, "tun packet too large on write (tried=3D%d,max= =3D%d)", c->c2.to_tun.len, c->c2.frame.buf.payload_size); } @@ -2085,9 +2048,8 @@ } static void -multi_io_process_flags(struct context *c, struct event_set *es, - const unsigned int flags, unsigned int *out_socket, - unsigned int *out_tuntap) +multi_io_process_flags(struct context *c, struct event_set *es, const unsi= gned int flags, + unsigned int *out_socket, unsigned int *out_tuntap) { unsigned int socket =3D 0; unsigned int tuntap =3D 0; @@ -2178,8 +2140,7 @@ */ for (int i =3D 0; i < c->c1.link_sockets_num; i++) { - socket_set(c->c2.link_sockets[i], es, socket, - &c->c2.link_sockets[i]->ev_arg, NULL); + socket_set(c->c2.link_sockets[i], es, socket, &c->c2.link_sockets[= i]->ev_arg, NULL); } tun_set(c->c1.tuntap, es, tuntap, (void *)tun_shift, NULL); @@ -2193,7 +2154,6 @@ { *out_tuntap =3D tuntap; } - } /* @@ -2244,15 +2204,16 @@ struct event_set_return esr[4]; /* These shifts all depend on EVENT_READ and EVENT_WRITE */ - static uintptr_t socket_shift =3D SOCKET_SHIFT; /* depends on SOCKET= _READ and SOCKET_WRITE */ + static uintptr_t socket_shift =3D SOCKET_SHIFT; /* depends on SOCKET_R= EAD and SOCKET_WRITE */ #ifdef ENABLE_MANAGEMENT - static uintptr_t management_shift =3D MANAGEMENT_SHIFT; /* depends on = MANAGEMENT_READ and MANAGEMENT_WRITE */ + static uintptr_t management_shift =3D + MANAGEMENT_SHIFT; /* depends on MANAGEMENT_READ and MANAGEMENT_WRI= TE */ #endif #ifdef ENABLE_ASYNC_PUSH static uintptr_t file_shift =3D FILE_SHIFT; #endif #if defined(TARGET_LINUX) || defined(TARGET_FREEBSD) - static uintptr_t dco_shift =3D DCO_SHIFT; /* Event from DCO linux k= ernel module */ + static uintptr_t dco_shift =3D DCO_SHIFT; /* Event from DCO linux kern= el module */ #endif /* @@ -2331,8 +2292,7 @@ if (ev_arg->type !=3D EVENT_ARG_LINK_SOCKET) { c->c2.event_set_status =3D ES_ERROR; - msg(D_LINK_ERRORS, - "io_work: non socket event delivered"); + msg(D_LINK_ERRORS, "io_work: non socket event = delivered"); return; } @@ -2375,7 +2335,7 @@ const unsigned int status =3D c->c2.event_set_status; #ifdef ENABLE_MANAGEMENT - if (status & (MANAGEMENT_READ|MANAGEMENT_WRITE)) + if (status & (MANAGEMENT_READ | MANAGEMENT_WRITE)) { ASSERT(management); management_io(management); diff --git a/src/openvpn/forward.h b/src/openvpn/forward.h index abb45c0..d564149 100644 --- a/src/openvpn/forward.h +++ b/src/openvpn/forward.h @@ -34,9 +34,9 @@ * file */ -#define TUN_OUT(c) (BLEN(&(c)->c2.to_tun) > 0) -#define LINK_OUT(c) (BLEN(&(c)->c2.to_link) > 0) -#define ANY_OUT(c) (TUN_OUT(c) || LINK_OUT(c)) +#define TUN_OUT(c) (BLEN(&(c)->c2.to_tun) > 0) +#define LINK_OUT(c) (BLEN(&(c)->c2.to_link) > 0) +#define ANY_OUT(c) (TUN_OUT(c) || LINK_OUT(c)) #ifdef ENABLE_FRAGMENT #define TO_LINK_FRAG(c) ((c)->c2.fragment && fragment_outgoing_defined((c)= ->c2.fragment)) @@ -44,31 +44,32 @@ #define TO_LINK_FRAG(c) (false) #endif -#define TO_LINK_DEF(c) (LINK_OUT(c) || TO_LINK_FRAG(c)) +#define TO_LINK_DEF(c) (LINK_OUT(c) || TO_LINK_FRAG(c)) #include "openvpn.h" #include "occ.h" #include "ping.h" #include "multi_io.h" -#define IOW_TO_TUN (1<<0) -#define IOW_TO_LINK (1<<1) -#define IOW_READ_TUN (1<<2) -#define IOW_READ_LINK (1<<3) -#define IOW_SHAPER (1<<4) -#define IOW_CHECK_RESIDUAL (1<<5) -#define IOW_FRAG (1<<6) -#define IOW_MBUF (1<<7) -#define IOW_READ_TUN_FORCE (1<<8) -#define IOW_WAIT_SIGNAL (1<<9) +#define IOW_TO_TUN (1 << 0) +#define IOW_TO_LINK (1 << 1) +#define IOW_READ_TUN (1 << 2) +#define IOW_READ_LINK (1 << 3) +#define IOW_SHAPER (1 << 4) +#define IOW_CHECK_RESIDUAL (1 << 5) +#define IOW_FRAG (1 << 6) +#define IOW_MBUF (1 << 7) +#define IOW_READ_TUN_FORCE (1 << 8) +#define IOW_WAIT_SIGNAL (1 << 9) -#define IOW_READ (IOW_READ_TUN|IOW_READ_LINK) +#define IOW_READ (IOW_READ_TUN | IOW_READ_LINK) extern counter_type link_read_bytes_global; extern counter_type link_write_bytes_global; -void get_io_flags_dowork_udp(struct context *c, struct multi_io *multi_io,= const unsigned int flags); +void get_io_flags_dowork_udp(struct context *c, struct multi_io *multi_io, + const unsigned int flags); void get_io_flags_udp(struct context *c, struct multi_io *multi_io, const = unsigned int flags); @@ -192,7 +193,8 @@ * @param orig_buf - Pointer to a buffer data. * */ -void process_incoming_link_part2(struct context *c, struct link_socket_inf= o *lsi, const uint8_t *orig_buf); +void process_incoming_link_part2(struct context *c, struct link_socket_inf= o *lsi, + const uint8_t *orig_buf); /** * Transfers \c float_sa data extracted from an incoming DCO @@ -204,10 +206,8 @@ * @param float_sa - The sockaddr struct containing the data received from= the * DCO notification */ -void -extract_dco_float_peer_addr(sa_family_t socket_family, - struct openvpn_sockaddr *out_osaddr, - const struct sockaddr *float_sa); +void extract_dco_float_peer_addr(sa_family_t socket_family, struct openvpn= _sockaddr *out_osaddr, + const struct sockaddr *float_sa); /** * Write a packet to the external network interface. @@ -285,8 +285,7 @@ * @param str - The message to be sent * @param msglevel - Message level to use for logging */ -bool -send_control_channel_string(struct context *c, const char *str, int msglev= el); +bool send_control_channel_string(struct context *c, const char *str, int m= sglevel); /* * Send a string to remote over the TLS control channel. @@ -304,9 +303,7 @@ * @param msglevel - Message level to use for logging */ -bool -send_control_channel_string_dowork(struct tls_session *session, - const char *str, int msglevel); +bool send_control_channel_string_dowork(struct tls_session *session, const= char *str, int msglevel); /** @@ -317,13 +314,13 @@ */ void reschedule_multi_process(struct context *c); -#define PIPV4_PASSTOS (1<<0) -#define PIP_MSSFIX (1<<1) /* v4 and v6 */ -#define PIP_OUTGOING (1<<2) -#define PIPV4_EXTRACT_DHCP_ROUTER (1<<3) -#define PIPV4_CLIENT_NAT (1<<4) -#define PIPV6_ICMP_NOHOST_CLIENT (1<<5) -#define PIPV6_ICMP_NOHOST_SERVER (1<<6) +#define PIPV4_PASSTOS (1 << 0) +#define PIP_MSSFIX (1 << 1) /* v4 and v6 */ +#define PIP_OUTGOING (1 << 2) +#define PIPV4_EXTRACT_DHCP_ROUTER (1 << 3) +#define PIPV4_CLIENT_NAT (1 << 4) +#define PIPV6_ICMP_NOHOST_CLIENT (1 << 5) +#define PIPV6_ICMP_NOHOST_SERVER (1 << 6) void process_ip_header(struct context *c, unsigned int flags, struct buffe= r *buf, @@ -365,7 +362,7 @@ static inline unsigned int p2p_iow_flags(const struct context *c) { - unsigned int flags =3D (IOW_SHAPER|IOW_CHECK_RESIDUAL|IOW_FRAG|IOW_REA= D|IOW_WAIT_SIGNAL); + unsigned int flags =3D (IOW_SHAPER | IOW_CHECK_RESIDUAL | IOW_FRAG | I= OW_READ | IOW_WAIT_SIGNAL); if (c->c2.to_link.len > 0) { flags |=3D IOW_TO_LINK; @@ -384,8 +381,8 @@ static inline void io_wait(struct context *c, const unsigned int flags) { - if (proto_is_dgram(c->c2.link_sockets[0]->info.proto) - && c->c2.fast_io && (flags & (IOW_TO_TUN|IOW_TO_LINK|IOW_MBUF))) + if (proto_is_dgram(c->c2.link_sockets[0]->info.proto) && c->c2.fast_io + && (flags & (IOW_TO_TUN | IOW_TO_LINK | IOW_MBUF))) { /* fast path -- only for TUN/TAP/UDP writes */ unsigned int ret =3D 0; @@ -393,7 +390,7 @@ { ret |=3D TUN_WRITE; } - if (flags & (IOW_TO_LINK|IOW_MBUF)) + if (flags & (IOW_TO_LINK | IOW_MBUF)) { ret |=3D SOCKET_WRITE; } diff --git a/src/openvpn/fragment.c b/src/openvpn/fragment.c index a7fbe09..7fc42e5 100644 --- a/src/openvpn/fragment.c +++ b/src/openvpn/fragment.c @@ -34,7 +34,11 @@ #include "integer.h" #include "memdbg.h" -#define FRAG_ERR(s) { errmsg =3D s; goto error; } +#define FRAG_ERR(s) \ + { \ + errmsg =3D s; \ + goto error; \ + } static void fragment_list_buf_init(struct fragment_list *list, const struct frame *fra= me) @@ -132,8 +136,7 @@ * If a fragment fully completes the datagram, return the datagram. */ void -fragment_incoming(struct fragment_master *f, struct buffer *buf, - const struct frame *frame) +fragment_incoming(struct fragment_master *f, struct buffer *buf, const str= uct frame *frame) { const char *errmsg =3D NULL; fragment_header_type flags =3D 0; @@ -164,11 +167,8 @@ /* handle the fragment type */ if (frag_type =3D=3D FRAG_WHOLE) { - dmsg(D_FRAG_DEBUG, - "FRAG_IN buf->len=3D%d type=3DFRAG_WHOLE flags=3D" - fragment_header_format, - buf->len, - flags); + dmsg(D_FRAG_DEBUG, "FRAG_IN buf->len=3D%d type=3DFRAG_WHOLE fl= ags=3D" fragment_header_format, + buf->len, flags); if (flags & (FRAG_SEQ_ID_MASK | FRAG_ID_MASK)) { @@ -179,22 +179,18 @@ { const int seq_id =3D ((flags >> FRAG_SEQ_ID_SHIFT) & FRAG_SEQ_= ID_MASK); const int n =3D ((flags >> FRAG_ID_SHIFT) & FRAG_ID_MASK); - const int size =3D ((frag_type =3D=3D FRAG_YES_LAST) - ? (int)(((flags >> FRAG_SIZE_SHIFT) & FRAG_S= IZE_MASK) << FRAG_SIZE_ROUND_SHIFT) - : buf->len); + const int size =3D + ((frag_type =3D=3D FRAG_YES_LAST) + ? (int)(((flags >> FRAG_SIZE_SHIFT) & FRAG_SIZE_MASK)= << FRAG_SIZE_ROUND_SHIFT) + : buf->len); /* get the appropriate fragment buffer based on received seq_i= d */ struct fragment *frag =3D fragment_list_get_buf(&f->incoming, = seq_id); - dmsg(D_FRAG_DEBUG, - "FRAG_IN len=3D%d type=3D%d seq_id=3D%d frag_id=3D%d size= =3D%d flags=3D" - fragment_header_format, - buf->len, - frag_type, - seq_id, - n, - size, - flags); + dmsg( + D_FRAG_DEBUG, + "FRAG_IN len=3D%d type=3D%d seq_id=3D%d frag_id=3D%d size= =3D%d flags=3D" fragment_header_format, + buf->len, frag_type, seq_id, n, size, flags); /* make sure that size is an even multiple of 1<len, type, seq_id, frag_id, frag_size, flags); + dmsg( + D_FRAG_DEBUG, + "FRAG_OUT len=3D%d type=3D%d seq_id=3D%d frag_id=3D%d frag_siz= e=3D%d flags=3D" fragment_header_format, + buf->len, type, seq_id, frag_id, frag_size, flags); } else { flags |=3D (((frag_size >> FRAG_SIZE_ROUND_SHIFT) & FRAG_SIZE_MASK= ) << FRAG_SIZE_SHIFT); - dmsg(D_FRAG_DEBUG, - "FRAG_OUT len=3D%d type=3D%d seq_id=3D%d frag_id=3D%d frag_si= ze=3D%d flags=3D" - fragment_header_format, - buf->len, type, seq_id, frag_id, frag_size, flags); + dmsg( + D_FRAG_DEBUG, + "FRAG_OUT len=3D%d type=3D%d seq_id=3D%d frag_id=3D%d frag_siz= e=3D%d flags=3D" fragment_header_format, + buf->len, type, seq_id, frag_id, frag_size, flags); } flags =3D hton_fragment_header_type(flags); @@ -306,8 +298,9 @@ if (div > 0 && mod > 0 && mod < mfs_aligned * 3 / 4) { - return min_int(mfs_aligned, (max_frag_size - ((max_frag_size - mod= ) / (div + 1)) - + FRAG_SIZE_ROUND_MASK) & ~FRAG_SIZE_= ROUND_MASK); + return min_int(mfs_aligned, + (max_frag_size - ((max_frag_size - mod) / (div + 1)= ) + FRAG_SIZE_ROUND_MASK) + & ~FRAG_SIZE_ROUND_MASK); } else { @@ -317,8 +310,7 @@ /* process an outgoing datagram, possibly breaking it up into fragments */ void -fragment_outgoing(struct fragment_master *f, struct buffer *buf, - const struct frame *frame) +fragment_outgoing(struct fragment_master *f, struct buffer *buf, const str= uct frame *frame) { const char *errmsg =3D NULL; if (buf->len > 0) @@ -326,8 +318,8 @@ /* The outgoing buffer should be empty so we can put new data in i= t */ if (f->outgoing.len) { - msg(D_FRAG_ERRORS, "FRAG: outgoing buffer is not empty, len=3D= [%d,%d]", - buf->len, f->outgoing.len); + msg(D_FRAG_ERRORS, "FRAG: outgoing buffer is not empty, len=3D= [%d,%d]", buf->len, + f->outgoing.len); } if (buf->len > frame->max_fragment_size) /* should we fragment? */ { @@ -351,11 +343,7 @@ /* * Send the datagram whole. */ - fragment_prepend_flags(buf, - FRAG_WHOLE, - 0, - 0, - 0); + fragment_prepend_flags(buf, FRAG_WHOLE, 0, 0, 0); } } return; @@ -363,8 +351,8 @@ error: if (errmsg) { - msg(D_FRAG_ERRORS, "FRAG_OUT error, len=3D%d frag_size=3D%d MAX_FR= AGS=3D%d: %s", - buf->len, f->outgoing_frag_size, MAX_FRAGS, errmsg); + msg(D_FRAG_ERRORS, "FRAG_OUT error, len=3D%d frag_size=3D%d MAX_FR= AGS=3D%d: %s", buf->len, + f->outgoing_frag_size, MAX_FRAGS, errmsg); } buf->len =3D 0; return; @@ -372,8 +360,7 @@ /* return true (and set buf) if we have an outgoing fragment which is read= y to send */ bool -fragment_ready_to_send(struct fragment_master *f, struct buffer *buf, - const struct frame *frame) +fragment_ready_to_send(struct fragment_master *f, struct buffer *buf, cons= t struct frame *frame) { if (fragment_outgoing_defined(f)) { @@ -392,13 +379,12 @@ ASSERT(buf_copy_n(buf, &f->outgoing, size)); /* fragment flags differ based on whether or not we are sending th= e last fragment */ - fragment_prepend_flags(buf, - last ? FRAG_YES_LAST : FRAG_YES_NOTLAST, - f->outgoing_seq_id, - f->outgoing_frag_id++, - f->outgoing_frag_size); + fragment_prepend_flags(buf, last ? FRAG_YES_LAST : FRAG_YES_NOTLAS= T, f->outgoing_seq_id, + f->outgoing_frag_id++, f->outgoing_frag_siz= e); - ASSERT(!last || !f->outgoing.len); /* outgoing buffer length shoul= d be zero after last fragment sent */ + ASSERT(!last + || !f->outgoing + .len); /* outgoing buffer length should be zero aft= er last fragment sent */ return true; } diff --git a/src/openvpn/fragment.h b/src/openvpn/fragment.h index 6120079..9719bf5 100644 --- a/src/openvpn/fragment.h +++ b/src/openvpn/fragment.h @@ -45,15 +45,15 @@ #include "error.h" -#define N_FRAG_BUF 25 +#define N_FRAG_BUF 25 /**< Number of packet buffers for * reassembling incoming fragmented * packets. */ -#define FRAG_TTL_SEC 10 +#define FRAG_TTL_SEC 10 /**< Time-to-live in seconds for a %fragment. */ -#define FRAG_WAKEUP_INTERVAL 5 +#define FRAG_WAKEUP_INTERVAL 5 /**< Interval in seconds between calls to * wakeup code. */ @@ -61,15 +61,16 @@ /** * Structure for reassembling one incoming fragmented packet. */ -struct fragment { - bool defined; /**< Whether reassembly is currently - * taking place in this structure. */ +struct fragment +{ + bool defined; /**< Whether reassembly is currently + * taking place in this structure. */ - int max_frag_size; /**< Maximum size of each %fragment. */ + int max_frag_size; /**< Maximum size of each %fragment. */ #define FRAG_MAP_MASK 0xFFFFFFFF /**< Mask for reassembly map. */ -#define MAX_FRAGS 32 /**< Maximum number of fragments per packe= t. */ +#define MAX_FRAGS 32 /**< Maximum number of fragments per packet. */ unsigned int map; /**< Reassembly map for recording which * fragments have been received. @@ -80,10 +81,10 @@ * n has been received. Needs to have * at least \c MAX_FRAGS bits. */ - time_t timestamp; /**< Timestamp for time-to-live purposes. = */ + time_t timestamp; /**< Timestamp for time-to-live purposes. */ - struct buffer buf; /**< Buffer in which received datagrams - * are reassembled. */ + struct buffer buf; /**< Buffer in which received datagrams + * are reassembled. */ }; =20 @@ -135,11 +136,12 @@ * fragment_incoming() function adds newly received parts into this array * and returns the whole packets once reassembly is complete. */ -struct fragment_master { +struct fragment_master +{ struct event_timeout wakeup; /**< Timeout structure used by the main * event loop to know when to do * fragmentation housekeeping. */ -#define N_SEQ_ID 256 +#define N_SEQ_ID 256 /**< One more than the maximum fragment * sequence ID, above which the IDs wrap * to zero. Should be a power of 2. */ @@ -195,24 +197,24 @@ #define ntoh_fragment_header_type(x) ntohl(x) /**< Convert a \c fragment_header_type from network to host order. */ -#define FRAG_TYPE_MASK 0x00000003 /**< Bit mask for %fragmen= t type info. */ -#define FRAG_TYPE_SHIFT 0 /**< Bit shift for %fragme= nt type info. */ +#define FRAG_TYPE_MASK 0x00000003 /**< Bit mask for %fragment type info. = */ +#define FRAG_TYPE_SHIFT 0 /**< Bit shift for %fragment type info.= */ -#define FRAG_WHOLE 0 /**< Fragment type indicat= ing packet is whole. */ -#define FRAG_YES_NOTLAST 1 +#define FRAG_WHOLE 0 /**< Fragment type indicating packet is= whole. */ +#define FRAG_YES_NOTLAST 1 /**< Fragment type indicating packet is part of a fragmented packet, but n= ot * the last part in the sequence. */ -#define FRAG_YES_LAST 2 +#define FRAG_YES_LAST 2 /**< Fragment type indicating packet is the last part in the sequence of p= arts. */ -#define FRAG_TEST 3 +#define FRAG_TEST 3 /**< Fragment type not implemented yet. * In the future might be used as a control packet for establishing MTU si= ze. */ -#define FRAG_SEQ_ID_MASK 0x000000ff /**< Bit mask for %fragmen= t sequence ID. */ -#define FRAG_SEQ_ID_SHIFT 2 /**< Bit shift for %fragme= nt sequence ID. */ +#define FRAG_SEQ_ID_MASK 0x000000ff /**< Bit mask for %fragment sequence = ID. */ +#define FRAG_SEQ_ID_SHIFT 2 /**< Bit shift for %fragment sequence= ID. */ -#define FRAG_ID_MASK 0x0000001f /**< Bit mask for %fragmen= t ID. */ -#define FRAG_ID_SHIFT 10 /**< Bit shift for %fragme= nt ID. */ +#define FRAG_ID_MASK 0x0000001f /**< Bit mask for %fragment ID. */ +#define FRAG_ID_SHIFT 10 /**< Bit shift for %fragment ID. */ /* @@ -224,10 +226,10 @@ * max_frag_size is only sent over the wire if FRAG_LAST is set. Otherw= ise it is assumed * to be the actual %fragment size received. */ -#define FRAG_SIZE_MASK 0x00003fff /**< Bit mask for %fragmen= t size. */ -#define FRAG_SIZE_SHIFT 15 /**< Bit shift for %fragme= nt size. */ -#define FRAG_SIZE_ROUND_SHIFT 2 /**< Bit shift for %fragme= nt size rounding. */ -#define FRAG_SIZE_ROUND_MASK ((1 << FRAG_SIZE_ROUND_SHIFT) - 1) +#define FRAG_SIZE_MASK 0x00003fff /**< Bit mask for %fragment size.= */ +#define FRAG_SIZE_SHIFT 15 /**< Bit shift for %fragment size= . */ +#define FRAG_SIZE_ROUND_SHIFT 2 /**< Bit shift for %fragment size= rounding. */ +#define FRAG_SIZE_ROUND_MASK ((1 << FRAG_SIZE_ROUND_SHIFT) - 1) /**< Bit mask for %fragment size rounding. */ /* @@ -235,14 +237,14 @@ * * IF FRAG_WHOLE or FRAG_YES_NOTLAST, these 16 bits are available (not cur= rently used) */ -#define FRAG_EXTRA_MASK 0x0000ffff /**< Bit mask for extra bi= ts. */ -#define FRAG_EXTRA_SHIFT 15 /**< Bit shift for extra b= its. */ +#define FRAG_EXTRA_MASK 0x0000ffff /**< Bit mask for extra bits. */ +#define FRAG_EXTRA_SHIFT 15 /**< Bit shift for extra bits. */ -/** @} name Fragment header *//*******************************************= */ +/** @} name Fragment header */ /*************************************= *******/ /*************************************************************************= */ -/** @name Functions for initialization and cleanup *//** @{ *//***********= */ +/** @name Functions for initialization and cleanup */ /** @{ */ /*********= ***/ /** * Allocate and initialize a \c fragment_master structure. @@ -278,7 +280,7 @@ */ void fragment_free(struct fragment_master *f); -/** @} name Functions for initialization and cleanup *//******************= */ +/** @} name Functions for initialization and cleanup */ /*****************= **/ /*************************************************************************= */ @@ -326,8 +328,7 @@ * complete. If an error occurs during processing, the buffer length * is also set to zero. */ -void fragment_incoming(struct fragment_master *f, struct buffer *buf, - const struct frame *frame); +void fragment_incoming(struct fragment_master *f, struct buffer *buf, cons= t struct frame *frame); /** @} name Functions for processing packets received from a VPN tunnel */ @@ -378,8 +379,7 @@ * cases a fragmentation header will have been prepended to inform the * remote peer how to handle the packet. */ -void fragment_outgoing(struct fragment_master *f, struct buffer *buf, - const struct frame *frame); +void fragment_outgoing(struct fragment_master *f, struct buffer *buf, cons= t struct frame *frame); =20 /** * Check whether outgoing fragments are ready to be send, and if so make @@ -435,7 +435,7 @@ /*************************************************************************= */ -/** @name Functions for regular housekeeping *//** @{ *//*****************= */ +/** @name Functions for regular housekeeping */ /** @{ */ /***************= ***/ /** * Perform housekeeping of a \c fragment_master structure. @@ -459,10 +459,10 @@ } } -/** @} name Functions for regular housekeeping *//************************= */ +/** @} name Functions for regular housekeeping */ /***********************= **/ -/** @} addtogroup fragmentation *//***************************************= */ +/** @} addtogroup fragmentation */ /**************************************= **/ #endif /* ifdef ENABLE_FRAGMENT */ diff --git a/src/openvpn/gremlin.c b/src/openvpn/gremlin.c index a3ecc8d..e6ebbef 100644 --- a/src/openvpn/gremlin.c +++ b/src/openvpn/gremlin.c @@ -64,28 +64,29 @@ * When network goes up, it will be up for between * UP_LOW and UP_HIGH seconds. */ -static const int up_low[] =3D { 60, 10, 5 }; +static const int up_low[] =3D { 60, 10, 5 }; static const int up_high[] =3D { 600, 60, 10 }; /* * When network goes down, it will be down for between * DOWN_LOW and DOWN_HIGH seconds. */ -static const int down_low[] =3D { 5, 10, 10 }; +static const int down_low[] =3D { 5, 10, 10 }; static const int down_high[] =3D { 10, 60, 120 }; /* * Packet flood levels: * { number of packets, packet size } */ -static const struct packet_flood_parms packet_flood_data[] =3D -{{10, 100}, {10, 1500}, {100, 1500}}; +static const struct packet_flood_parms packet_flood_data[] =3D { { 10, 100= }, + { 10, 1500 = }, + { 100, 1500= } }; struct packet_flood_parms get_packet_flood_parms(int level) { ASSERT(level > 0 && level < 4); - return packet_flood_data [level - 1]; + return packet_flood_data[level - 1]; } /* @@ -147,18 +148,16 @@ int delta; if (up) { - delta =3D roll(down_low[up_down_level-1], down_high[up_dow= n_level-1]); + delta =3D roll(down_low[up_down_level - 1], down_high[up_d= own_level - 1]); up =3D false; } else { - delta =3D roll(up_low[up_down_level-1], up_high[up_down_le= vel-1]); + delta =3D roll(up_low[up_down_level - 1], up_high[up_down_= level - 1]); up =3D true; } - msg(D_GREMLIN, - "GREMLIN: CONNECTION GOING %s FOR %d SECONDS", - (up ? "UP" : "DOWN"), + msg(D_GREMLIN, "GREMLIN: CONNECTION GOING %s FOR %d SECONDS", = (up ? "UP" : "DOWN"), delta); next =3D now + delta; } @@ -166,7 +165,7 @@ if (drop_level) { - if (up && flip(drop_freq[drop_level-1])) + if (up && flip(drop_freq[drop_level - 1])) { dmsg(D_GREMLIN_VERBOSE, "GREMLIN: Random packet drop"); return false; @@ -185,7 +184,7 @@ const int corrupt_level =3D GREMLIN_CORRUPT_LEVEL(flags); if (corrupt_level) { - if (flip(corrupt_freq[corrupt_level-1])) + if (flip(corrupt_freq[corrupt_level - 1])) { do { @@ -226,7 +225,7 @@ { break; } - } while (flip(2)); /* a 50% chance we will corrupt again */ + } while (flip(2)); /* a 50% chance we will corrupt again */ } } } diff --git a/src/openvpn/gremlin.h b/src/openvpn/gremlin.h index 3cbfb77..2422338 100644 --- a/src/openvpn/gremlin.h +++ b/src/openvpn/gremlin.h @@ -29,30 +29,32 @@ * Gremlin options, presented as bitmask argument to --gremlin directive */ -#define GREMLIN_CONNECTION_FLOOD_SHIFT (0) -#define GREMLIN_CONNECTION_FLOOD_MASK (0x07) +#define GREMLIN_CONNECTION_FLOOD_SHIFT (0) +#define GREMLIN_CONNECTION_FLOOD_MASK (0x07) -#define GREMLIN_PACKET_FLOOD_SHIFT (3) -#define GREMLIN_PACKET_FLOOD_MASK (0x03) +#define GREMLIN_PACKET_FLOOD_SHIFT (3) +#define GREMLIN_PACKET_FLOOD_MASK (0x03) -#define GREMLIN_CORRUPT_SHIFT (5) -#define GREMLIN_CORRUPT_MASK (0x03) +#define GREMLIN_CORRUPT_SHIFT (5) +#define GREMLIN_CORRUPT_MASK (0x03) -#define GREMLIN_UP_DOWN_SHIFT (7) -#define GREMLIN_UP_DOWN_MASK (0x03) +#define GREMLIN_UP_DOWN_SHIFT (7) +#define GREMLIN_UP_DOWN_MASK (0x03) /* 512:1/500 1024:1/100 1536:1/50 */ -#define GREMLIN_DROP_SHIFT (9) -#define GREMLIN_DROP_MASK (0x03) +#define GREMLIN_DROP_SHIFT (9) +#define GREMLIN_DROP_MASK (0x03) /* extract gremlin parms */ -#define GREMLIN_CONNECTION_FLOOD_LEVEL(x) (((x)>>GREMLIN_CONNECTION_FLOOD_= SHIFT) & GREMLIN_CONNECTION_FLOOD_MASK) -#define GREMLIN_PACKET_FLOOD_LEVEL(x) (((x)>>GREMLIN_PACKET_FLOOD_SHIF= T) & GREMLIN_PACKET_FLOOD_MASK) -#define GREMLIN_CORRUPT_LEVEL(x) (((x)>>GREMLIN_CORRUPT_SHIFT) = & GREMLIN_CORRUPT_MASK) -#define GREMLIN_UP_DOWN_LEVEL(x) (((x)>>GREMLIN_UP_DOWN_SHIFT) = & GREMLIN_UP_DOWN_MASK) -#define GREMLIN_DROP_LEVEL(x) (((x)>>GREMLIN_DROP_SHIFT) = & GREMLIN_DROP_MASK) +#define GREMLIN_CONNECTION_FLOOD_LEVEL(x) \ + (((x) >> GREMLIN_CONNECTION_FLOOD_SHIFT) & GREMLIN_CONNECTION_FLOOD_MA= SK) +#define GREMLIN_PACKET_FLOOD_LEVEL(x) \ + (((x) >> GREMLIN_PACKET_FLOOD_SHIFT) & GREMLIN_PACKET_FLOOD_MASK) +#define GREMLIN_CORRUPT_LEVEL(x) (((x) >> GREMLIN_CORRUPT_SHIFT) & GREMLIN= _CORRUPT_MASK) +#define GREMLIN_UP_DOWN_LEVEL(x) (((x) >> GREMLIN_UP_DOWN_SHIFT) & GREMLIN= _UP_DOWN_MASK) +#define GREMLIN_DROP_LEVEL(x) (((x) >> GREMLIN_DROP_SHIFT) & GREMLIN_DR= OP_MASK) #include "buffer.h" diff --git a/src/openvpn/helper.c b/src/openvpn/helper.c index 36b88f5..b2ecb1e 100644 --- a/src/openvpn/helper.c +++ b/src/openvpn/helper.c @@ -70,14 +70,12 @@ if (netmask) { - buf_printf(&out, "route %s %s", - print_in_addr_t(network, 0, gc), + buf_printf(&out, "route %s %s", print_in_addr_t(network, 0, gc), print_in_addr_t(netmask, 0, gc)); } else { - buf_printf(&out, "route %s", - print_in_addr_t(network, 0, gc)); + buf_printf(&out, "route %s", print_in_addr_t(network, 0, gc)); } =20 return BSTR(&out); @@ -113,11 +111,8 @@ helper_add_route(const in_addr_t network, const in_addr_t netmask, struct = options *o) { rol_check_alloc(o); - add_route_to_option_list(o->routes, - print_in_addr_t(network, 0, &o->gc), - print_in_addr_t(netmask, 0, &o->gc), - NULL, - NULL, + add_route_to_option_list(o->routes, print_in_addr_t(network, 0, &o->gc= ), + print_in_addr_t(netmask, 0, &o->gc), NULL, NU= LL, o->route_default_table_id); } @@ -127,10 +122,8 @@ struct gc_arena gc =3D gc_new(); if ((a & subnet) !=3D (b & subnet)) { - msg(M_USAGE, "%s IP addresses %s and %s are not in the same %s sub= net", - opt, - print_in_addr_t(a, 0, &gc), - print_in_addr_t(b, 0, &gc), + msg(M_USAGE, "%s IP addresses %s and %s are not in the same %s sub= net", opt, + print_in_addr_t(a, 0, &gc), print_in_addr_t(b, 0, &gc), print_in_addr_t(subnet, 0, &gc)); } gc_free(&gc); @@ -206,17 +199,17 @@ } if (o->ifconfig_ipv6_pool_defined) { - msg(M_USAGE, "--server-ipv6 already defines an ifconfig-ipv6-p= ool, so you can't also specify --ifconfig-pool explicitly"); + msg(M_USAGE, + "--server-ipv6 already defines an ifconfig-ipv6-pool, so y= ou can't also specify --ifconfig-pool explicitly"); } o->mode =3D MODE_SERVER; o->tls_server =3D true; /* local ifconfig is "base address + 1" and "+2" */ - o->ifconfig_ipv6_local =3D - print_in6_addr( add_in6_addr( o->server_network_ipv6, 1), 0, &= o->gc ); + o->ifconfig_ipv6_local =3D print_in6_addr(add_in6_addr(o->server_n= etwork_ipv6, 1), 0, &o->gc); o->ifconfig_ipv6_remote =3D - print_in6_addr( add_in6_addr( o->server_network_ipv6, 2), 0, &= o->gc ); + print_in6_addr(add_in6_addr(o->server_network_ipv6, 2), 0, &o-= >gc); o->ifconfig_ipv6_netbits =3D o->server_netbits_ipv6; /* basic sanity check */ @@ -228,8 +221,8 @@ * * Smaller pools can't get that far, therefore we just increase by= 2 */ - o->ifconfig_ipv6_pool_base =3D add_in6_addr(o->server_network_ipv6, - o->server_netbits_ipv6 <= 112 ? 0x1000 : 2); + o->ifconfig_ipv6_pool_base =3D + add_in6_addr(o->server_network_ipv6, o->server_netbits_ipv6 < = 112 ? 0x1000 : 2); o->ifconfig_ipv6_pool_netbits =3D o->server_netbits_ipv6; push_option(o, "tun-ipv6", M_USAGE); @@ -283,12 +276,14 @@ if (o->shared_secret_file) { - msg(M_USAGE, "--server and --secret cannot be used together (y= ou must use SSL/TLS keys)"); + msg(M_USAGE, + "--server and --secret cannot be used together (you must u= se SSL/TLS keys)"); } if (!(o->server_flags & SF_NOPOOL) && o->ifconfig_pool_defined) { - msg(M_USAGE, "--server already defines an ifconfig-pool, so yo= u can't also specify --ifconfig-pool explicitly"); + msg(M_USAGE, + "--server already defines an ifconfig-pool, so you can't a= lso specify --ifconfig-pool explicitly"); } if (!(dev =3D=3D DEV_TYPE_TAP || dev =3D=3D DEV_TYPE_TUN)) @@ -309,7 +304,8 @@ if (netbits < IFCONFIG_POOL_MIN_NETBITS) { - msg(M_USAGE, "--server directive netmask allows for too many h= ost addresses (subnet must be %s or higher)", + msg(M_USAGE, + "--server directive netmask allows for too many host addre= sses (subnet must be %s or higher)", print_netmask(IFCONFIG_POOL_MIN_NETBITS, &gc)); } @@ -319,7 +315,8 @@ if (netbits > 29) { - msg(M_USAGE, "--server directive when used with --dev tun = must define a subnet of %s or lower", + msg(M_USAGE, + "--server directive when used with --dev tun must defi= ne a subnet of %s or lower", print_netmask(29, &gc)); } @@ -342,14 +339,17 @@ { o->ifconfig_pool_defined =3D true; o->ifconfig_pool_start =3D o->server_network + 4; - o->ifconfig_pool_end =3D (o->server_network | ~o->serv= er_netmask) - pool_end_reserve; - ifconfig_pool_verify_range(M_USAGE, o->ifconfig_pool_s= tart, o->ifconfig_pool_end); + o->ifconfig_pool_end =3D + (o->server_network | ~o->server_netmask) - pool_en= d_reserve; + ifconfig_pool_verify_range(M_USAGE, o->ifconfig_pool_s= tart, + o->ifconfig_pool_end); } helper_add_route(o->server_network, o->server_netmask, o); if (o->enable_c2c) { - push_option(o, print_opt_route(o->server_network, o->s= erver_netmask, &o->gc), M_USAGE); + push_option(o, print_opt_route(o->server_network, o->s= erver_netmask, &o->gc), + M_USAGE); } else if (o->topology =3D=3D TOP_NET30) { @@ -366,7 +366,8 @@ o->ifconfig_pool_defined =3D true; o->ifconfig_pool_start =3D o->server_network + 2; o->ifconfig_pool_end =3D (o->server_network | ~o->serv= er_netmask) - 1; - ifconfig_pool_verify_range(M_USAGE, o->ifconfig_pool_s= tart, o->ifconfig_pool_end); + ifconfig_pool_verify_range(M_USAGE, o->ifconfig_pool_s= tart, + o->ifconfig_pool_end); } o->ifconfig_pool_netmask =3D o->server_netmask; @@ -386,16 +387,17 @@ if (o->topology =3D=3D TOP_NET30 && !(o->server_flags & SF_NOP= OOL)) { msg(M_WARN, "WARNING: --topology net30 support for server " - "configs with IPv4 pools will be removed in a future " - "release. Please migrate to --topology subnet as soon " - "as possible."); + "configs with IPv4 pools will be removed in a = future " + "release. Please migrate to --topology subnet = as soon " + "as possible."); } } else if (dev =3D=3D DEV_TYPE_TAP) { if (netbits > 30) { - msg(M_USAGE, "--server directive when used with --dev tap = must define a subnet of %s or lower", + msg(M_USAGE, + "--server directive when used with --dev tap must defi= ne a subnet of %s or lower", print_netmask(30, &gc)); } @@ -463,12 +465,14 @@ if (!(o->server_flags & SF_NOPOOL) && o->ifconfig_pool_defined) { - msg(M_USAGE, "--server-bridge already defines an ifconfig-pool= , so you can't also specify --ifconfig-pool explicitly"); + msg(M_USAGE, + "--server-bridge already defines an ifconfig-pool, so you = can't also specify --ifconfig-pool explicitly"); } if (o->shared_secret_file) { - msg(M_USAGE, "--server-bridge and --secret cannot be used toge= ther (you must use SSL/TLS keys)"); + msg(M_USAGE, + "--server-bridge and --secret cannot be used together (you= must use SSL/TLS keys)"); } if (dev !=3D DEV_TYPE_TAP) @@ -478,9 +482,12 @@ if (o->server_bridge_defined) { - verify_common_subnet("--server-bridge", o->server_bridge_ip, o= ->server_bridge_pool_start, o->server_bridge_netmask); - verify_common_subnet("--server-bridge", o->server_bridge_pool_= start, o->server_bridge_pool_end, o->server_bridge_netmask); - verify_common_subnet("--server-bridge", o->server_bridge_ip, o= ->server_bridge_pool_end, o->server_bridge_netmask); + verify_common_subnet("--server-bridge", o->server_bridge_ip, + o->server_bridge_pool_start, o->server_br= idge_netmask); + verify_common_subnet("--server-bridge", o->server_bridge_pool_= start, + o->server_bridge_pool_end, o->server_brid= ge_netmask); + verify_common_subnet("--server-bridge", o->server_bridge_ip, o= ->server_bridge_pool_end, + o->server_bridge_netmask); } o->mode =3D MODE_SERVER; @@ -551,13 +558,14 @@ } if (o->keepalive_ping * 2 > o->keepalive_timeout) { - msg(M_USAGE, "the second parameter to --keepalive (restart tim= eout=3D%d) must be at least twice the value of the first parameter (ping in= terval=3D%d). A ratio of 1:5 or 1:6 would be even better. Recommended set= ting is --keepalive 10 60.", - o->keepalive_timeout, - o->keepalive_ping); + msg(M_USAGE, + "the second parameter to --keepalive (restart timeout=3D%d= ) must be at least twice the value of the first parameter (ping interval=3D= %d). A ratio of 1:5 or 1:6 would be even better. Recommended setting is -= -keepalive 10 60.", + o->keepalive_timeout, o->keepalive_ping); } if (o->ping_send_timeout || o->ping_rec_timeout) { - msg(M_USAGE, "--keepalive conflicts with --ping, --ping-exit, = or --ping-restart. If you use --keepalive, you don't need any of the other= --ping directives."); + msg(M_USAGE, + "--keepalive conflicts with --ping, --ping-exit, or --ping= -restart. If you use --keepalive, you don't need any of the other --ping d= irectives."); } =20 /* diff --git a/src/openvpn/httpdigest.c b/src/openvpn/httpdigest.c index be700b2..be20638 100644 --- a/src/openvpn/httpdigest.c +++ b/src/openvpn/httpdigest.c @@ -32,10 +32,7 @@ #include "httpdigest.h" static void -CvtHex( - IN HASH Bin, - OUT HASHHEX Hex - ) +CvtHex(IN HASH Bin, OUT HASHHEX Hex) { unsigned short i; unsigned char j; @@ -45,20 +42,20 @@ j =3D (Bin[i] >> 4) & 0xf; if (j <=3D 9) { - Hex[i*2] =3D (j + '0'); + Hex[i * 2] =3D (j + '0'); } else { - Hex[i*2] =3D (j + 'a' - 10); + Hex[i * 2] =3D (j + 'a' - 10); } j =3D Bin[i] & 0xf; if (j <=3D 9) { - Hex[i*2+1] =3D (j + '0'); + Hex[i * 2 + 1] =3D (j + '0'); } else { - Hex[i*2+1] =3D (j + 'a' - 10); + Hex[i * 2 + 1] =3D (j + 'a' - 10); } } Hex[HASHHEXLEN] =3D '\0'; @@ -66,34 +63,27 @@ /* calculate H(A1) as per spec */ void -DigestCalcHA1( - IN char *pszAlg, - IN char *pszUserName, - IN char *pszRealm, - IN char *pszPassword, - IN char *pszNonce, - IN char *pszCNonce, - OUT HASHHEX SessionKey - ) +DigestCalcHA1(IN char *pszAlg, IN char *pszUserName, IN char *pszRealm, IN= char *pszPassword, + IN char *pszNonce, IN char *pszCNonce, OUT HASHHEX SessionKe= y) { HASH HA1; md_ctx_t *md5_ctx =3D md_ctx_new(); md_ctx_init(md5_ctx, "MD5"); - md_ctx_update(md5_ctx, (const uint8_t *) pszUserName, strlen(pszUserNa= me)); - md_ctx_update(md5_ctx, (const uint8_t *) ":", 1); - md_ctx_update(md5_ctx, (const uint8_t *) pszRealm, strlen(pszRealm)); - md_ctx_update(md5_ctx, (const uint8_t *) ":", 1); - md_ctx_update(md5_ctx, (const uint8_t *) pszPassword, strlen(pszPasswo= rd)); + md_ctx_update(md5_ctx, (const uint8_t *)pszUserName, strlen(pszUserNam= e)); + md_ctx_update(md5_ctx, (const uint8_t *)":", 1); + md_ctx_update(md5_ctx, (const uint8_t *)pszRealm, strlen(pszRealm)); + md_ctx_update(md5_ctx, (const uint8_t *)":", 1); + md_ctx_update(md5_ctx, (const uint8_t *)pszPassword, strlen(pszPasswor= d)); md_ctx_final(md5_ctx, HA1); if (pszAlg && strcasecmp(pszAlg, "md5-sess") =3D=3D 0) { md_ctx_init(md5_ctx, "MD5"); md_ctx_update(md5_ctx, HA1, HASHLEN); - md_ctx_update(md5_ctx, (const uint8_t *) ":", 1); - md_ctx_update(md5_ctx, (const uint8_t *) pszNonce, strlen(pszNonce= )); - md_ctx_update(md5_ctx, (const uint8_t *) ":", 1); - md_ctx_update(md5_ctx, (const uint8_t *) pszCNonce, strlen(pszCNon= ce)); + md_ctx_update(md5_ctx, (const uint8_t *)":", 1); + md_ctx_update(md5_ctx, (const uint8_t *)pszNonce, strlen(pszNonce)= ); + md_ctx_update(md5_ctx, (const uint8_t *)":", 1); + md_ctx_update(md5_ctx, (const uint8_t *)pszCNonce, strlen(pszCNonc= e)); md_ctx_final(md5_ctx, HA1); } md_ctx_cleanup(md5_ctx); @@ -103,17 +93,16 @@ /* calculate request-digest/response-digest as per HTTP Digest spec */ void -DigestCalcResponse( - IN HASHHEX HA1, /* H(A1) */ - IN char *pszNonce, /* nonce from server */ - IN char *pszNonceCount, /* 8 hex digits */ - IN char *pszCNonce, /* client nonce */ - IN char *pszQop, /* qop-value: "", "auth", "au= th-int" */ - IN char *pszMethod, /* method from the request */ - IN char *pszDigestUri, /* requested URL */ - IN HASHHEX HEntity, /* H(entity body) if qop=3D"a= uth-int" */ - OUT HASHHEX Response /* request-digest or response= -digest */ - ) +DigestCalcResponse(IN HASHHEX HA1, /* H(A1) */ + IN char *pszNonce, /* nonce from server */ + IN char *pszNonceCount, /* 8 hex digits */ + IN char *pszCNonce, /* client nonce */ + IN char *pszQop, /* qop-value: "", "auth", "auth= -int" */ + IN char *pszMethod, /* method from the request */ + IN char *pszDigestUri, /* requested URL */ + IN HASHHEX HEntity, /* H(entity body) if qop=3D"aut= h-int" */ + OUT HASHHEX Response /* request-digest or response-d= igest */ +) { HASH HA2; HASH RespHash; @@ -123,12 +112,12 @@ /* calculate H(A2) */ md_ctx_init(md5_ctx, "MD5"); - md_ctx_update(md5_ctx, (const uint8_t *) pszMethod, strlen(pszMethod)); - md_ctx_update(md5_ctx, (const uint8_t *) ":", 1); - md_ctx_update(md5_ctx, (const uint8_t *) pszDigestUri, strlen(pszDiges= tUri)); + md_ctx_update(md5_ctx, (const uint8_t *)pszMethod, strlen(pszMethod)); + md_ctx_update(md5_ctx, (const uint8_t *)":", 1); + md_ctx_update(md5_ctx, (const uint8_t *)pszDigestUri, strlen(pszDigest= Uri)); if (strcasecmp(pszQop, "auth-int") =3D=3D 0) { - md_ctx_update(md5_ctx, (const uint8_t *) ":", 1); + md_ctx_update(md5_ctx, (const uint8_t *)":", 1); md_ctx_update(md5_ctx, HEntity, HASHHEXLEN); } md_ctx_final(md5_ctx, HA2); @@ -137,17 +126,17 @@ /* calculate response */ md_ctx_init(md5_ctx, "MD5"); md_ctx_update(md5_ctx, HA1, HASHHEXLEN); - md_ctx_update(md5_ctx, (const uint8_t *) ":", 1); - md_ctx_update(md5_ctx, (const uint8_t *) pszNonce, strlen(pszNonce)); - md_ctx_update(md5_ctx, (const uint8_t *) ":", 1); + md_ctx_update(md5_ctx, (const uint8_t *)":", 1); + md_ctx_update(md5_ctx, (const uint8_t *)pszNonce, strlen(pszNonce)); + md_ctx_update(md5_ctx, (const uint8_t *)":", 1); if (*pszQop) { - md_ctx_update(md5_ctx, (const uint8_t *) pszNonceCount, strlen(psz= NonceCount)); - md_ctx_update(md5_ctx, (const uint8_t *) ":", 1); - md_ctx_update(md5_ctx, (const uint8_t *) pszCNonce, strlen(pszCNon= ce)); - md_ctx_update(md5_ctx, (const uint8_t *) ":", 1); - md_ctx_update(md5_ctx, (const uint8_t *) pszQop, strlen(pszQop)); - md_ctx_update(md5_ctx, (const uint8_t *) ":", 1); + md_ctx_update(md5_ctx, (const uint8_t *)pszNonceCount, strlen(pszN= onceCount)); + md_ctx_update(md5_ctx, (const uint8_t *)":", 1); + md_ctx_update(md5_ctx, (const uint8_t *)pszCNonce, strlen(pszCNonc= e)); + md_ctx_update(md5_ctx, (const uint8_t *)":", 1); + md_ctx_update(md5_ctx, (const uint8_t *)pszQop, strlen(pszQop)); + md_ctx_update(md5_ctx, (const uint8_t *)":", 1); } md_ctx_update(md5_ctx, HA2Hex, HASHHEXLEN); md_ctx_final(md5_ctx, RespHash); diff --git a/src/openvpn/httpdigest.h b/src/openvpn/httpdigest.h index ecdd6d3..1b51a62 100644 --- a/src/openvpn/httpdigest.h +++ b/src/openvpn/httpdigest.h @@ -25,34 +25,26 @@ #define HASHLEN 16 typedef unsigned char HASH[HASHLEN]; #define HASHHEXLEN 32 -typedef unsigned char HASHHEX[HASHHEXLEN+1]; +typedef unsigned char HASHHEX[HASHHEXLEN + 1]; #undef IN #undef OUT #define IN const #define OUT /* calculate H(A1) as per HTTP Digest spec */ -void DigestCalcHA1( - IN char *pszAlg, - IN char *pszUserName, - IN char *pszRealm, - IN char *pszPassword, - IN char *pszNonce, - IN char *pszCNonce, - OUT HASHHEX SessionKey - ); +void DigestCalcHA1(IN char *pszAlg, IN char *pszUserName, IN char *pszReal= m, IN char *pszPassword, + IN char *pszNonce, IN char *pszCNonce, OUT HASHHEX Sess= ionKey); /* calculate request-digest/response-digest as per HTTP Digest spec */ -void DigestCalcResponse( - IN HASHHEX HA1, /* H(A1) */ - IN char *pszNonce, /* nonce from server */ - IN char *pszNonceCount, /* 8 hex digits */ - IN char *pszCNonce, /* client nonce */ - IN char *pszQop, /* qop-value: "", "auth", "auth-int" */ - IN char *pszMethod, /* method from the request */ - IN char *pszDigestUri, /* requested URL */ - IN HASHHEX HEntity, /* H(entity body) if qop=3D"auth-int" */ - OUT HASHHEX Response /* request-digest or response-digest */ - ); +void DigestCalcResponse(IN HASHHEX HA1, /* H(A1) */ + IN char *pszNonce, /* nonce from server */ + IN char *pszNonceCount, /* 8 hex digits */ + IN char *pszCNonce, /* client nonce */ + IN char *pszQop, /* qop-value: "", "auth", = "auth-int" */ + IN char *pszMethod, /* method from the request= */ + IN char *pszDigestUri, /* requested URL */ + IN HASHHEX HEntity, /* H(entity body) if qop= =3D"auth-int" */ + OUT HASHHEX Response /* request-digest or respo= nse-digest */ +); #endif /* if PROXY_DIGEST_AUTH */ diff --git a/src/openvpn/init.c b/src/openvpn/init.c index 32f20e1..40ae2c8 100644 --- a/src/openvpn/init.c +++ b/src/openvpn/init.c @@ -58,15 +58,15 @@ #include "memdbg.h" =20 -static struct context *static_context; /* GLOBAL */ +static struct context *static_context; /* GLOBAL */ static const char *saved_pid_file_name; /* GLOBAL */ /* * Crypto initialization flags */ -#define CF_LOAD_PERSISTED_PACKET_ID (1<<0) -#define CF_INIT_TLS_MULTI (1<<1) -#define CF_INIT_TLS_AUTH_STANDALONE (1<<2) +#define CF_LOAD_PERSISTED_PACKET_ID (1 << 0) +#define CF_INIT_TLS_MULTI (1 << 1) +#define CF_INIT_TLS_AUTH_STANDALONE (1 << 2) static void do_init_first_time(struct context *c); @@ -105,21 +105,14 @@ * Used to execute the up/down script/plugins. */ static void -run_up_down(const char *command, - const struct plugin_list *plugins, - int plugin_type, +run_up_down(const char *command, const struct plugin_list *plugins, int pl= ugin_type, const char *arg, #ifdef _WIN32 DWORD adapter_index, #endif - const char *dev_type, - int tun_mtu, - const char *ifconfig_local, - const char *ifconfig_remote, - const char *context, - const char *signal_text, - const char *script_type, - struct env_set *es) + const char *dev_type, int tun_mtu, const char *ifconfig_local, + const char *ifconfig_remote, const char *context, const char *= signal_text, + const char *script_type, struct env_set *es) { struct gc_arena gc =3D gc_new(); @@ -155,9 +148,8 @@ { struct argv argv =3D argv_new(); ASSERT(arg); - argv_printf(&argv, - "%s %d 0 %s %s %s", - arg, tun_mtu, ifconfig_local, ifconfig_remote, context= ); + argv_printf(&argv, "%s %d 0 %s %s %s", arg, tun_mtu, ifconfig_loca= l, ifconfig_remote, + context); if (plugin_call(plugins, plugin_type, &argv, NULL, es) !=3D OPENVP= N_PLUGIN_FUNC_SUCCESS) { @@ -173,8 +165,8 @@ ASSERT(arg); setenv_str(es, "script_type", script_type); argv_parse_cmd(&argv, command); - argv_printf_cat(&argv, "%s %d 0 %s %s %s", arg, tun_mtu, - ifconfig_local, ifconfig_remote, context); + argv_printf_cat(&argv, "%s %d 0 %s %s %s", arg, tun_mtu, ifconfig_= local, ifconfig_remote, + context); argv_msg(M_INFO, &argv); openvpn_run_script(&argv, es, S_FATAL, "--up/--down"); argv_free(&argv); @@ -196,8 +188,7 @@ * for the period of time before we pull the --ping-restart parameter * from the server. */ - if (options->pull - && options->ping_rec_timeout_action =3D=3D PING_UNDEF + if (options->pull && options->ping_rec_timeout_action =3D=3D PING_UNDEF && proto_is_dgram(options->ce.proto)) { options->ping_rec_timeout =3D PRE_PULL_INITIAL_PING_RESTART; @@ -303,11 +294,9 @@ * @return if sending was successful */ static bool -management_callback_send_cc_message(void *arg, - const char *command, - const char *parameters) +management_callback_send_cc_message(void *arg, const char *command, const = char *parameters) { - struct context *c =3D (struct context *) arg; + struct context *c =3D (struct context *)arg; size_t len =3D strlen(command) + 1 + strlen(parameters) + 1; if (len > PUSH_BUNDLE_SIZE) { @@ -331,7 +320,7 @@ management_callback_remote_entry_count(void *arg) { assert(arg); - struct context *c =3D (struct context *) arg; + struct context *c =3D (struct context *)arg; struct connection_list *l =3D c->options.connection_list; return l->len; @@ -343,7 +332,7 @@ assert(arg); assert(remote); - struct context *c =3D (struct context *) arg; + struct context *c =3D (struct context *)arg; struct connection_list *l =3D c->options.connection_list; bool ret =3D true; @@ -354,8 +343,8 @@ const char *status =3D (ce->flags & CE_DISABLED) ? "disabled" : "e= nabled"; /* space for output including 3 commas and a nul */ - int len =3D strlen(ce->remote) + strlen(ce->remote_port) + strlen(= proto) - + strlen(status) + 3 + 1; + int len =3D + strlen(ce->remote) + strlen(ce->remote_port) + strlen(proto) += strlen(status) + 3 + 1; char *out =3D malloc(len); check_malloc_return(out); @@ -374,10 +363,12 @@ static bool management_callback_remote_cmd(void *arg, const char **p) { - struct context *c =3D (struct context *) arg; + struct context *c =3D (struct context *)arg; struct connection_entry *ce =3D &c->options.ce; int ret =3D false; - if (p[1] && ((ce->flags>>CE_MAN_QUERY_REMOTE_SHIFT)&CE_MAN_QUERY_REMOT= E_MASK) =3D=3D CE_MAN_QUERY_REMOTE_QUERY) + if (p[1] + && ((ce->flags >> CE_MAN_QUERY_REMOTE_SHIFT) & CE_MAN_QUERY_REMOTE= _MASK) + =3D=3D CE_MAN_QUERY_REMOTE_QUERY) { int flags =3D 0; if (!strcmp(p[1], "ACCEPT")) @@ -412,8 +403,8 @@ } if (ret) { - ce->flags &=3D ~(CE_MAN_QUERY_REMOTE_MASK<flags |=3D ((flags&CE_MAN_QUERY_REMOTE_MASK)<flags &=3D ~(CE_MAN_QUERY_REMOTE_MASK << CE_MAN_QUERY_REMO= TE_SHIFT); + ce->flags |=3D ((flags & CE_MAN_QUERY_REMOTE_MASK) << CE_MAN_Q= UERY_REMOTE_SHIFT); } } return ret; @@ -438,8 +429,8 @@ ce->flags &=3D ~(CE_MAN_QUERY_REMOTE_MASK << CE_MAN_QUERY_REMOTE_S= HIFT); ce->flags |=3D (CE_MAN_QUERY_REMOTE_QUERY << CE_MAN_QUERY_REMOTE_S= HIFT); - while (((ce->flags >> CE_MAN_QUERY_REMOTE_SHIFT) - & CE_MAN_QUERY_REMOTE_MASK) =3D=3D CE_MAN_QUERY_REMOTE_QUE= RY) + while (((ce->flags >> CE_MAN_QUERY_REMOTE_SHIFT) & CE_MAN_QUERY_RE= MOTE_MASK) + =3D=3D CE_MAN_QUERY_REMOTE_QUERY) { management_event_loop_n_seconds(management, 1); if (IS_SIG(c)) @@ -457,8 +448,7 @@ /* If it is likely a connection entry was modified, * check what changed in the flags and that it was not skipped */ - const int flags =3D ((ce->flags >> CE_MAN_QUERY_REMOTE_SHIFT) - & CE_MAN_QUERY_REMOTE_MASK); + const int flags =3D ((ce->flags >> CE_MAN_QUERY_REMOTE_SHIFT) & CE= _MAN_QUERY_REMOTE_MASK); ce_changed =3D (flags !=3D CE_MAN_QUERY_REMOTE_SKIP); } return ce_changed; @@ -635,7 +625,7 @@ /* Check if this connection attempt would bring us over the limit */ if (c->options.connect_retry_max > 0 - && c->options.unsuccessful_attempts > (l->len * c->options.connec= t_retry_max)) + && c->options.unsuccessful_attempts > (l->len * c->options.connect= _retry_max)) { msg(M_FATAL, "All connections have been connect-retry-max (%d) tim= es unsuccessful, exiting", c->options.connect_retry_max); @@ -660,12 +650,11 @@ { enable_auth_user_pass(); #ifdef ENABLE_MANAGEMENT - auth_user_pass_setup(c->options.auth_user_pass_file, - c->options.auth_user_pass_file_inline, + auth_user_pass_setup(c->options.auth_user_pass_file, c->options.au= th_user_pass_file_inline, &c->options.sc_info); #else - auth_user_pass_setup(c->options.auth_user_pass_file, - c->options.auth_user_pass_file_inline, NULL); + auth_user_pass_setup(c->options.auth_user_pass_file, c->options.au= th_user_pass_file_inline, + NULL); #endif } } @@ -713,9 +702,9 @@ if (!did_http && c->options.ce.socks_proxy_server) { - c->c1.socks_proxy =3D socks_proxy_new(c->options.ce.socks_proxy_se= rver, - c->options.ce.socks_proxy_port, - c->options.ce.socks_proxy_auth= file); + c->c1.socks_proxy =3D + socks_proxy_new(c->options.ce.socks_proxy_server, c->options.c= e.socks_proxy_port, + c->options.ce.socks_proxy_authfile); if (c->c1.socks_proxy) { c->c1.socks_proxy_owned =3D true; @@ -738,8 +727,8 @@ static void do_link_socket_addr_new(struct context *c) { - ALLOC_ARRAY_CLEAR_GC(c->c1.link_socket_addrs, struct link_socket_addr, - c->c1.link_sockets_num, &c->gc); + ALLOC_ARRAY_CLEAR_GC(c->c1.link_socket_addrs, struct link_socket_addr,= c->c1.link_sockets_num, + &c->gc); } void @@ -760,10 +749,11 @@ { int i; pkcs11_initialize(true, c->options.pkcs11_pin_cache_period); - for (i =3D 0; ioptions.pkcs11_providers[i] !=3D N= ULL; i++) + for (i =3D 0; i < MAX_PARMS && c->options.pkcs11_providers[i] !=3D= NULL; i++) { - pkcs11_addProvider(c->options.pkcs11_providers[i], c->options.= pkcs11_protected_authentication[i], - c->options.pkcs11_private_mode[i], c->optio= ns.pkcs11_cert_private[i]); + pkcs11_addProvider( + c->options.pkcs11_providers[i], c->options.pkcs11_protecte= d_authentication[i], + c->options.pkcs11_private_mode[i], c->options.pkcs11_cert_= private[i]); } } #endif @@ -788,9 +778,8 @@ * See possibly_become_daemon() [init.c] for more details. */ sd_notifyf(0, "READY=3D1\nSTATUS=3DPre-connection initialization succe= ssful\nMAINPID=3D%lu", - (unsigned long) getpid()); + (unsigned long)getpid()); #endif - } void @@ -818,10 +807,9 @@ { if (!port_share && (c->options.port_share_host && c->options.port_shar= e_port)) { - port_share =3D port_share_open(c->options.port_share_host, - c->options.port_share_port, - c->c2.frame.buf.payload_size, - c->options.port_share_journal_dir); + port_share =3D + port_share_open(c->options.port_share_host, c->options.port_sh= are_port, + c->c2.frame.buf.payload_size, c->options.port_= share_journal_dir); if (port_share =3D=3D NULL) { msg(M_FATAL, "Fatal error: Port sharing failed"); @@ -849,12 +837,12 @@ struct timeval tv; if (!gettimeofday(&tv, NULL)) { - const unsigned int seed =3D (unsigned int) tv.tv_sec ^ tv.tv_usec; + const unsigned int seed =3D (unsigned int)tv.tv_sec ^ tv.tv_usec; srandom(seed); } - error_reset(); /* initialize error.c */ - reset_check_status(); /* initialize status check code in socket.= c */ + error_reset(); /* initialize error.c */ + reset_check_status(); /* initialize status check code in socket.c */ #ifdef _WIN32 init_win32(); @@ -892,9 +880,7 @@ #ifdef GEN_PATH_TEST { struct gc_arena gc =3D gc_new(); - const char *fn =3D gen_path("foo", - "bar", - &gc); + const char *fn =3D gen_path("foo", "bar", &gc); printf("%s\n", fn); gc_free(&gc); } @@ -1011,8 +997,7 @@ } if (options->show_tls_ciphers) { - show_available_tls_ciphers(options->cipher_list, - options->cipher_list_tls13, + show_available_tls_ciphers(options->cipher_list, options->ciph= er_list_tls13, options->tls_cert_profile); } if (options->show_curves) @@ -1040,11 +1025,10 @@ * We do not want user to use --genkey with --secret. In the transisti= on * phase we for secret. */ - if (options->genkey && options->genkey_type !=3D GENKEY_SECRET - && options->shared_secret_file) + if (options->genkey && options->genkey_type !=3D GENKEY_SECRET && opti= ons->shared_secret_file) { msg(M_USAGE, "Using --genkey type with --secret filename is " - "not supported. Use --genkey type filename instead."); + "not supported. Use --genkey type filename instead."= ); } if (options->genkey && options->genkey_type =3D=3D GENKEY_SECRET) { @@ -1053,7 +1037,7 @@ if (options->shared_secret_file && options->genkey_filename) { msg(M_USAGE, "You must provide a filename to either --genkey " - "or --secret, not both"); + "or --secret, not both"); } /* @@ -1063,7 +1047,7 @@ if (options->shared_secret_file) { msg(M_WARN, "WARNING: Using --genkey --secret filename is " - "DEPRECATED. Use --genkey secret filename instead."); + "DEPRECATED. Use --genkey secret filename instead= ."); genkey_filename =3D options->shared_secret_file; } @@ -1073,8 +1057,7 @@ msg(M_FATAL, "Failed to write key file"); } - msg(D_GENKEY | M_NOPREFIX, - "Randomly generated %d bit key written to %s", nbits_written, + msg(D_GENKEY | M_NOPREFIX, "Randomly generated %d bit key written = to %s", nbits_written, options->shared_secret_file); return true; } @@ -1091,8 +1074,8 @@ "--genkey tls-crypt-v2-client requires a server key to be = set via --tls-crypt-v2 to create a client key"); } - tls_crypt_v2_write_client_key_file(options->genkey_filename, - options->genkey_extra_data, opt= ions->tls_crypt_v2_file, + tls_crypt_v2_write_client_key_file(options->genkey_filename, optio= ns->genkey_extra_data, + options->tls_crypt_v2_file, options->tls_crypt_v2_file_inli= ne); return true; } @@ -1120,13 +1103,10 @@ /* sanity check on options for --mktun or --rmtun */ notnull(options->dev, "TUN/TAP device (--dev)"); - if (options->ce.remote || options->ifconfig_local - || options->ifconfig_remote_netmask - || options->shared_secret_file - || options->tls_server || options->tls_client - ) + if (options->ce.remote || options->ifconfig_local || options->ifconfig= _remote_netmask + || options->shared_secret_file || options->tls_server || options->= tls_client) { - msg(M_FATAL|M_OPTERR, + msg(M_FATAL | M_OPTERR, "options --mktun or --rmtun should only be used together with = --dev"); } @@ -1150,21 +1130,20 @@ #endif #ifdef ENABLE_FEATURE_TUN_PERSIST - tuncfg(options->dev, options->dev_type, options->dev_node, - options->persist_mode, - options->username, options->groupname, &options->tuntap_options, - ctx); + tuncfg(options->dev, options->dev_type, options->dev_node, options->pe= rsist_mode, + options->username, options->groupname, &options->tuntap_options= , ctx); if (options->persist_mode && options->lladdr) { set_lladdr(ctx, options->dev, options->lladdr, NULL); } return true; -#else /* ifdef ENABLE_FEATURE_TUN_PERSIST */ - msg(M_FATAL|M_OPTERR, +#else /* ifdef ENABLE_FEATURE_TUN_PERSIST */ + msg(M_FATAL | M_OPTERR, "options --mktun and --rmtun are not available on your operating " "system. Please check 'man tun' (or 'tap'), whether your system " "supports using 'ifconfig %s create' / 'destroy' to create/remove " - "persistent tunnel interfaces.", options->dev ); + "persistent tunnel interfaces.", + options->dev); #endif return false; } @@ -1241,9 +1220,7 @@ { if (no_delay) { - platform_user_group_set(&c0->platform_state_user, - &c0->platform_state_group, - c); + platform_user_group_set(&c0->platform_state_user, &c0->pla= tform_state_group, c); } else if (c->first_time) { @@ -1271,7 +1248,8 @@ { if (-1 =3D=3D setcon(c->options.selinux_context)) { - msg(M_ERR, "setcon to '%s' failed; is /proc accessible= ?", c->options.selinux_context); + msg(M_ERR, "setcon to '%s' failed; is /proc accessible= ?", + c->options.selinux_context); } else { @@ -1316,17 +1294,12 @@ #ifdef _WIN32 if (options->exit_event_name) { - win32_signal_open(&win32_signal, - WSO_FORCE_SERVICE, - options->exit_event_name, + win32_signal_open(&win32_signal, WSO_FORCE_SERVICE, options->exit_= event_name, options->exit_event_initial_state); } else { - win32_signal_open(&win32_signal, - WSO_FORCE_CONSOLE, - NULL, - false); + win32_signal_open(&win32_signal, WSO_FORCE_CONSOLE, NULL, false); /* put a title on the top window bar */ if (win32_signal.mode =3D=3D WSO_MODE_CONSOLE) @@ -1377,8 +1350,7 @@ /* initialize inactivity timeout */ if (c->options.session_timeout) { - event_timeout_init(&c->c2.session_interval, c->options.session_tim= eout, - now); + event_timeout_init(&c->c2.session_interval, c->options.session_tim= eout, now); } /* initialize pings */ @@ -1409,8 +1381,7 @@ if (c->options.auth_token_generate && c->options.auth_token_renewal < c->options.renegotiate_seconds) { - event_timeout_init(&c->c2.auth_token_renewal_interval, - c->options.auth_token_renewal, now); + event_timeout_init(&c->c2.auth_token_renewal_interval, c->options.= auth_token_renewal, now); } if (!deferred) @@ -1420,16 +1391,16 @@ /* initialize occ timers */ - if (c->options.occ - && !TLS_MODE(c) - && c->c2.options_string_local && c->c2.options_string_remote) + if (c->options.occ && !TLS_MODE(c) && c->c2.options_string_local + && c->c2.options_string_remote) { event_timeout_init(&c->c2.occ_interval, OCC_INTERVAL_SECONDS, = now); } if (c->options.mtu_test) { - event_timeout_init(&c->c2.occ_mtu_load_test_interval, OCC_MTU_= LOAD_INTERVAL_SECONDS, now); + event_timeout_init(&c->c2.occ_mtu_load_test_interval, OCC_MTU_= LOAD_INTERVAL_SECONDS, + now); } /* initialize packet_id persistence timer */ @@ -1482,10 +1453,8 @@ * options and saving routes in the environment. */ static void -do_init_route_list(const struct options *options, - struct route_list *route_list, - const struct link_socket_info *link_socket_info, - struct env_set *es, +do_init_route_list(const struct options *options, struct route_list *route= _list, + const struct link_socket_info *link_socket_info, struct= env_set *es, openvpn_net_ctx_t *ctx) { const char *gw =3D NULL; @@ -1514,13 +1483,8 @@ metric =3D options->route_default_metric; } - if (init_route_list(route_list, - options->routes, - gw, - metric, - link_socket_current_remote(link_socket_info), - es, - ctx)) + if (init_route_list(route_list, options->routes, gw, metric, + link_socket_current_remote(link_socket_info), es, = ctx)) { /* copy routes to environment */ setenv_routes(es, route_list); @@ -1528,14 +1492,12 @@ } static void -do_init_route_ipv6_list(const struct options *options, - struct route_ipv6_list *route_ipv6_list, - const struct link_socket_info *link_socket_info, - struct env_set *es, +do_init_route_ipv6_list(const struct options *options, struct route_ipv6_l= ist *route_ipv6_list, + const struct link_socket_info *link_socket_info, s= truct env_set *es, openvpn_net_ctx_t *ctx) { const char *gw =3D NULL; - int metric =3D -1; /* no metric set */ + int metric =3D -1; /* no metric set */ /* see explanation in do_init_route_list() */ if (dco_enabled(options)) @@ -1543,7 +1505,7 @@ metric =3D DCO_DEFAULT_METRIC; } - gw =3D options->ifconfig_ipv6_remote; /* default GW =3D remote= end */ + gw =3D options->ifconfig_ipv6_remote; /* default GW =3D remote end */ if (options->route_ipv6_default_gateway) { gw =3D options->route_ipv6_default_gateway; @@ -1563,19 +1525,14 @@ for (i =3D 0; opt_list[i]; i++) { - add_route_ipv6_to_option_list( options->routes_ipv6, - string_alloc(opt_list[i], optio= ns->routes_ipv6->gc), - NULL, NULL, options->route_defa= ult_table_id); + add_route_ipv6_to_option_list(options->routes_ipv6, + string_alloc(opt_list[i], option= s->routes_ipv6->gc), NULL, + NULL, options->route_default_tab= le_id); } } - if (init_route_ipv6_list(route_ipv6_list, - options->routes_ipv6, - gw, - metric, - link_socket_current_remote_ipv6(link_socket_i= nfo), - es, - ctx)) + if (init_route_ipv6_list(route_ipv6_list, options->routes_ipv6, gw, me= tric, + link_socket_current_remote_ipv6(link_socket_i= nfo), es, ctx)) { /* copy routes to environment */ setenv_routes_ipv6(es, route_ipv6_list); @@ -1601,8 +1558,8 @@ if (flags & ISC_ERRORS) { #ifdef _WIN32 - show_routes(M_INFO|M_NOPREFIX); - show_adapters(M_INFO|M_NOPREFIX); + show_routes(M_INFO | M_NOPREFIX); + show_adapters(M_INFO | M_NOPREFIX); msg(M_INFO, "%s With Errors ( see http://openvpn.net/faq.html#dhcp= clientserv )", message); #else #ifdef ENABLE_SYSTEMD @@ -1620,7 +1577,7 @@ } /* Flag that we initialized */ - if ((flags & (ISC_ERRORS|ISC_SERVER)) =3D=3D 0) + if ((flags & (ISC_ERRORS | ISC_SERVER)) =3D=3D 0) { c->options.no_advance =3D true; } @@ -1682,13 +1639,8 @@ tun_local =3D &c->c1.tuntap->local; tun_local6 =3D &c->c1.tuntap->local_ipv6; } - management_set_state(management, - OPENVPN_STATE_CONNECTED, - detail, - tun_local, - tun_local6, - &local, - &remote); + management_set_state(management, OPENVPN_STATE_CONNECTED, detail, = tun_local, tun_local6, + &local, &remote); if (tun_local) { management_post_tunnel_open(management, *tun_local); @@ -1704,8 +1656,7 @@ static bool route_noexec_enabled(const struct options *o, const struct tuntap *tt) { - return o->route_noexec - || (tt && tt->backend_driver =3D=3D DRIVER_AFUNIX) + return o->route_noexec || (tt && tt->backend_driver =3D=3D DRIVER_AFUN= IX) || (tt && tt->backend_driver =3D=3D DRIVER_NULL); } @@ -1714,19 +1665,14 @@ * based on options. */ bool -do_route(const struct options *options, - struct route_list *route_list, - struct route_ipv6_list *route_ipv6_list, - const struct tuntap *tt, - const struct plugin_list *plugins, - struct env_set *es, - openvpn_net_ctx_t *ctx) +do_route(const struct options *options, struct route_list *route_list, + struct route_ipv6_list *route_ipv6_list, const struct tuntap *tt, + const struct plugin_list *plugins, struct env_set *es, openvpn_ne= t_ctx_t *ctx) { bool ret =3D true; - if (!route_noexec_enabled(options, tt) && ( route_list || route_ipv6_l= ist ) ) + if (!route_noexec_enabled(options, tt) && (route_list || route_ipv6_li= st)) { - ret =3D add_routes(route_list, route_ipv6_list, tt, ROUTE_OPTION_F= LAGS(options), - es, ctx); + ret =3D add_routes(route_list, route_ipv6_list, tt, ROUTE_OPTION_F= LAGS(options), es, ctx); setenv_int(es, "redirect_gateway", route_did_redirect_default_gate= way(route_list)); } #ifdef ENABLE_MANAGEMENT @@ -1738,7 +1684,8 @@ if (plugin_defined(plugins, OPENVPN_PLUGIN_ROUTE_UP)) { - if (plugin_call(plugins, OPENVPN_PLUGIN_ROUTE_UP, NULL, NULL, es) = !=3D OPENVPN_PLUGIN_FUNC_SUCCESS) + if (plugin_call(plugins, OPENVPN_PLUGIN_ROUTE_UP, NULL, NULL, es) + !=3D OPENVPN_PLUGIN_FUNC_SUCCESS) { msg(M_WARN, "WARNING: route-up plugin call failed"); } @@ -1756,13 +1703,13 @@ #ifdef _WIN32 if (options->show_net_up) { - show_routes(M_INFO|M_NOPREFIX); - show_adapters(M_INFO|M_NOPREFIX); + show_routes(M_INFO | M_NOPREFIX); + show_adapters(M_INFO | M_NOPREFIX); } else if (check_debug_level(D_SHOW_NET)) { - show_routes(D_SHOW_NET|M_NOPREFIX); - show_adapters(D_SHOW_NET|M_NOPREFIX); + show_routes(D_SHOW_NET | M_NOPREFIX); + show_adapters(D_SHOW_NET | M_NOPREFIX); } #endif return ret; @@ -1774,27 +1721,19 @@ static void do_init_tun(struct context *c) { - c->c1.tuntap =3D init_tun(c->options.dev, - c->options.dev_type, - c->options.topology, - c->options.ifconfig_local, - c->options.ifconfig_remote_netmask, - c->options.ifconfig_ipv6_local, - c->options.ifconfig_ipv6_netbits, - c->options.ifconfig_ipv6_remote, - c->c1.link_socket_addrs[0].bind_local, - c->c1.link_socket_addrs[0].remote_list, - !c->options.ifconfig_nowarn, - c->c2.es, - &c->net_ctx, - c->c1.tuntap); + c->c1.tuntap =3D init_tun(c->options.dev, c->options.dev_type, c->opti= ons.topology, + c->options.ifconfig_local, c->options.ifconfig= _remote_netmask, + c->options.ifconfig_ipv6_local, c->options.ifc= onfig_ipv6_netbits, + c->options.ifconfig_ipv6_remote, c->c1.link_so= cket_addrs[0].bind_local, + c->c1.link_socket_addrs[0].remote_list, !c->op= tions.ifconfig_nowarn, + c->c2.es, &c->net_ctx, c->c1.tuntap); if (is_tun_afunix(c->options.dev_node)) { /* Using AF_UNIX trumps using DCO */ c->c1.tuntap->backend_driver =3D DRIVER_AFUNIX; } - else if (is_dev_type(c->options.dev, c->options.dev_type, "null")) + else if (is_dev_type(c->options.dev, c->options.dev_type, "null")) { c->c1.tuntap->backend_driver =3D DRIVER_NULL; } @@ -1814,9 +1753,7 @@ } #endif - init_tun_post(c->c1.tuntap, - &c->c2.frame, - &c->options.tuntap_options); + init_tun_post(c->c1.tuntap, &c->c2.frame, &c->options.tuntap_options); c->c1.tuntap_owned =3D true; } @@ -1916,10 +1853,10 @@ } else { - open_tun(c->options.dev, c->options.dev_type, c->options.dev_node, - tt, &c->net_ctx); + open_tun(c->options.dev, c->options.dev_type, c->options.dev_node,= tt, &c->net_ctx); } - msg(M_INFO, "%s device [%s] opened", print_tun_backend_driver(tt->back= end_driver), tt->actual_name); + msg(M_INFO, "%s device [%s] opened", print_tun_backend_driver(tt->back= end_driver), + tt->actual_name); } @@ -1958,8 +1895,7 @@ #ifdef _WIN32 /* store (hide) interactive service handle in tuntap_options */ c->c1.tuntap->options.msg_channel =3D c->options.msg_channel; - msg(D_ROUTE, "interactive service msg_channel=3D%" PRIuPTR, - (intptr_t) c->options.msg_channel); + msg(D_ROUTE, "interactive service msg_channel=3D%" PRIuPTR, (intpt= r_t)c->options.msg_channel); #endif /* allocate route list structure */ @@ -1969,8 +1905,8 @@ ASSERT(c->c2.link_sockets[0]); if (c->options.routes && c->c1.route_list) { - do_init_route_list(&c->options, c->c1.route_list, - &c->c2.link_sockets[0]->info, c->c2.es, &c-= >net_ctx); + do_init_route_list(&c->options, c->c1.route_list, &c->c2.link_= sockets[0]->info, + c->c2.es, &c->net_ctx); } if (c->options.routes_ipv6 && c->c1.route_ipv6_list) { @@ -1979,15 +1915,12 @@ } /* do ifconfig */ - if (!ifconfig_noexec_enabled(c) - && ifconfig_order(c->c1.tuntap) =3D=3D IFCONFIG_BEFORE_TUN_OPE= N) + if (!ifconfig_noexec_enabled(c) && ifconfig_order(c->c1.tuntap) = =3D=3D IFCONFIG_BEFORE_TUN_OPEN) { /* guess actual tun/tap unit number that will be returned * by open_tun */ - const char *guess =3D guess_tuntap_dev(c->options.dev, - c->options.dev_type, - c->options.dev_node, - &gc); + const char *guess =3D + guess_tuntap_dev(c->options.dev, c->options.dev_type, c->o= ptions.dev_node, &gc); do_ifconfig(c->c1.tuntap, guess, c->c2.frame.tun_mtu, c->c2.es= , &c->net_ctx); } @@ -2019,31 +1952,23 @@ } /* do ifconfig */ - if (!ifconfig_noexec_enabled(c) - && ifconfig_order(c->c1.tuntap) =3D=3D IFCONFIG_AFTER_TUN_OPEN) + if (!ifconfig_noexec_enabled(c) && ifconfig_order(c->c1.tuntap) = =3D=3D IFCONFIG_AFTER_TUN_OPEN) { - do_ifconfig(c->c1.tuntap, c->c1.tuntap->actual_name, - c->c2.frame.tun_mtu, c->c2.es, &c->net_ctx); + do_ifconfig(c->c1.tuntap, c->c1.tuntap->actual_name, c->c2.fra= me.tun_mtu, c->c2.es, + &c->net_ctx); } run_dns_up_down(true, &c->options, c->c1.tuntap, &c->persist.duri); /* run the up script */ - run_up_down(c->options.up_script, - c->plugins, - OPENVPN_PLUGIN_UP, - c->c1.tuntap->actual_name, + run_up_down(c->options.up_script, c->plugins, OPENVPN_PLUGIN_UP, c= ->c1.tuntap->actual_name, #ifdef _WIN32 c->c1.tuntap->adapter_index, #endif - dev_type_string(c->options.dev, c->options.dev_type), - c->c2.frame.tun_mtu, + dev_type_string(c->options.dev, c->options.dev_type), = c->c2.frame.tun_mtu, print_in_addr_t(c->c1.tuntap->local, IA_EMPTY_IF_UNDEF= , &gc), - print_in_addr_t(c->c1.tuntap->remote_netmask, IA_EMPTY= _IF_UNDEF, &gc), - "init", - NULL, - "up", - c->c2.es); + print_in_addr_t(c->c1.tuntap->remote_netmask, IA_EMPTY= _IF_UNDEF, &gc), "init", + NULL, "up", c->c2.es); add_wfp_block(c); @@ -2060,8 +1985,7 @@ } else { - msg(M_INFO, "Preserving previous TUN/TAP instance: %s", - c->c1.tuntap->actual_name); + msg(M_INFO, "Preserving previous TUN/TAP instance: %s", c->c1.tunt= ap->actual_name); /* explicitly set the ifconfig_* env vars */ do_ifconfig_setenv(c->c1.tuntap, c->c2.es); @@ -2071,21 +1995,15 @@ /* run the up script if user specified --up-restart */ if (c->options.up_restart) { - run_up_down(c->options.up_script, - c->plugins, - OPENVPN_PLUGIN_UP, + run_up_down(c->options.up_script, c->plugins, OPENVPN_PLUGIN_U= P, c->c1.tuntap->actual_name, #ifdef _WIN32 c->c1.tuntap->adapter_index, #endif - dev_type_string(c->options.dev, c->options.dev_typ= e), - c->c2.frame.tun_mtu, + dev_type_string(c->options.dev, c->options.dev_typ= e), c->c2.frame.tun_mtu, print_in_addr_t(c->c1.tuntap->local, IA_EMPTY_IF_U= NDEF, &gc), print_in_addr_t(c->c1.tuntap->remote_netmask, IA_E= MPTY_IF_UNDEF, &gc), - "restart", - NULL, - "up", - c->c2.es); + "restart", NULL, "up", c->c2.es); } add_wfp_block(c); @@ -2101,8 +2019,7 @@ static void do_close_tun_simple(struct context *c) { - msg(D_CLOSE, "Closing %s interface", - print_tun_backend_driver(c->c1.tuntap->backend_driver)); + msg(D_CLOSE, "Closing %s interface", print_tun_backend_driver(c->c1.tu= ntap->backend_driver)); if (c->c1.tuntap) { @@ -2174,26 +2091,18 @@ /* delete any routes we added */ if (c->c1.route_list || c->c1.route_ipv6_list) { - run_up_down(c->options.route_predown_script, - c->plugins, - OPENVPN_PLUGIN_ROUTE_PREDOWN, + run_up_down(c->options.route_predown_script, c->plugins, OPENV= PN_PLUGIN_ROUTE_PREDOWN, tuntap_actual, #ifdef _WIN32 adapter_index, #endif - NULL, - c->c2.frame.tun_mtu, - print_in_addr_t(local, IA_EMPTY_IF_UNDEF, &gc), - print_in_addr_t(remote_netmask, IA_EMPTY_IF_UNDEF,= &gc), - "init", - signal_description(c->sig->signal_received, - c->sig->signal_text), - "route-pre-down", - c->c2.es); + NULL, c->c2.frame.tun_mtu, print_in_addr_t(local, = IA_EMPTY_IF_UNDEF, &gc), + print_in_addr_t(remote_netmask, IA_EMPTY_IF_UNDEF,= &gc), "init", + signal_description(c->sig->signal_received, c->sig= ->signal_text), + "route-pre-down", c->c2.es); - delete_routes(c->c1.route_list, c->c1.route_ipv6_list, - c->c1.tuntap, ROUTE_OPTION_FLAGS(&c->options), - c->c2.es, &c->net_ctx); + delete_routes(c->c1.route_list, c->c1.route_ipv6_list, c->c1.t= untap, + ROUTE_OPTION_FLAGS(&c->options), c->c2.es, &c->n= et_ctx); } /* actually close tun/tap device based on --down-pre flag */ @@ -2204,21 +2113,13 @@ /* Run the down script -- note that it will run at reduced * privilege if, for example, "--user" was used. */ - run_up_down(c->options.down_script, - c->plugins, - OPENVPN_PLUGIN_DOWN, - tuntap_actual, + run_up_down(c->options.down_script, c->plugins, OPENVPN_PLUGIN_DOW= N, tuntap_actual, #ifdef _WIN32 adapter_index, #endif - NULL, - c->c2.frame.tun_mtu, - print_in_addr_t(local, IA_EMPTY_IF_UNDEF, &gc), - print_in_addr_t(remote_netmask, IA_EMPTY_IF_UNDEF, &gc= ), - "init", - signal_description(c->sig->signal_received, - c->sig->signal_text), - "down", + NULL, c->c2.frame.tun_mtu, print_in_addr_t(local, IA_E= MPTY_IF_UNDEF, &gc), + print_in_addr_t(remote_netmask, IA_EMPTY_IF_UNDEF, &gc= ), "init", + signal_description(c->sig->signal_received, c->sig->si= gnal_text), "down", c->c2.es); del_wfp_block(c, adapter_index); @@ -2234,21 +2135,13 @@ /* run the down script on this restart if --up-restart was specifi= ed */ if (c->options.up_restart) { - run_up_down(c->options.down_script, - c->plugins, - OPENVPN_PLUGIN_DOWN, - tuntap_actual, + run_up_down(c->options.down_script, c->plugins, OPENVPN_PLUGIN= _DOWN, tuntap_actual, #ifdef _WIN32 adapter_index, #endif - NULL, - c->c2.frame.tun_mtu, - print_in_addr_t(local, IA_EMPTY_IF_UNDEF, &gc), - print_in_addr_t(remote_netmask, IA_EMPTY_IF_UNDEF,= &gc), - "restart", - signal_description(c->sig->signal_received, - c->sig->signal_text), - "down", + NULL, c->c2.frame.tun_mtu, print_in_addr_t(local, = IA_EMPTY_IF_UNDEF, &gc), + print_in_addr_t(remote_netmask, IA_EMPTY_IF_UNDEF,= &gc), "restart", + signal_description(c->sig->signal_received, c->sig= ->signal_text), "down", c->c2.es); } @@ -2277,10 +2170,9 @@ * equal, or either one is all-zeroes. */ static bool -options_hash_changed_or_zero(const struct sha256_digest *a, - const struct sha256_digest *b) +options_hash_changed_or_zero(const struct sha256_digest *a, const struct s= ha256_digest *b) { - const struct sha256_digest zero =3D {{0}}; + const struct sha256_digest zero =3D { { 0 } }; return memcmp(a, b, sizeof(struct sha256_digest)) || !memcmp(a, &zero, sizeof(struct sha256_digest)); } @@ -2316,13 +2208,12 @@ if (cipher_kt_mode_aead(o->ciphername)) { - buf_printf(&out, "Data Channel: cipher '%s'", - cipher_kt_name(o->ciphername)); + buf_printf(&out, "Data Channel: cipher '%s'", cipher_kt_name(o->ci= phername)); } else { - buf_printf(&out, "Data Channel: cipher '%s', auth '%s'", - cipher_kt_name(o->ciphername), md_kt_name(o->authname)); + buf_printf(&out, "Data Channel: cipher '%s', auth '%s'", cipher_kt= _name(o->ciphername), + md_kt_name(o->authname)); } if (o->use_peer_id) @@ -2393,8 +2284,7 @@ if (c->options.ce.explicit_exit_notification) { - buf_printf(&out, "explicit-exit-notify %d", - c->options.ce.explicit_exit_notification); + buf_printf(&out, "explicit-exit-notify %d", c->options.ce.explicit= _exit_notification); } if (c->options.imported_protocol_flags) { @@ -2446,10 +2336,8 @@ #endif struct tls_session *session =3D &c->c2.tls_multi->session[TM_ACTIVE]; - if (!tls_session_update_crypto_params(c->c2.tls_multi, session, - &c->options, &c->c2.frame, - frame_fragment, - get_link_socket_info(c), + if (!tls_session_update_crypto_params(c->c2.tls_multi, session, &c->op= tions, &c->c2.frame, + frame_fragment, get_link_socket_= info(c), &c->c1.tuntap->dco)) { msg(D_TLS_ERRORS, "OPTIONS ERROR: failed to import crypto options"= ); @@ -2486,14 +2374,13 @@ * Was tun interface object persisted from previous restart it= eration, * and if so did pulled options string change from previous it= eration? */ - if (!c->c2.did_open_tun - && PULL_DEFINED(&c->options) - && c->c1.tuntap + if (!c->c2.did_open_tun && PULL_DEFINED(&c->options) && c->c1.= tuntap && options_hash_changed_or_zero(&c->c1.pulled_options_dige= st_save, &c->c2.pulled_options_dige= st)) { /* if so, close tun, delete routes, then reinitialize tun = and add routes */ - msg(M_INFO, "NOTE: Pulled options changed on restart, will= need to close and reopen TUN/TAP device."); + msg(M_INFO, + "NOTE: Pulled options changed on restart, will need to= close and reopen TUN/TAP device."); bool tt_dco_win =3D tuntap_is_dco_win(c->c1.tuntap); do_close_tun(c, true); @@ -2519,7 +2406,8 @@ * reconnects to setup various things (like DCO and NCP cipher) that * might have changed from the previous connection. */ - if (!c->c2.do_up_ran || (c->c2.tls_multi && c->c2.tls_multi->multi_sta= te =3D=3D CAS_RECONNECT_PENDING)) + if (!c->c2.do_up_ran + || (c->c2.tls_multi && c->c2.tls_multi->multi_state =3D=3D CAS_REC= ONNECT_PENDING)) { if (c->mode =3D=3D MODE_POINT_TO_POINT) { @@ -2567,7 +2455,8 @@ if ((route_order(c->c1.tuntap) =3D=3D ROUTE_AFTER_TUN) && c->o= ptions.route_delay_defined) { event_timeout_init(&c->c2.route_wakeup, c->options.route_d= elay, now); - event_timeout_init(&c->c2.route_wakeup_expire, c->options.= route_delay + c->options.route_delay_window, now); + event_timeout_init(&c->c2.route_wakeup_expire, + c->options.route_delay + c->options.rou= te_delay_window, now); tun_standby_init(c->c1.tuntap); } else @@ -2630,7 +2519,8 @@ if ((route_order(c->c1.tuntap) =3D=3D ROUTE_AFTER_TUN) && c->optio= ns.route_delay_defined) { event_timeout_init(&c->c2.route_wakeup, c->options.route_delay= , now); - event_timeout_init(&c->c2.route_wakeup_expire, c->options.rout= e_delay + c->options.route_delay_window, now); + event_timeout_init(&c->c2.route_wakeup_expire, + c->options.route_delay + c->options.route_d= elay_window, now); tun_standby_init(c->c1.tuntap); } @@ -2648,23 +2538,10 @@ unsigned int pull_permission_mask(const struct context *c) { - unsigned int flags =3D - OPT_P_UP - | OPT_P_ROUTE_EXTRAS - | OPT_P_SOCKBUF - | OPT_P_SOCKFLAGS - | OPT_P_SETENV - | OPT_P_SHAPER - | OPT_P_TIMER - | OPT_P_COMP - | OPT_P_PERSIST - | OPT_P_MESSAGES - | OPT_P_EXPLICIT_NOTIFY - | OPT_P_ECHO - | OPT_P_PULL_MODE - | OPT_P_PEER_ID - | OPT_P_NCP - | OPT_P_PUSH_MTU; + unsigned int flags =3D OPT_P_UP | OPT_P_ROUTE_EXTRAS | OPT_P_SOCKBUF |= OPT_P_SOCKFLAGS + | OPT_P_SETENV | OPT_P_SHAPER | OPT_P_TIMER | OPT= _P_COMP | OPT_P_PERSIST + | OPT_P_MESSAGES | OPT_P_EXPLICIT_NOTIFY | OPT_P_= ECHO | OPT_P_PULL_MODE + | OPT_P_PEER_ID | OPT_P_NCP | OPT_P_PUSH_MTU; if (!c->options.route_nopull) { @@ -2686,8 +2563,8 @@ struct tls_session *session =3D &c->c2.tls_multi->session[TM_ACTIVE]; - const char *ncp_cipher =3D get_p2p_ncp_cipher(session, c->c2.tls_multi= ->peer_info, - &c->options.gc); + const char *ncp_cipher =3D + get_p2p_ncp_cipher(session, c->c2.tls_multi->peer_info, &c->option= s.gc); if (ncp_cipher) { @@ -2696,8 +2573,8 @@ else if (!c->options.enable_ncp_fallback) { msg(D_TLS_ERRORS, "ERROR: failed to negotiate cipher with peer and= " - "--data-ciphers-fallback not enabled. No usable " - "data channel cipher"); + "--data-ciphers-fallback not enabled. No usable " + "data channel cipher"); return false; } @@ -2709,9 +2586,8 @@ } #endif - if (!tls_session_update_crypto_params(c->c2.tls_multi, session, &c->op= tions, - &c->c2.frame, frame_fragment, - get_link_socket_info(c), + if (!tls_session_update_crypto_params(c->c2.tls_multi, session, &c->op= tions, &c->c2.frame, + frame_fragment, get_link_socket_= info(c), &c->c1.tuntap->dco)) { msg(D_TLS_ERRORS, "ERROR: failed to set crypto cipher"); @@ -2725,7 +2601,7 @@ { if (found & OPT_P_MESSAGES) { - init_verb_mute(c, IVM_LEVEL_1|IVM_LEVEL_2); + init_verb_mute(c, IVM_LEVEL_1 | IVM_LEVEL_2); msg(D_PUSH, "OPTIONS IMPORT: --verb and/or --mute level changed"); } if (found & OPT_P_TIMER) @@ -2754,9 +2630,9 @@ if (!check_compression_settings_valid(&c->options.comp, D_PUSH_ERR= ORS)) { msg(D_PUSH_ERRORS, "OPTIONS ERROR: server pushed compression " - "settings that are not allowed and will result " - "in a non-working connection. " - "See also allow-compression in the manual."); + "settings that are not allowed and will res= ult " + "in a non-working connection. " + "See also allow-compression in the manual."= ); return false; } #ifdef USE_COMP @@ -2778,8 +2654,7 @@ for (int i =3D 0; i < c->c1.link_sockets_num; i++) { - link_socket_update_buffer_sizes(c->c2.link_sockets[i], - c->options.rcvbuf, + link_socket_update_buffer_sizes(c->c2.link_sockets[i], c->opti= ons.rcvbuf, c->options.sndbuf); } } @@ -2789,8 +2664,7 @@ msg(D_PUSH, "OPTIONS IMPORT: --socket-flags option modified"); for (int i =3D 0; i < c->c1.link_sockets_num; i++) { - link_socket_update_flags(c->c2.link_sockets[i], - c->options.sockflags); + link_socket_update_flags(c->c2.link_sockets[i], c->options.soc= kflags); } } @@ -2838,12 +2712,11 @@ } /* Check if pushed options are compatible with DCO, if enabled */ - if (dco_enabled(&c->options) - && !dco_check_pull_options(D_PUSH_ERRORS, &c->options)) + if (dco_enabled(&c->options) && !dco_check_pull_options(D_PUSH_ERR= ORS, &c->options)) { msg(D_PUSH_ERRORS, "OPTIONS ERROR: pushed options are incompat= ible " - "with data channel offload. Use --disable-dco to connect t= o " - "this server"); + "with data channel offload. Use --disable-d= co to connect to " + "this server"); return false; } } @@ -2856,7 +2729,7 @@ if (epoch_data && !datav2_enabled) { msg(D_PUSH_ERRORS, "OPTIONS ERROR: Epoch key data format tag requi= res " - "data v2 (peer-id) to be enabled."); + "data v2 (peer-id) to be enabled."); return false; } @@ -2871,7 +2744,8 @@ if (c->options.ce.tun_mtu > frame->tun_max_mtu) { - msg(D_PUSH_ERRORS, "Server-pushed tun-mtu is too large, please= add " + msg(D_PUSH_ERRORS, + "Server-pushed tun-mtu is too large, please add " "tun-mtu-max %d in the client configuration", c->options.ce.tun_mtu); } @@ -2935,8 +2809,7 @@ } /* Slow down reconnection after 5 retries per remote -- for TCP client= or UDP tls-client only */ - if (c->mode =3D=3D CM_CHILD_TCP - || (c->options.ce.proto =3D=3D PROTO_UDP && c->options.tls_client)) + if (c->mode =3D=3D CM_CHILD_TCP || (c->options.ce.proto =3D=3D PROTO_U= DP && c->options.tls_client)) { backoff =3D (c->options.unsuccessful_attempts / c->options.connect= ion_list->len) - 4; if (backoff > 0) @@ -3005,10 +2878,8 @@ ASSERT(o->ce.link_mtu_defined); /* if we have a link mtu defined we calculate what the old code * would have come up with as tun-mtu */ - size_t overhead =3D frame_calculate_protocol_header_size(&c->c1.ks= .key_type, - o, true); + size_t overhead =3D frame_calculate_protocol_header_size(&c->c1.ks= .key_type, o, true); mtu =3D o->ce.link_mtu - overhead; - } else { @@ -3093,7 +2964,8 @@ size_t tailroom =3D headroom; #ifdef USE_COMP - msg(D_MTU_DEBUG, "MTU: adding %zu buffer tailroom for compression for = %zu " + msg(D_MTU_DEBUG, + "MTU: adding %zu buffer tailroom for compression for %zu " "bytes of payload", COMP_EXTRA_BUFFER(payload_size), payload_size); tailroom +=3D COMP_EXTRA_BUFFER(payload_size); @@ -3162,14 +3034,11 @@ } /* Initialize packet ID tracking */ - packet_id_init(&c->c2.crypto_options.packet_id, - options->replay_window, - options->replay_time, + packet_id_init(&c->c2.crypto_options.packet_id, options->replay_window= , options->replay_time, "STATIC", 0); c->c2.crypto_options.pid_persist =3D &c->c1.pid_persist; c->c2.crypto_options.flags |=3D CO_PACKET_ID_LONG_FORM; - packet_id_persist_load_obj(&c->c1.pid_persist, - &c->c2.crypto_options.packet_id); + packet_id_persist_load_obj(&c->c1.pid_persist, &c->c2.crypto_options.p= acket_id); if (!key_ctx_bi_defined(&c->c1.ks.static_key)) { @@ -3179,10 +3048,8 @@ /* Read cipher and hmac keys from shared secret file */ crypto_read_openvpn_key(&c->c1.ks.key_type, &c->c1.ks.static_key, - options->shared_secret_file, - options->shared_secret_file_inline, - options->key_direction, "Static Key Encryp= tion", - "secret", NULL); + options->shared_secret_file, options->shar= ed_secret_file_inline, + options->key_direction, "Static Key Encryp= tion", "secret", NULL); } else { @@ -3210,26 +3077,23 @@ c->c1.ks.tls_auth_key_type.digest =3D options->authname; if (!md_valid(options->authname)) { - msg(M_FATAL, "ERROR: tls-auth enabled, but no valid --auth " - "algorithm specified ('%s')", options->authname); + msg(M_FATAL, + "ERROR: tls-auth enabled, but no valid --auth " + "algorithm specified ('%s')", + options->authname); } - crypto_read_openvpn_key(&c->c1.ks.tls_auth_key_type, - &c->c1.ks.tls_wrap_key, - options->ce.tls_auth_file, - options->ce.tls_auth_file_inline, - options->ce.key_direction, - "Control Channel Authentication", "tls-aut= h", - &c->c1.ks.original_wrap_keydata); + crypto_read_openvpn_key(&c->c1.ks.tls_auth_key_type, &c->c1.ks.tls= _wrap_key, + options->ce.tls_auth_file, options->ce.tls= _auth_file_inline, + options->ce.key_direction, "Control Channe= l Authentication", + "tls-auth", &c->c1.ks.original_wrap_keydat= a); } /* TLS handshake encryption+authentication (--tls-crypt) */ if (options->ce.tls_crypt_file) { - tls_crypt_init_key(&c->c1.ks.tls_wrap_key, - &c->c1.ks.original_wrap_keydata, - options->ce.tls_crypt_file, - options->ce.tls_crypt_file_inline, + tls_crypt_init_key(&c->c1.ks.tls_wrap_key, &c->c1.ks.original_wrap= _keydata, + options->ce.tls_crypt_file, options->ce.tls_cry= pt_file_inline, options->tls_server); } @@ -3238,16 +3102,14 @@ { if (options->tls_server) { - tls_crypt_v2_init_server_key(&c->c1.ks.tls_crypt_v2_server_key, - true, options->ce.tls_crypt_v2_fi= le, + tls_crypt_v2_init_server_key(&c->c1.ks.tls_crypt_v2_server_key= , true, + options->ce.tls_crypt_v2_file, options->ce.tls_crypt_v2_file_inl= ine); } else { - tls_crypt_v2_init_client_key(&c->c1.ks.tls_wrap_key, - &c->c1.ks.original_wrap_keydata, - &c->c1.ks.tls_crypt_v2_wkc, - options->ce.tls_crypt_v2_file, + tls_crypt_v2_init_client_key(&c->c1.ks.tls_wrap_key, &c->c1.ks= .original_wrap_keydata, + &c->c1.ks.tls_crypt_v2_wkc, optio= ns->ce.tls_crypt_v2_file, options->ce.tls_crypt_v2_file_inl= ine); } /* We have to ensure that the loaded tls-crypt key is small enough @@ -3259,15 +3121,14 @@ if (required_size > c->options.ce.tls_mtu) { - msg(M_WARN, "ERROR: tls-crypt-v2 client key too large to work = with " + msg(M_WARN, + "ERROR: tls-crypt-v2 client key too large to work with " "requested --max-packet-size %d, requires at least " "--max-packet-size %d. Packets will ignore requested " - "maximum packet size", c->options.ce.tls_mtu, - required_size); + "maximum packet size", + c->options.ce.tls_mtu, required_size); } } - - } /* @@ -3296,7 +3157,7 @@ case AR_INTERACT: ssl_purge_auth(false); - /* Intentional [[fallthrough]]; */ + /* Intentional [[fallthrough]]; */ case AR_NOINTERACT: /* SOFT-SIGUSR1 -- Password failure error */ @@ -3337,8 +3198,7 @@ /* Do not warn if the cipher is used only in OCC */ bool warn =3D options->enable_ncp_fallback; - init_key_type(&c->c1.ks.key_type, ciphername, options->authname, - true, warn); + init_key_type(&c->c1.ks.key_type, ciphername, options->authname, t= rue, warn); /* initialize tls-auth/crypt/crypt-v2 key */ do_init_tls_wrap_key(c); @@ -3346,8 +3206,7 @@ /* initialise auth-token crypto support */ if (c->options.auth_token_generate) { - auth_token_init_secret(&c->c1.ks.auth_token_key, - c->options.auth_token_secret_file, + auth_token_init_secret(&c->c1.ks.auth_token_key, c->options.au= th_token_secret_file, c->options.auth_token_secret_file_inlin= e); } @@ -3425,25 +3284,27 @@ if (options->renegotiate_seconds_min < 0) { /* Add 10% jitter to reneg-sec by default (server side only) */ - int auto_jitter =3D options->mode !=3D MODE_SERVER ? 0 : - get_random() % max_int(options->renegotiate_seco= nds / 10, 1); + int auto_jitter =3D options->mode !=3D MODE_SERVER + ? 0 + : get_random() % max_int(options->renegotiat= e_seconds / 10, 1); to.renegotiate_seconds =3D options->renegotiate_seconds - auto_jit= ter; } else { /* Add user-specified jitter to reneg-sec */ - to.renegotiate_seconds =3D options->renegotiate_seconds - -(get_random() % max_int(options->renegot= iate_seconds - - options->reneg= otiate_seconds_min, 1)); + to.renegotiate_seconds =3D + options->renegotiate_seconds + - (get_random() + % max_int(options->renegotiate_seconds - options->renegotia= te_seconds_min, 1)); } to.single_session =3D options->single_session; to.mode =3D options->mode; to.pull =3D options->pull; - if (options->push_peer_info) /* all there is */ + if (options->push_peer_info) /* all there is */ { to.push_peer_info_detail =3D 3; } - else if (options->pull) /* pull clients send some details = */ + else if (options->pull) /* pull clients send some details */ { to.push_peer_info_detail =3D 2; } @@ -3451,7 +3312,7 @@ { to.push_peer_info_detail =3D 0; } - else /* default: minimal info to allow NCP in P2P mod= e */ + else /* default: minimal info to allow NCP in P2P mode */ { to.push_peer_info_detail =3D 1; } @@ -3554,8 +3415,7 @@ } /* TLS handshake encryption (--tls-crypt) */ - if (options->ce.tls_crypt_file - || (options->ce.tls_crypt_v2_file && options->tls_client)) + if (options->ce.tls_crypt_file || (options->ce.tls_crypt_v2_file && op= tions->tls_client)) { to.tls_wrap.mode =3D TLS_WRAP_CRYPT; } @@ -3613,10 +3473,8 @@ if (c->c2.tls_multi) { tls_multi_init_finalize(c->c2.tls_multi, c->options.ce.tls_mtu); - ASSERT(c->c2.tls_multi->opt.frame.buf.payload_size <=3D - c->c2.frame.buf.payload_size); - frame_print(&c->c2.tls_multi->opt.frame, D_MTU_INFO, - "Control Channel MTU parms"); + ASSERT(c->c2.tls_multi->opt.frame.buf.payload_size <=3D c->c2.fram= e.buf.payload_size); + frame_print(&c->c2.tls_multi->opt.frame, D_MTU_INFO, "Control Chan= nel MTU parms"); /* Keep the max mtu also in the frame of tls multi so it can access * it in push_peer_info */ @@ -3624,9 +3482,9 @@ } if (c->c2.tls_auth_standalone) { - tls_init_control_channel_frame_parameters(&c->c2.tls_auth_standalo= ne->frame, c->options.ce.tls_mtu); - frame_print(&c->c2.tls_auth_standalone->frame, D_MTU_INFO, - "TLS-Auth MTU parms"); + tls_init_control_channel_frame_parameters(&c->c2.tls_auth_standalo= ne->frame, + c->options.ce.tls_mtu); + frame_print(&c->c2.tls_auth_standalone->frame, D_MTU_INFO, "TLS-Au= th MTU parms"); c->c2.tls_auth_standalone->tls_wrap.work =3D alloc_buf_gc(BUF_SIZE= (&c->c2.frame), &c->c2.gc); c->c2.tls_auth_standalone->workbuf =3D alloc_buf_gc(BUF_SIZE(&c->c= 2.frame), &c->c2.gc); } @@ -3642,14 +3500,12 @@ /* Initialise key_type with auth/cipher "none", so the key_type struct= is * valid */ - init_key_type(&c->c1.ks.key_type, "none", "none", - c->options.test_crypto, true); + init_key_type(&c->c1.ks.key_type, "none", "none", c->options.test_cryp= to, true); =20 - msg(M_WARN, - "******* WARNING *******: All encryption and authentication featur= es " - "disabled -- All data will be tunnelled as clear text and will not= be " - "protected against man-in-the-middle changes. " - "PLEASE DO RECONSIDER THIS CONFIGURATION!"); + msg(M_WARN, "******* WARNING *******: All encryption and authenticatio= n features " + "disabled -- All data will be tunnelled as clear text and = will not be " + "protected against man-in-the-middle changes. " + "PLEASE DO RECONSIDER THIS CONFIGURATION!"); } static void @@ -3663,7 +3519,7 @@ { do_init_crypto_tls(c, flags); } - else /* no encryption or authentication. */ + else /* no encryption or authentication. */ { do_init_crypto_none(c); } @@ -3701,7 +3557,8 @@ #ifdef ENABLE_FRAGMENT if (c->options.ce.fragment > 0 && c->options.ce.mssfix > c->options.ce= .fragment) { - msg(M_WARN, "WARNING: if you use --mssfix and --fragment, you shou= ld " + msg(M_WARN, + "WARNING: if you use --mssfix and --fragment, you should " "set --fragment (%d) larger or equal than --mssfix (%d)", c->options.ce.fragment, c->options.ce.mssfix); } @@ -3709,7 +3566,7 @@ && c->options.ce.fragment_encap !=3D c->options.ce.mssfix_encap) { msg(M_WARN, "WARNING: if you use --mssfix and --fragment, you shou= ld " - "use the \"mtu\" flag for both or none of of them."); + "use the \"mtu\" flag for both or none of of them."); } #endif } @@ -3728,34 +3585,39 @@ #ifdef ENABLE_SELINUX || o->selinux_context #endif - ) + ) { if (!o->persist_tun) { - msg(M_WARN, "WARNING: you are using user/group/chroot/setcon w= ithout persist-tun -- this may cause restarts to fail"); + msg(M_WARN, + "WARNING: you are using user/group/chroot/setcon without p= ersist-tun -- this may cause restarts to fail"); } } if (o->chroot_dir && !(o->username && o->groupname)) { - msg(M_WARN, "WARNING: you are using chroot without specifying user= and group -- this may cause the chroot jail to be insecure"); + msg(M_WARN, + "WARNING: you are using chroot without specifying user and gro= up -- this may cause the chroot jail to be insecure"); } if (o->pull && o->ifconfig_local && c->first_time) { - msg(M_WARN, "WARNING: using --pull/--client and --ifconfig togethe= r is probably not what you want"); + msg(M_WARN, + "WARNING: using --pull/--client and --ifconfig together is pro= bably not what you want"); } if (o->server_bridge_defined || o->server_bridge_proxy_dhcp) { - msg(M_WARN, "NOTE: when bridging your LAN adapter with the TAP ada= pter, note that the new bridge adapter will often take on its own IP addres= s that is different from what the LAN adapter was previously set to"); + msg(M_WARN, + "NOTE: when bridging your LAN adapter with the TAP adapter, no= te that the new bridge adapter will often take on its own IP address that i= s different from what the LAN adapter was previously set to"); } if (o->mode =3D=3D MODE_SERVER) { if (o->duplicate_cn && o->client_config_dir) { - msg(M_WARN, "WARNING: using --duplicate-cn and --client-config= -dir together is probably not what you want"); + msg(M_WARN, + "WARNING: using --duplicate-cn and --client-config-dir tog= ether is probably not what you want"); } if (o->duplicate_cn && o->ifconfig_pool_persist_filename) { @@ -3771,14 +3633,12 @@ { warn_on_use_of_common_subnets(&c->net_ctx); } - if (o->tls_client - && !o->tls_verify - && o->verify_x509_type =3D=3D VERIFY_X509_NONE - && !(o->ns_cert_type & NS_CERT_CHECK_SERVER) - && !o->remote_cert_eku + if (o->tls_client && !o->tls_verify && o->verify_x509_type =3D=3D VERI= FY_X509_NONE + && !(o->ns_cert_type & NS_CERT_CHECK_SERVER) && !o->remote_cert_eku && !(o->verify_hash_depth =3D=3D 0 && o->verify_hash)) { - msg(M_WARN, "WARNING: No server certificate verification method ha= s been enabled. See http://openvpn.net/howto.html#mitm for more info."); + msg(M_WARN, + "WARNING: No server certificate verification method has been e= nabled. See http://openvpn.net/howto.html#mitm for more info."); } if (o->ns_cert_type) { @@ -3790,15 +3650,19 @@ { if (script_security() >=3D SSEC_SCRIPTS) { - msg(M_WARN, "NOTE: the current --script-security setting may a= llow this configuration to call user-defined scripts"); + msg(M_WARN, + "NOTE: the current --script-security setting may allow thi= s configuration to call user-defined scripts"); } else if (script_security() >=3D SSEC_PW_ENV) { - msg(M_WARN, "WARNING: the current --script-security setting ma= y allow passwords to be passed to scripts via environmental variables"); + msg(M_WARN, + "WARNING: the current --script-security setting may allow = passwords to be passed to scripts via environmental variables"); } else { - msg(M_WARN, "NOTE: starting with " PACKAGE_NAME " 2.1, '--scri= pt-security 2' or higher is required to call user-defined scripts or execut= ables"); + msg(M_WARN, + "NOTE: starting with " PACKAGE_NAME + " 2.1, '--script-security 2' or higher is required to call= user-defined scripts or executables"); } } } @@ -3877,8 +3741,8 @@ */ c->c2.frame_fragment =3D c->c2.frame; - frame_calculate_dynamic(&c->c2.frame_fragment, &c->c1.ks.key_type, - &c->options, get_link_socket_info(c)); + frame_calculate_dynamic(&c->c2.frame_fragment, &c->c1.ks.key_type, &c-= >options, + get_link_socket_info(c)); fragment_frame_init(c->c2.fragment, &c->c2.frame_fragment); } #endif @@ -3891,8 +3755,7 @@ { ASSERT(!c->c2.link_sockets); - ALLOC_ARRAY_GC(c->c2.link_sockets, struct link_socket *, - c->c1.link_sockets_num, &c->c2.gc); + ALLOC_ARRAY_GC(c->c2.link_sockets, struct link_socket *, c->c1.link_so= ckets_num, &c->c2.gc); for (int i =3D 0; i < c->c1.link_sockets_num; i++) { @@ -3955,8 +3818,7 @@ #ifdef ENABLE_FRAGMENT if (c->c2.fragment) { - frame_print(&c->c2.frame_fragment, D_MTU_INFO, - "Fragmentation MTU parms"); + frame_print(&c->c2.frame_fragment, D_MTU_INFO, "Fragmentation MTU = parms"); } #endif } @@ -3970,23 +3832,18 @@ struct gc_arena gc =3D gc_new(); c->c2.options_string_local =3D - options_string(&c->options, &c->c2.frame, c->c1.tuntap, &c->net_ct= x, - false, &gc); + options_string(&c->options, &c->c2.frame, c->c1.tuntap, &c->net_ct= x, false, &gc); c->c2.options_string_remote =3D - options_string(&c->options, &c->c2.frame, c->c1.tuntap, &c->net_ct= x, - true, &gc); + options_string(&c->options, &c->c2.frame, c->c1.tuntap, &c->net_ct= x, true, &gc); msg(D_SHOW_OCC, "Local Options String (VER=3D%s): '%s'", - options_string_version(c->c2.options_string_local, &gc), - c->c2.options_string_local); + options_string_version(c->c2.options_string_local, &gc), c->c2.opt= ions_string_local); msg(D_SHOW_OCC, "Expected Remote Options String (VER=3D%s): '%s'", - options_string_version(c->c2.options_string_remote, &gc), - c->c2.options_string_remote); + options_string_version(c->c2.options_string_remote, &gc), c->c2.op= tions_string_remote); if (c->c2.tls_multi) { - tls_multi_init_set_options(c->c2.tls_multi, - c->c2.options_string_local, + tls_multi_init_set_options(c->c2.tls_multi, c->c2.options_string_l= ocal, c->c2.options_string_remote); } @@ -4010,10 +3867,8 @@ /* get user and/or group that we want to setuid/setgid to, * sets also platform_x_state */ - bool group_defined =3D platform_group_get(c->options.groupname, - &c0->platform_state_group= ); - bool user_defined =3D platform_user_get(c->options.username, - &c0->platform_state_user); + bool group_defined =3D platform_group_get(c->options.groupname, &c= 0->platform_state_group); + bool user_defined =3D platform_user_get(c->options.username, &c0->= platform_state_user); c0->uid_gid_specified =3D user_defined || group_defined; @@ -4122,16 +3977,13 @@ * reconnect to the same host again or there are still addresses that = need * to be tried */ if (!(c->sig->signal_received =3D=3D SIGUSR1 - && ( (c->options.persist_remote_ip) - || - ( c->sig->source !=3D SIG_SOURCE_HARD - && ((c->c1.link_socket_addrs[0].current_remote - && c->c1.link_socket_addrs[0].current_remote->ai_nex= t) - || c->options.no_advance)) - ))) + && ((c->options.persist_remote_ip) + || (c->sig->source !=3D SIG_SOURCE_HARD + && ((c->c1.link_socket_addrs[0].current_remote + && c->c1.link_socket_addrs[0].current_remote->ai_ne= xt) + || c->options.no_advance))))) { - clear_remote_addrlist(&c->c1.link_socket_addrs[0], - !c->options.resolve_in_advance); + clear_remote_addrlist(&c->c1.link_socket_addrs[0], !c->options.res= olve_in_advance); } /* Clear the remote actual address when persist_remote_ip is not in us= e */ @@ -4147,8 +3999,7 @@ { for (int i =3D 0; i < c->c1.link_sockets_num; i++) { - if (c->c1.link_socket_addrs[i].bind_local - && !c->options.resolve_in_advance) + if (c->c1.link_socket_addrs[i].bind_local && !c->options.resol= ve_in_advance) { freeaddrinfo(c->c1.link_socket_addrs[i].bind_local); } @@ -4192,8 +4043,7 @@ */ static void -do_event_set_init(struct context *c, - bool need_us_timeout) +do_event_set_init(struct context *c, bool need_us_timeout) { unsigned int flags =3D 0; @@ -4230,11 +4080,9 @@ { if (!c->c1.status_output) { - c->c1.status_output =3D status_open(c->options.status_file, - c->options.status_file_update_fr= eq, - -1, - NULL, - STATUS_OUTPUT_WRITE); + c->c1.status_output =3D + status_open(c->options.status_file, c->options.status_file_upd= ate_freq, -1, NULL, + STATUS_OUTPUT_WRITE); c->c1.status_output_owned =3D true; } } @@ -4261,8 +4109,9 @@ { if (!c->c1.ifconfig_pool_persist && c->options.ifconfig_pool_persist_f= ilename) { - c->c1.ifconfig_pool_persist =3D ifconfig_pool_persist_init(c->opti= ons.ifconfig_pool_persist_filename, - c->option= s.ifconfig_pool_persist_refresh_freq); + c->c1.ifconfig_pool_persist =3D + ifconfig_pool_persist_init(c->options.ifconfig_pool_persist_fi= lename, + c->options.ifconfig_pool_persist_re= fresh_freq); c->c1.ifconfig_pool_persist_owned =3D true; } } @@ -4376,12 +4225,9 @@ unsigned int option_types_found =3D 0; if (config.list[i] && config.list[i]->value) { - options_string_import(&c->options, - config.list[i]->value, - D_IMPORT_ERRORS|M_OPTERR, - OPT_P_DEFAULT & ~OPT_P_PLUGI= N, - &option_types_found, - c->es); + options_string_import( + &c->options, config.list[i]->value, D_IMPORT_E= RRORS | M_OPTERR, + OPT_P_DEFAULT & ~OPT_P_PLUGIN, &option_types_f= ound, c->es); } } } @@ -4422,7 +4268,7 @@ static void management_callback_status_p2p(void *arg, const int version, struct status= _output *so) { - struct context *c =3D (struct context *) arg; + struct context *c =3D (struct context *)arg; print_status(c, so); } @@ -4455,7 +4301,7 @@ */ int socketfd =3D -1; - struct context *c =3D (struct context *) arg; + struct context *c =3D (struct context *)arg; if (!c->c2.link_sockets || !c->c2.link_sockets[0]) { return -1; @@ -4536,24 +4382,14 @@ { flags |=3D MF_SERVER; } - if (management_open(management, - c->options.management_addr, - c->options.management_port, - c->options.management_user_pass, - c->options.management_client_user, - c->options.management_client_group, - c->options.management_log_history_cache, - c->options.management_echo_buffer_size, - c->options.management_state_buffer_size, - c->options.remap_sigusr1, - flags)) + if (management_open( + management, c->options.management_addr, c->options.man= agement_port, + c->options.management_user_pass, c->options.management= _client_user, + c->options.management_client_group, c->options.managem= ent_log_history_cache, + c->options.management_echo_buffer_size, c->options.man= agement_state_buffer_size, + c->options.remap_sigusr1, flags)) { - management_set_state(management, - OPENVPN_STATE_CONNECTING, - NULL, - NULL, - NULL, - NULL, + management_set_state(management, OPENVPN_STATE_CONNECTING,= NULL, NULL, NULL, NULL, NULL); } @@ -4932,9 +4768,7 @@ /* close event objects */ do_close_event_set(c); - if (c->mode =3D=3D CM_P2P - || c->mode =3D=3D CM_CHILD_TCP - || c->mode =3D=3D CM_CHILD_UDP + if (c->mode =3D=3D CM_P2P || c->mode =3D=3D CM_CHILD_TCP || c->mode = =3D=3D CM_CHILD_UDP || c->mode =3D=3D CM_TOP) { #ifdef USE_COMP @@ -5002,9 +4836,7 @@ } void -inherit_context_child(struct context *dest, - const struct context *src, - struct link_socket *sock) +inherit_context_child(struct context *dest, const struct context *src, str= uct link_socket *sock) { CLEAR(*dest); @@ -5092,8 +4924,7 @@ } void -inherit_context_top(struct context *dest, - const struct context *src) +inherit_context_top(struct context *dest, const struct context *src) { /* copy parent */ *dest =3D *src; @@ -5221,7 +5052,7 @@ static void * test_crypto_thread(void *arg) { - struct context *c =3D (struct context *) arg; + struct context *c =3D (struct context *)arg; const struct options *options =3D &c->options; ASSERT(options->test_crypto); @@ -5255,7 +5086,7 @@ c.options =3D *o; options_detach(&c.options); c.first_time =3D true; - test_crypto_thread((void *) &c); + test_crypto_thread((void *)&c); return true; } return false; diff --git a/src/openvpn/init.h b/src/openvpn/init.h index 081a295..a807874 100644 --- a/src/openvpn/init.h +++ b/src/openvpn/init.h @@ -45,8 +45,8 @@ void uninit_static(void); -#define IVM_LEVEL_1 (1<<0) -#define IVM_LEVEL_2 (1<<1) +#define IVM_LEVEL_1 (1 << 0) +#define IVM_LEVEL_2 (1 << 1) void init_verb_mute(struct context *c, unsigned int flags); void init_options_dev(struct options *options); @@ -61,7 +61,8 @@ void pre_setup(const struct options *options); -void init_instance_handle_signals(struct context *c, const struct env_set = *env, const unsigned int flags); +void init_instance_handle_signals(struct context *c, const struct env_set = *env, + const unsigned int flags); void init_instance(struct context *c, const struct env_set *env, const uns= igned int flags); @@ -72,8 +73,7 @@ bool do_route(const struct options *options, struct route_list *route_list, struct route_ipv6_list *route_ipv6_list, const struct tuntap= *tt, - const struct plugin_list *plugins, struct env_set *es, - openvpn_net_ctx_t *ctx); + const struct plugin_list *plugins, struct env_set *es, openv= pn_net_ctx_t *ctx); void close_instance(struct context *c); @@ -81,9 +81,7 @@ void context_gc_free(struct context *c); -bool do_up(struct context *c, - bool pulled_options, - unsigned int option_types_found); +bool do_up(struct context *c, bool pulled_options, unsigned int option_typ= es_found); /** * @brief A simplified version of the do_up() function. This function is c= alled @@ -109,17 +107,15 @@ */ bool do_deferred_options(struct context *c, const unsigned int found, cons= t bool is_update); -void inherit_context_child(struct context *dest, - const struct context *src, +void inherit_context_child(struct context *dest, const struct context *src, struct link_socket *sock); -void inherit_context_top(struct context *dest, - const struct context *src); +void inherit_context_top(struct context *dest, const struct context *src); -#define CC_GC_FREE (1<<0) -#define CC_USR1_TO_HUP (1<<1) -#define CC_HARD_USR1_TO_HUP (1<<2) -#define CC_NO_CLOSE (1<<3) +#define CC_GC_FREE (1 << 0) +#define CC_USR1_TO_HUP (1 << 1) +#define CC_HARD_USR1_TO_HUP (1 << 2) +#define CC_NO_CLOSE (1 << 3) void close_context(struct context *c, int sig, unsigned int flags); @@ -127,9 +123,9 @@ void free_context_buffers(struct context_buffers *b); -#define ISC_ERRORS (1<<0) -#define ISC_SERVER (1<<1) -#define ISC_ROUTE_ERRORS (1<<2) +#define ISC_ERRORS (1 << 0) +#define ISC_SERVER (1 << 1) +#define ISC_ROUTE_ERRORS (1 << 2) void initialization_sequence_completed(struct context *c, const unsigned i= nt flags); =20 #ifdef ENABLE_MANAGEMENT diff --git a/src/openvpn/integer.h b/src/openvpn/integer.h index 4a95f4e..b82379e 100644 --- a/src/openvpn/integer.h +++ b/src/openvpn/integer.h @@ -26,13 +26,17 @@ #include "error.h" #ifndef htonll -#define htonll(x) ((1=3D=3Dhtonl(1)) ? (x) : \ - ((uint64_t)htonl((uint32_t)((x) & 0xFFFFFFFF)) << 32) |= htonl((uint32_t)((x) >> 32))) +#define htonll(x) \ + ((1 =3D=3D htonl(1)) \ + ? (x) \ + : ((uint64_t)htonl((uint32_t)((x) & 0xFFFFFFFF)) << 32) | htonl((= uint32_t)((x) >> 32))) #endif #ifndef ntohll -#define ntohll(x) ((1=3D=3Dntohl(1)) ? (x) : \ - ((uint64_t)ntohl((uint32_t)((x) & 0xFFFFFFFF)) << 32) |= ntohl((uint32_t)((x) >> 32))) +#define ntohll(x) \ + ((1 =3D=3D ntohl(1)) \ + ? (x) \ + : ((uint64_t)ntohl((uint32_t)((x) & 0xFFFFFFFF)) << 32) | ntohl((= uint32_t)((x) >> 32))) #endif static inline int @@ -196,10 +200,7 @@ if (index < 0 || index >=3D size) { msg(M_FATAL, "Assertion Failed: Array index=3D%d out of bounds for= array size=3D%d in %s:%d", - index, - size, - file, - line); + index, size, file, line); } return index; } diff --git a/src/openvpn/interval.c b/src/openvpn/interval.c index a2ac4f7..2b35314 100644 --- a/src/openvpn/interval.c +++ b/src/openvpn/interval.c @@ -39,9 +39,7 @@ } bool -event_timeout_trigger(struct event_timeout *et, - struct timeval *tv, - const int et_const_retry) +event_timeout_trigger(struct event_timeout *et, struct timeval *tv, const = int et_const_retry) { if (!et->defined) { @@ -54,8 +52,7 @@ if (wakeup <=3D 0) { #if INTERVAL_DEBUG - dmsg(D_INTERVAL, "EVENT event_timeout_trigger (%d) etcr=3D%d", et-= >n, - et_const_retry); + dmsg(D_INTERVAL, "EVENT event_timeout_trigger (%d) etcr=3D%d", et-= >n, et_const_retry); #endif if (et_const_retry < 0) { @@ -72,8 +69,8 @@ if (tv && wakeup < tv->tv_sec) { #if INTERVAL_DEBUG - dmsg(D_INTERVAL, "EVENT event_timeout_wakeup (%d/%d) etcr=3D%d", - (int) wakeup, et->n, et_const_retry); + dmsg(D_INTERVAL, "EVENT event_timeout_wakeup (%d/%d) etcr=3D%d", (= int)wakeup, et->n, + et_const_retry); #endif tv->tv_sec =3D wakeup; tv->tv_usec =3D 0; diff --git a/src/openvpn/interval.h b/src/openvpn/interval.h index 420a1be..b133c44 100644 --- a/src/openvpn/interval.h +++ b/src/openvpn/interval.h @@ -74,8 +74,7 @@ } if (top->last_action + top->horizon > local_now - || top->last_test_true + top->refresh <=3D local_now - || trigger) + || top->last_test_true + top->refresh <=3D local_now || trigger) { top->last_test_true =3D local_now; #if INTERVAL_DEBUG @@ -134,9 +133,9 @@ struct event_timeout { - bool defined; /**< This timeout is active */ - interval_t n; /**< periodic interval for periodic timeouts */ - time_t last; /**< time of last event */ + bool defined; /**< This timeout is active */ + interval_t n; /**< periodic interval for periodic timeouts */ + time_t last; /**< time of last event */ }; static inline bool @@ -217,7 +216,7 @@ static inline interval_t event_timeout_remaining(struct event_timeout *et) { - return (interval_t) ((et->last + et->n) - now); + return (interval_t)((et->last + et->n) - now); } #define ETT_DEFAULT (-1) @@ -254,19 +253,18 @@ * @param et_const_retry see above * @return if the timeout has triggered and event has bee= n reset */ -bool event_timeout_trigger(struct event_timeout *et, - struct timeval *tv, - int et_const_retry); +bool event_timeout_trigger(struct event_timeout *et, struct timeval *tv, i= nt et_const_retry); /* * Measure time intervals in microseconds */ -#define USEC_TIMER_MAX 60 /* maximum interval size in seconds */ +#define USEC_TIMER_MAX 60 /* maximum interval size in seconds */ #define USEC_TIMER_MAX_USEC (USEC_TIMER_MAX * 1000000) -struct usec_timer { +struct usec_timer +{ struct timeval start; struct timeval end; }; diff --git a/src/openvpn/list.c b/src/openvpn/list.c index 48e549f..f30d540 100644 --- a/src/openvpn/list.c +++ b/src/openvpn/list.c @@ -34,8 +34,7 @@ #include "memdbg.h" struct hash * -hash_init(const int n_buckets, - const uint32_t iv, +hash_init(const int n_buckets, const uint32_t iv, uint32_t (*hash_function)(const void *key, uint32_t iv), bool (*compare_function)(const void *key1, const void *key2)) { @@ -44,7 +43,7 @@ ASSERT(n_buckets > 0); ALLOC_OBJ_CLEAR(h, struct hash); - h->n_buckets =3D (int) adjust_power_of_2(n_buckets); + h->n_buckets =3D (int)adjust_power_of_2(n_buckets); h->mask =3D h->n_buckets - 1; h->hash_function =3D hash_function; h->compare_function =3D compare_function; @@ -79,10 +78,7 @@ } struct hash_element * -hash_lookup_fast(struct hash *hash, - struct hash_bucket *bucket, - const void *key, - uint32_t hv) +hash_lookup_fast(struct hash *hash, struct hash_bucket *bucket, const void= *key, uint32_t hv) { struct hash_element *he; struct hash_element *prev =3D NULL; @@ -110,10 +106,7 @@ } bool -hash_remove_fast(struct hash *hash, - struct hash_bucket *bucket, - const void *key, - uint32_t hv) +hash_remove_fast(struct hash *hash, struct hash_bucket *bucket, const void= *key, uint32_t hv) { struct hash_element *he; struct hash_element *prev =3D NULL; @@ -219,9 +212,7 @@ } void -hash_iterator_init_range(struct hash *hash, - struct hash_iterator *hi, - int start_bucket, +hash_iterator_init_range(struct hash *hash, struct hash_iterator *hi, int = start_bucket, int end_bucket) { if (end_bucket > hash->n_buckets) @@ -242,8 +233,7 @@ } void -hash_iterator_init(struct hash *hash, - struct hash_iterator *hi) +hash_iterator_init(struct hash *hash, struct hash_iterator *hi) { hash_iterator_init_range(hash, hi, 0, hash->n_buckets); } @@ -390,17 +380,35 @@ * -------------------------------------------------------------------- */ -#define mix(a, b, c) \ - { \ - a -=3D b; a -=3D c; a ^=3D (c>>13); \ - b -=3D c; b -=3D a; b ^=3D (a<<8); \ - c -=3D a; c -=3D b; c ^=3D (b>>13); \ - a -=3D b; a -=3D c; a ^=3D (c>>12); \ - b -=3D c; b -=3D a; b ^=3D (a<<16); \ - c -=3D a; c -=3D b; c ^=3D (b>>5); \ - a -=3D b; a -=3D c; a ^=3D (c>>3); \ - b -=3D c; b -=3D a; b ^=3D (a<<10); \ - c -=3D a; c -=3D b; c ^=3D (b>>15); \ +#define mix(a, b, c) \ + { \ + a -=3D b; \ + a -=3D c; \ + a ^=3D (c >> 13); \ + b -=3D c; \ + b -=3D a; \ + b ^=3D (a << 8); \ + c -=3D a; \ + c -=3D b; \ + c ^=3D (b >> 13); \ + a -=3D b; \ + a -=3D c; \ + a ^=3D (c >> 12); \ + b -=3D c; \ + b -=3D a; \ + b ^=3D (a << 16); \ + c -=3D a; \ + c -=3D b; \ + c ^=3D (b >> 5); \ + a -=3D b; \ + a -=3D c; \ + a ^=3D (c >> 3); \ + b -=3D c; \ + b -=3D a; \ + b ^=3D (a << 10); \ + c -=3D a; \ + c -=3D b; \ + c ^=3D (b >> 15); \ } uint32_t @@ -410,21 +418,15 @@ /* Set up the internal state */ len =3D length; - a =3D b =3D 0x9e3779b9; /* the golden ratio; an arbitrary value */ - c =3D initval; /* the previous hash value */ + a =3D b =3D 0x9e3779b9; /* the golden ratio; an arbitrary value */ + c =3D initval; /* the previous hash value */ /*---------------------------------------- handle most of the key */ while (len >=3D 12) { - a +=3D (k[0] + ((uint32_t) k[1] << 8) - + ((uint32_t) k[2] << 16) - + ((uint32_t) k[3] << 24)); - b +=3D (k[4] + ((uint32_t) k[5] << 8) - + ((uint32_t) k[6] << 16) - + ((uint32_t) k[7] << 24)); - c +=3D (k[8] + ((uint32_t) k[9] << 8) - + ((uint32_t) k[10] << 16) - + ((uint32_t) k[11] << 24)); + a +=3D (k[0] + ((uint32_t)k[1] << 8) + ((uint32_t)k[2] << 16) + ((= uint32_t)k[3] << 24)); + b +=3D (k[4] + ((uint32_t)k[5] << 8) + ((uint32_t)k[6] << 16) + ((= uint32_t)k[7] << 24)); + c +=3D (k[8] + ((uint32_t)k[9] << 8) + ((uint32_t)k[10] << 16) + (= (uint32_t)k[11] << 24)); mix(a, b, c); k +=3D 12; len -=3D 12; @@ -432,48 +434,48 @@ /*------------------------------------- handle the last 11 bytes */ c +=3D length; - switch (len) /* all the case statements fall through */ + switch (len) /* all the case statements fall through */ { case 11: - c +=3D ((uint32_t) k[10] << 24); - /* Intentional [[fallthrough]]; */ + c +=3D ((uint32_t)k[10] << 24); + /* Intentional [[fallthrough]]; */ case 10: - c +=3D ((uint32_t) k[9] << 16); - /* Intentional [[fallthrough]]; */ + c +=3D ((uint32_t)k[9] << 16); + /* Intentional [[fallthrough]]; */ case 9: - c +=3D ((uint32_t) k[8] << 8); + c +=3D ((uint32_t)k[8] << 8); /* Intentional [[fallthrough]]; */ /* the first byte of c is reserved for the length */ case 8: - b +=3D ((uint32_t) k[7] << 24); - /* Intentional [[fallthrough]]; */ + b +=3D ((uint32_t)k[7] << 24); + /* Intentional [[fallthrough]]; */ case 7: - b +=3D ((uint32_t) k[6] << 16); - /* Intentional [[fallthrough]]; */ + b +=3D ((uint32_t)k[6] << 16); + /* Intentional [[fallthrough]]; */ case 6: - b +=3D ((uint32_t) k[5] << 8); - /* Intentional [[fallthrough]]; */ + b +=3D ((uint32_t)k[5] << 8); + /* Intentional [[fallthrough]]; */ case 5: b +=3D k[4]; - /* Intentional [[fallthrough]]; */ + /* Intentional [[fallthrough]]; */ case 4: - a +=3D ((uint32_t) k[3] << 24); - /* Intentional [[fallthrough]]; */ + a +=3D ((uint32_t)k[3] << 24); + /* Intentional [[fallthrough]]; */ case 3: - a +=3D ((uint32_t) k[2] << 16); - /* Intentional [[fallthrough]]; */ + a +=3D ((uint32_t)k[2] << 16); + /* Intentional [[fallthrough]]; */ case 2: - a +=3D ((uint32_t) k[1] << 8); - /* Intentional [[fallthrough]]; */ + a +=3D ((uint32_t)k[1] << 8); + /* Intentional [[fallthrough]]; */ case 1: a +=3D k[0]; diff --git a/src/openvpn/list.h b/src/openvpn/list.h index 77807c7..fb3302d 100644 --- a/src/openvpn/list.h +++ b/src/openvpn/list.h @@ -36,8 +36,8 @@ #include "basic.h" #include "buffer.h" -#define hashsize(n) ((uint32_t)1<<(n)) -#define hashmask(n) (hashsize(n)-1) +#define hashsize(n) ((uint32_t)1 << (n)) +#define hashmask(n) (hashsize(n) - 1) struct hash_element { @@ -63,8 +63,7 @@ struct hash_bucket *buckets; }; -struct hash *hash_init(const int n_buckets, - const uint32_t iv, +struct hash *hash_init(const int n_buckets, const uint32_t iv, uint32_t (*hash_function)(const void *key, uint32_t= iv), bool (*compare_function)(const void *key1, const vo= id *key2)); @@ -72,15 +71,10 @@ bool hash_add(struct hash *hash, const void *key, void *value, bool replac= e); -struct hash_element *hash_lookup_fast(struct hash *hash, - struct hash_bucket *bucket, - const void *key, - uint32_t hv); +struct hash_element *hash_lookup_fast(struct hash *hash, struct hash_bucke= t *bucket, + const void *key, uint32_t hv); -bool hash_remove_fast(struct hash *hash, - struct hash_bucket *bucket, - const void *key, - uint32_t hv); +bool hash_remove_fast(struct hash *hash, struct hash_bucket *bucket, const= void *key, uint32_t hv); void hash_remove_by_value(struct hash *hash, void *value); @@ -96,9 +90,7 @@ int bucket_index_end; }; -void hash_iterator_init_range(struct hash *hash, - struct hash_iterator *hi, - int start_bucket, +void hash_iterator_init_range(struct hash *hash, struct hash_iterator *hi,= int start_bucket, int end_bucket); void hash_iterator_init(struct hash *hash, struct hash_iterator *iter); @@ -154,10 +146,7 @@ /* NOTE: assumes that key is not a duplicate */ static inline void -hash_add_fast(struct hash *hash, - struct hash_bucket *bucket, - const void *key, - uint32_t hv, +hash_add_fast(struct hash *hash, struct hash_bucket *bucket, const void *k= ey, uint32_t hv, void *value) { struct hash_element *he; diff --git a/src/openvpn/lladdr.c b/src/openvpn/lladdr.c index cc677b4..d8bcad9 100644 --- a/src/openvpn/lladdr.c +++ b/src/openvpn/lladdr.c @@ -14,8 +14,7 @@ #include "proto.h" int -set_lladdr(openvpn_net_ctx_t *ctx, const char *ifname, const char *lladdr, - const struct env_set *es) +set_lladdr(openvpn_net_ctx_t *ctx, const char *ifname, const char *lladdr,= const struct env_set *es) { int r; @@ -32,27 +31,16 @@ #else /* if defined(TARGET_LINUX) */ struct argv argv =3D argv_new(); #if defined(TARGET_SOLARIS) - argv_printf(&argv, - "%s %s ether %s", - IFCONFIG_PATH, - ifname, lladdr); + argv_printf(&argv, "%s %s ether %s", IFCONFIG_PATH, ifname, lladdr); #elif defined(TARGET_OPENBSD) - argv_printf(&argv, - "%s %s lladdr %s", - IFCONFIG_PATH, - ifname, lladdr); + argv_printf(&argv, "%s %s lladdr %s", IFCONFIG_PATH, ifname, lladdr); #elif defined(TARGET_DARWIN) - argv_printf(&argv, - "%s %s lladdr %s", - IFCONFIG_PATH, - ifname, lladdr); + argv_printf(&argv, "%s %s lladdr %s", IFCONFIG_PATH, ifname, lladdr); #elif defined(TARGET_FREEBSD) - argv_printf(&argv, - "%s %s ether %s", - IFCONFIG_PATH, - ifname, lladdr); + argv_printf(&argv, "%s %s ether %s", IFCONFIG_PATH, ifname, lladdr); #else /* if defined(TARGET_SOLARIS) */ - msg(M_WARN, "Sorry, but I don't know how to configure link layer addre= sses on this operating system."); + msg(M_WARN, + "Sorry, but I don't know how to configure link layer addresses on = this operating system."); return -1; #endif /* if defined(TARGET_SOLARIS) */ argv_msg(M_INFO, &argv); diff --git a/src/openvpn/lzo.c b/src/openvpn/lzo.c index d5f60ca..3a73d5f 100644 --- a/src/openvpn/lzo.c +++ b/src/openvpn/lzo.c @@ -50,9 +50,10 @@ int lzo_status =3D lzo_init(); if (lzo_status !=3D LZO_E_OK) { - msg(M_FATAL, "Cannot initialize LZO compression library (lzo_init(= ) returns %d)", lzo_status); + msg(M_FATAL, "Cannot initialize LZO compression library (lzo_init(= ) returns %d)", + lzo_status); } - compctx->wu.lzo.wmem =3D (lzo_voidp) malloc(compctx->wu.lzo.wmem_size); + compctx->wu.lzo.wmem =3D (lzo_voidp)malloc(compctx->wu.lzo.wmem_size); check_malloc_return(compctx->wu.lzo.wmem); } @@ -64,8 +65,7 @@ } static void -lzo_compress(struct buffer *buf, struct buffer work, - struct compress_context *compctx, +lzo_compress(struct buffer *buf, struct buffer work, struct compress_conte= xt *compctx, const struct frame *frame) { uint8_t *header =3D buf_prepend(buf, 1); @@ -73,13 +73,12 @@ } static void -lzo_decompress(struct buffer *buf, struct buffer work, - struct compress_context *compctx, +lzo_decompress(struct buffer *buf, struct buffer work, struct compress_con= text *compctx, const struct frame *frame) { lzo_uint zlen =3D frame->buf.payload_size; int err; - uint8_t c; /* flag indicating whether or not our peer compres= sed */ + uint8_t c; /* flag indicating whether or not our peer compressed */ if (buf->len <=3D 0) { @@ -94,8 +93,7 @@ if (c =3D=3D LZO_COMPRESS_BYTE) /* packet was compressed */ { ASSERT(buf_safe(&work, zlen)); - err =3D LZO_DECOMPRESS(BPTR(buf), BLEN(buf), BPTR(&work), &zlen, - compctx->wu.lzo.wmem); + err =3D LZO_DECOMPRESS(BPTR(buf), BLEN(buf), BPTR(&work), &zlen, c= ompctx->wu.lzo.wmem); if (err !=3D LZO_E_OK) { dmsg(D_COMP_ERRORS, "LZO decompression error: %d", err); @@ -112,7 +110,7 @@ *buf =3D work; } - else if (c =3D=3D NO_COMPRESS_BYTE) /* packet was not compressed */ + else if (c =3D=3D NO_COMPRESS_BYTE) /* packet was not compressed */ { /* nothing to do */ } @@ -123,11 +121,6 @@ } } -const struct compress_alg lzo_alg =3D { - "lzo", - lzo_compress_init, - lzo_compress_uninit, - lzo_compress, - lzo_decompress -}; +const struct compress_alg lzo_alg =3D { "lzo", lzo_compress_init, lzo_comp= ress_uninit, lzo_compress, + lzo_decompress }; #endif /* ENABLE_LZO */ diff --git a/src/openvpn/lzo.h b/src/openvpn/lzo.h index c47db83..9d4fa30 100644 --- a/src/openvpn/lzo.h +++ b/src/openvpn/lzo.h @@ -56,19 +56,19 @@ extern const struct compress_alg lzo_alg; /*************************************************************************= */ -/** @name LZO library interface defines *//** @{ *//**********************= */ -#define LZO_COMPRESS lzo1x_1_15_compress +/** @name LZO library interface defines */ /** @{ */ /********************= ***/ +#define LZO_COMPRESS lzo1x_1_15_compress /**< LZO library compression function. * * Use \c lzo1x_1_15_compress because it * is described as faster than the * standard routine, although it does * need a bit more memory. */ -#define LZO_WORKSPACE LZO1X_1_15_MEM_COMPRESS +#define LZO_WORKSPACE LZO1X_1_15_MEM_COMPRESS /**< The size in bytes of the memory * %buffer required by the LZO library * compression algorithm. */ -#define LZO_DECOMPRESS lzo1x_decompress_safe +#define LZO_DECOMPRESS lzo1x_decompress_safe /**< LZO library decompression function. * * Use safe decompress because it @@ -78,26 +78,30 @@ * verify the integrity of incoming * packets, you might want to consider * using the non-safe version. */ -/** @} name LZO library interface *//*************************************= */ +/** @} name LZO library interface */ /************************************= **/ /*************************************************************************= */ -/** @name Adaptive compression defines *//** @{ *//***********************= */ -#define AC_SAMP_SEC 2 /**< Number of seconds in a sample period.= */ -#define AC_MIN_BYTES 1000 /**< Minimum number of bytes a sample - * period must contain for it to be - * evaluated. */ -#define AC_SAVE_PCT 5 /**< Minimum size reduction percentage - * below which compression will be - * turned off. */ -#define AC_OFF_SEC 60 /**< Seconds to wait after compression has - * been turned off before retesting. */ -/** @} name Adaptive compression defines *//******************************= */ +/** @name Adaptive compression defines */ /** @{ */ /*********************= ***/ +#define AC_SAMP_SEC 2 /**< Number of seconds= in a sample period. */ +#define AC_MIN_BYTES = \ + 1000 /**< Minimum number of= bytes a sample \ + * period must conta= in for it to be \ + * evaluated. */ +#define AC_SAVE_PCT = \ + 5 /**< Minimum size redu= ction percentage \ + * below which compr= ession will be \ + * turned off. */ +#define AC_OFF_SEC = \ + 60 /**< Seconds to wait a= fter compression has \ + * been turned off b= efore retesting. */ +/** @} name Adaptive compression defines */ /*********************= **********/ /** * Adaptive compression state. */ -struct lzo_adaptive_compress { +struct lzo_adaptive_compress +{ bool compress_state; time_t next; int n_total; diff --git a/src/openvpn/manage.c b/src/openvpn/manage.c index c7bdd5a..aed04f5 100644 --- a/src/openvpn/manage.c +++ b/src/openvpn/manage.c @@ -74,7 +74,8 @@ msg(M_CLIENT, "auth-retry t : Auth failure retry mode (none,= interact,nointeract)."); msg(M_CLIENT, "bytecount n : Show bytes in/out, update ever= y n secs (0=3Doff)."); msg(M_CLIENT, "echo [on|off] [N|all] : Like log, but only show messag= es in echo buffer."); - msg(M_CLIENT, "cr-response response : Send a challenge response answ= er via CR_RESPONSE to server"); + msg(M_CLIENT, + "cr-response response : Send a challenge response answer via CR_= RESPONSE to server"); msg(M_CLIENT, "exit|quit : Close management session."); msg(M_CLIENT, "forget-passwords : Forget passwords entered so fa= r."); msg(M_CLIENT, "help : Print this message."); @@ -85,7 +86,8 @@ msg(M_CLIENT, "load-stats : Show global server load stats.= "); msg(M_CLIENT, "log [on|off] [N|all] : Turn on/off realtime log displ= ay"); msg(M_CLIENT, " + show last N lines or 'all' f= or entire history."); - msg(M_CLIENT, "mute [n] : Set log mute level to n, or sh= ow level if n is absent."); + msg(M_CLIENT, + "mute [n] : Set log mute level to n, or show level i= f n is absent."); msg(M_CLIENT, "needok type action : Enter confirmation for NEED-OK= request of 'type',"); msg(M_CLIENT, " where action =3D 'ok' or 'canc= el'."); msg(M_CLIENT, "needstr type action : Enter confirmation for NEED-ST= R request of 'type',"); @@ -103,18 +105,25 @@ #endif msg(M_CLIENT, "client-auth CID KID : Authenticate client-id/key-id = CID/KID (MULTILINE)"); msg(M_CLIENT, "client-auth-nt CID KID : Authenticate client-id/key-id = CID/KID"); - msg(M_CLIENT, "client-deny CID KID R [CR] : Deny auth client-id/key-id= CID/KID with log reason"); + msg(M_CLIENT, + "client-deny CID KID R [CR] : Deny auth client-id/key-id CID/KID w= ith log reason"); msg(M_CLIENT, " text R and optional client= reason text CR"); - msg(M_CLIENT, "client-pending-auth CID KID MSG timeout : Instruct Open= VPN to send AUTH_PENDING and INFO_PRE msg"); - msg(M_CLIENT, " to the client and= wait for a final client-auth/client-deny"); + msg(M_CLIENT, + "client-pending-auth CID KID MSG timeout : Instruct OpenVPN to sen= d AUTH_PENDING and INFO_PRE msg"); + msg(M_CLIENT, + " to the client and wait for = a final client-auth/client-deny"); msg(M_CLIENT, "client-kill CID [M] : Kill client instance CID with = message M (def=3DRESTART)"); msg(M_CLIENT, "env-filter [level] : Set env-var filter level"); msg(M_CLIENT, "rsa-sig : Enter a signature in response = to >RSA_SIGN challenge"); - msg(M_CLIENT, " Enter signature base64 on subs= equent lines followed by END"); + msg(M_CLIENT, + " Enter signature base64 on subsequent lin= es followed by END"); msg(M_CLIENT, "pk-sig : Enter a signature in response = to >PK_SIGN challenge"); - msg(M_CLIENT, " Enter signature base64 on subs= equent lines followed by END"); - msg(M_CLIENT, "certificate : Enter a client certificate in = response to >NEED-CERT challenge"); - msg(M_CLIENT, " Enter certificate base64 on su= bsequent lines followed by END"); + msg(M_CLIENT, + " Enter signature base64 on subsequent lin= es followed by END"); + msg(M_CLIENT, + "certificate : Enter a client certificate in response t= o >NEED-CERT challenge"); + msg(M_CLIENT, + " Enter certificate base64 on subsequent l= ines followed by END"); msg(M_CLIENT, "signal s : Send signal s to daemon,"); msg(M_CLIENT, " s =3D SIGHUP|SIGTERM|SIGUSR1|S= IGUSR2."); msg(M_CLIENT, "state [on|off] [N|all] : Like log, but show state histo= ry."); @@ -122,7 +131,8 @@ msg(M_CLIENT, "test n : Produce n lines of output for = testing/debugging."); msg(M_CLIENT, "username type u : Enter username u for a queried= OpenVPN username."); msg(M_CLIENT, "verb [n] : Set log verbosity level to n, = or show if n is absent."); - msg(M_CLIENT, "version [n] : Set client's version to n or s= how current version of daemon."); + msg(M_CLIENT, + "version [n] : Set client's version to n or show curren= t version of daemon."); msg(M_CLIENT, "END"); } =20 @@ -305,7 +315,7 @@ man_delete_unix_socket(struct management *man) { #if UNIX_SOCK_SUPPORT - if ((man->settings.flags & (MF_UNIX_SOCK|MF_CONNECT_AS_CLIENT)) =3D=3D= MF_UNIX_SOCK) + if ((man->settings.flags & (MF_UNIX_SOCK | MF_CONNECT_AS_CLIENT)) =3D= =3D MF_UNIX_SOCK) { socket_delete_unix(&man->settings.local_unix); } @@ -331,11 +341,11 @@ static void virtual_output_callback_func(void *arg, const unsigned int flags, const ch= ar *str) { - struct management *man =3D (struct management *) arg; + struct management *man =3D (struct management *)arg; static int recursive_level =3D 0; /* GLOBAL */ -#define AF_DID_PUSH (1<<0) -#define AF_DID_RESET (1<<1) +#define AF_DID_PUSH (1 << 0) +#define AF_DID_RESET (1 << 1) if (recursive_level < 5) /* limit recursion */ { struct gc_arena gc =3D gc_new(); @@ -369,10 +379,10 @@ } else if (man->connection.log_realtime) { - out =3D log_entry_print(&e, LOG_PRINT_INT_DATE - | LOG_PRINT_MSG_FLAGS - | LOG_PRINT_LOG_PREFIX - | LOG_PRINT_CRLF, &gc); + out =3D log_entry_print(&e, + LOG_PRINT_INT_DATE | LOG_PRINT_MSG_F= LAGS + | LOG_PRINT_LOG_PREFIX | LOG_PRI= NT_CRLF, + &gc); } if (out) { @@ -381,11 +391,11 @@ } if (flags & M_FATAL) { - out =3D log_entry_print(&e, LOG_FATAL_NOTIFY|LOG_PRINT_CRL= F, &gc); + out =3D log_entry_print(&e, LOG_FATAL_NOTIFY | LOG_PRINT_C= RLF, &gc); if (out) { man_output_list_push_str(man, out); - action_flags |=3D (AF_DID_PUSH|AF_DID_RESET); + action_flags |=3D (AF_DID_PUSH | AF_DID_RESET); } } } @@ -407,7 +417,8 @@ { /* cannot use msg here */ printf("virtual_output: message to management interface " - "dropped due to recursion: <%s>\n", str); + "dropped due to recursion: <%s>\n", + str); } } @@ -471,7 +482,8 @@ static void man_command_unsupported(const char *command_name) { - msg(M_CLIENT, "ERROR: The '%s' command is not supported by the current= daemon mode", command_name); + msg(M_CLIENT, "ERROR: The '%s' command is not supported by the current= daemon mode", + command_name); } static void @@ -494,8 +506,7 @@ { man->connection.bytecount_update_seconds =3D update_seconds; event_timeout_init(&man->connection.bytecount_update_interval, - man->connection.bytecount_update_seconds, - now); + man->connection.bytecount_update_seconds, now); } else { @@ -506,8 +517,7 @@ } static void -man_bytecount_output_client(struct management *man, - counter_type dco_read_bytes, +man_bytecount_output_client(struct management *man, counter_type dco_read_= bytes, counter_type dco_write_bytes) { char in[32]; @@ -520,8 +530,7 @@ } void -man_bytecount_output_server(const counter_type *bytes_in_total, - const counter_type *bytes_out_total, +man_bytecount_output_server(const counter_type *bytes_in_total, const coun= ter_type *bytes_out_total, struct man_def_auth_context *mdac) { char in[32]; @@ -546,7 +555,7 @@ char p3[128]; int n_killed; - buf_set_read(&buf, (uint8_t *) victim, strlen(victim) + 1); + buf_set_read(&buf, (uint8_t *)victim, strlen(victim) + 1); buf_parse(&buf, ':', p1, sizeof(p1)); buf_parse(&buf, ':', p2, sizeof(p2)); buf_parse(&buf, ':', p3, sizeof(p3)); @@ -555,29 +564,29 @@ { /* IP:port specified */ bool status; - const in_addr_t addr =3D getaddr(GETADDR_HOST_ORDER|GETADDR_MS= G_VIRT_OUT, p2, 0, &status, NULL); + const in_addr_t addr =3D + getaddr(GETADDR_HOST_ORDER | GETADDR_MSG_VIRT_OUT, p2, 0, = &status, NULL); if (status) { const int port =3D atoi(p3); - const int proto =3D (streq(p1, "tcp")) ? PROTO_TCP_SERVER : - (streq(p1, "udp")) ? PROTO_UDP : PROTO_N= ONE; + const int proto =3D (streq(p1, "tcp")) ? PROTO_TCP_SERVER + : (streq(p1, "udp")) ? PROTO_UDP + : PROTO_NONE; if ((port > 0 && port < 65536) && (proto !=3D PROTO_NONE)) { - n_killed =3D (*man->persist.callback.kill_by_addr)(man= ->persist.callback.arg, addr, port, proto); + n_killed =3D (*man->persist.callback.kill_by_addr)(man= ->persist.callback.arg, + addr,= port, proto); if (n_killed > 0) { - msg(M_CLIENT, "SUCCESS: %d client(s) at address %s= :%s:%d killed", - n_killed, - proto2ascii(proto, AF_UNSPEC, false), - print_in_addr_t(addr, 0, &gc), + msg(M_CLIENT, "SUCCESS: %d client(s) at address %s= :%s:%d killed", n_killed, + proto2ascii(proto, AF_UNSPEC, false), print_in= _addr_t(addr, 0, &gc), port); } else { msg(M_CLIENT, "ERROR: client at address %s:%s:%d n= ot found", - proto2ascii(proto, AF_UNSPEC, false), - print_in_addr_t(addr, 0, &gc), + proto2ascii(proto, AF_UNSPEC, false), print_in= _addr_t(addr, 0, &gc), port); } } @@ -622,12 +631,8 @@ * for the log and echo commands. */ static void -man_history(struct management *man, - const char *parm, - const char *type, - struct log_history *log, - bool *realtime, - const unsigned int lep_flags) +man_history(struct management *man, const char *parm, const char *type, st= ruct log_history *log, + bool *realtime, const unsigned int lep_flags) { struct gc_arena gc =3D gc_new(); int n =3D 0; @@ -670,35 +675,22 @@ static void man_log(struct management *man, const char *parm) { - man_history(man, - parm, - "log", - man->persist.log, - &man->connection.log_realtime, - LOG_PRINT_INT_DATE|LOG_PRINT_MSG_FLAGS); + man_history(man, parm, "log", man->persist.log, &man->connection.log_r= ealtime, + LOG_PRINT_INT_DATE | LOG_PRINT_MSG_FLAGS); } static void man_echo(struct management *man, const char *parm) { - man_history(man, - parm, - "echo", - man->persist.echo, - &man->connection.echo_realtime, - LOG_PRINT_INT_DATE|MANAGEMENT_ECHO_FLAGS); + man_history(man, parm, "echo", man->persist.echo, &man->connection.ech= o_realtime, + LOG_PRINT_INT_DATE | MANAGEMENT_ECHO_FLAGS); } static void man_state(struct management *man, const char *parm) { - man_history(man, - parm, - "state", - man->persist.state, - &man->connection.state_realtime, - LOG_PRINT_INT_DATE|LOG_PRINT_STATE - |LOG_PRINT_LOCAL_IP|LOG_PRINT_REMOTE_IP); + man_history(man, parm, "state", man->persist.state, &man->connection.s= tate_realtime, + LOG_PRINT_INT_DATE | LOG_PRINT_STATE | LOG_PRINT_LOCAL_IP = | LOG_PRINT_REMOTE_IP); } static void @@ -732,13 +724,8 @@ } static void -man_query_user_pass(struct management *man, - const char *type, - const char *string, - const bool needed, - const char *prompt, - char *dest, - int len) +man_query_user_pass(struct management *man, const char *type, const char *= string, const bool needed, + const char *prompt, char *dest, int len) { if (needed) { @@ -747,16 +734,12 @@ { strncpynt(dest, string, len); man_up_finalize(man); - msg(M_CLIENT, "SUCCESS: '%s' %s entered, but not yet verified", - type, - prompt); + msg(M_CLIENT, "SUCCESS: '%s' %s entered, but not yet verified"= , type, prompt); } else { - msg(M_CLIENT, "ERROR: %s of type '%s' entered, but we need one= of type '%s'", - prompt, - type, - man->connection.up_query_type); + msg(M_CLIENT, "ERROR: %s of type '%s' entered, but we need one= of type '%s'", prompt, + type, man->connection.up_query_type); } } else @@ -768,36 +751,42 @@ static void man_query_username(struct management *man, const char *type, const char *s= tring) { - const bool needed =3D ((man->connection.up_query_mode =3D=3D UP_QUERY_= USER_PASS - ) && man->connection.up_query_type); - man_query_user_pass(man, type, string, needed, "username", man->connec= tion.up_query.username, USER_PASS_LEN); + const bool needed =3D + ((man->connection.up_query_mode =3D=3D UP_QUERY_USER_PASS) && man-= >connection.up_query_type); + man_query_user_pass(man, type, string, needed, "username", man->connec= tion.up_query.username, + USER_PASS_LEN); } static void man_query_password(struct management *man, const char *type, const char *s= tring) { const bool needed =3D ((man->connection.up_query_mode =3D=3D UP_QUERY_= PASS - || man->connection.up_query_mode =3D=3D UP_QUERY= _USER_PASS - ) && man->connection.up_query_type); + || man->connection.up_query_mode =3D=3D UP_QUERY= _USER_PASS) + && man->connection.up_query_type); if (!string[0]) /* allow blank passwords to be passed through using th= e blank_up tag */ { string =3D blank_up; } - man_query_user_pass(man, type, string, needed, "password", man->connec= tion.up_query.password, USER_PASS_LEN); + man_query_user_pass(man, type, string, needed, "password", man->connec= tion.up_query.password, + USER_PASS_LEN); } static void man_query_need_ok(struct management *man, const char *type, const char *ac= tion) { - const bool needed =3D ((man->connection.up_query_mode =3D=3D UP_QUERY_= NEED_OK) && man->connection.up_query_type); - man_query_user_pass(man, type, action, needed, "needok-confirmation", = man->connection.up_query.password, USER_PASS_LEN); + const bool needed =3D + ((man->connection.up_query_mode =3D=3D UP_QUERY_NEED_OK) && man->c= onnection.up_query_type); + man_query_user_pass(man, type, action, needed, "needok-confirmation", + man->connection.up_query.password, USER_PASS_LEN); } static void man_query_need_str(struct management *man, const char *type, const char *a= ction) { - const bool needed =3D ((man->connection.up_query_mode =3D=3D UP_QUERY_= NEED_STR) && man->connection.up_query_type); - man_query_user_pass(man, type, action, needed, "needstr-string", man->= connection.up_query.password, USER_PASS_LEN); + const bool needed =3D + ((man->connection.up_query_mode =3D=3D UP_QUERY_NEED_STR) && man->= connection.up_query_type); + man_query_user_pass(man, type, action, needed, "needstr-string", + man->connection.up_query.password, USER_PASS_LEN); } static void @@ -826,8 +815,8 @@ { if (man->persist.callback.send_cc_message) { - const bool status =3D (*man->persist.callback.send_cc_message) - (man->persist.callback.arg, message, param= eters); + const bool status =3D (*man->persist.callback.send_cc_message)(man= ->persist.callback.arg, + messa= ge, parameters); if (status) { msg(M_CLIENT, "SUCCESS: command succeeded"); @@ -892,13 +881,12 @@ { ASSERT(p1); - if (man->persist.callback.remote_entry_get - && man->persist.callback.remote_entry_count) + if (man->persist.callback.remote_entry_get && man->persist.callback.re= mote_entry_count) { unsigned int count =3D (*man->persist.callback.remote_entry_count)= (man->persist.callback.arg); - unsigned int from =3D (unsigned int) atoi(p1); - unsigned int to =3D p2 ? (unsigned int) atoi(p2) : from + 1; + unsigned int from =3D (unsigned int)atoi(p1); + unsigned int to =3D p2 ? (unsigned int)atoi(p2) : from + 1; if (!strcmp(p1, "all")) { @@ -909,7 +897,8 @@ for (unsigned int i =3D from; i < min_uint(to, count); i++) { char *remote =3D NULL; - bool res =3D (*man->persist.callback.remote_entry_get)(man->pe= rsist.callback.arg, i, &remote); + bool res =3D + (*man->persist.callback.remote_entry_get)(man->persist.cal= lback.arg, i, &remote); if (res && remote) { msg(M_CLIENT, "%u,%s", i, remote); @@ -955,8 +944,8 @@ } } -#define IER_RESET 0 -#define IER_NEW 1 +#define IER_RESET 0 +#define IER_NEW 1 static void in_extra_reset(struct man_connection *mc, const int mode) @@ -989,14 +978,9 @@ case IEC_CLIENT_AUTH: if (man->persist.callback.client_auth) { - const bool status =3D (*man->persist.callback.client_auth) - (man->persist.callback.arg, - man->connection.in_extra_cid, - man->connection.in_extra_kid, - true, - NULL, - NULL, - man->connection.in_extra); + const bool status =3D (*man->persist.callback.client_auth)( + man->persist.callback.arg, man->connection.in_extra_ci= d, + man->connection.in_extra_kid, true, NULL, NULL, man->c= onnection.in_extra); man->connection.in_extra =3D NULL; report_command_status(status, "client-auth"); } @@ -1063,9 +1047,8 @@ * @param timeout_str The timeout value in string form */ static void -man_client_pending_auth(struct management *man, const char *cid_str, - const char *kid_str, const char *extra, - const char *timeout_str) +man_client_pending_auth(struct management *man, const char *cid_str, const= char *kid_str, + const char *extra, const char *timeout_str) { unsigned long cid =3D 0; unsigned int kid =3D 0; @@ -1075,8 +1058,8 @@ { if (man->persist.callback.client_pending_auth) { - bool ret =3D (*man->persist.callback.client_pending_auth) - (man->persist.callback.arg, cid, kid, extra, ti= meout); + bool ret =3D (*man->persist.callback.client_pending_auth)(man-= >persist.callback.arg, cid, + kid, e= xtra, timeout); if (ret) { @@ -1085,7 +1068,7 @@ else { msg(M_CLIENT, "ERROR: client-pending-auth command failed." - " Extra parameter might be too long"); + " Extra parameter might be too long"); } } else @@ -1101,8 +1084,7 @@ struct man_connection *mc =3D &man->connection; mc->in_extra_cid =3D 0; mc->in_extra_kid =3D 0; - if (parse_cid(cid_str, &mc->in_extra_cid) - && parse_uint(kid_str, "KID", &mc->in_extra_kid)) + if (parse_cid(cid_str, &mc->in_extra_cid) && parse_uint(kid_str, "KID"= , &mc->in_extra_kid)) { mc->in_extra_cmd =3D IEC_CLIENT_AUTH; in_extra_reset(mc, IER_NEW); @@ -1114,7 +1096,8 @@ } static void -man_client_deny(struct management *man, const char *cid_str, const char *k= id_str, const char *reason, const char *client_reason) +man_client_deny(struct management *man, const char *cid_str, const char *k= id_str, + const char *reason, const char *client_reason) { unsigned long cid =3D 0; unsigned int kid =3D 0; @@ -1122,14 +1105,8 @@ { if (man->persist.callback.client_auth) { - const bool status =3D (*man->persist.callback.client_auth) - (man->persist.callback.arg, - cid, - kid, - false, - reason, - client_reason, - NULL); + const bool status =3D (*man->persist.callback.client_auth)( + man->persist.callback.arg, cid, kid, false, reason, client= _reason, NULL); if (status) { msg(M_CLIENT, "SUCCESS: client-deny command succeeded"); @@ -1154,7 +1131,8 @@ { if (man->persist.callback.kill_by_cid) { - const bool status =3D (*man->persist.callback.kill_by_cid)(man= ->persist.callback.arg, cid, kill_msg); + const bool status =3D + (*man->persist.callback.kill_by_cid)(man->persist.callback= .arg, cid, kill_msg); if (status) { msg(M_CLIENT, "SUCCESS: client-kill command succeeded"); @@ -1237,12 +1215,10 @@ nclients =3D (*man->persist.callback.n_clients)(man->persist.callb= ack.arg); } msg(M_CLIENT, "SUCCESS: nclients=3D%d,bytesin=3D" counter_format ",byt= esout=3D" counter_format, - nclients, - link_read_bytes_global, - link_write_bytes_global); + nclients, link_read_bytes_global, link_write_bytes_global); } -#define MN_AT_LEAST (1<<0) +#define MN_AT_LEAST (1 << 0) /** * Checks if the correct number of arguments to a management command are p= resent * and otherwise prints an error and returns false. @@ -1262,11 +1238,8 @@ { if (!p[i]) { - msg(M_CLIENT, "ERROR: the '%s' command requires %s%d parameter= %s", - p[0], - (flags & MN_AT_LEAST) ? "at least " : "", - n, - n > 1 ? "s" : ""); + msg(M_CLIENT, "ERROR: the '%s' command requires %s%d parameter= %s", p[0], + (flags & MN_AT_LEAST) ? "at least " : "", n, n > 1 ? "s" := ""); return false; } } @@ -1312,8 +1285,7 @@ */ if (man->persist.callback.network_change) { - int fd =3D (*man->persist.callback.network_change) - (man->persist.callback.arg, samenetwork); + int fd =3D (*man->persist.callback.network_change)(man->persist.ca= llback.arg, samenetwork); man->connection.fdtosend =3D fd; msg(M_CLIENT, "PROTECTFD: fd '%d' sent to be protected", fd); if (fd =3D=3D -2) @@ -1334,7 +1306,8 @@ } static void -man_dispatch_command(struct management *man, struct status_output *so, con= st char **p, const int nparms) +man_dispatch_command(struct management *man, struct status_output *so, con= st char **p, + const int nparms) { struct gc_arena gc =3D gc_new(); @@ -1664,7 +1637,8 @@ const int n =3D atoi(p[1]); for (i =3D 0; i < n; ++i) { - msg(M_CLIENT, "[%d] The purpose of this command is to gene= rate large amounts of output.", i); + msg(M_CLIENT, + "[%d] The purpose of this command is to generate large= amounts of output.", i); } } } @@ -1691,7 +1665,8 @@ case MS_CC_WAIT_READ: case MS_CC_WAIT_WRITE: - net_event_win32_start(&man->connection.ne32, FD_READ|FD_WRITE|= FD_CLOSE, man->connection.sd_cli); + net_event_win32_start(&man->connection.ne32, FD_READ | FD_WRIT= E | FD_CLOSE, + man->connection.sd_cli); break; default: @@ -1736,27 +1711,24 @@ #if UNIX_SOCK_SUPPORT if (man->settings.flags & MF_UNIX_SOCK) { - msg(D_MANAGEMENT, "MANAGEMENT: %s %s", - description, + msg(D_MANAGEMENT, "MANAGEMENT: %s %s", description, sockaddr_unix_name(&man->settings.local_unix, "NULL")); } else #endif - if (man->settings.flags & MF_CONNECT_AS_CLIENT) + if (man->settings.flags & MF_CONNECT_AS_CLIENT) { - msg(D_MANAGEMENT, "MANAGEMENT: %s %s", - description, + msg(D_MANAGEMENT, "MANAGEMENT: %s %s", description, print_sockaddr(man->settings.local->ai_addr, &gc)); } else { struct sockaddr_storage addr; socklen_t addrlen =3D sizeof(addr); - if (!getpeername(man->connection.sd_cli, (struct sockaddr *) &addr, - &addrlen)) + if (!getpeername(man->connection.sd_cli, (struct sockaddr *)&addr,= &addrlen)) { msg(D_MANAGEMENT, "MANAGEMENT: %s %s", description, - print_sockaddr((struct sockaddr *) &addr, &gc)); + print_sockaddr((struct sockaddr *)&addr, &gc)); } else { @@ -1782,19 +1754,22 @@ { if (socket_defined(sd) && (man->settings.client_uid !=3D -1 || man->se= ttings.client_gid !=3D -1)) { - static const char err_prefix[] =3D "MANAGEMENT: unix domain socket= client connection rejected --"; + static const char err_prefix[] =3D + "MANAGEMENT: unix domain socket client connection rejected --"; int uid, gid; if (unix_socket_get_peer_uid_gid(man->connection.sd_cli, &uid, &gi= d)) { if (man->settings.client_uid !=3D -1 && man->settings.client_u= id !=3D uid) { - msg(D_MANAGEMENT, "%s UID of socket peer (%d) doesn't matc= h required value (%d) as given by --management-client-user", + msg(D_MANAGEMENT, + "%s UID of socket peer (%d) doesn't match required val= ue (%d) as given by --management-client-user", err_prefix, uid, man->settings.client_uid); return false; } if (man->settings.client_gid !=3D -1 && man->settings.client_g= id !=3D gid) { - msg(D_MANAGEMENT, "%s GID of socket peer (%d) doesn't matc= h required value (%d) as given by --management-client-group", + msg(D_MANAGEMENT, + "%s GID of socket peer (%d) doesn't match required val= ue (%d) as given by --management-client-group", err_prefix, gid, man->settings.client_gid); return false; } @@ -1876,8 +1851,8 @@ #endif { man->connection.sd_top =3D create_socket_tcp(man->settings.loc= al); - socket_bind(man->connection.sd_top, man->settings.local, - man->settings.local->ai_family, "MANAGEMENT", fals= e); + socket_bind(man->connection.sd_top, man->settings.local, man->= settings.local->ai_family, + "MANAGEMENT", false); } /* @@ -1905,14 +1880,13 @@ const struct sockaddr *man_addr =3D man->settings.local->ai_ad= dr; struct sockaddr_storage addr; socklen_t addrlen =3D sizeof(addr); - if (!getsockname(man->connection.sd_top, (struct sockaddr *) &= addr, &addrlen)) + if (!getsockname(man->connection.sd_top, (struct sockaddr *)&a= ddr, &addrlen)) { - man_addr =3D (struct sockaddr *) &addr; + man_addr =3D (struct sockaddr *)&addr; } else { - msg(M_WARN|M_ERRNO, - "Failed to get the management socket address"); + msg(M_WARN | M_ERRNO, "Failed to get the management socket= address"); } msg(D_MANAGEMENT, "MANAGEMENT: TCP Socket listening on %s", print_sockaddr(man_addr, &gc)); @@ -1958,9 +1932,7 @@ #endif { man->connection.sd_cli =3D create_socket_tcp(man->settings.local); - status =3D openvpn_connect(man->connection.sd_cli, - man->settings.local->ai_addr, - 5, + status =3D openvpn_connect(man->connection.sd_cli, man->settings.l= ocal->ai_addr, 5, &signal_received); } @@ -1975,15 +1947,13 @@ #if UNIX_SOCK_SUPPORT if (man->settings.flags & MF_UNIX_SOCK) { - msg(D_LINK_ERRORS | M_ERRNO, - "MANAGEMENT: connect to unix socket %s failed", + msg(D_LINK_ERRORS | M_ERRNO, "MANAGEMENT: connect to unix sock= et %s failed", sockaddr_unix_name(&man->settings.local_unix, "NULL")); } else #endif { - msg(D_LINK_ERRORS | M_ERRNO, - "MANAGEMENT: connect to %s failed", + msg(D_LINK_ERRORS | M_ERRNO, "MANAGEMENT: connect to %s failed= ", print_sockaddr(man->settings.local->ai_addr, &gc)); } throw_signal_soft(SIGTERM, "management-connect-failed"); @@ -2048,7 +2018,7 @@ struct gc_arena gc =3D gc_new(); struct status_output *so; int nparms; - char *parms[MAX_PARMS+1]; + char *parms[MAX_PARMS + 1]; CLEAR(parms); so =3D status_open(NULL, 0, -1, &man->persist.vout, 0); @@ -2101,8 +2071,7 @@ if (!ignore_sys_error(err, crt_error)) { struct gc_arena gc =3D gc_new(); - msg(D_MANAGEMENT, "MANAGEMENT: TCP %s error: %s", prefix, - strerror(err)); + msg(D_MANAGEMENT, "MANAGEMENT: TCP %s error: %s", prefix, strerror= (err)); gc_free(&gc); return true; } @@ -2119,7 +2088,8 @@ struct msghdr msg =3D { 0 }; struct iovec iov[1]; - union { + union + { struct cmsghdr cm; char control[CMSG_SPACE(sizeof(int))]; } control_un; @@ -2132,7 +2102,7 @@ cmptr->cmsg_len =3D CMSG_LEN(sizeof(int)); cmptr->cmsg_level =3D SOL_SOCKET; cmptr->cmsg_type =3D SCM_RIGHTS; - *((int *) CMSG_DATA(cmptr)) =3D sendfd; + *((int *)CMSG_DATA(cmptr)) =3D sendfd; msg.msg_name =3D NULL; msg.msg_namelen =3D 0; @@ -2152,13 +2122,14 @@ struct iovec iov[1]; ssize_t n; - union { + union + { struct cmsghdr cm; char control[CMSG_SPACE(sizeof(int))]; } control_un; - struct cmsghdr *cmptr; + struct cmsghdr *cmptr; - msghdr.msg_control =3D control_un.control; + msghdr.msg_control =3D control_un.control; msghdr.msg_controllen =3D sizeof(control_un.control); msghdr.msg_name =3D NULL; @@ -2169,13 +2140,12 @@ msghdr.msg_iov =3D iov; msghdr.msg_iovlen =3D 1; - if ( (n =3D recvmsg(fd, &msghdr, flags)) <=3D 0) + if ((n =3D recvmsg(fd, &msghdr, flags)) <=3D 0) { return (n); } - if ( (cmptr =3D CMSG_FIRSTHDR(&msghdr)) !=3D NULL - && cmptr->cmsg_len =3D=3D CMSG_LEN(sizeof(int))) + if ((cmptr =3D CMSG_FIRSTHDR(&msghdr)) !=3D NULL && cmptr->cmsg_len = =3D=3D CMSG_LEN(sizeof(int))) { if (cmptr->cmsg_level !=3D SOL_SOCKET) { @@ -2185,12 +2155,11 @@ { msg(M_ERR, "control type !=3D SCM_RIGHTS"); } - *recvfd =3D *((int *) CMSG_DATA(cmptr)); + *recvfd =3D *((int *)CMSG_DATA(cmptr)); } else { - *recvfd =3D -1; /* descriptor was not passed */ - + *recvfd =3D -1; /* descriptor was not passed */ } return (n); } @@ -2208,10 +2177,10 @@ } struct user_pass up; CLEAR(up); - strncpy(up.username, msg, sizeof(up.username)-1); + strncpy(up.username, msg, sizeof(up.username) - 1); - management_query_user_pass(management, &up, command, GET_USER_PASS_NEE= D_OK, (void *) 0); - return strcmp("ok", up.password)=3D=3D0; + management_query_user_pass(management, &up, command, GET_USER_PASS_NEE= D_OK, (void *)0); + return strcmp("ok", up.password) =3D=3D 0; } /* @@ -2226,8 +2195,8 @@ struct user_pass up; CLEAR(up); strcpy(up.username, "tunmethod"); - management_query_user_pass(management, &up, "PERSIST_TUN_ACTION", - GET_USER_PASS_NEED_OK, (void *) 0); + management_query_user_pass(management, &up, "PERSIST_TUN_ACTION", GET_= USER_PASS_NEED_OK, + (void *)0); if (!strcmp("NOACTION", up.password)) { return ANDROID_KEEP_OLD_TUN; @@ -2238,7 +2207,8 @@ } else { - msg(M_ERR, "Got unrecognised '%s' from management for PERSIST_TUN_= ACTION query", up.password); + msg(M_ERR, "Got unrecognised '%s' from management for PERSIST_TUN_= ACTION query", + up.password); } ASSERT(0); @@ -2264,7 +2234,7 @@ { man->connection.lastfdreceived =3D fd; } -#else /* ifdef TARGET_ANDROID */ +#else /* ifdef TARGET_ANDROID */ len =3D recv(man->connection.sd_cli, (void *)buf, sizeof(buf), MSG_NOS= IGNAL); #endif @@ -2276,7 +2246,7 @@ { bool processed_command =3D false; - ASSERT(len <=3D (int) sizeof(buf)); + ASSERT(len <=3D (int)sizeof(buf)); command_line_add(man->connection.in, buf, len); /* @@ -2304,7 +2274,7 @@ } else { - man_process_command(man, (char *) line); + man_process_command(man, (char *)line); } if (man->connection.halt) { @@ -2357,12 +2327,13 @@ #ifdef TARGET_ANDROID if (man->connection.fdtosend > 0) { - sent =3D man_send_with_fd(man->connection.sd_cli, BPTR(buf), l= en, MSG_NOSIGNAL, man->connection.fdtosend); + sent =3D man_send_with_fd(man->connection.sd_cli, BPTR(buf), l= en, MSG_NOSIGNAL, + man->connection.fdtosend); man->connection.fdtosend =3D -1; } else #endif - sent =3D send(man->connection.sd_cli, (const void *)BPTR(buf), len= , MSG_NOSIGNAL); + sent =3D send(man->connection.sd_cli, (const void *)BPTR(buf),= len, MSG_NOSIGNAL); if (sent >=3D 0) { buffer_list_advance(man->connection.out, sent); @@ -2398,9 +2369,7 @@ } static void -man_persist_init(struct management *man, - const int log_history_cache, - const int echo_buffer_size, +man_persist_init(struct management *man, const int log_history_cache, cons= t int echo_buffer_size, const int state_buffer_size) { struct man_persist *mp =3D &man->persist; @@ -2458,17 +2427,10 @@ } static void -man_settings_init(struct man_settings *ms, - const char *addr, - const char *port, - const char *pass_file, - const char *client_user, - const char *client_group, - const int log_history_cache, - const int echo_buffer_size, - const int state_buffer_size, - const int remap_sigusr1, - const unsigned int flags) +man_settings_init(struct man_settings *ms, const char *addr, const char *p= ort, + const char *pass_file, const char *client_user, const ch= ar *client_group, + const int log_history_cache, const int echo_buffer_size, + const int state_buffer_size, const int remap_sigusr1, co= nst unsigned int flags) { if (!ms->defined) { @@ -2514,7 +2476,6 @@ else #endif { - /* * Run management over tunnel, or * separate channel? @@ -2526,16 +2487,16 @@ else { int status; - int resolve_flags =3D GETADDR_RESOLVE|GETADDR_WARN_ON_SIGN= AL|GETADDR_FATAL; + int resolve_flags =3D GETADDR_RESOLVE | GETADDR_WARN_ON_SI= GNAL | GETADDR_FATAL; if (!(flags & MF_CONNECT_AS_CLIENT)) { resolve_flags |=3D GETADDR_PASSIVE; } - status =3D openvpn_getaddrinfo(resolve_flags, addr, port, = 0, - NULL, AF_UNSPEC, &ms->local); - ASSERT(status=3D=3D0); + status =3D + openvpn_getaddrinfo(resolve_flags, addr, port, 0, NULL= , AF_UNSPEC, &ms->local); + ASSERT(status =3D=3D 0); } } @@ -2653,9 +2614,7 @@ struct management *man; ALLOC_OBJ_CLEAR(man, struct management); - man_persist_init(man, - MANAGEMENT_LOG_HISTORY_INITIAL_SIZE, - MANAGEMENT_ECHO_BUFFER_SIZE, + man_persist_init(man, MANAGEMENT_LOG_HISTORY_INITIAL_SIZE, MANAGEMENT_= ECHO_BUFFER_SIZE, MANAGEMENT_STATE_BUFFER_SIZE); man_connection_clear(&man->connection); @@ -2664,16 +2623,9 @@ } bool -management_open(struct management *man, - const char *addr, - const char *port, - const char *pass_file, - const char *client_user, - const char *client_group, - const int log_history_cache, - const int echo_buffer_size, - const int state_buffer_size, - const int remap_sigusr1, +management_open(struct management *man, const char *addr, const char *port= , const char *pass_file, + const char *client_user, const char *client_group, const i= nt log_history_cache, + const int echo_buffer_size, const int state_buffer_size, c= onst int remap_sigusr1, const unsigned int flags) { bool ret =3D false; @@ -2682,17 +2634,8 @@ * Save the settings only if they have not * been saved before. */ - man_settings_init(&man->settings, - addr, - port, - pass_file, - client_user, - client_group, - log_history_cache, - echo_buffer_size, - state_buffer_size, - remap_sigusr1, - flags); + man_settings_init(&man->settings, addr, port, pass_file, client_user, = client_group, + log_history_cache, echo_buffer_size, state_buffer_si= ze, remap_sigusr1, flags); /* * The log is initially sized to MANAGEMENT_LOG_HISTORY_INITIAL_SIZE, @@ -2729,8 +2672,7 @@ } void -management_set_callback(struct management *man, - const struct management_callback *cb) +management_set_callback(struct management *man, const struct management_ca= llback *cb) { man->persist.standalone_disabled =3D true; man->persist.callback =3D *cb; @@ -2746,15 +2688,12 @@ } void -management_set_state(struct management *man, - const int state, - const char *detail, - const in_addr_t *tun_local_ip, - const struct in6_addr *tun_local_ip6, - const struct openvpn_sockaddr *local, - const struct openvpn_sockaddr *remote) +management_set_state(struct management *man, const int state, const char *= detail, + const in_addr_t *tun_local_ip, const struct in6_addr = *tun_local_ip6, + const struct openvpn_sockaddr *local, const struct op= envpn_sockaddr *remote) { - if (man->persist.state && (!(man->settings.flags & MF_SERVER) || state= < OPENVPN_STATE_CLIENT_BASE)) + if (man->persist.state + && (!(man->settings.flags & MF_SERVER) || state < OPENVPN_STATE_CL= IENT_BASE)) { struct gc_arena gc =3D gc_new(); struct log_entry e; @@ -2786,13 +2725,11 @@ if (man->connection.state_realtime) { - out =3D log_entry_print(&e, LOG_PRINT_STATE_PREFIX - | LOG_PRINT_INT_DATE - | LOG_PRINT_STATE - | LOG_PRINT_LOCAL_IP - | LOG_PRINT_REMOTE_IP - | LOG_PRINT_CRLF - | LOG_ECHO_TO_LOG, &gc); + out =3D log_entry_print(&e, + LOG_PRINT_STATE_PREFIX | LOG_PRINT_INT_D= ATE | LOG_PRINT_STATE + | LOG_PRINT_LOCAL_IP | LOG_PRINT_REM= OTE_IP | LOG_PRINT_CRLF + | LOG_ECHO_TO_LOG, + &gc); } if (out) @@ -2807,25 +2744,23 @@ static bool env_filter_match(const char *env_str, const int env_filter_level) { - static const char *env_names[] =3D { - "username=3D", - "password=3D", - "X509_0_CN=3D", - "tls_serial_", - "untrusted_ip=3D", - "ifconfig_local=3D", - "ifconfig_netmask=3D", - "daemon_start_time=3D", - "daemon_pid=3D", - "dev=3D", - "ifconfig_pool_remote_ip=3D", - "ifconfig_pool_netmask=3D", - "time_duration=3D", - "bytes_sent=3D", - "bytes_received=3D", - "session_id=3D", - "session_state=3D" - }; + static const char *env_names[] =3D { "username=3D", + "password=3D", + "X509_0_CN=3D", + "tls_serial_", + "untrusted_ip=3D", + "ifconfig_local=3D", + "ifconfig_netmask=3D", + "daemon_start_time=3D", + "daemon_pid=3D", + "dev=3D", + "ifconfig_pool_remote_ip=3D", + "ifconfig_pool_netmask=3D", + "time_duration=3D", + "bytes_sent=3D", + "bytes_received=3D", + "session_id=3D", + "session_state=3D" }; if (env_filter_level =3D=3D 0) { @@ -2853,7 +2788,8 @@ } static void -man_output_env(const struct env_set *es, const bool tail, const int env_fi= lter_level, const char *prefix) +man_output_env(const struct env_set *es, const bool tail, const int env_fi= lter_level, + const char *prefix) { if (es) { @@ -2914,11 +2850,12 @@ char line[256]; if (man->persist.callback.get_peer_info) { - const char *peer_info =3D (*man->persist.callback.get_peer_info)(m= an->persist.callback.arg, mdac->cid); + const char *peer_info =3D + (*man->persist.callback.get_peer_info)(man->persist.callback.a= rg, mdac->cid); if (peer_info) { struct buffer buf; - buf_set_read(&buf, (const uint8_t *) peer_info, strlen(peer_in= fo)); + buf_set_read(&buf, (const uint8_t *)peer_info, strlen(peer_inf= o)); while (buf_parse(&buf, '\n', line, sizeof(line))) { chomp(line); @@ -2936,10 +2873,8 @@ } void -management_notify_client_needing_auth(struct management *management, - const unsigned int mda_key_id, - struct man_def_auth_context *mdac, - const struct env_set *es) +management_notify_client_needing_auth(struct management *management, const= unsigned int mda_key_id, + struct man_def_auth_context *mdac, c= onst struct env_set *es) { if (!(mdac->flags & DAF_CONNECTION_CLOSED)) { @@ -2950,7 +2885,7 @@ } msg(M_CLIENT, ">CLIENT:%s,%lu,%u", mode, mdac->cid, mda_key_id); man_output_extra_env(management, "CLIENT"); - if (management->connection.env_filter_level>0) + if (management->connection.env_filter_level > 0) { man_output_peer_info_env(management, mdac); } @@ -2960,18 +2895,15 @@ } void -management_notify_client_cr_response(unsigned mda_key_id, - const struct man_def_auth_context *md= ac, - const struct env_set *es, - const char *response) +management_notify_client_cr_response(unsigned mda_key_id, const struct man= _def_auth_context *mdac, + const struct env_set *es, const char = *response) { struct gc_arena gc; if (management) { gc =3D gc_new(); - msg(M_CLIENT, ">CLIENT:CR_RESPONSE,%lu,%u,%s", - mdac->cid, mda_key_id, response); + msg(M_CLIENT, ">CLIENT:CR_RESPONSE,%lu,%u,%s", mdac->cid, mda_key_= id, response); man_output_extra_env(management, "CLIENT"); if (management->connection.env_filter_level > 0) { @@ -2983,8 +2915,7 @@ } void -management_connection_established(struct management *management, - struct man_def_auth_context *mdac, +management_connection_established(struct management *management, struct ma= n_def_auth_context *mdac, const struct env_set *es) { mdac->flags |=3D DAF_CONNECTION_ESTABLISHED; @@ -2994,8 +2925,7 @@ } void -management_notify_client_close(struct management *management, - struct man_def_auth_context *mdac, +management_notify_client_close(struct management *management, struct man_d= ef_auth_context *mdac, const struct env_set *es) { if ((mdac->flags & DAF_INITIAL_AUTH) && !(mdac->flags & DAF_CONNECTION= _CLOSED)) @@ -3007,18 +2937,14 @@ } void -management_learn_addr(struct management *management, - struct man_def_auth_context *mdac, - const struct mroute_addr *addr, - const bool primary) +management_learn_addr(struct management *management, struct man_def_auth_c= ontext *mdac, + const struct mroute_addr *addr, const bool primary) { struct gc_arena gc =3D gc_new(); if ((mdac->flags & DAF_INITIAL_AUTH) && !(mdac->flags & DAF_CONNECTION= _CLOSED)) { - msg(M_CLIENT, ">CLIENT:ADDRESS,%lu,%s,%d", - mdac->cid, - mroute_addr_print_ex(addr, MAPF_SUBNET, &gc), - BOOL_CAST(primary)); + msg(M_CLIENT, ">CLIENT:ADDRESS,%lu,%s,%d", mdac->cid, + mroute_addr_print_ex(addr, MAPF_SUBNET, &gc), BOOL_CAST(primar= y)); } gc_free(&gc); } @@ -3042,7 +2968,10 @@ if (man->connection.echo_realtime) { - out =3D log_entry_print(&e, LOG_PRINT_INT_DATE|LOG_PRINT_ECHO_= PREFIX|LOG_PRINT_CRLF|MANAGEMENT_ECHO_FLAGS, &gc); + out =3D log_entry_print(&e, + LOG_PRINT_INT_DATE | LOG_PRINT_ECHO_PREF= IX | LOG_PRINT_CRLF + | MANAGEMENT_ECHO_FLAGS, + &gc); } if (out) @@ -3061,8 +2990,7 @@ * If we are running management over the tunnel, * this is the place to initialize the connection. */ - if (man->settings.management_over_tunnel - && man->connection.state =3D=3D MS_INITIAL) + if (man->settings.management_over_tunnel && man->connection.state =3D= =3D MS_INITIAL) { /* listen on our local TUN/TAP IP address */ struct in_addr ia; @@ -3071,12 +2999,11 @@ ia.s_addr =3D htonl(tun_local_ip); inet_ntop(AF_INET, &ia, buf, sizeof(buf)); - ret =3D openvpn_getaddrinfo(GETADDR_PASSIVE, buf, NULL, 0, NULL, - AF_INET, &man->settings.local); - ASSERT(ret=3D=3D0); + ret =3D + openvpn_getaddrinfo(GETADDR_PASSIVE, buf, NULL, 0, NULL, AF_IN= ET, &man->settings.local); + ASSERT(ret =3D=3D 0); man_connection_init(man); } - } void @@ -3124,9 +3051,7 @@ #ifdef _WIN32 void -management_socket_set(struct management *man, - struct event_set *es, - void *arg, +management_socket_set(struct management *man, struct event_set *es, void *= arg, unsigned int *persistent) { if (man->connection.state !=3D MS_INITIAL) @@ -3153,7 +3078,7 @@ case MS_CC_WAIT_WRITE: if (man_persist_state(persistent, 3)) { - event_ctl(es, ev, EVENT_READ|EVENT_WRITE, arg); + event_ctl(es, ev, EVENT_READ | EVENT_WRITE, arg); } break; @@ -3186,7 +3111,8 @@ net_event_win32_clear_selected_events(&man->connection= .ne32, FD_ACCEPT); } } - else if (man->connection.state =3D=3D MS_CC_WAIT_READ || man->= connection.state =3D=3D MS_CC_WAIT_WRITE) + else if (man->connection.state =3D=3D MS_CC_WAIT_READ + || man->connection.state =3D=3D MS_CC_WAIT_WRITE) { if (net_events & FD_READ) { @@ -3213,9 +3139,7 @@ #else /* ifdef _WIN32 */ void -management_socket_set(struct management *man, - struct event_set *es, - void *arg, +management_socket_set(struct management *man, struct event_set *es, void *= arg, unsigned int *persistent) { switch (man->connection.state) @@ -3382,7 +3306,8 @@ * Process management event loop outside primary event loop */ static int -man_standalone_event_loop(struct management *man, volatile int *signal_rec= eived, const time_t expire) +man_standalone_event_loop(struct management *man, volatile int *signal_rec= eived, + const time_t expire) { int status =3D -1; if (man_standalone_ok(man)) @@ -3396,18 +3321,16 @@ return status; } -#define MWCC_PASSWORD_WAIT (1<<0) -#define MWCC_HOLD_WAIT (1<<1) -#define MWCC_OTHER_WAIT (1<<2) +#define MWCC_PASSWORD_WAIT (1 << 0) +#define MWCC_HOLD_WAIT (1 << 1) +#define MWCC_OTHER_WAIT (1 << 2) /* * Block until client connects */ static void -man_wait_for_client_connection(struct management *man, - volatile int *signal_received, - const time_t expire, - unsigned int flags) +man_wait_for_client_connection(struct management *man, volatile int *signa= l_received, + const time_t expire, unsigned int flags) { ASSERT(man_standalone_ok(man)); if (man->connection.state =3D=3D MS_LISTEN) @@ -3492,11 +3415,8 @@ * Get a username/password from management channel in standalone mode. */ bool -management_query_user_pass(struct management *man, - struct user_pass *up, - const char *type, - const unsigned int flags, - const char *static_challenge) +management_query_user_pass(struct management *man, struct user_pass *up, c= onst char *type, + const unsigned int flags, const char *static_ch= allenge) { struct gc_arena gc =3D gc_new(); bool ret =3D false; @@ -3545,10 +3465,7 @@ sc =3D static_challenge; } } - buf_printf(&alert_msg, ">%s:Need '%s' %s", - prefix, - type, - alert_type); + buf_printf(&alert_msg, ">%s:Need '%s' %s", prefix, type, alert_typ= e); if (flags & (GET_USER_PASS_NEED_OK | GET_USER_PASS_NEED_STR)) { @@ -3559,7 +3476,7 @@ { buf_printf(&alert_msg, " SC:%d,%s", BOOL_CAST(flags & GET_USER_PASS_STATIC_CHALLENGE_EC= HO) - |(BOOL_CAST(flags & GET_USER_PASS_STATIC_CHALLENGE_= CONCAT) << 1), + | (BOOL_CAST(flags & GET_USER_PASS_STATIC_CHALL= ENGE_CONCAT) << 1), sc); } @@ -3624,8 +3541,8 @@ } static int -management_query_multiline(struct management *man, - const char *b64_data, const char *prompt, const= char *cmd, int *state, struct buffer_list **input) +management_query_multiline(struct management *man, const char *b64_data, c= onst char *prompt, + const char *cmd, int *state, struct buffer_list= **input) { struct gc_arena gc =3D gc_new(); int ret =3D 0; @@ -3644,12 +3561,12 @@ if (b64_data) { - alert_msg =3D alloc_buf_gc(strlen(b64_data)+strlen(prompt)+3, = &gc); + alert_msg =3D alloc_buf_gc(strlen(b64_data) + strlen(prompt) += 3, &gc); buf_printf(&alert_msg, ">%s:%s", prompt, b64_data); } else { - alert_msg =3D alloc_buf_gc(strlen(prompt)+3, &gc); + alert_msg =3D alloc_buf_gc(strlen(prompt) + 3, &gc); buf_printf(&alert_msg, ">%s", prompt); } @@ -3702,8 +3619,9 @@ static char * /* returns allocated base64 signature */ -management_query_multiline_flatten_newline(struct management *man, - const char *b64_data, const cha= r *prompt, const char *cmd, int *state, struct buffer_list **input) +management_query_multiline_flatten_newline(struct management *man, const c= har *b64_data, + const char *prompt, const char = *cmd, int *state, + struct buffer_list **input) { int ok; char *result =3D NULL; @@ -3716,7 +3634,7 @@ buf =3D buffer_list_peek(*input); if (buf && BLEN(buf) > 0) { - result =3D (char *) malloc(BLEN(buf)+1); + result =3D (char *)malloc(BLEN(buf) + 1); check_malloc_return(result); memcpy(result, buf->data, BLEN(buf)); result[BLEN(buf)] =3D '\0'; @@ -3731,8 +3649,8 @@ static char * /* returns allocated base64 signature */ -management_query_multiline_flatten(struct management *man, - const char *b64_data, const char *promp= t, const char *cmd, int *state, struct buffer_list **input) +management_query_multiline_flatten(struct management *man, const char *b64= _data, const char *prompt, + const char *cmd, int *state, struct buf= fer_list **input) { int ok; char *result =3D NULL; @@ -3745,7 +3663,7 @@ buf =3D buffer_list_peek(*input); if (buf && BLEN(buf) > 0) { - result =3D (char *) malloc(BLEN(buf)+1); + result =3D (char *)malloc(BLEN(buf) + 1); check_malloc_return(result); memcpy(result, buf->data, BLEN(buf)); result[BLEN(buf)] =3D '\0'; @@ -3760,8 +3678,7 @@ char * /* returns allocated base64 signature */ -management_query_pk_sig(struct management *man, const char *b64_data, - const char *algorithm) +management_query_pk_sig(struct management *man, const char *b64_data, cons= t char *algorithm) { const char *prompt =3D "PK_SIGN"; const char *desc =3D "pk-sign"; @@ -3773,15 +3690,15 @@ desc =3D "rsa-sign"; } - buf_write(&buf_data, b64_data, (int) strlen(b64_data)); + buf_write(&buf_data, b64_data, (int)strlen(b64_data)); if (man->connection.client_version > 2) { - buf_write(&buf_data, ",", (int) strlen(",")); - buf_write(&buf_data, algorithm, (int) strlen(algorithm)); + buf_write(&buf_data, ",", (int)strlen(",")); + buf_write(&buf_data, algorithm, (int)strlen(algorithm)); } - char *ret =3D management_query_multiline_flatten(man, - (char *)buf_bptr(&buf_d= ata), prompt, desc, - &man->connection.ext_ke= y_state, &man->connection.ext_key_input); + char *ret =3D management_query_multiline_flatten(man, (char *)buf_bptr= (&buf_data), prompt, desc, + &man->connection.ext_ke= y_state, + &man->connection.ext_ke= y_input); free_buf(&buf_data); return ret; } @@ -3792,12 +3709,12 @@ const char prompt_1[] =3D "NEED-CERTIFICATE:"; struct buffer buf_prompt =3D alloc_buf(strlen(cert_name) + 20); buf_write(&buf_prompt, prompt_1, strlen(prompt_1)); - buf_write(&buf_prompt, cert_name, strlen(cert_name)+1); /* +1 for \0 */ + buf_write(&buf_prompt, cert_name, strlen(cert_name) + 1); /* +1 for \0= */ char *result; - result =3D management_query_multiline_flatten_newline(management, - NULL, (char *)buf_= bptr(&buf_prompt), "certificate", - &man->connection.e= xt_cert_state, &man->connection.ext_cert_input); + result =3D management_query_multiline_flatten_newline( + management, NULL, (char *)buf_bptr(&buf_prompt), "certificate", + &man->connection.ext_cert_state, &man->connection.ext_cert_input); free_buf(&buf_prompt); return result; } @@ -3824,7 +3741,8 @@ const bool standalone_disabled_save =3D man->persist.standalone_di= sabled; struct gc_arena gc =3D gc_new(); - man->persist.standalone_disabled =3D false; /* This is so M_CLIENT= messages will be correctly passed through msg() */ + man->persist.standalone_disabled =3D + false; /* This is so M_CLIENT messages will be correctly passe= d through msg() */ man->persist.special_state_msg =3D NULL; man->settings.mansig |=3D MANSIG_IGNORE_USR1_HUP; @@ -3903,7 +3821,7 @@ int i; for (i =3D 0; i < len; ++i) { - if (buf[i] && char_class(buf[i], (CC_PRINT|CC_NEWLINE))) + if (buf[i] && char_class(buf[i], (CC_PRINT | CC_NEWLINE))) { if (!buf_write_u8(&cl->buf, buf[i])) { @@ -3987,10 +3905,16 @@ } if (flags & LOG_PRINT_REMOTE_IP) { - buf_printf(&out, ",%s", (!addr_defined(&e->remote_sock) ? "," : - print_sockaddr_ex(&e->remote_sock.addr.sa= , ",", PS_DONT_SHOW_FAMILY|PS_SHOW_PORT, gc))); - buf_printf(&out, ",%s", (!addr_defined(&e->local_sock) ? "," : - print_sockaddr_ex(&e->local_sock.addr.sa,= ",", PS_DONT_SHOW_FAMILY|PS_SHOW_PORT, gc))); + buf_printf(&out, ",%s", + (!addr_defined(&e->remote_sock) + ? "," + : print_sockaddr_ex(&e->remote_sock.addr.sa, ",", + PS_DONT_SHOW_FAMILY | PS_SHOW_= PORT, gc))); + buf_printf(&out, ",%s", + (!addr_defined(&e->local_sock) + ? "," + : print_sockaddr_ex(&e->local_sock.addr.sa, ",", + PS_DONT_SHOW_FAMILY | PS_SHOW_= PORT, gc))); } if (flags & LOG_PRINT_LOCAL_IP && !IN6_IS_ADDR_UNSPECIFIED(&e->local_i= p6)) { @@ -4143,8 +4067,7 @@ void management_check_bytecount(struct context *c, struct management *man, stru= ct timeval *timeval) { - if (event_timeout_trigger(&man->connection.bytecount_update_interval, - timeval, ETT_DEFAULT)) + if (event_timeout_trigger(&man->connection.bytecount_update_interval, = timeval, ETT_DEFAULT)) { counter_type dco_read_bytes =3D 0; counter_type dco_write_bytes =3D 0; @@ -4181,7 +4104,7 @@ } } -#else /* ifdef ENABLE_MANAGEMENT */ +#else /* ifdef ENABLE_MANAGEMENT */ #include "win32.h" void diff --git a/src/openvpn/manage.h b/src/openvpn/manage.h index 36a1905..083caf5 100644 --- a/src/openvpn/manage.h +++ b/src/openvpn/manage.h @@ -24,24 +24,24 @@ #define MANAGE_H /* management_open flags */ -#define MF_SERVER (1<<0) -#define MF_QUERY_PASSWORDS (1<<1) -#define MF_HOLD (1<<2) -#define MF_SIGNAL (1<<3) -#define MF_FORGET_DISCONNECT (1<<4) -#define MF_CONNECT_AS_CLIENT (1<<5) -#define MF_CLIENT_AUTH (1<<6) +#define MF_SERVER (1 << 0) +#define MF_QUERY_PASSWORDS (1 << 1) +#define MF_HOLD (1 << 2) +#define MF_SIGNAL (1 << 3) +#define MF_FORGET_DISCONNECT (1 << 4) +#define MF_CONNECT_AS_CLIENT (1 << 5) +#define MF_CLIENT_AUTH (1 << 6) /* #define MF_CLIENT_PF (1<<7) *REMOVED FEATURE* */ -#define MF_UNIX_SOCK (1<<8) -#define MF_EXTERNAL_KEY (1<<9) -#define MF_EXTERNAL_KEY_NOPADDING (1<<10) -#define MF_EXTERNAL_KEY_PKCS1PAD (1<<11) -#define MF_UP_DOWN (1<<12) -#define MF_QUERY_REMOTE (1<<13) -#define MF_QUERY_PROXY (1<<14) -#define MF_EXTERNAL_CERT (1<<15) -#define MF_EXTERNAL_KEY_PSSPAD (1<<16) -#define MF_EXTERNAL_KEY_DIGEST (1<<17) +#define MF_UNIX_SOCK (1 << 8) +#define MF_EXTERNAL_KEY (1 << 9) +#define MF_EXTERNAL_KEY_NOPADDING (1 << 10) +#define MF_EXTERNAL_KEY_PKCS1PAD (1 << 11) +#define MF_UP_DOWN (1 << 12) +#define MF_QUERY_REMOTE (1 << 13) +#define MF_QUERY_PROXY (1 << 14) +#define MF_EXTERNAL_CERT (1 << 15) +#define MF_EXTERNAL_KEY_PSSPAD (1 << 16) +#define MF_EXTERNAL_KEY_DIGEST (1 << 17) #ifdef ENABLE_MANAGEMENT @@ -51,21 +51,22 @@ #include "socket.h" #include "mroute.h" -#define MANAGEMENT_VERSION 5 -#define MANAGEMENT_N_PASSWORD_RETRIES 3 -#define MANAGEMENT_LOG_HISTORY_INITIAL_SIZE 100 -#define MANAGEMENT_ECHO_BUFFER_SIZE 100 -#define MANAGEMENT_STATE_BUFFER_SIZE 100 +#define MANAGEMENT_VERSION 5 +#define MANAGEMENT_N_PASSWORD_RETRIES 3 +#define MANAGEMENT_LOG_HISTORY_INITIAL_SIZE 100 +#define MANAGEMENT_ECHO_BUFFER_SIZE 100 +#define MANAGEMENT_STATE_BUFFER_SIZE 100 /* * Management-interface-based deferred authentication */ -struct man_def_auth_context { +struct man_def_auth_context +{ unsigned long cid; -#define DAF_CONNECTION_ESTABLISHED (1<<0) -#define DAF_CONNECTION_CLOSED (1<<1) -#define DAF_INITIAL_AUTH (1<<2) +#define DAF_CONNECTION_ESTABLISHED (1 << 0) +#define DAF_CONNECTION_CLOSED (1 << 1) +#define DAF_INITIAL_AUTH (1 << 2) unsigned int flags; unsigned int mda_key_id_counter; @@ -98,7 +99,8 @@ * Manage log file history */ -union log_entry_union { +union log_entry_union +{ unsigned int msg_flags; int state; int intval; @@ -115,23 +117,23 @@ union log_entry_union u; }; -#define LOG_PRINT_LOG_PREFIX (1<<0) -#define LOG_PRINT_ECHO_PREFIX (1<<1) -#define LOG_PRINT_STATE_PREFIX (1<<2) +#define LOG_PRINT_LOG_PREFIX (1 << 0) +#define LOG_PRINT_ECHO_PREFIX (1 << 1) +#define LOG_PRINT_STATE_PREFIX (1 << 2) -#define LOG_PRINT_INT_DATE (1<<3) -#define LOG_PRINT_MSG_FLAGS (1<<4) -#define LOG_PRINT_STATE (1<<5) -#define LOG_PRINT_LOCAL_IP (1<<6) +#define LOG_PRINT_INT_DATE (1 << 3) +#define LOG_PRINT_MSG_FLAGS (1 << 4) +#define LOG_PRINT_STATE (1 << 5) +#define LOG_PRINT_LOCAL_IP (1 << 6) -#define LOG_PRINT_CRLF (1<<7) -#define LOG_FATAL_NOTIFY (1<<8) +#define LOG_PRINT_CRLF (1 << 7) +#define LOG_FATAL_NOTIFY (1 << 8) -#define LOG_PRINT_INTVAL (1<<9) +#define LOG_PRINT_INTVAL (1 << 9) -#define LOG_PRINT_REMOTE_IP (1<<10) +#define LOG_PRINT_REMOTE_IP (1 << 10) -#define LOG_ECHO_TO_LOG (1<<11) +#define LOG_ECHO_TO_LOG (1 << 11) const char *log_entry_print(const struct log_entry *e, unsigned int flags,= struct gc_arena *gc); @@ -173,32 +175,25 @@ { void *arg; -#define MCF_SERVER (1<<0) /* is OpenVPN being run as a server? */ +#define MCF_SERVER (1 << 0) /* is OpenVPN being run as a server? */ unsigned int flags; - void (*status) (void *arg, const int version, struct status_output *so= ); - void (*show_net) (void *arg, const int msglevel); - int (*kill_by_cn) (void *arg, const char *common_name); - int (*kill_by_addr) (void *arg, const in_addr_t addr, const int port, = const int proto); - void (*delete_event) (void *arg, event_t event); - int (*n_clients) (void *arg); - bool (*send_cc_message) (void *arg, const char *message, const char *p= arameter); + void (*status)(void *arg, const int version, struct status_output *so); + void (*show_net)(void *arg, const int msglevel); + int (*kill_by_cn)(void *arg, const char *common_name); + int (*kill_by_addr)(void *arg, const in_addr_t addr, const int port, c= onst int proto); + void (*delete_event)(void *arg, event_t event); + int (*n_clients)(void *arg); + bool (*send_cc_message)(void *arg, const char *message, const char *pa= rameter); bool (*kill_by_cid)(void *arg, const unsigned long cid, const char *ki= ll_msg); - bool (*client_auth) (void *arg, - const unsigned long cid, - const unsigned int mda_key_id, - const bool auth, - const char *reason, - const char *client_reason, - struct buffer_list *cc_config); /* ownership tran= sferred */ - bool (*client_pending_auth) (void *arg, - const unsigned long cid, - const unsigned int kid, - const char *extra, - unsigned int timeout); - char *(*get_peer_info) (void *arg, const unsigned long cid); + bool (*client_auth)(void *arg, const unsigned long cid, const unsigned= int mda_key_id, + const bool auth, const char *reason, const char *c= lient_reason, + struct buffer_list *cc_config); /* ownership trans= ferred */ + bool (*client_pending_auth)(void *arg, const unsigned long cid, const = unsigned int kid, + const char *extra, unsigned int timeout); + char *(*get_peer_info)(void *arg, const unsigned long cid); bool (*proxy_cmd)(void *arg, const char **p); - bool (*remote_cmd) (void *arg, const char **p); + bool (*remote_cmd)(void *arg, const char **p); #ifdef TARGET_ANDROID int (*network_change)(void *arg, bool samenetwork); #endif @@ -220,7 +215,8 @@ * connections. */ -struct man_persist { +struct man_persist +{ bool defined; struct log_history *log; @@ -240,7 +236,8 @@ counter_type bytes_out; }; -struct man_settings { +struct man_settings +{ bool defined; unsigned int flags; /* MF_x flags */ struct addrinfo *local; @@ -256,9 +253,9 @@ int client_gid; /* flags for handling the management interface "signal" command */ -#define MANSIG_IGNORE_USR1_HUP (1<<0) -#define MANSIG_MAP_USR1_TO_HUP (1<<1) -#define MANSIG_MAP_USR1_TO_TERM (1<<2) +#define MANSIG_IGNORE_USR1_HUP (1 << 0) +#define MANSIG_MAP_USR1_TO_HUP (1 << 1) +#define MANSIG_MAP_USR1_TO_TERM (1 << 2) unsigned int mansig; }; @@ -270,12 +267,13 @@ #define UP_QUERY_NEED_STR 4 /* states */ -#define MS_INITIAL 0 /* all sockets are closed */ -#define MS_LISTEN 1 /* no client is connected */ -#define MS_CC_WAIT_READ 2 /* client is connected, waiting for read on= socket */ -#define MS_CC_WAIT_WRITE 3 /* client is connected, waiting for ability= to write to socket */ +#define MS_INITIAL 0 /* all sockets are closed */ +#define MS_LISTEN 1 /* no client is connected */ +#define MS_CC_WAIT_READ 2 /* client is connected, waiting for read on soc= ket */ +#define MS_CC_WAIT_WRITE 3 /* client is connected, waiting for ability to = write to socket */ -struct man_connection { +struct man_connection +{ int state; socket_descriptor_t sd_top; @@ -344,16 +342,10 @@ struct management *management_init(void); -bool management_open(struct management *man, - const char *addr, - const char *port, - const char *pass_file, - const char *client_user, - const char *client_group, - const int log_history_cache, - const int echo_buffer_size, - const int state_buffer_size, - const int remap_sigusr1, +bool management_open(struct management *man, const char *addr, const char = *port, + const char *pass_file, const char *client_user, const= char *client_group, + const int log_history_cache, const int echo_buffer_si= ze, + const int state_buffer_size, const int remap_sigusr1, const unsigned int flags); void management_close(struct management *man); @@ -362,28 +354,22 @@ void management_pre_tunnel_close(struct management *man); -void management_socket_set(struct management *man, - struct event_set *es, - void *arg, +void management_socket_set(struct management *man, struct event_set *es, v= oid *arg, unsigned int *persistent); void management_io(struct management *man); -void management_set_callback(struct management *man, - const struct management_callback *cb); +void management_set_callback(struct management *man, const struct manageme= nt_callback *cb); void management_clear_callback(struct management *man); -bool management_query_user_pass(struct management *man, - struct user_pass *up, - const char *type, - const unsigned int flags, - const char *static_challenge); +bool management_query_user_pass(struct management *man, struct user_pass *= up, const char *type, + const unsigned int flags, const char *stat= ic_challenge); #ifdef TARGET_ANDROID bool management_android_control(struct management *man, const char *comman= d, const char *msg); -#define ANDROID_KEEP_OLD_TUN 1 +#define ANDROID_KEEP_OLD_TUN 1 #define ANDROID_OPEN_BEFORE_CLOSE 2 int managment_android_persisttun_action(struct management *man); @@ -397,7 +383,8 @@ void management_up_down(struct management *man, const char *updown, const = struct env_set *es); -void management_notify(struct management *man, const char *severity, const= char *type, const char *text); +void management_notify(struct management *man, const char *severity, const= char *type, + const char *text); void management_notify_generic(struct management *man, const char *str); @@ -407,25 +394,19 @@ const struct env_set *es); void management_connection_established(struct management *management, - struct man_def_auth_context *mdac, - const struct env_set *es); + struct man_def_auth_context *mdac, = const struct env_set *es); void management_notify_client_close(struct management *management, - struct man_def_auth_context *mdac, - const struct env_set *es); + struct man_def_auth_context *mdac, con= st struct env_set *es); -void management_learn_addr(struct management *management, - struct man_def_auth_context *mdac, - const struct mroute_addr *addr, - const bool primary); +void management_learn_addr(struct management *management, struct man_def_a= uth_context *mdac, + const struct mroute_addr *addr, const bool prim= ary); void management_notify_client_cr_response(unsigned mda_key_id, const struct man_def_auth_contex= t *mdac, - const struct env_set *es, - const char *response); + const struct env_set *es, const = char *response); -char *management_query_pk_sig(struct management *man, const char *b64_data, - const char *algorithm); +char *management_query_pk_sig(struct management *man, const char *b64_data= , const char *algorithm); char *management_query_cert(struct management *man, const char *cert_name); @@ -465,30 +446,28 @@ */ /* client/server states */ -#define OPENVPN_STATE_INITIAL 0 /* Initial, undefined state */ -#define OPENVPN_STATE_CONNECTING 1 /* Management interface has been in= itialized */ -#define OPENVPN_STATE_ASSIGN_IP 2 /* Assigning IP address to virtual = network interface */ -#define OPENVPN_STATE_ADD_ROUTES 3 /* Adding routes to system */ -#define OPENVPN_STATE_CONNECTED 4 /* Initialization sequence complete= d */ -#define OPENVPN_STATE_RECONNECTING 5 /* Restart */ -#define OPENVPN_STATE_EXITING 6 /* Exit */ +#define OPENVPN_STATE_INITIAL 0 /* Initial, undefined state */ +#define OPENVPN_STATE_CONNECTING 1 /* Management interface has been init= ialized */ +#define OPENVPN_STATE_ASSIGN_IP 2 /* Assigning IP address to virtual ne= twork interface */ +#define OPENVPN_STATE_ADD_ROUTES 3 /* Adding routes to system */ +#define OPENVPN_STATE_CONNECTED 4 /* Initialization sequence completed = */ +#define OPENVPN_STATE_RECONNECTING 5 /* Restart */ +#define OPENVPN_STATE_EXITING 6 /* Exit */ /* client-only states */ -#define OPENVPN_STATE_WAIT 7 /* Waiting for initial response fro= m server */ -#define OPENVPN_STATE_AUTH 8 /* Authenticating with server */ -#define OPENVPN_STATE_GET_CONFIG 9 /* Downloading configuration from s= erver */ -#define OPENVPN_STATE_RESOLVE 10 /* DNS lookup */ -#define OPENVPN_STATE_TCP_CONNECT 11 /* Connecting to TCP server */ -#define OPENVPN_STATE_AUTH_PENDING 12 /* Waiting in auth-pending mode - * technically variant of GET_CONFI= G */ +#define OPENVPN_STATE_WAIT 7 /* Waiting for initial response from = server */ +#define OPENVPN_STATE_AUTH 8 /* Authenticating with server */ +#define OPENVPN_STATE_GET_CONFIG 9 /* Downloading configuration from ser= ver */ +#define OPENVPN_STATE_RESOLVE 10 /* DNS lookup */ +#define OPENVPN_STATE_TCP_CONNECT 11 /* Connecting to TCP server */ +#define OPENVPN_STATE_AUTH_PENDING \ + 12 /* Waiting in auth-pending mode \ + * technically variant of GET_CONFIG = */ -#define OPENVPN_STATE_CLIENT_BASE 7 /* Base index of client-only states= */ +#define OPENVPN_STATE_CLIENT_BASE 7 /* Base index of client-only states */ -void management_set_state(struct management *man, - const int state, - const char *detail, - const in_addr_t *tun_local_ip, - const struct in6_addr *tun_local_ip6, +void management_set_state(struct management *man, const int state, const c= har *detail, + const in_addr_t *tun_local_ip, const struct in6_= addr *tun_local_ip6, const struct openvpn_sockaddr *local_addr, const struct openvpn_sockaddr *remote_addr); @@ -513,15 +492,10 @@ * These functions drive the bytecount in/out counters. */ -void -management_check_bytecount(struct context *c, - struct management *man, - struct timeval *timeval); +void management_check_bytecount(struct context *c, struct management *man,= struct timeval *timeval); static inline void -management_bytes_client(struct management *man, - const int size_in, - const int size_out) +management_bytes_client(struct management *man, const int size_in, const i= nt size_out) { if (!(man->persist.callback.flags & MCF_SERVER)) { @@ -530,27 +504,24 @@ } } -void -man_bytecount_output_server(const counter_type *bytes_in_total, - const counter_type *bytes_out_total, - struct man_def_auth_context *mdac); +void man_bytecount_output_server(const counter_type *bytes_in_total, + const counter_type *bytes_out_total, + struct man_def_auth_context *mdac); static inline void -management_bytes_server(struct management *man, - const counter_type *bytes_in_total, - const counter_type *bytes_out_total, - struct man_def_auth_context *mdac) +management_bytes_server(struct management *man, const counter_type *bytes_= in_total, + const counter_type *bytes_out_total, struct man_de= f_auth_context *mdac) { if (man->connection.bytecount_update_seconds > 0 && now >=3D mdac->bytecount_last_update + man->connection.bytecoun= t_update_seconds - && (mdac->flags & (DAF_CONNECTION_ESTABLISHED | DAF_CONNECTION_CLO= SED)) =3D=3D DAF_CONNECTION_ESTABLISHED) + && (mdac->flags & (DAF_CONNECTION_ESTABLISHED | DAF_CONNECTION_CLO= SED)) + =3D=3D DAF_CONNECTION_ESTABLISHED) { man_bytecount_output_server(bytes_in_total, bytes_out_total, mdac); } } -void -man_persist_client_stats(struct management *man, struct context *c); +void man_persist_client_stats(struct management *man, struct context *c); #endif /* ifdef ENABLE_MANAGEMENT */ diff --git a/src/openvpn/mbedtls_compat.h b/src/openvpn/mbedtls_compat.h index 655c48f..62ed257 100644 --- a/src/openvpn/mbedtls_compat.h +++ b/src/openvpn/mbedtls_compat.h @@ -48,7 +48,7 @@ #include =20 #ifdef HAVE_PSA_CRYPTO_H - #include +#include #endif #if MBEDTLS_VERSION_NUMBER >=3D 0x03000000 @@ -89,8 +89,7 @@ * an error code. */ static inline int -mbedtls_compat_ctr_drbg_update(mbedtls_ctr_drbg_context *ctx, - const unsigned char *additional, +mbedtls_compat_ctr_drbg_update(mbedtls_ctr_drbg_context *ctx, const unsign= ed char *additional, size_t add_len) { #if MBEDTLS_VERSION_NUMBER > 0x03000000 @@ -115,8 +114,7 @@ } static inline int -mbedtls_compat_pk_parse_key(mbedtls_pk_context *ctx, - const unsigned char *key, size_t keylen, +mbedtls_compat_pk_parse_key(mbedtls_pk_context *ctx, const unsigned char *= key, size_t keylen, const unsigned char *pwd, size_t pwdlen, int (*f_rng)(void *, unsigned char *, size_t),= void *p_rng) { @@ -128,8 +126,7 @@ } static inline int -mbedtls_compat_pk_parse_keyfile(mbedtls_pk_context *ctx, - const char *path, const char *password, +mbedtls_compat_pk_parse_keyfile(mbedtls_pk_context *ctx, const char *path,= const char *password, int (*f_rng)(void *, unsigned char *, size= _t), void *p_rng) { #if MBEDTLS_VERSION_NUMBER < 0x03020100 @@ -140,8 +137,9 @@ } #if MBEDTLS_VERSION_NUMBER < 0x03020100 -typedef enum { - MBEDTLS_SSL_VERSION_UNKNOWN, /*!< Context not in use or version not ye= t negotiated. */ +typedef enum +{ + MBEDTLS_SSL_VERSION_UNKNOWN, /*!< Context not in use or versio= n not yet negotiated. */ MBEDTLS_SSL_VERSION_TLS1_2 =3D 0x0303, /*!< (D)TLS 1.2 */ MBEDTLS_SSL_VERSION_TLS1_3 =3D 0x0304, /*!< (D)TLS 1.3 */ } mbedtls_ssl_protocol_version; diff --git a/src/openvpn/mbuf.c b/src/openvpn/mbuf.c index 76f2e58..0750fec 100644 --- a/src/openvpn/mbuf.c +++ b/src/openvpn/mbuf.c @@ -50,7 +50,7 @@ if (ms) { int i; - for (i =3D 0; i < (int) ms->len; ++i) + for (i =3D 0; i < (int)ms->len; ++i) { struct mbuf_item *item =3D &ms->array[MBUF_INDEX(ms->head, i, = ms->capacity)]; mbuf_free_buf(item->buffer); @@ -134,7 +134,7 @@ if (ms) { int i; - for (i =3D 0; i < (int) ms->len; ++i) + for (i =3D 0; i < (int)ms->len; ++i) { struct mbuf_item *item =3D &ms->array[MBUF_INDEX(ms->head, i, = ms->capacity)]; if (item->instance) @@ -153,7 +153,7 @@ if (ms) { int i; - for (i =3D 0; i < (int) ms->len; ++i) + for (i =3D 0; i < (int)ms->len; ++i) { struct mbuf_item *item =3D &ms->array[MBUF_INDEX(ms->head, i, = ms->capacity)]; if (item->instance =3D=3D mi) diff --git a/src/openvpn/mbuf.h b/src/openvpn/mbuf.h index 8cc7ab1..7f8c1b7 100644 --- a/src/openvpn/mbuf.h +++ b/src/openvpn/mbuf.h @@ -35,14 +35,14 @@ struct multi_instance; -#define MBUF_INDEX(head, offset, size) (((head) + (offset)) & ((size)-1)) +#define MBUF_INDEX(head, offset, size) (((head) + (offset)) & ((size) - 1)) struct mbuf_buffer { struct buffer buf; int refcount; -#define MF_UNICAST (1<<0) +#define MF_UNICAST (1 << 0) unsigned int flags; }; @@ -90,7 +90,7 @@ static inline int mbuf_maximum_queued(const struct mbuf_set *ms) { - return (int) ms->max_queued; + return (int)ms->max_queued; } struct multi_instance *mbuf_peek_dowork(struct mbuf_set *ms); diff --git a/src/openvpn/memdbg.h b/src/openvpn/memdbg.h index 9f8ff11..738a775 100644 --- a/src/openvpn/memdbg.h +++ b/src/openvpn/memdbg.h @@ -38,7 +38,8 @@ * from uninitialized data, we need to untaint it before use -- * otherwise we will get a lot of useless warnings. * - * valgrind --tool=3Dmemcheck --error-limit=3Dno --suppressions=3Ddebug/= valgrind-suppress --gen-suppressions=3Dyes ./openvpn ... + * valgrind --tool=3Dmemcheck --error-limit=3Dno --suppressions=3Ddebug/= valgrind-suppress + * --gen-suppressions=3Dyes ./openvpn ... */ #ifdef USE_VALGRIND @@ -47,7 +48,7 @@ #define VALGRIND_MAKE_READABLE(addr, len) -#else /* ifdef USE_VALGRIND */ +#else /* ifdef USE_VALGRIND */ #define VALGRIND_MAKE_READABLE(addr, len) @@ -85,7 +86,8 @@ #include -#define openvpn_dmalloc(file, line, size) dmalloc_malloc((file), (line), (= size), DMALLOC_FUNC_MALLOC, 0, 0) +#define openvpn_dmalloc(file, line, size) \ + dmalloc_malloc((file), (line), (size), DMALLOC_FUNC_MALLOC, 0, 0) /* * This #define will put the line number of the log diff --git a/src/openvpn/misc.c b/src/openvpn/misc.c index 5776d6a..17f7706 100644 --- a/src/openvpn/misc.c +++ b/src/openvpn/misc.c @@ -84,7 +84,7 @@ uint8_t rnd_bytes[n_rnd_bytes]; const char *rnd_str; - struct buffer hname =3D alloc_buf_gc(strlen(hostname)+sizeof(rnd_bytes= )*2+4, gc); + struct buffer hname =3D alloc_buf_gc(strlen(hostname) + sizeof(rnd_byt= es) * 2 + 4, gc); prng_bytes(rnd_bytes, sizeof(rnd_bytes)); rnd_str =3D format_hex_ex(rnd_bytes, sizeof(rnd_bytes), 40, 0, NULL, g= c); @@ -118,7 +118,9 @@ } else { - msg(M_FATAL, "ERROR: could not read %s username/password/ok/st= ring from management interface", prefix); + msg(M_FATAL, + "ERROR: could not read %s username/password/ok/string from= management interface", + prefix); } } return true; @@ -134,7 +136,8 @@ * @param auth_challenge The authentication challenge string to parse. Can= 't be NULL. * @param gc The gc_arena structure for memory allocation. * - * @return A pointer to the parsed auth_challenge_info struc= ture, or NULL if parsing fails. + * @return A pointer to the parsed auth_challenge_info struc= ture, or NULL if parsing + * fails. */ static struct auth_challenge_info * parse_auth_challenge(const char *auth_challenge, struct gc_arena *gc) @@ -143,7 +146,7 @@ struct auth_challenge_info *ac; const int len =3D strlen(auth_challenge); - char *work =3D (char *) gc_malloc(len+1, false, gc); + char *work =3D (char *)gc_malloc(len + 1, false, gc); char *cp; struct buffer b; @@ -191,7 +194,7 @@ { return NULL; } - ac->user =3D (char *) gc_malloc(strlen(work)+1, true, gc); + ac->user =3D (char *)gc_malloc(strlen(work) + 1, true, gc); openvpn_base64_decode(work, (void *)ac->user, -1); /* parse challenge text */ @@ -207,11 +210,8 @@ */ bool -get_user_pass_cr(struct user_pass *up, - const char *auth_file, - const char *prefix, - const unsigned int flags, - const char *auth_challenge) +get_user_pass_cr(struct user_pass *up, const char *auth_file, const char *= prefix, + const unsigned int flags, const char *auth_challenge) { struct gc_arena gc =3D gc_new(); @@ -232,8 +232,7 @@ /* * Get username/password from management interface? */ - if (management - && (!from_authfile && (flags & GET_USER_PASS_MANAGEMENT)) + if (management && (!from_authfile && (flags & GET_USER_PASS_MANAGE= MENT)) && management_query_user_pass_enabled(management)) { response_from_stdin =3D false; @@ -244,118 +243,119 @@ } else #endif /* ifdef ENABLE_MANAGEMENT */ - /* - * Get NEED_OK confirmation from the console - */ - if (flags & GET_USER_PASS_NEED_OK) - { - struct buffer user_prompt =3D alloc_buf_gc(128, &gc); - - buf_printf(&user_prompt, "NEED-OK|%s|%s:", prefix, up->usernam= e); - if (!query_user_SINGLE(BSTR(&user_prompt), BLEN(&user_prompt), - up->password, USER_PASS_LEN, false)) - { - msg(M_FATAL, "ERROR: could not read %s ok-confirmation fro= m stdin", prefix); - } - - if (!strlen(up->password)) - { - strcpy(up->password, "ok"); - } - } - else if (flags & GET_USER_PASS_INLINE_CREDS) - { - struct buffer buf; - buf_set_read(&buf, (uint8_t *) auth_file, strlen(auth_file) + = 1); - if (!(flags & GET_USER_PASS_PASSWORD_ONLY)) - { - buf_parse(&buf, '\n', up->username, USER_PASS_LEN); - } - buf_parse(&buf, '\n', up->password, USER_PASS_LEN); - - if (strlen(up->password) =3D=3D 0) - { - password_from_stdin =3D 1; - } - } - /* - * Read from auth file unless this is a dynamic challenge request. - */ - else if (from_authfile && !(flags & GET_USER_PASS_DYNAMIC_CHALLENG= E)) - { /* - * Try to get username/password from a file. + * Get NEED_OK confirmation from the console */ - FILE *fp; - char password_buf[USER_PASS_LEN] =3D { '\0' }; - - fp =3D platform_fopen(auth_file, "r"); - if (!fp) + if (flags & GET_USER_PASS_NEED_OK) { - msg(M_ERR, "Error opening '%s' auth file: %s", prefix, aut= h_file); - } + struct buffer user_prompt =3D alloc_buf_gc(128, &gc); - if ((flags & GET_USER_PASS_PASSWORD_ONLY) =3D=3D 0) - { - /* Read username first */ - if (fgets(up->username, USER_PASS_LEN, fp) =3D=3D NULL) + buf_printf(&user_prompt, "NEED-OK|%s|%s:", prefix, up->use= rname); + if (!query_user_SINGLE(BSTR(&user_prompt), BLEN(&user_prom= pt), up->password, + USER_PASS_LEN, false)) { - msg(M_FATAL, "Error reading username from %s authfile:= %s", - prefix, + msg(M_FATAL, "ERROR: could not read %s ok-confirmation= from stdin", prefix); + } + + if (!strlen(up->password)) + { + strcpy(up->password, "ok"); + } + } + else if (flags & GET_USER_PASS_INLINE_CREDS) + { + struct buffer buf; + buf_set_read(&buf, (uint8_t *)auth_file, strlen(auth_file)= + 1); + if (!(flags & GET_USER_PASS_PASSWORD_ONLY)) + { + buf_parse(&buf, '\n', up->username, USER_PASS_LEN); + } + buf_parse(&buf, '\n', up->password, USER_PASS_LEN); + + if (strlen(up->password) =3D=3D 0) + { + password_from_stdin =3D 1; + } + } + /* + * Read from auth file unless this is a dynamic challenge requ= est. + */ + else if (from_authfile && !(flags & GET_USER_PASS_DYNAMIC_CHAL= LENGE)) + { + /* + * Try to get username/password from a file. + */ + FILE *fp; + char password_buf[USER_PASS_LEN] =3D { '\0' }; + + fp =3D platform_fopen(auth_file, "r"); + if (!fp) + { + msg(M_ERR, "Error opening '%s' auth file: %s", prefix,= auth_file); + } + + if ((flags & GET_USER_PASS_PASSWORD_ONLY) =3D=3D 0) + { + /* Read username first */ + if (fgets(up->username, USER_PASS_LEN, fp) =3D=3D NULL) + { + msg(M_FATAL, "Error reading username from %s authf= ile: %s", prefix, + auth_file); + } + } + chomp(up->username); + + if (fgets(password_buf, USER_PASS_LEN, fp) !=3D NULL) + { + chomp(password_buf); + } + + if (flags & GET_USER_PASS_PASSWORD_ONLY && !password_buf[0= ]) + { + msg(M_FATAL, "Error reading password from %s authfile:= %s", prefix, auth_file); + } + + if (password_buf[0]) + { + strncpy(up->password, password_buf, USER_PASS_LEN); + } + /* The auth-file does not have the password: get both user= name + * and password from the management interface if possible. + * Otherwise set to read password from console. + */ +#if defined(ENABLE_MANAGEMENT) + else if (management && (flags & GET_USER_PASS_MANAGEMENT) + && management_query_user_pass_enabled(management)) + { + msg(D_LOW, + "No password found in %s authfile '%s'. Querying t= he management interface", + prefix, auth_file); + if (!auth_user_pass_mgmt(up, prefix, flags, auth_chall= enge)) + { + fclose(fp); + return false; + } + } +#endif + else + { + password_from_stdin =3D 1; + } + + fclose(fp); + + if (!(flags & GET_USER_PASS_PASSWORD_ONLY) && strlen(up->u= sername) =3D=3D 0) + { + msg(M_FATAL, "ERROR: username from %s authfile '%s' is= empty", prefix, auth_file); } } - chomp(up->username); - - if (fgets(password_buf, USER_PASS_LEN, fp) !=3D NULL) - { - chomp(password_buf); - } - - if (flags & GET_USER_PASS_PASSWORD_ONLY && !password_buf[0]) - { - msg(M_FATAL, "Error reading password from %s authfile: %s"= , prefix, auth_file); - } - - if (password_buf[0]) - { - strncpy(up->password, password_buf, USER_PASS_LEN); - } - /* The auth-file does not have the password: get both username - * and password from the management interface if possible. - * Otherwise set to read password from console. - */ -#if defined(ENABLE_MANAGEMENT) - else if (management - && (flags & GET_USER_PASS_MANAGEMENT) - && management_query_user_pass_enabled(management)) - { - msg(D_LOW, "No password found in %s authfile '%s'. Queryin= g the management interface", prefix, auth_file); - if (!auth_user_pass_mgmt(up, prefix, flags, auth_challenge= )) - { - fclose(fp); - return false; - } - } -#endif else { - password_from_stdin =3D 1; + username_from_stdin =3D true; + password_from_stdin =3D true; } - fclose(fp); - - if (!(flags & GET_USER_PASS_PASSWORD_ONLY) && strlen(up->usern= ame) =3D=3D 0) - { - msg(M_FATAL, "ERROR: username from %s authfile '%s' is emp= ty", prefix, auth_file); - } - } - else - { - username_from_stdin =3D true; - password_from_stdin =3D true; - } - /* * Get username/password from standard input? */ @@ -367,15 +367,15 @@ struct auth_challenge_info *ac =3D parse_auth_challenge(au= th_challenge, &gc); if (ac) { - char *response =3D (char *) gc_malloc(USER_PASS_LEN, f= alse, &gc); + char *response =3D (char *)gc_malloc(USER_PASS_LEN, fa= lse, &gc); struct buffer packed_resp, challenge; - challenge =3D alloc_buf_gc(14+strlen(ac->challenge_tex= t), &gc); + challenge =3D alloc_buf_gc(14 + strlen(ac->challenge_t= ext), &gc); buf_printf(&challenge, "CHALLENGE: %s", ac->challenge_= text); buf_set_write(&packed_resp, (uint8_t *)up->password, U= SER_PASS_LEN); - if (!query_user_SINGLE(BSTR(&challenge), BLEN(&challen= ge), - response, USER_PASS_LEN, BOOL_C= AST(ac->flags&CR_ECHO))) + if (!query_user_SINGLE(BSTR(&challenge), BLEN(&challen= ge), response, + USER_PASS_LEN, BOOL_CAST(ac->fl= ags & CR_ECHO))) { msg(M_FATAL, "ERROR: could not read challenge resp= onse from stdin"); } @@ -399,17 +399,17 @@ if (username_from_stdin && !(flags & GET_USER_PASS_PASSWOR= D_ONLY)) { - query_user_add(BSTR(&user_prompt), BLEN(&user_prompt), - up->username, USER_PASS_LEN, true); + query_user_add(BSTR(&user_prompt), BLEN(&user_prompt),= up->username, + USER_PASS_LEN, true); } if (password_from_stdin) { - query_user_add(BSTR(&pass_prompt), BLEN(&pass_prompt), - up->password, USER_PASS_LEN, false); + query_user_add(BSTR(&pass_prompt), BLEN(&pass_prompt),= up->password, + USER_PASS_LEN, false); } - if (!query_user_exec() ) + if (!query_user_exec()) { msg(M_FATAL, "ERROR: Failed retrieving username or pas= sword"); } @@ -423,17 +423,18 @@ } #ifdef ENABLE_MANAGEMENT - if (auth_challenge && (flags & GET_USER_PASS_STATIC_CHALLE= NGE) && response_from_stdin) + if (auth_challenge && (flags & GET_USER_PASS_STATIC_CHALLE= NGE) + && response_from_stdin) { - char *response =3D (char *) gc_malloc(USER_PASS_LEN, f= alse, &gc); + char *response =3D (char *)gc_malloc(USER_PASS_LEN, fa= lse, &gc); struct buffer packed_resp, challenge; char *pw64 =3D NULL, *resp64 =3D NULL; - challenge =3D alloc_buf_gc(14+strlen(auth_challenge), = &gc); + challenge =3D alloc_buf_gc(14 + strlen(auth_challenge)= , &gc); buf_printf(&challenge, "CHALLENGE: %s", auth_challenge= ); - if (!query_user_SINGLE(BSTR(&challenge), BLEN(&challen= ge), - response, USER_PASS_LEN, + if (!query_user_SINGLE(BSTR(&challenge), BLEN(&challen= ge), response, + USER_PASS_LEN, BOOL_CAST(flags & GET_USER_PASS= _STATIC_CHALLENGE_ECHO))) { msg(M_FATAL, "ERROR: could not retrieve static cha= llenge response"); @@ -456,7 +457,8 @@ { if (strlen(up->password) + strlen(response) >=3D U= SER_PASS_LEN) { - msg(M_FATAL, "ERROR: could not concatenate pas= sword/static_response: string too long"); + msg(M_FATAL, + "ERROR: could not concatenate password/sta= tic_response: string too long"); } strncat(up->password, response, USER_PASS_LEN - st= rlen(up->password) - 1); } @@ -499,7 +501,8 @@ */ if (!warn_shown) { - msg(M_WARN, "WARNING: this configuration may cache passwords i= n memory -- use the auth-nocache option to prevent this"); + msg(M_WARN, + "WARNING: this configuration may cache passwords in memory= -- use the auth-nocache option to prevent this"); warn_shown =3D true; } } @@ -594,7 +597,7 @@ char **ret =3D NULL; int i =3D 0; - buf_set_read(&buf, (const uint8_t *) str, strlen(str)); + buf_set_read(&buf, (const uint8_t *)str, strlen(str)); while (buf_parse(&buf, '\n', line, sizeof(line))) { ++len; @@ -603,7 +606,7 @@ /* alloc return array */ ALLOC_ARRAY_CLEAR_GC(ret, char *, len + 1, gc); - buf_set_read(&buf, (const uint8_t *) str, strlen(str)); + buf_set_read(&buf, (const uint8_t *)str, strlen(str)); while (buf_parse(&buf, '\n', line, sizeof(line))) { chomp(line); @@ -668,12 +671,12 @@ const char * sanitize_control_message(const char *src, struct gc_arena *gc) { - char *ret =3D gc_malloc(strlen(src)+1, false, gc); + char *ret =3D gc_malloc(strlen(src) + 1, false, gc); char *dest =3D ret; bool redact =3D false; int skip =3D 0; - for (;; ) + for (;;) { const char c =3D *src; if (c =3D=3D '\0') @@ -690,8 +693,7 @@ skip =3D 4; redact =3D true; } - else if (!check_debug_level(D_SHOW_KEYS) - && (c =3D=3D 'a' && !strncmp(src, "auth-token ", 11))) + else if (!check_debug_level(D_SHOW_KEYS) && (c =3D=3D 'a' && !strn= cmp(src, "auth-token ", 11))) { /* Unless --verb is 7 or higher (D_SHOW_KEYS), hide * the auth-token value coming in the src string @@ -755,8 +757,7 @@ case 2: /* after the '=3D', replace non-printable or shell meta wi= th '_' */ - if (!isprint(c) || isspace(c) - || c =3D=3D '$' || c =3D=3D '(' || c =3D=3D '`') + if (!isprint(c) || isspace(c) || c =3D=3D '$' || c =3D=3D = '(' || c =3D=3D '`') { *line =3D '_'; } @@ -771,12 +772,12 @@ { char line[256]; struct buffer buf; - buf_set_read(&buf, (const uint8_t *) peer_info, strlen(peer_info)); + buf_set_read(&buf, (const uint8_t *)peer_info, strlen(peer_info)); while (buf_parse(&buf, '\n', line, sizeof(line))) { chomp(line); if (validate_peer_info_line(line) - && (strncmp(line, "IV_", 3) =3D=3D 0 || strncmp(line, "UV_", 3= ) =3D=3D 0) ) + && (strncmp(line, "IV_", 3) =3D=3D 0 || strncmp(line, "UV_", 3= ) =3D=3D 0)) { msg(M_INFO, "peer info: %s", line); env_set_add(es, line); diff --git a/src/openvpn/misc.h b/src/openvpn/misc.h index eb2449c..1b10cd9 100644 --- a/src/openvpn/misc.h +++ b/src/openvpn/misc.h @@ -42,8 +42,7 @@ const char **make_arg_array(const char *first, const char *parms, struct g= c_arena *gc); -const char **make_extended_arg_array(char **p, bool is_inline, - struct gc_arena *gc); +const char **make_extended_arg_array(char **p, bool is_inline, struct gc_a= rena *gc); /* prepend a random prefix to hostname */ const char *hostname_randomize(const char *hostname, struct gc_arena *gc); @@ -76,9 +75,10 @@ /* * Challenge response info on client as pushed by server. */ -struct auth_challenge_info { -#define CR_ECHO (1<<0) /* echo response when typed by user */ -#define CR_RESPONSE (1<<1) /* response needed */ +struct auth_challenge_info +{ +#define CR_ECHO (1 << 0) /* echo response when typed by user */ +#define CR_RESPONSE (1 << 1) /* response needed */ unsigned int flags; const char *user; @@ -89,38 +89,43 @@ /* * Challenge response info on client as pushed by server. */ -struct static_challenge_info { -#define SC_ECHO (1<<0) /* echo response when typed by user */ -#define SC_CONCAT (1<<1) /* concatenate password and response and do no= t base64 encode */ +struct static_challenge_info +{ +#define SC_ECHO (1 << 0) /* echo response when typed by user */ +#define SC_CONCAT (1 << 1) /* concatenate password and response and do not= base64 encode */ unsigned int flags; const char *challenge_text; }; #else /* ifdef ENABLE_MANAGEMENT */ -struct auth_challenge_info {}; -struct static_challenge_info {}; +struct auth_challenge_info +{ +}; +struct static_challenge_info +{ +}; #endif /* ifdef ENABLE_MANAGEMENT */ /* * Flags for get_user_pass and management_query_user_pass */ -#define GET_USER_PASS_MANAGEMENT (1<<0) +#define GET_USER_PASS_MANAGEMENT (1 << 0) /* GET_USER_PASS_SENSITIVE (1<<1) not used anymore */ -#define GET_USER_PASS_PASSWORD_ONLY (1<<2) -#define GET_USER_PASS_NEED_OK (1<<3) -#define GET_USER_PASS_NOFATAL (1<<4) -#define GET_USER_PASS_NEED_STR (1<<5) -#define GET_USER_PASS_PREVIOUS_CREDS_FAILED (1<<6) +#define GET_USER_PASS_PASSWORD_ONLY (1 << 2) +#define GET_USER_PASS_NEED_OK (1 << 3) +#define GET_USER_PASS_NOFATAL (1 << 4) +#define GET_USER_PASS_NEED_STR (1 << 5) +#define GET_USER_PASS_PREVIOUS_CREDS_FAILED (1 << 6) -#define GET_USER_PASS_DYNAMIC_CHALLENGE (1<<7) /**< CRV1 protocol --= dynamic challenge */ -#define GET_USER_PASS_STATIC_CHALLENGE (1<<8) /**< SCRV1 protocol --= static challenge */ -#define GET_USER_PASS_STATIC_CHALLENGE_ECHO (1<<9) /**< SCRV1 protocol --= echo response */ +#define GET_USER_PASS_DYNAMIC_CHALLENGE (1 << 7) /**< CRV1 protocol -= - dynamic challenge */ +#define GET_USER_PASS_STATIC_CHALLENGE (1 << 8) /**< SCRV1 protocol -= - static challenge */ +#define GET_USER_PASS_STATIC_CHALLENGE_ECHO (1 << 9) /**< SCRV1 protocol -= - echo response */ /** indicates that auth_file is actually inline creds */ -#define GET_USER_PASS_INLINE_CREDS (1<<10) +#define GET_USER_PASS_INLINE_CREDS (1 << 10) /** indicates password and response should be concatenated */ -#define GET_USER_PASS_STATIC_CHALLENGE_CONCAT (1<<11) +#define GET_USER_PASS_STATIC_CHALLENGE_CONCAT (1 << 11) /** * Retrieves the user credentials from various sources depending on the fl= ags. @@ -132,11 +137,8 @@ * @param auth_challenge The authentication challenge string. * @return true if the user credentials were successfully retrieved, false= otherwise. */ -bool get_user_pass_cr(struct user_pass *up, - const char *auth_file, - const char *prefix, - const unsigned int flags, - const char *auth_challenge); +bool get_user_pass_cr(struct user_pass *up, const char *auth_file, const c= har *prefix, + const unsigned int flags, const char *auth_challenge= ); /** * Retrieves the user credentials from various sources depending on the fl= ags. @@ -148,9 +150,7 @@ * @return true if the user credentials were successfully retrieved, false= otherwise. */ static inline bool -get_user_pass(struct user_pass *up, - const char *auth_file, - const char *prefix, +get_user_pass(struct user_pass *up, const char *auth_file, const char *pre= fix, const unsigned int flags) { return get_user_pass_cr(up, auth_file, prefix, flags, NULL); @@ -205,29 +205,24 @@ /** * Prepend a directory to a path. */ -struct buffer -prepend_dir(const char *dir, const char *path, struct gc_arena *gc); +struct buffer prepend_dir(const char *dir, const char *path, struct gc_are= na *gc); /** * Encrypt username and password buffers in user_pass */ -void -protect_user_pass(struct user_pass *up); +void protect_user_pass(struct user_pass *up); =20 /** * Decrypt username and password buffers in user_pass */ -void -unprotect_user_pass(struct user_pass *up); +void unprotect_user_pass(struct user_pass *up); -#define _STRINGIFY(S) #S +#define _STRINGIFY(S) #S /* *INDENT-OFF* - uncrustify need to ignore this macro */ -#define MAC_FMT _STRINGIFY(%02hhx:%02hhx:%02hhx:%02hhx:%02hhx:%02hhx) +#define MAC_FMT _STRINGIFY(%02hhx:%02hhx:%02hhx:%02hhx:%02hhx:= %02hhx) /* *INDENT-ON* */ -#define MAC_PRINT_ARG(_mac) _mac[0], _mac[1], _mac[2], \ - _mac[3], _mac[4], _mac[5] -#define MAC_SCAN_ARG(_mac) &_mac[0], &_mac[1], &_mac[2], \ - &_mac[3], &_mac[4], &_mac[5] +#define MAC_PRINT_ARG(_mac) _mac[0], _mac[1], _mac[2], _mac[3], _mac[4], _= mac[5] +#define MAC_SCAN_ARG(_mac) &_mac[0], &_mac[1], &_mac[2], &_mac[3], &_mac[= 4], &_mac[5] #endif /* ifndef MISC_H */ diff --git a/src/openvpn/mroute.c b/src/openvpn/mroute.c index b14be7e..a598037 100644 --- a/src/openvpn/mroute.c +++ b/src/openvpn/mroute.c @@ -47,14 +47,13 @@ static inline bool is_mac_mcast_addr(const uint8_t *mac) { - return (bool) (mac[0] & 1); + return (bool)(mac[0] & 1); } static inline bool is_mac_mcast_maddr(const struct mroute_addr *addr) { - return (addr->type & MR_ADDR_MASK) =3D=3D MR_ADDR_ETHER - && is_mac_mcast_addr(addr->ether.addr); + return (addr->type & MR_ADDR_MASK) =3D=3D MR_ADDR_ETHER && is_mac_mcas= t_addr(addr->ether.addr); } /* @@ -81,8 +80,7 @@ } /* only networkss shorter than 8 bits are allowed to be all 0s. */ - if (all_zeros - && !((addr->type & MR_WITH_NETBITS) && (addr->netbits < 8))) + if (all_zeros && !((addr->type & MR_WITH_NETBITS) && (addr->netbits < = 8))) { msg(D_MULTI_LOW, "Can't learn %s: network is all 0s, but netbits >= =3D 8", mroute_addr_print(addr, gc)); @@ -91,8 +89,7 @@ if (all_ones) { - msg(D_MULTI_LOW, "Can't learn %s: network is all 1s", - mroute_addr_print(addr, gc)); + msg(D_MULTI_LOW, "Can't learn %s: network is all 1s", mroute_addr_= print(addr, gc)); return false; } @@ -147,8 +144,7 @@ unsigned int -mroute_extract_addr_ip(struct mroute_addr *src, struct mroute_addr *dest, - const struct buffer *buf) +mroute_extract_addr_ip(struct mroute_addr *src, struct mroute_addr *dest, = const struct buffer *buf) { unsigned int ret =3D 0; if (BLEN(buf) >=3D 1) @@ -156,9 +152,9 @@ switch (OPENVPN_IPH_GET_VER(*BPTR(buf))) { case 4: - if (BLEN(buf) >=3D (int) sizeof(struct openvpn_iphdr)) + if (BLEN(buf) >=3D (int)sizeof(struct openvpn_iphdr)) { - const struct openvpn_iphdr *ip =3D (const struct openv= pn_iphdr *) BPTR(buf); + const struct openvpn_iphdr *ip =3D (const struct openv= pn_iphdr *)BPTR(buf); mroute_get_in_addr_t(src, ip->saddr, 0); mroute_get_in_addr_t(dest, ip->daddr, 0); @@ -180,10 +176,10 @@ break; case 6: - if (BLEN(buf) >=3D (int) sizeof(struct openvpn_ipv6hdr)) + if (BLEN(buf) >=3D (int)sizeof(struct openvpn_ipv6hdr)) { - const struct openvpn_ipv6hdr *ipv6 =3D (const struct o= penvpn_ipv6hdr *) BPTR(buf); -#if 0 /* very basic debug */ + const struct openvpn_ipv6hdr *ipv6 =3D (const struct o= penvpn_ipv6hdr *)BPTR(buf); +#if 0 /* very basic debug */ struct gc_arena gc =3D gc_new(); msg( M_INFO, "IPv6 packet! src=3D%s, dst=3D%s", print_in6_addr( ipv6->saddr, 0, &gc ), @@ -212,9 +208,7 @@ } static void -mroute_copy_ether_to_addr(struct mroute_addr *maddr, - const uint8_t *ether_addr, - uint16_t vid) +mroute_copy_ether_to_addr(struct mroute_addr *maddr, const uint8_t *ether_= addr, uint16_t vid) { maddr->type =3D MR_ADDR_ETHER; maddr->netbits =3D 0; @@ -225,15 +219,13 @@ } unsigned int -mroute_extract_addr_ether(struct mroute_addr *src, - struct mroute_addr *dest, - uint16_t vid, +mroute_extract_addr_ether(struct mroute_addr *src, struct mroute_addr *des= t, uint16_t vid, const struct buffer *buf) { unsigned int ret =3D 0; - if (BLEN(buf) >=3D (int) sizeof(struct openvpn_ethhdr)) + if (BLEN(buf) >=3D (int)sizeof(struct openvpn_ethhdr)) { - const struct openvpn_ethhdr *eth =3D (const struct openvpn_ethhdr = *) BPTR(buf); + const struct openvpn_ethhdr *eth =3D (const struct openvpn_ethhdr = *)BPTR(buf); if (src) { mroute_copy_ether_to_addr(src, eth->source, vid); @@ -250,7 +242,6 @@ } ret |=3D MROUTE_EXTRACT_SUCCEEDED; - } return ret; } @@ -260,8 +251,7 @@ * to a struct mroute_addr (addr). */ bool -mroute_extract_openvpn_sockaddr(struct mroute_addr *addr, - const struct openvpn_sockaddr *osaddr, +mroute_extract_openvpn_sockaddr(struct mroute_addr *addr, const struct ope= nvpn_sockaddr *osaddr, bool use_port) { switch (osaddr->addr.sa.sa_family) @@ -335,7 +325,7 @@ } else if ((ma->type & MR_ADDR_MASK) =3D=3D MR_ADDR_IPV6) { - int byte =3D sizeof(ma->v6.addr) - 1; /* rightmost byte in add= ress */ + int byte =3D sizeof(ma->v6.addr) - 1; /* rightmost byte in address= */ int bits_to_clear =3D 128 - ma->netbits; while (byte >=3D 0 && bits_to_clear > 0) @@ -351,7 +341,7 @@ bits_to_clear =3D 0; } } - ASSERT( bits_to_clear =3D=3D 0 ); + ASSERT(bits_to_clear =3D=3D 0); } else { @@ -367,29 +357,24 @@ uint32_t mroute_addr_hash_function(const void *key, uint32_t iv) { - return hash_func(mroute_addr_hash_ptr((const struct mroute_addr *) key= ), - mroute_addr_hash_len((const struct mroute_addr *) key= ), - iv); + return hash_func(mroute_addr_hash_ptr((const struct mroute_addr *)key), + mroute_addr_hash_len((const struct mroute_addr *)key)= , iv); } bool mroute_addr_compare_function(const void *key1, const void *key2) { - return mroute_addr_equal((const struct mroute_addr *) key1, - (const struct mroute_addr *) key2); + return mroute_addr_equal((const struct mroute_addr *)key1, (const stru= ct mroute_addr *)key2); } const char * -mroute_addr_print(const struct mroute_addr *ma, - struct gc_arena *gc) +mroute_addr_print(const struct mroute_addr *ma, struct gc_arena *gc) { return mroute_addr_print_ex(ma, MAPF_IA_EMPTY_IF_UNDEF, gc); } const char * -mroute_addr_print_ex(const struct mroute_addr *ma, - const unsigned int flags, - struct gc_arena *gc) +mroute_addr_print_ex(const struct mroute_addr *ma, const unsigned int flag= s, struct gc_arena *gc) { struct buffer out =3D alloc_buf_gc(64, gc); if (ma) @@ -399,8 +384,8 @@ switch (maddr.type & MR_ADDR_MASK) { case MR_ADDR_ETHER: - buf_printf(&out, "%s", format_hex_ex(ma->ether.addr, - sizeof(ma->ether.addr= ), 0, 1, ":", gc)); + buf_printf(&out, "%s", + format_hex_ex(ma->ether.addr, sizeof(ma->ether.= addr), 0, 1, ":", gc)); buf_printf(&out, "@%hu", ma->ether.vid); break; @@ -418,8 +403,10 @@ { buf_printf(&out, "[AF_INET]"); } - buf_printf(&out, "%s", print_in_addr_t(ntohl(maddr.v4.addr= ), - (flags & MAPF_IA_EM= PTY_IF_UNDEF) ? IA_EMPTY_IF_UNDEF : 0, gc)); + buf_printf(&out, "%s", + print_in_addr_t(ntohl(maddr.v4.addr), + (flags & MAPF_IA_EMPTY_IF_UNDEF= ) ? IA_EMPTY_IF_UNDEF : 0, + gc)); if (maddr.type & MR_WITH_NETBITS) { if (flags & MAPF_SUBNET) @@ -449,10 +436,10 @@ { buf_printf(&out, "[AF_INET6]"); } - if (IN6_IS_ADDR_V4MAPPED( &maddr.v6.addr ) ) + if (IN6_IS_ADDR_V4MAPPED(&maddr.v6.addr)) { - buf_printf(&out, "%s", print_in_addr_t(maddr.v4mappedv= 6.addr, - IA_NET_ORDER, g= c)); + buf_printf(&out, "%s", + print_in_addr_t(maddr.v4mappedv6.addr, IA_N= ET_ORDER, gc)); } else if (maddr.type & MR_WITH_PORT) { @@ -508,7 +495,7 @@ { if (mh->net_len_refcount[i] > 0) { - mh->net_len[j++] =3D (uint8_t) i; + mh->net_len[j++] =3D (uint8_t)i; } } mh->n_net_len =3D j; diff --git a/src/openvpn/mroute.h b/src/openvpn/mroute.h index e06d272..5b0c694 100644 --- a/src/openvpn/mroute.h +++ b/src/openvpn/mroute.h @@ -29,22 +29,22 @@ #include -#define IP_MCAST_SUBNET_MASK ((in_addr_t)240<<24) -#define IP_MCAST_NETWORK ((in_addr_t)224<<24) +#define IP_MCAST_SUBNET_MASK ((in_addr_t)240 << 24) +#define IP_MCAST_NETWORK ((in_addr_t)224 << 24) /* Return status values for mroute_extract_addr_from_packet */ -#define MROUTE_EXTRACT_SUCCEEDED (1<<0) -#define MROUTE_EXTRACT_BCAST (1<<1) -#define MROUTE_EXTRACT_MCAST (1<<2) -#define MROUTE_EXTRACT_IGMP (1<<3) +#define MROUTE_EXTRACT_SUCCEEDED (1 << 0) +#define MROUTE_EXTRACT_BCAST (1 << 1) +#define MROUTE_EXTRACT_MCAST (1 << 2) +#define MROUTE_EXTRACT_IGMP (1 << 3) -#define MROUTE_SEC_EXTRACT_SUCCEEDED (1<<(0+MROUTE_SEC_SHIFT)) -#define MROUTE_SEC_EXTRACT_BCAST (1<<(1+MROUTE_SEC_SHIFT)) -#define MROUTE_SEC_EXTRACT_MCAST (1<<(2+MROUTE_SEC_SHIFT)) -#define MROUTE_SEC_EXTRACT_IGMP (1<<(3+MROUTE_SEC_SHIFT)) +#define MROUTE_SEC_EXTRACT_SUCCEEDED (1 << (0 + MROUTE_SEC_SHIFT)) +#define MROUTE_SEC_EXTRACT_BCAST (1 << (1 + MROUTE_SEC_SHIFT)) +#define MROUTE_SEC_EXTRACT_MCAST (1 << (2 + MROUTE_SEC_SHIFT)) +#define MROUTE_SEC_EXTRACT_IGMP (1 << (3 + MROUTE_SEC_SHIFT)) -#define MROUTE_SEC_SHIFT 4 +#define MROUTE_SEC_SHIFT 4 /* * Choose the largest address possible with @@ -56,60 +56,64 @@ /* * Address Types */ -#define MR_ADDR_NONE 0 -#define MR_ADDR_ETHER 1 -#define MR_ADDR_IPV4 2 -#define MR_ADDR_IPV6 3 -#define MR_ADDR_MASK 3 +#define MR_ADDR_NONE 0 +#define MR_ADDR_ETHER 1 +#define MR_ADDR_IPV4 2 +#define MR_ADDR_IPV6 3 +#define MR_ADDR_MASK 3 /* Address type mask indicating that port # is part of address */ -#define MR_WITH_PORT 4 +#define MR_WITH_PORT 4 /* Address type mask indicating that netbits is part of address */ -#define MR_WITH_NETBITS 8 +#define MR_WITH_NETBITS 8 /* Indicates than IPv4 addr was extracted from ARP packet */ -#define MR_ARP 16 +#define MR_ARP 16 /* Address type mask indicating that proto # is part of address */ -#define MR_WITH_PROTO 32 +#define MR_WITH_PROTO 32 -struct mroute_addr { - uint8_t len; /* length of address */ +struct mroute_addr +{ + uint8_t len; /* length of address */ uint8_t proto; - uint8_t type; /* MR_ADDR/MR_WITH flags */ + uint8_t type; /* MR_ADDR/MR_WITH flags */ uint8_t netbits; /* number of bits in network part of address, * valid if MR_WITH_NETBITS is set */ - union { + union + { uint8_t raw_addr[MR_MAX_ADDR_LEN]; /* actual address */ - struct { + struct + { uint8_t addr[OPENVPN_ETH_ALEN]; uint16_t vid; } ether; - struct { - in_addr_t addr; /* _network order_ IPv4 address */ - in_port_t port; /* _network order_ TCP/UDP port */ + struct + { + in_addr_t addr; /* _network order_ IPv4 address */ + in_port_t port; /* _network order_ TCP/UDP port */ } v4; - struct { + struct + { struct in6_addr addr; - in_port_t port; /* _network order_ TCP/UDP port */ + in_port_t port; /* _network order_ TCP/UDP port */ } v6; - struct { + struct + { uint8_t prefix[12]; - in_addr_t addr; /* _network order_ IPv4 address */ + in_addr_t addr; /* _network order_ IPv4 address */ } v4mappedv6; }; }; /* Double-check that struct packing works as expected */ -static_assert(offsetof(struct mroute_addr, v4.port) =3D=3D - offsetof(struct mroute_addr, v4) + 4, +static_assert(offsetof(struct mroute_addr, v4.port) =3D=3D offsetof(struct= mroute_addr, v4) + 4, "Unexpected struct packing of v4"); -static_assert(offsetof(struct mroute_addr, v6.port) =3D=3D - offsetof(struct mroute_addr, v6) + 16, +static_assert(offsetof(struct mroute_addr, v6.port) =3D=3D offsetof(struct= mroute_addr, v6) + 16, "Unexpected struct packing of v6"); -static_assert(offsetof(struct mroute_addr, v4mappedv6.addr) =3D=3D - offsetof(struct mroute_addr, v4mappedv6) + 12, +static_assert(offsetof(struct mroute_addr, v4mappedv6.addr) + =3D=3D offsetof(struct mroute_addr, v4mappedv6) + 12, "Unexpected struct packing of v4mappedv6"); /* @@ -120,22 +124,21 @@ /* * Used to help maintain CIDR routing table. */ -struct mroute_helper { - unsigned int cache_generation; /* incremented when route added */ - int ageable_ttl_secs; /* host route cache entry time-to-live*/ - int n_net_len; /* length of net_len array */ - uint8_t net_len[MR_HELPER_NET_LEN]; /* CIDR netlengths in descendin= g order */ +struct mroute_helper +{ + unsigned int cache_generation; /* incremented when route add= ed */ + int ageable_ttl_secs; /* host route cache entry tim= e-to-live*/ + int n_net_len; /* length of net_len array */ + uint8_t net_len[MR_HELPER_NET_LEN]; /* CIDR netlengths in descend= ing order */ int net_len_refcount[MR_HELPER_NET_LEN]; /* refcount of each netlength= */ }; struct openvpn_sockaddr; bool mroute_extract_openvpn_sockaddr(struct mroute_addr *addr, - const struct openvpn_sockaddr *osaddr, - bool use_port); + const struct openvpn_sockaddr *osaddr= , bool use_port); -bool mroute_learnable_address(const struct mroute_addr *addr, - struct gc_arena *gc); +bool mroute_learnable_address(const struct mroute_addr *addr, struct gc_ar= ena *gc); uint32_t mroute_addr_hash_function(const void *key, uint32_t iv); @@ -143,15 +146,13 @@ void mroute_addr_init(struct mroute_addr *addr); -const char *mroute_addr_print(const struct mroute_addr *ma, - struct gc_arena *gc); +const char *mroute_addr_print(const struct mroute_addr *ma, struct gc_aren= a *gc); -#define MAPF_SUBNET (1<<0) -#define MAPF_IA_EMPTY_IF_UNDEF (1<<1) -#define MAPF_SHOW_ARP (1<<2) -#define MAPF_SHOW_FAMILY (1<<3) -const char *mroute_addr_print_ex(const struct mroute_addr *ma, - const unsigned int flags, +#define MAPF_SUBNET (1 << 0) +#define MAPF_IA_EMPTY_IF_UNDEF (1 << 1) +#define MAPF_SHOW_ARP (1 << 2) +#define MAPF_SHOW_FAMILY (1 << 3) +const char *mroute_addr_print_ex(const struct mroute_addr *ma, const unsig= ned int flags, struct gc_arena *gc); void mroute_addr_mask_host_bits(struct mroute_addr *ma); @@ -164,25 +165,19 @@ void mroute_helper_del_iroute46(struct mroute_helper *mh, int netbits); -unsigned int mroute_extract_addr_ip(struct mroute_addr *src, - struct mroute_addr *dest, +unsigned int mroute_extract_addr_ip(struct mroute_addr *src, struct mroute= _addr *dest, const struct buffer *buf); -unsigned int mroute_extract_addr_ether(struct mroute_addr *src, - struct mroute_addr *dest, - uint16_t vid, - const struct buffer *buf); +unsigned int mroute_extract_addr_ether(struct mroute_addr *src, struct mro= ute_addr *dest, + uint16_t vid, const struct buffer *= buf); /* * Given a raw packet in buf, return the src and dest * addresses of the packet. */ static inline unsigned int -mroute_extract_addr_from_packet(struct mroute_addr *src, - struct mroute_addr *dest, - uint16_t vid, - const struct buffer *buf, - int tunnel_type) +mroute_extract_addr_from_packet(struct mroute_addr *src, struct mroute_add= r *dest, uint16_t vid, + const struct buffer *buf, int tunnel_type) { unsigned int ret =3D 0; verify_align_4(buf); @@ -232,13 +227,13 @@ mroute_addr_hash_ptr(const struct mroute_addr *a) { /* NOTE: depends on ordering of struct mroute_addr */ - return (uint8_t *) &a->proto; + return (uint8_t *)&a->proto; } static inline uint32_t mroute_addr_hash_len(const struct mroute_addr *a) { - return (uint32_t) a->len + 3; + return (uint32_t)a->len + 3; } static inline void diff --git a/src/openvpn/mss.c b/src/openvpn/mss.c index 96a9af0..32cd3f8 100644 --- a/src/openvpn/mss.c +++ b/src/openvpn/mss.c @@ -48,27 +48,24 @@ const struct openvpn_iphdr *pip; int hlen; - if (BLEN(buf) < (int) sizeof(struct openvpn_iphdr)) + if (BLEN(buf) < (int)sizeof(struct openvpn_iphdr)) { return; } verify_align_4(buf); - pip =3D (struct openvpn_iphdr *) BPTR(buf); + pip =3D (struct openvpn_iphdr *)BPTR(buf); hlen =3D OPENVPN_IPH_GET_LEN(pip->version_len); - if (pip->protocol =3D=3D OPENVPN_IPPROTO_TCP - && ntohs(pip->tot_len) =3D=3D BLEN(buf) - && (ntohs(pip->frag_off) & OPENVPN_IP_OFFMASK) =3D=3D 0 - && hlen <=3D BLEN(buf) - && BLEN(buf) - hlen - >=3D (int) sizeof(struct openvpn_tcphdr)) + if (pip->protocol =3D=3D OPENVPN_IPPROTO_TCP && ntohs(pip->tot_len) = =3D=3D BLEN(buf) + && (ntohs(pip->frag_off) & OPENVPN_IP_OFFMASK) =3D=3D 0 && hlen <= =3D BLEN(buf) + && BLEN(buf) - hlen >=3D (int)sizeof(struct openvpn_tcphdr)) { struct buffer newbuf =3D *buf; if (buf_advance(&newbuf, hlen)) { - struct openvpn_tcphdr *tc =3D (struct openvpn_tcphdr *) BPTR(&= newbuf); + struct openvpn_tcphdr *tc =3D (struct openvpn_tcphdr *)BPTR(&n= ewbuf); if (tc->flags & OPENVPN_TCPH_SYN_MASK) { mss_fixup_dowork(&newbuf, maxmss); @@ -88,18 +85,18 @@ const struct openvpn_ipv6hdr *pip6; struct buffer newbuf; - if (BLEN(buf) < (int) sizeof(struct openvpn_ipv6hdr)) + if (BLEN(buf) < (int)sizeof(struct openvpn_ipv6hdr)) { return; } verify_align_4(buf); - pip6 =3D (struct openvpn_ipv6hdr *) BPTR(buf); + pip6 =3D (struct openvpn_ipv6hdr *)BPTR(buf); /* do we have the full IPv6 packet? * "payload_len" does not include IPv6 header (+40 bytes) */ - if (BLEN(buf) !=3D (int) ntohs(pip6->payload_len)+40) + if (BLEN(buf) !=3D (int)ntohs(pip6->payload_len) + 40) { return; } @@ -123,13 +120,12 @@ * verify remainder is large enough to contain a full TCP header */ newbuf =3D *buf; - if (buf_advance( &newbuf, 40 ) - && BLEN(&newbuf) >=3D (int) sizeof(struct openvpn_tcphdr)) + if (buf_advance(&newbuf, 40) && BLEN(&newbuf) >=3D (int)sizeof(struct = openvpn_tcphdr)) { - struct openvpn_tcphdr *tc =3D (struct openvpn_tcphdr *) BPTR(&newb= uf); + struct openvpn_tcphdr *tc =3D (struct openvpn_tcphdr *)BPTR(&newbu= f); if (tc->flags & OPENVPN_TCPH_SYN_MASK) { - mss_fixup_dowork(&newbuf, maxmss-20); + mss_fixup_dowork(&newbuf, maxmss - 20); } } } @@ -148,25 +144,22 @@ int accumulate; struct openvpn_tcphdr *tc; - if (BLEN(buf) < (int) sizeof(struct openvpn_tcphdr)) + if (BLEN(buf) < (int)sizeof(struct openvpn_tcphdr)) { return; } verify_align_4(buf); - tc =3D (struct openvpn_tcphdr *) BPTR(buf); + tc =3D (struct openvpn_tcphdr *)BPTR(buf); hlen =3D OPENVPN_TCPH_GET_DOFF(tc->doff_res); /* Invalid header length or header without options. */ - if (hlen <=3D (int) sizeof(struct openvpn_tcphdr) - || hlen > BLEN(buf)) + if (hlen <=3D (int)sizeof(struct openvpn_tcphdr) || hlen > BLEN(buf)) { return; } - for (olen =3D hlen - (int) sizeof(struct openvpn_tcphdr), - opt =3D (uint8_t *)(tc + 1); - olen > 1; + for (olen =3D hlen - (int)sizeof(struct openvpn_tcphdr), opt =3D (uint= 8_t *)(tc + 1); olen > 1; olen -=3D optlen, opt +=3D optlen) { if (*opt =3D=3D OPENVPN_TCPOPT_EOL) @@ -196,8 +189,8 @@ { dmsg(D_MSS, "MSS: %" PRIu16 " -> %" PRIu16, mssval, ma= xmss); accumulate =3D htons(mssval); - opt[2] =3D (uint8_t)((maxmss>>8)&0xff); - opt[3] =3D (uint8_t)(maxmss&0xff); + opt[2] =3D (uint8_t)((maxmss >> 8) & 0xff); + opt[3] =3D (uint8_t)(maxmss & 0xff); accumulate -=3D htons(maxmss); ADJUST_CHECKSUM(accumulate, tc->check); } @@ -227,8 +220,7 @@ } static size_t -get_ip_encap_overhead(const struct options *options, - const struct link_socket_info *lsi) +get_ip_encap_overhead(const struct options *options, const struct link_soc= ket_info *lsi) { /* Add the overhead of the encapsulating IP packets */ sa_family_t af; @@ -252,8 +244,7 @@ } static void -frame_calculate_fragment(struct frame *frame, struct key_type *kt, - const struct options *options, +frame_calculate_fragment(struct frame *frame, struct key_type *kt, const s= truct options *options, struct link_socket_info *lsi) { #if defined(ENABLE_FRAGMENT) @@ -283,8 +274,7 @@ } static void -frame_calculate_mssfix(struct frame *frame, struct key_type *kt, - const struct options *options, +frame_calculate_mssfix(struct frame *frame, struct key_type *kt, const str= uct options *options, struct link_socket_info *lsi) { if (options->ce.mssfix_fixed) @@ -326,13 +316,10 @@ /* This is the target value our payload needs to be smaller */ size_t target =3D options->ce.mssfix - overhead; frame->mss_fix =3D (uint16_t)(adjust_payload_max_cbc(kt, target) - pay= load_overhead); - - } void -frame_calculate_dynamic(struct frame *frame, struct key_type *kt, - const struct options *options, +frame_calculate_dynamic(struct frame *frame, struct key_type *kt, const st= ruct options *options, struct link_socket_info *lsi) { if (options->ce.fragment > 0) @@ -363,30 +350,29 @@ int encap_overhead =3D datagram_overhead(af, proto); /* check if mssfix and fragment need to be adjusted */ - if (pmtu < o->ce.mssfix - || (o->ce.mssfix_encap && pmtu < o->ce.mssfix + encap_overhead)) + if (pmtu < o->ce.mssfix || (o->ce.mssfix_encap && pmtu < o->ce.mssfix = + encap_overhead)) { const char *mtustr =3D o->ce.mssfix_encap ? " mtu" : ""; - msg(D_MTU_INFO, "Note adjusting 'mssfix %d%s' to 'mssfix %d mtu' " - "according to path MTU discovery", o->ce.mssfix, - mtustr, pmtu); + msg(D_MTU_INFO, + "Note adjusting 'mssfix %d%s' to 'mssfix %d mtu' " + "according to path MTU discovery", + o->ce.mssfix, mtustr, pmtu); o->ce.mssfix =3D pmtu; o->ce.mssfix_encap =3D true; frame_calculate_dynamic(&c->c2.frame, &c->c1.ks.key_type, o, lsi); } #if defined(ENABLE_FRAGMENT) - if (pmtu < o->ce.fragment - || (o->ce.fragment_encap && pmtu < o->ce.fragment + encap_overhead= )) + if (pmtu < o->ce.fragment || (o->ce.fragment_encap && pmtu < o->ce.fra= gment + encap_overhead)) { const char *mtustr =3D o->ce.fragment_encap ? " mtu" : ""; - msg(D_MTU_INFO, "Note adjusting 'fragment %d%s' to 'fragment %d mt= u' " - "according to path MTU discovery", o->ce.fragment, - mtustr, pmtu); + msg(D_MTU_INFO, + "Note adjusting 'fragment %d%s' to 'fragment %d mtu' " + "according to path MTU discovery", + o->ce.fragment, mtustr, pmtu); o->ce.fragment =3D pmtu; o->ce.fragment_encap =3D true; - frame_calculate_dynamic(&c->c2.frame_fragment, &c->c1.ks.key_type, - o, lsi); + frame_calculate_dynamic(&c->c2.frame_fragment, &c->c1.ks.key_type,= o, lsi); } #endif } diff --git a/src/openvpn/mss.h b/src/openvpn/mss.h index 1b1eafb..05f12a7 100644 --- a/src/openvpn/mss.h +++ b/src/openvpn/mss.h @@ -36,8 +36,7 @@ /** Set the --mssfix option. */ void frame_calculate_dynamic(struct frame *frame, struct key_type *kt, - const struct options *options, - struct link_socket_info *lsi); + const struct options *options, struct link_so= cket_info *lsi); /** * Checks and adjusts the fragment and mssfix value according to the diff --git a/src/openvpn/mstats.c b/src/openvpn/mstats.c index d9ecee3..bd6316c 100644 --- a/src/openvpn/mstats.c +++ b/src/openvpn/mstats.c @@ -83,7 +83,7 @@ } /* mmap the file */ - data =3D mmap(NULL, sizeof(struct mmap_stats), PROT_READ|PROT_WRITE, M= AP_SHARED, fd, 0); + data =3D mmap(NULL, sizeof(struct mmap_stats), PROT_READ | PROT_WRITE,= MAP_SHARED, fd, 0); if (data =3D=3D MAP_FAILED) { msg(M_ERR, "mstats_open: write error: %s", fn); diff --git a/src/openvpn/mstats.h b/src/openvpn/mstats.h index b9f33b6..c38b0f2 100644 --- a/src/openvpn/mstats.h +++ b/src/openvpn/mstats.h @@ -30,7 +30,8 @@ #include "basic.h" /* this struct is mapped to the file */ -struct mmap_stats { +struct mmap_stats +{ counter_type link_read_bytes; /* counter_type can be assumed to be a u= int64_t */ counter_type link_write_bytes; int n_clients; diff --git a/src/openvpn/mtcp.c b/src/openvpn/mtcp.c index 9781724..81310a2 100644 --- a/src/openvpn/mtcp.c +++ b/src/openvpn/mtcp.c @@ -66,8 +66,9 @@ if (he) { - struct multi_instance *oldmi =3D (struct multi_instance *) he-= >value; - msg(D_MULTI_LOW, "MULTI TCP: new incoming client address match= es existing client address -- new client takes precedence"); + struct multi_instance *oldmi =3D (struct multi_instance *)he->= value; + msg(D_MULTI_LOW, + "MULTI TCP: new incoming client address matches existing c= lient address -- new client takes precedence"); oldmi->did_real_hash =3D false; multi_close_instance(m, oldmi, false); he->key =3D &mi->real; @@ -108,12 +109,10 @@ ASSERT(mi->context.c2.link_sockets[0]->info.lsa); ASSERT(mi->context.c2.link_sockets[0]->mode =3D=3D LS_MODE_TCP_ACCEPT_= FROM); ASSERT(mi->context.c2.link_sockets[0]->info.lsa->actual.dest.addr.sa.s= a_family =3D=3D AF_INET - || mi->context.c2.link_sockets[0]->info.lsa->actual.dest.addr.s= a.sa_family =3D=3D AF_INET6 - ); + || mi->context.c2.link_sockets[0]->info.lsa->actual.dest.addr.s= a.sa_family =3D=3D AF_INET6); mi->real.proto =3D mi->context.c2.link_sockets[0]->info.proto; - if (!mroute_extract_openvpn_sockaddr(&mi->real, - &mi->context.c2.link_sockets[0]->= info.lsa->actual.dest, - true)) + if (!mroute_extract_openvpn_sockaddr( + &mi->real, &mi->context.c2.link_sockets[0]->info.lsa->actual.d= est, true)) { msg(D_MULTI_ERRORS, "MULTI TCP: TCP client address is undefined"); return false; @@ -149,7 +148,8 @@ } bool -multi_tcp_process_outgoing_link_ready(struct multi_context *m, struct mult= i_instance *mi, const unsigned int mpp_flags) +multi_tcp_process_outgoing_link_ready(struct multi_context *m, struct mult= i_instance *mi, + const unsigned int mpp_flags) { struct mbuf_item item; bool ret =3D true; diff --git a/src/openvpn/mtcp.h b/src/openvpn/mtcp.h index 5158427d..f4b806c 100644 --- a/src/openvpn/mtcp.h +++ b/src/openvpn/mtcp.h @@ -39,9 +39,11 @@ void multi_tcp_instance_specific_free(struct multi_instance *mi); -bool multi_tcp_process_outgoing_link(struct multi_context *m, bool defer, = const unsigned int mpp_flags); +bool multi_tcp_process_outgoing_link(struct multi_context *m, bool defer, + const unsigned int mpp_flags); -bool multi_tcp_process_outgoing_link_ready(struct multi_context *m, struct= multi_instance *mi, const unsigned int mpp_flags); +bool multi_tcp_process_outgoing_link_ready(struct multi_context *m, struct= multi_instance *mi, + const unsigned int mpp_flags); struct multi_instance *multi_create_instance_tcp(struct multi_context *m, = struct link_socket *sock); diff --git a/src/openvpn/mtu.c b/src/openvpn/mtu.c index 7245f95..c9d3389 100644 --- a/src/openvpn/mtu.c +++ b/src/openvpn/mtu.c @@ -38,8 +38,7 @@ /* allocate a buffer for socket or tun layer */ void -alloc_buf_sock_tun(struct buffer *buf, - const struct frame *frame) +alloc_buf_sock_tun(struct buffer *buf, const struct frame *frame) { /* allocate buffer for overlapped I/O */ *buf =3D alloc_buf(BUF_SIZE(frame)); @@ -59,8 +58,7 @@ } size_t -frame_calculate_protocol_header_size(const struct key_type *kt, - const struct options *options, +frame_calculate_protocol_header_size(const struct key_type *kt, const stru= ct options *options, bool occ) { /* Sum of all the overhead that reduces the usable packet size */ @@ -97,8 +95,7 @@ size_t -frame_calculate_payload_overhead(size_t extra_tun, - const struct options *options, +frame_calculate_payload_overhead(size_t extra_tun, const struct options *o= ptions, const struct key_type *kt) { size_t overhead =3D 0; @@ -138,8 +135,7 @@ } size_t -frame_calculate_payload_size(const struct frame *frame, - const struct options *options, +frame_calculate_payload_size(const struct frame *frame, const struct optio= ns *options, const struct key_type *kt) { size_t payload_size =3D options->ce.tun_mtu; @@ -174,7 +170,7 @@ * overhead */ /* overhead of BF-CBC: 64 bit block size, 64 bit IV size */ - overhead +=3D 64/8 + 64/8; + overhead +=3D 64 / 8 + 64 / 8; /* set ciphername to none, so its size does get added in the * fake_kt and the cipher is not tried to be resolved */ ciphername =3D "none"; @@ -191,9 +187,7 @@ } void -frame_print(const struct frame *frame, - int level, - const char *prefix) +frame_print(const struct frame *frame, int level, const char *prefix) { struct gc_arena gc =3D gc_new(); struct buffer out =3D alloc_buf_gc(256, &gc); @@ -229,19 +223,18 @@ { #if defined(IP_MTU_DISCOVER) case AF_INET: - if (setsockopt(sd, IPPROTO_IP, IP_MTU_DISCOVER, - (void *) &mtu_type, sizeof(mtu_type))) + if (setsockopt(sd, IPPROTO_IP, IP_MTU_DISCOVER, (void *)&m= tu_type, + sizeof(mtu_type))) { - msg(M_ERR, "Error setting IP_MTU_DISCOVER type=3D%d on= TCP/UDP socket", - mtu_type); + msg(M_ERR, "Error setting IP_MTU_DISCOVER type=3D%d on= TCP/UDP socket", mtu_type); } break; #endif #if defined(IPV6_MTU_DISCOVER) case AF_INET6: - if (setsockopt(sd, IPPROTO_IPV6, IPV6_MTU_DISCOVER, - (void *) &mtu_type, sizeof(mtu_type))) + if (setsockopt(sd, IPPROTO_IPV6, IPV6_MTU_DISCOVER, (void = *)&mtu_type, + sizeof(mtu_type))) { msg(M_ERR, "Error setting IPV6_MTU_DISCOVER type=3D%d = on TCP6/UDP6 socket", mtu_type); @@ -272,13 +265,11 @@ { return IP_PMTUDISC_DONT; } - msg(M_FATAL, - "invalid --mtu-disc type: '%s' -- valid types are 'yes', 'maybe', = or 'no'", - name); -#else /* if defined(IP_PMTUDISC_DONT) && defined(IP_PMTUDISC_WANT) && def= ined(IP_PMTUDISC_DO) */ + msg(M_FATAL, "invalid --mtu-disc type: '%s' -- valid types are 'yes', = 'maybe', or 'no'", name); +#else /* if defined(IP_PMTUDISC_DONT) && defined(IP_PMTUDISC_WANT) && defi= ned(IP_PMTUDISC_DO) */ msg(M_FATAL, MTUDISC_NOT_SUPPORTED_MSG); #endif - return -1; /* NOTREACHED */ + return -1; /* NOTREACHED */ } #if EXTENDED_SOCKET_ERROR_CAPABILITY @@ -300,7 +291,7 @@ struct sock_extended_err *e; struct sockaddr_storage addr; struct buffer out =3D alloc_buf_gc(256, gc); - char *cbuf =3D (char *) gc_malloc(256, false, gc); + char *cbuf =3D (char *)gc_malloc(256, false, gc); *mtu =3D 0; @@ -309,7 +300,7 @@ memset(&rcvbuf, -1, sizeof(rcvbuf)); iov.iov_base =3D &rcvbuf; iov.iov_len =3D sizeof(rcvbuf); - msg.msg_name =3D (uint8_t *) &addr; + msg.msg_name =3D (uint8_t *)&addr; msg.msg_namelen =3D sizeof(addr); msg.msg_iov =3D &iov; msg.msg_iovlen =3D 1; @@ -331,7 +322,7 @@ { if (cmsg->cmsg_type =3D=3D IP_RECVERR) { - e =3D (struct sock_extended_err *) CMSG_DATA(cmsg); + e =3D (struct sock_extended_err *)CMSG_DATA(cmsg); } else { @@ -342,7 +333,7 @@ { if (cmsg->cmsg_type =3D=3D IPV6_RECVERR) { - e =3D (struct sock_extended_err *) CMSG_DATA(cmsg); + e =3D (struct sock_extended_err *)CMSG_DATA(cmsg); } else { @@ -405,7 +396,7 @@ /* see "man 7 ip" (on Linux) * this works on IPv4 and IPv6(-dual-stack) sockets (v4-mapped) */ - if (setsockopt(sd, SOL_IP, IP_RECVERR, (void *) &on, sizeof(on)) !=3D = 0) + if (setsockopt(sd, SOL_IP, IP_RECVERR, (void *)&on, sizeof(on)) !=3D 0) { msg(M_WARN | M_ERRNO, "Note: enable extended error passing on TCP/UDP socket failed = (IP_RECVERR)"); @@ -414,7 +405,7 @@ * this only works on IPv6 sockets */ if (proto_af =3D=3D AF_INET6 - && setsockopt(sd, IPPROTO_IPV6, IPV6_RECVERR, (void *) &on, sizeof= (on)) !=3D 0) + && setsockopt(sd, IPPROTO_IPV6, IPV6_RECVERR, (void *)&on, sizeof(= on)) !=3D 0) { msg(M_WARN | M_ERRNO, "Note: enable extended error passing on TCP/UDP socket failed = (IPV6_RECVERR)"); diff --git a/src/openvpn/mtu.h b/src/openvpn/mtu.h index 64fd5b9..925ef0b 100644 --- a/src/openvpn/mtu.h +++ b/src/openvpn/mtu.h @@ -50,38 +50,38 @@ /* * Standard ethernet MTU */ -#define ETHERNET_MTU 1500 +#define ETHERNET_MTU 1500 /* * It is a fatal error if mtu is less than * this value for tun device. */ -#define TUN_MTU_MIN 100 +#define TUN_MTU_MIN 100 /* * Default MTU of network over which tunnel data will pass by TCP/UDP. */ -#define LINK_MTU_DEFAULT 1500 +#define LINK_MTU_DEFAULT 1500 /* * Default MTU of tunnel device. */ -#define TUN_MTU_DEFAULT 1500 +#define TUN_MTU_DEFAULT 1500 /* * MTU Defaults for TAP devices */ -#define TAP_MTU_EXTRA_DEFAULT 32 +#define TAP_MTU_EXTRA_DEFAULT 32 /* * Default MSSFIX value, used for reducing TCP MTU size */ -#define MSSFIX_DEFAULT 1492 +#define MSSFIX_DEFAULT 1492 /* * Default maximum size of control channel packets */ -#define TLS_MTU_DEFAULT 1250 +#define TLS_MTU_DEFAULT 1250 /* * Alignment of payload data such as IP packet or @@ -94,62 +94,64 @@ /** * Packet geometry parameters. */ -struct frame { - struct { +struct frame +{ + struct + { /* This struct holds all the information about the buffers that are * allocated to match this frame */ - int payload_size; /**< the maximum size that a payload that = our - * buffers can hold from either tun devi= ce - * or network link. - */ + int payload_size; /**< the maximum size that a payload that our + * buffers can hold from either tun device + * or network link. + */ - int headroom; /**< the headroom in the buffer, this is c= hoosen - * to allow all potential header to be a= dded - * before the packet */ + int headroom; /**< the headroom in the buffer, this is choosen + * to allow all potential header to be added + * before the packet */ - int tailroom; /**< the tailroom in the buffer. Chosen l= arge - * enough to also accompany any extrea h= eader - * or work space required by - * decryption/encryption or compression.= */ + int tailroom; /**< the tailroom in the buffer. Chosen large + * enough to also accompany any extrea header + * or work space required by + * decryption/encryption or compression. */ } buf; - uint16_t mss_fix; /**< The actual MSS value that should be - * written to the payload packets. This - * is the value for IPv4 TCP packets. For - * IPv6 packets another 20 bytes must - * be subtracted */ + uint16_t mss_fix; /**< The actual MSS value that should be + * written to the payload packets. This + * is the value for IPv4 TCP packets. For + * IPv6 packets another 20 bytes must + * be subtracted */ - int max_fragment_size; /**< The maximum size of a fragment. - * Fragmentation is done on the unencrypted - * payload after (potential) compression. = So - * this value specifies the maximum payload - * size that can be send in a single fragm= ent - */ + int max_fragment_size; /**< The maximum size of a fragment. + * Fragmentation is done on the unencrypted + * payload after (potential) compression. So + * this value specifies the maximum payload + * size that can be send in a single fragment + */ - int tun_mtu; /**< the (user) configured tun-mtu. This i= s used - * in configuring the tun interface or - * in calculations that use the desired = size - * of the payload in the buffer. - * - * This variable is also used in control - * frame context to set the desired maxi= mum - * control frame payload (although most = of - * code ignores it) - */ - int tun_max_mtu; /**< the maximum tun-mtu size the buffers = are - * are sized for. This is the upper boun= d that - * a server can push as MTU */ + int tun_mtu; /**< the (user) configured tun-mtu. This is used + * in configuring the tun interface or + * in calculations that use the desired size + * of the payload in the buffer. + * + * This variable is also used in control + * frame context to set the desired maximum + * control frame payload (although most of + * code ignores it) + */ + int tun_max_mtu; /**< the maximum tun-mtu size the buffers are + * are sized for. This is the upper bound that + * a server can push as MTU */ - int extra_tun; /**< Maximum number of bytes in excess of - * the tun/tap MTU that might be read - * from or written to the virtual - * tun/tap network interface. - * - * Only set with the option --tun-mtu-ex= tra - * which defaults to 0 for tun and 32 - * (\c TAP_MTU_EXTRA_DEFAULT) for tap. - * */ + int extra_tun; /**< Maximum number of bytes in excess of + * the tun/tap MTU that might be read + * from or written to the virtual + * tun/tap network interface. + * + * Only set with the option --tun-mtu-extra + * which defaults to 0 for tun and 32 + * (\c TAP_MTU_EXTRA_DEFAULT) for tap. + * */ }; /* Forward declarations, to prevent includes */ @@ -174,9 +176,7 @@ * Function prototypes. */ -void frame_print(const struct frame *frame, - int level, - const char *prefix); +void frame_print(const struct frame *frame, int level, const char *prefix); void set_mtu_discover_type(socket_descriptor_t sd, int mtu_type, sa_family= _t proto_af); @@ -194,10 +194,8 @@ * * * [IP][UDP][OPENVPN PROTOCOL HEADER][ **PAYLOAD incl compression heade= r** ] */ -size_t -frame_calculate_payload_size(const struct frame *frame, - const struct options *options, - const struct key_type *kt); +size_t frame_calculate_payload_size(const struct frame *frame, const struc= t options *options, + const struct key_type *kt); /** * Calculates the size of the payload overhead according to tun-mtu and @@ -215,10 +213,8 @@ * * * [IP][UDP][OPENVPN PROTOCOL HEADER][ **PAYLOAD incl compression heade= r** ] */ -size_t -frame_calculate_payload_overhead(size_t extra_tun, - const struct options *options, - const struct key_type *kt); +size_t frame_calculate_payload_overhead(size_t extra_tun, const struct opt= ions *options, + const struct key_type *kt); /** @@ -236,10 +232,8 @@ * @param occ Use the calculation for the OCC link-mtu * @return size of the overhead in bytes */ -size_t -frame_calculate_protocol_header_size(const struct key_type *kt, - const struct options *options, - bool occ); +size_t frame_calculate_protocol_header_size(const struct key_type *kt, + const struct options *options,= bool occ); /** * Calculate the link-mtu to advertise to our peer. The actual value is n= ot @@ -248,23 +242,18 @@ * value they expect. This assumes that the traditional cipher/auth direc= tives * in the config match the config of the peer. */ -size_t -calc_options_string_link_mtu(const struct options *options, - const struct frame *frame); +size_t calc_options_string_link_mtu(const struct options *options, const s= truct frame *frame); /** * Return the size of the packet ID size that is currently in use by ciphe= r and * options for the data channel. */ -unsigned int -calc_packet_id_size_dc(const struct options *options, - const struct key_type *kt); +unsigned int calc_packet_id_size_dc(const struct options *options, const s= truct key_type *kt); /* * allocate a buffer for socket or tun layer */ -void alloc_buf_sock_tun(struct buffer *buf, - const struct frame *frame); +void alloc_buf_sock_tun(struct buffer *buf, const struct frame *frame); /* * EXTENDED_SOCKET_ERROR_CAPABILITY functions -- print extra error info diff --git a/src/openvpn/mudp.c b/src/openvpn/mudp.c index 5755273..7259a4b 100644 --- a/src/openvpn/mudp.c +++ b/src/openvpn/mudp.c @@ -38,18 +38,15 @@ #endif static void -send_hmac_reset_packet(struct multi_context *m, - struct tls_pre_decrypt_state *state, - struct tls_auth_standalone *tas, - struct session_id *sid, +send_hmac_reset_packet(struct multi_context *m, struct tls_pre_decrypt_sta= te *state, + struct tls_auth_standalone *tas, struct session_id = *sid, bool request_resend_wkc) { reset_packet_id_send(&state->tls_wrap_tmp.opt.packet_id.send); state->tls_wrap_tmp.opt.packet_id.rec.initialized =3D true; uint8_t header =3D 0 | (P_CONTROL_HARD_RESET_SERVER_V2 << P_OPCODE_SHI= FT); struct buffer buf =3D tls_reset_standalone(&state->tls_wrap_tmp, tas, = sid, - &state->peer_session_id, head= er, - request_resend_wkc); + &state->peer_session_id, head= er, request_resend_wkc); struct context *c =3D &m->top; @@ -65,8 +62,7 @@ /* Returns true if this packet should create a new session */ static bool -do_pre_decrypt_check(struct multi_context *m, - struct tls_pre_decrypt_state *state, +do_pre_decrypt_check(struct multi_context *m, struct tls_pre_decrypt_state= *state, struct mroute_addr addr) { ASSERT(m->top.c2.tls_auth_standalone); @@ -108,8 +104,8 @@ if (early_neg_support) { /* Calculate the session ID HMAC for our reply and create rese= t packet */ - struct session_id sid =3D calculate_session_id_hmac(state->pee= r_session_id, - from, hmac, = handwindow, 0); + struct session_id sid =3D + calculate_session_id_hmac(state->peer_session_id, from, hm= ac, handwindow, 0); send_hmac_reset_packet(m, state, tas, &sid, true); return false; @@ -124,8 +120,10 @@ { struct gc_arena gc =3D gc_new(); const char *peer =3D print_link_socket_actual(&m->top.c2.f= rom, &gc); - msg(D_MULTI_DEBUG, "tls-crypt-v2 force-cookie is enabled, " - "ignoring connection attempt from old client (%s)", pe= er); + msg(D_MULTI_DEBUG, + "tls-crypt-v2 force-cookie is enabled, " + "ignoring connection attempt from old client (%s)", + peer); gc_free(&gc); return false; } @@ -138,14 +136,13 @@ else if (verdict =3D=3D VERDICT_VALID_RESET_V2) { /* Calculate the session ID HMAC for our reply and create reset pa= cket */ - struct session_id sid =3D calculate_session_id_hmac(state->peer_se= ssion_id, - from, hmac, hand= window, 0); + struct session_id sid =3D + calculate_session_id_hmac(state->peer_session_id, from, hmac, = handwindow, 0); send_hmac_reset_packet(m, state, tas, &sid, false); /* We have a reply do not create a new session */ return false; - } else if (verdict =3D=3D VERDICT_VALID_CONTROL_V1 || verdict =3D=3D VER= DICT_VALID_ACK_V1 || verdict =3D=3D VERDICT_VALID_WKC_V1) @@ -157,7 +154,7 @@ bool ret =3D check_session_id_hmac(state, from, hmac, handwindow); const char *peer =3D print_link_socket_actual(&m->top.c2.from, &gc= ); - uint8_t pkt_firstbyte =3D *BPTR( &m->top.c2.buf); + uint8_t pkt_firstbyte =3D *BPTR(&m->top.c2.buf); int op =3D pkt_firstbyte >> P_OPCODE_SHIFT; if (!ret) @@ -167,8 +164,10 @@ } else { - msg(D_MULTI_DEBUG, "Valid packet (%s) with HMAC challenge from= peer (%s), " - "accepting new connection.", packet_opcode_name(op), peer); + msg(D_MULTI_DEBUG, + "Valid packet (%s) with HMAC challenge from peer (%s), " + "accepting new connection.", + packet_opcode_name(op), peer); } gc_free(&gc); @@ -186,18 +185,16 @@ */ struct multi_instance * -multi_get_create_instance_udp(struct multi_context *m, bool *floated, - struct link_socket *sock) +multi_get_create_instance_udp(struct multi_context *m, bool *floated, stru= ct link_socket *sock) { struct gc_arena gc =3D gc_new(); - struct mroute_addr real =3D {0}; + struct mroute_addr real =3D { 0 }; struct multi_instance *mi =3D NULL; struct hash *hash =3D m->hash; real.proto =3D sock->info.proto; m->hmac_reply_ls =3D sock; - if (mroute_extract_openvpn_sockaddr(&real, &m->top.c2.from.dest, true) - && m->top.c2.buf.len > 0) + if (mroute_extract_openvpn_sockaddr(&real, &m->top.c2.from.dest, true)= && m->top.c2.buf.len > 0) { struct hash_element *he; const uint32_t hv =3D hash_value(hash, &real); @@ -217,14 +214,16 @@ { /* Floating on TCP will never be possible, so ensure we on= ly process * UDP clients */ - if (m->instances[peer_id]->context.c2.link_sockets[0]->inf= o.proto =3D=3D sock->info.proto) + if (m->instances[peer_id]->context.c2.link_sockets[0]->inf= o.proto + =3D=3D sock->info.proto) { mi =3D m->instances[peer_id]; *floated =3D !link_socket_actual_match(&mi->context.c2= .from, &m->top.c2.from); if (*floated) { - /* reset prefix, since here we are not sure peer i= s the one it claims to be */ + /* reset prefix, since here we are not sure peer i= s the one it claims to be + */ ungenerate_prefix(mi); msg(D_MULTI_MEDIUM, "Float requested for peer %" P= RIu32 " to %s", peer_id, mroute_addr_print(&real, &gc)); @@ -237,19 +236,20 @@ he =3D hash_lookup_fast(hash, bucket, &real, hv); if (he) { - mi =3D (struct multi_instance *) he->value; + mi =3D (struct multi_instance *)he->value; } } /* we have no existing multi instance for this connection */ if (!mi) { - struct tls_pre_decrypt_state state =3D {0}; + struct tls_pre_decrypt_state state =3D { 0 }; if (m->deferred_shutdown_signal.signal_received) { msg(D_MULTI_ERRORS, "MULTI: Connection attempt from %s ignored while serve= r is " - "shutting down", mroute_addr_print(&real, &gc)); + "shutting down", + mroute_addr_print(&real, &gc)); } else if (do_pre_decrypt_check(m, &state, real)) { @@ -277,7 +277,8 @@ && session_id_defined((&state.peer_session_id)= )) { mi->context.c2.tls_multi->n_sessions++; - struct tls_session *session =3D &mi->context.c= 2.tls_multi->session[TM_INITIAL]; + struct tls_session *session =3D + &mi->context.c2.tls_multi->session[TM_INIT= IAL]; session_skip_to_pre_start(session, &state, &m-= >top.c2.from); } } @@ -297,9 +298,7 @@ { const char *status =3D mi ? "[ok]" : "[failed]"; =20 - dmsg(D_MULTI_DEBUG, "GET INST BY REAL: %s %s", - mroute_addr_print(&real, &gc), - status); + dmsg(D_MULTI_DEBUG, "GET INST BY REAL: %s %s", mroute_addr_pri= nt(&real, &gc), status); } #endif } @@ -339,8 +338,8 @@ { const unsigned int status =3D m->multi_io->udp_flags; const unsigned int mpp_flags =3D m->top.c2.fast_io - ? (MPP_CONDITIONAL_PRE_SELECT | MPP_CLO= SE_ON_SIGNAL) - : (MPP_PRE_SELECT | MPP_CLOSE_ON_SIGNAL= ); + ? (MPP_CONDITIONAL_PRE_SELECT | MPP= _CLOSE_ON_SIGNAL) + : (MPP_PRE_SELECT | MPP_CLOSE_ON_SI= GNAL); #ifdef MULTI_DEBUG_EVENT_LOOP char buf[16]; @@ -369,7 +368,7 @@ #endif /* ifdef MULTI_DEBUG_EVENT_LOOP */ #ifdef ENABLE_MANAGEMENT - if (status & (MANAGEMENT_READ|MANAGEMENT_WRITE)) + if (status & (MANAGEMENT_READ | MANAGEMENT_WRITE)) { ASSERT(management); management_io(management); diff --git a/src/openvpn/multi.c b/src/openvpn/multi.c index a306b12..8b352e9 100644 --- a/src/openvpn/multi.c +++ b/src/openvpn/multi.c @@ -91,9 +91,7 @@ } static bool -learn_address_script(const struct multi_context *m, - const struct multi_instance *mi, - const char *op, +learn_address_script(const struct multi_context *m, const struct multi_ins= tance *mi, const char *op, const struct mroute_addr *addr) { struct gc_arena gc =3D gc_new(); @@ -124,14 +122,13 @@ if (plugin_defined(plugins, OPENVPN_PLUGIN_LEARN_ADDRESS)) { struct argv argv =3D argv_new(); - argv_printf(&argv, "%s %s", - op, - mroute_addr_print(addr, &gc)); + argv_printf(&argv, "%s %s", op, mroute_addr_print(addr, &gc)); if (mi) { argv_printf_cat(&argv, "%s", tls_common_name(mi->context.c2.tl= s_multi, false)); } - if (plugin_call(plugins, OPENVPN_PLUGIN_LEARN_ADDRESS, &argv, NULL= , es) !=3D OPENVPN_PLUGIN_FUNC_SUCCESS) + if (plugin_call(plugins, OPENVPN_PLUGIN_LEARN_ADDRESS, &argv, NULL= , es) + !=3D OPENVPN_PLUGIN_FUNC_SUCCESS) { msg(M_WARN, "WARNING: learn-address plugin call failed"); ret =3D false; @@ -164,8 +161,7 @@ multi_ifconfig_pool_persist(struct multi_context *m, bool force) { /* write pool data to file */ - if (m->ifconfig_pool - && m->top.c1.ifconfig_pool_persist + if (m->ifconfig_pool && m->top.c1.ifconfig_pool_persist && (force || ifconfig_pool_write_trigger(m->top.c1.ifconfig_pool_p= ersist))) { ifconfig_pool_write(m->top.c1.ifconfig_pool_persist, m->ifconfig_p= ool); @@ -173,9 +169,7 @@ } static void -multi_reap_range(const struct multi_context *m, - int start_bucket, - int end_bucket) +multi_reap_range(const struct multi_context *m, int start_bucket, int end_= bucket) { struct gc_arena gc =3D gc_new(); struct hash_iterator hi; @@ -191,11 +185,10 @@ hash_iterator_init_range(m->vhash, &hi, start_bucket, end_bucket); while ((he =3D hash_iterator_next(&hi)) !=3D NULL) { - struct multi_route *r =3D (struct multi_route *) he->value; + struct multi_route *r =3D (struct multi_route *)he->value; if (!multi_route_defined(m, r)) { - dmsg(D_MULTI_DEBUG, "MULTI: REAP DEL %s", - mroute_addr_print(&r->addr, &gc)); + dmsg(D_MULTI_DEBUG, "MULTI: REAP DEL %s", mroute_addr_print(&r= ->addr, &gc)); learn_address_script(m, NULL, "delete", &r->addr); multi_route_del(r); hash_iterator_delete_element(&hi); @@ -256,7 +249,7 @@ cid_hash_function(const void *key, uint32_t iv) { const unsigned long *k =3D (const unsigned long *)key; - return (uint32_t) *k; + return (uint32_t)*k; } static bool @@ -295,8 +288,7 @@ struct multi_context *m =3D t->multi; int dev =3D DEV_TYPE_UNDEF; - msg(D_MULTI_LOW, "MULTI: multi_init called, r=3D%d v=3D%d", - t->options.real_hash_size, + msg(D_MULTI_LOW, "MULTI: multi_init called, r=3D%d v=3D%d", t->options= .real_hash_size, t->options.virtual_hash_size); /* @@ -315,18 +307,14 @@ * to determine which client sent an incoming packet * which is seen on the TCP/UDP socket. */ - m->hash =3D hash_init(t->options.real_hash_size, - get_random(), - mroute_addr_hash_function, + m->hash =3D hash_init(t->options.real_hash_size, get_random(), mroute_= addr_hash_function, mroute_addr_compare_function); /* * Virtual address hash table. Used to determine * which client to route a packet to. */ - m->vhash =3D hash_init(t->options.virtual_hash_size, - get_random(), - mroute_addr_hash_function, + m->vhash =3D hash_init(t->options.virtual_hash_size, get_random(), mro= ute_addr_hash_function, mroute_addr_compare_function); /* @@ -334,16 +322,10 @@ * bucket size of one so that it can be used * for fast iteration through the list. */ - m->iter =3D hash_init(1, - get_random(), - mroute_addr_hash_function, - mroute_addr_compare_function); + m->iter =3D hash_init(1, get_random(), mroute_addr_hash_function, mrou= te_addr_compare_function); #ifdef ENABLE_MANAGEMENT - m->cid_hash =3D hash_init(t->options.real_hash_size, - 0, - cid_hash_function, - cid_compare_function); + m->cid_hash =3D hash_init(t->options.real_hash_size, 0, cid_hash_funct= ion, cid_compare_function); #endif #ifdef ENABLE_ASYNC_PUSH @@ -351,10 +333,8 @@ * Mapping between inotify watch descriptors and * multi_instances. */ - m->inotify_watchers =3D hash_init(t->options.real_hash_size, - get_random(), - int_hash_function, - int_compare_function); + m->inotify_watchers =3D + hash_init(t->options.real_hash_size, get_random(), int_hash_functi= on, int_compare_function); #endif /* @@ -367,10 +347,9 @@ * Limit frequency of incoming connections to control * DoS. */ - m->new_connection_limiter =3D frequency_limit_init(t->options.cf_max, - t->options.cf_per); - m->initial_rate_limiter =3D initial_rate_limit_init(t->options.cf_init= ial_max, - t->options.cf_initia= l_per); + m->new_connection_limiter =3D frequency_limit_init(t->options.cf_max, = t->options.cf_per); + m->initial_rate_limiter =3D + initial_rate_limit_init(t->options.cf_initial_max, t->options.cf_i= nitial_per); /* * Allocate broadcast/multicast buffer list @@ -387,8 +366,7 @@ * differently based on whether a tun or tap style * tunnel. */ - if (t->options.ifconfig_pool_defined - || t->options.ifconfig_ipv6_pool_defined) + if (t->options.ifconfig_pool_defined || t->options.ifconfig_ipv6_pool_= defined) { int pool_type =3D IFCONFIG_POOL_INDIV; @@ -397,14 +375,11 @@ pool_type =3D IFCONFIG_POOL_30NET; } - m->ifconfig_pool =3D ifconfig_pool_init(t->options.ifconfig_pool_d= efined, - pool_type, - t->options.ifconfig_pool_sta= rt, - t->options.ifconfig_pool_end, - t->options.duplicate_cn, - t->options.ifconfig_ipv6_poo= l_defined, - t->options.ifconfig_ipv6_poo= l_base, - t->options.ifconfig_ipv6_poo= l_netbits ); + m->ifconfig_pool =3D ifconfig_pool_init( + t->options.ifconfig_pool_defined, pool_type, t->options.ifconf= ig_pool_start, + t->options.ifconfig_pool_end, t->options.duplicate_cn, + t->options.ifconfig_ipv6_pool_defined, t->options.ifconfig_ipv= 6_pool_base, + t->options.ifconfig_ipv6_pool_netbits); /* reload pool data from file */ if (t->c1.ifconfig_pool_persist) @@ -454,7 +429,8 @@ /* initialize stale routes check timer */ if (t->options.stale_routes_check_interval > 0) { - msg(M_INFO, "Initializing stale route check timer to run every %i = seconds and to removing routes with activity timeout older than %i seconds", + msg(M_INFO, + "Initializing stale route check timer to run every %i seconds = and to removing routes with activity timeout older than %i seconds", t->options.stale_routes_check_interval, t->options.stale_route= s_ageing_time); event_timeout_init(&m->stale_routes_check_et, t->options.stale_rou= tes_check_interval, 0); } @@ -475,8 +451,7 @@ buf_printf(&out, "%s/", cn); } buf_printf(&out, "%s", mroute_addr_print(&mi->real, gc)); - if (mi->context.c2.tls_multi - && check_debug_level(D_DCO_DEBUG) + if (mi->context.c2.tls_multi && check_debug_level(D_DCO_DEBUG) && dco_enabled(&mi->context.options)) { buf_printf(&out, " peer-id=3D%d", mi->context.c2.tls_multi->pe= er_id); @@ -523,8 +498,7 @@ * CIDR netlengths. */ static void -multi_del_iroutes(struct multi_context *m, - struct multi_instance *mi) +multi_del_iroutes(struct multi_context *m, struct multi_instance *mi) { const struct iroute *ir; const struct iroute_ipv6 *ir6; @@ -580,7 +554,9 @@ if (plugin_defined(mi->context.plugins, OPENVPN_PLUGIN_CLIENT_DISCONNE= CT)) { - if (plugin_call(mi->context.plugins, OPENVPN_PLUGIN_CLIENT_DISCONN= ECT, NULL, NULL, mi->context.c2.es) !=3D OPENVPN_PLUGIN_FUNC_SUCCESS) + if (plugin_call(mi->context.plugins, OPENVPN_PLUGIN_CLIENT_DISCONN= ECT, NULL, NULL, + mi->context.c2.es) + !=3D OPENVPN_PLUGIN_FUNC_SUCCESS) { msg(M_WARN, "WARNING: client-disconnect plugin call failed"); } @@ -603,9 +579,7 @@ } void -multi_close_instance(struct multi_context *m, - struct multi_instance *mi, - bool shutdown) +multi_close_instance(struct multi_context *m, struct multi_instance *mi, b= ool shutdown) { perf_push(PERF_MULTI_CLOSE_INSTANCE); @@ -650,7 +624,7 @@ #ifdef ENABLE_ASYNC_PUSH if (mi->inotify_watch !=3D -1) { - hash_remove(m->inotify_watchers, (void *) (unsigned long)mi->i= notify_watch); + hash_remove(m->inotify_watchers, (void *)(unsigned long)mi->in= otify_watch); mi->inotify_watch =3D -1; } #endif @@ -660,7 +634,7 @@ m->instances[mi->context.c2.tls_multi->peer_id] =3D NULL; } - schedule_remove_entry(m->schedule, (struct schedule_entry *) mi); + schedule_remove_entry(m->schedule, (struct schedule_entry *)mi); ifconfig_pool_release(m->ifconfig_pool, mi->vaddr_handle, false); @@ -717,7 +691,7 @@ hash_iterator_init(m->iter, &hi); while ((he =3D hash_iterator_next(&hi))) { - struct multi_instance *mi =3D (struct multi_instance *) he->va= lue; + struct multi_instance *mi =3D (struct multi_instance *)he->val= ue; mi->did_iter =3D false; multi_close_instance(m, mi, true); } @@ -789,7 +763,9 @@ if (hash_n_elements(m->hash) >=3D m->max_clients) { - msg(D_MULTI_ERRORS, "MULTI: new incoming connection would exceed m= aximum number of clients (%d)", m->max_clients); + msg(D_MULTI_ERRORS, + "MULTI: new incoming connection would exceed maximum number of= clients (%d)", + m->max_clients); goto err; } @@ -879,7 +855,7 @@ while ((he =3D hash_iterator_next(&hi))) { struct gc_arena gc =3D gc_new(); - const struct multi_instance *mi =3D (struct multi_instance= *) he->value; + const struct multi_instance *mi =3D (struct multi_instance= *)he->value; if (!mi->halt) { @@ -900,21 +876,19 @@ while ((he =3D hash_iterator_next(&hi))) { struct gc_arena gc =3D gc_new(); - const struct multi_route *route =3D (struct multi_route *)= he->value; + const struct multi_route *route =3D (struct multi_route *)= he->value; if (multi_route_defined(m, route)) { const struct multi_instance *mi =3D route->instance; const struct mroute_addr *ma =3D &route->addr; - char flags[2] =3D {0, 0}; + char flags[2] =3D { 0, 0 }; if (route->flags & MULTI_ROUTE_CACHE) { flags[0] =3D 'C'; } - status_printf(so, "%s%s,%s,%s,%s", - mroute_addr_print(ma, &gc), - flags, + status_printf(so, "%s%s,%s,%s,%s", mroute_addr_print(m= a, &gc), flags, tls_common_name(mi->context.c2.tls_multi= , false), mroute_addr_print(&mi->real, &gc), time_string(route->last_reference, 0, fa= lse, &gc)); @@ -926,8 +900,7 @@ status_printf(so, "GLOBAL STATS"); if (m->mbuf) { - status_printf(so, "Max bcast/mcast queue length,%d", - mbuf_maximum_queued(m->mbuf)); + status_printf(so, "Max bcast/mcast queue length,%d", mbuf_= maximum_queued(m->mbuf)); } status_printf(so, "END"); @@ -940,69 +913,77 @@ * Status file version 2 and 3 */ status_printf(so, "TITLE%c%s", sep, title_string); - status_printf(so, "TIME%c%s%c%u", sep, time_string(now, 0, fal= se, &gc_top), sep, (unsigned int)now); - status_printf(so, "HEADER%cCLIENT_LIST%cCommon Name%cReal Addr= ess%cVirtual Address%cVirtual IPv6 Address%cBytes Received%cBytes Sent%cCon= nected Since%cConnected Since (time_t)%cUsername%cClient ID%cPeer ID%cData = Channel Cipher", - sep, sep, sep, sep, sep, sep, sep, sep, sep, sep= , sep, sep, sep); + status_printf(so, "TIME%c%s%c%u", sep, time_string(now, 0, fal= se, &gc_top), sep, + (unsigned int)now); + status_printf( + so, + "HEADER%cCLIENT_LIST%cCommon Name%cReal Address%cVirtual A= ddress%cVirtual IPv6 Address%cBytes Received%cBytes Sent%cConnected Since%c= Connected Since (time_t)%cUsername%cClient ID%cPeer ID%cData Channel Cipher= ", + sep, sep, sep, sep, sep, sep, sep, sep, sep, sep, sep, sep= , sep); hash_iterator_init(m->hash, &hi); while ((he =3D hash_iterator_next(&hi))) { struct gc_arena gc =3D gc_new(); - const struct multi_instance *mi =3D (struct multi_instance= *) he->value; + const struct multi_instance *mi =3D (struct multi_instance= *)he->value; if (!mi->halt) { - status_printf(so, "CLIENT_LIST%c%s%c%s%c%s%c%s%c" coun= ter_format "%c" counter_format "%c%s%c%u%c%s%c" + status_printf( + so, + "CLIENT_LIST%c%s%c%s%c%s%c%s%c" counter_format "%c= " counter_format + "%c%s%c%u%c%s%c" #ifdef ENABLE_MANAGEMENT - "%lu" + "%lu" #else - "" + "" #endif - "%c%" PRIu32 "%c%s", - sep, tls_common_name(mi->context.c2.tls_= multi, false), - sep, mroute_addr_print(&mi->real, &gc), - sep, print_in_addr_t(mi->reporting_addr,= IA_EMPTY_IF_UNDEF, &gc), - sep, print_in6_addr(mi->reporting_addr_i= pv6, IA_EMPTY_IF_UNDEF, &gc), - sep, mi->context.c2.link_read_bytes + mi= ->context.c2.dco_read_bytes, - sep, mi->context.c2.link_write_bytes + m= i->context.c2.dco_write_bytes, - sep, time_string(mi->created, 0, false, = &gc), - sep, (unsigned int)mi->created, - sep, tls_username(mi->context.c2.tls_mul= ti, false), + "%c%" PRIu32 "%c%s", + sep, tls_common_name(mi->context.c2.tls_multi, fal= se), sep, + mroute_addr_print(&mi->real, &gc), sep, + print_in_addr_t(mi->reporting_addr, IA_EMPTY_IF_UN= DEF, &gc), sep, + print_in6_addr(mi->reporting_addr_ipv6, IA_EMPTY_I= F_UNDEF, &gc), sep, + mi->context.c2.link_read_bytes + mi->context.c2.dc= o_read_bytes, sep, + mi->context.c2.link_write_bytes + mi->context.c2.d= co_write_bytes, sep, + time_string(mi->created, 0, false, &gc), sep, (uns= igned int)mi->created, + sep, tls_username(mi->context.c2.tls_multi, false), #ifdef ENABLE_MANAGEMENT - sep, mi->context.c2.mda_context.cid, + sep, mi->context.c2.mda_context.cid, #else - sep, + sep, #endif - sep, mi->context.c2.tls_multi ? mi->cont= ext.c2.tls_multi->peer_id : UINT32_MAX, - sep, translate_cipher_name_to_openvpn(mi= ->context.options.ciphername)); + sep, + mi->context.c2.tls_multi ? mi->context.c2.tls_mult= i->peer_id : UINT32_MAX, + sep, translate_cipher_name_to_openvpn(mi->context.= options.ciphername)); } gc_free(&gc); } hash_iterator_free(&hi); - status_printf(so, "HEADER%cROUTING_TABLE%cVirtual Address%cCom= mon Name%cReal Address%cLast Ref%cLast Ref (time_t)", - sep, sep, sep, sep, sep, sep); + status_printf( + so, + "HEADER%cROUTING_TABLE%cVirtual Address%cCommon Name%cReal= Address%cLast Ref%cLast Ref (time_t)", + sep, sep, sep, sep, sep, sep); hash_iterator_init(m->vhash, &hi); while ((he =3D hash_iterator_next(&hi))) { struct gc_arena gc =3D gc_new(); - const struct multi_route *route =3D (struct multi_route *)= he->value; + const struct multi_route *route =3D (struct multi_route *)= he->value; if (multi_route_defined(m, route)) { const struct multi_instance *mi =3D route->instance; const struct mroute_addr *ma =3D &route->addr; - char flags[2] =3D {0, 0}; + char flags[2] =3D { 0, 0 }; if (route->flags & MULTI_ROUTE_CACHE) { flags[0] =3D 'C'; } - status_printf(so, "ROUTING_TABLE%c%s%s%c%s%c%s%c%s%c%u= ", - sep, mroute_addr_print(ma, &gc), flags, - sep, tls_common_name(mi->context.c2.tls_= multi, false), - sep, mroute_addr_print(&mi->real, &gc), - sep, time_string(route->last_reference, = 0, false, &gc), - sep, (unsigned int)route->last_reference= ); + status_printf(so, "ROUTING_TABLE%c%s%s%c%s%c%s%c%s%c%u= ", sep, + mroute_addr_print(ma, &gc), flags, sep, + tls_common_name(mi->context.c2.tls_multi= , false), sep, + mroute_addr_print(&mi->real, &gc), sep, + time_string(route->last_reference, 0, fa= lse, &gc), sep, + (unsigned int)route->last_reference); } gc_free(&gc); } @@ -1010,11 +991,12 @@ if (m->mbuf) { - status_printf(so, "GLOBAL_STATS%cMax bcast/mcast queue len= gth%c%d", - sep, sep, mbuf_maximum_queued(m->mbuf)); + status_printf(so, "GLOBAL_STATS%cMax bcast/mcast queue len= gth%c%d", sep, sep, + mbuf_maximum_queued(m->mbuf)); } - status_printf(so, "GLOBAL_STATS%cdco_enabled%c%d", sep, sep, d= co_enabled(&m->top.options)); + status_printf(so, "GLOBAL_STATS%cdco_enabled%c%d", sep, sep, + dco_enabled(&m->top.options)); status_printf(so, "END"); } else @@ -1024,19 +1006,22 @@ #ifdef PACKET_TRUNCATION_CHECK { - status_printf(so, "HEADER,ERRORS,Common Name,TUN Read Trunc,TU= N Write Trunc,Pre-encrypt Trunc,Post-decrypt Trunc"); + status_printf( + so, + "HEADER,ERRORS,Common Name,TUN Read Trunc,TUN Write Trunc,= Pre-encrypt Trunc,Post-decrypt Trunc"); hash_iterator_init(m->hash, &hi); while ((he =3D hash_iterator_next(&hi))) { struct gc_arena gc =3D gc_new(); - const struct multi_instance *mi =3D (struct multi_instance= *) he->value; + const struct multi_instance *mi =3D (struct multi_instance= *)he->value; if (!mi->halt) { - status_printf(so, "ERRORS,%s," counter_format "," coun= ter_format "," counter_format "," counter_format, + status_printf(so, + "ERRORS,%s," counter_format "," counter_= format "," counter_format + "," counter_format, tls_common_name(mi->context.c2.tls_multi= , false), - m->top.c2.n_trunc_tun_read, - mi->context.c2.n_trunc_tun_write, + m->top.c2.n_trunc_tun_read, mi->context.= c2.n_trunc_tun_write, mi->context.c2.n_trunc_pre_encrypt, mi->context.c2.n_trunc_post_decrypt); } @@ -1067,9 +1052,7 @@ * or NULL if none. */ static struct multi_instance * -multi_learn_addr(struct multi_context *m, - struct multi_instance *mi, - const struct mroute_addr *addr, +multi_learn_addr(struct multi_context *m, struct multi_instance *mi, const= struct mroute_addr *addr, const unsigned int flags) { struct hash_element *he; @@ -1083,7 +1066,7 @@ he =3D hash_lookup_fast(m->vhash, bucket, addr, hv); if (he) { - oldroute =3D (struct multi_route *) he->value; + oldroute =3D (struct multi_route *)he->value; } if (oldroute && multi_route_defined(m, oldroute)) { @@ -1141,10 +1124,8 @@ } } - msg(D_MULTI_LOW, "MULTI: Learn%s: %s -> %s", - learn_succeeded ? "" : " FAILED", - mroute_addr_print(&newroute->addr, &gc), - multi_instance_string(mi, false, &gc)); + msg(D_MULTI_LOW, "MULTI: Learn%s: %s -> %s", learn_succeeded ? "" = : " FAILED", + mroute_addr_print(&newroute->addr, &gc), multi_instance_string= (mi, false, &gc)); if (!learn_succeeded) { @@ -1160,8 +1141,7 @@ * Get client instance based on virtual address. */ static struct multi_instance * -multi_get_instance_by_virtual_addr(struct multi_context *m, - const struct mroute_addr *addr, +multi_get_instance_by_virtual_addr(struct multi_context *m, const struct m= route_addr *addr, bool cidr_routing) { struct multi_route *route; @@ -1173,7 +1153,7 @@ return NULL; } - route =3D (struct multi_route *) hash_lookup(m->vhash, addr); + route =3D (struct multi_route *)hash_lookup(m->vhash, addr); /* does host route (possible cached) exist? */ if (route && multi_route_defined(m, route)) @@ -1197,13 +1177,13 @@ mroute_addr_mask_host_bits(&tryaddr); /* look up a possible route with netbits netmask */ - route =3D (struct multi_route *) hash_lookup(m->vhash, &tryadd= r); + route =3D (struct multi_route *)hash_lookup(m->vhash, &tryaddr= ); if (route && multi_route_defined(m, route)) { /* found an applicable route, cache host route */ struct multi_instance *mi =3D route->instance; - multi_learn_addr(m, mi, addr, MULTI_ROUTE_CACHE|MULTI_ROUT= E_AGEABLE); + multi_learn_addr(m, mi, addr, MULTI_ROUTE_CACHE | MULTI_RO= UTE_AGEABLE); ret =3D mi; break; } @@ -1217,15 +1197,12 @@ const char *addr_text =3D mroute_addr_print(addr, &gc); if (ret) { - dmsg(D_MULTI_DEBUG, "GET INST BY VIRT: %s -> %s via %s", - addr_text, - multi_instance_string(ret, false, &gc), - mroute_addr_print(&route->addr, &gc)); + dmsg(D_MULTI_DEBUG, "GET INST BY VIRT: %s -> %s via %s", addr_= text, + multi_instance_string(ret, false, &gc), mroute_addr_print= (&route->addr, &gc)); } else { - dmsg(D_MULTI_DEBUG, "GET INST BY VIRT: %s [failed]", - addr_text); + dmsg(D_MULTI_DEBUG, "GET INST BY VIRT: %s [failed]", addr_text= ); } gc_free(&gc); } @@ -1239,14 +1216,12 @@ * Helper function to multi_learn_addr(). */ static struct multi_instance * -multi_learn_in_addr_t(struct multi_context *m, - struct multi_instance *mi, - in_addr_t a, - int netbits, /* -1 if host route, otherwise # of ne= twork bits in address */ +multi_learn_in_addr_t(struct multi_context *m, struct multi_instance *mi, = in_addr_t a, + int netbits, /* -1 if host route, otherwise # of net= work bits in address */ bool primary) { struct openvpn_sockaddr remote_si; - struct mroute_addr addr =3D {0}; + struct mroute_addr addr =3D { 0 }; CLEAR(remote_si); remote_si.addr.in4.sin_family =3D AF_INET; @@ -1257,7 +1232,7 @@ if (netbits >=3D 0) { addr.type |=3D MR_WITH_NETBITS; - addr.netbits =3D (uint8_t) netbits; + addr.netbits =3D (uint8_t)netbits; } struct multi_instance *owner =3D multi_learn_addr(m, mi, &addr, 0); @@ -1272,7 +1247,7 @@ /* "primary" is the VPN ifconfig address of the peer and already * known to DCO, so only install "extra" iroutes (primary =3D fals= e) */ - ASSERT(netbits >=3D 0); /* DCO requires populated netbit= s */ + ASSERT(netbits >=3D 0); /* DCO requires populated netbits */ dco_install_iroute(m, mi, &addr); } @@ -1280,13 +1255,11 @@ } static struct multi_instance * -multi_learn_in6_addr(struct multi_context *m, - struct multi_instance *mi, - struct in6_addr a6, - int netbits, /* -1 if host route, otherwise # of ne= twork bits in address */ +multi_learn_in6_addr(struct multi_context *m, struct multi_instance *mi, s= truct in6_addr a6, + int netbits, /* -1 if host route, otherwise # of netw= ork bits in address */ bool primary) { - struct mroute_addr addr =3D {0}; + struct mroute_addr addr =3D { 0 }; addr.len =3D 16; addr.type =3D MR_ADDR_IPV6; @@ -1296,8 +1269,8 @@ if (netbits >=3D 0) { addr.type |=3D MR_WITH_NETBITS; - addr.netbits =3D (uint8_t) netbits; - mroute_addr_mask_host_bits( &addr ); + addr.netbits =3D (uint8_t)netbits; + mroute_addr_mask_host_bits(&addr); } struct multi_instance *owner =3D multi_learn_addr(m, mi, &addr, 0); @@ -1312,7 +1285,7 @@ /* "primary" is the VPN ifconfig address of the peer and already * known to DCO, so only install "extra" iroutes (primary =3D fals= e) */ - ASSERT(netbits >=3D 0); /* DCO requires populated netbit= s */ + ASSERT(netbits >=3D 0); /* DCO requires populated netbits */ dco_install_iroute(m, mi, &addr); } =20 @@ -1324,8 +1297,7 @@ * to internal routing table. */ static void -multi_add_iroutes(struct multi_context *m, - struct multi_instance *mi) +multi_add_iroutes(struct multi_context *m, struct multi_instance *mi) { struct gc_arena gc =3D gc_new(); const struct iroute *ir; @@ -1338,15 +1310,13 @@ if (ir->netbits >=3D 0) { msg(D_MULTI_LOW, "MULTI: internal route %s/%d -> %s", - print_in_addr_t(ir->network, 0, &gc), - ir->netbits, + print_in_addr_t(ir->network, 0, &gc), ir->netbits, multi_instance_string(mi, false, &gc)); } else { msg(D_MULTI_LOW, "MULTI: internal route %s -> %s", - print_in_addr_t(ir->network, 0, &gc), - multi_instance_string(mi, false, &gc)); + print_in_addr_t(ir->network, 0, &gc), multi_instance_s= tring(mi, false, &gc)); } mroute_helper_add_iroute46(m->route_helper, ir->netbits); @@ -1356,8 +1326,7 @@ for (ir6 =3D mi->context.options.iroutes_ipv6; ir6 !=3D NULL; ir6 = =3D ir6->next) { msg(D_MULTI_LOW, "MULTI: internal route %s/%d -> %s", - print_in6_addr(ir6->network, 0, &gc), - ir6->netbits, + print_in6_addr(ir6->network, 0, &gc), ir6->netbits, multi_instance_string(mi, false, &gc)); mroute_helper_add_iroute46(m->route_helper, ir6->netbits); @@ -1387,7 +1356,7 @@ hash_iterator_init(m->iter, &hi); while ((he =3D hash_iterator_next(&hi))) { - struct multi_instance *mi =3D (struct multi_instance *) he= ->value; + struct multi_instance *mi =3D (struct multi_instance *)he-= >value; if (mi !=3D new_mi && !mi->halt) { const char *cn =3D tls_common_name(mi->context.c2.tls_= multi, true); @@ -1404,7 +1373,9 @@ if (count) { - msg(D_MULTI_LOW, "MULTI: new connection by client '%s' wil= l cause previous active sessions by this client to be dropped. Remember to= use the --duplicate-cn option if you want multiple clients using the same = certificate or username to concurrently connect.", new_cn); + msg(D_MULTI_LOW, + "MULTI: new connection by client '%s' will cause previ= ous active sessions by this client to be dropped. Remember to use the --du= plicate-cn option if you want multiple clients using the same certificate o= r username to concurrently connect.", + new_cn); } } } @@ -1413,7 +1384,6 @@ static void check_stale_routes(struct multi_context *m) { - struct gc_arena gc =3D gc_new(); struct hash_iterator hi; struct hash_element *he; @@ -1422,8 +1392,9 @@ hash_iterator_init_range(m->vhash, &hi, 0, hash_n_buckets(m->vhash)); while ((he =3D hash_iterator_next(&hi)) !=3D NULL) { - struct multi_route *r =3D (struct multi_route *) he->value; - if (multi_route_defined(m, r) && difftime(now, r->last_reference) = >=3D m->top.options.stale_routes_ageing_time) + struct multi_route *r =3D (struct multi_route *)he->value; + if (multi_route_defined(m, r) + && difftime(now, r->last_reference) >=3D m->top.options.stale_= routes_ageing_time) { dmsg(D_MULTI_DEBUG, "MULTI: Deleting stale route for address '= %s'", mroute_addr_print(&r->addr, &gc)); @@ -1446,7 +1417,8 @@ const struct options *o =3D &c->options; if (o->push_ifconfig_constraint_defined && c->c2.push_ifconfig_defined) { - return (o->push_ifconfig_constraint_netmask & c->c2.push_ifconfig_= local) =3D=3D o->push_ifconfig_constraint_network; + return (o->push_ifconfig_constraint_netmask & c->c2.push_ifconfig_= local) + =3D=3D o->push_ifconfig_constraint_network; } else { @@ -1480,7 +1452,8 @@ mi->context.c2.push_ifconfig_defined =3D true; mi->context.c2.push_ifconfig_local =3D mi->context.options.push_if= config_local; - mi->context.c2.push_ifconfig_remote_netmask =3D mi->context.option= s.push_ifconfig_remote_netmask; + mi->context.c2.push_ifconfig_remote_netmask =3D + mi->context.options.push_ifconfig_remote_netmask; mi->context.c2.push_ifconfig_local_alias =3D mi->context.options.p= ush_ifconfig_local_alias; /* the current implementation does not allow "static IPv4, pool IP= v6", @@ -1490,7 +1463,8 @@ if (mi->context.options.ifconfig_ipv6_pool_defined && !mi->context.options.push_ifconfig_ipv6_defined) { - msg( M_INFO, "MULTI_sva: WARNING: if --ifconfig-push is used f= or IPv4, automatic IPv6 assignment from --ifconfig-ipv6-pool does not work.= Use --ifconfig-ipv6-push for IPv6 then." ); + msg(M_INFO, + "MULTI_sva: WARNING: if --ifconfig-push is used for IPv4, = automatic IPv6 assignment from --ifconfig-ipv6-pool does not work. Use --i= fconfig-ipv6-push for IPv6 then."); } } else if (m->ifconfig_pool && mi->vaddr_handle < 0) /* otherwise, choos= e a pool address */ @@ -1505,30 +1479,33 @@ } CLEAR(remote_ipv6); - mi->vaddr_handle =3D ifconfig_pool_acquire(m->ifconfig_pool, &loca= l, &remote, &remote_ipv6, cn); + mi->vaddr_handle =3D + ifconfig_pool_acquire(m->ifconfig_pool, &local, &remote, &remo= te_ipv6, cn); if (mi->vaddr_handle >=3D 0) { const int tunnel_type =3D TUNNEL_TYPE(mi->context.c1.tuntap); const int tunnel_topology =3D TUNNEL_TOPOLOGY(mi->context.c1.t= untap); =20 - msg( M_INFO, "MULTI_sva: pool returned IPv4=3D%s, IPv6=3D%s", - (mi->context.options.ifconfig_pool_defined - ? print_in_addr_t(remote, 0, &gc) - : "(Not enabled)"), - (mi->context.options.ifconfig_ipv6_pool_defined - ? print_in6_addr( remote_ipv6, 0, &gc ) - : "(Not enabled)") ); + msg(M_INFO, "MULTI_sva: pool returned IPv4=3D%s, IPv6=3D%s", + (mi->context.options.ifconfig_pool_defined ? print_in_addr= _t(remote, 0, &gc) + : "(Not enabled= )"), + (mi->context.options.ifconfig_ipv6_pool_defined + ? print_in6_addr(remote_ipv6, 0, &gc) + : "(Not enabled)")); if (mi->context.options.ifconfig_pool_defined) { /* set push_ifconfig_remote_netmask from pool ifconfig add= ress(es) */ mi->context.c2.push_ifconfig_local =3D remote; - if (tunnel_type =3D=3D DEV_TYPE_TAP || (tunnel_type =3D=3D= DEV_TYPE_TUN && tunnel_topology =3D=3D TOP_SUBNET)) + if (tunnel_type =3D=3D DEV_TYPE_TAP + || (tunnel_type =3D=3D DEV_TYPE_TUN && tunnel_topology= =3D=3D TOP_SUBNET)) { - mi->context.c2.push_ifconfig_remote_netmask =3D mi->co= ntext.options.ifconfig_pool_netmask; + mi->context.c2.push_ifconfig_remote_netmask =3D + mi->context.options.ifconfig_pool_netmask; if (!mi->context.c2.push_ifconfig_remote_netmask) { - mi->context.c2.push_ifconfig_remote_netmask =3D mi= ->context.c1.tuntap->remote_netmask; + mi->context.c2.push_ifconfig_remote_netmask =3D + mi->context.c1.tuntap->remote_netmask; } } else if (tunnel_type =3D=3D DEV_TYPE_TUN) @@ -1558,8 +1535,7 @@ if (mi->context.options.ifconfig_ipv6_pool_defined) { mi->context.c2.push_ifconfig_ipv6_local =3D remote_ipv6; - mi->context.c2.push_ifconfig_ipv6_remote =3D - mi->context.c1.tuntap->local_ipv6; + mi->context.c2.push_ifconfig_ipv6_remote =3D mi->context.c= 1.tuntap->local_ipv6; mi->context.c2.push_ifconfig_ipv6_netbits =3D mi->context.options.ifconfig_ipv6_netbits; mi->context.c2.push_ifconfig_ipv6_defined =3D true; @@ -1580,17 +1556,14 @@ */ if (mi->context.options.push_ifconfig_ipv6_defined) { - mi->context.c2.push_ifconfig_ipv6_local =3D - mi->context.options.push_ifconfig_ipv6_local; - mi->context.c2.push_ifconfig_ipv6_remote =3D - mi->context.options.push_ifconfig_ipv6_remote; - mi->context.c2.push_ifconfig_ipv6_netbits =3D - mi->context.options.push_ifconfig_ipv6_netbits; + mi->context.c2.push_ifconfig_ipv6_local =3D mi->context.options.pu= sh_ifconfig_ipv6_local; + mi->context.c2.push_ifconfig_ipv6_remote =3D mi->context.options.p= ush_ifconfig_ipv6_remote; + mi->context.c2.push_ifconfig_ipv6_netbits =3D mi->context.options.= push_ifconfig_ipv6_netbits; mi->context.c2.push_ifconfig_ipv6_defined =3D true; - msg( M_INFO, "MULTI_sva: push_ifconfig_ipv6 %s/%d", - print_in6_addr( mi->context.c2.push_ifconfig_ipv6_local, 0, &= gc ), - mi->context.c2.push_ifconfig_ipv6_netbits ); + msg(M_INFO, "MULTI_sva: push_ifconfig_ipv6 %s/%d", + print_in6_addr(mi->context.c2.push_ifconfig_ipv6_local, 0, &gc= ), + mi->context.c2.push_ifconfig_ipv6_netbits); } gc_free(&gc); @@ -1611,24 +1584,19 @@ const int tunnel_type =3D TUNNEL_TYPE(mi->context.c1.tuntap); const int tunnel_topology =3D TUNNEL_TOPOLOGY(mi->context.c1.tunta= p); - setenv_in_addr_t(mi->context.c2.es, - "ifconfig_pool_remote_ip", - mi->context.c2.push_ifconfig_local, - SA_SET_IF_NONZERO); + setenv_in_addr_t(mi->context.c2.es, "ifconfig_pool_remote_ip", + mi->context.c2.push_ifconfig_local, SA_SET_IF_NON= ZERO); - if (tunnel_type =3D=3D DEV_TYPE_TAP || (tunnel_type =3D=3D DEV_TYP= E_TUN && tunnel_topology =3D=3D TOP_SUBNET)) + if (tunnel_type =3D=3D DEV_TYPE_TAP + || (tunnel_type =3D=3D DEV_TYPE_TUN && tunnel_topology =3D=3D = TOP_SUBNET)) { - setenv_in_addr_t(mi->context.c2.es, - "ifconfig_pool_netmask", - mi->context.c2.push_ifconfig_remote_netmask, - SA_SET_IF_NONZERO); + setenv_in_addr_t(mi->context.c2.es, "ifconfig_pool_netmask", + mi->context.c2.push_ifconfig_remote_netmask, = SA_SET_IF_NONZERO); } else if (tunnel_type =3D=3D DEV_TYPE_TUN) { - setenv_in_addr_t(mi->context.c2.es, - "ifconfig_pool_local_ip", - mi->context.c2.push_ifconfig_remote_netmask, - SA_SET_IF_NONZERO); + setenv_in_addr_t(mi->context.c2.es, "ifconfig_pool_local_ip", + mi->context.c2.push_ifconfig_remote_netmask, = SA_SET_IF_NONZERO); } } @@ -1638,16 +1606,11 @@ if (mi->context.c2.push_ifconfig_ipv6_defined) { - setenv_in6_addr(mi->context.c2.es, - "ifconfig_pool_remote", - &mi->context.c2.push_ifconfig_ipv6_local, - SA_SET_IF_NONZERO); - setenv_in6_addr(mi->context.c2.es, - "ifconfig_pool_local", - &mi->context.c2.push_ifconfig_ipv6_remote, - SA_SET_IF_NONZERO); - setenv_int(mi->context.c2.es, - "ifconfig_pool_ip6_netbits", + setenv_in6_addr(mi->context.c2.es, "ifconfig_pool_remote", + &mi->context.c2.push_ifconfig_ipv6_local, SA_SET_I= F_NONZERO); + setenv_in6_addr(mi->context.c2.es, "ifconfig_pool_local", + &mi->context.c2.push_ifconfig_ipv6_remote, SA_SET_= IF_NONZERO); + setenv_int(mi->context.c2.es, "ifconfig_pool_ip6_netbits", mi->context.c2.push_ifconfig_ipv6_netbits); } } @@ -1656,20 +1619,14 @@ * Called after client-connect script is called */ static void -multi_client_connect_post(struct multi_context *m, - struct multi_instance *mi, - const char *dc_file, +multi_client_connect_post(struct multi_context *m, struct multi_instance *= mi, const char *dc_file, unsigned int *option_types_found) { /* Did script generate a dynamic config file? */ if (platform_test_file(dc_file)) { - options_server_import(&mi->context.options, - dc_file, - D_IMPORT_ERRORS|M_OPTERR, - CLIENT_CONNECT_OPT_MASK, - option_types_found, - mi->context.c2.es); + options_server_import(&mi->context.options, dc_file, D_IMPORT_ERRO= RS | M_OPTERR, + CLIENT_CONNECT_OPT_MASK, option_types_found,= mi->context.c2.es); /* * If the --client-connect script generates a config file @@ -1688,10 +1645,8 @@ * Called after client-connect plug-in is called */ static void -multi_client_connect_post_plugin(struct multi_context *m, - struct multi_instance *mi, - const struct plugin_return *pr, - unsigned int *option_types_found) +multi_client_connect_post_plugin(struct multi_context *m, struct multi_ins= tance *mi, + const struct plugin_return *pr, unsigned = int *option_types_found) { struct plugin_return config; @@ -1705,12 +1660,9 @@ { if (config.list[i] && config.list[i]->value) { - options_string_import(&mi->context.options, - config.list[i]->value, - D_IMPORT_ERRORS|M_OPTERR, - CLIENT_CONNECT_OPT_MASK, - option_types_found, - mi->context.c2.es); + options_string_import(&mi->context.options, config.list[i]= ->value, + D_IMPORT_ERRORS | M_OPTERR, CLIENT_C= ONNECT_OPT_MASK, + option_types_found, mi->context.c2.e= s); } } @@ -1732,9 +1684,7 @@ * Called to load management-derived client-connect config */ enum client_connect_return -multi_client_connect_mda(struct multi_context *m, - struct multi_instance *mi, - bool deferred, +multi_client_connect_mda(struct multi_context *m, struct multi_instance *m= i, bool deferred, unsigned int *option_types_found) { /* We never return CC_RET_DEFERRED */ @@ -1747,12 +1697,8 @@ for (be =3D mi->cc_config->head; be !=3D NULL; be =3D be->next) { const char *opt =3D BSTR(&be->buf); - options_string_import(&mi->context.options, - opt, - D_IMPORT_ERRORS|M_OPTERR, - CLIENT_CONNECT_OPT_MASK, - option_types_found, - mi->context.c2.es); + options_string_import(&mi->context.options, opt, D_IMPORT_ERRO= RS | M_OPTERR, + CLIENT_CONNECT_OPT_MASK, option_types_fo= und, mi->context.c2.es); } /* @@ -1817,9 +1763,9 @@ else if (dco_enabled(o)) { msg(M_INFO, "Client does not support DATA_V2. Data channel offload= ing " - "requires DATA_V2. Dropping client."); + "requires DATA_V2. Dropping client."); auth_set_client_reason(tls_multi, "Data channel negotiation " - "failed (missing DATA_V2)"); + "failed (missing DATA_V2)"); return false; } @@ -1828,8 +1774,8 @@ if (proto & IV_PROTO_NCP_P2P) { msg(M_WARN, "Note: peer reports running in P2P mode (no --pull/--c= lient " - "option). It will not negotiate ciphers with this server. " - "Expect this connection to fail."); + "option). It will not negotiate ciphers with this serv= er. " + "Expect this connection to fail."); } if (proto & IV_PROTO_REQUEST_PUSH) @@ -1844,11 +1790,11 @@ else if (o->force_key_material_export) { msg(M_INFO, "PUSH: client does not support TLS Keying Material " - "Exporters but --force-tls-key-material-export is enabled."); + "Exporters but --force-tls-key-material-export is enab= led."); auth_set_client_reason(tls_multi, "Client incompatible with this " - "server. Keying Material Exporters (RFC 570= 5) " - "support missing. Upgrade to a client that " - "supports this feature (OpenVPN 2.6.0+)."); + "server. Keying Material Exporte= rs (RFC 5705) " + "support missing. Upgrade to a c= lient that " + "supports this feature (OpenVPN = 2.6.0+)."); return false; } if (proto & IV_PROTO_DYN_TLS_CRYPT) @@ -1869,10 +1815,11 @@ */ if (get_primary_key(tls_multi)->crypto_options.key_ctx_bi.initialized) { - msg(M_INFO, "PUSH: client wants to negotiate cipher (NCP), but " + msg(M_INFO, + "PUSH: client wants to negotiate cipher (NCP), but " "server has already generated data channel keys, " "re-sending previously negotiated cipher '%s'", - o->ciphername ); + o->ciphername); return true; } @@ -1880,14 +1827,13 @@ * Push the first cipher from --data-ciphers to the client that * the client announces to be supporting. */ - char *push_cipher =3D ncp_get_best_cipher(o->ncp_ciphers, peer_info, - tls_multi->remote_ciphername, - &o->gc); + char *push_cipher =3D + ncp_get_best_cipher(o->ncp_ciphers, peer_info, tls_multi->remote_c= iphername, &o->gc); if (push_cipher) { /* Enable epoch data key format if supported and AEAD cipher in us= e */ - if (tls_multi->session[TM_ACTIVE].opt->data_epoch_supported - && (proto & IV_PROTO_DATA_EPOCH) && cipher_kt_mode_aead(push_c= ipher)) + if (tls_multi->session[TM_ACTIVE].opt->data_epoch_supported && (pr= oto & IV_PROTO_DATA_EPOCH) + && cipher_kt_mode_aead(push_cipher)) { o->imported_protocol_flags |=3D CO_EPOCH_DATA_KEY_FORMAT; } @@ -1908,16 +1854,17 @@ * side, in this situation we fail the auth*/ if (strlen(peer_ciphers) > 0) { - msg(M_INFO, "PUSH: No common cipher between server and client. " + msg(M_INFO, + "PUSH: No common cipher between server and client. " "Server data-ciphers: '%s'%s, client supported ciphers '%s'", o->ncp_ciphers_conf, ncp_expanded_ciphers(o, &gc), peer_cipher= s); } else if (tls_multi->remote_ciphername) { - msg(M_INFO, "PUSH: No common cipher between server and client. " + msg(M_INFO, + "PUSH: No common cipher between server and client. " "Server data-ciphers: '%s'%s, client supports cipher '%s'", - o->ncp_ciphers_conf, ncp_expanded_ciphers(o, &gc), - tls_multi->remote_ciphername); + o->ncp_ciphers_conf, ncp_expanded_ciphers(o, &gc), tls_multi->= remote_ciphername); } else { @@ -1925,20 +1872,22 @@ if (o->enable_ncp_fallback && !tls_multi->remote_ciphername) { - msg(M_INFO, "Using data channel cipher '%s' since " - "--data-ciphers-fallback is set.", o->ciphername); + msg(M_INFO, + "Using data channel cipher '%s' since " + "--data-ciphers-fallback is set.", + o->ciphername); ret =3D true; } else { msg(M_INFO, "Use --data-ciphers-fallback with the cipher the " - "client is using if you want to allow the client to connec= t"); + "client is using if you want to allow the client t= o connect"); } } if (!ret) { auth_set_client_reason(tls_multi, "Data channel cipher negotiation= " - "failed (no shared cipher)"); + "failed (no shared cipher)"); } gc_free(&gc); @@ -1961,8 +1910,7 @@ setenv_del(mi->context.c2.es, "client_connect_deferred_file"); if (!platform_unlink(ccs->deferred_ret_file)) { - msg(D_MULTI_ERRORS, "MULTI: problem deleting temporary file: %s", - ccs->deferred_ret_file); + msg(D_MULTI_ERRORS, "MULTI: problem deleting temporary file: %s", = ccs->deferred_ret_file); } free(ccs->deferred_ret_file); ccs->deferred_ret_file =3D NULL; @@ -1993,8 +1941,7 @@ } ccs->deferred_ret_file =3D string_alloc(fn, NULL); - setenv_str(mi->context.c2.es, "client_connect_deferred_file", - ccs->deferred_ret_file); + setenv_str(mi->context.c2.es, "client_connect_deferred_file", ccs->def= erred_ret_file); gc_free(&gc); return true; @@ -2045,7 +1992,7 @@ default: /* We received an unknown/unexpected value. Assume failure. */ msg(M_WARN, "WARNING: Unknown/unexpected value in deferred " - "client-connect resultfile"); + "client-connect resultfile"); ret =3D CC_RET_FAILED; } fclose(fp); @@ -2067,8 +2014,7 @@ setenv_del(mi->context.c2.es, "client_connect_config_file"); if (!platform_unlink(ccs->config_file)) { - msg(D_MULTI_ERRORS, "MULTI: problem deleting temporary file: %= s", - ccs->config_file); + msg(D_MULTI_ERRORS, "MULTI: problem deleting temporary file: %= s", ccs->config_file); } free(ccs->config_file); ccs->config_file =3D NULL; @@ -2102,18 +2048,15 @@ } ccs->config_file =3D string_alloc(fn, NULL); - setenv_str(mi->context.c2.es, "client_connect_config_file", - ccs->config_file); + setenv_str(mi->context.c2.es, "client_connect_config_file", ccs->confi= g_file); gc_free(&gc); return true; } static enum client_connect_return -multi_client_connect_call_plugin_v1(struct multi_context *m, - struct multi_instance *mi, - bool deferred, - unsigned int *option_types_found) +multi_client_connect_call_plugin_v1(struct multi_context *m, struct multi_= instance *mi, + bool deferred, unsigned int *option_ty= pes_found) { enum client_connect_return ret =3D CC_RET_SKIPPED; #ifdef ENABLE_PLUGIN @@ -2131,8 +2074,7 @@ if (!deferred) { call =3D OPENVPN_PLUGIN_CLIENT_CONNECT; - if (!ccs_gen_config_file(mi) - || !ccs_gen_deferred_ret_file(mi)) + if (!ccs_gen_config_file(mi) || !ccs_gen_deferred_ret_file(mi)) { ret =3D CC_RET_FAILED; goto cleanup; @@ -2147,8 +2089,7 @@ } argv_printf(&argv, "%s", ccs->config_file); - int plug_ret =3D plugin_call(mi->context.plugins, call, - &argv, NULL, mi->context.c2.es); + int plug_ret =3D plugin_call(mi->context.plugins, call, &argv, NUL= L, mi->context.c2.es); if (plug_ret =3D=3D OPENVPN_PLUGIN_FUNC_SUCCESS) { ret =3D CC_RET_SUCCEEDED; @@ -2188,8 +2129,7 @@ /* if we still think we have succeeded, do postprocessing */ if (ret =3D=3D CC_RET_SUCCEEDED) { - multi_client_connect_post(m, mi, ccs->config_file, - option_types_found); + multi_client_connect_post(m, mi, ccs->config_file, option_type= s_found); } cleanup: argv_free(&argv); @@ -2205,10 +2145,8 @@ } static enum client_connect_return -multi_client_connect_call_plugin_v2(struct multi_context *m, - struct multi_instance *mi, - bool deferred, - unsigned int *option_types_found) +multi_client_connect_call_plugin_v2(struct multi_context *m, struct multi_= instance *mi, + bool deferred, unsigned int *option_ty= pes_found) { enum client_connect_return ret =3D CC_RET_SKIPPED; #ifdef ENABLE_PLUGIN @@ -2216,8 +2154,7 @@ ASSERT(mi); ASSERT(option_types_found); - int call =3D deferred ? OPENVPN_PLUGIN_CLIENT_CONNECT_DEFER_V2 : - OPENVPN_PLUGIN_CLIENT_CONNECT_V2; + int call =3D deferred ? OPENVPN_PLUGIN_CLIENT_CONNECT_DEFER_V2 : OPENV= PN_PLUGIN_CLIENT_CONNECT_V2; /* V2 callback, use a plugin_return struct for passing back return inf= o */ if (plugin_defined(mi->context.plugins, call)) { @@ -2225,8 +2162,7 @@ plugin_return_init(&pr); - int plug_ret =3D plugin_call(mi->context.plugins, call, - NULL, &pr, mi->context.c2.es); + int plug_ret =3D plugin_call(mi->context.plugins, call, NULL, &pr,= mi->context.c2.es); if (plug_ret =3D=3D OPENVPN_PLUGIN_FUNC_SUCCESS) { multi_client_connect_post_plugin(m, mi, &pr, option_types_foun= d); @@ -2235,13 +2171,12 @@ else if (plug_ret =3D=3D OPENVPN_PLUGIN_FUNC_DEFERRED) { ret =3D CC_RET_DEFERRED; - if (!(plugin_defined(mi->context.plugins, - OPENVPN_PLUGIN_CLIENT_CONNECT_DEFER_V2))) + if (!(plugin_defined(mi->context.plugins, OPENVPN_PLUGIN_CLIEN= T_CONNECT_DEFER_V2))) { msg(M_WARN, "A plugin that defers from the " - "OPENVPN_PLUGIN_CLIENT_CONNECT_V2 call must also " - "declare support for " - "OPENVPN_PLUGIN_CLIENT_CONNECT_DEFER_V2"); + "OPENVPN_PLUGIN_CLIENT_CONNECT_V2 call must al= so " + "declare support for " + "OPENVPN_PLUGIN_CLIENT_CONNECT_DEFER_V2"); ret =3D CC_RET_FAILED; } } @@ -2259,8 +2194,7 @@ } static enum client_connect_return -multi_client_connect_script_deferred(struct multi_context *m, - struct multi_instance *mi, +multi_client_connect_script_deferred(struct multi_context *m, struct multi= _instance *mi, unsigned int *option_types_found) { ASSERT(mi); @@ -2285,8 +2219,7 @@ if (ret =3D=3D CC_RET_SUCCEEDED) { ccs_delete_deferred_ret_file(mi); - multi_client_connect_post(m, mi, ccs->config_file, - option_types_found); + multi_client_connect_post(m, mi, ccs->config_file, option_types_fo= und); ccs_delete_config_file(mi); } if (ret =3D=3D CC_RET_FAILED) @@ -2302,9 +2235,7 @@ * Runs the --client-connect script if one is defined. */ static enum client_connect_return -multi_client_connect_call_script(struct multi_context *m, - struct multi_instance *mi, - bool deferred, +multi_client_connect_call_script(struct multi_context *m, struct multi_ins= tance *mi, bool deferred, unsigned int *option_types_found) { if (deferred) @@ -2324,8 +2255,7 @@ setenv_str(mi->context.c2.es, "script_type", "client-connect"); - if (!ccs_gen_config_file(mi) - || !ccs_gen_deferred_ret_file(mi)) + if (!ccs_gen_config_file(mi) || !ccs_gen_deferred_ret_file(mi)) { ret =3D CC_RET_FAILED; goto cleanup; @@ -2342,8 +2272,7 @@ } else { - multi_client_connect_post(m, mi, ccs->config_file, - option_types_found); + multi_client_connect_post(m, mi, ccs->config_file, option_= types_found); ret =3D CC_RET_SUCCEEDED; } } @@ -2364,8 +2293,7 @@ } static bool -multi_client_setup_dco_initial(struct multi_context *m, - struct multi_instance *mi, +multi_client_setup_dco_initial(struct multi_context *m, struct multi_insta= nce *mi, struct gc_arena *gc) { if (!dco_enabled(&mi->context.options)) @@ -2376,8 +2304,8 @@ int ret =3D dco_multi_add_new_peer(m, mi); if (ret < 0) { - msg(D_DCO, "Cannot add peer to DCO for %s: %s (%d)", - multi_instance_string(mi, false, gc), strerror(-ret), ret); + msg(D_DCO, "Cannot add peer to DCO for %s: %s (%d)", multi_instanc= e_string(mi, false, gc), + strerror(-ret), ret); return false; } @@ -2398,9 +2326,8 @@ } #endif struct tls_session *session =3D &c->c2.tls_multi->session[TM_ACTIVE]; - if (!tls_session_update_crypto_params(c->c2.tls_multi, session, &c->op= tions, - &c->c2.frame, frame_fragment, - get_link_socket_info(c), + if (!tls_session_update_crypto_params(c->c2.tls_multi, session, &c->op= tions, &c->c2.frame, + frame_fragment, get_link_socket_= info(c), &c->c1.tuntap->dco)) { msg(D_TLS_ERRORS, "TLS Error: initializing data channel failed"); @@ -2412,8 +2339,7 @@ } static void -multi_client_connect_late_setup(struct multi_context *m, - struct multi_instance *mi, +multi_client_connect_late_setup(struct multi_context *m, struct multi_inst= ance *mi, const unsigned int option_types_found) { ASSERT(m); @@ -2430,7 +2356,8 @@ */ if (!mi->context.c2.push_ifconfig_defined) { - msg(D_MULTI_ERRORS, "MULTI: no dynamic or static remote " + msg(D_MULTI_ERRORS, + "MULTI: no dynamic or static remote " "--ifconfig address is available for %s", multi_instance_string(mi, false, &gc)); } @@ -2446,7 +2373,8 @@ print_in_addr_t(mi->context.options.push_ifconfig_constraint_n= etmask, 0, &gc); /* JYFIXME -- this should cause the connection to fail */ - msg(D_MULTI_ERRORS, "MULTI ERROR: primary virtual IP for %s (%s) " + msg(D_MULTI_ERRORS, + "MULTI ERROR: primary virtual IP for %s (%s) " "violates tunnel network/netmask constraint (%s/%s)", multi_instance_string(mi, false, &gc), print_in_addr_t(mi->context.c2.push_ifconfig_local, 0, &gc), @@ -2490,9 +2418,7 @@ { if (mi->context.c2.push_ifconfig_defined) { - multi_learn_in_addr_t(m, mi, - mi->context.c2.push_ifconfig_local, - -1, true); + multi_learn_in_addr_t(m, mi, mi->context.c2.push_ifconfig_loca= l, -1, true); msg(D_MULTI_LOW, "MULTI: primary virtual IP for %s: %s", multi_instance_string(mi, false, &gc), print_in_addr_t(mi->context.c2.push_ifconfig_local, 0, &gc= )); @@ -2500,15 +2426,12 @@ if (mi->context.c2.push_ifconfig_ipv6_defined) { - multi_learn_in6_addr(m, mi, - mi->context.c2.push_ifconfig_ipv6_local, - -1, true); + multi_learn_in6_addr(m, mi, mi->context.c2.push_ifconfig_ipv6_= local, -1, true); /* TODO: find out where addresses are "unlearned"!! */ const char *ifconfig_local_ipv6 =3D print_in6_addr(mi->context.c2.push_ifconfig_ipv6_local, 0,= &gc); msg(D_MULTI_LOW, "MULTI: primary virtual IPv6 for %s: %s", - multi_instance_string(mi, false, &gc), - ifconfig_local_ipv6); + multi_instance_string(mi, false, &gc), ifconfig_local_ipv6= ); } /* add routes locally, pointing to new client, if @@ -2524,7 +2447,8 @@ } else if (mi->context.options.iroutes) { - msg(D_MULTI_ERRORS, "MULTI: --iroute options rejected for %s -- ir= oute " + msg(D_MULTI_ERRORS, + "MULTI: --iroute options rejected for %s -- iroute " "only works with tun-style tunnels", multi_instance_string(mi, false, &gc)); } @@ -2538,8 +2462,7 @@ } static void -multi_client_connect_early_setup(struct multi_context *m, - struct multi_instance *mi) +multi_client_connect_early_setup(struct multi_context *m, struct multi_ins= tance *mi) { ASSERT(mi->context.c1.tuntap); /* @@ -2574,10 +2497,8 @@ * ccd/script to do compression on a special client. */ static enum client_connect_return -multi_client_connect_compress_migrate(struct multi_context *m, - struct multi_instance *mi, - bool deferred, - unsigned int *option_types_found) +multi_client_connect_compress_migrate(struct multi_context *m, struct mult= i_instance *mi, + bool deferred, unsigned int *option_= types_found) { #ifdef USE_COMP struct options *o =3D &mi->context.options; @@ -2608,9 +2529,7 @@ * --client-config-dir directory. */ static enum client_connect_return -multi_client_connect_source_ccd(struct multi_context *m, - struct multi_instance *mi, - bool deferred, +multi_client_connect_source_ccd(struct multi_context *m, struct multi_inst= ance *mi, bool deferred, unsigned int *option_types_found) { /* Since we never return a CC_RET_DEFERRED, this indicates a serious @@ -2624,12 +2543,10 @@ const char *ccd_client =3D platform_gen_path(mi->context.options.client_config_dir, - tls_common_name(mi->context.c2.tls_multi, fa= lse), - &gc); + tls_common_name(mi->context.c2.tls_multi, fa= lse), &gc); const char *ccd_default =3D - platform_gen_path(mi->context.options.client_config_dir, - CCD_DEFAULT, &gc); + platform_gen_path(mi->context.options.client_config_dir, CCD_D= EFAULT, &gc); /* try common-name file */ @@ -2645,12 +2562,8 @@ if (ccd_file) { - options_server_import(&mi->context.options, - ccd_file, - D_IMPORT_ERRORS|M_OPTERR, - CLIENT_CONNECT_OPT_MASK, - option_types_found, - mi->context.c2.es); + options_server_import(&mi->context.options, ccd_file, D_IMPORT= _ERRORS | M_OPTERR, + CLIENT_CONNECT_OPT_MASK, option_types_fo= und, mi->context.c2.es); /* * Select a virtual address from either --ifconfig-push in * --client-config-dir file or --ifconfig-pool. @@ -2666,9 +2579,9 @@ return ret; } -typedef enum client_connect_return (*multi_client_connect_handler) - (struct multi_context *m, struct multi_instance *mi, - bool from_deferred, unsigned int *option_types_found); +typedef enum client_connect_return (*multi_client_connect_handler)( + struct multi_context *m, struct multi_instance *mi, bool from_deferred, + unsigned int *option_types_found); static const multi_client_connect_handler client_connect_handlers[] =3D { multi_client_connect_compress_migrate, @@ -2694,9 +2607,9 @@ if (!multi->locked_username) { msg(D_MULTI_ERRORS, "MULTI: Ignoring override-username as no " - "user/password method is enabled. Enable " - "--management-client-auth, --auth-user-pass-verify, or a " - "plugin with user/password verify capability."); + "user/password method is enabled. Enable " + "--management-client-auth, --auth-user-pass-ve= rify, or a " + "plugin with user/password verify capability."= ); return false; } @@ -2727,16 +2640,15 @@ { struct user_pass up; CLEAR(up); - strncpynt(up.username, multi->locked_username, - sizeof(up.username)); + strncpynt(up.username, multi->locked_username, sizeof(up.usern= ame)); generate_auth_token(&up, multi); } - msg(D_MULTI_LOW, "MULTI: Note, override-username changes username " + msg(D_MULTI_LOW, + "MULTI: Note, override-username changes username " "from '%s' to '%s'", - multi->locked_original_username, - multi->locked_username); + multi->locked_original_username, multi->locked_username); } return true; } @@ -2767,8 +2679,7 @@ bool from_deferred =3D (mi->context.c2.tls_multi->multi_state !=3D CAS= _PENDING); int *cur_handler_index =3D &mi->client_connect_defer_state.cur_handler= _index; - unsigned int *option_types_found =3D - &mi->client_connect_defer_state.option_types_found; + unsigned int *option_types_found =3D &mi->client_connect_defer_state.o= ption_types_found; /* We are called for the first time */ if (!from_deferred) @@ -2783,12 +2694,10 @@ bool cc_succeeded =3D true; - while (cc_succeeded - && client_connect_handlers[*cur_handler_index] !=3D NULL) + while (cc_succeeded && client_connect_handlers[*cur_handler_index] != =3D NULL) { enum client_connect_return ret; - ret =3D client_connect_handlers[*cur_handler_index](m, mi, from_de= ferred, - option_types_fou= nd); + ret =3D client_connect_handlers[*cur_handler_index](m, mi, from_de= ferred, option_types_found); from_deferred =3D false; @@ -2836,7 +2745,7 @@ if (mi->context.options.disable) { msg(D_MULTI_ERRORS, "MULTI: client has been rejected due to " - "'disable' directive"); + "'disable' directive"); cc_succeeded =3D false; } @@ -2889,8 +2798,8 @@ #ifdef ENABLE_MANAGEMENT if (management) { - management_connection_established(management, - &mi->context.c2.mda_context, mi-= >context.c2.es); + management_connection_established(management, &mi->context.c2.mda_= context, + mi->context.c2.es); } #endif } @@ -2912,13 +2821,14 @@ while (buffer_i < r) { /* parse inotify events */ - struct inotify_event *pevent =3D (struct inotify_event *) &buffer[= buffer_i]; + struct inotify_event *pevent =3D (struct inotify_event *)&buffer[b= uffer_i]; size_t event_size =3D sizeof(struct inotify_event) + pevent->len; buffer_i +=3D event_size; msg(D_MULTI_DEBUG, "MULTI: modified fd %d, mask %d", pevent->wd, p= event->mask); - struct multi_instance *mi =3D hash_lookup(m->inotify_watchers, (vo= id *) (unsigned long) pevent->wd); + struct multi_instance *mi =3D + hash_lookup(m->inotify_watchers, (void *)(unsigned long)pevent= ->wd); if (pevent->mask & IN_CLOSE_WRITE) { @@ -2937,7 +2847,7 @@ /* this event is _always_ fired when watch is removed or file = is deleted */ if (mi) { - hash_remove(m->inotify_watchers, (void *) (unsigned long) = pevent->wd); + hash_remove(m->inotify_watchers, (void *)(unsigned long)pe= vent->wd); mi->inotify_watch =3D -1; } } @@ -2954,9 +2864,7 @@ * instance. */ void -multi_add_mbuf(struct multi_context *m, - struct multi_instance *mi, - struct mbuf_buffer *mb) +multi_add_mbuf(struct multi_context *m, struct multi_instance *mi, struct = mbuf_buffer *mb) { if (multi_output_queue_ready(m, mi)) { @@ -2975,9 +2883,7 @@ * Add a packet to a client instance output queue. */ static inline void -multi_unicast(struct multi_context *m, - const struct buffer *buf, - struct multi_instance *mi) +multi_unicast(struct multi_context *m, const struct buffer *buf, struct mu= lti_instance *mi) { struct mbuf_buffer *mb; @@ -2994,10 +2900,8 @@ * Broadcast a packet to all clients. */ static void -multi_bcast(struct multi_context *m, - const struct buffer *buf, - const struct multi_instance *sender_instance, - uint16_t vid) +multi_bcast(struct multi_context *m, const struct buffer *buf, + const struct multi_instance *sender_instance, uint16_t vid) { struct hash_iterator hi; struct hash_element *he; @@ -3015,7 +2919,7 @@ while ((he =3D hash_iterator_next(&hi))) { - mi =3D (struct multi_instance *) he->value; + mi =3D (struct multi_instance *)he->value; if (mi !=3D sender_instance && !mi->halt) { if (vid !=3D 0 && vid !=3D mi->context.options.vlan_pvid) @@ -3073,29 +2977,24 @@ tv_add(&mi->wakeup, &mi->context.c2.timeval); /* tell scheduler to wake us up at some point in the future */ - schedule_add_entry(m->schedule, - (struct schedule_entry *) mi, - &mi->wakeup, + schedule_add_entry(m->schedule, (struct schedule_entry *)mi, &mi->wake= up, compute_wakeup_sigma(&mi->context.c2.timeval)); } #if defined(ENABLE_ASYNC_PUSH) static void -add_inotify_file_watch(struct multi_context *m, struct multi_instance *mi, - int inotify_fd, const char *file) +add_inotify_file_watch(struct multi_context *m, struct multi_instance *mi,= int inotify_fd, + const char *file) { /* watch acf file */ - long watch_descriptor =3D inotify_add_watch(inotify_fd, file, - IN_CLOSE_WRITE | IN_ONESHOT); + long watch_descriptor =3D inotify_add_watch(inotify_fd, file, IN_CLOSE= _WRITE | IN_ONESHOT); if (watch_descriptor >=3D 0) { if (mi->inotify_watch !=3D -1) { - hash_remove(m->inotify_watchers, - (void *) (unsigned long)mi->inotify_watch); + hash_remove(m->inotify_watchers, (void *)(unsigned long)mi->in= otify_watch); } - hash_add(m->inotify_watchers, (const uintptr_t *)watch_descriptor, - mi, true); + hash_add(m->inotify_watchers, (const uintptr_t *)watch_descriptor,= mi, true); mi->inotify_watch =3D watch_descriptor; } else @@ -3117,7 +3016,9 @@ { bool ret =3D true; - if (!IS_SIG(&mi->context) && ((flags & MPP_PRE_SELECT) || ((flags & MP= P_CONDITIONAL_PRE_SELECT) && !ANY_OUT(&mi->context)))) + if (!IS_SIG(&mi->context) + && ((flags & MPP_PRE_SELECT) + || ((flags & MPP_CONDITIONAL_PRE_SELECT) && !ANY_OUT(&mi->cont= ext)))) { #if defined(ENABLE_ASYNC_PUSH) bool was_unauthenticated =3D true; @@ -3142,14 +3043,12 @@ if (ks && ks->plugin_auth.auth_control_file && was_unauthenticated && (ks->authenticated =3D=3D KS_AUTH_DEFERRED)) { - add_inotify_file_watch(m, mi, m->top.c2.inotify_fd, - ks->plugin_auth.auth_control_file); + add_inotify_file_watch(m, mi, m->top.c2.inotify_fd, ks->plugin= _auth.auth_control_file); } if (ks && ks->script_auth.auth_control_file && was_unauthenticated && (ks->authenticated =3D=3D KS_AUTH_DEFERRED)) { - add_inotify_file_watch(m, mi, m->top.c2.inotify_fd, - ks->script_auth.auth_control_file); + add_inotify_file_watch(m, mi, m->top.c2.inotify_fd, ks->script= _auth.auth_control_file); } #endif @@ -3167,8 +3066,7 @@ && mi->client_connect_defer_state.deferred_ret_file) { add_inotify_file_watch(m, mi, m->top.c2.inotify_fd, - mi->client_connect_defer_state. - deferred_ret_file); + mi->client_connect_defer_state.defe= rred_ret_file); } #endif /* tell scheduler to wake us up at some point in the future */ @@ -3190,14 +3088,10 @@ multi_set_pending(m, ANY_OUT(&mi->context) ? mi : NULL); #ifdef MULTI_DEBUG_EVENT_LOOP - printf("POST %s[%d] to=3D%d lo=3D%d/%d w=3D%" PRIi64 "/%ld\n", - id(mi), - (int) (mi =3D=3D m->pending), - mi ? mi->context.c2.to_tun.len : -1, - mi ? mi->context.c2.to_link.len : -1, + printf("POST %s[%d] to=3D%d lo=3D%d/%d w=3D%" PRIi64 "/%ld\n", id(= mi), (int)(mi =3D=3D m->pending), + mi ? mi->context.c2.to_tun.len : -1, mi ? mi->context.c2.to= _link.len : -1, (mi && mi->context.c2.fragment) ? mi->context.c2.fragment->= outgoing.len : -1, - (int64_t)mi->context.c2.timeval.tv_sec, - (long)mi->context.c2.timeval.tv_usec); + (int64_t)mi->context.c2.timeval.tv_sec, (long)mi->context.c= 2.timeval.tv_usec); #endif } @@ -3218,10 +3112,9 @@ * updates hashtables in multi_context. */ static void -multi_process_float(struct multi_context *m, struct multi_instance *mi, - struct link_socket *sock) +multi_process_float(struct multi_context *m, struct multi_instance *mi, st= ruct link_socket *sock) { - struct mroute_addr real =3D {0}; + struct mroute_addr real =3D { 0 }; struct hash *hash =3D m->hash; struct gc_arena gc =3D gc_new(); @@ -3243,7 +3136,7 @@ struct hash_element *he =3D hash_lookup_fast(hash, bucket, &real, hv); if (he) { - struct multi_instance *ex_mi =3D (struct multi_instance *) he->val= ue; + struct multi_instance *ex_mi =3D (struct multi_instance *)he->valu= e; =20 struct tls_multi *m1 =3D mi->context.c2.tls_multi; struct tls_multi *m2 =3D ex_mi->context.c2.tls_multi; @@ -3265,23 +3158,23 @@ */ if (m1->peer_id =3D=3D m2->peer_id) { - msg(M_WARN, "disallowing peer %" PRIu32 " (%s) from floating t= o " + msg(M_WARN, + "disallowing peer %" PRIu32 " (%s) from floating to " "its own address (%s)", m1->peer_id, tls_common_name(mi->context.c2.tls_multi, fal= se), mroute_addr_print(&mi->real, &gc)); goto done; } - msg(D_MULTI_LOW, "closing instance %s due to float collision with = %s " + msg(D_MULTI_LOW, + "closing instance %s due to float collision with %s " "using the same certificate", - multi_instance_string(ex_mi, false, &gc), - multi_instance_string(mi, false, &gc)); + multi_instance_string(ex_mi, false, &gc), multi_instance_strin= g(mi, false, &gc)); multi_close_instance(m, ex_mi, false); } msg(D_MULTI_MEDIUM, "peer %" PRIu32 " (%s) floated from %s to %s", - mi->context.c2.tls_multi->peer_id, - tls_common_name(mi->context.c2.tls_multi, false), + mi->context.c2.tls_multi->peer_id, tls_common_name(mi->context.c2.= tls_multi, false), mroute_addr_print_ex(&mi->real, MAPF_SHOW_FAMILY, &gc), mroute_addr_print_ex(&real, MAPF_SHOW_FAMILY, &gc)); @@ -3327,7 +3220,8 @@ multi_close_instance(m, mi, false); } -#if (defined(ENABLE_DCO) && (defined(TARGET_LINUX) || defined(TARGET_FREEB= SD))) || defined(ENABLE_MANAGEMENT) +#if (defined(ENABLE_DCO) && (defined(TARGET_LINUX) || defined(TARGET_FREEB= SD))) \ + || defined(ENABLE_MANAGEMENT) static void multi_signal_instance(struct multi_context *m, struct multi_instance *mi, = const int sig) { @@ -3338,8 +3232,7 @@ #if defined(ENABLE_DCO) static void -process_incoming_del_peer(struct multi_context *m, struct multi_instance *= mi, - dco_context_t *dco) +process_incoming_del_peer(struct multi_context *m, struct multi_instance *= mi, dco_context_t *dco) { const char *reason =3D "ovpn-dco: unknown reason"; switch (dco->dco_del_peer_reason) @@ -3436,9 +3329,10 @@ */ msglevel =3D D_DCO_DEBUG; } - msg(msglevel, "Received DCO message for unknown peer-id: %d, " - "type %d, del_peer_reason %d", peer_id, dco->dco_message_type, - dco->dco_del_peer_reason); + msg(msglevel, + "Received DCO message for unknown peer-id: %d, " + "type %d, del_peer_reason %d", + peer_id, dco->dco_message_type, dco->dco_del_peer_reason); } dco->dco_message_type =3D 0; @@ -3528,11 +3422,8 @@ if (TUNNEL_TYPE(m->top.c1.tuntap) =3D=3D DEV_TYPE_TUN) { /* extract packet source and dest addresses */ - mroute_flags =3D mroute_extract_addr_from_packet(&src, - &dest, - 0, - &c->c2.to_t= un, - DEV_TYPE_TU= N); + mroute_flags =3D + mroute_extract_addr_from_packet(&src, &dest, 0, &c->c2= .to_tun, DEV_TYPE_TUN); /* drop packet if extract failed */ if (!(mroute_flags & MROUTE_EXTRACT_SUCCEEDED)) @@ -3543,14 +3434,15 @@ else if (multi_get_instance_by_virtual_addr(m, &src, true)= !=3D m->pending) { /* IPv6 link-local address (fe80::xxx)? */ - if ( (src.type & MR_ADDR_MASK) =3D=3D MR_ADDR_IPV6 - && IN6_IS_ADDR_LINKLOCAL(&src.v6.addr) ) + if ((src.type & MR_ADDR_MASK) =3D=3D MR_ADDR_IPV6 + && IN6_IS_ADDR_LINKLOCAL(&src.v6.addr)) { /* do nothing, for now. TODO: add address learnin= g */ } else { - msg(D_MULTI_DROPPED, "MULTI: bad source address fr= om client [%s], packet dropped", + msg(D_MULTI_DROPPED, + "MULTI: bad source address from client [%s], p= acket dropped", mroute_addr_print(&src, &gc)); } c->c2.to_tun.len =3D 0; @@ -3599,11 +3491,8 @@ } } /* extract packet source and dest addresses */ - mroute_flags =3D mroute_extract_addr_from_packet(&src, - &dest, - vid, - &c->c2.to_t= un, - DEV_TYPE_TA= P); + mroute_flags =3D + mroute_extract_addr_from_packet(&src, &dest, vid, &c->= c2.to_tun, DEV_TYPE_TAP); if (mroute_flags & MROUTE_EXTRACT_SUCCEEDED) { @@ -3612,7 +3501,7 @@ /* check for broadcast */ if (m->enable_c2c) { - if (mroute_flags & (MROUTE_EXTRACT_BCAST|MROUT= E_EXTRACT_MCAST)) + if (mroute_flags & (MROUTE_EXTRACT_BCAST | MRO= UTE_EXTRACT_MCAST)) { multi_bcast(m, &c->c2.to_tun, m->pending, = vid); } @@ -3632,7 +3521,8 @@ } else { - msg(D_MULTI_DROPPED, "MULTI: bad source address fr= om client [%s], packet dropped", + msg(D_MULTI_DROPPED, + "MULTI: bad source address from client [%s], p= acket dropped", mroute_addr_print(&src, &gc)); c->c2.to_tun.len =3D 0; } @@ -3666,7 +3556,7 @@ if (BLEN(&m->top.c2.buf) > 0) { unsigned int mroute_flags; - struct mroute_addr src =3D {0}, dest =3D {0}; + struct mroute_addr src =3D { 0 }, dest =3D { 0 }; const int dev_type =3D TUNNEL_TYPE(m->top.c1.tuntap); int16_t vid =3D 0; @@ -3693,25 +3583,22 @@ * the appropriate multi_instance object. */ - mroute_flags =3D mroute_extract_addr_from_packet(&src, - &dest, - vid, - &m->top.c2.buf, - dev_type); + mroute_flags =3D mroute_extract_addr_from_packet(&src, &dest, vid,= &m->top.c2.buf, dev_type); if (mroute_flags & MROUTE_EXTRACT_SUCCEEDED) { struct context *c; /* broadcast or multicast dest addr? */ - if (mroute_flags & (MROUTE_EXTRACT_BCAST|MROUTE_EXTRACT_MCAST)) + if (mroute_flags & (MROUTE_EXTRACT_BCAST | MROUTE_EXTRACT_MCAS= T)) { /* for now, treat multicast as broadcast */ multi_bcast(m, &m->top.c2.buf, NULL, vid); } else { - multi_set_pending(m, multi_get_instance_by_virtual_addr(m,= &dest, dev_type =3D=3D DEV_TYPE_TUN)); + multi_set_pending( + m, multi_get_instance_by_virtual_addr(m, &dest, dev_ty= pe =3D=3D DEV_TYPE_TUN)); if (m->pending) { @@ -3729,7 +3616,8 @@ else { /* drop packet */ - msg(D_MULTI_DROPPED, "MULTI: packet dropped du= e to output saturation (multi_process_incoming_tun)"); + msg(D_MULTI_DROPPED, + "MULTI: packet dropped due to output satur= ation (multi_process_incoming_tun)"); buf_reset_len(&c->c2.buf); } } @@ -3763,7 +3651,8 @@ set_prefix(item.instance); item.instance->context.c2.buf =3D item.buffer->buf; - if (item.buffer->flags & MF_UNICAST) /* --mssfix doesn't make sens= e for broadcast or multicast */ + if (item.buffer->flags + & MF_UNICAST) /* --mssfix doesn't make sense for broadcast or = multicast */ { pip_flags |=3D PIP_MSSFIX; } @@ -3801,7 +3690,8 @@ { if (m->earliest_wakeup =3D=3D (struct multi_instance *)&m->deferre= d_shutdown_signal) { - schedule_remove_entry(m->schedule, (struct schedule_entry *) &= m->deferred_shutdown_signal); + schedule_remove_entry(m->schedule, + (struct schedule_entry *)&m->deferred_sh= utdown_signal); throw_signal(m->deferred_shutdown_signal.signal_received); } else @@ -3844,9 +3734,9 @@ route_quota_exceeded(const struct multi_instance *mi) { struct gc_arena gc =3D gc_new(); - msg(D_ROUTE_QUOTA, "MULTI ROUTE: route quota (%d) exceeded for %s (see= --max-routes-per-client option)", - mi->context.options.max_routes_per_client, - multi_instance_string(mi, false, &gc)); + msg(D_ROUTE_QUOTA, + "MULTI ROUTE: route quota (%d) exceeded for %s (see --max-routes-p= er-client option)", + mi->context.options.max_routes_per_client, multi_instance_string(m= i, false, &gc)); gc_free(&gc); } @@ -3869,8 +3759,7 @@ parm.packet_size =3D min_int(parm.packet_size, m->top.c2.frame.buf= .payload_size); msg(D_GREMLIN, "GREMLIN_FLOOD_CLIENTS: flooding clients with %d pa= ckets of size %d", - parm.n_packets, - parm.packet_size); + parm.n_packets, parm.packet_size); for (i =3D 0; i < parm.packet_size; ++i) { @@ -3958,10 +3847,11 @@ hash_iterator_init(m->iter, &hi); while ((he =3D hash_iterator_next(&hi))) { - struct multi_instance *mi =3D (struct multi_instance *) he->value; + struct multi_instance *mi =3D (struct multi_instance *)he->value; if (!mi->halt && proto_is_dgram(mi->context.c2.link_sockets[0]->in= fo.proto)) { - send_control_channel_string(&mi->context, next_server ? "RESTA= RT,[N]" : "RESTART", D_PUSH); + send_control_channel_string(&mi->context, next_server ? "RESTA= RT,[N]" : "RESTART", + D_PUSH); multi_schedule_context_wakeup(m, mi); } } @@ -3975,8 +3865,7 @@ m->deferred_shutdown_signal.signal_received =3D m->top.sig->signal_rec= eived; - schedule_add_entry(m->schedule, - (struct schedule_entry *) &m->deferred_shutdown_sig= nal, + schedule_add_entry(m->schedule, (struct schedule_entry *)&m->deferred_= shutdown_signal, &m->deferred_shutdown_signal.wakeup, compute_wakeup_sigma(&m->deferred_shutdown_signal.w= akeup)); @@ -3997,8 +3886,7 @@ status_close(so); return false; } - else if (has_udp_in_local_list(&m->top.options) - && is_exit_restart(m->top.sig->signal_received) + else if (has_udp_in_local_list(&m->top.options) && is_exit_restart(m->= top.sig->signal_received) && (m->deferred_shutdown_signal.signal_received =3D=3D 0) && m->top.options.ce.explicit_exit_notification !=3D 0) { @@ -4016,7 +3904,7 @@ static void management_callback_status(void *arg, const int version, struct status_out= put *so) { - struct multi_context *m =3D (struct multi_context *) arg; + struct multi_context *m =3D (struct multi_context *)arg; if (!version) { @@ -4031,14 +3919,14 @@ static int management_callback_n_clients(void *arg) { - struct multi_context *m =3D (struct multi_context *) arg; + struct multi_context *m =3D (struct multi_context *)arg; return m->n_clients; } static int management_callback_kill_by_cn(void *arg, const char *del_cn) { - struct multi_context *m =3D (struct multi_context *) arg; + struct multi_context *m =3D (struct multi_context *)arg; struct hash_iterator hi; struct hash_element *he; int count =3D 0; @@ -4046,7 +3934,7 @@ hash_iterator_init(m->iter, &hi); while ((he =3D hash_iterator_next(&hi))) { - struct multi_instance *mi =3D (struct multi_instance *) he->value; + struct multi_instance *mi =3D (struct multi_instance *)he->value; if (!mi->halt) { const char *cn =3D tls_common_name(mi->context.c2.tls_multi, f= alse); @@ -4062,10 +3950,9 @@ } static int -management_callback_kill_by_addr(void *arg, const in_addr_t addr, - const int port, const int proto) +management_callback_kill_by_addr(void *arg, const in_addr_t addr, const in= t port, const int proto) { - struct multi_context *m =3D (struct multi_context *) arg; + struct multi_context *m =3D (struct multi_context *)arg; struct hash_iterator hi; struct hash_element *he; struct openvpn_sockaddr saddr; @@ -4082,7 +3969,7 @@ hash_iterator_init(m->iter, &hi); while ((he =3D hash_iterator_next(&hi))) { - struct multi_instance *mi =3D (struct multi_instance *) he->va= lue; + struct multi_instance *mi =3D (struct multi_instance *)he->val= ue; if (!mi->halt && mroute_addr_equal(&maddr, &mi->real)) { multi_signal_instance(m, mi, SIGTERM); @@ -4097,7 +3984,7 @@ static void management_delete_event(void *arg, event_t event) { - struct multi_context *m =3D (struct multi_context *) arg; + struct multi_context *m =3D (struct multi_context *)arg; if (m->multi_io) { multi_tcp_delete_event(m->multi_io, event); @@ -4109,7 +3996,7 @@ { if (m) { - struct multi_instance *mi =3D (struct multi_instance *) hash_looku= p(m->cid_hash, &cid); + struct multi_instance *mi =3D (struct multi_instance *)hash_lookup= (m->cid_hash, &cid); if (mi && !mi->halt) { return mi; @@ -4121,7 +4008,7 @@ static bool management_kill_by_cid(void *arg, const unsigned long cid, const char *kil= l_msg) { - struct multi_context *m =3D (struct multi_context *) arg; + struct multi_context *m =3D (struct multi_context *)arg; struct multi_instance *mi =3D lookup_by_cid(m, cid); if (mi) { @@ -4136,13 +4023,10 @@ } static bool -management_client_pending_auth(void *arg, - const unsigned long cid, - const unsigned int mda_key_id, - const char *extra, - unsigned int timeout) +management_client_pending_auth(void *arg, const unsigned long cid, const u= nsigned int mda_key_id, + const char *extra, unsigned int timeout) { - struct multi_context *m =3D (struct multi_context *) arg; + struct multi_context *m =3D (struct multi_context *)arg; struct multi_instance *mi =3D lookup_by_cid(m, cid); if (mi) @@ -4164,8 +4048,7 @@ } /* sends INFO_PRE and AUTH_PENDING messages to client */ - bool ret =3D send_auth_pending_messages(multi, session, extra, - timeout); + bool ret =3D send_auth_pending_messages(multi, session, extra, tim= eout); reschedule_multi_process(&mi->context); multi_schedule_context_wakeup(m, mi); return ret; @@ -4175,15 +4058,11 @@ static bool -management_client_auth(void *arg, - const unsigned long cid, - const unsigned int mda_key_id, - const bool auth, - const char *reason, - const char *client_reason, - struct buffer_list *cc_config) /* ownership transf= erred */ +management_client_auth(void *arg, const unsigned long cid, const unsigned = int mda_key_id, + const bool auth, const char *reason, const char *cl= ient_reason, + struct buffer_list *cc_config) /* ownership transfe= rred */ { - struct multi_context *m =3D (struct multi_context *) arg; + struct multi_context *m =3D (struct multi_context *)arg; struct multi_instance *mi =3D lookup_by_cid(m, cid); bool cc_config_owned =3D true; bool ret =3D false; @@ -4203,7 +4082,8 @@ } else if (reason) { - msg(D_MULTI_LOW, "MULTI: connection rejected: %s, CLI:%s",= reason, np(client_reason)); + msg(D_MULTI_LOW, "MULTI: connection rejected: %s, CLI:%s",= reason, + np(client_reason)); } } } @@ -4217,7 +4097,7 @@ static char * management_get_peer_info(void *arg, const unsigned long cid) { - struct multi_context *m =3D (struct multi_context *) arg; + struct multi_context *m =3D (struct multi_context *)arg; struct multi_instance *mi =3D lookup_by_cid(m, cid); char *ret =3D NULL; @@ -4361,7 +4241,7 @@ tunnel_server_loop(&multi); - #ifdef ENABLE_ASYNC_PUSH +#ifdef ENABLE_ASYNC_PUSH close(top->c2.inotify_fd); #endif @@ -4375,5 +4255,4 @@ multi_uninit(&multi); multi_top_free(&multi); close_instance(top); - } diff --git a/src/openvpn/multi.h b/src/openvpn/multi.h index 3c3db97..e87e465 100644 --- a/src/openvpn/multi.h +++ b/src/openvpn/multi.h @@ -99,27 +99,28 @@ * page describes the role the structure plays when OpenVPN is running in * server-mode. */ -struct multi_instance { - struct schedule_entry se; /* this must be the first element of the st= ructure, - * We cast between this and schedule_entry = so the - * beginning of the struct must be identica= l */ +struct multi_instance +{ + struct schedule_entry se; /* this must be the first element of the str= ucture, + * We cast between this and schedule_entry s= o the + * beginning of the struct must be identical= */ - struct event_arg ev_arg; /**< this struct will store a pointer to ei= ther mi or - * link_socket, depending on the event type= , to keep - * it accessible it's placed within the sam= e struct - * it points to. */ + struct event_arg ev_arg; /**< this struct will store a pointer to eit= her mi or + * link_socket, depending on the event type,= to keep + * it accessible it's placed within the same= struct + * it points to. */ struct gc_arena gc; bool halt; int refcount; - int route_count; /* number of routes (including cached route= s) owned by this instance */ - time_t created; /**< Time at which a VPN tunnel instance - * was created. This parameter is set - * by the \c multi_create_instance() - * function. */ - struct timeval wakeup; /* absolute time */ - struct mroute_addr real; /**< External network address of the - * remote peer. */ + int route_count; /* number of routes (including cached routes)= owned by this instance */ + time_t created; /**< Time at which a VPN tunnel instance + * was created. This parameter is set + * by the \c multi_create_instance() + * function. */ + struct timeval wakeup; /* absolute time */ + struct mroute_addr real; /**< External network address of the + * remote peer. */ ifconfig_pool_handle vaddr_handle; char msg_prefix[MULTI_PREFIX_MAX_LENGTH]; @@ -128,7 +129,7 @@ struct mbuf_set *tcp_link_out_deferred; bool socket_set_called; - in_addr_t reporting_addr; /* IP address shown in status listing */ + in_addr_t reporting_addr; /* IP address shown in status lis= ting */ struct in6_addr reporting_addr_ipv6; /* IPv6 address in status listing= */ bool did_real_hash; @@ -138,10 +139,10 @@ struct buffer_list *cc_config; #endif bool did_iroutes; - int n_clients_delta; /* added to multi_context.n_clients when instance= is closed */ + int n_clients_delta; /* added to multi_context.n_clients when insta= nce is closed */ - struct context context; /**< The context structure storing state - * for this VPN tunnel. */ + struct context context; /**< The context structure storing state + * for this VPN tunnel. */ struct client_connect_defer_state client_connect_defer_state; #ifdef ENABLE_ASYNC_PUSH int inotify_watch; /* watch descriptor for acf */ @@ -159,22 +160,23 @@ * page describes the role the structure plays when OpenVPN is running in * server-mode. */ -struct multi_context { - struct multi_instance **instances; /**< Array of multi_instances. An = instance can be - * accessed using peer-id as an in= dex. */ +struct multi_context +{ + struct multi_instance **instances; /**< Array of multi_instances. An i= nstance can be + * accessed using peer-id as an ind= ex. */ - struct hash *hash; /**< VPN tunnel instances indexed by real - * address of the remote peer. */ - struct hash *vhash; /**< VPN tunnel instances indexed by - * virtual address of remote hosts. */ - struct hash *iter; /**< VPN tunnel instances indexed by real - * address of the remote peer, optimized - * for iteration. */ + struct hash *hash; /**< VPN tunnel instances indexed b= y real + * address of the remote peer. */ + struct hash *vhash; /**< VPN tunnel instances indexed by + * virtual address of remote host= s. */ + struct hash *iter; /**< VPN tunnel instances indexed b= y real + * address of the remote peer, op= timized + * for iteration. */ struct schedule *schedule; - struct mbuf_set *mbuf; /**< Set of buffers for passing data - * channel packets between VPN tunnel - * instances. */ - struct multi_io *multi_io; /**< I/O state and events tracker */ + struct mbuf_set *mbuf; /**< Set of buffers for passing data + * channel packets between VPN tu= nnel + * instances. */ + struct multi_io *multi_io; /**< I/O state and events tracker */ struct ifconfig_pool *ifconfig_pool; struct frequency_limit *new_connection_limiter; struct initial_packet_rate_limit *initial_rate_limiter; @@ -198,8 +200,8 @@ struct context_buffers *context_buffers; time_t per_second_trigger; - struct context top; /**< Storage structure for process-wide - * configuration. */ + struct context top; /**< Storage structure for process-wide + * configuration. */ struct buffer hmac_reply; struct link_socket_actual *hmac_reply_dest; @@ -237,8 +239,8 @@ struct mroute_addr addr; struct multi_instance *instance; -#define MULTI_ROUTE_CACHE (1<<0) -#define MULTI_ROUTE_AGEABLE (1<<1) +#define MULTI_ROUTE_CACHE (1 << 0) +#define MULTI_ROUTE_AGEABLE (1 << 1) unsigned int flags; unsigned int cache_generation; @@ -262,17 +264,18 @@ * Called by mtcp.c, mudp.c, or other (to be written) protocol drivers */ -struct multi_instance *multi_create_instance(struct multi_context *m, cons= t struct mroute_addr *real, +struct multi_instance *multi_create_instance(struct multi_context *m, + const struct mroute_addr *rea= l, struct link_socket *sock); void multi_close_instance(struct multi_context *m, struct multi_instance *= mi, bool shutdown); bool multi_process_timeout(struct multi_context *m, const unsigned int mpp= _flags); -#define MPP_PRE_SELECT (1<<0) -#define MPP_CONDITIONAL_PRE_SELECT (1<<1) -#define MPP_CLOSE_ON_SIGNAL (1<<2) -#define MPP_RECORD_TOUCH (1<<3) +#define MPP_PRE_SELECT (1 << 0) +#define MPP_CONDITIONAL_PRE_SELECT (1 << 1) +#define MPP_CLOSE_ON_SIGNAL (1 << 2) +#define MPP_RECORD_TOUCH (1 << 3) /*************************************************************************= */ @@ -297,7 +300,8 @@ * signal during processing. * - False, if the VPN tunnel instance \a mi was closed. */ -bool multi_process_post(struct multi_context *m, struct multi_instance *mi= , const unsigned int flags); +bool multi_process_post(struct multi_context *m, struct multi_instance *mi, + const unsigned int flags); /** * Process an incoming DCO message (from kernel space). @@ -334,8 +338,8 @@ * @param mpp_flags - Fast I/O optimization flags. * @param sock - Socket where the packet was received. */ -bool multi_process_incoming_link(struct multi_context *m, struct multi_ins= tance *instance, const unsigned int mpp_flags, - struct link_socket *sock); +bool multi_process_incoming_link(struct multi_context *m, struct multi_ins= tance *instance, + const unsigned int mpp_flags, struct link= _socket *sock); /** @@ -360,9 +364,7 @@ struct multi_instance *multi_get_queue(struct mbuf_set *ms); -void multi_add_mbuf(struct multi_context *m, - struct multi_instance *mi, - struct mbuf_buffer *mb); +void multi_add_mbuf(struct multi_context *m, struct multi_instance *mi, st= ruct mbuf_buffer *mb); void multi_ifconfig_pool_persist(struct multi_context *m, bool force); @@ -388,8 +390,7 @@ * Return true if our output queue is not full */ static inline bool -multi_output_queue_ready(const struct multi_context *m, - const struct multi_instance *mi) +multi_output_queue_ready(const struct multi_context *m, const struct multi= _instance *mi) { if (mi->tcp_link_out_deferred) { @@ -485,8 +486,7 @@ } static inline bool -multi_route_defined(const struct multi_context *m, - const struct multi_route *r) +multi_route_defined(const struct multi_context *m, const struct multi_rout= e *r) { if (r->instance->halt) { @@ -511,8 +511,7 @@ /* * Takes prefix away from multi_instance. */ -void -ungenerate_prefix(struct multi_instance *mi); +void ungenerate_prefix(struct multi_instance *mi); /* * Set a msg() function prefix with our current client instance ID. @@ -548,10 +547,10 @@ * don't want to reap in a single pass. */ -#define REAP_MAX_WAKEUP 10 /* Do reap pass at least once per n seconds = */ -#define REAP_DIVISOR 256 /* How many passes to cover whole hash table= */ -#define REAP_MIN 16 /* Minimum number of buckets per pass */ -#define REAP_MAX 1024 /* Maximum number of buckets per pass */ +#define REAP_MAX_WAKEUP 10 /* Do reap pass at least once per n seconds */ +#define REAP_DIVISOR 256 /* How many passes to cover whole hash table = */ +#define REAP_MIN 16 /* Minimum number of buckets per pass */ +#define REAP_MAX 1024 /* Maximum number of buckets per pass */ /* * Mark a cached host route for deletion after this @@ -596,7 +595,7 @@ struct timeval tv, current; CLEAR(tv); - m->earliest_wakeup =3D (struct multi_instance *) schedule_get_earliest= _wakeup(m->schedule, &tv); + m->earliest_wakeup =3D (struct multi_instance *)schedule_get_earliest_= wakeup(m->schedule, &tv); if (m->earliest_wakeup) { ASSERT(!openvpn_gettimeofday(¤t, NULL)); @@ -641,9 +640,7 @@ ASSERT(mi); #ifdef MULTI_DEBUG_EVENT_LOOP - printf("%s -> TUN len=3D%d\n", - id(mi), - mi->context.c2.to_tun.len); + printf("%s -> TUN len=3D%d\n", id(mi), mi->context.c2.to_tun.len); #endif set_prefix(mi); vlan_process_outgoing_tun(m, mi); @@ -653,12 +650,13 @@ return ret; } -#define CLIENT_CONNECT_OPT_MASK (OPT_P_INSTANCE | OPT_P_INHERIT \ - |OPT_P_PUSH | OPT_P_TIMER | OPT_P_CONFIG = \ - |OPT_P_ECHO | OPT_P_COMP | OPT_P_SOCKFLAG= S) +#define CLIENT_CONNECT_OPT_MASK = \ + (OPT_P_INSTANCE | OPT_P_INHERIT | OPT_P_PUSH | OPT_P_TIMER | OPT_P_CON= FIG | OPT_P_ECHO \ + | OPT_P_COMP | OPT_P_SOCKFLAGS) static inline bool -multi_process_outgoing_link_dowork(struct multi_context *m, struct multi_i= nstance *mi, const unsigned int mpp_flags) +multi_process_outgoing_link_dowork(struct multi_context *m, struct multi_i= nstance *mi, + const unsigned int mpp_flags) { bool ret =3D true; set_prefix(mi); diff --git a/src/openvpn/multi_io.c b/src/openvpn/multi_io.c index 82f8372..ece789c 100644 --- a/src/openvpn/multi_io.c +++ b/src/openvpn/multi_io.c @@ -39,12 +39,12 @@ /* * Special tags passed to event.[ch] functions */ -#define MULTI_IO_SOCKET ((void *)1) -#define MULTI_IO_TUN ((void *)2) -#define MULTI_IO_SIG ((void *)3) /* Only on Windows */ -#define MULTI_IO_MANAGEMENT ((void *)4) +#define MULTI_IO_SOCKET ((void *)1) +#define MULTI_IO_TUN ((void *)2) +#define MULTI_IO_SIG ((void *)3) /* Only on Windows */ +#define MULTI_IO_MANAGEMENT ((void *)4) #define MULTI_IO_FILE_CLOSE_WRITE ((void *)5) -#define MULTI_IO_DCO ((void *)6) +#define MULTI_IO_DCO ((void *)6) =20 struct ta_iow_flags { @@ -127,7 +127,8 @@ wait_signal(multi_io->es, MULTI_IO_SIG); ALLOC_ARRAY(multi_io->esr, struct event_set_return, multi_io->maxevent= s); *maxclients =3D max_int(min_int(multi_io->maxevents - extra_events, *m= axclients), 1); - msg(D_MULTI_LOW, "MULTI IO: MULTI_IO INIT maxclients=3D%d maxevents=3D= %d", *maxclients, multi_io->maxevents); + msg(D_MULTI_LOW, "MULTI IO: MULTI_IO INIT maxclients=3D%d maxevents=3D= %d", *maxclients, + multi_io->maxevents); return multi_io; } @@ -142,18 +143,13 @@ mi->socket_set_called =3D true; if (proto_is_dgram(mi->context.c2.link_sockets[0]->info.proto)) { - socket_set(mi->context.c2.link_sockets[0], - m->multi_io->es, - EVENT_READ, - &mi->context.c2.link_sockets[0]->ev_arg, - NULL); + socket_set(mi->context.c2.link_sockets[0], m->multi_io->es, EVENT_= READ, + &mi->context.c2.link_sockets[0]->ev_arg, NULL); } else { - socket_set(mi->context.c2.link_sockets[0], - m->multi_io->es, - mbuf_defined(mi->tcp_link_out_deferred) ? EVENT_WRITE := EVENT_READ, - &mi->ev_arg, + socket_set(mi->context.c2.link_sockets[0], m->multi_io->es, + mbuf_defined(mi->tcp_link_out_deferred) ? EVENT_WRITE := EVENT_READ, &mi->ev_arg, &mi->tcp_rwflags); } } @@ -197,7 +193,8 @@ #ifdef ENABLE_MANAGEMENT if (management) { - management_socket_set(management, m->multi_io->es, MULTI_IO_MANAGE= MENT, &m->multi_io->management_persist_flags); + management_socket_set(management, m->multi_io->es, MULTI_IO_MANAGE= MENT, + &m->multi_io->management_persist_flags); } #endif @@ -206,7 +203,8 @@ event_ctl(m->multi_io->es, m->top.c2.inotify_fd, EVENT_READ, MULTI_IO_= FILE_CLOSE_WRITE); #endif - status =3D event_wait(m->multi_io->es, &m->top.c2.timeval, m->multi_io= ->esr, m->multi_io->maxevents); + status =3D + event_wait(m->multi_io->es, &m->top.c2.timeval, m->multi_io->esr, = m->multi_io->maxevents); update_time(); m->multi_io->n_esr =3D 0; if (status > 0) @@ -217,13 +215,13 @@ } static int -multi_io_wait_lite(struct multi_context *m, struct multi_instance *mi, con= st int action, bool *tun_input_pending) +multi_io_wait_lite(struct multi_context *m, struct multi_instance *mi, con= st int action, + bool *tun_input_pending) { struct context *c =3D multi_get_context(m, mi); unsigned int looking_for =3D 0; - dmsg(D_MULTI_DEBUG, "MULTI IO: multi_io_wait_lite a=3D%s mi=3D" ptr_fo= rmat, - pract(action), + dmsg(D_MULTI_DEBUG, "MULTI IO: multi_io_wait_lite a=3D%s mi=3D" ptr_fo= rmat, pract(action), (ptr_type)mi); tv_clear(&c->c2.timeval); /* ZERO-TIMEOUT */ @@ -254,7 +252,7 @@ case TA_SOCKET_WRITE: looking_for =3D SOCKET_WRITE; - io_wait(c, IOW_TO_LINK|IOW_READ_TUN_FORCE); + io_wait(c, IOW_TO_LINK | IOW_READ_TUN_FORCE); break; default: @@ -290,12 +288,11 @@ static struct multi_instance * multi_io_dispatch(struct multi_context *m, struct multi_instance *mi, cons= t int action) { - const unsigned int mpp_flags =3D MPP_PRE_SELECT|MPP_RECORD_TOUCH; + const unsigned int mpp_flags =3D MPP_PRE_SELECT | MPP_RECORD_TOUCH; struct multi_instance *touched =3D mi; m->mpp_touched =3D &touched; - dmsg(D_MULTI_DEBUG, "MULTI IO: multi_io_dispatch a=3D%s mi=3D" ptr_for= mat, - pract(action), + dmsg(D_MULTI_DEBUG, "MULTI IO: multi_io_dispatch a=3D%s mi=3D" ptr_for= mat, pract(action), (ptr_type)mi); switch (action) @@ -318,8 +315,7 @@ clear_prefix(); if (!IS_SIG(&mi->context)) { - multi_process_incoming_link(m, mi, mpp_flags, - mi->context.c2.link_sockets[0]= ); + multi_process_incoming_link(m, mi, mpp_flags, mi->context.= c2.link_sockets[0]); if (!IS_SIG(&mi->context)) { stream_buf_read_setup(mi->context.c2.link_sockets[0]); @@ -372,9 +368,9 @@ struct context *c =3D multi_get_context(m, mi); int newaction =3D TA_UNDEF; -#define MTP_NONE 0 -#define MTP_TUN_OUT (1<<0) -#define MTP_LINK_OUT (1<<1) +#define MTP_NONE 0 +#define MTP_TUN_OUT (1 << 0) +#define MTP_LINK_OUT (1 << 1) unsigned int flags =3D MTP_NONE; if (TUN_OUT(c)) @@ -388,7 +384,7 @@ switch (flags) { - case MTP_TUN_OUT|MTP_LINK_OUT: + case MTP_TUN_OUT | MTP_LINK_OUT: case MTP_TUN_OUT: newaction =3D TA_TUN_WRITE; break; @@ -412,16 +408,13 @@ { struct gc_arena gc =3D gc_new(); msg(M_FATAL, "MULTI IO: multi_io_post bad state, mi=3D%s flags= =3D%d", - multi_instance_string(mi, false, &gc), - flags); + multi_instance_string(mi, false, &gc), flags); gc_free(&gc); break; } } - dmsg(D_MULTI_DEBUG, "MULTI IO: multi_io_post %s -> %s", - pract(action), - pract(newaction)); + dmsg(D_MULTI_DEBUG, "MULTI IO: multi_io_post %s -> %s", pract(action),= pract(newaction)); return newaction; } @@ -500,47 +493,47 @@ } else #endif - /* incoming data on TUN? */ - if (e->arg =3D=3D MULTI_IO_TUN) - { - if (e->rwflags & EVENT_WRITE) + /* incoming data on TUN? */ + if (e->arg =3D=3D MULTI_IO_TUN) { - multi_io_action(m, NULL, TA_TUN_WRITE, false); + if (e->rwflags & EVENT_WRITE) + { + multi_io_action(m, NULL, TA_TUN_WRITE, false); + } + else if (e->rwflags & EVENT_READ) + { + multi_io_action(m, NULL, TA_TUN_READ, false); + } } - else if (e->rwflags & EVENT_READ) + /* new incoming TCP client attempting to connect? */ + else if (e->arg =3D=3D MULTI_IO_SOCKET) { - multi_io_action(m, NULL, TA_TUN_READ, false); + struct multi_instance *mi; + ASSERT(m->top.c2.link_sockets[0]); + socket_reset_listen_persistent(m->top.c2.link_sockets[= 0]); + mi =3D multi_create_instance_tcp(m, m->top.c2.link_soc= kets[0]); + if (mi) + { + multi_io_action(m, mi, TA_INITIAL, false); + } } - } - /* new incoming TCP client attempting to connect? */ - else if (e->arg =3D=3D MULTI_IO_SOCKET) - { - struct multi_instance *mi; - ASSERT(m->top.c2.link_sockets[0]); - socket_reset_listen_persistent(m->top.c2.link_sockets[0]); - mi =3D multi_create_instance_tcp(m, m->top.c2.link_sockets= [0]); - if (mi) - { - multi_io_action(m, mi, TA_INITIAL, false); - } - } #if defined(ENABLE_DCO) - /* incoming data on DCO? */ - else if (e->arg =3D=3D MULTI_IO_DCO) - { - multi_process_incoming_dco(m); - } + /* incoming data on DCO? */ + else if (e->arg =3D=3D MULTI_IO_DCO) + { + multi_process_incoming_dco(m); + } #endif - /* signal received? */ - else if (e->arg =3D=3D MULTI_IO_SIG) - { - get_signal(&m->top.sig->signal_received); - } + /* signal received? */ + else if (e->arg =3D=3D MULTI_IO_SIG) + { + get_signal(&m->top.sig->signal_received); + } #ifdef ENABLE_ASYNC_PUSH - else if (e->arg =3D=3D MULTI_IO_FILE_CLOSE_WRITE) - { - multi_process_file_closed(m, MPP_PRE_SELECT | MPP_RECORD_T= OUCH); - } + else if (e->arg =3D=3D MULTI_IO_FILE_CLOSE_WRITE) + { + multi_process_file_closed(m, MPP_PRE_SELECT | MPP_RECO= RD_TOUCH); + } #endif } if (IS_SIG(&m->top)) @@ -569,9 +562,7 @@ do { - dmsg(D_MULTI_DEBUG, "MULTI IO: multi_io_action a=3D%s p=3D%d", - pract(action), - poll); + dmsg(D_MULTI_DEBUG, "MULTI IO: multi_io_action a=3D%s p=3D%d", pra= ct(action), poll); /* * If TA_SOCKET_READ_RESIDUAL, it means we still have pending @@ -590,7 +581,8 @@ action =3D multi_io_wait_lite(m, mi, action, &tun_input_pendin= g); if (action =3D=3D TA_UNDEF) { - msg(M_FATAL, "MULTI IO: I/O wait required blocking in mult= i_io_action, action=3D%d", orig_action); + msg(M_FATAL, "MULTI IO: I/O wait required blocking in mult= i_io_action, action=3D%d", + orig_action); } } diff --git a/src/openvpn/networking.h b/src/openvpn/networking.h index eccd8d2..6c253f9 100644 --- a/src/openvpn/networking.h +++ b/src/openvpn/networking.h @@ -101,8 +101,8 @@ * * @return 0 on success, negative error code on error */ -int net_iface_new(openvpn_net_ctx_t *ctx, const openvpn_net_iface_t *iface, - const char *type, void *arg); +int net_iface_new(openvpn_net_ctx_t *ctx, const openvpn_net_iface_t *iface= , const char *type, + void *arg); /** * Retrieve the interface type @@ -113,8 +113,7 @@ * * @return 0 on success, a negative error code otherwise */ -int net_iface_type(openvpn_net_ctx_t *ctx, const char *iface, - char type[IFACE_TYPE_LEN_MAX]); +int net_iface_type(openvpn_net_ctx_t *ctx, const char *iface, char type[IF= ACE_TYPE_LEN_MAX]); /** * Remove an interface @@ -134,8 +133,7 @@ * * @return 0 on success, a negative error code otherwise */ -int net_iface_up(openvpn_net_ctx_t *ctx, const openvpn_net_iface_t *iface, - bool up); +int net_iface_up(openvpn_net_ctx_t *ctx, const openvpn_net_iface_t *iface,= bool up); /** * Set the MTU for an interface @@ -146,8 +144,7 @@ * * @return 0 on success, a negative error code otherwise */ -int net_iface_mtu_set(openvpn_net_ctx_t *ctx, - const openvpn_net_iface_t *iface, uint32_t mtu); +int net_iface_mtu_set(openvpn_net_ctx_t *ctx, const openvpn_net_iface_t *i= face, uint32_t mtu); /** * Set the Link Layer (Ethernet) address of the TAP interface @@ -158,8 +155,7 @@ * * @return 0 on success, a negative error code otherwise */ -int net_addr_ll_set(openvpn_net_ctx_t *ctx, const openvpn_net_iface_t *ifa= ce, - uint8_t *addr); +int net_addr_ll_set(openvpn_net_ctx_t *ctx, const openvpn_net_iface_t *ifa= ce, uint8_t *addr); /** * Add an IPv4 address to an interface @@ -171,8 +167,8 @@ * * @return 0 on success, a negative error code otherwise */ -int net_addr_v4_add(openvpn_net_ctx_t *ctx, const openvpn_net_iface_t *ifa= ce, - const in_addr_t *addr, int prefixlen); +int net_addr_v4_add(openvpn_net_ctx_t *ctx, const openvpn_net_iface_t *ifa= ce, const in_addr_t *addr, + int prefixlen); /** * Add an IPv6 address to an interface @@ -197,8 +193,8 @@ * * @return 0 on success, a negative error code otherwise */ -int net_addr_v4_del(openvpn_net_ctx_t *ctx, const openvpn_net_iface_t *ifa= ce, - const in_addr_t *addr, int prefixlen); +int net_addr_v4_del(openvpn_net_ctx_t *ctx, const openvpn_net_iface_t *ifa= ce, const in_addr_t *addr, + int prefixlen); /** * Remove an IPv6 from an interface @@ -222,8 +218,7 @@ * * @return 0 on success, a negative error code otherwise */ -int net_addr_ptp_v4_add(openvpn_net_ctx_t *ctx, - const openvpn_net_iface_t *iface, +int net_addr_ptp_v4_add(openvpn_net_ctx_t *ctx, const openvpn_net_iface_t = *iface, const in_addr_t *local, const in_addr_t *remote); /** @@ -236,8 +231,7 @@ * * @return 0 on success, a negative error code otherwise */ -int net_addr_ptp_v4_del(openvpn_net_ctx_t *ctx, - const openvpn_net_iface_t *iface, +int net_addr_ptp_v4_del(openvpn_net_ctx_t *ctx, const openvpn_net_iface_t = *iface, const in_addr_t *local, const in_addr_t *remote); #endif /* ENABLE_SITNL || ENABLE_IPROUTE */ @@ -257,9 +251,8 @@ * * @return 0 on success, a negative error code otherwise */ -int net_route_v4_add(openvpn_net_ctx_t *ctx, const in_addr_t *dst, - int prefixlen, const in_addr_t *gw, - const openvpn_net_iface_t *iface, uint32_t table, +int net_route_v4_add(openvpn_net_ctx_t *ctx, const in_addr_t *dst, int pre= fixlen, + const in_addr_t *gw, const openvpn_net_iface_t *iface= , uint32_t table, int metric); /** @@ -276,10 +269,9 @@ * * @return 0 on success, a negative error code otherwise */ -int net_route_v6_add(openvpn_net_ctx_t *ctx, const struct in6_addr *dst, - int prefixlen, const struct in6_addr *gw, - const openvpn_net_iface_t *iface, - uint32_t table, int metric); +int net_route_v6_add(openvpn_net_ctx_t *ctx, const struct in6_addr *dst, i= nt prefixlen, + const struct in6_addr *gw, const openvpn_net_iface_t = *iface, uint32_t table, + int metric); /** * Delete a route for an IPv4 address/network @@ -295,9 +287,8 @@ * * @return 0 on success, a negative error code otherwise */ -int net_route_v4_del(openvpn_net_ctx_t *ctx, const in_addr_t *dst, - int prefixlen, const in_addr_t *gw, - const openvpn_net_iface_t *iface, uint32_t table, +int net_route_v4_del(openvpn_net_ctx_t *ctx, const in_addr_t *dst, int pre= fixlen, + const in_addr_t *gw, const openvpn_net_iface_t *iface= , uint32_t table, int metric); /** @@ -314,10 +305,9 @@ * * @return 0 on success, a negative error code otherwise */ -int net_route_v6_del(openvpn_net_ctx_t *ctx, const struct in6_addr *dst, - int prefixlen, const struct in6_addr *gw, - const openvpn_net_iface_t *iface, - uint32_t table, int metric); +int net_route_v6_del(openvpn_net_ctx_t *ctx, const struct in6_addr *dst, i= nt prefixlen, + const struct in6_addr *gw, const openvpn_net_iface_t = *iface, uint32_t table, + int metric); #endif /* ENABLE_SITNL || ENABLE_IPROUTE || TARGET_FREEBSD */ @@ -334,8 +324,8 @@ * * @return 0 on success, a negative error code otherwise */ -int net_route_v4_best_gw(openvpn_net_ctx_t *ctx, const in_addr_t *dst, - in_addr_t *best_gw, openvpn_net_iface_t *best_ifa= ce); +int net_route_v4_best_gw(openvpn_net_ctx_t *ctx, const in_addr_t *dst, in_= addr_t *best_gw, + openvpn_net_iface_t *best_iface); /** * Retrieve the gateway and outgoing interface for the specified IPv6 @@ -349,8 +339,7 @@ * @return 0 on success, a negative error code otherwise */ int net_route_v6_best_gw(openvpn_net_ctx_t *ctx, const struct in6_addr *ds= t, - struct in6_addr *best_gw, - openvpn_net_iface_t *best_iface); + struct in6_addr *best_gw, openvpn_net_iface_t *be= st_iface); #endif /* ENABLE_SITNL || ENABLE_IPROUTE */ diff --git a/src/openvpn/networking_freebsd.c b/src/openvpn/networking_free= bsd.c index 1c94756..b47444c 100644 --- a/src/openvpn/networking_freebsd.c +++ b/src/openvpn/networking_freebsd.c @@ -9,9 +9,8 @@ #if defined(TARGET_FREEBSD) static int -net_route_v4(const char *op, const in_addr_t *dst, int prefixlen, - const in_addr_t *gw, const char *iface, uint32_t table, - int metric) +net_route_v4(const char *op, const in_addr_t *dst, int prefixlen, const in= _addr_t *gw, + const char *iface, uint32_t table, int metric) { char buf1[INET_ADDRSTRLEN], buf2[INET_ADDRSTRLEN]; in_addr_t _dst, _gw; @@ -21,16 +20,12 @@ _dst =3D ntohl(*dst); _gw =3D ntohl(*gw); - argv_printf(&argv, "%s %s -net %s/%d %s -fib %d", - ROUTE_PATH, op, - inet_ntop(AF_INET, &_dst, buf1, sizeof(buf1)), - prefixlen, - inet_ntop(AF_INET, &_gw, buf2, sizeof(buf2)), - table); + argv_printf(&argv, "%s %s -net %s/%d %s -fib %d", ROUTE_PATH, op, + inet_ntop(AF_INET, &_dst, buf1, sizeof(buf1)), prefixlen, + inet_ntop(AF_INET, &_gw, buf2, sizeof(buf2)), table); argv_msg(M_INFO, &argv); - status =3D openvpn_execve_check(&argv, NULL, 0, - "ERROR: FreeBSD route command failed"); + status =3D openvpn_execve_check(&argv, NULL, 0, "ERROR: FreeBSD route = command failed"); argv_free(&argv); @@ -38,24 +33,19 @@ } static int -net_route_v6(const char *op, const struct in6_addr *dst, - int prefixlen, const struct in6_addr *gw, const char *iface, - uint32_t table, int metric) +net_route_v6(const char *op, const struct in6_addr *dst, int prefixlen, co= nst struct in6_addr *gw, + const char *iface, uint32_t table, int metric) { char buf1[INET6_ADDRSTRLEN], buf2[INET6_ADDRSTRLEN]; struct argv argv =3D argv_new(); bool status; - argv_printf(&argv, "%s -6 %s -net %s/%d %s -fib %d", - ROUTE_PATH, op, - inet_ntop(AF_INET6, dst, buf1, sizeof(buf1)), - prefixlen, - inet_ntop(AF_INET6, gw, buf2, sizeof(buf2)), - table); + argv_printf(&argv, "%s -6 %s -net %s/%d %s -fib %d", ROUTE_PATH, op, + inet_ntop(AF_INET6, dst, buf1, sizeof(buf1)), prefixlen, + inet_ntop(AF_INET6, gw, buf2, sizeof(buf2)), table); argv_msg(M_INFO, &argv); - status =3D openvpn_execve_check(&argv, NULL, 0, - "ERROR: FreeBSD route command failed"); + status =3D openvpn_execve_check(&argv, NULL, 0, "ERROR: FreeBSD route = command failed"); argv_free(&argv); @@ -63,33 +53,29 @@ } int -net_route_v4_add(openvpn_net_ctx_t *ctx, const in_addr_t *dst, int prefixl= en, - const in_addr_t *gw, const char *iface, uint32_t table, - int metric) +net_route_v4_add(openvpn_net_ctx_t *ctx, const in_addr_t *dst, int prefixl= en, const in_addr_t *gw, + const char *iface, uint32_t table, int metric) { return net_route_v4("add", dst, prefixlen, gw, iface, table, metric); } int -net_route_v6_add(openvpn_net_ctx_t *ctx, const struct in6_addr *dst, - int prefixlen, const struct in6_addr *gw, const char *ifa= ce, - uint32_t table, int metric) +net_route_v6_add(openvpn_net_ctx_t *ctx, const struct in6_addr *dst, int p= refixlen, + const struct in6_addr *gw, const char *iface, uint32_t ta= ble, int metric) { return net_route_v6("add", dst, prefixlen, gw, iface, table, metric); } int -net_route_v4_del(openvpn_net_ctx_t *ctx, const in_addr_t *dst, int prefixl= en, - const in_addr_t *gw, const char *iface, uint32_t table, - int metric) +net_route_v4_del(openvpn_net_ctx_t *ctx, const in_addr_t *dst, int prefixl= en, const in_addr_t *gw, + const char *iface, uint32_t table, int metric) { return net_route_v4("del", dst, prefixlen, gw, iface, table, metric); } int -net_route_v6_del(openvpn_net_ctx_t *ctx, const struct in6_addr *dst, - int prefixlen, const struct in6_addr *gw, const char *ifa= ce, - uint32_t table, int metric) +net_route_v6_del(openvpn_net_ctx_t *ctx, const struct in6_addr *dst, int p= refixlen, + const struct in6_addr *gw, const char *iface, uint32_t ta= ble, int metric) { return net_route_v6("del", dst, prefixlen, gw, iface, table, metric); } diff --git a/src/openvpn/networking_iproute2.c b/src/openvpn/networking_ipr= oute2.c index ec8ab1e..0635b5d 100644 --- a/src/openvpn/networking_iproute2.c +++ b/src/openvpn/networking_iproute2.c @@ -61,8 +61,7 @@ } int -net_iface_new(openvpn_net_ctx_t *ctx, const char *iface, const char *type, - void *arg) +net_iface_new(openvpn_net_ctx_t *ctx, const char *iface, const char *type,= void *arg) { struct argv argv =3D argv_new(); @@ -76,8 +75,7 @@ } int -net_iface_type(openvpn_net_ctx_t *ctx, const char *iface, - char type[IFACE_TYPE_LEN_MAX]) +net_iface_type(openvpn_net_ctx_t *ctx, const char *iface, char type[IFACE_= TYPE_LEN_MAX]) { /* not supported by iproute2 */ msg(M_WARN, "%s: operation not supported by iproute2 backend", __func_= _); @@ -102,8 +100,7 @@ { struct argv argv =3D argv_new(); - argv_printf(&argv, "%s link set dev %s %s", iproute_path, iface, - up ? "up" : "down"); + argv_printf(&argv, "%s link set dev %s %s", iproute_path, iface, up ? = "up" : "down"); argv_msg(M_INFO, &argv); openvpn_execve_check(&argv, ctx->es, S_FATAL, "Linux ip link set faile= d"); @@ -117,8 +114,7 @@ { struct argv argv =3D argv_new(); - argv_printf(&argv, "%s link set dev %s up mtu %d", iproute_path, iface, - mtu); + argv_printf(&argv, "%s link set dev %s up mtu %d", iproute_path, iface= , mtu); argv_msg(M_INFO, &argv); openvpn_execve_check(&argv, ctx->es, S_FATAL, "Linux ip link set faile= d"); @@ -128,19 +124,16 @@ } int -net_addr_ll_set(openvpn_net_ctx_t *ctx, const openvpn_net_iface_t *iface, - uint8_t *addr) +net_addr_ll_set(openvpn_net_ctx_t *ctx, const openvpn_net_iface_t *iface, = uint8_t *addr) { struct argv argv =3D argv_new(); int ret =3D 0; - argv_printf(&argv, - "%s link set addr " MAC_FMT " dev %s", - iproute_path, MAC_PRINT_ARG(addr), iface); + argv_printf(&argv, "%s link set addr " MAC_FMT " dev %s", iproute_path= , MAC_PRINT_ARG(addr), + iface); argv_msg(M_INFO, &argv); - if (!openvpn_execve_check(&argv, ctx->es, 0, - "Linux ip link set addr failed")) + if (!openvpn_execve_check(&argv, ctx->es, 0, "Linux ip link set addr f= ailed")) { ret =3D -1; } @@ -151,15 +144,13 @@ } int -net_addr_v4_add(openvpn_net_ctx_t *ctx, const char *iface, - const in_addr_t *addr, int prefixlen) +net_addr_v4_add(openvpn_net_ctx_t *ctx, const char *iface, const in_addr_t= *addr, int prefixlen) { struct argv argv =3D argv_new(); const char *addr_str =3D print_in_addr_t(*addr, 0, &ctx->gc); - argv_printf(&argv, "%s addr add dev %s %s/%d", iproute_path, iface, - addr_str, prefixlen); + argv_printf(&argv, "%s addr add dev %s %s/%d", iproute_path, iface, ad= dr_str, prefixlen); argv_msg(M_INFO, &argv); openvpn_execve_check(&argv, ctx->es, S_FATAL, "Linux ip addr add faile= d"); @@ -169,17 +160,15 @@ } int -net_addr_v6_add(openvpn_net_ctx_t *ctx, const char *iface, - const struct in6_addr *addr, int prefixlen) +net_addr_v6_add(openvpn_net_ctx_t *ctx, const char *iface, const struct in= 6_addr *addr, + int prefixlen) { struct argv argv =3D argv_new(); char *addr_str =3D (char *)print_in6_addr(*addr, 0, &ctx->gc); - argv_printf(&argv, "%s -6 addr add %s/%d dev %s", iproute_path, addr_s= tr, - prefixlen, iface); + argv_printf(&argv, "%s -6 addr add %s/%d dev %s", iproute_path, addr_s= tr, prefixlen, iface); argv_msg(M_INFO, &argv); - openvpn_execve_check(&argv, ctx->es, S_FATAL, - "Linux ip -6 addr add failed"); + openvpn_execve_check(&argv, ctx->es, S_FATAL, "Linux ip -6 addr add fa= iled"); argv_free(&argv); @@ -187,14 +176,12 @@ } int -net_addr_v4_del(openvpn_net_ctx_t *ctx, const char *iface, - const in_addr_t *addr, int prefixlen) +net_addr_v4_del(openvpn_net_ctx_t *ctx, const char *iface, const in_addr_t= *addr, int prefixlen) { struct argv argv =3D argv_new(); const char *addr_str =3D print_in_addr_t(*addr, 0, &ctx->gc); - argv_printf(&argv, "%s addr del dev %s %s/%d", iproute_path, iface, - addr_str, prefixlen); + argv_printf(&argv, "%s addr del dev %s %s/%d", iproute_path, iface, ad= dr_str, prefixlen); argv_msg(M_INFO, &argv); openvpn_execve_check(&argv, ctx->es, 0, "Linux ip addr del failed"); @@ -205,14 +192,13 @@ } int -net_addr_v6_del(openvpn_net_ctx_t *ctx, const char *iface, - const struct in6_addr *addr, int prefixlen) +net_addr_v6_del(openvpn_net_ctx_t *ctx, const char *iface, const struct in= 6_addr *addr, + int prefixlen) { struct argv argv =3D argv_new(); char *addr_str =3D (char *)print_in6_addr(*addr, 0, &ctx->gc); - argv_printf(&argv, "%s -6 addr del %s/%d dev %s", iproute_path, - addr_str, prefixlen, iface); + argv_printf(&argv, "%s -6 addr del %s/%d dev %s", iproute_path, addr_s= tr, prefixlen, iface); argv_msg(M_INFO, &argv); openvpn_execve_check(&argv, ctx->es, 0, "Linux ip -6 addr del failed"); @@ -222,15 +208,15 @@ } int -net_addr_ptp_v4_add(openvpn_net_ctx_t *ctx, const char *iface, - const in_addr_t *local, const in_addr_t *remote) +net_addr_ptp_v4_add(openvpn_net_ctx_t *ctx, const char *iface, const in_ad= dr_t *local, + const in_addr_t *remote) { struct argv argv =3D argv_new(); const char *local_str =3D print_in_addr_t(*local, 0, &ctx->gc); const char *remote_str =3D print_in_addr_t(*remote, 0, &ctx->gc); - argv_printf(&argv, "%s addr add dev %s local %s peer %s", iproute_path, - iface, local_str, remote_str); + argv_printf(&argv, "%s addr add dev %s local %s peer %s", iproute_path= , iface, local_str, + remote_str); argv_msg(M_INFO, &argv); openvpn_execve_check(&argv, ctx->es, S_FATAL, "Linux ip addr add faile= d"); @@ -240,15 +226,15 @@ } int -net_addr_ptp_v4_del(openvpn_net_ctx_t *ctx, const char *iface, - const in_addr_t *local, const in_addr_t *remote) +net_addr_ptp_v4_del(openvpn_net_ctx_t *ctx, const char *iface, const in_ad= dr_t *local, + const in_addr_t *remote) { struct argv argv =3D argv_new(); const char *local_str =3D print_in_addr_t(*local, 0, &ctx->gc); const char *remote_str =3D print_in_addr_t(*remote, 0, &ctx->gc); - argv_printf(&argv, "%s addr del dev %s local %s peer %s", iproute_path, - iface, local_str, remote_str); + argv_printf(&argv, "%s addr del dev %s local %s peer %s", iproute_path= , iface, local_str, + remote_str); argv_msg(M_INFO, &argv); openvpn_execve_check(&argv, ctx->es, 0, "Linux ip addr del failed"); @@ -258,9 +244,8 @@ } int -net_route_v4_add(openvpn_net_ctx_t *ctx, const in_addr_t *dst, int prefixl= en, - const in_addr_t *gw, const char *iface, uint32_t table, - int metric) +net_route_v4_add(openvpn_net_ctx_t *ctx, const in_addr_t *dst, int prefixl= en, const in_addr_t *gw, + const char *iface, uint32_t table, int metric) { struct argv argv =3D argv_new(); const char *dst_str =3D print_in_addr_t(*dst, 0, &ctx->gc); @@ -297,16 +282,14 @@ } int -net_route_v6_add(openvpn_net_ctx_t *ctx, const struct in6_addr *dst, - int prefixlen, const struct in6_addr *gw, const char *ifa= ce, - uint32_t table, int metric) +net_route_v6_add(openvpn_net_ctx_t *ctx, const struct in6_addr *dst, int p= refixlen, + const struct in6_addr *gw, const char *iface, uint32_t ta= ble, int metric) { struct argv argv =3D argv_new(); char *dst_str =3D (char *)print_in6_addr(*dst, 0, &ctx->gc); int ret =3D 0; - argv_printf(&argv, "%s -6 route add %s/%d dev %s", iproute_path, dst_s= tr, - prefixlen, iface); + argv_printf(&argv, "%s -6 route add %s/%d dev %s", iproute_path, dst_s= tr, prefixlen, iface); if (gw) { @@ -332,9 +315,8 @@ } int -net_route_v4_del(openvpn_net_ctx_t *ctx, const in_addr_t *dst, int prefixl= en, - const in_addr_t *gw, const char *iface, uint32_t table, - int metric) +net_route_v4_del(openvpn_net_ctx_t *ctx, const in_addr_t *dst, int prefixl= en, const in_addr_t *gw, + const char *iface, uint32_t table, int metric) { struct argv argv =3D argv_new(); const char *dst_str =3D print_in_addr_t(*dst, 0, &ctx->gc); @@ -359,16 +341,14 @@ } int -net_route_v6_del(openvpn_net_ctx_t *ctx, const struct in6_addr *dst, - int prefixlen, const struct in6_addr *gw, const char *ifa= ce, - uint32_t table, int metric) +net_route_v6_del(openvpn_net_ctx_t *ctx, const struct in6_addr *dst, int p= refixlen, + const struct in6_addr *gw, const char *iface, uint32_t ta= ble, int metric) { struct argv argv =3D argv_new(); char *dst_str =3D (char *)print_in6_addr(*dst, 0, &ctx->gc); int ret =3D 0; - argv_printf(&argv, "%s -6 route del %s/%d dev %s", iproute_path, dst_s= tr, - prefixlen, iface); + argv_printf(&argv, "%s -6 route del %s/%d dev %s", iproute_path, dst_s= tr, prefixlen, iface); if (gw) { diff --git a/src/openvpn/networking_sitnl.c b/src/openvpn/networking_sitnl.c index 97e5749..4210e92 100644 --- a/src/openvpn/networking_sitnl.c +++ b/src/openvpn/networking_sitnl.c @@ -43,12 +43,12 @@ #define SNDBUF_SIZE (1024 * 2) #define RCVBUF_SIZE (1024 * 4) -#define SITNL_ADDATTR(_msg, _max_size, _attr, _data, _size) \ - { \ +#define SITNL_ADDATTR(_msg, _max_size, _attr, _data, _size) \ + { \ if (sitnl_addattr(_msg, _max_size, _attr, _data, _size) < 0) \ - { \ - goto err; \ - } \ + { \ + goto err; \ + } \ } #define SITNL_NEST(_msg, _max_size, _attr) \ @@ -58,8 +58,8 @@ _nest; \ }) -#define SITNL_NEST_END(_msg, _nest) \ - { \ +#define SITNL_NEST_END(_msg, _nest) \ + { \ _nest->rta_len =3D (void *)sitnl_nlmsg_tail(_msg) - (void *)_nest;= \ } @@ -73,7 +73,7 @@ * The only way out to avoid any warning/error is to force the function to * not be inline'd. */ -static __attribute__ ((noinline)) void * +static __attribute__((noinline)) void * sitnl_nlmsg_tail(const struct nlmsghdr *nlh) { return (unsigned char *)nlh + NLMSG_ALIGN(nlh->nlmsg_len); @@ -83,7 +83,8 @@ * Generic address data structure used to pass addresses and prefixes as * argument to AF family agnostic functions */ -typedef union { +typedef union +{ in_addr_t ipv4; struct in6_addr ipv6; } inet_address_t; @@ -91,7 +92,8 @@ /** * Link state request message */ -struct sitnl_link_req { +struct sitnl_link_req +{ struct nlmsghdr n; struct ifinfomsg i; char buf[256]; @@ -100,7 +102,8 @@ /** * Address request message */ -struct sitnl_addr_req { +struct sitnl_addr_req +{ struct nlmsghdr n; struct ifaddrmsg i; char buf[256]; @@ -109,7 +112,8 @@ /** * Route request message */ -struct sitnl_route_req { +struct sitnl_route_req +{ struct nlmsghdr n; struct rtmsg r; char buf[256]; @@ -120,7 +124,8 @@ /** * Object returned by route request operation */ -struct sitnl_route_data_cb { +struct sitnl_route_data_cb +{ unsigned int iface; inet_address_t gw; }; @@ -129,16 +134,14 @@ * Helper function used to easily add attributes to a rtnl message */ static int -sitnl_addattr(struct nlmsghdr *n, int maxlen, int type, const void *data, - int alen) +sitnl_addattr(struct nlmsghdr *n, int maxlen, int type, const void *data, = int alen) { int len =3D RTA_LENGTH(alen); struct rtattr *rta; if ((int)(NLMSG_ALIGN(n->nlmsg_len) + RTA_ALIGN(len)) > maxlen) { - msg(M_WARN, "%s: rtnl: message exceeded bound of %d", __func__, - maxlen); + msg(M_WARN, "%s: rtnl: message exceeded bound of %d", __func__, ma= xlen); return -EMSGSIZE; } @@ -240,8 +243,8 @@ * Send Netlink message and run callback on reply (if specified) */ static int -sitnl_send(struct nlmsghdr *payload, pid_t peer, unsigned int groups, - sitnl_parse_reply_cb cb, void *arg_cb) +sitnl_send(struct nlmsghdr *payload, pid_t peer, unsigned int groups, sitn= l_parse_reply_cb cb, + void *arg_cb) { int len, rem_len, fd, ret, rcv_len; struct sockaddr_nl nladdr; @@ -249,13 +252,11 @@ struct nlmsghdr *h; unsigned int seq; char buf[1024 * 16]; - struct iovec iov =3D - { + struct iovec iov =3D { .iov_base =3D payload, .iov_len =3D payload->nlmsg_len, }; - struct msghdr nlmsg =3D - { + struct msghdr nlmsg =3D { .msg_name =3D &nladdr, .msg_namelen =3D sizeof(nladdr), .msg_iov =3D &iov, @@ -334,8 +335,8 @@ if (nlmsg.msg_namelen !=3D sizeof(nladdr)) { - msg(M_WARN, "%s: sender address length: %u (expected %zu)", - __func__, nlmsg.msg_namelen, sizeof(nladdr)); + msg(M_WARN, "%s: sender address length: %u (expected %zu)", __= func__, nlmsg.msg_namelen, + sizeof(nladdr)); ret =3D -EIO; goto out; } @@ -359,17 +360,18 @@ goto out; } -/* if (((int)nladdr.nl_pid !=3D peer) || (h->nlmsg_pid !=3D nla= ddr.nl_pid) - * || (h->nlmsg_seq !=3D seq)) - * { - * rcv_len -=3D NLMSG_ALIGN(len); - * h =3D (struct nlmsghdr *)((char *)h + NLMSG_ALIGN(len)); - * msg(M_DEBUG, "%s: skipping unrelated message. nl_pid:%d (= peer:%d) nl_msg_pid:%d nl_seq:%d seq:%d", - * __func__, (int)nladdr.nl_pid, peer, h->nlmsg_pid, - * h->nlmsg_seq, seq); - * continue; - * } - */ + /* if (((int)nladdr.nl_pid !=3D peer) || (h->nlmsg_= pid !=3D nladdr.nl_pid) + * || (h->nlmsg_seq !=3D seq)) + * { + * rcv_len -=3D NLMSG_ALIGN(len); + * h =3D (struct nlmsghdr *)((char *)h + NLMSG_A= LIGN(len)); + * msg(M_DEBUG, "%s: skipping unrelated message.= nl_pid:%d (peer:%d) + * nl_msg_pid:%d nl_seq:%d seq:%d", + * __func__, (int)nladdr.nl_pid, peer, h->nl= msg_pid, + * h->nlmsg_seq, seq); + * continue; + * } + */ if (h->nlmsg_type =3D=3D NLMSG_DONE) { @@ -401,8 +403,8 @@ } else { - msg(M_WARN, "%s: rtnl: generic error (%d): %s", - __func__, err->error, strerror(-err->error)); + msg(M_WARN, "%s: rtnl: generic error (%d): %s", __= func__, err->error, + strerror(-err->error)); ret =3D err->error; } } @@ -446,7 +448,8 @@ return ret; } -typedef struct { +typedef struct +{ int addr_size; inet_address_t gw; char iface[IFNAMSIZ]; @@ -508,8 +511,7 @@ if (!if_indextoname(ifindex, res->iface)) { - msg(M_WARN | M_ERRNO, "%s: rtnl: can't get ifname for index %d", - __func__, ifindex); + msg(M_WARN | M_ERRNO, "%s: rtnl: can't get ifname for index %d", _= _func__, ifindex); return -1; } @@ -522,8 +524,8 @@ } static int -sitnl_route_best_gw(sa_family_t af_family, const inet_address_t *dst, - void *best_gw, char *best_iface) +sitnl_route_best_gw(sa_family_t af_family, const inet_address_t *dst, void= *best_gw, + char *best_iface) { struct sitnl_route_req req; route_res_t res; @@ -585,15 +587,14 @@ strncpy(best_iface, res.iface, IFNAMSIZ); err: return ret; - } /* used by iproute2 implementation too */ int -net_route_v6_best_gw(openvpn_net_ctx_t *ctx, const struct in6_addr *dst, - struct in6_addr *best_gw, char *best_iface) +net_route_v6_best_gw(openvpn_net_ctx_t *ctx, const struct in6_addr *dst, s= truct in6_addr *best_gw, + char *best_iface) { - inet_address_t dst_v6 =3D {0}; + inet_address_t dst_v6 =3D { 0 }; char buf[INET6_ADDRSTRLEN]; int ret; @@ -602,8 +603,7 @@ dst_v6.ipv6 =3D *dst; } - msg(D_ROUTE, "%s query: dst %s", __func__, - inet_ntop(AF_INET6, &dst_v6.ipv6, buf, sizeof(buf))); + msg(D_ROUTE, "%s query: dst %s", __func__, inet_ntop(AF_INET6, &dst_v6= .ipv6, buf, sizeof(buf))); ret =3D sitnl_route_best_gw(AF_INET6, &dst_v6, best_gw, best_iface); if (ret < 0) @@ -615,15 +615,14 @@ inet_ntop(AF_INET6, best_gw, buf, sizeof(buf)), best_iface); return ret; - } /* used by iproute2 implementation too */ int -net_route_v4_best_gw(openvpn_net_ctx_t *ctx, const in_addr_t *dst, - in_addr_t *best_gw, char *best_iface) +net_route_v4_best_gw(openvpn_net_ctx_t *ctx, const in_addr_t *dst, in_addr= _t *best_gw, + char *best_iface) { - inet_address_t dst_v4 =3D {0}; + inet_address_t dst_v4 =3D { 0 }; char buf[INET_ADDRSTRLEN]; int ret; @@ -632,8 +631,7 @@ dst_v4.ipv4 =3D htonl(*dst); } - msg(D_ROUTE, "%s query: dst %s", __func__, - inet_ntop(AF_INET, &dst_v4.ipv4, buf, sizeof(buf))); + msg(D_ROUTE, "%s query: dst %s", __func__, inet_ntop(AF_INET, &dst_v4.= ipv4, buf, sizeof(buf))); ret =3D sitnl_route_best_gw(AF_INET, &dst_v4, best_gw, best_iface); if (ret < 0) @@ -669,8 +667,7 @@ ifindex =3D if_nametoindex(iface); if (ifindex =3D=3D 0) { - msg(M_WARN, "%s: rtnl: cannot get ifindex for %s: %s", __func__, i= face, - strerror(errno)); + msg(M_WARN, "%s: rtnl: cannot get ifindex for %s: %s", __func__, i= face, strerror(errno)); return -ENOENT; } @@ -696,8 +693,7 @@ } int -net_iface_mtu_set(openvpn_net_ctx_t *ctx, const char *iface, - uint32_t mtu) +net_iface_mtu_set(openvpn_net_ctx_t *ctx, const char *iface, uint32_t mtu) { struct sitnl_link_req req; int ifindex, ret =3D -1; @@ -707,8 +703,7 @@ ifindex =3D if_nametoindex(iface); if (ifindex =3D=3D 0) { - msg(M_WARN | M_ERRNO, "%s: rtnl: cannot get ifindex for %s", __fun= c__, - iface); + msg(M_WARN | M_ERRNO, "%s: rtnl: cannot get ifindex for %s", __fun= c__, iface); return -1; } @@ -729,8 +724,7 @@ } int -net_addr_ll_set(openvpn_net_ctx_t *ctx, const openvpn_net_iface_t *iface, - uint8_t *addr) +net_addr_ll_set(openvpn_net_ctx_t *ctx, const openvpn_net_iface_t *iface, = uint8_t *addr) { struct sitnl_link_req req; int ifindex, ret =3D -1; @@ -740,8 +734,7 @@ ifindex =3D if_nametoindex(iface); if (ifindex =3D=3D 0) { - msg(M_WARN | M_ERRNO, "%s: rtnl: cannot get ifindex for %s", __fun= c__, - iface); + msg(M_WARN | M_ERRNO, "%s: rtnl: cannot get ifindex for %s", __fun= c__, iface); return -1; } @@ -754,8 +747,7 @@ SITNL_ADDATTR(&req.n, sizeof(req), IFLA_ADDRESS, addr, OPENVPN_ETH_ALE= N); - msg(M_INFO, "%s: lladdr " MAC_FMT " for %s", __func__, MAC_PRINT_ARG(a= ddr), - iface); + msg(M_INFO, "%s: lladdr " MAC_FMT " for %s", __func__, MAC_PRINT_ARG(a= ddr), iface); ret =3D sitnl_send(&req.n, 0, 0, NULL, NULL); err: @@ -764,8 +756,7 @@ static int sitnl_addr_set(int cmd, uint32_t flags, int ifindex, sa_family_t af_family, - const inet_address_t *local, const inet_address_t *remote, - int prefixlen) + const inet_address_t *local, const inet_address_t *remote, = int prefixlen) { struct sitnl_addr_req req; uint32_t size; @@ -791,8 +782,7 @@ break; default: - msg(M_WARN, "%s: rtnl: unknown address family %d", __func__, - af_family); + msg(M_WARN, "%s: rtnl: unknown address family %d", __func__, a= f_family); return -EINVAL; } @@ -823,8 +813,7 @@ } static int -sitnl_addr_ptp_add(sa_family_t af_family, const char *iface, - const inet_address_t *local, +sitnl_addr_ptp_add(sa_family_t af_family, const char *iface, const inet_ad= dress_t *local, const inet_address_t *remote) { int ifindex; @@ -848,18 +837,16 @@ ifindex =3D if_nametoindex(iface); if (ifindex =3D=3D 0) { - msg(M_WARN, "%s: cannot get ifindex for %s: %s", __func__, np(ifac= e), - strerror(errno)); + msg(M_WARN, "%s: cannot get ifindex for %s: %s", __func__, np(ifac= e), strerror(errno)); return -ENOENT; } - return sitnl_addr_set(RTM_NEWADDR, NLM_F_CREATE | NLM_F_REPLACE, ifind= ex, - af_family, local, remote, 0); + return sitnl_addr_set(RTM_NEWADDR, NLM_F_CREATE | NLM_F_REPLACE, ifind= ex, af_family, local, + remote, 0); } static int -sitnl_addr_ptp_del(sa_family_t af_family, const char *iface, - const inet_address_t *local) +sitnl_addr_ptp_del(sa_family_t af_family, const char *iface, const inet_ad= dress_t *local) { int ifindex; @@ -890,9 +877,8 @@ } static int -sitnl_route_set(int cmd, uint32_t flags, int ifindex, sa_family_t af_famil= y, - const void *dst, int prefixlen, - const void *gw, enum rt_class_t table, int metric, +sitnl_route_set(int cmd, uint32_t flags, int ifindex, sa_family_t af_famil= y, const void *dst, + int prefixlen, const void *gw, enum rt_class_t table, int = metric, enum rt_scope_t scope, int protocol, int type) { struct sitnl_route_req req; @@ -960,8 +946,7 @@ } static int -sitnl_addr_add(sa_family_t af_family, const char *iface, - const inet_address_t *addr, int prefixlen) +sitnl_addr_add(sa_family_t af_family, const char *iface, const inet_addres= s_t *addr, int prefixlen) { int ifindex; @@ -984,52 +969,47 @@ ifindex =3D if_nametoindex(iface); if (ifindex =3D=3D 0) { - msg(M_WARN | M_ERRNO, "%s: rtnl: cannot get ifindex for %s", __fun= c__, - iface); + msg(M_WARN | M_ERRNO, "%s: rtnl: cannot get ifindex for %s", __fun= c__, iface); return -ENOENT; } - return sitnl_addr_set(RTM_NEWADDR, NLM_F_CREATE | NLM_F_REPLACE, ifind= ex, - af_family, addr, NULL, prefixlen); -} - -static int -sitnl_addr_del(sa_family_t af_family, const char *iface, inet_address_t *a= ddr, - int prefixlen) -{ - int ifindex; - - switch (af_family) - { - case AF_INET: - case AF_INET6: - break; - - default: - return -EINVAL; - } - - if (!iface) - { - msg(M_WARN, "%s: passed NULL interface", __func__); - return -EINVAL; - } - - ifindex =3D if_nametoindex(iface); - if (ifindex =3D=3D 0) - { - msg(M_WARN | M_ERRNO, "%s: rtnl: cannot get ifindex for %s", __fun= c__, - iface); - return -ENOENT; - } - - return sitnl_addr_set(RTM_DELADDR, 0, ifindex, af_family, addr, NULL, + return sitnl_addr_set(RTM_NEWADDR, NLM_F_CREATE | NLM_F_REPLACE, ifind= ex, af_family, addr, NULL, prefixlen); } +static int +sitnl_addr_del(sa_family_t af_family, const char *iface, inet_address_t *a= ddr, int prefixlen) +{ + int ifindex; + + switch (af_family) + { + case AF_INET: + case AF_INET6: + break; + + default: + return -EINVAL; + } + + if (!iface) + { + msg(M_WARN, "%s: passed NULL interface", __func__); + return -EINVAL; + } + + ifindex =3D if_nametoindex(iface); + if (ifindex =3D=3D 0) + { + msg(M_WARN | M_ERRNO, "%s: rtnl: cannot get ifindex for %s", __fun= c__, iface); + return -ENOENT; + } + + return sitnl_addr_set(RTM_DELADDR, 0, ifindex, af_family, addr, NULL, = prefixlen); +} + int -net_addr_v4_add(openvpn_net_ctx_t *ctx, const char *iface, - const in_addr_t *addr, int prefixlen) +net_addr_v4_add(openvpn_net_ctx_t *ctx, const char *iface, const in_addr_t= *addr, int prefixlen) { inet_address_t addr_v4 =3D { 0 }; char buf[INET_ADDRSTRLEN]; @@ -1041,15 +1021,15 @@ addr_v4.ipv4 =3D htonl(*addr); - msg(M_INFO, "%s: %s/%d dev %s", __func__, - inet_ntop(AF_INET, &addr_v4.ipv4, buf, sizeof(buf)), prefixlen, if= ace); + msg(M_INFO, "%s: %s/%d dev %s", __func__, inet_ntop(AF_INET, &addr_v4.= ipv4, buf, sizeof(buf)), + prefixlen, iface); return sitnl_addr_add(AF_INET, iface, &addr_v4, prefixlen); } int -net_addr_v6_add(openvpn_net_ctx_t *ctx, const char *iface, - const struct in6_addr *addr, int prefixlen) +net_addr_v6_add(openvpn_net_ctx_t *ctx, const char *iface, const struct in= 6_addr *addr, + int prefixlen) { inet_address_t addr_v6 =3D { 0 }; char buf[INET6_ADDRSTRLEN]; @@ -1061,15 +1041,14 @@ addr_v6.ipv6 =3D *addr; - msg(M_INFO, "%s: %s/%d dev %s", __func__, - inet_ntop(AF_INET6, &addr_v6.ipv6, buf, sizeof(buf)), prefixlen, i= face); + msg(M_INFO, "%s: %s/%d dev %s", __func__, inet_ntop(AF_INET6, &addr_v6= .ipv6, buf, sizeof(buf)), + prefixlen, iface); return sitnl_addr_add(AF_INET6, iface, &addr_v6, prefixlen); } int -net_addr_v4_del(openvpn_net_ctx_t *ctx, const char *iface, - const in_addr_t *addr, int prefixlen) +net_addr_v4_del(openvpn_net_ctx_t *ctx, const char *iface, const in_addr_t= *addr, int prefixlen) { inet_address_t addr_v4 =3D { 0 }; char buf[INET_ADDRSTRLEN]; @@ -1081,15 +1060,15 @@ addr_v4.ipv4 =3D htonl(*addr); - msg(M_INFO, "%s: %s dev %s", __func__, - inet_ntop(AF_INET, &addr_v4.ipv4, buf, sizeof(buf)), iface); + msg(M_INFO, "%s: %s dev %s", __func__, inet_ntop(AF_INET, &addr_v4.ipv= 4, buf, sizeof(buf)), + iface); return sitnl_addr_del(AF_INET, iface, &addr_v4, prefixlen); } int -net_addr_v6_del(openvpn_net_ctx_t *ctx, const char *iface, - const struct in6_addr *addr, int prefixlen) +net_addr_v6_del(openvpn_net_ctx_t *ctx, const char *iface, const struct in= 6_addr *addr, + int prefixlen) { inet_address_t addr_v6 =3D { 0 }; char buf[INET6_ADDRSTRLEN]; @@ -1101,15 +1080,15 @@ addr_v6.ipv6 =3D *addr; - msg(M_INFO, "%s: %s/%d dev %s", __func__, - inet_ntop(AF_INET6, &addr_v6.ipv6, buf, sizeof(buf)), prefixlen, i= face); + msg(M_INFO, "%s: %s/%d dev %s", __func__, inet_ntop(AF_INET6, &addr_v6= .ipv6, buf, sizeof(buf)), + prefixlen, iface); return sitnl_addr_del(AF_INET6, iface, &addr_v6, prefixlen); } int -net_addr_ptp_v4_add(openvpn_net_ctx_t *ctx, const char *iface, - const in_addr_t *local, const in_addr_t *remote) +net_addr_ptp_v4_add(openvpn_net_ctx_t *ctx, const char *iface, const in_ad= dr_t *local, + const in_addr_t *remote) { inet_address_t local_v4 =3D { 0 }; inet_address_t remote_v4 =3D { 0 }; @@ -1136,8 +1115,8 @@ } int -net_addr_ptp_v4_del(openvpn_net_ctx_t *ctx, const char *iface, - const in_addr_t *local, const in_addr_t *remote) +net_addr_ptp_v4_del(openvpn_net_ctx_t *ctx, const char *iface, const in_ad= dr_t *local, + const in_addr_t *remote) { inet_address_t local_v4 =3D { 0 }; char buf[INET6_ADDRSTRLEN]; @@ -1150,15 +1129,15 @@ local_v4.ipv4 =3D htonl(*local); - msg(M_INFO, "%s: %s dev %s", __func__, - inet_ntop(AF_INET, &local_v4.ipv4, buf, sizeof(buf)), iface); + msg(M_INFO, "%s: %s dev %s", __func__, inet_ntop(AF_INET, &local_v4.ip= v4, buf, sizeof(buf)), + iface); return sitnl_addr_ptp_del(AF_INET, iface, &local_v4); } static int -sitnl_route_add(const char *iface, sa_family_t af_family, const void *dst, - int prefixlen, const void *gw, uint32_t table, int metric) +sitnl_route_add(const char *iface, sa_family_t af_family, const void *dst,= int prefixlen, + const void *gw, uint32_t table, int metric) { enum rt_scope_t scope =3D RT_SCOPE_UNIVERSE; int ifindex =3D 0; @@ -1168,8 +1147,7 @@ ifindex =3D if_nametoindex(iface); if (ifindex =3D=3D 0) { - msg(M_WARN | M_ERRNO, "%s: rtnl: can't get ifindex for %s", - __func__, iface); + msg(M_WARN | M_ERRNO, "%s: rtnl: can't get ifindex for %s", __= func__, iface); return -ENOENT; } } @@ -1184,15 +1162,13 @@ scope =3D RT_SCOPE_LINK; } - return sitnl_route_set(RTM_NEWROUTE, NLM_F_CREATE, ifindex, - af_family, dst, prefixlen, gw, table, metric, s= cope, - RTPROT_BOOT, RTN_UNICAST); + return sitnl_route_set(RTM_NEWROUTE, NLM_F_CREATE, ifindex, af_family,= dst, prefixlen, gw, + table, metric, scope, RTPROT_BOOT, RTN_UNICAST); } int -net_route_v4_add(openvpn_net_ctx_t *ctx, const in_addr_t *dst, int prefixl= en, - const in_addr_t *gw, const char *iface, - uint32_t table, int metric) +net_route_v4_add(openvpn_net_ctx_t *ctx, const in_addr_t *dst, int prefixl= en, const in_addr_t *gw, + const char *iface, uint32_t table, int metric) { in_addr_t *dst_ptr =3D NULL, *gw_ptr =3D NULL; in_addr_t dst_be =3D 0, gw_be =3D 0; @@ -1212,18 +1188,15 @@ } msg(D_ROUTE, "%s: %s/%d via %s dev %s table %d metric %d", __func__, - inet_ntop(AF_INET, &dst_be, dst_str, sizeof(dst_str)), - prefixlen, inet_ntop(AF_INET, &gw_be, gw_str, sizeof(gw_str)), - np(iface), table, metric); + inet_ntop(AF_INET, &dst_be, dst_str, sizeof(dst_str)), prefixlen, + inet_ntop(AF_INET, &gw_be, gw_str, sizeof(gw_str)), np(iface), tab= le, metric); - return sitnl_route_add(iface, AF_INET, dst_ptr, prefixlen, gw_ptr, tab= le, - metric); + return sitnl_route_add(iface, AF_INET, dst_ptr, prefixlen, gw_ptr, tab= le, metric); } int -net_route_v6_add(openvpn_net_ctx_t *ctx, const struct in6_addr *dst, - int prefixlen, const struct in6_addr *gw, - const char *iface, uint32_t table, int metric) +net_route_v6_add(openvpn_net_ctx_t *ctx, const struct in6_addr *dst, int p= refixlen, + const struct in6_addr *gw, const char *iface, uint32_t ta= ble, int metric) { inet_address_t dst_v6 =3D { 0 }; inet_address_t gw_v6 =3D { 0 }; @@ -1241,18 +1214,15 @@ } msg(D_ROUTE, "%s: %s/%d via %s dev %s table %d metric %d", __func__, - inet_ntop(AF_INET6, &dst_v6.ipv6, dst_str, sizeof(dst_str)), - prefixlen, inet_ntop(AF_INET6, &gw_v6.ipv6, gw_str, sizeof(gw_str)= ), - np(iface), table, metric); + inet_ntop(AF_INET6, &dst_v6.ipv6, dst_str, sizeof(dst_str)), prefi= xlen, + inet_ntop(AF_INET6, &gw_v6.ipv6, gw_str, sizeof(gw_str)), np(iface= ), table, metric); - return sitnl_route_add(iface, AF_INET6, dst, prefixlen, gw, table, - metric); + return sitnl_route_add(iface, AF_INET6, dst, prefixlen, gw, table, met= ric); } static int -sitnl_route_del(const char *iface, sa_family_t af_family, inet_address_t *= dst, - int prefixlen, inet_address_t *gw, uint32_t table, - int metric) +sitnl_route_del(const char *iface, sa_family_t af_family, inet_address_t *= dst, int prefixlen, + inet_address_t *gw, uint32_t table, int metric) { int ifindex =3D 0; @@ -1261,8 +1231,7 @@ ifindex =3D if_nametoindex(iface); if (ifindex =3D=3D 0) { - msg(M_WARN | M_ERRNO, "%s: rtnl: can't get ifindex for %s", - __func__, iface); + msg(M_WARN | M_ERRNO, "%s: rtnl: can't get ifindex for %s", __= func__, iface); return -ENOENT; } } @@ -1272,14 +1241,13 @@ table =3D RT_TABLE_MAIN; } - return sitnl_route_set(RTM_DELROUTE, 0, ifindex, af_family, dst, prefi= xlen, - gw, table, metric, RT_SCOPE_NOWHERE, 0, 0); + return sitnl_route_set(RTM_DELROUTE, 0, ifindex, af_family, dst, prefi= xlen, gw, table, metric, + RT_SCOPE_NOWHERE, 0, 0); } int -net_route_v4_del(openvpn_net_ctx_t *ctx, const in_addr_t *dst, int prefixl= en, - const in_addr_t *gw, const char *iface, uint32_t table, - int metric) +net_route_v4_del(openvpn_net_ctx_t *ctx, const in_addr_t *dst, int prefixl= en, const in_addr_t *gw, + const char *iface, uint32_t table, int metric) { inet_address_t dst_v4 =3D { 0 }; inet_address_t gw_v4 =3D { 0 }; @@ -1297,18 +1265,15 @@ } msg(D_ROUTE, "%s: %s/%d via %s dev %s table %d metric %d", __func__, - inet_ntop(AF_INET, &dst_v4.ipv4, dst_str, sizeof(dst_str)), - prefixlen, inet_ntop(AF_INET, &gw_v4.ipv4, gw_str, sizeof(gw_str)), - np(iface), table, metric); + inet_ntop(AF_INET, &dst_v4.ipv4, dst_str, sizeof(dst_str)), prefix= len, + inet_ntop(AF_INET, &gw_v4.ipv4, gw_str, sizeof(gw_str)), np(iface)= , table, metric); - return sitnl_route_del(iface, AF_INET, &dst_v4, prefixlen, &gw_v4, tab= le, - metric); + return sitnl_route_del(iface, AF_INET, &dst_v4, prefixlen, &gw_v4, tab= le, metric); } int -net_route_v6_del(openvpn_net_ctx_t *ctx, const struct in6_addr *dst, - int prefixlen, const struct in6_addr *gw, - const char *iface, uint32_t table, int metric) +net_route_v6_del(openvpn_net_ctx_t *ctx, const struct in6_addr *dst, int p= refixlen, + const struct in6_addr *gw, const char *iface, uint32_t ta= ble, int metric) { inet_address_t dst_v6 =3D { 0 }; inet_address_t gw_v6 =3D { 0 }; @@ -1326,20 +1291,17 @@ } msg(D_ROUTE, "%s: %s/%d via %s dev %s table %d metric %d", __func__, - inet_ntop(AF_INET6, &dst_v6.ipv6, dst_str, sizeof(dst_str)), - prefixlen, inet_ntop(AF_INET6, &gw_v6.ipv6, gw_str, sizeof(gw_str)= ), - np(iface), table, metric); + inet_ntop(AF_INET6, &dst_v6.ipv6, dst_str, sizeof(dst_str)), prefi= xlen, + inet_ntop(AF_INET6, &gw_v6.ipv6, gw_str, sizeof(gw_str)), np(iface= ), table, metric); - return sitnl_route_del(iface, AF_INET6, &dst_v6, prefixlen, &gw_v6, - table, metric); + return sitnl_route_del(iface, AF_INET6, &dst_v6, prefixlen, &gw_v6, ta= ble, metric); } int -net_iface_new(openvpn_net_ctx_t *ctx, const char *iface, const char *type, - void *arg) +net_iface_new(openvpn_net_ctx_t *ctx, const char *iface, const char *type,= void *arg) { - struct sitnl_link_req req =3D { }; + struct sitnl_link_req req =3D {}; int ret =3D -1; ASSERT(iface); @@ -1357,8 +1319,7 @@ { dco_context_t *dco =3D arg; struct rtattr *data =3D SITNL_NEST(&req.n, sizeof(req), IFLA_INFO_= DATA); - SITNL_ADDATTR(&req.n, sizeof(req), IFLA_OVPN_MODE, &dco->ifmode, - sizeof(uint8_t)); + SITNL_ADDATTR(&req.n, sizeof(req), IFLA_OVPN_MODE, &dco->ifmode, s= izeof(uint8_t)); SITNL_NEST_END(&req.n, data); } #endif @@ -1366,7 +1327,7 @@ req.i.ifi_family =3D AF_PACKET; - msg(D_ROUTE, "%s: add %s type %s", __func__, iface, type); + msg(D_ROUTE, "%s: add %s type %s", __func__, iface, type); ret =3D sitnl_send(&req.n, 0, 0, NULL, NULL); err: @@ -1374,8 +1335,8 @@ } static int -sitnl_parse_rtattr_flags(struct rtattr *tb[], int max, struct rtattr *rta, - int len, unsigned short flags) +sitnl_parse_rtattr_flags(struct rtattr *tb[], int max, struct rtattr *rta,= int len, + unsigned short flags) { unsigned short type; @@ -1395,8 +1356,7 @@ if (len) { - msg(D_ROUTE, "%s: %d bytes not parsed! (rta_len=3D%d)", __func__, = len, - rta->rta_len); + msg(D_ROUTE, "%s: %d bytes not parsed! (rta_len=3D%d)", __func__, = len, rta->rta_len); } return 0; @@ -1409,8 +1369,7 @@ } #define sitnl_parse_rtattr_nested(tb, max, rta) \ - (sitnl_parse_rtattr_flags(tb, max, RTA_DATA(rta), RTA_PAYLOAD(rta), \ - NLA_F_NESTED)) + (sitnl_parse_rtattr_flags(tb, max, RTA_DATA(rta), RTA_PAYLOAD(rta), NL= A_F_NESTED)) static int sitnl_type_save(struct nlmsghdr *n, void *arg) @@ -1430,8 +1389,7 @@ { struct rtattr *tb_link[IFLA_INFO_MAX + 1]; - ret =3D sitnl_parse_rtattr_nested(tb_link, IFLA_INFO_MAX, - tb[IFLA_LINKINFO]); + ret =3D sitnl_parse_rtattr_nested(tb_link, IFLA_INFO_MAX, tb[IFLA_= LINKINFO]); if (ret < 0) { return ret; @@ -1449,10 +1407,9 @@ } int -net_iface_type(openvpn_net_ctx_t *ctx, const char *iface, - char type[IFACE_TYPE_LEN_MAX]) +net_iface_type(openvpn_net_ctx_t *ctx, const char *iface, char type[IFACE_= TYPE_LEN_MAX]) { - struct sitnl_link_req req =3D { }; + struct sitnl_link_req req =3D {}; int ifindex =3D if_nametoindex(iface); if (!ifindex) @@ -1472,8 +1429,7 @@ int ret =3D sitnl_send(&req.n, 0, 0, sitnl_type_save, type); if (ret < 0) { - msg(D_ROUTE, "%s: cannot retrieve iface %s: %s (%d)", __func__, if= ace, - strerror(-ret), ret); + msg(D_ROUTE, "%s: cannot retrieve iface %s: %s (%d)", __func__, if= ace, strerror(-ret), ret); return ret; } @@ -1485,7 +1441,7 @@ int net_iface_del(openvpn_net_ctx_t *ctx, const char *iface) { - struct sitnl_link_req req =3D { }; + struct sitnl_link_req req =3D {}; int ifindex =3D if_nametoindex(iface); if (!ifindex) diff --git a/src/openvpn/ntlm.c b/src/openvpn/ntlm.c index 94e5d95..dc5c93f 100644 --- a/src/openvpn/ntlm.c +++ b/src/openvpn/ntlm.c @@ -44,15 +44,14 @@ #ifdef _MSC_VER /* MS compilers */ #define UINTEGER64 __int64 -#define UINT64(c) c ## Ui64 +#define UINT64(c) c##Ui64 #else /* Non MS compilers */ #define UINTEGER64 unsigned long long -#define UINT64(c) c ## LL +#define UINT64(c) c##LL #endif - static void gen_md4_hash(const uint8_t *data, int data_len, uint8_t *result) { @@ -64,8 +63,7 @@ } static void -gen_hmac_md5(const uint8_t *data, int data_len, const uint8_t *key, - uint8_t *result) +gen_hmac_md5(const uint8_t *data, int data_len, const uint8_t *key, uint8_= t *result) { hmac_ctx_t *hmac_ctx =3D hmac_ctx_new(); @@ -91,13 +89,13 @@ /* store little endian value */ timestamp[0] =3D timestamp_ull & UINT64(0xFF); - timestamp[1] =3D (timestamp_ull >> 8) & UINT64(0xFF); - timestamp[2] =3D (timestamp_ull >> 16) & UINT64(0xFF); - timestamp[3] =3D (timestamp_ull >> 24) & UINT64(0xFF); - timestamp[4] =3D (timestamp_ull >> 32) & UINT64(0xFF); - timestamp[5] =3D (timestamp_ull >> 40) & UINT64(0xFF); - timestamp[6] =3D (timestamp_ull >> 48) & UINT64(0xFF); - timestamp[7] =3D (timestamp_ull >> 56) & UINT64(0xFF); + timestamp[1] =3D (timestamp_ull >> 8) & UINT64(0xFF); + timestamp[2] =3D (timestamp_ull >> 16) & UINT64(0xFF); + timestamp[3] =3D (timestamp_ull >> 24) & UINT64(0xFF); + timestamp[4] =3D (timestamp_ull >> 32) & UINT64(0xFF); + timestamp[5] =3D (timestamp_ull >> 40) & UINT64(0xFF); + timestamp[6] =3D (timestamp_ull >> 48) & UINT64(0xFF); + timestamp[7] =3D (timestamp_ull >> 56) & UINT64(0xFF); } static void @@ -106,7 +104,7 @@ /* Generates 8 random bytes to be used as client nonce */ int i; - for (i =3D 0; i<8; i++) + for (i =3D 0; i < 8; i++) { nonce[i] =3D (unsigned char)get_random(); } @@ -152,8 +150,8 @@ } static void -add_security_buffer(int sb_offset, void *data, int length, - unsigned char *msg_buf, int *msg_bufpos, size_t msg_bu= fsize) +add_security_buffer(int sb_offset, void *data, int length, unsigned char *= msg_buf, int *msg_bufpos, + size_t msg_bufsize) { if (*msg_bufpos + length > msg_bufsize) { @@ -188,8 +186,7 @@ } const char * -ntlm_phase_3(const struct http_proxy_info *p, const char *phase_2, - struct gc_arena *gc) +ntlm_phase_3(const struct http_proxy_info *p, const char *phase_2, struct = gc_arena *gc) { /* NTLM handshake * @@ -205,13 +202,13 @@ int i, ret_val; uint8_t ntlmv2_response[256]; - char userdomain_u[256]; /* for uppercase unicode username and doma= in */ - char userdomain[128]; /* the same as previous but ascii */ + char userdomain_u[256]; /* for uppercase unicode username and domain */ + char userdomain[128]; /* the same as previous but ascii */ uint8_t ntlmv2_hash[MD5_DIGEST_LENGTH]; uint8_t ntlmv2_hmacmd5[16]; - uint8_t *ntlmv2_blob =3D ntlmv2_response + 16; /* inside ntlmv2_re= sponse, length: 128 */ + uint8_t *ntlmv2_blob =3D ntlmv2_response + 16; /* inside ntlmv2_respon= se, length: 128 */ int ntlmv2_blob_size =3D 0; - int phase3_bufpos =3D 0x40; /* offset to next security buffer data= to be added */ + int phase3_bufpos =3D 0x40; /* offset to next security buffer data to = be added */ size_t len; char domain[128]; @@ -225,20 +222,20 @@ separator =3D strchr(p->up.username, '\\'); if (separator =3D=3D NULL) { - strncpy(username, p->up.username, sizeof(username)-1); - username[sizeof(username)-1] =3D 0; + strncpy(username, p->up.username, sizeof(username) - 1); + username[sizeof(username) - 1] =3D 0; domain[0] =3D 0; } else { - strncpy(username, separator+1, sizeof(username)-1); - username[sizeof(username)-1] =3D 0; + strncpy(username, separator + 1, sizeof(username) - 1); + username[sizeof(username) - 1] =3D 0; len =3D separator - p->up.username; if (len > sizeof(domain) - 1) { len =3D sizeof(domain) - 1; } - strncpy(domain, p->up.username, len); + strncpy(domain, p->up.username, len); domain[len] =3D 0; } @@ -264,9 +261,9 @@ } /* extract the challenge from bytes 24-31 */ - for (i =3D 0; i<8; i++) + for (i =3D 0; i < 8; i++) { - challenge[i] =3D buf2[i+24]; + challenge[i] =3D buf2[i + 24]; } /* Generate NTLMv2 response */ @@ -284,17 +281,16 @@ msg(M_INFO, "NTLM: Username or domain too long"); } unicodize(userdomain_u, userdomain); - gen_hmac_md5((uint8_t *)userdomain_u, 2 * strlen(userdomain), md4_hash, - ntlmv2_hash); + gen_hmac_md5((uint8_t *)userdomain_u, 2 * strlen(userdomain), md4_hash= , ntlmv2_hash); /* NTLMv2 Blob */ - memset(ntlmv2_blob, 0, 128); /* Clear blob buff= er */ - ntlmv2_blob[0x00] =3D 1; /* Signature */ - ntlmv2_blob[0x01] =3D 1; /* Signature */ - ntlmv2_blob[0x04] =3D 0; /* Reserved */ - gen_timestamp(&ntlmv2_blob[0x08]); /* 64-bit Timestam= p */ - gen_nonce(&ntlmv2_blob[0x10]); /* 64-bit Client N= once */ - ntlmv2_blob[0x18] =3D 0; /* Unknown, zero= should work */ + memset(ntlmv2_blob, 0, 128); /* Clear blob buffer */ + ntlmv2_blob[0x00] =3D 1; /* Signature */ + ntlmv2_blob[0x01] =3D 1; /* Signature */ + ntlmv2_blob[0x04] =3D 0; /* Reserved */ + gen_timestamp(&ntlmv2_blob[0x08]); /* 64-bit Timestamp */ + gen_nonce(&ntlmv2_blob[0x10]); /* 64-bit Client Nonce */ + ntlmv2_blob[0x18] =3D 0; /* Unknown, zero should work */ /* Add target information block to the blob */ @@ -311,11 +307,11 @@ * byte order on the wire for the NTLM header is LE. */ const size_t hoff =3D 0x14; - unsigned long flags =3D buf2[hoff] | (buf2[hoff + 1] << 8) - |(buf2[hoff + 2] << 16) | (buf2[hoff + 3] << 24); + unsigned long flags =3D + buf2[hoff] | (buf2[hoff + 1] << 8) | (buf2[hoff + 2] << 16) | (buf= 2[hoff + 3] << 24); if ((flags & 0x00800000) =3D=3D 0x00800000) { - tib_len =3D buf2[0x28]; /* Get Target Information block= size */ + tib_len =3D buf2[0x28]; /* Get Target Information block size */ if (tib_len + 0x1c + 16 > sizeof(ntlmv2_response)) { msg(M_WARN, "NTLM: target information buffer too long for resp= onse (len=3D%d)", tib_len); @@ -327,7 +323,9 @@ uint8_t tib_pos =3D buf2[0x2c]; if (tib_pos + tib_len > sizeof(buf2)) { - msg(M_ERR, "NTLM: phase 2 response from server too long (n= eed %d bytes at offset %u)", tib_len, tib_pos); + msg(M_ERR, + "NTLM: phase 2 response from server too long (need %d = bytes at offset %u)", + tib_len, tib_pos); return NULL; } /* Get Target Information block pointer */ @@ -351,41 +349,38 @@ memcpy(&ntlmv2_response[8], challenge, 8); /* hmac-md5 */ - gen_hmac_md5(&ntlmv2_response[8], ntlmv2_blob_size + 8, ntlmv2_hash, - ntlmv2_hmacmd5); + gen_hmac_md5(&ntlmv2_response[8], ntlmv2_blob_size + 8, ntlmv2_hash, n= tlmv2_hmacmd5); /* Add hmac-md5 result to the blob. * Note: This overwrites challenge previously written at * ntlmv2_response[8..15] */ memcpy(ntlmv2_response, ntlmv2_hmacmd5, MD5_DIGEST_LENGTH); - memset(phase3, 0, sizeof(phase3)); /* clear reply */ + memset(phase3, 0, sizeof(phase3)); /* clear reply */ - strcpy((char *)phase3, "NTLMSSP\0"); /* signature */ - phase3[8] =3D 3; /* type 3 */ + strcpy((char *)phase3, "NTLMSSP\0"); /* signature */ + phase3[8] =3D 3; /* type 3 */ /* NTLMv2 response */ - add_security_buffer(0x14, ntlmv2_response, ntlmv2_blob_size + 16, - phase3, &phase3_bufpos, sizeof(phase3)); + add_security_buffer(0x14, ntlmv2_response, ntlmv2_blob_size + 16, phas= e3, &phase3_bufpos, + sizeof(phase3)); /* username in ascii */ - add_security_buffer(0x24, username, strlen(username), phase3, - &phase3_bufpos, sizeof(phase3)); + add_security_buffer(0x24, username, strlen(username), phase3, &phase3_= bufpos, sizeof(phase3)); /* Set domain. If is empty, default domain will be used * (i.e. proxy's domain) */ add_security_buffer(0x1c, domain, strlen(domain), phase3, &phase3_bufp= os, sizeof(phase3)); /* other security buffers will be empty */ - phase3[0x10] =3D phase3_bufpos; /* lm not used */ - phase3[0x30] =3D phase3_bufpos; /* no workstation name supplied */ - phase3[0x38] =3D phase3_bufpos; /* no session key */ + phase3[0x10] =3D phase3_bufpos; /* lm not used */ + phase3[0x30] =3D phase3_bufpos; /* no workstation name supplied */ + phase3[0x38] =3D phase3_bufpos; /* no session key */ /* flags */ phase3[0x3c] =3D 0x02; /* negotiate oem */ phase3[0x3d] =3D 0x02; /* negotiate ntlm */ - return ((const char *)make_base64_string2((unsigned char *)phase3, - phase3_bufpos, gc)); + return ((const char *)make_base64_string2((unsigned char *)phase3, pha= se3_bufpos, gc)); } #endif /* if NTLM */ diff --git a/src/openvpn/occ.c b/src/openvpn/occ.c index 00b2fa4..8821a06 100644 --- a/src/openvpn/occ.c +++ b/src/openvpn/occ.c @@ -51,95 +51,93 @@ * OCC_STRING_SIZE must be set to sizeof (occ_magic) */ -const uint8_t occ_magic[] =3D { - 0x28, 0x7f, 0x34, 0x6b, 0xd4, 0xef, 0x7a, 0x81, - 0x2d, 0x56, 0xb8, 0xd3, 0xaf, 0xc5, 0x45, 0x9c -}; +const uint8_t occ_magic[] =3D { 0x28, 0x7f, 0x34, 0x6b, 0xd4, 0xef, 0x7a, = 0x81, + 0x2d, 0x56, 0xb8, 0xd3, 0xaf, 0xc5, 0x45, 0x= 9c }; static const struct mtu_load_test mtu_load_test_sequence[] =3D { - {OCC_MTU_LOAD_REQUEST, -1000}, - {OCC_MTU_LOAD, -1000}, - {OCC_MTU_LOAD_REQUEST, -1000}, - {OCC_MTU_LOAD, -1000}, - {OCC_MTU_LOAD_REQUEST, -1000}, - {OCC_MTU_LOAD, -1000}, + { OCC_MTU_LOAD_REQUEST, -1000 }, + { OCC_MTU_LOAD, -1000 }, + { OCC_MTU_LOAD_REQUEST, -1000 }, + { OCC_MTU_LOAD, -1000 }, + { OCC_MTU_LOAD_REQUEST, -1000 }, + { OCC_MTU_LOAD, -1000 }, - {OCC_MTU_LOAD_REQUEST, -750}, - {OCC_MTU_LOAD, -750}, - {OCC_MTU_LOAD_REQUEST, -750}, - {OCC_MTU_LOAD, -750}, - {OCC_MTU_LOAD_REQUEST, -750}, - {OCC_MTU_LOAD, -750}, + { OCC_MTU_LOAD_REQUEST, -750 }, + { OCC_MTU_LOAD, -750 }, + { OCC_MTU_LOAD_REQUEST, -750 }, + { OCC_MTU_LOAD, -750 }, + { OCC_MTU_LOAD_REQUEST, -750 }, + { OCC_MTU_LOAD, -750 }, - {OCC_MTU_LOAD_REQUEST, -500}, - {OCC_MTU_LOAD, -500}, - {OCC_MTU_LOAD_REQUEST, -500}, - {OCC_MTU_LOAD, -500}, - {OCC_MTU_LOAD_REQUEST, -500}, - {OCC_MTU_LOAD, -500}, + { OCC_MTU_LOAD_REQUEST, -500 }, + { OCC_MTU_LOAD, -500 }, + { OCC_MTU_LOAD_REQUEST, -500 }, + { OCC_MTU_LOAD, -500 }, + { OCC_MTU_LOAD_REQUEST, -500 }, + { OCC_MTU_LOAD, -500 }, - {OCC_MTU_LOAD_REQUEST, -400}, - {OCC_MTU_LOAD, -400}, - {OCC_MTU_LOAD_REQUEST, -400}, - {OCC_MTU_LOAD, -400}, - {OCC_MTU_LOAD_REQUEST, -400}, - {OCC_MTU_LOAD, -400}, + { OCC_MTU_LOAD_REQUEST, -400 }, + { OCC_MTU_LOAD, -400 }, + { OCC_MTU_LOAD_REQUEST, -400 }, + { OCC_MTU_LOAD, -400 }, + { OCC_MTU_LOAD_REQUEST, -400 }, + { OCC_MTU_LOAD, -400 }, - {OCC_MTU_LOAD_REQUEST, -300}, - {OCC_MTU_LOAD, -300}, - {OCC_MTU_LOAD_REQUEST, -300}, - {OCC_MTU_LOAD, -300}, - {OCC_MTU_LOAD_REQUEST, -300}, - {OCC_MTU_LOAD, -300}, + { OCC_MTU_LOAD_REQUEST, -300 }, + { OCC_MTU_LOAD, -300 }, + { OCC_MTU_LOAD_REQUEST, -300 }, + { OCC_MTU_LOAD, -300 }, + { OCC_MTU_LOAD_REQUEST, -300 }, + { OCC_MTU_LOAD, -300 }, - {OCC_MTU_LOAD_REQUEST, -200}, - {OCC_MTU_LOAD, -200}, - {OCC_MTU_LOAD_REQUEST, -200}, - {OCC_MTU_LOAD, -200}, - {OCC_MTU_LOAD_REQUEST, -200}, - {OCC_MTU_LOAD, -200}, + { OCC_MTU_LOAD_REQUEST, -200 }, + { OCC_MTU_LOAD, -200 }, + { OCC_MTU_LOAD_REQUEST, -200 }, + { OCC_MTU_LOAD, -200 }, + { OCC_MTU_LOAD_REQUEST, -200 }, + { OCC_MTU_LOAD, -200 }, - {OCC_MTU_LOAD_REQUEST, -150}, - {OCC_MTU_LOAD, -150}, - {OCC_MTU_LOAD_REQUEST, -150}, - {OCC_MTU_LOAD, -150}, - {OCC_MTU_LOAD_REQUEST, -150}, - {OCC_MTU_LOAD, -150}, + { OCC_MTU_LOAD_REQUEST, -150 }, + { OCC_MTU_LOAD, -150 }, + { OCC_MTU_LOAD_REQUEST, -150 }, + { OCC_MTU_LOAD, -150 }, + { OCC_MTU_LOAD_REQUEST, -150 }, + { OCC_MTU_LOAD, -150 }, - {OCC_MTU_LOAD_REQUEST, -100}, - {OCC_MTU_LOAD, -100}, - {OCC_MTU_LOAD_REQUEST, -100}, - {OCC_MTU_LOAD, -100}, - {OCC_MTU_LOAD_REQUEST, -100}, - {OCC_MTU_LOAD, -100}, + { OCC_MTU_LOAD_REQUEST, -100 }, + { OCC_MTU_LOAD, -100 }, + { OCC_MTU_LOAD_REQUEST, -100 }, + { OCC_MTU_LOAD, -100 }, + { OCC_MTU_LOAD_REQUEST, -100 }, + { OCC_MTU_LOAD, -100 }, - {OCC_MTU_LOAD_REQUEST, -50}, - {OCC_MTU_LOAD, -50}, - {OCC_MTU_LOAD_REQUEST, -50}, - {OCC_MTU_LOAD, -50}, - {OCC_MTU_LOAD_REQUEST, -50}, - {OCC_MTU_LOAD, -50}, + { OCC_MTU_LOAD_REQUEST, -50 }, + { OCC_MTU_LOAD, -50 }, + { OCC_MTU_LOAD_REQUEST, -50 }, + { OCC_MTU_LOAD, -50 }, + { OCC_MTU_LOAD_REQUEST, -50 }, + { OCC_MTU_LOAD, -50 }, - {OCC_MTU_LOAD_REQUEST, 0}, - {OCC_MTU_LOAD, 0}, - {OCC_MTU_LOAD_REQUEST, 0}, - {OCC_MTU_LOAD, 0}, - {OCC_MTU_LOAD_REQUEST, 0}, - {OCC_MTU_LOAD, 0}, + { OCC_MTU_LOAD_REQUEST, 0 }, + { OCC_MTU_LOAD, 0 }, + { OCC_MTU_LOAD_REQUEST, 0 }, + { OCC_MTU_LOAD, 0 }, + { OCC_MTU_LOAD_REQUEST, 0 }, + { OCC_MTU_LOAD, 0 }, - {OCC_MTU_REQUEST, 0}, - {OCC_MTU_REQUEST, 0}, - {OCC_MTU_REQUEST, 0}, - {OCC_MTU_REQUEST, 0}, - {OCC_MTU_REQUEST, 0}, - {OCC_MTU_REQUEST, 0}, - {OCC_MTU_REQUEST, 0}, - {OCC_MTU_REQUEST, 0}, - {OCC_MTU_REQUEST, 0}, - {OCC_MTU_REQUEST, 0}, + { OCC_MTU_REQUEST, 0 }, + { OCC_MTU_REQUEST, 0 }, + { OCC_MTU_REQUEST, 0 }, + { OCC_MTU_REQUEST, 0 }, + { OCC_MTU_REQUEST, 0 }, + { OCC_MTU_REQUEST, 0 }, + { OCC_MTU_REQUEST, 0 }, + { OCC_MTU_REQUEST, 0 }, + { OCC_MTU_REQUEST, 0 }, + { OCC_MTU_REQUEST, 0 }, - {-1, 0} + { -1, 0 } }; void @@ -155,15 +153,12 @@ */ msg(D_SHOW_OCC, "NOTE: failed to obtain options consistency info from peer= -- " - "this could occur if the remote peer is running a version = of " - PACKAGE_NAME - " before 1.5-beta8 or if there is a network connectivity p= roblem, and will not necessarily prevent " - PACKAGE_NAME + "this could occur if the remote peer is running a version = of " PACKAGE_NAME + " before 1.5-beta8 or if there is a network connectivity p= roblem, and will not necessarily prevent " PACKAGE_NAME " from running (" counter_format " bytes received from pee= r, " counter_format " bytes authenticated data channel traffic) -- you can dis= able the options consistency " "check with --disable-occ.", - c->c2.link_read_bytes, - c->c2.link_read_bytes_auth); + c->c2.link_read_bytes, c->c2.link_read_bytes_auth); } event_timeout_clear(&c->c2.occ_interval); } @@ -196,16 +191,17 @@ if (entry->op >=3D 0) { c->c2.occ_op =3D entry->op; - size_t payload_size =3D frame_calculate_payload_size(&c->c2.fr= ame, - &c->options= , &c->c1.ks.key_type); - size_t header_size =3D frame_calculate_protocol_header_size(&c= ->c1.ks.key_type, &c->options, false); + size_t payload_size =3D + frame_calculate_payload_size(&c->c2.frame, &c->options, &c= ->c1.ks.key_type); + size_t header_size =3D + frame_calculate_protocol_header_size(&c->c1.ks.key_type, &= c->options, false); c->c2.occ_mtu_load_size =3D payload_size + header_size; } else { - msg(M_INFO, - "NOTE: failed to empirically measure MTU (requires " PACKA= GE_NAME " 1.5 or higher at other end of connection)."); + msg(M_INFO, "NOTE: failed to empirically measure MTU (requires= " PACKAGE_NAME + " 1.5 or higher at other end of connection)."); event_timeout_clear(&c->c2.occ_mtu_load_test_interval); c->c2.occ_mtu_load_n_tries =3D 0; } @@ -308,10 +304,8 @@ proto_hdr =3D frame_calculate_protocol_header_size(kt, &c->opt= ions, false); need_to_add =3D min_int(c->c2.occ_mtu_load_size, c->c2.frame.b= uf.payload_size) - - OCC_STRING_SIZE - - sizeof(uint8_t) /* occ opcode */ - - payload_hdr - - proto_hdr; + - OCC_STRING_SIZE - sizeof(uint8_t) /* occ opcod= e */ + - payload_hdr - proto_hdr; while (need_to_add > 0) { @@ -325,13 +319,8 @@ --need_to_add; } dmsg(D_PACKET_CONTENT, "SENT OCC_MTU_LOAD min_int(%d,%d)-%d-%d= -%d-%d) size=3D%d", - c->c2.occ_mtu_load_size, - c->c2.frame.buf.payload_size, - OCC_STRING_SIZE, - (int) sizeof(uint8_t), - (int) payload_hdr, - (int) proto_hdr, - BLEN(&c->c2.buf)); + c->c2.occ_mtu_load_size, c->c2.frame.buf.payload_size, OC= C_STRING_SIZE, + (int)sizeof(uint8_t), (int)payload_hdr, (int)proto_hdr, B= LEN(&c->c2.buf)); doit =3D true; } break; @@ -387,12 +376,10 @@ dmsg(D_PACKET_CONTENT, "RECEIVED OCC_REPLY"); if (c->options.occ && !TLS_MODE(c) && c->c2.options_string_rem= ote) { - if (!options_cmp_equal_safe((char *) BPTR(&c->c2.buf), - c->c2.options_string_remote, + if (!options_cmp_equal_safe((char *)BPTR(&c->c2.buf), c->c= 2.options_string_remote, c->c2.buf.len)) { - options_warning_safe((char *) BPTR(&c->c2.buf), - c->c2.options_string_remote, + options_warning_safe((char *)BPTR(&c->c2.buf), c->c2.o= ptions_string_remote, c->c2.buf.len); } } @@ -403,22 +390,20 @@ dmsg(D_PACKET_CONTENT, "RECEIVED OCC_MTU_REPLY"); c->c2.max_recv_size_remote =3D buf_read_u16(&c->c2.buf); c->c2.max_send_size_remote =3D buf_read_u16(&c->c2.buf); - if (c->options.mtu_test - && c->c2.max_recv_size_remote > 0 + if (c->options.mtu_test && c->c2.max_recv_size_remote > 0 && c->c2.max_send_size_remote > 0) { - msg(M_INFO, "NOTE: Empirical MTU test completed [Tried,Act= ual] local->remote=3D[%d,%d] remote->local=3D[%d,%d]", - c->c2.max_send_size_local, - c->c2.max_recv_size_remote, - c->c2.max_send_size_remote, - c->c2.max_recv_size_local); - if (!c->options.ce.fragment - && (proto_is_dgram(c->options.ce.proto)) + msg(M_INFO, + "NOTE: Empirical MTU test completed [Tried,Actual] loc= al->remote=3D[%d,%d] remote->local=3D[%d,%d]", + c->c2.max_send_size_local, c->c2.max_recv_size_remote, + c->c2.max_send_size_remote, c->c2.max_recv_size_local); + if (!c->options.ce.fragment && (proto_is_dgram(c->options.= ce.proto)) && c->c2.max_send_size_local > TUN_MTU_MIN && (c->c2.max_recv_size_remote < c->c2.max_send_size_l= ocal || c->c2.max_recv_size_local < c->c2.max_send_size= _remote)) { - msg(M_INFO, "NOTE: This connection is unable to accomm= odate a UDP packet size of %d. Consider using --fragment or --mssfix option= s as a workaround.", + msg(M_INFO, + "NOTE: This connection is unable to accommodate a = UDP packet size of %d. Consider using --fragment or --mssfix options as a w= orkaround.", c->c2.max_send_size_local); } } diff --git a/src/openvpn/occ.h b/src/openvpn/occ.h index d5f208e..369d94e 100644 --- a/src/openvpn/occ.h +++ b/src/openvpn/occ.h @@ -32,8 +32,8 @@ * OCC (OpenVPN Configuration Control) protocol opcodes. */ -#define OCC_REQUEST 0 /* request options string from peer */ -#define OCC_REPLY 1 /* deliver options string to peer */ +#define OCC_REQUEST 0 /* request options string from peer */ +#define OCC_REPLY 1 /* deliver options string to peer */ /* * Send an OCC_REQUEST once every OCC_INTERVAL @@ -48,11 +48,12 @@ /* * Other OCC protocol opcodes used to estimate the MTU empirically. */ -#define OCC_MTU_LOAD_REQUEST 2 /* Ask peer to send a big packet t= o us */ -#define OCC_MTU_LOAD 3 /* Send a big packet to peer */ -#define OCC_MTU_REQUEST 4 /* Ask peer to tell us the largest - * packet it has received from us = so far */ -#define OCC_MTU_REPLY 5 /* Send largest packet size to pee= r */ +#define OCC_MTU_LOAD_REQUEST 2 /* Ask peer to send a big packet to us */ +#define OCC_MTU_LOAD 3 /* Send a big packet to peer */ +#define OCC_MTU_REQUEST \ + 4 /* Ask peer to tell us the largest \ + * packet it has received from us so far */ +#define OCC_MTU_REPLY 5 /* Send largest packet size to peer */ /* * Process one command from mtu_load_test_sequence @@ -63,7 +64,7 @@ /* * Send an exit message to remote. */ -#define OCC_EXIT 6 +#define OCC_EXIT 6 /* * Used to conduct a load test command sequence @@ -71,10 +72,10 @@ */ struct mtu_load_test { - int op; /* OCC opcode to send to peer */ - int delta; /* determine packet size to send by using - * this delta against currently - * configured MTU */ + int op; /* OCC opcode to send to peer */ + int delta; /* determine packet size to send by using + * this delta against currently + * configured MTU */ }; extern const uint8_t occ_magic[]; @@ -110,8 +111,7 @@ check_send_occ_req(struct context *c) { if (event_timeout_defined(&c->c2.occ_interval) - && event_timeout_trigger(&c->c2.occ_interval, - &c->c2.timeval, + && event_timeout_trigger(&c->c2.occ_interval, &c->c2.timeval, (!TO_LINK_DEF(c) && c->c2.occ_op < 0) ? E= TT_DEFAULT : 0)) { check_send_occ_req_dowork(c); @@ -125,8 +125,7 @@ check_send_occ_load_test(struct context *c) { if (event_timeout_defined(&c->c2.occ_mtu_load_test_interval) - && event_timeout_trigger(&c->c2.occ_mtu_load_test_interval, - &c->c2.timeval, + && event_timeout_trigger(&c->c2.occ_mtu_load_test_interval, &c->c2= .timeval, (!TO_LINK_DEF(c) && c->c2.occ_op < 0) ? E= TT_DEFAULT : 0)) { check_send_occ_load_test_dowork(c); diff --git a/src/openvpn/openssl_compat.h b/src/openvpn/openssl_compat.h index 20f612e..143a3cf 100644 --- a/src/openvpn/openssl_compat.h +++ b/src/openvpn/openssl_compat.h @@ -67,15 +67,16 @@ } } -#define EVP_CTRL_AEAD_SET_TAG EVP_CTRL_GCM_SET_TAG -#define EVP_CTRL_AEAD_GET_TAG EVP_CTRL_GCM_GET_TAG +#define EVP_CTRL_AEAD_SET_TAG EVP_CTRL_GCM_SET_TAG +#define EVP_CTRL_AEAD_GET_TAG EVP_CTRL_GCM_GET_TAG #endif #if defined(LIBRESSL_VERSION_NUMBER) -#define RSA_F_RSA_OSSL_PRIVATE_ENCRYPT RSA_F_RSA_EAY_PRIVATE_ENCRYPT +#define RSA_F_RSA_OSSL_PRIVATE_ENCRYPT RSA_F_RSA_EAY_PRIVATE_ENCRYPT #endif -#if defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER < 0x305040= 0fL || defined(OPENSSL_IS_AWSLC) +#if defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER < 0x305040= 0fL \ + || defined(OPENSSL_IS_AWSLC) #define SSL_get_peer_tmp_key SSL_get_server_tmp_key #endif @@ -85,10 +86,8 @@ /* Note that this is not a perfect emulation of the new function but * is good enough for our case of printing certificate details during * handshake */ -static inline -int -EVP_PKEY_get_group_name(EVP_PKEY *pkey, char *gname, size_t gname_sz, - size_t *gname_len) +static inline int +EVP_PKEY_get_group_name(EVP_PKEY *pkey, char *gname, size_t gname_sz, size= _t *gname_len) { const EC_KEY *ec =3D EVP_PKEY_get0_EC_KEY(pkey); if (ec =3D=3D NULL) @@ -117,13 +116,12 @@ #endif /* if OPENSSL_VERSION_NUMBER < 0x30000000L && !defined(OPENSSL_NO_E= C) */ #if OPENSSL_VERSION_NUMBER < 0x30000000L -#define EVP_MD_get0_name EVP_MD_name -#define EVP_CIPHER_get0_name EVP_CIPHER_name +#define EVP_MD_get0_name EVP_MD_name +#define EVP_CIPHER_get0_name EVP_CIPHER_name #define EVP_CIPHER_CTX_get_mode EVP_CIPHER_CTX_mode /** Reduce SSL_CTX_new_ex() to SSL_CTX_new() for OpenSSL < 3 */ -#define SSL_CTX_new_ex(libctx, propq, method) \ - SSL_CTX_new((method)) +#define SSL_CTX_new_ex(libctx, propq, method) SSL_CTX_new((method)) /* Some safe typedefs to avoid too many ifdefs */ typedef void OSSL_LIB_CTX; @@ -160,9 +158,7 @@ } static inline unsigned long -ERR_get_error_all(const char **file, int *line, - const char **func, - const char **data, int *flags) +ERR_get_error_all(const char **file, int *line, const char **func, const c= har **data, int *flags) { static const char *empty =3D ""; *func =3D empty; @@ -172,13 +168,13 @@ #endif /* OPENSSL_VERSION_NUMBER < 0x30000000L */ -#if OPENSSL_VERSION_NUMBER < 0x30500000 && (!defined(LIBRESSL_VERSION_NUMB= ER) || LIBRESSL_VERSION_NUMBER > 0x3050400fL) +#if OPENSSL_VERSION_NUMBER < 0x30500000 \ + && (!defined(LIBRESSL_VERSION_NUMBER) || LIBRESSL_VERSION_NUMBER > 0x3= 050400fL) static inline int SSL_get0_peer_signature_name(SSL *ssl, const char **sigalg) { int peer_sig_nid; - if (SSL_get_peer_signature_nid(ssl, &peer_sig_nid) - && peer_sig_nid !=3D NID_undef) + if (SSL_get_peer_signature_nid(ssl, &peer_sig_nid) && peer_sig_nid != =3D NID_undef) { *sigalg =3D OBJ_nid2sn(peer_sig_nid); return 1; @@ -194,7 +190,8 @@ *sigalg =3D NULL; return 0; } -#endif /* if OPENSSL_VERSION_NUMBER < 0x30500000 && (!defined(LIBRESSL_VER= SION_NUMBER) || LIBRESSL_VERSION_NUMBER > 0x3050400fL) */ +#endif /* if OPENSSL_VERSION_NUMBER < 0x30500000 && (!defined(LIBRESSL_VER= SION_NUMBER) || \ + LIBRESSL_VERSION_NUMBER > 0x3050400fL) */ #if OPENSSL_VERSION_NUMBER < 0x30200000L && OPENSSL_VERSION_NUMBER >=3D 0x= 30000000L static inline const char * diff --git a/src/openvpn/openvpn.c b/src/openvpn/openvpn.c index 99c420a..f1e1f76 100644 --- a/src/openvpn/openvpn.c +++ b/src/openvpn/openvpn.c @@ -119,8 +119,7 @@ * printing depends on it */ for (int j =3D 1; j < MAX_PARMS && c->options.providers.names[j]; j++) { - c->options.providers.providers[j] =3D - crypto_load_provider(c->options.providers.names[j]); + c->options.providers.providers[j] =3D crypto_load_provider(c->opti= ons.providers.names[j]); } } @@ -129,8 +128,7 @@ { for (int j =3D 1; j < MAX_PARMS && c->options.providers.providers[j]; = j++) { - crypto_unload_provider(c->options.providers.names[j], - c->options.providers.providers[j]); + crypto_unload_provider(c->options.providers.names[j], c->options.p= roviders.providers[j]); } net_ctx_free(&c->net_ctx); } @@ -156,14 +154,15 @@ * @param argc - Commandline argument count. * @param argv - Commandline argument values. */ -static -int +static int openvpn_main(int argc, char *argv[]) { struct context c; #if PEDANTIC - fprintf(stderr, "Sorry, I was built with --enable-pedantic and I am in= capable of doing any real work!\n"); + fprintf( + stderr, + "Sorry, I was built with --enable-pedantic and I am incapable of d= oing any real work!\n"); return 1; #endif @@ -332,15 +331,13 @@ /* pass restart status to management subsystem */ signal_restart_status(c.sig); - } - while (signal_reset(c.sig, SIGUSR1) =3D=3D SIGUSR1); + } while (signal_reset(c.sig, SIGUSR1) =3D=3D SIGUSR1); env_set_destroy(c.es); uninit_options(&c.options); gc_reset(&c.gc); uninit_early(&c); - } - while (signal_reset(c.sig, SIGHUP) =3D=3D SIGHUP); + } while (signal_reset(c.sig, SIGHUP) =3D=3D SIGHUP); } context_gc_free(&c); @@ -365,7 +362,7 @@ int ret; int i; - if ((argv =3D calloc(argc+1, sizeof(char *))) =3D=3D NULL) + if ((argv =3D calloc(argc + 1, sizeof(char *))) =3D=3D NULL) { return 1; } diff --git a/src/openvpn/openvpn.h b/src/openvpn/openvpn.h index 004cbc7..cd99cd4 100644 --- a/src/openvpn/openvpn.h +++ b/src/openvpn/openvpn.h @@ -69,7 +69,7 @@ * renegotiation key */ struct key2 original_wrap_keydata; struct key_ctx tls_crypt_v2_server_key; - struct buffer tls_crypt_v2_wkc; /**< Wrapped client key */ + struct buffer tls_crypt_v2_wkc; /**< Wrapped client key */ struct key_ctx auth_token_key; }; @@ -169,10 +169,10 @@ /* persist crypto sequence number to/from file */ struct packet_id_persist pid_persist; - struct tuntap *tuntap; /**< Tun/tap virtual network interface. */ - bool tuntap_owned; /**< Whether the tun/tap interface should - * be cleaned up when this %context is - * cleaned up. */ + struct tuntap *tuntap; /**< Tun/tap virtual network interface. */ + bool tuntap_owned; /**< Whether the tun/tap interface should + * be cleaned up when this %context is + * cleaned up. */ struct route_list *route_list; /**< List of routing information. See the @@ -208,8 +208,7 @@ static inline bool is_cas_pending(enum multi_status cas) { - return cas =3D=3D CAS_PENDING || cas =3D=3D CAS_PENDING_DEFERRED - || cas =3D=3D CAS_PENDING_DEFERRED_PARTIAL; + return cas =3D=3D CAS_PENDING || cas =3D=3D CAS_PENDING_DEFERRED || ca= s =3D=3D CAS_PENDING_DEFERRED_PARTIAL; } /** @@ -223,9 +222,9 @@ */ struct context_2 { - struct gc_arena gc; /**< Garbage collection arena for - * allocations done in the level 2 scope - * of this context_2 structure. */ + struct gc_arena gc; /**< Garbage collection arena for + * allocations done in the level 2 scope + * of this context_2 structure. */ /* our global wait events */ struct event_set *event_set; @@ -240,13 +239,13 @@ bool link_socket_owned; - const struct link_socket *accept_from; /* possibly do accept() on a pa= rent link_socket */ + const struct link_socket *accept_from; /* possibly do accept() on a = parent link_socket */ - struct link_socket_actual *to_link_addr; /* IP address of remote */ - struct link_socket_actual from; /* address of incoming dat= agram */ + struct link_socket_actual *to_link_addr; /* IP address of remote */ + struct link_socket_actual from; /* address of incoming datagr= am */ /* MTU frame parameters */ - struct frame frame; /* Active frame parameters= */ + struct frame frame; /* Active frame parameters */ #ifdef ENABLE_FRAGMENT /* Object to handle advanced MTU negotiation and datagram fragmentatio= n */ @@ -297,7 +296,7 @@ char *options_string_local; char *options_string_remote; - int occ_op; /* INIT to -1 */ + int occ_op; /* INIT to -1 */ int occ_n_tries; struct event_timeout occ_interval; @@ -305,11 +304,11 @@ * Keep track of maximum packet size received so far * (of authenticated packets). */ - int original_recv_size; /* temporary */ - int max_recv_size_local; /* max packet size received */ - int max_recv_size_remote; /* max packet size received by remote */ - int max_send_size_local; /* max packet size sent */ - int max_send_size_remote; /* max packet size sent by remote */ + int original_recv_size; /* temporary */ + int max_recv_size_local; /* max packet size received */ + int max_recv_size_remote; /* max packet size received by remote */ + int max_send_size_local; /* max packet size sent */ + int max_send_size_remote; /* max packet size sent by remote */ /* remote wants us to send back a load test packet of this size */ @@ -473,63 +472,67 @@ */ struct context { - struct options options; /**< Options loaded from command line or - * configuration file. */ + struct options options; /**< Options loaded from command line or + * configuration file. */ - bool first_time; /**< True on the first iteration of - * OpenVPN's main loop. */ + bool first_time; /**< True on the first iteration of + * OpenVPN's main loop. */ /* context modes */ -#define CM_P2P 0 /* standalone point-to-point session or clien= t */ -#define CM_TOP 1 /* top level of a multi-client or point-to-mu= ltipoint server */ -#define CM_TOP_CLONE 2 /* clone of a CM_TOP context for one thread */ -#define CM_CHILD_UDP 3 /* child context of a CM_TOP or CM_THREAD */ -#define CM_CHILD_TCP 4 /* child context of a CM_TOP or CM_THREAD */ - int mode; /**< Role of this context within the - * OpenVPN process. Valid values are \c - * CM_P2P, \c CM_TOP, \c CM_TOP_CLONE, - * \c CM_CHILD_UDP, and \c CM_CHILD_TCP.= */ +#define CM_P2P 0 /* standalone point-to-point session or c= lient */ +#define CM_TOP 1 /* top level of a multi-client or point-t= o-multipoint server */ +#define CM_TOP_CLONE 2 /* clone of a CM_TOP context for one thre= ad */ +#define CM_CHILD_UDP 3 /* child context of a CM_TOP or CM_THREAD= */ +#define CM_CHILD_TCP 4 /* child context of a CM_TOP or CM_THREAD= */ + int mode; /**< Role of this context within the + * OpenVPN process. Valid values are \c + * CM_P2P, \c CM_TOP, \c CM_TOP_CLONE, + * \c CM_CHILD_UDP, and \c CM_CHILD_TCP= . */ struct multi_context *multi; /**< Pointer to the main P2MP context. * Non-NULL only when mode =3D=3D CM_TO= P. */ - struct gc_arena gc; /**< Garbage collection arena for - * allocations done in the scope of this - * context structure. */ + struct gc_arena gc; /**< Garbage collection arena for + * allocations done in the scope of this + * context structure. */ - struct env_set *es; /**< Set of environment variables. */ + struct env_set *es; /**< Set of environment variables. */ - openvpn_net_ctx_t net_ctx; /**< Networking API opaque context */ + openvpn_net_ctx_t net_ctx; /**< Networking API opaque context */ - struct signal_info *sig; /**< Internal error signaling object. */ + struct signal_info *sig; /**< Internal error signaling object. */ struct plugin_list *plugins; /**< List of plug-ins. */ - bool plugins_owned; /**< Whether the plug-ins should be - * cleaned up when this %context is - * cleaned up. */ + bool plugins_owned; /**< Whether the plug-ins should be + * cleaned up when this %context is + * cleaned up. */ - bool did_we_daemonize; /**< Whether demonization has already - * taken place. */ + bool did_we_daemonize; /**< Whether demonization has already + * taken place. */ struct context_persist persist; /**< Persistent %context. */ - struct context_0 *c0; /**< Level 0 %context. */ - struct context_1 c1; /**< Level 1 %context. */ - struct context_2 c2; /**< Level 2 %context. */ + struct context_0 *c0; /**< Level 0 %context. */ + struct context_1 c1; /**< Level 1 %context. */ + struct context_2 c2; /**< Level 2 %context. */ }; /* * Check for a signal when inside an event loop */ -#define EVENT_LOOP_CHECK_SIGNAL(c, func, arg) \ - if (IS_SIG(c)) \ - { \ - const int brk =3D func(arg); \ - perf_pop(); \ - if (brk) { \ - break;} \ - else { \ - continue;} \ +#define EVENT_LOOP_CHECK_SIGNAL(c, func, arg) \ + if (IS_SIG(c)) \ + { \ + const int brk =3D func(arg); \ + perf_pop(); \ + if (brk) \ + { \ + break; \ + } \ + else \ + { \ + continue; \ + } \ } /* @@ -537,14 +540,15 @@ * have been compiled in. */ -#define TLS_MODE(c) ((c)->c2.tls_multi !=3D NULL) -#define PROTO_DUMP_FLAGS (check_debug_level(D_LINK_RW_VERBOSE) ? (PD_SHOW_= DATA|PD_VERBOSE) : 0) -#define PROTO_DUMP(buf, gc) protocol_dump((buf), \ - PROTO_DUMP_FLAGS \ - |(c->c2.tls_multi ? PD_TLS : 0) = \ - |(c->options.tls_auth_file ? md_= kt_size(c->c1.ks.key_type.digest) : 0) \ - |(c->options.tls_crypt_file || c= ->options.tls_crypt_v2_file ? PD_TLS_CRYPT : 0), \ - gc) +#define TLS_MODE(c) ((c)->c2.tls_multi !=3D NULL) +#define PROTO_DUMP_FLAGS (check_debug_level(D_LINK_RW_VERBOSE) ? (PD_SHOW_= DATA | PD_VERBOSE) : 0) +#define PROTO_DUMP(buf, gc) = \ + protocol_dump( = \ + (buf), = \ + PROTO_DUMP_FLAGS | (c->c2.tls_multi ? PD_TLS : 0) = \ + | (c->options.tls_auth_file ? md_kt_size(c->c1.ks.key_type.dig= est) : 0) \ + | (c->options.tls_crypt_file || c->options.tls_crypt_v2_file ?= PD_TLS_CRYPT : 0), \ + gc) /* this represents "disabled peer-id" */ #define MAX_PEER_ID 0xFFFFFF diff --git a/src/openvpn/options.c b/src/openvpn/options.c index 67139b8..672b954 100644 --- a/src/openvpn/options.c +++ b/src/openvpn/options.c @@ -67,8 +67,7 @@ #include "memdbg.h" #include "options_util.h" -const char title_string[] =3D - PACKAGE_STRING +const char title_string[] =3D PACKAGE_STRING #ifdef CONFIGURE_GIT_REVISION " [git:" CONFIGURE_GIT_REVISION CONFIGURE_GIT_FLAGS "]" #endif @@ -114,7 +113,7 @@ #ifdef CONFIGURE_GIT_REVISION " built on " __DATE__ #endif -; + ; #ifndef ENABLE_SMALL @@ -698,7 +697,7 @@ " cache until token is removed.\n" "--pkcs11-id-management : Acquire identity from management in= terface.\n" "--pkcs11-id serialized-id 'id' : Identity to use, get using standalo= ne --show-pkcs11-ids\n" -#endif /* ENABLE_PKCS11 */ +#endif /* ENABLE_PKCS11 */ "\n" "SSL Library information:\n" "--show-ciphers : Show cipher algorithms to use with --cipher option.= \n" @@ -787,13 +786,13 @@ "--show-pkcs11-ids provider [cert_private] : Show PKCS#11 available id= s.\n" #endif " --verb option can be adde= d *BEFORE* this.\n" -#endif /* ENABLE_PKCS11 */ +#endif /* ENABLE_PKCS11 */ "\n" "General Standalone Options:\n" #ifdef ENABLE_DEBUG "--show-gateway [address]: Show info about gateway [to v4/v6 address].= \n" #endif -; + ; #endif /* !ENABLE_SMALL */ @@ -894,7 +893,7 @@ #endif #ifdef ENABLE_PKCS11 o->pkcs11_pin_cache_period =3D -1; -#endif /* ENABLE_PKCS11 */ +#endif /* ENABLE_PKCS11 */ /* P2MP server context features */ o->auth_token_generate =3D false; @@ -909,7 +908,7 @@ /* Error out if we can't find a valid temporary directory, which s= hould * be very unlikely. */ msg(M_USAGE, "Could not find a suitable temporary directory." - " (GetTempPath() failed). Consider using --tmp-dir"); + " (GetTempPath() failed). Consider using --tmp-dir"); } #else /* ifdef _WIN32 */ /* Non-windows platforms use $TMPDIR, and if not set, default to '/tmp= ' */ @@ -972,23 +971,19 @@ } #define SHOW_PARM(name, value, format) msg(D_SHOW_PARMS, " " #name " =3D = " format, (value)) -#define SHOW_STR(var) SHOW_PARM(var, (o->var ? o->var : "[UNDEF]"), = "'%s'") -#define SHOW_STR_INLINE(var) SHOW_PARM(var, \ - o->var ## _inline ? "[INLINE]" := \ - (o->var ? o->var : "[UNDEF]"), \ - "'%s'") -#define SHOW_INT(var) SHOW_PARM(var, o->var, "%d") -#define SHOW_UINT(var) SHOW_PARM(var, o->var, "%u") -#define SHOW_INT64(var) SHOW_PARM(var, o->var, "%" PRIi64) -#define SHOW_UNSIGNED(var) SHOW_PARM(var, o->var, "0x%08x") -#define SHOW_BOOL(var) SHOW_PARM(var, (o->var ? "ENABLED" : "DISABLED= "), "%s"); +#define SHOW_STR(var) SHOW_PARM(var, (o->var ? o->var : "= [UNDEF]"), "'%s'") +#define SHOW_STR_INLINE(var) \ + SHOW_PARM(var, o->var##_inline ? "[INLINE]" : (o->var ? o->var : "[UND= EF]"), "'%s'") +#define SHOW_INT(var) SHOW_PARM(var, o->var, "%d") +#define SHOW_UINT(var) SHOW_PARM(var, o->var, "%u") +#define SHOW_INT64(var) SHOW_PARM(var, o->var, "%" PRIi64) +#define SHOW_UNSIGNED(var) SHOW_PARM(var, o->var, "0x%08x") +#define SHOW_BOOL(var) SHOW_PARM(var, (o->var ? "ENABLED" : "DISABLED"= ), "%s"); #endif /* ifndef ENABLE_SMALL */ static void -setenv_connection_entry(struct env_set *es, - const struct connection_entry *e, - const int i) +setenv_connection_entry(struct env_set *es, const struct connection_entry = *e, const int i) { setenv_str_i(es, "remote", e->remote, i); setenv_str_i(es, "remote_port", e->remote_port, i); @@ -1006,9 +1001,7 @@ } static void -setenv_local_entry(struct env_set *es, - const struct local_entry *e, - const int i) +setenv_local_entry(struct env_set *es, const struct local_entry *e, const = int i) { setenv_str_i(es, "proto", proto2ascii(e->proto, AF_UNSPEC, false), i); setenv_str_i(es, "local", e->local, i); @@ -1030,7 +1023,7 @@ int i; for (i =3D 0; i < o->connection_list->len; ++i) { - setenv_connection_entry(es, o->connection_list->array[i], i+1); + setenv_connection_entry(es, o->connection_list->array[i], i + = 1); } } else @@ -1042,7 +1035,7 @@ { for (int i =3D 0; i < o->ce.local_list->len; i++) { - setenv_local_entry(es, o->ce.local_list->array[i], i+1); + setenv_local_entry(es, o->ce.local_list->array[i], i + 1); } } } @@ -1087,12 +1080,12 @@ for (current =3D *list, prev =3D NULL; current !=3D NULL; current =3D = current->next) { char *tmp_value =3D NULL; - if (!strncmp(current->string, "foreign_option_", sizeof("foreign_o= ption_")-1)) + if (!strncmp(current->string, "foreign_option_", sizeof("foreign_o= ption_") - 1)) { tmp_value =3D strchr(current->string, '=3D'); if (tmp_value && ++tmp_value) { - if (!strncmp(tmp_value, "dhcp-option ", sizeof("dhcp-optio= n ")-1)) + if (!strncmp(tmp_value, "dhcp-option ", sizeof("dhcp-optio= n ") - 1)) { if (prev) { @@ -1156,18 +1149,18 @@ } static bool -ipv6_addr_safe_hexplusbits( const char *ipv6_prefix_spec ) +ipv6_addr_safe_hexplusbits(const char *ipv6_prefix_spec) { struct in6_addr t_addr; unsigned int t_bits; - return get_ipv6_addr( ipv6_prefix_spec, &t_addr, &t_bits, M_WARN ); + return get_ipv6_addr(ipv6_prefix_spec, &t_addr, &t_bits, M_WARN); } static char * string_substitute(const char *src, int from, int to, struct gc_arena *gc) { - char *ret =3D (char *) gc_malloc(strlen(src) + 1, true, gc); + char *ret =3D (char *)gc_malloc(strlen(src) + 1, true, gc); char *dest =3D ret; char c; @@ -1179,8 +1172,7 @@ c =3D to; } *dest++ =3D c; - } - while (c); + } while (c); return ret; } @@ -1208,9 +1200,7 @@ while (*cp && i < nbytes) { /* valid segments consist of exactly two hex digits, then ':' or E= OS */ - if (!isxdigit(cp[0]) - || !isxdigit(cp[1]) - || (cp[2] !=3D ':' && cp[2] !=3D '\0') + if (!isxdigit(cp[0]) || !isxdigit(cp[1]) || (cp[2] !=3D ':' && cp[= 2] !=3D '\0') || sscanf(cp, "%x", &byte) !=3D 1) { msg(msglevel, "format error in hash fingerprint: %s", str); @@ -1228,7 +1218,8 @@ } if (i < nbytes) { - msg(msglevel, "hash fingerprint is wrong length - expected %d byte= s, got %d: %s", nbytes, i, str); + msg(msglevel, "hash fingerprint is wrong length - expected %d byte= s, got %d: %s", nbytes, i, + str); } else if (term !=3D '\0') { @@ -1248,8 +1239,7 @@ * @param gc The returned list items will be allocated in this = gc */ static struct verify_hash_list * -parse_hash_fingerprint_multiline(const char *str, int nbytes, int msglevel, - struct gc_arena *gc) +parse_hash_fingerprint_multiline(const char *str, int nbytes, int msglevel= , struct gc_arena *gc) { struct gc_arena gc_temp =3D gc_new(); char *lines =3D string_alloc(str, &gc_temp); @@ -1270,8 +1260,7 @@ continue; } - struct verify_hash_list *hash =3D parse_hash_fingerprint(line, nby= tes, - msglevel, g= c); + struct verify_hash_list *hash =3D parse_hash_fingerprint(line, nby= tes, msglevel, gc); if (!hash) { @@ -1296,7 +1285,7 @@ int i; for (i =3D 0; i < len; ++i) { - msg(D_SHOW_PARMS, " %s[%d] =3D %s", name, i, array[i] ); + msg(D_SHOW_PARMS, " %s[%d] =3D %s", name, i, array[i]); } } @@ -1307,10 +1296,7 @@ int i; for (i =3D 0; i < len; ++i) { - msg(D_SHOW_PARMS, " %s[%d] =3D %s", - name, - i, - print_in_addr_t(array[i], 0, &gc)); + msg(D_SHOW_PARMS, " %s[%d] =3D %s", name, i, print_in_addr_t(arra= y[i], 0, &gc)); } gc_free(&gc); } @@ -1356,14 +1342,13 @@ } } static void -dhcp_option_address_parse(const char *name, const char *parm, in_addr_t *a= rray, int *len, int msglevel) +dhcp_option_address_parse(const char *name, const char *parm, in_addr_t *a= rray, int *len, + int msglevel) { if (*len >=3D N_DHCP_ADDR) { - msg(msglevel, "--dhcp-option %s: maximum of %d %s servers can be s= pecified", - name, - N_DHCP_ADDR, - name); + msg(msglevel, "--dhcp-option %s: maximum of %d %s servers can be s= pecified", name, + N_DHCP_ADDR, name); } else { @@ -1408,12 +1393,15 @@ msg(D_SHOW_PARMS, " server_network =3D %s", print_in_addr_t(o->server= _network, 0, &gc)); msg(D_SHOW_PARMS, " server_netmask =3D %s", print_in_addr_t(o->server= _netmask, 0, &gc)); - msg(D_SHOW_PARMS, " server_network_ipv6 =3D %s", print_in6_addr(o->se= rver_network_ipv6, 0, &gc) ); + msg(D_SHOW_PARMS, " server_network_ipv6 =3D %s", print_in6_addr(o->se= rver_network_ipv6, 0, &gc)); SHOW_INT(server_netbits_ipv6); msg(D_SHOW_PARMS, " server_bridge_ip =3D %s", print_in_addr_t(o->serv= er_bridge_ip, 0, &gc)); - msg(D_SHOW_PARMS, " server_bridge_netmask =3D %s", print_in_addr_t(o-= >server_bridge_netmask, 0, &gc)); - msg(D_SHOW_PARMS, " server_bridge_pool_start =3D %s", print_in_addr_t= (o->server_bridge_pool_start, 0, &gc)); - msg(D_SHOW_PARMS, " server_bridge_pool_end =3D %s", print_in_addr_t(o= ->server_bridge_pool_end, 0, &gc)); + msg(D_SHOW_PARMS, " server_bridge_netmask =3D %s", + print_in_addr_t(o->server_bridge_netmask, 0, &gc)); + msg(D_SHOW_PARMS, " server_bridge_pool_start =3D %s", + print_in_addr_t(o->server_bridge_pool_start, 0, &gc)); + msg(D_SHOW_PARMS, " server_bridge_pool_end =3D %s", + print_in_addr_t(o->server_bridge_pool_end, 0, &gc)); if (o->push_list.head) { const struct push_entry *e =3D o->push_list.head; @@ -1427,13 +1415,16 @@ } } SHOW_BOOL(ifconfig_pool_defined); - msg(D_SHOW_PARMS, " ifconfig_pool_start =3D %s", print_in_addr_t(o->i= fconfig_pool_start, 0, &gc)); + msg(D_SHOW_PARMS, " ifconfig_pool_start =3D %s", + print_in_addr_t(o->ifconfig_pool_start, 0, &gc)); msg(D_SHOW_PARMS, " ifconfig_pool_end =3D %s", print_in_addr_t(o->ifc= onfig_pool_end, 0, &gc)); - msg(D_SHOW_PARMS, " ifconfig_pool_netmask =3D %s", print_in_addr_t(o-= >ifconfig_pool_netmask, 0, &gc)); + msg(D_SHOW_PARMS, " ifconfig_pool_netmask =3D %s", + print_in_addr_t(o->ifconfig_pool_netmask, 0, &gc)); SHOW_STR(ifconfig_pool_persist_filename); SHOW_INT(ifconfig_pool_persist_refresh_freq); SHOW_BOOL(ifconfig_ipv6_pool_defined); - msg(D_SHOW_PARMS, " ifconfig_ipv6_pool_base =3D %s", print_in6_addr(o= ->ifconfig_ipv6_pool_base, 0, &gc)); + msg(D_SHOW_PARMS, " ifconfig_ipv6_pool_base =3D %s", + print_in6_addr(o->ifconfig_ipv6_pool_base, 0, &gc)); SHOW_INT(ifconfig_ipv6_pool_netbits); SHOW_INT(n_bcast_buf); SHOW_INT(tcp_queue_limit); @@ -1447,11 +1438,15 @@ SHOW_BOOL(ccd_exclusive); SHOW_STR(tmp_dir); SHOW_BOOL(push_ifconfig_defined); - msg(D_SHOW_PARMS, " push_ifconfig_local =3D %s", print_in_addr_t(o->p= ush_ifconfig_local, 0, &gc)); - msg(D_SHOW_PARMS, " push_ifconfig_remote_netmask =3D %s", print_in_ad= dr_t(o->push_ifconfig_remote_netmask, 0, &gc)); + msg(D_SHOW_PARMS, " push_ifconfig_local =3D %s", + print_in_addr_t(o->push_ifconfig_local, 0, &gc)); + msg(D_SHOW_PARMS, " push_ifconfig_remote_netmask =3D %s", + print_in_addr_t(o->push_ifconfig_remote_netmask, 0, &gc)); SHOW_BOOL(push_ifconfig_ipv6_defined); - msg(D_SHOW_PARMS, " push_ifconfig_ipv6_local =3D %s/%d", print_in6_ad= dr(o->push_ifconfig_ipv6_local, 0, &gc), o->push_ifconfig_ipv6_netbits ); - msg(D_SHOW_PARMS, " push_ifconfig_ipv6_remote =3D %s", print_in6_addr= (o->push_ifconfig_ipv6_remote, 0, &gc)); + msg(D_SHOW_PARMS, " push_ifconfig_ipv6_local =3D %s/%d", + print_in6_addr(o->push_ifconfig_ipv6_local, 0, &gc), o->push_ifcon= fig_ipv6_netbits); + msg(D_SHOW_PARMS, " push_ifconfig_ipv6_remote =3D %s", + print_in6_addr(o->push_ifconfig_ipv6_remote, 0, &gc)); SHOW_BOOL(enable_c2c); SHOW_BOOL(duplicate_cn); SHOW_INT(cf_max); @@ -1484,16 +1479,13 @@ #endif /* ! ENABLE_SMALL */ static void -option_iroute(struct options *o, - const char *network_str, - const char *netmask_str, - int msglevel) +option_iroute(struct options *o, const char *network_str, const char *netm= ask_str, int msglevel) { struct iroute *ir; ALLOC_OBJ_GC(ir, struct iroute, &o->gc); ir->network =3D getaddr(GETADDR_HOST_ORDER, network_str, 0, NULL, NULL= ); - ir->netbits =3D 32; /* host route if no netmask given */ + ir->netbits =3D 32; /* host route if no netmask given */ if (netmask_str) { @@ -1502,8 +1494,7 @@ if (ir->netbits < 0) { - msg(msglevel, "in --iroute %s %s : Bad network/subnet specific= ation", - network_str, + msg(msglevel, "in --iroute %s %s : Bad network/subnet specific= ation", network_str, netmask_str); return; } @@ -1514,18 +1505,15 @@ } static void -option_iroute_ipv6(struct options *o, - const char *prefix_str, - int msglevel) +option_iroute_ipv6(struct options *o, const char *prefix_str, int msglevel) { struct iroute_ipv6 *ir; ALLOC_OBJ_GC(ir, struct iroute_ipv6, &o->gc); - if (!get_ipv6_addr(prefix_str, &ir->network, &ir->netbits, msglevel )) + if (!get_ipv6_addr(prefix_str, &ir->network, &ir->netbits, msglevel)) { - msg(msglevel, "in --iroute-ipv6 %s: Bad IPv6 prefix specification", - prefix_str); + msg(msglevel, "in --iroute-ipv6 %s: Bad IPv6 prefix specification"= , prefix_str); return; } @@ -1548,17 +1536,16 @@ SHOW_BOOL(nocache); SHOW_STR(http_version); SHOW_STR(user_agent); - for (i =3D 0; i < MAX_CUSTOM_HTTP_HEADER && o->custom_headers[i].name= ; i++) + for (i =3D 0; i < MAX_CUSTOM_HTTP_HEADER && o->custom_headers[i].name;= i++) { if (o->custom_headers[i].content) { - msg(D_SHOW_PARMS, " custom_header[%d] =3D %s: %s", i, - o->custom_headers[i].name, o->custom_headers[i].content); + msg(D_SHOW_PARMS, " custom_header[%d] =3D %s: %s", i, o->cust= om_headers[i].name, + o->custom_headers[i].content); } else { - msg(D_SHOW_PARMS, " custom_header[%d] =3D %s", i, - o->custom_headers[i].name); + msg(D_SHOW_PARMS, " custom_header[%d] =3D %s", i, o->custom_h= eaders[i].name); } } msg(D_SHOW_PARMS, "END http_proxy"); @@ -1615,7 +1602,8 @@ for (int i =3D 0; i < o->local_list->len; i++) { msg(D_SHOW_PARMS, " [%s]:%s-%s", o->local_list->array[i]->local, - o->local_list->array[i]->port, proto2ascii(o->local_list->arra= y[i]->proto, o->af, false)); + o->local_list->array[i]->port, + proto2ascii(o->local_list->array[i]->proto, o->af, false)); } SHOW_STR(remote); SHOW_STR(remote_port); @@ -1652,8 +1640,7 @@ SHOW_INT(explicit_exit_notification); SHOW_STR_INLINE(tls_auth_file); - SHOW_PARM(key_direction, keydirection2ascii(o->key_direction, false, t= rue), - "%s"); + SHOW_PARM(key_direction, keydirection2ascii(o->key_direction, false, t= rue), "%s"); SHOW_STR_INLINE(tls_crypt_file); SHOW_STR_INLINE(tls_crypt_v2_file); } @@ -1908,7 +1895,7 @@ SHOW_INT(ns_cert_type); { int i; - for (i =3D 0; iverify_hash; - int digest_len =3D (o->verify_hash_algo =3D=3D MD_SHA1) ? SHA_DIGE= ST_LENGTH : - SHA256_DIGEST_LENGTH; + int digest_len =3D + (o->verify_hash_algo =3D=3D MD_SHA1) ? SHA_DIGEST_LENGTH : SHA= 256_DIGEST_LENGTH; while (hl) { - char *s =3D format_hex_ex(hl->hash, digest_len, 0, - 1, ":", &gc); + char *s =3D format_hex_ex(hl->hash, digest_len, 0, 1, ":", &gc= ); SHOW_PARM(verify_hash, s, "%s"); hl =3D hl->next; } @@ -1951,36 +1937,38 @@ #ifdef ENABLE_PKCS11 { int i; - for (i =3D 0; ipkcs11_providers[i] !=3D NULL; i++) + for (i =3D 0; i < MAX_PARMS && o->pkcs11_providers[i] !=3D NULL; i= ++) { SHOW_PARM(pkcs11_providers, o->pkcs11_providers[i], "%s"); } } { int i; - for (i =3D 0; ipkcs11_protected= _authentication[i] ? "ENABLED" : "DISABLED", "%s"); + SHOW_PARM(pkcs11_protected_authentication, + o->pkcs11_protected_authentication[i] ? "ENABLED" : = "DISABLED", "%s"); } } { int i; - for (i =3D 0; ipkcs11_private_mode[i], "%08= x"); } } { int i; - for (i =3D 0; ipkcs11_cert_private[i] ? "EN= ABLED" : "DISABLED", "%s"); + SHOW_PARM(pkcs11_cert_private, o->pkcs11_cert_private[i] ? "EN= ABLED" : "DISABLED", + "%s"); } } SHOW_INT(pkcs11_pin_cache_period); SHOW_STR(pkcs11_id); SHOW_BOOL(pkcs11_id_management); -#endif /* ENABLE_PKCS11 */ +#endif /* ENABLE_PKCS11 */ show_p2mp_parms(o); @@ -2001,9 +1989,7 @@ #ifdef ENABLE_MANAGEMENT static struct http_proxy_options * -parse_http_proxy_override(const char *server, - const char *port, - const char *flags, +parse_http_proxy_override(const char *server, const char *port, const char= *flags, struct gc_arena *gc) { if (server && port) @@ -2058,7 +2044,8 @@ } else { - msg(M_WARN, "Note: option http-proxy-override ignored because no T= CP-based connection profiles are defined"); + msg(M_WARN, + "Note: option http-proxy-override ignored because no TCP-based= connection profiles are defined"); } } @@ -2075,8 +2062,7 @@ } static struct local_entry * -alloc_local_entry(struct connection_entry *ce, const int msglevel, - struct gc_arena *gc) +alloc_local_entry(struct connection_entry *ce, const int msglevel, struct = gc_arena *gc) { struct local_list *l =3D alloc_local_list_if_undef(ce, gc); struct local_entry *e; @@ -2089,7 +2075,9 @@ struct local_entry **new_array =3D gc_realloc(l->array, new_cap * = elem_size, gc); if (!new_array) { - msg(msglevel, "Unable to process more local options: out of me= mory. Number of entries =3D %d", l->len); + msg(msglevel, + "Unable to process more local options: out of memory. Numb= er of entries =3D %d", + l->len); return NULL; } @@ -2123,10 +2111,13 @@ if (l->len =3D=3D l->capacity) { int capacity =3D l->capacity + CONNECTION_LIST_SIZE; - struct connection_entry **ce =3D gc_realloc(l->array, capacity*siz= eof(struct connection_entry *), &options->gc); + struct connection_entry **ce =3D + gc_realloc(l->array, capacity * sizeof(struct connection_entry= *), &options->gc); if (ce =3D=3D NULL) { - msg(msglevel, "Unable to process more connection options: out = of memory. Number of entries =3D %d", l->len); + msg(msglevel, + "Unable to process more connection options: out of memory.= Number of entries =3D %d", + l->len); return NULL; } l->array =3D ce; @@ -2156,10 +2147,13 @@ if (l->len =3D=3D l->capacity) { int capacity =3D l->capacity + CONNECTION_LIST_SIZE; - struct remote_entry **re =3D gc_realloc(l->array, capacity*sizeof(= struct remote_entry *), &options->gc); + struct remote_entry **re =3D + gc_realloc(l->array, capacity * sizeof(struct remote_entry *),= &options->gc); if (re =3D=3D NULL) { - msg(msglevel, "Unable to process more remote options: out of m= emory. Number of entries =3D %d", l->len); + msg(msglevel, + "Unable to process more remote options: out of memory. Num= ber of entries =3D %d", + l->len); return NULL; } l->array =3D re; @@ -2223,8 +2217,7 @@ } static void -connection_entry_preload_key(const char **key_file, bool *key_inline, - struct gc_arena *gc) +connection_entry_preload_key(const char **key_file, bool *key_inline, stru= ct gc_arena *gc) { if (key_file && *key_file && !(*key_inline)) { @@ -2234,7 +2227,7 @@ msg(M_FATAL, "Cannot pre-load keyfile (%s)", *key_file); } - *key_file =3D (const char *) in.data; + *key_file =3D (const char *)in.data; *key_inline =3D true; } } @@ -2249,13 +2242,11 @@ } #endif - if (options->verify_hash_no_ca - || options->pkcs12_file - || options->ca_file + if (options->verify_hash_no_ca || options->pkcs12_file || options->ca_= file #ifndef ENABLE_CRYPTO_MBEDTLS || options->ca_path #endif - ) + ) { return; } @@ -2268,14 +2259,19 @@ msg(M_USAGE, "%s", str); } -#define MUST_BE_UNDEF(parm, parm_name) \ - if (options->parm !=3D defaults.parm) { msg(M_USAGE, use_err, parm_nam= e); } +#define MUST_BE_UNDEF(parm, parm_name) \ + if (options->parm !=3D defaults.parm) \ + { \ + msg(M_USAGE, use_err, parm_name); \ + } #define MUST_BE_FALSE(condition, parm_name) \ - if (condition) { msg(M_USAGE, use_err, parm_name); } + if (condition) \ + { \ + msg(M_USAGE, use_err, parm_name); \ + } static void -options_postprocess_verify_ce(const struct options *options, - const struct connection_entry *ce) +options_postprocess_verify_ce(const struct options *options, const struct = connection_entry *ce) { struct options defaults; int dev =3D DEV_TYPE_UNDEF; @@ -2303,9 +2299,8 @@ */ if (ce->proto =3D=3D PROTO_TCP) { - msg(M_USAGE, - "--proto tcp is ambiguous in this context. Please specify " - "--proto tcp-server or --proto tcp-client"); + msg(M_USAGE, "--proto tcp is ambiguous in this context. Please spe= cify " + "--proto tcp-server or --proto tcp-client"); } /* @@ -2345,16 +2340,13 @@ if (string_defined_equal(ce->remote, options->ifconfig_local) || string_defined_equal(ce->remote, options->ifconfig_remote_netma= sk)) { - msg(M_USAGE, - "--local and --remote addresses must be distinct from --ifconf= ig " - "addresses"); + msg(M_USAGE, "--local and --remote addresses must be distinct from= --ifconfig " + "addresses"); } - if (string_defined_equal(options->ifconfig_local, - options->ifconfig_remote_netmask)) + if (string_defined_equal(options->ifconfig_local, options->ifconfig_re= mote_netmask)) { - msg(M_USAGE, - "local and remote/netmask --ifconfig addresses must be differe= nt"); + msg(M_USAGE, "local and remote/netmask --ifconfig addresses must b= e different"); } if (ce->bind_defined && !ce->bind_local) @@ -2364,8 +2356,7 @@ if (ce->local_port_defined && !ce->bind_local) { - msg(M_USAGE, - "--lport and --nobind don't make sense when used together"); + msg(M_USAGE, "--lport and --nobind don't make sense when used toge= ther"); } if (!ce->remote && !ce->bind_local) @@ -2377,8 +2368,7 @@ { struct local_entry *le =3D ce->local_list->array[i]; - if (proto_is_net(le->proto) - && string_defined_equal(le->local, ce->remote) + if (proto_is_net(le->proto) && string_defined_equal(le->local, ce-= >remote) && string_defined_equal(le->port, ce->remote_port)) { msg(M_USAGE, "--remote and one of the --local addresses are th= e same"); @@ -2404,7 +2394,8 @@ && (options->management_flags || options->management_log_history_cache !=3D defaults.managem= ent_log_history_cache)) { - msg(M_USAGE, "--management is not specified, however one or more o= ptions which modify the behavior of --management were specified"); + msg(M_USAGE, + "--management is not specified, however one or more options wh= ich modify the behavior of --management were specified"); } if ((options->management_client_user || options->management_client_gro= up) @@ -2413,24 +2404,21 @@ msg(M_USAGE, "--management-client-(user|group) can only be used on= unix domain sockets"); } - if (options->management_addr - && !(options->management_flags & MF_UNIX_SOCK) + if (options->management_addr && !(options->management_flags & MF_UNIX_= SOCK) && (!options->management_user_pass)) { msg(M_WARN, "WARNING: Using --management on a TCP port WITHOUT " - "passwords is STRONGLY discouraged and considered insecure"); + "passwords is STRONGLY discouraged and considered inse= cure"); } #endif /* ifdef ENABLE_MANAGEMENT */ #if !defined(HAVE_XKEY_PROVIDER) - if ((tls_version_max() >=3D TLS_VER_1_3) - && (options->management_flags & MF_EXTERNAL_KEY) - && !(options->management_flags & (MF_EXTERNAL_KEY_NOPADDING)) - ) + if ((tls_version_max() >=3D TLS_VER_1_3) && (options->management_flags= & MF_EXTERNAL_KEY) + && !(options->management_flags & (MF_EXTERNAL_KEY_NOPADDING))) { msg(M_FATAL, "management-external-key with TLS 1.3 or later requir= es " - "nopadding argument/support"); + "nopadding argument/support"); } #endif /* @@ -2438,7 +2426,8 @@ */ #ifdef _WIN32 - if (dev =3D=3D DEV_TYPE_TUN && !(pull || (options->ifconfig_local && o= ptions->ifconfig_remote_netmask))) + if (dev =3D=3D DEV_TYPE_TUN + && !(pull || (options->ifconfig_local && options->ifconfig_remote_= netmask))) { msg(M_USAGE, "On Windows, --ifconfig is required when --dev tun is= used"); } @@ -2454,14 +2443,13 @@ const char *prefix =3D "Some --dhcp-option or --dns options requir= e DHCP server"; if (options->windows_driver !=3D WINDOWS_DRIVER_TAP_WINDOWS6) { - msg(M_USAGE, "%s, which is not supported by the selected %s dr= iver", - prefix, print_tun_backend_driver(options->windows_driver)); + msg(M_USAGE, "%s, which is not supported by the selected %s dr= iver", prefix, + print_tun_backend_driver(options->windows_driver)); } else if (options->tuntap_options.ip_win32_type !=3D IPW32_SET_DHCP= _MASQ && options->tuntap_options.ip_win32_type !=3D IPW32_SET_A= DAPTIVE) { - msg(M_USAGE, "%s, which requires --ip-win32 dynamic or adaptiv= e", - prefix); + msg(M_USAGE, "%s, which requires --ip-win32 dynamic or adaptiv= e", prefix); } } #endif /* ifdef _WIN32 */ @@ -2484,21 +2472,18 @@ if ((ce->http_proxy_options) && ce->proto !=3D PROTO_TCP_CLIENT) { - 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) { - msg(M_USAGE, - "--http-proxy not specified but other http proxy options prese= nt"); + msg(M_USAGE, "--http-proxy not specified but other http proxy opti= ons present"); } if (ce->http_proxy_options && ce->socks_proxy_server) { - msg(M_USAGE, - "--http-proxy can not be used together with --socks-proxy"); + msg(M_USAGE, "--http-proxy can not be used together with --socks-p= roxy"); } if (ce->socks_proxy_server && ce->proto =3D=3D PROTO_TCP_SERVER) @@ -2518,7 +2503,8 @@ { const char use_err[] =3D "--%s cannot be used with --mode server."; -#define USAGE_VALID_SERVER_PROTOS "--mode server currently only supports "= \ +#define USAGE_VALID_SERVER_PROTOS \ + "--mode server currently only supports " \ "--proto values of udp, tcp-server, tcp4-server, or tcp6-server" #ifdef TARGET_ANDROID msg(M_FATAL, "--mode server not supported on Android"); @@ -2541,7 +2527,7 @@ && (ce->proto !=3D PROTO_TCP_SERVER)) { msg(M_USAGE, "--port-share only works in TCP server mode " - "(--proto values of tcp-server, tcp4-server, or tcp6-serve= r)"); + "(--proto values of tcp-server, tcp4-server, or t= cp6-server)"); } #endif if (!options->tls_server) @@ -2555,8 +2541,7 @@ /* blocks force to have a remote embedded, so we check * for the --remote and bail out if it is present */ - if (options->connection_list->len >1 - || options->connection_list->array[0]->remote) + if (options->connection_list->len > 1 || options->connection_list-= >array[0]->remote) { msg(M_USAGE, " cannot be used with --mode server"); } @@ -2564,9 +2549,8 @@ MUST_BE_UNDEF(shaper, "shaper"); if (options->ipchange) { - msg(M_USAGE, - "--ipchange cannot be used with --mode server (use " - "--client-connect instead)"); + msg(M_USAGE, "--ipchange cannot be used with --mode server (us= e " + "--client-connect instead)"); } if (!(proto_is_dgram(ce->proto) || ce->proto =3D=3D PROTO_TCP_SERV= ER)) { @@ -2574,20 +2558,23 @@ } if (!proto_is_udp(ce->proto) && (options->cf_max || options->cf_pe= r)) { - msg(M_USAGE, "--connect-freq only works with --mode server --p= roto udp. Try --max-clients instead."); + msg(M_USAGE, + "--connect-freq only works with --mode server --proto udp.= Try --max-clients instead."); } - if (!(dev =3D=3D DEV_TYPE_TAP || (dev =3D=3D DEV_TYPE_TUN && optio= ns->topology =3D=3D TOP_SUBNET)) && options->ifconfig_pool_netmask) + if (!(dev =3D=3D DEV_TYPE_TAP || (dev =3D=3D DEV_TYPE_TUN && optio= ns->topology =3D=3D TOP_SUBNET)) + && options->ifconfig_pool_netmask) { - msg(M_USAGE, "The third parameter to --ifconfig-pool (netmask)= is only valid in --dev tap mode"); + msg(M_USAGE, + "The third parameter to --ifconfig-pool (netmask) is only = valid in --dev tap mode"); } if (options->routes && (options->routes->flags & RG_ENABLE)) { - msg(M_USAGE, "--redirect-gateway cannot be used with --mode se= rver (however --push \"redirect-gateway\" is fine)"); + msg(M_USAGE, + "--redirect-gateway cannot be used with --mode server (how= ever --push \"redirect-gateway\" is fine)"); } MUST_BE_UNDEF(route_delay_defined, "route-delay"); MUST_BE_UNDEF(up_delay, "up-delay"); - if (!options->ifconfig_pool_defined - && !options->ifconfig_ipv6_pool_defined + if (!options->ifconfig_pool_defined && !options->ifconfig_ipv6_poo= l_defined && options->ifconfig_pool_persist_filename) { msg(M_USAGE, @@ -2600,7 +2587,8 @@ MUST_BE_UNDEF(allow_recursive_routing, "allow-recursive-routing"); if (options->auth_user_pass_file) { - msg(M_USAGE, "--auth-user-pass cannot be used with --mode serv= er (it should be used on the client side only)"); + msg(M_USAGE, + "--auth-user-pass cannot be used with --mode server (it sh= ould be used on the client side only)"); } if (options->ccd_exclusive && !options->client_config_dir) { @@ -2609,24 +2597,24 @@ if (options->auth_token_generate && !options->renegotiate_seconds) { msg(M_USAGE, "--auth-gen-token needs a non-infinite " - "--renegotiate_seconds setting"); + "--renegotiate_seconds setting"); } if (options->auth_token_generate && options->auth_token_renewal && options->auth_token_renewal < 2 * options->handshake_window) { - msg(M_USAGE, "--auth-gen-token renewal time needs to be at lea= st " + msg(M_USAGE, + "--auth-gen-token renewal time needs to be at least " " two times --hand-window (%d).", options->handshake_window); - } - if (!options->auth_user_pass_verify_script - && !PLUGIN_OPTION_LIST(options) + if (!options->auth_user_pass_verify_script && !PLUGIN_OPTION_LIST(= options) && !MAN_CLIENT_AUTH_ENABLED(options)) { - const char *use_err =3D "--%s must be used with --management-c= lient-auth, an --auth-user-pass-verify script, or plugin"; + const char *use_err =3D + "--%s must be used with --management-client-auth, an --aut= h-user-pass-verify script, or plugin"; MUST_BE_FALSE(options->ssl_flags - & (SSLF_CLIENT_CERT_NOT_REQUIRED|SSLF_CLIENT_CER= T_OPTIONAL), + & (SSLF_CLIENT_CERT_NOT_REQUIRED | SSLF_CLIE= NT_CERT_OPTIONAL), "verify-client-cert none|optional"); MUST_BE_FALSE(options->ssl_flags & SSLF_USERNAME_AS_COMMON_NAM= E, "username-as-common-name"); @@ -2668,7 +2656,7 @@ MUST_BE_UNDEF(cf_max, "connect-freq"); MUST_BE_UNDEF(cf_per, "connect-freq"); MUST_BE_FALSE(options->ssl_flags - & (SSLF_CLIENT_CERT_NOT_REQUIRED|SSLF_CLIENT_CERT_OP= TIONAL), + & (SSLF_CLIENT_CERT_NOT_REQUIRED | SSLF_CLIENT_C= ERT_OPTIONAL), "verify-client-cert"); MUST_BE_FALSE(options->ssl_flags & SSLF_USERNAME_AS_COMMON_NAME, "= username-as-common-name"); MUST_BE_FALSE(options->ssl_flags & SSLF_AUTH_USER_PASS_OPTIONAL, "= auth-user-pass-optional"); @@ -2676,15 +2664,16 @@ if (options->server_flags & SF_TCP_NODELAY_HELPER) { msg(M_WARN, "WARNING: setting tcp-nodelay on the client side w= ill not " - "affect the server. To have TCP_NODELAY in both direction = use " - "tcp-nodelay in the server configuration instead."); + "affect the server. To have TCP_NODELAY in both di= rection use " + "tcp-nodelay in the server configuration instead."= ); } MUST_BE_UNDEF(auth_user_pass_verify_script, "auth-user-pass-verify= "); MUST_BE_UNDEF(auth_token_generate, "auth-gen-token"); #if PORT_SHARE if (options->port_share_host || options->port_share_port) { - msg(M_USAGE, "--port-share requires TCP server mode (--mode se= rver --proto tcp-server)"); + msg(M_USAGE, + "--port-share requires TCP server mode (--mode server --pr= oto tcp-server)"); } #endif MUST_BE_UNDEF(stale_routes_check_interval, "stale-routes-check"); @@ -2697,8 +2686,7 @@ /* * SSL/TLS mode sanity checks. */ - if (options->tls_server + options->tls_client - + (options->shared_secret_file !=3D NULL) > 1) + if (options->tls_server + options->tls_client + (options->shared_secre= t_file !=3D NULL) > 1) { msg(M_USAGE, "specify only one of --tls-server, --tls-client, or -= -secret"); } @@ -2712,29 +2700,26 @@ } msg(msglevel, "DEPRECATION: No tls-client or tls-server option in " - "configuration detected. OpenVPN 2.8 will remove the " - "functionality to run a VPN without TLS. " - "See the examples section in the manual page for " - "examples of a similar quick setup with peer-fingerprint. " - "OpenVPN 2.7 allows using this configuration when using " - "--allow-deprecated-insecure-static-crypto but you should move= " - "to a proper configuration using TLS as soon as possible." - ); + "configuration detected. OpenVPN 2.8 will remove the= " + "functionality to run a VPN without TLS. " + "See the examples section in the manual page for " + "examples of a similar quick setup with peer-fingerp= rint. " + "OpenVPN 2.7 allows using this configuration when us= ing " + "--allow-deprecated-insecure-static-crypto but you s= hould move " + "to a proper configuration using TLS as soon as poss= ible."); } - if (options->ssl_flags & (SSLF_CLIENT_CERT_NOT_REQUIRED|SSLF_CLIENT_CE= RT_OPTIONAL)) + if (options->ssl_flags & (SSLF_CLIENT_CERT_NOT_REQUIRED | SSLF_CLIENT_= CERT_OPTIONAL)) { msg(M_WARN, "WARNING: POTENTIALLY DANGEROUS OPTION " - "--verify-client-cert none|optional " - "may accept clients which do not present a certificate"); + "--verify-client-cert none|optional " + "may accept clients which do not present a certificate= "); } const int tls_version_max =3D - (options->ssl_flags >> SSLF_TLS_VERSION_MAX_SHIFT) - & SSLF_TLS_VERSION_MAX_MASK; + (options->ssl_flags >> SSLF_TLS_VERSION_MAX_SHIFT) & SSLF_TLS_VERS= ION_MAX_MASK; const int tls_version_min =3D - (options->ssl_flags >> SSLF_TLS_VERSION_MIN_SHIFT) - & SSLF_TLS_VERSION_MIN_MASK; + (options->ssl_flags >> SSLF_TLS_VERSION_MIN_SHIFT) & SSLF_TLS_VERS= ION_MIN_MASK; if (tls_version_max > 0 && tls_version_max < tls_version_min) { @@ -2751,20 +2736,24 @@ } else if (!options->pkcs11_providers[0] && options->pkcs11_id_manag= ement) { - msg(M_WARN, "Option pkcs11-id-management is ignored as no pkcs= 11-providers are specified"); + msg(M_WARN, + "Option pkcs11-id-management is ignored as no pkcs11-provi= ders are specified"); } if (options->pkcs11_providers[0]) { if (options->pkcs11_id_management && options->pkcs11_id !=3D N= ULL) { - msg(M_USAGE, "Parameter --pkcs11-id cannot be used when --= pkcs11-id-management is also specified."); + msg(M_USAGE, + "Parameter --pkcs11-id cannot be used when --pkcs11-id= -management is also specified."); } if (!options->pkcs11_id_management && options->pkcs11_id =3D= =3D NULL) { - msg(M_USAGE, "Parameter --pkcs11-id or --pkcs11-id-managem= ent should be specified."); + msg(M_USAGE, + "Parameter --pkcs11-id or --pkcs11-id-management shoul= d be specified."); } - const char use_err[] =3D "Parameter --%s cannot be used when -= -pkcs11-provider is also specified."; + const char use_err[] =3D + "Parameter --%s cannot be used when --pkcs11-provider is a= lso specified."; MUST_BE_UNDEF(cert_file, "cert"); MUST_BE_UNDEF(priv_key_file, "key"); MUST_BE_UNDEF(pkcs12_file, "pkcs12"); @@ -2777,9 +2766,10 @@ else #endif /* ifdef ENABLE_PKCS11 */ #ifdef ENABLE_CRYPTOAPI - if (options->cryptoapi_cert) + if (options->cryptoapi_cert) { - const char use_err[] =3D "Parameter --%s cannot be used when -= -cryptoapicert is also specified."; + const char use_err[] =3D + "Parameter --%s cannot be used when --cryptoapicert is als= o specified."; MUST_BE_UNDEF(cert_file, "cert"); MUST_BE_UNDEF(priv_key_file, "key"); MUST_BE_UNDEF(pkcs12_file, "pkcs12"); @@ -2788,7 +2778,7 @@ } else #endif - if (options->pkcs12_file) + if (options->pkcs12_file) { #ifdef ENABLE_CRYPTO_MBEDTLS msg(M_USAGE, "Parameter --pkcs12 cannot be used with the mbed = TLS version of OpenVPN."); @@ -2799,7 +2789,7 @@ MUST_BE_UNDEF(priv_key_file, "key"); MUST_BE_FALSE(options->management_flags & MF_EXTERNAL_KEY, "ma= nagement-external-key"); MUST_BE_FALSE(options->management_flags & MF_EXTERNAL_CERT, "m= anagement-external-cert"); -#endif /* ifdef ENABLE_CRYPTO_MBEDTLS */ +#endif /* ifdef ENABLE_CRYPTO_MBEDTLS */ } else /* cert/key from none of pkcs11, pkcs12, cryptoapi */ { @@ -2815,24 +2805,25 @@ } else if (!(options->management_flags & MF_EXTERNAL_KEY)) { - msg(M_USAGE, "--management-external-cert must be used = with --management-external-key"); + msg(M_USAGE, + "--management-external-cert must be used with --ma= nagement-external-key"); } } if (pull) { - const int sum =3D ((options->cert_file !=3D NULL) || (options->managemen= t_flags & MF_EXTERNAL_CERT)) - + ((options->priv_key_file !=3D NULL) || (options->man= agement_flags & MF_EXTERNAL_KEY)); + + ((options->priv_key_file !=3D NULL) + || (options->management_flags & MF_EXTERNAL_KEY)); if (sum =3D=3D 0) { if (!options->auth_user_pass_file) { msg(M_USAGE, "No client-side authentication method= is " - "specified. You must use either " - "--cert/--key, --pkcs12, or " - "--auth-user-pass"); + "specified. You must use either " + "--cert/--key, --pkcs12, or " + "--auth-user-pass"); } } else if (sum !=3D 2) @@ -2844,11 +2835,13 @@ { if (!(options->management_flags & MF_EXTERNAL_CERT)) { - notnull(options->cert_file, "certificate file (--cert)= or PKCS#12 file (--pkcs12)"); + notnull(options->cert_file, + "certificate file (--cert) or PKCS#12 file (--= pkcs12)"); } if (!(options->management_flags & MF_EXTERNAL_KEY)) { - notnull(options->priv_key_file, "private key file (--k= ey) or PKCS#12 file (--pkcs12)"); + notnull(options->priv_key_file, + "private key file (--key) or PKCS#12 file (--p= kcs12)"); } } } @@ -2859,7 +2852,8 @@ if (options->tls_client && ce->tls_crypt_v2_file && (ce->tls_auth_file || ce->tls_crypt_file)) { - msg(M_USAGE, "--tls-crypt-v2, --tls-auth and --tls-crypt are m= utually exclusive in client mode"); + msg(M_USAGE, + "--tls-crypt-v2, --tls-auth and --tls-crypt are mutually e= xclusive in client mode"); } } else @@ -2988,12 +2982,12 @@ if (ce->af =3D=3D AF_INET6) { msg(M_INFO, "WARNING: '--proto udp6' is not compatible with " - "'--socks-proxy' today. Forcing IPv4 mode." ); + "'--socks-proxy' today. Forcing IPv4 mode."); } else { msg(M_INFO, "NOTICE: dual-stack mode for '--proto udp' does no= t " - "work correctly with '--socks-proxy' today. Forcing IPv4.= " ); + "work correctly with '--socks-proxy' today. Forci= ng IPv4."); } ce->af =3D AF_INET; } @@ -3027,7 +3021,7 @@ } else #endif - if (ce->tun_mtu_defined) + if (ce->tun_mtu_defined) { if (o->ce.tun_mtu =3D=3D TUN_MTU_DEFAULT) { @@ -3070,12 +3064,9 @@ /* Pre-cache tls-auth/crypt(-v2) key file if * keys were not already embedded in the config file. */ - connection_entry_preload_key(&ce->tls_auth_file, - &ce->tls_auth_file_inline, &o->gc); - connection_entry_preload_key(&ce->tls_crypt_file, - &ce->tls_crypt_file_inline, &o->gc); - connection_entry_preload_key(&ce->tls_crypt_v2_file, - &ce->tls_crypt_v2_file_inline, &o->gc); + connection_entry_preload_key(&ce->tls_auth_file, &ce->tls_auth_file_in= line, &o->gc); + connection_entry_preload_key(&ce->tls_crypt_file, &ce->tls_crypt_file_= inline, &o->gc); + 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) @@ -3106,10 +3097,8 @@ static void remap_redirect_gateway_flags(struct options *opt) { - if (opt->routes - && opt->route_method =3D=3D ROUTE_METHOD_SERVICE - && opt->routes->flags & RG_REROUTE_GW - && !(opt->routes->flags & RG_DEF1)) + if (opt->routes && opt->route_method =3D=3D ROUTE_METHOD_SERVICE + && opt->routes->flags & RG_REROUTE_GW && !(opt->routes->flags & RG= _DEF1)) { msg(M_INFO, "Flag 'def1' added to --redirect-gateway (iservice is = in use)"); opt->routes->flags |=3D RG_DEF1; @@ -3288,8 +3277,7 @@ /* If p11-kit is present on the system then load its p11-kit-proxy.so * by default if the user asks for PKCS#11 without otherwise specifying * the module to use. */ - if (!options->pkcs11_providers[0] - && (options->pkcs11_id || options->pkcs11_id_management)) + if (!options->pkcs11_providers[0] && (options->pkcs11_id || options->p= kcs11_id_management)) { options->pkcs11_providers[0] =3D DEFAULT_PKCS11_MODULE; } @@ -3317,8 +3305,8 @@ if (dco_enabled(o) && o->enable_c2c) { msg(M_WARN, "Note: --client-to-client has no effect when using dat= a " - "channel offload: packets are always sent to the VPN " - "interface and then routed based on the system routing table"); + "channel offload: packets are always sent to the VPN " + "interface and then routed based on the system routing= table"); } } @@ -3348,17 +3336,19 @@ * parts of OpenVPN assert that the ciphername is set */ o->ciphername =3D "BF-CBC"; - msg(M_INFO, "Note: --cipher is not set. OpenVPN versions before 2.= 5 " + msg(M_INFO, + "Note: --cipher is not set. OpenVPN versions before 2.5 " "defaulted to BF-CBC as fallback when cipher negotiation " "failed in this case. If you need this fallback please add " "'--data-ciphers-fallback BF-CBC' to your configuration " "and/or add BF-CBC to --data-ciphers. E.g. " - "--data-ciphers %s:BF-CBC", o->ncp_ciphers_conf); + "--data-ciphers %s:BF-CBC", + o->ncp_ciphers_conf); } - else if (!o->enable_ncp_fallback - && !tls_item_in_cipher_list(o->ciphername, o->ncp_ciphers)) + else if (!o->enable_ncp_fallback && !tls_item_in_cipher_list(o->cipher= name, o->ncp_ciphers)) { - msg(M_WARN, "DEPRECATED OPTION: --cipher set to '%s' but missing i= n " + msg(M_WARN, + "DEPRECATED OPTION: --cipher set to '%s' but missing in " "--data-ciphers (%s). OpenVPN ignores --cipher for cipher " "negotiations. ", o->ciphername, o->ncp_ciphers_conf); @@ -3394,12 +3384,10 @@ options_set_backwards_compatible_options(struct options *o) { /* TLS min version is not set */ - int tls_ver_min =3D (o->ssl_flags >> SSLF_TLS_VERSION_MIN_SHIFT) - & SSLF_TLS_VERSION_MIN_MASK; + int tls_ver_min =3D (o->ssl_flags >> SSLF_TLS_VERSION_MIN_SHIFT) & SSL= F_TLS_VERSION_MIN_MASK; if (tls_ver_min =3D=3D 0) { - int tls_ver_max =3D (o->ssl_flags >> SSLF_TLS_VERSION_MAX_SHIFT) - & SSLF_TLS_VERSION_MAX_MASK; + int tls_ver_max =3D (o->ssl_flags >> SSLF_TLS_VERSION_MAX_SHIFT) &= SSLF_TLS_VERSION_MAX_MASK; if (need_compatibility_before(o, 20307)) { /* 2.3.6 and earlier have TLS 1.0 only, set minimum to TLS 1.0= */ @@ -3455,7 +3443,7 @@ o->comp.flags =3D COMP_F_ALLOW_STUB_ONLY | COMP_F_ADVERTISE_ST= UBS_ONLY; } } -#else /* ifdef USE_COMP */ +#else /* ifdef USE_COMP */ o->comp.flags =3D COMP_F_ALLOW_NOCOMP_ONLY; #endif } @@ -3466,17 +3454,16 @@ if (!check_tls_prf_working()) { msg(D_TLS_ERRORS, "Warning: TLS 1.0 PRF with MD5+SHA1 PRF is not " - "supported by the TLS library. Your system does not support th= is " - "calculation anymore or your security policy (e.g. FIPS 140-2)= " - "forbids it. Connections will only work with peers running " - "OpenVPN 2.6.0 or higher)"); + "supported by the TLS library. Your system does = not support this " + "calculation anymore or your security policy (e.= g. FIPS 140-2) " + "forbids it. Connections will only work with pee= rs running " + "OpenVPN 2.6.0 or higher)"); if (o->mode =3D=3D MODE_SERVER) { msg(M_WARN, "Automatically enabling option " - "--force-tls-key-material-export"); + "--force-tls-key-material-export"); o->force_key_material_export =3D true; } - } } @@ -3521,9 +3508,9 @@ #if defined(_WIN32) if (tt->ip_win32_type !=3D IPW32_SET_DHCP_MASQ && tt->ip_win32_type != =3D IPW32_SET_ADAPTIVE) { - return; /* Not in DHCP mode */ + return; /* Not in DHCP mode */ } -#endif /* if defined(_WIN32) */ +#endif /* if defined(_WIN32) */ /* Copy --dns options to tuntap_options */ @@ -3559,8 +3546,7 @@ } } if ((s->transport && s->transport !=3D DNS_TRANSPORT_PLAIN) - || (s->dnssec && s->dnssec !=3D DNS_SECURITY_NO) - || non_standard_server_port) + || (s->dnssec && s->dnssec !=3D DNS_SECURITY_NO) || non_standa= rd_server_port) { /* Skip servers requiring unsupported config to be set */ s =3D s->next; @@ -3593,7 +3579,7 @@ } } -#else /* if defined(_WIN32) || defined(TARGET_ANDROID) */ +#else /* if defined(_WIN32) || defined(TARGET_ANDROID) */ /** * @brief Postprocess DNS related settings @@ -3715,8 +3701,7 @@ } } if ((s->transport && s->transport !=3D DNS_TRANSPORT_PLAIN) - || (s->dnssec && s->dnssec !=3D DNS_SECURITY_NO) - || non_standard_server_port) + || (s->dnssec && s->dnssec !=3D DNS_SECURITY_NO) || non_st= andard_server_port) { /* Skip servers requiring unsupported config to be set */ s =3D s->next; @@ -3852,7 +3837,7 @@ { /* DH file is only meaningful in a tls-server context. */ msg(M_WARN, "WARNING: Ignoring option 'dh' in tls-client mode, ple= ase only " - "include this in your server configuration"); + "include this in your server configuration"); o->dh_file =3D NULL; } #if ENABLE_MANAGEMENT @@ -3861,25 +3846,23 @@ options_postprocess_http_proxy_override(o); } #endif - if (!o->ca_file && !o->ca_path && o->verify_hash - && o->verify_hash_depth =3D=3D 0) + if (!o->ca_file && !o->ca_path && o->verify_hash && o->verify_hash_dep= th =3D=3D 0) { msg(M_INFO, "Using certificate fingerprint to verify peer (no CA " - "option set). "); + "option set). "); o->verify_hash_no_ca =3D true; } if (o->config && streq(o->config, "stdin") && o->remap_sigusr1 =3D=3D = SIGHUP) { msg(M_USAGE, "Options 'config stdin' and 'remap-usr1 SIGHUP' are " - "incompatible with each other."); + "incompatible with each other."); } if (dco_enabled(o)) { /* check if any option should force disabling DCO */ - o->disable_dco =3D !dco_check_option(D_DCO, o) - || !dco_check_startup_option(D_DCO, o); + o->disable_dco =3D !dco_check_option(D_DCO, o) || !dco_check_start= up_option(D_DCO, o); } #ifdef USE_COMP if (dco_enabled(o)) @@ -3897,7 +3880,8 @@ { if (o->windows_driver =3D=3D DRIVER_DCO) { - msg(M_WARN, "Option --windows-driver ovpn-dco is ignored becau= se Data Channel Offload is disabled"); + msg(M_WARN, + "Option --windows-driver ovpn-dco is ignored because Data = Channel Offload is disabled"); o->windows_driver =3D WINDOWS_DRIVER_TAP_WINDOWS6; } else if (o->windows_driver =3D=3D WINDOWS_DRIVER_UNSPECIFIED) @@ -3909,7 +3893,7 @@ if (dco_enabled(o) && o->dev_node) { msg(M_WARN, "Note: ignoring --dev-node as it has no effect when us= ing " - "data channel offload"); + "data channel offload"); o->dev_node =3D NULL; } #endif /* _WIN32 */ @@ -3947,14 +3931,14 @@ * Check file/directory sanity * */ -#ifndef ENABLE_SMALL /* Expect people using the stripped down version to = know what they do */ +#ifndef ENABLE_SMALL /* Expect people using the stripped down version to k= now what they do */ -#define CHKACC_FILE (1<<0) /**< Check for a file/directory presence = */ -#define CHKACC_DIRPATH (1<<1) /**< Check for directory presence where a= file should reside */ -#define CHKACC_FILEXSTWR (1<<2) /**< If file exists, is it writable? */ -#define CHKACC_ACPTSTDIN (1<<3) /**< If filename is stdin, it's allowed a= nd "exists" */ -#define CHKACC_PRIVATE (1<<4) /**< Warn if this (private) file is group= /others accessible */ -#define CHKACC_ACCEPT_URI (1<<5) /**< Do not check URIs, unless they start= with file: */ +#define CHKACC_FILE (1 << 0) /**< Check for a file/directory presenc= e */ +#define CHKACC_DIRPATH (1 << 1) /**< Check for directory presence where= a file should reside */ +#define CHKACC_FILEXSTWR (1 << 2) /**< If file exists, is it writable? */ +#define CHKACC_ACPTSTDIN (1 << 3) /**< If filename is stdin, it's allowed= and "exists" */ +#define CHKACC_PRIVATE (1 << 4) /**< Warn if this (private) file is gro= up/others accessible */ +#define CHKACC_ACCEPT_URI (1 << 5) /**< Do not check URIs, unless they sta= rt with file: */ static bool check_file_access(const int type, const char *file, const int mode, const = char *opt) @@ -3970,7 +3954,7 @@ /* If stdin is allowed and the file name is 'stdin', then do no * further checks as stdin is always available */ - if ( (type & CHKACC_ACPTSTDIN) && streq(file, "stdin") ) + if ((type & CHKACC_ACPTSTDIN) && streq(file, "stdin")) { return false; } @@ -3993,10 +3977,11 @@ /* Is the directory path leading to the given file accessible? */ if (type & CHKACC_DIRPATH) { - char *fullpath =3D string_alloc(file, NULL); /* POSIX dirname() im= plementation may modify its arguments */ + char *fullpath =3D + string_alloc(file, NULL); /* POSIX dirname() implementation ma= y modify its arguments */ char *dirpath =3D dirname(fullpath); - if (platform_access(dirpath, mode|X_OK) !=3D 0) + if (platform_access(dirpath, mode | X_OK) !=3D 0) { errcode =3D errno; } @@ -4004,13 +3989,13 @@ } /* Is the file itself accessible? */ - if (!errcode && (type & CHKACC_FILE) && (platform_access(file, mode) != =3D 0) ) + if (!errcode && (type & CHKACC_FILE) && (platform_access(file, mode) != =3D 0)) { errcode =3D errno; } /* If the file exists and is accessible, is it writable? */ - if (!errcode && (type & CHKACC_FILEXSTWR) && (platform_access(file, F_= OK) =3D=3D 0) ) + if (!errcode && (type & CHKACC_FILEXSTWR) && (platform_access(file, F_= OK) =3D=3D 0)) { if (platform_access(file, W_OK) !=3D 0) { @@ -4029,7 +4014,7 @@ #ifndef _WIN32 else { - if (st.st_mode & (S_IRWXG|S_IRWXO)) + if (st.st_mode & (S_IRWXG | S_IRWXO)) { msg(M_WARN, "WARNING: file '%s' is group or others accessi= ble", file); } @@ -4052,7 +4037,8 @@ * otherwise it will look for the file inside the given chroot directory i= nstead. */ static bool -check_file_access_chroot(const char *chroot, const int type, const char *f= ile, const int mode, const char *opt) +check_file_access_chroot(const char *chroot, const int type, const char *f= ile, const int mode, + const char *opt) { bool ret =3D false; @@ -4085,9 +4071,8 @@ * the file is inline (and therefore there is no access to check) */ static bool -check_file_access_chroot_inline(bool is_inline, const char *chroot, - const int type, const char *file, - const int mode, const char *opt) +check_file_access_chroot_inline(bool is_inline, const char *chroot, const = int type, + const char *file, const int mode, const ch= ar *opt) { if (is_inline) { @@ -4102,8 +4087,8 @@ * is inline (and therefore there is no access to check) */ static bool -check_file_access_inline(bool is_inline, const int type, const char *file, - const int mode, const char *opt) +check_file_access_inline(bool is_inline, const int type, const char *file,= const int mode, + const char *opt) { if (is_inline) { @@ -4156,8 +4141,7 @@ } else { - msg(M_NOPREFIX|M_OPTERR, "%s fails with '%s': No path to executabl= e.", - opt, command); + msg(M_NOPREFIX | M_OPTERR, "%s fails with '%s': No path to executa= ble.", opt, command); return_code =3D true; } @@ -4176,55 +4160,51 @@ bool errs =3D false; /* ** SSL/TLS/crypto related files ** */ - errs |=3D check_file_access_inline(options->dh_file_inline, CHKACC_FIL= E, - options->dh_file, R_OK, "--dh"); + errs |=3D check_file_access_inline(options->dh_file_inline, CHKACC_FIL= E, options->dh_file, R_OK, + "--dh"); if (!options->verify_hash_no_ca) { - errs |=3D check_file_access_inline(options->ca_file_inline, CHKACC= _FILE, - options->ca_file, R_OK, "--ca"); + errs |=3D check_file_access_inline(options->ca_file_inline, CHKACC= _FILE, options->ca_file, + R_OK, "--ca"); } - errs |=3D check_file_access_chroot(options->chroot_dir, CHKACC_FILE, - options->ca_path, R_OK, "--capath"); + errs |=3D check_file_access_chroot(options->chroot_dir, CHKACC_FILE, o= ptions->ca_path, R_OK, + "--capath"); - errs |=3D check_file_access_inline(options->cert_file_inline, CHKACC_F= ILE|CHKACC_ACCEPT_URI, + errs |=3D check_file_access_inline(options->cert_file_inline, CHKACC_F= ILE | CHKACC_ACCEPT_URI, options->cert_file, R_OK, "--cert"); errs |=3D check_file_access_inline(options->extra_certs_file, CHKACC_F= ILE, - options->extra_certs_file, R_OK, - "--extra-certs"); + options->extra_certs_file, R_OK, "--e= xtra-certs"); if (!(options->management_flags & MF_EXTERNAL_KEY)) { errs |=3D check_file_access_inline(options->priv_key_file_inline, - CHKACC_FILE|CHKACC_PRIVATE|CHKACC= _ACCEPT_URI, + CHKACC_FILE | CHKACC_PRIVATE | CH= KACC_ACCEPT_URI, options->priv_key_file, R_OK, "--= key"); } - errs |=3D check_file_access_inline(options->pkcs12_file_inline, - CHKACC_FILE|CHKACC_PRIVATE, + errs |=3D check_file_access_inline(options->pkcs12_file_inline, CHKACC= _FILE | CHKACC_PRIVATE, options->pkcs12_file, R_OK, "--pkcs12= "); if (options->ssl_flags & SSLF_CRL_VERIFY_DIR) { - errs |=3D check_file_access_chroot(options->chroot_dir, CHKACC_FIL= E, - options->crl_file, R_OK|X_OK, - "--crl-verify directory"); + errs |=3D check_file_access_chroot(options->chroot_dir, CHKACC_FIL= E, options->crl_file, + R_OK | X_OK, "--crl-verify direct= ory"); } else { - errs |=3D check_file_access_chroot_inline(options->crl_file_inline, - options->chroot_dir, - CHKACC_FILE, options->crl_= file, - R_OK, "--crl-verify"); + errs |=3D + check_file_access_chroot_inline(options->crl_file_inline, opti= ons->chroot_dir, + CHKACC_FILE, options->crl_file= , R_OK, "--crl-verify"); } if (options->tls_export_peer_cert_dir) { - errs |=3D check_file_access_chroot(options->chroot_dir, CHKACC_FIL= E, - options->tls_export_peer_cert_dir, - W_OK, "--tls-export-cert"); + errs |=3D + check_file_access_chroot(options->chroot_dir, CHKACC_FILE, + options->tls_export_peer_cert_dir, W_= OK, "--tls-export-cert"); } ASSERT(options->connection_list); @@ -4232,55 +4212,46 @@ { struct connection_entry *ce =3D options->connection_list->array[i]; - errs |=3D check_file_access_inline(ce->tls_auth_file_inline, - CHKACC_FILE|CHKACC_PRIVATE, - ce->tls_auth_file, R_OK, - "--tls-auth"); - errs |=3D check_file_access_inline(ce->tls_crypt_file_inline, - CHKACC_FILE|CHKACC_PRIVATE, - ce->tls_crypt_file, R_OK, - "--tls-crypt"); - errs |=3D check_file_access_inline(ce->tls_crypt_v2_file_inline, - CHKACC_FILE|CHKACC_PRIVATE, - ce->tls_crypt_v2_file, R_OK, - "--tls-crypt-v2"); + errs |=3D check_file_access_inline(ce->tls_auth_file_inline, CHKAC= C_FILE | CHKACC_PRIVATE, + ce->tls_auth_file, R_OK, "--tls-a= uth"); + errs |=3D check_file_access_inline(ce->tls_crypt_file_inline, CHKA= CC_FILE | CHKACC_PRIVATE, + ce->tls_crypt_file, R_OK, "--tls-= crypt"); + errs |=3D check_file_access_inline(ce->tls_crypt_v2_file_inline, C= HKACC_FILE | CHKACC_PRIVATE, + ce->tls_crypt_v2_file, R_OK, "--t= ls-crypt-v2"); } - errs |=3D check_file_access_inline(options->shared_secret_file_inline, - CHKACC_FILE|CHKACC_PRIVATE, - options->shared_secret_file, R_OK, - "--secret"); + errs |=3D + check_file_access_inline(options->shared_secret_file_inline, CHKAC= C_FILE | CHKACC_PRIVATE, + options->shared_secret_file, R_OK, "--sec= ret"); - errs |=3D check_file_access(CHKACC_DIRPATH|CHKACC_FILEXSTWR, - options->packet_id_file, R_OK|W_OK, "--repla= y-persist"); + errs |=3D check_file_access(CHKACC_DIRPATH | CHKACC_FILEXSTWR, options= ->packet_id_file, + R_OK | W_OK, "--replay-persist"); /* ** Password files ** */ - errs |=3D check_file_access(CHKACC_FILE|CHKACC_ACPTSTDIN|CHKACC_PRIVAT= E, + errs |=3D check_file_access(CHKACC_FILE | CHKACC_ACPTSTDIN | CHKACC_PR= IVATE, options->key_pass_file, R_OK, "--askpass"); #ifdef ENABLE_MANAGEMENT - errs |=3D check_file_access(CHKACC_FILE|CHKACC_ACPTSTDIN|CHKACC_PRIVAT= E, - options->management_user_pass, R_OK, - "--management user/password file"); + errs |=3D + check_file_access(CHKACC_FILE | CHKACC_ACPTSTDIN | CHKACC_PRIVATE, + options->management_user_pass, R_OK, "--manageme= nt user/password file"); #endif /* ENABLE_MANAGEMENT */ errs |=3D check_file_access_inline(options->auth_user_pass_file_inline, - CHKACC_FILE|CHKACC_ACPTSTDIN|CHKACC_P= RIVATE, - options->auth_user_pass_file, R_OK, - "--auth-user-pass"); + CHKACC_FILE | CHKACC_ACPTSTDIN | CHKA= CC_PRIVATE, + options->auth_user_pass_file, R_OK, "= --auth-user-pass"); /* ** System related ** */ - errs |=3D check_file_access(CHKACC_FILE, options->chroot_dir, - R_OK|X_OK, "--chroot directory"); - errs |=3D check_file_access(CHKACC_DIRPATH|CHKACC_FILEXSTWR, options->= writepid, - R_OK|W_OK, "--writepid"); + errs |=3D check_file_access(CHKACC_FILE, options->chroot_dir, R_OK | X= _OK, "--chroot directory"); + errs |=3D check_file_access(CHKACC_DIRPATH | CHKACC_FILEXSTWR, options= ->writepid, R_OK | W_OK, + "--writepid"); /* ** Log related ** */ - errs |=3D check_file_access(CHKACC_DIRPATH|CHKACC_FILEXSTWR, options->= status_file, - R_OK|W_OK, "--status"); + errs |=3D check_file_access(CHKACC_DIRPATH | CHKACC_FILEXSTWR, options= ->status_file, R_OK | W_OK, + "--status"); /* ** Config related ** */ errs |=3D check_file_access_chroot(options->chroot_dir, CHKACC_FILE, o= ptions->client_config_dir, - R_OK|X_OK, "--client-config-dir"); + R_OK | X_OK, "--client-config-dir"); errs |=3D check_file_access_chroot(options->chroot_dir, CHKACC_FILE, o= ptions->tmp_dir, - R_OK|W_OK|X_OK, "Temporary directory = (--tmp-dir)"); + R_OK | W_OK | X_OK, "Temporary direct= ory (--tmp-dir)"); if (errs) { @@ -4366,12 +4337,8 @@ * the other end of the connection] */ char * -options_string(const struct options *o, - const struct frame *frame, - struct tuntap *tt, - openvpn_net_ctx_t *ctx, - bool remote, - struct gc_arena *gc) +options_string(const struct options *o, const struct frame *frame, struct = tuntap *tt, + openvpn_net_ctx_t *ctx, bool remote, struct gc_arena *gc) { struct buffer out =3D alloc_buf(OPTION_LINE_SIZE); bool tt_local =3D false; @@ -4387,8 +4354,7 @@ * cipher (p2p) or have a fallback cipher configured for older non * ncp clients. But not sending it will make even 2.4 complain * about it being missing. So still send it. */ - buf_printf(&out, ",link-mtu %u", - (unsigned int) calc_options_string_link_mtu(o, frame)); + buf_printf(&out, ",link-mtu %u", (unsigned int)calc_options_string_lin= k_mtu(o, frame)); if (o->ce.occ_mtu !=3D 0) { @@ -4399,7 +4365,7 @@ buf_printf(&out, ",tun-mtu %d", frame->tun_mtu); } - buf_printf(&out, ",proto %s", proto_remote(o->ce.proto, remote)); + buf_printf(&out, ",proto %s", proto_remote(o->ce.proto, remote)); bool p2p_nopull =3D o->mode =3D=3D MODE_POINT_TO_POINT && !PULL_DEFINE= D(o); /* send tun_ipv6 only in peer2peer mode - in client/server mode, it @@ -4416,20 +4382,9 @@ */ if (!tt) { - tt =3D init_tun(o->dev, - o->dev_type, - o->topology, - o->ifconfig_local, - o->ifconfig_remote_netmask, - o->ifconfig_ipv6_local, - o->ifconfig_ipv6_netbits, - o->ifconfig_ipv6_remote, - NULL, - NULL, - false, - NULL, - ctx, - NULL); + tt =3D init_tun(o->dev, o->dev_type, o->topology, o->ifconfig_loca= l, + o->ifconfig_remote_netmask, o->ifconfig_ipv6_local, = o->ifconfig_ipv6_netbits, + o->ifconfig_ipv6_remote, NULL, NULL, false, NULL, ct= x, NULL); if (tt) { tt_local =3D true; @@ -4453,7 +4408,8 @@ #ifdef USE_COMP if (o->comp.alg !=3D COMP_ALG_UNDEF) { - buf_printf(&out, ",comp-lzo"); /* for compatibility, this simply i= ndicates that compression context is active, not necessarily LZO per-se */ + buf_printf(&out, ",comp-lzo"); /* for compatibility, this simply i= ndicates that compression + context is active, not necessari= ly LZO per-se */ } #endif @@ -4485,10 +4441,7 @@ { struct key_type kt; - ASSERT((o->shared_secret_file !=3D NULL) - + (TLS_CLIENT =3D=3D true) - + (TLS_SERVER =3D=3D true) - <=3D 1); + ASSERT((o->shared_secret_file !=3D NULL) + (TLS_CLIENT =3D=3D true= ) + (TLS_SERVER =3D=3D true) <=3D 1); /* Skip resolving BF-CBC to allow SSL libraries without BF-CBC * to work here in the default configuration */ @@ -4597,8 +4550,7 @@ } static const char * -options_warning_extract_parm1(const char *option_string, - struct gc_arena *gc_ret) +options_warning_extract_parm1(const char *option_string, struct gc_arena *= gc_ret) { struct gc_arena gc =3D gc_new(); struct buffer b =3D string_alloc_buf(option_string, &gc); @@ -4612,24 +4564,16 @@ } static void -options_warning_safe_scan2(const int msglevel, - const int delim, - const bool report_inconsistent, - const char *p1, - const struct buffer *b2_src, - const char *b1_name, +options_warning_safe_scan2(const int msglevel, const int delim, const bool= report_inconsistent, + const char *p1, const struct buffer *b2_src, co= nst char *b1_name, const char *b2_name) { /* We will stop sending 'key-method', 'keydir', 'proto' and 'tls-auth'= in * OCC in a future version (because it's not useful). To reduce questi= ons * when interoperating, we no longer printing a warning about it. */ - if (strprefix(p1, "key-method ") - || strprefix(p1, "keydir ") - || strprefix(p1, "proto ") - || streq(p1, "tls-auth") - || strprefix(p1, "tun-ipv6") - || strprefix(p1, "cipher ")) + if (strprefix(p1, "key-method ") || strprefix(p1, "keydir ") || strpre= fix(p1, "proto ") + || streq(p1, "tls-auth") || strprefix(p1, "tun-ipv6") || strprefix= (p1, "cipher ")) { return; } @@ -4656,10 +4600,7 @@ if (report_inconsistent) { msg(msglevel, "WARNING: '%s' is used inconsistentl= y, %s=3D'%s', %s=3D'%s'", - safe_print(p1_prefix, &gc), - b1_name, - safe_print(p1, &gc), - b2_name, + safe_print(p1_prefix, &gc), b1_name, safe_prin= t(p1, &gc), b2_name, safe_print(p2, &gc)); } goto done; @@ -4668,11 +4609,7 @@ } msg(msglevel, "WARNING: '%s' is present in %s config but missing i= n %s config, %s=3D'%s'", - safe_print(p1_prefix, &gc), - b1_name, - b2_name, - b1_name, - safe_print(p1, &gc)); + safe_print(p1_prefix, &gc), b1_name, b2_name, b1_name, safe_pr= int(p1, &gc)); done: gc_free(&gc); @@ -4680,13 +4617,9 @@ } static void -options_warning_safe_scan1(const int msglevel, - const int delim, - const bool report_inconsistent, - const struct buffer *b1_src, - const struct buffer *b2_src, - const char *b1_name, - const char *b2_name) +options_warning_safe_scan1(const int msglevel, const int delim, const bool= report_inconsistent, + const struct buffer *b1_src, const struct buffe= r *b2_src, + const char *b1_name, const char *b2_name) { struct gc_arena gc =3D gc_new(); struct buffer b =3D *b1_src; @@ -4694,7 +4627,8 @@ while (buf_parse(&b, delim, p, OPTION_PARM_SIZE)) { - options_warning_safe_scan2(msglevel, delim, report_inconsistent, p= , b2_src, b1_name, b2_name); + options_warning_safe_scan2(msglevel, delim, report_inconsistent, p= , b2_src, b1_name, + b2_name); } gc_free(&gc); @@ -4714,13 +4648,9 @@ buf_printf(&local, "version %s", expected); buf_printf(&remote, "version %s", actual); - options_warning_safe_scan1(msglevel, ',', true, - &local, &remote, - "local", "remote"); + options_warning_safe_scan1(msglevel, ',', true, &local, &remote, "= local", "remote"); - options_warning_safe_scan1(msglevel, ',', false, - &remote, &local, - "remote", "local"); + options_warning_safe_scan1(msglevel, ',', false, &remote, &local, = "remote", "local"); } gc_free(&gc); @@ -4759,13 +4689,12 @@ options_string_version(const char *s, struct gc_arena *gc) { struct buffer out =3D alloc_buf_gc(4, gc); - strncpynt((char *) BPTR(&out), s, 3); + strncpynt((char *)BPTR(&out), s, 3); return BSTR(&out); } char * -options_string_extract_option(const char *options_string, const char *opt_= name, - struct gc_arena *gc) +options_string_extract_option(const char *options_string, const char *opt_= name, struct gc_arena *gc) { char *ret =3D NULL; const size_t opt_name_len =3D strlen(opt_name); @@ -4773,14 +4702,14 @@ const char *p =3D options_string; while (p) { - if (0 =3D=3D strncmp(p, opt_name, opt_name_len) - && strlen(p) > (opt_name_len+1) && p[opt_name_len] =3D=3D ' ') + if (0 =3D=3D strncmp(p, opt_name, opt_name_len) && strlen(p) > (op= t_name_len + 1) + && p[opt_name_len] =3D=3D ' ') { /* option found, extract value */ - const char *start =3D &p[opt_name_len+1]; + const char *start =3D &p[opt_name_len + 1]; const char *end =3D strchr(p, ','); size_t val_len =3D end ? end - start : strlen(start); - ret =3D gc_malloc(val_len+1, true, gc); + ret =3D gc_malloc(val_len + 1, true, gc); memcpy(ret, start, val_len); break; } @@ -4912,20 +4841,13 @@ struct options o; init_options(&o, true); - fprintf(fp, usage_message, - title_string, - o.ce.connect_retry_seconds, - o.ce.connect_retry_seconds_max, - o.ce.local_port, o.ce.remote_port, - TUN_MTU_DEFAULT, TAP_MTU_EXTRA_DEFAULT, - o.verbosity, - o.authname, - o.replay_window, o.replay_time, - o.tls_timeout, o.renegotiate_seconds, - o.handshake_window, o.transition_window); + fprintf(fp, usage_message, title_string, o.ce.connect_retry_seconds, + o.ce.connect_retry_seconds_max, o.ce.local_port, o.ce.remote_p= ort, TUN_MTU_DEFAULT, + TAP_MTU_EXTRA_DEFAULT, o.verbosity, o.authname, o.replay_windo= w, o.replay_time, + o.tls_timeout, o.renegotiate_seconds, o.handshake_window, o.tr= ansition_window); fflush(fp); -#endif /* ENABLE_SMALL */ +#endif /* ENABLE_SMALL */ openvpn_exit(OPENVPN_EXIT_STATUS_USAGE); /* exit point */ } @@ -4933,7 +4855,7 @@ void usage_small(void) { - msg(M_WARN|M_NOPREFIX, "Use --help for more information."); + msg(M_WARN | M_NOPREFIX, "Use --help for more information."); openvpn_exit(OPENVPN_EXIT_STATUS_USAGE); /* exit point */ } @@ -4966,8 +4888,7 @@ #define LZO_LIB_VER_STR "", "" #endif - msg(flags, "library versions: %s%s%s", get_ssl_library_version(), - LZO_LIB_VER_STR); + msg(flags, "library versions: %s%s%s", get_ssl_library_version(), LZO_= LIB_VER_STR); #undef LZO_LIB_VER_STR } @@ -4975,20 +4896,20 @@ static void usage_version(void) { - msg(M_INFO|M_NOPREFIX, "%s", title_string); - show_library_versions( M_INFO|M_NOPREFIX ); + msg(M_INFO | M_NOPREFIX, "%s", title_string); + show_library_versions(M_INFO | M_NOPREFIX); #ifdef _WIN32 - show_windows_version( M_INFO|M_NOPREFIX ); + show_windows_version(M_INFO | M_NOPREFIX); #endif show_dco_version(M_INFO | M_NOPREFIX); - msg(M_INFO|M_NOPREFIX, "Originally developed by James Yonan"); - msg(M_INFO|M_NOPREFIX, "Copyright (C) 2002-2025 OpenVPN Inc "); + msg(M_INFO | M_NOPREFIX, "Originally developed by James Yonan"); + msg(M_INFO | M_NOPREFIX, "Copyright (C) 2002-2025 OpenVPN Inc "); #ifndef ENABLE_SMALL #ifdef CONFIGURE_DEFINES - msg(M_INFO|M_NOPREFIX, "Compile time defines: %s", CONFIGURE_DEFINES); + msg(M_INFO | M_NOPREFIX, "Compile time defines: %s", CONFIGURE_DEFINES= ); #endif #ifdef CONFIGURE_SPECIAL_BUILD - msg(M_INFO|M_NOPREFIX, "special build: %s", CONFIGURE_SPECIAL_BUILD); + msg(M_INFO | M_NOPREFIX, "special build: %s", CONFIGURE_SPECIAL_BUILD); #endif #endif openvpn_exit(OPENVPN_EXIT_STATUS_GOOD); @@ -5024,7 +4945,7 @@ } #endif -#ifdef _WIN32 /* This function is only used when compiling on Windows */ +#ifdef _WIN32 /* This function is only used when compiling on Windows */ static unsigned int atou(const char *str) { @@ -5041,13 +4962,8 @@ } int -parse_line(const char *line, - char *p[], - const int n, - const char *file, - const int line_num, - int msglevel, - struct gc_arena *gc) +parse_line(const char *line, char *p[], const int n, const char *file, con= st int line_num, + int msglevel, struct gc_arena *gc) { const int STATE_INITIAL =3D 0; const int STATE_READING_QUOTED_PARM =3D 1; @@ -5156,9 +5072,13 @@ if (!(out =3D=3D '\\' || out =3D=3D '\"' || space(out))) { #ifdef ENABLE_SMALL - msg(msglevel, "%sOptions warning: Bad backslash ('\\')= usage in %s:%d", error_prefix, file, line_num); + msg(msglevel, "%sOptions warning: Bad backslash ('\\')= usage in %s:%d", + error_prefix, file, line_num); #else - msg(msglevel, "%sOptions warning: Bad backslash ('\\')= usage in %s:%d: remember that backslashes are treated as shell-escapes and= if you need to pass backslash characters as part of a Windows filename, yo= u should use double backslashes such as \"c:\\\\" PACKAGE "\\\\static.key\"= ", error_prefix, file, line_num); + msg(msglevel, + "%sOptions warning: Bad backslash ('\\') usage in = %s:%d: remember that backslashes are treated as shell-escapes and if you ne= ed to pass backslash characters as part of a Windows filename, you should u= se double backslashes such as \"c:\\\\" PACKAGE + "\\\\static.key\"", + error_prefix, file, line_num); #endif return 0; } @@ -5173,7 +5093,7 @@ { parm[SIZE(parm) - 1] =3D 0; msg(msglevel, "%sOptions error: Parameter at %s:%d is too = long (%d chars max): %s", - error_prefix, file, line_num, (int) SIZE(parm), parm); + error_prefix, file, line_num, (int)SIZE(parm), parm); return 0; } parm[parm_len++] =3D out; @@ -5189,17 +5109,20 @@ if (state =3D=3D STATE_READING_QUOTED_PARM) { - msg(msglevel, "%sOptions error: No closing quotation (\") in %s:%d= ", error_prefix, file, line_num); + msg(msglevel, "%sOptions error: No closing quotation (\") in %s:%d= ", error_prefix, file, + line_num); return 0; } if (state =3D=3D STATE_READING_SQUOTED_PARM) { - msg(msglevel, "%sOptions error: No closing single quotation (\') i= n %s:%d", error_prefix, file, line_num); + msg(msglevel, "%sOptions error: No closing single quotation (\') i= n %s:%d", error_prefix, + file, line_num); return 0; } if (state !=3D STATE_INITIAL) { - msg(msglevel, "%sOptions error: Residual parse state (%d) in %s:%d= ", error_prefix, state, file, line_num); + msg(msglevel, "%sOptions error: Residual parse state (%d) in %s:%d= ", error_prefix, state, + file, line_num); return 0; } #if 0 @@ -5223,11 +5146,13 @@ } } -struct in_src { -#define IS_TYPE_FP 1 +struct in_src +{ +#define IS_TYPE_FP 1 #define IS_TYPE_BUF 2 int type; - union { + union + { FILE *fp; struct buffer *multiline; } u; @@ -5243,7 +5168,7 @@ else if (is->type =3D=3D IS_TYPE_BUF) { bool status =3D buf_parse(is->u.multiline, '\n', line, size); - if ((int) strlen(line) + 1 < size) + if ((int)strlen(line) + 1 < size) { strcat(line, "\n"); } @@ -5257,11 +5182,10 @@ } static char * -read_inline_file(struct in_src *is, const char *close_tag, - int *num_lines, struct gc_arena *gc) +read_inline_file(struct in_src *is, const char *close_tag, int *num_lines,= struct gc_arena *gc) { char line[OPTION_LINE_SIZE]; - struct buffer buf =3D alloc_buf(8*OPTION_LINE_SIZE); + struct buffer buf =3D alloc_buf(8 * OPTION_LINE_SIZE); char *ret; bool endtagfound =3D false; @@ -5279,7 +5203,7 @@ endtagfound =3D true; break; } - if (!buf_safe(&buf, strlen(line)+1)) + if (!buf_safe(&buf, strlen(line) + 1)) { /* Increase buffer size */ struct buffer buf2 =3D alloc_buf(buf.capacity * 2); @@ -5309,7 +5233,7 @@ if (p[0] && !p[1]) { char *arg =3D p[0]; - if (arg[0] =3D=3D '<' && arg[strlen(arg)-1] =3D=3D '>') + if (arg[0] =3D=3D '<' && arg[strlen(arg) - 1] =3D=3D '>') { struct buffer close_tag; @@ -5335,8 +5259,7 @@ } static int -check_inline_file_via_buf(struct buffer *multiline, char *p[], - struct gc_arena *gc) +check_inline_file_via_buf(struct buffer *multiline, char *p[], struct gc_a= rena *gc) { struct in_src is; is.type =3D IS_TYPE_BUF; @@ -5344,60 +5267,31 @@ return check_inline_file(&is, p, gc); } -static void -add_option(struct options *options, - char *p[], - bool is_inline, - const char *file, - int line, - const int level, - const int msglevel, - const unsigned int permission_mask, - unsigned int *option_types_found, - struct env_set *es); +static void add_option(struct options *options, char *p[], bool is_inline,= const char *file, + int line, const int level, const int msglevel, + const unsigned int permission_mask, unsigned int *o= ption_types_found, + struct env_set *es); + +static void remove_option(struct context *c, struct options *options, char= *p[], bool is_inline, + const char *file, int line, const int msglevel, + const unsigned int permission_mask, unsigned int= *option_types_found, + struct env_set *es); + +static void update_option(struct context *c, struct options *options, char= *p[], bool is_inline, + const char *file, int line, const int level, con= st int msglevel, + const unsigned int permission_mask, unsigned int= *option_types_found, + struct env_set *es, unsigned int *update_options= _found); static void -remove_option(struct context *c, - struct options *options, - char *p[], - bool is_inline, - const char *file, - int line, - const int msglevel, - const unsigned int permission_mask, - unsigned int *option_types_found, - struct env_set *es); - -static void -update_option(struct context *c, - struct options *options, - char *p[], - bool is_inline, - const char *file, - int line, - const int level, - const int msglevel, - const unsigned int permission_mask, - unsigned int *option_types_found, - struct env_set *es, - unsigned int *update_options_found); - -static void -read_config_file(struct options *options, - const char *file, - int level, - const char *top_file, - const int top_line, - const int msglevel, - const unsigned int permission_mask, - unsigned int *option_types_found, - struct env_set *es) +read_config_file(struct options *options, const char *file, int level, con= st char *top_file, + const int top_line, const int msglevel, const unsigned in= t permission_mask, + unsigned int *option_types_found, struct env_set *es) { const int max_recursive_levels =3D 10; FILE *fp; int line_num; - char line[OPTION_LINE_SIZE+1]; - char *p[MAX_PARMS+1]; + char line[OPTION_LINE_SIZE + 1]; + char *p[MAX_PARMS + 1]; ++level; if (level <=3D max_recursive_levels) @@ -5420,7 +5314,8 @@ ++line_num; if (strlen(line) =3D=3D OPTION_LINE_SIZE) { - msg(msglevel, "In %s:%d: Maximum option line length (%= d) exceeded, line starts with %s", + msg(msglevel, + "In %s:%d: Maximum option line length (%d) exceede= d, line starts with %s", file, line_num, OPTION_LINE_SIZE, line); } @@ -5429,13 +5324,13 @@ { offset =3D 3; } - if (parse_line(line + offset, p, SIZE(p)-1, file, line_num= , msglevel, &options->gc)) + if (parse_line(line + offset, p, SIZE(p) - 1, file, line_n= um, msglevel, + &options->gc)) { bypass_doubledash(&p[0]); int lines_inline =3D check_inline_file_via_fp(fp, p, &= options->gc); - add_option(options, p, lines_inline, file, line_num, l= evel, - msglevel, permission_mask, option_types_fou= nd, - es); + add_option(options, p, lines_inline, file, line_num, l= evel, msglevel, + permission_mask, option_types_found, es); line_num +=3D lines_inline; } } @@ -5446,25 +5341,24 @@ } else { - msg(msglevel, "In %s:%d: Error opening configuration file: %s"= , top_file, top_line, file); + msg(msglevel, "In %s:%d: Error opening configuration file: %s"= , top_file, top_line, + file); } } else { - msg(msglevel, "In %s:%d: Maximum recursive include levels exceeded= in include attempt of file %s -- probably you have a configuration file th= at tries to include itself.", top_file, top_line, file); + msg(msglevel, + "In %s:%d: Maximum recursive include levels exceeded in includ= e attempt of file %s -- probably you have a configuration file that tries t= o include itself.", + top_file, top_line, file); } secure_memzero(line, sizeof(line)); CLEAR(p); } static void -read_config_string(const char *prefix, - struct options *options, - const char *config, - const int msglevel, - const unsigned int permission_mask, - unsigned int *option_types_found, - struct env_set *es) +read_config_string(const char *prefix, struct options *options, const char= *config, + const int msglevel, const unsigned int permission_mask, + unsigned int *option_types_found, struct env_set *es) { char line[OPTION_LINE_SIZE]; struct buffer multiline; @@ -5474,15 +5368,15 @@ while (buf_parse(&multiline, '\n', line, sizeof(line))) { - char *p[MAX_PARMS+1]; + char *p[MAX_PARMS + 1]; CLEAR(p); ++line_num; - if (parse_line(line, p, SIZE(p)-1, prefix, line_num, msglevel, &op= tions->gc)) + if (parse_line(line, p, SIZE(p) - 1, prefix, line_num, msglevel, &= options->gc)) { bypass_doubledash(&p[0]); int lines_inline =3D check_inline_file_via_buf(&multiline, p, = &options->gc); - add_option(options, p, lines_inline, prefix, line_num, 0, msgl= evel, - permission_mask, option_types_found, es); + add_option(options, p, lines_inline, prefix, line_num, 0, msgl= evel, permission_mask, + option_types_found, es); line_num +=3D lines_inline; } CLEAR(p); @@ -5491,13 +5385,8 @@ } void -parse_argv(struct options *options, - const int argc, - char *argv[], - const int msglevel, - const unsigned int permission_mask, - unsigned int *option_types_found, - struct env_set *es) +parse_argv(struct options *options, const int argc, char *argv[], const in= t msglevel, + const unsigned int permission_mask, unsigned int *option_types_= found, struct env_set *es) { /* usage message */ if (argc <=3D 1) @@ -5508,24 +5397,26 @@ /* config filename specified only? */ if (argc =3D=3D 2 && strncmp(argv[1], "--", 2)) { - char *p[MAX_PARMS+1]; + char *p[MAX_PARMS + 1]; CLEAR(p); p[0] =3D "config"; p[1] =3D argv[1]; - add_option(options, p, false, NULL, 0, 0, msglevel, permission_mas= k, - option_types_found, es); + add_option(options, p, false, NULL, 0, 0, msglevel, permission_mas= k, option_types_found, + es); } else { /* parse command line */ for (int i =3D 1; i < argc; ++i) { - char *p[MAX_PARMS+1]; + char *p[MAX_PARMS + 1]; CLEAR(p); p[0] =3D argv[i]; if (strncmp(p[0], "--", 2)) { - msg(msglevel, "I'm trying to parse \"%s\" as an --option p= arameter but I don't see a leading '--'", p[0]); + msg(msglevel, + "I'm trying to parse \"%s\" as an --option parameter b= ut I don't see a leading '--'", + p[0]); } else { @@ -5548,31 +5439,27 @@ } } } - add_option(options, p, false, NULL, 0, 0, msglevel, permission= _mask, - option_types_found, es); + add_option(options, p, false, NULL, 0, 0, msglevel, permission= _mask, option_types_found, + es); i +=3D j - 1; } } } bool -apply_push_options(struct context *c, - struct options *options, - struct buffer *buf, - unsigned int permission_mask, - unsigned int *option_types_found, - struct env_set *es, - bool is_update) +apply_push_options(struct context *c, struct options *options, struct buff= er *buf, + unsigned int permission_mask, unsigned int *option_type= s_found, + struct env_set *es, bool is_update) { char line[OPTION_PARM_SIZE]; int line_num =3D 0; const char *file =3D "[PUSH-OPTIONS]"; - const int msglevel =3D D_PUSH_ERRORS|M_OPTERR; + const int msglevel =3D D_PUSH_ERRORS | M_OPTERR; unsigned int update_options_found =3D 0; while (buf_parse(buf, ',', line, sizeof(line))) { - char *p[MAX_PARMS+1]; + char *p[MAX_PARMS + 1]; CLEAR(p); ++line_num; unsigned int push_update_option_flags =3D 0; @@ -5602,22 +5489,22 @@ return false; /* Cause push/pull error and stop push processin= g */ } - if (parse_line(&line[i], p, SIZE(p)-1, file, line_num, msglevel, &= options->gc)) + if (parse_line(&line[i], p, SIZE(p) - 1, file, line_num, msglevel,= &options->gc)) { if (!is_update) { - add_option(options, p, false, file, line_num, 0, msglevel, - permission_mask, option_types_found, es); + add_option(options, p, false, file, line_num, 0, msglevel,= permission_mask, + option_types_found, es); } else if (push_update_option_flags & PUSH_OPT_TO_REMOVE) { - remove_option(c, options, p, false, file, line_num, msglev= el, - permission_mask, option_types_found, es); + remove_option(c, options, p, false, file, line_num, msglev= el, permission_mask, + option_types_found, es); } else { - update_option(c, options, p, false, file, line_num, 0, msg= level, - permission_mask, option_types_found, es, &up= date_options_found); + update_option(c, options, p, false, file, line_num, 0, msg= level, permission_mask, + option_types_found, es, &update_options_foun= d); } } } @@ -5625,54 +5512,37 @@ } void -options_server_import(struct options *o, - const char *filename, - int msglevel, - unsigned int permission_mask, - unsigned int *option_types_found, +options_server_import(struct options *o, const char *filename, int msgleve= l, + unsigned int permission_mask, unsigned int *option_t= ypes_found, struct env_set *es) { msg(D_PUSH, "OPTIONS IMPORT: reading client specific options from: %s"= , filename); - read_config_file(o, - filename, - 0, - filename, - 0, - msglevel, - permission_mask, - option_types_found, + read_config_file(o, filename, 0, filename, 0, msglevel, permission_mas= k, option_types_found, es); } void -options_string_import(struct options *options, - const char *config, - const int msglevel, - const unsigned int permission_mask, - unsigned int *option_types_found, +options_string_import(struct options *options, const char *config, const i= nt msglevel, + const unsigned int permission_mask, unsigned int *op= tion_types_found, struct env_set *es) { - read_config_string("[CONFIG-STRING]", options, config, msglevel, permi= ssion_mask, option_types_found, es); + read_config_string("[CONFIG-STRING]", options, config, msglevel, permi= ssion_mask, + option_types_found, es); } -#define VERIFY_PERMISSION(mask) { = \ - if (!verify_permission(p[0], file, line, (mask), permission_mask, = \ - option_types_found, msglevel, options, is_i= nline)) \ - { = \ - goto err; = \ - } = \ -} +#define VERIFY_PERMISSION(mask) = \ + { = \ + if (!verify_permission(p[0], file, line, (mask), permission_mask, = option_types_found, \ + msglevel, options, is_inline)) = \ + { = \ + goto err; = \ + } = \ + } static bool -verify_permission(const char *name, - const char *file, - int line, - const unsigned int type, - const unsigned int allowed, - unsigned int *found, - const int msglevel, - struct options *options, - bool is_inline) +verify_permission(const char *name, const char *file, int line, const unsi= gned int type, + const unsigned int allowed, unsigned int *found, const i= nt msglevel, + struct options *options, bool is_inline) { if (!(type & allowed)) { @@ -5682,8 +5552,7 @@ if (is_inline && !(type & OPT_P_INLINE)) { - msg(msglevel, "option '%s' is not expected to be inline (%s:%d)", = name, - file, line); + msg(msglevel, "option '%s' is not expected to be inline (%s:%d)", = name, file, line); return false; } @@ -5700,12 +5569,12 @@ * connection_list */ - if ((type & OPT_P_CONNECTION) && options->connection_list - && !(allowed & OPT_P_PULL_MODE)) + if ((type & OPT_P_CONNECTION) && options->connection_list && !(allowed= & OPT_P_PULL_MODE)) { if (file) { - msg(M_WARN, "Option '%s' in %s:%d is ignored by previous blocks ", name, file, line); + msg(M_WARN, "Option '%s' in %s:%d is ignored by previous blocks ", name, + file, line); } else { @@ -5721,13 +5590,10 @@ * many parameters. */ -#define NM_QUOTE_HINT (1<<0) +#define NM_QUOTE_HINT (1 << 0) static bool -no_more_than_n_args(const int msglevel, - char *p[], - const int max, - const unsigned int flags) +no_more_than_n_args(const int msglevel, char *p[], const int max, const un= signed int flags) { const int len =3D string_array_len((const char **)p); @@ -5738,11 +5604,11 @@ if (len > max) { - msg(msglevel, "the --%s directive should have at most %d parameter= %s.%s", - p[0], - max - 1, + msg(msglevel, "the --%s directive should have at most %d parameter= %s.%s", p[0], max - 1, max >=3D 3 ? "s" : "", - (flags & NM_QUOTE_HINT) ? " To pass a list of arguments as on= e of the parameters, try enclosing them in double quotes (\"\")." : ""); + (flags & NM_QUOTE_HINT) + ? " To pass a list of arguments as one of the parameters,= try enclosing them in double quotes (\"\")." + : ""); return false; } else @@ -5758,10 +5624,10 @@ } #define RESET_OPTION_ROUTES(option_ptr, field) \ - if (option_ptr) \ - { \ - option_ptr->field =3D NULL; \ - option_ptr->flags =3D 0; \ + if (option_ptr) \ + { \ + option_ptr->field =3D NULL; \ + option_ptr->flags =3D 0; \ } /** @@ -5780,20 +5646,14 @@ * @param line The line number where the function is called. * @param msglevel The message level. * @param permission_mask The permission mask used by VERIFY_PERMISSION(). - * @param option_types_found A pointer to the variable where the flags cor= responding to the options found are stored. + * @param option_types_found A pointer to the variable where the flags cor= responding to the options + * found are stored. * @param es The environment set structure. */ static void -remove_option(struct context *c, - struct options *options, - char *p[], - bool is_inline, - const char *file, - int line, - const int msglevel, - const unsigned int permission_mask, - unsigned int *option_types_found, - struct env_set *es) +remove_option(struct context *c, struct options *options, char *p[], bool = is_inline, + const char *file, int line, const int msglevel, const unsign= ed int permission_mask, + unsigned int *option_types_found, struct env_set *es) { int msglevel_fc =3D msglevel_forward_compatible(options, msglevel); @@ -5815,9 +5675,8 @@ VERIFY_PERMISSION(OPT_P_ROUTE); if (c->c1.route_list) { - delete_routes_v4(c->c1.route_list, c->c1.tuntap, - ROUTE_OPTION_FLAGS(&c->options), - es, &c->net_ctx); + delete_routes_v4(c->c1.route_list, c->c1.tuntap, ROUTE_OPTION_= FLAGS(&c->options), es, + &c->net_ctx); RESET_OPTION_ROUTES(options->routes, routes); } } @@ -5826,8 +5685,7 @@ VERIFY_PERMISSION(OPT_P_ROUTE); if (c->c1.route_ipv6_list) { - delete_routes_v6(c->c1.route_ipv6_list, c->c1.tuntap, - ROUTE_OPTION_FLAGS(&c->options), + delete_routes_v6(c->c1.route_ipv6_list, c->c1.tuntap, ROUTE_OP= TION_FLAGS(&c->options), es, &c->net_ctx); RESET_OPTION_ROUTES(options->routes_ipv6, routes_ipv6); } @@ -5874,7 +5732,7 @@ } else if (streq(p[0], "tun-mtu") && !p[1]) { - VERIFY_PERMISSION(OPT_P_PUSH_MTU|OPT_P_CONNECTION); + VERIFY_PERMISSION(OPT_P_PUSH_MTU | OPT_P_CONNECTION); options->ce.tun_mtu =3D TUN_MTU_DEFAULT; options->ce.tun_mtu_defined =3D false; options->ce.occ_mtu =3D 0; @@ -5942,7 +5800,9 @@ break; } } - msg(msglevel_unknown, "Unrecognized option or missing or extra par= ameter(s) in %s:%d: -%s (%s)", file, line, p[0], PACKAGE_VERSION); + msg(msglevel_unknown, + "Unrecognized option or missing or extra parameter(s) in %s:%d= : -%s (%s)", file, line, + p[0], PACKAGE_VERSION); } return; err: @@ -5956,7 +5816,8 @@ rol_check_alloc(options); if (pull_mode) { - if (!ip_or_dns_addr_safe(p[1], options->allow_pull_fqdn) && !is_sp= ecial_addr(p[1])) /* FQDN -- may be DNS name */ + if (!ip_or_dns_addr_safe(p[1], options->allow_pull_fqdn) + && !is_special_addr(p[1])) /* FQDN -- may be DNS name */ { msg(msglevel, "route parameter network/IP '%s' must be a valid= address", p[1]); return false; @@ -5966,7 +5827,8 @@ msg(msglevel, "route parameter netmask '%s' must be an IP addr= ess", p[2]); return false; } - if (p[3] && !ip_or_dns_addr_safe(p[3], options->allow_pull_fqdn) &= & !is_special_addr(p[3])) /* FQDN -- may be DNS name */ + if (p[3] && !ip_or_dns_addr_safe(p[3], options->allow_pull_fqdn) + && !is_special_addr(p[3])) /* FQDN -- may be DNS name */ { msg(msglevel, "route parameter gateway '%s' must be a valid ad= dress", p[3]); return false; @@ -6002,7 +5864,8 @@ { if (streq(p[1], "search-domains") && p[2]) { - dns_domain_list_append(&options->dns_options.search_domains, &p[2]= , &options->dns_options.gc); + dns_domain_list_append(&options->dns_options.search_domains, &p[2], + &options->dns_options.gc); } else if (streq(p[1], "server") && p[2] && p[3] && p[4]) { @@ -6013,7 +5876,8 @@ return false; } - struct dns_server *server =3D dns_server_get(&options->dns_options= .servers, priority, &options->dns_options.gc); + struct dns_server *server =3D + dns_server_get(&options->dns_options.servers, priority, &optio= ns->dns_options.gc); if (streq(p[3], "address") && p[4]) { @@ -6021,7 +5885,8 @@ { if (!dns_server_addr_parse(server, p[i])) { - msg(msglevel, "--dns server %ld: malformed address or = maximum exceeded '%s'", priority, p[i]); + msg(msglevel, "--dns server %ld: malformed address or = maximum exceeded '%s'", + priority, p[i]); return false; } } @@ -6076,7 +5941,9 @@ } else { - msg(msglevel, "--dns server %ld: unknown option type '%s' or m= issing or unknown parameter", priority, p[3]); + msg(msglevel, + "--dns server %ld: unknown option type '%s' or missing or = unknown parameter", + priority, p[3]); return false; } } @@ -6092,7 +5959,8 @@ * @brief Processes an option to update. It first checks whether it has al= ready * received an option of the same type within the same update messa= ge. * If the option has already been received, it calls add_option(). - * Otherwise, it deletes all existing values related to that option= before calling add_option(). + * Otherwise, it deletes all existing values related to that option= before calling + * add_option(). * * @param c The context structure. * @param options A pointer to the options structure. @@ -6103,24 +5971,18 @@ * @param level The level of the option. * @param msglevel The message level for logging. * @param permission_mask The permission mask used by VERIFY_PERMISSION(). - * @param option_types_found A pointer to the variable where the flags cor= responding to the options found are stored. + * @param option_types_found A pointer to the variable where the flags cor= responding to the options + * found are stored. * @param es The environment set structure. - * @param update_options_found A pointer to the variable where the flags c= orresponding to the update options found are stored, - * used to check if an option of the same type= has already been processed by update_option() within the same push-update = message. + * @param update_options_found A pointer to the variable where the flags c= orresponding to the update + * options found are stored, used to check if an option of the same type h= as already been processed + * by update_option() within the same push-update message. */ static void -update_option(struct context *c, - struct options *options, - char *p[], - bool is_inline, - const char *file, - int line, - const int level, - const int msglevel, - const unsigned int permission_mask, - unsigned int *option_types_found, - struct env_set *es, - unsigned int *update_options_found) +update_option(struct context *c, struct options *options, char *p[], bool = is_inline, + const char *file, int line, const int level, const int msgle= vel, + const unsigned int permission_mask, unsigned int *option_typ= es_found, + struct env_set *es, unsigned int *update_options_found) { const bool pull_mode =3D BOOL_CAST(permission_mask & OPT_P_PULL_MODE); ASSERT(MAX_PARMS >=3D 7); @@ -6136,8 +5998,7 @@ } if (c->c1.route_list) { - delete_routes_v4(c->c1.route_list, c->c1.tuntap, - ROUTE_OPTION_FLAGS(&c->options), + delete_routes_v4(c->c1.route_list, c->c1.tuntap, ROUTE_OPT= ION_FLAGS(&c->options), es, &c->net_ctx); RESET_OPTION_ROUTES(options->routes, routes); } @@ -6156,8 +6017,7 @@ if (c->c1.route_ipv6_list) { delete_routes_v6(c->c1.route_ipv6_list, c->c1.tuntap, - ROUTE_OPTION_FLAGS(&c->options), - es, &c->net_ctx); + ROUTE_OPTION_FLAGS(&c->options), es, &c->= net_ctx); RESET_OPTION_ROUTES(options->routes_ipv6, routes_ipv6); } *update_options_found |=3D OPT_P_U_ROUTE6; @@ -6229,7 +6089,7 @@ *update_options_found |=3D OPT_P_U_DHCP; } } -#else /* if defined(_WIN32) || defined(TARGET_ANDROID) */ +#else /* if defined(_WIN32) || defined(TARGET_ANDROID) */ else if (streq(p[0], "dhcp-option") && p[1] && !p[3]) { if (!(*update_options_found & OPT_P_U_DHCP)) @@ -6240,8 +6100,7 @@ } } #endif /* if defined(_WIN32) || defined(TARGET_ANDROID) */ - add_option(options, p, is_inline, file, line, - level, msglevel, permission_mask, + add_option(options, p, is_inline, file, line, level, msglevel, permiss= ion_mask, option_types_found, es); return; err: @@ -6249,16 +6108,15 @@ } static void -set_user_script(struct options *options, - const char **script, - const char *new_script, - const char *type, - bool in_chroot) +set_user_script(struct options *options, const char **script, const char *= new_script, + const char *type, bool in_chroot) { if (*script) { - msg(M_WARN, "Multiple --%s scripts defined. " - "The previously configured script is overridden.", type); + msg(M_WARN, + "Multiple --%s scripts defined. " + "The previously configured script is overridden.", + type); } *script =3D new_script; options->user_script_used =3D true; @@ -6266,14 +6124,12 @@ #ifndef ENABLE_SMALL { char script_name[100]; - snprintf(script_name, sizeof(script_name), - "--%s script", type); + snprintf(script_name, sizeof(script_name), "--%s script", type); if (check_cmd_access(*script, script_name, (in_chroot ? options->c= hroot_dir : NULL))) { msg(M_USAGE, "Please correct this error."); } - } #endif } @@ -6284,9 +6140,9 @@ if (comp_non_stub_enabled(info)) { msg(M_WARN, "WARNING: Compression for receiving enabled. " - "Compression has been used in the past to break encryption. " - "Compression support is deprecated and we recommend to disable= " - "it completely."); + "Compression has been used in the past to break encryp= tion. " + "Compression support is deprecated and we recommend to= disable " + "it completely."); } } @@ -6306,16 +6162,9 @@ } static void -add_option(struct options *options, - char *p[], - bool is_inline, - const char *file, - int line, - const int level, - const int msglevel, - const unsigned int permission_mask, - unsigned int *option_types_found, - struct env_set *es) +add_option(struct options *options, char *p[], bool is_inline, const char = *file, int line, + const int level, const int msglevel, const unsigned int permiss= ion_mask, + unsigned int *option_types_found, struct env_set *es) { struct gc_arena gc =3D gc_new(); const bool pull_mode =3D BOOL_CAST(permission_mask & OPT_P_PULL_MODE); @@ -6367,7 +6216,8 @@ options->config =3D p[1]; } - read_config_file(options, p[1], level, file, line, msglevel, permi= ssion_mask, option_types_found, es); + read_config_file(options, p[1], level, file, line, msglevel, permi= ssion_mask, + option_types_found, es); } #if defined(ENABLE_DEBUG) && !defined(ENABLE_SMALL) else if (streq(p[0], "show-gateway") && !p[2]) @@ -6420,9 +6270,7 @@ * can potentially include security-sensitive strings */ if (p[1] && strncmp(p[1], "msg", 3) =3D=3D 0) { - msg(M_INFO, "%s:%s", - pull_mode ? "ECHO-PULL" : "ECHO", - BSTR(&string)); + msg(M_INFO, "%s:%s", pull_mode ? "ECHO-PULL" : "ECHO", BST= R(&string)); } #ifdef ENABLE_MANAGEMENT if (management) @@ -6537,8 +6385,7 @@ * When no option is present, assume that only PKCS1 * padding is supported */ - if (!(options->management_flags - &(MF_EXTERNAL_KEY_NOPADDING | MF_EXTERNAL_KEY_PKCS1PAD))) + if (!(options->management_flags & (MF_EXTERNAL_KEY_NOPADDING | MF_= EXTERNAL_KEY_PKCS1PAD))) { options->management_flags |=3D MF_EXTERNAL_KEY_PKCS1PAD; } @@ -6615,7 +6462,8 @@ else if (streq(p[0], "windows-driver") && p[1] && !p[2]) { VERIFY_PERMISSION(OPT_P_GENERAL); - msg(M_WARN, "DEPRECATED OPTION: windows-driver: In OpenVPN 2.7, th= e default Windows driver is ovpn-dco. " + msg(M_WARN, + "DEPRECATED OPTION: windows-driver: In OpenVPN 2.7, the defaul= t Windows driver is ovpn-dco. " "If incompatible options are used, OpenVPN will fall back to t= ap-windows6. Wintun support has been removed."); } #endif @@ -6650,7 +6498,8 @@ { if (!pull_mode) { - msg(M_WARN, "Note: option tun-ipv6 is ignored because modern o= perating systems do not need special IPv6 tun handling anymore."); + msg(M_WARN, + "Note: option tun-ipv6 is ignored because modern operating= systems do not need special IPv6 tun handling anymore."); } } #ifdef ENABLE_IPROUTE @@ -6663,7 +6512,8 @@ else if (streq(p[0], "ifconfig") && p[1] && p[2] && !p[3]) { VERIFY_PERMISSION(OPT_P_UP); - if (ip_or_dns_addr_safe(p[1], options->allow_pull_fqdn) && ip_or_d= ns_addr_safe(p[2], options->allow_pull_fqdn)) /* FQDN -- may be DNS name */ + if (ip_or_dns_addr_safe(p[1], options->allow_pull_fqdn) + && ip_or_dns_addr_safe(p[2], options->allow_pull_fqdn)) /* FQD= N -- may be DNS name */ { options->ifconfig_local =3D p[1]; options->ifconfig_remote_netmask =3D p[2]; @@ -6679,12 +6529,12 @@ unsigned int netbits; VERIFY_PERMISSION(OPT_P_UP); - if (get_ipv6_addr( p[1], NULL, &netbits, msglevel ) - && ipv6_addr_safe( p[2] ) ) + if (get_ipv6_addr(p[1], NULL, &netbits, msglevel) && ipv6_addr_saf= e(p[2])) { if (netbits < 64 || netbits > 124) { - msg( msglevel, "ifconfig-ipv6: /netbits must be between 64= and 124, not '/%d'", netbits ); + msg(msglevel, "ifconfig-ipv6: /netbits must be between 64 = and 124, not '/%d'", + netbits); goto err; } @@ -6712,7 +6562,7 @@ { struct local_entry *e; - VERIFY_PERMISSION(OPT_P_GENERAL|OPT_P_CONNECTION); + VERIFY_PERMISSION(OPT_P_GENERAL | OPT_P_CONNECTION); e =3D alloc_local_entry(&options->ce, M_USAGE, &options->gc); ASSERT(e); @@ -6742,7 +6592,7 @@ } else if (streq(p[0], "connection") && p[1] && !p[3]) { - VERIFY_PERMISSION(OPT_P_GENERAL|OPT_P_INLINE); + VERIFY_PERMISSION(OPT_P_GENERAL | OPT_P_INLINE); if (is_inline) { struct options sub; @@ -6750,11 +6600,12 @@ init_options(&sub, true); sub.ce =3D options->ce; - read_config_string("[CONNECTION-OPTIONS]", &sub, p[1], msgleve= l, - OPT_P_CONNECTION, option_types_found, es); + read_config_string("[CONNECTION-OPTIONS]", &sub, p[1], msgleve= l, OPT_P_CONNECTION, + option_types_found, es); if (!sub.ce.remote) { - msg(msglevel, "Each 'connection' block must contain exactl= y one 'remote' directive"); + msg(msglevel, + "Each 'connection' block must contain exactly one 'rem= ote' directive"); uninit_options(&sub); goto err; } @@ -6785,16 +6636,14 @@ } /* add number of options already ignored */ - for (i =3D 0; options->ignore_unknown_option - && options->ignore_unknown_option[i]; i++) + for (i =3D 0; options->ignore_unknown_option && options->ignore_un= known_option[i]; i++) { numignored++; } /* Allocate array */ - ALLOC_ARRAY_GC(ignore, const char *, numignored+1, &options->gc); - for (i =3D 0; options->ignore_unknown_option - && options->ignore_unknown_option[i]; i++) + ALLOC_ARRAY_GC(ignore, const char *, numignored + 1, &options->gc); + for (i =3D 0; options->ignore_unknown_option && options->ignore_un= known_option[i]; i++) { ignore[i] =3D options->ignore_unknown_option[i]; } @@ -6804,9 +6653,9 @@ for (j =3D 1; p[j]; j++) { /* Allow the user to specify ignore-unknown-option --opt too */ - if (p[j][0]=3D=3D'-' && p[j][1]=3D=3D'-') + if (p[j][0] =3D=3D '-' && p[j][1] =3D=3D '-') { - options->ignore_unknown_option[i] =3D (p[j]+2); + options->ignore_unknown_option[i] =3D (p[j] + 2); } else { @@ -6835,7 +6684,7 @@ re.proto =3D -1; re.af =3D 0; - VERIFY_PERMISSION(OPT_P_GENERAL|OPT_P_CONNECTION); + VERIFY_PERMISSION(OPT_P_GENERAL | OPT_P_CONNECTION); re.remote =3D p[1]; if (p[2]) { @@ -6846,9 +6695,7 @@ const sa_family_t af =3D ascii2af(p[3]); if (proto < 0) { - msg(msglevel, - "remote: bad protocol associated with host %s: '%s= '", - p[1], p[3]); + msg(msglevel, "remote: bad protocol associated with ho= st %s: '%s'", p[1], p[3]); goto err; } re.proto =3D proto; @@ -6894,7 +6741,7 @@ } else if (streq(p[0], "connect-retry") && p[1] && !p[3]) { - VERIFY_PERMISSION(OPT_P_GENERAL|OPT_P_CONNECTION); + VERIFY_PERMISSION(OPT_P_GENERAL | OPT_P_CONNECTION); options->ce.connect_retry_seconds =3D positive_atoi(p[1], msglevel= ); /* * Limit the base value of retry wait interval to 16 bits to avoid @@ -6913,15 +6760,15 @@ max_int(positive_atoi(p[2], msglevel), options->ce.connect= _retry_seconds); } } - else if ((streq(p[0], "connect-timeout") || streq(p[0], "server-poll-t= imeout")) - && p[1] && !p[2]) + else if ((streq(p[0], "connect-timeout") || streq(p[0], "server-poll-t= imeout")) && p[1] + && !p[2]) { - VERIFY_PERMISSION(OPT_P_GENERAL|OPT_P_CONNECTION); + VERIFY_PERMISSION(OPT_P_GENERAL | OPT_P_CONNECTION); options->ce.connect_timeout =3D positive_atoi(p[1], msglevel); } else if (streq(p[0], "connect-retry-max") && p[1] && !p[2]) { - VERIFY_PERMISSION(OPT_P_GENERAL|OPT_P_CONNECTION); + VERIFY_PERMISSION(OPT_P_GENERAL | OPT_P_CONNECTION); options->connect_retry_max =3D positive_atoi(p[1], msglevel); } else if (streq(p[0], "ipchange") && p[1]) @@ -6931,14 +6778,12 @@ { goto err; } - set_user_script(options, - &options->ipchange, - string_substitute(p[1], ',', ' ', &options->gc), - "ipchange", true); + set_user_script(options, &options->ipchange, + string_substitute(p[1], ',', ' ', &options->gc), "= ipchange", true); } else if (streq(p[0], "float") && !p[1]) { - VERIFY_PERMISSION(OPT_P_GENERAL|OPT_P_CONNECTION); + VERIFY_PERMISSION(OPT_P_GENERAL | OPT_P_CONNECTION); options->ce.remote_float =3D true; } #ifdef ENABLE_DEBUG @@ -7026,7 +6871,9 @@ { if (!didit) { - msg(M_WARN, "WARNING: Multiple --daemon directives specifi= ed, ignoring --daemon %s. (Note that initscripts sometimes add their own --= daemon directive.)", p[1]); + msg(M_WARN, + "WARNING: Multiple --daemon directives specified, igno= ring --daemon %s. (Note that initscripts sometimes add their own --daemon d= irective.)", + p[1]); goto err; } } @@ -7088,7 +6935,8 @@ /* Warn when a debug verbosity is supplied when built without debu= g support */ if (options->verbosity >=3D 7) { - msg(M_WARN, "NOTE: debug verbosity (--verb %d) is enabled but = this build lacks debug support.", + msg(M_WARN, + "NOTE: debug verbosity (--verb %d) is enabled but this bui= ld lacks debug support.", options->verbosity); } #endif @@ -7144,13 +6992,13 @@ } else if ((streq(p[0], "link-mtu") || streq(p[0], "udp-mtu")) && p[1] &= & !p[2]) { - VERIFY_PERMISSION(OPT_P_MTU|OPT_P_CONNECTION); + VERIFY_PERMISSION(OPT_P_MTU | OPT_P_CONNECTION); options->ce.link_mtu =3D positive_atoi(p[1], msglevel); options->ce.link_mtu_defined =3D true; } else if (streq(p[0], "tun-mtu") && p[1] && !p[3]) { - VERIFY_PERMISSION(OPT_P_PUSH_MTU|OPT_P_CONNECTION); + VERIFY_PERMISSION(OPT_P_PUSH_MTU | OPT_P_CONNECTION); options->ce.tun_mtu =3D positive_atoi(p[1], msglevel); options->ce.tun_mtu_defined =3D true; if (p[2]) @@ -7164,7 +7012,7 @@ } else if (streq(p[0], "tun-mtu-max") && p[1] && !p[3]) { - VERIFY_PERMISSION(OPT_P_MTU|OPT_P_CONNECTION); + VERIFY_PERMISSION(OPT_P_MTU | OPT_P_CONNECTION); int max_mtu =3D positive_atoi(p[1], msglevel); if (max_mtu < 68 || max_mtu > 65536) { @@ -7177,22 +7025,23 @@ } else if (streq(p[0], "tun-mtu-extra") && p[1] && !p[2]) { - VERIFY_PERMISSION(OPT_P_MTU|OPT_P_CONNECTION); + VERIFY_PERMISSION(OPT_P_MTU | OPT_P_CONNECTION); options->ce.tun_mtu_extra =3D positive_atoi(p[1], msglevel); options->ce.tun_mtu_extra_defined =3D true; } else if (streq(p[0], "max-packet-size") && p[1] && !p[2]) { - VERIFY_PERMISSION(OPT_P_MTU|OPT_P_CONNECTION); + VERIFY_PERMISSION(OPT_P_MTU | OPT_P_CONNECTION); int maxmtu =3D positive_atoi(p[1], msglevel); options->ce.tls_mtu =3D constrain_int(maxmtu, TLS_CHANNEL_MTU_MIN,= TLS_CHANNEL_BUF_SIZE); if (maxmtu < TLS_CHANNEL_MTU_MIN || maxmtu > TLS_CHANNEL_BUF_SIZE) { - msg(M_WARN, "Note: max-packet-size value outside of allowed " + msg(M_WARN, + "Note: max-packet-size value outside of allowed " "control channel packet size (%d to %d), will use %d " - "instead.", TLS_CHANNEL_MTU_MIN, TLS_CHANNEL_BUF_SIZE, - options->ce.tls_mtu); + "instead.", + TLS_CHANNEL_MTU_MIN, TLS_CHANNEL_BUF_SIZE, options->ce.tls= _mtu); } /* also set mssfix maxmtu mtu */ @@ -7203,13 +7052,13 @@ #ifdef ENABLE_FRAGMENT else if (streq(p[0], "mtu-dynamic")) { - VERIFY_PERMISSION(OPT_P_MTU|OPT_P_CONNECTION); + VERIFY_PERMISSION(OPT_P_MTU | OPT_P_CONNECTION); msg(msglevel, "--mtu-dynamic has been replaced by --fragment"); goto err; } else if (streq(p[0], "fragment") && p[1] && !p[3]) { - VERIFY_PERMISSION(OPT_P_MTU|OPT_P_CONNECTION); + VERIFY_PERMISSION(OPT_P_MTU | OPT_P_CONNECTION); options->ce.fragment =3D positive_atoi(p[1], msglevel); if (options->ce.fragment < 68) @@ -7230,7 +7079,7 @@ #endif /* ifdef ENABLE_FRAGMENT */ else if (streq(p[0], "mtu-disc") && p[1] && !p[2]) { - VERIFY_PERMISSION(OPT_P_MTU|OPT_P_CONNECTION); + VERIFY_PERMISSION(OPT_P_MTU | OPT_P_CONNECTION); options->ce.mtu_discover_type =3D translate_mtu_discover_type_name= (p[1]); } else if (streq(p[0], "mtu-test") && !p[1]) @@ -7301,20 +7150,19 @@ shaper =3D atoi_warn(p[1], msglevel); if (shaper < SHAPER_MIN || shaper > SHAPER_MAX) { - msg(msglevel, "Bad shaper value, must be between %d and %d", - SHAPER_MIN, SHAPER_MAX); + msg(msglevel, "Bad shaper value, must be between %d and %d", S= HAPER_MIN, SHAPER_MAX); goto err; } options->shaper =3D shaper; } else if (streq(p[0], "port") && p[1] && !p[2]) { - VERIFY_PERMISSION(OPT_P_GENERAL|OPT_P_CONNECTION); + VERIFY_PERMISSION(OPT_P_GENERAL | OPT_P_CONNECTION); options->ce.local_port =3D options->ce.remote_port =3D p[1]; } else if (streq(p[0], "lport") && p[1] && !p[2]) { - VERIFY_PERMISSION(OPT_P_GENERAL|OPT_P_CONNECTION); + VERIFY_PERMISSION(OPT_P_GENERAL | OPT_P_CONNECTION); /* only trigger bind() if port is not 0 (or --local is used) */ if (!streq(p[1], "0")) @@ -7325,22 +7173,21 @@ } else if (streq(p[0], "rport") && p[1] && !p[2]) { - VERIFY_PERMISSION(OPT_P_GENERAL|OPT_P_CONNECTION); + VERIFY_PERMISSION(OPT_P_GENERAL | OPT_P_CONNECTION); options->ce.remote_port =3D p[1]; } else if (streq(p[0], "bind") && !p[2]) { - VERIFY_PERMISSION(OPT_P_GENERAL|OPT_P_CONNECTION); + VERIFY_PERMISSION(OPT_P_GENERAL | OPT_P_CONNECTION); options->ce.bind_defined =3D true; if (p[1] && streq(p[1], "ipv6only")) { options->ce.bind_ipv6_only =3D true; } - } else if (streq(p[0], "nobind") && !p[1]) { - VERIFY_PERMISSION(OPT_P_GENERAL|OPT_P_CONNECTION); + VERIFY_PERMISSION(OPT_P_GENERAL | OPT_P_CONNECTION); options->ce.bind_local =3D false; } else if (streq(p[0], "fast-io") && !p[1]) @@ -7358,11 +7205,12 @@ options->inactivity_minimum_bytes =3D (val < 0) ? 0 : val; if (options->inactivity_minimum_bytes > INT_MAX) { - msg(M_WARN, "WARNING: '--inactive' with a 'bytes' value" + msg(M_WARN, + "WARNING: '--inactive' with a 'bytes' value" " >2 Gbyte was silently ignored in older versions. If= " " your VPN exits unexpectedly with 'Inactivity timeout= '" " in %d seconds, revisit this value.", - options->inactivity_timeout ); + options->inactivity_timeout); } } } @@ -7375,14 +7223,12 @@ { int proto; sa_family_t af; - VERIFY_PERMISSION(OPT_P_GENERAL|OPT_P_CONNECTION); + VERIFY_PERMISSION(OPT_P_GENERAL | OPT_P_CONNECTION); proto =3D ascii2proto(p[1]); af =3D ascii2af(p[1]); if (proto < 0) { - msg(msglevel, - "Bad protocol: '%s'. Allowed protocols with --proto option= : %s", - p[1], + msg(msglevel, "Bad protocol: '%s'. Allowed protocols with --pr= oto option: %s", p[1], proto2ascii_all(&gc)); goto err; } @@ -7405,7 +7251,7 @@ { struct http_proxy_options *ho; - VERIFY_PERMISSION(OPT_P_GENERAL|OPT_P_CONNECTION); + VERIFY_PERMISSION(OPT_P_GENERAL | OPT_P_CONNECTION); { if (!p[2]) @@ -7451,29 +7297,30 @@ else if (streq(p[0], "http-proxy-user-pass") && p[1]) { struct http_proxy_options *ho; - VERIFY_PERMISSION(OPT_P_GENERAL|OPT_P_INLINE); + VERIFY_PERMISSION(OPT_P_GENERAL | OPT_P_INLINE); ho =3D init_http_proxy_options_once(&options->ce.http_proxy_option= s, &options->gc); ho->auth_file_up =3D p[1]; ho->inline_creds =3D is_inline; } else if (streq(p[0], "http-proxy-retry") || streq(p[0], "socks-proxy-r= etry")) { - VERIFY_PERMISSION(OPT_P_GENERAL|OPT_P_CONNECTION); + VERIFY_PERMISSION(OPT_P_GENERAL | OPT_P_CONNECTION); msg(M_WARN, "DEPRECATED OPTION: http-proxy-retry and socks-proxy-r= etry: " - "In OpenVPN 2.4 proxy connection retries are handled like regu= lar connections. " - "Use connect-retry-max 1 to get a similar behavior as before."= ); + "In OpenVPN 2.4 proxy connection retries are handled l= ike regular connections. " + "Use connect-retry-max 1 to get a similar behavior as = before."); } else if (streq(p[0], "http-proxy-timeout") && p[1] && !p[2]) { - VERIFY_PERMISSION(OPT_P_GENERAL|OPT_P_CONNECTION); - msg(M_WARN, "DEPRECATED OPTION: http-proxy-timeout: In OpenVPN 2.4= the timeout until a connection to a " + VERIFY_PERMISSION(OPT_P_GENERAL | OPT_P_CONNECTION); + msg(M_WARN, + "DEPRECATED OPTION: http-proxy-timeout: In OpenVPN 2.4 the tim= eout until a connection to a " "server is established is managed with a single timeout set by= connect-timeout"); } else if (streq(p[0], "http-proxy-option") && p[1] && !p[4]) { struct http_proxy_options *ho; - VERIFY_PERMISSION(OPT_P_GENERAL|OPT_P_CONNECTION); + VERIFY_PERMISSION(OPT_P_GENERAL | OPT_P_CONNECTION); ho =3D init_http_proxy_options_once(&options->ce.http_proxy_option= s, &options->gc); if (streq(p[1], "VERSION") && p[2] && !p[3]) @@ -7503,7 +7350,8 @@ } if (!custom_header) { - msg(msglevel, "Cannot use more than %d http-proxy-option C= USTOM-HEADER : '%s'", MAX_CUSTOM_HTTP_HEADER, p[1]); + msg(msglevel, "Cannot use more than %d http-proxy-option C= USTOM-HEADER : '%s'", + MAX_CUSTOM_HTTP_HEADER, p[1]); } else { @@ -7520,7 +7368,7 @@ } else if (streq(p[0], "socks-proxy") && p[1] && !p[4]) { - VERIFY_PERMISSION(OPT_P_GENERAL|OPT_P_CONNECTION); + VERIFY_PERMISSION(OPT_P_GENERAL | OPT_P_CONNECTION); if (p[2]) { @@ -7563,7 +7411,7 @@ } else if (streq(p[0], "explicit-exit-notify") && !p[2]) { - VERIFY_PERMISSION(OPT_P_GENERAL|OPT_P_CONNECTION|OPT_P_EXPLICIT_NO= TIFY); + VERIFY_PERMISSION(OPT_P_GENERAL | OPT_P_CONNECTION | OPT_P_EXPLICI= T_NOTIFY); if (p[1]) { options->ce.explicit_exit_notification =3D positive_atoi(p[1],= msglevel); @@ -7582,7 +7430,7 @@ { VERIFY_PERMISSION(OPT_P_PERSIST); msg(M_WARN, "DEPRECATED: --persist-key option ignored. " - "Keys are now always persisted across restarts. "); + "Keys are now always persisted across restarts. "); } else if (streq(p[0], "persist-local-ip") && !p[1]) { @@ -7615,7 +7463,8 @@ { goto err; } - add_route_to_option_list(options->routes, p[1], p[2], p[3], p[4], = options->route_default_table_id); + add_route_to_option_list(options->routes, p[1], p[2], p[3], p[4], + options->route_default_table_id); } else if (streq(p[0], "route-ipv6") && p[1] && !p[4]) { @@ -7624,14 +7473,15 @@ { goto err; } - add_route_ipv6_to_option_list(options->routes_ipv6, p[1], p[2], p[= 3], options->route_default_table_id); + add_route_ipv6_to_option_list(options->routes_ipv6, p[1], p[2], p[= 3], + options->route_default_table_id); } else if (streq(p[0], "max-routes") && !p[2]) { msg(M_WARN, "DEPRECATED OPTION: --max-routes option ignored. " - "The number of routes is unlimited as of OpenVPN 2.4. " - "This option will be removed in a future version, " - "please remove it from your configuration."); + "The number of routes is unlimited as of OpenVPN 2.4. " + "This option will be removed in a future version, " + "please remove it from your configuration."); } else if (streq(p[0], "route-gateway") && p[1] && !p[2]) { @@ -7642,7 +7492,8 @@ } else { - if (ip_or_dns_addr_safe(p[1], options->allow_pull_fqdn) || is_= special_addr(p[1])) /* FQDN -- may be DNS name */ + if (ip_or_dns_addr_safe(p[1], options->allow_pull_fqdn) + || is_special_addr(p[1])) /* FQDN -- may be DNS name */ { options->route_default_gateway =3D p[1]; } @@ -7703,10 +7554,7 @@ { goto err; } - set_user_script(options, - &options->route_predown_script, - p[1], - "route-pre-down", true); + set_user_script(options, &options->route_predown_script, p[1], "ro= ute-pre-down", true); } else if (streq(p[0], "route-noexec") && !p[1]) { @@ -7757,11 +7605,10 @@ if (options->routes->flags & RG_ENABLE) { - msg(M_WARN, - "WARNING: You have specified redirect-gateway and " - "redirect-private at the same time (or the same option " - "multiple times). This is not well supported and may lead = to " - "unexpected results"); + msg(M_WARN, "WARNING: You have specified redirect-gateway and " + "redirect-private at the same time (or the same op= tion " + "multiple times). This is not well supported and m= ay lead to " + "unexpected results"); } options->routes->flags |=3D RG_ENABLE; @@ -7861,8 +7708,7 @@ unsigned int major, minor, patch; if (!(sscanf(p[1], "%u.%u.%u", &major, &minor, &patch) =3D=3D 3)) { - msg(msglevel, "cannot parse version number for --compat-mode: = %s", - p[1]); + msg(msglevel, "cannot parse version number for --compat-mode: = %s", p[1]); goto err; } @@ -7880,14 +7726,13 @@ } else if (streq(p[0], "mssfix") && !p[3]) { - VERIFY_PERMISSION(OPT_P_GENERAL|OPT_P_CONNECTION); + VERIFY_PERMISSION(OPT_P_GENERAL | OPT_P_CONNECTION); if (p[1]) { int mssfix =3D positive_atoi(p[1], msglevel); /* can be 0, but otherwise it needs to be high enough so we can * substract room for headers. */ - if (mssfix !=3D 0 - && (mssfix < TLS_CHANNEL_MTU_MIN || mssfix > UINT16_MAX)) + if (mssfix !=3D 0 && (mssfix < TLS_CHANNEL_MTU_MIN || mssfix >= UINT16_MAX)) { msg(msglevel, "--mssfix value '%s' is invalid", p[1]); goto err; @@ -7963,15 +7808,14 @@ unsigned int netbits =3D 0; VERIFY_PERMISSION(OPT_P_GENERAL); - if (!get_ipv6_addr(p[1], &network, &netbits, lev) ) + if (!get_ipv6_addr(p[1], &network, &netbits, lev)) { msg(msglevel, "error parsing --server-ipv6 parameter"); goto err; } if (netbits < 64 || netbits > 124) { - msg(msglevel, - "--server-ipv6 settings: network must be between /64 and /= 124 (not /%d)", + msg(msglevel, "--server-ipv6 settings: network must be between= /64 and /124 (not /%d)", netbits); goto err; @@ -8076,7 +7920,7 @@ unsigned int netbits =3D 0; VERIFY_PERMISSION(OPT_P_GENERAL); - if (!get_ipv6_addr(p[1], &network, &netbits, lev ) ) + if (!get_ipv6_addr(p[1], &network, &netbits, lev)) { msg(msglevel, "error parsing --ifconfig-ipv6-pool parameters"); goto err; @@ -8165,7 +8009,8 @@ else if (streq(p[0], "client-cert-not-required") && !p[1]) { VERIFY_PERMISSION(OPT_P_GENERAL); - msg(M_FATAL, "REMOVED OPTION: --client-cert-not-required, use '--v= erify-client-cert none' instead"); + msg(M_FATAL, + "REMOVED OPTION: --client-cert-not-required, use '--verify-cli= ent-cert none' instead"); } else if (streq(p[0], "verify-client-cert") && !p[2]) { @@ -8186,7 +8031,8 @@ } else if (!streq(p[1], "require")) { - msg(msglevel, "parameter to --verify-client-cert must be '= none', 'optional' or 'require'"); + msg(msglevel, + "parameter to --verify-client-cert must be 'none', 'op= tional' or 'require'"); goto err; } } @@ -8205,7 +8051,7 @@ { VERIFY_PERMISSION(OPT_P_GENERAL); msg(M_INFO, "DEPRECATION: opt-verify is deprecated and will be rem= oved " - "in OpenVPN 2.7"); + "in OpenVPN 2.7"); options->ssl_flags |=3D SSLF_OPT_VERIFY; } else if (streq(p[0], "auth-user-pass-verify") && p[1]) @@ -8227,18 +8073,19 @@ } else { - msg(msglevel, "second parm to --auth-user-pass-verify must= be 'via-env' or 'via-file'"); + msg(msglevel, + "second parm to --auth-user-pass-verify must be 'via-e= nv' or 'via-file'"); goto err; } } else { - msg(msglevel, "--auth-user-pass-verify requires a second param= eter ('via-env' or 'via-file')"); + msg(msglevel, + "--auth-user-pass-verify requires a second parameter ('via= -env' or 'via-file')"); goto err; } - set_user_script(options, - &options->auth_user_pass_verify_script, - p[1], "auth-user-pass-verify", true); + set_user_script(options, &options->auth_user_pass_verify_script, p= [1], + "auth-user-pass-verify", true); } else if (streq(p[0], "auth-gen-token")) { @@ -8262,14 +8109,12 @@ msg(msglevel, "Invalid argument to auth-gen-token: %s (%d)= ", p[i], i); } } - } else if (streq(p[0], "auth-gen-token-secret") && p[1] && !p[2]) { - VERIFY_PERMISSION(OPT_P_GENERAL|OPT_P_INLINE); + VERIFY_PERMISSION(OPT_P_GENERAL | OPT_P_INLINE); options->auth_token_secret_file =3D p[1]; options->auth_token_secret_file_inline =3D is_inline; - } else if (streq(p[0], "client-connect") && p[1]) { @@ -8278,8 +8123,7 @@ { goto err; } - set_user_script(options, &options->client_connect_script, - p[1], "client-connect", true); + set_user_script(options, &options->client_connect_script, p[1], "c= lient-connect", true); } else if (streq(p[0], "client-crresponse") && p[1]) { @@ -8288,8 +8132,8 @@ { goto err; } - set_user_script(options, &options->client_crresponse_script, - p[1], "client-crresponse", true); + set_user_script(options, &options->client_crresponse_script, p[1],= "client-crresponse", + true); } else if (streq(p[0], "client-disconnect") && p[1]) { @@ -8298,8 +8142,8 @@ { goto err; } - set_user_script(options, &options->client_disconnect_script, - p[1], "client-disconnect", true); + set_user_script(options, &options->client_disconnect_script, p[1],= "client-disconnect", + true); } else if (streq(p[0], "learn-address") && p[1]) { @@ -8308,8 +8152,7 @@ { goto err; } - set_user_script(options, &options->learn_address_script, - p[1], "learn-address", true); + set_user_script(options, &options->learn_address_script, p[1], "le= arn-address", true); } else if (streq(p[0], "tmp-dir") && p[1] && !p[2]) { @@ -8384,8 +8227,8 @@ in_addr_t local, remote_netmask; VERIFY_PERMISSION(OPT_P_INSTANCE); - local =3D getaddr(GETADDR_HOST_ORDER|GETADDR_RESOLVE, p[1], 0, NUL= L, NULL); - remote_netmask =3D getaddr(GETADDR_HOST_ORDER|GETADDR_RESOLVE, p[2= ], 0, NULL, NULL); + local =3D getaddr(GETADDR_HOST_ORDER | GETADDR_RESOLVE, p[1], 0, N= ULL, NULL); + remote_netmask =3D getaddr(GETADDR_HOST_ORDER | GETADDR_RESOLVE, p= [2], 0, NULL, NULL); if (local && remote_netmask) { options->push_ifconfig_defined =3D true; @@ -8393,7 +8236,8 @@ options->push_ifconfig_remote_netmask =3D remote_netmask; if (p[3]) { - options->push_ifconfig_local_alias =3D getaddr(GETADDR_HOS= T_ORDER|GETADDR_RESOLVE, p[3], 0, NULL, NULL); + options->push_ifconfig_local_alias =3D + getaddr(GETADDR_HOST_ORDER | GETADDR_RESOLVE, p[3], 0,= NULL, NULL); } } else @@ -8407,7 +8251,7 @@ in_addr_t network, netmask; VERIFY_PERMISSION(OPT_P_GENERAL); - network =3D getaddr(GETADDR_HOST_ORDER|GETADDR_RESOLVE, p[1], 0, N= ULL, NULL); + network =3D getaddr(GETADDR_HOST_ORDER | GETADDR_RESOLVE, p[1], 0,= NULL, NULL); netmask =3D getaddr(GETADDR_HOST_ORDER, p[2], 0, NULL, NULL); if (network && netmask) { @@ -8428,7 +8272,7 @@ VERIFY_PERMISSION(OPT_P_INSTANCE); - if (!get_ipv6_addr( p[1], &local, &netbits, msglevel ) ) + if (!get_ipv6_addr(p[1], &local, &netbits, msglevel)) { msg(msglevel, "cannot parse --ifconfig-ipv6-push addresses"); goto err; @@ -8436,19 +8280,19 @@ if (p[2]) { - if (!get_ipv6_addr( p[2], &remote, NULL, msglevel ) ) + if (!get_ipv6_addr(p[2], &remote, NULL, msglevel)) { - msg( msglevel, "cannot parse --ifconfig-ipv6-push addresse= s"); + msg(msglevel, "cannot parse --ifconfig-ipv6-push addresses= "); goto err; } } else { if (!options->ifconfig_ipv6_local - || !get_ipv6_addr( options->ifconfig_ipv6_local, &remote, - NULL, msglevel ) ) + || !get_ipv6_addr(options->ifconfig_ipv6_local, &remote, N= ULL, msglevel)) { - msg( msglevel, "second argument to --ifconfig-ipv6-push mi= ssing and no global --ifconfig-ipv6 address set"); + msg(msglevel, + "second argument to --ifconfig-ipv6-push missing and n= o global --ifconfig-ipv6 address set"); goto err; } } @@ -8469,8 +8313,10 @@ VERIFY_PERMISSION(OPT_P_INSTANCE); if (strlen(p[1]) > USER_PASS_LEN) { - msg(msglevel, "override-username exceeds the maximum length of= %d " - "characters", USER_PASS_LEN); + msg(msglevel, + "override-username exceeds the maximum length of %d " + "characters", + USER_PASS_LEN); /* disable the connection since ignoring the request to * set another username might cause serious problems */ @@ -8506,7 +8352,7 @@ msg(msglevel, "--stale-routes-check aging time and check inter= val must be >=3D 1"); goto err; } - options->stale_routes_ageing_time =3D ageing_time; + options->stale_routes_ageing_time =3D ageing_time; options->stale_routes_check_interval =3D check_interval; } @@ -8527,7 +8373,7 @@ } else if (streq(p[0], "auth-user-pass") && !p[2]) { - VERIFY_PERMISSION(OPT_P_GENERAL|OPT_P_INLINE); + VERIFY_PERMISSION(OPT_P_GENERAL | OPT_P_INLINE); if (p[1]) { options->auth_user_pass_file =3D p[1]; @@ -8568,15 +8414,15 @@ #ifdef _WIN32 VERIFY_PERMISSION(OPT_P_GENERAL); HANDLE process =3D GetCurrentProcess(); - HANDLE handle =3D (HANDLE) ((intptr_t) atoll(p[1])); - if (!DuplicateHandle(process, handle, process, &options->msg_chann= el, 0, - FALSE, DUPLICATE_CLOSE_SOURCE | DUPLICATE_SAM= E_ACCESS)) + HANDLE handle =3D (HANDLE)((intptr_t)atoll(p[1])); + if (!DuplicateHandle(process, handle, process, &options->msg_chann= el, 0, FALSE, + DUPLICATE_CLOSE_SOURCE | DUPLICATE_SAME_ACCES= S)) { msg(msglevel, "could not duplicate service pipe handle"); goto err; } options->route_method =3D ROUTE_METHOD_SERVICE; -#else /* ifdef _WIN32 */ +#else /* ifdef _WIN32 */ msg(msglevel, "--msg-channel is only supported on Windows"); goto err; #endif @@ -8588,8 +8434,8 @@ if (streq(p[1], "env")) { msg(M_INFO, "NOTE: --win-sys env is default from OpenVPN 2.3. = " - "This entry will now be ignored. " - "Please remove this entry from your configuration file."); + "This entry will now be ignored. " + "Please remove this entry from your configuration = file."); } else { @@ -8626,9 +8472,7 @@ if (index < 0) { - msg(msglevel, - "Bad --ip-win32 method: '%s'. Allowed methods: %s", - p[1], + msg(msglevel, "Bad --ip-win32 method: '%s'. Allowed methods: = %s", p[1], ipset2ascii_all(&gc)); goto err; } @@ -8648,7 +8492,9 @@ if (!(offset > -256 && offset < 256)) { - msg(msglevel, "--ip-win32 dynamic [offset] [lease-= time]: offset (%d) must be > -256 and < 256", offset); + msg(msglevel, + "--ip-win32 dynamic [offset] [lease-time]: off= set (%d) must be > -256 and < 256", + offset); goto err; } @@ -8663,7 +8509,9 @@ lease_time =3D atoi_warn(p[3], msglevel); if (lease_time < min_lease) { - msg(msglevel, "--ip-win32 dynamic [offset] [lease-= time]: lease time parameter (%d) must be at least %d seconds", lease_time, = min_lease); + msg(msglevel, + "--ip-win32 dynamic [offset] [lease-time]: lea= se time parameter (%d) must be at least %d seconds", + lease_time, min_lease); goto err; } to->dhcp_lease_time =3D lease_time; @@ -8803,10 +8651,11 @@ #endif else { - msg(msglevel, "--dhcp-option: unknown option type '%s' or miss= ing or unknown parameter", p[1]); + msg(msglevel, "--dhcp-option: unknown option type '%s' or miss= ing or unknown parameter", + p[1]); goto err; } -#else /* if defined(_WIN32) || defined(TARGET_ANDROID) */ +#else /* if defined(_WIN32) || defined(TARGET_ANDROID) */ setenv_foreign_option(options, p[1], p[2], es); #endif /* if defined(_WIN32) || defined(TARGET_ANDROID) */ @@ -8821,14 +8670,14 @@ else if (streq(p[0], "show-adapters") && !p[1]) { VERIFY_PERMISSION(OPT_P_GENERAL); - show_tap_win_adapters(M_INFO|M_NOPREFIX, M_WARN|M_NOPREFIX); + show_tap_win_adapters(M_INFO | M_NOPREFIX, M_WARN | M_NOPREFIX); openvpn_exit(OPENVPN_EXIT_STATUS_GOOD); /* exit point */ } else if (streq(p[0], "show-net") && !p[1]) { VERIFY_PERMISSION(OPT_P_GENERAL); - show_routes(M_INFO|M_NOPREFIX); - show_adapters(M_INFO|M_NOPREFIX); + show_routes(M_INFO | M_NOPREFIX); + show_adapters(M_INFO | M_NOPREFIX); openvpn_exit(OPENVPN_EXIT_STATUS_GOOD); /* exit point */ } else if (streq(p[0], "show-net-up") && !p[1]) @@ -8977,19 +8826,20 @@ if (streq(p[1], "no")) { - options->comp.flags =3D - COMP_F_ALLOW_STUB_ONLY|COMP_F_ADVERTISE_STUBS_ONLY; + options->comp.flags =3D COMP_F_ALLOW_STUB_ONLY | COMP_F_ADVERT= ISE_STUBS_ONLY; if (comp_non_stub_enabled(&options->comp)) { msg(msglevel, "'--allow-compression no' conflicts with " - " enabling compression"); + " enabling compression"); } } else if (options->comp.flags & COMP_F_ALLOW_STUB_ONLY) { /* Also printed on a push to hint at configuration problems */ - msg(msglevel, "Cannot set allow-compression to '%s' " - "after set to 'no'", p[1]); + msg(msglevel, + "Cannot set allow-compression to '%s' " + "after set to 'no'", + p[1]); goto err; } else if (streq(p[1], "asym")) @@ -8998,15 +8848,18 @@ } else if (streq(p[1], "yes")) { - msg(M_WARN, "DEPRECATED OPTION: \"--allow-compression yes\" ha= s been removed. " + msg(M_WARN, + "DEPRECATED OPTION: \"--allow-compression yes\" has been r= emoved. " "We will use \"asym\" mode instead. See the manual page fo= r more information."); options->comp.flags |=3D COMP_F_ALLOW_ASYM; } else { - msg(msglevel, "bad allow-compression option: %s -- " - "must be 'yes', 'no', or 'asym'", p[1]); + msg(msglevel, + "bad allow-compression option: %s -- " + "must be 'yes', 'no', or 'asym'", + p[1]); goto err; } } @@ -9030,7 +8883,8 @@ */ else if (!(streq(p[1], "yes") || streq(p[1], "adaptive"))) { - msg(msglevel, "bad comp-lzo option: %s -- must be 'yes', '= no', or 'adaptive'", p[1]); + msg(msglevel, "bad comp-lzo option: %s -- must be 'yes', '= no', or 'adaptive'", + p[1]); goto err; } } @@ -9052,7 +8906,7 @@ if (streq(alg, "stub")) { options->comp.alg =3D COMP_ALG_STUB; - options->comp.flags |=3D (COMP_F_SWAP|COMP_F_ADVERTISE_STUBS_O= NLY); + options->comp.flags |=3D (COMP_F_SWAP | COMP_F_ADVERTISE_STUBS= _ONLY); } else if (streq(alg, "stub-v2")) { @@ -9105,7 +8959,7 @@ { int key_direction; - VERIFY_PERMISSION(OPT_P_GENERAL|OPT_P_CONNECTION); + VERIFY_PERMISSION(OPT_P_GENERAL | OPT_P_CONNECTION); key_direction =3D ascii2keydirection(msglevel, p[1]); if (key_direction >=3D 0) @@ -9127,7 +8981,7 @@ else if (streq(p[0], "secret") && p[1] && !p[3]) { msg(M_WARN, "DEPRECATED OPTION: The option --secret is deprecated.= "); - VERIFY_PERMISSION(OPT_P_GENERAL|OPT_P_INLINE); + VERIFY_PERMISSION(OPT_P_GENERAL | OPT_P_INLINE); options->shared_secret_file =3D p[1]; options->shared_secret_file_inline =3D is_inline; if (!is_inline && p[2]) @@ -9149,7 +9003,6 @@ { VERIFY_PERMISSION(OPT_P_GENERAL); options->allow_deprecated_insecure_static_crypto =3D true; - } else if (streq(p[0], "genkey") && !p[4]) { @@ -9161,8 +9014,7 @@ } else { - if (streq(p[1], "secret") || streq(p[1], "tls-auth") - || streq(p[1], "tls-crypt")) + if (streq(p[1], "secret") || streq(p[1], "tls-auth") || streq(= p[1], "tls-crypt")) { options->genkey_type =3D GENKEY_SECRET; } @@ -9186,7 +9038,6 @@ { msg(msglevel, "unknown --genkey type: %s", p[1]); } - } if (p[2]) { @@ -9200,23 +9051,22 @@ } else if (streq(p[0], "cipher") && p[1] && !p[2]) { - VERIFY_PERMISSION(OPT_P_NCP|OPT_P_INSTANCE); + VERIFY_PERMISSION(OPT_P_NCP | OPT_P_INSTANCE); options->ciphername =3D p[1]; } else if (streq(p[0], "data-ciphers-fallback") && p[1] && !p[2]) { - VERIFY_PERMISSION(OPT_P_GENERAL|OPT_P_INSTANCE); + VERIFY_PERMISSION(OPT_P_GENERAL | OPT_P_INSTANCE); options->ciphername =3D p[1]; options->enable_ncp_fallback =3D true; } - else if ((streq(p[0], "data-ciphers") || streq(p[0], "ncp-ciphers")) - && p[1] && !p[2]) + else if ((streq(p[0], "data-ciphers") || streq(p[0], "ncp-ciphers")) &= & p[1] && !p[2]) { - VERIFY_PERMISSION(OPT_P_GENERAL|OPT_P_INSTANCE); + VERIFY_PERMISSION(OPT_P_GENERAL | OPT_P_INSTANCE); if (streq(p[0], "ncp-ciphers")) { msg(M_INFO, "Note: Treating option '--ncp-ciphers' as " - " '--data-ciphers' (renamed in OpenVPN 2.5)."); + " '--data-ciphers' (renamed in OpenVPN 2.5)."); } options->ncp_ciphers =3D p[1]; } @@ -9278,7 +9128,7 @@ VERIFY_PERMISSION(OPT_P_GENERAL); /* always error out, this breaks the connection */ msg(M_FATAL, "--no-replay was removed in OpenVPN 2.7. " - "Update your configuration."); + "Update your configuration."); } else if (streq(p[0], "replay-window") && !p[3]) { @@ -9291,9 +9141,7 @@ if (!(MIN_SEQ_BACKTRACK <=3D replay_window && replay_window <= =3D MAX_SEQ_BACKTRACK)) { msg(msglevel, "replay-window window size parameter (%d) mu= st be between %d and %d", - replay_window, - MIN_SEQ_BACKTRACK, - MAX_SEQ_BACKTRACK); + replay_window, MIN_SEQ_BACKTRACK, MAX_SEQ_BACKTRACK); goto err; } options->replay_window =3D replay_window; @@ -9305,10 +9153,9 @@ replay_time =3D atoi_warn(p[2], msglevel); if (!(MIN_TIME_BACKTRACK <=3D replay_time && replay_time <= =3D MAX_TIME_BACKTRACK)) { - msg(msglevel, "replay-window time window parameter (%d= ) must be between %d and %d", - replay_time, - MIN_TIME_BACKTRACK, - MAX_TIME_BACKTRACK); + msg(msglevel, + "replay-window time window parameter (%d) must be = between %d and %d", + replay_time, MIN_TIME_BACKTRACK, MAX_TIME_BACKTRAC= K); goto err; } options->replay_time =3D replay_time; @@ -9377,8 +9224,8 @@ { VERIFY_PERMISSION(OPT_P_GENERAL); msg(M_WARN, "Consider setting groups/curves preference with " - "tls-groups instead of forcing a specific curve with " - "ecdh-curve."); + "tls-groups instead of forcing a specific curve with " + "ecdh-curve."); options->ecdh_curve =3D p[1]; } else if (streq(p[0], "tls-server") && !p[1]) @@ -9393,7 +9240,7 @@ } else if (streq(p[0], "ca") && p[1] && !p[2]) { - VERIFY_PERMISSION(OPT_P_GENERAL|OPT_P_INLINE); + VERIFY_PERMISSION(OPT_P_GENERAL | OPT_P_INLINE); options->ca_file =3D p[1]; options->ca_file_inline =3D is_inline; } @@ -9406,33 +9253,33 @@ #endif /* ENABLE_CRYPTO_MBEDTLS */ else if (streq(p[0], "dh") && p[1] && !p[2]) { - VERIFY_PERMISSION(OPT_P_GENERAL|OPT_P_INLINE); + VERIFY_PERMISSION(OPT_P_GENERAL | OPT_P_INLINE); options->dh_file =3D p[1]; options->dh_file_inline =3D is_inline; } else if (streq(p[0], "cert") && p[1] && !p[2]) { - VERIFY_PERMISSION(OPT_P_GENERAL|OPT_P_INLINE); + VERIFY_PERMISSION(OPT_P_GENERAL | OPT_P_INLINE); options->cert_file =3D p[1]; options->cert_file_inline =3D is_inline; } else if (streq(p[0], "extra-certs") && p[1] && !p[2]) { - VERIFY_PERMISSION(OPT_P_GENERAL|OPT_P_INLINE); + VERIFY_PERMISSION(OPT_P_GENERAL | OPT_P_INLINE); options->extra_certs_file =3D p[1]; options->extra_certs_file_inline =3D is_inline; } else if ((streq(p[0], "verify-hash") && p[1] && !p[3]) || (streq(p[0], "peer-fingerprint") && p[1] && !p[2])) { - VERIFY_PERMISSION(OPT_P_GENERAL|OPT_P_INLINE); + VERIFY_PERMISSION(OPT_P_GENERAL | OPT_P_INLINE); int verify_hash_depth =3D 0; if (streq(p[0], "verify-hash")) { msg(M_WARN, "DEPRECATED OPTION: The option --verify-hash is de= precated. " - "You should switch to the either use the level 1 certifica= te as " - "--ca option, use --tls-verify or use --peer-fingerprint"); + "You should switch to the either use the level 1 c= ertificate as " + "--ca option, use --tls-verify or use --peer-finge= rprint"); /* verify level 1 cert, i.e. the CA that signed the leaf cert = */ verify_hash_depth =3D 1; } @@ -9443,8 +9290,10 @@ if (options->verify_hash && options->verify_hash_depth !=3D verify= _hash_depth) { - msg(msglevel, "ERROR: Setting %s not allowed. --verify-hash an= d" - " --peer-fingerprint are mutually exclusive", p[0]); + msg(msglevel, + "ERROR: Setting %s not allowed. --verify-hash and" + " --peer-fingerprint are mutually exclusive", + p[0]); goto err; } @@ -9457,15 +9306,16 @@ } else if (p[2] && !streq(p[2], "SHA256")) { - msg(msglevel, "invalid or unsupported hashing algorithm: %= s " - "(only SHA1 and SHA256 are supported)", p[2]); + msg(msglevel, + "invalid or unsupported hashing algorithm: %s " + "(only SHA1 and SHA256 are supported)", + p[2]); goto err; } } struct verify_hash_list *newlist; - newlist =3D parse_hash_fingerprint_multiline(p[1], digest_len, - msglevel, &options->gc); + newlist =3D parse_hash_fingerprint_multiline(p[1], digest_len, msg= level, &options->gc); /* Append the new list to the end of our current list */ if (!options->verify_hash) @@ -9494,7 +9344,7 @@ #endif else if (streq(p[0], "key") && p[1] && !p[2]) { - VERIFY_PERMISSION(OPT_P_GENERAL|OPT_P_INLINE); + VERIFY_PERMISSION(OPT_P_GENERAL | OPT_P_INLINE); options->priv_key_file =3D p[1]; options->priv_key_file_inline =3D is_inline; } @@ -9517,8 +9367,7 @@ } #endif - options->ssl_flags &=3D - ~(SSLF_TLS_VERSION_MIN_MASK << SSLF_TLS_VERSION_MIN_SHIFT); + options->ssl_flags &=3D ~(SSLF_TLS_VERSION_MIN_MASK << SSLF_TLS_VE= RSION_MIN_SHIFT); options->ssl_flags |=3D (ver << SSLF_TLS_VERSION_MIN_SHIFT); } else if (streq(p[0], "tls-version-max") && p[1] && !p[2]) @@ -9531,14 +9380,13 @@ msg(msglevel, "unknown tls-version-max parameter: %s", p[1]); goto err; } - options->ssl_flags &=3D - ~(SSLF_TLS_VERSION_MAX_MASK << SSLF_TLS_VERSION_MAX_SHIFT); + options->ssl_flags &=3D ~(SSLF_TLS_VERSION_MAX_MASK << SSLF_TLS_VE= RSION_MAX_SHIFT); options->ssl_flags |=3D (ver << SSLF_TLS_VERSION_MAX_SHIFT); } #ifndef ENABLE_CRYPTO_MBEDTLS else if (streq(p[0], "pkcs12") && p[1] && !p[2]) { - VERIFY_PERMISSION(OPT_P_GENERAL|OPT_P_INLINE); + VERIFY_PERMISSION(OPT_P_GENERAL | OPT_P_INLINE); options->pkcs12_file =3D p[1]; options->pkcs12_file_inline =3D is_inline; } @@ -9611,10 +9459,9 @@ VERIFY_PERMISSION(OPT_P_GENERAL); options->tls_groups =3D p[1]; } - else if (streq(p[0], "crl-verify") && p[1] && ((p[2] && streq(p[2], "d= ir")) - || !p[2])) + else if (streq(p[0], "crl-verify") && p[1] && ((p[2] && streq(p[2], "d= ir")) || !p[2])) { - VERIFY_PERMISSION(OPT_P_GENERAL|OPT_P_INLINE); + VERIFY_PERMISSION(OPT_P_GENERAL | OPT_P_INLINE); if (p[2] && streq(p[2], "dir")) { options->ssl_flags |=3D SSLF_CRL_VERIFY_DIR; @@ -9630,8 +9477,7 @@ goto err; } set_user_script(options, &options->tls_verify, - string_substitute(p[1], ',', ' ', &options->gc), - "tls-verify", true); + string_substitute(p[1], ',', ' ', &options->gc), "= tls-verify", true); } else if (streq(p[0], "tls-export-cert") && p[1] && !p[2]) { @@ -9642,14 +9488,14 @@ { VERIFY_PERMISSION(OPT_P_GENERAL); msg(msglevel, "--compat-names was removed in OpenVPN 2.5. " - "Update your configuration."); + "Update your configuration."); goto err; } else if (streq(p[0], "no-name-remapping") && !p[1]) { VERIFY_PERMISSION(OPT_P_GENERAL); msg(msglevel, "--no-name-remapping was removed in OpenVPN 2.5. " - "Update your configuration."); + "Update your configuration."); goto err; } else if (streq(p[0], "verify-x509-name") && p[1] && strlen(p[1]) && !p= [3]) @@ -9708,7 +9554,7 @@ size_t j; for (j =3D 1; j < MAX_PARMS && p[j] !=3D NULL; ++j) { - sscanf(p[j], "%x", &(options->remote_cert_ku[j-1])); + sscanf(p[j], "%x", &(options->remote_cert_ku[j - 1])); } if (j =3D=3D 1) { @@ -9793,7 +9639,7 @@ { int key_direction =3D -1; - VERIFY_PERMISSION(OPT_P_GENERAL|OPT_P_CONNECTION|OPT_P_INLINE); + VERIFY_PERMISSION(OPT_P_GENERAL | OPT_P_CONNECTION | OPT_P_INLINE); if (permission_mask & OPT_P_GENERAL) { @@ -9809,7 +9655,6 @@ } options->key_direction =3D key_direction; } - } else if (permission_mask & OPT_P_CONNECTION) { @@ -9830,7 +9675,7 @@ } else if (streq(p[0], "tls-crypt") && p[1] && !p[3]) { - VERIFY_PERMISSION(OPT_P_GENERAL|OPT_P_CONNECTION|OPT_P_INLINE); + VERIFY_PERMISSION(OPT_P_GENERAL | OPT_P_CONNECTION | OPT_P_INLINE); if (permission_mask & OPT_P_GENERAL) { options->tls_crypt_file =3D p[1]; @@ -9844,7 +9689,7 @@ } else if (streq(p[0], "tls-crypt-v2") && p[1] && !p[3]) { - VERIFY_PERMISSION(OPT_P_GENERAL|OPT_P_CONNECTION|OPT_P_INLINE); + VERIFY_PERMISSION(OPT_P_GENERAL | OPT_P_CONNECTION | OPT_P_INLINE); if (permission_mask & OPT_P_GENERAL) { options->tls_crypt_v2_file =3D p[1]; @@ -9887,19 +9732,19 @@ { char *s =3D p[j]; - if (strncmp("ext:", s, 4) =3D=3D 0 && !x509_username_field_ext= _supported(s+4)) + if (strncmp("ext:", s, 4) =3D=3D 0 && !x509_username_field_ext= _supported(s + 4)) { msg(msglevel, "Unsupported x509-username-field extension: = %s", s); } - options->x509_username_field[j-1] =3D p[j]; + options->x509_username_field[j - 1] =3D p[j]; } } #endif /* ENABLE_X509ALTUSERNAME */ #ifdef ENABLE_PKCS11 else if (streq(p[0], "show-pkcs11-ids") && !p[3]) { - char *provider =3D p[1]; - bool cert_private =3D (p[2] =3D=3D NULL ? false : (atoi_warn(p[2],= msglevel) !=3D 0 )); + char *provider =3D p[1]; + bool cert_private =3D (p[2] =3D=3D NULL ? false : (atoi_warn(p[2],= msglevel) !=3D 0)); #ifdef DEFAULT_PKCS11_MODULE if (!provider) @@ -9940,7 +9785,7 @@ for (j =3D 1; j < MAX_PARMS && p[j] !=3D NULL; ++j) { - options->pkcs11_providers[j-1] =3D p[j]; + options->pkcs11_providers[j - 1] =3D p[j]; } } else if (streq(p[0], "pkcs11-protected-authentication")) @@ -9951,7 +9796,8 @@ for (j =3D 1; j < MAX_PARMS && p[j] !=3D NULL; ++j) { - options->pkcs11_protected_authentication[j-1] =3D atoi_warn(p[= j], msglevel) !=3D 0 ? 1 : 0; + options->pkcs11_protected_authentication[j - 1] =3D + atoi_warn(p[j], msglevel) !=3D 0 ? 1 : 0; } } else if (streq(p[0], "pkcs11-private-mode") && p[1]) @@ -9962,7 +9808,7 @@ for (j =3D 1; j < MAX_PARMS && p[j] !=3D NULL; ++j) { - sscanf(p[j], "%x", &(options->pkcs11_private_mode[j-1])); + sscanf(p[j], "%x", &(options->pkcs11_private_mode[j - 1])); } } else if (streq(p[0], "pkcs11-cert-private")) @@ -9973,7 +9819,7 @@ for (j =3D 1; j < MAX_PARMS && p[j] !=3D NULL; ++j) { - options->pkcs11_cert_private[j-1] =3D (bool) (atoi_warn(p[j], = msglevel)); + options->pkcs11_cert_private[j - 1] =3D (bool)(atoi_warn(p[j],= msglevel)); } } else if (streq(p[0], "pkcs11-pin-cache") && p[1] && !p[2]) @@ -10019,13 +9865,13 @@ if (strncmp(p[1], "EXPORTER", 8)) { msg(msglevel, "Keying material exporter label must begin with " - "\"EXPORTER\""); + "\"EXPORTER\""); goto err; } if (streq(p[1], EXPORT_KEY_DATA_LABEL)) { - msg(msglevel, "Keying material exporter label must not be '" - EXPORT_KEY_DATA_LABEL "'."); + msg(msglevel, + "Keying material exporter label must not be '" EXPORT_KEY_= DATA_LABEL "'."); } if (ekm_length < 16 || ekm_length > 4095) { @@ -10069,13 +9915,12 @@ } else if (streq(p[0], "vlan-pvid") && p[1] && !p[2]) { - VERIFY_PERMISSION(OPT_P_GENERAL|OPT_P_INSTANCE); + VERIFY_PERMISSION(OPT_P_GENERAL | OPT_P_INSTANCE); options->vlan_pvid =3D positive_atoi(p[1], msglevel); if (options->vlan_pvid < OPENVPN_8021Q_MIN_VID || options->vlan_pvid > OPENVPN_8021Q_MAX_VID) { - msg(msglevel, - "the parameter of --vlan-pvid parameters must be >=3D %u a= nd <=3D %u", + msg(msglevel, "the parameter of --vlan-pvid parameters must be= >=3D %u and <=3D %u", OPENVPN_8021Q_MIN_VID, OPENVPN_8021Q_MAX_VID); goto err; } @@ -10096,11 +9941,14 @@ } if (file) { - msg(msglevel_unknown, "Unrecognized option or missing or extra= parameter(s) in %s:%d: %s (%s)", file, line, p[0], PACKAGE_VERSION); + msg(msglevel_unknown, + "Unrecognized option or missing or extra parameter(s) in %= s:%d: %s (%s)", file, + line, p[0], PACKAGE_VERSION); } else { - msg(msglevel_unknown, "Unrecognized option or missing or extra= parameter(s): --%s (%s)", p[0], PACKAGE_VERSION); + msg(msglevel_unknown, "Unrecognized option or missing or extra= parameter(s): --%s (%s)", + p[0], PACKAGE_VERSION); } } err: diff --git a/src/openvpn/options.h b/src/openvpn/options.h index dbd50f0..51468dd 100644 --- a/src/openvpn/options.h +++ b/src/openvpn/options.h @@ -121,33 +121,34 @@ const char *socks_proxy_port; const char *socks_proxy_authfile; - int tun_mtu; /* MTU of tun device */ - int occ_mtu; /* if non-null, this is the MTU we announce to pe= ers in OCC */ - int tun_mtu_max; /* maximum MTU that can be pushed */ + int tun_mtu; /* MTU of tun device */ + int occ_mtu; /* if non-null, this is the MTU we announce to p= eers in OCC */ + int tun_mtu_max; /* maximum MTU that can be pushed */ bool tun_mtu_defined; /* true if user overriding parm with command lin= e option */ int tun_mtu_extra; bool tun_mtu_extra_defined; - int link_mtu; /* MTU of device over which tunnel packets pass v= ia TCP/UDP */ + int link_mtu; /* MTU of device over which tunnel packets pass= via TCP/UDP */ bool link_mtu_defined; /* true if user overriding parm with command li= ne option */ - int tls_mtu; /* Maximum MTU for the control channel messages */ + int tls_mtu; /* Maximum MTU for the control channel messages= */ /* Advanced MTU negotiation and datagram fragmentation options */ int mtu_discover_type; /* used if OS supports setting Path MTU discove= ry options on socket */ =20 - int fragment; /* internal fragmentation size */ - bool fragment_encap; /* true if --fragment had the "mtu" parameter to - * include overhead from IP and TCP/UDP encapsula= tion */ - int mssfix; /* Upper bound on TCP MSS */ - bool mssfix_default; /* true if --mssfix should use the default parame= ters */ - bool mssfix_encap; /* true if --mssfix had the "mtu" parameter to in= clude - * overhead from IP and TCP/UDP encapsulation */ - bool mssfix_fixed; /* use the mssfix value without any encapsulation= adjustments */ + int fragment; /* internal fragmentation size */ + bool fragment_encap; /* true if --fragment had the "mtu" parameter to + * include overhead from IP and TCP/UDP encapsu= lation */ + int mssfix; /* Upper bound on TCP MSS */ + bool mssfix_default; /* true if --mssfix should use the default para= meters */ + bool mssfix_encap; /* true if --mssfix had the "mtu" parameter to = include + * overhead from IP and TCP/UDP encapsulation */ + bool mssfix_fixed; /* use the mssfix value without any encapsulati= on adjustments */ - int explicit_exit_notification; /* Explicitly tell peer when we are ex= iting via OCC_EXIT or [RESTART] message */ + int explicit_exit_notification; /* Explicitly tell peer when we are ex= iting via OCC_EXIT or + [RESTART] message */ -#define CE_DISABLED (1<<0) -#define CE_MAN_QUERY_PROXY (1<<1) +#define CE_DISABLED (1 << 0) +#define CE_MAN_QUERY_PROXY (1 << 1) #define CE_MAN_QUERY_REMOTE_UNDEF 0 #define CE_MAN_QUERY_REMOTE_QUERY 1 #define CE_MAN_QUERY_REMOTE_ACCEPT 2 @@ -230,7 +231,8 @@ char port[RH_PORT_LEN]; }; -enum genkey_type { +enum genkey_type +{ GENKEY_SECRET, GENKEY_TLS_CRYPTV2_CLIENT, GENKEY_TLS_CRYPTV2_SERVER, @@ -337,32 +339,32 @@ bool mlock; - int keepalive_ping; /* a proxy for ping/ping-restart */ + int keepalive_ping; /* a proxy for ping/ping-restart */ int keepalive_timeout; - int inactivity_timeout; /* --inactive */ + int inactivity_timeout; /* --inactive */ int64_t inactivity_minimum_bytes; - int session_timeout; /* Force-kill session after n seconds */ + int session_timeout; /* Force-kill session after n seconds */ - int ping_send_timeout; /* Send a TCP/UDP ping to remote every n s= econds */ - int ping_rec_timeout; /* Expect a TCP/UDP ping from remote at le= ast once every n seconds */ - bool ping_timer_remote; /* Run ping timer only if we have a remote= address */ + int ping_send_timeout; /* Send a TCP/UDP ping to remote every n secon= ds */ + int ping_rec_timeout; /* Expect a TCP/UDP ping from remote at least = once every n seconds */ + bool ping_timer_remote; /* Run ping timer only if we have a remote add= ress */ #define PING_UNDEF 0 #define PING_EXIT 1 #define PING_RESTART 2 int ping_rec_timeout_action; /* What action to take on ping_rec_timeou= t (exit or restart)? */ - bool persist_tun; /* Don't close/reopen TUN/TAP dev on SIGUS= R1 or PING_RESTART */ - bool persist_local_ip; /* Don't re-resolve local address on SIGUS= R1 or PING_RESTART */ - bool persist_remote_ip; /* Don't re-resolve remote address on SIGU= SR1 or PING_RESTART */ + bool persist_tun; /* Don't close/reopen TUN/TAP dev on SIGU= SR1 or PING_RESTART */ + bool persist_local_ip; /* Don't re-resolve local address on SIGU= SR1 or PING_RESTART */ + bool persist_remote_ip; /* Don't re-resolve remote address on SIG= USR1 or PING_RESTART */ #if PASSTOS_CAPABILITY bool passtos; #endif - int resolve_retry_seconds; /* If hostname resolve fails, retry for n = seconds */ + int resolve_retry_seconds; /* If hostname resolve fails, retry for n s= econds */ bool resolve_in_advance; const char *ip_remote_hint; @@ -433,7 +435,7 @@ int route_delay_window; bool route_delay_defined; struct route_option_list *routes; - struct route_ipv6_option_list *routes_ipv6; /* IPv6 */ + struct route_ipv6_option_list *routes_ipv6; /* IPv6 */ bool block_ipv6; bool route_nopull; bool route_gateway_via_dhcp; @@ -468,13 +470,13 @@ bool server_defined; in_addr_t server_network; in_addr_t server_netmask; - bool server_ipv6_defined; /* IPv6 */ - struct in6_addr server_network_ipv6; /* IPv6 */ - unsigned int server_netbits_ipv6; /* IPv6 */ + bool server_ipv6_defined; /* IPv6 */ + struct in6_addr server_network_ipv6; /* IPv6 */ + unsigned int server_netbits_ipv6; /* IPv6 */ -#define SF_NOPOOL (1<<0) -#define SF_TCP_NODELAY_HELPER (1<<1) -#define SF_NO_PUSH_ROUTE_GATEWAY (1<<2) +#define SF_NOPOOL (1 << 0) +#define SF_TCP_NODELAY_HELPER (1 << 1) +#define SF_NO_PUSH_ROUTE_GATEWAY (1 << 2) unsigned int server_flags; bool server_bridge_proxy_dhcp; @@ -493,9 +495,9 @@ const char *ifconfig_pool_persist_filename; int ifconfig_pool_persist_refresh_freq; - bool ifconfig_ipv6_pool_defined; /* IPv6 */ - struct in6_addr ifconfig_ipv6_pool_base; /* IPv6 */ - int ifconfig_ipv6_pool_netbits; /* IPv6 */ + bool ifconfig_ipv6_pool_defined; /* IPv6 */ + struct in6_addr ifconfig_ipv6_pool_base; /* IPv6 */ + int ifconfig_ipv6_pool_netbits; /* IPv6 */ int real_hash_size; int virtual_hash_size; @@ -510,7 +512,7 @@ int n_bcast_buf; int tcp_queue_limit; struct iroute *iroutes; - struct iroute_ipv6 *iroutes_ipv6; /* IPv6 */ + struct iroute_ipv6 *iroutes_ipv6; /* IPv6 */ bool push_ifconfig_defined; in_addr_t push_ifconfig_local; in_addr_t push_ifconfig_remote_netmask; @@ -518,12 +520,12 @@ bool push_ifconfig_constraint_defined; in_addr_t push_ifconfig_constraint_network; in_addr_t push_ifconfig_constraint_netmask; - bool push_ifconfig_ipv4_blocked; /* IPv4 */ - bool push_ifconfig_ipv6_defined; /* IPv6 */ - struct in6_addr push_ifconfig_ipv6_local; /* IPv6 */ - int push_ifconfig_ipv6_netbits; /* IPv6 */ - struct in6_addr push_ifconfig_ipv6_remote; /* IPv6 */ - bool push_ifconfig_ipv6_blocked; /* IPv6 */ + bool push_ifconfig_ipv4_blocked; /* IPv4 */ + bool push_ifconfig_ipv6_defined; /* IPv6 */ + struct in6_addr push_ifconfig_ipv6_local; /* IPv6 */ + int push_ifconfig_ipv6_netbits; /* IPv6 */ + struct in6_addr push_ifconfig_ipv6_remote; /* IPv6 */ + bool push_ifconfig_ipv6_blocked; /* IPv6 */ bool enable_c2c; bool duplicate_cn; @@ -572,8 +574,8 @@ bool allow_deprecated_insecure_static_crypto; int key_direction; const char *ciphername; - bool enable_ncp_fallback; /**< If defined fall back to - * ciphername if NCP fails */ + bool enable_ncp_fallback; /**< If defined fall back to + * ciphername if NCP fails */ /** The original ncp_ciphers specified by the user in the configuratio= n*/ const char *ncp_ciphers_conf; const char *ncp_ciphers; @@ -727,40 +729,40 @@ /* * Option classes. */ -#define OPT_P_GENERAL (1<<0) -#define OPT_P_UP (1<<1) -#define OPT_P_ROUTE (1<<2) -#define OPT_P_DHCPDNS (1<<3) /* includes ip windows options lik= e */ -#define OPT_P_SCRIPT (1<<4) -#define OPT_P_SETENV (1<<5) -#define OPT_P_SHAPER (1<<6) -#define OPT_P_TIMER (1<<7) -#define OPT_P_PERSIST (1<<8) -#define OPT_P_PERSIST_IP (1<<9) -#define OPT_P_COMP (1<<10) /* TODO */ -#define OPT_P_MESSAGES (1<<11) -#define OPT_P_NCP (1<<12) /**< Negotiable crypto parameters */ -#define OPT_P_TLS_PARMS (1<<13) /* TODO */ -#define OPT_P_MTU (1<<14) /* TODO */ -#define OPT_P_NICE (1<<15) -#define OPT_P_PUSH (1<<16) -#define OPT_P_INSTANCE (1<<17) /**< allowed in ccd, client-connect = etc*/ -#define OPT_P_CONFIG (1<<18) -#define OPT_P_EXPLICIT_NOTIFY (1<<19) -#define OPT_P_ECHO (1<<20) -#define OPT_P_INHERIT (1<<21) -#define OPT_P_ROUTE_EXTRAS (1<<22) -#define OPT_P_PULL_MODE (1<<23) -#define OPT_P_PLUGIN (1<<24) -#define OPT_P_SOCKBUF (1<<25) -#define OPT_P_SOCKFLAGS (1<<26) -#define OPT_P_CONNECTION (1<<27) -#define OPT_P_PEER_ID (1<<28) -#define OPT_P_INLINE (1<<29) -#define OPT_P_PUSH_MTU (1<<30) -#define OPT_P_ROUTE_TABLE (1<<31) +#define OPT_P_GENERAL (1 << 0) +#define OPT_P_UP (1 << 1) +#define OPT_P_ROUTE (1 << 2) +#define OPT_P_DHCPDNS (1 << 3) /* includes ip windows options like= */ +#define OPT_P_SCRIPT (1 << 4) +#define OPT_P_SETENV (1 << 5) +#define OPT_P_SHAPER (1 << 6) +#define OPT_P_TIMER (1 << 7) +#define OPT_P_PERSIST (1 << 8) +#define OPT_P_PERSIST_IP (1 << 9) +#define OPT_P_COMP (1 << 10) /* TODO */ +#define OPT_P_MESSAGES (1 << 11) +#define OPT_P_NCP (1 << 12) /**< Negotiable crypto parameters = */ +#define OPT_P_TLS_PARMS (1 << 13) /* TODO */ +#define OPT_P_MTU (1 << 14) /* TODO */ +#define OPT_P_NICE (1 << 15) +#define OPT_P_PUSH (1 << 16) +#define OPT_P_INSTANCE (1 << 17) /**< allowed in ccd, client-connec= t etc*/ +#define OPT_P_CONFIG (1 << 18) +#define OPT_P_EXPLICIT_NOTIFY (1 << 19) +#define OPT_P_ECHO (1 << 20) +#define OPT_P_INHERIT (1 << 21) +#define OPT_P_ROUTE_EXTRAS (1 << 22) +#define OPT_P_PULL_MODE (1 << 23) +#define OPT_P_PLUGIN (1 << 24) +#define OPT_P_SOCKBUF (1 << 25) +#define OPT_P_SOCKFLAGS (1 << 26) +#define OPT_P_CONNECTION (1 << 27) +#define OPT_P_PEER_ID (1 << 28) +#define OPT_P_INLINE (1 << 29) +#define OPT_P_PUSH_MTU (1 << 30) +#define OPT_P_ROUTE_TABLE (1 << 31) -#define OPT_P_DEFAULT (~(OPT_P_INSTANCE|OPT_P_PULL_MODE)) +#define OPT_P_DEFAULT (~(OPT_P_INSTANCE | OPT_P_PULL_MODE)) #define PULL_DEFINED(opt) ((opt)->pull) #define PUSH_DEFINED(opt) ((opt)->push_list) @@ -796,18 +798,18 @@ /* * some PUSH_UPDATE options */ -#define OPT_P_U_ROUTE (1<<0) -#define OPT_P_U_ROUTE6 (1<<1) -#define OPT_P_U_DNS (1<<2) -#define OPT_P_U_DHCP (1<<3) -#define OPT_P_U_REDIR_GATEWAY (1<<4) +#define OPT_P_U_ROUTE (1 << 0) +#define OPT_P_U_ROUTE6 (1 << 1) +#define OPT_P_U_DNS (1 << 2) +#define OPT_P_U_DHCP (1 << 3) +#define OPT_P_U_REDIR_GATEWAY (1 << 4) struct pull_filter { -#define PUF_TYPE_UNDEF 0 /**< undefined filter type */ -#define PUF_TYPE_ACCEPT 1 /**< filter type to accept a matching option = */ -#define PUF_TYPE_IGNORE 2 /**< filter type to ignore a matching option = */ -#define PUF_TYPE_REJECT 3 /**< filter type to reject and trigger SIGUSR= 1 */ +#define PUF_TYPE_UNDEF 0 /**< undefined filter type */ +#define PUF_TYPE_ACCEPT 1 /**< filter type to accept a matching option */ +#define PUF_TYPE_IGNORE 2 /**< filter type to ignore a matching option */ +#define PUF_TYPE_REJECT 3 /**< filter type to reject and trigger SIGUSR1 */ int type; int size; char *pattern; @@ -820,12 +822,8 @@ struct pull_filter *tail; }; -void parse_argv(struct options *options, - const int argc, - char *argv[], - const int msglevel, - const unsigned int permission_mask, - unsigned int *option_types_found, +void parse_argv(struct options *options, const int argc, char *argv[], con= st int msglevel, + const unsigned int permission_mask, unsigned int *option_t= ypes_found, struct env_set *es); void notnull(const char *arg, const char *description); @@ -853,12 +851,8 @@ const char *options_string_version(const char *s, struct gc_arena *gc); -char *options_string(const struct options *o, - const struct frame *frame, - struct tuntap *tt, - openvpn_net_ctx_t *ctx, - bool remote, - struct gc_arena *gc); +char *options_string(const struct options *o, const struct frame *frame, s= truct tuntap *tt, + openvpn_net_ctx_t *ctx, bool remote, struct gc_arena = *gc); bool options_cmp_equal_safe(char *actual, const char *expected, size_t act= ual_n); @@ -878,8 +872,8 @@ * @return gc-allocated value of option with name opt_name if option was f= ound, * or NULL otherwise. */ -char *options_string_extract_option(const char *options_string, - const char *opt_name, struct gc_arena = *gc); +char *options_string_extract_option(const char *options_string, const char= *opt_name, + struct gc_arena *gc); void options_postprocess(struct options *options, struct env_set *es); @@ -888,34 +882,22 @@ void pre_connect_restore(struct options *o, struct gc_arena *gc); -bool apply_push_options(struct context *c, - struct options *options, - struct buffer *buf, - unsigned int permission_mask, - unsigned int *option_types_found, - struct env_set *es, - bool is_update); +bool apply_push_options(struct context *c, struct options *options, struct= buffer *buf, + unsigned int permission_mask, unsigned int *option= _types_found, + struct env_set *es, bool is_update); void options_detach(struct options *o); -void options_server_import(struct options *o, - const char *filename, - int msglevel, - unsigned int permission_mask, - unsigned int *option_types_found, +void options_server_import(struct options *o, const char *filename, int ms= glevel, + unsigned int permission_mask, unsigned int *opt= ion_types_found, struct env_set *es); void pre_pull_default(struct options *o); void rol_check_alloc(struct options *options); -int parse_line(const char *line, - char *p[], - const int n, - const char *file, - const int line_num, - int msglevel, - struct gc_arena *gc); +int parse_line(const char *line, char *p[], const int n, const char *file,= const int line_num, + int msglevel, struct gc_arena *gc); /* * parse/print topology coding @@ -939,11 +921,8 @@ const char *auth_retry_print(void); -void options_string_import(struct options *options, - const char *config, - const int msglevel, - const unsigned int permission_mask, - unsigned int *option_types_found, +void options_string_import(struct options *options, const char *config, co= nst int msglevel, + const unsigned int permission_mask, unsigned in= t *option_types_found, struct env_set *es); bool key_is_external(const struct options *options); diff --git a/src/openvpn/options_util.c b/src/openvpn/options_util.c index e469c28..5251b21 100644 --- a/src/openvpn/options_util.c +++ b/src/openvpn/options_util.c @@ -124,12 +124,11 @@ if (i < 0 || *endptr !=3D '\0' || i > INT_MAX) { - msg(msglevel, "Cannot parse argument '%s' as non-negative integer", - str); + msg(msglevel, "Cannot parse argument '%s' as non-negative integer"= , str); i =3D 0; } - return (int) i; + return (int)i; } int @@ -144,27 +143,17 @@ i =3D 0; } - return (int) i; + return (int)i; } -static const char *updatable_options[] =3D { - "block-ipv6", - "block-outside-dns", - "dhcp-option", - "dns", - "ifconfig", - "ifconfig-ipv6", - "push-continuation", - "redirect-gateway", - "redirect-private", - "route", - "route-gateway", - "route-ipv6", - "route-metric", - "topology", - "tun-mtu", - "keepalive" -}; +static const char *updatable_options[] =3D { "block-ipv6", "block-o= utside-dns", + "dhcp-option", "dns", + "ifconfig", "ifconfig-= ipv6", + "push-continuation", "redirect-= gateway", + "redirect-private", "route", + "route-gateway", "route-ipv= 6", + "route-metric", "topology", + "tun-mtu", "keepalive= " }; bool check_push_update_option_flags(char *line, int *i, unsigned int *flags) @@ -196,7 +185,7 @@ } size_t len =3D strlen(&line[*i]); - int count =3D sizeof(updatable_options)/sizeof(char *); + int count =3D sizeof(updatable_options) / sizeof(char *); for (int j =3D 0; j < count; ++j) { size_t opt_len =3D strlen(updatable_options[j]); diff --git a/src/openvpn/options_util.h b/src/openvpn/options_util.h index 23fd78d..6f81b1e 100644 --- a/src/openvpn/options_util.h +++ b/src/openvpn/options_util.h @@ -26,28 +26,24 @@ #include "options.h" -const char * -parse_auth_failed_temp(struct options *o, const char *reason); +const char *parse_auth_failed_temp(struct options *o, const char *reason); /** Checks if the string is a valid integer by checking if it can be * converted to an integer */ -bool -valid_integer(const char *str, bool positive); +bool valid_integer(const char *str, bool positive); /** * Converts a str to a positive number if the string represents a postive * integer number. Otherwise print a warning with msglevel and return 0 */ -int -positive_atoi(const char *str, int msglevel); +int positive_atoi(const char *str, int msglevel); /** * Converts a str to an integer if the string can be represented as an * integer number. Otherwise print a warning with msglevel and return 0 */ -int -atoi_warn(const char *str, int msglevel); +int atoi_warn(const char *str, int msglevel); /** * Filter an option line by all pull filters. @@ -57,9 +53,7 @@ * reject, SIGUSR1 is triggered and the return value is false. * In that case the caller must end the push processing. */ -bool -apply_pull_filter(const struct options *o, - char *line); +bool apply_pull_filter(const struct options *o, char *line); /** * @brief Checks the formatting and validity of options inside push-update= messages. @@ -89,7 +83,6 @@ * - The `line` parameter is empty or `NULL`. * - The `?` flag is absent and the option is not updatable. */ -bool -check_push_update_option_flags(char *line, int *i, unsigned int *flags); +bool check_push_update_option_flags(char *line, int *i, unsigned int *flag= s); =20 #endif /* ifndef OPTIONS_UTIL_H_ */ diff --git a/src/openvpn/otime.c b/src/openvpn/otime.c index d6b9c2c..717f749 100644 --- a/src/openvpn/otime.c +++ b/src/openvpn/otime.c @@ -83,9 +83,7 @@ tv_string(const struct timeval *tv, struct gc_arena *gc) { struct buffer out =3D alloc_buf_gc(64, gc); - buf_printf(&out, "[%" PRIi64 "/%ld]", - (int64_t)tv->tv_sec, - (long)tv->tv_usec); + buf_printf(&out, "[%" PRIi64 "/%ld]", (int64_t)tv->tv_sec, (long)tv->t= v_usec); return BSTR(&out); } @@ -97,10 +95,7 @@ const char * tv_string_abs(const struct timeval *tv, struct gc_arena *gc) { - return time_string((time_t) tv->tv_sec, - (long) tv->tv_usec, - true, - gc); + return time_string((time_t)tv->tv_sec, (long)tv->tv_usec, true, gc); } /* format a time_t as ascii, or use current time if 0 */ @@ -124,9 +119,8 @@ t =3D tv.tv_sec; struct tm *tm =3D localtime(&t); - buf_printf(&out, "%04d-%02d-%02d %02d:%02d:%02d", - tm->tm_year+1900, tm->tm_mon+1, tm->tm_mday, - tm->tm_hour, tm->tm_min, tm->tm_sec); + buf_printf(&out, "%04d-%02d-%02d %02d:%02d:%02d", tm->tm_year + 1900, = tm->tm_mon + 1, + tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec); if (show_usec && tv.tv_usec) { @@ -196,9 +190,7 @@ t =3D time(NULL); gettimeofday(&tv, NULL); #if 1 - msg(M_INFO, "t=3D%" PRIi64 " s=3D%" PRIi64 " us=3D%ld", - (int64_t)t, - (int64_t)tv.tv_sec, + msg(M_INFO, "t=3D%" PRIi64 " s=3D%" PRIi64 " us=3D%ld", (int64_t)t= , (int64_t)tv.tv_sec, (long)tv.tv_usec); #endif } diff --git a/src/openvpn/otime.h b/src/openvpn/otime.h index 29e8046..5c700bb 100644 --- a/src/openvpn/otime.h +++ b/src/openvpn/otime.h @@ -236,7 +236,7 @@ dest->tv_usec =3D usec; } -#define TV_WITHIN_SIGMA_MAX_SEC 600 +#define TV_WITHIN_SIGMA_MAX_SEC 600 #define TV_WITHIN_SIGMA_MAX_USEC (TV_WITHIN_SIGMA_MAX_SEC * 1000000) /* @@ -259,7 +259,7 @@ { if (at > current) { - const interval_t delta =3D (interval_t) (at - current); + const interval_t delta =3D (interval_t)(at - current); if (delta < *wakeup) { *wakeup =3D delta; diff --git a/src/openvpn/ovpn_dco_freebsd.h b/src/openvpn/ovpn_dco_freebsd.h index 7eb643b..6006b54 100644 --- a/src/openvpn/ovpn_dco_freebsd.h +++ b/src/openvpn/ovpn_dco_freebsd.h @@ -32,42 +32,46 @@ #include /* Maximum size of an ioctl request. */ -#define OVPN_MAX_REQUEST_SIZE 4096 +#define OVPN_MAX_REQUEST_SIZE 4096 -enum ovpn_notif_type { +enum ovpn_notif_type +{ OVPN_NOTIF_DEL_PEER, OVPN_NOTIF_ROTATE_KEY, OVPN_NOTIF_FLOAT, }; -enum ovpn_del_reason { - OVPN_DEL_REASON_REQUESTED =3D 0, - OVPN_DEL_REASON_TIMEOUT =3D 1 +enum ovpn_del_reason +{ + OVPN_DEL_REASON_REQUESTED =3D 0, + OVPN_DEL_REASON_TIMEOUT =3D 1 }; -enum ovpn_key_slot { - OVPN_KEY_SLOT_PRIMARY =3D 0, +enum ovpn_key_slot +{ + OVPN_KEY_SLOT_PRIMARY =3D 0, OVPN_KEY_SLOT_SECONDARY =3D 1 }; -enum ovpn_key_cipher { - OVPN_CIPHER_ALG_NONE =3D 0, - OVPN_CIPHER_ALG_AES_GCM =3D 1, - OVPN_CIPHER_ALG_CHACHA20_POLY1305 =3D 2 +enum ovpn_key_cipher +{ + OVPN_CIPHER_ALG_NONE =3D 0, + OVPN_CIPHER_ALG_AES_GCM =3D 1, + OVPN_CIPHER_ALG_CHACHA20_POLY1305 =3D 2 }; -#define OVPN_NEW_PEER _IO('D', 1) -#define OVPN_DEL_PEER _IO('D', 2) -#define OVPN_GET_STATS _IO('D', 3) -#define OVPN_NEW_KEY _IO('D', 4) -#define OVPN_SWAP_KEYS _IO('D', 5) -#define OVPN_DEL_KEY _IO('D', 6) -#define OVPN_SET_PEER _IO('D', 7) -#define OVPN_START_VPN _IO('D', 8) -#define OVPN_SEND_PKT _IO('D', 9) -#define OVPN_POLL_PKT _IO('D', 10) -#define OVPN_GET_PKT _IO('D', 11) -#define OVPN_SET_IFMODE _IO('D', 12) -#define OVPN_GET_PEER_STATS _IO('D', 13) +#define OVPN_NEW_PEER _IO('D', 1) +#define OVPN_DEL_PEER _IO('D', 2) +#define OVPN_GET_STATS _IO('D', 3) +#define OVPN_NEW_KEY _IO('D', 4) +#define OVPN_SWAP_KEYS _IO('D', 5) +#define OVPN_DEL_KEY _IO('D', 6) +#define OVPN_SET_PEER _IO('D', 7) +#define OVPN_START_VPN _IO('D', 8) +#define OVPN_SEND_PKT _IO('D', 9) +#define OVPN_POLL_PKT _IO('D', 10) +#define OVPN_GET_PKT _IO('D', 11) +#define OVPN_SET_IFMODE _IO('D', 12) +#define OVPN_GET_PEER_STATS _IO('D', 13) #endif /* ifndef _NET_IF_OVPN_H_ */ diff --git a/src/openvpn/packet_id.c b/src/openvpn/packet_id.c index e6ca601..09696db 100644 --- a/src/openvpn/packet_id.c +++ b/src/openvpn/packet_id.c @@ -53,20 +53,15 @@ #define SEQ_EXPIRED ((time_t)1) #ifdef ENABLE_DEBUG -static void packet_id_debug_print(int msglevel, - const struct packet_id_rec *p, - const struct packet_id_net *pin, - const char *message, +static void packet_id_debug_print(int msglevel, const struct packet_id_rec= *p, + const struct packet_id_net *pin, const c= har *message, packet_id_print_type value); #endif /* ENABLE_DEBUG */ static inline void -packet_id_debug(int msglevel, - const struct packet_id_rec *p, - const struct packet_id_net *pin, - const char *message, - uint64_t value) +packet_id_debug(int msglevel, const struct packet_id_rec *p, const struct = packet_id_net *pin, + const char *message, uint64_t value) { #ifdef ENABLE_DEBUG if (unlikely(check_debug_level(msglevel))) @@ -77,7 +72,8 @@ } static void -packet_id_init_recv(struct packet_id_rec *rec, int seq_backtrack, int time= _backtrack, const char *name, int unit) +packet_id_init_recv(struct packet_id_rec *rec, int seq_backtrack, int time= _backtrack, + const char *name, int unit) { rec->name =3D name; rec->unit =3D unit; @@ -92,10 +88,10 @@ rec->initialized =3D true; } void -packet_id_init(struct packet_id *p, int seq_backtrack, int time_backtrack,= const char *name, int unit) +packet_id_init(struct packet_id *p, int seq_backtrack, int time_backtrack,= const char *name, + int unit) { - dmsg(D_PID_DEBUG, "PID packet_id_init seq_backtrack=3D%d time_backtrac= k=3D%d", - seq_backtrack, + dmsg(D_PID_DEBUG, "PID packet_id_init seq_backtrack=3D%d time_backtrac= k=3D%d", seq_backtrack, time_backtrack); ASSERT(p); @@ -118,8 +114,7 @@ /* Reinitalise the source */ CLEAR(*src); - packet_id_init_recv(src, dest->seq_backtrack, dest->time_backtrack, - dest->name, dest->unit); + packet_id_init_recv(src, dest->seq_backtrack, dest->time_backtrack, de= st->name, dest->unit); } void @@ -145,10 +140,8 @@ * If time value increases, start a new sequence list of number * sequence for the new time point. */ - if (!CIRC_LIST_SIZE(p->seq_list) - || pin->time > p->time - || (pin->id >=3D p->seq_backtrack - && pin->id - p->seq_backtrack > p->id)) + if (!CIRC_LIST_SIZE(p->seq_list) || pin->time > p->time + || (pin->id >=3D p->seq_backtrack && pin->id - p->seq_backtrac= k > p->id)) { p->time =3D pin->time; p->id =3D 0; @@ -163,15 +156,14 @@ #ifdef PID_SIMULATE_BACKTRACK || (get_random() % 64) < 31 #endif - ) + ) { CIRC_LIST_PUSH(p->seq_list, SEQ_UNSEEN); ++p->id; } diff =3D p->id - pin->id; - if (diff < CIRC_LIST_SIZE(p->seq_list) - && local_now > SEQ_EXPIRED) + if (diff < CIRC_LIST_SIZE(p->seq_list) && local_now > SEQ_EXPIRED) { CIRC_LIST_ITEM(p->seq_list, diff) =3D local_now; } @@ -220,8 +212,7 @@ * it is a replay. */ bool -packet_id_test(struct packet_id_rec *p, - const struct packet_id_net *pin) +packet_id_test(struct packet_id_rec *p, const struct packet_id_net *pin) { uint64_t diff; @@ -257,10 +248,11 @@ if (diff > p->max_backtrack_stat) { p->max_backtrack_stat =3D diff; - packet_id_debug(D_PID_DEBUG_LOW, p, pin, "PID_ERR replay-w= indow backtrack occurred", p->max_backtrack_stat); + packet_id_debug(D_PID_DEBUG_LOW, p, pin, "PID_ERR replay-w= indow backtrack occurred", + p->max_backtrack_stat); } - if (diff >=3D (packet_id_type) CIRC_LIST_SIZE(p->seq_list)) + if (diff >=3D (packet_id_type)CIRC_LIST_SIZE(p->seq_list)) { packet_id_debug(D_PID_DEBUG_LOW, p, pin, "PID_ERR large di= ff", diff); return false; @@ -285,7 +277,7 @@ packet_id_debug(D_PID_DEBUG_LOW, p, pin, "PID_ERR time backtra= ck", 0); return false; } - else /* time moved forward */ + else /* time moved forward */ { return true; } @@ -306,7 +298,7 @@ { return false; } - else /* time moved forward */ + else /* time moved forward */ { return pin->id =3D=3D 1; } @@ -382,8 +374,7 @@ } bool -packet_id_write(struct packet_id_send *p, struct buffer *buf, bool long_fo= rm, - bool prepend) +packet_id_write(struct packet_id_send *p, struct buffer *buf, bool long_fo= rm, bool prepend) { if (!packet_id_send_update(p, long_form)) { @@ -431,8 +422,7 @@ buf_printf(&out, "[ #" packet_id_format, (packet_id_print_type)pin->id= ); if (print_timestamp && pin->time) { - buf_printf(&out, " / time =3D (" packet_id_format ") %s", - (packet_id_print_type)pin->time, + buf_printf(&out, " / time =3D (" packet_id_format ") %s", (packet_= id_print_type)pin->time, time_string(pin->time, 0, false, gc)); } @@ -472,13 +462,10 @@ if (!packet_id_persist_enabled(p)) { /* open packet-id persist file for both read and write */ - p->fd =3D platform_open(filename, - O_CREAT | O_RDWR | O_BINARY, - S_IRUSR | S_IWUSR); + p->fd =3D platform_open(filename, O_CREAT | O_RDWR | O_BINARY, S_I= RUSR | S_IWUSR); if (p->fd =3D=3D -1) { - msg(D_PID_PERSIST | M_ERRNO, - "Cannot open --replay-persist file %s for read/write", + msg(D_PID_PERSIST | M_ERRNO, "Cannot open --replay-persist fil= e %s for read/write", filename); } else @@ -499,14 +486,12 @@ { p->time =3D p->time_last_written =3D image.time; p->id =3D p->id_last_written =3D image.id; - dmsg(D_PID_PERSIST_DEBUG, "PID Persist Read from %s: %s", - p->filename, packet_id_persist_print(p, &gc)); + dmsg(D_PID_PERSIST_DEBUG, "PID Persist Read from %s: %s", = p->filename, + packet_id_persist_print(p, &gc)); } else if (n =3D=3D -1) { - msg(D_PID_PERSIST | M_ERRNO, - "Read error on --replay-persist file %s", - p->filename); + msg(D_PID_PERSIST | M_ERRNO, "Read error on --replay-persi= st file %s", p->filename); } } } @@ -517,8 +502,8 @@ void packet_id_persist_save(struct packet_id_persist *p) { - if (packet_id_persist_enabled(p) && p->time && (p->time !=3D p->time_l= ast_written - || p->id !=3D p->id_la= st_written)) + if (packet_id_persist_enabled(p) && p->time + && (p->time !=3D p->time_last_written || p->id !=3D p->id_last_wri= tten)) { struct packet_id_persist_file_image image; ssize_t n; @@ -535,20 +520,18 @@ { p->time_last_written =3D p->time; p->id_last_written =3D p->id; - dmsg(D_PID_PERSIST_DEBUG, "PID Persist Write to %s: %s", - p->filename, packet_id_persist_print(p, &gc)); + dmsg(D_PID_PERSIST_DEBUG, "PID Persist Write to %s: %s", p= ->filename, + packet_id_persist_print(p, &gc)); } else { - msg(D_PID_PERSIST | M_ERRNO, - "Cannot write to --replay-persist file %s", + msg(D_PID_PERSIST | M_ERRNO, "Cannot write to --replay-per= sist file %s", p->filename); } } else { - msg(D_PID_PERSIST | M_ERRNO, - "Cannot seek to beginning of --replay-persist file %s", + msg(D_PID_PERSIST | M_ERRNO, "Cannot seek to beginning of --re= play-persist file %s", p->filename); } gc_free(&gc); @@ -578,8 +561,7 @@ buf_printf(&out, " #" packet_id_format, (packet_id_print_type)p->i= d); if (p->time) { - buf_printf(&out, " / time =3D (" packet_id_format ") %s", - (packet_id_print_type)p->time, + buf_printf(&out, " / time =3D (" packet_id_format ") %s", (pac= ket_id_print_type)p->time, time_string(p->time, 0, false, gc)); } } @@ -591,11 +573,8 @@ #ifdef ENABLE_DEBUG static void -packet_id_debug_print(int msglevel, - const struct packet_id_rec *p, - const struct packet_id_net *pin, - const char *message, - packet_id_print_type value) +packet_id_debug_print(int msglevel, const struct packet_id_rec *p, const s= truct packet_id_net *pin, + const char *message, packet_id_print_type value) { struct gc_arena gc =3D gc_new(); struct buffer out =3D alloc_buf_gc(256, &gc); @@ -648,23 +627,13 @@ buf_printf(&out, " %" PRIi64 ":" packet_id_format, (int64_t)pin->t= ime, pin->id); } - buf_printf(&out, " t=3D%" PRIi64 "[%d]", - (int64_t)prev_now, - (int)(prev_now - tv.tv_sec)); + buf_printf(&out, " t=3D%" PRIi64 "[%d]", (int64_t)prev_now, (int)(prev= _now - tv.tv_sec)); - buf_printf(&out, " r=3D[%d,%" PRIu64 ",%d,%" PRIu64 ",%d]", - (int)(p->last_reap - tv.tv_sec), - p->seq_backtrack, - p->time_backtrack, - p->max_backtrack_stat, - (int)p->initialized); + buf_printf(&out, " r=3D[%d,%" PRIu64 ",%d,%" PRIu64 ",%d]", (int)(p->l= ast_reap - tv.tv_sec), + p->seq_backtrack, p->time_backtrack, p->max_backtrack_stat,= (int)p->initialized); if (sl !=3D NULL) { - buf_printf(&out, " sl=3D[%d,%d,%d,%d]", - sl->x_head, - sl->x_size, - sl->x_cap, - sl->x_sizeof); + buf_printf(&out, " sl=3D[%d,%d,%d,%d]", sl->x_head, sl->x_size, sl= ->x_cap, sl->x_sizeof); } @@ -704,7 +673,7 @@ /* Highest 16 bits of packet id is the epoch. * * The lower 48 bits are the per-epoch packet id counter. */ - uint64_t net_id =3D ((uint64_t) epoch) << 48 | p->id; + uint64_t net_id =3D ((uint64_t)epoch) << 48 | p->id; /* convert to network order. This ensures that the highest bytes * also become the first ones on the wire*/ diff --git a/src/openvpn/packet_id.h b/src/openvpn/packet_id.h index 8bb6951..a7eb256 100644 --- a/src/openvpn/packet_id.h +++ b/src/openvpn/packet_id.h @@ -43,11 +43,11 @@ * These are ephemeral and are never saved to a file. */ typedef uint32_t packet_id_type; -#define PACKET_ID_MAX UINT32_MAX -#define PACKET_ID_EPOCH_MAX 0x0000ffffffffffffull +#define PACKET_ID_MAX UINT32_MAX +#define PACKET_ID_EPOCH_MAX 0x0000ffffffffffffull /** Mask of the bits that contain the 48-bit of the per-epoch packet * counter in the packet id*/ -#define PACKET_ID_MASK 0x0000ffffffffffffull +#define PACKET_ID_MASK 0x0000ffffffffffffull typedef uint32_t net_time_t; /* @@ -81,8 +81,8 @@ * sequence number due to packets arriving * out of order. */ -#define MIN_SEQ_BACKTRACK 0 -#define MAX_SEQ_BACKTRACK 65536 +#define MIN_SEQ_BACKTRACK 0 +#define MAX_SEQ_BACKTRACK 65536 #define DEFAULT_SEQ_BACKTRACK 64 /* @@ -90,8 +90,8 @@ * seconds due to packets arriving * out of order. */ -#define MIN_TIME_BACKTRACK 0 -#define MAX_TIME_BACKTRACK 600 +#define MIN_TIME_BACKTRACK 0 +#define MAX_TIME_BACKTRACK 600 #define DEFAULT_TIME_BACKTRACK 15 /* @@ -112,14 +112,14 @@ */ struct packet_id_rec { - time_t last_reap; /* last call of packet_id_reap */ - time_t time; /* highest time stamp received */ - uint64_t id; /* highest sequence number received */ - uint64_t seq_backtrack; /* set from --replay-window */ - int time_backtrack; /* set from --replay-window */ - uint64_t max_backtrack_stat; /* maximum backtrack seen so far */ - bool initialized; /* true if packet_id_init was called */ - struct seq_list *seq_list; /* packet-id "memory" */ + time_t last_reap; /* last call of packet_id_reap */ + time_t time; /* highest time stamp received */ + uint64_t id; /* highest sequence number received */ + uint64_t seq_backtrack; /* set from --replay-window */ + int time_backtrack; /* set from --replay-window */ + uint64_t max_backtrack_stat; /* maximum backtrack seen so far */ + bool initialized; /* true if packet_id_init was called */ + struct seq_list *seq_list; /* packet-id "memory" */ const char *name; int unit; }; @@ -132,16 +132,16 @@ { const char *filename; int fd; - time_t time; /* time stamp */ - packet_id_type id; /* sequence number */ + time_t time; /* time stamp */ + packet_id_type id; /* sequence number */ time_t time_last_written; packet_id_type id_last_written; }; struct packet_id_persist_file_image { - time_t time; /* time stamp */ - packet_id_type id; /* sequence number */ + time_t time; /* time stamp */ + packet_id_type id; /* sequence number */ }; /* @@ -201,7 +201,8 @@ struct packet_id_rec rec; }; -void packet_id_init(struct packet_id *p, int seq_backtrack, int time_backt= rack, const char *name, int unit); +void packet_id_init(struct packet_id *p, int seq_backtrack, int time_backt= rack, const char *name, + int unit); void packet_id_free(struct packet_id *p); @@ -209,16 +210,13 @@ * Move the packet id recv structure from \c src to \c dest. \c src will * be reinitialised. \c dest will be freed before the move. */ -void -packet_id_move_recv(struct packet_id_rec *dest, struct packet_id_rec *src); +void packet_id_move_recv(struct packet_id_rec *dest, struct packet_id_rec = *src); /* should we accept an incoming packet id ? */ -bool packet_id_test(struct packet_id_rec *p, - const struct packet_id_net *pin); +bool packet_id_test(struct packet_id_rec *p, const struct packet_id_net *p= in); /* change our current state to reflect an accepted packet id */ -void packet_id_add(struct packet_id_rec *p, - const struct packet_id_net *pin); +void packet_id_add(struct packet_id_rec *p, const struct packet_id_net *pi= n); /* expire TIME_BACKTRACK sequence numbers */ void packet_id_reap(struct packet_id_rec *p); @@ -262,8 +260,7 @@ * * @return true if successful, false otherwise. */ -bool packet_id_write(struct packet_id_send *p, struct buffer *buf, - bool long_form, bool prepend); +bool packet_id_write(struct packet_id_send *p, struct buffer *buf, bool lo= ng_form, bool prepend); /* * Inline functions. @@ -309,7 +306,8 @@ p->id =3D 0; } -const char *packet_id_net_print(const struct packet_id_net *pin, bool prin= t_timestamp, struct gc_arena *gc); +const char *packet_id_net_print(const struct packet_id_net *pin, bool prin= t_timestamp, + struct gc_arena *gc); static inline int packet_id_size(bool long_form) @@ -340,8 +338,7 @@ * @param buf buffer to write the packet id/epoch to * @return false if the packet id space is exhausted and cannot b= e written */ -bool -packet_id_write_epoch(struct packet_id_send *p, uint16_t epoch, struct buf= fer *buf); +bool packet_id_write_epoch(struct packet_id_send *p, uint16_t epoch, struc= t buffer *buf); /** * Reads the packet ID containing both the epoch and the per-epoch counter @@ -350,7 +347,6 @@ * @param buf buffer to read the packet id from. * @return 0 for an error/invalid id, epoch otherwise */ -uint16_t -packet_id_read_epoch(struct packet_id_net *p, struct buffer *buf); +uint16_t packet_id_read_epoch(struct packet_id_net *p, struct buffer *buf); #endif /* PACKET_ID_H */ diff --git a/src/openvpn/perf.c b/src/openvpn/perf.c index 580e0fe..51c1a97 100644 --- a/src/openvpn/perf.c +++ b/src/openvpn/perf.c @@ -35,34 +35,32 @@ #include "memdbg.h" -static const char *metric_names[] =3D { - "PERF_BIO_READ_PLAINTEXT", - "PERF_BIO_WRITE_PLAINTEXT", - "PERF_BIO_READ_CIPHERTEXT", - "PERF_BIO_WRITE_CIPHERTEXT", - "PERF_TLS_MULTI_PROCESS", - "PERF_IO_WAIT", - "PERF_EVENT_LOOP", - "PERF_MULTI_CREATE_INSTANCE", - "PERF_MULTI_CLOSE_INSTANCE", - "PERF_MULTI_SHOW_STATS", - "PERF_MULTI_BCAST", - "PERF_MULTI_MCAST", - "PERF_SCRIPT", - "PERF_READ_IN_LINK", - "PERF_PROC_IN_LINK", - "PERF_READ_IN_TUN", - "PERF_PROC_IN_TUN", - "PERF_PROC_OUT_LINK", - "PERF_PROC_OUT_TUN", - "PERF_PROC_OUT_TUN_MTCP" -}; +static const char *metric_names[] =3D { "PERF_BIO_READ_PLAINTEXT", + "PERF_BIO_WRITE_PLAINTEXT", + "PERF_BIO_READ_CIPHERTEXT", + "PERF_BIO_WRITE_CIPHERTEXT", + "PERF_TLS_MULTI_PROCESS", + "PERF_IO_WAIT", + "PERF_EVENT_LOOP", + "PERF_MULTI_CREATE_INSTANCE", + "PERF_MULTI_CLOSE_INSTANCE", + "PERF_MULTI_SHOW_STATS", + "PERF_MULTI_BCAST", + "PERF_MULTI_MCAST", + "PERF_SCRIPT", + "PERF_READ_IN_LINK", + "PERF_PROC_IN_LINK", + "PERF_READ_IN_TUN", + "PERF_PROC_IN_TUN", + "PERF_PROC_OUT_LINK", + "PERF_PROC_OUT_TUN", + "PERF_PROC_OUT_TUN_MTCP" }; struct perf { -#define PS_INITIAL 0 -#define PS_METER_RUNNING 1 -#define PS_METER_INTERRUPTED 2 +#define PS_INITIAL 0 +#define PS_METER_RUNNING 1 +#define PS_METER_INTERRUPTED 2 int state; struct timeval start; @@ -138,8 +136,7 @@ { const int sindex =3D get_stack_index(0); const int newlen =3D get_stack_index(1); - if (sindex >=3D 0 && newlen >=3D 0 - && pindex >=3D 0 && pindex < PERF_N) + if (sindex >=3D 0 && newlen >=3D 0 && pindex >=3D 0 && pindex < PERF_N) { int i; for (i =3D 0; i < sindex; ++i) @@ -147,8 +144,7 @@ if (perf_set.stack[i] =3D=3D pindex) { perf_print_state(M_INFO); - msg(M_FATAL, "PERF: push_perf_index %s failed", - metric_names [pindex]); + msg(M_FATAL, "PERF: push_perf_index %s failed", metric_nam= es[pindex]); } } @@ -180,9 +176,7 @@ { if (p->state !=3D wanted) { - msg(M_FATAL, "PERF: bad state actual=3D%d wanted=3D%d", - p->state, - wanted); + msg(M_FATAL, "PERF: bad state actual=3D%d wanted=3D%d", p->state, = wanted); } } @@ -191,7 +185,7 @@ { struct timeval current; ASSERT(!gettimeofday(¤t, NULL)); - p->sofar +=3D (double) tv_subtract(¤t, &p->start, 600) / 1000000= .0; + p->sofar +=3D (double)tv_subtract(¤t, &p->start, 600) / 1000000.= 0; tv_clear(&p->start); } @@ -287,7 +281,8 @@ if (p->count > 0.0) { const double mean =3D p->sum / p->count; - msg(M_INFO, "%s n=3D%.0f mean=3D%.3f max=3D%.3f", metric_names= [i], p->count, mean*1000.0, p->max*1000.0); + msg(M_INFO, "%s n=3D%.0f mean=3D%.3f max=3D%.3f", metric_names= [i], p->count, mean * 1000.0, + p->max * 1000.0); } } } @@ -303,15 +298,8 @@ { const int j =3D perf_set.stack[i]; const struct perf *p =3D &perf_set.perf[j]; - msg(lev, "[%d] %s state=3D%d start=3D%s sofar=3D%f sum=3D%f max=3D= %f count=3D%f", - i, - metric_names[j], - p->state, - tv_string(&p->start, &gc), - p->sofar, - p->sum, - p->max, - p->count); + msg(lev, "[%d] %s state=3D%d start=3D%s sofar=3D%f sum=3D%f max=3D= %f count=3D%f", i, metric_names[j], + p->state, tv_string(&p->start, &gc), p->sofar, p->sum, p->max,= p->count); } gc_free(&gc); } diff --git a/src/openvpn/perf.h b/src/openvpn/perf.h index 7b35b5e..2a178a1 100644 --- a/src/openvpn/perf.h +++ b/src/openvpn/perf.h @@ -34,27 +34,27 @@ /* * Metrics */ -#define PERF_BIO_READ_PLAINTEXT 0 -#define PERF_BIO_WRITE_PLAINTEXT 1 -#define PERF_BIO_READ_CIPHERTEXT 2 -#define PERF_BIO_WRITE_CIPHERTEXT 3 -#define PERF_TLS_MULTI_PROCESS 4 -#define PERF_IO_WAIT 5 -#define PERF_EVENT_LOOP 6 -#define PERF_MULTI_CREATE_INSTANCE 7 -#define PERF_MULTI_CLOSE_INSTANCE 8 -#define PERF_MULTI_SHOW_STATS 9 -#define PERF_MULTI_BCAST 10 -#define PERF_MULTI_MCAST 11 -#define PERF_SCRIPT 12 -#define PERF_READ_IN_LINK 13 -#define PERF_PROC_IN_LINK 14 -#define PERF_READ_IN_TUN 15 -#define PERF_PROC_IN_TUN 16 -#define PERF_PROC_OUT_LINK 17 -#define PERF_PROC_OUT_TUN 18 -#define PERF_PROC_OUT_TUN_MTCP 19 -#define PERF_N 20 +#define PERF_BIO_READ_PLAINTEXT 0 +#define PERF_BIO_WRITE_PLAINTEXT 1 +#define PERF_BIO_READ_CIPHERTEXT 2 +#define PERF_BIO_WRITE_CIPHERTEXT 3 +#define PERF_TLS_MULTI_PROCESS 4 +#define PERF_IO_WAIT 5 +#define PERF_EVENT_LOOP 6 +#define PERF_MULTI_CREATE_INSTANCE 7 +#define PERF_MULTI_CLOSE_INSTANCE 8 +#define PERF_MULTI_SHOW_STATS 9 +#define PERF_MULTI_BCAST 10 +#define PERF_MULTI_MCAST 11 +#define PERF_SCRIPT 12 +#define PERF_READ_IN_LINK 13 +#define PERF_PROC_IN_LINK 14 +#define PERF_READ_IN_TUN 15 +#define PERF_PROC_IN_TUN 16 +#define PERF_PROC_OUT_LINK 17 +#define PERF_PROC_OUT_TUN 18 +#define PERF_PROC_OUT_TUN_MTCP 19 +#define PERF_N 20 #ifdef ENABLE_PERFORMANCE_METRICS @@ -63,7 +63,7 @@ /* * Stack size */ -#define STACK_N 64 +#define STACK_N 64 void perf_push(int type); diff --git a/src/openvpn/ping.c b/src/openvpn/ping.c index 50f255a..b9c0b96 100644 --- a/src/openvpn/ping.c +++ b/src/openvpn/ping.c @@ -38,10 +38,8 @@ * * PING_STRING_SIZE must be sizeof (ping_string) */ -const uint8_t ping_string[] =3D { - 0x2a, 0x18, 0x7b, 0xf3, 0x64, 0x1e, 0xb4, 0xcb, - 0x07, 0xed, 0x2d, 0x0a, 0x98, 0x1f, 0xc7, 0x48 -}; +const uint8_t ping_string[] =3D { 0x2a, 0x18, 0x7b, 0xf3, 0x64, 0x1e, 0xb4= , 0xcb, + 0x07, 0xed, 0x2d, 0x0a, 0x98, 0x1f, 0xc7, = 0x48 }; void trigger_ping_timeout_signal(struct context *c) @@ -50,8 +48,7 @@ switch (c->options.ping_rec_timeout_action) { case PING_EXIT: - msg(M_INFO, "%sInactivity timeout (--ping-exit), exiting", - format_common_name(c, &gc)); + msg(M_INFO, "%sInactivity timeout (--ping-exit), exiting", for= mat_common_name(c, &gc)); register_signal(c->sig, SIGTERM, "ping-exit"); break; diff --git a/src/openvpn/ping.h b/src/openvpn/ping.h index 29ee2f2..48d4c0a 100644 --- a/src/openvpn/ping.h +++ b/src/openvpn/ping.h @@ -29,7 +29,7 @@ /* * Initial default --ping-restart before --pull */ -#define PRE_PULL_INITIAL_PING_RESTART 120 /* in seconds */ +#define PRE_PULL_INITIAL_PING_RESTART 120 /* in seconds */ extern const uint8_t ping_string[]; @@ -59,11 +59,11 @@ check_ping_restart(struct context *c) { if (c->options.ping_rec_timeout - && event_timeout_trigger(&c->c2.ping_rec_interval, - &c->c2.timeval, + && event_timeout_trigger(&c->c2.ping_rec_interval, &c->c2.timeval, (!c->options.ping_timer_remote || link_socket_actual_defined(&c->c1.lin= k_socket_addrs[0].actual)) - ? ETT_DEFAULT : 15)) + ? ETT_DEFAULT + : 15)) { trigger_ping_timeout_signal(c); } @@ -76,8 +76,7 @@ check_ping_send(struct context *c) { if (c->options.ping_send_timeout - && event_timeout_trigger(&c->c2.ping_send_interval, - &c->c2.timeval, + && event_timeout_trigger(&c->c2.ping_send_interval, &c->c2.timeval, !TO_LINK_DEF(c) ? ETT_DEFAULT : 1)) { check_ping_send_dowork(c); diff --git a/src/openvpn/pkcs11.c b/src/openvpn/pkcs11.c index 0177b18..dfc87f6 100644 --- a/src/openvpn/pkcs11.c +++ b/src/openvpn/pkcs11.c @@ -39,51 +39,41 @@ #include "console.h" #include "pkcs11_backend.h" -static -time_t +static time_t __mytime(void) { return openvpn_time(NULL); } #if !defined(_WIN32) -static -int +static int __mygettimeofday(struct timeval *tv) { return gettimeofday(tv, NULL); } #endif -static -void +static void __mysleep(const unsigned long usec) { #if defined(_WIN32) - Sleep(usec/1000); + Sleep(usec / 1000); #else usleep(usec); #endif } -static pkcs11h_engine_system_t s_pkcs11h_sys_engine =3D { - malloc, - free, - __mytime, - __mysleep, +static pkcs11h_engine_system_t s_pkcs11h_sys_engine =3D { malloc, free, __= mytime, __mysleep, #if defined(_WIN32) - NULL + NULL #else - __mygettimeofday + __mygettimeofday #endif }; -static -unsigned -_pkcs11_msg_pkcs112openvpn( - const unsigned flags - ) +static unsigned +_pkcs11_msg_pkcs112openvpn(const unsigned flags) { unsigned openvpn_flags; @@ -121,11 +111,8 @@ return openvpn_flags; } -static -unsigned -_pkcs11_msg_openvpn2pkcs11( - const unsigned flags - ) +static unsigned +_pkcs11_msg_openvpn2pkcs11(const unsigned flags) { unsigned pkcs11_flags; @@ -161,33 +148,23 @@ return pkcs11_flags; } -static -void -_pkcs11_openvpn_log( - void *const global_data, - unsigned flags, - const char *const szFormat, - va_list args - ) +static void +_pkcs11_openvpn_log(void *const global_data, unsigned flags, const char *c= onst szFormat, + va_list args) { - char Buffer[10*1024]; + char Buffer[10 * 1024]; (void)global_data; vsnprintf(Buffer, sizeof(Buffer), szFormat, args); - Buffer[sizeof(Buffer)-1] =3D 0; + Buffer[sizeof(Buffer) - 1] =3D 0; msg(_pkcs11_msg_pkcs112openvpn(flags), "%s", Buffer); } -static -PKCS11H_BOOL -_pkcs11_openvpn_token_prompt( - void *const global_data, - void *const user_data, - const pkcs11h_token_id_t token, - const unsigned retry - ) +static PKCS11H_BOOL +_pkcs11_openvpn_token_prompt(void *const global_data, void *const user_dat= a, + const pkcs11h_token_id_t token, const unsigne= d retry) { struct user_pass token_resp; @@ -195,26 +172,16 @@ (void)user_data; (void)retry; - ASSERT(token!=3DNULL); + ASSERT(token !=3D NULL); CLEAR(token_resp); token_resp.defined =3D false; token_resp.nocache =3D true; - snprintf( - token_resp.username, - sizeof(token_resp.username), - "Please insert %s token", - token->label - ); + snprintf(token_resp.username, sizeof(token_resp.username), "Please ins= ert %s token", + token->label); - if ( - !get_user_pass( - &token_resp, - NULL, - "token-insertion-request", - GET_USER_PASS_MANAGEMENT|GET_USER_PASS_NEED_OK|GET_USER_PASS_N= OFATAL - ) - ) + if (!get_user_pass(&token_resp, NULL, "token-insertion-request", + GET_USER_PASS_MANAGEMENT | GET_USER_PASS_NEED_OK | = GET_USER_PASS_NOFATAL)) { return false; } @@ -224,16 +191,10 @@ } } -static -PKCS11H_BOOL -_pkcs11_openvpn_pin_prompt( - void *const global_data, - void *const user_data, - const pkcs11h_token_id_t token, - const unsigned retry, - char *const pin, - const size_t pin_max - ) +static PKCS11H_BOOL +_pkcs11_openvpn_pin_prompt(void *const global_data, void *const user_data, + const pkcs11h_token_id_t token, const unsigned = retry, char *const pin, + const size_t pin_max) { struct user_pass token_pass; char prompt[1024]; @@ -243,21 +204,16 @@ (void)user_data; (void)retry; - ASSERT(token!=3DNULL); + ASSERT(token !=3D NULL); snprintf(prompt, sizeof(prompt), "%s token", token->label); token_pass.defined =3D false; token_pass.nocache =3D true; - if ( - !get_user_pass( - &token_pass, - NULL, - prompt, - GET_USER_PASS_MANAGEMENT|GET_USER_PASS_PASSWORD_ONLY|GET_USER_= PASS_NOFATAL - ) - ) + if (!get_user_pass(&token_pass, NULL, prompt, + GET_USER_PASS_MANAGEMENT | GET_USER_PASS_PASSWORD_O= NLY + | GET_USER_PASS_NOFATAL)) { return false; } @@ -278,21 +234,16 @@ } bool -pkcs11_initialize( - const bool protected_auth, - const int nPINCachePeriod - ) +pkcs11_initialize(const bool protected_auth, const int nPINCachePeriod) { CK_RV rv =3D CKR_FUNCTION_FAILED; - dmsg( - D_PKCS11_DEBUG, - "PKCS#11: pkcs11_initialize - entered" - ); + dmsg(D_PKCS11_DEBUG, "PKCS#11: pkcs11_initialize - entered"); if ((rv =3D pkcs11h_engine_setSystem(&s_pkcs11h_sys_engine)) !=3D CKR_= OK) { - msg(M_FATAL, "PKCS#11: Cannot initialize system engine %ld-'%s'", = rv, pkcs11h_getMessage(rv)); + msg(M_FATAL, "PKCS#11: Cannot initialize system engine %ld-'%s'", = rv, + pkcs11h_getMessage(rv)); goto cleanup; } @@ -330,7 +281,8 @@ if ((rv =3D pkcs11h_setProtectedAuthentication(protected_auth)) !=3D C= KR_OK) { - msg(M_FATAL, "PKCS#11: Cannot set protected authentication mode %l= d-'%s'", rv, pkcs11h_getMessage(rv)); + msg(M_FATAL, "PKCS#11: Cannot set protected authentication mode %l= d-'%s'", rv, + pkcs11h_getMessage(rv)); goto cleanup; } @@ -343,12 +295,8 @@ rv =3D CKR_OK; cleanup: - dmsg( - D_PKCS11_DEBUG, - "PKCS#11: pkcs11_initialize - return %ld-'%s'", - rv, - pkcs11h_getMessage(rv) - ); + dmsg(D_PKCS11_DEBUG, "PKCS#11: pkcs11_initialize - return %ld-'%s'", r= v, + pkcs11h_getMessage(rv)); return rv =3D=3D CKR_OK; } @@ -356,105 +304,85 @@ void pkcs11_terminate(void) { - dmsg( - D_PKCS11_DEBUG, - "PKCS#11: pkcs11_terminate - entered" - ); + dmsg(D_PKCS11_DEBUG, "PKCS#11: pkcs11_terminate - entered"); pkcs11h_terminate(); - dmsg( - D_PKCS11_DEBUG, - "PKCS#11: pkcs11_terminate - return" - ); + dmsg(D_PKCS11_DEBUG, "PKCS#11: pkcs11_terminate - return"); } bool -pkcs11_addProvider( - const char *const provider, - const bool protected_auth, - const unsigned private_mode, - const bool cert_private - ) +pkcs11_addProvider(const char *const provider, const bool protected_auth, + const unsigned private_mode, const bool cert_private) { CK_RV rv =3D CKR_OK; - ASSERT(provider!=3DNULL); + ASSERT(provider !=3D NULL); - dmsg( - D_PKCS11_DEBUG, - "PKCS#11: pkcs11_addProvider - entered - provider=3D'%s', private_= mode=3D%08x", - provider, - private_mode - ); + dmsg(D_PKCS11_DEBUG, "PKCS#11: pkcs11_addProvider - entered - provider= =3D'%s', private_mode=3D%08x", + provider, private_mode); - msg( - M_INFO, - "PKCS#11: Adding PKCS#11 provider '%s'", - provider - ); + msg(M_INFO, "PKCS#11: Adding PKCS#11 provider '%s'", provider); -#if PKCS11H_VERSION >=3D ((1<<16) | (28<<8) | (0<<0)) +#if PKCS11H_VERSION >=3D ((1 << 16) | (28 << 8) | (0 << 0)) if ((rv =3D pkcs11h_registerProvider(provider)) !=3D CKR_OK) { - msg(M_WARN, "PKCS#11: Cannot register provider '%s' %ld-'%s'", pro= vider, rv, pkcs11h_getMessage(rv)); + msg(M_WARN, "PKCS#11: Cannot register provider '%s' %ld-'%s'", pro= vider, rv, + pkcs11h_getMessage(rv)); } else { PKCS11H_BOOL allow_protected_auth =3D protected_auth; PKCS11H_BOOL cert_is_private =3D cert_private; - rv =3D pkcs11h_setProviderProperty(provider, PKCS11H_PROVIDER_PROP= ERTY_LOCATION, provider, strlen(provider) + 1); + rv =3D pkcs11h_setProviderProperty(provider, PKCS11H_PROVIDER_PROP= ERTY_LOCATION, provider, + strlen(provider) + 1); if (rv =3D=3D CKR_OK) { - rv =3D pkcs11h_setProviderProperty(provider, PKCS11H_PROVIDER_= PROPERTY_ALLOW_PROTECTED_AUTH, &allow_protected_auth, sizeof(allow_protecte= d_auth)); + rv =3D pkcs11h_setProviderProperty(provider, + PKCS11H_PROVIDER_PROPERTY_ALL= OW_PROTECTED_AUTH, + &allow_protected_auth, sizeof= (allow_protected_auth)); } if (rv =3D=3D CKR_OK) { - rv =3D pkcs11h_setProviderProperty(provider, PKCS11H_PROVIDER_= PROPERTY_MASK_PRIVATE_MODE, &private_mode, sizeof(private_mode)); + rv =3D pkcs11h_setProviderProperty(provider, PKCS11H_PROVIDER_= PROPERTY_MASK_PRIVATE_MODE, + &private_mode, sizeof(private= _mode)); } if (rv =3D=3D CKR_OK) { - rv =3D pkcs11h_setProviderProperty(provider, PKCS11H_PROVIDER_= PROPERTY_CERT_IS_PRIVATE, &cert_is_private, sizeof(cert_is_private)); + rv =3D pkcs11h_setProviderProperty(provider, PKCS11H_PROVIDER_= PROPERTY_CERT_IS_PRIVATE, + &cert_is_private, sizeof(cert= _is_private)); } #if defined(WIN32) && defined(PKCS11H_PROVIDER_PROPERTY_LOADER_FLAGS) if (rv =3D=3D CKR_OK && platform_absolute_pathname(provider)) { - unsigned loader_flags =3D LOAD_LIBRARY_SEARCH_DEFAULT_DIRS | L= OAD_LIBRARY_SEARCH_DLL_LOAD_DIR; - rv =3D pkcs11h_setProviderProperty(provider, PKCS11H_PROVIDER_= PROPERTY_LOADER_FLAGS, &loader_flags, sizeof(loader_flags)); + unsigned loader_flags =3D + LOAD_LIBRARY_SEARCH_DEFAULT_DIRS | LOAD_LIBRARY_SEARCH_DLL= _LOAD_DIR; + rv =3D pkcs11h_setProviderProperty(provider, PKCS11H_PROVIDER_= PROPERTY_LOADER_FLAGS, + &loader_flags, sizeof(loader_= flags)); } #endif if (rv !=3D CKR_OK || (rv =3D pkcs11h_initializeProvider(provider)= ) !=3D CKR_OK) { - msg(M_WARN, "PKCS#11: Cannot initialize provider '%s' %ld-'%s'= ", provider, rv, pkcs11h_getMessage(rv)); + msg(M_WARN, "PKCS#11: Cannot initialize provider '%s' %ld-'%s'= ", provider, rv, + pkcs11h_getMessage(rv)); pkcs11h_removeProvider(provider); } } #else /* if PKCS11H_VERSION >=3D ((1<<16) | (28<<8) | (0<<0)) */ - if ( - (rv =3D pkcs11h_addProvider( - provider, - provider, - protected_auth, - private_mode, - PKCS11H_SLOTEVENT_METHOD_AUTO, - 0, - cert_private - )) !=3D CKR_OK - ) + if ((rv =3D pkcs11h_addProvider(provider, provider, protected_auth, pr= ivate_mode, + PKCS11H_SLOTEVENT_METHOD_AUTO, 0, cert_p= rivate)) + !=3D CKR_OK) { - msg(M_WARN, "PKCS#11: Cannot initialize provider '%s' %ld-'%s'", p= rovider, rv, pkcs11h_getMessage(rv)); + msg(M_WARN, "PKCS#11: Cannot initialize provider '%s' %ld-'%s'", p= rovider, rv, + pkcs11h_getMessage(rv)); } #endif /* if PKCS11H_VERSION >=3D ((1<<16) | (28<<8) | (0<<0)) */ - dmsg( - D_PKCS11_DEBUG, - "PKCS#11: pkcs11_addProvider - return rv=3D%ld-'%s'", - rv, - pkcs11h_getMessage(rv) - ); + dmsg(D_PKCS11_DEBUG, "PKCS#11: pkcs11_addProvider - return rv=3D%ld-'%= s'", rv, + pkcs11h_getMessage(rv)); return rv =3D=3D CKR_OK; } @@ -473,20 +401,11 @@ CK_RV rv =3D CKR_OK; int count =3D 0; - dmsg( - D_PKCS11_DEBUG, - "PKCS#11: pkcs11_management_id_count - entered" - ); + dmsg(D_PKCS11_DEBUG, "PKCS#11: pkcs11_management_id_count - entered"); - if ( - (rv =3D pkcs11h_certificate_enumCertificateIds( - PKCS11H_ENUM_METHOD_CACHE_EXIST, - NULL, - PKCS11H_PROMPT_MASK_ALLOW_ALL, - NULL, - &id_list - )) !=3D CKR_OK - ) + if ((rv =3D pkcs11h_certificate_enumCertificateIds(PKCS11H_ENUM_METHOD= _CACHE_EXIST, NULL, + PKCS11H_PROMPT_MASK_A= LLOW_ALL, NULL, &id_list)) + !=3D CKR_OK) { msg(M_WARN, "PKCS#11: Cannot get certificate list %ld-'%s'", rv, p= kcs11h_getMessage(rv)); goto cleanup; @@ -502,21 +421,13 @@ pkcs11h_certificate_freeCertificateIdList(id_list); id_list =3D NULL; - dmsg( - D_PKCS11_DEBUG, - "PKCS#11: pkcs11_management_id_count - return count=3D%d", - count - ); + dmsg(D_PKCS11_DEBUG, "PKCS#11: pkcs11_management_id_count - return cou= nt=3D%d", count); return count; } bool -pkcs11_management_id_get( - const int index, - char **id, - char **base64 - ) +pkcs11_management_id_get(const int index, char **id, char **base64) { pkcs11h_certificate_id_list_t id_list =3D NULL; pkcs11h_certificate_id_list_t entry =3D NULL; @@ -533,27 +444,17 @@ int count =3D 0; bool success =3D false; - ASSERT(id!=3DNULL); - ASSERT(base64!=3DNULL); + ASSERT(id !=3D NULL); + ASSERT(base64 !=3D NULL); - dmsg( - D_PKCS11_DEBUG, - "PKCS#11: pkcs11_management_id_get - entered index=3D%d", - index - ); + dmsg(D_PKCS11_DEBUG, "PKCS#11: pkcs11_management_id_get - entered inde= x=3D%d", index); *id =3D NULL; *base64 =3D NULL; - if ( - (rv =3D pkcs11h_certificate_enumCertificateIds( - PKCS11H_ENUM_METHOD_CACHE_EXIST, - NULL, - PKCS11H_PROMPT_MASK_ALLOW_ALL, - NULL, - &id_list - )) !=3D CKR_OK - ) + if ((rv =3D pkcs11h_certificate_enumCertificateIds(PKCS11H_ENUM_METHOD= _CACHE_EXIST, NULL, + PKCS11H_PROMPT_MASK_A= LLOW_ALL, NULL, &id_list)) + !=3D CKR_OK) { msg(M_WARN, "PKCS#11: Cannot get certificate list %ld-'%s'", rv, p= kcs11h_getMessage(rv)); goto cleanup; @@ -569,23 +470,16 @@ if (entry =3D=3D NULL) { - dmsg( - D_PKCS11_DEBUG, - "PKCS#11: pkcs11_management_id_get - no certificate at index= =3D%d", - index - ); + dmsg(D_PKCS11_DEBUG, "PKCS#11: pkcs11_management_id_get - no certi= ficate at index=3D%d", + index); goto cleanup; } - if ( - (rv =3D pkcs11h_certificate_serializeCertificateId( - NULL, - &max, - entry->certificate_id - )) !=3D CKR_OK - ) + if ((rv =3D pkcs11h_certificate_serializeCertificateId(NULL, &max, ent= ry->certificate_id)) + !=3D CKR_OK) { - msg(M_WARN, "PKCS#11: Cannot serialize certificate id %ld-'%s'", r= v, pkcs11h_getMessage(rv)); + msg(M_WARN, "PKCS#11: Cannot serialize certificate id %ld-'%s'", r= v, + pkcs11h_getMessage(rv)); goto cleanup; } @@ -595,39 +489,24 @@ goto cleanup; } - if ( - (rv =3D pkcs11h_certificate_serializeCertificateId( - internal_id, - &max, - entry->certificate_id - )) !=3D CKR_OK - ) + if ((rv =3D pkcs11h_certificate_serializeCertificateId(internal_id, &m= ax, entry->certificate_id)) + !=3D CKR_OK) { - msg(M_WARN, "PKCS#11: Cannot serialize certificate id %ld-'%s'", r= v, pkcs11h_getMessage(rv)); + msg(M_WARN, "PKCS#11: Cannot serialize certificate id %ld-'%s'", r= v, + pkcs11h_getMessage(rv)); goto cleanup; } - if ( - (rv =3D pkcs11h_certificate_create( - entry->certificate_id, - NULL, - PKCS11H_PROMPT_MASK_ALLOW_ALL, - PKCS11H_PIN_CACHE_INFINITE, - &certificate - )) !=3D CKR_OK - ) + if ((rv =3D pkcs11h_certificate_create(entry->certificate_id, NULL, PK= CS11H_PROMPT_MASK_ALLOW_ALL, + PKCS11H_PIN_CACHE_INFINITE, &cert= ificate)) + !=3D CKR_OK) { msg(M_WARN, "PKCS#11: Cannot get certificate %ld-'%s'", rv, pkcs11= h_getMessage(rv)); goto cleanup; } - if ( - (rv =3D pkcs11h_certificate_getCertificateBlob( - certificate, - NULL, - &certificate_blob_size - )) !=3D CKR_OK - ) + if ((rv =3D pkcs11h_certificate_getCertificateBlob(certificate, NULL, = &certificate_blob_size)) + !=3D CKR_OK) { msg(M_WARN, "PKCS#11: Cannot get certificate blob %ld-'%s'", rv, p= kcs11h_getMessage(rv)); goto cleanup; @@ -639,13 +518,9 @@ goto cleanup; } - if ( - (rv =3D pkcs11h_certificate_getCertificateBlob( - certificate, - certificate_blob, - &certificate_blob_size - )) !=3D CKR_OK - ) + if ((rv =3D pkcs11h_certificate_getCertificateBlob(certificate, certif= icate_blob, + &certificate_blob_siz= e)) + !=3D CKR_OK) { msg(M_WARN, "PKCS#11: Cannot get certificate blob %ld-'%s'", rv, p= kcs11h_getMessage(rv)); goto cleanup; @@ -677,22 +552,15 @@ free(certificate_blob); certificate_blob =3D NULL; =20 - dmsg( - D_PKCS11_DEBUG, - "PKCS#11: pkcs11_management_id_get - return success=3D%d, id=3D'%s= '", - success ? 1 : 0, - *id - ); + dmsg(D_PKCS11_DEBUG, "PKCS#11: pkcs11_management_id_get - return succe= ss=3D%d, id=3D'%s'", + success ? 1 : 0, *id); return success; } int -tls_ctx_use_pkcs11( - struct tls_root_ctx *const ssl_ctx, - bool pkcs11_id_management, - const char *const pkcs11_id - ) +tls_ctx_use_pkcs11(struct tls_root_ctx *const ssl_ctx, bool pkcs11_id_mana= gement, + const char *const pkcs11_id) { pkcs11h_certificate_id_t certificate_id =3D NULL; pkcs11h_certificate_t certificate =3D NULL; @@ -700,16 +568,13 @@ bool ok =3D false; - ASSERT(ssl_ctx!=3DNULL); - ASSERT(pkcs11_id_management || pkcs11_id!=3DNULL); + ASSERT(ssl_ctx !=3D NULL); + ASSERT(pkcs11_id_management || pkcs11_id !=3D NULL); dmsg( D_PKCS11_DEBUG, "PKCS#11: tls_ctx_use_pkcs11 - entered - ssl_ctx=3D%p, pkcs11_id_m= anagement=3D%d, pkcs11_id=3D'%s'", - (void *)ssl_ctx, - pkcs11_id_management ? 1 : 0, - pkcs11_id - ); + (void *)ssl_ctx, pkcs11_id_management ? 1 : 0, pkcs11_id); if (pkcs11_id_management) { @@ -719,30 +584,17 @@ id_resp.defined =3D false; id_resp.nocache =3D true; - snprintf( - id_resp.username, - sizeof(id_resp.username), - "Please specify PKCS#11 id to use" - ); + snprintf(id_resp.username, sizeof(id_resp.username), "Please speci= fy PKCS#11 id to use"); - if ( - !get_user_pass( - &id_resp, - NULL, - "pkcs11-id-request", - GET_USER_PASS_MANAGEMENT|GET_USER_PASS_NEED_STR|GET_USER_P= ASS_NOFATAL - ) - ) + if (!get_user_pass(&id_resp, NULL, "pkcs11-id-request", + GET_USER_PASS_MANAGEMENT | GET_USER_PASS_NEED_S= TR + | GET_USER_PASS_NOFATAL)) { goto cleanup; } - if ( - (rv =3D pkcs11h_certificate_deserializeCertificateId( - &certificate_id, - id_resp.password - )) !=3D CKR_OK - ) + if ((rv =3D pkcs11h_certificate_deserializeCertificateId(&certific= ate_id, id_resp.password)) + !=3D CKR_OK) { msg(M_WARN, "PKCS#11: Cannot deserialize id %ld-'%s'", rv, pkc= s11h_getMessage(rv)); goto cleanup; @@ -750,38 +602,23 @@ } else { - if ( - (rv =3D pkcs11h_certificate_deserializeCertificateId( - &certificate_id, - pkcs11_id - )) !=3D CKR_OK - ) + if ((rv =3D pkcs11h_certificate_deserializeCertificateId(&certific= ate_id, pkcs11_id)) + !=3D CKR_OK) { msg(M_WARN, "PKCS#11: Cannot deserialize id %ld-'%s'", rv, pkc= s11h_getMessage(rv)); goto cleanup; } } - if ( - (rv =3D pkcs11h_certificate_create( - certificate_id, - NULL, - PKCS11H_PROMPT_MASK_ALLOW_ALL, - PKCS11H_PIN_CACHE_INFINITE, - &certificate - )) !=3D CKR_OK - ) + if ((rv =3D pkcs11h_certificate_create(certificate_id, NULL, PKCS11H_P= ROMPT_MASK_ALLOW_ALL, + PKCS11H_PIN_CACHE_INFINITE, &cert= ificate)) + !=3D CKR_OK) { msg(M_WARN, "PKCS#11: Cannot get certificate %ld-'%s'", rv, pkcs11= h_getMessage(rv)); goto cleanup; } - if ( - (pkcs11_init_tls_session( - certificate, - ssl_ctx - )) - ) + if ((pkcs11_init_tls_session(certificate, ssl_ctx))) { /* Handled by SSL context free */ certificate =3D NULL; @@ -805,26 +642,15 @@ certificate_id =3D NULL; } - dmsg( - D_PKCS11_DEBUG, - "PKCS#11: tls_ctx_use_pkcs11 - return ok=3D%d, rv=3D%ld", - ok ? 1 : 0, - rv - ); + dmsg(D_PKCS11_DEBUG, "PKCS#11: tls_ctx_use_pkcs11 - return ok=3D%d, rv= =3D%ld", ok ? 1 : 0, rv); return ok ? 1 : 0; } -static -PKCS11H_BOOL -_pkcs11_openvpn_show_pkcs11_ids_pin_prompt( - void *const global_data, - void *const user_data, - const pkcs11h_token_id_t token, - const unsigned retry, - char *const pin, - const size_t pin_max - ) +static PKCS11H_BOOL +_pkcs11_openvpn_show_pkcs11_ids_pin_prompt(void *const global_data, void *= const user_data, + const pkcs11h_token_id_t token,= const unsigned retry, + char *const pin, const size_t p= in_max) { struct gc_arena gc =3D gc_new(); struct buffer pass_prompt =3D alloc_buf_gc(128, &gc); @@ -833,11 +659,10 @@ (void)user_data; (void)retry; - ASSERT(token!=3DNULL); + ASSERT(token !=3D NULL); buf_printf(&pass_prompt, "Please enter '%s' token PIN or 'cancel': ", = token->display); - if (!query_user_SINGLE(BSTR(&pass_prompt), BLEN(&pass_prompt), - pin, pin_max, false)) + if (!query_user_SINGLE(BSTR(&pass_prompt), BLEN(&pass_prompt), pin, pi= n_max, false)) { msg(M_FATAL, "Could not retrieve the PIN"); } @@ -855,10 +680,7 @@ } void -show_pkcs11_ids( - const char *const provider, - bool cert_private - ) +show_pkcs11_ids(const char *const provider, bool cert_private) { struct gc_arena gc =3D gc_new(); pkcs11h_certificate_id_list_t user_certificates =3D NULL; @@ -881,7 +703,8 @@ if ((rv =3D pkcs11h_setProtectedAuthentication(TRUE)) !=3D CKR_OK) { - msg(M_FATAL, "PKCS#11: Cannot set protected authentication %ld-'%s= '", rv, pkcs11h_getMessage(rv)); + msg(M_FATAL, "PKCS#11: Cannot set protected authentication %ld-'%s= '", rv, + pkcs11h_getMessage(rv)); goto cleanup; } @@ -897,118 +720,77 @@ goto cleanup; } - if ( - (rv =3D pkcs11h_certificate_enumCertificateIds( - PKCS11H_ENUM_METHOD_CACHE_EXIST, - NULL, - PKCS11H_PROMPT_MASK_ALLOW_ALL, - NULL, - &user_certificates - )) !=3D CKR_OK - ) + if ((rv =3D pkcs11h_certificate_enumCertificateIds(PKCS11H_ENUM_METHOD= _CACHE_EXIST, NULL, + PKCS11H_PROMPT_MASK_A= LLOW_ALL, NULL, + &user_certificates)) + !=3D CKR_OK) { msg(M_FATAL, "PKCS#11: Cannot enumerate certificates %ld-'%s'", rv= , pkcs11h_getMessage(rv)); goto cleanup; } - msg( - M_INFO|M_NOPREFIX|M_NOLF, - ( - "\n" - "The following objects are available for use.\n" - "Each object shown below may be used as parameter to\n" - "--pkcs11-id option please remember to use single quote mark.\= n" - ) - ); + msg(M_INFO | M_NOPREFIX | M_NOLF, + ("\n" + "The following objects are available for use.\n" + "Each object shown below may be used as parameter to\n" + "--pkcs11-id option please remember to use single quote mark.\n")= ); for (current =3D user_certificates; current !=3D NULL; current =3D cur= rent->next) { pkcs11h_certificate_t certificate =3D NULL; char *dn =3D NULL; - char serial[1024] =3D {0}; + char serial[1024] =3D { 0 }; char *ser =3D NULL; size_t ser_len =3D 0; - if ( - (rv =3D pkcs11h_certificate_serializeCertificateId( - NULL, - &ser_len, - current->certificate_id - )) !=3D CKR_OK - ) + if ((rv =3D pkcs11h_certificate_serializeCertificateId(NULL, &ser_= len, + current->cert= ificate_id)) + !=3D CKR_OK) { - msg(M_FATAL, "PKCS#11: Cannot serialize certificate %ld-'%s'",= rv, pkcs11h_getMessage(rv)); + msg(M_FATAL, "PKCS#11: Cannot serialize certificate %ld-'%s'",= rv, + pkcs11h_getMessage(rv)); goto cleanup1; } - if ( - rv =3D=3D CKR_OK - && (ser =3D (char *)malloc(ser_len)) =3D=3D NULL - ) + if (rv =3D=3D CKR_OK && (ser =3D (char *)malloc(ser_len)) =3D=3D N= ULL) { msg(M_FATAL, "PKCS#11: Cannot allocate memory"); goto cleanup1; } - if ( - (rv =3D pkcs11h_certificate_serializeCertificateId( - ser, - &ser_len, - current->certificate_id - )) !=3D CKR_OK - ) + if ((rv =3D + pkcs11h_certificate_serializeCertificateId(ser, &ser_len,= current->certificate_id)) + !=3D CKR_OK) { - msg(M_FATAL, "PKCS#11: Cannot serialize certificate %ld-'%s'",= rv, pkcs11h_getMessage(rv)); + msg(M_FATAL, "PKCS#11: Cannot serialize certificate %ld-'%s'",= rv, + pkcs11h_getMessage(rv)); goto cleanup1; } - if ( - (rv =3D pkcs11h_certificate_create( - current->certificate_id, - NULL, - PKCS11H_PROMPT_MASK_ALLOW_ALL, - PKCS11H_PIN_CACHE_INFINITE, - &certificate - )) - ) + if ((rv =3D pkcs11h_certificate_create(current->certificate_id, NU= LL, + PKCS11H_PROMPT_MASK_ALLOW_ALL, + PKCS11H_PIN_CACHE_INFINITE, &= certificate))) { msg(M_FATAL, "PKCS#11: Cannot create certificate %ld-'%s'", rv= , pkcs11h_getMessage(rv)); goto cleanup1; } - if ( - (dn =3D pkcs11_certificate_dn( - certificate, - &gc - )) =3D=3D NULL - ) + if ((dn =3D pkcs11_certificate_dn(certificate, &gc)) =3D=3D NULL) { goto cleanup1; } - if ( - (pkcs11_certificate_serial( - certificate, - serial, - sizeof(serial) - )) - ) + if ((pkcs11_certificate_serial(certificate, serial, sizeof(serial)= ))) { goto cleanup1; } - msg( - M_INFO|M_NOPREFIX|M_NOLF, - ( - "\n" - "Certificate\n" - " DN: %s\n" - " Serial: %s\n" - " Serialized id: %s\n" - ), - dn, - serial, - ser - ); + msg(M_INFO | M_NOPREFIX | M_NOLF, + ("\n" + "Certificate\n" + " DN: %s\n" + " Serial: %s\n" + " Serialized id: %s\n"), + dn, serial, ser); cleanup1: diff --git a/src/openvpn/pkcs11.h b/src/openvpn/pkcs11.h index 644d7ce..d431db1 100644 --- a/src/openvpn/pkcs11.h +++ b/src/openvpn/pkcs11.h @@ -27,49 +27,24 @@ #include "ssl_common.h" -bool -pkcs11_initialize( - const bool fProtectedAuthentication, - const int nPINCachePeriod - ); +bool pkcs11_initialize(const bool fProtectedAuthentication, const int nPIN= CachePeriod); -void -pkcs11_terminate(void); +void pkcs11_terminate(void); -bool -pkcs11_addProvider( - const char *const provider, - const bool fProtectedAuthentication, - const unsigned private_mode, - const bool fCertIsPrivate - ); +bool pkcs11_addProvider(const char *const provider, const bool fProtectedA= uthentication, + const unsigned private_mode, const bool fCertIsPri= vate); -int -pkcs11_logout(void); +int pkcs11_logout(void); -int -pkcs11_management_id_count(void); +int pkcs11_management_id_count(void); -bool -pkcs11_management_id_get( - const int index, - char **id, - char **base64 - ); +bool pkcs11_management_id_get(const int index, char **id, char **base64); -int -tls_ctx_use_pkcs11( - struct tls_root_ctx *const ssl_ctx, - bool pkcs11_id_management, - const char *const pkcs11_id - ); +int tls_ctx_use_pkcs11(struct tls_root_ctx *const ssl_ctx, bool pkcs11_id_= management, + const char *const pkcs11_id); -void -show_pkcs11_ids( - const char *const provider, - bool cert_private - ); +void show_pkcs11_ids(const char *const provider, bool cert_private); -#endif /* ENABLE_PKCS11 */ +#endif /* ENABLE_PKCS11 */ -#endif /* OPENVPN_PKCS11H_H */ +#endif /* OPENVPN_PKCS11H_H */ diff --git a/src/openvpn/pkcs11_backend.h b/src/openvpn/pkcs11_backend.h index f65ba3f..caa0735 100644 --- a/src/openvpn/pkcs11_backend.h +++ b/src/openvpn/pkcs11_backend.h @@ -56,8 +56,7 @@ * * @return 1 on failure, 0 on success */ -int pkcs11_certificate_serial(pkcs11h_certificate_t certificate, char *ser= ial, - size_t serial_len); +int pkcs11_certificate_serial(pkcs11h_certificate_t certificate, char *ser= ial, size_t serial_len); /** * Load PKCS #11 Certificate's information into the given TLS context @@ -67,8 +66,7 @@ * * @return 1 on failure, 0 on success */ -int pkcs11_init_tls_session(pkcs11h_certificate_t certificate, - struct tls_root_ctx *const ssl_ctx); +int pkcs11_init_tls_session(pkcs11h_certificate_t certificate, struct tls_= root_ctx *const ssl_ctx); #endif /* defined(ENABLE_PKCS11) */ #endif /* PKCS11_BACKEND_H_ */ diff --git a/src/openvpn/pkcs11_mbedtls.c b/src/openvpn/pkcs11_mbedtls.c index d1c8957..245aa8d 100644 --- a/src/openvpn/pkcs11_mbedtls.c +++ b/src/openvpn/pkcs11_mbedtls.c @@ -46,16 +46,14 @@ size_t cert_blob_size =3D 0; bool ret =3D false; - if (pkcs11h_certificate_getCertificateBlob(pkcs11_cert, NULL, - &cert_blob_size) !=3D CKR_O= K) + if (pkcs11h_certificate_getCertificateBlob(pkcs11_cert, NULL, &cert_bl= ob_size) !=3D CKR_OK) { msg(M_WARN, "PKCS#11: Cannot retrieve certificate object size"); goto cleanup; } check_malloc_return((cert_blob =3D calloc(1, cert_blob_size))); - if (pkcs11h_certificate_getCertificateBlob(pkcs11_cert, cert_blob, - &cert_blob_size) !=3D CKR_O= K) + if (pkcs11h_certificate_getCertificateBlob(pkcs11_cert, cert_blob, &ce= rt_blob_size) !=3D CKR_OK) { msg(M_WARN, "PKCS#11: Cannot retrieve certificate object"); goto cleanup; @@ -74,16 +72,14 @@ } static bool -pkcs11_sign(void *pkcs11_cert, const void *src, size_t src_len, - void *dst, size_t dst_len) +pkcs11_sign(void *pkcs11_cert, const void *src, size_t src_len, void *dst,= size_t dst_len) { - return CKR_OK =3D=3D pkcs11h_certificate_signAny(pkcs11_cert, CKM_RSA_= PKCS, - src, src_len, dst, &dst_l= en); + return CKR_OK + =3D=3D pkcs11h_certificate_signAny(pkcs11_cert, CKM_RSA_PKCS, s= rc, src_len, dst, &dst_len); } int -pkcs11_init_tls_session(pkcs11h_certificate_t certificate, - struct tls_root_ctx *const ssl_ctx) +pkcs11_init_tls_session(pkcs11h_certificate_t certificate, struct tls_root= _ctx *const ssl_ctx) { ASSERT(NULL !=3D ssl_ctx); @@ -130,8 +126,7 @@ } int -pkcs11_certificate_serial(pkcs11h_certificate_t cert, char *serial, - size_t serial_len) +pkcs11_certificate_serial(pkcs11h_certificate_t cert, char *serial, size_t= serial_len) { int ret =3D 1; mbedtls_x509_crt mbed_crt =3D { 0 }; diff --git a/src/openvpn/pkcs11_openssl.c b/src/openvpn/pkcs11_openssl.c index 489aa35..a912747 100644 --- a/src/openvpn/pkcs11_openssl.c +++ b/src/openvpn/pkcs11_openssl.c @@ -43,18 +43,21 @@ #ifdef HAVE_XKEY_PROVIDER static XKEY_EXTERNAL_SIGN_fn xkey_pkcs11h_sign; -#if PKCS11H_VERSION > ((1<<16) | (27<<8)) /* version > 1.27 */ +#if PKCS11H_VERSION > ((1 << 16) | (27 << 8)) /* version > 1.27 */ /* Table linking OpenSSL digest NID with CKM and CKG constants in PKCS#11 = */ -#define MD_TYPE(n) {NID_sha ## n, CKM_SHA ## n, CKG_MGF1_SHA ## n} +#define MD_TYPE(n) { NID_sha##n, CKM_SHA##n, CKG_MGF1_SHA##n } static const struct { int nid; unsigned long ckm_id; unsigned long mgf_id; -} mdtypes[] =3D {MD_TYPE(224), MD_TYPE(256), MD_TYPE(384), MD_TYPE(512), - {NID_sha1, CKM_SHA_1, CKG_MGF1_SHA1}, /* SHA_1 naming is an= oddity */ - {NID_undef, 0, 0}}; +} mdtypes[] =3D { MD_TYPE(224), + MD_TYPE(256), + MD_TYPE(384), + MD_TYPE(512), + { NID_sha1, CKM_SHA_1, CKG_MGF1_SHA1 }, /* SHA_1 naming is= an oddity */ + { NID_undef, 0, 0 } }; /* From sigalg, derive parameters for pss signature and fill in pss_param= s. * Its of type CK_RSA_PKCS_PSS_PARAMS struct with three fields to be fille= d in: @@ -62,15 +65,13 @@ * where hashAlg is CKM_SHA256 etc., mgf is CKG_MGF1_SHA256 etc. */ static int -set_pss_params(CK_RSA_PKCS_PSS_PARAMS *pss_params, XKEY_SIGALG sigalg, - pkcs11h_certificate_t cert) +set_pss_params(CK_RSA_PKCS_PSS_PARAMS *pss_params, XKEY_SIGALG sigalg, pkc= s11h_certificate_t cert) { int ret =3D 0; X509 *x509 =3D NULL; EVP_PKEY *pubkey =3D NULL; - if ((x509 =3D pkcs11h_openssl_getX509(cert)) =3D=3D NULL - || (pubkey =3D X509_get0_pubkey(x509)) =3D=3D NULL) + if ((x509 =3D pkcs11h_openssl_getX509(cert)) =3D=3D NULL || (pubkey = =3D X509_get0_pubkey(x509)) =3D=3D NULL) { msg(M_WARN, "PKCS#11: Unable get public key"); goto cleanup; @@ -90,8 +91,10 @@ const EVP_MD *md =3D EVP_get_digestbyname(sigalg.mdname); if (!md) { - msg(M_WARN, "WARN: set_pss_params: EVP_get_digestbyname returned N= ULL " - "for mdname =3D <%s>", sigalg.mdname); + msg(M_WARN, + "WARN: set_pss_params: EVP_get_digestbyname returned NULL " + "for mdname =3D <%s>", + sigalg.mdname); goto cleanup; } int mdsize =3D EVP_MD_get_size(md); @@ -108,14 +111,16 @@ =20 if (saltlen < 0 || pss_params->hashAlg =3D=3D 0) { - msg(M_WARN, "WARN: invalid RSA_PKCS1_PSS parameters: saltlen =3D <= %s> " - "mdname =3D <%s>.", sigalg.saltlen, sigalg.mdname); + msg(M_WARN, + "WARN: invalid RSA_PKCS1_PSS parameters: saltlen =3D <%s> " + "mdname =3D <%s>.", + sigalg.saltlen, sigalg.mdname); goto cleanup; } - pss_params->sLen =3D (unsigned long) saltlen; /* saltlen >=3D 0 at thi= s point */ + pss_params->sLen =3D (unsigned long)saltlen; /* saltlen >=3D 0 at this= point */ - msg(D_XKEY, "set_pss_params: sLen =3D %lu, hashAlg =3D %lu, mgf =3D %l= u", - pss_params->sLen, pss_params->hashAlg, pss_params->mgf); + msg(D_XKEY, "set_pss_params: sLen =3D %lu, hashAlg =3D %lu, mgf =3D %l= u", pss_params->sLen, + pss_params->hashAlg, pss_params->mgf); ret =3D 1; @@ -138,14 +143,14 @@ * is PSS in which case we return an error. */ static CK_RV -pkcs11h_certificate_signAny_ex(const pkcs11h_certificate_t cert, - const CK_MECHANISM *mech, const unsigned ch= ar *tbs, - size_t tbslen, unsigned char *sig, size_t *= siglen) +pkcs11h_certificate_signAny_ex(const pkcs11h_certificate_t cert, const CK_= MECHANISM *mech, + const unsigned char *tbs, size_t tbslen, un= signed char *sig, + size_t *siglen) { if (mech->mechanism =3D=3D CKM_RSA_PKCS_PSS) { msg(M_NONFATAL, "PKCS#11: Error: PSS padding is not supported by " - "this version of pkcs11-helper library."); + "this version of pkcs11-helper library."); return CKR_MECHANISM_INVALID; } return pkcs11h_certificate_signAny(cert, mech->mechanism, tbs, tbslen,= sig, siglen); @@ -158,12 +163,12 @@ * We support ECDSA, RSA_NO_PADDING, RSA_PKCS1_PADDING, RSA_PKCS_PSS_PADDI= NG */ static int -xkey_pkcs11h_sign(void *handle, unsigned char *sig, - size_t *siglen, const unsigned char *tbs, size_t tbslen,= XKEY_SIGALG sigalg) +xkey_pkcs11h_sign(void *handle, unsigned char *sig, size_t *siglen, const = unsigned char *tbs, + size_t tbslen, XKEY_SIGALG sigalg) { pkcs11h_certificate_t cert =3D handle; - CK_MECHANISM mech =3D {CKM_RSA_PKCS, NULL, 0}; /* default value */ - CK_RSA_PKCS_PSS_PARAMS pss_params =3D {0}; + CK_MECHANISM mech =3D { CKM_RSA_PKCS, NULL, 0 }; /* default value */ + CK_RSA_PKCS_PSS_PARAMS pss_params =3D { 0 }; unsigned char buf[EVP_MAX_MD_SIZE]; size_t buflen =3D 0; @@ -178,7 +183,7 @@ if (xkey_digest(tbs, tbslen, buf, &buflen, sigalg.mdname)) { tbs =3D buf; - tbslen =3D (size_t) buflen; + tbslen =3D (size_t)buflen; sigalg.op =3D "Sign"; } else @@ -194,8 +199,7 @@ } else if (!strcmp(sigalg.keytype, "RSA")) { - msg(D_XKEY, "xkey_pkcs11h_sign: signing with RSA key: padmode =3D = %s", - sigalg.padmode); + msg(D_XKEY, "xkey_pkcs11h_sign: signing with RSA key: padmode =3D = %s", sigalg.padmode); if (!strcmp(sigalg.padmode, "none")) { mech.mechanism =3D CKM_RSA_X_509; @@ -230,11 +234,10 @@ } else { - ASSERT(0); /* coding error -- we couldnt have created any such ke= y */ + ASSERT(0); /* coding error -- we couldnt have created any such key= */ } - if (CKR_OK !=3D pkcs11h_certificate_signAny_ex(cert, &mech, - tbs, tbslen, sig, siglen)) + if (CKR_OK !=3D pkcs11h_certificate_signAny_ex(cert, &mech, tbs, tbsle= n, sig, siglen)) { return 0; } @@ -244,7 +247,7 @@ } /* For EC keys, pkcs11 returns signature as r|s: convert to der encode= d */ - int derlen =3D ecdsa_bin2der(sig, (int) *siglen, siglen_max); + int derlen =3D ecdsa_bin2der(sig, (int)*siglen, siglen_max); if (derlen <=3D 0) { @@ -274,8 +277,7 @@ * other xkey_load_.. routines */ static int -xkey_load_from_pkcs11h(pkcs11h_certificate_t certificate, - struct tls_root_ctx *const ctx) +xkey_load_from_pkcs11h(pkcs11h_certificate_t certificate, struct tls_root_= ctx *const ctx) { int ret =3D 0; @@ -326,10 +328,8 @@ #endif /* HAVE_XKEY_PROVIDER */ int -pkcs11_init_tls_session(pkcs11h_certificate_t certificate, - struct tls_root_ctx *const ssl_ctx) +pkcs11_init_tls_session(pkcs11h_certificate_t certificate, struct tls_root= _ctx *const ssl_ctx) { - #ifdef HAVE_XKEY_PROVIDER return (xkey_load_from_pkcs11h(certificate, ssl_ctx) =3D=3D 0); /* inv= erts the return value */ #else @@ -403,7 +403,7 @@ openssl_session =3D NULL; } return ret; -#endif /* ifdef HAVE_XKEY_PROVIDER */ +#endif /* ifdef H= AVE_XKEY_PROVIDER */ } char * @@ -429,8 +429,7 @@ } int -pkcs11_certificate_serial(pkcs11h_certificate_t certificate, char *serial, - size_t serial_len) +pkcs11_certificate_serial(pkcs11h_certificate_t certificate, char *serial,= size_t serial_len) { X509 *x509 =3D NULL; BIO *bio =3D NULL; @@ -450,9 +449,9 @@ } i2a_ASN1_INTEGER(bio, X509_get_serialNumber(x509)); - n =3D BIO_read(bio, serial, serial_len-1); + n =3D BIO_read(bio, serial, serial_len - 1); - if (n<0) + if (n < 0) { serial[0] =3D '\x0'; } diff --git a/src/openvpn/platform.c b/src/openvpn/platform.c index 623daaa..880d14e 100644 --- a/src/openvpn/platform.c +++ b/src/openvpn/platform.c @@ -66,8 +66,10 @@ msg(M_ERR, "cd to '%s' failed", top); } msg(M_INFO, "chroot to '%s' and cd to '%s' succeeded", path, top); -#else /* ifdef HAVE_CHROOT */ - msg(M_FATAL, "Sorry but I can't chroot to '%s' because this operat= ing system doesn't appear to support the chroot() system call", path); +#else /* ifdef HAVE_CHROOT */ + msg(M_FATAL, + "Sorry but I can't chroot to '%s' because this operating syste= m doesn't appear to support the chroot() system call", + path); #endif } } @@ -94,8 +96,10 @@ } state->username =3D username; ret =3D true; -#else /* if defined(HAVE_GETPWNAM) && defined(HAVE_SETUID) */ - msg(M_FATAL, "cannot get UID for user %s -- platform lacks getpwna= me() or setuid() system calls", username); +#else /* if defined(HAVE_GETPWNAM) && defined(HAVE_SETUID) */ + msg(M_FATAL, + "cannot get UID for user %s -- platform lacks getpwname() or s= etuid() system calls", + username); #endif } return ret; @@ -138,8 +142,10 @@ } state->groupname =3D groupname; ret =3D true; -#else /* if defined(HAVE_GETGRNAM) && defined(HAVE_SETGID) */ - msg(M_FATAL, "cannot get GID for group %s -- platform lacks getgrn= am() or setgid() system calls", groupname); +#else /* if defined(HAVE_GETGRNAM) && defined(HAVE_SETGID) */ + msg(M_FATAL, + "cannot get GID for group %s -- platform lacks getgrnam() or s= etgid() system calls", + groupname); #endif } return ret; @@ -214,8 +220,7 @@ */ void platform_user_group_set(const struct platform_state_user *user_state, - const struct platform_state_group *group_state, - struct context *c) + const struct platform_state_group *group_state, st= ruct context *c) { int keep_caps =3D need_keep_caps(c); unsigned int err_flags =3D (keep_caps > 0) ? M_FATAL : M_NONFATAL; @@ -258,8 +263,8 @@ { /* -4 and -6 mean failure of setuid/gid respectively. * There is no point for us to continue if those failed. */ - msg(M_ERR, "capng_change_id('%s','%s') failed: %d", - user_state->username, group_state->groupname, res); + msg(M_ERR, "capng_change_id('%s','%s') failed: %d", user_state->us= ername, + group_state->groupname, res); } else if (res =3D=3D -3) { @@ -294,7 +299,7 @@ { msg(M_ERR, "Clearing KEEPCAPS flag failed"); } -#endif /* HAVE_LIBCAPNG */ +#endif /* HAVE_LIBCAPNG */ if (keep_caps) { @@ -321,7 +326,7 @@ { msg(M_INFO, "nice %d succeeded", niceval); } -#else /* ifdef HAVE_NICE */ +#else /* ifdef HAVE_NICE */ msg(M_WARN, "WARNING: nice %d failed (function not implemented)", = niceval); #endif } @@ -332,9 +337,9 @@ platform_getpid(void) { #ifdef _WIN32 - return (unsigned int) GetCurrentProcessId(); + return (unsigned int)GetCurrentProcessId(); #else - return (unsigned int) getpid(); + return (unsigned int)getpid(); #endif } @@ -354,12 +359,11 @@ else { msg(M_INFO, "mlock: MEMLOCK limit: soft=3D%ld KB, hard=3D%ld KB", - ((long int) rl.rlim_cur) / 1024, ((long int) rl.rlim_max) / 10= 24); - if (rl.rlim_cur < MIN_LOCKED_MEM_MB*1024*1024) + ((long int)rl.rlim_cur) / 1024, ((long int)rl.rlim_max) / 1024= ); + if (rl.rlim_cur < MIN_LOCKED_MEM_MB * 1024 * 1024) { - msg(M_INFO, "mlock: RLIMIT_MEMLOCK < %d MB, increase limit", - MIN_LOCKED_MEM_MB); - rl.rlim_cur =3D MIN_LOCKED_MEM_MB*1024*1024; + msg(M_INFO, "mlock: RLIMIT_MEMLOCK < %d MB, increase limit", M= IN_LOCKED_MEM_MB); + rl.rlim_cur =3D MIN_LOCKED_MEM_MB * 1024 * 1024; if (rl.rlim_max < rl.rlim_cur) { rl.rlim_max =3D rl.rlim_cur; @@ -397,10 +401,10 @@ res =3D _wchdir(wide_string(dir, &gc)); gc_free(&gc); return res; -#else /* ifdef _WIN32 */ +#else /* ifdef _WIN32 */ #ifdef HAVE_CHDIR return chdir(dir); -#else /* ifdef HAVE_CHDIR */ +#else /* ifdef HAVE_CHDIR */ return -1; #endif #endif @@ -550,9 +554,8 @@ { ++attempts; - if (!snprintf(fname, sizeof(fname), fname_fmt, max_prefix_len, - prefix, (unsigned long) get_random(), - (unsigned long) get_random())) + if (!snprintf(fname, sizeof(fname), fname_fmt, max_prefix_len, pre= fix, + (unsigned long)get_random(), (unsigned long)get_rand= om())) { msg(M_WARN, "ERROR: temporary filename too long"); return NULL; @@ -576,8 +579,7 @@ else if (fd =3D=3D -1 && errno !=3D EEXIST) { /* Something else went wrong, no need to retry. */ - msg(M_WARN | M_ERRNO, "Could not create temporary file '%s'", - retfname); + msg(M_WARN | M_ERRNO, "Could not create temporary file '%s'", = retfname); return NULL; } } @@ -590,12 +592,12 @@ * Put a directory and filename together. */ const char * -platform_gen_path(const char *directory, const char *filename, - struct gc_arena *gc) +platform_gen_path(const char *directory, const char *filename, struct gc_a= rena *gc) { #ifdef _WIN32 - const int CC_PATH_RESERVED =3D CC_LESS_THAN|CC_GREATER_THAN|CC_COLON - |CC_DOUBLE_QUOTE|CC_SLASH|CC_BACKSLASH|CC= _PIPE|CC_QUESTION_MARK|CC_ASTERISK; + const int CC_PATH_RESERVED =3D CC_LESS_THAN | CC_GREATER_THAN | CC_COL= ON | CC_DOUBLE_QUOTE + | CC_SLASH | CC_BACKSLASH | CC_PIPE | CC_= QUESTION_MARK + | CC_ASTERISK; #else const int CC_PATH_RESERVED =3D CC_SLASH; #endif @@ -607,13 +609,11 @@ const char *safe_filename =3D string_mod_const(filename, CC_PRINT, CC_= PATH_RESERVED, '_', gc); - if (safe_filename - && strcmp(safe_filename, ".") - && strcmp(safe_filename, "..") + if (safe_filename && strcmp(safe_filename, ".") && strcmp(safe_filenam= e, "..") #ifdef _WIN32 && win_safe_filename(safe_filename) #endif - ) + ) { const size_t outsize =3D strlen(safe_filename) + (directory ? strl= en(directory) : 0) + 16; struct buffer out =3D alloc_buf_gc(outsize, gc); @@ -671,14 +671,12 @@ { if (errno =3D=3D EACCES) { - msg( M_WARN | M_ERRNO, "Could not access file '%s'", filen= ame); + msg(M_WARN | M_ERRNO, "Could not access file '%s'", filena= me); } } } - dmsg(D_TEST_FILE, "TEST FILE '%s' [%d]", - filename ? filename : "UNDEF", - ret); + dmsg(D_TEST_FILE, "TEST FILE '%s' [%d]", filename ? filename : "UNDEF"= , ret); return ret; } diff --git a/src/openvpn/platform.h b/src/openvpn/platform.h index 18ea97d..f1a2b01 100644 --- a/src/openvpn/platform.h +++ b/src/openvpn/platform.h @@ -59,7 +59,8 @@ /* Get/Set UID of process */ -struct platform_state_user { +struct platform_state_user +{ #if defined(HAVE_GETPWNAM) && defined(HAVE_SETUID) const char *username; uid_t uid; @@ -70,7 +71,8 @@ /* Get/Set GID of process */ -struct platform_state_group { +struct platform_state_group +{ #if defined(HAVE_GETGRNAM) && defined(HAVE_SETGID) const char *groupname; gid_t gid; @@ -84,8 +86,7 @@ bool platform_group_get(const char *groupname, struct platform_state_group= *state); void platform_user_group_set(const struct platform_state_user *user_state, - const struct platform_state_group *group_stat= e, - struct context *c); + const struct platform_state_group *group_stat= e, struct context *c); /* @@ -116,7 +117,7 @@ unsigned int platform_getpid(void); -void platform_mlockall(bool print_msg); /* Disable paging */ +void platform_mlockall(bool print_msg); /* Disable paging */ int platform_chdir(const char *dir); @@ -152,8 +153,7 @@ struct gc_arena *gc); /** Put a directory and filename together. */ -const char *platform_gen_path(const char *directory, const char *filename, - struct gc_arena *gc); +const char *platform_gen_path(const char *directory, const char *filename,= struct gc_arena *gc); /** Return true if pathname is absolute. */ bool platform_absolute_pathname(const char *pathname); diff --git a/src/openvpn/plugin.c b/src/openvpn/plugin.c index 12912c0..e65a3bc 100644 --- a/src/openvpn/plugin.c +++ b/src/openvpn/plugin.c @@ -44,7 +44,7 @@ #include "win32.h" #include "memdbg.h" -#define PLUGIN_SYMBOL_REQUIRED (1<<0) +#define PLUGIN_SYMBOL_REQUIRED (1 << 0) /* used only for program aborts */ static struct plugin_common *static_plugin_common =3D NULL; /* GLOBAL */ @@ -152,7 +152,7 @@ static inline unsigned int plugin_supported_types(void) { - return ((1<n < MAX_PLUGINS) { @@ -193,7 +192,8 @@ for (i =3D 0; i < list->n; ++i) { const struct plugin_option *o =3D &list->plugins[i]; - msg(msglevel, " plugin[%d] %s '%s'", i, o->so_pathname, print_arg= v(o->argv, &gc, PA_BRACKET)); + msg(msglevel, " plugin[%d] %s '%s'", i, o->so_pathname, + print_argv(o->argv, &gc, PA_BRACKET)); } gc_free(&gc); @@ -203,24 +203,28 @@ #ifndef _WIN32 static void -libdl_resolve_symbol(void *handle, void **dest, const char *symbol, const = char *plugin_name, const unsigned int flags) +libdl_resolve_symbol(void *handle, void **dest, const char *symbol, const = char *plugin_name, + const unsigned int flags) { *dest =3D dlsym(handle, symbol); if ((flags & PLUGIN_SYMBOL_REQUIRED) && !*dest) { - msg(M_FATAL, "PLUGIN: could not find required symbol '%s' in plugi= n shared object %s: %s", symbol, plugin_name, dlerror()); + msg(M_FATAL, "PLUGIN: could not find required symbol '%s' in plugi= n shared object %s: %s", + symbol, plugin_name, dlerror()); } } #else /* ifndef _WIN32 */ static void -dll_resolve_symbol(HMODULE module, void **dest, const char *symbol, const = char *plugin_name, const unsigned int flags) +dll_resolve_symbol(HMODULE module, void **dest, const char *symbol, const = char *plugin_name, + const unsigned int flags) { *dest =3D GetProcAddress(module, symbol); if ((flags & PLUGIN_SYMBOL_REQUIRED) && !*dest) { - msg(M_FATAL, "PLUGIN: could not find required symbol '%s' in plugi= n DLL %s", symbol, plugin_name); + msg(M_FATAL, "PLUGIN: could not find required symbol '%s' in plugi= n DLL %s", symbol, + plugin_name); } } @@ -254,8 +258,7 @@ * was parsed. * */ - if (!platform_absolute_pathname(p->so_pathname) - && p->so_pathname[0] !=3D '.') + if (!platform_absolute_pathname(p->so_pathname) && p->so_pathname[0] != =3D '.') { char full[PATH_MAX]; @@ -269,24 +272,29 @@ } if (!p->handle) { - msg(M_ERR, "PLUGIN_INIT: could not load plugin shared object %s: %= s", p->so_pathname, dlerror()); + msg(M_ERR, "PLUGIN_INIT: could not load plugin shared object %s: %= s", p->so_pathname, + dlerror()); } -#define PLUGIN_SYM(var, name, flags) libdl_resolve_symbol(p->handle, (void= *)&p->var, name, p->so_pathname, flags) +#define PLUGIN_SYM(var, name, flags) \ + libdl_resolve_symbol(p->handle, (void *)&p->var, name, p->so_pathname,= flags) -#else /* ifndef _WIN32 */ +#else /* ifndef _WIN32 */ WCHAR *wpath =3D wide_string(p->so_pathname, &gc); - WCHAR normalized_plugin_path[MAX_PATH] =3D {0}; + WCHAR normalized_plugin_path[MAX_PATH] =3D { 0 }; /* Normalize the plugin path, converting any relative paths to absolut= e paths. */ if (!GetFullPathNameW(wpath, MAX_PATH, normalized_plugin_path, NULL)) { - msg(M_ERR, "PLUGIN_INIT: could not load plugin DLL: %ls. Failed to= normalize plugin path.", wpath); + msg(M_ERR, "PLUGIN_INIT: could not load plugin DLL: %ls. Failed to= normalize plugin path.", + wpath); } if (!plugin_in_trusted_dir(normalized_plugin_path)) { - msg(M_FATAL, "PLUGIN_INIT: could not load plugin DLL: %ls. The DLL= is not in a trusted directory.", normalized_plugin_path); + msg(M_FATAL, + "PLUGIN_INIT: could not load plugin DLL: %ls. The DLL is not i= n a trusted directory.", + normalized_plugin_path); } p->module =3D LoadLibraryW(normalized_plugin_path); @@ -295,7 +303,8 @@ msg(M_ERR, "PLUGIN_INIT: could not load plugin DLL: %ls", normaliz= ed_plugin_path); } -#define PLUGIN_SYM(var, name, flags) dll_resolve_symbol(p->module, (void *= )&p->var, name, p->so_pathname, flags) +#define PLUGIN_SYM(var, name, flags) \ + dll_resolve_symbol(p->module, (void *)&p->var, name, p->so_pathname, f= lags) #endif /* ifndef _WIN32 */ @@ -314,12 +323,14 @@ if (!p->open1 && !p->open2 && !p->open3) { - msg(M_FATAL, "PLUGIN: symbol openvpn_plugin_open_vX is undefined i= n plugin: %s", p->so_pathname); + msg(M_FATAL, "PLUGIN: symbol openvpn_plugin_open_vX is undefined i= n plugin: %s", + p->so_pathname); } if (!p->func1 && !p->func2 && !p->func3) { - msg(M_FATAL, "PLUGIN: symbol openvpn_plugin_func_vX is undefined i= n plugin: %s", p->so_pathname); + msg(M_FATAL, "PLUGIN: symbol openvpn_plugin_func_vX is undefined i= n plugin: %s", + p->so_pathname); } /* @@ -330,10 +341,9 @@ const int plugin_needs_version =3D (*p->min_version_required)(); if (plugin_needs_version > OPENVPN_PLUGIN_VERSION) { - msg(M_FATAL, "PLUGIN_INIT: plugin needs interface version %d, = but this version of OpenVPN only supports version %d: %s", - plugin_needs_version, - OPENVPN_PLUGIN_VERSION, - p->so_pathname); + msg(M_FATAL, + "PLUGIN_INIT: plugin needs interface version %d, but this = version of OpenVPN only supports version %d: %s", + plugin_needs_version, OPENVPN_PLUGIN_VERSION, p->so_pathna= me); } } @@ -348,7 +358,9 @@ if (rel) { - msg(M_WARN, "WARNING: plugin '%s' specified by a relative pathname= -- using an absolute pathname would be more secure", p->so_pathname); + msg(M_WARN, + "WARNING: plugin '%s' specified by a relative pathname -- usin= g an absolute pathname would be more secure", + p->so_pathname); } p->initialized =3D true; @@ -427,9 +439,9 @@ static struct openvpn_plugin_callbacks callbacks =3D { plugin_log, plugin_vlog, - secure_memzero, /* plugin_secure_memzero */ - openvpn_base64_encode, /* plugin_base64_encode */ - openvpn_base64_decode, /* plugin_base64_decode */ + secure_memzero, /* plugin_secure_memzero */ + openvpn_base64_encode, /* plugin_base64_encode */ + openvpn_base64_decode, /* plugin_base64_decode */ }; @@ -444,10 +456,8 @@ #endif static void -plugin_open_item(struct plugin *p, - const struct plugin_option *o, - struct openvpn_plugin_string_list **retlist, - const char **envp, +plugin_open_item(struct plugin *p, const struct plugin_option *o, + struct openvpn_plugin_string_list **retlist, const char *= *envp, const int init_point) { ASSERT(p->initialized); @@ -471,19 +481,20 @@ if (p->open3) { struct openvpn_plugin_args_open_in args =3D { p->plugin_type_m= ask, - (const char **cons= t) o->argv, - (const char **cons= t) envp, + (const char **cons= t)o->argv, + (const char **cons= t)envp, &callbacks, SSLAPI, PACKAGE_VERSION, OPENVPN_VERSION_MA= JOR, OPENVPN_VERSION_MI= NOR, - _OPENVPN_PATCH_LEV= EL}; + _OPENVPN_PATCH_LEV= EL }; struct openvpn_plugin_args_open_return retargs; CLEAR(retargs); retargs.return_list =3D retlist; - if ((*p->open3)(OPENVPN_PLUGINv3_STRUCTVER, &args, &retargs) = =3D=3D OPENVPN_PLUGIN_FUNC_SUCCESS) + if ((*p->open3)(OPENVPN_PLUGINv3_STRUCTVER, &args, &retargs) + =3D=3D OPENVPN_PLUGIN_FUNC_SUCCESS) { p->plugin_type_mask =3D retargs.type_mask; p->plugin_handle =3D retargs.handle; @@ -506,24 +517,20 @@ ASSERT(0); } - msg(D_PLUGIN, "PLUGIN_INIT: POST %s '%s' intercepted=3D%s %s", - p->so_pathname, - print_argv(o->argv, &gc, PA_BRACKET), - plugin_mask_string(p->plugin_type_mask, &gc), + msg(D_PLUGIN, "PLUGIN_INIT: POST %s '%s' intercepted=3D%s %s", p->= so_pathname, + print_argv(o->argv, &gc, PA_BRACKET), plugin_mask_string(p->pl= ugin_type_mask, &gc), (retlist && *retlist) ? "[RETLIST]" : ""); if ((p->plugin_type_mask | plugin_supported_types()) !=3D plugin_s= upported_types()) { - msg(M_FATAL, "PLUGIN_INIT: plugin %s expressed interest in uns= upported plugin types: [want=3D0x%08x, have=3D0x%08x]", - p->so_pathname, - p->plugin_type_mask, - plugin_supported_types()); + msg(M_FATAL, + "PLUGIN_INIT: plugin %s expressed interest in unsupported = plugin types: [want=3D0x%08x, have=3D0x%08x]", + p->so_pathname, p->plugin_type_mask, plugin_supported_type= s()); } if (p->plugin_handle =3D=3D NULL) { - msg(M_FATAL, "PLUGIN_INIT: plugin initialization function fail= ed: %s", - p->so_pathname); + msg(M_FATAL, "PLUGIN_INIT: plugin initialization function fail= ed: %s", p->so_pathname); } gc_free(&gc); @@ -531,15 +538,9 @@ } static int -plugin_call_item(const struct plugin *p, - void *per_client_context, - const int type, - const struct argv *av, - struct openvpn_plugin_string_list **retlist, - const char **envp, - int certdepth, - openvpn_x509_cert_t *current_cert - ) +plugin_call_item(const struct plugin *p, void *per_client_context, const i= nt type, + const struct argv *av, struct openvpn_plugin_string_list = **retlist, + const char **envp, int certdepth, openvpn_x509_cert_t *cu= rrent_cert) { int status =3D OPENVPN_PLUGIN_FUNC_SUCCESS; @@ -563,8 +564,8 @@ if (p->func3) { struct openvpn_plugin_args_func_in args =3D { type, - (const char **cons= t) a.argv, - (const char **cons= t) envp, + (const char **cons= t)a.argv, + (const char **cons= t)envp, p->plugin_handle, per_client_context, (current_cert ? ce= rtdepth : -1), @@ -578,7 +579,8 @@ } else if (p->func2) { - status =3D (*p->func2)(p->plugin_handle, type, (const char **)= a.argv, envp, per_client_context, retlist); + status =3D (*p->func2)(p->plugin_handle, type, (const char **)= a.argv, envp, + per_client_context, retlist); } else if (p->func1) { @@ -589,17 +591,13 @@ ASSERT(0); } - msg(D_PLUGIN, "PLUGIN_CALL: POST %s/%s status=3D%d", - p->so_pathname, - plugin_type_name(type), + msg(D_PLUGIN, "PLUGIN_CALL: POST %s/%s status=3D%d", p->so_pathnam= e, plugin_type_name(type), status); if (status =3D=3D OPENVPN_PLUGIN_FUNC_ERROR) { msg(M_WARN, "PLUGIN_CALL: plugin function %s failed with statu= s %d: %s", - plugin_type_name(type), - status, - p->so_pathname); + plugin_type_name(type), status, p->so_pathname); } argv_free(&a); @@ -652,8 +650,7 @@ } static void -plugin_per_client_init(const struct plugin_common *pc, - struct plugin_per_client *cli, +plugin_per_client_init(const struct plugin_common *pc, struct plugin_per_c= lient *cli, const int init_point) { const int n =3D pc->n; @@ -662,8 +659,7 @@ for (i =3D 0; i < n; ++i) { const struct plugin *p =3D &pc->plugins[i]; - if (p->plugin_handle - && (init_point < 0 || init_point =3D=3D p->requested_initializ= ation_point) + if (p->plugin_handle && (init_point < 0 || init_point =3D=3D p->re= quested_initialization_point) && p->client_constructor) { cli->per_client_context[i] =3D (*p->client_constructor)(p->plu= gin_handle); @@ -711,8 +707,7 @@ for (i =3D 0; i < list->n; ++i) { - plugin_init_item(&pc->plugins[i], - &list->plugins[i]); + plugin_init_item(&pc->plugins[i], &list->plugins[i]); pc->n =3D i + 1; } @@ -721,11 +716,8 @@ } static void -plugin_common_open(struct plugin_common *pc, - const struct plugin_option_list *list, - struct plugin_return *pr, - const struct env_set *es, - const int init_point) +plugin_common_open(struct plugin_common *pc, const struct plugin_option_li= st *list, + struct plugin_return *pr, const struct env_set *es, con= st int init_point) { struct gc_arena gc =3D gc_new(); int i; @@ -740,10 +732,7 @@ for (i =3D 0; i < pc->n; ++i) { - plugin_open_item(&pc->plugins[i], - &list->plugins[i], - pr ? &pr->list[i] : NULL, - envp, + plugin_open_item(&pc->plugins[i], &list->plugins[i], pr ? &pr->lis= t[i] : NULL, envp, init_point); } @@ -782,25 +771,17 @@ } void -plugin_list_open(struct plugin_list *pl, - const struct plugin_option_list *list, - struct plugin_return *pr, - const struct env_set *es, - const int init_point) +plugin_list_open(struct plugin_list *pl, const struct plugin_option_list *= list, + struct plugin_return *pr, const struct env_set *es, const= int init_point) { plugin_common_open(pl->common, list, pr, es, init_point); plugin_per_client_init(pl->common, &pl->per_client, init_point); } int -plugin_call_ssl(const struct plugin_list *pl, - const int type, - const struct argv *av, - struct plugin_return *pr, - struct env_set *es, - int certdepth, - openvpn_x509_cert_t *current_cert - ) +plugin_call_ssl(const struct plugin_list *pl, const int type, const struct= argv *av, + struct plugin_return *pr, struct env_set *es, int certdept= h, + openvpn_x509_cert_t *current_cert) { if (pr) { @@ -821,23 +802,16 @@ for (i =3D 0; i < n; ++i) { - const int status =3D plugin_call_item(&pl->common->plugins[i], - pl->per_client.per_client_= context[i], - type, - av, - pr ? &pr->list[i] : NULL, - envp, - certdepth, - current_cert - ); + const int status =3D + plugin_call_item(&pl->common->plugins[i], pl->per_client.p= er_client_context[i], + type, av, pr ? &pr->list[i] : NULL, envp,= certdepth, current_cert); switch (status) { case OPENVPN_PLUGIN_FUNC_SUCCESS: break; case OPENVPN_PLUGIN_FUNC_DEFERRED: - if ((type =3D=3D OPENVPN_PLUGIN_AUTH_USER_PASS_VERIFY) - && deferred_auth_done) + if ((type =3D=3D OPENVPN_PLUGIN_AUTH_USER_PASS_VERIFY)= && deferred_auth_done) { /* * Do not allow deferred auth if a deferred auth h= as @@ -854,13 +828,12 @@ * error, we bail out and exit the OpenVPN process. */ error =3D true; - msg(M_FATAL, - "Exiting due to multiple authentication plug-i= ns " - "performing deferred authentication. Only one= " - "authentication plug-in doing deferred auth is= " - "allowed. Ignoring the result and stopping no= w, " - "the current authentication result is not to b= e " - "trusted."); + msg(M_FATAL, "Exiting due to multiple authenticati= on plug-ins " + "performing deferred authentication. = Only one " + "authentication plug-in doing deferre= d auth is " + "allowed. Ignoring the result and st= opping now, " + "the current authentication result is= not to be " + "trusted."); break; } deferred_auth_done =3D true; @@ -996,8 +969,7 @@ } void -plugin_return_get_column(const struct plugin_return *src, - struct plugin_return *dest, +plugin_return_get_column(const struct plugin_return *src, struct plugin_re= turn *dest, const char *colname) { int i; @@ -1035,10 +1007,7 @@ msg(msglevel, "PLUGIN #%d (%s)", i, prefix); while (l) { - msg(msglevel, "[%d] '%s' -> '%s'\n", - ++count, - l->name, - l->value); + msg(msglevel, "[%d] '%s' -> '%s'\n", ++count, l->name, l->valu= e); l =3D l->next; } } diff --git a/src/openvpn/plugin.h b/src/openvpn/plugin.h index b44cf0d..63999b6 100644 --- a/src/openvpn/plugin.h +++ b/src/openvpn/plugin.h @@ -41,17 +41,20 @@ #define MAX_PLUGINS 16 -struct plugin_option { +struct plugin_option +{ const char *so_pathname; const char **argv; }; -struct plugin_option_list { +struct plugin_option_list +{ int n; struct plugin_option plugins[MAX_PLUGINS]; }; -struct plugin { +struct plugin +{ bool initialized; const char *so_pathname; unsigned int plugin_type_mask; @@ -105,8 +108,7 @@ struct plugin_option_list *plugin_option_list_new(struct gc_arena *gc); -bool plugin_option_list_add(struct plugin_option_list *list, char **p, - struct gc_arena *gc); +bool plugin_option_list_add(struct plugin_option_list *list, char **p, str= uct gc_arena *gc); #ifndef ENABLE_SMALL void plugin_option_list_print(const struct plugin_option_list *list, int m= sglevel); @@ -115,29 +117,20 @@ struct plugin_list *plugin_list_init(const struct plugin_option_list *list= ); -void plugin_list_open(struct plugin_list *pl, - const struct plugin_option_list *list, - struct plugin_return *pr, - const struct env_set *es, - const int init_point); +void plugin_list_open(struct plugin_list *pl, const struct plugin_option_l= ist *list, + struct plugin_return *pr, const struct env_set *es, = const int init_point); struct plugin_list *plugin_list_inherit(const struct plugin_list *src); -int plugin_call_ssl(const struct plugin_list *pl, - const int type, - const struct argv *av, - struct plugin_return *pr, - struct env_set *es, - int current_cert_depth, - openvpn_x509_cert_t *current_cert - ); +int plugin_call_ssl(const struct plugin_list *pl, const int type, const st= ruct argv *av, + struct plugin_return *pr, struct env_set *es, int curr= ent_cert_depth, + openvpn_x509_cert_t *current_cert); void plugin_list_close(struct plugin_list *pl); bool plugin_defined(const struct plugin_list *pl, const int type); -void plugin_return_get_column(const struct plugin_return *src, - struct plugin_return *dest, +void plugin_return_get_column(const struct plugin_return *src, struct plug= in_return *dest, const char *colname); void plugin_return_free(struct plugin_return *pr); @@ -173,8 +166,14 @@ } #else /* ifdef ENABLE_PLUGIN */ -struct plugin_list { int dummy; }; -struct plugin_return { int dummy; }; +struct plugin_list +{ + int dummy; +}; +struct plugin_return +{ + int dummy; +}; static inline bool plugin_defined(const struct plugin_list *pl, const int type) @@ -183,14 +182,9 @@ } static inline int -plugin_call_ssl(const struct plugin_list *pl, - const int type, - const struct argv *av, - struct plugin_return *pr, - struct env_set *es, - int current_cert_depth, - openvpn_x509_cert_t *current_cert - ) +plugin_call_ssl(const struct plugin_list *pl, const int type, const struct= argv *av, + struct plugin_return *pr, struct env_set *es, int current_= cert_depth, + openvpn_x509_cert_t *current_cert) { return 0; } @@ -198,11 +192,8 @@ #endif /* ENABLE_PLUGIN */ static inline int -plugin_call(const struct plugin_list *pl, - const int type, - const struct argv *av, - struct plugin_return *pr, - struct env_set *es) +plugin_call(const struct plugin_list *pl, const int type, const struct arg= v *av, + struct plugin_return *pr, struct env_set *es) { return plugin_call_ssl(pl, type, av, pr, es, -1, NULL); } diff --git a/src/openvpn/pool.c b/src/openvpn/pool.c index bfa43ec..898a045 100644 --- a/src/openvpn/pool.c +++ b/src/openvpn/pool.c @@ -89,14 +89,11 @@ * Keep track of a possible allocation to us * from an earlier session. */ - if (previous_usage < 0 - && common_name - && ipe->common_name + if (previous_usage < 0 && common_name && ipe->common_name && !strcmp(common_name, ipe->common_name)) { previous_usage =3D i; } - } } @@ -125,16 +122,14 @@ if (start > end) { msg(msglevel, "--ifconfig-pool start IP [%s] is greater than end I= P [%s]", - print_in_addr_t(start, 0, &gc), - print_in_addr_t(end, 0, &gc)); + print_in_addr_t(start, 0, &gc), print_in_addr_t(end, 0, &gc)); ret =3D false; } if (end - start >=3D IFCONFIG_POOL_MAX) { - msg(msglevel, "--ifconfig-pool address range is too large [%s -> %= s]. Current maximum is %d addresses, as defined by IFCONFIG_POOL_MAX varia= ble.", - print_in_addr_t(start, 0, &gc), - print_in_addr_t(end, 0, &gc), - IFCONFIG_POOL_MAX); + msg(msglevel, + "--ifconfig-pool address range is too large [%s -> %s]. Curre= nt maximum is %d addresses, as defined by IFCONFIG_POOL_MAX variable.", + print_in_addr_t(start, 0, &gc), print_in_addr_t(end, 0, &gc), = IFCONFIG_POOL_MAX); ret =3D false; } gc_free(&gc); @@ -142,10 +137,9 @@ } struct ifconfig_pool * -ifconfig_pool_init(const bool ipv4_pool, enum pool_type type, in_addr_t st= art, - in_addr_t end, const bool duplicate_cn, - const bool ipv6_pool, const struct in6_addr ipv6_base, - const int ipv6_netbits ) +ifconfig_pool_init(const bool ipv4_pool, enum pool_type type, in_addr_t st= art, in_addr_t end, + const bool duplicate_cn, const bool ipv6_pool, const st= ruct in6_addr ipv6_base, + const int ipv6_netbits) { struct gc_arena gc =3D gc_new(); struct ifconfig_pool *pool =3D NULL; @@ -179,8 +173,7 @@ if (pool_ipv4_size < 2) { - msg(M_FATAL, "IPv4 pool size is too small (%d), must be at lea= st 2", - pool_ipv4_size); + msg(M_FATAL, "IPv4 pool size is too small (%d), must be at lea= st 2", pool_ipv4_size); } msg(D_IFCONFIG_POOL, "IFCONFIG POOL IPv4: base=3D%s size=3D%d", @@ -198,10 +191,8 @@ * 4 bytes, therefore we can just extract that and use it as base = in * integer form */ - uint32_t base =3D (ipv6_base.s6_addr[12] << 24) - | (ipv6_base.s6_addr[13] << 16) - | (ipv6_base.s6_addr[14] << 8) - | ipv6_base.s6_addr[15]; + uint32_t base =3D (ipv6_base.s6_addr[12] << 24) | (ipv6_base.s6_ad= dr[13] << 16) + | (ipv6_base.s6_addr[14] << 8) | ipv6_base.s6_addr= [15]; /* some bits of the last 4 bytes may still be part of the network * portion of the address, therefore we need to set them to 0 */ @@ -214,7 +205,7 @@ * the following operation first computes mask=3D0x3fffff and = then * uses mask to extract the wanted bits from base */ - uint32_t mask =3D (1 << (128 - ipv6_netbits) ) - 1; + uint32_t mask =3D (1 << (128 - ipv6_netbits)) - 1; base &=3D mask; } @@ -232,24 +223,21 @@ if (base =3D=3D 0) { msg(D_IFCONFIG_POOL, "IFCONFIG POOL IPv6: incrementing pool st= art " - "to avoid ::0 assignment"); + "to avoid ::0 assignment"); base++; pool->ipv6.base.s6_addr[15]++; } - pool_ipv6_size =3D ipv6_netbits >=3D 112 - ? (1 << (128 - ipv6_netbits)) - base - : IFCONFIG_POOL_MAX; + pool_ipv6_size =3D + ipv6_netbits >=3D 112 ? (1 << (128 - ipv6_netbits)) - base : I= FCONFIG_POOL_MAX; if (pool_ipv6_size < 2) { - msg(M_FATAL, "IPv6 pool size is too small (%d), must be at lea= st 2", - pool_ipv6_size); + msg(M_FATAL, "IPv6 pool size is too small (%d), must be at lea= st 2", pool_ipv6_size); } msg(D_IFCONFIG_POOL, "IFCONFIG POOL IPv6: base=3D%s size=3D%d netb= its=3D%d", - print_in6_addr(pool->ipv6.base, 0, &gc), pool_ipv6_size, - ipv6_netbits); + print_in6_addr(pool->ipv6.base, 0, &gc), pool_ipv6_size, ipv6_= netbits); /* if there is no v4 pool, or the v6 pool is smaller, use * v6 pool size as "unified pool size" @@ -264,16 +252,20 @@ { if (pool_ipv4_size < pool_ipv6_size) { - msg(M_INFO, "NOTE: IPv4 pool size is %d, IPv6 pool size is %d.= " + msg(M_INFO, + "NOTE: IPv4 pool size is %d, IPv6 pool size is %d. " "IPv4 pool size limits the number of clients that can be " - "served from the pool", pool_ipv4_size, pool_ipv6_size); + "served from the pool", + pool_ipv4_size, pool_ipv6_size); } else if (pool_ipv4_size > pool_ipv6_size) { - msg(M_WARN, "WARNING: IPv4 pool size is %d, IPv6 pool size is = %d. " + msg(M_WARN, + "WARNING: IPv4 pool size is %d, IPv6 pool size is %d. " "IPv6 pool size limits the number of clients that can be " "served from the pool. This is likely a MISTAKE - please c= heck " - "your configuration", pool_ipv4_size, pool_ipv6_size); + "your configuration", + pool_ipv4_size, pool_ipv6_size); } } @@ -302,7 +294,8 @@ } ifconfig_pool_handle -ifconfig_pool_acquire(struct ifconfig_pool *pool, in_addr_t *local, in_add= r_t *remote, struct in6_addr *remote_ipv6, const char *common_name) +ifconfig_pool_acquire(struct ifconfig_pool *pool, in_addr_t *local, in_add= r_t *remote, + struct in6_addr *remote_ipv6, const char *common_nam= e) { int i; @@ -402,8 +395,7 @@ } static ifconfig_pool_handle -ifconfig_pool_ipv6_base_to_handle(const struct ifconfig_pool *pool, - const struct in6_addr *in_addr) +ifconfig_pool_ipv6_base_to_handle(const struct ifconfig_pool *pool, const = struct in6_addr *in_addr) { ifconfig_pool_handle ret; uint32_t base, addr; @@ -422,14 +414,10 @@ } } - base =3D (pool->ipv6.base.s6_addr[12] << 24) - | (pool->ipv6.base.s6_addr[13] << 16) - | (pool->ipv6.base.s6_addr[14] << 8) - | pool->ipv6.base.s6_addr[15]; + base =3D (pool->ipv6.base.s6_addr[12] << 24) | (pool->ipv6.base.s6_add= r[13] << 16) + | (pool->ipv6.base.s6_addr[14] << 8) | pool->ipv6.base.s6_addr[= 15]; - addr =3D (in_addr->s6_addr[12] << 24) - | (in_addr->s6_addr[13] << 16) - | (in_addr->s6_addr[14] << 8) + addr =3D (in_addr->s6_addr[12] << 24) | (in_addr->s6_addr[13] << 16) |= (in_addr->s6_addr[14] << 8) | in_addr->s6_addr[15]; ret =3D addr - base; @@ -478,14 +466,14 @@ /* IPv6 pools are always INDIV (--linear) */ if (pool->ipv6.enabled && hand >=3D 0 && hand < pool->size) { - ret =3D add_in6_addr( pool->ipv6.base, hand ); + ret =3D add_in6_addr(pool->ipv6.base, hand); } return ret; } static void -ifconfig_pool_set(struct ifconfig_pool *pool, const char *cn, - ifconfig_pool_handle h, const bool fixed) +ifconfig_pool_set(struct ifconfig_pool *pool, const char *cn, ifconfig_poo= l_handle h, + const bool fixed) { struct ifconfig_pool_entry *e =3D &pool->list[h]; ifconfig_pool_entry_free(e, true); @@ -557,7 +545,8 @@ if (refresh_freq > 0) { ret->fixed =3D false; - ret->file =3D status_open(filename, refresh_freq, -1, NULL, STATUS= _OUTPUT_READ|STATUS_OUTPUT_WRITE); + ret->file =3D + status_open(filename, refresh_freq, -1, NULL, STATUS_OUTPUT_RE= AD | STATUS_OUTPUT_WRITE); } else { @@ -640,8 +629,7 @@ * - CN,IP4 * - CN,,IP6 */ - if (!buf_parse(&in, ',', cn_buf, buf_size) - || !buf_parse(&in, ',', ip_buf, buf_size)) + if (!buf_parse(&in, ',', cn_buf, buf_size) || !buf_parse(&in, = ',', ip_buf, buf_size)) { continue; } @@ -651,22 +639,18 @@ if (strlen(ip_buf) > 0) { bool v4_ok =3D true; - in_addr_t addr =3D getaddr(GETADDR_HOST_ORDER, ip_buf, 0, = &v4_ok, - NULL); + in_addr_t addr =3D getaddr(GETADDR_HOST_ORDER, ip_buf, 0, = &v4_ok, NULL); if (!v4_ok) { - msg(M_WARN, "pool: invalid IPv4 (%s) for CN=3D%s", ip_= buf, - cn_buf); + msg(M_WARN, "pool: invalid IPv4 (%s) for CN=3D%s", ip_= buf, cn_buf); } else { h =3D ifconfig_pool_ip_base_to_handle(pool, addr); if (h < 0) { - msg(M_WARN, - "pool: IPv4 (%s) out of pool range for CN=3D%s= ", - ip_buf, cn_buf); + msg(M_WARN, "pool: IPv4 (%s) out of pool range for= CN=3D%s", ip_buf, cn_buf); } } } @@ -677,17 +661,14 @@ if (!get_ipv6_addr(ip6_buf, &addr6, NULL, M_WARN)) { - msg(M_WARN, "pool: invalid IPv6 (%s) for CN=3D%s", ip6= _buf, - cn_buf); + msg(M_WARN, "pool: invalid IPv6 (%s) for CN=3D%s", ip6= _buf, cn_buf); } else { h6 =3D ifconfig_pool_ipv6_base_to_handle(pool, &addr6); if (h6 < 0) { - msg(M_WARN, - "pool: IPv6 (%s) out of pool range for CN=3D%s= ", - ip6_buf, cn_buf); + msg(M_WARN, "pool: IPv6 (%s) out of pool range for= CN=3D%s", ip6_buf, cn_buf); } /* Rely on IPv6 if no IPv4 was provided or the one pro= vided @@ -707,8 +688,7 @@ */ if ((h6 >=3D 0) && (h !=3D h6)) { - msg(M_WARN, - "pool: IPv4 (%s) and IPv6 (%s) have different offsets!= Relying on IPv4", + msg(M_WARN, "pool: IPv4 (%s) and IPv6 (%s) have different = offsets! Relying on IPv4", ip_buf, ip6_buf); } @@ -759,7 +739,7 @@ CLEAR(array); msg(M_INFO | M_NOPREFIX, "************ 1"); - for (i =3D 0; i < (int) SIZE(array); ++i) + for (i =3D 0; i < (int)SIZE(array); ++i) { char *cn; ifconfig_pool_handle h; @@ -777,15 +757,12 @@ break; } msg(M_INFO | M_NOPREFIX, "IFCONFIG_POOL TEST pass 1: l=3D%s r=3D%s= cn=3D%s", - print_in_addr_t(local, 0, &gc), - print_in_addr_t(remote, 0, &gc), - cn); + print_in_addr_t(local, 0, &gc), print_in_addr_t(remote, 0, &gc= ), cn); array[i] =3D h; - } msg(M_INFO | M_NOPREFIX, "************* 2"); - for (i =3D (int) SIZE(array) / 16; i < (int) SIZE(array) / 8; ++i) + for (i =3D (int)SIZE(array) / 16; i < (int)SIZE(array) / 8; ++i) { msg(M_INFO, "Attempt to release %d cn=3D%s", array[i], p->list[i].= common_name); if (!ifconfig_pool_release(p, array[i])) @@ -798,13 +775,13 @@ CLEAR(array); msg(M_INFO | M_NOPREFIX, "**************** 3"); - for (i =3D 0; i < (int) SIZE(array); ++i) + for (i =3D 0; i < (int)SIZE(array); ++i) { char *cn; ifconfig_pool_handle h; in_addr_t local, remote; char buf[256]; - snprintf(buf, sizeof(buf), "common-name-%d", i+24); + snprintf(buf, sizeof(buf), "common-name-%d", i + 24); #ifdef DUP_CN cn =3D NULL; #else @@ -816,11 +793,8 @@ break; } msg(M_INFO | M_NOPREFIX, "IFCONFIG_POOL TEST pass 3: l=3D%s r=3D%s= cn=3D%s", - print_in_addr_t(local, 0, &gc), - print_in_addr_t(remote, 0, &gc), - cn); + print_in_addr_t(local, 0, &gc), print_in_addr_t(remote, 0, &gc= ), cn); array[i] =3D h; - } ifconfig_pool_free(p); diff --git a/src/openvpn/pool.h b/src/openvpn/pool.h index 9f50ca9..6cecef0 100644 --- a/src/openvpn/pool.h +++ b/src/openvpn/pool.h @@ -29,7 +29,7 @@ #include "status.h" #define IFCONFIG_POOL_MAX 65536 -#define IFCONFIG_POOL_MIN_NETBITS 16 +#define IFCONFIG_POOL_MIN_NETBITS 16 enum pool_type { @@ -48,12 +48,14 @@ struct ifconfig_pool { bool duplicate_cn; - struct { + struct + { bool enabled; enum pool_type type; in_addr_t base; } ipv4; - struct { + struct + { bool enabled; struct in6_addr base; } ipv6; @@ -69,18 +71,18 @@ typedef int ifconfig_pool_handle; -struct ifconfig_pool *ifconfig_pool_init(const bool ipv4_pool, - enum pool_type type, in_addr_t st= art, +struct ifconfig_pool *ifconfig_pool_init(const bool ipv4_pool, enum pool_t= ype type, in_addr_t start, in_addr_t end, const bool duplica= te_cn, - const bool ipv6_pool, - const struct in6_addr ipv6_base, + const bool ipv6_pool, const struc= t in6_addr ipv6_base, const int ipv6_netbits); void ifconfig_pool_free(struct ifconfig_pool *pool); bool ifconfig_pool_verify_range(const int msglevel, const in_addr_t start,= const in_addr_t end); -ifconfig_pool_handle ifconfig_pool_acquire(struct ifconfig_pool *pool, in_= addr_t *local, in_addr_t *remote, struct in6_addr *remote_ipv6, const char = *common_name); +ifconfig_pool_handle ifconfig_pool_acquire(struct ifconfig_pool *pool, in_= addr_t *local, + in_addr_t *remote, struct in6_a= ddr *remote_ipv6, + const char *common_name); bool ifconfig_pool_release(struct ifconfig_pool *pool, ifconfig_pool_handl= e hand, const bool hard); diff --git a/src/openvpn/proto.c b/src/openvpn/proto.c index 4820602..34b3378 100644 --- a/src/openvpn/proto.c +++ b/src/openvpn/proto.c @@ -54,8 +54,7 @@ else if (tunnel_type =3D=3D DEV_TYPE_TAP) { const struct openvpn_ethhdr *eh; - if (BLEN(buf) < (sizeof(struct openvpn_ethhdr) - + sizeof(struct openvpn_iphdr))) + if (BLEN(buf) < (sizeof(struct openvpn_ethhdr) + sizeof(struct ope= nvpn_iphdr))) { return false; } @@ -71,8 +70,7 @@ if (proto =3D=3D htons(OPENVPN_ETH_P_8021Q)) { const struct openvpn_8021qhdr *evh; - if (BLEN(buf) < (sizeof(struct openvpn_ethhdr) - + sizeof(struct openvpn_iphdr))) + if (BLEN(buf) < (sizeof(struct openvpn_ethhdr) + sizeof(struct= openvpn_iphdr))) { return false; } @@ -109,12 +107,12 @@ bool is_ipv4(int tunnel_type, struct buffer *buf) { - return is_ipv_X( tunnel_type, buf, 4 ); + return is_ipv_X(tunnel_type, buf, 4); } bool is_ipv6(int tunnel_type, struct buffer *buf) { - return is_ipv_X( tunnel_type, buf, 6 ); + return is_ipv_X(tunnel_type, buf, 6); } @@ -131,9 +129,8 @@ */ for (int i =3D 0; i < len_payload; i +=3D 2) { - sum +=3D (uint16_t)(((payload[i] << 8) & 0xFF00) - +((i + 1 < len_payload) ? (payload[i + 1] & 0xF= F) : 0)); - + sum +=3D (uint16_t)(((payload[i] << 8) & 0xFF00) + + ((i + 1 < len_payload) ? (payload[i + 1] & 0xF= F) : 0)); } /* @@ -143,7 +140,6 @@ for (int i =3D 0; i < addr_len; i +=3D 2) { sum +=3D (uint16_t)((src_addr[i] << 8) & 0xFF00) + (src_addr[i + 1= ] & 0xFF); - } for (int i =3D 0; i < addr_len; i +=3D 2) { @@ -166,17 +162,14 @@ } /* Take the one's complement of sum */ - return ((uint16_t) ~sum); + return ((uint16_t)~sum); } #ifdef PACKET_TRUNCATION_CHECK void -ipv4_packet_size_verify(const uint8_t *data, - const int size, - const int tunnel_type, - const char *prefix, - counter_type *errors) +ipv4_packet_size_verify(const uint8_t *data, const int size, const int tun= nel_type, + const char *prefix, counter_type *errors) { if (size > 0) { @@ -192,13 +185,13 @@ const char *msgstr =3D "PACKET SIZE INFO"; unsigned int msglevel =3D D_PACKET_TRUNC_DEBUG; - if (BLEN(&buf) < (int) sizeof(struct openvpn_iphdr)) + if (BLEN(&buf) < (int)sizeof(struct openvpn_iphdr)) { return; } verify_align_4(&buf); - pip =3D (struct openvpn_iphdr *) BPTR(&buf); + pip =3D (struct openvpn_iphdr *)BPTR(&buf); hlen =3D OPENVPN_IPH_GET_LEN(pip->version_len); totlen =3D ntohs(pip->tot_len); @@ -213,13 +206,8 @@ } } - msg(msglevel, "%s %s: size=3D%d totlen=3D%d hlen=3D%d errcount= =3D" counter_format, - msgstr, - prefix, - BLEN(&buf), - totlen, - hlen, - errors ? *errors : (counter_type)0); + msg(msglevel, "%s %s: size=3D%d totlen=3D%d hlen=3D%d errcount= =3D" counter_format, msgstr, + prefix, BLEN(&buf), totlen, hlen, errors ? *errors : (coun= ter_type)0); } } } diff --git a/src/openvpn/proto.h b/src/openvpn/proto.h index 0942c11..62157fa 100644 --- a/src/openvpn/proto.h +++ b/src/openvpn/proto.h @@ -32,15 +32,15 @@ * Tunnel types */ #define DEV_TYPE_UNDEF 0 -#define DEV_TYPE_TUN 2 /* point-to-point IP tunnel */ -#define DEV_TYPE_TAP 3 /* ethernet (802.3) tunnel */ +#define DEV_TYPE_TUN 2 /* point-to-point IP tunnel */ +#define DEV_TYPE_TAP 3 /* ethernet (802.3) tunnel */ /* TUN topologies */ -#define TOP_UNDEF 0 -#define TOP_NET30 1 -#define TOP_P2P 2 -#define TOP_SUBNET 3 +#define TOP_UNDEF 0 +#define TOP_NET30 1 +#define TOP_P2P 2 +#define TOP_SUBNET 3 /* * IP and Ethernet protocol structs. For portability, @@ -49,46 +49,45 @@ * native structs. */ -#define OPENVPN_ETH_ALEN 6 /* ethernet address length */ +#define OPENVPN_ETH_ALEN 6 /* ethernet address length */ struct openvpn_ethhdr { uint8_t dest[OPENVPN_ETH_ALEN]; /* destination ethernet addr */ uint8_t source[OPENVPN_ETH_ALEN]; /* source ethernet addr */ -#define OPENVPN_ETH_P_IPV4 0x0800 /* IPv4 protocol */ -#define OPENVPN_ETH_P_IPV6 0x86DD /* IPv6 protocol */ -#define OPENVPN_ETH_P_ARP 0x0806 /* ARP protocol */ -#define OPENVPN_ETH_P_8021Q 0x8100 /* 802.1Q protocol */ +#define OPENVPN_ETH_P_IPV4 0x0800 /* IPv4 protocol */ +#define OPENVPN_ETH_P_IPV6 0x86DD /* IPv6 protocol */ +#define OPENVPN_ETH_P_ARP 0x0806 /* ARP protocol */ +#define OPENVPN_ETH_P_8021Q 0x8100 /* 802.1Q protocol */ uint16_t proto; /* packet type ID field */ }; struct openvpn_8021qhdr { - uint8_t dest[OPENVPN_ETH_ALEN]; /* destination ethernet addr */ - uint8_t source[OPENVPN_ETH_ALEN]; /* source ethernet addr */ + uint8_t dest[OPENVPN_ETH_ALEN]; /* destination ethernet addr = */ + uint8_t source[OPENVPN_ETH_ALEN]; /* source ethernet addr */ - uint16_t tpid; /* 802.1Q Tag Protocol Identifier = */ + uint16_t tpid; /* 802.1Q Tag Protocol Identi= fier */ #define OPENVPN_8021Q_MASK_PCP htons(0xE000) /* mask PCP out of pcp_cfi_vi= d */ #define OPENVPN_8021Q_MASK_CFI htons(0x1000) /* mask CFI out of pcp_cfi_vi= d */ #define OPENVPN_8021Q_MASK_VID htons(0x0FFF) /* mask VID out of pcp_cfi_vi= d */ - uint16_t pcp_cfi_vid; /* bit fields, see IEEE 802.1Q */ - uint16_t proto; /* contained packet type ID field = */ + uint16_t pcp_cfi_vid; /* bit fields, see IEEE 802.1= Q */ + uint16_t proto; /* contained packet type ID f= ield */ }; /* * Size difference between a regular Ethernet II header and an Ethernet II * header with additional IEEE 802.1Q tagging. */ -#define SIZE_ETH_TO_8021Q_HDR (sizeof(struct openvpn_8021qhdr) \ - - sizeof(struct openvpn_ethhdr)) +#define SIZE_ETH_TO_8021Q_HDR (sizeof(struct openvpn_8021qhdr) - sizeof(st= ruct openvpn_ethhdr)) /** Version of IN6_ARE_ADDR_EQUAL that is guaranteed to work for * unaligned access. E.g. Linux uses 32bit compares which are * not safe if the struct is unaligned. */ -#define OPENVPN_IN6_ARE_ADDR_EQUAL(a, b) \ - (memcmp(a, b, sizeof(struct in6_addr)) =3D=3D 0) +#define OPENVPN_IN6_ARE_ADDR_EQUAL(a, b) (memcmp(a, b, sizeof(struct in6_a= ddr)) =3D=3D 0) -struct openvpn_iphdr { +struct openvpn_iphdr +{ #define OPENVPN_IPH_GET_VER(v) (((v) >> 4) & 0x0F) #define OPENVPN_IPH_GET_LEN(v) (((v) & 0x0F) << 2) uint8_t version_len; @@ -102,9 +101,9 @@ uint8_t ttl; -#define OPENVPN_IPPROTO_IGMP 2 /* IGMP protocol */ -#define OPENVPN_IPPROTO_TCP 6 /* TCP protocol */ -#define OPENVPN_IPPROTO_UDP 17 /* UDP protocol */ +#define OPENVPN_IPPROTO_IGMP 2 /* IGMP protocol */ +#define OPENVPN_IPPROTO_TCP 6 /* TCP protocol */ +#define OPENVPN_IPPROTO_UDP 17 /* UDP protocol */ #define OPENVPN_IPPROTO_ICMPV6 58 /* ICMPV6 protocol */ uint8_t protocol; @@ -117,31 +116,33 @@ /* * IPv6 header */ -struct openvpn_ipv6hdr { +struct openvpn_ipv6hdr +{ uint8_t version_prio; uint8_t flow_lbl[3]; uint16_t payload_len; uint8_t nexthdr; uint8_t hop_limit; - struct in6_addr saddr; - struct in6_addr daddr; + struct in6_addr saddr; + struct in6_addr daddr; }; /* * ICMPv6 header */ -struct openvpn_icmp6hdr { -#define OPENVPN_ICMP6_DESTINATION_UNREACHABLE 1 -#define OPENVPN_ND_ROUTER_SOLICIT 133 -#define OPENVPN_ND_ROUTER_ADVERT 134 -#define OPENVPN_ND_NEIGHBOR_SOLICIT 135 -#define OPENVPN_ND_NEIGHBOR_ADVERT 136 -#define OPENVPN_ND_INVERSE_SOLICIT 141 -#define OPENVPN_ND_INVERSE_ADVERT 142 +struct openvpn_icmp6hdr +{ +#define OPENVPN_ICMP6_DESTINATION_UNREACHABLE 1 +#define OPENVPN_ND_ROUTER_SOLICIT 133 +#define OPENVPN_ND_ROUTER_ADVERT 134 +#define OPENVPN_ND_NEIGHBOR_SOLICIT 135 +#define OPENVPN_ND_NEIGHBOR_ADVERT 136 +#define OPENVPN_ND_INVERSE_SOLICIT 141 +#define OPENVPN_ND_INVERSE_ADVERT 142 uint8_t icmp6_type; -#define OPENVPN_ICMP6_DU_NOROUTE 0 -#define OPENVPN_ICMP6_DU_COMMUNICATION_PROHIBTED 1 +#define OPENVPN_ICMP6_DU_NOROUTE 0 +#define OPENVPN_ICMP6_DU_COMMUNICATION_PROHIBTED 1 uint8_t icmp6_code; uint16_t icmp6_cksum; uint8_t icmp6_dataun[4]; @@ -150,7 +151,8 @@ /* * UDP header */ -struct openvpn_udphdr { +struct openvpn_udphdr +{ uint16_t source; uint16_t dest; uint16_t len; @@ -160,23 +162,24 @@ /* * TCP header, per RFC 793. */ -struct openvpn_tcphdr { - uint16_t source; /* source port */ - uint16_t dest; /* destination port */ - uint32_t seq; /* sequence number */ - uint32_t ack_seq; /* acknowledgement number */ +struct openvpn_tcphdr +{ + uint16_t source; /* source port */ + uint16_t dest; /* destination port */ + uint32_t seq; /* sequence number */ + uint32_t ack_seq; /* acknowledgement number */ #define OPENVPN_TCPH_GET_DOFF(d) (((d) & 0xF0) >> 2) uint8_t doff_res; -#define OPENVPN_TCPH_FIN_MASK (1<<0) -#define OPENVPN_TCPH_SYN_MASK (1<<1) -#define OPENVPN_TCPH_RST_MASK (1<<2) -#define OPENVPN_TCPH_PSH_MASK (1<<3) -#define OPENVPN_TCPH_ACK_MASK (1<<4) -#define OPENVPN_TCPH_URG_MASK (1<<5) -#define OPENVPN_TCPH_ECE_MASK (1<<6) -#define OPENVPN_TCPH_CWR_MASK (1<<7) +#define OPENVPN_TCPH_FIN_MASK (1 << 0) +#define OPENVPN_TCPH_SYN_MASK (1 << 1) +#define OPENVPN_TCPH_RST_MASK (1 << 2) +#define OPENVPN_TCPH_PSH_MASK (1 << 3) +#define OPENVPN_TCPH_ACK_MASK (1 << 4) +#define OPENVPN_TCPH_URG_MASK (1 << 5) +#define OPENVPN_TCPH_ECE_MASK (1 << 6) +#define OPENVPN_TCPH_CWR_MASK (1 << 7) uint8_t flags; uint16_t window; @@ -189,9 +192,11 @@ #define OPENVPN_TCPOPT_MAXSEG 2 #define OPENVPN_TCPOLEN_MAXSEG 4 -struct ip_tcp_udp_hdr { +struct ip_tcp_udp_hdr +{ struct openvpn_iphdr ip; - union { + union + { struct openvpn_tcphdr tcp; struct openvpn_udphdr udp; } u; @@ -207,30 +212,36 @@ * subtracting out new words), and "cksum" * is the checksum value to be updated. */ -#define ADJUST_CHECKSUM(acc, cksum) { \ - int _acc =3D acc; \ - _acc +=3D (cksum); \ - if (_acc < 0) { \ - _acc =3D -_acc; \ +#define ADJUST_CHECKSUM(acc, cksum) \ + { \ + int _acc =3D acc; \ + _acc +=3D (cksum); \ + if (_acc < 0) \ + { \ + _acc =3D -_acc; \ _acc =3D (_acc >> 16) + (_acc & 0xffff); \ - _acc +=3D _acc >> 16; \ - (cksum) =3D (uint16_t) ~_acc; \ - } else { \ + _acc +=3D _acc >> 16; \ + (cksum) =3D (uint16_t)~_acc; \ + } \ + else \ + { \ _acc =3D (_acc >> 16) + (_acc & 0xffff); \ - _acc +=3D _acc >> 16; \ - (cksum) =3D (uint16_t) _acc; \ - } \ -} + _acc +=3D _acc >> 16; \ + (cksum) =3D (uint16_t)_acc; \ + } \ + } -#define ADD_CHECKSUM_32(acc, u32) { \ - acc +=3D (u32) & 0xffff; \ - acc +=3D (u32) >> 16; \ -} +#define ADD_CHECKSUM_32(acc, u32) \ + { \ + acc +=3D (u32) & 0xffff; \ + acc +=3D (u32) >> 16; \ + } -#define SUB_CHECKSUM_32(acc, u32) { \ - acc -=3D (u32) & 0xffff; \ - acc -=3D (u32) >> 16; \ -} +#define SUB_CHECKSUM_32(acc, u32) \ + { \ + acc -=3D (u32) & 0xffff; \ + acc -=3D (u32) >> 16; \ + } /* * This returns an ip protocol version of packet inside tun @@ -245,7 +256,7 @@ if (tunnel_type =3D=3D DEV_TYPE_TUN) { *ip_hdr_offset =3D 0; - if (likely(BLEN(buf) >=3D (int) sizeof(struct openvpn_iphdr))) + if (likely(BLEN(buf) >=3D (int)sizeof(struct openvpn_iphdr))) { ip_ver =3D OPENVPN_IPH_GET_VER(*BPTR(buf)); } @@ -256,7 +267,7 @@ /* for tap get ip version from eth header */ if (likely(BLEN(buf) >=3D *ip_hdr_offset)) { - const struct openvpn_ethhdr *eh =3D (const struct openvpn_ethh= dr *) BPTR(buf); + const struct openvpn_ethhdr *eh =3D (const struct openvpn_ethh= dr *)BPTR(buf); uint16_t proto =3D ntohs(eh->proto); if (proto =3D=3D OPENVPN_ETH_P_IPV6) { @@ -293,17 +304,12 @@ * @param proto next - header or IP protocol of the packet * @return The calculated checksum in host order */ -uint16_t -ip_checksum(const sa_family_t af, const uint8_t *payload, const int len_pa= yload, - const uint8_t *src_addr, const uint8_t *dest_addr, const int = proto); +uint16_t ip_checksum(const sa_family_t af, const uint8_t *payload, const i= nt len_payload, + const uint8_t *src_addr, const uint8_t *dest_addr, co= nst int proto); #ifdef PACKET_TRUNCATION_CHECK -void ipv4_packet_size_verify(const uint8_t *data, - const int size, - const int tunnel_type, - const char - *prefix, - counter_type *errors); +void ipv4_packet_size_verify(const uint8_t *data, const int size, const in= t tunnel_type, + const char *prefix, counter_type *errors); #endif diff --git a/src/openvpn/proxy.c b/src/openvpn/proxy.c index 393abb4..054cc79 100644 --- a/src/openvpn/proxy.c +++ b/src/openvpn/proxy.c @@ -39,11 +39,10 @@ #include "memdbg.h" #include "forward.h" -#define UP_TYPE_PROXY "HTTP Proxy" +#define UP_TYPE_PROXY "HTTP Proxy" struct http_proxy_options * -init_http_proxy_options_once(struct http_proxy_options **hpo, - struct gc_arena *gc) +init_http_proxy_options_once(struct http_proxy_options **hpo, struct gc_ar= ena *gc) { if (!*hpo) { @@ -59,13 +58,8 @@ static struct user_pass static_proxy_user_pass; static bool -recv_line(socket_descriptor_t sd, - char *buf, - int len, - const int timeout_sec, - const bool verbose, - struct buffer *lookahead, - volatile int *signal_received) +recv_line(socket_descriptor_t sd, char *buf, int len, const int timeout_se= c, const bool verbose, + struct buffer *lookahead, volatile int *signal_received) { struct buffer la; int lastc =3D 0; @@ -161,7 +155,8 @@ { if (verbose) { - msg(D_LINK_ERRORS | M_ERRNO, "recv_line: Non-ASCII cha= racter (%d) read on recv()", (int)c); + msg(D_LINK_ERRORS | M_ERRNO, + "recv_line: Non-ASCII character (%d) read on recv(= )", (int)c); } *lookahead =3D la; return false; @@ -190,11 +185,10 @@ } static bool -send_line(socket_descriptor_t sd, - const char *buf) +send_line(socket_descriptor_t sd, const char *buf) { const ssize_t size =3D send(sd, buf, strlen(buf), MSG_NOSIGNAL); - if (size !=3D (ssize_t) strlen(buf)) + if (size !=3D (ssize_t)strlen(buf)) { msg(D_LINK_ERRORS | M_ERRNO, "send_line: TCP port write failed on = send()"); return false; @@ -203,8 +197,7 @@ } static bool -send_line_crlf(socket_descriptor_t sd, - const char *src) +send_line_crlf(socket_descriptor_t sd, const char *src) { bool ret; @@ -228,7 +221,7 @@ uint8_t *ret =3D NULL; char *b64out =3D NULL; ASSERT(openvpn_base64_encode((const void *)str, src_len, &b64out) >=3D= 0); - ret =3D (uint8_t *) string_alloc(b64out, gc); + ret =3D (uint8_t *)string_alloc(b64out, gc); free(b64out); return ret; } @@ -240,8 +233,7 @@ } static const char * -username_password_as_base64(const struct http_proxy_info *p, - struct gc_arena *gc) +username_password_as_base64(const struct http_proxy_info *p, struct gc_are= na *gc) { struct buffer out =3D alloc_buf_gc(strlen(p->up.username) + strlen(p->= up.password) + 2, gc); ASSERT(strlen(p->up.username) > 0); @@ -285,10 +277,7 @@ { flags |=3D GET_USER_PASS_INLINE_CREDS; } - get_user_pass(&static_proxy_user_pass, - auth_file, - UP_TYPE_PROXY, - flags); + get_user_pass(&static_proxy_user_pass, auth_file, UP_TYPE_PROXY, f= lags); static_proxy_user_pass.nocache =3D p->options.nocache; protect_user_pass(&static_proxy_user_pass); } @@ -325,9 +314,7 @@ * Consumes all headers. */ static int -get_proxy_authenticate(socket_descriptor_t sd, - int timeout, - char **data, +get_proxy_authenticate(socket_descriptor_t sd, int timeout, char **data, volatile int *signal_received) { char buf[256]; @@ -347,22 +334,22 @@ } if (ret =3D=3D HTTP_AUTH_NONE && !strncmp(buf, "Proxy-Authenticate= : ", 20)) { - if (!strncmp(buf+20, "Basic ", 6)) + if (!strncmp(buf + 20, "Basic ", 6)) { msg(D_PROXY, "PROXY AUTH BASIC: '%s'", buf); - *data =3D string_alloc(buf+26, NULL); + *data =3D string_alloc(buf + 26, NULL); ret =3D HTTP_AUTH_BASIC; } #if PROXY_DIGEST_AUTH - else if (!strncmp(buf+20, "Digest ", 7)) + else if (!strncmp(buf + 20, "Digest ", 7)) { msg(D_PROXY, "PROXY AUTH DIGEST: '%s'", buf); - *data =3D string_alloc(buf+27, NULL); + *data =3D string_alloc(buf + 27, NULL); ret =3D HTTP_AUTH_DIGEST; } #endif #if NTLM - else if (!strncmp(buf+20, "NTLM", 4)) + else if (!strncmp(buf + 20, "NTLM", 4)) { msg(D_PROXY, "PROXY AUTH NTLM: '%s'", buf); *data =3D NULL; @@ -385,18 +372,16 @@ * Return true on success, or false on parse failure. */ static bool -get_key_value(const char *str, /* source string */ - char *key, /* key stored here */ - char *value, /* value stored here */ - int max_key_len, - int max_value_len, - const char **endptr) /* next search position */ +get_key_value(const char *str, /* = source string */ + char *key, /* = key stored here */ + char *value, /* = value stored here */ + int max_key_len, int max_value_len, const char **endptr) /* = next search position */ { int c; bool starts_with_quote =3D false; bool escape =3D false; - for (c =3D max_key_len-1; (*str && (*str !=3D '=3D') && c--); ) + for (c =3D max_key_len - 1; (*str && (*str !=3D '=3D') && c--);) { *key++ =3D *str++; } @@ -415,7 +400,7 @@ starts_with_quote =3D true; } - for (c =3D max_value_len-1; *str && c--; str++) + for (c =3D max_value_len - 1; *str && c--; str++) { switch (*str) { @@ -529,7 +514,8 @@ #if NTLM else if (!strcmp(o->auth_method_string, "ntlm")) { - msg(M_WARN, "NTLM v1 authentication has been removed in OpenVP= N 2.7. Will try to use NTLM v2 authentication."); + msg(M_WARN, + "NTLM v1 authentication has been removed in OpenVPN 2.7. W= ill try to use NTLM v2 authentication."); p->auth_method =3D HTTP_AUTH_NTLM2; } else if (!strcmp(o->auth_method_string, "ntlm2")) @@ -539,8 +525,7 @@ #endif else { - msg(M_FATAL, "ERROR: unknown HTTP authentication method: '%s'", - o->auth_method_string); + msg(M_FATAL, "ERROR: unknown HTTP authentication method: '%s'"= , o->auth_method_string); } } @@ -555,7 +540,8 @@ #if !NTLM if (p->auth_method =3D=3D HTTP_AUTH_NTLM2) { - msg(M_FATAL, "Sorry, this version of " PACKAGE_NAME " was built wi= thout NTLM Proxy support."); + msg(M_FATAL, + "Sorry, this version of " PACKAGE_NAME " was built without NTL= M Proxy support."); } #endif @@ -570,10 +556,9 @@ } static bool -add_proxy_headers(struct http_proxy_info *p, - socket_descriptor_t sd, /* already open to proxy */ - const char *host /* openvpn server remote */ - ) +add_proxy_headers(struct http_proxy_info *p, socket_descriptor_t sd, /* al= ready open to proxy */ + const char *host /* op= envpn server remote */ +) { char buf[512]; int i; @@ -584,12 +569,11 @@ * If content is NULL the whole header is in name * Also remember if we already sent a Host: header */ - for (i =3D 0; i < MAX_CUSTOM_HTTP_HEADER && p->options.custom_headers= [i].name; i++) + for (i =3D 0; i < MAX_CUSTOM_HTTP_HEADER && p->options.custom_headers[= i].name; i++) { if (p->options.custom_headers[i].content) { - snprintf(buf, sizeof(buf), "%s: %s", - p->options.custom_headers[i].name, + snprintf(buf, sizeof(buf), "%s: %s", p->options.custom_headers= [i].name, p->options.custom_headers[i].content); if (!strcasecmp(p->options.custom_headers[i].name, "Host")) { @@ -598,8 +582,7 @@ } else { - snprintf(buf, sizeof(buf), "%s", - p->options.custom_headers[i].name); + snprintf(buf, sizeof(buf), "%s", p->options.custom_headers[i].= name); if (!strncasecmp(p->options.custom_headers[i].name, "Host:", 5= )) { host_header_sent =3D true; @@ -626,8 +609,7 @@ /* send User-Agent string if provided */ if (p->options.user_agent) { - snprintf(buf, sizeof(buf), "User-Agent: %s", - p->options.user_agent); + snprintf(buf, sizeof(buf), "User-Agent: %s", p->options.user_agent= ); msg(D_PROXY, "Send to HTTP proxy: '%s'", buf); if (!send_line_crlf(sd, buf)) { @@ -641,11 +623,10 @@ bool establish_http_proxy_passthru(struct http_proxy_info *p, - socket_descriptor_t sd, /* already open to = proxy */ - const char *host, /* openvpn server r= emote */ - const char *port, /* openvpn server= port */ - struct event_timeout *server_poll_timeout, - struct buffer *lookahead, + socket_descriptor_t sd, /* already open to p= roxy */ + const char *host, /* openvpn server re= mote */ + const char *port, /* openvpn server po= rt */ + struct event_timeout *server_poll_timeout, s= truct buffer *lookahead, struct signal_info *sig_info) { struct gc_arena gc =3D gc_new(); @@ -657,8 +638,7 @@ volatile int *signal_received =3D &sig_info->signal_received; /* get user/pass if not previously given */ - if (p->auth_method =3D=3D HTTP_AUTH_BASIC - || p->auth_method =3D=3D HTTP_AUTH_DIGEST + if (p->auth_method =3D=3D HTTP_AUTH_BASIC || p->auth_method =3D=3D HTT= P_AUTH_DIGEST || p->auth_method =3D=3D HTTP_AUTH_NTLM2) { get_user_pass_http(p, false); @@ -670,7 +650,8 @@ unprotect_user_pass(&p->up); } - /* are we being called again after getting the digest server nonce in = the previous transaction? */ + /* are we being called again after getting the digest server nonce in = the previous transaction? + */ if (p->auth_method =3D=3D HTTP_AUTH_DIGEST && p->proxy_authenticate) { nparms =3D 1; @@ -679,10 +660,7 @@ else { /* format HTTP CONNECT message */ - snprintf(buf, sizeof(buf), "CONNECT %s:%s HTTP/%s", - host, - port, - p->options.http_version); + snprintf(buf, sizeof(buf), "CONNECT %s:%s HTTP/%s", host, port, p-= >options.http_version); msg(D_PROXY, "Send to HTTP proxy: '%s'", buf); @@ -723,8 +701,7 @@ goto error; } - snprintf(buf, sizeof(buf), "Proxy-Authorization: NTLM %s", - ntlm_phase_1(p, &gc)); + snprintf(buf, sizeof(buf), "Proxy-Authorization: NTLM %s",= ntlm_phase_1(p, &gc)); msg(D_PROXY, "Attempting NTLM Proxy-Authorization phase 1"= ); dmsg(D_SHOW_KEYS, "Send to HTTP proxy: '%s'", buf); if (!send_line_crlf(sd, buf)) @@ -748,7 +725,8 @@ } /* receive reply from proxy */ - if (!recv_line(sd, buf, sizeof(buf), get_server_poll_remaining_tim= e(server_poll_timeout), true, NULL, signal_received)) + if (!recv_line(sd, buf, sizeof(buf), get_server_poll_remaining_tim= e(server_poll_timeout), + true, NULL, signal_received)) { goto error; } @@ -760,7 +738,6 @@ /* parse return string */ nparms =3D sscanf(buf, "%*s %d", &status); - } /* check for a "407 Proxy Authentication Required" response */ @@ -779,7 +756,9 @@ char buf2[512]; while (true) { - if (!recv_line(sd, buf, sizeof(buf), get_server_poll_remai= ning_time(server_poll_timeout), true, NULL, signal_received)) + if (!recv_line(sd, buf, sizeof(buf), + get_server_poll_remaining_time(server_poll_= timeout), true, NULL, + signal_received)) { goto error; } @@ -810,9 +789,7 @@ /* now send the phase 3 reply */ /* format HTTP CONNECT message */ - snprintf(buf, sizeof(buf), "CONNECT %s:%s HTTP/%s", - host, - port, + snprintf(buf, sizeof(buf), "CONNECT %s:%s HTTP/%s", host, port, p->options.http_version); msg(D_PROXY, "Send to HTTP proxy: '%s'", buf); @@ -841,7 +818,8 @@ const char *np3 =3D ntlm_phase_3(p, buf2, &gc); if (!np3) { - msg(D_PROXY, "NTLM Proxy-Authorization phase 3 failed:= received corrupted data from proxy server"); + msg(D_PROXY, + "NTLM Proxy-Authorization phase 3 failed: received= corrupted data from proxy server"); goto error; } snprintf(buf, sizeof(buf), "Proxy-Authorization: NTLM %s",= np3); @@ -860,7 +838,9 @@ } /* receive reply from proxy */ - if (!recv_line(sd, buf, sizeof(buf), get_server_poll_remaining= _time(server_poll_timeout), true, NULL, signal_received)) + if (!recv_line(sd, buf, sizeof(buf), + get_server_poll_remaining_time(server_poll_time= out), true, NULL, + signal_received)) { goto error; } @@ -904,7 +884,7 @@ if (!realm || !nonce) { msg(D_LINK_ERRORS, "HTTP proxy: digest auth failed, ma= lformed response " - "from server: realm=3D or nonce=3D missing" ); + "from server: realm=3D or nonce=3D = missing"); goto error; } @@ -914,38 +894,21 @@ /* build the digest response */ - snprintf(uri, sizeof(uri), "%s:%s", - host, - port); + snprintf(uri, sizeof(uri), "%s:%s", host, port); if (opaque) { - const int len =3D strlen(opaque)+16; + const int len =3D strlen(opaque) + 16; opaque_kv =3D gc_malloc(len, false, &gc); snprintf(opaque_kv, len, ", opaque=3D\"%s\"", opaque); } - DigestCalcHA1(algor, - username, - realm, - password, - nonce, - (char *)cnonce, - session_key); - DigestCalcResponse(session_key, - nonce, - nonce_count, - (char *)cnonce, - qop, - http_method, - uri, - NULL, - response); + DigestCalcHA1(algor, username, realm, password, nonce, (ch= ar *)cnonce, session_key); + DigestCalcResponse(session_key, nonce, nonce_count, (char = *)cnonce, qop, + http_method, uri, NULL, response); /* format HTTP CONNECT message */ - snprintf(buf, sizeof(buf), "%s %s HTTP/%s", - http_method, - uri, + snprintf(buf, sizeof(buf), "%s %s HTTP/%s", http_method, u= ri, p->options.http_version); msg(D_PROXY, "Send to HTTP proxy: '%s'", buf); @@ -963,17 +926,10 @@ } /* send digest response */ - int sret =3D snprintf(buf, sizeof(buf), "Proxy-Authorizati= on: Digest username=3D\"%s\", realm=3D\"%s\", nonce=3D\"%s\", uri=3D\"%s\",= qop=3D%s, nc=3D%s, cnonce=3D\"%s\", response=3D\"%s\"%s", - username, - realm, - nonce, - uri, - qop, - nonce_count, - cnonce, - response, - opaque_kv - ); + int sret =3D snprintf( + buf, sizeof(buf), + "Proxy-Authorization: Digest username=3D\"%s\", realm= =3D\"%s\", nonce=3D\"%s\", uri=3D\"%s\", qop=3D%s, nc=3D%s, cnonce=3D\"%s\"= , response=3D\"%s\"%s", + username, realm, nonce, uri, qop, nonce_count, cnonce,= response, opaque_kv); if (sret >=3D sizeof(buf)) { goto error; @@ -992,7 +948,9 @@ secure_memzero(buf, sizeof(buf)); /* receive reply from proxy */ - if (!recv_line(sd, buf, sizeof(buf), get_server_poll_remai= ning_time(server_poll_timeout), true, NULL, signal_received)) + if (!recv_line(sd, buf, sizeof(buf), + get_server_poll_remaining_time(server_poll_= timeout), true, NULL, + signal_received)) { goto error; } @@ -1017,10 +975,8 @@ { /* figure out what kind of authentication the proxy needs */ char *pa =3D NULL; - const int method =3D get_proxy_authenticate(sd, - get_server_poll_rema= ining_time(server_poll_timeout), - &pa, - signal_received); + const int method =3D get_proxy_authenticate( + sd, get_server_poll_remaining_time(server_poll_timeout), &= pa, signal_received); if (method !=3D HTTP_AUTH_NONE) { if (pa) @@ -1029,7 +985,8 @@ } if (p->options.auth_retry =3D=3D PAR_NCT && method =3D=3D = HTTP_AUTH_BASIC) { - msg(D_PROXY, "HTTP proxy: support for basic auth and o= ther cleartext proxy auth methods is disabled"); + msg(D_PROXY, + "HTTP proxy: support for basic auth and other clea= rtext proxy auth methods is disabled"); free(pa); goto error; } @@ -1040,7 +997,8 @@ } else { - msg(D_PROXY, "HTTP proxy: do not recognize the authenticat= ion method required by proxy"); + msg(D_PROXY, + "HTTP proxy: do not recognize the authentication metho= d required by proxy"); free(pa); goto error; } @@ -1069,7 +1027,8 @@ /* SUCCESS */ /* receive line from proxy and discard */ - if (!recv_line(sd, NULL, 0, get_server_poll_remaining_time(server_poll= _timeout), true, NULL, signal_received)) + if (!recv_line(sd, NULL, 0, get_server_poll_remaining_time(server_poll= _timeout), true, NULL, + signal_received)) { goto error; } @@ -1082,7 +1041,8 @@ { } - /* reset queried_creds so that we don't think that the next creds requ= est is due to an auth error */ + /* reset queried_creds so that we don't think that the next creds requ= est is due to an auth + * error */ p->queried_creds =3D false; #if 0 diff --git a/src/openvpn/proxy.h b/src/openvpn/proxy.h index fcca1ab..be16d83 100644 --- a/src/openvpn/proxy.h +++ b/src/openvpn/proxy.h @@ -34,19 +34,21 @@ #define HTTP_AUTH_NTLM2 4 #define HTTP_AUTH_N 5 /* number of HTTP_AUTH methods */ -struct http_custom_header { +struct http_custom_header +{ const char *name; const char *content; }; #define MAX_CUSTOM_HTTP_HEADER 10 -struct http_proxy_options { +struct http_proxy_options +{ const char *server; const char *port; -#define PAR_NO 0 /* don't support any auth retries */ -#define PAR_ALL 1 /* allow all proxy auth protocols */ -#define PAR_NCT 2 /* disable cleartext proxy auth protocols */ +#define PAR_NO 0 /* don't support any auth retries */ +#define PAR_ALL 1 /* allow all proxy auth protocols */ +#define PAR_NCT 2 /* disable cleartext proxy auth protocols */ int auth_retry; const char *auth_method_string; @@ -56,11 +58,13 @@ const char *user_agent; struct http_custom_header custom_headers[MAX_CUSTOM_HTTP_HEADER]; bool inline_creds; /* auth_file_up is inline credentials */ - bool first_time; /* indicates if we need to wipe user creds at the fir= st iteration of the main loop */ + bool first_time; /* indicates if we need to wipe user creds at the f= irst iteration of the main + loop */ bool nocache; }; -struct http_proxy_info { +struct http_proxy_info +{ bool defined; int auth_method; struct http_proxy_options options; @@ -77,12 +81,11 @@ void http_proxy_close(struct http_proxy_info *hp); bool establish_http_proxy_passthru(struct http_proxy_info *p, - socket_descriptor_t sd, /* already ope= n to proxy */ - const char *host, /* openvpn ser= ver remote */ - const char *port, /* openvpn s= erver port */ + socket_descriptor_t sd, /* already open= to proxy */ + const char *host, /* openvpn serv= er remote */ + const char *port, /* openvpn serv= er port */ struct event_timeout *server_poll_timeo= ut, - struct buffer *lookahead, - struct signal_info *sig_info); + struct buffer *lookahead, struct signal= _info *sig_info); uint8_t *make_base64_string2(const uint8_t *str, int str_len, struct gc_ar= ena *gc); diff --git a/src/openvpn/ps.c b/src/openvpn/ps.c index 6c6e5ea..eae03e3 100644 --- a/src/openvpn/ps.c +++ b/src/openvpn/ps.c @@ -46,24 +46,25 @@ #define COMMAND_EXIT 11 /* Response codes for background -> foreground communication */ -#define RESPONSE_INIT_SUCCEEDED 20 -#define RESPONSE_INIT_FAILED 21 +#define RESPONSE_INIT_SUCCEEDED 20 +#define RESPONSE_INIT_FAILED 21 /* * Return values for proxy_connection_io functions */ -#define IOSTAT_EAGAIN_ON_READ 0 /* recv returned EAGAIN */ -#define IOSTAT_EAGAIN_ON_WRITE 1 /* send returned EAGAIN */ -#define IOSTAT_READ_ERROR 2 /* the other end of our read socket (pc)= was closed */ -#define IOSTAT_WRITE_ERROR 3 /* the other end of our write socket (pc= ->counterpart) was closed */ -#define IOSTAT_GOOD 4 /* nothing to report */ +#define IOSTAT_EAGAIN_ON_READ 0 /* recv returned EAGAIN */ +#define IOSTAT_EAGAIN_ON_WRITE 1 /* send returned EAGAIN */ +#define IOSTAT_READ_ERROR 2 /* the other end of our read socket (pc) = was closed */ +#define IOSTAT_WRITE_ERROR 3 /* the other end of our write socket (pc-= >counterpart) was closed */ +#define IOSTAT_GOOD 4 /* nothing to report */ /* * A foreign (non-OpenVPN) connection we are proxying, * usually HTTPS */ -struct proxy_connection { +struct proxy_connection +{ bool defined; struct proxy_connection *next; struct proxy_connection *counterpart; @@ -156,11 +157,11 @@ static int send_control(const socket_descriptor_t fd, int code) { - unsigned char c =3D (unsigned char) code; + unsigned char c =3D (unsigned char)code; const ssize_t size =3D write(fd, &c, sizeof(c)); if (size =3D=3D sizeof(c)) { - return (int) size; + return (int)size; } else { @@ -182,9 +183,7 @@ * send commands, data, and file descriptors to the background process. */ static void -port_share_sendmsg(const socket_descriptor_t sd, - const char command, - const struct buffer *head, +port_share_sendmsg(const socket_descriptor_t sd, const char command, const= struct buffer *head, const socket_descriptor_t sd_send) { if (socket_defined(sd)) @@ -196,8 +195,7 @@ char cmd; ssize_t status; - dmsg(D_PS_PROXY_DEBUG, "PORT SHARE: sendmsg sd=3D%d len=3D%d", - (int)sd_send, + dmsg(D_PS_PROXY_DEBUG, "PORT SHARE: sendmsg sd=3D%d len=3D%d", (in= t)sd_send, head ? BLEN(head) : -1); CLEAR(mesg); @@ -218,7 +216,7 @@ mesg.msg_iov =3D iov; mesg.msg_controllen =3D cmsg_size(); - mesg.msg_control =3D (char *) malloc(mesg.msg_controllen); + mesg.msg_control =3D (char *)malloc(mesg.msg_controllen); check_malloc_return(mesg.msg_control); mesg.msg_flags =3D 0; @@ -240,9 +238,9 @@ status =3D sendmsg(sd, &mesg, MSG_NOSIGNAL); if (status =3D=3D -1) { - msg(M_WARN|M_ERRNO, "PORT SHARE: sendmsg failed -- unable to c= ommunicate with background process (%d,%d,%d,%d)", - sd, sd_send, sd_null[0], sd_null[1] - ); + msg(M_WARN | M_ERRNO, + "PORT SHARE: sendmsg failed -- unable to communicate with = background process (%d,%d,%d,%d)", + sd, sd_send, sd_null[0], sd_null[1]); } close_socket_if_defined(sd_null[0]); @@ -345,13 +343,13 @@ slen =3D sizeof(from.addr); dlen =3D sizeof(to.addr); - if (!getpeername(pc->sd, (struct sockaddr *) &from.addr.sa, &slen) - && !getsockname(cp->sd, (struct sockaddr *) &to.addr.sa, &dlen)) + if (!getpeername(pc->sd, (struct sockaddr *)&from.addr.sa, &slen) + && !getsockname(cp->sd, (struct sockaddr *)&to.addr.sa, &dlen)) { const char *f =3D print_openvpn_sockaddr(&from, &gc); const char *t =3D print_openvpn_sockaddr(&to, &gc); - fnlen =3D strlen(journal_dir) + strlen(t) + 2; - jfn =3D (char *) malloc(fnlen); + fnlen =3D strlen(journal_dir) + strlen(t) + 2; + jfn =3D (char *)malloc(fnlen); check_malloc_return(jfn); snprintf(jfn, fnlen, "%s/%s", journal_dir, t); dmsg(D_PS_PROXY_DEBUG, "PORT SHARE PROXY: client origin %s -> %s",= jfn, f); @@ -367,7 +365,7 @@ } else { - msg(M_WARN|M_ERRNO, "PORT SHARE: unable to write journal file = in %s", jfn); + msg(M_WARN | M_ERRNO, "PORT SHARE: unable to write journal fil= e in %s", jfn); free(jfn); } } @@ -393,11 +391,13 @@ } static inline void -proxy_connection_io_requeue(struct proxy_connection *pc, const int rwflags= _new, struct event_set *es) +proxy_connection_io_requeue(struct proxy_connection *pc, const int rwflags= _new, + struct event_set *es) { if (socket_defined(pc->sd) && pc->rwflags !=3D rwflags_new) { - /*dmsg (D_PS_PROXY_DEBUG, "PORT SHARE PROXY: requeue[%d] rwflags= =3D%d", (int)pc->sd, rwflags_new);*/ + /*dmsg (D_PS_PROXY_DEBUG, "PORT SHARE PROXY: requeue[%d] rwflags= =3D%d", (int)pc->sd, + * rwflags_new);*/ event_ctl(es, pc->sd, rwflags_new, (void *)pc); pc->rwflags =3D rwflags_new; } @@ -411,12 +411,9 @@ * on success and false on failure to connect to server. */ static bool -proxy_entry_new(struct proxy_connection **list, - struct event_set *es, - const struct openvpn_sockaddr server_addr, - const socket_descriptor_t sd_client, - struct buffer *initial_data, - const char *journal_dir) +proxy_entry_new(struct proxy_connection **list, struct event_set *es, + const struct openvpn_sockaddr server_addr, const socket_de= scriptor_t sd_client, + struct buffer *initial_data, const char *journal_dir) { socket_descriptor_t sd_server; int status; @@ -426,7 +423,7 @@ /* connect to port share server */ if ((sd_server =3D socket(server_addr.addr.sa.sa_family, SOCK_STREAM, = IPPROTO_TCP)) < 0) { - msg(M_WARN|M_ERRNO, "PORT SHARE PROXY: cannot create socket"); + msg(M_WARN | M_ERRNO, "PORT SHARE PROXY: cannot create socket"); return false; } status =3D openvpn_connect(sd_server, &server_addr.addr.sa, 5, NULL); @@ -472,11 +469,12 @@ journal_add(journal_dir, pc, cp); } - dmsg(D_PS_PROXY_DEBUG, "PORT SHARE PROXY: NEW CONNECTION [c=3D%d s=3D%= d]", (int)sd_client, (int)sd_server); + dmsg(D_PS_PROXY_DEBUG, "PORT SHARE PROXY: NEW CONNECTION [c=3D%d s=3D%= d]", (int)sd_client, + (int)sd_server); /* set initial i/o states */ proxy_connection_io_requeue(pc, EVENT_READ, es); - proxy_connection_io_requeue(cp, EVENT_READ|EVENT_WRITE, es); + proxy_connection_io_requeue(cp, EVENT_READ | EVENT_WRITE, es); return true; } @@ -488,12 +486,9 @@ * exit, true otherwise. */ static bool -control_message_from_parent(const socket_descriptor_t sd_control, - struct proxy_connection **list, - struct event_set *es, - const struct openvpn_sockaddr server_addr, - const int max_initial_buf, - const char *journal_dir) +control_message_from_parent(const socket_descriptor_t sd_control, struct p= roxy_connection **list, + struct event_set *es, const struct openvpn_soc= kaddr server_addr, + const int max_initial_buf, const char *journal= _dir) { /* this buffer needs to be large enough to handle the largest buffer * that might be returned by the link_socket_read call in read_incomin= g_link. */ @@ -516,7 +511,7 @@ mesg.msg_iovlen =3D 2; mesg.msg_controllen =3D cmsg_size(); - mesg.msg_control =3D (char *) malloc(mesg.msg_controllen); + mesg.msg_control =3D (char *)malloc(mesg.msg_controllen); check_malloc_return(mesg.msg_control); mesg.msg_flags =3D 0; @@ -530,10 +525,8 @@ status =3D recvmsg(sd_control, &mesg, MSG_NOSIGNAL); if (status !=3D -1) { - if (h =3D=3D NULL - || h->cmsg_len !=3D CMSG_LEN(sizeof(socket_descriptor_t)) - || h->cmsg_level !=3D SOL_SOCKET - || h->cmsg_type !=3D SCM_RIGHTS) + if (h =3D=3D NULL || h->cmsg_len !=3D CMSG_LEN(sizeof(socket_descr= iptor_t)) + || h->cmsg_level !=3D SOL_SOCKET || h->cmsg_type !=3D SCM_RIGH= TS) { msg(M_WARN, "PORT SHARE PROXY: received unknown message"); } @@ -546,12 +539,7 @@ if (status >=3D 2 && command =3D=3D COMMAND_REDIRECT) { buf.len =3D status - 1; - if (proxy_entry_new(list, - es, - server_addr, - received_fd, - &buf, - journal_dir)) + if (proxy_entry_new(list, es, server_addr, received_fd, &b= uf, journal_dir)) { CLEAR(buf); /* we gave the buffer to proxy_entry_new */ } @@ -610,7 +598,8 @@ *bytes_sent +=3D status; if (status !=3D pc->buf.len) { - dmsg(D_PS_PROXY_DEBUG, "PORT SHARE PROXY: partial write[%d], t= ried=3D%d got=3D%d", (int)sd, pc->buf.len, status); + dmsg(D_PS_PROXY_DEBUG, "PORT SHARE PROXY: partial write[%d], t= ried=3D%d got=3D%d", (int)sd, + pc->buf.len, status); buf_advance(&pc->buf, status); return IOSTAT_EAGAIN_ON_WRITE; } @@ -698,9 +687,7 @@ * in the proxied connection. */ static int -proxy_connection_io_dispatch(struct proxy_connection *pc, - const int rwflags, - struct event_set *es) +proxy_connection_io_dispatch(struct proxy_connection *pc, const int rwflag= s, struct event_set *es) { const int max_transfer_per_iteration =3D 10000; struct proxy_connection *cp =3D pc->counterpart; @@ -739,10 +726,8 @@ * This is the main function for the port share proxy background process. */ static void -port_share_proxy(const struct openvpn_sockaddr hostaddr, - const socket_descriptor_t sd_control, - const int max_initial_buf, - const char *journal_dir) +port_share_proxy(const struct openvpn_sockaddr hostaddr, const socket_desc= riptor_t sd_control, + const int max_initial_buf, const char *journal_dir) { if (send_control(sd_control, RESPONSE_INIT_SUCCEEDED) >=3D 0) { @@ -776,7 +761,8 @@ const struct event_set_return *e =3D &esr[i]; if (e->arg =3D=3D sd_control_marker) { - if (!control_message_from_parent(sd_control, &list= , es, hostaddr, max_initial_buf, journal_dir)) + if (!control_message_from_parent(sd_control, &list= , es, hostaddr, + max_initial_buf, = journal_dir)) { goto done; } @@ -814,9 +800,7 @@ * share proxy. */ struct port_share * -port_share_open(const char *host, - const char *port, - const int max_initial_buf, +port_share_open(const char *host, const char *port, const int max_initial_= buf, const char *journal_dir) { pid_t pid; @@ -834,9 +818,9 @@ * Get host's IP address */ - status =3D openvpn_getaddrinfo(GETADDR_RESOLVE|GETADDR_FATAL, - host, port, 0, NULL, AF_UNSPEC, &ai); - ASSERT(status=3D=3D0); + status =3D + openvpn_getaddrinfo(GETADDR_RESOLVE | GETADDR_FATAL, host, port, 0= , NULL, AF_UNSPEC, &ai); + ASSERT(status =3D=3D 0); ASSERT(sizeof(hostaddr.addr) >=3D ai->ai_addrlen); memcpy(&hostaddr.addr.sa, ai->ai_addr, ai->ai_addrlen); freeaddrinfo(ai); @@ -982,7 +966,7 @@ bool is_openvpn_protocol(const struct buffer *buf) { - const unsigned char *p =3D (const unsigned char *) BSTR(buf); + const unsigned char *p =3D (const unsigned char *)BSTR(buf); const int len =3D BLEN(buf); if (len >=3D 3) { @@ -1004,7 +988,7 @@ * We don't do the 2 byte check for tls-crypt-v2 because it is= very * unrealistic to have only 2 bytes available. */ - return (plen >=3D 336 && plen < (1024 + 255)); + return (plen >=3D 336 && plen < (1024 + 255)); } else { diff --git a/src/openvpn/ps.h b/src/openvpn/ps.h index c6f5633..e28c403 100644 --- a/src/openvpn/ps.h +++ b/src/openvpn/ps.h @@ -29,7 +29,8 @@ #include "buffer.h" #include "ssl.h" -struct port_share { +struct port_share +{ /* Foreground's socket to background process */ socket_descriptor_t foreground_fd; @@ -39,9 +40,7 @@ extern struct port_share *port_share; -struct port_share *port_share_open(const char *host, - const char *port, - const int max_initial_buf, +struct port_share *port_share_open(const char *host, const char *port, con= st int max_initial_buf, const char *journal_dir); void port_share_close(struct port_share *ps); diff --git a/src/openvpn/push.c b/src/openvpn/push.c index 3013100..889b268 100644 --- a/src/openvpn/push.c +++ b/src/openvpn/push.c @@ -95,7 +95,7 @@ case AR_INTERACT: ssl_purge_auth(false); - /* Intentional [[fallthrough]]; */ + /* Intentional [[fallthrough]]; */ case AR_NOINTERACT: /* SOFT-SIGTUSR1 -- Auth failure error */ @@ -114,20 +114,19 @@ /* * Save the dynamic-challenge text even when management is defined */ - if (authfail_extended - && buf_string_match_head_str(&buf, "CRV1:") && BLEN(&buf)) + if (authfail_extended && buf_string_match_head_str(&buf, "CRV1:") && B= LEN(&buf)) { ssl_put_auth_challenge(BSTR(&buf)); } #endif /* ifdef ENABLE_MANAGEMENT */ - } /* * Act on received restart message from server */ void -server_pushed_signal(struct context *c, const struct buffer *buffer, const= bool restart, const int adv) +server_pushed_signal(struct context *c, const struct buffer *buffer, const= bool restart, + const int adv) { if (c->options.pull) { @@ -250,7 +249,8 @@ } else { - msg(D_PUSH_ERRORS, "WARNING: Received INFO command is too long= , won't notify management client."); + msg(D_PUSH_ERRORS, + "WARNING: Received INFO command is too long, won't notify = management client."); } gc_free(&gc); @@ -292,20 +292,18 @@ * if the server does not push a timeout */ static void -parse_auth_pending_keywords(const struct buffer *buffer, - unsigned int *server_timeout) +parse_auth_pending_keywords(const struct buffer *buffer, unsigned int *ser= ver_timeout) { struct buffer buf =3D *buffer; /* does the buffer start with "AUTH_PENDING," ? */ - if (!buf_advance(&buf, strlen("AUTH_PENDING")) - || !(buf_read_u8(&buf) =3D=3D ',') || !BLEN(&buf)) + if (!buf_advance(&buf, strlen("AUTH_PENDING")) || !(buf_read_u8(&buf) = =3D=3D ',') || !BLEN(&buf)) { #ifdef ENABLE_MANAGEMENT if (management) { - management_set_state(management, OPENVPN_STATE_AUTH_PENDING, - "", NULL, NULL, NULL, NULL); + management_set_state(management, OPENVPN_STATE_AUTH_PENDING, "= ", NULL, NULL, NULL, + NULL); } #endif @@ -320,8 +318,8 @@ * buf_parse is called, as it will insert \0 bytes into the buffer */ if (management) { - management_set_state(management, OPENVPN_STATE_AUTH_PENDING, - BSTR(&buf), NULL, NULL, NULL, NULL); + management_set_state(management, OPENVPN_STATE_AUTH_PENDING, BSTR(= &buf), NULL, NULL, NULL, + NULL); } #endif @@ -344,17 +342,18 @@ /* Cap the increase at the maximum time we are willing stay in the * pending authentication state */ - unsigned int max_timeout =3D max_uint(c->options.renegotiate_seconds/2, - c->options.handshake_window); + unsigned int max_timeout =3D + max_uint(c->options.renegotiate_seconds / 2, c->options.handshake_= window); /* try to parse parameter keywords, default to hand-winow timeout if t= he * server does not supply a timeout */ unsigned int server_timeout =3D c->options.handshake_window; parse_auth_pending_keywords(buffer, &server_timeout); - msg(D_PUSH, "AUTH_PENDING received, extending handshake timeout from %= us " - "to %us", c->options.handshake_window, - min_uint(max_timeout, server_timeout)); + msg(D_PUSH, + "AUTH_PENDING received, extending handshake timeout from %us " + "to %us", + c->options.handshake_window, min_uint(max_timeout, server_timeout)= ); const struct key_state *ks =3D get_primary_key(c->c2.tls_multi); c->c2.push_request_timeout =3D ks->established + min_uint(max_timeout,= server_timeout); @@ -374,16 +373,16 @@ * * @return true on success, false on failure. */ -static bool push_option_fmt(struct gc_arena *gc, struct push_list *push_li= st, - int msglevel, const char *fmt, ...) +static bool push_option_fmt(struct gc_arena *gc, struct push_list *push_li= st, int msglevel, + const char *fmt, ...) #ifdef __GNUC__ #if __USE_MINGW_ANSI_STDIO -__attribute__ ((format(gnu_printf, 4, 5))) + __attribute__((format(gnu_printf, 4, 5))) #else -__attribute__ ((format(__printf__, 4, 5))) + __attribute__((format(__printf__, 4, 5))) #endif #endif -; + ; /* * Send auth failed message from server to client. @@ -403,7 +402,7 @@ static const char auth_failed[] =3D "AUTH_FAILED"; size_t len; - len =3D (client_reason ? strlen(client_reason)+1 : 0) + sizeof(auth_fa= iled); + len =3D (client_reason ? strlen(client_reason) + 1 : 0) + sizeof(auth_= failed); if (len > PUSH_BUNDLE_SIZE) { len =3D PUSH_BUNDLE_SIZE; @@ -419,13 +418,12 @@ /* We kill the whole session, send the AUTH_FAILED to any TLS sess= ion * that might be active */ - send_control_channel_string_dowork(&c->c2.tls_multi->session[TM_IN= ITIAL], - BSTR(&buf), D_PUSH); - send_control_channel_string_dowork(&c->c2.tls_multi->session[TM_AC= TIVE], - BSTR(&buf), D_PUSH); + send_control_channel_string_dowork(&c->c2.tls_multi->session[TM_IN= ITIAL], BSTR(&buf), + D_PUSH); + send_control_channel_string_dowork(&c->c2.tls_multi->session[TM_AC= TIVE], BSTR(&buf), + D_PUSH); reschedule_multi_process(c); - } gc_free(&gc); @@ -433,8 +431,7 @@ bool -send_auth_pending_messages(struct tls_multi *tls_multi, - struct tls_session *session, +send_auth_pending_messages(struct tls_multi *tls_multi, struct tls_session= *session, const char *extra, unsigned int timeout) { struct key_state *ks =3D &session->key[KS_PRIMARY]; @@ -446,8 +443,8 @@ /* Calculate the maximum timeout and subtract the time we already wait= ed */ - unsigned int max_timeout =3D max_uint(tls_multi->opt.renegotiate_secon= ds/2, - tls_multi->opt.handshake_window); + unsigned int max_timeout =3D + max_uint(tls_multi->opt.renegotiate_seconds / 2, tls_multi->opt.ha= ndshake_window); max_timeout =3D max_timeout - (now - ks->initial); timeout =3D min_uint(max_timeout, timeout); @@ -506,17 +503,19 @@ struct gc_arena gc =3D gc_new(); unsigned int option_types_found =3D 0; - msg(D_PUSH, "PUSH: Received control message: '%s'", sanitize_control_m= essage(BSTR(buffer), &gc)); + msg(D_PUSH, "PUSH: Received control message: '%s'", + sanitize_control_message(BSTR(buffer), &gc)); - int status =3D process_incoming_push_msg(c, buffer, c->options.pull, - pull_permission_mask(c), + int status =3D process_incoming_push_msg(c, buffer, c->options.pull, p= ull_permission_mask(c), &option_types_found); if (status =3D=3D PUSH_MSG_ERROR) { - msg(D_PUSH_ERRORS, "WARNING: Received bad push/pull message: %s", = sanitize_control_message(BSTR(buffer), &gc)); + msg(D_PUSH_ERRORS, "WARNING: Received bad push/pull message: %s", + sanitize_control_message(BSTR(buffer), &gc)); } - else if (status =3D=3D PUSH_MSG_REPLY || status =3D=3D PUSH_MSG_UPDATE= || status =3D=3D PUSH_MSG_CONTINUATION) + else if (status =3D=3D PUSH_MSG_REPLY || status =3D=3D PUSH_MSG_UPDATE + || status =3D=3D PUSH_MSG_CONTINUATION) { c->options.push_option_types_found |=3D option_types_found; @@ -605,17 +604,14 @@ */ if (tls_multi->auth_token) { - push_option_fmt(gc, push_list, M_USAGE, "auth-token %s", - tls_multi->auth_token); + push_option_fmt(gc, push_list, M_USAGE, "auth-token %s", tls_multi= ->auth_token); char *base64user =3D NULL; int ret =3D openvpn_base64_encode(tls_multi->locked_username, - (int)strlen(tls_multi->locked_user= name), - &base64user); + (int)strlen(tls_multi->locked_user= name), &base64user); if (ret < USER_PASS_LEN && ret > 0) { - push_option_fmt(gc, push_list, M_USAGE, "auth-token-user %s", - base64user); + push_option_fmt(gc, push_list, M_USAGE, "auth-token-user %s", = base64user); } free(base64user); } @@ -631,8 +627,7 @@ * @return true on success, false on failure. */ bool -prepare_push_reply(struct context *c, struct gc_arena *gc, - struct push_list *push_list) +prepare_push_reply(struct context *c, struct gc_arena *gc, struct push_lis= t *push_list) { struct tls_multi *tls_multi =3D c->c2.tls_multi; struct options *o =3D &c->options; @@ -643,14 +638,12 @@ push_option_fmt(gc, push_list, M_USAGE, "ifconfig-ipv6 %s/%d %s", print_in6_addr(c->c2.push_ifconfig_ipv6_local, 0, = gc), c->c2.push_ifconfig_ipv6_netbits, - print_in6_addr(c->c2.push_ifconfig_ipv6_remote, - 0, gc)); + print_in6_addr(c->c2.push_ifconfig_ipv6_remote, 0,= gc)); } /* ipv4 */ if (c->c2.push_ifconfig_defined && c->c2.push_ifconfig_local - && c->c2.push_ifconfig_remote_netmask - && !o->push_ifconfig_ipv4_blocked) + && c->c2.push_ifconfig_remote_netmask && !o->push_ifconfig_ipv4_bl= ocked) { in_addr_t ifconfig_local =3D c->c2.push_ifconfig_local; if (c->c2.push_ifconfig_local_alias) @@ -659,14 +652,12 @@ } push_option_fmt(gc, push_list, M_USAGE, "ifconfig %s %s", print_in_addr_t(ifconfig_local, 0, gc), - print_in_addr_t(c->c2.push_ifconfig_remote_netmask, - 0, gc)); + print_in_addr_t(c->c2.push_ifconfig_remote_netmask= , 0, gc)); } if (tls_multi->use_peer_id) { - push_option_fmt(gc, push_list, M_USAGE, "peer-id %d", - tls_multi->peer_id); + push_option_fmt(gc, push_list, M_USAGE, "peer-id %d", tls_multi->p= eer_id); } /* * If server uses --auth-gen-token and we have an auth token @@ -728,10 +719,11 @@ push_option_fmt(gc, push_list, M_USAGE, "tun-mtu %d", o->ce.tun_mt= u); if (client_max_mtu < o->ce.tun_mtu) { - msg(M_WARN, "Warning: reported maximum MTU from client (%d) is= lower " + msg(M_WARN, + "Warning: reported maximum MTU from client (%d) is lower " "than MTU used on the server (%d). Add tun-max-mtu %d " - "to client configuration.", client_max_mtu, - o->ce.tun_mtu, o->ce.tun_mtu); + "to client configuration.", + client_max_mtu, o->ce.tun_mtu, o->ce.tun_mtu); } } @@ -739,8 +731,7 @@ } static bool -send_push_options(struct context *c, struct buffer *buf, - struct push_list *push_list, int safe_cap, +send_push_options(struct context *c, struct buffer *buf, struct push_list = *push_list, int safe_cap, bool *push_sent, bool *multi_push) { struct push_entry *e =3D push_list->head; @@ -810,15 +801,13 @@ buf_printf(&buf, "%s", push_reply_cmd); /* send options which are common to all clients */ - if (!send_push_options(c, &buf, &c->options.push_list, safe_cap, - &push_sent, &multi_push)) + if (!send_push_options(c, &buf, &c->options.push_list, safe_cap, &push= _sent, &multi_push)) { goto fail; } /* send client-specific options */ - if (!send_push_options(c, &buf, per_client_push_list, safe_cap, - &push_sent, &multi_push)) + if (!send_push_options(c, &buf, per_client_push_list, safe_cap, &push_= sent, &multi_push)) { goto fail; } @@ -828,7 +817,7 @@ buf_printf(&buf, ",push-continuation 1"); } - if (BLEN(&buf) > sizeof(push_reply_cmd)-1) + if (BLEN(&buf) > sizeof(push_reply_cmd) - 1) { const bool status =3D send_control_channel_string(c, BSTR(&buf), D= _PUSH); if (!status) @@ -863,8 +852,8 @@ } static void -push_option_ex(struct gc_arena *gc, struct push_list *push_list, - const char *opt, bool enable, int msglevel) +push_option_ex(struct gc_arena *gc, struct push_list *push_list, const cha= r *opt, bool enable, + int msglevel) { if (!string_class(opt, CC_ANY, CC_COMMA)) { @@ -906,8 +895,7 @@ push_reset(o); while (e) { - push_option_ex(&o->gc, &o->push_list, - string_alloc(e->option, &o->gc), true, M_FATAL); + push_option_ex(&o->gc, &o->push_list, string_alloc(e->option, = &o->gc), true, M_FATAL); e =3D e->next; } } @@ -922,16 +910,16 @@ } static bool -push_option_fmt(struct gc_arena *gc, struct push_list *push_list, - int msglevel, const char *format, ...) +push_option_fmt(struct gc_arena *gc, struct push_list *push_list, int msgl= evel, const char *format, + ...) { va_list arglist; - char tmp[256] =3D {0}; + char tmp[256] =3D { 0 }; int len; va_start(arglist, format); len =3D vsnprintf(tmp, sizeof(tmp), format, arglist); va_end(arglist); - if (len > sizeof(tmp)-1) + if (len > sizeof(tmp) - 1) { return false; } @@ -958,7 +946,7 @@ } =20 /* ifconfig-ipv6 is special, as not part of the push list */ - if (streq( p, "ifconfig-ipv6" )) + if (streq(p, "ifconfig-ipv6")) { o->push_ifconfig_ipv6_blocked =3D true; return; @@ -971,8 +959,7 @@ /* cycle through the push list */ while (e) { - if (e->enable - && strncmp( e->option, p, strlen(p) ) =3D=3D 0) + if (e->enable && strncmp(e->option, p, strlen(p)) =3D=3D 0) { msg(D_PUSH_DEBUG, "PUSH_REMOVE removing: '%s'", e->option); e->enable =3D false; @@ -1012,8 +999,7 @@ struct push_list push_list =3D { 0 }; struct gc_arena gc =3D gc_new(); - if (prepare_push_reply(c, &gc, &push_list) - && send_push_reply(c, &push_list)) + if (prepare_push_reply(c, &gc, &push_list) && send_push_reply(= c, &push_list)) { ret =3D PUSH_MSG_REQUEST; c->c2.sent_push_reply_expiry =3D now + 30; @@ -1035,9 +1021,9 @@ char line[OPTION_PARM_SIZE]; while (buf_parse(buf, ',', line, sizeof(line))) { - /* peer-id and auth-token might change on restart and this should = not trigger reopening tun */ - if (strprefix(line, "peer-id ") - || strprefix(line, "auth-token ") + /* peer-id and auth-token might change on restart and this should = not trigger reopening tun + */ + if (strprefix(line, "peer-id ") || strprefix(line, "auth-token ") || strprefix(line, "auth-token-user ")) { continue; @@ -1047,15 +1033,13 @@ { continue; } - md_ctx_update(ctx, (const uint8_t *) line, strlen(line)+1); + md_ctx_update(ctx, (const uint8_t *)line, strlen(line) + 1); } } static int -process_incoming_push_reply(struct context *c, - unsigned int permission_mask, - unsigned int *option_types_found, - struct buffer *buf) +process_incoming_push_reply(struct context *c, unsigned int permission_mas= k, + unsigned int *option_types_found, struct buffe= r *buf) { int ret =3D PUSH_MSG_ERROR; const uint8_t ch =3D buf_read_u8(buf); @@ -1068,22 +1052,15 @@ md_ctx_init(c->c2.pulled_options_state, "SHA256"); c->c2.pulled_options_digest_init_done =3D true; } - if (apply_push_options(c, - &c->options, - buf, - permission_mask, - option_types_found, - c->c2.es, + if (apply_push_options(c, &c->options, buf, permission_mask, optio= n_types_found, c->c2.es, false)) { - push_update_digest(c->c2.pulled_options_state, &buf_orig, - &c->options); + push_update_digest(c->c2.pulled_options_state, &buf_orig, &c->= options); switch (c->options.push_continuation) { case 0: case 1: - md_ctx_final(c->c2.pulled_options_state, - c->c2.pulled_options_digest.digest); + md_ctx_final(c->c2.pulled_options_state, c->c2.pulled_= options_digest.digest); md_ctx_cleanup(c->c2.pulled_options_state); md_ctx_free(c->c2.pulled_options_state); c->c2.pulled_options_state =3D NULL; @@ -1106,10 +1083,8 @@ } int -process_incoming_push_msg(struct context *c, - const struct buffer *buffer, - bool honor_received_options, - unsigned int permission_mask, +process_incoming_push_msg(struct context *c, const struct buffer *buffer, + bool honor_received_options, unsigned int permis= sion_mask, unsigned int *option_types_found) { struct buffer buf =3D *buffer; @@ -1119,17 +1094,13 @@ c->c2.push_request_received =3D true; return process_incoming_push_request(c); } - else if (honor_received_options - && buf_string_compare_advance(&buf, push_reply_cmd)) + else if (honor_received_options && buf_string_compare_advance(&buf, pu= sh_reply_cmd)) { - return process_incoming_push_reply(c, permission_mask, - option_types_found, &buf); + return process_incoming_push_reply(c, permission_mask, option_type= s_found, &buf); } - else if (honor_received_options - && buf_string_compare_advance(&buf, push_update_cmd)) + else if (honor_received_options && buf_string_compare_advance(&buf, pu= sh_update_cmd)) { - return process_incoming_push_update(c, permission_mask, - option_types_found, &buf); + return process_incoming_push_update(c, permission_mask, option_typ= es_found, &buf); } else { @@ -1152,13 +1123,14 @@ /* cycle through the push list */ while (e) { - char *p[MAX_PARMS+1]; + char *p[MAX_PARMS + 1]; bool enable =3D true; /* parse the push item */ CLEAR(p); if (e->enable - && parse_line(e->option, p, SIZE(p)-1, "[PUSH_ROUTE_REMOVE= ]", 1, D_ROUTE_DEBUG, &gc)) + && parse_line(e->option, p, SIZE(p) - 1, "[PUSH_ROUTE_REMO= VE]", 1, D_ROUTE_DEBUG, + &gc)) { /* is the push item a route directive? */ if (p[0] && !strcmp(p[0], "route") && !p[3] && o->iroutes) @@ -1166,7 +1138,8 @@ /* get route parameters */ bool status1, status2; const in_addr_t network =3D getaddr(GETADDR_HOST_ORDER= , p[1], 0, &status1, NULL); - const in_addr_t netmask =3D getaddr(GETADDR_HOST_ORDER= , p[2] ? p[2] : "255.255.255.255", 0, &status2, NULL); + const in_addr_t netmask =3D getaddr( + GETADDR_HOST_ORDER, p[2] ? p[2] : "255.255.255.255= ", 0, &status2, NULL); /* did route parameters parse correctly? */ if (status1 && status2) @@ -1176,7 +1149,9 @@ /* does route match an iroute? */ for (ir =3D o->iroutes; ir !=3D NULL; ir =3D ir->n= ext) { - if (network =3D=3D ir->network && netmask =3D= =3D netbits_to_netmask(ir->netbits >=3D 0 ? ir->netbits : 32)) + if (network =3D=3D ir->network + && netmask + =3D=3D netbits_to_netmask(ir->netbi= ts >=3D 0 ? ir->netbits : 32)) { enable =3D false; break; @@ -1184,8 +1159,7 @@ } } } - else if (p[0] && !strcmp(p[0], "route-ipv6") && !p[2] - && o->iroutes_ipv6) + else if (p[0] && !strcmp(p[0], "route-ipv6") && !p[2] && o= ->iroutes_ipv6) { /* get route parameters */ struct in6_addr network; diff --git a/src/openvpn/push.h b/src/openvpn/push.h index b6770bc..22b940f 100644 --- a/src/openvpn/push.h +++ b/src/openvpn/push.h @@ -34,17 +34,18 @@ #define PUSH_MSG_ALREADY_REPLIED 6 #define PUSH_MSG_UPDATE 7 -#define push_reply_cmd "PUSH_REPLY" +#define push_reply_cmd "PUSH_REPLY" #define push_update_cmd "PUSH_UPDATE" /* Push-update options flags */ -#define PUSH_OPT_TO_REMOVE (1<<0) -#define PUSH_OPT_OPTIONAL (1<<1) +#define PUSH_OPT_TO_REMOVE (1 << 0) +#define PUSH_OPT_OPTIONAL (1 << 1) int process_incoming_push_request(struct context *c); /** - * @brief Handles the receiving of a push-update message and applies updat= es to the specified options. + * @brief Handles the receiving of a push-update message and applies updat= es to the specified + * options. * * This function processes a push-update message, validating its content a= nd applying updates * to the options specified in the message. It also handles split messages= if the complete @@ -63,22 +64,19 @@ * - `PUSH_MSG_ERROR`: An error occurred during message processing, or the= message is invalid. */ -int process_incoming_push_update(struct context *c, - unsigned int permission_mask, - unsigned int *option_types_found, - struct buffer *buf); +int process_incoming_push_update(struct context *c, unsigned int permissio= n_mask, + unsigned int *option_types_found, struct = buffer *buf); -int process_incoming_push_msg(struct context *c, - const struct buffer *buffer, - bool honor_received_options, - unsigned int permission_mask, +int process_incoming_push_msg(struct context *c, const struct buffer *buff= er, + bool honor_received_options, unsigned int pe= rmission_mask, unsigned int *option_types_found); bool send_push_request(struct context *c); void receive_auth_failed(struct context *c, const struct buffer *buffer); -void server_pushed_signal(struct context *c, const struct buffer *buffer, = const bool restart, const int adv); +void server_pushed_signal(struct context *c, const struct buffer *buffer, = const bool restart, + const int adv); void receive_exit_message(struct context *c); @@ -92,8 +90,7 @@ void push_option(struct options *o, const char *opt, int msglevel); -void push_options(struct options *o, char **p, int msglevel, - struct gc_arena *gc); +void push_options(struct options *o, char **p, int msglevel, struct gc_are= na *gc); void push_reset(struct options *o); @@ -108,10 +105,8 @@ * doc/management-notes.txt under client-pending-auth for * more details on message format */ -bool -send_auth_pending_messages(struct tls_multi *tls_multi, - struct tls_session *session, const char *extra, - unsigned int timeout); +bool send_auth_pending_messages(struct tls_multi *tls_multi, struct tls_se= ssion *session, + const char *extra, unsigned int timeout); void send_restart(struct context *c, const char *kill_msg); @@ -130,7 +125,6 @@ * @param c The context struct * @param buffer Buffer containing the control message with AUTH_PE= NDING */ -void -receive_auth_pending(struct context *c, const struct buffer *buffer); +void receive_auth_pending(struct context *c, const struct buffer *buffer); #endif /* ifndef PUSH_H */ diff --git a/src/openvpn/push_util.c b/src/openvpn/push_util.c index b4d1e8b..0862a74 100644 --- a/src/openvpn/push_util.c +++ b/src/openvpn/push_util.c @@ -5,21 +5,14 @@ #include "push.h" int -process_incoming_push_update(struct context *c, - unsigned int permission_mask, - unsigned int *option_types_found, - struct buffer *buf) +process_incoming_push_update(struct context *c, unsigned int permission_ma= sk, + unsigned int *option_types_found, struct buff= er *buf) { int ret =3D PUSH_MSG_ERROR; const uint8_t ch =3D buf_read_u8(buf); if (ch =3D=3D ',') { - if (apply_push_options(c, - &c->options, - buf, - permission_mask, - option_types_found, - c->c2.es, + if (apply_push_options(c, &c->options, buf, permission_mask, optio= n_types_found, c->c2.es, true)) { switch (c->options.push_continuation) diff --git a/src/openvpn/pushlist.h b/src/openvpn/pushlist.h index 1b66517..ef4de88 100644 --- a/src/openvpn/pushlist.h +++ b/src/openvpn/pushlist.h @@ -25,13 +25,15 @@ /* parameters to be pushed to peer */ -struct push_entry { +struct push_entry +{ struct push_entry *next; bool enable; const char *option; }; -struct push_list { +struct push_list +{ struct push_entry *head; struct push_entry *tail; }; diff --git a/src/openvpn/reflect_filter.c b/src/openvpn/reflect_filter.c index 17255f7..071df7c 100644 --- a/src/openvpn/reflect_filter.c +++ b/src/openvpn/reflect_filter.c @@ -46,10 +46,10 @@ int64_t dropped =3D irl->curr_period_counter - irl->max_per_period; if (dropped > 0) { - msg(D_TLS_DEBUG_LOW, "Dropped %" PRId64 " initial handshake pa= ckets" - " due to --connect-freq-initial %" PRId64 " %d", dropped, - irl->max_per_period, irl->period_length); - + msg(D_TLS_DEBUG_LOW, + "Dropped %" PRId64 " initial handshake packets" + " due to --connect-freq-initial %" PRId64 " %d", + dropped, irl->max_per_period, irl->period_length); } irl->last_period_reset =3D now; irl->curr_period_counter =3D 0; @@ -62,9 +62,11 @@ if (over_limit && !irl->warning_displayed) { - msg(M_WARN, "Note: --connect-freq-initial %" PRId64 " %d rate limi= t " + msg(M_WARN, + "Note: --connect-freq-initial %" PRId64 " %d rate limit " "exceeded, dropping initial handshake packets for the next %d " - "seconds", irl->max_per_period, irl->period_length, + "seconds", + irl->max_per_period, irl->period_length, (int)(irl->last_period_reset + irl->period_length - now)); irl->warning_displayed =3D true; } diff --git a/src/openvpn/reflect_filter.h b/src/openvpn/reflect_filter.h index e3fb165..0601f4b 100644 --- a/src/openvpn/reflect_filter.h +++ b/src/openvpn/reflect_filter.h @@ -26,7 +26,8 @@ /** struct that handles all the rate limiting logic for initial * responses */ -struct initial_packet_rate_limit { +struct initial_packet_rate_limit +{ /** This is a hard limit for packets per seconds. */ int64_t max_per_period; @@ -50,22 +51,19 @@ * checks if the connection is still allowed to connect under the rate * limit. This also increases the internal counter at the same time */ -bool -reflect_filter_rate_limit_check(struct initial_packet_rate_limit *irl); +bool reflect_filter_rate_limit_check(struct initial_packet_rate_limit *irl= ); /** * decreases the counter of initial packets seen, so connections that * successfully completed the three-way handshake do not count against * the counter of initial connection attempts */ -void -reflect_filter_rate_limit_decrease(struct initial_packet_rate_limit *irl); +void reflect_filter_rate_limit_decrease(struct initial_packet_rate_limit *= irl); /** * allocate and initialize the initial-packet rate limiter structure */ -struct initial_packet_rate_limit * -initial_rate_limit_init(int max_per_period, int period_length); +struct initial_packet_rate_limit *initial_rate_limit_init(int max_per_peri= od, int period_length); /** * free the initial-packet rate limiter structure diff --git a/src/openvpn/reliable.c b/src/openvpn/reliable.c index 278dc33..b4a747f 100644 --- a/src/openvpn/reliable.c +++ b/src/openvpn/reliable.c @@ -50,8 +50,7 @@ * verify that test - base < extent while allowing for base or test wrapar= ound */ static inline bool -reliable_pid_in_range1(const packet_id_type test, - const packet_id_type base, +reliable_pid_in_range1(const packet_id_type test, const packet_id_type bas= e, const unsigned int extent) { return subtract_pid(test, base) < extent; @@ -61,8 +60,7 @@ * verify that test < base + extent while allowing for base or test wrapar= ound */ static inline bool -reliable_pid_in_range2(const packet_id_type test, - const packet_id_type base, +reliable_pid_in_range2(const packet_id_type test, const packet_id_type bas= e, const unsigned int extent) { if (base + extent >=3D base) @@ -74,7 +72,7 @@ } else { - if ((test+0x80000000u) < (base+0x80000000u) + extent) + if ((test + 0x80000000u) < (base + 0x80000000u) + extent) { return true; } @@ -87,8 +85,7 @@ * verify that p1 < p2 while allowing for p1 or p2 wraparound */ static inline bool -reliable_pid_min(const packet_id_type p1, - const packet_id_type p2) +reliable_pid_min(const packet_id_type p1, const packet_id_type p2) { return !reliable_pid_in_range1(p1, p2, 0x80000000u); } @@ -144,8 +141,7 @@ bool -reliable_ack_read(struct reliable_ack *ack, - struct buffer *buf, const struct session_id *sid) +reliable_ack_read(struct reliable_ack *ack, struct buffer *buf, const stru= ct session_id *sid) { struct session_id session_id_remote; @@ -154,12 +150,11 @@ return false; } - if (ack->len >=3D 1 && (!session_id_defined(&session_id_remote) - || !session_id_equal(&session_id_remote, sid))) + if (ack->len >=3D 1 + && (!session_id_defined(&session_id_remote) || !session_id_equal(&= session_id_remote, sid))) { struct gc_arena gc =3D gc_new(); - dmsg(D_REL_LOW, - "ACK read BAD SESSION-ID FROM REMOTE, local=3D%s, remote=3D%s= ", + dmsg(D_REL_LOW, "ACK read BAD SESSION-ID FROM REMOTE, local=3D%s, = remote=3D%s", session_id_print(sid, &gc), session_id_print(&session_id_remo= te, &gc)); gc_free(&gc); return false; @@ -210,7 +205,7 @@ { ASSERT(ack->len >=3D n); /* This loop is backward to ensure the same order as in ack */ - for (int i =3D n-1; i >=3D 0; i--) + for (int i =3D n - 1; i >=3D 0; i--) { packet_id_type id =3D ack->packet_id[i]; @@ -250,9 +245,7 @@ /* write a packet ID acknowledgement record to buf, */ /* removing all acknowledged entries from ack */ bool -reliable_ack_write(struct reliable_ack *ack, - struct reliable_ack *ack_mru, - struct buffer *buf, +reliable_ack_write(struct reliable_ack *ack, struct reliable_ack *ack_mru,= struct buffer *buf, const struct session_id *sid, int max, bool prepend) { int i, j, n; @@ -284,7 +277,8 @@ packet_id_type pid =3D ack_mru->packet_id[i]; packet_id_type net_pid =3D htonpid(pid); ASSERT(buf_write(&sub, &net_pid, sizeof(net_pid))); - dmsg(D_REL_DEBUG, "ACK write ID " packet_id_format " (ack->len=3D%= d, n=3D%d)", (packet_id_print_type)pid, ack->len, n); + dmsg(D_REL_DEBUG, "ACK write ID " packet_id_format " (ack->len=3D%= d, n=3D%d)", + (packet_id_print_type)pid, ack->len, n); } if (total_acks) { @@ -293,7 +287,7 @@ } if (n) { - for (i =3D 0, j =3D n; j < ack->len; ) + for (i =3D 0, j =3D n; j < ack->len;) { ack->packet_id[i++] =3D ack->packet_id[j++]; } @@ -494,7 +488,8 @@ return true; bad: - dmsg(D_REL_DEBUG, "ACK " packet_id_format " is a replay: %s", (packet_= id_print_type)id, reliable_print_ids(rel, &gc)); + dmsg(D_REL_DEBUG, "ACK " packet_id_format " is a replay: %s", (packet_= id_print_type)id, + reliable_print_ids(rel, &gc)); gc_free(&gc); return false; } @@ -513,7 +508,8 @@ gc_free(&gc); } - dmsg(D_REL_DEBUG, "ACK RWBS rel->size=3D%d rel->packet_id=3D%08x id=3D= %08x ret=3D%d", rel->size, rel->packet_id, id, ret); + dmsg(D_REL_DEBUG, "ACK RWBS rel->size=3D%d rel->packet_id=3D%08x id=3D= %08x ret=3D%d", rel->size, + rel->packet_id, id, ret); return ret; } @@ -630,9 +626,7 @@ } } (void)n_active; /* dmsg might not generate code */ - dmsg(D_REL_DEBUG, "ACK reliable_can_send active=3D%d current=3D%d : %s= ", - n_active, - n_current, + dmsg(D_REL_DEBUG, "ACK reliable_can_send active=3D%d current=3D%d : %s= ", n_active, n_current, reliable_print_ids(rel, &gc)); gc_free(&gc); @@ -653,8 +647,7 @@ /* If N_ACK_RETRANSMIT later packets have received ACKs, we assume * that the packet was lost and resend it even if the timeout has * not expired yet. */ - if (e->active - && (e->n_acks >=3D N_ACK_RETRANSMIT || local_now >=3D e->next_= try)) + if (e->active && (e->n_acks >=3D N_ACK_RETRANSMIT || local_now >= =3D e->next_try)) { if (!best || reliable_pid_min(e->packet_id, best->packet_id)) { @@ -720,9 +713,7 @@ } } - dmsg(D_REL_DEBUG, "ACK reliable_send_timeout %d %s", - (int) ret, - reliable_print_ids(rel, &gc)); + dmsg(D_REL_DEBUG, "ACK reliable_send_timeout %d %s", (int)ret, reliabl= e_print_ids(rel, &gc)); gc_free(&gc); return ret; @@ -733,8 +724,8 @@ */ void -reliable_mark_active_incoming(struct reliable *rel, struct buffer *buf, - packet_id_type pid, int opcode) +reliable_mark_active_incoming(struct reliable *rel, struct buffer *buf, pa= cket_id_type pid, + int opcode) { for (int i =3D 0; i < rel->size; ++i) { @@ -753,11 +744,12 @@ e->next_try =3D 0; e->timeout =3D 0; e->n_acks =3D 0; - dmsg(D_REL_DEBUG, "ACK mark active incoming ID " packet_id_for= mat, (packet_id_print_type)e->packet_id); + dmsg(D_REL_DEBUG, "ACK mark active incoming ID " packet_id_for= mat, + (packet_id_print_type)e->packet_id); return; } } - ASSERT(0); /* buf not found in rel */ + ASSERT(0); /* buf not found in rel */ } /* @@ -782,11 +774,12 @@ e->opcode =3D opcode; e->next_try =3D 0; e->timeout =3D rel->initial_timeout; - dmsg(D_REL_DEBUG, "ACK mark active outgoing ID " packet_id_for= mat, (packet_id_print_type)e->packet_id); + dmsg(D_REL_DEBUG, "ACK mark active outgoing ID " packet_id_for= mat, + (packet_id_print_type)e->packet_id); return; } } - ASSERT(0); /* buf not found in rel */ + ASSERT(0); /* buf not found in rel */ } /* delete a buffer previously activated by reliable_mark_active() */ diff --git a/src/openvpn/reliable.h b/src/openvpn/reliable.h index 6c37d78..89a9b16 100644 --- a/src/openvpn/reliable.h +++ b/src/openvpn/reliable.h @@ -40,18 +40,21 @@ * @{ */ -#define RELIABLE_ACK_SIZE 8 /**< The maximum number of packet IDs - * waiting to be acknowledged which can - * be stored in one \c reliable_ack - * structure. */ +#define RELIABLE_ACK_SIZE \ + 8 /**< The maximum number of packet IDs \ + * waiting to be acknowledged which can \ + * be stored in one \c reliable_ack \ + * structure. */ -#define RELIABLE_CAPACITY 12 /**< The maximum number of packets that - * the reliability layer for one VPN - * tunnel in one direction can store. */ +#define RELIABLE_CAPACITY \ + 12 /**< The maximum number of packets that \ + * the reliability layer for one VPN \ + * tunnel in one direction can store. */ -#define N_ACK_RETRANSMIT 3 /**< We retry sending a packet early if - * this many later packets have been - * ACKed. */ +#define N_ACK_RETRANSMIT \ + 3 /**< We retry sending a packet early if \ + * this many later packets have been \ + * ACKed. */ /** * The acknowledgment structure in which packet IDs are stored for later @@ -76,9 +79,9 @@ interval_t timeout; time_t next_try; packet_id_type packet_id; - size_t n_acks; /* Number of acks received for packets with higher PID. - * Used for fast retransmission when there were at lea= st - * N_ACK_RETRANSMIT. */ + size_t n_acks; /* Number of acks received for packets with higher PID. + * Used for fast retransmission when there were at least + * N_ACK_RETRANSMIT. */ int opcode; struct buffer buf; }; @@ -93,7 +96,7 @@ interval_t initial_timeout; packet_id_type packet_id; int offset; /**< Offset of the bufs in the reliable_entry array */ - bool hold; /* don't xmit until reliable_schedule_now is called */ + bool hold; /* don't xmit until reliable_schedule_now is called */ struct reliable_entry array[RELIABLE_CAPACITY]; }; @@ -120,8 +123,7 @@ * @li True, if processing was successful. * @li False, if an error occurs during processing. */ -bool reliable_ack_read(struct reliable_ack *ack, - struct buffer *buf, const struct session_id *sid); +bool reliable_ack_read(struct reliable_ack *ack, struct buffer *buf, const= struct session_id *sid); /** @@ -141,9 +143,8 @@ * @li True, if processing was successful. * @li False, if an error occurs during processing. */ -bool -reliable_ack_parse(struct buffer *buf, struct reliable_ack *ack, - struct session_id *session_id_remote); +bool reliable_ack_parse(struct buffer *buf, struct reliable_ack *ack, + struct session_id *session_id_remote); /** * Remove acknowledged packets from a reliable structure. @@ -212,9 +213,7 @@ * @li True, if processing was successful. * @li False, if an error occurs during processing. */ -bool reliable_ack_write(struct reliable_ack *ack, - struct reliable_ack *ack_mru, - struct buffer *buf, +bool reliable_ack_write(struct reliable_ack *ack, struct reliable_ack *ack= _mru, struct buffer *buf, const struct session_id *sid, int max, bool prepen= d); /** @} name Functions for processing outgoing acknowledgments */ @@ -337,8 +336,8 @@ * @param pid The packet's packet ID. * @param opcode The packet's opcode. */ -void reliable_mark_active_incoming(struct reliable *rel, struct buffer *bu= f, - packet_id_type pid, int opcode); +void reliable_mark_active_incoming(struct reliable *rel, struct buffer *bu= f, packet_id_type pid, + int opcode); /** * Record a packet ID for later acknowledgment. @@ -374,7 +373,6 @@ struct reliable_entry *reliable_get_entry_sequenced(struct reliable *rel); - /** * Copies the first n acks from \c ack to \c ack_mru * @@ -382,8 +380,7 @@ * @param ack_mru The reliable structure to insert the acks into * @param n The number of ACKS to copy */ -void -copy_acks_to_mru(struct reliable_ack *ack, struct reliable_ack *ack_mru, i= nt n); +void copy_acks_to_mru(struct reliable_ack *ack, struct reliable_ack *ack_m= ru, int n); /** @@ -426,8 +423,7 @@ * @return the number of buffer that are available for sending without * breaking ack sequence * */ -int -reliable_get_num_output_sequenced_available(struct reliable *rel); +int reliable_get_num_output_sequenced_available(struct reliable *rel); /** * Mark the reliable entry associated with the given buffer as diff --git a/src/openvpn/ring_buffer.h b/src/openvpn/ring_buffer.h new file mode 100644 index 0000000..e554296 --- /dev/null +++ b/src/openvpn/ring_buffer.h @@ -0,0 +1,124 @@ +/* + * OpenVPN -- An application to securely tunnel IP networks + * over a single UDP port, with support for SSL/TLS-based + * session authentication and key exchange, + * packet encryption, packet authentication, and + * packet compression. + * + * Copyright (C) 2002-2024 OpenVPN Inc + * 2019 Lev Stipakov + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +#ifdef _WIN32 +#ifndef OPENVPN_RING_BUFFER_H +#define OPENVPN_RING_BUFFER_H + +#include +#include + +#include +#include + +/* + * Values below are taken from Wireguard Windows client + * https://github.com/WireGuard/wireguard-go/blob/master/tun/wintun/ring_w= indows.go#L14 + */ +#define WINTUN_RING_CAPACITY 0x800000 +#define WINTUN_RING_TRAILING_BYTES 0x10000 +#define WINTUN_MAX_PACKET_SIZE 0xffff +#define WINTUN_PACKET_ALIGN 4 + +#define TUN_IOCTL_REGISTER_RINGS \ + CTL_CODE(51820U, 0x970U, METHOD_BUFFERED, FILE_READ_DATA | FILE_WRITE_= DATA) + +/** + * Wintun ring buffer + * See https://github.com/WireGuard/wintun#ring-layout + */ +struct tun_ring +{ + volatile ULONG head; + volatile ULONG tail; + volatile LONG alertable; + UCHAR data[WINTUN_RING_CAPACITY + WINTUN_RING_TRAILING_BYTES]; +}; + +/** + * Struct for ring buffers registration + * See https://github.com/WireGuard/wintun#registering-rings + */ +struct tun_register_rings +{ + struct + { + ULONG ring_size; + struct tun_ring *ring; + HANDLE tail_moved; + } send, receive; +}; + +struct TUN_PACKET_HEADER +{ + uint32_t size; +}; + +struct TUN_PACKET +{ + uint32_t size; + UCHAR data[WINTUN_MAX_PACKET_SIZE]; +}; + +/** + * Registers ring buffers used to exchange data between + * userspace openvpn process and wintun kernel driver, + * see https://github.com/WireGuard/wintun#registering-rings + * + * @param device handle to opened wintun device + * @param send_ring pointer to send ring + * @param receive_ring pointer to receive ring + * @param send_tail_moved event set by wintun to signal openvpn + * that data is available for reading in send r= ing + * @param receive_tail_moved event set by openvpn to signal wintun + * that data has been written to receive ring + * @return true if registration is successful, false ot= herwise - use + * GetLastError() + */ +static inline bool +register_ring_buffers(HANDLE device, struct tun_ring *send_ring, struct tu= n_ring *receive_ring, + HANDLE send_tail_moved, HANDLE receive_tail_moved) +{ + struct tun_register_rings rr; + BOOL res; + DWORD bytes_returned; + + ZeroMemory(&rr, sizeof(rr)); + + rr.send.ring =3D send_ring; + rr.send.ring_size =3D sizeof(struct tun_ring); + rr.send.tail_moved =3D send_tail_moved; + + rr.receive.ring =3D receive_ring; + rr.receive.ring_size =3D sizeof(struct tun_ring); + rr.receive.tail_moved =3D receive_tail_moved; + + res =3D DeviceIoControl(device, TUN_IOCTL_REGISTER_RINGS, &rr, sizeof(= rr), NULL, 0, + &bytes_returned, NULL); + + return res !=3D FALSE; +} + +#endif /* ifndef OPENVPN_RING_BUFFER_H */ +#endif /* ifdef _WIN32 */ diff --git a/src/openvpn/route.c b/src/openvpn/route.c index c4f7f95..e504485 100644 --- a/src/openvpn/route.c +++ b/src/openvpn/route.c @@ -46,11 +46,11 @@ #include "memdbg.h" #if defined(TARGET_LINUX) || defined(TARGET_ANDROID) -#include /* RTM_GETROUTE etc. */ +#include /* RTM_GETROUTE etc. */ #endif #if defined(TARGET_NETBSD) -#include /* RT_ROUNDUP(), RT_ADVANCE() */ +#include /* RT_ROUNDUP(), RT_ADVANCE() */ #endif #ifdef _WIN32 @@ -67,7 +67,8 @@ static int route_ipv6_ipapi(bool add, const struct route_ipv6 *, const str= uct tuntap *); -static int add_route_ipapi(const struct route_ipv4 *r, const struct tuntap= *tt, DWORD adapter_index); +static int add_route_ipapi(const struct route_ipv4 *r, const struct tuntap= *tt, + DWORD adapter_index); static bool del_route_ipapi(const struct route_ipv4 *r, const struct tunta= p *tt); @@ -89,9 +90,7 @@ int i; for (i =3D 0; i < rb->n_bypass; ++i) { - msg(D_ROUTE, "ROUTE: bypass_host_route[%d]=3D%s", - i, - print_in_addr_t(rb->bypass[i], 0, &gc)); + msg(D_ROUTE, "ROUTE: bypass_host_route[%d]=3D%s", i, print_in_addr= _t(rb->bypass[i], 0, &gc)); } gc_free(&gc); } @@ -99,9 +98,9 @@ #endif /* Route addition return status codes */ -#define RTA_ERROR 0 /* route addition failed */ -#define RTA_SUCCESS 1 /* route addition succeeded */ -#define RTA_EEXIST 2 /* route not added as it already exists */ +#define RTA_ERROR 0 /* route addition failed */ +#define RTA_SUCCESS 1 /* route addition succeeded */ +#define RTA_EEXIST 2 /* route not added as it already exists */ static bool add_bypass_address(struct route_bypass *rb, const in_addr_t a) @@ -169,7 +168,8 @@ } void -copy_route_option_list(struct route_option_list *dest, const struct route_= option_list *src, struct gc_arena *a) +copy_route_option_list(struct route_option_list *dest, const struct route_= option_list *src, + struct gc_arena *a) { *dest =3D *src; dest->gc =3D a; @@ -177,8 +177,7 @@ void copy_route_ipv6_option_list(struct route_ipv6_option_list *dest, - const struct route_ipv6_option_list *src, - struct gc_arena *a) + const struct route_ipv6_option_list *src, stru= ct gc_arena *a) { *dest =3D *src; dest->gc =3D a; @@ -188,11 +187,8 @@ route_string(const struct route_ipv4 *r, struct gc_arena *gc) { struct buffer out =3D alloc_buf_gc(256, gc); - buf_printf(&out, "ROUTE network %s netmask %s gateway %s", - print_in_addr_t(r->network, 0, gc), - print_in_addr_t(r->netmask, 0, gc), - print_in_addr_t(r->gateway, 0, gc) - ); + buf_printf(&out, "ROUTE network %s netmask %s gateway %s", print_in_ad= dr_t(r->network, 0, gc), + print_in_addr_t(r->netmask, 0, gc), print_in_addr_t(r->gate= way, 0, gc)); if (r->flags & RT_METRIC_DEFINED) { buf_printf(&out, " metric %d", r->metric); @@ -232,10 +228,7 @@ } static bool -get_special_addr(const struct route_list *rl, - const char *string, - in_addr_t *out, - bool *status) +get_special_addr(const struct route_list *rl, const char *string, in_addr_= t *out, bool *status) { if (status) { @@ -270,7 +263,8 @@ } else { - msg(M_INFO, PACKAGE_NAME " ROUTE: net_gateway undefined --= unable to get default gateway from system"); + msg(M_INFO, PACKAGE_NAME + " ROUTE: net_gateway undefined -- unable to get defaul= t gateway from system"); if (status) { *status =3D false; @@ -315,15 +309,13 @@ } static bool -init_route(struct route_ipv4 *r, - struct addrinfo **network_list, - const struct route_option *ro, +init_route(struct route_ipv4 *r, struct addrinfo **network_list, const str= uct route_option *ro, const struct route_list *rl) { const in_addr_t default_netmask =3D IPV4_NETMASK_HOST; bool status; int ret; - struct in_addr special =3D {0}; + struct in_addr special =3D { 0 }; CLEAR(*r); r->option =3D ro; @@ -337,7 +329,7 @@ /* get_special_addr replaces specialaddr with a special ip addr * like gw. getaddrinfo is called to convert a a addrinfo struct */ - if (get_special_addr(rl, ro->network, (in_addr_t *) &special.s_addr, &= status)) + if (get_special_addr(rl, ro->network, (in_addr_t *)&special.s_addr, &s= tatus)) { if (!status) { @@ -346,13 +338,12 @@ special.s_addr =3D htonl(special.s_addr); char buf[INET_ADDRSTRLEN]; inet_ntop(AF_INET, &special, buf, sizeof(buf)); - ret =3D openvpn_getaddrinfo(0, buf, NULL, 0, NULL, - AF_INET, network_list); + ret =3D openvpn_getaddrinfo(0, buf, NULL, 0, NULL, AF_INET, networ= k_list); } else { - ret =3D openvpn_getaddrinfo(GETADDR_RESOLVE | GETADDR_WARN_ON_SIGN= AL, - ro->network, NULL, 0, NULL, AF_INET, net= work_list); + ret =3D openvpn_getaddrinfo(GETADDR_RESOLVE | GETADDR_WARN_ON_SIGN= AL, ro->network, NULL, 0, + NULL, AF_INET, network_list); } status =3D (ret =3D=3D 0); @@ -366,13 +357,8 @@ if (is_route_parm_defined(ro->netmask)) { - r->netmask =3D getaddr( - GETADDR_HOST_ORDER - | GETADDR_WARN_ON_SIGNAL, - ro->netmask, - 0, - &status, - NULL); + r->netmask =3D + getaddr(GETADDR_HOST_ORDER | GETADDR_WARN_ON_SIGNAL, ro->netma= sk, 0, &status, NULL); if (!status) { goto fail; @@ -389,14 +375,8 @@ { if (!get_special_addr(rl, ro->gateway, &r->gateway, &status)) { - r->gateway =3D getaddr( - GETADDR_RESOLVE - | GETADDR_HOST_ORDER - | GETADDR_WARN_ON_SIGNAL, - ro->gateway, - 0, - &status, - NULL); + r->gateway =3D getaddr(GETADDR_RESOLVE | GETADDR_HOST_ORDER | = GETADDR_WARN_ON_SIGNAL, + ro->gateway, 0, &status, NULL); } if (!status) { @@ -411,7 +391,9 @@ } else { - msg(M_WARN, PACKAGE_NAME " ROUTE: " PACKAGE_NAME " needs a gat= eway parameter for a --route option and no default was specified by either = --route-gateway or --ifconfig options"); + msg(M_WARN, PACKAGE_NAME + " ROUTE: " PACKAGE_NAME + " needs a gateway parameter for a --route option and no de= fault was specified by either --route-gateway or --ifconfig options"); goto fail; } } @@ -425,8 +407,7 @@ if (r->metric < 0) { msg(M_WARN, PACKAGE_NAME " ROUTE: route metric for network %s = (%s) must be >=3D 0", - ro->network, - ro->metric); + ro->network, ro->metric); goto fail; } r->flags |=3D RT_METRIC_DEFINED; @@ -451,13 +432,12 @@ } static bool -init_route_ipv6(struct route_ipv6 *r6, - const struct route_ipv6_option *r6o, - const struct route_ipv6_list *rl6 ) +init_route_ipv6(struct route_ipv6 *r6, const struct route_ipv6_option *r6o, + const struct route_ipv6_list *rl6) { CLEAR(*r6); - if (!get_ipv6_addr( r6o->prefix, &r6->network, &r6->netbits, M_WARN )) + if (!get_ipv6_addr(r6o->prefix, &r6->network, &r6->netbits, M_WARN)) { goto fail; } @@ -465,9 +445,9 @@ /* gateway */ if (is_route_parm_defined(r6o->gateway)) { - if (inet_pton( AF_INET6, r6o->gateway, &r6->gateway ) !=3D 1) + if (inet_pton(AF_INET6, r6o->gateway, &r6->gateway) !=3D 1) { - msg( M_WARN, PACKAGE_NAME "ROUTE6: cannot parse gateway spec '= %s'", r6o->gateway ); + msg(M_WARN, PACKAGE_NAME "ROUTE6: cannot parse gateway spec '%= s'", r6o->gateway); } } else if (rl6->spec_flags & RTSA_REMOTE_ENDPOINT) @@ -484,8 +464,7 @@ if (r6->metric < 0) { msg(M_WARN, PACKAGE_NAME " ROUTE: route metric for network %s = (%s) must be >=3D 0", - r6o->prefix, - r6o->metric); + r6o->prefix, r6o->metric); goto fail; } r6->flags |=3D RT_METRIC_DEFINED; @@ -510,12 +489,8 @@ } void -add_route_to_option_list(struct route_option_list *l, - const char *network, - const char *netmask, - const char *gateway, - const char *metric, - int table_id) +add_route_to_option_list(struct route_option_list *l, const char *network,= const char *netmask, + const char *gateway, const char *metric, int tabl= e_id) { struct route_option *ro; ALLOC_OBJ_GC(ro, struct route_option, l->gc); @@ -526,15 +501,11 @@ ro->table_id =3D table_id; ro->next =3D l->routes; l->routes =3D ro; - } void -add_route_ipv6_to_option_list(struct route_ipv6_option_list *l, - const char *prefix, - const char *gateway, - const char *metric, - int table_id) +add_route_ipv6_to_option_list(struct route_ipv6_option_list *l, const char= *prefix, + const char *gateway, const char *metric, int= table_id) { struct route_ipv6_option *ro; ALLOC_OBJ_GC(ro, struct route_ipv6_option, l->gc); @@ -561,9 +532,7 @@ } void -route_list_add_vpn_gateway(struct route_list *rl, - struct env_set *es, - const in_addr_t addr) +route_list_add_vpn_gateway(struct route_list *rl, struct env_set *es, cons= t in_addr_t addr) { ASSERT(rl); rl->spec.remote_endpoint =3D addr; @@ -572,8 +541,7 @@ } static void -add_block_local_item(struct route_list *rl, - const struct route_gateway_address *gateway, +add_block_local_item(struct route_list *rl, const struct route_gateway_add= ress *gateway, in_addr_t target) { if (rl->rgi.gateway.netmask < 0xFFFFFFFF) @@ -585,11 +553,11 @@ ALLOC_OBJ_GC(r2, struct route_ipv4, &rl->gc); /* split a route into two smaller blocking routes, and direct them= to target */ - l2 =3D ((~gateway->netmask)+1)>>1; + l2 =3D ((~gateway->netmask) + 1) >> 1; r1->flags =3D RT_DEFINED; r1->gateway =3D target; r1->network =3D gateway->addr & gateway->netmask; - r1->netmask =3D ~(l2-1); + r1->netmask =3D ~(l2 - 1); r1->next =3D rl->routes; rl->routes =3D r1; @@ -627,21 +595,15 @@ bool block_local_needed(const struct route_list *rl) { - const int rgi_needed =3D (RGI_ADDR_DEFINED|RGI_NETMASK_DEFINED); - return (rl->flags & RG_BLOCK_LOCAL) - && (rl->rgi.flags & rgi_needed) =3D=3D rgi_needed - && (rl->spec.flags & RTSA_REMOTE_ENDPOINT) - && rl->spec.remote_host_local !=3D TLA_LOCAL; + const int rgi_needed =3D (RGI_ADDR_DEFINED | RGI_NETMASK_DEFINED); + return (rl->flags & RG_BLOCK_LOCAL) && (rl->rgi.flags & rgi_needed) = =3D=3D rgi_needed + && (rl->spec.flags & RTSA_REMOTE_ENDPOINT) && rl->spec.remote_h= ost_local !=3D TLA_LOCAL; } bool -init_route_list(struct route_list *rl, - const struct route_option_list *opt, - const char *remote_endpoint, - int default_metric, - in_addr_t remote_host, - struct env_set *es, - openvpn_net_ctx_t *ctx) +init_route_list(struct route_list *rl, const struct route_option_list *opt, + const char *remote_endpoint, int default_metric, in_addr_t= remote_host, + struct env_set *es, openvpn_net_ctx_t *ctx) { struct gc_arena gc =3D gc_new(); bool ret =3D true; @@ -683,14 +645,9 @@ if (is_route_parm_defined(remote_endpoint)) { bool defined =3D false; - rl->spec.remote_endpoint =3D getaddr( - GETADDR_RESOLVE - | GETADDR_HOST_ORDER - | GETADDR_WARN_ON_SIGNAL, - remote_endpoint, - 0, - &defined, - NULL); + rl->spec.remote_endpoint =3D + getaddr(GETADDR_RESOLVE | GETADDR_HOST_ORDER | GETADDR_WARN_ON= _SIGNAL, remote_endpoint, + 0, &defined, NULL); if (defined) { @@ -758,14 +715,13 @@ * "good enough") */ static bool -route_ipv6_match_host( const struct route_ipv6 *r6, - const struct in6_addr *host ) +route_ipv6_match_host(const struct route_ipv6 *r6, const struct in6_addr *= host) { unsigned int bits =3D r6->netbits; int i; unsigned int mask; - if (bits>128) + if (bits > 128) { return false; } @@ -783,9 +739,9 @@ return true; } - mask =3D 0xff << (8-bits); + mask =3D 0xff << (8 - bits); - if ( (r6->network.s6_addr[i] & mask) =3D=3D (host->s6_addr[i] & mask )) + if ((r6->network.s6_addr[i] & mask) =3D=3D (host->s6_addr[i] & mask)) { return true; } @@ -794,12 +750,9 @@ } bool -init_route_ipv6_list(struct route_ipv6_list *rl6, - const struct route_ipv6_option_list *opt6, - const char *remote_endpoint, - int default_metric, - const struct in6_addr *remote_host_ipv6, - struct env_set *es, +init_route_ipv6_list(struct route_ipv6_list *rl6, const struct route_ipv6_= option_list *opt6, + const char *remote_endpoint, int default_metric, + const struct in6_addr *remote_host_ipv6, struct env_s= et *es, openvpn_net_ctx_t *ctx) { struct gc_arena gc =3D gc_new(); @@ -823,7 +776,7 @@ } msg(D_ROUTE, "GDG6: remote_host_ipv6=3D%s", - remote_host_ipv6 ? print_in6_addr(*remote_host_ipv6, 0, &gc) : "n= /a" ); + remote_host_ipv6 ? print_in6_addr(*remote_host_ipv6, 0, &gc) : "n/= a"); get_default_gateway_ipv6(&rl6->rgi6, remote_host_ipv6, ctx); if (rl6->rgi6.flags & RGI_ADDR_DEFINED) @@ -838,16 +791,16 @@ dmsg(D_ROUTE, "ROUTE6: default_gateway=3DUNDEF"); } - if (is_route_parm_defined( remote_endpoint )) + if (is_route_parm_defined(remote_endpoint)) { - if (inet_pton( AF_INET6, remote_endpoint, - &rl6->remote_endpoint_ipv6) =3D=3D 1) + if (inet_pton(AF_INET6, remote_endpoint, &rl6->remote_endpoint_ipv= 6) =3D=3D 1) { rl6->spec_flags |=3D RTSA_REMOTE_ENDPOINT; } else { - msg(M_WARN, PACKAGE_NAME " ROUTE: failed to parse/resolve VPN = endpoint: %s", remote_endpoint); + msg(M_WARN, PACKAGE_NAME " ROUTE: failed to parse/resolve VPN = endpoint: %s", + remote_endpoint); ret =3D false; } } @@ -877,11 +830,11 @@ * avoiding routing loops, so ignore this part and let * need_remote_ipv6_route always evaluate to false */ - if (remote_host_ipv6 - && route_ipv6_match_host( r6, remote_host_ipv6 ) ) + if (remote_host_ipv6 && route_ipv6_match_host(r6, remote_h= ost_ipv6)) { need_remote_ipv6_route =3D true; - msg(D_ROUTE, "ROUTE6: %s/%d overlaps IPv6 remote %s, a= dding host route to VPN endpoint", + msg(D_ROUTE, + "ROUTE6: %s/%d overlaps IPv6 remote %s, adding hos= t route to VPN endpoint", print_in6_addr(r6->network, 0, &gc), r6->netbits, print_in6_addr(*remote_host_ipv6, 0, &gc)); } @@ -893,15 +846,15 @@ /* add VPN server host route if needed */ if (need_remote_ipv6_route) { - if ( (rl6->rgi6.flags & (RGI_ADDR_DEFINED|RGI_IFACE_DEFINED) ) =3D= =3D - (RGI_ADDR_DEFINED|RGI_IFACE_DEFINED) ) + if ((rl6->rgi6.flags & (RGI_ADDR_DEFINED | RGI_IFACE_DEFINED)) + =3D=3D (RGI_ADDR_DEFINED | RGI_IFACE_DEFINED)) { struct route_ipv6 *r6; ALLOC_OBJ_CLEAR_GC(r6, struct route_ipv6, &rl6->gc); r6->network =3D *remote_host_ipv6; r6->netbits =3D 128; - if (!(rl6->rgi6.flags & RGI_ON_LINK) ) + if (!(rl6->rgi6.flags & RGI_ON_LINK)) { r6->gateway =3D rl6->rgi6.gateway.addr_ipv6; } @@ -918,7 +871,8 @@ } else { - msg(M_WARN, "ROUTE6: IPv6 route overlaps with IPv6 remote addr= ess, but could not determine IPv6 gateway address + interface, expect failu= re\n" ); + msg(M_WARN, + "ROUTE6: IPv6 route overlaps with IPv6 remote address, but= could not determine IPv6 gateway address + interface, expect failure\n"); } } @@ -927,13 +881,8 @@ } static bool -add_route3(in_addr_t network, - in_addr_t netmask, - in_addr_t gateway, - const struct tuntap *tt, - unsigned int flags, - const struct route_gateway_info *rgi, - const struct env_set *es, +add_route3(in_addr_t network, in_addr_t netmask, in_addr_t gateway, const = struct tuntap *tt, + unsigned int flags, const struct route_gateway_info *rgi, const= struct env_set *es, openvpn_net_ctx_t *ctx) { struct route_ipv4 r; @@ -946,18 +895,13 @@ } static void -del_route3(in_addr_t network, - in_addr_t netmask, - in_addr_t gateway, - const struct tuntap *tt, - unsigned int flags, - const struct route_gateway_info *rgi, - const struct env_set *es, +del_route3(in_addr_t network, in_addr_t netmask, in_addr_t gateway, const = struct tuntap *tt, + unsigned int flags, const struct route_gateway_info *rgi, const= struct env_set *es, openvpn_net_ctx_t *ctx) { struct route_ipv4 r; CLEAR(r); - r.flags =3D RT_DEFINED|RT_ADDED; + r.flags =3D RT_DEFINED | RT_ADDED; r.network =3D network; r.netmask =3D netmask; r.gateway =3D gateway; @@ -965,56 +909,42 @@ } static bool -add_bypass_routes(struct route_bypass *rb, - in_addr_t gateway, - const struct tuntap *tt, - unsigned int flags, - const struct route_gateway_info *rgi, - const struct env_set *es, - openvpn_net_ctx_t *ctx) +add_bypass_routes(struct route_bypass *rb, in_addr_t gateway, const struct= tuntap *tt, + unsigned int flags, const struct route_gateway_info *rgi, + const struct env_set *es, openvpn_net_ctx_t *ctx) { int ret =3D true; for (int i =3D 0; i < rb->n_bypass; ++i) { if (rb->bypass[i]) { - ret =3D add_route3(rb->bypass[i], IPV4_NETMASK_HOST, gateway, = tt, - flags | ROUTE_REF_GW, rgi, es, ctx) && ret; + ret =3D add_route3(rb->bypass[i], IPV4_NETMASK_HOST, gateway, = tt, flags | ROUTE_REF_GW, + rgi, es, ctx) + && ret; } } return ret; } static void -del_bypass_routes(struct route_bypass *rb, - in_addr_t gateway, - const struct tuntap *tt, - unsigned int flags, - const struct route_gateway_info *rgi, - const struct env_set *es, - openvpn_net_ctx_t *ctx) +del_bypass_routes(struct route_bypass *rb, in_addr_t gateway, const struct= tuntap *tt, + unsigned int flags, const struct route_gateway_info *rgi, + const struct env_set *es, openvpn_net_ctx_t *ctx) { int i; for (i =3D 0; i < rb->n_bypass; ++i) { if (rb->bypass[i]) { - del_route3(rb->bypass[i], - IPV4_NETMASK_HOST, - gateway, - tt, - flags | ROUTE_REF_GW, - rgi, - es, + del_route3(rb->bypass[i], IPV4_NETMASK_HOST, gateway, tt, flag= s | ROUTE_REF_GW, rgi, es, ctx); } } } static bool -redirect_default_route_to_vpn(struct route_list *rl, const struct tuntap *= tt, - unsigned int flags, const struct env_set *es, - openvpn_net_ctx_t *ctx) +redirect_default_route_to_vpn(struct route_list *rl, const struct tuntap *= tt, unsigned int flags, + const struct env_set *es, openvpn_net_ctx_t = *ctx) { const char err[] =3D "NOTE: unable to redirect IPv4 default gateway --= "; bool ret =3D true; @@ -1064,9 +994,8 @@ if ((rl->spec.flags & RTSA_REMOTE_HOST) && rl->spec.remote_host !=3D IPV4_INVALID_ADDR) { - ret =3D add_route3(rl->spec.remote_host, IPV4_NETMASK_= HOST, - rl->rgi.gateway.addr, tt, flags | ROU= TE_REF_GW, - &rl->rgi, es, ctx); + ret =3D add_route3(rl->spec.remote_host, IPV4_NETMASK_= HOST, rl->rgi.gateway.addr, + tt, flags | ROUTE_REF_GW, &rl->rgi, e= s, ctx); if (ret) { rl->iflags |=3D RL_DID_LOCAL; @@ -1080,20 +1009,23 @@ #endif /* ifndef TARGET_ANDROID */ /* route DHCP/DNS server traffic through original default gate= way */ - ret =3D add_bypass_routes(&rl->spec.bypass, rl->rgi.gateway.ad= dr, tt, flags, - &rl->rgi, es, ctx) && ret; + ret =3D add_bypass_routes(&rl->spec.bypass, rl->rgi.gateway.ad= dr, tt, flags, &rl->rgi, es, + ctx) + && ret; if (rl->flags & RG_REROUTE_GW) { if (rl->flags & RG_DEF1) { /* add new default route (1st component) */ - ret =3D add_route3(0x00000000, 0x80000000, rl->spec.re= mote_endpoint, - tt, flags, &rl->rgi, es, ctx) && ret; + ret =3D add_route3(0x00000000, 0x80000000, rl->spec.re= mote_endpoint, tt, flags, + &rl->rgi, es, ctx) + && ret; /* add new default route (2nd component) */ - ret =3D add_route3(0x80000000, 0x80000000, rl->spec.re= mote_endpoint, - tt, flags, &rl->rgi, es, ctx) && ret; + ret =3D add_route3(0x80000000, 0x80000000, rl->spec.re= mote_endpoint, tt, flags, + &rl->rgi, es, ctx) + && ret; } else { @@ -1101,13 +1033,13 @@ if (rl->rgi.flags & RGI_ADDR_DEFINED) { /* delete default route */ - del_route3(0, 0, rl->rgi.gateway.addr, tt, - flags | ROUTE_REF_GW, &rl->rgi, es, ctx= ); + del_route3(0, 0, rl->rgi.gateway.addr, tt, flags |= ROUTE_REF_GW, &rl->rgi, + es, ctx); } /* add new default route */ - ret =3D add_route3(0, 0, rl->spec.remote_endpoint, tt, - flags, &rl->rgi, es, ctx) && ret; + ret =3D add_route3(0, 0, rl->spec.remote_endpoint, tt,= flags, &rl->rgi, es, ctx) + && ret; } } @@ -1119,9 +1051,8 @@ } static void -undo_redirect_default_route_to_vpn(struct route_list *rl, - const struct tuntap *tt, unsigned int f= lags, - const struct env_set *es, +undo_redirect_default_route_to_vpn(struct route_list *rl, const struct tun= tap *tt, + unsigned int flags, const struct env_se= t *es, openvpn_net_ctx_t *ctx) { if (rl && rl->iflags & RL_DID_REDIRECT_DEFAULT_GATEWAY) @@ -1129,61 +1060,35 @@ /* delete remote host route */ if (rl->iflags & RL_DID_LOCAL) { - del_route3(rl->spec.remote_host, - IPV4_NETMASK_HOST, - rl->rgi.gateway.addr, - tt, - flags | ROUTE_REF_GW, - &rl->rgi, - es, - ctx); + del_route3(rl->spec.remote_host, IPV4_NETMASK_HOST, rl->rgi.ga= teway.addr, tt, + flags | ROUTE_REF_GW, &rl->rgi, es, ctx); rl->iflags &=3D ~RL_DID_LOCAL; } /* delete special DHCP/DNS bypass route */ - del_bypass_routes(&rl->spec.bypass, rl->rgi.gateway.addr, tt, flag= s, - &rl->rgi, es, ctx); + del_bypass_routes(&rl->spec.bypass, rl->rgi.gateway.addr, tt, flag= s, &rl->rgi, es, ctx); if (rl->flags & RG_REROUTE_GW) { if (rl->flags & RG_DEF1) { /* delete default route (1st component) */ - del_route3(0x00000000, - 0x80000000, - rl->spec.remote_endpoint, - tt, - flags, - &rl->rgi, - es, - ctx); + del_route3(0x00000000, 0x80000000, rl->spec.remote_endpoin= t, tt, flags, &rl->rgi, + es, ctx); /* delete default route (2nd component) */ - del_route3(0x80000000, - 0x80000000, - rl->spec.remote_endpoint, - tt, - flags, - &rl->rgi, - es, - ctx); + del_route3(0x80000000, 0x80000000, rl->spec.remote_endpoin= t, tt, flags, &rl->rgi, + es, ctx); } else { /* delete default route */ - del_route3(0, - 0, - rl->spec.remote_endpoint, - tt, - flags, - &rl->rgi, - es, - ctx); + del_route3(0, 0, rl->spec.remote_endpoint, tt, flags, &rl-= >rgi, es, ctx); /* restore original default route if there was any */ if (rl->rgi.flags & RGI_ADDR_DEFINED) { - add_route3(0, 0, rl->rgi.gateway.addr, tt, - flags | ROUTE_REF_GW, &rl->rgi, es, ctx); + add_route3(0, 0, rl->rgi.gateway.addr, tt, flags | ROU= TE_REF_GW, &rl->rgi, es, + ctx); } } } @@ -1193,32 +1098,28 @@ } bool -add_routes(struct route_list *rl, struct route_ipv6_list *rl6, - const struct tuntap *tt, unsigned int flags, - const struct env_set *es, openvpn_net_ctx_t *ctx) +add_routes(struct route_list *rl, struct route_ipv6_list *rl6, const struc= t tuntap *tt, + unsigned int flags, const struct env_set *es, openvpn_net_ctx_t= *ctx) { bool ret =3D redirect_default_route_to_vpn(rl, tt, flags, es, ctx); - if (rl && !(rl->iflags & RL_ROUTES_ADDED) ) + if (rl && !(rl->iflags & RL_ROUTES_ADDED)) { struct route_ipv4 *r; if (rl->routes && !tt->did_ifconfig_setup) { - msg(M_INFO, "WARNING: OpenVPN was configured to add an IPv4 " + msg(M_INFO, + "WARNING: OpenVPN was configured to add an IPv4 " "route. However, no IPv4 has been configured for %s, " "therefore the route installation may fail or may not work= " - "as expected.", tt->actual_name); + "as expected.", + tt->actual_name); } #ifdef ENABLE_MANAGEMENT if (management && rl->routes) { - management_set_state(management, - OPENVPN_STATE_ADD_ROUTES, - NULL, - NULL, - NULL, - NULL, + management_set_state(management, OPENVPN_STATE_ADD_ROUTES, NUL= L, NULL, NULL, NULL, NULL); } #endif @@ -1233,16 +1134,18 @@ } rl->iflags |=3D RL_ROUTES_ADDED; } - if (rl6 && !(rl6->iflags & RL_ROUTES_ADDED) ) + if (rl6 && !(rl6->iflags & RL_ROUTES_ADDED)) { struct route_ipv6 *r; if (!tt->did_ifconfig_ipv6_setup) { - msg(M_INFO, "WARNING: OpenVPN was configured to add an IPv6 " + msg(M_INFO, + "WARNING: OpenVPN was configured to add an IPv6 " "route. However, no IPv6 has been configured for %s, " "therefore the route installation may fail or may not work= " - "as expected.", tt->actual_name); + "as expected.", + tt->actual_name); } for (r =3D rl6->routes_ipv6; r; r =3D r->next) @@ -1260,18 +1163,16 @@ } void -delete_routes(struct route_list *rl, struct route_ipv6_list *rl6, - const struct tuntap *tt, unsigned int flags, - const struct env_set *es, openvpn_net_ctx_t *ctx) +delete_routes(struct route_list *rl, struct route_ipv6_list *rl6, const st= ruct tuntap *tt, + unsigned int flags, const struct env_set *es, openvpn_net_ct= x_t *ctx) { delete_routes_v4(rl, tt, flags, es, ctx); delete_routes_v6(rl6, tt, flags, es, ctx); } void -delete_routes_v4(struct route_list *rl, const struct tuntap *tt, - unsigned int flags, const struct env_set *es, - openvpn_net_ctx_t *ctx) +delete_routes_v4(struct route_list *rl, const struct tuntap *tt, unsigned = int flags, + const struct env_set *es, openvpn_net_ctx_t *ctx) { if (rl && (rl->iflags & RL_ROUTES_ADDED)) { @@ -1292,9 +1193,8 @@ } void -delete_routes_v6(struct route_ipv6_list *rl6, const struct tuntap *tt, - unsigned int flags, const struct env_set *es, - openvpn_net_ctx_t *ctx) +delete_routes_v6(struct route_ipv6_list *rl6, const struct tuntap *tt, uns= igned int flags, + const struct env_set *es, openvpn_net_ctx_t *ctx) { if (rl6 && (rl6->iflags & RL_ROUTES_ADDED)) { @@ -1330,22 +1230,17 @@ static void print_route_option(const struct route_option *ro, int level) { - msg(level, " route %s/%s/%s/%s", - show_opt(ro->network), - show_opt(ro->netmask), - show_opt(ro->gateway), - show_opt(ro->metric)); + msg(level, " route %s/%s/%s/%s", show_opt(ro->network), show_opt(ro->= netmask), + show_opt(ro->gateway), show_opt(ro->metric)); } void -print_route_options(const struct route_option_list *rol, - int level) +print_route_options(const struct route_option_list *rol, int level) { struct route_option *ro; if (rol->flags & RG_ENABLE) { - msg(level, " [redirect_default_gateway local=3D%d]", - (rol->flags & RG_LOCAL) !=3D 0); + msg(level, " [redirect_default_gateway local=3D%d]", (rol->flags = & RG_LOCAL) !=3D 0); } for (ro =3D rol->routes; ro; ro =3D ro->next) { @@ -1354,8 +1249,7 @@ } void -print_default_gateway(const int msglevel, - const struct route_gateway_info *rgi, +print_default_gateway(const int msglevel, const struct route_gateway_info = *rgi, const struct route_ipv6_gateway_info *rgi6) { struct gc_arena gc =3D gc_new(); @@ -1486,23 +1380,22 @@ struct gc_arena gc =3D gc_new(); if (r6->flags & RT_DEFINED) { - struct buffer name1 =3D alloc_buf_gc( 256, &gc ); - struct buffer val =3D alloc_buf_gc( 256, &gc ); - struct buffer name2 =3D alloc_buf_gc( 256, &gc ); + struct buffer name1 =3D alloc_buf_gc(256, &gc); + struct buffer val =3D alloc_buf_gc(256, &gc); + struct buffer name2 =3D alloc_buf_gc(256, &gc); - buf_printf( &name1, "route_ipv6_network_%d", i ); - buf_printf( &val, "%s/%d", print_in6_addr( r6->network, 0, &gc ), - r6->netbits ); - setenv_str( es, BSTR(&name1), BSTR(&val) ); + buf_printf(&name1, "route_ipv6_network_%d", i); + buf_printf(&val, "%s/%d", print_in6_addr(r6->network, 0, &gc), r6-= >netbits); + setenv_str(es, BSTR(&name1), BSTR(&val)); - buf_printf( &name2, "route_ipv6_gateway_%d", i ); - setenv_str( es, BSTR(&name2), print_in6_addr( r6->gateway, 0, &gc = )); + buf_printf(&name2, "route_ipv6_gateway_%d", i); + setenv_str(es, BSTR(&name2), print_in6_addr(r6->gateway, 0, &gc)); if (r6->flags & RT_METRIC_DEFINED) { - struct buffer name3 =3D alloc_buf_gc( 256, &gc ); - buf_printf( &name3, "route_ipv6_metric_%d", i); - setenv_int( es, BSTR(&name3), r6->metric); + struct buffer name3 =3D alloc_buf_gc(256, &gc); + buf_printf(&name3, "route_ipv6_metric_%d", i); + setenv_int(es, BSTR(&name3), r6->metric); } } gc_free(&gc); @@ -1542,19 +1435,15 @@ #define LR_ERROR 2 /* caller should abort adding route */ static int -local_route(in_addr_t network, - in_addr_t netmask, - in_addr_t gateway, +local_route(in_addr_t network, in_addr_t netmask, in_addr_t gateway, const struct route_gateway_info *rgi) { /* set LR_MATCH on local host routes */ - const int rgi_needed =3D (RGI_ADDR_DEFINED|RGI_NETMASK_DEFINED|RGI_IFA= CE_DEFINED); - if (rgi - && (rgi->flags & rgi_needed) =3D=3D rgi_needed - && gateway =3D=3D rgi->gateway.addr + const int rgi_needed =3D (RGI_ADDR_DEFINED | RGI_NETMASK_DEFINED | RGI= _IFACE_DEFINED); + if (rgi && (rgi->flags & rgi_needed) =3D=3D rgi_needed && gateway =3D= =3D rgi->gateway.addr && netmask =3D=3D 0xFFFFFFFF) { - if (((network ^ rgi->gateway.addr) & rgi->gateway.netmask) =3D=3D= 0) + if (((network ^ rgi->gateway.addr) & rgi->gateway.netmask) =3D=3D = 0) { return LR_MATCH; } @@ -1581,17 +1470,16 @@ static inline bool is_on_link(const int is_local_route, const unsigned int flags, const struc= t route_gateway_info *rgi) { - return rgi && (is_local_route =3D=3D LR_MATCH || ((flags & ROUTE_REF_G= W) && (rgi->flags & RGI_ON_LINK))); + return rgi + && (is_local_route =3D=3D LR_MATCH + || ((flags & ROUTE_REF_GW) && (rgi->flags & RGI_ON_LINK))); } #endif bool -add_route(struct route_ipv4 *r, - const struct tuntap *tt, - unsigned int flags, - const struct route_gateway_info *rgi, /* may be NULL */ - const struct env_set *es, - openvpn_net_ctx_t *ctx) +add_route(struct route_ipv4 *r, const struct tuntap *tt, unsigned int flag= s, + const struct route_gateway_info *rgi, /* may be NULL */ + const struct env_set *es, openvpn_net_ctx_t *ctx) { int status =3D 0; int is_local_route; @@ -1634,8 +1522,8 @@ status =3D RTA_SUCCESS; - int ret =3D net_route_v4_add(ctx, &r->network, netmask_to_netbits2(r->= netmask), - &r->gateway, iface, r->table_id, metric); + int ret =3D net_route_v4_add(ctx, &r->network, netmask_to_netbits2(r->= netmask), &r->gateway, + iface, r->table_id, metric); if (ret =3D=3D -EEXIST) { msg(D_ROUTE, "NOTE: Linux route add command failed because route e= xists"); @@ -1647,7 +1535,7 @@ status =3D RTA_ERROR; } -#elif defined (TARGET_ANDROID) +#elif defined(TARGET_ANDROID) char out[128]; if (rgi) @@ -1661,15 +1549,11 @@ bool ret =3D management_android_control(management, "ROUTE", out); status =3D ret ? RTA_SUCCESS : RTA_ERROR; -#elif defined (_WIN32) +#elif defined(_WIN32) { DWORD ai =3D TUN_ADAPTER_INDEX_INVALID; - argv_printf(&argv, "%s%s ADD %s MASK %s %s", - get_win_sys_path(), - WIN_ROUTE_PATH_SUFFIX, - network, - netmask, - gateway); + argv_printf(&argv, "%s%s ADD %s MASK %s %s", get_win_sys_path(), W= IN_ROUTE_PATH_SUFFIX, + network, netmask, gateway); if (r->flags & RT_METRIC_DEFINED) { argv_printf_cat(&argv, "METRIC %d", r->metric); @@ -1695,8 +1579,8 @@ else if ((flags & ROUTE_METHOD_MASK) =3D=3D ROUTE_METHOD_EXE) { netcmd_semaphore_lock(); - bool ret =3D openvpn_execve_check(&argv, es, 0, - "ERROR: Windows route add comm= and failed"); + bool ret =3D + openvpn_execve_check(&argv, es, 0, "ERROR: Windows route a= dd command failed"); status =3D ret ? RTA_SUCCESS : RTA_ERROR; netcmd_semaphore_release(); method =3D "route.exe"; @@ -1709,8 +1593,8 @@ { msg(D_ROUTE, "Route addition fallback to route.exe"); netcmd_semaphore_lock(); - bool ret =3D openvpn_execve_check(&argv, es, 0, - "ERROR: Windows route add = command failed [adaptive]"); + bool ret =3D openvpn_execve_check( + &argv, es, 0, "ERROR: Windows route add command failed= [adaptive]"); status =3D ret ? RTA_SUCCESS : RTA_ERROR; netcmd_semaphore_release(); method =3D "route.exe"; @@ -1727,17 +1611,13 @@ } } -#elif defined (TARGET_SOLARIS) +#elif defined(TARGET_SOLARIS) /* example: route add 192.0.2.32 -netmask 255.255.255.224 somegateway = */ - argv_printf(&argv, "%s add", - ROUTE_PATH); + argv_printf(&argv, "%s add", ROUTE_PATH); - argv_printf_cat(&argv, "%s -netmask %s %s", - network, - netmask, - gateway); + argv_printf_cat(&argv, "%s -netmask %s %s", network, netmask, gateway); /* Solaris can only distinguish between "metric 0" =3D=3D "on-link on = the * interface where the IP address given is configured" and "metric > 0" @@ -1752,14 +1632,12 @@ } argv_msg(D_ROUTE, &argv); - bool ret =3D openvpn_execve_check(&argv, es, 0, - "ERROR: Solaris route add command fail= ed"); + bool ret =3D openvpn_execve_check(&argv, es, 0, "ERROR: Solaris route = add command failed"); status =3D ret ? RTA_SUCCESS : RTA_ERROR; #elif defined(TARGET_FREEBSD) - argv_printf(&argv, "%s add", - ROUTE_PATH); + argv_printf(&argv, "%s add", ROUTE_PATH); #if 0 if (r->flags & RT_METRIC_DEFINED) @@ -1768,22 +1646,17 @@ } #endif - argv_printf_cat(&argv, "-net %s %s %s", - network, - gateway, - netmask); + argv_printf_cat(&argv, "-net %s %s %s", network, gateway, netmask); /* FIXME -- add on-link support for FreeBSD */ argv_msg(D_ROUTE, &argv); - bool ret =3D openvpn_execve_check(&argv, es, 0, - "ERROR: FreeBSD route add command fail= ed"); + bool ret =3D openvpn_execve_check(&argv, es, 0, "ERROR: FreeBSD route = add command failed"); status =3D ret ? RTA_SUCCESS : RTA_ERROR; #elif defined(TARGET_DRAGONFLY) - argv_printf(&argv, "%s add", - ROUTE_PATH); + argv_printf(&argv, "%s add", ROUTE_PATH); #if 0 if (r->flags & RT_METRIC_DEFINED) @@ -1792,22 +1665,17 @@ } #endif - argv_printf_cat(&argv, "-net %s %s %s", - network, - gateway, - netmask); + argv_printf_cat(&argv, "-net %s %s %s", network, gateway, netmask); /* FIXME -- add on-link support for Dragonfly */ argv_msg(D_ROUTE, &argv); - bool ret =3D openvpn_execve_check(&argv, es, 0, - "ERROR: DragonFly route add command fa= iled"); + bool ret =3D openvpn_execve_check(&argv, es, 0, "ERROR: DragonFly rout= e add command failed"); status =3D ret ? RTA_SUCCESS : RTA_ERROR; #elif defined(TARGET_DARWIN) - argv_printf(&argv, "%s add", - ROUTE_PATH); + argv_printf(&argv, "%s add", ROUTE_PATH); #if 0 if (r->flags & RT_METRIC_DEFINED) @@ -1820,28 +1688,21 @@ { /* Mac OS X route syntax for ON_LINK: * route add -cloning -net 10.10.0.1 -netmask 255.255.255.255 -int= erface en0 */ - argv_printf_cat(&argv, "-cloning -net %s -netmask %s -interface %s= ", - network, - netmask, + argv_printf_cat(&argv, "-cloning -net %s -netmask %s -interface %s= ", network, netmask, rgi->iface); } else { - argv_printf_cat(&argv, "-net %s %s %s", - network, - gateway, - netmask); + argv_printf_cat(&argv, "-net %s %s %s", network, gateway, netmask); } argv_msg(D_ROUTE, &argv); - bool ret =3D openvpn_execve_check(&argv, es, 0, - "ERROR: OS X route add command failed"= ); + bool ret =3D openvpn_execve_check(&argv, es, 0, "ERROR: OS X route add= command failed"); status =3D ret ? RTA_SUCCESS : RTA_ERROR; #elif defined(TARGET_OPENBSD) || defined(TARGET_NETBSD) - argv_printf(&argv, "%s add", - ROUTE_PATH); + argv_printf(&argv, "%s add", ROUTE_PATH); #if 0 if (r->flags & RT_METRIC_DEFINED) @@ -1850,47 +1711,36 @@ } #endif - argv_printf_cat(&argv, "-net %s %s -netmask %s", - network, - gateway, - netmask); + argv_printf_cat(&argv, "-net %s %s -netmask %s", network, gateway, net= mask); /* FIXME -- add on-link support for OpenBSD/NetBSD */ argv_msg(D_ROUTE, &argv); - bool ret =3D openvpn_execve_check(&argv, es, 0, - "ERROR: OpenBSD/NetBSD route add comma= nd failed"); + bool ret =3D openvpn_execve_check(&argv, es, 0, "ERROR: OpenBSD/NetBSD= route add command failed"); status =3D ret ? RTA_SUCCESS : RTA_ERROR; #elif defined(TARGET_AIX) { int netbits =3D netmask_to_netbits2(r->netmask); - argv_printf(&argv, "%s add -net %s/%d %s", - ROUTE_PATH, - network, netbits, gateway); + argv_printf(&argv, "%s add -net %s/%d %s", ROUTE_PATH, network, ne= tbits, gateway); argv_msg(D_ROUTE, &argv); - bool ret =3D openvpn_execve_check(&argv, es, 0, - "ERROR: AIX route add command fail= ed"); + bool ret =3D openvpn_execve_check(&argv, es, 0, "ERROR: AIX route = add command failed"); status =3D ret ? RTA_SUCCESS : RTA_ERROR; } #elif defined(TARGET_HAIKU) /* ex: route add /dev/net/ipro1000/0 0.0.0.0 gw 192.168.1.1 netmask 12= 8.0.0.0 */ - argv_printf(&argv, "%s add %s inet %s gw %s netmask %s", - ROUTE_PATH, - rgi->iface, - network, - gateway, - netmask); + argv_printf(&argv, "%s add %s inet %s gw %s netmask %s", ROUTE_PATH, r= gi->iface, network, + gateway, netmask); argv_msg(D_ROUTE, &argv); - bool ret =3D openvpn_execve_check(&argv, es, 0, - "ERROR: Haiku inet route add command f= ailed"); + bool ret =3D openvpn_execve_check(&argv, es, 0, "ERROR: Haiku inet rou= te add command failed"); status =3D ret ? RTA_SUCCESS : RTA_ERROR; -#else /* if defined(TARGET_LINUX) */ - msg(M_FATAL, "Sorry, but I don't know how to do 'route' commands on th= is operating system. Try putting your routes in a --route-up script"); +#else /* if defined(TARGET_LINUX) */ + msg(M_FATAL, + "Sorry, but I don't know how to do 'route' commands on this operat= ing system. Try putting your routes in a --route-up script"); #endif /* if defined(TARGET_LINUX) */ done: @@ -1912,7 +1762,7 @@ void -route_ipv6_clear_host_bits( struct route_ipv6 *r6 ) +route_ipv6_clear_host_bits(struct route_ipv6 *r6) { /* clear host bit parts of route * (needed if routes are specified improperly, or if we need to @@ -1925,24 +1775,25 @@ { if (bits_to_clear >=3D 8) { - r6->network.s6_addr[byte--] =3D 0; bits_to_clear -=3D 8; + r6->network.s6_addr[byte--] =3D 0; + bits_to_clear -=3D 8; } else { - r6->network.s6_addr[byte--] &=3D (0xff << bits_to_clear); bits= _to_clear =3D 0; + r6->network.s6_addr[byte--] &=3D (0xff << bits_to_clear); + bits_to_clear =3D 0; } } } bool -add_route_ipv6(struct route_ipv6 *r6, const struct tuntap *tt, - unsigned int flags, const struct env_set *es, - openvpn_net_ctx_t *ctx) +add_route_ipv6(struct route_ipv6 *r6, const struct tuntap *tt, unsigned in= t flags, + const struct env_set *es, openvpn_net_ctx_t *ctx) { int status =3D 0; bool gateway_needed =3D false; - if (!(r6->flags & RT_DEFINED) ) + if (!(r6->flags & RT_DEFINED)) { return true; /* no error */ } @@ -1952,10 +1803,10 @@ #ifndef _WIN32 const char *device =3D tt->actual_name; - if (r6->iface !=3D NULL) /* vpn server special route */ + if (r6->iface !=3D NULL) /* vpn server special route */ { device =3D r6->iface; - if (!IN6_IS_ADDR_UNSPECIFIED(&r6->gateway) ) + if (!IN6_IS_ADDR_UNSPECIFIED(&r6->gateway)) { gateway_needed =3D true; } @@ -1963,11 +1814,10 @@ #endif route_ipv6_clear_host_bits(r6); - const char *network =3D print_in6_addr( r6->network, 0, &gc); - const char *gateway =3D print_in6_addr( r6->gateway, 0, &gc); + const char *network =3D print_in6_addr(r6->network, 0, &gc); + const char *gateway =3D print_in6_addr(r6->gateway, 0, &gc); -#if defined(TARGET_DARWIN) \ - || defined(TARGET_FREEBSD) || defined(TARGET_DRAGONFLY) \ +#if defined(TARGET_DARWIN) || defined(TARGET_FREEBSD) || defined(TARGET_DR= AGONFLY) \ || defined(TARGET_OPENBSD) || defined(TARGET_NETBSD) /* the BSD platforms cannot specify gateway and interface independentl= y, @@ -1975,22 +1825,21 @@ * we build a combined "$gateway%$interface" gateway string */ if (r6->iface !=3D NULL && gateway_needed - && IN6_IS_ADDR_LINKLOCAL(&r6->gateway) ) /* fe80::...%intf = */ + && IN6_IS_ADDR_LINKLOCAL(&r6->gateway)) /* fe80::...%intf */ { - int len =3D strlen(gateway) + 1 + strlen(r6->iface)+1; - char *tmp =3D gc_malloc( len, true, &gc ); - snprintf( tmp, len, "%s%%%s", gateway, r6->iface ); + int len =3D strlen(gateway) + 1 + strlen(r6->iface) + 1; + char *tmp =3D gc_malloc(len, true, &gc); + snprintf(tmp, len, "%s%%%s", gateway, r6->iface); gateway =3D tmp; } #endif #ifndef _WIN32 - msg(D_ROUTE, "add_route_ipv6(%s/%d -> %s metric %d) dev %s", - network, r6->netbits, gateway, r6->metric, device ); + msg(D_ROUTE, "add_route_ipv6(%s/%d -> %s metric %d) dev %s", network, = r6->netbits, gateway, + r6->metric, device); #else - msg(D_ROUTE, "add_route_ipv6(%s/%d -> %s metric %d) IF %lu", - network, r6->netbits, gateway, r6->metric, - r6->adapter_index ? r6->adapter_index : tt->adapter_index); + msg(D_ROUTE, "add_route_ipv6(%s/%d -> %s metric %d) IF %lu", network, = r6->netbits, gateway, + r6->metric, r6->adapter_index ? r6->adapter_index : tt->adapter_in= dex); #endif /* @@ -2004,18 +1853,19 @@ * interfaces. OTOH, on "tap" interface, we must always set the * gateway unless the route is to be an on-link network */ - if (tt->type =3D=3D DEV_TYPE_TAP - && !( (r6->flags & RT_METRIC_DEFINED) && r6->metric =3D=3D 0 ) ) + if (tt->type =3D=3D DEV_TYPE_TAP && !((r6->flags & RT_METRIC_DEFINED) = && r6->metric =3D=3D 0)) { gateway_needed =3D true; } if (gateway_needed && IN6_IS_ADDR_UNSPECIFIED(&r6->gateway)) { - msg(M_WARN, "ROUTE6 WARNING: " PACKAGE_NAME " needs a gateway " + msg(M_WARN, + "ROUTE6 WARNING: " PACKAGE_NAME " needs a gateway " "parameter for a --route-ipv6 option and no default was set vi= a " "--ifconfig-ipv6 or --route-ipv6-gateway option. Not installi= ng " - "IPv6 route to %s/%d.", network, r6->netbits); + "IPv6 route to %s/%d.", + network, r6->netbits); status =3D 0; goto done; } @@ -2028,8 +1878,7 @@ } status =3D RTA_SUCCESS; - int ret =3D net_route_v6_add(ctx, &r6->network, r6->netbits, - gateway_needed ? &r6->gateway : NULL, + int ret =3D net_route_v6_add(ctx, &r6->network, r6->netbits, gateway_n= eeded ? &r6->gateway : NULL, device, r6->table_id, metric); if (ret =3D=3D -EEXIST) { @@ -2042,14 +1891,14 @@ status =3D RTA_ERROR; } -#elif defined (TARGET_ANDROID) +#elif defined(TARGET_ANDROID) char out[64]; snprintf(out, sizeof(out), "%s/%d %s", network, r6->netbits, device); status =3D management_android_control(management, "ROUTE6", out); -#elif defined (_WIN32) +#elif defined(_WIN32) if (tt->options.msg_channel) { @@ -2059,7 +1908,7 @@ { status =3D route_ipv6_ipapi(true, r6, tt); } -#elif defined (TARGET_SOLARIS) +#elif defined(TARGET_SOLARIS) /* example: route add -inet6 2001:db8::/32 somegateway 0 */ @@ -2072,11 +1921,7 @@ * use the GW addresses - it seems to still work for fe80:: addresses, * however this is done internally. NUD maybe?) */ - argv_printf(&argv, "%s add -inet6 %s/%d %s", - ROUTE_PATH, - network, - r6->netbits, - gateway ); + argv_printf(&argv, "%s add -inet6 %s/%d %s", ROUTE_PATH, network, r6->= netbits, gateway); /* on tun (not tap), not "elsewhere"? -> metric 0 */ if (tt->type =3D=3D DEV_TYPE_TUN && !r6->iface) @@ -2085,16 +1930,12 @@ } argv_msg(D_ROUTE, &argv); - bool ret =3D openvpn_execve_check(&argv, es, 0, - "ERROR: Solaris route add -inet6 comma= nd failed"); + bool ret =3D openvpn_execve_check(&argv, es, 0, "ERROR: Solaris route = add -inet6 command failed"); status =3D ret ? RTA_SUCCESS : RTA_ERROR; #elif defined(TARGET_FREEBSD) || defined(TARGET_DRAGONFLY) - argv_printf(&argv, "%s add -inet6 %s/%d", - ROUTE_PATH, - network, - r6->netbits); + argv_printf(&argv, "%s add -inet6 %s/%d", ROUTE_PATH, network, r6->net= bits); if (gateway_needed) { @@ -2106,15 +1947,12 @@ } argv_msg(D_ROUTE, &argv); - bool ret =3D openvpn_execve_check(&argv, es, 0, - "ERROR: *BSD route add -inet6 command = failed"); + bool ret =3D openvpn_execve_check(&argv, es, 0, "ERROR: *BSD route add= -inet6 command failed"); status =3D ret ? RTA_SUCCESS : RTA_ERROR; #elif defined(TARGET_DARWIN) - argv_printf(&argv, "%s add -inet6 %s -prefixlen %d", - ROUTE_PATH, - network, r6->netbits ); + argv_printf(&argv, "%s add -inet6 %s -prefixlen %d", ROUTE_PATH, netwo= rk, r6->netbits); if (gateway_needed) { @@ -2126,58 +1964,45 @@ } argv_msg(D_ROUTE, &argv); - bool ret =3D openvpn_execve_check(&argv, es, 0, - "ERROR: MacOS X route add -inet6 comma= nd failed"); + bool ret =3D openvpn_execve_check(&argv, es, 0, "ERROR: MacOS X route = add -inet6 command failed"); status =3D ret ? RTA_SUCCESS : RTA_ERROR; #elif defined(TARGET_OPENBSD) - argv_printf(&argv, "%s add -inet6 %s -prefixlen %d %s", - ROUTE_PATH, - network, r6->netbits, gateway ); + argv_printf(&argv, "%s add -inet6 %s -prefixlen %d %s", ROUTE_PATH, ne= twork, r6->netbits, + gateway); argv_msg(D_ROUTE, &argv); - bool ret =3D openvpn_execve_check(&argv, es, 0, - "ERROR: OpenBSD route add -inet6 comma= nd failed"); + bool ret =3D openvpn_execve_check(&argv, es, 0, "ERROR: OpenBSD route = add -inet6 command failed"); status =3D ret ? RTA_SUCCESS : RTA_ERROR; #elif defined(TARGET_NETBSD) - argv_printf(&argv, "%s add -inet6 %s/%d %s", - ROUTE_PATH, - network, r6->netbits, gateway ); + argv_printf(&argv, "%s add -inet6 %s/%d %s", ROUTE_PATH, network, r6->= netbits, gateway); argv_msg(D_ROUTE, &argv); - bool ret =3D openvpn_execve_check(&argv, es, 0, - "ERROR: NetBSD route add -inet6 comman= d failed"); + bool ret =3D openvpn_execve_check(&argv, es, 0, "ERROR: NetBSD route a= dd -inet6 command failed"); status =3D ret ? RTA_SUCCESS : RTA_ERROR; #elif defined(TARGET_AIX) - argv_printf(&argv, "%s add -inet6 %s/%d %s", - ROUTE_PATH, - network, r6->netbits, gateway); + argv_printf(&argv, "%s add -inet6 %s/%d %s", ROUTE_PATH, network, r6->= netbits, gateway); argv_msg(D_ROUTE, &argv); - bool ret =3D openvpn_execve_check(&argv, es, 0, - "ERROR: AIX route add command failed"); + bool ret =3D openvpn_execve_check(&argv, es, 0, "ERROR: AIX route add = command failed"); status =3D ret ? RTA_SUCCESS : RTA_ERROR; #elif defined(TARGET_HAIKU) /* ex: route add /dev/net/ipro1000/0 inet6 :: gw beef::cafe prefixlen = 64 */ - argv_printf(&argv, "%s add %s inet6 %s gw %s prefixlen %d", - ROUTE_PATH, - r6->iface, - network, - gateway, - r6->netbits); + argv_printf(&argv, "%s add %s inet6 %s gw %s prefixlen %d", ROUTE_PATH= , r6->iface, network, + gateway, r6->netbits); argv_msg(D_ROUTE, &argv); - bool ret =3D openvpn_execve_check(&argv, es, 0, - "ERROR: Haiku inet6 route add command = failed"); + bool ret =3D openvpn_execve_check(&argv, es, 0, "ERROR: Haiku inet6 ro= ute add command failed"); status =3D ret ? RTA_SUCCESS : RTA_ERROR; #else /* if defined(TARGET_LINUX) */ - msg(M_FATAL, "Sorry, but I don't know how to do 'route ipv6' commands = on this operating system. Try putting your routes in a --route-up script"); + msg(M_FATAL, + "Sorry, but I don't know how to do 'route ipv6' commands on this o= perating system. Try putting your routes in a --route-up script"); #endif /* if defined(TARGET_LINUX) */ done: @@ -2198,12 +2023,8 @@ } static void -delete_route(struct route_ipv4 *r, - const struct tuntap *tt, - unsigned int flags, - const struct route_gateway_info *rgi, - const struct env_set *es, - openvpn_net_ctx_t *ctx) +delete_route(struct route_ipv4 *r, const struct tuntap *tt, unsigned int f= lags, + const struct route_gateway_info *rgi, const struct env_set *e= s, openvpn_net_ctx_t *ctx) { #if !defined(TARGET_LINUX) const char *network; @@ -2213,12 +2034,12 @@ #if !defined(TARGET_ANDROID) const char *gateway; #endif -#else /* if !defined(TARGET_LINUX) */ +#else /* if !defined(TARGET_LINUX) */ int metric; #endif int is_local_route; - if ((r->flags & (RT_DEFINED|RT_ADDED)) !=3D (RT_DEFINED|RT_ADDED)) + if ((r->flags & (RT_DEFINED | RT_ADDED)) !=3D (RT_DEFINED | RT_ADDED)) { return; } @@ -2249,19 +2070,16 @@ metric =3D r->metric; } - if (net_route_v4_del(ctx, &r->network, netmask_to_netbits2(r->netmask), - &r->gateway, NULL, r->table_id, metric) < 0) + if (net_route_v4_del(ctx, &r->network, netmask_to_netbits2(r->netmask)= , &r->gateway, NULL, + r->table_id, metric) + < 0) { msg(M_WARN, "ERROR: Linux route delete command failed"); } -#elif defined (_WIN32) +#elif defined(_WIN32) - argv_printf(&argv, "%s%s DELETE %s MASK %s %s", - get_win_sys_path(), - WIN_ROUTE_PATH_SUFFIX, - network, - netmask, - gateway); + argv_printf(&argv, "%s%s DELETE %s MASK %s %s", get_win_sys_path(), WI= N_ROUTE_PATH_SUFFIX, + network, netmask, gateway); argv_msg(D_ROUTE, &argv); @@ -2289,7 +2107,8 @@ { msg(D_ROUTE, "Route deletion fallback to route.exe"); netcmd_semaphore_lock(); - openvpn_execve_check(&argv, es, 0, "ERROR: Windows route delet= e command failed [adaptive]"); + openvpn_execve_check(&argv, es, 0, + "ERROR: Windows route delete command fail= ed [adaptive]"); netcmd_semaphore_release(); } } @@ -2298,35 +2117,23 @@ ASSERT(0); } -#elif defined (TARGET_SOLARIS) +#elif defined(TARGET_SOLARIS) - argv_printf(&argv, "%s delete %s -netmask %s %s", - ROUTE_PATH, - network, - netmask, - gateway); + argv_printf(&argv, "%s delete %s -netmask %s %s", ROUTE_PATH, network,= netmask, gateway); argv_msg(D_ROUTE, &argv); openvpn_execve_check(&argv, es, 0, "ERROR: Solaris route delete comman= d failed"); #elif defined(TARGET_FREEBSD) - argv_printf(&argv, "%s delete -net %s %s %s", - ROUTE_PATH, - network, - gateway, - netmask); + argv_printf(&argv, "%s delete -net %s %s %s", ROUTE_PATH, network, gat= eway, netmask); argv_msg(D_ROUTE, &argv); openvpn_execve_check(&argv, es, 0, "ERROR: FreeBSD route delete comman= d failed"); #elif defined(TARGET_DRAGONFLY) - argv_printf(&argv, "%s delete -net %s %s %s", - ROUTE_PATH, - network, - gateway, - netmask); + argv_printf(&argv, "%s delete -net %s %s %s", ROUTE_PATH, network, gat= eway, netmask); argv_msg(D_ROUTE, &argv); openvpn_execve_check(&argv, es, 0, "ERROR: DragonFly route delete comm= and failed"); @@ -2335,19 +2142,12 @@ if (is_on_link(is_local_route, flags, rgi)) { - argv_printf(&argv, "%s delete -cloning -net %s -netmask %s -interf= ace %s", - ROUTE_PATH, - network, - netmask, - rgi->iface); + argv_printf(&argv, "%s delete -cloning -net %s -netmask %s -interf= ace %s", ROUTE_PATH, + network, netmask, rgi->iface); } else { - argv_printf(&argv, "%s delete -net %s %s %s", - ROUTE_PATH, - network, - gateway, - netmask); + argv_printf(&argv, "%s delete -net %s %s %s", ROUTE_PATH, network,= gateway, netmask); } argv_msg(D_ROUTE, &argv); @@ -2355,26 +2155,20 @@ #elif defined(TARGET_OPENBSD) || defined(TARGET_NETBSD) - argv_printf(&argv, "%s delete -net %s %s -netmask %s", - ROUTE_PATH, - network, - gateway, - netmask); + argv_printf(&argv, "%s delete -net %s %s -netmask %s", ROUTE_PATH, net= work, gateway, netmask); argv_msg(D_ROUTE, &argv); openvpn_execve_check(&argv, es, 0, "ERROR: OpenBSD/NetBSD route delete= command failed"); #elif defined(TARGET_ANDROID) msg(D_ROUTE_DEBUG, "Deleting routes on Android is not possible/not " - "needed. The VpnService API allows routes to be set " - "on connect only and will clean up automatically."); + "needed. The VpnService API allows routes to be set= " + "on connect only and will clean up automatically."); #elif defined(TARGET_AIX) =20 { int netbits =3D netmask_to_netbits2(r->netmask); - argv_printf(&argv, "%s delete -net %s/%d %s", - ROUTE_PATH, - network, netbits, gateway); + argv_printf(&argv, "%s delete -net %s/%d %s", ROUTE_PATH, network,= netbits, gateway); argv_msg(D_ROUTE, &argv); openvpn_execve_check(&argv, es, 0, "ERROR: AIX route delete comman= d failed"); } @@ -2382,17 +2176,14 @@ #elif defined(TARGET_HAIKU) /* ex: route delete /dev/net/ipro1000/0 inet 192.168.0.0 gw 192.168.1.= 1 netmask 255.255.0.0 */ - argv_printf(&argv, "%s delete %s inet %s gw %s netmask %s", - ROUTE_PATH, - rgi->iface, - network, - gateway, - netmask); + argv_printf(&argv, "%s delete %s inet %s gw %s netmask %s", ROUTE_PATH= , rgi->iface, network, + gateway, netmask); argv_msg(D_ROUTE, &argv); openvpn_execve_check(&argv, es, 0, "ERROR: Haiku inet route delete com= mand failed"); #else /* if defined(TARGET_LINUX) */ - msg(M_FATAL, "Sorry, but I don't know how to do 'route' commands on th= is operating system. Try putting your routes in a --route-up script"); + msg(M_FATAL, + "Sorry, but I don't know how to do 'route' commands on this operat= ing system. Try putting your routes in a --route-up script"); #endif /* if defined(TARGET_LINUX) */ done: @@ -2404,13 +2195,12 @@ } void -delete_route_ipv6(const struct route_ipv6 *r6, const struct tuntap *tt, - const struct env_set *es, +delete_route_ipv6(const struct route_ipv6 *r6, const struct tuntap *tt, co= nst struct env_set *es, openvpn_net_ctx_t *ctx) { const char *network; - if ((r6->flags & (RT_DEFINED|RT_ADDED)) !=3D (RT_DEFINED|RT_ADDED)) + if ((r6->flags & (RT_DEFINED | RT_ADDED)) !=3D (RT_DEFINED | RT_ADDED)) { return; } @@ -2422,7 +2212,7 @@ #if !defined(TARGET_SOLARIS) bool gateway_needed =3D false; const char *device =3D tt->actual_name; - if (r6->iface !=3D NULL) /* vpn server special route */ + if (r6->iface !=3D NULL) /* vpn server special route */ { device =3D r6->iface; gateway_needed =3D true; @@ -2431,8 +2221,7 @@ /* if we used a gateway on "add route", we also need to specify it on * delete, otherwise some OSes will refuse to delete the route */ - if (tt->type =3D=3D DEV_TYPE_TAP - && !( (r6->flags & RT_METRIC_DEFINED) && r6->metric =3D=3D 0 ) ) + if (tt->type =3D=3D DEV_TYPE_TAP && !((r6->flags & RT_METRIC_DEFINED) = && r6->metric =3D=3D 0)) { gateway_needed =3D true; } @@ -2442,13 +2231,12 @@ struct gc_arena gc =3D gc_new(); struct argv argv =3D argv_new(); - network =3D print_in6_addr( r6->network, 0, &gc); + network =3D print_in6_addr(r6->network, 0, &gc); #if !defined(TARGET_LINUX) && !defined(_WIN32) - gateway =3D print_in6_addr( r6->gateway, 0, &gc); + gateway =3D print_in6_addr(r6->gateway, 0, &gc); #endif -#if defined(TARGET_DARWIN) \ - || defined(TARGET_FREEBSD) || defined(TARGET_DRAGONFLY) \ +#if defined(TARGET_DARWIN) || defined(TARGET_FREEBSD) || defined(TARGET_DR= AGONFLY) \ || defined(TARGET_OPENBSD) || defined(TARGET_NETBSD) /* the BSD platforms cannot specify gateway and interface independentl= y, @@ -2456,16 +2244,16 @@ * we build a combined "$gateway%$interface" gateway string */ if (r6->iface !=3D NULL && gateway_needed - && IN6_IS_ADDR_LINKLOCAL(&r6->gateway) ) /* fe80::...%intf = */ + && IN6_IS_ADDR_LINKLOCAL(&r6->gateway)) /* fe80::...%intf */ { - int len =3D strlen(gateway) + 1 + strlen(r6->iface)+1; - char *tmp =3D gc_malloc( len, true, &gc ); - snprintf( tmp, len, "%s%%%s", gateway, r6->iface ); + int len =3D strlen(gateway) + 1 + strlen(r6->iface) + 1; + char *tmp =3D gc_malloc(len, true, &gc); + snprintf(tmp, len, "%s%%%s", gateway, r6->iface); gateway =3D tmp; } #endif - msg(D_ROUTE, "delete_route_ipv6(%s/%d)", network, r6->netbits ); + msg(D_ROUTE, "delete_route_ipv6(%s/%d)", network, r6->netbits); #if defined(TARGET_LINUX) int metric =3D -1; @@ -2474,14 +2262,14 @@ metric =3D r6->metric; } - if (net_route_v6_del(ctx, &r6->network, r6->netbits, - gateway_needed ? &r6->gateway : NULL, device, r6-= >table_id, - metric) < 0) + if (net_route_v6_del(ctx, &r6->network, r6->netbits, gateway_needed ? = &r6->gateway : NULL, + device, r6->table_id, metric) + < 0) { msg(M_WARN, "ERROR: Linux route v6 delete command failed"); } -#elif defined (_WIN32) +#elif defined(_WIN32) if (tt->options.msg_channel) { @@ -2491,25 +2279,18 @@ { route_ipv6_ipapi(false, r6, tt); } -#elif defined (TARGET_SOLARIS) +#elif defined(TARGET_SOLARIS) /* example: route delete -inet6 2001:db8::/32 somegateway */ - argv_printf(&argv, "%s delete -inet6 %s/%d %s", - ROUTE_PATH, - network, - r6->netbits, - gateway ); + argv_printf(&argv, "%s delete -inet6 %s/%d %s", ROUTE_PATH, network, r= 6->netbits, gateway); argv_msg(D_ROUTE, &argv); openvpn_execve_check(&argv, es, 0, "ERROR: Solaris route delete -inet6= command failed"); #elif defined(TARGET_FREEBSD) || defined(TARGET_DRAGONFLY) - argv_printf(&argv, "%s delete -inet6 %s/%d", - ROUTE_PATH, - network, - r6->netbits ); + argv_printf(&argv, "%s delete -inet6 %s/%d", ROUTE_PATH, network, r6->= netbits); if (gateway_needed) { @@ -2525,9 +2306,7 @@ #elif defined(TARGET_DARWIN) - argv_printf(&argv, "%s delete -inet6 %s -prefixlen %d", - ROUTE_PATH, - network, r6->netbits ); + argv_printf(&argv, "%s delete -inet6 %s -prefixlen %d", ROUTE_PATH, ne= twork, r6->netbits); if (gateway_needed) { @@ -2543,48 +2322,40 @@ #elif defined(TARGET_OPENBSD) - argv_printf(&argv, "%s delete -inet6 %s -prefixlen %d %s", - ROUTE_PATH, - network, r6->netbits, gateway ); + argv_printf(&argv, "%s delete -inet6 %s -prefixlen %d %s", ROUTE_PATH,= network, r6->netbits, + gateway); argv_msg(D_ROUTE, &argv); openvpn_execve_check(&argv, es, 0, "ERROR: OpenBSD route delete -inet6= command failed"); #elif defined(TARGET_NETBSD) - argv_printf(&argv, "%s delete -inet6 %s/%d %s", - ROUTE_PATH, - network, r6->netbits, gateway ); + argv_printf(&argv, "%s delete -inet6 %s/%d %s", ROUTE_PATH, network, r= 6->netbits, gateway); argv_msg(D_ROUTE, &argv); openvpn_execve_check(&argv, es, 0, "ERROR: NetBSD route delete -inet6 = command failed"); #elif defined(TARGET_AIX) - argv_printf(&argv, "%s delete -inet6 %s/%d %s", - ROUTE_PATH, - network, r6->netbits, gateway); + argv_printf(&argv, "%s delete -inet6 %s/%d %s", ROUTE_PATH, network, r= 6->netbits, gateway); argv_msg(D_ROUTE, &argv); openvpn_execve_check(&argv, es, 0, "ERROR: AIX route add command faile= d"); #elif defined(TARGET_ANDROID) msg(D_ROUTE_DEBUG, "Deleting routes on Android is not possible/not " - "needed. The VpnService API allows routes to be set " - "on connect only and will clean up automatically."); + "needed. The VpnService API allows routes to be set= " + "on connect only and will clean up automatically."); #elif defined(TARGET_HAIKU) /* ex: route delete /dev/net/ipro1000/0 inet6 :: gw beef::cafe prefixl= en 64 */ - argv_printf(&argv, "%s delete %s inet6 %s gw %s prefixlen %d", - ROUTE_PATH, - r6->iface, - network, - gateway, - r6->netbits); + argv_printf(&argv, "%s delete %s inet6 %s gw %s prefixlen %d", ROUTE_P= ATH, r6->iface, network, + gateway, r6->netbits); argv_msg(D_ROUTE, &argv); openvpn_execve_check(&argv, es, 0, "ERROR: Haiku inet6 route delete co= mmand failed"); #else /* if defined(TARGET_LINUX) */ - msg(M_FATAL, "Sorry, but I don't know how to do 'route ipv6' commands = on this operating system. Try putting your routes in a --route-down script= "); + msg(M_FATAL, + "Sorry, but I don't know how to do 'route ipv6' commands on this o= perating system. Try putting your routes in a --route-down script"); #endif /* if defined(TARGET_LINUX) */ argv_free(&argv); @@ -2610,13 +2381,12 @@ status =3D GetIpForwardTable(NULL, &size, TRUE); if (status =3D=3D ERROR_INSUFFICIENT_BUFFER) { - rt =3D (PMIB_IPFORWARDTABLE) gc_malloc(size, false, gc); + rt =3D (PMIB_IPFORWARDTABLE)gc_malloc(size, false, gc); status =3D GetIpForwardTable(rt, &size, TRUE); if (status !=3D NO_ERROR) { msg(D_ROUTE, "NOTE: GetIpForwardTable returned error: %s (code= =3D%u)", - strerror_win32(status, gc), - (unsigned int)status); + strerror_win32(status, gc), (unsigned int)status); rt =3D NULL; } } @@ -2624,9 +2394,7 @@ } static int -test_route(const IP_ADAPTER_INFO *adapters, - const in_addr_t gateway, - DWORD *index) +test_route(const IP_ADAPTER_INFO *adapters, const in_addr_t gateway, DWORD= *index) { int count =3D 0; DWORD i =3D adapter_index_of_ip(adapters, gateway, &count, NULL); @@ -2638,11 +2406,7 @@ } static void -test_route_helper(bool *ret, - int *count, - int *good, - int *ambig, - const IP_ADAPTER_INFO *adapters, +test_route_helper(bool *ret, int *count, int *good, int *ambig, const IP_A= DAPTER_INFO *adapters, const in_addr_t gateway) { int c; @@ -2702,13 +2466,8 @@ } } - msg(D_ROUTE, "TEST ROUTES: %d/%d succeeded len=3D%d ret=3D%d a=3D%d u/= d=3D%s", - good, - count, - len, - (int)ret, - ambig, - adapter_up ? "up" : "down"); + msg(D_ROUTE, "TEST ROUTES: %d/%d succeeded len=3D%d ret=3D%d a=3D%d u/= d=3D%s", good, count, len, + (int)ret, ambig, adapter_up ? "up" : "down"); gc_free(&gc); return ret; @@ -2732,12 +2491,9 @@ const DWORD index =3D row->dwForwardIfIndex; const DWORD metric =3D row->dwForwardMetric1; - dmsg(D_ROUTE_DEBUG, "GDGR: route[%lu] %s/%s i=3D%d m=3D%d", - i, - print_in_addr_t((in_addr_t) net, 0, &gc), - print_in_addr_t((in_addr_t) mask, 0, &gc), - (int)index, - (int)metric); + dmsg(D_ROUTE_DEBUG, "GDGR: route[%lu] %s/%s i=3D%d m=3D%d", i, + print_in_addr_t((in_addr_t)net, 0, &gc), print_in_addr_t(= (in_addr_t)mask, 0, &gc), + (int)index, (int)metric); if (!net && !mask && metric < lowest_metric) { @@ -2778,8 +2534,7 @@ if (status !=3D NO_ERROR) { msg(D_ROUTE, "NOTE: GetBestInterfaceEx returned error: %s (code=3D= %u)", - strerror_win32(status, gc), - (unsigned int)status); + strerror_win32(status, gc), (unsigned int)status); goto done; } @@ -2790,13 +2545,11 @@ CLEAR(luid); SOCKADDR_INET best_src; CLEAR(best_src); - status =3D GetBestRoute2(&luid, best_if_index, NULL, - dest, 0, best_route, &best_src); + status =3D GetBestRoute2(&luid, best_if_index, NULL, dest, 0, best_rou= te, &best_src); if (status !=3D NO_ERROR) { msg(D_ROUTE, "NOTE: GetIpForwardEntry2 returned error: %s (code=3D= %u)", - strerror_win32(status, gc), - (unsigned int)status); + strerror_win32(status, gc), (unsigned int)status); goto done; } @@ -2887,13 +2640,10 @@ else if (count > 1) { msg(M_WARN, "Warning: route gateway is ambiguous: %s (%d matches)", - print_in_addr_t(r->gateway, 0, &gc), - count); + print_in_addr_t(r->gateway, 0, &gc), count); } - dmsg(D_ROUTE_DEBUG, "DEBUG: route find if: on_tun=3D%d count=3D%d inde= x=3D%d", - on_tun, - count, + dmsg(D_ROUTE_DEBUG, "DEBUG: route find if: on_tun=3D%d count=3D%d inde= x=3D%d", on_tun, count, (int)ret); gc_free(&gc); @@ -2906,8 +2656,8 @@ * https://msdn.microsoft.com/en-us/library/windows/desktop/aa814411(v=3Dv= s.85).aspx */ void -get_default_gateway_ipv6(struct route_ipv6_gateway_info *rgi6, - const struct in6_addr *dest, openvpn_net_ctx_t *c= tx) +get_default_gateway_ipv6(struct route_ipv6_gateway_info *rgi6, const struc= t in6_addr *dest, + openvpn_net_ctx_t *ctx) { struct gc_arena gc =3D gc_new(); CLEAR(*rgi6); @@ -2929,23 +2679,19 @@ goto done; } - msg( D_ROUTE, "GDG6: II=3D%lu DP=3D%s/%d NH=3D%s", - BestRoute.InterfaceIndex, - print_in6_addr( BestRoute.DestinationPrefix.Prefix.Ipv6.sin6_addr= , 0, &gc), - BestRoute.DestinationPrefix.PrefixLength, - print_in6_addr( BestRoute.NextHop.Ipv6.sin6_addr, 0, &gc) ); - msg( D_ROUTE, "GDG6: Metric=3D%d, Loopback=3D%d, AA=3D%d, I=3D%d", - (int) BestRoute.Metric, - (int) BestRoute.Loopback, - (int) BestRoute.AutoconfigureAddress, - (int) BestRoute.Immortal ); + msg(D_ROUTE, "GDG6: II=3D%lu DP=3D%s/%d NH=3D%s", BestRoute.InterfaceI= ndex, + print_in6_addr(BestRoute.DestinationPrefix.Prefix.Ipv6.sin6_addr, = 0, &gc), + BestRoute.DestinationPrefix.PrefixLength, + print_in6_addr(BestRoute.NextHop.Ipv6.sin6_addr, 0, &gc)); + msg(D_ROUTE, "GDG6: Metric=3D%d, Loopback=3D%d, AA=3D%d, I=3D%d", (int= )BestRoute.Metric, + (int)BestRoute.Loopback, (int)BestRoute.AutoconfigureAddress, (int= )BestRoute.Immortal); rgi6->gateway.addr_ipv6 =3D BestRoute.NextHop.Ipv6.sin6_addr; - rgi6->adapter_index =3D BestRoute.InterfaceIndex; + rgi6->adapter_index =3D BestRoute.InterfaceIndex; rgi6->flags |=3D RGI_ADDR_DEFINED | RGI_IFACE_DEFINED; /* on-link is signalled by receiving an empty (::) NextHop */ - if (IN6_IS_ADDR_UNSPECIFIED(&BestRoute.NextHop.Ipv6.sin6_addr) ) + if (IN6_IS_ADDR_UNSPECIFIED(&BestRoute.NextHop.Ipv6.sin6_addr)) { rgi6->flags |=3D RGI_ON_LINK; } @@ -2961,7 +2707,9 @@ struct gc_arena gc =3D gc_new(); int ret =3D RTA_ERROR; DWORD status; - const DWORD if_index =3D (adapter_index =3D=3D TUN_ADAPTER_INDEX_INVAL= ID) ? windows_route_find_if_index(r, tt) : adapter_index; + const DWORD if_index =3D (adapter_index =3D=3D TUN_ADAPTER_INDEX_INVAL= ID) + ? windows_route_find_if_index(r, tt) + : adapter_index; if (if_index !=3D TUN_ADAPTER_INDEX_INVALID) { @@ -2972,7 +2720,7 @@ fr.dwForwardPolicy =3D 0; fr.dwForwardNextHop =3D htonl(r->gateway); fr.dwForwardIfIndex =3D if_index; - fr.dwForwardType =3D 4; /* the next hop is not the final dest */ + fr.dwForwardType =3D 4; /* the next hop is not the final dest */ fr.dwForwardProto =3D 3; /* PROTO_IP_NETMGMT */ fr.dwForwardAge =3D 0; fr.dwForwardNextHopAS =3D 0; @@ -2985,8 +2733,7 @@ if ((r->network & r->netmask) !=3D r->network) { msg(M_WARN, "Warning: address %s is not a network address in r= elation to netmask %s", - print_in_addr_t(r->network, 0, &gc), - print_in_addr_t(r->netmask, 0, &gc)); + print_in_addr_t(r->network, 0, &gc), print_in_addr_t(r->ne= tmask, 0, &gc)); } status =3D CreateIpForwardEntry(&fr); @@ -3002,20 +2749,22 @@ else { /* failed, try increasing the metric to work around Vista issu= e */ - const unsigned int forward_metric_limit =3D 2048; /* iterative= ly retry higher metrics up to this limit */ + const unsigned int forward_metric_limit =3D + 2048; /* iteratively retry higher metrics up to this limit= */ for (; fr.dwForwardMetric1 <=3D forward_metric_limit; ++fr.dwF= orwardMetric1) { - /* try a different forward type=3D3 ("the next hop is the = final dest") in addition to 4. + /* try a different forward type=3D3 ("the next hop is the = final dest") in addition + * to 4. * --redirect-gateway over RRAS seems to need this. */ for (fr.dwForwardType =3D 4; fr.dwForwardType >=3D 3; --fr= .dwForwardType) { status =3D CreateIpForwardEntry(&fr); if (status =3D=3D NO_ERROR) { - msg(D_ROUTE, "ROUTE: CreateIpForwardEntry succeede= d with dwForwardMetric1=3D%u and dwForwardType=3D%u", - (unsigned int)fr.dwForwardMetric1, - (unsigned int)fr.dwForwardType); + msg(D_ROUTE, + "ROUTE: CreateIpForwardEntry succeeded with dw= ForwardMetric1=3D%u and dwForwardType=3D%u", + (unsigned int)fr.dwForwardMetric1, (unsigned i= nt)fr.dwForwardType); ret =3D RTA_SUCCESS; goto doublebreak; } @@ -3035,9 +2784,10 @@ } else { - msg(M_WARN, "ERROR: route addition failed using Create= IpForwardEntry: " - "%s [status=3D%u if_index=3D%u]", strerror_win32(s= tatus, &gc), - (unsigned int)status, (unsigned int)if_index); + msg(M_WARN, + "ERROR: route addition failed using CreateIpForwar= dEntry: " + "%s [status=3D%u if_index=3D%u]", + strerror_win32(status, &gc), (unsigned int)status,= (unsigned int)if_index); } } } @@ -3125,18 +2875,13 @@ return RTA_ERROR; } - route_message_t msg =3D { - .header =3D { - (add ? msg_add_route : msg_del_route), - sizeof(route_message_t), - 0 - }, - .family =3D AF_INET, - .prefix.ipv4.s_addr =3D htonl(r->network), - .gateway.ipv4.s_addr =3D htonl(r->gateway), - .iface =3D { .index =3D if_index, .name =3D "" }, - .metric =3D (r->flags & RT_METRIC_DEFINED ? r->metric : -1) - }; + route_message_t msg =3D { .header =3D { (add ? msg_add_route : msg_del= _route), + sizeof(route_message_t), 0 }, + .family =3D AF_INET, + .prefix.ipv4.s_addr =3D htonl(r->network), + .gateway.ipv4.s_addr =3D htonl(r->gateway), + .iface =3D { .index =3D if_index, .name =3D ""= }, + .metric =3D (r->flags & RT_METRIC_DEFINED ? r-= >metric : -1) }; netmask_to_netbits(r->network, r->netmask, &msg.prefix_len); if (msg.prefix_len =3D=3D -1) @@ -3166,7 +2911,7 @@ fwd_row->Metric =3D ((r->flags & RT_METRIC_DEFINED) ? r->metric : -1); fwd_row->DestinationPrefix.Prefix.si_family =3D AF_INET6; fwd_row->DestinationPrefix.Prefix.Ipv6.sin6_addr =3D r->network; - fwd_row->DestinationPrefix.PrefixLength =3D (UINT8) r->netbits; + fwd_row->DestinationPrefix.PrefixLength =3D (UINT8)r->netbits; fwd_row->NextHop.si_family =3D AF_INET6; fwd_row->NextHop.Ipv6.sin6_addr =3D r->gateway; fwd_row->InterfaceIndex =3D r->adapter_index ? r->adapter_index : tt->= adapter_index; @@ -3231,21 +2976,16 @@ do_route_ipv6_service(const bool add, const struct route_ipv6 *r, const st= ruct tuntap *tt) { int status; - route_message_t msg =3D { - .header =3D { - (add ? msg_add_route : msg_del_route), - sizeof(route_message_t), - 0 - }, - .family =3D AF_INET6, - .prefix.ipv6 =3D r->network, - .prefix_len =3D r->netbits, - .gateway.ipv6 =3D r->gateway, - .iface =3D { .index =3D tt->adapter_index, .name =3D "" }, - .metric =3D ( (r->flags & RT_METRIC_DEFINED) ? r->metric : -1) - }; + route_message_t msg =3D { .header =3D { (add ? msg_add_route : msg_del= _route), + sizeof(route_message_t), 0 }, + .family =3D AF_INET6, + .prefix.ipv6 =3D r->network, + .prefix_len =3D r->netbits, + .gateway.ipv6 =3D r->gateway, + .iface =3D { .index =3D tt->adapter_index, .na= me =3D "" }, + .metric =3D ((r->flags & RT_METRIC_DEFINED) ? = r->metric : -1) }; - if (r->adapter_index) /* vpn server special route */ + if (r->adapter_index) /* vpn server special route */ { msg.iface.index =3D r->adapter_index; } @@ -3254,8 +2994,7 @@ * The tapdrvr knows about it and will answer neighbor discovery packe= ts. * (only do this for routes actually using the tun/tap device) */ - if (tt->type =3D=3D DEV_TYPE_TUN - && msg.iface.index =3D=3D tt->adapter_index) + if (tt->type =3D=3D DEV_TYPE_TUN && msg.iface.index =3D=3D tt->adapter= _index) { inet_pton(AF_INET6, "fe80::8", &msg.gateway.ipv6); } @@ -3269,8 +3008,7 @@ status =3D do_route_service(add, &msg, sizeof(msg), tt->options.msg_ch= annel); if (status !=3D RTA_ERROR) { - msg(D_ROUTE, "IPv6 route %s via service %s", - add ? "addition" : "deletion", + msg(D_ROUTE, "IPv6 route %s via service %s", add ? "addition" : "d= eletion", (status =3D=3D RTA_SUCCESS) ? "succeeded" : "failed because ro= ute exists"); } return status; @@ -3309,17 +3047,10 @@ buf_printf(&out, "%s %s %s p=3D%d i=3D%d t=3D%d pr=3D%d a=3D%d h=3D%d = m=3D%d/%d/%d/%d/%d", print_in_addr_t(r->dwForwardDest, IA_NET_ORDER, gc), print_in_addr_t(r->dwForwardMask, IA_NET_ORDER, gc), - print_in_addr_t(r->dwForwardNextHop, IA_NET_ORDER, gc), - (int)r->dwForwardPolicy, - (int)r->dwForwardIfIndex, - (int)r->dwForwardType, - (int)r->dwForwardProto, - (int)r->dwForwardAge, - (int)r->dwForwardNextHopAS, - (int)r->dwForwardMetric1, - (int)r->dwForwardMetric2, - (int)r->dwForwardMetric3, - (int)r->dwForwardMetric4, + print_in_addr_t(r->dwForwardNextHop, IA_NET_ORDER, gc), (in= t)r->dwForwardPolicy, + (int)r->dwForwardIfIndex, (int)r->dwForwardType, (int)r->dw= ForwardProto, + (int)r->dwForwardAge, (int)r->dwForwardNextHopAS, (int)r->d= wForwardMetric1, + (int)r->dwForwardMetric2, (int)r->dwForwardMetric3, (int)r-= >dwForwardMetric4, (int)r->dwForwardMetric5); return BSTR(&out); } @@ -3368,12 +3099,11 @@ * normally on Linux. * It always fails and "ioctl(SIOCGIFCONF) failed" confuses users */ - } void -get_default_gateway_ipv6(struct route_ipv6_gateway_info *rgi6, - const struct in6_addr *dest, openvpn_net_ctx_t *c= tx) +get_default_gateway_ipv6(struct route_ipv6_gateway_info *rgi6, const struc= t in6_addr *dest, + openvpn_net_ctx_t *ctx) { /* Same for ipv6 */ @@ -3437,7 +3167,7 @@ if (ifr->ifr_addr.sa_family =3D=3D AF_INET) { /* get interface addr */ - addr =3D ntohl(((struct sockaddr_in *) &ifr->ifr_addr)->si= n_addr.s_addr); + addr =3D ntohl(((struct sockaddr_in *)&ifr->ifr_addr)->sin= _addr.s_addr); /* get interface name */ strncpynt(ifreq.ifr_name, ifr->ifr_name, sizeof(ifreq.ifr_= name)); @@ -3455,7 +3185,7 @@ if (rgi->flags & RGI_ON_LINK) { /* check that interface name of current interface - * matches interface name of best default route */ + * matches interface name of best default route */ if (strcmp(ifreq.ifr_name, best_name)) { continue; @@ -3479,7 +3209,7 @@ { continue; } - netmask =3D ntohl(((struct sockaddr_in *) &ifreq.ifr_a= ddr)->sin_addr.s_addr); + netmask =3D ntohl(((struct sockaddr_in *)&ifreq.ifr_ad= dr)->sin_addr.s_addr); /* check that interface matches default route */ if (((rgi->gateway.addr ^ addr) & netmask) !=3D 0) @@ -3524,22 +3254,22 @@ * netlink(3), netlink(7), rtnetlink(7) * http://www.virtualbox.org/svn/vbox/trunk/src/VBox/NetworkServices/NAT/r= tmon_linux.c */ -struct rtreq { +struct rtreq +{ struct nlmsghdr nh; struct rtmsg rtm; char attrbuf[512]; }; void -get_default_gateway_ipv6(struct route_ipv6_gateway_info *rgi6, - const struct in6_addr *dest, openvpn_net_ctx_t *c= tx) +get_default_gateway_ipv6(struct route_ipv6_gateway_info *rgi6, const struc= t in6_addr *dest, + openvpn_net_ctx_t *ctx) { int flags; CLEAR(*rgi6); - if (net_route_v6_best_gw(ctx, dest, &rgi6->gateway.addr_ipv6, - rgi6->iface) =3D=3D 0) + if (net_route_v6_best_gw(ctx, dest, &rgi6->gateway.addr_ipv6, rgi6->if= ace) =3D=3D 0) { if (!IN6_IS_ADDR_UNSPECIFIED(&rgi6->gateway.addr_ipv6)) { @@ -3564,9 +3294,8 @@ } } -#elif defined(TARGET_DARWIN) || defined(TARGET_SOLARIS) \ - || defined(TARGET_FREEBSD) || defined(TARGET_DRAGONFLY) \ - || defined(TARGET_OPENBSD) || defined(TARGET_NETBSD) +#elif defined(TARGET_DARWIN) || defined(TARGET_SOLARIS) || defined(TARGET_= FREEBSD) \ + || defined(TARGET_DRAGONFLY) || defined(TARGET_OPENBSD) || defined(TAR= GET_NETBSD) #include #include @@ -3577,7 +3306,8 @@ #include #endif -struct rtmsg { +struct rtmsg +{ struct rt_msghdr m_rtm; char m_space[512]; }; @@ -3599,26 +3329,30 @@ */ #if defined(TARGET_DARWIN) -#define ROUNDUP(a) \ - ((a) > 0 ? (1 + (((a) - 1) | (sizeof(uint32_t) - 1))) : sizeof(uint32_= t)) +#define ROUNDUP(a) ((a) > 0 ? (1 + (((a) - 1) | (sizeof(uint32_t) - 1))) := sizeof(uint32_t)) #elif defined(TARGET_NETBSD) #define ROUNDUP(a) RT_ROUNDUP(a) #else -#define ROUNDUP(a) \ - ((a) > 0 ? (1 + (((a) - 1) | (sizeof(long) - 1))) : sizeof(long)) +#define ROUNDUP(a) ((a) > 0 ? (1 + (((a) - 1) | (sizeof(long) - 1))) : siz= eof(long)) #endif #if defined(TARGET_SOLARIS) -#define NEXTADDR(w, u) \ - if (rtm_addrs & (w)) { \ - l =3D sizeof(u); memmove(cp, &(u), l); cp +=3D ROUNDUP(l); \ +#define NEXTADDR(w, u) \ + if (rtm_addrs & (w)) \ + { \ + l =3D sizeof(u); \ + memmove(cp, &(u), l); \ + cp +=3D ROUNDUP(l); \ } #define ADVANCE(x, n) (x +=3D ROUNDUP(sizeof(struct sockaddr_in))) -#else /* if defined(TARGET_SOLARIS) */ -#define NEXTADDR(w, u) \ - if (rtm_addrs & (w)) { \ - l =3D ((struct sockaddr *)&(u))->sa_len; memmove(cp, &(u), l); cp = +=3D ROUNDUP(l); \ +#else /* if defined(TARGET_SOLARIS) */ +#define NEXTADDR(w, u) \ + if (rtm_addrs & (w)) \ + { \ + l =3D ((struct sockaddr *)&(u))->sa_len; \ + memmove(cp, &(u), l); \ + cp +=3D ROUNDUP(l); \ } #define ADVANCE(x, n) (x +=3D ROUNDUP((n)->sa_len)) @@ -3637,7 +3371,7 @@ struct sockaddr so_dst, so_mask; char *cp =3D m_rtmsg.m_space; struct sockaddr *gate =3D NULL, *ifp =3D NULL, *sa; - struct rt_msghdr *rtm_aux; + struct rt_msghdr *rtm_aux; #define rtm m_rtmsg.m_rtm @@ -3647,7 +3381,7 @@ pid =3D getpid(); seq =3D 0; #ifdef TARGET_OPENBSD - rtm_addrs =3D RTA_DST | RTA_NETMASK; /* Kernel refuses RTA_IF= P */ + rtm_addrs =3D RTA_DST | RTA_NETMASK; /* Kernel refuses RTA_IFP */ #else rtm_addrs =3D RTA_DST | RTA_NETMASK | RTA_IFP; #endif @@ -3688,7 +3422,7 @@ } if (write(sockfd, (char *)&m_rtmsg, l) < 0) { - msg(M_WARN|M_ERRNO, "GDG: problem writing to routing socket"); + msg(M_WARN | M_ERRNO, "GDG: problem writing to routing socket"); goto done; } do @@ -3738,7 +3472,7 @@ if (ifp) { /* get interface name */ - const struct sockaddr_dl *adl =3D (struct sockaddr_dl *) ifp; + const struct sockaddr_dl *adl =3D (struct sockaddr_dl *)ifp; if (adl->sdl_nlen && adl->sdl_nlen < sizeof(rgi->iface)) { memcpy(rgi->iface, adl->sdl_data, adl->sdl_nlen); @@ -3806,15 +3540,14 @@ if (getifaddrs(&ifap) !=3D 0) { - msg(M_WARN|M_ERRNO, "GDG: getifaddrs() failed"); + msg(M_WARN | M_ERRNO, "GDG: getifaddrs() failed"); goto done; } for (ifa =3D ifap; ifa; ifa =3D ifa->ifa_next) { - if (ifa->ifa_addr !=3D NULL - && ifa->ifa_addr->sa_family =3D=3D AF_LINK - && !strncmp(ifa->ifa_name, rgi->iface, IFNAMSIZ) ) + if (ifa->ifa_addr !=3D NULL && ifa->ifa_addr->sa_family =3D=3D= AF_LINK + && !strncmp(ifa->ifa_name, rgi->iface, IFNAMSIZ)) { struct sockaddr_dl *sdl =3D (struct sockaddr_dl *)ifa->ifa= _addr; memcpy(rgi->hwaddr, LLADDR(sdl), 6); @@ -3847,10 +3580,9 @@ #endif void -get_default_gateway_ipv6(struct route_ipv6_gateway_info *rgi6, - const struct in6_addr *dest, openvpn_net_ctx_t *c= tx) +get_default_gateway_ipv6(struct route_ipv6_gateway_info *rgi6, const struc= t in6_addr *dest, + openvpn_net_ctx_t *ctx) { - struct rtmsg m_rtmsg; int sockfd =3D -1; int seq, l, pid, rtm_addrs; @@ -3866,7 +3598,7 @@ pid =3D getpid(); seq =3D 0; #ifdef TARGET_OPENBSD - rtm_addrs =3D RTA_DST | RTA_NETMASK; /* Kernel refuses RTA_IF= P */ + rtm_addrs =3D RTA_DST | RTA_NETMASK; /* Kernel refuses RTA_IFP */ #else rtm_addrs =3D RTA_DST | RTA_NETMASK | RTA_IFP; #endif @@ -3887,8 +3619,8 @@ so_dst.sin6_family =3D AF_INET6; so_mask.sin6_family =3D AF_INET6; - if (dest !=3D NULL /* specific host? */ - && !IN6_IS_ADDR_UNSPECIFIED(dest) ) + if (dest !=3D NULL /* specific host? */ + && !IN6_IS_ADDR_UNSPECIFIED(dest)) { so_dst.sin6_addr =3D *dest; /* :: needs /0 "netmask", host route wants "no netmask */ @@ -3916,15 +3648,14 @@ } if (write(sockfd, (char *)&m_rtmsg, l) < 0) { - msg(M_WARN|M_ERRNO, "GDG6: problem writing to routing socket"); + msg(M_WARN | M_ERRNO, "GDG6: problem writing to routing socket"); goto done; } do { l =3D read(sockfd, (char *)&m_rtmsg, sizeof(m_rtmsg)); - } - while (l > 0 && (rtm.rtm_seq !=3D seq || rtm.rtm_pid !=3D pid)); + } while (l > 0 && (rtm.rtm_seq !=3D seq || rtm.rtm_pid !=3D pid)); close(sockfd); sockfd =3D -1; @@ -3967,14 +3698,12 @@ * (KAME encodes the 16 bit scope_id in s6_addr[2] + [3], * but for a correct link-local address these must be :0000: ) */ - if (gate->sa_len =3D=3D sizeof(struct sockaddr_in6) - && IN6_IS_ADDR_LINKLOCAL(&gw) ) + if (gate->sa_len =3D=3D sizeof(struct sockaddr_in6) && IN6_IS_ADDR= _LINKLOCAL(&gw)) { gw.s6_addr[2] =3D gw.s6_addr[3] =3D 0; } - if (gate->sa_len !=3D sizeof(struct sockaddr_in6) - || IN6_IS_ADDR_UNSPECIFIED(&gw) ) + if (gate->sa_len !=3D sizeof(struct sockaddr_in6) || IN6_IS_ADDR_U= NSPECIFIED(&gw)) { rgi6->flags |=3D RGI_ON_LINK; } @@ -3988,7 +3717,7 @@ if (ifp) { /* get interface name */ - const struct sockaddr_dl *adl =3D (struct sockaddr_dl *) ifp; + const struct sockaddr_dl *adl =3D (struct sockaddr_dl *)ifp; if (adl->sdl_nlen && adl->sdl_nlen < sizeof(rgi6->iface)) { memcpy(rgi6->iface, adl->sdl_data, adl->sdl_nlen); @@ -4072,15 +3801,15 @@ address_size +=3D route.gateway->sa_len; } - interface =3D (struct ifreq *)((addr_t)interface + IF_NAMESIZE - + sizeof(struct route_entry) + addres= s_size); + interface =3D (struct ifreq *)((addr_t)interface + IF_NAMESIZE + s= izeof(struct route_entry) + + address_size); } free(buffer); } void -get_default_gateway_ipv6(struct route_ipv6_gateway_info *rgi6, - const struct in6_addr *dest, openvpn_net_ctx_t *c= tx) +get_default_gateway_ipv6(struct route_ipv6_gateway_info *rgi6, const struc= t in6_addr *dest, + openvpn_net_ctx_t *ctx) { /* TODO: Same for ipv6 with AF_INET6 */ CLEAR(*rgi6); @@ -4118,8 +3847,8 @@ CLEAR(*rgi); } void -get_default_gateway_ipv6(struct route_ipv6_gateway_info *rgi6, - const struct in6_addr *dest, openvpn_net_ctx_t *c= tx) +get_default_gateway_ipv6(struct route_ipv6_gateway_info *rgi6, const struc= t in6_addr *dest, + openvpn_net_ctx_t *ctx) { msg(D_ROUTE, "no support for get_default_gateway_ipv6() on this system= "); CLEAR(*rgi6); @@ -4199,7 +3928,8 @@ while (iplist) { bool succeed =3D false; - const in_addr_t ip =3D getaddr(GETADDR_HOST_ORDER, iplist->IpAddre= ss.String, 0, &succeed, NULL); + const in_addr_t ip =3D + getaddr(GETADDR_HOST_ORDER, iplist->IpAddress.String, 0, &succ= eed, NULL); if (succeed) { add_host_route_if_nonlocal(rb, ip); @@ -4247,7 +3977,7 @@ #else /* if defined(_WIN32) */ static void -get_bypass_addresses(struct route_bypass *rb, const unsigned int flags) = /* PLATFORM-SPECIFIC */ +get_bypass_addresses(struct route_bypass *rb, const unsigned int flags) /*= PLATFORM-SPECIFIC */ { } =20 @@ -4268,7 +3998,8 @@ test_local_addr(const in_addr_t addr, const struct route_gateway_info *rgi) { struct gc_arena gc =3D gc_new(); - const in_addr_t nonlocal_netmask =3D 0x80000000L; /* routes with netma= sk <=3D to this are considered non-local */ + const in_addr_t nonlocal_netmask =3D + 0x80000000L; /* routes with netmask <=3D to this are considered no= n-local */ int ret =3D TLA_NONLOCAL; /* get full routing table */ @@ -4295,7 +4026,7 @@ #else /* if defined(_WIN32) */ int -test_local_addr(const in_addr_t addr, const struct route_gateway_info *rgi= ) /* PLATFORM-SPECIFIC */ +test_local_addr(const in_addr_t addr, const struct route_gateway_info *rgi= ) /* PLATFORM-SPECIFIC */ { if (rgi) { diff --git a/src/openvpn/route.h b/src/openvpn/route.h index 1a358e32..ea8b767 100644 --- a/src/openvpn/route.h +++ b/src/openvpn/route.h @@ -36,18 +36,18 @@ /* * Windows route methods */ -#define ROUTE_METHOD_ADAPTIVE 0 /* try IP helper first then route.exe */ -#define ROUTE_METHOD_IPAPI 1 /* use IP helper API */ -#define ROUTE_METHOD_EXE 2 /* use route.exe */ -#define ROUTE_METHOD_SERVICE 3 /* use the privileged Windows service */ -#define ROUTE_METHOD_MASK 3 +#define ROUTE_METHOD_ADAPTIVE 0 /* try IP helper first then route.exe */ +#define ROUTE_METHOD_IPAPI 1 /* use IP helper API */ +#define ROUTE_METHOD_EXE 2 /* use route.exe */ +#define ROUTE_METHOD_SERVICE 3 /* use the privileged Windows service */ +#define ROUTE_METHOD_MASK 3 #endif /* * Route add/delete flags (must stay clear of ROUTE_METHOD bits) */ -#define ROUTE_DELETE_FIRST (1<<2) -#define ROUTE_REF_GW (1<<3) +#define ROUTE_DELETE_FIRST (1 << 2) +#define ROUTE_REF_GW (1 << 3) struct route_bypass { @@ -59,9 +59,9 @@ struct route_special_addr { /* bits indicating which members below are defined */ -#define RTSA_REMOTE_ENDPOINT (1<<0) -#define RTSA_REMOTE_HOST (1<<1) -#define RTSA_DEFAULT_METRIC (1<<2) +#define RTSA_REMOTE_ENDPOINT (1 << 0) +#define RTSA_REMOTE_HOST (1 << 1) +#define RTSA_DEFAULT_METRIC (1 << 2) unsigned int flags; in_addr_t remote_endpoint; @@ -72,7 +72,8 @@ int default_metric; }; -struct route_option { +struct route_option +{ struct route_option *next; const char *network; const char *netmask; @@ -82,39 +83,43 @@ }; /* redirect-gateway flags */ -#define RG_ENABLE (1<<0) -#define RG_LOCAL (1<<1) -#define RG_DEF1 (1<<2) -#define RG_BYPASS_DHCP (1<<3) -#define RG_BYPASS_DNS (1<<4) -#define RG_REROUTE_GW (1<<5) -#define RG_AUTO_LOCAL (1<<6) -#define RG_BLOCK_LOCAL (1<<7) +#define RG_ENABLE (1 << 0) +#define RG_LOCAL (1 << 1) +#define RG_DEF1 (1 << 2) +#define RG_BYPASS_DHCP (1 << 3) +#define RG_BYPASS_DNS (1 << 4) +#define RG_REROUTE_GW (1 << 5) +#define RG_AUTO_LOCAL (1 << 6) +#define RG_BLOCK_LOCAL (1 << 7) -struct route_option_list { +struct route_option_list +{ unsigned int flags; /* RG_x flags */ struct route_option *routes; struct gc_arena *gc; }; -struct route_ipv6_option { +struct route_ipv6_option +{ struct route_ipv6_option *next; - const char *prefix; /* e.g. "2001:db8:1::/64" */ - const char *gateway; /* e.g. "2001:db8:0::2" */ - const char *metric; /* e.g. "5" */ + const char *prefix; /* e.g. "2001:db8:1::/64" */ + const char *gateway; /* e.g. "2001:db8:0::2" */ + const char *metric; /* e.g. "5" */ int table_id; }; -struct route_ipv6_option_list { - unsigned int flags; /* RG_x flags, see route_option-list */ +struct route_ipv6_option_list +{ + unsigned int flags; /* RG_x flags, see route_option-list */ struct route_ipv6_option *routes_ipv6; struct gc_arena *gc; }; -struct route_ipv4 { -#define RT_DEFINED (1<<0) -#define RT_ADDED (1<<1) -#define RT_METRIC_DEFINED (1<<2) +struct route_ipv4 +{ +#define RT_DEFINED (1 << 0) +#define RT_ADDED (1 << 1) +#define RT_METRIC_DEFINED (1 << 2) struct route_ipv4 *next; unsigned int flags; const struct route_option *option; @@ -125,9 +130,10 @@ int metric; }; -struct route_ipv6 { +struct route_ipv6 +{ struct route_ipv6 *next; - unsigned int flags; /* RT_ flags, see route_ip= v4 */ + unsigned int flags; /* RT_ flags, see route_ipv4 */ struct in6_addr network; unsigned int netbits; struct in6_addr gateway; @@ -135,25 +141,27 @@ int table_id; /* gateway interface */ #ifdef _WIN32 - DWORD adapter_index; /* interface or ~0 if undefined */ + DWORD adapter_index; /* interface or ~0 if undefined */ #else - char *iface; /* interface name (null terminated) */ + char *iface; /* interface name (null terminated) */ #endif }; -struct route_gateway_address { +struct route_gateway_address +{ in_addr_t addr; in_addr_t netmask; }; -struct route_gateway_info { -#define RGI_ADDR_DEFINED (1<<0) /* set if gateway.addr defined */ -#define RGI_NETMASK_DEFINED (1<<1) /* set if gateway.netmask defined */ -#define RGI_HWADDR_DEFINED (1<<2) /* set if hwaddr is defined */ -#define RGI_IFACE_DEFINED (1<<3) /* set if iface is defined */ -#define RGI_OVERFLOW (1<<4) /* set if more interface addresses th= an will fit in addrs */ -#define RGI_ON_LINK (1<<5) +struct route_gateway_info +{ +#define RGI_ADDR_DEFINED (1 << 0) /* set if gateway.addr defined */ +#define RGI_NETMASK_DEFINED (1 << 1) /* set if gateway.netmask defined */ +#define RGI_HWADDR_DEFINED (1 << 2) /* set if hwaddr is defined */ +#define RGI_IFACE_DEFINED (1 << 3) /* set if iface is defined */ +#define RGI_OVERFLOW (1 << 4) /* set if more interface addresses th= an will fit in addrs */ +#define RGI_ON_LINK (1 << 5) unsigned int flags; /* gateway interface */ @@ -173,17 +181,19 @@ /* address/netmask pairs bound to interface */ #define RGI_N_ADDRESSES 8 - int n_addrs; /* len of addrs, may be 0 */ + int n_addrs; /* len of addrs, = may be 0 */ struct route_gateway_address addrs[RGI_N_ADDRESSES]; /* local addresse= s attached to iface */ }; -struct route_ipv6_gateway_address { +struct route_ipv6_gateway_address +{ struct in6_addr addr_ipv6; int netbits_ipv6; }; -struct route_ipv6_gateway_info { -/* RGI_ flags used as in route_gateway_info */ +struct route_ipv6_gateway_info +{ + /* RGI_ flags used as in route_gateway_info */ unsigned int flags; /* gateway interface */ @@ -210,45 +220,50 @@ /* address/netmask pairs bound to interface */ #define RGI_N_ADDRESSES 8 - int n_addrs; /* len of addrs, may be 0 */ - struct route_ipv6_gateway_address addrs[RGI_N_ADDRESSES]; /* local add= resses attached to iface */ + int n_addrs; /* len of addrs, may be 0 */ + struct route_ipv6_gateway_address + addrs[RGI_N_ADDRESSES]; /* local addresses attached to iface */ }; -struct route_list { -#define RL_DID_REDIRECT_DEFAULT_GATEWAY (1<<0) -#define RL_DID_LOCAL (1<<1) -#define RL_ROUTES_ADDED (1<<2) +struct route_list +{ +#define RL_DID_REDIRECT_DEFAULT_GATEWAY (1 << 0) +#define RL_DID_LOCAL (1 << 1) +#define RL_ROUTES_ADDED (1 << 2) unsigned int iflags; struct route_special_addr spec; struct route_gateway_info rgi; - unsigned int flags; /* RG_x flags */ + unsigned int flags; /* RG_x flags */ struct route_ipv4 *routes; struct gc_arena gc; }; -struct route_ipv6_list { - unsigned int iflags; /* RL_ flags, see route_list */ +struct route_ipv6_list +{ + unsigned int iflags; /* RL_ flags, see route_list */ - unsigned int spec_flags; /* RTSA_ flags, route_special_addr= */ + unsigned int spec_flags; /* RTSA_ flags, route_special_ad= dr */ struct in6_addr remote_endpoint_ipv6; /* inside tun */ - struct in6_addr remote_host_ipv6; /* --remote address */ + struct in6_addr remote_host_ipv6; /* --remote address */ int default_metric; struct route_ipv6_gateway_info rgi6; - unsigned int flags; /* RG_x flags, see route_option_li= st */ + unsigned int flags; /* RG_x flags, see route_option_list */ struct route_ipv6 *routes_ipv6; struct gc_arena gc; }; /* internal OpenVPN route */ -struct iroute { +struct iroute +{ in_addr_t network; int netbits; struct iroute *next; }; -struct iroute_ipv6 { +struct iroute_ipv6 +{ struct in6_addr network; unsigned int netbits; struct iroute_ipv6 *next; @@ -270,79 +285,58 @@ struct route_ipv6_option_list *new_route_ipv6_option_list(struct gc_arena = *a); -struct route_option_list *clone_route_option_list(const struct route_optio= n_list *src, struct gc_arena *a); +struct route_option_list *clone_route_option_list(const struct route_optio= n_list *src, + struct gc_arena *a); -struct route_ipv6_option_list *clone_route_ipv6_option_list(const struct r= oute_ipv6_option_list *src, struct gc_arena *a); +struct route_ipv6_option_list *clone_route_ipv6_option_list( + const struct route_ipv6_option_list *src, struct gc_arena *a); -void copy_route_option_list(struct route_option_list *dest, const struct r= oute_option_list *src, struct gc_arena *a); +void copy_route_option_list(struct route_option_list *dest, const struct r= oute_option_list *src, + struct gc_arena *a); void copy_route_ipv6_option_list(struct route_ipv6_option_list *dest, - const struct route_ipv6_option_list *src, - struct gc_arena *a); + const struct route_ipv6_option_list *src,= struct gc_arena *a); -void route_ipv6_clear_host_bits( struct route_ipv6 *r6 ); +void route_ipv6_clear_host_bits(struct route_ipv6 *r6); -bool add_route_ipv6(struct route_ipv6 *r, const struct tuntap *tt, unsigne= d int flags, const struct env_set *es, openvpn_net_ctx_t *ctx); +bool add_route_ipv6(struct route_ipv6 *r, const struct tuntap *tt, unsigne= d int flags, + const struct env_set *es, openvpn_net_ctx_t *ctx); -void delete_route_ipv6(const struct route_ipv6 *r, const struct tuntap *tt= , const struct env_set *es, openvpn_net_ctx_t *ctx); +void delete_route_ipv6(const struct route_ipv6 *r, const struct tuntap *tt, + const struct env_set *es, openvpn_net_ctx_t *ctx); bool add_route(struct route_ipv4 *r, const struct tuntap *tt, unsigned int= flags, const struct route_gateway_info *rgi, const struct env_set = *es, openvpn_net_ctx_t *ctx); -void add_route_to_option_list(struct route_option_list *l, - const char *network, - const char *netmask, - const char *gateway, - const char *metric, - int table_id); +void add_route_to_option_list(struct route_option_list *l, const char *net= work, const char *netmask, + const char *gateway, const char *metric, int= table_id); -void add_route_ipv6_to_option_list(struct route_ipv6_option_list *l, - const char *prefix, - const char *gateway, - const char *metric, - int table_id); +void add_route_ipv6_to_option_list(struct route_ipv6_option_list *l, const= char *prefix, + const char *gateway, const char *metric= , int table_id); -bool init_route_list(struct route_list *rl, - const struct route_option_list *opt, - const char *remote_endpoint, - int default_metric, - in_addr_t remote_host, - struct env_set *es, - openvpn_net_ctx_t *ctx); +bool init_route_list(struct route_list *rl, const struct route_option_list= *opt, + const char *remote_endpoint, int default_metric, in_a= ddr_t remote_host, + struct env_set *es, openvpn_net_ctx_t *ctx); -bool init_route_ipv6_list(struct route_ipv6_list *rl6, - const struct route_ipv6_option_list *opt6, - const char *remote_endpoint, - int default_metric, - const struct in6_addr *remote_host, - struct env_set *es, +bool init_route_ipv6_list(struct route_ipv6_list *rl6, const struct route_= ipv6_option_list *opt6, + const char *remote_endpoint, int default_metric, + const struct in6_addr *remote_host, struct env_s= et *es, openvpn_net_ctx_t *ctx); -void route_list_add_vpn_gateway(struct route_list *rl, - struct env_set *es, - const in_addr_t addr); +void route_list_add_vpn_gateway(struct route_list *rl, struct env_set *es,= const in_addr_t addr); -bool add_routes(struct route_list *rl, struct route_ipv6_list *rl6, - const struct tuntap *tt, unsigned int flags, - const struct env_set *es, openvpn_net_ctx_t *ctx); +bool add_routes(struct route_list *rl, struct route_ipv6_list *rl6, const = struct tuntap *tt, + unsigned int flags, const struct env_set *es, openvpn_net_= ctx_t *ctx); -void delete_routes(struct route_list *rl, - struct route_ipv6_list *rl6, - const struct tuntap *tt, - unsigned int flags, - const struct env_set *es, - openvpn_net_ctx_t *ctx); +void delete_routes(struct route_list *rl, struct route_ipv6_list *rl6, con= st struct tuntap *tt, + unsigned int flags, const struct env_set *es, openvpn_n= et_ctx_t *ctx); -void -delete_routes_v4(struct route_list *rl, const struct tuntap *tt, - unsigned int flags, const struct env_set *es, - openvpn_net_ctx_t *ctx); +void delete_routes_v4(struct route_list *rl, const struct tuntap *tt, unsi= gned int flags, + const struct env_set *es, openvpn_net_ctx_t *ctx); -void -delete_routes_v6(struct route_ipv6_list *rl6, const struct tuntap *tt, - unsigned int flags, const struct env_set *es, - openvpn_net_ctx_t *ctx); +void delete_routes_v6(struct route_ipv6_list *rl6, const struct tuntap *tt= , unsigned int flags, + const struct env_set *es, openvpn_net_ctx_t *ctx); void setenv_routes(struct env_set *es, const struct route_list *rl); @@ -357,16 +351,12 @@ * @param dest Destination IP address in host byte order. * @param ctx Pointer to a platform-specific network context struct. */ -void get_default_gateway(struct route_gateway_info *rgi, - in_addr_t dest, - openvpn_net_ctx_t *ctx); +void get_default_gateway(struct route_gateway_info *rgi, in_addr_t dest, o= penvpn_net_ctx_t *ctx); -void get_default_gateway_ipv6(struct route_ipv6_gateway_info *rgi, - const struct in6_addr *dest, +void get_default_gateway_ipv6(struct route_ipv6_gateway_info *rgi, const s= truct in6_addr *dest, openvpn_net_ctx_t *ctx); -void print_default_gateway(const int msglevel, - const struct route_gateway_info *rgi, +void print_default_gateway(const int msglevel, const struct route_gateway_= info *rgi, const struct route_ipv6_gateway_info *rgi6); /* @@ -381,8 +371,7 @@ int test_local_addr(const in_addr_t addr, const struct route_gateway_info = *rgi); #ifndef ENABLE_SMALL -void print_route_options(const struct route_option_list *rol, - int level); +void print_route_options(const struct route_option_list *rol, int level); #endif @@ -394,7 +383,7 @@ bool test_routes(const struct route_list *rl, const struct tuntap *tt); -#else /* ifdef _WIN32 */ +#else /* ifdef _WIN32 */ static inline bool test_routes(const struct route_list *rl, const struct tuntap *tt) { @@ -413,7 +402,7 @@ in_addr_t mask =3D 0; if (netbits > 0 && netbits <=3D addrlen) { - mask =3D IPV4_NETMASK_HOST << (addrlen-netbits); + mask =3D IPV4_NETMASK_HOST << (addrlen - netbits); } return mask; } diff --git a/src/openvpn/run_command.c b/src/openvpn/run_command.c index ed5b08c..4a1ef22 100644 --- a/src/openvpn/run_command.c +++ b/src/openvpn/run_command.c @@ -67,7 +67,7 @@ #ifdef _WIN32 case OPENVPN_EXECVE_ERROR: buf_printf(&out, "external program did not execute -- "); - /* fall through */ + /* fall through */ default: buf_printf(&out, "returned error code %d", stat); @@ -126,20 +126,16 @@ if (exitcode =3D=3D OPENVPN_EXECVE_FAILURE) { - msg(msglevel, "%scould not execute external program (exit code= 127)", - msg_prefix); + msg(msglevel, "%scould not execute external program (exit code= 127)", msg_prefix); } else { - msg(msglevel, "%sexternal program exited with error status: %d= ", - msg_prefix, exitcode); + msg(msglevel, "%sexternal program exited with error status: %d= ", msg_prefix, exitcode); } - } else if (WIFSIGNALED(status)) { - msg(msglevel, "%sexternal program received signal %d", - msg_prefix, WTERMSIG(status)); + msg(msglevel, "%sexternal program received signal %d", msg_prefix,= WTERMSIG(status)); } return false; @@ -234,7 +230,8 @@ * Wrapper around openvpn_execve */ int -openvpn_execve_check(const struct argv *a, const struct env_set *es, const= unsigned int flags, const char *error_message) +openvpn_execve_check(const struct argv *a, const struct env_set *es, const= unsigned int flags, + const char *error_message) { struct gc_arena gc =3D gc_new(); const int stat =3D openvpn_execve(a, es, flags); @@ -260,8 +257,7 @@ } if (error_message) { - msg(((flags & S_FATAL) ? M_FATAL : M_WARN), "%s: %s", - error_message, + msg(((flags & S_FATAL) ? M_FATAL : M_WARN), "%s: %s", error_messag= e, system_error_message(stat, &gc)); } done: @@ -276,7 +272,7 @@ * associated with formatting and parsing a command line. */ int -openvpn_popen(const struct argv *a, const struct env_set *es) +openvpn_popen(const struct argv *a, const struct env_set *es) { struct gc_arena gc =3D gc_new(); int ret =3D -1; @@ -298,20 +294,20 @@ pid =3D fork(); if (pid =3D=3D (pid_t)0) /* child side */ { - close(pipe_stdout[0]); /* Close read end */ + close(pipe_stdout[0]); /* Close read end */ dup2(pipe_stdout[1], 1); execve(cmd, argv, envp); exit(OPENVPN_EXECVE_FAILURE); } - else if (pid > (pid_t)0) /* parent side */ + else if (pid > (pid_t)0) /* parent side */ { int status =3D 0; - close(pipe_stdout[1]); /* Close write end */ + close(pipe_stdout[1]); /* Close write end */ waitpid(pid, &status, 0); ret =3D pipe_stdout[0]; } - else /* fork failed */ + else /* fork failed */ { close(pipe_stdout[0]); close(pipe_stdout[1]); diff --git a/src/openvpn/run_command.h b/src/openvpn/run_command.h index e703732..4b74f22 100644 --- a/src/openvpn/run_command.h +++ b/src/openvpn/run_command.h @@ -27,36 +27,38 @@ #include "env_set.h" /* Script security */ -#define SSEC_NONE 0 /* strictly no calling of external programs */ -#define SSEC_BUILT_IN 1 /* only call built-in programs such as ifconfig, = route, netsh, etc.*/ -#define SSEC_SCRIPTS 2 /* allow calling of built-in programs and user-de= fined scripts */ -#define SSEC_PW_ENV 3 /* allow calling of built-in programs and user-de= fined scripts that may receive a password as an environmental variable */ +#define SSEC_NONE 0 /* strictly no calling of external programs */ +#define SSEC_BUILT_IN 1 /* only call built-in programs such as ifconfig, r= oute, netsh, etc.*/ +#define SSEC_SCRIPTS 2 /* allow calling of built-in programs and user-def= ined scripts */ +#define SSEC_PW_ENV = \ + 3 /* allow calling of built-in programs and user-defined scripts that = may receive a password \ + as an environmental variable */ -#define OPENVPN_EXECVE_ERROR -1 /* generic error while forking to ru= n an external program */ -#define OPENVPN_EXECVE_NOT_ALLOWED -2 /* external program not run due to s= cript security */ -#define OPENVPN_EXECVE_FAILURE 127 /* exit code passed back from child = when execve fails */ +#define OPENVPN_EXECVE_ERROR -1 /* generic error while forking to r= un an external program */ +#define OPENVPN_EXECVE_NOT_ALLOWED -2 /* external program not run due to = script security */ +#define OPENVPN_EXECVE_FAILURE 127 /* exit code passed back from child= when execve fails */ int script_security(void); void script_security_set(int level); /* openvpn_execve flags */ -#define S_SCRIPT (1<<0) -#define S_FATAL (1<<1) +#define S_SCRIPT (1 << 0) +#define S_FATAL (1 << 1) /** Instead of returning 1/0 for success/fail, * return exit code when between 0 and 255 and -1 otherwise */ -#define S_EXITCODE (1<<2) +#define S_EXITCODE (1 << 2) /** instead of waiting for child process to exit and report the status, * return the pid of the child process */ -#define S_NOWAITPID (1<<3) +#define S_NOWAITPID (1 << 3) /* wrapper around the execve() call */ -int openvpn_popen(const struct argv *a, const struct env_set *es); +int openvpn_popen(const struct argv *a, const struct env_set *es); bool openvpn_execve_allowed(const unsigned int flags); -int openvpn_execve_check(const struct argv *a, const struct env_set *es, - const unsigned int flags, const char *error_messa= ge); +int openvpn_execve_check(const struct argv *a, const struct env_set *es, c= onst unsigned int flags, + const char *error_message); #ifndef WIN32 @@ -72,9 +74,7 @@ * @return true if the process is still running, false if * an error condition occurred */ -bool -openvpn_waitpid_check(pid_t pid, const char *msg_prefix, - int msglevel); +bool openvpn_waitpid_check(pid_t pid, const char *msg_prefix, int msglevel= ); #endif @@ -83,13 +83,12 @@ * 0 and 255, -1 otherwise */ static inline int -openvpn_run_script(const struct argv *a, const struct env_set *es, - const unsigned int flags, const char *hook) +openvpn_run_script(const struct argv *a, const struct env_set *es, const u= nsigned int flags, + const char *hook) { char msg[256]; - snprintf(msg, sizeof(msg), - "WARNING: Failed running command (%s)", hook); + snprintf(msg, sizeof(msg), "WARNING: Failed running command (%s)", hoo= k); return openvpn_execve_check(a, es, flags | S_SCRIPT, msg); } diff --git a/src/openvpn/schedule.c b/src/openvpn/schedule.c index f89f341..c9fef24 100644 --- a/src/openvpn/schedule.c +++ b/src/openvpn/schedule.c @@ -54,15 +54,12 @@ struct gc_arena gc =3D gc_new(); if (e) { - dmsg(D_SCHEDULER, "SCHEDULE: %s wakeup=3D[%s] pri=3D%u", - caller, - tv_string_abs(&e->tv, &gc), + dmsg(D_SCHEDULER, "SCHEDULE: %s wakeup=3D[%s] pri=3D%u", caller, t= v_string_abs(&e->tv, &gc), e->pri); } else { - dmsg(D_SCHEDULER, "SCHEDULE: %s NULL", - caller); + dmsg(D_SCHEDULER, "SCHEDULE: %s NULL", caller); } gc_free(&gc); } @@ -84,8 +81,7 @@ * that keys do not collide. */ static inline int -schedule_entry_compare(const struct schedule_entry *e1, - const struct schedule_entry *e2) +schedule_entry_compare(const struct schedule_entry *e1, const struct sched= ule_entry *e2) { if (e1->tv.tv_sec < e2->tv.tv_sec) { @@ -360,12 +356,11 @@ if (s->root) { - schedule_insert(s, e); /* trivial insert into tree */ + schedule_insert(s, e); /* trivial insert into tree */ } else { s->root =3D e; /* tree was empty, we are the first element */ - } /* This is the magic of the randomized treap algorithm which * keeps the tree balanced. Move the node up the tree until @@ -446,12 +441,8 @@ * internally consistent. */ int -schedule_debug_entry(const struct schedule_entry *e, - int depth, - int *count, - struct timeval *least, - const struct timeval *min, - const struct timeval *max) +schedule_debug_entry(const struct schedule_entry *e, int depth, int *count= , struct timeval *least, + const struct timeval *min, const struct timeval *max) { struct gc_arena gc =3D gc_new(); int maxdepth =3D depth; @@ -493,13 +484,13 @@ *least =3D e->tv; } - d =3D schedule_debug_entry(e->lt, depth+1, count, least, min, &e->= tv); + d =3D schedule_debug_entry(e->lt, depth + 1, count, least, min, &e= ->tv); if (d > maxdepth) { maxdepth =3D d; } - d =3D schedule_debug_entry(e->gt, depth+1, count, least, &e->tv, m= ax); + d =3D schedule_debug_entry(e->gt, depth + 1, count, least, &e->tv,= max); if (d > maxdepth) { maxdepth =3D d; @@ -576,14 +567,8 @@ if (e) { - printf("Verification Phase count=3D%d maxlev=3D%d sru=3D%d ins=3D= %d coll=3D%d ls=3D%d l=3D%s", - count, - maxlev, - zz.sru, - zz.ins, - zz.coll, - zz.lsteps, - tv_string(&e->tv, &gc)); + printf("Verification Phase count=3D%d maxlev=3D%d sru=3D%d ins=3D= %d coll=3D%d ls=3D%d l=3D%s", count, + maxlev, zz.sru, zz.ins, zz.coll, zz.lsteps, tv_string(&e->t= v, &gc)); if (!tv_eq(&least, &e->tv)) { @@ -604,11 +589,11 @@ for (i =3D 0; i < size; ++i) { const int src =3D get_random() % size; - struct schedule_entry *tmp =3D array [i]; + struct schedule_entry *tmp =3D array[i]; if (i !=3D src) { - array [i] =3D array [src]; - array [src] =3D tmp; + array[i] =3D array[src]; + array[src] =3D tmp; } } } @@ -625,14 +610,10 @@ if (e) { printf("%s [%u] e=3D" ptr_format ", p=3D" ptr_format " lt=3D" ptr_= format " gt=3D" ptr_format "\n", - tv_string(&e->tv, &gc), - e->pri, - (ptr_type)e, - (ptr_type)e->parent, - (ptr_type)e->lt, + tv_string(&e->tv, &gc), e->pri, (ptr_type)e, (ptr_type)e->p= arent, (ptr_type)e->lt, (ptr_type)e->gt); - schedule_print_work(e->lt, indent+1); - schedule_print_work(e->gt, indent+1); + schedule_print_work(e->lt, indent + 1); + schedule_print_work(e->gt, indent + 1); } else { diff --git a/src/openvpn/schedule.h b/src/openvpn/schedule.h index fad3f36..79311c5 100644 --- a/src/openvpn/schedule.h +++ b/src/openvpn/schedule.h @@ -42,8 +42,8 @@ struct schedule_entry { - struct timeval tv; /* wakeup time */ - unsigned int pri; /* random treap priority */ + struct timeval tv; /* wakeup time */ + unsigned int pri; /* random treap priority */ struct schedule_entry *parent; /* treap (btree) links */ struct schedule_entry *lt; struct schedule_entry *gt; @@ -52,7 +52,7 @@ struct schedule { struct schedule_entry *earliest_wakeup; /* cached earliest wakeup */ - struct schedule_entry *root; /* the root of the treap (btree)= */ + struct schedule_entry *root; /* the root of the treap (btre= e) */ }; /* Public functions */ @@ -94,9 +94,7 @@ * an opaque object. */ static inline void -schedule_add_entry(struct schedule *s, - struct schedule_entry *e, - const struct timeval *tv, +schedule_add_entry(struct schedule *s, struct schedule_entry *e, const str= uct timeval *tv, unsigned int sigma) { if (!IN_TREE(e) || !sigma || !tv_within_sigma(tv, &e->tv, sigma)) @@ -114,8 +112,7 @@ * is randomized every time an entry is re-added). */ static inline struct schedule_entry * -schedule_get_earliest_wakeup(struct schedule *s, - struct timeval *wakeup) +schedule_get_earliest_wakeup(struct schedule *s, struct timeval *wakeup) { struct schedule_entry *ret; diff --git a/src/openvpn/session_id.h b/src/openvpn/session_id.h index 7c0a968..24e7ab0 100644 --- a/src/openvpn/session_id.h +++ b/src/openvpn/session_id.h @@ -44,8 +44,7 @@ #define SID_SIZE (sizeof(x_session_id_zero.id)) static inline bool -session_id_equal(const struct session_id *sid1, - const struct session_id *sid2) +session_id_equal(const struct session_id *sid1, const struct session_id *s= id2) { return !memcmp(sid1->id, sid2->id, SID_SIZE); } diff --git a/src/openvpn/shaper.c b/src/openvpn/shaper.c index 1c8cfb3..fb2621e 100644 --- a/src/openvpn/shaper.c +++ b/src/openvpn/shaper.c @@ -86,6 +86,5 @@ void shaper_msg(struct shaper *s) { - msg(M_INFO, "Output Traffic Shaping initialized at %d bytes per second= ", - s->bytes_per_second); + msg(M_INFO, "Output Traffic Shaping initialized at %d bytes per second= ", s->bytes_per_second); } diff --git a/src/openvpn/shaper.h b/src/openvpn/shaper.h index 9996b08..4483d15 100644 --- a/src/openvpn/shaper.h +++ b/src/openvpn/shaper.h @@ -36,10 +36,10 @@ * the output direction. */ -#define SHAPER_MIN 100 /* bytes per second */ +#define SHAPER_MIN 100 /* bytes per second */ #define SHAPER_MAX 100000000 -#define SHAPER_MAX_TIMEOUT 10 /* seconds */ +#define SHAPER_MAX_TIMEOUT 10 /* seconds */ #define SHAPER_USE_FP @@ -125,11 +125,12 @@ /* compute delay in microseconds */ tv.tv_sec =3D 0; #ifdef SHAPER_USE_FP - tv.tv_usec =3D min_int((int)((double)max_int(nbytes, 100) * s->factor)= , (SHAPER_MAX_TIMEOUT*1000000)); + tv.tv_usec =3D + min_int((int)((double)max_int(nbytes, 100) * s->factor), (SHAPER_M= AX_TIMEOUT * 1000000)); #else tv.tv_usec =3D s->bytes_per_second - ? min_int(max_int(nbytes, 100) * s->factor, (SHAPER_MAX_T= IMEOUT*1000000)) - : 0; + ? min_int(max_int(nbytes, 100) * s->factor, (SHAPER_M= AX_TIMEOUT * 1000000)) + : 0; #endif if (tv.tv_usec) @@ -138,11 +139,9 @@ tv_add(&s->wakeup, &tv); #ifdef SHAPER_DEBUG - dmsg(D_SHAPER_DEBUG, "SHAPER shaper_wrote_bytes bytes=3D%d delay= =3D%ld sec=3D%" PRIi64 " usec=3D%ld", - nbytes, - (long)tv.tv_usec, - (int64_t)s->wakeup.tv_sec, - (long)s->wakeup.tv_usec); + dmsg(D_SHAPER_DEBUG, + "SHAPER shaper_wrote_bytes bytes=3D%d delay=3D%ld sec=3D%" PR= Ii64 " usec=3D%ld", nbytes, + (long)tv.tv_usec, (int64_t)s->wakeup.tv_sec, (long)s->wakeup.= tv_usec); #endif } } diff --git a/src/openvpn/sig.c b/src/openvpn/sig.c index 02df5e0..5f5a808 100644 --- a/src/openvpn/sig.c +++ b/src/openvpn/sig.c @@ -43,20 +43,19 @@ struct signal_info siginfo_static; /* GLOBAL */ -struct signame { +struct signame +{ int value; int priority; const char *upper; const char *lower; }; -static const struct signame signames[] =3D { - { SIGINT, 5, "SIGINT", "sigint"}, - { SIGTERM, 4, "SIGTERM", "sigterm" }, - { SIGHUP, 3, "SIGHUP", "sighup" }, - { SIGUSR1, 2, "SIGUSR1", "sigusr1" }, - { SIGUSR2, 1, "SIGUSR2", "sigusr2" } -}; +static const struct signame signames[] =3D { { SIGINT, 5, "SIGINT", "sigin= t" }, + { SIGTERM, 4, "SIGTERM", "sigte= rm" }, + { SIGHUP, 3, "SIGHUP", "sighup"= }, + { SIGUSR1, 2, "SIGUSR1", "sigus= r1" }, + { SIGUSR2, 1, "SIGUSR2", "sigus= r2" } }; /* mask for hard signals from management or windows */ static unsigned long long ignored_hard_signals_mask; @@ -209,8 +208,7 @@ if (try_throw_signal(&siginfo_static, signum, SIG_SOURCE_SOFT)) { siginfo_static.signal_text =3D signal_text; - msg(D_SIGNAL_DEBUG, "Throw signal (soft): %s (%s)", signal_name(si= gnum, true), - signal_text); + msg(D_SIGNAL_DEBUG, "Throw signal (soft): %s (%s)", signal_name(si= gnum, true), signal_text); } else { @@ -241,8 +239,7 @@ { si->source =3D SIG_SOURCE_CONNECTION_FAILED; } - msg(D_SIGNAL_DEBUG, "register signal: %s (%s)", signal_name(signum= , true), - signal_text); + msg(D_SIGNAL_DEBUG, "register signal: %s (%s)", signal_name(signum= , true), signal_text); } else { @@ -330,7 +327,8 @@ break; default: - msg(msglevel, "Unknown signal %d [%s,%s] received by %s", = si->signal_received, hs, type, t); + msg(msglevel, "Unknown signal %d [%s,%s] received by %s", = si->signal_received, hs, + type, t); break; } } @@ -365,13 +363,10 @@ if (state >=3D 0) { - management_set_state(management, - state, - si->signal_text ? si->signal_text : signa= l_name(si->signal_received, true), - NULL, - NULL, - NULL, - NULL); + management_set_state(management, state, + si->signal_text ? si->signal_text + : signal_name(si->signal_= received, true), + NULL, NULL, NULL, NULL); } } #endif /* ifdef ENABLE_MANAGEMENT */ @@ -401,7 +396,7 @@ struct sigaction sa; CLEAR(sa); - sigfillset(&block_mask); /* all signals */ + sigfillset(&block_mask); /* all signals */ sa.sa_handler =3D signal_handler; sa.sa_mask =3D block_mask; /* signals blocked inside the handler */ sa.sa_flags =3D SA_RESTART; /* match with the behaviour of signal() on= Linux and BSD */ @@ -430,9 +425,9 @@ struct sigaction sa; CLEAR(sa); - sigfillset(&block_mask); /* all signals */ + sigfillset(&block_mask); /* all signals */ sa.sa_handler =3D signal_handler; - sa.sa_mask =3D block_mask; /* signals blocked inside the handler */ + sa.sa_mask =3D block_mask; /* signals blocked inside the handler */ sa.sa_flags =3D SA_RESTART; /* match with the behaviour of signal() on= Linux and BSD */ signal_mode =3D SM_POST_INIT; @@ -498,8 +493,10 @@ status_printf(so, "Updated,%s", time_string(0, 0, false, &gc)); status_printf(so, "TUN/TAP read bytes," counter_format, c->c2.tun_read= _bytes); status_printf(so, "TUN/TAP write bytes," counter_format, c->c2.tun_wri= te_bytes); - status_printf(so, "TCP/UDP read bytes," counter_format, c->c2.link_rea= d_bytes + c->c2.dco_read_bytes); - status_printf(so, "TCP/UDP write bytes," counter_format, c->c2.link_wr= ite_bytes + c->c2.dco_write_bytes); + status_printf(so, "TCP/UDP read bytes," counter_format, + c->c2.link_read_bytes + c->c2.dco_read_bytes); + status_printf(so, "TCP/UDP write bytes," counter_format, + c->c2.link_write_bytes + c->c2.dco_write_bytes); status_printf(so, "Auth read bytes," counter_format, c->c2.link_read_b= ytes_auth); #ifdef USE_COMP if (c->c2.comp_context) @@ -565,12 +562,13 @@ void process_explicit_exit_notification_timer_wakeup(struct context *c) { - if (event_timeout_trigger(&c->c2.explicit_exit_notification_interval, - &c->c2.timeval, + if (event_timeout_trigger(&c->c2.explicit_exit_notification_interval, = &c->c2.timeval, ETT_DEFAULT)) { - ASSERT(c->c2.explicit_exit_notification_time_wait && c->options.ce= .explicit_exit_notification); - if (now >=3D c->c2.explicit_exit_notification_time_wait + c->optio= ns.ce.explicit_exit_notification) + ASSERT(c->c2.explicit_exit_notification_time_wait + && c->options.ce.explicit_exit_notification); + if (now >=3D c->c2.explicit_exit_notification_time_wait + + c->options.ce.explicit_exit_notification) { event_timeout_clear(&c->c2.explicit_exit_notification_interval= ); register_signal(c->sig, SIGTERM, "exit-with-notification"); @@ -608,8 +606,7 @@ process_sigterm(struct context *c) { bool ret =3D true; - if (c->options.ce.explicit_exit_notification - && !c->c2.explicit_exit_notification_time_wait) + if (c->options.ce.explicit_exit_notification && !c->c2.explicit_exit_n= otification_time_wait) { process_explicit_exit_notification_init(c); ret =3D false; diff --git a/src/openvpn/sig.h b/src/openvpn/sig.h index 93219f7..7e5dd9f 100644 --- a/src/openvpn/sig.h +++ b/src/openvpn/sig.h @@ -26,8 +26,8 @@ #include "status.h" #include "win32.h" -#define SIG_SOURCE_SOFT 0 -#define SIG_SOURCE_HARD 1 +#define SIG_SOURCE_SOFT 0 +#define SIG_SOURCE_HARD 1 /* CONNECTION_FAILED is also a "soft" status, * It is thrown if a connection attempt fails */ diff --git a/src/openvpn/socket.c b/src/openvpn/socket.c index 8510e1d..8fc10bc 100644 --- a/src/openvpn/socket.c +++ b/src/openvpn/socket.c @@ -60,8 +60,7 @@ * Convert sockflags/getaddr_flags into getaddr_flags */ static unsigned int -sf2gaf(const unsigned int getaddr_flags, - const unsigned int sockflags) +sf2gaf(const unsigned int getaddr_flags, const unsigned int sockflags) { if (sockflags & SF_HOST_RANDOMIZE) { @@ -77,9 +76,8 @@ * Functions related to the translation of DNS names to IP addresses. */ static int -get_addr_generic(sa_family_t af, unsigned int flags, const char *hostname, - void *network, unsigned int *netbits, - int resolve_retry_seconds, struct signal_info *sig_info, +get_addr_generic(sa_family_t af, unsigned int flags, const char *hostname,= void *network, + unsigned int *netbits, int resolve_retry_seconds, struct = signal_info *sig_info, int msglevel) { char *endp, *sep, *var_host =3D NULL; @@ -108,9 +106,7 @@ break; default: - msg(M_WARN, - "Unsupported AF family passed to getaddrinfo for %s (%d)", - hostname, af); + msg(M_WARN, "Unsupported AF family passed to getaddrinfo for %= s (%d)", hostname, af); goto out; } @@ -122,8 +118,7 @@ var_host =3D strdup(hostname); if (!var_host) { - msg(M_NONFATAL | M_ERRNO, - "Can't allocate hostname buffer for getaddrinfo"); + msg(M_NONFATAL | M_ERRNO, "Can't allocate hostname buffer for geta= ddrinfo"); goto out; } @@ -134,15 +129,14 @@ bits =3D strtoul(sep + 1, &endp, 10); if ((*endp !=3D '\0') || (bits > max_bits)) { - msg(msglevel, "IP prefix '%s': invalid '/bits' spec (%s)", hos= tname, - sep + 1); + msg(msglevel, "IP prefix '%s': invalid '/bits' spec (%s)", hos= tname, sep + 1); goto out; } *sep =3D '\0'; } - ret =3D openvpn_getaddrinfo(flags & ~GETADDR_HOST_ORDER, var_host, NUL= L, - resolve_retry_seconds, sig_info, af, &ai); + ret =3D openvpn_getaddrinfo(flags & ~GETADDR_HOST_ORDER, var_host, NUL= L, resolve_retry_seconds, + sig_info, af, &ai); if ((ret =3D=3D 0) && network) { struct in6_addr *ip6; @@ -167,8 +161,7 @@ default: /* can't get here because 'af' was previously checked */ - msg(M_WARN, - "Unsupported AF family for %s (%d)", var_host, af); + msg(M_WARN, "Unsupported AF family for %s (%d)", var_host,= af); goto out; } } @@ -191,19 +184,15 @@ } in_addr_t -getaddr(unsigned int flags, - const char *hostname, - int resolve_retry_seconds, - bool *succeeded, +getaddr(unsigned int flags, const char *hostname, int resolve_retry_second= s, bool *succeeded, struct signal_info *sig_info) { in_addr_t addr; int status; - status =3D get_addr_generic(AF_INET, flags, hostname, &addr, NULL, - resolve_retry_seconds, sig_info, - M_WARN); - if (status=3D=3D0) + status =3D get_addr_generic(AF_INET, flags, hostname, &addr, NULL, res= olve_retry_seconds, + sig_info, M_WARN); + if (status =3D=3D 0) { if (succeeded) { @@ -222,16 +211,15 @@ } bool -get_ipv6_addr(const char *hostname, struct in6_addr *network, - unsigned int *netbits, int msglevel) +get_ipv6_addr(const char *hostname, struct in6_addr *network, unsigned int= *netbits, int msglevel) { - if (get_addr_generic(AF_INET6, GETADDR_RESOLVE, hostname, network, net= bits, - 0, NULL, msglevel) < 0) + if (get_addr_generic(AF_INET6, GETADDR_RESOLVE, hostname, network, net= bits, 0, NULL, msglevel) + < 0) { return false; } - return true; /* parsing OK, values set */ + return true; /* parsing OK, values set */ } static inline bool @@ -256,12 +244,8 @@ * otherwise. (like getaddrinfo) */ static int -get_cached_dns_entry(struct cached_dns_entry *dns_cache, - const char *hostname, - const char *servname, - int ai_family, - int resolve_flags, - struct addrinfo **ai) +get_cached_dns_entry(struct cached_dns_entry *dns_cache, const char *hostn= ame, const char *servname, + int ai_family, int resolve_flags, struct addrinfo **a= i) { struct cached_dns_entry *ph; int flags; @@ -271,10 +255,8 @@ for (ph =3D dns_cache; ph; ph =3D ph->next) { - if (streqnull(ph->hostname, hostname) - && streqnull(ph->servname, servname) - && ph->ai_family =3D=3D ai_family - && ph->flags =3D=3D flags) + if (streqnull(ph->hostname, hostname) && streqnull(ph->servname, s= ervname) + && ph->ai_family =3D=3D ai_family && ph->flags =3D=3D flags) { *ai =3D ph->ai; return 0; @@ -285,28 +267,19 @@ static int -do_preresolve_host(struct context *c, - const char *hostname, - const char *servname, - const int af, +do_preresolve_host(struct context *c, const char *hostname, const char *se= rvname, const int af, const int flags) { struct addrinfo *ai; int status; - if (get_cached_dns_entry(c->c1.dns_cache, - hostname, - servname, - af, - flags, - &ai) =3D=3D 0) + if (get_cached_dns_entry(c->c1.dns_cache, hostname, servname, af, flag= s, &ai) =3D=3D 0) { /* entry already cached, return success */ return 0; } - status =3D openvpn_getaddrinfo(flags, hostname, servname, - c->options.resolve_retry_seconds, NULL, + status =3D openvpn_getaddrinfo(flags, hostname, servname, c->options.r= esolve_retry_seconds, NULL, af, &ai); if (status =3D=3D 0) { @@ -333,7 +306,6 @@ } gc_addspecial(ai, &gc_freeaddrinfo_callback, &c->gc); - } return status; } @@ -342,10 +314,8 @@ do_preresolve(struct context *c) { struct connection_list *l =3D c->options.connection_list; - const unsigned int preresolve_flags =3D GETADDR_RESOLVE - |GETADDR_UPDATE_MANAGEMENT_STATE - |GETADDR_MENTION_RESOLVE_RETRY - |GETADDR_FATAL; + const unsigned int preresolve_flags =3D GETADDR_RESOLVE | GETADDR_UPDA= TE_MANAGEMENT_STATE + | GETADDR_MENTION_RESOLVE_RETRY = | GETADDR_FATAL; for (int i =3D 0; i < l->len; ++i) @@ -378,8 +348,7 @@ /* HTTP remote hostname does not need to be resolved */ if (!ce->http_proxy_options) { - status =3D do_preresolve_host(c, remote, ce->remote_port, - ce->af, flags); + status =3D do_preresolve_host(c, remote, ce->remote_port, ce->= af, flags); if (status !=3D 0) { goto err; @@ -389,11 +358,8 @@ /* Preresolve proxy */ if (ce->http_proxy_options) { - status =3D do_preresolve_host(c, - ce->http_proxy_options->server, - ce->http_proxy_options->port, - ce->af, - preresolve_flags); + status =3D do_preresolve_host(c, ce->http_proxy_options->serve= r, + ce->http_proxy_options->port, ce->= af, preresolve_flags); if (status !=3D 0) { @@ -403,11 +369,8 @@ if (ce->socks_proxy_server) { - status =3D do_preresolve_host(c, - ce->socks_proxy_server, - ce->socks_proxy_port, - ce->af, - flags); + status =3D + do_preresolve_host(c, ce->socks_proxy_server, ce->socks_pr= oxy_port, ce->af, flags); if (status !=3D 0) { goto err; @@ -433,10 +396,8 @@ { goto err; } - } } - } return; @@ -453,9 +414,11 @@ { switch (af) { - case AF_INET: return "[AF_INET]"; + case AF_INET: + return "[AF_INET]"; - case AF_INET6: return "[AF_INET6]"; + case AF_INET6: + return "[AF_INET6]"; } return ""; } @@ -465,17 +428,13 @@ * If resolve error, try again for resolve_retry_seconds seconds. */ int -openvpn_getaddrinfo(unsigned int flags, - const char *hostname, - const char *servname, - int resolve_retry_seconds, - struct signal_info *sig_info, - int ai_family, +openvpn_getaddrinfo(unsigned int flags, const char *hostname, const char *= servname, + int resolve_retry_seconds, struct signal_info *sig_inf= o, int ai_family, struct addrinfo **res) { struct addrinfo hints; int status; - struct signal_info sigrec =3D {0}; + struct signal_info sigrec =3D { 0 }; int msglevel =3D (flags & GETADDR_FATAL) ? M_FATAL : D_RESOLVE_ERRORS; struct gc_arena gc =3D gc_new(); const char *print_hostname; @@ -500,8 +459,7 @@ msglevel |=3D M_MSG_VIRT_OUT; } - if ((flags & (GETADDR_FATAL_ON_SIGNAL|GETADDR_WARN_ON_SIGNAL)) - && !sig_info) + if ((flags & (GETADDR_FATAL_ON_SIGNAL | GETADDR_WARN_ON_SIGNAL)) && !s= ig_info) { sig_info =3D &sigrec; } @@ -533,12 +491,12 @@ status =3D getaddrinfo(hostname, servname, &hints, res); - if (status !=3D 0) /* parse as numeric address failed? */ + if (status !=3D 0) /* parse as numeric address fa= iled? */ { const int fail_wait_interval =3D 5; /* seconds */ /* Add +4 to cause integer division rounding up (1 + 4) =3D 5, (0+= 4)/5=3D0 */ - int resolve_retries =3D (flags & GETADDR_TRY_ONCE) ? 1 : - ((resolve_retry_seconds + 4)/ fail_wait_inte= rval); + int resolve_retries =3D + (flags & GETADDR_TRY_ONCE) ? 1 : ((resolve_retry_seconds + 4) = / fail_wait_interval); const char *fmt; int level =3D 0; @@ -561,8 +519,7 @@ } fmt =3D "RESOLVE: Cannot resolve host address: %s:%s%s (%s)"; - if ((flags & GETADDR_MENTION_RESOLVE_RETRY) - && !resolve_retry_seconds) + if ((flags & GETADDR_MENTION_RESOLVE_RETRY) && !resolve_retry_seco= nds) { fmt =3D "RESOLVE: Cannot resolve host address: %s:%s%s (%s)" "(I would have retried this name query if you had " @@ -571,8 +528,8 @@ if (!(flags & GETADDR_RESOLVE) || status =3D=3D EAI_FAIL) { - msg(msglevel, "RESOLVE: Cannot parse IP address: %s:%s (%s)", - print_hostname, print_servname, gai_strerror(status)); + msg(msglevel, "RESOLVE: Cannot parse IP address: %s:%s (%s)", = print_hostname, + print_servname, gai_strerror(status)); goto done; } @@ -581,12 +538,7 @@ { if (management) { - management_set_state(management, - OPENVPN_STATE_RESOLVE, - NULL, - NULL, - NULL, - NULL, + management_set_state(management, OPENVPN_STATE_RESOLVE, NU= LL, NULL, NULL, NULL, NULL); } } @@ -603,9 +555,8 @@ #endif /* try hostname lookup */ hints.ai_flags &=3D ~AI_NUMERICHOST; - dmsg(D_SOCKET_DEBUG, - "GETADDRINFO flags=3D0x%04x ai_family=3D%d ai_socktype=3D= %d", - flags, hints.ai_family, hints.ai_socktype); + dmsg(D_SOCKET_DEBUG, "GETADDRINFO flags=3D0x%04x ai_family=3D%= d ai_socktype=3D%d", flags, + hints.ai_family, hints.ai_socktype); status =3D getaddrinfo(hostname, servname, &hints, res); if (sig_info) @@ -616,9 +567,8 @@ /* why are we overwriting SIGUSR1 ? */ if (signal_reset(sig_info, SIGUSR1) =3D=3D SIGUSR1) /*= ignore SIGUSR1 */ { - msg(level, - "RESOLVE: Ignored SIGUSR1 signal received duri= ng " - "DNS resolution attempt"); + msg(level, "RESOLVE: Ignored SIGUSR1 signal receiv= ed during " + "DNS resolution attempt"); } else { @@ -650,11 +600,7 @@ level =3D D_RESOLVE_ERRORS; } - msg(level, - fmt, - print_hostname, - print_servname, - getaddrinfo_addr_family_name(ai_family), + msg(level, fmt, print_hostname, print_servname, getaddrinfo_ad= dr_family_name(ai_family), gai_strerror(status)); if (--resolve_retries <=3D 0) @@ -679,9 +625,8 @@ /* 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 becaus= e the " + "hostname is an IP address"); } } @@ -718,11 +663,11 @@ { if (a < 256 && b < 256 && c < 256 && d < 256) { - addr->s_addr =3D htonl(a<<24 | b<<16 | c<<8 | d); + addr->s_addr =3D htonl(a << 24 | b << 16 | c << 8 | d); return OIA_IP; /* good dotted quad */ } } - if (string_class(dotted_quad, CC_DIGIT|CC_DOT, 0)) + if (string_class(dotted_quad, CC_DIGIT | CC_DOT, 0)) { return OIA_ERROR; /* probably a badly formatted dotted quad */ } @@ -800,7 +745,7 @@ /* verify that string will convert to IPv6 address */ { struct in6_addr a6; - return inet_pton( AF_INET6, ipv6_text_addr, &a6 ) =3D=3D 1; + return inet_pton(AF_INET6, ipv6_text_addr, &a6) =3D=3D 1; } } @@ -810,7 +755,7 @@ if (addr) { const size_t len =3D strlen(addr); - return len > 0 && len <=3D 255 && string_class(addr, CC_ALNUM|CC_D= ASH|CC_DOT, 0); + return len > 0 && len <=3D 255 && string_class(addr, CC_ALNUM | CC= _DASH | CC_DOT, 0); } else { @@ -859,7 +804,7 @@ while ((c =3D *p++)) { - if ( (c >=3D '0' && c <=3D '9') || (c >=3D 'a' && c <=3D 'f') = || (c >=3D 'A' && c <=3D 'F') ) + if ((c >=3D '0' && c <=3D '9') || (c >=3D 'a' && c <=3D 'f') |= | (c >=3D 'A' && c <=3D 'F')) { ++nnum; if (nnum > 2) @@ -890,8 +835,7 @@ socklen_t len; len =3D sizeof(val); - if (getsockopt(sd, SOL_SOCKET, SO_SNDBUF, (void *) &val, &len) =3D=3D 0 - && len =3D=3D sizeof(val)) + if (getsockopt(sd, SOL_SOCKET, SO_SNDBUF, (void *)&val, &len) =3D=3D 0= && len =3D=3D sizeof(val)) { return val; } @@ -903,7 +847,7 @@ socket_set_sndbuf(socket_descriptor_t sd, int size) { #if defined(SOL_SOCKET) && defined(SO_SNDBUF) - if (setsockopt(sd, SOL_SOCKET, SO_SNDBUF, (void *) &size, sizeof(size)= ) !=3D 0) + if (setsockopt(sd, SOL_SOCKET, SO_SNDBUF, (void *)&size, sizeof(size))= !=3D 0) { msg(M_WARN, "NOTE: setsockopt SO_SNDBUF=3D%d failed", size); } @@ -918,8 +862,7 @@ socklen_t len; len =3D sizeof(val); - if (getsockopt(sd, SOL_SOCKET, SO_RCVBUF, (void *) &val, &len) =3D=3D 0 - && len =3D=3D sizeof(val)) + if (getsockopt(sd, SOL_SOCKET, SO_RCVBUF, (void *)&val, &len) =3D=3D 0= && len =3D=3D sizeof(val)) { return val; } @@ -931,7 +874,7 @@ socket_set_rcvbuf(socket_descriptor_t sd, int size) { #if defined(SOL_SOCKET) && defined(SO_RCVBUF) - if (setsockopt(sd, SOL_SOCKET, SO_RCVBUF, (void *) &size, sizeof(size)= ) !=3D 0) + if (setsockopt(sd, SOL_SOCKET, SO_RCVBUF, (void *)&size, sizeof(size))= !=3D 0) { msg(M_WARN, "NOTE: setsockopt SO_RCVBUF=3D%d failed", size); return false; @@ -941,31 +884,25 @@ } void -socket_set_buffers(socket_descriptor_t fd, const struct socket_buffer_size= *sbs, - bool reduce_size) +socket_set_buffers(socket_descriptor_t fd, const struct socket_buffer_size= *sbs, bool reduce_size) { if (sbs) { const int sndbuf_old =3D socket_get_sndbuf(fd); const int rcvbuf_old =3D socket_get_rcvbuf(fd); - if (sbs->sndbuf - && (reduce_size || sndbuf_old < sbs->sndbuf)) + if (sbs->sndbuf && (reduce_size || sndbuf_old < sbs->sndbuf)) { socket_set_sndbuf(fd, sbs->sndbuf); } - if (sbs->rcvbuf - && (reduce_size || rcvbuf_old < sbs->rcvbuf)) + if (sbs->rcvbuf && (reduce_size || rcvbuf_old < sbs->rcvbuf)) { socket_set_rcvbuf(fd, sbs->rcvbuf); } - msg(D_OSBUF, "Socket Buffers: R=3D[%d->%d] S=3D[%d->%d]", - rcvbuf_old, - socket_get_rcvbuf(fd), - sndbuf_old, - socket_get_sndbuf(fd)); + msg(D_OSBUF, "Socket Buffers: R=3D[%d->%d] S=3D[%d->%d]", rcvbuf_o= ld, socket_get_rcvbuf(fd), + sndbuf_old, socket_get_sndbuf(fd)); } } @@ -977,7 +914,7 @@ socket_set_tcp_nodelay(socket_descriptor_t sd, int state) { #if defined(_WIN32) || (defined(IPPROTO_TCP) && defined(TCP_NODELAY)) - if (setsockopt(sd, IPPROTO_TCP, TCP_NODELAY, (void *) &state, sizeof(s= tate)) !=3D 0) + if (setsockopt(sd, IPPROTO_TCP, TCP_NODELAY, (void *)&state, sizeof(st= ate)) !=3D 0) { msg(M_WARN, "NOTE: setsockopt TCP_NODELAY=3D%d failed", state); return false; @@ -987,7 +924,7 @@ dmsg(D_OSBUF, "Socket flags: TCP_NODELAY=3D%d succeeded", state); return true; } -#else /* if defined(_WIN32) || (defined(IPPROTO_TCP) && defined(TCP_NODEL= AY)) */ +#else /* if defined(_WIN32) || (defined(IPPROTO_TCP) && defined(TCP_NODELA= Y)) */ msg(M_WARN, "NOTE: setsockopt TCP_NODELAY=3D%d failed (No kernel suppo= rt)", state); return false; #endif @@ -997,7 +934,7 @@ socket_set_mark(socket_descriptor_t sd, int mark) { #if defined(TARGET_LINUX) && HAVE_DECL_SO_MARK - if (mark && setsockopt(sd, SOL_SOCKET, SO_MARK, (void *) &mark, sizeof= (mark)) !=3D 0) + if (mark && setsockopt(sd, SOL_SOCKET, SO_MARK, (void *)&mark, sizeof(= mark)) !=3D 0) { msg(M_WARN, "NOTE: setsockopt SO_MARK=3D%d failed", mark); } @@ -1065,8 +1002,7 @@ /* set SO_REUSEADDR on socket */ { int on =3D 1; - if (setsockopt(sd, SOL_SOCKET, SO_REUSEADDR, - (void *) &on, sizeof(on)) < 0) + if (setsockopt(sd, SOL_SOCKET, SO_REUSEADDR, (void *)&on, sizeof(o= n)) < 0) { msg(M_ERR, "TCP: Cannot setsockopt SO_REUSEADDR on TCP socket"= ); } @@ -1099,31 +1035,29 @@ if (addrinfo->ai_family =3D=3D AF_INET) { #if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST) - if (setsockopt(sd, SOL_IP, IP_PKTINFO, - (void *)&pad, sizeof(pad)) < 0) + if (setsockopt(sd, SOL_IP, IP_PKTINFO, (void *)&pad, sizeof(pa= d)) < 0) { msg(M_ERR, "UDP: failed setsockopt for IP_PKTINFO"); } #elif defined(IP_RECVDSTADDR) - if (setsockopt(sd, IPPROTO_IP, IP_RECVDSTADDR, - (void *)&pad, sizeof(pad)) < 0) + if (setsockopt(sd, IPPROTO_IP, IP_RECVDSTADDR, (void *)&pad, s= izeof(pad)) < 0) { msg(M_ERR, "UDP: failed setsockopt for IP_RECVDSTADDR"); } -#else /* if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST) */ +#else /* if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST) */ #error ENABLE_IP_PKTINFO is set without IP_PKTINFO xor IP_RECVDSTADDR (fix= syshead.h) #endif } else if (addrinfo->ai_family =3D=3D AF_INET6) { #ifndef IPV6_RECVPKTINFO /* Some older Darwin platforms require this */ - if (setsockopt(sd, IPPROTO_IPV6, IPV6_PKTINFO, - (void *)&pad, sizeof(pad)) < 0) + if (setsockopt(sd, IPPROTO_IPV6, IPV6_PKTINFO, (void *)&pad, s= izeof(pad)) < 0) #else - if (setsockopt(sd, IPPROTO_IPV6, IPV6_RECVPKTINFO, - (void *)&pad, sizeof(pad)) < 0) + if (setsockopt(sd, IPPROTO_IPV6, IPV6_RECVPKTINFO, (void *)&pa= d, sizeof(pad)) < 0) #endif - { msg(M_ERR, "UDP: failed setsockopt for IPV6_RECVPKTINFO");} + { + msg(M_ERR, "UDP: failed setsockopt for IPV6_RECVPKTINFO"); + } } } #endif /* if ENABLE_IP_PKTINFO */ @@ -1143,14 +1077,12 @@ { if (sock->socks_proxy && sock->info.proto =3D=3D PROTO_UDP) { - socket_bind(sock->ctrl_sd, sock->info.lsa->bind_local, - ai_family, "SOCKS", false); + socket_bind(sock->ctrl_sd, sock->info.lsa->bind_local, ai_fami= ly, "SOCKS", false); } else { - socket_bind(sock->sd, sock->info.lsa->bind_local, - ai_family, - "TCP/UDP", sock->info.bind_ipv6_only); + socket_bind(sock->sd, sock->info.lsa->bind_local, ai_family, "= TCP/UDP", + sock->info.bind_ipv6_only); } } } @@ -1198,11 +1130,12 @@ if (sock->bind_dev) { msg(M_INFO, "Using bind-dev %s", sock->bind_dev); - if (setsockopt(sock->sd, SOL_SOCKET, SO_BINDTODEVICE, sock->bind_d= ev, strlen(sock->bind_dev) + 1) !=3D 0) + if (setsockopt(sock->sd, SOL_SOCKET, SO_BINDTODEVICE, sock->bind_d= ev, + strlen(sock->bind_dev) + 1) + !=3D 0) { - msg(M_WARN|M_ERRNO, "WARN: setsockopt SO_BINDTODEVICE=3D%s fai= led", sock->bind_dev); + msg(M_WARN | M_ERRNO, "WARN: setsockopt SO_BINDTODEVICE=3D%s f= ailed", sock->bind_dev); } - } #endif @@ -1237,9 +1170,7 @@ * Functions used for establishing a TCP stream connection. */ static void -socket_do_listen(socket_descriptor_t sd, - const struct addrinfo *local, - bool do_listen, +socket_do_listen(socket_descriptor_t sd, const struct addrinfo *local, boo= l do_listen, bool do_set_nonblock) { struct gc_arena gc =3D gc_new(); @@ -1264,9 +1195,7 @@ } socket_descriptor_t -socket_do_accept(socket_descriptor_t sd, - struct link_socket_actual *act, - const bool nowait) +socket_do_accept(socket_descriptor_t sd, struct link_socket_actual *act, c= onst bool nowait) { /* af_addr_size WILL return 0 in this case if AFs other than AF_INET * are compiled because act is empty here. @@ -1314,7 +1243,8 @@ /* only valid if we have remote_len_af!=3D0 */ else if (remote_len_af && remote_len !=3D remote_len_af) { - msg(D_LINK_ERRORS, "TCP: Received strange incoming connection with= unknown address length=3D%d", remote_len); + msg(D_LINK_ERRORS, + "TCP: Received strange incoming connection with unknown addres= s length=3D%d", remote_len); openvpn_close_socket(new_sd); new_sd =3D SOCKET_UNDEFINED; } @@ -1331,19 +1261,14 @@ tcp_connection_established(const struct link_socket_actual *act) { struct gc_arena gc =3D gc_new(); - msg(M_INFO, "TCP connection established with %s", - print_link_socket_actual(act, &gc)); + msg(M_INFO, "TCP connection established with %s", print_link_socket_ac= tual(act, &gc)); gc_free(&gc); } static socket_descriptor_t -socket_listen_accept(socket_descriptor_t sd, - struct link_socket_actual *act, - const char *remote_dynamic, - const struct addrinfo *local, - bool do_listen, - bool nowait, - volatile int *signal_received) +socket_listen_accept(socket_descriptor_t sd, struct link_socket_actual *ac= t, + const char *remote_dynamic, const struct addrinfo *lo= cal, bool do_listen, + bool nowait, volatile int *signal_received) { struct gc_arena gc =3D gc_new(); /* struct openvpn_sockaddr *remote =3D &act->dest; */ @@ -1397,8 +1322,7 @@ if (ai && !addrlist_match(&remote_verify, ai)) { - msg(M_WARN, - "TCP NOTE: Rejected connection attempt from %s due to = --remote setting", + msg(M_WARN, "TCP NOTE: Rejected connection attempt from %s= due to --remote setting", print_link_socket_actual(act, &gc)); if (openvpn_close_socket(new_sd)) { @@ -1430,10 +1354,7 @@ } void -socket_bind(socket_descriptor_t sd, - struct addrinfo *local, - int ai_family, - const char *prefix, +socket_bind(socket_descriptor_t sd, struct addrinfo *local, int ai_family,= const char *prefix, bool ipv6only) { struct gc_arena gc =3D gc_new(); @@ -1460,33 +1381,30 @@ } if (!cur) { - msg(M_FATAL, "%s: Socket bind failed: Addr to bind has no %s recor= d", - prefix, addr_family_name(ai_family)); + msg(M_FATAL, "%s: Socket bind failed: Addr to bind has no %s recor= d", prefix, + addr_family_name(ai_family)); } if (ai_family =3D=3D AF_INET6) { - int v6only =3D ipv6only ? 1 : 0; /* setsockopt must have an "int"= */ + int v6only =3D ipv6only ? 1 : 0; /* setsockopt must have an "int" = */ msg(M_INFO, "setsockopt(IPV6_V6ONLY=3D%d)", v6only); - if (setsockopt(sd, IPPROTO_IPV6, IPV6_V6ONLY, (void *) &v6only, si= zeof(v6only))) + if (setsockopt(sd, IPPROTO_IPV6, IPV6_V6ONLY, (void *)&v6only, siz= eof(v6only))) { - msg(M_NONFATAL|M_ERRNO, "Setting IPV6_V6ONLY=3D%d failed", v6o= nly); + msg(M_NONFATAL | M_ERRNO, "Setting IPV6_V6ONLY=3D%d failed", v= 6only); } } if (bind(sd, cur->ai_addr, cur->ai_addrlen)) { - msg(M_FATAL | M_ERRNO, "%s: Socket bind failed on local address %s= ", - prefix, + msg(M_FATAL | M_ERRNO, "%s: Socket bind failed on local address %s= ", prefix, print_sockaddr_ex(local->ai_addr, ":", PS_SHOW_PORT, &gc)); } gc_free(&gc); } int -openvpn_connect(socket_descriptor_t sd, - const struct sockaddr *remote, - int connect_timeout, +openvpn_connect(socket_descriptor_t sd, const struct sockaddr *remote, int= connect_timeout, volatile int *signal_received) { int status =3D 0; @@ -1506,7 +1424,7 @@ #else status =3D=3D EINPROGRESS #endif - ) + ) { while (true) { @@ -1561,7 +1479,7 @@ socklen_t len; len =3D sizeof(val); - if (getsockopt(sd, SOL_SOCKET, SO_ERROR, (void *) &val, &l= en) =3D=3D 0 + if (getsockopt(sd, SOL_SOCKET, SO_ERROR, (void *)&val, &le= n) =3D=3D 0 && len =3D=3D sizeof(val)) { status =3D val; @@ -1586,43 +1504,31 @@ if (ai->ai_family =3D=3D AF_INET) { - actual->dest.addr.in4 =3D - *((struct sockaddr_in *) ai->ai_addr); + actual->dest.addr.in4 =3D *((struct sockaddr_in *)ai->ai_addr); } else if (ai->ai_family =3D=3D AF_INET6) { - actual->dest.addr.in6 =3D - *((struct sockaddr_in6 *) ai->ai_addr); + actual->dest.addr.in6 =3D *((struct sockaddr_in6 *)ai->ai_addr); } else { ASSERT(0); } - } static void -socket_connect(socket_descriptor_t *sd, - const struct sockaddr *dest, - const int connect_timeout, +socket_connect(socket_descriptor_t *sd, const struct sockaddr *dest, const= int connect_timeout, struct signal_info *sig_info) { struct gc_arena gc =3D gc_new(); int status; - msg(M_INFO, "Attempting to establish TCP connection with %s", - print_sockaddr(dest, &gc)); + msg(M_INFO, "Attempting to establish TCP connection with %s", print_so= ckaddr(dest, &gc)); #ifdef ENABLE_MANAGEMENT if (management) { - management_set_state(management, - OPENVPN_STATE_TCP_CONNECT, - NULL, - NULL, - NULL, - NULL, - NULL); + management_set_state(management, OPENVPN_STATE_TCP_CONNECT, NULL, = NULL, NULL, NULL, NULL); } #endif @@ -1637,9 +1543,8 @@ if (status) { - - msg(D_LINK_ERRORS, "TCP: connect to %s failed: %s", - print_sockaddr(dest, &gc), strerror(status)); + msg(D_LINK_ERRORS, "TCP: connect to %s failed: %s", print_sockaddr= (dest, &gc), + strerror(status)); openvpn_close_socket(*sd); *sd =3D SOCKET_UNDEFINED; @@ -1647,8 +1552,7 @@ } else { - msg(M_INFO, "TCP connection established with %s", - print_sockaddr(dest, &gc)); + msg(M_INFO, "TCP connection established with %s", print_sockaddr(d= est, &gc)); } done: @@ -1661,15 +1565,12 @@ * such as TCP. */ -static void -stream_buf_init(struct stream_buf *sb, struct buffer *buf, - const unsigned int sockflags, const int proto); +static void stream_buf_init(struct stream_buf *sb, struct buffer *buf, con= st unsigned int sockflags, + const int proto); -static void -stream_buf_close(struct stream_buf *sb); +static void stream_buf_close(struct stream_buf *sb); -static bool -stream_buf_added(struct stream_buf *sb, int length_added); +static bool stream_buf_added(struct stream_buf *sb, int length_added); /* For stream protocols, allocate a buffer to build up packet. * Called after frame has been finalized. */ @@ -1687,16 +1588,12 @@ if (link_socket_connection_oriented(sock)) { #ifdef _WIN32 - stream_buf_init(&sock->stream_buf, - &sock->reads.buf_init, - sock->sockflags, + stream_buf_init(&sock->stream_buf, &sock->reads.buf_init, sock->so= ckflags, sock->info.proto); #else alloc_buf_sock_tun(&sock->stream_buf_data, frame); - stream_buf_init(&sock->stream_buf, - &sock->stream_buf_data, - sock->sockflags, + stream_buf_init(&sock->stream_buf, &sock->stream_buf_data, sock->s= ockflags, sock->info.proto); #endif } @@ -1710,8 +1607,7 @@ /* resolve local address if undefined */ if (!sock->info.lsa->bind_local) { - int flags =3D GETADDR_RESOLVE | GETADDR_WARN_ON_SIGNAL - |GETADDR_FATAL | GETADDR_PASSIVE; + int flags =3D GETADDR_RESOLVE | GETADDR_WARN_ON_SIGNAL | GETADDR_F= ATAL | GETADDR_PASSIVE; int status; if (proto_is_dgram(sock->info.proto)) @@ -1720,24 +1616,19 @@ } /* will return AF_{INET|INET6}from local_host */ - status =3D get_cached_dns_entry(sock->dns_cache, - sock->local_host, - sock->local_port, - af, - flags, - &sock->info.lsa->bind_local); + status =3D get_cached_dns_entry(sock->dns_cache, sock->local_host,= sock->local_port, af, + flags, &sock->info.lsa->bind_local); if (status) { - status =3D openvpn_getaddrinfo(flags, sock->local_host, sock->= local_port, 0, - NULL, af, &sock->info.lsa->bind_l= ocal); + status =3D openvpn_getaddrinfo(flags, sock->local_host, sock->= local_port, 0, NULL, af, + &sock->info.lsa->bind_local); } - if (status !=3D0) + if (status !=3D 0) { - msg(M_FATAL, "getaddrinfo() failed for local \"%s:%s\": %s", - sock->local_host, sock->local_port, - gai_strerror(status)); + msg(M_FATAL, "getaddrinfo() failed for local \"%s:%s\": %s", s= ock->local_host, + sock->local_port, gai_strerror(status)); } /* the address family returned by openvpn_getaddrinfo() should be @@ -1759,9 +1650,7 @@ } static void -resolve_remote(struct link_socket *sock, - int phase, - const char **remote_dynamic, +resolve_remote(struct link_socket *sock, int phase, const char **remote_dy= namic, struct signal_info *sig_info) { volatile int *signal_received =3D sig_info ? &sig_info->signal_receive= d : NULL; @@ -1772,7 +1661,8 @@ { if (sock->remote_host) { - unsigned int flags =3D sf2gaf(GETADDR_RESOLVE|GETADDR_UPDATE_M= ANAGEMENT_STATE, sock->sockflags); + unsigned int flags =3D + sf2gaf(GETADDR_RESOLVE | GETADDR_UPDATE_MANAGEMENT_STATE, = sock->sockflags); int retry =3D 0; int status =3D -1; struct addrinfo *ai; @@ -1819,15 +1709,12 @@ } - status =3D get_cached_dns_entry(sock->dns_cache, - sock->remote_host, - sock->remote_port, - sock->info.af, - flags, &ai); + status =3D get_cached_dns_entry(sock->dns_cache, sock->remote_= host, sock->remote_port, + sock->info.af, flags, &ai); if (status) { - status =3D openvpn_getaddrinfo(flags, sock->remote_host, s= ock->remote_port, - retry, sig_info, sock->info.a= f, &ai); + status =3D openvpn_getaddrinfo(flags, sock->remote_host, s= ock->remote_port, retry, + sig_info, sock->info.af, &ai); } =20 if (status =3D=3D 0) @@ -1835,19 +1722,14 @@ sock->info.lsa->remote_list =3D ai; sock->info.lsa->current_remote =3D ai; - dmsg(D_SOCKET_DEBUG, - "RESOLVE_REMOTE flags=3D0x%04x phase=3D%d rrs=3D%d si= g=3D%d status=3D%d", - flags, - phase, - retry, - signal_received ? *signal_received : -1, - status); + dmsg(D_SOCKET_DEBUG, "RESOLVE_REMOTE flags=3D0x%04x phase= =3D%d rrs=3D%d sig=3D%d status=3D%d", + flags, phase, retry, signal_received ? *signal_receiv= ed : -1, status); } if (signal_received && *signal_received) { goto done; } - if (status!=3D0) + if (status !=3D 0) { if (signal_received) { @@ -1874,8 +1756,7 @@ CLEAR(sock->info.lsa->actual); if (sock->info.lsa->current_remote) { - set_actual_address(&sock->info.lsa->actual, - sock->info.lsa->current_remote); + set_actual_address(&sock->info.lsa->actual, sock->info.lsa->cu= rrent_remote); } } @@ -1884,7 +1765,6 @@ } - struct link_socket * link_socket_new(void) { @@ -2077,8 +1957,7 @@ } ASSERT(cur); msg(msglevel, "%s link local (bound): %s", - proto2ascii(sock->info.proto, sock->info.af, true), - print_sockaddr(cur->ai_addr, &gc)); + proto2ascii(sock->info.proto, sock->info.af, true), print_sock= addr(cur->ai_addr, &gc)); } else { @@ -2087,12 +1966,8 @@ } /* print active remote address */ - msg(msglevel, "%s link remote: %s", - proto2ascii(sock->info.proto, sock->info.af, true), - print_link_socket_actual_ex(&sock->info.lsa->actual, - ":", - PS_SHOW_PORT_IF_DEFINED, - &gc)); + msg(msglevel, "%s link remote: %s", proto2ascii(sock->info.proto, sock= ->info.af, true), + print_link_socket_actual_ex(&sock->info.lsa->actual, ":", PS_SHOW_= PORT_IF_DEFINED, &gc)); gc_free(&gc); } @@ -2105,26 +1980,17 @@ switch (sock->mode) { case LS_MODE_DEFAULT: - sock->sd =3D socket_listen_accept(sock->sd, - &sock->info.lsa->actual, - remote_dynamic, - sock->info.lsa->bind_local, - true, - false, - signal_received); + sock->sd =3D + socket_listen_accept(sock->sd, &sock->info.lsa->actual, re= mote_dynamic, + sock->info.lsa->bind_local, true, fal= se, signal_received); break; case LS_MODE_TCP_LISTEN: - socket_do_listen(sock->sd, - sock->info.lsa->bind_local, - true, - false); + socket_do_listen(sock->sd, sock->info.lsa->bind_local, true, f= alse); break; case LS_MODE_TCP_ACCEPT_FROM: - sock->sd =3D socket_do_accept(sock->sd, - &sock->info.lsa->actual, - false); + sock->sd =3D socket_do_accept(sock->sd, &sock->info.lsa->actua= l, false); if (!socket_defined(sock->sd)) { register_signal(sig_info, SIGTERM, "socket-undefined"); @@ -2145,10 +2011,8 @@ bool proxy_retry =3D false; do { - socket_connect(&sock->sd, - sock->info.lsa->current_remote->ai_addr, - get_server_poll_remaining_time(sock->server_poll_ti= meout), - sig_info); + socket_connect(&sock->sd, sock->info.lsa->current_remote->ai_addr, + get_server_poll_remaining_time(sock->server_poll_ti= meout), sig_info); if (sig_info->signal_received) { @@ -2157,21 +2021,14 @@ if (sock->http_proxy) { - proxy_retry =3D establish_http_proxy_passthru(sock->http_proxy, - sock->sd, - sock->proxy_dest_h= ost, - sock->proxy_dest_p= ort, - sock->server_poll_= timeout, - &sock->stream_buf.= residual, - sig_info); + proxy_retry =3D establish_http_proxy_passthru( + sock->http_proxy, sock->sd, sock->proxy_dest_host, sock->p= roxy_dest_port, + sock->server_poll_timeout, &sock->stream_buf.residual, sig= _info); } else if (sock->socks_proxy) { - establish_socks_proxy_passthru(sock->socks_proxy, - sock->sd, - sock->proxy_dest_host, - sock->proxy_dest_port, - sock->server_poll_timeout, + establish_socks_proxy_passthru(sock->socks_proxy, sock->sd, so= ck->proxy_dest_host, + sock->proxy_dest_port, sock->se= rver_poll_timeout, sig_info); } if (proxy_retry) @@ -2181,27 +2038,21 @@ } } while (proxy_retry); - } static void phase2_socks_client(struct link_socket *sock, struct signal_info *sig_info) { - socket_connect(&sock->ctrl_sd, - sock->info.lsa->current_remote->ai_addr, - get_server_poll_remaining_time(sock->server_poll_timeou= t), - sig_info); + socket_connect(&sock->ctrl_sd, sock->info.lsa->current_remote->ai_addr, + get_server_poll_remaining_time(sock->server_poll_timeou= t), sig_info); if (sig_info->signal_received) { return; } - establish_socks_proxy_udpassoc(sock->socks_proxy, - sock->ctrl_sd, - &sock->socks_relay.dest, - sock->server_poll_timeout, - sig_info); + establish_socks_proxy_udpassoc(sock->socks_proxy, sock->ctrl_sd, &sock= ->socks_relay.dest, + sock->server_poll_timeout, sig_info); if (sig_info->signal_received) { @@ -2224,8 +2075,7 @@ #if defined(_WIN32) static void -create_socket_dco_win(struct context *c, struct link_socket *sock, - struct signal_info *sig_info) +create_socket_dco_win(struct context *c, struct link_socket *sock, struct = signal_info *sig_info) { /* in P2P mode we must have remote resolved at this point */ struct addrinfo *remoteaddr =3D sock->info.lsa->current_remote; @@ -2273,14 +2123,13 @@ /* finalize socket initialization */ void -link_socket_init_phase2(struct context *c, - struct link_socket *sock) +link_socket_init_phase2(struct context *c, struct link_socket *sock) { const struct frame *frame =3D &c->c2.frame; struct signal_info *sig_info =3D c->sig; const char *remote_dynamic =3D NULL; - struct signal_info sig_save =3D {0}; + struct signal_info sig_save =3D { 0 }; ASSERT(sock); ASSERT(sig_info); @@ -2305,7 +2154,7 @@ } /* Second chance to resolv/create socket */ - resolve_remote(sock, 2, &remote_dynamic, sig_info); + resolve_remote(sock, 2, &remote_dynamic, sig_info); /* If a valid remote has been found, create the socket with its addrin= fo */ #if defined(_WIN32) @@ -2326,7 +2175,7 @@ /* If we have no --remote and have still not figured out the * protocol family to use we will use the first of the bind */ - if (sock->bind_local && !sock->remote_host && sock->info.lsa->bin= d_local) + if (sock->bind_local && !sock->remote_host && sock->info.lsa->bind= _local) { /* Warn if this is because neither v4 or v6 was specified * and we should not connect a remote */ @@ -2360,7 +2209,6 @@ else if (sock->info.proto =3D=3D PROTO_TCP_CLIENT) { phase2_tcp_client(sock, sig_info); - } else if (sock->info.proto =3D=3D PROTO_UDP && sock->socks_proxy) { @@ -2454,7 +2302,8 @@ } static void -ipchange_fmt(const bool include_cmd, struct argv *argv, const struct link_= socket_info *info, struct gc_arena *gc) +ipchange_fmt(const bool include_cmd, struct argv *argv, const struct link_= socket_info *info, + struct gc_arena *gc) { const char *host =3D print_sockaddr_ex(&info->lsa->actual.dest.addr.sa= , " ", PS_SHOW_PORT, gc); if (include_cmd) @@ -2466,13 +2315,11 @@ { argv_printf(argv, "%s", host); } - } void link_socket_connection_initiated(struct link_socket_info *info, - const struct link_socket_actual *act, - const char *common_name, + const struct link_socket_actual *act, con= st char *common_name, struct env_set *es) { struct gc_arena gc =3D gc_new(); @@ -2488,7 +2335,8 @@ { buf_printf(&out, "[%s] ", common_name); } - buf_printf(&out, "Peer Connection Initiated with %s", print_link_s= ocket_actual(&info->lsa->actual, &gc)); + buf_printf(&out, "Peer Connection Initiated with %s", + print_link_socket_actual(&info->lsa->actual, &gc)); msg(M_INFO, "%s", BSTR(&out)); } @@ -2500,7 +2348,8 @@ { struct argv argv =3D argv_new(); ipchange_fmt(false, &argv, info, &gc); - if (plugin_call(info->plugins, OPENVPN_PLUGIN_IPCHANGE, &argv, NUL= L, es) !=3D OPENVPN_PLUGIN_FUNC_SUCCESS) + if (plugin_call(info->plugins, OPENVPN_PLUGIN_IPCHANGE, &argv, NUL= L, es) + !=3D OPENVPN_PLUGIN_FUNC_SUCCESS) { msg(M_WARN, "WARNING: ipchange plugin call failed"); } @@ -2521,8 +2370,7 @@ } void -link_socket_bad_incoming_addr(struct buffer *buf, - const struct link_socket_info *info, +link_socket_bad_incoming_addr(struct buffer *buf, const struct link_socket= _info *info, const struct link_socket_actual *from_addr) { struct gc_arena gc =3D gc_new(); @@ -2534,8 +2382,7 @@ case AF_INET6: msg(D_LINK_ERRORS, "TCP/UDP: Incoming packet rejected from %s[%d], expected p= eer address: %s (allow this incoming source address/port by removing --remo= te or adding --float)", - print_link_socket_actual(from_addr, &gc), - (int)from_addr->dest.addr.sa.sa_family, + print_link_socket_actual(from_addr, &gc), (int)from_addr->= dest.addr.sa.sa_family, print_sockaddr_ex(info->lsa->remote_list->ai_addr, ":", PS= _SHOW_PORT, &gc)); /* print additional remote addresses */ for (ai =3D info->lsa->remote_list->ai_next; ai; ai =3D ai->ai= _next) @@ -2560,16 +2407,16 @@ { const struct link_socket_addr *lsa =3D info->lsa; -/* - * This logic supports "redirect-gateway" semantic, which - * makes sense only for PF_INET routes over PF_INET endpoints - * - * Maybe in the future consider PF_INET6 endpoints also ... - * by now just ignore it - * - * For --remote entries with multiple addresses this - * only return the actual endpoint we have successfully connected to - */ + /* + * This logic supports "redirect-gateway" semantic, which + * makes sense only for PF_INET routes over PF_INET endpoints + * + * Maybe in the future consider PF_INET6 endpoints also ... + * by now just ignore it + * + * For --remote entries with multiple addresses this + * only return the actual endpoint we have successfully connected to + */ if (lsa->actual.dest.addr.sa.sa_family !=3D AF_INET) { return IPV4_INVALID_ADDR; @@ -2581,8 +2428,7 @@ } else if (lsa->current_remote) { - return ntohl(((struct sockaddr_in *)lsa->current_remote->ai_addr) - ->sin_addr.s_addr); + return ntohl(((struct sockaddr_in *)lsa->current_remote->ai_addr)-= >sin_addr.s_addr); } else { @@ -2595,12 +2441,12 @@ { const struct link_socket_addr *lsa =3D info->lsa; -/* This logic supports "redirect-gateway" semantic, - * for PF_INET6 routes over PF_INET6 endpoints - * - * For --remote entries with multiple addresses this - * only return the actual endpoint we have successfully connected to - */ + /* This logic supports "redirect-gateway" semantic, + * for PF_INET6 routes over PF_INET6 endpoints + * + * For --remote entries with multiple addresses this + * only return the actual endpoint we have successfully connected to + */ if (lsa->actual.dest.addr.sa.sa_family !=3D AF_INET6) { return NULL; @@ -2631,20 +2477,16 @@ { if (rwflags & EVENT_READ) { - buf_printf(&out, "S%s", - (s->rwflags_debug & EVENT_READ) ? "R" : "r"); + buf_printf(&out, "S%s", (s->rwflags_debug & EVENT_READ) ? "R" = : "r"); #ifdef _WIN32 - buf_printf(&out, "%s", - overlapped_io_state_ascii(&s->reads)); + buf_printf(&out, "%s", overlapped_io_state_ascii(&s->reads)); #endif } if (rwflags & EVENT_WRITE) { - buf_printf(&out, "S%s", - (s->rwflags_debug & EVENT_WRITE) ? "W" : "w"); + buf_printf(&out, "S%s", (s->rwflags_debug & EVENT_WRITE) ? "W"= : "w"); #ifdef _WIN32 - buf_printf(&out, "%s", - overlapped_io_state_ascii(&s->writes)); + buf_printf(&out, "%s", overlapped_io_state_ascii(&s->writes)); #endif } } @@ -2671,9 +2513,7 @@ } static void -stream_buf_init(struct stream_buf *sb, - struct buffer *buf, - const unsigned int sockflags, +stream_buf_init(struct stream_buf *sb, struct buffer *buf, const unsigned = int sockflags, const int proto) { sb->buf_init =3D *buf; @@ -2682,9 +2522,8 @@ sb->residual =3D alloc_buf(sb->maxlen); sb->error =3D false; #if PORT_SHARE - sb->port_share_state =3D ((sockflags & SF_PORT_SHARE) && (proto =3D=3D= PROTO_TCP_SERVER)) - ? PS_ENABLED - : PS_DISABLED; + sb->port_share_state =3D + ((sockflags & SF_PORT_SHARE) && (proto =3D=3D PROTO_TCP_SERVER)) ?= PS_ENABLED : PS_DISABLED; #endif stream_buf_reset(sb); @@ -2699,9 +2538,7 @@ sb->next.offset =3D sb->buf.offset + sb->buf.len; sb->next.len =3D (sb->len >=3D 0 ? sb->len : sb->maxlen) - sb->buf.len; dmsg(D_STREAM_DEBUG, "STREAM: SET NEXT, buf=3D[%d,%d] next=3D[%d,%d] l= en=3D%d maxlen=3D%d", - sb->buf.offset, sb->buf.len, - sb->next.offset, sb->next.len, - sb->len, sb->maxlen); + sb->buf.offset, sb->buf.len, sb->next.offset, sb->next.len, sb->l= en, sb->maxlen); ASSERT(sb->next.len > 0); ASSERT(buf_safe(&sb->buf, sb->next.len)); } @@ -2709,8 +2546,7 @@ static inline void stream_buf_get_final(struct stream_buf *sb, struct buffer *buf) { - dmsg(D_STREAM_DEBUG, "STREAM: GET FINAL len=3D%d", - buf_defined(&sb->buf) ? sb->buf.len : -1); + dmsg(D_STREAM_DEBUG, "STREAM: GET FINAL len=3D%d", buf_defined(&sb->bu= f) ? sb->buf.len : -1); ASSERT(buf_defined(&sb->buf)); *buf =3D sb->buf; } @@ -2718,8 +2554,7 @@ static inline void stream_buf_get_next(struct stream_buf *sb, struct buffer *buf) { - dmsg(D_STREAM_DEBUG, "STREAM: GET NEXT len=3D%d", - buf_defined(&sb->next) ? sb->next.len : -1); + dmsg(D_STREAM_DEBUG, "STREAM: GET NEXT len=3D%d", buf_defined(&sb->nex= t) ? sb->next.len : -1); ASSERT(buf_defined(&sb->next)); *buf =3D sb->next; } @@ -2733,8 +2568,7 @@ ASSERT(buf_init(&sock->stream_buf.residual, 0)); sock->stream_buf.residual_fully_formed =3D stream_buf_added(&sock-= >stream_buf, 0); dmsg(D_STREAM_DEBUG, "STREAM: RESIDUAL FULLY FORMED [%s], len=3D%d= ", - sock->stream_buf.residual_fully_formed ? "YES" : "NO", - sock->stream_buf.residual.len); + sock->stream_buf.residual_fully_formed ? "YES" : "NO", sock->= stream_buf.residual.len); } if (!sock->stream_buf.residual_fully_formed) @@ -2745,8 +2579,7 @@ } static bool -stream_buf_added(struct stream_buf *sb, - int length_added) +stream_buf_added(struct stream_buf *sb, int length_added) { dmsg(D_STREAM_DEBUG, "STREAM: ADD length_added=3D%d", length_added); if (length_added > 0) @@ -2756,7 +2589,7 @@ /* if length unknown, see if we can get the length prefix from * the head of the buffer */ - if (sb->len < 0 && sb->buf.len >=3D (int) sizeof(packet_size_type)) + if (sb->len < 0 && sb->buf.len >=3D (int)sizeof(packet_size_type)) { packet_size_type net_size; @@ -2782,7 +2615,9 @@ if (sb->len < 1 || sb->len > sb->maxlen) { - msg(M_WARN, "WARNING: Bad encapsulated packet length from peer= (%d), which must be > 0 and <=3D %d -- please ensure that --tun-mtu or --l= ink-mtu is equal on both peers -- this condition could also indicate a poss= ible active attack on the TCP link -- [Attempting restart...]", sb->len, sb= ->maxlen); + msg(M_WARN, + "WARNING: Bad encapsulated packet length from peer (%d), w= hich must be > 0 and <=3D %d -- please ensure that --tun-mtu or --link-mtu = is equal on both peers -- this condition could also indicate a possible act= ive attack on the TCP link -- [Attempting restart...]", + sb->len, sb->maxlen); stream_buf_reset(sb); sb->error =3D true; return false; @@ -2799,8 +2634,7 @@ ASSERT(buf_copy_excess(&sb->residual, &sb->buf, sb->len)); } dmsg(D_STREAM_DEBUG, "STREAM: ADD returned TRUE, buf_len=3D%d, res= idual_len=3D%d", - BLEN(&sb->buf), - BLEN(&sb->residual)); + BLEN(&sb->buf), BLEN(&sb->residual)); return true; } else @@ -2831,7 +2665,7 @@ init_net_event_win32(&s->listen_handle, FD_ACCEPT, s->sd, 0); } return &s->listen_handle; -#else /* ifdef _WIN32 */ +#else /* ifdef _WIN32 */ return s->sd; #endif } @@ -2841,9 +2675,7 @@ */ const char * -print_sockaddr_ex(const struct sockaddr *sa, - const char *separator, - const unsigned int flags, +print_sockaddr_ex(const struct sockaddr *sa, const char *separator, const = unsigned int flags, struct gc_arena *gc) { struct buffer out =3D alloc_buf_gc(128, gc); @@ -2861,7 +2693,7 @@ buf_puts(&out, "[AF_INET]"); } salen =3D sizeof(struct sockaddr_in); - addr_is_defined =3D ((struct sockaddr_in *) sa)->sin_addr.s_ad= dr !=3D 0; + addr_is_defined =3D ((struct sockaddr_in *)sa)->sin_addr.s_add= r !=3D 0; break; case AF_INET6: @@ -2870,7 +2702,7 @@ buf_puts(&out, "[AF_INET6]"); } salen =3D sizeof(struct sockaddr_in6); - addr_is_defined =3D !IN6_IS_ADDR_UNSPECIFIED(&((struct sockadd= r_in6 *) sa)->sin6_addr); + addr_is_defined =3D !IN6_IS_ADDR_UNSPECIFIED(&((struct sockadd= r_in6 *)sa)->sin6_addr); break; case AF_UNSPEC: @@ -2887,10 +2719,10 @@ ASSERT(0); } - status =3D getnameinfo(sa, salen, hostaddr, sizeof(hostaddr), - servname, sizeof(servname), NI_NUMERICHOST | NI_N= UMERICSERV); + status =3D getnameinfo(sa, salen, hostaddr, sizeof(hostaddr), servname= , sizeof(servname), + NI_NUMERICHOST | NI_NUMERICSERV); - if (status!=3D0) + if (status !=3D 0) { buf_printf(&out, "[nameinfo() err: %s]", gai_strerror(status)); return BSTR(&out); @@ -2924,7 +2756,7 @@ const char * print_link_socket_actual(const struct link_socket_actual *act, struct gc_a= rena *gc) { - return print_link_socket_actual_ex(act, ":", PS_SHOW_PORT|PS_SHOW_PKTI= NFO, gc); + return print_link_socket_actual_ex(act, ":", PS_SHOW_PORT | PS_SHOW_PK= TINFO, gc); } #ifndef IF_NAMESIZE @@ -2932,10 +2764,8 @@ #endif const char * -print_link_socket_actual_ex(const struct link_socket_actual *act, - const char *separator, - const unsigned int flags, - struct gc_arena *gc) +print_link_socket_actual_ex(const struct link_socket_actual *act, const ch= ar *separator, + const unsigned int flags, struct gc_arena *gc) { if (act) { @@ -2959,12 +2789,11 @@ #elif defined(IP_RECVDSTADDR) sa.addr.in4.sin_addr =3D act->pi.in4; ifname[0] =3D 0; -#else /* if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST) */ +#else /* if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST) */ #error ENABLE_IP_PKTINFO is set without IP_PKTINFO xor IP_RECVDSTADDR (fix= syshead.h) #endif buf_printf(&out, " (via %s%%%s)", - print_sockaddr_ex(&sa.addr.sa, separator, 0= , gc), - ifname); + print_sockaddr_ex(&sa.addr.sa, separator, 0= , gc), ifname); } break; @@ -2976,8 +2805,9 @@ sin6.sin6_family =3D AF_INET6; sin6.sin6_addr =3D act->pi.in6.ipi6_addr; if_indextoname(act->pi.in6.ipi6_ifindex, ifname); - if (getnameinfo((struct sockaddr *)&sin6, sizeof(struc= t sockaddr_in6), - buf, sizeof(buf), NULL, 0, NI_NUMERICH= OST) =3D=3D 0) + if (getnameinfo((struct sockaddr *)&sin6, sizeof(struc= t sockaddr_in6), buf, + sizeof(buf), NULL, 0, NI_NUMERICHOST) + =3D=3D 0) { buf_printf(&out, " (via %s%%%s)", buf, ifname); } @@ -3027,8 +2857,7 @@ { char *out =3D gc_malloc(INET6_ADDRSTRLEN, true, gc); - if (memcmp(&a6, &in6addr_any, sizeof(a6)) !=3D 0 - || !(flags & IA_EMPTY_IF_UNDEF)) + if (memcmp(&a6, &in6addr_any, sizeof(a6)) !=3D 0 || !(flags & IA_EMPTY= _IF_UNDEF)) { inet_ntop(AF_INET6, &a6, out, INET6_ADDRSTRLEN); } @@ -3050,30 +2879,31 @@ * (add in steps of 8 bits, taking overflow into next round) */ struct in6_addr -add_in6_addr( struct in6_addr base, uint32_t add ) +add_in6_addr(struct in6_addr base, uint32_t add) { int i; - for (i =3D 15; i>=3D0 && add > 0; i--) + for (i =3D 15; i >=3D 0 && add > 0; i--) { register int carry; register uint32_t h; - h =3D (unsigned char) base.s6_addr[i]; - base.s6_addr[i] =3D (h+add) & UINT8_MAX; + h =3D (unsigned char)base.s6_addr[i]; + base.s6_addr[i] =3D (h + add) & UINT8_MAX; /* using explicit carry for the 8-bit additions will catch * 8-bit and(!) 32-bit overruns nicely */ - carry =3D ((h & 0xff) + (add & 0xff)) >> 8; - add =3D (add>>8) + carry; + carry =3D ((h & 0xff) + (add & 0xff)) >> 8; + add =3D (add >> 8) + carry; } return base; } /* set environmental variables for ip/port in *addr */ void -setenv_sockaddr(struct env_set *es, const char *name_prefix, const struct = openvpn_sockaddr *addr, const unsigned int flags) +setenv_sockaddr(struct env_set *es, const char *name_prefix, const struct = openvpn_sockaddr *addr, + const unsigned int flags) { char name_buf[256]; @@ -3101,11 +2931,10 @@ break; case AF_INET6: - if (IN6_IS_ADDR_V4MAPPED( &addr->addr.in6.sin6_addr )) + if (IN6_IS_ADDR_V4MAPPED(&addr->addr.in6.sin6_addr)) { struct in_addr ia; - memcpy(&ia.s_addr, &addr->addr.in6.sin6_addr.s6_addr[12], - sizeof(ia.s_addr)); + memcpy(&ia.s_addr, &addr->addr.in6.sin6_addr.s6_addr[12], = sizeof(ia.s_addr)); snprintf(name_buf, sizeof(name_buf), "%s_ip", name_prefix); inet_ntop(AF_INET, &ia, buf, sizeof(buf)); } @@ -3126,7 +2955,8 @@ } void -setenv_in_addr_t(struct env_set *es, const char *name_prefix, in_addr_t ad= dr, const unsigned int flags) +setenv_in_addr_t(struct env_set *es, const char *name_prefix, in_addr_t ad= dr, + const unsigned int flags) { if (addr || !(flags & SA_SET_IF_NONZERO)) { @@ -3139,9 +2969,7 @@ } void -setenv_in6_addr(struct env_set *es, - const char *name_prefix, - const struct in6_addr *addr, +setenv_in6_addr(struct env_set *es, const char *name_prefix, const struct = in6_addr *addr, const unsigned int flags) { if (!IN6_IS_ADDR_UNSPECIFIED(addr) || !(flags & SA_SET_IF_NONZERO)) @@ -3155,10 +2983,8 @@ } void -setenv_link_socket_actual(struct env_set *es, - const char *name_prefix, - const struct link_socket_actual *act, - const unsigned int flags) +setenv_link_socket_actual(struct env_set *es, const char *name_prefix, + const struct link_socket_actual *act, const unsi= gned int flags) { setenv_sockaddr(es, name_prefix, &act->dest, flags); } @@ -3167,7 +2993,8 @@ * Convert protocol names between index and ascii form. */ -struct proto_names { +struct proto_names +{ const char *short_form; const char *display_form; sa_family_t proto_af; @@ -3176,22 +3003,22 @@ /* Indexed by PROTO_x */ static const struct proto_names proto_names[] =3D { - {"proto-uninitialized", "proto-NONE", AF_UNSPEC, PROTO_NONE}, + { "proto-uninitialized", "proto-NONE", AF_UNSPEC, PROTO_NONE }, /* try IPv4 and IPv6 (client), bind dual-stack (server) */ - {"udp", "UDP", AF_UNSPEC, PROTO_UDP}, - {"tcp-server", "TCP_SERVER", AF_UNSPEC, PROTO_TCP_SERVER}, - {"tcp-client", "TCP_CLIENT", AF_UNSPEC, PROTO_TCP_CLIENT}, - {"tcp", "TCP", AF_UNSPEC, PROTO_TCP}, + { "udp", "UDP", AF_UNSPEC, PROTO_UDP }, + { "tcp-server", "TCP_SERVER", AF_UNSPEC, PROTO_TCP_SERVER }, + { "tcp-client", "TCP_CLIENT", AF_UNSPEC, PROTO_TCP_CLIENT }, + { "tcp", "TCP", AF_UNSPEC, PROTO_TCP }, /* 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}, + { "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 }, /* 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}, + { "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 }, }; int @@ -3262,9 +3089,11 @@ { switch (af) { - case AF_INET: return "AF_INET"; + case AF_INET: + return "AF_INET"; - case AF_INET6: return "AF_INET6"; + case AF_INET6: + return "AF_INET6"; } return "AF_UNSPEC"; } @@ -3290,13 +3119,11 @@ return "UDPv4"; } - if ( (remote && proto =3D=3D PROTO_TCP_CLIENT) - || (!remote && proto =3D=3D PROTO_TCP_SERVER)) + if ((remote && proto =3D=3D PROTO_TCP_CLIENT) || (!remote && proto =3D= =3D PROTO_TCP_SERVER)) { return "TCPv4_SERVER"; } - if ( (remote && proto =3D=3D PROTO_TCP_SERVER) - || (!remote && proto =3D=3D PROTO_TCP_CLIENT)) + if ((remote && proto =3D=3D PROTO_TCP_SERVER) || (!remote && proto =3D= =3D PROTO_TCP_CLIENT)) { return "TCPv4_CLIENT"; } @@ -3312,9 +3139,9 @@ void bad_address_length(int actual, int expected) { - msg(M_FATAL, "ERROR: received strange incoming packet with an address = length of %d -- we only accept address lengths of %d.", - actual, - expected); + msg(M_FATAL, + "ERROR: received strange incoming packet with an address length of= %d -- we only accept address lengths of %d.", + actual, expected); } /* @@ -3322,8 +3149,7 @@ */ int -link_socket_read_tcp(struct link_socket *sock, - struct buffer *buf) +link_socket_read_tcp(struct link_socket *sock, struct buffer *buf) { int len =3D 0; @@ -3336,9 +3162,9 @@ */ if (sock->sd =3D=3D SOCKET_UNDEFINED) { - msg(M_INFO, "BUG: link_socket_read_tcp(): sock->sd=3D=3D-1, re= set client instance" ); - sock->stream_reset =3D true; /* reset client inst= ance */ - return buf->len =3D 0; /* nothing to read */ + msg(M_INFO, "BUG: link_socket_read_tcp(): sock->sd=3D=3D-1, re= set client instance"); + sock->stream_reset =3D true; /* reset client instance */ + return buf->len =3D 0; /* nothing to read */ } #ifdef _WIN32 @@ -3381,24 +3207,23 @@ * both IPv4 and IPv6 destination addresses, plus padding (see RFC 2292) */ #if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST) -#define PKTINFO_BUF_SIZE max_int( CMSG_SPACE(sizeof(struct in6_pktinfo)), \ - CMSG_SPACE(sizeof(struct in_pktinfo)) ) +#define PKTINFO_BUF_SIZE \ + max_int(CMSG_SPACE(sizeof(struct in6_pktinfo)), CMSG_SPACE(sizeof(stru= ct in_pktinfo))) #else -#define PKTINFO_BUF_SIZE max_int( CMSG_SPACE(sizeof(struct in6_pktinfo)), \ - CMSG_SPACE(sizeof(struct in_addr)) ) +#define PKTINFO_BUF_SIZE \ + max_int(CMSG_SPACE(sizeof(struct in6_pktinfo)), CMSG_SPACE(sizeof(stru= ct in_addr))) #endif static socklen_t -link_socket_read_udp_posix_recvmsg(struct link_socket *sock, - struct buffer *buf, +link_socket_read_udp_posix_recvmsg(struct link_socket *sock, struct buffer= *buf, struct link_socket_actual *from) { struct iovec iov; uint8_t pktinfo_buf[PKTINFO_BUF_SIZE]; - struct msghdr mesg =3D {0}; + struct msghdr mesg =3D { 0 }; socklen_t fromlen =3D sizeof(from->dest.addr); - ASSERT(sock->sd >=3D 0); /* can't happen */ + ASSERT(sock->sd >=3D 0); /* can't happen */ iov.iov_base =3D BPTR(buf); iov.iov_len =3D buf_forward_capacity_total(buf); @@ -3414,43 +3239,40 @@ struct cmsghdr *cmsg; fromlen =3D mesg.msg_namelen; cmsg =3D CMSG_FIRSTHDR(&mesg); - if (cmsg !=3D NULL - && CMSG_NXTHDR(&mesg, cmsg) =3D=3D NULL + if (cmsg !=3D NULL && CMSG_NXTHDR(&mesg, cmsg) =3D=3D NULL #if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST) - && cmsg->cmsg_level =3D=3D SOL_IP - && cmsg->cmsg_type =3D=3D IP_PKTINFO - && cmsg->cmsg_len >=3D CMSG_LEN(sizeof(struct in_pktinfo)) ) + && cmsg->cmsg_level =3D=3D SOL_IP && cmsg->cmsg_type =3D=3D IP= _PKTINFO + && cmsg->cmsg_len >=3D CMSG_LEN(sizeof(struct in_pktinfo))) #elif defined(IP_RECVDSTADDR) - && cmsg->cmsg_level =3D=3D IPPROTO_IP - && cmsg->cmsg_type =3D=3D IP_RECVDSTADDR - && cmsg->cmsg_len >=3D CMSG_LEN(sizeof(struct in_addr)) ) -#else /* if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST) */ + && cmsg->cmsg_level =3D=3D IPPROTO_IP && cmsg->cmsg_type =3D= =3D IP_RECVDSTADDR + && cmsg->cmsg_len >=3D CMSG_LEN(sizeof(struct in_addr))) +#else /* if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST) */ #error ENABLE_IP_PKTINFO is set without IP_PKTINFO xor IP_RECVDSTADDR (fix= syshead.h) #endif { #if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST) - struct in_pktinfo *pkti =3D (struct in_pktinfo *) CMSG_DATA(cm= sg); + struct in_pktinfo *pkti =3D (struct in_pktinfo *)CMSG_DATA(cms= g); from->pi.in4.ipi_ifindex =3D pkti->ipi_ifindex; from->pi.in4.ipi_spec_dst =3D pkti->ipi_spec_dst; #elif defined(IP_RECVDSTADDR) - from->pi.in4 =3D *(struct in_addr *) CMSG_DATA(cmsg); -#else /* if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST) */ + from->pi.in4 =3D *(struct in_addr *)CMSG_DATA(cmsg); +#else /* if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST) */ #error ENABLE_IP_PKTINFO is set without IP_PKTINFO xor IP_RECVDSTADDR (fix= syshead.h) #endif } - else if (cmsg !=3D NULL - && CMSG_NXTHDR(&mesg, cmsg) =3D=3D NULL - && cmsg->cmsg_level =3D=3D IPPROTO_IPV6 - && cmsg->cmsg_type =3D=3D IPV6_PKTINFO - && cmsg->cmsg_len >=3D CMSG_LEN(sizeof(struct in6_pktinfo= )) ) + else if (cmsg !=3D NULL && CMSG_NXTHDR(&mesg, cmsg) =3D=3D NULL + && cmsg->cmsg_level =3D=3D IPPROTO_IPV6 && cmsg->cmsg_typ= e =3D=3D IPV6_PKTINFO + && cmsg->cmsg_len >=3D CMSG_LEN(sizeof(struct in6_pktinfo= ))) { - struct in6_pktinfo *pkti6 =3D (struct in6_pktinfo *) CMSG_DATA= (cmsg); + struct in6_pktinfo *pkti6 =3D (struct in6_pktinfo *)CMSG_DATA(= cmsg); from->pi.in6.ipi6_ifindex =3D pkti6->ipi6_ifindex; from->pi.in6.ipi6_addr =3D pkti6->ipi6_addr; } else if (cmsg !=3D NULL) { - msg(M_WARN, "CMSG received that cannot be parsed (cmsg_level= =3D%d, cmsg_type=3D%d, cmsg=3Dlen=3D%d)", (int)cmsg->cmsg_level, (int)cmsg-= >cmsg_type, (int)cmsg->cmsg_len ); + msg(M_WARN, + "CMSG received that cannot be parsed (cmsg_level=3D%d, cms= g_type=3D%d, cmsg=3Dlen=3D%d)", + (int)cmsg->cmsg_level, (int)cmsg->cmsg_type, (int)cmsg->cm= sg_len); } } @@ -3459,15 +3281,14 @@ #endif /* if ENABLE_IP_PKTINFO */ int -link_socket_read_udp_posix(struct link_socket *sock, - struct buffer *buf, +link_socket_read_udp_posix(struct link_socket *sock, struct buffer *buf, struct link_socket_actual *from) { socklen_t fromlen =3D sizeof(from->dest.addr); socklen_t expectedlen =3D af_addr_size(sock->info.af); addr_zero_host(&from->dest); - ASSERT(sock->sd >=3D 0); /* can't happen */ + ASSERT(sock->sd >=3D 0); /* can't happen */ #if ENABLE_IP_PKTINFO /* Both PROTO_UDPv4 and PROTO_UDPv6 */ @@ -3478,8 +3299,8 @@ else #endif { - buf->len =3D recvfrom(sock->sd, BPTR(buf), buf_forward_capacity(bu= f), 0, - &from->dest.addr.sa, &fromlen); + buf->len =3D recvfrom(sock->sd, BPTR(buf), buf_forward_capacity(bu= f), 0, &from->dest.addr.sa, + &fromlen); } /* FIXME: won't do anything when sock->info.af =3D=3D AF_UNSPEC */ if (buf->len >=3D 0 && expectedlen && fromlen !=3D expectedlen) @@ -3496,9 +3317,7 @@ */ ssize_t -link_socket_write_tcp(struct link_socket *sock, - struct buffer *buf, - struct link_socket_actual *to) +link_socket_write_tcp(struct link_socket *sock, struct buffer *buf, struct= link_socket_actual *to) { packet_size_type len =3D BLEN(buf); dmsg(D_STREAM_DEBUG, "STREAM: WRITE %d offset=3D%d", (int)len, buf->of= fset); @@ -3515,8 +3334,7 @@ #if ENABLE_IP_PKTINFO ssize_t -link_socket_write_udp_posix_sendmsg(struct link_socket *sock, - struct buffer *buf, +link_socket_write_udp_posix_sendmsg(struct link_socket *sock, struct buffe= r *buf, struct link_socket_actual *to) { struct iovec iov; @@ -3544,19 +3362,19 @@ cmsg->cmsg_type =3D IP_PKTINFO; { struct in_pktinfo *pkti; - pkti =3D (struct in_pktinfo *) CMSG_DATA(cmsg); + pkti =3D (struct in_pktinfo *)CMSG_DATA(cmsg); pkti->ipi_ifindex =3D to->pi.in4.ipi_ifindex; pkti->ipi_spec_dst =3D to->pi.in4.ipi_spec_dst; pkti->ipi_addr.s_addr =3D 0; } #elif defined(IP_RECVDSTADDR) - ASSERT( CMSG_SPACE(sizeof(struct in_addr)) <=3D sizeof(pktinfo= _buf) ); + ASSERT(CMSG_SPACE(sizeof(struct in_addr)) <=3D sizeof(pktinfo_= buf)); mesg.msg_controllen =3D CMSG_SPACE(sizeof(struct in_addr)); cmsg =3D CMSG_FIRSTHDR(&mesg); cmsg->cmsg_len =3D CMSG_LEN(sizeof(struct in_addr)); cmsg->cmsg_level =3D IPPROTO_IP; cmsg->cmsg_type =3D IP_RECVDSTADDR; - *(struct in_addr *) CMSG_DATA(cmsg) =3D to->pi.in4; + *(struct in_addr *)CMSG_DATA(cmsg) =3D to->pi.in4; #else /* if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST) */ #error ENABLE_IP_PKTINFO is set without IP_PKTINFO xor IP_RECVDSTADDR (fix= syshead.h) #endif /* if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST) */ @@ -3569,7 +3387,7 @@ mesg.msg_name =3D &to->dest.addr.sa; mesg.msg_namelen =3D sizeof(struct sockaddr_in6); - ASSERT( CMSG_SPACE(sizeof(struct in6_pktinfo)) <=3D sizeof(pkt= info_buf) ); + ASSERT(CMSG_SPACE(sizeof(struct in6_pktinfo)) <=3D sizeof(pkti= nfo_buf)); mesg.msg_control =3D pktinfo_buf; mesg.msg_controllen =3D CMSG_SPACE(sizeof(struct in6_pktinfo)); mesg.msg_flags =3D 0; @@ -3578,13 +3396,14 @@ cmsg->cmsg_level =3D IPPROTO_IPV6; cmsg->cmsg_type =3D IPV6_PKTINFO; - pkti6 =3D (struct in6_pktinfo *) CMSG_DATA(cmsg); + pkti6 =3D (struct in6_pktinfo *)CMSG_DATA(cmsg); pkti6->ipi6_ifindex =3D to->pi.in6.ipi6_ifindex; pkti6->ipi6_addr =3D to->pi.in6.ipi6_addr; break; } - default: ASSERT(0); + default: + ASSERT(0); } return sendmsg(sock->sd, &mesg, 0); } @@ -3643,8 +3462,8 @@ if (socket_is_dco_win(sock)) { - status =3D ReadFile((HANDLE)sock->sd, wsabuf[0].buf, wsabuf[0]= .len, - &sock->reads.size, &sock->reads.overlapped); + status =3D ReadFile((HANDLE)sock->sd, wsabuf[0].buf, wsabuf[0]= .len, &sock->reads.size, + &sock->reads.overlapped); /* Readfile status is inverted from WSARecv */ status =3D !status; } @@ -3652,28 +3471,15 @@ { sock->reads.addr_defined =3D true; sock->reads.addrlen =3D sizeof(sock->reads.addr6); - status =3D WSARecvFrom( - sock->sd, - wsabuf, - 1, - &sock->reads.size, - &sock->reads.flags, - (struct sockaddr *) &sock->reads.addr, - &sock->reads.addrlen, - &sock->reads.overlapped, - NULL); + status =3D WSARecvFrom(sock->sd, wsabuf, 1, &sock->reads.size,= &sock->reads.flags, + (struct sockaddr *)&sock->reads.addr, &so= ck->reads.addrlen, + &sock->reads.overlapped, NULL); } else if (proto_is_tcp(sock->info.proto)) { sock->reads.addr_defined =3D false; - status =3D WSARecv( - sock->sd, - wsabuf, - 1, - &sock->reads.size, - &sock->reads.flags, - &sock->reads.overlapped, - NULL); + status =3D WSARecv(sock->sd, wsabuf, 1, &sock->reads.size, &so= ck->reads.flags, + &sock->reads.overlapped, NULL); } else { @@ -3696,8 +3502,7 @@ sock->reads.status =3D 0; dmsg(D_WIN32_IO, "WIN32 I/O: Socket Receive immediate return [= %d,%d]", - (int) wsabuf[0].len, - (int) sock->reads.size); + (int)wsabuf[0].len, (int)sock->reads.size); } else { @@ -3706,8 +3511,7 @@ { sock->reads.iostate =3D IOSTATE_QUEUED; sock->reads.status =3D status; - dmsg(D_WIN32_IO, "WIN32 I/O: Socket Receive queued [%d]", - (int) wsabuf[0].len); + dmsg(D_WIN32_IO, "WIN32 I/O: Socket Receive queued [%d]", = (int)wsabuf[0].len); } else /* error occurred */ { @@ -3715,8 +3519,7 @@ ASSERT(SetEvent(sock->reads.overlapped.hEvent)); sock->reads.iostate =3D IOSTATE_IMMEDIATE_RETURN; sock->reads.status =3D status; - dmsg(D_WIN32_IO, "WIN32 I/O: Socket Receive error [%d]: %s= ", - (int) wsabuf[0].len, + dmsg(D_WIN32_IO, "WIN32 I/O: Socket Receive error [%d]: %s= ", (int)wsabuf[0].len, strerror_win32(status, &gc)); gc_free(&gc); } @@ -3748,12 +3551,11 @@ if (socket_is_dco_win(sock)) { - status =3D WriteFile((HANDLE)sock->sd, wsabuf[0].buf, wsabuf[0= ].len, - &sock->writes.size, &sock->writes.overlappe= d); + status =3D WriteFile((HANDLE)sock->sd, wsabuf[0].buf, wsabuf[0= ].len, &sock->writes.size, + &sock->writes.overlapped); /* WriteFile status is inverted from WSASendTo */ status =3D !status; - } else if (proto_is_udp(sock->info.proto)) { @@ -3770,30 +3572,17 @@ sock->writes.addrlen =3D sizeof(sock->writes.addr); } - status =3D WSASendTo( - sock->sd, - wsabuf, - 1, - &sock->writes.size, - sock->writes.flags, - (struct sockaddr *) &sock->writes.addr, - sock->writes.addrlen, - &sock->writes.overlapped, - NULL); + status =3D WSASendTo(sock->sd, wsabuf, 1, &sock->writes.size, = sock->writes.flags, + (struct sockaddr *)&sock->writes.addr, sock= ->writes.addrlen, + &sock->writes.overlapped, NULL); } else if (proto_is_tcp(sock->info.proto)) { /* destination address for TCP writes was established on conne= ction initiation */ sock->writes.addr_defined =3D false; - status =3D WSASend( - sock->sd, - wsabuf, - 1, - &sock->writes.size, - sock->writes.flags, - &sock->writes.overlapped, - NULL); + status =3D WSASend(sock->sd, wsabuf, 1, &sock->writes.size, so= ck->writes.flags, + &sock->writes.overlapped, NULL); } else { @@ -3810,9 +3599,8 @@ sock->writes.status =3D 0; - dmsg(D_WIN32_IO, "WIN32 I/O: Socket Send immediate return [%d,= %d]", - (int) wsabuf[0].len, - (int) sock->writes.size); + dmsg(D_WIN32_IO, "WIN32 I/O: Socket Send immediate return [%d,= %d]", (int)wsabuf[0].len, + (int)sock->writes.size); } else { @@ -3822,8 +3610,7 @@ { sock->writes.iostate =3D IOSTATE_QUEUED; sock->writes.status =3D status; - dmsg(D_WIN32_IO, "WIN32 I/O: Socket Send queued [%d]", - (int) wsabuf[0].len); + dmsg(D_WIN32_IO, "WIN32 I/O: Socket Send queued [%d]", (in= t)wsabuf[0].len); } else /* error occurred */ { @@ -3832,8 +3619,7 @@ sock->writes.iostate =3D IOSTATE_IMMEDIATE_RETURN; sock->writes.status =3D status; - dmsg(D_WIN32_IO, "WIN32 I/O: Socket Send error [%d]: %s", - (int) wsabuf[0].len, + dmsg(D_WIN32_IO, "WIN32 I/O: Socket Send error [%d]: %s", = (int)wsabuf[0].len, strerror_win32(status, &gc)); gc_free(&gc); @@ -3905,7 +3691,9 @@ sa_len =3D sizeof(struct sockaddr_in); if (buf_len(buf) < sa_len) { - msg(M_FATAL, "ERROR: received incoming packet with too sho= rt length of %d -- must be at least %d.", buf_len(buf), sa_len); + msg(M_FATAL, + "ERROR: received incoming packet with too short length= of %d -- must be at least %d.", + buf_len(buf), sa_len); } memcpy(dst, sa, sa_len); buf_advance(buf, sa_len); @@ -3915,14 +3703,17 @@ sa_len =3D sizeof(struct sockaddr_in6); if (buf_len(buf) < sa_len) { - msg(M_FATAL, "ERROR: received incoming packet with too sho= rt length of %d -- must be at least %d.", buf_len(buf), sa_len); + msg(M_FATAL, + "ERROR: received incoming packet with too short length= of %d -- must be at least %d.", + buf_len(buf), sa_len); } memcpy(dst, sa, sa_len); buf_advance(buf, sa_len); break; default: - msg(M_FATAL, "ERROR: received incoming packet with invalid add= ress family %d.", sa->sa_family); + msg(M_FATAL, "ERROR: received incoming packet with invalid add= ress family %d.", + sa->sa_family); } return sa_len; @@ -3930,9 +3721,7 @@ /* Returns the number of bytes successfully read */ int -sockethandle_finalize(sockethandle_t sh, - struct overlapped_io *io, - struct buffer *buf, +sockethandle_finalize(sockethandle_t sh, struct overlapped_io *io, struct = buffer *buf, struct link_socket_actual *from) { int ret =3D -1; @@ -4025,10 +3814,7 @@ */ unsigned int -socket_set(struct link_socket *s, - struct event_set *es, - unsigned int rwflags, - void *arg, +socket_set(struct link_socket *s, struct event_set *es, unsigned int rwfla= gs, void *arg, unsigned int *persistent) { if (s) @@ -4108,20 +3894,15 @@ } void -socket_bind_unix(socket_descriptor_t sd, - struct sockaddr_un *local, - const char *prefix) +socket_bind_unix(socket_descriptor_t sd, struct sockaddr_un *local, const = char *prefix) { struct gc_arena gc =3D gc_new(); const mode_t orig_umask =3D umask(0); - if (bind(sd, (struct sockaddr *) local, sizeof(struct sockaddr_un))) + if (bind(sd, (struct sockaddr *)local, sizeof(struct sockaddr_un))) { - msg(M_FATAL | M_ERRNO, - "%s: Socket bind[%d] failed on unix domain socket %s", - prefix, - (int)sd, - sockaddr_unix_name(local, "NULL")); + msg(M_FATAL | M_ERRNO, "%s: Socket bind[%d] failed on unix domain = socket %s", prefix, + (int)sd, sockaddr_unix_name(local, "NULL")); } umask(orig_umask); @@ -4129,14 +3910,13 @@ } socket_descriptor_t -socket_accept_unix(socket_descriptor_t sd, - struct sockaddr_un *remote) +socket_accept_unix(socket_descriptor_t sd, struct sockaddr_un *remote) { socklen_t remote_len =3D sizeof(struct sockaddr_un); socket_descriptor_t ret; CLEAR(*remote); - ret =3D accept(sd, (struct sockaddr *) remote, &remote_len); + ret =3D accept(sd, (struct sockaddr *)remote, &remote_len); if (ret >=3D 0) { /* set socket file descriptor to not pass across execs, so that @@ -4147,10 +3927,9 @@ } int -socket_connect_unix(socket_descriptor_t sd, - struct sockaddr_un *remote) +socket_connect_unix(socket_descriptor_t sd, struct sockaddr_un *remote) { - int status =3D connect(sd, (struct sockaddr *) remote, sizeof(struct s= ockaddr_un)); + int status =3D connect(sd, (struct sockaddr *)remote, sizeof(struct so= ckaddr_un)); if (status) { status =3D openvpn_errno(); diff --git a/src/openvpn/socket.h b/src/openvpn/socket.h index f30411d..ed37590 100644 --- a/src/openvpn/socket.h +++ b/src/openvpn/socket.h @@ -64,7 +64,8 @@ struct openvpn_sockaddr { /*int dummy;*/ /* add offset to force a bug if sa not explicitly deref= erenced */ - union { + union + { struct sockaddr sa; struct sockaddr_in in4; struct sockaddr_in6 in6; @@ -72,7 +73,8 @@ }; /* struct to hold preresolved host names */ -struct cached_dns_entry { +struct cached_dns_entry +{ const char *hostname; const char *servname; int ai_family; @@ -88,7 +90,8 @@ struct openvpn_sockaddr dest; #if ENABLE_IP_PKTINFO - union { + union + { #if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST) struct in_pktinfo in4; #elif defined(IP_RECVDSTADDR) @@ -103,9 +106,9 @@ struct link_socket_addr { struct addrinfo *bind_local; - struct addrinfo *remote_list; /* complete remote list */ - struct addrinfo *current_remote; /* remote used in the - * current connection attempt */ + struct addrinfo *remote_list; /* complete remote list */ + struct addrinfo *current_remote; /* remote used in the + * current connection attempt */ struct link_socket_actual actual; /* reply to this address */ }; @@ -116,10 +119,10 @@ const char *ipchange_command; const struct plugin_list *plugins; bool remote_float; - int proto; /* Protocol (PROTO_x defined below) */ - sa_family_t af; /* Address family like AF_INET, AF= _INET6 or AF_UNSPEC*/ + int proto; /* Protocol (PROTO_x defined below) */ + sa_family_t af; /* Address family like AF_INET, AF_INET6 or AF_UNSPEC= */ bool bind_ipv6_only; - int mtu_changed; /* Set to true when mtu value is changed */ + int mtu_changed; /* Set to true when mtu value is changed */ }; /* @@ -135,7 +138,7 @@ struct buffer buf; struct buffer next; - int len; /* -1 if not yet known */ + int len; /* -1 if not yet known */ =20 bool error; /* if true, fatal TCP error has occurred, * requiring that connection be restarted */ @@ -163,10 +166,8 @@ * @param sbs new sizes. * @param reduce_size apply the new size even if smaller than current one */ -void -socket_set_buffers(socket_descriptor_t fd, - const struct socket_buffer_size *sbs, - bool reduce_size); +void socket_set_buffers(socket_descriptor_t fd, const struct socket_buffer= _size *sbs, + bool reduce_size); /* * This is the main socket structure used by OpenVPN. The SOCKET_ @@ -177,10 +178,10 @@ { struct link_socket_info info; - struct event_arg ev_arg; /**< this struct will store a pointer to ei= ther mi or - * link_socket, depending on the event type= , to keep - * it accessible it's placed within the sam= e struct - * it points to. */ + struct event_arg ev_arg; /**< this struct will store a pointer to eith= er mi or + * link_socket, depending on the event type, = to keep + * it accessible it's placed within the same = struct + * it points to. */ socket_descriptor_t sd; socket_descriptor_t ctrl_sd; /* only used for UDP over Socks */ @@ -205,9 +206,9 @@ struct cached_dns_entry *dns_cache; bool bind_local; -#define LS_MODE_DEFAULT 0 -#define LS_MODE_TCP_LISTEN 1 -#define LS_MODE_TCP_ACCEPT_FROM 2 +#define LS_MODE_DEFAULT 0 +#define LS_MODE_TCP_LISTEN 1 +#define LS_MODE_TCP_ACCEPT_FROM 2 int mode; int resolve_retry_seconds; @@ -215,15 +216,15 @@ struct socket_buffer_size socket_buffer_sizes; - int mtu; /* OS discovered MTU, or 0 if unknown */ + int mtu; /* OS discovered MTU, or 0 if unknown */ -#define SF_USE_IP_PKTINFO (1<<0) -#define SF_TCP_NODELAY (1<<1) -#define SF_PORT_SHARE (1<<2) -#define SF_HOST_RANDOMIZE (1<<3) -#define SF_GETADDRINFO_DGRAM (1<<4) -#define SF_DCO_WIN (1<<5) -#define SF_PREPEND_SA (1<<6) +#define SF_USE_IP_PKTINFO (1 << 0) +#define SF_TCP_NODELAY (1 << 1) +#define SF_PORT_SHARE (1 << 2) +#define SF_HOST_RANDOMIZE (1 << 3) +#define SF_GETADDRINFO_DGRAM (1 << 4) +#define SF_DCO_WIN (1 << 5) +#define SF_PREPEND_SA (1 << 6) unsigned int sockflags; int mark; const char *bind_dev; @@ -277,12 +278,13 @@ int socket_recv_queue(struct link_socket *sock, int maxsize); -int socket_send_queue(struct link_socket *sock, - struct buffer *buf, +int socket_send_queue(struct link_socket *sock, struct buffer *buf, const struct link_socket_actual *to); -typedef struct { - union { +typedef struct +{ + union + { SOCKET s; HANDLE h; }; @@ -290,17 +292,15 @@ bool prepend_sa; /* are incoming packets prepended with sockaddr? */ } sockethandle_t; -int sockethandle_finalize(sockethandle_t sh, - struct overlapped_io *io, - struct buffer *buf, +int sockethandle_finalize(sockethandle_t sh, struct overlapped_io *io, str= uct buffer *buf, struct link_socket_actual *from); static inline BOOL SocketHandleGetOverlappedResult(sockethandle_t sh, struct overlapped_io *i= o) { - return sh.is_handle ? - GetOverlappedResult(sh.h, &io->overlapped, &io->size, FALSE) : - WSAGetOverlappedResult(sh.s, &io->overlapped, &io->size, FALSE,= &io->flags); + return sh.is_handle + ? GetOverlappedResult(sh.h, &io->overlapped, &io->size, FAL= SE) + : WSAGetOverlappedResult(sh.s, &io->overlapped, &io->size, = FALSE, &io->flags); } static inline int @@ -321,7 +321,7 @@ sh.is_handle ? SetLastError(ERROR_INVALID_FUNCTION) : WSASetLastError(= WSAEINVAL); } -#else /* ifdef _WIN32 */ +#else /* ifdef _WIN32 */ #define openvpn_close_socket(s) close(s) @@ -329,29 +329,19 @@ struct link_socket *link_socket_new(void); -void socket_bind(socket_descriptor_t sd, - struct addrinfo *local, - int af_family, - const char *prefix, +void socket_bind(socket_descriptor_t sd, struct addrinfo *local, int af_fa= mily, const char *prefix, bool ipv6only); -int openvpn_connect(socket_descriptor_t sd, - const struct sockaddr *remote, - int connect_timeout, +int openvpn_connect(socket_descriptor_t sd, const struct sockaddr *remote,= int connect_timeout, volatile int *signal_received); - /* * Initialize link_socket object. */ -void -link_socket_init_phase1(struct context *c, - int sock_index, - int mode); +void link_socket_init_phase1(struct context *c, int sock_index, int mode); -void link_socket_init_phase2(struct context *c, - struct link_socket *sock); +void link_socket_init_phase2(struct context *c, struct link_socket *sock); void do_preresolve(struct context *c); @@ -359,75 +349,57 @@ void sd_close(socket_descriptor_t *sd); -#define PS_SHOW_PORT_IF_DEFINED (1<<0) -#define PS_SHOW_PORT (1<<1) -#define PS_SHOW_PKTINFO (1<<2) -#define PS_DONT_SHOW_ADDR (1<<3) -#define PS_DONT_SHOW_FAMILY (1<<4) +#define PS_SHOW_PORT_IF_DEFINED (1 << 0) +#define PS_SHOW_PORT (1 << 1) +#define PS_SHOW_PKTINFO (1 << 2) +#define PS_DONT_SHOW_ADDR (1 << 3) +#define PS_DONT_SHOW_FAMILY (1 << 4) -const char *print_sockaddr_ex(const struct sockaddr *addr, - const char *separator, - const unsigned int flags, - struct gc_arena *gc); +const char *print_sockaddr_ex(const struct sockaddr *addr, const char *sep= arator, + const unsigned int flags, struct gc_arena *g= c); -static inline -const char * -print_openvpn_sockaddr(const struct openvpn_sockaddr *addr, - struct gc_arena *gc) +static inline const char * +print_openvpn_sockaddr(const struct openvpn_sockaddr *addr, struct gc_aren= a *gc) { return print_sockaddr_ex(&addr->addr.sa, ":", PS_SHOW_PORT, gc); } -static inline -const char * -print_sockaddr(const struct sockaddr *addr, - struct gc_arena *gc) +static inline const char * +print_sockaddr(const struct sockaddr *addr, struct gc_arena *gc) { return print_sockaddr_ex(addr, ":", PS_SHOW_PORT, gc); } +const char *print_link_socket_actual_ex(const struct link_socket_actual *a= ct, const char *separator, + const unsigned int flags, struct g= c_arena *gc); -const char *print_link_socket_actual_ex(const struct link_socket_actual *a= ct, - const char *separator, - const unsigned int flags, - struct gc_arena *gc); - -const char *print_link_socket_actual(const struct link_socket_actual *act, - struct gc_arena *gc); +const char *print_link_socket_actual(const struct link_socket_actual *act,= struct gc_arena *gc); -#define IA_EMPTY_IF_UNDEF (1<<0) -#define IA_NET_ORDER (1<<1) +#define IA_EMPTY_IF_UNDEF (1 << 0) +#define IA_NET_ORDER (1 << 1) const char *print_in_addr_t(in_addr_t addr, unsigned int flags, struct gc_= arena *gc); const char *print_in6_addr(struct in6_addr addr6, unsigned int flags, stru= ct gc_arena *gc); const char *print_in_port_t(in_port_t port, struct gc_arena *gc); -struct in6_addr add_in6_addr( struct in6_addr base, uint32_t add ); +struct in6_addr add_in6_addr(struct in6_addr base, uint32_t add); -#define SA_IP_PORT (1<<0) -#define SA_SET_IF_NONZERO (1<<1) -void setenv_sockaddr(struct env_set *es, - const char *name_prefix, - const struct openvpn_sockaddr *addr, - const unsigned int flags); +#define SA_IP_PORT (1 << 0) +#define SA_SET_IF_NONZERO (1 << 1) +void setenv_sockaddr(struct env_set *es, const char *name_prefix, + const struct openvpn_sockaddr *addr, const unsigned i= nt flags); -void setenv_in_addr_t(struct env_set *es, - const char *name_prefix, - in_addr_t addr, +void setenv_in_addr_t(struct env_set *es, const char *name_prefix, in_addr= _t addr, const unsigned int flags); -void setenv_in6_addr(struct env_set *es, - const char *name_prefix, - const struct in6_addr *addr, +void setenv_in6_addr(struct env_set *es, const char *name_prefix, const st= ruct in6_addr *addr, const unsigned int flags); -void setenv_link_socket_actual(struct env_set *es, - const char *name_prefix, - const struct link_socket_actual *act, - const unsigned int flags); +void setenv_link_socket_actual(struct env_set *es, const char *name_prefix, + const struct link_socket_actual *act, const= unsigned int flags); void bad_address_length(int actual, int expected); @@ -437,20 +409,16 @@ #define IPV4_INVALID_ADDR 0xffffffff in_addr_t link_socket_current_remote(const struct link_socket_info *info); -const struct in6_addr *link_socket_current_remote_ipv6 - (const struct link_socket_info *info); +const struct in6_addr *link_socket_current_remote_ipv6(const struct link_s= ocket_info *info); void link_socket_connection_initiated(struct link_socket_info *info, const struct link_socket_actual *add= r, - const char *common_name, - struct env_set *es); + const char *common_name, struct env_= set *es); -void link_socket_bad_incoming_addr(struct buffer *buf, - const struct link_socket_info *info, +void link_socket_bad_incoming_addr(struct buffer *buf, const struct link_s= ocket_info *info, const struct link_socket_actual *from_a= ddr); -void set_actual_address(struct link_socket_actual *actual, - struct addrinfo *ai); +void set_actual_address(struct link_socket_actual *actual, struct addrinfo= *ai); void link_socket_bad_outgoing_addr(void); @@ -465,9 +433,9 @@ */ /* return values of openvpn_inet_aton */ -#define OIA_HOSTNAME 0 -#define OIA_IP 1 -#define OIA_ERROR -1 +#define OIA_HOSTNAME 0 +#define OIA_IP 1 +#define OIA_ERROR -1 int openvpn_inet_aton(const char *dotted_quad, struct in_addr *addr); /* integrity validation on pulled options */ @@ -481,23 +449,18 @@ socket_descriptor_t create_socket_tcp(struct addrinfo *); -socket_descriptor_t socket_do_accept(socket_descriptor_t sd, - struct link_socket_actual *act, +socket_descriptor_t socket_do_accept(socket_descriptor_t sd, struct link_s= ocket_actual *act, const bool nowait); #if UNIX_SOCK_SUPPORT socket_descriptor_t create_socket_unix(void); -void socket_bind_unix(socket_descriptor_t sd, - struct sockaddr_un *local, - const char *prefix); +void socket_bind_unix(socket_descriptor_t sd, struct sockaddr_un *local, c= onst char *prefix); -socket_descriptor_t socket_accept_unix(socket_descriptor_t sd, - struct sockaddr_un *remote); +socket_descriptor_t socket_accept_unix(socket_descriptor_t sd, struct sock= addr_un *remote); -int socket_connect_unix(socket_descriptor_t sd, - struct sockaddr_un *remote); +int socket_connect_unix(socket_descriptor_t sd, struct sockaddr_un *remote= ); void sockaddr_unix_init(struct sockaddr_un *local, const char *path); @@ -513,20 +476,20 @@ * DNS resolution */ -#define GETADDR_RESOLVE (1<<0) -#define GETADDR_FATAL (1<<1) -#define GETADDR_HOST_ORDER (1<<2) -#define GETADDR_MENTION_RESOLVE_RETRY (1<<3) -#define GETADDR_FATAL_ON_SIGNAL (1<<4) -#define GETADDR_WARN_ON_SIGNAL (1<<5) -#define GETADDR_MSG_VIRT_OUT (1<<6) -#define GETADDR_TRY_ONCE (1<<7) -#define GETADDR_UPDATE_MANAGEMENT_STATE (1<<8) -#define GETADDR_RANDOMIZE (1<<9) -#define GETADDR_PASSIVE (1<<10) -#define GETADDR_DATAGRAM (1<<11) +#define GETADDR_RESOLVE (1 << 0) +#define GETADDR_FATAL (1 << 1) +#define GETADDR_HOST_ORDER (1 << 2) +#define GETADDR_MENTION_RESOLVE_RETRY (1 << 3) +#define GETADDR_FATAL_ON_SIGNAL (1 << 4) +#define GETADDR_WARN_ON_SIGNAL (1 << 5) +#define GETADDR_MSG_VIRT_OUT (1 << 6) +#define GETADDR_TRY_ONCE (1 << 7) +#define GETADDR_UPDATE_MANAGEMENT_STATE (1 << 8) +#define GETADDR_RANDOMIZE (1 << 9) +#define GETADDR_PASSIVE (1 << 10) +#define GETADDR_DATAGRAM (1 << 11) -#define GETADDR_CACHE_MASK (GETADDR_DATAGRAM|GETADDR_PASSIVE) +#define GETADDR_CACHE_MASK (GETADDR_DATAGRAM | GETADDR_PASSIVE) /** * Translate an IPv4 addr or hostname from string form to in_addr_t @@ -534,24 +497,17 @@ * In case of resolve error, it will try again for * resolve_retry_seconds seconds. */ -in_addr_t getaddr(unsigned int flags, - const char *hostname, - int resolve_retry_seconds, - bool *succeeded, - struct signal_info *sig_info); +in_addr_t getaddr(unsigned int flags, const char *hostname, int resolve_re= try_seconds, + bool *succeeded, struct signal_info *sig_info); /** * Translate an IPv6 addr or hostname from string form to in6_addr */ -bool get_ipv6_addr(const char *hostname, struct in6_addr *network, - unsigned int *netbits, int msglevel); +bool get_ipv6_addr(const char *hostname, struct in6_addr *network, unsigne= d int *netbits, + int msglevel); -int openvpn_getaddrinfo(unsigned int flags, - const char *hostname, - const char *servname, - int resolve_retry_seconds, - struct signal_info *sig_info, - int ai_family, +int openvpn_getaddrinfo(unsigned int flags, const char *hostname, const ch= ar *servname, + int resolve_retry_seconds, struct signal_info *sig= _info, int ai_family, struct addrinfo **res); /* @@ -562,8 +518,9 @@ * Use enum's instead of #define to allow for easier * optional proto support */ -enum proto_num { - PROTO_NONE, /* catch for uninitialized */ +enum proto_num +{ + PROTO_NONE, /* catch for uninitialized */ PROTO_UDP, PROTO_TCP, PROTO_TCP_SERVER, @@ -665,11 +622,14 @@ } switch (addr->addr.sa.sa_family) { - case AF_INET: return addr->addr.in4.sin_addr.s_addr !=3D 0; + case AF_INET: + return addr->addr.in4.sin_addr.s_addr !=3D 0; - case AF_INET6: return !IN6_IS_ADDR_UNSPECIFIED(&addr->addr.in6.sin= 6_addr); + case AF_INET6: + return !IN6_IS_ADDR_UNSPECIFIED(&addr->addr.in6.sin6_addr); - default: return 0; + default: + return 0; } } @@ -705,17 +665,21 @@ switch (lsa->dest.addr.sa.sa_family) { #if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST) - case AF_INET: return lsa->pi.in4.ipi_spec_dst.s_addr !=3D 0; + case AF_INET: + return lsa->pi.in4.ipi_spec_dst.s_addr !=3D 0; #elif defined(IP_RECVDSTADDR) - case AF_INET: return lsa->pi.in4.s_addr !=3D 0; + case AF_INET: + return lsa->pi.in4.s_addr !=3D 0; #endif - case AF_INET6: return !IN6_IS_ADDR_UNSPECIFIED(&lsa->pi.in6.ipi6_a= ddr); + case AF_INET6: + return !IN6_IS_ADDR_UNSPECIFIED(&lsa->pi.in6.ipi6_addr); - default: return 0; + default: + return 0; } -#else /* if ENABLE_IP_PKTINFO */ +#else /* if ENABLE_IP_PKTINFO */ ASSERT(0); #endif return false; @@ -751,14 +715,16 @@ switch (a1->addr.sa.sa_family) { case AF_INET: - if (a1->addr.in4.sin_addr.s_addr =3D=3D ((struct sockaddr_= in *)curele->ai_addr)->sin_addr.s_addr) + if (a1->addr.in4.sin_addr.s_addr + =3D=3D ((struct sockaddr_in *)curele->ai_addr)->sin_ad= dr.s_addr) { return true; } break; case AF_INET6: - if (IN6_ARE_ADDR_EQUAL(&a1->addr.in6.sin6_addr, &((struct = sockaddr_in6 *) curele->ai_addr)->sin6_addr)) + if (IN6_ARE_ADDR_EQUAL(&a1->addr.in6.sin6_addr, + &((struct sockaddr_in6 *)curele->ai= _addr)->sin6_addr)) { return true; } @@ -781,7 +747,8 @@ { case AF_INET: if (curele->ai_family =3D=3D AF_INET - && a1->addr.in4.sin_addr.s_addr =3D=3D ((struct sockad= dr_in *)curele->ai_addr)->sin_addr.s_addr + && a1->addr.in4.sin_addr.s_addr + =3D=3D ((struct sockaddr_in *)curele->ai_addr)-= >sin_addr.s_addr && a1->addr.in4.sin_port =3D=3D ((struct sockaddr_in *= )curele->ai_addr)->sin_port) { return true; @@ -790,8 +757,10 @@ case AF_INET6: if (curele->ai_family =3D=3D AF_INET6 - && IN6_ARE_ADDR_EQUAL(&a1->addr.in6.sin6_addr, &((stru= ct sockaddr_in6 *) curele->ai_addr)->sin6_addr) - && a1->addr.in6.sin6_port =3D=3D ((struct sockaddr_in6= *) curele->ai_addr)->sin6_port) + && IN6_ARE_ADDR_EQUAL(&a1->addr.in6.sin6_addr, + &((struct sockaddr_in6 *)curele-= >ai_addr)->sin6_addr) + && a1->addr.in6.sin6_port + =3D=3D ((struct sockaddr_in6 *)curele->ai_addr)= ->sin6_port) { return true; } @@ -805,7 +774,6 @@ } - static inline bool addr_port_match(const struct openvpn_sockaddr *a1, const struct openvpn_so= ckaddr *a2) { @@ -824,24 +792,19 @@ } static inline bool -addr_match_proto(const struct openvpn_sockaddr *a1, - const struct openvpn_sockaddr *a2, +addr_match_proto(const struct openvpn_sockaddr *a1, const struct openvpn_s= ockaddr *a2, const int proto) { - return link_socket_proto_connection_oriented(proto) - ? addr_match(a1, a2) - : addr_port_match(a1, a2); + return link_socket_proto_connection_oriented(proto) ? addr_match(a1, a= 2) + : addr_port_match(= a1, a2); } static inline bool -addrlist_match_proto(const struct openvpn_sockaddr *a1, - struct addrinfo *addr_list, - const int proto) +addrlist_match_proto(const struct openvpn_sockaddr *a1, struct addrinfo *a= ddr_list, const int proto) { - return link_socket_proto_connection_oriented(proto) - ? addrlist_match(a1, addr_list) - : addrlist_port_match(a1, addr_list); + return link_socket_proto_connection_oriented(proto) ? addrlist_match(a= 1, addr_list) + : addrlist_port_ma= tch(a1, addr_list); } static inline void @@ -864,9 +827,11 @@ { switch (af) { - case AF_INET: return sizeof(struct sockaddr_in); + case AF_INET: + return sizeof(struct sockaddr_in); - case AF_INET6: return sizeof(struct sockaddr_in6); + case AF_INET6: + return sizeof(struct sockaddr_in6); default: #if 0 @@ -889,8 +854,7 @@ static inline bool socket_foreign_protocol_detected(const struct link_socket *sock) { - return link_socket_connection_oriented(sock) - && sock->stream_buf.port_share_state =3D=3D PS_FOREIGN; + return link_socket_connection_oriented(sock) && sock->stream_buf.port_= share_state =3D=3D PS_FOREIGN; } static inline const struct buffer * @@ -931,8 +895,7 @@ } static inline bool -link_socket_verify_incoming_addr(struct buffer *buf, - const struct link_socket_info *info, +link_socket_verify_incoming_addr(struct buffer *buf, const struct link_soc= ket_info *info, const struct link_socket_actual *from_add= r) { if (buf->len > 0) @@ -959,8 +922,7 @@ } static inline void -link_socket_get_outgoing_addr(struct buffer *buf, - const struct link_socket_info *info, +link_socket_get_outgoing_addr(struct buffer *buf, const struct link_socket= _info *info, struct link_socket_actual **act) { if (buf->len > 0) @@ -980,23 +942,18 @@ } static inline void -link_socket_set_outgoing_addr(struct link_socket_info *info, - const struct link_socket_actual *act, - const char *common_name, - struct env_set *es) +link_socket_set_outgoing_addr(struct link_socket_info *info, const struct = link_socket_actual *act, + const char *common_name, struct env_set *es) { struct link_socket_addr *lsa =3D info->lsa; if ( /* new or changed address? */ (!info->connection_established - || !addr_match_proto(&act->dest, &lsa->actual.dest, info->proto) - ) + || !addr_match_proto(&act->dest, &lsa->actual.dest, info->proto)) && /* address undef or address =3D=3D remote or --float */ (info->remote_float - || (!lsa->remote_list || addrlist_match_proto(&act->dest, lsa->re= mote_list, info->proto)) - ) - ) + || (!lsa->remote_list || addrlist_match_proto(&act->dest, lsa->re= mote_list, info->proto)))) { link_socket_connection_initiated(info, act, common_name, es); } @@ -1032,14 +989,12 @@ * Socket Read Routines */ -int link_socket_read_tcp(struct link_socket *sock, - struct buffer *buf); +int link_socket_read_tcp(struct link_socket *sock, struct buffer *buf); #ifdef _WIN32 static inline int -link_socket_read_udp_win32(struct link_socket *sock, - struct buffer *buf, +link_socket_read_udp_win32(struct link_socket *sock, struct buffer *buf, struct link_socket_actual *from) { sockethandle_t sh =3D { .s =3D sock->sd }; @@ -1054,17 +1009,14 @@ #else /* ifdef _WIN32 */ -int link_socket_read_udp_posix(struct link_socket *sock, - struct buffer *buf, +int link_socket_read_udp_posix(struct link_socket *sock, struct buffer *bu= f, struct link_socket_actual *from); #endif /* ifdef _WIN32 */ /* read a TCP or UDP packet from link */ static inline int -link_socket_read(struct link_socket *sock, - struct buffer *buf, - struct link_socket_actual *from) +link_socket_read(struct link_socket *sock, struct buffer *buf, struct link= _socket_actual *from) { if (proto_is_udp(sock->info.proto) || socket_is_dco_win(sock)) /* unified UDPv4 and UDPv6, for DCO-WIN the kernel @@ -1096,16 +1048,13 @@ * Socket Write routines */ -ssize_t link_socket_write_tcp(struct link_socket *sock, - struct buffer *buf, +ssize_t link_socket_write_tcp(struct link_socket *sock, struct buffer *buf, struct link_socket_actual *to); #ifdef _WIN32 static inline int -link_socket_write_win32(struct link_socket *sock, - struct buffer *buf, - struct link_socket_actual *to) +link_socket_write_win32(struct link_socket *sock, struct buffer *buf, stru= ct link_socket_actual *to) { int err =3D 0; int status =3D 0; @@ -1144,16 +1093,14 @@ } } -#else /* ifdef _WIN32 */ +#else /* ifdef _WIN32 */ -ssize_t link_socket_write_udp_posix_sendmsg(struct link_socket *sock, - struct buffer *buf, +ssize_t link_socket_write_udp_posix_sendmsg(struct link_socket *sock, stru= ct buffer *buf, struct link_socket_actual *to); static inline ssize_t -link_socket_write_udp_posix(struct link_socket *sock, - struct buffer *buf, +link_socket_write_udp_posix(struct link_socket *sock, struct buffer *buf, struct link_socket_actual *to) { #if ENABLE_IP_PKTINFO @@ -1164,14 +1111,12 @@ } else #endif - return sendto(sock->sd, BPTR(buf), BLEN(buf), 0, - (struct sockaddr *) &to->dest.addr.sa, - (socklen_t) af_addr_size(to->dest.addr.sa.sa_family)); + return sendto(sock->sd, BPTR(buf), BLEN(buf), 0, (struct sockaddr = *)&to->dest.addr.sa, + (socklen_t)af_addr_size(to->dest.addr.sa.sa_family)); } static inline ssize_t -link_socket_write_tcp_posix(struct link_socket *sock, - struct buffer *buf) +link_socket_write_tcp_posix(struct link_socket *sock, struct buffer *buf) { return send(sock->sd, BPTR(buf), BLEN(buf), MSG_NOSIGNAL); } @@ -1179,9 +1124,7 @@ #endif /* ifdef _WIN32 */ static inline ssize_t -link_socket_write_udp(struct link_socket *sock, - struct buffer *buf, - struct link_socket_actual *to) +link_socket_write_udp(struct link_socket *sock, struct buffer *buf, struct= link_socket_actual *to) { #ifdef _WIN32 return link_socket_write_win32(sock, buf, to); @@ -1192,9 +1135,7 @@ /* write a TCP or UDP packet to link */ static inline ssize_t -link_socket_write(struct link_socket *sock, - struct buffer *buf, - struct link_socket_actual *to) +link_socket_write(struct link_socket *sock, struct buffer *buf, struct lin= k_socket_actual *to) { if (proto_is_udp(sock->info.proto) || socket_is_dco_win(sock)) { @@ -1222,7 +1163,7 @@ { if (sock && ipbuf) { - struct openvpn_iphdr *iph =3D (struct openvpn_iphdr *) BPTR(ipbuf); + struct openvpn_iphdr *iph =3D (struct openvpn_iphdr *)BPTR(ipbuf); sock->ptos =3D iph->tos; sock->ptos_defined =3D true; } @@ -1266,17 +1207,11 @@ event_t socket_listen_event_handle(struct link_socket *sock); -unsigned int -socket_set(struct link_socket *sock, - struct event_set *es, - unsigned int rwflags, - void *arg, - unsigned int *persistent); +unsigned int socket_set(struct link_socket *sock, struct event_set *es, un= signed int rwflags, + void *arg, unsigned int *persistent); static inline void -socket_set_listen_persistent(struct link_socket *sock, - struct event_set *es, - void *arg) +socket_set_listen_persistent(struct link_socket *sock, struct event_set *e= s, void *arg) { if (sock && !sock->listen_persistent_queued) { diff --git a/src/openvpn/socks.c b/src/openvpn/socks.c index 6192c39..481d3fb 100644 --- a/src/openvpn/socks.c +++ b/src/openvpn/socks.c @@ -45,12 +45,10 @@ #include "memdbg.h" -#define UP_TYPE_SOCKS "SOCKS Proxy" +#define UP_TYPE_SOCKS "SOCKS Proxy" struct socks_proxy_info * -socks_proxy_new(const char *server, - const char *port, - const char *authfile) +socks_proxy_new(const char *server, const char *port, const char *authfile) { struct socks_proxy_info *p; @@ -83,8 +81,7 @@ } static bool -socks_username_password_auth(struct socks_proxy_info *p, - socket_descriptor_t sd, +socks_username_password_auth(struct socks_proxy_info *p, socket_descriptor= _t sd, struct event_timeout *server_poll_timeout, volatile int *signal_received) { @@ -102,24 +99,23 @@ goto cleanup; } - if ( (strlen(creds.username) > 255) || (strlen(creds.password) > 255) ) + if ((strlen(creds.username) > 255) || (strlen(creds.password) > 255)) { - msg(M_NONFATAL, - "SOCKS username and/or password exceeds 255 characters. " - "Authentication not possible."); + msg(M_NONFATAL, "SOCKS username and/or password exceeds 255 charac= ters. " + "Authentication not possible."); goto cleanup; } - int sret =3D snprintf(to_send, sizeof(to_send), "\x01%c%s%c%s", - (int) strlen(creds.username), creds.username, - (int) strlen(creds.password), creds.password); + int sret =3D snprintf(to_send, sizeof(to_send), "\x01%c%s%c%s", (int)s= trlen(creds.username), + creds.username, (int)strlen(creds.password), creds= .password); ASSERT(sret <=3D sizeof(to_send)); size =3D send(sd, to_send, strlen(to_send), MSG_NOSIGNAL); if (size !=3D strlen(to_send)) { - msg(D_LINK_ERRORS | M_ERRNO, "socks_username_password_auth: TCP po= rt write failed on send()"); + msg(D_LINK_ERRORS | M_ERRNO, + "socks_username_password_auth: TCP port write failed on send()= "); goto cleanup; } @@ -147,14 +143,16 @@ /* timeout? */ if (status =3D=3D 0) { - msg(D_LINK_ERRORS | M_ERRNO, "socks_username_password_auth: TC= P port read timeout expired"); + msg(D_LINK_ERRORS | M_ERRNO, + "socks_username_password_auth: TCP port read timeout expir= ed"); goto cleanup; } /* error */ if (status < 0) { - msg(D_LINK_ERRORS | M_ERRNO, "socks_username_password_auth: TC= P port read failed on select()"); + msg(D_LINK_ERRORS | M_ERRNO, + "socks_username_password_auth: TCP port read failed on sel= ect()"); goto cleanup; } @@ -164,7 +162,8 @@ /* error? */ if (size !=3D 1) { - msg(D_LINK_ERRORS | M_ERRNO, "socks_username_password_auth: TC= P port read failed on recv()"); + msg(D_LINK_ERRORS | M_ERRNO, + "socks_username_password_auth: TCP port read failed on rec= v()"); goto cleanup; } @@ -187,10 +186,8 @@ } static bool -socks_handshake(struct socks_proxy_info *p, - socket_descriptor_t sd, - struct event_timeout *server_poll_timeout, - volatile int *signal_received) +socks_handshake(struct socks_proxy_info *p, socket_descriptor_t sd, + struct event_timeout *server_poll_timeout, volatile int *s= ignal_received) { char buf[2]; int len =3D 0; @@ -201,7 +198,6 @@ if (p->authfile[0]) { method_sel[2] =3D 0x02; /* METHODS =3D [2 (plain login)] */ - } size =3D send(sd, method_sel, sizeof(method_sel), MSG_NOSIGNAL); if (size !=3D sizeof(method_sel)) @@ -282,7 +278,8 @@ case 2: /* login/password */ if (!p->authfile[0]) { - msg(D_LINK_ERRORS, "socks_handshake: server asked for user= name/login auth but we were " + msg(D_LINK_ERRORS, + "socks_handshake: server asked for username/login auth= but we were " "not provided any credentials"); return false; } @@ -303,15 +300,13 @@ } static bool -recv_socks_reply(socket_descriptor_t sd, - struct openvpn_sockaddr *addr, - struct event_timeout *server_poll_timeout, - volatile int *signal_received) +recv_socks_reply(socket_descriptor_t sd, struct openvpn_sockaddr *addr, + struct event_timeout *server_poll_timeout, volatile int *= signal_received) { char atyp =3D '\0'; int alen =3D 0; int len =3D 0; - char buf[270]; /* 4 + alen(max 256) + 2 */ + char buf[270]; /* 4 + alen(max 256) + 2 */ if (addr !=3D NULL) { @@ -379,18 +374,18 @@ { switch (atyp) { - case '\x01': /* IP V4 */ + case '\x01': /* IP V4 */ alen =3D 4; break; - case '\x03': /* DOMAINNAME */ + case '\x03': /* DOMAINNAME */ /* RFC 1928, section 5: 1 byte length, bytes name, * so the total "address length" is (length+1) */ - alen =3D (unsigned char) c + 1; + alen =3D (unsigned char)c + 1; break; - case '\x04': /* IP V6 */ + case '\x04': /* IP V6 */ alen =3D 16; break; @@ -421,8 +416,7 @@ memcpy(&addr->addr.in4.sin_addr, buf + 4, sizeof(addr->addr.in4.si= n_addr)); memcpy(&addr->addr.in4.sin_port, buf + 8, sizeof(addr->addr.in4.si= n_port)); struct gc_arena gc =3D gc_new(); - msg(M_INFO, "SOCKS proxy wants us to send UDP to %s", - print_openvpn_sockaddr(addr, &gc)); + msg(M_INFO, "SOCKS proxy wants us to send UDP to %s", print_openvp= n_sockaddr(addr, &gc)); gc_free(&gc); } @@ -435,12 +429,12 @@ { int port =3D 0; port =3D atoi(servname); - if (port >0 && port < 65536) + if (port > 0 && port < 65536) { return port; } - struct servent *service; + struct servent *service; service =3D getservbyname(servname, NULL); if (service) { @@ -452,9 +446,9 @@ void establish_socks_proxy_passthru(struct socks_proxy_info *p, - socket_descriptor_t sd, /* already open to= proxy */ - const char *host, /* openvpn server = remote */ - const char *servname, /* openvpn server = port */ + socket_descriptor_t sd, /* already open to = proxy */ + const char *host, /* openvpn server r= emote */ + const char *servname, /* openvpn server p= ort */ struct event_timeout *server_poll_timeout, struct signal_info *sig_info) { @@ -467,32 +461,34 @@ } /* format Socks CONNECT message */ - buf[0] =3D '\x05'; /* VER =3D 5 */ - buf[1] =3D '\x01'; /* CMD =3D 1 (CONNECT) */ - buf[2] =3D '\x00'; /* RSV */ - buf[3] =3D '\x03'; /* ATYP =3D 3 (DOMAINNAME) */ + buf[0] =3D '\x05'; /* VER =3D 5 */ + buf[1] =3D '\x01'; /* CMD =3D 1 (CONNECT) */ + buf[2] =3D '\x00'; /* RSV */ + buf[3] =3D '\x03'; /* ATYP =3D 3 (DOMAINNAME) */ len =3D strlen(host); len =3D (5 + len + 2 > sizeof(buf)) ? (sizeof(buf) - 5 - 2) : len; - buf[4] =3D (char) len; + buf[4] =3D (char)len; memcpy(buf + 5, host, len); int port =3D port_from_servname(servname); - if (port =3D=3D0) + if (port =3D=3D 0) { - msg(D_LINK_ERRORS, "establish_socks_proxy_passthrough: Cannot conv= ert %s to port number", servname); + msg(D_LINK_ERRORS, "establish_socks_proxy_passthrough: Cannot conv= ert %s to port number", + servname); goto error; } - buf[5 + len] =3D (char) (port >> 8); - buf[5 + len + 1] =3D (char) (port & 0xff); + buf[5 + len] =3D (char)(port >> 8); + buf[5 + len + 1] =3D (char)(port & 0xff); { const ssize_t size =3D send(sd, buf, 5 + len + 2, MSG_NOSIGNAL); if ((int)size !=3D 5 + (int)len + 2) { - msg(D_LINK_ERRORS | M_ERRNO, "establish_socks_proxy_passthru: = TCP port write failed on send()"); + msg(D_LINK_ERRORS | M_ERRNO, + "establish_socks_proxy_passthru: TCP port write failed on = send()"); goto error; } } @@ -514,7 +510,7 @@ void establish_socks_proxy_udpassoc(struct socks_proxy_info *p, - socket_descriptor_t ctrl_sd, /* already op= en to proxy */ + socket_descriptor_t ctrl_sd, /* already ope= n to proxy */ struct openvpn_sockaddr *relay_addr, struct event_timeout *server_poll_timeout, struct signal_info *sig_info) @@ -528,12 +524,12 @@ /* send Socks UDP ASSOCIATE message */ /* VER =3D 5, CMD =3D 3 (UDP ASSOCIATE), RSV =3D 0, ATYP =3D 1 (IP= V4), * BND.ADDR =3D 0, BND.PORT =3D 0 */ - const ssize_t size =3D send(ctrl_sd, - "\x05\x03\x00\x01\x00\x00\x00\x00\x00\x0= 0", - 10, MSG_NOSIGNAL); + const ssize_t size =3D + send(ctrl_sd, "\x05\x03\x00\x01\x00\x00\x00\x00\x00\x00", 10, = MSG_NOSIGNAL); if (size !=3D 10) { - msg(D_LINK_ERRORS | M_ERRNO, "establish_socks_proxy_passthru: = TCP port write failed on send()"); + msg(D_LINK_ERRORS | M_ERRNO, + "establish_socks_proxy_passthru: TCP port write failed on = send()"); goto error; } } @@ -560,8 +556,7 @@ * Run after UDP read. */ void -socks_process_incoming_udp(struct buffer *buf, - struct link_socket_actual *from) +socks_process_incoming_udp(struct buffer *buf, struct link_socket_actual *= from) { int atyp; @@ -577,7 +572,7 @@ } atyp =3D buf_read_u8(buf); - if (atyp !=3D 1) /* ATYP =3D=3D 1 (IP V4) */ + if (atyp !=3D 1) /* ATYP =3D=3D 1 (IP V4) */ { goto error; } @@ -599,8 +594,7 @@ * Returns the size of the header. */ int -socks_process_outgoing_udp(struct buffer *buf, - const struct link_socket_actual *to) +socks_process_outgoing_udp(struct buffer *buf, const struct link_socket_ac= tual *to) { /* * Get a 10 byte subset buffer prepended to buf -- @@ -612,8 +606,8 @@ /* crash if not enough headroom in buf */ ASSERT(buf_defined(&head)); - buf_write_u16(&head, 0); /* RSV =3D 0 */ - buf_write_u8(&head, 0); /* FRAG =3D 0 */ + buf_write_u16(&head, 0); /* RSV =3D 0 */ + buf_write_u8(&head, 0); /* FRAG =3D 0 */ buf_write_u8(&head, '\x01'); /* ATYP =3D 1 (IP V4) */ buf_write(&head, &to->dest.addr.in4.sin_addr, sizeof(to->dest.addr.in4= .sin_addr)); buf_write(&head, &to->dest.addr.in4.sin_port, sizeof(to->dest.addr.in4= .sin_port)); diff --git a/src/openvpn/socks.h b/src/openvpn/socks.h index 985745b..b5a69b9 100644 --- a/src/openvpn/socks.h +++ b/src/openvpn/socks.h @@ -33,7 +33,8 @@ struct openvpn_sockaddr; struct link_socket_actual; -struct socks_proxy_info { +struct socks_proxy_info +{ bool defined; char server[128]; @@ -41,29 +42,26 @@ char authfile[256]; }; -struct socks_proxy_info *socks_proxy_new(const char *server, - const char *port, +struct socks_proxy_info *socks_proxy_new(const char *server, const char *p= ort, const char *authfile); void socks_proxy_close(struct socks_proxy_info *sp); void establish_socks_proxy_passthru(struct socks_proxy_info *p, - socket_descriptor_t sd, /* already op= en to proxy */ - const char *host, /* openvpn se= rver remote */ - const char *servname, /* open= vpn server port */ + socket_descriptor_t sd, /* already ope= n to proxy */ + const char *host, /* openvpn ser= ver remote */ + const char *servname, /* openvpn ser= ver port */ struct event_timeout *server_poll_time= out, struct signal_info *sig_info); void establish_socks_proxy_udpassoc(struct socks_proxy_info *p, - socket_descriptor_t ctrl_sd, /* alrea= dy open to proxy */ + socket_descriptor_t ctrl_sd, /* alread= y open to proxy */ struct openvpn_sockaddr *relay_addr, struct event_timeout *server_poll_time= out, struct signal_info *sig_info); =20 -void socks_process_incoming_udp(struct buffer *buf, - struct link_socket_actual *from); +void socks_process_incoming_udp(struct buffer *buf, struct link_socket_act= ual *from); -int socks_process_outgoing_udp(struct buffer *buf, - const struct link_socket_actual *to); +int socks_process_outgoing_udp(struct buffer *buf, const struct link_socke= t_actual *to); #endif /* ifndef SOCKS_H */ diff --git a/src/openvpn/ssl.c b/src/openvpn/ssl.c index 06621bd..b7db1e7 100644 --- a/src/openvpn/ssl.c +++ b/src/openvpn/ssl.c @@ -74,20 +74,20 @@ static int tls_packets_generated; /* GLOBAL */ static int tls_packets_sent; /* GLOBAL */ -#define INCR_SENT ++tls_packets_sent -#define INCR_GENERATED ++tls_packets_generated -#define INCR_SUCCESS ++tls_handshake_success -#define INCR_ERROR ++tls_handshake_error +#define INCR_SENT ++tls_packets_sent +#define INCR_GENERATED ++tls_packets_generated +#define INCR_SUCCESS ++tls_handshake_success +#define INCR_ERROR ++tls_handshake_error void show_tls_performance_stats(void) { msg(D_TLS_DEBUG_LOW, "TLS Handshakes, success=3D%f%% (good=3D%d, bad= =3D%d), retransmits=3D%f%%", - (double) tls_handshake_success / (tls_handshake_success + tls_hand= shake_error) * 100.0, + (double)tls_handshake_success / (tls_handshake_success + tls_hands= hake_error) * 100.0, tls_handshake_success, tls_handshake_error, - (double) (tls_packets_sent - tls_packets_generated) / tls_packets_= generated * 100.0); + (double)(tls_packets_sent - tls_packets_generated) / tls_packets_g= enerated * 100.0); } -#else /* ifdef MEASURE_TLS_HANDSHAKE_STATS */ +#else /* ifdef MEASURE_TLS_HANDSHAKE_STATS */ #define INCR_SENT #define INCR_GENERATED @@ -111,7 +111,7 @@ if (*reneg_bytes =3D=3D -1) /* Not user-specified */ { msg(M_WARN, "WARNING: cipher with small block size in use, " - "reducing reneg-bytes to 64MB to mitigate SWEET32 attacks.= "); + "reducing reneg-bytes to 64MB to mitigate SWEET32 = attacks."); *reneg_bytes =3D 64 * 1024 * 1024; } } @@ -129,9 +129,10 @@ /* set limit to 7/8 of the limit so the renegotiation can succeed befo= re * we go over the limit */ - limit =3D limit/8 * 7; + limit =3D limit / 8 * 7; - msg(D_SHOW_KEYS, "Note: AEAD cipher %s will trigger a renegotiation" + msg(D_SHOW_KEYS, + "Note: AEAD cipher %s will trigger a renegotiation" " at a sum of %" PRIi64 " blocks and packets.", ciphername, limit); return limit; @@ -152,8 +153,7 @@ overhead +=3D 10; /* tls-auth and tls-crypt */ - overhead +=3D max_int(tls_crypt_buf_overhead(), - packet_id_size(true) + OPENVPN_MAX_HMAC_SIZE); + overhead +=3D max_int(tls_crypt_buf_overhead(), packet_id_size(true) += OPENVPN_MAX_HMAC_SIZE); /* TCP length field and opcode */ overhead +=3D 3; @@ -217,8 +217,7 @@ /* Add the typical UDP overhead for an IPv6 UDP packet. TCP+IPv6 has a * larger overhead but the risk of a TCP connection getting dropped be= cause * we try to send a too large packet is basically zero */ - overhead +=3D datagram_overhead(session->untrusted_addr.dest.addr.sa.s= a_family, - PROTO_UDP); + overhead +=3D datagram_overhead(session->untrusted_addr.dest.addr.sa.s= a_family, PROTO_UDP); return overhead; } @@ -252,7 +251,8 @@ unprotect_user_pass(&passbuf); if (!strlen(passbuf.password)) { - get_user_pass(&passbuf, auth_file, UP_TYPE_PRIVATE_KEY, GET_USER_P= ASS_MANAGEMENT|GET_USER_PASS_PASSWORD_ONLY); + get_user_pass(&passbuf, auth_file, UP_TYPE_PRIVATE_KEY, + GET_USER_PASS_MANAGEMENT | GET_USER_PASS_PASSWORD_ON= LY); } } @@ -291,8 +291,7 @@ } void -auth_user_pass_setup(const char *auth_file, bool is_inline, - const struct static_challenge_info *sci) +auth_user_pass_setup(const char *auth_file, bool is_inline, const struct s= tatic_challenge_info *sci) { unsigned int flags =3D GET_USER_PASS_MANAGEMENT; @@ -308,11 +307,7 @@ if (auth_challenge) /* dynamic challenge/response */ { flags |=3D GET_USER_PASS_DYNAMIC_CHALLENGE; - get_user_pass_cr(&auth_user_pass, - auth_file, - UP_TYPE_AUTH, - flags, - auth_challenge); + get_user_pass_cr(&auth_user_pass, auth_file, UP_TYPE_AUTH, fla= gs, auth_challenge); } else if (sci) /* static challenge response */ { @@ -325,11 +320,7 @@ { flags |=3D GET_USER_PASS_STATIC_CHALLENGE_CONCAT; } - get_user_pass_cr(&auth_user_pass, - auth_file, - UP_TYPE_AUTH, - flags, - sci->challenge_text); + get_user_pass_cr(&auth_user_pass, auth_file, UP_TYPE_AUTH, fla= gs, sci->challenge_text); } else #endif /* ifdef ENABLE_MANAGEMENT */ @@ -468,11 +459,10 @@ * @param crl_file_inline True if crl_file is an inline CRL. */ static void -tls_ctx_reload_crl(struct tls_root_ctx *ssl_ctx, const char *crl_file, - bool crl_file_inline) +tls_ctx_reload_crl(struct tls_root_ctx *ssl_ctx, const char *crl_file, boo= l crl_file_inline) { /* if something goes wrong with stat(), we'll store 0 as mtime */ - platform_stat_t crl_stat =3D {0}; + platform_stat_t crl_stat =3D { 0 }; /* * an inline CRL can't change at runtime, therefore there is no need to @@ -536,11 +526,10 @@ if (options->dh_file) { - tls_ctx_load_dh_params(new_ctx, options->dh_file, - options->dh_file_inline); + tls_ctx_load_dh_params(new_ctx, options->dh_file, options->dh_= file_inline); } } - else /* if client */ + else /* if client */ { tls_ctx_client_new(new_ctx); } @@ -567,8 +556,9 @@ if (options->pkcs12_file) { - if (0 !=3D tls_ctx_load_pkcs12(new_ctx, options->pkcs12_file, - options->pkcs12_file_inline, !options= ->ca_file)) + if (0 + !=3D tls_ctx_load_pkcs12(new_ctx, options->pkcs12_file, option= s->pkcs12_file_inline, + !options->ca_file)) { goto err; } @@ -593,8 +583,7 @@ #ifdef ENABLE_MANAGEMENT else if (options->management_flags & MF_EXTERNAL_CERT) { - char *cert =3D management_query_cert(management, - options->management_certificate= ); + char *cert =3D management_query_cert(management, options->manageme= nt_certificate); tls_ctx_load_cert_file(new_ctx, cert, true); free(cert); } @@ -606,8 +595,9 @@ if (options->priv_key_file) { - if (0 !=3D tls_ctx_load_priv_file(new_ctx, options->priv_key_file, - options->priv_key_file_inline)) + if (0 + !=3D tls_ctx_load_priv_file(new_ctx, options->priv_key_file, + options->priv_key_file_inline)) { goto err; } @@ -625,15 +615,16 @@ if (options->ca_file || options->ca_path) { - tls_ctx_load_ca(new_ctx, options->ca_file, options->ca_file_inline, - options->ca_path, options->tls_server); + tls_ctx_load_ca(new_ctx, options->ca_file, options->ca_file_inline= , options->ca_path, + options->tls_server); } /* Load extra certificates that are part of our own certificate * chain but shouldn't be included in the verify chain */ if (options->extra_certs_file) { - tls_ctx_load_extra_certs(new_ctx, options->extra_certs_file, optio= ns->extra_certs_file_inline); + tls_ctx_load_extra_certs(new_ctx, options->extra_certs_file, + options->extra_certs_file_inline); } /* Check certificate notBefore and notAfter */ @@ -777,9 +768,8 @@ for (int i =3D 0; i < KEY_SCAN_SIZE; ++i) { struct key_state *ks =3D get_key_scan(multi, i); - buf_printf(&out, " [key#%d state=3D%s auth=3D%s id=3D%d sid=3D%s]"= , i, - state_name(ks->state), ks_auth_name(ks->authenticated), - ks->key_id, + buf_printf(&out, " [key#%d state=3D%s auth=3D%s id=3D%d sid=3D%s]"= , i, state_name(ks->state), + ks_auth_name(ks->authenticated), ks->key_id, session_id_print(&ks->session_id_remote, gc)); } @@ -832,8 +822,7 @@ * Build TLS object that reads/writes ciphertext * to/from memory BIOs. */ - key_state_ssl_init(&ks->ks_ssl, &session->opt->ssl_ctx, session->opt->= server, - session); + key_state_ssl_init(&ks->ks_ssl, &session->opt->ssl_ctx, session->opt->= server, session); /* Set control-channel initiation mode */ ks->initial_opcode =3D session->initial_opcode; @@ -869,14 +858,12 @@ session->opt->frame.buf.headroom, TLS_RELIABLE_N_SEND_BU= FFERS, ks->key_id ? false : session->opt->xmit_hold); reliable_init(ks->rec_reliable, BUF_SIZE(&session->opt->frame), - session->opt->frame.buf.headroom, TLS_RELIABLE_N_REC_BUF= FERS, - false); + session->opt->frame.buf.headroom, TLS_RELIABLE_N_REC_BUF= FERS, false); reliable_set_timeout(ks->send_reliable, session->opt->packet_timeout); /* init packet ID tracker */ - packet_id_init(&ks->crypto_options.packet_id, - session->opt->replay_window, session->opt->replay_time,= "SSL", - ks->key_id); + packet_id_init(&ks->crypto_options.packet_id, session->opt->replay_win= dow, + session->opt->replay_time, "SSL", ks->key_id); ks->crypto_options.pid_persist =3D NULL; @@ -888,11 +875,10 @@ * Attempt CRL reload before TLS negotiation. Won't be performed if * the file was not modified since the last reload */ - if (session->opt->crl_file - && !(session->opt->ssl_flags & SSLF_CRL_VERIFY_DIR)) + if (session->opt->crl_file && !(session->opt->ssl_flags & SSLF_CRL_VER= IFY_DIR)) { - tls_ctx_reload_crl(&session->opt->ssl_ctx, - session->opt->crl_file, session->opt->crl_file_= inline); + tls_ctx_reload_crl(&session->opt->ssl_ctx, session->opt->crl_file, + session->opt->crl_file_inline); } } @@ -963,7 +949,7 @@ #ifdef ENABLE_MANAGEMENT || management_enable_def_auth(management) #endif - ); + ); } @@ -1012,8 +998,8 @@ } else { - session->initial_opcode =3D session->opt->tls_crypt_v2 ? - P_CONTROL_HARD_RESET_CLIENT_V3 : P_CONTR= OL_HARD_RESET_CLIENT_V2; + session->initial_opcode =3D session->opt->tls_crypt_v2 ? P_CONTROL= _HARD_RESET_CLIENT_V3 + : P_CONTROL_H= ARD_RESET_CLIENT_V2; } /* Initialize control channel authentication parameters */ @@ -1021,10 +1007,8 @@ session->tls_wrap.work =3D alloc_buf(BUF_SIZE(&session->opt->frame)); /* initialize packet ID replay window for --tls-auth */ - packet_id_init(&session->tls_wrap.opt.packet_id, - session->opt->replay_window, - session->opt->replay_time, - "TLS_WRAP", session->key_id); + packet_id_init(&session->tls_wrap.opt.packet_id, session->opt->replay_= window, + session->opt->replay_time, "TLS_WRAP", session->key_id); /* If we are using tls-crypt-v2 we manipulate the packet id to be (ab)= used * to indicate early protocol negotiation */ @@ -1035,8 +1019,7 @@ } /* load most recent packet-id to replay protect on --tls-auth */ - packet_id_persist_load_obj(session->tls_wrap.opt.pid_persist, - &session->tls_wrap.opt.packet_id); + packet_id_persist_load_obj(session->tls_wrap.opt.pid_persist, &session= ->tls_wrap.opt.packet_id); key_state_init(session, &session->key[KS_PRIMARY]); @@ -1094,9 +1077,7 @@ move_session(struct tls_multi *multi, int dest, int src, bool reinit_src) { msg(D_TLS_DEBUG_LOW, "TLS: move_session: dest=3D%s src=3D%s reinit_src= =3D%d", - session_index_name(dest), - session_index_name(src), - reinit_src); + session_index_name(dest), session_index_name(src), reinit_src); ASSERT(src !=3D dest); ASSERT(src >=3D 0 && src < TM_SIZE); ASSERT(dest >=3D 0 && dest < TM_SIZE); @@ -1200,8 +1181,7 @@ */ struct tls_auth_standalone * -tls_auth_standalone_init(struct tls_options *tls_options, - struct gc_arena *gc) +tls_auth_standalone_init(struct tls_options *tls_options, struct gc_arena = *gc) { struct tls_auth_standalone *tas; @@ -1242,9 +1222,7 @@ * sets. */ void -tls_multi_init_set_options(struct tls_multi *multi, - const char *local, - const char *remote) +tls_multi_init_set_options(struct tls_multi *multi, const char *local, con= st char *remote) { /* initialize options string */ multi->opt.local_options =3D local; @@ -1290,8 +1268,7 @@ */ static void -key_source_print(const struct key_source *k, - const char *prefix) +key_source_print(const struct key_source *k, const char *prefix) { struct gc_arena gc =3D gc_new(); @@ -1299,17 +1276,11 @@ VALGRIND_MAKE_READABLE((void *)k->random1, sizeof(k->random1)); VALGRIND_MAKE_READABLE((void *)k->random2, sizeof(k->random2)); - dmsg(D_SHOW_KEY_SOURCE, - "%s pre_master: %s", - prefix, + dmsg(D_SHOW_KEY_SOURCE, "%s pre_master: %s", prefix, format_hex(k->pre_master, sizeof(k->pre_master), 0, &gc)); - dmsg(D_SHOW_KEY_SOURCE, - "%s random1: %s", - prefix, + dmsg(D_SHOW_KEY_SOURCE, "%s random1: %s", prefix, format_hex(k->random1, sizeof(k->random1), 0, &gc)); - dmsg(D_SHOW_KEY_SOURCE, - "%s random2: %s", - prefix, + dmsg(D_SHOW_KEY_SOURCE, "%s random2: %s", prefix, format_hex(k->random2, sizeof(k->random2), 0, &gc)); gc_free(&gc); @@ -1323,24 +1294,15 @@ } static bool -openvpn_PRF(const uint8_t *secret, - int secret_len, - const char *label, - const uint8_t *client_seed, - int client_seed_len, - const uint8_t *server_seed, - int server_seed_len, - const struct session_id *client_sid, - const struct session_id *server_sid, - uint8_t *output, - int output_len) +openvpn_PRF(const uint8_t *secret, int secret_len, const char *label, cons= t uint8_t *client_seed, + int client_seed_len, const uint8_t *server_seed, int server_se= ed_len, + const struct session_id *client_sid, const struct session_id *= server_sid, + uint8_t *output, int output_len) { /* concatenate seed components */ - struct buffer seed =3D alloc_buf(strlen(label) - + client_seed_len - + server_seed_len - + SID_SIZE * 2); + struct buffer seed =3D + alloc_buf(strlen(label) + client_seed_len + server_seed_len + SID_= SIZE * 2); ASSERT(buf_write(&seed, label, strlen(label))); ASSERT(buf_write(&seed, client_seed, client_seed_len)); @@ -1356,8 +1318,7 @@ } /* compute PRF */ - bool ret =3D ssl_tls1_PRF(BPTR(&seed), BLEN(&seed), secret, secret_len, - output, output_len); + bool ret =3D ssl_tls1_PRF(BPTR(&seed), BLEN(&seed), secret, secret_len= , output, output_len); buf_clear(&seed); free_buf(&seed); @@ -1367,11 +1328,8 @@ } static void -init_epoch_keys(struct key_state *ks, - struct tls_multi *multi, - const struct key_type *key_type, - bool server, - struct key2 *key2) +init_epoch_keys(struct key_state *ks, struct tls_multi *multi, const struc= t key_type *key_type, + bool server, struct key2 *key2) { /* For now we hardcode this to be 16 for the software based data chann= el * DCO based implementations/HW implementation might adjust this number @@ -1402,19 +1360,15 @@ * b) They let userspace do the key derivation and pass all the indivi= dual * keys to the DCO layer. * */ - epoch_init_key_ctx(co, key_type, &e1_send, &e1_recv, future_key_count= ); + epoch_init_key_ctx(co, key_type, &e1_send, &e1_recv, future_key_count); secure_memzero(&e1_send, sizeof(e1_send)); secure_memzero(&e1_recv, sizeof(e1_recv)); } static void -init_key_contexts(struct key_state *ks, - struct tls_multi *multi, - const struct key_type *key_type, - bool server, - struct key2 *key2, - bool dco_enabled) +init_key_contexts(struct key_state *ks, struct tls_multi *multi, const str= uct key_type *key_type, + bool server, struct key2 *key2, bool dco_enabled) { struct key_ctx_bi *key =3D &ks->crypto_options.key_ctx_bi; @@ -1428,12 +1382,10 @@ msg(M_FATAL, "FATAL: DCO does not support --auth"); } - int ret =3D init_key_dco_bi(multi, ks, key2, key_direction, - key_type->cipher, server); + int ret =3D init_key_dco_bi(multi, ks, key2, key_direction, key_ty= pe->cipher, server); if (ret < 0) { - msg(M_FATAL, "Impossible to install key material in DCO: %s", - strerror(-ret)); + msg(M_FATAL, "Impossible to install key material in DCO: %s", = strerror(-ret)); } /* encrypt/decrypt context are unused with DCO */ @@ -1445,7 +1397,8 @@ { if (!cipher_kt_mode_aead(key_type->cipher)) { - msg(M_FATAL, "AEAD cipher (currently %s) " + msg(M_FATAL, + "AEAD cipher (currently %s) " "required for epoch data format.", cipher_kt_name(key_type->cipher)); } @@ -1461,8 +1414,8 @@ generate_key_expansion_tls_export(struct tls_session *session, struct key2= *key2) { if (!key_state_export_keying_material(session, EXPORT_KEY_DATA_LABEL, - strlen(EXPORT_KEY_DATA_LABEL), - key2->keys, sizeof(key2->keys))) + strlen(EXPORT_KEY_DATA_LABEL), k= ey2->keys, + sizeof(key2->keys))) { return false; } @@ -1479,42 +1432,28 @@ const struct key_state *ks =3D &session->key[KS_PRIMARY]; const struct key_source2 *key_src =3D ks->key_src; - const struct session_id *client_sid =3D session->opt->server ? - &ks->session_id_remote : &sessio= n->session_id; - const struct session_id *server_sid =3D !session->opt->server ? - &ks->session_id_remote : &sessio= n->session_id; + const struct session_id *client_sid =3D + session->opt->server ? &ks->session_id_remote : &session->session_= id; + const struct session_id *server_sid =3D + !session->opt->server ? &ks->session_id_remote : &session->session= _id; /* debugging print of source key material */ key_source2_print(key_src); /* compute master secret */ - if (!openvpn_PRF(key_src->client.pre_master, - sizeof(key_src->client.pre_master), - KEY_EXPANSION_ID " master secret", - key_src->client.random1, - sizeof(key_src->client.random1), - key_src->server.random1, - sizeof(key_src->server.random1), - NULL, - NULL, - master, - sizeof(master))) + if (!openvpn_PRF(key_src->client.pre_master, sizeof(key_src->client.pr= e_master), + KEY_EXPANSION_ID " master secret", key_src->client.ra= ndom1, + sizeof(key_src->client.random1), key_src->server.rand= om1, + sizeof(key_src->server.random1), NULL, NULL, master, = sizeof(master))) { return false; } /* compute key expansion */ - if (!openvpn_PRF(master, - sizeof(master), - KEY_EXPANSION_ID " key expansion", - key_src->client.random2, - sizeof(key_src->client.random2), - key_src->server.random2, - sizeof(key_src->server.random2), - client_sid, - server_sid, - (uint8_t *)key2->keys, - sizeof(key2->keys))) + if (!openvpn_PRF(master, sizeof(master), KEY_EXPANSION_ID " key expans= ion", + key_src->client.random2, sizeof(key_src->client.rando= m2), + key_src->server.random2, sizeof(key_src->server.rando= m2), client_sid, + server_sid, (uint8_t *)key2->keys, sizeof(key2->keys)= )) { return false; } @@ -1530,8 +1469,7 @@ * master key. */ static bool -generate_key_expansion(struct tls_multi *multi, struct key_state *ks, - struct tls_session *session) +generate_key_expansion(struct tls_multi *multi, struct key_state *ks, stru= ct tls_session *session) { struct key_ctx_bi *key =3D &ks->crypto_options.key_ctx_bi; bool ret =3D false; @@ -1558,17 +1496,16 @@ if (!generate_key_expansion_openvpn_prf(session, &key2)) { msg(D_TLS_ERRORS, "TLS Error: PRF calculation failed. Your sys= tem " - "might not support the old TLS 1.0 PRF calculation anymore= or " - "the policy does not allow it (e.g. running in FIPS mode).= " - "The peer did not announce support for the modern TLS Expo= rt " - "feature that replaces the TLS 1.0 PRF (requires OpenVPN " - "2.6.x or higher)"); + "might not support the old TLS 1.0 PRF calcu= lation anymore or " + "the policy does not allow it (e.g. running = in FIPS mode). " + "The peer did not announce support for the m= odern TLS Export " + "feature that replaces the TLS 1.0 PRF (requ= ires OpenVPN " + "2.6.x or higher)"); goto exit; } } - key2_print(&key2, &session->opt->key_type, - "Master Encrypt", "Master Decrypt"); + key2_print(&key2, &session->opt->key_type, "Master Encrypt", "Master D= ecrypt"); /* check for weak keys */ for (int i =3D 0; i < 2; ++i) @@ -1580,8 +1517,7 @@ } } - init_key_contexts(ks, multi, &session->opt->key_type, server, &key2, - session->opt->dco_enabled); + init_key_contexts(ks, multi, &session->opt->key_type, server, &key2, s= ession->opt->dco_enabled); ret =3D true; exit: @@ -1597,11 +1533,10 @@ * can thus be called only once per session. */ bool -tls_session_generate_data_channel_keys(struct tls_multi *multi, - struct tls_session *session) +tls_session_generate_data_channel_keys(struct tls_multi *multi, struct tls= _session *session) { bool ret =3D false; - struct key_state *ks =3D &session->key[KS_PRIMARY]; /* primary key */ + struct key_state *ks =3D &session->key[KS_PRIMARY]; /* primary key */ if (ks->authenticated <=3D KS_AUTH_FALSE) { @@ -1616,8 +1551,7 @@ msg(D_TLS_ERRORS, "TLS Error: generate_key_expansion failed"); goto cleanup; } - tls_limit_reneg_bytes(session->opt->key_type.cipher, - &session->opt->renegotiate_bytes); + tls_limit_reneg_bytes(session->opt->key_type.cipher, &session->opt->re= negotiate_bytes); session->opt->aead_usage_limit =3D tls_get_limit_aead(session->opt->ke= y_type.cipher); @@ -1631,23 +1565,18 @@ } bool -tls_session_update_crypto_params_do_work(struct tls_multi *multi, - struct tls_session *session, - struct options *options, - struct frame *frame, - struct frame *frame_fragment, - struct link_socket_info *lsi, +tls_session_update_crypto_params_do_work(struct tls_multi *multi, struct t= ls_session *session, + struct options *options, struct f= rame *frame, + struct frame *frame_fragment, str= uct link_socket_info *lsi, dco_context_t *dco) { if (session->key[KS_PRIMARY].crypto_options.key_ctx_bi.initialized) { /* keys already generated, nothing to do */ return true; - } - init_key_type(&session->opt->key_type, options->ciphername, - options->authname, true, true); + init_key_type(&session->opt->key_type, options->ciphername, options->a= uthname, true, true); bool packet_id_long_form =3D cipher_kt_mode_ofb_cfb(session->opt->key_= type.cipher); session->opt->crypto_flags &=3D ~(CO_PACKET_ID_LONG_FORM); @@ -1691,10 +1620,8 @@ * mssfix are set to update in-kernel config */ if (options->ping_send_timeout || frame->mss_fix) { - int ret =3D dco_set_peer(dco, multi->dco_peer_id, - options->ping_send_timeout, - options->ping_rec_timeout, - frame->mss_fix); + int ret =3D dco_set_peer(dco, multi->dco_peer_id, options->pin= g_send_timeout, + options->ping_rec_timeout, frame->mss_f= ix); if (ret < 0) { msg(D_DCO, "Cannot set DCO peer parameters for peer (id=3D= %u): %s", @@ -1707,11 +1634,9 @@ } bool -tls_session_update_crypto_params(struct tls_multi *multi, - struct tls_session *session, +tls_session_update_crypto_params(struct tls_multi *multi, struct tls_sessi= on *session, struct options *options, struct frame *fr= ame, - struct frame *frame_fragment, - struct link_socket_info *lsi, + struct frame *frame_fragment, struct link= _socket_info *lsi, dco_context_t *dco) { if (!check_session_cipher(session, options)) @@ -1722,19 +1647,18 @@ /* Import crypto settings that might be set by pull/push */ session->opt->crypto_flags |=3D options->imported_protocol_flags; - return tls_session_update_crypto_params_do_work(multi, session, option= s, - frame, frame_fragment,= lsi, dco); + return tls_session_update_crypto_params_do_work(multi, session, option= s, frame, frame_fragment, + lsi, dco); } static bool -random_bytes_to_buf(struct buffer *buf, - uint8_t *out, - int outlen) +random_bytes_to_buf(struct buffer *buf, uint8_t *out, int outlen) { if (!rand_bytes(out, outlen)) { - msg(M_FATAL, "ERROR: Random number generator cannot obtain entropy= for key generation [SSL]"); + msg(M_FATAL, + "ERROR: Random number generator cannot obtain entropy for key = generation [SSL]"); } if (!buf_write(buf, out, outlen)) { @@ -1744,9 +1668,7 @@ } static bool -key_source2_randomize_write(struct key_source2 *k2, - struct buffer *buf, - bool server) +key_source2_randomize_write(struct key_source2 *k2, struct buffer *buf, bo= ol server) { struct key_source *k =3D &k2->client; if (server) @@ -1777,9 +1699,7 @@ } static int -key_source2_read(struct key_source2 *k2, - struct buffer *buf, - bool server) +key_source2_read(struct key_source2 *k2, struct buffer *buf, bool server) { struct key_source *k =3D &k2->client; @@ -1829,10 +1749,10 @@ static void key_state_soft_reset(struct tls_session *session) { - struct key_state *ks =3D &session->key[KS_PRIMARY]; /* primary ke= y */ + struct key_state *ks =3D &session->key[KS_PRIMARY]; /* primary = key */ struct key_state *ks_lame =3D &session->key[KS_LAME_DUCK]; /* retiring= key */ - ks->must_die =3D now + session->opt->transition_window; /* remaining l= ifetime of old key */ + ks->must_die =3D now + session->opt->transition_window; /* remainin= g lifetime of old key */ key_state_free(ks_lame, false); *ks_lame =3D *ks; @@ -1905,7 +1825,7 @@ { return -len; } - str[len-1] =3D '\0'; + str[len - 1] =3D '\0'; return len; } @@ -1919,14 +1839,14 @@ { return NULL; } - str =3D (char *) malloc(len); + str =3D (char *)malloc(len); check_malloc_return(str); if (!buf_read(buf, str, len)) { free(str); return NULL; } - str[len-1] =3D '\0'; + str[len - 1] =3D '\0'; return str; } @@ -2019,7 +1939,6 @@ if (tls_item_in_cipher_list("AES-128-GCM", session->opt->confi= g_ncp_ciphers) && tls_item_in_cipher_list("AES-256-GCM", session->opt->co= nfig_ncp_ciphers)) { - buf_printf(&out, "IV_NCP=3D2\n"); } } @@ -2058,7 +1977,7 @@ { buf_printf(&out, "IV_HWADDR=3D%s\n", format_hex_ex(rgi.hwa= ddr, 6, 0, 1, ":", &gc)); } - buf_printf(&out, "IV_SSL=3D%s\n", get_ssl_library_version() ); + buf_printf(&out, "IV_SSL=3D%s\n", get_ssl_library_version()); #if defined(_WIN32) buf_printf(&out, "IV_PLAT_VER=3D%s\n", win32_version_string(&g= c)); #else @@ -2080,8 +1999,7 @@ || strncmp(e->string, "IV_PLAT_VER=3D", sizeof(= "IV_PLAT_VER=3D") - 1) =3D=3D 0) && session->opt->push_peer_info_detail > 2) || (strncmp(e->string, "IV_GUI_VER=3D", sizeof("I= V_GUI_VER=3D") - 1) =3D=3D 0) - || (strncmp(e->string, "IV_SSO=3D", sizeof("IV_SS= O=3D") - 1) =3D=3D 0) - ) + || (strncmp(e->string, "IV_SSO=3D", sizeof("IV_SS= O=3D") - 1) =3D=3D 0)) && buf_safe(&out, strlen(e->string) + 1)) { buf_printf(&out, "%s\n", e->string); @@ -2128,7 +2046,7 @@ static bool key_method_2_write(struct buffer *buf, struct tls_multi *multi, struct tls= _session *session) { - struct key_state *ks =3D &session->key[KS_PRIMARY]; /* primary ke= y */ + struct key_state *ks =3D &session->key[KS_PRIMARY]; /* primary key */ ASSERT(buf_init(buf, 0)); @@ -2163,7 +2081,7 @@ } else #endif - if (!write_string(buf, session->opt->local_options, TLS_OPTIONS_LE= N)) + if (!write_string(buf, session->opt->local_options, TLS_OPTION= S_LEN)) { goto error; } @@ -2174,8 +2092,7 @@ { #ifdef ENABLE_MANAGEMENT auth_user_pass_setup(session->opt->auth_user_pass_file, - session->opt->auth_user_pass_file_inline, - session->opt->sci); + session->opt->auth_user_pass_file_inline, ses= sion->opt->sci); #else auth_user_pass_setup(session->opt->auth_user_pass_file, session->opt->auth_user_pass_file_inline, NUL= L); @@ -2228,8 +2145,7 @@ goto error; } - if (session->opt->server && session->opt->mode !=3D MODE_SERVER - && ks->key_id =3D=3D 0) + if (session->opt->server && session->opt->mode !=3D MODE_SERVER && ks-= >key_id =3D=3D 0) { /* tls-server option set and not P2MP server, so we * are a P2P client running in tls-server mode */ @@ -2253,18 +2169,16 @@ struct gc_arena gc =3D gc_new(); unsigned char *ekm =3D gc_malloc(session->opt->ekm_size, true, &gc= ); - if (key_state_export_keying_material(session, - session->opt->ekm_label, - session->opt->ekm_label_size, - ekm, session->opt->ekm_size)) + if (key_state_export_keying_material(session, session->opt->ekm_la= bel, + session->opt->ekm_label_size,= ekm, + session->opt->ekm_size)) { unsigned int len =3D (size * 2) + 2; const char *key =3D format_hex_ex(ekm, size, len, 0, NULL, &gc= ); setenv_str(session->opt->es, "exported_keying_material", key); - dmsg(D_TLS_DEBUG_MED, "%s: exported keying material: %s", - __func__, key); + dmsg(D_TLS_DEBUG_MED, "%s: exported keying material: %s", __fu= nc__, key); secure_memzero(ekm, size); } else @@ -2283,7 +2197,7 @@ static bool key_method_2_read(struct buffer *buf, struct tls_multi *multi, struct tls_= session *session) { - struct key_state *ks =3D &session->key[KS_PRIMARY]; /* primary ke= y */ + struct key_state *ks =3D &session->key[KS_PRIMARY]; /* primary key */ struct gc_arena gc =3D gc_new(); char *options; @@ -2295,8 +2209,7 @@ /* discard leading uint32 */ if (!buf_advance(buf, 4)) { - msg(D_TLS_ERRORS, "TLS ERROR: Plaintext buffer too short (%d bytes= ).", - buf->len); + msg(D_TLS_ERRORS, "TLS ERROR: Plaintext buffer too short (%d bytes= ).", buf->len); goto error; } @@ -2304,8 +2217,7 @@ int key_method_flags =3D buf_read_u8(buf); if ((key_method_flags & KEY_METHOD_MASK) !=3D 2) { - msg(D_TLS_ERRORS, - "TLS ERROR: Unknown key_method/flags=3D%d received from remote= host", + msg(D_TLS_ERRORS, "TLS ERROR: Unknown key_method/flags=3D%d receiv= ed from remote host", key_method_flags); goto error; } @@ -2313,7 +2225,8 @@ /* get key source material (not actual keys yet) */ if (!key_source2_read(ks->key_src, buf, session->opt->server)) { - msg(D_TLS_ERRORS, "TLS Error: Error reading remote data channel ke= y source entropy from plaintext buffer"); + msg(D_TLS_ERRORS, + "TLS Error: Error reading remote data channel key source entro= py from plaintext buffer"); goto error; } @@ -2343,13 +2256,11 @@ } free(multi->remote_ciphername); - multi->remote_ciphername =3D - options_string_extract_option(options, "cipher", NULL); + multi->remote_ciphername =3D options_string_extract_option(options, "c= ipher", NULL); multi->remote_usescomp =3D strstr(options, ",comp-lzo,"); /* In OCC we send '[null-cipher]' instead 'none' */ - if (multi->remote_ciphername - && strcmp(multi->remote_ciphername, "[null-cipher]") =3D=3D 0) + if (multi->remote_ciphername && strcmp(multi->remote_ciphername, "[nul= l-cipher]") =3D=3D 0) { free(multi->remote_ciphername); multi->remote_ciphername =3D string_alloc("none", NULL); @@ -2357,10 +2268,10 @@ if (username_len < 0 || password_len < 0) { - msg(D_TLS_ERRORS, "TLS Error: Username (%d) or password (%d) too l= ong", - abs(username_len), abs(password_len)); + msg(D_TLS_ERRORS, "TLS Error: Username (%d) or password (%d) too l= ong", abs(username_len), + abs(password_len)); auth_set_client_reason(multi, "Username or password is too long. " - "Maximum length is 128 bytes"); + "Maximum length is 128 bytes"); /* treat the same as failed username/password and do not error * out (goto error) to sent an AUTH_FAILED back to the client */ @@ -2386,8 +2297,7 @@ /* Session verification should have occurred during TLS negotiatio= n*/ if (!session->verified) { - msg(D_TLS_ERRORS, - "TLS Error: Certificate verification failed (key-method 2)= "); + msg(D_TLS_ERRORS, "TLS Error: Certificate verification failed = (key-method 2)"); goto error; } ks->authenticated =3D KS_AUTH_TRUE; @@ -2410,7 +2320,7 @@ if (multi->opt.comp_options.flags & COMP_F_MIGRATE && multi->remot= e_usescomp) { msg(D_PUSH, "Note: 'compress migrate' detected remote peer " - "with compression enabled."); + "with compression enabled."); remote_options =3D options_string_compat_lzo(remote_options, &= gc); } #endif @@ -2419,7 +2329,8 @@ if (session->opt->ssl_flags & SSLF_OPT_VERIFY) { - msg(D_TLS_ERRORS, "Option inconsistency warnings triggering di= sconnect due to --opt-verify"); + msg(D_TLS_ERRORS, + "Option inconsistency warnings triggering disconnect due t= o --opt-verify"); ks->authenticated =3D KS_AUTH_FALSE; } } @@ -2435,7 +2346,9 @@ { export_user_keying_material(session); - if (plugin_call(session->opt->plugins, OPENVPN_PLUGIN_TLS_FINAL, N= ULL, NULL, session->opt->es) !=3D OPENVPN_PLUGIN_FUNC_SUCCESS) + if (plugin_call(session->opt->plugins, OPENVPN_PLUGIN_TLS_FINAL, N= ULL, NULL, + session->opt->es) + !=3D OPENVPN_PLUGIN_FUNC_SUCCESS) { ks->authenticated =3D KS_AUTH_FALSE; } @@ -2485,8 +2398,8 @@ * @return if the state change was succesful */ static bool -session_move_pre_start(const struct tls_session *session, - struct key_state *ks, bool skip_initial_send) +session_move_pre_start(const struct tls_session *session, struct key_state= *ks, + bool skip_initial_send) { struct buffer *buf =3D reliable_get_buf_output_sequenced(ks->send_reli= able); if (!buf) @@ -2519,17 +2432,10 @@ #ifdef ENABLE_MANAGEMENT if (management && ks->initial_opcode !=3D P_CONTROL_SOFT_RESET_V1) { - management_set_state(management, - OPENVPN_STATE_WAIT, - NULL, - NULL, - NULL, - NULL, - NULL); + management_set_state(management, OPENVPN_STATE_WAIT, NULL, NULL, N= ULL, NULL, NULL); } #endif return true; - } /** @@ -2538,8 +2444,7 @@ */ static void session_move_active(struct tls_multi *multi, struct tls_session *session, - struct link_socket_info *to_link_socket_info, - struct key_state *ks) + struct link_socket_info *to_link_socket_info, struct k= ey_state *ks) { dmsg(D_TLS_DEBUG_MED, "STATE S_ACTIVE"); @@ -2554,8 +2459,8 @@ INCR_SUCCESS; /* Set outgoing address for data channel packets */ - link_socket_set_outgoing_addr(to_link_socket_info, &ks->remote_addr, - session->common_name, session->opt->es); + link_socket_set_outgoing_addr(to_link_socket_info, &ks->remote_addr, s= ession->common_name, + session->opt->es); /* Check if we need to advance the tls_multi state machine */ if (multi->multi_state =3D=3D CAS_NOT_CONNECTED) @@ -2581,8 +2486,7 @@ } bool -session_skip_to_pre_start(struct tls_session *session, - struct tls_pre_decrypt_state *state, +session_skip_to_pre_start(struct tls_session *session, struct tls_pre_decr= ypt_state *state, struct link_socket_actual *from) { struct key_state *ks =3D &session->key[KS_PRIMARY]; @@ -2656,8 +2560,7 @@ * Returns false if an error is encountered that should abort the session. */ static bool -read_incoming_tls_ciphertext(struct buffer *buf, struct key_state *ks, - bool *continue_tls_process) +read_incoming_tls_ciphertext(struct buffer *buf, struct key_state *ks, boo= l *continue_tls_process) { int status =3D 0; if (buf->len) @@ -2665,8 +2568,7 @@ status =3D key_state_write_ciphertext(&ks->ks_ssl, buf); if (status =3D=3D -1) { - msg(D_TLS_ERRORS, - "TLS Error: Incoming Ciphertext -> TLS object write error"= ); + msg(D_TLS_ERRORS, "TLS Error: Incoming Ciphertext -> TLS objec= t write error"); return false; } } @@ -2686,14 +2588,13 @@ static bool control_packet_needs_wkc(const struct key_state *ks) { - return (ks->crypto_options.flags & CO_RESEND_WKC) - && (ks->send_reliable->packet_id =3D=3D 1); + return (ks->crypto_options.flags & CO_RESEND_WKC) && (ks->send_reliabl= e->packet_id =3D=3D 1); } static bool -read_incoming_tls_plaintext(struct key_state *ks, struct buffer *buf, - interval_t *wakeup, bool *continue_tls_process) +read_incoming_tls_plaintext(struct key_state *ks, struct buffer *buf, inte= rval_t *wakeup, + bool *continue_tls_process) { ASSERT(buf_init(buf, 0)); @@ -2748,7 +2649,8 @@ * if we have a large wrapped client key. */ if (maxlen < 16) { - msg(D_TLS_ERRORS, "Warning: --max-packet-size (%d) setting too low= . " + msg(D_TLS_ERRORS, + "Warning: --max-packet-size (%d) setting too low. " "Sending minimum sized packet.", session->opt->frame.tun_mtu); maxlen =3D 16; @@ -2765,8 +2667,7 @@ if (status =3D=3D -1) { - msg(D_TLS_ERRORS, - "TLS Error: Ciphertext -> reliable TCP/UDP transport read erro= r"); + msg(D_TLS_ERRORS, "TLS Error: Ciphertext -> reliable TCP/UDP trans= port read error"); gc_free(&gc); return false; } @@ -2822,12 +2723,9 @@ } static bool -tls_process_state(struct tls_multi *multi, - struct tls_session *session, - struct buffer *to_link, +tls_process_state(struct tls_multi *multi, struct tls_session *session, st= ruct buffer *to_link, struct link_socket_actual **to_link_addr, - struct link_socket_info *to_link_socket_info, - interval_t *wakeup) + struct link_socket_info *to_link_socket_info, interval_t= *wakeup) { /* This variable indicates if we should call this method * again to process more incoming/outgoing TLS state/data @@ -2836,7 +2734,7 @@ * should only be done after the outer loop (sending packets etc.) * has run once more */ bool continue_tls_process =3D false; - struct key_state *ks =3D &session->key[KS_PRIMARY]; /* primary ke= y */ + struct key_state *ks =3D &session->key[KS_PRIMARY]; /* primary key */ /* Initial handshake */ if (ks->state =3D=3D S_INITIAL) @@ -2886,8 +2784,7 @@ struct buffer b =3D *buf; INCR_SENT; - write_control_auth(session, ks, &b, to_link_addr, opcode, - CONTROL_SEND_ACK_MAX, true); + write_control_auth(session, ks, &b, to_link_addr, opcode, CONTROL_= SEND_ACK_MAX, true); *to_link =3D b; dmsg(D_TLS_DEBUG, "Reliable -> TCP/UDP"); @@ -2943,8 +2840,9 @@ /* Send Key */ buf =3D &ks->plaintext_write_buf; - if (!buf->len && ((ks->state =3D=3D S_START && !session->opt->server) - || (ks->state =3D=3D S_GOT_KEY && session->opt->serv= er))) + if (!buf->len + && ((ks->state =3D=3D S_START && !session->opt->server) + || (ks->state =3D=3D S_GOT_KEY && session->opt->server))) { if (!key_method_2_write(buf, multi, session)) { @@ -2979,8 +2877,7 @@ int status =3D key_state_write_plaintext(&ks->ks_ssl, buf); if (status =3D=3D -1) { - msg(D_TLS_ERRORS, - "TLS ERROR: Outgoing Plaintext -> TLS object write error"); + msg(D_TLS_ERRORS, "TLS ERROR: Outgoing Plaintext -> TLS object= write error"); goto error; } if (status =3D=3D 1) @@ -3027,15 +2924,13 @@ } /* Byte limit */ - if (session->opt->renegotiate_bytes > 0 - && ks->n_bytes >=3D session->opt->renegotiate_bytes) + if (session->opt->renegotiate_bytes > 0 && ks->n_bytes >=3D session->o= pt->renegotiate_bytes) { return true; } /* Packet limit */ - if (session->opt->renegotiate_packets - && ks->n_packets >=3D session->opt->renegotiate_packets) + if (session->opt->renegotiate_packets && ks->n_packets >=3D session->o= pt->renegotiate_packets) { return true; } @@ -3102,14 +2997,11 @@ * want to send to our peer. */ static bool -tls_process(struct tls_multi *multi, - struct tls_session *session, - struct buffer *to_link, - struct link_socket_actual **to_link_addr, - struct link_socket_info *to_link_socket_info, +tls_process(struct tls_multi *multi, struct tls_session *session, struct b= uffer *to_link, + struct link_socket_actual **to_link_addr, struct link_socket_i= nfo *to_link_socket_info, interval_t *wakeup) { - struct key_state *ks =3D &session->key[KS_PRIMARY]; /* primary ke= y */ + struct key_state *ks =3D &session->key[KS_PRIMARY]; /* primary = key */ struct key_state *ks_lame =3D &session->key[KS_LAME_DUCK]; /* retiring= key */ /* Make sure we were initialized and that we're not in an error state = */ @@ -3118,21 +3010,18 @@ ASSERT(session_id_defined(&session->session_id)); /* Should we trigger a soft reset? -- new key, keeps old key for a whi= le */ - if (ks->state >=3D S_GENERATED_KEYS - && should_trigger_renegotiation(session, ks)) + if (ks->state >=3D S_GENERATED_KEYS && should_trigger_renegotiation(se= ssion, ks)) { - msg(D_TLS_DEBUG_LOW, "TLS: soft reset sec=3D%d/%d bytes=3D" counte= r_format - "/%" PRIi64 " pkts=3D" counter_format "/%" PRIi64 - " aead_limit_send=3D%" PRIu64 "/%" PRIu64 - " aead_limit_recv=3D%" PRIu64 "/%" PRIu64, - (int) (now - ks->established), session->opt->renegotiate_secon= ds, - ks->n_bytes, session->opt->renegotiate_bytes, - ks->n_packets, session->opt->renegotiate_packets, + msg(D_TLS_DEBUG_LOW, + "TLS: soft reset sec=3D%d/%d bytes=3D" counter_format "/%" PRI= i64 " pkts=3D" counter_format + "/%" PRIi64 " aead_limit_send=3D%" PRIu64 "/%" PRIu64 " aead_l= imit_recv=3D%" PRIu64 + "/%" PRIu64, + (int)(now - ks->established), session->opt->renegotiate_second= s, ks->n_bytes, + session->opt->renegotiate_bytes, ks->n_packets, session->opt->= renegotiate_packets, ks->crypto_options.key_ctx_bi.encrypt.plaintext_blocks + ks->n= _packets, session->opt->aead_usage_limit, ks->crypto_options.key_ctx_bi.decrypt.plaintext_blocks + ks->n= _packets, - session->opt->aead_usage_limit - ); + session->opt->aead_usage_limit); key_state_soft_reset(session); } @@ -3149,19 +3038,15 @@ update_time(); dmsg(D_TLS_DEBUG, "TLS: tls_process: chg=3D%d ks=3D%s lame=3D%s to= _link->len=3D%d wakeup=3D%d", - continue_tls_process, - state_name(ks->state), - state_name(ks_lame->state), - to_link->len, + continue_tls_process, state_name(ks->state), state_name(ks_la= me->state), to_link->len, *wakeup); - continue_tls_process =3D tls_process_state(multi, session, to_link= , to_link_addr, - to_link_socket_info, wake= up); + continue_tls_process =3D + tls_process_state(multi, session, to_link, to_link_addr, to_li= nk_socket_info, wakeup); if (ks->state =3D=3D S_ERROR) { return false; } - } update_time(); @@ -3192,8 +3077,7 @@ { struct buffer buf =3D ks->ack_write_buf; ASSERT(buf_init(&buf, multi->opt.frame.buf.headroom)); - write_control_auth(session, ks, &buf, to_link_addr, P_ACK_V1, - RELIABLE_ACK_SIZE, false); + write_control_auth(session, ks, &buf, to_link_addr, P_ACK_V1, = RELIABLE_ACK_SIZE, false); *to_link =3D buf; dmsg(D_TLS_DEBUG, "Dedicated ACK -> TCP/UDP"); } @@ -3202,8 +3086,7 @@ /* When should we wake up again? */ if (ks->state >=3D S_INITIAL || ks->state =3D=3D S_ERROR_PRE) { - compute_earliest_wakeup(wakeup, - reliable_send_timeout(ks->send_reliable)); + compute_earliest_wakeup(wakeup, reliable_send_timeout(ks->send_rel= iable)); if (ks->must_negotiate) { @@ -3213,8 +3096,7 @@ if (ks->established && session->opt->renegotiate_seconds) { - compute_earliest_wakeup(wakeup, - ks->established + session->opt->renegotiat= e_seconds - now); + compute_earliest_wakeup(wakeup, ks->established + session->opt->re= negotiate_seconds - now); } dmsg(D_TLS_DEBUG, "TLS: tls_process: timeout set to %d", *wakeup); @@ -3260,7 +3142,7 @@ if (session->tls_wrap.work.data =3D=3D dataptr) { msg(M_INFO, "Warning buffer of freed TLS session is " - "still in use (tls_wrap.work.data)"); + "still in use (tls_wrap.work.data)"); goto used; } @@ -3278,7 +3160,8 @@ */ if (!ks->send_reliable) { - msg(M_FATAL, "ERROR: session->key[%d]->send_reliable is NULL " + msg(M_FATAL, + "ERROR: session->key[%d]->send_reliable is NULL " "while key state is %s. Exiting.", i, state_name(ks->state)); } @@ -3287,7 +3170,8 @@ { if (ks->send_reliable->array[j].buf.data =3D=3D dataptr) { - msg(M_INFO, "Warning buffer of freed TLS session is still = in" + msg(M_INFO, + "Warning buffer of freed TLS session is still in" " use (session->key[%d].send_reliable->array[%d])", i, j); @@ -3310,11 +3194,9 @@ */ int -tls_multi_process(struct tls_multi *multi, - struct buffer *to_link, +tls_multi_process(struct tls_multi *multi, struct buffer *to_link, struct link_socket_actual **to_link_addr, - struct link_socket_info *to_link_socket_info, - interval_t *wakeup) + struct link_socket_info *to_link_socket_info, interval_t= *wakeup) { struct gc_arena gc =3D gc_new(); int active =3D TLSMP_INACTIVE; @@ -3338,29 +3220,26 @@ /* set initial remote address. This triggers connecting with that * session. So we only do that if the TM_ACTIVE session is not * established */ - if (i =3D=3D TM_INITIAL && ks->state =3D=3D S_INITIAL - && get_primary_key(multi)->state <=3D S_INITIAL + if (i =3D=3D TM_INITIAL && ks->state =3D=3D S_INITIAL && get_prima= ry_key(multi)->state <=3D S_INITIAL && link_socket_actual_defined(&to_link_socket_info->lsa->actua= l)) { ks->remote_addr =3D to_link_socket_info->lsa->actual; } dmsg(D_TLS_DEBUG, - "TLS: tls_multi_process: i=3D%d state=3D%s, mysid=3D%s, store= d-sid=3D%s, stored-ip=3D%s", - i, - state_name(ks->state), - session_id_print(&session->session_id, &gc), + "TLS: tls_multi_process: i=3D%d state=3D%s, mysid=3D%s, store= d-sid=3D%s, stored-ip=3D%s", i, + state_name(ks->state), session_id_print(&session->session_id,= &gc), session_id_print(&ks->session_id_remote, &gc), print_link_socket_actual(&ks->remote_addr, &gc)); - if ((ks->state >=3D S_INITIAL || ks->state =3D=3D S_ERROR_PRE) && = link_socket_actual_defined(&ks->remote_addr)) + if ((ks->state >=3D S_INITIAL || ks->state =3D=3D S_ERROR_PRE) + && link_socket_actual_defined(&ks->remote_addr)) { struct link_socket_actual *tla =3D NULL; update_time(); - if (tls_process(multi, session, to_link, &tla, - to_link_socket_info, wakeup)) + if (tls_process(multi, session, to_link, &tla, to_link_socket_= info, wakeup)) { active =3D TLSMP_ACTIVE; } @@ -3386,14 +3265,12 @@ { ++multi->n_soft_errors; - if (i =3D=3D TM_ACTIVE - || (i =3D=3D TM_INITIAL && get_primary_key(multi)->sta= te < S_ACTIVE)) + if (i =3D=3D TM_ACTIVE || (i =3D=3D TM_INITIAL && get_prim= ary_key(multi)->state < S_ACTIVE)) { error =3D true; } - if (i =3D=3D TM_ACTIVE - && ks_lame->state >=3D S_GENERATED_KEYS + if (i =3D=3D TM_ACTIVE && ks_lame->state >=3D S_GENERATED_= KEYS && !multi->opt.single_session) { move_session(multi, TM_LAME_DUCK, TM_ACTIVE, true); @@ -3425,8 +3302,8 @@ if (ks->state =3D=3D S_ACTIVE && ks->authenticated =3D=3D KS_AUTH_= TRUE) { /* Session is now fully authenticated. - * tls_session_generate_data_channel_keys will move ks->state - * from S_ACTIVE to S_GENERATED_KEYS */ + * tls_session_generate_data_channel_keys will move ks->state + * from S_ACTIVE to S_GENERATED_KEYS */ if (!tls_session_generate_data_channel_keys(multi, session)) { msg(D_TLS_ERRORS, "TLS Error: generate_key_expansion faile= d"); @@ -3471,7 +3348,8 @@ { move_session(multi, TM_ACTIVE, TM_INITIAL, true); tas =3D tls_authentication_status(multi); - msg(D_TLS_DEBUG_LOW, "TLS: tls_multi_process: initial untrusted " + msg(D_TLS_DEBUG_LOW, + "TLS: tls_multi_process: initial untrusted " "session promoted to %strusted", tas =3D=3D TLS_AUTHENTICATION_SUCCEEDED ? "" : "semi-"); @@ -3528,8 +3406,8 @@ * try to generate a sensible error message and print it */ static void -print_key_id_not_found_reason(struct tls_multi *multi, - const struct link_socket_actual *from, int k= ey_id) +print_key_id_not_found_reason(struct tls_multi *multi, const struct link_s= ocket_actual *from, + int key_id) { struct gc_arena gc =3D gc_new(); const char *source =3D print_link_socket_actual(from, &gc); @@ -3547,17 +3425,14 @@ * session but has not generated keys. */ if (ks->state >=3D S_INITIAL && ks->state < S_GENERATED_KEYS) { - msg(D_MULTI_DROPPED, - "Key %s [%d] not initialized (yet), dropping packet.", - source, key_id); + msg(D_MULTI_DROPPED, "Key %s [%d] not initialized (yet), dropp= ing packet.", source, + key_id); gc_free(&gc); return; } if (ks->state >=3D S_ACTIVE && ks->authenticated !=3D KS_AUTH_TRUE) { - msg(D_MULTI_DROPPED, - "Key %s [%d] not authorized%s, dropping packet.", - source, key_id, + msg(D_MULTI_DROPPED, "Key %s [%d] not authorized%s, dropping p= acket.", source, key_id, (ks->authenticated =3D=3D KS_AUTH_DEFERRED) ? " (deferred)= " : ""); gc_free(&gc); return; @@ -3567,8 +3442,7 @@ msg(D_TLS_ERRORS, "TLS Error: local/remote TLS keys are out of sync: %s " "(received key id: %d, known key ids: %s)", - source, key_id, - print_key_id(multi, &gc)); + source, key_id, print_key_id(multi, &gc)); gc_free(&gc); } @@ -3580,11 +3454,8 @@ * AEAD ciphers to the start of the authenticated data. */ static inline void -handle_data_channel_packet(struct tls_multi *multi, - const struct link_socket_actual *from, - struct buffer *buf, - struct crypto_options **opt, - bool floated, +handle_data_channel_packet(struct tls_multi *multi, const struct link_sock= et_actual *from, + struct buffer *buf, struct crypto_options **opt= , bool floated, const uint8_t **ad_start) { struct gc_arena gc =3D gc_new(); @@ -3630,7 +3501,8 @@ { if (buf->len < 4) { - msg(D_TLS_ERRORS, "Protocol error: received P_DATA_V2 = from %s but length is < 4", + msg(D_TLS_ERRORS, + "Protocol error: received P_DATA_V2 from %s but le= ngth is < 4", print_link_socket_actual(from, &gc)); ++multi->n_soft_errors; goto done; @@ -3640,9 +3512,8 @@ ++ks->n_packets; ks->n_bytes +=3D buf->len; - dmsg(D_TLS_KEYSELECT, - "TLS: tls_pre_decrypt, key_id=3D%d, IP=3D%s", - key_id, print_link_socket_actual(from, &gc)); + dmsg(D_TLS_KEYSELECT, "TLS: tls_pre_decrypt, key_id=3D%d, IP= =3D%s", key_id, + print_link_socket_actual(from, &gc)); gc_free(&gc); return; } @@ -3683,14 +3554,9 @@ */ bool -tls_pre_decrypt(struct tls_multi *multi, - const struct link_socket_actual *from, - struct buffer *buf, - struct crypto_options **opt, - bool floated, - const uint8_t **ad_start) +tls_pre_decrypt(struct tls_multi *multi, const struct link_socket_actual *= from, struct buffer *buf, + struct crypto_options **opt, bool floated, const uint8_t *= *ad_start) { - if (buf->len <=3D 0) { buf->len =3D 0; @@ -3717,18 +3583,16 @@ /* control channel packet */ bool do_burst =3D false; bool new_link =3D false; - struct session_id sid; /* remote session ID */ + struct session_id sid; /* remote session ID */ /* verify legal opcode */ if (op < P_FIRST_OPCODE || op > P_LAST_OPCODE) { - if (op =3D=3D P_CONTROL_HARD_RESET_CLIENT_V1 - || op =3D=3D P_CONTROL_HARD_RESET_SERVER_V1) + if (op =3D=3D P_CONTROL_HARD_RESET_CLIENT_V1 || op =3D=3D P_CONTRO= L_HARD_RESET_SERVER_V1) { msg(D_TLS_ERRORS, "Peer tried unsupported key-method 1"); } - msg(D_TLS_ERRORS, - "TLS Error: unknown opcode received from %s op=3D%d", + msg(D_TLS_ERRORS, "TLS Error: unknown opcode received from %s op= =3D%d", print_link_socket_actual(from, &gc), op); goto error; } @@ -3737,8 +3601,8 @@ if (is_hard_reset_method2(op)) { /* verify client -> server or server -> client connection */ - if (((op =3D=3D P_CONTROL_HARD_RESET_CLIENT_V2 - || op =3D=3D P_CONTROL_HARD_RESET_CLIENT_V3) && !multi->opt.= server) + if (((op =3D=3D P_CONTROL_HARD_RESET_CLIENT_V2 || op =3D=3D P_CONT= ROL_HARD_RESET_CLIENT_V3) + && !multi->opt.server) || ((op =3D=3D P_CONTROL_HARD_RESET_SERVER_V2) && multi->opt.s= erver)) { msg(D_TLS_ERRORS, @@ -3751,8 +3615,8 @@ /* * Authenticate Packet */ - dmsg(D_TLS_DEBUG, "TLS: control channel, op=3D%s, IP=3D%s", - packet_opcode_name(op), print_link_socket_actual(from, &gc)); + dmsg(D_TLS_DEBUG, "TLS: control channel, op=3D%s, IP=3D%s", packet_opc= ode_name(op), + print_link_socket_actual(from, &gc)); /* get remote session-id */ { @@ -3760,8 +3624,7 @@ buf_advance(&tmp, 1); if (!session_id_read(&sid, &tmp) || !session_id_defined(&sid)) { - msg(D_TLS_ERRORS, - "TLS Error: session-id not found in packet from %s", + msg(D_TLS_ERRORS, "TLS Error: session-id not found in packet f= rom %s", print_link_socket_actual(from, &gc)); goto error; } @@ -3774,29 +3637,25 @@ struct tls_session *session =3D &multi->session[i]; struct key_state *ks =3D &session->key[KS_PRIMARY]; - dmsg(D_TLS_DEBUG, - "TLS: initial packet test, i=3D%d state=3D%s, mysid=3D%s, rec= -sid=3D%s, rec-ip=3D%s, stored-sid=3D%s, stored-ip=3D%s", - i, - state_name(ks->state), - session_id_print(&session->session_id, &gc), - session_id_print(&sid, &gc), - print_link_socket_actual(from, &gc), - session_id_print(&ks->session_id_remote, &gc), - print_link_socket_actual(&ks->remote_addr, &gc)); + dmsg( + D_TLS_DEBUG, + "TLS: initial packet test, i=3D%d state=3D%s, mysid=3D%s, rec-= sid=3D%s, rec-ip=3D%s, stored-sid=3D%s, stored-ip=3D%s", + i, state_name(ks->state), session_id_print(&session->session_i= d, &gc), + session_id_print(&sid, &gc), print_link_socket_actual(from, &g= c), + session_id_print(&ks->session_id_remote, &gc), + print_link_socket_actual(&ks->remote_addr, &gc)); if (session_id_equal(&ks->session_id_remote, &sid)) /* found a match */ { if (i =3D=3D TM_LAME_DUCK) { - msg(D_TLS_ERRORS, - "TLS ERROR: received control packet with stale session= -id=3D%s", + msg(D_TLS_ERRORS, "TLS ERROR: received control packet with= stale session-id=3D%s", session_id_print(&sid, &gc)); goto error; } - dmsg(D_TLS_DEBUG, - "TLS: found match, session[%d], sid=3D%s", - i, session_id_print(&sid, &gc)); + dmsg(D_TLS_DEBUG, "TLS: found match, session[%d], sid=3D%s", i, + session_id_print(&sid, &gc)); break; } } @@ -3827,8 +3686,8 @@ goto error; } - if (!read_control_auth(buf, tls_session_get_tls_wrap(session, key_= id), from, - session->opt, true)) + if (!read_control_auth(buf, tls_session_get_tls_wrap(session, key_= id), from, session->opt, + true)) { goto error; } @@ -3836,13 +3695,7 @@ #ifdef ENABLE_MANAGEMENT if (management) { - management_set_state(management, - OPENVPN_STATE_AUTH, - NULL, - NULL, - NULL, - NULL, - NULL); + management_set_state(management, OPENVPN_STATE_AUTH, NULL, NUL= L, NULL, NULL, NULL); } #endif @@ -3852,10 +3705,8 @@ * * Without --tls-auth, we leave authentication entirely up to TLS. */ - msg(D_TLS_DEBUG_LOW, - "TLS: Initial packet from %s, sid=3D%s", - print_link_socket_actual(from, &gc), - session_id_print(&sid, &gc)); + msg(D_TLS_DEBUG_LOW, "TLS: Initial packet from %s, sid=3D%s", + print_link_socket_actual(from, &gc), session_id_print(&sid, &g= c)); do_burst =3D true; new_link =3D true; @@ -3872,11 +3723,8 @@ */ if (i !=3D TM_ACTIVE && i !=3D TM_INITIAL) { - msg(D_TLS_ERRORS, - "TLS Error: Unroutable control packet received from %s (si= =3D%d op=3D%s)", - print_link_socket_actual(from, &gc), - i, - packet_opcode_name(op)); + msg(D_TLS_ERRORS, "TLS Error: Unroutable control packet receiv= ed from %s (si=3D%d op=3D%s)", + print_link_socket_actual(from, &gc), i, packet_opcode_name= (op)); goto error; } @@ -3897,17 +3745,16 @@ */ if (op =3D=3D P_CONTROL_SOFT_RESET_V1 && ks->state >=3D S_GENERATE= D_KEYS) { - if (!read_control_auth(buf, tls_session_get_tls_wrap(session, = key_id), - from, session->opt, false)) + if (!read_control_auth(buf, tls_session_get_tls_wrap(session, = key_id), from, + session->opt, false)) { goto error; } key_state_soft_reset(session); - dmsg(D_TLS_DEBUG, - "TLS: received P_CONTROL_SOFT_RESET_V1 s=3D%d sid=3D%s", - i, session_id_print(&sid, &gc)); + dmsg(D_TLS_DEBUG, "TLS: received P_CONTROL_SOFT_RESET_V1 s=3D%= d sid=3D%s", i, + session_id_print(&sid, &gc)); } else { @@ -3928,8 +3775,8 @@ do_burst =3D true; } - if (!read_control_auth(buf, tls_session_get_tls_wrap(session, = key_id), - from, session->opt, initial_packet)) + if (!read_control_auth(buf, tls_session_get_tls_wrap(session, = key_id), from, + session->opt, initial_packet)) { /* if an initial packet in read_control_auth, we rather * error out than anything else */ @@ -3940,9 +3787,8 @@ goto error; } - dmsg(D_TLS_DEBUG, - "TLS: received control channel packet s#=3D%d sid=3D%s", - i, session_id_print(&sid, &gc)); + dmsg(D_TLS_DEBUG, "TLS: received control channel packet s#=3D%= d sid=3D%s", i, + session_id_print(&sid, &gc)); } } @@ -3994,9 +3840,8 @@ /* Check key_id */ if (ks->key_id !=3D key_id) { - msg(D_TLS_ERRORS, - "TLS ERROR: local/remote key IDs out of sync (%d/%d) ID: %s", - ks->key_id, key_id, print_key_id(multi, &gc)); + msg(D_TLS_ERRORS, "TLS ERROR: local/remote key IDs out of sync (%d= /%d) ID: %s", ks->key_id, + key_id, print_key_id(multi, &gc)); goto error; } @@ -4010,8 +3855,7 @@ if (!reliable_ack_read(&send_ack, buf, &session->session_id)) { - msg(D_TLS_ERRORS, - "TLS Error: reading acknowledgement record from packet"); + msg(D_TLS_ERRORS, "TLS Error: reading acknowledgement record f= rom packet"); goto error; } reliable_send_purge(ks->send_reliable, &send_ack); @@ -4034,14 +3878,14 @@ ASSERT(in); if (!buf_copy(in, buf)) { - msg(D_MULTI_DROPPED, - "Incoming control channel packet too big, drop= ping."); + msg(D_MULTI_DROPPED, "Incoming control channel pac= ket too big, dropping."); goto error; } reliable_mark_active_incoming(ks->rec_reliable, in, id= , op); } - /* Process outgoing acknowledgment for packet just receive= d, even if it's a replay */ + /* Process outgoing acknowledgment for packet just receive= d, even if it's a replay + */ reliable_ack_acknowledge_packet_id(ks->rec_ack, id); } } @@ -4090,8 +3934,7 @@ /* Choose the key with which to encrypt a data packet */ void -tls_pre_encrypt(struct tls_multi *multi, - struct buffer *buf, struct crypto_options **opt) +tls_pre_encrypt(struct tls_multi *multi, struct buffer *buf, struct crypto= _options **opt) { multi->save_ks =3D NULL; if (buf->len <=3D 0) @@ -4146,8 +3989,7 @@ ASSERT(ks); - peer =3D htonl(((P_DATA_V2 << P_OPCODE_SHIFT) | ks->key_id) << 24 - | (multi->peer_id & 0xFFFFFF)); + peer =3D htonl(((P_DATA_V2 << P_OPCODE_SHIFT) | ks->key_id) << 24 | (m= ulti->peer_id & 0xFFFFFF)); ASSERT(buf_write_prepend(buf, &peer, 4)); } @@ -4172,9 +4014,7 @@ */ bool -tls_send_payload(struct key_state *ks, - const uint8_t *data, - int size) +tls_send_payload(struct key_state *ks, const uint8_t *data, int size) { bool ret =3D false; @@ -4206,8 +4046,7 @@ } bool -tls_rec_payload(struct tls_multi *multi, - struct buffer *buf) +tls_rec_payload(struct tls_multi *multi, struct buffer *buf) { bool ret =3D false; @@ -4260,8 +4099,7 @@ } void -show_available_tls_ciphers(const char *cipher_list, - const char *cipher_list_tls13, +show_available_tls_ciphers(const char *cipher_list, const char *cipher_lis= t_tls13, const char *tls_cert_profile) { printf("Available TLS Ciphers, listed in order of preference:\n"); @@ -4278,8 +4116,7 @@ printf("\n" "Be aware that that whether a cipher suite in this list can act= ually work\n" "depends on the specific setup of both peers. See the man page = entries of\n" - "--tls-cipher and --show-tls for more details.\n\n" - ); + "--tls-cipher and --show-tls for more details.\n\n"); } /* @@ -4385,7 +4222,8 @@ } if (flags & PD_VERBOSE) { - buf_printf(&out, " tls_crypt_hmac=3D%s", format_hex(tls_crypt_= hmac, TLS_CRYPT_TAG_SIZE, 0, gc)); + buf_printf(&out, " tls_crypt_hmac=3D%s", + format_hex(tls_crypt_hmac, TLS_CRYPT_TAG_SIZE, 0, g= c)); } /* * Remainder is encrypted and optional wKc diff --git a/src/openvpn/ssl.h b/src/openvpn/ssl.h index b952cd9..976808d 100644 --- a/src/openvpn/ssl.h +++ b/src/openvpn/ssl.h @@ -57,9 +57,10 @@ /* * Various timeouts */ -#define TLS_MULTI_REFRESH 15 /* call tls_multi_process once every n sec= onds */ -#define TLS_MULTI_HORIZON 2 /* call tls_multi_process frequently for n= seconds after - * every packet sent/received action */ +#define TLS_MULTI_REFRESH 15 /* call tls_multi_process once every n second= s */ +#define TLS_MULTI_HORIZON = \ + 2 /* call tls_multi_process frequently for n se= conds after \ + * every packet sent/received action */ /* * Buffer sizes (also see mtu.h). @@ -77,49 +78,49 @@ * as reserved for this reason */ /** Support P_DATA_V2 */ -#define IV_PROTO_DATA_V2 (1<<1) +#define IV_PROTO_DATA_V2 (1 << 1) /** Assume client will send a push request and server does not need * to wait for a push-request to send a push-reply */ -#define IV_PROTO_REQUEST_PUSH (1<<2) +#define IV_PROTO_REQUEST_PUSH (1 << 2) /** Supports key derivation via TLS key material exporter [RFC5705] */ -#define IV_PROTO_TLS_KEY_EXPORT (1<<3) +#define IV_PROTO_TLS_KEY_EXPORT (1 << 3) /** Supports signaling keywords with AUTH_PENDING, e.g. timeout=3Dxy */ -#define IV_PROTO_AUTH_PENDING_KW (1<<4) +#define IV_PROTO_AUTH_PENDING_KW (1 << 4) /** Support doing NCP in P2P mode. This mode works by both peers looking at * each other's IV_ variables and deterministically deciding both on the s= ame * result. */ -#define IV_PROTO_NCP_P2P (1<<5) +#define IV_PROTO_NCP_P2P (1 << 5) /** Supports the --dns option introduced in version 2.6. Not sent anymore.= */ -#define IV_PROTO_DNS_OPTION (1<<6) +#define IV_PROTO_DNS_OPTION (1 << 6) /** Support for explicit exit notify via control channel * This also includes support for the protocol-flags pushed option */ -#define IV_PROTO_CC_EXIT_NOTIFY (1<<7) +#define IV_PROTO_CC_EXIT_NOTIFY (1 << 7) /** Support for AUTH_FAIL,TEMP messages */ -#define IV_PROTO_AUTH_FAIL_TEMP (1<<8) +#define IV_PROTO_AUTH_FAIL_TEMP (1 << 8) /** Support to dynamic tls-crypt (renegotiation with TLS-EKM derived tls-c= rypt key) */ -#define IV_PROTO_DYN_TLS_CRYPT (1<<9) +#define IV_PROTO_DYN_TLS_CRYPT (1 << 9) /** Support the extended packet id and epoch format for data channel packe= ts */ -#define IV_PROTO_DATA_EPOCH (1<<10) +#define IV_PROTO_DATA_EPOCH (1 << 10) /** Supports the --dns option after all the incompatible changes */ -#define IV_PROTO_DNS_OPTION_V2 (1<<11) +#define IV_PROTO_DNS_OPTION_V2 (1 << 11) /** Supports push-update */ -#define IV_PROTO_PUSH_UPDATE (1<<12) +#define IV_PROTO_PUSH_UPDATE (1 << 12) /* Default field in X509 to be username */ #define X509_USERNAME_FIELD_DEFAULT "CN" -#define KEY_METHOD_2 2 +#define KEY_METHOD_2 2 /* key method taken from lower 4 bits */ #define KEY_METHOD_MASK 0x0F @@ -206,9 +207,7 @@ * Used to verify compatibility of local and remote option * sets. */ -void tls_multi_init_set_options(struct tls_multi *multi, - const char *local, - const char *remote); +void tls_multi_init_set_options(struct tls_multi *multi, const char *local= , const char *remote); /** * Cleanup a \c tls_multi structure and free associated memory @@ -228,9 +227,9 @@ /** @} addtogroup control_processor */ -#define TLSMP_INACTIVE 0 -#define TLSMP_ACTIVE 1 -#define TLSMP_KILL 2 +#define TLSMP_INACTIVE 0 +#define TLSMP_ACTIVE 1 +#define TLSMP_KILL 2 #define TLSMP_RECONNECT 3 /* @@ -239,11 +238,9 @@ * Basically decides if we should call tls_process for * the active or untrusted sessions. */ -int tls_multi_process(struct tls_multi *multi, - struct buffer *to_link, +int tls_multi_process(struct tls_multi *multi, struct buffer *to_link, struct link_socket_actual **to_link_addr, - struct link_socket_info *to_link_socket_info, - interval_t *wakeup); + struct link_socket_info *to_link_socket_info, interv= al_t *wakeup); /*************************************************************************= */ @@ -299,11 +296,8 @@ * @li False if the packet is a data channel packet, or if an error * occurred during processing of a control channel packet. */ -bool tls_pre_decrypt(struct tls_multi *multi, - const struct link_socket_actual *from, - struct buffer *buf, - struct crypto_options **opt, - bool floated, +bool tls_pre_decrypt(struct tls_multi *multi, const struct link_socket_act= ual *from, + struct buffer *buf, struct crypto_options **opt, bool= floated, const uint8_t **ad_start); @@ -325,8 +319,7 @@ * @param buf - The buffer containing the outgoing packet. * @param opt - Returns a crypto options structure with the security param= eters. */ -void tls_pre_encrypt(struct tls_multi *multi, - struct buffer *buf, struct crypto_options **opt); +void tls_pre_encrypt(struct tls_multi *multi, struct buffer *buf, struct c= rypto_options **opt); /** * Selects the primary encryption that should be used to encrypt data of an @@ -351,8 +344,7 @@ * * @ingroup data_crypto */ -void -tls_prepend_opcode_v1(const struct tls_multi *multi, struct buffer *buf); +void tls_prepend_opcode_v1(const struct tls_multi *multi, struct buffer *b= uf); /** * Prepend an OpenVPN data channel P_DATA_V2 header to the packet. The @@ -370,8 +362,7 @@ * * @ingroup data_crypto */ -void -tls_prepend_opcode_v2(const struct tls_multi *multi, struct buffer *buf); +void tls_prepend_opcode_v2(const struct tls_multi *multi, struct buffer *b= uf); /** * Perform some accounting for the key state used. @@ -435,15 +426,12 @@ /* * Send a payload over the TLS control channel */ -bool tls_send_payload(struct key_state *ks, - const uint8_t *data, - int size); +bool tls_send_payload(struct key_state *ks, const uint8_t *data, int size); /* * Receive a payload through the TLS control channel */ -bool tls_rec_payload(struct tls_multi *multi, - struct buffer *buf); +bool tls_rec_payload(struct tls_multi *multi, struct buffer *buf); /** * Updates remote address in TLS sessions. @@ -451,8 +439,7 @@ * @param multi - Tunnel to update * @param addr - new address */ -void tls_update_remote_addr(struct tls_multi *multi, - const struct link_socket_actual *addr); +void tls_update_remote_addr(struct tls_multi *multi, const struct link_soc= ket_actual *addr); /** * Update TLS session crypto parameters (cipher and auth) and derive data @@ -472,12 +459,9 @@ * * @return true if updating succeeded or keys are already generated, false= otherwise. */ -bool tls_session_update_crypto_params(struct tls_multi *multi, - struct tls_session *session, - struct options *options, - struct frame *frame, - struct frame *frame_fragment, - struct link_socket_info *lsi, +bool tls_session_update_crypto_params(struct tls_multi *multi, struct tls_= session *session, + struct options *options, struct fram= e *frame, + struct frame *frame_fragment, struct= link_socket_info *lsi, dco_context_t *dco); /* @@ -536,14 +520,12 @@ * protocol_dump() flags */ #define PD_TLS_AUTH_HMAC_SIZE_MASK 0xFF -#define PD_SHOW_DATA (1<<8) -#define PD_TLS (1<<9) -#define PD_VERBOSE (1<<10) -#define PD_TLS_CRYPT (1<<11) +#define PD_SHOW_DATA (1 << 8) +#define PD_TLS (1 << 9) +#define PD_VERBOSE (1 << 10) +#define PD_TLS_CRYPT (1 << 11) -const char *protocol_dump(struct buffer *buffer, - unsigned int flags, - struct gc_arena *gc); +const char *protocol_dump(struct buffer *buffer, unsigned int flags, struc= t gc_arena *gc); /* * debugging code @@ -569,10 +551,8 @@ * @param cipher_list_tls13 list of allowed TLS 1.3+ cipher, or NULL * @param tls_cert_profile TLS certificate crypto profile name. */ -void -show_available_tls_ciphers(const char *cipher_list, - const char *cipher_list_tls13, - const char *tls_cert_profile); +void show_available_tls_ciphers(const char *cipher_list, const char *ciphe= r_list_tls13, + const char *tls_cert_profile); /** @@ -581,25 +561,19 @@ * This erases the source material used to generate the data channel keys,= and * can thus be called only once per session. */ -bool -tls_session_generate_data_channel_keys(struct tls_multi *multi, - struct tls_session *session); +bool tls_session_generate_data_channel_keys(struct tls_multi *multi, struc= t tls_session *session); -void -tls_session_soft_reset(struct tls_multi *multi); +void tls_session_soft_reset(struct tls_multi *multi); /** * Load ovpn.xkey provider used for external key signing */ -void -load_xkey_provider(void); +void load_xkey_provider(void); /* Special method to skip the three way handshake RESET stages. This is * used by the HMAC code when seeing a packet that matches the previous * HMAC based stateless server state */ -bool -session_skip_to_pre_start(struct tls_session *session, - struct tls_pre_decrypt_state *state, - struct link_socket_actual *from); +bool session_skip_to_pre_start(struct tls_session *session, struct tls_pre= _decrypt_state *state, + struct link_socket_actual *from); #endif /* ifndef OPENVPN_SSL_H */ diff --git a/src/openvpn/ssl_backend.h b/src/openvpn/ssl_backend.h index 8023fed..da3e1e1 100644 --- a/src/openvpn/ssl_backend.h +++ b/src/openvpn/ssl_backend.h @@ -101,11 +101,11 @@ * if a parse error should be flagged. */ #define TLS_VER_BAD -1 -#define TLS_VER_UNSPEC 0 /* default */ -#define TLS_VER_1_0 1 -#define TLS_VER_1_1 2 -#define TLS_VER_1_2 3 -#define TLS_VER_1_3 4 +#define TLS_VER_UNSPEC 0 /* default */ +#define TLS_VER_1_0 1 +#define TLS_VER_1_1 2 +#define TLS_VER_1_2 3 +#define TLS_VER_1_3 4 int tls_version_parse(const char *vstr, const char *extra); /** @@ -218,8 +218,7 @@ * of inline files. * @param dh_file_inline True if dh_file is an inline file. */ -void tls_ctx_load_dh_params(struct tls_root_ctx *ctx, const char *dh_file, - bool dh_file_inline); +void tls_ctx_load_dh_params(struct tls_root_ctx *ctx, const char *dh_file,= bool dh_file_inline); /** * Load Elliptic Curve Parameters, and load them into the library-specific @@ -228,8 +227,7 @@ * @param ctx TLS context to use * @param curve_name The name of the elliptic curve to load. */ -void tls_ctx_load_ecdh_params(struct tls_root_ctx *ctx, const char *curve_= name - ); +void tls_ctx_load_ecdh_params(struct tls_root_ctx *ctx, const char *curve_= name); /** * Load PKCS #12 file for key, cert and (optionally) CA certs, and add to @@ -246,8 +244,8 @@ * @return 1 if an error occurred, 0 if parsing was * successful. */ -int tls_ctx_load_pkcs12(struct tls_root_ctx *ctx, const char *pkcs12_file, - bool pkcs12_file_inline, bool load_ca_file); +int tls_ctx_load_pkcs12(struct tls_root_ctx *ctx, const char *pkcs12_file,= bool pkcs12_file_inline, + bool load_ca_file); /** * Use Windows cryptoapi for key and cert, and add to library-specific TLS @@ -271,8 +269,7 @@ * of inline files. * @param cert_file_inline True if cert_file is an inline file. */ -void tls_ctx_load_cert_file(struct tls_root_ctx *ctx, const char *cert_fil= e, - bool cert_file_inline); +void tls_ctx_load_cert_file(struct tls_root_ctx *ctx, const char *cert_fil= e, bool cert_file_inline); /** * Load private key file into the given TLS context. @@ -318,8 +315,8 @@ * connection and should use the CA for verif= ying * client certificates */ -void tls_ctx_load_ca(struct tls_root_ctx *ctx, const char *ca_file, - bool ca_file_inline, const char *ca_path, bool tls_se= rver); +void tls_ctx_load_ca(struct tls_root_ctx *ctx, const char *ca_file, bool c= a_file_inline, + const char *ca_path, bool tls_server); /** * Load extra certificate authority certificates from the given file or pa= th. @@ -334,8 +331,7 @@ * @param extra_certs_file_inline True if extra_certs_file is an inl= ine * file. */ -void tls_ctx_load_extra_certs(struct tls_root_ctx *ctx, - const char *extra_certs_file, +void tls_ctx_load_extra_certs(struct tls_root_ctx *ctx, const char *extra_= certs_file, bool extra_certs_file_inline); #ifdef ENABLE_CRYPTO_MBEDTLS @@ -364,15 +360,14 @@ * @param is_server Initialise a server? * @param session The session associated with the given key_state */ -void key_state_ssl_init(struct key_state_ssl *ks_ssl, - const struct tls_root_ctx *ssl_ctx, bool is_server= , struct tls_session *session); +void key_state_ssl_init(struct key_state_ssl *ks_ssl, const struct tls_roo= t_ctx *ssl_ctx, + bool is_server, struct tls_session *session); /** * Sets a TLS session to be shutdown state, so the TLS library will genera= te * a shutdown alert. */ -void -key_state_ssl_shutdown(struct key_state_ssl *ks_ssl); +void key_state_ssl_shutdown(struct key_state_ssl *ks_ssl); /** * Free the SSL channel part of the given key state. @@ -389,12 +384,12 @@ * an array containing the inline CRL. * @param crl_inline True if crl_file is an inline CRL. */ -void backend_tls_ctx_reload_crl(struct tls_root_ctx *ssl_ctx, - const char *crl_file, bool crl_inline); +void backend_tls_ctx_reload_crl(struct tls_root_ctx *ssl_ctx, const char *= crl_file, + bool crl_inline); -#define EXPORT_KEY_DATA_LABEL "EXPORTER-OpenVPN-datakeys" -#define EXPORT_P2P_PEERID_LABEL "EXPORTER-OpenVPN-p2p-peerid" -#define EXPORT_DYNAMIC_TLS_CRYPT_LABEL "EXPORTER-OpenVPN-dynamic-tls-cryp= t" +#define EXPORT_KEY_DATA_LABEL "EXPORTER-OpenVPN-datakeys" +#define EXPORT_P2P_PEERID_LABEL "EXPORTER-OpenVPN-p2p-peerid" +#define EXPORT_DYNAMIC_TLS_CRYPT_LABEL "EXPORTER-OpenVPN-dynamic-tls-crypt" /** * Keying Material Exporters [RFC 5705] allows additional keying material = to be * derived from existing TLS channel. This exported keying material can th= en be @@ -407,10 +402,8 @@ * @param ekm_size The size of ekm, in bytes * @returns true if exporting succeeded, false otherwise */ -bool -key_state_export_keying_material(struct tls_session *session, - const char *label, size_t label_size, - void *ekm, size_t ekm_size); +bool key_state_export_keying_material(struct tls_session *session, const c= har *label, + size_t label_size, void *ekm, size_t= ekm_size); /*************************************************************************= */ /** @addtogroup control_tls @@ -453,8 +446,7 @@ * again later to retry. * - \c -1: An error occurred. */ -int key_state_write_plaintext_const(struct key_state_ssl *ks_ssl, - const uint8_t *data, int len); +int key_state_write_plaintext_const(struct key_state_ssl *ks_ssl, const ui= nt8_t *data, int len); /** * Extract ciphertext data from the TLS module. @@ -499,8 +491,7 @@ * again later to retry. * - \c -1: An error occurred. */ -int key_state_write_ciphertext(struct key_state_ssl *ks_ssl, - struct buffer *buf); +int key_state_write_ciphertext(struct key_state_ssl *ks_ssl, struct buffer= *buf); /** * Extract plaintext data from the TLS module. @@ -548,10 +539,8 @@ * @param tls13 Select if <=3DTLS1.2 or TLS1.3+ ciphers * should be shown */ -void -show_available_tls_ciphers_list(const char *cipher_list, - const char *tls_cert_profile, - bool tls13); +void show_available_tls_ciphers_list(const char *cipher_list, const char *= tls_cert_profile, + bool tls13); /** * Show the available elliptic curves in the crypto library diff --git a/src/openvpn/ssl_common.h b/src/openvpn/ssl_common.h index 1fdc187..cd5293a 100644 --- a/src/openvpn/ssl_common.h +++ b/src/openvpn/ssl_common.h @@ -117,15 +117,16 @@ * \ref key_generation "data channel key generation". * @ingroup control_processor */ -struct key_source { - uint8_t pre_master[48]; /**< Random used for master secret - * generation, provided only by client - * OpenVPN peer. */ - uint8_t random1[32]; /**< Seed used for master secret - * generation, provided by both client - * and server. */ - uint8_t random2[32]; /**< Seed used for key expansion, provided - * by both client and server. */ +struct key_source +{ + uint8_t pre_master[48]; /**< Random used for master secret + * generation, provided only by client + * OpenVPN peer. */ + uint8_t random1[32]; /**< Seed used for master secret + * generation, provided by both client + * and server. */ + uint8_t random2[32]; /**< Seed used for key expansion, provided + * by both client and server. */ }; =20 @@ -134,9 +135,10 @@ * 2 \ref key_generation "data channel key generation". * @ingroup control_processor */ -struct key_source2 { - struct key_source client; /**< Random provided by client. */ - struct key_source server; /**< Random provided by server. */ +struct key_source2 +{ + struct key_source client; /**< Random provided by client. */ + struct key_source server; /**< Random provided by server. */ }; @@ -147,15 +149,16 @@ * being set to KS_AUTH_TRUE or KS_AUTH_FALSE * Only KS_AUTH_TRUE is fully authenticated */ -enum ks_auth_state { - KS_AUTH_FALSE, /**< Key state is not authenticated */ - KS_AUTH_DEFERRED, /**< Key state authentication is being defer= red, - * by async auth */ - KS_AUTH_TRUE /**< Key state is authenticated. TLS and use= r/pass - * succeeded. This includes AUTH_PENDING/OOB - * authentication as those hold the - * connection artificially in KS_AUTH_DEFERR= ED - */ +enum ks_auth_state +{ + KS_AUTH_FALSE, /**< Key state is not authenticated */ + KS_AUTH_DEFERRED, /**< Key state authentication is being deferred, + * by async auth */ + KS_AUTH_TRUE /**< Key state is authenticated. TLS and user/pass + * succeeded. This includes AUTH_PENDING/OOB + * authentication as those hold the + * connection artificially in KS_AUTH_DEFERRED + */ }; struct auth_deferred_status @@ -168,14 +171,16 @@ /* key_state_test_auth_control_file return values, these specify the * current status of a deferred authentication */ -enum auth_deferred_result { - ACF_PENDING, /**< deferred auth still pending */ - ACF_SUCCEEDED, /**< deferred auth has suceeded */ - ACF_DISABLED, /**< deferred auth is not used */ - ACF_FAILED /**< deferred auth has failed */ +enum auth_deferred_result +{ + ACF_PENDING, /**< deferred auth still pending */ + ACF_SUCCEEDED, /**< deferred auth has suceeded */ + ACF_DISABLED, /**< deferred auth is not used */ + ACF_FAILED /**< deferred auth has failed */ }; -enum dco_key_status { +enum dco_key_status +{ DCO_NOT_INSTALLED, DCO_INSTALLED_PRIMARY, DCO_INSTALLED_SECONDARY @@ -219,34 +224,34 @@ struct key_state_ssl ks_ssl; /* contains SSL object and BIOs for the c= ontrol channel */ - time_t initial; /* when we created this session */ - time_t established; /* when our state went S_ACTIVE */ - time_t must_negotiate; /* key negotiation times out if not finish= ed before this time */ - time_t must_die; /* this object is destroyed at this time */ - time_t peer_last_packet; /* Last time we received a packet in this = control session */ + time_t initial; /* when we created this session */ + time_t established; /* when our state went S_ACTIVE */ + time_t must_negotiate; /* key negotiation times out if not finis= hed before this time */ + time_t must_die; /* this object is destroyed at this time = */ + time_t peer_last_packet; /* Last time we received a packet in this= control session */ - int initial_opcode; /* our initial P_ opcode */ - struct session_id session_id_remote; /* peer's random session ID */ + int initial_opcode; /* our initial P_ opcode */ + struct session_id session_id_remote; /* peer's random session ID */ struct link_socket_actual remote_addr; /* peer's IP addr */ - struct crypto_options crypto_options;/* data channel crypto options */ + struct crypto_options crypto_options; /* data channel crypto options = */ - struct key_source2 *key_src; /* source entropy for key expansion= */ + struct key_source2 *key_src; /* source entropy for key expan= sion */ =20 struct buffer plaintext_read_buf; struct buffer plaintext_write_buf; struct buffer ack_write_buf; struct reliable *send_reliable; /* holds a copy of outgoing packets un= til ACK received */ - struct reliable *rec_reliable; /* order incoming ciphertext packets be= fore we pass to TLS */ - struct reliable_ack *rec_ack; /* buffers all packet IDs we want to ACK= back to sender */ - struct reliable_ack *lru_acks; /* keeps the most recently acked packag= es*/ + struct reliable *rec_reliable; /* order incoming ciphertext packets b= efore we pass to TLS */ + struct reliable_ack *rec_ack; /* buffers all packet IDs we want to A= CK back to sender */ + struct reliable_ack *lru_acks; /* keeps the most recently acked packa= ges*/ /** Holds outgoing message for the control channel until ks->state rea= ches * S_ACTIVE */ struct buffer_list *paybuf; - counter_type n_bytes; /* how many bytes sent/recvd sinc= e last key exchange */ - counter_type n_packets; /* how many packets sent/recvd si= nce last key exchange */ + counter_type n_bytes; /* how many bytes sent/recvd since last key ex= change */ + counter_type n_packets; /* how many packets sent/recvd since last key = exchange */ /* * If bad username/password, TLS connection will come up but 'authenti= cated' will be false. @@ -269,19 +274,20 @@ /** Control channel wrapping (--tls-auth/--tls-crypt) context */ struct tls_wrap_ctx { - enum { - TLS_WRAP_NONE =3D 0, /**< No control channel wrapping */ - TLS_WRAP_AUTH, /**< Control channel authentication */ - TLS_WRAP_CRYPT, /**< Control channel encryption and authentication= */ - } mode; /**< Control channel wrapping mode */ - struct crypto_options opt; /**< Crypto state */ - struct buffer work; /**< Work buffer (only for --tls-crypt) */ - struct key_ctx tls_crypt_v2_server_key; /**< Decrypts client keys */ - const struct buffer *tls_crypt_v2_wkc; /**< Wrapped client key, - * sent to server */ - struct buffer tls_crypt_v2_metadata; /**< Received from client */ - bool cleanup_key_ctx; /**< opt.key_ctx_bi is owned = by - * this context */ + enum + { + TLS_WRAP_NONE =3D 0, /**< No control channel wrap= ping */ + TLS_WRAP_AUTH, /**< Control channel authentic= ation */ + TLS_WRAP_CRYPT, /**< Control channel encryptio= n and authentication */ + } mode; /**< Control channel wrapping = mode */ + struct crypto_options opt; /**< Crypto state */ + struct buffer work; /**< Work buffer (only for --t= ls-crypt) */ + struct key_ctx tls_crypt_v2_server_key; /**< Decrypts client keys */ + const struct buffer *tls_crypt_v2_wkc; /**< Wrapped client key, + * sent to server */ + struct buffer tls_crypt_v2_metadata; /**< Received from client */ + bool cleanup_key_ctx; /**< opt.key_ctx_bi is owned by + * this context */ /** original key data to be xored in to the key for dynamic tls-crypt. * * We keep the original key data to ensure that the newly generated key @@ -363,8 +369,8 @@ /* struct crypto_option flags */ unsigned int crypto_flags; - int replay_window; /* --replay-window parm */ - int replay_time; /* --replay-window parm */ + int replay_window; /* --replay-window parm */ + int replay_time; /* --replay-window parm */ const char *config_ciphername; const char *config_ncp_ciphers; @@ -392,9 +398,9 @@ const char *auth_user_pass_file; bool auth_user_pass_file_inline; - bool auth_token_generate; /**< Generate auth-tokens on successful - * user/pass auth,seet via - * options->auth_token_generate. */ + bool auth_token_generate; /**< Generate auth-tokens on successful + * user/pass auth,seet via + * options->auth_token_generate. */ bool auth_token_call_auth; /**< always call normal authentication */ unsigned int auth_token_lifetime; unsigned int auth_token_renewal; @@ -415,17 +421,17 @@ #endif /* configuration file SSL-related boolean and low-permutation options = */ -#define SSLF_CLIENT_CERT_NOT_REQUIRED (1<<0) -#define SSLF_CLIENT_CERT_OPTIONAL (1<<1) -#define SSLF_USERNAME_AS_COMMON_NAME (1<<2) -#define SSLF_AUTH_USER_PASS_OPTIONAL (1<<3) -#define SSLF_OPT_VERIFY (1<<4) -#define SSLF_CRL_VERIFY_DIR (1<<5) +#define SSLF_CLIENT_CERT_NOT_REQUIRED (1 << 0) +#define SSLF_CLIENT_CERT_OPTIONAL (1 << 1) +#define SSLF_USERNAME_AS_COMMON_NAME (1 << 2) +#define SSLF_AUTH_USER_PASS_OPTIONAL (1 << 3) +#define SSLF_OPT_VERIFY (1 << 4) +#define SSLF_CRL_VERIFY_DIR (1 << 5) #define SSLF_TLS_VERSION_MIN_SHIFT 6 -#define SSLF_TLS_VERSION_MIN_MASK 0xF /* (uses bit positions 6 to 9) = */ +#define SSLF_TLS_VERSION_MIN_MASK 0xF /* (uses bit positions 6 to 9) */ #define SSLF_TLS_VERSION_MAX_SHIFT 10 -#define SSLF_TLS_VERSION_MAX_MASK 0xF /* (uses bit positions 10 to 13= ) */ -#define SSLF_TLS_DEBUG_ENABLED (1<<14) +#define SSLF_TLS_VERSION_MAX_MASK 0xF /* (uses bit positions 10 to 13)= */ +#define SSLF_TLS_DEBUG_ENABLED (1 << 14) unsigned int ssl_flags; #ifdef ENABLE_MANAGEMENT @@ -456,10 +462,11 @@ * This is the index of \c tls_session.key * * @{ */ -#define KS_PRIMARY 0 /**< Primary %key state index. */ -#define KS_LAME_DUCK 1 /**< %Key state index that will retire - * soon. */ -#define KS_SIZE 2 /**< Size of the \c tls_session.key array.= */ +#define KS_PRIMARY 0 /**< Primary %key state index. */ +#define KS_LAME_DUCK \ + 1 /**< %Key state index that will retire \ + * soon. */ +#define KS_SIZE 2 /**< Size of the \c tls_session.key array. */ /** @} name Index of key_state objects within a tls_session structure */ /** @} addtogroup control_processor */ @@ -494,7 +501,7 @@ * tls_wrap_reneg.mode is TLS_WRAP_CRYPT, otherwise ignore it */ struct tls_wrap_ctx tls_wrap_reneg; - int initial_opcode; /* our initial P_ opcode */ + int initial_opcode; /* our initial P_ opcode */ struct session_id session_id; /* our random session ID */ /** @@ -510,7 +517,7 @@ struct cert_hash_set *cert_hash_set; - bool verified; /* true if peer certificate was verified a= gainst CA */ + bool verified; /* true if peer certificate was verified against CA */ /* not-yet-authenticated incoming client */ struct link_socket_actual untrusted_addr; @@ -535,12 +542,14 @@ * is being negotiated. * * @{ */ -#define TM_ACTIVE 0 /**< Active \c tls_session. */ -#define TM_INITIAL 1 /**< As yet un-trusted \c tls_session - * being negotiated. */ -#define TM_LAME_DUCK 2 /**< Old \c tls_session. */ -#define TM_SIZE 3 /**< Size of the \c tls_multi.session - * array. */ +#define TM_ACTIVE 0 /**< Active \c tls_session. */ +#define TM_INITIAL \ + 1 /**< As yet un-trusted \c tls_session \ + * being negotiated. */ +#define TM_LAME_DUCK 2 /**< Old \c tls_session. */ +#define TM_SIZE \ + 3 /**< Size of the \c tls_multi.session \ + * array. */ /** @} name Index of tls_session objects within a tls_multi structure */ /** @} addtogroup control_processor */ @@ -612,7 +621,7 @@ * used by tls_pre_encrypt to communicate the encrypt key * to tls_post_encrypt() */ - struct key_state *save_ks; /* temporary pointer used between pre/post= routines */ + struct key_state *save_ks; /* temporary pointer used between pre/post = routines */ /* * Used to return outgoing address from @@ -620,8 +629,8 @@ */ struct link_socket_actual to_link_addr; - int n_sessions; /**< Number of sessions negotiated thus - * far. */ + int n_sessions; /**< Number of sessions negotiated thus + * far. */ enum multi_status multi_state; /* @@ -692,8 +701,8 @@ uint32_t peer_id; bool use_peer_id; - char *remote_ciphername; /**< cipher specified in peer's config fil= e */ - bool remote_usescomp; /**< remote announced comp-lzo in OCC stri= ng */ + char *remote_ciphername; /**< cipher specified in peer's config file */ + bool remote_usescomp; /**< remote announced comp-lzo in OCC string = */ /* * Our session objects. diff --git a/src/openvpn/ssl_mbedtls.c b/src/openvpn/ssl_mbedtls.c index 22e777b..635b53c 100644 --- a/src/openvpn/ssl_mbedtls.c +++ b/src/openvpn/ssl_mbedtls.c @@ -52,35 +52,28 @@ #include #if MBEDTLS_VERSION_NUMBER >=3D 0x02040000 - #include +#include #else - #include +#include #endif #include #include -static const mbedtls_x509_crt_profile openvpn_x509_crt_profile_legacy =3D -{ +static const mbedtls_x509_crt_profile openvpn_x509_crt_profile_legacy =3D { /* Hashes from SHA-1 and above */ - MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA1 ) - |MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_RIPEMD160 ) - |MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA224 ) - |MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA256 ) - |MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA384 ) - |MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA512 ), + MBEDTLS_X509_ID_FLAG(MBEDTLS_MD_SHA1) | MBEDTLS_X509_ID_FLAG(MBEDTLS_M= D_RIPEMD160) + | MBEDTLS_X509_ID_FLAG(MBEDTLS_MD_SHA224) | MBEDTLS_X509_ID_FLAG(M= BEDTLS_MD_SHA256) + | MBEDTLS_X509_ID_FLAG(MBEDTLS_MD_SHA384) | MBEDTLS_X509_ID_FLAG(M= BEDTLS_MD_SHA512), 0xFFFFFFF, /* Any PK alg */ 0xFFFFFFF, /* Any curve */ 1024, /* RSA-1024 and larger */ }; -static const mbedtls_x509_crt_profile openvpn_x509_crt_profile_preferred = =3D -{ +static const mbedtls_x509_crt_profile openvpn_x509_crt_profile_preferred = =3D { /* SHA-2 and above */ - MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA224 ) - |MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA256 ) - |MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA384 ) - |MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA512 ), + MBEDTLS_X509_ID_FLAG(MBEDTLS_MD_SHA224) | MBEDTLS_X509_ID_FLAG(MBEDTLS= _MD_SHA256) + | MBEDTLS_X509_ID_FLAG(MBEDTLS_MD_SHA384) | MBEDTLS_X509_ID_FLAG(M= BEDTLS_MD_SHA512), 0xFFFFFFF, /* Any PK alg */ 0xFFFFFFF, /* Any curve */ 2048, /* RSA-2048 and larger */ @@ -184,9 +177,8 @@ * Mbed TLS stores this callback in the mbedtls_ssl_config struct and it * is used in the mbedtls_ssl_contexts set up from that config. */ int -mbedtls_ssl_export_keys_cb(void *p_expkey, const unsigned char *ms, - const unsigned char *kb, size_t maclen, - size_t keylen, size_t ivlen, +mbedtls_ssl_export_keys_cb(void *p_expkey, const unsigned char *ms, const = unsigned char *kb, + size_t maclen, size_t keylen, size_t ivlen, const unsigned char client_random[32], const unsigned char server_random[32], mbedtls_tls_prf_types tls_prf_type) @@ -195,8 +187,8 @@ struct key_state_ssl *ks_ssl =3D &session->key[KS_PRIMARY].ks_ssl; struct tls_key_cache *cache =3D &ks_ssl->tls_key_cache; - static_assert(sizeof(ks_ssl->ctx->session->master) - =3D=3D sizeof(cache->master_secret), "master size mismat= ch"); + static_assert(sizeof(ks_ssl->ctx->session->master) =3D=3D sizeof(cache= ->master_secret), + "master size mismatch"); memcpy(cache->client_server_random, client_random, 32); memcpy(cache->client_server_random + 32, server_random, 32); @@ -218,10 +210,8 @@ * mbedtls_ssl_config. It is placed in the mbedtls_ssl_context after it * has been set up. */ void -mbedtls_ssl_export_keys_cb(void *p_expkey, - mbedtls_ssl_key_export_type type, - const unsigned char *secret, - size_t secret_len, +mbedtls_ssl_export_keys_cb(void *p_expkey, mbedtls_ssl_key_export_type typ= e, + const unsigned char *secret, size_t secret_len, const unsigned char client_random[32], const unsigned char server_random[32], mbedtls_tls_prf_types tls_prf_type) @@ -241,8 +231,7 @@ * a different value, something is wrong with mbed TLS. */ if (secret_len !=3D sizeof(cache->master_secret)) { - msg(M_FATAL, - "ERROR: Incorrect TLS 1.2 master secret length: Got %zu, expec= ted %zu", + msg(M_FATAL, "ERROR: Incorrect TLS 1.2 master secret length: Got %= zu, expected %zu", secret_len, sizeof(cache->master_secret)); } @@ -257,8 +246,7 @@ bool -key_state_export_keying_material(struct tls_session *session, - const char *label, size_t label_size, +key_state_export_keying_material(struct tls_session *session, const char *= label, size_t label_size, void *ekm, size_t ekm_size) { ASSERT(strlen(label) =3D=3D label_size); @@ -267,7 +255,8 @@ /* Our version of mbed TLS has a built-in TLS-Exporter. */ mbedtls_ssl_context *ctx =3D session->key[KS_PRIMARY].ks_ssl.ctx; - if (mbed_ok(mbedtls_ssl_export_keying_material(ctx, ekm, ekm_size, lab= el, label_size, NULL, 0, 0))) + if (mbed_ok( + mbedtls_ssl_export_keying_material(ctx, ekm, ekm_size, label, = label_size, NULL, 0, 0))) { return true; } @@ -287,10 +276,8 @@ } int ret =3D mbedtls_ssl_tls_prf(cache->tls_prf_type, cache->master_sec= ret, - sizeof(cache->master_secret), - label, cache->client_server_random, - sizeof(cache->client_server_random), - ekm, ekm_size); + sizeof(cache->master_secret), label, cac= he->client_server_random, + sizeof(cache->client_server_random), ekm= , ekm_size); if (mbed_ok(ret)) { @@ -301,7 +288,7 @@ secure_memzero(ekm, session->opt->ekm_size); return false; } -#endif /* defined(MBEDTLS_SSL_KEYING_MATERIAL_EXPORT) */ +#endif /* defined(MBEDTLS_SSL_KEYING_MATERIAL_EXPORT) */ } bool @@ -324,7 +311,8 @@ if (0 !=3D strcmp(cipher_name, pair->iana_name)) { /* Deprecated name found, notify user */ - msg(M_WARN, "Deprecated cipher suite name '%s', please use IANA na= me '%s'", pair->openssl_name, pair->iana_name); + msg(M_WARN, "Deprecated cipher suite name '%s', please use IANA na= me '%s'", + pair->openssl_name, pair->iana_name); } return pair->iana_name; @@ -339,8 +327,10 @@ return; } - msg(M_WARN, "mbed TLS does not support setting tls-ciphersuites. " - "Ignoring TLS 1.3 cipher list: %s", ciphers); + msg(M_WARN, + "mbed TLS does not support setting tls-ciphersuites. " + "Ignoring TLS 1.3 cipher list: %s", + ciphers); } void @@ -359,7 +349,7 @@ int cipher_count =3D get_num_elements(ciphers, ':'); /* Allocate an array for them */ - ALLOC_ARRAY_CLEAR(ctx->allowed_ciphers, int, cipher_count+1) + ALLOC_ARRAY_CLEAR(ctx->allowed_ciphers, int, cipher_count + 1) /* Parse allowed ciphers, getting IDs */ int i =3D 0; @@ -368,8 +358,7 @@ token =3D strtok(tmp_ciphers, ":"); while (token) { - ctx->allowed_ciphers[i] =3D mbedtls_ssl_get_ciphersuite_id( - tls_translate_cipher_name(token)); + ctx->allowed_ciphers[i] =3D mbedtls_ssl_get_ciphersuite_id(tls_tra= nslate_cipher_name(token)); if (0 !=3D ctx->allowed_ciphers[i]) { i++; @@ -382,8 +371,7 @@ void tls_ctx_set_cert_profile(struct tls_root_ctx *ctx, const char *profile) { - if (!profile || 0 =3D=3D strcmp(profile, "legacy") - || 0 =3D=3D strcmp(profile, "insecure")) + if (!profile || 0 =3D=3D strcmp(profile, "legacy") || 0 =3D=3D strcmp(= profile, "insecure")) { ctx->cert_profile =3D openvpn_x509_crt_profile_legacy; } @@ -418,8 +406,7 @@ const char *token; while ((token =3D strsep(&tmp_groups, ":"))) { - const mbedtls_ecp_curve_info *ci =3D - mbedtls_ecp_curve_info_from_name(token); + const mbedtls_ecp_curve_info *ci =3D mbedtls_ecp_curve_info_from_n= ame(token); if (!ci) { msg(M_WARN, "Warning unknown curve/group specified: %s", token= ); @@ -461,13 +448,11 @@ } void -tls_ctx_load_dh_params(struct tls_root_ctx *ctx, const char *dh_file, - bool dh_inline) +tls_ctx_load_dh_params(struct tls_root_ctx *ctx, const char *dh_file, bool= dh_inline) { if (dh_inline) { - if (!mbed_ok(mbedtls_dhm_parse_dhm(ctx->dhm_ctx, - (const unsigned char *) dh_file, + if (!mbed_ok(mbedtls_dhm_parse_dhm(ctx->dhm_ctx, (const unsigned c= har *)dh_file, strlen(dh_file) + 1))) { msg(M_FATAL, "Cannot read inline DH parameters"); @@ -482,24 +467,23 @@ } msg(D_TLS_DEBUG_LOW, "Diffie-Hellman initialized with " counter_format= " bit key", - (counter_type) mbedtls_dhm_get_bitlen(ctx->dhm_ctx)); + (counter_type)mbedtls_dhm_get_bitlen(ctx->dhm_ctx)); } void -tls_ctx_load_ecdh_params(struct tls_root_ctx *ctx, const char *curve_name - ) +tls_ctx_load_ecdh_params(struct tls_root_ctx *ctx, const char *curve_name) { if (NULL !=3D curve_name) { msg(M_WARN, "WARNING: mbed TLS builds do not support specifying an= " - "ECDH curve with --ecdh-curve, using default curves. Use " - "--tls-groups to specify curves."); + "ECDH curve with --ecdh-curve, using default curves. U= se " + "--tls-groups to specify curves."); } } int -tls_ctx_load_pkcs12(struct tls_root_ctx *ctx, const char *pkcs12_file, - bool pkcs12_file_inline, bool load_ca_file) +tls_ctx_load_pkcs12(struct tls_root_ctx *ctx, const char *pkcs12_file, boo= l pkcs12_file_inline, + bool load_ca_file) { msg(M_FATAL, "PKCS #12 files not yet supported for mbed TLS."); return 0; @@ -514,8 +498,7 @@ #endif /* _WIN32 */ void -tls_ctx_load_cert_file(struct tls_root_ctx *ctx, const char *cert_file, - bool cert_inline) +tls_ctx_load_cert_file(struct tls_root_ctx *ctx, const char *cert_file, bo= ol cert_inline) { ASSERT(NULL !=3D ctx); @@ -526,8 +509,7 @@ if (cert_inline) { - if (!mbed_ok(mbedtls_x509_crt_parse(ctx->crt_chain, - (const unsigned char *)cert_fi= le, + if (!mbed_ok(mbedtls_x509_crt_parse(ctx->crt_chain, (const unsigne= d char *)cert_file, strlen(cert_file) + 1))) { msg(M_FATAL, "Cannot load inline certificate file"); @@ -543,8 +525,7 @@ } int -tls_ctx_load_priv_file(struct tls_root_ctx *ctx, const char *priv_key_file, - bool priv_key_inline) +tls_ctx_load_priv_file(struct tls_root_ctx *ctx, const char *priv_key_file= , bool priv_key_inline) { int status; ASSERT(NULL !=3D ctx); @@ -556,40 +537,29 @@ if (priv_key_inline) { - status =3D mbedtls_compat_pk_parse_key(ctx->priv_key, - (const unsigned char *) priv_= key_file, + status =3D mbedtls_compat_pk_parse_key(ctx->priv_key, (const unsig= ned char *)priv_key_file, strlen(priv_key_file) + 1, NU= LL, 0, - mbedtls_ctr_drbg_random, - rand_ctx_get()); + mbedtls_ctr_drbg_random, rand= _ctx_get()); if (MBEDTLS_ERR_PK_PASSWORD_REQUIRED =3D=3D status) { - char passbuf[512] =3D {0}; + char passbuf[512] =3D { 0 }; pem_password_callback(passbuf, 512, 0, NULL); - status =3D mbedtls_compat_pk_parse_key(ctx->priv_key, - (const unsigned char *) p= riv_key_file, - strlen(priv_key_file) + 1, - (unsigned char *) passbuf, - strlen(passbuf), - mbedtls_ctr_drbg_random, - rand_ctx_get()); + status =3D mbedtls_compat_pk_parse_key( + ctx->priv_key, (const unsigned char *)priv_key_file, strle= n(priv_key_file) + 1, + (unsigned char *)passbuf, strlen(passbuf), mbedtls_ctr_drb= g_random, rand_ctx_get()); } } else { - status =3D mbedtls_compat_pk_parse_keyfile(ctx->priv_key, - priv_key_file, - NULL, - mbedtls_ctr_drbg_random, - rand_ctx_get()); + status =3D mbedtls_compat_pk_parse_keyfile(ctx->priv_key, priv_key= _file, NULL, + mbedtls_ctr_drbg_random, = rand_ctx_get()); if (MBEDTLS_ERR_PK_PASSWORD_REQUIRED =3D=3D status) { - char passbuf[512] =3D {0}; + char passbuf[512] =3D { 0 }; pem_password_callback(passbuf, 512, 0, NULL); - status =3D mbedtls_compat_pk_parse_keyfile(ctx->priv_key, - priv_key_file, passbu= f, - mbedtls_ctr_drbg_rand= om, - rand_ctx_get()); + status =3D mbedtls_compat_pk_parse_keyfile(ctx->priv_key, priv= _key_file, passbuf, + mbedtls_ctr_drbg_rand= om, rand_ctx_get()); } } if (!mbed_ok(status)) @@ -605,10 +575,8 @@ return 1; } - if (!mbed_ok(mbedtls_compat_pk_check_pair(&ctx->crt_chain->pk, - ctx->priv_key, - mbedtls_ctr_drbg_random, - rand_ctx_get()))) + if (!mbed_ok(mbedtls_compat_pk_check_pair(&ctx->crt_chain->pk, ctx->pr= iv_key, + mbedtls_ctr_drbg_random, ran= d_ctx_get()))) { msg(M_WARN, "Private key does not match the certificate"); return 1; @@ -636,13 +604,12 @@ * @return 0 on success, non-zero mbed TLS error code on failure. */ static inline int -external_pkcs1_sign( void *ctx_voidptr, - int (*f_rng)(void *, unsigned char *, size_t), void *= p_rng, +external_pkcs1_sign(void *ctx_voidptr, int (*f_rng)(void *, unsigned char = *, size_t), void *p_rng, #if MBEDTLS_VERSION_NUMBER < 0x03020100 - int mode, + int mode, #endif - mbedtls_md_type_t md_alg, unsigned int hashlen, const= unsigned char *hash, - unsigned char *sig ) + mbedtls_md_type_t md_alg, unsigned int hashlen, const = unsigned char *hash, + unsigned char *sig) { struct external_context *const ctx =3D ctx_voidptr; int rv; @@ -670,23 +637,22 @@ */ if (md_alg !=3D MBEDTLS_MD_NONE) { - const mbedtls_md_info_t *md_info =3D mbedtls_md_info_from_type( md= _alg ); + const mbedtls_md_info_t *md_info =3D mbedtls_md_info_from_type(md_= alg); if (md_info =3D=3D NULL) { - return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); + return (MBEDTLS_ERR_RSA_BAD_INPUT_DATA); } - if (!mbed_ok(mbedtls_oid_get_oid_by_md( md_alg, &oid, &oid_size ))) + if (!mbed_ok(mbedtls_oid_get_oid_by_md(md_alg, &oid, &oid_size))) { - return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); + return (MBEDTLS_ERR_RSA_BAD_INPUT_DATA); } - hashlen =3D mbedtls_md_get_size( md_info ); + hashlen =3D mbedtls_md_get_size(md_info); asn_len =3D 10 + oid_size; } - if ((SIZE_MAX - hashlen) < asn_len - || ctx->signature_length < (asn_len + hashlen)) + if ((SIZE_MAX - hashlen) < asn_len || ctx->signature_length < (asn_len= + hashlen)) { return MBEDTLS_ERR_RSA_BAD_INPUT_DATA; } @@ -705,12 +671,12 @@ * Digest ::=3D OCTET STRING */ *p++ =3D MBEDTLS_ASN1_SEQUENCE | MBEDTLS_ASN1_CONSTRUCTED; - *p++ =3D (unsigned char) ( 0x08 + oid_size + hashlen ); + *p++ =3D (unsigned char)(0x08 + oid_size + hashlen); *p++ =3D MBEDTLS_ASN1_SEQUENCE | MBEDTLS_ASN1_CONSTRUCTED; - *p++ =3D (unsigned char) ( 0x04 + oid_size ); + *p++ =3D (unsigned char)(0x04 + oid_size); *p++ =3D MBEDTLS_ASN1_OID; *p++ =3D oid_size & 0xFF; - memcpy( p, oid, oid_size ); + memcpy(p, oid, oid_size); p +=3D oid_size; *p++ =3D MBEDTLS_ASN1_NULL; *p++ =3D 0x00; @@ -725,8 +691,7 @@ memcpy(p, hash, hashlen); /* Call external signature function */ - if (!ctx->sign(ctx->sign_ctx, to_sign, asn_len + hashlen, sig, - ctx->signature_length)) + if (!ctx->sign(ctx->sign_ctx, to_sign, asn_len + hashlen, sig, ctx->si= gnature_length)) { rv =3D MBEDTLS_ERR_RSA_PRIVATE_FAILED; goto done; @@ -748,8 +713,8 @@ } int -tls_ctx_use_external_signing_func(struct tls_root_ctx *ctx, - external_sign_func sign_func, void *sign= _ctx) +tls_ctx_use_external_signing_func(struct tls_root_ctx *ctx, external_sign_= func sign_func, + void *sign_ctx) { ASSERT(NULL !=3D ctx); @@ -762,7 +727,7 @@ if (mbedtls_pk_get_type(&ctx->crt_chain->pk) !=3D MBEDTLS_PK_RSA) { msg(M_WARN, "ERROR: external key with mbed TLS requires a " - "certificate with an RSA key."); + "certificate with an RSA key."); return 1; } @@ -771,8 +736,8 @@ ctx->external_key.sign_ctx =3D sign_ctx; ALLOC_OBJ_CLEAR(ctx->priv_key, mbedtls_pk_context); - if (!mbed_ok(mbedtls_pk_setup_rsa_alt(ctx->priv_key, &ctx->external_ke= y, - NULL, external_pkcs1_sign, exter= nal_key_len))) + if (!mbed_ok(mbedtls_pk_setup_rsa_alt(ctx->priv_key, &ctx->external_ke= y, NULL, + external_pkcs1_sign, external_ke= y_len))) { return 1; } @@ -783,8 +748,7 @@ #ifdef ENABLE_MANAGEMENT /** Query the management interface for a signature, see external_sign_func= . */ static bool -management_sign_func(void *sign_ctx, const void *src, size_t src_len, - void *dst, size_t dst_len) +management_sign_func(void *sign_ctx, const void *src, size_t src_len, void= *dst, size_t dst_len) { bool ret =3D false; char *src_b64 =3D NULL; @@ -799,8 +763,7 @@ * We only support RSA external keys and PKCS1 signatures at the moment * in mbed TLS, so the signature parameter is hardcoded to this encodi= ng */ - if (!(dst_b64 =3D management_query_pk_sig(management, src_b64, - "RSA_PKCS1_PADDING"))) + if (!(dst_b64 =3D management_query_pk_sig(management, src_b64, "RSA_PK= CS1_PADDING"))) { goto cleanup; } @@ -827,8 +790,8 @@ #endif /* ifdef ENABLE_MANAGEMENT */ void -tls_ctx_load_ca(struct tls_root_ctx *ctx, const char *ca_file, - bool ca_inline, const char *ca_path, bool tls_server) +tls_ctx_load_ca(struct tls_root_ctx *ctx, const char *ca_file, bool ca_inl= ine, const char *ca_path, + bool tls_server) { if (ca_path) { @@ -837,8 +800,7 @@ if (ca_file && ca_inline) { - if (!mbed_ok(mbedtls_x509_crt_parse(ctx->ca_chain, - (const unsigned char *) ca_fil= e, + if (!mbed_ok(mbedtls_x509_crt_parse(ctx->ca_chain, (const unsigned= char *)ca_file, strlen(ca_file) + 1))) { msg(M_FATAL, "Cannot load inline CA certificates"); @@ -867,8 +829,7 @@ if (extra_certs_inline) { - if (!mbed_ok(mbedtls_x509_crt_parse(ctx->crt_chain, - (const unsigned char *) extra_= certs_file, + if (!mbed_ok(mbedtls_x509_crt_parse(ctx->crt_chain, (const unsigne= d char *)extra_certs_file, strlen(extra_certs_file) + 1))) { msg(M_FATAL, "Cannot load inline extra-certs file"); @@ -916,7 +877,7 @@ } static int -endless_buf_read( endless_buffer *in, unsigned char *out, size_t out_len ) +endless_buf_read(endless_buffer *in, unsigned char *out, size_t out_len) { size_t read_len =3D 0; @@ -931,8 +892,7 @@ if (block_len <=3D out_len - read_len) { buffer_entry *cur_entry =3D in->first_block; - memcpy(out + read_len, cur_entry->data + in->data_start, - block_len); + memcpy(out + read_len, cur_entry->data + in->data_start, block= _len); read_len +=3D block_len; @@ -948,8 +908,7 @@ } else { - memcpy(out + read_len, in->first_block->data + in->data_start, - out_len - read_len); + memcpy(out + read_len, in->first_block->data + in->data_start,= out_len - read_len); in->data_start +=3D out_len - read_len; read_len =3D out_len; } @@ -959,7 +918,7 @@ } static int -endless_buf_write( endless_buffer *out, const unsigned char *in, size_t le= n ) +endless_buf_write(endless_buffer *out, const unsigned char *in, size_t len) { buffer_entry *new_block =3D malloc(sizeof(buffer_entry)); if (NULL =3D=3D new_block) @@ -995,22 +954,21 @@ } static int -ssl_bio_read( void *ctx, unsigned char *out, size_t out_len) +ssl_bio_read(void *ctx, unsigned char *out, size_t out_len) { - bio_ctx *my_ctx =3D (bio_ctx *) ctx; + bio_ctx *my_ctx =3D (bio_ctx *)ctx; return endless_buf_read(&my_ctx->in, out, out_len); } static int -ssl_bio_write( void *ctx, const unsigned char *in, size_t in_len) +ssl_bio_write(void *ctx, const unsigned char *in, size_t in_len) { - bio_ctx *my_ctx =3D (bio_ctx *) ctx; + bio_ctx *my_ctx =3D (bio_ctx *)ctx; return endless_buf_write(&my_ctx->out, in, in_len); } static void -my_debug( void *ctx, int level, const char *file, int line, - const char *str ) +my_debug(void *ctx, int level, const char *file, int line, const char *str) { int my_loglevel =3D (level < 3) ? D_TLS_DEBUG_MED : D_TLS_DEBUG; msg(my_loglevel, "mbed TLS msg (%s:%d): %s", file, line, str); @@ -1022,8 +980,8 @@ void tls_ctx_personalise_random(struct tls_root_ctx *ctx) { - static char old_sha256_hash[32] =3D {0}; - unsigned char sha256_hash[32] =3D {0}; + static char old_sha256_hash[32] =3D { 0 }; + unsigned char sha256_hash[32] =3D { 0 }; mbedtls_ctr_drbg_context *cd_ctx =3D rand_ctx_get(); if (NULL !=3D ctx->crt_chain) @@ -1055,7 +1013,7 @@ #elif defined(MBEDTLS_SSL_PROTO_TLS1_2) return TLS_VER_1_2; #else - #error mbedtls is compiled without support for TLS 1.2 or 1.3 +#error mbedtls is compiled without support for TLS 1.2 or 1.3 #endif } @@ -1088,8 +1046,7 @@ } void -backend_tls_ctx_reload_crl(struct tls_root_ctx *ctx, const char *crl_file, - bool crl_inline) +backend_tls_ctx_reload_crl(struct tls_root_ctx *ctx, const char *crl_file,= bool crl_inline) { ASSERT(crl_file); @@ -1101,8 +1058,7 @@ if (crl_inline) { - if (!mbed_ok(mbedtls_x509_crl_parse(ctx->crl, - (const unsigned char *)crl_fil= e, + if (!mbed_ok(mbedtls_x509_crl_parse(ctx->crl, (const unsigned char= *)crl_file, strlen(crl_file) + 1))) { msg(M_WARN, "CRL: cannot parse inline CRL"); @@ -1124,8 +1080,7 @@ } void -key_state_ssl_init(struct key_state_ssl *ks_ssl, - const struct tls_root_ctx *ssl_ctx, bool is_server, +key_state_ssl_init(struct key_state_ssl *ks_ssl, const struct tls_root_ctx= *ssl_ctx, bool is_server, struct tls_session *session) { ASSERT(NULL !=3D ssl_ctx); @@ -1135,8 +1090,8 @@ /* Initialise SSL config */ ALLOC_OBJ_CLEAR(ks_ssl->ssl_config, mbedtls_ssl_config); mbedtls_ssl_config_init(ks_ssl->ssl_config); - mbedtls_ssl_config_defaults(ks_ssl->ssl_config, ssl_ctx->endpoint, - MBEDTLS_SSL_TRANSPORT_STREAM, MBEDTLS_SSL_= PRESET_DEFAULT); + mbedtls_ssl_config_defaults(ks_ssl->ssl_config, ssl_ctx->endpoint, MBE= DTLS_SSL_TRANSPORT_STREAM, + MBEDTLS_SSL_PRESET_DEFAULT); #ifdef MBEDTLS_DEBUG_C /* We only want to have mbed TLS generate debug level logging when we = would * also display it. @@ -1152,8 +1107,7 @@ } #endif mbedtls_ssl_conf_dbg(ks_ssl->ssl_config, my_debug, NULL); - mbedtls_ssl_conf_rng(ks_ssl->ssl_config, mbedtls_ctr_drbg_random, - rand_ctx_get()); + mbedtls_ssl_conf_rng(ks_ssl->ssl_config, mbedtls_ctr_drbg_random, rand= _ctx_get()); mbedtls_ssl_conf_cert_profile(ks_ssl->ssl_config, &ssl_ctx->cert_profi= le); =20 @@ -1168,8 +1122,8 @@ } /* Disable TLS renegotiations if the mbedtls library supports that fea= ture. - * OpenVPN's renegotiation creates new SSL sessions and does not depend= on - * this feature and TLS renegotiations have been problematic in the pas= t. */ + * OpenVPN's renegotiation creates new SSL sessions and does not depen= d on + * this feature and TLS renegotiations have been problematic in the pa= st. */ #if defined(MBEDTLS_SSL_RENEGOTIATION) mbedtls_ssl_conf_renegotiation(ks_ssl->ssl_config, MBEDTLS_SSL_RENEGOT= IATION_DISABLED); #endif /* MBEDTLS_SSL_RENEGOTIATION */ @@ -1186,12 +1140,10 @@ /* Initialise authentication information */ if (is_server) { - mbed_ok(mbedtls_ssl_conf_dh_param_ctx(ks_ssl->ssl_config, - ssl_ctx->dhm_ctx)); + mbed_ok(mbedtls_ssl_conf_dh_param_ctx(ks_ssl->ssl_config, ssl_ctx-= >dhm_ctx)); } - mbed_ok(mbedtls_ssl_conf_own_cert(ks_ssl->ssl_config, ssl_ctx->crt_cha= in, - ssl_ctx->priv_key)); + mbed_ok(mbedtls_ssl_conf_own_cert(ks_ssl->ssl_config, ssl_ctx->crt_cha= in, ssl_ctx->priv_key)); /* Initialise SSL verification */ if (session->opt->ssl_flags & SSLF_CLIENT_CERT_OPTIONAL) @@ -1210,8 +1162,7 @@ /* Initialize minimum TLS version */ { const int configured_tls_version_min =3D - (session->opt->ssl_flags >> SSLF_TLS_VERSION_MIN_SHIFT) - &SSLF_TLS_VERSION_MIN_MASK; + (session->opt->ssl_flags >> SSLF_TLS_VERSION_MIN_SHIFT) & SSLF= _TLS_VERSION_MIN_MASK; /* default to TLS 1.2 */ mbedtls_ssl_protocol_version version =3D MBEDTLS_SSL_VERSION_TLS1_= 2; @@ -1227,8 +1178,7 @@ /* Initialize maximum TLS version */ { const int configured_tls_version_max =3D - (session->opt->ssl_flags >> SSLF_TLS_VERSION_MAX_SHIFT) - &SSLF_TLS_VERSION_MAX_MASK; + (session->opt->ssl_flags >> SSLF_TLS_VERSION_MAX_SHIFT) & SSLF= _TLS_VERSION_MAX_MASK; mbedtls_ssl_protocol_version version =3D MBEDTLS_SSL_VERSION_UNKNO= WN; @@ -1245,10 +1195,10 @@ mbedtls_ssl_conf_max_tls_version(ks_ssl->ssl_config, version); } -#if defined(HAVE_MBEDTLS_SSL_CONF_EXPORT_KEYS_EXT_CB) && !defined(MBEDTLS_= SSL_KEYING_MATERIAL_EXPORT) +#if defined(HAVE_MBEDTLS_SSL_CONF_EXPORT_KEYS_EXT_CB) \ + && !defined(MBEDTLS_SSL_KEYING_MATERIAL_EXPORT) /* Initialize keying material exporter, old style. */ - mbedtls_ssl_conf_export_keys_ext_cb(ks_ssl->ssl_config, - mbedtls_ssl_export_keys_cb, sessio= n); + mbedtls_ssl_conf_export_keys_ext_cb(ks_ssl->ssl_config, mbedtls_ssl_ex= port_keys_cb, session); #endif /* Initialise SSL context */ @@ -1267,8 +1217,7 @@ /* Initialise BIOs */ ALLOC_OBJ_CLEAR(ks_ssl->bio_ctx, bio_ctx); - mbedtls_ssl_set_bio(ks_ssl->ctx, ks_ssl->bio_ctx, ssl_bio_write, - ssl_bio_read, NULL); + mbedtls_ssl_set_bio(ks_ssl->ctx, ks_ssl->bio_ctx, ssl_bio_write, ssl_b= io_read, NULL); } @@ -1317,7 +1266,7 @@ if (1 =3D=3D retval) { - memset(BPTR(buf), 0, BLEN(buf)); /* erase data just written */ + memset(BPTR(buf), 0, BLEN(buf)); /* erase data just written */ buf->len =3D 0; } @@ -1350,16 +1299,14 @@ { return 0; } - mbed_log_err(D_TLS_ERRORS, retval, - "TLS ERROR: write tls_write_plaintext_const error"); + mbed_log_err(D_TLS_ERRORS, retval, "TLS ERROR: write tls_write_pla= intext_const error"); return -1; } if (retval !=3D len) { - msg(D_TLS_ERRORS, - "TLS ERROR: write tls_write_plaintext_const incomplete %d/%d", - retval, len); + msg(D_TLS_ERRORS, "TLS ERROR: write tls_write_plaintext_const inco= mplete %d/%d", retval, + len); perf_pop(); return -1; } @@ -1446,15 +1393,14 @@ { return 0; } - mbed_log_err(D_TLS_ERRORS, retval, - "TLS ERROR: write tls_write_ciphertext error"); + mbed_log_err(D_TLS_ERRORS, retval, "TLS ERROR: write tls_write_cip= hertext error"); return -1; } if (retval !=3D buf->len) { - msg(D_TLS_ERRORS, "TLS ERROR: write tls_write_ciphertext incomplet= e %d/%d", - retval, buf->len); + msg(D_TLS_ERRORS, "TLS ERROR: write tls_write_ciphertext incomplet= e %d/%d", retval, + buf->len); perf_pop(); return -1; } @@ -1462,7 +1408,7 @@ /* successful write */ dmsg(D_HANDSHAKE_VERBOSE, "write tls_write_ciphertext %d bytes", retva= l); - memset(BPTR(buf), 0, BLEN(buf)); /* erase data just written */ + memset(BPTR(buf), 0, BLEN(buf)); /* erase data just written */ buf->len =3D 0; perf_pop(); @@ -1534,25 +1480,20 @@ char s2[256]; s1[0] =3D s2[0] =3D 0; - snprintf(s1, sizeof(s1), "%s %s, cipher %s", - prefix, - mbedtls_ssl_get_version(ks_ssl->ctx), + snprintf(s1, sizeof(s1), "%s %s, cipher %s", prefix, mbedtls_ssl_get_v= ersion(ks_ssl->ctx), mbedtls_ssl_get_ciphersuite(ks_ssl->ctx)); cert =3D mbedtls_ssl_get_peer_cert(ks_ssl->ctx); if (cert !=3D NULL) { - snprintf(s2, sizeof(s2), ", %u bit key", - (unsigned int) mbedtls_pk_get_bitlen(&cert->pk)); + snprintf(s2, sizeof(s2), ", %u bit key", (unsigned int)mbedtls_pk_= get_bitlen(&cert->pk)); } msg(D_HANDSHAKE, "%s%s", s1, s2); } void -show_available_tls_ciphers_list(const char *cipher_list, - const char *tls_cert_profile, - bool tls13) +show_available_tls_ciphers_list(const char *cipher_list, const char *tls_c= ert_profile, bool tls13) { if (tls13) { @@ -1603,8 +1544,8 @@ { static char mbedtls_version[30]; unsigned int pv =3D mbedtls_version_get_number(); - snprintf(mbedtls_version, sizeof(mbedtls_version), "mbed TLS %d.%d.%d", - (pv>>24)&0xff, (pv>>16)&0xff, (pv>>8)&0xff ); + snprintf(mbedtls_version, sizeof(mbedtls_version), "mbed TLS %d.%d.%d"= , (pv >> 24) & 0xff, + (pv >> 16) & 0xff, (pv >> 8) & 0xff); return mbedtls_version; } diff --git a/src/openvpn/ssl_mbedtls.h b/src/openvpn/ssl_mbedtls.h index fba766b..513a07e 100644 --- a/src/openvpn/ssl_mbedtls.h +++ b/src/openvpn/ssl_mbedtls.h @@ -43,19 +43,22 @@ typedef struct _buffer_entry buffer_entry; -struct _buffer_entry { +struct _buffer_entry +{ size_t length; uint8_t *data; buffer_entry *next_block; }; -typedef struct { +typedef struct +{ size_t data_start; buffer_entry *first_block; buffer_entry *last_block; } endless_buffer; -typedef struct { +typedef struct +{ endless_buffer in; endless_buffer out; } bio_ctx; @@ -73,12 +76,12 @@ * * @return true if signing succeeded, false otherwise. */ -typedef bool (*external_sign_func)( - void *sign_ctx, const void *src, size_t src_size, - void *dst, size_t dst_size); +typedef bool (*external_sign_func)(void *sign_ctx, const void *src, size_t= src_size, void *dst, + size_t dst_size); /** Context used by external_pkcs1_sign() */ -struct external_context { +struct external_context +{ size_t signature_length; external_sign_func sign; void *sign_ctx; @@ -91,13 +94,16 @@ * * The constants 64 and 48 are inherent to TLS 1.2. For TLS 1.3, it is not * possible to obtain the exporter master secret from mbed TLS. */ -struct tls_key_cache { +struct tls_key_cache +{ unsigned char client_server_random[64]; mbedtls_tls_prf_types tls_prf_type; unsigned char master_secret[48]; }; -#else /* !defined(MBEDTLS_SSL_KEYING_MATERIAL_EXPORT) */ -struct tls_key_cache { }; +#else /* !defined(MBEDTLS_SSL_KEYING_MATERIAL_EXPORT) */ +struct tls_key_cache +{ +}; #endif /** @@ -106,30 +112,32 @@ * * Either \c priv_key_pkcs11 or \c priv_key must be filled in. */ -struct tls_root_ctx { - bool initialised; /**< True if the context has been initiali= sed */ +struct tls_root_ctx +{ + bool initialised; /**< True if the context has be= en initialised */ - int endpoint; /**< Whether or not this is a server or a = client */ + int endpoint; /**< Whether or not this is a s= erver or a client */ - mbedtls_dhm_context *dhm_ctx; /**< Diffie-Helmann-Merkle context= */ - mbedtls_x509_crt *crt_chain; /**< Local Certificate chain */ - mbedtls_x509_crt *ca_chain; /**< CA chain for remote verificat= ion */ - mbedtls_pk_context *priv_key; /**< Local private key */ - mbedtls_x509_crl *crl; /**< Certificate Revocation List */ - time_t crl_last_mtime; /**< CRL last modification time */ - off_t crl_last_size; /**< size of last loaded CRL */ + mbedtls_dhm_context *dhm_ctx; /**< Diffie-Helmann-Merkle cont= ext */ + mbedtls_x509_crt *crt_chain; /**< Local Certificate chain */ + mbedtls_x509_crt *ca_chain; /**< CA chain for remote verifi= cation */ + mbedtls_pk_context *priv_key; /**< Local private key */ + mbedtls_x509_crl *crl; /**< Certificate Revocation Lis= t */ + time_t crl_last_mtime; /**< CRL last modification time= */ + off_t crl_last_size; /**< size of last loaded CRL */ #ifdef ENABLE_PKCS11 - pkcs11h_certificate_t pkcs11_cert; /**< PKCS11 certificate */ + pkcs11h_certificate_t pkcs11_cert; /**< PKCS11 certificate */ #endif - struct external_context external_key; /**< External key context */ - int *allowed_ciphers; /**< List of allowed ciphers for this conn= ection */ - mbedtls_compat_group_id *groups; /**< List of allowed groups for t= his connection */ + struct external_context external_key; /**< External key context */ + int *allowed_ciphers; /**< List of allowed ciphers fo= r this connection */ + mbedtls_compat_group_id *groups; /**< List of allowed groups for= this connection */ mbedtls_x509_crt_profile cert_profile; /**< Allowed certificate types = */ }; -struct key_state_ssl { - mbedtls_ssl_config *ssl_config; /**< mbedTLS global ssl config */ - mbedtls_ssl_context *ctx; /**< mbedTLS connection context */ +struct key_state_ssl +{ + mbedtls_ssl_config *ssl_config; /**< mbedTLS global ssl config */ + mbedtls_ssl_context *ctx; /**< mbedTLS connection context */ bio_ctx *bio_ctx; struct tls_key_cache tls_key_cache; @@ -145,8 +153,7 @@ * * @return 0 if successful, 1 if an error occurred. */ -int tls_ctx_use_external_signing_func(struct tls_root_ctx *ctx, - external_sign_func sign_func, +int tls_ctx_use_external_signing_func(struct tls_root_ctx *ctx, external_s= ign_func sign_func, void *sign_ctx); static inline void diff --git a/src/openvpn/ssl_ncp.c b/src/openvpn/ssl_ncp.c index 62fef42..5e094a2 100644 --- a/src/openvpn/ssl_ncp.c +++ b/src/openvpn/ssl_ncp.c @@ -82,8 +82,7 @@ { return false; } - else if (tls_peer_info_ncp_ver(peer_info) >=3D 2 - || strstr(peer_info, "IV_CIPHERS=3D")) + else if (tls_peer_info_ncp_ver(peer_info) >=3D 2 || strstr(peer_info, = "IV_CIPHERS=3D")) { return true; } @@ -98,7 +97,7 @@ { bool error_found =3D false; - struct buffer new_list =3D alloc_buf(MAX_NCP_CIPHERS_LENGTH); + struct buffer new_list =3D alloc_buf(MAX_NCP_CIPHERS_LENGTH); char *const tmp_ciphers =3D string_alloc(list, NULL); const char *token =3D strtok(tmp_ciphers, ":"); @@ -126,22 +125,23 @@ if (nonecipher) { msg(M_WARN, "WARNING: cipher 'none' specified for --data-ciphe= rs. " - "This allows negotiation of NO encryption and " - "tunnelled data WILL then be transmitted in clear text " - "over the network! " - "PLEASE DO RECONSIDER THIS SETTING!"); + "This allows negotiation of NO encryption and " + "tunnelled data WILL then be transmitted in clear = text " + "over the network! " + "PLEASE DO RECONSIDER THIS SETTING!"); } if (!nonecipher && !cipher_valid(token)) { msg(M_WARN, "Unsupported %scipher in --data-ciphers: %s", opts= tr, token); error_found =3D error_found || !optional; } - else if (!nonecipher && !cipher_kt_mode_aead(token) - && !cipher_kt_mode_cbc(token) + else if (!nonecipher && !cipher_kt_mode_aead(token) && !cipher_kt_= mode_cbc(token) && !cipher_kt_mode_ofb_cfb(token)) { - msg(M_WARN, "Unsupported %scipher algorithm '%s'. It does not = use " - "CFB, OFB, CBC, or a supported AEAD mode", optstr, token); + msg(M_WARN, + "Unsupported %scipher algorithm '%s'. It does not use " + "CFB, OFB, CBC, or a supported AEAD mode", + optstr, token); error_found =3D error_found || !optional; } else @@ -154,7 +154,7 @@ ovpn_cipher_name =3D "none"; } - if (buf_len(&new_list)> 0) + if (buf_len(&new_list) > 0) { /* The next if condition ensure there is always space for * a : @@ -163,11 +163,10 @@ } /* Ensure buffer has capacity for cipher name + : + \0 */ - if (!(buf_forward_capacity(&new_list) > - strlen(ovpn_cipher_name) + 2)) + if (!(buf_forward_capacity(&new_list) > strlen(ovpn_cipher_nam= e) + 2)) { msg(M_WARN, "Length of --data-ciphers is over the " - "limit of 127 chars"); + "limit of 127 chars"); error_found =3D true; } else @@ -179,7 +178,6 @@ } - char *ret =3D NULL; if (!error_found && buf_len(&new_list) > 0) { @@ -200,8 +198,7 @@ size_t newlen =3D strlen(o->ncp_ciphers) + 1 + strlen(ciphername) + 1; char *ncp_ciphers =3D gc_malloc(newlen, false, &o->gc); - ASSERT(snprintf(ncp_ciphers, newlen, "%s:%s", o->ncp_ciphers, - ciphername)); + ASSERT(snprintf(ncp_ciphers, newlen, "%s:%s", o->ncp_ciphers, cipherna= me)); o->ncp_ciphers =3D ncp_ciphers; } @@ -233,7 +230,7 @@ { return iv_ciphers; } - else if (tls_peer_info_ncp_ver(peer_info)>=3D2) + else if (tls_peer_info_ncp_ver(peer_info) >=3D 2) { /* If the peer announces IV_NCP=3D2 then it supports the AES GCM * ciphers */ @@ -246,8 +243,8 @@ } char * -ncp_get_best_cipher(const char *server_list, const char *peer_info, - const char *remote_cipher, struct gc_arena *gc) +ncp_get_best_cipher(const char *server_list, const char *peer_info, const = char *remote_cipher, + struct gc_arena *gc) { /* * The gc of the parameter is tied to the VPN session, create a @@ -262,8 +259,7 @@ /* non-NCP clients without OCC? "assume nothing" */ /* For client doing the newer version of NCP (that send IV_CIPHERS) * we cannot assume that they will accept remote_cipher */ - if (remote_cipher =3D=3D NULL - || (peer_info && strstr(peer_info, "IV_CIPHERS=3D"))) + if (remote_cipher =3D=3D NULL || (peer_info && strstr(peer_info, "IV_C= IPHERS=3D"))) { remote_cipher =3D ""; } @@ -273,8 +269,7 @@ const char *token; while ((token =3D strsep(&tmp_ciphers, ":"))) { - if (tls_item_in_cipher_list(token, peer_ncp_list) - || streq(token, remote_cipher)) + if (tls_item_in_cipher_list(token, peer_ncp_list) || streq(token, = remote_cipher)) { break; } @@ -302,8 +297,7 @@ static bool tls_poor_mans_ncp(struct options *o, const char *remote_ciphername) { - if (remote_ciphername - && tls_item_in_cipher_list(remote_ciphername, o->ncp_ciphers)) + if (remote_ciphername && tls_item_in_cipher_list(remote_ciphername, o-= >ncp_ciphers)) { o->ciphername =3D string_alloc(remote_ciphername, &o->gc); msg(D_TLS_DEBUG_LOW, "Using peer cipher '%s'", o->ciphername); @@ -338,29 +332,27 @@ /* We failed negotiation, give appropriate error message */ if (c->c2.tls_multi->remote_ciphername) { - msg(D_TLS_ERRORS, "OPTIONS ERROR: failed to negotiate " + msg(D_TLS_ERRORS, + "OPTIONS ERROR: failed to negotiate " "cipher with server. Add the server's " "cipher ('%s') to --data-ciphers (currently '%s'), e.g." "--data-ciphers %s:%s if you want to connect to this server.", - c->c2.tls_multi->remote_ciphername, - c->options.ncp_ciphers_conf, c->options.ncp_ciphers_conf, - c->c2.tls_multi->remote_ciphername); + c->c2.tls_multi->remote_ciphername, c->options.ncp_ciphers_con= f, + c->options.ncp_ciphers_conf, c->c2.tls_multi->remote_ciphernam= e); return false; - } else { msg(D_TLS_ERRORS, "OPTIONS ERROR: failed to negotiate " - "cipher with server. Configure " - "--data-ciphers-fallback if you want to connect " - "to this server."); + "cipher with server. Configure " + "--data-ciphers-fallback if you want to connect " + "to this server."); return false; } } const char * -get_p2p_ncp_cipher(struct tls_session *session, const char *peer_info, - struct gc_arena *gc) +get_p2p_ncp_cipher(struct tls_session *session, const char *peer_info, str= uct gc_arena *gc) { /* we use a local gc arena to keep the temporary strings needed by str= sep */ struct gc_arena gc_local =3D gc_new(); @@ -410,8 +402,7 @@ } static void -p2p_ncp_set_options(struct tls_multi *multi, struct tls_session *session, - const char *common_cipher) +p2p_ncp_set_options(struct tls_multi *multi, struct tls_session *session, = const char *common_cipher) { /* will return 0 if peer_info is null */ const unsigned int iv_proto_peer =3D extract_iv_proto(multi->peer_info= ); @@ -433,8 +424,8 @@ session->opt->crypto_flags |=3D CO_USE_CC_EXIT_NOTIFY; } - if (session->opt->data_epoch_supported && (iv_proto_peer & IV_PROTO_DA= TA_EPOCH) - && common_cipher && cipher_kt_mode_aead(common_cipher)) + if (session->opt->data_epoch_supported && (iv_proto_peer & IV_PROTO_DA= TA_EPOCH) && common_cipher + && cipher_kt_mode_aead(common_cipher)) { session->opt->crypto_flags |=3D CO_EPOCH_DATA_KEY_FORMAT; } @@ -457,20 +448,18 @@ uint8_t peerid[3]; if (!key_state_export_keying_material(session, EXPORT_P2P_PEER= ID_LABEL, - strlen(EXPORT_P2P_PEERID= _LABEL), - &peerid, 3)) + strlen(EXPORT_P2P_PEERID= _LABEL), &peerid, 3)) { /* Non DCO setup might still work but also this should nev= er * happen or very likely the TLS encryption key exporter w= ill * also fail */ msg(M_NONFATAL, "TLS key export for P2P peer id failed. " - "Continuing anyway, expect problems"); + "Continuing anyway, expect problems"); } else { multi->peer_id =3D (peerid[0] << 16) + (peerid[1] << 8) + = peerid[2]; } - } } if (iv_proto_peer & IV_PROTO_DYN_TLS_CRYPT) @@ -511,12 +500,11 @@ common_cipher =3D BSTR(&out); } - msg(D_TLS_DEBUG_LOW, "P2P mode NCP negotiation result: " + msg(D_TLS_DEBUG_LOW, + "P2P mode NCP negotiation result: " "TLS_export=3D%d, DATA_v2=3D%d, peer-id %d, epoch=3D%d, cipher=3D%= s", - (bool)(session->opt->crypto_flags & CO_USE_TLS_KEY_MATERIAL_EXPORT= ), - multi->use_peer_id, - multi->peer_id, - (bool)(session->opt->crypto_flags & CO_EPOCH_DATA_KEY_FORMAT), + (bool)(session->opt->crypto_flags & CO_USE_TLS_KEY_MATERIAL_EXPORT= ), multi->use_peer_id, + multi->peer_id, (bool)(session->opt->crypto_flags & CO_EPOCH_DATA_= KEY_FORMAT), common_cipher); gc_free(&gc); @@ -526,16 +514,15 @@ bool check_session_cipher(struct tls_session *session, struct options *options) { - bool cipher_allowed_as_fallback =3D options->enable_ncp_fallback - && streq(options->ciphername, sessio= n->opt->config_ciphername); + bool cipher_allowed_as_fallback =3D + options->enable_ncp_fallback && streq(options->ciphername, session= ->opt->config_ciphername); if (!session->opt->server && !cipher_allowed_as_fallback && !tls_item_in_cipher_list(options->ciphername, options->ncp_ciph= ers)) { struct gc_arena gc =3D gc_new(); msg(D_TLS_ERRORS, "Error: negotiated cipher not allowed - %s not i= n %s%s", - options->ciphername, options->ncp_ciphers_conf, - ncp_expanded_ciphers(options, &gc)); + options->ciphername, options->ncp_ciphers_conf, ncp_expanded_c= iphers(options, &gc)); /* undo cipher push, abort connection setup */ options->ciphername =3D session->opt->config_ciphername; gc_free(&gc); @@ -576,7 +563,7 @@ const char *after_default =3D def + strlen(search); buf_write(&ncp_ciphers_buf, after_default, strlen(after_default)); - o->ncp_ciphers =3D (char *) ncp_ciphers; + o->ncp_ciphers =3D (char *)ncp_ciphers; } =20 /** @@ -587,8 +574,8 @@ void options_postprocess_setdefault_ncpciphers(struct options *o) { - bool default_in_cipher_list =3D o->ncp_ciphers - && tls_item_in_cipher_list("DEFAULT", o-= >ncp_ciphers); + bool default_in_cipher_list =3D + o->ncp_ciphers && tls_item_in_cipher_list("DEFAULT", o->ncp_cipher= s); /* preserve the values that the user put into the configuration */ o->ncp_ciphers_conf =3D o->ncp_ciphers; diff --git a/src/openvpn/ssl_ncp.h b/src/openvpn/ssl_ncp.h index b01cd87..2b2ff85 100644 --- a/src/openvpn/ssl_ncp.h +++ b/src/openvpn/ssl_ncp.h @@ -38,8 +38,7 @@ * Returns whether the client supports NCP either by * announcing IV_NCP>=3D2 or the IV_CIPHERS list */ -bool -tls_peer_supports_ncp(const char *peer_info); +bool tls_peer_supports_ncp(const char *peer_info); /* forward declaration to break include dependency loop */ struct context; @@ -50,8 +49,7 @@ * * @return Wether the client NCP process suceeded or failed */ -bool -check_pull_client_ncp(struct context *c, int found); +bool check_pull_client_ncp(struct context *c, int found); /** * Iterates through the ciphers in server_list and return the first @@ -73,9 +71,8 @@ * @returns NULL if no common cipher is available, otherwise the best comm= on * cipher */ -char * -ncp_get_best_cipher(const char *server_list, const char *peer_info, - const char *remote_cipher, struct gc_arena *gc); +char *ncp_get_best_cipher(const char *server_list, const char *peer_info, = const char *remote_cipher, + struct gc_arena *gc); /** @@ -86,8 +83,7 @@ * or allocated via gc. If no information is available an empty string * ("") is returned. */ -const char * -tls_peer_ncp_list(const char *peer_info, struct gc_arena *gc); +const char *tls_peer_ncp_list(const char *peer_info, struct gc_arena *gc); /** * Check whether the ciphers in the supplied list are supported. @@ -102,8 +98,7 @@ * is short than MAX_NCP_CIPHERS_LENGTH. NULL * otherwise. */ -char * -mutate_ncp_cipher_list(const char *list, struct gc_arena *gc); +char *mutate_ncp_cipher_list(const char *list, struct gc_arena *gc); /** * Appends the cipher specified by the ciphernamer parameter to to @@ -147,17 +142,15 @@ * @param gc gc arena that will be used to allocate the returne= d cipher * @return common cipher if one exist. */ -const char * -get_p2p_ncp_cipher(struct tls_session *session, const char *peer_info, - struct gc_arena *gc); +const char *get_p2p_ncp_cipher(struct tls_session *session, const char *pe= er_info, + struct gc_arena *gc); /** * Checks if the cipher is allowed, otherwise returns false and reset the * cipher to the config cipher. */ -bool -check_session_cipher(struct tls_session *session, struct options *options); +bool check_session_cipher(struct tls_session *session, struct options *opt= ions); /** * Checks for availability of Chacha20-Poly1305 and sets @@ -167,8 +160,7 @@ * If DEFAULT is in the ncp_cipher string, it will be replaced * by the default cipher string as defined above. */ -void -options_postprocess_setdefault_ncpciphers(struct options *o); +void options_postprocess_setdefault_ncpciphers(struct options *o); /** returns the o->ncp_ciphers in brackets, e.g. * (AES-256-GCM:CHACHA20-POLY1305) if o->ncp_ciphers_conf @@ -176,6 +168,5 @@ * * The returned string will be allocated in the passed \c gc */ -const char * -ncp_expanded_ciphers(struct options *o, struct gc_arena *gc); +const char *ncp_expanded_ciphers(struct options *o, struct gc_arena *gc); #endif /* ifndef OPENVPN_SSL_NCP_H */ diff --git a/src/openvpn/ssl_openssl.c b/src/openvpn/ssl_openssl.c index 1c1649f..1948d12 100644 --- a/src/openvpn/ssl_openssl.c +++ b/src/openvpn/ssl_openssl.c @@ -113,7 +113,7 @@ if (ERR_peek_error() !=3D 0) { crypto_msg(M_WARN, "Warning: TLS server context initialisation " - "has warnings."); + "has warnings."); } } @@ -131,7 +131,7 @@ if (ERR_peek_error() !=3D 0) { crypto_msg(M_WARN, "Warning: TLS client context initialisation " - "has warnings."); + "has warnings."); } } @@ -152,15 +152,13 @@ } bool -key_state_export_keying_material(struct tls_session *session, - const char *label, size_t label_size, +key_state_export_keying_material(struct tls_session *session, const char *= label, size_t label_size, void *ekm, size_t ekm_size) { SSL *ssl =3D session->key[KS_PRIMARY].ks_ssl.ssl; - if (SSL_export_keying_material(ssl, ekm, ekm_size, label, - label_size, NULL, 0, 0) =3D=3D 1) + if (SSL_export_keying_material(ssl, ekm, ekm_size, label, label_size, = NULL, 0, 0) =3D=3D 1) { return true; } @@ -184,16 +182,15 @@ if (where & SSL_CB_LOOP) { dmsg(D_HANDSHAKE_VERBOSE, "SSL state (%s): %s", - where & SSL_ST_CONNECT ? "connect" : - where &SSL_ST_ACCEPT ? "accept" : - "undefined", SSL_state_string_long(s)); + where & SSL_ST_CONNECT ? "connect" + : where & SSL_ST_ACCEPT ? "accept" + : "undefined", + SSL_state_string_long(s)); } else if (where & SSL_CB_ALERT) { - dmsg(D_TLS_DEBUG_LOW, "%s %s SSL alert: %s", - where & SSL_CB_READ ? "Received" : "Sent", - SSL_alert_type_string_long(ret), - SSL_alert_desc_string_long(ret)); + dmsg(D_TLS_DEBUG_LOW, "%s %s SSL alert: %s", where & SSL_CB_READ ?= "Received" : "Sent", + SSL_alert_type_string_long(ret), SSL_alert_desc_string_long(r= et)); } } @@ -232,7 +229,7 @@ return TLS_VER_1_2; #elif defined(TLS1_1_VERSION) || defined(SSL_OP_NO_TLSv1_1) return TLS_VER_1_1; -#else /* if defined(TLS1_3_VERSION) */ +#else /* if defined(TLS1_3_VERSION) */ return TLS_VER_1_0; #endif } @@ -278,10 +275,10 @@ static bool tls_ctx_set_tls_versions(struct tls_root_ctx *ctx, unsigned int ssl_flags) { - int tls_ver_min =3D openssl_tls_version( - (ssl_flags >> SSLF_TLS_VERSION_MIN_SHIFT) & SSLF_TLS_VERSION_MIN_M= ASK); - int tls_ver_max =3D openssl_tls_version( - (ssl_flags >> SSLF_TLS_VERSION_MAX_SHIFT) & SSLF_TLS_VERSION_MAX_M= ASK); + int tls_ver_min =3D + openssl_tls_version((ssl_flags >> SSLF_TLS_VERSION_MIN_SHIFT) & SS= LF_TLS_VERSION_MIN_MASK); + int tls_ver_max =3D + openssl_tls_version((ssl_flags >> SSLF_TLS_VERSION_MAX_SHIFT) & SS= LF_TLS_VERSION_MAX_MASK); if (!tls_ver_min) { @@ -372,7 +369,8 @@ for (; begin_of_cipher < strlen(ciphers); begin_of_cipher =3D end_of_c= ipher) { end_of_cipher +=3D strcspn(&ciphers[begin_of_cipher], ":"); - cipher_pair =3D tls_get_cipher_name_pair(&ciphers[begin_of_cipher]= , end_of_cipher - begin_of_cipher); + cipher_pair =3D + tls_get_cipher_name_pair(&ciphers[begin_of_cipher], end_of_cip= her - begin_of_cipher); if (NULL =3D=3D cipher_pair) { @@ -393,11 +391,13 @@ current_cipher_len =3D strlen(current_cipher); if (end_of_cipher - begin_of_cipher =3D=3D current_cipher_len - && 0 !=3D memcmp(&ciphers[begin_of_cipher], cipher_pair->i= ana_name, - end_of_cipher - begin_of_cipher)) + && 0 + !=3D memcmp(&ciphers[begin_of_cipher], cipher_pair-= >iana_name, + end_of_cipher - begin_of_cipher)) { /* Non-IANA name used, show warning */ - msg(M_WARN, "Deprecated TLS cipher name '%s', please use I= ANA name '%s'", cipher_pair->openssl_name, cipher_pair->iana_name); + msg(M_WARN, "Deprecated TLS cipher name '%s', please use I= ANA name '%s'", + cipher_pair->openssl_name, cipher_pair->iana_name); } } @@ -405,8 +405,7 @@ if ((SIZE_MAX - openssl_ciphers_len) < current_cipher_len || (len - 1) < (openssl_ciphers_len + current_cipher_len)) { - msg(M_FATAL, - "Failed to set restricted TLS cipher list, too long (>%d).= ", + msg(M_FATAL, "Failed to set restricted TLS cipher list, too lo= ng (>%d).", (int)(len - 1)); } @@ -421,7 +420,7 @@ if (openssl_ciphers_len > 0) { - openssl_ciphers[openssl_ciphers_len-1] =3D '\0'; + openssl_ciphers[openssl_ciphers_len - 1] =3D '\0'; } } @@ -431,17 +430,18 @@ if (ciphers =3D=3D NULL) { /* Use sane default TLS cipher list */ - if (!SSL_CTX_set_cipher_list(ctx->ctx, - /* Use openssl's default list as a ba= sis */ - "DEFAULT" - /* Disable export ciphers and openssl= 's 'low' and 'medium' ciphers */ - ":!EXP:!LOW:!MEDIUM" - /* Disable static (EC)DH keys (no for= ward secrecy) */ - ":!kDH:!kECDH" - /* Disable DSA private keys */ - ":!DSS" - /* Disable unsupported TLS modes */ - ":!PSK:!SRP:!kRSA")) + if (!SSL_CTX_set_cipher_list( + ctx->ctx, + /* Use openssl's default list as a basis */ + "DEFAULT" + /* Disable export ciphers and openssl's 'low' and 'medium'= ciphers */ + ":!EXP:!LOW:!MEDIUM" + /* Disable static (EC)DH keys (no forward secrecy) */ + ":!kDH:!kECDH" + /* Disable DSA private keys */ + ":!DSS" + /* Disable unsupported TLS modes */ + ":!PSK:!SRP:!kRSA")) { crypto_msg(M_FATAL, "Failed to set default TLS cipher list."); } @@ -461,8 +461,7 @@ } static void -convert_tls13_list_to_openssl(char *openssl_ciphers, size_t len, - const char *ciphers) +convert_tls13_list_to_openssl(char *openssl_ciphers, size_t len, const cha= r *ciphers) { /* * OpenSSL (and official IANA) cipher names have _ in them. We @@ -471,9 +470,8 @@ */ if (strlen(ciphers) >=3D (len - 1)) { - msg(M_FATAL, - "Failed to set restricted TLS 1.3 cipher list, too long (>%d).= ", - (int) (len - 1)); + msg(M_FATAL, "Failed to set restricted TLS 1.3 cipher list, too lo= ng (>%d).", + (int)(len - 1)); } strncpy(openssl_ciphers, ciphers, len); @@ -498,20 +496,19 @@ } #if !defined(TLS1_3_VERSION) - crypto_msg(M_WARN, "Not compiled with OpenSSL 1.1.1 or higher. " + crypto_msg(M_WARN, + "Not compiled with OpenSSL 1.1.1 or higher. " "Ignoring TLS 1.3 only tls-ciphersuites '%s' setting.", ciphers); #else ASSERT(NULL !=3D ctx); char openssl_ciphers[4096]; - convert_tls13_list_to_openssl(openssl_ciphers, sizeof(openssl_ciphers), - ciphers); + convert_tls13_list_to_openssl(openssl_ciphers, sizeof(openssl_ciphers)= , ciphers); if (!SSL_CTX_set_ciphersuites(ctx->ctx, openssl_ciphers)) { - crypto_msg(M_FATAL, "Failed to set restricted TLS 1.3 cipher list:= %s", - openssl_ciphers); + crypto_msg(M_FATAL, "Failed to set restricted TLS 1.3 cipher list:= %s", openssl_ciphers); } #endif } @@ -520,7 +517,7 @@ tls_ctx_set_cert_profile(struct tls_root_ctx *ctx, const char *profile) { #if OPENSSL_VERSION_NUMBER > 0x10100000L \ - && (!defined(LIBRESSL_VERSION_NUMBER) || LIBRESSL_VERSION_NUMBER > 0x= 3060000fL) + && (!defined(LIBRESSL_VERSION_NUMBER) || LIBRESSL_VERSION_NUMBER > 0x3= 060000fL) /* OpenSSL does not have certificate profiles, but a complex set of * callbacks that we could try to implement to achieve something simil= ar. * For now, use OpenSSL's security levels to achieve similar (but not = equal) @@ -549,8 +546,10 @@ #else /* if OPENSSL_VERSION_NUMBER > 0x10100000L */ if (profile) { - msg(M_WARN, "WARNING: OpenSSL 1.1.0 and LibreSSL do not support " - "--tls-cert-profile, ignoring user-set profile: '%s'", profile= ); + msg(M_WARN, + "WARNING: OpenSSL 1.1.0 and LibreSSL do not support " + "--tls-cert-profile, ignoring user-set profile: '%s'", + profile); } #endif /* if OPENSSL_VERSION_NUMBER > 0x10100000L */ } @@ -602,15 +601,13 @@ if (!SSL_CTX_set1_groups(ctx->ctx, glist, glistlen)) { - crypto_msg(M_FATAL, "Failed to set allowed TLS group list: %s", - groups); + crypto_msg(M_FATAL, "Failed to set allowed TLS group list: %s", gr= oups); } gc_free(&gc); #else /* if OPENSSL_VERSION_NUMBER < 0x30000000L */ if (!SSL_CTX_set1_groups_list(ctx->ctx, groups)) { - crypto_msg(M_FATAL, "Failed to set allowed TLS group list: %s", - groups); + crypto_msg(M_FATAL, "Failed to set allowed TLS group list: %s", gr= oups); } #endif /* if OPENSSL_VERSION_NUMBER < 0x30000000L */ } @@ -652,8 +649,7 @@ } void -tls_ctx_load_dh_params(struct tls_root_ctx *ctx, const char *dh_file, - bool dh_file_inline) +tls_ctx_load_dh_params(struct tls_root_ctx *ctx, const char *dh_file, bool= dh_file_inline) { BIO *bio; @@ -689,8 +685,7 @@ crypto_msg(M_FATAL, "SSL_CTX_set0_tmp_dh_pkey"); } - msg(D_TLS_DEBUG_LOW, "Diffie-Hellman initialized with %d bit key", - 8 * EVP_PKEY_get_size(dh)); + msg(D_TLS_DEBUG_LOW, "Diffie-Hellman initialized with %d bit key", 8 *= EVP_PKEY_get_size(dh)); #else /* if OPENSSL_VERSION_NUMBER >=3D 0x30000000L */ DH *dh =3D PEM_read_bio_DHparams(bio, NULL, NULL, NULL); BIO_free(bio); @@ -705,8 +700,7 @@ crypto_msg(M_FATAL, "SSL_CTX_set_tmp_dh"); } - msg(D_TLS_DEBUG_LOW, "Diffie-Hellman initialized with %d bit key", - 8 * DH_size(dh)); + msg(D_TLS_DEBUG_LOW, "Diffie-Hellman initialized with %d bit key", 8 *= DH_size(dh)); DH_free(dh); #endif /* if OPENSSL_VERSION_NUMBER >=3D 0x30000000L */ @@ -719,8 +713,8 @@ if (curve_name !=3D NULL) { msg(M_WARN, "WARNING: OpenSSL 3.0+ builds do not support specifyin= g an " - "ECDH curve with --ecdh-curve, using default curves. Use " - "--tls-groups to specify groups."); + "ECDH curve with --ecdh-curve, using default curves. U= se " + "--tls-groups to specify groups."); } #elif !defined(OPENSSL_NO_EC) int nid =3D NID_undef; @@ -753,10 +747,9 @@ { /* Creating key failed, fall back on sane default */ ecdh =3D EC_KEY_new_by_curve_name(NID_secp384r1); - const char *source =3D (NULL =3D=3D curve_name) ? - "extract curve from certificate" : "use suppl= ied curve"; - msg(D_TLS_DEBUG_LOW, - "Failed to %s (%s), using secp384r1 instead.", source, sname); + const char *source =3D + (NULL =3D=3D curve_name) ? "extract curve from certificate" : = "use supplied curve"; + msg(D_TLS_DEBUG_LOW, "Failed to %s (%s), using secp384r1 instead."= , source, sname); sname =3D OBJ_nid2sn(NID_secp384r1); } @@ -770,7 +763,7 @@ EC_KEY_free(ecdh); #else /* ifndef OPENSSL_NO_EC */ msg(D_LOW, "Your OpenSSL library was built without elliptic curve supp= ort." - " Skipping ECDH parameter loading."); + " Skipping ECDH parameter loading."); #endif /* OPENSSL_NO_EC */ } @@ -794,7 +787,8 @@ { struct user_pass up; CLEAR(up); - get_user_pass(&up, NULL, "PKCS#11 token", GET_USER_PASS_MANAGE= MENT|GET_USER_PASS_PASSWORD_ONLY); + get_user_pass(&up, NULL, "PKCS#11 token", + GET_USER_PASS_MANAGEMENT | GET_USER_PASS_PASSWOR= D_ONLY); UI_set_result(ui, uis, up.password); purge_user_pass(&up, true); } @@ -845,12 +839,11 @@ { return NULL; } - pkey =3D PEM_read_bio_PrivateKey(in, NULL, - SSL_CTX_get_default_passwd_cb(ssl_ctx), + pkey =3D PEM_read_bio_PrivateKey(in, NULL, SSL_CTX_get_default_passwd_= cb(ssl_ctx), SSL_CTX_get_default_passwd_cb_userdata(= ssl_ctx)); BIO_free(in); -#else /* defined(HAVE_OPENSSL_STORE_API) */ +#else /* defined(HAVE_OPENSSL_STORE_API) */ OSSL_STORE_CTX *store_ctx =3D NULL; OSSL_STORE_INFO *info =3D NULL; @@ -863,8 +856,7 @@ } UI_method_set_reader(ui_method, ui_reader); - store_ctx =3D OSSL_STORE_open_ex(uri, tls_libctx, NULL, ui_method, ssl= _ctx, - NULL, NULL, NULL); + store_ctx =3D OSSL_STORE_open_ex(uri, tls_libctx, NULL, ui_method, ssl= _ctx, NULL, NULL, NULL); if (!store_ctx) { goto end; @@ -904,8 +896,8 @@ } int -tls_ctx_load_pkcs12(struct tls_root_ctx *ctx, const char *pkcs12_file, - bool pkcs12_file_inline, bool load_ca_file) +tls_ctx_load_pkcs12(struct tls_root_ctx *ctx, const char *pkcs12_file, boo= l pkcs12_file_inline, + bool load_ca_file) { FILE *fp; EVP_PKEY *pkey; @@ -920,8 +912,7 @@ if (pkcs12_file_inline) { BIO *b64 =3D BIO_new(BIO_f_base64()); - BIO *bio =3D BIO_new_mem_buf((void *) pkcs12_file, - (int) strlen(pkcs12_file)); + BIO *bio =3D BIO_new_mem_buf((void *)pkcs12_file, (int)strlen(pkcs= 12_file)); ASSERT(b64 && bio); BIO_push(b64, bio); p12 =3D d2i_PKCS12_bio(b64, NULL); @@ -956,7 +947,7 @@ if (!PKCS12_parse(p12, password, &pkey, &cert, &ca)) { crypto_msg(M_WARN, "Decoding PKCS12 failed. Probably wrong pas= sword " - "or unsupported/legacy encryption"); + "or unsupported/legacy encryption"); #ifdef ENABLE_MANAGEMENT if (management && (ERR_GET_REASON(ERR_peek_error()) =3D=3D PKC= S12_R_MAC_VERIFY_FAILURE)) { @@ -1002,11 +993,13 @@ X509_STORE *cert_store =3D SSL_CTX_get_cert_store(ctx->ctx= ); if (!X509_STORE_add_cert(cert_store, sk_X509_value(ca, i))) { - crypto_msg(M_FATAL, "Cannot add certificate to certifi= cate chain (X509_STORE_add_cert)"); + crypto_msg(M_FATAL, + "Cannot add certificate to certificate chai= n (X509_STORE_add_cert)"); } if (!SSL_CTX_add_client_CA(ctx->ctx, sk_X509_value(ca, i))) { - crypto_msg(M_FATAL, "Cannot add certificate to client = CA list (SSL_CTX_add_client_CA)"); + crypto_msg(M_FATAL, + "Cannot add certificate to client CA list (= SSL_CTX_add_client_CA)"); } } } @@ -1024,7 +1017,9 @@ { if (!SSL_CTX_add_extra_chain_cert(ctx->ctx, sk_X509_value(= ca, i))) { - crypto_msg(M_FATAL, "Cannot add extra certificate to c= hain (SSL_CTX_add_extra_chain_cert)"); + crypto_msg( + M_FATAL, + "Cannot add extra certificate to chain (SSL_CTX_ad= d_extra_chain_cert)"); } } } @@ -1041,7 +1036,8 @@ /* Load Certificate and Private Key */ if (!SSL_CTX_use_CryptoAPI_certificate(ctx->ctx, cryptoapi_cert)) { - crypto_msg(M_FATAL, "Cannot load certificate \"%s\" from Microsoft= Certificate Store", cryptoapi_cert); + crypto_msg(M_FATAL, "Cannot load certificate \"%s\" from Microsoft= Certificate Store", + cryptoapi_cert); } } #endif /* ENABLE_CRYPTOAPI */ @@ -1059,8 +1055,7 @@ * is found in the buffer. If loading more certificates is * optional, break without raising an error */ - if (optional - && ERR_GET_REASON(ERR_peek_error()) =3D=3D PEM_R_NO_START_= LINE) + if (optional && ERR_GET_REASON(ERR_peek_error()) =3D=3D PEM_R_= NO_START_LINE) { /* remove that error from error stack */ (void)ERR_get_error(); @@ -1109,8 +1104,8 @@ } UI_method_set_reader(ui_method, ui_reader); - store_ctx =3D OSSL_STORE_open_ex(uri, tls_libctx, NULL, ui_method, tls= _ctx->ctx, - NULL, NULL, NULL); + store_ctx =3D + OSSL_STORE_open_ex(uri, tls_libctx, NULL, ui_method, tls_ctx->ctx,= NULL, NULL, NULL); if (!store_ctx) { goto end; @@ -1187,14 +1182,13 @@ UI_destroy_method(ui_method); OSSL_STORE_INFO_free(info); OSSL_STORE_close(store_ctx); -#else /* defined(HAVE_OPENSSL_STORE_API */ +#else /* defined(HAVE_OPENSSL_STORE_API */ ASSERT(0); #endif /* defined(HAVE_OPENSSL_STORE_API */ } static void -tls_ctx_load_cert_pem_file(struct tls_root_ctx *ctx, const char *cert_file, - bool cert_file_inline) +tls_ctx_load_cert_pem_file(struct tls_root_ctx *ctx, const char *cert_file= , bool cert_file_inline) { BIO *in =3D NULL; X509 *x =3D NULL; @@ -1204,11 +1198,11 @@ if (cert_file_inline) { - in =3D BIO_new_mem_buf((char *) cert_file, -1); + in =3D BIO_new_mem_buf((char *)cert_file, -1); } else { - in =3D BIO_new_file((char *) cert_file, "r"); + in =3D BIO_new_file((char *)cert_file, "r"); } if (in =3D=3D NULL) @@ -1217,8 +1211,7 @@ goto end; } - x =3D PEM_read_bio_X509(in, NULL, - SSL_CTX_get_default_passwd_cb(ctx->ctx), + x =3D PEM_read_bio_X509(in, NULL, SSL_CTX_get_default_passwd_cb(ctx->c= tx), SSL_CTX_get_default_passwd_cb_userdata(ctx->ctx)= ); if (x =3D=3D NULL) { @@ -1255,8 +1248,7 @@ } void -tls_ctx_load_cert_file(struct tls_root_ctx *ctx, const char *cert_file, - bool cert_file_inline) +tls_ctx_load_cert_file(struct tls_root_ctx *ctx, const char *cert_file, bo= ol cert_file_inline) { if (cert_uri_supported() && !cert_file_inline) { @@ -1283,13 +1275,12 @@ if (priv_key_file_inline) { - in =3D BIO_new_mem_buf((char *) priv_key_file, -1); + in =3D BIO_new_mem_buf((char *)priv_key_file, -1); if (in =3D=3D NULL) { goto end; } - pkey =3D PEM_read_bio_PrivateKey(in, NULL, - SSL_CTX_get_default_passwd_cb(ctx->= ctx), + pkey =3D PEM_read_bio_PrivateKey(in, NULL, SSL_CTX_get_default_pas= swd_cb(ctx->ctx), SSL_CTX_get_default_passwd_cb_userd= ata(ctx->ctx)); } else @@ -1324,8 +1315,7 @@ } void -backend_tls_ctx_reload_crl(struct tls_root_ctx *ssl_ctx, const char *crl_f= ile, - bool crl_inline) +backend_tls_ctx_reload_crl(struct tls_root_ctx *ssl_ctx, const char *crl_f= ile, bool crl_inline) { BIO *in =3D NULL; @@ -1354,7 +1344,7 @@ if (crl_inline) { - in =3D BIO_new_mem_buf((char *) crl_file, -1); + in =3D BIO_new_mem_buf((char *)crl_file, -1); } else { @@ -1363,8 +1353,7 @@ if (in =3D=3D NULL) { - msg(M_WARN, "CRL: cannot read: %s", - print_key_filename(crl_file, crl_inline)); + msg(M_WARN, "CRL: cannot read: %s", print_key_filename(crl_file, c= rl_inline)); goto end; } @@ -1477,9 +1466,8 @@ * @return signature length or -1 on error. */ static int -get_sig_from_man(const unsigned char *dgst, unsigned int dgstlen, - unsigned char *sig, unsigned int siglen, - const char *algorithm) +get_sig_from_man(const unsigned char *dgst, unsigned int dgstlen, unsigned= char *sig, + unsigned int siglen, const char *algorithm) { char *in_b64 =3D NULL; char *out_b64 =3D NULL; @@ -1490,7 +1478,6 @@ if (management && bencret > 0) { out_b64 =3D management_query_pk_sig(management, in_b64, algorithm); - } if (out_b64) { @@ -1504,8 +1491,7 @@ /* sign arbitrary data */ static int -rsa_priv_enc(int flen, const unsigned char *from, unsigned char *to, RSA *= rsa, - int padding) +rsa_priv_enc(int flen, const unsigned char *from, unsigned char *to, RSA *= rsa, int padding) { unsigned int len =3D RSA_size(rsa); int ret =3D -1; @@ -1533,8 +1519,7 @@ ASSERT(NULL !=3D pub_rsa); /* allocate custom RSA method object */ - rsa_meth =3D RSA_meth_new("OpenVPN external private key RSA Method", - RSA_METHOD_FLAG_NO_CHECK); + rsa_meth =3D RSA_meth_new("OpenVPN external private key RSA Method", R= SA_METHOD_FLAG_NO_CHECK); check_malloc_return(rsa_meth); RSA_meth_set_pub_enc(rsa_meth, rsa_pub_enc); RSA_meth_set_pub_dec(rsa_meth, rsa_pub_dec); @@ -1594,7 +1579,7 @@ { /* release the method structure */ const EC_KEY_METHOD *ec_meth =3D EC_KEY_get_method(ec); - EC_KEY_METHOD_free((EC_KEY_METHOD *) ec_meth); + EC_KEY_METHOD_free((EC_KEY_METHOD *)ec_meth); } /* EC_KEY_METHOD callback: sign(). @@ -1633,8 +1618,8 @@ * struct or NULL on error. */ static ECDSA_SIG * -ecdsa_sign_sig(const unsigned char *dgst, int dgstlen, const BIGNUM *in_ki= nv, - const BIGNUM *in_r, EC_KEY *ec) +ecdsa_sign_sig(const unsigned char *dgst, int dgstlen, const BIGNUM *in_ki= nv, const BIGNUM *in_r, + EC_KEY *ec) { ECDSA_SIG *ecsig =3D NULL; unsigned int len =3D ECDSA_size(ec); @@ -1732,8 +1717,7 @@ #ifdef HAVE_XKEY_PROVIDER EVP_PKEY *privkey =3D xkey_load_management_key(tls_libctx, pkey); - if (!privkey - || !SSL_CTX_use_PrivateKey(ctx->ctx, privkey)) + if (!privkey || !SSL_CTX_use_PrivateKey(ctx->ctx, privkey)) { EVP_PKEY_free(privkey); goto cleanup; @@ -1742,7 +1726,7 @@ #else /* ifdef HAVE_XKEY_PROVIDER */ #if OPENSSL_VERSION_NUMBER < 0x30000000L if (EVP_PKEY_id(pkey) =3D=3D EVP_PKEY_RSA) -#else /* OPENSSL_VERSION_NUMBER < 0x30000000L */ +#else /* OPENSSL_VERSION_NUMBER < 0x30000000L */ if (EVP_PKEY_is_a(pkey, "RSA")) #endif /* OPENSSL_VERSION_NUMBER < 0x30000000L */ { @@ -1754,7 +1738,7 @@ #if !defined(OPENSSL_NO_EC) #if OPENSSL_VERSION_NUMBER < 0x30000000L else if (EVP_PKEY_id(pkey) =3D=3D EVP_PKEY_EC) -#else /* OPENSSL_VERSION_NUMBER < 0x30000000L */ +#else /* OPENSSL_VERSION_NUMBER < 0x30000000L */ else if (EVP_PKEY_is_a(pkey, "EC")) #endif /* OPENSSL_VERSION_NUMBER < 0x30000000L */ { @@ -1796,8 +1780,8 @@ } void -tls_ctx_load_ca(struct tls_root_ctx *ctx, const char *ca_file, - bool ca_file_inline, const char *ca_path, bool tls_server) +tls_ctx_load_ca(struct tls_root_ctx *ctx, const char *ca_file, bool ca_fil= e_inline, + const char *ca_path, bool tls_server) { STACK_OF(X509_INFO) *info_stack =3D NULL; STACK_OF(X509_NAME) *cert_names =3D NULL; @@ -1892,8 +1876,7 @@ { crypto_msg(M_WARN, "Cannot load CA certificate file %s (en= try %d did not validate)", - print_key_filename(ca_file, ca_file_inl= ine), - added); + print_key_filename(ca_file, ca_file_inl= ine), added); } prev =3D cnum; } @@ -1909,8 +1892,7 @@ if (!added) { - crypto_msg(M_FATAL, - "Cannot load CA certificate file %s (no entries wer= e read)", + crypto_msg(M_FATAL, "Cannot load CA certificate file %s (no en= tries were read)", print_key_filename(ca_file, ca_file_inline)); } @@ -1918,10 +1900,10 @@ { if (cnum !=3D added) { - crypto_msg(M_FATAL, "Cannot load CA certificate file %s (o= nly %d " + crypto_msg(M_FATAL, + "Cannot load CA certificate file %s (only %d " "of %d entries were valid X509 names)", - print_key_filename(ca_file, ca_file_inline), cn= um, - added); + print_key_filename(ca_file, ca_file_inline), cn= um, added); } } @@ -1961,9 +1943,7 @@ if (in =3D=3D NULL) { crypto_msg(M_FATAL, "Cannot load extra-certs file: %s", - print_key_filename(extra_certs_file, - extra_certs_file_inline)); - + print_key_filename(extra_certs_file, extra_certs_file_i= nline)); } else { @@ -1988,10 +1968,10 @@ #warning BIO_DEBUG defined -static FILE *biofp; /* GLOBAL */ -static bool biofp_toggle; /* GLOBAL */ -static time_t biofp_last_open; /* GLOBAL */ -static const int biofp_reopen_interval =3D 600; /* GLOBAL */ +static FILE *biofp; /* GLOBAL */ +static bool biofp_toggle; /* GLOBAL */ +static time_t biofp_last_open; /* GLOBAL */ +static const int biofp_reopen_interval =3D 600; /* GLOBAL */ static void close_biofp(void) @@ -2031,8 +2011,8 @@ if (len > 0) { open_biofp(); - fprintf(biofp, "BIO_%s %s time=3D%" PRIi64 " bio=3D" ptr_format " = len=3D%d data=3D%s\n", - mode, desc, (int64_t)time(NULL), (ptr_type)bio, len, forma= t_hex(buf, len, 0, &gc)); + fprintf(biofp, "BIO_%s %s time=3D%" PRIi64 " bio=3D" ptr_format " = len=3D%d data=3D%s\n", mode, desc, + (int64_t)time(NULL), (ptr_type)bio, len, format_hex(buf, l= en, 0, &gc)); fflush(biofp); } gc_free(&gc); @@ -2042,8 +2022,8 @@ bio_debug_oc(const char *mode, BIO *bio) { open_biofp(); - fprintf(biofp, "BIO %s time=3D%" PRIi64 " bio=3D" ptr_format "\n", - mode, (int64_t)time(NULL), (ptr_type)bio); + fprintf(biofp, "BIO %s time=3D%" PRIi64 " bio=3D" ptr_format "\n", mod= e, (int64_t)time(NULL), + (ptr_type)bio); fflush(biofp); } @@ -2082,13 +2062,12 @@ } else if (i !=3D size) { - crypto_msg(D_TLS_ERRORS, "TLS ERROR: BIO write %s incomplete %= d/%d", - desc, i, size); + crypto_msg(D_TLS_ERRORS, "TLS ERROR: BIO write %s incomplete %= d/%d", desc, i, size); ret =3D -1; ERR_clear_error(); } else - { /* successful write */ + { /* successful write */ dmsg(D_HANDSHAKE_VERBOSE, "BIO write %s %d bytes", desc, i); ret =3D 1; } @@ -2104,9 +2083,9 @@ static void bio_write_post(const int status, struct buffer *buf) { - if (status =3D=3D 1) /* success status return from bio_write? */ + if (status =3D=3D 1) /* success status return from= bio_write? */ { - memset(BPTR(buf), 0, BLEN(buf)); /* erase data just written */ + memset(BPTR(buf), 0, BLEN(buf)); /* erase data just written */ buf->len =3D 0; } } @@ -2132,7 +2111,7 @@ */ int i =3D BIO_read(bio, BPTR(buf), len); - VALGRIND_MAKE_READABLE((void *) &i, sizeof(i)); + VALGRIND_MAKE_READABLE((void *)&i, sizeof(i)); #ifdef BIO_DEBUG bio_debug_data("read", bio, BPTR(buf), i, desc); @@ -2154,17 +2133,18 @@ buf->len =3D 0; } else - { /* successful read */ + { /* successful read */ dmsg(D_HANDSHAKE_VERBOSE, "BIO read %s %d bytes", desc, i); buf->len =3D i; ret =3D 1; - VALGRIND_MAKE_READABLE((void *) BPTR(buf), BLEN(buf)); + VALGRIND_MAKE_READABLE((void *)BPTR(buf), BLEN(buf)); } return ret; } void -key_state_ssl_init(struct key_state_ssl *ks_ssl, const struct tls_root_ctx= *ssl_ctx, bool is_server, struct tls_session *session) +key_state_ssl_init(struct key_state_ssl *ks_ssl, const struct tls_root_ctx= *ssl_ctx, bool is_server, + struct tls_session *session) { ASSERT(NULL !=3D ssl_ctx); ASSERT(ks_ssl); @@ -2232,8 +2212,7 @@ ASSERT(NULL !=3D ks_ssl); - ret =3D bio_write(ks_ssl->ssl_bio, BPTR(buf), BLEN(buf), - "tls_write_plaintext"); + ret =3D bio_write(ks_ssl->ssl_bio, BPTR(buf), BLEN(buf), "tls_write_pl= aintext"); bio_write_post(ret, buf); perf_pop(); @@ -2337,7 +2316,7 @@ type =3D OBJ_nid2sn(typeid); /* OpenSSL reports rsaEncryption, dsaEncryption and - * id-ecPublicKey, map these values to nicer ones */ + * id-ecPublicKey, map these values to nicer ones */ if (typeid =3D=3D EVP_PKEY_RSA) { type =3D "RSA"; @@ -2355,7 +2334,7 @@ { type =3D "unknown type"; } -#else /* OpenSSL >=3D 3 */ +#else /* OpenSSL >=3D 3 */ type =3D EVP_PKEY_get0_type_name(pkey); if (type =3D=3D NULL) { @@ -2364,8 +2343,7 @@ #endif /* if OPENSSL_VERSION_NUMBER < 0x30000000L */ } - snprintf(buf, buflen, "%d bits %s%s", - EVP_PKEY_bits(pkey), type, curve); + snprintf(buf, buflen, "%d bits %s%s", EVP_PKEY_bits(pkey), type, curve= ); } /** @@ -2385,12 +2363,10 @@ int signature_nid =3D X509_get_signature_nid(cert); if (signature_nid !=3D 0) { - snprintf(sig, sizeof(sig), ", signature: %s", - OBJ_nid2sn(signature_nid)); + snprintf(sig, sizeof(sig), ", signature: %s", OBJ_nid2sn(signature= _nid)); } - snprintf(buf, buflen, ", peer certificate: %s%s", - pkeybuf, sig); + snprintf(buf, buflen, ", peer certificate: %s%s", pkeybuf, sig); EVP_PKEY_free(pkey); } @@ -2408,8 +2384,7 @@ char pkeybuf[128] =3D { 0 }; print_pkey_details(pkey, pkeybuf, sizeof(pkeybuf)); - snprintf(buf, buflen, ", peer temporary key: %s", - pkeybuf); + snprintf(buf, buflen, ", peer temporary key: %s", pkeybuf); EVP_PKEY_free(pkey); } @@ -2471,8 +2446,7 @@ || (defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER >=3D 0= x3090000fL) /* LibreSSL 3.7.x and 3.8.x implement this function but do not export = it * and fail linking with an unresolved symbol */ - if (SSL_get_peer_signature_type_nid(ssl, &peer_sig_type_nid) - && peer_sig_type_nid !=3D NID_undef) + if (SSL_get_peer_signature_type_nid(ssl, &peer_sig_type_nid) && peer_s= ig_type_nid !=3D NID_undef) { peer_sig_type =3D get_sigtype(peer_sig_type_nid); } @@ -2483,8 +2457,7 @@ return; } - snprintf(buf, buflen, ", peer signing digest/type: %s %s", - peer_sig, peer_sig_type); + snprintf(buf, buflen, ", peer signing digest/type: %s %s", peer_sig, p= eer_sig_type); } #if OPENSSL_VERSION_NUMBER >=3D 0x30000000L @@ -2522,11 +2495,8 @@ s1[0] =3D s2[0] =3D s3[0] =3D s4[0] =3D s5[0] =3D 0; ciph =3D SSL_get_current_cipher(ks_ssl->ssl); - snprintf(s1, sizeof(s1), "%s %s, cipher %s %s", - prefix, - SSL_get_version(ks_ssl->ssl), - SSL_CIPHER_get_version(ciph), - SSL_CIPHER_get_name(ciph)); + snprintf(s1, sizeof(s1), "%s %s, cipher %s %s", prefix, SSL_get_versio= n(ks_ssl->ssl), + SSL_CIPHER_get_version(ciph), SSL_CIPHER_get_name(ciph)); X509 *cert =3D SSL_get_peer_certificate(ks_ssl->ssl); if (cert) @@ -2544,9 +2514,7 @@ } void -show_available_tls_ciphers_list(const char *cipher_list, - const char *tls_cert_profile, - bool tls13) +show_available_tls_ciphers_list(const char *cipher_list, const char *tls_c= ert_profile, bool tls13) { struct tls_root_ctx tls_ctx; @@ -2559,8 +2527,7 @@ #if defined(TLS1_3_VERSION) if (tls13) { - SSL_CTX_set_min_proto_version(tls_ctx.ctx, - openssl_tls_version(TLS_VER_1_3)); + SSL_CTX_set_min_proto_version(tls_ctx.ctx, openssl_tls_version(TLS= _VER_1_3)); tls_ctx_restrict_ciphers_tls13(&tls_ctx, cipher_list); } else @@ -2599,8 +2566,7 @@ else if (NULL =3D=3D pair) { /* No translation found, print warning */ - printf("%s (No IANA name known to OpenVPN, use OpenSSL name.)\= n", - cipher_name); + printf("%s (No IANA name known to OpenVPN, use OpenSSL name.)\= n", cipher_name); } else { @@ -2638,7 +2604,7 @@ for (n =3D 0; n < crv_len; n++) { const char *sname; - sname =3D OBJ_nid2sn(curves[n].nid); + sname =3D OBJ_nid2sn(curves[n].nid); if (sname =3D=3D NULL) { sname =3D ""; @@ -2654,7 +2620,7 @@ free(curves); #else /* ifndef OPENSSL_NO_EC */ msg(M_WARN, "Your OpenSSL library was built without elliptic curve sup= port. " - "No curves available."); + "No curves available."); #endif /* ifndef OPENSSL_NO_EC */ } @@ -2678,7 +2644,7 @@ static int provider_unload(OSSL_PROVIDER *prov, void *unused) { - (void) unused; + (void)unused; OSSL_PROVIDER_unload(prov); return 1; } @@ -2716,7 +2682,7 @@ if (!OSSL_PROVIDER_load(tls_libctx, "ovpn.xkey")) { msg(M_NONFATAL, "ERROR: failed loading external key provider: " - "Signing with external keys will not work."); + "Signing with external keys will not work."); } } diff --git a/src/openvpn/ssl_openssl.h b/src/openvpn/ssl_openssl.h index 966bb44..08a3d53 100644 --- a/src/openvpn/ssl_openssl.h +++ b/src/openvpn/ssl_openssl.h @@ -36,17 +36,19 @@ * Structure that wraps the TLS context. Contents differ depending on the * SSL library used. */ -struct tls_root_ctx { +struct tls_root_ctx +{ SSL_CTX *ctx; time_t crl_last_mtime; off_t crl_last_size; }; -struct key_state_ssl { - SSL *ssl; /* SSL object -- new obj created for each = new key */ - BIO *ssl_bio; /* read/write plaintext from here = */ - BIO *ct_in; /* write ciphertext to here */ - BIO *ct_out; /* read ciphertext from here */ +struct key_state_ssl +{ + SSL *ssl; /* SSL object -- new obj created for each new key */ + BIO *ssl_bio; /* read/write plaintext from here */ + BIO *ct_in; /* write ciphertext to here */ + BIO *ct_out; /* read ciphertext from here */ }; /** diff --git a/src/openvpn/ssl_pkt.c b/src/openvpn/ssl_pkt.c index e730e33..b901f87 100644 --- a/src/openvpn/ssl_pkt.c +++ b/src/openvpn/ssl_pkt.c @@ -61,8 +61,7 @@ { ASSERT(co); - const struct key_ctx *ctx =3D (incoming ? &co->key_ctx_bi.decrypt : - &co->key_ctx_bi.encrypt); + const struct key_ctx *ctx =3D (incoming ? &co->key_ctx_bi.decrypt : &c= o->key_ctx_bi.encrypt); ASSERT(ctx->hmac); { @@ -120,8 +119,7 @@ tls_wrap_control(struct tls_wrap_ctx *ctx, uint8_t header, struct buffer *= buf, struct session_id *session_id) { - if (ctx->mode =3D=3D TLS_WRAP_AUTH - || ctx->mode =3D=3D TLS_WRAP_NONE) + if (ctx->mode =3D=3D TLS_WRAP_AUTH || ctx->mode =3D=3D TLS_WRAP_NONE) { ASSERT(session_id_write_prepend(session_id, buf)); ASSERT(buf_write_prepend(buf, &header, sizeof(header))); @@ -148,8 +146,7 @@ if ((header >> P_OPCODE_SHIFT) =3D=3D P_CONTROL_HARD_RESET_CLIENT_= V3 || (header >> P_OPCODE_SHIFT) =3D=3D P_CONTROL_WKC_V1) { - if (!buf_copy(&ctx->work, - ctx->tls_crypt_v2_wkc)) + if (!buf_copy(&ctx->work, ctx->tls_crypt_v2_wkc)) { msg(D_TLS_ERRORS, "Could not append tls-crypt-v2 client ke= y"); buf->len =3D 0; @@ -164,12 +161,8 @@ } void -write_control_auth(struct tls_session *session, - struct key_state *ks, - struct buffer *buf, - struct link_socket_actual **to_link_addr, - int opcode, - int max_ack, +write_control_auth(struct tls_session *session, struct key_state *ks, stru= ct buffer *buf, + struct link_socket_actual **to_link_addr, int opcode, i= nt max_ack, bool prepend_ack) { uint8_t header =3D ks->key_id | (opcode << P_OPCODE_SHIFT); @@ -184,34 +177,30 @@ } ASSERT(link_socket_actual_defined(&ks->remote_addr)); - ASSERT(reliable_ack_write - (ks->rec_ack, ks->lru_acks, buf, &ks->session_id_remote, - max_ack, prepend_ack)); + ASSERT(reliable_ack_write(ks->rec_ack, ks->lru_acks, buf, &ks->session= _id_remote, max_ack, + prepend_ack)); msg(D_TLS_DEBUG, "%s(): %s", __func__, packet_opcode_name(opcode)); - tls_wrap_control(tls_session_get_tls_wrap(session, ks->key_id), header= , buf, &session->session_id); + tls_wrap_control(tls_session_get_tls_wrap(session, ks->key_id), header= , buf, + &session->session_id); *to_link_addr =3D &ks->remote_addr; } bool -read_control_auth(struct buffer *buf, - struct tls_wrap_ctx *ctx, - const struct link_socket_actual *from, - const struct tls_options *opt, +read_control_auth(struct buffer *buf, struct tls_wrap_ctx *ctx, + const struct link_socket_actual *from, const struct tls_= options *opt, bool initial_packet) { struct gc_arena gc =3D gc_new(); bool ret =3D false; const uint8_t opcode =3D *(BPTR(buf)) >> P_OPCODE_SHIFT; - if ((opcode =3D=3D P_CONTROL_HARD_RESET_CLIENT_V3 - || opcode =3D=3D P_CONTROL_WKC_V1) + if ((opcode =3D=3D P_CONTROL_HARD_RESET_CLIENT_V3 || opcode =3D=3D P_C= ONTROL_WKC_V1) && !tls_crypt_v2_extract_client_key(buf, ctx, opt, initial_packet)) { - msg(D_TLS_ERRORS, - "TLS Error: can not extract tls-crypt-v2 client key from %s", + msg(D_TLS_ERRORS, "TLS Error: can not extract tls-crypt-v2 client = key from %s", print_link_socket_actual(from, &gc)); goto cleanup; } @@ -223,8 +212,7 @@ /* move the hmac record to the front of the packet */ if (!swap_hmac(buf, &ctx->opt, true)) { - msg(D_TLS_ERRORS, - "TLS Error: cannot locate HMAC in incoming packet from %s", + msg(D_TLS_ERRORS, "TLS Error: cannot locate HMAC in incoming p= acket from %s", print_link_socket_actual(from, &gc)); gc_free(&gc); return false; @@ -235,12 +223,10 @@ openvpn_decrypt(buf, null, &ctx->opt, NULL, BPTR(buf)); if (!buf->len) { - msg(D_TLS_ERRORS, - "TLS Error: incoming packet authentication failed from %s", + msg(D_TLS_ERRORS, "TLS Error: incoming packet authentication f= ailed from %s", print_link_socket_actual(from, &gc)); goto cleanup; } - } else if (ctx->mode =3D=3D TLS_WRAP_CRYPT) { @@ -304,17 +290,14 @@ * on the UDP port listener in --mode server mode. */ enum first_packet_verdict -tls_pre_decrypt_lite(const struct tls_auth_standalone *tas, - struct tls_pre_decrypt_state *state, - const struct link_socket_actual *from, - const struct buffer *buf) +tls_pre_decrypt_lite(const struct tls_auth_standalone *tas, struct tls_pre= _decrypt_state *state, + const struct link_socket_actual *from, const struct b= uffer *buf) { struct gc_arena gc =3D gc_new(); /* A packet needs to have at least an opcode and session id */ if (buf->len < (1 + SID_SIZE)) { - dmsg(D_TLS_STATE_ERRORS, - "TLS State Error: Too short packet (length %d) received from= %s", + dmsg(D_TLS_STATE_ERRORS, "TLS State Error: Too short packet (lengt= h %d) received from %s", buf->len, print_link_socket_actual(from, &gc)); goto error; } @@ -328,27 +311,21 @@ * scrutinize carefully */ /* Allow only the reset packet or the first packet of the actual hands= hake. */ - if (op !=3D P_CONTROL_HARD_RESET_CLIENT_V2 - && op !=3D P_CONTROL_HARD_RESET_CLIENT_V3 - && op !=3D P_CONTROL_V1 - && op !=3D P_CONTROL_WKC_V1 - && op !=3D P_ACK_V1) + if (op !=3D P_CONTROL_HARD_RESET_CLIENT_V2 && op !=3D P_CONTROL_HARD_R= ESET_CLIENT_V3 + && op !=3D P_CONTROL_V1 && op !=3D P_CONTROL_WKC_V1 && op !=3D P_A= CK_V1) { /* * This can occur due to bogus data or DoS packets. */ - dmsg(D_TLS_STATE_ERRORS, - "TLS State Error: No TLS state for client %s, opcode=3D%d", - print_link_socket_actual(from, &gc), - op); + dmsg(D_TLS_STATE_ERRORS, "TLS State Error: No TLS state for client= %s, opcode=3D%d", + print_link_socket_actual(from, &gc), op); goto error; } if (key_id !=3D 0) { dmsg(D_TLS_STATE_ERRORS, - "TLS State Error: Unknown key ID (%d) received from %s -- 0 w= as expected", - key_id, + "TLS State Error: Unknown key ID (%d) received from %s -- 0 w= as expected", key_id, print_link_socket_actual(from, &gc)); goto error; } @@ -360,8 +337,7 @@ if (!session_id_read(&state->peer_session_id, &tmp) || !session_id_defined(&state->peer_session_id)) { - msg(D_TLS_ERRORS, - "TLS Error: session-id not found in packet from %s", + msg(D_TLS_ERRORS, "TLS Error: session-id not found in packet from = %s", print_link_socket_actual(from, &gc)); goto error; } @@ -372,8 +348,7 @@ /* HMAC test and unwrapping the encrypted part of the control message * into newbuf or just setting newbuf to point to the start of control * message */ - bool status =3D read_control_auth(&state->newbuf, &state->tls_wrap_tmp, - from, NULL, true); + bool status =3D read_control_auth(&state->newbuf, &state->tls_wrap_tmp= , from, NULL, true); if (!status) { @@ -425,11 +400,8 @@ struct buffer -tls_reset_standalone(struct tls_wrap_ctx *ctx, - struct tls_auth_standalone *tas, - struct session_id *own_sid, - struct session_id *remote_sid, - uint8_t header, +tls_reset_standalone(struct tls_wrap_ctx *ctx, struct tls_auth_standalone = *tas, + struct session_id *own_sid, struct session_id *remote= _sid, uint8_t header, bool request_resend_wkc) { /* Copy buffer here to point at the same data but allow tls_wrap_contr= ol @@ -484,12 +456,11 @@ } struct session_id -calculate_session_id_hmac(struct session_id client_sid, - const struct openvpn_sockaddr *from, - hmac_ctx_t *hmac, - int handwindow, int offset) +calculate_session_id_hmac(struct session_id client_sid, const struct openv= pn_sockaddr *from, + hmac_ctx_t *hmac, int handwindow, int offset) { - union { + union + { uint8_t hmac_result[SHA256_DIGEST_LENGTH]; struct session_id sid; } result; @@ -497,23 +468,22 @@ /* Get the valid time quantisation for our hmac, * we divide time by handwindow/2 and allow the previous * and future session time if specified by offset */ - uint32_t session_id_time =3D ntohl(now/((handwindow+1)/2) + offset); + uint32_t session_id_time =3D ntohl(now / ((handwindow + 1) / 2) + offs= et); hmac_ctx_reset(hmac); /* We do not care about endian here since it does not need to be * portable */ - hmac_ctx_update(hmac, (const uint8_t *) &session_id_time, - sizeof(session_id_time)); + hmac_ctx_update(hmac, (const uint8_t *)&session_id_time, sizeof(sessio= n_id_time)); /* add client IP and port */ switch (from->addr.sa.sa_family) { case AF_INET: - hmac_ctx_update(hmac, (const uint8_t *) &from->addr.in4, sizeo= f(struct sockaddr_in)); + hmac_ctx_update(hmac, (const uint8_t *)&from->addr.in4, sizeof= (struct sockaddr_in)); break; case AF_INET6: - hmac_ctx_update(hmac, (const uint8_t *) &from->addr.in6, sizeo= f(struct sockaddr_in6)); + hmac_ctx_update(hmac, (const uint8_t *)&from->addr.in6, sizeof= (struct sockaddr_in6)); break; } @@ -526,10 +496,8 @@ } bool -check_session_id_hmac(struct tls_pre_decrypt_state *state, - const struct openvpn_sockaddr *from, - hmac_ctx_t *hmac, - int handwindow) +check_session_id_hmac(struct tls_pre_decrypt_state *state, const struct op= envpn_sockaddr *from, + hmac_ctx_t *hmac, int handwindow) { if (!from) { @@ -574,7 +542,7 @@ } /* include the NUL byte and ensure NUL termination */ - cmdlen +=3D 1; + cmdlen +=3D 1; /* Construct a buffer that only holds the current command and * its closing NUL byte */ diff --git a/src/openvpn/ssl_pkt.h b/src/openvpn/ssl_pkt.h index 1e9f4e9..8fe4880 100644 --- a/src/openvpn/ssl_pkt.h +++ b/src/openvpn/ssl_pkt.h @@ -35,40 +35,40 @@ #include "ssl_common.h" /* packet opcode (high 5 bits) and key-id (low 3 bits) are combined in one= byte */ -#define P_KEY_ID_MASK 0x07 -#define P_OPCODE_SHIFT 3 +#define P_KEY_ID_MASK 0x07 +#define P_OPCODE_SHIFT 3 /* packet opcodes -- the V1 is intended to allow protocol changes in the f= uture */ -#define P_CONTROL_HARD_RESET_CLIENT_V1 1 /* initial key from client, f= orget previous state */ -#define P_CONTROL_HARD_RESET_SERVER_V1 2 /* initial key from server, f= orget previous state */ -#define P_CONTROL_SOFT_RESET_V1 3 /* new key, graceful transiti= on from old to new key */ -#define P_CONTROL_V1 4 /* control channel packet (us= ually TLS ciphertext) */ -#define P_ACK_V1 5 /* acknowledgement for packet= s received */ -#define P_DATA_V1 6 /* data channel packet */ -#define P_DATA_V2 9 /* data channel packet with p= eer-id */ +#define P_CONTROL_HARD_RESET_CLIENT_V1 1 /* initial key from client, forge= t previous state */ +#define P_CONTROL_HARD_RESET_SERVER_V1 2 /* initial key from server, forge= t previous state */ +#define P_CONTROL_SOFT_RESET_V1 3 /* new key, graceful transition f= rom old to new key */ +#define P_CONTROL_V1 4 /* control channel packet (usuall= y TLS ciphertext) */ +#define P_ACK_V1 5 /* acknowledgement for packets re= ceived */ +#define P_DATA_V1 6 /* data channel packet */ +#define P_DATA_V2 9 /* data channel packet with peer-= id */ /* indicates key_method >=3D 2 */ -#define P_CONTROL_HARD_RESET_CLIENT_V2 7 /* initial key from client, f= orget previous state */ -#define P_CONTROL_HARD_RESET_SERVER_V2 8 /* initial key from server, f= orget previous state */ +#define P_CONTROL_HARD_RESET_CLIENT_V2 7 /* initial key from client, forge= t previous state */ +#define P_CONTROL_HARD_RESET_SERVER_V2 8 /* initial key from server, forge= t previous state */ /* indicates key_method >=3D 2 and client-specific tls-crypt key */ -#define P_CONTROL_HARD_RESET_CLIENT_V3 10 /* initial key from client, f= orget previous state */ +#define P_CONTROL_HARD_RESET_CLIENT_V3 10 /* initial key from client, forg= et previous state */ /* Variant of P_CONTROL_V1 but with appended wrapped key * like P_CONTROL_HARD_RESET_CLIENT_V3 */ -#define P_CONTROL_WKC_V1 11 +#define P_CONTROL_WKC_V1 11 /* define the range of legal opcodes * Since we do no longer support key-method 1 we consider * the v1 op codes invalid */ -#define P_FIRST_OPCODE 3 -#define P_LAST_OPCODE 11 +#define P_FIRST_OPCODE 3 +#define P_LAST_OPCODE 11 /* * Define number of buffers for send and receive in the reliability layer. */ -#define TLS_RELIABLE_N_SEND_BUFFERS 6 /* also window size for reliability= layer */ -#define TLS_RELIABLE_N_REC_BUFFERS 12 +#define TLS_RELIABLE_N_SEND_BUFFERS 6 /* also window size for reliability = layer */ +#define TLS_RELIABLE_N_REC_BUFFERS 12 /* * Used in --mode server mode to check tls-auth signature on initial @@ -81,7 +81,8 @@ struct frame frame; }; -enum first_packet_verdict { +enum first_packet_verdict +{ /** This packet is a valid reset packet from the peer (all but tls-cry= pt-v2) */ VERDICT_VALID_RESET_V2, /** This is a valid v3 reset (tls-crypt-v2) */ @@ -101,7 +102,8 @@ * struct that stores the temporary data for the tls lite decrypt * functions */ -struct tls_pre_decrypt_state { +struct tls_pre_decrypt_state +{ struct tls_wrap_ctx tls_wrap_tmp; struct buffer newbuf; struct session_id peer_session_id; @@ -144,11 +146,10 @@ * @li False if the packet is not valid, did not pass the HMAC firewall * test, or some other error occurred. */ -enum first_packet_verdict -tls_pre_decrypt_lite(const struct tls_auth_standalone *tas, - struct tls_pre_decrypt_state *state, - const struct link_socket_actual *from, - const struct buffer *buf); +enum first_packet_verdict tls_pre_decrypt_lite(const struct tls_auth_stand= alone *tas, + struct tls_pre_decrypt_stat= e *state, + const struct link_socket_ac= tual *from, + const struct buffer *buf); /* Creates an SHA256 HMAC context with a random key that is used for the * session id. @@ -170,11 +171,9 @@ * @param offset offset to 'now' to use * @return the expected server session id */ -struct session_id -calculate_session_id_hmac(struct session_id client_sid, - const struct openvpn_sockaddr *from, - hmac_ctx_t *hmac, - int handwindow, int offset); +struct session_id calculate_session_id_hmac(struct session_id client_sid, + const struct openvpn_sockaddr = *from, hmac_ctx_t *hmac, + int handwindow, int offset); /** * Checks if a control packet has a correct HMAC server session id @@ -185,24 +184,15 @@ * @param handwindow the quantisation of the current time * @return the expected server session id */ -bool -check_session_id_hmac(struct tls_pre_decrypt_state *state, - const struct openvpn_sockaddr *from, - hmac_ctx_t *hmac, - int handwindow); +bool check_session_id_hmac(struct tls_pre_decrypt_state *state, const stru= ct openvpn_sockaddr *from, + hmac_ctx_t *hmac, int handwindow); /* * Write a control channel authentication record. */ -void -write_control_auth(struct tls_session *session, - struct key_state *ks, - struct buffer *buf, - struct link_socket_actual **to_link_addr, - int opcode, - int max_ack, - bool prepend_ack); - +void write_control_auth(struct tls_session *session, struct key_state *ks,= struct buffer *buf, + struct link_socket_actual **to_link_addr, int opco= de, int max_ack, + bool prepend_ack); /** @@ -214,12 +204,9 @@ * @param initial_packet whether this is the initial packet for the con= nection * @return if the packet was successfully processed */ -bool -read_control_auth(struct buffer *buf, - struct tls_wrap_ctx *ctx, - const struct link_socket_actual *from, - const struct tls_options *opt, - bool initial_packet); +bool read_control_auth(struct buffer *buf, struct tls_wrap_ctx *ctx, + const struct link_socket_actual *from, const struct= tls_options *opt, + bool initial_packet); /** @@ -227,13 +214,9 @@ * from the tls pre decrypt state. * */ -struct buffer -tls_reset_standalone(struct tls_wrap_ctx *ctx, - struct tls_auth_standalone *tas, - struct session_id *own_sid, - struct session_id *remote_sid, - uint8_t header, - bool request_resend_wkc); +struct buffer tls_reset_standalone(struct tls_wrap_ctx *ctx, struct tls_au= th_standalone *tas, + struct session_id *own_sid, struct sess= ion_id *remote_sid, + uint8_t header, bool request_resend_wkc= ); /** @@ -246,8 +229,7 @@ * with length 0 if there is no message or the message has * invalid characters. */ -struct buffer -extract_command_buffer(struct buffer *buf, struct gc_arena *gc); +struct buffer extract_command_buffer(struct buffer *buf, struct gc_arena *= gc); static inline const char * packet_opcode_name(int op) @@ -323,14 +305,14 @@ * but the network time part of the packet id takes care of that. And * this is also a rather theoretical scenario as it still needs more than * 2^31 control channel packets to happen */ -#define EARLY_NEG_MASK 0xff000000 -#define EARLY_NEG_START 0x0f000000 +#define EARLY_NEG_MASK 0xff000000 +#define EARLY_NEG_START 0x0f000000 /* Early negotiation that part of the server response in the RESET_V2 pack= et. * Since clients that announce early negotiation support will treat the pa= yload * of reset packets special and parse it as TLV messages. * as TLV (type, length, value) */ -#define TLV_TYPE_EARLY_NEG_FLAGS 0x0001 -#define EARLY_NEG_FLAG_RESEND_WKC 0x0001 +#define TLV_TYPE_EARLY_NEG_FLAGS 0x0001 +#define EARLY_NEG_FLAG_RESEND_WKC 0x0001 #endif /* ifndef SSL_PKT_H */ diff --git a/src/openvpn/ssl_util.c b/src/openvpn/ssl_util.c index 6e00630..918a1f1 100644 --- a/src/openvpn/ssl_util.c +++ b/src/openvpn/ssl_util.c @@ -28,8 +28,7 @@ #include "ssl_util.h" char * -extract_var_peer_info(const char *peer_info, const char *var, - struct gc_arena *gc) +extract_var_peer_info(const char *peer_info, const char *var, struct gc_ar= ena *gc) { if (!peer_info) { @@ -77,8 +76,10 @@ options_string_compat_lzo(const char *options, struct gc_arena *gc) { /* Example string without and with comp-lzo, i.e. input/output of this= function */ - /* w/o comp: 'V4,dev-type tun,link-mtu 1457,tun-mtu 1400,proto UDPv4,a= uth SHA1,keysize 128,key-method 2,tls-server' */ - /* comp-lzo: 'V4,dev-type tun,link-mtu 1458,tun-mtu 1400,proto UDPv4,c= omp-lzo,auth SHA1,keysize 128,key-method 2,tls-server' */ + /* w/o comp: 'V4,dev-type tun,link-mtu 1457,tun-mtu 1400,proto UDPv4,a= uth SHA1,keysize + * 128,key-method 2,tls-server' */ + /* comp-lzo: 'V4,dev-type tun,link-mtu 1458,tun-mtu 1400,proto UDPv4,c= omp-lzo,auth SHA1,keysize + * 128,key-method 2,tls-server' */ /* Note: since this function is used only in a very limited scope it m= akes * assumptions how the string looks. Since we locally generated the st= ring @@ -118,146 +119,156 @@ * SSL/TLS Cipher suite name translation table */ static const tls_cipher_name_pair tls_cipher_name_translation_table[] =3D { - {"ADH-SEED-SHA", "TLS-DH-anon-WITH-SEED-CBC-SHA"}, - {"AES128-GCM-SHA256", "TLS-RSA-WITH-AES-128-GCM-SHA256"}, - {"AES128-SHA256", "TLS-RSA-WITH-AES-128-CBC-SHA256"}, - {"AES128-SHA", "TLS-RSA-WITH-AES-128-CBC-SHA"}, - {"AES256-GCM-SHA384", "TLS-RSA-WITH-AES-256-GCM-SHA384"}, - {"AES256-SHA256", "TLS-RSA-WITH-AES-256-CBC-SHA256"}, - {"AES256-SHA", "TLS-RSA-WITH-AES-256-CBC-SHA"}, - {"CAMELLIA128-SHA256", "TLS-RSA-WITH-CAMELLIA-128-CBC-SHA256"}, - {"CAMELLIA128-SHA", "TLS-RSA-WITH-CAMELLIA-128-CBC-SHA"}, - {"CAMELLIA256-SHA256", "TLS-RSA-WITH-CAMELLIA-256-CBC-SHA256"}, - {"CAMELLIA256-SHA", "TLS-RSA-WITH-CAMELLIA-256-CBC-SHA"}, - {"DES-CBC3-SHA", "TLS-RSA-WITH-3DES-EDE-CBC-SHA"}, - {"DES-CBC-SHA", "TLS-RSA-WITH-DES-CBC-SHA"}, - {"DH-DSS-SEED-SHA", "TLS-DH-DSS-WITH-SEED-CBC-SHA"}, - {"DHE-DSS-AES128-GCM-SHA256", "TLS-DHE-DSS-WITH-AES-128-GCM-SHA256"}, - {"DHE-DSS-AES128-SHA256", "TLS-DHE-DSS-WITH-AES-128-CBC-SHA256"}, - {"DHE-DSS-AES128-SHA", "TLS-DHE-DSS-WITH-AES-128-CBC-SHA"}, - {"DHE-DSS-AES256-GCM-SHA384", "TLS-DHE-DSS-WITH-AES-256-GCM-SHA384"}, - {"DHE-DSS-AES256-SHA256", "TLS-DHE-DSS-WITH-AES-256-CBC-SHA256"}, - {"DHE-DSS-AES256-SHA", "TLS-DHE-DSS-WITH-AES-256-CBC-SHA"}, - {"DHE-DSS-CAMELLIA128-SHA256", "TLS-DHE-DSS-WITH-CAMELLIA-128-CBC-SHA2= 56"}, - {"DHE-DSS-CAMELLIA128-SHA", "TLS-DHE-DSS-WITH-CAMELLIA-128-CBC-SHA"}, - {"DHE-DSS-CAMELLIA256-SHA256", "TLS-DHE-DSS-WITH-CAMELLIA-256-CBC-SHA2= 56"}, - {"DHE-DSS-CAMELLIA256-SHA", "TLS-DHE-DSS-WITH-CAMELLIA-256-CBC-SHA"}, - {"DHE-DSS-SEED-SHA", "TLS-DHE-DSS-WITH-SEED-CBC-SHA"}, - {"DHE-RSA-AES128-GCM-SHA256", "TLS-DHE-RSA-WITH-AES-128-GCM-SHA256"}, - {"DHE-RSA-AES128-SHA256", "TLS-DHE-RSA-WITH-AES-128-CBC-SHA256"}, - {"DHE-RSA-AES128-SHA", "TLS-DHE-RSA-WITH-AES-128-CBC-SHA"}, - {"DHE-RSA-AES256-GCM-SHA384", "TLS-DHE-RSA-WITH-AES-256-GCM-SHA384"}, - {"DHE-RSA-AES256-SHA256", "TLS-DHE-RSA-WITH-AES-256-CBC-SHA256"}, - {"DHE-RSA-AES256-SHA", "TLS-DHE-RSA-WITH-AES-256-CBC-SHA"}, - {"DHE-RSA-CAMELLIA128-SHA256", "TLS-DHE-RSA-WITH-CAMELLIA-128-CBC-SHA2= 56"}, - {"DHE-RSA-CAMELLIA128-SHA", "TLS-DHE-RSA-WITH-CAMELLIA-128-CBC-SHA"}, - {"DHE-RSA-CAMELLIA256-SHA256", "TLS-DHE-RSA-WITH-CAMELLIA-256-CBC-SHA2= 56"}, - {"DHE-RSA-CAMELLIA256-SHA", "TLS-DHE-RSA-WITH-CAMELLIA-256-CBC-SHA"}, - {"DHE-RSA-CHACHA20-POLY1305", "TLS-DHE-RSA-WITH-CHACHA20-POLY1305-SHA2= 56"}, - {"DHE-RSA-SEED-SHA", "TLS-DHE-RSA-WITH-SEED-CBC-SHA"}, - {"DH-RSA-SEED-SHA", "TLS-DH-RSA-WITH-SEED-CBC-SHA"}, - {"ECDH-ECDSA-AES128-GCM-SHA256", "TLS-ECDH-ECDSA-WITH-AES-128-GCM-SHA2= 56"}, - {"ECDH-ECDSA-AES128-SHA256", "TLS-ECDH-ECDSA-WITH-AES-128-CBC-SHA256"}, - {"ECDH-ECDSA-AES128-SHA", "TLS-ECDH-ECDSA-WITH-AES-128-CBC-SHA"}, - {"ECDH-ECDSA-AES256-GCM-SHA384", "TLS-ECDH-ECDSA-WITH-AES-256-GCM-SHA3= 84"}, - {"ECDH-ECDSA-AES256-SHA256", "TLS-ECDH-ECDSA-WITH-AES-256-CBC-SHA256"}, - {"ECDH-ECDSA-AES256-SHA384", "TLS-ECDH-ECDSA-WITH-AES-256-CBC-SHA384"}, - {"ECDH-ECDSA-AES256-SHA", "TLS-ECDH-ECDSA-WITH-AES-256-CBC-SHA"}, - {"ECDH-ECDSA-CAMELLIA128-SHA256", "TLS-ECDH-ECDSA-WITH-CAMELLIA-128-CB= C-SHA256"}, - {"ECDH-ECDSA-CAMELLIA128-SHA", "TLS-ECDH-ECDSA-WITH-CAMELLIA-128-CBC-S= HA"}, - {"ECDH-ECDSA-CAMELLIA256-SHA256", "TLS-ECDH-ECDSA-WITH-CAMELLIA-256-CB= C-SHA256"}, - {"ECDH-ECDSA-CAMELLIA256-SHA", "TLS-ECDH-ECDSA-WITH-CAMELLIA-256-CBC-S= HA"}, - {"ECDH-ECDSA-DES-CBC3-SHA", "TLS-ECDH-ECDSA-WITH-3DES-EDE-CBC-SHA"}, - {"ECDH-ECDSA-DES-CBC-SHA", "TLS-ECDH-ECDSA-WITH-DES-CBC-SHA"}, - {"ECDH-ECDSA-RC4-SHA", "TLS-ECDH-ECDSA-WITH-RC4-128-SHA"}, - {"ECDHE-ECDSA-AES128-GCM-SHA256", "TLS-ECDHE-ECDSA-WITH-AES-128-GCM-SH= A256"}, - {"ECDHE-ECDSA-AES128-SHA256", "TLS-ECDHE-ECDSA-WITH-AES-128-CBC-SHA256= "}, - {"ECDHE-ECDSA-AES128-SHA384", "TLS-ECDHE-ECDSA-WITH-AES-128-CBC-SHA384= "}, - {"ECDHE-ECDSA-AES128-SHA", "TLS-ECDHE-ECDSA-WITH-AES-128-CBC-SHA"}, - {"ECDHE-ECDSA-AES256-GCM-SHA384", "TLS-ECDHE-ECDSA-WITH-AES-256-GCM-SH= A384"}, - {"ECDHE-ECDSA-AES256-SHA256", "TLS-ECDHE-ECDSA-WITH-AES-256-CBC-SHA256= "}, - {"ECDHE-ECDSA-AES256-SHA384", "TLS-ECDHE-ECDSA-WITH-AES-256-CBC-SHA384= "}, - {"ECDHE-ECDSA-AES256-SHA", "TLS-ECDHE-ECDSA-WITH-AES-256-CBC-SHA"}, - {"ECDHE-ECDSA-CAMELLIA128-SHA256", "TLS-ECDHE-ECDSA-WITH-CAMELLIA-128-= CBC-SHA256"}, - {"ECDHE-ECDSA-CAMELLIA128-SHA", "TLS-ECDHE-ECDSA-WITH-CAMELLIA-128-CBC= -SHA"}, - {"ECDHE-ECDSA-CAMELLIA256-SHA256", "TLS-ECDHE-ECDSA-WITH-CAMELLIA-256-= CBC-SHA256"}, - {"ECDHE-ECDSA-CAMELLIA256-SHA", "TLS-ECDHE-ECDSA-WITH-CAMELLIA-256-CBC= -SHA"}, - {"ECDHE-ECDSA-CHACHA20-POLY1305", "TLS-ECDHE-ECDSA-WITH-CHACHA20-POLY1= 305-SHA256"}, - {"ECDHE-ECDSA-DES-CBC3-SHA", "TLS-ECDHE-ECDSA-WITH-3DES-EDE-CBC-SHA"}, - {"ECDHE-ECDSA-DES-CBC-SHA", "TLS-ECDHE-ECDSA-WITH-DES-CBC-SHA"}, - {"ECDHE-ECDSA-RC4-SHA", "TLS-ECDHE-ECDSA-WITH-RC4-128-SHA"}, - {"ECDHE-RSA-AES128-GCM-SHA256", "TLS-ECDHE-RSA-WITH-AES-128-GCM-SHA256= "}, - {"ECDHE-RSA-AES128-SHA256", "TLS-ECDHE-RSA-WITH-AES-128-CBC-SHA256"}, - {"ECDHE-RSA-AES128-SHA384", "TLS-ECDHE-RSA-WITH-AES-128-CBC-SHA384"}, - {"ECDHE-RSA-AES128-SHA", "TLS-ECDHE-RSA-WITH-AES-128-CBC-SHA"}, - {"ECDHE-RSA-AES256-GCM-SHA384", "TLS-ECDHE-RSA-WITH-AES-256-GCM-SHA384= "}, - {"ECDHE-RSA-AES256-SHA256", "TLS-ECDHE-RSA-WITH-AES-256-CBC-SHA256"}, - {"ECDHE-RSA-AES256-SHA384", "TLS-ECDHE-RSA-WITH-AES-256-CBC-SHA384"}, - {"ECDHE-RSA-AES256-SHA", "TLS-ECDHE-RSA-WITH-AES-256-CBC-SHA"}, - {"ECDHE-RSA-CAMELLIA128-SHA256", "TLS-ECDHE-RSA-WITH-CAMELLIA-128-CBC-= SHA256"}, - {"ECDHE-RSA-CAMELLIA128-SHA", "TLS-ECDHE-RSA-WITH-CAMELLIA-128-CBC-SHA= "}, - {"ECDHE-RSA-CAMELLIA256-SHA256", "TLS-ECDHE-RSA-WITH-CAMELLIA-256-CBC-= SHA256"}, - {"ECDHE-RSA-CAMELLIA256-SHA", "TLS-ECDHE-RSA-WITH-CAMELLIA-256-CBC-SHA= "}, - {"ECDHE-RSA-CHACHA20-POLY1305", "TLS-ECDHE-RSA-WITH-CHACHA20-POLY1305-= SHA256"}, - {"ECDHE-RSA-DES-CBC3-SHA", "TLS-ECDHE-RSA-WITH-3DES-EDE-CBC-SHA"}, - {"ECDHE-RSA-DES-CBC-SHA", "TLS-ECDHE-RSA-WITH-DES-CBC-SHA"}, - {"ECDHE-RSA-RC4-SHA", "TLS-ECDHE-RSA-WITH-RC4-128-SHA"}, - {"ECDH-RSA-AES128-GCM-SHA256", "TLS-ECDH-RSA-WITH-AES-128-GCM-SHA256"}, - {"ECDH-RSA-AES128-SHA256", "TLS-ECDH-RSA-WITH-AES-128-CBC-SHA256"}, - {"ECDH-RSA-AES128-SHA384", "TLS-ECDH-RSA-WITH-AES-128-CBC-SHA384"}, - {"ECDH-RSA-AES128-SHA", "TLS-ECDH-RSA-WITH-AES-128-CBC-SHA"}, - {"ECDH-RSA-AES256-GCM-SHA384", "TLS-ECDH-RSA-WITH-AES-256-GCM-SHA384"}, - {"ECDH-RSA-AES256-SHA256", "TLS-ECDH-RSA-WITH-AES-256-CBC-SHA256"}, - {"ECDH-RSA-AES256-SHA384", "TLS-ECDH-RSA-WITH-AES-256-CBC-SHA384"}, - {"ECDH-RSA-AES256-SHA", "TLS-ECDH-RSA-WITH-AES-256-CBC-SHA"}, - {"ECDH-RSA-CAMELLIA128-SHA256", "TLS-ECDH-RSA-WITH-CAMELLIA-128-CBC-SH= A256"}, - {"ECDH-RSA-CAMELLIA128-SHA", "TLS-ECDH-RSA-WITH-CAMELLIA-128-CBC-SHA"}, - {"ECDH-RSA-CAMELLIA256-SHA256", "TLS-ECDH-RSA-WITH-CAMELLIA-256-CBC-SH= A256"}, - {"ECDH-RSA-CAMELLIA256-SHA", "TLS-ECDH-RSA-WITH-CAMELLIA-256-CBC-SHA"}, - {"ECDH-RSA-DES-CBC3-SHA", "TLS-ECDH-RSA-WITH-3DES-EDE-CBC-SHA"}, - {"ECDH-RSA-DES-CBC-SHA", "TLS-ECDH-RSA-WITH-DES-CBC-SHA"}, - {"ECDH-RSA-RC4-SHA", "TLS-ECDH-RSA-WITH-RC4-128-SHA"}, - {"EDH-DSS-DES-CBC3-SHA", "TLS-DHE-DSS-WITH-3DES-EDE-CBC-SHA"}, - {"EDH-DSS-DES-CBC-SHA", "TLS-DHE-DSS-WITH-DES-CBC-SHA"}, - {"EDH-RSA-DES-CBC3-SHA", "TLS-DHE-RSA-WITH-3DES-EDE-CBC-SHA"}, - {"EDH-RSA-DES-CBC-SHA", "TLS-DHE-RSA-WITH-DES-CBC-SHA"}, - {"EXP-DES-CBC-SHA", "TLS-RSA-EXPORT-WITH-DES40-CBC-SHA"}, - {"EXP-EDH-DSS-DES-CBC-SHA", "TLS-DH-DSS-EXPORT-WITH-DES40-CBC-SHA"}, - {"EXP-EDH-RSA-DES-CBC-SHA", "TLS-DH-RSA-EXPORT-WITH-DES40-CBC-SHA"}, - {"EXP-RC2-CBC-MD5", "TLS-RSA-EXPORT-WITH-RC2-CBC-40-MD5"}, - {"EXP-RC4-MD5", "TLS-RSA-EXPORT-WITH-RC4-40-MD5"}, - {"NULL-MD5", "TLS-RSA-WITH-NULL-MD5"}, - {"NULL-SHA256", "TLS-RSA-WITH-NULL-SHA256"}, - {"NULL-SHA", "TLS-RSA-WITH-NULL-SHA"}, - {"PSK-3DES-EDE-CBC-SHA", "TLS-PSK-WITH-3DES-EDE-CBC-SHA"}, - {"PSK-AES128-CBC-SHA", "TLS-PSK-WITH-AES-128-CBC-SHA"}, - {"PSK-AES256-CBC-SHA", "TLS-PSK-WITH-AES-256-CBC-SHA"}, - {"PSK-RC4-SHA", "TLS-PSK-WITH-RC4-128-SHA"}, - {"RC4-MD5", "TLS-RSA-WITH-RC4-128-MD5"}, - {"RC4-SHA", "TLS-RSA-WITH-RC4-128-SHA"}, - {"SEED-SHA", "TLS-RSA-WITH-SEED-CBC-SHA"}, - {"SRP-DSS-3DES-EDE-CBC-SHA", "TLS-SRP-SHA-DSS-WITH-3DES-EDE-CBC-SHA"}, - {"SRP-DSS-AES-128-CBC-SHA", "TLS-SRP-SHA-DSS-WITH-AES-128-CBC-SHA"}, - {"SRP-DSS-AES-256-CBC-SHA", "TLS-SRP-SHA-DSS-WITH-AES-256-CBC-SHA"}, - {"SRP-RSA-3DES-EDE-CBC-SHA", "TLS-SRP-SHA-RSA-WITH-3DES-EDE-CBC-SHA"}, - {"SRP-RSA-AES-128-CBC-SHA", "TLS-SRP-SHA-RSA-WITH-AES-128-CBC-SHA"}, - {"SRP-RSA-AES-256-CBC-SHA", "TLS-SRP-SHA-RSA-WITH-AES-256-CBC-SHA"}, + { "ADH-SEED-SHA", "TLS-DH-anon-WITH-SEED-CBC-SHA" }, + { "AES128-GCM-SHA256", "TLS-RSA-WITH-AES-128-GCM-SHA256" }, + { "AES128-SHA256", "TLS-RSA-WITH-AES-128-CBC-SHA256" }, + { "AES128-SHA", "TLS-RSA-WITH-AES-128-CBC-SHA" }, + { "AES256-GCM-SHA384", "TLS-RSA-WITH-AES-256-GCM-SHA384" }, + { "AES256-SHA256", "TLS-RSA-WITH-AES-256-CBC-SHA256" }, + { "AES256-SHA", "TLS-RSA-WITH-AES-256-CBC-SHA" }, + { "CAMELLIA128-SHA256", "TLS-RSA-WITH-CAMELLIA-128-CBC-SHA256" }, + { "CAMELLIA128-SHA", "TLS-RSA-WITH-CAMELLIA-128-CBC-SHA" }, + { "CAMELLIA256-SHA256", "TLS-RSA-WITH-CAMELLIA-256-CBC-SHA256" }, + { "CAMELLIA256-SHA", "TLS-RSA-WITH-CAMELLIA-256-CBC-SHA" }, + { "DES-CBC3-SHA", "TLS-RSA-WITH-3DES-EDE-CBC-SHA" }, + { "DES-CBC-SHA", "TLS-RSA-WITH-DES-CBC-SHA" }, + { "DH-DSS-SEED-SHA", "TLS-DH-DSS-WITH-SEED-CBC-SHA" }, + { "DHE-DSS-AES128-GCM-SHA256", "TLS-DHE-DSS-WITH-AES-128-GCM-SHA256" }, + { "DHE-DSS-AES128-SHA256", "TLS-DHE-DSS-WITH-AES-128-CBC-SHA256" }, + { "DHE-DSS-AES128-SHA", "TLS-DHE-DSS-WITH-AES-128-CBC-SHA" }, + { "DHE-DSS-AES256-GCM-SHA384", "TLS-DHE-DSS-WITH-AES-256-GCM-SHA384" }, + { "DHE-DSS-AES256-SHA256", "TLS-DHE-DSS-WITH-AES-256-CBC-SHA256" }, + { "DHE-DSS-AES256-SHA", "TLS-DHE-DSS-WITH-AES-256-CBC-SHA" }, + { "DHE-DSS-CAMELLIA128-SHA256", "TLS-DHE-DSS-WITH-CAMELLIA-128-CBC-SHA= 256" }, + { "DHE-DSS-CAMELLIA128-SHA", "TLS-DHE-DSS-WITH-CAMELLIA-128-CBC-SHA" }, + { "DHE-DSS-CAMELLIA256-SHA256", "TLS-DHE-DSS-WITH-CAMELLIA-256-CBC-SHA= 256" }, + { "DHE-DSS-CAMELLIA256-SHA", "TLS-DHE-DSS-WITH-CAMELLIA-256-CBC-SHA" }, + { "DHE-DSS-SEED-SHA", "TLS-DHE-DSS-WITH-SEED-CBC-SHA" }, + { "DHE-RSA-AES128-GCM-SHA256", "TLS-DHE-RSA-WITH-AES-128-GCM-SHA256" }, + { "DHE-RSA-AES128-SHA256", "TLS-DHE-RSA-WITH-AES-128-CBC-SHA256" }, + { "DHE-RSA-AES128-SHA", "TLS-DHE-RSA-WITH-AES-128-CBC-SHA" }, + { "DHE-RSA-AES256-GCM-SHA384", "TLS-DHE-RSA-WITH-AES-256-GCM-SHA384" }, + { "DHE-RSA-AES256-SHA256", "TLS-DHE-RSA-WITH-AES-256-CBC-SHA256" }, + { "DHE-RSA-AES256-SHA", "TLS-DHE-RSA-WITH-AES-256-CBC-SHA" }, + { "DHE-RSA-CAMELLIA128-SHA256", "TLS-DHE-RSA-WITH-CAMELLIA-128-CBC-SHA= 256" }, + { "DHE-RSA-CAMELLIA128-SHA", "TLS-DHE-RSA-WITH-CAMELLIA-128-CBC-SHA" }, + { "DHE-RSA-CAMELLIA256-SHA256", "TLS-DHE-RSA-WITH-CAMELLIA-256-CBC-SHA= 256" }, + { "DHE-RSA-CAMELLIA256-SHA", "TLS-DHE-RSA-WITH-CAMELLIA-256-CBC-SHA" }, + { "DHE-RSA-CHACHA20-POLY1305", "TLS-DHE-RSA-WITH-CHACHA20-POLY1305-SHA= 256" }, + { "DHE-RSA-SEED-SHA", "TLS-DHE-RSA-WITH-SEED-CBC-SHA" }, + { "DH-RSA-SEED-SHA", "TLS-DH-RSA-WITH-SEED-CBC-SHA" }, + { "ECDH-ECDSA-AES128-GCM-SHA256", "TLS-ECDH-ECDSA-WITH-AES-128-GCM-SHA= 256" }, + { "ECDH-ECDSA-AES128-SHA256", "TLS-ECDH-ECDSA-WITH-AES-128-CBC-SHA256"= }, + { "ECDH-ECDSA-AES128-SHA", "TLS-ECDH-ECDSA-WITH-AES-128-CBC-SHA" }, + { "ECDH-ECDSA-AES256-GCM-SHA384", "TLS-ECDH-ECDSA-WITH-AES-256-GCM-SHA= 384" }, + { "ECDH-ECDSA-AES256-SHA256", "TLS-ECDH-ECDSA-WITH-AES-256-CBC-SHA256"= }, + { "ECDH-ECDSA-AES256-SHA384", "TLS-ECDH-ECDSA-WITH-AES-256-CBC-SHA384"= }, + { "ECDH-ECDSA-AES256-SHA", "TLS-ECDH-ECDSA-WITH-AES-256-CBC-SHA" }, + { "ECDH-ECDSA-CAMELLIA128-SHA256", "TLS-ECDH-ECDSA-WITH-CAMELLIA-128-C= BC-SHA256" }, + { "ECDH-ECDSA-CAMELLIA128-SHA", "TLS-ECDH-ECDSA-WITH-CAMELLIA-128-CBC-= SHA" }, + { "ECDH-ECDSA-CAMELLIA256-SHA256", "TLS-ECDH-ECDSA-WITH-CAMELLIA-256-C= BC-SHA256" }, + { "ECDH-ECDSA-CAMELLIA256-SHA", "TLS-ECDH-ECDSA-WITH-CAMELLIA-256-CBC-= SHA" }, + { "ECDH-ECDSA-DES-CBC3-SHA", "TLS-ECDH-ECDSA-WITH-3DES-EDE-CBC-SHA" }, + { "ECDH-ECDSA-DES-CBC-SHA", "TLS-ECDH-ECDSA-WITH-DES-CBC-SHA" }, + { "ECDH-ECDSA-RC4-SHA", "TLS-ECDH-ECDSA-WITH-RC4-128-SHA" }, + { "ECDHE-ECDSA-AES128-GCM-SHA256", "TLS-ECDHE-ECDSA-WITH-AES-128-GCM-S= HA256" }, + { "ECDHE-ECDSA-AES128-SHA256", "TLS-ECDHE-ECDSA-WITH-AES-128-CBC-SHA25= 6" }, + { "ECDHE-ECDSA-AES128-SHA384", "TLS-ECDHE-ECDSA-WITH-AES-128-CBC-SHA38= 4" }, + { "ECDHE-ECDSA-AES128-SHA", "TLS-ECDHE-ECDSA-WITH-AES-128-CBC-SHA" }, + { "ECDHE-ECDSA-AES256-GCM-SHA384", "TLS-ECDHE-ECDSA-WITH-AES-256-GCM-S= HA384" }, + { "ECDHE-ECDSA-AES256-SHA256", "TLS-ECDHE-ECDSA-WITH-AES-256-CBC-SHA25= 6" }, + { "ECDHE-ECDSA-AES256-SHA384", "TLS-ECDHE-ECDSA-WITH-AES-256-CBC-SHA38= 4" }, + { "ECDHE-ECDSA-AES256-SHA", "TLS-ECDHE-ECDSA-WITH-AES-256-CBC-SHA" }, + { "ECDHE-ECDSA-CAMELLIA128-SHA256", "TLS-ECDHE-ECDSA-WITH-CAMELLIA-128= -CBC-SHA256" }, + { "ECDHE-ECDSA-CAMELLIA128-SHA", "TLS-ECDHE-ECDSA-WITH-CAMELLIA-128-CB= C-SHA" }, + { "ECDHE-ECDSA-CAMELLIA256-SHA256", "TLS-ECDHE-ECDSA-WITH-CAMELLIA-256= -CBC-SHA256" }, + { "ECDHE-ECDSA-CAMELLIA256-SHA", "TLS-ECDHE-ECDSA-WITH-CAMELLIA-256-CB= C-SHA" }, + { "ECDHE-ECDSA-CHACHA20-POLY1305", "TLS-ECDHE-ECDSA-WITH-CHACHA20-POLY= 1305-SHA256" }, + { "ECDHE-ECDSA-DES-CBC3-SHA", "TLS-ECDHE-ECDSA-WITH-3DES-EDE-CBC-SHA" = }, + { "ECDHE-ECDSA-DES-CBC-SHA", "TLS-ECDHE-ECDSA-WITH-DES-CBC-SHA" }, + { "ECDHE-ECDSA-RC4-SHA", "TLS-ECDHE-ECDSA-WITH-RC4-128-SHA" }, + { "ECDHE-RSA-AES128-GCM-SHA256", "TLS-ECDHE-RSA-WITH-AES-128-GCM-SHA25= 6" }, + { "ECDHE-RSA-AES128-SHA256", "TLS-ECDHE-RSA-WITH-AES-128-CBC-SHA256" }, + { "ECDHE-RSA-AES128-SHA384", "TLS-ECDHE-RSA-WITH-AES-128-CBC-SHA384" }, + { "ECDHE-RSA-AES128-SHA", "TLS-ECDHE-RSA-WITH-AES-128-CBC-SHA" }, + { "ECDHE-RSA-AES256-GCM-SHA384", "TLS-ECDHE-RSA-WITH-AES-256-GCM-SHA38= 4" }, + { "ECDHE-RSA-AES256-SHA256", "TLS-ECDHE-RSA-WITH-AES-256-CBC-SHA256" }, + { "ECDHE-RSA-AES256-SHA384", "TLS-ECDHE-RSA-WITH-AES-256-CBC-SHA384" }, + { "ECDHE-RSA-AES256-SHA", "TLS-ECDHE-RSA-WITH-AES-256-CBC-SHA" }, + { "ECDHE-RSA-CAMELLIA128-SHA256", "TLS-ECDHE-RSA-WITH-CAMELLIA-128-CBC= -SHA256" }, + { "ECDHE-RSA-CAMELLIA128-SHA", "TLS-ECDHE-RSA-WITH-CAMELLIA-128-CBC-SH= A" }, + { "ECDHE-RSA-CAMELLIA256-SHA256", "TLS-ECDHE-RSA-WITH-CAMELLIA-256-CBC= -SHA256" }, + { "ECDHE-RSA-CAMELLIA256-SHA", "TLS-ECDHE-RSA-WITH-CAMELLIA-256-CBC-SH= A" }, + { "ECDHE-RSA-CHACHA20-POLY1305", "TLS-ECDHE-RSA-WITH-CHACHA20-POLY1305= -SHA256" }, + { "ECDHE-RSA-DES-CBC3-SHA", "TLS-ECDHE-RSA-WITH-3DES-EDE-CBC-SHA" }, + { "ECDHE-RSA-DES-CBC-SHA", "TLS-ECDHE-RSA-WITH-DES-CBC-SHA" }, + { "ECDHE-RSA-RC4-SHA", "TLS-ECDHE-RSA-WITH-RC4-128-SHA" }, + { "ECDH-RSA-AES128-GCM-SHA256", "TLS-ECDH-RSA-WITH-AES-128-GCM-SHA256"= }, + { "ECDH-RSA-AES128-SHA256", "TLS-ECDH-RSA-WITH-AES-128-CBC-SHA256" }, + { "ECDH-RSA-AES128-SHA384", "TLS-ECDH-RSA-WITH-AES-128-CBC-SHA384" }, + { "ECDH-RSA-AES128-SHA", "TLS-ECDH-RSA-WITH-AES-128-CBC-SHA" }, + { "ECDH-RSA-AES256-GCM-SHA384", "TLS-ECDH-RSA-WITH-AES-256-GCM-SHA384"= }, + { "ECDH-RSA-AES256-SHA256", "TLS-ECDH-RSA-WITH-AES-256-CBC-SHA256" }, + { "ECDH-RSA-AES256-SHA384", "TLS-ECDH-RSA-WITH-AES-256-CBC-SHA384" }, + { "ECDH-RSA-AES256-SHA", "TLS-ECDH-RSA-WITH-AES-256-CBC-SHA" }, + { "ECDH-RSA-CAMELLIA128-SHA256", "TLS-ECDH-RSA-WITH-CAMELLIA-128-CBC-S= HA256" }, + { "ECDH-RSA-CAMELLIA128-SHA", "TLS-ECDH-RSA-WITH-CAMELLIA-128-CBC-SHA"= }, + { "ECDH-RSA-CAMELLIA256-SHA256", "TLS-ECDH-RSA-WITH-CAMELLIA-256-CBC-S= HA256" }, + { "ECDH-RSA-CAMELLIA256-SHA", "TLS-ECDH-RSA-WITH-CAMELLIA-256-CBC-SHA"= }, + { "ECDH-RSA-DES-CBC3-SHA", "TLS-ECDH-RSA-WITH-3DES-EDE-CBC-SHA" }, + { "ECDH-RSA-DES-CBC-SHA", "TLS-ECDH-RSA-WITH-DES-CBC-SHA" }, + { "ECDH-RSA-RC4-SHA", "TLS-ECDH-RSA-WITH-RC4-128-SHA" }, + { "EDH-DSS-DES-CBC3-SHA", "TLS-DHE-DSS-WITH-3DES-EDE-CBC-SHA" }, + { "EDH-DSS-DES-CBC-SHA", "TLS-DHE-DSS-WITH-DES-CBC-SHA" }, + { "EDH-RSA-DES-CBC3-SHA", "TLS-DHE-RSA-WITH-3DES-EDE-CBC-SHA" }, + { "EDH-RSA-DES-CBC-SHA", "TLS-DHE-RSA-WITH-DES-CBC-SHA" }, + { "EXP-DES-CBC-SHA", "TLS-RSA-EXPORT-WITH-DES40-CBC-SHA" }, + { "EXP-EDH-DSS-DES-CBC-SHA", "TLS-DH-DSS-EXPORT-WITH-DES40-CBC-SHA" }, + { "EXP-EDH-RSA-DES-CBC-SHA", "TLS-DH-RSA-EXPORT-WITH-DES40-CBC-SHA" }, + { "EXP-RC2-CBC-MD5", "TLS-RSA-EXPORT-WITH-RC2-CBC-40-MD5" }, + { "EXP-RC4-MD5", "TLS-RSA-EXPORT-WITH-RC4-40-MD5" }, + { "NULL-MD5", "TLS-RSA-WITH-NULL-MD5" }, + { "NULL-SHA256", "TLS-RSA-WITH-NULL-SHA256" }, + { "NULL-SHA", "TLS-RSA-WITH-NULL-SHA" }, + { "PSK-3DES-EDE-CBC-SHA", "TLS-PSK-WITH-3DES-EDE-CBC-SHA" }, + { "PSK-AES128-CBC-SHA", "TLS-PSK-WITH-AES-128-CBC-SHA" }, + { "PSK-AES256-CBC-SHA", "TLS-PSK-WITH-AES-256-CBC-SHA" }, + { "PSK-RC4-SHA", "TLS-PSK-WITH-RC4-128-SHA" }, + { "RC4-MD5", "TLS-RSA-WITH-RC4-128-MD5" }, + { "RC4-SHA", "TLS-RSA-WITH-RC4-128-SHA" }, + { "SEED-SHA", "TLS-RSA-WITH-SEED-CBC-SHA" }, + { "SRP-DSS-3DES-EDE-CBC-SHA", "TLS-SRP-SHA-DSS-WITH-3DES-EDE-CBC-SHA" = }, + { "SRP-DSS-AES-128-CBC-SHA", "TLS-SRP-SHA-DSS-WITH-AES-128-CBC-SHA" }, + { "SRP-DSS-AES-256-CBC-SHA", "TLS-SRP-SHA-DSS-WITH-AES-256-CBC-SHA" }, + { "SRP-RSA-3DES-EDE-CBC-SHA", "TLS-SRP-SHA-RSA-WITH-3DES-EDE-CBC-SHA" = }, + { "SRP-RSA-AES-128-CBC-SHA", "TLS-SRP-SHA-RSA-WITH-AES-128-CBC-SHA" }, + { "SRP-RSA-AES-256-CBC-SHA", "TLS-SRP-SHA-RSA-WITH-AES-256-CBC-SHA" }, #ifdef ENABLE_CRYPTO_OPENSSL /* OpenSSL-specific group names */ - {"DEFAULT", "DEFAULT"}, - {"ALL", "ALL"}, - {"HIGH", "HIGH"}, {"!HIGH", "!HIGH"}, - {"MEDIUM", "MEDIUM"}, {"!MEDIUM", "!MEDIUM"}, - {"LOW", "LOW"}, {"!LOW", "!LOW"}, - {"ECDH", "ECDH"}, {"!ECDH", "!ECDH"}, - {"ECDSA", "ECDSA"}, {"!ECDSA", "!ECDSA"}, - {"EDH", "EDH"}, {"!EDH", "!EDH"}, - {"EXP", "EXP"}, {"!EXP", "!EXP"}, - {"RSA", "RSA"}, {"!RSA", "!RSA"}, - {"kRSA", "kRSA"}, {"!kRSA", "!kRSA"}, - {"SRP", "SRP"}, {"!SRP", "!SRP"}, + { "DEFAULT", "DEFAULT" }, + { "ALL", "ALL" }, + { "HIGH", "HIGH" }, + { "!HIGH", "!HIGH" }, + { "MEDIUM", "MEDIUM" }, + { "!MEDIUM", "!MEDIUM" }, + { "LOW", "LOW" }, + { "!LOW", "!LOW" }, + { "ECDH", "ECDH" }, + { "!ECDH", "!ECDH" }, + { "ECDSA", "ECDSA" }, + { "!ECDSA", "!ECDSA" }, + { "EDH", "EDH" }, + { "!EDH", "!EDH" }, + { "EXP", "EXP" }, + { "!EXP", "!EXP" }, + { "RSA", "RSA" }, + { "!RSA", "!RSA" }, + { "kRSA", "kRSA" }, + { "!kRSA", "!kRSA" }, + { "SRP", "SRP" }, + { "!SRP", "!SRP" }, #endif - {NULL, NULL} + { NULL, NULL } }; const tls_cipher_name_pair * diff --git a/src/openvpn/ssl_util.h b/src/openvpn/ssl_util.h index 189b1d0..007ed69 100644 --- a/src/openvpn/ssl_util.h +++ b/src/openvpn/ssl_util.h @@ -43,8 +43,7 @@ * @return The content of the variable as NULL terminated string or NULL = if the * variable cannot be found. */ -char *extract_var_peer_info(const char *peer_info, const char *var, - struct gc_arena *gc); +char *extract_var_peer_info(const char *peer_info, const char *var, struct= gc_arena *gc); /** * Extracts the IV_PROTO variable and returns its value or 0 @@ -74,7 +73,11 @@ * @param cipher_name Can be either OpenSSL or IANA cipher name * @return tls_cipher_name_pair* if found, NULL otherwise */ -typedef struct { const char *openssl_name; const char *iana_name; } tls_ci= pher_name_pair; +typedef struct +{ + const char *openssl_name; + const char *iana_name; +} tls_cipher_name_pair; const tls_cipher_name_pair *tls_get_cipher_name_pair(const char *cipher_na= me, size_t len); /** @@ -88,7 +91,6 @@ * @param delimiter the delimiter to count, typically ':' * @return occrrences of delimiter + 1 */ -int -get_num_elements(const char *string, char delimiter); +int get_num_elements(const char *string, char delimiter); #endif /* ifndef SSL_UTIL_H_ */ diff --git a/src/openvpn/ssl_verify.c b/src/openvpn/ssl_verify.c index 82337cf..6f85dca 100644 --- a/src/openvpn/ssl_verify.c +++ b/src/openvpn/ssl_verify.c @@ -149,11 +149,12 @@ /* If the username has been overridden, we accept both the original * username and the changed username */ if (strcmp(username, multi->locked_username) !=3D 0 - && (!multi->locked_original_username || strcmp(username, mult= i->locked_original_username) !=3D 0)) + && (!multi->locked_original_username + || strcmp(username, multi->locked_original_username) !=3D = 0)) { - msg(D_TLS_ERRORS, "TLS Auth Error: username attempted to chang= e from '%s' to '%s' -- tunnel disabled", - multi->locked_username, - username); + msg(D_TLS_ERRORS, + "TLS Auth Error: username attempted to change from '%s' to= '%s' -- tunnel disabled", + multi->locked_username, username); /* disable the tunnel */ tls_deauthenticate(multi); @@ -239,8 +240,8 @@ { continue; } - else if (ch1 && ch2 && !memcmp(ch1->sha256_hash, ch2->sha256_h= ash, - sizeof(ch1->sha256_hash))) + else if (ch1 && ch2 + && !memcmp(ch1->sha256_hash, ch2->sha256_hash, sizeof= (ch1->sha256_hash))) { continue; } @@ -275,8 +276,7 @@ if (ch) { ALLOC_OBJ(dest->ch[i], struct cert_hash); - memcpy(dest->ch[i]->sha256_hash, ch->sha256_hash, - sizeof(dest->ch[i]->sha256_hash)); + memcpy(dest->ch[i]->sha256_hash, ch->sha256_hash, sizeof(d= est->ch[i]->sha256_hash)); } } } @@ -320,22 +320,21 @@ * @param subject the peer's extracted common name */ static result_t -verify_peer_cert(const struct tls_options *opt, openvpn_x509_cert_t *peer_= cert, - const char *subject, const char *common_name) +verify_peer_cert(const struct tls_options *opt, openvpn_x509_cert_t *peer_= cert, const char *subject, + const char *common_name) { /* verify certificate nsCertType */ if (opt->ns_cert_type !=3D NS_CERT_CHECK_NONE) { if (SUCCESS =3D=3D x509_verify_ns_cert_type(peer_cert, opt->ns_cer= t_type)) { - msg(D_HANDSHAKE, "VERIFY OK: nsCertType=3D%s", - print_nsCertType(opt->ns_cert_type)); + msg(D_HANDSHAKE, "VERIFY OK: nsCertType=3D%s", print_nsCertTyp= e(opt->ns_cert_type)); } else { - msg(D_HANDSHAKE, "VERIFY nsCertType ERROR: %s, require nsCertT= ype=3D%s", - subject, print_nsCertType(opt->ns_cert_type)); - return FAILURE; /* Reject connection */ + msg(D_HANDSHAKE, "VERIFY nsCertType ERROR: %s, require nsCertT= ype=3D%s", subject, + print_nsCertType(opt->ns_cert_type)); + return FAILURE; /* Reject connection */ } } @@ -349,7 +348,7 @@ else { msg(D_HANDSHAKE, "VERIFY KU ERROR"); - return FAILURE; /* Reject connection */ + return FAILURE; /* Reject connection */ } } @@ -363,28 +362,27 @@ else { msg(D_HANDSHAKE, "VERIFY EKU ERROR"); - return FAILURE; /* Reject connection */ + return FAILURE; /* Reject connection */ } } /* verify X509 name or username against --verify-x509-[user]name */ if (opt->verify_x509_type !=3D VERIFY_X509_NONE) { - if ( (opt->verify_x509_type =3D=3D VERIFY_X509_SUBJECT_DN - && strcmp(opt->verify_x509_name, subject) =3D=3D 0) - || (opt->verify_x509_type =3D=3D VERIFY_X509_SUBJECT_RDN - && strcmp(opt->verify_x509_name, common_name) =3D=3D 0) - || (opt->verify_x509_type =3D=3D VERIFY_X509_SUBJECT_RDN_PREF= IX - && strncmp(opt->verify_x509_name, common_name, - strlen(opt->verify_x509_name)) =3D=3D 0) ) + if ((opt->verify_x509_type =3D=3D VERIFY_X509_SUBJECT_DN + && strcmp(opt->verify_x509_name, subject) =3D=3D 0) + || (opt->verify_x509_type =3D=3D VERIFY_X509_SUBJECT_RDN + && strcmp(opt->verify_x509_name, common_name) =3D=3D 0) + || (opt->verify_x509_type =3D=3D VERIFY_X509_SUBJECT_RDN_PREFIX + && strncmp(opt->verify_x509_name, common_name, strlen(opt-= >verify_x509_name)) =3D=3D 0)) { msg(D_HANDSHAKE, "VERIFY X509NAME OK: %s", subject); } else { - msg(D_HANDSHAKE, "VERIFY X509NAME ERROR: %s, must be %s", - subject, opt->verify_x509_name); - return FAILURE; /* Reject connection */ + msg(D_HANDSHAKE, "VERIFY X509NAME ERROR: %s, must be %s", subj= ect, + opt->verify_x509_name); + return FAILURE; /* Reject connection */ } } @@ -397,8 +395,7 @@ */ static void verify_cert_set_env(struct env_set *es, openvpn_x509_cert_t *peer_cert, in= t cert_depth, - const char *subject, - const struct x509_track *x509_track) + const char *subject, const struct x509_track *x509_tra= ck) { char envname[64]; char *serial =3D NULL; @@ -424,13 +421,10 @@ struct buffer sha256 =3D x509_get_sha256_fingerprint(peer_cert, &g= c); snprintf(envname, sizeof(envname), "tls_digest_%d", cert_depth); - setenv_str(es, envname, - format_hex_ex(BPTR(&sha1), BLEN(&sha1), 0, 1, ":", &gc)= ); + setenv_str(es, envname, format_hex_ex(BPTR(&sha1), BLEN(&sha1), 0,= 1, ":", &gc)); - snprintf(envname, sizeof(envname), "tls_digest_sha256_%d", - cert_depth); - setenv_str(es, envname, - format_hex_ex(BPTR(&sha256), BLEN(&sha256), 0, 1, ":", = &gc)); + snprintf(envname, sizeof(envname), "tls_digest_sha256_%d", cert_de= pth); + setenv_str(es, envname, format_hex_ex(BPTR(&sha256), BLEN(&sha256)= , 0, 1, ":", &gc)); } /* export serial number as environmental variable */ @@ -474,8 +468,8 @@ * call --tls-verify plug-in(s) */ static result_t -verify_cert_call_plugin(const struct plugin_list *plugins, struct env_set = *es, - int cert_depth, openvpn_x509_cert_t *cert, char *s= ubject) +verify_cert_call_plugin(const struct plugin_list *plugins, struct env_set = *es, int cert_depth, + openvpn_x509_cert_t *cert, char *subject) { if (plugin_defined(plugins, OPENVPN_PLUGIN_TLS_VERIFY)) { @@ -484,20 +478,19 @@ argv_printf(&argv, "%d %s", cert_depth, subject); - ret =3D plugin_call_ssl(plugins, OPENVPN_PLUGIN_TLS_VERIFY, &argv,= NULL, es, cert_depth, cert); + ret =3D + plugin_call_ssl(plugins, OPENVPN_PLUGIN_TLS_VERIFY, &argv, NUL= L, es, cert_depth, cert); argv_free(&argv); if (ret =3D=3D OPENVPN_PLUGIN_FUNC_SUCCESS) { - msg(D_HANDSHAKE, "VERIFY PLUGIN OK: depth=3D%d, %s", - cert_depth, subject); + msg(D_HANDSHAKE, "VERIFY PLUGIN OK: depth=3D%d, %s", cert_dept= h, subject); } else { - msg(D_HANDSHAKE, "VERIFY PLUGIN ERROR: depth=3D%d, %s", - cert_depth, subject); - return FAILURE; /* Reject connection */ + msg(D_HANDSHAKE, "VERIFY PLUGIN ERROR: depth=3D%d, %s", cert_d= epth, subject); + return FAILURE; /* Reject connection */ } } return SUCCESS; @@ -507,8 +500,8 @@ * run --tls-verify script */ static result_t -verify_cert_call_command(const char *verify_command, struct env_set *es, - int cert_depth, char *subject) +verify_cert_call_command(const char *verify_command, struct env_set *es, i= nt cert_depth, + char *subject) { int ret; struct gc_arena gc =3D gc_new(); @@ -527,22 +520,20 @@ if (ret) { - msg(D_HANDSHAKE, "VERIFY SCRIPT OK: depth=3D%d, %s", - cert_depth, subject); + msg(D_HANDSHAKE, "VERIFY SCRIPT OK: depth=3D%d, %s", cert_depth, s= ubject); return SUCCESS; } - msg(D_HANDSHAKE, "VERIFY SCRIPT ERROR: depth=3D%d, %s", - cert_depth, subject); - return FAILURE; /* Reject connection */ + msg(D_HANDSHAKE, "VERIFY SCRIPT ERROR: depth=3D%d, %s", cert_depth, su= bject); + return FAILURE; /* Reject connection */ } /* * check peer cert against CRL directory */ static result_t -verify_check_crl_dir(const char *crl_dir, openvpn_x509_cert_t *cert, - const char *subject, int cert_depth) +verify_check_crl_dir(const char *crl_dir, openvpn_x509_cert_t *cert, const= char *subject, + int cert_depth) { result_t ret =3D FAILURE; char fn[256]; @@ -552,8 +543,8 @@ char *serial =3D backend_x509_get_serial(cert, &gc); if (!serial) { - msg(D_HANDSHAKE, "VERIFY CRL: depth=3D%d, %s, serial number is not= available", - cert_depth, subject); + msg(D_HANDSHAKE, "VERIFY CRL: depth=3D%d, %s, serial number is not= available", cert_depth, + subject); goto cleanup; } @@ -565,8 +556,8 @@ fd =3D platform_open(fn, O_RDONLY, 0); if (fd >=3D 0) { - msg(D_HANDSHAKE, "VERIFY CRL: depth=3D%d, %s, serial=3D%s is revok= ed", - cert_depth, subject, serial); + msg(D_HANDSHAKE, "VERIFY CRL: depth=3D%d, %s, serial=3D%s is revok= ed", cert_depth, subject, + serial); goto cleanup; } @@ -600,8 +591,10 @@ char *subject =3D x509_get_subject(cert, &gc); if (!subject) { - msg(D_TLS_ERRORS, "VERIFY ERROR: depth=3D%d, could not extract X50= 9 " - "subject string from certificate", cert_depth); + msg(D_TLS_ERRORS, + "VERIFY ERROR: depth=3D%d, could not extract X509 " + "subject string from certificate", + cert_depth); goto cleanup; } @@ -613,19 +606,19 @@ struct buffer buf =3D alloc_buf_gc(256, &gc); for (int i =3D 0; opt->x509_username_field[i] !=3D NULL; i++) { - char username[TLS_USERNAME_LEN+1] =3D {0}; /* null-terminated */ + char username[TLS_USERNAME_LEN + 1] =3D { 0 }; /* null-terminated = */ - if (SUCCESS !=3D backend_x509_get_username(username, sizeof(userna= me), - opt->x509_username_field[= i], cert)) + if (SUCCESS + !=3D backend_x509_get_username(username, sizeof(username), opt= ->x509_username_field[i], + cert)) { if (!cert_depth) { - msg(D_TLS_ERRORS, "VERIFY ERROR: could not extract %s from= X509 " + msg(D_TLS_ERRORS, + "VERIFY ERROR: could not extract %s from X509 " "subject string ('%s') -- note that the field length i= s " "limited to %d characters", - opt->x509_username_field[i], - subject, - TLS_USERNAME_LEN); + opt->x509_username_field[i], subject, TLS_USERNAME_LEN= ); goto cleanup; } break; @@ -634,11 +627,11 @@ { if (!cert_depth) { - msg(D_TLS_ERRORS, "VERIFY ERROR: could not append %s from = X509 " + msg(D_TLS_ERRORS, + "VERIFY ERROR: could not append %s from X509 " "certificate -- note that the username length is " "limited to %d characters", - opt->x509_username_field[i], - buf.capacity - 1); + opt->x509_username_field[i], buf.capacity - 1); goto cleanup; } break; @@ -648,8 +641,10 @@ char *common_name =3D BSTR(&buf); if (!common_name) { - msg(D_TLS_ERRORS, "VERIFY ERROR: depth=3D%d, could not extract X50= 9 " - "username string from certificate", cert_depth); + msg(D_TLS_ERRORS, + "VERIFY ERROR: depth=3D%d, could not extract X509 " + "username string from certificate", + cert_depth); goto cleanup; } @@ -659,13 +654,15 @@ /* warn if cert chain is too deep */ if (cert_depth >=3D MAX_CERT_DEPTH) { - msg(D_TLS_ERRORS, "TLS Error: Convoluted certificate chain detecte= d with depth [%d] greater than %d", cert_depth, MAX_CERT_DEPTH); - goto cleanup; /* Reject connection */ + msg(D_TLS_ERRORS, + "TLS Error: Convoluted certificate chain detected with depth [= %d] greater than %d", + cert_depth, MAX_CERT_DEPTH); + goto cleanup; /* Reject connection */ } if (cert_depth =3D=3D opt->verify_hash_depth && opt->verify_hash) { - struct buffer cert_fp =3D {0}; + struct buffer cert_fp =3D { 0 }; switch (opt->verify_hash_algo) { @@ -683,8 +680,10 @@ * value in an enumerated type. So if this unlikely scena= rio * happens, consider this a failure */ - msg(M_WARN, "Unexpected invalid algorithm used with " - "--verify-hash (%i)", opt->verify_hash_algo); + msg(M_WARN, + "Unexpected invalid algorithm used with " + "--verify-hash (%i)", + opt->verify_hash_algo); ret =3D FAILURE; goto cleanup; } @@ -693,8 +692,7 @@ while (current_hash) { - if (memcmp_constant_time(BPTR(&cert_fp), current_hash->hash, - BLEN(&cert_fp)) =3D=3D 0) + if (memcmp_constant_time(BPTR(&cert_fp), current_hash->hash, B= LEN(&cert_fp)) =3D=3D 0) { break; } @@ -703,11 +701,12 @@ if (!current_hash) { - const char *hex_fp =3D format_hex_ex(BPTR(&cert_fp), BLEN(&cer= t_fp), - 0, 1, ":", &gc); - msg(D_TLS_ERRORS, "TLS Error: --tls-verify/--peer-fingerprint " + const char *hex_fp =3D format_hex_ex(BPTR(&cert_fp), BLEN(&cer= t_fp), 0, 1, ":", &gc); + msg(D_TLS_ERRORS, + "TLS Error: --tls-verify/--peer-fingerprint " "certificate hash verification failed. (got certificate " - "fingerprint: %s)", hex_fp); + "fingerprint: %s)", + hex_fp); goto cleanup; } } @@ -722,14 +721,14 @@ if (opt->export_peer_cert_dir) { - pem_export_fname =3D platform_create_temp_file(opt->export_peer_ce= rt_dir, - "pef", &gc); + pem_export_fname =3D platform_create_temp_file(opt->export_peer_ce= rt_dir, "pef", &gc); - if (!pem_export_fname - || !verify_cert_cert_export_env(opt->es, cert, pem_export_fnam= e)) + if (!pem_export_fname || !verify_cert_cert_export_env(opt->es, cer= t, pem_export_fname)) { - msg(D_TLS_ERRORS, "TLS Error: Failed to export certificate for= " - "--tls-export-cert in %s", opt->export_peer_cert_dir); + msg(D_TLS_ERRORS, + "TLS Error: Failed to export certificate for " + "--tls-export-cert in %s", + opt->export_peer_cert_dir); goto cleanup; } } @@ -752,8 +751,8 @@ } /* run --tls-verify script */ - if (opt->verify_command && SUCCESS !=3D verify_cert_call_command(opt->= verify_command, - opt->es= , cert_depth, subject)) + if (opt->verify_command + && SUCCESS !=3D verify_cert_call_command(opt->verify_command, opt-= >es, cert_depth, subject)) { goto cleanup; } @@ -786,7 +785,7 @@ verify_cert_cert_delete_env(opt->es, pem_export_fname); if (ret !=3D SUCCESS) { - tls_clear_error(); /* always? */ + tls_clear_error(); /* always? */ session->verified =3D false; /* double sure? */ } @@ -796,9 +795,9 @@ } /* ***********************************************************************= **** -* Functions for the management of deferred authentication when using -* user/password authentication. -**************************************************************************= * */ + * Functions for the management of deferred authentication when using + * user/password authentication. + *************************************************************************= ** */ void auth_set_client_reason(struct tls_multi *multi, const char *client_reason) @@ -884,15 +883,13 @@ * @returns false The file had an invlaid format or another error occured */ static bool -key_state_check_auth_pending_file(struct auth_deferred_status *ads, - struct tls_multi *multi, +key_state_check_auth_pending_file(struct auth_deferred_status *ads, struct= tls_multi *multi, struct tls_session *session) { bool ret =3D true; if (ads->auth_pending_file) { - struct buffer_list *lines =3D buffer_list_file(ads->auth_pending_f= ile, - 1024); + struct buffer_list *lines =3D buffer_list_file(ads->auth_pending_f= ile, 1024); if (lines && lines->head) { /* Must have at least three lines. further lines are ignored f= or @@ -900,7 +897,7 @@ if (!lines->head || !lines->head->next || !lines->head->next->= next) { msg(M_WARN, "auth pending control file is not at least " - "three lines long."); + "three lines long."); buffer_list_free(lines); return false; } @@ -927,10 +924,13 @@ char buf[128]; snprintf(buf, sizeof(buf), "Authentication failed, required pending auth " - "method '%s' not supported", pending_method); + "method '%s' not supported", + pending_method); auth_set_client_reason(multi, buf); - msg(M_INFO, "Client does not supported auth pending method= " - "'%s'", pending_method); + msg(M_INFO, + "Client does not supported auth pending method " + "'%s'", + pending_method); ret =3D false; } else @@ -975,8 +975,7 @@ * @return true if file creation was successful */ static bool -key_state_gen_auth_control_files(struct auth_deferred_status *ads, - const struct tls_options *opt) +key_state_gen_auth_control_files(struct auth_deferred_status *ads, const s= truct tls_options *opt) { struct gc_arena gc =3D gc_new(); @@ -1017,7 +1016,6 @@ { ret =3D BSTR(&reason); } - } return ret; } @@ -1088,8 +1086,7 @@ #endif ASSERT(auth_plugin < 4 && auth_script < 4 && auth_man < 4); - if (auth_plugin =3D=3D ACF_FAILED || auth_script =3D=3D ACF_FAILED - || auth_man =3D=3D ACF_FAILED) + if (auth_plugin =3D=3D ACF_FAILED || auth_script =3D=3D ACF_FAILED= || auth_man =3D=3D ACF_FAILED) { ks->authenticated =3D KS_AUTH_FALSE; return; @@ -1122,7 +1119,7 @@ * with no caching (0) here as well to have the same super quick initial * reaction. */ -static time_t cache_intervals[] =3D {0, 0, 0, 0, 0, 1, 1, 2, 2, 4, 8}; +static time_t cache_intervals[] =3D { 0, 0, 0, 0, 0, 1, 1, 2, 2, 4, 8 }; /** * uses cache_intervals times to determine if we should update the @@ -1189,8 +1186,10 @@ { struct gc_arena gc =3D gc_new(); const struct key_state *ks =3D get_primary_key(multi); - const char *plugin_message =3D key_state_check_auth_failed_message= _file(&ks->plugin_auth, &gc); - const char *script_message =3D key_state_check_auth_failed_message= _file(&ks->script_auth, &gc); + const char *plugin_message =3D + key_state_check_auth_failed_message_file(&ks->plugin_auth, &gc= ); + const char *script_message =3D + key_state_check_auth_failed_message_file(&ks->script_auth, &gc= ); if (plugin_message) { @@ -1234,7 +1233,8 @@ * to indicate auth failure/success. */ bool -tls_authenticate_key(struct tls_multi *multi, const unsigned int mda_key_i= d, const bool auth, const char *client_reason) +tls_authenticate_key(struct tls_multi *multi, const unsigned int mda_key_i= d, const bool auth, + const char *client_reason) { bool ret =3D false; if (multi) @@ -1270,8 +1270,7 @@ * Check if the script/plugin left a message in the auth failed message * file and relay it to the user */ static void -check_for_client_reason(struct tls_multi *multi, - struct auth_deferred_status *status) +check_for_client_reason(struct tls_multi *multi, struct auth_deferred_stat= us *status) { struct gc_arena gc =3D gc_new(); const char *msg =3D key_state_check_auth_failed_message_file(status, &= gc); @@ -1292,7 +1291,7 @@ struct argv argv =3D argv_new(); const char *tmp_file =3D ""; int retval =3D OPENVPN_PLUGIN_FUNC_ERROR; - struct key_state *ks =3D &session->key[KS_PRIMARY]; /* primary ke= y */ + struct key_state *ks =3D &session->key[KS_PRIMARY]; /* primary key */ /* Set environmental variables prior to calling script */ setenv_str(session->opt->es, "script_type", "user-pass-verify"); @@ -1304,8 +1303,7 @@ { struct status_output *so; - tmp_file =3D platform_create_temp_file(session->opt->tmp_dir, "up", - &gc); + tmp_file =3D platform_create_temp_file(session->opt->tmp_dir, "up"= , &gc); if (tmp_file) { so =3D status_open(tmp_file, 0, -1, NULL, STATUS_OUTPUT_WRITE); @@ -1330,15 +1328,17 @@ /* pre-create files for deferred auth control */ if (!key_state_gen_auth_control_files(&ks->script_auth, session->opt)) { - msg(D_TLS_ERRORS, "TLS Auth Error (%s): " - "could not create deferred auth control file", __func__); + msg(D_TLS_ERRORS, + "TLS Auth Error (%s): " + "could not create deferred auth control file", + __func__); retval =3D OPENVPN_PLUGIN_FUNC_ERROR; goto error; } /* call command */ - int script_ret =3D openvpn_run_script(&argv, session->opt->es, S_EXITC= ODE, - "--auth-user-pass-verify"); + int script_ret =3D + openvpn_run_script(&argv, session->opt->es, S_EXITCODE, "--auth-us= er-pass-verify"); switch (script_ret) { case 0: @@ -1358,13 +1358,11 @@ { /* Check if we the plugin has written the pending auth control * file and send the pending auth to the client */ - if (!key_state_check_auth_pending_file(&ks->script_auth, - multi, session)) + if (!key_state_check_auth_pending_file(&ks->script_auth, multi, se= ssion)) { retval =3D OPENVPN_PLUGIN_FUNC_ERROR; key_state_rm_auth_control_files(&ks->script_auth); } - } else { @@ -1395,8 +1393,8 @@ struct tls_session *session =3D &multi->session[TM_ACTIVE]; setenv_str(session->opt->es, "crresponse", cr_response); - plugin_call(session->opt->plugins, OPENVPN_PLUGIN_CLIENT_CRRESPONSE, N= ULL, - NULL, session->opt->es); + plugin_call(session->opt->plugins, OPENVPN_PLUGIN_CLIENT_CRRESPONSE, N= ULL, NULL, + session->opt->es); setenv_del(session->opt->es, "crresponse"); } @@ -1405,7 +1403,6 @@ void verify_crresponse_script(struct tls_multi *multi, const char *cr_response) { - struct tls_session *session =3D &multi->session[TM_ACTIVE]; if (!session->opt->client_crresponse_script) @@ -1425,8 +1422,7 @@ if (tmp_file) { - struct status_output *so =3D status_open(tmp_file, 0, -1, NULL, - STATUS_OUTPUT_WRITE); + struct status_output *so =3D status_open(tmp_file, 0, -1, NULL, ST= ATUS_OUTPUT_WRITE); status_printf(so, "%s", cr_response); if (!status_close(so)) { @@ -1463,7 +1459,7 @@ const struct user_pass *up) { int retval =3D OPENVPN_PLUGIN_FUNC_ERROR; - struct key_state *ks =3D &session->key[KS_PRIMARY]; /* primary ke= y */ + struct key_state *ks =3D &session->key[KS_PRIMARY]; /* primary key */ /* set password in private env space */ setenv_str(session->opt->es, "password", up->password); @@ -1471,13 +1467,16 @@ /* generate filename for deferred auth control file */ if (!key_state_gen_auth_control_files(&ks->plugin_auth, session->opt)) { - msg(D_TLS_ERRORS, "TLS Auth Error (%s): " - "could not create deferred auth control file", __func__); + msg(D_TLS_ERRORS, + "TLS Auth Error (%s): " + "could not create deferred auth control file", + __func__); return retval; } /* call command */ - retval =3D plugin_call(session->opt->plugins, OPENVPN_PLUGIN_AUTH_USER= _PASS_VERIFY, NULL, NULL, session->opt->es); + retval =3D plugin_call(session->opt->plugins, OPENVPN_PLUGIN_AUTH_USER= _PASS_VERIFY, NULL, NULL, + session->opt->es); if (retval =3D=3D OPENVPN_PLUGIN_FUNC_DEFERRED) { @@ -1516,18 +1515,18 @@ #define KMDA_DEF 3 static int -verify_user_pass_management(struct tls_session *session, - const struct user_pass *up) +verify_user_pass_management(struct tls_session *session, const struct user= _pass *up) { int retval =3D KMDA_ERROR; - struct key_state *ks =3D &session->key[KS_PRIMARY]; /* primary ke= y */ + struct key_state *ks =3D &session->key[KS_PRIMARY]; /* primary key */ /* set username/password in private env space */ setenv_str(session->opt->es, "password", up->password); if (management) { - management_notify_client_needing_auth(management, ks->mda_key_id, = session->opt->mda_context, session->opt->es); + management_notify_client_needing_auth(management, ks->mda_key_id, = session->opt->mda_context, + session->opt->es); } setenv_del(session->opt->es, "password"); @@ -1539,8 +1538,7 @@ #endif /* ifdef ENABLE_MANAGEMENT */ static bool -set_verify_user_pass_env(struct user_pass *up, struct tls_multi *multi, - struct tls_session *session) +set_verify_user_pass_env(struct user_pass *up, struct tls_multi *multi, st= ruct tls_session *session) { /* Is username defined? */ if ((session->opt->ssl_flags & SSLF_AUTH_USER_PASS_OPTIONAL) || strlen= (up->username)) @@ -1576,7 +1574,8 @@ msg(D_TLS_ERRORS, "TLS Auth Error: --username-as-common name specified and " "username is longer than the maximum permitted Common Name " - "length of %d characters", TLS_USERNAME_LEN); + "length of %d characters", + TLS_USERNAME_LEN); return false; } else @@ -1592,10 +1591,9 @@ * result of the username/password verification */ void -verify_user_pass(struct user_pass *up, struct tls_multi *multi, - struct tls_session *session) +verify_user_pass(struct user_pass *up, struct tls_multi *multi, struct tls= _session *session) { - struct key_state *ks =3D &session->key[KS_PRIMARY]; /* primary ke= y */ + struct key_state *ks =3D &session->key[KS_PRIMARY]; /* primary key */ ASSERT(up && !up->protected); @@ -1623,9 +1621,10 @@ if (multi->locked_original_username && strncmp(up->username, multi->locked_original_username, sizeof(u= p->username)) =3D=3D 0) { - msg(D_MULTI_LOW, "TLS: Replacing client provided username '%s' wit= h " - "username from override-user '%s'", up->username, - multi->locked_username); + msg(D_MULTI_LOW, + "TLS: Replacing client provided username '%s' with " + "username from override-user '%s'", + up->username, multi->locked_username); strncpy(up->username, multi->locked_username, sizeof(up->username)= ); } @@ -1661,7 +1660,8 @@ * We do not want the EXPIRED or EMPTY USER flags here so check * for equality with AUTH_TOKEN_HMAC_OK */ - msg(M_WARN, "TLS: Username/auth-token authentication " + msg(M_WARN, + "TLS: Username/auth-token authentication " "succeeded for username '%s'", up->username); skip_auth =3D true; @@ -1670,8 +1670,10 @@ { wipe_auth_token(multi); ks->authenticated =3D KS_AUTH_FALSE; - msg(M_WARN, "TLS: Username/auth-token authentication " - "failed for username '%s'", up->username); + msg(M_WARN, + "TLS: Username/auth-token authentication " + "failed for username '%s'", + up->username); return; } } @@ -1716,14 +1718,14 @@ bool plugin_ok =3D plugin_status =3D=3D OPENVPN_PLUGIN_FUNC_SUCCESS || plugin_status =3D=3D OPENVPN_PLUGIN_FUNC_DEFERRED; - bool script_ok =3D script_status =3D=3D OPENVPN_PLUGIN_FUNC_SUCCESS - || script_status =3D=3D OPENVPN_PLUGIN_FUNC_DEFERRED; + bool script_ok =3D script_status =3D=3D OPENVPN_PLUGIN_FUNC_SUCCESS + || script_status =3D=3D OPENVPN_PLUGIN_FUNC_DEFERRED; if (script_ok && plugin_ok && tls_lock_username(multi, up->username) #ifdef ENABLE_MANAGEMENT && man_def_auth !=3D KMDA_ERROR #endif - ) + ) { ks->authenticated =3D KS_AUTH_TRUE; if (plugin_status =3D=3D OPENVPN_PLUGIN_FUNC_DEFERRED @@ -1757,8 +1759,7 @@ * to store the auth-token in multi->auth_token, so * the initial timestamp and session id can be extracted from = it */ - if (!multi->auth_token - && (ks->auth_token_state_flags & AUTH_TOKEN_HMAC_OK) + if (!multi->auth_token && (ks->auth_token_state_flags & AUTH_T= OKEN_HMAC_OK) && !(ks->auth_token_state_flags & AUTH_TOKEN_EXPIRED)) { multi->auth_token =3D strdup(up->password); @@ -1772,8 +1773,7 @@ } msg(D_HANDSHAKE, "TLS: Username/Password authentication %s for use= rname '%s' %s", - (ks->authenticated =3D=3D KS_AUTH_DEFERRED) ? "deferred" : "su= cceeded", - up->username, + (ks->authenticated =3D=3D KS_AUTH_DEFERRED) ? "deferred" : "su= cceeded", up->username, (session->opt->ssl_flags & SSLF_USERNAME_AS_COMMON_NAME) ? "[C= N SET]" : ""); } else @@ -1786,7 +1786,7 @@ void verify_final_auth_checks(struct tls_multi *multi, struct tls_session *sess= ion) { - struct key_state *ks =3D &session->key[KS_PRIMARY]; /* primary ke= y */ + struct key_state *ks =3D &session->key[KS_PRIMARY]; /* primary key */ /* While it shouldn't really happen, don't allow the common name to be= NULL */ if (!session->common_name) @@ -1800,9 +1800,9 @@ const char *cn =3D session->common_name; if (cn && strcmp(cn, multi->locked_cn)) { - msg(D_TLS_ERRORS, "TLS Auth Error: TLS object CN attempted to = change from '%s' to '%s' -- tunnel disabled", - multi->locked_cn, - cn); + msg(D_TLS_ERRORS, + "TLS Auth Error: TLS object CN attempted to change from '%= s' to '%s' -- tunnel disabled", + multi->locked_cn, cn); /* change the common name back to its original value and disab= le the tunnel */ set_common_name(session, multi->locked_cn); @@ -1816,7 +1816,8 @@ const struct cert_hash_set *chs =3D session->cert_hash_set; if (chs && !cert_hash_compare(chs, multi->locked_cert_hash_set)) { - msg(D_TLS_ERRORS, "TLS Auth Error: TLS object CN=3D%s client-p= rovided SSL certs unexpectedly changed during mid-session reauth", + msg(D_TLS_ERRORS, + "TLS Auth Error: TLS object CN=3D%s client-provided SSL ce= rts unexpectedly changed during mid-session reauth", session->common_name); /* disable the tunnel */ @@ -1830,15 +1831,14 @@ struct gc_arena gc =3D gc_new(); const char *cn =3D session->common_name; - const char *path =3D platform_gen_path(session->opt->client_config= _dir_exclusive, - cn, &gc); + const char *path =3D platform_gen_path(session->opt->client_config= _dir_exclusive, cn, &gc); if (!cn || !strcmp(cn, CCD_DEFAULT) || !platform_test_file(path)) { ks->authenticated =3D KS_AUTH_FALSE; wipe_auth_token(multi); - msg(D_TLS_ERRORS, "TLS Auth Error: --client-config-dir authent= ication failed for common name '%s' file=3D'%s'", - session->common_name, - path ? path : "UNDEF"); + msg(D_TLS_ERRORS, + "TLS Auth Error: --client-config-dir authentication failed= for common name '%s' file=3D'%s'", + session->common_name, path ? path : "UNDEF"); } gc_free(&gc); @@ -1852,8 +1852,7 @@ while (item) { struct env_item *next =3D item->next; - if (item->string - && 0 =3D=3D strncmp("X509_", item->string, strlen("X509_"))) + if (item->string && 0 =3D=3D strncmp("X509_", item->string, strlen= ("X509_"))) { env_set_del(es, item->string); } diff --git a/src/openvpn/ssl_verify.h b/src/openvpn/ssl_verify.h index 76f1e24..fdf6bb5 100644 --- a/src/openvpn/ssl_verify.h +++ b/src/openvpn/ssl_verify.h @@ -54,25 +54,27 @@ #define TLS_USERNAME_LEN 64 /** Structure containing the hash for a single certificate */ -struct cert_hash { - unsigned char sha256_hash[256/8]; +struct cert_hash +{ + unsigned char sha256_hash[256 / 8]; }; /** Structure containing the hashes for a full certificate chain */ -struct cert_hash_set { +struct cert_hash_set +{ struct cert_hash *ch[MAX_CERT_DEPTH]; /**< Array of certificate hashes= */ }; -#define VERIFY_X509_NONE 0 -#define VERIFY_X509_SUBJECT_DN 1 -#define VERIFY_X509_SUBJECT_RDN 2 -#define VERIFY_X509_SUBJECT_RDN_PREFIX 3 +#define VERIFY_X509_NONE 0 +#define VERIFY_X509_SUBJECT_DN 1 +#define VERIFY_X509_SUBJECT_RDN 2 +#define VERIFY_X509_SUBJECT_RDN_PREFIX 3 enum tls_auth_status { - TLS_AUTHENTICATION_SUCCEEDED=3D0, - TLS_AUTHENTICATION_FAILED=3D1, - TLS_AUTHENTICATION_DEFERRED=3D2 + TLS_AUTHENTICATION_SUCCEEDED =3D 0, + TLS_AUTHENTICATION_FAILED =3D 1, + TLS_AUTHENTICATION_DEFERRED =3D 2 }; /** @@ -91,8 +93,7 @@ * * @return Current authentication status of the tls_multi */ -enum tls_auth_status -tls_authentication_status(struct tls_multi *multi); +enum tls_auth_status tls_authentication_status(struct tls_multi *multi); /** Check whether the \a ks \c key_state has finished the key exchange part * of the OpenVPN hand shake. This is that the key_method_2read/write @@ -155,8 +156,7 @@ * @param session The session to set the common name for * @param common_name The name to set the common name to */ -void -set_common_name(struct tls_session *session, const char *common_name); +void set_common_name(struct tls_session *session, const char *common_name); /** * Returns the username field for the given tunnel @@ -187,8 +187,7 @@ * @param session The current TLS session * */ -void verify_user_pass(struct user_pass *up, struct tls_multi *multi, - struct tls_session *session); +void verify_user_pass(struct user_pass *up, struct tls_multi *multi, struc= t tls_session *session); /** @@ -203,8 +202,7 @@ * @return true if name is under limit or username-as-common-= name * is not active */ -bool ssl_verify_username_length(struct tls_session *session, - const char *username); +bool ssl_verify_username_length(struct tls_session *session, const char *u= sername); /** * Runs the --client-crresponse script if one is defined. @@ -214,8 +212,7 @@ * the files for the deferred auth like the management commands. * */ -void -verify_crresponse_script(struct tls_multi *multi, const char *cr_response); +void verify_crresponse_script(struct tls_multi *multi, const char *cr_resp= onse); /** * Call the plugin OPENVPN_PLUGIN_CLIENT_CRRESPONSE. @@ -224,8 +221,7 @@ * that it does not directly participate in the authentication but rather * should set the files for the deferred auth like the management commands. */ -void -verify_crresponse_plugin(struct tls_multi *multi, const char *cr_response); +void verify_crresponse_plugin(struct tls_multi *multi, const char *cr_resp= onse); /** * Perform final authentication checks, including locking of the cn, the a= llowed @@ -242,7 +238,7 @@ { const struct x509_track *next; const char *name; -#define XT_FULL_CHAIN (1<<0) +#define XT_FULL_CHAIN (1 << 0) unsigned int flags; int nid; }; @@ -251,11 +247,11 @@ * Certificate checking for verify_nsCertType */ /** Do not perform Netscape certificate type verification */ -#define NS_CERT_CHECK_NONE (0) +#define NS_CERT_CHECK_NONE (0) /** Do not perform Netscape certificate type verification */ -#define NS_CERT_CHECK_SERVER (1<<0) +#define NS_CERT_CHECK_SERVER (1 << 0) /** Do not perform Netscape certificate type verification */ -#define NS_CERT_CHECK_CLIENT (1<<1) +#define NS_CERT_CHECK_CLIENT (1 << 1) /** Require keyUsage to be present in cert (0xFFFF is an invalid KU value)= */ #define OPENVPN_KU_REQUIRED (0xFFFF) @@ -264,7 +260,8 @@ * TODO: document */ #ifdef ENABLE_MANAGEMENT -bool tls_authenticate_key(struct tls_multi *multi, const unsigned int mda_= key_id, const bool auth, const char *client_reason); +bool tls_authenticate_key(struct tls_multi *multi, const unsigned int mda_= key_id, const bool auth, + const char *client_reason); #endif diff --git a/src/openvpn/ssl_verify_backend.h b/src/openvpn/ssl_verify_back= end.h index 03f591c..a0559c9 100644 --- a/src/openvpn/ssl_verify_backend.h +++ b/src/openvpn/ssl_verify_backend.h @@ -32,7 +32,11 @@ /** * Result of verification function */ -typedef enum { SUCCESS =3D 0, FAILURE =3D 1 } result_t; +typedef enum +{ + SUCCESS =3D 0, + FAILURE =3D 1 +} result_t; /* * Backend support functions. @@ -94,8 +98,7 @@ * * @return a string containing the certificate fingerprint */ -struct buffer x509_get_sha1_fingerprint(openvpn_x509_cert_t *cert, - struct gc_arena *gc); +struct buffer x509_get_sha1_fingerprint(openvpn_x509_cert_t *cert, struct = gc_arena *gc); /** * Retrieve the certificate's SHA256 fingerprint. @@ -105,8 +108,7 @@ * * @return a string containing the certificate fingerprint */ -struct buffer x509_get_sha256_fingerprint(openvpn_x509_cert_t *cert, - struct gc_arena *gc); +struct buffer x509_get_sha256_fingerprint(openvpn_x509_cert_t *cert, struc= t gc_arena *gc); /* * Retrieve the certificate's username from the specified field. @@ -121,8 +123,8 @@ * * @return \c FAILURE, \c or SUCCESS */ -result_t backend_x509_get_username(char *common_name, int cn_len, - char *x509_username_field, openvpn_x509= _cert_t *peer_cert); +result_t backend_x509_get_username(char *common_name, int cn_len, char *x5= 09_username_field, + openvpn_x509_cert_t *peer_cert); #ifdef ENABLE_X509ALTUSERNAME /** @@ -157,8 +159,7 @@ * @return String representation of the certificate's serial = number * in hex notation, or NULL on error. */ -char *backend_x509_get_serial_hex(openvpn_x509_cert_t *cert, - struct gc_arena *gc); +char *backend_x509_get_serial_hex(openvpn_x509_cert_t *cert, struct gc_are= na *gc); /* * Write the certificate to the file in PEM format. @@ -168,8 +169,7 @@ * * @return \c FAILURE, \c or SUCCESS */ -result_t backend_x509_write_pem(openvpn_x509_cert_t *cert, - const char *filename); +result_t backend_x509_write_pem(openvpn_x509_cert_t *cert, const char *fil= ename); /* * Save X509 fields to environment, using the naming convention: @@ -193,8 +193,8 @@ * @param gc Garbage collection arena for temp data * */ -void x509_track_add(const struct x509_track **ll_head, const char *name, - int msglevel, struct gc_arena *gc); +void x509_track_add(const struct x509_track **ll_head, const char *name, i= nt msglevel, + struct gc_arena *gc); /* * Save X509 fields to environment, using the naming convention: @@ -216,8 +216,8 @@ * @param cert_depth Depth of the certificate * @param cert Certificate to set the environment for */ -void x509_setenv_track(const struct x509_track *xt, struct env_set *es, - const int depth, openvpn_x509_cert_t *x509); +void x509_setenv_track(const struct x509_track *xt, struct env_set *es, co= nst int depth, + openvpn_x509_cert_t *x509); /* * Check X.509 Netscape certificate type field, if available. diff --git a/src/openvpn/ssl_verify_mbedtls.c b/src/openvpn/ssl_verify_mbed= tls.c index 43bbde5..cfcfb25 100644 --- a/src/openvpn/ssl_verify_mbedtls.c +++ b/src/openvpn/ssl_verify_mbedtls.c @@ -46,10 +46,9 @@ #define MAX_SUBJECT_LENGTH 256 int -verify_callback(void *session_obj, mbedtls_x509_crt *cert, int cert_depth, - uint32_t *flags) +verify_callback(void *session_obj, mbedtls_x509_crt *cert, int cert_depth,= uint32_t *flags) { - struct tls_session *session =3D (struct tls_session *) session_obj; + struct tls_session *session =3D (struct tls_session *)session_obj; struct gc_arena gc =3D gc_new(); ASSERT(cert); @@ -71,8 +70,7 @@ * Clearing these flags relies on verify_cert will later rejecting= a * certificate that has no matching fingerprint. */ - uint32_t flags_ignore =3D MBEDTLS_X509_BADCERT_NOT_TRUSTED - | MBEDTLS_X509_BADCERT_EXPIRED + uint32_t flags_ignore =3D MBEDTLS_X509_BADCERT_NOT_TRUSTED | MBEDT= LS_X509_BADCERT_EXPIRED | MBEDTLS_X509_BADCERT_FUTURE; *flags =3D *flags & ~flags_ignore; } @@ -85,9 +83,10 @@ char *subject =3D x509_get_subject(cert, &gc); char *serial =3D backend_x509_get_serial(cert, &gc); - ret =3D mbedtls_x509_crt_verify_info(errstr, sizeof(errstr)-1, "",= *flags); - if (ret <=3D 0 && !snprintf(errstr, sizeof(errstr), - "Could not retrieve error string, flags= =3D%" PRIx32, *flags)) + ret =3D mbedtls_x509_crt_verify_info(errstr, sizeof(errstr) - 1, "= ", *flags); + if (ret <=3D 0 + && !snprintf(errstr, sizeof(errstr), "Could not retrieve error= string, flags=3D%" PRIx32, + *flags)) { errstr[0] =3D '\0'; } @@ -98,13 +97,15 @@ if (subject) { - msg(D_TLS_ERRORS, "VERIFY ERROR: depth=3D%d, subject=3D%s, ser= ial=3D%s: %s", - cert_depth, subject, serial ? serial : "", = errstr); + msg(D_TLS_ERRORS, "VERIFY ERROR: depth=3D%d, subject=3D%s, ser= ial=3D%s: %s", cert_depth, + subject, serial ? serial : "", errstr); } else { - msg(D_TLS_ERRORS, "VERIFY ERROR: depth=3D%d, (could not extrac= t X509 " - "subject string from certificate): %s", cert_depth, errstr= ); + msg(D_TLS_ERRORS, + "VERIFY ERROR: depth=3D%d, (could not extract X509 " + "subject string from certificate): %s", + cert_depth, errstr); } /* Leave flags set to non-zero to indicate that the cert is not ok= */ @@ -127,20 +128,18 @@ #endif result_t -backend_x509_get_username(char *cn, int cn_len, - char *x509_username_field, mbedtls_x509_crt *cer= t) +backend_x509_get_username(char *cn, int cn_len, char *x509_username_field,= mbedtls_x509_crt *cert) { mbedtls_x509_name *name; - ASSERT( cn !=3D NULL ); + ASSERT(cn !=3D NULL); name =3D &cert->subject; /* Find common name */ while (name !=3D NULL) { - if (0 =3D=3D memcmp(name->oid.p, MBEDTLS_OID_AT_CN, - MBEDTLS_OID_SIZE(MBEDTLS_OID_AT_CN))) + if (0 =3D=3D memcmp(name->oid.p, MBEDTLS_OID_AT_CN, MBEDTLS_OID_SI= ZE(MBEDTLS_OID_AT_CN))) { break; } @@ -157,13 +156,13 @@ /* Found, extract CN */ if (cn_len > name->val.len) { - memcpy( cn, name->val.p, name->val.len ); + memcpy(cn, name->val.p, name->val.len); cn[name->val.len] =3D '\0'; } else { - memcpy( cn, name->val.p, cn_len); - cn[cn_len-1] =3D '\0'; + memcpy(cn, name->val.p, cn_len); + cn[cn_len - 1] =3D '\0'; } return SUCCESS; @@ -178,8 +177,7 @@ /* Transform asn1 integer serial into mbed TLS MPI */ mbedtls_mpi_init(&serial_mpi); - if (!mbed_ok(mbedtls_mpi_read_binary(&serial_mpi, cert->serial.p, - cert->serial.len))) + if (!mbed_ok(mbedtls_mpi_read_binary(&serial_mpi, cert->serial.p, cert= ->serial.len))) { msg(M_WARN, "Failed to retrieve serial from certificate."); goto end; @@ -210,7 +208,7 @@ buf =3D gc_malloc(len, true, gc); - if (mbedtls_x509_serial_gets(buf, len-1, &cert->serial) < 0) + if (mbedtls_x509_serial_gets(buf, len - 1, &cert->serial) < 0) { buf =3D NULL; } @@ -234,7 +232,7 @@ struct buffer der =3D {}; buf_set_read(&der, cert->raw.p, cert->raw.len); - if (!crypto_pem_encode("CERTIFICATE", &pem, &der, &gc)) + if (!crypto_pem_encode("CERTIFICATE", &pem, &der, &gc)) { goto err; } @@ -247,15 +245,13 @@ gc_free(&gc); return SUCCESS; err: - msg(D_TLS_DEBUG_LOW, "Error writing X509 certificate to file %s", - filename); + msg(D_TLS_DEBUG_LOW, "Error writing X509 certificate to file %s", file= name); gc_free(&gc); return FAILURE; } static struct buffer -x509_get_fingerprint(const mbedtls_md_info_t *md_info, mbedtls_x509_crt *c= ert, - struct gc_arena *gc) +x509_get_fingerprint(const mbedtls_md_info_t *md_info, mbedtls_x509_crt *c= ert, struct gc_arena *gc) { const size_t md_size =3D mbedtls_md_get_size(md_info); struct buffer fingerprint =3D alloc_buf_gc(md_size, gc); @@ -267,26 +263,24 @@ struct buffer x509_get_sha1_fingerprint(mbedtls_x509_crt *cert, struct gc_arena *gc) { - return x509_get_fingerprint(mbedtls_md_info_from_type(MBEDTLS_MD_SHA1), - cert, gc); + return x509_get_fingerprint(mbedtls_md_info_from_type(MBEDTLS_MD_SHA1)= , cert, gc); } struct buffer x509_get_sha256_fingerprint(mbedtls_x509_crt *cert, struct gc_arena *gc) { - return x509_get_fingerprint(mbedtls_md_info_from_type(MBEDTLS_MD_SHA25= 6), - cert, gc); + return x509_get_fingerprint(mbedtls_md_info_from_type(MBEDTLS_MD_SHA25= 6), cert, gc); } char * x509_get_subject(mbedtls_x509_crt *cert, struct gc_arena *gc) { - char tmp_subject[MAX_SUBJECT_LENGTH] =3D {0}; + char tmp_subject[MAX_SUBJECT_LENGTH] =3D { 0 }; char *subject =3D NULL; int ret =3D 0; - ret =3D mbedtls_x509_dn_gets( tmp_subject, MAX_SUBJECT_LENGTH-1, &cert= ->subject ); + ret =3D mbedtls_x509_dn_gets(tmp_subject, MAX_SUBJECT_LENGTH - 1, &cer= t->subject); if (ret > 0) { /* Allocate the required space for the subject */ @@ -305,7 +299,7 @@ string_mod(value, CC_ANY, CC_CRLF, '?'); msg(D_X509_ATTR, "X509 ATTRIBUTE name=3D'%s' value=3D'%s' depth=3D%d",= name, value, depth); name_expand_size =3D 64 + strlen(name); - name_expand =3D (char *) malloc(name_expand_size); + name_expand =3D (char *)malloc(name_expand_size); check_malloc_return(name_expand); snprintf(name_expand, name_expand_size, "X509_%d_%s", depth, name); setenv_str(es, name_expand, value); @@ -318,8 +312,7 @@ size_t i; char *val; - if (!(orig->tag =3D=3D MBEDTLS_ASN1_UTF8_STRING - || orig->tag =3D=3D MBEDTLS_ASN1_PRINTABLE_STRING + if (!(orig->tag =3D=3D MBEDTLS_ASN1_UTF8_STRING || orig->tag =3D=3D MB= EDTLS_ASN1_PRINTABLE_STRING || orig->tag =3D=3D MBEDTLS_ASN1_IA5_STRING)) { /* Only support C-string compatible types */ @@ -333,15 +326,15 @@ return string_alloc("ERROR: embedded null value", gc); } } - val =3D gc_malloc(orig->len+1, false, gc); + val =3D gc_malloc(orig->len + 1, false, gc); memcpy(val, orig->p, orig->len); val[orig->len] =3D '\0'; return val; } static void -do_setenv_name(struct env_set *es, const struct x509_track *xt, - const mbedtls_x509_crt *cert, int depth, struct gc_arena *g= c) +do_setenv_name(struct env_set *es, const struct x509_track *xt, const mbed= tls_x509_crt *cert, + int depth, struct gc_arena *gc) { const mbedtls_x509_name *xn; for (xn =3D &cert->subject; xn !=3D NULL; xn =3D xn->next) @@ -357,7 +350,8 @@ } void -x509_track_add(const struct x509_track **ll_head, const char *name, int ms= glevel, struct gc_arena *gc) +x509_track_add(const struct x509_track **ll_head, const char *name, int ms= glevel, + struct gc_arena *gc) { struct x509_track *xt; ALLOC_OBJ_CLEAR_GC(xt, struct x509_track, gc); @@ -372,8 +366,8 @@ } void -x509_setenv_track(const struct x509_track *xt, struct env_set *es, - const int depth, mbedtls_x509_crt *cert) +x509_setenv_track(const struct x509_track *xt, struct env_set *es, const i= nt depth, + mbedtls_x509_crt *cert) { struct gc_arena gc =3D gc_new(); while (xt) @@ -395,8 +389,8 @@ cert_hash =3D x509_get_sha256_fingerprint(cert, &gc); } - fingerprint =3D format_hex_ex(BPTR(&cert_hash), - BLEN(&cert_hash), 0, 1 | FHE_C= APS, ":", &gc); + fingerprint =3D + format_hex_ex(BPTR(&cert_hash), BLEN(&cert_hash), 0, 1= | FHE_CAPS, ":", &gc); do_setenv_x509(es, xt->name, fingerprint, depth); } else @@ -426,29 +420,27 @@ while (name !=3D NULL) { - char name_expand[64+8]; + char name_expand[64 + 8]; const char *shortname; - if (0 =3D=3D mbedtls_oid_get_attr_short_name(&name->oid, &shortnam= e) ) + if (0 =3D=3D mbedtls_oid_get_attr_short_name(&name->oid, &shortnam= e)) { - snprintf(name_expand, sizeof(name_expand), "X509_%d_%s", - cert_depth, shortname); + snprintf(name_expand, sizeof(name_expand), "X509_%d_%s", cert_= depth, shortname); } else { - snprintf(name_expand, sizeof(name_expand), "X509_%d_\?\?", - cert_depth); + snprintf(name_expand, sizeof(name_expand), "X509_%d_\?\?", cer= t_depth); } for (i =3D 0; i < name->val.len; i++) { - if (i >=3D (int) sizeof( s ) - 1) + if (i >=3D (int)sizeof(s) - 1) { break; } c =3D name->val.p[i]; - if (c < 32 || c =3D=3D 127 || ( c > 128 && c < 160 ) ) + if (c < 32 || c =3D=3D 127 || (c > 128 && c < 160)) { s[i] =3D '?'; } @@ -482,15 +474,13 @@ } result_t -x509_verify_cert_ku(mbedtls_x509_crt *cert, const unsigned *const expected= _ku, - int expected_len) +x509_verify_cert_ku(mbedtls_x509_crt *cert, const unsigned *const expected= _ku, int expected_len) { msg(D_HANDSHAKE, "Validating certificate key usage"); if (!mbedtls_x509_crt_has_ext_type(cert, MBEDTLS_X509_EXT_KEY_USAGE)) { - msg(D_TLS_ERRORS, - "ERROR: Certificate does not have key usage extension"); + msg(D_TLS_ERRORS, "ERROR: Certificate does not have key usage exte= nsion"); return FAILURE; } @@ -501,10 +491,9 @@ } result_t fFound =3D FAILURE; - for (size_t i =3D 0; SUCCESS !=3D fFound && i"); + X509_verify_cert_error_string(X509_STORE_CTX_get_error(ctx)), = subject, + serial ? serial : ""); ERR_clear_error(); @@ -120,8 +119,7 @@ return nid =3D=3D NID_subject_alt_name || nid =3D=3D NID_issuer_alt_na= me; } -static -bool +static bool extract_x509_extension(X509 *cert, char *fieldname, char *out, int size) { bool retval =3D false; @@ -129,8 +127,7 @@ if (!x509_username_field_ext_supported(fieldname)) { - msg(D_TLS_ERRORS, - "ERROR: --x509-username-field 'ext:%s' not supported", fieldna= me); + msg(D_TLS_ERRORS, "ERROR: --x509-username-field 'ext:%s' not suppo= rted", fieldname); return false; } @@ -148,10 +145,10 @@ numalts =3D sk_GENERAL_NAME_num(extensions); /* loop through all alternatives */ - for (i =3D 0; itype) { @@ -174,8 +171,8 @@ break; default: - msg(D_TLS_DEBUG, "%s: ignoring general name field type= %i", - __func__, name->type); + msg(D_TLS_DEBUG, "%s: ignoring general name field type= %i", __func__, + name->type); break; } } @@ -198,8 +195,7 @@ * to contain result is grounds for error). */ static result_t -extract_x509_field_ssl(X509_NAME *x509, const char *field_name, char *out, - int size) +extract_x509_field_ssl(X509_NAME *x509, const char *field_name, char *out,= int size) { int lastpos =3D -1; int tmp =3D -1; @@ -256,13 +252,12 @@ } result_t -backend_x509_get_username(char *common_name, int cn_len, - char *x509_username_field, X509 *peer_cert) +backend_x509_get_username(char *common_name, int cn_len, char *x509_userna= me_field, X509 *peer_cert) { #ifdef ENABLE_X509ALTUSERNAME if (strncmp("ext:", x509_username_field, 4) =3D=3D 0) { - if (!extract_x509_extension(peer_cert, x509_username_field+4, comm= on_name, cn_len)) + if (!extract_x509_extension(peer_cert, x509_username_field + 4, co= mmon_name, cn_len)) { return FAILURE; } @@ -271,10 +266,9 @@ { ASN1_INTEGER *asn1_i =3D X509_get_serialNumber(peer_cert); struct gc_arena gc =3D gc_new(); - char *serial =3D format_hex_ex(asn1_i->data, asn1_i->length, - 0, 1 | FHE_CAPS, NULL, &gc); + char *serial =3D format_hex_ex(asn1_i->data, asn1_i->length, 0, 1 = | FHE_CAPS, NULL, &gc); - if (!serial || cn_len <=3D strlen(serial)+2) + if (!serial || cn_len <=3D strlen(serial) + 2) { gc_free(&gc); return FAILURE; @@ -284,11 +278,12 @@ } else #endif /* ifdef ENABLE_X509ALTUSERNAME */ - if (FAILURE =3D=3D extract_x509_field_ssl(X509_get_subject_name(peer_c= ert), - x509_username_field, common_name= , cn_len)) - { - return FAILURE; - } + if (FAILURE + =3D=3D extract_x509_field_ssl(X509_get_subject_name(peer_cert)= , x509_username_field, + common_name, cn_len)) + { + return FAILURE; + } return SUCCESS; } @@ -338,8 +333,7 @@ return SUCCESS; err: BIO_free(out); - crypto_msg(D_TLS_DEBUG_LOW, "Error writing X509 certificate to file %s= ", - filename); + crypto_msg(D_TLS_DEBUG_LOW, "Error writing X509 certificate to file %s= ", filename); return FAILURE; } @@ -376,9 +370,9 @@ goto err; } - X509_NAME_print_ex(subject_bio, X509_get_subject_name(cert), - 0, XN_FLAG_SEP_CPLUS_SPC | XN_FLAG_FN_SN - |ASN1_STRFLGS_UTF8_CONVERT | ASN1_STRFLGS_ESC_CTRL); + X509_NAME_print_ex(subject_bio, X509_get_subject_name(cert), 0, + XN_FLAG_SEP_CPLUS_SPC | XN_FLAG_FN_SN | ASN1_STRFLG= S_UTF8_CONVERT + | ASN1_STRFLGS_ESC_CTRL); if (BIO_eof(subject_bio)) { @@ -420,7 +414,8 @@ */ void -x509_track_add(const struct x509_track **ll_head, const char *name, int ms= glevel, struct gc_arena *gc) +x509_track_add(const struct x509_track **ll_head, const char *name, int ms= glevel, + struct gc_arena *gc) { struct x509_track *xt; ALLOC_OBJ_CLEAR_GC(xt, struct x509_track, gc); @@ -452,7 +447,7 @@ string_mod(value, CC_ANY, CC_CRLF, '?'); msg(D_X509_ATTR, "X509 ATTRIBUTE name=3D'%s' value=3D'%s' depth=3D%d",= name, value, depth); name_expand_size =3D 64 + strlen(name); - name_expand =3D (char *) malloc(name_expand_size); + name_expand =3D (char *)malloc(name_expand_size); check_malloc_return(name_expand); snprintf(name_expand, name_expand_size, "X509_%d_%s", depth, name); setenv_str(es, name_expand, value); @@ -487,8 +482,7 @@ fp_buf =3D x509_get_sha256_fingerprint(x509, &gc); } - fp_str =3D format_hex_ex(BPTR(&fp_buf), BLEN(&fp_buf),= 0, - 1 | FHE_CAPS, ":", &gc); + fp_str =3D format_hex_ex(BPTR(&fp_buf), BLEN(&fp_buf),= 0, 1 | FHE_CAPS, ":", &gc); do_setenv_x509(es, xt->name, fp_str, depth); } break; @@ -595,10 +589,9 @@ continue; } name_expand_size =3D 64 + strlen(objbuf); - name_expand =3D (char *) malloc(name_expand_size); + name_expand =3D (char *)malloc(name_expand_size); check_malloc_return(name_expand); - snprintf(name_expand, name_expand_size, "X509_%d_%s", cert_depth, - objbuf); + snprintf(name_expand, name_expand_size, "X509_%d_%s", cert_depth, = objbuf); string_mod(name_expand, CC_PRINT, CC_CRLF, '_'); string_mod((char *)buf, CC_PRINT, CC_CRLF, '_'); setenv_str_incr(es, name_expand, (char *)buf); @@ -620,8 +613,8 @@ * Unfortunately, X509_check_purpose() does some weird thing that * prevent it to take a const argument */ - result_t result =3D X509_check_purpose(peer_cert, X509_PURPOSE_SSL= _CLIENT, 0) ? - SUCCESS : FAILURE; + result_t result =3D + X509_check_purpose(peer_cert, X509_PURPOSE_SSL_CLIENT, 0) ? SU= CCESS : FAILURE; /* * old versions of OpenSSL allow us to make the less strict check = we used to @@ -636,7 +629,7 @@ if (result =3D=3D SUCCESS) { msg(M_WARN, "X509: Certificate is a client certificate yet= it's purpose " - "cannot be verified (check may fail in the future)"); + "cannot be verified (check may fail in the fut= ure)"); } ASN1_BIT_STRING_free(ns); } @@ -648,8 +641,8 @@ * Unfortunately, X509_check_purpose() does some weird thing that * prevent it to take a const argument */ - result_t result =3D X509_check_purpose(peer_cert, X509_PURPOSE_SSL= _SERVER, 0) ? - SUCCESS : FAILURE; + result_t result =3D + X509_check_purpose(peer_cert, X509_PURPOSE_SSL_SERVER, 0) ? SU= CCESS : FAILURE; /* * old versions of OpenSSL allow us to make the less strict check = we used to @@ -664,7 +657,7 @@ if (result =3D=3D SUCCESS) { msg(M_WARN, "X509: Certificate is a server certificate yet= it's purpose " - "cannot be verified (check may fail in the future)"); + "cannot be verified (check may fail in the fut= ure)"); } ASN1_BIT_STRING_free(ns); } @@ -675,8 +668,7 @@ } result_t -x509_verify_cert_ku(X509 *x509, const unsigned *const expected_ku, - int expected_len) +x509_verify_cert_ku(X509 *x509, const unsigned *const expected_ku, int exp= ected_len) { ASN1_BIT_STRING *ku =3D X509_get_ext_d2i(x509, NID_key_usage, NULL, NU= LL); @@ -722,8 +714,7 @@ if (fFound !=3D SUCCESS) { - msg(D_TLS_ERRORS, - "ERROR: Certificate has key usage %04x, expected one of:", nku= ); + msg(D_TLS_ERRORS, "ERROR: Certificate has key usage %04x, expected= one of:", nku); for (size_t i =3D 0; i < expected_len && expected_ku[i]; i++) { msg(D_TLS_ERRORS, " * %04x", expected_ku[i]); @@ -741,8 +732,7 @@ EXTENDED_KEY_USAGE *eku =3D NULL; result_t fFound =3D FAILURE; - if ((eku =3D (EXTENDED_KEY_USAGE *) X509_get_ext_d2i(x509, NID_ext_key= _usage, - NULL, NULL)) =3D=3D= NULL) + if ((eku =3D (EXTENDED_KEY_USAGE *)X509_get_ext_d2i(x509, NID_ext_key_= usage, NULL, NULL)) =3D=3D NULL) { msg(D_HANDSHAKE, "Certificate does not have extended key usage ext= ension"); } @@ -758,8 +748,8 @@ if (SUCCESS !=3D fFound && OBJ_obj2txt(szOid, sizeof(szOid), o= id, 0) !=3D -1) { - msg(D_HANDSHAKE, "++ Certificate has EKU (str) %s, expects= %s", - szOid, expected_oid); + msg(D_HANDSHAKE, "++ Certificate has EKU (str) %s, expects= %s", szOid, + expected_oid); if (!strcmp(expected_oid, szOid)) { fFound =3D SUCCESS; @@ -767,8 +757,8 @@ } if (SUCCESS !=3D fFound && OBJ_obj2txt(szOid, sizeof(szOid), o= id, 1) !=3D -1) { - msg(D_HANDSHAKE, "++ Certificate has EKU (oid) %s, expects= %s", - szOid, expected_oid); + msg(D_HANDSHAKE, "++ Certificate has EKU (oid) %s, expects= %s", szOid, + expected_oid); if (!strcmp(expected_oid, szOid)) { fFound =3D SUCCESS; diff --git a/src/openvpn/status.c b/src/openvpn/status.c index 1f5e67a..34e5a2f 100644 --- a/src/openvpn/status.c +++ b/src/openvpn/status.c @@ -48,7 +48,7 @@ case STATUS_OUTPUT_READ: return "READ"; - case STATUS_OUTPUT_READ|STATUS_OUTPUT_WRITE: + case STATUS_OUTPUT_READ | STATUS_OUTPUT_WRITE: return "READ/WRITE"; default: @@ -57,11 +57,8 @@ } struct status_output * -status_open(const char *filename, - const int refresh_freq, - const int msglevel, - const struct virtual_output *vout, - const unsigned int flags) +status_open(const char *filename, const int refresh_freq, const int msglev= el, + const struct virtual_output *vout, const unsigned int flags) { struct status_output *so =3D NULL; if (filename || msglevel >=3D 0 || vout) @@ -78,21 +75,16 @@ switch (so->flags) { case STATUS_OUTPUT_WRITE: - so->fd =3D platform_open(filename, - O_CREAT | O_TRUNC | O_WRONLY, - S_IRUSR | S_IWUSR); + so->fd =3D + platform_open(filename, O_CREAT | O_TRUNC | O_WRON= LY, S_IRUSR | S_IWUSR); break; case STATUS_OUTPUT_READ: - so->fd =3D platform_open(filename, - O_RDONLY, - S_IRUSR | S_IWUSR); + so->fd =3D platform_open(filename, O_RDONLY, S_IRUSR |= S_IWUSR); break; - case STATUS_OUTPUT_READ|STATUS_OUTPUT_WRITE: - so->fd =3D platform_open(filename, - O_CREAT | O_RDWR, - S_IRUSR | S_IWUSR); + case STATUS_OUTPUT_READ | STATUS_OUTPUT_WRITE: + so->fd =3D platform_open(filename, O_CREAT | O_RDWR, S= _IRUSR | S_IWUSR); break; default: @@ -167,10 +159,10 @@ } #elif defined(HAVE_CHSIZE) { - const long off =3D (long) lseek(so->fd, (off_t)0, SEEK_CUR); + const long off =3D (long)lseek(so->fd, (off_t)0, SEEK_CUR); chsize(so->fd, off); } -#else /* if defined(HAVE_FTRUNCATE) */ +#else /* if defined(HAVE_FTRUNCATE) */ #warning both ftruncate and chsize functions appear to be missing from thi= s OS #endif @@ -222,7 +214,7 @@ { if (so && (so->flags & STATUS_OUTPUT_WRITE)) { - char buf[STATUS_PRINTF_MAXLEN+2]; /* leave extra bytes for CR, LF = */ + char buf[STATUS_PRINTF_MAXLEN + 2]; /* leave extra bytes for CR, L= F */ va_list arglist; int stat; diff --git a/src/openvpn/status.h b/src/openvpn/status.h index ddbaeef..0c7a869 100644 --- a/src/openvpn/status.h +++ b/src/openvpn/status.h @@ -28,10 +28,11 @@ /* * virtual function interface for status output */ -struct virtual_output { +struct virtual_output +{ void *arg; unsigned int flags_default; - void (*func) (void *arg, const unsigned int flags, const char *str); + void (*func)(void *arg, const unsigned int flags, const char *str); }; static inline void @@ -46,8 +47,8 @@ struct status_output { -#define STATUS_OUTPUT_READ (1<<0) -#define STATUS_OUTPUT_WRITE (1<<1) +#define STATUS_OUTPUT_READ (1 << 0) +#define STATUS_OUTPUT_WRITE (1 << 1) unsigned int flags; char *filename; @@ -62,11 +63,8 @@ bool errors; }; -struct status_output *status_open(const char *filename, - const int refresh_freq, - const int msglevel, - const struct virtual_output *vout, - const unsigned int flags); +struct status_output *status_open(const char *filename, const int refresh_= freq, const int msglevel, + const struct virtual_output *vout, const= unsigned int flags); bool status_trigger(struct status_output *so); @@ -79,12 +77,12 @@ void status_printf(struct status_output *so, const char *format, ...) #ifdef __GNUC__ #if __USE_MINGW_ANSI_STDIO -__attribute__ ((format(gnu_printf, 2, 3))) + __attribute__((format(gnu_printf, 2, 3))) #else -__attribute__ ((format(__printf__, 2, 3))) + __attribute__((format(__printf__, 2, 3))) #endif #endif -; + ; bool status_read(struct status_output *so, struct buffer *buf); diff --git a/src/openvpn/syshead.h b/src/openvpn/syshead.h index e77f313..524923b 100644 --- a/src/openvpn/syshead.h +++ b/src/openvpn/syshead.h @@ -28,20 +28,20 @@ /* branch prediction hints */ #if defined(__GNUC__) -#define likely(x) __builtin_expect((x), 1) -#define unlikely(x) __builtin_expect((x), 0) +#define likely(x) __builtin_expect((x), 1) +#define unlikely(x) __builtin_expect((x), 0) #else -#define likely(x) (x) -#define unlikely(x) (x) +#define likely(x) (x) +#define unlikely(x) (x) #endif #ifdef _WIN32 #include #include #include -#define sleep(x) Sleep((x)*1000) -#define random rand -#define srandom srand +#define sleep(x) Sleep((x) * 1000) +#define random rand +#define srandom srand #endif #ifdef _MSC_VER /* Visual Studio */ @@ -51,7 +51,7 @@ #if defined(__APPLE__) #if __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ >=3D 1070 -#define __APPLE_USE_RFC_3542 1 +#define __APPLE_USE_RFC_3542 1 #endif #endif @@ -166,10 +166,10 @@ #endif #if defined(TARGET_HAIKU) -#include /* uint32, etc */ -#include /* ifconf etc */ -#include /* SIOCGRTTABLE, etc */ -#endif /* TARGET_HAIKU */ +#include /* uint32, etc */ +#include /* ifconf etc */ +#include /* SIOCGRTTABLE, etc */ +#endif /* TARGET_HAIKU */ #ifdef HAVE_ARPA_INET_H #include @@ -183,7 +183,7 @@ #include #endif -#if defined(TARGET_LINUX) || defined (TARGET_ANDROID) +#if defined(TARGET_LINUX) || defined(TARGET_ANDROID) #ifdef HAVE_LINUX_IF_TUN_H #include @@ -373,7 +373,9 @@ * Does this platform support linux-style IP_PKTINFO * or bsd-style IP_RECVDSTADDR ? */ -#if ((defined(HAVE_IN_PKTINFO) && defined(IP_PKTINFO)) || defined(IP_RECVD= STADDR)) && defined(HAVE_MSGHDR) && defined(HAVE_CMSGHDR) && defined(CMSG_F= IRSTHDR) && defined(CMSG_NXTHDR) && defined(HAVE_RECVMSG) && defined(HAVE_S= ENDMSG) +#if ((defined(HAVE_IN_PKTINFO) && defined(IP_PKTINFO)) || defined(IP_RECVD= STADDR)) \ + && defined(HAVE_MSGHDR) && defined(HAVE_CMSGHDR) && defined(CMSG_FIRST= HDR) \ + && defined(CMSG_NXTHDR) && defined(HAVE_RECVMSG) && defined(HAVE_SENDM= SG) #define ENABLE_IP_PKTINFO 1 #else #define ENABLE_IP_PKTINFO 0 @@ -422,10 +424,10 @@ * Directory separation char */ #ifdef _WIN32 -#define PATH_SEPARATOR '\\' +#define PATH_SEPARATOR '\\' #define PATH_SEPARATOR_STR "\\" #else -#define PATH_SEPARATOR '/' +#define PATH_SEPARATOR '/' #define PATH_SEPARATOR_STR "/" #endif @@ -434,11 +436,11 @@ */ #ifdef _WIN32 #define SOCKET_UNDEFINED (INVALID_SOCKET) -#define SOCKET_PRINTF "%" PRIxPTR +#define SOCKET_PRINTF "%" PRIxPTR typedef SOCKET socket_descriptor_t; #else #define SOCKET_UNDEFINED (-1) -#define SOCKET_PRINTF "%d" +#define SOCKET_PRINTF "%d" typedef int socket_descriptor_t; #endif @@ -459,7 +461,9 @@ /* * HTTPS port sharing capability */ -#if defined(ENABLE_PORT_SHARE) && defined(SCM_RIGHTS) && defined(HAVE_MSGH= DR) && defined(HAVE_CMSGHDR) && defined(CMSG_FIRSTHDR) && defined(CMSG_NXTH= DR) && defined(HAVE_RECVMSG) && defined(HAVE_SENDMSG) +#if defined(ENABLE_PORT_SHARE) && defined(SCM_RIGHTS) && defined(HAVE_MSGH= DR) \ + && defined(HAVE_CMSGHDR) && defined(CMSG_FIRSTHDR) && defined(CMSG_NXT= HDR) \ + && defined(HAVE_RECVMSG) && defined(HAVE_SENDMSG) #define PORT_SHARE 1 #else #define PORT_SHARE 0 @@ -493,8 +497,7 @@ /* * Do we have CryptoAPI capability? */ -#if defined(_WIN32) && defined(ENABLE_CRYPTO_OPENSSL) \ - && !defined(ENABLE_CRYPTO_WOLFSSL) +#if defined(_WIN32) && defined(ENABLE_CRYPTO_OPENSSL) && !defined(ENABLE_C= RYPTO_WOLFSSL) #define ENABLE_CRYPTOAPI #endif @@ -521,8 +524,7 @@ /* * Compression support */ -#if defined(ENABLE_LZO) || defined(ENABLE_LZ4) \ - || defined(ENABLE_COMP_STUB) +#if defined(ENABLE_LZO) || defined(ENABLE_LZ4) || defined(ENABLE_COMP_STUB) #define USE_COMP #endif diff --git a/src/openvpn/tls_crypt.c b/src/openvpn/tls_crypt.c index b0c4291..2892199 100644 --- a/src/openvpn/tls_crypt.c +++ b/src/openvpn/tls_crypt.c @@ -40,9 +40,9 @@ const char *tls_crypt_v2_srv_pem_name =3D "OpenVPN tls-crypt-v2 server key= "; /** Metadata contains user-specified data */ -static const uint8_t TLS_CRYPT_METADATA_TYPE_USER =3D 0x00; +static const uint8_t TLS_CRYPT_METADATA_TYPE_USER =3D 0x00; /** Metadata contains a 64-bit unix timestamp in network byte order */ -static const uint8_t TLS_CRYPT_METADATA_TYPE_TIMESTAMP =3D 0x01; +static const uint8_t TLS_CRYPT_METADATA_TYPE_TIMESTAMP =3D 0x01; static struct key_type tls_crypt_kt(void) @@ -57,11 +57,10 @@ } void -tls_crypt_init_key(struct key_ctx_bi *key, struct key2 *keydata, - const char *key_file, bool key_inline, bool tls_server) +tls_crypt_init_key(struct key_ctx_bi *key, struct key2 *keydata, const cha= r *key_file, + bool key_inline, bool tls_server) { - const int key_direction =3D tls_server ? - KEY_DIRECTION_NORMAL : KEY_DIRECTION_INVERSE; + const int key_direction =3D tls_server ? KEY_DIRECTION_NORMAL : KEY_DI= RECTION_INVERSE; struct key_type kt =3D tls_crypt_kt(); if (!kt.cipher || !kt.digest) { @@ -89,7 +88,6 @@ { key->keys[k].hmac[j] =3D key->keys[k].hmac[j] ^ other->keys[k]= .hmac[j]; } - } } @@ -98,8 +96,8 @@ { struct key2 rengokeys; if (!key_state_export_keying_material(session, EXPORT_DYNAMIC_TLS_CRYP= T_LABEL, - strlen(EXPORT_DYNAMIC_TLS_CRYPT_= LABEL), - rengokeys.keys, sizeof(rengokeys= .keys))) + strlen(EXPORT_DYNAMIC_TLS_CRYPT_= LABEL), rengokeys.keys, + sizeof(rengokeys.keys))) { return false; } @@ -111,27 +109,23 @@ session->tls_wrap_reneg.work =3D alloc_buf(BUF_SIZE(&session->opt->fra= me)); session->tls_wrap_reneg.opt.pid_persist =3D NULL; - packet_id_init(&session->tls_wrap_reneg.opt.packet_id, - session->opt->replay_window, - session->opt->replay_time, - "TLS_WRAP_RENEG", session->key_id); + packet_id_init(&session->tls_wrap_reneg.opt.packet_id, session->opt->r= eplay_window, + session->opt->replay_time, "TLS_WRAP_RENEG", session->k= ey_id); - if (session->tls_wrap.mode =3D=3D TLS_WRAP_CRYPT - || session->tls_wrap.mode =3D=3D TLS_WRAP_AUTH) + if (session->tls_wrap.mode =3D=3D TLS_WRAP_CRYPT || session->tls_wrap.= mode =3D=3D TLS_WRAP_AUTH) { xor_key2(&rengokeys, &session->tls_wrap.original_wrap_keydata); } - const int key_direction =3D session->opt->server ? - KEY_DIRECTION_NORMAL : KEY_DIRECTION_INVERSE; + const int key_direction =3D session->opt->server ? KEY_DIRECTION_NORMA= L : KEY_DIRECTION_INVERSE; struct key_direction_state kds; key_direction_state_init(&kds, key_direction); struct key_type kt =3D tls_crypt_kt(); - init_key_ctx_bi(&session->tls_wrap_reneg.opt.key_ctx_bi, &rengokeys, k= ey_direction, - &kt, "dynamic tls-crypt"); + init_key_ctx_bi(&session->tls_wrap_reneg.opt.key_ctx_bi, &rengokeys, k= ey_direction, &kt, + "dynamic tls-crypt"); secure_memzero(&rengokeys, sizeof(rengokeys)); return true; @@ -139,8 +133,7 @@ bool -tls_crypt_wrap(const struct buffer *src, struct buffer *dst, - struct crypto_options *opt) +tls_crypt_wrap(const struct buffer *src, struct buffer *dst, struct crypto= _options *opt) { const struct key_ctx *ctx =3D &opt->key_ctx_bi.encrypt; struct gc_arena gc; @@ -149,12 +142,11 @@ ASSERT(ctx->cipher); ASSERT(ctx->hmac); ASSERT(packet_id_initialized(&opt->packet_id)); - ASSERT(hmac_ctx_size(ctx->hmac) =3D=3D 256/8); + ASSERT(hmac_ctx_size(ctx->hmac) =3D=3D 256 / 8); gc_init(&gc); - dmsg(D_PACKET_CONTENT, "TLS-CRYPT WRAP FROM: %s", - format_hex(BPTR(src), BLEN(src), 80, &gc)); + dmsg(D_PACKET_CONTENT, "TLS-CRYPT WRAP FROM: %s", format_hex(BPTR(src)= , BLEN(src), 80, &gc)); /* Get packet ID */ if (!packet_id_write(&opt->packet_id.send, dst, true, false)) @@ -163,15 +155,15 @@ goto err; } - dmsg(D_PACKET_CONTENT, "TLS-CRYPT WRAP AD: %s", - format_hex(BPTR(dst), BLEN(dst), 0, &gc)); + dmsg(D_PACKET_CONTENT, "TLS-CRYPT WRAP AD: %s", format_hex(BPTR(dst), = BLEN(dst), 0, &gc)); /* Buffer overflow check */ if (!buf_safe(dst, BLEN(src) + TLS_CRYPT_BLOCK_SIZE + TLS_CRYPT_TAG_SI= ZE)) { - msg(D_CRYPT_ERRORS, "TLS-CRYPT WRAP: buffer size error, " - "sc=3D%d so=3D%d sl=3D%d dc=3D%d do=3D%d dl=3D%d", src->capaci= ty, src->offset, - src->len, dst->capacity, dst->offset, dst->len); + msg(D_CRYPT_ERRORS, + "TLS-CRYPT WRAP: buffer size error, " + "sc=3D%d so=3D%d sl=3D%d dc=3D%d do=3D%d dl=3D%d", + src->capacity, src->offset, src->len, dst->capacity, dst->offs= et, dst->len); goto err; } @@ -195,15 +187,13 @@ /* Encrypt src */ { int outlen =3D 0; - ASSERT(cipher_ctx_update(ctx->cipher, BEND(dst), &outlen, - BPTR(src), BLEN(src))); + ASSERT(cipher_ctx_update(ctx->cipher, BEND(dst), &outlen, BPTR(src= ), BLEN(src))); ASSERT(buf_inc_len(dst, outlen)); ASSERT(cipher_ctx_final(ctx->cipher, BPTR(dst), &outlen)); ASSERT(buf_inc_len(dst, outlen)); } - dmsg(D_PACKET_CONTENT, "TLS-CRYPT WRAP TO: %s", - format_hex(BPTR(dst), BLEN(dst), 80, &gc)); + dmsg(D_PACKET_CONTENT, "TLS-CRYPT WRAP TO: %s", format_hex(BPTR(dst), = BLEN(dst), 80, &gc)); gc_free(&gc); return true; @@ -216,8 +206,7 @@ } bool -tls_crypt_unwrap(const struct buffer *src, struct buffer *dst, - struct crypto_options *opt) +tls_crypt_unwrap(const struct buffer *src, struct buffer *dst, struct cryp= to_options *opt) { static const char error_prefix[] =3D "tls-crypt unwrap error"; const struct key_ctx *ctx =3D &opt->key_ctx_bi.decrypt; @@ -228,11 +217,9 @@ ASSERT(opt); ASSERT(src->len > 0); ASSERT(ctx->cipher); - ASSERT(packet_id_initialized(&opt->packet_id) - || (opt->flags & CO_IGNORE_PACKET_ID)); + ASSERT(packet_id_initialized(&opt->packet_id) || (opt->flags & CO_IGNO= RE_PACKET_ID)); - dmsg(D_PACKET_CONTENT, "TLS-CRYPT UNWRAP FROM: %s", - format_hex(BPTR(src), BLEN(src), 80, &gc)); + dmsg(D_PACKET_CONTENT, "TLS-CRYPT UNWRAP FROM: %s", format_hex(BPTR(sr= c), BLEN(src), 80, &gc)); if (buf_len(src) < TLS_CRYPT_OFF_CT) { @@ -253,8 +240,8 @@ { CRYPT_ERROR("cipher reset failed"); } - if (!cipher_ctx_update(ctx->cipher, BPTR(dst), &outlen, - BPTR(src) + TLS_CRYPT_OFF_CT, BLEN(src) - T= LS_CRYPT_OFF_CT)) + if (!cipher_ctx_update(ctx->cipher, BPTR(dst), &outlen, BPTR(src) = + TLS_CRYPT_OFF_CT, + BLEN(src) - TLS_CRYPT_OFF_CT)) { CRYPT_ERROR("cipher update failed"); } @@ -283,10 +270,8 @@ if (memcmp_constant_time(tag, tag_check, sizeof(tag_check))) { - dmsg(D_CRYPTO_DEBUG, "tag : %s", - format_hex(tag, sizeof(tag_check), 0, &gc)); - dmsg(D_CRYPTO_DEBUG, "tag_check: %s", - format_hex(tag_check, sizeof(tag_check), 0, &gc)); + dmsg(D_CRYPTO_DEBUG, "tag : %s", format_hex(tag, sizeof(t= ag_check), 0, &gc)); + dmsg(D_CRYPTO_DEBUG, "tag_check: %s", format_hex(tag_check, si= zeof(tag_check), 0, &gc)); CRYPT_ERROR("packet authentication failed"); } } @@ -315,30 +300,24 @@ } static inline void -tls_crypt_v2_load_client_key(struct key_ctx_bi *key, const struct key2 *ke= y2, - bool tls_server) +tls_crypt_v2_load_client_key(struct key_ctx_bi *key, const struct key2 *ke= y2, bool tls_server) { - const int key_direction =3D tls_server ? - KEY_DIRECTION_NORMAL : KEY_DIRECTION_INVERSE; + const int key_direction =3D tls_server ? KEY_DIRECTION_NORMAL : KEY_DI= RECTION_INVERSE; struct key_type kt =3D tls_crypt_kt(); if (!kt.cipher || !kt.digest) { msg(M_FATAL, "ERROR: --tls-crypt-v2 not supported"); } - init_key_ctx_bi(key, key2, key_direction, &kt, - "Control Channel Encryption"); + init_key_ctx_bi(key, key2, key_direction, &kt, "Control Channel Encryp= tion"); } void tls_crypt_v2_init_client_key(struct key_ctx_bi *key, struct key2 *original= _key, - struct buffer *wkc_buf, const char *key_file, - bool key_inline) + struct buffer *wkc_buf, const char *key_file,= bool key_inline) { - struct buffer client_key =3D alloc_buf(TLS_CRYPT_V2_CLIENT_KEY_LEN - + TLS_CRYPT_V2_MAX_WKC_LEN); + struct buffer client_key =3D alloc_buf(TLS_CRYPT_V2_CLIENT_KEY_LEN + T= LS_CRYPT_V2_MAX_WKC_LEN); - if (!read_pem_key_file(&client_key, tls_crypt_v2_cli_pem_name, - key_file, key_inline)) + if (!read_pem_key_file(&client_key, tls_crypt_v2_cli_pem_name, key_fil= e, key_inline)) { msg(M_FATAL, "ERROR: invalid tls-crypt-v2 client key format"); } @@ -356,15 +335,14 @@ } void -tls_crypt_v2_init_server_key(struct key_ctx *key_ctx, bool encrypt, - const char *key_file, bool key_inline) +tls_crypt_v2_init_server_key(struct key_ctx *key_ctx, bool encrypt, const = char *key_file, + bool key_inline) { struct key srv_key; struct buffer srv_key_buf; buf_set_write(&srv_key_buf, (void *)&srv_key, sizeof(srv_key)); - if (!read_pem_key_file(&srv_key_buf, tls_crypt_v2_srv_pem_name, - key_file, key_inline)) + if (!read_pem_key_file(&srv_key_buf, tls_crypt_v2_srv_pem_name, key_fi= le, key_inline)) { msg(M_FATAL, "ERROR: invalid tls-crypt-v2 server key format"); } @@ -383,14 +361,13 @@ } static bool -tls_crypt_v2_wrap_client_key(struct buffer *wkc, - const struct key2 *src_key, - const struct buffer *src_metadata, - struct key_ctx *server_key, struct gc_arena *= gc) +tls_crypt_v2_wrap_client_key(struct buffer *wkc, const struct key2 *src_ke= y, + const struct buffer *src_metadata, struct key= _ctx *server_key, + struct gc_arena *gc) { cipher_ctx_t *cipher_ctx =3D server_key->cipher; - struct buffer work =3D alloc_buf_gc(TLS_CRYPT_V2_MAX_WKC_LEN - + cipher_ctx_block_size(cipher_ctx),= gc); + struct buffer work =3D + alloc_buf_gc(TLS_CRYPT_V2_MAX_WKC_LEN + cipher_ctx_block_size(ciph= er_ctx), gc); /* Calculate auth tag and synthetic IV */ uint8_t *tag =3D buf_write_alloc(&work, TLS_CRYPT_TAG_SIZE); @@ -399,8 +376,8 @@ msg(M_WARN, "ERROR: could not write tag"); return false; } - uint16_t net_len =3D htons(sizeof(src_key->keys) + BLEN(src_metadata) - + TLS_CRYPT_V2_TAG_SIZE + sizeof(uint16_t)); + uint16_t net_len =3D htons(sizeof(src_key->keys) + BLEN(src_metadata) = + TLS_CRYPT_V2_TAG_SIZE + + sizeof(uint16_t)); hmac_ctx_t *hmac_ctx =3D server_key->hmac; hmac_ctx_reset(hmac_ctx); hmac_ctx_update(hmac_ctx, (void *)&net_len, sizeof(net_len)); @@ -408,16 +385,13 @@ hmac_ctx_update(hmac_ctx, BPTR(src_metadata), BLEN(src_metadata)); hmac_ctx_final(hmac_ctx, tag); - dmsg(D_CRYPTO_DEBUG, "TLS-CRYPT WRAP TAG: %s", - format_hex(tag, TLS_CRYPT_TAG_SIZE, 0, gc)); + dmsg(D_CRYPTO_DEBUG, "TLS-CRYPT WRAP TAG: %s", format_hex(tag, TLS_CRY= PT_TAG_SIZE, 0, gc)); /* Use the 128 most significant bits of the tag as IV */ ASSERT(cipher_ctx_reset(cipher_ctx, tag)); /* Overflow check (OpenSSL requires an extra block in the dst buffer) = */ - if (buf_forward_capacity(&work) < (sizeof(src_key->keys) - + BLEN(src_metadata) - + sizeof(net_len) + if (buf_forward_capacity(&work) < (sizeof(src_key->keys) + BLEN(src_me= tadata) + sizeof(net_len) + cipher_ctx_block_size(cipher_ctx)= )) { msg(M_WARN, "ERROR: could not crypt: insufficient space in dst"); @@ -426,11 +400,11 @@ /* Encrypt */ int outlen =3D 0; - ASSERT(cipher_ctx_update(cipher_ctx, BEND(&work), &outlen, - (void *)src_key->keys, sizeof(src_key->keys))= ); + ASSERT(cipher_ctx_update(cipher_ctx, BEND(&work), &outlen, (void *)src= _key->keys, + sizeof(src_key->keys))); ASSERT(buf_inc_len(&work, outlen)); - ASSERT(cipher_ctx_update(cipher_ctx, BEND(&work), &outlen, - BPTR(src_metadata), BLEN(src_metadata))); + ASSERT(cipher_ctx_update(cipher_ctx, BEND(&work), &outlen, BPTR(src_me= tadata), + BLEN(src_metadata))); ASSERT(buf_inc_len(&work, outlen)); ASSERT(cipher_ctx_final(cipher_ctx, BEND(&work), &outlen)); ASSERT(buf_inc_len(&work, outlen)); @@ -441,8 +415,7 @@ static bool tls_crypt_v2_unwrap_client_key(struct key2 *client_key, struct buffer *met= adata, - struct buffer wrapped_client_key, - struct key_ctx *server_key) + struct buffer wrapped_client_key, struct ke= y_ctx *server_key) { const char *error_prefix =3D __func__; bool ret =3D false; @@ -454,9 +427,8 @@ struct buffer plaintext =3D { 0 }; dmsg(D_TLS_DEBUG_MED, "%s: unwrapping client key (len=3D%d): %s", __fu= nc__, - BLEN(&wrapped_client_key), format_hex(BPTR(&wrapped_client_key), - BLEN(&wrapped_client_key), - 0, &gc)); + BLEN(&wrapped_client_key), + format_hex(BPTR(&wrapped_client_key), BLEN(&wrapped_client_key), = 0, &gc)); if (TLS_CRYPT_V2_MAX_WKC_LEN < BLEN(&wrapped_client_key)) { @@ -471,13 +443,12 @@ { CRYPT_ERROR("failed to read length"); } - memcpy(&net_len, BEND(&wrapped_client_key) - sizeof(net_len), - sizeof(net_len)); + memcpy(&net_len, BEND(&wrapped_client_key) - sizeof(net_len), sizeof(n= et_len)); if (ntohs(net_len) !=3D BLEN(&wrapped_client_key)) { - dmsg(D_TLS_DEBUG_LOW, "%s: net_len=3D%u, BLEN=3D%i", __func__, - ntohs(net_len), BLEN(&wrapped_client_key)); + dmsg(D_TLS_DEBUG_LOW, "%s: net_len=3D%u, BLEN=3D%i", __func__, nto= hs(net_len), + BLEN(&wrapped_client_key)); CRYPT_ERROR("invalid length"); } @@ -494,8 +465,7 @@ } buf_set_write(&plaintext, plaintext_buf_data, sizeof(plaintext_buf_dat= a)); int outlen =3D 0; - if (!cipher_ctx_update(server_key->cipher, BPTR(&plaintext), &outlen, - BPTR(&wrapped_client_key), + if (!cipher_ctx_update(server_key->cipher, BPTR(&plaintext), &outlen, = BPTR(&wrapped_client_key), BLEN(&wrapped_client_key))) { CRYPT_ERROR("could not decrypt client key"); @@ -512,19 +482,16 @@ uint8_t tag_check[TLS_CRYPT_TAG_SIZE] =3D { 0 }; hmac_ctx_reset(server_key->hmac); hmac_ctx_update(server_key->hmac, (void *)&net_len, sizeof(net_len)); - hmac_ctx_update(server_key->hmac, BPTR(&plaintext), - BLEN(&plaintext)); + hmac_ctx_update(server_key->hmac, BPTR(&plaintext), BLEN(&plaintext)); hmac_ctx_final(server_key->hmac, tag_check); if (memcmp_constant_time(tag, tag_check, sizeof(tag_check))) { - dmsg(D_CRYPTO_DEBUG, "tag : %s", - format_hex(tag, sizeof(tag_check), 0, &gc)); - dmsg(D_CRYPTO_DEBUG, "tag_check: %s", - format_hex(tag_check, sizeof(tag_check), 0, &gc)); + dmsg(D_CRYPTO_DEBUG, "tag : %s", format_hex(tag, sizeof(tag_c= heck), 0, &gc)); + dmsg(D_CRYPTO_DEBUG, "tag_check: %s", format_hex(tag_check, sizeof= (tag_check), 0, &gc)); CRYPT_ERROR("client key authentication error"); msg(D_TLS_DEBUG_LOW, "This might be a client-key that was generate= d for " - "a different tls-crypt-v2 server key)"); + "a different tls-crypt-v2 server key)"); } if (buf_len(&plaintext) < sizeof(client_key->keys)) @@ -552,8 +519,7 @@ } static bool -tls_crypt_v2_verify_metadata(const struct tls_wrap_ctx *ctx, - const struct tls_options *opt) +tls_crypt_v2_verify_metadata(const struct tls_wrap_ctx *ctx, const struct = tls_options *opt) { bool ret =3D false; struct gc_arena gc =3D gc_new(); @@ -566,8 +532,7 @@ goto cleanup; } - tmp_file =3D platform_create_temp_file(opt->tmp_dir, "tls_crypt_v2_met= adata_", - &gc); + tmp_file =3D platform_create_temp_file(opt->tmp_dir, "tls_crypt_v2_met= adata_", &gc); if (!tmp_file || !buffer_write_file(tmp_file, &metadata)) { msg(M_WARN, "ERROR: could not write metadata to file"); @@ -575,8 +540,7 @@ } char metadata_type_str[4] =3D { 0 }; /* Max value: 255 */ - snprintf(metadata_type_str, sizeof(metadata_type_str), - "%i", (uint8_t) metadata_type); + snprintf(metadata_type_str, sizeof(metadata_type_str), "%i", (uint8_t)= metadata_type); struct env_set *es =3D env_set_create(NULL); setenv_str(es, "script_type", "tls-crypt-v2-verify"); setenv_str(es, "metadata_type", metadata_type_str); @@ -611,15 +575,12 @@ } bool -tls_crypt_v2_extract_client_key(struct buffer *buf, - struct tls_wrap_ctx *ctx, - const struct tls_options *opt, - bool initial_packet) +tls_crypt_v2_extract_client_key(struct buffer *buf, struct tls_wrap_ctx *c= tx, + const struct tls_options *opt, bool initia= l_packet) { if (!ctx->tls_crypt_v2_server_key.cipher) { - msg(D_TLS_ERRORS, - "Client wants tls-crypt-v2, but no server key present."); + msg(D_TLS_ERRORS, "Client wants tls-crypt-v2, but no server key pr= esent."); return false; } @@ -633,8 +594,7 @@ msg(D_TLS_ERRORS, "Can not read tls-crypt-v2 client key length"); return false; } - memcpy(&net_len, BEND(&wrapped_client_key) - sizeof(net_len), - sizeof(net_len)); + memcpy(&net_len, BEND(&wrapped_client_key) - sizeof(net_len), sizeof(n= et_len)); uint16_t wkc_len =3D ntohs(net_len); if (!buf_advance(&wrapped_client_key, BLEN(&wrapped_client_key) - wkc_= len)) @@ -657,7 +617,7 @@ * basically transforming the CONTROL_WKC_V1 into a normal CONTROL= _V1 * packet*/ msg(D_TLS_ERRORS, "control channel security already setup ignoring= " - "wrapped key part of packet."); + "wrapped key part of packet."); /* Remove client key from buffer so tls-crypt code can unwrap mess= age */ ASSERT(buf_inc_len(buf, -(BLEN(&wrapped_client_key)))); @@ -665,10 +625,8 @@ } ctx->tls_crypt_v2_metadata =3D alloc_buf(TLS_CRYPT_V2_MAX_METADATA_LEN= ); - if (!tls_crypt_v2_unwrap_client_key(&ctx->original_wrap_keydata, - &ctx->tls_crypt_v2_metadata, - wrapped_client_key, - &ctx->tls_crypt_v2_server_key)) + if (!tls_crypt_v2_unwrap_client_key(&ctx->original_wrap_keydata, &ctx-= >tls_crypt_v2_metadata, + wrapped_client_key, &ctx->tls_cryp= t_v2_server_key)) { msg(D_TLS_ERRORS, "Can not unwrap tls-crypt-v2 client key"); secure_memzero(&ctx->original_wrap_keydata, sizeof(ctx->original_w= rap_keydata)); @@ -680,8 +638,7 @@ ctx->cleanup_key_ctx =3D true; ctx->opt.flags |=3D CO_PACKET_ID_LONG_FORM; memset(&ctx->opt.key_ctx_bi, 0, sizeof(ctx->opt.key_ctx_bi)); - tls_crypt_v2_load_client_key(&ctx->opt.key_ctx_bi, - &ctx->original_wrap_keydata, true); + tls_crypt_v2_load_client_key(&ctx->opt.key_ctx_bi, &ctx->original_wrap= _keydata, true); /* Remove client key from buffer so tls-crypt code can unwrap message = */ ASSERT(buf_inc_len(buf, -(BLEN(&wrapped_client_key)))); @@ -701,16 +658,13 @@ } void -tls_crypt_v2_write_client_key_file(const char *filename, - const char *b64_metadata, - const char *server_key_file, - bool server_key_inline) +tls_crypt_v2_write_client_key_file(const char *filename, const char *b64_m= etadata, + const char *server_key_file, bool serve= r_key_inline) { struct gc_arena gc =3D gc_new(); struct key_ctx server_key =3D { 0 }; struct buffer client_key_pem =3D { 0 }; - struct buffer dst =3D alloc_buf_gc(TLS_CRYPT_V2_CLIENT_KEY_LEN - + TLS_CRYPT_V2_MAX_WKC_LEN, &gc); + struct buffer dst =3D alloc_buf_gc(TLS_CRYPT_V2_CLIENT_KEY_LEN + TLS_C= RYPT_V2_MAX_WKC_LEN, &gc); struct key2 client_key =3D { .n =3D 2 }; if (!rand_bytes((void *)client_key.keys, sizeof(client_key.keys))) @@ -726,8 +680,7 @@ size_t b64_length =3D strlen(b64_metadata); metadata =3D alloc_buf_gc(OPENVPN_BASE64_DECODED_LENGTH(b64_length= ) + 1, &gc); ASSERT(buf_write(&metadata, &TLS_CRYPT_METADATA_TYPE_USER, 1)); - int decoded_len =3D openvpn_base64_decode(b64_metadata, BEND(&meta= data), - BCAP(&metadata)); + int decoded_len =3D openvpn_base64_decode(b64_metadata, BEND(&meta= data), BCAP(&metadata)); if (decoded_len < 0) { msg(M_FATAL, "ERROR: failed to base64 decode provided metadata= "); @@ -735,9 +688,8 @@ } if (decoded_len > TLS_CRYPT_V2_MAX_METADATA_LEN - 1) { - msg(M_FATAL, - "ERROR: metadata too long (%d bytes, max %u bytes)", - decoded_len, TLS_CRYPT_V2_MAX_METADATA_LEN - 1); + msg(M_FATAL, "ERROR: metadata too long (%d bytes, max %u bytes= )", decoded_len, + TLS_CRYPT_V2_MAX_METADATA_LEN - 1); goto cleanup; } ASSERT(buf_inc_len(&metadata, decoded_len)); @@ -750,18 +702,15 @@ ASSERT(buf_write(&metadata, ×tamp, sizeof(timestamp))); } - tls_crypt_v2_init_server_key(&server_key, true, server_key_file, - server_key_inline); - if (!tls_crypt_v2_wrap_client_key(&dst, &client_key, &metadata, &serve= r_key, - &gc)) + tls_crypt_v2_init_server_key(&server_key, true, server_key_file, serve= r_key_inline); + if (!tls_crypt_v2_wrap_client_key(&dst, &client_key, &metadata, &serve= r_key, &gc)) { msg(M_FATAL, "ERROR: could not wrap generated client key"); goto cleanup; } /* PEM-encode Kc || WKc */ - if (!crypto_pem_encode(tls_crypt_v2_cli_pem_name, &client_key_pem, &ds= t, - &gc)) + if (!crypto_pem_encode(tls_crypt_v2_cli_pem_name, &client_key_pem, &ds= t, &gc)) { msg(M_FATAL, "ERROR: could not PEM-encode client key"); goto cleanup; @@ -787,17 +736,15 @@ struct buffer test_wrapped_client_key; struct key2 keydata; msg(D_GENKEY, "Testing client-side key loading..."); - tls_crypt_v2_init_client_key(&test_client_key, &keydata, &test_wrapped= _client_key, - client_file, client_inline); + tls_crypt_v2_init_client_key(&test_client_key, &keydata, &test_wrapped= _client_key, client_file, + client_inline); free_key_ctx_bi(&test_client_key); /* Sanity check: unwrap and load client key (as "server") */ - struct buffer test_metadata =3D alloc_buf_gc(TLS_CRYPT_V2_MAX_METADATA= _LEN, - &gc); + struct buffer test_metadata =3D alloc_buf_gc(TLS_CRYPT_V2_MAX_METADATA= _LEN, &gc); struct key2 test_client_key2 =3D { 0 }; free_key_ctx(&server_key); - tls_crypt_v2_init_server_key(&server_key, false, server_key_file, - server_key_inline); + tls_crypt_v2_init_server_key(&server_key, false, server_key_file, serv= er_key_inline); msg(D_GENKEY, "Testing server-side key loading..."); ASSERT(tls_crypt_v2_unwrap_client_key(&test_client_key2, &test_metadat= a, test_wrapped_client_key, &server= _key)); diff --git a/src/openvpn/tls_crypt.h b/src/openvpn/tls_crypt.h index c8bd384..87aa8d2 100644 --- a/src/openvpn/tls_crypt.h +++ b/src/openvpn/tls_crypt.h @@ -85,21 +85,21 @@ #include "session_id.h" #include "ssl_common.h" -#define TLS_CRYPT_TAG_SIZE (256/8) -#define TLS_CRYPT_PID_SIZE (sizeof(packet_id_type) + sizeof(net_time_t)) -#define TLS_CRYPT_BLOCK_SIZE (128/8) +#define TLS_CRYPT_TAG_SIZE (256 / 8) +#define TLS_CRYPT_PID_SIZE (sizeof(packet_id_type) + sizeof(net_time_t)) +#define TLS_CRYPT_BLOCK_SIZE (128 / 8) #define TLS_CRYPT_OFF_PID (1 + SID_SIZE) #define TLS_CRYPT_OFF_TAG (TLS_CRYPT_OFF_PID + TLS_CRYPT_PID_SIZE) -#define TLS_CRYPT_OFF_CT (TLS_CRYPT_OFF_TAG + TLS_CRYPT_TAG_SIZE) +#define TLS_CRYPT_OFF_CT (TLS_CRYPT_OFF_TAG + TLS_CRYPT_TAG_SIZE) -#define TLS_CRYPT_V2_MAX_WKC_LEN (1024) +#define TLS_CRYPT_V2_MAX_WKC_LEN (1024) #define TLS_CRYPT_V2_CLIENT_KEY_LEN (2048 / 8) #define TLS_CRYPT_V2_SERVER_KEY_LEN (sizeof(struct key)) -#define TLS_CRYPT_V2_TAG_SIZE (TLS_CRYPT_TAG_SIZE) -#define TLS_CRYPT_V2_MAX_METADATA_LEN (unsigned)(TLS_CRYPT_V2_MAX_WKC_LEN \ - - (TLS_CRYPT_V2_CLIENT_KE= Y_LEN + TLS_CRYPT_V2_TAG_SIZE \ - + sizeof(uint16_t))) +#define TLS_CRYPT_V2_TAG_SIZE (TLS_CRYPT_TAG_SIZE) +#define TLS_CRYPT_V2_MAX_METADATA_LEN \ + (unsigned)(TLS_CRYPT_V2_MAX_WKC_LEN \ + - (TLS_CRYPT_V2_CLIENT_KEY_LEN + TLS_CRYPT_V2_TAG_SIZE + si= zeof(uint16_t))) /** * Initialize a key_ctx_bi structure for use with @c --tls-crypt. @@ -112,8 +112,8 @@ * otherwise. * @param tls_server Must be set to true is this is a TLS server instan= ce. */ -void tls_crypt_init_key(struct key_ctx_bi *key, struct key2 *keydata, - const char *key_file, bool key_inline, bool tls_se= rver); +void tls_crypt_init_key(struct key_ctx_bi *key, struct key2 *keydata, cons= t char *key_file, + bool key_inline, bool tls_server); /** * Generates a TLS-Crypt key to be used with dynamic tls-crypt using the @@ -124,8 +124,7 @@ * @param session session that will be used for the TLS EKM exporter * @return true iff generating the key was successful */ -bool -tls_session_generate_dynamic_tls_crypt_key(struct tls_session *session); +bool tls_session_generate_dynamic_tls_crypt_key(struct tls_session *sessio= n); /** * Returns the maximum overhead (in bytes) added to the destination buffer= by @@ -144,8 +143,7 @@ * * @returns true iff wrapping succeeded. */ -bool tls_crypt_wrap(const struct buffer *src, struct buffer *dst, - struct crypto_options *opt); +bool tls_crypt_wrap(const struct buffer *src, struct buffer *dst, struct c= rypto_options *opt); =20 /** * Unwrap a control channel packet (decrypts, authenticates and performs @@ -158,8 +156,7 @@ * @returns true iff unwrapping succeeded (data authenticated correctly an= d was * no replay). */ -bool tls_crypt_unwrap(const struct buffer *src, struct buffer *dst, - struct crypto_options *opt); +bool tls_crypt_unwrap(const struct buffer *src, struct buffer *dst, struct= crypto_options *opt); /** * Initialize a tls-crypt-v2 server key (used to encrypt/decrypt client ke= ys). @@ -173,8 +170,8 @@ * otherwise. * */ -void tls_crypt_v2_init_server_key(struct key_ctx *key_ctx, bool encrypt, - const char *key_file, bool key_inline); +void tls_crypt_v2_init_server_key(struct key_ctx *key_ctx, bool encrypt, c= onst char *key_file, + bool key_inline); /** * Initialize a tls-crypt-v2 client key. @@ -191,10 +188,9 @@ * @param key_inline True if key_file contains an inline key, False * otherwise. */ -void tls_crypt_v2_init_client_key(struct key_ctx_bi *key, - struct key2 *original_key, - struct buffer *wrapped_key_buf, - const char *key_file, bool key_inline); +void tls_crypt_v2_init_client_key(struct key_ctx_bi *key, struct key2 *ori= ginal_key, + struct buffer *wrapped_key_buf, const ch= ar *key_file, + bool key_inline); /** * Extract a tls-crypt-v2 client key from a P_CONTROL_HARD_RESET_CLIENT_V3 @@ -211,10 +207,8 @@ * * @returns true if a key was successfully extracted. */ -bool tls_crypt_v2_extract_client_key(struct buffer *buf, - struct tls_wrap_ctx *ctx, - const struct tls_options *opt, - bool initial_packet); +bool tls_crypt_v2_extract_client_key(struct buffer *buf, struct tls_wrap_c= tx *ctx, + const struct tls_options *opt, bool i= nitial_packet); /** * Generate a tls-crypt-v2 server key, and write to file. @@ -233,8 +227,7 @@ * @param key_inline True if key_file contains an inline key, False * otherwise. */ -void tls_crypt_v2_write_client_key_file(const char *filename, - const char *b64_metadata, +void tls_crypt_v2_write_client_key_file(const char *filename, const char *= b64_metadata, const char *key_file, bool key_inl= ine); /** @} */ diff --git a/src/openvpn/tun.c b/src/openvpn/tun.c index a96a305..f54b608 100644 --- a/src/openvpn/tun.c +++ b/src/openvpn/tun.c @@ -84,27 +84,25 @@ #ifdef _WIN32 -const static GUID GUID_DEVCLASS_NET =3D { 0x4d36e972L, 0xe325, 0x11ce, { 0= xbf, 0xc1, 0x08, 0x00, 0x2b, 0xe1, 0x03, 0x18 } }; -const static GUID GUID_DEVINTERFACE_NET =3D { 0xcac88484, 0x7515, 0x4c03, = { 0x82, 0xe6, 0x71, 0xa8, 0x7a, 0xba, 0xc3, 0x61 } }; +const static GUID GUID_DEVCLASS_NET =3D { + 0x4d36e972L, 0xe325, 0x11ce, { 0xbf, 0xc1, 0x08, 0x00, 0x2b, 0xe1, 0x0= 3, 0x18 } +}; +const static GUID GUID_DEVINTERFACE_NET =3D { + 0xcac88484, 0x7515, 0x4c03, { 0x82, 0xe6, 0x71, 0xa8, 0x7a, 0xba, 0xc3= , 0x61 } +}; -/* #define SIMULATE_DHCP_FAILED */ /* simulate bad DHCP negotiation = */ +/* #define SIMULATE_DHCP_FAILED */ /* simulate bad DHCP negotiation */ -#define NI_TEST_FIRST (1<<0) -#define NI_IP_NETMASK (1<<1) -#define NI_OPTIONS (1<<2) +#define NI_TEST_FIRST (1 << 0) +#define NI_IP_NETMASK (1 << 1) +#define NI_OPTIONS (1 << 2) -static void netsh_ifconfig(const struct tuntap_options *to, - DWORD adapter_index, - const in_addr_t ip, - const in_addr_t netmask, - const unsigned int flags); +static void netsh_ifconfig(const struct tuntap_options *to, DWORD adapter_= index, const in_addr_t ip, + const in_addr_t netmask, const unsigned int fla= gs); -static void windows_set_mtu(const int iface_index, - const short family, - const int mtu); +static void windows_set_mtu(const int iface_index, const short family, con= st int mtu); -static void netsh_set_dns6_servers(const struct in6_addr *addr_list, - const int addr_len, +static void netsh_set_dns6_servers(const struct in6_addr *addr_list, const= int addr_len, DWORD adapter_index); static void netsh_command(const struct argv *a, int n, int msglevel); @@ -121,15 +119,10 @@ struct gc_arena gc =3D gc_new(); HANDLE pipe =3D tt->options.msg_channel; - address_message_t addr =3D { - .header =3D { - (add ? msg_add_address : msg_del_address), - sizeof(address_message_t), - 0 - }, - .family =3D family, - .iface =3D { .index =3D tt->adapter_index, .name =3D "" } - }; + address_message_t addr =3D { .header =3D { (add ? msg_add_address : ms= g_del_address), + sizeof(address_message_t), 0 }, + .family =3D family, + .iface =3D { .index =3D tt->adapter_index, = .name =3D "" } }; if (addr.iface.index =3D=3D TUN_ADAPTER_INDEX_INVALID) { @@ -141,16 +134,14 @@ { addr.address.ipv4.s_addr =3D htonl(tt->local); addr.prefix_len =3D netmask_to_netbits2(tt->adapter_netmask); - msg(D_IFCONFIG, "INET address service: %s %s/%d", - add ? "add" : "remove", + msg(D_IFCONFIG, "INET address service: %s %s/%d", add ? "add" : "r= emove", print_in_addr_t(tt->local, 0, &gc), addr.prefix_len); } else { addr.address.ipv6 =3D tt->local_ipv6; addr.prefix_len =3D (tt->type =3D=3D DEV_TYPE_TUN) ? 128 : tt->net= bits_ipv6; - msg(D_IFCONFIG, "INET6 address service: %s %s/%d", - add ? "add" : "remove", + msg(D_IFCONFIG, "INET6 address service: %s %s/%d", add ? "add" : "= remove", print_in6_addr(tt->local_ipv6, 0, &gc), addr.prefix_len); } @@ -162,8 +153,8 @@ if (ack.error_number !=3D NO_ERROR) { msg(M_WARN, "TUN: %s address failed using service: %s [status=3D%u= if_index=3D%d]", - (add ? "adding" : "deleting"), strerror_win32(ack.error_number= , &gc), - ack.error_number, addr.iface.index); + (add ? "adding" : "deleting"), strerror_win32(ack.error_number= , &gc), ack.error_number, + addr.iface.index); goto out; } @@ -189,15 +180,11 @@ /* Use dns_cfg_msg with addr_len =3D 0 for setting only the DOMAIN */ dns_cfg_message_t dns =3D { - .header =3D { - (add ? msg_add_dns_cfg : msg_del_dns_cfg), - sizeof(dns_cfg_message_t), - 0 - }, + .header =3D { (add ? msg_add_dns_cfg : msg_del_dns_cfg), sizeof(dn= s_cfg_message_t), 0 }, .iface =3D { .index =3D tt->adapter_index, .name =3D "" }, - .domains =3D "", /* set below */ - .family =3D AF_INET, /* unused */ - .addr_len =3D 0 /* add/delete only the domain, not DNS serve= rs */ + .domains =3D "", /* set below */ + .family =3D AF_INET, /* unused */ + .addr_len =3D 0 /* add/delete only the domain, not DNS server= s */ }; /* interface name is required */ @@ -237,8 +224,8 @@ if (ack.error_number !=3D NO_ERROR) { msg(M_WARN, "TUN: %s DNS domains failed using service: %s [status= =3D%u if_name=3D%s]", - (add ? "adding" : "deleting"), strerror_win32(ack.error_number= , &gc), - ack.error_number, dns.iface.name); + (add ? "adding" : "deleting"), strerror_win32(ack.error_number= , &gc), ack.error_number, + dns.iface.name); goto out; } @@ -265,17 +252,12 @@ } /* Use dns_cfg_msg with domain =3D "" for setting only the DNS servers= */ - dns_cfg_message_t dns =3D { - .header =3D { - (add ? msg_add_dns_cfg : msg_del_dns_cfg), - sizeof(dns_cfg_message_t), - 0 - }, - .iface =3D { .index =3D tt->adapter_index, .name =3D "" }, - .domains =3D "", - .family =3D family, - .addr_len =3D addr_len - }; + dns_cfg_message_t dns =3D { .header =3D { (add ? msg_add_dns_cfg : msg= _del_dns_cfg), + sizeof(dns_cfg_message_t), 0 }, + .iface =3D { .index =3D tt->adapter_index, .= name =3D "" }, + .domains =3D "", + .family =3D family, + .addr_len =3D addr_len }; /* interface name is required */ strncpy(dns.iface.name, tt->actual_name, sizeof(dns.iface.name)); @@ -285,8 +267,8 @@ { addr_len =3D _countof(dns.addr); dns.addr_len =3D addr_len; - msg(M_WARN, "Number of %s DNS addresses sent to service truncated = to %d", - ip_proto_name, addr_len); + msg(M_WARN, "Number of %s DNS addresses sent to service truncated = to %d", ip_proto_name, + addr_len); } for (int i =3D 0; i < addr_len; ++i) @@ -337,15 +319,10 @@ goto out; } - wins_cfg_message_t wins =3D { - .header =3D { - (add ? msg_add_wins_cfg : msg_del_wins_cfg), - sizeof(wins_cfg_message_t), - 0 - }, - .iface =3D {.index =3D tt->adapter_index, .name =3D "" }, - .addr_len =3D addr_len - }; + wins_cfg_message_t wins =3D { .header =3D { (add ? msg_add_wins_cfg : = msg_del_wins_cfg), + sizeof(wins_cfg_message_t), 0 = }, + .iface =3D { .index =3D tt->adapter_index,= .name =3D "" }, + .addr_len =3D addr_len }; /* interface name is required */ strncpy(wins.iface.name, tt->actual_name, sizeof(wins.iface.name)); @@ -355,8 +332,7 @@ { addr_len =3D _countof(wins.addr); wins.addr_len =3D addr_len; - msg(M_WARN, "Number of WINS addresses sent to service truncated to= %d", - addr_len); + msg(M_WARN, "Number of WINS addresses sent to service truncated to= %d", addr_len); } for (int i =3D 0; i < addr_len; ++i) @@ -375,8 +351,8 @@ if (ack.error_number !=3D NO_ERROR) { msg(M_WARN, "TUN: %s WINS failed using service: %s [status=3D%u if= _name=3D%s]", - (add ? "adding" : "deleting"), strerror_win32(ack.error_number= , &gc), - ack.error_number, wins.iface.name); + (add ? "adding" : "deleting"), strerror_win32(ack.error_number= , &gc), ack.error_number, + wins.iface.name); goto out; } @@ -394,20 +370,15 @@ struct gc_arena gc =3D gc_new(); HANDLE pipe =3D tt->options.msg_channel; const char *family_name =3D (family =3D=3D AF_INET6) ? "IPv6" : "IPv4"; - set_mtu_message_t mtu_msg =3D { - .header =3D { - msg_set_mtu, - sizeof(set_mtu_message_t), - 0 - }, - .iface =3D {.index =3D tt->adapter_index}, - .mtu =3D mtu, - .family =3D family - }; + set_mtu_message_t mtu_msg =3D { .header =3D { msg_set_mtu, sizeof(set_= mtu_message_t), 0 }, + .iface =3D { .index =3D tt->adapter_inde= x }, + .mtu =3D mtu, + .family =3D family }; strncpynt(mtu_msg.iface.name, tt->actual_name, sizeof(mtu_msg.iface.na= me)); if (family =3D=3D AF_INET6 && mtu < 1280) { - msg(M_INFO, "NOTE: IPv6 interface MTU < 1280 conflicts with IETF s= tandards and might not work"); + msg(M_INFO, + "NOTE: IPv6 interface MTU < 1280 conflicts with IETF standards= and might not work"); } if (!send_msg_iservice(pipe, &mtu_msg, sizeof(mtu_msg), &ack, "Set_mtu= ")) @@ -418,11 +389,13 @@ if (ack.error_number !=3D NO_ERROR) { msg(M_NONFATAL, "TUN: setting %s mtu using service failed: %s [sta= tus=3D%u if_index=3D%d]", - family_name, strerror_win32(ack.error_number, &gc), ack.error_= number, mtu_msg.iface.index); + family_name, strerror_win32(ack.error_number, &gc), ack.error_= number, + mtu_msg.iface.index); } else { - msg(M_INFO, "%s MTU set to %d on interface %d using service", fami= ly_name, mtu, mtu_msg.iface.index); + msg(M_INFO, "%s MTU set to %d on interface %d using service", fami= ly_name, mtu, + mtu_msg.iface.index); ret =3D true; } @@ -441,7 +414,8 @@ struct argv argv =3D argv_new(); argv_printf(&argv, "%s%s nicconfig where (InterfaceIndex=3D%ld) call S= etDNSDomain '%s'", - get_win_sys_path(), WMIC_PATH_SUFFIX, tt->adapter_index, a= dd ? tt->options.domain : ""); + get_win_sys_path(), WMIC_PATH_SUFFIX, tt->adapter_index, + add ? tt->options.domain : ""); exec_command("WMIC", &argv, 1, M_WARN); argv_free(&argv); @@ -479,12 +453,7 @@ } create_adapter_message_t msg =3D { - .header =3D { - msg_create_adapter, - sizeof(create_adapter_message_t), - 0 - }, - .adapter_type =3D t + .header =3D { msg_create_adapter, sizeof(create_adapter_message_t)= , 0 }, .adapter_type =3D t }; if (!send_msg_iservice(msg_channel, &msg, sizeof(msg), &ack, "create_a= dapter")) @@ -495,7 +464,8 @@ if (ack.error_number !=3D NO_ERROR) { msg(M_NONFATAL, "TUN: creating %s adapter using service failed: %s= [status=3D%u]", - print_tun_backend_driver(driver_type), strerror_win32(ack.erro= r_number, &gc), ack.error_number); + print_tun_backend_driver(driver_type), strerror_win32(ack.erro= r_number, &gc), + ack.error_number); } else { @@ -511,7 +481,8 @@ #endif /* ifdef _WIN32 */ #ifdef TARGET_SOLARIS -static void solaris_error_close(struct tuntap *tt, const struct env_set *e= s, const char *actual, bool unplumb_inet6); +static void solaris_error_close(struct tuntap *tt, const struct env_set *e= s, const char *actual, + bool unplumb_inet6); #include #endif @@ -582,10 +553,7 @@ * before the device is actually opened. */ const char * -guess_tuntap_dev(const char *dev, - const char *dev_type, - const char *dev_node, - struct gc_arena *gc) +guess_tuntap_dev(const char *dev, const char *dev_type, const char *dev_no= de, struct gc_arena *gc) { #ifdef _WIN32 const int dt =3D dev_type_enum(dev, dev_type); @@ -619,16 +587,17 @@ { if (looks_like_netmask) { - msg(M_WARN, "WARNING: Since you are using --dev tun with a poi= nt-to-point topology, the second argument to --ifconfig must be an IP addre= ss. You are using something (%s) that looks more like a netmask. %s", - print_in_addr_t(addr, 0, &gc), - ifconfig_warn_how_to_silence); + msg(M_WARN, + "WARNING: Since you are using --dev tun with a point-to-po= int topology, the second argument to --ifconfig must be an IP address. You= are using something (%s) that looks more like a netmask. %s", + print_in_addr_t(addr, 0, &gc), ifconfig_warn_how_to_silenc= e); } } else { if (!looks_like_netmask) { - msg(M_WARN, "WARNING: Since you are using subnet topology, the= second argument to --ifconfig must be a netmask, for example something lik= e 255.255.255.0. %s", + msg(M_WARN, + "WARNING: Since you are using subnet topology, the second = argument to --ifconfig must be a netmask, for example something like 255.25= 5.255.0. %s", ifconfig_warn_how_to_silence); } } @@ -640,10 +609,7 @@ * clash with ifconfig addresses or subnet. */ static void -check_addr_clash(const char *name, - int type, - in_addr_t public, - in_addr_t local, +check_addr_clash(const char *name, int type, in_addr_t public, in_addr_t l= ocal, in_addr_t remote_netmask) { struct gc_arena gc =3D gc_new(); @@ -660,7 +626,7 @@ if (type =3D=3D DEV_TYPE_TUN) { const in_addr_t test_netmask =3D 0xFFFFFF00; - const in_addr_t public_net =3D public &test_netmask; + const in_addr_t public_net =3D public & test_netmask; const in_addr_t local_net =3D local & test_netmask; const in_addr_t remote_net =3D remote_netmask & test_netmask; @@ -668,37 +634,28 @@ { msg(M_WARN, "WARNING: --%s address [%s] conflicts with --ifconfig = address pair [%s, %s]. %s", - name, - print_in_addr_t(public, 0, &gc), - print_in_addr_t(local, 0, &gc), - print_in_addr_t(remote_netmask, 0, &gc), - ifconfig_warn_how_to_silence); + name, print_in_addr_t(public, 0, &gc), print_in_addr_t= (local, 0, &gc), + print_in_addr_t(remote_netmask, 0, &gc), ifconfig_warn= _how_to_silence); } if (public_net =3D=3D local_net || public_net =3D=3D remote_ne= t) { msg(M_WARN, "WARNING: potential conflict between --%s address [%s]= and --ifconfig address pair [%s, %s] -- this is a warning only that is tri= ggered when local/remote addresses exist within the same /24 subnet as --if= config endpoints. %s", - name, - print_in_addr_t(public, 0, &gc), - print_in_addr_t(local, 0, &gc), - print_in_addr_t(remote_netmask, 0, &gc), - ifconfig_warn_how_to_silence); + name, print_in_addr_t(public, 0, &gc), print_in_addr_t= (local, 0, &gc), + print_in_addr_t(remote_netmask, 0, &gc), ifconfig_warn= _how_to_silence); } } else if (type =3D=3D DEV_TYPE_TAP) { - const in_addr_t public_network =3D public &remote_netmask; + const in_addr_t public_network =3D public & remote_netmask; const in_addr_t virtual_network =3D local & remote_netmask; if (public_network =3D=3D virtual_network) { msg(M_WARN, "WARNING: --%s address [%s] conflicts with --ifconfig = subnet [%s, %s] -- local and remote addresses cannot be inside of the --ifc= onfig subnet. %s", - name, - print_in_addr_t(public, 0, &gc), - print_in_addr_t(local, 0, &gc), - print_in_addr_t(remote_netmask, 0, &gc), - ifconfig_warn_how_to_silence); + name, print_in_addr_t(public, 0, &gc), print_in_addr_t= (local, 0, &gc), + print_in_addr_t(remote_netmask, 0, &gc), ifconfig_warn= _how_to_silence); } } } @@ -710,7 +667,7 @@ { struct gc_arena gc =3D gc_new(); struct route_gateway_info rgi; - const unsigned int needed =3D (RGI_ADDR_DEFINED|RGI_NETMASK_DEFINED); + const unsigned int needed =3D (RGI_ADDR_DEFINED | RGI_NETMASK_DEFINED); get_default_gateway(&rgi, 0, ctx); if ((rgi.flags & needed) =3D=3D needed) @@ -718,7 +675,8 @@ const in_addr_t lan_network =3D rgi.gateway.addr & rgi.gateway.net= mask; if (lan_network =3D=3D 0xC0A80000 || lan_network =3D=3D 0xC0A80100) { - msg(M_WARN, "NOTE: your local LAN uses the extremely common su= bnet address 192.168.0.x or 192.168.1.x. Be aware that this might create r= outing conflicts if you connect to the VPN server from public locations suc= h as internet cafes that use the same subnet."); + msg(M_WARN, + "NOTE: your local LAN uses the extremely common subnet add= ress 192.168.0.x or 192.168.1.x. Be aware that this might create routing c= onflicts if you connect to the VPN server from public locations such as int= ernet cafes that use the same subnet."); } } gc_free(&gc); @@ -736,8 +694,7 @@ { if (!is_tun_p2p(tt)) { - buf_printf(&out, "%s %s", - print_in_addr_t(tt->local & tt->remote_netmask, 0, = gc), + buf_printf(&out, "%s %s", print_in_addr_t(tt->local & tt->remo= te_netmask, 0, gc), print_in_addr_t(tt->remote_netmask, 0, gc)); } else if (tt->type =3D=3D DEV_TYPE_TUN) /* tun p2p topology */ @@ -774,20 +731,16 @@ { if (rwflags & EVENT_READ) { - buf_printf(&out, "T%s", - (tt->rwflags_debug & EVENT_READ) ? "R" : "r"); + buf_printf(&out, "T%s", (tt->rwflags_debug & EVENT_READ) ? "R"= : "r"); #ifdef _WIN32 - buf_printf(&out, "%s", - overlapped_io_state_ascii(&tt->reads)); + buf_printf(&out, "%s", overlapped_io_state_ascii(&tt->reads)); #endif } if (rwflags & EVENT_WRITE) { - buf_printf(&out, "T%s", - (tt->rwflags_debug & EVENT_WRITE) ? "W" : "w"); + buf_printf(&out, "T%s", (tt->rwflags_debug & EVENT_WRITE) ? "W= " : "w"); #ifdef _WIN32 - buf_printf(&out, "%s", - overlapped_io_state_ascii(&tt->writes)); + buf_printf(&out, "%s", overlapped_io_state_ascii(&tt->writes)); #endif } } @@ -806,8 +759,7 @@ { bool tun_p2p =3D false; - if (tt->type =3D=3D DEV_TYPE_TAP - || (tt->type =3D=3D DEV_TYPE_TUN && tt->topology =3D=3D TOP_SUBNET= )) + if (tt->type =3D=3D DEV_TYPE_TAP || (tt->type =3D=3D DEV_TYPE_TUN && t= t->topology =3D=3D TOP_SUBNET)) { tun_p2p =3D false; } @@ -817,7 +769,8 @@ } else { - msg(M_FATAL, "Error: problem with tun vs. tap setting"); /* JYFIXM= E -- needs to be caught earlier, in init_tun? */ + msg(M_FATAL, "Error: problem with tun vs. tap setting"); /* JYFIXM= E -- needs to be caught + earlie= r, in init_tun? */ } return tun_p2p; } @@ -870,20 +823,16 @@ * but don't execute yet. */ struct tuntap * -init_tun(const char *dev, /* --dev option */ - const char *dev_type, /* --dev-type option */ - int topology, /* one of the TOP_x values */ - const char *ifconfig_local_parm, /* --ifconfig parm 1 */ - const char *ifconfig_remote_netmask_parm, /* --ifconfig parm 2 */ - const char *ifconfig_ipv6_local_parm, /* --ifconfig parm 1 I= Pv6 */ +init_tun(const char *dev, /* --dev option */ + const char *dev_type, /* --dev-type option */ + int topology, /* one of the TOP_x val= ues */ + const char *ifconfig_local_parm, /* --ifconfig parm 1 */ + const char *ifconfig_remote_netmask_parm, /* --ifconfig parm 2 */ + const char *ifconfig_ipv6_local_parm, /* --ifconfig parm 1 IP= v6 */ int ifconfig_ipv6_netbits_parm, - const char *ifconfig_ipv6_remote_parm, /* --ifconfig parm 2 I= Pv6 */ - struct addrinfo *local_public, - struct addrinfo *remote_public, - const bool strict_warn, - struct env_set *es, - openvpn_net_ctx_t *ctx, - struct tuntap *tt) + const char *ifconfig_ipv6_remote_parm, /* --ifconfig parm 2 IP= v6 */ + struct addrinfo *local_public, struct addrinfo *remote_public, co= nst bool strict_warn, + struct env_set *es, openvpn_net_ctx_t *ctx, struct tuntap *tt) { if (!tt) { @@ -905,25 +854,13 @@ * Convert arguments to binary IPv4 addresses. */ - tt->local =3D getaddr( - GETADDR_RESOLVE - | GETADDR_HOST_ORDER - | GETADDR_FATAL_ON_SIGNAL - | GETADDR_FATAL, - ifconfig_local_parm, - 0, - NULL, - NULL); + tt->local =3D + getaddr(GETADDR_RESOLVE | GETADDR_HOST_ORDER | GETADDR_FATAL_O= N_SIGNAL | GETADDR_FATAL, + ifconfig_local_parm, 0, NULL, NULL); - tt->remote_netmask =3D getaddr( - (tun_p2p ? GETADDR_RESOLVE : 0) - | GETADDR_HOST_ORDER - | GETADDR_FATAL_ON_SIGNAL - | GETADDR_FATAL, - ifconfig_remote_netmask_parm, - 0, - NULL, - NULL); + tt->remote_netmask =3D getaddr((tun_p2p ? GETADDR_RESOLVE : 0) | G= ETADDR_HOST_ORDER + | GETADDR_FATAL_ON_SIGNAL | GETAD= DR_FATAL, + ifconfig_remote_netmask_parm, 0, NULL= , NULL); /* * Look for common errors in --ifconfig parms @@ -942,12 +879,9 @@ { if (curele->ai_family =3D=3D AF_INET) { - const in_addr_t local =3D ntohl(((struct sockaddr_in *= )curele->ai_addr)->sin_addr.s_addr); - check_addr_clash("local", - tt->type, - local, - tt->local, - tt->remote_netmask); + const in_addr_t local =3D + ntohl(((struct sockaddr_in *)curele->ai_addr)->sin= _addr.s_addr); + check_addr_clash("local", tt->type, local, tt->local, = tt->remote_netmask); } } @@ -955,12 +889,9 @@ { if (curele->ai_family =3D=3D AF_INET) { - const in_addr_t remote =3D ntohl(((struct sockaddr_in = *)curele->ai_addr)->sin_addr.s_addr); - check_addr_clash("remote", - tt->type, - remote, - tt->local, - tt->remote_netmask); + const in_addr_t remote =3D + ntohl(((struct sockaddr_in *)curele->ai_addr)->sin= _addr.s_addr); + check_addr_clash("remote", tt->type, remote, tt->local= , tt->remote_netmask); } } } @@ -986,15 +917,15 @@ if (ifconfig_ipv6_local_parm && ifconfig_ipv6_remote_parm) { - /* * Convert arguments to binary IPv6 addresses. */ - if (inet_pton( AF_INET6, ifconfig_ipv6_local_parm, &tt->local_ipv6= ) !=3D 1 - || inet_pton( AF_INET6, ifconfig_ipv6_remote_parm, &tt->remote= _ipv6 ) !=3D 1) + if (inet_pton(AF_INET6, ifconfig_ipv6_local_parm, &tt->local_ipv6)= !=3D 1 + || inet_pton(AF_INET6, ifconfig_ipv6_remote_parm, &tt->remote_= ipv6) !=3D 1) { - msg( M_FATAL, "init_tun: problem converting IPv6 ifconfig addr= esses %s and %s to binary", ifconfig_ipv6_local_parm, ifconfig_ipv6_remote_= parm ); + msg(M_FATAL, "init_tun: problem converting IPv6 ifconfig addre= sses %s and %s to binary", + ifconfig_ipv6_local_parm, ifconfig_ipv6_remote_parm); } tt->netbits_ipv6 =3D ifconfig_ipv6_netbits_parm; @@ -1016,9 +947,7 @@ * Platform specific tun initializations */ void -init_tun_post(struct tuntap *tt, - const struct frame *frame, - const struct tuntap_options *options) +init_tun_post(struct tuntap *tt, const struct frame *frame, const struct t= untap_options *options) { tt->options =3D *options; #ifdef _WIN32 @@ -1045,8 +974,7 @@ * -> helper function to simplify code below */ static void -add_route_connected_v6_net(struct tuntap *tt, - const struct env_set *es) +add_route_connected_v6_net(struct tuntap *tt, const struct env_set *es) { struct route_ipv6 r6; @@ -1054,8 +982,8 @@ r6.network =3D tt->local_ipv6; r6.netbits =3D tt->netbits_ipv6; r6.gateway =3D tt->local_ipv6; - r6.metric =3D 0; /* connected route */ - r6.flags =3D RT_DEFINED | RT_METRIC_DEFINED; + r6.metric =3D 0; /* connected route */ + r6.flags =3D RT_DEFINED | RT_METRIC_DEFINED; add_route_ipv6(&r6, tt, 0, es, NULL); } @@ -1068,15 +996,16 @@ r6.network =3D tt->local_ipv6; r6.netbits =3D tt->netbits_ipv6; r6.gateway =3D tt->local_ipv6; - r6.metric =3D 0; /* connected route */ - r6.flags =3D RT_DEFINED | RT_ADDED | RT_METRIC_DEFINED; + r6.metric =3D 0; /* connected route */ + r6.flags =3D RT_DEFINED | RT_ADDED | RT_METRIC_DEFINED; route_ipv6_clear_host_bits(&r6); delete_route_ipv6(&r6, tt, NULL, NULL); } -#endif /* if defined(_WIN32) || defined(TARGET_DARWIN) || defined(TARGET_N= ETBSD) || defined(TARGET_OPENBSD) */ +#endif /* if defined(_WIN32) || defined(TARGET_DARWIN) || defined(TARGET_N= ETBSD) || \ + defined(TARGET_OPENBSD) */ -#if defined(TARGET_FREEBSD) || defined(TARGET_DRAGONFLY) \ - || defined(TARGET_NETBSD) || defined(TARGET_OPENBSD) +#if defined(TARGET_FREEBSD) || defined(TARGET_DRAGONFLY) || defined(TARGET= _NETBSD) \ + || defined(TARGET_OPENBSD) /* we can't use true subnet mode on tun on all platforms, as that * conflicts with IPv6 (wants to use ND then, which we don't do), * but the OSes want "a remote address that is different from ours" @@ -1087,11 +1016,11 @@ */ in_addr_t -create_arbitrary_remote( struct tuntap *tt ) +create_arbitrary_remote(struct tuntap *tt) { in_addr_t remote; - remote =3D (tt->local & tt->remote_netmask) +1; + remote =3D (tt->local & tt->remote_netmask) + 1; if (remote =3D=3D tt->local) { @@ -1112,8 +1041,8 @@ * @param ctx the networking API opaque context */ static void -do_ifconfig_ipv6(struct tuntap *tt, const char *ifname, int tun_mtu, - const struct env_set *es, openvpn_net_ctx_t *ctx) +do_ifconfig_ipv6(struct tuntap *tt, const char *ifname, int tun_mtu, const= struct env_set *es, + openvpn_net_ctx_t *ctx) { #if !defined(TARGET_LINUX) struct argv argv =3D argv_new(); @@ -1132,16 +1061,14 @@ msg(M_FATAL, "Linux can't bring %s up", ifname); } - if (net_addr_v6_add(ctx, ifname, &tt->local_ipv6, - tt->netbits_ipv6) < 0) + if (net_addr_v6_add(ctx, ifname, &tt->local_ipv6, tt->netbits_ipv6) < = 0) { msg(M_FATAL, "Linux can't add IPv6 to interface %s", ifname); } #elif defined(TARGET_ANDROID) char out6[64]; - snprintf(out6, sizeof(out6), "%s/%d %d", - ifconfig_ipv6_local, tt->netbits_ipv6, tun_mtu); + snprintf(out6, sizeof(out6), "%s/%d %d", ifconfig_ipv6_local, tt->netb= its_ipv6, tun_mtu); management_android_control(management, "IFCONFIG6", out6); #elif defined(TARGET_SOLARIS) argv_printf(&argv, "%s %s inet6 unplumb", IFCONFIG_PATH, ifname); @@ -1152,9 +1079,8 @@ { const char *ifconfig_ipv6_remote =3D print_in6_addr(tt->remote_ipv= 6, 0, &gc); - argv_printf(&argv, "%s %s inet6 plumb %s/%d %s mtu %d up", - IFCONFIG_PATH, ifname, ifconfig_ipv6_local, - tt->netbits_ipv6, ifconfig_ipv6_remote, tun_mtu); + argv_printf(&argv, "%s %s inet6 plumb %s/%d %s mtu %d up", IFCONFI= G_PATH, ifname, + ifconfig_ipv6_local, tt->netbits_ipv6, ifconfig_ipv6_r= emote, tun_mtu); } else /* tap mode */ { @@ -1162,8 +1088,7 @@ argv_printf(&argv, "%s %s inet6 plumb up", IFCONFIG_PATH, ifname); argv_msg(M_INFO, &argv); - if (!openvpn_execve_check(&argv, es, 0, - "Solaris ifconfig IPv6 (prepare) failed"= )) + if (!openvpn_execve_check(&argv, es, 0, "Solaris ifconfig IPv6 (pr= epare) failed")) { solaris_error_close(tt, es, ifname, true); } @@ -1177,8 +1102,8 @@ /* static IPv6 addresses need to go to a subinterface (tap0:1) * and we cannot set an mtu here (must go to the "parent") */ - argv_printf(&argv, "%s %s inet6 addif %s/%d up", IFCONFIG_PATH, - ifname, ifconfig_ipv6_local, tt->netbits_ipv6 ); + argv_printf(&argv, "%s %s inet6 addif %s/%d up", IFCONFIG_PATH, if= name, ifconfig_ipv6_local, + tt->netbits_ipv6); } argv_msg(M_INFO, &argv); @@ -1189,23 +1114,19 @@ if (tt->type !=3D DEV_TYPE_TUN) { - argv_printf(&argv, "%s %s inet6 mtu %d", IFCONFIG_PATH, - ifname, tun_mtu); + argv_printf(&argv, "%s %s inet6 mtu %d", IFCONFIG_PATH, ifname, tu= n_mtu); argv_msg(M_INFO, &argv); openvpn_execve_check(&argv, es, 0, "Solaris ifconfig IPv6 mtu fail= ed"); } -#elif defined(TARGET_OPENBSD) || defined(TARGET_NETBSD) \ - || defined(TARGET_DARWIN) || defined(TARGET_FREEBSD) \ - || defined(TARGET_DRAGONFLY) - argv_printf(&argv, "%s %s inet6 %s/%d mtu %d up", IFCONFIG_PATH, ifnam= e, - ifconfig_ipv6_local, tt->netbits_ipv6, tun_mtu); +#elif defined(TARGET_OPENBSD) || defined(TARGET_NETBSD) || defined(TARGET_= DARWIN) \ + || defined(TARGET_FREEBSD) || defined(TARGET_DRAGONFLY) + argv_printf(&argv, "%s %s inet6 %s/%d mtu %d up", IFCONFIG_PATH, ifnam= e, ifconfig_ipv6_local, + tt->netbits_ipv6, tun_mtu); argv_msg(M_INFO, &argv); - openvpn_execve_check(&argv, es, S_FATAL, - "generic BSD ifconfig inet6 failed"); + openvpn_execve_check(&argv, es, S_FATAL, "generic BSD ifconfig inet6 f= ailed"); -#if defined(TARGET_FREEBSD) && __FreeBSD_version >=3D 1200000 \ - && __FreeBSD_version < 1300000 +#if defined(TARGET_FREEBSD) && __FreeBSD_version >=3D 1200000 && __FreeBSD= _version < 1300000 /* On FreeBSD 12.0-12.4, there is ipv6_activate_all_interfaces=3D"YES" * in rc.conf, which is not set by default. If it is *not* set, * "all new interfaces that are not already up" are configured by @@ -1224,27 +1145,26 @@ argv_printf(&argv, "%s %s inet6 -ifdisabled", IFCONFIG_PATH, ifname); argv_msg(M_INFO, &argv); - openvpn_execve_check(&argv, es, S_FATAL, - "FreeBSD BSD 'ifconfig inet6 -ifdisabled' failed"= ); + openvpn_execve_check(&argv, es, S_FATAL, "FreeBSD BSD 'ifconfig inet6 = -ifdisabled' failed"); #endif #elif defined(TARGET_AIX) - argv_printf(&argv, "%s %s inet6 %s/%d mtu %d up", IFCONFIG_PATH, ifnam= e, - ifconfig_ipv6_local, tt->netbits_ipv6, tun_mtu); + argv_printf(&argv, "%s %s inet6 %s/%d mtu %d up", IFCONFIG_PATH, ifnam= e, ifconfig_ipv6_local, + tt->netbits_ipv6, tun_mtu); argv_msg(M_INFO, &argv); /* AIX ifconfig will complain if it can't find ODM path in env */ es =3D env_set_create(NULL); env_set_add(es, "ODMDIR=3D/etc/objrepos"); - openvpn_execve_check(&argv, es, S_FATAL, - "generic BSD ifconfig inet6 failed"); + openvpn_execve_check(&argv, es, S_FATAL, "generic BSD ifconfig inet6 f= ailed"); env_set_destroy(es); -#elif defined (_WIN32) +#elif defined(_WIN32) if (tt->options.ip_win32_type =3D=3D IPW32_SET_MANUAL) { - msg(M_INFO, "******** NOTE: Please manually set the v6 IP of '%s'= to %s (if it is not already set)", + msg(M_INFO, + "******** NOTE: Please manually set the v6 IP of '%s' to %s (= if it is not already set)", ifname, ifconfig_ipv6_local); } else if (tt->options.msg_channel) @@ -1275,8 +1195,8 @@ int netbits =3D (tt->type =3D=3D DEV_TYPE_TUN) ? 128 : tt->netbits= _ipv6; argv_printf(&argv, "%s%s interface ipv6 set address %lu %s/%d stor= e=3Dactive", - get_win_sys_path(), NETSH_PATH_SUFFIX, tt->adapter_ind= ex, - ifconfig_ipv6_local, netbits); + get_win_sys_path(), NETSH_PATH_SUFFIX, tt->adapter_ind= ex, ifconfig_ipv6_local, + netbits); netsh_command(&argv, 4, M_FATAL); if (tt->type =3D=3D DEV_TYPE_TUN) { @@ -1291,8 +1211,9 @@ do_dns_domain_wmic(true, tt); } } -#else /* platforms we have no IPv6 code for */ - msg(M_FATAL, "Sorry, but I don't know how to do IPv6 'ifconfig' comman= ds on this operating system. You should ifconfig your TUN/TAP device manua= lly or use an --up script."); +#else /* platforms we have no IPv6 code for */ + msg(M_FATAL, + "Sorry, but I don't know how to do IPv6 'ifconfig' commands on thi= s operating system. You should ifconfig your TUN/TAP device manually or us= e an --up script."); #endif /* outer "if defined(TARGET_xxx)" conditional */ #if !defined(TARGET_LINUX) @@ -1311,8 +1232,8 @@ * @param ctx the networking API opaque context */ static void -do_ifconfig_ipv4(struct tuntap *tt, const char *ifname, int tun_mtu, - const struct env_set *es, openvpn_net_ctx_t *ctx) +do_ifconfig_ipv4(struct tuntap *tt, const char *ifname, int tun_mtu, const= struct env_set *es, + openvpn_net_ctx_t *ctx) { #if !defined(_WIN32) && !defined(TARGET_ANDROID) /* @@ -1347,16 +1268,14 @@ if (tun_p2p) { - if (net_addr_ptp_v4_add(ctx, ifname, &tt->local, - &tt->remote_netmask) < 0) + if (net_addr_ptp_v4_add(ctx, ifname, &tt->local, &tt->remote_netma= sk) < 0) { msg(M_FATAL, "Linux can't add IP to interface %s", ifname); } } else { - if (net_addr_v4_add(ctx, ifname, &tt->local, - netmask_to_netbits2(tt->remote_netmask)) < 0) + if (net_addr_v4_add(ctx, ifname, &tt->local, netmask_to_netbits2(t= t->remote_netmask)) < 0) { msg(M_FATAL, "Linux can't add IP to interface %s", ifname); } @@ -1364,8 +1283,8 @@ #elif defined(TARGET_ANDROID) char out[64]; - snprintf(out, sizeof(out), "%s %s %d %s", ifconfig_local, - ifconfig_remote_netmask, tun_mtu, print_topology(tt->topology= )); + snprintf(out, sizeof(out), "%s %s %d %s", ifconfig_local, ifconfig_rem= ote_netmask, tun_mtu, + print_topology(tt->topology)); management_android_control(management, "IFCONFIG", out); #elif defined(TARGET_SOLARIS) @@ -1376,8 +1295,8 @@ */ if (tun_p2p) { - argv_printf(&argv, "%s %s %s %s mtu %d up", IFCONFIG_PATH, ifname, - ifconfig_local, ifconfig_remote_netmask, tun_mtu); + argv_printf(&argv, "%s %s %s %s mtu %d up", IFCONFIG_PATH, ifname,= ifconfig_local, + ifconfig_remote_netmask, tun_mtu); argv_msg(M_INFO, &argv); if (!openvpn_execve_check(&argv, es, 0, "Solaris ifconfig phase-1 = failed")) @@ -1385,19 +1304,16 @@ solaris_error_close(tt, es, ifname, false); } - argv_printf(&argv, "%s %s netmask 255.255.255.255", IFCONFIG_PATH, - ifname); + argv_printf(&argv, "%s %s netmask 255.255.255.255", IFCONFIG_PATH,= ifname); } else if (tt->type =3D=3D DEV_TYPE_TUN) { - argv_printf(&argv, "%s %s %s %s netmask %s mtu %d up", IFCONFIG_PA= TH, - ifname, ifconfig_local, ifconfig_local, - ifconfig_remote_netmask, tun_mtu); + argv_printf(&argv, "%s %s %s %s netmask %s mtu %d up", IFCONFIG_PA= TH, ifname, + ifconfig_local, ifconfig_local, ifconfig_remote_netmas= k, tun_mtu); } else /* tap */ { - argv_printf(&argv, "%s %s %s netmask %s up", - IFCONFIG_PATH, ifname, ifconfig_local, + argv_printf(&argv, "%s %s %s netmask %s up", IFCONFIG_PATH, ifname= , ifconfig_local, ifconfig_remote_netmask); } @@ -1422,7 +1338,7 @@ #elif defined(TARGET_OPENBSD) - in_addr_t remote_end; /* for "virtual" subnet topology */ + in_addr_t remote_end; /* for "virtual" subnet topology */ /* * On OpenBSD, tun interfaces are persistent if created with @@ -1433,24 +1349,20 @@ /* example: ifconfig tun2 10.2.0.2 10.2.0.1 mtu 1450 netmask 255.255.2= 55.255 up */ if (tun_p2p) { - argv_printf(&argv, - "%s %s %s %s mtu %d netmask 255.255.255.255 up -link0", - IFCONFIG_PATH, ifname, ifconfig_local, - ifconfig_remote_netmask, tun_mtu); + argv_printf(&argv, "%s %s %s %s mtu %d netmask 255.255.255.255 up = -link0", IFCONFIG_PATH, + ifname, ifconfig_local, ifconfig_remote_netmask, tun_m= tu); } else if (tt->type =3D=3D DEV_TYPE_TUN) { - remote_end =3D create_arbitrary_remote( tt ); - argv_printf(&argv, "%s %s %s %s mtu %d netmask %s up -link0", - IFCONFIG_PATH, ifname, ifconfig_local, - print_in_addr_t(remote_end, 0, &gc), tun_mtu, + remote_end =3D create_arbitrary_remote(tt); + argv_printf(&argv, "%s %s %s %s mtu %d netmask %s up -link0", IFCO= NFIG_PATH, ifname, + ifconfig_local, print_in_addr_t(remote_end, 0, &gc), t= un_mtu, ifconfig_remote_netmask); } else /* tap */ { - argv_printf(&argv, "%s %s %s netmask %s mtu %d link0", - IFCONFIG_PATH, ifname, ifconfig_local, - ifconfig_remote_netmask, tun_mtu); + argv_printf(&argv, "%s %s %s netmask %s mtu %d link0", IFCONFIG_PA= TH, ifname, + ifconfig_local, ifconfig_remote_netmask, tun_mtu); } argv_msg(M_INFO, &argv); openvpn_execve_check(&argv, es, S_FATAL, "OpenBSD ifconfig failed"); @@ -1468,20 +1380,19 @@ } #elif defined(TARGET_NETBSD) - in_addr_t remote_end =3D INADDR_ANY; /* for "virtual" subnet topology= */ + in_addr_t remote_end =3D INADDR_ANY; /* for "virtual" subnet topology = */ if (tun_p2p) { - argv_printf(&argv, "%s %s %s %s mtu %d netmask 255.255.255.255 up", - IFCONFIG_PATH, ifname, ifconfig_local, - ifconfig_remote_netmask, tun_mtu); + argv_printf(&argv, "%s %s %s %s mtu %d netmask 255.255.255.255 up"= , IFCONFIG_PATH, ifname, + ifconfig_local, ifconfig_remote_netmask, tun_mtu); } else if (tt->type =3D=3D DEV_TYPE_TUN) { remote_end =3D create_arbitrary_remote(tt); - argv_printf(&argv, "%s %s %s %s mtu %d netmask %s up", IFCONFIG_PA= TH, - ifname, ifconfig_local, print_in_addr_t(remote_end, 0,= &gc), - tun_mtu, ifconfig_remote_netmask); + argv_printf(&argv, "%s %s %s %s mtu %d netmask %s up", IFCONFIG_PA= TH, ifname, + ifconfig_local, print_in_addr_t(remote_end, 0, &gc), t= un_mtu, + ifconfig_remote_netmask); } else /* tap */ { @@ -1490,8 +1401,7 @@ * so we don't need the "link0" extra parameter to specify we want= to do * tunneling at the ethernet level */ - argv_printf(&argv, "%s %s %s netmask %s mtu %d", - IFCONFIG_PATH, ifname, ifconfig_local, + argv_printf(&argv, "%s %s %s netmask %s mtu %d", IFCONFIG_PATH, if= name, ifconfig_local, ifconfig_remote_netmask, tun_mtu); } argv_msg(M_INFO, &argv); @@ -1517,28 +1427,24 @@ argv_printf(&argv, "%s %s delete", IFCONFIG_PATH, ifname); argv_msg(M_INFO, &argv); openvpn_execve_check(&argv, es, 0, NULL); - msg(M_INFO, - "NOTE: Tried to delete pre-existing tun/tap instance -- No Problem= if failure"); + msg(M_INFO, "NOTE: Tried to delete pre-existing tun/tap instance -- No= Problem if failure"); /* example: ifconfig tun2 10.2.0.2 10.2.0.1 mtu 1450 netmask 255.255.2= 55.255 up */ if (tun_p2p) { - argv_printf(&argv, "%s %s %s %s mtu %d netmask 255.255.255.255 up", - IFCONFIG_PATH, ifname, ifconfig_local, - ifconfig_remote_netmask, tun_mtu); + argv_printf(&argv, "%s %s %s %s mtu %d netmask 255.255.255.255 up"= , IFCONFIG_PATH, ifname, + ifconfig_local, ifconfig_remote_netmask, tun_mtu); } else if (tt->type =3D=3D DEV_TYPE_TUN) { - argv_printf(&argv, "%s %s %s %s netmask %s mtu %d up", - IFCONFIG_PATH, ifname, ifconfig_local, ifconfig_local, - ifconfig_remote_netmask, tun_mtu); + argv_printf(&argv, "%s %s %s %s netmask %s mtu %d up", IFCONFIG_PA= TH, ifname, + ifconfig_local, ifconfig_local, ifconfig_remote_netmas= k, tun_mtu); } else /* tap */ { - argv_printf(&argv, "%s %s %s netmask %s mtu %d up", IFCONFIG_PATH, - ifname, ifconfig_local, ifconfig_remote_netmask, - tun_mtu); + argv_printf(&argv, "%s %s %s netmask %s mtu %d up", IFCONFIG_PATH,= ifname, ifconfig_local, + ifconfig_remote_netmask, tun_mtu); } argv_msg(M_INFO, &argv); @@ -1559,17 +1465,16 @@ #elif defined(TARGET_FREEBSD) || defined(TARGET_DRAGONFLY) /* example: ifconfig tun2 10.2.0.2 10.2.0.1 mtu 1450 netmask 255.255.2= 55.255 up */ - if (tun_p2p) /* point-to-point tun */ + if (tun_p2p) /* point-to-point tun */ { - argv_printf(&argv, "%s %s %s %s mtu %d netmask 255.255.255.255 up", - IFCONFIG_PATH, ifname, ifconfig_local, - ifconfig_remote_netmask, tun_mtu); + argv_printf(&argv, "%s %s %s %s mtu %d netmask 255.255.255.255 up"= , IFCONFIG_PATH, ifname, + ifconfig_local, ifconfig_remote_netmask, tun_mtu); } - else /* tun with topology subnet and tap mode (always subne= t) */ + else /* tun with topology subnet and tap mode (always subnet) */ { int netbits =3D netmask_to_netbits2(tt->remote_netmask); - argv_printf(&argv, "%s %s %s/%d mtu %d up", IFCONFIG_PATH, - ifname, ifconfig_local, netbits, tun_mtu ); + argv_printf(&argv, "%s %s %s/%d mtu %d up", IFCONFIG_PATH, ifname,= ifconfig_local, netbits, + tun_mtu); } argv_msg(M_INFO, &argv); @@ -1579,7 +1484,7 @@ { /* AIX ifconfig will complain if it can't find ODM path in env */ struct env_set *aix_es =3D env_set_create(NULL); - env_set_add( aix_es, "ODMDIR=3D/etc/objrepos" ); + env_set_add(aix_es, "ODMDIR=3D/etc/objrepos"); if (tt->type =3D=3D DEV_TYPE_TUN) { @@ -1587,23 +1492,23 @@ } /* example: ifconfig tap0 172.30.1.1 netmask 255.255.254.0 up */ - argv_printf(&argv, "%s %s %s netmask %s mtu %d up", IFCONFIG_PATH, - ifname, ifconfig_local, ifconfig_remote_netmask, tun_m= tu); + argv_printf(&argv, "%s %s %s netmask %s mtu %d up", IFCONFIG_PATH,= ifname, ifconfig_local, + ifconfig_remote_netmask, tun_mtu); argv_msg(M_INFO, &argv); openvpn_execve_check(&argv, aix_es, S_FATAL, "AIX ifconfig failed"= ); env_set_destroy(aix_es); } -#elif defined (_WIN32) +#elif defined(_WIN32) if (tt->options.ip_win32_type =3D=3D IPW32_SET_MANUAL) { msg(M_INFO, "******** NOTE: Please manually set the IP/netmask of '%s' to= %s/%s (if it is not already set)", - ifname, ifconfig_local, - ifconfig_remote_netmask); + ifname, ifconfig_local, ifconfig_remote_netmask); } - else if (tt->options.ip_win32_type =3D=3D IPW32_SET_DHCP_MASQ || tt->o= ptions.ip_win32_type =3D=3D IPW32_SET_ADAPTIVE) + else if (tt->options.ip_win32_type =3D=3D IPW32_SET_DHCP_MASQ + || tt->options.ip_win32_type =3D=3D IPW32_SET_ADAPTIVE) { /* Let the DHCP configure the interface. */ } @@ -1618,8 +1523,8 @@ { if (tt->options.ip_win32_type =3D=3D IPW32_SET_NETSH) { - netsh_ifconfig(&tt->options, tt->adapter_index, tt->local, - tt->adapter_netmask, NI_IP_NETMASK | NI_OPTIONS= ); + netsh_ifconfig(&tt->options, tt->adapter_index, tt->local, tt-= >adapter_netmask, + NI_IP_NETMASK | NI_OPTIONS); } do_dns_domain_wmic(true, tt); @@ -1636,13 +1541,14 @@ } #elif defined(TARGET_HAIKU) /* example: ifconfig tun/0 inet 1.1.1.1 255.255.255.0 mtu 1450 up */ - argv_printf(&argv, "%s %s inet %s %s mtu %d up", IFCONFIG_PATH, - ifname, ifconfig_local, ifconfig_remote_netmask, tun_mtu); + argv_printf(&argv, "%s %s inet %s %s mtu %d up", IFCONFIG_PATH, ifname= , ifconfig_local, + ifconfig_remote_netmask, tun_mtu); argv_msg(M_INFO, &argv); openvpn_execve_check(&argv, es, S_FATAL, "Haiku ifconfig failed"); #else /* if defined(TARGET_LINUX) */ - msg(M_FATAL, "Sorry, but I don't know how to do 'ifconfig' commands on= this operating system. You should ifconfig your TUN/TAP device manually o= r use an --up script."); + msg(M_FATAL, + "Sorry, but I don't know how to do 'ifconfig' commands on this ope= rating system. You should ifconfig your TUN/TAP device manually or use an = --up script."); #endif /* if defined(TARGET_LINUX) */ #if !defined(TARGET_LINUX) @@ -1653,8 +1559,8 @@ /* execute the ifconfig command through the shell */ void -do_ifconfig(struct tuntap *tt, const char *ifname, int tun_mtu, - const struct env_set *es, openvpn_net_ctx_t *ctx) +do_ifconfig(struct tuntap *tt, const char *ifname, int tun_mtu, const stru= ct env_set *es, + openvpn_net_ctx_t *ctx) { msg(D_LOW, "do_ifconfig, ipv4=3D%d, ipv6=3D%d", tt->did_ifconfig_setup, tt->did_ifconfig_ipv6_setup); @@ -1662,13 +1568,8 @@ #ifdef ENABLE_MANAGEMENT if (management) { - management_set_state(management, - OPENVPN_STATE_ASSIGN_IP, - NULL, - &tt->local, - &tt->local_ipv6, - NULL, - NULL); + management_set_state(management, OPENVPN_STATE_ASSIGN_IP, NULL, &t= t->local, &tt->local_ipv6, + NULL, NULL); } #endif @@ -1694,19 +1595,16 @@ if (is_tun_p2p(tt)) { - if (net_addr_ptp_v4_del(ctx, tt->actual_name, &tt->local, - &tt->remote_netmask) < 0) + if (net_addr_ptp_v4_del(ctx, tt->actual_name, &tt->local, &tt->rem= ote_netmask) < 0) { - msg(M_WARN, "Linux can't del IP from iface %s", - tt->actual_name); + msg(M_WARN, "Linux can't del IP from iface %s", tt->actual_nam= e); } } else { if (net_addr_v4_del(ctx, tt->actual_name, &tt->local, netbits) < 0) { - msg(M_WARN, "Linux can't del IP from iface %s", - tt->actual_name); + msg(M_WARN, "Linux can't del IP from iface %s", tt->actual_nam= e); } } #elif defined(TARGET_FREEBSD) @@ -1714,8 +1612,7 @@ const char *ifconfig_local =3D print_in_addr_t(tt->local, 0, &gc); struct argv argv =3D argv_new(); - argv_printf(&argv, "%s %s %s -alias", IFCONFIG_PATH, - tt->actual_name, ifconfig_local); + argv_printf(&argv, "%s %s %s -alias", IFCONFIG_PATH, tt->actual_name, = ifconfig_local); argv_msg(M_INFO, &argv); openvpn_execve_check(&argv, NULL, 0, "FreeBSD ip addr del failed"); @@ -1729,8 +1626,7 @@ undo_ifconfig_ipv6(struct tuntap *tt, openvpn_net_ctx_t *ctx) { #if defined(TARGET_LINUX) - if (net_addr_v6_del(ctx, tt->actual_name, &tt->local_ipv6, - tt->netbits_ipv6) < 0) + if (net_addr_v6_del(ctx, tt->actual_name, &tt->local_ipv6, tt->netbits= _ipv6) < 0) { msg(M_WARN, "Linux can't del IPv6 from iface %s", tt->actual_name); } @@ -1739,8 +1635,8 @@ const char *ifconfig_ipv6_local =3D print_in6_addr(tt->local_ipv6, 0, = &gc); struct argv argv =3D argv_new(); - argv_printf(&argv, "%s %s inet6 %s/%d -alias", IFCONFIG_PATH, - tt->actual_name, ifconfig_ipv6_local, tt->netbits_ipv6); + argv_printf(&argv, "%s %s inet6 %s/%d -alias", IFCONFIG_PATH, tt->actu= al_name, + ifconfig_ipv6_local, tt->netbits_ipv6); argv_msg(M_INFO, &argv); openvpn_execve_check(&argv, NULL, 0, "FreeBSD ip -6 addr del failed"); @@ -1830,7 +1726,7 @@ struct iovec iv[2]; struct openvpn_iphdr *iph; - iph =3D (struct openvpn_iphdr *) buf; + iph =3D (struct openvpn_iphdr *)buf; if (OPENVPN_IPH_GET_VER(iph->version_len) =3D=3D 6) { @@ -1893,8 +1789,7 @@ #if !(defined(_WIN32) || defined(TARGET_LINUX) || defined(TARGET_SOLARIS)) static void -open_tun_generic(const char *dev, const char *dev_type, const char *dev_no= de, - struct tuntap *tt) +open_tun_generic(const char *dev, const char *dev_type, const char *dev_no= de, struct tuntap *tt) { char tunname[256]; char dynamic_name[256]; @@ -1924,10 +1819,8 @@ #if defined(TARGET_HAIKU) sep =3D "/"; #endif - snprintf(tunname, sizeof(tunname), - "/dev/%s%s%d", dev, sep, i); - snprintf(dynamic_name, sizeof(dynamic_name), - "%s%s%d", dev, sep, i); + snprintf(tunname, sizeof(tunname), "/dev/%s%s%d", dev, sep= , i); + snprintf(dynamic_name, sizeof(dynamic_name), "%s%s%d", dev= , sep, i); if ((tt->fd =3D open(tunname, O_RDWR)) > 0) { dynamic_opened =3D true; @@ -1952,9 +1845,9 @@ if (!dynamic_opened) { /* has named device existed before? if so, don't destroy at end */ - if (if_nametoindex( dev ) > 0) + if (if_nametoindex(dev) > 0) { - msg(M_INFO, "TUN/TAP device %s exists previously, keep at prog= ram end", dev ); + msg(M_INFO, "TUN/TAP device %s exists previously, keep at prog= ram end", dev); tt->persistent_if =3D true; } @@ -1970,14 +1863,13 @@ /* tt->actual_name is passed to up and down scripts and used as the if= config dev name */ tt->actual_name =3D string_alloc(dynamic_opened ? dynamic_name : dev, = NULL); - } #endif /* !_WIN32 && !TARGET_LINUX && !TARGET_FREEBSD*/ #if defined(TARGET_LINUX) || defined(TARGET_FREEBSD) static void -open_tun_dco_generic(const char *dev, const char *dev_type, - struct tuntap *tt, openvpn_net_ctx_t *ctx) +open_tun_dco_generic(const char *dev, const char *dev_type, struct tuntap = *tt, + openvpn_net_ctx_t *ctx) { char dynamic_name[256]; bool dynamic_opened =3D false; @@ -1994,8 +1886,7 @@ { for (int i =3D 0; i < 256; ++i) { - snprintf(dynamic_name, sizeof(dynamic_name), - "%s%d", dev, i); + snprintf(dynamic_name, sizeof(dynamic_name), "%s%d", dev, i); int ret =3D open_tun_dco(tt, ctx, dynamic_name); if (ret =3D=3D 0) { @@ -2025,14 +1916,12 @@ int ret =3D open_tun_dco(tt, ctx, dev); if (ret =3D=3D -EEXIST) { - msg(M_INFO, "DCO device %s already exists, won't be destroyed = at shutdown", - dev); + msg(M_INFO, "DCO device %s already exists, won't be destroyed = at shutdown", dev); tt->persistent_if =3D true; } else if (ret < 0) { - msg(M_ERR, "Cannot open DCO device %s: %s (%d)", dev, - strerror(-ret), ret); + msg(M_ERR, "Cannot open DCO device %s: %s (%d)", dev, strerror= (-ret), ret); } else { @@ -2059,7 +1948,7 @@ } #endif /* !_WIN32 */ =20 -#if defined (TARGET_ANDROID) +#if defined(TARGET_ANDROID) void open_tun(const char *dev, const char *dev_type, const char *dev_node, stru= ct tuntap *tt, openvpn_net_ctx_t *ctx) @@ -2099,7 +1988,7 @@ int android_method =3D managment_android_persisttun_action(management); - if (oldtunfd >=3D0 && android_method =3D=3D ANDROID_KEEP_OLD_TUN) + if (oldtunfd >=3D 0 && android_method =3D=3D ANDROID_KEEP_OLD_TUN) { /* keep the old fd */ opentun =3D true; @@ -2210,8 +2099,7 @@ } else { - msg(M_FATAL, "I don't recognize device %s as a tun or tap devi= ce", - dev); + msg(M_FATAL, "I don't recognize device %s as a tun or tap devi= ce", dev); } /* @@ -2226,7 +2114,7 @@ * Use special ioctl that configures tun/tap device with the parms * we set in ifr */ - if (ioctl(tt->fd, TUNSETIFF, (void *) &ifr) < 0) + if (ioctl(tt->fd, TUNSETIFF, (void *)&ifr) < 0) { msg(M_ERR, "ERROR: Cannot ioctl TUNSETIFF %s", dev); } @@ -2247,7 +2135,7 @@ CLEAR(netifr); strncpynt(netifr.ifr_name, ifr.ifr_name, IFNAMSIZ); netifr.ifr_qlen =3D tt->options.txqueuelen; - if (ioctl(ctl_fd, SIOCSIFTXQLEN, (void *) &netifr) >=3D 0) + if (ioctl(ctl_fd, SIOCSIFTXQLEN, (void *)&netifr) >=3D 0) { msg(D_OSBUF, "TUN/TAP TX queue length set to %d", tt->= options.txqueuelen); } @@ -2286,13 +2174,13 @@ /* TUNSETGROUP appeared in 2.6.23 */ #ifndef TUNSETGROUP -#define TUNSETGROUP _IOW('T', 206, int) +#define TUNSETGROUP _IOW('T', 206, int) #endif void -tuncfg(const char *dev, const char *dev_type, const char *dev_node, - int persist_mode, const char *username, const char *groupname, - const struct tuntap_options *options, openvpn_net_ctx_t *ctx) +tuncfg(const char *dev, const char *dev_type, const char *dev_node, int pe= rsist_mode, + const char *username, const char *groupname, const struct tuntap_op= tions *options, + openvpn_net_ctx_t *ctx) { struct tuntap *tt; @@ -2412,8 +2300,7 @@ } else { - msg(M_FATAL, "I don't recognize device %s as a tun or tap device", - dev); + msg(M_FATAL, "I don't recognize device %s as a tun or tap device",= dev); } if ((tt->ip_fd =3D open(ip_node, O_RDWR, 0)) < 0) @@ -2431,7 +2318,7 @@ /* get unit number */ if (*ptr) { - while (*ptr && !isdigit((int) *ptr)) + while (*ptr && !isdigit((int)*ptr)) { ptr++; } @@ -2444,7 +2331,7 @@ strioc_ppa.ic_len =3D sizeof(ppa); strioc_ppa.ic_dp =3D (char *)&ppa; - if (*ptr =3D=3D '\0') /* no number given, try dynamic */ + if (*ptr =3D=3D '\0') /* no number given, try dynamic */ { bool found_one =3D false; while (!found_one && ppa < 64) @@ -2452,27 +2339,28 @@ int new_ppa =3D ioctl(tt->fd, I_STR, &strioc_ppa); if (new_ppa >=3D 0) { - msg( M_INFO, "open_tun: got dynamic interface '%s%d'", dev= _tuntap_type, new_ppa ); + msg(M_INFO, "open_tun: got dynamic interface '%s%d'", dev_= tuntap_type, new_ppa); ppa =3D new_ppa; found_one =3D true; break; } if (errno !=3D EEXIST) { - msg(M_ERR, "open_tun: unexpected error trying to find free= %s interface", dev_tuntap_type ); + msg(M_ERR, "open_tun: unexpected error trying to find free= %s interface", + dev_tuntap_type); } ppa++; } if (!found_one) { - msg(M_ERR, "open_tun: could not find free %s interface, give u= p.", dev_tuntap_type ); + msg(M_ERR, "open_tun: could not find free %s interface, give u= p.", dev_tuntap_type); } } - else /* try this particular one */ + else /* try this particular one */ { if ((ppa =3D ioctl(tt->fd, I_STR, &strioc_ppa)) < 0) { - msg(M_ERR, "Can't assign PPA for new interface (%s%d)", dev_tu= ntap_type, ppa ); + msg(M_ERR, "Can't assign PPA for new interface (%s%d)", dev_tu= ntap_type, ppa); } } @@ -2489,13 +2377,13 @@ if (tt->type =3D=3D DEV_TYPE_TUN) { /* Assign ppa according to the unit number returned by tun device = */ - if (ioctl(if_fd, IF_UNITSEL, (char *) &ppa) < 0) + if (ioctl(if_fd, IF_UNITSEL, (char *)&ppa) < 0) { msg(M_ERR, "Can't set PPA %d", ppa); } } - tt->actual_name =3D (char *) malloc(32); + tt->actual_name =3D (char *)malloc(32); check_malloc_return(tt->actual_name); snprintf(tt->actual_name, 32, "%s%d", dev_tuntap_type, ppa); @@ -2513,7 +2401,7 @@ { msg(M_ERR, "Can't set PPA %d", ppa); } - if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) <0) + if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) < 0) { msg(M_ERR, "Can't get flags\n"); } @@ -2575,7 +2463,7 @@ CLEAR(ifr); strncpynt(ifr.lifr_name, tt->actual_name, sizeof(ifr.lifr_name)); - ifr.lifr_ip_muxid =3D ip_muxid; + ifr.lifr_ip_muxid =3D ip_muxid; if (tt->type =3D=3D DEV_TYPE_TAP) { ifr.lifr_arp_muxid =3D arp_muxid; @@ -2605,8 +2493,7 @@ if (tt->did_ifconfig_ipv6_setup) { struct argv argv =3D argv_new(); - argv_printf( &argv, "%s %s inet6 unplumb", - IFCONFIG_PATH, tt->actual_name ); + argv_printf(&argv, "%s %s inet6 unplumb", IFCONFIG_PATH, tt->actua= l_name); argv_msg(M_INFO, &argv); openvpn_execve_check(&argv, NULL, 0, "Solaris ifconfig inet6 unplu= mb failed"); argv_free(&argv); @@ -2669,23 +2556,19 @@ } static void -solaris_error_close(struct tuntap *tt, const struct env_set *es, - const char *actual, bool unplumb_inet6 ) +solaris_error_close(struct tuntap *tt, const struct env_set *es, const cha= r *actual, + bool unplumb_inet6) { struct argv argv =3D argv_new(); if (unplumb_inet6) { - argv_printf( &argv, "%s %s inet6 unplumb", - IFCONFIG_PATH, actual ); + argv_printf(&argv, "%s %s inet6 unplumb", IFCONFIG_PATH, actual); argv_msg(M_INFO, &argv); openvpn_execve_check(&argv, es, 0, "Solaris ifconfig inet6 unplumb= failed"); } - argv_printf(&argv, - "%s %s unplumb", - IFCONFIG_PATH, - actual); + argv_printf(&argv, "%s %s unplumb", IFCONFIG_PATH, actual); argv_msg(M_INFO, &argv); openvpn_execve_check(&argv, es, 0, "Solaris ifconfig unplumb failed"); @@ -2771,8 +2654,7 @@ /* setup command, close tun dev (clears tt->actual_name!), run command */ - argv_printf(&argv, "%s %s destroy", - IFCONFIG_PATH, tt->actual_name); + argv_printf(&argv, "%s %s destroy", IFCONFIG_PATH, tt->actual_name); close_tun_generic(tt); @@ -2822,11 +2704,11 @@ if (strcmp(dev, "tap") =3D=3D 0) { struct ifreq ifr; - if ((tt->fd =3D open( "/dev/tap", O_RDWR)) < 0) + if ((tt->fd =3D open("/dev/tap", O_RDWR)) < 0) { msg(M_FATAL, "Cannot allocate NetBSD TAP dev dynamically"); } - if (ioctl( tt->fd, TAPGIFNAME, (void *)&ifr ) < 0) + if (ioctl(tt->fd, TAPGIFNAME, (void *)&ifr) < 0) { msg(M_FATAL, "Cannot query NetBSD TAP device name"); } @@ -2846,15 +2728,15 @@ if (tt->fd >=3D 0) { - int i =3D IFF_POINTOPOINT|IFF_MULTICAST; - ioctl(tt->fd, TUNSIFMODE, &i); /* multicast on */ + int i =3D IFF_POINTOPOINT | IFF_MULTICAST; + ioctl(tt->fd, TUNSIFMODE, &i); /* multicast on */ i =3D 0; - ioctl(tt->fd, TUNSLMODE, &i); /* link layer mode off */ + ioctl(tt->fd, TUNSLMODE, &i); /* link layer mode off */ if (tt->type =3D=3D DEV_TYPE_TUN) { i =3D 1; - if (ioctl(tt->fd, TUNSIFHEAD, &i) < 0) /* multi-af mode o= n */ + if (ioctl(tt->fd, TUNSIFHEAD, &i) < 0) /* multi-af mode on */ { msg(M_WARN | M_ERRNO, "ioctl(TUNSIFHEAD)"); } @@ -2885,8 +2767,7 @@ /* setup command, close tun dev (clears tt->actual_name!), run command */ - argv_printf(&argv, "%s %s destroy", - IFCONFIG_PATH, tt->actual_name); + argv_printf(&argv, "%s %s destroy", IFCONFIG_PATH, tt->actual_name); close_tun_generic(tt); @@ -2919,7 +2800,7 @@ struct iovec iv[2]; struct openvpn_iphdr *iph; - iph =3D (struct openvpn_iphdr *) buf; + iph =3D (struct openvpn_iphdr *)buf; if (OPENVPN_IPH_GET_VER(iph->version_len) =3D=3D 6) { @@ -3027,7 +2908,7 @@ { ASSERT(tt); - if (tt->persistent_if) /* keep pre-existing if around */ + if (tt->persistent_if) /* keep pre-existing if around */ { close_tun_generic(tt); free(tt); @@ -3040,14 +2921,12 @@ /* setup command, close tun dev (clears tt->actual_name!), run command */ - argv_printf(&argv, "%s %s destroy", - IFCONFIG_PATH, tt->actual_name); + argv_printf(&argv, "%s %s destroy", IFCONFIG_PATH, tt->actual_name); close_tun_generic(tt); argv_msg(M_INFO, &argv); - openvpn_execve_check(&argv, NULL, 0, - "FreeBSD 'destroy tun interface' failed (non-crit= ical)"); + openvpn_execve_check(&argv, NULL, 0, "FreeBSD 'destroy tun interface' = failed (non-critical)"); free(tt); argv_free(&argv); @@ -3062,7 +2941,7 @@ struct iovec iv[2]; struct ip *iph; - iph =3D (struct ip *) buf; + iph =3D (struct ip *)buf; if (iph->ip_v =3D=3D 6) { @@ -3157,7 +3036,7 @@ struct iovec iv[2]; struct ip *iph; - iph =3D (struct ip *) buf; + iph =3D (struct ip *)buf; if (iph->ip_v =3D=3D 6) { @@ -3233,16 +3112,14 @@ if (fd < 0) { - msg(M_INFO | M_ERRNO, "Opening utun%d failed (socket(SYSPROTO_CONT= ROL))", - utunnum); + msg(M_INFO | M_ERRNO, "Opening utun%d failed (socket(SYSPROTO_CONT= ROL))", utunnum); return -2; } if (ioctl(fd, CTLIOCGINFO, &ctlInfo) =3D=3D -1) { close(fd); - msg(M_INFO | M_ERRNO, "Opening utun%d failed (ioctl(CTLIOCGINFO))", - utunnum); + msg(M_INFO | M_ERRNO, "Opening utun%d failed (ioctl(CTLIOCGINFO))"= , utunnum); return -2; } @@ -3252,7 +3129,7 @@ sc.sc_family =3D AF_SYSTEM; sc.ss_sysaddr =3D AF_SYS_CONTROL; - sc.sc_unit =3D utunnum+1; + sc.sc_unit =3D utunnum + 1; /* If the connect is successful, a utun%d device will be created, wher= e "%d" @@ -3260,8 +3137,7 @@ if (connect(fd, (struct sockaddr *)&sc, sizeof(sc)) < 0) { - msg(M_INFO | M_ERRNO, "Opening utun%d failed (connect(AF_SYS_CONTR= OL))", - utunnum); + msg(M_INFO | M_ERRNO, "Opening utun%d failed (connect(AF_SYS_CONTR= OL))", utunnum); close(fd); return -1; } @@ -3283,20 +3159,21 @@ /* dev_node is simply utun, do the normal dynamic utun * otherwise try to parse the utun number */ - if (dev_node && (strcmp("utun", dev_node) !=3D 0 )) + if (dev_node && (strcmp("utun", dev_node) !=3D 0)) { if (sscanf(dev_node, "utun%d", &utunnum) !=3D 1) { - msg(M_FATAL, "Cannot parse 'dev-node %s' please use 'dev-node = utunX'" - "to use a utun device number X", dev_node); + msg(M_FATAL, + "Cannot parse 'dev-node %s' please use 'dev-node utunX'" + "to use a utun device number X", + dev_node); } } - CLEAR(ctlInfo); - if (strlcpy(ctlInfo.ctl_name, UTUN_CONTROL_NAME, sizeof(ctlInfo.ctl_na= me)) >=3D - sizeof(ctlInfo.ctl_name)) + if (strlcpy(ctlInfo.ctl_name, UTUN_CONTROL_NAME, sizeof(ctlInfo.ctl_na= me)) + >=3D sizeof(ctlInfo.ctl_name)) { msg(M_ERR, "Opening utun: UTUN_CONTROL_NAME too long"); } @@ -3316,7 +3193,7 @@ fd =3D utun_open_helper(ctlInfo, utunnum); /* Break if the fd is valid, * or if early initialization failed (-2) */ - if (fd !=3D-1) + if (fd !=3D -1) { break; } @@ -3352,13 +3229,11 @@ openvpn_net_ctx_t *ctx) { /* If dev_node does not start start with utun assume regular tun/tap */ - if ((!dev_node && tt->type=3D=3DDEV_TYPE_TUN) - || (dev_node && !strncmp(dev_node, "utun", 4))) + if ((!dev_node && tt->type =3D=3D DEV_TYPE_TUN) || (dev_node && !strnc= mp(dev_node, "utun", 4))) { - /* Check if user has specific dev_type tap and forced utun with * dev-node utun */ - if (tt->type!=3DDEV_TYPE_TUN) + if (tt->type !=3D DEV_TYPE_TUN) { msg(M_FATAL, "Cannot use utun devices with --dev-type %s", dev_type_string(dev, dev_type)); @@ -3386,12 +3261,11 @@ } else { - /* Use plain dev-node tun to select /dev/tun style * Unset dev_node variable prior to passing to open_tun_generic to * let open_tun_generic pick the first available tun device */ - if (dev_node && strcmp(dev_node, "tun")=3D=3D0) + if (dev_node && strcmp(dev_node, "tun") =3D=3D 0) { dev_node =3D NULL; } @@ -3410,11 +3284,9 @@ if (tt->did_ifconfig_ipv6_setup) { - const char *ifconfig_ipv6_local =3D - print_in6_addr(tt->local_ipv6, 0, &gc); + const char *ifconfig_ipv6_local =3D print_in6_addr(tt->local_ipv6,= 0, &gc); - argv_printf(&argv, "%s delete -inet6 %s", - ROUTE_PATH, ifconfig_ipv6_local ); + argv_printf(&argv, "%s delete -inet6 %s", ROUTE_PATH, ifconfig_ipv= 6_local); argv_msg(M_INFO, &argv); openvpn_execve_check(&argv, NULL, 0, "MacOS X 'remove inet6 route'= failed (non-critical)"); } @@ -3463,44 +3335,46 @@ if (tt->type =3D=3D DEV_TYPE_TUN) { - msg(M_FATAL, "no support for 'tun' devices on AIX" ); + msg(M_FATAL, "no support for 'tun' devices on AIX"); } - if (strncmp( dev, "tap", 3 ) !=3D 0 || dev_node) + if (strncmp(dev, "tap", 3) !=3D 0 || dev_node) { - msg(M_FATAL, "'--dev %s' and/or '--dev-node' not supported on AIX,= use '--dev tap0', 'tap1', etc.", dev ); + msg(M_FATAL, + "'--dev %s' and/or '--dev-node' not supported on AIX, use '--d= ev tap0', 'tap1', etc.", + dev); } - if (strcmp( dev, "tap" ) =3D=3D 0) /* find first free tap= dev */ - { /* (=3D no /dev/tapN node)= */ + if (strcmp(dev, "tap") =3D=3D 0) /* find first free tap dev */ + { /* (=3D no /dev/tapN node) */ int i; - for (i =3D 0; i<99; i++) + for (i =3D 0; i < 99; i++) { snprintf(tunname, sizeof(tunname), "/dev/tap%d", i); - if (access( tunname, F_OK ) < 0 && errno =3D=3D ENOENT) + if (access(tunname, F_OK) < 0 && errno =3D=3D ENOENT) { break; } } if (i >=3D 99) { - msg( M_FATAL, "cannot find unused tap device" ); + msg(M_FATAL, "cannot find unused tap device"); } - snprintf( dynamic_name, sizeof(dynamic_name), "tap%d", i ); + snprintf(dynamic_name, sizeof(dynamic_name), "tap%d", i); dev =3D dynamic_name; } - else /* name given, sanity chec= k */ + else /* name given, sanity check */ { /* ensure that dev name is "tap+" *only* */ p =3D &dev[3]; - while (isdigit(*p) ) + while (isdigit(*p)) { p++; } if (*p !=3D '\0') { - msg( M_FATAL, "TAP device name must be '--dev tapNNNN'" ); + msg(M_FATAL, "TAP device name must be '--dev tapNNNN'"); } snprintf(tunname, sizeof(tunname), "/dev/%s", dev); @@ -3508,16 +3382,15 @@ /* pre-existing device? */ - if (access( tunname, F_OK ) < 0 && errno =3D=3D ENOENT) + if (access(tunname, F_OK) < 0 && errno =3D=3D ENOENT) { - /* tunnel device must be created with 'ifconfig tapN create' */ struct argv argv =3D argv_new(); struct env_set *es =3D env_set_create(NULL); argv_printf(&argv, "%s %s create", IFCONFIG_PATH, dev); argv_msg(M_INFO, &argv); - env_set_add( es, "ODMDIR=3D/etc/objrepos" ); + env_set_add(es, "ODMDIR=3D/etc/objrepos"); openvpn_execve_check(&argv, es, S_FATAL, "AIX 'create tun interfac= e' failed"); env_set_destroy(es); argv_free(&argv); @@ -3555,18 +3428,16 @@ */ if (tt->persistent_if) { - argv_printf(&argv, "%s %s 0.0.0.0 down", - IFCONFIG_PATH, tt->actual_name); + argv_printf(&argv, "%s %s 0.0.0.0 down", IFCONFIG_PATH, tt->actual= _name); } else { - argv_printf(&argv, "%s %s destroy", - IFCONFIG_PATH, tt->actual_name); + argv_printf(&argv, "%s %s destroy", IFCONFIG_PATH, tt->actual_name= ); } close_tun_generic(tt); argv_msg(M_INFO, &argv); - env_set_add( es, "ODMDIR=3D/etc/objrepos" ); + env_set_add(es, "ODMDIR=3D/etc/objrepos"); openvpn_execve_check(&argv, es, 0, "AIX 'destroy tap interface' failed= (non-critical)"); free(tt); @@ -3606,13 +3477,8 @@ /* the overlapped read will signal this event on I/O completion */ ASSERT(ResetEvent(tt->reads.overlapped.hEvent)); - status =3D ReadFile( - tt->hand, - BPTR(&tt->reads.buf), - len, - &tt->reads.size, - &tt->reads.overlapped - ); + status =3D + ReadFile(tt->hand, BPTR(&tt->reads.buf), len, &tt->reads.size,= &tt->reads.overlapped); if (status) /* operation completed immediately? */ { @@ -3622,9 +3488,8 @@ tt->reads.iostate =3D IOSTATE_IMMEDIATE_RETURN; tt->reads.status =3D 0; - dmsg(D_WIN32_IO, "WIN32 I/O: TAP Read immediate return [%d,%d]= ", - (int) len, - (int) tt->reads.size); + dmsg(D_WIN32_IO, "WIN32 I/O: TAP Read immediate return [%d,%d]= ", (int)len, + (int)tt->reads.size); } else { @@ -3633,8 +3498,7 @@ { tt->reads.iostate =3D IOSTATE_QUEUED; tt->reads.status =3D err; - dmsg(D_WIN32_IO, "WIN32 I/O: TAP Read queued [%d]", - (int) len); + dmsg(D_WIN32_IO, "WIN32 I/O: TAP Read queued [%d]", (int)l= en); } else /* error occurred */ { @@ -3642,8 +3506,7 @@ ASSERT(SetEvent(tt->reads.overlapped.hEvent)); tt->reads.iostate =3D IOSTATE_IMMEDIATE_RETURN; tt->reads.status =3D err; - dmsg(D_WIN32_IO, "WIN32 I/O: TAP Read error [%d] : %s", - (int) len, + dmsg(D_WIN32_IO, "WIN32 I/O: TAP Read error [%d] : %s", (i= nt)len, strerror_win32(status, &gc)); gc_free(&gc); } @@ -3668,13 +3531,8 @@ /* the overlapped write will signal this event on I/O completion */ ASSERT(ResetEvent(tt->writes.overlapped.hEvent)); - status =3D WriteFile( - tt->hand, - BPTR(&tt->writes.buf), - BLEN(&tt->writes.buf), - &tt->writes.size, - &tt->writes.overlapped - ); + status =3D WriteFile(tt->hand, BPTR(&tt->writes.buf), BLEN(&tt->wr= ites.buf), &tt->writes.size, + &tt->writes.overlapped); if (status) /* operation completed immediately? */ { @@ -3685,9 +3543,8 @@ tt->writes.status =3D 0; - dmsg(D_WIN32_IO, "WIN32 I/O: TAP Write immediate return [%d,%d= ]", - BLEN(&tt->writes.buf), - (int) tt->writes.size); + dmsg(D_WIN32_IO, "WIN32 I/O: TAP Write immediate return [%d,%d= ]", BLEN(&tt->writes.buf), + (int)tt->writes.size); } else { @@ -3696,8 +3553,7 @@ { tt->writes.iostate =3D IOSTATE_QUEUED; tt->writes.status =3D err; - dmsg(D_WIN32_IO, "WIN32 I/O: TAP Write queued [%d]", - BLEN(&tt->writes.buf)); + dmsg(D_WIN32_IO, "WIN32 I/O: TAP Write queued [%d]", BLEN(= &tt->writes.buf)); } else /* error occurred */ { @@ -3705,8 +3561,7 @@ ASSERT(SetEvent(tt->writes.overlapped.hEvent)); tt->writes.iostate =3D IOSTATE_IMMEDIATE_RETURN; tt->writes.status =3D err; - dmsg(D_WIN32_IO, "WIN32 I/O: TAP Write error [%d] : %s", - BLEN(&tt->writes.buf), + dmsg(D_WIN32_IO, "WIN32 I/O: TAP Write error [%d] : %s", B= LEN(&tt->writes.buf), strerror_win32(err, &gc)); gc_free(&gc); } @@ -3749,11 +3604,13 @@ struct device_instance_id_interface *first =3D NULL; struct device_instance_id_interface *last =3D NULL; - dev_info_set =3D SetupDiGetClassDevsEx(&GUID_DEVCLASS_NET, NULL, NULL,= DIGCF_PRESENT, NULL, NULL, NULL); + dev_info_set =3D + SetupDiGetClassDevsEx(&GUID_DEVCLASS_NET, NULL, NULL, DIGCF_PRESEN= T, NULL, NULL, NULL); if (dev_info_set =3D=3D INVALID_HANDLE_VALUE) { err =3D GetLastError(); - msg(M_FATAL, "Error [%u] opening device information set key: %s", = (unsigned int)err, strerror_win32(err, gc)); + msg(M_FATAL, "Error [%u] opening device information set key: %s", = (unsigned int)err, + strerror_win32(err, gc)); } msg(D_TAP_WIN_DEBUG, "Enumerate device interface lists:"); @@ -3786,7 +3643,8 @@ } } - dev_key =3D SetupDiOpenDevRegKey(dev_info_set, &device_info_data, = DICS_FLAG_GLOBAL, 0, DIREG_DRV, KEY_QUERY_VALUE); + dev_key =3D SetupDiOpenDevRegKey(dev_info_set, &device_info_data, = DICS_FLAG_GLOBAL, 0, + DIREG_DRV, KEY_QUERY_VALUE); if (dev_key =3D=3D INVALID_HANDLE_VALUE) { continue; @@ -3794,27 +3652,23 @@ len =3D sizeof(net_cfg_instance_id); data_type =3D REG_SZ; - status =3D RegQueryValueEx(dev_key, - net_cfg_instance_id_string, - NULL, - &data_type, - net_cfg_instance_id, - &len); + status =3D RegQueryValueEx(dev_key, net_cfg_instance_id_string, NU= LL, &data_type, + net_cfg_instance_id, &len); if (status !=3D ERROR_SUCCESS) { goto next; } len =3D sizeof(device_instance_id); - res =3D SetupDiGetDeviceInstanceId(dev_info_set, &device_info_data= , device_instance_id, len, &len); + res =3D SetupDiGetDeviceInstanceId(dev_info_set, &device_info_data= , device_instance_id, len, + &len); if (!res) { goto next; } cr =3D CM_Get_Device_Interface_List_Size(&dev_interface_list_size, - (LPGUID)&GUID_DEVINTERFACE_= NET, - device_instance_id, + (LPGUID)&GUID_DEVINTERFACE_= NET, device_instance_id, CM_GET_DEVICE_INTERFACE_LIS= T_PRESENT); if (cr !=3D CR_SUCCESS) @@ -3824,8 +3678,7 @@ char *dev_interface_list =3D gc_malloc(dev_interface_list_size, fa= lse, gc); cr =3D CM_Get_Device_Interface_List((LPGUID)&GUID_DEVINTERFACE_NET= , device_instance_id, - dev_interface_list, - dev_interface_list_size, + dev_interface_list, dev_interfac= e_list_size, CM_GET_DEVICE_INTERFACE_LIST_PRE= SENT); if (cr !=3D CR_SUCCESS) { @@ -3839,12 +3692,12 @@ { struct device_instance_id_interface *dev_iif; ALLOC_OBJ_CLEAR_GC(dev_iif, struct device_instance_id_interfac= e, gc); - dev_iif->net_cfg_instance_id =3D (unsigned char *)string_alloc= ((char *)net_cfg_instance_id, gc); + dev_iif->net_cfg_instance_id =3D + (unsigned char *)string_alloc((char *)net_cfg_instance_id,= gc); dev_iif->device_interface =3D string_alloc(dev_if, gc); msg(D_TAP_WIN_DEBUG, "NetCfgInstanceId: %s, Device Interface: = %s", - dev_iif->net_cfg_instance_id, - dev_iif->device_interface); + dev_iif->net_cfg_instance_id, dev_iif->device_interface); /* link into return list */ if (!first) @@ -3879,12 +3732,7 @@ struct tap_reg *last =3D NULL; int i =3D 0; - status =3D RegOpenKeyEx( - HKEY_LOCAL_MACHINE, - ADAPTER_KEY, - 0, - KEY_READ, - &adapter_key); + status =3D RegOpenKeyEx(HKEY_LOCAL_MACHINE, ADAPTER_KEY, 0, KEY_READ, = &adapter_key); =20 if (status !=3D ERROR_SUCCESS) { @@ -3904,34 +3752,19 @@ DWORD data_type; len =3D sizeof(enum_name); - status =3D RegEnumKeyEx( - adapter_key, - i, - enum_name, - &len, - NULL, - NULL, - NULL, - NULL); + status =3D RegEnumKeyEx(adapter_key, i, enum_name, &len, NULL, NUL= L, NULL, NULL); if (status =3D=3D ERROR_NO_MORE_ITEMS) { break; } else if (status !=3D ERROR_SUCCESS) { - msg(M_FATAL, "Error enumerating registry subkeys of key: %s", - ADAPTER_KEY); + msg(M_FATAL, "Error enumerating registry subkeys of key: %s", = ADAPTER_KEY); } - snprintf(unit_string, sizeof(unit_string), "%s\\%s", - ADAPTER_KEY, enum_name); + snprintf(unit_string, sizeof(unit_string), "%s\\%s", ADAPTER_KEY, = enum_name); - status =3D RegOpenKeyEx( - HKEY_LOCAL_MACHINE, - unit_string, - 0, - KEY_READ, - &unit_key); + status =3D RegOpenKeyEx(HKEY_LOCAL_MACHINE, unit_string, 0, KEY_RE= AD, &unit_key); if (status !=3D ERROR_SUCCESS) { @@ -3940,29 +3773,19 @@ else { len =3D sizeof(component_id); - status =3D RegQueryValueEx( - unit_key, - component_id_string, - NULL, - &data_type, - (LPBYTE)component_id, - &len); + status =3D RegQueryValueEx(unit_key, component_id_string, NULL= , &data_type, + (LPBYTE)component_id, &len); if (status !=3D ERROR_SUCCESS || data_type !=3D REG_SZ) { - dmsg(D_REGISTRY, "Error opening registry key: %s\\%s", - unit_string, component_id_string); + dmsg(D_REGISTRY, "Error opening registry key: %s\\%s", uni= t_string, + component_id_string); } else { len =3D sizeof(net_cfg_instance_id); - status =3D RegQueryValueEx( - unit_key, - net_cfg_instance_id_string, - NULL, - &data_type, - net_cfg_instance_id, - &len); + status =3D RegQueryValueEx(unit_key, net_cfg_instance_id_s= tring, NULL, &data_type, + net_cfg_instance_id, &len); if (status =3D=3D ERROR_SUCCESS && data_type =3D=3D REG_SZ) { @@ -3996,8 +3819,8 @@ } last =3D reg; - msg(D_TAP_WIN_DEBUG, "NetCfgInstanceId: %s, Driver= : %s", - reg->guid, print_tun_backend_driver(reg->windo= ws_driver)); + msg(D_TAP_WIN_DEBUG, "NetCfgInstanceId: %s, Driver= : %s", reg->guid, + print_tun_backend_driver(reg->windows_driver)); } } } @@ -4020,12 +3843,8 @@ struct panel_reg *last =3D NULL; int i =3D 0; - status =3D RegOpenKeyEx( - HKEY_LOCAL_MACHINE, - NETWORK_CONNECTIONS_KEY, - 0, - KEY_READ, - &network_connections_key); + status =3D RegOpenKeyEx(HKEY_LOCAL_MACHINE, NETWORK_CONNECTIONS_KEY, 0= , KEY_READ, + &network_connections_key); if (status !=3D ERROR_SUCCESS) { @@ -4042,35 +3861,20 @@ const WCHAR name_string[] =3D L"Name"; len =3D sizeof(enum_name); - status =3D RegEnumKeyEx( - network_connections_key, - i, - enum_name, - &len, - NULL, - NULL, - NULL, - NULL); + status =3D RegEnumKeyEx(network_connections_key, i, enum_name, &le= n, NULL, NULL, NULL, NULL); if (status =3D=3D ERROR_NO_MORE_ITEMS) { break; } else if (status !=3D ERROR_SUCCESS) { - msg(M_FATAL, "Error enumerating registry subkeys of key: %s", - NETWORK_CONNECTIONS_KEY); + msg(M_FATAL, "Error enumerating registry subkeys of key: %s", = NETWORK_CONNECTIONS_KEY); } - snprintf(connection_string, sizeof(connection_string), - "%s\\%s\\Connection", + snprintf(connection_string, sizeof(connection_string), "%s\\%s\\Co= nnection", NETWORK_CONNECTIONS_KEY, enum_name); - status =3D RegOpenKeyEx( - HKEY_LOCAL_MACHINE, - connection_string, - 0, - KEY_READ, - &connection_key); + status =3D RegOpenKeyEx(HKEY_LOCAL_MACHINE, connection_string, 0, = KEY_READ, &connection_key); if (status !=3D ERROR_SUCCESS) { @@ -4079,18 +3883,13 @@ else { len =3D sizeof(name_data); - status =3D RegQueryValueExW( - connection_key, - name_string, - NULL, - &name_type, - (LPBYTE) name_data, - &len); + status =3D RegQueryValueExW(connection_key, name_string, NULL,= &name_type, + (LPBYTE)name_data, &len); if (status !=3D ERROR_SUCCESS || name_type !=3D REG_SZ) { - dmsg(D_REGISTRY, "Error opening registry key: %s\\%s\\%ls", - NETWORK_CONNECTIONS_KEY, connection_string, name_stri= ng); + dmsg(D_REGISTRY, "Error opening registry key: %s\\%s\\%ls"= , NETWORK_CONNECTIONS_KEY, + connection_string, name_string); } else { @@ -4143,15 +3942,14 @@ } if ((local & (~mask)) !=3D (remote & (~mask))) { - err =3D "must exist within the same 255.255.255.252 subnet. This = is a limitation of --dev tun when used with the TAP-WIN32 driver"; + err =3D + "must exist within the same 255.255.255.252 subnet. This is a= limitation of --dev tun when used with the TAP-WIN32 driver"; goto error; } - if ((local & mask) =3D=3D 0 - || (local & mask) =3D=3D 3 - || (remote & mask) =3D=3D 0 - || (remote & mask) =3D=3D 3) + if ((local & mask) =3D=3D 0 || (local & mask) =3D=3D 3 || (remote & ma= sk) =3D=3D 0 || (remote & mask) =3D=3D 3) { - err =3D "cannot use the first or last address within a given 255.2= 55.255.252 subnet. This is a limitation of --dev tun when used with the TA= P-WIN32 driver"; + err =3D + "cannot use the first or last address within a given 255.255.2= 55.252 subnet. This is a limitation of --dev tun when used with the TAP-WI= N32 driver"; goto error; } @@ -4159,10 +3957,10 @@ return; error: - msg(M_FATAL, "There is a problem in your selection of --ifconfig endpo= ints [local=3D%s, remote=3D%s]. The local and remote VPN endpoints %s. Tr= y '" PACKAGE " --show-valid-subnets' option for more info.", - print_in_addr_t(local, 0, &gc), - print_in_addr_t(remote, 0, &gc), - err); + msg(M_FATAL, + "There is a problem in your selection of --ifconfig endpoints [loc= al=3D%s, remote=3D%s]. The local and remote VPN endpoints %s. Try '" PACK= AGE + " --show-valid-subnets' option for more info.", + print_in_addr_t(local, 0, &gc), print_in_addr_t(remote, 0, &gc), e= rr); gc_free(&gc); } @@ -4186,7 +3984,7 @@ for (i =3D 0; i < 256; i +=3D 4) { - printf("[%3d,%3d] ", i+1, i+2); + printf("[%3d,%3d] ", i + 1, i + 2); if (++col > 4) { col =3D 0; @@ -4229,7 +4027,8 @@ { if (!strcmp(tr->guid, pr->guid)) { - msg(msglev, "'%s' %s %s", pr->name, tr->guid, print_tun_ba= ckend_driver(tr->windows_driver)); + msg(msglev, "'%s' %s %s", pr->name, tr->guid, + print_tun_backend_driver(tr->windows_driver)); ++links; } } @@ -4267,12 +4066,14 @@ =20 if (warn_panel_dup) { - msg(warnlev, "WARNING: Some TAP-Windows adapters have duplicate li= nks from the Network Connections control panel"); + msg(warnlev, + "WARNING: Some TAP-Windows adapters have duplicate links from = the Network Connections control panel"); } if (warn_panel_null) { - msg(warnlev, "WARNING: Some TAP-Windows adapters have no link from= the Network Connections control panel"); + msg(warnlev, + "WARNING: Some TAP-Windows adapters have no link from the Netw= ork Connections control panel"); } gc_free(&gc); @@ -4314,7 +4115,8 @@ } static const struct tap_reg * -get_adapter_by_name(const char *name, const struct tap_reg *tap_reg, const= struct panel_reg *panel_reg) +get_adapter_by_name(const char *name, const struct tap_reg *tap_reg, + const struct panel_reg *panel_reg) { const struct panel_reg *pr; @@ -4335,8 +4137,8 @@ if (!tap_reg) { msg(M_FATAL, "There are no TAP-Windows or ovpn-dco adapters " - "on this system. You should be able to create an adapter " - "by using tapctl.exe utility."); + "on this system. You should be able to create an ada= pter " + "by using tapctl.exe utility."); } } @@ -4345,13 +4147,10 @@ * registry for the TAP device # =3D device_number. */ static const char * -get_unspecified_device_guid(const int device_number, - uint8_t *actual_name, - int actual_name_size, +get_unspecified_device_guid(const int device_number, uint8_t *actual_name,= int actual_name_size, const struct tap_reg *tap_reg_src, const struct panel_reg *panel_reg_src, - enum tun_driver_type *windows_driver, - struct gc_arena *gc) + enum tun_driver_type *windows_driver, struct g= c_arena *gc) { const struct tap_reg *tap_reg =3D tap_reg_src; struct buffer actual =3D clear_buf(); @@ -4411,13 +4210,9 @@ * returning the GUID and optional actual_name and device type */ static const char * -get_device_guid(const char *name, - uint8_t *actual_name, - int actual_name_size, - enum tun_driver_type *windows_driver, - const struct tap_reg *tap_reg, - const struct panel_reg *panel_reg, - struct gc_arena *gc) +get_device_guid(const char *name, uint8_t *actual_name, int actual_name_si= ze, + enum tun_driver_type *windows_driver, const struct tap_reg= *tap_reg, + const struct panel_reg *panel_reg, struct gc_arena *gc) { struct buffer ret =3D alloc_buf_gc(256, gc); struct buffer actual =3D clear_buf(); @@ -4487,17 +4282,15 @@ if ((status =3D GetAdaptersInfo(NULL, &size)) !=3D ERROR_BUFFER_OVERFL= OW) { - msg(M_INFO, "GetAdaptersInfo #1 failed (status=3D%u) : %s", - (unsigned int)status, + msg(M_INFO, "GetAdaptersInfo #1 failed (status=3D%u) : %s", (unsig= ned int)status, strerror_win32(status, gc)); } else { - pi =3D (PIP_ADAPTER_INFO) gc_malloc(size, false, gc); + pi =3D (PIP_ADAPTER_INFO)gc_malloc(size, false, gc); if ((status =3D GetAdaptersInfo(pi, &size)) !=3D NO_ERROR) { - msg(M_INFO, "GetAdaptersInfo #2 failed (status=3D%u) : %s", - (unsigned int)status, + msg(M_INFO, "GetAdaptersInfo #2 failed (status=3D%u) : %s", (u= nsigned int)status, strerror_win32(status, gc)); pi =3D NULL; } @@ -4516,21 +4309,19 @@ { if ((status =3D GetPerAdapterInfo(index, NULL, &size)) !=3D ERROR_= BUFFER_OVERFLOW) { - msg(M_INFO, "GetPerAdapterInfo #1 failed (status=3D%u) : %s", - (unsigned int)status, + msg(M_INFO, "GetPerAdapterInfo #1 failed (status=3D%u) : %s", = (unsigned int)status, strerror_win32(status, gc)); } else { - pi =3D (PIP_PER_ADAPTER_INFO) gc_malloc(size, false, gc); + pi =3D (PIP_PER_ADAPTER_INFO)gc_malloc(size, false, gc); if ((status =3D GetPerAdapterInfo((ULONG)index, pi, &size)) = =3D=3D ERROR_SUCCESS) { return pi; } else { - msg(M_INFO, "GetPerAdapterInfo #2 failed (status=3D%u) : %= s", - (unsigned int)status, + msg(M_INFO, "GetPerAdapterInfo #2 failed (status=3D%u) : %= s", (unsigned int)status, strerror_win32(status, gc)); } } @@ -4547,21 +4338,19 @@ if ((status =3D GetInterfaceInfo(NULL, &size)) !=3D ERROR_INSUFFICIENT= _BUFFER) { - msg(M_INFO, "GetInterfaceInfo #1 failed (status=3D%u) : %s", - (unsigned int)status, + msg(M_INFO, "GetInterfaceInfo #1 failed (status=3D%u) : %s", (unsi= gned int)status, strerror_win32(status, gc)); } else { - ii =3D (PIP_INTERFACE_INFO) gc_malloc(size, false, gc); + ii =3D (PIP_INTERFACE_INFO)gc_malloc(size, false, gc); if ((status =3D GetInterfaceInfo(ii, &size)) =3D=3D NO_ERROR) { return ii; } else { - msg(M_INFO, "GetInterfaceInfo #2 failed (status=3D%u) : %s", - (unsigned int)status, + msg(M_INFO, "GetInterfaceInfo #2 failed (status=3D%u) : %s", (= unsigned int)status, strerror_win32(status, gc)); } } @@ -4749,7 +4538,6 @@ else { ret =3D true; /* this can occur when TAP adapter is bridged */ - } return ret; } @@ -4773,7 +4561,8 @@ in_addr_t adapter_ip, adapter_netmask; if (get_adapter_ip_netmask(ai, i, &adapter_ip, &adapter_netmas= k)) { - if (adapter_ip && adapter_netmask && (ip & adapter_netmask= ) =3D=3D (adapter_ip & adapter_netmask)) + if (adapter_ip && adapter_netmask + && (ip & adapter_netmask) =3D=3D (adapter_ip & adapter= _netmask)) { if (highest_netmask && adapter_netmask > *highest_netm= ask) { @@ -4788,10 +4577,7 @@ } DWORD -adapter_index_of_ip(const IP_ADAPTER_INFO *list, - const in_addr_t ip, - int *count, - in_addr_t *netmask) +adapter_index_of_ip(const IP_ADAPTER_INFO *list, const in_addr_t ip, int *= count, in_addr_t *netmask) { struct gc_arena gc =3D gc_new(); DWORD ret =3D TUN_ADAPTER_INDEX_INVALID; @@ -4842,11 +4628,8 @@ } dmsg(D_ROUTE_DEBUG, "DEBUG: IP Locate: ip=3D%s nm=3D%s index=3D%d coun= t=3D%d metric=3D%d", - print_in_addr_t(ip, 0, &gc), - print_in_addr_t(highest_netmask, 0, &gc), - (int)ret, - count ? *count : -1, - lowest_metric); + print_in_addr_t(ip, 0, &gc), print_in_addr_t(highest_netmask, 0, = &gc), (int)ret, + count ? *count : -1, lowest_metric); if (ret =3D=3D TUN_ADAPTER_INDEX_INVALID && count) { @@ -4867,9 +4650,9 @@ * is DHCP disabled. */ -#define DHCP_STATUS_UNDEF 0 -#define DHCP_STATUS_ENABLED 1 -#define DHCP_STATUS_DISABLED 2 +#define DHCP_STATUS_UNDEF 0 +#define DHCP_STATUS_ENABLED 1 +#define DHCP_STATUS_DISABLED 2 static int dhcp_status(DWORD index) @@ -4914,22 +4697,19 @@ DWORD status; const DWORD context =3D ip->Context; - if ((status =3D DeleteIPAddress((ULONG) context)) =3D=3D NO_ER= ROR) + if ((status =3D DeleteIPAddress((ULONG)context)) =3D=3D NO_ERR= OR) { msg(M_INFO, "Successfully deleted previously set dynamic I= P/netmask: %s/%s", - ip->IpAddress.String, - ip->IpMask.String); + ip->IpAddress.String, ip->IpMask.String); } else { const char *empty =3D "0.0.0.0"; - if (strcmp(ip->IpAddress.String, empty) - || strcmp(ip->IpMask.String, empty)) + if (strcmp(ip->IpAddress.String, empty) || strcmp(ip->IpMa= sk.String, empty)) { - msg(M_INFO, "NOTE: could not delete previously set dyn= amic IP/netmask: %s/%s (status=3D%u)", - ip->IpAddress.String, - ip->IpMask.String, - (unsigned int)status); + msg(M_INFO, + "NOTE: could not delete previously set dynamic IP/= netmask: %s/%s (status=3D%u)", + ip->IpAddress.String, ip->IpMask.String, (unsigned= int)status); } } ip =3D ip->Next; @@ -5099,7 +4879,7 @@ } else { - msg(M_INFO|M_NOPREFIX, "TAP-Windows device: %s [Non-admin access a= llowed]", device_path); + msg(M_INFO | M_NOPREFIX, "TAP-Windows device: %s [Non-admin access= allowed]", device_path); } } @@ -5119,7 +4899,8 @@ if (dev_node) { /* Get the device GUID for the device specified with --dev-node. */ - device_guid =3D get_device_guid(dev_node, actual_buffer, sizeof(ac= tual_buffer), NULL, tap_reg, panel_reg, &gc); + device_guid =3D get_device_guid(dev_node, actual_buffer, sizeof(ac= tual_buffer), NULL, tap_reg, + panel_reg, &gc); if (!device_guid) { @@ -5127,20 +4908,11 @@ } /* Open Windows TAP-Windows adapter */ - snprintf(device_path, sizeof(device_path), "%s%s%s", - USERMODEDEVICEDIR, - device_guid, + snprintf(device_path, sizeof(device_path), "%s%s%s", USERMODEDEVIC= EDIR, device_guid, TAP_WIN_SUFFIX); - hand =3D CreateFile( - device_path, - MAXIMUM_ALLOWED, - 0, /* was: FILE_SHARE_READ */ - 0, - OPEN_EXISTING, - FILE_ATTRIBUTE_SYSTEM | FILE_FLAG_OVERLAPPED, - 0 - ); + hand =3D CreateFile(device_path, MAXIMUM_ALLOWED, 0, /* was: FILE_= SHARE_READ */ + 0, OPEN_EXISTING, FILE_ATTRIBUTE_SYSTEM | FILE_F= LAG_OVERLAPPED, 0); if (hand =3D=3D INVALID_HANDLE_VALUE) { @@ -5157,13 +4929,8 @@ /* Try opening all TAP devices */ while (true) { - device_guid =3D get_unspecified_device_guid(device_number, - actual_buffer, - sizeof(actual_buffer= ), - tap_reg, - panel_reg, - NULL, - &gc); + device_guid =3D get_unspecified_device_guid( + device_number, actual_buffer, sizeof(actual_buffer), tap_r= eg, panel_reg, NULL, &gc); if (!device_guid) { @@ -5171,20 +4938,11 @@ } /* Open Windows TAP-Windows adapter */ - snprintf(device_path, sizeof(device_path), "%s%s%s", - USERMODEDEVICEDIR, - device_guid, + snprintf(device_path, sizeof(device_path), "%s%s%s", USERMODED= EVICEDIR, device_guid, TAP_WIN_SUFFIX); - hand =3D CreateFile( - device_path, - MAXIMUM_ALLOWED, - 0, /* was: FILE_SHARE_READ */ - 0, - OPEN_EXISTING, - FILE_ATTRIBUTE_SYSTEM | FILE_FLAG_OVERLAPPED, - 0 - ); + hand =3D CreateFile(device_path, MAXIMUM_ALLOWED, 0, /* was: F= ILE_SHARE_READ */ + 0, OPEN_EXISTING, FILE_ATTRIBUTE_SYSTEM | FI= LE_FLAG_OVERLAPPED, 0); if (hand =3D=3D INVALID_HANDLE_VALUE) { @@ -5222,9 +4980,9 @@ } else { - msg(M_WARN, "NOTE: Release of DHCP-assigned IP address lease o= n TAP-Windows adapter failed: %s (code=3D%u)", - strerror_win32(status, &gc), - (unsigned int)status); + msg(M_WARN, + "NOTE: Release of DHCP-assigned IP address lease on TAP-Wi= ndows adapter failed: %s (code=3D%u)", + strerror_win32(status, &gc), (unsigned int)status); } } @@ -5235,7 +4993,8 @@ static bool dhcp_release(const struct tuntap *tt) { - if (tt && tt->options.ip_win32_type =3D=3D IPW32_SET_DHCP_MASQ && tt->= adapter_index !=3D TUN_ADAPTER_INDEX_INVALID) + if (tt && tt->options.ip_win32_type =3D=3D IPW32_SET_DHCP_MASQ + && tt->adapter_index !=3D TUN_ADAPTER_INDEX_INVALID) { return dhcp_release_by_adapter_index(tt->adapter_index); } @@ -5262,9 +5021,9 @@ } else { - msg(M_WARN, "WARNING: Failed to renew DHCP IP address lease on= TAP-Windows adapter: %s (code=3D%u)", - strerror_win32(status, &gc), - (unsigned int)status); + msg(M_WARN, + "WARNING: Failed to renew DHCP IP address lease on TAP-Win= dows adapter: %s (code=3D%u)", + strerror_win32(status, &gc), (unsigned int)status); } } gc_free(&gc); @@ -5274,7 +5033,8 @@ static bool dhcp_renew(const struct tuntap *tt) { - if (tt && tt->options.ip_win32_type =3D=3D IPW32_SET_DHCP_MASQ && tt->= adapter_index !=3D TUN_ADAPTER_INDEX_INVALID) + if (tt && tt->options.ip_win32_type =3D=3D IPW32_SET_DHCP_MASQ + && tt->adapter_index !=3D TUN_ADAPTER_INDEX_INVALID) { return dhcp_renew_by_adapter_index(tt->adapter_index); } @@ -5320,15 +5080,11 @@ msg(D_TUNTAP_INFO, "Start ipconfig commands for register-dns..."); netcmd_semaphore_lock(); - argv_printf(&argv, "%s%s /flushdns", - get_win_sys_path(), - WIN_IPCONFIG_PATH_SUFFIX); + argv_printf(&argv, "%s%s /flushdns", get_win_sys_path(), WIN_IPCONFIG_= PATH_SUFFIX); argv_msg(D_TUNTAP_INFO, &argv); openvpn_execve_check(&argv, es, 0, err); - argv_printf(&argv, "%s%s /registerdns", - get_win_sys_path(), - WIN_IPCONFIG_PATH_SUFFIX); + argv_printf(&argv, "%s%s /registerdns", get_win_sys_path(), WIN_IPCONF= IG_PATH_SUFFIX); argv_msg(D_TUNTAP_INFO, &argv); openvpn_execve_check(&argv, es, 0, err); argv_free(&argv); @@ -5429,34 +5185,28 @@ * are cleared first. */ static void -netsh_set_dns6_servers(const struct in6_addr *addr_list, - const int addr_len, - DWORD adapter_index) +netsh_set_dns6_servers(const struct in6_addr *addr_list, const int addr_le= n, DWORD adapter_index) { struct gc_arena gc =3D gc_new(); struct argv argv =3D argv_new(); /* delete existing DNS settings from TAP interface */ - argv_printf(&argv, "%s%s interface ipv6 delete dns %lu all", - get_win_sys_path(), - NETSH_PATH_SUFFIX, - adapter_index); + argv_printf(&argv, "%s%s interface ipv6 delete dns %lu all", get_win_s= ys_path(), + NETSH_PATH_SUFFIX, adapter_index); netsh_command(&argv, 2, M_FATAL); for (int i =3D 0; i < addr_len; ++i) { - const char *fmt =3D (i =3D=3D 0) ? - "%s%s interface ipv6 set dns %lu static %s" - : "%s%s interface ipv6 add dns %lu %s"; - argv_printf(&argv, fmt, get_win_sys_path(), - NETSH_PATH_SUFFIX, adapter_index, + const char *fmt =3D (i =3D=3D 0) ? "%s%s interface ipv6 set dns %l= u static %s" + : "%s%s interface ipv6 add dns %lu %s"; + argv_printf(&argv, fmt, get_win_sys_path(), NETSH_PATH_SUFFIX, ada= pter_index, print_in6_addr(addr_list[i], 0, &gc)); /* disable slow address validation */ argv_printf_cat(&argv, "%s", "validate=3Dno"); /* Treat errors while adding as non-fatal as we do not check for d= uplicates */ - netsh_command(&argv, 1, (i=3D=3D0) ? M_FATAL : M_NONFATAL); + netsh_command(&argv, 1, (i =3D=3D 0) ? M_FATAL : M_NONFATAL); } argv_free(&argv); @@ -5464,12 +5214,8 @@ } static void -netsh_ifconfig_options(const char *type, - const in_addr_t *addr_list, - const int addr_len, - const IP_ADDR_STRING *current, - DWORD adapter_index, - const bool test_first) +netsh_ifconfig_options(const char *type, const in_addr_t *addr_list, const= int addr_len, + const IP_ADDR_STRING *current, DWORD adapter_index,= const bool test_first) { struct gc_arena gc =3D gc_new(); struct argv argv =3D argv_new(); @@ -5492,11 +5238,8 @@ /* delete existing DNS/WINS settings from TAP interface */ if (delete_first) { - argv_printf(&argv, "%s%s interface ip delete %s %lu all", - get_win_sys_path(), - NETSH_PATH_SUFFIX, - type, - adapter_index); + argv_printf(&argv, "%s%s interface ip delete %s %lu all", get_win_= sys_path(), + NETSH_PATH_SUFFIX, type, adapter_index); netsh_command(&argv, 2, M_FATAL); } @@ -5508,15 +5251,10 @@ { if (delete_first || !test_first || !ip_addr_member_of(addr_lis= t[i], current)) { - const char *fmt =3D count ? - "%s%s interface ip add %s %lu %s" - : "%s%s interface ip set %s %lu static %= s"; + const char *fmt =3D count ? "%s%s interface ip add %s %lu = %s" + : "%s%s interface ip set %s %lu st= atic %s"; - argv_printf(&argv, fmt, - get_win_sys_path(), - NETSH_PATH_SUFFIX, - type, - adapter_index, + argv_printf(&argv, fmt, get_win_sys_path(), NETSH_PATH_SUF= FIX, type, adapter_index, print_in_addr_t(addr_list[i], 0, &gc)); /* disable slow address validation for DNS */ @@ -5531,9 +5269,7 @@ } else { - msg(M_INFO, "NETSH: %lu %s %s [already set]", - adapter_index, - type, + msg(M_INFO, "NETSH: %lu %s %s [already set]", adapter_inde= x, type, print_in_addr_t(addr_list[i], 0, &gc)); } } @@ -5562,11 +5298,8 @@ } static void -netsh_ifconfig(const struct tuntap_options *to, - DWORD adapter_index, - const in_addr_t ip, - const in_addr_t netmask, - const unsigned int flags) +netsh_ifconfig(const struct tuntap_options *to, DWORD adapter_index, const= in_addr_t ip, + const in_addr_t netmask, const unsigned int flags) { struct gc_arena gc =3D gc_new(); struct argv argv =3D argv_new(); @@ -5584,19 +5317,14 @@ { if (test_adapter_ip_netmask(ai, ip, netmask)) { - msg(M_INFO, "NETSH: %lu %s/%s [already set]", - adapter_index, - print_in_addr_t(ip, 0, &gc), - print_in_addr_t(netmask, 0, &gc)); + msg(M_INFO, "NETSH: %lu %s/%s [already set]", adapter_index, + print_in_addr_t(ip, 0, &gc), print_in_addr_t(netmask, 0, &= gc)); } else { /* example: netsh interface ip set address 42 static 10.3.0.1 = 255.255.255.0 */ - argv_printf(&argv, "%s%s interface ip set address %lu static %= s %s", - get_win_sys_path(), - NETSH_PATH_SUFFIX, - adapter_index, - print_in_addr_t(ip, 0, &gc), + argv_printf(&argv, "%s%s interface ip set address %lu static %= s %s", get_win_sys_path(), + NETSH_PATH_SUFFIX, adapter_index, print_in_addr_t(= ip, 0, &gc), print_in_addr_t(netmask, 0, &gc)); netsh_command(&argv, 4, M_FATAL); @@ -5610,22 +5338,14 @@ CLEAR(wins[0]); CLEAR(wins[1]); - netsh_ifconfig_options("dns", - to->dns, - to->dns_len, - pai ? &pai->DnsServerList : NULL, - adapter_index, - BOOL_CAST(flags & NI_TEST_FIRST)); + netsh_ifconfig_options("dns", to->dns, to->dns_len, pai ? &pai->Dn= sServerList : NULL, + adapter_index, BOOL_CAST(flags & NI_TEST_FI= RST)); if (ai && ai->HaveWins) { init_ip_addr_string2(wins, &ai->PrimaryWinsServer, &ai->Second= aryWinsServer); } - netsh_ifconfig_options("wins", - to->wins, - to->wins_len, - ai ? wins : NULL, - adapter_index, + netsh_ifconfig_options("wins", to->wins, to->wins_len, ai ? wins := NULL, adapter_index, BOOL_CAST(flags & NI_TEST_FIRST)); } @@ -5639,11 +5359,8 @@ struct argv argv =3D argv_new(); /* example: netsh interface ip set address 42 dhcp */ - argv_printf(&argv, - "%s%s interface ip set address %lu dhcp", - get_win_sys_path(), - NETSH_PATH_SUFFIX, - adapter_index); + argv_printf(&argv, "%s%s interface ip set address %lu dhcp", get_win_s= ys_path(), + NETSH_PATH_SUFFIX, adapter_index); netsh_command(&argv, 4, M_FATAL); @@ -5659,14 +5376,8 @@ struct gc_arena gc =3D gc_new(); HANDLE pipe =3D tt->options.msg_channel; - enable_dhcp_message_t dhcp =3D { - .header =3D { - msg_enable_dhcp, - sizeof(enable_dhcp_message_t), - 0 - }, - .iface =3D { .index =3D tt->adapter_index, .name =3D "" } - }; + enable_dhcp_message_t dhcp =3D { .header =3D { msg_enable_dhcp, sizeof= (enable_dhcp_message_t), 0 }, + .iface =3D { .index =3D tt->adapter_ind= ex, .name =3D "" } }; if (!send_msg_iservice(pipe, &dhcp, sizeof(dhcp), &ack, "Enable_dhcp")) { @@ -5690,8 +5401,7 @@ } static void -windows_set_mtu(const int iface_index, const short family, - const int mtu) +windows_set_mtu(const int iface_index, const short family, const int mtu) { DWORD err =3D 0; struct gc_arena gc =3D gc_new(); @@ -5702,7 +5412,8 @@ ipiface.InterfaceIndex =3D iface_index; if (family =3D=3D AF_INET6 && mtu < 1280) { - msg(M_INFO, "NOTE: IPv6 interface MTU < 1280 conflicts with IETF s= tandards and might not work"); + msg(M_INFO, + "NOTE: IPv6 interface MTU < 1280 conflicts with IETF standards= and might not work"); } err =3D GetIpInterfaceEntry(&ipiface); @@ -5718,12 +5429,13 @@ if (err !=3D NO_ERROR) { - msg(M_WARN, "TUN: Setting %s mtu failed: %s [status=3D%lu if_index= =3D%d]", - family_name, strerror_win32(err, &gc), err, iface_index); + msg(M_WARN, "TUN: Setting %s mtu failed: %s [status=3D%lu if_index= =3D%d]", family_name, + strerror_win32(err, &gc), err, iface_index); } else { - msg(M_INFO, "%s MTU set to %d on interface %d using SetIpInterface= Entry()", family_name, mtu, iface_index); + msg(M_INFO, "%s MTU set to %d on interface %d using SetIpInterface= Entry()", family_name, + mtu, iface_index); } } @@ -5743,13 +5455,16 @@ if (dev_node) { - guid =3D get_device_guid(dev_node, BPTR(&actual), BCAP(&actual), N= ULL, tap_reg, panel_reg, gc); + guid =3D + get_device_guid(dev_node, BPTR(&actual), BCAP(&actual), NULL, = tap_reg, panel_reg, gc); } else { - guid =3D get_unspecified_device_guid(0, BPTR(&actual), BCAP(&actua= l), tap_reg, panel_reg, NULL, gc); + guid =3D get_unspecified_device_guid(0, BPTR(&actual), BCAP(&actua= l), tap_reg, panel_reg, + NULL, gc); - if (get_unspecified_device_guid(1, NULL, 0, tap_reg, panel_reg, NU= LL, gc)) /* ambiguous if more than one TAP-Windows adapter */ + if (get_unspecified_device_guid(1, NULL, 0, tap_reg, panel_reg, NU= LL, + gc)) /* ambiguous if more than one= TAP-Windows adapter */ { guid =3D NULL; } @@ -5757,7 +5472,7 @@ if (!guid) { - return "NULL"; /* not found */ + return "NULL"; /* not found */ } else if (strcmp(BSTR(&actual), "NULL")) { @@ -5765,7 +5480,7 @@ } else { - return guid; /* no control panel name, return GUID instead */ + return guid; /* no control panel name, return GUID instead */ } } @@ -5788,13 +5503,10 @@ if (tt->standby_iter =3D=3D IPW32_SET_ADAPTIVE_TRY_NETSH) { msg(M_INFO, "NOTE: now trying netsh (this may take some time)"= ); - netsh_ifconfig(&tt->options, - tt->adapter_index, - tt->local, - tt->adapter_netmask, - NI_TEST_FIRST|NI_IP_NETMASK|NI_OPTIONS); + netsh_ifconfig(&tt->options, tt->adapter_index, tt->local, tt-= >adapter_netmask, + NI_TEST_FIRST | NI_IP_NETMASK | NI_OPTIONS); } - else if (tt->standby_iter >=3D IPW32_SET_ADAPTIVE_TRY_NETSH*2) + else if (tt->standby_iter >=3D IPW32_SET_ADAPTIVE_TRY_NETSH * 2) { ret =3D false; } @@ -5822,7 +5534,8 @@ } static void -write_dhcp_u32_array(struct buffer *buf, const int type, const uint32_t *d= ata, const unsigned int len, bool *error) +write_dhcp_u32_array(struct buffer *buf, const int type, const uint32_t *d= ata, + const unsigned int len, bool *error) { if (len > 0) { @@ -5890,7 +5603,7 @@ for (i =3D 0; i < array_len; i++) { - const char *ptr =3D str_array[i]; + const char *ptr =3D str_array[i]; if (strlen(ptr) + len + 1 > sizeof(tmp_buf)) { @@ -5909,7 +5622,7 @@ { if (*ptr =3D=3D '.' || *ptr =3D=3D '\0') { - tmp_buf[label_length_pos] =3D (len-label_length_pos)-1; + tmp_buf[label_length_pos] =3D (len - label_length_pos) - 1; label_length_pos =3D len; if (*ptr =3D=3D '\0') { @@ -5966,9 +5679,7 @@ if (o->domain_search_list_len > 0) { - write_dhcp_search_str(buf, 119, o->domain_search_list, - o->domain_search_list_len, - &error); + write_dhcp_search_str(buf, 119, o->domain_search_list, o->domain_s= earch_list_len, &error); } /* the MS DHCP server option 'Disable Netbios-over-TCP/IP @@ -5981,10 +5692,10 @@ msg(M_WARN, "build_dhcp_options_string: buffer overflow buildi= ng DHCP options"); return false; } - buf_write_u8(buf, 43); - buf_write_u8(buf, 6);/* total length field */ - buf_write_u8(buf, 0x001); - buf_write_u8(buf, 4);/* length of the vendor specified field */ + buf_write_u8(buf, 43); + buf_write_u8(buf, 6); /* total length field */ + buf_write_u8(buf, 0x001); + buf_write_u8(buf, 4); /* length of the vendor specified field */ buf_write_u32(buf, 0x002); } return !error; @@ -6081,7 +5792,9 @@ if (dsa =3D=3D local) { - msg(M_FATAL, "ERROR: There is a clash between the --ifconfig local= address and the internal DHCP server address -- both are set to %s -- plea= se use the --ip-win32 dynamic option to choose a different free address fro= m the --ifconfig subnet for the internal DHCP server", print_in_addr_t(dsa,= 0, &gc)); + msg(M_FATAL, + "ERROR: There is a clash between the --ifconfig local address = and the internal DHCP server address -- both are set to %s -- please use th= e --ip-win32 dynamic option to choose a different free address from the --i= fconfig subnet for the internal DHCP server", + print_in_addr_t(dsa, 0, &gc)); } if ((local & netmask) !=3D (dsa & netmask)) @@ -6099,38 +5812,38 @@ ULONG info[3]; DWORD len; CLEAR(info); - if (DeviceIoControl(tt->hand, TAP_WIN_IOCTL_GET_VERSION, - &info, sizeof(info), - &info, sizeof(info), &len, NULL)) + if (DeviceIoControl(tt->hand, TAP_WIN_IOCTL_GET_VERSION, &info, sizeof= (info), &info, + sizeof(info), &len, NULL)) { - msg(D_TUNTAP_INFO, "TAP-Windows Driver Version %d.%d %s", - (int)info[0], - (int)info[1], + msg(D_TUNTAP_INFO, "TAP-Windows Driver Version %d.%d %s", (int)inf= o[0], (int)info[1], (info[2] ? "(DEBUG)" : "")); - } if (!(info[0] =3D=3D TAP_WIN_MIN_MAJOR && info[1] >=3D TAP_WIN_MIN_MIN= OR)) { - msg(M_FATAL, "ERROR: This version of " PACKAGE_NAME " requires a = TAP-Windows driver that is at least version %d.%d -- If you recently upgrad= ed your " PACKAGE_NAME " distribution, a reboot is probably required at thi= s point to get Windows to see the new driver.", - TAP_WIN_MIN_MAJOR, - TAP_WIN_MIN_MINOR); + msg(M_FATAL, + "ERROR: This version of " PACKAGE_NAME + " requires a TAP-Windows driver that is at least version %d.%d= -- If you recently upgraded your " PACKAGE_NAME + " distribution, a reboot is probably required at this point to= get Windows to see the new driver.", + TAP_WIN_MIN_MAJOR, TAP_WIN_MIN_MINOR); } /* usage of numeric constants is ugly, but this is really tied to * *this* version of the driver */ - if (tt->type =3D=3D DEV_TYPE_TUN - && info[0] =3D=3D 9 && info[1] < 8) + if (tt->type =3D=3D DEV_TYPE_TUN && info[0] =3D=3D 9 && info[1] < 8) { - msg(M_INFO, "WARNING: Tap-Win32 driver version %d.%d does not sup= port IPv6 in TUN mode. IPv6 will not work. Upgrade your Tap-Win32 driver.",= (int)info[0], (int)info[1]); + msg(M_INFO, + "WARNING: Tap-Win32 driver version %d.%d does not support IPv= 6 in TUN mode. IPv6 will not work. Upgrade your Tap-Win32 driver.", + (int)info[0], (int)info[1]); } /* tap driver 9.8 (2.2.0 and 2.2.1 release) is buggy */ - if (tt->type =3D=3D DEV_TYPE_TUN - && info[0] =3D=3D 9 && info[1] =3D=3D 8) + if (tt->type =3D=3D DEV_TYPE_TUN && info[0] =3D=3D 9 && info[1] =3D=3D= 8) { - msg(M_FATAL, "ERROR: Tap-Win32 driver version %d.%d is buggy rega= rding small IPv4 packets in TUN mode. Upgrade your Tap-Win32 driver.", (int= )info[0], (int)info[1]); + msg(M_FATAL, + "ERROR: Tap-Win32 driver version %d.%d is buggy regarding sma= ll IPv4 packets in TUN mode. Upgrade your Tap-Win32 driver.", + (int)info[0], (int)info[1]); } } @@ -6139,43 +5852,33 @@ { ULONG mtu =3D 0; DWORD len; - if (DeviceIoControl(tt->hand, TAP_WIN_IOCTL_GET_MTU, - &mtu, sizeof(mtu), - &mtu, sizeof(mtu), &len, NULL)) + if (DeviceIoControl(tt->hand, TAP_WIN_IOCTL_GET_MTU, &mtu, sizeof(mtu)= , &mtu, sizeof(mtu), &len, + NULL)) { msg(D_MTU_INFO, "TAP-Windows MTU=3D%d", (int)mtu); } } static void -tuntap_set_ip_addr(struct tuntap *tt, - const char *device_guid, - bool dhcp_masq_post) +tuntap_set_ip_addr(struct tuntap *tt, const char *device_guid, bool dhcp_m= asq_post) { struct gc_arena gc =3D gc_new(); const DWORD index =3D tt->adapter_index; /* flush arp cache */ - if (tt->backend_driver =3D=3D WINDOWS_DRIVER_TAP_WINDOWS6 - && index !=3D TUN_ADAPTER_INDEX_INVALID) + if (tt->backend_driver =3D=3D WINDOWS_DRIVER_TAP_WINDOWS6 && index != =3D TUN_ADAPTER_INDEX_INVALID) { DWORD status =3D -1; if (tt->options.msg_channel) { ack_message_t ack; - flush_neighbors_message_t msg =3D { - .header =3D { - msg_flush_neighbors, - sizeof(flush_neighbors_message_t), - 0 - }, - .family =3D AF_INET, - .iface =3D {.index =3D index, .name =3D "" } - }; + flush_neighbors_message_t msg =3D { .header =3D { msg_flush_ne= ighbors, + sizeof(flush_nei= ghbors_message_t), 0 }, + .family =3D AF_INET, + .iface =3D { .index =3D inde= x, .name =3D "" } }; - if (send_msg_iservice(tt->options.msg_channel, &msg, sizeof(ms= g), - &ack, "TUN")) + if (send_msg_iservice(tt->options.msg_channel, &msg, sizeof(ms= g), &ack, "TUN")) { status =3D ack.error_number; } @@ -6187,17 +5890,13 @@ if (status =3D=3D NO_ERROR) { - msg(M_INFO, "Successful ARP Flush on interface [%lu] %s", - index, - device_guid); + msg(M_INFO, "Successful ARP Flush on interface [%lu] %s", inde= x, device_guid); } else if (status !=3D -1) { - msg(D_TUNTAP_INFO, "NOTE: FlushIpNetTable failed on interface = [%lu] %s (status=3D%lu) : %s", - index, - device_guid, - status, - strerror_win32(status, &gc)); + msg(D_TUNTAP_INFO, + "NOTE: FlushIpNetTable failed on interface [%lu] %s (statu= s=3D%lu) : %s", index, + device_guid, status, strerror_win32(status, &gc)); } /* @@ -6210,7 +5909,8 @@ /* check dhcp enable status */ if (dhcp_status(index) =3D=3D DHCP_STATUS_DISABLED) { - msg(M_WARN, "WARNING: You have selected '--ip-win32 dynami= c', which will not work unless the TAP-Windows TCP/IP properties are set to= 'Obtain an IP address automatically'"); + msg(M_WARN, + "WARNING: You have selected '--ip-win32 dynamic', whic= h will not work unless the TAP-Windows TCP/IP properties are set to 'Obtain= an IP address automatically'"); } /* force an explicit DHCP lease renewal on TAP adapter? */ @@ -6232,20 +5932,21 @@ if (tt->did_ifconfig_setup && tt->options.ip_win32_type =3D=3D IPW32_S= ET_IPAPI) { DWORD status; - const char *error_suffix =3D "I am having trouble using the Window= s 'IP helper API' to automatically set the IP address -- consider using oth= er --ip-win32 methods (not 'ipapi')"; + const char *error_suffix =3D + "I am having trouble using the Windows 'IP helper API' to auto= matically set the IP address -- consider using other --ip-win32 methods (no= t 'ipapi')"; /* couldn't get adapter index */ if (index =3D=3D TUN_ADAPTER_INDEX_INVALID) { - msg(M_FATAL, "ERROR: unable to get adapter index for interface= %s -- %s", - device_guid, + msg(M_FATAL, "ERROR: unable to get adapter index for interface= %s -- %s", device_guid, error_suffix); } /* check dhcp enable status */ if (dhcp_status(index) =3D=3D DHCP_STATUS_DISABLED) { - msg(M_WARN, "NOTE: You have selected (explicitly or by default= ) '--ip-win32 ipapi', which has a better chance of working correctly if the= TAP-Windows TCP/IP properties are set to 'Obtain an IP address automatical= ly'"); + msg(M_WARN, + "NOTE: You have selected (explicitly or by default) '--ip-= win32 ipapi', which has a better chance of working correctly if the TAP-Win= dows TCP/IP properties are set to 'Obtain an IP address automatically'"); } /* delete previously added IP addresses which were not @@ -6253,28 +5954,21 @@ delete_temp_addresses(index); /* add a new IP address */ - if ((status =3D AddIPAddress(htonl(tt->local), - htonl(tt->adapter_netmask), - index, - &tt->ipapi_context, - &tt->ipapi_instance)) =3D=3D NO_ERROR) + if ((status =3D AddIPAddress(htonl(tt->local), htonl(tt->adapter_n= etmask), index, + &tt->ipapi_context, &tt->ipapi_instance= )) + =3D=3D NO_ERROR) { - msg(M_INFO, "Succeeded in adding a temporary IP/netmask of %s/= %s to interface %s using the Win32 IP Helper API", - print_in_addr_t(tt->local, 0, &gc), - print_in_addr_t(tt->adapter_netmask, 0, &gc), - device_guid - ); + msg(M_INFO, + "Succeeded in adding a temporary IP/netmask of %s/%s to in= terface %s using the Win32 IP Helper API", + print_in_addr_t(tt->local, 0, &gc), print_in_addr_t(tt->ad= apter_netmask, 0, &gc), + device_guid); } else { - msg(M_FATAL, "ERROR: AddIPAddress %s/%s failed on interface %s= , index=3D%lu, status=3D%lu (windows error: '%s') -- %s", - print_in_addr_t(tt->local, 0, &gc), - print_in_addr_t(tt->adapter_netmask, 0, &gc), - device_guid, - index, - status, - strerror_win32(status, &gc), - error_suffix); + msg(M_FATAL, + "ERROR: AddIPAddress %s/%s failed on interface %s, index= =3D%lu, status=3D%lu (windows error: '%s') -- %s", + print_in_addr_t(tt->local, 0, &gc), print_in_addr_t(tt->ad= apter_netmask, 0, &gc), + device_guid, index, status, strerror_win32(status, &gc), e= rror_suffix); } tt->ipapi_context_defined =3D true; } @@ -6287,11 +5981,11 @@ { ULONG status =3D TRUE; DWORD len; - if (!DeviceIoControl(tt->hand, TAP_WIN_IOCTL_SET_MEDIA_STATUS, - &status, sizeof(status), - &status, sizeof(status), &len, NULL)) + if (!DeviceIoControl(tt->hand, TAP_WIN_IOCTL_SET_MEDIA_STATUS, &status= , sizeof(status), &status, + sizeof(status), &len, NULL)) { - msg(M_WARN, "WARNING: The TAP-Windows driver rejected a TAP_WIN_IO= CTL_SET_MEDIA_STATUS DeviceIoControl call."); + msg(M_WARN, + "WARNING: The TAP-Windows driver rejected a TAP_WIN_IOCTL_SET_= MEDIA_STATUS DeviceIoControl call."); } int s =3D tt->options.tap_sleep; @@ -6325,17 +6019,16 @@ ep[1] =3D htonl(tt->local & tt->remote_netmask); ep[2] =3D htonl(tt->remote_netmask); =20 - status =3D DeviceIoControl(tt->hand, TAP_WIN_IOCTL_CONFIG_TUN, - ep, sizeof(ep), - ep, sizeof(ep), &len, NULL); + status =3D DeviceIoControl(tt->hand, TAP_WIN_IOCTL_CONFIG_TUN, ep,= sizeof(ep), ep, sizeof(ep), + &len, NULL); if (tt->did_ifconfig_setup) { - msg(status ? M_INFO : M_FATAL, "Set TAP-Windows TUN subnet mod= e network/local/netmask =3D %s/%s/%s [%s]", + msg(status ? M_INFO : M_FATAL, + "Set TAP-Windows TUN subnet mode network/local/netmask =3D= %s/%s/%s [%s]", print_in_addr_t(ep[1], IA_NET_ORDER, &gc), print_in_addr_t(ep[0], IA_NET_ORDER, &gc), - print_in_addr_t(ep[2], IA_NET_ORDER, &gc), - status ? "SUCCEEDED" : "FAILED"); + print_in_addr_t(ep[2], IA_NET_ORDER, &gc), status ? "SUCCE= EDED" : "FAILED"); } else { @@ -6349,11 +6042,11 @@ ep[0] =3D htonl(tt->local); ep[1] =3D htonl(tt->remote_netmask); - if (!DeviceIoControl(tt->hand, TAP_WIN_IOCTL_CONFIG_POINT_TO_POINT, - ep, sizeof(ep), - ep, sizeof(ep), &len, NULL)) + if (!DeviceIoControl(tt->hand, TAP_WIN_IOCTL_CONFIG_POINT_TO_POINT= , ep, sizeof(ep), ep, + sizeof(ep), &len, NULL)) { - msg(M_FATAL, "ERROR: The TAP-Windows driver rejected a DeviceI= oControl call to set Point-to-Point mode, which is required for --dev tun"); + msg(M_FATAL, + "ERROR: The TAP-Windows driver rejected a DeviceIoControl = call to set Point-to-Point mode, which is required for --dev tun"); } } @@ -6376,7 +6069,9 @@ { if (tt->topology =3D=3D TOP_SUBNET) { - ep[2] =3D dhcp_masq_addr(tt->local, tt->remote_netmask, tt->op= tions.dhcp_masq_custom_offset ? tt->options.dhcp_masq_offset : 0); + ep[2] =3D dhcp_masq_addr( + tt->local, tt->remote_netmask, + tt->options.dhcp_masq_custom_offset ? tt->options.dhcp_mas= q_offset : 0); } else { @@ -6386,7 +6081,9 @@ else { ASSERT(tt->type =3D=3D DEV_TYPE_TAP); - ep[2] =3D dhcp_masq_addr(tt->local, tt->adapter_netmask, tt->optio= ns.dhcp_masq_custom_offset ? tt->options.dhcp_masq_offset : 0); + ep[2] =3D + dhcp_masq_addr(tt->local, tt->adapter_netmask, + tt->options.dhcp_masq_custom_offset ? tt->optio= ns.dhcp_masq_offset : 0); } /* lease time in seconds */ @@ -6395,20 +6092,17 @@ ASSERT(ep[3] > 0); #ifndef SIMULATE_DHCP_FAILED /* this code is disabled to simulate bad DHCP= negotiation */ - if (!DeviceIoControl(tt->hand, TAP_WIN_IOCTL_CONFIG_DHCP_MASQ, - ep, sizeof(ep), - ep, sizeof(ep), &len, NULL)) + if (!DeviceIoControl(tt->hand, TAP_WIN_IOCTL_CONFIG_DHCP_MASQ, ep, siz= eof(ep), ep, sizeof(ep), + &len, NULL)) { - msg(M_FATAL, "ERROR: The TAP-Windows driver rejected a DeviceIoCon= trol call to set TAP_WIN_IOCTL_CONFIG_DHCP_MASQ mode"); + msg(M_FATAL, + "ERROR: The TAP-Windows driver rejected a DeviceIoControl call= to set TAP_WIN_IOCTL_CONFIG_DHCP_MASQ mode"); } - msg(M_INFO, "Notified TAP-Windows driver to set a DHCP IP/netmask of %= s/%s on interface %s [DHCP-serv: %s, lease-time: %d]", - print_in_addr_t(tt->local, 0, &gc), - print_in_addr_t(tt->adapter_netmask, 0, &gc), - device_guid, - print_in_addr_t(ep[2], IA_NET_ORDER, &gc), - ep[3] - ); + msg(M_INFO, + "Notified TAP-Windows driver to set a DHCP IP/netmask of %s/%s on = interface %s [DHCP-serv: %s, lease-time: %d]", + print_in_addr_t(tt->local, 0, &gc), print_in_addr_t(tt->adapter_ne= tmask, 0, &gc), + device_guid, print_in_addr_t(ep[2], IA_NET_ORDER, &gc), ep[3]); /* user-supplied DHCP options capability */ if (tt->options.dhcp_options) @@ -6417,11 +6111,11 @@ if (build_dhcp_options_string(&buf, &tt->options)) { msg(D_DHCP_OPT, "DHCP option string: %s", format_hex(BPTR(&buf= ), BLEN(&buf), 0, &gc)); - if (!DeviceIoControl(tt->hand, TAP_WIN_IOCTL_CONFIG_DHCP_SET_O= PT, - BPTR(&buf), BLEN(&buf), - BPTR(&buf), BLEN(&buf), &len, NULL)) + if (!DeviceIoControl(tt->hand, TAP_WIN_IOCTL_CONFIG_DHCP_SET_O= PT, BPTR(&buf), + BLEN(&buf), BPTR(&buf), BLEN(&buf), &len,= NULL)) { - msg(M_FATAL, "ERROR: The TAP-Windows driver rejected a TAP= _WIN_IOCTL_CONFIG_DHCP_SET_OPT DeviceIoControl call"); + msg(M_FATAL, + "ERROR: The TAP-Windows driver rejected a TAP_WIN_IOCT= L_CONFIG_DHCP_SET_OPT DeviceIoControl call"); } } else @@ -6430,13 +6124,14 @@ } free_buf(&buf); } -#endif /* ifndef SIMULATE_DHCP_FAILED */ +#endif /* ifndef SIMULATE_DHCP_FAILED */ gc_free(&gc); } static bool -tun_try_open_device(struct tuntap *tt, const char *device_guid, const stru= ct device_instance_id_interface *device_instance_id_interface) +tun_try_open_device(struct tuntap *tt, const char *device_guid, + const struct device_instance_id_interface *device_inst= ance_id_interface) { const char *path =3D NULL; char tuntap_device_path[256]; @@ -6455,8 +6150,7 @@ if (tt->backend_driver =3D=3D DRIVER_DCO) { char *last_sep =3D strrchr(dev_if->device_interface, '\\'); - if (!last_sep - || strcmp(last_sep + 1, DCO_WIN_REFERENCE_STRING) !=3D= 0) + if (!last_sep || strcmp(last_sep + 1, DCO_WIN_REFERENCE_ST= RING) !=3D 0) { continue; } @@ -6473,25 +6167,19 @@ else { /* Open TAP-Windows */ - snprintf(tuntap_device_path, sizeof(tuntap_device_path), "%s%s%s", - USERMODEDEVICEDIR, - device_guid, - TAP_WIN_SUFFIX); + snprintf(tuntap_device_path, sizeof(tuntap_device_path), "%s%s%s",= USERMODEDEVICEDIR, + device_guid, TAP_WIN_SUFFIX); path =3D tuntap_device_path; } msg(D_TAP_WIN_DEBUG, "Using device interface: %s", path); - tt->hand =3D CreateFile(path, - GENERIC_READ | GENERIC_WRITE, - 0, /* was: FILE_SHARE_READ */ - 0, - OPEN_EXISTING, - FILE_ATTRIBUTE_SYSTEM | FILE_FLAG_OVERLAPPED, - 0); + tt->hand =3D CreateFile(path, GENERIC_READ | GENERIC_WRITE, 0, /* was:= FILE_SHARE_READ */ + 0, OPEN_EXISTING, FILE_ATTRIBUTE_SYSTEM | FILE_F= LAG_OVERLAPPED, 0); if (tt->hand =3D=3D INVALID_HANDLE_VALUE) { - msg(D_TUNTAP_INFO | M_ERRNO, "CreateFile failed on %s device: %s",= print_tun_backend_driver(tt->backend_driver), path); + msg(D_TUNTAP_INFO | M_ERRNO, "CreateFile failed on %s device: %s", + print_tun_backend_driver(tt->backend_driver), path); return false; } @@ -6499,11 +6187,13 @@ } void -tun_open_device(struct tuntap *tt, const char *dev_node, const char **devi= ce_guid, struct gc_arena *gc) +tun_open_device(struct tuntap *tt, const char *dev_node, const char **devi= ce_guid, + struct gc_arena *gc) { const struct tap_reg *tap_reg =3D get_tap_reg(gc); const struct panel_reg *panel_reg =3D get_panel_reg(gc); - const struct device_instance_id_interface *device_instance_id_interfac= e =3D get_device_instance_id_interface(gc); + const struct device_instance_id_interface *device_instance_id_interfac= e =3D + get_device_instance_id_interface(gc); uint8_t actual_buffer[256]; @@ -6515,7 +6205,8 @@ enum tun_driver_type windows_driver =3D WINDOWS_DRIVER_UNSPECIFIED; /* Get the device GUID for the device specified with --dev-node. */ - *device_guid =3D get_device_guid(dev_node, actual_buffer, sizeof(a= ctual_buffer), &windows_driver, tap_reg, panel_reg, gc); + *device_guid =3D get_device_guid(dev_node, actual_buffer, sizeof(a= ctual_buffer), + &windows_driver, tap_reg, panel_reg= , gc); if (!*device_guid) { @@ -6524,13 +6215,16 @@ if (tt->backend_driver !=3D windows_driver) { - msg(M_FATAL, "Adapter '%s' is using %s driver, %s expected. If= you want to use this device, adjust --windows-driver.", - dev_node, print_tun_backend_driver(windows_driver), print_= tun_backend_driver(tt->backend_driver)); + msg(M_FATAL, + "Adapter '%s' is using %s driver, %s expected. If you want= to use this device, adjust --windows-driver.", + dev_node, print_tun_backend_driver(windows_driver), + print_tun_backend_driver(tt->backend_driver)); } if (!tun_try_open_device(tt, *device_guid, device_instance_id_inte= rface)) { - msg(M_FATAL, "Failed to open %s adapter: %s", print_tun_backen= d_driver(tt->backend_driver), dev_node); + msg(M_FATAL, "Failed to open %s adapter: %s", + print_tun_backend_driver(tt->backend_driver), dev_node); } } else @@ -6542,20 +6236,18 @@ while (true) { enum tun_driver_type windows_driver =3D WINDOWS_DRIVER_UNSPECI= FIED; - *device_guid =3D get_unspecified_device_guid(device_number, - actual_buffer, - sizeof(actual_buffe= r), - tap_reg, - panel_reg, - &windows_driver, - gc); + *device_guid =3D + get_unspecified_device_guid(device_number, actual_buffer, = sizeof(actual_buffer), + tap_reg, panel_reg, &windows_d= river, gc); if (!*device_guid) { /* try to create an adapter a few times if we have a servi= ce pipe handle */ - if ((++adapters_created > 10) || !do_create_adapter_servic= e(tt->options.msg_channel, tt->backend_driver)) + if ((++adapters_created > 10) + || !do_create_adapter_service(tt->options.msg_channel,= tt->backend_driver)) { - msg(M_FATAL, "All %s adapters on this system are curre= ntly in use or disabled.", print_tun_backend_driver(tt->backend_driver)); + msg(M_FATAL, "All %s adapters on this system are curre= ntly in use or disabled.", + print_tun_backend_driver(tt->backend_driver)); } else { @@ -6622,10 +6314,7 @@ */ if (dhcp_status(tt->adapter_index) !=3D DHCP_STATUS_ENABLED) { - netsh_ifconfig(&tt->options, - tt->adapter_index, - tt->local, - tt->adapter_netmask, + netsh_ifconfig(&tt->options, tt->adapter_index, tt->local, tt-= >adapter_netmask, NI_TEST_FIRST | NI_IP_NETMASK | NI_OPTIONS); } else @@ -6686,9 +6375,11 @@ if ((tt->options.dhcp_options & DHCP_OPTIONS_DHCP_REQUIRED) && tt->backend_driver !=3D WINDOWS_DRIVER_TAP_WINDOWS6) { - msg(M_WARN, "Some --dhcp-option or --dns options require DHCP serv= er," + msg(M_WARN, + "Some --dhcp-option or --dns options require DHCP server," " which is not supported by the selected %s driver. They will = be" - " ignored.", print_tun_backend_driver(tt->backend_driver)); + " ignored.", + print_tun_backend_driver(tt->backend_driver)); } /* dco-win already opened the device, which handle we treat as socket = */ @@ -6701,11 +6392,11 @@ /*netcmd_semaphore_lock ();*/ - msg( M_INFO, "open_tun"); + msg(M_INFO, "open_tun"); if (tt->type !=3D DEV_TYPE_TAP && tt->type !=3D DEV_TYPE_TUN) { - msg(M_FATAL|M_NOPREFIX, "Unknown virtual device type: '%s'", dev); + msg(M_FATAL | M_NOPREFIX, "Unknown virtual device type: '%s'", dev= ); } struct gc_arena gc =3D gc_new(); /* used also for device_guid allocati= on */ @@ -6725,10 +6416,8 @@ { struct buffer out =3D alloc_buf_gc(256, gc); DWORD len; - if (DeviceIoControl(tt->hand, TAP_WIN_IOCTL_GET_INFO, - BSTR(&out), BCAP(&out), - BSTR(&out), BCAP(&out), - &len, NULL)) + if (DeviceIoControl(tt->hand, TAP_WIN_IOCTL_GET_INFO, BSTR(&out), = BCAP(&out), BSTR(&out), + BCAP(&out), &len, NULL)) { return BSTR(&out); } @@ -6743,10 +6432,8 @@ { struct buffer out =3D alloc_buf(1024); DWORD len; - while (DeviceIoControl(tt->hand, TAP_WIN_IOCTL_GET_LOG_LINE, - BSTR(&out), BCAP(&out), - BSTR(&out), BCAP(&out), - &len, NULL)) + while (DeviceIoControl(tt->hand, TAP_WIN_IOCTL_GET_LOG_LINE, BSTR(= &out), BCAP(&out), + BSTR(&out), BCAP(&out), &len, NULL)) { msg(D_TAP_WIN_DEBUG, "TAP-Windows: %s", BSTR(&out)); } @@ -6764,22 +6451,15 @@ int len =3D ipv6 ? tt->options.dns6_len : tt->options.dns_len; if (len > 0) { - argv_printf(&argv, - "%s%s interface %s delete dns %lu all", - get_win_sys_path(), - NETSH_PATH_SUFFIX, - ipv6 ? "ipv6" : "ipv4", - tt->adapter_index); + argv_printf(&argv, "%s%s interface %s delete dns %lu all", get_win= _sys_path(), + NETSH_PATH_SUFFIX, ipv6 ? "ipv6" : "ipv4", tt->adapter= _index); netsh_command(&argv, 1, M_WARN); } if (!ipv6 && tt->options.wins_len > 0) { - argv_printf(&argv, - "%s%s interface ipv4 delete winsservers %lu all", - get_win_sys_path(), - NETSH_PATH_SUFFIX, - tt->adapter_index); + argv_printf(&argv, "%s%s interface ipv4 delete winsservers %lu all= ", get_win_sys_path(), + NETSH_PATH_SUFFIX, tt->adapter_index); netsh_command(&argv, 1, M_WARN); } @@ -6801,13 +6481,8 @@ { ifconfig_ip_local =3D print_in_addr_t(tt->local, 0, gc); } - argv_printf(&argv, - "%s%s interface %s delete address %lu %s store=3Dactive", - get_win_sys_path(), - NETSH_PATH_SUFFIX, - ipv6 ? "ipv6" : "ipv4", - tt->adapter_index, - ifconfig_ip_local); + argv_printf(&argv, "%s%s interface %s delete address %lu %s store=3Dac= tive", get_win_sys_path(), + NETSH_PATH_SUFFIX, ipv6 ? "ipv6" : "ipv4", tt->adapter_ind= ex, ifconfig_ip_local); netsh_command(&argv, 1, M_WARN); argv_free(&argv); @@ -6885,7 +6560,8 @@ { /* We didn't do ifconfig. */ } - else if (tt->options.ip_win32_type =3D=3D IPW32_SET_DHCP_MASQ || t= t->options.ip_win32_type =3D=3D IPW32_SET_ADAPTIVE) + else if (tt->options.ip_win32_type =3D=3D IPW32_SET_DHCP_MASQ + || tt->options.ip_win32_type =3D=3D IPW32_SET_ADAPTIVE) { /* We don't have to clean the configuration with DHCP. */ } @@ -6912,10 +6588,9 @@ DWORD status; if ((status =3D DeleteIPAddress(tt->ipapi_context)) !=3D NO_ERROR) { - msg(M_WARN, "Warning: DeleteIPAddress[%u] failed on TAP-Window= s adapter, status=3D%u : %s", - (unsigned int)tt->ipapi_context, - (unsigned int)status, - strerror_win32(status, &gc)); + msg(M_WARN, + "Warning: DeleteIPAddress[%u] failed on TAP-Windows adapte= r, status=3D%u : %s", + (unsigned int)tt->ipapi_context, (unsigned int)status, str= error_win32(status, &gc)); } } @@ -6934,17 +6609,14 @@ * Convert --ip-win32 constants between index and ascii form. */ -struct ipset_names { +struct ipset_names +{ const char *short_form; }; /* Indexed by IPW32_SET_x */ static const struct ipset_names ipset_names[] =3D { - {"manual"}, - {"netsh"}, - {"ipapi"}, - {"dynamic"}, - {"adaptive"} + { "manual" }, { "netsh" }, { "ipapi" }, { "dynamic" }, { "adaptive" } }; int @@ -6994,7 +6666,7 @@ return BSTR(&out); } -#else /* generic */ +#else /* generic */ void open_tun(const char *dev, const char *dev_type, const char *dev_node, stru= ct tuntap *tt, @@ -7024,4 +6696,4 @@ return read(tt->fd, buf, len); } -#endif /* if defined (TARGET_ANDROID) */ +#endif /* if defined (TARGET_ANDROID) */ diff --git a/src/openvpn/tun.h b/src/openvpn/tun.h index c53fdc0..06fc729 100644 --- a/src/openvpn/tun.h +++ b/src/openvpn/tun.h @@ -40,7 +40,8 @@ #include "networking.h" #include "dco.h" -enum tun_driver_type { +enum tun_driver_type +{ WINDOWS_DRIVER_UNSPECIFIED, WINDOWS_DRIVER_TAP_WINDOWS6, DRIVER_GENERIC_TUNTAP, @@ -67,19 +68,20 @@ #define IPW32_SET_ADAPTIVE_TRY_NETSH 20 /* bit flags for DHCP options */ -#define DHCP_OPTIONS_DHCP_OPTIONAL (1<<0) -#define DHCP_OPTIONS_DHCP_REQUIRED (1<<1) +#define DHCP_OPTIONS_DHCP_OPTIONAL (1 << 0) +#define DHCP_OPTIONS_DHCP_REQUIRED (1 << 1) -struct tuntap_options { +struct tuntap_options +{ /* --ip-win32 options */ bool ip_win32_defined; -#define IPW32_SET_MANUAL 0 /* "--ip-win32 manual" */ -#define IPW32_SET_NETSH 1 /* "--ip-win32 netsh" */ -#define IPW32_SET_IPAPI 2 /* "--ip-win32 ipapi" */ -#define IPW32_SET_DHCP_MASQ 3 /* "--ip-win32 dynamic" */ -#define IPW32_SET_ADAPTIVE 4 /* "--ip-win32 adaptive" */ -#define IPW32_SET_N 5 +#define IPW32_SET_MANUAL 0 /* "--ip-win32 manual" */ +#define IPW32_SET_NETSH 1 /* "--ip-win32 netsh" */ +#define IPW32_SET_IPAPI 2 /* "--ip-win32 ipapi" */ +#define IPW32_SET_DHCP_MASQ 3 /* "--ip-win32 dynamic" */ +#define IPW32_SET_ADAPTIVE 4 /* "--ip-win32 adaptive" */ +#define IPW32_SET_N 5 int ip_win32_type; #ifdef _WIN32 @@ -98,14 +100,15 @@ int dhcp_options; - const char *domain; /* DOMAIN (15) */ + const char *domain; /* DOMAIN (15) */ const char *netbios_scope; /* NBS (47) */ - int netbios_node_type; /* NBT 1,2,4,8 (46) */ + int netbios_node_type; /* NBT 1,2,4,8 (46) */ -#define N_DHCP_ADDR 4 /* Max # of addresses allowed for - * DNS, WINS, etc. */ +#define N_DHCP_ADDR \ + 4 /* Max # of addresses allowed for \ + * DNS, WINS, etc. */ /* DNS (6) */ in_addr_t dns[N_DHCP_ADDR]; @@ -147,13 +150,15 @@ #elif defined(TARGET_LINUX) -struct tuntap_options { +struct tuntap_options +{ int txqueuelen; }; #else /* if defined(_WIN32) || defined(TARGET_ANDROID) */ -struct tuntap_options { +struct tuntap_options +{ int dummy; /* not used */ }; @@ -169,7 +174,8 @@ } afunix_context_t; #else /* ifndef WIN32 */ -typedef struct { +typedef struct +{ int dummy; } afunix_context_t; #endif @@ -195,11 +201,11 @@ * been set up. This does NOT mean ifconfig has been called */ bool did_ifconfig_ipv6_setup; - bool persistent_if; /* if existed before, keep on program end = */ + bool persistent_if; /* if existed before, keep on program e= nd */ struct tuntap_options options; /* options set on command line */ - char *actual_name; /* actual name of TUN/TAP dev, usually including un= it number */ + char *actual_name; /* actual name of TUN/TAP dev, usually = including unit number */ /* ifconfig parameters */ in_addr_t local; @@ -230,7 +236,7 @@ int standby_iter; - #else /* ifdef _WIN32 */ +#else /* ifdef _WIN32 */ int fd; /* file descriptor for TUN/TAP dev */ #endif /* ifdef _WIN32 */ @@ -259,13 +265,13 @@ * Function prototypes */ -void open_tun(const char *dev, const char *dev_type, const char *dev_node, - struct tuntap *tt, openvpn_net_ctx_t *ctx); +void open_tun(const char *dev, const char *dev_type, const char *dev_node,= struct tuntap *tt, + openvpn_net_ctx_t *ctx); void close_tun(struct tuntap *tt, openvpn_net_ctx_t *ctx); -void tun_open_device(struct tuntap *tt, const char *dev_node, - const char **device_guid, struct gc_arena *gc); +void tun_open_device(struct tuntap *tt, const char *dev_node, const char *= *device_guid, + struct gc_arena *gc); void close_tun_handle(struct tuntap *tt); @@ -273,37 +279,29 @@ int read_tun(struct tuntap *tt, uint8_t *buf, int len); -void tuncfg(const char *dev, const char *dev_type, const char *dev_node, - int persist_mode, const char *username, - const char *groupname, const struct tuntap_options *options, +void tuncfg(const char *dev, const char *dev_type, const char *dev_node, i= nt persist_mode, + const char *username, const char *groupname, const struct tunt= ap_options *options, openvpn_net_ctx_t *ctx); -const char *guess_tuntap_dev(const char *dev, - const char *dev_type, - const char *dev_node, +const char *guess_tuntap_dev(const char *dev, const char *dev_type, const = char *dev_node, struct gc_arena *gc); -struct tuntap *init_tun(const char *dev, /* --dev option */ - const char *dev_type, /* --dev-type option */ - int topology, /* one of the TOP_x values= */ - const char *ifconfig_local_parm, /* --if= config parm 1 */ - const char *ifconfig_remote_netmask_parm, /* --if= config parm 2 */ - const char *ifconfig_ipv6_local_parm, /* --if= config parm 1 / IPv6 */ - int ifconfig_ipv6_netbits_parm, /* --if= config parm 1 / bits */ - const char *ifconfig_ipv6_remote_parm, /* --if= config parm 2 / IPv6 */ - struct addrinfo *local_public, - struct addrinfo *remote_public, - const bool strict_warn, - struct env_set *es, - openvpn_net_ctx_t *ctx, +struct tuntap *init_tun(const char *dev, /* --dev= option */ + const char *dev_type, /* --dev= -type option */ + int topology, /* one o= f the TOP_x values */ + const char *ifconfig_local_parm, /* --ifc= onfig parm 1 */ + const char *ifconfig_remote_netmask_parm, /* --ifc= onfig parm 2 */ + const char *ifconfig_ipv6_local_parm, /* --ifc= onfig parm 1 / IPv6 */ + int ifconfig_ipv6_netbits_parm, /* --ifc= onfig parm 1 / bits */ + const char *ifconfig_ipv6_remote_parm, /* --ifc= onfig parm 2 / IPv6 */ + struct addrinfo *local_public, struct addrinfo *re= mote_public, + const bool strict_warn, struct env_set *es, openvp= n_net_ctx_t *ctx, struct tuntap *tt); -void init_tun_post(struct tuntap *tt, - const struct frame *frame, +void init_tun_post(struct tuntap *tt, const struct frame *frame, const struct tuntap_options *options); -void do_ifconfig_setenv(const struct tuntap *tt, - struct env_set *es); +void do_ifconfig_setenv(const struct tuntap *tt, struct env_set *es); /** * do_ifconfig - configure the tunnel interface @@ -314,8 +312,8 @@ * @param es the environment to be used when executing the commands * @param ctx the networking API opaque context */ -void do_ifconfig(struct tuntap *tt, const char *ifname, int tun_mtu, - const struct env_set *es, openvpn_net_ctx_t *ctx); +void do_ifconfig(struct tuntap *tt, const char *ifname, int tun_mtu, const= struct env_set *es, + openvpn_net_ctx_t *ctx); /** * undo_ifconfig - undo configuration of the tunnel interface @@ -331,7 +329,8 @@ const char *dev_type_string(const char *dev, const char *dev_type); -const char *ifconfig_options_string(const struct tuntap *tt, bool remote, = bool disable, struct gc_arena *gc); +const char *ifconfig_options_string(const struct tuntap *tt, bool remote, = bool disable, + struct gc_arena *gc); bool is_tun_p2p(const struct tuntap *tt); @@ -340,8 +339,7 @@ /** * Return a string representation of the tun backed driver type */ -const char * -print_tun_backend_driver(enum tun_driver_type driver); +const char *print_tun_backend_driver(enum tun_driver_type driver); /* * Should ifconfig be called before or after @@ -351,7 +349,7 @@ #define IFCONFIG_BEFORE_TUN_OPEN 0 #define IFCONFIG_AFTER_TUN_OPEN 1 -#define IFCONFIG_DEFAULT IFCONFIG_AFTER_TUN_OPEN +#define IFCONFIG_DEFAULT IFCONFIG_AFTER_TUN_OPEN static inline int ifconfig_order(struct tuntap *tt) @@ -374,13 +372,13 @@ return IFCONFIG_AFTER_TUN_OPEN; #elif defined(TARGET_ANDROID) return IFCONFIG_BEFORE_TUN_OPEN; -#else /* if defined(TARGET_LINUX) */ +#else /* if defined(TARGET_LINUX) */ return IFCONFIG_DEFAULT; #endif } -#define ROUTE_BEFORE_TUN 0 -#define ROUTE_AFTER_TUN 1 +#define ROUTE_BEFORE_TUN 0 +#define ROUTE_AFTER_TUN 1 #define ROUTE_ORDER_DEFAULT ROUTE_AFTER_TUN static inline int @@ -441,11 +439,10 @@ bool is_adapter_up(const struct tuntap *tt, const IP_ADAPTER_INFO *list); -bool is_ip_in_adapter_subnet(const IP_ADAPTER_INFO *ai, const in_addr_t ip= , in_addr_t *highest_netmask); +bool is_ip_in_adapter_subnet(const IP_ADAPTER_INFO *ai, const in_addr_t ip, + in_addr_t *highest_netmask); -DWORD adapter_index_of_ip(const IP_ADAPTER_INFO *list, - const in_addr_t ip, - int *count, +DWORD adapter_index_of_ip(const IP_ADAPTER_INFO *list, const in_addr_t ip,= int *count, in_addr_t *netmask); void show_tap_win_adapters(int msglev, int warnlev); @@ -599,10 +596,7 @@ } static inline void -tun_set(struct tuntap *tt, - struct event_set *es, - unsigned int rwflags, - void *arg, +tun_set(struct tuntap *tt, struct event_set *es, unsigned int rwflags, voi= d *arg, unsigned int *persistent) { if (!tuntap_defined(tt) || tuntap_is_dco_win(tt)) @@ -626,7 +620,6 @@ } #endif tt->rwflags_debug =3D rwflags; - } const char *tun_stat(const struct tuntap *tt, unsigned int rwflags, struct= gc_arena *gc); diff --git a/src/openvpn/tun_afunix.c b/src/openvpn/tun_afunix.c index ac12070..4d48a31 100644 --- a/src/openvpn/tun_afunix.c +++ b/src/openvpn/tun_afunix.c @@ -47,7 +47,6 @@ #include - static void tun_afunix_exec_child(const char *dev_node, struct tuntap *tt, struct env_= set *env) { @@ -60,8 +59,7 @@ argv_printf(&argv, "%s", program); - tt->afunix.childprocess =3D openvpn_execve_check(&argv, env, S_NOWAITP= ID, - msgprefix); + tt->afunix.childprocess =3D openvpn_execve_check(&argv, env, S_NOWAITP= ID, msgprefix); if (!openvpn_waitpid_check(tt->afunix.childprocess, msgprefix, M_WARN)) { tt->afunix.childprocess =3D 0; @@ -70,10 +68,7 @@ } void -open_tun_afunix(struct options *o, - int mtu, - struct tuntap *tt, - struct env_set *orig_env) +open_tun_afunix(struct options *o, int mtu, struct tuntap *tt, struct env_= set *orig_env) { struct gc_arena gc =3D gc_new(); @@ -81,14 +76,14 @@ if (!(socketpair(AF_UNIX, SOCK_DGRAM, 0, fds) =3D=3D 0)) { msg(M_ERR, "Cannot create socket pair for AF_UNIX socket to extern= al " - "program"); + "program"); return; } /* Ensure that the buffer sizes are decently sized. Otherwise macOS wi= ll * just have 2048 */ - struct socket_buffer_size newsizes =3D {65536, 65536 }; + struct socket_buffer_size newsizes =3D { 65536, 65536 }; socket_set_buffers(fds[0], &newsizes, false); socket_set_buffers(fds[1], &newsizes, false); @@ -167,8 +162,8 @@ } #else /* ifndef WIN32 */ void -open_tun_afunix(const char *dev, const char *dev_type, int mtu, - struct tuntap *tt, struct env_set env) +open_tun_afunix(const char *dev, const char *dev_type, int mtu, struct tun= tap *tt, + struct env_set env) { msg(M_ERR, "AF_UNIX socket support not available on this platform"); } diff --git a/src/openvpn/tun_afunix.h b/src/openvpn/tun_afunix.h index faca142..3346403 100644 --- a/src/openvpn/tun_afunix.h +++ b/src/openvpn/tun_afunix.h @@ -31,31 +31,24 @@ * the user provided taking care of implementing the actual tun * device. */ -void -open_tun_afunix(struct options *o, - int mtu, - struct tuntap *tt, - struct env_set *env); +void open_tun_afunix(struct options *o, int mtu, struct tuntap *tt, struct= env_set *env); /** * Closes the socket used for the AF_UNIX based device. Also sends a * SIGINT to the child process that was spawned to handle the tun device */ -void -close_tun_afunix(struct tuntap *tt); +void close_tun_afunix(struct tuntap *tt); /** * Writes a packet to a AF_UNIX based tun device. */ -ssize_t -write_tun_afunix(struct tuntap *tt, uint8_t *buf, int len); +ssize_t write_tun_afunix(struct tuntap *tt, uint8_t *buf, int len); /** * Reads a packet from a AF_UNIX based tun device. */ -ssize_t -read_tun_afunix(struct tuntap *tt, uint8_t *buf, int len); +ssize_t read_tun_afunix(struct tuntap *tt, uint8_t *buf, int len); #endif /* AFUNIX_TUN_H */ diff --git a/src/openvpn/vlan.c b/src/openvpn/vlan.c index 5cc23f4..a6a6e93 100644 --- a/src/openvpn/vlan.c +++ b/src/openvpn/vlan.c @@ -52,8 +52,8 @@ static void vlanhdr_set_vid(struct openvpn_8021qhdr *hdr, const uint16_t vid) { - hdr->pcp_cfi_vid =3D (hdr->pcp_cfi_vid & ~OPENVPN_8021Q_MASK_VID) - | (htons(vid) & OPENVPN_8021Q_MASK_VID); + hdr->pcp_cfi_vid =3D + (hdr->pcp_cfi_vid & ~OPENVPN_8021Q_MASK_VID) | (htons(vid) & OPENV= PN_8021Q_MASK_VID); } /* @@ -96,15 +96,13 @@ /* reject untagged frame */ if (c->options.vlan_accept =3D=3D VLAN_ONLY_TAGGED) { - msg(D_VLAN_DEBUG, - "dropping frame without vlan-tag (proto/len 0x%04x)", + msg(D_VLAN_DEBUG, "dropping frame without vlan-tag (proto/len = 0x%04x)", ntohs(ethhdr->proto)); goto drop; } /* untagged frame is accepted and associated with the global VID */ - msg(D_VLAN_DEBUG, - "assuming pvid for frame without vlan-tag, pvid: %u (proto/len= 0x%04x)", + msg(D_VLAN_DEBUG, "assuming pvid for frame without vlan-tag, pvid:= %u (proto/len 0x%04x)", c->options.vlan_pvid, ntohs(ethhdr->proto)); return c->options.vlan_pvid; @@ -125,8 +123,8 @@ /* VLAN-tagged frame: drop packet */ if (vid !=3D 0) { - msg(D_VLAN_DEBUG, "dropping frame with vlan-tag, vid: %u (= proto/len 0x%04x)", - vid, ntohs(vlanhdr->proto)); + msg(D_VLAN_DEBUG, "dropping frame with vlan-tag, vid: %u (= proto/len 0x%04x)", vid, + ntohs(vlanhdr->proto)); goto drop; } @@ -148,8 +146,7 @@ /* here we have a proper VLAN tagged frame: perform decapsulat= ion * and return embedded VID */ - msg(D_VLAN_DEBUG, - "removing vlan-tag from frame: vid: %u, wrapped proto/len:= 0x%04x", + msg(D_VLAN_DEBUG, "removing vlan-tag from frame: vid: %u, wrap= ped proto/len: 0x%04x", vid, ntohs(vlanhdr->proto)); /* save inner protocol to be restored later after decapsulatio= n */ @@ -224,8 +221,7 @@ goto drop; } - vlanhdr =3D (struct openvpn_8021qhdr *)buf_prepend(buf, - SIZE_ETH_TO_8021Q= _HDR); + vlanhdr =3D (struct openvpn_8021qhdr *)buf_prepend(buf, SIZE_ETH_T= O_8021Q_HDR); /* Initialise VLAN/802.1q header. * Move the Eth header so to keep dst/src addresses the same and t= hen @@ -244,8 +240,8 @@ /* set the VID corresponding to the current context (client) */ vlanhdr_set_vid(vlanhdr, c->options.vlan_pvid); - msg(D_VLAN_DEBUG, "tagging frame: vid %u (wrapping proto/len: %04x)", - c->options.vlan_pvid, vlanhdr->proto); + msg(D_VLAN_DEBUG, "tagging frame: vid %u (wrapping proto/len: %04x)", = c->options.vlan_pvid, + vlanhdr->proto); return; drop: diff --git a/src/openvpn/vlan.h b/src/openvpn/vlan.h index 7602585..e2c9c44 100644 --- a/src/openvpn/vlan.h +++ b/src/openvpn/vlan.h @@ -31,13 +31,10 @@ struct multi_context; struct multi_instance; -int16_t -vlan_decapsulate(const struct context *c, struct buffer *buf); +int16_t vlan_decapsulate(const struct context *c, struct buffer *buf); -bool -vlan_is_tagged(const struct buffer *buf); +bool vlan_is_tagged(const struct buffer *buf); -void -vlan_process_outgoing_tun(struct multi_context *m, struct multi_instance *= mi); +void vlan_process_outgoing_tun(struct multi_context *m, struct multi_insta= nce *mi); #endif /* VLAN_H */ diff --git a/src/openvpn/wfp_block.c b/src/openvpn/wfp_block.c index ce5cef2..506d41b 100644 --- a/src/openvpn/wfp_block.c +++ b/src/openvpn/wfp_block.c @@ -48,68 +48,33 @@ #endif /* c38d57d1-05a7-4c33-904f-7fbceee60e82 */ -DEFINE_GUID( - FWPM_LAYER_ALE_AUTH_CONNECT_V4, - 0xc38d57d1, - 0x05a7, - 0x4c33, - 0x90, 0x4f, 0x7f, 0xbc, 0xee, 0xe6, 0x0e, 0x82 - ); +DEFINE_GUID(FWPM_LAYER_ALE_AUTH_CONNECT_V4, 0xc38d57d1, 0x05a7, 0x4c33, 0x= 90, 0x4f, 0x7f, 0xbc, + 0xee, 0xe6, 0x0e, 0x82); /* 4a72393b-319f-44bc-84c3-ba54dcb3b6b4 */ -DEFINE_GUID( - FWPM_LAYER_ALE_AUTH_CONNECT_V6, - 0x4a72393b, - 0x319f, - 0x44bc, - 0x84, 0xc3, 0xba, 0x54, 0xdc, 0xb3, 0xb6, 0xb4 - ); +DEFINE_GUID(FWPM_LAYER_ALE_AUTH_CONNECT_V6, 0x4a72393b, 0x319f, 0x44bc, 0x= 84, 0xc3, 0xba, 0x54, + 0xdc, 0xb3, 0xb6, 0xb4); /* d78e1e87-8644-4ea5-9437-d809ecefc971 */ -DEFINE_GUID( - FWPM_CONDITION_ALE_APP_ID, - 0xd78e1e87, - 0x8644, - 0x4ea5, - 0x94, 0x37, 0xd8, 0x09, 0xec, 0xef, 0xc9, 0x71 - ); +DEFINE_GUID(FWPM_CONDITION_ALE_APP_ID, 0xd78e1e87, 0x8644, 0x4ea5, 0x94, 0= x37, 0xd8, 0x09, 0xec, + 0xef, 0xc9, 0x71); /* c35a604d-d22b-4e1a-91b4-68f674ee674b */ -DEFINE_GUID( - FWPM_CONDITION_IP_REMOTE_PORT, - 0xc35a604d, - 0xd22b, - 0x4e1a, - 0x91, 0xb4, 0x68, 0xf6, 0x74, 0xee, 0x67, 0x4b - ); +DEFINE_GUID(FWPM_CONDITION_IP_REMOTE_PORT, 0xc35a604d, 0xd22b, 0x4e1a, 0x9= 1, 0xb4, 0x68, 0xf6, 0x74, + 0xee, 0x67, 0x4b); /* 4cd62a49-59c3-4969-b7f3-bda5d32890a4 */ -DEFINE_GUID( - FWPM_CONDITION_IP_LOCAL_INTERFACE, - 0x4cd62a49, - 0x59c3, - 0x4969, - 0xb7, 0xf3, 0xbd, 0xa5, 0xd3, 0x28, 0x90, 0xa4 - ); +DEFINE_GUID(FWPM_CONDITION_IP_LOCAL_INTERFACE, 0x4cd62a49, 0x59c3, 0x4969,= 0xb7, 0xf3, 0xbd, 0xa5, + 0xd3, 0x28, 0x90, 0xa4); /* 632ce23b-5167-435c-86d7-e903684aa80c */ -DEFINE_GUID( - FWPM_CONDITION_FLAGS, - 0x632ce23b, - 0x5167, - 0x435c, - 0x86, 0xd7, 0xe9, 0x03, 0x68, 0x4a, 0xa8, 0x0c - ); +DEFINE_GUID(FWPM_CONDITION_FLAGS, 0x632ce23b, 0x5167, 0x435c, 0x86, 0xd7, = 0xe9, 0x03, 0x68, 0x4a, + 0xa8, 0x0c); /* UUID of WFP sublayer used by all instances of openvpn * 2f660d7e-6a37-11e6-a181-001e8c6e04a2 */ -DEFINE_GUID( - OPENVPN_WFP_BLOCK_SUBLAYER, - 0x2f660d7e, - 0x6a37, - 0x11e6, - 0xa1, 0x81, 0x00, 0x1e, 0x8c, 0x6e, 0x04, 0xa2 - ); +DEFINE_GUID(OPENVPN_WFP_BLOCK_SUBLAYER, 0x2f660d7e, 0x6a37, 0x11e6, 0xa1, = 0x81, 0x00, 0x1e, 0x8c, + 0x6e, 0x04, 0xa2); static WCHAR *FIREWALL_NAME =3D L"OpenVPN"; @@ -123,7 +88,11 @@ } #define OUT_ON_ERROR(err, msg) \ - if (err) { msg_handler(err, msg); goto out; } + if (err) \ + { \ + msg_handler(err, msg); \ + goto out; \ + } /* * Add a persistent sublayer with specified uuid. @@ -181,24 +150,21 @@ */ DWORD -add_wfp_block_filters(HANDLE *engine_handle, - int index, - const WCHAR *exe_path, - wfp_block_msg_handler_t msg_handler, - BOOL dns_only) +add_wfp_block_filters(HANDLE *engine_handle, int index, const WCHAR *exe_p= ath, + wfp_block_msg_handler_t msg_handler, BOOL dns_only) { - FWPM_SESSION0 session =3D {0}; + FWPM_SESSION0 session =3D { 0 }; FWPM_SUBLAYER0 *sublayer_ptr =3D NULL; NET_LUID itf_luid; UINT64 filterid; FWP_BYTE_BLOB *openvpnblob =3D NULL; - FWPM_FILTER0 Filter =3D {0}; + FWPM_FILTER0 Filter =3D { 0 }; FWPM_FILTER_CONDITION0 Condition[2]; - FWPM_FILTER_CONDITION0 match_openvpn =3D {0}; - FWPM_FILTER_CONDITION0 match_port_53 =3D {0}; - FWPM_FILTER_CONDITION0 match_interface =3D {0}; - FWPM_FILTER_CONDITION0 match_loopback =3D {0}; - FWPM_FILTER_CONDITION0 match_not_loopback =3D {0}; + FWPM_FILTER_CONDITION0 match_openvpn =3D { 0 }; + FWPM_FILTER_CONDITION0 match_port_53 =3D { 0 }; + FWPM_FILTER_CONDITION0 match_interface =3D { 0 }; + FWPM_FILTER_CONDITION0 match_loopback =3D { 0 }; + FWPM_FILTER_CONDITION0 match_not_loopback =3D { 0 }; DWORD err =3D 0; if (!msg_handler) @@ -223,8 +189,8 @@ FwpmFreeMemory0((void **)&sublayer_ptr); } else - { /* Add a new sublayer -- as another process may add it in the meant= ime, - * do not treat "already exists" as an error */ + { /* Add a new sublayer -- as another process may add it in the meanti= me, + * do not treat "already exists" as an error */ err =3D add_sublayer(OPENVPN_WFP_BLOCK_SUBLAYER); if (err =3D=3D FWP_E_ALREADY_EXISTS || err =3D=3D ERROR_SUCCESS) @@ -439,8 +405,7 @@ */ DWORD -set_interface_metric(const NET_IFINDEX index, const ADDRESS_FAMILY family, - const ULONG metric) +set_interface_metric(const NET_IFINDEX index, const ADDRESS_FAMILY family,= const ULONG metric) { DWORD err =3D 0; MIB_IPINTERFACE_ROW ipiface; diff --git a/src/openvpn/wfp_block.h b/src/openvpn/wfp_block.h index 6de39f5..5ca093c 100644 --- a/src/openvpn/wfp_block.h +++ b/src/openvpn/wfp_block.h @@ -32,7 +32,7 @@ /* Any value less than 5 should work fine. 3 is chosen without any real re= ason. */ #define WFP_BLOCK_IFACE_METRIC 3 -typedef void (*wfp_block_msg_handler_t) (DWORD err, const char *msg); +typedef void (*wfp_block_msg_handler_t)(DWORD err, const char *msg); DWORD delete_wfp_block_filters(HANDLE engine); @@ -51,8 +51,7 @@ * * @return positive interface metric on success or -1 on error */ -int -get_interface_metric(const NET_IFINDEX index, const ADDRESS_FAMILY family,= int *is_auto); +int get_interface_metric(const NET_IFINDEX index, const ADDRESS_FAMILY fam= ily, int *is_auto); /** * Sets interface metric value for specified interface index. @@ -65,8 +64,7 @@ */ DWORD -set_interface_metric(const NET_IFINDEX index, const ADDRESS_FAMILY family, - const ULONG metric); +set_interface_metric(const NET_IFINDEX index, const ADDRESS_FAMILY family,= const ULONG metric); #endif /* ifndef WFP_BLOCK_H */ #endif /* ifdef _WIN32 */ diff --git a/src/openvpn/win32-util.c b/src/openvpn/win32-util.c index c23d066..0d6d029 100644 --- a/src/openvpn/win32-util.c +++ b/src/openvpn/win32-util.c @@ -161,7 +161,7 @@ if (WideCharToMultiByte(CP_UTF8, 0, wtmpdir, -1, NULL, 0, NULL, NULL) = > sizeof(tmpdir)) { msg(M_WARN, "Could not get temporary directory. Path is too long." - " Consider using --tmp-dir"); + " Consider using --tmp-dir"); return NULL; } diff --git a/src/openvpn/win32.c b/src/openvpn/win32.c index 0524c57..15bcf37 100644 --- a/src/openvpn/win32.c +++ b/src/openvpn/win32.c @@ -101,8 +101,7 @@ /** * Set OpenSSL environment variables to a safe directory */ -static void -set_openssl_env_vars(void); +static void set_openssl_env_vars(void); void init_win32(void) @@ -167,9 +166,7 @@ } void -overlapped_io_init(struct overlapped_io *o, - const struct frame *frame, - BOOL event_state) +overlapped_io_init(struct overlapped_io *o, const struct frame *frame, BOO= L event_state) { CLEAR(*o); @@ -219,7 +216,8 @@ */ void -init_net_event_win32(struct rw_handle *event, long network_events, socket_= descriptor_t sd, unsigned int flags) +init_net_event_win32(struct rw_handle *event, long network_events, socket_= descriptor_t sd, + unsigned int flags) { /* manual reset events, initially set to unsignaled */ @@ -292,7 +290,8 @@ { if (!CloseHandle(event->read)) { - msg(M_WARN | M_ERRNO, "Warning: CloseHandle (read) failed = in close_net_event_win32"); + msg(M_WARN | M_ERRNO, + "Warning: CloseHandle (read) failed in close_net_event= _win32"); } event->read =3D NULL; } @@ -308,7 +307,8 @@ { if (!CloseHandle(event->write)) { - msg(M_WARN | M_ERRNO, "Warning: CloseHandle (write) failed= in close_net_event_win32"); + msg(M_WARN | M_ERRNO, + "Warning: CloseHandle (write) failed in close_net_even= t_win32"); } event->write =3D NULL; } @@ -332,7 +332,7 @@ ASSERT(!socket_defined(ne->sd)); ne->sd =3D sd; ne->event_mask =3D 0; - init_net_event_win32(&ne->handle, network_events, sd, NE32_PERSIST_EVE= NT|NE32_WRITE_EVENT); + init_net_event_win32(&ne->handle, network_events, sd, NE32_PERSIST_EVE= NT | NE32_WRITE_EVENT); } void @@ -406,7 +406,7 @@ ir.Event.KeyEvent.bKeyDown =3D true; if (!stdin_handle || !WriteConsoleInput(stdin_handle, &ir, 1, &tmp= )) { - msg(M_WARN|M_ERRNO, "WARN: win_trigger_event: WriteConsoleInpu= t"); + msg(M_WARN | M_ERRNO, "WARN: win_trigger_event: WriteConsoleIn= put"); } } } @@ -417,7 +417,7 @@ static bool WINAPI win_ctrl_handler(DWORD signum) { - msg(D_LOW, "win_ctrl_handler: signal received (code=3D%lu)", (unsigned= long) signum); + msg(D_LOW, "win_ctrl_handler: signal received (code=3D%lu)", (unsigned= long)signum); if (siginfo_static.signal_received =3D=3D SIGTERM) { @@ -435,7 +435,7 @@ break; default: - msg(D_LOW, "win_ctrl_handler: signal (code=3D%lu) not handled"= , (unsigned long) signum); + msg(D_LOW, "win_ctrl_handler: signal (code=3D%lu) not handled"= , (unsigned long)signum); break; } /* pass all other signals to the next handler */ @@ -449,9 +449,7 @@ } void -win32_signal_open(struct win32_signal *ws, - int force, - const char *exit_event_name, +win32_signal_open(struct win32_signal *ws, int force, const char *exit_eve= nt_name, bool exit_event_initial_state) { CLEAR(*ws); @@ -473,12 +471,10 @@ if (GetConsoleMode(ws->in.read, &ws->console_mode_save)) { /* running on a console */ - const DWORD new_console_mode =3D ws->console_mode_save - & ~(ENABLE_WINDOW_INPUT - | ENABLE_PROCESSED_INPUT - | ENABLE_LINE_INPUT - | ENABLE_ECHO_INPUT - | ENABLE_MOUSE_INPUT); + const DWORD new_console_mode =3D + ws->console_mode_save + & ~(ENABLE_WINDOW_INPUT | ENABLE_PROCESSED_INPUT | ENA= BLE_LINE_INPUT + | ENABLE_ECHO_INPUT | ENABLE_MOUSE_INPUT); if (new_console_mode !=3D ws->console_mode_save) { @@ -501,8 +497,8 @@ * If console open failed, assume we are running * as a service. */ - if ((force =3D=3D WSO_NOFORCE || force =3D=3D WSO_FORCE_SERVICE) - && !HANDLE_DEFINED(ws->in.read) && exit_event_name) + if ((force =3D=3D WSO_NOFORCE || force =3D=3D WSO_FORCE_SERVICE) && !H= ANDLE_DEFINED(ws->in.read) + && exit_event_name) { struct security_attributes sa; struct gc_arena gc =3D gc_new(); @@ -513,11 +509,11 @@ msg(M_ERR, "Error: win32_signal_open: init SA failed"); } - ws->in.read =3D CreateEventW(&sa.sa, TRUE, exit_event_initial_stat= e ? TRUE : FALSE, - exit_event_nameW); + ws->in.read =3D + CreateEventW(&sa.sa, TRUE, exit_event_initial_state ? TRUE : F= ALSE, exit_event_nameW); if (ws->in.read =3D=3D NULL) { - msg(M_WARN|M_ERRNO, "NOTE: CreateEventW '%s' failed", exit_eve= nt_name); + msg(M_WARN | M_ERRNO, "NOTE: CreateEventW '%s' failed", exit_e= vent_name); } else { @@ -533,9 +529,9 @@ gc_free(&gc); } /* set the ctrl handler in both console and service modes */ - if (!SetConsoleCtrlHandler((PHANDLER_ROUTINE) win_ctrl_handler, true)) + if (!SetConsoleCtrlHandler((PHANDLER_ROUTINE)win_ctrl_handler, true)) { - msg(M_WARN|M_ERRNO, "WARN: SetConsoleCtrlHandler failed"); + msg(M_WARN | M_ERRNO, "WARN: SetConsoleCtrlHandler failed"); } } @@ -562,8 +558,7 @@ return ir->Event.KeyEvent.wVirtualScanCode; } - if ((ir->Event.KeyEvent.dwControlKeyState - & (LEFT_ALT_PRESSED | RIGHT_ALT_PRESSED)) + if ((ir->Event.KeyEvent.dwControlKeyState & (LEFT_ALT_PRESSED | RIGHT_= ALT_PRESSED)) && (ir->Event.KeyEvent.wVirtualKeyCode !=3D 18)) { return ir->Event.KeyEvent.wVirtualScanCode * 256; @@ -625,8 +620,7 @@ { if (ws->mode =3D=3D WSO_MODE_SERVICE) { - if (HANDLE_DEFINED(ws->in.read) - && WaitForSingleObject(ws->in.read, 0) =3D=3D WAIT_OBJECT_0) + if (HANDLE_DEFINED(ws->in.read) && WaitForSingleObject(ws->in.read= , 0) =3D=3D WAIT_OBJECT_0) { return true; } @@ -683,7 +677,7 @@ { if (ws->mode =3D=3D WSO_MODE_CONSOLE && HANDLE_DEFINED(ws->in.read)) { - msg(M_INFO|M_NOPREFIX, "Press any key to continue..."); + msg(M_INFO | M_NOPREFIX, "Press any key to continue..."); do { WaitForSingleObject(ws->in.read, INFINITE); @@ -734,7 +728,8 @@ { title =3D ""; } - buf_printf(&out, "[%s] " PACKAGE_NAME " " PACKAGE_VERSION " F4:EXIT F1= :USR1 F2:USR2 F3:HUP", title); + buf_printf(&out, "[%s] " PACKAGE_NAME " " PACKAGE_VERSION " F4:EXIT F1= :USR1 F2:USR2 F3:HUP", + title); SetConsoleTitle(BSTR(&out)); gc_free(&gc); } @@ -763,7 +758,7 @@ if (s->hand =3D=3D NULL) { - msg(M_WARN|M_ERRNO, "WARNING: Cannot create Win32 semaphore '%s'",= name); + msg(M_WARN | M_ERRNO, "WARNING: Cannot create Win32 semaphore '%s'= ", name); } else { @@ -781,9 +776,10 @@ DWORD status; ASSERT(!s->locked); - dmsg(D_SEMAPHORE_LOW, "Attempting to lock Win32 semaphore '%s' pri= or to net shell command (timeout =3D %d sec)", - s->name, - timeout_milliseconds / 1000); + dmsg( + D_SEMAPHORE_LOW, + "Attempting to lock Win32 semaphore '%s' prior to net shell co= mmand (timeout =3D %d sec)", + s->name, timeout_milliseconds / 1000); status =3D WaitForSingleObject(s->hand, timeout_milliseconds); if (status =3D=3D WAIT_FAILED) { @@ -798,8 +794,7 @@ else { dmsg(D_SEMAPHORE, "Wait on Win32 semaphore '%s' timed out afte= r %d milliseconds", - s->name, - timeout_milliseconds); + s->name, timeout_milliseconds); } } return ret; @@ -814,8 +809,7 @@ dmsg(D_SEMAPHORE, "Releasing Win32 semaphore '%s'", s->name); if (!ReleaseSemaphore(s->hand, 1, NULL)) { - msg(M_WARN | M_ERRNO, "ReleaseSemaphore failed on Win32 semaph= ore '%s'", - s->name); + msg(M_WARN | M_ERRNO, "ReleaseSemaphore failed on Win32 semaph= ore '%s'", s->name); } s->locked =3D false; } @@ -906,9 +900,9 @@ nchars +=3D strlen(e->string) + 1; } - nchars +=3D strlen(force_path)+1; + nchars +=3D strlen(force_path) + 1; - ret =3D (char *) malloc(nchars); + ret =3D (char *)malloc(nchars); check_malloc_return(ret); p =3D ret; @@ -919,7 +913,7 @@ strcpy(p, e->string); p +=3D strlen(e->string) + 1; } - if (strncmp(e->string, "PATH=3D", 5 ) =3D=3D 0) + if (strncmp(e->string, "PATH=3D", 5) =3D=3D 0) { path_seen =3D true; } @@ -928,8 +922,8 @@ /* make sure PATH is set */ if (!path_seen) { - msg( M_INFO, "env_block: add %s", force_path ); - strcpy( p, force_path ); + msg(M_INFO, "env_block: add %s", force_path); + strcpy(p, force_path); p +=3D strlen(force_path) + 1; } @@ -975,7 +969,7 @@ { const char *arg =3D a->argv[i]; strcpy(work, arg); - string_mod(work, CC_PRINT, CC_DOUBLE_QUOTE|CC_CRLF, '_'); + string_mod(work, CC_PRINT, CC_DOUBLE_QUOTE | CC_CRLF, '_'); if (i) { buf_printf(&buf, " "); @@ -1026,7 +1020,8 @@ start_info.dwFlags =3D STARTF_USESHOWWINDOW; start_info.wShowWindow =3D SW_HIDE; - if (CreateProcessW(cmd, cl, NULL, NULL, FALSE, proc_flags, env= , NULL, &start_info, &proc_info)) + if (CreateProcessW(cmd, cl, NULL, NULL, FALSE, proc_flags, env= , NULL, &start_info, + &proc_info)) { DWORD exit_status =3D 0; CloseHandle(proc_info.hThread); @@ -1037,13 +1032,13 @@ } else { - msg(M_WARN|M_ERRNO, "openvpn_execve: GetExitCodeProces= s %ls failed", cmd); + msg(M_WARN | M_ERRNO, "openvpn_execve: GetExitCodeProc= ess %ls failed", cmd); } CloseHandle(proc_info.hProcess); } else { - msg(M_WARN|M_ERRNO, "openvpn_execve: CreateProcess %ls fai= led", cmd); + msg(M_WARN | M_ERRNO, "openvpn_execve: CreateProcess %ls f= ailed", cmd); } free(env); gc_free(&gc); @@ -1084,7 +1079,8 @@ status =3D GetModuleFileName(NULL, self_exe, sizeof(self_exe)); if (status =3D=3D 0 || status =3D=3D sizeof(self_exe)) { - msg(M_WARN|M_ERRNO, "fork_to_self: CreateProcess failed: cannot ge= t module name via GetModuleFileName"); + msg(M_WARN | M_ERRNO, + "fork_to_self: CreateProcess failed: cannot get module name vi= a GetModuleFileName"); goto done; } @@ -1101,7 +1097,7 @@ } else { - msg(M_WARN|M_ERRNO, "fork_to_self: CreateProcess failed: %s", cmdl= ine); + msg(M_WARN | M_ERRNO, "fork_to_self: CreateProcess failed: %s", cm= dline); } done: @@ -1134,7 +1130,8 @@ } if (status > sizeof(buf) - 1) { - msg(M_FATAL, "String overflow attempting to read environmental var= iable %s", SYS_PATH_ENV_VAR_NAME); + msg(M_FATAL, "String overflow attempting to read environmental var= iable %s", + SYS_PATH_ENV_VAR_NAME); } set_win_sys_path(buf, es); } @@ -1145,7 +1142,7 @@ DWORD status =3D GetModuleFileNameW(NULL, path, size); if (status =3D=3D 0 || status =3D=3D size) { - msg(M_WARN|M_ERRNO, "cannot get executable path"); + msg(M_WARN | M_ERRNO, "cannot get executable path"); return false; } return true; @@ -1162,8 +1159,7 @@ } else { - msg(M_WARN, "Error in WFP: %s : %s [status=3D0x%lx]", - msg, strerror_win32(err, &gc), err); + msg(M_WARN, "Error in WFP: %s : %s [status=3D0x%lx]", msg, strerro= r_win32(err, &gc), err); } gc_free(&gc); @@ -1176,15 +1172,10 @@ ack_message_t ack; struct gc_arena gc =3D gc_new(); - wfp_block_message_t data =3D { - .header =3D { - (add ? msg_add_wfp_block : msg_del_wfp_block), - sizeof(wfp_block_message_t), - 0 - }, - .flags =3D dns_only ? wfp_block_dns : wfp_block_local, - .iface =3D { .index =3D index, .name =3D "" } - }; + wfp_block_message_t data =3D { .header =3D { (add ? msg_add_wfp_block = : msg_del_wfp_block), + sizeof(wfp_block_message_t), = 0 }, + .flags =3D dns_only ? wfp_block_dns : wfp= _block_local, + .iface =3D { .index =3D index, .name =3D = "" } }; if (!send_msg_iservice(pipe, &data, sizeof(data), &ack, "WFP block")) { @@ -1193,9 +1184,10 @@ if (ack.error_number !=3D NO_ERROR) { - msg(M_WARN, "WFP block: %s block filters using service failed: %s = [status=3D0x%x if_index=3D%d]", - (add ? "adding" : "deleting"), strerror_win32(ack.error_number= , &gc), - ack.error_number, data.iface.index); + msg(M_WARN, + "WFP block: %s block filters using service failed: %s [status= =3D0x%x if_index=3D%d]", + (add ? "adding" : "deleting"), strerror_win32(ack.error_number= , &gc), ack.error_number, + data.iface.index); goto out; } @@ -1226,8 +1218,8 @@ goto out; } - status =3D add_wfp_block_filters(&m_hEngineHandle, index, openvpnpath, - win_wfp_msg_handler, dns_only); + status =3D + add_wfp_block_filters(&m_hEngineHandle, index, openvpnpath, win_wf= p_msg_handler, dns_only); if (status =3D=3D 0) { int is_auto =3D 0; @@ -1282,7 +1274,8 @@ return true; } -typedef enum { +typedef enum +{ ARCH_X86, ARCH_AMD64, ARCH_ARM64, @@ -1296,9 +1289,9 @@ *process_arch =3D ARCH_UNKNOWN; *host_arch =3D ARCH_NATIVE; - typedef BOOL (WINAPI *is_wow64_process2_t)(HANDLE, USHORT *, USHORT *); - is_wow64_process2_t is_wow64_process2 =3D (is_wow64_process2_t) - GetProcAddress(GetModuleHandle= ("Kernel32.dll"), "IsWow64Process2"); + typedef BOOL(WINAPI * is_wow64_process2_t)(HANDLE, USHORT *, USHORT *); + is_wow64_process2_t is_wow64_process2 =3D + (is_wow64_process2_t)GetProcAddress(GetModuleHandle("Kernel32.dll"= ), "IsWow64Process2"); USHORT process_machine =3D 0; USHORT native_machine =3D 0; @@ -1310,8 +1303,7 @@ if (is_wow64_process2) { /* this could be amd64 on arm64 */ - BOOL is_wow64 =3D is_wow64_process2(GetCurrentProcess(), - &process_machine, &native_machin= e); + BOOL is_wow64 =3D is_wow64_process2(GetCurrentProcess(), &process_= machine, &native_machine); if (is_wow64 && native_machine =3D=3D IMAGE_FILE_MACHINE_ARM64) { *host_arch =3D ARCH_ARM64; @@ -1323,8 +1315,7 @@ if (is_wow64_process2) { /* check if we're running on arm64 or amd64 machine */ - BOOL is_wow64 =3D is_wow64_process2(GetCurrentProcess(), - &process_machine, &native_machin= e); + BOOL is_wow64 =3D is_wow64_process2(GetCurrentProcess(), &process_= machine, &native_machine); if (is_wow64) { switch (native_machine) @@ -1383,7 +1374,7 @@ } } -typedef LONG (WINAPI *RtlGetVersionPtr)(PRTL_OSVERSIONINFOW); +typedef LONG(WINAPI *RtlGetVersionPtr)(PRTL_OSVERSIONINFOW); const char * win32_version_string(struct gc_arena *gc) @@ -1428,18 +1419,16 @@ } bool -send_msg_iservice(HANDLE pipe, const void *data, size_t size, - ack_message_t *ack, const char *context) +send_msg_iservice(HANDLE pipe, const void *data, size_t size, ack_message_= t *ack, + const char *context) { struct gc_arena gc =3D gc_new(); DWORD len; bool ret =3D true; - if (!WriteFile(pipe, data, size, &len, NULL) - || !ReadFile(pipe, ack, sizeof(*ack), &len, NULL)) + if (!WriteFile(pipe, data, size, &len, NULL) || !ReadFile(pipe, ack, s= izeof(*ack), &len, NULL)) { - msg(M_WARN, "%s: could not talk to service: %s [%lu]", - context ? context : "Unknown", + msg(M_WARN, "%s: could not talk to service: %s [%lu]", context ? c= ontext : "Unknown", strerror_win32(GetLastError(), &gc), GetLastError()); ret =3D false; } @@ -1487,14 +1476,13 @@ install_path[wcslen(install_path) - 1] =3D L'\0'; } - static struct { + static struct + { WCHAR *name; WCHAR *value; - } ossl_env[] =3D { - {L"OPENSSL_CONF", L"openssl.cnf"}, - {L"OPENSSL_ENGINES", L"engines"}, - {L"OPENSSL_MODULES", L"modules"} - }; + } ossl_env[] =3D { { L"OPENSSL_CONF", L"openssl.cnf" }, + { L"OPENSSL_ENGINES", L"engines" }, + { L"OPENSSL_MODULES", L"modules" } }; for (size_t i =3D 0; i < SIZE(ossl_env); ++i) { @@ -1503,7 +1491,7 @@ _wgetenv_s(&size, NULL, 0, ossl_env[i].name); if (size =3D=3D 0) { - WCHAR val[MAX_PATH] =3D {0}; + WCHAR val[MAX_PATH] =3D { 0 }; swprintf(val, _countof(val), L"%ls\\ssl\\%ls", install_path, o= ssl_env[i].value); _wputenv_s(ossl_env[i].name, val); } @@ -1524,7 +1512,7 @@ { if (n > 0) { - Sleep(n*1000); + Sleep(n * 1000); } return; } @@ -1534,9 +1522,8 @@ while (expire >=3D now) { - DWORD status =3D WaitForSingleObject(win32_signal.in.read, (expire= -now)*1000); - if ((status =3D=3D WAIT_OBJECT_0 && win32_signal_get(&win32_signal= )) - || status =3D=3D WAIT_TIMEOUT) + DWORD status =3D WaitForSingleObject(win32_signal.in.read, (expire= - now) * 1000); + if ((status =3D=3D WAIT_OBJECT_0 && win32_signal_get(&win32_signal= )) || status =3D=3D WAIT_TIMEOUT) { return; } @@ -1547,7 +1534,7 @@ { if (expire > now) { - Sleep((expire-now)*1000); + Sleep((expire - now) * 1000); } return; } @@ -1599,8 +1586,8 @@ } /* Check if the plugin path resides within the plugin/install director= y */ - if ((wcslen(normalized_plugin_dir) > 0) && (wcsnicmp(normalized_plugin= _dir, - plugin_path, wcsl= en(normalized_plugin_dir)) =3D=3D 0)) + if ((wcslen(normalized_plugin_dir) > 0) + && (wcsnicmp(normalized_plugin_dir, plugin_path, wcslen(normalized= _plugin_dir)) =3D=3D 0)) { return true; } diff --git a/src/openvpn/win32.h b/src/openvpn/win32.h index 34d18c6..dbfa5bc 100644 --- a/src/openvpn/win32.h +++ b/src/openvpn/win32.h @@ -34,12 +34,13 @@ #include "win32-util.h" /* location of executables */ -#define SYS_PATH_ENV_VAR_NAME "SystemRoot" /* environmental variable name= that normally contains the system path */ -#define NETSH_PATH_SUFFIX "\\system32\\netsh.exe" -#define WIN_ROUTE_PATH_SUFFIX "\\system32\\route.exe" +#define SYS_PATH_ENV_VAR_NAME \ + "SystemRoot" /* environmental variable name that normally contains the= system path */ +#define NETSH_PATH_SUFFIX "\\system32\\netsh.exe" +#define WIN_ROUTE_PATH_SUFFIX "\\system32\\route.exe" #define WIN_IPCONFIG_PATH_SUFFIX "\\system32\\ipconfig.exe" -#define WIN_NET_PATH_SUFFIX "\\system32\\net.exe" -#define WMIC_PATH_SUFFIX "\\system32\\wbem\\wmic.exe" +#define WIN_NET_PATH_SUFFIX "\\system32\\net.exe" +#define WMIC_PATH_SUFFIX "\\system32\\wbem\\wmic.exe" /* * Win32-specific OpenVPN code, targeted at the mingw @@ -75,7 +76,8 @@ char old_window_title[256]; }; -struct rw_handle { +struct rw_handle +{ HANDLE read; HANDLE write; }; @@ -84,8 +86,8 @@ * Event-based notification of incoming TCP connections */ -#define NE32_PERSIST_EVENT (1<<0) -#define NE32_WRITE_EVENT (1<<1) +#define NE32_PERSIST_EVENT (1 << 0) +#define NE32_WRITE_EVENT (1 << 1) static inline bool defined_net_event_win32(const struct rw_handle *event) @@ -93,7 +95,8 @@ return event->read !=3D NULL; } -void init_net_event_win32(struct rw_handle *event, long network_events, so= cket_descriptor_t sd, unsigned int flags); +void init_net_event_win32(struct rw_handle *event, long network_events, so= cket_descriptor_t sd, + unsigned int flags); long reset_net_event_win32(struct rw_handle *event, socket_descriptor_t sd= ); @@ -149,7 +152,8 @@ /* * Signal handling */ -struct win32_signal { +struct win32_signal +{ #define WSO_MODE_UNDEF 0 #define WSO_MODE_SERVICE 1 #define WSO_MODE_CONSOLE 2 @@ -169,10 +173,8 @@ #define WSO_FORCE_SERVICE 1 #define WSO_FORCE_CONSOLE 2 -void win32_signal_open(struct win32_signal *ws, - int force, /* set to WSO force parm */ - const char *exit_event_name, - bool exit_event_initial_state); +void win32_signal_open(struct win32_signal *ws, int force, /* set to WSO f= orce parm */ + const char *exit_event_name, bool exit_event_initia= l_state); void win32_signal_close(struct win32_signal *ws); @@ -198,17 +200,19 @@ * We try to do all Win32 I/O using overlapped * (i.e. asynchronous) I/O for a performance win. */ -struct overlapped_io { +struct overlapped_io +{ #define IOSTATE_INITIAL 0 -#define IOSTATE_QUEUED 1 /* overlapped I/O has been queued */ -#define IOSTATE_IMMEDIATE_RETURN 2 /* I/O function returned immediately w= ithout queueing */ +#define IOSTATE_QUEUED 1 /* overlapped I/O has been queued */ +#define IOSTATE_IMMEDIATE_RETURN 2 /* I/O function returned immediately wi= thout queueing */ int iostate; OVERLAPPED overlapped; DWORD size; DWORD flags; int status; bool addr_defined; - union { + union + { struct sockaddr_in addr; struct sockaddr_in6 addr6; }; @@ -217,9 +221,7 @@ struct buffer buf; }; -void overlapped_io_init(struct overlapped_io *o, - const struct frame *frame, - BOOL event_state); +void overlapped_io_init(struct overlapped_io *o, const struct frame *frame= , BOOL event_state); void overlapped_io_close(struct overlapped_io *o); @@ -304,14 +306,13 @@ * and read the result in |ack|. Returns false on communication error. * The string in |context| is used to prefix error messages. */ -bool send_msg_iservice(HANDLE pipe, const void *data, size_t size, - ack_message_t *ack, const char *context); +bool send_msg_iservice(HANDLE pipe, const void *data, size_t size, ack_mes= sage_t *ack, + const char *context); /* * Attempt to simulate fork/execve on Windows */ -int -openvpn_execve(const struct argv *a, const struct env_set *es, const unsig= ned int flags); +int openvpn_execve(const struct argv *a, const struct env_set *es, const u= nsigned int flags); /* Sleep that can be interrupted by signals and exit event */ void win32_sleep(const int n); @@ -324,8 +325,7 @@ * @param size Size of `value` buffer in bytes. * @return `true` if successful, `false` otherwise. */ -bool -get_openvpn_reg_value(const WCHAR *key, WCHAR *value, DWORD size); +bool get_openvpn_reg_value(const WCHAR *key, WCHAR *value, DWORD size); /** * @brief Checks if a plugin is located in a trusted directory. @@ -340,8 +340,7 @@ * @param plugin_path Normalized path to the plugin. * @return \c true if the plugin is in a trusted directory and not a UNC p= ath; \c false otherwise. */ -bool -plugin_in_trusted_dir(const WCHAR *plugin_path); +bool plugin_in_trusted_dir(const WCHAR *plugin_path); /** * Encrypt a region of memory using CryptProtectMemory() @@ -351,8 +350,7 @@ * - len number of bytes to encrypt -- must be a multiple of * CRYPTPROTECTMEMORY_BLOCK_SIZE =3D 16 */ -bool -protect_buffer_win32(char *buf, size_t len); +bool protect_buffer_win32(char *buf, size_t len); /** * Decrypt a previously encrypted region of memory using CryptUnProtectMem= ory() @@ -362,8 +360,7 @@ * - len number of bytes to encrypt -- must be a multiple of * CRYPTPROTECTMEMORY_BLOCK_SIZE =3D 16 */ -bool -unprotect_buffer_win32(char *buf, size_t len); +bool unprotect_buffer_win32(char *buf, size_t len); #endif /* ifndef OPENVPN_WIN32_H */ #endif /* ifdef _WIN32 */ diff --git a/src/openvpn/xkey_common.h b/src/openvpn/xkey_common.h index 111596e..3d65e1f 100644 --- a/src/openvpn/xkey_common.h +++ b/src/openvpn/xkey_common.h @@ -46,12 +46,13 @@ * Struct to encapsulate signature algorithm parameters to pass * to sign operation. */ -typedef struct { +typedef struct +{ const char *padmode; /**< "pkcs1", "pss" or "none" */ - const char *mdname; /**< "SHA256" or "SHA2-256" etc. */ + const char *mdname; /**< "SHA256" or "SHA2-256" etc. */ const char *saltlen; /**< "digest", "auto" or "max" */ const char *keytype; /**< "EC" or "RSA" */ - const char *op; /**< "Sign" or "DigestSign" */ + const char *op; /**< "Sign" or "DigestSign" */ } XKEY_SIGALG; /** @@ -78,15 +79,14 @@ * before signing. The digest algorithm used (or to be used) is passed in = the sigalg * structure. */ -typedef int (XKEY_EXTERNAL_SIGN_fn)(void *handle, unsigned char *sig, size= _t *siglen, - const unsigned char *tbs, size_t tbsle= n, - XKEY_SIGALG sigalg); +typedef int(XKEY_EXTERNAL_SIGN_fn)(void *handle, unsigned char *sig, size_= t *siglen, + const unsigned char *tbs, size_t tbslen= , XKEY_SIGALG sigalg); /** * Signature of private key free function callback used * to free the opaque private key handle obtained from the * backend. Not required for management-external-key. */ -typedef void (XKEY_PRIVKEY_FREE_fn)(void *handle); +typedef void(XKEY_PRIVKEY_FREE_fn)(void *handle); /** * Generate an encapsulated EVP_PKEY for management-external-key @@ -115,9 +115,8 @@ * to the required size and false is returned. * */ -bool -encode_pkcs1(unsigned char *enc, size_t *enc_len, const char *mdname, - const unsigned char *tbs, size_t tbslen); +bool encode_pkcs1(unsigned char *enc, size_t *enc_len, const char *mdname,= const unsigned char *tbs, + size_t tbslen); /** * Compute message digest @@ -133,9 +132,8 @@ * On successful return *buflen is set to the actual size of the result. * TIP: EVP_MD_MAX_SIZE should be enough capacity of buf for al algorithms. */ -int -xkey_digest(const unsigned char *src, size_t srclen, unsigned char *buf, - size_t *buflen, const char *mdname); +int xkey_digest(const unsigned char *src, size_t srclen, unsigned char *bu= f, size_t *buflen, + const char *mdname); /** * Load a generic external key with custom sign and free ops @@ -150,9 +148,8 @@ * IMPORTANT: a reference to the handle is retained by the provider and * relased by calling free_op. The caller should not free it. */ -EVP_PKEY * -xkey_load_generic_key(OSSL_LIB_CTX *libctx, void *handle, EVP_PKEY *pubkey, - XKEY_EXTERNAL_SIGN_fn *sign_op, XKEY_PRIVKEY_FREE_fn= *free_op); +EVP_PKEY *xkey_load_generic_key(OSSL_LIB_CTX *libctx, void *handle, EVP_PK= EY *pubkey, + XKEY_EXTERNAL_SIGN_fn *sign_op, XKEY_PRIVK= EY_FREE_fn *free_op); extern OSSL_LIB_CTX *tls_libctx; /* Global */ @@ -166,7 +163,7 @@ static inline int xkey_max_saltlen(int modBits, int hLen) { - int emLen =3D (modBits - 1 + 7)/8; /* ceil((modBits - 1)/8) */ + int emLen =3D (modBits - 1 + 7) / 8; /* ceil((modBits - 1)/8) */ return emLen - hLen - 2; } @@ -181,8 +178,7 @@ * @returns the size of the converted signature or <=3D 0 on error. * On success, buf is overwritten by its DER encoding */ -int -ecdsa_bin2der(unsigned char *buf, int len, size_t capacity); +int ecdsa_bin2der(unsigned char *buf, int len, size_t capacity); #endif /* HAVE_XKEY_PROVIDER */ diff --git a/src/openvpn/xkey_helper.c b/src/openvpn/xkey_helper.c index 487bfe6..f4a9948 100644 --- a/src/openvpn/xkey_helper.c +++ b/src/openvpn/xkey_helper.c @@ -59,8 +59,8 @@ /** helper to compute digest */ int -xkey_digest(const unsigned char *src, size_t srclen, unsigned char *buf, - size_t *buflen, const char *mdname) +xkey_digest(const unsigned char *src, size_t srclen, unsigned char *buf, s= ize_t *buflen, + const char *mdname) { dmsg(D_XKEY, "In xkey_digest"); EVP_MD *md =3D EVP_MD_fetch(NULL, mdname, NULL); /* from default conte= xt */ @@ -70,7 +70,7 @@ return 0; } - unsigned int len =3D (unsigned int) *buflen; + unsigned int len =3D (unsigned int)*buflen; if (EVP_Digest(src, srclen, buf, &len, md, NULL) !=3D 1) { msg(M_WARN, "WARN: xkey_digest: EVP_Digest failed"); @@ -121,18 +121,17 @@ /* UTF8 string pointers in here are only read from, so cast is safe */ OSSL_PARAM params[] =3D { - {"xkey-origin", OSSL_PARAM_UTF8_STRING, (char *) origin, 0, 0}, - {"pubkey", OSSL_PARAM_OCTET_STRING, &pubkey, sizeof(pubkey), 0}, - {"handle", OSSL_PARAM_OCTET_PTR, &handle, sizeof(handle), 0}, - {"sign_op", OSSL_PARAM_OCTET_PTR, (void **) &sign_op, sizeof(sign_= op), 0}, - {"free_op", OSSL_PARAM_OCTET_PTR, (void **) &free_op, sizeof(free_= op), 0}, - {NULL, 0, NULL, 0, 0} + { "xkey-origin", OSSL_PARAM_UTF8_STRING, (char *)origin, 0, 0 }, + { "pubkey", OSSL_PARAM_OCTET_STRING, &pubkey, sizeof(pubkey), 0 }, + { "handle", OSSL_PARAM_OCTET_PTR, &handle, sizeof(handle), 0 }, + { "sign_op", OSSL_PARAM_OCTET_PTR, (void **)&sign_op, sizeof(sign_= op), 0 }, + { "free_op", OSSL_PARAM_OCTET_PTR, (void **)&free_op, sizeof(free_= op), 0 }, + { NULL, 0, NULL, 0, 0 } }; /* Do not use EVP_PKEY_new_from_pkey as that will take keymgmt from pu= bkey */ EVP_PKEY_CTX *ctx =3D EVP_PKEY_CTX_new_from_name(libctx, EVP_PKEY_get0= _type_name(pubkey), props); - if (!ctx - || EVP_PKEY_fromdata_init(ctx) !=3D 1 + if (!ctx || EVP_PKEY_fromdata_init(ctx) !=3D 1 || EVP_PKEY_fromdata(ctx, &pkey, EVP_PKEY_KEYPAIR, params) !=3D 1) { print_openssl_errors(); @@ -161,13 +160,12 @@ * @return signature length or -1 on error. */ int -xkey_management_sign(void *unused, unsigned char *sig, size_t *siglen, - const unsigned char *tbs, size_t tbslen, XKEY_SIGALG = alg) +xkey_management_sign(void *unused, unsigned char *sig, size_t *siglen, con= st unsigned char *tbs, + size_t tbslen, XKEY_SIGALG alg) { - dmsg(D_XKEY, "In xkey_management_sign with keytype =3D %s, op =3D %s", - alg.keytype, alg.op); + dmsg(D_XKEY, "In xkey_management_sign with keytype =3D %s, op =3D %s",= alg.keytype, alg.op); - (void) unused; + (void)unused; char alg_str[128]; unsigned char buf[EVP_MAX_MD_SIZE]; /* for computing digest if require= d */ size_t buflen =3D sizeof(buf); @@ -228,8 +226,7 @@ /* For undigested message, add hashalg=3Ddigest parameter */ else { - snprintf(alg_str, sizeof(alg_str), "%s,hashalg=3D%s", - "RSA_PKCS1_PADDING", alg.mdname); + snprintf(alg_str, sizeof(alg_str), "%s,hashalg=3D%s", "RSA_PKC= S1_PADDING", alg.mdname); } } else if (!strcmp(alg.padmode, "none") && (flags & MF_EXTERNAL_KEY_NOPA= DDING) @@ -239,13 +236,12 @@ } else if (!strcmp(alg.padmode, "pss") && (flags & MF_EXTERNAL_KEY_PSSPA= D)) { - snprintf(alg_str, sizeof(alg_str), "%s,hashalg=3D%s,saltlen=3D%s", - "RSA_PKCS1_PSS_PADDING", alg.mdname, alg.saltlen); + snprintf(alg_str, sizeof(alg_str), "%s,hashalg=3D%s,saltlen=3D%s",= "RSA_PKCS1_PSS_PADDING", + alg.mdname, alg.saltlen); } else { - msg(M_NONFATAL, "RSA padding mode not supported by management-clie= nt <%s>", - alg.padmode); + msg(M_NONFATAL, "RSA padding mode not supported by management-clie= nt <%s>", alg.padmode); return 0; } @@ -260,7 +256,7 @@ char *out_b64 =3D NULL; int len =3D -1; - int bencret =3D openvpn_base64_encode(tbs, (int) tbslen, &in_b64); + int bencret =3D openvpn_base64_encode(tbs, (int)tbslen, &in_b64); if (management && bencret > 0) { @@ -268,7 +264,7 @@ } if (out_b64) { - len =3D openvpn_base64_decode(out_b64, sig, (int) *siglen); + len =3D openvpn_base64_decode(out_b64, sig, (int)*siglen); } free(in_b64); free(out_b64); @@ -295,8 +291,8 @@ * to the required size and false is returned. */ bool -encode_pkcs1(unsigned char *enc, size_t *enc_len, const char *mdname, - const unsigned char *tbs, size_t tbslen) +encode_pkcs1(unsigned char *enc, size_t *enc_len, const char *mdname, cons= t unsigned char *tbs, + size_t tbslen) { ASSERT(enc_len !=3D NULL); ASSERT(tbs !=3D NULL); @@ -309,32 +305,34 @@ * Also see the table in RFC 8017 section 9.2, Note 1. */ - const unsigned char sha1[] =3D {0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x= 2b, - 0x0e, 0x03, 0x02, 0x1a, 0x05, 0x00, 0x04= , 0x14}; - const unsigned char sha256[] =3D {0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, = 0x60, 0x86, 0x48, - 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x= 05, 0x00, 0x04, 0x20}; - const unsigned char sha384[] =3D {0x30, 0x41, 0x30, 0x0d, 0x06, 0x09, = 0x60, 0x86, 0x48, - 0x01, 0x65, 0x03, 0x04, 0x02, 0x02, 0x= 05, 0x00, 0x04, 0x30}; - const unsigned char sha512[] =3D {0x30, 0x51, 0x30, 0x0d, 0x06, 0x09, = 0x60, 0x86, 0x48, - 0x01, 0x65, 0x03, 0x04, 0x02, 0x03, 0x= 05, 0x00, 0x04, 0x40}; - const unsigned char sha224[] =3D {0x30, 0x2d, 0x30, 0x0d, 0x06, 0x09, = 0x60, 0x86, 0x48, - 0x01, 0x65, 0x03, 0x04, 0x02, 0x04, 0x= 05, 0x00, 0x04, 0x1c}; - const unsigned char sha512_224[] =3D {0x30, 0x2d, 0x30, 0x0d, 0x06, 0x= 09, 0x60, 0x86, 0x48, - 0x01, 0x65, 0x03, 0x04, 0x02, 0x05= , 0x05, 0x00, 0x04, 0x1c}; - const unsigned char sha512_256[] =3D {0x30, 0x31, 0x30, 0x0d, 0x06, 0x= 09, 0x60, 0x86, 0x48, - 0x01, 0x65, 0x03, 0x04, 0x02, 0x06= , 0x05, 0x00, 0x04, 0x20}; + const unsigned char sha1[] =3D { 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0= x2b, 0x0e, + 0x03, 0x02, 0x1a, 0x05, 0x00, 0x04, 0x1= 4 }; + const unsigned char sha256[] =3D { 0x30, 0x31, 0x30, 0x0d, 0x06, 0x09,= 0x60, 0x86, 0x48, 0x01, + 0x65, 0x03, 0x04, 0x02, 0x01, 0x05, 0= x00, 0x04, 0x20 }; + const unsigned char sha384[] =3D { 0x30, 0x41, 0x30, 0x0d, 0x06, 0x09,= 0x60, 0x86, 0x48, 0x01, + 0x65, 0x03, 0x04, 0x02, 0x02, 0x05, 0= x00, 0x04, 0x30 }; + const unsigned char sha512[] =3D { 0x30, 0x51, 0x30, 0x0d, 0x06, 0x09,= 0x60, 0x86, 0x48, 0x01, + 0x65, 0x03, 0x04, 0x02, 0x03, 0x05, 0= x00, 0x04, 0x40 }; + const unsigned char sha224[] =3D { 0x30, 0x2d, 0x30, 0x0d, 0x06, 0x09,= 0x60, 0x86, 0x48, 0x01, + 0x65, 0x03, 0x04, 0x02, 0x04, 0x05, 0= x00, 0x04, 0x1c }; + const unsigned char sha512_224[] =3D { 0x30, 0x2d, 0x30, 0x0d, 0x06, 0= x09, 0x60, 0x86, 0x48, 0x01, + 0x65, 0x03, 0x04, 0x02, 0x05, 0x0= 5, 0x00, 0x04, 0x1c }; + const unsigned char sha512_256[] =3D { 0x30, 0x31, 0x30, 0x0d, 0x06, 0= x09, 0x60, 0x86, 0x48, 0x01, + 0x65, 0x03, 0x04, 0x02, 0x06, 0x0= 5, 0x00, 0x04, 0x20 }; - typedef struct { + typedef struct + { const int nid; const unsigned char *header; size_t sz; } DIG_INFO; -#define MAKE_DI(x) {NID_ ## x, x, sizeof(x)} +#define MAKE_DI(x) { NID_##x, x, sizeof(x) } - DIG_INFO dinfo[] =3D {MAKE_DI(sha1), MAKE_DI(sha256), MAKE_DI(sha384), - MAKE_DI(sha512), MAKE_DI(sha224), MAKE_DI(sha512_2= 24), - MAKE_DI(sha512_256), {0, NULL, 0}}; + DIG_INFO dinfo[] =3D { + MAKE_DI(sha1), MAKE_DI(sha256), MAKE_DI(sha384), MAKE_DI= (sha512), + MAKE_DI(sha224), MAKE_DI(sha512_224), MAKE_DI(sha512_256), { 0, NU= LL, 0 } + }; size_t out_len =3D 0; bool ret =3D false; @@ -387,8 +385,7 @@ /* combine header and digest */ memcpy(enc, di->header, di->sz); memcpy(enc + di->sz, tbs, tbslen); - dmsg(D_XKEY, "encode_pkcs1: digest length =3D %zu encoded length = =3D %zu", - tbslen, out_len); + dmsg(D_XKEY, "encode_pkcs1: digest length =3D %zu encoded length = =3D %zu", tbslen, out_len); ret =3D true; } @@ -408,9 +405,9 @@ ecdsa_bin2der(unsigned char *buf, int len, size_t capacity) { ECDSA_SIG *ecsig =3D NULL; - int rlen =3D len/2; + int rlen =3D len / 2; BIGNUM *r =3D BN_bin2bn(buf, rlen, NULL); - BIGNUM *s =3D BN_bin2bn(buf+rlen, rlen, NULL); + BIGNUM *s =3D BN_bin2bn(buf + rlen, rlen, NULL); if (!r || !s) { goto err; @@ -427,7 +424,7 @@ } int derlen =3D i2d_ECDSA_SIG(ecsig, NULL); - if (derlen > (int) capacity) + if (derlen > (int)capacity) { ECDSA_SIG_free(ecsig); msg(M_NONFATAL, "Error: DER encoded ECDSA signature is too long (%= d)\n", derlen); diff --git a/src/openvpn/xkey_provider.c b/src/openvpn/xkey_provider.c index edd64d3..1819ab0 100644 --- a/src/openvpn/xkey_provider.c +++ b/src/openvpn/xkey_provider.c @@ -46,15 +46,16 @@ typedef struct { - OSSL_LIB_CTX *libctx; /**< a child libctx for our own use */ + OSSL_LIB_CTX *libctx; /**< a child libctx for our own use */ } XKEY_PROVIDER_CTX; /* helper to print debug messages */ -#define xkey_dmsg(f, ...) \ - do { \ - dmsg(f|M_NOLF, "xkey_provider: In %s: ", __func__); \ - dmsg(f|M_NOPREFIX, __VA_ARGS__); \ - } while(0) +#define xkey_dmsg(f, ...) \ + do \ + { \ + dmsg(f | M_NOLF, "xkey_provider: In %s: ", __func__); \ + dmsg(f | M_NOPREFIX, __VA_ARGS__); \ + } while (0) typedef enum { @@ -93,7 +94,7 @@ /** keydata handle free function of backend */ XKEY_PRIVKEY_FREE_fn *free; XKEY_PROVIDER_CTX *prov; - int refcount; /**< reference count */ + int refcount; /**< reference count */ } XKEY_KEYDATA; static inline const char * @@ -128,9 +129,8 @@ * Helper sign function for native keys * Implemented using OpenSSL calls. */ -int -xkey_native_sign(XKEY_KEYDATA *key, unsigned char *sig, size_t *siglen, - const unsigned char *tbs, size_t tbslen, XKEY_SIGALG siga= lg); +int xkey_native_sign(XKEY_KEYDATA *key, unsigned char *sig, size_t *siglen, + const unsigned char *tbs, size_t tbslen, XKEY_SIGALG = sigalg); /* keymgmt provider */ @@ -150,8 +150,7 @@ static OSSL_FUNC_keymgmt_query_operation_name_fn rsa_keymgmt_name; static OSSL_FUNC_keymgmt_query_operation_name_fn ec_keymgmt_name; -static int -keymgmt_import_helper(XKEY_KEYDATA *key, const OSSL_PARAM params[]); +static int keymgmt_import_helper(XKEY_KEYDATA *key, const OSSL_PARAM param= s[]); static XKEY_KEYDATA * keydata_new(void) @@ -273,9 +272,8 @@ int selection_pub =3D selection & ~OSSL_KEYMGMT_SELECT_PRIVATE_KEY; EVP_PKEY_CTX *ctx =3D EVP_PKEY_CTX_new_from_name(key->prov->libctx, na= me, NULL); - if (!ctx - || (EVP_PKEY_fromdata_init(ctx) !=3D 1) - || (EVP_PKEY_fromdata(ctx, &pkey, selection_pub, (OSSL_PARAM *) pa= rams) !=3D1)) + if (!ctx || (EVP_PKEY_fromdata_init(ctx) !=3D 1) + || (EVP_PKEY_fromdata(ctx, &pkey, selection_pub, (OSSL_PARAM *)par= ams) !=3D 1)) { msg(M_WARN, "Error: keymgmt_import failed for key type <%s>", name= ); if (pkey) @@ -295,10 +293,10 @@ { /* create private key */ pkey =3D NULL; - if (EVP_PKEY_fromdata(ctx, &pkey, selection, (OSSL_PARAM *) params= ) =3D=3D 1) + if (EVP_PKEY_fromdata(ctx, &pkey, selection, (OSSL_PARAM *)params)= =3D=3D 1) { key->handle =3D pkey; - key->free =3D (XKEY_PRIVKEY_FREE_fn *) EVP_PKEY_free; + key->free =3D (XKEY_PRIVKEY_FREE_fn *)EVP_PKEY_free; } } EVP_PKEY_CTX_free(ctx); @@ -419,12 +417,10 @@ { xkey_dmsg(D_XKEY, "entry"); - static OSSL_PARAM gettable[] =3D { - OSSL_PARAM_int(OSSL_PKEY_PARAM_BITS, NULL), - OSSL_PARAM_int(OSSL_PKEY_PARAM_SECURITY_BITS, NULL), - OSSL_PARAM_int(OSSL_PKEY_PARAM_MAX_SIZE, NULL), - OSSL_PARAM_END - }; + static OSSL_PARAM gettable[] =3D { OSSL_PARAM_int(OSSL_PKEY_PARAM_BITS= , NULL), + OSSL_PARAM_int(OSSL_PKEY_PARAM_SECURI= TY_BITS, NULL), + OSSL_PARAM_int(OSSL_PKEY_PARAM_MAX_SI= ZE, NULL), + OSSL_PARAM_END }; return gettable; } @@ -471,14 +467,14 @@ /* only check params we understand and ignore the rest */ p =3D OSSL_PARAM_locate_const(params, "pubkey"); /*setting pubkey on o= ur keydata */ - if (p && p->data_type =3D=3D OSSL_PARAM_OCTET_STRING - && p->data_size =3D=3D sizeof(pkey)) + if (p && p->data_type =3D=3D OSSL_PARAM_OCTET_STRING && p->data_size = =3D=3D sizeof(pkey)) { pkey =3D *(EVP_PKEY **)p->data; ASSERT(pkey); int id =3D EVP_PKEY_get_id(pkey); - if (id !=3D EVP_PKEY_RSA && id !=3D EVP_PKEY_EC && id !=3D EVP_PKE= Y_ED25519 && id !=3D EVP_PKEY_ED448) + if (id !=3D EVP_PKEY_RSA && id !=3D EVP_PKEY_EC && id !=3D EVP_PKE= Y_ED25519 + && id !=3D EVP_PKEY_ED448) { msg(M_WARN, "Error: xkey keymgmt_import: unknown key type (%d)= ", id); return 0; @@ -493,8 +489,7 @@ } p =3D OSSL_PARAM_locate_const(params, "handle"); /*setting privkey */ - if (p && p->data_type =3D=3D OSSL_PARAM_OCTET_PTR - && p->data_size =3D=3D sizeof(key->handle)) + if (p && p->data_type =3D=3D OSSL_PARAM_OCTET_PTR && p->data_size =3D= =3D sizeof(key->handle)) { key->handle =3D *(void **)p->data; /* caller should keep the reference alive until we call free */ @@ -502,8 +497,7 @@ } p =3D OSSL_PARAM_locate_const(params, "sign_op"); /*setting sign_op */ - if (p && p->data_type =3D=3D OSSL_PARAM_OCTET_PTR - && p->data_size =3D=3D sizeof(key->sign)) + if (p && p->data_type =3D=3D OSSL_PARAM_OCTET_PTR && p->data_size =3D= =3D sizeof(key->sign)) { key->sign =3D *(void **)p->data; ASSERT(key->sign); /* fix your params array */ @@ -511,8 +505,7 @@ /* optional parameters */ p =3D OSSL_PARAM_locate_const(params, "free_op"); /*setting free_op */ - if (p && p->data_type =3D=3D OSSL_PARAM_OCTET_PTR - && p->data_size =3D=3D sizeof(key->free)) + if (p && p->data_type =3D=3D OSSL_PARAM_OCTET_PTR && p->data_size =3D= =3D sizeof(key->free)) { key->free =3D *(void **)p->data; } @@ -586,75 +579,80 @@ } static const OSSL_DISPATCH rsa_keymgmt_functions[] =3D { - {OSSL_FUNC_KEYMGMT_NEW, (void (*)(void))keymgmt_new}, - {OSSL_FUNC_KEYMGMT_FREE, (void (*)(void))keymgmt_free}, - {OSSL_FUNC_KEYMGMT_LOAD, (void (*)(void))keymgmt_load}, - {OSSL_FUNC_KEYMGMT_HAS, (void (*)(void))keymgmt_has}, - {OSSL_FUNC_KEYMGMT_MATCH, (void (*)(void))keymgmt_match}, - {OSSL_FUNC_KEYMGMT_IMPORT, (void (*)(void))rsa_keymgmt_import}, - {OSSL_FUNC_KEYMGMT_IMPORT_TYPES, (void (*)(void))keymgmt_import_types}, - {OSSL_FUNC_KEYMGMT_GETTABLE_PARAMS, (void (*)(void))keymgmt_gettable_p= arams}, - {OSSL_FUNC_KEYMGMT_GET_PARAMS, (void (*)(void))keymgmt_get_params}, - {OSSL_FUNC_KEYMGMT_SET_PARAMS, (void (*)(void))keymgmt_set_params}, - {OSSL_FUNC_KEYMGMT_SETTABLE_PARAMS, (void (*)(void))keymgmt_gettable_p= arams}, /* same as gettable */ - {OSSL_FUNC_KEYMGMT_QUERY_OPERATION_NAME, (void (*)(void))rsa_keymgmt_n= ame}, - {0, NULL } + { OSSL_FUNC_KEYMGMT_NEW, (void (*)(void))keymgmt_new }, + { OSSL_FUNC_KEYMGMT_FREE, (void (*)(void))keymgmt_free }, + { OSSL_FUNC_KEYMGMT_LOAD, (void (*)(void))keymgmt_load }, + { OSSL_FUNC_KEYMGMT_HAS, (void (*)(void))keymgmt_has }, + { OSSL_FUNC_KEYMGMT_MATCH, (void (*)(void))keymgmt_match }, + { OSSL_FUNC_KEYMGMT_IMPORT, (void (*)(void))rsa_keymgmt_import }, + { OSSL_FUNC_KEYMGMT_IMPORT_TYPES, (void (*)(void))keymgmt_import_types= }, + { OSSL_FUNC_KEYMGMT_GETTABLE_PARAMS, (void (*)(void))keymgmt_gettable_= params }, + { OSSL_FUNC_KEYMGMT_GET_PARAMS, (void (*)(void))keymgmt_get_params }, + { OSSL_FUNC_KEYMGMT_SET_PARAMS, (void (*)(void))keymgmt_set_params }, + { OSSL_FUNC_KEYMGMT_SETTABLE_PARAMS, + (void (*)(void))keymgmt_gettable_params }, /* same as gettable */ + { OSSL_FUNC_KEYMGMT_QUERY_OPERATION_NAME, (void (*)(void))rsa_keymgmt_= name }, + { 0, NULL } }; static const OSSL_DISPATCH ec_keymgmt_functions[] =3D { - {OSSL_FUNC_KEYMGMT_NEW, (void (*)(void))keymgmt_new}, - {OSSL_FUNC_KEYMGMT_FREE, (void (*)(void))keymgmt_free}, - {OSSL_FUNC_KEYMGMT_LOAD, (void (*)(void))keymgmt_load}, - {OSSL_FUNC_KEYMGMT_HAS, (void (*)(void))keymgmt_has}, - {OSSL_FUNC_KEYMGMT_MATCH, (void (*)(void))keymgmt_match}, - {OSSL_FUNC_KEYMGMT_IMPORT, (void (*)(void))ec_keymgmt_import}, - {OSSL_FUNC_KEYMGMT_IMPORT_TYPES, (void (*)(void))keymgmt_import_types}, - {OSSL_FUNC_KEYMGMT_GETTABLE_PARAMS, (void (*)(void))keymgmt_gettable_p= arams}, - {OSSL_FUNC_KEYMGMT_GET_PARAMS, (void (*)(void))keymgmt_get_params}, - {OSSL_FUNC_KEYMGMT_SET_PARAMS, (void (*)(void))keymgmt_set_params}, - {OSSL_FUNC_KEYMGMT_SETTABLE_PARAMS, (void (*)(void))keymgmt_gettable_p= arams}, /* same as gettable */ - {OSSL_FUNC_KEYMGMT_QUERY_OPERATION_NAME, (void (*)(void))ec_keymgmt_na= me}, - {0, NULL } + { OSSL_FUNC_KEYMGMT_NEW, (void (*)(void))keymgmt_new }, + { OSSL_FUNC_KEYMGMT_FREE, (void (*)(void))keymgmt_free }, + { OSSL_FUNC_KEYMGMT_LOAD, (void (*)(void))keymgmt_load }, + { OSSL_FUNC_KEYMGMT_HAS, (void (*)(void))keymgmt_has }, + { OSSL_FUNC_KEYMGMT_MATCH, (void (*)(void))keymgmt_match }, + { OSSL_FUNC_KEYMGMT_IMPORT, (void (*)(void))ec_keymgmt_import }, + { OSSL_FUNC_KEYMGMT_IMPORT_TYPES, (void (*)(void))keymgmt_import_types= }, + { OSSL_FUNC_KEYMGMT_GETTABLE_PARAMS, (void (*)(void))keymgmt_gettable_= params }, + { OSSL_FUNC_KEYMGMT_GET_PARAMS, (void (*)(void))keymgmt_get_params }, + { OSSL_FUNC_KEYMGMT_SET_PARAMS, (void (*)(void))keymgmt_set_params }, + { OSSL_FUNC_KEYMGMT_SETTABLE_PARAMS, + (void (*)(void))keymgmt_gettable_params }, /* same as gettable */ + { OSSL_FUNC_KEYMGMT_QUERY_OPERATION_NAME, (void (*)(void))ec_keymgmt_n= ame }, + { 0, NULL } }; static const OSSL_DISPATCH ed448_keymgmt_functions[] =3D { - {OSSL_FUNC_KEYMGMT_NEW, (void (*)(void))keymgmt_new}, - {OSSL_FUNC_KEYMGMT_FREE, (void (*)(void))keymgmt_free}, - {OSSL_FUNC_KEYMGMT_LOAD, (void (*)(void))keymgmt_load}, - {OSSL_FUNC_KEYMGMT_HAS, (void (*)(void))keymgmt_has}, - {OSSL_FUNC_KEYMGMT_MATCH, (void (*)(void))keymgmt_match}, - {OSSL_FUNC_KEYMGMT_IMPORT, (void (*)(void))ed448_keymgmt_import}, - {OSSL_FUNC_KEYMGMT_IMPORT_TYPES, (void (*)(void))keymgmt_import_types}, - {OSSL_FUNC_KEYMGMT_GETTABLE_PARAMS, (void (*)(void))keymgmt_gettable_p= arams}, - {OSSL_FUNC_KEYMGMT_GET_PARAMS, (void (*)(void))keymgmt_get_params}, - {OSSL_FUNC_KEYMGMT_SET_PARAMS, (void (*)(void))keymgmt_set_params}, - {OSSL_FUNC_KEYMGMT_SETTABLE_PARAMS, (void (*)(void))keymgmt_gettable_p= arams}, /* same as gettable */ - {0, NULL } + { OSSL_FUNC_KEYMGMT_NEW, (void (*)(void))keymgmt_new }, + { OSSL_FUNC_KEYMGMT_FREE, (void (*)(void))keymgmt_free }, + { OSSL_FUNC_KEYMGMT_LOAD, (void (*)(void))keymgmt_load }, + { OSSL_FUNC_KEYMGMT_HAS, (void (*)(void))keymgmt_has }, + { OSSL_FUNC_KEYMGMT_MATCH, (void (*)(void))keymgmt_match }, + { OSSL_FUNC_KEYMGMT_IMPORT, (void (*)(void))ed448_keymgmt_import }, + { OSSL_FUNC_KEYMGMT_IMPORT_TYPES, (void (*)(void))keymgmt_import_types= }, + { OSSL_FUNC_KEYMGMT_GETTABLE_PARAMS, (void (*)(void))keymgmt_gettable_= params }, + { OSSL_FUNC_KEYMGMT_GET_PARAMS, (void (*)(void))keymgmt_get_params }, + { OSSL_FUNC_KEYMGMT_SET_PARAMS, (void (*)(void))keymgmt_set_params }, + { OSSL_FUNC_KEYMGMT_SETTABLE_PARAMS, + (void (*)(void))keymgmt_gettable_params }, /* same as gettable */ + { 0, NULL } }; static const OSSL_DISPATCH ed25519_keymgmt_functions[] =3D { - {OSSL_FUNC_KEYMGMT_NEW, (void (*)(void))keymgmt_new}, - {OSSL_FUNC_KEYMGMT_FREE, (void (*)(void))keymgmt_free}, - {OSSL_FUNC_KEYMGMT_LOAD, (void (*)(void))keymgmt_load}, - {OSSL_FUNC_KEYMGMT_HAS, (void (*)(void))keymgmt_has}, - {OSSL_FUNC_KEYMGMT_MATCH, (void (*)(void))keymgmt_match}, - {OSSL_FUNC_KEYMGMT_IMPORT, (void (*)(void))ed25519_keymgmt_import}, - {OSSL_FUNC_KEYMGMT_IMPORT_TYPES, (void (*)(void))keymgmt_import_types}, - {OSSL_FUNC_KEYMGMT_GETTABLE_PARAMS, (void (*)(void))keymgmt_gettable_p= arams}, - {OSSL_FUNC_KEYMGMT_GET_PARAMS, (void (*)(void))keymgmt_get_params}, - {OSSL_FUNC_KEYMGMT_SET_PARAMS, (void (*)(void))keymgmt_set_params}, - {OSSL_FUNC_KEYMGMT_SETTABLE_PARAMS, (void (*)(void))keymgmt_gettable_p= arams}, /* same as gettable */ - {0, NULL } + { OSSL_FUNC_KEYMGMT_NEW, (void (*)(void))keymgmt_new }, + { OSSL_FUNC_KEYMGMT_FREE, (void (*)(void))keymgmt_free }, + { OSSL_FUNC_KEYMGMT_LOAD, (void (*)(void))keymgmt_load }, + { OSSL_FUNC_KEYMGMT_HAS, (void (*)(void))keymgmt_has }, + { OSSL_FUNC_KEYMGMT_MATCH, (void (*)(void))keymgmt_match }, + { OSSL_FUNC_KEYMGMT_IMPORT, (void (*)(void))ed25519_keymgmt_import }, + { OSSL_FUNC_KEYMGMT_IMPORT_TYPES, (void (*)(void))keymgmt_import_types= }, + { OSSL_FUNC_KEYMGMT_GETTABLE_PARAMS, (void (*)(void))keymgmt_gettable_= params }, + { OSSL_FUNC_KEYMGMT_GET_PARAMS, (void (*)(void))keymgmt_get_params }, + { OSSL_FUNC_KEYMGMT_SET_PARAMS, (void (*)(void))keymgmt_set_params }, + { OSSL_FUNC_KEYMGMT_SETTABLE_PARAMS, + (void (*)(void))keymgmt_gettable_params }, /* same as gettable */ + { 0, NULL } }; const OSSL_ALGORITHM keymgmts[] =3D { - {"RSA:rsaEncryption", XKEY_PROV_PROPS, rsa_keymgmt_functions, "OpenVPN= xkey RSA Key Manager"}, - {"RSA-PSS:RSASSA-PSS", XKEY_PROV_PROPS, rsa_keymgmt_functions, "OpenVP= N xkey RSA-PSS Key Manager"}, - {"EC:id-ecPublicKey", XKEY_PROV_PROPS, ec_keymgmt_functions, "OpenVPN = xkey EC Key Manager"}, - {"ED448", XKEY_PROV_PROPS, ed448_keymgmt_functions, "OpenVPN xkey ED44= 8 Key Manager"}, - {"ED25519", XKEY_PROV_PROPS, ed25519_keymgmt_functions, "OpenVPN xkey = ED25519 Key Manager"}, - {NULL, NULL, NULL, NULL} + { "RSA:rsaEncryption", XKEY_PROV_PROPS, rsa_keymgmt_functions, "OpenVP= N xkey RSA Key Manager" }, + { "RSA-PSS:RSASSA-PSS", XKEY_PROV_PROPS, rsa_keymgmt_functions, + "OpenVPN xkey RSA-PSS Key Manager" }, + { "EC:id-ecPublicKey", XKEY_PROV_PROPS, ec_keymgmt_functions, "OpenVPN= xkey EC Key Manager" }, + { "ED448", XKEY_PROV_PROPS, ed448_keymgmt_functions, "OpenVPN xkey ED4= 48 Key Manager" }, + { "ED25519", XKEY_PROV_PROPS, ed25519_keymgmt_functions, "OpenVPN xkey= ED25519 Key Manager" }, + { NULL, NULL, NULL, NULL } }; @@ -681,29 +679,39 @@ XKEY_SIGALG sigalg; } XKEY_SIGNATURE_CTX; -static const XKEY_SIGALG default_sigalg =3D { .mdname =3D "MD5-SHA1", .sal= tlen =3D "digest", - .padmode =3D "pkcs1", .keytype= =3D "RSA"}; +static const XKEY_SIGALG default_sigalg =3D { + .mdname =3D "MD5-SHA1", .saltlen =3D "digest", .padmode =3D "pkcs1", .= keytype =3D "RSA" +}; -const struct { +const struct +{ int nid; const char *name; -} digest_names[] =3D {{NID_md5_sha1, "MD5-SHA1"}, {NID_sha1, "SHA1"}, - {NID_sha224, "SHA224", }, {NID_sha256, "SHA256"}, {NID= _sha384, "SHA384"}, - {NID_sha512, "SHA512"}, {0, NULL}}; +} digest_names[] =3D { { NID_md5_sha1, "MD5-SHA1" }, + { NID_sha1, "SHA1" }, + { + NID_sha224, + "SHA224", + }, + { NID_sha256, "SHA256" }, + { NID_sha384, "SHA384" }, + { NID_sha512, "SHA512" }, + { 0, NULL } }; /* Use of NIDs as opposed to EVP_MD_fetch is okay here * as these are only used for converting names passed in * by OpenSSL to const strings. */ -static struct { +static struct +{ int id; const char *name; -} padmode_names[] =3D {{RSA_PKCS1_PADDING, "pkcs1"}, - {RSA_PKCS1_PSS_PADDING, "pss"}, - {RSA_NO_PADDING, "none"}, - {0, NULL}}; +} padmode_names[] =3D { { RSA_PKCS1_PADDING, "pkcs1" }, + { RSA_PKCS1_PSS_PADDING, "pss" }, + { RSA_NO_PADDING, "none" }, + { 0, NULL } }; -static const char *saltlen_names[] =3D {"digest", "max", "auto", NULL}; +static const char *saltlen_names[] =3D { "digest", "max", "auto", NULL }; /* Return a string literal for digest name - normalizes * alternate names like SHA2-256 to SHA256 etc. @@ -724,7 +732,7 @@ { i++; } - return digest_names[i].name ? digest_names[i].name : "MD5-SHA1"; + return digest_names[i].name ? digest_names[i].name : "MD5-SHA1"; } static void * @@ -732,7 +740,7 @@ { xkey_dmsg(D_XKEY, "entry"); - (void) propq; /* unused */ + (void)propq; /* unused */ XKEY_SIGNATURE_CTX *sctx =3D OPENSSL_zalloc(sizeof(*sctx)); if (!sctx) @@ -767,8 +775,7 @@ static OSSL_PARAM settable[] =3D { OSSL_PARAM_utf8_string(OSSL_SIGNATURE_PARAM_PAD_MODE, NULL, 0), OSSL_PARAM_utf8_string(OSSL_SIGNATURE_PARAM_DIGEST, NULL, 0), - OSSL_PARAM_utf8_string(OSSL_SIGNATURE_PARAM_PSS_SALTLEN, NULL, 0), - OSSL_PARAM_END + OSSL_PARAM_utf8_string(OSSL_SIGNATURE_PARAM_PSS_SALTLEN, NULL, 0),= OSSL_PARAM_END }; return settable; @@ -784,7 +791,7 @@ if (params =3D=3D NULL) { - return 1; /* not an error */ + return 1; /* not an error */ } p =3D OSSL_PARAM_locate_const(params, OSSL_SIGNATURE_PARAM_PAD_MODE); if (p && p->data_type =3D=3D OSSL_PARAM_UTF8_STRING) @@ -800,8 +807,7 @@ } if (sctx->sigalg.padmode =3D=3D NULL) { - msg(M_WARN, "xkey signature_ctx: padmode <%s>, treating as ", - (char *)p->data); + msg(M_WARN, "xkey signature_ctx: padmode <%s>, treating as ", (char *)p->data); sctx->sigalg.padmode =3D "none"; } xkey_dmsg(D_XKEY, "setting padmode as %s", sctx->sigalg.padmode); @@ -834,7 +840,7 @@ } p =3D OSSL_PARAM_locate_const(params, OSSL_SIGNATURE_PARAM_DIGEST); - if (p && p->data_type =3D=3D OSSL_PARAM_UTF8_STRING) + if (p && p->data_type =3D=3D OSSL_PARAM_UTF8_STRING) { sctx->sigalg.mdname =3D xkey_mdname(p->data); xkey_dmsg(D_XKEY, "setting hashalg as %s", sctx->sigalg.mdname); @@ -858,8 +864,7 @@ } if (sctx->sigalg.saltlen =3D=3D NULL) { - msg(M_WARN, "xkey_signature_params: unknown saltlen <%s>", - (char *)p->data); + msg(M_WARN, "xkey_signature_params: unknown saltlen <%s>", (ch= ar *)p->data); sctx->sigalg.saltlen =3D "digest"; /* most common */ } xkey_dmsg(D_XKEY, "setting saltlen to %s", sctx->sigalg.saltlen); @@ -924,7 +929,8 @@ else if (sign) { ret =3D sign(sctx->keydata->handle, sig, siglen, tbs, tbslen, sctx= ->sigalg); - xkey_dmsg(D_XKEY, "xkey_provider: external sign op returned ret = =3D %d siglen =3D %d", ret, (int) *siglen); + xkey_dmsg(D_XKEY, "xkey_provider: external sign op returned ret = =3D %d siglen =3D %d", ret, + (int)*siglen); } else { @@ -979,8 +985,7 @@ } static int -signature_digest_sign_init(void *ctx, const char *mdname, - void *provkey, const OSSL_PARAM params[]) +signature_digest_sign_init(void *ctx, const char *mdname, void *provkey, c= onst OSSL_PARAM params[]) { xkey_dmsg(D_XKEY, "mdname =3D <%s>", mdname); @@ -1022,8 +1027,8 @@ } static int -signature_digest_sign(void *ctx, unsigned char *sig, size_t *siglen, - size_t sigsize, const unsigned char *tbs, size_t tbs= len) +signature_digest_sign(void *ctx, unsigned char *sig, size_t *siglen, size_= t sigsize, + const unsigned char *tbs, size_t tbslen) { xkey_dmsg(D_XKEY, "entry"); @@ -1072,8 +1077,8 @@ /* Sign digest using native sign function -- will only work for native keys */ int -xkey_native_sign(XKEY_KEYDATA *key, unsigned char *sig, size_t *siglen, - const unsigned char *tbs, size_t tbslen, XKEY_SIGALG siga= lg) +xkey_native_sign(XKEY_KEYDATA *key, unsigned char *sig, size_t *siglen, co= nst unsigned char *tbs, + size_t tbslen, XKEY_SIGALG sigalg) { xkey_dmsg(D_XKEY, "entry"); @@ -1100,13 +1105,17 @@ OSSL_PARAM params[6]; if (EVP_PKEY_get_id(pkey) =3D=3D EVP_PKEY_RSA) { - params[i++] =3D OSSL_PARAM_construct_utf8_string(OSSL_SIGNATURE_PA= RAM_DIGEST, (char *)mdname, 0); - params[i++] =3D OSSL_PARAM_construct_utf8_string(OSSL_SIGNATURE_PA= RAM_PAD_MODE, (char *)padmode, 0); + params[i++] =3D + OSSL_PARAM_construct_utf8_string(OSSL_SIGNATURE_PARAM_DIGEST, = (char *)mdname, 0); + params[i++] =3D + OSSL_PARAM_construct_utf8_string(OSSL_SIGNATURE_PARAM_PAD_MODE= , (char *)padmode, 0); if (!strcmp(sigalg.padmode, "pss")) { - params[i++] =3D OSSL_PARAM_construct_utf8_string(OSSL_SIGNATUR= E_PARAM_PSS_SALTLEN, (char *) saltlen, 0); + params[i++] =3D OSSL_PARAM_construct_utf8_string(OSSL_SIGNATUR= E_PARAM_PSS_SALTLEN, + (char *)saltlen= , 0); /* same digest for mgf1 */ - params[i++] =3D OSSL_PARAM_construct_utf8_string(OSSL_SIGNATUR= E_PARAM_MGF1_DIGEST, (char *) mdname, 0); + params[i++] =3D OSSL_PARAM_construct_utf8_string(OSSL_SIGNATUR= E_PARAM_MGF1_DIGEST, + (char *)mdname,= 0); } } params[i++] =3D OSSL_PARAM_construct_end(); @@ -1133,27 +1142,27 @@ } static const OSSL_DISPATCH signature_functions[] =3D { - {OSSL_FUNC_SIGNATURE_NEWCTX, (void (*)(void))signature_newctx}, - {OSSL_FUNC_SIGNATURE_FREECTX, (void (*)(void))signature_freectx}, - {OSSL_FUNC_SIGNATURE_SIGN_INIT, (void (*)(void))signature_sign_init}, - {OSSL_FUNC_SIGNATURE_SIGN, (void (*)(void))signature_sign}, - {OSSL_FUNC_SIGNATURE_DIGEST_VERIFY_INIT, (void (*)(void))signature_dig= est_verify_init}, - {OSSL_FUNC_SIGNATURE_DIGEST_VERIFY, (void (*)(void))signature_digest_v= erify}, - {OSSL_FUNC_SIGNATURE_DIGEST_SIGN_INIT, (void (*)(void))signature_diges= t_sign_init}, - {OSSL_FUNC_SIGNATURE_DIGEST_SIGN, (void (*)(void))signature_digest_sig= n}, - {OSSL_FUNC_SIGNATURE_SET_CTX_PARAMS, (void (*)(void))signature_set_ctx= _params}, - {OSSL_FUNC_SIGNATURE_SETTABLE_CTX_PARAMS, (void (*)(void))signature_se= ttable_ctx_params}, - {OSSL_FUNC_SIGNATURE_GET_CTX_PARAMS, (void (*)(void))signature_get_ctx= _params}, - {OSSL_FUNC_SIGNATURE_GETTABLE_CTX_PARAMS, (void (*)(void))signature_ge= ttable_ctx_params}, - {0, NULL } + { OSSL_FUNC_SIGNATURE_NEWCTX, (void (*)(void))signature_newctx }, + { OSSL_FUNC_SIGNATURE_FREECTX, (void (*)(void))signature_freectx }, + { OSSL_FUNC_SIGNATURE_SIGN_INIT, (void (*)(void))signature_sign_init }, + { OSSL_FUNC_SIGNATURE_SIGN, (void (*)(void))signature_sign }, + { OSSL_FUNC_SIGNATURE_DIGEST_VERIFY_INIT, (void (*)(void))signature_di= gest_verify_init }, + { OSSL_FUNC_SIGNATURE_DIGEST_VERIFY, (void (*)(void))signature_digest_= verify }, + { OSSL_FUNC_SIGNATURE_DIGEST_SIGN_INIT, (void (*)(void))signature_dige= st_sign_init }, + { OSSL_FUNC_SIGNATURE_DIGEST_SIGN, (void (*)(void))signature_digest_si= gn }, + { OSSL_FUNC_SIGNATURE_SET_CTX_PARAMS, (void (*)(void))signature_set_ct= x_params }, + { OSSL_FUNC_SIGNATURE_SETTABLE_CTX_PARAMS, (void (*)(void))signature_s= ettable_ctx_params }, + { OSSL_FUNC_SIGNATURE_GET_CTX_PARAMS, (void (*)(void))signature_get_ct= x_params }, + { OSSL_FUNC_SIGNATURE_GETTABLE_CTX_PARAMS, (void (*)(void))signature_g= ettable_ctx_params }, + { 0, NULL } }; const OSSL_ALGORITHM signatures[] =3D { - {"RSA:rsaEncryption", XKEY_PROV_PROPS, signature_functions, "OpenVPN x= key RSA Signature"}, - {"ECDSA", XKEY_PROV_PROPS, signature_functions, "OpenVPN xkey ECDSA Si= gnature"}, - {"ED448", XKEY_PROV_PROPS, signature_functions, "OpenVPN xkey Ed448 Si= gnature"}, - {"ED25519", XKEY_PROV_PROPS, signature_functions, "OpenVPN xkey Ed2551= 9 Signature"}, - {NULL, NULL, NULL, NULL} + { "RSA:rsaEncryption", XKEY_PROV_PROPS, signature_functions, "OpenVPN = xkey RSA Signature" }, + { "ECDSA", XKEY_PROV_PROPS, signature_functions, "OpenVPN xkey ECDSA S= ignature" }, + { "ED448", XKEY_PROV_PROPS, signature_functions, "OpenVPN xkey Ed448 S= ignature" }, + { "ED25519", XKEY_PROV_PROPS, signature_functions, "OpenVPN xkey Ed255= 19 Signature" }, + { NULL, NULL, NULL, NULL } }; /* main provider interface */ @@ -1192,8 +1201,7 @@ xkey_dmsg(D_XKEY, "entry"); static const OSSL_PARAM param_types[] =3D { - OSSL_PARAM_DEFN(OSSL_PROV_PARAM_NAME, OSSL_PARAM_UTF8_PTR, NULL, 0= ), - OSSL_PARAM_END + OSSL_PARAM_DEFN(OSSL_PROV_PARAM_NAME, OSSL_PARAM_UTF8_PTR, NULL, 0= ), OSSL_PARAM_END }; return param_types; @@ -1228,11 +1236,11 @@ } static const OSSL_DISPATCH dispatch_table[] =3D { - {OSSL_FUNC_PROVIDER_GETTABLE_PARAMS, (void (*)(void))gettable_params}, - {OSSL_FUNC_PROVIDER_GET_PARAMS, (void (*)(void))get_params}, - {OSSL_FUNC_PROVIDER_QUERY_OPERATION, (void (*)(void))query_operation}, - {OSSL_FUNC_PROVIDER_TEARDOWN, (void (*)(void))teardown}, - {0, NULL} + { OSSL_FUNC_PROVIDER_GETTABLE_PARAMS, (void (*)(void))gettable_params = }, + { OSSL_FUNC_PROVIDER_GET_PARAMS, (void (*)(void))get_params }, + { OSSL_FUNC_PROVIDER_QUERY_OPERATION, (void (*)(void))query_operation = }, + { OSSL_FUNC_PROVIDER_TEARDOWN, (void (*)(void))teardown }, + { 0, NULL } }; int diff --git a/src/openvpnmsica/dllmain.c b/src/openvpnmsica/dllmain.c index 7121c02..e7d4a4b 100644 --- a/src/openvpnmsica/dllmain.c +++ b/src/openvpnmsica/dllmain.c @@ -41,10 +41,7 @@ * DLL entry point */ BOOL WINAPI -DllMain( - _In_ HINSTANCE hinstDLL, - _In_ DWORD dwReason, - _In_ LPVOID lpReserved) +DllMain(_In_ HINSTANCE hinstDLL, _In_ DWORD dwReason, _In_ LPVOID lpReserv= ed) { UNREFERENCED_PARAMETER(hinstDLL); UNREFERENCED_PARAMETER(lpReserved); @@ -58,12 +55,13 @@ { return FALSE; } - /* Fall through. */ + /* Fall through. */ case DLL_THREAD_ATTACH: { /* Create thread local storage data. */ - struct openvpnmsica_thread_data *s =3D (struct openvpnmsica_th= read_data *)calloc(1, sizeof(struct openvpnmsica_thread_data)); + struct openvpnmsica_thread_data *s =3D (struct openvpnmsica_th= read_data *)calloc( + 1, sizeof(struct openvpnmsica_thread_data)); if (s =3D=3D NULL) { return FALSE; @@ -107,7 +105,8 @@ /* Secure last error before it is overridden. */ DWORD dwResult =3D (flags & M_ERRNO) !=3D 0 ? GetLastError() : ERROR_S= UCCESS; - struct openvpnmsica_thread_data *s =3D (struct openvpnmsica_thread_dat= a *)TlsGetValue(openvpnmsica_thread_data_idx); + struct openvpnmsica_thread_data *s =3D + (struct openvpnmsica_thread_data *)TlsGetValue(openvpnmsica_thread= _data_idx); if (s->hInstall =3D=3D 0) { /* No MSI session, no fun. */ @@ -160,16 +159,13 @@ /* Field 4: The Windows error description. */ LPWSTR szErrMessage =3D NULL; - if (FormatMessage( - FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFE= R | FORMAT_MESSAGE_IGNORE_INSERTS, - 0, - dwResult, - 0, - (LPWSTR)&szErrMessage, - 0, - NULL) && szErrMessage) + if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLO= CATE_BUFFER + | FORMAT_MESSAGE_IGNORE_INSERTS, + 0, dwResult, 0, (LPWSTR)&szErrMessage, 0, NULL) + && szErrMessage) { - /* Trim trailing whitespace. Set terminator after the last non= -whitespace character. This prevents excessive trailing line breaks. */ + /* Trim trailing whitespace. Set terminator after the last non= -whitespace character. + * This prevents excessive trailing line breaks. */ for (size_t i =3D 0, i_last =3D 0;; i++) { if (szErrMessage[i]) @@ -190,6 +186,7 @@ } } =20 - MsiProcessMessage(s->hInstall, (flags & M_WARN) ? INSTALLMESSAGE_INFO = : INSTALLMESSAGE_ERROR, hRecordProg); + MsiProcessMessage(s->hInstall, (flags & M_WARN) ? INSTALLMESSAGE_INFO = : INSTALLMESSAGE_ERROR, + hRecordProg); MsiCloseHandle(hRecordProg); } diff --git a/src/openvpnmsica/msica_arg.c b/src/openvpnmsica/msica_arg.c index 46bef2b..d750fb0 100644 --- a/src/openvpnmsica/msica_arg.c +++ b/src/openvpnmsica/msica_arg.c @@ -51,15 +51,14 @@ void -msica_arg_seq_add_head( - _Inout_ struct msica_arg_seq *seq, - _In_z_ LPCWSTR argument) +msica_arg_seq_add_head(_Inout_ struct msica_arg_seq *seq, _In_z_ LPCWSTR a= rgument) { size_t argument_size =3D (wcslen(argument) + 1) * sizeof(WCHAR); struct msica_arg *p =3D malloc(sizeof(struct msica_arg) + argument_siz= e); if (p =3D=3D NULL) { - msg(M_FATAL, "%s: malloc(%u) failed", __FUNCTION__, sizeof(struct = msica_arg) + argument_size); + msg(M_FATAL, "%s: malloc(%u) failed", __FUNCTION__, + sizeof(struct msica_arg) + argument_size); } memcpy(p->val, argument, argument_size); p->next =3D seq->head; @@ -72,15 +71,14 @@ void -msica_arg_seq_add_tail( - _Inout_ struct msica_arg_seq *seq, - _Inout_ LPCWSTR argument) +msica_arg_seq_add_tail(_Inout_ struct msica_arg_seq *seq, _Inout_ LPCWSTR = argument) { size_t argument_size =3D (wcslen(argument) + 1) * sizeof(WCHAR); struct msica_arg *p =3D malloc(sizeof(struct msica_arg) + argument_siz= e); if (p =3D=3D NULL) { - msg(M_FATAL, "%s: malloc(%u) failed", __FUNCTION__, sizeof(struct = msica_arg) + argument_size); + msg(M_FATAL, "%s: malloc(%u) failed", __FUNCTION__, + sizeof(struct msica_arg) + argument_size); } memcpy(p->val, argument, argument_size); p->next =3D NULL; @@ -110,10 +108,13 @@ #ifdef _MSC_VER #pragma warning(push) -#pragma warning(disable: 4996) /* Using unsafe string functions: The space= in s and termination of p->val has been implicitly verified at the beginni= ng of this function. */ +#pragma warning( = \ + disable : 4996) /* Using unsafe string functions: The space in s and t= ermination of p->val has \ + been implicitly verified at the beginning of this f= unction. */ #endif - /* Dummy argv[0] (i.e. executable name), for CommandLineToArgvW to wor= k correctly when parsing this string. */ + /* Dummy argv[0] (i.e. executable name), for CommandLineToArgvW to wor= k correctly when parsing + * this string. */ wcscpy(str, L"x"); /* Join. */ diff --git a/src/openvpnmsica/msica_arg.h b/src/openvpnmsica/msica_arg.h index c8f7595..858fdb6 100644 --- a/src/openvpnmsica/msica_arg.h +++ b/src/openvpnmsica/msica_arg.h @@ -27,7 +27,7 @@ #ifdef _MSC_VER #pragma warning(push) -#pragma warning(disable: 4200) /* Using zero-sized arrays in struct/union.= */ +#pragma warning(disable : 4200) /* Using zero-sized arrays in struct/union= . */ #endif @@ -56,8 +56,7 @@ * * @param seq Pointer to uninitialized argument sequence */ -void -msica_arg_seq_init(_Inout_ struct msica_arg_seq *seq); +void msica_arg_seq_init(_Inout_ struct msica_arg_seq *seq); /** @@ -65,8 +64,7 @@ * * @param seq Pointer to the argument sequence */ -void -msica_arg_seq_free(_Inout_ struct msica_arg_seq *seq); +void msica_arg_seq_free(_Inout_ struct msica_arg_seq *seq); /** @@ -76,10 +74,7 @@ * * @param argument Zero-terminated argument string to insert. */ -void -msica_arg_seq_add_head( - _Inout_ struct msica_arg_seq *seq, - _In_z_ LPCWSTR argument); +void msica_arg_seq_add_head(_Inout_ struct msica_arg_seq *seq, _In_z_ LPCW= STR argument); /** @@ -89,10 +84,7 @@ * * @param argument Zero-terminated argument string to append. */ -void -msica_arg_seq_add_tail( - _Inout_ struct msica_arg_seq *seq, - _Inout_ LPCWSTR argument); +void msica_arg_seq_add_tail(_Inout_ struct msica_arg_seq *seq, _Inout_ LPC= WSTR argument); /** * Join arguments of the argument sequence into a space delimited string diff --git a/src/openvpnmsica/msiex.c b/src/openvpnmsica/msiex.c index 3529e9a..12dc0db 100644 --- a/src/openvpnmsica/msiex.c +++ b/src/openvpnmsica/msiex.c @@ -34,10 +34,7 @@ UINT -msi_get_string( - _In_ MSIHANDLE hInstall, - _In_z_ LPCWSTR szName, - _Out_ LPWSTR *pszValue) +msi_get_string(_In_ MSIHANDLE hInstall, _In_z_ LPCWSTR szName, _Out_ LPWST= R *pszValue) { if (pszValue =3D=3D NULL) { @@ -84,7 +81,8 @@ } else { - SetLastError(uiResult); /* MSDN does not mention MsiGetProperty() = to set GetLastError(). But we do have an error code. Set last error manuall= y. */ + SetLastError(uiResult); /* MSDN does not mention MsiGetProperty() = to set GetLastError(). But + we do have an error code. Set last erro= r manually. */ msg(M_NONFATAL | M_ERRNO, "%s: MsiGetProperty failed", __FUNCTION_= _); return uiResult; } @@ -92,10 +90,7 @@ UINT -msi_get_record_string( - _In_ MSIHANDLE hRecord, - _In_ unsigned int iField, - _Out_ LPWSTR *pszValue) +msi_get_record_string(_In_ MSIHANDLE hRecord, _In_ unsigned int iField, _O= ut_ LPWSTR *pszValue) { if (pszValue =3D=3D NULL) { @@ -142,7 +137,8 @@ } else { - SetLastError(uiResult); /* MSDN does not mention MsiRecordGetStrin= g() to set GetLastError(). But we do have an error code. Set last error man= ually. */ + SetLastError(uiResult); /* MSDN does not mention MsiRecordGetStrin= g() to set GetLastError(). + But we do have an error code. Set last = error manually. */ msg(M_NONFATAL | M_ERRNO, "%s: MsiRecordGetString failed", __FUNCT= ION__); return uiResult; } @@ -150,10 +146,7 @@ UINT -msi_format_record( - _In_ MSIHANDLE hInstall, - _In_ MSIHANDLE hRecord, - _Out_ LPWSTR *pszValue) +msi_format_record(_In_ MSIHANDLE hInstall, _In_ MSIHANDLE hRecord, _Out_ L= PWSTR *pszValue) { if (pszValue =3D=3D NULL) { @@ -200,7 +193,8 @@ } else { - SetLastError(uiResult); /* MSDN does not mention MsiFormatRecord()= to set GetLastError(). But we do have an error code. Set last error manual= ly. */ + SetLastError(uiResult); /* MSDN does not mention MsiFormatRecord()= to set GetLastError(). + But we do have an error code. Set last = error manually. */ msg(M_NONFATAL | M_ERRNO, "%s: MsiFormatRecord failed", __FUNCTION= __); return uiResult; } @@ -208,11 +202,8 @@ UINT -msi_format_field( - _In_ MSIHANDLE hInstall, - _In_ MSIHANDLE hRecord, - _In_ unsigned int iField, - _Out_ LPWSTR *pszValue) +msi_format_field(_In_ MSIHANDLE hInstall, _In_ MSIHANDLE hRecord, _In_ uns= igned int iField, + _Out_ LPWSTR *pszValue) { if (pszValue =3D=3D NULL) { @@ -246,7 +237,8 @@ uiResult =3D MsiRecordSetString(hRecordEx, 0, szValue); if (uiResult !=3D ERROR_SUCCESS) { - SetLastError(uiResult); /* MSDN does not mention MsiRecordSetStrin= g() to set GetLastError(). But we do have an error code. Set last error man= ually. */ + SetLastError(uiResult); /* MSDN does not mention MsiRecordSetStrin= g() to set GetLastError(). + But we do have an error code. Set last = error manually. */ msg(M_NONFATAL | M_ERRNO, "%s: MsiRecordSetString failed", __FUNCT= ION__); goto cleanup_hRecordEx; } diff --git a/src/openvpnmsica/msiex.h b/src/openvpnmsica/msiex.h index d9afeb5..60c26b5 100644 --- a/src/openvpnmsica/msiex.h +++ b/src/openvpnmsica/msiex.h @@ -37,11 +37,7 @@ * * @return ERROR_SUCCESS on success; Win32 error code otherwise */ -UINT -msi_get_string( - _In_ MSIHANDLE hInstall, - _In_z_ LPCWSTR szName, - _Out_ LPWSTR *pszValue); +UINT msi_get_string(_In_ MSIHANDLE hInstall, _In_z_ LPCWSTR szName, _Out_ = LPWSTR *pszValue); /** @@ -56,11 +52,8 @@ * * @return ERROR_SUCCESS on success; Win32 error code otherwise */ -UINT -msi_get_record_string( - _In_ MSIHANDLE hRecord, - _In_ unsigned int iField, - _Out_ LPWSTR *pszValue); +UINT msi_get_record_string(_In_ MSIHANDLE hRecord, _In_ unsigned int iFiel= d, + _Out_ LPWSTR *pszValue); /** @@ -78,11 +71,7 @@ * * @return ERROR_SUCCESS on success; Win32 error code otherwise */ -UINT -msi_format_record( - _In_ MSIHANDLE hInstall, - _In_ MSIHANDLE hRecord, - _Out_ LPWSTR *pszValue); +UINT msi_format_record(_In_ MSIHANDLE hInstall, _In_ MSIHANDLE hRecord, _O= ut_ LPWSTR *pszValue); /** @@ -101,11 +90,7 @@ * * @return ERROR_SUCCESS on success; Win32 error code otherwise */ -UINT -msi_format_field( - _In_ MSIHANDLE hInstall, - _In_ MSIHANDLE hRecord, - _In_ unsigned int iField, - _Out_ LPWSTR *pszValue); +UINT msi_format_field(_In_ MSIHANDLE hInstall, _In_ MSIHANDLE hRecord, _In= _ unsigned int iField, + _Out_ LPWSTR *pszValue); #endif /* ifndef MSIHLP_H */ diff --git a/src/openvpnmsica/openvpnmsica.c b/src/openvpnmsica/openvpnmsic= a.c index 8d860e2..7779a1e 100644 --- a/src/openvpnmsica/openvpnmsica.c +++ b/src/openvpnmsica/openvpnmsica.c @@ -59,9 +59,9 @@ */ /** Amount of tick space to reserve for one TAP/TUN adapter creation/delet= ition. */ -#define MSICA_ADAPTER_TICK_SIZE (16 * 1024) +#define MSICA_ADAPTER_TICK_SIZE (16 * 1024) -#define FILE_NEED_REBOOT L".ovpn_need_reboot" +#define FILE_NEED_REBOOT L".ovpn_need_reboot" #define OPENVPN_CONNECT_ADAPTER_SUBSTR L"OpenVPN Connect" @@ -77,10 +77,7 @@ * @return ERROR_SUCCESS on success; An error code otherwise */ static UINT -setup_sequence( - _In_ MSIHANDLE hInstall, - _In_z_ LPCWSTR szProperty, - _In_ struct msica_arg_seq *seq) +setup_sequence(_In_ MSIHANDLE hInstall, _In_z_ LPCWSTR szProperty, _In_ st= ruct msica_arg_seq *seq) { UINT uiResult; LPWSTR szSequence =3D msica_arg_seq_join(seq); @@ -110,12 +107,11 @@ static void _debug_popup(_In_z_ LPCSTR szFunctionName) { - WCHAR szTitle[0x100], szMessage[0x100+MAX_PATH], szProcessPath[MAX_PAT= H]; + WCHAR szTitle[0x100], szMessage[0x100 + MAX_PATH], szProcessPath[MAX_P= ATH]; /* Compose pop-up title. The dialog title will contain function name t= o ease the process * locating. Mind that Visual Studio displays window titles on the pro= cess list. */ - swprintf_s(szTitle, _countof(szTitle), L"%hs v%ls", - szFunctionName, _L(PACKAGE_VERSION)); + swprintf_s(szTitle, _countof(szTitle), L"%hs v%ls", szFunctionName, _L= (PACKAGE_VERSION)); /* Get process name. */ GetModuleFileName(NULL, szProcessPath, _countof(szProcessPath)); @@ -131,9 +127,7 @@ L"If you would like to debug the custom action, attach a debugger = to this process and set breakpoints before dismissing this dialog.\r\n" L"\r\n" L"If you are not debugging this custom action, you can safely igno= re this message.", - szProcessName, - GetCurrentProcessId(), - szFunctionName); + szProcessName, GetCurrentProcessId(), szFunctionName); MessageBox(NULL, szMessage, szTitle, MB_OK); } @@ -144,11 +138,8 @@ #endif /* ifdef _DEBUG */ static void -find_adapters( - _In_ MSIHANDLE hInstall, - _In_z_ LPCWSTR szzHardwareIDs, - _In_z_ LPCWSTR szAdaptersPropertyName, - _In_z_ LPCWSTR szActiveAdaptersPropertyName) +find_adapters(_In_ MSIHANDLE hInstall, _In_z_ LPCWSTR szzHardwareIDs, + _In_z_ LPCWSTR szAdaptersPropertyName, _In_z_ LPCWSTR szActi= veAdaptersPropertyName) { UINT uiResult; @@ -165,24 +156,26 @@ return; } - /* Get IPv4/v6 info for all network adapters. Actually, we're interest= ed in link status only: up/down? */ + /* Get IPv4/v6 info for all network adapters. Actually, we're interest= ed in link status only: + * up/down? */ PIP_ADAPTER_ADDRESSES pAdapterAdresses =3D NULL; - ULONG ulAdapterAdressesSize =3D 16*1024; + ULONG ulAdapterAdressesSize =3D 16 * 1024; for (size_t iteration =3D 0; iteration < 2; iteration++) { pAdapterAdresses =3D (PIP_ADAPTER_ADDRESSES)malloc(ulAdapterAdress= esSize); if (pAdapterAdresses =3D=3D NULL) { msg(M_NONFATAL, "%s: malloc(%u) failed", __FUNCTION__, ulAdapt= erAdressesSize); - uiResult =3D ERROR_OUTOFMEMORY; goto cleanup_pAdapterList; + uiResult =3D ERROR_OUTOFMEMORY; + goto cleanup_pAdapterList; } ULONG ulResult =3D GetAdaptersAddresses( AF_UNSPEC, - GAA_FLAG_SKIP_UNICAST | GAA_FLAG_SKIP_ANYCAST | GAA_FLAG_SKIP_= MULTICAST | GAA_FLAG_SKIP_DNS_SERVER | GAA_FLAG_SKIP_FRIENDLY_NAME | GAA_FL= AG_INCLUDE_ALL_INTERFACES, - NULL, - pAdapterAdresses, - &ulAdapterAdressesSize); + GAA_FLAG_SKIP_UNICAST | GAA_FLAG_SKIP_ANYCAST | GAA_FLAG_SKIP_= MULTICAST + | GAA_FLAG_SKIP_DNS_SERVER | GAA_FLAG_SKIP_FRIENDLY_NAME + | GAA_FLAG_INCLUDE_ALL_INTERFACES, + NULL, pAdapterAdresses, &ulAdapterAdressesSize); if (ulResult =3D=3D ERROR_SUCCESS) { @@ -192,9 +185,12 @@ free(pAdapterAdresses); if (ulResult !=3D ERROR_BUFFER_OVERFLOW) { - SetLastError(ulResult); /* MSDN does not mention GetAdaptersAd= dresses() to set GetLastError(). But we do have an error code. Set last err= or manually. */ + SetLastError( + ulResult); /* MSDN does not mention GetAdaptersAddresses()= to set GetLastError(). + But we do have an error code. Set last error= manually. */ msg(M_NONFATAL | M_ERRNO, "%s: GetAdaptersAddresses() failed",= __FUNCTION__); - uiResult =3D ulResult; goto cleanup_pAdapterList; + uiResult =3D ulResult; + goto cleanup_pAdapterList; } } @@ -207,26 +203,33 @@ /* Prepare semicolon delimited list of TAP adapter ID(s) and active TA= P adapter ID(s). */ LPWSTR - szAdapters =3D (LPWSTR)malloc(adapter_count * (38 /*GUID*/ + 1= /*separator/terminator*/) * sizeof(WCHAR)), - szAdaptersTail =3D szAdapters; + szAdapters =3D + (LPWSTR)malloc(adapter_count * (38 /*GUID*/ + 1 /*separator/termin= ator*/) * sizeof(WCHAR)), + szAdaptersTail =3D szAdapters; if (szAdapters =3D=3D NULL) { - msg(M_FATAL, "%s: malloc(%u) failed", __FUNCTION__, adapter_count = * (38 /*GUID*/ + 1 /*separator/terminator*/) * sizeof(WCHAR)); - uiResult =3D ERROR_OUTOFMEMORY; goto cleanup_pAdapterAdresses; + msg(M_FATAL, "%s: malloc(%u) failed", __FUNCTION__, + adapter_count * (38 /*GUID*/ + 1 /*separator/terminator*/) * s= izeof(WCHAR)); + uiResult =3D ERROR_OUTOFMEMORY; + goto cleanup_pAdapterAdresses; } LPWSTR - szAdaptersActive =3D (LPWSTR)malloc(adapter_count * (38 /*GUID= */ + 1 /*separator/terminator*/) * sizeof(WCHAR)), - szAdaptersActiveTail =3D szAdaptersActive; + szAdaptersActive =3D + (LPWSTR)malloc(adapter_count * (38 /*GUID*/ + 1 /*separator/termin= ator*/) * sizeof(WCHAR)), + szAdaptersActiveTail =3D szAdaptersActive; if (szAdaptersActive =3D=3D NULL) { - msg(M_FATAL, "%s: malloc(%u) failed", __FUNCTION__, adapter_count = * (38 /*GUID*/ + 1 /*separator/terminator*/) * sizeof(WCHAR)); - uiResult =3D ERROR_OUTOFMEMORY; goto cleanup_szAdapters; + msg(M_FATAL, "%s: malloc(%u) failed", __FUNCTION__, + adapter_count * (38 /*GUID*/ + 1 /*separator/terminator*/) * s= izeof(WCHAR)); + uiResult =3D ERROR_OUTOFMEMORY; + goto cleanup_szAdapters; } for (struct tap_adapter_node *pAdapter =3D pAdapterList; pAdapter; pAd= apter =3D pAdapter->pNext) { - /* exclude adapters created by OpenVPN Connect, since they're remo= ved on Connect uninstallation */ + /* exclude adapters created by OpenVPN Connect, since they're remo= ved on Connect + * uninstallation */ if (wcsstr(pAdapter->szName, OPENVPN_CONNECT_ADAPTER_SUBSTR)) { msg(M_WARN, "%s: skip OpenVPN Connect adapter '%ls'", __FUNCTI= ON__, pAdapter->szName); @@ -250,7 +253,9 @@ { OLECHAR szId[38 /*GUID*/ + 1 /*terminator*/]; GUID guid; - if (MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, p->AdapterName= , -1, szId, _countof(szId)) > 0 + if (MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, p->AdapterName= , -1, szId, + _countof(szId)) + > 0 && SUCCEEDED(IIDFromString(szId, &guid)) && memcmp(&guid, &pAdapter->guid, sizeof(GUID)) =3D=3D 0) { @@ -269,22 +274,26 @@ } CoTaskMemFree(szAdapterId); } - szAdaptersTail [0] =3D 0; + szAdaptersTail[0] =3D 0; szAdaptersActiveTail[0] =3D 0; /* Set Installer properties. */ uiResult =3D MsiSetProperty(hInstall, szAdaptersPropertyName, szAdapte= rs); if (uiResult !=3D ERROR_SUCCESS) { - SetLastError(uiResult); /* MSDN does not mention MsiSetProperty() = to set GetLastError(). But we do have an error code. Set last error manuall= y. */ - msg(M_NONFATAL | M_ERRNO, "%s: MsiSetProperty(\"%s\") failed", __F= UNCTION__, szAdaptersPropertyName); + SetLastError(uiResult); /* MSDN does not mention MsiSetProperty() = to set GetLastError(). But + we do have an error code. Set last erro= r manually. */ + msg(M_NONFATAL | M_ERRNO, "%s: MsiSetProperty(\"%s\") failed", __F= UNCTION__, + szAdaptersPropertyName); goto cleanup_szAdaptersActive; } uiResult =3D MsiSetProperty(hInstall, szActiveAdaptersPropertyName, sz= AdaptersActive); if (uiResult !=3D ERROR_SUCCESS) { - SetLastError(uiResult); /* MSDN does not mention MsiSetProperty() = to set GetLastError(). But we do have an error code. Set last error manuall= y. */ - msg(M_NONFATAL | M_ERRNO, "%s: MsiSetProperty(\"%s\") failed", __F= UNCTION__, szActiveAdaptersPropertyName); + SetLastError(uiResult); /* MSDN does not mention MsiSetProperty() = to set GetLastError(). But + we do have an error code. Set last erro= r manually. */ + msg(M_NONFATAL | M_ERRNO, "%s: MsiSetProperty(\"%s\") failed", __F= UNCTION__, + szActiveAdaptersPropertyName); goto cleanup_szAdaptersActive; } @@ -299,8 +308,7 @@ } -UINT __stdcall -FindSystemInfo(_In_ MSIHANDLE hInstall) +UINT __stdcall FindSystemInfo(_In_ MSIHANDLE hInstall) { #ifdef DLLEXP_EXPORT #pragma comment(linker, DLLEXP_EXPORT) @@ -312,16 +320,12 @@ OPENVPNMSICA_SAVE_MSI_SESSION(hInstall); - find_adapters( - hInstall, - L"root\\" _L(TAP_WIN_COMPONENT_ID) L"\0" _L(TAP_WIN_COMPONENT_ID) = L"\0", - L"TAPWINDOWS6ADAPTERS", - L"ACTIVETAPWINDOWS6ADAPTERS"); - find_adapters( - hInstall, - L"ovpn-dco" L"\0", - L"OVPNDCOADAPTERS", - L"ACTIVEOVPNDCOADAPTERS"); + find_adapters(hInstall, L"root\\" _L(TAP_WIN_COMPONENT_ID) L"\0" _L(TA= P_WIN_COMPONENT_ID) L"\0", + L"TAPWINDOWS6ADAPTERS", L"ACTIVETAPWINDOWS6ADAPTERS"); + find_adapters(hInstall, + L"ovpn-dco" + L"\0", + L"OVPNDCOADAPTERS", L"ACTIVEOVPNDCOADAPTERS"); if (bIsCoInitialized) { @@ -331,13 +335,13 @@ } -UINT __stdcall -CloseOpenVPNGUI(_In_ MSIHANDLE hInstall) +UINT __stdcall CloseOpenVPNGUI(_In_ MSIHANDLE hInstall) { #ifdef DLLEXP_EXPORT #pragma comment(linker, DLLEXP_EXPORT) #endif - UNREFERENCED_PARAMETER(hInstall); /* This CA is does not interact with= MSI session (report errors, access properties, tables, etc.). */ + UNREFERENCED_PARAMETER(hInstall); /* This CA is does not interact with= MSI session (report + errors, access properties, tables= , etc.). */ debug_popup(__FUNCTION__); @@ -345,7 +349,8 @@ HWND hWnd =3D FindWindow(L"OpenVPN-GUI", NULL); if (hWnd) { - /* Ask it to close and wait for 100ms. Unfortunately, this will su= cceed only for recent OpenVPN GUI that do not run elevated. */ + /* Ask it to close and wait for 100ms. Unfortunately, this will su= cceed only for recent + * OpenVPN GUI that do not run elevated. */ SendMessage(hWnd, WM_CLOSE, 0, 0); Sleep(100); } @@ -354,8 +359,7 @@ } -UINT __stdcall -StartOpenVPNGUI(_In_ MSIHANDLE hInstall) +UINT __stdcall StartOpenVPNGUI(_In_ MSIHANDLE hInstall) { #ifdef DLLEXP_EXPORT #pragma comment(linker, DLLEXP_EXPORT) @@ -379,7 +383,8 @@ uiResult =3D MsiRecordSetString(hRecord, 0, L"\"[#bin.openvpn_gui.exe]= \""); if (uiResult !=3D ERROR_SUCCESS) { - SetLastError(uiResult); /* MSDN does not mention MsiRecordSetStrin= g() to set GetLastError(). But we do have an error code. Set last error man= ually. */ + SetLastError(uiResult); /* MSDN does not mention MsiRecordSetStrin= g() to set GetLastError(). + But we do have an error code. Set last = error manually. */ msg(M_NONFATAL | M_ERRNO, "%s: MsiRecordSetString failed", __FUNCT= ION__); goto cleanup_MsiCreateRecord; } @@ -396,25 +401,26 @@ if (szPath =3D=3D NULL) { msg(M_FATAL, "%s: malloc(%u) failed", __FUNCTION__, dwPathSize= * sizeof(WCHAR)); - uiResult =3D ERROR_OUTOFMEMORY; goto cleanup_MsiCreateRecord; + uiResult =3D ERROR_OUTOFMEMORY; + goto cleanup_MsiCreateRecord; } uiResult =3D MsiFormatRecord(hInstall, hRecord, szPath, &dwPathSiz= e); } if (uiResult !=3D ERROR_SUCCESS) { - SetLastError(uiResult); /* MSDN does not mention MsiFormatRecord()= to set GetLastError(). But we do have an error code. Set last error manual= ly. */ + SetLastError(uiResult); /* MSDN does not mention MsiFormatRecord()= to set GetLastError(). + But we do have an error code. Set last = error manually. */ msg(M_NONFATAL | M_ERRNO, "%s: MsiFormatRecord failed", __FUNCTION= __); goto cleanup_malloc_szPath; } /* Launch the OpenVPN GUI. */ - SHELLEXECUTEINFO sei =3D { - .cbSize =3D sizeof(SHELLEXECUTEINFO), - .fMask =3D SEE_MASK_FLAG_NO_UI, /* Don't show error UI, we'll dis= play it. */ - .lpFile =3D szPath, - .nShow =3D SW_SHOWNORMAL - }; + SHELLEXECUTEINFO sei =3D { .cbSize =3D sizeof(SHELLEXECUTEINFO), + .fMask =3D + SEE_MASK_FLAG_NO_UI, /* Don't show error = UI, we'll display it. */ + .lpFile =3D szPath, + .nShow =3D SW_SHOWNORMAL }; if (!ShellExecuteEx(&sei)) { uiResult =3D GetLastError(); @@ -461,12 +467,9 @@ * @return ERROR_SUCCESS on success; An error code otherwise */ static DWORD -schedule_adapter_create( - _Inout_ struct msica_arg_seq *seq, - _Inout_opt_ struct msica_arg_seq *seqRollback, - _In_z_ LPCWSTR szDisplayName, - _In_z_ LPCWSTR szHardwareId, - _Inout_ int *iTicks) +schedule_adapter_create(_Inout_ struct msica_arg_seq *seq, + _Inout_opt_ struct msica_arg_seq *seqRollback, _In= _z_ LPCWSTR szDisplayName, + _In_z_ LPCWSTR szHardwareId, _Inout_ int *iTicks) { /* Get existing network adapters. */ struct tap_adapter_node *pAdapterList =3D NULL; @@ -477,28 +480,25 @@ } /* Does adapter exist? */ - for (struct tap_adapter_node *pAdapterOther =3D pAdapterList;; pAdapte= rOther =3D pAdapterOther->pNext) + for (struct tap_adapter_node *pAdapterOther =3D pAdapterList;; + pAdapterOther =3D pAdapterOther->pNext) { if (pAdapterOther =3D=3D NULL) { /* No adapter with a same name found. */ - WCHAR szArgument[10 /*create=3D""|deleteN=3D""*/ + MAX_PATH /*= szDisplayName*/ + 1 /*|*/ + MAX_PATH /*szHardwareId*/ + 1 /*terminator*/]; + WCHAR szArgument[10 /*create=3D""|deleteN=3D""*/ + MAX_PATH /*= szDisplayName*/ + 1 /*|*/ + + MAX_PATH /*szHardwareId*/ + 1 /*terminator*= /]; /* InstallTUNTAPAdapters will create the adapter. */ - swprintf_s( - szArgument, _countof(szArgument), - L"create=3D\"%.*s|%.*s\"", - MAX_PATH, szDisplayName, - MAX_PATH, szHardwareId); + swprintf_s(szArgument, _countof(szArgument), L"create=3D\"%.*s= |%.*s\"", MAX_PATH, + szDisplayName, MAX_PATH, szHardwareId); msica_arg_seq_add_tail(seq, szArgument); if (seqRollback) { /* InstallTUNTAPAdaptersRollback will delete the adapter. = */ - swprintf_s( - szArgument, _countof(szArgument), - L"deleteN=3D\"%.*s\"", - MAX_PATH, szDisplayName); + swprintf_s(szArgument, _countof(szArgument), L"deleteN=3D\= "%.*s\"", MAX_PATH, + szDisplayName); msica_arg_seq_add_head(seqRollback, szArgument); } @@ -513,13 +513,15 @@ if (hwid[0] =3D=3D 0) { /* This adapter has a different hardware ID. */ - msg(M_NONFATAL, "%s: Adapter with name \"%ls\" already= exists", __FUNCTION__, pAdapterOther->szName); + msg(M_NONFATAL, "%s: Adapter with name \"%ls\" already= exists", __FUNCTION__, + pAdapterOther->szName); dwResult =3D ERROR_ALREADY_EXISTS; goto cleanup_pAdapterList; } else if (wcsicmp(hwid, szHardwareId) =3D=3D 0) { - /* This is an adapter with the requested hardware ID. = We already have what we want! */ + /* This is an adapter with the requested hardware ID. = We already have what we + * want! */ break; } } @@ -561,13 +563,10 @@ * @return ERROR_SUCCESS on success; An error code otherwise */ static DWORD -schedule_adapter_delete( - _Inout_ struct msica_arg_seq *seq, - _Inout_opt_ struct msica_arg_seq *seqCommit, - _Inout_opt_ struct msica_arg_seq *seqRollback, - _In_z_ LPCWSTR szDisplayName, - _In_z_ LPCWSTR szzHardwareIDs, - _Inout_ int *iTicks) +schedule_adapter_delete(_Inout_ struct msica_arg_seq *seq, + _Inout_opt_ struct msica_arg_seq *seqCommit, + _Inout_opt_ struct msica_arg_seq *seqRollback, _In= _z_ LPCWSTR szDisplayName, + _In_z_ LPCWSTR szzHardwareIDs, _Inout_ int *iTicks) { /* Get adapters with given hardware ID. */ struct tap_adapter_node *pAdapterList =3D NULL; @@ -578,42 +577,36 @@ } /* Does adapter exist? */ - for (struct tap_adapter_node *pAdapter =3D pAdapterList; pAdapter !=3D= NULL; pAdapter =3D pAdapter->pNext) + for (struct tap_adapter_node *pAdapter =3D pAdapterList; pAdapter !=3D= NULL; + pAdapter =3D pAdapter->pNext) { if (wcsicmp(szDisplayName, pAdapter->szName) =3D=3D 0) { /* Adapter found. */ - WCHAR szArgument[8 /*disable=3D|enable=3D|delete=3D*/ + 38 /*{= xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}*/ + 1 /*terminator*/]; + WCHAR szArgument[8 /*disable=3D|enable=3D|delete=3D*/ + + 38 /*{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}= */ + 1 /*terminator*/]; if (seqCommit && seqRollback) { /* UninstallTUNTAPAdapters will disable the adapter. */ - swprintf_s( - szArgument, _countof(szArgument), - L"disable=3D" _L(PRIXGUID), - PRIGUID_PARAM(pAdapter->guid)); + swprintf_s(szArgument, _countof(szArgument), L"disable=3D"= _L(PRIXGUID), + PRIGUID_PARAM(pAdapter->guid)); msica_arg_seq_add_tail(seq, szArgument); /* UninstallTUNTAPAdaptersRollback will re-enable the adap= ter. */ - swprintf_s( - szArgument, _countof(szArgument), - L"enable=3D" _L(PRIXGUID), - PRIGUID_PARAM(pAdapter->guid)); + swprintf_s(szArgument, _countof(szArgument), L"enable=3D" = _L(PRIXGUID), + PRIGUID_PARAM(pAdapter->guid)); msica_arg_seq_add_head(seqRollback, szArgument); /* UninstallTUNTAPAdaptersCommit will delete the adapter. = */ - swprintf_s( - szArgument, _countof(szArgument), - L"delete=3D" _L(PRIXGUID), - PRIGUID_PARAM(pAdapter->guid)); + swprintf_s(szArgument, _countof(szArgument), L"delete=3D" = _L(PRIXGUID), + PRIGUID_PARAM(pAdapter->guid)); msica_arg_seq_add_tail(seqCommit, szArgument); } else { /* UninstallTUNTAPAdapters will delete the adapter. */ - swprintf_s( - szArgument, _countof(szArgument), - L"delete=3D" _L(PRIXGUID), - PRIGUID_PARAM(pAdapter->guid)); + swprintf_s(szArgument, _countof(szArgument), L"delete=3D" = _L(PRIXGUID), + PRIGUID_PARAM(pAdapter->guid)); msica_arg_seq_add_tail(seq, szArgument); } @@ -627,8 +620,7 @@ } -UINT __stdcall -EvaluateTUNTAPAdapters(_In_ MSIHANDLE hInstall) +UINT __stdcall EvaluateTUNTAPAdapters(_In_ MSIHANDLE hInstall) { #ifdef DLLEXP_EXPORT #pragma comment(linker, DLLEXP_EXPORT) @@ -641,13 +633,8 @@ OPENVPNMSICA_SAVE_MSI_SESSION(hInstall); - struct msica_arg_seq - seqInstall, - seqInstallCommit, - seqInstallRollback, - seqUninstall, - seqUninstallCommit, - seqUninstallRollback; + struct msica_arg_seq seqInstall, seqInstallCommit, seqInstallRollback,= seqUninstall, + seqUninstallCommit, seqUninstallRollback; msica_arg_seq_init(&seqInstall); msica_arg_seq_init(&seqInstallCommit); msica_arg_seq_init(&seqInstallRollback); @@ -656,7 +643,8 @@ msica_arg_seq_init(&seqUninstallRollback); /* Check rollback state. */ - bool bRollbackEnabled =3D MsiEvaluateCondition(hInstall, L"RollbackDis= abled") !=3D MSICONDITION_TRUE; + bool bRollbackEnabled =3D + MsiEvaluateCondition(hInstall, L"RollbackDisabled") !=3D MSICONDIT= ION_TRUE; /* Open MSI database. */ MSIHANDLE hDatabase =3D MsiGetActiveDatabase(hInstall); @@ -671,7 +659,8 @@ switch (MsiDatabaseIsTablePersistent(hDatabase, L"TUNTAPAdapter")) { case MSICONDITION_FALSE: - case MSICONDITION_TRUE: break; + case MSICONDITION_TRUE: + break; default: uiResult =3D ERROR_SUCCESS; @@ -680,11 +669,14 @@ /* Prepare a query to get a list/view of adapters. */ MSIHANDLE hViewST =3D 0; - LPCWSTR szQuery =3D L"SELECT `Adapter`,`DisplayName`,`Condition`,`Comp= onent_`,`HardwareId` FROM `TUNTAPAdapter`"; + LPCWSTR szQuery =3D + L"SELECT `Adapter`,`DisplayName`,`Condition`,`Component_`,`Hardwar= eId` FROM `TUNTAPAdapter`"; uiResult =3D MsiDatabaseOpenView(hDatabase, szQuery, &hViewST); if (uiResult !=3D ERROR_SUCCESS) { - SetLastError(uiResult); /* MSDN does not mention MsiDatabaseOpenVi= ew() to set GetLastError(). But we do have an error code. Set last error ma= nually. */ + SetLastError( + uiResult); /* MSDN does not mention MsiDatabaseOpenView() to s= et GetLastError(). But we + do have an error code. Set last error manually. = */ msg(M_NONFATAL | M_ERRNO, "%s: MsiDatabaseOpenView(\"%ls\") failed= ", __FUNCTION__, szQuery); goto cleanup_hDatabase; } @@ -693,7 +685,8 @@ uiResult =3D MsiViewExecute(hViewST, 0); if (uiResult !=3D ERROR_SUCCESS) { - SetLastError(uiResult); /* MSDN does not mention MsiViewExecute() = to set GetLastError(). But we do have an error code. Set last error manuall= y. */ + SetLastError(uiResult); /* MSDN does not mention MsiViewExecute() = to set GetLastError(). But + we do have an error code. Set last erro= r manually. */ msg(M_NONFATAL | M_ERRNO, "%s: MsiViewExecute(\"%ls\") failed", __= FUNCTION__, szQuery); goto cleanup_hViewST; } @@ -707,7 +700,7 @@ goto cleanup_hViewST_close; } - for (;; ) + for (;;) { /* Fetch one record from the view. */ MSIHANDLE hRecord =3D 0; @@ -719,7 +712,8 @@ } else if (uiResult !=3D ERROR_SUCCESS) { - SetLastError(uiResult); /* MSDN does not mention MsiViewFetch(= ) to set GetLastError(). But we do have an error code. Set last error manua= lly. */ + SetLastError(uiResult); /* MSDN does not mention MsiViewFetch(= ) to set GetLastError(). + But we do have an error code. Set l= ast error manually. */ msg(M_NONFATAL | M_ERRNO, "%s: MsiViewFetch failed", __FUNCTIO= N__); goto cleanup_hRecordProg; } @@ -738,8 +732,11 @@ uiResult =3D MsiGetComponentState(hInstall, szValue, &iInstall= ed, &iAction); if (uiResult !=3D ERROR_SUCCESS) { - SetLastError(uiResult); /* MSDN does not mention MsiGetCom= ponentState() to set GetLastError(). But we do have an error code. Set last= error manually. */ - msg(M_NONFATAL | M_ERRNO, "%s: MsiGetComponentState(\"%ls\= ") failed", __FUNCTION__, szValue); + SetLastError(uiResult); /* MSDN does not mention MsiGetCom= ponentState() to set + GetLastError(). But we do have = an error code. Set last + error manually. */ + msg(M_NONFATAL | M_ERRNO, "%s: MsiGetComponentState(\"%ls\= ") failed", __FUNCTION__, + szValue); free(szValue); goto cleanup_hRecord; } @@ -753,7 +750,9 @@ { goto cleanup_hRecord; } - /* `DisplayName` field type is [Filename](https://docs.microsoft.c= om/en-us/windows/win32/msi/filename), which is either "8.3|long name" or "8= .3". */ + /* `DisplayName` field type is + * [Filename](https://docs.microsoft.com/en-us/windows/win32/msi/f= ilename), which is either + * "8.3|long name" or "8.3". */ LPWSTR szDisplayNameEx =3D wcschr(szDisplayName, L'|'); szDisplayNameEx =3D szDisplayNameEx !=3D NULL ? szDisplayNameEx + = 1 : szDisplayName; @@ -766,7 +765,10 @@ { goto cleanup_szDisplayName; } - memcpy_s(szzHardwareIDs, sizeof(szzHardwareIDs) - 2*sizeof(WCH= AR) /*requires double zero termination*/, szHwId, wcslen(szHwId)*sizeof(WCH= AR)); + memcpy_s(szzHardwareIDs, + sizeof(szzHardwareIDs) + - 2 * sizeof(WCHAR) /*requires double zero termin= ation*/, + szHwId, wcslen(szHwId) * sizeof(WCHAR)); free(szHwId); } @@ -799,7 +801,8 @@ case MSICONDITION_ERROR: uiResult =3D ERROR_INVALID_FIELD; - msg(M_NONFATAL | M_ERRNO, "%s: MsiEvaluateConditio= n(\"%ls\") failed", __FUNCTION__, szValue); + msg(M_NONFATAL | M_ERRNO, "%s: MsiEvaluateConditio= n(\"%ls\") failed", + __FUNCTION__, szValue); free(szValue); goto cleanup_szDisplayName; } @@ -809,12 +812,10 @@ free(szValue); /* Component is or should be installed. Schedule adapter c= reation. */ - if (schedule_adapter_create( - &seqInstall, - bRollbackEnabled ? &seqInstallRollback : NULL, - szDisplayNameEx, - szzHardwareIDs, - &iTicks) !=3D ERROR_SUCCESS) + if (schedule_adapter_create(&seqInstall, + bRollbackEnabled ? &seqInstall= Rollback : NULL, + szDisplayNameEx, szzHardwareID= s, &iTicks) + !=3D ERROR_SUCCESS) { uiResult =3D ERROR_INSTALL_FAILED; goto cleanup_szDisplayName; @@ -822,18 +823,16 @@ } else { - /* Component is installed, but should be degraded to adver= tised/removed. Schedule adapter deletition. + /* Component is installed, but should be degraded to adver= tised/removed. Schedule + * adapter deletition. * - * Note: On adapter removal (product is being uninstalled)= , we tolerate dwResult error. - * Better a partial uninstallation than no uninstallation = at all. + * Note: On adapter removal (product is being uninstalled)= , we tolerate dwResult + * error. Better a partial uninstallation than no uninstal= lation at all. */ - schedule_adapter_delete( - &seqUninstall, - bRollbackEnabled ? &seqUninstallCommit : NULL, - bRollbackEnabled ? &seqUninstallRollback : NULL, - szDisplayNameEx, - szzHardwareIDs, - &iTicks); + schedule_adapter_delete(&seqUninstall, + bRollbackEnabled ? &seqUninstallCo= mmit : NULL, + bRollbackEnabled ? &seqUninstallRo= llback : NULL, + szDisplayNameEx, szzHardwareIDs, &= iTicks); } /* Arrange the amount of tick space to add to the progress ind= icator. @@ -871,12 +870,21 @@ msica_arg_seq_add_tail(&seqUninstallRollback, str); /* Store deferred custom action parameters. */ - if ((uiResult =3D setup_sequence(hInstall, L"InstallTUNTAPAdapters", &= seqInstall )) !=3D ERROR_SUCCESS - || (uiResult =3D setup_sequence(hInstall, L"InstallTUNTAPAdaptersC= ommit", &seqInstallCommit )) !=3D ERROR_SUCCESS - || (uiResult =3D setup_sequence(hInstall, L"InstallTUNTAPAdaptersR= ollback", &seqInstallRollback )) !=3D ERROR_SUCCESS - || (uiResult =3D setup_sequence(hInstall, L"UninstallTUNTAPAdapter= s", &seqUninstall )) !=3D ERROR_SUCCESS - || (uiResult =3D setup_sequence(hInstall, L"UninstallTUNTAPAdapter= sCommit", &seqUninstallCommit )) !=3D ERROR_SUCCESS - || (uiResult =3D setup_sequence(hInstall, L"UninstallTUNTAPAdapter= sRollback", &seqUninstallRollback)) !=3D ERROR_SUCCESS) + if ((uiResult =3D setup_sequence(hInstall, L"InstallTUNTAPAdapters", &= seqInstall)) + !=3D ERROR_SUCCESS + || (uiResult =3D setup_sequence(hInstall, L"InstallTUNTAPAdaptersC= ommit", &seqInstallCommit)) + !=3D ERROR_SUCCESS + || (uiResult =3D + setup_sequence(hInstall, L"InstallTUNTAPAdaptersRollback",= &seqInstallRollback)) + !=3D ERROR_SUCCESS + || (uiResult =3D setup_sequence(hInstall, L"UninstallTUNTAPAdapter= s", &seqUninstall)) + !=3D ERROR_SUCCESS + || (uiResult =3D + setup_sequence(hInstall, L"UninstallTUNTAPAdaptersCommit",= &seqUninstallCommit)) + !=3D ERROR_SUCCESS + || (uiResult =3D + setup_sequence(hInstall, L"UninstallTUNTAPAdaptersRollback= ", &seqUninstallRollback)) + !=3D ERROR_SUCCESS) { goto cleanup_hRecordProg; } @@ -916,9 +924,7 @@ * @return TRUE on success; FALSE otherwise */ static BOOL -parse_guid( - _In_z_ LPCWSTR szArg, - _Out_ GUID *guid) +parse_guid(_In_z_ LPCWSTR szArg, _Out_ GUID *guid) { if (swscanf_s(szArg, _L(PRIXGUID), PRIGUID_PARAM_REF(*guid)) !=3D 11) { @@ -945,7 +951,8 @@ msg(M_WARN, "%s: Reboot required, create reboot indication file \"%ls\= "", __FUNCTION__, path); - HANDLE file =3D CreateFileW(path, GENERIC_WRITE, 0, NULL, CREATE_ALWAY= S, FILE_ATTRIBUTE_NORMAL, NULL); + HANDLE file =3D + CreateFileW(path, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTR= IBUTE_NORMAL, NULL); if (file =3D=3D INVALID_HANDLE_VALUE) { msg(M_NONFATAL | M_ERRNO, "%s: CreateFile(\"%ls\") failed", __FUNC= TION__, path); @@ -956,8 +963,7 @@ } } -UINT __stdcall -ProcessDeferredAction(_In_ MSIHANDLE hInstall) +UINT __stdcall ProcessDeferredAction(_In_ MSIHANDLE hInstall) { #ifdef DLLEXP_EXPORT #pragma comment(linker, DLLEXP_EXPORT) @@ -967,13 +973,15 @@ UINT uiResult; BOOL bIsCoInitialized =3D SUCCEEDED(CoInitialize(NULL)); - WCHAR tmpDir[MAX_PATH] =3D {0}; + WCHAR tmpDir[MAX_PATH] =3D { 0 }; OPENVPNMSICA_SAVE_MSI_SESSION(hInstall); - BOOL bIsCleanup =3D MsiGetMode(hInstall, MSIRUNMODE_COMMIT) || MsiGetM= ode(hInstall, MSIRUNMODE_ROLLBACK); + BOOL bIsCleanup =3D + MsiGetMode(hInstall, MSIRUNMODE_COMMIT) || MsiGetMode(hInstall, MS= IRUNMODE_ROLLBACK); - /* Get sequence arguments. Always Unicode as CommandLineToArgvW() is a= vailable as Unicode-only. */ + /* Get sequence arguments. Always Unicode as CommandLineToArgvW() is a= vailable as Unicode-only. + */ LPWSTR szSequence =3D NULL; uiResult =3D msi_get_string(hInstall, L"CustomActionData", &szSequence= ); if (uiResult !=3D ERROR_SUCCESS) @@ -985,7 +993,8 @@ if (szArg =3D=3D NULL) { uiResult =3D GetLastError(); - msg(M_NONFATAL | M_ERRNO, "%s: CommandLineToArgvW(\"%ls\") failed"= , __FUNCTION__, szSequence); + msg(M_NONFATAL | M_ERRNO, "%s: CommandLineToArgvW(\"%ls\") failed"= , __FUNCTION__, + szSequence); goto cleanup_szSequence; } @@ -1037,8 +1046,8 @@ dwResult =3D tap_create_adapter(NULL, NULL, szHardwareId, &bRe= bootRequired, &guidAdapter); if (dwResult =3D=3D ERROR_SUCCESS) { - /* Set adapter name. May fail on some machines, but that i= s not critical - use silent - * flag to mute messagebox and print error only to log */ + /* Set adapter name. May fail on some machines, but that i= s not critical - use + * silent flag to mute messagebox and print error only to = log */ tap_set_adapter_name(&guidAdapter, szName, TRUE); } } @@ -1067,7 +1076,8 @@ if (dwResult =3D=3D ERROR_SUCCESS) { /* Does the adapter exist? */ - for (struct tap_adapter_node *pAdapter =3D pAdapterList; p= Adapter !=3D NULL; pAdapter =3D pAdapter->pNext) + for (struct tap_adapter_node *pAdapter =3D pAdapterList; p= Adapter !=3D NULL; + pAdapter =3D pAdapter->pNext) { if (wcsicmp(szName, pAdapter->szName) =3D=3D 0) { @@ -1156,8 +1166,7 @@ return uiResult; } -UINT __stdcall -CheckAndScheduleReboot(_In_ MSIHANDLE hInstall) +UINT __stdcall CheckAndScheduleReboot(_In_ MSIHANDLE hInstall) { #ifdef DLLEXP_EXPORT #pragma comment(linker, DLLEXP_EXPORT) diff --git a/src/openvpnmsica/openvpnmsica.h b/src/openvpnmsica/openvpnmsic= a.h index d07554f..c3e0445 100644 --- a/src/openvpnmsica/openvpnmsica.h +++ b/src/openvpnmsica/openvpnmsica.h @@ -50,10 +50,11 @@ /** * Set MSI session handle in thread local storage. */ -#define OPENVPNMSICA_SAVE_MSI_SESSION(hInstall) \ - { \ - struct openvpnmsica_thread_data *s =3D (struct openvpnmsica_thread= _data *)TlsGetValue(openvpnmsica_thread_data_idx); \ - s->hInstall =3D (hInstall); \ +#define OPENVPNMSICA_SAVE_MSI_SESSION(hInstall) = \ + { = \ + struct openvpnmsica_thread_data *s =3D = \ + (struct openvpnmsica_thread_data *)TlsGetValue(openvpnmsica_th= read_data_idx); \ + s->hInstall =3D (hInstall); = \ } @@ -62,7 +63,8 @@ */ #ifdef __cplusplus -extern "C" { +extern "C" +{ #endif /* Ensure that clang-cl, which does not understand the cl specific @@ -77,90 +79,84 @@ #endif -/** - * Determines Windows information: - * - * - Sets `OPENVPNSERVICE` MSI property to PID of OpenVPN Service if runni= ng, or its EXE path if - * configured for auto-start. - * - * - Finds existing TAP-Windows6 adapters and set TAPWINDOWS6ADAPTERS and - * ACTIVETAPWINDOWS6ADAPTERS properties with semicolon delimited list of= all installed adapter - * GUIDs and active adapter GUIDs respectively. - * - * - Finds existing ovpn-dco adapters and set OVPNDCOADAPTERS and ACTIVEOV= PNDCOADAPTERS properties - * with semicolon delimited list of all installed adapter GUIDs and acti= ve adapter GUIDs - * respectively. - * - * @param hInstall Handle to the installation provided to the DLL cus= tom action - * - * @return ERROR_SUCCESS on success; An error code otherwise - * See: https://msdn.microsoft.com/en-us/library/windows/desktop/a= a368072.aspx - */ -DLLEXP_DECL UINT __stdcall -FindSystemInfo(_In_ MSIHANDLE hInstall); + /** + * Determines Windows information: + * + * - Sets `OPENVPNSERVICE` MSI property to PID of OpenVPN Service if r= unning, or its EXE path if + * configured for auto-start. + * + * - Finds existing TAP-Windows6 adapters and set TAPWINDOWS6ADAPTERS = and + * ACTIVETAPWINDOWS6ADAPTERS properties with semicolon delimited lis= t of all installed adapter + * GUIDs and active adapter GUIDs respectively. + * + * - Finds existing ovpn-dco adapters and set OVPNDCOADAPTERS and ACTI= VEOVPNDCOADAPTERS + * properties with semicolon delimited list of all installed adapter G= UIDs and active adapter + * GUIDs respectively. + * + * @param hInstall Handle to the installation provided to the DLL= custom action + * + * @return ERROR_SUCCESS on success; An error code otherwise + * See: https://msdn.microsoft.com/en-us/library/windows/deskt= op/aa368072.aspx + */ + DLLEXP_DECL UINT __stdcall FindSystemInfo(_In_ MSIHANDLE hInstall); -/** - * Find OpenVPN GUI window and send it a WM_CLOSE message. - * - * @param hInstall Handle to the installation provided to the DLL cus= tom action - * - * @return ERROR_SUCCESS on success; An error code otherwise - * See: https://msdn.microsoft.com/en-us/library/windows/desktop/a= a368072.aspx - */ -DLLEXP_DECL UINT __stdcall -CloseOpenVPNGUI(_In_ MSIHANDLE hInstall); + /** + * Find OpenVPN GUI window and send it a WM_CLOSE message. + * + * @param hInstall Handle to the installation provided to the DLL= custom action + * + * @return ERROR_SUCCESS on success; An error code otherwise + * See: https://msdn.microsoft.com/en-us/library/windows/deskt= op/aa368072.aspx + */ + DLLEXP_DECL UINT __stdcall CloseOpenVPNGUI(_In_ MSIHANDLE hInstall); -/** - * Launches OpenVPN GUI. It's path is obtained by expanding the `[#bin.ope= nvpn_gui.exe]` - * therefore, its Id field in File table must be "bin.openvpn_gui.exe". - * - * @param hInstall Handle to the installation provided to the DLL cus= tom action - * - * @return ERROR_SUCCESS on success; An error code otherwise - * See: https://msdn.microsoft.com/en-us/library/windows/desktop/a= a368072.aspx - */ -DLLEXP_DECL UINT __stdcall -StartOpenVPNGUI(_In_ MSIHANDLE hInstall); + /** + * Launches OpenVPN GUI. It's path is obtained by expanding the `[#bin= .openvpn_gui.exe]` + * therefore, its Id field in File table must be "bin.openvpn_gui.exe". + * + * @param hInstall Handle to the installation provided to the DLL= custom action + * + * @return ERROR_SUCCESS on success; An error code otherwise + * See: https://msdn.microsoft.com/en-us/library/windows/deskt= op/aa368072.aspx + */ + DLLEXP_DECL UINT __stdcall StartOpenVPNGUI(_In_ MSIHANDLE hInstall); -/** - * Evaluate the TUNTAPAdapter table of the MSI package database and prepar= e a list of TAP - * adapters to install/remove. - * - * @param hInstall Handle to the installation provided to the DLL cus= tom action - * - * @return ERROR_SUCCESS on success; An error code otherwise - * See: https://msdn.microsoft.com/en-us/library/windows/desktop/a= a368072.aspx - */ -DLLEXP_DECL UINT __stdcall -EvaluateTUNTAPAdapters(_In_ MSIHANDLE hInstall); + /** + * Evaluate the TUNTAPAdapter table of the MSI package database and pr= epare a list of TAP + * adapters to install/remove. + * + * @param hInstall Handle to the installation provided to the DLL= custom action + * + * @return ERROR_SUCCESS on success; An error code otherwise + * See: https://msdn.microsoft.com/en-us/library/windows/deskt= op/aa368072.aspx + */ + DLLEXP_DECL UINT __stdcall EvaluateTUNTAPAdapters(_In_ MSIHANDLE hInst= all); -/** - * Perform scheduled deferred action. - * - * @param hInstall Handle to the installation provided to the DLL cus= tom action - * - * @return ERROR_SUCCESS on success; An error code otherwise - * See: https://msdn.microsoft.com/en-us/library/windows/desktop/a= a368072.aspx - */ -DLLEXP_DECL UINT __stdcall -ProcessDeferredAction(_In_ MSIHANDLE hInstall); + /** + * Perform scheduled deferred action. + * + * @param hInstall Handle to the installation provided to the DLL= custom action + * + * @return ERROR_SUCCESS on success; An error code otherwise + * See: https://msdn.microsoft.com/en-us/library/windows/deskt= op/aa368072.aspx + */ + DLLEXP_DECL UINT __stdcall ProcessDeferredAction(_In_ MSIHANDLE hInsta= ll); -/** - * Schedule reboot after installation if reboot - * indication file is found in user's temp directory - * - * @param hInstall Handle to the installation provided to the DLL cus= tom action - * - * @return ERROR_SUCCESS on success; An error code otherwise - * See: https://msdn.microsoft.com/en-us/library/windows/desktop/a= a368072.aspx - */ -DLLEXP_DECL UINT __stdcall -CheckAndScheduleReboot(_In_ MSIHANDLE hInstall); + /** + * Schedule reboot after installation if reboot + * indication file is found in user's temp directory + * + * @param hInstall Handle to the installation provided to the DLL= custom action + * + * @return ERROR_SUCCESS on success; An error code otherwise + * See: https://msdn.microsoft.com/en-us/library/windows/deskt= op/aa368072.aspx + */ + DLLEXP_DECL UINT __stdcall CheckAndScheduleReboot(_In_ MSIHANDLE hInst= all); #ifdef __cplusplus } diff --git a/src/openvpnserv/common.c b/src/openvpnserv/common.c index 5543c37..a42c65d 100644 --- a/src/openvpnserv/common.c +++ b/src/openvpnserv/common.c @@ -29,12 +29,11 @@ static DWORD GetRegString(HKEY key, LPCWSTR value, LPWSTR data, DWORD size, LPCWSTR def= ault_value) { - LONG status =3D RegGetValue(key, NULL, value, RRF_RT_REG_SZ, - NULL, (LPBYTE) data, &size); + LONG status =3D RegGetValue(key, NULL, value, RRF_RT_REG_SZ, NULL, (LP= BYTE)data, &size); if (status =3D=3D ERROR_FILE_NOT_FOUND && default_value) { - size_t len =3D size/sizeof(data[0]); + size_t len =3D size / sizeof(data[0]); if (swprintf(data, len, default_value)) { status =3D ERROR_SUCCESS; @@ -44,7 +43,10 @@ if (status !=3D ERROR_SUCCESS) { SetLastError(status); - return MsgToEventLog(M_SYSERR, L"Error querying registry value: HK= LM\\SOFTWARE\\" _L(PACKAGE_NAME) L"%ls\\%ls", service_instance, value); + return MsgToEventLog( + M_SYSERR, + L"Error querying registry value: HKLM\\SOFTWARE\\" _L(PACKAGE_= NAME) L"%ls\\%ls", + service_instance, value); } return ERROR_SUCCESS; @@ -68,7 +70,8 @@ if (status !=3D ERROR_SUCCESS) { SetLastError(status); - return MsgToEventLog(M_SYSERR, L"Could not open Registry key HKLM\= \%ls not found", reg_path); + return MsgToEventLog(M_SYSERR, L"Could not open Registry key HKLM\= \%ls not found", + reg_path); } /* The default value of REG_KEY is the install path */ @@ -79,8 +82,7 @@ goto out; } - swprintf(default_value, _countof(default_value), L"%ls\\bin\\openvpn.e= xe", - install_path); + swprintf(default_value, _countof(default_value), L"%ls\\bin\\openvpn.e= xe", install_path); error =3D GetRegString(key, L"exe_path", s->exe_path, sizeof(s->exe_pa= th), default_value); if (error !=3D ERROR_SUCCESS) { @@ -88,23 +90,20 @@ } swprintf(default_value, _countof(default_value), L"%ls\\config", insta= ll_path); - error =3D GetRegString(key, L"config_dir", s->config_dir, sizeof(s->co= nfig_dir), - default_value); + error =3D GetRegString(key, L"config_dir", s->config_dir, sizeof(s->co= nfig_dir), default_value); if (error !=3D ERROR_SUCCESS) { goto out; } swprintf(default_value, _countof(default_value), L"%ls\\bin", install_= path); - error =3D GetRegString(key, L"bin_dir", s->bin_dir, sizeof(s->bin_dir), - default_value); + error =3D GetRegString(key, L"bin_dir", s->bin_dir, sizeof(s->bin_dir)= , default_value); if (error !=3D ERROR_SUCCESS) { goto out; } - error =3D GetRegString(key, L"config_ext", s->ext_string, sizeof(s->ex= t_string), - L".ovpn"); + error =3D GetRegString(key, L"config_ext", s->ext_string, sizeof(s->ex= t_string), L".ovpn"); if (error !=3D ERROR_SUCCESS) { goto out; @@ -117,8 +116,7 @@ goto out; } - error =3D GetRegString(key, L"priority", priority, sizeof(priority), - L"NORMAL_PRIORITY_CLASS"); + error =3D GetRegString(key, L"priority", priority, sizeof(priority), L= "NORMAL_PRIORITY_CLASS"); if (error !=3D ERROR_SUCCESS) { goto out; @@ -131,8 +129,8 @@ } /* read if present, else use default */ - error =3D GetRegString(key, L"ovpn_admin_group", s->ovpn_admin_group, - sizeof(s->ovpn_admin_group), OVPN_ADMIN_GROUP); + error =3D GetRegString(key, L"ovpn_admin_group", s->ovpn_admin_group, = sizeof(s->ovpn_admin_group), + OVPN_ADMIN_GROUP); if (error !=3D ERROR_SUCCESS) { goto out; @@ -185,7 +183,8 @@ else { SetLastError(ERROR_INVALID_DATA); - error =3D MsgToEventLog(M_ERR, L"Log file append flag (given as '%= ls') must be '0' or '1'", append); + error =3D MsgToEventLog(M_ERR, L"Log file append flag (given as '%= ls') must be '0' or '1'", + append); goto out; } @@ -204,10 +203,11 @@ LPWSTR tmp =3D NULL; error =3D GetLastError(); - len =3D FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_= FROM_SYSTEM | FORMAT_MESSAGE_ARGUMENT_ARRAY, + len =3D FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_= FROM_SYSTEM + | FORMAT_MESSAGE_ARGUMENT_ARRAY, NULL, error, LANG_NEUTRAL, tmp, 0, NULL); - if (len =3D=3D 0 || (long) _countof(buf) < (long) len + 14) + if (len =3D=3D 0 || (long)_countof(buf) < (long)len + 14) { buf[0] =3D L'\0'; } @@ -244,8 +244,7 @@ hEventSource =3D RegisterEventSource(NULL, APPNAME); if (hEventSource !=3D NULL) { - swprintf(msg[0], _countof(msg[0]), - L"%ls%ls%ls: %ls", APPNAME, service_instance, + swprintf(msg[0], _countof(msg[0]), L"%ls%ls%ls: %ls", APPNAME, ser= vice_instance, (flags & MSG_FLAGS_ERROR) ? L" error" : L"", err_msg); va_start(arglist, format); @@ -253,9 +252,9 @@ va_end(arglist); const WCHAR *mesg[] =3D { msg[0], msg[1] }; - ReportEvent(hEventSource, flags & MSG_FLAGS_ERROR ? - EVENTLOG_ERROR_TYPE : EVENTLOG_INFORMATION_TYPE, - 0, 0, NULL, 2, 0, mesg, NULL); + ReportEvent(hEventSource, + flags & MSG_FLAGS_ERROR ? EVENTLOG_ERROR_TYPE : EVENTL= OG_INFORMATION_TYPE, 0, 0, + NULL, 2, 0, mesg, NULL); DeregisterEventSource(hEventSource); } diff --git a/src/openvpnserv/interactive.c b/src/openvpnserv/interactive.c index bc63296..0983e59 100644 --- a/src/openvpnserv/interactive.c +++ b/src/openvpnserv/interactive.c @@ -40,32 +40,30 @@ #include "validate.h" #include "wfp_block.h" -#define IO_TIMEOUT 2000 /*ms*/ +#define IO_TIMEOUT 2000 /*ms*/ -#define ERROR_OPENVPN_STARTUP 0x20000000 -#define ERROR_STARTUP_DATA 0x20000001 -#define ERROR_MESSAGE_DATA 0x20000002 -#define ERROR_MESSAGE_TYPE 0x20000003 +#define ERROR_OPENVPN_STARTUP 0x20000000 +#define ERROR_STARTUP_DATA 0x20000001 +#define ERROR_MESSAGE_DATA 0x20000002 +#define ERROR_MESSAGE_TYPE 0x20000003 static SERVICE_STATUS_HANDLE service; static SERVICE_STATUS status =3D { .dwServiceType =3D SERVICE_WIN32_SHARE_= PROCESS }; static HANDLE exit_event =3D NULL; static settings_t settings; static HANDLE rdns_semaphore =3D NULL; -#define RDNS_TIMEOUT 600 /* seconds to wait for the semaphore */ +#define RDNS_TIMEOUT 600 /* seconds to wait for the semaphore */ -#define TUN_IOCTL_REGISTER_RINGS CTL_CODE(51820U, 0x970U, METHOD_BUFFERED,= FILE_READ_DATA | FILE_WRITE_DATA) +#define TUN_IOCTL_REGISTER_RINGS \ + CTL_CODE(51820U, 0x970U, METHOD_BUFFERED, FILE_READ_DATA | FILE_WRITE_= DATA) -openvpn_service_t interactive_service =3D { - interactive, - _L(PACKAGE_NAME) L"ServiceInteractive", - _L(PACKAGE_NAME) L" Interactive Service", - SERVICE_DEPENDENCIES, - SERVICE_AUTO_START -}; +openvpn_service_t interactive_service =3D { interactive, _L(PACKAGE_NAME) = L"ServiceInteractive", + _L(PACKAGE_NAME) L" Interactive = Service", + SERVICE_DEPENDENCIES, SERVICE_AU= TO_START }; -typedef struct { +typedef struct +{ WCHAR *directory; WCHAR *options; WCHAR *std_input; @@ -73,14 +71,16 @@ /* Datatype for linked lists */ -typedef struct _list_item { +typedef struct _list_item +{ struct _list_item *next; LPVOID data; } list_item_t; /* Datatypes for undo information */ -typedef enum { +typedef enum +{ address, route, wfp_block, @@ -93,19 +93,22 @@ } undo_type_t; typedef list_item_t *undo_lists_t[_undo_type_max]; -typedef struct { +typedef struct +{ HANDLE engine; int index; int metric_v4; int metric_v6; } wfp_block_data_t; -typedef struct { +typedef struct +{ char itf_name[256]; PWSTR domains; } dns_domains_undo_data_t; -typedef union { +typedef union +{ message_header_t header; address_message_t address; route_message_t route; @@ -119,7 +122,8 @@ create_adapter_message_t create_adapter; } pipe_message_t; -typedef struct { +typedef struct +{ CHAR addresses[NRPT_ADDR_NUM * NRPT_ADDR_SIZE]; WCHAR domains[512]; /* MULTI_SZ string */ DWORD domains_size; /* bytes in domains */ @@ -142,7 +146,7 @@ return NO_ERROR; } -typedef BOOL (*match_fn_t) (LPVOID item, LPVOID ctx); +typedef BOOL (*match_fn_t)(LPVOID item, LPVOID ctx); static LPVOID RemoveListItem(list_item_t **pfirst, match_fn_t match, LPVOID ctx) @@ -201,7 +205,8 @@ } -typedef enum { +typedef enum +{ peek, read, write @@ -248,8 +253,7 @@ handles[i + 1] =3D events[i]; } - res =3D WaitForMultipleObjects(count + 1, handles, FALSE, - op =3D=3D peek ? INFINITE : IO_TIMEOUT); + res =3D WaitForMultipleObjects(count + 1, handles, FALSE, op =3D=3D pe= ek ? INFINITE : IO_TIMEOUT); if (res !=3D WAIT_OBJECT_0) { CancelIo(pipe); @@ -309,32 +313,25 @@ { DWORD result_len; LPWSTR result =3D L"0xffffffff\nFormatMessage failed\nCould not return= result"; - DWORD_PTR args[] =3D { - (DWORD_PTR) error, - (DWORD_PTR) func, - (DWORD_PTR) "" - }; + DWORD_PTR args[] =3D { (DWORD_PTR)error, (DWORD_PTR)func, (DWORD_PTR) = "" }; if (error !=3D ERROR_OPENVPN_STARTUP) { - FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM - |FORMAT_MESSAGE_ALLOCATE_BUFFER - |FORMAT_MESSAGE_IGNORE_INSERTS, - 0, error, 0, (LPWSTR) &args[2], 0, NULL); + FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCAT= E_BUFFER + | FORMAT_MESSAGE_IGNORE_INSERTS, + 0, error, 0, (LPWSTR)&args[2], 0, NULL); } - result_len =3D FormatMessageW(FORMAT_MESSAGE_FROM_STRING - |FORMAT_MESSAGE_ALLOCATE_BUFFER - |FORMAT_MESSAGE_ARGUMENT_ARRAY, - L"0x%1!08x!\n%2!s!\n%3!s!", 0, 0, - (LPWSTR) &result, 0, (va_list *) args); + result_len =3D FormatMessageW( + FORMAT_MESSAGE_FROM_STRING | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORM= AT_MESSAGE_ARGUMENT_ARRAY, + L"0x%1!08x!\n%2!s!\n%3!s!", 0, 0, (LPWSTR)&result, 0, (va_list *)a= rgs); WritePipeAsync(pipe, result, (DWORD)(wcslen(result) * 2), count, event= s); MsgToEventLog(MSG_FLAGS_ERROR, result); if (error !=3D ERROR_OPENVPN_STARTUP) { - LocalFree((LPVOID) args[2]); + LocalFree((LPVOID)args[2]); } if (result_len) { @@ -355,7 +352,8 @@ * Returns true on success, false on error with reason set in errmsg. */ static BOOL -ValidateOptions(HANDLE pipe, const WCHAR *workdir, const WCHAR *options, W= CHAR *errmsg, DWORD capacity) +ValidateOptions(HANDLE pipe, const WCHAR *workdir, const WCHAR *options, W= CHAR *errmsg, + DWORD capacity) { WCHAR **argv; int argc; @@ -380,7 +378,7 @@ } /* Note: argv[0] is the first option */ - if (argc < 1) /* no options */ + if (argc < 1) /* no options */ { ret =3D TRUE; goto out; @@ -395,8 +393,7 @@ if (!CheckOption(workdir, 2, argv_tmp, &settings)) { - swprintf(errmsg, capacity, msg1, argv[0], workdir, - settings.ovpn_admin_group); + swprintf(errmsg, capacity, msg1, argv[0], workdir, settings.ov= pn_admin_group); } goto out; } @@ -408,17 +405,15 @@ continue; } - if (!CheckOption(workdir, argc-i, &argv[i], &settings)) + if (!CheckOption(workdir, argc - i, &argv[i], &settings)) { - if (wcscmp(L"--config", argv[i]) =3D=3D 0 && argc-i > 1) + if (wcscmp(L"--config", argv[i]) =3D=3D 0 && argc - i > 1) { - swprintf(errmsg, capacity, msg1, argv[i+1], workdir, - settings.ovpn_admin_group); + swprintf(errmsg, capacity, msg1, argv[i + 1], workdir, set= tings.ovpn_admin_group); } else { - swprintf(errmsg, capacity, msg2, argv[i], - settings.ovpn_admin_group); + swprintf(errmsg, capacity, msg2, argv[i], settings.ovpn_ad= min_group); } goto out; } @@ -505,7 +500,7 @@ return TRUE; err: - sud->directory =3D NULL; /* caller must not free() */ + sud->directory =3D NULL; /* caller must not free() */ free(data); return FALSE; } @@ -580,7 +575,7 @@ InitializeUnicastIpAddressEntry(addr_row); addr_row->Address =3D sockaddr_inet(msg->family, &msg->address); - addr_row->OnLinkPrefixLength =3D (UINT8) msg->prefix_len; + addr_row->OnLinkPrefixLength =3D (UINT8)msg->prefix_len; if (msg->iface.index !=3D -1) { @@ -662,7 +657,7 @@ fwd_row->Protocol =3D MIB_IPPROTO_NETMGMT; fwd_row->Metric =3D msg->metric; fwd_row->DestinationPrefix.Prefix =3D sockaddr_inet(msg->family, &msg-= >prefix); - fwd_row->DestinationPrefix.PrefixLength =3D (UINT8) msg->prefix_len; + fwd_row->DestinationPrefix.PrefixLength =3D (UINT8)msg->prefix_len; fwd_row->NextHop =3D sockaddr_inet(msg->family, &msg->gateway); if (msg->iface.index !=3D -1) @@ -740,7 +735,7 @@ err_str =3D L"Unknown Win32 Error"; if (FormatMessage(FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_= SYSTEM - | FORMAT_MESSAGE_ARGUMENT_ARRAY, + | FORMAT_MESSAGE_ARGUMENT_ARRAY, NULL, err, 0, buf, sizeof(buf), NULL)) { err_str =3D buf; @@ -767,13 +762,11 @@ err =3D delete_wfp_block_filters(block_data->engine); if (block_data->metric_v4 >=3D 0) { - set_interface_metric(msg->iface.index, AF_INET, - block_data->metric_v4); + set_interface_metric(msg->iface.index, AF_INET, block_data->me= tric_v4); } if (block_data->metric_v6 >=3D 0) { - set_interface_metric(msg->iface.index, AF_INET6, - block_data->metric_v6); + set_interface_metric(msg->iface.index, AF_INET6, block_data->m= etric_v6); } free(block_data); } @@ -809,14 +802,12 @@ block_data->engine =3D engine; block_data->index =3D msg->iface.index; int is_auto =3D 0; - block_data->metric_v4 =3D get_interface_metric(msg->iface.index, - AF_INET, &is_auto); + block_data->metric_v4 =3D get_interface_metric(msg->iface.index, A= F_INET, &is_auto); if (is_auto) { block_data->metric_v4 =3D 0; } - block_data->metric_v6 =3D get_interface_metric(msg->iface.index, - AF_INET6, &is_auto); + block_data->metric_v6 =3D get_interface_metric(msg->iface.index, A= F_INET6, &is_auto); if (is_auto) { block_data->metric_v6 =3D 0; @@ -825,8 +816,7 @@ err =3D AddListItem(&(*lists)[wfp_block], block_data); if (!err) { - err =3D set_interface_metric(msg->iface.index, AF_INET, - WFP_BLOCK_IFACE_METRIC); + err =3D set_interface_metric(msg->iface.index, AF_INET, WFP_BL= OCK_IFACE_METRIC); if (!err) { /* for IPv6, we intentionally ignore errors, because @@ -834,8 +824,7 @@ * admin has disabled IPv6 on the tun/tap/dco interface * (if OpenVPN wants IPv6 ifconfig, we'll fail there) */ - set_interface_metric(msg->iface.index, AF_INET6, - WFP_BLOCK_IFACE_METRIC); + set_interface_metric(msg->iface.index, AF_INET6, WFP_BLOCK= _IFACE_METRIC); } if (err) { @@ -880,7 +869,7 @@ DWORD exit_code; STARTUPINFOW si; PROCESS_INFORMATION pi; - DWORD proc_flags =3D CREATE_NO_WINDOW|CREATE_UNICODE_ENVIRONMENT; + DWORD proc_flags =3D CREATE_NO_WINDOW | CREATE_UNICODE_ENVIRONMENT; WCHAR *cmdline_dup =3D NULL; ZeroMemory(&si, sizeof(si)); @@ -890,8 +879,8 @@ /* CreateProcess needs a modifiable cmdline: make a copy */ cmdline_dup =3D _wcsdup(cmdline); - if (cmdline_dup && CreateProcessW(argv0, cmdline_dup, NULL, NULL, FALS= E, - proc_flags, NULL, NULL, &si, &pi) ) + if (cmdline_dup + && CreateProcessW(argv0, cmdline_dup, NULL, NULL, FALSE, proc_flag= s, NULL, NULL, &si, &pi)) { WaitForSingleObject(pi.hProcess, timeout ? timeout : INFINITE); if (!GetExitCodeProcess(pi.hProcess, &exit_code)) @@ -905,13 +894,12 @@ /* kill without impunity */ TerminateProcess(pi.hProcess, exit_code); - MsgToEventLog(M_ERR, L"ExecCommand: \"%ls %ls\" killed after t= imeout", - argv0, cmdline); + MsgToEventLog(M_ERR, L"ExecCommand: \"%ls %ls\" killed after t= imeout", argv0, cmdline); } else if (exit_code) { - MsgToEventLog(M_ERR, L"ExecCommand: \"%ls %ls\" exited with st= atus =3D %lu", - argv0, cmdline, exit_code); + MsgToEventLog(M_ERR, L"ExecCommand: \"%ls %ls\" exited with st= atus =3D %lu", argv0, + cmdline, exit_code); } else { @@ -924,8 +912,7 @@ else { exit_code =3D GetLastError(); - MsgToEventLog(M_SYSERR, L"ExecCommand: could not run \"%ls %ls\" := ", - argv0, cmdline); + MsgToEventLog(M_SYSERR, L"ExecCommand: could not run \"%ls %ls\" := ", argv0, cmdline); } free(cmdline_dup); @@ -950,12 +937,12 @@ WCHAR *argv0; WCHAR *cmdline; DWORD timeout; - } cmds [] =3D { - { ipcfg, L"ipconfig /flushdns", timeout }, + } cmds[] =3D { + { ipcfg, L"ipconfig /flushdns", timeout }, { ipcfg, L"ipconfig /registerdns", timeout }, }; - HANDLE wait_handles[2] =3D {rdns_semaphore, exit_event}; + HANDLE wait_handles[2] =3D { rdns_semaphore, exit_event }; swprintf(ipcfg, MAX_PATH, L"%ls\\%ls", get_win_sys_path(), L"ipconfig.= exe"); @@ -967,9 +954,10 @@ ExecCommand(cmds[i].argv0, cmds[i].cmdline, cmds[i].timeout); } err =3D 0; - if (!ReleaseSemaphore(rdns_semaphore, 1, NULL) ) + if (!ReleaseSemaphore(rdns_semaphore, 1, NULL)) { - err =3D MsgToEventLog(M_SYSERR, L"RegisterDNS: Failed to relea= se regsiter-dns semaphore:"); + err =3D + MsgToEventLog(M_SYSERR, L"RegisterDNS: Failed to release r= egsiter-dns semaphore:"); } } else @@ -1046,7 +1034,7 @@ /* max cmdline length in wchars -- include room for worst case and som= e */ size_t ncmdline =3D wcslen(fmt) + wcslen(if_name) + wcslen(action) + w= cslen(addr) - +wcslen(addr_static) + 32 + 1; + + wcslen(addr_static) + 32 + 1; cmdline =3D malloc(ncmdline * sizeof(wchar_t)); if (!cmdline) { @@ -1078,13 +1066,8 @@ static BOOL ApplyGpolSettings32(void) { - typedef NTSTATUS (__stdcall *publish_fn_t)( - DWORD StateNameLo, - DWORD StateNameHi, - DWORD TypeId, - DWORD Buffer, - DWORD Length, - DWORD ExplicitScope); + typedef NTSTATUS(__stdcall * publish_fn_t)(DWORD StateNameLo, DWORD St= ateNameHi, DWORD TypeId, + DWORD Buffer, DWORD Length,= DWORD ExplicitScope); publish_fn_t RtlPublishWnfStateData; const DWORD WNF_GPOL_SYSTEM_CHANGES_HI =3D 0x0D891E2A; const DWORD WNF_GPOL_SYSTEM_CHANGES_LO =3D 0xA3BC0875; @@ -1095,13 +1078,14 @@ return FALSE; } - RtlPublishWnfStateData =3D (publish_fn_t) GetProcAddress(ntdll, "RtlPu= blishWnfStateData"); + RtlPublishWnfStateData =3D (publish_fn_t)GetProcAddress(ntdll, "RtlPub= lishWnfStateData"); if (RtlPublishWnfStateData =3D=3D NULL) { return FALSE; } - if (RtlPublishWnfStateData(WNF_GPOL_SYSTEM_CHANGES_LO, WNF_GPOL_SYSTEM= _CHANGES_HI, 0, 0, 0, 0) !=3D ERROR_SUCCESS) + if (RtlPublishWnfStateData(WNF_GPOL_SYSTEM_CHANGES_LO, WNF_GPOL_SYSTEM= _CHANGES_HI, 0, 0, 0, 0) + !=3D ERROR_SUCCESS) { return FALSE; } @@ -1118,12 +1102,8 @@ static BOOL ApplyGpolSettings64(void) { - typedef NTSTATUS (*publish_fn_t)( - INT64 StateName, - INT64 TypeId, - INT64 Buffer, - unsigned int Length, - INT64 ExplicitScope); + typedef NTSTATUS (*publish_fn_t)(INT64 StateName, INT64 TypeId, INT64 = Buffer, + unsigned int Length, INT64 ExplicitSc= ope); publish_fn_t RtlPublishWnfStateData; const INT64 WNF_GPOL_SYSTEM_CHANGES =3D 0x0D891E2AA3BC0875; @@ -1133,7 +1113,7 @@ return FALSE; } - RtlPublishWnfStateData =3D (publish_fn_t) GetProcAddress(ntdll, "RtlPu= blishWnfStateData"); + RtlPublishWnfStateData =3D (publish_fn_t)GetProcAddress(ntdll, "RtlPub= lishWnfStateData"); if (RtlPublishWnfStateData =3D=3D NULL) { return FALSE; @@ -1183,24 +1163,21 @@ scm =3D OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS); if (scm =3D=3D NULL) { - MsgToEventLog(M_ERR, L"%S: OpenSCManager call failed (%lu)", - __func__, GetLastError()); + MsgToEventLog(M_ERR, L"%S: OpenSCManager call failed (%lu)", __fun= c__, GetLastError()); goto out; } dnssvc =3D OpenServiceA(scm, "Dnscache", SERVICE_PAUSE_CONTINUE); if (dnssvc =3D=3D NULL) { - MsgToEventLog(M_ERR, L"%S: OpenService call failed (%lu)", - __func__, GetLastError()); + MsgToEventLog(M_ERR, L"%S: OpenService call failed (%lu)", __func_= _, GetLastError()); goto out; } SERVICE_STATUS status; if (ControlService(dnssvc, SERVICE_CONTROL_PARAMCHANGE, &status) =3D= =3D 0) { - MsgToEventLog(M_ERR, L"%S: ControlService call failed (%lu)", - __func__, GetLastError()); + MsgToEventLog(M_ERR, L"%S: ControlService call failed (%lu)", __fu= nc__, GetLastError()); goto out; } @@ -1328,8 +1305,7 @@ *gpol =3D FALSE; /* Try the group policy search list */ - err =3D RegOpenKeyExA(HKEY_LOCAL_MACHINE, - "SOFTWARE\\Policies\\Microsoft\\Windows NT\\DNSCli= ent", + err =3D RegOpenKeyExA(HKEY_LOCAL_MACHINE, "SOFTWARE\\Policies\\Microso= ft\\Windows NT\\DNSClient", 0, KEY_ALL_ACCESS, key); if (!err) { @@ -1342,9 +1318,9 @@ } /* Try the system-wide search list */ - err =3D RegOpenKeyExA(HKEY_LOCAL_MACHINE, - "System\\CurrentControlSet\\Services\\TCPIP\\Param= eters", - 0, KEY_ALL_ACCESS, key); + err =3D + RegOpenKeyExA(HKEY_LOCAL_MACHINE, "System\\CurrentControlSet\\Serv= ices\\TCPIP\\Parameters", + 0, KEY_ALL_ACCESS, key); if (!err) { if (HasValidSearchList(*key)) @@ -1362,9 +1338,10 @@ if (!iid_err) { HKEY itfs; - err =3D RegOpenKeyExA(HKEY_LOCAL_MACHINE, - "System\\CurrentControlSet\\Services\\TCPI= P\\Parameters\\Interfaces", - 0, KEY_ALL_ACCESS, &itfs); + err =3D + RegOpenKeyExA(HKEY_LOCAL_MACHINE, + "System\\CurrentControlSet\\Services\\TCPIP\= \Parameters\\Interfaces", + 0, KEY_ALL_ACCESS, &itfs); if (!err) { err =3D RegOpenKeyExW(itfs, iid, 0, KEY_ALL_ACCESS, key); @@ -1400,8 +1377,7 @@ { return FALSE; } - MsgToEventLog(M_ERR, L"%S: failed to get InitialSearchList (%lu)", - __func__, err); + MsgToEventLog(M_ERR, L"%S: failed to get InitialSearchList (%lu)",= __func__, err); } return TRUE; @@ -1436,8 +1412,7 @@ LSTATUS err =3D RegSetValueExW(key, L"InitialSearchList", 0, REG_SZ, (= PBYTE)list, size); if (err) { - MsgToEventLog(M_ERR, L"%S: failed to set InitialSearchList value (= %lu)", - __func__, err); + MsgToEventLog(M_ERR, L"%S: failed to set InitialSearchList value (= %lu)", __func__, err); return FALSE; } @@ -1457,7 +1432,7 @@ AddDnsSearchDomains(HKEY key, BOOL have_list, PCWSTR domains) { LSTATUS err; - WCHAR list[2048] =3D {0}; + WCHAR list[2048] =3D { 0 }; DWORD size =3D sizeof(list); if (have_list) @@ -1465,8 +1440,8 @@ err =3D RegGetValueW(key, NULL, L"SearchList", RRF_RT_REG_SZ, NULL= , list, &size); if (err) { - MsgToEventLog(M_SYSERR, L"%S: could not get SearchList from re= gistry (%lu)", - __func__, err); + MsgToEventLog(M_SYSERR, L"%S: could not get SearchList from re= gistry (%lu)", __func__, + err); return FALSE; } @@ -1498,8 +1473,7 @@ err =3D RegSetValueExW(key, L"SearchList", 0, REG_SZ, (PBYTE)list, siz= e); if (err) { - MsgToEventLog(M_SYSERR, L"%S: could not set SearchList to registry= (%lu)", - __func__, err); + MsgToEventLog(M_SYSERR, L"%S: could not set SearchList to registry= (%lu)", __func__, err); return FALSE; } @@ -1540,8 +1514,7 @@ err =3D RegSetValueExW(key, L"SearchList", 0, REG_SZ, (PBYTE)list, siz= e); if (err) { - MsgToEventLog(M_SYSERR, L"%S: could not set SearchList in registry= (%lu)", - __func__, err); + MsgToEventLog(M_SYSERR, L"%S: could not set SearchList in registry= (%lu)", __func__, err); goto out; } @@ -1568,8 +1541,7 @@ err =3D RegGetValueW(key, NULL, L"SearchList", RRF_RT_REG_SZ, NULL, li= st, &size); if (err) { - MsgToEventLog(M_SYSERR, L"%S: could not get SearchList from regist= ry (%lu)", - __func__, err); + MsgToEventLog(M_SYSERR, L"%S: could not get SearchList from regist= ry (%lu)", __func__, err); return; } @@ -1613,8 +1585,7 @@ err =3D RegSetValueExW(key, L"SearchList", 0, REG_SZ, (PBYTE)list, siz= e); if (err) { - MsgToEventLog(M_SYSERR, L"%S: could not set SearchList in registry= (%lu)", - __func__, err); + MsgToEventLog(M_SYSERR, L"%S: could not set SearchList in registry= (%lu)", __func__, err); } } @@ -1732,8 +1703,8 @@ GetInterfacesKey(short family, PHKEY key) { PCSTR itfs_key =3D family =3D=3D AF_INET6 - ? "SYSTEM\\CurrentControlSet\\Services\\Tcpip6\\Parameters\\Interf= aces" - : "SYSTEM\\CurrentControlSet\\Services\\Tcpip\\Parameters\\Interfa= ces"; + ? "SYSTEM\\CurrentControlSet\\Services\\Tcpip6\\P= arameters\\Interfaces" + : "SYSTEM\\CurrentControlSet\\Services\\Tcpip\\Pa= rameters\\Interfaces"; LSTATUS err =3D RegOpenKeyExA(HKEY_LOCAL_MACHINE, itfs_key, 0, KEY_ALL= _ACCESS, key); if (err) @@ -1842,11 +1813,12 @@ return ERROR_MESSAGE_DATA; } - /* use a non-const reference with limited scope to enforce null-termin= ation of strings from client */ + /* use a non-const reference with limited scope to enforce null-termin= ation of strings from + * client */ { - dns_cfg_message_t *msgptr =3D (dns_cfg_message_t *) msg; - msgptr->iface.name[_countof(msg->iface.name)-1] =3D '\0'; - msgptr->domains[_countof(msg->domains)-1] =3D '\0'; + dns_cfg_message_t *msgptr =3D (dns_cfg_message_t *)msg; + msgptr->iface.name[_countof(msg->iface.name) - 1] =3D '\0'; + msgptr->domains[_countof(msg->domains) - 1] =3D '\0'; } WCHAR iid[64]; @@ -1878,7 +1850,7 @@ err =3D SetDnsSearchDomains(msg->iface.name, NULL, &gpol, list= s); } ApplyDnsSettings(gpol); - return err; /* job done */ + return err; /* job done */ } if (msg->addr_len > 0) @@ -2100,8 +2072,7 @@ s--; } - if (inet_ntop(AF_INET6, &in_addrs[i], - pos, s) !=3D NULL) + if (inet_ntop(AF_INET6, &in_addrs[i], pos, s) !=3D NULL) { *size =3D 0; return ERROR_MORE_DATA; @@ -2188,7 +2159,7 @@ LSTATUS err =3D ERROR_FILE_NOT_FOUND; const DWORD buf_size =3D *size; const size_t one_glyph =3D sizeof(*domains); - PWSTR values[] =3D { L"SearchList", L"Domain", L"DhcpDomainSearchList"= , L"DhcpDomain", NULL}; + PWSTR values[] =3D { L"SearchList", L"Domain", L"DhcpDomainSearchList"= , L"DhcpDomain", NULL }; for (int i =3D 0; values[i]; i++) { @@ -2284,7 +2255,8 @@ /* Get GUID from string */ if (IIDFromString(iid_str, &iid) !=3D S_OK) { - MsgToEventLog(M_SYSERR, L"%S: could not convert interface %s GUID = string", __func__, iid_str); + MsgToEventLog(M_SYSERR, L"%S: could not convert interface %s GUID = string", __func__, + iid_str); goto out; } @@ -2326,8 +2298,7 @@ HKEY v4_itfs =3D INVALID_HANDLE_VALUE; HKEY v6_itfs =3D INVALID_HANDLE_VALUE; - if (!GetInterfacesKey(AF_INET, &v4_itfs) - || !GetInterfacesKey(AF_INET6, &v6_itfs)) + if (!GetInterfacesKey(AF_INET, &v4_itfs) || !GetInterfacesKey(AF_INET6= , &v6_itfs)) { goto out; } @@ -2338,8 +2309,8 @@ { WCHAR itf_guid[MAX_PATH]; DWORD itf_guid_len =3D _countof(itf_guid); - LSTATUS err =3D RegEnumKeyExW(v4_itfs, enum_index++, itf_guid, &it= f_guid_len, - NULL, NULL, NULL, NULL); + LSTATUS err =3D + RegEnumKeyExW(v4_itfs, enum_index++, itf_guid, &itf_guid_len, = NULL, NULL, NULL, NULL); if (err) { if (err !=3D ERROR_NO_MORE_ITEMS) @@ -2358,7 +2329,8 @@ HKEY v4_itf; if (RegOpenKeyExW(v4_itfs, itf_guid, 0, KEY_READ, &v4_itf) !=3D NO= _ERROR) { - MsgToEventLog(M_SYSERR, L"%S: could not open interface %s v4 r= egistry key", __func__, itf_guid); + MsgToEventLog(M_SYSERR, L"%S: could not open interface %s v4 r= egistry key", __func__, + itf_guid); goto out; } @@ -2370,7 +2342,8 @@ { if (err !=3D ERROR_FILE_NOT_FOUND) { - MsgToEventLog(M_SYSERR, L"%S: could not read interface %s = domain suffix", __func__, itf_guid); + MsgToEventLog(M_SYSERR, L"%S: could not read interface %s = domain suffix", __func__, + itf_guid); } goto next_itf; } @@ -2393,7 +2366,8 @@ HKEY v6_itf; if (RegOpenKeyExW(v6_itfs, itf_guid, 0, KEY_READ, &v6_itf) != =3D NO_ERROR) { - MsgToEventLog(M_SYSERR, L"%S: could not open interface %s = v6 registry key", __func__, itf_guid); + MsgToEventLog(M_SYSERR, L"%S: could not open interface %s = v6 registry key", + __func__, itf_guid); goto next_itf; } err =3D GetItfDnsServersV6(v6_itf, v6_addrs, &v6_addrs_size); @@ -2441,8 +2415,8 @@ * @return NO_ERROR on success, or Windows error code */ static DWORD -SetNrptRule(HKEY nrpt_key, PCWSTR subkey, PCSTR address, - PCWSTR domains, DWORD dom_size, BOOL dnssec) +SetNrptRule(HKEY nrpt_key, PCWSTR subkey, PCSTR address, PCWSTR domains, D= WORD dom_size, + BOOL dnssec) { /* Create rule subkey */ DWORD err =3D NO_ERROR; @@ -2461,7 +2435,8 @@ } /* Set DNS Server address */ - err =3D RegSetValueExA(rule_key, "GenericDNSServers", 0, REG_SZ, (PBYT= E)address, strlen(address) + 1); + err =3D RegSetValueExA(rule_key, "GenericDNSServers", 0, REG_SZ, (PBYT= E)address, + strlen(address) + 1); if (err) { goto out; @@ -2472,21 +2447,24 @@ if (dnssec) { reg_val =3D 1; - err =3D RegSetValueExA(rule_key, "DNSSECValidationRequired", 0, RE= G_DWORD, (PBYTE)®_val, sizeof(reg_val)); + err =3D RegSetValueExA(rule_key, "DNSSECValidationRequired", 0, RE= G_DWORD, (PBYTE)®_val, + sizeof(reg_val)); if (err) { goto out; } reg_val =3D 0; - err =3D RegSetValueExA(rule_key, "DNSSECQueryIPSECRequired", 0, RE= G_DWORD, (PBYTE)®_val, sizeof(reg_val)); + err =3D RegSetValueExA(rule_key, "DNSSECQueryIPSECRequired", 0, RE= G_DWORD, (PBYTE)®_val, + sizeof(reg_val)); if (err) { goto out; } reg_val =3D 0; - err =3D RegSetValueExA(rule_key, "DNSSECQueryIPSECEncryption", 0, = REG_DWORD, (PBYTE)®_val, sizeof(reg_val)); + err =3D RegSetValueExA(rule_key, "DNSSECQueryIPSECEncryption", 0, = REG_DWORD, (PBYTE)®_val, + sizeof(reg_val)); if (err) { goto out; @@ -2495,7 +2473,8 @@ /* Set NRPT config options */ reg_val =3D dnssec ? 0x0000000A : 0x00000008; - err =3D RegSetValueExA(rule_key, "ConfigOptions", 0, REG_DWORD, (const= PBYTE)®_val, sizeof(reg_val)); + err =3D RegSetValueExA(rule_key, "ConfigOptions", 0, REG_DWORD, (const= PBYTE)®_val, + sizeof(reg_val)); if (err) { goto out; @@ -2653,7 +2632,8 @@ * remains in the registry even if the last GP-NRPT rule is deleted. */ static PCSTR gpol_key =3D "SOFTWARE\\Policies\\Microsoft\\Windows NT\\= DNSClient\\DnsPolicyConfig"; - static PCSTR sys_key =3D "SYSTEM\\CurrentControlSet\\Services\\Dnscach= e\\Parameters\\DnsPolicyConfig"; + static PCSTR sys_key =3D + "SYSTEM\\CurrentControlSet\\Services\\Dnscache\\Parameters\\DnsPol= icyConfig"; HKEY nrpt; *gpol =3D TRUE; @@ -2661,7 +2641,8 @@ if (err =3D=3D ERROR_FILE_NOT_FOUND) { *gpol =3D FALSE; - err =3D RegCreateKeyExA(HKEY_LOCAL_MACHINE, sys_key, 0, NULL, 0, K= EY_ALL_ACCESS, NULL, &nrpt, NULL); + err =3D RegCreateKeyExA(HKEY_LOCAL_MACHINE, sys_key, 0, NULL, 0, K= EY_ALL_ACCESS, NULL, &nrpt, + NULL); if (err) { nrpt =3D INVALID_HANDLE_VALUE; @@ -2763,15 +2744,14 @@ * @return NO_ERROR on success, or a Windows error code */ static DWORD -HandleDNSConfigNrptMessage(const nrpt_dns_cfg_message_t *msg, - DWORD ovpn_pid, undo_lists_t *lists) +HandleDNSConfigNrptMessage(const nrpt_dns_cfg_message_t *msg, DWORD ovpn_p= id, undo_lists_t *lists) { /* * Use a non-const reference with limited scope to * enforce null-termination of strings from client */ { - nrpt_dns_cfg_message_t *msgptr =3D (nrpt_dns_cfg_message_t *) msg; + nrpt_dns_cfg_message_t *msgptr =3D (nrpt_dns_cfg_message_t *)msg; msgptr->iface.name[_countof(msg->iface.name) - 1] =3D '\0'; msgptr->search_domains[_countof(msg->search_domains) - 1] =3D '\0'; msgptr->resolve_domains[_countof(msg->resolve_domains) - 1] =3D '\= 0'; @@ -2864,7 +2844,8 @@ /* Set NRPT rules */ BOOL dnssec =3D (msg->flags & nrpt_dnssec) !=3D 0; - err =3D SetNrptRules(key, msg->addresses, msg->resolve_domains, msg->s= earch_domains, dnssec, ovpn_pid); + err =3D SetNrptRules(key, msg->addresses, msg->resolve_domains, msg->s= earch_domains, dnssec, + ovpn_pid); if (err) { goto out; @@ -2907,7 +2888,8 @@ return ERROR_MESSAGE_DATA; } - /* use a non-const reference with limited scope to enforce null-termin= ation of strings from client */ + /* use a non-const reference with limited scope to enforce null-termin= ation of strings from + * client */ { wins_cfg_message_t *msgptr =3D (wins_cfg_message_t *)msg; msgptr->iface.name[_countof(msg->iface.name) - 1] =3D '\0'; @@ -2934,7 +2916,7 @@ if (msg->header.type =3D=3D msg_del_wins_cfg) { - goto out; /* job done */ + goto out; /* job done */ } for (int i =3D 0; i < addr_len; ++i) @@ -2988,7 +2970,7 @@ * 10 chars for 32 bit int in decimal and +1 for NUL */ size_t ncmdline =3D wcslen(fmt) + 10 + 1; - wchar_t *cmdline =3D malloc(ncmdline*sizeof(wchar_t)); + wchar_t *cmdline =3D malloc(ncmdline * sizeof(wchar_t)); if (!cmdline) { err =3D ERROR_OUTOFMEMORY; @@ -3073,16 +3055,12 @@ } static VOID -HandleMessage(HANDLE pipe, PPROCESS_INFORMATION proc_info, - DWORD bytes, DWORD count, LPHANDLE events, undo_lists_t *lis= ts) +HandleMessage(HANDLE pipe, PPROCESS_INFORMATION proc_info, DWORD bytes, DW= ORD count, + LPHANDLE events, undo_lists_t *lists) { pipe_message_t msg; ack_message_t ack =3D { - .header =3D { - .type =3D msg_acknowledgement, - .size =3D sizeof(ack), - .message_id =3D -1 - }, + .header =3D { .type =3D msg_acknowledgement, .size =3D sizeof(ack)= , .message_id =3D -1 }, .error_number =3D ERROR_MESSAGE_DATA }; @@ -3264,27 +3242,24 @@ STARTUPINFOW startup_info; PROCESS_INFORMATION proc_info; LPVOID user_env =3D NULL; - WCHAR ovpn_pipe_name[256]; /* The entire pipe name string can be up to= 256 characters long according to MSDN. */ + WCHAR ovpn_pipe_name[256]; /* The entire pipe name string can be up to= 256 characters long + according to MSDN. */ LPCWSTR exe_path; WCHAR *cmdline =3D NULL; size_t cmdline_size; undo_lists_t undo_lists; WCHAR errmsg[512] =3D L""; - SECURITY_ATTRIBUTES inheritable =3D { - .nLength =3D sizeof(inheritable), - .lpSecurityDescriptor =3D NULL, - .bInheritHandle =3D TRUE - }; + SECURITY_ATTRIBUTES inheritable =3D { .nLength =3D sizeof(inheritable), + .lpSecurityDescriptor =3D NULL, + .bInheritHandle =3D TRUE }; PACL ovpn_dacl; EXPLICIT_ACCESS ea[2]; SECURITY_DESCRIPTOR ovpn_sd; - SECURITY_ATTRIBUTES ovpn_sa =3D { - .nLength =3D sizeof(ovpn_sa), - .lpSecurityDescriptor =3D &ovpn_sd, - .bInheritHandle =3D FALSE - }; + SECURITY_ATTRIBUTES ovpn_sa =3D { .nLength =3D sizeof(ovpn_sa), + .lpSecurityDescriptor =3D &ovpn_sd, + .bInheritHandle =3D FALSE }; ZeroMemory(&ea, sizeof(ea)); ZeroMemory(&startup_info, sizeof(startup_info)); @@ -3370,7 +3345,8 @@ * OR user is authorized to run any config. */ if (!ValidateOptions(pipe, sud.directory, sud.options, errmsg, _counto= f(errmsg)) - && !IsAuthorizedUser(ovpn_user->User.Sid, imp_token, settings.ovpn= _admin_group, settings.ovpn_service_user)) + && !IsAuthorizedUser(ovpn_user->User.Sid, imp_token, settings.ovpn= _admin_group, + settings.ovpn_service_user)) { ReturnError(pipe, ERROR_STARTUP_DATA, errmsg, 1, &exit_event); goto out; @@ -3382,14 +3358,14 @@ ea[0].grfInheritance =3D NO_INHERITANCE; ea[0].Trustee.TrusteeForm =3D TRUSTEE_IS_SID; ea[0].Trustee.TrusteeType =3D TRUSTEE_IS_UNKNOWN; - ea[0].Trustee.ptstrName =3D (LPWSTR) svc_user->User.Sid; - ea[1].grfAccessPermissions =3D READ_CONTROL | SYNCHRONIZE | PROCESS_VM= _READ - |SYNCHRONIZE | PROCESS_TERMINATE | PROCES= S_QUERY_INFORMATION; + ea[0].Trustee.ptstrName =3D (LPWSTR)svc_user->User.Sid; + ea[1].grfAccessPermissions =3D READ_CONTROL | SYNCHRONIZE | PROCESS_VM= _READ | SYNCHRONIZE + | PROCESS_TERMINATE | PROCESS_QUERY_INFOR= MATION; ea[1].grfAccessMode =3D SET_ACCESS; ea[1].grfInheritance =3D NO_INHERITANCE; ea[1].Trustee.TrusteeForm =3D TRUSTEE_IS_SID; ea[1].Trustee.TrusteeType =3D TRUSTEE_IS_UNKNOWN; - ea[1].Trustee.ptstrName =3D (LPWSTR) ovpn_user->User.Sid; + ea[1].Trustee.ptstrName =3D (LPWSTR)ovpn_user->User.Sid; /* Set owner and DACL of OpenVPN security descriptor */ if (!SetSecurityDescriptorOwner(&ovpn_sd, svc_user->User.Sid, FALSE)) @@ -3416,8 +3392,8 @@ } /* use /dev/null for stdout of openvpn (client should use --log for ou= tput) */ - stdout_write =3D CreateFile(_L("NUL"), GENERIC_WRITE, FILE_SHARE_WRITE, - &inheritable, OPEN_EXISTING, 0, NULL); + stdout_write =3D CreateFile(_L("NUL"), GENERIC_WRITE, FILE_SHARE_WRITE= , &inheritable, + OPEN_EXISTING, 0, NULL); if (stdout_write =3D=3D INVALID_HANDLE_VALUE) { ReturnLastError(pipe, L"CreateFile for stdout"); @@ -3432,18 +3408,19 @@ } swprintf(ovpn_pipe_name, _countof(ovpn_pipe_name), - L"\\\\.\\pipe\\" _L(PACKAGE) L"%ls\\service_%lu", service_ins= tance, GetCurrentThreadId()); - ovpn_pipe =3D CreateNamedPipe(ovpn_pipe_name, - PIPE_ACCESS_DUPLEX | FILE_FLAG_FIRST_PIPE_= INSTANCE | FILE_FLAG_OVERLAPPED, - PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE = | PIPE_WAIT, 1, 128, 128, 0, NULL); + L"\\\\.\\pipe\\" _L(PACKAGE) L"%ls\\service_%lu", service_ins= tance, + GetCurrentThreadId()); + ovpn_pipe =3D CreateNamedPipe( + ovpn_pipe_name, PIPE_ACCESS_DUPLEX | FILE_FLAG_FIRST_PIPE_INSTANCE= | FILE_FLAG_OVERLAPPED, + PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT, 1, 128, 128= , 0, NULL); if (ovpn_pipe =3D=3D INVALID_HANDLE_VALUE) { ReturnLastError(pipe, L"CreateNamedPipe"); goto out; } - svc_pipe =3D CreateFile(ovpn_pipe_name, GENERIC_READ | GENERIC_WRITE, = 0, - &inheritable, OPEN_EXISTING, 0, NULL); + svc_pipe =3D CreateFile(ovpn_pipe_name, GENERIC_READ | GENERIC_WRITE, = 0, &inheritable, + OPEN_EXISTING, 0, NULL); if (svc_pipe =3D=3D INVALID_HANDLE_VALUE) { ReturnLastError(pipe, L"CreateFile"); @@ -3467,8 +3444,8 @@ /* there seem to be no common printf specifier that works on all * mingw/msvc platforms without trickery, so convert to void* and use * PRIuPTR to print that as best compromise */ - swprintf(cmdline, cmdline_size, L"openvpn %ls --msg-channel %" PRIuPTR, - sud.options, (uintptr_t)svc_pipe); + swprintf(cmdline, cmdline_size, L"openvpn %ls --msg-channel %" PRIuPTR= , sud.options, + (uintptr_t)svc_pipe); if (!CreateEnvironmentBlock(&user_env, imp_token, FALSE)) { @@ -3527,7 +3504,10 @@ if (bytes > sizeof(pipe_message_t)) { /* process at the other side of the pipe is misbehaving, shut = it down */ - MsgToEventLog(MSG_FLAGS_ERROR, L"OpenVPN process sent too larg= e payload length to the pipe (%lu bytes), it will be terminated", bytes); + MsgToEventLog( + MSG_FLAGS_ERROR, + L"OpenVPN process sent too large payload length to the pip= e (%lu bytes), it will be terminated", + bytes); break; } @@ -3543,8 +3523,7 @@ else if (exit_code !=3D 0) { WCHAR buf[256]; - swprintf(buf, _countof(buf), - L"OpenVPN exited with error: exit code =3D %lu", exit_cod= e); + swprintf(buf, _countof(buf), L"OpenVPN exited with error: exit cod= e =3D %lu", exit_code); ReturnError(pipe, ERROR_OPENVPN_STARTUP, buf, 1, &exit_event); } Undo(&undo_lists); @@ -3607,17 +3586,19 @@ * allow read/write for authenticated users * deny all access to anonymous */ - const WCHAR *sddlString =3D L"D:(A;OICI;GA;;;S-1-5-18)(D;OICI;0x4;;;S-= 1-1-0)(A;OICI;GRGW;;;S-1-5-11)(D;;GA;;;S-1-5-7)"; + const WCHAR *sddlString =3D + L"D:(A;OICI;GA;;;S-1-5-18)(D;OICI;0x4;;;S-1-1-0)(A;OICI;GRGW;;;S-1= -5-11)(D;;GA;;;S-1-5-7)"; PSECURITY_DESCRIPTOR sd =3D NULL; - if (!ConvertStringSecurityDescriptorToSecurityDescriptor(sddlString, S= DDL_REVISION_1, &sd, NULL)) + if (!ConvertStringSecurityDescriptorToSecurityDescriptor(sddlString, S= DDL_REVISION_1, &sd, + NULL)) { MsgToEventLog(M_SYSERR, L"ConvertStringSecurityDescriptorToSecurit= yDescriptor failed."); return INVALID_HANDLE_VALUE; } /* Set up SECURITY_ATTRIBUTES */ - SECURITY_ATTRIBUTES sa =3D {0}; + SECURITY_ATTRIBUTES sa =3D { 0 }; sa.nLength =3D sizeof(SECURITY_ATTRIBUTES); sa.lpSecurityDescriptor =3D sd; sa.bInheritHandle =3D FALSE; @@ -3631,11 +3612,13 @@ first =3D FALSE; } - WCHAR pipe_name[256]; /* The entire pipe name string can be up to 256 = characters long according to MSDN. */ - swprintf(pipe_name, _countof(pipe_name), L"\\\\.\\pipe\\" _L(PACKAGE) = L"%ls\\service", service_instance); - HANDLE pipe =3D CreateNamedPipe(pipe_name, flags, - PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAG= E | PIPE_REJECT_REMOTE_CLIENTS, - PIPE_UNLIMITED_INSTANCES, 1024, 1024, 0,= &sa); + WCHAR pipe_name[256]; /* The entire pipe name string can be up to 256 = characters long according + to MSDN. */ + swprintf(pipe_name, _countof(pipe_name), L"\\\\.\\pipe\\" _L(PACKAGE) = L"%ls\\service", + service_instance); + HANDLE pipe =3D CreateNamedPipe( + pipe_name, flags, PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE= _REJECT_REMOTE_CLIENTS, + PIPE_UNLIMITED_INSTANCES, 1024, 1024, 0, &sa); LocalFree(sd); @@ -3650,8 +3633,8 @@ static DWORD -UpdateWaitHandles(LPHANDLE *handles_ptr, LPDWORD count, - HANDLE io_event, HANDLE exit_event, list_item_t *threads) +UpdateWaitHandles(LPHANDLE *handles_ptr, LPDWORD count, HANDLE io_event, H= ANDLE exit_event, + list_item_t *threads) { static DWORD size =3D 10; static LPHANDLE handles =3D NULL; @@ -3762,7 +3745,8 @@ PHANDLE handles =3D NULL; DWORD handle_count; - service =3D RegisterServiceCtrlHandlerEx(interactive_service.name, Ser= viceCtrlInteractive, &status); + service =3D + RegisterServiceCtrlHandlerEx(interactive_service.name, ServiceCtrl= Interactive, &status); if (!service) { return; @@ -3817,8 +3801,7 @@ while (TRUE) { - if (ConnectNamedPipe(pipe, &overlapped) =3D=3D FALSE - && GetLastError() !=3D ERROR_PIPE_CONNECTED + if (ConnectNamedPipe(pipe, &overlapped) =3D=3D FALSE && GetLastErr= or() !=3D ERROR_PIPE_CONNECTED && GetLastError() !=3D ERROR_IO_PENDING) { MsgToEventLog(M_SYSERR, L"Could not connect pipe"); @@ -3836,11 +3819,13 @@ error =3D AddListItem(&threads, thread); if (!error) { - error =3D UpdateWaitHandles(&handles, &handle_count, i= o_event, exit_event, threads); + error =3D + UpdateWaitHandles(&handles, &handle_count, io_even= t, exit_event, threads); } if (error) { - ReturnError(pipe, error, L"Insufficient resources to s= ervice new clients", 1, &exit_event); + ReturnError(pipe, error, L"Insufficient resources to s= ervice new clients", 1, + &exit_event); /* Update wait handles again after removing the last w= orker thread */ RemoveListItem(&threads, CmpHandle, thread); UpdateWaitHandles(&handles, &handle_count, io_event, e= xit_event, threads); diff --git a/src/openvpnserv/service.c b/src/openvpnserv/service.c index a76dce7..04b20d7 100644 --- a/src/openvpnserv/service.c +++ b/src/openvpnserv/service.c @@ -33,8 +33,7 @@ status->dwControlsAccepted =3D SERVICE_ACCEPT_STOP; } - if (status->dwCurrentState =3D=3D SERVICE_RUNNING - || status->dwCurrentState =3D=3D SERVICE_STOPPED) + if (status->dwCurrentState =3D=3D SERVICE_RUNNING || status->dwCurrent= State =3D=3D SERVICE_STOPPED) { status->dwCheckPoint =3D 0; } @@ -79,16 +78,10 @@ for (i =3D 0; i < _service_max; i++) { - service =3D CreateService(svc_ctl_mgr, - openvpn_service[i].name, - openvpn_service[i].display_name, - SERVICE_QUERY_STATUS, - SERVICE_WIN32_SHARE_PROCESS, - openvpn_service[i].start_type, - SERVICE_ERROR_NORMAL, - path, NULL, NULL, - openvpn_service[i].dependencies, - NULL, NULL); + service =3D CreateService( + svc_ctl_mgr, openvpn_service[i].name, openvpn_service[i].displ= ay_name, + SERVICE_QUERY_STATUS, SERVICE_WIN32_SHARE_PROCESS, openvpn_ser= vice[i].start_type, + SERVICE_ERROR_NORMAL, path, NULL, NULL, openvpn_service[i].dep= endencies, NULL, NULL); if (service) { wprintf(L"%ls installed.\n", openvpn_service[i].display_name); @@ -163,8 +156,8 @@ for (i =3D 0; i < _service_max; i++) { openvpn_service_t *ovpn_svc =3D &openvpn_service[i]; - service =3D OpenService(svc_ctl_mgr, ovpn_svc->name, - DELETE | SERVICE_STOP | SERVICE_QUERY_STATUS= ); + service =3D + OpenService(svc_ctl_mgr, ovpn_svc->name, DELETE | SERVICE_STOP= | SERVICE_QUERY_STATUS); if (service =3D=3D NULL) { wprintf(L"OpenService failed - %ls\n", GetLastErrorText()); @@ -228,15 +221,12 @@ * This is the default. */ const SERVICE_TABLE_ENTRY dispatchTable_shared[] =3D { - { interactive_service.name, ServiceStartInteractive }, - { NULL, NULL } + { interactive_service.name, ServiceStartInteractive }, { NULL, NUL= L } }; =20 /* Interactive service only (as a SERVICE_WIN32_OWN_PROCESS) */ - const SERVICE_TABLE_ENTRY dispatchTable_interactive[] =3D { - { L"", ServiceStartInteractiveOwn }, - { NULL, NULL } - }; + const SERVICE_TABLE_ENTRY dispatchTable_interactive[] =3D { { L"", Ser= viceStartInteractiveOwn }, + { NULL, NULL= } }; const SERVICE_TABLE_ENTRY *dispatchTable =3D dispatchTable_shared; @@ -260,7 +250,7 @@ } else if (argc > i + 2 && _wcsicmp(L"instance", argv[i] + 1) = =3D=3D 0) { - if (_wcsicmp(L"interactive", argv[i+1]) =3D=3D 0) + if (_wcsicmp(L"interactive", argv[i + 1]) =3D=3D 0) { dispatchTable =3D dispatchTable_interactive; service_instance =3D argv[i + 2]; @@ -268,22 +258,28 @@ } else { - MsgToEventLog(M_ERR, L"Invalid argument to -instance <= %s>. Service not started.", argv[i+1]); + MsgToEventLog(M_ERR, + L"Invalid argument to -instance <%s>. Se= rvice not started.", + argv[i + 1]); return 1; } } else { wprintf(L"%ls -install to install the interactive s= ervice\n", APPNAME); - wprintf(L"%ls -start [name] to start the service (name = =3D \"interactive\") is optional\n", APPNAME); + wprintf( + L"%ls -start [name] to start the service (name =3D \= "interactive\") is optional\n", + APPNAME); wprintf(L"%ls -remove to remove the service\n", AP= PNAME); wprintf(L"\nService run-time parameters:\n"); wprintf(L"-instance interactive \n" L" Runs the service as an alternate instance.\n" L" The service settings will be loaded from\n" - L" HKLM\\Software\\" _L(PACKAGE_NAME) L" reg= istry key, and the service will accept\n" - L" requests on \\\\.\\pipe\\" _L(PACKAGE) L"= \\service named pipe.\n"); + L" HKLM\\Software\\" _L( + PACKAGE_NAME) L" registry key, and the ser= vice will accept\n" + L" requests on \\\\.\\pipe\\" = _L( + PACKAGE) L"\\service nam= ed pipe.\n"); return 0; } diff --git a/src/openvpnserv/service.h b/src/openvpnserv/service.h index 8989e60..3d3b82b 100644 --- a/src/openvpnserv/service.h +++ b/src/openvpnserv/service.h @@ -33,24 +33,26 @@ #include #include "../tapctl/basic.h" -#define APPNAME _L(PACKAGE) L"serv" -#define SERVICE_DEPENDENCIES _L(TAP_WIN_COMPONENT_ID) L"\0Dhcp\0\0" +#define APPNAME _L(PACKAGE) L"serv" +#define SERVICE_DEPENDENCIES _L(TAP_WIN_COMPONENT_ID) L"\0Dhcp\0\0" /* * Message handling */ -#define MSG_FLAGS_ERROR (1<<0) -#define MSG_FLAGS_SYS_CODE (1<<1) -#define M_INFO (0) /* informational */ -#define M_SYSERR (MSG_FLAGS_ERROR|MSG_FLAGS_SYS_CODE) /* error + system c= ode */ -#define M_ERR (MSG_FLAGS_ERROR) /* error */ +#define MSG_FLAGS_ERROR (1 << 0) +#define MSG_FLAGS_SYS_CODE (1 << 1) +#define M_INFO (0) /* infor= mational */ +#define M_SYSERR (MSG_FLAGS_ERROR | MSG_FLAGS_SYS_CODE) /* error= + system code */ +#define M_ERR (MSG_FLAGS_ERROR) /* error= */ -typedef enum { +typedef enum +{ interactive, _service_max } openvpn_service_type; -typedef struct { +typedef struct +{ openvpn_service_type type; WCHAR *name; WCHAR *display_name; @@ -59,7 +61,8 @@ } openvpn_service_t; #define MAX_NAME 256 -typedef struct { +typedef struct +{ WCHAR exe_path[MAX_PATH]; WCHAR config_dir[MAX_PATH]; WCHAR bin_dir[MAX_PATH]; diff --git a/src/openvpnserv/validate.c b/src/openvpnserv/validate.c index 6ed5bea..59d5b86 100644 --- a/src/openvpnserv/validate.c +++ b/src/openvpnserv/validate.c @@ -26,8 +26,7 @@ #include #include -static const WCHAR *white_list[] =3D -{ +static const WCHAR *white_list[] =3D { L"auth-retry", L"config", L"log", @@ -46,7 +45,7 @@ L"pull-filter", L"script-security", - NULL /* last value */ + NULL /* last value */ }; static BOOL IsUserInGroup(PSID sid, const PTOKEN_GROUPS groups, const WCHA= R *group_name); @@ -65,7 +64,7 @@ const WCHAR *config_dir =3D NULL; /* convert fname to full path */ - if (PathIsRelativeW(fname) ) + if (PathIsRelativeW(fname)) { swprintf(tmp, _countof(tmp), L"%ls\\%ls", workdir, fname); config_file =3D tmp; @@ -128,7 +127,7 @@ return FALSE; } - b =3D CreateWellKnownSid(WinBuiltinAdministratorsSid, NULL, admin_sid,= &sid_size); + b =3D CreateWellKnownSid(WinBuiltinAdministratorsSid, NULL, admin_sid,= &sid_size); if (b) { b =3D LookupAccountSidW(NULL, admin_sid, name, &nlen, domain, &dle= n, &snu); @@ -140,7 +139,8 @@ } BOOL -IsAuthorizedUser(PSID sid, const HANDLE token, const WCHAR *ovpn_admin_gro= up, const WCHAR *ovpn_service_user) +IsAuthorizedUser(PSID sid, const HANDLE token, const WCHAR *ovpn_admin_gro= up, + const WCHAR *ovpn_service_user) { const WCHAR *admin_group[2]; WCHAR username[MAX_NAME]; @@ -171,7 +171,8 @@ } else { - MsgToEventLog(M_SYSERR, L"Failed to get the name of Administrators= group. Using the default."); + MsgToEventLog(M_SYSERR, + L"Failed to get the name of Administrators group. Us= ing the default."); /* use the default value */ admin_group[0] =3D SYSTEM_ADMIN_GROUP; } @@ -183,7 +184,8 @@ ret =3D IsUserInGroup(sid, token_groups, admin_group[i]); if (ret) { - MsgToEventLog(M_INFO, L"Authorizing user '%ls@%ls' by virtue o= f membership in group '%ls'", + MsgToEventLog(M_INFO, + L"Authorizing user '%ls@%ls' by virtue of member= ship in group '%ls'", username, domain, admin_group[i]); goto out; } @@ -265,11 +267,11 @@ int nloop =3D 0; /* a counter used to not get stuck in the do .. while= () */ /* first check in the token groups */ - if (token_groups && LookupSID(group_name, (PSID) grp_sid, _countof(grp= _sid))) + if (token_groups && LookupSID(group_name, (PSID)grp_sid, _countof(grp_= sid))) { for (DWORD i =3D 0; i < token_groups->GroupCount; ++i) { - if (EqualSid((PSID) grp_sid, token_groups->Groups[i].Sid)) + if (EqualSid((PSID)grp_sid, token_groups->Groups[i].Sid)) { return TRUE; } @@ -285,8 +287,8 @@ { DWORD nread, nmax; LOCALGROUP_MEMBERS_INFO_0 *members =3D NULL; - err =3D NetLocalGroupGetMembers(NULL, group_name, 0, (LPBYTE *) &m= embers, - MAX_PREFERRED_LENGTH, &nread, &nmax,= &resume); + err =3D NetLocalGroupGetMembers(NULL, group_name, 0, (LPBYTE *)&me= mbers, MAX_PREFERRED_LENGTH, + &nread, &nmax, &resume); if ((err !=3D NERR_Success && err !=3D ERROR_MORE_DATA)) { break; @@ -319,16 +321,13 @@ { /* Do not modify argv or *argv -- ideally it should be const WCHAR *co= nst *, but alas...*/ - if (wcscmp(argv[0], L"--config") =3D=3D 0 - && argc > 1 - && !CheckConfigPath(workdir, argv[1], s) - ) + if (wcscmp(argv[0], L"--config") =3D=3D 0 && argc > 1 && !CheckConfigP= ath(workdir, argv[1], s)) { return FALSE; } /* option name starts at 2 characters from argv[i] */ - if (OptionLookup(argv[0] + 2, white_list) =3D=3D -1) /* not found */ + if (OptionLookup(argv[0] + 2, white_list) =3D=3D -1) /* not found */ { return FALSE; } diff --git a/src/openvpnserv/validate.h b/src/openvpnserv/validate.h index bde1892..6f3bf09 100644 --- a/src/openvpnserv/validate.h +++ b/src/openvpnserv/validate.h @@ -28,19 +28,20 @@ =20 /* Authorized groups who can use any options and config locations */ #define SYSTEM_ADMIN_GROUP L"Administrators" -#define OVPN_ADMIN_GROUP L"OpenVPN Administrators" /* may be set in HKLM\S= oftware\OpenVPN\ovpn_admin_group */ -#define OVPN_SERVICE_USER L"OpenVPNService" /* may be set in HKLM\Software= \OpenVPN\ovpn_service_user */ +#define OVPN_ADMIN_GROUP \ + L"OpenVPN Administrators" /* may be set in HKLM\Software\OpenVPN\ovpn_= admin_group */ +#define OVPN_SERVICE_USER \ + L"OpenVPNService" /* may be set in HKLM\Software\OpenVPN\ovpn_= service_user */ /* * Check whether user is a member of Administrators group or * the group specified in ovpn_admin_group or * OpenVPN Virtual Service Account user */ -BOOL -IsAuthorizedUser(PSID sid, const HANDLE token, const WCHAR *ovpn_admin_gro= up, const WCHAR *ovpn_service_user); +BOOL IsAuthorizedUser(PSID sid, const HANDLE token, const WCHAR *ovpn_admi= n_group, + const WCHAR *ovpn_service_user); -BOOL -CheckOption(const WCHAR *workdir, int narg, WCHAR *argv[], const settings_= t *s); +BOOL CheckOption(const WCHAR *workdir, int narg, WCHAR *argv[], const sett= ings_t *s); static inline BOOL IsOption(const WCHAR *o) diff --git a/src/plugins/auth-pam/auth-pam.c b/src/plugins/auth-pam/auth-pa= m.c index bff4767..15169ca 100644 --- a/src/plugins/auth-pam/auth-pam.c +++ b/src/plugins/auth-pam/auth-pam.c @@ -99,12 +99,14 @@ #define N_NAME_VALUE 16 -struct name_value { +struct name_value +{ const char *name; const char *value; }; -struct name_value_list { +struct name_value_list +{ int len; struct name_value data[N_NAME_VALUE]; }; @@ -113,7 +115,8 @@ * Used to pass the username/password * to the PAM conversation function. */ -struct user_pass { +struct user_pass +{ int verb; char username[128]; @@ -126,7 +129,8 @@ }; /* Background process function */ -static void pam_server(int fd, const char *service, int verb, const struct= name_value_list *name_value_list); +static void pam_server(int fd, const char *service, int verb, + const struct name_value_list *name_value_list); /* @@ -152,11 +156,11 @@ static int send_control(int fd, int code) { - unsigned char c =3D (unsigned char) code; + unsigned char c =3D (unsigned char)code; const ssize_t size =3D write(fd, &c, sizeof(c)); if (size =3D=3D sizeof(c)) { - return (int) size; + return (int)size; } else { @@ -171,7 +175,7 @@ { memset(buffer, 0, len); ssize_t size =3D read(fd, buffer, len); - buffer[len-1] =3D 0; + buffer[len - 1] =3D 0; if (size >=3D 1) { return size; @@ -220,7 +224,7 @@ #endif if (daemon(0, 0) < 0) { - plugin_log(PLOG_ERR|PLOG_ERRNO, MODULE, "daemonization failed"= ); + plugin_log(PLOG_ERR | PLOG_ERRNO, MODULE, "daemonization faile= d"); } #if defined(__APPLE__) && defined(__clang__) #pragma clang diagnostic pop @@ -321,11 +325,11 @@ } *resp++ =3D '\0'; - int n =3D plugin_base64_decode(pass, up->password, sizeof(up->password= )-1); + int n =3D plugin_base64_decode(pass, up->password, sizeof(up->password= ) - 1); if (n >=3D 0) { up->password[n] =3D '\0'; - n =3D plugin_base64_decode(resp, up->response, sizeof(up->response= )-1); + n =3D plugin_base64_decode(resp, up->response, sizeof(up->response= ) - 1); if (n >=3D 0) { up->response[n] =3D '\0'; @@ -353,8 +357,7 @@ } OPENVPN_EXPORT int -openvpn_plugin_open_v3(const int v3structver, - struct openvpn_plugin_args_open_in const *args, +openvpn_plugin_open_v3(const int v3structver, struct openvpn_plugin_args_o= pen_in const *args, struct openvpn_plugin_args_open_return *ret) { pid_t pid; @@ -371,14 +374,15 @@ /* Check API compatibility -- struct version 5 or higher needed */ if (v3structver < 5) { - fprintf(stderr, "AUTH-PAM: This plugin is incompatible with the ru= nning version of OpenVPN\n"); + fprintf(stderr, + "AUTH-PAM: This plugin is incompatible with the running ve= rsion of OpenVPN\n"); return OPENVPN_PLUGIN_FUNC_ERROR; } /* * Allocate our context */ - context =3D (struct auth_pam_context *) calloc(1, sizeof(struct auth_p= am_context)); + context =3D (struct auth_pam_context *)calloc(1, sizeof(struct auth_pa= m_context)); if (!context) { goto error; @@ -426,7 +430,7 @@ { const int base =3D base_parms + i * 2; name_value_list.data[i].name =3D argv[base]; - name_value_list.data[i].value =3D argv[base+1]; + name_value_list.data[i].value =3D argv[base + 1]; } } @@ -447,7 +451,7 @@ */ if (socketpair(PF_UNIX, SOCK_DGRAM, 0, fd) =3D=3D -1) { - plugin_log(PLOG_ERR|PLOG_ERRNO, MODULE, "socketpair call failed"); + plugin_log(PLOG_ERR | PLOG_ERRNO, MODULE, "socketpair call failed"= ); goto error; } @@ -473,7 +477,8 @@ /* don't let future subprocesses inherit child socket */ if (fcntl(fd[0], F_SETFD, FD_CLOEXEC) < 0) { - plugin_log(PLOG_ERR|PLOG_ERRNO, MODULE, "Set FD_CLOEXEC flag o= n socket file descriptor failed"); + plugin_log(PLOG_ERR | PLOG_ERRNO, MODULE, + "Set FD_CLOEXEC flag on socket file descriptor fail= ed"); } /* wait for background child process to initialize */ @@ -481,8 +486,8 @@ if (status =3D=3D RESPONSE_INIT_SUCCEEDED) { context->foreground_fd =3D fd[0]; - ret->handle =3D (openvpn_plugin_handle_t *) context; - plugin_log( PLOG_NOTE, MODULE, "initialization succeeded (fg)"= ); + ret->handle =3D (openvpn_plugin_handle_t *)context; + plugin_log(PLOG_NOTE, MODULE, "initialization succeeded (fg)"); return OPENVPN_PLUGIN_FUNC_SUCCESS; } } @@ -518,9 +523,10 @@ } OPENVPN_EXPORT int -openvpn_plugin_func_v1(openvpn_plugin_handle_t handle, const int type, con= st char *argv[], const char *envp[]) +openvpn_plugin_func_v1(openvpn_plugin_handle_t handle, const int type, con= st char *argv[], + const char *envp[]) { - struct auth_pam_context *context =3D (struct auth_pam_context *) handl= e; + struct auth_pam_context *context =3D (struct auth_pam_context *)handle; if (type =3D=3D OPENVPN_PLUGIN_AUTH_USER_PASS_VERIFY && context->foreg= round_fd >=3D 0) { @@ -549,8 +555,7 @@ { if (DEBUG(context->verb)) { - plugin_log(PLOG_NOTE, MODULE, "do deferred auth '%s'", - auth_control_file); + plugin_log(PLOG_NOTE, MODULE, "do deferred auth '%s'", aut= h_control_file); } } else @@ -567,7 +572,8 @@ || send_string(context->foreground_fd, auth_control_file) = =3D=3D -1 || send_string(context->foreground_fd, remote) =3D=3D -1) { - plugin_log(PLOG_ERR|PLOG_ERRNO, MODULE, "Error sending aut= h info to background process"); + plugin_log(PLOG_ERR | PLOG_ERRNO, MODULE, + "Error sending auth info to background process"= ); } else { @@ -586,7 +592,8 @@ } if (status =3D=3D -1) { - plugin_log(PLOG_ERR|PLOG_ERRNO, MODULE, "Error receivi= ng auth confirmation from background process"); + plugin_log(PLOG_ERR | PLOG_ERRNO, MODULE, + "Error receiving auth confirmation from bac= kground process"); } } } @@ -597,7 +604,7 @@ OPENVPN_EXPORT void openvpn_plugin_close_v1(openvpn_plugin_handle_t handle) { - struct auth_pam_context *context =3D (struct auth_pam_context *) handl= e; + struct auth_pam_context *context =3D (struct auth_pam_context *)handle; if (DEBUG(context->verb)) { @@ -609,7 +616,7 @@ /* tell background process to exit */ if (send_control(context->foreground_fd, COMMAND_EXIT) =3D=3D -1) { - plugin_log(PLOG_ERR|PLOG_ERRNO, MODULE, "Error signaling backg= round process to exit"); + plugin_log(PLOG_ERR | PLOG_ERRNO, MODULE, "Error signaling bac= kground process to exit"); } /* wait for background process to exit */ @@ -628,7 +635,7 @@ OPENVPN_EXPORT void openvpn_plugin_abort_v1(openvpn_plugin_handle_t handle) { - struct auth_pam_context *context =3D (struct auth_pam_context *) handl= e; + struct auth_pam_context *context =3D (struct auth_pam_context *)handle; /* tell background process to exit */ if (context && context->foreground_fd >=3D 0) @@ -643,10 +650,10 @@ * PAM conversation function */ static int -my_conv(int num_msg, const struct pam_message **msg_array, - struct pam_response **response_array, void *appdata_ptr) +my_conv(int num_msg, const struct pam_message **msg_array, struct pam_resp= onse **response_array, + void *appdata_ptr) { - const struct user_pass *up =3D ( const struct user_pass *) appdata_ptr; + const struct user_pass *up =3D (const struct user_pass *)appdata_ptr; struct pam_response *aresp; int ret =3D PAM_SUCCESS; @@ -670,10 +677,8 @@ if (DEBUG(up->verb)) { - plugin_log(PLOG_NOTE, MODULE, "BACKGROUND: my_conv[%d] query= =3D'%s' style=3D%d", - i, - msg->msg ? msg->msg : "NULL", - msg->msg_style); + plugin_log(PLOG_NOTE, MODULE, "BACKGROUND: my_conv[%d] query= =3D'%s' style=3D%d", i, + msg->msg ? msg->msg : "NULL", msg->msg_style); } if (up->name_value_list && up->name_value_list->len > 0) @@ -695,10 +700,10 @@ if (DEBUG(up->verb)) { - plugin_log(PLOG_NOTE, MODULE, "BACKGROUND: name ma= tch found, query/match-string ['%s', '%s'] =3D '%s'", - msg->msg, - match_name, - match_value); + plugin_log( + PLOG_NOTE, MODULE, + "BACKGROUND: name match found, query/match-str= ing ['%s', '%s'] =3D '%s'", + msg->msg, match_name, match_value); } if (strstr(match_value, "USERNAME")) @@ -711,7 +716,8 @@ } else if (strstr(match_value, "COMMONNAME")) { - aresp[i].resp =3D searchandreplace(match_value, "C= OMMONNAME", up->common_name); + aresp[i].resp =3D + searchandreplace(match_value, "COMMONNAME", up= ->common_name); } else if (strstr(match_value, "OTP")) { @@ -822,8 +828,7 @@ if (!ret) { plugin_log(PLOG_ERR, MODULE, "BACKGROUND: user '%s' failed to = authenticate: %s", - up->username, - pam_strerror(pamh, status)); + up->username, pam_strerror(pamh, status)); } /* Close PAM */ @@ -844,12 +849,12 @@ */ static void -do_deferred_pam_auth(int fd, const char *ac_file_name, - const char *service, const struct user_pass *up) +do_deferred_pam_auth(int fd, const char *ac_file_name, const char *service, + const struct user_pass *up) { if (send_control(fd, RESPONSE_DEFER) =3D=3D -1) { - plugin_log(PLOG_ERR|PLOG_ERRNO, MODULE, "BACKGROUND: write error o= n response socket [4]"); + plugin_log(PLOG_ERR | PLOG_ERRNO, MODULE, "BACKGROUND: write error= on response socket [4]"); return; } @@ -858,52 +863,50 @@ if (p1 < 0) { - plugin_log(PLOG_ERR|PLOG_ERRNO, MODULE, "BACKGROUND: fork(1) faile= d"); + plugin_log(PLOG_ERR | PLOG_ERRNO, MODULE, "BACKGROUND: fork(1) fai= led"); return; } - if (p1 !=3D 0) /* parent */ + if (p1 !=3D 0) /* parent */ { waitpid(p1, NULL, 0); - return; /* parent's job succeeded */ + return; /* parent's job succeeded */ } /* child */ - close(fd); /* socketpair no longer needed= */ + close(fd); /* socketpair no longer needed */ pid_t p2 =3D fork(); if (p2 < 0) { - plugin_log(PLOG_ERR|PLOG_ERRNO, MODULE, "BACKGROUND: fork(2) faile= d"); + plugin_log(PLOG_ERR | PLOG_ERRNO, MODULE, "BACKGROUND: fork(2) fai= led"); exit(1); } - if (p2 !=3D 0) /* new parent: exit right aw= ay */ + if (p2 !=3D 0) /* new parent: exit right away */ { exit(0); } /* grandchild */ - plugin_log(PLOG_NOTE, MODULE, "BACKGROUND: deferred auth for '%s', pid= =3D%d", - up->username, (int) getpid() ); + plugin_log(PLOG_NOTE, MODULE, "BACKGROUND: deferred auth for '%s', pid= =3D%d", up->username, + (int)getpid()); /* the rest is very simple: do PAM, write status byte to file, done */ - int ac_fd =3D open( ac_file_name, O_WRONLY ); + int ac_fd =3D open(ac_file_name, O_WRONLY); if (ac_fd < 0) { - plugin_log(PLOG_ERR|PLOG_ERRNO, MODULE, "cannot open '%s' for writ= ing", - ac_file_name ); + plugin_log(PLOG_ERR | PLOG_ERRNO, MODULE, "cannot open '%s' for wr= iting", ac_file_name); exit(1); } int pam_success =3D pam_auth(service, up); - if (write( ac_fd, pam_success ? "1" : "0", 1 ) !=3D 1) + if (write(ac_fd, pam_success ? "1" : "0", 1) !=3D 1) { - plugin_log(PLOG_ERR|PLOG_ERRNO, MODULE, "cannot write to '%s'", - ac_file_name ); + plugin_log(PLOG_ERR | PLOG_ERRNO, MODULE, "cannot write to '%s'", = ac_file_name); } close(ac_fd); - plugin_log(PLOG_NOTE, MODULE, "BACKGROUND: %s: deferred auth: PAM %s", - up->username, pam_success ? "succeeded" : "rejected" ); + plugin_log(PLOG_NOTE, MODULE, "BACKGROUND: %s: deferred auth: PAM %s",= up->username, + pam_success ? "succeeded" : "rejected"); exit(0); } @@ -934,7 +937,8 @@ */ if (!dlopen_pam(pam_so)) { - plugin_log(PLOG_ERR, MODULE, "BACKGROUND: could not load PAM lib %= s: %s", pam_so, dlerror()); + plugin_log(PLOG_ERR, MODULE, "BACKGROUND: could not load PAM lib %= s: %s", pam_so, + dlerror()); send_control(fd, RESPONSE_INIT_FAILED); goto done; } @@ -945,7 +949,7 @@ */ if (send_control(fd, RESPONSE_INIT_SUCCEEDED) =3D=3D -1) { - plugin_log(PLOG_ERR|PLOG_ERRNO, MODULE, "BACKGROUND: write error o= n response socket [1]"); + plugin_log(PLOG_ERR | PLOG_ERRNO, MODULE, "BACKGROUND: write error= on response socket [1]"); goto done; } @@ -977,7 +981,8 @@ || recv_string(fd, ac_file_name, sizeof(ac_file_name))= =3D=3D -1 || recv_string(fd, up.remote, sizeof(up.remote)) =3D= =3D -1) { - plugin_log(PLOG_ERR|PLOG_ERRNO, MODULE, "BACKGROUND: r= ead error on command channel: code=3D%d, exiting", + plugin_log(PLOG_ERR | PLOG_ERRNO, MODULE, + "BACKGROUND: read error on command channel:= code=3D%d, exiting", command); goto done; } @@ -1012,7 +1017,8 @@ { if (send_control(fd, RESPONSE_VERIFY_SUCCEEDED) =3D=3D= -1) { - plugin_log(PLOG_ERR|PLOG_ERRNO, MODULE, "BACKGROUN= D: write error on response socket [2]"); + plugin_log(PLOG_ERR | PLOG_ERRNO, MODULE, + "BACKGROUND: write error on response so= cket [2]"); goto done; } } @@ -1020,7 +1026,8 @@ { if (send_control(fd, RESPONSE_VERIFY_FAILED) =3D=3D -1) { - plugin_log(PLOG_ERR|PLOG_ERRNO, MODULE, "BACKGROUN= D: write error on response socket [3]"); + plugin_log(PLOG_ERR | PLOG_ERRNO, MODULE, + "BACKGROUND: write error on response so= cket [3]"); goto done; } } @@ -1031,7 +1038,8 @@ goto done; case -1: - plugin_log(PLOG_ERR|PLOG_ERRNO, MODULE, "BACKGROUND: read = error on command channel"); + plugin_log(PLOG_ERR | PLOG_ERRNO, MODULE, + "BACKGROUND: read error on command channel"); goto done; default: diff --git a/src/plugins/auth-pam/pamdl.c b/src/plugins/auth-pam/pamdl.c index 02ea71a..c1ecfa0 100644 --- a/src/plugins/auth-pam/pamdl.c +++ b/src/plugins/auth-pam/pamdl.c @@ -19,14 +19,20 @@ static void *libpam_h =3D NULL; -#define RESOLVE_PAM_FUNCTION(x, y, z, err) \ - { \ - union { const void *tpointer; y(*fn) z; } fptr; \ - fptr.tpointer =3D dlsym(libpam_h, #x); real_ ## x =3D fptr.fn; \ - if (real_ ## x =3D=3D NULL) { \ +#define RESOLVE_PAM_FUNCTION(x, y, z, err) = \ + { = \ + union = \ + { = \ + const void *tpointer; = \ + y(*fn) z; = \ + } fptr; = \ + fptr.tpointer =3D dlsym(libpam_h, #x); = \ + real_##x =3D fptr.fn; = \ + if (real_##x =3D=3D NULL) = \ + { = \ fprintf(stderr, "PAMDL: unable to resolve '%s': %s\n", #x, dle= rror()); \ - return err; \ - } \ + return err; = \ + } = \ } int @@ -34,7 +40,7 @@ { if (libpam_h =3D=3D NULL) { - libpam_h =3D dlopen(so, RTLD_GLOBAL|RTLD_NOW); + libpam_h =3D dlopen(so, RTLD_GLOBAL | RTLD_NOW); } return libpam_h !=3D NULL; } @@ -50,16 +56,13 @@ } int -pam_start(const char *service_name, const char *user, - const struct pam_conv *pam_conversation, +pam_start(const char *service_name, const char *user, const struct pam_con= v *pam_conversation, pam_handle_t **pamh) { - int (*real_pam_start)(const char *, const char *, - const struct pam_conv *, - pam_handle_t **); - RESOLVE_PAM_FUNCTION(pam_start, int, (const char *, const char *, - const struct pam_conv *, - pam_handle_t **), PAM_ABORT); + int (*real_pam_start)(const char *, const char *, const struct pam_con= v *, pam_handle_t **); + RESOLVE_PAM_FUNCTION(pam_start, int, + (const char *, const char *, const struct pam_con= v *, pam_handle_t **), + PAM_ABORT); return real_pam_start(service_name, user, pam_conversation, pamh); } @@ -75,8 +78,7 @@ pam_set_item(pam_handle_t *pamh, int item_type, const void *item) { int (*real_pam_set_item)(pam_handle_t *, int, const void *); - RESOLVE_PAM_FUNCTION(pam_set_item, int, - (pam_handle_t *, int, const void *), PAM_ABORT); + RESOLVE_PAM_FUNCTION(pam_set_item, int, (pam_handle_t *, int, const vo= id *), PAM_ABORT); return real_pam_set_item(pamh, item_type, item); } @@ -84,9 +86,7 @@ pam_get_item(const pam_handle_t *pamh, int item_type, const void **item) { int (*real_pam_get_item)(const pam_handle_t *, int, const void **); - RESOLVE_PAM_FUNCTION(pam_get_item, int, - (const pam_handle_t *, int, const void **), - PAM_ABORT); + RESOLVE_PAM_FUNCTION(pam_get_item, int, (const pam_handle_t *, int, co= nst void **), PAM_ABORT); return real_pam_get_item(pamh, item_type, item); } @@ -94,8 +94,7 @@ pam_fail_delay(pam_handle_t *pamh, unsigned int musec_delay) { int (*real_pam_fail_delay)(pam_handle_t *, unsigned int); - RESOLVE_PAM_FUNCTION(pam_fail_delay, int, (pam_handle_t *, unsigned in= t), - PAM_ABORT); + RESOLVE_PAM_FUNCTION(pam_fail_delay, int, (pam_handle_t *, unsigned in= t), PAM_ABORT); return real_pam_fail_delay(pamh, musec_delay); } @@ -105,8 +104,7 @@ pam_strerror(pam_handle_t *pamh, int errnum) { const_char_pointer (*real_pam_strerror)(pam_handle_t *, int); - RESOLVE_PAM_FUNCTION(pam_strerror, const_char_pointer, - (pam_handle_t *, int), NULL); + RESOLVE_PAM_FUNCTION(pam_strerror, const_char_pointer, (pam_handle_t *= , int), NULL); return real_pam_strerror(pamh, errnum); } @@ -114,8 +112,7 @@ pam_putenv(pam_handle_t *pamh, const char *name_value) { int (*real_pam_putenv)(pam_handle_t *, const char *); - RESOLVE_PAM_FUNCTION(pam_putenv, int, (pam_handle_t *, const char *), - PAM_ABORT); + RESOLVE_PAM_FUNCTION(pam_putenv, int, (pam_handle_t *, const char *), = PAM_ABORT); return real_pam_putenv(pamh, name_value); } @@ -123,8 +120,7 @@ pam_getenv(pam_handle_t *pamh, const char *name) { const_char_pointer (*real_pam_getenv)(pam_handle_t *, const char *); - RESOLVE_PAM_FUNCTION(pam_getenv, const_char_pointer, - (pam_handle_t *, const char *), NULL); + RESOLVE_PAM_FUNCTION(pam_getenv, const_char_pointer, (pam_handle_t *, = const char *), NULL); return real_pam_getenv(pamh, name); } @@ -133,8 +129,7 @@ pam_getenvlist(pam_handle_t *pamh) { char_ppointer (*real_pam_getenvlist)(pam_handle_t *); - RESOLVE_PAM_FUNCTION(pam_getenvlist, char_ppointer, (pam_handle_t *), - NULL); + RESOLVE_PAM_FUNCTION(pam_getenvlist, char_ppointer, (pam_handle_t *), = NULL); return real_pam_getenvlist(pamh); } @@ -144,8 +139,7 @@ pam_authenticate(pam_handle_t *pamh, int flags) { int (*real_pam_authenticate)(pam_handle_t *, int); - RESOLVE_PAM_FUNCTION(pam_authenticate, int, (pam_handle_t *, int), - PAM_ABORT); + RESOLVE_PAM_FUNCTION(pam_authenticate, int, (pam_handle_t *, int), PAM= _ABORT); return real_pam_authenticate(pamh, flags); } @@ -173,8 +167,7 @@ pam_open_session(pam_handle_t *pamh, int flags) { int (*real_pam_open_session)(pam_handle_t *, int); - RESOLVE_PAM_FUNCTION(pam_open_session, int, (pam_handle_t *, int), - PAM_ABORT); + RESOLVE_PAM_FUNCTION(pam_open_session, int, (pam_handle_t *, int), PAM= _ABORT); return real_pam_open_session(pamh, flags); } @@ -182,8 +175,7 @@ pam_close_session(pam_handle_t *pamh, int flags) { int (*real_pam_close_session)(pam_handle_t *, int); - RESOLVE_PAM_FUNCTION(pam_close_session, int, (pam_handle_t *, int), - PAM_ABORT); + RESOLVE_PAM_FUNCTION(pam_close_session, int, (pam_handle_t *, int), PA= M_ABORT); return real_pam_close_session(pamh, flags); } diff --git a/src/plugins/auth-pam/utils.c b/src/plugins/auth-pam/utils.c index 6524051..0da162d 100644 --- a/src/plugins/auth-pam/utils.c +++ b/src/plugins/auth-pam/utils.c @@ -55,7 +55,8 @@ return NULL; } - bool is_potential_integer_overflow =3D (templen =3D=3D SIZE_MAX) || (= templen / tosearchlen !=3D replacewithlen); + bool is_potential_integer_overflow =3D + (templen =3D=3D SIZE_MAX) || (templen / tosearchlen !=3D replacewi= thlen); if (is_potential_integer_overflow) { @@ -67,7 +68,7 @@ const char *searching =3D tosearch; char *scratch; - char temp[templen+1]; + char temp[templen + 1]; temp[0] =3D 0; scratch =3D strstr(searching, searchfor); @@ -78,10 +79,10 @@ while (scratch) { - strncat(temp, searching, (size_t)(scratch-searching)); + strncat(temp, searching, (size_t)(scratch - searching)); strcat(temp, replacewith); - searching =3D scratch+strlen(searchfor); + searching =3D scratch + strlen(searchfor); scratch =3D strstr(searching, searchfor); } return strdup(temp); diff --git a/src/plugins/auth-pam/utils.h b/src/plugins/auth-pam/utils.h index 0b90aee..a733feb 100644 --- a/src/plugins/auth-pam/utils.h +++ b/src/plugins/auth-pam/utils.h @@ -34,11 +34,10 @@ * @param searchfor needle to search for in the haystack * @param replacewith when a match is found, replace needle with this s= tring * - * @return Returns NULL when any parameter is NULL or the worst-case resu= lt is to large ( >=3D SIZE_MAX). - * Otherwise it returns a pointer to a new buffer containing the = modified input + * @return Returns NULL when any parameter is NULL or the worst-case resu= lt is to large ( >=3D + * SIZE_MAX). Otherwise it returns a pointer to a new buffer containing th= e modified input */ -char * -searchandreplace(const char *tosearch, const char *searchfor, const char *= replacewith); +char *searchandreplace(const char *tosearch, const char *searchfor, const = char *replacewith); /** * Given an environmental variable name, search @@ -47,10 +46,10 @@ * @param name Environment variable to look up * @param envp Environment variable table with all key/value pairs * - * @return Returns a pointer to the value of the environment variable if f= ound, otherwise NULL is returned. + * @return Returns a pointer to the value of the environment variable if f= ound, otherwise NULL is + * returned. */ -const char * -get_env(const char *name, const char *envp[]); +const char *get_env(const char *name, const char *envp[]); /** * Return the length of a string array @@ -58,7 +57,6 @@ * @param array Pointer to the array to calculate size of * */ -int -string_array_len(const char *array[]); +int string_array_len(const char *array[]); #endif diff --git a/src/plugins/down-root/down-root.c b/src/plugins/down-root/down= -root.c index 5f595fd..da476fc 100644 --- a/src/plugins/down-root/down-root.c +++ b/src/plugins/down-root/down-root.c @@ -142,7 +142,7 @@ static ssize_t send_control(int fd, int code) { - unsigned char c =3D (unsigned char) code; + unsigned char c =3D (unsigned char)code; const ssize_t size =3D write(fd, &c, sizeof(c)); if (size =3D=3D sizeof(c)) { @@ -252,7 +252,7 @@ int ret =3D 0; pid =3D fork(); - if (pid =3D=3D (pid_t)0) /* child side */ + if (pid =3D=3D (pid_t)0) /* child side */ { execve(argv[0], argv, envp); /* If execve() fails to run, exit child with exit code 127 */ @@ -263,12 +263,13 @@ warn("DOWN-ROOT: Failed to fork child to run %s", argv[0]); return -1; } - else /* parent side */ + else /* parent side */ { if (waitpid(pid, &ret, 0) !=3D pid) { /* waitpid does not return error information via errno */ - fprintf(stderr, "DOWN-ROOT: waitpid() failed, don't know exit = code of child (%s)\n", argv[0]); + fprintf(stderr, "DOWN-ROOT: waitpid() failed, don't know exit = code of child (%s)\n", + argv[0]); return -1; } } @@ -283,7 +284,7 @@ /* * Allocate our context */ - context =3D (struct down_root_context *) calloc(1, sizeof(struct down_= root_context)); + context =3D (struct down_root_context *)calloc(1, sizeof(struct down_r= oot_context)); if (!context) { warn("DOWN-ROOT: Could not allocate memory for plug-in context"); @@ -319,7 +320,7 @@ /* Ignore argv[0], as it contains just the plug-in file name */ for (int i =3D 1; i < string_array_len(argv); i++) { - context->command[i-1] =3D (char *) argv[i]; + context->command[i - 1] =3D (char *)argv[i]; } /* @@ -333,7 +334,7 @@ } } - return (openvpn_plugin_handle_t) context; + return (openvpn_plugin_handle_t)context; error: free_context(context); @@ -341,11 +342,13 @@ } OPENVPN_EXPORT int -openvpn_plugin_func_v1(openvpn_plugin_handle_t handle, const int type, con= st char *argv[], const char *envp[]) +openvpn_plugin_func_v1(openvpn_plugin_handle_t handle, const int type, con= st char *argv[], + const char *envp[]) { - struct down_root_context *context =3D (struct down_root_context *) han= dle; + struct down_root_context *context =3D (struct down_root_context *)hand= le; - if (type =3D=3D OPENVPN_PLUGIN_UP && context->foreground_fd =3D=3D -1)= /* fork off a process to hold onto root */ + if (type =3D=3D OPENVPN_PLUGIN_UP + && context->foreground_fd =3D=3D -1) /* fork off a process to hold= onto root */ { pid_t pid; int fd[2]; @@ -409,7 +412,7 @@ daemonize(envp); /* execute the event loop */ - down_root_server(fd[1], context->command, (char *const *) envp= , context->verb); + down_root_server(fd[1], context->command, (char *const *)envp,= context->verb); close(fd[1]); exit(0); @@ -431,7 +434,8 @@ } if (status =3D=3D -1) { - warn("DOWN-ROOT: Error receiving script execution confirma= tion from background process"); + warn( + "DOWN-ROOT: Error receiving script execution confirmat= ion from background process"); } } } @@ -441,7 +445,7 @@ OPENVPN_EXPORT void openvpn_plugin_close_v1(openvpn_plugin_handle_t handle) { - struct down_root_context *context =3D (struct down_root_context *) han= dle; + struct down_root_context *context =3D (struct down_root_context *)hand= le; if (DEBUG(context->verb)) { @@ -472,7 +476,7 @@ OPENVPN_EXPORT void openvpn_plugin_abort_v1(openvpn_plugin_handle_t handle) { - struct down_root_context *context =3D (struct down_root_context *) han= dle; + struct down_root_context *context =3D (struct down_root_context *)hand= le; if (context && context->foreground_fd >=3D 0) { @@ -525,7 +529,7 @@ switch (command_code) { case COMMAND_RUN_SCRIPT: - if ( (exit_code =3D run_script(argv, envp)) =3D=3D 0) /* S= ucceeded */ + if ((exit_code =3D run_script(argv, envp)) =3D=3D 0) /* Su= cceeded */ { if (send_control(fd, RESPONSE_SCRIPT_SUCCEEDED) =3D=3D= -1) { @@ -535,7 +539,8 @@ } else /* Failed */ { - fprintf(stderr, "DOWN-ROOT: BACKGROUND: %s exited with= exit code %i\n", argv[0], exit_code); + fprintf(stderr, "DOWN-ROOT: BACKGROUND: %s exited with= exit code %i\n", argv[0], + exit_code); if (send_control(fd, RESPONSE_SCRIPT_FAILED) =3D=3D -1) { warn("DOWN-ROOT: BACKGROUND: write error on respon= se socket [3]"); diff --git a/src/tapctl/basic.h b/src/tapctl/basic.h index 571ae62..620c1ca 100644 --- a/src/tapctl/basic.h +++ b/src/tapctl/basic.h @@ -26,14 +26,16 @@ #define UNICODE #endif -#define PRIXGUID "{%08lX-%04hX-%04hX-%02hhX%02hhX-%02hhX%02hhX%02hh= X%02hhX%02hhX%02hhX}" -#define PRIGUID_PARAM(g) \ - (g).Data1, (g).Data2, (g).Data3, (g).Data4[0], (g).Data4[1], (g).Data4= [2], (g).Data4[3], (g).Data4[4], (g).Data4[5], (g).Data4[6], (g).Data4[7] -#define PRIGUID_PARAM_REF(g) \ - &(g).Data1, &(g).Data2, &(g).Data3, &(g).Data4[0], &(g).Data4[1], &(g)= .Data4[2], &(g).Data4[3], &(g).Data4[4], &(g).Data4[5], &(g).Data4[6], &(g)= .Data4[7] +#define PRIXGUID "{%08lX-%04hX-%04hX-%02hhX%02hhX-%02hhX%02hhX%02hhX%02hhX= %02hhX%02hhX}" +#define PRIGUID_PARAM(g) = \ + (g).Data1, (g).Data2, (g).Data3, (g).Data4[0], (g).Data4[1], (g).Data4= [2], (g).Data4[3], \ + (g).Data4[4], (g).Data4[5], (g).Data4[6], (g).Data4[7] +#define PRIGUID_PARAM_REF(g) = \ + &(g).Data1, &(g).Data2, &(g).Data3, &(g).Data4[0], &(g).Data4[1], &(g)= .Data4[2], \ + &(g).Data4[3], &(g).Data4[4], &(g).Data4[5], &(g).Data4[6], &(g).D= ata4[7] -#define __L(q) L ## q -#define _L(q) __L(q) +#define __L(q) L##q +#define _L(q) __L(q) #ifndef _In_ #define _In_ diff --git a/src/tapctl/error.h b/src/tapctl/error.h index 3da5674..fb24a61 100644 --- a/src/tapctl/error.h +++ b/src/tapctl/error.h @@ -34,27 +34,27 @@ /* msg() flags */ -#define M_DEBUG_LEVEL (0x0F) /* debug level mask */ +#define M_DEBUG_LEVEL (0x0F) /* debug level mask */ -#define M_FATAL (1<<4) /* exit program */ -#define M_NONFATAL (1<<5) /* non-fatal error */ -#define M_WARN (1<<6) /* call syslog with LOG_WARNING */ -#define M_DEBUG (1<<7) +#define M_FATAL (1 << 4) /* exit program */ +#define M_NONFATAL (1 << 5) /* non-fatal error */ +#define M_WARN (1 << 6) /* call syslog with LOG_WARNING */ +#define M_DEBUG (1 << 7) -#define M_ERRNO (1<<8) /* show errno description */ +#define M_ERRNO (1 << 8) /* show errno description */ -#define M_NOMUTE (1<<11) /* don't do mute processing */ -#define M_NOPREFIX (1<<12) /* don't show date/time prefix */ -#define M_USAGE_SMALL (1<<13) /* fatal options error, call usag= e_small */ -#define M_MSG_VIRT_OUT (1<<14) /* output message through msg_sta= tus_output callback */ -#define M_OPTERR (1<<15) /* print "Options error:" prefix = */ -#define M_NOLF (1<<16) /* don't print new line */ -#define M_NOIPREFIX (1<<17) /* don't print instance prefix */ +#define M_NOMUTE (1 << 11) /* don't do mute processing */ +#define M_NOPREFIX (1 << 12) /* don't show date/time prefix */ +#define M_USAGE_SMALL (1 << 13) /* fatal options error, call usage_small = */ +#define M_MSG_VIRT_OUT (1 << 14) /* output message through msg_status_outp= ut callback */ +#define M_OPTERR (1 << 15) /* print "Options error:" prefix */ +#define M_NOLF (1 << 16) /* don't print new line */ +#define M_NOIPREFIX (1 << 17) /* don't print instance prefix */ /* flag combinations which are frequently used */ -#define M_ERR (M_FATAL | M_ERRNO) -#define M_USAGE (M_USAGE_SMALL | M_NOPREFIX | M_OPTERR) -#define M_CLIENT (M_MSG_VIRT_OUT | M_NOMUTE | M_NOIPREFIX) +#define M_ERR (M_FATAL | M_ERRNO) +#define M_USAGE (M_USAGE_SMALL | M_NOPREFIX | M_OPTERR) +#define M_CLIENT (M_MSG_VIRT_OUT | M_NOMUTE | M_NOIPREFIX) /** Check muting filter */ @@ -62,18 +62,42 @@ /* Macro to ensure (and teach static analysis tools) we exit on fatal erro= rs */ #ifdef _MSC_VER -#pragma warning(disable: 4127) /* EXIT_FATAL(flags) macro raises "warning = C4127: conditional expression is constant" on each non M_FATAL invocation. = */ +#pragma warning(disable : 4127) /* EXIT_FATAL(flags) macro raises "warning= C4127: conditional \ + expression is constant" on each non M_F= ATAL invocation. */ #endif -#define EXIT_FATAL(flags) do { if ((flags) & M_FATAL) {_exit(1);}} while (= false) +#define EXIT_FATAL(flags) \ + do \ + { \ + if ((flags) & M_FATAL) \ + { \ + _exit(1); \ + } \ + } while (false) -#define msg(flags, ...) do { if (msg_test(flags)) {x_msg((flags), __VA_ARG= S__);} EXIT_FATAL(flags); } while (false) +#define msg(flags, ...) \ + do \ + { \ + if (msg_test(flags)) \ + { \ + x_msg((flags), __VA_ARGS__); \ + } \ + EXIT_FATAL(flags); \ + } while (false) #ifdef ENABLE_DEBUG -#define dmsg(flags, ...) do { if (msg_test(flags)) {x_msg((flags), __VA_AR= GS__);} EXIT_FATAL(flags); } while (false) +#define dmsg(flags, ...) \ + do \ + { \ + if (msg_test(flags)) \ + { \ + x_msg((flags), __VA_ARGS__); \ + } \ + EXIT_FATAL(flags); \ + } while (false) #else #define dmsg(flags, ...) #endif -void x_msg(const unsigned int flags, const char *format, ...); /* shou= ld be called via msg above */ +void x_msg(const unsigned int flags, const char *format, ...); /* should b= e called via msg above */ void x_msg_va(const unsigned int flags, const char *format, va_list arglis= t); diff --git a/src/tapctl/main.c b/src/tapctl/main.c index 0dec303..031e262 100644 --- a/src/tapctl/main.c +++ b/src/tapctl/main.c @@ -120,9 +120,7 @@ static void usage(void) { - fwprintf(stderr, - usage_message, - title_string); + fwprintf(stderr, usage_message, title_string); } /** @@ -139,8 +137,10 @@ { LPOLESTR adapter_id =3D NULL; StringFromIID((REFIID)&a->guid, &adapter_id); - fwprintf(stderr, L"Adapter \"%ls\" already exists (GUID %" - L"ls).\n", a->szName, adapter_id); + fwprintf(stderr, + L"Adapter \"%ls\" already exists (GUID %" + L"ls).\n", + a->szName, adapter_id); CoTaskMemFree(adapter_id); } @@ -204,8 +204,7 @@ /** * Program entry point */ -int __cdecl -wmain(int argc, LPCWSTR argv[]) +int __cdecl wmain(int argc, LPCWSTR argv[]) { int iResult; BOOL bRebootRequired =3D FALSE; @@ -239,8 +238,10 @@ } else { - fwprintf(stderr, L"Unknown command \"%ls" - L"\". Please, use \"tapctl help\" to list supported c= ommands.\n", argv[2]); + fwprintf(stderr, + L"Unknown command \"%ls" + L"\". Please, use \"tapctl help\" to list supported c= ommands.\n", + argv[2]); } return 1; @@ -263,25 +264,24 @@ } else { - fwprintf(stderr, L"Unknown option \"%ls" - L"\". Please, use \"tapctl help create\" to list = supported options. Ignored.\n", - argv[i]); + fwprintf( + stderr, + L"Unknown option \"%ls" + L"\". Please, use \"tapctl help create\" to list suppo= rted options. Ignored.\n", + argv[i]); } } /* Create TUN/TAP adapter. */ GUID guidAdapter; LPOLESTR szAdapterId =3D NULL; - DWORD dwResult =3D tap_create_adapter( - NULL, - L"Virtual Ethernet", - szHwId, - &bRebootRequired, - &guidAdapter); + DWORD dwResult =3D + tap_create_adapter(NULL, L"Virtual Ethernet", szHwId, &bReboot= Required, &guidAdapter); if (dwResult !=3D ERROR_SUCCESS) { fwprintf(stderr, L"Creating TUN/TAP adapter failed (error 0x%x= ).\n", dwResult); - iResult =3D 1; goto quit; + iResult =3D 1; + goto quit; } /* Get existing network adapters. */ @@ -294,7 +294,8 @@ goto create_delete_adapter; } - LPWSTR adapter_name =3D szName ? wcsdup(szName) : get_unique_adapt= er_name(szHwId, pAdapterList); + LPWSTR adapter_name =3D + szName ? wcsdup(szName) : get_unique_adapter_name(szHwId, pAda= pterList); if (adapter_name) { /* Check for duplicates when name was specified, @@ -310,11 +311,13 @@ if (dwResult !=3D ERROR_SUCCESS) { StringFromIID((REFIID)&guidAdapter, &szAdapterId); - fwprintf(stderr, L"Renaming TUN/TAP adapter %ls" + fwprintf(stderr, + L"Renaming TUN/TAP adapter %ls" L" to \"%ls\" failed (error 0x%x).\n", szAdapterId, adapter_name, dwResult); CoTaskMemFree(szAdapterId); - iResult =3D 1; goto quit; + iResult =3D 1; + goto quit; } } @@ -334,21 +337,19 @@ fwprintf(stdout, L"%ls\n", szAdapterId); CoTaskMemFree(szAdapterId); - iResult =3D 0; goto quit; + iResult =3D 0; + goto quit; create_delete_adapter: - tap_delete_adapter( - NULL, - &guidAdapter, - &bRebootRequired); - iResult =3D 1; goto quit; + tap_delete_adapter(NULL, &guidAdapter, &bRebootRequired); + iResult =3D 1; + goto quit; } else if (wcsicmp(argv[1], L"list") =3D=3D 0) { WCHAR szzHwId[0x100] =3D - L"root\\" _L(TAP_WIN_COMPONENT_ID) L"\0" - _L(TAP_WIN_COMPONENT_ID) L"\0" - L"ovpn-dco\0"; + L"root\\" _L(TAP_WIN_COMPONENT_ID) L"\0" _L(TAP_WIN_COMPONENT_= ID) L"\0" + = L"ovpn-dco\0"; /* Parse options. */ for (int i =3D 2; i < argc; i++) @@ -357,13 +358,17 @@ { memset(szzHwId, 0, sizeof(szzHwId)); ++i; - memcpy_s(szzHwId, sizeof(szzHwId) - 2*sizeof(WCHAR) /*requ= ires double zero termination*/, argv[i], wcslen(argv[i])*sizeof(WCHAR)); + memcpy_s(szzHwId, + sizeof(szzHwId) - 2 * sizeof(WCHAR) /*requires do= uble zero termination*/, + argv[i], wcslen(argv[i]) * sizeof(WCHAR)); } else { - fwprintf(stderr, L"Unknown option \"%ls" - L"\". Please, use \"tapctl help list\" to list su= pported options. Ignored.\n", - argv[i]); + fwprintf( + stderr, + L"Unknown option \"%ls" + L"\". Please, use \"tapctl help list\" to list support= ed options. Ignored.\n", + argv[i]); } } @@ -373,15 +378,18 @@ if (dwResult !=3D ERROR_SUCCESS) { fwprintf(stderr, L"Enumerating TUN/TAP adapters failed (error = 0x%x).\n", dwResult); - iResult =3D 1; goto quit; + iResult =3D 1; + goto quit; } for (struct tap_adapter_node *pAdapter =3D pAdapterList; pAdapter;= pAdapter =3D pAdapter->pNext) { LPOLESTR szAdapterId =3D NULL; StringFromIID((REFIID)&pAdapter->guid, &szAdapterId); - fwprintf(stdout, L"%ls\t%" - L"ls\n", szAdapterId, pAdapter->szName); + fwprintf(stdout, + L"%ls\t%" + L"ls\n", + szAdapterId, pAdapter->szName); CoTaskMemFree(szAdapterId); } @@ -392,7 +400,9 @@ { if (argc < 3) { - fwprintf(stderr, L"Missing adapter GUID or name. Please, use \= "tapctl help delete\" for usage info.\n"); + fwprintf( + stderr, + L"Missing adapter GUID or name. Please, use \"tapctl help = delete\" for usage info.\n"); return 1; } @@ -405,7 +415,8 @@ if (dwResult !=3D ERROR_SUCCESS) { fwprintf(stderr, L"Enumerating TUN/TAP adapters failed (er= ror 0x%x).\n", dwResult); - iResult =3D 1; goto quit; + iResult =3D 1; + goto quit; } for (struct tap_adapter_node *pAdapter =3D pAdapterList;; pAda= pter =3D pAdapter->pNext) @@ -413,7 +424,8 @@ if (pAdapter =3D=3D NULL) { fwprintf(stderr, L"\"%ls\" adapter not found.\n", argv= [2]); - iResult =3D 1; goto delete_cleanup_pAdapterList; + iResult =3D 1; + goto delete_cleanup_pAdapterList; } else if (wcsicmp(argv[2], pAdapter->szName) =3D=3D 0) { @@ -433,23 +445,26 @@ } /* Delete the network adapter. */ - DWORD dwResult =3D tap_delete_adapter( - NULL, - &guidAdapter, - &bRebootRequired); + DWORD dwResult =3D tap_delete_adapter(NULL, &guidAdapter, &bReboot= Required); if (dwResult !=3D ERROR_SUCCESS) { - fwprintf(stderr, L"Deleting adapter \"%ls" - L"\" failed (error 0x%x).\n", argv[2], dwResult); - iResult =3D 1; goto quit; + fwprintf(stderr, + L"Deleting adapter \"%ls" + L"\" failed (error 0x%x).\n", + argv[2], dwResult); + iResult =3D 1; + goto quit; } - iResult =3D 0; goto quit; + iResult =3D 0; + goto quit; } else { - fwprintf(stderr, L"Unknown command \"%ls" - L"\". Please, use \"tapctl help\" to list supported comma= nds.\n", argv[1]); + fwprintf(stderr, + L"Unknown command \"%ls" + L"\". Please, use \"tapctl help\" to list supported comma= nds.\n", + argv[1]); return 1; } @@ -484,16 +499,13 @@ /* Output system error message (if possible). */ DWORD dwResult =3D GetLastError(); LPWSTR szErrMessage =3D NULL; - if (FormatMessage( - FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFE= R | FORMAT_MESSAGE_IGNORE_INSERTS, - 0, - dwResult, - 0, - (LPWSTR)&szErrMessage, - 0, - NULL) && szErrMessage) + if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLO= CATE_BUFFER + | FORMAT_MESSAGE_IGNORE_INSERTS, + 0, dwResult, 0, (LPWSTR)&szErrMessage, 0, NULL) + && szErrMessage) { - /* Trim trailing whitespace. Set terminator after the last non= -whitespace character. This prevents excessive trailing line breaks. */ + /* Trim trailing whitespace. Set terminator after the last non= -whitespace character. + * This prevents excessive trailing line breaks. */ for (size_t i =3D 0, i_last =3D 0;; i++) { if (szErrMessage[i]) diff --git a/src/tapctl/tap.c b/src/tapctl/tap.c index 96f09ee..09be7e8 100644 --- a/src/tapctl/tap.c +++ b/src/tapctl/tap.c @@ -40,10 +40,15 @@ #endif -const static GUID GUID_DEVCLASS_NET =3D { 0x4d36e972L, 0xe325, 0x11ce, { 0= xbf, 0xc1, 0x08, 0x00, 0x2b, 0xe1, 0x03, 0x18 } }; +const static GUID GUID_DEVCLASS_NET =3D { + 0x4d36e972L, 0xe325, 0x11ce, { 0xbf, 0xc1, 0x08, 0x00, 0x2b, 0xe1, 0x0= 3, 0x18 } +}; -const static WCHAR szAdapterRegKeyPathTemplate[] =3D L"SYSTEM\\CurrentCont= rolSet\\Control\\Network\\%ls\\%ls\\Connection"; -#define ADAPTER_REGKEY_PATH_MAX (_countof(L"SYSTEM\\CurrentControlSet\\Con= trol\\Network\\") - 1 + 38 + _countof(L"\\") - 1 + 38 + _countof(L"\\Connec= tion")) +const static WCHAR szAdapterRegKeyPathTemplate[] =3D + L"SYSTEM\\CurrentControlSet\\Control\\Network\\%ls\\%ls\\Connection"; +#define ADAPTER_REGKEY_PATH_MAX = \ + (_countof(L"SYSTEM\\CurrentControlSet\\Control\\Network\\") - 1 + 38 += _countof(L"\\") - 1 \ + + 38 + _countof(L"\\Connection")) /** * Dynamically load a library and find a function in it @@ -154,10 +159,8 @@ * * @return ERROR_SUCCESS on success; Win32 error code otherwise **/ -typedef DWORD (*devop_func_t)( - _In_ HDEVINFO hDeviceInfoSet, - _In_ PSP_DEVINFO_DATA pDeviceInfoData, - _Inout_ LPBOOL pbRebootRequired); +typedef DWORD (*devop_func_t)(_In_ HDEVINFO hDeviceInfoSet, _In_ PSP_DEVIN= FO_DATA pDeviceInfoData, + _Inout_ LPBOOL pbRebootRequired); /** @@ -177,10 +180,8 @@ * @return ERROR_SUCCESS on success; Win32 error code otherwise **/ static DWORD -check_reboot( - _In_ HDEVINFO hDeviceInfoSet, - _In_ PSP_DEVINFO_DATA pDeviceInfoData, - _Inout_ LPBOOL pbRebootRequired) +check_reboot(_In_ HDEVINFO hDeviceInfoSet, _In_ PSP_DEVINFO_DATA pDeviceIn= foData, + _Inout_ LPBOOL pbRebootRequired) { if (pbRebootRequired =3D=3D NULL) { @@ -188,10 +189,7 @@ } SP_DEVINSTALL_PARAMS devinstall_params =3D { .cbSize =3D sizeof(SP_DEV= INSTALL_PARAMS) }; - if (!SetupDiGetDeviceInstallParams( - hDeviceInfoSet, - pDeviceInfoData, - &devinstall_params)) + if (!SetupDiGetDeviceInstallParams(hDeviceInfoSet, pDeviceInfoData, &d= evinstall_params)) { DWORD dwResult =3D GetLastError(); msg(M_NONFATAL | M_ERRNO, "%s: SetupDiGetDeviceInstallParams faile= d", __FUNCTION__); @@ -224,10 +222,8 @@ * @return ERROR_SUCCESS on success; Win32 error code otherwise **/ static DWORD -delete_device( - _In_ HDEVINFO hDeviceInfoSet, - _In_ PSP_DEVINFO_DATA pDeviceInfoData, - _Inout_ LPBOOL pbRebootRequired) +delete_device(_In_ HDEVINFO hDeviceInfoSet, _In_ PSP_DEVINFO_DATA pDeviceI= nfoData, + _Inout_ LPBOOL pbRebootRequired) { SP_REMOVEDEVICE_PARAMS params =3D { @@ -241,11 +237,8 @@ }; /* Set class installer parameters for DIF_REMOVE. */ - if (!SetupDiSetClassInstallParams( - hDeviceInfoSet, - pDeviceInfoData, - ¶ms.ClassInstallHeader, - sizeof(SP_REMOVEDEVICE_PARAMS))) + if (!SetupDiSetClassInstallParams(hDeviceInfoSet, pDeviceInfoData, &pa= rams.ClassInstallHeader, + sizeof(SP_REMOVEDEVICE_PARAMS))) { DWORD dwResult =3D GetLastError(); msg(M_NONFATAL | M_ERRNO, "%s: SetupDiSetClassInstallParams failed= ", __FUNCTION__); @@ -253,10 +246,7 @@ } /* Call appropriate class installer. */ - if (!SetupDiCallClassInstaller( - DIF_REMOVE, - hDeviceInfoSet, - pDeviceInfoData)) + if (!SetupDiCallClassInstaller(DIF_REMOVE, hDeviceInfoSet, pDeviceInfo= Data)) { DWORD dwResult =3D GetLastError(); msg(M_NONFATAL | M_ERRNO, "%s: SetupDiCallClassInstaller(DIF_REMOV= E) failed", __FUNCTION__); @@ -288,11 +278,8 @@ * @return ERROR_SUCCESS on success; Win32 error code otherwise **/ static DWORD -change_device_state( - _In_ HDEVINFO hDeviceInfoSet, - _In_ PSP_DEVINFO_DATA pDeviceInfoData, - _In_ BOOL bEnable, - _Inout_ LPBOOL pbRebootRequired) +change_device_state(_In_ HDEVINFO hDeviceInfoSet, _In_ PSP_DEVINFO_DATA pD= eviceInfoData, + _In_ BOOL bEnable, _Inout_ LPBOOL pbRebootRequired) { SP_PROPCHANGE_PARAMS params =3D { @@ -307,11 +294,8 @@ }; /* Set class installer parameters for DIF_PROPERTYCHANGE. */ - if (!SetupDiSetClassInstallParams( - hDeviceInfoSet, - pDeviceInfoData, - ¶ms.ClassInstallHeader, - sizeof(SP_PROPCHANGE_PARAMS))) + if (!SetupDiSetClassInstallParams(hDeviceInfoSet, pDeviceInfoData, &pa= rams.ClassInstallHeader, + sizeof(SP_PROPCHANGE_PARAMS))) { DWORD dwResult =3D GetLastError(); msg(M_NONFATAL | M_ERRNO, "%s: SetupDiSetClassInstallParams failed= ", __FUNCTION__); @@ -319,13 +303,11 @@ } /* Call appropriate class installer. */ - if (!SetupDiCallClassInstaller( - DIF_PROPERTYCHANGE, - hDeviceInfoSet, - pDeviceInfoData)) + if (!SetupDiCallClassInstaller(DIF_PROPERTYCHANGE, hDeviceInfoSet, pDe= viceInfoData)) { DWORD dwResult =3D GetLastError(); - msg(M_NONFATAL | M_ERRNO, "%s: SetupDiCallClassInstaller(DIF_PROPE= RTYCHANGE) failed", __FUNCTION__); + msg(M_NONFATAL | M_ERRNO, "%s: SetupDiCallClassInstaller(DIF_PROPE= RTYCHANGE) failed", + __FUNCTION__); return dwResult; } =20 @@ -352,10 +334,8 @@ * @return ERROR_SUCCESS on success; Win32 error code otherwise **/ static DWORD -enable_device( - _In_ HDEVINFO hDeviceInfoSet, - _In_ PSP_DEVINFO_DATA pDeviceInfoData, - _Inout_ LPBOOL pbRebootRequired) +enable_device(_In_ HDEVINFO hDeviceInfoSet, _In_ PSP_DEVINFO_DATA pDeviceI= nfoData, + _Inout_ LPBOOL pbRebootRequired) { return change_device_state(hDeviceInfoSet, pDeviceInfoData, TRUE, pbRe= bootRequired); } @@ -378,10 +358,8 @@ * @return ERROR_SUCCESS on success; Win32 error code otherwise **/ static DWORD -disable_device( - _In_ HDEVINFO hDeviceInfoSet, - _In_ PSP_DEVINFO_DATA pDeviceInfoData, - _Inout_ LPBOOL pbRebootRequired) +disable_device(_In_ HDEVINFO hDeviceInfoSet, _In_ PSP_DEVINFO_DATA pDevice= InfoData, + _Inout_ LPBOOL pbRebootRequired) { return change_device_state(hDeviceInfoSet, pDeviceInfoData, FALSE, pbR= ebootRequired); } @@ -402,10 +380,7 @@ * @return ERROR_SUCCESS on success; Win32 error code otherwise */ static DWORD -get_reg_string( - _In_ HKEY hKey, - _In_ LPCWSTR szName, - _Out_ LPWSTR *pszValue) +get_reg_string(_In_ HKEY hKey, _In_ LPCWSTR szName, _Out_ LPWSTR *pszValue) { if (pszValue =3D=3D NULL) { @@ -413,17 +388,13 @@ } DWORD dwValueType =3D REG_NONE, dwSize =3D 0; - DWORD dwResult =3D RegQueryValueEx( - hKey, - szName, - NULL, - &dwValueType, - NULL, - &dwSize); + DWORD dwResult =3D RegQueryValueEx(hKey, szName, NULL, &dwValueType, N= ULL, &dwSize); if (dwResult !=3D ERROR_SUCCESS) { - SetLastError(dwResult); /* MSDN does not mention RegQueryValueEx()= to set GetLastError(). But we do have an error code. Set last error manual= ly. */ - msg(M_NONFATAL | M_ERRNO, "%s: enumerating \"%ls\" registry value = failed", __FUNCTION__, szName); + SetLastError(dwResult); /* MSDN does not mention RegQueryValueEx()= to set GetLastError(). + But we do have an error code. Set last = error manually. */ + msg(M_NONFATAL | M_ERRNO, "%s: enumerating \"%ls\" registry value = failed", __FUNCTION__, + szName); return dwResult; } @@ -440,17 +411,14 @@ return ERROR_OUTOFMEMORY; } - dwResult =3D RegQueryValueEx( - hKey, - szName, - NULL, - NULL, - (LPBYTE)szValue, - &dwSize); + dwResult =3D RegQueryValueEx(hKey, szName, NULL, NULL, (LPBYTE= )szValue, &dwSize); if (dwResult !=3D ERROR_SUCCESS) { - SetLastError(dwResult); /* MSDN does not mention RegQueryV= alueEx() to set GetLastError(). But we do have an error code. Set last erro= r manually. */ - msg(M_NONFATAL | M_ERRNO, "%s: reading \"%ls\" registry va= lue failed", __FUNCTION__, szName); + SetLastError( + dwResult); /* MSDN does not mention RegQueryValueEx() = to set GetLastError(). But + we do have an error code. Set last error= manually. */ + msg(M_NONFATAL | M_ERRNO, "%s: reading \"%ls\" registry va= lue failed", __FUNCTION__, + szName); free(szValue); return dwResult; } @@ -459,12 +427,12 @@ { /* Expand the environment strings. */ DWORD - dwSizeExp =3D dwSize * 2, - dwCountExp =3D + dwSizeExp =3D dwSize * 2, dwCountExp =3D #ifdef UNICODE - dwSizeExp / sizeof(WCHAR); + dwSizeExp / sizeof(WCHAR); #else - dwSizeExp / sizeof(WCHAR) - 1; /* Note: ANSI versi= on requires one extra char. */ + dwSizeExp / sizeof(WCHAR) + - 1; /* Note: ANSI version req= uires one extra char. */ #endif LPWSTR szValueExp =3D (LPWSTR)malloc(dwSizeExp); if (szValueExp =3D=3D NULL) @@ -474,13 +442,11 @@ return ERROR_OUTOFMEMORY; } - DWORD dwCountExpResult =3D ExpandEnvironmentStrings( - szValue, - szValueExp, dwCountExp - ); + DWORD dwCountExpResult =3D ExpandEnvironmentStrings(szValu= e, szValueExp, dwCountExp); if (dwCountExpResult =3D=3D 0) { - msg(M_NONFATAL | M_ERRNO, "%s: expanding \"%ls\" regis= try value failed", __FUNCTION__, szName); + msg(M_NONFATAL | M_ERRNO, "%s: expanding \"%ls\" regis= try value failed", + __FUNCTION__, szName); free(szValueExp); free(szValue); return dwResult; @@ -511,9 +477,7 @@ return ERROR_OUTOFMEMORY; } - dwCountExpResult =3D ExpandEnvironmentStrings( - szValue, - szValueExp, dwCountExp); + dwCountExpResult =3D ExpandEnvironmentStrings(szValue,= szValueExp, dwCountExp); free(szValue); *pszValue =3D szValueExp; return ERROR_SUCCESS; @@ -527,7 +491,8 @@ } default: - msg(M_NONFATAL, "%s: \"%ls\" registry value is not string (typ= e %u)", __FUNCTION__, dwValueType); + msg(M_NONFATAL, "%s: \"%ls\" registry value is not string (typ= e %u)", __FUNCTION__, + dwValueType); return ERROR_UNSUPPORTED_TYPE; } } @@ -552,11 +517,8 @@ * @return ERROR_SUCCESS on success; Win32 error code otherwise **/ static DWORD -get_net_adapter_guid( - _In_ HDEVINFO hDeviceInfoSet, - _In_ PSP_DEVINFO_DATA pDeviceInfoData, - _In_ int iNumAttempts, - _Out_ LPGUID pguidAdapter) +get_net_adapter_guid(_In_ HDEVINFO hDeviceInfoSet, _In_ PSP_DEVINFO_DATA p= DeviceInfoData, + _In_ int iNumAttempts, _Out_ LPGUID pguidAdapter) { DWORD dwResult =3D ERROR_BAD_ARGUMENTS; @@ -566,13 +528,8 @@ } /* Open HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Class\\ registry key. */ - HKEY hKey =3D SetupDiOpenDevRegKey( - hDeviceInfoSet, - pDeviceInfoData, - DICS_FLAG_GLOBAL, - 0, - DIREG_DRV, - KEY_READ); + HKEY hKey =3D SetupDiOpenDevRegKey(hDeviceInfoSet, pDeviceInfoData, DI= CS_FLAG_GLOBAL, 0, + DIREG_DRV, KEY_READ); if (hKey =3D=3D INVALID_HANDLE_VALUE) { dwResult =3D GetLastError(); @@ -582,7 +539,8 @@ while (iNumAttempts > 0) { - /* Query the NetCfgInstanceId value. Using get_reg_string() right = on might clutter the output with error messages while the registry is still= being populated. */ + /* Query the NetCfgInstanceId value. Using get_reg_string() right = on might clutter the + * output with error messages while the registry is still being po= pulated. */ LPWSTR szCfgGuidString =3D NULL; dwResult =3D RegQueryValueEx(hKey, L"NetCfgInstanceId", NULL, NULL= , NULL, NULL); if (dwResult !=3D ERROR_SUCCESS) @@ -594,22 +552,24 @@ continue; } - SetLastError(dwResult); /* MSDN does not mention RegQueryValue= Ex() to set GetLastError(). But we do have an error code. Set last error ma= nually. */ - msg(M_NONFATAL | M_ERRNO, "%s: querying \"NetCfgInstanceId\" r= egistry value failed", __FUNCTION__); + SetLastError( + dwResult); /* MSDN does not mention RegQueryValueEx() to s= et GetLastError(). But we + do have an error code. Set last error manual= ly. */ + msg(M_NONFATAL | M_ERRNO, "%s: querying \"NetCfgInstanceId\" r= egistry value failed", + __FUNCTION__); break; } /* Read the NetCfgInstanceId value now. */ - dwResult =3D get_reg_string( - hKey, - L"NetCfgInstanceId", - &szCfgGuidString); + dwResult =3D get_reg_string(hKey, L"NetCfgInstanceId", &szCfgGuidS= tring); if (dwResult !=3D ERROR_SUCCESS) { break; } - dwResult =3D SUCCEEDED(CLSIDFromString(szCfgGuidString, (LPCLSID)p= guidAdapter)) ? ERROR_SUCCESS : ERROR_INVALID_DATA; + dwResult =3D SUCCEEDED(CLSIDFromString(szCfgGuidString, (LPCLSID)p= guidAdapter)) + ? ERROR_SUCCESS + : ERROR_INVALID_DATA; free(szCfgGuidString); break; } @@ -641,12 +601,9 @@ * @return ERROR_SUCCESS on success; Win32 error code otherwise **/ static DWORD -get_device_reg_property( - _In_ HDEVINFO hDeviceInfoSet, - _In_ PSP_DEVINFO_DATA pDeviceInfoData, - _In_ DWORD dwProperty, - _Out_opt_ LPDWORD pdwPropertyRegDataType, - _Out_ LPVOID *ppData) +get_device_reg_property(_In_ HDEVINFO hDeviceInfoSet, _In_ PSP_DEVINFO_DAT= A pDeviceInfoData, + _In_ DWORD dwProperty, _Out_opt_ LPDWORD pdwProper= tyRegDataType, + _Out_ LPVOID *ppData) { DWORD dwResult =3D ERROR_BAD_ARGUMENTS; @@ -658,14 +615,9 @@ /* Try with stack buffer first. */ BYTE bBufStack[128]; DWORD dwRequiredSize =3D 0; - if (SetupDiGetDeviceRegistryProperty( - hDeviceInfoSet, - pDeviceInfoData, - dwProperty, - pdwPropertyRegDataType, - bBufStack, - sizeof(bBufStack), - &dwRequiredSize)) + if (SetupDiGetDeviceRegistryProperty(hDeviceInfoSet, pDeviceInfoData, = dwProperty, + pdwPropertyRegDataType, bBufStack= , sizeof(bBufStack), + &dwRequiredSize)) { /* Copy from stack. */ *ppData =3D malloc(dwRequiredSize); @@ -691,27 +643,24 @@ return ERROR_OUTOFMEMORY; } - if (SetupDiGetDeviceRegistryProperty( - hDeviceInfoSet, - pDeviceInfoData, - dwProperty, - pdwPropertyRegDataType, - *ppData, - dwRequiredSize, - &dwRequiredSize)) + if (SetupDiGetDeviceRegistryProperty(hDeviceInfoSet, pDeviceIn= foData, dwProperty, + pdwPropertyRegDataType, *= ppData, dwRequiredSize, + &dwRequiredSize)) { return ERROR_SUCCESS; } else { dwResult =3D GetLastError(); - msg(M_NONFATAL | M_ERRNO, "%s: SetupDiGetDeviceRegistryPro= perty(%u) failed", __FUNCTION__, dwProperty); + msg(M_NONFATAL | M_ERRNO, "%s: SetupDiGetDeviceRegistryPro= perty(%u) failed", + __FUNCTION__, dwProperty); return dwResult; } } else { - msg(M_NONFATAL | M_ERRNO, "%s: SetupDiGetDeviceRegistryPropert= y(%u) failed", __FUNCTION__, dwProperty); + msg(M_NONFATAL | M_ERRNO, "%s: SetupDiGetDeviceRegistryPropert= y(%u) failed", + __FUNCTION__, dwProperty); return dwResult; } } @@ -719,19 +668,13 @@ DWORD -tap_create_adapter( - _In_opt_ HWND hwndParent, - _In_opt_ LPCWSTR szDeviceDescription, - _In_ LPCWSTR szHwId, - _Inout_ LPBOOL pbRebootRequired, - _Out_ LPGUID pguidAdapter) +tap_create_adapter(_In_opt_ HWND hwndParent, _In_opt_ LPCWSTR szDeviceDesc= ription, + _In_ LPCWSTR szHwId, _Inout_ LPBOOL pbRebootRequired, _= Out_ LPGUID pguidAdapter) { DWORD dwResult; HMODULE libnewdev =3D NULL; - if (szHwId =3D=3D NULL - || pbRebootRequired =3D=3D NULL - || pguidAdapter =3D=3D NULL) + if (szHwId =3D=3D NULL || pbRebootRequired =3D=3D NULL || pguidAdapter= =3D=3D NULL) { return ERROR_BAD_ARGUMENTS; } @@ -747,11 +690,7 @@ /* Get the device class name from GUID. */ WCHAR szClassName[MAX_CLASS_NAME_LEN]; - if (!SetupDiClassNameFromGuid( - &GUID_DEVCLASS_NET, - szClassName, - _countof(szClassName), - NULL)) + if (!SetupDiClassNameFromGuid(&GUID_DEVCLASS_NET, szClassName, _counto= f(szClassName), NULL)) { dwResult =3D GetLastError(); msg(M_NONFATAL, "%s: SetupDiClassNameFromGuid failed", __FUNCTION_= _); @@ -760,14 +699,8 @@ /* Create a new device info element and add it to the device info set.= */ SP_DEVINFO_DATA devinfo_data =3D { .cbSize =3D sizeof(SP_DEVINFO_DATA)= }; - if (!SetupDiCreateDeviceInfo( - hDevInfoList, - szClassName, - &GUID_DEVCLASS_NET, - szDeviceDescription, - hwndParent, - DICD_GENERATE_ID, - &devinfo_data)) + if (!SetupDiCreateDeviceInfo(hDevInfoList, szClassName, &GUID_DEVCLASS= _NET, szDeviceDescription, + hwndParent, DICD_GENERATE_ID, &devinfo_da= ta)) { dwResult =3D GetLastError(); msg(M_NONFATAL, "%s: SetupDiCreateDeviceInfo failed", __FUNCTION__= ); @@ -775,9 +708,7 @@ } /* Set a device information element as the selected member of a device= information set. */ - if (!SetupDiSetSelectedDevice( - hDevInfoList, - &devinfo_data)) + if (!SetupDiSetSelectedDevice(hDevInfoList, &devinfo_data)) { dwResult =3D GetLastError(); msg(M_NONFATAL, "%s: SetupDiSetSelectedDevice failed", __FUNCTION_= _); @@ -785,11 +716,9 @@ } /* Set Plug&Play device hardware ID property. */ - if (!SetupDiSetDeviceRegistryProperty( - hDevInfoList, - &devinfo_data, - SPDRP_HARDWAREID, - (const BYTE *)szHwId, (DWORD)((wcslen(szHwId) + 1) * sizeof(WC= HAR)))) + if (!SetupDiSetDeviceRegistryProperty(hDevInfoList, &devinfo_data, SPD= RP_HARDWAREID, + (const BYTE *)szHwId, + (DWORD)((wcslen(szHwId) + 1) * s= izeof(WCHAR)))) { dwResult =3D GetLastError(); msg(M_NONFATAL, "%s: SetupDiSetDeviceRegistryProperty failed", __F= UNCTION__); @@ -797,10 +726,7 @@ } /* Register the device instance with the PnP Manager */ - if (!SetupDiCallClassInstaller( - DIF_REGISTERDEVICE, - hDevInfoList, - &devinfo_data)) + if (!SetupDiCallClassInstaller(DIF_REGISTERDEVICE, hDevInfoList, &devi= nfo_data)) { dwResult =3D GetLastError(); msg(M_NONFATAL, "%s: SetupDiCallClassInstaller(DIF_REGISTERDEVICE)= failed", __FUNCTION__); @@ -816,10 +742,9 @@ if (!DiInstallDevice(hwndParent, hDevInfoList, &devinfo_data, NULL, 0,= pbRebootRequired)) #else /* mingw does not resolve DiInstallDevice, so load it at run time. */ - typedef BOOL (WINAPI *DiInstallDeviceFn)(HWND, HDEVINFO, SP_DEVINFO_DA= TA *, - SP_DRVINFO_DATA *, DWORD, BOO= L *); - DiInstallDeviceFn installfn - =3D find_function(L"newdev.dll", "DiInstallDevice", &libnewdev); + typedef BOOL(WINAPI * DiInstallDeviceFn)(HWND, HDEVINFO, SP_DEVINFO_DA= TA *, SP_DRVINFO_DATA *, + DWORD, BOOL *); + DiInstallDeviceFn installfn =3D find_function(L"newdev.dll", "DiInstal= lDevice", &libnewdev); if (!installfn) { @@ -855,24 +780,20 @@ }; /* Set class installer parameters for DIF_REMOVE. */ - if (SetupDiSetClassInstallParams( - hDevInfoList, - &devinfo_data, - &removedevice_params.ClassInstallHeader, - sizeof(SP_REMOVEDEVICE_PARAMS))) + if (SetupDiSetClassInstallParams(hDevInfoList, &devinfo_data, + &removedevice_params.ClassInstall= Header, + sizeof(SP_REMOVEDEVICE_PARAMS))) { /* Call appropriate class installer. */ - if (SetupDiCallClassInstaller( - DIF_REMOVE, - hDevInfoList, - &devinfo_data)) + if (SetupDiCallClassInstaller(DIF_REMOVE, hDevInfoList, &devin= fo_data)) { /* Check if a system reboot is required. */ check_reboot(hDevInfoList, &devinfo_data, pbRebootRequired= ); } else { - msg(M_NONFATAL | M_ERRNO, "%s: SetupDiCallClassInstaller(D= IF_REMOVE) failed", __FUNCTION__); + msg(M_NONFATAL | M_ERRNO, "%s: SetupDiCallClassInstaller(D= IF_REMOVE) failed", + __FUNCTION__); } } else @@ -912,11 +833,8 @@ * @return ERROR_SUCCESS on success; Win32 error code otherwise **/ static DWORD -execute_on_first_adapter( - _In_opt_ HWND hwndParent, - _In_ LPCGUID pguidAdapter, - _In_ devop_func_t funcOperation, - _Inout_ LPBOOL pbRebootRequired) +execute_on_first_adapter(_In_opt_ HWND hwndParent, _In_ LPCGUID pguidAdapt= er, + _In_ devop_func_t funcOperation, _Inout_ LPBOOL p= bRebootRequired) { DWORD dwResult; @@ -926,14 +844,8 @@ } /* Create a list of network devices. */ - HDEVINFO hDevInfoList =3D SetupDiGetClassDevsEx( - &GUID_DEVCLASS_NET, - NULL, - hwndParent, - DIGCF_PRESENT, - NULL, - NULL, - NULL); + HDEVINFO hDevInfoList =3D SetupDiGetClassDevsEx(&GUID_DEVCLASS_NET, NU= LL, hwndParent, + DIGCF_PRESENT, NULL, NUL= L, NULL); if (hDevInfoList =3D=3D INVALID_HANDLE_VALUE) { dwResult =3D GetLastError(); @@ -942,7 +854,8 @@ } /* Retrieve information associated with a device information set. */ - SP_DEVINFO_LIST_DETAIL_DATA devinfo_list_detail_data =3D { .cbSize =3D= sizeof(SP_DEVINFO_LIST_DETAIL_DATA) }; + SP_DEVINFO_LIST_DETAIL_DATA devinfo_list_detail_data =3D { .cbSize =3D= sizeof( + SP_DEVINF= O_LIST_DETAIL_DATA) }; if (!SetupDiGetDeviceInfoListDetail(hDevInfoList, &devinfo_list_detail= _data)) { dwResult =3D GetLastError(); @@ -955,10 +868,7 @@ { /* Get the device from the list. */ SP_DEVINFO_DATA devinfo_data =3D { .cbSize =3D sizeof(SP_DEVINFO_D= ATA) }; - if (!SetupDiEnumDeviceInfo( - hDevInfoList, - dwIndex, - &devinfo_data)) + if (!SetupDiEnumDeviceInfo(hDevInfoList, dwIndex, &devinfo_data)) { if (GetLastError() =3D=3D ERROR_NO_MORE_ITEMS) { @@ -972,7 +882,8 @@ else { /* Something is wrong with this device. Skip it. */ - msg(M_WARN | M_ERRNO, "%s: SetupDiEnumDeviceInfo(%u) faile= d", __FUNCTION__, dwIndex); + msg(M_WARN | M_ERRNO, "%s: SetupDiEnumDeviceInfo(%u) faile= d", __FUNCTION__, + dwIndex); continue; } } @@ -1001,23 +912,19 @@ DWORD -tap_delete_adapter( - _In_opt_ HWND hwndParent, - _In_ LPCGUID pguidAdapter, - _Inout_ LPBOOL pbRebootRequired) +tap_delete_adapter(_In_opt_ HWND hwndParent, _In_ LPCGUID pguidAdapter, + _Inout_ LPBOOL pbRebootRequired) { return execute_on_first_adapter(hwndParent, pguidAdapter, delete_devic= e, pbRebootRequired); } DWORD -tap_enable_adapter( - _In_opt_ HWND hwndParent, - _In_ LPCGUID pguidAdapter, - _In_ BOOL bEnable, - _Inout_ LPBOOL pbRebootRequired) +tap_enable_adapter(_In_opt_ HWND hwndParent, _In_ LPCGUID pguidAdapter, _I= n_ BOOL bEnable, + _Inout_ LPBOOL pbRebootRequired) { - return execute_on_first_adapter(hwndParent, pguidAdapter, bEnable ? en= able_device : disable_device, pbRebootRequired); + return execute_on_first_adapter(hwndParent, pguidAdapter, + bEnable ? enable_device : disable_devi= ce, pbRebootRequired); } /* stripped version of ExecCommand in interactive.c */ @@ -1037,8 +944,8 @@ /* CreateProcess needs a modifiable cmdline: make a copy */ cmdline_dup =3D _wcsdup(cmdline); - if (cmdline_dup && CreateProcessW(NULL, cmdline_dup, NULL, NULL, FALSE, - proc_flags, NULL, NULL, &si, &pi)) + if (cmdline_dup + && CreateProcessW(NULL, cmdline_dup, NULL, NULL, FALSE, proc_flags= , NULL, NULL, &si, &pi)) { WaitForSingleObject(pi.hProcess, INFINITE); if (!GetExitCodeProcess(pi.hProcess, &exit_code)) @@ -1059,10 +966,7 @@ } DWORD -tap_set_adapter_name( - _In_ LPCGUID pguidAdapter, - _In_ LPCWSTR szName, - _In_ BOOL bSilent) +tap_set_adapter_name(_In_ LPCGUID pguidAdapter, _In_ LPCWSTR szName, _In_ = BOOL bSilent) { DWORD dwResult; int msg_flag =3D bSilent ? M_WARN : M_NONFATAL; @@ -1083,23 +987,16 @@ /* Render registry key path. */ WCHAR szRegKey[ADAPTER_REGKEY_PATH_MAX]; - swprintf_s( - szRegKey, _countof(szRegKey), - szAdapterRegKeyPathTemplate, - szDevClassNetId, - szAdapterId); + swprintf_s(szRegKey, _countof(szRegKey), szAdapterRegKeyPathTemplate, = szDevClassNetId, + szAdapterId); /* Open network adapter registry key. */ HKEY hKey =3D NULL; - dwResult =3D RegOpenKeyEx( - HKEY_LOCAL_MACHINE, - szRegKey, - 0, - KEY_QUERY_VALUE, - &hKey); + dwResult =3D RegOpenKeyEx(HKEY_LOCAL_MACHINE, szRegKey, 0, KEY_QUERY_V= ALUE, &hKey); if (dwResult !=3D ERROR_SUCCESS) { - SetLastError(dwResult); /* MSDN does not mention RegOpenKeyEx() to= set GetLastError(). But we do have an error code. Set last error manually.= */ + SetLastError(dwResult); /* MSDN does not mention RegOpenKeyEx() to= set GetLastError(). But + we do have an error code. Set last erro= r manually. */ msg(msg_flag, "%s: RegOpenKeyEx(HKLM, \"%ls\") failed", __FUNCTION= __, szRegKey); goto cleanup_szAdapterId; } @@ -1142,10 +1039,8 @@ DWORD -tap_list_adapters( - _In_opt_ HWND hwndParent, - _In_opt_ LPCWSTR szzHwIDs, - _Out_ struct tap_adapter_node **ppAdapter) +tap_list_adapters(_In_opt_ HWND hwndParent, _In_opt_ LPCWSTR szzHwIDs, + _Out_ struct tap_adapter_node **ppAdapter) { DWORD dwResult; @@ -1155,14 +1050,8 @@ } /* Create a list of network devices. */ - HDEVINFO hDevInfoList =3D SetupDiGetClassDevsEx( - &GUID_DEVCLASS_NET, - NULL, - hwndParent, - DIGCF_PRESENT, - NULL, - NULL, - NULL); + HDEVINFO hDevInfoList =3D SetupDiGetClassDevsEx(&GUID_DEVCLASS_NET, NU= LL, hwndParent, + DIGCF_PRESENT, NULL, NUL= L, NULL); if (hDevInfoList =3D=3D INVALID_HANDLE_VALUE) { dwResult =3D GetLastError(); @@ -1171,7 +1060,8 @@ } /* Retrieve information associated with a device information set. */ - SP_DEVINFO_LIST_DETAIL_DATA devinfo_list_detail_data =3D { .cbSize =3D= sizeof(SP_DEVINFO_LIST_DETAIL_DATA) }; + SP_DEVINFO_LIST_DETAIL_DATA devinfo_list_detail_data =3D { .cbSize =3D= sizeof( + SP_DEVINF= O_LIST_DETAIL_DATA) }; if (!SetupDiGetDeviceInfoListDetail(hDevInfoList, &devinfo_list_detail= _data)) { dwResult =3D GetLastError(); @@ -1190,10 +1080,7 @@ { /* Get the device from the list. */ SP_DEVINFO_DATA devinfo_data =3D { .cbSize =3D sizeof(SP_DEVINFO_D= ATA) }; - if (!SetupDiEnumDeviceInfo( - hDevInfoList, - dwIndex, - &devinfo_data)) + if (!SetupDiEnumDeviceInfo(hDevInfoList, dwIndex, &devinfo_data)) { if (GetLastError() =3D=3D ERROR_NO_MORE_ITEMS) { @@ -1202,7 +1089,8 @@ else { /* Something is wrong with this device. Skip it. */ - msg(M_WARN | M_ERRNO, "%s: SetupDiEnumDeviceInfo(%u) faile= d", __FUNCTION__, dwIndex); + msg(M_WARN | M_ERRNO, "%s: SetupDiEnumDeviceInfo(%u) faile= d", __FUNCTION__, + dwIndex); continue; } } @@ -1210,12 +1098,8 @@ /* Get device hardware ID(s). */ DWORD dwDataType =3D REG_NONE; LPWSTR szzDeviceHardwareIDs =3D NULL; - dwResult =3D get_device_reg_property( - hDevInfoList, - &devinfo_data, - SPDRP_HARDWAREID, - &dwDataType, - (LPVOID)&szzDeviceHardwareIDs); + dwResult =3D get_device_reg_property(hDevInfoList, &devinfo_data, = SPDRP_HARDWAREID, + &dwDataType, (LPVOID)&szzDevice= HardwareIDs); if (dwResult !=3D ERROR_SUCCESS) { /* Something is wrong with this device. Skip it. */ @@ -1271,48 +1155,42 @@ /* Render registry key path. */ WCHAR szRegKey[ADAPTER_REGKEY_PATH_MAX]; - swprintf_s( - szRegKey, _countof(szRegKey), - szAdapterRegKeyPathTemplate, - szDevClassNetId, - szAdapterId); + swprintf_s(szRegKey, _countof(szRegKey), szAdapterRegKeyPathTempla= te, szDevClassNetId, + szAdapterId); /* Open network adapter registry key. */ HKEY hKey =3D NULL; - dwResult =3D RegOpenKeyEx( - HKEY_LOCAL_MACHINE, - szRegKey, - 0, - KEY_READ, - &hKey); + dwResult =3D RegOpenKeyEx(HKEY_LOCAL_MACHINE, szRegKey, 0, KEY_REA= D, &hKey); if (dwResult !=3D ERROR_SUCCESS) { - SetLastError(dwResult); /* MSDN does not mention RegOpenKeyEx(= ) to set GetLastError(). But we do have an error code. Set last error manua= lly. */ + SetLastError(dwResult); /* MSDN does not mention RegOpenKeyEx(= ) to set GetLastError(). + But we do have an error code. Set l= ast error manually. */ msg(M_WARN | M_ERRNO, "%s: RegOpenKeyEx(HKLM, \"%ls\") failed"= , __FUNCTION__, szRegKey); goto cleanup_szAdapterId; } /* Read adapter name. */ LPWSTR szName =3D NULL; - dwResult =3D get_reg_string( - hKey, - L"Name", - &szName); + dwResult =3D get_reg_string(hKey, L"Name", &szName); if (dwResult !=3D ERROR_SUCCESS) { SetLastError(dwResult); - msg(M_WARN | M_ERRNO, "%s: Cannot determine %ls adapter name",= __FUNCTION__, szAdapterId); + msg(M_WARN | M_ERRNO, "%s: Cannot determine %ls adapter name",= __FUNCTION__, + szAdapterId); goto cleanup_hKey; } /* Append to the list. */ size_t hwid_size =3D (wcszlen(szzDeviceHardwareIDs) + 1) * sizeof(= WCHAR); size_t name_size =3D (wcslen(szName) + 1) * sizeof(WCHAR); - struct tap_adapter_node *node =3D (struct tap_adapter_node *)mallo= c(sizeof(struct tap_adapter_node) + hwid_size + name_size); + struct tap_adapter_node *node =3D (struct tap_adapter_node *)mallo= c( + sizeof(struct tap_adapter_node) + hwid_size + name_size); if (node =3D=3D NULL) { - msg(M_FATAL, "%s: malloc(%u) failed", __FUNCTION__, sizeof(str= uct tap_adapter_node) + hwid_size + name_size); - dwResult =3D ERROR_OUTOFMEMORY; goto cleanup_szName; + msg(M_FATAL, "%s: malloc(%u) failed", __FUNCTION__, + sizeof(struct tap_adapter_node) + hwid_size + name_size); + dwResult =3D ERROR_OUTOFMEMORY; + goto cleanup_szName; } memcpy(&node->guid, &guidAdapter, sizeof(GUID)); @@ -1351,8 +1229,7 @@ void -tap_free_adapter_list( - _In_ struct tap_adapter_node *pAdapterList) +tap_free_adapter_list(_In_ struct tap_adapter_node *pAdapterList) { /* Iterate over all nodes of the list. */ while (pAdapterList) diff --git a/src/tapctl/tap.h b/src/tapctl/tap.h index a0b0561..ee5fb09 100644 --- a/src/tapctl/tap.h +++ b/src/tapctl/tap.h @@ -49,12 +49,8 @@ * @return ERROR_SUCCESS on success; Win32 error code otherwise **/ DWORD -tap_create_adapter( - _In_opt_ HWND hwndParent, - _In_opt_ LPCWSTR szDeviceDescription, - _In_ LPCWSTR szHwId, - _Inout_ LPBOOL pbRebootRequired, - _Out_ LPGUID pguidAdapter); +tap_create_adapter(_In_opt_ HWND hwndParent, _In_opt_ LPCWSTR szDeviceDesc= ription, + _In_ LPCWSTR szHwId, _Inout_ LPBOOL pbRebootRequired, _= Out_ LPGUID pguidAdapter); /** @@ -76,10 +72,8 @@ * @return ERROR_SUCCESS on success; Win32 error code otherwise **/ DWORD -tap_delete_adapter( - _In_opt_ HWND hwndParent, - _In_ LPCGUID pguidAdapter, - _Inout_ LPBOOL pbRebootRequired); +tap_delete_adapter(_In_opt_ HWND hwndParent, _In_ LPCGUID pguidAdapter, + _Inout_ LPBOOL pbRebootRequired); /** @@ -103,11 +97,8 @@ * @return ERROR_SUCCESS on success; Win32 error code otherwise **/ DWORD -tap_enable_adapter( - _In_opt_ HWND hwndParent, - _In_ LPCGUID pguidAdapter, - _In_ BOOL bEnable, - _Inout_ LPBOOL pbRebootRequired); +tap_enable_adapter(_In_opt_ HWND hwndParent, _In_ LPCGUID pguidAdapter, _I= n_ BOOL bEnable, + _Inout_ LPBOOL pbRebootRequired); /** @@ -123,10 +114,7 @@ * @return ERROR_SUCCESS on success; Win32 error code otherwise **/ DWORD -tap_set_adapter_name( - _In_ LPCGUID pguidAdapter, - _In_ LPCWSTR szName, - _In_ BOOL bSilent); +tap_set_adapter_name(_In_ LPCGUID pguidAdapter, _In_ LPCWSTR szName, _In_ = BOOL bSilent); /** @@ -134,9 +122,9 @@ */ struct tap_adapter_node { - GUID guid; /**< Adapter GUID */ - LPWSTR szzHardwareIDs; /**< Device hardware ID(s) */ - LPWSTR szName; /**< Adapter name */ + GUID guid; /**< Adapter GUID */ + LPWSTR szzHardwareIDs; /**< Device hardware ID(s) */ + LPWSTR szName; /**< Adapter name */ struct tap_adapter_node *pNext; /**< Pointer to next adapter */ }; @@ -162,10 +150,8 @@ * @return ERROR_SUCCESS on success; Win32 error code otherwise */ DWORD -tap_list_adapters( - _In_opt_ HWND hwndParent, - _In_opt_ LPCWSTR szzHwIDs, - _Out_ struct tap_adapter_node **ppAdapterList); +tap_list_adapters(_In_opt_ HWND hwndParent, _In_opt_ LPCWSTR szzHwIDs, + _Out_ struct tap_adapter_node **ppAdapterList); /** @@ -173,8 +159,6 @@ * * @param pAdapterList A pointer to the first adapter in the list to free. */ -void -tap_free_adapter_list( - _In_ struct tap_adapter_node *pAdapterList); +void tap_free_adapter_list(_In_ struct tap_adapter_node *pAdapterList); #endif /* ifndef TAP_H */ diff --git a/tests/ntlm_support.c b/tests/ntlm_support.c index 3960cc5..7007051 100644 --- a/tests/ntlm_support.c +++ b/tests/ntlm_support.c @@ -49,7 +49,7 @@ crypto_unload_provider("legacy", legacy); crypto_unload_provider("default", def); #endif -#else /* ifdef NTLM */ +#else /* ifdef NTLM */ msg(M_FATAL, "NTLM support not compiled in"); #endif } diff --git a/tests/unit_tests/example_test/test.c b/tests/unit_tests/exampl= e_test/test.c index c174025..139e06f 100644 --- a/tests/unit_tests/example_test/test.c +++ b/tests/unit_tests/example_test/test.c @@ -10,7 +10,7 @@ static int setup(void **state) { - int *answer =3D malloc(sizeof(int)); + int *answer =3D malloc(sizeof(int)); *answer =3D 42; *state =3D answer; @@ -29,7 +29,7 @@ static void null_test_success(void **state) { - (void) state; + (void)state; } static void @@ -39,8 +39,7 @@ assert_int_equal(*answer, 42); } -__attribute__((unused)) -static void +__attribute__((unused)) static void failing_test(void **state) { /* This tests fails to test that make check fails */ @@ -53,7 +52,7 @@ const struct CMUnitTest tests[] =3D { cmocka_unit_test(null_test_success), cmocka_unit_test_setup_teardown(int_test_success, setup, teardown), -/* cmocka_unit_test(failing_test), */ + /* cmocka_unit_test(failing_test), */ }; return cmocka_run_group_tests_name("success_test", tests, NULL, NULL); diff --git a/tests/unit_tests/example_test/test2.c b/tests/unit_tests/examp= le_test/test2.c index bb54633..3089432 100644 --- a/tests/unit_tests/example_test/test2.c +++ b/tests/unit_tests/example_test/test2.c @@ -11,7 +11,7 @@ static void test_true(void **state) { - (void) state; + (void)state; } diff --git a/tests/unit_tests/openvpn/cert_data.h b/tests/unit_tests/openvp= n/cert_data.h index 638af39..9e2974a 100644 --- a/tests/unit_tests/openvpn/cert_data.h +++ b/tests/unit_tests/openvpn/cert_data.h @@ -52,12 +52,11 @@ "srXMaPe0lAea4etMSZsjIRPwGRMXBrwbRmb6iN2Cq40867HdaJoAryYig7IiDwSX\n" "htCbOA6sX+60+FEOYDEx5cmkogl633Pw7LJ3ICkyzIrUSEt6BOT1Gsc1eQ=3D=3D\n" "-----END CERTIFICATE-----\n"; -static const char *const key1 =3D - "-----BEGIN PRIVATE KEY-----\n" - "MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQg5Xpw/lLvBrWjAWDq\n" - "L6dm/4a1or6AQ6O3yXYgw78B23ihRANCAAR4SRvnSuGdJmPitKbqcFbcgyzsMBlh\n" - "4wWOrty4I0ZlIXxY2qEnyb3YKz4OdMGzpK7FLfQZehHg6LGblcLs4EW7\n" - "-----END PRIVATE KEY-----\n"; +static const char *const key1 =3D "-----BEGIN PRIVATE KEY-----\n" + "MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wa= wIBAQQg5Xpw/lLvBrWjAWDq\n" + "L6dm/4a1or6AQ6O3yXYgw78B23ihRANCAAR4SRvnS= uGdJmPitKbqcFbcgyzsMBlh\n" + "4wWOrty4I0ZlIXxY2qEnyb3YKz4OdMGzpK7FLfQZe= hHg6LGblcLs4EW7\n" + "-----END PRIVATE KEY-----\n"; static const char *const hash1 =3D "A4B74F1D68AF50691F62CBD675E24C86553695= 67"; static const char *const cname1 =3D "ovpn-test-ec1"; @@ -104,35 +103,34 @@ "F6MgVGSxl6eylJgDYckvJiAbmcp2PD/LRQQOxQA0yqeAMg2cbdvclETuYD6zoFfu\n" "Y8aO7dvDlw=3D=3D\n" "-----END CERTIFICATE-----\n"; -static const char *const key3 =3D - "-----BEGIN PRIVATE KEY-----\n" - "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQC7xFoR6fmoyfsJ\n" - "IQDKKgbYgFw0MzVuDAmpRx6KTEihgTchkQx9fHddWbKiOUbcEnQi3LNux7P4QVl/\n" - "4dRR3skisBug6Vd5LXeBGZqmpu5XZiF4DgLz1lX21G0aOogFWkie2qGEcso40159\n" - "x9FBDl5A3sLP18ubeex0pd/BzDFv6SLOTyVWO/GCNc8IX/i0uN4mLvoVU00SeqwT\n" - "PnS+CRXrSq4JjGDJLsXl0/PlxkjsgU0yOOA0Z2d8Fzk3wClwP6Hc49BOMWKstUIh\n" - "LbG2DcIv8l29EuEj2w3ju/7gkewol96XQ2twpPvpoVAaiVh/m7hQUcQORQCD6eJc\n" - "DjOZVCArAgMBAAECggEACqkuWAAJ3cyCBVWrXs8eDmLTWV9i9DmYvtS75ixIn2rf\n" - "v3cl12YevN0f6FgKLuqZT3Vqdqq+DCVhuIIQ9QkKMH8BQpSdE9NCCsFyZ23o8Gtr\n" - "EQ7ymfecb+RFwYx7NpqWrvZI32VJGArgPZH/zorLTTGYrAZbmBtHEqRsXOuEDw97\n" - "slwwcWaa9ztaYC8/N/7fgsnydaCFSaOByRlWuyvSmHvn6ZwLv8ANOshY6fstC0Jb\n" - "BW0GpSe9eZPjpl71VT2RtpghqLV5+iAoFDHoT+eZvBospcUGtfcZSU7RrBjKB8+a\n" - "U1d6hwKhduVs2peIQzl+FiOSdWriLcsZv79q4sBhsQKBgQDUDVTf5BGJ8apOs/17\n" - "YVk+Ad8Ey8sXvsfk49psmlCRa8Z4g0LVXfrP94qzhtl8U5kE9hs3nEF4j/kX1ZWG\n" - "k11tdsNTZN5x5bbAgEgPA6Ap6J/uto0HS8G0vSv0lyBymdKA3p/i5Dx+8Nc9cGns\n" - "LGI9MvviLX7pQFIkvbaCkdKwYwKBgQDirowjWZnm7BgVhF0G1m3DY9nQTYYU185W\n" - "UESaO5/nVzwUrA+FypJamD+AvmlSuY8rJeQAGAS6nQr9G8/617r+GwJnzRtxC6Vl\n" - "4OF5BJRsD70oX4CFOOlycMoJ8tzcYVH7NI8KVocjxb+QW82hqSvEwSsvnwwn3eOW\n" - "nr5u5vIHmQKBgCuc3lL6Dl1ntdZgEIdau0cUjXDoFUo589TwxBDIID/4gaZxoMJP\n" - "hPFXAVDxMDPw4azyjSB/47tPKTUsuYcnMfT8kynIujOEwnSPLcLgxQU5kgM/ynuw\n" - "qhNpQOwaVRMc7f2RTCMXPBYDpNE/GJn5eu8JWGLpZovEreBeoHX0VffvAoGAVrWn\n" - "+3mxykhzaf+oyg3KDNysG+cbq+tlDVVE+K5oG0kePVYX1fjIBQmJ+QhdJ3y9jCbB\n" - "UVveqzeZVXqHEw/kgoD4aZZmsdZfnVnpRa5/y9o1ZDUr50n+2nzUe/u/ijlb77iK\n" - "Is04gnGJNoI3ZWhdyrSNfXjcYH+bKClu9OM4n7kCgYAorc3PAX7M0bsQrrqYxUS8\n" - "56UU0YdhAgYitjM7Fm/0iIm0vDpSevxL9js4HnnsSMVR77spCBAGOCCZrTcI3Ejg\n" - "xKDYzh1xlfMRjJBuBu5Pd55ZAv9NXFGpsX5SO8fDZQJMwpcbQH36+UdqRRFDpjJ0\n" - "ZbX6nKcJ7jciJVKJds59Jg=3D=3D\n" - "-----END PRIVATE KEY-----\n"; +static const char *const key3 =3D "-----BEGIN PRIVATE KEY-----\n" + "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiA= gEAAoIBAQC7xFoR6fmoyfsJ\n" + "IQDKKgbYgFw0MzVuDAmpRx6KTEihgTchkQx9fHddW= bKiOUbcEnQi3LNux7P4QVl/\n" + "4dRR3skisBug6Vd5LXeBGZqmpu5XZiF4DgLz1lX21= G0aOogFWkie2qGEcso40159\n" + "x9FBDl5A3sLP18ubeex0pd/BzDFv6SLOTyVWO/GCN= c8IX/i0uN4mLvoVU00SeqwT\n" + "PnS+CRXrSq4JjGDJLsXl0/PlxkjsgU0yOOA0Z2d8F= zk3wClwP6Hc49BOMWKstUIh\n" + "LbG2DcIv8l29EuEj2w3ju/7gkewol96XQ2twpPvpo= VAaiVh/m7hQUcQORQCD6eJc\n" + "DjOZVCArAgMBAAECggEACqkuWAAJ3cyCBVWrXs8eD= mLTWV9i9DmYvtS75ixIn2rf\n" + "v3cl12YevN0f6FgKLuqZT3Vqdqq+DCVhuIIQ9QkKM= H8BQpSdE9NCCsFyZ23o8Gtr\n" + "EQ7ymfecb+RFwYx7NpqWrvZI32VJGArgPZH/zorLT= TGYrAZbmBtHEqRsXOuEDw97\n" + "slwwcWaa9ztaYC8/N/7fgsnydaCFSaOByRlWuyvSm= Hvn6ZwLv8ANOshY6fstC0Jb\n" + "BW0GpSe9eZPjpl71VT2RtpghqLV5+iAoFDHoT+eZv= BospcUGtfcZSU7RrBjKB8+a\n" + "U1d6hwKhduVs2peIQzl+FiOSdWriLcsZv79q4sBhs= QKBgQDUDVTf5BGJ8apOs/17\n" + "YVk+Ad8Ey8sXvsfk49psmlCRa8Z4g0LVXfrP94qzh= tl8U5kE9hs3nEF4j/kX1ZWG\n" + "k11tdsNTZN5x5bbAgEgPA6Ap6J/uto0HS8G0vSv0l= yBymdKA3p/i5Dx+8Nc9cGns\n" + "LGI9MvviLX7pQFIkvbaCkdKwYwKBgQDirowjWZnm7= BgVhF0G1m3DY9nQTYYU185W\n" + "UESaO5/nVzwUrA+FypJamD+AvmlSuY8rJeQAGAS6n= Qr9G8/617r+GwJnzRtxC6Vl\n" + "4OF5BJRsD70oX4CFOOlycMoJ8tzcYVH7NI8KVocjx= b+QW82hqSvEwSsvnwwn3eOW\n" + "nr5u5vIHmQKBgCuc3lL6Dl1ntdZgEIdau0cUjXDoF= Uo589TwxBDIID/4gaZxoMJP\n" + "hPFXAVDxMDPw4azyjSB/47tPKTUsuYcnMfT8kynIu= jOEwnSPLcLgxQU5kgM/ynuw\n" + "qhNpQOwaVRMc7f2RTCMXPBYDpNE/GJn5eu8JWGLpZ= ovEreBeoHX0VffvAoGAVrWn\n" + "+3mxykhzaf+oyg3KDNysG+cbq+tlDVVE+K5oG0keP= VYX1fjIBQmJ+QhdJ3y9jCbB\n" + "UVveqzeZVXqHEw/kgoD4aZZmsdZfnVnpRa5/y9o1Z= DUr50n+2nzUe/u/ijlb77iK\n" + "Is04gnGJNoI3ZWhdyrSNfXjcYH+bKClu9OM4n7kCg= YAorc3PAX7M0bsQrrqYxUS8\n" + "56UU0YdhAgYitjM7Fm/0iIm0vDpSevxL9js4HnnsS= MVR77spCBAGOCCZrTcI3Ejg\n" + "xKDYzh1xlfMRjJBuBu5Pd55ZAv9NXFGpsX5SO8fDZ= QJMwpcbQH36+UdqRRFDpjJ0\n" + "ZbX6nKcJ7jciJVKJds59Jg=3D=3D\n" + "-----END PRIVATE KEY-----\n"; static const char *const hash3 =3D "2463628674E362578113F508BA05F29EF142E9= 79"; static const char *const cname3 =3D "ovpn-test-rsa1"; @@ -162,4 +160,4 @@ static const char *const hash4 =3D "E1401D4497C944783E3D62CDBD2A1F69F5E507= 1E"; #define cname4 cname3 /* same CN as that of cert3 */ -#endif /* CERT_DATA_H */ +#endif /* CERT_DATA_H */ diff --git a/tests/unit_tests/openvpn/mock_management.c b/tests/unit_tests/= openvpn/mock_management.c index 9674b45..b24e4c4 100644 --- a/tests/unit_tests/openvpn/mock_management.c +++ b/tests/unit_tests/openvpn/mock_management.c @@ -42,8 +42,7 @@ } char * -management_query_pk_sig(struct management *man, const char *b64_data, - const char *algorithm) +management_query_pk_sig(struct management *man, const char *b64_data, cons= t char *algorithm) { return NULL; } diff --git a/tests/unit_tests/openvpn/mock_msg.c b/tests/unit_tests/openvpn= /mock_msg.c index 5407561..603520b 100644 --- a/tests/unit_tests/openvpn/mock_msg.c +++ b/tests/unit_tests/openvpn/mock_msg.c @@ -71,8 +71,7 @@ } void -x_msg_va(const unsigned int flags, const char *format, - va_list arglist) +x_msg_va(const unsigned int flags, const char *format, va_list arglist) { if (flags & M_FATAL) { @@ -107,7 +106,7 @@ /* Keep compiler happy. Should not happen, mock_assert() does not ret= urn */ exit(1); } -#else /* ifndef NO_CMOCKA */ +#else /* ifndef NO_CMOCKA */ void assert_failed(const char *filename, int line, const char *condition) { diff --git a/tests/unit_tests/openvpn/mock_msg.h b/tests/unit_tests/openvpn= /mock_msg.h index 40d7609..f4ebc23 100644 --- a/tests/unit_tests/openvpn/mock_msg.h +++ b/tests/unit_tests/openvpn/mock_msg.h @@ -35,13 +35,10 @@ extern bool fatal_error_triggered; extern char mock_msg_buf[MOCK_MSG_BUF]; -void -mock_set_debug_level(int level); +void mock_set_debug_level(int level); -int -mock_get_debug_level(void); +int mock_get_debug_level(void); -void -mock_set_print_debug_level(int level); +void mock_set_print_debug_level(int level); #endif /* MOCK_MSG */ diff --git a/tests/unit_tests/openvpn/mock_ssl_dependencies.c b/tests/unit_= tests/openvpn/mock_ssl_dependencies.c index 2a562fc..7333c47 100644 --- a/tests/unit_tests/openvpn/mock_ssl_dependencies.c +++ b/tests/unit_tests/openvpn/mock_ssl_dependencies.c @@ -37,8 +37,8 @@ #include "ssl_verify.h" int -parse_line(const char *line, char **p, const int n, const char *file, - const int line_num, int msglevel, struct gc_arena *gc) +parse_line(const char *line, char **p, const int n, const char *file, cons= t int line_num, + int msglevel, struct gc_arena *gc) { /* Dummy function to get the linker happy, should never be called */ assert_true(false); diff --git a/tests/unit_tests/openvpn/pkey_test_utils.c b/tests/unit_tests/= openvpn/pkey_test_utils.c index 56608ea..c9aef46 100644 --- a/tests/unit_tests/openvpn/pkey_test_utils.c +++ b/tests/unit_tests/openvpn/pkey_test_utils.c @@ -56,14 +56,14 @@ size_t siglen =3D 0; int ret =3D 0; - OSSL_PARAM params[2] =3D {OSSL_PARAM_END}; + OSSL_PARAM params[2] =3D { OSSL_PARAM_END }; const char *mdname =3D "SHA256"; if (EVP_PKEY_get_id(privkey) =3D=3D EVP_PKEY_RSA) { const char *padmode =3D "pss"; /* RSA_PSS: for all other params, u= se defaults */ - params[0] =3D OSSL_PARAM_construct_utf8_string(OSSL_SIGNATURE_PARA= M_PAD_MODE, - (char *)padmode, 0); + params[0] =3D + OSSL_PARAM_construct_utf8_string(OSSL_SIGNATURE_PARAM_PAD_MODE= , (char *)padmode, 0); params[1] =3D OSSL_PARAM_construct_end(); } else if (EVP_PKEY_get_id(privkey) =3D=3D EVP_PKEY_EC) @@ -79,8 +79,7 @@ EVP_PKEY_CTX *pctx =3D NULL; EVP_MD_CTX *mctx =3D EVP_MD_CTX_new(); - if (!mctx - || EVP_DigestSignInit_ex(mctx, &pctx, mdname, tls_libctx, NULL, pr= ivkey, params) <=3D 0) + if (!mctx || EVP_DigestSignInit_ex(mctx, &pctx, mdname, tls_libctx, NU= LL, privkey, params) <=3D 0) { /* cmocka assert output for these kinds of failures is hardly expl= anatory, * print a message and assert in caller. */ @@ -115,7 +114,7 @@ mctx =3D EVP_MD_CTX_new(); pctx =3D NULL; if (!mctx - || EVP_DigestVerifyInit_ex(mctx, &pctx, mdname, tls_libctx, NULL, = pubkey, params) <=3D 0) + || EVP_DigestVerifyInit_ex(mctx, &pctx, mdname, tls_libctx, NULL, = pubkey, params) <=3D 0) { print_error("Failed to initialize EVP_DigestVerifyInit_ex()"); goto done; diff --git a/tests/unit_tests/openvpn/test_argv.c b/tests/unit_tests/openvp= n/test_argv.c index 33b3dec..a65857b 100644 --- a/tests/unit_tests/openvpn/test_argv.c +++ b/tests/unit_tests/openvpn/test_argv.c @@ -15,15 +15,15 @@ #include "test_common.h" /* Defines for use in the tests and the mock parse_line() */ -#define PATH1 "/s p a c e" -#define PATH2 "/foo bar/baz" -#define PARAM1 "param1" -#define PARAM2 "param two" -#define SCRIPT_CMD "\"" PATH1 PATH2 "\"" PARAM1 "\"" PARAM2 "\"" +#define PATH1 "/s p a c e" +#define PATH2 "/foo bar/baz" +#define PARAM1 "param1" +#define PARAM2 "param two" +#define SCRIPT_CMD "\"" PATH1 PATH2 "\"" PARAM1 "\"" PARAM2 "\"" int -__wrap_parse_line(const char *line, char **p, const int n, const char *fil= e, - const int line_num, int msglevel, struct gc_arena *gc) +__wrap_parse_line(const char *line, char **p, const int n, const char *fil= e, const int line_num, + int msglevel, struct gc_arena *gc) { p[0] =3D PATH1 PATH2; p[1] =3D PARAM1; @@ -201,10 +201,10 @@ argv_printf_cat(&a, "%s", PARAM2); argv_printf_cat(&a, "%d", -1); argv_printf_cat(&a, "%u", -1); - argv_printf_cat(&a, "%lu", 1L ); + argv_printf_cat(&a, "%lu", 1L); output =3D argv_str(&a, &gc, PA_BRACKET); assert_string_equal(output, "[" PATH1 PATH2 "] [" PARAM1 "] [" PARAM2 = "]" - " [-1] [4294967295] [1]"); + " [-1] [4294967295] [1]"); argv_free(&a); gc_free(&gc); diff --git a/tests/unit_tests/openvpn/test_auth_token.c b/tests/unit_tests/= openvpn/test_auth_token.c index 960422c..0c5467e 100644 --- a/tests/unit_tests/openvpn/test_auth_token.c +++ b/tests/unit_tests/openvpn/test_auth_token.c @@ -36,7 +36,8 @@ #include "auth_token.c" #include "test_common.h" -struct test_context { +struct test_context +{ struct tls_multi multi; struct key_type kt; struct user_pass up; @@ -52,10 +53,10 @@ void auth_set_client_reason(struct tls_multi *multi, const char *reason) { - } -static const char *now0key0 =3D "SESS_ID_AT_0123456789abcdefAAAAAAAAAAAAAA= AAAAAAAE5JsQJOVfo8jnI3RL3tBaR5NkE4yPfcylFUHmHSc5Bu"; +static const char *now0key0 =3D + "SESS_ID_AT_0123456789abcdefAAAAAAAAAAAAAAAAAAAAAE5JsQJOVfo8jnI3RL3tBa= R5NkE4yPfcylFUHmHSc5Bu"; static const char *zeroinline =3D "-----BEGIN OpenVPN auth-token server ke= y-----\n" "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= AAAAAAAAAAAAAAAAAAAAAAA\n" @@ -63,21 +64,24 @@ "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= AA=3D\n" "-----END OpenVPN auth-token server key---= --"; -static const char *allx01inline =3D "-----BEGIN OpenVPN auth-token server = key-----\n" - "AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE= BAQEBAQEBAQEBAQEBAQEBAQEB\n" - "AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE= BAQEBAQEBAQEBAQEBAQEBAQEB\n" - "AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE= BAQE=3D\n" - "-----END OpenVPN auth-token server key-= ----"; +static const char *allx01inline =3D + "-----BEGIN OpenVPN auth-token server key-----\n" + "AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEB\n" + "AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEB\n" + "AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE=3D\n" + "-----END OpenVPN auth-token server key-----"; -static const char *random_key =3D "-----BEGIN OpenVPN auth-token server ke= y-----\n" - "+mmmf7IQ5cymtMVjKYTWk8IOcYanRlpQmV9Tb3Ejk= HYxueBVDg3yqRgzeBlVGzNLD//rAPiOVhau\n" - "3NDBjNOQB8951bfs7Cc2mYfay92Bh2gRJ5XEM/DMf= zCWN+7uU6NWoTTHr4FuojnIQtjtqVAj/JS9\n" - "w+dTSp/vYHl+c7uHd19uVRu/qLqV85+rm4tUGIjO7= FfYuwyPqwmhuIsi3hs9QkSimh888FmBpoKY\n" - "/tbKVTJZmSERKti9KEwtV2eVAR0znN5KW7lCB3mHV= AhN7bUpcoDjfCzYIFARxwswTFu9gFkwqUMY\n" - "I1KUOgIsVNs4llACioeXplYekWETR+YkJwDc/A=3D= =3D\n" - "-----END OpenVPN auth-token server key---= --"; +static const char *random_key =3D + "-----BEGIN OpenVPN auth-token server key-----\n" + "+mmmf7IQ5cymtMVjKYTWk8IOcYanRlpQmV9Tb3EjkHYxueBVDg3yqRgzeBlVGzNLD//rA= PiOVhau\n" + "3NDBjNOQB8951bfs7Cc2mYfay92Bh2gRJ5XEM/DMfzCWN+7uU6NWoTTHr4FuojnIQtjtq= VAj/JS9\n" + "w+dTSp/vYHl+c7uHd19uVRu/qLqV85+rm4tUGIjO7FfYuwyPqwmhuIsi3hs9QkSimh888= FmBpoKY\n" + "/tbKVTJZmSERKti9KEwtV2eVAR0znN5KW7lCB3mHVAhN7bUpcoDjfCzYIFARxwswTFu9g= FkwqUMY\n" + "I1KUOgIsVNs4llACioeXplYekWETR+YkJwDc/A=3D=3D\n" + "-----END OpenVPN auth-token server key-----"; -static const char *random_token =3D "SESS_ID_AT_ThhRItzOKNKrh3dfAAAAAFwzHp= wAAAAAXDMenDdrq0RoH3dkA1f7O3wO+7kZcx2DusVZrRmFlWQM9HOb"; +static const char *random_token =3D + "SESS_ID_AT_ThhRItzOKNKrh3dfAAAAAFwzHpwAAAAAXDMenDdrq0RoH3dkA1f7O3wO+7= kZcx2DusVZrRmFlWQM9HOb"; static int @@ -87,7 +91,7 @@ *state =3D ctx; struct key_parameters key =3D { 0 }; - key.hmac_size =3D MAX_HMAC_KEY_LENGTH; /* 64 byte of 0 */ + key.hmac_size =3D MAX_HMAC_KEY_LENGTH; /* 64 byte of 0 */ ctx->kt =3D auth_token_kt(); if (!ctx->kt.digest) @@ -115,7 +119,7 @@ static int teardown(void **state) { - struct test_context *ctx =3D (struct test_context *) *state; + struct test_context *ctx =3D (struct test_context *)*state; free_key_ctx(&ctx->multi.opt.auth_token_key); wipe_auth_token(&ctx->multi); @@ -129,23 +133,21 @@ static void auth_token_basic_test(void **state) { - struct test_context *ctx =3D (struct test_context *) *state; + struct test_context *ctx =3D (struct test_context *)*state; generate_auth_token(&ctx->up, &ctx->multi); strcpy(ctx->up.password, ctx->multi.auth_token); - assert_int_equal(verify_auth_token(&ctx->up, &ctx->multi, ctx->session= ), - AUTH_TOKEN_HMAC_OK); + assert_int_equal(verify_auth_token(&ctx->up, &ctx->multi, ctx->session= ), AUTH_TOKEN_HMAC_OK); } static void auth_token_fail_invalid_key(void **state) { - struct test_context *ctx =3D (struct test_context *) *state; + struct test_context *ctx =3D (struct test_context *)*state; generate_auth_token(&ctx->up, &ctx->multi); strcpy(ctx->up.password, ctx->multi.auth_token); - assert_int_equal(verify_auth_token(&ctx->up, &ctx->multi, ctx->session= ), - AUTH_TOKEN_HMAC_OK); + assert_int_equal(verify_auth_token(&ctx->up, &ctx->multi, ctx->session= ), AUTH_TOKEN_HMAC_OK); /* Change auth-token key */ struct key_parameters key; @@ -161,15 +163,13 @@ memset(&key.hmac, 0, sizeof(key.hmac)); free_key_ctx(&ctx->multi.opt.auth_token_key); init_key_ctx(&ctx->multi.opt.auth_token_key, &key, &ctx->kt, false, "T= EST"); - assert_int_equal(verify_auth_token(&ctx->up, &ctx->multi, ctx->session= ), - AUTH_TOKEN_HMAC_OK); - + assert_int_equal(verify_auth_token(&ctx->up, &ctx->multi, ctx->session= ), AUTH_TOKEN_HMAC_OK); } static void auth_token_test_timeout(void **state) { - struct test_context *ctx =3D (struct test_context *) *state; + struct test_context *ctx =3D (struct test_context *)*state; now =3D 100000; generate_auth_token(&ctx->up, &ctx->multi); @@ -179,33 +179,31 @@ ctx->multi.auth_token_initial =3D NULL; /* No time has passed */ - assert_int_equal(verify_auth_token(&ctx->up, &ctx->multi, ctx->session= ), - AUTH_TOKEN_HMAC_OK); + assert_int_equal(verify_auth_token(&ctx->up, &ctx->multi, ctx->session= ), AUTH_TOKEN_HMAC_OK); /* Token before validity, should be rejected */ now =3D 100000 - 100; assert_int_equal(verify_auth_token(&ctx->up, &ctx->multi, ctx->session= ), - AUTH_TOKEN_HMAC_OK|AUTH_TOKEN_EXPIRED); + AUTH_TOKEN_HMAC_OK | AUTH_TOKEN_EXPIRED); /* Token no valid for renegotiate_seconds but still for renewal_time */ - now =3D 100000 + 2*ctx->session->opt->renegotiate_seconds - 20; + now =3D 100000 + 2 * ctx->session->opt->renegotiate_seconds - 20; assert_int_equal(verify_auth_token(&ctx->up, &ctx->multi, ctx->session= ), - AUTH_TOKEN_HMAC_OK|AUTH_TOKEN_EXPIRED); + AUTH_TOKEN_HMAC_OK | AUTH_TOKEN_EXPIRED); - now =3D 100000 + 2*ctx->session->opt->auth_token_renewal - 20; - assert_int_equal(verify_auth_token(&ctx->up, &ctx->multi, ctx->session= ), - AUTH_TOKEN_HMAC_OK); + now =3D 100000 + 2 * ctx->session->opt->auth_token_renewal - 20; + assert_int_equal(verify_auth_token(&ctx->up, &ctx->multi, ctx->session= ), AUTH_TOKEN_HMAC_OK); /* Token past validity, should be rejected */ - now =3D 100000 + 2*ctx->session->opt->renegotiate_seconds + 20; + now =3D 100000 + 2 * ctx->session->opt->renegotiate_seconds + 20; assert_int_equal(verify_auth_token(&ctx->up, &ctx->multi, ctx->session= ), - AUTH_TOKEN_HMAC_OK|AUTH_TOKEN_EXPIRED); + AUTH_TOKEN_HMAC_OK | AUTH_TOKEN_EXPIRED); /* But not when we reached our timeout */ now =3D 100000 + ctx->session->opt->auth_token_lifetime + 1; assert_int_equal(verify_auth_token(&ctx->up, &ctx->multi, ctx->session= ), - AUTH_TOKEN_HMAC_OK|AUTH_TOKEN_EXPIRED); + AUTH_TOKEN_HMAC_OK | AUTH_TOKEN_EXPIRED); free(ctx->multi.auth_token_initial); ctx->multi.auth_token_initial =3D NULL; @@ -223,26 +221,25 @@ assert_int_equal(verify_auth_token(&ctx->up, &ctx->multi, ctx->session= ), - AUTH_TOKEN_HMAC_OK|AUTH_TOKEN_EXPIRED); + AUTH_TOKEN_HMAC_OK | AUTH_TOKEN_EXPIRED); ctx->multi.opt.auth_token_lifetime =3D 0; /* Non expiring token should be fine */ - assert_int_equal(verify_auth_token(&ctx->up, &ctx->multi, ctx->session= ), - AUTH_TOKEN_HMAC_OK); + assert_int_equal(verify_auth_token(&ctx->up, &ctx->multi, ctx->session= ), AUTH_TOKEN_HMAC_OK); } static void zerohmac(char *token) { - char *hmacstart =3D token + AUTH_TOKEN_SESSION_ID_LEN - + strlen(SESSION_ID_PREFIX) + 2*sizeof(uint64_t); + char *hmacstart =3D + token + AUTH_TOKEN_SESSION_ID_LEN + strlen(SESSION_ID_PREFIX) + 2 = * sizeof(uint64_t); memset(hmacstart, 0x8d, strlen(hmacstart)); } static void auth_token_test_known_keys(void **state) { - struct test_context *ctx =3D (struct test_context *) *state; + struct test_context *ctx =3D (struct test_context *)*state; now =3D 0; /* Preload the session id so the same session id is used here */ @@ -257,8 +254,7 @@ assert_string_equal(now0key0, ctx->multi.auth_token); strcpy(ctx->up.password, ctx->multi.auth_token); - assert_int_equal(verify_auth_token(&ctx->up, &ctx->multi, ctx->session= ), - AUTH_TOKEN_HMAC_OK); + assert_int_equal(verify_auth_token(&ctx->up, &ctx->multi, ctx->session= ), AUTH_TOKEN_HMAC_OK); } static const char *lastsesion_statevalue; @@ -274,13 +270,12 @@ void auth_token_test_session_mismatch(void **state) { - struct test_context *ctx =3D (struct test_context *) *state; + struct test_context *ctx =3D (struct test_context *)*state; /* Generate first auth token and check it is correct */ generate_auth_token(&ctx->up, &ctx->multi); strcpy(ctx->up.password, ctx->multi.auth_token); - assert_int_equal(verify_auth_token(&ctx->up, &ctx->multi, ctx->session= ), - AUTH_TOKEN_HMAC_OK); + assert_int_equal(verify_auth_token(&ctx->up, &ctx->multi, ctx->session= ), AUTH_TOKEN_HMAC_OK); char *token_sessiona =3D strdup(ctx->multi.auth_token); @@ -289,8 +284,7 @@ generate_auth_token(&ctx->up, &ctx->multi); strcpy(ctx->up.password, ctx->multi.auth_token); - assert_int_equal(verify_auth_token(&ctx->up, &ctx->multi, ctx->session= ), - AUTH_TOKEN_HMAC_OK); + assert_int_equal(verify_auth_token(&ctx->up, &ctx->multi, ctx->session= ), AUTH_TOKEN_HMAC_OK); assert_int_not_equal(0, memcmp(ctx->multi.auth_token_initial + strlen(= SESSION_ID_PREFIX), token_sessiona + strlen(SESSION_ID_PREF= IX), @@ -306,39 +300,37 @@ static void auth_token_test_empty_user(void **state) { - struct test_context *ctx =3D (struct test_context *) *state; + struct test_context *ctx =3D (struct test_context *)*state; CLEAR(ctx->up.username); now =3D 0; generate_auth_token(&ctx->up, &ctx->multi); strcpy(ctx->up.password, ctx->multi.auth_token); - assert_int_equal(verify_auth_token(&ctx->up, &ctx->multi, ctx->session= ), - AUTH_TOKEN_HMAC_OK); + assert_int_equal(verify_auth_token(&ctx->up, &ctx->multi, ctx->session= ), AUTH_TOKEN_HMAC_OK); now =3D 100000; assert_int_equal(verify_auth_token(&ctx->up, &ctx->multi, ctx->session= ), - AUTH_TOKEN_HMAC_OK|AUTH_TOKEN_EXPIRED); + AUTH_TOKEN_HMAC_OK | AUTH_TOKEN_EXPIRED); strcpy(ctx->up.username, "test user name"); now =3D 0; assert_int_equal(verify_auth_token(&ctx->up, &ctx->multi, ctx->session= ), - AUTH_TOKEN_HMAC_OK|AUTH_TOKEN_VALID_EMPTYUSER); + AUTH_TOKEN_HMAC_OK | AUTH_TOKEN_VALID_EMPTYUSER); strcpy(ctx->up.username, "test user name"); now =3D 100000; assert_int_equal(verify_auth_token(&ctx->up, &ctx->multi, ctx->session= ), - AUTH_TOKEN_HMAC_OK|AUTH_TOKEN_EXPIRED|AUTH_TOKEN_VALI= D_EMPTYUSER); + AUTH_TOKEN_HMAC_OK | AUTH_TOKEN_EXPIRED | AUTH_TOKEN_= VALID_EMPTYUSER); zerohmac(ctx->up.password); - assert_int_equal(verify_auth_token(&ctx->up, &ctx->multi, ctx->session= ), - 0); + assert_int_equal(verify_auth_token(&ctx->up, &ctx->multi, ctx->session= ), 0); } static void auth_token_test_env(void **state) { - struct test_context *ctx =3D (struct test_context *) *state; + struct test_context *ctx =3D (struct test_context *)*state; =20 struct key_state *ks =3D &ctx->multi.session[TM_ACTIVE].key[KS_PRIMARY= ]; @@ -356,15 +348,16 @@ add_session_token_env(ctx->session, &ctx->multi, &ctx->up); assert_string_equal(lastsesion_statevalue, "Authenticated"); - ks->auth_token_state_flags =3D AUTH_TOKEN_HMAC_OK|AUTH_TOKEN_EXPIRED; + ks->auth_token_state_flags =3D AUTH_TOKEN_HMAC_OK | AUTH_TOKEN_EXPIRED; add_session_token_env(ctx->session, &ctx->multi, &ctx->up); assert_string_equal(lastsesion_statevalue, "Expired"); - ks->auth_token_state_flags =3D AUTH_TOKEN_HMAC_OK|AUTH_TOKEN_VALID_EMP= TYUSER; + ks->auth_token_state_flags =3D AUTH_TOKEN_HMAC_OK | AUTH_TOKEN_VALID_E= MPTYUSER; add_session_token_env(ctx->session, &ctx->multi, &ctx->up); assert_string_equal(lastsesion_statevalue, "AuthenticatedEmptyUser"); - ks->auth_token_state_flags =3D AUTH_TOKEN_HMAC_OK|AUTH_TOKEN_EXPIRED|A= UTH_TOKEN_VALID_EMPTYUSER; + ks->auth_token_state_flags =3D + AUTH_TOKEN_HMAC_OK | AUTH_TOKEN_EXPIRED | AUTH_TOKEN_VALID_EMPTYUS= ER; add_session_token_env(ctx->session, &ctx->multi, &ctx->up); assert_string_equal(lastsesion_statevalue, "ExpiredEmptyUser"); } @@ -372,7 +365,7 @@ static void auth_token_test_random_keys(void **state) { - struct test_context *ctx =3D (struct test_context *) *state; + struct test_context *ctx =3D (struct test_context *)*state; now =3D 0x5c331e9c; /* Preload the session id so the same session id is used here */ @@ -397,7 +390,7 @@ static void auth_token_test_key_load(void **state) { - struct test_context *ctx =3D (struct test_context *) *state; + struct test_context *ctx =3D (struct test_context *)*state; free_key_ctx(&ctx->multi.opt.auth_token_key); auth_token_init_secret(&ctx->multi.opt.auth_token_key, zeroinline, tru= e); diff --git a/tests/unit_tests/openvpn/test_buffer.c b/tests/unit_tests/open= vpn/test_buffer.c index 4b3aaf8..0cfb918 100644 --- a/tests/unit_tests/openvpn/test_buffer.c +++ b/tests/unit_tests/openvpn/test_buffer.c @@ -43,13 +43,13 @@ assert_false(strprefix("12", "123")); } -#define testsep "," +#define testsep "," #define testnosep "" -#define teststr1 "one" -#define teststr2 "two" -#define teststr3 "three" +#define teststr1 "one" +#define teststr2 "two" +#define teststr3 "three" -#define assert_buf_equals_str(buf, str) \ +#define assert_buf_equals_str(buf, str) \ assert_int_equal(BLEN(buf), strlen(str)); \ assert_memory_equal(BPTR(buf), str, BLEN(buf)); @@ -82,9 +82,7 @@ test_buffer_format_hex_ex(void **state) { const int input_size =3D 10; - const uint8_t input[] =3D { - 0x01, 0x00, 0xff, 0x10, 0xff, 0x00, 0xf0, 0x0f, 0x09, 0x0a - }; + const uint8_t input[] =3D { 0x01, 0x00, 0xff, 0x10, 0xff, 0x00, 0xf0, = 0x0f, 0x09, 0x0a }; char *output; struct gc_arena gc =3D gc_new(); @@ -113,7 +111,8 @@ gc_free(&gc); } -struct test_buffer_list_aggregate_ctx { +struct test_buffer_list_aggregate_ctx +{ struct buffer_list *empty; struct buffer_list *one_two_three; struct buffer_list *zero_length_strings; @@ -123,7 +122,7 @@ static int test_buffer_list_setup(void **state) { - struct test_buffer_list_aggregate_ctx *ctx =3D calloc(1, sizeof(*ctx)= ); + struct test_buffer_list_aggregate_ctx *ctx =3D calloc(1, sizeof(*ctx)); ctx->empty =3D buffer_list_new(); ctx->one_two_three =3D buffer_list_new(); @@ -188,8 +187,7 @@ /* Aggregate the first two elements * (add 1 to max_len to test if "three" is not sneaked in too) */ - buffer_list_aggregate_separator(ctx->one_two_three, strlen(expected) += 1, - testsep); + buffer_list_aggregate_separator(ctx->one_two_three, strlen(expected) += 1, testsep); assert_int_equal(ctx->one_two_three->size, 2); struct buffer *buf =3D buffer_list_peek(ctx->one_two_three); assert_buf_equals_str(buf, expected); @@ -201,11 +199,10 @@ struct test_buffer_list_aggregate_ctx *ctx =3D *state; /* Aggregate all */ - buffer_list_aggregate_separator(ctx->one_two_three, 1<<16, testsep); + buffer_list_aggregate_separator(ctx->one_two_three, 1 << 16, testsep); assert_int_equal(ctx->one_two_three->size, 1); struct buffer *buf =3D buffer_list_peek(ctx->one_two_three); - assert_buf_equals_str(buf, - teststr1 testsep teststr2 testsep teststr3 tests= ep); + assert_buf_equals_str(buf, teststr1 testsep teststr2 testsep teststr3 = testsep); } static void @@ -214,7 +211,7 @@ struct test_buffer_list_aggregate_ctx *ctx =3D *state; /* Aggregate all */ - buffer_list_aggregate_separator(ctx->one_two_three, 1<<16, testnosep); + buffer_list_aggregate_separator(ctx->one_two_three, 1 << 16, testnosep= ); assert_int_equal(ctx->one_two_three->size, 1); struct buffer *buf =3D buffer_list_peek(ctx->one_two_three); assert_buf_equals_str(buf, teststr1 teststr2 teststr3); @@ -227,7 +224,7 @@ struct buffer_list *bl_zerolen =3D ctx->zero_length_strings; /* Aggregate all */ - buffer_list_aggregate_separator(bl_zerolen, 1<<16, testnosep); + buffer_list_aggregate_separator(bl_zerolen, 1 << 16, testnosep); assert_int_equal(bl_zerolen->size, 1); struct buffer *buf =3D buffer_list_peek(bl_zerolen); assert_buf_equals_str(buf, ""); @@ -240,7 +237,7 @@ struct buffer_list *bl_emptybuffers =3D ctx->empty_buffers; /* Aggregate all */ - buffer_list_aggregate_separator(bl_emptybuffers, 1<<16, testnosep); + buffer_list_aggregate_separator(bl_emptybuffers, 1 << 16, testnosep); assert_int_equal(bl_emptybuffers->size, 1); struct buffer *buf =3D buffer_list_peek(bl_emptybuffers); assert_int_equal(BLEN(buf), 0); @@ -344,11 +341,12 @@ assert_string_equal(buf, "There.is...a.nice......year.old.tr..ee."); strcpy(buf, "There is \x01 a 'nice' \"1234\"\n year old \ntr\x7f ee!"); - assert_false(string_mod(buf, CC_ALPHA|CC_DIGIT|CC_NEWLINE|CC_SINGLE_QU= OTE, CC_DOUBLE_QUOTE|CC_BLANK, '.')); + assert_false(string_mod(buf, CC_ALPHA | CC_DIGIT | CC_NEWLINE | CC_SIN= GLE_QUOTE, + CC_DOUBLE_QUOTE | CC_BLANK, '.')); assert_string_equal(buf, "There.is...a.'nice'..1234.\n.year.old.\ntr..= ee."); strcpy(buf, "There is a \\'nice\\' \"1234\" [*] year old \ntree!"); - assert_false(string_mod(buf, CC_PRINT, CC_BACKSLASH|CC_ASTERISK, '.')); + assert_false(string_mod(buf, CC_PRINT, CC_BACKSLASH | CC_ASTERISK, '.'= )); assert_string_equal(buf, "There is a .'nice.' \"1234\" [.] year old .t= ree!"); } @@ -360,7 +358,7 @@ =20 struct buffer buf =3D alloc_buf_gc(1024, &gc); - const char test1[] =3D "There is a nice 1234\x00 year old tree!"; + const char test1[] =3D "There is a nice 1234\x00 year old tree!"; buf_write(&buf, test1, sizeof(test1)); /* allow the null bytes and string but not the ! */ @@ -432,7 +430,7 @@ struct gc_arena gc =3D gc_new(); struct buffer buf =3D alloc_buf_gc(1024, &gc); - const char test1[] =3D "There is a nice 1234 year old tree!\n\r"; + const char test1[] =3D "There is a nice 1234 year old tree!\n\r"; buf_write(&buf, test1, sizeof(test1)); buf_chomp(&buf); /* Check that our own method agrees */ @@ -440,7 +438,7 @@ assert_string_equal(BSTR(&buf), "There is a nice 1234 year old tree!"); struct buffer buf2 =3D alloc_buf_gc(1024, &gc); - const char test2[] =3D "CR_RESPONSE,MTIx\x0a\x00"; + const char test2[] =3D "CR_RESPONSE,MTIx\x0a\x00"; buf_write(&buf2, test2, sizeof(test2)); buf_chomp(&buf2); @@ -461,26 +459,19 @@ cmocka_unit_test(test_buffer_printf_catrunc), cmocka_unit_test(test_buffer_format_hex_ex), cmocka_unit_test_setup_teardown(test_buffer_list_aggregate_separat= or_empty, - test_buffer_list_setup, - test_buffer_list_teardown), + test_buffer_list_setup, test_buffe= r_list_teardown), cmocka_unit_test_setup_teardown(test_buffer_list_aggregate_separat= or_noop, - test_buffer_list_setup, - test_buffer_list_teardown), + test_buffer_list_setup, test_buffe= r_list_teardown), cmocka_unit_test_setup_teardown(test_buffer_list_aggregate_separat= or_two, - test_buffer_list_setup, - test_buffer_list_teardown), + test_buffer_list_setup, test_buffe= r_list_teardown), cmocka_unit_test_setup_teardown(test_buffer_list_aggregate_separat= or_all, - test_buffer_list_setup, - test_buffer_list_teardown), + test_buffer_list_setup, test_buffe= r_list_teardown), cmocka_unit_test_setup_teardown(test_buffer_list_aggregate_separat= or_nosep, - test_buffer_list_setup, - test_buffer_list_teardown), + test_buffer_list_setup, test_buffe= r_list_teardown), cmocka_unit_test_setup_teardown(test_buffer_list_aggregate_separat= or_zerolen, - test_buffer_list_setup, - test_buffer_list_teardown), + test_buffer_list_setup, test_buffe= r_list_teardown), cmocka_unit_test_setup_teardown(test_buffer_list_aggregate_separat= or_emptybuffers, - test_buffer_list_setup, - test_buffer_list_teardown), + test_buffer_list_setup, test_buffe= r_list_teardown), cmocka_unit_test(test_buffer_free_gc_one), cmocka_unit_test(test_buffer_free_gc_two), cmocka_unit_test(test_buffer_gc_realloc), diff --git a/tests/unit_tests/openvpn/test_crypto.c b/tests/unit_tests/open= vpn/test_crypto.c index 1c3b146..12ddaba 100644 --- a/tests/unit_tests/openvpn/test_crypto.c +++ b/tests/unit_tests/openvpn/test_crypto.c @@ -156,7 +156,7 @@ const size_t seed_len =3D strlen(seedstr); - const unsigned char *secret =3D (const unsigned char *) ipsumlorem; + const unsigned char *secret =3D (const unsigned char *)ipsumlorem; size_t secret_len =3D strlen((const char *)secret); @@ -168,18 +168,16 @@ assert_false(ret); #else assert_true(ret); - uint8_t good_prf[32] =3D {0xd9, 0x8c, 0x85, 0x18, 0xc8, 0x5e, 0x94, 0x= 69, - 0x27, 0x91, 0x6a, 0xcf, 0xc2, 0xd5, 0x92, 0xfb, - 0xb1, 0x56, 0x7e, 0x4b, 0x4b, 0x14, 0x59, 0xe6, - 0xa9, 0x04, 0xac, 0x2d, 0xda, 0xb7, 0x2d, 0x67= }; + uint8_t good_prf[32] =3D { 0xd9, 0x8c, 0x85, 0x18, 0xc8, 0x5e, 0x94, 0= x69, 0x27, 0x91, 0x6a, + 0xcf, 0xc2, 0xd5, 0x92, 0xfb, 0xb1, 0x56, 0x7= e, 0x4b, 0x4b, 0x14, + 0x59, 0xe6, 0xa9, 0x04, 0xac, 0x2d, 0xda, 0xb= 7, 0x2d, 0x67 }; assert_memory_equal(good_prf, out, sizeof(out)); #endif } -static uint8_t testkey[20] =3D {0x0b, 0x00}; -static uint8_t goodhash[20] =3D {0x58, 0xea, 0x5a, 0xf0, 0x42, 0x94, 0xe9,= 0x17, - 0xed, 0x84, 0xb9, 0xf0, 0x83, 0x30, 0x23, 0= xae, - 0x8b, 0xa7, 0x7e, 0xb8}; +static uint8_t testkey[20] =3D { 0x0b, 0x00 }; +static uint8_t goodhash[20] =3D { 0x58, 0xea, 0x5a, 0xf0, 0x42, 0x94, 0xe9= , 0x17, 0xed, 0x84, + 0xb9, 0xf0, 0x83, 0x30, 0x23, 0xae, 0x8b, = 0xa7, 0x7e, 0xb8 }; static void crypto_test_hmac(void **state) @@ -192,8 +190,8 @@ memcpy(key, testkey, sizeof(key)); hmac_ctx_init(hmac, key, "SHA1"); - hmac_ctx_update(hmac, (const uint8_t *)ipsumlorem, (int) strlen(ipsuml= orem)); - hmac_ctx_update(hmac, (const uint8_t *)ipsumlorem, (int) strlen(ipsuml= orem)); + hmac_ctx_update(hmac, (const uint8_t *)ipsumlorem, (int)strlen(ipsumlo= rem)); + hmac_ctx_update(hmac, (const uint8_t *)ipsumlorem, (int)strlen(ipsumlo= rem)); uint8_t hash[20]; hmac_ctx_final(hmac, hash); @@ -203,8 +201,8 @@ /* try again */ hmac_ctx_reset(hmac); - hmac_ctx_update(hmac, (const uint8_t *)ipsumlorem, (int) strlen(ipsuml= orem)); - hmac_ctx_update(hmac, (const uint8_t *)ipsumlorem, (int) strlen(ipsuml= orem)); + hmac_ctx_update(hmac, (const uint8_t *)ipsumlorem, (int)strlen(ipsumlo= rem)); + hmac_ctx_update(hmac, (const uint8_t *)ipsumlorem, (int)strlen(ipsumlo= rem)); hmac_ctx_final(hmac, hash); assert_memory_equal(hash, goodhash, sizeof(hash)); @@ -213,8 +211,8 @@ memset(key, 0x55, sizeof(key)); hmac_ctx_reset(hmac); - hmac_ctx_update(hmac, (const uint8_t *)ipsumlorem, (int) strlen(ipsuml= orem)); - hmac_ctx_update(hmac, (const uint8_t *)ipsumlorem, (int) strlen(ipsuml= orem)); + hmac_ctx_update(hmac, (const uint8_t *)ipsumlorem, (int)strlen(ipsumlo= rem)); + hmac_ctx_update(hmac, (const uint8_t *)ipsumlorem, (int)strlen(ipsumlo= rem)); hmac_ctx_final(hmac, hash); assert_memory_equal(hash, goodhash, sizeof(hash)); @@ -481,22 +479,16 @@ crypto_test_hkdf_expand_testa1(void **state) { /* RFC 5889 A.1 Test Case 1 */ - uint8_t prk[32] =3D - {0x07, 0x77, 0x09, 0x36, 0x2c, 0x2e, 0x32, 0xdf, - 0x0d, 0xdc, 0x3f, 0x0d, 0xc4, 0x7b, 0xba, 0x63, - 0x90, 0xb6, 0xc7, 0x3b, 0xb5, 0x0f, 0x9c, 0x31, - 0x22, 0xec, 0x84, 0x4a, 0xd7, 0xc2, 0xb3, 0xe5}; + uint8_t prk[32] =3D { 0x07, 0x77, 0x09, 0x36, 0x2c, 0x2e, 0x32, 0xdf, = 0x0d, 0xdc, 0x3f, + 0x0d, 0xc4, 0x7b, 0xba, 0x63, 0x90, 0xb6, 0xc7, 0x= 3b, 0xb5, 0x0f, + 0x9c, 0x31, 0x22, 0xec, 0x84, 0x4a, 0xd7, 0xc2, 0x= b3, 0xe5 }; - uint8_t info[10] =3D {0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, - 0xf6, 0xf7, 0xf8, 0xf9}; + uint8_t info[10] =3D { 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7,= 0xf8, 0xf9 }; - uint8_t okm[42] =3D - {0x3c, 0xb2, 0x5f, 0x25, 0xfa, 0xac, 0xd5, 0x7a, - 0x90, 0x43, 0x4f, 0x64, 0xd0, 0x36, 0x2f, 0x2a, - 0x2d, 0x2d, 0x0a, 0x90, 0xcf, 0x1a, 0x5a, 0x4c, - 0x5d, 0xb0, 0x2d, 0x56, 0xec, 0xc4, 0xc5, 0xbf, - 0x34, 0x00, 0x72, 0x08, 0xd5, 0xb8, 0x87, 0x18, - 0x58, 0x65}; + uint8_t okm[42] =3D { 0x3c, 0xb2, 0x5f, 0x25, 0xfa, 0xac, 0xd5, 0x7a, = 0x90, 0x43, 0x4f, + 0x64, 0xd0, 0x36, 0x2f, 0x2a, 0x2d, 0x2d, 0x0a, 0x= 90, 0xcf, 0x1a, + 0x5a, 0x4c, 0x5d, 0xb0, 0x2d, 0x56, 0xec, 0xc4, 0x= c5, 0xbf, 0x34, + 0x00, 0x72, 0x08, 0xd5, 0xb8, 0x87, 0x18, 0x58, 0x= 65 }; uint8_t out[42]; ovpn_hkdf_expand(prk, info, sizeof(info), out, sizeof(out)); @@ -508,39 +500,28 @@ crypto_test_hkdf_expand_testa2(void **state) { /* RFC 5889 A.2 Test Case 2 */ - uint8_t prk[32] =3D - {0x06, 0xa6, 0xb8, 0x8c, 0x58, 0x53, 0x36, 0x1a, - 0x06, 0x10, 0x4c, 0x9c, 0xeb, 0x35, 0xb4, 0x5c, - 0xef, 0x76, 0x00, 0x14, 0x90, 0x46, 0x71, 0x01, - 0x4a, 0x19, 0x3f, 0x40, 0xc1, 0x5f, 0xc2, 0x44}; + uint8_t prk[32] =3D { 0x06, 0xa6, 0xb8, 0x8c, 0x58, 0x53, 0x36, 0x1a, = 0x06, 0x10, 0x4c, + 0x9c, 0xeb, 0x35, 0xb4, 0x5c, 0xef, 0x76, 0x00, 0x= 14, 0x90, 0x46, + 0x71, 0x01, 0x4a, 0x19, 0x3f, 0x40, 0xc1, 0x5f, 0x= c2, 0x44 }; - uint8_t info[80] =3D - {0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, - 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, - 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, - 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, - 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, - 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, - 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, - 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, - 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, - 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff}; + uint8_t info[80] =3D { 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7,= 0xb8, 0xb9, 0xba, 0xbb, + 0xbc, 0xbd, 0xbe, 0xbf, 0xc0, 0xc1, 0xc2, 0xc3, 0= xc4, 0xc5, 0xc6, 0xc7, + 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, 0= xd0, 0xd1, 0xd2, 0xd3, + 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xdb, 0= xdc, 0xdd, 0xde, 0xdf, + 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0= xe8, 0xe9, 0xea, 0xeb, + 0xec, 0xed, 0xee, 0xef, 0xf0, 0xf1, 0xf2, 0xf3, 0= xf4, 0xf5, 0xf6, 0xf7, + 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff }; const int L =3D 82; - uint8_t okm[82] =3D - {0xb1, 0x1e, 0x39, 0x8d, 0xc8, 0x03, 0x27, 0xa1, - 0xc8, 0xe7, 0xf7, 0x8c, 0x59, 0x6a, 0x49, 0x34, - 0x4f, 0x01, 0x2e, 0xda, 0x2d, 0x4e, 0xfa, 0xd8, - 0xa0, 0x50, 0xcc, 0x4c, 0x19, 0xaf, 0xa9, 0x7c, - 0x59, 0x04, 0x5a, 0x99, 0xca, 0xc7, 0x82, 0x72, - 0x71, 0xcb, 0x41, 0xc6, 0x5e, 0x59, 0x0e, 0x09, - 0xda, 0x32, 0x75, 0x60, 0x0c, 0x2f, 0x09, 0xb8, - 0x36, 0x77, 0x93, 0xa9, 0xac, 0xa3, 0xdb, 0x71, - 0xcc, 0x30, 0xc5, 0x81, 0x79, 0xec, 0x3e, 0x87, - 0xc1, 0x4c, 0x01, 0xd5, 0xc1, 0xf3, 0x43, 0x4f, - 0x1d, 0x87}; + uint8_t okm[82] =3D { 0xb1, 0x1e, 0x39, 0x8d, 0xc8, 0x03, 0x27, 0xa1, = 0xc8, 0xe7, 0xf7, 0x8c, + 0x59, 0x6a, 0x49, 0x34, 0x4f, 0x01, 0x2e, 0xda, 0x= 2d, 0x4e, 0xfa, 0xd8, + 0xa0, 0x50, 0xcc, 0x4c, 0x19, 0xaf, 0xa9, 0x7c, 0x= 59, 0x04, 0x5a, 0x99, + 0xca, 0xc7, 0x82, 0x72, 0x71, 0xcb, 0x41, 0xc6, 0x= 5e, 0x59, 0x0e, 0x09, + 0xda, 0x32, 0x75, 0x60, 0x0c, 0x2f, 0x09, 0xb8, 0x= 36, 0x77, 0x93, 0xa9, + 0xac, 0xa3, 0xdb, 0x71, 0xcc, 0x30, 0xc5, 0x81, 0x= 79, 0xec, 0x3e, 0x87, + 0xc1, 0x4c, 0x01, 0xd5, 0xc1, 0xf3, 0x43, 0x4f, 0x= 1d, 0x87 }; - uint8_t out[82] =3D {0xaa}; + uint8_t out[82] =3D { 0xaa }; ovpn_hkdf_expand(prk, info, sizeof(info), out, L); assert_memory_equal(out, okm, L); @@ -550,22 +531,17 @@ crypto_test_hkdf_expand_testa3(void **state) { /* RFC 5889 A.3 Test Case 3 */ - uint8_t prk[32] =3D - {0x19, 0xef, 0x24, 0xa3, 0x2c, 0x71, 0x7b, 0x16, - 0x7f, 0x33, 0xa9, 0x1d, 0x6f, 0x64, 0x8b, 0xdf, - 0x96, 0x59, 0x67, 0x76, 0xaf, 0xdb, 0x63, 0x77, - 0xac, 0x43, 0x4c, 0x1c, 0x29, 0x3c, 0xcb, 0x04}; + uint8_t prk[32] =3D { 0x19, 0xef, 0x24, 0xa3, 0x2c, 0x71, 0x7b, 0x16, = 0x7f, 0x33, 0xa9, + 0x1d, 0x6f, 0x64, 0x8b, 0xdf, 0x96, 0x59, 0x67, 0x= 76, 0xaf, 0xdb, + 0x63, 0x77, 0xac, 0x43, 0x4c, 0x1c, 0x29, 0x3c, 0x= cb, 0x04 }; uint8_t info[] =3D {}; int L =3D 42; - uint8_t okm[42] =3D - {0x8d, 0xa4, 0xe7, 0x75, 0xa5, 0x63, 0xc1, 0x8f, - 0x71, 0x5f, 0x80, 0x2a, 0x06, 0x3c, 0x5a, 0x31, - 0xb8, 0xa1, 0x1f, 0x5c, 0x5e, 0xe1, 0x87, 0x9e, - 0xc3, 0x45, 0x4e, 0x5f, 0x3c, 0x73, 0x8d, 0x2d, - 0x9d, 0x20, 0x13, 0x95, 0xfa, 0xa4, 0xb6, 0x1a, - 0x96, 0xc8}; + uint8_t okm[42] =3D { 0x8d, 0xa4, 0xe7, 0x75, 0xa5, 0x63, 0xc1, 0x8f, = 0x71, 0x5f, 0x80, + 0x2a, 0x06, 0x3c, 0x5a, 0x31, 0xb8, 0xa1, 0x1f, 0x= 5c, 0x5e, 0xe1, + 0x87, 0x9e, 0xc3, 0x45, 0x4e, 0x5f, 0x3c, 0x73, 0x= 8d, 0x2d, 0x9d, + 0x20, 0x13, 0x95, 0xfa, 0xa4, 0xb6, 0x1a, 0x96, 0x= c8 }; uint8_t out[42]; ovpn_hkdf_expand(prk, info, 0, out, L); @@ -579,23 +555,17 @@ /* tests the HDKF with a label/okm that OpenVPN itself uses in OpenSSL= 3 * HDKF unit test*/ - uint8_t prk[32] =3D - {0x07, 0x77, 0x09, 0x36, 0x2c, 0x2e, 0x32, 0xdf, - 0x0d, 0xdc, 0x3f, 0x0d, 0xc4, 0x7b, 0xba, 0x63, - 0x90, 0xb6, 0xc7, 0x3b, 0xb5, 0x0f, 0x9c, 0x31, - 0x22, 0xec, 0x84, 0x4a, 0xd7, 0xc2, 0xb3, 0xe5}; + uint8_t prk[32] =3D { 0x07, 0x77, 0x09, 0x36, 0x2c, 0x2e, 0x32, 0xdf, = 0x0d, 0xdc, 0x3f, + 0x0d, 0xc4, 0x7b, 0xba, 0x63, 0x90, 0xb6, 0xc7, 0x= 3b, 0xb5, 0x0f, + 0x9c, 0x31, 0x22, 0xec, 0x84, 0x4a, 0xd7, 0xc2, 0x= b3, 0xe5 }; - uint8_t info[18] =3D - {0x00, 0x1b, 0x0e, 0x6f, 0x76, 0x70, 0x6e, 0x20, - 0x75, 0x6e, 0x69, 0x74, 0x20, 0x74, 0x65, 0x73, - 0x74, 0x00}; + uint8_t info[18] =3D { 0x00, 0x1b, 0x0e, 0x6f, 0x76, 0x70, 0x6e, 0x20,= 0x75, + 0x6e, 0x69, 0x74, 0x20, 0x74, 0x65, 0x73, 0x74, 0= x00 }; =20 int L =3D 27; - uint8_t okm[27] =3D - {0x87, 0x5a, 0x8e, 0xec, 0x18, 0x55, 0x63, 0x80, - 0xb8, 0xd9, 0x33, 0xed, 0x32, 0x3c, 0x2d, 0xf8, - 0xe8, 0xec, 0xcf, 0x49, 0x72, 0xe6, 0x83, 0xf0, - 0x6a, 0x83, 0xac }; + uint8_t okm[27] =3D { 0x87, 0x5a, 0x8e, 0xec, 0x18, 0x55, 0x63, 0x80, = 0xb8, + 0xd9, 0x33, 0xed, 0x32, 0x3c, 0x2d, 0xf8, 0xe8, 0x= ec, + 0xcf, 0x49, 0x72, 0xe6, 0x83, 0xf0, 0x6a, 0x83, 0x= ac }; uint8_t out[27]; ovpn_hkdf_expand(prk, info, sizeof(info), out, L); @@ -606,19 +576,16 @@ void crypto_test_ovpn_label_expand(void **state) { - uint8_t secret[32] =3D - {0x07, 0x77, 0x09, 0x36, 0x2c, 0x2e, 0x32, 0xdf, - 0x0d, 0xdc, 0x3f, 0x0d, 0xc4, 0x7b, 0xba, 0x63, - 0x90, 0xb6, 0xc7, 0x3b, 0xb5, 0x0f, 0x9c, 0x31, - 0x22, 0xec, 0x84, 0x4a, 0xd7, 0xc2, 0xb3, 0xe5}; + uint8_t secret[32] =3D { 0x07, 0x77, 0x09, 0x36, 0x2c, 0x2e, 0x32, 0xd= f, 0x0d, 0xdc, 0x3f, + 0x0d, 0xc4, 0x7b, 0xba, 0x63, 0x90, 0xb6, 0xc7,= 0x3b, 0xb5, 0x0f, + 0x9c, 0x31, 0x22, 0xec, 0x84, 0x4a, 0xd7, 0xc2,= 0xb3, 0xe5 }; - const uint8_t *label =3D (const uint8_t *) ("unit test"); + const uint8_t *label =3D (const uint8_t *)("unit test"); uint8_t out[16]; ovpn_expand_label(secret, sizeof(secret), label, 9, NULL, 0, out, size= of(out)); - uint8_t out_expected[16] =3D - {0x18, 0x5e, 0xaa, 0x1c, 0x7f, 0x22, 0x8a, 0xb8, - 0xeb, 0x29, 0x77, 0x32, 0x14, 0xd9, 0x20, 0x46}; + uint8_t out_expected[16] =3D { 0x18, 0x5e, 0xaa, 0x1c, 0x7f, 0x22, 0x8= a, 0xb8, + 0xeb, 0x29, 0x77, 0x32, 0x14, 0xd9, 0x20,= 0x46 }; assert_memory_equal(out, out_expected, 16); } @@ -630,15 +597,13 @@ * openvpn_PRF ifdef maze */ bool -ossl_expand_label(const uint8_t *secret, size_t secret_len, - const uint8_t *label, size_t label_len, - const uint8_t *context, size_t context_len, - uint8_t *out, uint16_t out_len) +ossl_expand_label(const uint8_t *secret, size_t secret_len, const uint8_t = *label, size_t label_len, + const uint8_t *context, size_t context_len, uint8_t *out= , uint16_t out_len) { OSSL_LIB_CTX *libctx =3D NULL; const char *properties =3D NULL; =20 - const uint8_t *label_prefix =3D (const uint8_t *) ("ovpn "); + const uint8_t *label_prefix =3D (const uint8_t *)("ovpn "); const size_t label_prefix_len =3D 5; EVP_KDF *kdf =3D EVP_KDF_fetch(libctx, OSSL_KDF_NAME_TLS1_3_KDF, prope= rties); @@ -657,15 +622,12 @@ int mode =3D EVP_PKEY_HKDEF_MODE_EXPAND_ONLY; *p++ =3D OSSL_PARAM_construct_int(OSSL_KDF_PARAM_MODE, &mode); - *p++ =3D OSSL_PARAM_construct_utf8_string(OSSL_KDF_PARAM_DIGEST, - (char *) mdname, 0); - *p++ =3D OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_KEY, - (unsigned char *) secret, has= hlen); - *p++ =3D OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_PREFIX, - (unsigned char *) label_prefi= x, + *p++ =3D OSSL_PARAM_construct_utf8_string(OSSL_KDF_PARAM_DIGEST, (char= *)mdname, 0); + *p++ =3D OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_KEY, (unsign= ed char *)secret, hashlen); + *p++ =3D OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_PREFIX, (uns= igned char *)label_prefix, label_prefix_len); - *p++ =3D OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_LABEL, - (unsigned char *) label, labe= l_len); + *p++ =3D + OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_LABEL, (unsigned = char *)label, label_len); *p++ =3D OSSL_PARAM_construct_end(); @@ -680,13 +642,11 @@ void crypto_test_ovpn_expand_openssl3(void **state) { - uint8_t secret[32] =3D - {0x07, 0x77, 0x09, 0x36, 0x2c, 0x2e, 0x32, 0xdf, - 0x0d, 0xdc, 0x3f, 0x0d, 0xc4, 0x7b, 0xba, 0x63, - 0x90, 0xb6, 0xc7, 0x3b, 0xb5, 0x0f, 0x9c, 0x31, - 0x22, 0xec, 0x84, 0x4a, 0xd7, 0xc2, 0xb3, 0xe5}; + uint8_t secret[32] =3D { 0x07, 0x77, 0x09, 0x36, 0x2c, 0x2e, 0x32, 0xd= f, 0x0d, 0xdc, 0x3f, + 0x0d, 0xc4, 0x7b, 0xba, 0x63, 0x90, 0xb6, 0xc7,= 0x3b, 0xb5, 0x0f, + 0x9c, 0x31, 0x22, 0xec, 0x84, 0x4a, 0xd7, 0xc2,= 0xb3, 0xe5 }; - const uint8_t *label =3D (const uint8_t *) ("unit test"); + const uint8_t *label =3D (const uint8_t *)("unit test"); const size_t labellen =3D 9; uint8_t out[27]; @@ -725,11 +685,10 @@ init_key_type(&data->kt, "AES-128-GCM", "none", true, false); /* have an epoch key that uses 0x23 for the key for all bytes */ - struct epoch_key epoch1send =3D { .epoch =3D 1, .epoch_key =3D {0x23} = }; - struct epoch_key epoch1recv =3D { .epoch =3D 1, .epoch_key =3D {0x27} = }; + struct epoch_key epoch1send =3D { .epoch =3D 1, .epoch_key =3D { 0x23 = } }; + struct epoch_key epoch1recv =3D { .epoch =3D 1, .epoch_key =3D { 0x27 = } }; - epoch_init_key_ctx(&data->co, &data->kt, &epoch1send, - &epoch1recv, *num_future_keys); + epoch_init_key_ctx(&data->co, &data->kt, &epoch1send, &epoch1recv, *nu= m_future_keys); *state =3D data; return 0; @@ -913,7 +872,7 @@ void epoch_test_derive_data_key(void **state) { - struct epoch_key e17 =3D { .epoch =3D 17, .epoch_key =3D { 19, 12 }}; + struct epoch_key e17 =3D { .epoch =3D 17, .epoch_key =3D { 19, 12 } }; struct key_type kt =3D { 0 }; struct key_parameters key_parameters =3D { 0 }; init_key_type(&kt, "AES-192-GCM", "none", true, false); @@ -924,13 +883,12 @@ assert_int_equal(key_parameters.cipher_size, 24); assert_int_equal(key_parameters.hmac_size, 12); - uint8_t exp_cipherkey[24] =3D - {0xed, 0x85, 0x33, 0xdb, 0x1c, 0x28, 0xac, 0xe4, - 0x18, 0xe9, 0x00, 0x6a, 0xb2, 0x9c, 0x17, 0x41, - 0x7d, 0x60, 0xeb, 0xe6, 0xcd, 0x90, 0xbf, 0x0a}; + uint8_t exp_cipherkey[24] =3D { 0xed, 0x85, 0x33, 0xdb, 0x1c, 0x28, 0x= ac, 0xe4, + 0x18, 0xe9, 0x00, 0x6a, 0xb2, 0x9c, 0x17= , 0x41, + 0x7d, 0x60, 0xeb, 0xe6, 0xcd, 0x90, 0xbf= , 0x0a }; - uint8_t exp_impl_iv[12] =3D - {0x86, 0x89, 0x0a, 0xab, 0xf0, 0x32, 0xcb, 0x59, 0xf4, 0xcf, 0xa3, 0x4= e}; + uint8_t exp_impl_iv[12] =3D { 0x86, 0x89, 0x0a, 0xab, 0xf0, 0x32, + 0xcb, 0x59, 0xf4, 0xcf, 0xa3, 0x4e }; assert_memory_equal(key_parameters.cipher, exp_cipherkey, sizeof(exp_c= ipherkey)); assert_memory_equal(key_parameters.hmac, exp_impl_iv, sizeof(exp_impl_= iv)); @@ -960,20 +918,16 @@ cmocka_unit_test(crypto_test_ovpn_expand_openssl3), cmocka_unit_test_prestate_setup_teardown(crypto_test_epoch_key_gen= eration, crypto_test_epoch_setup, - crypto_test_epoch_teardow= n, - &prestate_num16), + crypto_test_epoch_teardow= n, &prestate_num16), cmocka_unit_test_prestate_setup_teardown(crypto_test_epoch_key_rot= ation, crypto_test_epoch_setup, - crypto_test_epoch_teardow= n, - &prestate_num13), + crypto_test_epoch_teardow= n, &prestate_num13), cmocka_unit_test_prestate_setup_teardown(crypto_test_epoch_key_rec= eive_lookup, crypto_test_epoch_setup, - crypto_test_epoch_teardow= n, - &prestate_num13), + crypto_test_epoch_teardow= n, &prestate_num13), cmocka_unit_test_prestate_setup_teardown(crypto_test_epoch_key_ove= rflow, crypto_test_epoch_setup, - crypto_test_epoch_teardow= n, - &prestate_num32), + crypto_test_epoch_teardow= n, &prestate_num32), cmocka_unit_test(epoch_test_derive_data_key) }; diff --git a/tests/unit_tests/openvpn/test_cryptoapi.c b/tests/unit_tests/o= penvpn/test_cryptoapi.c index 072cc78..0cfc952 100644 --- a/tests/unit_tests/openvpn/test_cryptoapi.c +++ b/tests/unit_tests/openvpn/test_cryptoapi.c @@ -31,7 +31,7 @@ #include "xkey_common.h" #include "cert_data.h" -#if defined(HAVE_XKEY_PROVIDER) && defined (ENABLE_CRYPTOAPI) +#if defined(HAVE_XKEY_PROVIDER) && defined(ENABLE_CRYPTOAPI) #include #include #include @@ -42,19 +42,18 @@ #include "test_common.h" #include -#include /* pull-in the whole file to test static functions = */ +#include /* pull-in the whole file to test static fu= nctions */ struct management *management; /* global */ static OSSL_PROVIDER *prov[2]; /* mock a management function that xkey_provider needs */ char * -management_query_pk_sig(struct management *man, const char *b64_data, - const char *algorithm) +management_query_pk_sig(struct management *man, const char *b64_data, cons= t char *algorithm) { - (void) man; - (void) b64_data; - (void) algorithm; + (void)man; + (void)b64_data; + (void)algorithm; return NULL; } @@ -73,14 +72,12 @@ OSSL_LIB_CTX *tls_libctx; #ifndef _countof -#define _countof(x) sizeof((x))/sizeof(*(x)) +#define _countof(x) sizeof((x)) / sizeof(*(x)) #endif /* test data */ -static const uint8_t test_hash[] =3D { - 0x77, 0x38, 0x65, 0x00, 0x1e, 0x96, 0x48, 0xc6, 0x57, 0x0b, 0xae, - 0xc0, 0xb7, 0x96, 0xf9, 0x66, 0x4d, 0x5f, 0xd0, 0xb7 -}; +static const uint8_t test_hash[] =3D { 0x77, 0x38, 0x65, 0x00, 0x1e, 0x96,= 0x48, 0xc6, 0x57, 0x0b, + 0xae, 0xc0, 0xb7, 0x96, 0xf9, 0x66, 0= x4d, 0x5f, 0xd0, 0xb7 }; /* valid test strings to test with and without embedded and trailing space= s */ static const char *valid_str[] =3D { @@ -101,13 +98,13 @@ */ static struct test_cert { - const char *const cert; /* certificate as PEM */ - const char *const key; /* key as unencrypted PEM */ - const char *const cname; /* common-name */ - const char *const issuer; /* issuer common-name */ - const char *const friendly_name; /* identifies certs loaded to the = store -- keep unique */ - const char *hash; /* SHA1 fingerprint */ - int valid; /* nonzero if certificate has not = expired */ + const char *const cert; /* certificate as PEM */ + const char *const key; /* key as unencrypted PEM */ + const char *const cname; /* common-name */ + const char *const issuer; /* issuer common-name */ + const char *const friendly_name; /* identifies certs loaded to the sto= re -- keep unique */ + const char *hash; /* SHA1 fingerprint */ + int valid; /* nonzero if certificate has not exp= ired */ } certs[5]; static bool certs_loaded; @@ -118,11 +115,11 @@ init_cert_data(void) { struct test_cert certs_local[] =3D { - {cert1, key1, cname1, "OVPN TEST CA1", "OVPN Test Cert 1", ha= sh1, 1}, - {cert2, key2, cname2, "OVPN TEST CA2", "OVPN Test Cert 2", ha= sh2, 1}, - {cert3, key3, cname3, "OVPN TEST CA1", "OVPN Test Cert 3", ha= sh3, 1}, - {cert4, key4, cname4, "OVPN TEST CA2", "OVPN Test Cert 4", ha= sh4, 0}, - {0} + { cert1, key1, cname1, "OVPN TEST CA1", "OVPN Test Cert 1", hash1,= 1 }, + { cert2, key2, cname2, "OVPN TEST CA2", "OVPN Test Cert 2", hash2,= 1 }, + { cert3, key3, cname3, "OVPN TEST CA1", "OVPN Test Cert 3", hash3,= 1 }, + { cert4, key4, cname4, "OVPN TEST CA2", "OVPN Test Cert 4", hash4,= 0 }, + { 0 } }; assert(sizeof(certs_local) =3D=3D sizeof(certs)); memcpy(certs, certs_local, sizeof(certs_local)); @@ -144,20 +141,21 @@ static void import_certs(void **state) { - (void) state; + (void)state; if (certs_loaded) { return; } init_cert_data(); - user_store =3D CertOpenStore(CERT_STORE_PROV_SYSTEM, 0, 0, CERT_SYSTEM= _STORE_CURRENT_USER - |CERT_STORE_OPEN_EXISTING_FLAG, L"MY"); + user_store =3D + CertOpenStore(CERT_STORE_PROV_SYSTEM, 0, 0, + CERT_SYSTEM_STORE_CURRENT_USER | CERT_STORE_OPEN_EXI= STING_FLAG, L"MY"); assert_non_null(user_store); for (struct test_cert *c =3D certs; c->cert; c++) { /* Convert PEM cert & key to pkcs12 and import */ - const char *pass =3D "opensesame"; /* some password */ - const wchar_t *wpass =3D L"opensesame"; /* same as a wide string= */ + const char *pass =3D "opensesame"; /* some password */ + const wchar_t *wpass =3D L"opensesame"; /* same as a wide string */ X509 *x509 =3D NULL; EVP_PKEY *pkey =3D NULL; @@ -191,7 +189,7 @@ return; } - CRYPT_DATA_BLOB blob =3D {.cbData =3D 0, .pbData =3D NULL}; + CRYPT_DATA_BLOB blob =3D { .cbData =3D 0, .pbData =3D NULL }; int len =3D i2d_PKCS12(p12, &blob.pbData); /* pbData will be alloc= ated by OpenSSL */ if (len <=3D 0) { @@ -200,7 +198,7 @@ } blob.cbData =3D len; - DWORD flags =3D PKCS12_ALLOW_OVERWRITE_KEY|PKCS12_ALWAYS_CNG_KSP; + DWORD flags =3D PKCS12_ALLOW_OVERWRITE_KEY | PKCS12_ALWAYS_CNG_KSP; HCERTSTORE tmp_store =3D PFXImportCertStore(&blob, wpass, flags); PKCS12_free(p12); OPENSSL_free(blob.pbData); @@ -228,7 +226,7 @@ static int cleanup(void **state) { - (void) state; + (void)state; struct gc_arena gc =3D gc_new(); if (user_store) /* delete all certs we imported */ { @@ -260,7 +258,7 @@ static void test_find_cert_bythumb(void **state) { - (void) state; + (void)state; char select_string[64]; struct gc_arena gc =3D gc_new(); const CERT_CONTEXT *ctx; @@ -293,7 +291,7 @@ static void test_find_cert_byname(void **state) { - (void) state; + (void)state; char select_string[64]; struct gc_arena gc =3D gc_new(); const CERT_CONTEXT *ctx; @@ -326,7 +324,7 @@ static void test_find_cert_byissuer(void **state) { - (void) state; + (void)state; char select_string[64]; struct gc_arena gc =3D gc_new(); const CERT_CONTEXT *ctx; @@ -359,7 +357,7 @@ static int setup_xkey_provider(void **state) { - (void) state; + (void)state; /* Initialize providers in a way matching what OpenVPN core does */ tls_libctx =3D OSSL_LIB_CTX_new(); prov[0] =3D OSSL_PROVIDER_load(tls_libctx, "default"); @@ -374,7 +372,7 @@ static int teardown_xkey_provider(void **state) { - (void) state; + (void)state; for (size_t i =3D 0; i < _countof(prov); i++) { if (prov[i]) @@ -396,7 +394,7 @@ void test_cryptoapi_sign(void **state) { - (void) state; + (void)state; char select_string[64]; X509 *x509 =3D NULL; EVP_PKEY *privkey =3D NULL; @@ -430,7 +428,7 @@ void test_ssl_ctx_use_cryptoapicert(void **state) { - (void) state; + (void)state; char select_string[64]; import_certs(state); /* a no-op if already imported */ @@ -454,7 +452,8 @@ /* Use OpenSSL to check that the cert and private key in ssl_ctx "= match" */ if (!SSL_CTX_check_private_key(ssl_ctx)) { - fail_msg("Certificate and private key in ssl_ctx do not match = for <%s>", c->friendly_name); + fail_msg("Certificate and private key in ssl_ctx do not match = for <%s>", + c->friendly_name); return; } @@ -466,7 +465,7 @@ test_parse_hexstring(void **state) { unsigned char hash[255]; - (void) state; + (void)state; for (int i =3D 0; i < _countof(valid_str); i++) { @@ -512,4 +511,4 @@ return 0; } -#endif /* ifdef HAVE_XKEY_PROVIDER */ +#endif /* ifdef HAVE_XKEY_PROVIDER */ diff --git a/tests/unit_tests/openvpn/test_misc.c b/tests/unit_tests/openvp= n/test_misc.c index fb46e99..1857922 100644 --- a/tests/unit_tests/openvpn/test_misc.c +++ b/tests/unit_tests/openvpn/test_misc.c @@ -44,14 +44,18 @@ { struct gc_arena gc =3D gc_new(); - const char *input =3D "V4,dev-type tun,link-mtu 1457,tun-mtu 1400,prot= o UDPv4,auth SHA1,keysize 128,key-method 2,tls-server"; + const char *input =3D + "V4,dev-type tun,link-mtu 1457,tun-mtu 1400,proto UDPv4,auth SHA1,= keysize 128,key-method 2,tls-server"; const char *output =3D options_string_compat_lzo(input, &gc); - assert_string_equal(output, "V4,dev-type tun,link-mtu 1458,tun-mtu 140= 0,proto UDPv4,auth SHA1,keysize 128,key-method 2,tls-server,comp-lzo"); + assert_string_equal( + output, + "V4,dev-type tun,link-mtu 1458,tun-mtu 1400,proto UDPv4,auth SHA1,= keysize 128,key-method 2,tls-server,comp-lzo"); /* This string is has a much too small link-mtu so we should fail on i= t" */ - input =3D "V4,dev-type tun,link-mtu 2,tun-mtu 1400,proto UDPv4,auth SH= A1,keysize 128,key-method 2,tls-server"; + input =3D + "V4,dev-type tun,link-mtu 2,tun-mtu 1400,proto UDPv4,auth SHA1,key= size 128,key-method 2,tls-server"; output =3D options_string_compat_lzo(input, &gc); @@ -64,11 +68,14 @@ assert_string_equal(input, output); - input =3D "V4,dev-type tun,link-mtu 999,tun-mtu 1400,proto UDPv4,auth = SHA1,keysize 128,key-method 2,tls-server"; + input =3D + "V4,dev-type tun,link-mtu 999,tun-mtu 1400,proto UDPv4,auth SHA1,k= eysize 128,key-method 2,tls-server"; output =3D options_string_compat_lzo(input, &gc); /* 999 -> 1000, 3 to 4 chars */ - assert_string_equal(output, "V4,dev-type tun,link-mtu 1000,tun-mtu 140= 0,proto UDPv4,auth SHA1,keysize 128,key-method 2,tls-server,comp-lzo"); + assert_string_equal( + output, + "V4,dev-type tun,link-mtu 1000,tun-mtu 1400,proto UDPv4,auth SHA1,= keysize 128,key-method 2,tls-server,comp-lzo"); gc_free(&gc); } @@ -110,7 +117,6 @@ } - struct word { const char *word; @@ -121,7 +127,7 @@ static uint32_t word_hash_function(const void *key, uint32_t iv) { - const char *str =3D (const char *) key; + const char *str =3D (const char *)key; const int len =3D strlen(str); return hash_func((const uint8_t *)str, len, iv); } @@ -161,11 +167,10 @@ static void test_list(void **state) { - -/* - * Test the hash code by implementing a simple - * word frequency algorithm. - */ + /* + * Test the hash code by implementing a simple + * word frequency algorithm. + */ struct gc_arena gc =3D gc_new(); struct hash *hash =3D hash_init(10000, get_random(), word_hash_functio= n, word_compare_function); @@ -174,7 +179,7 @@ printf("hash_init n_buckets=3D%d mask=3D0x%08x\n", hash->n_buckets, ha= sh->mask); =20 char wordfile[PATH_MAX] =3D { 0 }; - openvpn_test_get_srcdir_dir(wordfile, PATH_MAX, "/../../../COPYRIGHT.G= PL" ); + openvpn_test_get_srcdir_dir(wordfile, PATH_MAX, "/../../../COPYRIGHT.G= PL"); FILE *words =3D fopen(wordfile, "r"); assert_non_null(words); @@ -200,7 +205,7 @@ c =3D buf[bi++]; if (isalnum(c) || c =3D=3D '_') { - assert_true(wbi < (int) sizeof(wordbuf)); + assert_true(wbi < (int)sizeof(wordbuf)); wordbuf[wbi++] =3D c; } else @@ -209,13 +214,13 @@ { wordcount++; - ASSERT(wbi < (int) sizeof(wordbuf)); + ASSERT(wbi < (int)sizeof(wordbuf)); wordbuf[wbi++] =3D '\0'; /* word is parsed from stdin */ /* does it already exist in table? */ - struct word *w =3D (struct word *) hash_lookup(hash, w= ordbuf); + struct word *w =3D (struct word *)hash_lookup(hash, wo= rdbuf); if (w) { @@ -230,13 +235,13 @@ w->word =3D string_alloc(wordbuf, &gc); w->n =3D 1; assert_true(hash_add(hash, w->word, w, false)); - assert_true(hash_add(nhash, w->word, (void *) ((pt= r_type )(random() & 0x0F) + 1), false)); + assert_true(hash_add(nhash, w->word, + (void *)((ptr_type)(random() = & 0x0F) + 1), false)); } } wbi =3D 0; } - } - while (c); + } while (c); } assert_int_equal(wordcount, 2971); @@ -261,7 +266,7 @@ while ((he =3D hash_iterator_next(&hi))) { - struct word *w =3D (struct word *) he->value; + struct word *w =3D (struct word *)he->value; /*printf("%6d '%s'\n", w->n, w->word); */ ++count; /* check a few words to match prior results */ @@ -269,19 +274,19 @@ { assert_int_equal(w->n, 49); } - else if (!strcmp(w->word, "redistribute")) + else if (!strcmp(w->word, "redistribute")) { assert_int_equal(w->n, 5); } - else if (!strcmp(w->word, "circumstances")) + else if (!strcmp(w->word, "circumstances")) { assert_int_equal(w->n, 1); } - else if (!strcmp(w->word, "so")) + else if (!strcmp(w->word, "so")) { assert_int_equal(w->n, 8); } - else if (!strcmp(w->word, "BECAUSE")) + else if (!strcmp(w->word, "BECAUSE")) { assert_int_equal(w->n, 1); } @@ -296,12 +301,12 @@ { for (ptr_type i =3D 1; i <=3D 16; ++i) { - struct hash_element *item =3D hash_lookup_by_value(nhash, (voi= d *) i); - hash_remove_by_value(nhash, (void *) i); + struct hash_element *item =3D hash_lookup_by_value(nhash, (voi= d *)i); + hash_remove_by_value(nhash, (void *)i); /* check item got removed if it was present before */ if (item) { - assert_null(hash_lookup_by_value(nhash, (void *) i)); + assert_null(hash_lookup_by_value(nhash, (void *)i)); } } } @@ -378,14 +383,12 @@ mock_set_debug_level(saved_log_level); } -const struct CMUnitTest misc_tests[] =3D { - cmocka_unit_test(test_compat_lzo_string), - cmocka_unit_test(test_auth_fail_temp_no_flags), - cmocka_unit_test(test_auth_fail_temp_flags), - cmocka_unit_test(test_auth_fail_temp_flags_msg), - cmocka_unit_test(test_list), - cmocka_unit_test(test_atoi_variants) -}; +const struct CMUnitTest misc_tests[] =3D { cmocka_unit_test(test_compat_lz= o_string), + cmocka_unit_test(test_auth_fail_t= emp_no_flags), + cmocka_unit_test(test_auth_fail_t= emp_flags), + cmocka_unit_test(test_auth_fail_t= emp_flags_msg), + cmocka_unit_test(test_list), + cmocka_unit_test(test_atoi_varian= ts) }; int main(void) diff --git a/tests/unit_tests/openvpn/test_ncp.c b/tests/unit_tests/openvpn= /test_ncp.c index 941216a..0a1c774 100644 --- a/tests/unit_tests/openvpn/test_ncp.c +++ b/tests/unit_tests/openvpn/test_ncp.c @@ -46,8 +46,7 @@ /* Define this function here as dummy since including the ssl_*.c files * leads to having to include even more unrelated code */ bool -key_state_export_keying_material(struct tls_session *session, - const char *label, size_t label_size, +key_state_export_keying_material(struct tls_session *session, const char *= label, size_t label_size, void *ekm, size_t ekm_size) { ASSERT(0); @@ -72,8 +71,7 @@ bool have_blowfish =3D cipher_valid("BF-CBC"); assert_string_equal(mutate_ncp_cipher_list("none", &gc), "none"); - assert_string_equal(mutate_ncp_cipher_list("AES-256-GCM:none", &gc), - "AES-256-GCM:none"); + assert_string_equal(mutate_ncp_cipher_list("AES-256-GCM:none", &gc), "= AES-256-GCM:none"); assert_string_equal(mutate_ncp_cipher_list(aes_ciphers, &gc), aes_ciph= ers); @@ -85,8 +83,7 @@ if (have_chacha && have_blowfish) { assert_string_equal(mutate_ncp_cipher_list(bf_chacha, &gc), bf_cha= cha); - assert_string_equal(mutate_ncp_cipher_list("BF-CBC:CHACHA20-POLY13= 05", &gc), - bf_chacha); + assert_string_equal(mutate_ncp_cipher_list("BF-CBC:CHACHA20-POLY13= 05", &gc), bf_chacha); } else { @@ -98,14 +95,14 @@ aes_ciphers); /* Check that optional ciphers work */ - assert_string_equal(mutate_ncp_cipher_list("?AES-256-GCM:?AES-128-GCM"= , &gc), - aes_ciphers); + assert_string_equal(mutate_ncp_cipher_list("?AES-256-GCM:?AES-128-GCM"= , &gc), aes_ciphers); /* All unsupported should still yield an empty list */ assert_ptr_equal(mutate_ncp_cipher_list("?kugelfisch:?grasshopper", &g= c), NULL); /* If the last is optional, previous invalid ciphers should be ignored= */ - assert_ptr_equal(mutate_ncp_cipher_list("Vollbit:Littlebit:AES-256-CBC= :BF-CBC:?nixbit", &gc), NULL); + assert_ptr_equal(mutate_ncp_cipher_list("Vollbit:Littlebit:AES-256-CBC= :BF-CBC:?nixbit", &gc), + NULL); /* We do not support CCM ciphers */ assert_ptr_equal(mutate_ncp_cipher_list("AES-256-GCM:AES-128-CCM", &gc= ), NULL); @@ -126,19 +123,19 @@ assert_ptr_equal(mutate_ncp_cipher_list("AES-256-GCM:vollbit", &gc), N= ULL); assert_ptr_equal(mutate_ncp_cipher_list("", &gc), NULL); - assert_ptr_equal(mutate_ncp_cipher_list( - "ChaCha20-Poly1305:ChaCha20-Poly1305:ChaCha20-Pol= y1305:" - "ChaCha20-Poly1305:ChaCha20-Poly1305:ChaCha20-Pol= y1305:" - "ChaCha20-Poly1305", &gc), NULL); + assert_ptr_equal(mutate_ncp_cipher_list("ChaCha20-Poly1305:ChaCha20-Po= ly1305:ChaCha20-Poly1305:" + "ChaCha20-Poly1305:ChaCha20-Po= ly1305:ChaCha20-Poly1305:" + "ChaCha20-Poly1305", + &gc), + NULL); #ifdef ENABLE_CRYPTO_OPENSSL - assert_string_equal(mutate_ncp_cipher_list("id-aes128-GCM:id-aes256-GC= M", - &gc), "AES-128-GCM:AES-256-= GCM"); + assert_string_equal(mutate_ncp_cipher_list("id-aes128-GCM:id-aes256-GC= M", &gc), + "AES-128-GCM:AES-256-GCM"); #else if (have_blowfish) { - assert_string_equal(mutate_ncp_cipher_list("BLOWFISH-CBC", - &gc), "BF-CBC"); + assert_string_equal(mutate_ncp_cipher_list("BLOWFISH-CBC", &gc), "= BF-CBC"); } #endif gc_free(&gc); @@ -192,37 +189,28 @@ const char *serverlist =3D "CHACHA20_POLY1305:AES-128-GCM"; const char *serverlistbfcbc =3D "CHACHA20_POLY1305:AES-128-GCM:BF-CBC:= none"; - best_cipher =3D ncp_get_best_cipher(serverlist, - "IV_YOLO=3DNO\nIV_BAR=3D7", - "BF-CBC", &gc); + best_cipher =3D ncp_get_best_cipher(serverlist, "IV_YOLO=3DNO\nIV_BAR= =3D7", "BF-CBC", &gc); assert_ptr_equal(best_cipher, NULL); - best_cipher =3D ncp_get_best_cipher(serverlistbfcbc, - "IV_YOLO=3DNO\nIV_BAR=3D7", - "BF-CBC", &gc); + best_cipher =3D ncp_get_best_cipher(serverlistbfcbc, "IV_YOLO=3DNO\nIV= _BAR=3D7", "BF-CBC", &gc); assert_string_equal(best_cipher, "BF-CBC"); - best_cipher =3D ncp_get_best_cipher(serverlist, - "IV_NCP=3D1\nIV_BAR=3D7", - "AES-128-GCM", &gc); + best_cipher =3D ncp_get_best_cipher(serverlist, "IV_NCP=3D1\nIV_BAR=3D= 7", "AES-128-GCM", &gc); assert_string_equal(best_cipher, "AES-128-GCM"); - best_cipher =3D ncp_get_best_cipher(serverlist, NULL, - "AES-128-GCM", &gc); + best_cipher =3D ncp_get_best_cipher(serverlist, NULL, "AES-128-GCM", &= gc); assert_string_equal(best_cipher, "AES-128-GCM"); - best_cipher =3D ncp_get_best_cipher(serverlist, NULL, - "none", &gc); + best_cipher =3D ncp_get_best_cipher(serverlist, NULL, "none", &gc); assert_ptr_equal(best_cipher, NULL); - best_cipher =3D ncp_get_best_cipher(serverlistbfcbc, NULL, - "none", &gc); + best_cipher =3D ncp_get_best_cipher(serverlistbfcbc, NULL, "none", &gc= ); assert_string_equal(best_cipher, "none"); best_cipher =3D ncp_get_best_cipher(serverlist, NULL, NULL, &gc); @@ -240,28 +228,23 @@ const char *serverlist =3D "CHACHA20_POLY1305:AES-128-GCM:AES-256-GCM"; - best_cipher =3D ncp_get_best_cipher(serverlist, - "IV_YOLO=3DNO\nIV_NCP=3D2\nIV_BAR=3D= 7", - "BF-CBC", &gc); + best_cipher =3D ncp_get_best_cipher(serverlist, "IV_YOLO=3DNO\nIV_NCP= =3D2\nIV_BAR=3D7", "BF-CBC", &gc); assert_string_equal(best_cipher, "AES-128-GCM"); /* Best cipher is in --cipher of client */ - best_cipher =3D ncp_get_best_cipher(serverlist, "IV_NCP=3D2\nIV_BAR=3D= 7", - "CHACHA20_POLY1305", &gc); + best_cipher =3D ncp_get_best_cipher(serverlist, "IV_NCP=3D2\nIV_BAR=3D= 7", "CHACHA20_POLY1305", &gc); assert_string_equal(best_cipher, "CHACHA20_POLY1305"); /* Best cipher is in --cipher of client */ - best_cipher =3D ncp_get_best_cipher(serverlist, "IV_CIPHERS=3DAES-128-= GCM", - "AES-256-CBC", &gc); + best_cipher =3D ncp_get_best_cipher(serverlist, "IV_CIPHERS=3DAES-128-= GCM", "AES-256-CBC", &gc); assert_string_equal(best_cipher, "AES-128-GCM"); /* IV_NCP=3D2 should be ignored if IV_CIPHERS is sent */ - best_cipher =3D ncp_get_best_cipher(serverlist, - "IV_FOO=3D7\nIV_CIPHERS=3DAES-256-GC= M\nIV_NCP=3D2", + best_cipher =3D ncp_get_best_cipher(serverlist, "IV_FOO=3D7\nIV_CIPHER= S=3DAES-256-GCM\nIV_NCP=3D2", "AES-256-CBC", &gc); assert_string_equal(best_cipher, "AES-256-GCM"); @@ -312,11 +295,14 @@ if (have_chacha) { - assert_string_equal(o.ncp_ciphers, "BF-CBC:AES-256-GCM:AES-128-GCM= :CHACHA20-POLY1305:AES-128-CBC:AES-256-CBC"); + assert_string_equal( + o.ncp_ciphers, + "BF-CBC:AES-256-GCM:AES-128-GCM:CHACHA20-POLY1305:AES-128-CBC:= AES-256-CBC"); } else { - assert_string_equal(o.ncp_ciphers, "BF-CBC:AES-256-GCM:AES-128-GCM= :AES-128-CBC:AES-256-CBC"); + assert_string_equal(o.ncp_ciphers, + "BF-CBC:AES-256-GCM:AES-128-GCM:AES-128-CBC:AE= S-256-CBC"); } assert_string_equal(o.ncp_ciphers_conf, "BF-CBC:DEFAULT:AES-128-CBC:AE= S-256-CBC"); @@ -326,7 +312,8 @@ if (have_chacha) { - assert_string_equal(o.ncp_ciphers, "AES-256-GCM:AES-128-GCM:CHACHA= 20-POLY1305:AES-128-CBC:AES-192-CBC"); + assert_string_equal(o.ncp_ciphers, + "AES-256-GCM:AES-128-GCM:CHACHA20-POLY1305:AES= -128-CBC:AES-192-CBC"); } else { @@ -340,7 +327,8 @@ if (have_chacha) { - assert_string_equal(o.ncp_ciphers, "AES-192-GCM:AES-128-CBC:AES-25= 6-GCM:AES-128-GCM:CHACHA20-POLY1305"); + assert_string_equal(o.ncp_ciphers, + "AES-192-GCM:AES-128-CBC:AES-256-GCM:AES-128-G= CM:CHACHA20-POLY1305"); } else { @@ -355,7 +343,7 @@ test_ncp_expand(void **state) { bool have_chacha =3D cipher_valid("CHACHA20-POLY1305"); - struct options o =3D {0}; + struct options o =3D { 0 }; o.gc =3D gc_new(); struct gc_arena gc =3D gc_new(); diff --git a/tests/unit_tests/openvpn/test_networking.c b/tests/unit_tests/= openvpn/test_networking.c index 0434707..f2da83e 100644 --- a/tests/unit_tests/openvpn/test_networking.c +++ b/tests/unit_tests/openvpn/test_networking.c @@ -110,12 +110,10 @@ printf("\n"); return net_route_v4_add(NULL, &dst, prefixlen, NULL, iface, 0, metric); - } static int -net__route_v4_add_gw(const char *dst_str, int prefixlen, const char *gw_st= r, - int metric) +net__route_v4_add_gw(const char *dst_str, int prefixlen, const char *gw_st= r, int metric) { in_addr_t dst, gw; int ret; @@ -140,8 +138,7 @@ dst =3D ntohl(dst); gw =3D ntohl(gw); - printf("CMD: ip route add %s/%d dev %s via %s", dst_str, prefixlen, if= ace, - gw_str); + printf("CMD: ip route add %s/%d dev %s via %s", dst_str, prefixlen, if= ace, gw_str); if (metric > 0) { printf(" metric %d", metric); @@ -176,12 +173,10 @@ printf("\n"); return net_route_v6_add(NULL, &dst, prefixlen, NULL, iface, 0, metric); - } static int -net__route_v6_add_gw(const char *dst_str, int prefixlen, const char *gw_st= r, - int metric) +net__route_v6_add_gw(const char *dst_str, int prefixlen, const char *gw_st= r, int metric) { struct in6_addr dst, gw; int ret; @@ -203,8 +198,7 @@ return -1; } - printf("CMD: ip -6 route add %s/%d dev %s via %s", dst_str, prefixlen, - iface, gw_str); + printf("CMD: ip -6 route add %s/%d dev %s via %s", dst_str, prefixlen,= iface, gw_str); if (metric > 0) { printf(" metric %d", metric); diff --git a/tests/unit_tests/openvpn/test_packet_id.c b/tests/unit_tests/o= penvpn/test_packet_id.c index 084db5e..d623c3d 100644 --- a/tests/unit_tests/openvpn/test_packet_id.c +++ b/tests/unit_tests/openvpn/test_packet_id.c @@ -36,8 +36,10 @@ #include "reliable.h" #include "test_common.h" -struct test_packet_id_write_data { - struct { +struct test_packet_id_write_data +{ + struct + { uint32_t buf_id; uint32_t buf_time; } test_buf_data; @@ -49,15 +51,14 @@ static int test_packet_id_write_setup(void **state) { - struct test_packet_id_write_data *data =3D - calloc(1, sizeof(struct test_packet_id_write_data)); + struct test_packet_id_write_data *data =3D calloc(1, sizeof(struct tes= t_packet_id_write_data)); if (!data) { return -1; } - data->test_buf.data =3D (void *) &data->test_buf_data; + data->test_buf.data =3D (void *)&data->test_buf_data; data->test_buf.capacity =3D sizeof(data->test_buf_data); data->gc =3D gc_new(); @@ -162,7 +163,6 @@ static void test_get_num_output_sequenced_available(void **state) { - struct reliable *rel =3D malloc(sizeof(struct reliable)); reliable_init(rel, 100, 50, 8, false); @@ -180,14 +180,14 @@ /* test ids close to int/unsigned int barrier */ rel->array[5].active =3D true; - rel->array[5].packet_id =3D (0x80000000u -3); + rel->array[5].packet_id =3D (0x80000000u - 3); rel->array[6].active =3D false; - rel->packet_id =3D (0x80000000u -1); + rel->packet_id =3D (0x80000000u - 1); assert_int_equal(6, reliable_get_num_output_sequenced_available(rel)); rel->array[5].active =3D true; - rel->array[5].packet_id =3D (0x80000000u -3); + rel->array[5].packet_id =3D (0x80000000u - 3); rel->packet_id =3D 0x80000001u; assert_int_equal(4, reliable_get_num_output_sequenced_available(rel)); @@ -195,7 +195,7 @@ /* test wrapping */ rel->array[5].active =3D true; - rel->array[5].packet_id =3D (0xffffffffu -3); + rel->array[5].packet_id =3D (0xffffffffu - 3); rel->array[6].active =3D false; rel->packet_id =3D (0xffffffffu - 1); @@ -223,7 +223,7 @@ assert_true(packet_id_write_epoch(&data->pis, 0x23, &buf)); assert_int_equal(buf.len, 8); - uint8_t expected_header[8] =3D { 0x00, 0x23, 0, 0, 0, 0, 0, 1}; + uint8_t expected_header[8] =3D { 0x00, 0x23, 0, 0, 0, 0, 0, 1 }; assert_memory_equal(BPTR(&buf), expected_header, 8); /* too small buffer should error out */ @@ -234,7 +234,7 @@ data->pis.id =3D 0xfa079ab9d2e8; struct buffer buf_48 =3D alloc_buf_gc(128, &data->gc); assert_true(packet_id_write_epoch(&data->pis, 0xfffe, &buf_48)); - uint8_t expected_header_48[8] =3D { 0xff, 0xfe, 0xfa, 0x07, 0x9a, 0xb9= , 0xd2, 0xe9}; + uint8_t expected_header_48[8] =3D { 0xff, 0xfe, 0xfa, 0x07, 0x9a, 0xb9= , 0xd2, 0xe9 }; assert_memory_equal(BPTR(&buf_48), expected_header_48, 8); /* test writing/checking the 48 bit per epoch packet counter @@ -242,7 +242,7 @@ data->pis.id =3D 0xfffffffffffe; struct buffer buf_of =3D alloc_buf_gc(128, &data->gc); assert_true(packet_id_write_epoch(&data->pis, 0xf00f, &buf_of)); - uint8_t expected_header_of[8] =3D { 0xf0, 0x0f, 0xff, 0xff, 0xff, 0xff= , 0xff, 0xff}; + uint8_t expected_header_of[8] =3D { 0xf0, 0x0f, 0xff, 0xff, 0xff, 0xff= , 0xff, 0xff }; assert_memory_equal(BPTR(&buf_of), expected_header_of, 8); /* This is go over 2^48 - 1 and should error out. */ @@ -264,9 +264,9 @@ static void test_copy_acks_to_lru(void **state) { - struct reliable_ack ack =3D { .len =3D 4, .packet_id =3D {2, 1, 3, 2} = }; + struct reliable_ack ack =3D { .len =3D 4, .packet_id =3D { 2, 1, 3, 2 = } }; - struct reliable_ack mru_ack =3D {0 }; + struct reliable_ack mru_ack =3D { 0 }; /* Test copying to empty ack structure */ copy_acks_to_mru(&ack, &mru_ack, 4); @@ -292,7 +292,7 @@ /* Adding just two packets shoudl ignore the 42 in array and * reorder the order in the MRU */ - struct reliable_ack ack2 =3D { .len =3D 3, .packet_id =3D {3, 2, 42} }; + struct reliable_ack ack2 =3D { .len =3D 3, .packet_id =3D { 3, 2, 42 }= }; copy_acks_to_mru(&ack2, &mru_ack2, 2); assert_int_equal(mru_ack2.packet_id[0], 3); assert_int_equal(mru_ack2.packet_id[1], 2); @@ -313,12 +313,12 @@ assert_int_equal(mru_ack.packet_id[1], 1); assert_int_equal(mru_ack.packet_id[2], 3); - struct reliable_ack ack3 =3D { .len =3D 7, .packet_id =3D {5, 6, 7, 8,= 9, 10, 11}}; + struct reliable_ack ack3 =3D { .len =3D 7, .packet_id =3D { 5, 6, 7, 8= , 9, 10, 11 } }; /* Adding multiple acks tests if the a full array is handled correctly= */ copy_acks_to_mru(&ack3, &mru_ack, 7); - struct reliable_ack expected_ack =3D { .len =3D 8, .packet_id =3D {5, = 6, 7, 8, 9, 10, 11, 2}}; + struct reliable_ack expected_ack =3D { .len =3D 8, .packet_id =3D { 5,= 6, 7, 8, 9, 10, 11, 2 } }; assert_int_equal(mru_ack.len, expected_ack.len); assert_memory_equal(mru_ack.packet_id, expected_ack.packet_id, sizeof(= expected_ack.packet_id)); @@ -329,26 +329,19 @@ { openvpn_unit_test_setup(); const struct CMUnitTest tests[] =3D { - cmocka_unit_test_setup_teardown(test_packet_id_write_short, - test_packet_id_write_setup, + cmocka_unit_test_setup_teardown(test_packet_id_write_short, test_p= acket_id_write_setup, test_packet_id_write_teardown), - cmocka_unit_test_setup_teardown(test_packet_id_write_long, - test_packet_id_write_setup, + cmocka_unit_test_setup_teardown(test_packet_id_write_long, test_pa= cket_id_write_setup, test_packet_id_write_teardown), cmocka_unit_test_setup_teardown(test_packet_id_write_short_prepend, - test_packet_id_write_setup, - test_packet_id_write_teardown), + test_packet_id_write_setup, test_p= acket_id_write_teardown), cmocka_unit_test_setup_teardown(test_packet_id_write_long_prepend, - test_packet_id_write_setup, + test_packet_id_write_setup, test_p= acket_id_write_teardown), + cmocka_unit_test_setup_teardown(test_packet_id_write_short_wrap, t= est_packet_id_write_setup, test_packet_id_write_teardown), - cmocka_unit_test_setup_teardown(test_packet_id_write_short_wrap, - test_packet_id_write_setup, + cmocka_unit_test_setup_teardown(test_packet_id_write_long_wrap, te= st_packet_id_write_setup, test_packet_id_write_teardown), - cmocka_unit_test_setup_teardown(test_packet_id_write_long_wrap, - test_packet_id_write_setup, - test_packet_id_write_teardown), - cmocka_unit_test_setup_teardown(test_packet_id_write_epoch, - test_packet_id_write_setup, + cmocka_unit_test_setup_teardown(test_packet_id_write_epoch, test_p= acket_id_write_setup, test_packet_id_write_teardown), cmocka_unit_test(test_get_num_output_sequenced_available), diff --git a/tests/unit_tests/openvpn/test_pkcs11.c b/tests/unit_tests/open= vpn/test_pkcs11.c index 591a457..56125df 100644 --- a/tests/unit_tests/openvpn/test_pkcs11.c +++ b/tests/unit_tests/openvpn/test_pkcs11.c @@ -39,8 +39,8 @@ #include "test_common.h" =20 #define token_name "Test Token" -#define PIN "12345" -#define HASHSIZE 20 +#define PIN "12345" +#define HASHSIZE 20 struct management *management; /* global */ @@ -58,8 +58,8 @@ /* stubs for some unused functions instead of pulling in too many dependen= cies */ int -parse_line(const char *line, char **p, const int n, const char *file, - const int line_num, int msglevel, struct gc_arena *gc) +parse_line(const char *line, char **p, const int n, const char *file, cons= t int line_num, + int msglevel, struct gc_arena *gc) { assert_true(0); return 0; @@ -91,45 +91,43 @@ void query_user_add(char *prompt, size_t prompt_len, char *resp, size_t resp_le= n, bool echo) { - (void) prompt; - (void) prompt_len; - (void) resp; - (void) resp_len; - (void) echo; + (void)prompt; + (void)prompt_len; + (void)resp; + (void)resp_len; + (void)echo; assert_true(0); } void purge_user_pass(struct user_pass *up, const bool force) { - (void) force; + (void)force; secure_memzero(up, sizeof(*up)); } char * -management_query_pk_sig(struct management *man, const char *b64_data, - const char *algorithm) +management_query_pk_sig(struct management *man, const char *b64_data, cons= t char *algorithm) { - (void) man; - (void) b64_data; - (void) algorithm; + (void)man; + (void)b64_data; + (void)algorithm; return NULL; } -int -digest_sign_verify(EVP_PKEY *privkey, EVP_PKEY *pubkey); +int digest_sign_verify(EVP_PKEY *privkey, EVP_PKEY *pubkey); /* Test certificate database: data for cert1, cert2 .. key1, key2 etc. * are defined in cert_data.h */ static struct test_cert { - const char *const cert; /* certificate as PEM */ - const char *const key; /* key as unencrypted PEM */ - const char *const cname; /* common-name */ - const char *const issuer; /* issuer common-name */ - const char *const friendly_name; /* identifies certs loaded to the = store -- keep unique */ - uint8_t hash[HASHSIZE]; /* SHA1 fingerprint: computed and = filled in later */ - char *p11_id; /* PKCS#11 id -- filled in later */ + const char *const cert; /* certificate as PEM */ + const char *const key; /* key as unencrypted PEM */ + const char *const cname; /* common-name */ + const char *const issuer; /* issuer common-name */ + const char *const friendly_name; /* identifies certs loaded to the sto= re -- keep unique */ + uint8_t hash[HASHSIZE]; /* SHA1 fingerprint: computed and fil= led in later */ + char *p11_id; /* PKCS#11 id -- filled in later */ } certs[5]; static bool pkcs11_id_management; @@ -144,11 +142,11 @@ init_cert_data(void) { struct test_cert certs_local[] =3D { - {cert1, key1, cname1, "OVPN TEST CA1", "OVPN Test Cert 1", {0= }, NULL}, - {cert2, key2, cname2, "OVPN TEST CA2", "OVPN Test Cert 2", {0= }, NULL}, - {cert3, key3, cname3, "OVPN TEST CA1", "OVPN Test Cert 3", {0= }, NULL}, - {cert4, key4, cname4, "OVPN TEST CA2", "OVPN Test Cert 4", {0= }, NULL}, - {0} + { cert1, key1, cname1, "OVPN TEST CA1", "OVPN Test Cert 1", { 0 },= NULL }, + { cert2, key2, cname2, "OVPN TEST CA2", "OVPN Test Cert 2", { 0 },= NULL }, + { cert3, key3, cname3, "OVPN TEST CA1", "OVPN Test Cert 3", { 0 },= NULL }, + { cert4, key4, cname4, "OVPN TEST CA2", "OVPN Test Cert 4", { 0 },= NULL }, + { 0 } }; assert(sizeof(certs_local) =3D=3D sizeof(certs)); memcpy(certs, certs_local, sizeof(certs_local)); @@ -159,9 +157,9 @@ get_user_pass_cr(struct user_pass *up, const char *auth_file, const char *= prefix, const unsigned int flags, const char *unused) { - (void) unused; + (void)unused; bool ret =3D true; - if (!strcmp(prefix, "pkcs11-id-request") && flags&GET_USER_PASS_NEED_S= TR) + if (!strcmp(prefix, "pkcs11-id-request") && flags & GET_USER_PASS_NEED= _STR) { assert_true(pkcs11_id_management); strncpynt(up->password, pkcs11_id_current, sizeof(up->password)); @@ -195,15 +193,16 @@ static int init(void **state) { - (void) state; + (void)state; - umask(0077); /* ensure all files and directories we create get user o= nly access */ + umask(0077); /* ensure all files and directories we create get user on= ly access */ char config[256]; init_cert_data(); if (!mkdtemp(softhsm2_tokens_path)) { - fail_msg("make tmpdir using template <%s> failed (error =3D %d)", = softhsm2_tokens_path, errno); + fail_msg("make tmpdir using template <%s> failed (error =3D %d)", = softhsm2_tokens_path, + errno); } int fd =3D mkstemp(softhsm2_conf_path); @@ -211,8 +210,7 @@ { fail_msg("make tmpfile using template <%s> failed (error =3D %d)",= softhsm2_conf_path, errno); } - snprintf(config, sizeof(config), "directories.tokendir=3D%s/", - softhsm2_tokens_path); + snprintf(config, sizeof(config), "directories.tokendir=3D%s/", softhsm= 2_tokens_path); assert_int_equal(write(fd, config, strlen(config)), strlen(config)); close(fd); @@ -260,14 +258,16 @@ argv_free(&a); a =3D argv_new(); /* Use numcerts+1 as a unique id of the object -- same id for mat= ching cert and key */ - argv_printf(&a, "%s --provider %s --load-certificate %s --label \"= %s\" --id %08x --login --write", - P11TOOL_PATH, SOFTHSM2_MODULE_PATH, cert, c->friendly_= name, num_certs+1); + argv_printf( + &a, "%s --provider %s --load-certificate %s --label \"%s\" --i= d %08x --login --write", + P11TOOL_PATH, SOFTHSM2_MODULE_PATH, cert, c->friendly_name, nu= m_certs + 1); assert_true(openvpn_execve_check(&a, es, 0, "Failed to upload cert= ificate into token")); argv_free(&a); a =3D argv_new(); - argv_printf(&a, "%s --provider %s --load-privkey %s --label \"%s\"= --id %08x --login --write", - P11TOOL_PATH, SOFTHSM2_MODULE_PATH, key, c->friendly_n= ame, num_certs+1); + argv_printf(&a, + "%s --provider %s --load-privkey %s --label \"%s\" --i= d %08x --login --write", + P11TOOL_PATH, SOFTHSM2_MODULE_PATH, key, c->friendly_n= ame, num_certs + 1); assert_true(openvpn_execve_check(&a, es, 0, "Failed to upload key = into token")); assert_int_equal(ftruncate(cert_fd, 0), 0); @@ -288,7 +288,7 @@ static int cleanup(void **state) { - (void) state; + (void)state; struct argv a =3D argv_new(); argv_printf(&a, "%s --delete-token --token \"%s\"", SOFTHSM2_UTIL_PATH= , token_name); @@ -410,7 +410,7 @@ static void test_tls_ctx_use_pkcs11(void **state) { - (void) state; + (void)state; struct tls_root_ctx tls_ctx =3D {}; uint8_t sha1[HASHSIZE]; for (struct test_cert *c =3D certs; c->cert; c++) @@ -451,7 +451,8 @@ #else if (!SSL_CTX_check_private_key(tls_ctx.ctx)) { - fail_msg("Certificate and private key in ssl_ctx do not match = for <%s>", c->friendly_name); + fail_msg("Certificate and private key in ssl_ctx do not match = for <%s>", + c->friendly_name); return; } #endif @@ -472,10 +473,8 @@ { openvpn_unit_test_setup(); const struct CMUnitTest tests[] =3D { - cmocka_unit_test_setup_teardown(test_pkcs11_ids, setup_pkcs11, - teardown_pkcs11), - cmocka_unit_test_setup_teardown(test_tls_ctx_use_pkcs11, setup_pkc= s11, - teardown_pkcs11), + cmocka_unit_test_setup_teardown(test_pkcs11_ids, setup_pkcs11, tea= rdown_pkcs11), + cmocka_unit_test_setup_teardown(test_tls_ctx_use_pkcs11, setup_pkc= s11, teardown_pkcs11), cmocka_unit_test_setup_teardown(test_tls_ctx_use_pkcs11__managemen= t, setup_pkcs11, teardown_pkcs11), }; diff --git a/tests/unit_tests/openvpn/test_pkt.c b/tests/unit_tests/openvpn= /test_pkt.c index 46206fe..3823d39 100644 --- a/tests/unit_tests/openvpn/test_pkt.c +++ b/tests/unit_tests/openvpn/test_pkt.c @@ -44,8 +44,8 @@ #include "reliable.h" int -parse_line(const char *line, char **p, const int n, const char *file, - const int line_num, int msglevel, struct gc_arena *gc) +parse_line(const char *line, char **p, const int n, const char *file, cons= t int line_num, + int msglevel, struct gc_arena *gc) { /* Dummy function to get the linker happy, should never be called */ assert_true(false); @@ -55,8 +55,7 @@ /* Define this function here as dummy since including the ssl_*.c files * leads to having to include even more unrelated code */ bool -key_state_export_keying_material(struct tls_session *session, - const char *label, size_t label_size, +key_state_export_keying_material(struct tls_session *session, const char *= label, size_t label_size, void *ekm, size_t ekm_size) { ASSERT(0); @@ -89,104 +88,73 @@ "-----END OpenVPN Static key V1-----\n" "\n"; -const uint8_t client_reset_v2_none[] =3D -{ 0x38, 0x68, 0x91, 0x92, 0x3f, 0xa3, 0x10, 0x34, - 0x37, 0x00, 0x00, 0x00, 0x00, 0x00 }; +const uint8_t client_reset_v2_none[] =3D { 0x38, 0x68, 0x91, 0x92, 0x3f, 0= xa3, 0x10, + 0x34, 0x37, 0x00, 0x00, 0x00, 0x0= 0, 0x00 }; -const uint8_t client_reset_v2_tls_auth[] =3D -{ 0x38, 0xde, 0x69, 0x4c, 0x5c, 0x7b, 0xfb, 0xa2, - 0x74, 0x93, 0x53, 0x7c, 0x1d, 0xed, 0x4e, 0x78, - 0x15, 0x29, 0xae, 0x7c, 0xfe, 0x4b, 0x8c, 0x6d, - 0x6b, 0x2b, 0x51, 0xf0, 0x5a, 0x00, 0x00, 0x00, - 0x01, 0x61, 0xd3, 0xbf, 0x6c, 0x00, 0x00, 0x00, - 0x00, 0x00}; +const uint8_t client_reset_v2_tls_auth[] =3D { 0x38, 0xde, 0x69, 0x4c, 0x5= c, 0x7b, 0xfb, 0xa2, 0x74, + 0x93, 0x53, 0x7c, 0x1d, 0xed,= 0x4e, 0x78, 0x15, 0x29, + 0xae, 0x7c, 0xfe, 0x4b, 0x8c,= 0x6d, 0x6b, 0x2b, 0x51, + 0xf0, 0x5a, 0x00, 0x00, 0x00,= 0x01, 0x61, 0xd3, 0xbf, + 0x6c, 0x00, 0x00, 0x00, 0x00,= 0x00 }; -const uint8_t client_reset_v2_tls_crypt[] =3D -{0x38, 0xf4, 0x19, 0xcb, 0x12, 0xd1, 0xf9, 0xe4, - 0x8f, 0x00, 0x00, 0x00, 0x01, 0x61, 0xd3, 0xf8, - 0xe1, 0x33, 0x02, 0x06, 0xf5, 0x68, 0x02, 0xbe, - 0x44, 0xfb, 0xed, 0x90, 0x50, 0x64, 0xe3, 0xdb, - 0x43, 0x41, 0x6b, 0xec, 0x5e, 0x52, 0x67, 0x19, - 0x46, 0x2b, 0x7e, 0xb9, 0x0c, 0x96, 0xde, 0xfc, - 0x9b, 0x05, 0xc4, 0x48, 0x79, 0xf7}; +const uint8_t client_reset_v2_tls_crypt[] =3D { + 0x38, 0xf4, 0x19, 0xcb, 0x12, 0xd1, 0xf9, 0xe4, 0x8f, 0x00, 0x00, 0x00= , 0x01, 0x61, + 0xd3, 0xf8, 0xe1, 0x33, 0x02, 0x06, 0xf5, 0x68, 0x02, 0xbe, 0x44, 0xfb= , 0xed, 0x90, + 0x50, 0x64, 0xe3, 0xdb, 0x43, 0x41, 0x6b, 0xec, 0x5e, 0x52, 0x67, 0x19= , 0x46, 0x2b, + 0x7e, 0xb9, 0x0c, 0x96, 0xde, 0xfc, 0x9b, 0x05, 0xc4, 0x48, 0x79, 0xf7 +}; /* Valid tls-auth client CONTROL_V1 packet with random server id */ const uint8_t client_ack_tls_auth_randomid[] =3D { - 0x20, 0x14, 0x01, 0x4e, 0xbc, 0x80, 0xc6, 0x14, - 0x2b, 0x7b, 0xc8, 0x76, 0xfb, 0xc5, 0x2e, 0x27, - 0xb1, 0xc5, 0x07, 0x35, 0x5b, 0xb6, 0x00, 0x6b, - 0xae, 0x71, 0xba, 0x4e, 0x38, 0x00, 0x00, 0x00, - 0x03, 0x61, 0xd3, 0xff, 0x53, 0x00, 0x00, 0x00, - 0x00, 0x01, 0x16, 0x03, 0x01, 0x01, 0x0c, 0x01, - 0x00, 0x01, 0x08, 0x03, 0x03, 0x8c, 0xaa, 0xac, - 0x3a, 0x1a, 0x07, 0xbd, 0xe7, 0xb7, 0x50, 0x06, - 0x9b, 0x94, 0x0c, 0x34, 0x4b, 0x5a, 0x35, 0xca, - 0xc4, 0x79, 0xbd, 0xc9, 0x09, 0xb0, 0x7b, 0xd9, - 0xee, 0xbb, 0x7d, 0xe7, 0x25, 0x20, 0x39, 0x38, - 0xe2, 0x18, 0x33, 0x36, 0x14, 0x9f, 0x34, 0xf0, - 0x44, 0x59, 0x96, 0x8d, 0x0e, 0xd2, 0x47, 0x76, - 0x64, 0x88, 0x59, 0xe9, 0x38, 0x03, 0x97, 0x96, - 0x98, 0x45, 0xfb, 0xf5, 0xff, 0x23, 0x00, 0x32, - 0x13, 0x02, 0x13, 0x03, 0x13, 0x01, 0xc0, 0x2c, - 0xc0, 0x30, 0x00, 0x9f, 0xcc, 0xa9, 0xcc, 0xa8, - 0xcc, 0xaa, 0xc0, 0x2b, 0xc0, 0x2f, 0x00, 0x9e, - 0xc0, 0x24, 0xc0, 0x28, 0x00, 0x6b, 0xc0, 0x23, - 0xc0, 0x27, 0x00, 0x67, 0xc0, 0x0a, 0xc0, 0x14, - 0x00, 0x39, 0xc0, 0x09, 0xc0, 0x13, 0x00, 0x33, - 0x00, 0xff, 0x01, 0x00, 0x00, 0x8d, 0x00, 0x0b, - 0x00, 0x04, 0x03, 0x00, 0x01, 0x02, 0x00, 0x0a, - 0x00, 0x0c, 0x00, 0x0a, 0x00, 0x1d, 0x00, 0x17, - 0x00, 0x1e, 0x00, 0x19, 0x00, 0x18, 0x00, 0x16, - 0x00, 0x00, 0x00, 0x17, 0x00, 0x00, 0x00, 0x0d, - 0x00, 0x30, 0x00, 0x2e, 0x04, 0x03, 0x05, 0x03, - 0x06, 0x03, 0x08, 0x07, 0x08, 0x08, 0x08, 0x09, - 0x08, 0x0a, 0x08, 0x0b, 0x08, 0x04, 0x08, 0x05, - 0x08, 0x06, 0x04, 0x01, 0x05, 0x01, 0x06, 0x01, - 0x03, 0x03, 0x02, 0x03, 0x03, 0x01, 0x02, 0x01, - 0x03, 0x02, 0x02, 0x02, 0x04, 0x02, 0x05, 0x02, - 0x06, 0x02, 0x00, 0x2b, 0x00, 0x05, 0x04, 0x03, - 0x04, 0x03, 0x03, 0x00, 0x2d, 0x00, 0x02, 0x01, - 0x01, 0x00, 0x33, 0x00, 0x26, 0x00, 0x24, 0x00, - 0x1d, 0x00, 0x20, 0x0e, 0xc9, 0x7a, 0xff, 0x58, - 0xdb, 0x56, 0xf6, 0x40, 0xd1, 0xed, 0xdb, 0x91, - 0x81, 0xd6, 0xef, 0x83, 0x86, 0x8a, 0xb2, 0x3d, - 0x88, 0x92, 0x3f, 0xd8, 0x51, 0x9c, 0xd6, 0x26, - 0x56, 0x33, 0x6b + 0x20, 0x14, 0x01, 0x4e, 0xbc, 0x80, 0xc6, 0x14, 0x2b, 0x7b, 0xc8, 0x76= , 0xfb, 0xc5, 0x2e, 0x27, + 0xb1, 0xc5, 0x07, 0x35, 0x5b, 0xb6, 0x00, 0x6b, 0xae, 0x71, 0xba, 0x4e= , 0x38, 0x00, 0x00, 0x00, + 0x03, 0x61, 0xd3, 0xff, 0x53, 0x00, 0x00, 0x00, 0x00, 0x01, 0x16, 0x03= , 0x01, 0x01, 0x0c, 0x01, + 0x00, 0x01, 0x08, 0x03, 0x03, 0x8c, 0xaa, 0xac, 0x3a, 0x1a, 0x07, 0xbd= , 0xe7, 0xb7, 0x50, 0x06, + 0x9b, 0x94, 0x0c, 0x34, 0x4b, 0x5a, 0x35, 0xca, 0xc4, 0x79, 0xbd, 0xc9= , 0x09, 0xb0, 0x7b, 0xd9, + 0xee, 0xbb, 0x7d, 0xe7, 0x25, 0x20, 0x39, 0x38, 0xe2, 0x18, 0x33, 0x36= , 0x14, 0x9f, 0x34, 0xf0, + 0x44, 0x59, 0x96, 0x8d, 0x0e, 0xd2, 0x47, 0x76, 0x64, 0x88, 0x59, 0xe9= , 0x38, 0x03, 0x97, 0x96, + 0x98, 0x45, 0xfb, 0xf5, 0xff, 0x23, 0x00, 0x32, 0x13, 0x02, 0x13, 0x03= , 0x13, 0x01, 0xc0, 0x2c, + 0xc0, 0x30, 0x00, 0x9f, 0xcc, 0xa9, 0xcc, 0xa8, 0xcc, 0xaa, 0xc0, 0x2b= , 0xc0, 0x2f, 0x00, 0x9e, + 0xc0, 0x24, 0xc0, 0x28, 0x00, 0x6b, 0xc0, 0x23, 0xc0, 0x27, 0x00, 0x67= , 0xc0, 0x0a, 0xc0, 0x14, + 0x00, 0x39, 0xc0, 0x09, 0xc0, 0x13, 0x00, 0x33, 0x00, 0xff, 0x01, 0x00= , 0x00, 0x8d, 0x00, 0x0b, + 0x00, 0x04, 0x03, 0x00, 0x01, 0x02, 0x00, 0x0a, 0x00, 0x0c, 0x00, 0x0a= , 0x00, 0x1d, 0x00, 0x17, + 0x00, 0x1e, 0x00, 0x19, 0x00, 0x18, 0x00, 0x16, 0x00, 0x00, 0x00, 0x17= , 0x00, 0x00, 0x00, 0x0d, + 0x00, 0x30, 0x00, 0x2e, 0x04, 0x03, 0x05, 0x03, 0x06, 0x03, 0x08, 0x07= , 0x08, 0x08, 0x08, 0x09, + 0x08, 0x0a, 0x08, 0x0b, 0x08, 0x04, 0x08, 0x05, 0x08, 0x06, 0x04, 0x01= , 0x05, 0x01, 0x06, 0x01, + 0x03, 0x03, 0x02, 0x03, 0x03, 0x01, 0x02, 0x01, 0x03, 0x02, 0x02, 0x02= , 0x04, 0x02, 0x05, 0x02, + 0x06, 0x02, 0x00, 0x2b, 0x00, 0x05, 0x04, 0x03, 0x04, 0x03, 0x03, 0x00= , 0x2d, 0x00, 0x02, 0x01, + 0x01, 0x00, 0x33, 0x00, 0x26, 0x00, 0x24, 0x00, 0x1d, 0x00, 0x20, 0x0e= , 0xc9, 0x7a, 0xff, 0x58, + 0xdb, 0x56, 0xf6, 0x40, 0xd1, 0xed, 0xdb, 0x91, 0x81, 0xd6, 0xef, 0x83= , 0x86, 0x8a, 0xb2, 0x3d, + 0x88, 0x92, 0x3f, 0xd8, 0x51, 0x9c, 0xd6, 0x26, 0x56, 0x33, 0x6b }; /* This is a truncated packet as we do not care for the TLS payload in the * unit test */ -const uint8_t client_control_with_ack[] =3D { - 0x20, 0x78, 0x19, 0xbf, 0x2e, 0xbc, 0xd1, 0x9a, - 0x45, 0x01, 0x00, 0x00, 0x00, 0x00, 0xea, - 0xfe, 0xbf, 0xa4, 0x41, 0x8a, 0xe3, 0x1b, - 0x00, 0x00, 0x00, 0x01, 0x16, 0x03, 0x01 -}; +const uint8_t client_control_with_ack[] =3D { 0x20, 0x78, 0x19, 0xbf, 0x2e= , 0xbc, 0xd1, 0x9a, + 0x45, 0x01, 0x00, 0x00, 0x00, = 0x00, 0xea, 0xfe, + 0xbf, 0xa4, 0x41, 0x8a, 0xe3, = 0x1b, 0x00, 0x00, + 0x00, 0x01, 0x16, 0x03, 0x01 }; -const uint8_t client_ack_none_random_id[] =3D { - 0x28, 0xae, 0xb9, 0xaf, 0xe1, 0xf0, 0x1d, 0x79, - 0xc8, 0x01, 0x00, 0x00, 0x00, 0x00, 0xdd, - 0x85, 0xdb, 0x53, 0x56, 0x23, 0xb0, 0x2e -}; +const uint8_t client_ack_none_random_id[] =3D { 0x28, 0xae, 0xb9, 0xaf, 0x= e1, 0xf0, 0x1d, 0x79, + 0xc8, 0x01, 0x00, 0x00, 0x00= , 0x00, 0xdd, 0x85, + 0xdb, 0x53, 0x56, 0x23, 0xb0= , 0x2e }; struct tls_auth_standalone init_tas_auth(int key_direction) { struct tls_auth_standalone tas =3D { 0 }; - struct frame frame =3D { {.headroom =3D 200, .payload_size =3D 1400}, = 0}; + struct frame frame =3D { { .headroom =3D 200, .payload_size =3D 1400 }= , 0 }; tas.frame =3D frame; tas.tls_wrap.mode =3D TLS_WRAP_AUTH; /* we ignore packet ids on for the first packet check */ - tas.tls_wrap.opt.flags |=3D (CO_IGNORE_PACKET_ID|CO_PACKET_ID_LONG_FOR= M); + tas.tls_wrap.opt.flags |=3D (CO_IGNORE_PACKET_ID | CO_PACKET_ID_LONG_F= ORM); struct key_type tls_crypt_kt; init_key_type(&tls_crypt_kt, "none", "SHA1", true, false); - crypto_read_openvpn_key(&tls_crypt_kt, &tas.tls_wrap.opt.key_ctx_bi, - static_key, true, key_direction, - "Control Channel Authentication", "tls-auth", - NULL); + crypto_read_openvpn_key(&tls_crypt_kt, &tas.tls_wrap.opt.key_ctx_bi, s= tatic_key, true, + key_direction, "Control Channel Authentication= ", "tls-auth", NULL); tas.workbuf =3D alloc_buf(1600); return tas; @@ -197,11 +165,10 @@ { struct tls_auth_standalone tas =3D { 0 }; tas.tls_wrap.mode =3D TLS_WRAP_CRYPT; - tas.tls_wrap.opt.flags |=3D (CO_IGNORE_PACKET_ID|CO_PACKET_ID_LONG_FOR= M); + tas.tls_wrap.opt.flags |=3D (CO_IGNORE_PACKET_ID | CO_PACKET_ID_LONG_F= ORM); - tls_crypt_init_key(&tas.tls_wrap.opt.key_ctx_bi, - &tas.tls_wrap.original_wrap_keydata, static_key, - true, server); + tls_crypt_init_key(&tas.tls_wrap.opt.key_ctx_bi, &tas.tls_wrap.origina= l_wrap_keydata, + static_key, true, server); tas.workbuf =3D alloc_buf(1600); tas.tls_wrap.work =3D alloc_buf(1600); @@ -248,7 +215,7 @@ free_tls_pre_decrypt_state(&state); /* flip a byte in various places */ - for (int i =3D 0; isettings.flags =3D MF_EXTERNAL_KEY|MF_EXTERNAL_KEY_PSS= PAD; + management->settings.flags =3D MF_EXTERNAL_KEY | MF_EXTERNAL_KEY_P= SSPAD; /* first without digest support in management client */ again: @@ -328,8 +328,8 @@ } static int -xkey_sign(void *handle, unsigned char *sig, size_t *siglen, - const unsigned char *tbs, size_t tbslen, XKEY_SIGALG s) +xkey_sign(void *handle, unsigned char *sig, size_t *siglen, const unsigned= char *tbs, size_t tbslen, + XKEY_SIGALG s) { if (!sig) { @@ -386,7 +386,8 @@ pubkey =3D load_pubkey(pubkeys[i]); assert_true(pubkey !=3D NULL); - EVP_PKEY *privkey =3D xkey_load_generic_key(NULL, (void *)dummy, p= ubkey, xkey_sign, xkey_free); + EVP_PKEY *privkey =3D + xkey_load_generic_key(NULL, (void *)dummy, pubkey, xkey_sign, = xkey_free); assert_true(privkey !=3D NULL); xkey_sign_called =3D 0; diff --git a/tests/unit_tests/openvpn/test_push_update_msg.c b/tests/unit_t= ests/openvpn/test_push_update_msg.c index d47286a..0f4ad41 100644 --- a/tests/unit_tests/openvpn/test_push_update_msg.c +++ b/tests/unit_tests/openvpn/test_push_update_msg.c @@ -14,36 +14,17 @@ unsigned int pull_permission_mask(const struct context *c) { - unsigned int flags =3D - OPT_P_UP - | OPT_P_ROUTE_EXTRAS - | OPT_P_SOCKBUF - | OPT_P_SOCKFLAGS - | OPT_P_SETENV - | OPT_P_SHAPER - | OPT_P_TIMER - | OPT_P_COMP - | OPT_P_PERSIST - | OPT_P_MESSAGES - | OPT_P_EXPLICIT_NOTIFY - | OPT_P_ECHO - | OPT_P_PULL_MODE - | OPT_P_PEER_ID - | OPT_P_NCP - | OPT_P_PUSH_MTU - | OPT_P_ROUTE - | OPT_P_DHCPDNS; + unsigned int flags =3D OPT_P_UP | OPT_P_ROUTE_EXTRAS | OPT_P_SOCKBUF |= OPT_P_SOCKFLAGS + | OPT_P_SETENV | OPT_P_SHAPER | OPT_P_TIMER | OPT= _P_COMP | OPT_P_PERSIST + | OPT_P_MESSAGES | OPT_P_EXPLICIT_NOTIFY | OPT_P_= ECHO | OPT_P_PULL_MODE + | OPT_P_PEER_ID | OPT_P_NCP | OPT_P_PUSH_MTU | OP= T_P_ROUTE | OPT_P_DHCPDNS; return flags; } bool -apply_push_options(struct context *c, - struct options *options, - struct buffer *buf, - unsigned int permission_mask, - unsigned int *option_types_found, - struct env_set *es, - bool is_update) +apply_push_options(struct context *c, struct options *options, struct buff= er *buf, + unsigned int permission_mask, unsigned int *option_type= s_found, + struct env_set *es, bool is_update) { char line[OPTION_PARM_SIZE]; @@ -80,10 +61,8 @@ } int -process_incoming_push_msg(struct context *c, - const struct buffer *buffer, - bool honor_received_options, - unsigned int permission_mask, +process_incoming_push_msg(struct context *c, const struct buffer *buffer, + bool honor_received_options, unsigned int permis= sion_mask, unsigned int *option_types_found) { struct buffer buf =3D *buffer; @@ -92,16 +71,13 @@ { return PUSH_MSG_REQUEST; } - else if (honor_received_options - && buf_string_compare_advance(&buf, push_reply_cmd)) + else if (honor_received_options && buf_string_compare_advance(&buf, pu= sh_reply_cmd)) { return PUSH_MSG_REPLY; } - else if (honor_received_options - && buf_string_compare_advance(&buf, push_update_cmd)) + else if (honor_received_options && buf_string_compare_advance(&buf, pu= sh_update_cmd)) { - return process_incoming_push_update(c, permission_mask, - option_types_found, &buf); + return process_incoming_push_update(c, permission_mask, option_typ= es_found, &buf); } else { @@ -116,11 +92,14 @@ { struct context *c =3D *state; struct buffer buf =3D alloc_buf(256); - const char *update_msg =3D "PUSH_UPDATE,dhcp-option DNS 8.8.8.8, route= 0.0.0.0 0.0.0.0 10.10.10.1"; + const char *update_msg =3D + "PUSH_UPDATE,dhcp-option DNS 8.8.8.8, route 0.0.0.0 0.0.0.0 10.10.= 10.1"; buf_write(&buf, update_msg, strlen(update_msg)); unsigned int option_types_found =3D 0; - assert_int_equal(process_incoming_push_msg(c, &buf, c->options.pull, p= ull_permission_mask(c), &option_types_found), PUSH_MSG_UPDATE); + assert_int_equal(process_incoming_push_msg(c, &buf, c->options.pull, p= ull_permission_mask(c), + &option_types_found), + PUSH_MSG_UPDATE); free_buf(&buf); } @@ -134,7 +113,9 @@ buf_write(&buf, update_msg, strlen(update_msg)); unsigned int option_types_found =3D 0; - assert_int_equal(process_incoming_push_msg(c, &buf, c->options.pull, p= ull_permission_mask(c), &option_types_found), PUSH_MSG_ERROR); + assert_int_equal(process_incoming_push_msg(c, &buf, c->options.pull, p= ull_permission_mask(c), + &option_types_found), + PUSH_MSG_ERROR); free_buf(&buf); } @@ -149,7 +130,9 @@ buf_write(&buf, update_msg, strlen(update_msg)); unsigned int option_types_found =3D 0; - assert_int_equal(process_incoming_push_msg(c, &buf, c->options.pull, p= ull_permission_mask(c), &option_types_found), PUSH_MSG_ERROR); + assert_int_equal(process_incoming_push_msg(c, &buf, c->options.pull, p= ull_permission_mask(c), + &option_types_found), + PUSH_MSG_ERROR); free_buf(&buf); } @@ -163,7 +146,9 @@ buf_write(&buf, update_msg, strlen(update_msg)); unsigned int option_types_found =3D 0; - assert_int_equal(process_incoming_push_msg(c, &buf, c->options.pull, p= ull_permission_mask(c), &option_types_found), PUSH_MSG_UPDATE); + assert_int_equal(process_incoming_push_msg(c, &buf, c->options.pull, p= ull_permission_mask(c), + &option_types_found), + PUSH_MSG_UPDATE); free_buf(&buf); } @@ -177,7 +162,9 @@ buf_write(&buf, update_msg, strlen(update_msg)); unsigned int option_types_found =3D 0; - assert_int_equal(process_incoming_push_msg(c, &buf, c->options.pull, p= ull_permission_mask(c), &option_types_found), PUSH_MSG_ERROR); + assert_int_equal(process_incoming_push_msg(c, &buf, c->options.pull, p= ull_permission_mask(c), + &option_types_found), + PUSH_MSG_ERROR); free_buf(&buf); } @@ -191,7 +178,9 @@ buf_write(&buf, update_msg, strlen(update_msg)); unsigned int option_types_found =3D 0; - assert_int_equal(process_incoming_push_msg(c, &buf, c->options.pull, p= ull_permission_mask(c), &option_types_found), PUSH_MSG_ERROR); + assert_int_equal(process_incoming_push_msg(c, &buf, c->options.pull, p= ull_permission_mask(c), + &option_types_found), + PUSH_MSG_ERROR); free_buf(&buf); } @@ -201,11 +190,14 @@ { struct context *c =3D *state; struct buffer buf =3D alloc_buf(256); - const char *update_msg =3D "PUSH_UPDATE,-dhcp-option, route 10.10.10.0= , dhcp-option DNS 1.1.1.1, route 10.11.12.0, dhcp-option DOMAIN corp.local,= keepalive 10 60"; + const char *update_msg =3D + "PUSH_UPDATE,-dhcp-option, route 10.10.10.0, dhcp-option DNS 1.1.1= .1, route 10.11.12.0, dhcp-option DOMAIN corp.local, keepalive 10 60"; buf_write(&buf, update_msg, strlen(update_msg)); unsigned int option_types_found =3D 0; - assert_int_equal(process_incoming_push_msg(c, &buf, c->options.pull, p= ull_permission_mask(c), &option_types_found), PUSH_MSG_UPDATE); + assert_int_equal(process_incoming_push_msg(c, &buf, c->options.pull, p= ull_permission_mask(c), + &option_types_found), + PUSH_MSG_UPDATE); free_buf(&buf); } @@ -215,11 +207,14 @@ { struct context *c =3D *state; struct buffer buf =3D alloc_buf(256); - const char *update_msg =3D "PUSH_UPDATE,-dhcp-option,dhcp-option DNS 8= .8.8.8,redirect-gateway local,route 192.168.1.0 255.255.255.0"; + const char *update_msg =3D + "PUSH_UPDATE,-dhcp-option,dhcp-option DNS 8.8.8.8,redirect-gateway= local,route 192.168.1.0 255.255.255.0"; buf_write(&buf, update_msg, strlen(update_msg)); unsigned int option_types_found =3D 0; - assert_int_equal(process_incoming_push_msg(c, &buf, c->options.pull, p= ull_permission_mask(c), &option_types_found), PUSH_MSG_UPDATE); + assert_int_equal(process_incoming_push_msg(c, &buf, c->options.pull, p= ull_permission_mask(c), + &option_types_found), + PUSH_MSG_UPDATE); free_buf(&buf); } @@ -249,7 +244,8 @@ cmocka_unit_test_setup_teardown(test_incoming_push_message_basic, = setup, teardown), cmocka_unit_test_setup_teardown(test_incoming_push_message_error1,= setup, teardown), cmocka_unit_test_setup_teardown(test_incoming_push_message_error2,= setup, teardown), - cmocka_unit_test_setup_teardown(test_incoming_push_message_not_upd= atable_option, setup, teardown), + cmocka_unit_test_setup_teardown(test_incoming_push_message_not_upd= atable_option, setup, + teardown), cmocka_unit_test_setup_teardown(test_incoming_push_message_1, setu= p, teardown), cmocka_unit_test_setup_teardown(test_incoming_push_message_bad_for= mat, setup, teardown), cmocka_unit_test_setup_teardown(test_incoming_push_message_mix, se= tup, teardown), diff --git a/tests/unit_tests/openvpn/test_ssl.c b/tests/unit_tests/openvpn= /test_ssl.c index c758f87..7bf5396 100644 --- a/tests/unit_tests/openvpn/test_ssl.c +++ b/tests/unit_tests/openvpn/test_ssl.c @@ -159,7 +159,7 @@ static int init(void **state) { - (void) state; + (void)state; global_state.gc =3D gc_new(); global_state.certfile =3D platform_create_temp_file(get_tmp_dir(), "ce= rt", &global_state.gc); global_state.keyfile =3D platform_create_temp_file(get_tmp_dir(), "key= ", &global_state.gc); @@ -180,7 +180,7 @@ static int cleanup(void **state) { - (void) state; + (void)state; unlink(global_state.certfile); unlink(global_state.keyfile); gc_free(&global_state.gc); @@ -220,7 +220,7 @@ static void test_load_certificate_and_key(void **state) { - (void) state; + (void)state; struct tls_root_ctx ctx =3D { 0 }; =20 /* test loading of inlined cert and key. @@ -242,11 +242,11 @@ static void test_load_certificate_and_key_uri(void **state) { - (void) state; + (void)state; #if !defined(HAVE_OPENSSL_STORE) skip(); -#else /* HAVE_OPENSSL_STORE */ +#else /* HAVE_OPENSSL_STORE */ struct tls_root_ctx ctx =3D { 0 }; const char *certfile =3D global_state.certfile; @@ -306,7 +306,6 @@ frame->buf.tailroom =3D overhead; frame->tun_mtu =3D tls_mtu; - } static void @@ -333,7 +332,6 @@ /* Test encryption, decryption for all packet sizes */ for (int i =3D 1; i <=3D frame.buf.payload_size; ++i) { - /* msg(M_INFO, "TESTING ENCRYPT/DECRYPT of packet length=3D%d", i)= ; */ /* @@ -413,7 +411,6 @@ static void check_aead_limits(struct crypto_options *co, bool chachapoly) { - /* Check that we correctly react when we have a nearing AEAD limits */ /* manually increase the send counter to be past @@ -445,9 +442,8 @@ { /* Check always against the GCM usage limit here to see if that * check works */ - assert_true(aead_usage_limit_reached((1ull << 36), - &co->key_ctx_bi.encrypt, - co->packet_id.send.id)); + assert_true( + aead_usage_limit_reached((1ull << 36), &co->key_ctx_bi.encrypt= , co->packet_id.send.id)); return; } @@ -464,10 +460,9 @@ static struct crypto_options -init_crypto_options(const char *cipher, const char *auth, bool epoch, - struct key2 *statickey) +init_crypto_options(const char *cipher, const char *auth, bool epoch, stru= ct key2 *statickey) { - struct key2 key2 =3D { .n =3D 2}; + struct key2 key2 =3D { .n =3D 2 }; if (statickey) { @@ -488,7 +483,7 @@ if (epoch) { - struct epoch_key e1 =3D { .epoch =3D 1, .epoch_key =3D { 0 }}; + struct epoch_key e1 =3D { .epoch =3D 1, .epoch_key =3D { 0 } }; memcpy(e1.epoch_key, key2.keys[0].cipher, sizeof(e1.epoch_key)); co.flags |=3D CO_EPOCH_DATA_KEY_FORMAT; epoch_init_key_ctx(&co, &kt, &e1, &e1, 5); @@ -633,11 +628,11 @@ static struct key2 create_key(void) { - struct key2 key2 =3D {.n =3D 2}; + struct key2 key2 =3D { .n =3D 2 }; - const uint8_t key[] =3D - {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', '0', '1', '2', '3', '4', '5',= '6', '7', 'A', 'B', 'C', 'D', 'E', 'F', - 'G', 'H', 'j', 'k', 'u', 'c', 'h', 'e', 'n', 'l'}; + const uint8_t key[] =3D { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', '0',= '1', '2', + '3', '4', '5', '6', '7', 'A', 'B', 'C', 'D', '= E', 'F', + 'G', 'H', 'j', 'k', 'u', 'c', 'h', 'e', 'n', '= l' }; static_assert(sizeof(key) =3D=3D 32, "Size of key should be 32 bytes"); @@ -647,7 +642,7 @@ for (int i =3D 0; i < sizeof(key2.keys); i++) { - keydata[i] =3D (uint8_t) (key[i % sizeof(key)] ^ i); + keydata[i] =3D (uint8_t)(key[i % sizeof(key)] ^ i); } ASSERT(memcpy(key2.keys[0].cipher, keydata, sizeof(key2.keys[0].cipher= ))); @@ -663,8 +658,7 @@ { struct key2 key2 =3D create_key(); - struct crypto_options co =3D init_crypto_options("AES-256-GCM", "none"= , epoch, - &key2); + struct crypto_options co =3D init_crypto_options("AES-256-GCM", "none"= , epoch, &key2); struct gc_arena gc =3D gc_new(); @@ -716,41 +710,40 @@ if (epoch) { - uint8_t packetid1[8] =3D {0, 0x04, 0, 0, 0, 0, 0, 1}; + uint8_t packetid1[8] =3D { 0, 0x04, 0, 0, 0, 0, 0, 1 }; assert_memory_equal(BPTR(&buf), packetid1, 8); } else { - uint8_t packetid1[4] =3D {0, 0, 0, 1}; + uint8_t packetid1[4] =3D { 0, 0, 0, 1 }; assert_memory_equal(BPTR(&buf), packetid1, 4); } if (epoch) { uint8_t *tag_location =3D BEND(&buf) - OPENVPN_AEAD_TAG_LENGTH; - const uint8_t exp_tag_epoch[16] =3D - {0x0f, 0xff, 0xf5, 0x91, 0x3d, 0x39, 0xd7, 0x5b, - 0x18, 0x57, 0x3b, 0x57, 0x48, 0x58, 0x9a, 0x7d}; + const uint8_t exp_tag_epoch[16] =3D { 0x0f, 0xff, 0xf5, 0x91, 0x3d= , 0x39, 0xd7, 0x5b, + 0x18, 0x57, 0x3b, 0x57, 0x48, = 0x58, 0x9a, 0x7d }; assert_memory_equal(tag_location, exp_tag_epoch, OPENVPN_AEAD_TAG_= LENGTH); } else { uint8_t *tag_location =3D BPTR(&buf) + 4; - const uint8_t exp_tag_noepoch[16] =3D - {0x1f, 0xdd, 0x90, 0x8f, 0x0e, 0x9d, 0xc2, 0x5e, 0x79, 0xd8, 0x32,= 0x02, 0x0d, 0x58, 0xe7, 0x3f}; + const uint8_t exp_tag_noepoch[16] =3D { 0x1f, 0xdd, 0x90, 0x8f, 0x= 0e, 0x9d, 0xc2, 0x5e, + 0x79, 0xd8, 0x32, 0x02, 0x0d= , 0x58, 0xe7, 0x3f }; assert_memory_equal(tag_location, exp_tag_noepoch, OPENVPN_AEAD_TA= G_LENGTH); } /* Check some bytes at the beginning of the encrypted part */ if (epoch) { - const uint8_t bytesat14[6] =3D {0x36, 0xaa, 0xb4, 0xd4, 0x9c, 0xe6= }; + const uint8_t bytesat14[6] =3D { 0x36, 0xaa, 0xb4, 0xd4, 0x9c, 0xe= 6 }; assert_memory_equal(BPTR(&buf) + 14, bytesat14, sizeof(bytesat14)); } else { - const uint8_t bytesat30[6] =3D {0xa8, 0x2e, 0x6b, 0x17, 0x06, 0xd9= }; + const uint8_t bytesat30[6] =3D { 0xa8, 0x2e, 0x6b, 0x17, 0x06, 0xd= 9 }; assert_memory_equal(BPTR(&buf) + 30, bytesat30, sizeof(bytesat30)); } diff --git a/tests/unit_tests/openvpn/test_tls_crypt.c b/tests/unit_tests/o= penvpn/test_tls_crypt.c index 1b5eb27..532bfcd 100644 --- a/tests/unit_tests/openvpn/test_tls_crypt.c +++ b/tests/unit_tests/openvpn/test_tls_crypt.c @@ -39,8 +39,7 @@ /* Define this function here as dummy since including the ssl_*.c files * leads to having to include even more unrelated code */ bool -key_state_export_keying_material(struct tls_session *session, - const char *label, size_t label_size, +key_state_export_keying_material(struct tls_session *session, const char *= label, size_t label_size, void *ekm, size_t ekm_size) { memset(ekm, 0xba, ekm_size); @@ -48,22 +47,22 @@ } -#define TESTBUF_SIZE 128 +#define TESTBUF_SIZE 128 /* Defines for use in the tests and the mock parse_line() */ -#define PATH1 "/s p a c e" -#define PATH2 "/foo bar/baz" -#define PARAM1 "param1" -#define PARAM2 "param two" +#define PATH1 "/s p a c e" +#define PATH2 "/foo bar/baz" +#define PARAM1 "param1" +#define PARAM2 "param two" -static const char *test_server_key =3D \ +static const char *test_server_key =3D "-----BEGIN OpenVPN tls-crypt-v2 server key-----\n" "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISIjJCUmJygpKissLS4v\n" "MDEyMzQ1Njc4OTo7PD0+P0BBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWltcXV5f\n" "YGFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6e3x9fn8=3D\n" "-----END OpenVPN tls-crypt-v2 server key-----\n"; -static const char *test_client_key =3D \ +static const char *test_client_key =3D "-----BEGIN OpenVPN tls-crypt-v2 client key-----\n" "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISIjJCUmJygpKissLS4v\n" "MDEyMzQ1Njc4OTo7PD0+P0BBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWltcXV5f\n" @@ -81,7 +80,7 @@ /* Has custom metadata of AABBCCDD (base64) */ -static const char *test_client_key_metadata =3D \ +static const char *test_client_key_metadata =3D "-----BEGIN OpenVPN tls-crypt-v2 client key-----\n" "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISIjJCUmJygpKissLS4v\n" "MDEyMzQ1Njc4OTo7PD0+P0BBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWltcXV5f\n" @@ -98,8 +97,8 @@ "-----END OpenVPN tls-crypt-v2 client key-----\n"; int -__wrap_parse_line(const char *line, char **p, const int n, const char *fil= e, - const int line_num, int msglevel, struct gc_arena *gc) +__wrap_parse_line(const char *line, char **p, const int n, const char *fil= e, const int line_num, + int msglevel, struct gc_arena *gc) { p[0] =3D PATH1 PATH2; p[1] =3D PARAM1; @@ -141,7 +140,8 @@ return true; } -struct test_tls_crypt_context { +struct test_tls_crypt_context +{ struct crypto_options co; struct key_type kt; struct buffer source; @@ -156,8 +156,10 @@ struct test_tls_crypt_context *ctx =3D calloc(1, sizeof(*ctx)); *state =3D ctx; - struct key_parameters key =3D { .cipher =3D { 0 }, .hmac =3D { 0 }, - .hmac_size =3D MAX_HMAC_KEY_LENGTH, .cip= her_size =3D MAX_CIPHER_KEY_LENGTH }; + struct key_parameters key =3D { .cipher =3D { 0 }, + .hmac =3D { 0 }, + .hmac_size =3D MAX_HMAC_KEY_LENGTH, + .cipher_size =3D MAX_CIPHER_KEY_LENGTH }; ctx->kt =3D tls_crypt_kt(); if (!ctx->kt.cipher || !ctx->kt.digest) @@ -187,8 +189,7 @@ static int test_tls_crypt_teardown(void **state) { - struct test_tls_crypt_context *ctx =3D - (struct test_tls_crypt_context *)*state; + struct test_tls_crypt_context *ctx =3D (struct test_tls_crypt_context = *)*state; free_buf(&ctx->source); free_buf(&ctx->ciphertext); @@ -216,7 +217,7 @@ static void tls_crypt_loopback(void **state) { - struct test_tls_crypt_context *ctx =3D (struct test_tls_crypt_context = *) *state; + struct test_tls_crypt_context *ctx =3D (struct test_tls_crypt_context = *)*state; skip_if_tls_crypt_not_supported(ctx); @@ -224,8 +225,7 @@ assert_true(BLEN(&ctx->source) < BLEN(&ctx->ciphertext)); assert_true(tls_crypt_unwrap(&ctx->ciphertext, &ctx->unwrapped, &ctx->= co)); assert_int_equal(BLEN(&ctx->source), BLEN(&ctx->unwrapped)); - assert_memory_equal(BPTR(&ctx->source), BPTR(&ctx->unwrapped), - BLEN(&ctx->source)); + assert_memory_equal(BPTR(&ctx->source), BPTR(&ctx->unwrapped), BLEN(&c= tx->source)); } @@ -235,8 +235,7 @@ static void test_tls_crypt_secure_reneg_key(void **state) { - struct test_tls_crypt_context *ctx =3D - (struct test_tls_crypt_context *)*state; + struct test_tls_crypt_context *ctx =3D (struct test_tls_crypt_context = *)*state; struct gc_arena gc =3D gc_new(); @@ -255,19 +254,19 @@ tls_crypt_wrap(&ctx->source, &rctx->work, &rctx->opt); assert_int_equal(buf_len(&ctx->source) + 40, buf_len(&rctx->work)); - uint8_t expected_ciphertext[] =3D { - 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0xe3, 0x19, 0x27, = 0x7f, 0x1c, 0x8d, 0x6e, 0x6a, - 0x77, 0x96, 0xa8, 0x55, 0x33, 0x7b, 0x9c, 0xfb, 0x56, 0xe1, 0xf1, = 0x3a, 0x87, 0x0e, 0x66, 0x47, - 0xdf, 0xa1, 0x95, 0xc9, 0x2c, 0x17, 0xa0, 0x15, 0xba, 0x49, 0x67, = 0xa1, 0x1d, 0x55, 0xea, 0x1a, - 0x06, 0xa7 - }; + uint8_t expected_ciphertext[] =3D { 0x00, 0x00, 0x00, 0x01, 0x00, 0x00= , 0x00, 0x00, 0xe3, 0x19, + 0x27, 0x7f, 0x1c, 0x8d, 0x6e, 0x6a, = 0x77, 0x96, 0xa8, 0x55, + 0x33, 0x7b, 0x9c, 0xfb, 0x56, 0xe1, = 0xf1, 0x3a, 0x87, 0x0e, + 0x66, 0x47, 0xdf, 0xa1, 0x95, 0xc9, = 0x2c, 0x17, 0xa0, 0x15, + 0xba, 0x49, 0x67, 0xa1, 0x1d, 0x55, = 0xea, 0x1a, 0x06, 0xa7 }; assert_memory_equal(BPTR(&rctx->work), expected_ciphertext, buf_len(&r= ctx->work)); tls_wrap_free(&session.tls_wrap_reneg); /* Use previous tls-crypt key as 0x00, with xor we should have the sam= e key * and expect the same result */ session.tls_wrap.mode =3D TLS_WRAP_CRYPT; - memset(&session.tls_wrap.original_wrap_keydata.keys, 0x00, sizeof(sess= ion.tls_wrap.original_wrap_keydata.keys)); + memset(&session.tls_wrap.original_wrap_keydata.keys, 0x00, + sizeof(session.tls_wrap.original_wrap_keydata.keys)); session.tls_wrap.original_wrap_keydata.n =3D 2; tls_session_generate_dynamic_tls_crypt_key(&session); @@ -278,7 +277,8 @@ tls_wrap_free(&session.tls_wrap_reneg); /* XOR should not force a different key */ - memset(&session.tls_wrap.original_wrap_keydata.keys, 0x42, sizeof(sess= ion.tls_wrap.original_wrap_keydata.keys)); + memset(&session.tls_wrap.original_wrap_keydata.keys, 0x42, + sizeof(session.tls_wrap.original_wrap_keydata.keys)); tls_session_generate_dynamic_tls_crypt_key(&session); tls_crypt_wrap(&ctx->source, &rctx->work, &rctx->opt); @@ -302,7 +302,7 @@ static void tls_crypt_loopback_zero_len(void **state) { - struct test_tls_crypt_context *ctx =3D (struct test_tls_crypt_context = *) *state; + struct test_tls_crypt_context *ctx =3D (struct test_tls_crypt_context = *)*state; skip_if_tls_crypt_not_supported(ctx); @@ -312,8 +312,7 @@ assert_true(BLEN(&ctx->source) < BLEN(&ctx->ciphertext)); assert_true(tls_crypt_unwrap(&ctx->ciphertext, &ctx->unwrapped, &ctx->= co)); assert_int_equal(BLEN(&ctx->source), BLEN(&ctx->unwrapped)); - assert_memory_equal(BPTR(&ctx->source), BPTR(&ctx->unwrapped), - BLEN(&ctx->source)); + assert_memory_equal(BPTR(&ctx->source), BPTR(&ctx->unwrapped), BLEN(&c= tx->source)); } /** @@ -322,20 +321,19 @@ static void tls_crypt_loopback_max_len(void **state) { - struct test_tls_crypt_context *ctx =3D (struct test_tls_crypt_context = *) *state; + struct test_tls_crypt_context *ctx =3D (struct test_tls_crypt_context = *)*state; skip_if_tls_crypt_not_supported(ctx); buf_clear(&ctx->source); - assert_non_null(buf_write_alloc(&ctx->source, - TESTBUF_SIZE - BLEN(&ctx->ciphertext) = - tls_crypt_buf_overhead())); + assert_non_null(buf_write_alloc(&ctx->source, TESTBUF_SIZE - BLEN(&ctx= ->ciphertext) + - tls_crypt_buf_over= head())); assert_true(tls_crypt_wrap(&ctx->source, &ctx->ciphertext, &ctx->co)); assert_true(BLEN(&ctx->source) < BLEN(&ctx->ciphertext)); assert_true(tls_crypt_unwrap(&ctx->ciphertext, &ctx->unwrapped, &ctx->= co)); assert_int_equal(BLEN(&ctx->source), BLEN(&ctx->unwrapped)); - assert_memory_equal(BPTR(&ctx->source), BPTR(&ctx->unwrapped), - BLEN(&ctx->source)); + assert_memory_equal(BPTR(&ctx->source), BPTR(&ctx->unwrapped), BLEN(&c= tx->source)); } /** @@ -344,13 +342,13 @@ static void tls_crypt_fail_msg_too_long(void **state) { - struct test_tls_crypt_context *ctx =3D (struct test_tls_crypt_context = *) *state; + struct test_tls_crypt_context *ctx =3D (struct test_tls_crypt_context = *)*state; skip_if_tls_crypt_not_supported(ctx); buf_clear(&ctx->source); - assert_non_null(buf_write_alloc(&ctx->source, - TESTBUF_SIZE - BLEN(&ctx->ciphertext) = - tls_crypt_buf_overhead() + 1)); + assert_non_null(buf_write_alloc(&ctx->source, TESTBUF_SIZE - BLEN(&ctx= ->ciphertext) + - tls_crypt_buf_over= head() + 1)); assert_false(tls_crypt_wrap(&ctx->source, &ctx->ciphertext, &ctx->co)); } @@ -361,13 +359,15 @@ static void tls_crypt_fail_invalid_key(void **state) { - struct test_tls_crypt_context *ctx =3D (struct test_tls_crypt_context = *) *state; + struct test_tls_crypt_context *ctx =3D (struct test_tls_crypt_context = *)*state; skip_if_tls_crypt_not_supported(ctx); /* Change decrypt key */ - struct key_parameters key =3D { .cipher =3D { 1 }, .hmac =3D { 1 }, - .cipher_size =3D MAX_CIPHER_KEY_LENGTH, = .hmac_size =3D MAX_HMAC_KEY_LENGTH }; + struct key_parameters key =3D { .cipher =3D { 1 }, + .hmac =3D { 1 }, + .cipher_size =3D MAX_CIPHER_KEY_LENGTH, + .hmac_size =3D MAX_HMAC_KEY_LENGTH }; free_key_ctx(&ctx->co.key_ctx_bi.decrypt); init_key_ctx(&ctx->co.key_ctx_bi.decrypt, &key, &ctx->kt, false, "TEST= "); @@ -382,7 +382,7 @@ static void tls_crypt_fail_replay(void **state) { - struct test_tls_crypt_context *ctx =3D (struct test_tls_crypt_context = *) *state; + struct test_tls_crypt_context *ctx =3D (struct test_tls_crypt_context = *)*state; skip_if_tls_crypt_not_supported(ctx); @@ -402,7 +402,7 @@ static void tls_crypt_ignore_replay(void **state) { - struct test_tls_crypt_context *ctx =3D (struct test_tls_crypt_context = *) *state; + struct test_tls_crypt_context *ctx =3D (struct test_tls_crypt_context = *)*state; skip_if_tls_crypt_not_supported(ctx); @@ -416,7 +416,8 @@ assert_true(tls_crypt_unwrap(&ctx->ciphertext, &ctx->unwrapped, &ctx->= co)); } -struct test_tls_crypt_v2_context { +struct test_tls_crypt_v2_context +{ struct gc_arena gc; struct key2 server_key2; struct key_ctx_bi server_keys; @@ -436,17 +437,15 @@ ctx->gc =3D gc_new(); /* Slightly longer buffers to be able to test too-long data */ - ctx->metadata =3D alloc_buf_gc(TLS_CRYPT_V2_MAX_METADATA_LEN+16, &ctx-= >gc); - ctx->unwrapped_metadata =3D alloc_buf_gc(TLS_CRYPT_V2_MAX_METADATA_LEN= +16, - &ctx->gc); - ctx->wkc =3D alloc_buf_gc(TLS_CRYPT_V2_MAX_WKC_LEN+16, &ctx->gc); + ctx->metadata =3D alloc_buf_gc(TLS_CRYPT_V2_MAX_METADATA_LEN + 16, &ct= x->gc); + ctx->unwrapped_metadata =3D alloc_buf_gc(TLS_CRYPT_V2_MAX_METADATA_LEN= + 16, &ctx->gc); + ctx->wkc =3D alloc_buf_gc(TLS_CRYPT_V2_MAX_WKC_LEN + 16, &ctx->gc); /* Generate server key */ rand_bytes((void *)ctx->server_key2.keys, sizeof(ctx->server_key2.keys= )); ctx->server_key2.n =3D 2; struct key_type kt =3D tls_crypt_kt(); - init_key_ctx_bi(&ctx->server_keys, &ctx->server_key2, - KEY_DIRECTION_BIDIRECTIONAL, &kt, + init_key_ctx_bi(&ctx->server_keys, &ctx->server_key2, KEY_DIRECTION_BI= DIRECTIONAL, &kt, "tls-crypt-v2 server key"); /* Generate client key */ @@ -459,8 +458,7 @@ static int test_tls_crypt_v2_teardown(void **state) { - struct test_tls_crypt_v2_context *ctx =3D - (struct test_tls_crypt_v2_context *) *state; + struct test_tls_crypt_v2_context *ctx =3D (struct test_tls_crypt_v2_co= ntext *)*state; free_key_ctx_bi(&ctx->server_keys); free_key_ctx_bi(&ctx->client_key); @@ -478,27 +476,20 @@ static void tls_crypt_v2_wrap_unwrap_no_metadata(void **state) { - struct test_tls_crypt_v2_context *ctx =3D - (struct test_tls_crypt_v2_context *) *state; + struct test_tls_crypt_v2_context *ctx =3D (struct test_tls_crypt_v2_co= ntext *)*state; - struct buffer wrapped_client_key =3D alloc_buf_gc(TLS_CRYPT_V2_MAX_WKC= _LEN, - &ctx->gc); - assert_true(tls_crypt_v2_wrap_client_key(&wrapped_client_key, - &ctx->client_key2, - &ctx->metadata, - &ctx->server_keys.encrypt, - &ctx->gc)); + struct buffer wrapped_client_key =3D alloc_buf_gc(TLS_CRYPT_V2_MAX_WKC= _LEN, &ctx->gc); + assert_true(tls_crypt_v2_wrap_client_key(&wrapped_client_key, &ctx->cl= ient_key2, &ctx->metadata, + &ctx->server_keys.encrypt, &c= tx->gc)); - struct buffer unwrap_metadata =3D alloc_buf_gc(TLS_CRYPT_V2_MAX_METADA= TA_LEN, - &ctx->gc); + struct buffer unwrap_metadata =3D alloc_buf_gc(TLS_CRYPT_V2_MAX_METADA= TA_LEN, &ctx->gc); struct key2 unwrapped_client_key2 =3D { 0 }; - assert_true(tls_crypt_v2_unwrap_client_key(&unwrapped_client_key2, - &unwrap_metadata, - wrapped_client_key, - &ctx->server_keys.decrypt)); + assert_true(tls_crypt_v2_unwrap_client_key(&unwrapped_client_key2, &un= wrap_metadata, + wrapped_client_key, &ctx->s= erver_keys.decrypt)); - assert_true(0 =3D=3D memcmp(ctx->client_key2.keys, unwrapped_client_ke= y2.keys, - sizeof(ctx->client_key2.keys))); + assert_true(0 + =3D=3D memcmp(ctx->client_key2.keys, unwrapped_client_key2= .keys, + sizeof(ctx->client_key2.keys))); } /** @@ -508,26 +499,21 @@ static void tls_crypt_v2_wrap_unwrap_max_metadata(void **state) { - struct test_tls_crypt_v2_context *ctx =3D - (struct test_tls_crypt_v2_context *) *state; + struct test_tls_crypt_v2_context *ctx =3D (struct test_tls_crypt_v2_co= ntext *)*state; - uint8_t *metadata =3D - buf_write_alloc(&ctx->metadata, TLS_CRYPT_V2_MAX_METADATA_LEN); + uint8_t *metadata =3D buf_write_alloc(&ctx->metadata, TLS_CRYPT_V2_MAX= _METADATA_LEN); assert_true(rand_bytes(metadata, TLS_CRYPT_V2_MAX_METADATA_LEN)); - assert_true(tls_crypt_v2_wrap_client_key(&ctx->wkc, &ctx->client_key2, - &ctx->metadata, - &ctx->server_keys.encrypt, - &ctx->gc)); + assert_true(tls_crypt_v2_wrap_client_key(&ctx->wkc, &ctx->client_key2,= &ctx->metadata, + &ctx->server_keys.encrypt, &c= tx->gc)); - struct buffer unwrap_metadata =3D alloc_buf_gc(TLS_CRYPT_V2_MAX_METADA= TA_LEN, - &ctx->gc); + struct buffer unwrap_metadata =3D alloc_buf_gc(TLS_CRYPT_V2_MAX_METADA= TA_LEN, &ctx->gc); struct key2 unwrapped_client_key2 =3D { 0 }; - assert_true(tls_crypt_v2_unwrap_client_key(&unwrapped_client_key2, - &unwrap_metadata, ctx->wkc, + assert_true(tls_crypt_v2_unwrap_client_key(&unwrapped_client_key2, &un= wrap_metadata, ctx->wkc, &ctx->server_keys.decrypt)); - assert_true(0 =3D=3D memcmp(ctx->client_key2.keys, unwrapped_client_ke= y2.keys, - sizeof(ctx->client_key2.keys))); + assert_true(0 + =3D=3D memcmp(ctx->client_key2.keys, unwrapped_client_key2= .keys, + sizeof(ctx->client_key2.keys))); assert_true(buf_equal(&ctx->metadata, &unwrap_metadata)); struct tls_wrap_ctx wrap_ctx =3D { @@ -545,14 +531,11 @@ static void tls_crypt_v2_wrap_too_long_metadata(void **state) { - struct test_tls_crypt_v2_context *ctx =3D - (struct test_tls_crypt_v2_context *) *state; + struct test_tls_crypt_v2_context *ctx =3D (struct test_tls_crypt_v2_co= ntext *)*state; - assert_true(buf_inc_len(&ctx->metadata, TLS_CRYPT_V2_MAX_METADATA_LEN+= 1)); - assert_false(tls_crypt_v2_wrap_client_key(&ctx->wkc, &ctx->client_key2, - &ctx->metadata, - &ctx->server_keys.encrypt, - &ctx->gc)); + assert_true(buf_inc_len(&ctx->metadata, TLS_CRYPT_V2_MAX_METADATA_LEN = + 1)); + assert_false(tls_crypt_v2_wrap_client_key(&ctx->wkc, &ctx->client_key2= , &ctx->metadata, + &ctx->server_keys.encrypt, &= ctx->gc)); } =20 /** @@ -562,28 +545,22 @@ static void tls_crypt_v2_wrap_unwrap_wrong_key(void **state) { - struct test_tls_crypt_v2_context *ctx =3D - (struct test_tls_crypt_v2_context *) *state; + struct test_tls_crypt_v2_context *ctx =3D (struct test_tls_crypt_v2_co= ntext *)*state; - assert_true(tls_crypt_v2_wrap_client_key(&ctx->wkc, &ctx->client_key2, - &ctx->metadata, - &ctx->server_keys.encrypt, - &ctx->gc)); + assert_true(tls_crypt_v2_wrap_client_key(&ctx->wkc, &ctx->client_key2,= &ctx->metadata, + &ctx->server_keys.encrypt, &c= tx->gc)); /* Change server key */ struct key_type kt =3D tls_crypt_kt(); free_key_ctx_bi(&ctx->server_keys); memset(&ctx->server_key2.keys, 0, sizeof(ctx->server_key2.keys)); - init_key_ctx_bi(&ctx->server_keys, &ctx->server_key2, - KEY_DIRECTION_BIDIRECTIONAL, &kt, + init_key_ctx_bi(&ctx->server_keys, &ctx->server_key2, KEY_DIRECTION_BI= DIRECTIONAL, &kt, "wrong tls-crypt-v2 server key"); struct key2 unwrapped_client_key2 =3D { 0 }; - assert_false(tls_crypt_v2_unwrap_client_key(&unwrapped_client_key2, - &ctx->unwrapped_metadata, - ctx->wkc, - &ctx->server_keys.decrypt)= ); + assert_false(tls_crypt_v2_unwrap_client_key(&unwrapped_client_key2, &c= tx->unwrapped_metadata, + ctx->wkc, &ctx->server_key= s.decrypt)); const struct key2 zero =3D { 0 }; assert_true(0 =3D=3D memcmp(&unwrapped_client_key2, &zero, sizeof(zero= ))); @@ -597,23 +574,17 @@ static void tls_crypt_v2_wrap_unwrap_dst_too_small(void **state) { - struct test_tls_crypt_v2_context *ctx =3D - (struct test_tls_crypt_v2_context *) *state; + struct test_tls_crypt_v2_context *ctx =3D (struct test_tls_crypt_v2_co= ntext *)*state; - uint8_t *metadata =3D - buf_write_alloc(&ctx->metadata, TLS_CRYPT_V2_MAX_METADATA_LEN); + uint8_t *metadata =3D buf_write_alloc(&ctx->metadata, TLS_CRYPT_V2_MAX= _METADATA_LEN); assert_true(rand_bytes(metadata, TLS_CRYPT_V2_MAX_METADATA_LEN)); - assert_true(tls_crypt_v2_wrap_client_key(&ctx->wkc, &ctx->client_key2, - &ctx->metadata, - &ctx->server_keys.encrypt, - &ctx->gc)); + assert_true(tls_crypt_v2_wrap_client_key(&ctx->wkc, &ctx->client_key2,= &ctx->metadata, + &ctx->server_keys.encrypt, &c= tx->gc)); struct key2 unwrapped_client_key2 =3D { 0 }; - struct buffer unwrapped_metadata =3D - alloc_buf_gc(TLS_CRYPT_V2_MAX_METADATA_LEN-1, &ctx->gc); - assert_false(tls_crypt_v2_unwrap_client_key(&unwrapped_client_key2, - &unwrapped_metadata, ctx->= wkc, - &ctx->server_keys.decrypt)= ); + struct buffer unwrapped_metadata =3D alloc_buf_gc(TLS_CRYPT_V2_MAX_MET= ADATA_LEN - 1, &ctx->gc); + assert_false(tls_crypt_v2_unwrap_client_key(&unwrapped_client_key2, &u= nwrapped_metadata, + ctx->wkc, &ctx->server_key= s.decrypt)); const struct key2 zero =3D { 0 }; assert_true(0 =3D=3D memcmp(&unwrapped_client_key2, &zero, sizeof(zero= ))); @@ -626,8 +597,7 @@ const char *filename =3D "testfilename.key"; expect_string(__wrap_buffer_write_file, filename, filename); - expect_memory(__wrap_buffer_write_file, pem, test_server_key, - strlen(test_server_key)); + expect_memory(__wrap_buffer_write_file, pem, test_server_key, strlen(t= est_server_key)); will_return(__wrap_buffer_write_file, true); tls_crypt_v2_write_server_key_file(filename); @@ -640,8 +610,7 @@ /* Test writing the client key */ expect_string(__wrap_buffer_write_file, filename, filename); - expect_memory(__wrap_buffer_write_file, pem, test_client_key, - strlen(test_client_key)); + expect_memory(__wrap_buffer_write_file, pem, test_client_key, strlen(t= est_client_key)); will_return(__wrap_buffer_write_file, true); /* Key generation re-reads the created file as a sanity check */ @@ -667,8 +636,7 @@ expect_string(__wrap_buffer_read_from_file, filename, filename); will_return(__wrap_buffer_read_from_file, test_client_key_metadata); - tls_crypt_v2_write_client_key_file(filename, b64metadata, test_server_= key, - true); + tls_crypt_v2_write_client_key_file(filename, b64metadata, test_server_= key, true); } int @@ -676,44 +644,31 @@ { openvpn_unit_test_setup(); const struct CMUnitTest tests[] =3D { - cmocka_unit_test_setup_teardown(tls_crypt_loopback, - test_tls_crypt_setup, + cmocka_unit_test_setup_teardown(tls_crypt_loopback, test_tls_crypt= _setup, test_tls_crypt_teardown), - cmocka_unit_test_setup_teardown(tls_crypt_loopback_zero_len, - test_tls_crypt_setup, + cmocka_unit_test_setup_teardown(tls_crypt_loopback_zero_len, test_= tls_crypt_setup, test_tls_crypt_teardown), - cmocka_unit_test_setup_teardown(tls_crypt_loopback_max_len, - test_tls_crypt_setup, + cmocka_unit_test_setup_teardown(tls_crypt_loopback_max_len, test_t= ls_crypt_setup, test_tls_crypt_teardown), - cmocka_unit_test_setup_teardown(tls_crypt_fail_msg_too_long, - test_tls_crypt_setup, + cmocka_unit_test_setup_teardown(tls_crypt_fail_msg_too_long, test_= tls_crypt_setup, test_tls_crypt_teardown), - cmocka_unit_test_setup_teardown(tls_crypt_fail_invalid_key, - test_tls_crypt_setup, + cmocka_unit_test_setup_teardown(tls_crypt_fail_invalid_key, test_t= ls_crypt_setup, test_tls_crypt_teardown), - cmocka_unit_test_setup_teardown(tls_crypt_fail_replay, - test_tls_crypt_setup, + cmocka_unit_test_setup_teardown(tls_crypt_fail_replay, test_tls_cr= ypt_setup, test_tls_crypt_teardown), - cmocka_unit_test_setup_teardown(tls_crypt_ignore_replay, - test_tls_crypt_setup, + cmocka_unit_test_setup_teardown(tls_crypt_ignore_replay, test_tls_= crypt_setup, test_tls_crypt_teardown), cmocka_unit_test_setup_teardown(tls_crypt_v2_wrap_unwrap_no_metada= ta, - test_tls_crypt_v2_setup, - test_tls_crypt_v2_teardown), + test_tls_crypt_v2_setup, test_tls_= crypt_v2_teardown), cmocka_unit_test_setup_teardown(tls_crypt_v2_wrap_unwrap_max_metad= ata, - test_tls_crypt_v2_setup, - test_tls_crypt_v2_teardown), + test_tls_crypt_v2_setup, test_tls_= crypt_v2_teardown), cmocka_unit_test_setup_teardown(tls_crypt_v2_wrap_too_long_metadat= a, - test_tls_crypt_v2_setup, - test_tls_crypt_v2_teardown), - cmocka_unit_test_setup_teardown(tls_crypt_v2_wrap_unwrap_wrong_key, - test_tls_crypt_v2_setup, + test_tls_crypt_v2_setup, test_tls_= crypt_v2_teardown), + cmocka_unit_test_setup_teardown(tls_crypt_v2_wrap_unwrap_wrong_key= , test_tls_crypt_v2_setup, test_tls_crypt_v2_teardown), cmocka_unit_test_setup_teardown(tls_crypt_v2_wrap_unwrap_dst_too_s= mall, - test_tls_crypt_v2_setup, - test_tls_crypt_v2_teardown), - cmocka_unit_test_setup_teardown(test_tls_crypt_secure_reneg_key, - test_tls_crypt_setup, + test_tls_crypt_v2_setup, test_tls_= crypt_v2_teardown), + cmocka_unit_test_setup_teardown(test_tls_crypt_secure_reneg_key, t= est_tls_crypt_setup, test_tls_crypt_teardown), cmocka_unit_test(test_tls_crypt_v2_write_server_key_file), cmocka_unit_test(test_tls_crypt_v2_write_client_key_file), diff --git a/tests/unit_tests/openvpn/test_user_pass.c b/tests/unit_tests/o= penvpn/test_user_pass.c index 74f67a7..460b37f 100644 --- a/tests/unit_tests/openvpn/test_user_pass.c +++ b/tests/unit_tests/openvpn/test_user_pass.c @@ -64,19 +64,16 @@ assert_true(0); } bool -management_query_user_pass(struct management *man, - struct user_pass *up, - const char *type, - const unsigned int flags, - const char *static_challenge) +management_query_user_pass(struct management *man, struct user_pass *up, c= onst char *type, + const unsigned int flags, const char *static_ch= allenge) { assert_true(0); return false; } /* stubs for some unused functions instead of pulling in too many dependen= cies */ int -parse_line(const char *line, char **p, const int n, const char *file, - const int line_num, int msglevel, struct gc_arena *gc) +parse_line(const char *line, char **p, const int n, const char *file, cons= t int line_num, + int msglevel, struct gc_arena *gc) { assert_true(0); return 0; @@ -162,7 +159,9 @@ /*FIXME: query_user_exec() called even though nothing queued */ will_return(query_user_exec_builtin, true); /* FIXME? content after first two lines just ignored */ - assert_true(get_user_pass_cr(&up, "#iuser and =EC=BB=A4=EB=AE=A4=EB=8B= =88=ED=8B=B0\n//ipassw=C3=B6rd!\nsome other content\nnot relevant", "UT", f= lags, NULL)); + assert_true( + get_user_pass_cr(&up, "#iuser and =EC=BB=A4=EB=AE=A4=EB=8B=88=ED= =8B=B0\n//ipassw=C3=B6rd!\nsome other content\nnot relevant", + "UT", flags, NULL)); assert_true(up.defined); assert_string_equal(up.username, "#iuser and =EC=BB=A4=EB=AE=A4=EB=8B= =88=ED=8B=B0"); assert_string_equal(up.password, "//ipassw=C3=B6rd!"); @@ -250,7 +249,7 @@ unsigned int flags =3D 0; char authfile[PATH_MAX] =3D { 0 }; - openvpn_test_get_srcdir_dir(authfile, PATH_MAX, "input/user_pass.txt" = ); + openvpn_test_get_srcdir_dir(authfile, PATH_MAX, "input/user_pass.txt"); /*FIXME: query_user_exec() called even though nothing queued */ will_return(query_user_exec_builtin, true); @@ -292,7 +291,8 @@ const char *challenge =3D "CRV1:R,E:Om01u7Fh4LrGBS7uh0SWmzwabUiGiW6l:Y= 3Ix:Please enter token PIN"; unsigned int flags =3D GET_USER_PASS_DYNAMIC_CHALLENGE; - expect_string(query_user_exec_builtin, query_user[i].prompt, "CHALLENG= E: Please enter token PIN"); + expect_string(query_user_exec_builtin, query_user[i].prompt, + "CHALLENGE: Please enter token PIN"); will_return(query_user_exec_builtin, "challenge_response"); will_return(query_user_exec_builtin, true); assert_true(get_user_pass_cr(&up, NULL, "UT", flags, challenge)); @@ -314,7 +314,8 @@ expect_string(query_user_exec_builtin, query_user[i].prompt, "Enter UT= Password:"); will_return(query_user_exec_builtin, "cpassword"); will_return(query_user_exec_builtin, true); - expect_string(query_user_exec_builtin, query_user[i].prompt, "CHALLENG= E: Please enter token PIN"); + expect_string(query_user_exec_builtin, query_user[i].prompt, + "CHALLENGE: Please enter token PIN"); will_return(query_user_exec_builtin, "challenge_response"); will_return(query_user_exec_builtin, true); assert_true(get_user_pass_cr(&up, NULL, "UT", flags, challenge)); @@ -332,7 +333,8 @@ expect_string(query_user_exec_builtin, query_user[i].prompt, "Enter UT= Password:"); will_return(query_user_exec_builtin, "c1password"); will_return(query_user_exec_builtin, true); - expect_string(query_user_exec_builtin, query_user[i].prompt, "CHALLENG= E: Please enter token PIN"); + expect_string(query_user_exec_builtin, query_user[i].prompt, + "CHALLENGE: Please enter token PIN"); will_return(query_user_exec_builtin, "0123456"); will_return(query_user_exec_builtin, true); assert_true(get_user_pass_cr(&up, NULL, "UT", flags, challenge)); @@ -343,11 +345,12 @@ reset_user_pass(&up); - flags =3D GET_USER_PASS_STATIC_CHALLENGE|GET_USER_PASS_INLINE_CREDS; + flags =3D GET_USER_PASS_STATIC_CHALLENGE | GET_USER_PASS_INLINE_CREDS; /*FIXME: query_user_exec() called even though nothing queued */ will_return(query_user_exec_builtin, true); - expect_string(query_user_exec_builtin, query_user[i].prompt, "CHALLENG= E: Please enter token PIN"); + expect_string(query_user_exec_builtin, query_user[i].prompt, + "CHALLENGE: Please enter token PIN"); will_return(query_user_exec_builtin, "challenge_response"); will_return(query_user_exec_builtin, true); assert_true(get_user_pass_cr(&up, "iuser\nipassword", "UT", flags, cha= llenge)); diff --git a/tests/unit_tests/plugins/auth-pam/test_search_and_replace.c b/= tests/unit_tests/plugins/auth-pam/test_search_and_replace.c index 50b241d..a861bfd 100644 --- a/tests/unit_tests/plugins/auth-pam/test_search_and_replace.c +++ b/tests/unit_tests/plugins/auth-pam/test_search_and_replace.c @@ -12,7 +12,6 @@ static void pass_any_null_param__returns_null(void **state) { - char DUMMY[] =3D "DUMMY"; assert_null(searchandreplace(NULL, DUMMY, DUMMY)); @@ -23,7 +22,6 @@ static void pass_any_empty_string__returns_null(void **state) { - char DUMMY[] =3D "DUMMY"; char EMPTY[] =3D ""; -- To view, visit http://gerrit.openvpn.net/c/openvpn/+/791?usp=3Demail To unsubscribe, or for help writing mail filters, visit http://gerrit.openv= pn.net/settings Gerrit-Project: openvpn Gerrit-Branch: master Gerrit-Change-Id: I2566ad493629e1f5fdfa6f6483b8973463404e3e Gerrit-Change-Number: 791 Gerrit-PatchSet: 23 Gerrit-Owner: flichtenheld Gerrit-Reviewer: plaisthos Gerrit-CC: cron2 Gerrit-CC: openvpn-devel Gerrit-CC: ordex Gerrit-Attention: plaisthos Gerrit-Attention: cron2 Gerrit-Attention: ordex Gerrit-MessageType: newpatchset --aFNSkfgjrpU= Content-Type: text/html; charset="UTF-8" Content-Transfer-Encoding: quoted-printable

Attention is currently required from: cron2, ordex, plaisthos.

flichtenheld uploaded patch set #23 to this change.

=

View C= hange

Reformat the whole project with clang-format

Done with pre= -commit run -a, so the version
defined in pre-commit config is used.
=
This also changes the Github workflow so that
there is no commit tha= t fails GHA.

Change-Id: I2566ad493629e1f5fdfa6f6483b8973463404e3eSigned-off-by: Frank Lichtenheld <frank@...2641...>
---
M .git= hub/workflows/build.yaml
M include/openvpn-msg.h
M sample/sample-plug= ins/client-connect/sample-client-connect.c
M sample/sample-plugins/defer= /multi-auth.c
M sample/sample-plugins/keying-material-exporter-demo/keyi= ngmaterialexporter.c
M sample/sample-plugins/log/log.c
M sample/sampl= e-plugins/log/log_v3.c
M sample/sample-plugins/simple/base64.c
M samp= le/sample-plugins/simple/simple.c
M src/compat/compat-basename.c
M sr= c/compat/compat-dirname.c
M src/compat/compat-gettimeofday.c
M src/op= envpn/argv.c
M src/openvpn/argv.h
M src/openvpn/auth_token.c
M src= /openvpn/auth_token.h
M src/openvpn/base64.c
M src/openvpn/base64.hM src/openvpn/basic.h
M src/openvpn/buffer.c
M src/openvpn/buffer.h=
M src/openvpn/circ_list.h
M src/openvpn/clinat.c
M src/openvpn/cl= inat.h
M src/openvpn/common.h
M src/openvpn/comp-lz4.c
M src/openv= pn/comp.c
M src/openvpn/comp.h
M src/openvpn/compstub.c
M src/open= vpn/console.c
M src/openvpn/console.h
M src/openvpn/console_builtin.c=
M src/openvpn/console_systemd.c
M src/openvpn/crypto.c
M src/open= vpn/crypto.h
M src/openvpn/crypto_backend.h
M src/openvpn/crypto_epoc= h.c
M src/openvpn/crypto_epoch.h
M src/openvpn/crypto_mbedtls.c
M = src/openvpn/crypto_mbedtls.h
M src/openvpn/crypto_openssl.c
M src/ope= nvpn/crypto_openssl.h
M src/openvpn/cryptoapi.c
M src/openvpn/dco.cM src/openvpn/dco.h
M src/openvpn/dco_freebsd.c
M src/openvpn/dco_f= reebsd.h
M src/openvpn/dco_internal.h
M src/openvpn/dco_linux.c
M = src/openvpn/dco_linux.h
M src/openvpn/dco_win.c
M src/openvpn/dco_win= .h
M src/openvpn/dhcp.c
M src/openvpn/dhcp.h
M src/openvpn/dns.cM src/openvpn/dns.h
M src/openvpn/env_set.c
M src/openvpn/env_set.h=
M src/openvpn/errlevel.h
M src/openvpn/error.c
M src/openvpn/erro= r.h
M src/openvpn/event.c
M src/openvpn/event.h
M src/openvpn/fdmi= sc.c
M src/openvpn/fdmisc.h
M src/openvpn/forward.c
M src/openvpn/= forward.h
M src/openvpn/fragment.c
M src/openvpn/fragment.h
M src/= openvpn/gremlin.c
M src/openvpn/gremlin.h
M src/openvpn/helper.c
M= src/openvpn/httpdigest.c
M src/openvpn/httpdigest.h
M src/openvpn/in= it.c
M src/openvpn/init.h
M src/openvpn/integer.h
M src/openvpn/in= terval.c
M src/openvpn/interval.h
M src/openvpn/list.c
M src/openv= pn/list.h
M src/openvpn/lladdr.c
M src/openvpn/lzo.c
M src/openvpn= /lzo.h
M src/openvpn/manage.c
M src/openvpn/manage.h
M src/openvpn= /mbedtls_compat.h
M src/openvpn/mbuf.c
M src/openvpn/mbuf.h
M src/= openvpn/memdbg.h
M src/openvpn/misc.c
M src/openvpn/misc.h
M src/o= penvpn/mroute.c
M src/openvpn/mroute.h
M src/openvpn/mss.c
M src/o= penvpn/mss.h
M src/openvpn/mstats.c
M src/openvpn/mstats.h
M src/o= penvpn/mtcp.c
M src/openvpn/mtcp.h
M src/openvpn/mtu.c
M src/openv= pn/mtu.h
M src/openvpn/mudp.c
M src/openvpn/multi.c
M src/openvpn/= multi.h
M src/openvpn/multi_io.c
M src/openvpn/networking.h
M src/= openvpn/networking_freebsd.c
M src/openvpn/networking_iproute2.c
M sr= c/openvpn/networking_sitnl.c
M src/openvpn/ntlm.c
M src/openvpn/occ.c=
M src/openvpn/occ.h
M src/openvpn/openssl_compat.h
M src/openvpn/= openvpn.c
M src/openvpn/openvpn.h
M src/openvpn/options.c
M src/op= envpn/options.h
M src/openvpn/options_util.c
M src/openvpn/options_ut= il.h
M src/openvpn/otime.c
M src/openvpn/otime.h
M src/openvpn/ovp= n_dco_freebsd.h
M src/openvpn/packet_id.c
M src/openvpn/packet_id.hM src/openvpn/perf.c
M src/openvpn/perf.h
M src/openvpn/ping.c
M= src/openvpn/ping.h
M src/openvpn/pkcs11.c
M src/openvpn/pkcs11.h
= M src/openvpn/pkcs11_backend.h
M src/openvpn/pkcs11_mbedtls.c
M src/o= penvpn/pkcs11_openssl.c
M src/openvpn/platform.c
M src/openvpn/platfo= rm.h
M src/openvpn/plugin.c
M src/openvpn/plugin.h
M src/openvpn/p= ool.c
M src/openvpn/pool.h
M src/openvpn/proto.c
M src/openvpn/pro= to.h
M src/openvpn/proxy.c
M src/openvpn/proxy.h
M src/openvpn/ps.= c
M src/openvpn/ps.h
M src/openvpn/push.c
M src/openvpn/push.h
= M src/openvpn/push_util.c
M src/openvpn/pushlist.h
M src/openvpn/refl= ect_filter.c
M src/openvpn/reflect_filter.h
M src/openvpn/reliable.c<= br>M src/openvpn/reliable.h
A src/openvpn/ring_buffer.h
M src/openvpn= /route.c
M src/openvpn/route.h
M src/openvpn/run_command.c
M src/o= penvpn/run_command.h
M src/openvpn/schedule.c
M src/openvpn/schedule.= h
M src/openvpn/session_id.h
M src/openvpn/shaper.c
M src/openvpn/= shaper.h
M src/openvpn/sig.c
M src/openvpn/sig.h
M src/openvpn/soc= ket.c
M src/openvpn/socket.h
M src/openvpn/socks.c
M src/openvpn/s= ocks.h
M src/openvpn/ssl.c
M src/openvpn/ssl.h
M src/openvpn/ssl_b= ackend.h
M src/openvpn/ssl_common.h
M src/openvpn/ssl_mbedtls.c
M = src/openvpn/ssl_mbedtls.h
M src/openvpn/ssl_ncp.c
M src/openvpn/ssl_n= cp.h
M src/openvpn/ssl_openssl.c
M src/openvpn/ssl_openssl.h
M src= /openvpn/ssl_pkt.c
M src/openvpn/ssl_pkt.h
M src/openvpn/ssl_util.cM src/openvpn/ssl_util.h
M src/openvpn/ssl_verify.c
M src/openvpn/s= sl_verify.h
M src/openvpn/ssl_verify_backend.h
M src/openvpn/ssl_veri= fy_mbedtls.c
M src/openvpn/ssl_verify_mbedtls.h
M src/openvpn/ssl_ver= ify_openssl.c
M src/openvpn/status.c
M src/openvpn/status.h
M src/= openvpn/syshead.h
M src/openvpn/tls_crypt.c
M src/openvpn/tls_crypt.h=
M src/openvpn/tun.c
M src/openvpn/tun.h
M src/openvpn/tun_afunix.= c
M src/openvpn/tun_afunix.h
M src/openvpn/vlan.c
M src/openvpn/vl= an.h
M src/openvpn/wfp_block.c
M src/openvpn/wfp_block.h
M src/ope= nvpn/win32-util.c
M src/openvpn/win32.c
M src/openvpn/win32.h
M sr= c/openvpn/xkey_common.h
M src/openvpn/xkey_helper.c
M src/openvpn/xke= y_provider.c
M src/openvpnmsica/dllmain.c
M src/openvpnmsica/msica_ar= g.c
M src/openvpnmsica/msica_arg.h
M src/openvpnmsica/msiex.c
M sr= c/openvpnmsica/msiex.h
M src/openvpnmsica/openvpnmsica.c
M src/openvp= nmsica/openvpnmsica.h
M src/openvpnserv/common.c
M src/openvpnserv/in= teractive.c
M src/openvpnserv/service.c
M src/openvpnserv/service.hM src/openvpnserv/validate.c
M src/openvpnserv/validate.h
M src/plu= gins/auth-pam/auth-pam.c
M src/plugins/auth-pam/pamdl.c
M src/plugins= /auth-pam/utils.c
M src/plugins/auth-pam/utils.h
M src/plugins/down-r= oot/down-root.c
M src/tapctl/basic.h
M src/tapctl/error.h
M src/ta= pctl/main.c
M src/tapctl/tap.c
M src/tapctl/tap.h
M tests/ntlm_sup= port.c
M tests/unit_tests/example_test/test.c
M tests/unit_tests/exam= ple_test/test2.c
M tests/unit_tests/openvpn/cert_data.h
M tests/unit_= tests/openvpn/mock_management.c
M tests/unit_tests/openvpn/mock_msg.cM tests/unit_tests/openvpn/mock_msg.h
M tests/unit_tests/openvpn/mock_s= sl_dependencies.c
M tests/unit_tests/openvpn/pkey_test_utils.c
M test= s/unit_tests/openvpn/test_argv.c
M tests/unit_tests/openvpn/test_auth_to= ken.c
M tests/unit_tests/openvpn/test_buffer.c
M tests/unit_tests/ope= nvpn/test_crypto.c
M tests/unit_tests/openvpn/test_cryptoapi.c
M test= s/unit_tests/openvpn/test_misc.c
M tests/unit_tests/openvpn/test_ncp.cM tests/unit_tests/openvpn/test_networking.c
M tests/unit_tests/openvp= n/test_packet_id.c
M tests/unit_tests/openvpn/test_pkcs11.c
M tests/u= nit_tests/openvpn/test_pkt.c
M tests/unit_tests/openvpn/test_provider.c<= br>M tests/unit_tests/openvpn/test_push_update_msg.c
M tests/unit_tests/= openvpn/test_ssl.c
M tests/unit_tests/openvpn/test_tls_crypt.c
M test= s/unit_tests/openvpn/test_user_pass.c
M tests/unit_tests/plugins/auth-pa= m/test_search_and_replace.c
258 files changed, 12,008 insertions(+), 15,= 234 deletions(-)

git pull ssh://gerrit.openvpn.net:29418/openvpn =
refs/changes/91/791/23
diff --git a/.github/workflows/build.yaml b/=
.github/workflows/build.yaml
index bd5895b..ba7f64b 100644<= /span>
--- a/.github/workflows/build.yaml
+++ b/.g= ithub/workflows/build.yaml
@@ -5,35 +5,26 @@
pull_request:


jobs:
- checkuncrustify:
- name: "Check code style with Un= crustify"
- # U= buntu 22.04 has uncrustify 0.72_f
- runs-on: ubuntu-22.04
+ clang-format:
+ name: Check code style with clang-format
+ runs-on: ubuntu-24.04
= steps:
- name: Install dependencies

- run: sudo apt updat= e && sudo apt install -y uncrustify
+ run: |
+ sudo apt update && sudo apt install -y= python3-pip
+ = pip3 install pre-commit
- name: Checkout OpenVPN<= /span>
uses: actions/checkout@...2844... # v4.2.2<= br>- with:
- path: openvpn

- - name: Show uncrustify versi= on
- run: uncrus= tify --version
- -= name: Run uncrustify
-= run: ./dev-tools/reformat-all.sh
- working-directory: openvpn
+ - name: Run clang-format
= + run: pre-commit run -a= --show-diff-on-failure || true
- name: Check for ch= anges
- run: git= diff --output=3Duncrustify-changes.patch
- working-directory: openvpn
- - name: Show changes on standard out= put
- run: git d= iff
- working-di= rectory: openvpn
+ = run: git diff --output=3Dformat-changes.patch
-= uses: actions/upload-artifact@...2868... # v4.6.2
= with:
- name:= uncrustify-changes.patch
- path: 'openvpn/uncrustify-changes.patch'
+ name: format-changes.p= atch
+ path:= format-changes.patch
- name: Set job status<= br>- run: test ! -s uncrus= tify-changes.patch
- = working-directory: openvpn
+ run: test ! -s format-changes.patch

android:
strategy:
d= iff --git a/include/openvpn-msg.h b/include/openvpn-msg.h
i= ndex 106a274..a692137 100644
--- a/include/openvpn-msg.h

+++ b/include/openvpn-msg.h
@@ -26,7 +26,8 @@=
#include <windef.h>
#include <w= s2tcpip.h>

-typedef enum {
+typedef enum
+{<= /span>
msg_acknowledgement,
msg_add_addr= ess,
msg_del_address,
@@ -50,28 +51,33= @@
msg_create_adapter
} message_type= _t;

-= typedef struct {
+typ= edef struct
+{=
message_type_t type;
size_t size;
int message_id;
} message_header_t;=

-typedef un= ion {
+typedef union<= /span>
+{
= struct in_addr ipv4;
struct in6_addr ipv6; } inet_address_t;

-typedef struct {
+typedef struct
+{
int index;
char = name[256];
} interface_t;

-typedef enum {

- wfp_block_local =3D 1<<0,<= br>- wfp_block_dns =3D 1<&l= t;1
+typedef enum

+{
+ wfp_block_local =3D 1 << 0,
+ wfp_block_dns =3D 1= << 1
} wfp_block_flags_t;
<= br>-typedef struct {
+typedef struct

+{
message_header= _t header;
short family;
inet_add= ress_t address;
@@ -79,7 +85,8 @@
inte= rface_t iface;
} address_message_t;

-typedef struct {+typedef struct
+{

message_hea= der_t header;
short family;
inet_= address_t prefix;
@@ -89,7 +96,8 @@
in= t metric;
} route_message_t;

<= span style=3D"color: hsl(0, 100%, 40%);">-typedef struct {
+typedef struct
+{
message_header_t h= eader;
interface_t iface;
char do= mains[512];
@@ -99,14 +107,16 @@
} dns_cfg= _message_t;


-typedef enum {
+typedef enum
+{
nrpt_dnssec
} nrpt_fl= ags_t;

+#define NRPT_ADDR_NUM 8 /* Max. n= umber of addresses */
#define NRPT_ADDR_SIZE 48 /* Max. ad= dress strlen + some */
typedef char nrpt_address_t[NRPT_AD= DR_SIZE];
-typedef stru= ct {
+typedef struct<= /span>
+{
= message_header_t header;
interface_t iface;<= br> nrpt_address_t addresses[NRPT_ADDR_NUM];
@@ -= 115,14 +125,16 @@
nrpt_flags_t flags;
= } nrpt_dns_cfg_message_t;

-typedef struct {
+typedef struct
+{
message_header_t header;
interface_t iface;

int addr_len;
inet_address_t addr[4]; /* support up to 4 dns addresses */=
} wins_cfg_message_t;

-typedef struct {
+typedef struct
+{
message_header_t header;=
interface_t iface;
int disable_nbt;
@@ -134,41 +146,48 @@

/* TO= DO: NTP */

-typedef struct {
+typedef struct
+{=
message_header_t header;
short f= amily;
interface_t iface;
} flush_nei= ghbors_message_t;

-typedef struct {
+typedef struct
+{
message_header_t header;
= int error_number;
} ack_message_t;

-typedef struct {
= +typedef struct
+{

message_head= er_t header;
wfp_block_flags_t flags;
= interface_t iface;
} wfp_block_message_t;
<= span>

-typedef struct = {
+typedef struct
+{
= message_header_t header;
interface_t iface;
= } enable_dhcp_message_t;

-typedef struct {
+typedef struct
+{
message_header_t header;<= br> interface_t iface;
short family;<= br> int mtu;
} set_mtu_message_t;

-typedef enum {
+typedef enum
= +{
ADAPTER= _TYPE_DCO,
ADAPTER_TYPE_TAP,
} adapte= r_type_t;

-typedef struct {
+{<= /span>
message_header_t header;
adapter_= type_t adapter_type;
} create_adapter_message_t;diff --git a/sample/sample-plugins/client-connect/sample-client-conn= ect.c b/sample/sample-plugins/client-connect/sample-client-connect.c=
index 3dda782..7e3b5a9 100644
--- a/sample/sample= -plugins/client-connect/sample-client-connect.c
+++ b/sampl= e/sample-plugins/client-connect/sample-client-connect.c
@@ = -58,8 +58,9 @@
* Our context, where we keep our state.

*/

-struct plugin_context {
- int verb; /* logging verbosi= ty */
+struct plugin_= context
+{
= + int verb; /* logging verbo= sity */
};

/* this is u= sed for the CLIENT_CONNECT_V2 async/deferred handler
@@ -68= ,8 +69,9 @@
* this, and the "CLIENT_CONNECT_DEFER_V2= " handler looks at it to see
* if it's time yet = to succeed/fail
*/
-struct plugin_per_client_context {
- time_t sleep_until; /* wake= up time (time() + sleep) */
+struct plugin_per_client_context
+{
-openvpn_plugin_open_v3(const= int v3structver,
- = struct openvpn_plugin_args_open_in const *args,+openvpn_plugin_open_v3(const= int v3structver, struct openvpn_plugin_args_open_in const *args, struct openvpn_plugin_args_open_return *ret)=
{
/* const char **argv =3D args->= argv; */ /* command line arguments (unused) */
@@ -127,7 +1= 28,9 @@
/* Check API compatibility -- struct version 5= or higher needed */
if (v3structver < 5) {
- = fprintf(stderr, "sample-client-connect: this plugin is incompatible wi= th the running version of OpenVPN\n");
+ fprintf(
+ stderr,
+ "sample-client-connect: this plugin i= s incompatible with the running version of OpenVPN\n");
return OPENVPN_PLUGIN_FUNC_ERROR;
}<= br>
@@ -143,18 +146,17 @@
/*
* Intercept just about everything...
= */
- ret->typ= e_mask =3D
- OPE= NVPN_PLUGIN_MASK(OPENVPN_PLUGIN_UP)
- |OPENVPN_PLUGIN_MASK(OPENVPN_PLUGIN_DOWN)
<= span style=3D"color: hsl(0, 100%, 40%);">- |OPENVPN_PLUGIN_MASK(OPEN= VPN_PLUGIN_ROUTE_UP)

- = |OPENVPN_PLUGIN_MASK(OPENVPN_PLUGIN_IPCHANGE)
- |OPENVPN_PLUGIN_MASK(OPENVPN_PLUGIN= _TLS_VERIFY)
- |= OPENVPN_PLUGIN_MASK(OPENVPN_PLUGIN_CLIENT_CONNECT)
- |OPENVPN_PLUGIN_MASK(OPENVPN_PLUGIN_CL= IENT_CONNECT_V2)
- = |OPENVPN_PLUGIN_MASK(OPENVPN_PLUGIN_CLIENT_CONNECT_DEFER_V2)
<= span style=3D"color: hsl(0, 100%, 40%);">- |OPENVPN_PLUGIN_MASK(OPEN= VPN_PLUGIN_CLIENT_DISCONNECT)
- |OPENVPN_PLUGIN_MASK(OPENVPN_PLUGIN_LEARN_ADDRESS)- |OPENVPN_PLUGIN_MASK(O= PENVPN_PLUGIN_TLS_FINAL);
+ ret->type_mask =3D OPENVPN_PLUGIN_MASK(OPENVPN_PLUGIN_UP)

+ | O= PENVPN_PLUGIN_MASK(OPENVPN_PLUGIN_DOWN)
+ | OPENVPN_PLUGIN_MASK(OPENVPN_PLUG= IN_ROUTE_UP)
+ = | OPENVPN_PLUGIN_MASK(OPENVPN_PLUGIN_IPCHANGE)
+ | OPENVPN_PLU= GIN_MASK(OPENVPN_PLUGIN_TLS_VERIFY)
+ | OPENVPN_PLUGIN_MASK(OPENVPN_PLUGIN_C= LIENT_CONNECT)
+ = | OPENVPN_PLUGIN_MASK(OPENVPN_PLUGIN_CLIENT_CONNECT_V2)
+ | = OPENVPN_PLUGIN_MASK(OPENVPN_PLUGIN_CLIENT_CONNECT_DEFER_V2)
+ | OPENVPN_PLUG= IN_MASK(OPENVPN_PLUGIN_CLIENT_DISCONNECT)

+ | OPENVPN_PLUGIN_MASK(OPENVPN_PL= UGIN_LEARN_ADDRESS)
+= | OPENVPN_PLUGIN_MASK(OPENVPN_PLUGIN_TLS_FINAL);

/* Save global pointers to functions expo= rted from openvpn */
plugin_log =3D args->callbacks= ->plugin_log;
@@ -166,7 +168,7 @@
= */
context->verb =3D atoi_null0(get_env("verb&= quot;, envp));

- ret->handle =3D (openvpn_plugin_handle_t *) context;

+ ret->handle =3D (= openvpn_plugin_handle_t *)context;
plugin_log(PLOG_NOT= E, MODULE, "initialization succeeded");
retu= rn OPENVPN_PLUGIN_FUNC_SUCCESS;

@@ -242,8= +244,10 @@
const char *ccd_file =3D get_env("cli= ent_connect_deferred_file", envp);
if (!ccd_file)=
{
- plugin_log(PLOG_NOTE, MODULE, "env has UV_WANT_CC_ASYNC=3D%d= , but "
- = "'client_connect_deferred_file' not set -> fail&q= uot;, seconds);
+ = plugin_log(PLOG_NOTE, MODULE,
+ "env has UV_WANT_CC_ASYNC=3D%d, but &= quot;
+ = "'client_connect_deferred_file' not set -> fail",=
+ = seconds);
return OPENVPN_PLUGIN_FUNC_ERROR;=
}

@@ -257,13 +261,13 @@
int fd =3D open(ccd_file, O_WRONLY);
= if (fd < 0)
{
- plugin_log(PLOG_ERR|PLOG_ERRNO, MODULE, "ope= n('%s') failed", ccd_file);
+ plugin_log(PLOG_ERR | PLOG_ERRNO, MODULE, &quo= t;open('%s') failed", ccd_file);
retu= rn OPENVPN_PLUGIN_FUNC_ERROR;
}

if (write(fd, "2", 1) !=3D 1)
= {
- plugin_lo= g(PLOG_ERR|PLOG_ERRNO, MODULE, "write to '%s' failed", cc= d_file );
+ pl= ugin_log(PLOG_ERR | PLOG_ERRNO, MODULE, "write to '%s' failed&= quot;, ccd_file);
close(fd);
= return OPENVPN_PLUGIN_FUNC_ERROR;
}
@@ -277,11 +281,11 @@


/* fork, sle= ep, succeed/fail according to env vars */
pid_t p1 =3D= fork();
- if (p1 &l= t; 0) /* Fork failed */
+ if (p1 < 0) /* Fork failed */
= {
return OPENVPN_PLUGIN_FUNC_ERROR;
<= span> }

- if (p1= > 0) /* parent process */
+ if (p1 > 0) /* parent process */ {
waitpid(p1, NULL, 0);
return OPENVPN_PLUGIN_FUNC_DEFERRED;
@@ -291,10 = +295,10 @@
pid_t p2 =3D fork();
i= f (p2 < 0)
{
- plugin_log(PLOG_ERR|PLOG_ERRNO, MODULE, "BACKGR= OUND: fork(2) failed");
+ plugin_log(PLOG_ERR | PLOG_ERRNO, MODULE, "BACKGROUND= : fork(2) failed");
exit(1);
= }
- if (p2 >= 0) /* new parent: exit right away */
+ if (p2 > 0) /* new parent: exit ri= ght away */
{
exit(0);=
}
@@ -324,16 +328,16 @@
= fd =3D open(ccd_file, O_WRONLY);
if (fd < 0)
{
- = plugin_log(PLOG_ERR|PLOG_ERRNO, MODULE, "open('%s') failed= ", ccd_file);
+ = plugin_log(PLOG_ERR | PLOG_ERRNO, MODULE, "open('%s') f= ailed", ccd_file);
exit(1);
= }

plugin_log(PLOG_NOTE, MODULE, = "cc_handle_deferred_v1: done, signalling %s",
- (ret =3D=3D OPENVPN_PLUGIN= _FUNC_SUCCESS) ? "success" : "fail" );
+ (ret =3D=3D OPENVPN_P= LUGIN_FUNC_SUCCESS) ? "success" : "fail");

if (write(fd, (ret =3D=3D OPENVPN_PLUGIN_FUNC_SU= CCESS) ? "1" : "0", 1) !=3D 1)
{
- plugin_log(PLOG= _ERR|PLOG_ERRNO, MODULE, "write to '%s' failed", ccd_file= );
+ plugin_l= og(PLOG_ERR | PLOG_ERRNO, MODULE, "write to '%s' failed",= ccd_file);
}
close(fd);
@@ -341,14 +345,12 @@
}
int
-openvpn_plugin_client_connect(struct plugin_context *context,

- = const char **argv,
= - const char **envp)
+openvpn_plugin_client_connect(struct plugin_c= ontext *context, const char **argv, const char **envp)
{
/* log environment variables handed to us by OpenVPN, b= ut
* only if "setenv verb" is 3 or higher (= arbitrary number)
*/
- if (context->verb>=3D3)
+ if (context->verb >=3D 3)
{
for (int i =3D 0; argv[i]; i++)=
{
@@ -389,8 +391,7 @@
<= span>

int
openvpn_plugin_client_connect_= v2(struct plugin_context *context,
- struct plugin_per_client_cont= ext *pcc,
- = const char **envp,
+ struct plugin_per_clie= nt_context *pcc, const char **envp,
= struct openvpn_plugin_string_list **return_list)
{

/* by setting "UV_WANT_CC2_ASYNC" we go = to async/deferred mode */
@@ -420,7 +421,8 @@
pcc->want_fail =3D (want_fail !=3D NULL);
= pcc->want_disable =3D (want_disable !=3D NULL);
= pcc->client_config =3D client_config;
- plugin_log(PLOG_NOTE, MODULE, "env = has UV_WANT_CC2_ASYNC=3D%s -> set up deferred handler", want_async)= ;
+ plugin_log= (PLOG_NOTE, MODULE, "env has UV_WANT_CC2_ASYNC=3D%s -> set up defer= red handler",
+ = want_async);
return OPENVPN_PLUG= IN_FUNC_DEFERRED;
}

= @@ -431,8 +433,7 @@
return OPENVPN_PLUGIN_FUNC_ERR= OR;
}

- struct openvpn_plugin_string_list *rl =3D=
- calloc(1, sizeof(str= uct openvpn_plugin_string_list));
+ struct openvpn_plugin_string_list *rl =3D calloc(1, sizeo= f(struct openvpn_plugin_string_list));
if (!rl)=
{
plugin_log(PLOG_ERR, MODULE, &quo= t;malloc(return_list) failed");
@@ -466,12 +467,10 @@<= /span>
int
openvpn_plugin_client_connect_defer_v= 2(struct plugin_context *context,
= struct plugin_per_client_context *pcc,
- stru= ct openvpn_plugin_string_list
- **return_list)
+ = struct openvpn_plugin_string_list **return_list)

{
time_t time_left =3D pcc->sleep_until - time(NULL);<= /span>
- plugin_log(PLOG_NO= TE, MODULE, "defer_v2: seconds left=3D%d",
- (int) time_left);
= + plugin_log(PLOG_NOTE, MODU= LE, "defer_v2: seconds left=3D%d", (int)time_left);

/* not yet due? */
if (time_= left > 0)
@@ -482,15 +481,14 @@
/* = client wants fail? */
if (pcc->want_fail) {
- = plugin_log(PLOG_NOTE, MODULE, "env has UV_WANT_CC2_FAIL -> fail&quo= t; );
+ plugin= _log(PLOG_NOTE, MODULE, "env has UV_WANT_CC2_FAIL -> fail");
return OPENVPN_PLUGIN_FUNC_ERROR;
= }

/* fill in RL according to wit= h-disable / without-disable */

/* TO= DO: unify this with non-deferred case */
- struct openvpn_plugin_string_list *rl =3D
= - calloc(1, sizeof(struct = openvpn_plugin_string_list));
+ struct openvpn_plugin_string_list *rl =3D calloc(1, sizeof(st= ruct openvpn_plugin_string_list));
if (!rl)
= {
plugin_log(PLOG_ERR, MODULE, "ma= lloc(return_list) failed");
@@ -522,15 +520,12 @@
}

OPENVPN_EXPORT int=
-openvpn_plugin_func_v2(openv= pn_plugin_handle_t handle,
- const int type,
- const char *argv[],
= - const cha= r *envp[],
- = void *per_client_context,
+openvpn_plugin_func_v2(openvpn_plugin_handle_t handle, co= nst int type, const char *argv[],
+ const char *envp[], void *per_client_c= ontext,
struct openvpn_plugin_strin= g_list **return_list)
{
- struct plugin_context *context =3D (struct plugin_co= ntext *) handle;
- s= truct plugin_per_client_context *pcc =3D (struct plugin_per_client_context = *) per_client_context;
+ struct plugin_pe= r_client_context *pcc =3D (struct plugin_per_client_context *)per_client_co= ntext;

/* for most functions, we jus= t "don't do anything" but log the
* eve= nt received (so one can follow it in the log and understand
@@ -564,13 +559,11 @@


case OPEN= VPN_PLUGIN_CLIENT_CONNECT_V2:
plugin_log(PLOG_= NOTE, MODULE, "OPENVPN_PLUGIN_CLIENT_CONNECT_V2");
- return openvpn_plugin_cl= ient_connect_v2(context, pcc, envp,

- return_li= st);
+ ret= urn openvpn_plugin_client_connect_v2(context, pcc, envp, return_list);

case OPENVPN_PLUGIN_CLIENT_CONNECT_D= EFER_V2:
plugin_log(PLOG_NOTE, MODULE, "O= PENVPN_PLUGIN_CLIENT_CONNECT_DEFER_V2");
- return openvpn_plugin_client_connect_de= fer_v2(context, pcc,
- = return_list);
+ return openv= pn_plugin_client_connect_defer_v2(context, pcc, return_list);

case OPENVPN_PLUGIN_CLIENT_DISCONNECT:=
plugin_log(PLOG_NOTE, MODULE, "OPENVPN_PLUGIN_C= LIENT_DISCONNECT");
@@ -607,7 +600,7 @@
OPENVPN_EXPORT void

openvpn_plugin_close_v1(openvpn_plu= gin_handle_t handle)
{
- struct plugin_context *context =3D (struct plugin_con= text *) handle;
+ = struct plugin_context *context =3D (struct plugin_context *)handle;<= br> printf("FUNC: openvpn_plugin_close_v1\n"); free(context);
}
diff --git a= /sample/sample-plugins/defer/multi-auth.c b/sample/sample-plugins/defer/mul= ti-auth.c
index 9a2cb13..3c9c9c6 100644
---= a/sample/sample-plugins/defer/multi-auth.c
+++ b/sample/sa= mple-plugins/defer/multi-auth.c
@@ -62,7 +62,8 @@ * Our context, where we keep our state.
*/

-struct pl= ugin_context {
+struc= t plugin_context
+{
int test_deferred_auth;
char *auth= id;
char *test_valid_user;
@@ -103,11 = +104,12 @@
* structver '5' here to indicate a des= ire for modern openvpn, rather
* than a need for any part= icular feature found in structver beyond '1'.
*/<= /span>
-#define OPENVPN_PLUGIN= _VERSION_MIN 3
+#defi= ne OPENVPN_PLUGIN_VERSION_MIN 3
#define OPENVPN_PLUGIN_S= TRUCTVER_MIN 5


-struct plugin_per_client_context {
<= span style=3D"color: hsl(120, 100%, 40%);">+struct plugin_per_client_contex= t

+{
= int n_calls;
bool generated_pf_file;
};

@@ -175,13 +177,13 @@

<= span> /* use v3 functions so we can use openvpn's logging and base64 et= c. */

OPENVPN_EXPORT int
-openvpn_plugin_open_v3(const int v3structver,- struct o= penvpn_plugin_args_open_in const *args,
+openvpn_plugin_open_v3(const int v3structver, struct op= envpn_plugin_args_open_in const *args,
= struct openvpn_plugin_args_open_return *ret)
{<= br> if (v3structver < OPENVPN_PLUGIN_STRUCTVER_MIN)
= {
- f= printf(stderr, "%s: this plugin is incompatible with the running versi= on of OpenVPN\n", MODULE);
+ fprintf(stderr, "%s: this plugin is incompatible w= ith the running version of OpenVPN\n",
+ MODULE);
r= eturn OPENVPN_PLUGIN_FUNC_ERROR;
}

@@ -194,7 +196,7 @@
* Allocate our con= text
*/
struct plugin_context *c= ontext =3D NULL;
- c= ontext =3D (struct plugin_context *) calloc(1, sizeof(struct plugin_context= ));
+ context =3D = (struct plugin_context *)calloc(1, sizeof(struct plugin_context)); if (!context)
{
= goto error;
@@ -238,7 +240,7 @@
* Whi= ch callbacks to intercept.
*/
re= t->type_mask =3D OPENVPN_PLUGIN_MASK(OPENVPN_PLUGIN_AUTH_USER_PASS_VERIF= Y);
- ret->handle= =3D (openvpn_plugin_handle_t *) context;
+ ret->handle =3D (openvpn_plugin_handle_t *)con= text;

plog(context, PLOG_NOTE, "= ;initialization succeeded");
return OPENVPN_PLUGI= N_FUNC_SUCCESS;
@@ -253,29 +255,22 @@
}

static bool
-do_auth_user_pass(struct plugin_context *context,
- const = char *username, const char *password)
+do_auth_user_pass(struct plugin_context *context, const c= har *username, const char *password)
{
- plog(context, PLOG_NOTE,
- "expect_user=3D%s, r= eceived_user=3D%s, expect_passw=3D%s, received_passw=3D%s",

= - np(context->test_val= id_user),
- np(= username),
- np= (context->test_valid_pass),
- np(password));
+ plog(context, PLOG_NOTE, "expect_user=3D%s, received_= user=3D%s, expect_passw=3D%s, received_passw=3D%s",
+ np(context->test_valid_use= r), np(username), np(context->test_valid_pass), np(password));
if (context->test_valid_user && co= ntext->test_valid_pass)
{
= if ((strcmp(context->test_valid_user, username) !=3D 0)
= || (strcmp(context->test_valid_pass, password) !=3D 0))

{
- plog(context, PLOG_ERR,
- "User/Password auth result: FAIL"= ;);
+ plog= (context, PLOG_ERR, "User/Password auth result: FAIL"); return false;
}
else
{
- plog(context, PLOG_NOTE,
- "User/Password au= th result: PASS");
+ plog(context, PLOG_NOTE, "User/Password auth result: P= ASS");
return true;
= }
}
@@ -284,8 +279,7 @@
=

static int
-auth_user_pass_verify(struct plugin_context= *context,
- = struct plugin_per_client_context *pcc,
+auth_user_pass_verify(struct plugin_context *= context, struct plugin_per_client_context *pcc,
= const char *argv[], const char *envp[])
{

/* get username/password from envp string array */<= br>@@ -295,8 +289,8 @@
if (!context->test_def= erred_auth)
{
plog(context, P= LOG_NOTE, "Direct authentication");
- return do_auth_user_pass(context, username,= password) ?
- = OPENVPN_PLUGIN_FUNC_SUCCESS : OPENVPN_PLUGIN_FUNC_ERROR;
+ return do_auth_user_pass= (context, username, password) ? OPENVPN_PLUGIN_FUNC_SUCCESS
+ = : OPENVPN_PLUGIN_FUNC_ERROR;
= }

/* get auth_control_file filenam= e from envp string array*/
@@ -317,11 +311,11 @@
=
/* fork, sleep, succeed (no "real" a= uth done =3D always succeed) */
pid_t p1 =3D fork();
- if (p1 < 0) = /* Fork failed */
+ if (p1 < 0) /* Fork failed */
{

return OPENVPN_PLUGIN_FUNC_ERROR;
= }
- if (p1 > 0) = /* parent process */
+ if (p1 > 0) /* parent process */
= {
waitpid(p1, NULL, 0);
= return OPENVPN_PLUGIN_FUNC_DEFERRED;
@@ -331,11 +325,11 @@=
pid_t p2 =3D fork();
if (p2 <= 0)
{
- plog(context, PLOG_ERR|PLOG_ERRNO, "BACKGROUND: fork(2) f= ailed");
+ = plog(context, PLOG_ERR | PLOG_ERRNO, "BACKGROUND: fork(2) failed&quo= t;);
exit(1);
}

- if (p2 !=3D 0= ) /* new parent: exit right away */
+ if (p2 !=3D 0) /* new parent= : exit right away */
{
exit(0= );
}
@@ -347,7 +341,7 @@
*/

/* do mighty complicated= work that will really take time here... */
- useconds_t wait_time =3D (useconds_t)context->= test_deferred_auth*1000;
+ useconds_t wait_time =3D (useconds_t)context->test_deferred_aut= h * 1000;
plog(context, PLOG_NOTE, "in async/defe= rred handler, usleep(%u)", wait_time);
usleep(wai= t_time);

@@ -355,8 +349,7 @@
int fd =3D open(auth_control_file, O_WRONLY);
= if (fd < 0)
{
- plog(context, PLOG_ERR|PLOG_ERRNO,
- "open('%s')= failed", auth_control_file);
+ plog(context, PLOG_ERR | PLOG_ERRNO, "open('= ;%s') failed", auth_control_file);
exit(1= );
}

@@ -368,7 +361,= 7 @@

if (write(fd, result, 1) !=3D 1= )
{
+ plog(context, PLOG_ERR | PLOG_ERRNO, "write to &= #39;%s' failed", auth_control_file);
}=
close(fd);

@@ -377,19 +370= ,20 @@


OPENVPN_EXPORT = int
-openvpn_plugin_fun= c_v3(const int v3structver,
- struct openvpn_plugin_args_func_in const *args= ,
+openvpn_plugin_fun= c_v3(const int v3structver, struct openvpn_plugin_args_func_in const *args,=
struct openvpn_plugin_args_func_re= turn *ret)
{
if (v3structver < OPE= NVPN_PLUGIN_STRUCTVER_MIN)
{
- fprintf(stderr, "%s: this plugin i= s incompatible with the running version of OpenVPN\n", MODULE);=
+ fprintf(stderr, &q= uot;%s: this plugin is incompatible with the running version of OpenVPN\n&q= uot;,
+ = MODULE);
return OPENVPN_PLUGIN_FUNC_ERROR;

}
const char **argv =3D args->argv;=
const char **envp =3D args->envp;
- struct plugin_context *context =3D= (struct plugin_context *) args->handle;
- struct plugin_per_client_context *pcc =3D (struct= plugin_per_client_context *) args->per_client_context;
+ struct plugin_context *context = =3D (struct plugin_context *)args->handle;
+ struct plugin_per_client_context *pcc =3D

+ (struct plugin_= per_client_context *)args->per_client_context;
swit= ch (args->type)
{
case OPE= NVPN_PLUGIN_AUTH_USER_PASS_VERIFY:
@@ -405,7 +399,7 @@
OPENVPN_EXPORT void *
openvpn_plugin_client_c= onstructor_v1(openvpn_plugin_handle_t handle)
{
= - struct plugin_context *conte= xt =3D (struct plugin_context *) handle;
+ struct plugin_context *context =3D (struct plugin_= context *)handle;
plog(context, PLOG_NOTE, "FUNC:= openvpn_plugin_client_constructor_v1");
return c= alloc(1, sizeof(struct plugin_per_client_context));
}
@@ -413,7 +407,7 @@
OPENVPN_EXPORT void=
openvpn_plugin_client_destructor_v1(openvpn_plugin_handle_t hand= le, void *per_client_context)
{
- struct plugin_context *context =3D (struct p= lugin_context *) handle;
+ struct plugin_context *context =3D (struct plugin_context *)handle= ;
plog(context, PLOG_NOTE, "FUNC: openvpn_plugin_= client_destructor_v1");
free(per_client_context);=
}
@@ -421,7 +415,7 @@
OP= ENVPN_EXPORT void
openvpn_plugin_close_v1(openvpn_plugin_h= andle_t handle)
{
- struct plugin_context *context =3D (struct plugin_context = *) handle;
+ struc= t plugin_context *context =3D (struct plugin_context *)handle;
plog(context, PLOG_NOTE, "FUNC: openvpn_plugin_close_v1"= );

free(context);
}
d= iff --git a/sample/sample-plugins/keying-material-exporter-demo/keyingmater= ialexporter.c b/sample/sample-plugins/keying-material-exporter-demo/keyingm= aterialexporter.c
index b73144f..e7556a1 100644
<= span>--- a/sample/sample-plugins/keying-material-exporter-demo/keyingmateri= alexporter.c

+++ b/sample/sample-plugins/keying-material-ex= porter-demo/keyingmaterialexporter.c
@@ -37,22 +37,25 @@

#define MAXPATH 1024
#endif

-#define ovpn_err(fm= t, ...) \
- plugin-&= gt;log(PLOG_ERR, "SSO", fmt, ## __VA_ARGS__)
-#define ovpn_dbg(fmt, ...) \
<= span style=3D"color: hsl(0, 100%, 40%);">- plugin->log(PLOG_DEBUG, &q= uot;SSO", fmt, ## __VA_ARGS__)
-#define ovpn_note(fmt, ...) \
- plugin->log(PLOG_NOTE, "SSO", fmt, = ## __VA_ARGS__)
+#def= ine ovpn_err(fmt, ...) plugin->log(PLOG_ERR, "SSO", fmt, ##__= VA_ARGS__)
+#define o= vpn_dbg(fmt, ...) plugin->log(PLOG_DEBUG, "SSO", fmt, ##__VA_= ARGS__)
+#define ovpn= _note(fmt, ...) plugin->log(PLOG_NOTE, "SSO", fmt, ##__VA_ARGS= __)

-= enum endpoint { CLIENT =3D 1, SERVER =3D 2 };
+enum endpoint
+{
+ CLIENT =3D 1,
+= SERVER =3D 2
+};<= /span>

-stru= ct plugin {
+struct p= lugin
+{
plugin_log_t log;

enum endpoint type;<= br> int mask;
};

-struct session {
+struct session
+{
char user[48];

char key[48];
};
@@ -85,= 8 +88,7 @@
}

OPENVPN_EX= PORT int
-openvpn_plugi= n_open_v3(const int version,
- struct openvpn_plugin_args_open_in const *arg= s,
+openvpn_plugin_op= en_v3(const int version, struct openvpn_plugin_args_open_in const *args,

struct openvpn_plugin_args_open_retur= n *rv)
{
struct plugin *plugin =3D ca= lloc(1, sizeof(*plugin));
@@ -98,9 +100,9 @@
}

plugin->type =3D get_env= ("remote_1", args->envp) ? CLIENT : SERVER;
- plugin->log =3D args->callbac= ks->plugin_log;
+ = plugin->log =3D args->callbacks->plugin_log;
<= /span>
- plugin->mask = =3D OPENVPN_PLUGIN_MASK(OPENVPN_PLUGIN_TLS_FINAL);
+ plugin->mask =3D OPENVPN_PLUGIN_MASK(= OPENVPN_PLUGIN_TLS_FINAL);
plugin->mask |=3D OPENVP= N_PLUGIN_MASK(OPENVPN_PLUGIN_TLS_VERIFY);

ovpn_note("vpn endpoint type=3D%s", plugin->type =3D=3D = CLIENT ? "client" : "server");

@@ -163,= 8 +165,8 @@
static int
tls_verify(struct = openvpn_plugin_args_func_in const *args)
{
- struct plugin *plugin =3D (struct= plugin *)args->handle;
- struct session *sess =3D (struct session *)args->per_client_c= ontext;
+ struct p= lugin *plugin =3D (struct plugin *)args->handle;
+ struct session *sess =3D (struct sess= ion *)args->per_client_context;

/= * we store cert subject for the server end point only */
= if (plugin->type !=3D SERVER)
@@ -199,8 +201,8 @@
static void
server_store(struct openvpn_plug= in_args_func_in const *args)
{
- struct plugin *plugin =3D (struct plugin *)a= rgs->handle;
- st= ruct session *sess =3D (struct session *)args->per_client_context;

+ struct plugin *plugi= n =3D (struct plugin *)args->handle;
+ struct session *sess =3D (struct session *)args->= ;per_client_context;

char file[MAXPA= TH];
snprintf(file, sizeof(file) - 1, "/tmp/openv= pn_sso_%s", sess->key);
@@ -211,8 +213,8 @@<= br> static void
client_store(struct openvpn_plugin_a= rgs_func_in const *args)
{
- struct plugin *plugin =3D (struct plugin *)args-= >handle;
- struct= session *sess =3D (struct session *)args->per_client_context;+ struct plugin *plugin = =3D (struct plugin *)args->handle;
+ struct session *sess =3D (struct session *)args->p= er_client_context;

char *file =3D &q= uot;/tmp/openvpn_sso_user";
ovpn_note("app s= ession file: %s", file);
@@ -223,8 +225,8 @@ tls_final(struct openvpn_plugin_args_func_in const *args, struct openvpn_plugin_args_func_return *rv)
{
- struct plugi= n *plugin =3D (struct plugin *)args->handle;
- struct session *sess =3D (struct session *)= args->per_client_context;
+ struct plugin *plugin =3D (struct plugin *)args->handle;
+ struct session *se= ss =3D (struct session *)args->per_client_context;

const char *key;
if (!(key =3D get_e= nv("exported_keying_material", args->envp)))
@= @ -251,8 +253,7 @@
}

OP= ENVPN_EXPORT int
-openv= pn_plugin_func_v3(const int version,
- struct openvpn_plugin_args_func_in co= nst *args,
+openvpn_p= lugin_func_v3(const int version, struct openvpn_plugin_args_func_in const *= args,
struct openvpn_plugin_args_fu= nc_return *rv)
{
switch (args->typ= e)
@@ -270,7 +271,7 @@
openvpn_plugin_clie= nt_constructor_v1(openvpn_plugin_handle_t handle)
{=
struct plugin *plugin =3D (struct plugin *)handle;- struct session *sess =3D c= alloc(1, sizeof(*sess));
+ struct session *sess =3D calloc(1, sizeof(*sess));

ovpn_note("app session created");<= br>
@@ -281,7 +282,7 @@
openvpn_plu= gin_client_destructor_v1(openvpn_plugin_handle_t handle, void *ctx)<= br> {
struct plugin *plugin =3D (struct plugin *= )handle;
- struct se= ssion *sess =3D (struct session *)ctx;
+ struct session *sess =3D (struct session *)ctx;

ovpn_note("app session key: %s&quo= t;, sess->key);
ovpn_note("app session destroy= ed");
diff --git a/sample/sample-plugins/log/log.c b/s= ample/sample-plugins/log/log.c
index 63d714f..70fa60d 10064= 4
--- a/sample/sample-plugins/log/log.c
+++= b/sample/sample-plugins/log/log.c
@@ -36,7 +36,8 @@=
/*
* Our context, where we keep our state.
*/
-stru= ct plugin_context {
+= struct plugin_context
+{
const char *username;
const c= har *password;
};
@@ -75,7 +76,7 @@=
/*
* Allocate our context
*/

- conte= xt =3D (struct plugin_context *) calloc(1, sizeof(struct plugin_context));<= /span>
+ context =3D (str= uct plugin_context *)calloc(1, sizeof(struct plugin_context));
if (context =3D=3D NULL)

{
= printf("PLUGIN: allocating memory for context failed\n");<= /span>
@@ -91,19 +92,17 @@
/*
* Which callbacks to intercept.

*/
<= span style=3D"color: hsl(0, 100%, 40%);">- *type_mask =3D

- OPENVPN_PLUGIN_MASK(OPENVPN_= PLUGIN_UP)
- |OP= ENVPN_PLUGIN_MASK(OPENVPN_PLUGIN_DOWN)
- |OPENVPN_PLUGIN_MASK(OPENVPN_PLUGIN_ROUTE_UP)

- |OPENVPN_PLUGIN_MA= SK(OPENVPN_PLUGIN_IPCHANGE)
- |OPENVPN_PLUGIN_MASK(OPENVPN_PLUGIN_TLS_VERIFY)
- |OPENVPN_PLUGIN_MASK(OPENVP= N_PLUGIN_AUTH_USER_PASS_VERIFY)
- |OPENVPN_PLUGIN_MASK(OPENVPN_PLUGIN_CLIENT_CONNECT_V2)
- |OPENVPN_PLUGIN_= MASK(OPENVPN_PLUGIN_CLIENT_DISCONNECT)
- |OPENVPN_PLUGIN_MASK(OPENVPN_PLUGIN_LEARN_ADDRESS)=
- |OPENVPN_PLUG= IN_MASK(OPENVPN_PLUGIN_TLS_FINAL);
+ *type_mask =3D OPENVPN_PLUGIN_MASK(OPENVPN_PLUGIN_UP) | = OPENVPN_PLUGIN_MASK(OPENVPN_PLUGIN_DOWN)
+ | OPENVPN_PLUGIN_MASK(OPENVPN_PLUGIN_= ROUTE_UP)
+ = | OPENVPN_PLUGIN_MASK(OPENVPN_PLUGIN_IPCHANGE)
+ | OPENVPN_PLUGIN_MASK(OP= ENVPN_PLUGIN_TLS_VERIFY)
+ | OPENVPN_PLUGIN_MASK(OPENVPN_PLUGIN_AUTH_USER_PASS_V= ERIFY)
+ = | OPENVPN_PLUGIN_MASK(OPENVPN_PLUGIN_CLIENT_CONNECT_V2)
+ | OPENVPN_PLUGIN_M= ASK(OPENVPN_PLUGIN_CLIENT_DISCONNECT)

+ | OPENVPN_PLUGIN_MASK(OPENVPN_PLUGIN_LEA= RN_ADDRESS)
+ = | OPENVPN_PLUGIN_MASK(OPENVPN_PLUGIN_TLS_FINAL);
=
- return (openvpn_p= lugin_handle_t) context;
+ return (openvpn_plugin_handle_t)context;
}=

void
@@ -171,9 +170,10 @@
}

OPENVPN_EXPORT int=
-openvpn_plugin_func_v1(openv= pn_plugin_handle_t handle, const int type, const char *argv[], const char *= envp[])
+openvpn_plug= in_func_v1(openvpn_plugin_handle_t handle, const int type, const char *argv= [],
+ = const char *envp[])
{
- struct plugin_context *context =3D (struct plug= in_context *) handle;
+ struct plugin_context *context =3D (struct plugin_context *)handle;

show(type, argv, envp);

@@ -184,8 +184,8 @@
const cha= r *username =3D get_env("username", envp);
= const char *password =3D get_env("password", envp);
=
- if (us= ername && !strcmp(username, context->username)
- && password &&a= mp; !strcmp(password, context->password))
+ if (username && !strcmp(username, = context->username) && password
+ && !strcmp(password, context->= password))
{
return O= PENVPN_PLUGIN_FUNC_SUCCESS;
}
@@ -= 203,6 +203,6 @@
OPENVPN_EXPORT void
openv= pn_plugin_close_v1(openvpn_plugin_handle_t handle)
{

- struct plugin_context *= context =3D (struct plugin_context *) handle;
+ struct plugin_context *context =3D (struct pl= ugin_context *)handle;
free(context);
= }
diff --git a/sample/sample-plugins/log/log_v3.c b/sample= /sample-plugins/log/log_v3.c
index 02cdda8..cef22cf 100644<= /span>
--- a/sample/sample-plugins/log/log_v3.c
++= + b/sample/sample-plugins/log/log_v3.c
@@ -39,7 +39,8 @@
/*
* Our context, where we keep our state.=
*/
-= struct plugin_context {
+struct plugin_context
+{
const char *username;
con= st char *password;
};
@@ -71,8 +72,7 @@
}

OPENVPN_EXPORT int
-openvpn_plugin_open_v3(con= st int v3structver,
- = struct openvpn_plugin_args_open_in const *args,=
+openvpn_plugin_open_v3(con= st int v3structver, struct openvpn_plugin_args_open_in const *args,<= br> struct openvpn_plugin_args_open_return *re= t)
{
struct plugin_context *context = =3D NULL;
@@ -80,7 +80,8 @@
/* Check t= hat we are API compatible */
if (v3structver !=3D OPEN= VPN_PLUGINv3_STRUCTVER)
{
- printf("log_v3: ** ERROR ** Incompati= ble plug-in interface between this plug-in and OpenVPN\n");
= + printf(
+ "log_v3: ** ERROR= ** Incompatible plug-in interface between this plug-in and OpenVPN\n"= );

return OPENVPN_PLUGIN_FUNC_ERROR;
}


@@ -91,26 +92,24 @@
<= span> }


/* Print some version in= formation about the OpenVPN process using this plug-in */
- printf("log_v3: OpenVPN %s (M= ajor: %i, Minor: %i, Patch: %s)\n",
- args->ovpn_version, args->ovpn_version_= major,
- args= ->ovpn_version_minor, args->ovpn_version_patch);
+ printf("log_v3: OpenVPN %s (Ma= jor: %i, Minor: %i, Patch: %s)\n", args->ovpn_version,
+ args->ovpn_version= _major, args->ovpn_version_minor, args->ovpn_version_patch);

/* Which callbacks to intercept. */=
- ret->type_mask =3D
- OPENVPN_PLUGIN_M= ASK(OPENVPN_PLUGIN_UP)
= - |OPENVPN_PLUGIN_MASK(OPENVPN_PLUGIN_DOWN)
- |OPENVPN_PLUGIN_MASK(OPENVPN_PLUGIN_RO= UTE_UP)
- |OPENV= PN_PLUGIN_MASK(OPENVPN_PLUGIN_IPCHANGE)
- |OPENVPN_PLUGIN_MASK(OPENVPN_PLUGIN_TLS_VERIFY)
- |OPENVPN_PLUGIN= _MASK(OPENVPN_PLUGIN_AUTH_USER_PASS_VERIFY)
- |OPENVPN_PLUGIN_MASK(OPENVPN_PLUGIN_CLIENT_CO= NNECT_V2)
- |OPE= NVPN_PLUGIN_MASK(OPENVPN_PLUGIN_CLIENT_DISCONNECT)
- |OPENVPN_PLUGIN_MASK(OPENVPN_PLUGIN_LE= ARN_ADDRESS)
- |= OPENVPN_PLUGIN_MASK(OPENVPN_PLUGIN_TLS_FINAL);
+ ret->type_mask =3D OPENVPN_PLUGIN_MASK(OP= ENVPN_PLUGIN_UP)
+ = | OPENVPN_PLUGIN_MASK(OPENVPN_PLUGIN_DOWN)
+ | OPENVPN_PLU= GIN_MASK(OPENVPN_PLUGIN_ROUTE_UP)

+ | OPENVPN_PLUGIN_MASK(OPENVPN_PLUGIN_IPC= HANGE)
+ = | OPENVPN_PLUGIN_MASK(OPENVPN_PLUGIN_TLS_VERIFY)
+ | OPENVPN_PLUGIN_= MASK(OPENVPN_PLUGIN_AUTH_USER_PASS_VERIFY)
+ | OPENVPN_PLUGIN_MASK(OPENVPN_P= LUGIN_CLIENT_CONNECT_V2)
+ | OPENVPN_PLUGIN_MASK(OPENVPN_PLUGIN_CLIENT_DISCO= NNECT)
+ = | OPENVPN_PLUGIN_MASK(OPENVPN_PLUGIN_LEARN_ADDRESS)
+ | OPENVPN_PLUG= IN_MASK(OPENVPN_PLUGIN_TLS_FINAL);



/* Allocate our context */
- context =3D (struct plugin_context *) calloc(1, s= izeof(struct plugin_context));
+ context =3D (struct plugin_context *)calloc(1, sizeof(struct= plugin_context));
if (context =3D=3D NULL)
= {
printf("PLUGIN: allocating memor= y for context failed\n");
@@ -122,7 +121,7 @@ context->password =3D "bar";

/* Point the global context handle to our newly created = context */
- ret->= ;handle =3D (void *) context;
+ ret->handle =3D (void *)context;
<= br> return OPENVPN_PLUGIN_FUNC_SUCCESS;
}=
@@ -243,13 +242,11 @@
}
=

- OPENVPN_EXPORT int
-openvpn_plugin_func_v3(const int version,
- struct openvpn_plugin_args_= func_in const *args,
= +openvpn_plugin_func_v3(const int version, struct openvpn_plugin_args_func_= in const *args,
struct openvpn_plug= in_args_func_return *retptr)
{
- struct plugin_context *context =3D (struct pl= ugin_context *) args->handle;
+ struct plugin_context *context =3D (struct plugin_context = *)args->handle;

printf("\nop= envpn_plugin_func_v3() :::::>> ");
show(arg= s->type, args->argv, args->envp);
@@ -270,8 +267,8= @@
const char *username =3D get_env("usernam= e", args->envp);
const char *password =3D = get_env("password", args->envp);

<= span style=3D"color: hsl(0, 100%, 40%);">- if (username && != strcmp(username, context->username)

- && password && !strcmp(passwor= d, context->password))
+ if (username && !strcmp(username, context->usernam= e) && password
- struct plugin_context *context =3D (struct= plugin_context *) handle;
+ struct plugin_context *context =3D (struct plugin_context *)hand= le;
free(context);
}
= diff --git a/sample/sample-plugins/simple/base64.c b/sample/sample-plugins/= simple/base64.c
index b6c0c97..8a1dedd 100644
--- a/sample/sample-plugins/simple/base64.c

+++ b/sample= /sample-plugins/simple/base64.c
@@ -98,21 +98,20 @@<= br> *
*/
OPENVPN_EXPORT int
-openvpn_plugin_open_v3(cons= t int v3structver,
- = struct openvpn_plugin_args_open_in const *args,<= br>+openvpn_plugin_open_v3(cons= t int v3structver, struct openvpn_plugin_args_open_in const *args, struct openvpn_plugin_args_open_return *ret= )
{
/* Check that we are API compatib= le */
if (v3structver !=3D OPENVPN_PLUGINv3_STRUCTVER)=
{
- printf("base64.c: ** ERROR ** Incompatible plug-in interface= between this plug-in and OpenVPN\n");
+ printf(
+ "base64.c: ** ERROR ** Incompatible pl= ug-in interface between this plug-in and OpenVPN\n");
= return OPENVPN_PLUGIN_FUNC_ERROR;
}
/* Which callbacks to intercept. */<= br>- ret->type_mask =3D
- OPENVPN_PLUGIN_MA= SK(OPENVPN_PLUGIN_TLS_VERIFY)
- |OPENVPN_PLUGIN_MASK(OPENVPN_PLUGIN_CLIENT_CONNECT_V2);
+ ret->type_mask = =3D OPENVPN_PLUGIN_MASK(OPENVPN_PLUGIN_TLS_VERIFY)
+ | OPENVPN_PLUGIN_MASK(O= PENVPN_PLUGIN_CLIENT_CONNECT_V2);

/*= we don't need a plug-in context in this example, but OpenVPN expects &= quot;something" */
ret->handle =3D calloc(1, 1= );
@@ -125,8 +124,8 @@

= /* Print some version information about the OpenVPN process using this p= lug-in */
ovpn_log(PLOG_NOTE, PLUGIN_NAME, "OpenV= PN %s (Major: %i, Minor: %i, Patch: %s)\n",
- args->ovpn_version, args->ov= pn_version_major,
- = args->ovpn_version_minor, args->ovpn_version_patch);<= br>+ args->ovpn_= version, args->ovpn_version_major, args->ovpn_version_minor,+ args->ovpn_v= ersion_patch);

return OPENVPN_PLUGIN= _FUNC_SUCCESS;
}
@@ -154,10 +153,10 @@
*/

OPENVPN_EXPORT int
-openvpn_plugin_func_v1(op= envpn_plugin_handle_t handle, const int type, const char *argv[], const cha= r *envp[])
+openvpn_p= lugin_func_v1(openvpn_plugin_handle_t handle, const int type, const char *a= rgv[],
+ = const char *envp[])
{
- if (type !=3D OPENVPN_PLUGIN_TLS_VERIFY
- && type != =3D OPENVPN_PLUGIN_CLIENT_CONNECT_V2)
+ if (type !=3D OPENVPN_PLUGIN_TLS_VERIFY && ty= pe !=3D OPENVPN_PLUGIN_CLIENT_CONNECT_V2)
{
= ovpn_log(PLOG_ERR, PLUGIN_NAME, "Unsupported plug-in ho= ok call attempted");
return OPENVPN_PLUGIN_FU= NC_ERROR;
@@ -174,14 +173,13 @@
/* tes= t the BASE64 encode function */
char *buf =3D NULL;
int r =3D ovpn_base64_encode(clcert_cn, (int)strlen(clce= rt_cn), &buf);
- = ovpn_log(PLOG_NOTE, PLUGIN_NAME, "BASE64 encoded '%s' (return= value %i): '%s'",
- clcert_cn, r, buf);
+ ovpn_log(PLOG_NOTE, PLUGIN_NAME, "BASE64 e= ncoded '%s' (return value %i): '%s'", clcert_cn, r,
+ buf);

/* test the BASE64 decode function */<= /span>
- char buf2[256] =3D= {0};
+ char buf2[= 256] =3D { 0 };
r =3D ovpn_base64_decode(buf, &buf= 2, 255);
- ovpn_log(= PLOG_NOTE, PLUGIN_NAME, "BASE64 decoded '%s' (return value %i)= : '%s'",
= - buf, r, buf2);
+ ovpn_log(PLOG_NOTE, PLUGIN_NAME, "BASE64 decoded '%s&= #39; (return value %i): '%s'", buf, r, buf2);

/* Verify the result, and free the buffer allocated= by ovpn_base64_encode() */
r =3D strcmp(clcert_cn, bu= f2);
@@ -201,6 +199,6 @@
OPENVPN_EXPORT vo= id
openvpn_plugin_close_v1(openvpn_plugin_handle_t handle)=
{
- = struct plugin_context *context =3D (struct plugin_context *) handle;
+ struct plugin_contex= t *context =3D (struct plugin_context *)handle;
free(c= ontext);
}
diff --git a/sample/sample-plug= ins/simple/simple.c b/sample/sample-plugins/simple/simple.c
index ed5bce5..8b2b793 100644

--- a/sample/sample-plugins/= simple/simple.c
+++ b/sample/sample-plugins/simple/simple.c=
@@ -38,7 +38,8 @@
/*
* = Our context, where we keep our state.
*/
-struct plugin_context {
+struct plugin_context

+{

const cha= r *username;
const char *password;
};=
@@ -77,7 +78,7 @@
/*
= * Allocate our context
*/
- context =3D (struct plugin_context *) c= alloc(1, sizeof(struct plugin_context));
+ context =3D (struct plugin_context *)calloc(1, siz= eof(struct plugin_context));
if (context =3D=3D NULL)<= /span>
{
printf("PLUGIN: alloca= ting memory for context failed\n");
@@ -96,21 +97,22 @= @
*/
*type_mask =3D OPENVPN_PLUG= IN_MASK(OPENVPN_PLUGIN_AUTH_USER_PASS_VERIFY);

= - return (openvpn_plugin_handl= e_t) context;
+ re= turn (openvpn_plugin_handle_t)context;
}
=
OPENVPN_EXPORT int
-openvpn_plugin_func_v1(openvpn_plugin_handle_t handle, const= int type, const char *argv[], const char *envp[])
+openvpn_plugin_func_v1(openvpn_plugin_handle= _t handle, const int type, const char *argv[],
+ const char *envp[])
{
- stru= ct plugin_context *context =3D (struct plugin_context *) handle;
= + struct plugin_context *con= text =3D (struct plugin_context *)handle;

/* get username/password from envp string array */

= const char *username =3D get_env("username", envp);
= const char *password =3D get_env("password", envp);

/* check entered username/password aga= inst what we require */
- if (username && !strcmp(username, context->username)
- && password= && !strcmp(password, context->password))
+ if (username && !strcmp(usern= ame, context->username) && password
+ && !strcmp(password, context->= ;password))
{
return OPENVPN_= PLUGIN_FUNC_SUCCESS;
}
@@ -123,6 +125,= 6 @@
OPENVPN_EXPORT void
openvpn_plugin_c= lose_v1(openvpn_plugin_handle_t handle)
{
- struct plugin_context *context =3D= (struct plugin_context *) handle;
+ struct plugin_context *context =3D (struct plugin_contex= t *)handle;
free(context);
}diff --git a/src/compat/compat-basename.c b/src/compat/compat-basen= ame.c
index 18944f6..24f5af7 100644
--- a/s= rc/compat/compat-basename.c
+++ b/src/compat/compat-basenam= e.c
@@ -41,7 +41,7 @@
/* If NULL, = check for \ instead ... might be Windows a path */
= p =3D strrchr(filename, '\\');
}
- return p ? p + 1 : (char *) fi= lename;

+ return p= ? p + 1 : (char *)filename;
}
#endif /* HAVE_BASENAME */
diff --git a/src/compat/= compat-dirname.c b/src/compat/compat-dirname.c
index 17de8a= d..a432bae 100644
--- a/src/compat/compat-dirname.c<= br>+++ b/src/compat/compat-dirname.c
@@ -89,7 +89,7 @= @
/* The '/' is the last character, we hav= e to look further. */
if (runp !=3D path)<= br> {
- = last_slash =3D (char *) __memrchr(path, separator, runp - path);<= /span>
+ last_sla= sh =3D (char *)__memrchr(path, separator, runp - path);
= }
}

@@ -134,7 = +134,7 @@
/* This assignment is ill-designed but t= he XPG specs require to
* return a string contain= ing "." in any case no directory part is
= * found and so a static and constant string is required. */
- path =3D (char *) dot;
+ path =3D (char = *)dot;
}

return= path;
diff --git a/src/compat/compat-gettimeofday.c b/src/= compat/compat-gettimeofday.c
index de53cb5..29ded6c 100644<= /span>
--- a/src/compat/compat-gettimeofday.c
+++ = b/src/compat/compat-gettimeofday.c
@@ -48,7 +48,7 @@=
{
const time_t t =3D time(NULL);
= const DWORD gtc =3D GetTickCount();
- gtc_base =3D t - gtc/1000;
+ gtc_base =3D t - gtc / 1000;=
gtc_last =3D gtc;
}

@@ -112,7 +112,7 @@
return 0;
}


-#else /* ifdef _WIN32 */
+#else /* ifdef _WIN32 */

#includ= e <time.h>

diff --git a/src/openvpn= /argv.c b/src/openvpn/argv.c
index 34266d4..903fc0a 100644<= /span>
--- a/src/openvpn/argv.c
+++ b/src/openvpn/= argv.c
@@ -284,8 +284,7 @@
* fr= ee()d to avoid memory leaks.
*/
static c= har *
-argv_prep_format= (const char *format, const char delim, size_t *count,
- struct gc_arena *gc)
+argv_prep_format(const ch= ar *format, const char delim, size_t *count, struct gc_arena *gc) {
if (format =3D=3D NULL)
= {
@@ -311,7 +310,7 @@
* the = string is empty; the resulting format string
= * will never start with a delimiter.
*/
- if (j > 0) = /* Has anything been written to the output string? */
+ if (j > 0) /* Has anything= been written to the output string? */
{
f[j++] =3D delim;
= }
@@ -347,7 +346,7 @@
static bool argv_printf_arglist(struct argv *argres, const char *format, va_li= st arglist)
{
- const char delim =3D 0x1D; /* ASCII Group Separator (GS) */
+ const char delim = =3D 0x1D; /* ASCII Group Separator (GS) */
bool res = =3D false;

/*
@@ -48= 4,8 +483,8 @@
argv_reset(argres);

char *parms[MAX_PARMS + 1] =3D { 0 };
- int nparms =3D parse_line(cmdstr, pa= rms, MAX_PARMS, "SCRIPT-ARGV", 0,
- D_ARGV_PARSE_CMD, &ar= gres->gc);
+ in= t nparms =3D
+ = parse_line(cmdstr, parms, MAX_PARMS, "SCRIPT-ARGV", 0, D_ARGV_PA= RSE_CMD, &argres->gc);
if (nparms)
{

int i;
diff --git a/src= /openvpn/argv.h b/src/openvpn/argv.h
index f694760..056fe31= 100644
--- a/src/openvpn/argv.h
+++ b/src/= openvpn/argv.h
@@ -31,7 +31,8 @@
#include "buffer.h"

-struct argv {
+struct argv
+{
struct gc_arena gc;
<= span> size_t capacity;

size_t argc;
@@ -55,21 +56,21 @@

bool argv_printf(struct argv *a, con= st char *format, ...)
#ifdef __GNUC__
#if= __USE_MINGW_ANSI_STDIO
-__attribute__ ((format(gnu_printf, 2, 3)))
+ __attribute__((format(gnu_printf, 2, 3)))
#else
-__a= ttribute__ ((format(__printf__, 2, 3)))
+ __attribute__((format(__printf__, 2, 3))) #endif
#endif
-;
+ = ;

bool argv_printf_cat(struct argv *a= , const char *format, ...)
#ifdef __GNUC__
#if __USE_MINGW_ANSI_STDIO

-__attribute__ ((format(gnu_printf, 2, 3)))
+ __attribute__((format(gnu_printf, 2, 3)))=
#else
-__attribute__ ((format(__printf__, 2, 3)))
+ __attribute__((format(__printf__, 2, 3)))
#endif
#endif
-;
+ ;

#endif /* ifndef ARGV_H */
diff --git a/src/openvpn/auth_token.c b/src/openvpn/auth_token= .c
index 3cf55e8..a694e81 100644
--- a/src/= openvpn/auth_token.c
+++ b/src/openvpn/auth_token.c<= br>@@ -18,7 +18,7 @@

const char *a= uth_token_pem_name =3D "OpenVPN auth-token server key";
-#define AUTH_= TOKEN_SESSION_ID_LEN 12
+#define AUTH_TOKEN_SESSION_ID_LEN 12
#define AU= TH_TOKEN_SESSION_ID_BASE64_LEN (AUTH_TOKEN_SESSION_ID_LEN * 8 / 6)
#if AUTH_TOKEN_SESSION_ID_LEN % 3
@@ -53,7 +53,7 @@

}
else if (au= th_token_state_flags & AUTH_TOKEN_HMAC_OK)
{
- switch (auth_token_= state_flags & (AUTH_TOKEN_VALID_EMPTYUSER|AUTH_TOKEN_EXPIRED))+ switch (auth_token_s= tate_flags & (AUTH_TOKEN_VALID_EMPTYUSER | AUTH_TOKEN_EXPIRED))<= br> {
case 0:
= state =3D "Authenticated";
@@ -107= ,9 +107,9 @@
* in the encoding
= */

- = char session_id[AUTH_TOKEN_SESSION_ID_LEN*2] =3D {0};
+ char session_id[AUTH_TOKEN_SESSION= _ID_LEN * 2] =3D { 0 };
memcpy(session_id, session_id_= source + strlen(SESSION_ID_PREFIX),
- AUTH_TOKEN_SESSION_ID_LEN*8/6);
+ AUTH_TOKEN_SESSION_ID_LEN *= 8 / 6);

setenv_str(session->opt-= >es, "session_id", session_id);
}
<= span>@@ -121,8 +121,7 @@

}

void

-auth_token_in= it_secret(struct key_ctx *key_ctx, const char *key_file,
- bool key_inline)<= /span>
+auth_token_init_secr= et(struct key_ctx *key_ctx, const char *key_file, bool key_inline) {
struct key_type kt =3D auth_token_kt();

@@ -131,14 +130,12 @@
b= ool key_loaded =3D false;
if (key_file)
{

- key_l= oaded =3D read_pem_key_file(&server_secret_key,
- auth= _token_pem_name,
- = key_file, key_inline);
+ key_loaded =3D
+ read_pem_key_file(&= server_secret_key, auth_token_pem_name, key_file, key_inline);

}

else
{
- key_loaded =3D generate_ephem= eral_key(&server_secret_key,

- auth_token_pem_name)= ;
+ key_loaded= =3D generate_ephemeral_key(&server_secret_key, auth_token_pem_name);
}

if (!key_loade= d)
@@ -169,7 +166,7 @@
int64_t initial= _timestamp =3D timestamp;

hmac_ctx_t= *ctx =3D multi->opt.auth_token_key.hmac;
- ASSERT(hmac_ctx_size(ctx) =3D=3D 256/8);<= br>+ ASSERT(hmac_ctx_size(ct= x) =3D=3D 256 / 8);

uint8_t sessid[A= UTH_TOKEN_SESSION_ID_LEN];

@@ -185,7 +182= ,7 @@
char *initial_token_copy =3D string_alloc(mu= lti->auth_token_initial, &gc);

= char *old_sessid =3D initial_token_copy + strlen(SESSION_ID_PREFIX);<= /span>
- char *old_tsta= mp_initial =3D old_sessid + AUTH_TOKEN_SESSION_ID_LEN*8/6;
+ char *old_tstamp_initial =3D= old_sessid + AUTH_TOKEN_SESSION_ID_LEN * 8 / 6;
/*
* We null terminate the old t= oken just after the session ID to let
@@ -197,12 +194,13 @@=
memcpy(&initial_timestamp, &old_tstamp_de= code, sizeof(initial_timestamp));

= old_tstamp_initial[0] =3D '\0';
- ASSERT(openvpn_base64_decode(old_sessid, sessid= , AUTH_TOKEN_SESSION_ID_LEN) =3D=3D AUTH_TOKEN_SESSION_ID_LEN);
<= span style=3D"color: hsl(120, 100%, 40%);">+ ASSERT(openvpn_base64_d= ecode(old_sessid, sessid, AUTH_TOKEN_SESSION_ID_LEN)

+ =3D=3D AUTH_TOKEN_SESSION_= ID_LEN);
}
else if (!rand_bytes(s= essid, AUTH_TOKEN_SESSION_ID_LEN))
{
- msg( M_FATAL, "Failed to g= et enough randomness for "
- "authentication token");
+ msg(M_FATAL, "Failed to = get enough randomness for "
+ "authentication token");=
}

/* Calculate the HM= AC */
@@ -210,7 +208,7 @@
* with \0 i= n them is asking for troubles in so many ways anyway that we
* ignore that corner case here

*/
<= span style=3D"color: hsl(0, 100%, 40%);">- uint8_t hmac_output[256/8];
+ uint8_t hmac_outp= ut[256 / 8];

hmac_ctx_reset(ctx);

@@ -222,20 +220,20 @@
= struct key_state *ks =3D &multi->session[TM_ACTIVE].key[KS_PRIMARY];=
if (ks->auth_token_state_flags & AUTH_TOKEN_VA= LID_EMPTYUSER)
{
- hmac_ctx_update(ctx, (const uint8_t *) ""= , 0);
+ hmac_c= tx_update(ctx, (const uint8_t *)"", 0);
}
else
{
- hmac_ctx_update(ctx, (uint8_t *) up->us= ername, (int) strlen(up->username));
+ hmac_ctx_update(ctx, (uint8_t *)up->username= , (int)strlen(up->username));
}
= hmac_ctx_update(ctx, sessid, AUTH_TOKEN_SESSION_ID_LEN);
- hmac_ctx_update(ctx, (uint8_t *) &= amp;initial_timestamp, sizeof(initial_timestamp));
- hmac_ctx_update(ctx, (uint8_t *) &time= stamp, sizeof(timestamp));
+ hmac_ctx_update(ctx, (uint8_t *)&initial_timestamp, sizeof(i= nitial_timestamp));
+= hmac_ctx_update(ctx, (uint8_t *)&timestamp, sizeof(timestamp));
hmac_ctx_final(ctx, hmac_output);

/* Construct the unencoded session token */
- struct buffer token =3D alloc_buf= _gc(

- 2*sizeof(= uint64_t) + AUTH_TOKEN_SESSION_ID_LEN + 256/8, &gc);
+ struct buffer token =3D
= + alloc_buf_gc(2 * sizeo= f(uint64_t) + AUTH_TOKEN_SESSION_ID_LEN + 256 / 8, &gc);

ASSERT(buf_write(&token, sessid, sizeof(sessid= )));
ASSERT(buf_write(&token, &initial_timesta= mp, sizeof(initial_timestamp)));
@@ -245,8 +243,8 @@=
char *b64output =3D NULL;
openvpn_base6= 4_encode(BPTR(&token), BLEN(&token), &b64output);

- struct buffer= session_token =3D alloc_buf_gc(
- strlen(SESSION_ID_PREFIX) + strlen(b64output) + 1, &= gc);
+ struct buff= er session_token =3D
= + alloc_buf_gc(strlen(SESSION_ID_PREFIX) + strlen(b64output) + 1, &a= mp;gc);

ASSERT(buf_write(&sessio= n_token, SESSION_ID_PREFIX, strlen(SESSION_ID_PREFIX)));
= ASSERT(buf_write(&session_token, b64output, (int)strlen(b64output)))= ;
@@ -258,8 +256,7 @@
free(multi->a= uth_token);
multi->auth_token =3D strdup((char *)BP= TR(&session_token));

- dmsg(D_SHOW_KEYS, "Generated token for client= : %s (%s)",
- = multi->auth_token, up->username);
+ dmsg(D_SHOW_KEYS, "Generated token for cli= ent: %s (%s)", multi->auth_token, up->username);

if (!multi->auth_token_initial)
= {
@@ -277,22 +274,21 @@
static bool
check_hmac_token(hmac_ctx_t *ctx, const uint8_t *b64decoded= , const char *username)
{
- ASSERT(hmac_ctx_size(ctx) =3D=3D 256/8);+ ASSERT(hmac_ctx_size(ctx)= =3D=3D 256 / 8);

- uint8_t hmac_output[256/8];
+ uint8_t hmac_output[256 / 8];

hmac_ctx_reset(ctx);
- hmac_ctx_update(ctx, (uint8_t *) username, (int)= strlen(username));
- = hmac_ctx_update(ctx, b64decoded, TOKEN_DATA_LEN - 256/8);
+ hmac_ctx_update(ctx, (uint8_t *)= username, (int)strlen(username));
+ hmac_ctx_update(ctx, b64decoded, TOKEN_DATA_LEN - 256 / 8= );
hmac_ctx_final(ctx, hmac_output);
=
- const uint8_t *hm= ac =3D b64decoded + TOKEN_DATA_LEN - 256/8;
+ const uint8_t *hmac =3D b64decoded + TOKEN_DATA= _LEN - 256 / 8;
return memcmp_constant_time(&hmac_= output, hmac, 32) =3D=3D 0;
}

= unsigned int
-ve= rify_auth_token(struct user_pass *up, struct tls_multi *multi,
- struct tls_sessi= on *session)

+verify_= auth_token(struct user_pass *up, struct tls_multi *multi, struct tls_sessio= n *session)
{
/*
= * Base64 is <=3D input and input is < USER_PASS_LEN, so using USER_= PASS_LEN
@@ -300,8 +296,8 @@
*/
ASSERT(up && !up->protected);
= uint8_t b64decoded[USER_PASS_LEN];
- int decoded_len =3D openvpn_base64_decode(up->passwo= rd + strlen(SESSION_ID_PREFIX),
- b64decoded, USER_PASS= _LEN);
+ int decod= ed_len =3D
+ o= penvpn_base64_decode(up->password + strlen(SESSION_ID_PREFIX), b64decode= d, USER_PASS_LEN);

/*
* Ensure that the decoded data is the size of the

@= @ -309,8 +305,7 @@
*/
if (decode= d_len !=3D TOKEN_DATA_LEN)
{
- msg(M_WARN, "ERROR: --auth-token w= rong size (%d!=3D%d)",
- decoded_len, (int) TOKEN_DATA_LEN);
+ msg(M_WARN, "ERROR: --auth-t= oken wrong size (%d!=3D%d)", decoded_len, (int)TOKEN_DATA_LEN);=
return 0;
}

@@ -343,15 +338,14 @@
}
= else
{
- msg(M_WARN, "--auth-gen-token: HMAC on token from clie= nt failed (%s)",
-= up->username);
+ msg(M_WARN, "--auth-gen-token: HMAC on token from cl= ient failed (%s)", up->username);
return 0= ;
}

/* Accept s= ession tokens only if their timestamp is in the acceptable range
= * for renegotiations */
- bool in_renegotiation_time =3D now >=3D timestamp
- = && now < timestamp + 2 * session->opt->auth_token_r= enewal;
+ bool in_= renegotiation_time =3D
- msg(M_WA= RN, "Initial timestamp (%" PRIu64 ") in token from client ea= rlier than "
+ = msg(M_WARN,
+ = "Initial timestamp (%" PRIu64 ") in token from cli= ent earlier than "
"current timestam= p %" PRIu64 ". Broken/unsynchronised clock?",
timestamp_initial, timestamp);

ret = |=3D AUTH_TOKEN_EXPIRED;
}
- if (multi->opt.auth_toke= n_lifetime
- &am= p;& now > timestamp_initial + multi->opt.auth_token_lifetime)
+ if (multi->opt.a= uth_token_lifetime && now > timestamp_initial + multi->opt.au= th_token_lifetime)
{
ret |=3D= AUTH_TOKEN_EXPIRED;
}
@@ -391,7 +385,= 7 @@
strlen(SESSION_ID_PRE= FIX) + AUTH_TOKEN_SESSION_ID_BASE64_LEN))
{
= msg(M_WARN, "--auth-gen-token: session id in token chan= ged (Rejecting "
-= "token.");
+ "token.");
= ret =3D 0;
}
return ret;
@@ -409,8 +403,7 @@
}
= if (multi->auth_token_initial)
{
- secure_memzero(= multi->auth_token_initial,
- strlen(multi->auth_token_initial));
+ secure_me= mzero(multi->auth_token_initial, strlen(multi->auth_token_initial));<= /span>
free(multi->auth_token_initial);
= }
multi->auth_token =3D NULL;
@@ -438,7 +431,7 @@
if (!multi->auth_= token_initial)
{
msg(D_SHOW_K= EYS, "initial auth-token not generated yet, skipping "
= - "auth-token ren= ewal.");
+ = "auth-token renewal.");
= return;
}

diff --= git a/src/openvpn/auth_token.h b/src/openvpn/auth_token.h
i= ndex 3d56ee6..1e4a413 100644
--- a/src/openvpn/auth_token.h=
+++ b/src/openvpn/auth_token.h
@@ -58,27 += 58,22 @@
* This function will free() an existing multi-&g= t;auth_token and keep the
* existing initial timestamp an= d session id contained in that token.
*/
-void
-generate_auth_token(const struct user_pass *up, struct = tls_multi *multi);
+v= oid generate_auth_token(const struct user_pass *up, struct tls_multi *multi= );

/**
* Verifies the = auth token to be in the format that generate_auth_token
*= create and checks if the token is valid.
*
*/

-unsigned
-verify_auth_token(struct us= er_pass *up, struct tls_multi *multi,
- struct tls_session *session);
<= span style=3D"color: hsl(0, 100%, 40%);">-

+unsigned verify_auth_token(struct user_pass *up, str= uct tls_multi *multi,
+ struct tls_session *session);
=

/**
* Loads an HMAC = secret from a file or if no file is present generates a
*= epheremal secret for the run time of the server and stores it into ctx
*/
-void=
-auth_token_init_secre= t(struct key_ctx *key_ctx, const char *key_file,
- bool key_inline);<= br>+void auth_token_init_secret= (struct key_ctx *key_ctx, const char *key_file, bool key_inline);

/**
@@ -125,8 += 120,7 @@
static inline bool
is_auth_token= (const char *password)
{
- return (memcmp_constant_time(SESSION_ID_PREFIX, pas= sword,
- = strlen(SESSION_ID_PREFIX)) =3D=3D 0);
+ return (memcmp_constant_time(SESSIO= N_ID_PREFIX, password, strlen(SESSION_ID_PREFIX)) =3D=3D 0);
}

/**
* Checks if a client should be = sent a new auth token to update its
@@ -134,15 +128,13 @@
* @param multi Pointer the multi object of the TLS ses= sion
* @param session Pointer to the TLS session itself=
*/
-= void
-resend_auth_token= _renegotiation(struct tls_multi *multi, struct tls_session *session);
+void resend_auth_token_re= negotiation(struct tls_multi *multi, struct tls_session *session);

/**
* Checks= if the timer to resend the auth-token has expired and if a new
<= span> * auth-token should be send to the client and triggers the resending=

*/
-= void
-check_send_auth_t= oken(struct context *c);
+void check_send_auth_token(struct context *c);

#endif /* AUTH_TOKEN_H */
diff --git a/src/open= vpn/base64.c b/src/openvpn/base64.c
index a9c2f4c..54d5b79 = 100644
--- a/src/openvpn/base64.c
+++ b/src= /openvpn/base64.c
@@ -41,8 +41,7 @@

#include "memdbg.h"

-static char base64_chars[] =3D
=
- "ABCDEFGHIJKLMNOPQR= STUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
+static char base64_chars[] =3D "ABCD= EFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";<= br> /*
* base64 encode input data of length size to= malloced
* buffer which is returned as *str. Returns st= ring
@@ -60,14 +59,14 @@
{
<= span> return -1;

}
- p =3D s =3D (char *) malloc(size * 4 / 3 + 4)= ;
+ p =3D s =3D (c= har *)malloc(size * 4 / 3 + 4);
if (p =3D=3D NULL)
{
return -1;
= }
- q =3D (const u= nsigned char *) data;
+ q =3D (const unsigned char *)data;
i =3D 0;
- for (i =3D 0; i < s= ize; )
+ for (i = =3D 0; i < size;)
{
c =3D = q[i++];
c *=3D 256;
@@ -196,5 +195= ,5 @@
*q++ =3D val & 0xff;
}

}
- return q - (unsigned char *) data;
+ return q - (unsigned char *)data;
}
diff --git a/src/openvpn/base64.h b/src/ope= nvpn/base64.h
index 7b4224a..be7aa64 100644
--- a/src/openvpn/base64.h

+++ b/src/openvpn/base64.h
@@ -35,12 +35,10 @@
#define _BASE64_H_<= br>
/** Compute resulting base64 length. 6 bits pe= r byte, padded to 4 bytes. */
-#define OPENVPN_BASE64_LENGTH(binary_length) \
- ((((8 * binary_length) / 6) + 3) &= ~3)
+#define OPENVPN= _BASE64_LENGTH(binary_length) ((((8 * binary_length) / 6) + 3) & ~3)

/** Compute the maximal number of bytes en= coded in a base64 string. */
-#define OPENVPN_BASE64_DECODED_LENGTH(base64_length) \
- ((base64_length / 4) * 3)
+#define OPENVPN_BASE64_DE= CODED_LENGTH(base64_length) ((base64_length / 4) * 3)

int openvpn_base64_encode(const void *data, int size, char **= str);

diff --git a/src/openvpn/basic.h b/= src/openvpn/basic.h
index 47a86d9..aae84f5 100644--- a/src/openvpn/basic.h
+++ b/src/openvpn/basic.h<= /span>
@@ -26,7 +26,7 @@
#define BOOL_CAST(x) ((x= ) ? (true) : (false))

/* size of an arra= y */
-#define SIZE(x) (= sizeof(x)/sizeof(x[0]))
+#define SIZE(x) (sizeof(x) / sizeof(x[0]))

= /* clear an object (may be optimized away, use secure_memzero() to e= rase secrets) */
#define CLEAR(x) memset(&(x), 0, size= of(x))
diff --git a/src/openvpn/buffer.c b/src/openvpn/buff= er.c
index 5940ad9..0f0d17e 100644
--- a/sr= c/openvpn/buffer.c
+++ b/src/openvpn/buffer.c
@@ -40,12 +40,14 @@

array_mult_safe(const size_t m1, co= nst size_t m2, const size_t extra)
{
= const size_t limit =3D 0xFFFFFFFF;
- unsigned long long res =3D (unsigned long long)m1 * (unsig= ned long long)m2 + (unsigned long long)extra;
- if (unlikely(m1 > limit) || unlikely(m2 >= limit) || unlikely(extra > limit) || unlikely(res > (unsigned long l= ong)limit))
+ unsi= gned long long res =3D
+ if = (unlikely(m1 > limit) || unlikely(m2 > limit) || unlikely(extra > = limit)
+ || un= likely(res > (unsigned long long)limit))
{ msg(M_FATAL, "attempted allocation of excessively lar= ge array");
}
- return (size_t) res;
+ return (size_t)res;
}
void
@@ -96,9 +98,9 @@
= buf.offset =3D 0;
buf.len =3D 0;
= #ifdef DMALLOC
-= buf.data =3D (uint8_t *) gc_malloc_debug(size, false, gc, file, line);<= /span>
+ buf.data =3D (ui= nt8_t *)gc_malloc_debug(size, false, gc, file, line);
#els= e
- buf.data =3D (ui= nt8_t *) gc_malloc(size, false, gc);
+ buf.data =3D (uint8_t *)gc_malloc(size, false, gc);
#endif
if (size)
{=
@@ -119,9 +121,9 @@
ret.offset =3D bu= f->offset;
ret.len =3D buf->len;
#ifdef DMALLOC

- r= et.data =3D (uint8_t *) openvpn_dmalloc(file, line, buf->capacity);
+ ret.data =3D (uint8_= t *)openvpn_dmalloc(file, line, buf->capacity);
#else
- ret.data =3D (uint8= _t *) malloc(buf->capacity);
+ ret.data =3D (uint8_t *)malloc(buf->capacity); #endif
check_malloc_return(ret.data); memcpy(BPTR(&ret), BPTR(buf), BLEN(buf));
= @@ -150,7 +152,7 @@
return buf->debug_file;<= br> }

-#else /* ifdef BUF_INIT_TRACKING */
+#else /* ifdef BUF_INIT_TRACKING */

#define buf_debug_line(buf) 0
#define= buf_debug_file(buf) "[UNDEF]"
@@ -252,7 +254,7 @= @
stat =3D vsnprintf((char *)ptr, cap, format,= arglist);
va_end(arglist);
= *(buf->data + buf->capacity - 1) =3D 0; /* windows vsnprin= tf needs this */
- = buf->len +=3D (int) strlen((char *)ptr);
+ buf->len +=3D (int)strlen((ch= ar *)ptr);
if (stat >=3D 0 && stat = < cap)
{
r= et =3D true;
@@ -272,7 +274,7 @@
{
strncpynt((char *)ptr, str, cap);
= *(buf->data + buf->capacity - 1) =3D 0; /* windows vsnprintf ne= eds this */
- bu= f->len +=3D (int) strlen((char *)ptr);
+ buf->len +=3D (int)strlen((char *)ptr);
ret =3D true;
}
return ret;

@@ -299,8 +301,7 @@
buff= er_write_file(const char *filename, const struct buffer *buf)
{

bool ret =3D false;
- int fd =3D platform_open(filename, O_CREAT | O= _TRUNC | O_WRONLY,
- = S_IRUSR | S_IWUSR);
+ int fd =3D platform_open(filename, O_CREAT | O_= TRUNC | O_WRONLY, S_IRUSR | S_IWUSR);
if (fd =3D=3D -1= )
{
msg(M_ERRNO, "Cannot= open file '%s' for write", filename);
@@ -340= ,12 +341,12 @@
{
struct gc_en= try *e;
#ifdef DMALLOC
- e =3D (struct gc_entry *) openvpn_dmalloc(file, l= ine, size + sizeof(struct gc_entry));
+ e =3D (struct gc_entry *)openvpn_dmalloc(file, li= ne, size + sizeof(struct gc_entry));
#else
- e =3D (struct gc_entry *) mal= loc(size + sizeof(struct gc_entry));

+ e =3D (struct gc_entry *)malloc(size + sizeof(stru= ct gc_entry));
#endif
check_mallo= c_return(e);
- r= et =3D (char *) e + sizeof(struct gc_entry);
+ ret =3D (char *)e + sizeof(struct gc_entry= );
e->next =3D a->list;
= a->list =3D e;
}
@@ -361,7 +36= 2,7 @@
#ifndef ZERO_BUFFER_ON_ALLOC
i= f (clear)
#endif
- memset(ret, 0, size);
+ memset(ret, 0, size);
return= ret;
}

@@ -439,9 +440,9= @@
ASSERT(a);
struct gc_entry_sp= ecial *e;
#ifdef DMALLOC
- e =3D (struct gc_entry_special *) openvpn_dmalloc(f= ile, line, sizeof(struct gc_entry_special));
+ e =3D (struct gc_entry_special *)openvpn_dmall= oc(file, line, sizeof(struct gc_entry_special));
#else
- e =3D (struct gc_entr= y_special *) malloc(sizeof(struct gc_entry_special));
+ e =3D (struct gc_entry_special *)mall= oc(sizeof(struct gc_entry_special));
#endif
check_malloc_return(e);

e->free_fnc =3D free= _function;
@@ -479,15 +480,15 @@
*/

char *
-format_hex_ex(const uint8_t *data, int size, int maxoutput,<= /span>
- unsigned= int space_break_flags, const char *separator,
- struct gc_arena *gc)
+format_hex_ex(const uint8_t *data, = int size, int maxoutput, unsigned int space_break_flags,

+ const char *separator, s= truct gc_arena *gc)
{
const size_t by= tes_per_hexblock =3D space_break_flags & FHE_SPACE_BREAK_MASK; const size_t separator_len =3D separator ? strlen(separator) := 0;
static_assert(INT_MAX <=3D SIZE_MAX, "Code= assumes INT_MAX <=3D SIZE_MAX");
- const size_t out_len =3D maxoutput > 0 ? maxoutp= ut :
- = ((size * 2) + ((size / bytes_per_hexblock) * separator_len) + 2);=
+ const size_t ou= t_len =3D maxoutput > 0
+ ? maxoutput
+ : ((size * 2) = + ((size / bytes_per_hexblock) * separator_len) + 2);

struct buffer out =3D alloc_buf_gc(out_len, gc); for (int i =3D 0; i < size; ++i)
@@ -531,13= +532,13 @@
void
buf_null_terminate(struc= t buffer *buf)
{
- char *last =3D (char *) BLAST(buf);
+ char *last =3D (char *)BLAST(buf);
if (last && *last =3D=3D '\0') /* alread= y terminated? */
{
return;
}

- if (!buf_safe(buf, 1)) /* make space for trailing nu= ll */
+ if (!buf_s= afe(buf, 1)) /* make space for trailing null */
{
buf_inc_len(buf, -1);
}@@ -554,12 +555,12 @@
{
while = (true)
{
- char *last =3D (char *) BLAST(buf);
+ char *last =3D (char *)BLAST(buf)= ;
if (!last)
{
= break;
}
- if (char_class(*last, CC_CRLF|CC_NU= LL))
+ if (cha= r_class(*last, CC_CRLF | CC_NULL))
{
if (!buf_inc_len(buf, -1))

{
@@ -656,9 +657,9 @@
if (gc)<= br> {
#ifdef DMALLOC
- ret =3D (char *) gc_malloc_debu= g(n, false, gc, file, line);
+ ret =3D (char *)gc_malloc_debug(n, false, gc, file, li= ne);
#else
- ret =3D (char *) gc_malloc(n, false, gc);
+ ret =3D (char *)gc_mall= oc(n, false, gc);

#endif
}=
else
@@ -717,7 +718,7 @@
{

struct buffer out =3D alloc_buf_gc(256, gc);
int i =3D 0;
- for (;; )
= + for (;;)
{
const char *c= p =3D *p++;
if (!cp)
@@ -756,9 +75= 7,9 @@
ASSERT(str);

= #ifdef DMALLOC
- bu= f_set_read(&buf, (uint8_t *) string_alloc_debug(str, gc, file, line), s= trlen(str) + 1);
+ = buf_set_read(&buf, (uint8_t *)string_alloc_debug(str, gc, file, line),= strlen(str) + 1);
#else
- buf_set_read(&buf, (uint8_t *) string_alloc(str= , gc), strlen(str) + 1);
+ buf_set_read(&buf, (uint8_t *)string_alloc(str, gc), strlen(st= r) + 1);
#endif

if = (buf.len > 0) /* Don't count trailing '\0' as part of length= */
@@ -845,10 +846,9 @@
break= ;
}
line[n++] =3D (char)c= ;
- }
- while (c);

+ } while (c);
=
- line[size-1] =3D '\0= ';
+ line[size= - 1] =3D '\0';
return !(eol && !strle= n(line));
}

@@ -1038,7 += 1038,8 @@
* Guaranteed to not increase string length.
*/
bool
-string_mod(char *str, const unsigned int inclusive, const= unsigned int exclusive, const char replace)
+string_mod(char *str, const unsigned int inclusive= , const unsigned int exclusive,
+ const char replace)
{
const char *in =3D str;

bool ret =3D true;
@@ -1087,11 +1088,8 @@
}

const char *
-string_mod_const(const char *str,
- const unsigned int inclusive,
= - const unsigned = int exclusive,
- = const char replace,
- struct gc_arena *gc)
+string_mod_const(const char *str, const unsigned = int inclusive, const unsigned int exclusive,
+ const char replace, struct gc_are= na *gc)
{
if (str)
= {
@@ -1130,23 +1128,16 @@
if (buf &= amp;& buf->len)
{
int = msglevel =3D D_ALIGN_DEBUG;
- const unsigned int u =3D (unsigned int) BPTR(buf);
= + const unsigned int u = =3D (unsigned int)BPTR(buf);

- if (u & (PAYLOAD_ALIGN-1))
<= span style=3D"color: hsl(120, 100%, 40%);">+ if (u & (PAYLOAD_AL= IGN - 1))

{
msglevel = =3D D_ALIGN_ERRORS;
}

= msg(msglevel, "%sAlignment at %s/%d ptr=3D" ptr_fo= rmat " OLC=3D%d/%d/%d I=3D%s/%d",
- (msglevel =3D=3D D_ALIGN_ERRORS) ? "= ERROR: " : "",
- file,
- line,
-= (ptr_type)buf->data,
- buf->offset,
- buf->len,
- buf->capacity,
- buf_debug_file(buf),
= - buf_debug_line(buf))= ;
+ (msgle= vel =3D=3D D_ALIGN_ERRORS) ? "ERROR: " : "", file, line= , (ptr_type)buf->data,
+ buf->offset, buf->len, buf->capacity, buf_debug_= file(buf), buf_debug_line(buf));
}
}<= /span>
#endif /* ifdef VERIFY_ALIGNMENT */
@@ -12= 00,7 +1191,7 @@
if (str)
{=
const size_t len =3D strlen((const char *)str);- struct buffer_entry *e= =3D buffer_list_push_data(ol, str, len+1);
+ struct buffer_entry *e =3D buffer_list_push= _data(ol, str, len + 1);
if (e)
= {
e->buf.len =3D (int)len; /* Don= 9;t count trailing '\0' as part of length */
@@ -12= 49,8 +1240,7 @@
}

void<= /span>
-buffer_list_aggregate_= separator(struct buffer_list *bl, const size_t max_len,
- const cha= r *sep)
+buffer_list_= aggregate_separator(struct buffer_list *bl, const size_t max_len, const cha= r *sep)
{
const size_t sep_len =3D st= rlen(sep);
struct buffer_entry *more =3D bl->head;<= /span>
@@ -1339,7 +1329,7 @@

= if (fp)
{
- char *line =3D (char *) malloc(max_line_len);
= + char *line =3D (char *= )malloc(max_line_len);
if (line)
= {
bl =3D buffer_list_new();
= diff --git a/src/openvpn/buffer.h b/src/openvpn/buffer.h
index 0d5c30d..ae783c6 100644

--- a/src/openvpn/buffer.= h
+++ b/src/openvpn/buffer.h
@@ -58,13 +58,= 13 @@
*/
struct buffer
= {
- int capacity; = /**< Size in bytes of memory allocated by
- * \c = malloc(). */
- int o= ffset; /**< Offset in bytes of the actual content=
- = * within the allocated memory. */
- int len; /**< Length in bytes = of the actual content
-= * within the allocated memory. */=
- uint8_t *data; = /**< Pointer to the allocated memory. */
+ int capacity; /**< Size in bytes of mem= ory allocated by
+ = * \c malloc(). */
+ int offset; /**< Offset in bytes of the actual c= ontent
+ = * within the allocated memory. */
+ int len; /**< Length in bytes of the ac= tual content
+ = * within the allocated memory. */
+ uint8_t *data; /**< Pointer to the allo= cated memory. */

#ifdef BUF_INIT_TRACKIN= G
const char *debug_file;
@@ -85,8 +85= ,8 @@
*/
struct gc_entry
{

- struct gc_entr= y *next; /**< Pointer to the next item in the
- * linked= list. */
+ struct= gc_entry *next; /**< Pointer to the next item in the
+ * linked= list. */
};

/**=
@@ -114,8 +114,8 @@
*/
struct = gc_arena
{
- struct gc_entry *list; /**< First element of the linked l= ist of
- = * \c gc_entry structures. */
+ struct gc_entry *list; /**< First eleme= nt of the linked list of
+ * \c gc_entry structures. */
<= span> struct gc_entry_special *list_special;

};=

@@ -140,7 +140,7 @@
size_t array_mult_safe(const size_t m1, const size_t m2, const size= _t extra);

-#define PA_BRACKET (1<<0)
+#define PA_BRACKET (1 << 0)
char = *print_argv(const char **p, struct gc_arena *gc, const unsigned int flags);=

void buf_size_error(const size_t size);=
@@ -166,13 +166,15 @@

c= har *string_alloc_debug(const char *str, struct gc_arena *gc, const char *f= ile, int line);

-struct buffer string_alloc_buf_debug(const char *str, struct gc= _arena *gc, const char *file, int line);
+struct buffer string_alloc_buf_debug(const char *str, = struct gc_arena *gc, const char *file,
+ int line);
#else /* ifdef DMALLOC */

struct buffer alloc_buf(size_t size);

-struct buffer alloc_buf_gc(= size_t size, struct gc_arena *gc); /* allocate buffer with garbage collect= ion */
+struct buffer= alloc_buf_gc(size_t size,
+ struct gc_arena *gc); /* allocate buffer = with garbage collection */

struct buffer= clone_buf(const struct buffer *buf);

@@ = -197,8 +199,7 @@
* @param a gc_arena to use * @return new pointer
*/
-void *
-gc_realloc(void *ptr, size_t size, struct gc_arena *a);=
+void *gc_realloc(vo= id *ptr, size_t size, struct gc_arena *a);

#ifdef BUF_INIT_TRACKING

#define buf_init(buf, offset) = buf_init_debug(buf, offset, __FILE__, __LINE__)
@@ -213,14 = +214,14 @@
static inline void
gc_freeaddr= info_callback(void *addr)
{
- freeaddrinfo((struct addrinfo *) addr);+ freeaddrinfo((struct add= rinfo *)addr);
}

/** Re= turn an empty struct buffer */
static inline struct buffer=
clear_buf(void)
{
- return (struct buffer) { 0 };+ return (struct buffer){ 0= };
}

static inline boo= l
@@ -361,7 +362,7 @@
{
= if (maxlen > 0)
{
- strncpy(dest, src, maxlen-1);
+ strncpy(dest, src, maxlen = - 1);

dest[maxlen - 1] =3D 0;
= }
}
@@ -416,9 +417,9 @@
= SecureZeroMemory(data, len);
#elif defined(__GNUC__) |= | defined(__clang__)
memset(data, 0, len);
<= span style=3D"color: hsl(0, 100%, 40%);">- __asm__ __volatile__ ("&= quot; : : "r" (data) : "memory");

+ __asm__ __volatile__("" : := "r"(data) : "memory");
#else- volatile char *p =3D (vola= tile char *) data;
+ = volatile char *p =3D (volatile char *)data;
while (= len--)
{
*p++ =3D 0;@@ -435,12 +436,12 @@
bool buf_printf(struct buffe= r *buf, const char *format, ...)
#ifdef __GNUC__ #if __USE_MINGW_ANSI_STDIO
-__attribute__ ((format(gnu_printf, 2, 3)))
+ __attribute__((format(gnu_printf, 2= , 3)))
#else
-__attribute__ ((format(__printf__, 2, 3)))
+ __attribute__((format(__printf__, 2, 3))= )
#endif
#endif
-;
+ ;

/*
* p= uts append to a buffer with overflow check
@@ -493,12 +494,= 10 @@
/*
* Hex dump -- Output a binary b= uffer to a hex string and return it.
*/
-#define FHE_SPACE_BREAK_MASK 0xFF /* sp= ace_break parameter in lower 8 bits */
-#define FHE_CAPS 0x100 /* output hex in caps */=
-char *
-format_hex_ex(const uint8_t *data, i= nt size, int maxoutput,

- unsigned int space_break_flags, const char *separator,
- struct gc_ar= ena *gc);
+#define FH= E_SPACE_BREAK_MASK 0xFF /* space_break parameter in lower 8 bits */=
+#define FHE_CAPS = 0x100 /* output hex in caps */
+char *format_hex_ex(const uint8_t *data, int size, int maxout= put, unsigned int space_break_flags,
+ const char *separator, struct gc_arena= *gc);

static inline char *
format_hex(const uint8_t *data, int size, int maxoutput, struct gc_are= na *gc)

@@ -725,16 +724,10 @@
}
=
static inline bool
-buf_copy_range(struct buffer *dest,
- int dest_index,- const struct bu= ffer *src,
- = int src_index,
+b= uf_copy_range(struct buffer *dest, int dest_index, const struct buffer *src= , int src_index,
int src_len)
{

- if (src_inde= x < 0
- || sr= c_len < 0
- |= | src_index + src_len > src->len
- || dest_index < 0
+ if (src_index < 0 || src_len < 0 || src= _index + src_len > src->len || dest_index < 0
= || dest->offset + dest_index + src_len > dest->capacity)
{
return false;
@= @ -749,9 +742,7 @@

/* truncate src to le= n, copy excess data beyond len to dest */
static inline bo= ol
-buf_copy_excess(str= uct buffer *dest,
- = struct buffer *src,
- int len)
+buf_copy_excess(struct buffer *dest, struct buffer *src, int= len)
{
if (len < 0)
{

@@ -879,44 +870,44 @@
/* character classes */

-#define CC_ANY (1<<0) /**&= lt; any character */
-#= define CC_NULL (1<<1) /**< null character \0 */
+#define CC_ANY (1 <&= lt; 0) /**< any character */
+#define CC_NULL (1 << 1) /**< null= character \0 */

-#define CC_ALNUM (1<<2) /**< alphanumeri= c isalnum() */
-#define= CC_ALPHA (1<<3) /**< alphabetic isalpha() */<= br>-#define CC_ASCII = (1<<4) /**< ASCII character */
-#define CC_CNTRL (1<<5) /**< contr= ol character iscntrl() */
-#define CC_DIGIT (1<<6) /**< digit isdigit() */
-#define CC_PRINT = (1<<7) /**< printable (>=3D 32, !=3D 127) */
<= span style=3D"color: hsl(0, 100%, 40%);">-#define CC_PUNCT (1&= lt;<8) /**< punctuation ispunct() */

-#define CC_SPACE (1<<9) /**< whi= tespace isspace() */
-#= define CC_XDIGIT (1<<10) /**< hex digit isxdigit() */<= /span>
+#define CC_ALNUM (1= << 2) /**< alphanumeric isalnum() */
+#define CC_ALPHA (1 << 3) = /**< alphabetic isalpha() */
+#define CC_ASCII (1 << 4) /**< ASCII charact= er */
+#define CC_CNT= RL (1 << 5) /**< control character iscntrl() */+#define CC_DIGIT (1 <<= 6) /**< digit isdigit() */
+#define CC_PRINT (1 << 7) /**< printab= le (>=3D 32, !=3D 127) */
+#define CC_PUNCT (1 << 8) /**< punctuation ispun= ct() */
+#define CC_S= PACE (1 << 9) /**< whitespace isspace() */
+#define CC_XDIGIT (1 << 10) = /**< hex digit isxdigit() */


-#define CC_BLANK (1<<= 11) /**< space or tab */
-#define CC_NEWLINE (1<<12) /**< newline */=
-#define CC_CR = (1<<13) /**< carriage return */
+#define CC_BLANK (1 << 11) /**< spa= ce or tab */
+#define= CC_NEWLINE (1 << 12) /**< newline */
+#define CC_CR (1 << 13) = /**< carriage return */

-#define CC_BACKSLASH (1<<14) /**< = backslash */
-#define C= C_UNDERBAR (1<<15) /**< underscore */
-#define CC_DASH (1<<= 16) /**< dash */
-#d= efine CC_DOT (1<<17) /**< dot */
-#define CC_COMMA (1<<= 18) /**< comma */
-#= define CC_COLON (1<<19) /**< colon */
-#define CC_SLASH (1<&= lt;20) /**< slash */

-#define CC_SINGLE_QUOTE (1<<21) /**< single quote */
-#define CC_DOUBLE_QUOTE = (1<<22) /**< double quote */
-#define CC_REVERSE_QUOTE (1<<23) /**< reve= rse quote */
-#define C= C_AT (1<<24) /**< at sign */
-#define CC_EQUAL (1<<25)= /**< equal sign */
= -#define CC_LESS_THAN (1<<26) /**< less than sign */
-#define CC_GREATER_THAN = (1<<27) /**< greater than sign */
-#define CC_PIPE (1<<28) /**<= ; pipe */
-#define CC_Q= UESTION_MARK (1<<29) /**< question mark */
-#define CC_ASTERISK (1<<= 30) /**< asterisk */
+#define CC_BACKSLASH (1 << 14) /**< backslash */+#define CC_UNDERBAR (1 &= lt;< 15) /**< underscore */
+#define CC_DASH (1 << 16) /**< dash */
+#define CC_DOT = (1 << 17) /**< dot */
+#define CC_COMMA (1 << 18) /**< comma */
+#define CC_COLON = (1 << 19) /**< colon */
+#define CC_SLASH (1 << 20) /**< slash */
+#define CC_SINGLE_QUOTE = (1 << 21) /**< single quote */
+#define CC_DOUBLE_QUOTE (1 << 22) /**< doubl= e quote */
+#define C= C_REVERSE_QUOTE (1 << 23) /**< reverse quote */
+#define CC_AT (1 << 2= 4) /**< at sign */
+#define CC_EQUAL (1 << 25) /**< equal sign */
= +#define CC_LESS_THAN (1 &l= t;< 26) /**< less than sign */
+#define CC_GREATER_THAN (1 << 27) /**< greater t= han sign */
+#define = CC_PIPE (1 << 28) /**< pipe */
+#define CC_QUESTION_MARK (1 << 29) /**&l= t; question mark */
+= #define CC_ASTERISK (1 << 30) /**< asterisk */

/* macro classes */
-#define CC_NAME (CC_ALNUM|CC_UNDERBAR) /**= < alphanumeric plus underscore */
-#define CC_CRLF (CC_CR|CC_NEWLINE) /**< car= riage return or newline */
+#define CC_NAME (CC_ALNUM | CC_UNDERBAR) /**< alphanumeric plus u= nderscore */
+#define= CC_CRLF (CC_CR | CC_NEWLINE) /**< carriage return or newline */

bool char_class(const unsigned char c, cons= t unsigned int flags);

@@ -935,7 +926,8 @= @
* @param replace The character to replace the specified= character classes with.
* @return True if the string was= not modified, false otherwise.
*/
-bool string_mod(char *str, const unsigned i= nt inclusive, const unsigned int exclusive, const char replace);
= +bool string_mod(char *str, con= st unsigned int inclusive, const unsigned int exclusive,
+ const char replace);


/**
@@ = -946,8 +938,8 @@
* @param exclusive Character classes tha= t are not allowed even if they are also in inclusive.
* @= return True if the string consists only of allowed characters, false otherw= ise.
*/
-bool
-string_check_= buf(struct buffer *buf, const unsigned int inclusive, const unsigned int ex= clusive);
+bool strin= g_check_buf(struct buffer *buf, const unsigned int inclusive,
+ const unsig= ned int exclusive);


/**
= * Returns a copy of a string with certain classes of characters of it rep= laced with a specified
@@ -963,11 +955,8 @@
*

* @return The modified string with characters replac= ed within the specified range.
*/
-const char *string_mod_const(const char *st= r,
- = const unsigned int inclusive,
- const unsigned int exclusive= ,
- = const char replace,
- struct gc_arena *gc);
+const char *string_mod_const(const ch= ar *str, const unsigned int inclusive,
+ const unsigned int exclusiv= e, const char replace, struct gc_arena *gc);

void string_replace_leading(char *str, const char match, const char re= place);


@@ -1051,51 +1040,51 @@ * Allocate memory to hold a structure
*/<= br>
-#define ALL= OC_OBJ(dptr, type) \
- = { \
- check_m= alloc_return((dptr) =3D (type *) malloc(sizeof(type))); \
+#define ALLOC_OBJ(dptr, type) = \
+ { = \
+ chec= k_malloc_return((dptr) =3D (type *)malloc(sizeof(type))); \
}


-#define ALLOC_OBJ_CLEAR(dptr, type) \
- { \
- ALLOC_OBJ(dptr, type); \
+#define ALLOC_OBJ_CLEAR(dptr, type) \
+ { = \

+ AL= LOC_OBJ(dptr, type); \
memset((dptr), 0,= sizeof(type)); \
}

-#define ALLOC_ARRAY(dptr, type, n) \
- { \
- check_malloc_return((dptr) = =3D (type *) malloc(array_mult_safe(sizeof(type), (n), 0))); \

+#define ALLOC_ARRAY(dptr, type, = n) \

+ { = \

+ check_malloc_return((dpt= r) =3D (type *)malloc(array_mult_safe(sizeof(type), (n), 0))); \

= }

-#define ALLOC_ARRAY_GC(dptr, type, n, gc) \
- { \
- (dptr) =3D (type *) gc_malloc(array_mult_safe(siz= eof(type), (n), 0), false, (gc)); \
+#define ALLOC_ARRAY_GC(dptr, type, n, gc) = \
+ { = \
+ (dptr) =3D (type *)gc_malloc(array_mult_safe(sizeof(type), (n= ), 0), false, (gc)); \
}

<= span style=3D"color: hsl(0, 100%, 40%);">-#define ALLOC_ARRAY_CLEAR(dptr, t= ype, n) \

- { \
- ALLOC_ARRAY(dptr, = type, n); \
+#define = ALLOC_ARRAY_CLEAR(dptr, type, n) \
+ { = \

+ ALLOC_ARRAY(dptr, type, n); = \
memset((dptr), 0, (array_mult_safe(siz= eof(type), (n), 0))); \
}

= -#define ALLOC_ARRAY_CLEAR_GC(dpt= r, type, n, gc) \
- = { \
- (dptr) =3D= (type *) gc_malloc(array_mult_safe(sizeof(type), (n), 0), true, (gc)); \
+#define ALLOC_ARRAY_C= LEAR_GC(dptr, type, n, gc) \<= br>+ { = \
+ (dptr) =3D (type *)gc_mal= loc(array_mult_safe(sizeof(type), (n), 0), true, (gc)); \

= }

-#define ALLOC_VAR_ARRAY_CLEAR_GC(dptr, type, atype, n, gc) \<= br>- { \
- (dptr) =3D (type *) gc_malloc(array= _mult_safe(sizeof(atype), (n), sizeof(type)), true, (gc)); \
+#define ALLOC_VAR_ARRAY_CLEAR_GC(d= ptr, type, atype, n, gc) \
+ { = \
+ (dptr) =3D (ty= pe *)gc_malloc(array_mult_safe(sizeof(atype), (n), sizeof(type)), true, (gc= )); \
}

-#define ALLOC_OBJ_GC(dptr, type, gc) \
<= span style=3D"color: hsl(0, 100%, 40%);">- { \

- (dptr) =3D (type *) gc_malloc(sizeof(ty= pe), false, (gc)); \
= +#define ALLOC_OBJ_GC(dptr, type, gc) \+ { = \
+ (dptr) =3D (type *)gc_malloc(sizeof(type), false, (= gc)); \
}

-#define ALLOC_OBJ_CLEAR_GC(dptr, type, gc) \
- { \
- (dptr) =3D (type *) gc_malloc(s= izeof(type), true, (gc)); \
+#define ALLOC_OBJ_CLEAR_GC(dptr, type, gc) \
+ { = \
+ (dptr) =3D (type *)gc_malloc(sizeof(type), tru= e, (gc)); \
}

stati= c inline void
@@ -1120,8 +1109,8 @@
{
struct buffer_entry *head; /* next item to pop/peek */
struct buffer_entry *tail; /* last item pushed */<= br>- int size; = /* current number of entries */
- int max_size; /* maximum size list should grow to = */
+ int size; = /* current number of entries */
+ int max_size; /* maximum size li= st should grow to */
};

= /**
@@ -1209,8 +1198,7 @@
* @param max_l= en the maximum length of the aggregated buffer
* @param= sep the separator to put between buffers during aggregation */
-void buff= er_list_aggregate_separator(struct buffer_list *bl,
- const = size_t max_len, const char *sep);
+void buffer_list_aggregate_separator(struct buffer_list *bl, = const size_t max_len, const char *sep);

= struct buffer_list *buffer_list_file(const char *fn, int max_line_len);

diff --git a/src/openvpn/circ_list.h b/src/o= penvpn/circ_list.h
index cdbc8ef..eebf087 100644
= --- a/src/openvpn/circ_list.h
+++ b/src/openvpn/circ_= list.h
@@ -28,49 +28,46 @@
#include "= error.h"

#define CIRC_LIST(name, ty= pe) \
- struct name = { \
- int x_head= ; \
- int x_size= ; \
- int x_cap;= \
- int x_sizeo= f; \
- type x_li= st[]; \
+ struct n= ame \
+= { \
+ int x_head; \
+ int x_size; \
+ int x_cap; \<= br>+ int x_sizeof; = \
+ type x_= list[]; \
}

-#define CIRC_LIST_PUSH(obj, item) \
- { \
+#define CIRC_LIST_PUSH(obj, item) = \
+ { = \
(obj)->x_head =3D modulo_add((obj)-&g= t;x_head, -1, (obj)->x_cap); \
- (obj)->x_list[(obj)->x_head] =3D (item); \=
- (obj)->x_size =3D= min_int((obj)->x_size + 1, (obj)->x_cap); \
+ (obj)->x_list[(obj)->x_head] = =3D (item); \
+ (obj)->x_size =3D min_int((obj)->x_size + 1, = (obj)->x_cap); \
}

<= span style=3D"color: hsl(0, 100%, 40%);">-#define CIRC_LIST_SIZE(obj) \
- ((obj)->x_size)
+#define CIRC_LIST_SIZE= (obj) ((obj)->x_size)

-#define CIRC_LIST_INDEX(obj, index) \
- modulo_add((obj)->x_head, \
- index_veri= fy((index), (obj)->x_size, __FILE__, __LINE__), \
+#define CIRC_LIST_INDEX(obj, index) = \
+ modulo_add((obj)->x_head, index_verify(= (index), (obj)->x_size, __FILE__, __LINE__), \
= (obj)->x_cap)

-#define CIRC_LIST_ITEM(obj, index) \
- ((obj)->x_list[CIRC_LIST_INDEX((o= bj), (index))])
+#def= ine CIRC_LIST_ITEM(obj, index) ((obj)->x_list[CIRC_LIST_INDEX((obj), (in= dex))])

#define CIRC_LIST_RESET(obj) \
- { \
- (obj)->x_head =3D 0; \
- (obj)->x_size = =3D 0; \
+ { = \
+= (obj)->x_head =3D 0; \
+ (obj)->x_size =3D 0; \
}<= /span>

-#def= ine CIRC_LIST_ALLOC(dest, list_type, size) \
- { \
+#define CIRC_LIST_ALLOC(dest, list_type, size) = \
+ = { = \
const int so =3D sizeof(list_type) + sizeof((de= st)->x_list[0]) * (size); \
- (dest) =3D (list_type *) malloc(so); \
- check_malloc_return(dest); \
- memset((dest), 0, = so); \
- (dest)-= >x_cap =3D size; \
-= (dest)->x_sizeof =3D so; \
+ (dest) =3D (list_type *)malloc(so); = \
+ check_malloc_return(dest); = \
+ = memset((dest), 0, so); \
+ (dest)->x_c= ap =3D size; \
<= span style=3D"color: hsl(120, 100%, 40%);">+ (dest)->x_sizeof =3D= so; \

= }

-#= define CIRC_LIST_FREE(dest) \
- free(dest)
-add_entry(struct client_nat_o= ption_list *dest,
- = const struct client_nat_entry *e)
+add_entry(struct client_nat_option_list *dest, const st= ruct client_nat_entry *e)
{
if (dest-= >n >=3D MAX_CLIENT_NAT)
{
@@ -59= ,9 +58,7 @@
for (i =3D 0; i < list->n; ++i)<= /span>
{
const struct client= _nat_entry *e =3D &list->entries[i];
- msg(msglevel, " CNAT[%d] t=3D%d %s/= %s/%s",
- = i,
- = e->type,
+ = msg(msglevel, " CNAT[%d] t=3D%d %s/%s/%s", i, e->type= ,
print_in_addr_t(e->network, IA_NET_OR= DER, &gc),
print_in_addr_t(e->netma= sk, IA_NET_ORDER, &gc),
print_in_addr_= t(e->foreign_network, IA_NET_ORDER, &gc));
@@ -102,1= 1 +99,8 @@
}

void

-add_client_nat_to_option_li= st(struct client_nat_option_list *dest,
- const char *type,- c= onst char *network,
- = const char *netmask,
- const char *foreig= n_network,
+add_clien= t_nat_to_option_list(struct client_nat_option_list *dest, const char *type,=
+ = const char *network, const char *netmask, const char *foreign_ne= twork,
int msglevel)<= br> {
struct client_nat_entry e;
@@ -179,9 +173,7 @@

dirstr =3D "IN";
}

- msg(msglevel, "** CNAT %s %s %s -> %s",
- dirstr,<= br>- prefix,
+ msg(msglevel, "** CNAT %= s %s %s -> %s", dirstr, prefix,

print_in_a= ddr_t(iph->saddr, IA_NET_ORDER, &gc),
print= _in_addr_t(iph->daddr, IA_NET_ORDER, &gc));
=
@@ -189,11 +181,10 @@
}
=
void
-client= _nat_transform(const struct client_nat_option_list *list,
- struct buffer *ipb= uf,
+client_nat_trans= form(const struct client_nat_option_list *list, struct buffer *ipbuf,
const int direction)
{
- struct ip_tcp_udp_hd= r *h =3D (struct ip_tcp_udp_hdr *) BPTR(ipbuf);
+ struct ip_tcp_udp_hdr *h =3D (struct ip_tcp= _udp_hdr *)BPTR(ipbuf);
int i;
ui= nt32_t addr, *addr_ptr;
const uint32_t *from, *to;
diff --git a/src/openvpn/clinat.h b/src/openvpn/clinat.h
index d565a49..abfa0b7 100644
--- a/src/openvpn/= clinat.h
+++ b/src/openvpn/clinat.h
@@ -30,= 7 +30,8 @@
#define CN_OUTGOING 0
#define = CN_INCOMING 1

-struct client_nat_entry {
+struct client_nat_entry
+{
#define CN_SNAT 0
#= define CN_DNAT 1
int type;
@@ -39,28 += 40,27 @@
in_addr_t foreign_network;
}= ;

-st= ruct client_nat_option_list {
+struct client_nat_option_list
+{
int n;
stru= ct client_nat_entry entries[MAX_CLIENT_NAT];
};
=
struct client_nat_option_list *new_client_nat_list= (struct gc_arena *gc);

-struct client_nat_option_list *clone_client_nat_option_l= ist(const struct client_nat_option_list *src, struct gc_arena *gc);<= br>+struct client_nat_option_li= st *clone_client_nat_option_list(
+ const struct client_nat_option_list *src, struct gc_arena= *gc);

+void copy_client_nat_option_list(struct client_nat_opt= ion_list *dest,
+ = const struct client_nat_option_list *src);

void print_client_nat_list(const struct cli= ent_nat_option_list *list, int msglevel);

-void add_client_nat_to_option_list(st= ruct client_nat_option_list *dest,

- const char *type,- = const char *network,
- con= st char *foreign_network,
- int msglevel);
+void add_client_nat_to_option_list(struct= client_nat_option_list *dest, const char *type,
+ const char = *network, const char *netmask,
+ const char *foreign_network, = int msglevel);

-void client_nat_transform(const struct client_nat_option_list *l= ist,
- = struct buffer *ipbuf,
+void client_nat_transform(const struct client_nat_option_list *l= ist, struct buffer *ipbuf,
const= int direction);

#endif /* if !defined(C= LINAT_H) */
diff --git a/src/openvpn/common.h b/src/openvpn= /common.h
index d7f5d959..c0947da 100644
--= - a/src/openvpn/common.h
+++ b/src/openvpn/common.h<= br>@@ -27,7 +27,7 @@
* Statistics counters and asso= ciated printf format.
*/
typedef uint64_= t counter_type;
-#defin= e counter_format "%" PRIu64
+#define counter_format "%" PRIu64

/*
* Time intervals
@@ -37,17 +37,17 @@

/*
* Used as an up= per bound for timeouts.
*/
-#define BIG_TIMEOUT (60*60*24*7) /* one week (in s= econds) */
+#define B= IG_TIMEOUT (60 * 60 * 24 * 7) /* one week (in seconds) */
=
/*
* Printf formats for special types
*/
#ifdef _WIN64
-#define ptr_format "0x%016&q= uot; PRIx64
+#define = ptr_format "0x%016" PRIx64
#else
-#define ptr_format "= ;0x%08lx"

+#defi= ne ptr_format "0x%08lx"
#endif
-#define fragment_header_format "0= x%08x"
+#define = fragment_header_format "0x%08x"

/* these are used to cast the arguments

* and MUST matc= h the formats above */
@@ -94,6 +94,7 @@
/= *
* Script security warning
*/-#define SCRIPT_SECURITY_WARNIN= G "WARNING: External program may not be called unless '--script-se= curity 2' or higher is enabled. See --help text or man page for detaile= d info."
+#defin= e SCRIPT_SECURITY_WARNING \
+ "WARNING: External program may not be called unless '-= -script-security 2' or higher is enabled. See --help text or man page f= or detailed info."

#endif /* ifndef= COMMON_H */
diff --git a/src/openvpn/comp-lz4.c b/src/open= vpn/comp-lz4.c
index 425b1d9..6736469 100644
--- a/src/openvpn/comp-lz4.c

+++ b/src/openvpn/comp-lz4.c=
@@ -56,8 +56,7 @@

/* Do= esn't do any actual compression anymore */
static void=
-lz4_compress(struct b= uffer *buf, struct buffer work,
- struct compress_context *compctx,
+lz4_compress(struct buffer *buf, struc= t buffer work, struct compress_context *compctx,
= const struct frame *frame)
{
if (= buf->len <=3D 0)
@@ -78,8 +77,7 @@
<= /span>
/* Doesn't do any actual compression anymore */=
static void
= -lz4v2_compress(struct buffer *buf, struct buffer work,
- struct compress_context *c= ompctx,
+lz4v2_compre= ss(struct buffer *buf, struct buffer work, struct compress_context *compctx= ,
const struct frame *frame)
{

if (buf->len <=3D 0)
@@ -91= ,14 +89,13 @@
}

static = void
-do_lz4_decompress= (size_t zlen_max,
- = struct buffer *work,
- struct buffer *buf,
+do_lz4_decompress(size_t zlen_max, struct bu= ffer *work, struct buffer *buf,
struct c= ompress_context *compctx)
{
int uncom= p_len;
ASSERT(buf_safe(work, zlen_max));
- uncomp_len =3D LZ4_decompress_s= afe((const char *)BPTR(buf), (char *)BPTR(work), (size_t)BLEN(buf), zlen_ma= x);

+ uncomp_len = =3D LZ4_decompress_safe((const char *)BPTR(buf), (char *)BPTR(work), (size_= t)BLEN(buf),
+ = zlen_max);
if (uncomp_le= n <=3D 0)
{
dmsg(D_COMP_ER= RORS, "LZ4 decompression error: %d", uncomp_len);
@@ -117,12 +114,11 @@

}

static void

-lz4_deco= mpress(struct buffer *buf, struct buffer work,
- struct compress_context *compctx,
+lz4_decompress(struct= buffer *buf, struct buffer work, struct compress_context *compctx,<= br> const struct frame *frame)
{
size_t zlen_max =3D frame->buf.payload_size;
= - uint8_t c; /* flag = indicating whether or not our peer compressed */
+ uint8_t c; /* flag indicating whether or n= ot our peer compressed */

if (buf-&g= t;len <=3D 0)
{
@@ -155,12 +151,11 = @@
}

static void=
-lz4v2_decompress(struct buff= er *buf, struct buffer work,
- struct compress_context *compctx,
+lz4v2_decompress(struct buffer *buf, = struct buffer work, struct compress_context *compctx,
= const struct frame *frame)
{
= size_t zlen_max =3D frame->buf.payload_size;
- uint8_t c; /* flag indicating = whether or not our peer compressed */
+ uint8_t c; /* flag indicating whether or not our peer= compressed */

if (buf->len <= =3D 0)
{
@@ -203,19 +198,9 @@ }
}

-const struct compress_alg lz4_alg =3D {
- "lz4",
- lz4_compress_init,
- lz4_compress_uninit,<= /span>
- lz4_compress,
- lz4_decompress<= br>-};
+const struct compress_alg lz4_alg =3D { "= lz4", lz4_compress_init, lz4_compress_uninit, lz4_compress,
= + = lz4_decompress };

-const struct compress_alg lz4v2_alg =3D {
<= span style=3D"color: hsl(0, 100%, 40%);">- "lz4v2",

= - lz4v2_compress_init,<= br>- lz4_compress_uninit,
- lz4v2_compress,=
- lz4v2_decompress<= br>-};
+const struct compress_alg lz4v2_alg =3D { &quo= t;lz4v2", lz4v2_compress_init, lz4_compress_uninit,
+ = lz4v2_compress, lz4v2_decompress };
#endif /* ENABLE_LZ4= */
diff --git a/src/openvpn/comp.c b/src/openvpn/comp.c
index afea948..1a2e775 100644
--- a/src/openv= pn/comp.c
+++ b/src/openvpn/comp.c
@@ -171,= 10 +171,10 @@
{
#ifdef USE_COMP
msg(msglevel, "Compression or compression stub fra= ming is not allowed "
- "since data-channel offloading is enabled.");
+ = "since data-channel offloading is enabled.");
#e= lse
msg(msglevel, "Compression or compression= stub framing is not allowed "
- "since OpenVPN was built without compression= support.");
+ = "since OpenVPN was built without compression suppo= rt.");
#endif
return false;<= /span>
}
@@ -182,14 +182,14 @@
if ((info->flags & COMP_F_ALLOW_STUB_ONLY) && comp_no= n_stub_enabled(info))

{
msg(m= sglevel, "Compression is not allowed since allow-compression is "=
- "set= to 'stub-only'");
+ "set to 'stub-only'");<= /span>
return false;
}
#ifndef ENABLE_LZ4

if (info->alg =3D=3D COMP_AL= GV2_LZ4 || info->alg =3D=3D COMP_ALG_LZ4)
{<= br> msg(msglevel, "OpenVPN is compiled without LZ4 suppo= rt. Requested "
- = "compression cannot be enabled.");
+ "compression= cannot be enabled.");
return false; }
#endif
@@ -197,7 +197,7 @@<= /span>
if (info->alg =3D=3D COMP_ALG_LZO)
= {
msg(msglevel, "OpenVPN is compiled wit= hout LZO support. Requested "
- "compression cannot be enabled.");
+ &qu= ot;compression cannot be enabled.");
return f= alse;
}
#endif
diff -= -git a/src/openvpn/comp.h b/src/openvpn/comp.h
index a1c885= b..265e15d 100644
--- a/src/openvpn/comp.h
= +++ b/src/openvpn/comp.h
@@ -33,21 +33,22 @@
/* Compression flags */

/* Removed
#d= efine COMP_F_ADAPTIVE (1<<0) / * COMP_ALG_LZO only * /
- #define COMP_F_ALLOW_CO= MPRESS (1<<1) / * not only incoming is compressed but also outg= oing * /
+ #define CO= MP_F_ALLOW_COMPRESS (1<<1) / * not only incoming is compressed = but also outgoing *
+= /
*/
/** initial command byte is swappe= d with last byte in buffer to preserve payload alignment */
-#define COMP_F_SWAP (= 1<<2)

+#define = COMP_F_SWAP (1 << 2)
/** tell server= that we only support compression stubs */
-#define COMP_F_ADVERTISE_STUBS_ONLY (1<<3)
+#define COMP_F_ADVERTISE_= STUBS_ONLY (1 << 3)
/** Only accept stub compression= , even with COMP_F_ADVERTISE_STUBS_ONLY
* we still accept= other compressions to be pushed */
-#define COMP_F_ALLOW_STUB_ONLY (1<<4)
+#define COMP_F_ALLOW_STUB_ONLY = (1 << 4)

/** push stub-v2 or comp-lzo no when we= see a client with comp-lzo in occ */
-#define COMP_F_MIGRATE (1<<5)
= +#define COMP_F_MIGRATE = (1 << 5)
/** Compression was explicitly set to= allow asymetric compression */
-#define COMP_F_ALLOW_ASYM (1<<6)
+#define COMP_F_ALLOW_ASYM = (1 << 6)
/** Do not allow compression framing (break= s DCO) */
-#define COMP= _F_ALLOW_NOCOMP_ONLY (1<<7)
+#define COMP_F_ALLOW_NOCOMP_ONLY (1 << 7)<= br>
/* algorithms */
#define COMP_= ALG_UNDEF 0
@@ -60,7 +61,7 @@

= /* algorithm v2 */
#define COMP_ALGV2_UNCOMPRESSED = 10
-#define COMP_ALGV2_= LZ4 11
+#define = COMP_ALGV2_LZ4 11
/*
#define CO= MP_ALGV2_LZO 12
#define COMP_ALGV2_SNAPPY 13=
@@ -79,8 +80,7 @@
static inline bool
<= span> comp_non_stub_enabled(const struct compress_options *info)

= {
- return in= fo->alg !=3D COMP_ALGV2_UNCOMPRESSED
- && info->alg !=3D COMP_ALG_STUB
+ return info->alg= !=3D COMP_ALGV2_UNCOMPRESSED && info->alg !=3D COMP_ALG_STUB
&& info->alg !=3D COMP_ALG_UNDEF;
}

@@ -89,8 +89,7 @@ * flags of allow-compression and also the whether algorithms are = compiled
* in
*/
-bool
-check_compression_settings_valid(struct compress_options *in= fo, int msglevel);
+b= ool check_compression_settings_valid(struct compress_options *info, int msg= level);

#ifdef USE_COMP
= #include "buffer.h"
@@ -109,18 +108,18 @@=

/* V1 on wire codes */
/* Ini= tial command byte to tell our peer if we compressed */
-#define LZO_COMPRESS_BYTE 0x66
<= span style=3D"color: hsl(0, 100%, 40%);">-#define LZ4_COMPRESS_BYTE 0x69
+#define LZO_COMPRESS_B= YTE 0x66
+#define= LZ4_COMPRESS_BYTE 0x69
#define NO_COMPRESS_BYTE = 0xFA
/** to maintain payload alignment, replace this byte = with last byte of packet */
#define NO_COMPRESS_BYTE_SWAP = 0xFB

/* V2 on wire code */
-#define COMP_ALGV2_INDICATOR_BYTE = 0x50

-#define COMP= _ALGV2_UNCOMPRESSED_BYTE 0
-#define COMP_ALGV2_LZ4_BYTE 1
-#define COMP_ALGV2_LZO_BYTE 2
-#define COMP_ALGV2_SNAPPY_B= YTE 3
+#defi= ne COMP_ALGV2_INDICATOR_BYTE 0x50
+#define COMP_ALGV2_UNCOMPRESSED_BYTE 0
+#define COMP_ALGV2_LZ4_BYTE 1<= /span>
+#define COMP_ALGV2_L= ZO_BYTE 2
+#= define COMP_ALGV2_SNAPPY_BYTE 3

/*=
* Compress worst case size expansion (for any algorithm)=
@@ -129,7 +128,7 @@
* Snappy: len + len/= 6 + 32
* LZ4: len + len/255 + 16 (LZ4_COMPRESSBOUND(l= en))
*/
-#define COMP_EXTRA_BUFFER(len) ((len)/6 + 128 + 3 + COMP_PREFIX_LEN)
+#define COMP_EXTRA_BUF= FER(len) ((len) / 6 + 128 + 3 + COMP_PREFIX_LEN)
/*
* Don't try to compress any packet smalle= r than this.
@@ -147,12 +146,10 @@
con= st char *name;
void (*compress_init)(struct compress_c= ontext *compctx);
void (*compress_uninit)(struct compr= ess_context *compctx);
= - void (*compress)(struct buffer *buf, struct buffer work,
- struct compres= s_context *compctx,

+= void (*compress)(struct buffer *buf, struct buffer work, struct compres= s_context *compctx,
const struct fram= e *frame);

- void (*decompress)(struct buffer *buf, struct buffer work,
- stru= ct compress_context *compctx,
+ void (*decompress)(struct buffer *buf, struct buffer work, st= ruct compress_context *compctx,
con= st struct frame *frame);
};

diff --git a/src/openvpn/compstub.c b/src/openvpn/compstub.c

= index 853e9ee..bf709df 100644
--- a/src/openvpn/comps= tub.c
+++ b/src/openvpn/compstub.c
@@ -45,8= +45,7 @@
}

static void=
-stub_compress(struct = buffer *buf, struct buffer work,
- struct compress_context *compctx,
+stub_compress(struct buffer *buf, st= ruct buffer work, struct compress_context *compctx,
= const struct frame *frame)
{
= if (buf->len <=3D 0)
@@ -56,7 +55,7 @@
if (compctx->flags & COMP_F_SWAP)

{
uint8_t *head =3D BPTR(buf);
- uint8_t *tail =3D BEND(buf);+ uint8_t *tail =3D BEN= D(buf);
ASSERT(buf_safe(buf, 1));
= ++buf->len;

@@ -72,8 +71,7 @@=
}

static void-stub_decompress(struct buffer = *buf, struct buffer work,
- struct compress_context *compctx,
+stub_decompress(struct buffer *buf, struc= t buffer work, struct compress_context *compctx,
= const struct frame *frame)
{
u= int8_t c;
@@ -107,8 +105,7 @@

<= span>

static void
-stubv2_compress(struct buffer *buf, struct buffer work,
- struct comp= ress_context *compctx,
-= stubv2_decompress(struct buffer *buf, struct buffer work,
- struct compress_conte= xt *compctx,
+stubv2_= decompress(struct buffer *buf, struct buffer work, struct compress_context = *compctx,
const struct frame *frame)
{
if (buf->len <=3D 0)
<= span>@@ -157,19 +153,9 @@

}
}<= br>
-const struc= t compress_alg compv2_stub_alg =3D {
- "stubv2",
- stub_compress_init,
- stub_compress_uninit,
- stubv2_compress,
- stubv2_decompress
-};
+const struct compress_alg compv2_stub_alg =3D { "stubv2", st= ub_compress_init, stub_compress_uninit,
+ stubv2_co= mpress, stubv2_decompress };

-const struct compress_alg comp_stub_alg =3D {
- "stub",
- stub_compress_init,
- stub_compress_uninit= ,
- stub_compress,
- stub_decompress
-};
+const struct compress_alg comp_stub_alg = =3D { "stub", stub_compress_init, stub_compress_uninit,+ = stub_compress, stub_decompress };
#endif /*= USE_STUB */
diff --git a/src/openvpn/console.c b/src/openv= pn/console.c
index 7cc4fff..bdceaf2 100644
= --- a/src/openvpn/console.c
+++ b/src/openvpn/console.c
@@ -37,7 +37,7 @@
#endif


-struct= _query_user query_user[QUERY_USER_NUMSLOTS]; /* GLOBAL */
+struct _query_user query_user[QUERY= _USER_NUMSLOTS]; /* GLOBAL */


void
@@ -53,16 +53,14 @@

void
-query_user_add(char *prompt, size_t prompt_len,
- char *resp, size_t resp_= len,
- bo= ol echo)
+query_user_= add(char *prompt, size_t prompt_len, char *resp, size_t resp_len, bool echo= )
{
int i;
/* Ensure input is sane. All these must be present otherwise = it is
* a programming error.
*/=
- ASSERT( prompt_le= n > 0 && prompt !=3D NULL && resp_len > 0 && = resp !=3D NULL );
+ = ASSERT(prompt_len > 0 && prompt !=3D NULL && resp_len = > 0 && resp !=3D NULL);

/= * Seek to the last unused slot */
for (i =3D 0; i <= QUERY_USER_NUMSLOTS; i++)
@@ -72,7 +70,7 @@
break;

}
}
- ASSERT( i < QUERY_= USER_NUMSLOTS ); /* Unlikely, but we want to panic if it happens */=
+ ASSERT(i < QUERY_US= ER_NUMSLOTS); /* Unlikely, but we want to panic if it happens */
=
/* Save the information needed for the user in= teraction */
query_user[i].prompt =3D prompt;diff --git a/src/openvpn/console.h b/src/openvpn/console.hindex 3e99776..14b6116 100644
--- a/src/openvpn/con= sole.h
+++ b/src/openvpn/console.h
@@ -30,1= 6 +30,17 @@
/**
* Configuration setup f= or declaring what kind of information to ask a user for
*= /
-struct _query_user {=
- char *prompt; = /**< Prompt to present to the user */
- size_t prompt_len; /**< Length of= the prompt string */
-= char *response; /**< The user's response */
= - size_t response_len; /*= *< Length the of the user response */
- bool echo; /**< True: The user sho= uld see what is being typed, otherwise mask it */
+struct _query_user
+{
+ char *prompt; /**< Prompt to present to the user *= /
+ size_t prompt_= len; /**< Length of the prompt string */
+ char *response; /**< The user's r= esponse */
+ size_= t response_len; /**< Length the of the user response */
+ bool echo; /**< Tru= e: The user should see what is being typed, otherwise mask it */
= };

#define QUERY_USER_NUMSLOTS 10=
-extern struct _query_= user query_user[]; /**< Global variable, declared in console.c */
+extern struct _query_user= query_user[]; /**< Global variable, declared in console.c */
=
/**
* Wipes all data put into al= l of the query_user structs
@@ -58,9 +59,7 @@
* @param echo Should the user input be echoed to the user? If F= alse, input will be masked

*
*/<= br>-void query_user_add(char *pro= mpt, size_t prompt_len,
- char *resp, size_t resp_len,
- bool echo);
+void query_user_add(char *prompt, = size_t prompt_len, char *resp, size_t resp_len, bool echo);



/**
@@ -107,7 +106,7 = @@
{
return query_user_exec_builtin()= ;
}
-#= endif /* defined(ENABLE_SYSTEMD) */
+#endif /* defined(ENABLE_SYSTEMD) */


/**
@@ -118,9 +117,7 @@
*
*/
static inline bool
-query_user_SINGLE(char = *prompt, size_t prompt_len,
- char *resp, size_t resp_len,
- bool echo)
+query_user_SINGLE(char *prompt, si= ze_t prompt_len, char *resp, size_t resp_len, bool echo)

{=
query_user_clear();
query_user_a= dd(prompt, prompt_len, resp, resp_len, echo);
diff --git a/= src/openvpn/console_builtin.c b/src/openvpn/console_builtin.c
index b6db701..b0228dd 100644

--- a/src/openvpn/console_= builtin.c
+++ b/src/openvpn/console_builtin.c
@@ -67,11 +67,10 @@


HANDLE in =3D= GetStdHandle(STD_INPUT_HANDLE);
int orig_stderr =3D g= et_orig_stderr(); /* guaranteed to be always valid */
- if ((in =3D=3D INVALID_HANDLE_VALUE)
- || win32_service= _interrupt(&win32_signal)
+ if ((in =3D=3D INVALID_HANDLE_VALUE) || win32_service_interru= pt(&win32_signal)
|| (_write(orig_stderr, prom= pt, strlen(prompt)) =3D=3D -1))
{
- msg(M_WARN|M_ERRNO, "get_cons= ole_input_win32(): unexpected error");
+ msg(M_WARN | M_ERRNO, "get_console_inp= ut_win32(): unexpected error");
return false;=
}

@@ -135,7 +134,7 = @@
return false;
}
<= /span>
-#endif /* _WIN32 */<= /span>
+#endif /* _WIN32 */<= /span>


#ifdef HAVE_TERMIOS_H<= /span>
@@ -177,7 +176,7 @@
}
= }

-#= endif /* HAVE_TERMIOS_H */
+#endif /* HAVE_TERMIOS_H */


/**
@@ -209,15 +208,17 @@
= * (in which case neither stdin or stderr are connected to a tty and
* /dev/tty can not be open()ed anymore)
= */
- if (!isat= ty(0) && !isatty(2) )
+ if (!isatty(0) && !isatty(2))
{<= /span>
- int fd =3D ope= n( "/dev/tty", O_RDWR );
+ int fd =3D open("/dev/tty", O_RDWR);
if (fd < 0)
{
- msg(M_FATAL, "neit= her stdin nor stderr are a tty device and you have neither a "
<= br>+ msg(M_FATAL,
+ "= neither stdin nor stderr are a tty device and you have neither a "
"controlling tty nor systemd - can't= ask for '%s'. If you used --daemon, "
= "you need to use --askpass to make passphrase-protected key= s work, and you "
= - "can not use --auth-nocache.", prompt );<= br>+ "can n= ot use --auth-nocache.",
+ prompt);
}
close(fd);

}
@@ -285,8 +28= 6,8 @@
/* Loop through configured query_user slots */<= /span>
for (i =3D 0; i < QUERY_USER_NUMSLOTS && qu= ery_user[i].response !=3D NULL; i++)
{
- if (!get_console_input(query_= user[i].prompt, query_user[i].echo,

- query_user[i].response, query_= user[i].response_len) )
+ if (!get_console_input(query_user[i].prompt, query_user[i].echo= , query_user[i].response,
+ query_user[i].response_len)) {
/* Force the final result st= ate to failed on failure */
ret =3D false;
diff --git a/src/openvpn/console_systemd.c b/src/openvpn/conso= le_systemd.c
index 36103b2..d277bd4 100644
= --- a/src/openvpn/console_systemd.c
+++ b/src/openvpn/conso= le_systemd.c
@@ -50,9 +50,7 @@
* moun= ted, as well as the systemd-ask-password executable
*= being available */

- return (sd_booted() > 0)
- && (stat(SYSTEMD_ASK_PASSWORD_= PATH, &c) =3D=3D 0);
+ return (sd_b= ooted() > 0) && (stat(SYSTEMD_ASK_PASSWORD_PATH, &c) =3D=3D = 0);
}

static bool
@@ -79,7 +77,7 @@
return false;<= br> }
memset(input, 0, capacity);
= - if (read(std_out, input, cap= acity-1) !=3D 0)
+ = if (read(std_out, input, capacity - 1) !=3D 0)
{
chomp(input);
ret =3D true;
@@ -99,7 +97,7 @@
bool
que= ry_user_exec_systemd(void)
{
- bool ret =3D true; /* Presume everything goes = okay */
+ bool ret= =3D true; /* Presume everything goes okay */
int i;

/* If systemd is not available, use t= he default built-in mechanism */
@@ -112,7 +110,7 @@=
for (i =3D 0; i < QUERY_USER_NUMSLOTS && query_us= er[i].response !=3D NULL; i++)
{
= if (!get_console_input_systemd(query_user[i].prompt, query_user[i].echo= ,
- = query_user[i].response, query_user[i].response_len) )
+ = query_user[i].response, query_user[i].response_len))
{
/* Force the final resul= t state to failed on failure */
ret =3D false;=
diff --git a/src/openvpn/crypto.c b/src/openvpn/crypto.c
index 1c1be46..af7583a 100644
--- a/src/open= vpn/crypto.c
+++ b/src/openvpn/crypto.c
@@ = -63,8 +63,7 @@
*/

stat= ic void
-openvpn_encryp= t_aead(struct buffer *buf, struct buffer work,
- struct crypto_options *opt)
+openvpn_encrypt_aead(= struct buffer *buf, struct buffer work, struct crypto_options *opt)<= br> {
struct gc_arena gc;
i= nt outlen =3D 0;
@@ -88,7 +87,7 @@
/* = Prepare IV */
{
struct buffer= iv_buffer;
- ui= nt8_t iv[OPENVPN_MAX_IV_LENGTH] =3D {0};
+ uint8_t iv[OPENVPN_MAX_IV_LENGTH] =3D { 0 };
const int iv_len =3D cipher_ctx_iv_length(ctx->c= ipher);

ASSERT(iv_len >=3D OP= ENVPN_AEAD_MIN_IV_LEN && iv_len <=3D OPENVPN_MAX_IV_LENGTH);
@@ -133,17 +132,14 @@
/* Buffer overflow = check */
if (!buf_safe(&work, buf->len + mac_le= n + cipher_ctx_block_size(ctx->cipher)))
{- msg(D_CRYPT_ERRORS,
- "ENCRYP= T: buffer size error, bc=3D%d bo=3D%d bl=3D%d wc=3D%d wo=3D%d wl=3D%d"= ,
- buf->= capacity, buf->offset, buf->len, work.capacity, work.offset,- work.len);<= br>+ msg(D_CRYPT_ERRORS,= "ENCRYPT: buffer size error, bc=3D%d bo=3D%d bl=3D%d wc=3D%d wo=3D%d = wl=3D%d",
+ = buf->capacity, buf->offset, buf->len, work.capacity, work.o= ffset, work.len);
goto err;
}=

/* For AEAD ciphers, authenticate A= dditional Data, including opcode */
ASSERT(cipher_ctx_= update_ad(ctx->cipher, BPTR(&work), BLEN(&work)));
- dmsg(D_PACKET_CONTENT, "EN= CRYPT AD: %s",

- = format_hex(BPTR(&work), BLEN(&work), 0, &gc));+ dmsg(D_PACKET_CONTENT, &q= uot;ENCRYPT AD: %s", format_hex(BPTR(&work), BLEN(&work), 0, &= amp;gc));

if (!use_epoch_data_format= )
{
@@ -159,7 +155,7 @@
/* update number of plaintext blocks encrypted. Use the (x + (n-1))/= n trick

* to round up the result to the number of blo= cks used */
const int blocksize =3D AEAD_LIMIT_BLOCKSI= ZE;
- opt->key_ct= x_bi.encrypt.plaintext_blocks +=3D (outlen + (blocksize - 1))/blocksize;
+ opt->key_ctx_bi= .encrypt.plaintext_blocks +=3D (outlen + (blocksize - 1)) / blocksize;

/* Flush the encryption buffer */=
ASSERT(cipher_ctx_final(ctx->cipher, BEND(&work), &am= p;outlen));
@@ -191,8 +187,7 @@
}
static void
-openvpn_encrypt_v1(struct buffer *buf, struct buffer work,=
- st= ruct crypto_options *opt)
+openvpn_encrypt_v1(struct buffer *buf, struct buffer work, struct cry= pto_options *opt)
{
struct gc_arena g= c;
gc_init(&gc);
@@ -206,7 +201,7 = @@
/* Do Encrypt from buf -> work */
= if (ctx->cipher)
{
- uint8_t iv_buf[OPENVPN_= MAX_IV_LENGTH] =3D {0};

+ uint8_t iv_buf[OPENVPN_MAX_IV_LENGTH] =3D { 0 };
= const int iv_size =3D cipher_ctx_iv_length(ctx->ciphe= r);
int outlen;

@@ -226,8 +221,7 @@

/* Put packet ID i= n plaintext buffer */
if (packet_id_initia= lized(&opt->packet_id)
&&am= p; !packet_id_write(&opt->packet_id.send, buf,
- opt= ->flags & CO_PACKET_ID_LONG_FORM,
- true))+ = opt->flags & CO_PACKET_ID_LONG_FORM, true))
{

msg(D_CRYPT_ERRO= RS, "ENCRYPT ERROR: packet ID roll over");
= goto err;
@@ -252,8 +246,7 @@
ASSERT(buf_write(&work, iv_buf, iv_size));

dmsg(D_PACKET_CONTENT, "ENCRYPT IV: %s", format_h= ex(iv_buf, iv_size, 0, &gc));


- dmsg(D_PACKET_CONTENT, "EN= CRYPT FROM: %s",
-= format_hex(BPTR(buf), BLEN(buf), 80, &gc));
= + dmsg(D_PACKET_CONT= ENT, "ENCRYPT FROM: %s", format_hex(BPTR(buf), BLEN(buf), 80, &am= p;gc));

/* cipher_ctx was al= ready initialized with key & keylen */
ASS= ERT(cipher_ctx_reset(ctx->cipher, iv_buf));
@@ -261,13 += 254,9 @@
/* Buffer overflow check */ if (!buf_safe(&work, buf->len + cipher_ctx_block= _size(ctx->cipher)))
{
- msg(D_CRYPT_ERRORS, "= ENCRYPT: buffer size error, bc=3D%d bo=3D%d bl=3D%d wc=3D%d wo=3D%d wl=3D%d= cbs=3D%d",
- = buf->capacity,
- buf->offset,
- buf->len,
- work.capacity,
- work.o= ffset,
- = work.len,
+ = msg(D_CRYPT_ERRORS,
+ "ENCRYPT: buffer size error, bc=3D%d bo= =3D%d bl=3D%d wc=3D%d wo=3D%d wl=3D%d cbs=3D%d",
+ buf->capacity, buf= ->offset, buf->len, work.capacity, work.offset, work.len,
<= span> cipher_ctx_block_size(ctx->cipher));
goto err;
}
= @@ -281,14 +270,13 @@
ASSERT(buf_inc_len= (&work, outlen));

/* For= all CBC mode ciphers, check the last block is complete */
- ASSERT(cipher_ctx_mode(ctx= ->cipher) !=3D OPENVPN_MODE_CBC
- || outlen =3D=3D iv_size);
+ ASSERT(cipher_ctx_mode(c= tx->cipher) !=3D OPENVPN_MODE_CBC || outlen =3D=3D iv_size);
<= span> }

- = else /* No Encryption */
+ else /* No Encryption */ {
if (packet_id_initialized(&= amp;opt->packet_id)
= - && !packet_id_write(&opt->packet_id.send, b= uf,
- = opt->flags & CO_PACKET_ID_LONG_FORM, true))=
+ &&= !packet_id_write(&opt->packet_id.send, buf, opt->flags & CO_= PACKET_ID_LONG_FORM,
= + true))
{<= /span>
msg(D_CRYPT_ERRORS, "ENCRYPT ERROR: p= acket ID roll over");
goto err;
@@ -317,8 +305,7 @@

*= buf =3D work;

- dmsg(D_PACKET_CONTENT, "ENCRYPT TO: %s",=
- format_hex(BPTR= (&work), BLEN(&work), 80, &gc));
+ dmsg(D_PACKET_CONTENT, "ENCRYPT TO: %= s", format_hex(BPTR(&work), BLEN(&work), 80, &gc));=
}

gc_free(&gc);
@@ -332,8 +319,7 @@
}

void
-ope= nvpn_encrypt(struct buffer *buf, struct buffer work,
- struct crypto_options *opt)=
+openvpn_encrypt(str= uct buffer *buf, struct buffer work, struct crypto_options *opt)
= {
if (buf->len > 0 && opt)=
{
@@ -380,10 +366,8 @@
}

bool
-crypto_check_replay(struct crypto_options *opt,
<= span style=3D"color: hsl(0, 100%, 40%);">- const struct = packet_id_net *pin, uint16_t epoch,

- const char *error_prefix,
- struct gc_arena *= gc)

+crypto_check_rep= lay(struct crypto_options *opt, const struct packet_id_net *pin, uint16_t e= poch,
+ = const char *error_prefix, struct gc_arena *gc)
{
bool ret =3D false;
struct packet_id= _rec *recv;
@@ -400,8 +384,10 @@
{
/* We have an epoch that is neither current or old re= cv key but
* is authenticated, ie we need to move= to a new current recv key */
- msg(D_GENKEY, "Received data packet with new epoch %d.= Updating "
- = "receive key", epoch);
+ msg(D_GENKEY,
+ "Received data packet with new epoch= %d. Updating "
= + "receive key",
+ epoch);
epoch_replac= e_update_recv_key(opt, epoch);
recv =3D &opt-&= gt;packet_id.rec;
}
@@ -420,7 +406,8 @= @
{
if (!(opt->flags &= CO_MUTE_REPLAY_WARNINGS))
{
- msg(D_REPLAY_ERRORS, "%s: = bad packet ID (may be a replay): %s -- "
+ msg(D_REPLAY_ERRORS,
+ "%s: bad packet= ID (may be a replay): %s -- "
"= see the man page entry for --replay-window for "
= "more info or silence this warning with --mute-replay-warn= ings",
error_prefix, packet_id_net_pr= int(pin, true, gc));
@@ -438,9 +425,8 @@
= * On success, buf is set to point to plaintext, true is returned. */
static bool
-openvpn_decrypt_aead(struct buffer *buf, struct buffer w= ork,
- = struct crypto_options *opt, const struct frame *frame,
- const uint8_t *ad= _start)
+openvpn_decr= ypt_aead(struct buffer *buf, struct buffer work, struct crypto_options *opt= ,
+ = const struct frame *frame, const uint8_t *ad_start)
{
static const char error_prefix[] =3D "AEAD Decrypt= error";
struct packet_id_net pin =3D { 0 };
@@ -462,8 +448,7 @@
ASSERT(buf->len >= ; 0);
ASSERT(ctx->cipher);
=
- dmsg(D_PACKET_CONTENT, &= quot;DECRYPT FROM: %s",
- format_hex(BPTR(buf), BLEN(buf), 80, &gc));
<= span style=3D"color: hsl(120, 100%, 40%);">+ dmsg(D_PACKET_CONTENT, &quo= t;DECRYPT FROM: %s", format_hex(BPTR(buf), BLEN(buf), 80, &gc));

ASSERT(ad_start >=3D buf->data = && ad_start <=3D BPTR(buf));

@= @ -571,28 +556,24 @@

/* feed in tag = and the authenticated data */
ASSERT(cipher_ctx_update= _ad(ctx->cipher, ad_start, ad_size));
- dmsg(D_PACKET_CONTENT, "DECRYPT AD: %s",
- format_hex(ad_= start, ad_size, 0, &gc));
+ dmsg(D_PACKET_CONTENT, "DECRYPT AD: %s", format_hex= (ad_start, ad_size, 0, &gc));

/*= Decrypt and authenticate packet */
int outlen;=
- if (!cipher_ctx_update(c= tx->cipher, BPTR(&work), &outlen, BPTR(buf),
- data_len))
+ if (!cipher_ctx_upd= ate(ctx->cipher, BPTR(&work), &outlen, BPTR(buf), data_len))
{
CRYPT_ERROR("packet decry= ption failed");
}

ASSERT(buf_inc_len(&work, outlen));

- if (!cipher_ctx_final_check_tag(ctx->ciphe= r, BPTR(&work) + outlen,
- &outlen, tag_ptr, tag_size))=
+ if (!cipher_ctx= _final_check_tag(ctx->cipher, BPTR(&work) + outlen, &outlen, tag= _ptr, tag_size))
{
ctx->fa= iled_verifications++;
CRYPT_DROP("packet tag = authentication failed");
}
A= SSERT(buf_inc_len(&work, outlen));

- dmsg(D_PACKET_CONTENT, "DECRYPT= TO: %s",
- = format_hex(BPTR(&work), BLEN(&work), 80, &gc));
+ dmsg(D_PACKET_CONTENT, "= DECRYPT TO: %s", format_hex(BPTR(&work), BLEN(&work), 80, &= ;gc));


if (!crypto_check_replay(opt,= &pin, epoch, error_prefix, &gc))
{
= @@ -603,7 +584,7 @@
/* update number of plaintex= t blocks decrypted. Use the (x + (n-1))/n trick
* to = round up the result to the number of blocks used. */
c= onst int blocksize =3D AEAD_LIMIT_BLOCKSIZE;
- opt->key_ctx_bi.decrypt.plaintext_blocks +=3D= (outlen + (blocksize - 1))/blocksize;
+ opt->key_ctx_bi.decrypt.plaintext_blocks +=3D (ou= tlen + (blocksize - 1)) / blocksize;

= *buf =3D work;

@@ -626,8 +607,8 @@
* On success, buf is set to point to plaintext, true is return= ed.
*/
static bool
-openvpn_decrypt_v1(struct buffer *buf, stru= ct buffer work,
- = struct crypto_options *opt, const struct frame *frame)<= br>+openvpn_decrypt_v1(struct b= uffer *buf, struct buffer work, struct crypto_options *opt,
+ const struct fra= me *frame)

{
static const char error_= prefix[] =3D "Authenticate/Decrypt packet error";
struct gc_arena gc;

@@ -639,8 +620,7 @@
struct packet_id_net pin;

bool have_pi= n =3D false;

- dmsg(D_PACKET_CONTENT, "DECRYPT FROM: %s",
- format_hex(BPT= R(buf), BLEN(buf), 80, &gc));
+ dmsg(D_PACKET_CONTENT, "DECRYPT FROM: %s", = format_hex(BPTR(buf), BLEN(buf), 80, &gc));
/* Verify the HMAC */
if (ctx->= hmac)
@@ -722,8 +702,7 @@
}
ASSERT(buf_inc_len(&work, outlen));
- = dmsg(D_PACKET_CONTENT, "DECRYPT TO: %s",
- format_hex(BPTR(&work), B= LEN(&work), 80, &gc));
+ dmsg(D_PACKET_CONTENT, "DECRYPT TO: %s", f= ormat_hex(BPTR(&work), BLEN(&work), 80, &gc));
=
/* Get packet ID from plaintext buffer or IV= , depending on cipher mode */
{
@@ -731,7 +710,8 @@

{
= if (packet_id_initialized(&opt->packet_id))
{
- if (!packet_id_read(&pin, &work= , BOOL_CAST(opt->flags & CO_PACKET_ID_LONG_FORM)))
+ if (!packet_i= d_read(&pin, &work,
+ BOOL_CAST(opt->flags= & CO_PACKET_ID_LONG_FORM)))
{=
CRYPT_ERROR("error readi= ng CBC packet-id");
}<= br>@@ -790,9 +770,8 @@


= bool
-openvpn_de= crypt(struct buffer *buf, struct buffer work,
- struct crypto_options *opt, const s= truct frame *frame,
- = const uint8_t *ad_start)
+openvpn_decrypt(struct buffer *buf, struct buffer work, = struct crypto_options *opt,
+ const struct frame *frame, const uint8_t *ad_start)=
{
bool ret =3D false;

@@ -815,9 +794,7 @@
}
=
unsigned int
-calculate_crypto_overhead(const struct key_type *kt,
- unsigned= int pkt_id_size,

- = bool occ)
+calculate_crypto_overhead(const struct key_type *kt, unsigned i= nt pkt_id_size, bool occ)
{
unsigned = int crypto_overhead =3D 0;

@@ -866,9 +843= ,8 @@
unsigned int
crypto_max_overhead(vo= id)
{
= - return packet_id_size(true) + OPENVPN_MAX_IV_LENGTH
- +OPENVPN_MAX_CIPHER_BLOCK_SIZ= E
- +max_int(= OPENVPN_MAX_HMAC_SIZE, OPENVPN_AEAD_TAG_LENGTH);
+ return packet_id_size(true) + OPENVPN_MAX_= IV_LENGTH + OPENVPN_MAX_CIPHER_BLOCK_SIZE
+ + max_int(OPENVPN_MAX_HMAC_SIZE, OPENVPN_A= EAD_TAG_LENGTH);
}

stat= ic void
@@ -876,12 +852,13 @@
{
= if (cipher_kt_insecure(ciphername))
{
- msg(M_WARN, "W= ARNING: INSECURE cipher (%s) with block size less than 128"
= + msg(M_WARN,
= + "WARNING: INS= ECURE cipher (%s) with block size less than 128"
= " bit (%d bit). This allows attacks like SWEET32. Mitigate b= y "
"using a --cipher with a larger = block size (e.g. AES-256-CBC). "
"Su= pport for these insecure ciphers will be removed in "
= "OpenVPN 2.7.",
- ciphername, cipher_kt_block_size(ciphername)*8= );
+ ciphe= rname, cipher_kt_block_size(ciphername) * 8);
}=
}

@@ -889,8 +866,8 @@ * Build a struct key_type.
*/
= void
-init_key_type(str= uct key_type *kt, const char *ciphername,
- const char *authname, bool tls_mode, bool= warn)
+init_key_type= (struct key_type *kt, const char *ciphername, const char *authname, bool tl= s_mode,
+ = bool warn)
{
bool aead_cipher =3D f= alse;

@@ -908,12 +885,11 @@

/* check legal cipher mode */
aead_cipher =3D cipher_kt_mode_aead(kt->cipher);

- if (!(cipher_kt_mode_cbc(kt= ->cipher)

- = || (tls_mode && aead_cipher)
+ if (!(cipher_kt_mode_cbc(kt->cipher) || (t= ls_mode && aead_cipher)
#ifdef ENABLE_OFB_CFB_MODE=
|| (tls_mode && cipher_kt_mode_ofb_= cfb(kt->cipher))
#endif
- ))
+ ))
{ msg(M_FATAL, "Cipher '%s' mode not suppor= ted", ciphername);
}
@@ -932,= 9 +908,9 @@
if (warn)
{
msg(M_WARN, "******* WARNING *******: '= ;--cipher none' was specified. "
- "This means NO encryption will be = performed and tunnelled "
- "data WILL be transmitted in clear text over = the network! "
- = "PLEASE DO RECONSIDER THIS SETTING!");
+ "Th= is means NO encryption will be performed and tunnelled "

+ "dat= a WILL be transmitted in clear text over the network! "

+ "PLEA= SE DO RECONSIDER THIS SETTING!");

} }
kt->digest =3D authname;
@@ -959,10 +935,10 @@

if (warn)
{

msg(M_WARN, "******* WARNING= *******: '--auth none' was specified. "
- "This means no authent= ication will be performed on received "
- "packets, meaning you CANNOT tr= ust that the data received by "
- "the remote side have NOT been manipula= ted. "
- = "PLEASE DO RECONSIDER THIS SETTING!");
+ "This means= no authentication will be performed on received "
+ "packets, = meaning you CANNOT trust that the data received by "
+ "the rem= ote side have NOT been manipulated. "
+ "PLEASE DO RECONSIDER T= HIS SETTING!");
}
}
}
@@ -1011,9 +987,8 @@

/* given a key and key_type, build a key_ctx */
void

-init_key_ctx(st= ruct key_ctx *ctx, const struct key_parameters *key,
- const struct key_type *kt, int= enc,
- con= st char *prefix)
+ini= t_key_ctx(struct key_ctx *ctx, const struct key_parameters *key, const stru= ct key_type *kt,
+ = int enc, const char *prefix)
{
= struct gc_arena gc =3D gc_new();
CLEAR(*ctx);
@@ -1024,14 +999,13 @@
cipher_ctx_init= (ctx->cipher, key->cipher, kt->cipher, enc);

const char *ciphername =3D cipher_kt_name(kt->ciph= er);
- msg(D_CIP= HER_INIT, "%s: Cipher '%s' initialized with %d bit key",<= /span>
- prefix, ci= phername, cipher_kt_key_size(kt->cipher) * 8);
+ msg(D_CIPHER_INIT, "%s: Cipher &= #39;%s' initialized with %d bit key", prefix, ciphername,+ cipher_kt_key_si= ze(kt->cipher) * 8);

dmsg(D_S= HOW_KEYS, "%s: CIPHER KEY: %s", prefix,
= format_hex(key->cipher, cipher_kt_key_size(kt->cipher), 0, &= gc));
- dmsg(D_C= RYPTO_DEBUG, "%s: CIPHER block_size=3D%d iv_size=3D%d",- prefix, cipher_kt_= block_size(kt->cipher),
- cipher_kt_iv_size(kt->cipher));
+ dmsg(D_CRYPTO_DEBUG, "%s: CI= PHER block_size=3D%d iv_size=3D%d", prefix,
+ cipher_kt_block_size(kt->ciphe= r), cipher_kt_iv_size(kt->cipher));
warn_insecu= re_key_type(ciphername);
}
@@ -1041,18 +1015,14 @@
ctx->hmac =3D hm= ac_ctx_new();
hmac_ctx_init(ctx->hmac, key->= hmac, kt->digest);

- msg(D_CIPHER_INIT,
- "%s: Using %d bit message hash '= ;%s' for HMAC authentication",
- prefix, md_kt_size(kt->digest) * 8, md_kt_= name(kt->digest));
+ msg(D_CIPHER_INIT, "%s: Using %d bit message hash '%s= 9; for HMAC authentication", prefix,
+ md_kt_size(kt->digest) * 8, md_kt_name= (kt->digest));

dmsg(D_SHOW_KE= YS, "%s: HMAC KEY: %s", prefix,
for= mat_hex(key->hmac, md_kt_size(kt->digest), 0, &gc));

- dmsg(D_C= RYPTO_DEBUG, "%s: HMAC size=3D%d block_size=3D%d",
- prefix,

- md_kt_size(kt->digest= ),

+ dmsg(D_CR= YPTO_DEBUG, "%s: HMAC size=3D%d block_size=3D%d", prefix, md_kt_s= ize(kt->digest),
hmac_ctx_size(ctx->hma= c));
-
= }
ctx->epoch =3D key->epoch;
gc_free(&gc);

@@ -1083,8 +1053,8 @@
}


void
-init_key_ctx_bi(struct key_ctx_bi *ctx, const stru= ct key2 *key2,
- = int key_direction, const struct key_type *kt, const char *name)
+init_key_ctx_bi(struct= key_ctx_bi *ctx, const struct key2 *key2, int key_direction,
+ const struct key_= type *kt, const char *name)

{
struct = key_direction_state kds;

@@ -1174,39 +114= 4,34 @@
struct gc_arena gc =3D gc_new();

CLEAR(*key);
- if (!rand_bytes(key->cipher, cipher_len)
= - || !rand_bytes(key->h= mac, hmac_len))
+ = if (!rand_bytes(key->cipher, cipher_len) || !rand_bytes(key->hmac, hm= ac_len))
{
msg(M_FATAL, "= ;ERROR: Random number generator cannot obtain entropy for key generation&qu= ot;);
}

- dmsg(D_SHOW_KEY_SOURCE, "Cipher source en= tropy: %s", format_hex(key->cipher, cipher_len, 0, &gc));
+ dmsg(D_SHOW_KEY_SOURC= E, "Cipher source entropy: %s",
+ format_hex(key->cipher, cipher_len, 0, &a= mp;gc));
dmsg(D_SHOW_KEY_SOURCE, "HMAC source ent= ropy: %s", format_hex(key->hmac, hmac_len, 0, &gc));
=
gc_free(&gc);
}
static void
-key_print(const struct key *key,
- const struct key_type *kt,
<= span style=3D"color: hsl(0, 100%, 40%);">- const char *prefix)
+key_print(const struct = key *key, const struct key_type *kt, const char *prefix)
{=
struct gc_arena gc =3D gc_new();
- dmsg(D_SHOW_KEY_SOURCE, "%s (ciph= er, %s, %d bits): %s",
- prefix, cipher_kt_name(kt->cipher), cipher_kt_key_size(kt= ->cipher) * 8,
+ = dmsg(D_SHOW_KEY_SOURCE, "%s (cipher, %s, %d bits): %s", prefix,= cipher_kt_name(kt->cipher),
+ cipher_kt_key_size(kt->cipher) * 8,
format_hex(key->cipher, cipher_kt_key_size(kt->cipher), 0,= &gc));

- dmsg(D= _SHOW_KEY_SOURCE, "%s (hmac, %s, %d bits): %s",
- prefix, md_kt_name(kt->dige= st), md_kt_size(kt->digest) * 8,
- format_hex(key->hmac, md_kt_size(kt->digest), = 0, &gc));
+ dm= sg(D_SHOW_KEY_SOURCE, "%s (hmac, %s, %d bits): %s", prefix, md_kt= _name(kt->digest),
+ md_kt_size(kt->digest) * 8, format_hex(key->hmac, md_kt_si= ze(kt->digest), 0, &gc));
gc_free(&gc);
}
/**
* Prints the keys in= a key2 structure.
*/
void
-key2_print(const struct key2 *k,
- const struct = key_type *kt,
- = const char *prefix0,
+key2_print(const struct key2 *k, const struct key_type *kt, const char = *prefix0,
const char *prefix1)
= {
ASSERT(k->n =3D=3D 2);
@@ -1248,= 11 +1213,10 @@
ASSERT(cipher_ctx_iv_length(cip= her) >=3D OPENVPN_AEAD_MIN_IV_LEN);

= /* Generate dummy implicit IV */
- ASSERT(rand_bytes(co->key_ctx_bi.encry= pt.implicit_iv,
- = OPENVPN_MAX_IV_LENGTH));
+ ASSERT(rand_bytes(co->key_ctx_b= i.encrypt.implicit_iv, OPENVPN_MAX_IV_LENGTH));
- memcpy(co->key_c= tx_bi.decrypt.implicit_iv,
- co->key_ctx_bi.encrypt.implicit_iv, OPENVPN_MAX_= IV_LENGTH);
+ = memcpy(co->key_ctx_bi.decrypt.implicit_iv, co->key_ctx_bi.encrypt= .implicit_iv,
+ = OPENVPN_MAX_IV_LENGTH);
}
<= span> }


@@ -1317,11 +1281,9 @@=
}

void
-crypto_read_openvpn_key(const struct key_ty= pe *key_type,
- = struct key_ctx_bi *ctx, const char *key_file,
- bool key_in= line, const int key_direction,

- const char *key_name, const char *opt_name= ,
- = struct key2 *keydata)
+crypto_read_openvpn_key(const struct key_type *key_type, struct key_c= tx_bi *ctx,
+ = const char *key_file, bool key_inline, const int key_direct= ion,
+ = const char *key_name, const char *opt_name, struct key2 *keydata)<= /span>
{
struct key2 key2;
= struct key_direction_state kds;
@@ -1335,7 +1297,8 @@

if (key2.n !=3D 2)
= {
- msg(M_ERR= , "File '%s' does not have OpenVPN Static Key format. Using &= quot;
+ msg(M_= ERR,
+ &qu= ot;File '%s' does not have OpenVPN Static Key format. Using "=
"free-form passphrase file is not suppor= ted anymore.",
print_key_filename(key_fil= e, key_inline));
}
@@ -1374,7 +1337,7 = @@
struct gc_arena gc =3D gc_new();
= struct buffer in;
int size;
- uint8_t hex_byte[3] =3D {0, 0, 0};
+ uint8_t hex_byte[3] = =3D { 0, 0, 0 };

/* parse info */
const unsigned char *cp;
@@ -1384,17 +13= 47,17 @@
int match =3D 0;

= /* output */
- uint8_t *out =3D (uint8_t *) &key2->keys;
+ uint8_t *out =3D (uint8_t *)&key= 2->keys;
const int keylen =3D sizeof(key2->keys)= ;
int count =3D 0;

= /* parse states */
= -#define PARSE_INITIAL 0
-#define PARSE_HEAD 1
-#define PARSE_DATA 2
-#define PARSE_DATA_COMPLETE 3
-#define PARSE_FOOT 4<= br>-#define PARSE_FINISHED = 5
+#define PARSE_INIT= IAL 0
+#define = PARSE_HEAD 1
+#define PARSE_DATA 2
+#define PARSE_DATA_COMPLETE 3
+#define PARSE_FOOT 4
+#define PARSE_FINISHED 5
<= span> int state =3D PARSE_INITIAL;


= /* constants */
@@ -1506,11 +1469,9 @@
= }
else
= {
- = msg(M_FATAL,
- (isprint(c) ? printable_char_fmt : unprintable= _char_fmt),
- = c, line_num,
- print_key_filename(file, flags & RKF_INLIN= E), count,
- = onekeylen, keylen);
+ msg(M_FATAL, (isprint(c) ? printable_char_= fmt : unprintable_char_fmt), c,
+ line_num, print_key_filename(file, flag= s & RKF_INLINE), count, onekeylen,
+ keylen);
= }
}
++l= ine_index;
@@ -1524,22 +1485,21 @@
*/=
key2->n =3D count / onekeylen;

- ASSERT(key2->n &= gt;=3D 0 && key2->n <=3D (int) SIZE(key2->keys));+ ASSERT(key2->n >= =3D 0 && key2->n <=3D (int)SIZE(key2->keys));

if (flags & RKF_MUST_SUCCEED)
{

if (!key2->n)
= {
- msg(M_F= ATAL, "Insufficient key material or header text not found in file '= ;%s' (%d/%d/%d bytes found/min/max)",
- print_key_filename(file, flags &am= p; RKF_INLINE), count, onekeylen,
- keylen);
+ msg(M_FATAL,
+ "Insufficient key material or he= ader text not found in file '%s' (%d/%d/%d bytes found/min/max)&quo= t;,
+ = print_key_filename(file, flags & RKF_INLINE), count, onekeylen, keylen)= ;
}

if = (state !=3D PARSE_FINISHED)
{
= msg(M_FATAL, "Footer text not found in file '%s' (%d/= %d/%d bytes found/min/max)",
- print_key_filename(file, flags & RKF_INLINE= ), count, onekeylen,
- = keylen);
+ print_key_filename(file, flags & RKF_INLINE), count= , onekeylen, keylen);
}
}

@@ -1598,12 +1558,7 @@
= generate_key_random(&key);

= /* format key as ascii */
- fmt =3D format_hex_ex((const uint8_t *)&key,
<= span style=3D"color: hsl(0, 100%, 40%);">- sizeo= f(key),

- = 0,
- = bytes_per_line,
- "\n",
- &gc)= ;

+ fmt =3D fo= rmat_hex_ex((const uint8_t *)&key, sizeof(key), 0, bytes_per_line, &quo= t;\n", &gc);

/* write t= o holding buffer */
buf_printf(&out, "%s\= n", fmt);
@@ -1616,7 +1571,7 @@
b= uf_printf(&out, "%s\n", static_key_foot);

/* write key file to stdout if no filename given */
- if (!filename || strc= mp(filename, "")=3D=3D0)
+ if (!filename || strcmp(filename, "") =3D=3D 0= )
{
printf("%.*s\n"= , BLEN(&out), BPTR(&out));
}
@= @ -1641,9 +1596,14 @@
if (key2->n < n) {
#ifdef ENABLE_SMALL
- msg(M_FATAL, "Key file '%s= 9; used in --%s contains insufficient key material [keys found=3D%d require= d=3D%d]", filename, option, key2->n, n);
+ msg(M_FATAL,
+ "Key file '%s' used = in --%s contains insufficient key material [keys found=3D%d required=3D%d]&= quot;,
+ f= ilename, option, key2->n, n);
#else
- msg(M_FATAL, "Key file '= %s' used in --%s contains insufficient key material [keys found=3D%d re= quired=3D%d] -- try generating a new key file with '" PACKAGE &quo= t; --genkey secret [file]', or use the existing key file in bidirection= al mode by specifying --%s without a key direction parameter", filenam= e, option, key2->n, n, option);
+ msg(M_FATAL,
+ "Key file '%s' used in --%s contai= ns insufficient key material [keys found=3D%d required=3D%d] -- try generat= ing a new key file with '" PACKAGE
+ " --genkey secret [file]', or = use the existing key file in bidirectional mode by specifying --%s without = a key direction parameter",
+ filename, option, key2->n, n, option); #endif
}
}
@= @ -1739,8 +1699,8 @@
/* This should be a very impr= obable failure */
if (!check_key(&key2->key= s[i], kt))
{
- msg(M_FATAL, "Key #%d in '%s' is b= ad. Try making a new key with --genkey.",
- i+1, shared_secret_file);<= br>+ msg(M_FATAL, &q= uot;Key #%d in '%s' is bad. Try making a new key with --genkey.&qu= ot;, i + 1,
+ = shared_secret_file);
}
= }
}
@@ -1767,9 +1727,7 @@
void

print_cipher(const char *ciphername)
{

- printf("= ;%s (%d bit key, ",
- cipher_kt_name(ciphername),
- cipher_kt_key_size(ciphername) * 8);=
+ printf("%s (%d b= it key, ", cipher_kt_name(ciphername), cipher_kt_key_size(ciphername) = * 8);

if (cipher_kt_block_size(ciphe= rname) =3D=3D 1)
{
@@ -1855,14 +1813,1= 3 @@
goto cleanup;
} buf_set_read(&server_key_buf, (void *)&server_key, siz= eof(server_key));
- = if (!crypto_pem_encode(pem_name, &server_key_pem,
- &server_key_= buf, &gc))
+ i= f (!crypto_pem_encode(pem_name, &server_key_pem, &server_key_buf, &= amp;gc))
{
msg(M_WARN, "= ERROR: could not PEM-encode key");
goto clean= up;
}

- if (!filename || strcmp(filename, "")= =3D=3D0)
+ if (!fi= lename || strcmp(filename, "") =3D=3D 0)
{
printf("%.*s", BLEN(&server_key_pem),= BPTR(&server_key_pem));
}
@@ -189= 8,8 +1855,7 @@
}

bool
-read_pem_key_file(struc= t buffer *key, const char *pem_name,
- const char *key_file, bool key_inline)
+read_pem_key_file(struc= t buffer *key, const char *pem_name, const char *key_file, bool key_inline)=
{
bool ret =3D false;
struct buffer key_pem =3D { 0 };

@@ -1910,8 +1866,7 = @@
key_pem =3D buffer_read_from_file(key_file, &am= p;gc);
if (!buf_valid(&key_pem))
{

- = msg(M_WARN, "ERROR: failed to read %s file (%s)",
<= span style=3D"color: hsl(0, 100%, 40%);">- pem_name, key_fil= e);

+ msg(= M_WARN, "ERROR: failed to read %s file (%s)", pem_name, key_file)= ;
goto cleanup;
}
}
@@ -1948,9 +1903,8 @@
= uint8_t out[8];
uint8_t expected_out[] =3D { '= q', 'D', '\xfe', '%', '@', 's',= 'u', '\x95' };

- int ret =3D ssl_tls1_PRF((uint8_t *)seed, (= int) strlen(seed),
- = (uint8_t *)secret, (int) strlen(secret),
= - out, = sizeof(out));
+ in= t ret =3D ssl_tls1_PRF((uint8_t *)seed, (int)strlen(seed), (uint8_t *)secre= t,
+ = (int)strlen(secret), out, sizeof(out));
<= br> return (ret && memcmp(out, expected_out, sizeof(out))= =3D=3D 0);
}
diff --git a/src/openvpn/cry= pto.h b/src/openvpn/crypto.h
index b6f3549..cee4145 100644<= /span>
--- a/src/openvpn/crypto.h
+++ b/src/openvp= n/crypto.h
@@ -129,7 +129,8 @@
#include &q= uot;mtu.h"

/** Wrapper struct to pa= ss around SHA256 digests */
-struct sha256_digest {
+struct sha256_digest
+{
uint8_t digest[SHA256_DIGEST_LENGTH];
};

@@ -138,8 +139,8 @@
*/
struct key_type
{<= br>- const char *cipher; = /**< const name of the cipher */
- const char *digest; /**< Message digest sta= tic parameters */
+ = const char *cipher; /**< const name of the cipher */
+ const char *digest; /**< Messa= ge digest static parameters */
};
=
/**
@@ -158,7 +159,8 @@
/** int= ernal structure similar to struct key that holds key information
= * but is not represented on wire and can be changed/extended=
*/
-struct = key_parameters {
+str= uct key_parameters
+{=
/** %Key material for cipher operations. */ uint8_t cipher[MAX_CIPHER_KEY_LENGTH];
=
@@ -184,10 +186,10 @@
* @param key_params de= stination for the converted struct
* @param key = source of the conversion
*/
-void
-key_parameters_from_key(struct key_parameters *key_params, const st= ruct key *key);
+void= key_parameters_from_key(struct key_parameters *key_params, const struct ke= y *key);

-struct epoch_key {
+struct epoch_key
= +{
uint8_t epoch_key[SHA256_DIGEST_LENGTH];
= uint16_t epoch;
};
@@ -198,8 +2= 00,8 @@
*/
struct key_ctx
{

- cipher_ctx_t = *cipher; /**< Generic cipher %context. */
- hmac_ctx_t *hmac; /**< Generi= c HMAC %context. */
+= cipher_ctx_t *cipher; /**< Generic cipher %context. */
+ hmac_ctx_t *hmac; /**<= Generic HMAC %context. */

/**
*= This implicit IV will be always XORed with the packet id that is sent on
* the wire to get the IV. For the common AEAD ciphers = of AES-GCM and
@@ -213,7 +215,7 @@
*/=
uint8_t implicit_iv[OPENVPN_MAX_IV_LENGTH]; /**< The implicit part of the IV */
- size_t implicit_iv_len; /**< The le= ngth of implicit_iv */
- int n; /**< The number of \c key objects stor= ed
- = * in the \c key2.keys array. */
- struct key keys[2]; /**< Two unidi= rectional sets of %key
= - * material. The first key is the client=
- = * (encrypts) to server (decrypts), the
- * second= the server to client key. */
+ int n; /**< The number of \c key objects stor= ed
+ = * in the \c key2.keys array. */
+ struct key keys[2]; /**< Two unidirectional se= ts of %key
+ = * material. The first key is the client
+ * (encrypt= s) to server (decrypts), the
+ * second the server to client key. */
};

/**
@= @ -255,18 +257,18 @@
*/
struct key_direc= tion_state
{
- int out_key; /**< Index into the \c key2.keys= array for
- = * the sending direction. */
- int in_key; /**< Ind= ex into the \c key2.keys array for
- * the receiving direction. = */
- int need_keys; = /**< The number of key objects necessary
- * to = support both sending and
- *
<= span style=3D"color: hsl(0, 100%, 40%);">- = * This will be 1 if the same keys are

- * used in both directi= ons, or 2 if
- = * there are two sets of unidirectional
= - = * keys. */
+ in= t out_key; /**< Index into the \c key2.keys array for
+ * the sending = direction. */
+ in= t in_key; /**< Index into the \c key2.keys array for
+ * the receivin= g direction. */
+ = int need_keys; /**< The number of key objects necessary
+ * to support b= oth sending and
+ = * receiving.
+ *
+ * This will be 1 if the same keys are
+ * = used in both directions, or 2 if
+ * there are two sets of unidirectional=
+ = * keys. */
};

/**
@@ -276,10 +278,10 @@
*/
s= truct key_ctx_bi
{
- struct key_ctx encrypt; /**< Cipher and/or HMAC co= ntexts for sending
- = * direction. */
- struct key_ctx decrypt; /**< cipher an= d/or HMAC contexts for
= - * receiving direction. */
+ struct key_ctx encrypt; /**&l= t; Cipher and/or HMAC contexts for sending

+ * direction. */
+ struct key_ctx decryp= t; /**< cipher and/or HMAC contexts for
+ * receiving direction= . */
bool initialized;
};
<= span>

@@ -340,54 +342,58 @@
* keep= ing state between successive
* OpenVPN process star= tups. */

-#define CO_PACKET_ID_LONG_FORM (1<<0)
+#define CO_PACKET_ID_LONG_FORM (1 <= ;< 0)
/**< Bit-flag indicating whether to use
- * OpenVPN's lo= ng packet ID format. */
-#define CO_IGNORE_PACKET_ID (1<<1)
+ * OpenVPN's long packet ID format. */=
+#define CO_IGNORE_P= ACKET_ID (1 << 1)
/**< Bit-flag in= dicating whether to ignore
* the packet ID of a rec= eived packet.
* This flag is used during processing=
* of the first packet received from a
* client. */

+#define CO_MUTE_REPLAY_WARNINGS (1 <&= lt; 2)
/**< Bit-flag indicating not to display
* replay warnings. */
-#define CO_USE_TLS_KEY_MATERIAL_EXPORT (1<<3)
+#define CO_USE_TLS_KEY= _MATERIAL_EXPORT (1 << 3)
/**< Bit-flag indic= ating that data channel key derivation
* is done usin= g TLS keying material export [RFC5705]
*/
<= span style=3D"color: hsl(0, 100%, 40%);">-#define CO_RESEND_WKC (1<<4= )

+#define CO_RESEND_= WKC (1 << 4)
/**< Bit-flag i= ndicating that the client is expected to
* resend the= wrapped client key with the 2nd packet (packet-id 1)
= * like with the HARD_RESET_CLIENT_V3 packet */
-#define CO_FORCE_TLSCRYPTV2_COOKIE (1<<5)<= /span>
+#define CO_FORCE_TLS= CRYPTV2_COOKIE (1 << 5)
/**< Bit-flag ind= icating that we do not allow clients that do
* not su= pport resending the wrapped client key (WKc) with the
= * third packet of the three-way handshake */
-#define CO_USE_CC_EXIT_NOTIFY (1<<6)
+#define CO_USE_CC_EXIT= _NOTIFY (1 << 6)
/**< Bit-flag indic= ating that explicit exit notifies should be
* sent vi= a the control channel instead of using an OCC message
= */
-#define CO_USE_DYN= AMIC_TLS_CRYPT (1<<7)
+#define CO_USE_DYNAMIC_TLS_CRYPT (1 << 7)
<= span> /**< Bit-flag indicating that renegotiations are using tls-cry= pt

* with a TLS-EKM derived key.
= */
-#define CO_EPOC= H_DATA_KEY_FORMAT (1<<8)
+#define CO_EPOCH_DATA_KEY_FORMAT (1 << 8) /**< Bit-flag indicating the epoch the data format. This for= mat
* has the AEAD tag at the end of the packet and i= s using a longer
* 64-bit packet id that is split int= o a 16 bit epoch and 48 bit
* epoch counter */

- unsigned int flags; /**< Bit-flags determining b= ehavior of
- = * security operation functions. */
+ unsigned int flags; /**< Bit-= flags determining behavior of
+ * security operation functions. */
};

-#define CRYPT_ERROR_EXIT(flags, format) \
- do { msg(flags, "%s: " forma= t, error_prefix); goto error_exit; } while (false)
+#define CRYPT_ERROR_EXIT(flags, format) = \
+ do = \
+ { \=
+ msg(flags, "%= s: " format, error_prefix); \
+ goto error_exit; \+ } while (false)
#define CRYPT_ERROR(format) CRYPT_ERROR_EXIT(D_CR= YPT_ERRORS, format)
-#d= efine CRYPT_DROP(format) CRYPT_ERROR_EXIT(D_MULTI_DROPPED, format)+#define CRYPT_DROP(format) = CRYPT_ERROR_EXIT(D_MULTI_DROPPED, format)

/**

* Minimal IV length for AEAD mode ciphers (in bytes= ):
@@ -395,8 +401,8 @@
*/
#define OPENVPN_AEAD_MIN_IV_LEN (sizeof(packet_id_type) + 8)


-#define RKF_MUST= _SUCCEED (1<<0)
-= #define RKF_INLINE (1<<1)
+#define RKF_MUST_SUCCEED (1 << 0)
+#define RKF_INLINE (1 << = 1)
void read_key_file(struct key2 *key2, const char *file,= const unsigned int flags);

/**@@ -418,30 +424,26 @@
* more c= iphers than static key mode.
* @param warn Print w= arnings when null cipher / auth is used.
*/
-void init_key_type(struct key_type = *kt, const char *ciphername,

- const char *authname, bool tls_mode, bool warn);<= /span>
+void init_key_type(s= truct key_type *kt, const char *ciphername, const char *authname, bool tls_= mode,
+ = bool warn);

/*
* = Key context functions
*/

-void init_key_ctx(struct key_ctx *ct= x, const struct key_parameters *key,

- const struct key_type *kt, int enc,=
- const char= *prefix);
+void init= _key_ctx(struct key_ctx *ctx, const struct key_parameters *key, const struc= t key_type *kt,
+ = int enc, const char *prefix);

-void

-init_key_bi_ctx_send(struct key_ctx *ctx, const stru= ct key_parameters *key,
- const struct key_type *kt, const char *name);=
+void init_key_bi_ctx_send(= struct key_ctx *ctx, const struct key_parameters *key,
+ const struct k= ey_type *kt, const char *name);

-void
-init_key_bi_ctx_recv(struct key_ctx *ctx, const struct key_param= eters *key,
- = const struct key_type *kt, const char *name);
+void init_key_bi_ctx_recv(struct key_c= tx *ctx, const struct key_parameters *key,
+ const struct key_type *kt,= const char *name);

void free_key_ctx(st= ruct key_ctx *ctx);

-void init_key_ctx_bi(struct key_ctx_bi *ctx, const struct k= ey2 *key2,
- = int key_direction, const struct key_type *kt,
- const char *name);
+void init_key_ctx_bi(= struct key_ctx_bi *ctx, const struct key2 *key2, int key_direction,<= br>+ const = struct key_type *kt, const char *name);

= void free_key_ctx_bi(struct key_ctx_bi *ctx);

<= span>@@ -476,8 +478,7 @@

* contain the processed pack= et ready for sending, or be empty if an
* error occur= red.
*/
-void openvpn_encrypt(struct buffer *buf, struct buffer work,
= - struct cryp= to_options *opt);
+vo= id openvpn_encrypt(struct buffer *buf, struct buffer work, struct crypto_op= tions *opt);


/**
@@ -513,9 +514,8 @@
* the plaintext packet= ready for further processing, or be empty if
* an er= ror occurred.
*/
-bool openvpn_decrypt(struct buffer *buf, struct buffer work,
- st= ruct crypto_options *opt, const struct frame *frame,
- const uint8_t *ad_star= t);
+bool openvpn_dec= rypt(struct buffer *buf, struct buffer work, struct crypto_options *opt,
+ c= onst struct frame *frame, const uint8_t *ad_start);

/** @} name Functions for performing security operations on dat= a channel packets */

@@ -530,11 +530,8 @@=
*
* @return true if packet ID is valid= ated to be not a replay, false otherwise.
*/
-bool crypto_check_replay(struct cr= ypto_options *opt,

- = const struct packet_id_net *pin,
- uint16_t epoch,
- = const char *error_prefix,
- struct gc_arena *gc);
+bool crypto_check_replay(struct crypto_op= tions *opt, const struct packet_id_net *pin,
+ uint16_t epoch, const cha= r *error_prefix, struct gc_arena *gc);

<= /span>
/** Calculate the maximum overhead that our encryption has=
@@ -550,10 +547,8 @@
* = incorrect way as all previous OpenVPN versions did, to
= * end up with identical numbers for OCC compatibilit= y
*/
= -unsigned int
-calculat= e_crypto_overhead(const struct key_type *kt,
- unsigned int pkt_id_size,<= /span>
- = bool occ);
+unsig= ned int calculate_crypto_overhead(const struct key_type *kt, unsigned int p= kt_id_size,
+ = bool occ);

/** Return the worst-case OpenVPN crypto overhead (in bytes) */
unsigned int crypto_max_overhead(void);
@@ -565,8 += 560,7 @@
* @param filename Filename of the serve= r key file to create.
* @param key_name The name= to use in the PEM header/footer.
*/
-void
-write_pem_key_file(const char *filename, const char *key_na= me);
+void write_pem_= key_file(const char *filename, const char *key_name);

/**
* Generate ephermal key material into t= he key structure
@@ -575,8 +569,7 @@
* @p= aram pem_name the name used for logging
* @return = true if key generation was successful
*/
-bool
-generate_ephemeral_key(struct buffer *key, = const char *pem_name);
-bool
-read_pem_key_file(struct = buffer *key, const char *pem_name,
- const char *key_file, bool key_inline);
+bool read_pem_key_file(s= truct buffer *key, const char *pem_name, const char *key_file,
+ bool key_= inline);


/*
* Message = digest-based pseudo random number generator.
@@ -631,16 +62= 3,12 @@
const char *keydirection2ascii(int kd, bool remote= , bool humanreadable);

/* print keys */<= /span>
-void key2_print(const = struct key2 *k,
- = const struct key_type *kt,
- const char *prefix0,
+void key2_print(const struct key2 *k, con= st struct key_type *kt, const char *prefix0,
= const char *prefix1);

-void crypto_read_openvpn_key(const struct key_type *ke= y_type,
- = struct key_ctx_bi *ctx, const char *key_file,
- bool ke= y_inline, const int key_direction,

- const char *key_name, const char = *opt_name,
- = struct key2 *keydata);
+void crypto_read_openvpn_key(const struct key_type *ke= y_type, struct key_ctx_bi *ctx,
+ const char *key_file, bool key_inl= ine, const int key_direction,
+ const char *key_name, const char *op= t_name, struct key2 *keydata);

/*=
* Inline functions
@@ -690,12 +678,12 @@=
if (cipher_defined(kt.cipher) && !cipher_valid(kt.ci= pher))
{
msg(M_WARN, "ER= ROR: --%s requires %s support.", optname, kt.cipher);
- return (struct key_type) { 0 }= ;
+ return (st= ruct key_type){ 0 };
}
if (md_def= ined(kt.digest) && !md_valid(kt.digest))
{
msg(M_WARN, "ERROR: --%s requires %s support.&qu= ot;, optname, kt.digest);
- return (struct key_type) { 0 };
+ return (struct key_type){ 0 };
}


return kt;
@@ -710,8 +698,7 @@

* For reference see the OpenVPN RFC= draft and
* https://www.ietf.org/archive/id/draft-irtf-c= frg-aead-limits-08.html
*/
-uint64_t
-cipher_get_aead_limits(const char *ciphername);
+uint64_t cipher_get_aead_limits(const= char *ciphername);

/**
= * Check if the number of failed decryption is over the acceptable limit.<= /span>
@@ -724,7 +711,7 @@
* but we accept s= lightly lower security bound for the edge
* of Chacha= 20-Poly1305 and packets over 16k as MTUs over 16k are
= * extremely rarely used */
- return ctx->failed_verifications > (1ull << 36);
+ return ctx->fail= ed_verifications > (1ull << 36);
}

/**
@@ -735,7 +722,7 @@
cipher_decrypt_verify_fail_warn(const struct key_ctx *ctx)

{

/* Use 2**35, half the amount after which we ref= use to decrypt */
- = return ctx->failed_verifications > (1ull << 35);
+ return ctx->failed_verific= ations > (1ull << 35);

}
=

@@ -744,7 +731,7 @@
*<= br> * Since cipher_ctx_block_size() is not reliable and will return = 1 in many
* cases use a hardcoded blocksize instead */
-#define AEAD_LIMIT_B= LOCKSIZE 16
+#defi= ne AEAD_LIMIT_BLOCKSIZE 16

/** * Checks if the current TLS library supports the TLS 1.0 PRF with = MD5+SHA1
@@ -761,13 +748,12 @@
* to read.=
*/
static inline bool
-aead_usage_limit_reached(const uint64_t= limit, const struct key_ctx *key_ctx,
- int64_t higest_pid)
+aead_usage_limit_reached(const ui= nt64_t limit, const struct key_ctx *key_ctx, int64_t higest_pid)

= {
/* This is the q + s <=3D p^(1/2) * 2^(1= 29/2) - 1 calculation where
* q is the number of prot= ected messages (highest_pid)
* s Total plaintext leng= th in all messages (in blocks) */
- return (limit > 0 && key_ctx->plaintext_block= s + (uint64_t) higest_pid > limit);
+ return (limit > 0 && key_ctx->plaintex= t_blocks + (uint64_t)higest_pid > limit);
}
<= span>

#endif /* CRYPTO_H */
diff --git a/= src/openvpn/crypto_backend.h b/src/openvpn/crypto_backend.h
index df5bc4d..59418f6 100644

--- a/src/openvpn/crypto_bac= kend.h
+++ b/src/openvpn/crypto_backend.h
@= @ -45,18 +45,20 @@
#define OPENVPN_MAX_CIPHER_BLOCK_SIZE 3= 2

/* Maximum HMAC digest size (bytes) */=
-#define OPENVPN_MAX_H= MAC_SIZE 64
+#defin= e OPENVPN_MAX_HMAC_SIZE 64

/** Types ref= erencing specific message digest hashing algorithms */
-typedef enum {
+typedef enum
+{
MD_SHA1,
M= D_SHA256
} hash_algo_type;

/** Struct used in cipher name translation table */

-typedef struct {
- const char *openvpn_name; /**< Cipher= name used by OpenVPN */
+typedef struct=
+{
+ const char *openvpn_name; /**<= Cipher name used by OpenVPN */
+ const char *lib_name; /**< Cipher name used by crypt= o library */
} cipher_name_pair;
<= br> /** Cipher name translation table */
@@ -122,8 +1= 24,8 @@
*
* @return true iff PEM encode= succeeded.
*/
-bool crypto_pem_encode(const char *name, struct buffer *dst,
- co= nst struct buffer *src, struct gc_arena *gc);
+bool crypto_pem_encode(const char *name, struct b= uffer *dst, const struct buffer *src,
+ struct gc_arena *gc);

/**
* Decode a PEM buffer to binar= y data.
@@ -134,8 +136,7 @@
*
<= span> * @return true iff PEM decode succeeded.

*/=
-bool crypto_pem_decode(const= char *name, struct buffer *dst,
- const struct buffer *src);
+bool crypto_pem_decode(const char = *name, struct buffer *dst, const struct buffer *src);


/*
*
@@ -338,8 +339,8 @@
* @param enc Whether to encrypt or decrypt (eithe= r
* \c OPENVPN_OP_ENCRYPT or \c OPEN= VPN_OP_DECRYPT).
*/
-void cipher_ctx_init(cipher_ctx_t *ctx, const uint8_t *key,=
- = const char *ciphername, crypto_operation_t enc);
+void cipher_ctx_init(cipher_ctx_t *ctx, const = uint8_t *key, const char *ciphername,
+ crypto_operation_t enc);
<= span>

/**
* Returns the size of the IV = used by the cipher, in bytes, or 0 if no IV is
@@ -447,8 +4= 48,7 @@
*
* @return \c 0 o= n failure, \c 1 on success.
*/
-int cipher_ctx_update(cipher_ctx_t *ctx, uint8_t= *dst, int *dst_len,
- = uint8_t *src, int src_len);
+int cipher_ctx_update(cipher_ctx_t *ctx, uint8= _t *dst, int *dst_len, uint8_t *src, int src_len);
=
/**
* Pads the final cipher block using PKCS p= adding, and output to the destination
@@ -475,8 +475,8 @@
*
* @return \c 0 on failure= , \c 1 on success.
*/
-int cipher_ctx_final_check_tag(cipher_ctx_t *ctx, uint8_t= *dst, int *dst_len,
- = uint8_t *tag, size_t tag_len);
+int cipher_ctx_final_check_tag(cip= her_ctx_t *ctx, uint8_t *dst, int *dst_len, uint8_t *tag,

+ size_t= tag_len);


/*@@ -716,7 +716,7 @@
*
* @return= true if successful, false on any error
*/
-bool ssl_tls1_PRF(const= uint8_t *seed, int seed_len, const uint8_t *secret,
- int secret_len, uint8_t *= output, int output_len);
+bool ssl_tls1_PRF(const uint8_t *seed, int seed_len, const uint8_t *se= cret, int secret_len,
+ uint8_t *output, int output_len);

#endif /* CRYPTO_BACKEND_H_ */
diff --git a/s= rc/openvpn/crypto_epoch.c b/src/openvpn/crypto_epoch.c
inde= x 741ad23..b5cbc8d 100644
--- a/src/openvpn/crypto_epoch.c<= /span>
+++ b/src/openvpn/crypto_epoch.c
@@ -39,9 += 39,8 @@
#include "integer.h"

void
-o= vpn_hkdf_expand(const uint8_t *secret,
- const uint8_t *info, int info_len,=
- uint8_t *ou= t, int out_len)
+ovpn= _hkdf_expand(const uint8_t *secret, const uint8_t *info, int info_len, uint= 8_t *out,
+ = int out_len)
{
hmac_ctx_t *hma= c_ctx =3D hmac_ctx_new();
hmac_ctx_init(hmac_ctx, secr= et, "SHA256");
@@ -74,13 +73,10 @@
}


bool
-ovpn_expand_label(const uint8_t *secret, size_t secr= et_len,
- = const uint8_t *label, size_t label_len,
- const uint8_t *context, size_t cont= ext_len,
- = uint8_t *out, uint16_t out_len)
+ovpn_expand_label(const uint8_t *secret, size_t secret_len= , const uint8_t *label, size_t label_len,
+ const uint8_t *context, size_t cont= ext_len, uint8_t *out, uint16_t out_len)
{
- if (secret_len !=3D 32 || label_l= en > 250 || context_len > 255

- || label_len < 1)
+ if (secret_len !=3D 32 || label_len > 250 || = context_len > 255 || label_len < 1)
{
= /* Our current implementation is not a general purpose one
* and assumes that the secret size matches the siz= e of the
@@ -92,7 +88,7 @@
struct gc_a= rena gc =3D gc_new();
/* 2 byte for the outlen encoded= as uint16, 5 bytes for "ovpn ",
* 1 byte f= or context len byte and 1 byte for label len byte */
- const uint8_t *label_prefix =3D (const = uint8_t *) ("ovpn ");
+ const uint8_t *label_prefix =3D (const uint8_t *)("ovp= n ");
int prefix_len =3D 5;

int hkdf_label_len =3D 2 + prefix_len + 1 + label_len + 1= + context_len;
@@ -111,8 +107,7 @@

ASSERT(buf_len(&hkdf_label) =3D=3D hkdf_label_len);

- ovp= n_hkdf_expand(secret, buf_bptr(&hkdf_label),
- buf_len(&hkdf_label), o= ut, out_len);
+ ov= pn_hkdf_expand(secret, buf_bptr(&hkdf_label), buf_len(&hkdf_label),= out, out_len);

gc_free(&gc);
return true;
@@ -133,16 +128,14 @@
const size_t epoch_update_label_len =3D sizeof(epoch_update= _label) - 1;

/* E_N+1 =3D OVPN-Expan= d-Label(E_N, "datakey upd", "", 32) */
- ovpn_expand_label(epoch_key->ep= och_key, sizeof(epoch_key->epoch_key),
- epoch_update_label, epoch_update_= label_len,
- = NULL, 0,
- = new_epoch_key.epoch_key, sizeof(new_epoch_key.epoch_key= ));
+ ovpn_expand_= label(epoch_key->epoch_key, sizeof(epoch_key->epoch_key), epoch_updat= e_label,
+ = epoch_update_label_len, NULL, 0, new_epoch_key.epoch_key,=
+ size= of(new_epoch_key.epoch_key));
*epoch_key =3D new_epoch= _key;
}

void
= -epoch_data_key_derive(struct key= _parameters *key,
- = const struct epoch_key *epoch_key,
+epoch_data_key_derive(struct key_paramete= rs *key, const struct epoch_key *epoch_key,
= const struct key_type *kt)
{
= key->hmac_size =3D cipher_kt_iv_size(kt->cipher);
@@ = -157,19 +150,16 @@
/* length of the array without extr= a \0 byte from the string */
const size_t epoch_data_k= ey_label_len =3D sizeof(epoch_data_key_label) - 1;
=
- ovpn_expand_label(epoch_= key->epoch_key, sizeof(epoch_key->epoch_key),
- epoch_data_key_label,= epoch_data_key_label_len,
- NULL, 0,
- (uint8_t *)(&key->cipher), key-&= gt;cipher_size);
+ = ovpn_expand_label(epoch_key->epoch_key, sizeof(epoch_key->epoch_key)= , epoch_data_key_label,
+ epoch_data_key_label_len, NULL, 0, (uint8_t *)(&a= mp;key->cipher),
+= key->cipher_size);

const uint8_t epoch_data_iv_label[] =3D "data_iv";
=
/* length of the array without extra \0 byte from the string= */
const size_t epoch_data_iv_label_len =3D sizeof(ep= och_data_iv_label) - 1;

- ovpn_expand_label(epoch_key->epoch_key, sizeof(e= poch_key->epoch_key),
- NULL= , 0,
- = (uint8_t *)(&key->hmac), key->hmac_size);
+ ovpn_expand_label(epoch_key->ep= och_key, sizeof(epoch_key->epoch_key), epoch_data_iv_label,
+ epoch_data= _iv_label_len, NULL, 0, (uint8_t *)(&key->hmac), key->hmac_size);=

key->epoch =3D epoch_key->epoch;
}


@@ -187,8 +177,7 @@
=
epoch_data_key_derive(&send_key, &co->epo= ch_key_send, &co->epoch_key_type);

- init_key_bi_ctx_send(&co->= key_ctx_bi.encrypt, &send_key,

- &co->epoch_key_type, name);
+ init_key_bi_ctx_se= nd(&co->key_ctx_bi.encrypt, &send_key, &co->epoch_key_typ= e, name);
reset_packet_id_send(&co->packet_id.s= end);
CLEAR(send_key);
}
@@ -219,10 +208,10 @@

/* Either we have not genera= ted any future keys yet (first initialisation)
* or t= he last index is the same as our current epoch key
* = (last generated receive epoch key should match the epoch key) */
= - struct key_ctx *highest_futu= re_key =3D &co->epoch_data_keys_future[co->epoch_data_keys_future= _count - 1];
+ str= uct key_ctx *highest_future_key =3D
+ &co->epoch_data_keys_future[co->epoch_dat= a_keys_future_count - 1];

- ASSERT(co->epoch_key_recv.epoch =3D=3D 1
- || highest_futur= e_key->epoch =3D=3D co->epoch_key_recv.epoch);
+ ASSERT(co->epoch_key_recv.epoch = =3D=3D 1 || highest_future_key->epoch =3D=3D co->epoch_key_recv.epoch= );

/* free the keys that are not use= d anymore */
for (uint16_t i =3D 0; i < co->epoc= h_data_keys_future_count; i++)
@@ -250,12 +239,12 @@=
{
ASSERT(co->epoch_data_keys_fut= ure[i].epoch =3D=3D 0);
}
- memmove(co->epoch_data_keys_future,<= br>- co->epoch_data= _keys_future + num_keys_generate,
+ memmove(co->epoch_data_keys_future, co->epoch_data_= keys_future + num_keys_generate,
(co->epoch= _data_keys_future_count - num_keys_generate) * sizeof(struct key_ctx));

/* Clear and regenerate the array eleme= nts at the end */
- = for (uint16_t i =3D co->epoch_data_keys_future_count - num_keys_generate= ; i < co->epoch_data_keys_future_count; i++)
+ for (uint16_t i =3D co->epoch_data_ke= ys_future_count - num_keys_generate;
+ i < co->epoch_data_keys_future_count; i++)<= /span>
{
CLEAR(co->epoch_data_key= s_future[i]);
epoch_key_iterate(&co->epoch_= key_recv);
@@ -280,8 +269,7 @@
}
void
-epoch_replace_update_recv_key(struct crypto_options *co,- u= int16_t new_epoch)
+e= poch_replace_update_recv_key(struct crypto_options *co, uint16_t new_epoch)=
{
/* Find the key of the new epoch i= n future keys */
uint16_t fki;
@@ -350= ,8 +338,7 @@

void
epoch= _init_key_ctx(struct crypto_options *co, const struct key_type *key_type,
- cons= t struct epoch_key *e1_send,
- const struct epoch_key *e1_recv,
+ const struct epoc= h_key *e1_send, const struct epoch_key *e1_recv,
= uint16_t future_key_count)
{
= ASSERT(e1_send->epoch =3D=3D 1 && e1_recv->epoch =3D=3D 1);=
@@ -441,11 +428,9 @@
* decryptio= n fail warn limit.
* */
= else if (opt->key_ctx_bi.encrypt.epoch =3D=3D opt->key_ctx_bi.decrypt= .epoch
- = && (aead_usage_limit_reached(opt->aead_usage_limit,
= - = &opt->key_ctx_bi.decrypt,
+ && (aead_usage_limit_re= ached(opt->aead_usage_limit, &opt->key_ctx_bi.decrypt,
= opt->packet_id.rec.= id)
- = || cipher_decrypt_verify_fail_warn(&opt->key_ctx_bi.decrypt)
- ))
+ |= | cipher_decrypt_verify_fail_warn(&opt->key_ctx_bi.decrypt)))=
{
/* Receive key limit reac= hed. Increase our own send key to signal
* th= at we want to use a new epoch. Peer should then also move its
@@ -458,5 +443,4 @@

{
epoc= h_iterate_send_key(opt);
}
-
}
diff --git a/= src/openvpn/crypto_epoch.h b/src/openvpn/crypto_epoch.h
ind= ex ff5974e..33ca741 100644
--- a/src/openvpn/crypto_epoch.h=
+++ b/src/openvpn/crypto_epoch.h
@@ -38,10= +38,8 @@
* @param out output keying material
* @param out_len length of output keying material
= */
-void=
-ovpn_hkdf_expand(const uint8= _t *secret,
- = const uint8_t *info, int info_len,
- uint8_t *out, int out_len);
= +void ovpn_hkdf_expand(const ui= nt8_t *secret, const uint8_t *info, int info_len, uint8_t *out,
<= span style=3D"color: hsl(120, 100%, 40%);">+ int out_l= en);


/**
* Variant of = the RFC 8446 TLS 1.3 HKDF-Expand-Label function with the
@= @ -60,11 +58,9 @@
* @param out_len length of output keyi= ng material
* @return
*/
-bool

-ovpn_expand_label(const uint8_t *secret, size_t secre= t_len,
- = const uint8_t *label, size_t label_len,
- const uint8_t *context, size_t conte= xt_len,
- = uint8_t *out, uint16_t out_len);
+bool ovpn_expand_label(const uint8_t *secret, size_t secre= t_len, const uint8_t *label,
+ size_t label_len, const uint8_t *context, s= ize_t context_len, uint8_t *out,
+ uint16_t out_len);

/**
* Generate a data channel key pair fro= m the epoch key
@@ -72,10 +68,8 @@
* @par= am epoch_key Epoch key to be used
* @param kt = Cipher information to generate the data channel key for
*/

-void
<= span style=3D"color: hsl(0, 100%, 40%);">-epoch_data_key_derive(struct key_= parameters *key,

- = const struct epoch_key *epoch_key,
- const struct key_type= *kt);
+void epoch_da= ta_key_derive(struct key_parameters *key, const struct epoch_key *epoch_key= ,
+ = const struct key_type *kt);

/**=
* Generates and fills the epoch_data_keys_future with ne= xt valid
@@ -90,8 +84,7 @@
* free the one= s that are older than the crypto_options.key_ctx_bi.decrypt and
<= span> * generate the keys from the newer epoch.

*/
-void
-epoch_generate_future_receive_keys(struct c= rypto_options *co);
+= void epoch_generate_future_receive_keys(struct crypto_options *co);<= br>

/** This is called when the p= eer uses a new send key that is not the default
@@ -102,21 = +95,17 @@
* @param co crypto_options to update
* @param new_epoch the new epoch to use for the receive key<= /span>
*/
-v= oid
-epoch_replace_upda= te_recv_key(struct crypto_options *co,
- uint16_t new_epoch);<= br>+void epoch_replace_update_r= ecv_key(struct crypto_options *co, uint16_t new_epoch);

/**
* Updates the send key and send_epoch= _key in cryptio_options->key_ctx_bi to
* use the next = epoch */
-void-epoch_iterate_send_key(struct = crypto_options *co);
= +void epoch_iterate_send_key(struct crypto_options *co);
<= /span>
/**
* Frees the extra data structures us= ed by epoch keys in \c crypto_options
*/
-void
-free_epoch_key_ctx(struct crypto_options *co);+void free_epoch_key_ctx(stru= ct crypto_options *co);

/**
* Initialises data channel keys and internal structures for epoch dat= a keys

@@ -131,10 +120,9 @@
* @param futu= re_key_count the number of future epoch keys that should be
* considered valid when receiving data from th= e peer

*/
-void
-epoch_init_= key_ctx(struct crypto_options *co, const struct key_type *key_type,<= br>- const stru= ct epoch_key *e1_send, const struct epoch_key *e1_recv,
- uint16_t future_key_co= unt);
+void epoch_ini= t_key_ctx(struct crypto_options *co, const struct key_type *key_type,
+ c= onst struct epoch_key *e1_send, const struct epoch_key *e1_recv,
= + uint16= _t future_key_count);

/**
* Using an epoch, this function will try to retrieve a decryption
@@ -143,8 +131,7 @@
* @param epoch epoch o= f the key to lookup
* @return the key context wi= th
*/
-struct key_ctx *
-epo= ch_lookup_decrypt_key(struct crypto_options *opt, uint16_t epoch);+struct key_ctx *epoch_lookup= _decrypt_key(struct crypto_options *opt, uint16_t epoch);
=
/**
* Checks if we need to iterate the = send epoch key. This needs to be in one
@@ -153,8 +140,7 @@=
* - send key aead usage limit reached (for AES-GCM and = similar ciphers)
* - recv key usage limit reached=
*/
-void
-epoch_check_send_iterate= (struct crypto_options *opt);
+void epoch_check_send_iterate(struct crypto_options *opt);=


#endif /* ifndef CRYPTO_EPOC= H_H */
diff --git a/src/openvpn/crypto_mbedtls.c b/src/open= vpn/crypto_mbedtls.c
index 0950f6b..86317dd 100644--- a/src/openvpn/crypto_mbedtls.c
+++ b/src/openvp= n/crypto_mbedtls.c
@@ -65,7 +65,7 @@
crypt= o_init_lib_engine(const char *engine_name)
{
msg(M_WARN, "Note: mbed TLS hardware crypto engine functionali= ty is not "

- = "available");
+ "available");
}
provider_t *
@@ -123,8 +123,7 @@<= /span>
}

bool
-mbed_log_func_line(unsigned int flags,= int errval, const char *func,
- int line)
+mbed_log_func_line(unsigned int flags, int errval, const = char *func, int line)
{
char prefix[2= 56];

@@ -203,8 +202,8 @@
= const int *digests =3D mbedtls_md_list();

= #ifndef ENABLE_SMALL
- printf("The following message digests are available for use = with\n"
- = PACKAGE_NAME ". A message digest is used in conjunction with\n"= ;
+ printf("T= he following message digests are available for use with\n" PACKAGE_NAM= E
+ ".= A message digest is used in conjunction with\n"
= "the HMAC function, to authenticate received packets.\n"<= /span>
"You can specify a message digest as param= eter to\n"
"the --auth option.\n\n&qu= ot;);
@@ -232,12 +231,12 @@
}

bool
-crypto_pem_encode(const char *name, struct buffer *dst,
- const struct buff= er *src, struct gc_arena *gc)

+crypto_pem_encode(const char *name, struct buffer *dst, const str= uct buffer *src,
+ = struct gc_arena *gc)
{
= /* 1000 chars is the PEM line length limit (+1 for tailing NUL) */<= br>- char header[1000+1] =3D {= 0 };
- char footer[= 1000+1] =3D { 0 };
+ = char header[1000 + 1] =3D { 0 };
+ char footer[1000 + 1] =3D { 0 };

if (!snprintf(header, sizeof(header), "-----BEGIN %s-= ----\n", name))
{
@@ -249,9 +248,= 8 @@
}

size_t o= ut_len =3D 0;
- if (= MBEDTLS_ERR_BASE64_BUFFER_TOO_SMALL !=3D
- mbedtls_pem_write_buffer(header, footer, BPTR(sr= c), BLEN(src),
- = NULL, 0, &out_len))
+ if (MBEDTLS_ERR_BASE64_BUFFER_TOO_SMALL
+ !=3D mbedtls_= pem_write_buffer(header, footer, BPTR(src), BLEN(src), NULL, 0, &out_le= n))
{
return false; }
@@ -259,9 +257,9 @@
/* W= e set the size buf to out_len-1 to NOT include the 0 byte that
* mbedtls_pem_write_buffer in its length calculation */
*dst =3D alloc_buf_gc(out_len, gc);
- if (!mbed_ok(mbedtls_pem_write_buffer(header,= footer, BPTR(src), BLEN(src),
- BPTR(dst), BCAP(dst), &a= mp;out_len))
- |= | !buf_inc_len(dst, out_len-1))
+ if (!mbed_ok(mbedtls_pem_write_buffer(header, footer, BPTR(= src), BLEN(src), BPTR(dst),
+ BCAP(dst), &out_len))=
+ || !buf_inc= _len(dst, out_len - 1))
{
CLE= AR(*dst);
return false;
@@ -271,12= +269,11 @@
}

bool
-crypto_pem_decode(const ch= ar *name, struct buffer *dst,
- const struct buffer *src)
+crypto_pem_decode(const char *name, struc= t buffer *dst, const struct buffer *src)
{
/* 1000 chars is the PEM line length limit (+1 for tailing NUL) */
- char header[1000+1] = =3D { 0 };
- char fo= oter[1000+1] =3D { 0 };
+ char header[1000 + 1] =3D { 0 };
+ char footer[1000 + 1] =3D { 0 };
=
if (!snprintf(header, sizeof(header), "-----BEGI= N %s-----", name))
{
@@ -296,8 +2= 93,8 @@

size_t use_len =3D 0;=
mbedtls_pem_context ctx =3D { 0 };
- bool ret =3D mbed_ok(mbedtls_pem_read_buffe= r(&ctx, header, footer, BPTR(&input),
- NULL= , 0, &use_len));
= + bool ret =3D
+ = mbed_ok(mbedtls_pem_read_buffer(&ctx, header, footer, BPTR(&i= nput), NULL, 0, &use_len));
size_t buf_size =3D 0;=
const unsigned char *buf =3D mbedtls_pem_get_buffer(&= amp;ctx, &buf_size);
if (ret && !buf_write= (dst, buf, buf_size))
@@ -327,8 +324,8 @@
= mbedtls_ctr_drbg_context *
rand_ctx_get(void)
{

- static mbed= tls_entropy_context ec =3D {0};
- static mbedtls_ctr_drbg_context cd_ctx =3D {0};
+ static mbedtls_entropy_contex= t ec =3D { 0 };

+ = static mbedtls_ctr_drbg_context cd_ctx =3D { 0 };
stat= ic bool rand_initialised =3D false;

= if (!rand_initialised)
@@ -341,14 +338,15 @@
* 800-90 section 8.7.1). We have very little information at thi= s stage.

* Include Program Name, memory address o= f the context and PID.
*/
- buf_printf(&pers_string, "= OpenVPN %0u %p %s", platform_getpid(), &cd_ctx, time_string(0, 0, = 0, &gc));
+ = buf_printf(&pers_string, "OpenVPN %0u %p %s", platform_getp= id(), &cd_ctx,
+ = time_string(0, 0, 0, &gc));
<= br> /* Initialise mbed TLS RNG, and built-in entropy sources = */
mbedtls_entropy_init(&ec);
=
mbedtls_ctr_drbg_init(&cd_ctx);
- if (!mbed_ok(mbedtls_ctr_d= rbg_seed(&cd_ctx, mbedtls_entropy_func, &ec,

- = BPTR(&pers_string), BLEN(&pers_string))))
+ if (!mbed_ok(mbedtls_ctr_drbg_seed(&a= mp;cd_ctx, mbedtls_entropy_func, &ec, BPTR(&pers_string),+ = BLEN(&pers_string))))
{ msg(M_FATAL, "Failed to initialize random generat= or");
}
@@ -421,12 +419,14 @@=
return false;
}

- const size_t= key_bytelen =3D mbedtls_cipher_info_get_key_bitlen(cipher)/8;
+ const size_t key_bytelen =3D= mbedtls_cipher_info_get_key_bitlen(cipher) / 8;

if (k= ey_bytelen > MAX_CIPHER_KEY_LENGTH)
{
- msg(D_LOW, "Cipher alg= orithm '%s' uses a default key size (%zu bytes) "

+ msg(D_LOW,

+ "Cipher algorith= m '%s' uses a default key size (%zu bytes) "

= "which is larger than " PACKAGE_NAME "'s cur= rent maximum key size "
- "(%d bytes)", ciphername, key_bytelen, MAX_CIP= HER_KEY_LENGTH);
+ = "(%d bytes)",
+ ciphername, key_bytelen, MAX_CIPHER_KEY_LENGTH);
*reason =3D "disabled due to key size too larg= e";
return false;
}
@@ -457,7 +457,7 @@
return 0; }

- return (int)mbedtls_cipher_info_get_key_bitlen(cipher_kt)/8;=
+ return (int)mbe= dtls_cipher_info_get_key_bitlen(cipher_kt) / 8;
}
int
@@ -506,7 +506,7 @@ #ifdef MBEDTLS_CHACHAPOLY_C
|| mbedt= ls_cipher_info_get_type(cipher_kt) =3D=3D MBEDTLS_CIPHER_CHACHA20_POLY1305<= /span>
#endif
- );
+ = );
}

static mbedtls_c= ipher_mode_t
@@ -527,19 +527,21 @@
cipher_= kt_mode_ofb_cfb(const char *ciphername)
{
= const mbedtls_cipher_info_t *cipher =3D cipher_get(ciphername);=
- return cipher &&= (cipher_kt_mode(cipher) =3D=3D OPENVPN_MODE_OFB
- || cipher_kt_mode(cipher) = =3D=3D OPENVPN_MODE_CFB);
+ return cipher
+ && (cipher_kt_mode(cipher) =3D=3D OPENVPN_MODE_OFB
+ || cip= her_kt_mode(cipher) =3D=3D OPENVPN_MODE_CFB);
}
=
bool
cipher_kt_mode_aead(const ch= ar *ciphername)
{
const mbedtls_ciphe= r_info_t *cipher =3D cipher_get(ciphername);
- return cipher && (cipher_kt_mode(cipher)= =3D=3D OPENVPN_MODE_GCM
+ return cipher
- || cipher_kt_mode(cipher) =3D=3D= MBEDTLS_MODE_CHACHAPOLY
+ || cipher_kt_mode(cipher) =3D=3D MBEDTLS_MODE_CHACHAPOL= Y
#endif
- );
+ );
}


@@ -565,8 +567,8 @@
}
=
void
= -cipher_ctx_init(mbedtls_cipher_context_t *ctx, const uint8_t *key,<= br>- const char *c= iphername, crypto_operation_t enc)
+cipher_ctx_init(mbedtls_cipher_context_t *ctx, const uint8_t= *key, const char *ciphername,
+ crypto_operation_t enc)
{
ASSERT(NULL !=3D ciphername && NULL !=3D ctx);
CLEAR(*ctx);
@@ -611,7 +613,7 @@ return 0;
}
- if (!mbed_ok(mbedtls_ciphe= r_write_tag(ctx, (unsigned char *) tag, tag_len)))
+ if (!mbed_ok(mbedtls_cipher_write_tag(ct= x, (unsigned char *)tag, tag_len)))
{
= return 0;
}
@@ -643,18 +645,2= 0 @@
bool
cipher_ctx_mode_ofb_cfb(const c= ipher_ctx_t *ctx)
{
- return ctx && (cipher_ctx_mode(ctx) =3D=3D OPENV= PN_MODE_OFB
- = || cipher_ctx_mode(ctx) =3D=3D OPENVPN_MODE_CFB);
+ return ctx
+ && (cipher_ctx_mode(ct= x) =3D=3D OPENVPN_MODE_OFB
+ || cipher_ctx_mode(ctx) =3D=3D OPENVPN_MODE_CFB);
}

bool
ci= pher_ctx_mode_aead(const cipher_ctx_t *ctx)
{
- return ctx && (cipher_= ctx_mode(ctx) =3D=3D OPENVPN_MODE_GCM

+ return ctx
+ && (cipher_ctx_mode(ctx) =3D=3D OPENVPN_MOD= E_GCM
#ifdef MBEDTLS_CHACHAPOLY_C
- || cipher_ctx_mode(ctx) =3D= =3D MBEDTLS_MODE_CHACHAPOLY
+ || cipher_ctx_mode(ctx) =3D=3D MBEDTLS_MODE_CHACHAPO= LY
#endif
- );
+ );
}

= int
@@ -690,13 +694,12 @@
}

int
- int *dst_len,= uint8_t *src, int src_len)
+cipher_ctx_update(mbedtls_cipher_context_t *ctx, uint8_t *dst, int = *dst_len, uint8_t *src,
+ int src_len)
{
= size_t s_dst_len =3D *dst_len;

- if (!mbed_ok(mbedtls_cipher_update(ctx, src,= (size_t) src_len, dst,
- &s_dst_len)))
+ if (!mbed_ok(mbedtls_cipher_upda= te(ctx, src, (size_t)src_len, dst, &s_dst_len)))
{=
return 0;
}
= @@ -722,8 +725,8 @@
}

i= nt
-cipher_ctx_final_ch= eck_tag(mbedtls_cipher_context_t *ctx, uint8_t *dst,
- int *dst_len, ui= nt8_t *tag, size_t tag_len)
+cipher_ctx_final_check_tag(mbedtls_cipher_context_t *ctx, uint8_t *= dst, int *dst_len, uint8_t *tag,
+ size_t tag_len)
{<= /span>
size_t olen =3D 0;

@= @ -749,8 +752,7 @@
}
*dst_len =3D= olen;

- = tag_len)))
+ if (!mbed_ok(mbedtls_cipher_check_tag(ctx, (const unsign= ed char *)tag, tag_len)))
{
r= eturn 0;
}
@@ -759,7 +761,6 @@<= br> }


-
/*
* * Generic message digest information functions
@@= -780,10 +781,10 @@
}
if (mbedtls= _md_get_size(md) > MAX_HMAC_KEY_LENGTH)
{- msg(M_FATAL, "Mess= age hash algorithm '%s' uses a default hash size (%d bytes) which i= s larger than " PACKAGE_NAME "'s current maximum hash size (%= d bytes)",
- = digest,
- = mbedtls_md_get_size(md),
- MAX_HMAC_KEY_LENGTH);
+ msg(M_FATAL,
+ "Message hash algorithm '%s'= uses a default hash size (%d bytes) which is larger than " PACKAGE_NA= ME
+ "= ;'s current maximum hash size (%d bytes)",
+ digest, mbedtls_md_get_size(m= d), MAX_HMAC_KEY_LENGTH);
}
retur= n md;
}
@@ -791,7 +792,7 @@
bool

md_valid(const char *digest)
{
- const mbedtls_md_inf= o_t *md =3D mbedtls_md_info_from_string(digest);
+ const mbedtls_md_info_t *md =3D mbedtls_m= d_info_from_string(digest);
return md !=3D NULL;
}

@@ -966,8 +967,8 @@<= br> * via its APIs like OpenSSL does with CRYPTO_memcmp * Adapt the function that mbedtls itself uses in
* mbedtls_safer_memcmp as it considers that to be safe */
<= br>- volatile const unsigned c= har *A =3D (volatile const unsigned char *) a;
- volatile const unsigned char *B =3D (volatile = const unsigned char *) b;
+ volatile const unsigned char *A =3D (volatile const unsigned char= *)a;
+ volatile c= onst unsigned char *B =3D (volatile const unsigned char *)b;
volatile unsigned char diff =3D 0;


for (size_t i =3D 0; i < size; i++)

@@ -982,12 +98= 3,11 @@
* from recent versions, so we use our own impleme= ntation if necessary. */
#if defined(HAVE_MBEDTLS_SSL_TLS_= PRF) && defined(MBEDTLS_SSL_TLS_PRF_TLS1)
bool
-ssl_tls1_PRF(const uint8_= t *seed, int seed_len, const uint8_t *secret,
- int secret_len, uint8_t *output, int o= utput_len)
+ssl_tls1_= PRF(const uint8_t *seed, int seed_len, const uint8_t *secret, int secret_le= n,
+ uint= 8_t *output, int output_len)
{
- return mbed_ok(mbedtls_ssl_tls_prf(MBEDTLS_SS= L_TLS_PRF_TLS1, secret,
- secret_len, "", seed, se= ed_len, output,
- = output_len));
+ return mbed_ok(mbedtls_ssl_tls_prf(MBEDTLS_S= SL_TLS_PRF_TLS1, secret, secret_len, "", seed,
+ = seed_len, output, output_len));
}
#else = /* defined(HAVE_MBEDTLS_SSL_TLS_PRF) && defined(MBEDTLS_SSL_TLS_PRF= _TLS1) */
/*
@@ -1002,8 +1002,8 @@<= br> * @param olen Length of the output buffer
*/

static void
-tls1_P_hash(const mbedtls_md_info_t *md_kt, const uint8_t *s= ec, int sec_len,
- = const uint8_t *seed, int seed_len, uint8_t *out, int olen)+tls1_P_hash(const mbedtls_md_= info_t *md_kt, const uint8_t *sec, int sec_len, const uint8_t *seed,=
+ int seed_len, = uint8_t *out, int olen)
{
struct gc_a= rena gc =3D gc_new();
uint8_t A1[MAX_HMAC_KEY_LENGTH];=
@@ -1037,7 +1037,7 @@
hmac_ctx_update= (ctx, seed, seed_len);
hmac_ctx_final(ctx, A1);=

- for (;= ; )
+ for (;;)
{
hmac_ctx_reset(ctx); hmac_ctx_reset(ctx_tmp);
@@ -1052,7 +1052,7= @@
olen -=3D chunk;
= hmac_ctx_final(ctx_tmp, A1); /* calc the next A1 value */
}

- = else /* last one */
-ssl_tls1_PRF(const uint8_t *label, int label_len, = const uint8_t *sec,
- = int slen, uint8_t *out1, int olen)
+ssl_tls1_PRF(const uint8_t *label, int label_len,= const uint8_t *sec, int slen, uint8_t *out1,
+ int olen)
{<= br> struct gc_arena gc =3D gc_new();
const m= d_kt_t *md5 =3D md_get("MD5");
@@ -1098,15 +1098,= 15 @@

uint8_t *out2 =3D (uint8_t *)g= c_malloc(olen, false, &gc);

- int len =3D slen/2;
+ int len =3D slen / 2;
const uint8_t *S1 =3D sec;

const uint8_t *S2 =3D= &(sec[len]);
- = len +=3D (slen&1); /* add for odd, make longer */
+ len +=3D (slen & 1); /* add for o= dd, make longer */

tls1_P_hash(md5, = S1, len, label, label_len, out1, olen);
tls1_P_hash(sh= a1, S2, len, label, label_len, out2, olen);

- for (int i =3D 0; i<olen; i+= +)

+ for (int i = =3D 0; i < olen; i++)
{
ou= t1[i] ^=3D out2[i];
}
diff --git a/src= /openvpn/crypto_mbedtls.h b/src/openvpn/crypto_mbedtls.h
in= dex 620732e..80f1d16 100644
--- a/src/openvpn/crypto_mbedtl= s.h
+++ b/src/openvpn/crypto_mbedtls.h
@@ -= 50,32 +50,32 @@
typedef void provider_t;
=
/** Maximum length of an IV */
-#define OPENVPN_MAX_IV_LENGTH MBEDTLS_MAX_IV_L= ENGTH
+#define OPENVP= N_MAX_IV_LENGTH MBEDTLS_MAX_IV_LENGTH

/*= * Cipher is in CBC mode */
-#define OPENVPN_MODE_CBC MBEDTLS_MODE_CBC
+#define OPENVPN_MODE_CBC MBEDTLS_MODE_CBC=

/** Cipher is in OFB mode */
= -#define OPENVPN_MODE_OFB = MBEDTLS_MODE_OFB
+#de= fine OPENVPN_MODE_OFB MBEDTLS_MODE_OFB

/= ** Cipher is in CFB mode */
-#define OPENVPN_MODE_CFB MBEDTLS_MODE_CFB
+#define OPENVPN_MODE_CFB MBEDTLS_MODE_CF= B

/** Cipher is in GCM mode */-#define OPENVPN_MODE_GCM = MBEDTLS_MODE_GCM
+#d= efine OPENVPN_MODE_GCM MBEDTLS_MODE_GCM

= typedef mbedtls_operation_t crypto_operation_t;
/** Cipher should encrypt */
-#define OPENVPN_OP_ENCRYPT MBEDTLS_ENCRYPT
+#define OPENVPN_OP_ENCRYPT MBEDT= LS_ENCRYPT


/** Cipher should decrypt */<= /span>
-#define OPENVPN_OP_DEC= RYPT MBEDTLS_DECRYPT
+#define OPENVPN_OP_DECRYPT MBEDTLS_DECRYPT
-#define MD4_DIGEST_LENGTH = 16
-#define MD5_DIGES= T_LENGTH 16
-#def= ine SHA_DIGEST_LENGTH 20
-#define SHA256_DIGEST_LENGTH 32
+#define MD4_DIGEST_LENGTH 16
+#define MD5_DIGEST_LENGTH 16<= br>+#define SHA_DIGEST_LENGTH = 20
+#define SHA256_= DIGEST_LENGTH 32

/**
*= Returns a singleton instance of the mbed TLS random number generator.
@@ -118,13 +118,11 @@
*
* @= returns true if no errors are detected, false otherwise.
= */
-bool mbed_log_func_= line(unsigned int flags, int errval, const char *func,
- int line);<= br>+bool mbed_log_func_line(uns= igned int flags, int errval, const char *func, int line);
=
/** Wraps mbed_log_func_line() to prevent function calls = for non-errors */
static inline bool
-mbed_log_func_line_lite(unsigned int flags,= int errval,
- = const char *func, int line)
+mbed_log_func_line_lite(unsigned int flags, int errv= al, const char *func, int line)
{
if = (errval)
{
@@ -145,7 +143,6 @@<= br> *
* @returns true if no errors are detected, f= alse otherwise.
*/
-#define mbed_ok(errval) \
- mbed_log_func_line_lite(D_CRYPT_ERRORS, errval, __fu= nc__, __LINE__)
+#def= ine mbed_ok(errval) mbed_log_func_line_lite(D_CRYPT_ERRORS, errval, __func_= _, __LINE__)

#endif /* CRYPTO_MBEDTLS_H_= */
diff --git a/src/openvpn/crypto_openssl.c b/src/openvpn= /crypto_openssl.c
index 2e7bd63..cfea3eb 100644
<= span>--- a/src/openvpn/crypto_openssl.c

+++ b/src/openvpn/c= rypto_openssl.c
@@ -63,7 +63,7 @@
<= br> #ifdef _MSC_VER
/* mute ossl3 deprecation warnin= gs treated as errors in msvc */
-#pragma warning(disable: 4996)
+#pragma warning(disable : 4996)
#endi= f

/*
@@ -118,22 +118,17 = @@
ENGINE_register_all_complete();
<= span> return NULL;

}
- if ((e =3D ENGINE_by_id(engine)= ) =3D=3D NULL
- = && (e =3D try_load_engine(engine)) =3D=3D NULL)
+ if ((e =3D ENGINE_by_id(eng= ine)) =3D=3D NULL && (e =3D try_load_engine(engine)) =3D=3D NULL)
{
- crypto_msg(M_FATAL, "OpenSSL error: cannot load engine= '%s'",
- = engine);
+ crypto_msg(M_FATAL, "OpenSSL error: cannot load= engine '%s'", engine);
}
<= span>

if (!ENGINE_set_default(e, ENGINE_METHOD_AL= L))
{
- crypto_msg(M_FATAL,
- "OpenSSL error: ENGINE_set_d= efault failed on engine '%s'",
- engine);
+ crypto_msg(M_FATAL, "Ope= nSSL error: ENGINE_set_default failed on engine '%s'", engine)= ;
}

- msg(M_INFO, "Initializing OpenSSL sup= port for engine '%s'",
- ENGINE_get_id(e));
+ msg(M_INFO, "Initializing OpenSSL sup= port for engine '%s'", ENGINE_get_id(e));
= }
return e;
}
@@ -15= 1,7 +146,7 @@
engine_persist =3D setup_engine(engi= ne_name);
engine_initialized =3D true;
<= span> }

-#else /* = if HAVE_OPENSSL_ENGINE */
+#else /* if HAVE_OPENSSL_ENGINE */
msg(M_WARN, &= quot;Note: OpenSSL hardware crypto engine functionality is not available&qu= ot;);
#endif
}
@@ -167,7 = +162,7 @@
crypto_msg(M_FATAL, "failed to load= provider '%s'", provider);
}
<= span> return prov;

= -#else /* OPENSSL_VERSION_NUMBER >=3D 0x30000000L */
+#else /* OPENSSL_VERSION_NUMBER >= =3D 0x30000000L */
msg(M_WARN, "Note: OpenSSL pro= vider functionality is not available");
return NU= LL;
#endif
@@ -249,12 +244,13 @@ if (ERR_GET_REASON(err) =3D=3D SSL_R_NO_SHARED_CIPHER)
{
msg(D_CRYPT_ERRORS, &qu= ot;TLS error: The server has no TLS ciphersuites "
- "in common with the = client. Your --tls-cipher setting might be "
- "too restrictive.");<= /span>
+ = "in common with the client. Your --tls-cipher setting migh= t be "
+ = "too restrictive.");
= }
else if (ERR_GET_REASON(err) =3D=3D SSL_R_U= NSUPPORTED_PROTOCOL)
{
- msg(D_CRYPT_ERRORS, "TLS error: = Unsupported protocol. This typically "
+ msg(D_CRYPT_ERRORS,
+ "TLS error: Unsupp= orted protocol. This typically "
&quo= t;indicates that client and server have no common TLS version enabled. &quo= t;
"This can be caused by mismatched = tls-version-min and tls-version-max "
= "options on client and server. "
@@ -270,8 +266,= 8 @@
}
else
{

- = msg(flags, "OpenSSL: %s:%s:%s:%d:%s", ERR_error_string(err, N= ULL),
- = data, file, line, func);
+ msg(flags, "OpenSSL: %s:%s:%s:%d:%s", ERR_error_= string(err, NULL), data, file, line,
+ func);
} }
}
@@ -307,9 +303,7 @@
void
crypto_init_dmalloc(void)
{

- CRYPTO_set_mem= _ex_functions(crypto_malloc,
- crypto_realloc,
- crypto_fre= e);
+ CRYPTO_set_m= em_ex_functions(crypto_malloc, crypto_realloc, crypto_free);
}

#endif /* DMALLOC */

@@ -332,7 +326,8 @@

return strcmp(EVP_CIPHER_get0_na= me(*cipher_a), EVP_CIPHER_get0_name(*cipher_b));
}<= br>
-struct coll= ect_ciphers {
+struct= collect_ciphers
+{
/* If we ever exceed this, we must be more selective */=
const EVP_CIPHER *list[1000];
si= ze_t num;
@@ -354,12 +349,12 @@
const char *ciphername =3D EVP_CIPHER_get0_name(cipher);=

- if (ci= phername && (cipher_kt_mode_cbc(ciphername)
+ if (ciphername
+ && (cipher_kt_mode_cbc(ci= phername)
#ifdef ENABLE_OFB_CFB_MODE
- || cipher_kt_mode_of= b_cfb(ciphername)
+ = || cipher_kt_mode_ofb_cfb(ciphername)
#endif
- ||= cipher_kt_mode_aead(ciphername)
- ))
+ || cipher_kt_mode_aead(ciphername))) {
cipher_list->list[cipher_list->= ;num++] =3D cipher;
}
@@ -393,17 +388,= 18 @@
{
cipher =3D EV= P_get_cipherbyname(name);
}
-#else /* if defined(LIBRESSL_VERSION_NUMBE= R) */
+#else /* if de= fined(LIBRESSL_VERSION_NUMBER) */
const EVP_CIPHER= *cipher =3D EVP_get_cipherbynid(nid);
#endif
/* We cast the const away so we can keep the function prototyp= e

* compatible with EVP_CIPHER_do_all_provided */=
- collect_ciphe= rs((EVP_CIPHER *) cipher, &cipher_list);
+ collect_ciphers((EVP_CIPHER *)cipher, &= ;cipher_list);
}
#endif

/* cast to non-const to prevent warning */=
- qsort((EVP_CIPHER *)ciph= er_list.list, cipher_list.num, sizeof(*cipher_list.list), cipher_name_cmp);=
+ qsort((EVP_CIPH= ER *)cipher_list.list, cipher_list.num, sizeof(*cipher_list.list),+ cipher_name_cmp);<= /span>

for (size_t i =3D 0; i < cipher_l= ist.num; i++)
{
@@ -436,8 +432,8 @@
show_available_digests(void)
{
#ifndef ENABLE_SMALL

- printf("The following message digests are available for use wi= th\n"
- = PACKAGE_NAME ". A message digest is used in conjunction with\n"<= /span>
+ printf("The= following message digests are available for use with\n" PACKAGE_NAME<= /span>
+ ". = A message digest is used in conjunction with\n"
= "the HMAC function, to authenticate received packets.\n"
"You can specify a message digest as paramet= er to\n"
"the --auth option.\n")= ;
@@ -486,21 +482,19 @@
e =3D ENGINE_g= et_first();
while (e)
{- printf("%s [%s]\n&= quot;,
- = ENGINE_get_name(e),
- = ENGINE_get_id(e));
+ printf("%s [%s]\n", ENGINE_get_name(e), ENGIN= E_get_id(e));
e =3D ENGINE_get_next(e);
= }
ENGINE_cleanup();
-#else /* if HAVE_OPENSSL_ENGINE */<= br>+#else /* if HAVE_OPENSSL_EN= GINE */
printf("Sorry, OpenSSL hardware crypto en= gine functionality is not available.\n");
#endif
}


bool
-crypto_pem_encode(const = char *name, struct buffer *dst,
- const struct buffer *src, struct gc_arena *gc)<= /span>
+crypto_pem_encode(co= nst char *name, struct buffer *dst, const struct buffer *src,
+ struct gc_arena= *gc)

{
bool ret =3D false; BIO *bio =3D BIO_new(BIO_s_mem());
@@ -527,8 +5= 21,7 @@
}

bool-crypto_pem_decode(const char *= name, struct buffer *dst,
- const struct buffer *src)
+crypto_pem_decode(const char *name, struct buff= er *dst, const struct buffer *src)
{
= bool ret =3D false;

@@ -542,8 +535,7 @@
char *header_read =3D NULL;
uint8_= t *data_read =3D NULL;
long data_read_len =3D 0;
- if (!PEM_read_bio(bio, = &name_read, &header_read, &data_read,
- &data_read_len))
+ if (!PEM_read_bio(bi= o, &name_read, &header_read, &data_read, &data_read_len))
{
dmsg(D_CRYPT_ERRORS, "%= s: PEM decode failed", __func__);
goto cleanu= p;
@@ -551,17 +543,16 @@

= if (strcmp(name, name_read))
{
- dmsg(D_CRYPT_ERRORS,
<= span style=3D"color: hsl(0, 100%, 40%);">- "%s: unexpected= PEM name (got '%s', expected '%s')",

- __func__, name_read, name= );
+ dmsg(D_CR= YPT_ERRORS, "%s: unexpected PEM name (got '%s', expected '= %s')", __func__,
+ name_read, name);
goto cleanup;=
}

uint8_t *dst= _data =3D buf_write_alloc(dst, data_read_len);
if (!ds= t_data)
{
- dmsg(D_CRYPT_ERRORS, "%s: dst too small (%i, needs %l= i)", __func__,
- = BCAP(dst), data_read_len);
+ dmsg(D_CRYPT_ERRORS, "%s: dst too small (%i,= needs %li)", __func__, BCAP(dst),
+ data_read_len);
g= oto cleanup;
}
memcpy(dst_data, d= ata_read, data_read_len);
@@ -632,18 +623,21 @@
<= span>

if (FIPS_mode() && !(EVP_CIPHER_flags(c= ipher) & EVP_CIPH_FLAG_FIPS))
{
- msg(D_LOW, "Cipher algorith= m '%s' is known by OpenSSL library but "
- "currently disabled by run= ning in FIPS mode.", ciphername);
+ msg(D_LOW,
+ "Cipher algorithm '%s' is known = by OpenSSL library but "
+ "currently disabled by running in FIPS mode.&quo= t;,
+ ciph= ername);
*reason =3D "disabled by FIPS mode&q= uot;;
goto out;
}
<= span> #endif

if (EVP_CIPHER_key_length(cipher) > MA= X_CIPHER_KEY_LENGTH)
{
- msg(D_LOW, "Cipher algorithm '%s'= ; uses a default key size (%d bytes) "
+ msg(D_LOW,
+ "Cipher algorithm '%s' uses= a default key size (%d bytes) "
"wh= ich is larger than " PACKAGE_NAME "'s current maximum key siz= e "
- &= quot;(%d bytes)", ciphername, EVP_CIPHER_key_length(cipher),- MAX_CIPHER_KEY_LENG= TH);
+ &qu= ot;(%d bytes)",
= + ciphername, EVP_CIPHER_key_length(cipher), MAX_CIPHER_KEY_LENG= TH);
*reason =3D "disabled due to key size to= o large";
goto out;
}
@@ -758,7 +752,6 @@
bool
ci= pher_kt_insecure(const char *ciphername)
{
-

if (cipher_kt_b= lock_size(ciphername) >=3D 128 / 8)
{
return false;

@@ -790,12 +783,13 @@
<= span> {

evp_cipher_type *cipher =3D cipher_get(ciphern= ame);

- bool ret =3D cipher && (cipher_kt_mode(cipher) =3D=3D OPENVPN= _MODE_CBC
- = /* Exclude AEAD cipher modes, they require a different API */=
+ bool ret =3D ci= pher
+ = && (cipher_kt_mode(cipher) =3D=3D OPENVPN_MODE_CBC
+ /* Exclude AEAD cipher modes, th= ey require a different API */
#ifdef EVP_CIPH_FLAG_CTS
- = && !(EVP_CIPHER_flags(cipher) & EVP_CIPH_FLAG_CTS)
<= span style=3D"color: hsl(120, 100%, 40%);">+ && != (EVP_CIPHER_flags(cipher) & EVP_CIPH_FLAG_CTS)

#endif<= /span>
- = && !(EVP_CIPHER_flags(cipher) & EVP_CIPH_FLAG_AEAD_CIPHER))= ;
+ = && !(EVP_CIPHER_flags(cipher) & EVP_CIPH_FLAG_AEAD_CIPHER));
EVP_CIPHER_free(cipher);
return re= t;
}
@@ -804,8 +798,9 @@
= cipher_kt_mode_ofb_cfb(const char *ciphername)
{ evp_cipher_type *cipher =3D cipher_get(ciphername);
<= span style=3D"color: hsl(0, 100%, 40%);">- bool ofb_cfb =3D cipher &= & (cipher_kt_mode(cipher) =3D=3D OPENVPN_MODE_OFB

- || cipher_kt_= mode(cipher) =3D=3D OPENVPN_MODE_CFB)
+ bool ofb_cfb =3D cipher
+ && (cipher_kt_mode(cip= her) =3D=3D OPENVPN_MODE_OFB
+ || cipher_kt_mode(cipher) =3D=3D OPENVPN_MO= DE_CFB)
/* Exclude AEAD cipher modes, t= hey require a different API */
&&am= p; !(EVP_CIPHER_flags(cipher) & EVP_CIPH_FLAG_AEAD_CIPHER);
<= span> EVP_CIPHER_free(cipher);

@@ -828,7 +823,7 @@
#ifdef NID_chacha20_poly1305
if (EVP_= CIPHER_nid(cipher) =3D=3D NID_chacha20_poly1305)
{=
- isaead = =3D true;
+ = isaead =3D true;
}
#endif
}
@@ -859,8 +854,8 @@
}

void
-cipher_ctx_init(EVP_CIPHER_CTX *ctx, const uint8_t *key,
- const c= har *ciphername, crypto_operation_t enc)
+cipher_ctx_init(EVP_CIPHER_CTX *ctx, const uint8_t *ke= y, const char *ciphername,
+ crypto_operation_t enc)
{ ASSERT(NULL !=3D ciphername && NULL !=3D ctx); evp_cipher_type *kt =3D cipher_get(ciphername);
@@ -913,7 +908,7 @@

int mode =3D EVP_CIPHER_CTX_mode= (ctx);

return mode =3D=3D EVP_CIPH_C= BC_MODE
- /* = Exclude AEAD cipher modes, they require a different API */
+ /* Exclude AEAD cipher modes, th= ey require a different API */
#ifdef EVP_CIPH_FLAG_CTS
&& !(flags & EVP_CIPH_FLAG_CTS)=
#endif
@@ -976,8 +971,7 @@
}

int
-cipher_ctx_update(EVP_CIPHER_CTX *ctx, uint8_t *dst, int *ds= t_len,
- = uint8_t *src, int src_len)
+cipher_ctx_update(EVP_CIPHER_CTX *ctx, uint8_t *dst, int *dst_len= , uint8_t *src, int src_len)
{
if (!E= VP_CipherUpdate(ctx, dst, dst_len, src, src_len))
{
@@ -993,8 +987,8 @@
}

int
-ciphe= r_ctx_final_check_tag(EVP_CIPHER_CTX *ctx, uint8_t *dst, int *dst_len,
- = uint8_t *tag, size_t tag_len)
+cipher_ctx_final_check_tag(EVP_CIPHER_CTX *ctx, uint8_t *dst, in= t *dst_len, uint8_t *tag,
+ size_t tag_len)
{<= br> ASSERT(tag_len < SIZE_MAX);
if (!EVP_= CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_TAG, tag_len, tag))
= @@ -1025,7 +1019,8 @@
}
if (EVP_M= D_size(md) > MAX_HMAC_KEY_LENGTH)
{
- crypto_msg(M_FATAL, "Mes= sage hash algorithm '%s' uses a default hash "

+ crypto_msg(M_FATAL,
<= br>+ "Me= ssage hash algorithm '%s' uses a default hash "
"size (%d bytes) which is larger than " PAC= KAGE_NAME "'s current "

&= quot;maximum hash size (%d bytes)",
= digest, EVP_MD_size(md), MAX_HMAC_KEY_LENGTH);
@@ -1051,1= 7 +1046,12 @@
* this translation table for forward lookup= , only for returning the name
* with md_kt_name() */
const cipher_name_pair digest_name_translation_table[] =3D {
- { "BLAKE2s256&= quot;, "BLAKE2S-256"},
- { "BLAKE2b512", "BLAKE2B-512"},- { "RIPEMD160", &= quot;RIPEMD-160" },
- { "SHA256", "SHA2-256&qu= ot;},
- { "SHA3= 84", "SHA2-384"},
- { "SHA512", "SHA2-512"},
- { "SHA512-224", "S= HA2-512/224"},

- = { "SHA512-256", "SHA2-512/256"},
- { "SHAKE128", "SHAKE-12= 8"},
- { "= SHAKE256", "SHAKE-256"},
+ { "BLAKE2s256", "BLAKE2S-256" }= , { "BLAKE2b512", "BLAKE2B-512" },
+ { "RIPEMD160", "RIPE= MD-160" }, { "SHA224", "SHA2-224" },
= + { "SHA256", &quo= t;SHA2-256" }, { "SHA384", "SHA2-384" },
+ { "SHA512&qu= ot;, "SHA2-512" }, { "SHA512-224", "SHA2-5= 12/224" },
+ = { "SHA512-256", "SHA2-512/256" }, { "SHAKE128"= ;, "SHAKE-128" },
+ { "SHAKE256", "SHAKE-256" },
};

const size_t digest_name_translation_table_count =3D=
sizeof(digest_name_translation_table) / sizeof(*diges= t_name_translation_table);
@@ -1098,7 +1088,7 @@
= return 0;
}
evp_md= _type *kt =3D md_get(mdname);
- unsigned char size =3D (unsigned char)EVP_MD_size(kt);<= br>+ unsigned char size =3D = (unsigned char)EVP_MD_size(kt);
EVP_MD_free(kt);
return size;
}
@@ -1286,10= +1276,8 @@
* only used for lookup so we cast (as Ope= nSSL also does internally)
* the constness away here.=
*/
- ctx->params[0] =3D OSSL_PARAM_construct_utf8_string("digest= ",
- = (char *) EVP_MD_get0_name(kt), 0);<= /span>
- ctx->params[1] = =3D OSSL_PARAM_construct_octet_string("key",
- = ctx->key, EVP_MD_size(kt));
+ ctx->params[0] =3D OSSL_PARAM_construct_utf8= _string("digest", (char *)EVP_MD_get0_name(kt), 0);
+ ctx->params[1] =3D OSSL_PA= RAM_construct_octet_string("key", ctx->key, EVP_MD_size(kt));<= /span>
ctx->params[2] =3D OSSL_PARAM_construct_end();

if (!EVP_MAC_init(ctx->ctx, NULL, 0, = ctx->params))
@@ -1348,8 +1336,8 @@
}
#if (OPENSSL_VERSION_NUMBER >=3D 0x30000000L) &&= !defined(LIBRESSL_VERSION_NUMBER)
bool
-ssl_tls1_PRF(const uint8_t *seed, int se= ed_len, const uint8_t *secret,
- int secret_len, uint8_t *output, int output_len)
+ssl_tls1_PRF(const uint8= _t *seed, int seed_len, const uint8_t *secret, int secret_len,
+ uint8_t *output, in= t output_len)

{
bool ret =3D true;
EVP_KDF_CTX *kctx =3D NULL;
@@ -1372,18 = +1360,18 @@

/* The OpenSSL APIs requ= ire us to cast the const aways even though the
* stri= ngs are never changed and only read */
- params[0] =3D OSSL_PARAM_construct_utf8_string(OSSL_KD= F_PARAM_DIGEST,
- = SN_md5_sha1, strlen(SN_md5_sha1)= );
- params[1] =3D O= SSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_SECRET,
- = (uint8_t *) secret, (size_t) secret_len);
- params[2] =3D OSSL_PARAM_construct_octet_s= tring(OSSL_KDF_PARAM_SEED,
- (uint8_t *) seed, (s= ize_t) seed_len);
+ = params[0] =3D
+ = OSSL_PARAM_construct_utf8_string(OSSL_KDF_PARAM_DIGEST, SN_md5_sha1, st= rlen(SN_md5_sha1));
+= params[1] =3D OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_SECRET, = (uint8_t *)secret,
+ = (size_t)secret_len);
+ params[2] =3D<= br>+ OSSL_PARAM_construc= t_octet_string(OSSL_KDF_PARAM_SEED, (uint8_t *)seed, (size_t)seed_len);

params[3] =3D OSSL_PARAM_construct_end();

if (EVP_KDF_derive(kctx, output, output_len, params= ) <=3D 0)
{
crypto_msg(D_T= LS_DEBUG_LOW, "Generating TLS 1.0 PRF using "
- "EVP_KDF_derive f= ailed");
+ = "EVP_KDF_derive failed"); goto err;
}
@@ -1399,15 +1387,15 @@
}
#elif d= efined(OPENSSL_IS_AWSLC)
bool
-ssl_tls1_PRF(const uint8_t *label, int label_len, = const uint8_t *sec,
- = int slen, uint8_t *out1, int olen)
+ssl_tls1_PRF(const uint8_t *label, int label_len,= const uint8_t *sec, int slen, uint8_t *out1,
+ int olen)
{<= br> CRYPTO_tls1_prf(EVP_md5_sha1(), out1, olen, sec, slen, label,= label_len, NULL, 0, NULL, 0);
}
#elif !d= efined(LIBRESSL_VERSION_NUMBER) && !defined(ENABLE_CRYPTO_WOLFSSL)<= /span>
bool
-= ssl_tls1_PRF(const uint8_t *seed, int seed_len, const uint8_t *secret,
- int secret_le= n, uint8_t *output, int output_len)
+ssl_tls1_PRF(const uint8_t *seed, int seed_len, const uint8= _t *secret, int secret_len,
+ uint8_t *output, int output_len)
{
EVP_PKEY_CTX *pctx =3D EVP_PKEY_CTX_new_id(EVP_PKEY_TLS1= _PRF, NULL);
if (!pctx)
@@ -1455,8 +14= 43,8 @@
* OpenSSL does. As result they will only be able = to support
* peers that support TLS EKM like when running= with OpenSSL 3.x FIPS */
bool
-ssl_tls1_PRF(const uint8_t *label, int label_len,= const uint8_t *sec,
- = int slen, uint8_t *out1, int olen)
+ssl_tls1_PRF(const uint8_t *label, int label_len= , const uint8_t *sec, int slen, uint8_t *out1,
+ int olen)
{=
return false;
}
diff --git = a/src/openvpn/crypto_openssl.h b/src/openvpn/crypto_openssl.h
index 9680c18..6218b39 100644

--- a/src/openvpn/crypto_o= penssl.h
+++ b/src/openvpn/crypto_openssl.h
@@ -50,7 +50,8 @@

/* Use a dummy type for the provider */=
typedef void provider_t;
#else-typedef struct {
+typedef struct

+{
OSSL_PARAM param= s[3];
uint8_t key[EVP_MAX_KEY_LENGTH];
EVP_MAC_CTX *ctx;

@@ -71,29 +72,29 @@
#endif


/** Maximum length of an IV */<= /span>
-#define OPENVPN_MAX_IV= _LENGTH EVP_MAX_IV_LENGTH
+#define OPENVPN_MAX_IV_LENGTH EVP_MAX_IV_LENGTH

/** Cipher is in CBC mode */
-#define OPENVPN_MODE_CBC EVP_CIPH_CBC_MODE
+#define OPENVPN_MODE_C= BC EVP_CIPH_CBC_MODE

/** Cipher is in OF= B mode */
-#define OPEN= VPN_MODE_OFB EVP_CIPH_OFB_MODE
+#define OPENVPN_MODE_OFB EVP_CIPH_OFB_MODE

/** Cipher is in CFB mode */
-#define OPENVPN_MODE_CFB EVP_CIPH_CFB_MO= DE
+#define OPENVPN_M= ODE_CFB EVP_CIPH_CFB_MODE

/** Cipher is = in GCM mode */
-#define= OPENVPN_MODE_GCM EVP_CIPH_GCM_MODE
+#define OPENVPN_MODE_GCM EVP_CIPH_GCM_MODE
typedef int crypto_operation_t;
=
/** Cipher should encrypt */
-#define OPENVPN_OP_ENCRYPT 1
+#define OPENVPN_OP_ENCRYPT 1<= br>
/** Cipher should decrypt */
-#define OPENVPN_OP_DECRYPT 0=
+#define OPENVPN_OP_DECRYPT= 0

-#= define MD4_DIGEST_LENGTH 16
+#define MD4_DIGEST_LENGTH 16

/**

* Retrieve any occurred OpenSSL errors and print t= hose errors.
@@ -112,10 +113,11 @@
* @par= am flags Flags to indicate error type and priority.
* @param ... Format string and optional format arguments
*/
-#defin= e crypto_msg(flags, ...) \
- do { \
+#def= ine crypto_msg(flags, ...) \
+ do = \
+ {= \
= crypto_print_openssl_errors(nonfatal(flags)); \
- msg((flags), __VA_ARGS__); \
<= span style=3D"color: hsl(120, 100%, 40%);">+ msg((flags), __VA_ARGS_= _); \

} while (false)

#endif /* CRYPTO_OPENSSL_H_ */
diff -= -git a/src/openvpn/cryptoapi.c b/src/openvpn/cryptoapi.c
in= dex 67dc382..d91d9a1 100644
--- a/src/openvpn/cryptoapi.c
+++ b/src/openvpn/cryptoapi.c
@@ -62,11 +62,= 12 @@
return 0;
}

-#else /* HAVE_XKEY_PROV= IDER */
+#else /* HA= VE_XKEY_PROVIDER */

static XKEY_EXTERNAL= _SIGN_fn xkey_cng_sign;

-typedef struct _CAPI_DATA {
+typedef struct _CAPI_DATA
+{
const CERT_CONTEXT= *cert_context;
HCRYPTPROV_OR_NCRYPT_KEY_HANDLE crypt_= prov;
EVP_PKEY *pubkey;
@@ -112,7 +113= ,7 @@
break;

default:

- = msg(M_WARN|M_INFO, "cryptoapicert: Unknown hash type NID=3D0x= %x", md_type);
+= msg(M_WARN | M_INFO, "cryptoapicert: Unknown hash type NID= =3D0x%x", md_type);
break;
}

return alg;
@@ -157,7 +158,7 = @@
parse_hexstring(const char *p, unsigned char *arr, size= _t capacity)
{
int i =3D 0;- for ( ; *p && i <= ; capacity; p +=3D 2)
+ for (; *p && i < capacity; p +=3D 2)
= {
/* skip spaces */
while= (*p =3D=3D ' ')
@@ -169,8 +170,7 @@
break;

}
- if (!isxdigit(p[0]) ||= !isxdigit(p[1])
- = || sscanf(p, "%2hhx", &arr[i++]) !=3D 1)
+ if (!isxdigit(p[0]) || !i= sxdigit(p[1]) || sscanf(p, "%2hhx", &arr[i++]) !=3D 1)
=
{
return 0;
}

@@ -179,21 +179,21 @@
}=

static void *
-decode_object(struct gc_arena *gc, LPCSTR struct_type,=
- const C= RYPT_OBJID_BLOB *val, DWORD flags, DWORD *cb)
+decode_object(struct gc_arena *gc, LPCSTR struct_= type, const CRYPT_OBJID_BLOB *val, DWORD flags,
+ DWORD *cb)
{
/* get byte count for decoding */
BY= TE *buf;
- if (!Cryp= tDecodeObject(X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, struct_type,<= br>- va= l->pbData, val->cbData, flags, NULL, cb))
+ if (!CryptDecodeObject(X509_ASN_ENCODING | = PKCS_7_ASN_ENCODING, struct_type, val->pbData,
+ val->cbData, fl= ags, NULL, cb))
{
return NULL= ;
}

/* do the a= ctual decode */
buf =3D gc_malloc(*cb, false, gc);
- if (!CryptDecodeObjec= t(X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, struct_type,
- val->pbData= , val->cbData, flags, buf, cb))
+ if (!CryptDecodeObject(X509_ASN_ENCODING | PKCS_7_ASN_EN= CODING, struct_type, val->pbData,
+ val->cbData, flags, buf, cb)= )
{
return NULL;
}

@@ -243,8 +243,8 @@
= return true;
}
- const CRYPT_OID_IN= FO *tmpl_oid =3D find_oid(CRYPT_OID_INFO_NAME_KEY, tmpl_name,
- = CRYPT_TEMPLATE_OID_GROUP_ID);

+ const CRYPT_OID_INFO *tmpl_oid =3D=
+ fin= d_oid(CRYPT_OID_INFO_NAME_KEY, tmpl_name, CRYPT_TEMPLATE_OID_GROUP_ID);
if (tmpl_oid && !stricmp(tmpl_oid->psz= OID, cte->pszObjId))
{
= /* found OID match in extension against resolved key */=
@@ -274,7 +274,7 @@
DWORD find_type;<= br> const void *find_param;
unsigned char ha= sh[255];
- CRYPT_HAS= H_BLOB blob =3D {.cbData =3D 0, .pbData =3D hash};
+ CRYPT_HASH_BLOB blob =3D { .cbData =3D 0= , .pbData =3D hash };
struct gc_arena gc =3D gc_new();=

if (!strncmp(cert_prop, "SUBJ:= ", 5))
@@ -296,7 +296,7 @@
bl= ob.cbData =3D parse_hexstring(cert_prop + 6, hash, sizeof(hash)); if (blob.cbData =3D=3D 0)
{=
- msg(M_WARN|M_INF= O, "WARNING: cryptoapicert: error parsing <%s>.", cert_prop= );
+ msg(M= _WARN | M_INFO, "WARNING: cryptoapicert: error parsing <%s>.&quo= t;, cert_prop);
goto out;
= }
}
@@ -308,7 +308,8 @@ }
else
{
- msg(M_NONFATAL, "Erro= r in cryptoapicert: unsupported certificate specification <%s>",= cert_prop);

+ = msg(M_NONFATAL, "Error in cryptoapicert: unsupported certificate spec= ification <%s>",
+ cert_prop);
goto out; }

@@ -316,15 +317,14 @@
{
int validity =3D 1;
<= span> /* this frees previous rv, if not NULL */

- rv =3D CertFindCertificateInStore= (cert_store, X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,
- 0, = find_type, find_param, rv);
+ rv =3D CertFindCertificateInStore(cert_store, X509_ASN_ENCO= DING | PKCS_7_ASN_ENCODING, 0,
+ find_type, find_param, r= v);
if (!rv)
{
= break;
}
= /* if searching by template name, check now if it matches */
<= span style=3D"color: hsl(0, 100%, 40%);">- if (find_type =3D=3D CERT= _FIND_HAS_PRIVATE_KEY

-= && !test_certificate_template(cert_prop, rv))+ if (find_type =3D=3D = CERT_FIND_HAS_PRIVATE_KEY && !test_certificate_template(cert_prop, = rv))
{
continue;
}
@@ -333,7 +333,7 @@
= {
break;
}
- msg(M_WARN|M_IN= FO, "WARNING: cryptoapicert: ignoring certificate in store %s.",<= /span>
+ msg(M_WARN |= M_INFO, "WARNING: cryptoapicert: ignoring certificate in store %s.&qu= ot;,
validity < 0 ? "not yet valid&quo= t; : "that has expired");
}
=
@@ -356,12 +356,12 @@
if (status != =3D ERROR_SUCCESS)
{
SetLastE= rror(status);
- = msg(M_NONFATAL|M_ERRNO, "Error in cryptoapicert: ECDSA signature using= CNG failed.");
= + msg(M_NONFATAL | M_ERRNO, "Error in cryptoapicert: ECDSA sign= ature using CNG failed.");
return 0; }

/* NCryptSignHash ret= urns r|s -- convert to DER encoded buffer expected by OpenSSL */
= - int derlen =3D ecdsa_bin2der= (sig, (int) len, *siglen);
+ int derlen =3D ecdsa_bin2der(sig, (int)len, *siglen);
= if (derlen <=3D 0)
{
= return 0;
@@ -396,9 +396,9 @@
{<= /span>
msg(D_LOW, "Signing using NCryptSignHash with= PKCS1 padding: hashalg <%s>", sigalg.mdname);
=
- BCRYPT_PKCS1_= PADDING_INFO padinfo =3D {hashalg};
- status =3D NCryptSignHash(cd->crypt_prov, &pad= info, (BYTE *)tbs, (DWORD)tbslen,
- sig, (DWORD)*siglen, &len, = BCRYPT_PAD_PKCS1);
+ = BCRYPT_PKCS1_PADDING_INFO padinfo =3D { hashalg };
+ status =3D NCryptSignHash(cd-= >crypt_prov, &padinfo, (BYTE *)tbs, (DWORD)tbslen, sig,
+ = (DWORD)*siglen, &len, BCRYPT_PAD_PKCS1);

}<= br> else if (!strcmp(sigalg.padmode, "pss"))
= {
@@ -416,9 +416,10 @@
= msg(D_LOW, "Signing using NCryptSignHash with PSS padding: hashalg <= ;%s>, saltlen <%d>",
sigalg.mdna= me, saltlen);

- BCRYPT_PSS_PADDING_INFO padinfo =3D {hashalg, (DWORD) sal= tlen}; /* cast is safe as saltlen >=3D 0 */
- status =3D NCryptSignHash(cd->crypt_pro= v, &padinfo, (BYTE *)tbs, (DWORD) tbslen,
- sig, (DWORD)*siglen= , &len, BCRYPT_PAD_PSS);
+ BCRYPT_PSS_PADDING_INFO padinfo =3D { hashalg,
<= span style=3D"color: hsl(120, 100%, 40%);">+ = (DWORD)saltlen }; /* cast is safe as saltlen >=3D 0 */
+ status =3D NCryp= tSignHash(cd->crypt_prov, &padinfo, (BYTE *)tbs, (DWORD)tbslen, sig,=
+ = (DWORD)*siglen, &len, BCRYPT_PAD_PSS);
= }
else
{
@@ -42= 9,7 +430,7 @@
if (status !=3D ERROR_SUCCESS) {
SetLastError(status);
- msg(M_NONFATAL|M_ERRNO, &quo= t;Error in cryptoapicert: RSA signature using CNG failed.");
+ msg(M_NONFATAL | M_ER= RNO, "Error in cryptoapicert: RSA signature using CNG failed.");<= /span>
return 0;
}
=
@@ -484,7 +485,7 @@
char *name =3D NU= LL;
if (len)
{
- wchar_t *wname =3D gc_malloc(len= *sizeof(wchar_t), false, gc);
+ wchar_t *wname =3D gc_malloc(len * sizeof(wchar_t), false= , gc);
if (!wname
|| = CertGetNameStringW(cc, CERT_NAME_FRIENDLY_DISPLAY_TYPE, 0, NULL, wname, len= ) =3D=3D 0)
{
@@ -504,7 +505,6 @@<= /span>
static int
Load_CryptoAPI_certificate(con= st char *cert_prop, X509 **cert, EVP_PKEY **privkey)
{
-
HCE= RTSTORE cs;
CAPI_DATA *cd =3D calloc(1, sizeof(*cd));<= /span>
struct gc_arena gc =3D gc_new();
@@ -5= 15,29 +515,35 @@
goto err;
}<= /span>
/* search CURRENT_USER first, then LOCAL_MACHINE */
- cs =3D CertOpenStore= ((LPCSTR) CERT_STORE_PROV_SYSTEM, 0, 0, CERT_SYSTEM_STORE_CURRENT_USER
- |CE= RT_STORE_OPEN_EXISTING_FLAG | CERT_STORE_READONLY_FLAG, L"MY");
+ cs =3D CertOpenSt= ore((LPCSTR)CERT_STORE_PROV_SYSTEM, 0, 0,
+ CERT_SYSTEM_STORE_CURRENT_USER= | CERT_STORE_OPEN_EXISTING_FLAG
+ | CERT_STORE_READONLY_FLAG,<= br>+ L&qu= ot;MY");
if (cs =3D=3D NULL)
= {
- msg(M_NONFA= TAL|M_ERRNO, "Error in cryptoapicert: failed to open user certficate s= tore");
+ = msg(M_NONFATAL | M_ERRNO, "Error in cryptoapicert: failed to open use= r certficate store");
goto err;
}

cd->cert_context =3D find_certificate_in_= store(cert_prop, cs);
CertCloseStore(cs, 0); if (!cd->cert_context)
{
- cs =3D CertOpenStore((LPCSTR= ) CERT_STORE_PROV_SYSTEM, 0, 0, CERT_SYSTEM_STORE_LOCAL_MACHINE

<= span style=3D"color: hsl(0, 100%, 40%);">- |CERT_= STORE_OPEN_EXISTING_FLAG | CERT_STORE_READONLY_FLAG, L"MY");
+ cs =3D CertOpenS= tore((LPCSTR)CERT_STORE_PROV_SYSTEM, 0, 0,
+ CERT_SYSTEM_STORE_LOCAL_M= ACHINE | CERT_STORE_OPEN_EXISTING_FLAG
+ | CERT_STORE_READONLY_FLA= G,
+ = L"MY");
if (cs =3D=3D NULL)
{
+ msg(M_NONFATAL | M_ERRNO,
+ "Error in cryp= toapicert: failed to open machine certficate store");

= goto err;
}
= cd->cert_context =3D find_certificate_in_store(cert_prop, cs); CertCloseStore(cs, 0);
if (cd->= cert_context =3D=3D NULL)
{
- msg(M_NONFATAL, "Error in = cryptoapicert: certificate matching <%s> not found", cert_prop);=
+ msg(M_N= ONFATAL, "Error in cryptoapicert: certificate matching <%s> not = found",
+ = cert_prop);
goto err;
}

}
@@ -550,7 +556,7 @@
}

/* cert_context-&= gt;pbCertEncoded is the cert X509 DER encoded. */
- *cert =3D d2i_X509(NULL, (const unsigned ch= ar **) &cd->cert_context->pbCertEncoded,
+ *cert =3D d2i_X509(NULL, (const unsigned= char **)&cd->cert_context->pbCertEncoded,
= cd->cert_context->cbCertEncoded);
= if (*cert =3D=3D NULL)
{
@@ -560,13 = +566,13 @@

/* set up stuff to use th= e private key */
/* We support NCRYPT key handles only= */
- DWORD flags = =3D CRYPT_ACQUIRE_COMPARE_KEY_FLAG
- | CRYPT_ACQUIRE_ONLY_NCRYPT_KEY_FLAG;=
- if (!CryptAcquireCertifi= catePrivateKey(cd->cert_context, flags, NULL,
- &= cd->crypt_prov, &cd->key_spec, &cd->free_crypt_prov))
+ DWORD flags =3D CRYP= T_ACQUIRE_COMPARE_KEY_FLAG | CRYPT_ACQUIRE_ONLY_NCRYPT_KEY_FLAG;
= + if (!CryptAcquireCertifica= tePrivateKey(cd->cert_context, flags, NULL, &cd->crypt_prov,
+ = &cd->key_spec, &cd->free_crypt_prov))
{
/* private key may be in a toke= n not available, or incompatible with CNG */
- msg(M_NONFATAL|M_ERRNO, "Error in crypt= oapicert: failed to acquire key. Key not present or "
+ msg(M_NONFATAL | M_ERRNO,
+ "Erro= r in cryptoapicert: failed to acquire key. Key not present or "=
"is in a legacy token not supported by Windows = CNG API");
X509_free(*cert);
= goto err;
@@ -576,8 +582,8 @@
= EVP_PKEY *pkey =3D X509_get_pubkey(*cert);
cd->pub= key =3D pkey; /* will be freed with cd */

- *privkey =3D xkey_load_generic_ke= y(tls_libctx, cd, pkey,

- xkey_cng_sign, (XKEY_PRIVKEY_FREE_fn= *) CAPI_DATA_free);
= + *privkey =3D xkey_load_generic_key(tls_libctx, cd, pkey, xkey_cng_sign= ,
+ = (XKEY_PRIVKEY_FREE_fn *)CAPI_DATA_free);
gc_free(&gc);

return 1; /* do not free cd --= its kept by xkey provider */

@@ -598,8 += 604,7 @@
{
return ret;=
}
- i= f (SSL_CTX_use_certificate(ssl_ctx, cert)
- && SSL_CTX_use_PrivateKey(ssl_ctx, priv= key))
+ if (SSL_CT= X_use_certificate(ssl_ctx, cert) && SSL_CTX_use_PrivateKey(ssl_ctx,= privkey))
{
crypto_print_ope= nssl_errors(M_WARN);
ret =3D 1;
@@= -612,5 +617,5 @@
return ret;
}

-#endif /= * HAVE_XKEY_PROVIDER */
-#endif /* _WIN32 */
+#endif /* HAVE_XKEY_PROVIDER */
+#endif /* _WIN32 */
= diff --git a/src/openvpn/dco.c b/src/openvpn/dco.c
index df= 70e87..1abebbb 100644
--- a/src/openvpn/dco.c
+++ b/src/openvpn/dco.c

@@ -51,14 +51,13 @@
#endif


static int
-dco_install_key(struct tls_multi *multi= , struct key_state *ks,
- const uint8_t *encrypt_key, const uint8_t *encrypt_iv,
- const ui= nt8_t *decrypt_key, const uint8_t *decrypt_iv,
+dco_install_key(struct tls_multi *multi, struct = key_state *ks, const uint8_t *encrypt_key,
+ const uint8_t *encrypt_iv, const uin= t8_t *decrypt_key, const uint8_t *decrypt_iv,
= const char *ciphername)

{
= - msg(D_DCO_DEBUG, "%s: p= eer_id=3D%d keyid=3D%d, currently %d keys installed",
- __func__, multi->dco_peer_i= d, ks->key_id, multi->dco_keys_installed);
+ msg(D_DCO_DEBUG, "%s: peer_id=3D%d ke= yid=3D%d, currently %d keys installed", __func__,
+ multi->dco_peer_id, ks->ke= y_id, multi->dco_keys_installed);

= /* Install a key in the PRIMARY slot only when no other key exist.<= br> * From that moment on, any new key will be installed in the = SECONDARY
@@ -71,33 +70,27 @@
slot= =3D OVPN_KEY_SLOT_SECONDARY;
}

- int ret =3D dco_new_ke= y(multi->dco, multi->dco_peer_id, ks->key_id, slot,
- encrypt_ke= y, encrypt_iv,

- = decrypt_key, decrypt_iv,
- ciphername);
+ int ret =3D dco_new_key(multi-= >dco, multi->dco_peer_id, ks->key_id, slot, encrypt_key, encrypt_i= v,

+ = decrypt_key, decrypt_iv, ciphername);
if ((re= t =3D=3D 0) && (multi->dco_keys_installed < 2))
{

multi->dco_keys_installed++;- ks->dco_status =3D = (slot =3D=3D OVPN_KEY_SLOT_PRIMARY) ? DCO_INSTALLED_PRIMARY :
- DCO_INSTAL= LED_SECONDARY;

+ = ks->dco_status =3D
+ (slot =3D=3D OVPN_KEY_SLOT_PRIMARY) ? DCO_INSTALLED_PRIMAR= Y : DCO_INSTALLED_SECONDARY;
}

return ret;
}

= int
-init_key_dc= o_bi(struct tls_multi *multi, struct key_state *ks,
- const struct key2 *key2, in= t key_direction,
- = const char *ciphername, bool server)
+init_key_dco_bi(struct tls_multi *multi, struct= key_state *ks, const struct key2 *key2,
+ int key_direction, const char *ciphern= ame, bool server)
{
struct key_direct= ion_state kds;
key_direction_state_init(&kds, key_= direction);

- return dco_install_key(multi, ks,
- key2->keys[kds.out_ke= y].cipher,
- = key2->keys[(int)server].hmac,
- key2->keys[kds.in_= key].cipher,
- = key2->keys[1 - (int)server].hmac,
+ return dco_install_key(multi, ks, ke= y2->keys[kds.out_key].cipher, key2->keys[(int)server].hmac,+ ke= y2->keys[kds.in_key].cipher, key2->keys[1 - (int)server].hmac,=
ciphername);
}

@@ -183,13 +176,15 @@
{
if (secondary)
{- msg(D_DCO_DEBUG, &q= uot;Swapping primary and secondary keys to "
+ msg(D_DCO_DEBUG,
+ "Swapping prima= ry and secondary keys to "
"prim= ary-id=3D%d secondary-id=3D%d",
prima= ry->key_id, secondary->key_id);
}
= else
{
- msg(D_DCO_DEBUG, "Swapping primar= y and secondary keys to "
+ msg(D_DCO_DEBUG,
+ "Swapping primary and secondary ke= ys to "
"primary-id=3D%d seconda= ry-id=3D(to be deleted)",
primary->= ;key_id);
}
@@ -275,13 +270,15 @@<= /span>
#if defined(_WIN32)
if (!proto_is_udp= (ce->proto) && mode =3D=3D MODE_SERVER)
{
- msg(msglevel, &= quot;NOTE: TCP transport disables data channel offload on Windows in server= mode.");
+ = msg(msglevel,
+ = "NOTE: TCP transport disables data channel offload on Windows= in server mode.");
return false;
<= span> }


if (!ce->remote &= & !dco_win_supports_multipeer())
{
- msg(msglevel, "NOTE: --r= emote is not defined. This DCO version doesn't support multipeer. Disab= ling Data Channel Offload");

+ msg(msglevel,
+ "NOTE: --remote is not defined. This DCO v= ersion doesn't support multipeer. Disabling Data Channel Offload")= ;
return false;
}
<= span>

@@ -310,7 +307,7 @@
if (!o->= tls_client && !o->tls_server)
{
<= span> msg(msglevel, "No tls-client or tls-server option in con= figuration "

- = "detected. Disabling data channel offload.");
<= span style=3D"color: hsl(120, 100%, 40%);">+ "det= ected. Disabling data channel offload.");

ret= urn false;
}

@@ -354= ,7 +351,8 @@
#if defined(_WIN32)
if (= (o->mode =3D=3D MODE_SERVER) && !dco_win_supports_multipeer())
{
-= msg(msglevel, "--mode server is set. This DCO version doesn= 9;t support multipeer. Disabling Data Channel Offload");
+ msg(msglevel,

<= span style=3D"color: hsl(120, 100%, 40%);">+ "--mode server= is set. This DCO version doesn't support multipeer. Disabling Data Cha= nnel Offload");

return false;
}


@@ -385,8 +383,8 @@
}

else if ((ret < 0) && (re= t !=3D -ENODEV))
{
- msg(msglevel, "Cannot retrieve type = of device %s: %s (%d)", o->dev,
- strerror(-ret), ret);
+ msg(msglevel, "Cannot = retrieve type of device %s: %s (%d)", o->dev, strerror(-ret),
+ ret);
}
}
#endif /* i= f defined(_WIN32) */
@@ -401,13 +399,13 @@
= if (!capng_have_capability(CAPNG_EFFECTIVE, CAP_SETPCAP)) {
msg(msglevel, "--user = specified but lacking CAP_SETPCAP. "
- "Cannot retain CAP_NET_ADMIN. Disa= bling data channel offload");
+ "Cannot retain CAP_NET_ADMIN.= Disabling data channel offload");
return= false;
}
if (!capng_have= _capability(CAPNG_PERMITTED, CAP_NET_ADMIN))
{
msg(msglevel, "--user specified but not perm= itted to retain CAP_NET_ADMIN. "
- "Disabling data channel offload")= ;
+ = "Disabling data channel offload");
= return false;
}
}
@@ -438,16 +436,18 @@
if (o->enable_ncp= _fallback
&& !tls_item_in_cipher_list(o-&g= t;ciphername, dco_get_supported_ciphers()))
{- msg(msglevel, "No= te: --data-ciphers-fallback with cipher '%s' "
- "disables data chann= el offload.", o->ciphername);

+ msg(msglevel,
+ "Note: --data-ciphers-fallback with ci= pher '%s' "
+ "disables data channel offload.",
+ o->ciphername);
return false;
}
=
#if defined(USE_COMP)
- if (o->comp.alg !=3D COMP_ALG_UNDEF
- || o->comp.flags & C= OMP_F_ALLOW_ASYM)

+ = if (o->comp.alg !=3D COMP_ALG_UNDEF || o->comp.flags & COMP_F_A= LLOW_ASYM)
{
- msg(msglevel, "Note: '--allow-compression'= is not set to 'no', disabling data channel offload.");=
+ msg(msglevel,
+ "Note: = '--allow-compression' is not set to 'no', disabling data ch= annel offload.");

if (o->= ;mode =3D=3D MODE_SERVER && !(o->comp.flags & COMP_F_MIGRATE= ))
{
@@ -466,8 +466,10 @@ {
if (!tls_item_in_cipher_list(token,= dco_get_supported_ciphers()))
{
- msg(msglevel, "Note: c= ipher '%s' in --data-ciphers is not supported "
- "by ovpn-dco, d= isabling data channel offload.", token);

+ msg(msglevel,
+ "Note: cipher '%= s' in --data-ciphers is not supported "
+ "by ovpn-dco, disabling d= ata channel offload.",
+ token);
gc_free(&g= c);
return false;
}
@@ -483,7 +485,7 @@
if (!o->use_peer= _id)
{
msg(msglevel, "OP= TIONS IMPORT: Server did not request DATA_V2 packet "
- "format required for = data channel offload");
+ "format required for data channel offlo= ad");
return false;
}
return true;
@@ -513,8 +515,7 @@<= br> }
#endif
int ret =3D dc= o_new_peer(&c->c1.tuntap->dco, multi->peer_id, sock->sd, NU= LL,
- = proto_is_dgram(sock->info.proto) ? remoteaddr : NULL,- NULL= , NULL);
+ = proto_is_dgram(sock->info.proto) ? remoteaddr : NULL, NU= LL, NULL);
if (ret < 0)
{
return ret;
@@ -547,7 +548,8 @@=
#if ENABLE_IP_PKTINFO
struct context *c =3D= &mi->context;

- if (!proto_is_udp(c->c2.link_sockets[0]->info.p= roto) || !(c->options.sockflags & SF_USE_IP_PKTINFO))
+ if (!proto_is_udp(c->c2.lin= k_sockets[0]->info.proto)

+ || !(c->options.sockflags & SF_USE_IP_PKTINFO))
{
return false;
= }
@@ -631,8 +633,8 @@
localad= dr =3D (struct sockaddr *)&local;
}

- int ret =3D dc= o_new_peer(&c->c1.tuntap->dco, peer_id, sd, localaddr,
= - remot= eaddr, vpn_addr4, vpn_addr6);
+ int ret =3D
+ dco_new_peer(&c->c1.tuntap->dco, peer_id, sd, local= addr, remoteaddr, vpn_addr4, vpn_addr6);
if (ret < = 0)
{
return ret;
@@ -644,8 +646,7 @@

}

void

-dco_install_ir= oute(struct multi_context *m, struct multi_instance *mi,
- struct mroute_addr *a= ddr)
+dco_install_iro= ute(struct multi_context *m, struct multi_instance *mi, struct mroute_addr = *addr)
{
#if defined(TARGET_LINUX) || def= ined(TARGET_FREEBSD) || defined(_WIN32)
if (!dco_enabl= ed(&m->top.options))
@@ -666,7 +667,8 @@
<= span> if (addrtype =3D=3D MR_ADDR_IPV6)

{ #if defined(_WIN32)
- dco_win_add_iroute_ipv6(&c->c1.tuntap->dco, addr-&= gt;v6.addr, addr->netbits, c->c2.tls_multi->peer_id);
+ dco_win_add_iroute_ipv6(= &c->c1.tuntap->dco, addr->v6.addr, addr->netbits,
+ = c->c2.tls_multi->peer_id);
#else
= net_route_v6_add(&m->top.net_ctx, &addr->v6.addr, ad= dr->netbits,
&mi->conte= xt.c2.push_ifconfig_ipv6_local, c->c1.tuntap->actual_name, 0,<= br>@@ -676,12 +678,12 @@
else if (addrtype =3D= =3D MR_ADDR_IPV4)
{
#if defined(_WIN3= 2)
- dco_win_add= _iroute_ipv4(&c->c1.tuntap->dco, addr->v4.addr, addr->netbi= ts, c->c2.tls_multi->peer_id);
+ dco_win_add_iroute_ipv4(&c->c1.tuntap->d= co, addr->v4.addr, addr->netbits,
+ c->c2.tls_multi->= peer_id);
#else
in_addr_t dest = =3D htonl(addr->v4.addr);
- net_route_v4_add(&m->top.net_ctx, &dest, addr->= ;netbits,
- = &mi->context.c2.push_ifconfig_local, c->c1.tuntap-&g= t;actual_name, 0,
- = DCO_IROUTE_METRIC);
+ net_route_v4_add(&m->top.net_ctx, &= dest, addr->netbits, &mi->context.c2.push_ifconfig_local,<= br>+ c-= >c1.tuntap->actual_name, 0, DCO_IROUTE_METRIC);
#end= if
}
#endif /* if defined(TARGET_LINU= X) || defined(TARGET_FREEBSD) || defined(_WIN32) */
@@ -701= ,32 +703,28 @@

if (mi->context.c2= .push_ifconfig_defined)
{
- for (const struct iroute *ir =3D c->opt= ions.iroutes;
- = ir;
- = ir =3D ir->next)
+= for (const struct iroute *ir =3D c->options.iroutes; ir; ir =3D = ir->next)
{
#if defined(_WIN32= )
dco_win_del_iroute_ipv4(&c->c1.tuntap= ->dco, htonl(ir->network), ir->netbits);
#else
net_route_v4_del(&m->top.net_ctx, &ir= ->network, ir->netbits,
- &mi->context.c2.push_ifconfig_l= ocal, c->c1.tuntap->actual_name,
- 0, DCO_IROUTE_METRIC);=
+ = &mi->context.c2.push_ifconfig_local, c->c1.tuntap->actual_n= ame, 0,
+ = DCO_IROUTE_METRIC);
#endif
}

}

= if (mi->context.c2.push_ifconfig_ipv6_defined)
{
- for (const struc= t iroute_ipv6 *ir6 =3D c->options.iroutes_ipv6;
- ir6;
- ir6 =3D ir6->next)
+ for (const struct iroute_ip= v6 *ir6 =3D c->options.iroutes_ipv6; ir6; ir6 =3D ir6->next)
{
#if defined(_WIN32)
= dco_win_del_iroute_ipv6(&c->c1.tuntap->dco, ir6->net= work, ir6->netbits);
#else
= net_route_v6_del(&m->top.net_ctx, &ir6->network, ir6->net= bits,
- = &mi->context.c2.push_ifconfig_ipv6_local, c->c1.tunt= ap->actual_name,
- = 0, DCO_IROUTE_METRIC);
+ &mi->cont= ext.c2.push_ifconfig_ipv6_local, c->c1.tuntap->actual_name, 0,=
+ = DCO_IROUTE_METRIC);
#endif
}
}
diff --git a/src/openvpn/dco.h b/src/= openvpn/dco.h
index 95abf71..59acb18 100644
--- a/src/openvpn/dco.h

+++ b/src/openvpn/dco.h
= @@ -43,8 +43,8 @@
struct tls_multi;
= struct tuntap;

-#define DCO_IROUTE_METRIC 100
-#define DCO_DEFAULT_METRIC 200
+#define DCO_IROUTE_METRIC 100
= +#define DCO_DEFAULT_METRIC 200=

#if defined(ENABLE_DCO)

@@ -153,9 +153,8 @@
*
= * @return 0 on success or a negative error code otherwise=
*/
-int ini= t_key_dco_bi(struct tls_multi *multi, struct key_state *ks,
- const struct key2= *key2, int key_direction,

- const char *ciphername, bool server);
+int init_key_dco_bi(struct tls_m= ulti *multi, struct key_state *ks, const struct key2 *key2,

+ int key_directi= on, const char *ciphername, bool server);


/**

* Possibly swap or wipe keys from DCO
@@ -187,8 +186,8 @@

*
* @return = 0 on success or a negative error code otherwise
*/

-int dco_set_pe= er(dco_context_t *dco, unsigned int peerid,
- int keepalive_interval, int keepaliv= e_timeout, int mss);
= +int dco_set_peer(dco_context_t *dco, unsigned int peerid, int keepalive_in= terval,
+ = int keepalive_timeout, int mss);

/*= *
* Remove a peer from DCO
@@ -257,7 +256= ,7 @@
{
return false;
}

-#else /* if define= d(ENABLE_DCO) */
+#el= se /* if defined(ENABLE_DCO) */

typedef= void *dco_context_t;

@@ -321,9 +320,8 @@=
}

static inline int
-init_key_dco_bi(struct t= ls_multi *multi, struct key_state *ks,
- const struct key2 *key2, int key_direction= ,
- cons= t char *ciphername, bool server)
+init_key_dco_bi(struct tls_multi *multi, struct key_state *ks,= const struct key2 *key2,
+ int key_direction, const char *ciphername, bool serve= r)
{
return 0;
}
@@ -342,8 +340,8 @@
}

static inline int
-dco_set_peer(dco_context_t *dco, unsigned int peerid,
- int keepalive_interval= , int keepalive_timeout, int mss)

+dco_set_peer(dco_context_t *dco, unsigned int peerid, int kee= palive_interval, int keepalive_timeout,
+ int mss)
{
return 0;

}
@@ -360,8 +358,7 @@
}

static inline void
-dco_install_iroute(struct m= ulti_context *m, struct multi_instance *mi,
- struct mroute_addr *addr)+dco_install_iroute(struct mu= lti_context *m, struct multi_instance *mi, struct mroute_addr *addr)=
{
}

diff --gi= t a/src/openvpn/dco_freebsd.c b/src/openvpn/dco_freebsd.c
i= ndex 04c1e3d..931f9f6 100644
--- a/src/openvpn/dco_freebsd.= c
+++ b/src/openvpn/dco_freebsd.c
@@ -133,9= +133,8 @@
}

int=
-dco_new_peer(dco_context_t *= dco, unsigned int peerid, int sd,
- struct sockaddr *localaddr, struct sockaddr *remot= eaddr,
- st= ruct in_addr *vpn_ipv4, struct in6_addr *vpn_ipv6)
+dco_new_peer(dco_context_t *dco, unsigned in= t peerid, int sd, struct sockaddr *localaddr,
+ struct sockaddr *remoteaddr, struct = in_addr *vpn_ipv4, struct in6_addr *vpn_ipv6)
{
= struct ifdrv drv;
nvlist_t *nvl, *local_nvl= , *remote_nvl;
@@ -159,8 +158,7 @@
=
if (vpn_ipv4)
{
- nvlist_add_binary(nvl, "vpn_ip= v4", &vpn_ipv4->s_addr,
- sizeof(vpn_ipv4->s_addr));
+ nvlist_add_binary= (nvl, "vpn_ipv4", &vpn_ipv4->s_addr, sizeof(vpn_ipv4->s= _addr));
}

if (= vpn_ipv6)
@@ -278,7 +276,7 @@
if (ret)=
{
ret =3D -errno;
= - msg(M_WARN|M_ERRNO, &quo= t;Failed to create interface %s (SIOCIFCREATE2)", ifr.ifr_name);
+ msg(M_WARN | M_ER= RNO, "Failed to create interface %s (SIOCIFCREATE2)", ifr.ifr_nam= e);
return ret;
}
<= span>

@@ -300,7 +298,7 @@
ret =3D= -errno;
/* Delete the created interface again. */=
(void)ioctl(tt->dco.fd, SIOCIFDESTROY, &if= r);
- msg(M_WARN= |M_ERRNO, "Failed to create interface %s (SIOCSIFNAME)", ifr.ifr_= data);
+ msg(M= _WARN | M_ERRNO, "Failed to create interface %s (SIOCSIFNAME)", i= fr.ifr_data);
return ret;
}

@@ -412,8 +410,7 @@
}

int
-dco_del_key(dco_context_t *dco, unsigned int peerid,- dco_key_slot_t slo= t)
+dco_del_key(dco_c= ontext_t *dco, unsigned int peerid, dco_key_slot_t slot)
{=
struct ifdrv drv;
nvlist_t *nvl;=
@@ -483,18 +480,16 @@
}
=
int
-= dco_new_key(dco_context_t *dco, unsigned int peerid, int keyid,
<= span style=3D"color: hsl(0, 100%, 40%);">- dco_key_slot_t slot,<= /span>
- const uint= 8_t *encrypt_key, const uint8_t *encrypt_iv,
- const uint8_t *decrypt_key, const uint8_= t *decrypt_iv,
- = const char *ciphername)
+dco_new_key(dco_context_t *dco, unsigned int peerid, int keyid, dc= o_key_slot_t slot,
+ = const uint8_t *encrypt_key, const uint8_t *encrypt_iv, const uin= t8_t *decrypt_key,
+ = const uint8_t *decrypt_iv, const char *ciphername)
{

struct ifdrv drv;
nvlist_t = *nvl, *encrypt_nvl, *decrypt_nvl;
int ret;
<= span>

- msg(D_DCO_D= EBUG, "%s: slot %d, key-id %d, peer-id %d, cipher %s",
= - __func__, slot, keyid, p= eerid, ciphername);
+= msg(D_DCO_DEBUG, "%s: slot %d, key-id %d, peer-id %d, cipher %s&qu= ot;, __func__, slot, keyid, peerid,
+ ciphername);

= nvl =3D nvlist_create(0);

@@ -532,16 +52= 7,15 @@
}

int-dco_set_peer(dco_context_t *dco= , unsigned int peerid,
= - int keepalive_interval, int keepalive_timeout,
+dco_set_peer(dco_context_t *dco, u= nsigned int peerid, int keepalive_interval, int keepalive_timeout,
int mss)
{
stru= ct ifdrv drv;
nvlist_t *nvl;
int = ret;

= - msg(D_DCO_DEBUG, "%s: peer-id %d, ping interval %d, ping timeout = %d",
- __fu= nc__, peerid, keepalive_interval, keepalive_timeout);
+ msg(D_DCO_DEBUG, "%s: peer-id %d= , ping interval %d, ping timeout %d", __func__, peerid,
+ keepalive_interval, keepal= ive_timeout);


nvl =3D nvlist_create(= 0);
nvlist_add_number(nvl, "peerid", peerid)= ;
@@ -633,7 +627,8 @@
dco->= dco_message_type =3D OVPN_CMD_SWAP_KEYS;
break= ;

- = case OVPN_NOTIF_FLOAT: {
+ case OVPN_NOTIF_FLOAT:
+ {
const nvlist_t= *address;

if (!nvlist_exist= s_nvlist(nvl, "address"))
@@ -780,7 +775,6 @@
static void
dco_update_peer_stat(struct mult= i_context *m, uint32_t peerid, const nvlist_t *nvl)
{
-
if (= peerid >=3D m->max_clients || !m->instances[peerid])
{

msg(M_WARN, "dco_update_peer_stat: = invalid peer ID %d returned by kernel", peerid);
@@ -7= 96,7 +790,6 @@
int
dco_get_peer_stats_mul= ti(dco_context_t *dco, const bool raise_sigusr1_on_err)
{<= /span>
-
= struct ifdrv drv;
uint8_t *buf =3D NULL;
size_t buf_size =3D 4096;

diff --git a/src/openvpn/= dco_freebsd.h b/src/openvpn/dco_freebsd.h
index cbb1dda..2f= 486f0 100644
--- a/src/openvpn/dco_freebsd.h
+++ b/src/openvpn/dco_freebsd.h

@@ -26,26 +26,29 @@

#include "ovpn_dco_freebsd.h"

-#define D= CO_IROUTE_METRIC 100
-enum ovpn_message_type_t {
+enum ovpn_message_type_t
+{
OVPN_CMD_DEL_PEER,
OVPN_CMD_PACKET,
OVPN_CMD_SWAP_KEYS,<= /span>
OVPN_CMD_FLOAT_PEER,
};

-enum ovpn_del_rea= son_t {
+enum ovpn_de= l_reason_t
+{<= br> OVPN_DEL_PEER_REASON_EXPIRED,
OVPN_DEL_P= EER_REASON_TRANSPORT_ERROR,
OVPN_DEL_PEER_REASON_USERS= PACE,
OVPN_DEL_PEER_REASON_TRANSPORT_DISCONNECT,
};

-typedef struct dco_context {
+typedef struct dco_context
+{
bool open;
int fd;

int pipefd[2];
diff --g= it a/src/openvpn/dco_internal.h b/src/openvpn/dco_internal.h
index 96aa281..83013ef 100644

--- a/src/openvpn/dco_inter= nal.h
+++ b/src/openvpn/dco_internal.h
@@ -= 59,17 +59,14 @@
* They are implemented by dco_linux.c
*/

-int dco_new_peer(dco_context_t *dco, unsigned int peerid, int= sd,
- = struct sockaddr *localaddr, struct sockaddr *remoteaddr,
- struct in_addr *vpn_ipv= 4, struct in6_addr *vpn_ipv6);
+int dco_new_peer(dco_context_t *dco, unsigned int peerid, int sd= , struct sockaddr *localaddr,
+ struct sockaddr *remoteaddr, struct in_addr *vpn= _ipv4, struct in6_addr *vpn_ipv6);

int d= co_del_peer(dco_context_t *dco, unsigned int peerid);

-int dco_new_key(dco_conte= xt_t *dco, unsigned int peerid, int keyid,
- dco_key_slot_t slot,
- const uint8_t *encrypt_= key, const uint8_t *encrypt_iv,
- const uint8_t *decrypt_key, const uint8_t *decryp= t_iv,
- = const char *ciphername);
+int dco_new_key(dco_context_t *dco, unsigned int peerid, int keyid, dc= o_key_slot_t slot,
+ = const uint8_t *encrypt_key, const uint8_t *encrypt_iv, const= uint8_t *decrypt_key,
-#define nla_nest_st= art(_msg, _type) \
- = nla_nest_start(_msg, (_type) | NLA_F_NESTED)
+#define nla_nest_start(_msg, _type) nla_nest_star= t(_msg, (_type) | NLA_F_NESTED)

static i= nt ovpn_get_mcast_id(dco_context_t *dco);

@@ -89,8 +88,7 @@

ret =3D genl_connect(nl_sock);
if (ret)
{
- msg(msglevel, "Cannot connect to ge= neric netlink: %s",
+ msg(msglevel, "Cannot connect to generic netlink= : %s", nl_geterror(ret));
goto err_sock;
}
set_cloexec(nl_socket_get_fd(nl_soc= k));
@@ -98,8 +96,7 @@
ret =3D genl_ct= rl_resolve(nl_sock, OVPN_FAMILY_NAME);
if (ret < 0)=
{
- msg(msglevel, "Cannot find ovpn_dco netlink component: %s&qu= ot;,
- nl_ge= terror(ret));
+ = msg(msglevel, "Cannot find ovpn_dco netlink component: %s", nl_= geterror(ret));
}

e= rr_sock:
@@ -157,7 +154,8 @@
defau= lt:
if (ret)
{
- msg(M_NO= NFATAL, "%s: netlink reports error (%d): %s", prefix, ret, nl_get= error(-ret));
+ = msg(M_NONFATAL, "%s: netlink reports error (%d): %s", p= refix, ret,
+ = nl_geterror(-ret));
}
break;

}
@@ -188,8 +1= 86,8 @@

if (dco->status < 0)
{
-= msg(M_INFO, "%s: failed to send netlink message: %s (%d)"= ,
- prefix, = strerror(-dco->status), dco->status);
+ msg(M_INFO, "%s: failed to send netlin= k message: %s (%d)", prefix, strerror(-dco->status),
+ dco->status);
}

return dco->sta= tus;
@@ -201,7 +199,6 @@
struct sockad= dr_in6 *sock6 =3D (struct sockaddr_in6 *)sock;
if (soc= k->sa_family =3D=3D AF_INET6 && IN6_IS_ADDR_V4MAPPED(&sock6-= >sin6_addr))
{
-
struct sockaddr_in *sock4;
ALLOC_OBJ_CLEAR_GC(sock4, struct sockaddr_in, gc);

memcpy(&sock4->sin_addr, sock6->sin6_addr.s6= _addr + 12, 4);
@@ -213,9 +210,8 @@
}

int
-dco_new_peer(dco_context_t *dco, unsigned int peerid, int sd,<= /span>
- struct so= ckaddr *localaddr, struct sockaddr *remoteaddr,
- struct in_addr *vpn_ipv4, struct in6= _addr *vpn_ipv6)
+dco= _new_peer(dco_context_t *dco, unsigned int peerid, int sd, struct sockaddr = *localaddr,
+ = struct sockaddr *remoteaddr, struct in_addr *vpn_ipv4, struct in6_addr= *vpn_ipv6)
{
struct gc_arena gc =3D = gc_new();
const char *remotestr =3D "[undefined]&= quot;;
@@ -223,8 +219,7 @@
{ remotestr =3D print_sockaddr(remoteaddr, &gc); }
- msg= (D_DCO_DEBUG, "%s: peer-id %d, fd %d, remote addr: %s", __func__,=
- peerid, sd, r= emotestr);
+ msg(D= _DCO_DEBUG, "%s: peer-id %d, fd %d, remote addr: %s", __func__, p= eerid, sd, remotestr);

struct nl_msg= *nl_msg =3D ovpn_dco_nlmsg_create(dco, OVPN_CMD_PEER_NEW);
struct nlattr *attr =3D nla_nest_start(nl_msg, OVPN_A_PEER);
@@ -242,14 +237,17 @@
{
= NLA_PUT(nl_msg, OVPN_A_PEER_REMOTE_IPV4, sizeof(struct in_addr),=
&((struct sockaddr_in *)remoteadd= r)->sin_addr);
- = NLA_PUT_U16(nl_msg, OVPN_A_PEER_REMOTE_PORT, ((struct sockaddr_in *= )remoteaddr)->sin_port);
+ NLA_PUT_U16(nl_msg, OVPN_A_PEER_REMOTE_PORT,
= + ((stru= ct sockaddr_in *)remoteaddr)->sin_port);
}
else if (remoteaddr->sa_family =3D=3D AF_INET6)
{
NLA_PUT(nl_msg, OVPN_A= _PEER_REMOTE_IPV6, sizeof(struct in6_addr),
= &((struct sockaddr_in6 *)remoteaddr)->sin6_addr);
- NLA_PUT_U16(nl_msg, OV= PN_A_PEER_REMOTE_PORT, ((struct sockaddr_in6 *)remoteaddr)->sin6_port);<= /span>
- NLA_PUT_U3= 2(nl_msg, OVPN_A_PEER_REMOTE_IPV6_SCOPE_ID, ((struct sockaddr_in6 *)remotea= ddr)->sin6_scope_id);
+ NLA_PUT_U16(nl_msg, OVPN_A_PEER_REMOTE_PORT,
+ ((struct = sockaddr_in6 *)remoteaddr)->sin6_port);

+ NLA_PUT_U32(nl_msg, OVPN_A_PEER_REMOTE_I= PV6_SCOPE_ID,
+ = ((struct sockaddr_in6 *)remoteaddr)->sin6_scope_id);
}
}
@@ -275,8 +273,7 @@
}
if = (vpn_ipv6)
{
- NLA_PUT(nl_msg, OVPN_A_PEER_VPN_IPV6, sizeof(struct in6= _addr),
- = vpn_ipv6);
+ = NLA_PUT(nl_msg, OVPN_A_PEER_VPN_IPV6, sizeof(struct in6_addr), vpn_ipv6);<= /span>
}
nla_nest_end(nl_msg, attr);

@@ -289,7 +286,7 @@
}

static int
-ovpn_nl_cb_finish(struct nl_msg (*msg) __attribute__ ((u= nused)), void *arg)
+= ovpn_nl_cb_finish(struct nl_msg(*msg) __attribute__((unused)), void *arg)
{
int *status =3D arg;

@@ -310,7 +307,8 @@
* missing at the = message level
* @NLMSGERR_ATTR_MISS_NEST: offset of the n= est where attribute was missing
*/
-enum ovpn_nlmsgerr_attrs {
+enum ovpn_nlmsgerr_attrs
<= span style=3D"color: hsl(120, 100%, 40%);">+{

OVPN_NLM= SGERR_ATTR_MISS_TYPE =3D 5,
OVPN_NLMSGERR_ATTR_MISS_NE= ST =3D 6,
OVPN_NLMSGERR_ATTR_MAX =3D 6,
@@ -325,8 +323,7 @@

* reply to see if it contains a hum= an-readable error. If found, it is printed.
*/
= static int
-ovpn= _nl_cb_error(struct sockaddr_nl (*nla) __attribute__ ((unused)),
= - struct nlmsgerr= *err, void *arg)
+ov= pn_nl_cb_error(struct sockaddr_nl(*nla) __attribute__((unused)), struct nlm= sgerr *err, void *arg)
{
struct nlmsg= hdr *nlh =3D (struct nlmsghdr *)err - 1;
struct nlattr= *tb_msg[OVPN_NLMSGERR_ATTR_MAX + 1];
@@ -360,8 +357,7 @@
{
len =3D strnlen((char *)nla_= data(tb_msg[NLMSGERR_ATTR_MSG]),
nla= _len(tb_msg[NLMSGERR_ATTR_MSG]));
- msg(M_WARN, "kernel error: %*s", len,<= br>- (char *)nla_data(= tb_msg[NLMSGERR_ATTR_MSG]));
+ msg(M_WARN, "kernel error: %*s", len, (char *)nl= a_data(tb_msg[NLMSGERR_ATTR_MSG]));
}
=
if (tb_msg[OVPN_NLMSGERR_ATTR_MISS_NEST])
= @@ -387,7 +383,7 @@

if (dco-&g= t;ovpn_dco_mcast_id < 0)
{
- msg(M_FATAL, "cannot get mcast gr= oup: %s", nl_geterror(dco->ovpn_dco_mcast_id));
+ msg(M_FATAL, "cannot get = mcast group: %s", nl_geterror(dco->ovpn_dco_mcast_id));
<= span> }


/* Register for ovpn-dco= specific multicast messages that the kernel may
@@ -417,14= +413,12 @@
int ret =3D genl_connect(dco->nl_sock);=
if (ret)
{
- msg(M_FATAL, "Cannot connect t= o generic netlink: %s",
- nl_geterror(ret));
+ msg(M_FATAL, "Cannot connect to generic netl= ink: %s", nl_geterror(ret));
}
<= /span>
/* enable Extended ACK for detailed error reporting */=
ret =3D 1;
- setsockopt(nl_socket_get_fd(dco->nl_sock), SOL_NETLINK, N= ETLINK_EXT_ACK,
- = &ret, sizeof(ret));
+ setsockopt(nl_socket_get_fd(dco->nl_sock), SOL_NETLINK,= NETLINK_EXT_ACK, &ret, sizeof(ret));

/* set close on exec and non-block on the netlink socket */
set_cloexec(nl_socket_get_fd(dco->nl_sock));
@@ -440,10 +434,8 @@


dco->dco_me= ssage_peer_id =3D -1;
nl_cb_err(dco->nl_cb, NL_CB_C= USTOM, ovpn_nl_cb_error, &dco->status);
- nl_cb_set(dco->nl_cb, NL_CB_FINISH, NL_CB_C= USTOM, ovpn_nl_cb_finish,
- &dco->status);
- nl_cb_set(dco->nl_cb, NL_CB_ACK, NL_CB_CUSTOM, ovp= n_nl_cb_finish,
- = &dco->status);
+ nl_cb_set(dco->nl_cb, NL_CB_FINISH, NL_CB_CUSTOM, ovpn_nl_= cb_finish, &dco->status);
+ nl_cb_set(dco->nl_cb, NL_CB_ACK, NL_CB_CUSTOM, ovpn_nl_= cb_finish, &dco->status);
nl_cb_set(dco->nl_= cb, NL_CB_VALID, NL_CB_CUSTOM, ovpn_handle_msg, dco);

ovpn_dco_register(dco);
@@ -456,7 +448,7 = @@
/* nl library sets the buffer size to 32k/32k by de= fault which is sometimes
* overrun with very fast con= necting/disconnecting clients.
* TODO: fix this in a = better and more reliable way */
- ASSERT(!nl_socket_set_buffer_size(dco->nl_sock, 1024*1024,= 1024*1024));
+ AS= SERT(!nl_socket_set_buffer_size(dco->nl_sock, 1024 * 1024, 1024 * 1024))= ;
}

bool
@@ -578,8 +570,7 @@



= int
-dco_del_key(dco_co= ntext_t *dco, unsigned int peerid,
- dco_key_slot_t slot)
+dco_del_key(dco_context_t *dco, unsigned int peer= id, dco_key_slot_t slot)
{
int ret = =3D -EMSGSIZE;
msg(D_DCO_DEBUG, "%s: peer-id %d, = slot %d", __func__, peerid, slot);
@@ -603,14 +594,12 = @@
}

int
-dco_new_key(dco_context_t *dco, unsi= gned int peerid, int keyid,

- dco_key_slot_t slot,
- const uint8_t *encrypt_key, const uint8_t *enc= rypt_iv,
- c= onst uint8_t *decrypt_key, const uint8_t *decrypt_iv,
- const char *ciphername)<= br>+dco_new_key(dco_context_t *= dco, unsigned int peerid, int keyid, dco_key_slot_t slot,
+ const uint8_t *encrypt_ke= y, const uint8_t *encrypt_iv, const uint8_t *decrypt_key,
+ const uint8_t *decrypt_iv= , const char *ciphername)
{
- msg(D_DCO_DEBUG, "%s: slot %d, key-id %d, p= eer-id %d, cipher %s",
- __func__, slot, keyid, peerid, ciphername);
+ msg(D_DCO_DEBUG, "%s: slot %= d, key-id %d, peer-id %d, cipher %s", __func__, slot, keyid, peerid,
+ ciphername);<= /span>

const size_t key_len =3D cipher_kt_k= ey_size(ciphername);
const int nonce_tail_len =3D 8;
@@ -631,23 +620,19 @@
NLA_PUT_U32(nl_ms= g, OVPN_A_KEYCONF_KEY_ID, keyid);
NLA_PUT_U32(nl_msg, = OVPN_A_KEYCONF_CIPHER_ALG, dco_cipher);

- struct nlattr *key_enc =3D nla_nest= _start(nl_msg,
- = OVPN_A_KEYCONF_ENCRYPT_DIR);+ struct nlattr *key_enc = =3D nla_nest_start(nl_msg, OVPN_A_KEYCONF_ENCRYPT_DIR);
= if (dco_cipher !=3D OVPN_CIPHER_ALG_NONE)
{ NLA_PUT(nl_msg, OVPN_A_KEYDIR_CIPHER_KEY, key_len, encrypt= _key);
- NLA_PUT= (nl_msg, OVPN_A_KEYDIR_NONCE_TAIL, nonce_tail_len,
- encrypt_iv);
+ NLA_PUT(nl_msg, OVPN_A_KEYDIR= _NONCE_TAIL, nonce_tail_len, encrypt_iv);
}
= nla_nest_end(nl_msg, key_enc);

- struct nlattr *key_dec =3D nla_ne= st_start(nl_msg,

- = OVPN_A_KEYCONF_DECRYPT_DIR);<= br>+ struct nlattr *key_dec = =3D nla_nest_start(nl_msg, OVPN_A_KEYCONF_DECRYPT_DIR);
= if (dco_cipher !=3D OVPN_CIPHER_ALG_NONE)
{ NLA_PUT(nl_msg, OVPN_A_KEYDIR_CIPHER_KEY, key_len, decrypt= _key);
- NLA_PUT= (nl_msg, OVPN_A_KEYDIR_NONCE_TAIL, nonce_tail_len,
- decrypt_iv);
+ NLA_PUT(nl_msg, OVPN_A_KEYDIR= _NONCE_TAIL, nonce_tail_len, decrypt_iv);
}
= nla_nest_end(nl_msg, key_dec);

@@ -662,11 +647,11 @@

}

int

-dco_set_peer(dco= _context_t *dco, unsigned int peerid,
- int keepalive_interval, int keepalive_timeout,= int mss)
+dco_set_pe= er(dco_context_t *dco, unsigned int peerid, int keepalive_interval, int kee= palive_timeout,
+ = int mss)
{
- msg(D_DCO_DEBUG, "%s: peer-id %d, keepalive %d/%d, = mss %d", __func__,
- peerid, keepalive_interval, keepalive_timeout, mss);
+ msg(D_DCO_DEBUG, "%s: p= eer-id %d, keepalive %d/%d, mss %d", __func__, peerid,

+ keepalive_interval, keepali= ve_timeout, mss);


struct nl_msg *nl_= msg =3D ovpn_dco_nlmsg_create(dco, OVPN_CMD_PEER_SET);
= if (!nl_msg)
@@ -677,10 +662,8 @@
str= uct nlattr *attr =3D nla_nest_start(nl_msg, OVPN_A_PEER);
= int ret =3D -EMSGSIZE;
NLA_PUT_U32(nl_msg, OVPN_A_= PEER_ID, peerid);
- = NLA_PUT_U32(nl_msg, OVPN_A_PEER_KEEPALIVE_INTERVAL,
- keepalive_interval);=
- NLA_PUT_U32(nl_msg, OVPN= _A_PEER_KEEPALIVE_TIMEOUT,
- keepalive_timeout);
+ NLA_PUT_U32(nl_msg, OVPN_A_PEER_KEEPALIVE_INTERVAL= , keepalive_interval);
- nla_parse(tb, CTRL_ATTR_MAX, genlmsg_attrdata(gnlh, 0),<= br>- genlmsg_attrlen= (gnlh, 0), NULL);
+ = nla_parse(tb, CTRL_ATTR_MAX, genlmsg_attrdata(gnlh, 0), genlmsg_attrlen(g= nlh, 0), NULL);

if (!tb[CTRL_ATTR_MC= AST_GROUPS])
{
@@ -718,18 +700,16 @@
{
struct nlattr *tb_mcgrp[CTRL= _ATTR_MCAST_GRP_MAX + 1];

- nla_parse(tb_mcgrp, CTRL_ATTR_MCAST_GRP_MAX,<= /span>
- nla_= data(mcgrp), nla_len(mcgrp), NULL);
+ nla_parse(tb_mcgrp, CTRL_ATTR_MCAST_GRP_MAX, nla_da= ta(mcgrp), nla_len(mcgrp), NULL);

- if (!tb_mcgrp[CTRL_ATTR_MCAST_GRP_N= AME]
- || !t= b_mcgrp[CTRL_ATTR_MCAST_GRP_ID])
+ if (!tb_mcgrp[CTRL_ATTR_MCAST_GRP_NAME] || !tb_mcgrp[C= TRL_ATTR_MCAST_GRP_ID])
{
= continue;
}

- if (strncmp(nla_data(tb_mcgrp= [CTRL_ATTR_MCAST_GRP_NAME]),

- OVPN_MCGRP_PEERS,
- nla_len(tb_mcgrp[CTRL_ATTR_MCAST= _GRP_NAME])) !=3D 0)
= + if (strncmp(nla_data(tb_mcgrp[CTRL_ATTR_MCAST_GRP_NAME]), OVPN_MCG= RP_PEERS,
+ = nla_len(tb_mcgrp[CTRL_ATTR_MCAST_GRP_NAME]))
+ !=3D 0)
= {
continue;
}
@@ -829,49 +809,41 @@
if (tb[OVPN_A_PEER= _LINK_RX_BYTES])
{
c2->dco= _read_bytes =3D ovpn_nla_get_uint(tb[OVPN_A_PEER_LINK_RX_BYTES]);- msg(D_DCO_DEBUG, "= %s / dco_read_bytes: " counter_format, __func__,
- c2->dco_read_bytes);<= br>+ msg(D_DCO_DEBUG, &q= uot;%s / dco_read_bytes: " counter_format, __func__, c2->dco_read_b= ytes);
}
else
= {
- msg(M_WARN= , "%s: no link RX bytes provided in reply for peer %u",- __func__, id);
+ msg(M_WARN, &quo= t;%s: no link RX bytes provided in reply for peer %u", __func__, id);<= /span>
}

if (tb[OVPN_A= _PEER_LINK_TX_BYTES])
{
c2-&g= t;dco_write_bytes =3D ovpn_nla_get_uint(tb[OVPN_A_PEER_LINK_TX_BYTES]);
- msg(D_DCO_DEBUG, = "%s / dco_write_bytes: " counter_format, __func__,
- c2->dco_write_bytes);=

+ msg(D_DCO_D= EBUG, "%s / dco_write_bytes: " counter_format, __func__, c2->d= co_write_bytes);
}
else {
- = msg(M_WARN, "%s: no link TX bytes provided in reply for peer %u",=
- __func__,= id);
+ msg(M_= WARN, "%s: no link TX bytes provided in reply for peer %u", __fun= c__, id);
}

if = (tb[OVPN_A_PEER_VPN_RX_BYTES])
{
= c2->tun_read_bytes =3D ovpn_nla_get_uint(tb[OVPN_A_PEER_VPN_RX_BYTES= ]);
- msg(D_DCO_= DEBUG, "%s / tun_read_bytes: " counter_format, __func__,- c2->tun_read_by= tes);
+ msg(D_= DCO_DEBUG, "%s / tun_read_bytes: " counter_format, __func__, c2-&= gt;tun_read_bytes);
}
else=
{
- = msg(M_WARN, "%s: no VPN RX bytes provided in reply for peer %u"= ;,
- __func_= _, id);
+ msg(= M_WARN, "%s: no VPN RX bytes provided in reply for peer %u", __fu= nc__, id);
}

if= (tb[OVPN_A_PEER_VPN_TX_BYTES])
{
= c2->tun_write_bytes =3D ovpn_nla_get_uint(tb[OVPN_A_PEER_VPN_TX_BYT= ES]);
- msg(D_DC= O_DEBUG, "%s / tun_write_bytes: " counter_format, __func__,
- c2->tun_writ= e_bytes);
+ ms= g(D_DCO_DEBUG, "%s / tun_write_bytes: " counter_format, __func__,= c2->tun_write_bytes);
}
else<= /span>
{
= - msg(M_WARN, "%s: no VPN TX bytes provided in reply for peer %= u",
- _= _func__, id);
+ = msg(M_WARN, "%s: no VPN TX bytes provided in reply for peer %u"= , __func__, id);
}
}
=
@@ -945,8 +917,7 @@
uint32_t ifindex= =3D nla_get_u32(attrs[OVPN_A_IFINDEX]);
if (ifindex != =3D dco->ifindex)
{
- msg(D_DCO_DEBUG,
- "ovpn-dco: ignoring message for f= oreign ifindex %d", ifindex);
+ msg(D_DCO_DEBUG, "ovpn-dco: ignoring message fo= r foreign ifindex %d", ifindex);
return false= ;
}

@@ -968,8 +939,7= @@
}

struct nl= attr *dp_attrs[OVPN_A_PEER_MAX + 1];
- if (nla_parse_nested(dp_attrs, OVPN_A_PEER_MAX, attrs[OV= PN_A_PEER],
- = NULL))
+ if (nla_parse_nested(dp_attrs, OVPN_A_PEER_MAX, attrs[OVPN_A_PEER], N= ULL))
{
msg(D_DCO, "ovpn= -dco: can't parse peer in PEER_DEL_NTF messsage");
return NL_STOP;

@@ -1013,8 +983,7 @@
}


struct nlattr *fp_attrs[O= VPN_A_PEER_MAX + 1];
- = if (nla_parse_nested(fp_attrs, OVPN_A_PEER_MAX, attrs[OVPN_A_PEER],
- N= ULL))
+ if (nla_pa= rse_nested(fp_attrs, OVPN_A_PEER_MAX, attrs[OVPN_A_PEER], NULL))
= {
msg(D_DCO, "ovpn-dco: can't = parse peer in PEER_FLOAT_NTF messsage");
retu= rn NL_STOP;
@@ -1033,8 +1002,7 @@
}

struct gc_arena gc =3D gc_new();
- msg(D_DCO_DEBUG,=
- "ovpn-dco: rece= ived CMD_PEER_FLOAT_NTF, ifindex: %u, peer-id %u, address: %s",=
+ msg(D_DCO_DEBUG, "= ;ovpn-dco: received CMD_PEER_FLOAT_NTF, ifindex: %u, peer-id %u, address: %= s",
dco->ifindex, peerid, print_sockaddr((= struct sockaddr *)&dco->dco_float_peer_ss, &gc));
dco->dco_message_peer_id =3D (int)peerid;

dc= o->dco_message_type =3D OVPN_CMD_PEER_FLOAT_NTF;
@@ -105= 9,8 +1027,7 @@
}

= struct nlattr *dp_attrs[OVPN_A_KEYCONF_MAX + 1];
- if (nla_parse_nested(dp_attrs, OVPN_A_KEYC= ONF_MAX,
- = attrs[OVPN_A_KEYCONF], NULL))
+ if (nla_parse_nested(dp_attrs, OVPN_A_KEYCONF_MAX= , attrs[OVPN_A_KEYCONF], NULL))
{
= msg(D_DCO, "ovpn-dco: can't parse keyconf in KEY_SWAP_NTF mes= sage");
return NL_STOP;
@@ -1= 117,8 +1084,7 @@
return NL_STOP;
= }

- if (nla_parse(attrs, OVPN_A_MAX, genlmsg_attrdata(gnlh, 0),- genlmsg_attrl= en(gnlh, 0), NULL))
+= if (nla_parse(attrs, OVPN_A_MAX, genlmsg_attrdata(gnlh, 0), genlmsg_att= rlen(gnlh, 0), NULL))
{
msg(D= _DCO, "received bogus data from ovpn-dco");
= return NL_STOP;
@@ -1206,8 +1172,8 @@
= if (raise_sigusr1_on_err && ret < 0)
{<= /span>
msg(M_WARN, "Error retrieving DCO peer stats:= the underlying DCO peer"
- "may have been deleted from the kernel without no= tifying "
- = "userspace. Restarting the session");
+ "may have been d= eleted from the kernel without notifying "
+ "userspace. Restarting= the session");
register_signal(dco->c->= ;sig, SIGUSR1, "dco peer stats error");
}
return ret;
@@ -1230,8 +1196,7 @@=
{
if (resolve_ovpn_netlink_id(D_DCO_DEBUG) = < 0)
{
- msg(msglevel,
- "Note: Kernel support for ovpn-dco missing, disab= ling data channel offload.");
+ msg(msglevel, "Note: Kernel support for ovpn-dc= o missing, disabling data channel offload.");
= return false;
}

dif= f --git a/src/openvpn/dco_linux.h b/src/openvpn/dco_linux.h
index 9f15199..310d433 100644

--- a/src/openvpn/dco_linux.= h
+++ b/src/openvpn/dco_linux.h
@@ -31,8 +3= 1,8 @@
#include <netlink/netlink.h>
=
/* Defines to avoid mismatching with other platforms */<= /span>
-#define OVPN_CMD_DEL_P= EER OVPN_CMD_PEER_DEL_NTF
-#define OVPN_CMD_SWAP_KEYS OVPN_CMD_KEY_SWAP_NTF
+#define OVPN_CMD_DEL_PEER OVPN_CMD_PEER= _DEL_NTF
+#define OVP= N_CMD_SWAP_KEYS OVPN_CMD_KEY_SWAP_NTF
#define OVPN_CMD_FL= OAT_PEER OVPN_CMD_PEER_FLOAT_NTF

typedef= enum ovpn_key_slot dco_key_slot_t;
@@ -42,12 +42,14 @@

#ifndef IFLA_OVPN_MAX

-enum ovpn_mode {+enum ovpn_mode
+{

OVPN_MODE_= P2P,
OVPN_MODE_MP,
};

-enum ovpn_ifla_attr= s {
+enum ovpn_ifla_a= ttrs
+{
IFLA_OVPN_UNSPEC =3D 0,

IFLA_OVPN_MODE,=

diff --git a/src/openvpn/dco_win.c b/src/openvp= n/dco_win.c
index d227965..5317ac1 100644
-= -- a/src/openvpn/dco_win.c
+++ b/src/openvpn/dco_win.c
@@ -75,14 +75,12 @@

bool= res =3D false;

- HANDLE h =3D CreateFile("\\\\.\\ovpn-dco-ver", GE= NERIC_READ,
- = 0, NULL, OPEN_EXISTING, 0, NULL);
+ HANDLE h =3D CreateFile("\\\\.\\ovpn= -dco-ver", GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL);
<= span>

if (h =3D=3D INVALID_HANDLE_VALUE)
{

/* fallback to a "normal" dev= ice, this will fail if device is already in use */
- h =3D CreateFile("\\\\.\\ovpn-dco= ", GENERIC_READ,
-= 0, NULL, OPEN_EXISTING, 0, NULL);
+ h =3D CreateFile("\\\\.\\= ovpn-dco", GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL);
<= span> }


if (h =3D=3D INVALID_HAN= DLE_VALUE)
@@ -91,8 +89,8 @@
}<= br>
DWORD bytes_returned =3D 0;
- if (!DeviceIoControl(h, OVPN_IOCT= L_GET_VERSION, NULL, 0,

- version, sizeof(*version), &bytes_returned, = NULL))
+ if (!Devi= ceIoControl(h, OVPN_IOCTL_GET_VERSION, NULL, 0, version, sizeof(*version),<= /span>
+ = &bytes_returned, NULL))
{
= goto done;
}
@@ -145,7 +143,8 @@=
/* set mp mode */
OVPN_MODE m = =3D OVPN_MODE_MP;
DWORD bytes_returned =3D 0;- if (!DeviceIoControl(dco-&= gt;tt->hand, OVPN_IOCTL_SET_MODE, &m, sizeof(m), NULL, 0, &bytes= _returned, NULL))
+ = if (!DeviceIoControl(dco->tt->hand, OVPN_IOCTL_SET_MODE, &m, si= zeof(m), NULL, 0,
+ = &bytes_returned, NULL))
{
msg(M_ERR, "DeviceIoControl(OVPN_IOCTL_SET_MOD= E) failed");
}
@@ -221,7 +220,7 @= @
{
volatile int *signal_received =3D= &sig_info->signal_received;
/* GetOverlappedRe= sultEx is available starting from Windows 8 */
- typedef BOOL (WINAPI *get_overlapped_result_ex= _t)(HANDLE, LPOVERLAPPED, LPDWORD, DWORD, BOOL);
+ typedef BOOL(WINAPI * get_overlapped_resul= t_ex_t)(HANDLE, LPOVERLAPPED, LPDWORD, DWORD, BOOL);
g= et_overlapped_result_ex_t get_overlapped_result_ex =3D
= (get_overlapped_result_ex_t)GetProcAddress(GetModuleHandle("Kerne= l32.dll"),
= "GetOverlappedResultEx");
@@ -295,8 +294= ,8 @@
}
if (!cur)
{

- msg(M_= FATAL, "%s: Socket bind failed: Addr to bind has no %s record",
- __func__, a= ddr_family_name(ai_family));
+ msg(M_FATAL, "%s: Socket bind failed: Addr to bind ha= s no %s record", __func__,
+ addr_family_name(ai_family));
= }

OVPN_MP_START_VPN in, out;<= br>@@ -322,7 +321,8 @@
}
void
-dco_p2p_n= ew_peer(HANDLE handle, OVERLAPPED *ov, struct link_socket *sock, struct sig= nal_info *sig_info)
+= dco_p2p_new_peer(HANDLE handle, OVERLAPPED *ov, struct link_socket *sock,
+ stru= ct signal_info *sig_info)
{
msg(D_DCO= _DEBUG, "%s", __func__);

@@ -33= 3,8 +333,7 @@
struct sockaddr *local =3D NULL;<= br> struct sockaddr *remote =3D remoteaddr->ai_addr;
- if (remot= eaddr->ai_protocol =3D=3D IPPROTO_TCP
- || remoteaddr->ai_socktype =3D=3D SOCK_STREAM= )
+ if (remoteaddr= ->ai_protocol =3D=3D IPPROTO_TCP || remoteaddr->ai_socktype =3D=3D SO= CK_STREAM)
{
peer.Proto =3D O= VPN_PROTO_TCP;
}
@@ -406,15 +405,15 @@=
}
else
= {
- = dco_connect_wait(handle, ov, get_server_poll_remaining_time(sock->server= _poll_timeout), sig_info);
+ dco_connect_wait(handle, ov, get_server_poll_remaining_t= ime(sock->server_poll_timeout),
+ sig_info);
= }
}
}
int
-dco_new_p= eer(dco_context_t *dco, unsigned int peerid, int sd,
- struct sockaddr *localaddr, st= ruct sockaddr *remoteaddr,
- struct in_addr *vpn_ipv4, struct in6_addr *vpn_ipv6)
+dco_new_peer(dco_context= _t *dco, unsigned int peerid, int sd, struct sockaddr *localaddr,+ struct sockaddr = *remoteaddr, struct in_addr *vpn_ipv4, struct in6_addr *vpn_ipv6) {
msg(D_DCO_DEBUG, "%s: peer-id %d, fd %d= ", __func__, peerid, sd);

@@ -424,7 = +423,7 @@
return 0;
}<= br>
- OVPN_MP= _NEW_PEER newPeer =3D {0};
+ OVPN_MP_NEW_PEER newPeer =3D { 0 };

= if (remoteaddr)
{
@@ -454,7= +453,8 @@
newPeer.PeerId =3D peerid;
=
DWORD bytesReturned;
- if (!DeviceIoControl(dco->tt->hand, OVPN_IO= CTL_MP_NEW_PEER, &newPeer, sizeof(newPeer), NULL, 0, &bytesReturned= , NULL))
+ if (!De= viceIoControl(dco->tt->hand, OVPN_IOCTL_MP_NEW_PEER, &newPeer, si= zeof(newPeer), NULL, 0,
+ &bytesReturned, NULL))
= {
msg(M_ERR, "DeviceIoControl(OVPN_IOCTL_MP= _NEW_PEER) failed");
}
@@ -489,11= +489,11 @@
}

int
-dco_set_peer(dco_context_t = *dco, unsigned int peerid,
- int keepalive_interval, int keepalive_timeout, int mss)
+dco_set_peer(dco_cont= ext_t *dco, unsigned int peerid, int keepalive_interval, int keepalive_time= out,
+ in= t mss)
{
- msg(D_DCO_DEBUG, "%s: peer-id %d, keepalive %d/%d, mss %d"= ;, __func__,
- p= eerid, keepalive_interval, keepalive_timeout, mss);
+ msg(D_DCO_DEBUG, "%s: peer-id %d= , keepalive %d/%d, mss %d", __func__, peerid,
+ keepalive_interval, keepalive_timeou= t, mss);

OVPN_MP_SET_PEER mp_peer = =3D { peerid, keepalive_interval, keepalive_timeout, mss };
OVPN_SET_PEER peer =3D { keepalive_interval, keepalive_timeout, mss }= ;

@@ -523,14 +523,12 @@
}
=
int
= -dco_new_key(dco_context_t *dco, unsigned int peerid, int keyid,
= - dco_key_slot_t slot,=
- const uin= t8_t *encrypt_key, const uint8_t *encrypt_iv,
- const uint8_t *decrypt_key, const uint8= _t *decrypt_iv,
- = const char *ciphername)
+dco_new_key(dco_context_t *dco, unsigned int peerid, int keyid, d= co_key_slot_t slot,
+= const uint8_t *encrypt_key, const uint8_t *encrypt_iv, const ui= nt8_t *decrypt_key,
+= const uint8_t *decrypt_iv, const char *ciphername)
{

- msg(D_DCO_D= EBUG, "%s: slot %d, key-id %d, peer-id %d, cipher %s",
= - __func__, slot, keyid, p= eerid, ciphername);
+= msg(D_DCO_DEBUG, "%s: slot %d, key-id %d, peer-id %d, cipher %s&qu= ot;, __func__, slot, keyid, peerid,
+ ciphername);

= const int nonce_len =3D 8;
size_t key_len =3D cipher_= kt_key_size(ciphername);
@@ -555,8 +553,8 @@

DWORD bytes_returned =3D 0;

- if (!DeviceIoControl(d= co->tt->hand, OVPN_IOCTL_NEW_KEY, &crypto_data,
- sizeof(crypto_= data), NULL, 0, &bytes_returned, NULL))
+ if (!DeviceIoControl(dco->tt->hand, OVPN_= IOCTL_NEW_KEY, &crypto_data, sizeof(crypto_data), NULL,
+ 0, &by= tes_returned, NULL))

{
msg(M_= ERR, "DeviceIoControl(OVPN_IOCTL_NEW_KEY) failed");
return -1;

@@ -566,8 +564,7 @@
= int
dco_del_key(dco_context_t *dco, unsigned int peerid, = dco_key_slot_t slot)
{
- msg(D_DCO, "%s: peer-id %d, slot %d called but i= gnored", __func__, peerid,
- slot);
+ msg(D_DCO, "%s: peer-id %d, slot %d called but ignored",= __func__, peerid, slot);
/* FIXME: Implement in drive= r first */
return 0;
}
@@ -577,7 +574,7 @@

{
msg(D_DCO_DEB= UG, "%s: peer-id %d", __func__, peer_id);

- OVPN_MP_SWAP_KEYS swap = =3D {peer_id};
+ O= VPN_MP_SWAP_KEYS swap =3D { peer_id };
DWORD ioctl =3D= OVPN_IOCTL_SWAP_KEYS;
VOID *buf =3D NULL;
<= span> DWORD len =3D 0;

@@ -602,8 +599,8 @@
dco_available(int msglevel)

{
/*= try to open device by symbolic name */
- HANDLE h =3D CreateFile("\\\\.\\ovpn-dco", = GENERIC_READ | GENERIC_WRITE,
- 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_SY= STEM | FILE_FLAG_OVERLAPPED, NULL);
+ HANDLE h =3D CreateFile("\\\\.\\ovpn-dco", GE= NERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING,
+ FILE_ATTRIBUTE_= SYSTEM | FILE_FLAG_OVERLAPPED, NULL);

= if (h !=3D INVALID_HANDLE_VALUE)
{
@= @ -628,7 +625,7 @@
const char *
dco_versi= on_string(struct gc_arena *gc)
{
- OVPN_VERSION version =3D {0};
+ OVPN_VERSION version =3D { 0 = };

if (dco_get_version(&version))
= {
struct buffer out =3D alloc_buf_gc(256, gc)= ;
@@ -659,7 +656,8 @@
BOOL res =3D Get= OverlappedResult(dco->tt->hand, &dco->ov, &bytes_read, FAL= SE);
if (res)
{
- msg(D_DCO_DEBUG, "%s: comp= letion%s success [%ld]", __func__, queued ? "" : " non-= queued", bytes_read);
+ msg(D_DCO_DEBUG, "%s: completion%s success [%ld]",= __func__, queued ? "" : " non-queued",
+ bytes_read);

=
dco->dco_message_peer_id =3D dco->no= tif_buf.PeerId;
dco->dco_message_type =3D dco-&= gt;notif_buf.Cmd;
@@ -734,8 +732,8 @@
= ZeroMemory(&stats, sizeof(OVPN_STATS));

DWORD bytes_returned =3D 0;

- if (!DeviceIoControl(tt->hand, OVPN_IOCTL_GET_STATS, N= ULL, 0,
- = &stats, sizeof(stats), &bytes_returned, NULL))+ if (!DeviceIoControl(tt-&= gt;hand, OVPN_IOCTL_GET_STATS, NULL, 0, &stats, sizeof(stats),+ &am= p;bytes_returned, NULL))
{
ms= g(M_WARN | M_ERRNO, "DeviceIoControl(OVPN_IOCTL_GET_STATS) failed"= ;);
return -1;
@@ -765,7 +763,8 @@=
/* the overlapped IOCTL will signal this event on= I/O completion */
ASSERT(ResetEvent(dco->ov.hE= vent));

- if (!DeviceIoControl(dco->tt->hand, OVPN_IOCTL_NOTIFY_EVE= NT, NULL, 0, &dco->notif_buf, sizeof(dco->notif_buf), NULL, &= dco->ov))
+ = if (!DeviceIoControl(dco->tt->hand, OVPN_IOCTL_NOTIFY_EVENT, NULL, 0= , &dco->notif_buf,
+ sizeof(dco->notif_buf), NULL, &dc= o->ov))
{
DWORD er= r =3D GetLastError();
if (err =3D=3D ERROR_IO_= PENDING) /* operation queued? */
@@ -826,17 +825,21 @@
}

void
-dco_win_add_iroute_ipv4(dco_context_t *dco= , in_addr_t dst, unsigned int netbits, unsigned int peer_id)
+dco_win_add_iroute_ipv4(dco_contex= t_t *dco, in_addr_t dst, unsigned int netbits,

+ unsigned int peer_id)
{
struct gc_arena gc =3D gc_new();

- OVPN= _MP_IROUTE route =3D {.Addr.Addr4.S_un.S_addr =3D dst, .Netbits =3D netbits= , .PeerId =3D peer_id, .IPv6 =3D 0};
+ OVPN_MP_IROUTE route =3D {
+ .Addr.Addr4.S_un.S_addr =3D dst, .Netbi= ts =3D netbits, .PeerId =3D peer_id, .IPv6 =3D 0
+ };

- msg(D_DCO_DEBUG, "%s: %s/%d -> = peer %d", __func__, print_in_addr_t(dst, IA_NET_ORDER, &gc), netbi= ts, peer_id);
+ ms= g(D_DCO_DEBUG, "%s: %s/%d -> peer %d", __func__, print_in_addr= _t(dst, IA_NET_ORDER, &gc),
+ netbits, peer_id);

= DWORD bytes_returned =3D 0;
- if (!DeviceIoControl(dco->tt->hand, OVPN_IOCTL_MP_ADD_IR= OUTE, &route,
- = sizeof(route), NULL, 0, &bytes_returned, NULL))
+ if (!DeviceIoContr= ol(dco->tt->hand, OVPN_IOCTL_MP_ADD_IROUTE, &route, sizeof(route)= , NULL, 0,
+ = &bytes_returned, NULL))
{ msg(M_WARN | M_ERRNO, "DeviceIoControl(OVPN_IOCTL_MP_= ADD_IROUTE) failed");
}
@@ -845,1= 7 +848,19 @@
}

void
-dco_win_add_iroute_ipv6(d= co_context_t *dco, struct in6_addr dst, unsigned int netbits, unsigned int = peer_id)
+dco_win_add= _iroute_ipv6(dco_context_t *dco, struct in6_addr dst, unsigned int netbits,=
+ = unsigned int peer_id)
{
struct g= c_arena gc =3D gc_new();

OVPN_MP_IRO= UTE route =3D { .Addr.Addr6 =3D dst, .Netbits =3D netbits, .PeerId =3D peer= _id, .IPv6 =3D 1 };

- msg(D_DCO_DEBUG, "%s: %s/%d -> peer %d", _= _func__, print_in6_addr(dst, IA_NET_ORDER, &gc), netbits, peer_id);
+ msg(D_DCO_DEBUG, &q= uot;%s: %s/%d -> peer %d", __func__, print_in6_addr(dst, IA_NET_ORD= ER, &gc),
+ = netbits, peer_id);

DWORD bytes_ret= urned =3D 0;
- if (!= DeviceIoControl(dco->tt->hand, OVPN_IOCTL_MP_ADD_IROUTE, &route,<= /span>
- = sizeof(route), NULL, 0, &bytes_returned, NULL))
+ if (!DeviceIoControl(dco->tt->= hand, OVPN_IOCTL_MP_ADD_IROUTE, &route, sizeof(route), NULL, 0,<= br>+ &a= mp;bytes_returned, NULL))
{
m= sg(M_WARN | M_ERRNO, "DeviceIoControl(OVPN_IOCTL_MP_ADD_IROUTE) failed= ");
}
@@ -868,13 +873,15 @@
{
struct gc_arena gc =3D gc_new();<= br>
- OVPN_MP= _IROUTE route =3D { .Addr.Addr4.S_un.S_addr =3D dst, .Netbits =3D netbits, = .PeerId =3D -1, .IPv6 =3D 0 };
+ OVPN_MP_IROUTE route =3D {
+ .Addr.Addr4.S_un.S_addr =3D dst, .Netbits =3D= netbits, .PeerId =3D -1, .IPv6 =3D 0
+ };

msg(D_DCO_D= EBUG, "%s: %s/%d", __func__, print_in_addr_t(dst, IA_NET_ORDER, &= amp;gc), netbits);

DWORD bytes_retur= ned =3D 0;
- if (!De= viceIoControl(dco->tt->hand, OVPN_IOCTL_MP_DEL_IROUTE, &route,
- = sizeof(route), NULL, 0, &bytes_returned, NULL))
+ if (!DeviceIoControl(dco->tt->h= and, OVPN_IOCTL_MP_DEL_IROUTE, &route, sizeof(route), NULL, 0,+ &am= p;bytes_returned, NULL))
{
ms= g(M_WARN | M_ERRNO, "DeviceIoControl(OVPN_IOCTL_MP_DEL_IROUTE) failed&= quot;);
}
@@ -892,8 +899,8 @@ msg(D_DCO_DEBUG, "%s: %s/%d", __func__, print_in6_ad= dr(dst, IA_NET_ORDER, &gc), netbits);

DWORD bytes_returned =3D 0;

- if (!DeviceIoControl(dco->tt->hand, OVPN_IOCTL_MP_DEL= _IROUTE, &route,
- = sizeof(route), NULL, 0, &bytes_returned, NULL))=
+ if (!DeviceIoCo= ntrol(dco->tt->hand, OVPN_IOCTL_MP_DEL_IROUTE, &route, sizeof(rou= te), NULL, 0,
+ = &bytes_returned, NULL))
{
msg(M_WARN | M_ERRNO, "DeviceIoControl(OVPN_IOCTL_= MP_DEL_IROUTE) failed");
}
diff -= -git a/src/openvpn/dco_win.h b/src/openvpn/dco_win.h
index = 7311de8..a7f4865 100644
--- a/src/openvpn/dco_win.h<= br>+++ b/src/openvpn/dco_win.h
@@ -32,21 +32,23 @@
typedef OVPN_KEY_SLOT dco_key_slot_t;
typed= ef OVPN_CIPHER_ALG dco_cipher_t;

-typedef enum {
+typedef enum
+{
DCO_MODE_UNINIT,
= DCO_MODE_P2P,
DCO_MODE_MP
} dco_mo= de_type;

-struct dco_context {
+struct dco_context
+{
struct tuntap *tt;
dco_mod= e_type ifmode;

OVPN_NOTIFY_EVENT not= if_buf; /**< Buffer for incoming notifications. */
- OVERLAPPED ov; /**< Used by overlapp= ed I/O for async IOCTL. */
- int iostate; /**< State of overlapped I/O; see definitions in w= in32.h. */
- struct = rw_handle rwhandle; /**< Used to hook async I/O to the OpenVPN event loo= p. */
- int ov_ret; = /**< Win32 error code for overlapped operation, 0 for success */<= br>+ OVERLAPPED ov; = /**< Used by overlapped I/O for async IOCTL. */
+ int iostate; /**&l= t; State of overlapped I/O; see definitions in win32.h. */
+ struct rw_handle rwhandle; /**= < Used to hook async I/O to the OpenVPN event loop. */
+ int ov_ret; /**&= lt; Win32 error code for overlapped operation, 0 for success */
<= span>

int dco_message_peer_id;
i= nt dco_message_type;
@@ -59,31 +61,26 @@
<= /span>
typedef struct dco_context dco_context_t;
=
-void
-dco_mp_start_vpn(HANDLE handle, struc= t link_socket *sock);

+void dco_mp_start_vpn(HANDLE handle, struct link_socket *sock);
-void-dco_p2p_new_peer(HANDLE handle= , OVERLAPPED *ov, struct link_socket *sock, struct signal_info *sig_info);<= /span>
+void dco_p2p_new_pee= r(HANDLE handle, OVERLAPPED *ov, struct link_socket *sock,
+ struct signal_= info *sig_info);

-void
-dco_= start_tun(struct tuntap *tt);
+void dco_start_tun(struct tuntap *tt);
-bool
-dco_win_supports_multipeer(void);
+bool dco_win_supports_multipeer(v= oid);


-void
-dco_win_add_iro= ute_ipv4(dco_context_t *dco, in_addr_t dst, unsigned int netbits, unsigned = int peer_id);
+void d= co_win_add_iroute_ipv4(dco_context_t *dco, in_addr_t dst, unsigned int netb= its,
+ = unsigned int peer_id);

-void
-dco_win_add_iroute_ipv6(dco_context_t *dco, struct in6_addr= dst, unsigned int netbits, unsigned int peer_id);
+void dco_win_add_iroute_ipv6(dco_context_t *= dco, struct in6_addr dst, unsigned int netbits,
+ unsigned int peer_= id);

= -void
-dco_win_del_irou= te_ipv4(dco_context_t *dco, in_addr_t dst, unsigned int netbits);+void dco_win_del_iroute_ipv4(= dco_context_t *dco, in_addr_t dst, unsigned int netbits);
=
-void
-dco_win_del_iroute_ipv6(dco_context_t = *dco, struct in6_addr dst, unsigned int netbits);
+void dco_win_del_iroute_ipv6(dco_context_t *d= co, struct in6_addr dst, unsigned int netbits);
-#else /* if defined(ENABLE_DCO)= && defined(_WIN32) */
+#else /* if defined(ENABLE_DCO) && defined(_WIN32) */

static inline void
dco_s= tart_tun(struct tuntap *tt)
diff --git a/src/openvpn/dhcp.c= b/src/openvpn/dhcp.c
index df01412..0a7689f 100644<= br>--- a/src/openvpn/dhcp.c
+++ b/src/openvpn/dhcp.c<= /span>
@@ -35,37 +35,37 @@
static int
<= span> get_dhcp_message_type(const struct dhcp *dhcp, const int optlen)
{
- con= st uint8_t *p =3D (uint8_t *) (dhcp + 1);
+ const uint8_t *p =3D (uint8_t *)(dhcp + 1);
int i;

for (i =3D 0;= i < optlen; ++i)
{
const = uint8_t type =3D p[i];
const int room =3D optlen -= i;
- if (type = =3D=3D DHCP_END) /* didn't find what we were looking for */
+ if (type =3D=3D= DHCP_END) /* didn't find what we were looking for */
= {
return -1;
= }
- else if (typ= e =3D=3D DHCP_PAD) /* no-operation */
+ else if (type =3D=3D DHCP_PAD) /* no-operation= */
{
}
= else if (type =3D=3D DHCP_MSG_TYPE) /* what we are looking for */
{
if (room >=3D 3)<= /span>
{
- if (p[i+1] =3D=3D 1) /* option length should = be 1 */
+ = if (p[i + 1] =3D=3D 1) /* option length should be 1 */
{

- = return p[i+2]; /* return message type */
+ return p[i += 2]; /* return message type */

} }
return -1;
}

- = else /* some other option */
+ else /* some other option */
{
if (room >=3D 2)
{
- const int len =3D p[i+1]; /* get option length */
- i +=3D (l= en + 1); /* advance to next option */
+ const int len =3D p[i + 1]; /* get = option length */
+ = i +=3D (len + 1); /* advance to next option */
}
}
}=
@@ -75,11 +75,11 @@
static in_addr_t
do_extract(struct dhcp *dhcp, int optlen)
{
- uint8_t *p =3D (uin= t8_t *) (dhcp + 1);
+= uint8_t *p =3D (uint8_t *)(dhcp + 1);
int i;
in_addr_t ret =3D 0;

- for (i =3D 0; i < optlen; )<= br>+ for (i =3D 0; i < op= tlen;)
{
const uint8_t type = =3D p[i];
const int room =3D optlen - i;@@ -95,25 +95,25 @@
{
= if (room >=3D 2)
{
- const int len =3D p[i+= 1]; /* get option length */
- if (len <=3D (room-2))
+ const int len =3D p[i + 1]; /* = get option length */
= + if (len <=3D (room - 2))
= {
/* get router IP address */
if (!ret && len >=3D 4 &&= ; (len & 3) =3D=3D 0)
{
= - memcpy(&= amp;ret, p+i+2, 4);
+= memcpy(&ret, p + i + 2, 4);
= ret =3D ntohl(ret);
= }
{
= /* delete the router option */
= uint8_t *dest =3D p + i;
- const int owlen =3D len + 2; /* l= en of data to overwrite */
+ const int owlen =3D len + 2; /* len of data = to overwrite */
uint8_t *src =3D d= est + owlen;
uint8_t *end =3D p + = optlen;
const int movlen =3D end -= src;
if (movlen > 0) {
- memmove(dest, src, movlen); /* ov= erwrite router option */
+ memmove(dest, src, movlen); /* overw= rite router option */
}
= memset(end - owlen, DHCP_PAD, owlen); /* pad= tail */
}
@@ -128,12 = +128,12 @@
break;
= }
}
- else /* some other option */=
+ else /* som= e other option */
{
i= f (room >=3D 2)
{
- const int len =3D p[i+1]; /* ge= t option length */
- = i +=3D (len + 2); /* advance to next option */<= br>+ const int l= en =3D p[i + 1]; /* get option length */
+ i +=3D (len + 2); /* advance= to next option */
}
= else
{
@@ -147,13 +147,13 = @@
in_addr_t
dhcp_extract_router_msg(stru= ct buffer *ipbuf)
{
- struct dhcp_full *df =3D (struct dhcp_full *) BPTR(ipbuf= );
- const int optle= n =3D BLEN(ipbuf) - (sizeof(struct openvpn_iphdr) + sizeof(struct openvpn_u= dphdr) + sizeof(struct dhcp));
+ struct dhcp_full *df =3D (struct dhcp_full *)BPTR(ipbuf);
+ const int optlen = =3D
+ BLEN(ipb= uf)
+ - (sizeo= f(struct openvpn_iphdr) + sizeof(struct openvpn_udphdr) + sizeof(struct dhc= p));

= - if (optlen >=3D 0
- && df->ip.protocol =3D=3D OPENVPN_IPPROTO_UDP=
- && df->ud= p.source =3D=3D htons(BOOTPS_PORT)
- && df->udp.dest =3D=3D htons(BOOTPC_PORT)
+ if (optlen >= =3D 0 && df->ip.protocol =3D=3D OPENVPN_IPPROTO_UDP
+ && df->udp.so= urce =3D=3D htons(BOOTPS_PORT) && df->udp.dest =3D=3D htons(BOOT= PC_PORT)

&& df->dhcp.op =3D=3D BOOTREPL= Y)
{
const int message_type = =3D get_dhcp_message_type(&df->dhcp, optlen);
@@ -16= 4,10 +164,10 @@

/* recompute= the UDP checksum */
df->udp.check =3D 0;
- df->udp.= check =3D htons(ip_checksum(AF_INET, (uint8_t *)&df->udp,
= - = sizeof(struct openvpn_udphdr) + sizeof(struct dhcp) + optlen,=
- = (uint8_t *)&df->ip.saddr, (uint8_t *)&d= f->ip.daddr,
- = OPENVPN_IPPROTO_UDP));
+ df->udp.check =3D= htons(ip_checksum(

+= AF_INET, (uint8_t *)&df->udp,
+ sizeof(struct openvpn_udp= hdr) + sizeof(struct dhcp) + optlen,
+ (uint8_t *)&df->ip.saddr, (uint8_t = *)&df->ip.daddr, OPENVPN_IPPROTO_UDP));

= /* only return the extracted Router address if DHCPACK *= /
if (message_type =3D=3D DHCPACK)
<= span>diff --git a/src/openvpn/dhcp.h b/src/openvpn/dhcp.h

i= ndex 34f4513..af5c2c4 100644
--- a/src/openvpn/dhcp.h
+++ b/src/openvpn/dhcp.h
@@ -30,10 +30,10 @@
#pragma pack(1)

/* DHCP Op= tion types */
-#define = DHCP_PAD 0
-#d= efine DHCP_ROUTER 3
-#define DHCP_MSG_TYPE 53 /* message type (u8) */
-#define DHCP_END 255
+#define DHCP_PAD 0
+#define DHCP_ROUTER 3
+#define DHCP_MSG_TYPE 53= /* message type (u8) */
+#define DHCP_END 255

/* DHCP M= essages types */
#define DHCPDISCOVER 1
@@= -49,28 +49,30 @@
#define BOOTPS_PORT 67
= #define BOOTPC_PORT 68

-struct dhcp {
+struct dhcp
+{
#define BOOTREQUEST 1
#define BOOT= REPLY 2
- uint8_t = op; /* message op */
+ uint8_t op; /* message op */
- uint8_t htype; /* hard= ware address type (e.g. '1' =3D 10Mb Ethernet) */
- uint8_t hlen; /* hardware addr= ess length (e.g. '6' for 10Mb Ethernet) */
- uint8_t hops; /* client sets to 0, ma= y be used by relay agents */
- uint32_t xid; /* transaction ID, chosen by client */=
- uint16_t secs; /* se= conds since request process began, set by client */
+ uint8_t htype; /* hardware addre= ss type (e.g. '1' =3D 10Mb Ethernet) */
+ uint8_t hlen; /* hardware address len= gth (e.g. '6' for 10Mb Ethernet) */
+ uint8_t hops; /* client sets to 0, may be= used by relay agents */
+ uint32_t xid; /* transaction ID, chosen by client */<= br>+ uint16_t secs; /* = seconds since request process began, set by client */
= uint16_t flags;
- ui= nt32_t ciaddr; /* client IP address, client sets if known */
- uint32_t yiaddr; /* 'you= r' IP address -- server's response to client */

- uint32_t siaddr; /* server IP addre= ss */
- uint32_t gia= ddr; /* relay agent IP address */
+ uint32_t ciaddr; /* client IP address, client sets i= f known */
+ uint3= 2_t yiaddr; /* 'your' IP address -- server's response to cli= ent */
+ uint32_t = siaddr; /* server IP address */
+ uint32_t giaddr; /* relay agent IP address */<= br> uint8_t chaddr[16]; /* client hardware address */
<= span style=3D"color: hsl(0, 100%, 40%);">- uint8_t sname[64]; /* optiona= l server host name */

-= uint8_t file[128]; /* boot file name */
- uint32_t magic; /* must be 0x63825363 (network= order) */
+ uint8= _t sname[64]; /* optional server host name */
+ uint8_t file[128]; /* boot file name */
+ uint32_t magic; = /* must be 0x63825363 (network order) */
};

-struct dhcp_full = {
+struct dhcp_full
+{
= struct openvpn_iphdr ip;
struct openvpn_udphdr udp;<= /span>
struct dhcp dhcp;
diff --git a/src/ope= nvpn/dns.c b/src/openvpn/dns.c
index 22f4cec..8e28c2b 10064= 4
--- a/src/openvpn/dns.c
+++ b/src/openvpn= /dns.c
@@ -65,7 +65,7 @@
return fa= lse;
}

- char addrcopy[INET6_ADDRSTRLEN] =3D {0};=
+ char addrcopy[INET6_AD= DRSTRLEN] =3D { 0 };
size_t copylen =3D 0;
<= span> in_port_t port =3D 0;

sa_family_t af;=
@@ -202,13 +202,13 @@
bool
dns_= options_verify(int msglevel, const struct dns_options *o)
= {
- const struct dns= _server *server =3D
- = o->servers ? o->servers : o->servers_prepull;
+ const struct dns_server *serve= r =3D o->servers ? o->servers : o->servers_prepull;

while (server)

{
if (s= erver->addr_count =3D=3D 0)
{
- msg(msglevel, "ERROR: = dns server %ld does not have an address assigned", server->priority= );
+ msg(m= sglevel, "ERROR: dns server %ld does not have an address assigned"= ;,
+ s= erver->priority);
return false;
<= span> }

server =3D server->next;=
@@ -352,8 +352,8 @@
#ifdef _WIN32

static void
-make_domain_list(const char *what, const struct dns_domain *src,=
- bool= nrpt_domains, char *dst, size_t dst_size)
+make_domain_list(const char *what, const struct dns_= domain *src, bool nrpt_domains, char *dst,
+ size_t dst_size)
{=
/* NRPT domains need two \0 at the end for REG_MULTI_= SZ
* and a leading '.' added in front of the = domain name */
@@ -429,11 +429,8 @@

ack_message_t ack;
nrpt_dns_cfg_messag= e_t nrpt =3D {
- = .header =3D {
- = (add ? msg_add_nrpt_cfg : msg_del_nrpt_cfg),
- sizeof(nrpt_dns_cfg_message_t),
- 0
<= span style=3D"color: hsl(0, 100%, 40%);">- },

+ .header =3D { (add ? msg_add_nrpt= _cfg : msg_del_nrpt_cfg), sizeof(nrpt_dns_cfg_message_t),
+ 0 },
.iface =3D { .index =3D tt->adapter_index, .name =3D "= " },

.flags =3D server->dnssec =3D=3D DNS_= SECURITY_NO ? 0 : nrpt_dnssec,
};
@@ -= 447,33 +444,31 @@
break;
= }

- if (inet_ntop(server->addr[i].family, &server->addr[i].= in,
- = nrpt.addresses[i], NRPT_ADDR_SIZE) =3D=3D NULL)
+ if (inet_ntop(server->addr[i].= family, &server->addr[i].in, nrpt.addresses[i],
+ NRPT_ADDR_SIZE)
+ =3D=3D NUL= L)
{
msg(M_WARN, &quo= t;WARNING: could not convert dns server address");
= }
}

- make_domain_list("dns server resolve do= mains", server->domains, true,
- nrpt.resolve_domains, sizeof(nrpt.res= olve_domains));
+ = make_domain_list("dns server resolve domains", server->domains= , true, nrpt.resolve_domains,
+ sizeof(nrpt.resolve_domains));

- make_domain_l= ist("dns search domains", search_domains, false,
- nrpt.search_domai= ns, sizeof(nrpt.search_domains));
+ make_domain_list("dns search domains", search_d= omains, false, nrpt.search_domains,
+ sizeof(nrpt.search_domains));
msg(D_LOW, "%s NRPT DNS%s%s on '%s&= #39; (if_index =3D %d) using service",
(add ?= "Setting" : "Deleting"), nrpt.resolve_domains[0] !=3D = 0 ? ", resolve domains" : "",
- nrpt.search_domains[0] !=3D 0 ? ",= search domains" : "",
- nrpt.iface.name, nrpt.iface.index);
+ nrpt.search_domains[0] !=3D= 0 ? ", search domains" : "", nrpt.iface.name, nrpt.ifa= ce.index);


send_msg_iservice(o->m= sg_channel, &nrpt, sizeof(nrpt), &ack, "DNS");
= }

-#else /* ifdef _WIN32 */
+#else /* ifdef _WIN32 */

stat= ic void
-setenv_dns_opt= ion(struct env_set *es,
- const char *format, int i, int j,
- const char *value)=
+setenv_dns_option(struct e= nv_set *es, const char *format, int i, int j, const char *value)
= {
char name[64];
bool name= _ok =3D false;
@@ -539,14 +534,12 @@

if (s->dnssec)
{- setenv_dns_option(e= s, "dns_server_%d_dnssec", i, -1,
- dnssec_value(s->dnss= ec));
+ se= tenv_dns_option(es, "dns_server_%d_dnssec", i, -1, dnssec_value(s= ->dnssec));
}

if (s->transport)

{
- setenv_dns_option(es, "= ;dns_server_%d_transport", i, -1,
- transport_value(s->transp= ort));
+ s= etenv_dns_option(es, "dns_server_%d_transport", i, -1, transport_= value(s->transport));
}
= if (s->sni)
{
@@ -566,7 +559,= 8 @@
}

static int
-do_run_up_down_command(bool= up, const char *vars_file, const struct dns_options *o, const struct tunta= p *tt)
+do_run_up_dow= n_command(bool up, const char *vars_file, const struct dns_options *o,
+ c= onst struct tuntap *tt)
{
struct gc_a= rena gc =3D gc_new();
struct argv argv =3D argv_new();=
@@ -598,12 +592,12 @@
}
=
static bool
-run_updown_runner(bool up, struct options *o, const struct tuntap *= tt, struct dns_updown_runner_info *updown_runner)
+run_updown_runner(bool up, struct options *o,= const struct tuntap *tt,
+ struct dns_updown_runner_info *updown_runner)
{
int dns_pipe_fd[2];
= int ack_pipe_fd[2];
- = if (pipe(dns_pipe_fd) !=3D 0
- || pipe(ack_pipe_fd) !=3D 0)
+ if (pipe(dns_pipe_fd) !=3D 0 || pipe(ack_pip= e_fd) !=3D 0)
{
msg(M_ERR | M= _ERRNO, "run_dns_up_down: unable to create pipes");
return false;

@@ -631,8 +625,7 @@
/* Script runner process, close unused FDs */

= for (int fd =3D 3; fd < 100; ++fd)
{
- if (fd !=3D = dns_pipe_fd[0]
- = && fd !=3D ack_pipe_fd[1])
+ if (fd !=3D dns_pipe_fd[0] && f= d !=3D ack_pipe_fd[1])
{
= close(fd);
}
@@ -6= 93,7 +686,8 @@
}

static= void
-run_up_down_comm= and(bool up, struct options *o, const struct tuntap *tt, struct dns_updown_= runner_info *updown_runner)
+run_up_down_command(bool up, struct options *o, const struct tuntap= *tt,
+ = struct dns_updown_runner_info *updown_runner)
{
struct dns_options *dns =3D &o->dns_options;=
if (!dns->updown || (o->up_script && !dns_updo= wn_user_set(dns) && !dns_updown_forced(dns)))
@@ -8= 51,7 +845,8 @@
}

void
-run_dns_up_down(bool up= , struct options *o, const struct tuntap *tt, struct dns_updown_runner_info= *duri)
+run_dns_up_d= own(bool up, struct options *o, const struct tuntap *tt,
+ struct dns_updown_runn= er_info *duri)
{
if (!o->dns_optio= ns.servers)
{
@@ -881,14 +876,17 @@
}
if (bad_count =3D=3D s-&g= t;addr_count)
{
- msg(M_WARN, "DNS server %ld only has ad= dress(es) from a family "
+ msg(M_WARN,
+ "DNS server %ld only has address(es) fr= om a family "
"the tunnel is not= configured for - it will not be reachable",
= s->priority);
}
= else if (bad_count)
{
- msg(M_WARN, "DNS server %ld has= address(es) from a family "
- "the tunnel is not configured for", s= ->priority);
+ = msg(M_WARN,
+= "DNS server %ld has address(es) from a family "
+ "= ;the tunnel is not configured for",
+ s->priority);
= }
s =3D s->next;
}
diff --git a/src/openvpn/dns.h b/src/openvpn/dns.h
<= span>index 94c76e5..6d97b40 100644

--- a/src/openvpn/dns.h<= /span>
+++ b/src/openvpn/dns.h
@@ -27,33 +27,39 @@=
#include "env_set.h"
#include = "tun.h"

-enum dns_security {
+enum dns_security
+{
DNS_SECURITY_UNSET,
= DNS_SECURITY_NO,
DNS_SECURITY_YES,
= DNS_SECURITY_OPTIONAL
};

-enum dns_server_transport {
=
+enum dns_server_transport<= /span>
+{
= DNS_TRANSPORT_UNSET,
DNS_TRANSPORT_PLAIN, DNS_TRANSPORT_HTTPS,
DNS_TRANSPORT_TLS
};

-enum dns_updown_flags {
+enum dns_updown_flags
+{
DNS_UPDOWN_NO_FLAGS,
DNS_UPDOWN_USER_SET,

DNS_UPDOWN_FORCED=
};

-struct dns_domain {
+struct dns_domain
+{
struct dns_domain *next;
= const char *name;
};

-struct dns_server_addr {
- union {

+struct dns_server_addr
+{
+ union
+ {
struct in_addr a4;
= struct in6_addr a6;
} in;
@@ -61= ,7 +67,8 @@
in_port_t port;
};=

-struct dns= _server {
+struct dns= _server
+{
= struct dns_server *next;
long priority;
size_t addr_count;
@@ -72,7 +79,8 @@
const char *sni;
};

-struct dns_updown_runner_= info {
+struct dns_up= down_runner_info
+{
bool required;
int fds[2];<= br> #if !defined(_WIN32)
@@ -88,7 +96,8 @@
= #define N_SEARCH_LIST_LEN 10
#endif

-struct dhcp_options= {
+struct dhcp_optio= ns
+{
in_addr_t dns[N_DHCP_ADDR];

int dns_len;<= br>
@@ -100,7 +109,8 @@
int dom= ain_search_list_len;
};

-struct dns_options {
+struct dns_options
+{
struct dhcp_opt= ions from_dhcp;
struct dns_domain *search_domains;
struct dns_server *servers_prepull;
@@ -1= 65,8 +175,7 @@
* @param gc Pointer to the gc_a= rena to use for the clone
* @return The dns_= options clone
*/
-struct dns_options clone_dns_options(const struct dns_options = *o,
- = struct gc_arena *gc);
+struct dns_options clone_dns_options(const struct dns_= options *o, struct gc_arena *gc);

/**
* Saves and resets the server options, so that pulled ones = don't mix in.
diff --git a/src/openvpn/env_set.c b/src/= openvpn/env_set.c
index 7809237..6c7df8e 100644
<= span>--- a/src/openvpn/env_set.c

+++ b/src/openvpn/env_set.= c
@@ -246,7 +246,7 @@

= if (es)
{
- const struct env_item *item =3D es->list;
= + const struct env_item = *item =3D es->list;
while (item)
{

fputs(item->string, fp);
@@ -356,15 +356,10 @@
}

void
-seten= v_str_ex(struct env_set *es,
- const char *name,
- const char *value,
- const unsigned int name_include,<= /span>
- const un= signed int name_exclude,
- const unsigned int value_include,<= br>- const unsigned = int value_exclude,
- = const char value_replace)
+setenv_str_ex(struct env_set *es, const char *name, const = char *value,
+ = const unsigned int name_include, const unsigned int name_exclude,
+ const ch= ar name_replace, const unsigned int value_include,
+ const unsigned int value_exclu= de, const char value_replace)
{
struc= t gc_arena gc =3D gc_new();
const char *name_tmp;
@@ -442,9 +437,7 @@
/* Make arrays of strings = */

const char **
-make_env_array(const struct env_set *es,
- const boo= l check_allowed,
- = struct gc_arena *gc)
+make_env_array(const struct env_set *es, const bool check_allowe= d, struct gc_arena *gc)
{
char **ret = =3D NULL;
struct env_item *e =3D NULL;
@@ -460,7 +453,7 @@

}

/* alloc return array */

- ALLOC_ARRAY_CLEAR_GC(ret, char *, n+1, gc);
+ ALLOC_ARRAY_CLEAR_GC(ret, char *= , n + 1, gc);

/* fill return array *= /
if (es)
diff --git a/src/openvpn/env= _set.h b/src/openvpn/env_set.h
index 63237a7..3973a4e 10064= 4
--- a/src/openvpn/env_set.h
+++ b/src/ope= nvpn/env_set.h
@@ -33,26 +33,23 @@
* Hand= le environmental variable lists
*/

-struct env_item {+struct env_item
+{

char *str= ing;
struct env_item *next;
};=

-struct env= _set {
+struct env_se= t
+{
= struct gc_arena *gc;
struct env_item *list;
};

/* set/delete environment= al variable */
-void se= tenv_str_ex(struct env_set *es,
- const char *name,
- const char *value,
- const unsigned = int name_include,

- = const unsigned int name_exclude,
- const char name_replace,
- const un= signed int value_include,
- const unsigned int value_exclude,
- const char value_repl= ace);
+void setenv_st= r_ex(struct env_set *es, const char *name, const char *value,
+ const unsigned= int name_include, const unsigned int name_exclude,

+ const char name_replac= e, const unsigned int value_include,
+ const unsigned int value_exclude, const= char value_replace);

void setenv_counte= r(struct env_set *es, const char *name, counter_type value);

@@ -123,8 +120,7 @@
/* returns true if= environmental variable may be passed to an external program */
<= span> bool env_allowed(const char *str);


-const char **make_env_array(const stru= ct env_set *es,
- = const bool check_allowed,
+const char **make_env_array(const struct env_se= t *es, const bool check_allowed,
= struct gc_arena *gc);

#endif /* ifnde= f ENV_SET_H */
diff --git a/src/openvpn/errlevel.h b/src/op= envpn/errlevel.h
index e5e5b48..2d33d55 100644
--- a/src/openvpn/errlevel.h

+++ b/src/openvpn/errlevel= .h
@@ -49,134 +49,134 @@
* of output.
*/

-#define M_VERB0 LOGLEV(0, 0, 0) /* Messa= ges displayed even at --verb 0 (fatal errors only) */
+#define M_VERB0 LOGLEV(0, 0, 0) /* Messag= es displayed even at --verb 0 (fatal errors only) */

-#define M_INFO = LOGLEV(1, 0, 0) /* default informational messages */
<= span style=3D"color: hsl(120, 100%, 40%);">+#define M_INFO LOGLEV(1, 0, 0) = /* default informational messages */


-#define D_LINK_ERRORS LOGLEV(1, 1,= M_NONFATAL) /* show link errors from main event loop */
-#define D_CRYPT_ERRORS LOGLEV(1,= 2, M_NONFATAL) /* show errors from encrypt/decrypt */
-#define D_TLS_ERRORS LOGLEV(1, 3= , M_NONFATAL) /* show TLS control channel errors */
-#define D_RESOLVE_ERRORS LOGLEV(1, 4, M= _NONFATAL) /* show hostname resolve errors */
-#define D_COMP_ERRORS LOGLEV(1, 5, M_NONFA= TAL) /* show compression errors */
-#define D_REPLAY_ERRORS LOGLEV(1, 6, M_NONFATAL) /* s= how packet replay errors */
-#define D_STREAM_ERRORS LOGLEV(1, 7, M_NONFATAL) /* TCP strea= m error requiring restart */
-#define D_IMPORT_ERRORS LOGLEV(1, 8, M_NONFATAL) /* show ser= ver import option errors */
-#define D_MULTI_ERRORS LOGLEV(1, 9, M_NONFATAL) /* show mult= i-client server errors */
-#define D_EVENT_ERRORS LOGLEV(1, 10, M_NONFATAL) /* show event.= [ch] errors */
-#define= D_PUSH_ERRORS LOGLEV(1, 11, M_NONFATAL) /* show push/pull errors = */
-#define D_PID_PERSI= ST LOGLEV(1, 12, M_NONFATAL) /* show packet_id persist errors */
-#define D_FRAG_ERRORS = LOGLEV(1, 13, M_NONFATAL) /* show fragmentation errors */-#define D_ALIGN_ERRORS LO= GLEV(1, 14, M_NONFATAL) /* show bad struct alignments */
+#define D_LINK_ERRORS LOGLEV(1, 1= , M_NONFATAL) /* show link errors from main event loop */
+#define D_CRYPT_ERRORS LOGLEV(1, 2= , M_NONFATAL) /* show errors from encrypt/decrypt */
+#define D_TLS_ERRORS LOGLEV(1, 3, M_N= ONFATAL) /* show TLS control channel errors */
+#define D_RESOLVE_ERRORS LOGLEV(1, 4, M_NONFATA= L) /* show hostname resolve errors */
+#define D_COMP_ERRORS LOGLEV(1, 5, M_NONFATAL) /* sh= ow compression errors */
+#define D_REPLAY_ERRORS LOGLEV(1, 6, M_NONFATAL) /* show packet repl= ay errors */
+#define= D_STREAM_ERRORS LOGLEV(1, 7, M_NONFATAL) /* TCP stream error requiring r= estart */
+#define D_= IMPORT_ERRORS LOGLEV(1, 8, M_NONFATAL) /* show server import option error= s */
+#define D_MULTI= _ERRORS LOGLEV(1, 9, M_NONFATAL) /* show multi-client server errors */
+#define D_EVENT_ERROR= S LOGLEV(1, 10, M_NONFATAL) /* show event.[ch] errors */
+#define D_PUSH_ERRORS LOGLEV(1, 1= 1, M_NONFATAL) /* show push/pull errors */
+#define D_PID_PERSIST LOGLEV(1, 12, M_NONFATAL) /= * show packet_id persist errors */
+#define D_FRAG_ERRORS LOGLEV(1, 13, M_NONFATAL) /* show f= ragmentation errors */
-#define D_HANDSHAKE LOGLEV(2, 20, 0) /* show data &= amp; control channel handshakes */
-#define D_CLOSE LOGLEV(2, 22, 0) /* show s= ocket and TUN/TAP close */
-#define D_PROXY LOGLEV(2, 24, 0) /* show http prox= y control packets */
-#= define D_ARGV LOGLEV(2, 25, 0) /* show struct argv err= ors */
+#define D_HAN= DSHAKE LOGLEV(2, 20, 0) /* show data & control channel ha= ndshakes */
+#define = D_CLOSE LOGLEV(2, 22, 0) /* show socket and TUN/TAP close= */
+#define D_PROXY = LOGLEV(2, 24, 0) /* show http proxy control packets */
+#define D_ARGV LO= GLEV(2, 25, 0) /* show struct argv errors */
=
-#define D_TLS_DEBUG_= LOW LOGLEV(3, 20, 0) /* low frequency info from tls_session rou= tines */
-#define D_GRE= MLIN LOGLEV(3, 30, 0) /* show simulated outage info from = gremlin module */
-#def= ine D_GENKEY LOGLEV(3, 31, 0) /* print message after key= generation */
-#define= D_ROUTE LOGLEV(3, 0, 0) /* show routes added and dele= ted (don't mute) */
-#define D_TUNTAP_INFO LOGLEV(3, 32, 0) /* show debugging in= fo from TUN/TAP driver */
-#define D_RESTART LOGLEV(3, 33, 0) /* show certain re= start messages */
-#def= ine D_PUSH LOGLEV(3, 34, 0) /* show push/pull info */<= /span>
-#define D_IFCONFIG_POO= L LOGLEV(3, 35, 0) /* show ifconfig pool info */
-#define D_AUTH LOGLEV(= 3, 37, 0) /* show user/pass auth info */

-#define D_MULTI_LOW LOGLEV(3, 38, 0) = /* show point-to-multipoint low-freq debug info */
-#define D_PLUGIN LOGLEV(3, 39,= 0) /* show plugin calls */
-#define D_MANAGEMENT LOGLEV(3, 40, 0) /* show -= -management info */
-#d= efine D_SCHED_EXIT LOGLEV(3, 41, 0) /* show arming of schedu= led exit */
-#define D_= ROUTE_QUOTA LOGLEV(3, 42, 0) /* show route quota exceeded mes= sages */
-#define D_OSB= UF LOGLEV(3, 43, 0) /* show socket/tun/tap buffer sizes= */
-#define D_PS_PROXY= LOGLEV(3, 44, 0) /* messages related to --port-share opti= on */
-#define D_IFCONF= IG LOGLEV(3, 0, 0) /* show ifconfig info (don't mute)= */
-#define D_DCO = LOGLEV(3, 0, 0) /* show DCO related messages */+#define D_TLS_DEBUG_LOW LOGL= EV(3, 20, 0) /* low frequency info from tls_session routines */
+#define D_GREMLIN L= OGLEV(3, 30, 0) /* show simulated outage info from gremlin module */<= /span>
+#define D_GENKEY = LOGLEV(3, 31, 0) /* print message after key generation */<= br>+#define D_ROUTE LOG= LEV(3, 0, 0) /* show routes added and deleted (don't mute) */
+#define D_TUNTAP_INFO = LOGLEV(3, 32, 0) /* show debugging info from TUN/TAP driver */
+#define D_RESTART = LOGLEV(3, 33, 0) /* show certain restart messages */
+#define D_PUSH LOGLEV(3, 34= , 0) /* show push/pull info */
+#define D_IFCONFIG_POOL LOGLEV(3, 35, 0) /* show ifc= onfig pool info */
+#= define D_AUTH LOGLEV(3, 37, 0) /* show user/pass auth info *= /
+#define D_MULTI_LO= W LOGLEV(3, 38, 0) /* show point-to-multipoint low-freq debug inf= o */
+#define D_PLUGI= N LOGLEV(3, 39, 0) /* show plugin calls */
+#define D_MANAGEMENT LOGLEV(3, 40, 0= ) /* show --management info */
+#define D_SCHED_EXIT LOGLEV(3, 41, 0) /* show arm= ing of scheduled exit */
+#define D_ROUTE_QUOTA LOGLEV(3, 42, 0) /* show route quota exc= eeded messages */
+#d= efine D_OSBUF LOGLEV(3, 43, 0) /* show socket/tun/tap buffer = sizes */
+#define D_P= S_PROXY LOGLEV(3, 44, 0) /* messages related to --port-share opt= ion */
+#define D_IFC= ONFIG LOGLEV(3, 0, 0) /* show ifconfig info (don't mute) */=
+#define D_DCO = LOGLEV(3, 0, 0) /* show DCO related messages */

-#define D_SHOW_PARM= S LOGLEV(4, 50, 0) /* show all parameters on program initiat= ion */
-#define D_LOW = LOGLEV(4, 52, 0) /* miscellaneous low-frequency debug = info */
-#define D_DHCP= _OPT LOGLEV(4, 53, 0) /* show DHCP options binary string *= /
-#define D_MBUF = LOGLEV(4, 54, 0) /* mbuf.[ch] routines */
-#define D_PACKET_TRUNC_ERR LOGLEV(4, = 55, 0) /* PACKET_TRUNCATION_CHECK */
-#define D_MULTI_DROPPED LOGLEV(4, 57, 0) = /* show point-to-multipoint packet drops */
-#define D_MULTI_MEDIUM LOGLEV(4, 58, 0) = /* show medium frequency multi messages */
-#define D_X509_ATTR LOGLEV(4, 59, 0) /= * show x509-track attributes on connection */
-#define D_INIT_MEDIUM LOGLEV(4, 60, 0) = /* show medium frequency init messages */
-#define D_MTU_INFO LOGLEV(4, 61, 0) = /* show terse MTU info */
-#define D_PID_DEBUG_LOW LOGLEV(4, 63, 0) /* show low-freq p= acket-id debugging info */
-#define D_PID_DEBUG_MEDIUM LOGLEV(4, 64, 0) /* show medium-fr= eq packet-id debugging info */
-#define D_CIPHER_INIT LOGLEV(4, 65, 0) /* show messa= ges about cipher init */
+#define D_SHOW_PARMS LOGLEV(4, 50, 0) /* show all parameters = on program initiation */
+#define D_LOW LOGLEV(4, 52, 0) /* miscellaneous low-fr= equency debug info */
+#define D_DHCP_OPT LOGLEV(4, 53, 0) /* show DHCP options binar= y string */
+#define = D_MBUF LOGLEV(4, 54, 0) /* mbuf.[ch] routines */
<= span style=3D"color: hsl(120, 100%, 40%);">+#define D_PACKET_TRUNC_ERR LOGL= EV(4, 55, 0) /* PACKET_TRUNCATION_CHECK */

+#define D_MULTI_DROPPED LOGLEV(4, 57, 0) /*= show point-to-multipoint packet drops */
+#define D_MULTI_MEDIUM LOGLEV(4, 58, 0) /* sho= w medium frequency multi messages */
+#define D_X509_ATTR LOGLEV(4, 59, 0) /* show x50= 9-track attributes on connection */
+#define D_INIT_MEDIUM LOGLEV(4, 60, 0) /* show medi= um frequency init messages */
+#define D_MTU_INFO LOGLEV(4, 61, 0) /* show terse MTU = info */
+#define D_PI= D_DEBUG_LOW LOGLEV(4, 63, 0) /* show low-freq packet-id debugging inf= o */
+#define D_PID_D= EBUG_MEDIUM LOGLEV(4, 64, 0) /* show medium-freq packet-id debugging inf= o */
+#define D_CIPHE= R_INIT LOGLEV(4, 65, 0) /* show messages about cipher init */

-#define D= _LOG_RW LOGLEV(5, 0, 0) /* Print 'R' or 'W&= #39; to stdout for read/write */
+#define D_LOG_RW LOGLEV(5, 0, 0) /* Print 'R= ' or 'W' to stdout for read/write */
-#define D_RTNL L= OGLEV(6, 68, M_DEBUG) /* show RTNL low level operations */
-#define D_LINK_RW LOGLEV(6= , 69, M_DEBUG) /* show TCP/UDP reads/writes (terse) */

-#define D_TUN_RW LOGLEV(6, 69= , M_DEBUG) /* show TUN/TAP reads/writes */
-#define D_TAP_WIN_DEBUG LOGLEV(6, 69, M_DEBUG) = /* show TAP-Windows driver debug info */
-#define D_CLIENT_NAT LOGLEV(6, 69, M_DEBUG) /* = show client NAT debug info */
-#define D_XKEY LOGLEV(6, 69, M_DEBUG) /* show xkey-p= rovider debug info */
-= #define D_DCO_DEBUG LOGLEV(6, 69, M_DEBUG) /* show DCO related lo= wlevel debug messages */
+#define D_RTNL LOGLEV(6, 68, M_DEBUG) /* show RTNL low level ope= rations */
+#define D= _LINK_RW LOGLEV(6, 69, M_DEBUG) /* show TCP/UDP reads/writes (terse) = */
+#define D_TUN_RW = LOGLEV(6, 69, M_DEBUG) /* show TUN/TAP reads/writes */
+#define D_TAP_WIN_DEBUG LOGLEV(6,= 69, M_DEBUG) /* show TAP-Windows driver debug info */

+#define D_CLIENT_NAT LOGLEV(6, 69, M_= DEBUG) /* show client NAT debug info */
+#define D_XKEY LOGLEV(6, 69, M_DEBUG) /* show = xkey-provider debug info */
+#define D_DCO_DEBUG LOGLEV(6, 69, M_DEBUG) /* show DCO related = lowlevel debug messages */
+#define D_SIGNAL_DEBUG LOGLEV(6, 69, M_DEBUG) /* show signal relate= d debug messages */

-#define D_SHOW_KEYS LOGLEV(7, 70, M_DEBUG) /* sho= w data channel encryption keys */
-#define D_SHOW_KEY_SOURCE LOGLEV(7, 70, M_DEBUG) /* show da= ta channel key source entropy */
-#define D_REL_LOW LOGLEV(7, 70, M_DEBUG) /* show low= frequency info from reliable layer */
-#define D_FRAG_DEBUG LOGLEV(7, 70, M_DEBUG) /* sh= ow fragment debugging info */
-#define D_WIN32_IO_LOW LOGLEV(7, 70, M_DEBUG) /* low freq wi= n32 I/O debugging info */
-#define D_MTU_DEBUG LOGLEV(7, 70, M_DEBUG) /* show MTU debugg= ing info */
-#define D_= MULTI_DEBUG LOGLEV(7, 70, M_DEBUG) /* show medium-freq multi debugg= ing info */
-#define D_= MSS LOGLEV(7, 70, M_DEBUG) /* show MSS adjustments */
-#define D_COMP_LOW = LOGLEV(7, 70, M_DEBUG) /* show adaptive compression state changes */
-#define D_CONNECTION_LIST= LOGLEV(7, 70, M_DEBUG) /* show <connection> list info */<= br>-#define D_SCRIPT = LOGLEV(7, 70, M_DEBUG) /* show parms & env vars passed to scripts */
-#define D_SHOW_NET = LOGLEV(7, 70, M_DEBUG) /* show routing table and adapter list */
-#define D_ROUTE_DEBUG = LOGLEV(7, 70, M_DEBUG) /* show verbose route.[ch] output */
= -#define D_TLS_STATE_ERRORS LOG= LEV(7, 70, M_DEBUG) /* no TLS state for client */
-#define D_SEMAPHORE_LOW LOGLEV(7, 70, M_D= EBUG) /* show Win32 semaphore waits (low freq) */
-#define D_SEMAPHORE LOGLEV(7, 70, M_D= EBUG) /* show Win32 semaphore waits */
-#define D_TEST_FILE LOGLEV(7, 70, M_DEBUG) /* s= how test_file() calls */
-#defin= e D_PLUGIN_DEBUG LOGLEV(7, 70, M_DEBUG) /* show verbose plugin calls= */
-#define D_SOCKET_D= EBUG LOGLEV(7, 70, M_DEBUG) /* show socket.[ch] debugging info */
-#define D_SHOW_PKCS11 = LOGLEV(7, 70, M_DEBUG) /* show PKCS#11 actions */
-#define D_ALIGN_DEBUG LOGLEV(7, 70= , M_DEBUG) /* show verbose struct alignment info */
-#define D_PACKET_TRUNC_DEBUG LOGLEV(7, 70, = M_DEBUG) /* PACKET_TRUNCATION_CHECK verbose */
-#define D_PING LOGLEV(7, 70, M_DEBU= G) /* PING send/receive messages */
-#define D_PS_PROXY_DEBUG LOGLEV(7, 70, M_DEBUG) /* port= share proxy debug */
-= #define D_TLS_KEYSELECT LOGLEV(7, 70, M_DEBUG) /* show key selection = for data channel */
-#d= efine D_ARGV_PARSE_CMD LOGLEV(7, 70, M_DEBUG) /* show parse_line() err= ors in argv_parse_cmd */
-#define D_PID_DEBUG LOGLEV(7, 70, M_DEBUG) /* show packet-= id debugging info */
-#= define D_PUSH_DEBUG LOGLEV(7, 73, M_DEBUG) /* show push/pull debug= ging info */
-#define D= _SHOW_OCC LOGLEV(7, 74, M_DEBUG) /* show options compatibility s= tring */
+#define D_S= HOW_KEYS LOGLEV(7, 70, M_DEBUG) /* show data channel encryption ke= ys */
+#define D_SHOW= _KEY_SOURCE LOGLEV(7, 70, M_DEBUG) /* show data channel key source entro= py */
+#define D_REL_= LOW LOGLEV(7, 70, M_DEBUG) /* show low frequency info from relia= ble layer */
+#define= D_FRAG_DEBUG LOGLEV(7, 70, M_DEBUG) /* show fragment debugging inf= o */
+#define D_WIN32= _IO_LOW LOGLEV(7, 70, M_DEBUG) /* low freq win32 I/O debugging info *= /
+#define D_MTU_DEBU= G LOGLEV(7, 70, M_DEBUG) /* show MTU debugging info */
<= span style=3D"color: hsl(120, 100%, 40%);">+#define D_MULTI_DEBUG LO= GLEV(7, 70, M_DEBUG) /* show medium-freq multi debugging info */

= +#define D_MSS L= OGLEV(7, 70, M_DEBUG) /* show MSS adjustments */
+#define D_COMP_LOW LOGLEV(7, 70, M_D= EBUG) /* show adaptive compression state changes */
+#define D_CONNECTION_LIST LOGLEV(7, 70= , M_DEBUG) /* show <connection> list info */
+#define D_SCRIPT LOGLEV(7, 70, M= _DEBUG) /* show parms & env vars passed to scripts */
+#define D_SHOW_NET LOGLEV(7= , 70, M_DEBUG) /* show routing table and adapter list */
+#define D_ROUTE_DEBUG LOGLEV(7,= 70, M_DEBUG) /* show verbose route.[ch] output */
+#define D_TLS_STATE_ERRORS LOGLEV(7, 70, M= _DEBUG) /* no TLS state for client */
+#define D_SEMAPHORE_LOW LOGLEV(7, 70, M_DEBUG) /* sh= ow Win32 semaphore waits (low freq) */
+#define D_SEMAPHORE LOGLEV(7, 70, M_DEBUG) /* s= how Win32 semaphore waits */
+#define D_TEST_FILE LOGLEV(7, 70, M_DEBUG) /* show test_f= ile() calls */
+#defi= ne D_MANAGEMENT_DEBUG LOGLEV(3, 70, M_DEBUG) /* show --management debug i= nfo */
+#define D_PLU= GIN_DEBUG LOGLEV(7, 70, M_DEBUG) /* show verbose plugin calls */
+#define D_SOCKET_DEBUG = LOGLEV(7, 70, M_DEBUG) /* show socket.[ch] debugging info */+#define D_SHOW_PKCS11 = LOGLEV(7, 70, M_DEBUG) /* show PKCS#11 actions */
+#define D_ALIGN_DEBUG LOGLEV(7, 70, M_= DEBUG) /* show verbose struct alignment info */
+#define D_PACKET_TRUNC_DEBUG LOGLEV(7, 70, M_DE= BUG) /* PACKET_TRUNCATION_CHECK verbose */
+#define D_PING LOGLEV(7, 70, M_DEBUG) = /* PING send/receive messages */
+#define D_PS_PROXY_DEBUG LOGLEV(7, 70, M_DEBUG) /* port sh= are proxy debug */
+#= define D_TLS_KEYSELECT LOGLEV(7, 70, M_DEBUG) /* show key selection fo= r data channel */
+#d= efine D_ARGV_PARSE_CMD LOGLEV(7, 70, M_DEBUG) /* show parse_line() erro= rs in argv_parse_cmd */
+#define D_CRYPTO_DEBUG LOGLEV(7, 70, M_DEBUG) /* show detailed in= fo from crypto.c routines */
+#define D_PID_DEBUG LOGLEV(7, 70, M_DEBUG) /* show packet= -id debugging info */
+#define D_PUSH_DEBUG LOGLEV(7, 73, M_DEBUG) /* show push/pull deb= ugging info */
+#defi= ne D_SHOW_OCC LOGLEV(7, 74, M_DEBUG) /* show options compatibilit= y string */


-#define D_VLAN_DEBUG LOGLEV(7, 74, M_DEBU= G) /* show VLAN tagging/untagging debug info */
+#define D_VLAN_DEBUG LOGLEV(7, 74, M_DEBUG) = /* show VLAN tagging/untagging debug info */
<= br>-#define D_HANDSHAKE_VERBOSE = LOGLEV(8, 70, M_DEBUG) /* show detailed description of handshake */=
-#define D_TLS_DEBUG_MED = LOGLEV(8, 70, M_DEBUG) /* limited info from tls_session routines */
-#define D_INTERVAL = LOGLEV(8, 70, M_DEBUG) /* show interval.h debugging info */
-#define D_SCHEDULER LOGLE= V(8, 70, M_DEBUG) /* show scheduler debugging info */

-#define D_GREMLIN_VERBOSE LOGLEV(8, 70,= M_DEBUG) /* show verbose info from gremlin module */
-#define D_REL_DEBUG LOGLEV(8, 70,= M_DEBUG) /* show detailed info from reliable routines */
-#define D_EVENT_WAIT LOGLEV(8,= 70, M_DEBUG) /* show detailed info from event waits */
-#define D_MULTI_TCP LOGLEV(8, 7= 0, M_DEBUG) /* show debug info from mtcp.c */
+#define D_HANDSHAKE_VERBOSE LOGLEV(8, 70, M_DEBU= G) /* show detailed description of handshake */
+#define D_TLS_DEBUG_MED LOGLEV(8, 70, M_DEB= UG) /* limited info from tls_session routines */
+#define D_INTERVAL LOGLEV(8, 70, M_DE= BUG) /* show interval.h debugging info */
+#define D_SCHEDULER LOGLEV(8, 70, M_DEBUG) /*= show scheduler debugging info */
+#define D_GREMLIN_VERBOSE LOGLEV(8, 70, M_DEBUG) /* show ve= rbose info from gremlin module */
+#define D_REL_DEBUG LOGLEV(8, 70, M_DEBUG) /* show de= tailed info from reliable routines */
+#define D_EVENT_WAIT LOGLEV(8, 70, M_DEBUG) /* sho= w detailed info from event waits */
+#define D_MULTI_TCP LOGLEV(8, 70, M_DEBUG) /* show = debug info from mtcp.c */

-#define D_TLS_DEBUG LOGLEV(9, 70, M_DEBUG) = /* show detailed info from TLS routines */
-#define D_COMP LOGLEV(9, 70, M_DEBUG) /= * show compression info */
-#define D_READ_WRITE LOGLEV(9, 70, M_DEBUG) /* show all tun/t= cp/udp reads/writes/opens */
-#define D_PACKET_CONTENT LOGLEV(9, 70, M_DEBUG) /* show before/= after encryption packet content */
-#define D_TLS_NO_SEND_KEY LOGLEV(9, 70, M_DEBUG) /* show w= hen no data channel send-key exists */
-#define D_PID_PERSIST_DEBUG LOGLEV(9, 70, M_DEBUG) /* sh= ow packet-id persist debugging info */
-#define D_LINK_RW_VERBOSE LOGLEV(9, 70, M_DEBUG) /* in= crease link reads/writes verbosity */
-#define D_STREAM_DEBUG LOGLEV(9, 70, M_DEBUG) /* sho= w TCP stream debug info */
-#define D_WIN32_IO LOGLEV(9, 70, M_DEBUG) /* win32 I/O debu= gging info */
-#define = D_PKCS11_DEBUG LOGLEV(9, 70, M_DEBUG) /* show PKCS#11 debugging */
+#define D_TLS_DEBUG = LOGLEV(9, 70, M_DEBUG) /* show detailed info from TLS routines */
+#define D_COMP = LOGLEV(9, 70, M_DEBUG) /* show compression info */
+#define D_READ_WRITE LOGLEV(9, = 70, M_DEBUG) /* show all tun/tcp/udp reads/writes/opens */
+#define D_PACKET_CONTENT LOGLEV(9= , 70, M_DEBUG) /* show before/after encryption packet content */
= +#define D_TLS_NO_SEND_KEY LO= GLEV(9, 70, M_DEBUG) /* show when no data channel send-key exists */=
+#define D_PID_PERSIST_DEBU= G LOGLEV(9, 70, M_DEBUG) /* show packet-id persist debugging info */=
+#define D_LINK_RW_VERBOSE = LOGLEV(9, 70, M_DEBUG) /* increase link reads/writes verbosity */<= br>+#define D_STREAM_DEBUG = LOGLEV(9, 70, M_DEBUG) /* show TCP stream debug info */
+#define D_WIN32_IO LOGLEV(9, = 70, M_DEBUG) /* win32 I/O debugging info */
+#define D_PKCS11_DEBUG LOGLEV(9, 70, M_DEBUG) = /* show PKCS#11 debugging */

-#define D_SHAPER_DEBUG LOGLEV(10, 70, M_DEBU= G) /* show traffic shaper info */
+#define D_SHAPER_DEBUG LOGLEV(10, 70, M_DEBUG) /* show tr= affic shaper info */

-#define D_REGISTRY LOGLEV(11, 70, M_DEBUG) /* wi= n32 registry debugging info */
-#define D_OPENSSL_LOCK LOGLEV(11, 70, M_DEBUG) /* show OpenS= SL locks */
+#define = D_REGISTRY LOGLEV(11, 70, M_DEBUG) /* win32 registry debugging info= */
+#define D_OPENSS= L_LOCK LOGLEV(11, 70, M_DEBUG) /* show OpenSSL locks */

-/*#define D_THREAD_= DEBUG LOGLEV(4, 70, M_DEBUG)*/ /* show pthread debug information */<= /span>
+/*#define D_THREAD_D= EBUG LOGLEV(4, 70, M_DEBUG)*/ /* show pthread debug information */

-#endif= /* ifndef ERRLEVEL_H */
+#endif /* ifndef ERRL= EVEL_H */
diff --git a/src/openvpn/error.c b/src/openvpn/er= ror.c
index 22c339f..dacfa8f 100644
--- a/s= rc/openvpn/error.c
+++ b/src/openvpn/error.c
@@ -51,9 +51,9 @@

unsigned int x_debug_level; /* GLOBAL = */

/* Mute state */
-static int mute_cutoff; /* GLOBAL */
-static int mute_count; = /* GLOBAL */
-stat= ic int mute_category; /* GLOBAL */
+static int mute_cutoff; /* GLOBAL */
+static int mute_count; /* GLOBAL */<= /span>
+static int mute_cate= gory; /* GLOBAL */

/*
= * Output mode priorities are as follows:
@@ -67,28 +67,28 @= @

/* If true, indicates that stdin/stdou= t/stderr
* have been redirected due to --log */-static bool std_redir; /* = GLOBAL */
+static boo= l std_redir; /* GLOBAL */

/* Should mess= ages be written to the syslog? */
-static bool use_syslog; /* GLOBAL */
+static bool use_syslog; /* GLOBAL */

/* Should stdout/stderr be be parsable and a= lways be prefixed with time
* and message flags */=
-static bool machine_readable= _output; /* GLOBAL */
+static bool machine_readable_output; /* GLOBAL */

/* Should timestamps be included on messages to stdout/stderr= ? */
static bool suppress_timestamps; /* GLOBAL */<= br>
/* The program name passed to syslog */<= br> #if SYSLOG_CAPABILITY
-static char *pgmname_syslog; /* GLOBAL */
+static char *pgmname_syslog; /* GLOBAL */=
#endif

/* If non-null,= messages should be written here (used for debugging only) */
-static FILE *msgfp; /* GLOB= AL */

+static FILE *m= sgfp; /* GLOBAL */

/* If true, we forked= from main OpenVPN process */
-static bool forked; /* GLOBAL */
+static bool forked; /* GLOBAL */

/* our default output targets */
sta= tic FILE *default_out; /* GLOBAL */
@@ -175,7 +175,7 @@
{
openvpn_exit(OPENVPN_EXIT_STAT= US_CANNOT_OPEN_DEBUG_FILE); /* exit point */
}<= br>-#else /* ifdef OPENVPN_DEBUG= _COMMAND_LINE */
+#el= se /* ifdef OPENVPN_DEBUG_COMMAND_LINE */
msgfp =3D NU= LL;
#endif
}
@@ -195,7 +1= 95,7 @@
FILE *fp =3D msgfp;
if (!= fp)
{
- fp =3D (flags & (M_FATAL|M_USAGE_SMALL)) ? default_err : d= efault_out;
+ = fp =3D (flags & (M_FATAL | M_USAGE_SMALL)) ? default_err : default_out;=
}
if (!fp)
= {
@@ -204,7 +204,12 @@
return fp;
}

-#define SWAP { tmp =3D m1; m1 =3D m2; m2 =3D tmp; }
+#define SWAP \

+ { \

+ tmp =3D m1; \

= + m1 =3D m2; \+ m2 =3D tmp; \=
+ }

int x_msg_line_num; /* GLOBAL */
@@ -265,16 +270,15 @@

gc_init= (&gc);

- m1 =3D (char *) gc_malloc(ERR_BUF_SIZE, false, &gc);<= br>- m2 =3D (char *) gc_malloc= (ERR_BUF_SIZE, false, &gc);
+ m1 =3D (char *)gc_malloc(ERR_BUF_SIZE, false, &gc);
+ m2 =3D (char *)gc_m= alloc(ERR_BUF_SIZE, false, &gc);

= vsnprintf(m1, ERR_BUF_SIZE, format, arglist);
m1[ERR_= BUF_SIZE - 1] =3D 0; /* windows vsnprintf needs this */

if ((flags & M_ERRNO) && e)
{

- snprin= tf(m2, ERR_BUF_SIZE, "%s: %s (errno=3D%d)",
- m1, openvpn_strerror(e, cr= t_error, &gc), e);
- if (flags = & (M_FATAL|M_NONFATAL|M_USAGE_SMALL))
+ if (flags & (M_FATAL | M_NONFATAL | M_USAGE_S= MALL))
{
level =3D LOG_ERR;
}
@@ -320,10 +324,7 @@
= const struct virtual_output *vo =3D msg_get_virtual_output();
if (vo)
{
- snprintf(m2, ERR_BUF_SIZE, &q= uot;%s%s%s",
- = prefix,
- m1);
+ snprintf(m2, ERR_BUF_SIZE, "%s%s%s&quo= t;, prefix, prefix_sep, m1);
virtual_output_pr= int(vo, flags, m2);
}
}
@@ -333,10 +334,7 @@
if (use_syslog &am= p;& !std_redir && !forked)
{ #if SYSLOG_CAPABILITY
- syslog(level, "%s%s%s",
- prefix,
- prefix_sep,<= br>- m1);
+ syslog(level,= "%s%s%s", prefix, prefix_sep, m1);
#endif
}
else
@@ -349= ,32 +347,17 @@
struct timeval tv; gettimeofday(&tv, NULL);

- fprintf(f= p, "%" PRIi64 ".%06ld %x %s%s%s%s",
- (int64_t)tv.tv_se= c,
- = (long)tv.tv_usec,
= - flags,
- prefix,
- prefix_sep,
- m1,
- "\n&qu= ot;);

-
+ fprintf(fp, "%= " PRIi64 ".%06ld %x %s%s%s%s", (int64_t)tv.tv_sec, (long)tv.= tv_usec,

+ = flags, prefix, prefix_sep, m1, "\n");
}

else if ((flags & M_NOPRE= FIX) || suppress_timestamps)
{
- fprintf(fp, "%s%= s%s%s",

- = prefix,
= - prefix_sep,
- m1,
- (flags&M_NOLF) ? "&qu= ot; : "\n");
- fpr= intf(fp, "%s %s%s%s%s",
- time_string(0, 0, show_usec, &gc),<= /span>
- = prefix,
- = prefix_sep,
- m1,
- (flags&M_NOLF) ? "" : "\= n");
+ = fprintf(fp, "%s %s%s%s%s", time_string(0, 0, show_usec, &am= p;gc), prefix, prefix_sep,
+ m1, (flags & M_NOLF) ? "" : &q= uot;\n");
}
= fflush(fp);
++x_msg_line_num;
= @@ -389,7 +372,6 @@
if (flags & M_FATAL) {
openvpn_exit(OPENVPN_EXIT_STATUS_ERR= OR); /* exit point */
-=
}
if (flags & M_USAGE_SMALL)=
{
@@ -426,8 +408,7 @@
if (suppressed > 0)

{<= br> msg(M_INFO | M_NOMUTE,
- "%d variation(s) on pre= vious %d message(s) suppressed by --mute",
- suppressed,
+ "%d variatio= n(s) on previous %d message(s) suppressed by --mute", suppressed,
mute_cutoff);
= }
mute_count =3D 1;
@@ -481,8= +462,9 @@
}
}=
}
-#else= /* if SYSLOG_CAPABILITY */
- msg(M_WARN, "Warning on use of --daemon: this operating sys= tem lacks daemon logging features, therefore when I become a daemon, I won&= #39;t be able to log status or error messages");
+#else /* if SYSLOG_CAPABILITY */+ msg(M_WARN,
+ "Warning on use of = --daemon: this operating system lacks daemon logging features, therefore wh= en I become a daemon, I won't be able to log status or error messages&q= uot;);

#endif
}
<= br>@@ -525,19 +507,14 @@
saAttr.bInheritHand= le =3D TRUE;
saAttr.lpSecurityDescriptor =3D NULL;=

- = log_handle =3D CreateFileW(wide_string(file, &gc),
- GENE= RIC_WRITE,

- = FILE_SHARE_READ,
- &saAttr,
- a= ppend ? OPEN_ALWAYS : CREATE_ALWAYS,

- FILE_ATTRIBUTE_NORMAL,
- = NULL);
+ = log_handle =3D CreateFileW(wide_string(file, &gc), GENERIC_WRITE, FIL= E_SHARE_READ, &saAttr,
+ append ? OPEN_ALWAYS : CREATE_ALWAY= S, FILE_ATTRIBUTE_NORMAL, NULL);

= gc_free(&gc);

if (log_handl= e =3D=3D INVALID_HANDLE_VALUE)
{
- msg(M_WARN|M_ERRNO, "W= arning: cannot open --log file: %s", file);
+ msg(M_WARN | M_ERRNO, "Warnin= g: cannot open --log file: %s", file);
re= turn;
}

@@ -554,= 7 +531,8 @@
orig_stderr =3D _dup(_fileno(stderr));=
if (orig_stderr =3D=3D -1)
= {
- msg(M= _WARN | M_ERRNO, "Warning: cannot duplicate stderr, password prompts w= ill appear in log file instead of console.");
+ msg(M_WARN | M_ERRNO,
= + "Warning:= cannot duplicate stderr, password prompts will appear in log file instead = of console.");
orig_stderr =3D _fileno(st= derr);
}

@@ -584= ,13 +562,12 @@
#elif defined(HAVE_DUP2)
= if (!std_redir)
{
- int out =3D open(file,
- O_CREAT | O_WRONLY | (a= ppend ? O_APPEND : O_TRUNC),
- S_IRUSR | S_IWUSR);
+ int out =3D open(file, O_CREAT | O_WR= ONLY | (append ? O_APPEND : O_TRUNC), S_IRUSR | S_IWUSR);
=
if (out < 0)
{=
- msg(M_WARN|M_ERR= NO, "Warning: Error redirecting stdout/stderr to --log file: %s",= file);
+ = msg(M_WARN | M_ERRNO, "Warning: Error redirecting stdout/stderr to --l= og file: %s",
+ = file);
return;
= }

@@ -612,7 +589,8 @@
= }

#else /* if defined(_WIN32= ) */
- msg(M_WARN, &= quot;WARNING: The --log option is not supported on this OS because it lacks= the dup2 function");
+ msg(M_WARN,
-x_check_s= tatus(int status,
- = const char *description,
- struct link_socket *sock,
- struct tuntap *tt)+x_check_status(int status, c= onst char *description, struct link_socket *sock, struct tuntap *tt)=
{
const char *extended_msg =3D NULL;=

@@ -659,9 +634,7 @@
int my= _errno =3D openvpn_errno_maybe_crt(&crt_error);

msg(x_cs_verbose_level, "%s %s returned %d",
- sock ? proto2ascii= (sock->info.proto, sock->info.af, true) : "",
- description,

- status);

+ sock ? proto2ascii(sock->inf= o.proto, sock->info.af, true) : "", description, status);

if (status < 0)
= {
@@ -693,16 +666,14 @@
if (ex= tended_msg)
{
= msg(x_cs_info_level, "%s %s [%s]: %s (fd=3D" SOCKET_PRINTF "= ;,code=3D%d)", description,
- sock ? proto2ascii(sock->info.proto, sock= ->info.af, true) : "",
- extended_msg, openvpn_strerror(my_errno, = crt_error, &gc),
- = sock ? sock->sd : -1, my_errno);
+ sock ? proto2ascii(s= ock->info.proto, sock->info.af, true) : "", extended_msg,
+ o= penvpn_strerror(my_errno, crt_error, &gc), sock ? sock->sd : -1, my_= errno);
}
else
{
msg(x_cs_info= _level, "%s %s: %s (fd=3D" SOCKET_PRINTF ",code=3D%d)",= description,
sock ? proto2ascii(sock-= >info.proto, sock->info.af, true) : "",
- openvpn_strerror(my_e= rrno, crt_error, &gc),
- sock ? sock->sd : -1, my_errno);
+ openvpn_strerr= or(my_errno, crt_error, &gc), sock ? sock->sd : -1, my_errno);
}

if= (x_cs_err_delay_ms)
@@ -970,16 +941,10 @@
= wchar_t wmessage[256];
char *message =3D = NULL;
struct buffer out =3D alloc_buf_gc(256, gc);=
- const DWORD s= tatus =3D FormatMessageW(
- FORMAT_MESSAGE_IGNORE_INSERTS
- | FORMAT_MESSAGE_FROM_SYSTEM- | FORMAT_MESSAGE_AR= GUMENT_ARRAY,
- = NULL,
- = errnum,
- 0,=
- wmessage,=
- SIZE(wmes= sage),
- NUL= L);
+ const DW= ORD status =3D
+ = FormatMessageW(FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_S= YSTEM
+ = | FORMAT_MESSAGE_ARGUMENT_ARRAY,
+ NULL, errnum, 0, w= message, SIZE(wmessage), NULL);
if (status)=
{
message =3D utf16to8(wmes= sage, gc);
diff --git a/src/openvpn/error.h b/src/openvpn/e= rror.h
index cd0cac3..8388f82 100644
--- a/= src/openvpn/error.h
+++ b/src/openvpn/error.h
@@ -49,10 +49,10 @@

* Exit status codes
*/


-#define OPENVPN_EXIT_STATUS_ERROR = 1
-#define = OPENVPN_EXIT_STATUS_USAGE 1
-#define OPENVPN_EXIT_STATUS_CANNOT_OPEN_DEBUG_FILE = 1
+#define OPENVPN_E= XIT_STATUS_GOOD 0
+#define OPENVPN_EXIT_STATUS_ERROR 1=
+#define OPENVPN_EXIT_STATU= S_USAGE 1
+#define OPENVPN_EXIT_STATUS_CANNOT_OPEN_DEBUG_FILE 1

/*
* Special command line debugging m= ode.
@@ -83,27 +83,27 @@

= /* msg() flags */

-#define M_DEBUG_LEVEL (0x0F) /* debug level mask= */
+#define M_DEBUG_= LEVEL (0x0F) /* debug level mask */

-#define M_FATAL (1<<4) = /* exit program */
= -#define M_NONFATAL (1<<5) /* non-fatal error */
-#define M_WARN (= 1<<6) /* call syslog with LOG_WARNING */
-#define M_DEBUG (1<<7)
+#define M_FATAL (1 &= lt;< 4) /* exit program */
+#define M_NONFATAL (1 << 5) /* non-fatal error */<= br>+#define M_WARN (1 <&= lt; 6) /* call syslog with LOG_WARNING */
+#define M_DEBUG (1 << 7)
<= /span>
-#define M_ERRNO = (1<<8) /* show errno description */
+#define M_ERRNO (1 << 8) /*= show errno description */

-#define M_NOMUTE (1<<11) /* do= n't do mute processing */
-#define M_NOPREFIX (1<<12) /* don't show da= te/time prefix */
-#def= ine M_USAGE_SMALL (1<<13) /* fatal options error, call usa= ge_small */
-#define M_= MSG_VIRT_OUT (1<<14) /* output message through msg_status_o= utput callback */
-#def= ine M_OPTERR (1<<15) /* print "Options error:&qu= ot; prefix */
-#define = M_NOLF (1<<16) /* don't print new line */
-#define M_NOIPREFIX (= 1<<17) /* don't print instance prefix */
+#define M_NOMUTE (1 << 11= ) /* don't do mute processing */
+#define M_NOPREFIX (1 << 12) /* don't show d= ate/time prefix */
+#= define M_USAGE_SMALL (1 << 13) /* fatal options error, call usage_sm= all */
+#define M_MSG= _VIRT_OUT (1 << 14) /* output message through msg_status_output callb= ack */
+#define M_OPT= ERR (1 << 15) /* print "Options error:" prefix */
+#define M_NOLF = (1 << 16) /* don't print new line */
+#define M_NOIPREFIX (1 << 17) /* don= 9;t print instance prefix */

/* flag com= binations which are frequently used */
-#define M_ERR (M_FATAL | M_ERRNO)
-#define M_USAGE (M_USAGE_SMALL | M_NOPRE= FIX | M_OPTERR)
-#defin= e M_CLIENT (M_MSG_VIRT_OUT | M_NOMUTE | M_NOIPREFIX)
+#define M_ERR (M_FATAL | M_ERRNO)
+#define M_USAGE (M_USAG= E_SMALL | M_NOPREFIX | M_OPTERR)
+#define M_CLIENT (M_MSG_VIRT_OUT | M_NOMUTE | M_NOIPREFIX)

/*
* Mute levels are desi= gned to avoid large numbers of
@@ -112,10 +112,10 @@=
* A mute level of 0 is always printed.
*/
#define MUTE_LEVEL_SHIFT 24
-#define MUTE_LEVEL_MASK 0xFF
+#define MUTE_LEVEL_MASK 0xFF
=
#define ENCODE_MUTE_LEVEL(mute_level) (((mute_level) &am= p; MUTE_LEVEL_MASK) << MUTE_LEVEL_SHIFT)
-#define DECODE_MUTE_LEVEL(flags) (((flags) >>= ; MUTE_LEVEL_SHIFT) & MUTE_LEVEL_MASK)
+#define DECODE_MUTE_LEVEL(flags) (((flags) >= > MUTE_LEVEL_SHIFT) & MUTE_LEVEL_MASK)

<= span> /*

* log_level: verbosity level n (--verb n) must = be >=3D log_level to print.
@@ -138,11 +138,34 @@=
bool dont_mute(unsigned int flags);

= /* Macro to ensure (and teach static analysis tools) we exit on fata= l errors */
-#define EX= IT_FATAL(flags) do { if ((flags) & M_FATAL) {_exit(1);}} while (false)<= /span>
+#define EXIT_FATAL(f= lags) \
+ do = \
+ { \
+ if ((flags) & M_FATAL) \
+ { \=
+ _exit(1); = \
+ } = \
+= } while (false)

-#define msg(flags, ...) do { if (msg_test(flags)) {x_msg((f= lags), __VA_ARGS__);} EXIT_FATAL(flags); } while (false)
+#define msg(flags, ...) = \
+ do = \
+ { \
+ if (msg_test(flags)) \
+ { = \
+ x_msg((flags), __VA_ARGS__); \
+ } \<= br>+ EXIT_FATAL(flags); = \
+ = } while (false)
#ifdef ENABLE_DEBUG
-#define dmsg(flags, ...) do { if (msg_test(= flags)) {x_msg((flags), __VA_ARGS__);} EXIT_FATAL(flags); } while (false)
+#define dmsg(flags, .= ..) \
+ do \
+ { \<= br>+ if (msg_test(flags)= ) \
+ = { \
+ x_msg((flags), __VA_ARGS__); \
+ } = \

+ EX= IT_FATAL(flags); \
+ } while (false)
#else
#d= efine dmsg(flags, ...)
#endif
@@ -150,12 += 173,12 @@
void x_msg(const unsigned int flags, const char = *format, ...)
#ifdef __GNUC__
#if __USE_M= INGW_ANSI_STDIO
-__attr= ibute__ ((format(gnu_printf, 2, 3)))
+ __attribute__((format(gnu_printf, 2, 3)))
#else

-__attribute= __ ((format(__printf__, 2, 3)))
+ __attribute__((format(__printf__, 2, 3)))
= #endif
#endif
-; /* should be called via msg above */
+ ; /* should be called via msg above *= /

void x_msg_va(const unsigned int flags= , const char *format, va_list arglist);

@= @ -173,7 +196,7 @@
void set_machine_readable_output(bool p= arsable);


-#define SDL_CONSTRAIN (1<<0)
+#define SDL_CONSTRAIN (1 << 0)=
bool set_debug_level(const int level, const unsigned int = flags);

bool set_mute_cutoff(const int c= utoff);
@@ -191,26 +214,41 @@

<= span> /* Fatal logic errors */

#ifndef ENABLE_SMALL=
-#define ASSERT(x) do { if (!= (x)) {assert_failed(__FILE__, __LINE__, #x);}} while (false)
+#define ASSERT(x) = \

+ = do \
+ { = \
+ = if (!(x)) \
+ { = \
+ asser= t_failed(__FILE__, __LINE__, #x); \
+ } \=
+ } while (false)=
#else
-#defi= ne ASSERT(x) do { if (!(x)) {assert_failed(__FILE__, __LINE__, NULL);}} whi= le (false)
+#define A= SSERT(x) \
+ do = \
+ { = \
+ if (!(x)) \=
+ { = \
+ assert_failed(__FILE__, __LINE__, NULL); \
+ } = \
+ } while (false)
#endif

#ifdef _MSC_VER
__declspec(noreturn)=
#endif
-void= assert_failed(const char *filename, int line, const char *condition)
+void
+assert_failed(const char *filename, int = line, const char *condition)
#ifndef _MSC_VER
-__attribute__((__noreturn__))
+ __attribute__((__nor= eturn__))
#endif
-;
+ ;<= /span>

/* Poor-man's static_assert() for wh= en not supplied by assert.h, taken from
* Linux's sys= /cdefs.h under GPLv2 */
#ifndef static_assert
-#define static_assert(expr, diagno= stic) \

- extern int= (*__OpenVPN_static_assert_function(void)) \
- [!!sizeof(struct { int __error_if_negative : (ex= pr) ? 2 : -1; })]
+#d= efine static_assert(expr, diagnostic) \
+ extern int (*__OpenVPN_static_assert_fun= ction( \
+ voi= d))[!!sizeof(struct { int __error_if_negative : (expr) ? 2 : -1; })]=
#endif

/* Inline functions */=
@@ -267,9 +305,7 @@

voi= d set_check_status(unsigned int info_level, unsigned int verbose_level);


-void x= _check_status(int status,
- const char *description,
- struct link_socket *sock,
+void x_check_status(in= t status, const char *description, struct link_socket *sock,
struct tuntap *tt);


static inline void

@@ -383,7 +419,7 @@
= *crt_error =3D true;
err =3D errno;=
}
-#else= /* ifdef _WIN32 */
= +#else /* ifdef _WIN32 */
*crt_error =3D true;<= br> err =3D errno;
#endif
diff -= -git a/src/openvpn/event.c b/src/openvpn/event.c
index c773= 783..581bdbb 100644
--- a/src/openvpn/event.c
+++ b/src/openvpn/event.c

@@ -176,8 +176,8 @@
= ASSERT(index >=3D 0 && index < wes->n_events);<= /span>
for (i =3D index; i < wes->n_events - 1; ++i)
{
- = wes->events[i] =3D wes->events[i+1];
- wes->esr[i] =3D wes->esr[i+1];
+ wes->events= [i] =3D wes->events[i + 1];
+ wes->esr[i] =3D wes->esr[i + 1];
= }
--wes->n_events;
}@@ -206,7 +206,7 @@
static void
we= _free(struct event_set *es)
{
- struct we_set *wes =3D (struct we_set *) es;
+ struct we_set *we= s =3D (struct we_set *)es;
free(wes->events);
free(wes->esr);
free(wes);@@ -215,7 +215,7 @@
static void
w= e_reset(struct event_set *es)
{
- struct we_set *wes =3D (struct we_set *) es;=
+ struct we_set *= wes =3D (struct we_set *)es;
ASSERT(wes->fast);
wes->n_events =3D 0;
}
@@ -223,7 +223,7 @@

static void
we_del(= struct event_set *es, event_t event)
{
- struct we_set *wes =3D (struct we_set= *) es;
+ struct w= e_set *wes =3D (struct we_set *)es;
ASSERT(!wes->fa= st);
we_del_event(wes, event);
}
@@ -231,13 +231,10 @@
static void
we_ctl(struct event_set *es, event_t event, unsigned int rwflags, void= *arg)

{
- struct we_set *wes =3D (struct we_set *) es;
+ struct we_set *wes =3D (struct we_set= *)es;

-= wes->n_events,
- event,
- = rwflags,
- = (ptr_type)arg);
+= dmsg(D_EVENT_WAIT, "WE_CTL n=3D%d ev=3D%p rwflags=3D0x%04x arg=3D&= quot; ptr_format, wes->n_events, event,
+ rwflags, (ptr_type)arg);
<= /span>
if (wes->fast)
{
@@ -330,11 +327,11 @@

}
break;


- case EVENT_READ|EVENT_WRITE:
+ case EVENT_READ | EVE= NT_WRITE:

switch (n)
= {
case 0:
- if (!we_append= _event(wes, event, EVENT_READ|EVENT_WRITE, arg))
+ if (!we_append_event(w= es, event, EVENT_READ | EVENT_WRITE, arg))
= {
goto err; }
@@ -377,13 +374,15 @@
return;

err:- msg(D_EVENT_ERRORS, "E= rror: Windows resource limit WSA_MAXIMUM_WAIT_EVENTS (%d) has been exceeded= ", WSA_MAXIMUM_WAIT_EVENTS);
+ msg(D_EVENT_ERRORS,
+ "Error: Windows resource limit WSA_MAXIMUM_W= AIT_EVENTS (%d) has been exceeded",
+ WSA_MAXIMUM_WAIT_EVENTS);
}

static int
we_wait(struc= t event_set *es, const struct timeval *tv, struct event_set_return *out, in= t outlen)
{
- struct we_set *wes =3D (struct we_set *) es;
+ struct we_set *wes =3D (struct we_s= et *)es;
const int timeout =3D tv_to_ms_timeout(tv);
DWORD status;

@@ -395= ,11 +394,8 @@
int i;
for = (i =3D 0; i < wes->n_events; ++i)
{- dmsg(D_EVENT_WAIT,= "[%d] ev=3D%p rwflags=3D0x%04x arg=3D" ptr_format,
- i,

- wes->events[i],
- wes-&g= t;esr[i].rwflags,
- = (ptr_type)wes->esr[i].arg);
+ dmsg(D_EVENT_WAIT, "[%d] ev=3D%p r= wflags=3D0x%04x arg=3D" ptr_format, i, wes->events[i],
+ wes->esr[i].= rwflags, (ptr_type)wes->esr[i].arg);

} }
#endif
@@ -407,18 +403,13 @= @
/*
* First poll our event list= with 0 timeout
*/
- status =3D WSAWaitForMultipleEvents(
- (DWORD) wes->n_events,
- wes->events,
- FALSE,- (DWORD) 0,
<= span style=3D"color: hsl(0, 100%, 40%);">- FALSE);

+ status =3D WSAWaitForMultipleEven= ts((DWORD)wes->n_events, wes->events, FALSE, (DWORD)0, FALSE);=

/*
* If at least one= event is already set, we must
* individually poll th= e whole list.
*/
- if (status >=3D WSA_WAIT_EVENT_0 && status = < WSA_WAIT_EVENT_0 + (DWORD) wes->n_events)
+ if (status >=3D WSA_WAIT_EVENT_0 &= & status < WSA_WAIT_EVENT_0 + (DWORD)wes->n_events)
{

int i;
int j = =3D 0;
@@ -431,8 +422,8 @@
if = (WaitForSingleObject(wes->events[i], 0) =3D=3D WAIT_OBJECT_0)
= {
*out =3D wes->esr[= i];
- dm= sg(D_EVENT_WAIT, "WE_WAIT leave [%d,%d] rwflags=3D0x%04x arg=3D" = ptr_format,
- = i, j, out->rwflags, (ptr_type)out->arg);
+ dmsg(D_EVENT_WAIT, &q= uot;WE_WAIT leave [%d,%d] rwflags=3D0x%04x arg=3D" ptr_format, i, j,
+ = out->rwflags, (ptr_type)out->arg);
+= +j;
++out;
}<= /span>
@@ -452,19 +443,16 @@
*/ if (timeout > 0)
{
<= span style=3D"color: hsl(0, 100%, 40%);">- status =3D WSAWaitFor= MultipleEvents(

- = (DWORD) wes->n_events,
- wes->events,
- FALSE,
- (DWORD) timeout,
- FALSE);
+ status =3D WSAWaitForMu= ltipleEvents((DWORD)wes->n_events, wes->events, FALSE,

+ = (DWORD)timeout, FALSE);

}

- if (outl= en >=3D 1 && status >=3D WSA_WAIT_EVENT_0 && status &= lt; WSA_WAIT_EVENT_0 + (DWORD) wes->n_events)
+ if (outlen >=3D 1 && status= >=3D WSA_WAIT_EVENT_0
+ && status < WSA_WAIT_EVENT_0 + (DWORD)wes->= n_events)
{
*out =3D = wes->esr[status - WSA_WAIT_EVENT_0];
- dmsg(D_EVENT_WAIT, "WE_WAIT leave rwflag= s=3D0x%04x arg=3D" ptr_format,
- out->rwflags, (ptr_type)out->arg);
+ dmsg(D_EVEN= T_WAIT, "WE_WAIT leave rwflags=3D0x%04x arg=3D" ptr_format, out-&= gt;rwflags,
+ = (ptr_type)out->arg);
return 1;
}
else if (status =3D=3D WSA= _WAIT_TIMEOUT)
@@ -511,10 +499,9 @@
/*= Allocate space for event_set_return objects */
ALLOC_= ARRAY_CLEAR(wes->esr, struct event_set_return, wes->capacity);=

- dmsg(D= _EVENT_WAIT, "WE_INIT maxevents=3D%d capacity=3D%d",
- *maxevents, wes->capac= ity);

+ dmsg(D_EVE= NT_WAIT, "WE_INIT maxevents=3D%d capacity=3D%d", *maxevents, wes-= >capacity);

- return (struct event_set *) wes;
+ return (struct event_set *)wes;
<= span> }


#endif /* _WIN32 */
@@ -533,7 +520,7 @@

static void
ep_fr= ee(struct event_set *es)
{
- struct ep_set *eps =3D (struct ep_set *) es;
+ struct ep_set *eps = =3D (struct ep_set *)es;
close(eps->epfd); free(eps->events);
free(eps);@@ -542,7 +529,7 @@
static void
e= p_reset(struct event_set *es)
{
- const struct ep_set *eps =3D (struct ep_set = *) es;
+ const str= uct ep_set *eps =3D (struct ep_set *)es;
ASSERT(eps-&g= t;fast);
}

@@ -550,7 +53= 7,7 @@
ep_del(struct event_set *es, event_t event)<= br> {
struct epoll_event ev;
- struct ep_set *eps =3D (struct ep_set= *) es;
+ struct e= p_set *eps =3D (struct ep_set *)es;

= dmsg(D_EVENT_WAIT, "EP_DEL ev=3D%d", (int)event);

@@ -558,14 +545,14 @@
CLEAR(ev);
if (epoll_ctl(eps->epfd, EPOLL_CTL_DEL, event, &e= v) < 0)
{
- msg(M_WARN|M_ERRNO, "EVENT: epoll_ctl EPOLL_CTL_DE= L failed, sd=3D%d", (int)event);
+ msg(M_WARN | M_ERRNO, "EVENT: epoll_ctl EPOL= L_CTL_DEL failed, sd=3D%d", (int)event);
}=
}

static void
ep_ctl(struct event_set *es, event_t event, unsigned int rwflags, void *a= rg)

{
= - struct ep_set *eps =3D (struct ep_set *) es;
+ struct ep_set *eps =3D (struct ep_set *)e= s;
struct epoll_event ev;

= CLEAR(ev);
@@ -580,11 +567,8 @@
= ev.events |=3D EPOLLOUT;
}
<= /span>
- dmsg(D_EVENT_WAIT,= "EP_CTL fd=3D%d rwflags=3D0x%04x ev=3D0x%08x arg=3D" ptr_format,=
- (int)event,<= /span>
- rwflags,
- (unsigned int)ev.= events,
- (ptr_= type)ev.data.ptr);
+ = dmsg(D_EVENT_WAIT, "EP_CTL fd=3D%d rwflags=3D0x%04x ev=3D0x%08x arg= =3D" ptr_format, (int)event, rwflags,
+ (unsigned int)ev.events, (ptr_type)ev.data.= ptr);

if (epoll_ctl(eps->epfd, EP= OLL_CTL_MOD, event, &ev) < 0)
{
@@ -605,7 +589,7 @@

static int
ep_wait(s= truct event_set *es, const struct timeval *tv, struct event_set_return *out= , int outlen)
{
- struct ep_set *eps =3D (struct ep_set *) es;
+ struct ep_set *eps =3D (struct = ep_set *)es;

int stat;

if (outlen > eps->maxevents)

@@ -624,7 +608,7= @@
for (i =3D 0; i < stat; ++i)
{

esr->rwflags =3D 0;
= - if (ev->events &a= mp; (EPOLLIN|EPOLLPRI|EPOLLERR|EPOLLHUP))
+ if (ev->events & (EPOLLIN | EPOLLP= RI | EPOLLERR | EPOLLHUP))
{
= esr->rwflags |=3D EVENT_READ;
= }
@@ -633,8 +617,8 @@
e= sr->rwflags |=3D EVENT_WRITE;
}
<= span> esr->arg =3D ev->data.ptr;

- dmsg(D_EVENT_WAIT, "EP_WAIT[%= d] rwflags=3D0x%04x ev=3D0x%08x arg=3D" ptr_format,
- i, esr->rwflags, ev-= >events, (ptr_type)ev->data.ptr);
+ dmsg(D_EVENT_WAIT, "EP_WAIT[%d] rwflag= s=3D0x%04x ev=3D0x%08x arg=3D" ptr_format, i,
+ esr->rwflags, ev->eve= nts, (ptr_type)ev->data.ptr);
++ev;<= br> ++esr;
}
@@ = -682,7 +666,7 @@
/* set epoll control fd */
= eps->epfd =3D fd;

- return (struct event_set *) eps;
= + return (struct event_set *= )eps;
}
#endif /* EPOLL */

@@ -701,7 +685,7 @@
static void=
po_free(struct event_set *es)
{
- struct po_set *pos =3D (struct po= _set *) es;

+ stru= ct po_set *pos =3D (struct po_set *)es;
free(pos->e= vents);
free(pos->args);
free(= pos);
@@ -710,7 +694,7 @@
static void
po_reset(struct event_set *es)
{
- struct po_set *pos =3D (struct= po_set *) es;

+ s= truct po_set *pos =3D (struct po_set *)es;
ASSERT(pos-= >fast);
pos->n_events =3D 0;
}<= /span>
@@ -718,7 +702,7 @@
static void
= po_del(struct event_set *es, event_t event)
{
- struct po_set *pos =3D = (struct po_set *) es;
+ struct po_set *pos =3D (struct po_set *)es;
int = i;

dmsg(D_EVENT_WAIT, "PO_DEL e= v=3D%d", (int)event);
@@ -731,8 +715,8 @@
int j;

for (j =3D i; j < p= os->n_events - 1; ++j)
{
- pos->events[j] =3D po= s->events[j+1];
- = pos->args[j] =3D pos->args[j+1];
+ pos->events[j] =3D pos= ->events[j + 1];
+= pos->args[j] =3D pos->args[j + 1];
= }
--pos->n_events;
break;

@@ -750,7 +734,7 @@
= }
if (rwflags & EVENT_READ)
= {
- pfdp->= ;events |=3D (POLLIN|POLLPRI);
+ pfdp->events |=3D (POLLIN | POLLPRI);
}

}

@@ -775,10 +75= 9,10 @@
static void
po_ctl(struct event_s= et *es, event_t event, unsigned int rwflags, void *arg)
{<= /span>
- struct po_set *pos= =3D (struct po_set *) es;
+ struct po_set *pos =3D (struct po_set *)es;

- dmsg(D_EVENT_WAIT, &= quot;PO_CTL rwflags=3D0x%04x ev=3D%d arg=3D" ptr_format,
- rwflags, (int)event, (ptr_= type)arg);

+ dmsg(= D_EVENT_WAIT, "PO_CTL rwflags=3D0x%04x ev=3D%d arg=3D" ptr_format= , rwflags, (int)event,
- struct po_se= t *pos =3D (struct po_set *) es;
+ struct po_set *pos =3D (struct po_set *)es;
int stat;


stat =3D poll(pos-&= gt;events, pos->n_events, tv_to_ms_timeout(tv));
@@ -829= ,10 +813,10 @@
const struct pollfd *pfdp =3D pos-&= gt;events;
for (i =3D 0; i < pos->n_events &= amp;& j < outlen; ++i)
{
- if (pfdp->revents & (= POLLIN|POLLPRI|POLLERR|POLLHUP|POLLOUT))
+ if (pfdp->revents & (POLLIN | POLLP= RI | POLLERR | POLLHUP | POLLOUT))
{ out->rwflags =3D 0;
- if (pfdp->revents & (POLLIN= |POLLPRI|POLLERR|POLLHUP))
+ if (pfdp->revents & (POLLIN | POLLPRI | POLLE= RR | POLLHUP))
{
= out->rwflags |=3D EVENT_READ;
= }
@@ -841,8 +825,10 @@
= out->rwflags |=3D EVENT_WRITE;
}
out->arg =3D pos->args[i];
<= span style=3D"color: hsl(0, 100%, 40%);">- dmsg(D_EVENT_WAIT= , "PO_WAIT[%d,%d] fd=3D%d rev=3D0x%08x rwflags=3D0x%04x arg=3D" p= tr_format " %s",

- i, j, pfdp->fd, pfdp->revents, out->rwfl= ags, (ptr_type)out->arg, pos->fast ? "" : "[scalable]&= quot;);
+ = dmsg(D_EVENT_WAIT,
+ pfdp->fd, pfdp= ->revents, out->rwflags, (ptr_type)out->arg,
+ pos->fast ? "= ;" : "[scalable]");
++out;<= /span>
++j;
}=
@@ -891,7 +877,7 @@
/* Allocate space for ev= ent_set_return objects */
ALLOC_ARRAY_CLEAR(pos->ar= gs, void *, pos->capacity);

- return (struct event_set *) pos;
<= span style=3D"color: hsl(120, 100%, 40%);">+ return (struct event_set *)= pos;

}
#endif /* POLL */
=
@@ -903,15 +889,15 @@
bool fast;
fd_set readfds;
fd_set writefds;
- void **args; /* alloc= ated to capacity size */
+ void **args; /* allo= cated to capacity size */
+ int maxfd; /* largest fd seen so far, always < capacity */<= /span>
int capacity; /* fixed largest fd + 1 */
};


static void
se_f= ree(struct event_set *es)
{
- struct se_set *ses =3D (struct se_set *) es;
+ struct se_set *ses = =3D (struct se_set *)es;
free(ses->args); free(ses);
}
@@ -919,7 +905,7 = @@
static void
se_reset(struct event_set = *es)
{
- struct se_set *ses =3D (struct se_set *) es;
+ struct se_set *ses =3D (struct se_set *)= es;
int i;
ASSERT(ses->fast);<= /span>

@@ -937,7 +923,7 @@
stat= ic void
se_del(struct event_set *es, event_t event)=
{
- struc= t se_set *ses =3D (struct se_set *) es;
+ struct se_set *ses =3D (struct se_set *)es;<= br> ASSERT(!ses->fast);

= dmsg(D_EVENT_WAIT, "SE_DEL ev=3D%d", (int)event);
@@ -958,7 +944,7 @@

static void
se_ctl(= struct event_set *es, event_t event, unsigned int rwflags, void *arg)
{
- stru= ct se_set *ses =3D (struct se_set *) es;
+ struct se_set *ses =3D (struct se_set *)es;=

dmsg(D_EVENT_WAIT, "SE_CTL rwflags=3D= 0x%04x ev=3D%d fast=3D%d cap=3D%d maxfd=3D%d arg=3D" ptr_format,
rwflags, (int)event, (int)ses->fast, ses->capaci= ty, ses->maxfd, (ptr_type)arg);
@@ -1000,17 +986,13 @@
}
else
{
- msg(D_EVENT_ERRORS= , "Error: select: too many I/O wait events, fd=3D%d cap=3D%d",
- (int) event,=
+ msg(D_EVENT= _ERRORS, "Error: select: too many I/O wait events, fd=3D%d cap=3D%d&qu= ot;, (int)event,
ses->capacity);
= }
}

static i= nt
-se_wait_return(stru= ct se_set *ses,
- = fd_set *read,
= - fd_set *write,
- struct event_set_return *out,
+se_wait_return(struct se_set *ses, fd_set= *read, fd_set *write, struct event_set_return *out,
= int outlen)
{
int i, j =3D = 0;
@@ -1030,8 +1012,8 @@
o= ut->rwflags |=3D EVENT_WRITE;
}
<= span> out->arg =3D ses->args[i];

- dmsg(D_EVENT_WAIT, "SE_WAIT[%= d,%d] rwflags=3D0x%04x arg=3D" ptr_format,
- i, j, out->rwflags, (ptr_type= )out->arg);
+ = dmsg(D_EVENT_WAIT, "SE_WAIT[%d,%d] rwflags=3D0x%04x arg=3D"= ; ptr_format, i, j, out->rwflags,
+ (ptr_type)out->arg);
= ++out;
++j;
= }
@@ -1040,16 +1022,15 @@
}
<= span>

static int
-se_wait_fast(struct event_set *es, const struct timeval *tv, s= truct event_set_return *out, int outlen)
+se_wait_fast(struct event_set *es, const struct timeva= l *tv, struct event_set_return *out,
+ int outlen)
{
- struct se_set *ses =3D (struct s= e_set *) es;

+ str= uct se_set *ses =3D (struct se_set *)es;
struct timeva= l tv_tmp =3D *tv;
int stat;
- dmsg(D_EVENT_WAIT, "S= E_WAIT_FAST maxfd=3D%d tv=3D%" PRIi64 "/%ld",
- ses->maxfd,

- (int64_t)tv_tmp.tv_sec,
- (long)tv_tmp.t= v_usec);
+ dmsg(D_= EVENT_WAIT, "SE_WAIT_FAST maxfd=3D%d tv=3D%" PRIi64 "/%ld&qu= ot;, ses->maxfd,
+= (int64_t)tv_tmp.tv_sec, (long)tv_tmp.tv_usec);

stat =3D select(ses->maxfd + 1, &ses->readfds= , &ses->writefds, NULL, &tv_tmp);

@@ -1062,16 +1043,17 @@

}

= static int
-se_w= ait_scalable(struct event_set *es, const struct timeval *tv, struct event_s= et_return *out, int outlen)
+se_wait_scalable(struct event_set *es, const struct timeval *tv, st= ruct event_set_return *out,
+ int outlen)
{
- struct se_set *ses =3D (struct se_set= *) es;
+ struct s= e_set *ses =3D (struct se_set *)es;
struct timeval tv_= tmp =3D *tv;
fd_set read =3D ses->readfds; fd_set write =3D ses->writefds;
int st= at;

-= dmsg(D_EVENT_WAIT, "SE_WAIT_SCALEABLE maxfd=3D%d tv=3D%" PRIi= 64 "/%ld",
- = ses->maxfd, (int64_t)tv_tmp.tv_sec, (long)tv_tmp.tv_usec);
+ dmsg(D_EVENT_WAIT, &q= uot;SE_WAIT_SCALEABLE maxfd=3D%d tv=3D%" PRIi64 "/%ld", ses-= >maxfd,
+ = (int64_t)tv_tmp.tv_sec, (long)tv_tmp.tv_usec);

= stat =3D select(ses->maxfd + 1, &read, &write, NULL, = &tv_tmp);

@@ -1116,7 +1098,7 @@
/* Allocate space for event_set_return void * args */
ALLOC_ARRAY_CLEAR(ses->args, void *, ses->capacity);<= /span>

- = return (struct event_set *) ses;
+ return (struct event_set *)ses;
}<= br> #endif /* SELECT */

@@ -1142,7 = +1124,7 @@
{
ret =3D po_init(= maxevents, flags);
}
-#else /* ifdef SELECT_PREFERRED_OVER_POLL */+#else /* ifdef SELECT_PREFERR= ED_OVER_POLL */
if (!ret)
{
ret =3D po_init(maxevents, flags);
@@ -= 1174,7 +1156,7 @@
msg(M_WARN, "Note: sys_epol= l API is unavailable, falling back to poll/select API");
ret =3D event_set_init_simple(maxevents, flags);

}

-#else /* if = EPOLL */
+#else /* if= EPOLL */
ret =3D event_set_init_simple(maxevents, fla= gs);
#endif
ASSERT(ret);
diff --git a/src/openvpn/event.h b/src/openvpn/event.h

= index 38178fc..8422996 100644
--- a/src/openvpn/event.h
+++ b/src/openvpn/event.h
@@ -31,12 +31,12 @@<= /span>
* rwflags passed to event_ctl and returned by
<= span> * struct event_set_return.

*/
-#define READ_SHIFT 0
-#define WRITE_SHIFT 1
+#define READ_SHIFT 0

= +#define WRITE_SHIFT 1
-#define EVEN= T_UNDEF 4
-#define = EVENT_READ (1 << READ_SHIFT)
-#define EVENT_WRITE (1 << WRITE_SHIFT)+#define EVENT_UNDEF 4=
+#define EVENT_READ (1 <= ;< READ_SHIFT)
+#d= efine EVENT_WRITE (1 << WRITE_SHIFT)

/* event flags returned by io_wait.

*
= @@ -57,35 +57,35 @@
* signals.
*/

-#define S= OCKET_SHIFT 0
-#= define SOCKET_READ (1 << (SOCKET_SHIFT + READ_SHIFT))<= br>-#define SOCKET_WRITE (= 1 << (SOCKET_SHIFT + WRITE_SHIFT))
-#define TUN_SHIFT 2
-#define TUN_READ (1 << (TUN_SHI= FT + READ_SHIFT))
-#def= ine TUN_WRITE (1 << (TUN_SHIFT + WRITE_SHIFT))
-#define ERR_SHIFT 4
-#define ES_ERROR = (1 << (ERR_SHIFT + READ_SHIFT))
-#define ES_TIMEOUT (1 << (ERR_SHIFT + WRIT= E_SHIFT))
-#define MANA= GEMENT_SHIFT 6
-#def= ine MANAGEMENT_READ (1 << (MANAGEMENT_SHIFT + READ_SHIFT))=
-#define MANAGEMENT_WRITE = (1 << (MANAGEMENT_SHIFT + WRITE_SHIFT))
-#define FILE_SHIFT 8
-#define FILE_CLOSED (1 << (FI= LE_SHIFT + READ_SHIFT))
-#define DCO_SHIFT 10
-#define DCO_READ (1 << (DCO_SHIFT + READ_SHIFT)= )
-#define DCO_WRITE = (1 << (DCO_SHIFT + WRITE_SHIFT))
+#define SOCKET_SHIFT 0
+#define SOCKET_READ (1 << (SOC= KET_SHIFT + READ_SHIFT))
+#define SOCKET_WRITE (1 << (SOCKET_SHIFT + WRITE_SHIFT))
+#define TUN_SHIFT = 2
+#define TUN_READ= (1 << (TUN_SHIFT + READ_SHIFT))
+#define TUN_WRITE (1 << (TUN_SHIFT = + WRITE_SHIFT))
+#def= ine ERR_SHIFT 4
+#define ES_TIMEOUT (1 &= lt;< (ERR_SHIFT + WRITE_SHIFT))
+#define MANAGEMENT_SHIFT 6
+#define MANAGEMENT_READ (1 << (MANAGEMENT_SHIF= T + READ_SHIFT))
+#de= fine MANAGEMENT_WRITE (1 << (MANAGEMENT_SHIFT + WRITE_SHIFT))<= br>+#define FILE_SHIFT 8<= /span>
+#define FILE_CLOSED = (1 << (FILE_SHIFT + READ_SHIFT))
+#define DCO_SHIFT 10
+#define DCO_READ (1 << (DCO= _SHIFT + READ_SHIFT))
+#define DCO_WRITE (1 << (DCO_SHIFT + WRITE_SHIFT))
/*
* Initialization flags passe= d to event_set_init
*/
-#define EVENT_METHOD_US_TIMEOUT (1<<0)-#define EVENT_METHOD_FAST = (1<<1)
+#def= ine EVENT_METHOD_US_TIMEOUT (1 << 0)
+#define EVENT_METHOD_FAST (1 << 1)

/*
* The following constant= is used as boundary between integer value
* and real add= resses when passing arguments to event handlers as (void *)
*/

-#define MULTI_N = ((void *)16) /* upper bound on MTCP_x */
+#define MULTI_N ((void *)16) /* upper bound = on MTCP_x */

#ifdef _WIN32

@@ -93,7 +93,7 @@

#= define UNDEFINED_EVENT (NULL)

-#else /* ifdef _WIN32 */
+#else /* ifdef _WIN32 */
=
typedef int event_t;

@= @ -117,7 +117,8 @@
* 0 on timeout
= * length of event_set_return if at least 1 event is returned
<= span> */

- int = (*wait)(struct event_set *es, const struct timeval *tv, struct event_set_re= turn *out, int outlen);
+ int (*wait)(struct event_set *es, const struct timeval *tv, struct = event_set_return *out,
-typedef = enum {
+typedef enum<= /span>
+{
= EVENT_ARG_MULTI_INSTANCE =3D 0,
EVENT_ARG_LINK_SOCK= ET,
} event_arg_t;
@@ -140,9 +142,10 @@

struct event_arg
{
eve= nt_arg_t type;
- uni= on {
+ union
+ {
= struct multi_instance *mi; /* if type =3D EVENT_ARG_MULTI_INSTANCE */=
- struct link_s= ocket *sock; /* if type =3D EVENT_ARG_LINK_SOCKET */
+ struct link_socket *sock; /* if = type =3D EVENT_ARG_LINK_SOCKET */
} u;
};


@@ -210,7 +213,7 @@
= }
}

-#else /* ifdef _WIN32 */
+#else /* ifdef _WIN32 */

static inline void
wait_signal(struct event_s= et *es, void *arg)
diff --git a/src/openvpn/fdmisc.c b/src/= openvpn/fdmisc.c
index b8d9334..2c6525b 100644
--- a/src/openvpn/fdmisc.c

+++ b/src/openvpn/fdmisc.c
@@ -41,7 +41,7 @@
{
= return false;
}
-#else /* ifdef _WIN32 */
+#else /* ifdef _WIN32 */
if= (fcntl(fd, F_SETFL, O_NONBLOCK) < 0)
{
<= span> return false;

diff --git a/src/openvpn/fdmisc= .h b/src/openvpn/fdmisc.h
index de0007a..4c0ab65 100644
--- a/src/openvpn/fdmisc.h
+++ b/src/openvpn/f= dmisc.h
@@ -45,4 +45,4 @@
}
#undef FD_SET /* prevent direct use of FD_SET() */


-#endif /* FD_MISC_H */

+#endif /* FD_MI= SC_H */
diff --git a/src/openvpn/forward.c b/src/openvpn/fo= rward.c
index d750ebf..75ca9d5 100644
--- a= /src/openvpn/forward.c
+++ b/src/openvpn/forward.c@@ -58,14 +58,11 @@
{
struct = buffer out =3D alloc_buf_gc(64, gc);

- buf_printf(&out, "I/O WAIT %s= |%s| %s",
- = tun_stat(c->c1.tuntap, EVENT_READ, gc),
- tun_stat(c->c1.tuntap, EVENT= _WRITE, gc),
- = tv_string(&c->c2.timeval, gc));
+ buf_printf(&out, "I/O WAIT %s|%s| %s&= quot;, tun_stat(c->c1.tuntap, EVENT_READ, gc),
+ tun_stat(c->c1.tuntap, EVEN= T_WRITE, gc), tv_string(&c->c2.timeval, gc));
f= or (int i =3D 0; i < c->c1.link_sockets_num; i++)
= {
- buf_printf= (&out, "\n %s|%s",
- socket_stat(c->c2.link_sockets[i], EVENT_R= EAD, gc),
+ bu= f_printf(&out, "\n %s|%s", socket_stat(c->c2.link_sockets[= i], EVENT_READ, gc),
socket_stat(c->= c2.link_sockets[i], EVENT_WRITE, gc));
}
return BSTR(&out);

@@ -127,7 +124,7 @@ static inline void
context_immediate_reschedule(s= truct context *c)
{
- c->c2.timeval.tv_sec =3D 0; /* ZERO-TIMEOUT */
+ c->c2.timeval.tv_s= ec =3D 0; /* ZERO-TIMEOUT */
c->c2.timeval.tv_usec = =3D 0;
}

@@ -185,9 +182,= 8 @@

if (interval_test(&c->c2= .tmp_int))
{
- const int tmp_status =3D tls_multi_process
- = (c->c2.tls_multi, &c->c2.to_link, &c->c2.to_link_addr,
- = get_link_socket_info(c), &wakeup);
+ const int tmp_status =3D tls_multi_pr= ocess(
+ c= ->c2.tls_multi, &c->c2.to_link, &c->c2.to_link_addr, get_l= ink_socket_info(c), &wakeup);

= if (tmp_status =3D=3D TLSMP_RECONNECT)
{<= br>@@ -345,12 +341,7 @@
#ifdef ENABLE_MANAGEMENT
if (management)
{
- manageme= nt_set_state(management,
- = NULL,
- = NULL,
- NULL,
- NULL,<= /span>
+ mana= gement_set_state(management, OPENVPN_STATE_GET_CONFIG, NULL, NULL, NULL, NU= LL,
NULL);
= }
#endif
@@ -377,8 +368= ,7 @@
}

bool
= -send_control_channel_string_dowo= rk(struct tls_session *session,
- const char *str, int msglevel)=
+send_control_channe= l_string_dowork(struct tls_session *session, const char *str, int msglevel)=
{
struct gc_arena gc =3D gc_new();
bool stat;
@@ -387,12 +377,11 @@=
struct key_state *ks =3D &session->key[KS_PRIMARY];

/* buffered cleartext write onto TLS = control channel */
- = stat =3D tls_send_payload(ks, (uint8_t *) str, strlen(str) + 1);+ stat =3D tls_send_payload= (ks, (uint8_t *)str, strlen(str) + 1);

= msg(msglevel, "SENT CONTROL [%s]: '%s' (status=3D%d)",=
- session->c= ommon_name ? session->common_name : "UNDEF",
- sanitize_control_message(str, &= amp;gc),
- (int)= stat);
+ sess= ion->common_name ? session->common_name : "UNDEF", sanitize= _control_message(str, &gc),
+ (int)stat);

gc_f= ree(&gc);
return stat;
@@ -425,8 += 414,8 @@
static void
check_add_routes_act= ion(struct context *c, const bool errors)
{
- bool route_status =3D do_route(&= amp;c->options, c->c1.route_list, c->c1.route_ipv6_list,
- = c->c1.tuntap, c->plugins, c->c2.es, &c->net_ctx);<= br>+ bool route_status =3D d= o_route(&c->options, c->c1.route_list, c->c1.route_ipv6_list, = c->c1.tuntap,
+ = c->plugins, c->c2.es, &c->net_ct= x);

int flags =3D (errors ? ISC_ERRO= RS : 0);
flags |=3D (!route_status ? ISC_ROUTE_ERRORS = : 0);
@@ -458,8 +447,8 @@
= register_signal(c->sig, SIGHUP, "ip-fail");
= c->persist.restart_sleep_seconds =3D 10;
= #ifdef _WIN32
- = show_routes(M_INFO|M_NOPREFIX);
- show_adapters(M_INFO|M_NOPREFIX);=
+ show_route= s(M_INFO | M_NOPREFIX);
+ show_adapters(M_INFO | M_NOPREFIX);
#e= ndif
}
}
@@ -602,7 +591,8 @@

* Buffer reallocation, for use wi= th null encryption.
*/
static inline voi= d
-buffer_turnover(cons= t uint8_t *orig_buf, struct buffer *dest_stub, struct buffer *src_stub, str= uct buffer *storage)
= +buffer_turnover(const uint8_t *orig_buf, struct buffer *dest_stub, struct = buffer *src_stub,
+ = struct buffer *storage)
{
= if (orig_buf =3D=3D src_stub->data && src_stub->data !=3D = storage->data)
{
@@ -630,7 +620,7 @= @
if (dco_enabled(&c->options))
{

msg(M_WARN, "Attempting to send data = packet while data channel offload is in use. "
- "Dropping packet");
+ &= quot;Dropping packet");
c->c2.buf.len =3D = 0;
}

@@ -650,7 +640,= 8 @@
/* Compress the packet. */
= if (c->c2.comp_context)
{
- (*c->c2.comp_context-= >alg.compress)(&c->c2.buf, b->compress_buf, c->c2.comp_cont= ext, &c->c2.frame);

+ (*c->c2.comp_context->alg.compress)(&c->c2.= buf, b->compress_buf, c->c2.comp_context,
+ = &c->c2.frame);
}
#endif
#ifdef ENABLE_FRAGMENT
@@ -697,8 +688,7 @@<= /span>
/*
* Get the address we will be = sending the packet to.
*/
- link_socket_get_outgoing_addr(&c->c2.b= uf, get_link_socket_info(c),
- &c->c2.to_link_addr);
+ link_socket_get_outgo= ing_addr(&c->c2.buf, get_link_socket_info(c), &c->c2.to_link_= addr);

/* if null encryption, copy r= esult to read_tun_buf */
buffer_turnover(orig_buf, &am= p;c->c2.to_link, &c->c2.buf, &b->read_tun_buf);
= @@ -711,8 +701,7 @@
check_session_timeout(struct con= text *c)
{
if (c->options.session_= timeout
- &&= amp; event_timeout_trigger(&c->c2.session_interval, &c->c2.ti= meval,
- = ETT_DEFAULT))
+ && event_timeout_trigger(&c->c2.session_= interval, &c->c2.timeval, ETT_DEFAULT))
{
msg(M_INFO, "Session timeout, exiting");
register_signal(c->sig, SIGTERM, "session-time= out");
@@ -726,7 +715,7 @@
process_co= arse_timers(struct context *c)
{
/* f= lush current packet-id to file once per 60
- * seconds if --replay-persist was specified */
+ * seconds if --rep= lay-persist was specified */
if (packet_id_persist_ena= bled(&c->c1.pid_persist)
&& event_t= imeout_trigger(&c->c2.packet_id_persist_interval, &c->c2.time= val, ETT_DEFAULT))
{
@@ -849,7 +838,8 = @@
process_coarse_timers(c);
c-&g= t;c2.coarse_timer_wakeup =3D now + c->c2.timeval.tv_sec;

- dmsg(D_INTERVAL= , "TIMER: coarse timer wakeup %" PRIi64 " seconds", (in= t64_t)c->c2.timeval.tv_sec);
+ dmsg(D_INTERVAL, "TIMER: coarse timer wakeup %" P= RIi64 " seconds",
+ (int64_t)c->c2.timeval.tv_sec);

/* Is the coarse timeout NOT the earliest one? */ if (c->c2.timeval.tv_sec > save.tv_sec)
@= @ -863,10 +853,10 @@
{
const int upda= te_interval =3D 10; /* seconds */
c->c2.update_time= out_random_component =3D now + update_interval;
- c->c2.timeout_random_component.tv_usec =3D= (time_t) get_random() & 0x0003FFFF;
+ c->c2.timeout_random_component.tv_usec =3D (tim= e_t)get_random() & 0x0003FFFF;
c->c2.timeout_ra= ndom_component.tv_sec =3D 0;

- dmsg(D_INTERVAL, "RANDOM USEC=3D%ld"= , (long) c->c2.timeout_random_component.tv_usec);
+ dmsg(D_INTERVAL, "RANDOM USEC=3D= %ld", (long)c->c2.timeout_random_component.tv_usec);
}


static inline void
= @@ -897,10 +887,8 @@
}

= static inline void
-soc= ks_preprocess_outgoing_link(struct context *c,
- struct link_socket = *sock,
- = struct link_socket_actual **to_addr,
- int *size_de= lta)
+socks_preproces= s_outgoing_link(struct context *c, struct link_socket *sock,
+ str= uct link_socket_actual **to_addr, int *size_delta)

{
if (sock->socks_proxy && sock->info.proto =3D= =3D PROTO_UDP)
{
@@ -911,9 +899,7 @@

/* undo effect of socks_preprocess_outgoi= ng_link */
static inline void
-link_socket_write_post_size_adjust(int *size,
- = int size_delta,
+link_socket_write_post_size_adjust(in= t *size, int size_delta, struct buffer *buf)
{
<= span> if (size_delta > 0 && *size > size_delta)
{
@@ -945,9 +931,7 @@
c-&g= t;c2.buf =3D c->c2.buffers->read_link_buf;
ASSER= T(buf_init(&c->c2.buf, c->c2.frame.buf.headroom));

- status =3D lin= k_socket_read(sock,
- = &c->c2.buf,
- &c->c2.from);=
+ status =3D link= _socket_read(sock, &c->c2.buf, &c->c2.from);
=
if (socket_connection_reset(sock, status)) {
@@ -965,12 +949,14 @@
= /* received a disconnect from a connection-oriented protocol */
if (event_timeout_defined(&c->c2.explicit_ex= it_notification_interval))
{
- msg(D_STREAM_ERRORS, &q= uot;Connection reset during exit notification period, ignoring [%d]", = status);
+ = msg(D_STREAM_ERRORS,
+ "Connection reset during exit notification p= eriod, ignoring [%d]", status);
manag= ement_sleep(1);
}
= else
{
- register_signal(c->sig, SIGUSR1, "co= nnection-reset"); /* SOFT-SIGUSR1 -- TCP connection reset */+ register_sign= al(c->sig, SIGUSR1,
- = management_bytes_server(management, &c->c2.link_read_bytes= , &c->c2.link_write_bytes, &c->c2.mda_context);
+ management_bytes_serv= er(management, &c->c2.link_read_bytes, &c->c2.link_write_byte= s,

+ = &c->c2.mda_context);
}
#endif
}
@@ -1044,11 += 1031,8 @@
fprintf(stderr, "R"); }
#endif
- msg(D_LINK_RW, "%s READ [%d] from %s: %s",
- proto2ascii(lsi= ->proto, lsi->af, true),
- BLEN(&c->c2.buf),
- print_link_socket_actual(&c->c2.from, &a= mp;gc),
- PROTO_= DUMP(&c->c2.buf, &gc));
+ msg(D_LINK_RW, "%s READ [%d] from %s: %s", pro= to2ascii(lsi->proto, lsi->af, true),
+ BLEN(&c->c2.buf), print_link_socket_a= ctual(&c->c2.from, &gc), PROTO_DUMP(&c->c2.buf, &gc))= ;

/*
* Good, n= on-zero length packet received.
@@ -1080,9 +1064,8 @@
*/
if ((opcode =3D=3D= P_DATA_V1) && dco_enabled(&c->options))
= {
- = msg(D_LINK_ERRORS,
- = "Upgrade your server to 2.4.5 or newer.");
+ msg(D_LIN= K_ERRORS, "Data Channel Offload doesn't support DATA_V1 packets. &= quot;
+ = "Upgrade your server to 2.4.5 or newer.");
c->c2.buf.len =3D 0;
= }

@@ -1096,8 +1079,7 @@<= br> * will load crypto_options with the correct encrypti= on key
* and return false.
= */
- = if (tls_pre_decrypt(c->c2.tls_multi, &c->c2.from, &c->= ;c2.buf, &co,
- = floated, &ad_start))
+ if (tls_pre_decrypt(c->c2.= tls_multi, &c->c2.from, &c->c2.buf, &co, floated, &ad= _start))
{
in= terval_action(&c->c2.tmp_int);

@@ = -1124,15 +1106,16 @@
}
/* authenticate and decrypt the incoming packet */- decrypt_status =3D ope= nvpn_decrypt(&c->c2.buf, c->c2.buffers->decrypt_buf,- = co, &c->c2.frame, ad_start);
+ decrypt_status =3D
+ openvpn_decrypt(&c->c2= .buf, c->c2.buffers->decrypt_buf, co, &c->c2.frame, ad_start);=

if (!decrypt_status
<= span> /* on the instance context we have only one socket, so ju= st check the first one */

&& link_sock= et_connection_oriented(c->c2.link_sockets[0]))
= {
/* decryption errors are fatal in TCP mode *= /
- register= _signal(c->sig, SIGUSR1, "decryption-error"); /* SOFT-SIGUSR1 = -- decryption error in TCP mode */
+ register_signal(c->sig, SIGUSR1,
+ &quo= t;decryption-error"); /* SOFT-SIGUSR1 -- decryption error in TCP mode = */

msg(D_STREAM_ERRORS, "Fatal decryption= error (process_incoming_link), restarting");
= }
}
@@ -1146,7 +1129,8 @@
<= span> }


void
-process_incoming_link_part2(struct context *c, st= ruct link_socket_info *lsi, const uint8_t *orig_buf)
+process_incoming_link_part2(struct contex= t *c, struct link_socket_info *lsi,
+ const uint8_t *orig_buf)=
{
if (c->c2.buf.len > 0)
{

@@ -1161,17 +1145,15 @@
= /* decompress the incoming packet */
if (c->c2= .comp_context)
{
- (*c->c2.comp_context->alg.decompress)= (&c->c2.buf, c->c2.buffers->decompress_buf, c->c2.comp_cont= ext, &c->c2.frame);
+ (*c->c2.comp_context->alg.decompress)(&c->c= 2.buf, c->c2.buffers->decompress_buf,
+ c= ->c2.comp_context, &c->c2.frame);
}
#endif

#ifdef PACKET_TRUNCA= TION_CHECK
/* if (c->c2.buf.len > 1) --c->= ;c2.buf.len; */
- = ipv4_packet_size_verify(BPTR(&c->c2.buf),
- BLEN(&c-&g= t;c2.buf),
- = TUNNEL_TYPE(c->c1.tuntap),
- "POST_DEC= RYPT",
- = &c->c2.n_trunc_post_decrypt);
+ ipv4_packet_size_verify(BPTR= (&c->c2.buf), BLEN(&c->c2.buf), TUNNEL_TYPE(c->c1.tuntap),=
+ = "POST_DECRYPT", &c->c2.n_trunc_post_decrypt);=
#endif

/*
@@ -1198,7 +1180,8 @@
if (c->c2.buf= .len > 0)
{
c->= c2.link_read_bytes_auth +=3D c->c2.buf.len;
- c->c2.max_recv_size_local =3D max_i= nt(c->c2.original_recv_size, c->c2.max_recv_size_local);
+ c->c2.max_recv_si= ze_local =3D

+ = max_int(c->c2.original_recv_size, c->c2.max_recv_size_local)= ;
}

/* = Did we just receive an openvpn ping packet? */
@@ -1243,8 += 1226,7 @@
}

void=
-extract_dco_float_peer_addr(= const sa_family_t socket_family,
- struct openvpn_sockaddr *out_osaddr,=
+extract_dco_float_p= eer_addr(const sa_family_t socket_family, struct openvpn_sockaddr *out_osad= dr,
const struct sockaddr *flo= at_sa)
{
if (float_sa->sa_family = =3D=3D AF_INET)
@@ -1262,8 +1244,8 @@
= memset(&out_osaddr->addr.in6.sin6_addr.s6_addr, 0, 10);
out_osaddr->addr.in6.sin6_addr.s6_addr[10] =3D = 0xff;
out_osaddr->addr.in6.sin6_addr.s6_add= r[11] =3D 0xff;
- = memcpy(&out_osaddr->addr.in6.sin6_addr.s6_addr[12],
= - &float4-&= gt;sin_addr.s_addr, sizeof(in_addr_t));
+ memcpy(&out_osaddr->addr.in6.sin6_ad= dr.s6_addr[12], &float4->sin_addr.s_addr,
+ sizeof(in_addr_t));<= br> }
else
= {
@@ -1296,9 +1278,10 @@
* ourselves = in the foot and removing the just established session */
= if (dco->dco_message_peer_id !=3D c->c2.tls_multi->dco_peer_id)=
{
- msg(D_DCO_DEBUG, "%s: received message for mismatching peer-= id %d, "
- = "expected %d", __func__, dco->dco_message_peer_id,<= br>- c->c2.tls_mult= i->dco_peer_id);
+= msg(D_DCO_DEBUG,
+ "%s: received message for mismatching peer-id %d, &qu= ot;
+ &quo= t;expected %d",
= + __func__, dco->dco_message_peer_id, c->c2.tls_multi->= dco_peer_id);
return;
}

@@ -1309,16 +1292,18 @@
= c->c2.tls_multi->dco_peer_id =3D -1;
= if (dco->dco_del_peer_reason =3D=3D OVPN_DEL_PEER_REASON_EXPIRED)
{
- msg(D_DCO_DEBUG, "%s: received peer expired not= ification of for peer-id "
- "%d", __func__, dco->dco_message= _peer_id);
+ = msg(D_DCO_DEBUG,
+ "%s: received peer expired notification of for= peer-id "
+ = "%d",
+ __func__, dco->dco_message_peer_id);
trigger_ping_timeout_signal(c);
return;

}
= break;

case OVPN_CM= D_SWAP_KEYS:
- = msg(D_DCO_DEBUG, "%s: received key rotation notification for peer-i= d %d",
- = __func__, dco->dco_message_peer_id);
+ msg(D_DCO_DEBUG, "%s: received k= ey rotation notification for peer-id %d", __func__,
+ dco->dco_message_pe= er_id);
tls_session_soft_reset(c->c2.tls_mu= lti);
break;

@@ -1358,7 +1343,8 @@

ASSERT(buf_safe(&c->c2.b= uf, c->c2.frame.buf.payload_size));
if (c->c1.tu= ntap->backend_driver =3D=3D DRIVER_AFUNIX)
{=
- c->c2.buf.len =3D= read_tun_afunix(c->c1.tuntap, BPTR(&c->c2.buf), c->c2.frame.b= uf.payload_size);
+ = c->c2.buf.len =3D
+ read_tun_afunix(c->c1.tuntap, BPTR(&c->c2.buf)= , c->c2.frame.buf.payload_size);
}
= else
{
@@ -1367,11 +1353,8 @@
#endif /* ifdef _WIN32 */

= #ifdef PACKET_TRUNCATION_CHECK
- ipv4_packet_size_verify(BPTR(&c->c2.buf),
- BLEN(&a= mp;c->c2.buf),

- = TUNNEL_TYPE(c->c1.tuntap),
- "READ_TUN&= quot;,
- = &c->c2.n_trunc_tun_read);
+ ipv4_packet_size_verify(BPTR(&c->c2.bu= f), BLEN(&c->c2.buf), TUNNEL_TYPE(c->c1.tuntap),
+ "RE= AD_TUN", &c->c2.n_trunc_tun_read);
#endif

/* Was TUN/TAP interface stopped? */
@@ -1426,7 +1409,7 @@
if (proto_ver =3D= =3D 4)
{
/* make sure we got = whole IP header */
- = if (BLEN(buf) < ((int) sizeof(struct openvpn_iphdr) + ip_hdr_offset= ))
+ if (BLEN(= buf) < ((int)sizeof(struct openvpn_iphdr) + ip_hdr_offset))
{

return;
= }
@@ -1437,7 +1420,7 @@
retu= rn;
}

- struct openvpn_iphdr *pip =3D (struct op= envpn_iphdr *) (BPTR(buf) + ip_hdr_offset);
+ struct openvpn_iphdr *pip =3D (struct openv= pn_iphdr *)(BPTR(buf) + ip_hdr_offset);

= /* drop packets with same dest addr as gateway */
= if (memcmp(&tun_sa.addr.in4.sin_addr.s_addr, &pip->daddr= , sizeof(pip->daddr)) =3D=3D 0)
@@ -1448,7 +1431,7 @@
else if (proto_ver =3D=3D 6)
{
/* make sure we got whole IPv6 header */
- if (BLEN(buf) < ((int) s= izeof(struct openvpn_ipv6hdr) + ip_hdr_offset))

+ if (BLEN(buf) < ((int)sizeof(struct = openvpn_ipv6hdr) + ip_hdr_offset))
{
return;

}
@@ -1459= ,7 +1442,7 @@
return;
= }

- = struct openvpn_ipv6hdr *pip6 =3D (struct openvpn_ipv6hdr *) (BPTR(bu= f) + ip_hdr_offset);
= + struct openvpn_ipv6hdr *pip6 =3D (struct openvpn_ipv6hdr *)(BPTR(b= uf) + ip_hdr_offset);

/* drop pa= ckets with same dest addr as gateway */
if (OPENVP= N_IN6_ARE_ADDR_EQUAL(&tun_sa.addr.in6.sin6_addr, &pip6->daddr))<= /span>
@@ -1517,19 +1500,15 @@
* The --p= asstos and --mssfix options require
* us to exami= ne the IP header (IPv4 or IPv6).
*/
- unsigned int flags =3D PIPV= 4_PASSTOS | PIP_MSSFIX | PIPV4_CLIENT_NAT

- | PIPV6_ICMP_NOHOST_CLIENT= ;
+ unsigned i= nt flags =3D
+ = PIPV4_PASSTOS | PIP_MSSFIX | PIPV4_CLIENT_NAT | PIPV6_ICMP_NOHOST_CLIE= NT;
process_ip_header(c, flags, &c->c2.buf,= out_sock);

#ifdef PACKET_TRUNCATION_CHE= CK
/* if (c->c2.buf.len > 1) --c->c2.buf.= len; */
- ipv4_p= acket_size_verify(BPTR(&c->c2.buf),
- BLEN(&c->c2.buf= ),
- = TUNNEL_TYPE(c->c1.tuntap),
- "PRE_ENCRYPT"= ;,
- = &c->c2.n_trunc_pre_encrypt);
+ ipv4_packet_size_verify(BPTR(&c-&g= t;c2.buf), BLEN(&c->c2.buf), TUNNEL_TYPE(c->c1.tuntap),+ = "PRE_ENCRYPT", &c->c2.n_trunc_pre_encrypt);
<= span> #endif

- }
if (c->c2.buf.len > 0)
= {
@@ -1605,8 +1584,7 @@
icm= p6out.icmp6_type =3D OPENVPN_ICMP6_DESTINATION_UNREACHABLE;
icmp6out.icmp6_code =3D OPENVPN_ICMP6_DU_NOROUTE;


- int icmpheader_len = =3D sizeof(struct openvpn_ipv6hdr)
- + sizeof(struct openvpn_icmp6hdr);
+ int icmpheader_len= =3D sizeof(struct openvpn_ipv6hdr) + sizeof(struct openvpn_icmp6hdr);
int totalheader_len =3D icmpheader_len;
<= /span>
if (TUNNEL_TYPE(c->c1.tuntap) =3D=3D DEV_TYPE_TAP)<= /span>
@@ -1619,8 +1597,7 @@
* frame should = be <=3D 1280 and have as much as possible of the original
* packet

*/
- int max_payload_size =3D min_int(MAX_ICMPV6LEN,
- = c->c2.frame.tun_mtu - icmpheader_len);
+ int max_payload_size =3D min_int(MAX_= ICMPV6LEN, c->c2.frame.tun_mtu - icmpheader_len);
i= nt payload_len =3D min_int(max_payload_size, BLEN(&inputipbuf));=

pip6out.payload_len =3D htons(sizeof(struc= t openvpn_icmp6hdr) + payload_len);
@@ -1648,10 +1625,10 @@=

/* Calculate checksum over the pack= et and write to header */

- uint16_t new_csum =3D ip_checksum(AF_INET6, BPTR(= outbuf), BLEN(outbuf),
= - (const uint8_t *)&pip6out.saddr,
- = (uint8_t *)&pip6out.daddr, OPENVPN_IPPROTO_ICMPV6);=
- ((struct openvpn_icmp6hd= r *) BPTR(outbuf))->icmp6_cksum =3D htons(new_csum);
+ uint16_t new_csum =3D
+ ip_checksum(AF_INET6, BPT= R(outbuf), BLEN(outbuf), (const uint8_t *)&pip6out.saddr,

+ (uint8_t *)&a= mp;pip6out.daddr, OPENVPN_IPPROTO_ICMPV6);

+ ((struct openvpn_icmp6hdr *)BPTR(outbuf))->ic= mp6_cksum =3D htons(new_csum);

/* IPv6 Header */
@@ -1667,7 +1644,7 @@=
return;
}
=
- const struct = openvpn_ethhdr *orig_ethhdr =3D (struct openvpn_ethhdr *) BPTR(buf);=
+ const struct openv= pn_ethhdr *orig_ethhdr =3D (struct openvpn_ethhdr *)BPTR(buf);

/* Copy frametype and reverse source/destina= tion for the response */
struct openvpn_ethhdr eth= hdr;
@@ -1748,15 +1725,13 @@
{=
mss_fixup_ipv6(&ipbuf, c->c2.frame= .mss_fix);
}
- if (!(flags & PIP_OUTGOING) && = (flags
- = &(PIPV6_ICMP_NOHOST_CLIENT | PIPV6_ICMP_NO= HOST_SERVER)))
+ = if (!(flags & PIP_OUTGOING)
+ && (flags & (PIPV6_ICMP_NOHO= ST_CLIENT | PIPV6_ICMP_NOHOST_SERVER)))
{
- ipv6_send_= icmp_unreachable(c, buf,
+ = ipv6_send_icmp_unreachable(c, buf, (bool)(flags & PIPV6_I= CMP_NOHOST_CLIENT));
/* Drop the IPv6 pack= et */
buf->len =3D 0;
= }
-<= br> }
}
}
@@ -1793,10 +1768,9 @@

*/
= if (c->options.shaper)
{
- int overhea= d =3D datagram_overhead(c->c2.to_link_addr->dest.addr.sa.sa_family,
- = sock->info.proto);
- shaper_wrote_bytes(&c->c2.= shaper,
- = BLEN(&c->c2.to_link) + overhead);
+ int overhead =3D<= /span>
+ = datagram_overhead(c->c2.to_link_addr->dest.addr.sa.sa_family, sock-&g= t;info.proto);
+ = shaper_wrote_bytes(&c->c2.shaper, BLEN(&c->c2.to_l= ink) + overhead);
}
/*
@@ -1820,10 +1794,8 @@
}

#endif
msg= (D_LINK_RW, "%s WRITE [%d] to %s: %s",
- proto2ascii(sock->info.proto,= sock->info.af, true),
- BLEN(&c->c2.to_link),
- print_link_socket_actual(c->c= 2.to_link_addr, &gc),
- PROTO_DUMP(&c->c2.to_link, &gc));
= + proto2ascii(so= ck->info.proto, sock->info.af, true), BLEN(&c->c2.to_link),
+ print_= link_socket_actual(c->c2.to_link_addr, &gc), PROTO_DUMP(&c->c= 2.to_link, &gc));

/* Pac= ket send complexified by possible Socks5 usage */
= {
@@ -1834,9 +1806,7 @@
= socks_preprocess_outgoing_link(c, sock, &to_addr, &size_delta);

/* Send packet */<= br>- size =3D (int= )link_socket_write(sock,
- = to_addr);
+ size =3D (int)link_socket_write(sock, &c->= ;c2.to_link, to_addr);

/= * Undo effect of prepend */
link_socket_wr= ite_post_size_adjust(&size, size_delta, &c->c2.to_link);<= br>@@ -1857,7 +1827,8 @@
if (managem= ent)
{
= management_bytes_client(management, 0, size);
- management_bytes_server(manag= ement, &c->c2.link_read_bytes, &c->c2.link_write_bytes, &= c->c2.mda_context);
+ = &c->c2.link_write_bytes, &= ;c->c2.mda_context);
}
= #endif
}
@@ -1874,9 +1845,7 @= @
{
msg(D_LIN= K_ERRORS,
"TCP/UDP packet was tru= ncated/expanded on write to %s (tried=3D%d,actual=3D%d)",
- print_link_soc= ket_actual(c->c2.to_link_addr, &gc),

- BLEN(&c->c2.to_link),
- size);=
+ = print_link_socket_actual(c->c2.to_link_addr, &gc), BLEN(&c->= c2.to_link), size);
}
= }

@@ -1895,7 +1864,8 @@
= ENETUNREACH;
#endif
= if (size < 0 && unreachable && c->c2.t= ls_multi
- &= amp;& !tls_initial_packet_received(c->c2.tls_multi) && c->= ;options.mode =3D=3D MODE_POINT_TO_POINT)
+ && !tls_initial_packet_received(c= ->c2.tls_multi)
+ = && c->options.mode =3D=3D MODE_POINT_TO_POINT)=
{
msg(M_INFO, "Network= unreachable, restarting");
register_sign= al(c->sig, SIGUSR1, "network-unreachable");
@@= -1906,8 +1876,7 @@
if (c->c2.to_link.len > = 0)
{
msg(D_LINK_ERROR= S, "TCP/UDP packet too large on write to %s (tried=3D%d,max=3D%d)"= ;,
- pri= nt_link_socket_actual(c->c2.to_link_addr, &gc),
- c->c2.to_link.len,
+ print_li= nk_socket_actual(c->c2.to_link_addr, &gc), c->c2.to_link.len,
c->c2.frame.buf.payload_size);
<= span> }

}
@@ -1940,8 +1909,8 @= @
* The --mssfix option requires
= * us to examine the IP header (IPv4 or IPv6).
*/
- process_ip_header(c,= PIP_MSSFIX|PIPV4_EXTRACT_DHCP_ROUTER|PIPV4_CLIENT_NAT|PIP_OUTGOING, &c= ->c2.to_tun,
- = in_sock);
+ process_ip_header(c, PIP_MSSFIX | PIPV4_EXTRACT_DHCP_ROUTER | PIP= V4_CLIENT_NAT | PIP_OUTGOING,
+ &c->c2.to_tun, in_sock);
<= span>

if (c->c2.to_tun.len <=3D c->c2.frame.= buf.payload_size)
{
@@ -1959,11 +1928,= 8 @@
dmsg(D_TUN_RW, "TUN WRITE [%d]", BL= EN(&c->c2.to_tun));

#ifdef PACKET= _TRUNCATION_CHECK
- = ipv4_packet_size_verify(BPTR(&c->c2.to_tun),
- BLEN(&= ;c->c2.to_tun),
- = TUNNEL_TYPE(c->c1.tuntap),
- "= WRITE_TUN",
- = &c->c2.n_trunc_tun_write);
+ ipv4_packet_size_verify(BP= TR(&c->c2.to_tun), BLEN(&c->c2.to_tun), TUNNEL_TYPE(c->c1.= tuntap),

+ = "WRITE_TUN", &c->c2.n_trunc_tun_write= );
#endif

#ifdef _WIN32=
@@ -1993,9 +1959,7 @@
{
msg(D_LINK_ERRORS,
= "TUN/TAP packet was destructively fragmented on write to %s (= tried=3D%d,actual=3D%d)",
- c->c1.tuntap->actual_name,
- BLEN(&c->= ;c2.to_tun),

- = size);
+ = c->c1.tuntap->actual_name, BLEN(&c->c2.to_tu= n), size);
}

/* indicate activity regarding --inactive parameter */
=
@@ -2008,8 +1972,7 @@
* This should nev= er happen, probably indicates some kind
* of MTU = mismatch.
*/
- msg(D_LINK_ERRORS, "tun packet too large on w= rite (tried=3D%d,max=3D%d)",
- c->c2.to_tun.len,
+ msg(D_LINK_ERRORS, "tun packet too la= rge on write (tried=3D%d,max=3D%d)", c->c2.to_tun.len,
c->c2.frame.buf.payload_size);

}

@@ -2085,9 +2048,8 @@
}

static void
-multi_io_process_flags(struct context *c, struct ev= ent_set *es,
- = const unsigned int flags, unsigned int *out_socket,- unsigned= int *out_tuntap)
+mu= lti_io_process_flags(struct context *c, struct event_set *es, const unsigne= d int flags,
+ = unsigned int *out_socket, unsigned int *out_tuntap)<= br> {
unsigned int socket =3D 0;
unsigned int tuntap =3D 0;

@@ -2178,8 +2140,7 @@
*/
for (int i =3D 0; i < c->c1= .link_sockets_num; i++)
{
- socket_set(c->c2.link_sockets[i], es, s= ocket,
- = &c->c2.link_sockets[i]->ev_arg, NULL);
+ socket_set(c->c2.link_sockets[= i], es, socket, &c->c2.link_sockets[i]->ev_arg, NULL);
= }

tun_set(c->c1.tuntap= , es, tuntap, (void *)tun_shift, NULL);
@@ -2193,7 +2154,6 = @@
{
*out_tuntap =3D tuntap;<= /span>
}
= -
}

/*
= @@ -2244,15 +2204,16 @@
struct event_set_return esr[4]= ;

/* These shifts all depend on EVEN= T_READ and EVENT_WRITE */
- static uintptr_t socket_shift =3D SOCKET_SHIFT; /* depends on SOC= KET_READ and SOCKET_WRITE */
+ static uintptr_t socket_shift =3D SOCKET_SHIFT; /* depends on = SOCKET_READ and SOCKET_WRITE */
#ifdef ENABLE_MANAGEMENT
- static uintptr_t ma= nagement_shift =3D MANAGEMENT_SHIFT; /* depends on MANAGEMENT_READ and MANA= GEMENT_WRITE */
+ = static uintptr_t management_shift =3D
+ MANAGEMENT_SHIFT; /* depends on MANAGEMENT_READ a= nd MANAGEMENT_WRITE */
#endif
#ifdef ENAB= LE_ASYNC_PUSH
static uintptr_t file_shift =3D FILE_SHI= FT;
#endif
#if defined(TARGET_LINUX) || d= efined(TARGET_FREEBSD)
= - static uintptr_t dco_shift =3D DCO_SHIFT; /* Event from DCO linux k= ernel module */
+ = static uintptr_t dco_shift =3D DCO_SHIFT; /* Event from DCO linux kernel mo= dule */
#endif

/*
@@ -2331,8 +2292,7 @@
= if (ev_arg->type !=3D EVENT_ARG_LINK_SOCKET)
= {
c->c2.ev= ent_set_status =3D ES_ERROR;
- msg(D_LINK_ERRORS,
- "io_wo= rk: non socket event delivered");
+ msg(D_LINK_ERRORS, "io_= work: non socket event delivered");
= return;
}

@@ -2375,7 +2335,7 @@
const unsig= ned int status =3D c->c2.event_set_status;

<= span> #ifdef ENABLE_MANAGEMENT

- if (status & (MANAGEMENT_READ|MANAGEMENT_WRITE))+ if (status & (MANAGEM= ENT_READ | MANAGEMENT_WRITE))
{
= ASSERT(management);
management_io(management);<= /span>
diff --git a/src/openvpn/forward.h b/src/openvpn/forward.h<= /span>
index abb45c0..d564149 100644
--- a/src/ope= nvpn/forward.h
+++ b/src/openvpn/forward.h
= @@ -34,9 +34,9 @@
* file
*/
<= span>

-#define TUN_OUT= (c) (BLEN(&(c)->c2.to_tun) > 0)
-#define LINK_OUT(c) (BLEN(&(c)->c2.to_l= ink) > 0)
-#define A= NY_OUT(c) (TUN_OUT(c) || LINK_OUT(c))
+#define TUN_OUT(c) (BLEN(&(c)->c2.to_tun) &g= t; 0)
+#define LINK_O= UT(c) (BLEN(&(c)->c2.to_link) > 0)
+#define ANY_OUT(c) (TUN_OUT(c) || LINK_OUT(c))

#ifdef ENABLE_FRAGMENT
#d= efine TO_LINK_FRAG(c) ((c)->c2.fragment && fragment_outgoing_def= ined((c)->c2.fragment))
@@ -44,31 +44,32 @@
#define TO_LINK_FRAG(c) (false)

#endif

-#define TO_LINK_DE= F(c) (LINK_OUT(c) || TO_LINK_FRAG(c))
+#define TO_LINK_DEF(c) (LINK_OUT(c) || TO_LINK_FRAG(c))<= /span>

#include "openvpn.h" #include "occ.h"
#include "ping.h&q= uot;
#include "multi_io.h"

-#define IOW_TO_TUN = (1<<0)
-#defin= e IOW_TO_LINK (1<<1)
-#define IOW_READ_TUN (1<<2)
-#define IOW_READ_LINK (1<<3)
-#define IOW_SHAPER = (1<<4)
-#defi= ne IOW_CHECK_RESIDUAL (1<<5)
-#define IOW_FRAG (1<<6)
-#define IOW_MBUF (1<<7)
-#define IOW_READ_TUN_FO= RCE (1<<8)
-#def= ine IOW_WAIT_SIGNAL (1<<9)
+#define IOW_TO_TUN (1 << 0)
+#define IOW_TO_LINK (1 <&l= t; 1)
+#define IOW_RE= AD_TUN (1 << 2)
+#define IOW_READ_LINK (1 << 3)
+#define IOW_SHAPER (1 << 4)
+#define IOW_CHECK_RESID= UAL (1 << 5)
+#= define IOW_FRAG (1 << 6)
+#define IOW_MBUF (1 << 7)
+#define IOW_READ_TUN_FORCE (1 &l= t;< 8)

+#define IO= W_WAIT_SIGNAL (1 << 9)

-#define IOW_READ (IOW_READ_TUN|IOW_R= EAD_LINK)
+#define IO= W_READ (IOW_READ_TUN | IOW_READ_LINK)

ex= tern counter_type link_read_bytes_global;

extern counter_type link_write_bytes_global;


= -void get_io_flags_dowork_udp(str= uct context *c, struct multi_io *multi_io, const unsigned int flags);
+void get_io_flags_dowork_= udp(struct context *c, struct multi_io *multi_io,
+ const unsigned i= nt flags);

void get_io_flags_udp(struct = context *c, struct multi_io *multi_io, const unsigned int flags);
@@ -192,7 +193,8 @@
* @param ori= g_buf - Pointer to a buffer data.
*
*/<= /span>
-void process_incoming_= link_part2(struct context *c, struct link_socket_info *lsi, const uint8_t *= orig_buf);
+void proc= ess_incoming_link_part2(struct context *c, struct link_socket_info *lsi,
+ = const uint8_t *orig_buf);

/**=
* Transfers \c float_sa data extracted from an incoming = DCO
@@ -204,10 +206,8 @@
* @param float_s= a - The sockaddr struct containing the data received from the
* DCO notification

*/
-void
-extract_dco_float_peer_addr(sa_family_t socket_family,- str= uct openvpn_sockaddr *out_osaddr,
- const struct sockaddr *float_sa);
+void extract_dco_floa= t_peer_addr(sa_family_t socket_family, struct openvpn_sockaddr *out_osaddr,=
+ = const struct sockaddr *float_sa);
/**
* Write a packet to the external network inte= rface.
@@ -285,8 +285,7 @@
* @param str = - The message to be sent
* @param msglevel - Mess= age level to use for logging
*/
-bool
-send_control_channel_string(struct context *c, const char *str, = int msglevel);
+bool = send_control_channel_string(struct context *c, const char *str, int msgleve= l);

/*
* Send a string= to remote over the TLS control channel.
@@ -304,9 +303,7 @= @
* @param msglevel - Message level to use for logging<= /span>
*/

-bool
-= send_control_channel_string_dowork(struct tls_session *session,
<= span style=3D"color: hsl(0, 100%, 40%);">- = const char *str, int msglevel);

+bool send_control_channel_string_dowork(struct tls_session *s= ession, const char *str, int msglevel);

=
/**
@@ -317,13 +314,13 @@
*/

void reschedule_multi_process(struct context *c);

-#defin= e PIPV4_PASSTOS (1<<0)
-#define PIP_MSSFIX (1<<= 1) /* v4 and v6 */
-#define PIP_OUTGOING (1<<2)
-#define PIPV4_EXTRACT_DHCP_ROUTER = (1<<3)
-#define = PIPV4_CLIENT_NAT (1<<4)
-#define PIPV6_ICMP_NOHOST_CLIENT (1<<5)=
-#define PIPV6_ICMP_NO= HOST_SERVER (1<<6)
+#define PIPV4_PASSTOS (1 << 0)
+#define PIP_MSSFIX = (1 << 1) /* v4 and v6 */

+#define PIP_OUTGOING (1 << 2)
+#define PIPV4_EXTRACT_DHCP_ROUTER (= 1 << 3)

+#defin= e PIPV4_CLIENT_NAT (1 << 4)
+#define PIPV6_ICMP_NOHOST_CLIENT (1 << 5)
+#define PIPV6_ICMP_NOHO= ST_SERVER (1 << 6)


void process_ip_header(struct context *c, unsigned int flags, struct bu= ffer *buf,

@@ -365,7 +362,7 @@
static inli= ne unsigned int
p2p_iow_flags(const struct context *c)
{
- un= signed int flags =3D (IOW_SHAPER|IOW_CHECK_RESIDUAL|IOW_FRAG|IOW_READ|IOW_W= AIT_SIGNAL);
+ uns= igned int flags =3D (IOW_SHAPER | IOW_CHECK_RESIDUAL | IOW_FRAG | IOW_READ = | IOW_WAIT_SIGNAL);
if (c->c2.to_link.len > 0)
{
flags |=3D IOW_TO_LINK;
@@ -384,8 +381,8 @@
static inline void<= br> io_wait(struct context *c, const unsigned int flags)
{

- if (proto_i= s_dgram(c->c2.link_sockets[0]->info.proto)
- && c->c2.fast_io && (= flags & (IOW_TO_TUN|IOW_TO_LINK|IOW_MBUF)))
+ if (proto_is_dgram(c->c2.link_sockets[0]= ->info.proto) && c->c2.fast_io
+ && (flags & (IOW_TO_TUN | IOW_= TO_LINK | IOW_MBUF)))
{
/* fa= st path -- only for TUN/TAP/UDP writes */
unsigned= int ret =3D 0;
@@ -393,7 +390,7 @@
= {
ret |=3D TUN_WRITE;
= }
- if (flags= & (IOW_TO_LINK|IOW_MBUF))
+ if (flags & (IOW_TO_LINK | IOW_MBUF))
{

ret |=3D SOCKET_WRITE;
= }
diff --git a/src/openvpn/fragment.c b/src/= openvpn/fragment.c
index a7fbe09..7fc42e5 100644
= --- a/src/openvpn/fragment.c
+++ b/src/openvpn/fragme= nt.c
@@ -34,7 +34,11 @@
#include "int= eger.h"
#include "memdbg.h"

-#define FRAG_ERR(s)= { errmsg =3D s; goto error; }
+#define FRAG_ERR(s) \
+ { \
+ errmsg =3D s; \
+ goto error; \
+ }

static void
fragment_list_buf_init(struct fragment_list *list, const st= ruct frame *frame)
@@ -132,8 +136,7 @@
* = If a fragment fully completes the datagram, return the datagram.
= */
void
-fragment_incoming(struct fragment_master *f, struct buffer *buf,=
- con= st struct frame *frame)
+fragment_incoming(struct fragment_master *f, struct buffer *buf, const = struct frame *frame)
{
const char *er= rmsg =3D NULL;
fragment_header_type flags =3D 0;
@@ -164,11 +167,8 @@
/* handle the frag= ment type */
if (frag_type =3D=3D FRAG_WHOLE)
{
= - dmsg(D_FRAG_DEBUG,
- "FRAG_IN buf->len=3D%d type=3DFRAG_WHOLE= flags=3D"
- = fragment_header_format,
- buf->len,
- flags);
+ dmsg(D_FRAG_DEBUG, "FRAG_IN buf-= >len=3D%d type=3DFRAG_WHOLE flags=3D" fragment_header_format,
+ buf->= len, flags);

if (flags &= (FRAG_SEQ_ID_MASK | FRAG_ID_MASK))
{@@ -179,22 +179,18 @@
{
= const int seq_id =3D ((flags >> FRAG_SEQ_ID_SHIFT) & F= RAG_SEQ_ID_MASK);
const int n =3D ((flags >= > FRAG_ID_SHIFT) & FRAG_ID_MASK);
- const int size =3D ((frag_type =3D=3D FRAG_Y= ES_LAST)
- = ? (int)(((flags >> FRAG_SIZE_SHIFT) & FRAG_SIZE_= MASK) << FRAG_SIZE_ROUND_SHIFT)
- : buf->len);
+ const int size =3D
+ ((frag= _type =3D=3D FRAG_YES_LAST)
+ ? (int)(((flags >> FRAG_SIZE_SHIFT) &= ; FRAG_SIZE_MASK) << FRAG_SIZE_ROUND_SHIFT)
+ : buf->len);
/* get the appropriate fragment buff= er based on received seq_id */
struct fragment= *frag =3D fragment_list_get_buf(&f->incoming, seq_id);

- dmsg= (D_FRAG_DEBUG,
- = "FRAG_IN len=3D%d type=3D%d seq_id=3D%d frag_id=3D%d size=3D= %d flags=3D"
- = fragment_header_format,
- buf->len,
- frag_type,
- seq_id,
- n,
- size,
- flags);
+ dmsg(
+ D_FRAG_DEBUG,+ "FRAG_IN= len=3D%d type=3D%d seq_id=3D%d frag_id=3D%d size=3D%d flags=3D" fragm= ent_header_format,
+ = buf->len, frag_type, seq_id, n, size, flags);
<= span>

/* make sure that size is an even multi= ple of 1<<FRAG_SIZE_ROUND_SHIFT */
if (s= ize & FRAG_SIZE_ROUND_MASK)
@@ -257,11 +253,7 @@=

/* pack fragment parms into a uint32_t and pre= pend to buffer */
static void
-fragment_prepend_flags(struct buffer *buf,<= br>- int ty= pe,
- = int seq_id,
- = int frag_id,
- int frag_size)
+fragment_prepend_flags(struct buffer *buf, int t= ype, int seq_id, int frag_id, int frag_size)
{
<= span> fragment_header_type flags =3D ((type & FRAG_TYPE_MASK) <&= lt; FRAG_TYPE_SHIFT)

| ((= seq_id & FRAG_SEQ_ID_MASK) << FRAG_SEQ_ID_SHIFT)
= @@ -273,19 +265,19 @@
* If you want to set FRAG_E= XTRA_MASK/FRAG_EXTRA_SHIFT bits,
* do it here.
*/
- dmsg(D_FRAG_DEBUG,
- "FRAG_OUT len=3D%d type=3D%d seq_id=3D%d frag_i= d=3D%d frag_size=3D%d flags=3D"
- fragment_header_format,
- buf->len, type, seq_id, fra= g_id, frag_size, flags);
+ dmsg(
+ = D_FRAG_DEBUG,
+ "FRAG_OUT len=3D%d type=3D%d seq_id=3D%d frag_id=3D%d= frag_size=3D%d flags=3D" fragment_header_format,
+ buf->len, type, seq_id, f= rag_id, frag_size, flags);
}
else=
{
flags |=3D (((frag_size &g= t;> FRAG_SIZE_ROUND_SHIFT) & FRAG_SIZE_MASK) << FRAG_SIZE_SHIF= T);

-= dmsg(D_FRAG_DEBUG,
- "FRAG_OUT len=3D%d type=3D%d seq_id=3D%d frag_id=3D%= d frag_size=3D%d flags=3D"
- fragment_header_format,
- buf->len, type, seq_id, frag_id, f= rag_size, flags);
+ = dmsg(
+ = D_FRAG_DEBUG,
+ = "FRAG_OUT len=3D%d type=3D%d seq_id=3D%d frag_id=3D%d frag_s= ize=3D%d flags=3D" fragment_header_format,
+ buf->len, type, seq_id, frag_id,= frag_size, flags);
}

flags =3D hton_fragment_header_type(flags);

@@ -306,= 8 +298,9 @@

if (div > 0 &&= ; mod > 0 && mod < mfs_aligned * 3 / 4)
= {
- return min_i= nt(mfs_aligned, (max_frag_size - ((max_frag_size - mod) / (div + 1))=
- = + FRAG_SIZE_ROUND_MASK) & ~FRAG_SIZE_ROUND_MASK);
+ return min_int(mfs_align= ed,

+ = (max_frag_size - ((max_frag_size - mod) / (div + 1)) + FRAG_SIZE_ROU= ND_MASK)
+ = & ~FRAG_SIZE_ROUND_MASK);
}=
else
{
@@ -317,8 +310,7= @@

/* process an outgoing datagram, pos= sibly breaking it up into fragments */
void
-fragment_outgoing(struct fragment_ma= ster *f, struct buffer *buf,

- const struct frame *frame)
+fragment_outgoing(struct fragment_master = *f, struct buffer *buf, const struct frame *frame)
{
const char *errmsg =3D NULL;
if (buf-&= gt;len > 0)
@@ -326,8 +318,8 @@
= /* The outgoing buffer should be empty so we can put new data in it */
if (f->outgoing.len)
{
- msg(D_FRAG_E= RRORS, "FRAG: outgoing buffer is not empty, len=3D[%d,%d]",
- buf->len= , f->outgoing.len);
+ f->outgoing.len);
= }
if (buf->len > frame->max_fragment_si= ze) /* should we fragment? */
{
@@= -351,11 +343,7 @@
/*
= * Send the datagram whole.
*/- fragment_prepend_fl= ags(buf,
- = FRAG_WHOLE,
- 0,
- 0,- = 0);
+ = fragment_prepend_flags(buf, FRAG_WHOLE, 0, 0, 0);
= }
}
return;
@@ -3= 63,8 +351,8 @@
error:
if (errmsg)
{
- = msg(D_FRAG_ERRORS, "FRAG_OUT error, len=3D%d frag_size=3D%d MAX_= FRAGS=3D%d: %s",
-= buf->len, f->outgoing_frag_size, MAX_FRAGS, errmsg);
+ msg(D_FRAG_ERROR= S, "FRAG_OUT error, len=3D%d frag_size=3D%d MAX_FRAGS=3D%d: %s", = buf->len,
+ = f->outgoing_frag_size, MAX_FRAGS, errmsg);
}
buf->len =3D 0;
return;<= br>@@ -372,8 +360,7 @@

/* return t= rue (and set buf) if we have an outgoing fragment which is ready to send */=
bool
= -fragment_ready_to_send(struct fragment_master *f, struct buffer *buf,
- con= st struct frame *frame)
+fragment_ready_to_send(struct fragment_master *f, struct buffer *buf, c= onst struct frame *frame)
{
if (fragm= ent_outgoing_defined(f))
{
@@ -392,13 = +379,12 @@
ASSERT(buf_copy_n(buf, &f->outgo= ing, size));

/* fragment flags d= iffer based on whether or not we are sending the last fragment */- fragment_prepend_flags(= buf,
- = last ? FRAG_YES_LAST : FRAG_YES_NOTLAST,
- f->outgo= ing_seq_id,
- = f->outgoing_frag_id++,
- f->outgoing_frag= _size);
+ frag= ment_prepend_flags(buf, last ? FRAG_YES_LAST : FRAG_YES_NOTLAST, f->outg= oing_seq_id,
+ = f->outgoing_frag_id++, f->outgoing_frag_size)= ;

- = ASSERT(!last || !f->outgoing.len); /* outgoing buffer length shoul= d be zero after last fragment sent */
+ ASSERT(!last
+ || !f->outgoing
+ .len); /* outgoing= buffer length should be zero after last fragment sent */
=
return true;
}
diff --git a/src/openvpn/fragment.h b/src/openvpn/fragment.h

<= span>index 6120079..9719bf5 100644

--- a/src/openvpn/fragme= nt.h
+++ b/src/openvpn/fragment.h
@@ -45,15= +45,15 @@
#include "error.h"
<= /span>

-#def= ine N_FRAG_BUF 25
+#define N_FRAG_BUF 25
/**< Number of pa= cket buffers for
* reassembling incoming fragmented
* packets. */

-#define FRAG_TTL_SEC 10+#define FRAG_TTL_SEC 10
/**< Time-to-live in seconds for a %fragment. */
=
-#define FRAG_W= AKEUP_INTERVAL 5
+#define FRAG_WAKEUP_INTERVAL 5
/**< Interval in se= conds between calls to
* wakeup code. */

@@ -61,15 +61,16 @@
/**
* Structure for reassembling one incoming fragmented packet.

= */
-struct frag= ment {
- bool define= d; /**< Whether reassembly is currently
- * tak= ing place in this structure. */
+struct fragment
+{
+ bool d= efined; /**< Whether reassembly is currently
+ * taking place = in this structure. */

- int max_frag_size; /**< Maximum size of e= ach %fragment. */
+ = int max_frag_size; /**< Maximum size of each %fragment. */
<= span>

#define FRAG_MAP_MASK 0xFFFFFFFF
= /**< Mask for reassembly map. */
-#define MAX_FRAGS 32 /**< Maximum number of = fragments per packet. */
+#define MAX_FRAGS 32 /**< Maximum number of fragments per packe= t. */
unsigned int map;
/**< R= eassembly map for recording which
* fragments have = been received.
@@ -80,10 +81,10 @@
* = n has been received. Needs to have
* at least \c= MAX_FRAGS bits. */

- time_t timestamp; /**< Timestamp for time-= to-live purposes. */
= + time_t timestamp; /**< Timestamp for time-to-live purposes. */

- str= uct buffer buf; /**< Buffer in which received datagrams<= br>- = * are reassembled. */
+ struct buffer buf; /**< Buffer in which received datagrams
+ = * are reassembled. */
};

=
@@ -135,11 +136,12 @@
* fragment_= incoming() function adds newly received parts into this array
* and returns the whole packets once reassembly is complete.
*/
-struct fra= gment_master {
+struc= t fragment_master
+{<= /span>
struct event_timeout wakeup; /**< Timeout structure= used by the main
* ev= ent loop to know when to do
= * fragmentation housekeeping. */
-#define N_SEQ_ID 256
+#define N_SEQ_ID 256
/**&= lt; One more than the maximum fragment
* sequence I= D, above which the IDs wrap
* to zero. Should be a= power of 2. */
@@ -195,24 +197,24 @@
#def= ine ntoh_fragment_header_type(x) ntohl(x)
/**< Convert = a \c fragment_header_type from network to host order. */
<= /span>
-#define FRAG_TYPE_MASK= 0x00000003 /**< Bit mask for %fragment type info. */
-#define FRAG_TYPE_SHIFT = 0 /**< Bit shift for %fragment type info. */<= br>+#define FRAG_TYPE_MASK 0x0= 0000003 /**< Bit mask for %fragment type info. */
+#define FRAG_TYPE_SHIFT 0 /**<= ; Bit shift for %fragment type info. */

-#define FRAG_WHOLE 0 = /**< Fragment type indicating packet is whole. */
-#define FRAG_YES_NOTLAST = 1

+#define FRAG_WHO= LE 0 /**< Fragment type indicating packet is whole. */
+#define FRAG_YES_NOTLAS= T 1
/**< Fragment type indicating packet is part of a f= ragmented packet, but not
* the last part in the sequen= ce. */
-#define FRAG_YE= S_LAST 2
+#define FRAG_YES_LAST 2
/**< Fragment type indic= ating packet is the last part in the sequence of parts. */
-#define FRAG_TEST 3=
+#define FRAG_TEST = 3
/**< Fragment type not implemented yet.<= br> * In the future might be used as a control packet for establishi= ng MTU size. */

-#define FRAG_SEQ_ID_MASK 0x000000ff /**< Bit mas= k for %fragment sequence ID. */
-#define FRAG_SEQ_ID_SHIFT 2 /**< Bit shift= for %fragment sequence ID. */
+#define FRAG_SEQ_ID_MASK 0x000000ff /**< Bit mask for %fragm= ent sequence ID. */
+= #define FRAG_SEQ_ID_SHIFT 2 /**< Bit shift for %fragment sequen= ce ID. */

-#define FRAG_ID_MASK 0x0000001f /**< Bit mask for = %fragment ID. */
-#defi= ne FRAG_ID_SHIFT 10 /**< Bit shift for %fragment = ID. */
+#define FRAG_= ID_MASK 0x0000001f /**< Bit mask for %fragment ID. */
+#define FRAG_ID_SHIFT 10 = /**< Bit shift for %fragment ID. */



/*
@@ -224,10 +226,10 @@
* max_frag_size is only sent over the wire if FRAG_LAST is set. Oth= erwise it is assumed

* to be the actual %fragment size = received.
*/
-#define FRAG_SIZE_MASK 0x00003fff /**< Bit mask f= or %fragment size. */
-= #define FRAG_SIZE_SHIFT 15 /**< Bit shift for %frag= ment size. */
-#define = FRAG_SIZE_ROUND_SHIFT 2 /**< Bit shift for %fragment siz= e rounding. */
-#define= FRAG_SIZE_ROUND_MASK ((1 << FRAG_SIZE_ROUND_SHIFT) - 1)
+#define FRAG_SIZE_MASK = 0x00003fff /**< Bit mask for %fragment size. */
+#define FRAG_SIZE_SHIFT 15 = /**< Bit shift for %fragment size. */
+#define FRAG_SIZE_ROUND_SHIFT 2 /**< Bi= t shift for %fragment size rounding. */
+#define FRAG_SIZE_ROUND_MASK ((1 << FRAG_SIZE_RO= UND_SHIFT) - 1)
/**< Bit mask for %fragment size roundi= ng. */

/*
@@ -235,14 +23= 7,14 @@
*
* IF FRAG_WHOLE or FRAG_YES_N= OTLAST, these 16 bits are available (not currently used)
= */
-#define FRAG_EXTRA_= MASK 0x0000ffff /**< Bit mask for extra bits. */
= -#define FRAG_EXTRA_SHIFT = 15 /**< Bit shift for extra bits. */
+#define FRAG_EXTRA_MASK 0x0000ffff /**&l= t; Bit mask for extra bits. */
+#define FRAG_EXTRA_SHIFT 15 /**< Bit shift for extra = bits. */

-/** @} name Fragment header *//***************************************= *****/
+/** @} name F= ragment header */ /********************************************/


/**************************= ************************************************/
-/** @name Functions for initialization and clea= nup *//** @{ *//************/
+/** @name Functions for initialization and cleanup */ /** @{ */ /= ************/

/**
* Al= locate and initialize a \c fragment_master structure.
@@ -2= 78,7 +280,7 @@
*/
void fragment_free(str= uct fragment_master *f);

-/** @} name Functions for initialization and cleanup *= //*******************/
-void fragment_incoming(struct fragment_master *f, struct buffer *buf= ,
- = const struct frame *frame);
+void fragment_incoming(struct fragment_master *f, struct buffer = *buf, const struct frame *frame);

/** @}= name Functions for processing packets received from a VPN tunnel */=

@@ -378,8 +379,7 @@
* cas= es a fragmentation header will have been prepended to inform the
= * remote peer how to handle the packet.
*/
-void fragment_outgoing(s= truct fragment_master *f, struct buffer *buf,
- const struct frame *frame);<= /span>
+void fragment_outgoi= ng(struct fragment_master *f, struct buffer *buf, const struct frame *frame= );

/**
* Check whether= outgoing fragments are ready to be send, and if so make
@@= -435,7 +435,7 @@


/***= ***********************************************************************/
-/** @name Functions for = regular housekeeping *//** @{ *//******************/
+/** @name Functions for regular housekeep= ing */ /** @{ */ /******************/

/*= *
* Perform housekeeping of a \c fragment_master structur= e.
@@ -459,10 +459,10 @@
}
<= span> }


-/** @} name Functions for regular housekeeping *//*********************= ****/
+/** @} name Fu= nctions for regular housekeeping */ /*************************/
<= span>


+/** @} addtogro= up fragmentation */ /****************************************/


#endif /* ifdef ENABLE_FRAGMENT */=
diff --git a/src/openvpn/gremlin.c b/src/openvpn/gremlin.c=
index a3ecc8d..e6ebbef 100644
--- a/src/op= envpn/gremlin.c
+++ b/src/openvpn/gremlin.c
@@ -64,28 +64,29 @@

* When network goes up, it will be u= p for between
* UP_LOW and UP_HIGH seconds.
*/

-static const i= nt up_low[] =3D { 60, 10, 5 };
+static const int up_low[] =3D { 60, 10, 5 };
= static const int up_high[] =3D { 600, 60, 10 };
/*
* When network goes down, it will be down for= between
* DOWN_LOW and DOWN_HIGH seconds.
*/

-static const in= t down_low[] =3D { 5, 10, 10 };
+static const int down_low[] =3D { 5, 10, 10 };
static const int down_high[] =3D { 10, 60, 120 };


/*
* Packet flood levels:
= * { number of packets, packet size }
*/
-static const struct packet_flood_parm= s packet_flood_data[] =3D

-{{10, 100}, {10, 1500}, {100, 1500}};
+static const struct packet_flood_parms packet_flood_d= ata[] =3D { { 10, 100 },
+ { 10, 1= 500 },
+ = { 100, 1500 } };
struct packet_flood_parms
get_p= acket_flood_parms(int level)
{
ASSERT= (level > 0 && level < 4);
- return packet_flood_data [level - 1];
+ return packet_flood_data[level = - 1];

}

/*
@@ -147,18 +148,16 @@

int delta; if (up)
{
- delta =3D roll(down_lo= w[up_down_level-1], down_high[up_down_level-1]);
+ delta =3D roll(down_low[up_dow= n_level - 1], down_high[up_down_level - 1]);
= up =3D false;
}
= else
{
- delta =3D roll(up_low[up_down_level-1], up_= high[up_down_level-1]);
+ delta =3D roll(up_low[up_down_level - 1], up_high[up_do= wn_level - 1]);
up =3D true;
}


- msg(D_GREMLIN,
- "GREMLIN: CONNECTION GOING %s FOR %= d SECONDS",
- = (up ? "UP" : "DOWN"),
+ msg(D_GREMLIN, "GREMLIN:= CONNECTION GOING %s FOR %d SECONDS", (up ? "UP" : "DOW= N"),
delta);
= next =3D now + delta;
}
@@ -1= 66,7 +165,7 @@

if (drop_level)
{
- = if (up && flip(drop_freq[drop_level-1]))
+ if (up && flip(drop_freq[= drop_level - 1]))
{
d= msg(D_GREMLIN_VERBOSE, "GREMLIN: Random packet drop");
= return false;
@@ -185,7 +184,7 @@=
const int corrupt_level =3D GREMLIN_CORRUPT_LEVEL(flags);
if (corrupt_level)
{
- if (flip(corrupt_freq[corrup= t_level-1]))

+ = if (flip(corrupt_freq[corrupt_level - 1]))
{
do
{
= @@ -226,7 +225,7 @@
{
= break;
}
- } while (flip(2)); /* a 5= 0% chance we will corrupt again */
+ } while (flip(2)); /* a 50% chance we will corru= pt again */
}
}
}

diff --git a/src/openvpn/gremlin.h b/src/openvpn/grem= lin.h
index 3cbfb77..2422338 100644
--- a/s= rc/openvpn/gremlin.h
+++ b/src/openvpn/gremlin.h
= @@ -29,30 +29,32 @@
* Gremlin options, presented as= bitmask argument to --gremlin directive
*/

-#define GREMLIN_C= ONNECTION_FLOOD_SHIFT (0)
-#define GREMLIN_CONNECTION_FLOOD_MASK (0x07)
+#define GREMLIN_CONNECTION_FLOOD_SHIFT (0= )
+#define GREMLIN_CO= NNECTION_FLOOD_MASK (0x07)

-#define GREMLIN_PACKET_FLOOD_SHIFT (3)=
-#define GREMLIN_PACKET_FLOOD= _MASK (0x03)
+= #define GREMLIN_PACKET_FLOOD_SHIFT (3)
+#define GREMLIN_PACKET_FLOOD_MASK (0x03)

-#define GREMLIN_CO= RRUPT_SHIFT (5)
-#define GREMLIN_CORRUPT_MASK (0x03)
+#define GREMLIN_CORRUPT_SHIFT (5)<= br>+#define GREMLIN_CORRUPT_MAS= K (0x03)

-#define GREMLIN_UP_DOWN_SHIFT (7)
-#define GREMLIN_UP_DOWN_MASK (0x03= )
+#define GREMLIN_UP= _DOWN_SHIFT (7)
+#def= ine GREMLIN_UP_DOWN_MASK (0x03)

/* 512:= 1/500 1024:1/100 1536:1/50 */

-#define GREMLIN_DROP_SHIFT (9)
-#define GREMLIN_DROP_MASK = (0x03)
+#define GREMLIN_DROP_SHIFT (9)
+#define GREMLIN_DROP_MASK (0x03)

= /* extract gremlin parms */

-#define GREMLIN_CONNECTION_FLOOD_LEVEL(x) (= ((x)>>GREMLIN_CONNECTION_FLOOD_SHIFT) & GREMLIN_CONNECTION_FLOOD_= MASK)
-#define GREMLIN_= PACKET_FLOOD_LEVEL(x) (((x)>>GREMLIN_PACKET_FLOOD_SHIFT) &= ; GREMLIN_PACKET_FLOOD_MASK)
-#define GREMLIN_CORRUPT_LEVEL(x) (((x)>>GREMLIN_CORRU= PT_SHIFT) & GREMLIN_CORRUPT_MASK)
-#define GREMLIN_UP_DOWN_LEVEL(x) (((x)>= ;>GREMLIN_UP_DOWN_SHIFT) & GREMLIN_UP_DOWN_MASK)
= -#define GREMLIN_DROP_LEVEL(x) = (((x)>>GREMLIN_DROP_SHIFT) & GREMLIN_DROP_M= ASK)
+#define GREMLIN= _CONNECTION_FLOOD_LEVEL(x) \
+ (((x) >> GREMLIN_CONNECTION_FLOOD_SHIFT) & GREMLIN_C= ONNECTION_FLOOD_MASK)
+#define GREMLIN_PACKET_FLOOD_LEVEL(x) \
+ (((x) >> GREMLIN_PACKET_FLOOD_SHIFT) & = GREMLIN_PACKET_FLOOD_MASK)
+#define GREMLIN_CORRUPT_LEVEL(x) (((x) >> GREMLIN_CORRUPT_SHIF= T) & GREMLIN_CORRUPT_MASK)
+#define GREMLIN_UP_DOWN_LEVEL(x) (((x) >> GREMLIN_UP_DOWN_= SHIFT) & GREMLIN_UP_DOWN_MASK)
+#define GREMLIN_DROP_LEVEL(x) (((x) >> GREMLIN_DROP= _SHIFT) & GREMLIN_DROP_MASK)

#includ= e "buffer.h"

diff --git a/src/o= penvpn/helper.c b/src/openvpn/helper.c
index 36b88f5..b2ecb= 1e 100644
--- a/src/openvpn/helper.c
+++ b/= src/openvpn/helper.c
@@ -70,14 +70,12 @@
<= /span>
if (netmask)
{
- buf_printf(&out, "route= %s %s",
- = print_in_addr_t(network, 0, gc),
+ buf_printf(&out, "route %s %s"= ;, print_in_addr_t(network, 0, gc),
pri= nt_in_addr_t(netmask, 0, gc));
}
= else
{
- buf_printf(&out, "route %s",
- print_in_addr_t(netwo= rk, 0, gc));
+ = buf_printf(&out, "route %s", print_in_addr_t(network, 0, gc)= );
}

return BST= R(&out);
@@ -113,11 +111,8 @@
helper_a= dd_route(const in_addr_t network, const in_addr_t netmask, struct options *= o)
{
rol_check_alloc(o);
- add_route_to_option_list(o->= ;routes,

- = print_in_addr_t(network, 0, &o->gc),
- print_in= _addr_t(netmask, 0, &o->gc),

- NULL,
- NULL,
+ add_route_to_option_list(o-&g= t;routes, print_in_addr_t(network, 0, &o->gc),

+ print_in_add= r_t(netmask, 0, &o->gc), NULL, NULL,
= o->route_default_table_id);
}
=
@@ -127,10 +122,8 @@
struct gc= _arena gc =3D gc_new();
if ((a & subnet) !=3D (b &= amp; subnet))
{
- msg(M_USAGE, "%s IP addresses %s and %s are not= in the same %s subnet",
- opt,
- print_in_addr_t(b, 0, &gc),=
+ msg(M_USAGE, "= ;%s IP addresses %s and %s are not in the same %s subnet", opt,=
+ print_in_addr_= t(a, 0, &gc), print_in_addr_t(b, 0, &gc),
= print_in_addr_t(subnet, 0, &gc));
}
= gc_free(&gc);
@@ -206,17 +199,17 @@ }
if (o->ifconfig_ipv6_pool_de= fined)
{
- msg(M_USAGE, "--server-ipv6 already defines an= ifconfig-ipv6-pool, so you can't also specify --ifconfig-pool explicit= ly");
+ = msg(M_USAGE,
+ = "--server-ipv6 already defines an ifconfig-ipv6-pool, so y= ou can't also specify --ifconfig-pool explicitly");
}


o->mode =3D MODE= _SERVER;
o->tls_server =3D true;

/* local ifconfig is "base address + 1&qu= ot; and "+2" */
- o->ifconfig_ipv6_local =3D
- print_in6_addr( add_in6_addr( o->server_= network_ipv6, 1), 0, &o->gc );
+ o->ifconfig_ipv6_local =3D print_in6_addr(add_= in6_addr(o->server_network_ipv6, 1), 0, &o->gc);
= o->ifconfig_ipv6_remote =3D
- print_in6_addr( add_in6_addr( o->server_ne= twork_ipv6, 2), 0, &o->gc );
+ print_in6_addr(add_in6_addr(o->server_networ= k_ipv6, 2), 0, &o->gc);
o->ifconfig_ipv6= _netbits =3D o->server_netbits_ipv6;

= /* basic sanity check */
@@ -228,8 +221,8 @@=
*
* Smaller pools can't g= et that far, therefore we just increase by 2
*/
- o->ifconfig_= ipv6_pool_base =3D add_in6_addr(o->server_network_ipv6,
- = o->server_netbits_ipv6 < 112 ? 0x1000 : 2);
+ o->ifconfig_ipv6_pool_= base =3D

+ = add_in6_addr(o->server_network_ipv6, o->server_netbits_ipv6 < 112= ? 0x1000 : 2);
o->ifconfig_ipv6_pool_netbits = =3D o->server_netbits_ipv6;

p= ush_option(o, "tun-ipv6", M_USAGE);
@@ -283,12 +2= 76,14 @@

if (o->shared_secret= _file)
{
- msg(M_USAGE, "--server and --secret cannot be = used together (you must use SSL/TLS keys)");
+ msg(M_USAGE,
+ "--server and --sec= ret cannot be used together (you must use SSL/TLS keys)");
<= span> }


if (!(o->serv= er_flags & SF_NOPOOL) && o->ifconfig_pool_defined) {
- = msg(M_USAGE, "--server already defines an ifconfig-pool, so yo= u can't also specify --ifconfig-pool explicitly");
+ msg(M_USAGE,

= + "--server= already defines an ifconfig-pool, so you can't also specify --ifconfig= -pool explicitly");
}

if (!(dev =3D=3D DEV_TYPE_TAP || dev =3D=3D DEV_TYPE_TU= N))
@@ -309,7 +304,8 @@

= if (netbits < IFCONFIG_POOL_MIN_NETBITS)
= {
- msg(M_= USAGE, "--server directive netmask allows for too many host addresses = (subnet must be %s or higher)",
+ msg(M_USAGE,
+ "--server directive netmask allo= ws for too many host addresses (subnet must be %s or higher)",<= br> print_netmask(IFCONFIG_POOL_MIN_NETBITS, &gc)= );
}

@@ -319,7 += 315,8 @@

if (netbits > 29= )
{
- msg(M_USAGE, "--server directive when used = with --dev tun must define a subnet of %s or lower",
+ msg(M_USAGE,+ "--= server directive when used with --dev tun must define a subnet of %s or low= er",
print_netmask(29, &gc));=
}

@@ -342,1= 4 +339,17 @@
{
= o->ifconfig_pool_defined =3D true;
= o->ifconfig_pool_start =3D o->server_network + 4;- o->ifcon= fig_pool_end =3D (o->server_network | ~o->server_netmask) - pool_end_= reserve;
- = ifconfig_pool_verify_range(M_USAGE, o->ifconfig_pool_start, o->= ;ifconfig_pool_end);
= + o->ifconfig_pool_end =3D
+ (o->server_network = | ~o->server_netmask) - pool_end_reserve;
+ ifconfig_pool_verify_range(M_U= SAGE, o->ifconfig_pool_start,
+ o->ifconfig_= pool_end);
}

<= span> helper_add_route(o->server_network, o->server_n= etmask, o);

if (o->enable_c2c) {
- push_option(o, print_opt_route(o->server_networ= k, o->server_netmask, &o->gc), M_USAGE);
+ push_option(o, print_opt= _route(o->server_network, o->server_netmask, &o->gc),+ = M_USAGE);
}
= else if (o->topology =3D=3D TOP_NET30)
= {
@@ -366,7 +366,8 @@
= o->ifconfig_pool_defined =3D true;
= o->ifconfig_pool_start =3D o->server_network + 2;
o->ifconfig_pool_end =3D (o->server_network = | ~o->server_netmask) - 1;

- ifconfig_pool_verify_range(M_USAGE, o->ifcon= fig_pool_start, o->ifconfig_pool_end);
+ ifconfig_pool_verify_range(M_USAG= E, o->ifconfig_pool_start,
+ o->ifconfig_poo= l_end);
}
= o->ifconfig_pool_netmask =3D o->server_netmask;

@@ -386,16 +387,17 @@
if (o->= topology =3D=3D TOP_NET30 && !(o->server_flags & SF_NOPOOL))=
{
msg(M_WARN= , "WARNING: --topology net30 support for server "
- "configs wit= h IPv4 pools will be removed in a future "

- "release. Please migrate= to --topology subnet as soon "
- "as possible.");
+ "= ;configs with IPv4 pools will be removed in a future "

+ "r= elease. Please migrate to --topology subnet as soon "

+ "as= possible.");
}
= }
else if (dev =3D=3D DEV_TYPE_TAP)
{

if (netbits > 30)
{

- = msg(M_USAGE, "--server directive when used with --dev tap= must define a subnet of %s or lower",
+ msg(M_USAGE,
+ "--server direct= ive when used with --dev tap must define a subnet of %s or lower",
print_netmask(30, &gc));
}


@@ -463,12 +465,14 @@<= /span>

if (!(o->server_flags & S= F_NOPOOL) && o->ifconfig_pool_defined)
= {
- msg(M_US= AGE, "--server-bridge already defines an ifconfig-pool, so you can'= ;t also specify --ifconfig-pool explicitly");
+ msg(M_USAGE,
+ "--server-bridge a= lready defines an ifconfig-pool, so you can't also specify --ifconfig-p= ool explicitly");
}
<= br> if (o->shared_secret_file)
{<= /span>
- msg(M_USAG= E, "--server-bridge and --secret cannot be used together (you must use= SSL/TLS keys)");
+ "--server-bridge and --secret cannot be used t= ogether (you must use SSL/TLS keys)");
}

if (dev !=3D DEV_TYPE_TAP)@@ -478,9 +482,12 @@

if (= o->server_bridge_defined)
{
- verify_common_subnet("--= server-bridge", o->server_bridge_ip, o->server_bridge_pool_start= , o->server_bridge_netmask);
- verify_common_subnet("--server-bridge", o-&= gt;server_bridge_pool_start, o->server_bridge_pool_end, o->server_bri= dge_netmask);
- = verify_common_subnet("--server-bridge", o->server_bridge_i= p, o->server_bridge_pool_end, o->server_bridge_netmask);
+ verify_common_subnet= ("--server-bridge", o->server_bridge_ip,

+ o->se= rver_bridge_pool_start, o->server_bridge_netmask);
+ verify_common_subnet("--= server-bridge", o->server_bridge_pool_start,
+ o->se= rver_bridge_pool_end, o->server_bridge_netmask);
+ verify_common_subnet("--= server-bridge", o->server_bridge_ip, o->server_bridge_pool_end,<= /span>
+ = o->server_bridge_netmask);
}

o->mode =3D MODE_SERVER;@@ -551,13 +558,14 @@
}
= if (o->keepalive_ping * 2 > o->keepalive_timeout)
= {
- = msg(M_USAGE, "the second parameter to --keepalive (restart time= out=3D%d) must be at least twice the value of the first parameter (ping int= erval=3D%d). A ratio of 1:5 or 1:6 would be even better. Recommended sett= ing is --keepalive 10 60.",
- o->keepalive_timeout,
- o->keepalive_ping);
+ msg(M_USAGE,=
+ &qu= ot;the second parameter to --keepalive (restart timeout=3D%d) must be at le= ast twice the value of the first parameter (ping interval=3D%d). A ratio o= f 1:5 or 1:6 would be even better. Recommended setting is --keepalive 10 6= 0.",
+ = o->keepalive_timeout, o->keepalive_ping);
= }
if (o->ping_send_timeout || o->ping_re= c_timeout)
{
- msg(M_USAGE, "--keepalive conflicts with -= -ping, --ping-exit, or --ping-restart. If you use --keepalive, you don'= ;t need any of the other --ping directives.");
+ msg(M_USAGE,
+ "--keepalive co= nflicts with --ping, --ping-exit, or --ping-restart. If you use --keepaliv= e, you don't need any of the other --ping directives."); }

/*
<= span>diff --git a/src/openvpn/httpdigest.c b/src/openvpn/httpdigest.c
index be700b2..be20638 100644
--- a/src/openvpn/= httpdigest.c
+++ b/src/openvpn/httpdigest.c
@@ -32,10 +32,7 @@

#include "httpdigest.h"

static void
-CvtHex(
- IN HASH Bin,
- OUT HASHHEX Hex
-= )
+CvtHex(IN HASH= Bin, OUT HASHHEX Hex)
{
unsigned sho= rt i;
unsigned char j;
@@ -45,20 +42,2= 0 @@
j =3D (Bin[i] >> 4) & 0xf; if (j <=3D 9)
{
- Hex[i*2] =3D (j + '0= ');

+ = Hex[i * 2] =3D (j + '0');
}
else

{
- Hex[i*2] =3D (j + 'a' - 10);
+ Hex[i * 2] = =3D (j + 'a' - 10);
}
= j =3D Bin[i] & 0xf;
if (j <=3D 9)
{
= - Hex[i*2+1] =3D (j + '0');
+ Hex[i * 2 + 1] =3D (j + '0')= ;
}
else
= {
- = Hex[i*2+1] =3D (j + 'a' - 10);
+ Hex[i * 2 + 1] =3D (j + 'a' - 10);<= /span>
}
}
Hex[= HASHHEXLEN] =3D '\0';
@@ -66,34 +63,27 @@
/* calculate H(A1) as per spec */
void

-DigestCalcHA1(<= /span>
- IN char *pszAlg,
- IN char *pszUserNam= e,
- IN char *pszRea= lm,
- IN char *pszPa= ssword,
- IN char *p= szNonce,
- IN char *= pszCNonce,
- OUT HAS= HHEX SessionKey
- )<= /span>
+DigestCalcHA1(IN cha= r *pszAlg, IN char *pszUserName, IN char *pszRealm, IN char *pszPassword,
+ IN char= *pszNonce, IN char *pszCNonce, OUT HASHHEX SessionKey)
{<= /span>
HASH HA1;
md_ctx_t *md5_ctx =3D m= d_ctx_new();

md_ctx_init(md5_ctx, &q= uot;MD5");
- md= _ctx_update(md5_ctx, (const uint8_t *) pszUserName, strlen(pszUserName));
- md_ctx_update(md5_c= tx, (const uint8_t *) ":", 1);
- md_ctx_update(md5_ctx, (const uint8_t *) pszRealm, s= trlen(pszRealm));
- = md_ctx_update(md5_ctx, (const uint8_t *) ":", 1);
- md_ctx_update(md5_ctx, (const uin= t8_t *) pszPassword, strlen(pszPassword));

+ md_ctx_update(md5_ctx, (const uint8_t *)pszUserN= ame, strlen(pszUserName));
+ md_ctx_update(md5_ctx, (const uint8_t *)":", 1);
+ md_ctx_update(md5_ctx= , (const uint8_t *)pszRealm, strlen(pszRealm));
+ md_ctx_update(md5_ctx, (const uint8_t *)&qu= ot;:", 1);
+ = md_ctx_update(md5_ctx, (const uint8_t *)pszPassword, strlen(pszPassword));<= /span>
md_ctx_final(md5_ctx, HA1);
if (p= szAlg && strcasecmp(pszAlg, "md5-sess") =3D=3D 0)<= br> {
md_ctx_init(md5_ctx, "MD5&quo= t;);
md_ctx_update(md5_ctx, HA1, HASHLEN);<= br>- md_ctx_update(md5_ctx= , (const uint8_t *) ":", 1);
- md_ctx_update(md5_ctx, (const uint8_t *) pszNonce,= strlen(pszNonce));
- = md_ctx_update(md5_ctx, (const uint8_t *) ":", 1);- md_ctx_update(md5_ctx, = (const uint8_t *) pszCNonce, strlen(pszCNonce));
+ md_ctx_update(md5_ctx, (const uint8_t = *)":", 1);
= + md_ctx_update(md5_ctx, (const uint8_t *)pszNonce, strlen(pszNonce)= );
+ md_ctx_up= date(md5_ctx, (const uint8_t *)":", 1);
+ md_ctx_update(md5_ctx, (const uint8_t= *)pszCNonce, strlen(pszCNonce));
md_ctx_final(md5= _ctx, HA1);
}
md_ctx_cleanup(md5_= ctx);
@@ -103,17 +93,16 @@

/* calculate request-digest/response-digest as per HTTP Digest spec */
void
-D= igestCalcResponse(
- = IN HASHHEX HA1, /* H(A1) */
- IN char *pszNonce, = /* nonce from server */
- IN char *pszNonceCount, /* 8 hex digits */<= br>- IN char *pszCNonce, = /* client nonce */
- IN char *pszQop, /* qop-value: &qu= ot;", "auth", "auth-int" */
- IN char *pszMethod, = /* method from the request */
- IN char *pszDigestUri, /* requested URL */<= /span>
- IN HASHHEX HEntity= , /* H(entity body) if qop=3D"auth-int" */
- OUT HASHHEX Respons= e /* request-digest or response-digest */
- )

+DigestCalcResponse(IN HASHHEX HA1, /* H(A= 1) */
+ = IN char *pszNonce, /* nonce from server */
+ IN char *pszNonceCount= , /* 8 hex digits */
= + IN char *pszCNonce, /* client nonce */
+ IN char *pszQ= op, /* qop-value: "", "auth", "auth-int&quo= t; */

+ = IN char *pszMethod, /* method from the request */
+ IN char *pszDiges= tUri, /* requested URL */
+ IN HASHHEX HEntity, /* H(entity body) if qop= =3D"auth-int" */
+ OUT HASHHEX Response /* request-digest or resp= onse-digest */
+)
{
HASH HA2;
HASH Re= spHash;
@@ -123,12 +112,12 @@

<= span> /* calculate H(A2) */

md_ctx_init(md5_ctx, &= quot;MD5");
- m= d_ctx_update(md5_ctx, (const uint8_t *) pszMethod, strlen(pszMethod));

- md_ctx_update(md5_ctx,= (const uint8_t *) ":", 1);
- md_ctx_update(md5_ctx, (const uint8_t *) pszDigestUri, = strlen(pszDigestUri));
+ md_ctx_update= (md5_ctx, (const uint8_t *)":", 1);
+ md_ctx_update(md5_ctx, (const uint8_t *)pszDi= gestUri, strlen(pszDigestUri));
if (strcasecmp(pszQop,= "auth-int") =3D=3D 0)
{
- md_ctx_update(md5_ctx, (const uin= t8_t *) ":", 1);
+ md_ctx_update(md5_ctx, (const uint8_t *)":", 1);
md_ctx_update(md5_ctx, HEntity, HASHHEXLEN);=
}
md_ctx_final(md5_ctx, HA2);@@ -137,17 +126,17 @@
/* calculate response */<= /span>
md_ctx_init(md5_ctx, "MD5");
md_ctx_update(md5_ctx, HA1, HASHHEXLEN);

- md_ctx_update(md5_ctx, (const uint8_t *) "= ;:", 1);
- md_c= tx_update(md5_ctx, (const uint8_t *) pszNonce, strlen(pszNonce));- md_ctx_update(md5_ctx, (con= st uint8_t *) ":", 1);
+ md_ctx_update(md5_ctx, (const uint8_t *)":", 1);=
+ md_ctx_update(m= d5_ctx, (const uint8_t *)pszNonce, strlen(pszNonce));
+ md_ctx_update(md5_ctx, (const uint8_t= *)":", 1);
if (*pszQop)
= {
- md_ctx_upd= ate(md5_ctx, (const uint8_t *) pszNonceCount, strlen(pszNonceCount));
- md_ctx_update(md5_c= tx, (const uint8_t *) ":", 1);
- md_ctx_update(md5_ctx, (const uint8_t *) pszCNon= ce, strlen(pszCNonce));
- md_ctx_update(md5_ctx, (const uint8_t *) ":", 1);
- md_ctx_update(md5_c= tx, (const uint8_t *) pszQop, strlen(pszQop));
- md_ctx_update(md5_ctx, (const uint8_t *) &= quot;:", 1);
+ = md_ctx_update(md5_ctx, (const uint8_t *)pszNonceCount, strlen(pszNonc= eCount));
+ md= _ctx_update(md5_ctx, (const uint8_t *)":", 1);
+ md_ctx_update(md5_ctx, (const = uint8_t *)pszCNonce, strlen(pszCNonce));
+ md_ctx_update(md5_ctx, (const uint8_t *)"= :", 1);
+ = md_ctx_update(md5_ctx, (const uint8_t *)pszQop, strlen(pszQop));+ md_ctx_update(md5_ctx= , (const uint8_t *)":", 1);
}
md_ctx_update(md5_ctx, HA2Hex, HASHHEXLEN);

md_= ctx_final(md5_ctx, RespHash);
diff --git a/src/openvpn/http= digest.h b/src/openvpn/httpdigest.h
index ecdd6d3..1b51a62 = 100644
--- a/src/openvpn/httpdigest.h
+++ b= /src/openvpn/httpdigest.h
@@ -25,34 +25,26 @@
#define HASHLEN 16

typedef unsigned char HASH[HASHLEN]= ;
#define HASHHEXLEN 32
-typedef unsigned char HASHHEX[HASHHEXLEN+1];
<= span style=3D"color: hsl(120, 100%, 40%);">+typedef unsigned char HASHHEX[H= ASHHEXLEN + 1];

#undef IN
#undef OUT
#define IN const
#define OUT
=
/* calculate H(A1) as per HTTP Digest spec */
= -void DigestCalcHA1(
- IN char *pszAlg,

- IN char *pszUserName,
- IN char *pszRealm,- IN char *pszPassword,
- IN char *pszNonce,
- IN char *pszCNonce,
- OUT HASHHEX Session= Key
- );
<= span style=3D"color: hsl(120, 100%, 40%);">+void DigestCalcHA1(IN char *psz= Alg, IN char *pszUserName, IN char *pszRealm, IN char *pszPassword,
<= br>+ IN char = *pszNonce, IN char *pszCNonce, OUT HASHHEX SessionKey);

/* calculate request-digest/response-digest as per HTTP Dig= est spec */
-void Diges= tCalcResponse(
- IN = HASHHEX HA1, /* H(A1) */
- IN char *pszNonce, /* nonce from server */- IN char *pszNonceCount, = /* 8 hex digits */
- = IN char *pszCNonce, /* client nonce */
- IN char *pszQop, /* qop-value: "&= quot;, "auth", "auth-int" */
- IN char *pszMethod, /* method from the= request */
- IN cha= r *pszDigestUri, /* requested URL */
- IN HASHHEX HEntity, /* H(entity body) if qop=3D= "auth-int" */
- OUT HASHHEX Response /* request-digest or response-digest */
- );
+void DigestCalcResponse(IN HASHHEX HA1= , /* H(A1) */
+ IN char *pszNonce, /* nonce from server */
+ = IN char *pszNonceCount, /* 8 hex digits */
+ IN char *pszCNonce, /= * client nonce */
+ = IN char *pszQop, /* qop-value: "", &= quot;auth", "auth-int" */
+ IN char *pszMethod, /* met= hod from the request */
+ IN char *pszDigestUri, /* requested URL */
+ = IN HASHHEX HEntity, /* H(entity body) if qop=3D"auth-int" */=
+ = OUT HASHHEX Response /* request-digest or response-digest */=
+);

#endif /* if PROXY_DIGEST_AUTH */
diff --git a/= src/openvpn/init.c b/src/openvpn/init.c
index 32f20e1..40ae= 2c8 100644
--- a/src/openvpn/init.c
+++ b/s= rc/openvpn/init.c
@@ -58,15 +58,15 @@
#inc= lude "memdbg.h"


-static struct context *static_conte= xt; /* GLOBAL */

+sta= tic struct context *static_context; /* GLOBAL */
static c= onst char *saved_pid_file_name; /* GLOBAL */

/*

* Crypto initialization flags
*= /
-#define CF_LOAD_PERS= ISTED_PACKET_ID (1<<0)
-#define CF_INIT_TLS_MULTI (1<<1)
-#define CF_INIT_TLS_AUTH_STANDALONE (1<= ;<2)
+#define CF_L= OAD_PERSISTED_PACKET_ID (1 << 0)
+#define CF_INIT_TLS_MULTI (1 << 1)
+#define CF_INIT_TLS_AUTH_= STANDALONE (1 << 2)

static void do= _init_first_time(struct context *c);

@@ -= 105,21 +105,14 @@
* Used to execute the up/down script/pl= ugins.
*/
static void
-run_up_down(const char *command,<= br>- const struct plug= in_list *plugins,
- = int plugin_type,
+run_up_down(const char *command, const struct plugin_list *plugins, in= t plugin_type,
const char *arg,
#ifdef _WIN32

DWORD adapter_index, #endif
- = const char *dev_type,
- int tun_mtu,
- const char *ifconfig_local,
- const char *ifconfig_remote,<= br>- const char *conte= xt,
- const = char *signal_text,
- = const char *script_type,
- struct env_set *es)
+ const char *dev_type, int tun_mtu, cons= t char *ifconfig_local,
+ const char *ifconfig_remote, const char *context, const cha= r *signal_text,
+ = const char *script_type, struct env_set *es)
{
struct gc_arena gc =3D gc_new();
=
@@ -155,9 +148,8 @@
{
= struct argv argv =3D argv_new();
ASSERT(arg);
- argv_printf(&am= p;argv,
- = "%s %d 0 %s %s %s",
- arg, tun_mtu, ifconfig_local, ifconfig_re= mote, context);
+ = argv_printf(&argv, "%s %d 0 %s %s %s", arg, tun_mtu, ifco= nfig_local, ifconfig_remote,
+ context);

= if (plugin_call(plugins, plugin_type, &argv, NULL, es) !=3D OPEN= VPN_PLUGIN_FUNC_SUCCESS)
{
@@ -173= ,8 +165,8 @@
ASSERT(arg);
= setenv_str(es, "script_type", script_type);
= argv_parse_cmd(&argv, command);
- argv_printf_cat(&argv, "%s %d 0 %s %s %= s", arg, tun_mtu,
= - ifconfig_local, ifconfig_remote, context);<= br>+ argv_printf_cat(&am= p;argv, "%s %d 0 %s %s %s", arg, tun_mtu, ifconfig_local, ifconfi= g_remote,
+ = context);
argv_msg(M_INFO, &argv= );
openvpn_run_script(&argv, es, S_FATAL, &quo= t;--up/--down");
argv_free(&argv);=
@@ -196,8 +188,7 @@
* for the period of tim= e before we pull the --ping-restart parameter
* from = the server.
*/
- if (options->pull
- && options->ping_rec_timeout_action = =3D=3D PING_UNDEF
+ = if (options->pull && options->ping_rec_timeout_action =3D= =3D PING_UNDEF
&& proto_is_dgram(options-&= gt;ce.proto))
{
options->p= ing_rec_timeout =3D PRE_PULL_INITIAL_PING_RESTART;
@@ -303,= 11 +294,9 @@
* @return if sending was succes= sful
*/
static bool
-management_callback_send_cc_message(void *= arg,
- = const char *command,
- const char *parameter= s)
+management_callba= ck_send_cc_message(void *arg, const char *command, const char *parameters)<= /span>
{
- = struct context *c =3D (struct context *) arg;
+ struct context *c =3D (struct context *)arg;=
size_t len =3D strlen(command) + 1 + strlen(parameter= s) + 1;
if (len > PUSH_BUNDLE_SIZE)
{

@@ -331,7 +320,7 @@
management_cal= lback_remote_entry_count(void *arg)
{
= assert(arg);
- stru= ct context *c =3D (struct context *) arg;
+ struct context *c =3D (struct context *)arg;
struct connection_list *l =3D c->options.connection_lis= t;

return l->len;
@@ -343,7 +332,7 @@

assert(arg);
= assert(remote);

- struct context *c =3D (struct context *) arg;
+ struct context *c =3D (struc= t context *)arg;

struct connection_list *l =3D c->o= ptions.connection_list;
bool ret =3D true;
<= span>

@@ -354,8 +343,8 @@
const c= har *status =3D (ce->flags & CE_DISABLED) ? "disabled" : &= quot;enabled";

/* space for= output including 3 commas and a nul */
- int len =3D strlen(ce->remote) + strlen(ce->= ;remote_port) + strlen(proto)
- + strlen(status) + 3 + 1;
+ int len =3D
+ strlen(ce->remote) + strle= n(ce->remote_port) + strlen(proto) + strlen(status) + 3 + 1;
<= span> char *out =3D malloc(len);

check_mal= loc_return(out);

@@ -374,10 +363,12 @@
static bool
management_callback_remote_cmd(= void *arg, const char **p)
{
- struct context *c =3D (struct context *) arg;
+ struct context *c= =3D (struct context *)arg;
struct connection_entry *c= e =3D &c->options.ce;
int ret =3D false;=
- if (p[1] && ((ce= ->flags>>CE_MAN_QUERY_REMOTE_SHIFT)&CE_MAN_QUERY_REMOTE_MASK) = =3D=3D CE_MAN_QUERY_REMOTE_QUERY)
+ if (p[1]
+ && ((ce->flags >> CE_MAN_QUERY_REMOTE_SHIFT= ) & CE_MAN_QUERY_REMOTE_MASK)
+ =3D=3D CE_MAN_QUERY_REMOTE_QUERY)
{

int flags =3D 0;
= if (!strcmp(p[1], "ACCEPT"))
@@ -412,8 +403,8 = @@
}
if (ret)
<= span> {

- = ce->flags &=3D ~(CE_MAN_QUERY_REMOTE_MASK<<CE_MAN_QUERY_= REMOTE_SHIFT);
- = ce->flags |=3D ((flags&CE_MAN_QUERY_REMOTE_MASK)<<CE_MAN_= QUERY_REMOTE_SHIFT);
= + ce->flags &=3D ~(CE_MAN_QUERY_REMOTE_MASK << CE_M= AN_QUERY_REMOTE_SHIFT);
+ ce->flags |=3D ((flags & CE_MAN_QUERY_REMOTE_MASK) &= lt;< CE_MAN_QUERY_REMOTE_SHIFT);
}
}

return ret;
@@ -438,8 +429,= 8 @@

ce->flags &=3D ~(CE_= MAN_QUERY_REMOTE_MASK << CE_MAN_QUERY_REMOTE_SHIFT);
= ce->flags |=3D (CE_MAN_QUERY_REMOTE_QUERY << CE_MAN_QUERY= _REMOTE_SHIFT);
- = while (((ce->flags >> CE_MAN_QUERY_REMOTE_SHIFT)
- & CE_MAN_QUERY_RE= MOTE_MASK) =3D=3D CE_MAN_QUERY_REMOTE_QUERY)

+ while (((ce->flags >> CE_MAN_QUER= Y_REMOTE_SHIFT) & CE_MAN_QUERY_REMOTE_MASK)
+ =3D=3D CE_MAN_QUERY_REMOTE_QUERY= )
{
management_event_= loop_n_seconds(management, 1);
if (IS_SIG(c))<= /span>
@@ -457,8 +448,7 @@
/* If it is li= kely a connection entry was modified,
* check wha= t changed in the flags and that it was not skipped
= */
- const int= flags =3D ((ce->flags >> CE_MAN_QUERY_REMOTE_SHIFT)
- & CE= _MAN_QUERY_REMOTE_MASK);

+ const int flags =3D ((ce->flags >> CE_MAN_QUERY_REMOT= E_SHIFT) & CE_MAN_QUERY_REMOTE_MASK);
ce_chang= ed =3D (flags !=3D CE_MAN_QUERY_REMOTE_SKIP);
}=
return ce_changed;
@@ -635,7 +625,7 @@

/* Check if this connection attempt would= bring us over the limit */
if (c->options.connect_= retry_max > 0
- = && c->options.unsuccessful_attempts > (l->len * c->= options.connect_retry_max))
+ && c->options.unsuccessful_attempts > (l->= len * c->options.connect_retry_max))
{
msg(M_FATAL, "All connections have been connect-retry-max= (%d) times unsuccessful, exiting",

c->= ;options.connect_retry_max);
@@ -660,12 +650,11 @@ {
enable_auth_user_pass();
= #ifdef ENABLE_MANAGEMENT
- auth_user_pass_setup(c->options.auth_user_pass_file,
- = c->options.auth_user_pass_file_inline,
+ auth_user_pass_setup(c->options.auth= _user_pass_file, c->options.auth_user_pass_file_inline,
= &c->options.sc_info);
= #else
- auth_us= er_pass_setup(c->options.auth_user_pass_file,
- c->options.auth_= user_pass_file_inline, NULL);
+ auth_user_pass_setup(c->options.auth_user_pass_file, c= ->options.auth_user_pass_file_inline,
+ NULL);
#= endif
}
}
@@ -713,9 += 702,9 @@

if (!did_http && c-= >options.ce.socks_proxy_server)
{
- c->c1.socks_proxy =3D socks_= proxy_new(c->options.ce.socks_proxy_server,
- c->= options.ce.socks_proxy_port,
- c->options.ce.socks_p= roxy_authfile);
+ = c->c1.socks_proxy =3D
+ socks_proxy_new(c->options.ce.socks_proxy_server, c= ->options.ce.socks_proxy_port,
+ c->options.ce.socks_proxy_auth= file);
if (c->c1.socks_proxy)
= {
c->c1.socks_proxy_owned =3D true;=
@@ -738,8 +727,8 @@
static void do_link_socket_addr_new(struct context *c)
{
- ALLOC_ARRAY_CLEAR_GC(c-= >c1.link_socket_addrs, struct link_socket_addr,
- c->c1.link_sockets= _num, &c->gc);
+ ALLOC_ARRAY_CLEAR_GC(c->c1.link_socket_addrs, struct link_socket_a= ddr, c->c1.link_sockets_num,
+ &c->gc);
}

void
@@ -760,10 +749,11 @@<= /span>
{
int i;
= pkcs11_initialize(true, c->options.pkcs11_pin_cache_period);=
- for (i =3D 0; i<M= AX_PARMS && c->options.pkcs11_providers[i] !=3D NULL; i++)
+ for (i =3D 0; i &= lt; MAX_PARMS && c->options.pkcs11_providers[i] !=3D NULL; i++)<= /span>
{
- pkcs11_addProvider(c->options.pkcs11_providers[i], c-&g= t;options.pkcs11_protected_authentication[i],
- c->options.pkcs11= _private_mode[i], c->options.pkcs11_cert_private[i]);
+ pkcs11_addProvider(=
+ c->opti= ons.pkcs11_providers[i], c->options.pkcs11_protected_authentication[i],<= /span>
+ c-&g= t;options.pkcs11_private_mode[i], c->options.pkcs11_cert_private[i]);
}
}
#endif
@@ -788,9 +778,8 @@
* See possibly_becom= e_daemon() [init.c] for more details.
*/
sd_notifyf(0, "READY=3D1\nSTATUS=3DPre-connection initializat= ion successful\nMAINPID=3D%lu",

- (unsigned long) getpid());
+ (unsigned long)getpid()= );
#endif
-
}

void
= @@ -818,10 +807,9 @@
{
if (!por= t_share && (c->options.port_share_host && c->options.= port_share_port))
{
- port_share =3D port_share_open(c->options.por= t_share_host,
- = c->options.port_share_port,
- = c->c2.frame.buf.payload_size,

- c->options.port_share_jo= urnal_dir);
+ = port_share =3D
+ = port_share_open(c->options.port_share_host, c->options.port_sh= are_port,
+ = c->c2.frame.buf.payload_size, c->options.port_share= _journal_dir);
if (port_share =3D=3D NULL)<= br> {
msg(M_FATAL, "Fatal e= rror: Port sharing failed");
@@ -849,12 +837,12 @@
struct timeval tv;
if (!gettimeofday= (&tv, NULL))
{
- const unsigned int seed =3D (unsigned int) tv.tv_= sec ^ tv.tv_usec;
+ = const unsigned int seed =3D (unsigned int)tv.tv_sec ^ tv.tv_usec;
srandom(seed);
}

- error_reset(); = /* initialize error.c */
- reset_check_status(); /* initialize status check = code in socket.c */
+= error_reset(); /* initialize error.c */
+ reset_check_status(); /* initialize stat= us check code in socket.c */

#ifdef _WIN= 32
init_win32();
@@ -892,9 +880,7 @@
#ifdef GEN_PATH_TEST
{
struct gc_arena gc =3D gc_new();

- const char *fn =3D gen_path("foo",
- = "bar",
- &gc);
+ const char *fn =3D gen_path("foo= ", "bar", &gc);
printf("%s= \n", fn);
gc_free(&gc);
= }
@@ -1011,8 +997,7 @@
}
if (options->show_tls_ciphers)
= {
- show= _available_tls_ciphers(options->cipher_list,
- options-&g= t;cipher_list_tls13,
= + show_available_tls_ciphers(options->cipher_list, options-&g= t;cipher_list_tls13,
= options->tls_cert_profile);
}
if (options->show_curves)

@@ -1040,11 +1025,10= @@
* We do not want user to use --genkey with --secr= et. In the transistion
* phase we for secret.<= br> */
- = if (options->genkey && options->genkey_type !=3D GENKEY_SECRE= T
- && o= ptions->shared_secret_file)
+ if (options->genkey && options->genkey_type != =3D GENKEY_SECRET && options->shared_secret_file)
{

msg(M_USAGE, "Using --genkey type wi= th --secret filename is "
- "not supported. Use --genkey type filename inste= ad.");
+ = "not supported. Use --genkey type filename instead."= ;);
}
if (options->genkey &= ;& options->genkey_type =3D=3D GENKEY_SECRET)
{=
@@ -1053,7 +1037,7 @@
if (options= ->shared_secret_file && options->genkey_filename)
<= span> {

msg(M_USAGE, "You must pr= ovide a filename to either --genkey "
- "or --secret, not both");
+ = "or --secret, not both");
}
/*
@@ -1063,7 +1047,7 @@<= /span>
if (options->shared_secret_file)
{

msg(M_WARN, "WARNING: Using = --genkey --secret filename is "
- "DEPRECATED. Use --genkey secret filen= ame instead.");
= + "DEPRECATED. Use --genkey secret filename in= stead.");
genkey_filename =3D options->= ;shared_secret_file;
}
@@ -1073,8 +1057,7 @@
msg(M_FATAL, &quo= t;Failed to write key file");
}

- msg(D_GEN= KEY | M_NOPREFIX,
- = "Randomly generated %d bit key written to %s", nbits_writ= ten,
+ msg(D_G= ENKEY | M_NOPREFIX, "Randomly generated %d bit key written to %s"= , nbits_written,
options->shared_secret_fil= e);
return true;
}
= @@ -1091,8 +1074,8 @@
"--genkey= tls-crypt-v2-client requires a server key to be set via --tls-crypt-v2 to = create a client key");
}

- tls_crypt_v2_wri= te_client_key_file(options->genkey_filename,
- option= s->genkey_extra_data, options->tls_crypt_v2_file,
+ tls_crypt_v2_write_client_key_f= ile(options->genkey_filename, options->genkey_extra_data,
<= span style=3D"color: hsl(120, 100%, 40%);">+ = options->tls_crypt_v2_file,

= options->tls_crypt_v2_file_inline); return true;
}
@@ -11= 20,13 +1103,10 @@

/* sanity check on= options for --mktun or --rmtun */
notnull(options->= ;dev, "TUN/TAP device (--dev)");
- if (options->ce.remote || options->ifconfig_= local
- || optio= ns->ifconfig_remote_netmask
- || options->shared_secret_file
- || options->tls_server || options-&= gt;tls_client
- = )
+ if (options-&g= t;ce.remote || options->ifconfig_local || options->ifconfig_remote_ne= tmask
+ || opt= ions->shared_secret_file || options->tls_server || options->tls_cl= ient)
{
- msg(M_FATAL|M_OPTERR,
+ msg(M_FATAL | M_OPTERR,
= "options --mktun or --rmtun should only be used together with --dev= ");
}

@@ -1150,= 21 +1130,20 @@
#endif

#= ifdef ENABLE_FEATURE_TUN_PERSIST
- tuncfg(options->dev, options->dev_type, options->de= v_node,
- opt= ions->persist_mode,
= - options->username, options->groupname, &options->t= untap_options,
- = ctx);
+ tuncfg= (options->dev, options->dev_type, options->dev_node, options->p= ersist_mode,
+ = options->username, options->groupname, &options->tuntap_op= tions, ctx);
if (options->persist_mode && o= ptions->lladdr)
{
set_llad= dr(ctx, options->dev, options->lladdr, NULL);
}<= /span>
return true;
-#else /* ifdef ENABLE_FEATURE_TUN_PERSIST */
- msg(M_FATAL|M_OPTERR,
+#else /* ifdef ENABLE_FEATURE_TUN= _PERSIST */

+ msg(= M_FATAL | M_OPTERR,
"options --mktun and --rm= tun are not available on your operating "
&qu= ot;system. Please check 'man tun' (or 'tap'), whether your= system "
"supports using 'ifconfig = %s create' / 'destroy' to create/remove "
- "persistent tunnel interf= aces.", options->dev );
+ "persistent tunnel interfaces.",
+ options->dev);
=
#endif
return false;
}
@@ -1241,9 +1220,7 @@
{
if (no_delay)

{
- platform_user_group_= set(&c0->platform_state_user,

- &c0->platform= _state_group,
- = c);
+ platform_user_group_set(&c0->platfor= m_state_user, &c0->platform_state_group, c);
= }
else if (c->first_time)
<= span> {

@@ -1271,7 +1248,8 @@
= {
if (-1 =3D=3D setcon(c->o= ptions.selinux_context))
{
- msg(M_ERR, "= setcon to '%s' failed; is /proc accessible?", c->options.se= linux_context);

+ = msg(M_ERR, "setcon to '%s' failed; is /proc ac= cessible?",
+ = c->options.selinux_context);
= }
else
= {
@@ -1316,17 +1294,12 @@
#ifdef = _WIN32
if (options->exit_event_name)
{

- win32= _signal_open(&win32_signal,
- WSO_FORCE_SERVICE,
- options->exit= _event_name,
+ = win32_signal_open(&win32_signal, WSO_FORCE_SERVICE, options->exit_e= vent_name,
options->exit_even= t_initial_state);
}
else {
- = win32_signal_open(&win32_signal,
- WSO_FORCE_CONSOLE,
- NULL,
- = false);
+ win3= 2_signal_open(&win32_signal, WSO_FORCE_CONSOLE, NULL, false);
/* put a title on the top window bar */
if (win32_signal.mode =3D=3D WSO_MODE_CONSOLE)
@@ -1377,8 +1350,7 @@
/* initialize inacti= vity timeout */
if (c->options.session_timeout)
{
- = event_timeout_init(&c->c2.session_interval, c->options.sess= ion_timeout,
- = now);
+ event_timeout_init(&c->c2.session_interval, c->option= s.session_timeout, now);
}
/* initialize pings */
@@ -1409,8 +1381,7 @@
if (c->options.auth_token_generate
= && c->options.auth_token_renewal < c->options.reneg= otiate_seconds)
{
- event_timeout_init(&c->c2.auth_token_renewa= l_interval,
- = c->options.auth_token_renewal, now);
+ event_timeout_init(&c->= c2.auth_token_renewal_interval, c->options.auth_token_renewal, now);
}

if (!deferred)
@@ -1420,16 +1391,16 @@

= /* initialize occ timers */

- if (c->options.occ
- && !TLS_MODE(c)=

- &&= ; c->c2.options_string_local && c->c2.options_string_remote)<= /span>
+ if (c->op= tions.occ && !TLS_MODE(c) && c->c2.options_string_local<= /span>
+ &&am= p; c->c2.options_string_remote)
{
event_timeout_init(&c->c2.occ_interval, OCC_INTERVAL= _SECONDS, now);

}

if (c->options.mtu_test)

{- event_timeout_init(= &c->c2.occ_mtu_load_test_interval, OCC_MTU_LOAD_INTERVAL_SECONDS, no= w);
+ even= t_timeout_init(&c->c2.occ_mtu_load_test_interval, OCC_MTU_LOAD_INTER= VAL_SECONDS,
+ = now);
}
<= /span>
/* initialize packet_id persistence timer */
@@ -1482,10 +1453,8 @@
* options and saving ro= utes in the environment.
*/
static void<= /span>
-do_init_route_list(con= st struct options *options,
- struct route_list *route_list,
- const struct link_sock= et_info *link_socket_info,
- struct env_set *es,
+do_init_route_list(const struct options *options, s= truct route_list *route_list,
+ const struct link_socket_info *link_socket_inf= o, struct env_set *es,
openvpn_net_ctx_= t *ctx)
{
const char *gw =3D NULL;
@@ -1514,13 +1483,8 @@
metric =3D op= tions->route_default_metric;
}

- if (init_route_list(= route_list,
- = options->routes,
- gw,
- metric,
- link_socket_current_rem= ote(link_socket_info),
= - es,
- ctx))
+ if (init_route_list(route_list, options->routes, gw= , metric,
+ = link_socket_current_remote(link_socket_info), es, ctx))
{
/* copy routes to environment */=
setenv_routes(es, route_list);
@@= -1528,14 +1492,12 @@
}

= static void
-do_init_r= oute_ipv6_list(const struct options *options,
- struct route_ipv6_list *rou= te_ipv6_list,
- = const struct link_socket_info *link_socket_info,
= - struct e= nv_set *es,
+do_init_= route_ipv6_list(const struct options *options, struct route_ipv6_list *rout= e_ipv6_list,
+ = const struct link_socket_info *link_socket_info, struct en= v_set *es,
openvpn_net_ctx_t *ctx)=
{
const char *gw =3D NULL;- int metric =3D -1; = /* no metric set */
- gw = =3D options->ifconfig_ipv6_remote; /* default GW =3D remote end = */
+ gw =3D option= s->ifconfig_ipv6_remote; /* default GW =3D remote end */
if (options->route_ipv6_default_gateway)

{
gw =3D options->route_ipv6_default_gateway;
@@ -1563,19 +1525,14 @@

= for (i =3D 0; opt_list[i]; i++)
{
- add_route_ipv6_to_optio= n_list( options->routes_ipv6,

- string_alloc(opt_list= [i], options->routes_ipv6->gc),
- NULL, NULL, opti= ons->route_default_table_id);
+ add_route_ipv6_to_option_list(options->routes_i= pv6,
+ = string_alloc(opt_list[i], options->routes_ipv= 6->gc), NULL,
+ = NULL, options->route_default_tabl= e_id);
}
}
<= /span>
- if (init_route_ipv= 6_list(route_ipv6_list,
- options->routes_ipv6,
- gw,- m= etric,
- = link_socket_current_remote_ipv6(link_socket_info),
= - es,=
- = ctx))
+ if= (init_route_ipv6_list(route_ipv6_list, options->routes_ipv6, gw, metric= ,
+ = link_socket_current_remote_ipv6(link_socket_info), es, ctx))
{
/* copy routes to environment = */
setenv_routes_ipv6(es, route_ipv6_list);=
@@ -1601,8 +1558,8 @@
if (flags & ISC_ER= RORS)
{
#ifdef _WIN32
- show_routes(M_INFO|M_NOPREFIX= );

- show_adapte= rs(M_INFO|M_NOPREFIX);
+ show_adapters(M_INFO | M_NOPREFIX);=
msg(M_INFO, "%s With Errors ( see http://openvpn.ne= t/faq.html#dhcpclientserv )", message);
#else<= br> #ifdef ENABLE_SYSTEMD
@@ -1620,7 +1577,7 @@
}

/* Flag that we in= itialized */
- if ((= flags & (ISC_ERRORS|ISC_SERVER)) =3D=3D 0)
+ if ((flags & (ISC_ERRORS | ISC_SERVER)) = =3D=3D 0)
{
c->options.no_= advance =3D true;
}
@@ -1682,13 +1639,= 8 @@
tun_local =3D &c->c1.tuntap->lo= cal;
tun_local6 =3D &c->c1.tuntap->l= ocal_ipv6;
}
- management_set_state(management,
- OPENVPN_STA= TE_CONNECTED,
- = detail,
- tun_local,
- tun_local6,- &a= mp;local,
- = &remote);
+ management_set_state(management, OPENVPN_STATE_CONNECTED= , detail, tun_local, tun_local6,
+ &local, &remote);<= br> if (tun_local)
{
management_post_tunnel_open(management, *tun_local);
@@ -1704,8 +1656,7 @@
static bool
= route_noexec_enabled(const struct options *o, const struct tuntap *tt)
{
- re= turn o->route_noexec
- || (tt && tt->backend_driver =3D=3D DRIVER_AFUNIX)<= /span>
+ return o->rou= te_noexec || (tt && tt->backend_driver =3D=3D DRIVER_AFUNIX)
|| (tt && tt->backend_driver =3D=3D DRI= VER_NULL);
}

@@ -1714,19= +1665,14 @@
* based on options.
*/
bool
-do_= route(const struct options *options,
- struct route_list *route_list,
- struct route_ipv6_list *route_ipv= 6_list,
- const= struct tuntap *tt,
- = const struct plugin_list *plugins,
- struct env_set *es,
- openvpn_net_ctx_t *ctx)
+do_route(const struct options *opti= ons, struct route_list *route_list,

+ struct route_ipv6_list *route_ipv6_list, const str= uct tuntap *tt,
+ = const struct plugin_list *plugins, struct env_set *es, openvpn_net_ctx= _t *ctx)
{
bool ret =3D true;<= br>- if (!route_noexec_enabled= (options, tt) && ( route_list || route_ipv6_list ) )
+ if (!route_noexec_enabled(opti= ons, tt) && (route_list || route_ipv6_list))

{=
- ret =3D add_r= outes(route_list, route_ipv6_list, tt, ROUTE_OPTION_FLAGS(options),<= br>- es, = ctx);
+ ret = =3D add_routes(route_list, route_ipv6_list, tt, ROUTE_OPTION_FLAGS(options)= , es, ctx);
setenv_int(es, "redirect_gateway&= quot;, route_did_redirect_default_gateway(route_list));
= }
#ifdef ENABLE_MANAGEMENT
@@ -1738,7 +1= 684,8 @@

if (plugin_defined(plugins,= OPENVPN_PLUGIN_ROUTE_UP))
{
- if (plugin_call(plugins, OPENVPN_PLUGIN= _ROUTE_UP, NULL, NULL, es) !=3D OPENVPN_PLUGIN_FUNC_SUCCESS)
+ if (plugin_call(plugins, O= PENVPN_PLUGIN_ROUTE_UP, NULL, NULL, es)

+ !=3D OPENVPN_PLUGIN_FUNC_SUCCESS) {
msg(M_WARN, "WARNING: r= oute-up plugin call failed");
}
@@ -1756,13 +1703,13 @@

#ifdef _WIN32
= if (options->show_net_up)
{
- show_routes(M_INFO|M_NOPREFIX);
- show_adapters(M= _INFO|M_NOPREFIX);
+ = show_routes(M_INFO | M_NOPREFIX);
+ show_adapters(M_INFO | M_NOPREFIX);
= }
else if (check_debug_level(D_SHOW_NET))
{
-= show_routes(D_SHOW_NET|M_NOPREFIX);
- show_adapters(D_SHOW_NET|M_NOPREFIX);<= br>+ show_routes(D_SHOW_= NET | M_NOPREFIX);
+ = show_adapters(D_SHOW_NET | M_NOPREFIX);
}
#endif
return ret;
@@ -177= 4,27 +1721,19 @@
static void
do_init_tun(= struct context *c)
{
- c->c1.tuntap =3D init_tun(c->options.dev,<= br>- c= ->options.dev_type,
= - c->options.topology,
- c->options.i= fconfig_local,
- = c->options.ifconfig_remote_netmask,
- c->opt= ions.ifconfig_ipv6_local,

- c->options.ifconfig_ipv6_netbits,=
- = c->options.ifconfig_ipv6_remote,
- c->c1.link_socket_addrs[0].bin= d_local,
- = c->c1.link_socket_addrs[0].remote_list,
- !c->opti= ons.ifconfig_nowarn,
- = c->c2.es,
- &c->net_ctx,- c-&= gt;c1.tuntap);
+ c= ->c1.tuntap =3D init_tun(c->options.dev, c->options.dev_type, c-&g= t;options.topology,
+= c->options.ifconfig_local, c->options.ifc= onfig_remote_netmask,
+ c->options.ifconfig_ipv6_local, c->opti= ons.ifconfig_ipv6_netbits,
+ c->options.ifconfig_ipv6_remote, c-&g= t;c1.link_socket_addrs[0].bind_local,
+ c->c1.link_socket_addrs[0]= .remote_list, !c->options.ifconfig_nowarn,
+ c->c2.es, &c-&= gt;net_ctx, c->c1.tuntap);

if (is= _tun_afunix(c->options.dev_node))
{
/* Using AF_UNIX trumps using DCO */

c-&= gt;c1.tuntap->backend_driver =3D DRIVER_AFUNIX;
}
- else if (is_dev_typ= e(c->options.dev, c->options.dev_type, "null"))
= + else if (is_dev_type(c->= ;options.dev, c->options.dev_type, "null"))
= {
c->c1.tuntap->backend_driver =3D DRIVER= _NULL;
}
@@ -1814,9 +1753,7 @@<= br> }
#endif

- init_tun_post(c->c1.tuntap,
- &c-&= gt;c2.frame,
- = &c->options.tuntap_options);
+ init_tun_post(c->c1.tuntap, &c->c2.f= rame, &c->options.tuntap_options);

c->c1.tuntap_owned =3D true;

}
@@= -1916,10 +1853,10 @@
}
else
{
- = open_tun(c->options.dev, c->options.dev_type, c->options.dev_= node,
- = tt, &c->net_ctx);
+ open_tun(c->options.dev, c->options.dev_type, c->opt= ions.dev_node, tt, &c->net_ctx);
}
- msg(M_INFO, "%s device [%= s] opened", print_tun_backend_driver(tt->backend_driver), tt->ac= tual_name);

+ msg(= M_INFO, "%s device [%s] opened", print_tun_backend_driver(tt->= backend_driver),
+ = tt->actual_name);
}


@@ -1958,8 +1895,7 @@
#ifdef _WIN32<= /span>
/* store (hide) interactive service handle in tunt= ap_options */
c->c1.tuntap->options.msg_chan= nel =3D c->options.msg_channel;
- msg(D_ROUTE, "interactive service msg_channel=3D%= " PRIuPTR,
- = (intptr_t) c->options.msg_channel);
+ msg(D_ROUTE, "interactive service msg= _channel=3D%" PRIuPTR, (intptr_t)c->options.msg_channel); #endif

/* allocate route= list structure */
@@ -1969,8 +1905,8 @@
= ASSERT(c->c2.link_sockets[0]);
if (c->= ;options.routes && c->c1.route_list)
{<= /span>
- do_init_ro= ute_list(&c->options, c->c1.route_list,
- &c->c2.li= nk_sockets[0]->info, c->c2.es, &c->net_ctx);
+ do_init_route_list(&c= ->options, c->c1.route_list, &c->c2.link_sockets[0]->info,<= /span>
+ = c->c2.es, &c->net_ctx);
}
if (c->options.routes_ipv6 && c->c1.rou= te_ipv6_list)
{
@@ -1979,15 +1915,= 12 @@
}

= /* do ifconfig */
- = if (!ifconfig_noexec_enabled(c)
- && ifconfig_order(c->c1.tuntap) =3D= =3D IFCONFIG_BEFORE_TUN_OPEN)
+ if (!ifconfig_noexec_enabled(c) && ifconfig_order= (c->c1.tuntap) =3D=3D IFCONFIG_BEFORE_TUN_OPEN)
= {
/* guess actual tun/tap unit number that wi= ll be returned
* by open_tun */
- const char *guess =3D g= uess_tuntap_dev(c->options.dev,

- c->options= .dev_type,
- = c->options.dev_node,
- = &gc);

+ const char *guess =3D
+ guess_tuntap_dev(c->options.dev, c->= ;options.dev_type, c->options.dev_node, &gc);
= do_ifconfig(c->c1.tuntap, guess, c->c2.frame.tun_mtu, c->c2= .es, &c->net_ctx);
}

@@ -2019,31 +1952,23 @@
}

/* do ifconfig */
- if (!ifconfig_noexec_enabled(c)- && ifconfi= g_order(c->c1.tuntap) =3D=3D IFCONFIG_AFTER_TUN_OPEN)
+ if (!ifconfig_noexec_enabled(c= ) && ifconfig_order(c->c1.tuntap) =3D=3D IFCONFIG_AFTER_TUN_OPEN= )
{
- do_ifconfig(c->c1.tuntap, c->c1.tuntap->actual_= name,
- = c->c2.frame.tun_mtu, c->c2.es, &c->net_ctx);+ do_ifconfig(c->= ;c1.tuntap, c->c1.tuntap->actual_name, c->c2.frame.tun_mtu, c->= c2.es,
+ = &c->net_ctx);
}
=
run_dns_up_down(true, &c->options, c->= c1.tuntap, &c->persist.duri);

= /* run the up script */
- run_up_down(c->options.up_script,
- c->plugins,- OPENVPN_PL= UGIN_UP,
- = c->c1.tuntap->actual_name,
+ run_up_down(c->options.up_script, c->plug= ins, OPENVPN_PLUGIN_UP, c->c1.tuntap->actual_name,
#= ifdef _WIN32
c->c1.tuntap->adapt= er_index,
#endif
- dev_type_string(c->options.dev, c->op= tions.dev_type),
- = c->c2.frame.tun_mtu,
+ dev_type_string(c->options.dev, c= ->options.dev_type), c->c2.frame.tun_mtu,
= print_in_addr_t(c->c1.tuntap->local, IA_EMPTY_IF_UNDEF, &am= p;gc),
- = print_in_addr_t(c->c1.tuntap->remote_netmask, IA_EMPTY_IF_UNDEF,= &gc),
- = "init",
- NULL,
- "up",
- c->c2.es);
+ print_in_addr_t(c-= >c1.tuntap->remote_netmask, IA_EMPTY_IF_UNDEF, &gc), "init&q= uot;,
+ = NULL, "up", c->c2.es);

add_wfp_block(c);


@@ -2060,8 +1= 985,7 @@
}
else
= {
- msg(M_IN= FO, "Preserving previous TUN/TAP instance: %s",
- c->c1.tuntap->actual_= name);
+ msg(M= _INFO, "Preserving previous TUN/TAP instance: %s", c->c1.tunta= p->actual_name);

/* explicitl= y set the ifconfig_* env vars */
do_ifconfig_seten= v(c->c1.tuntap, c->c2.es);
@@ -2071,21 +1995,15 @@
/* run the up script if user specified --up-restart = */
if (c->options.up_restart)
= {
- = run_up_down(c->options.up_script,
- c->plugins,
- OPENVPN_PLUGIN_UP,<= /span>
+ run_up_d= own(c->options.up_script, c->plugins, OPENVPN_PLUGIN_UP,
c->c1.tuntap->actual_name,

#ifdef _WIN32

c->c1.tuntap-= >adapter_index,
#endif
- dev_type_string(c->options.= dev, c->options.dev_type),
- c->c2.frame.tun_mtu,
+ dev_type_string= (c->options.dev, c->options.dev_type), c->c2.frame.tun_mtu,=
print_in_addr_t(c->c1.tuntap->loca= l, IA_EMPTY_IF_UNDEF, &gc),
pr= int_in_addr_t(c->c1.tuntap->remote_netmask, IA_EMPTY_IF_UNDEF, &g= c),
- = "restart",
- NULL,
- "up",
- c->c2.es);
+ &= quot;restart", NULL, "up", c->c2.es);
= }

add_wfp_block(c);=
@@ -2101,8 +2019,7 @@
static void
do_close_tun_simple(struct context *c)

{
- msg(D_CLOSE, "Closing %s in= terface",

- = print_tun_backend_driver(c->c1.tuntap->backend_driver));
<= span style=3D"color: hsl(120, 100%, 40%);">+ msg(D_CLOSE, "Closing = %s interface", print_tun_backend_driver(c->c1.tuntap->backend_dr= iver));


if (c->c1.tuntap)<= br> {
@@ -2174,26 +2091,18 @@
= /* delete any routes we added */
if (c->c= 1.route_list || c->c1.route_ipv6_list)
{=
- run_up_down(c-&g= t;options.route_predown_script,
- c->plugins,
- OPENVPN_PLUGIN_ROUTE_PRE= DOWN,
+ ru= n_up_down(c->options.route_predown_script, c->plugins, OPENVPN_PLUGIN= _ROUTE_PREDOWN,
tuntap_actual,
#ifdef _WIN32
adapte= r_index,
#endif
- NULL,
- c->c2.frame.tun_mtu,- print_= in_addr_t(local, IA_EMPTY_IF_UNDEF, &gc),
- print_in_addr_t(remote_netm= ask, IA_EMPTY_IF_UNDEF, &gc),
- "init",
- signal_description(= c->sig->signal_received,
- c->sig->signal_te= xt),
- = "route-pre-down",
- c->c2.es);
+ NULL, c->c2.frame= .tun_mtu, print_in_addr_t(local, IA_EMPTY_IF_UNDEF, &gc),
+ print_in_= addr_t(remote_netmask, IA_EMPTY_IF_UNDEF, &gc), "init",
+ s= ignal_description(c->sig->signal_received, c->sig->signal_text)= ,
+ = "route-pre-down", c->c2.es);
- delete_routes(c->= ;c1.route_list, c->c1.route_ipv6_list,
- c->c1.tuntap, ROUTE_OPTION= _FLAGS(&c->options),
- c->c2.es, &c->net_ctx);+ delete_routes(c-&= gt;c1.route_list, c->c1.route_ipv6_list, c->c1.tuntap,
+ ROUTE_OP= TION_FLAGS(&c->options), c->c2.es, &c->net_ctx);
}

/* actually cl= ose tun/tap device based on --down-pre flag */
@@ -2204,21 = +2113,13 @@

/* Run the down scri= pt -- note that it will run at reduced
* privileg= e if, for example, "--user" was used. */
- run_up_down(c->options.down_script,=
- c= ->plugins,
- = OPENVPN_PLUGIN_DOWN,
- tuntap_actual,
+ run_up_down(c->options.down_script, c-= >plugins, OPENVPN_PLUGIN_DOWN, tuntap_actual,
#ifdef _W= IN32
adapter_index,
#= endif
- = NULL,
- = c->c2.frame.tun_mtu,
- print_in_addr_t(local, IA_EMPTY_IF_UNDEF, &am= p;gc),
- = print_in_addr_t(remote_netmask, IA_EMPTY_IF_UNDEF, &gc),- "init&= quot;,
- = signal_description(c->sig->signal_received,
- c-&= gt;sig->signal_text),
+ NULL, c->c2.frame.tun_mtu, prin= t_in_addr_t(local, IA_EMPTY_IF_UNDEF, &gc),
+ print_in_addr_t(remote_netm= ask, IA_EMPTY_IF_UNDEF, &gc), "init",
+ signal_description(c-= >sig->signal_received, c->sig->signal_text), "down",<= /span>
c->c2.es);
=
del_wfp_block(c, adapter_index);
@@ -223= 4,21 +2135,13 @@
/* run the down script on this re= start if --up-restart was specified */
if (c->o= ptions.up_restart)
{
- run_up_down(c->options.down_script,<= /span>
- = c->plugins,
- = OPENVPN_PLUGIN_DOWN,
- tuntap_actual,
+ run_up_down(c->options.= down_script, c->plugins, OPENVPN_PLUGIN_DOWN, tuntap_actual,
<= span> #ifdef _WIN32

adapter_index,=
#endif
- c->c2.frame.tun_mtu,
- print_in_addr_= t(local, IA_EMPTY_IF_UNDEF, &gc),
- print_in_addr_t(remote_netmask, IA_= EMPTY_IF_UNDEF, &gc),
- "restart",
- signal_description(c->= ;sig->signal_received,
- c->sig->signal_text),<= /span>
- = "down",
+= NULL, c->c2.frame.tun_mtu, print_in_addr_t(local= , IA_EMPTY_IF_UNDEF, &gc),
+ print_in_addr_t(remote_netmask, IA_EMPTY= _IF_UNDEF, &gc), "restart",
+ signal_description(c->sig-= >signal_received, c->sig->signal_text), "down", c->c2.es);
}

@@ -2277,10 +2170,9 @@
*= equal, or either one is all-zeroes.
*/
= static bool
-options_ha= sh_changed_or_zero(const struct sha256_digest *a,
- const struct sha25= 6_digest *b)
+options= _hash_changed_or_zero(const struct sha256_digest *a, const struct sha256_di= gest *b)
{
- const struct sha256_digest zero =3D {{0}};
+ const struct sha256_digest zero =3D {= { 0 } };
return memcmp(a, b, sizeof(struct sha256_dig= est))
|| !memcmp(a, &zero, sizeof(struct sh= a256_digest));
}
@@ -2316,13 +2208,12 @@

if (cipher_kt_mode_aead(o->ciphern= ame))
{
- buf_printf(&out, "Data Channel: cipher '%s'= ",
- = cipher_kt_name(o->ciphername));
+ buf_printf(&out, "Data Channel: cipher= '%s'", cipher_kt_name(o->ciphername));
= }
else
{
- buf_printf(&out, "Data Cha= nnel: cipher '%s', auth '%s'",
- cipher_kt_name(o->cip= hername), md_kt_name(o->authname));
+ buf_printf(&out, "Data Channel: cipher = '%s', auth '%s'", cipher_kt_name(o->ciphername),
+ md_= kt_name(o->authname));
}
if (o->use_peer_id)
@@ -2393,8 +2284,7 @@

if (c->options.ce.explicit_exit_no= tification)
{
- buf_printf(&out, "explicit-exit-notify %d&quo= t;,
- = c->options.ce.explicit_exit_notification);
+ buf_printf(&out, "explicit-exit= -notify %d", c->options.ce.explicit_exit_notification);
<= span> }

if (c->options.imported_protocol_flags)=
{
@@ -2446,10 +2336,8 @@
#endif


struct tls_session *sess= ion =3D &c->c2.tls_multi->session[TM_ACTIVE];
- if (!tls_session_update_crypto_params= (c->c2.tls_multi, session,
- &c->options, &= c->c2.frame,
- = frame_fragment,
- g= et_link_socket_info(c),
+ if (!tls_session_update_crypto_params(c->c2.tls_multi, session, = &c->options, &c->c2.frame,
+ frame_fragme= nt, get_link_socket_info(c),
= &c->c1.tuntap->dco))
{ msg(D_TLS_ERRORS, "OPTIONS ERROR: failed to import cr= ypto options");
@@ -2486,14 +2374,13 @@
* Was tun interface object persisted from previous restart = iteration,

* and if so did pulled options str= ing change from previous iteration?
*/=
- if (!c->c2.di= d_open_tun
- = && PULL_DEFINED(&c->options)
- && c->c1.tuntap
+ if (!c->c2= .did_open_tun && PULL_DEFINED(&c->options) && c->= c1.tuntap
&& options_hash_changed_= or_zero(&c->c1.pulled_options_digest_save,
= &c->c2.pulled_options_digest= ))
{
/* if so= , close tun, delete routes, then reinitialize tun and add routes */<= br>- msg(M_INFO, &= quot;NOTE: Pulled options changed on restart, will need to close and reopen= TUN/TAP device.");
+ msg(M_INFO,
+ "NOTE: Pulled options changed on rest= art, will need to close and reopen TUN/TAP device.");
=
bool tt_dco_win =3D tuntap_is_dco_win(c-= >c1.tuntap);
do_close_tun(c, true);
@@ -2519,7 +2406,8 @@
* reconnects to se= tup various things (like DCO and NCP cipher) that
* m= ight have changed from the previous connection.
*/
- if (!c->c2.do_up_= ran || (c->c2.tls_multi && c->c2.tls_multi->multi_state = =3D=3D CAS_RECONNECT_PENDING))
+ if (!c->c2.do_up_ran
+ || (c->c2.tls_multi && c->c2.tls_m= ulti->multi_state =3D=3D CAS_RECONNECT_PENDING))
{<= /span>
if (c->mode =3D=3D MODE_POINT_TO_POINT)<= br> {
@@ -2567,7 +2455,8 @@
= if ((route_order(c->c1.tuntap) =3D=3D ROUTE_AFTER_TUN) &= & c->options.route_delay_defined)
{
event_timeout_init(&c->c2.route_wakeup= , c->options.route_delay, now);
- event_timeout_init(&c->c2.route_wakeup_= expire, c->options.route_delay + c->options.route_delay_window, now);=
+ eve= nt_timeout_init(&c->c2.route_wakeup_expire,
+ c->opt= ions.route_delay + c->options.route_delay_window, now);
= tun_standby_init(c->c1.tuntap);
= }
else
@@ -2630,7 +2519,= 8 @@
if ((route_order(c->c1.tuntap) =3D=3D ROUT= E_AFTER_TUN) && c->options.route_delay_defined)
= {
event_timeout_init(&c->c2.ro= ute_wakeup, c->options.route_delay, now);
- event_timeout_init(&c->c2.route_w= akeup_expire, c->options.route_delay + c->options.route_delay_window,= now);
+ e= vent_timeout_init(&c->c2.route_wakeup_expire,
+ c->opti= ons.route_delay + c->options.route_delay_window, now);
= tun_standby_init(c->c1.tuntap);
}

@@ -2648,23 +2538,10 @@
u= nsigned int
pull_permission_mask(const struct context *c)<= /span>
{
- = unsigned int flags =3D
- OPT_P_UP
- = | OPT_P_ROUTE_EXTRAS
- | OPT_P_SOCKBUF
- | OPT_P_SOCKFLAGS
- | OPT_P_SETENV
- | OPT_P_SHAPER
- | OPT_P_TIMER
- | OPT_P_COMP
- | OPT_P_PERSIST
- | OPT_P_MESSAGES
- | OPT_P_EXPLICIT_NOTIFY
- | OPT_P_ECHO
- | OPT_P_PULL_MODE
- | OPT_P_PEER_ID
- | OPT_P_NCP
- | OPT_P_PUSH_MTU;
+ unsigned int flags =3D OPT_P_UP |= OPT_P_ROUTE_EXTRAS | OPT_P_SOCKBUF | OPT_P_SOCKFLAGS
+ | OPT_P_SETENV |= OPT_P_SHAPER | OPT_P_TIMER | OPT_P_COMP | OPT_P_PERSIST
+ | OPT_P_MESSA= GES | OPT_P_EXPLICIT_NOTIFY | OPT_P_ECHO | OPT_P_PULL_MODE
+ | OPT_P_PEE= R_ID | OPT_P_NCP | OPT_P_PUSH_MTU;

i= f (!c->options.route_nopull)
{
@@ -= 2686,8 +2563,8 @@

struct tls_session= *session =3D &c->c2.tls_multi->session[TM_ACTIVE];

- const char *n= cp_cipher =3D get_p2p_ncp_cipher(session, c->c2.tls_multi->peer_info,=
- = &c->options.gc);
+ const char *ncp_cipher =3D
+ get_p2p_ncp_cipher(sessio= n, c->c2.tls_multi->peer_info, &c->options.gc);


if (ncp_cipher)
{
<= span>@@ -2696,8 +2573,8 @@

else if (!c->options.ena= ble_ncp_fallback)
{
msg(D_TLS= _ERRORS, "ERROR: failed to negotiate cipher with peer and "
- "--data-ci= phers-fallback not enabled. No usable "
- "data channel cipher");=
+ = "--data-ciphers-fallback not enabled. No usable "
+ "dat= a channel cipher");

return false;
<= span> }


@@ -2709,9 +2586,8 @@<= br> }
#endif

- if (!tls_session_update_crypto_para= ms(c->c2.tls_multi, session, &c->options,
- &= amp;c->c2.frame, frame_fragment,
- get_link_socket_inf= o(c),
+ if (!tls_s= ession_update_crypto_params(c->c2.tls_multi, session, &c->options= , &c->c2.frame,
- init_verb_mute(c, IVM_LEVEL_1|IVM_LEVEL_= 2);
+ init_ver= b_mute(c, IVM_LEVEL_1 | IVM_LEVEL_2);
msg(D_PUSH, = "OPTIONS IMPORT: --verb and/or --mute level changed");
= }
if (found & OPT_P_TIMER)
@@ -2754,9 +2630,9 @@

if (!check_compression_s= ettings_valid(&c->options.comp, D_PUSH_ERRORS))
= {
msg(D_PUSH_ERRORS, "OPTIONS ERROR:= server pushed compression "
- "settings that are not allowed and will re= sult "
- = "in a non-working connection. "
- "See also allow-compression = in the manual.");
+ = "in a non-working connection. "
+ = "See also allow-compression in the manual.");
return false;

}
= #ifdef USE_COMP
@@ -2778,8 +2654,7 @@

for (int i =3D 0; i < c->c1.link_sockets_num; i= ++)
{
- link_socket_update_buffer_sizes(c->c2.link_sockets[= i],
- = c->options.rcvbuf,
+ link_socket_update_buffer_sizes(c-&= gt;c2.link_sockets[i], c->options.rcvbuf,
= c->options.sndbuf);
= }
}
@@ -2789,8 +2664,7 @@ msg(D_PUSH, "OPTIONS IMPORT: --socket-flags option mo= dified");
for (int i =3D 0; i < c->c1.l= ink_sockets_num; i++)
{
- link_socket_update_flags(c->c2.li= nk_sockets[i],
- = c->options.sockflags);
+ link_socket_update_flags(c-= >c2.link_sockets[i], c->options.sockflags);
= }
}

@@ -2838,12 +271= 2,11 @@
}

= /* Check if pushed options are compatible with DCO, if enabled */=
- if (dco_enabled(&= ;c->options)
- = && !dco_check_pull_options(D_PUSH_ERRORS, &c->options)= )
+ if (dco_en= abled(&c->options) && !dco_check_pull_options(D_PUSH_ERRORS,= &c->options))
{
= msg(D_PUSH_ERRORS, "OPTIONS ERROR: pushed options are incompatible = "
- = "with data channel offload. Use --disable-dco to connect to "
- "th= is server");
+ = "with data channel offload. Use --disable= -dco to connect to "
+ "this server");
return false;

}
= }
@@ -2856,7 +2729,7 @@
if (epoch_= data && !datav2_enabled)
{
= msg(D_PUSH_ERRORS, "OPTIONS ERROR: Epoch key data format tag req= uires "
- = "data v2 (peer-id) to be enabled.");
+ "data v2 (pee= r-id) to be enabled.");
return false;<= br> }

@@ -2871,7 +2744,8 @@

if (c->options.ce.tun_mtu > f= rame->tun_max_mtu)
{
- msg(D_PUSH_ERRORS, "Server-push= ed tun-mtu is too large, please add "
+ msg(D_PUSH_ERRORS,
+ "Server-pushed tun-m= tu is too large, please add "
"t= un-mtu-max %d in the client configuration",
= c->options.ce.tun_mtu);
}
@@ -2935,8 +2809,7 @@

}

= /* Slow down reconnection after 5 retries per remote -- for TCP = client or UDP tls-client only */
- if (c->mode =3D=3D CM_CHILD_TCP
- || (c->options.ce.proto =3D=3D PROTO= _UDP && c->options.tls_client))
+ if (c->mode =3D=3D CM_CHILD_TCP || (c->opt= ions.ce.proto =3D=3D PROTO_UDP && c->options.tls_client))=
{
backoff =3D (c->options.unsucc= essful_attempts / c->options.connection_list->len) - 4;
if (backoff > 0)

@@ -3005,10 +2878,8 @@
ASSERT(o->ce.link_mtu_defined);
= /* if we have a link mtu defined we calculate what the old code
* would have come up with as tun-mtu */
- size_t overhead =3D frame_ca= lculate_protocol_header_size(&c->c1.ks.key_type,

- = o, true);
+ size_t overhead =3D frame_calculate_protocol_header_siz= e(&c->c1.ks.key_type, o, true);
mtu =3D o-&= gt;ce.link_mtu - overhead;
-
}
else
= {
@@ -3093,7 +2964,8 @@
size_t tailro= om =3D headroom;

#ifdef USE_COMP<= br>- msg(D_MTU_DEBUG, "MT= U: adding %zu buffer tailroom for compression for %zu "
+ msg(D_MTU_DEBUG,

+ "MTU: adding %zu buf= fer tailroom for compression for %zu "

"= bytes of payload",
COMP_EXTRA_BUFFER(payload_= size), payload_size);
tailroom +=3D COMP_EXTRA_BUFFER(= payload_size);
@@ -3162,14 +3034,11 @@
= }

/* Initialize packet ID tracking = */
- packet_id_init(= &c->c2.crypto_options.packet_id,
- options->replay_window,
<= span style=3D"color: hsl(0, 100%, 40%);">- options->re= play_time,

+ packe= t_id_init(&c->c2.crypto_options.packet_id, options->replay_window= , options->replay_time,
"STATIC= ", 0);
c->c2.crypto_options.pid_persist =3D &a= mp;c->c1.pid_persist;
c->c2.crypto_options.flags= |=3D CO_PACKET_ID_LONG_FORM;
- packet_id_persist_load_obj(&c->c1.pid_persist,- = &c->c2.crypto_options.packet_id);
+ packet_id_persist_load_obj(&c->c1.pid_persi= st, &c->c2.crypto_options.packet_id);

if (!key_ctx_bi_defined(&c->c1.ks.static_key))

{

@@ -3179,10 +3048,8 @@
<= br> /* Read cipher and hmac keys from shared secret file */
crypto_read_openvpn_key(&c->c1.ks.key_type, = &c->c1.ks.static_key,
- options->shared_secret_file,
- = options->shared_secret_file_inline,
- options->key_dire= ction, "Static Key Encryption",
- "secret", NUL= L);
+ = options->shared_secret_file, options->shared_secret_f= ile_inline,
+ = options->key_direction, "Static Key Encrypt= ion", "secret", NULL);
}
else

{
@@ -3210,26 +3077,23 @@<= /span>
c->c1.ks.tls_auth_key_type.digest =3D options-&= gt;authname;
if (!md_valid(options->authname))<= /span>
{
- msg(M_FATAL, "ERROR: tls-auth enabled, but no valid -= -auth "
- = "algorithm specified ('%s')", options->authname= );
+ msg(M= _FATAL,
+ = "ERROR: tls-auth enabled, but no valid --auth "
+ "algorithm s= pecified ('%s')",

+ options->authname);
= }

- = crypto_read_openvpn_key(&c->c1.ks.tls_auth_key_type,- = &c->c1.ks.tls_wrap_key,
- options->ce.tls_auth_file,
- = options->ce.tls_auth_file_inline,
- options->ce.key_di= rection,
- = "Control Channel Authentication", "tls-au= th",
- = &c->c1.ks.original_wrap_keydata);
+ crypto_read_openvpn_key(&a= mp;c->c1.ks.tls_auth_key_type, &c->c1.ks.tls_wrap_key,

= + = options->ce.tls_auth_file, options->ce.tls_auth_file_inline,=
+ = options->ce.key_direction, "Control Channel Authentication&qu= ot;,
+ = "tls-auth", &c->c1.ks.original_wrap_keyda= ta);
}

/* TLS h= andshake encryption+authentication (--tls-crypt) */
if= (options->ce.tls_crypt_file)
{
- tls_crypt_init_key(&c->c1.= ks.tls_wrap_key,
- = &c->c1.ks.original_wrap_keydata,
- options-= >ce.tls_crypt_file,

= - options->ce.tls_crypt_file_inline,+ tls_crypt_init_key(&a= mp;c->c1.ks.tls_wrap_key, &c->c1.ks.original_wrap_keydata,=
+ = options->ce.tls_crypt_file, options->ce.tls_crypt_file_inline,
options->tls_server);
<= span> }


@@ -3238,16 +3102,14 @@
{
if (options->tls_server)
{
= - tls_crypt_v2_init_server_key(&c->c1.ks.tls_crypt_v2_ser= ver_key,
- = true, options->ce.tls_crypt_v2_file,<= br>+ tls_crypt_v2_in= it_server_key(&c->c1.ks.tls_crypt_v2_server_key, true,
+ = options->ce.tls_crypt_v2_file,

= options->ce.tls_crypt_v2_file_inline); }
else
{=
- tls_crypt= _v2_init_client_key(&c->c1.ks.tls_wrap_key,
- &= c->c1.ks.original_wrap_keydata,
- &c->c1.ks.tls_= crypt_v2_wkc,
- = options->ce.tls_crypt_v2_file,+ tls_crypt_v2_ini= t_client_key(&c->c1.ks.tls_wrap_key, &c->c1.ks.original_wrap_= keydata,
+ = &c->c1.ks.tls_crypt_v2_wkc, options-&g= t;ce.tls_crypt_v2_file,
= options->ce.tls_crypt_v2_file_inline);
}=
/* We have to ensure that the loaded tls-crypt ke= y is small enough
@@ -3259,15 +3121,14 @@
=
if (required_size > c->options.ce.tls_mtu)<= /span>
{
- msg(M_WARN, "ERROR: tls-crypt-v2 client key too large= to work with "
= + msg(M_WARN,
+ "ERROR: tls-crypt-v2 client key too large to work= with "
"requested --max-packet-= size %d, requires at least "
"--= max-packet-size %d. Packets will ignore requested "
- "maximum packet siz= e", c->options.ce.tls_mtu,
- required_size);
+ "maximum packet size",
+ c->= ;options.ce.tls_mtu, required_size);
}
<= span> }

--
}
<= span>

/*
@@ -3296,7 +3157,7 @@
=
case AR_INTERACT:
= ssl_purge_auth(false);
- /* Intentional [[fallthrough]]; */
+ /*= Intentional [[fallthrough]]; */

= case AR_NOINTERACT:
/* SOFT-S= IGUSR1 -- Password failure error */
@@ -3337,8 +3198,7 @@

/* Do not warn if the cipher is u= sed only in OCC */
bool warn =3D options->enabl= e_ncp_fallback;
- = init_key_type(&c->c1.ks.key_type, ciphername, options->authname= ,
- = true, warn);
+ = init_key_type(&c->c1.ks.key_type, ciphername, options->authnam= e, true, warn);

/* initialize tl= s-auth/crypt/crypt-v2 key */
do_init_tls_wrap_key(= c);
@@ -3346,8 +3206,7 @@
/* initi= alise auth-token crypto support */
if (c->optio= ns.auth_token_generate)
{
- auth_token_init_secret(&c->= c1.ks.auth_token_key,
-= c->options.auth_token_secret_file,
+ auth_token= _init_secret(&c->c1.ks.auth_token_key, c->options.auth_token_secr= et_file,
c->options.= auth_token_secret_file_inline);
}
=
@@ -3425,25 +3284,27 @@
if (options-= >renegotiate_seconds_min < 0)
{
= /* Add 10% jitter to reneg-sec by default (server side only) */
- int auto_jitter = =3D options->mode !=3D MODE_SERVER ? 0 :
- get_random() % max_int(opti= ons->renegotiate_seconds / 10, 1);
+ int auto_jitter =3D options->mode !=3D MODE_SE= RVER
+ = ? 0
+ = : get_random() % max_int(options->renegotia= te_seconds / 10, 1);
to.renegotiate_seconds =3D op= tions->renegotiate_seconds - auto_jitter;
}<= br> else
{
/* Add u= ser-specified jitter to reneg-sec */
- to.renegotiate_seconds =3D options->renegotiate_s= econds
- = -(get_random() % max_int(options->renegotiate_seconds<= /span>
- = - options->renegotiate_seconds_min, = 1));
+ to.rene= gotiate_seconds =3D
+= options->renegotiate_seconds
+ - (get_random()
+ % max_int(options->rene= gotiate_seconds - options->renegotiate_seconds_min, 1));
}

to.single_session =3D options->single_sessi= on;
to.mode =3D options->mode;
= to.pull =3D options->pull;
- if (options->push_peer_info) /* all there is */
+ if (options->push= _peer_info) /* all there is */
{
= to.push_peer_info_detail =3D 3;
}
- else if (options->pull) = /* pull clients send some details */
+ else if (options->pull) /* pull clients send s= ome details */
{
to.push_peer= _info_detail =3D 2;
}
@@ -3451,7 +3312= ,7 @@
{
to.push_peer_info_det= ail =3D 0;
}
- else /* default: minimal info to allow NCP= in P2P mode */
+ = else /* default: minimal info to allow NCP in P2P mode */
= {
to.push_peer_info_detail =3D 1;
}

@@ -3554,8 +3415,7 @@
}

/* TLS handshake encryption (--tls-cryp= t) */
- if (options-= >ce.tls_crypt_file
-= || (options->ce.tls_crypt_v2_file && options->tls_cli= ent))
+ if (option= s->ce.tls_crypt_file || (options->ce.tls_crypt_v2_file && opt= ions->tls_client))
{
to.tl= s_wrap.mode =3D TLS_WRAP_CRYPT;
}
@@ -= 3613,10 +3473,8 @@
if (c->c2.tls_multi)
<= span> {

tls_multi_init_finalize(c->c2.tls_m= ulti, c->options.ce.tls_mtu);
- ASSERT(c->c2.tls_multi->opt.frame.buf.payload_size= <=3D
- = c->c2.frame.buf.payload_size);
- frame_print(&c->c2.tls_multi->opt.frame, D_= MTU_INFO,
- = "Control Channel MTU parms");
+ ASSERT(c->c2.tls_multi->opt.frame= .buf.payload_size <=3D c->c2.frame.buf.payload_size);
+ frame_print(&c->c2.t= ls_multi->opt.frame, D_MTU_INFO, "Control Channel MTU parms");=


/* Keep the max mtu also in the= frame of tls multi so it can access
* it in push= _peer_info */
@@ -3624,9 +3482,9 @@
}<= /span>
if (c->c2.tls_auth_standalone)
= {
- tls_init_co= ntrol_channel_frame_parameters(&c->c2.tls_auth_standalone->frame,= c->options.ce.tls_mtu);
- frame_print(&c->c2.tls_auth_standalone->frame, D_MT= U_INFO,
- = "TLS-Auth MTU parms");
+ tls_init_control_channel_frame_parameters(&c= ->c2.tls_auth_standalone->frame,
+ c->= options.ce.tls_mtu);
= + frame_print(&c->c2.tls_auth_standalone->frame, D_MTU_INF= O, "TLS-Auth MTU parms");
c->c2.tls_a= uth_standalone->tls_wrap.work =3D alloc_buf_gc(BUF_SIZE(&c->c2.fr= ame), &c->c2.gc);
c->c2.tls_auth_standal= one->workbuf =3D alloc_buf_gc(BUF_SIZE(&c->c2.frame), &c->= c2.gc);
}
@@ -3642,14 +3500,12 @@

/* Initialise key_type with auth/cipher = "none", so the key_type struct is
* valid *= /
- init_key_type(&a= mp;c->c1.ks.key_type, "none", "none",
- c->options.test= _crypto, true);

+ = init_key_type(&c->c1.ks.key_type, "none", "none"= , c->options.test_crypto, true);

- msg(M_WARN,
- "******* WARNING *******: All encryp= tion and authentication features "
- "disabled -- All data will be tunnelled as c= lear text and will not be "
- "protected against man-in-the-middle changes. "= ;
- "PLEASE= DO RECONSIDER THIS CONFIGURATION!");
+ msg(M_WARN, "******* WARNING *******: All e= ncryption and authentication features "
+ "disabled -- All data will be= tunnelled as clear text and will not be "
+ "protected against man-in-= the-middle changes. "
+ "PLEASE DO RECONSIDER THIS CONFIGURATION!"= );
}

static void=
@@ -3663,7 +3519,7 @@
{
= do_init_crypto_tls(c, flags);
}
- else /* no e= ncryption or authentication. */
+ else /* no encryption or authentication. */
{

do_init_crypto_none(c);
= }
@@ -3701,7 +3557,8 @@
#ifdef ENABLE_F= RAGMENT
if (c->options.ce.fragment > 0 &&= ; c->options.ce.mssfix > c->options.ce.fragment)
= {
- msg(M_WA= RN, "WARNING: if you use --mssfix and --fragment, you should "
+ msg(M_WARN,
+ "WARN= ING: if you use --mssfix and --fragment, you should "
= "set --fragment (%d) larger or equal than --mssfix (%d)&q= uot;,
c->options.ce.fragment, c->options= .ce.mssfix);
}
@@ -3709,7 +3566,7 @@
&& c->options.ce.fragment_encap !=3D c-&= gt;options.ce.mssfix_encap)
{
= msg(M_WARN, "WARNING: if you use --mssfix and --fragment, you should = "
- &qu= ot;use the \"mtu\" flag for both or none of of them.");
+ &quo= t;use the \"mtu\" flag for both or none of of them.");
}
#endif
}
@@ -3728,34 +3585,39 @@

#ifdef ENABLE_SELINUX
= || o->selinux_context
#endif
<= span style=3D"color: hsl(0, 100%, 40%);">- )

+ )
{
if (!o->persist_tun)

{
<= span style=3D"color: hsl(0, 100%, 40%);">- msg(M_WARN, "WAR= NING: you are using user/group/chroot/setcon without persist-tun -- this ma= y cause restarts to fail");

+ msg(M_WARN,
+ "WARNING: you are using user/group/ch= root/setcon without persist-tun -- this may cause restarts to fail");<= /span>
}
}
<= br> if (o->chroot_dir && !(o->username && o= ->groupname))
{
- msg(M_WARN, "WARNING: you are using chroot w= ithout specifying user and group -- this may cause the chroot jail to be in= secure");
+ = msg(M_WARN,
+ = "WARNING: you are using chroot without specifying user and grou= p -- this may cause the chroot jail to be insecure");
= }

if (o->pull && o-&= gt;ifconfig_local && c->first_time)
{
- msg(M_WARN, "W= ARNING: using --pull/--client and --ifconfig together is probably not what = you want");
+ = msg(M_WARN,
+ = "WARNING: using --pull/--client and --ifconfig together is pr= obably not what you want");
}

if (o->server_bridge_defined || o->server_bridge_= proxy_dhcp)
{
- msg(M_WARN, "NOTE: when bridging your LAN adapter= with the TAP adapter, note that the new bridge adapter will often take on = its own IP address that is different from what the LAN adapter was previous= ly set to");
+ = msg(M_WARN,
+ = "NOTE: when bridging your LAN adapter with the TAP adapter, = note that the new bridge adapter will often take on its own IP address that= is different from what the LAN adapter was previously set to");
}

if (o->mode =3D= =3D MODE_SERVER)
{
if (o->= duplicate_cn && o->client_config_dir)
{=
- msg(M_WAR= N, "WARNING: using --duplicate-cn and --client-config-dir together is = probably not what you want");
+ msg(M_WARN,
+ "WARNING: using --duplicate-cn and = --client-config-dir together is probably not what you want"); }
if (o->duplicate_cn &&am= p; o->ifconfig_pool_persist_filename)
{<= br>@@ -3771,14 +3633,12 @@
{
= warn_on_use_of_common_subnets(&c->net_ctx);
= }
- if (o->tls= _client
- &&= amp; !o->tls_verify
= - && o->verify_x509_type =3D=3D VERIFY_X509_NONE- && !(o->ns_= cert_type & NS_CERT_CHECK_SERVER)
- && !o->remote_cert_eku
+ if (o->tls_client && != o->tls_verify && o->verify_x509_type =3D=3D VERIFY_X509_NONE<= /span>
+ && != (o->ns_cert_type & NS_CERT_CHECK_SERVER) && !o->remote_ce= rt_eku
&& !(o->verify_hash_depth =3D=3D= 0 && o->verify_hash))
{
- msg(M_WARN, "WARNING: No se= rver certificate verification method has been enabled. See http://openvpn.= net/howto.html#mitm for more info.");
+ msg(M_WARN,
+ "WARNING: No server certificate ver= ification method has been enabled. See http://openvpn.net/howto.html#mitm = for more info.");
}
if (o-&g= t;ns_cert_type)
{
@@ -3790,15 +3650,19= @@
{
if (script_security() &= gt;=3D SSEC_SCRIPTS)
{
- msg(M_WARN, "NOTE: the current -= -script-security setting may allow this configuration to call user-defined = scripts");
+ = msg(M_WARN,
+= "NOTE: the current --script-security setting may allow= this configuration to call user-defined scripts");
= }
else if (script_security() >=3D SSEC_P= W_ENV)
{
- msg(M_WARN, "WARNING: the current --script-sec= urity setting may allow passwords to be passed to scripts via environmental= variables");
+ = msg(M_WARN,
- = msg(M_WARN, "NOTE: starting with " PACKAGE_NAME " 2.1, '= ;--script-security 2' or higher is required to call user-defined script= s or executables");
+ msg(M_WARN,
+ "NOTE: starting with " PACKAGE_NAME
+ " 2= .1, '--script-security 2' or higher is required to call user-define= d scripts or executables");
}
}

}
@@ -3877,8 +3741,8 @@
= */
c->c2.frame_fragment =3D c->c2.fr= ame;

= - frame_calculate_dynamic(&c->c2.frame_fragment, &c->c1.ks= .key_type,
- = &c->options, get_link_socket_info(c));
+ frame_calculate_dynamic(&= ;c->c2.frame_fragment, &c->c1.ks.key_type, &c->options,
+ = get_link_socket_info(c));
fragment_frame_init(c-= >c2.fragment, &c->c2.frame_fragment);
} #endif
@@ -3891,8 +3755,7 @@
{
ASSERT(!c->c2.link_sockets);
=
- ALLOC_ARRAY_GC(c->c2.= link_sockets, struct link_socket *,
- c->c1.link_sockets_num, &c->c2.g= c);
+ ALLOC_ARRAY_= GC(c->c2.link_sockets, struct link_socket *, c->c1.link_sockets_num, = &c->c2.gc);

for (int i =3D 0;= i < c->c1.link_sockets_num; i++)
{
@@ -3955,8 +3818,7 @@

#ifdef ENABLE_FRAGMENT if (c->c2.fragment)
{
- frame_print(&c->c2.frame= _fragment, D_MTU_INFO,
= - "Fragmentation MTU parms");
+ frame_print(&c->c2.fr= ame_fragment, D_MTU_INFO, "Fragmentation MTU parms");
<= span> }

#endif
}
@@ -= 3970,23 +3832,18 @@
struct gc_arena gc =3D gc_new();

c->c2.options_string_local =3D
- options_string(&a= mp;c->options, &c->c2.frame, c->c1.tuntap, &c->net_ctx,=
- = false, &gc);
+ = options_string(&c->options, &c->c2.frame, c->c1.tun= tap, &c->net_ctx, false, &gc);
c->c2.opt= ions_string_remote =3D
= - options_string(&c->options, &c->c2.frame, c->c1.t= untap, &c->net_ctx,
- true, &gc);
+ options_string(&c->options, &c-&= gt;c2.frame, c->c1.tuntap, &c->net_ctx, true, &gc);
msg(D_SHOW_OCC, "Local Options String (V= ER=3D%s): '%s'",
- options_string_version(c->c2.options_string_local, &= gc),
- c->c2.= options_string_local);
- options_string_version(c-&= gt;c2.options_string_remote, &gc),
- c->c2.options_string_remote);
+ options_string_version(c->= c2.options_string_remote, &gc), c->c2.options_string_remote);=

if (c->c2.tls_multi)
= {
- tls_multi= _init_set_options(c->c2.tls_multi,
- c->c2.options_string_= local,
+ tls_m= ulti_init_set_options(c->c2.tls_multi, c->c2.options_string_local,
c->c2.options_string_r= emote);
}

@@ -4010,1= 0 +3867,8 @@

/* get user and/or = group that we want to setuid/setgid to,
* sets al= so platform_x_state */
= - bool group_defined =3D platform_group_get(c->options.groupname= ,
- = &c0->platform_state_group);
<= span style=3D"color: hsl(0, 100%, 40%);">- bool user_defined =3D pla= tform_user_get(c->options.username,

- &c0->= platform_state_user);
+ bool group_defined =3D platform_group_get(c->options.groupname= , &c0->platform_state_group);
+ bool user_defined =3D platform_user_get(c->opti= ons.username, &c0->platform_state_user);
c0->uid_gid_specified =3D user_defined || group_defined;=

@@ -4122,16 +3977,13 @@
= * reconnect to the same host again or there are still addresses that = need
* to be tried */
if (!(c-&g= t;sig->signal_received =3D=3D SIGUSR1
- && ( (c->options.persist_remote_ip)=
- ||
- ( c->si= g->source !=3D SIG_SOURCE_HARD
- && ((c->c1.link_socket_addrs[0].cur= rent_remote
- = && c->c1.link_socket_addrs[0].current_remote->ai_= next)
- = || c->options.no_advance))
- )))
+ && ((c->options.persist_remote_ip)<= br>+ || (c->sig= ->source !=3D SIG_SOURCE_HARD
+ && ((c->c1.link_socket_addrs[0].c= urrent_remote
+ = && c->c1.link_socket_addrs[0].current_remote-&g= t;ai_next)
+ = || c->options.no_advance)))))
{=
- clear_remote_addrlis= t(&c->c1.link_socket_addrs[0],
- !c->options.resolve_in_adv= ance);
+ clear= _remote_addrlist(&c->c1.link_socket_addrs[0], !c->options.resolve= _in_advance);
}

= /* Clear the remote actual address when persist_remote_ip is not in use */=
@@ -4147,8 +3999,7 @@
{
for (int i =3D 0; i < c->c1.link_sockets_num; i++)
=
{
- = if (c->c1.link_socket_addrs[i].bind_local
- && !c->options= .resolve_in_advance)
= + if (c->c1.link_socket_addrs[i].bind_local && !c->= ;options.resolve_in_advance)
{
freeaddrinfo(c->c1.link_socket_addrs[i].bind_local);
}
@@ -4192,8 +4043,7 @@<= br> */

static void
-do_event_set_init(struct context *c,=

- boo= l need_us_timeout)
+d= o_event_set_init(struct context *c, bool need_us_timeout)
= {
unsigned int flags =3D 0;
@@ -4230,11 +4080,9 @@
{
if (= !c->c1.status_output)
{
- c->c1.status_output =3D status_open(c-= >options.status_file,
- = -1,
- NULL,
- = STATUS_OUTPUT_WRITE);
+ c->c1.status_output =3D
+ status_open(c->options.status_file, c-&= gt;options.status_file_update_freq, -1, NULL,
+ STATUS_OUTPUT_WRITE);
c->c1.status_output_owned =3D true;
}

}
@@ -4261,8 +4109,9 @@ {
if (!c->c1.ifconfig_pool_persist &&am= p; c->options.ifconfig_pool_persist_filename)
{
- c->c1.ifconfig= _pool_persist =3D ifconfig_pool_persist_init(c->options.ifconfig_pool_pe= rsist_filename,
- = c->options.if= config_pool_persist_refresh_freq);
+ c->c1.ifconfig_pool_persist =3D
+ ifconfig_pool_persist_ini= t(c->options.ifconfig_pool_persist_filename,
+ c->op= tions.ifconfig_pool_persist_refresh_freq);
c->c= 1.ifconfig_pool_persist_owned =3D true;
}
}

@@ -4376,12 +4225,9 @@
= unsigned int option_types_found =3D 0;
= if (config.list[i] && config.list[i]->value)
= {
- options_string_import(&c->options,
- = config.list[i]->value,
- D_I= MPORT_ERRORS|M_OPTERR,
= - OPT_P_DEFAULT & ~OPT_P_P= LUGIN,
- = &option_types_found,
- = c->es);
+ = options_string_import(
+ &c->options, conf= ig.list[i]->value, D_IMPORT_ERRORS | M_OPTERR,
+ OPT_P_DEFAULT &am= p; ~OPT_P_PLUGIN, &option_types_found, c->es);
= }
}
= }
@@ -4422,7 +4268,7 @@
static void=
management_callback_status_p2p(void *arg, const int versi= on, struct status_output *so)
{
- struct context *c =3D (struct context *) arg= ;
+ struct context= *c =3D (struct context *)arg;
print_status(c, so);
}

@@ -4455,7 +4301,7 @@
*/

int socketfd = =3D -1;
- struct con= text *c =3D (struct context *) arg;
+ struct context *c =3D (struct context *)arg;
= if (!c->c2.link_sockets || !c->c2.link_sockets[0])<= br> {
return -1;
@@ -453= 6,24 +4382,14 @@
{
= flags |=3D MF_SERVER;
}
- if (management_open(manage= ment,
- = c->options.management_addr,
- c->options.mana= gement_port,
- = c->options.management_user_pass,
- c->= options.management_client_user,
- c->options.management_client_g= roup,
- = c->options.management_log_history_cache,
- c->= ;options.management_echo_buffer_size,

- c->options.management_st= ate_buffer_size,
- = c->options.remap_sigusr1,
- flags))
+ if (manag= ement_open(
+ = management, c->options.management_addr, c->options.manage= ment_port,
+ = c->options.management_user_pass, c->options.management_cli= ent_user,
+ = c->options.management_client_group, c->options.management_l= og_history_cache,
+ = c->options.management_echo_buffer_size, c->options.= management_state_buffer_size,
+ c->options.remap_sigusr1, flags)) {
= - management_set_state(management,
- OPENVPN_ST= ATE_CONNECTING,
- = NULL,
- NULL,
- NU= LL,
- = NULL,
+ management_set_state(management, OPENVPN_STATE_CONNECT= ING, NULL, NULL, NULL, NULL,
= NULL);
}

<= span>@@ -4932,9 +4768,7 @@

/* close event objects */
do_close_event_set(c);

- if (c->mode =3D=3D CM_P2P
- || c->mode =3D= =3D CM_CHILD_TCP
- = || c->mode =3D=3D CM_CHILD_UDP
+ if (c->mode =3D=3D CM_P2P || c->mode =3D=3D CM_C= HILD_TCP || c->mode =3D=3D CM_CHILD_UDP
|| c-&g= t;mode =3D=3D CM_TOP)
{
#ifdef USE_CO= MP
@@ -5002,9 +4836,7 @@
}

void
- const struct context *src,
- s= truct link_socket *sock)
+inherit_context_child(struct context *dest, const struct context *src,= struct link_socket *sock)
{
CLEAR(*d= est);

@@ -5092,8 +4924,7 @@
}


void
-inherit_context_top(struct context *dest,- const struc= t context *src)
+inhe= rit_context_top(struct context *dest, const struct context *src)
= {
/* copy parent */
*dest = =3D *src;
@@ -5221,7 +5052,7 @@
static voi= d *
test_crypto_thread(void *arg)
{
- struct context *c =3D (= struct context *) arg;
- test= _crypto_thread((void *) &c);
+ test_crypto_thread((void *)&c);
= return true;
}
return fals= e;
diff --git a/src/openvpn/init.h b/src/openvpn/init.h
index 081a295..a807874 100644
--- a/src/openvp= n/init.h
+++ b/src/openvpn/init.h
@@ -45,8 = +45,8 @@

void uninit_static(void);

-#define I= VM_LEVEL_1 (1<<0)
-#define IVM_LEVEL_2 (1<<1)
+#define IVM_LEVEL_1 (1 << 0)
+#define IVM_LEVEL_2 (1 << 1)
= void init_verb_mute(struct context *c, unsigned int flags);
void init_options_dev(struct options *options);<= /span>
@@ -61,7 +61,8 @@

void p= re_setup(const struct options *options);

-void init_instance_handle_signals(stru= ct context *c, const struct env_set *env, const unsigned int flags);=
+void init_instance_handle_= signals(struct context *c, const struct env_set *env,
+ const u= nsigned int flags);

void init_instance(s= truct context *c, const struct env_set *env, const unsigned int flags);

@@ -72,8 +73,7 @@
bool do_route(const struct options *options, struct route_list *ro= ute_list,
struct route_ipv6_list *route_ipv6= _list, const struct tuntap *tt,
- const struct plugin_list *plugins, struct env_set *= es,
- open= vpn_net_ctx_t *ctx);
= + const struct plugin_list *plugins, struct env_set *es, openv= pn_net_ctx_t *ctx);

void close_instance(= struct context *c);

@@ -81,9 +81,7 @@

void context_gc_free(struct context *c);

-bool d= o_up(struct context *c,
- bool pulled_options,
- unsigned int option_types_found);
+bool do_up(struct context *c, bool pul= led_options, unsigned int option_types_found);

= /**
* @brief A simplified version of the do_up() f= unction. This function is called
@@ -109,17 +107,15 @@
*/
bool do_deferred_options(struct context *= c, const unsigned int found, const bool is_update);

-void inherit_context_child(= struct context *dest,
-= const struct context *src,
+void inherit_context_child(struct context= *dest, const struct context *src,
= struct link_socket *sock);

-void inherit_context_top(struct context *dest,
- = const struct context *src);
+void inherit_context_top(struct context *dest, const struct conte= xt *src);

-#define CC_GC_FREE (1<<0)
-#define CC_USR1_TO_HUP (1<<1)-#define CC_HARD_USR1_TO_HUP (1&= lt;<2)
-#define CC_N= O_CLOSE (1<<3)
+#define CC_GC_FREE (1 << 0)
+#define CC_USR1_TO_HUP (1 << 1= )
+#define CC_HARD_US= R1_TO_HUP (1 << 2)
+#define CC_NO_CLOSE (1 << 3)
void close_context(struct context *c, int sig, unsigned int flags);=

@@ -127,9 +123,9 @@

void free_context_buffers(struct context_buffers *b);=

-#define IS= C_ERRORS (1<<0)
-= #define ISC_SERVER (1<<1)
-#define ISC_ROUTE_ERRORS (1<<2)
+#define ISC_ERRORS (1 << 0)<= br>+#define ISC_SERVER (1= << 1)
+#define= ISC_ROUTE_ERRORS (1 << 2)
void initialization_seque= nce_completed(struct context *c, const unsigned int flags);

#ifdef ENABLE_MANAGEMENT
diff --git a/s= rc/openvpn/integer.h b/src/openvpn/integer.h
index 4a95f4e.= .b82379e 100644
--- a/src/openvpn/integer.h
+++ b/src/openvpn/integer.h

@@ -26,13 +26,17 @@
= #include "error.h"

#ifn= def htonll
-#define hto= nll(x) ((1=3D=3Dhtonl(1)) ? (x) : \
- ((uint64_t)htonl((uint32_t)((x) & 0xFF= FFFFFF)) << 32) | htonl((uint32_t)((x) >> 32)))
+#define htonll(x) \

+ ((1 =3D=3D htonl(1)) \
+ ? (x) \

+ : ((uint64_t)= htonl((uint32_t)((x) & 0xFFFFFFFF)) << 32) | htonl((uint32_t)((x)= >> 32)))
#endif

= #ifndef ntohll
-#define= ntohll(x) ((1=3D=3Dntohl(1)) ? (x) : \
- ((uint64_t)ntohl((uint32_t)((x) & = 0xFFFFFFFF)) << 32) | ntohl((uint32_t)((x) >> 32)))
<= span style=3D"color: hsl(120, 100%, 40%);">+#define ntohll(x) \
+ ((1 =3D=3D ntohl(1)) \
+ ? (x) = \
+ : ((uint6= 4_t)ntohl((uint32_t)((x) & 0xFFFFFFFF)) << 32) | ntohl((uint32_t)= ((x) >> 32)))
#endif

static inline int

@@ -196,10 +200,7 @@
= if (index < 0 || index >=3D size)
{<= br> msg(M_FATAL, "Assertion Failed: Array index=3D%d out= of bounds for array size=3D%d in %s:%d",
- index,
- size,
- file,
- line);
+ index, size, file, line);
}
return index;
}
diff -= -git a/src/openvpn/interval.c b/src/openvpn/interval.c
inde= x a2ac4f7..2b35314 100644
--- a/src/openvpn/interval.c
+++ b/src/openvpn/interval.c
@@ -39,9 +39,7 @@<= /span>
}

bool
-event_timeout_trigger(struct event_tim= eout *et,
- = struct timeval *tv,
- const int et_const_retry)
+event_timeout_trigger(struct event_time= out *et, struct timeval *tv, const int et_const_retry)
{
if (!et->defined)
{
<= span>@@ -54,8 +52,7 @@

if (wakeup <=3D 0) {
#if INTERVAL_DEBUG
- dmsg(D_INTERVAL, "EVENT event_time= out_trigger (%d) etcr=3D%d", et->n,
- et_const_retry);
+ dmsg(D_INTERVAL, "EVENT even= t_timeout_trigger (%d) etcr=3D%d", et->n, et_const_retry); #endif
if (et_const_retry < 0)<= br> {
@@ -72,8 +69,8 @@
= if (tv && wakeup < tv->tv_sec)
{<= br> #if INTERVAL_DEBUG
- dmsg(D_INTERVAL, "EVENT event_timeout_wakeup (%d/%d) et= cr=3D%d",
- = (int) wakeup, et->n, et_const_retry);
+ dmsg(D_INTERVAL, "EVENT event_timeo= ut_wakeup (%d/%d) etcr=3D%d", (int)wakeup, et->n,
+ et_const_retry);<= br> #endif
tv->tv_sec =3D wakeup;<= br> tv->tv_usec =3D 0;
diff --git a/src/op= envpn/interval.h b/src/openvpn/interval.h
index 420a1be..b1= 33c44 100644
--- a/src/openvpn/interval.h
+= ++ b/src/openvpn/interval.h
@@ -74,8 +74,7 @@
}


if (top->last_action + = top->horizon > local_now
- || top->last_test_true + top->refresh <=3D local_= now
- || trigger= )
+ || top->= ;last_test_true + top->refresh <=3D local_now || trigger)
<= span> {

top->last_test_true =3D local_now;<= /span>
#if INTERVAL_DEBUG
@@ -134,9 +133,9 @@

struct event_timeout
{
- bool defined; /= **< This timeout is active */
- interval_t n; /**< periodic interval for periodic t= imeouts */
- time_t = last; /**< time of last event */
+ bool defined; /**< This timeout is active */<= /span>
+ interval_t n; /*= *< periodic interval for periodic timeouts */
+ time_t last; /**< time of last event *= /
};

static inline bool=
@@ -217,7 +216,7 @@
static inline interva= l_t
event_timeout_remaining(struct event_timeout *et)
{
- ret= urn (interval_t) ((et->last + et->n) - now);
+ return (interval_t)((et->last + et-&g= t;n) - now);
}

#define = ETT_DEFAULT (-1)
@@ -254,19 +253,18 @@
* = @param et_const_retry see above
* @return = if the timeout has triggered and event has been reset
= */
-bool event_timeou= t_trigger(struct event_timeout *et,
- struct timeval *tv,
- int et_co= nst_retry);

+bool eve= nt_timeout_trigger(struct event_timeout *et, struct timeval *tv, int et_con= st_retry);

/*
* Measur= e time intervals in microseconds
*/

-#define USEC_TIMER_MAX = 60 /* maximum interval size in seconds */
+#define USEC_TIMER_MAX 60 /* maximum interval size= in seconds */

#define USEC_TIMER_MAX_US= EC (USEC_TIMER_MAX * 1000000)

-struct usec_timer {
+struct usec_timer
+{
struct timeval start;=
struct timeval end;
};
diff= --git a/src/openvpn/list.c b/src/openvpn/list.c
index 48e5= 49f..f30d540 100644
--- a/src/openvpn/list.c
+++ b/src/openvpn/list.c

@@ -34,8 +34,7 @@
#include "memdbg.h"


struct = hash *
-hash_init(const= int n_buckets,
- = const uint32_t iv,
= - h->n_buckets =3D (int) adjust_power_of_2(n_buckets);
+ h->n_buckets =3D (int)adjus= t_power_of_2(n_buckets);

h->mask =3D h->n_bucket= s - 1;
h->hash_function =3D hash_function; h->compare_function =3D compare_function;
@= @ -79,10 +78,7 @@
}

str= uct hash_element *
-has= h_lookup_fast(struct hash *hash,
- struct hash_bucket *bucket,
- const void *key,<= br>- uint32_t hv)=
+hash_lookup_fast(st= ruct hash *hash, struct hash_bucket *bucket, const void *key, uint32_t hv)<= /span>
{
struct hash_element *he;
= struct hash_element *prev =3D NULL;
@@ -110,10 += 106,7 @@
}

bool<= br>-hash_remove_fast(struct hash = *hash,
- = struct hash_bucket *bucket,
- const void *key,
- uint32_t hv)
+hash_remove_fast(struct hash *hash, struct ha= sh_bucket *bucket, const void *key, uint32_t hv)
{<= br> struct hash_element *he;
struct hash_ele= ment *prev =3D NULL;
@@ -219,9 +212,7 @@
}=

void
-hash_iterator_init_range(struct hash *hash,
- struct ha= sh_iterator *hi,

- = int start_bucket,
+hash_iterator_init_range(struct hash *hash, struct hash_i= terator *hi, int start_bucket,
in= t end_bucket)
{
if (end_bucket > h= ash->n_buckets)
@@ -242,8 +233,7 @@
}

void
-hash_iterator_init(struct hash *hash,
- struct hash_iterator *h= i)
+hash_iterator_ini= t(struct hash *hash, struct hash_iterator *hi)
{ hash_iterator_init_range(hash, hi, 0, hash->n_buckets);
}
@@ -390,17 +380,35 @@
* --= ------------------------------------------------------------------ */

-#define mix(a, b, c) \
- { \
- a -=3D b; a -=3D c; a ^=3D= (c>>13); \

- = b -=3D c; b -=3D a; b ^=3D (a<<8); \
- c -=3D a; c -=3D b; c ^=3D (b>>13= ); \
- a -=3D b= ; a -=3D c; a ^=3D (c>>12); \
- b -=3D c; b -=3D a; b ^=3D (a<<16); \<= br>- c -=3D a; c -=3D b; c= ^=3D (b>>5); \
- a -=3D b; a -=3D c; a ^=3D (c>>3); \
- b -=3D c; b -=3D a; b ^=3D (a<&= lt;10); \
- c -= =3D a; c -=3D b; c ^=3D (b>>15); \
+#define mix(a, b, c) \
+ { \
+ a -=3D b; \
+ a -=3D c; \
+ a ^=3D (c >>= ; 13); \
+ b -= =3D c; \
+ = b -=3D a; \
+ b ^=3D (a << 8); \
+ c -=3D a; \
+ c -=3D b; \
+ c ^=3D (b >> 13); \=
+ a -=3D b; = \
+ a -=3D c; = \
+ a = ^=3D (c >> 12); \
+ b -=3D c; \
+ b -=3D a; \
+ b ^=3D (a << 16); \
+ c -=3D a; \
+ c -=3D b; \
+ c ^=3D (b >>= ; 5); \
+ a -= =3D b; \
+ = a -=3D c; \
+ a ^=3D (c >> 3); \
+ b -=3D c; \
+ b -=3D a; \
+ b ^=3D (a << 10); \=
+ c -=3D a; = \
+ c -=3D b; = \
+ c = ^=3D (b >> 15); \
}

= uint32_t
@@ -410,21 +418,15 @@

/* Set up the internal state */
len = =3D length;
- a =3D = b =3D 0x9e3779b9; /* the golden ratio; an arbitrary value */- c =3D initval; = /* the previous hash value */
+ a =3D b =3D 0x9e3779b9; /* the golden ratio; an arbitrary val= ue */
+ c =3D init= val; /* the previous hash value */

/*---------------------------------------- handle most of the key */<= /span>
while (len >=3D 12)
{- a +=3D (k[0] + ((uint3= 2_t) k[1] << 8)
-= + ((uint32_t) k[2] << 16)
- + ((uint32_t) k[3] << 24));

- b +=3D (k[4] + ((= uint32_t) k[5] << 8)
- + ((uint32_t) k[6] << 16)
- + ((uint32_t) k[7] << 24))= ;
- c +=3D (k[8]= + ((uint32_t) k[9] << 8)
- + ((uint32_t) k[10] << 16)
- + ((uint32_t) k[11] <&l= t; 24));
+ a += =3D (k[0] + ((uint32_t)k[1] << 8) + ((uint32_t)k[2] << 16) + ((= uint32_t)k[3] << 24));
+ b +=3D (k[4] + ((uint32_t)k[5] << 8) + ((uint32_t)k[= 6] << 16) + ((uint32_t)k[7] << 24));
+ c +=3D (k[8] + ((uint32_t)k[9] <<= ; 8) + ((uint32_t)k[10] << 16) + ((uint32_t)k[11] << 24));
mix(a, b, c);
k +=3D 12;
len -=3D 12;
@@ -432,48 +434,48 @@

/*-------------------------------------= handle the last 11 bytes */
c +=3D length;
= - switch (len) /* a= ll the case statements fall through */
+ switch (len) /* all the case statements fall through= */
{
case 11:
- c +=3D ((uint32_t) k[10]= << 24);

- = /* Intentional [[fallthrough]]; */
+ c +=3D ((uint32_t)k[10] << 24);+ /* Intentional [[= fallthrough]]; */

case 10:
- c +=3D ((uint32= _t) k[9] << 16);
= - /* Intentional [[fallthrough]]; */
+ c +=3D ((uint32_t)k[9] << 16);
+ /* Intenti= onal [[fallthrough]]; */

case 9:=
- c +=3D ((= uint32_t) k[8] << 8);
+ c +=3D ((uint32_t)k[8] << 8);
= /* Intentional [[fallthrough]]; */

= /* the first byte of c is reserved for the length */
case 8:

- = b +=3D ((uint32_t) k[7] << 24);
- /* Intentional [[fallthrough]]; */=
+ b +=3D ((uint3= 2_t)k[7] << 24);
- b +=3D ((uint32_t) k[6] << 16);
- /* Intentional [[fallthrough]]; */<= /span>
+ b +=3D (= (uint32_t)k[6] << 16);
+ /* Intentional [[fallthrough]]; */

case 6:
- b +=3D ((uint32_t) k[5] << 8);
- /* Intentional [[fallthrough]]= ; */
+ b += =3D ((uint32_t)k[5] << 8);
+ /* Intentional [[fallthrough]]; */

case 5:
b +=3D k[4= ];
- /* Intentio= nal [[fallthrough]]; */
+ /* Intentional [[fallthrough]]; */
=
case 4:
- a +=3D ((uint32_t) k[3] << 24);
- /* Intentional [[fallthrough]]; */=
+ a +=3D = ((uint32_t)k[3] << 24);
+ /* Intentional [[fallthrough]]; */
<= /span>
case 3:
- a +=3D ((uint32_t) k[2] << 16);
- /* Intentional [[fallthrough= ]]; */

+ a= +=3D ((uint32_t)k[2] << 16);
+ /* Intentional [[fallthrough]]; */

case 2:
- a +=3D ((uint32_t) k[1] << 8);- /* Intentional [[fallth= rough]]; */
+ = a +=3D ((uint32_t)k[1] << 8);
+ /* Intentional [[fallthrough]]; */
case 1:
a += =3D k[0];
diff --git a/src/openvpn/list.h b/src/openvpn/lis= t.h
index 77807c7..fb3302d 100644
--- a/src= /openvpn/list.h
+++ b/src/openvpn/list.h
@@= -36,8 +36,8 @@
#include "basic.h"
#include "buffer.h"


-#define hashsize(n) ((uint32_t)1<<(n)= )
-#define hashmask(n) = (hashsize(n)-1)
+#def= ine hashsize(n) ((uint32_t)1 << (n))
+#define hashmask(n) (hashsize(n) - 1)

struct hash_element
{
@@ -63,8 +63,7 @@

struct hash_bucket *buckets;=
};

-struct hash *hash_init(const int n_buckets,
- const uint32_t iv,
+struct hash *hash_ini= t(const int n_buckets, const uint32_t iv,
= uint32_t (*hash_function)(const void *key, uint32_t iv),
<= span> bool (*compare_function)(const void *key1, con= st void *key2));


@@ -72,15 +71,10 @@

bool hash_add(struct hash *hash, const void = *key, void *value, bool replace);

-struct hash_element *hash_lookup_fast(struc= t hash *hash,
- = struct hash_bucket *bucket,
- c= onst void *key,
- = uint32_t hv);
+struct hash_element *hash_lookup_fast(struct hash= *hash, struct hash_bucket *bucket,
+ const void *key, uint= 32_t hv);

-bool hash_remove_fast(struct hash *hash,
- struct hash_bucket *bucket,<= /span>
- = const void *key,
- = uint32_t hv);
+bool hash_remove_fast(struct hash *hash, struct hash_bucket *buc= ket, const void *key, uint32_t hv);

void= hash_remove_by_value(struct hash *hash, void *value);

@@ -96,9 +90,7 @@
int bucket_index_end;<= /span>
};

-void hash_iterator_init_range(struct hash *hash,
= - st= ruct hash_iterator *hi,
- int start_bucket,
+void hash_iterator_init_range(struct hash *ha= sh, struct hash_iterator *hi, int start_bucket,
= int end_bucket);

voi= d hash_iterator_init(struct hash *hash, struct hash_iterator *iter);=
@@ -154,10 +146,7 @@

/* NOTE: = assumes that key is not a duplicate */
static inline void<= /span>
-hash_add_fast(struct h= ash *hash,
- = struct hash_bucket *bucket,
- const void *key,
- uint32_t hv,
+hash_add_fast(struct hash *hash, struct hash_bucke= t *bucket, const void *key, uint32_t hv,
voi= d *value)
{
struct hash_element *he;<= /span>
diff --git a/src/openvpn/lladdr.c b/src/openvpn/lladdr.c
index cc677b4..d8bcad9 100644
--- a/src/openv= pn/lladdr.c
+++ b/src/openvpn/lladdr.c
@@ -= 14,8 +14,7 @@
#include "proto.h"

int
-set_lladdr(openvpn_net_ctx_t *ctx, const char *ifname, const char *lladdr= ,
- const str= uct env_set *es)
+set= _lladdr(openvpn_net_ctx_t *ctx, const char *ifname, const char *lladdr, con= st struct env_set *es)
{
int r;

@@ -32,27 +31,16 @@
#else /* = if defined(TARGET_LINUX) */
struct argv argv =3D argv_= new();
#if defined(TARGET_SOLARIS)
- argv_printf(&argv,
- "%s %s ether %s&q= uot;,
- = IFCONFIG_PATH,
- = ifname, lladdr);
+ argv_printf(&argv, "%s %s ether %s", IFCONFIG_PATH,= ifname, lladdr);
#elif defined(TARGET_OPENBSD)
= - argv_printf(&argv,
- "%s %s= lladdr %s",
- = IFCONFIG_PATH,
- ifname, lladdr);
+ argv_printf(&argv, "%s %s lladdr %s", I= FCONFIG_PATH, ifname, lladdr);
#elif defined(TARGET_DARWIN= )
- argv_printf(&= ;argv,
- = "%s %s lladdr %s",
- IFCONFIG_PATH,
- ifname, lladdr);
+ argv_printf(&argv, "%s %s lladdr= %s", IFCONFIG_PATH, ifname, lladdr);
#elif defined(T= ARGET_FREEBSD)
- arg= v_printf(&argv,
- = "%s %s ether %s",
- IFCONFIG_PATH,
- ifname, lladdr);
+ argv_printf(&argv, "= %s %s ether %s", IFCONFIG_PATH, ifname, lladdr);

#els= e /* if defined(TARGET_SOLARIS) */
- msg(M_WARN, "Sorry, but I don't know how to conf= igure link layer addresses on this operating system.");
+ msg(M_WARN,

+ "Sorry, but I don't k= now how to configure link layer addresses on this operating system.");=
return -1;
#endif /* if defined(TARG= ET_SOLARIS) */
argv_msg(M_INFO, &argv);
= diff --git a/src/openvpn/lzo.c b/src/openvpn/lzo.c
in= dex d5f60ca..3a73d5f 100644
--- a/src/openvpn/lzo.c<= br>+++ b/src/openvpn/lzo.c
@@ -50,9 +50,10 @@<= br> int lzo_status =3D lzo_init();
if (lzo_s= tatus !=3D LZO_E_OK)
{
- msg(M_FATAL, "Cannot initialize LZO comp= ression library (lzo_init() returns %d)", lzo_status);
+ msg(M_FATAL, "Cannot i= nitialize LZO compression library (lzo_init() returns %d)",

= + lzo_status);
}
- = compctx->wu.lzo.wmem =3D (lzo_voidp) malloc(compctx->wu.lzo.wmem_size= );
+ compctx->w= u.lzo.wmem =3D (lzo_voidp)malloc(compctx->wu.lzo.wmem_size);
<= span> check_malloc_return(compctx->wu.lzo.wmem);

}<= /span>

@@ -64,8 +65,7 @@
}

static void
-lzo_compress(struct buffer *buf, struct buffer work,
- struct com= press_context *compctx,
+lzo_compress(struct buffer *buf, struct buffer work, struct compress_co= ntext *compctx,
const struct frame *frame)
{
uint8_t *header =3D buf_prepend(buf, = 1);
@@ -73,13 +73,12 @@
}
=
static void
-lzo_decompress(struct buffer *buf, struct buffer work,
<= span style=3D"color: hsl(0, 100%, 40%);">- struct compress_co= ntext *compctx,

+lzo_= decompress(struct buffer *buf, struct buffer work, struct compress_context = *compctx,
const struct frame *frame)=
{
lzo_uint zlen =3D frame->buf.payload_s= ize;
int err;
- uint8_t c; /* flag indicating whether or not our = peer compressed */
+ = uint8_t c; /* flag indicating whether or not our peer compressed */

if (buf->len <=3D 0)
{

@@ -94,8 +93,7 @@
if (c =3D= =3D LZO_COMPRESS_BYTE) /* packet was compressed */
{
ASSERT(buf_safe(&work, zlen));
- err =3D LZO_DECOMPRESS(BPTR(bu= f), BLEN(buf), BPTR(&work), &zlen,
- compctx->wu.lzo.wmem);=
+ err =3D LZO= _DECOMPRESS(BPTR(buf), BLEN(buf), BPTR(&work), &zlen, compctx->w= u.lzo.wmem);
if (err !=3D LZO_E_OK)
{

dmsg(D_COMP_ERRORS, "LZO dec= ompression error: %d", err);
@@ -112,7 +110,7 @@

*buf =3D work;
}=
- else if (c =3D=3D= NO_COMPRESS_BYTE) /* packet was not compressed */
+ else if (c =3D=3D NO_COMPRESS_BYTE) = /* packet was not compressed */
{
= /* nothing to do */
}
@@ -123,11 = +121,6 @@
}
}

-const struct compress_alg l= zo_alg =3D {
- "= ;lzo",
- lzo_co= mpress_init,
- lzo_c= ompress_uninit,
- lz= o_compress,
- lzo_de= compress
-};
= +const struct compress_alg lzo_= alg =3D { "lzo", lzo_compress_init, lzo_compress_uninit, lzo_comp= ress,
+ = lzo_decompress };
#endif /* ENABLE= _LZO */
diff --git a/src/openvpn/lzo.h b/src/openvpn/lzo.h<= /span>
index c47db83..9d4fa30 100644
--- a/src/ope= nvpn/lzo.h
+++ b/src/openvpn/lzo.h
@@ -56,1= 9 +56,19 @@
extern const struct compress_alg lzo_alg;

/*******************************************= *******************************/
-/** @name LZO library interface defines *//** @{ *//************= ***********/
-#define L= ZO_COMPRESS lzo1x_1_15_compress
+/** @name LZO library interface defines */ /** @{ */ /******= *****************/
+#= define LZO_COMPRESS lzo1x_1_15_compress
/**< LZO libr= ary compression function.
*
* Use \c = lzo1x_1_15_compress because it
* is described as faster= than the
* standard routine, although it does * need a bit more memory. */
-#define LZO_WORKSPACE LZO1X_1_15_MEM_COMPRESS+#define LZO_WORKSPACE LZO1X= _1_15_MEM_COMPRESS
/**< The size in bytes of the memory=
* %buffer required by the LZO library
= * compression algorithm. */
-#define LZO_DECOMPRESS lzo1x_decompress_safe
+#define LZO_DECOMPRESS lzo1x_decompress= _safe
/**< LZO library decompression function. *
* Use safe decompress because it
= @@ -78,26 +78,30 @@
* verify the integrity of inc= oming
* packets, you might want to consider
<= span> * using the non-safe version. */

-/** @} name LZO library interface *//******************= ********************/
+/** @} name LZO library interface */ /***********************************= ***/


/****************= **********************************************************/
-/** @name Adaptive compression define= s *//** @{ *//************************/

-#define AC_SAMP_SEC 2 /**< Number of seconds= in a sample period. */
-#define AC_MIN_BYTES 1000 /**< Minimum number of bytes a sample<= /span>
- = * period must contain for it to be
- * evaluated. *= /
-#define AC_SAVE_PCT = 5 /**< Minimum size reduction percentage
- * below = which compression will be
- * turned off. */
-#define AC_OFF_SEC 60 /**< S= econds to wait after compression has
- * been turned off before = retesting. */
-/** @} n= ame Adaptive compression defines *//*******************************/=
+/** @name Adaptive compres= sion defines */ /** @{ */ /************************/
+#define AC_SAMP_SEC 2 = /**< Number of seconds in a sample period. */
+#define AC_MIN_BYTES = \

+ 1000 = /**< Minimum number of bytes a sample \
+ = * period must contain for it to be \
+ = * evaluated. */
+#define AC_SAVE_PCT = \
+ 5 /**< Minimum= size reduction percentage \
+ * below whi= ch compression will be \
+ * turned off.= */
+#define AC_OFF_S= EC = \
+ 60 = /**< Seconds to wait after compres= sion has \
+ = * been turned off before rete= sting. */
+/** @} nam= e Adaptive compression defines */ /*******************************/=

/**
* Adaptive compre= ssion state.
*/
-struct lzo_adaptive_compress {
+struct lzo_adaptive_compress
+{
bool compress_stat= e;
time_t next;
int n_total;
diff --git a/src/openvpn/manage.c b/src/openvpn/manage.c=
index c7bdd5a..aed04f5 100644
--- a/src/openvpn/m= anage.c
+++ b/src/openvpn/manage.c
@@ -74,7= +74,8 @@
msg(M_CLIENT, "auth-retry t := Auth failure retry mode (none,interact,nointeract).");
msg(M_CLIENT, "bytecount n : Show bytes in/out, upda= te every n secs (0=3Doff).");

msg(M_CLIENT, "= ;echo [on|off] [N|all] : Like log, but only show messages in echo buffer.&= quot;);
- msg(M_CLIE= NT, "cr-response response : Send a challenge response answer via CR_= RESPONSE to server");
+ msg(M_CLIENT,
+ "cr-response response : Send a challenge response answe= r via CR_RESPONSE to server");
msg(M_CLIENT, &quo= t;exit|quit : Close management session.");
msg(M_CLIENT, "forget-passwords : Forget passwords entere= d so far.");

msg(M_CLIENT, "help = : Print this message.");
@@ -85,7 +86,8 @@
msg(M_CLIENT, "load-stats : Show global s= erver load stats.");
msg(M_CLIENT, "log [on|= off] [N|all] : Turn on/off realtime log display");
= msg(M_CLIENT, " + show last N lines or = 9;all' for entire history.");
- msg(M_CLIENT, "mute [n] : Set log m= ute level to n, or show level if n is absent.");
+ msg(M_CLIENT,
+ "mute [n] : Se= t log mute level to n, or show level if n is absent.");
msg(M_CLIENT, "needok type action : Enter confirmation for = NEED-OK request of 'type',");

msg(M_CLIEN= T, " where action =3D 'ok' or 'can= cel'.");
msg(M_CLIENT, "needstr type act= ion : Enter confirmation for NEED-STR request of 'type',");=
@@ -103,18 +105,25 @@
#endif
msg(M_CLIENT, "client-auth CID KID : Authenticate client-i= d/key-id CID/KID (MULTILINE)");

msg(M_CLIENT, &qu= ot;client-auth-nt CID KID : Authenticate client-id/key-id CID/KID");
- msg(M_CLIENT, "= ;client-deny CID KID R [CR] : Deny auth client-id/key-id CID/KID with log r= eason");
+ ms= g(M_CLIENT,
+ = "client-deny CID KID R [CR] : Deny auth client-id/key-id CID/KID with = log reason");
msg(M_CLIENT, " = text R and optional client reason text CR");
<= span style=3D"color: hsl(0, 100%, 40%);">- msg(M_CLIENT, "client-pe= nding-auth CID KID MSG timeout : Instruct OpenVPN to send AUTH_PENDING and = INFO_PRE msg");

- = msg(M_CLIENT, " to the client = and wait for a final client-auth/client-deny");
+ msg(M_CLIENT,
+ "client-pending-auth CID KID= MSG timeout : Instruct OpenVPN to send AUTH_PENDING and INFO_PRE msg"= );
+ msg(M_CLIENT,=
+ " = to the client and wait for a final client-= auth/client-deny");
msg(M_CLIENT, "client-ki= ll CID [M] : Kill client instance CID with message M (def=3DRESTART)&quo= t;);
msg(M_CLIENT, "env-filter [level] : Set = env-var filter level");
msg(M_CLIENT, "rsa-s= ig : Enter a signature in response to >RSA_SIGN challenge= ");
- msg(M_CLI= ENT, " Enter signature base64 on subsequent li= nes followed by END");
+ msg(M_CLIENT,
+ " Enter signature base64 on subs= equent lines followed by END");
msg(M_CLIENT, &qu= ot;pk-sig : Enter a signature in response to >PK_SIGN ch= allenge");
- ms= g(M_CLIENT, " Enter signature base64 on subseq= uent lines followed by END");
- msg(M_CLIENT, "certificate : Enter a clien= t certificate in response to >NEED-CERT challenge");
- msg(M_CLIENT, " = Enter certificate base64 on subsequent lines followed by END&q= uot;);

+ msg(M_CLI= ENT,
+ " = Enter signature base64 on subsequent lines followed= by END");
+ = msg(M_CLIENT,
+ = "certificate : Enter a client certificate in response to = >NEED-CERT challenge");
+ msg(M_CLIENT,
+ " Enter certificate base64 o= n subsequent lines followed by END");
msg(M_CLIEN= T, "signal s : Send signal s to daemon,"); msg(M_CLIENT, " s =3D SIGHUP|SIGT= ERM|SIGUSR1|SIGUSR2.");
msg(M_CLIENT, "state= [on|off] [N|all] : Like log, but show state history.");
@@ -122,7 +131,8 @@

msg(M_CLIENT, "test n = : Produce n lines of output for testing/debugging.");
msg(M_CLIENT, "username type u : Enter usernam= e u for a queried OpenVPN username.");
msg(M_CLIE= NT, "verb [n] : Set log verbosity level to n, or show if= n is absent.");
-= msg(M_CLIENT, "version [n] : Set client's version t= o n or show current version of daemon.");
+ msg(M_CLIENT,
+ "version [n] : Set client&= #39;s version to n or show current version of daemon.");
msg(M_CLIENT, "END");

}
=
@@ -305,7 +315,7 @@
man_delete_unix_sock= et(struct management *man)
{
#if UNIX_SOC= K_SUPPORT
- if ((man= ->settings.flags & (MF_UNIX_SOCK|MF_CONNECT_AS_CLIENT)) =3D=3D MF_UN= IX_SOCK)
+ if ((ma= n->settings.flags & (MF_UNIX_SOCK | MF_CONNECT_AS_CLIENT)) =3D=3D MF= _UNIX_SOCK)
{
socket_delete_u= nix(&man->settings.local_unix);
}
@@ -331,11 +341,11 @@

static void
virt= ual_output_callback_func(void *arg, const unsigned int flags, const char *s= tr)
{
= - struct management *man =3D (struct management *) arg;
+ struct management *man =3D (stru= ct management *)arg;
static int recursive_level =3D 0;= /* GLOBAL */

-#define AF_DID_PUSH (1<<0)
-#define AF_DID_RESET (1<<1)
+#define AF_DID_PUSH (1 << 0)
+#define AF_DID_RESET (1= << 1)
if (recursive_level < 5) /* limit recu= rsion */
{
struct gc_arena gc= =3D gc_new();
@@ -369,10 +379,10 @@
= }
else if (man->connection.log_realt= ime)
{
- out =3D log_entry_print(&e, LOG_PRINT_INT= _DATE
- = | LOG_PRINT_MSG_FLAGS
- | LOG_PRINT= _LOG_PREFIX
- = | LOG_PRINT_CRLF, &gc);
+ out =3D log_entry_pri= nt(&e,
+ = LOG_PRINT_INT_DATE | LOG_PRINT_MSG_FLAGS
+ = | LOG_PRINT_LOG_PREFIX | LOG_PRINT_CRLF,
+ = &gc);
}
if (= out)
{
@@ -381,11 +391,11 @@
}
if (flags & = M_FATAL)
{
- out =3D log_entry_print(&e, LOG_FATAL= _NOTIFY|LOG_PRINT_CRLF, &gc);
+ out =3D log_entry_print(&e, LOG_FATAL_NOT= IFY | LOG_PRINT_CRLF, &gc);
if (out)
{
man_= output_list_push_str(man, out);
- action_flags |=3D (AF_DID_PUSH|AF_DID_RESET);=
+ = action_flags |=3D (AF_DID_PUSH | AF_DID_RESET);
= }
}
}@@ -407,7 +417,8 @@
{
= /* cannot use msg here */
printf("virtual_ou= tput: message to management interface "
- "dropped due to recursion: <%= s>\n", str);
= + "dropped due to recursion: <%s>\n",<= br>+ str);=
}
}

@@ -4= 71,7 +482,8 @@
static void
man_command_un= supported(const char *command_name)
{
- msg(M_CLIENT, "ERROR: The '%s= ' command is not supported by the current daemon mode", command_na= me);
+ msg(M_CLIEN= T, "ERROR: The '%s' command is not supported by the current da= emon mode",
+ = command_name);
}

s= tatic void
@@ -494,8 +506,7 @@
{
man->connection.bytecount_update_seconds =3D update_= seconds;
event_timeout_init(&man->connectio= n.bytecount_update_interval,
- man->connection.bytecount_update_secon= ds,
- = now);
+ = man->connection.bytecount_update_seconds, now);
}
else
{
@@ -506,8 +517,7 @@
}
<= br> static void
-= man_bytecount_output_client(struct management *man,
- counter_type dc= o_read_bytes,
+man_by= tecount_output_client(struct management *man, counter_type dco_read_bytes,<= /span>
counter_type dco_write_bytes)<= /span>
{
char in[32];
@@ -52= 0,8 +530,7 @@
}

void
-man_bytecount_output_ser= ver(const counter_type *bytes_in_total,
- const counter_type *bytes_out= _total,
+man_bytecoun= t_output_server(const counter_type *bytes_in_total, const counter_type *byt= es_out_total,
struct man_def_a= uth_context *mdac)
{
char in[32];
@@ -546,7 +555,7 @@
char p3[128];
int n_killed;

- buf_set_read(&buf, (uint8_t *) = victim, strlen(victim) + 1);
+ buf_set_read(&buf, (uint8_t *)victim, strlen(victim) += 1);
buf_parse(&buf, ':', p1, sizeof(p= 1));
buf_parse(&buf, ':', p2, sizeof(p= 2));
buf_parse(&buf, ':', p3, sizeof(p= 3));
@@ -555,29 +564,29 @@
{
/* IP:port specified */
= bool status;
- = const in_addr_t addr =3D getaddr(GETADDR_HOST_ORDER|GETADDR_MSG_VIRT_O= UT, p2, 0, &status, NULL);
+ const in_addr_t addr =3D
+ getaddr(GETADDR_HOST_ORDER | GE= TADDR_MSG_VIRT_OUT, p2, 0, &status, NULL);
= if (status)
{
= const int port =3D atoi(p3);
- const int proto =3D (streq(p1, "tcp")) ?= PROTO_TCP_SERVER :
- = (streq(p1, "udp")) ? PROTO_UDP : = PROTO_NONE;
+ = const int proto =3D (streq(p1, "tcp")) ? PROTO_TCP_SERV= ER
+ = : (streq(p1, "udp")) ? PROTO_UDP
+ = : PROTO_NONE;


= if ((port > 0 && port < 65536) && (proto != =3D PROTO_NONE))
{
- n_killed =3D (*man->= persist.callback.kill_by_addr)(man->persist.callback.arg, addr, port, pr= oto);
+ = n_killed =3D (*man->persist.callback.kill_by_addr)(man->persist= .callback.arg,
+ = addr, port,= proto);
if (n_killed > 0) {
- msg(M_CLIENT, "SUCCESS: %d client(s) = at address %s:%s:%d killed",
- n_killed,
- proto2ascii(proto, = AF_UNSPEC, false),
- = print_in_addr_t(addr, 0, &gc),
+ msg(M_CLIEN= T, "SUCCESS: %d client(s) at address %s:%s:%d killed", n_killed,<= /span>
+ = proto2ascii(proto, AF_UNSPEC, false), print_in_addr_t(addr, 0, &= ;gc),
port);
= }
else
<= span> {

msg(M_= CLIENT, "ERROR: client at address %s:%s:%d not found",
= - prot= o2ascii(proto, AF_UNSPEC, false),
- print_in_addr_t(addr, 0, &gc),<= /span>
+ = proto2ascii(proto, AF_UNSPEC, false), print_in_addr_t(addr, 0, &= ;gc),
port);
= }
}
@@= -622,12 +631,8 @@
* for the log and echo commands.
*/
static void
-man_history(struct management *man,
- const char *parm,- const char *type,<= /span>
- struct log= _history *log,
- = bool *realtime,
- = const unsigned int lep_flags)
+man_history(struct management *man, const char *parm, = const char *type, struct log_history *log,
+ bool *realtime, const unsigned int lep_f= lags)
{
struct gc_arena gc =3D gc_new= ();
int n =3D 0;
@@ -670,35 +675,22 @@=
static void
man_log(struct management *m= an, const char *parm)
{
- man_history(man,
- parm,
- "log",
- man->persist.log,- &man->co= nnection.log_realtime,
= - LOG_PRINT_INT_DATE|LOG_PRINT_MSG_FLAGS);
+ man_history(man, parm, "log&= quot;, man->persist.log, &man->connection.log_realtime,+ LOG_PRINT_INT= _DATE | LOG_PRINT_MSG_FLAGS);
}
static void
man_echo(struct management *man, cons= t char *parm)
{
- man_history(man,
- parm,
- "echo",
- man->persist.echo,
- &man->connecti= on.echo_realtime,

- = LOG_PRINT_INT_DATE|MANAGEMENT_ECHO_FLAGS);
+ man_history(man, parm, "echo&qu= ot;, man->persist.echo, &man->connection.echo_realtime,+ LOG_PRINT_INT= _DATE | MANAGEMENT_ECHO_FLAGS);
}
=
static void
man_state(struct management *man, c= onst char *parm)
{
- man_history(man,
- parm,
- "state",
- man->persist.state,
= - &man->con= nection.state_realtime,
- LOG_PRINT_INT_DATE|LOG_PRINT_STATE
- |LOG_PRINT_LOCAL_IP|LOG_PRI= NT_REMOTE_IP);
+ m= an_history(man, parm, "state", man->persist.state, &man-&g= t;connection.state_realtime,
+ LOG_PRINT_INT_DATE | LOG_PRINT_STATE | LOG_PRINT_L= OCAL_IP | LOG_PRINT_REMOTE_IP);
}
=
static void
@@ -732,13 +724,8 @@
}


static void
-man_query_user_pass(struct management *man,
- cons= t char *type,
- = const char *string,
- const bool needed,
- const char *prompt,- char *dest= ,
- = int len)
+man_query_u= ser_pass(struct management *man, const char *type, const char *string, cons= t bool needed,
+ = const char *prompt, char *dest, int len)
{<= /span>
if (needed)
{
@@ = -747,16 +734,12 @@
{
= strncpynt(dest, string, len);
man_up_finalize(= man);
- msg(= M_CLIENT, "SUCCESS: '%s' %s entered, but not yet verified"= ;,
- typ= e,
- pro= mpt);
+ ms= g(M_CLIENT, "SUCCESS: '%s' %s entered, but not yet verified&qu= ot;, type, prompt);
}
els= e
{
- msg(M_CLIENT, "ERROR: %s of type '%s' enter= ed, but we need one of type '%s'",
- prompt,
- type,
- man->connection.up_query_typ= e);
+ msg(= M_CLIENT, "ERROR: %s of type '%s' entered, but we need one of = type '%s'", prompt,
+ type, man->connection.up_query_type);
}
}
else
@@ -768,36 +751,42 @@
static void
man_query_username(struct management *man, const char *type, const cha= r *string)

{
- const bool needed =3D ((man->connection.up_query_mode =3D=3D= UP_QUERY_USER_PASS
- = ) && man->connection.up_query_type);
- man_query_user_pass(m= an, type, string, needed, "username", man->connection.up_query= .username, USER_PASS_LEN);
+ const bool needed =3D
+ ((man->connection.up_query_mode =3D=3D UP_QUERY_USE= R_PASS) && man->connection.up_query_type);
+ man_query_user_pass(man, type, string= , needed, "username", man->connection.up_query.username,
+ U= SER_PASS_LEN);
}

static= void
man_query_password(struct management *man, const cha= r *type, const char *string)
{
const = bool needed =3D ((man->connection.up_query_mode =3D=3D UP_QUERY_PASS
- = || man->connection.up_query_mode =3D=3D UP_QUERY_USER_PASS
- ) &&= amp; man->connection.up_query_type);

+ || man->connection.up_quer= y_mode =3D=3D UP_QUERY_USER_PASS)
+ && man->connection.up_que= ry_type);
if (!string[0]) /* allow blank passwords to = be passed through using the blank_up tag */
{ string =3D blank_up;
}
- man_query_user_pass(man, type, s= tring, needed, "password", man->connection.up_query.password, = USER_PASS_LEN);

+ = man_query_user_pass(man, type, string, needed, "password", man-&g= t;connection.up_query.password,
+ USER_PASS_LEN);
}

static void
man_query_need_= ok(struct management *man, const char *type, const char *action)
= {
- const boo= l needed =3D ((man->connection.up_query_mode =3D=3D UP_QUERY_NEED_OK) &a= mp;& man->connection.up_query_type);
- man_query_user_pass(man, type, action, needed, &q= uot;needok-confirmation", man->connection.up_query.password, USER_P= ASS_LEN);
+ const = bool needed =3D
+ = ((man->connection.up_query_mode =3D=3D UP_QUERY_NEED_OK) && = man->connection.up_query_type);
+ man_query_user_pass(man, type, action, needed, "nee= dok-confirmation",
+ man->connection.up_query.password, USER_PASS= _LEN);
}

static void
man_query_need_str(struct management *man, const char *type,= const char *action)
{
- const bool needed =3D ((man->connection.up_query_m= ode =3D=3D UP_QUERY_NEED_STR) && man->connection.up_query_type);=
- man_query_user_pa= ss(man, type, action, needed, "needstr-string", man->connectio= n.up_query.password, USER_PASS_LEN);
+ const bool needed =3D
+ ((man->connection.up_query_mode =3D=3D UP= _QUERY_NEED_STR) && man->connection.up_query_type);
+ man_query_user_pass(man, typ= e, action, needed, "needstr-string",

+ man->connection.up_qu= ery.password, USER_PASS_LEN);
}
static void
@@ -826,8 +815,8 @@
{=
if (man->persist.callback.send_cc_message)<= br> {
- = const bool status =3D (*man->persist.callback.send_cc_message)<= br>- = (man->persist.callback.arg, message, parameters);
+ const bool status =3D (*man->= ;persist.callback.send_cc_message)(man->persist.callback.arg,
= + = message, parameters);
if (status)

{
= msg(M_CLIENT, "SUCCESS: command succeeded");
= @@ -892,13 +881,12 @@
{
ASSERT(p1);

- i= f (man->persist.callback.remote_entry_get
- && man->persist.callback.remote_e= ntry_count)
+ if (= man->persist.callback.remote_entry_get && man->persist.callba= ck.remote_entry_count)
{
unsi= gned int count =3D (*man->persist.callback.remote_entry_count)(man->p= ersist.callback.arg);

- unsigned int from =3D (unsigned int) atoi(p1);
- unsigned int to = =3D p2 ? (unsigned int) atoi(p2) : from + 1;
+ unsigned int from =3D (unsigned int)atoi(p= 1);
+ unsigned= int to =3D p2 ? (unsigned int)atoi(p2) : from + 1;

if (!strcmp(p1, "all"))
= {
@@ -909,7 +897,8 @@
for (uns= igned int i =3D from; i < min_uint(to, count); i++)
= {
char *remote =3D NULL;
- bool res =3D (*man->per= sist.callback.remote_entry_get)(man->persist.callback.arg, i, &remot= e);
+ bool= res =3D
+ = (*man->persist.callback.remote_entry_get)(man->persist.callback.= arg, i, &remote);
if (res && remot= e)
{
msg(M_CL= IENT, "%u,%s", i, remote);
@@ -955,8 +944,8 @@
}
}

-#define IER_RESET 0
-#define IER_NEW 1

<= span style=3D"color: hsl(120, 100%, 40%);">+#define IER_RESET 0

<= span style=3D"color: hsl(120, 100%, 40%);">+#define IER_NEW 1

<= span>

static void
in_extra_reset(struct = man_connection *mc, const int mode)
@@ -989,14 +978,9 @@
case IEC_CLIENT_AUTH:
i= f (man->persist.callback.client_auth)
{
- const boo= l status =3D (*man->persist.callback.client_auth)
- (ma= n->persist.callback.arg,
- man->connection.in_extra_c= id,
- = man->connection.in_extra_kid,
- tr= ue,
- = NULL,
- NULL,
- man= ->connection.in_extra);
+ const bool status =3D (*man->persist.callback.cli= ent_auth)(
+ = man->persist.callback.arg, man->connection.in_extra_cid,
+ m= an->connection.in_extra_kid, true, NULL, NULL, man->connection.in_ext= ra);
man->connection.in_extra =3D NULL;=
report_command_status(status, "clien= t-auth");
}
@@ -1063,9 +1= 047,8 @@
* @param timeout_str The timeout value in stri= ng form
*/
static void
-man_client_pending_auth(struct manageme= nt *man, const char *cid_str,
- const char *kid_str, const char *extra,
- c= onst char *timeout_str)
+man_client_pending_auth(struct management *man, const char *cid_str, co= nst char *kid_str,
+ = const char *extra, const char *timeout_str) {
unsigned long cid =3D 0;
= unsigned int kid =3D 0;
@@ -1075,8 +1058,8 @@
= {
if (man->persist.callback.client_p= ending_auth)
{
- bool ret =3D (*man->persist.callback.clien= t_pending_auth)
- = (man->persist.callback.arg, cid, kid, extra, timeou= t);
+ bool= ret =3D (*man->persist.callback.client_pending_auth)(man->persist.ca= llback.arg, cid,
+ = kid, extra= , timeout);

if (ret)<= br> {
@@ -1085,7 +1068,7 @@
else

{
= msg(M_CLIENT, "ERROR: client-pending-auth command failed.&qu= ot;
- = " Extra parameter might be too long");
+ " Extra p= arameter might be too long");
} }
else
@@ -1101,8 = +1084,7 @@
struct man_connection *mc =3D &man->= connection;
mc->in_extra_cid =3D 0;
mc->in_extra_kid =3D 0;

- if (parse_cid(cid_str, &mc->in_extra_cid)
<= span style=3D"color: hsl(0, 100%, 40%);">- && parse_uint(kid= _str, "KID", &mc->in_extra_kid))

+ if (parse_cid(cid_str, &mc->in_ext= ra_cid) && parse_uint(kid_str, "KID", &mc->in_extr= a_kid))
{
mc->in_extra_cmd= =3D IEC_CLIENT_AUTH;
in_extra_reset(mc, IER_NEW);=
@@ -1114,7 +1096,8 @@
}
=
static void
-man_client_deny(struct management *man, const char *cid_str, const = char *kid_str, const char *reason, const char *client_reason)
+man_client_deny(struct management= *man, const char *cid_str, const char *kid_str,

+ const char *reason, const char= *client_reason)
{
unsigned long cid = =3D 0;
unsigned int kid =3D 0;
@@ -112= 2,14 +1105,8 @@
{
if (man->= ;persist.callback.client_auth)
{
- const bool status =3D (*man= ->persist.callback.client_auth)
- (man->persist.callback.= arg,
- = cid,
- kid,
- false,
<= span style=3D"color: hsl(0, 100%, 40%);">- = reason,

- = client_reason,
- NULL);
+ const bool status =3D = (*man->persist.callback.client_auth)(

+ man->persist.callback.arg, cid, kid= , false, reason, client_reason, NULL);
if (sta= tus)
{
msg(M_= CLIENT, "SUCCESS: client-deny command succeeded");
@@ -1154,7 +1131,8 @@

{
if = (man->persist.callback.kill_by_cid)
{- const bool status = =3D (*man->persist.callback.kill_by_cid)(man->persist.callback.arg, c= id, kill_msg);
+ = const bool status =3D
+ (*man->persist.callback.kill_by_cid)(man->pe= rsist.callback.arg, cid, kill_msg);
if (status= )
{
msg(M_CLI= ENT, "SUCCESS: client-kill command succeeded");
@= @ -1237,12 +1215,10 @@
nclients =3D (*man->pers= ist.callback.n_clients)(man->persist.callback.arg);
= }
msg(M_CLIENT, "SUCCESS: nclients=3D%d,bytesin= =3D" counter_format ",bytesout=3D" counter_format,- nclients,
- link_read_bytes_global,
- link_write_bytes_= global);
+ ncl= ients, link_read_bytes_global, link_write_bytes_global);
}=

-#de= fine MN_AT_LEAST (1<<0)
+#define MN_AT_LEAST (1 << 0)
/** * Checks if the correct number of arguments to a management comman= d are present
* and otherwise prints an error and returns= false.
@@ -1262,11 +1238,8 @@
{
if (!p[i])
{
- msg(M_CLIENT, "ERROR: = the '%s' command requires %s%d parameter%s",
- p[0],
- (flags & MN_AT_LEAS= T) ? "at least " : "",
- n,
- n > 1 ? "s" : "");=
+ msg(M_C= LIENT, "ERROR: the '%s' command requires %s%d parameter%s"= ;, p[0],
+ = (flags & MN_AT_LEAST) ? "at least " : "", n, n= > 1 ? "s" : "");
retur= n false;
}
}
= @@ -1312,8 +1285,7 @@
*/
if (man= ->persist.callback.network_change)
{
- int fd =3D (*man->persist= .callback.network_change)

- (man->persist.callback.arg, samenetwork);
+ int fd =3D (*man-= >persist.callback.network_change)(man->persist.callback.arg, samenetw= ork);
man->connection.fdtosend =3D fd; msg(M_CLIENT, "PROTECTFD: fd '%d' sent to be = protected", fd);
if (fd =3D=3D -2)
= @@ -1334,7 +1306,8 @@
}

= static void
-man= _dispatch_command(struct management *man, struct status_output *so, const c= har **p, const int nparms)
+man_dispatch_command(struct management *man, struct status_output *s= o, const char **p,
+ = const int nparms)
{
= struct gc_arena gc =3D gc_new();

@@ -1= 664,7 +1637,8 @@
const int n =3D atoi(p[1]);
for (i =3D 0; i < n; ++i)
= {
- = msg(M_CLIENT, "[%d] The purpose of this command is to generate = large amounts of output.", i);
+ msg(M_CLIENT,
+ "[%d] The purpose of thi= s command is to generate large amounts of output.", i);
}

}
}@@ -1691,7 +1665,8 @@

ca= se MS_CC_WAIT_READ:
case MS_CC_WAIT_WRITE:<= br>- net_event_win32_s= tart(&man->connection.ne32, FD_READ|FD_WRITE|FD_CLOSE, man->conne= ction.sd_cli);
+ = net_event_win32_start(&man->connection.ne32, FD_READ | FD_WRI= TE | FD_CLOSE,
+ = man->connection.sd_cli);
= break;

default:
@@ -1736,27 +1711,24 @@
#if UNIX_SOCK_SUPPORT
if (man->settings.flags & MF_UNIX_SOCK) {
- = msg(D_MANAGEMENT, "MANAGEMENT: %s %s",
- description,
+ msg(D_MANAGEMENT, "MANAGEMEN= T: %s %s", description,
sockaddr_unix_nam= e(&man->settings.local_unix, "NULL"));
= }
else
#endif
- if (man->settings.flags & MF_CON= NECT_AS_CLIENT)
+ = if (man->settings.flags & MF_CONNECT_AS_CLIENT)
= {
- msg(D_M= ANAGEMENT, "MANAGEMENT: %s %s",
- description,
+ msg(D_MANAGEMENT, "MANAGEMENT: %s %s&= quot;, description,
print_sockaddr(man->set= tings.local->ai_addr, &gc));
}
= else
{
struct sockaddr_s= torage addr;
socklen_t addrlen =3D sizeof(addr);
- if (!getpeernam= e(man->connection.sd_cli, (struct sockaddr *) &addr,
- &addrlen= ))

+ if (!getp= eername(man->connection.sd_cli, (struct sockaddr *)&addr, &addrl= en))
{
msg(D_MANAGEME= NT, "MANAGEMENT: %s %s", description,
- print_sockaddr((struct sockaddr *= ) &addr, &gc));
+ print_sockaddr((struct sockaddr *)&addr, &gc));=
}
else
= {
@@ -1782,19 +1754,22 @@
{=
if (socket_defined(sd) && (man->settings.client_u= id !=3D -1 || man->settings.client_gid !=3D -1))
{<= /span>
- static const c= har err_prefix[] =3D "MANAGEMENT: unix domain socket client connection= rejected --";
+= static const char err_prefix[] =3D
+ "MANAGEMENT: unix domain socket cli= ent connection rejected --";
int uid, gid;
if (unix_socket_get_peer_uid_gid(man->connection.= sd_cli, &uid, &gid))
{
= if (man->settings.client_uid !=3D -1 && man->settin= gs.client_uid !=3D uid)
{
- msg(D_MANAGEMENT, "%s= UID of socket peer (%d) doesn't match required value (%d) as given by = --management-client-user",
+ msg(D_MANAGEMENT,
+ "%s UID of socket peer (= %d) doesn't match required value (%d) as given by --management-client-u= ser",
err_prefix, uid, man->se= ttings.client_uid);
return false; }
if (man->settings.cl= ient_gid !=3D -1 && man->settings.client_gid !=3D gid) {
-= msg(D_MANAGEMENT, "%s GID of socket peer (%d) doesn= 9;t match required value (%d) as given by --management-client-group",<= /span>
+ msg(= D_MANAGEMENT,
+ = "%s GID of socket peer (%d) doesn't match required v= alue (%d) as given by --management-client-group",
= err_prefix, gid, man->settings.client_gid);
<= span> return false;

}@@ -1876,8 +1851,8 @@
#endif
= {
man->connection.sd_top =3D create_soc= ket_tcp(man->settings.local);
- socket_bind(man->connection.sd_top, man->setti= ngs.local,
- = man->settings.local->ai_family, "MANAGEMENT", = false);
+ = socket_bind(man->connection.sd_top, man->settings.local, man->sett= ings.local->ai_family,
+ "MANAGEMENT", false);
}


/*
@@ -1905,14 +1880,13 @@

const struct sockaddr= *man_addr =3D man->settings.local->ai_addr;
= struct sockaddr_storage addr;
socklen_t a= ddrlen =3D sizeof(addr);
+ if (!getsockname(man->connection.sd_top, (struct s= ockaddr *)&addr, &addrlen))
{- man_addr =3D (= struct sockaddr *) &addr;
+ man_addr =3D (struct sockaddr *)&addr;=
}
else
= {
- = msg(M_WARN|M_ERRNO,
- "Failed to get the management socket addres= s");
+ = msg(M_WARN | M_ERRNO, "Failed to get the management socket addre= ss");
}
msg(= D_MANAGEMENT, "MANAGEMENT: TCP Socket listening on %s", print_sockaddr(man_addr, &gc));
@@ -1958,9 +1932,7 @@

#endif
{
man->connection.sd_cli =3D create_socket_tcp(man->= ;settings.local);
- = status =3D openvpn_connect(man->connection.sd_cli,
- man-&g= t;settings.local->ai_addr,
- 5,
+ status =3D openvpn_connect(man->connecti= on.sd_cli, man->settings.local->ai_addr, 5,
= &signal_received);
}

@@ -1975,15 +1947,13 @@
#if = UNIX_SOCK_SUPPORT
if (man->settings.flags &= MF_UNIX_SOCK)
{
- msg(D_LINK_ERRORS | M_ERRNO,
- "MANAGEMENT: co= nnect to unix socket %s failed",

+ msg(D_LINK_ERRORS | M_ERRNO, "MANAGEMENT= : connect to unix socket %s failed",
= sockaddr_unix_name(&man->settings.local_unix, "NULL"));
}
else
#en= dif
{
- msg(D_LINK_ERRORS | M_ERRNO,
- "MANAGEMENT: connect to %s= failed",
+ = msg(D_LINK_ERRORS | M_ERRNO, "MANAGEMENT: connect to %s failed&= quot;,
print_sockaddr(man->settings.loc= al->ai_addr, &gc));
}
= throw_signal_soft(SIGTERM, "management-connect-failed");
@@ -2048,7 +2018,7 @@
struct gc_arena gc = =3D gc_new();
struct status_output *so;
int nparms;

- = char *parms[MAX_PARMS+1];
+ char *parms[MAX_PARMS + 1];

= CLEAR(parms);
so =3D status_open(NULL, 0, -1, &= man->persist.vout, 0);
@@ -2101,8 +2071,7 @@
<= span> if (!ignore_sys_error(err, crt_error))

{
struct gc_arena gc =3D gc_new();
- msg(D_MANAGEMENT, "MANAGEMENT= : TCP %s error: %s", prefix,
- strerror(err));
+ msg(D_MANAGEMENT, "MANAGEMENT: TCP %s erro= r: %s", prefix, strerror(err));
gc_free(&= gc);
return true;
}@@ -2119,7 +2088,8 @@
struct msghdr msg =3D { 0= };
struct iovec iov[1];

<= span style=3D"color: hsl(0, 100%, 40%);">- union {

+ union
+ {
struct cmsghdr cm;
char control[CMSG_SPACE(sizeof(int))];
} control_un;

@@ -2132,7 +2102,7 @@
cmptr->cmsg_len =3D CMSG_LEN(sizeof(int));

c= mptr->cmsg_level =3D SOL_SOCKET;
cmptr->cmsg_typ= e =3D SCM_RIGHTS;
- = *((int *) CMSG_DATA(cmptr)) =3D sendfd;
+ *((int *)CMSG_DATA(cmptr)) =3D sendfd;

msg.msg_name =3D NULL;
msg.= msg_namelen =3D 0;
@@ -2152,13 +2122,14 @@
= struct iovec iov[1];
ssize_t n;
=
- union {+ union
+ {
struct c= msghdr cm;
char control[CMSG_SPACE(sizeof(int))];<= /span>
} control_un;
- struct cmsghdr *cmptr;
+ struct cmsghdr *cmptr;
- msghdr.msg_control =3D con= trol_un.control;
+ = msghdr.msg_control =3D control_un.control;
msghdr.msg= _controllen =3D sizeof(control_un.control);

msghdr.msg_name =3D NULL;

@@ -2169,13 +2140,12 @@
msghdr.msg_iov =3D iov;
msghdr.msg= _iovlen =3D 1;

- if ( (n =3D recvmsg(fd, &msghdr, flags)) <=3D 0)
+ if ((n =3D recvmsg(f= d, &msghdr, flags)) <=3D 0)
{
= return (n);
}

- if ( (cmptr =3D CMSG_FIRSTHDR(&a= mp;msghdr)) !=3D NULL

-= && cmptr->cmsg_len =3D=3D CMSG_LEN(sizeof(int)))=
+ if ((cmptr =3D CMSG_FI= RSTHDR(&msghdr)) !=3D NULL && cmptr->cmsg_len =3D=3D CMSG_LE= N(sizeof(int)))
{
if (cmptr-&= gt;cmsg_level !=3D SOL_SOCKET)
{
@= @ -2185,12 +2155,11 @@
{
= msg(M_ERR, "control type !=3D SCM_RIGHTS");
= }
- *rec= vfd =3D *((int *) CMSG_DATA(cmptr));
+ *recvfd =3D *((int *)CMSG_DATA(cmptr));
= }
else
{
- *recvfd =3D -1; /* de= scriptor was not passed */

-
+ *recvf= d =3D -1; /* descriptor was not passed */
}
= return (n);
}
@@ -2208,10 +2177= ,10 @@
}
struct user_pass up;
CLEAR(up);
- strncpy(up.username, msg, sizeof(up.username)-1);
+ strncpy(up.username, msg, size= of(up.username) - 1);


- management_query_user_pass(management, &up, comma= nd, GET_USER_PASS_NEED_OK, (void *) 0);
- return strcmp("ok", up.password)=3D=3D0;
+ management_query_u= ser_pass(management, &up, command, GET_USER_PASS_NEED_OK, (void *)0);
+ return strcmp(&qu= ot;ok", up.password) =3D=3D 0;
}

/*
@@ -2226,8 +2195,8 @@
= struct user_pass up;
CLEAR(up);
= strcpy(up.username, "tunmethod");
- management_query_user_pass(management, &up, = "PERSIST_TUN_ACTION",
- GET_USER_PASS_NEED_OK, (void *) 0)= ;
+ management_que= ry_user_pass(management, &up, "PERSIST_TUN_ACTION", GET_USER_= PASS_NEED_OK,
+ = (void *)0);
if (!strcmp("= ;NOACTION", up.password))
{
= return ANDROID_KEEP_OLD_TUN;
@@ -2238,7 +2207,8 @@
}
else
{<= br>- msg(M_ERR, "Got = unrecognised '%s' from management for PERSIST_TUN_ACTION query"= ;, up.password);
+ = msg(M_ERR, "Got unrecognised '%s' from management for PER= SIST_TUN_ACTION query",
+ up.password);
}
=
ASSERT(0);
@@ -2264,7 +2234,7 @@
{
man->connection.lastfdreceiv= ed =3D fd;
}
-#else /* ifdef TARGET_ANDROID */
+#else /* ifdef TARGET_ANDROID */
= len =3D recv(man->connection.sd_cli, (void *)buf, sizeof(buf), MSG_= NOSIGNAL);
#endif

@@ -22= 76,7 +2246,7 @@
{
bool proces= sed_command =3D false;

- ASSERT(len <=3D (int) sizeof(buf));+ ASSERT(len <=3D (i= nt)sizeof(buf));
command_line_add(man->connecti= on.in, buf, len);

/*
<= span>@@ -2304,7 +2274,7 @@

}
else

{
- man_process_comma= nd(man, (char *) line);

+ man_process_command(man, (char *)line);
<= span> }

if (man->connec= tion.halt)
{
@@ -2357,12 += 2327,13 @@
#ifdef TARGET_ANDROID
= if (man->connection.fdtosend > 0)
{- sent =3D man_send_= with_fd(man->connection.sd_cli, BPTR(buf), len, MSG_NOSIGNAL, man->co= nnection.fdtosend);
+= sent =3D man_send_with_fd(man->connection.sd_cli, BPTR(buf),= len, MSG_NOSIGNAL,
+= man->connection.fdtosend); man->connection.fdtosend =3D -1;
= }
else
#endif
- sent =3D send(man->conne= ction.sd_cli, (const void *)BPTR(buf), len, MSG_NOSIGNAL);

+ sent =3D send(man->co= nnection.sd_cli, (const void *)BPTR(buf), len, MSG_NOSIGNAL);
if (sent >=3D 0)

{
= buffer_list_advance(man->connection.out, sent);
<= span>@@ -2398,9 +2369,7 @@

}

<= span> static void

-man_= persist_init(struct management *man,
- const int log_history_cache,
- const int echo_buff= er_size,

+man_persist= _init(struct management *man, const int log_history_cache, const int echo_b= uffer_size,
const int state_buffer_size)<= /span>
{
struct man_persist *mp =3D &man= ->persist;
@@ -2458,17 +2427,10 @@
}

static void
-man_settings_init(struct man_settings *ms,- const char *a= ddr,
- = const char *port,
- = const char *pass_file,
- const char *client_user,
- const char *client_g= roup,
- = const int log_history_cache,
- const int echo_buffer_size,
- const int state_buffer_s= ize,
- = const int remap_sigusr1,
- const unsigned int flags)
+man_settings_init(struct man_settings *ms, cons= t char *addr, const char *port,
+ const char *pass_file, const char *client_use= r, const char *client_group,
+ const int log_history_cache, const int echo_buff= er_size,
+ = const int state_buffer_size, const int remap_sigusr1, const unsigned= int flags)
{
if (!ms->defined)
{
@@ -2514,7 +2476,6 @@
= else
#endif
{
= -
/*=
* Run management over tunnel, or
<= span> * separate channel?

@@ -2526,16 +2487,16= @@
else
{=
int status;
- int resolve_flags =3D GETADDR_RESOLVE|GETA= DDR_WARN_ON_SIGNAL|GETADDR_FATAL;
+ int resolve_flags =3D GETADDR_RESOLVE | GETAD= DR_WARN_ON_SIGNAL | GETADDR_FATAL;

= if (!(flags & MF_CONNECT_AS_CLIENT))
= {
resolve_flags |=3D GETADDR= _PASSIVE;
}

- status =3D openvpn= _getaddrinfo(resolve_flags, addr, port, 0,

- NULL, AF_= UNSPEC, &ms->local);
- ASSERT(status=3D=3D0);
+ status =3D
+ openvpn_getaddrinfo(r= esolve_flags, addr, port, 0, NULL, AF_UNSPEC, &ms->local);+ ASSERT(status= =3D=3D 0);
}
}

@@ -2653,9 +2614,7 @@
str= uct management *man;
ALLOC_OBJ_CLEAR(man, struct manag= ement);

- man_persist_init(man,
- MANAGEMENT_LOG_HISTORY_INITIAL_SIZE,- MANAGEMENT= _ECHO_BUFFER_SIZE,
+ = man_persist_init(man, MANAGEMENT_LOG_HISTORY_INITIAL_SIZE, MANAGEMENT_EC= HO_BUFFER_SIZE,
MANAGEMENT_STATE_BUFF= ER_SIZE);

man_connection_clear(&= man->connection);
@@ -2664,16 +2623,9 @@
}


bool
-management_open(struct management *man,
- const char *addr,
- const c= har *port,
- = const char *pass_file,
- const char *client_user,
- const char *client_group,- const int log_= history_cache,
- = const int echo_buffer_size,
- const int state_buffer_size,
- const int remap_sigus= r1,

+management_open(= struct management *man, const char *addr, const char *port, const char *pas= s_file,
+ = const char *client_user, const char *client_group, const int log_histor= y_cache,
+ = const int echo_buffer_size, const int state_buffer_size, const int rem= ap_sigusr1,
const unsigned int flags)
{
bool ret =3D false;
@@ = -2682,17 +2634,8 @@
* Save the settings only if they = have not
* been saved before.
*= /
- man_settings_ini= t(&man->settings,
- port,
- pass_file,
- client_user,
- client_group,<= /span>
- = log_history_cache,
- = echo_buffer_size,
- state_buffer_size,
- remap_sigusr1,

- flag= s);
+ man_settings= _init(&man->settings, addr, port, pass_file, client_user, client_gro= up,
+ = log_history_cache, echo_buffer_size, state_buffer_size, remap_sigusr1= , flags);

/*
*= The log is initially sized to MANAGEMENT_LOG_HISTORY_INITIAL_SIZE,<= br>@@ -2729,8 +2672,7 @@
}
<= br> void
-managem= ent_set_callback(struct management *man,
- const struct management_callback= *cb)
+management_set= _callback(struct management *man, const struct management_callback *cb)
{
man->persist.standalone_disabled = =3D true;
man->persist.callback =3D *cb;
= @@ -2746,15 +2688,12 @@
}
void
-manageme= nt_set_state(struct management *man,
- const int state,
- const char *detail,
- con= st in_addr_t *tun_local_ip,
- const struct in6_addr *tun_local_ip6,
= - const struc= t openvpn_sockaddr *local,
- const struct openvpn_sockaddr *remote)
= +management_set_state(struct ma= nagement *man, const int state, const char *detail,
+ const in_addr_t *tun= _local_ip, const struct in6_addr *tun_local_ip6,
+ const struct openvpn_sock= addr *local, const struct openvpn_sockaddr *remote)
{
- if (man->persist.st= ate && (!(man->settings.flags & MF_SERVER) || state < OPE= NVPN_STATE_CLIENT_BASE))
+ if (man->persist.state
+ && (!(man->settings.flags & MF_SERVER= ) || state < OPENVPN_STATE_CLIENT_BASE))
{ struct gc_arena gc =3D gc_new();
= struct log_entry e;
@@ -2786,13 +2725,11 @@

if (man->connection.state_realtime) {
- = out =3D log_entry_print(&e, LOG_PRINT_STATE_PREFIX
<= span style=3D"color: hsl(0, 100%, 40%);">- = | LOG_PRINT_INT_DATE

- | LOG_PRINT_STATE
- | LOG= _PRINT_LOCAL_IP
- = | LOG_PRINT_REMOTE_IP
- | LOG_P= RINT_CRLF
- = | LOG_ECHO_TO_LOG, &gc);
+ out =3D log_entry_print(&= e,
+ = LOG_PRINT_STATE_PREFIX | LOG_PRINT_INT_DATE | LOG_PRINT_ST= ATE
+ = | LOG_PRINT_LOCAL_IP | LOG_PRINT_REMOTE_IP | LOG_PRIN= T_CRLF
+ = | LOG_ECHO_TO_LOG,
+ &gc);<= br> }

if (out)
@@ -2807,25 +2744,23 @@
static bool env_filter_match(const char *env_str, const int env_filter_level)
{
- = static const char *env_names[] =3D {
- "username=3D",
- "password=3D",
- "X509_0_CN=3D",
- "tls_serial_&= quot;,
- "u= ntrusted_ip=3D",
-= "ifconfig_local=3D",
- "ifconfig_netmask=3D",
- "daemon_start_time=3D"= ;,
- "daemo= n_pid=3D",
- = "dev=3D",
-= "ifconfig_pool_remote_ip=3D",
- "ifconfig_pool_netmask=3D",
- "time_durati= on=3D",
- &= quot;bytes_sent=3D",
- "bytes_received=3D",
- "session_id=3D",
- "session_state=3D"
- };
+ static const char *env_names[] =3D = { "username=3D",
+ "password=3D",
+ = "X509_0_CN=3D",
+ "tls_seria= l_",
+ = "untrusted_ip=3D",
+ = "ifconfig_local=3D",
+ "ifconfig_netmask= =3D",
+ = "daemon_start_time=3D",
<= span style=3D"color: hsl(120, 100%, 40%);">+ = "daemon_pid=3D",

+ "dev=3D",
+ = "ifconfig_pool_remote_ip=3D",
+ = "ifconfig_pool_netmask=3D",
+ "time_durat= ion=3D",
+ = "bytes_sent=3D",
+ = "bytes_received=3D",

+ "session_id=3D&q= uot;,
+ = "session_state=3D" };
<= /span>
if (env_filter_level =3D=3D 0)
{<= /span>
@@ -2853,7 +2788,8 @@
}
<= /span>
static void
-man_output_env(const struct env_set *es, const bool tail, const int = env_filter_level, const char *prefix)
+man_output_env(const struct env_set *es, const bool tail,= const int env_filter_level,
+ const char *prefix)
{
if (es)

{
@@ -2914,11 +2850,1= 2 @@
char line[256];
if (man->= persist.callback.get_peer_info)
{
- const char *peer_info =3D (*man-&g= t;persist.callback.get_peer_info)(man->persist.callback.arg, mdac->ci= d);
+ const ch= ar *peer_info =3D
+ = (*man->persist.callback.get_peer_info)(man->persist.callbac= k.arg, mdac->cid);
if (peer_info)
{

struct buffer buf;
- buf_set_read(&buf, = (const uint8_t *) peer_info, strlen(peer_info));

+ buf_set_read(&buf, (const uint= 8_t *)peer_info, strlen(peer_info));
while (bu= f_parse(&buf, '\n', line, sizeof(line)))
= {
chomp(line);
@@ -= 2936,10 +2873,8 @@
}

vo= id
-management_notify_c= lient_needing_auth(struct management *management,
- const uns= igned int mda_key_id,
-= struct man_def_auth_context *mdac,
- = const struct env_set *es)
+management_notify_client_needing_auth(struct management= *management, const unsigned int mda_key_id,
+ struct man_d= ef_auth_context *mdac, const struct env_set *es)
{<= br> if (!(mdac->flags & DAF_CONNECTION_CLOSED))
= {
@@ -2950,7 +2885,7 @@
= }
msg(M_CLIENT, ">CLIENT:%s,%lu,%u",= mode, mdac->cid, mda_key_id);
man_output_extra= _env(management, "CLIENT");
- if (management->connection.env_filter_level>0= )
+ if (manage= ment->connection.env_filter_level > 0)
{
man_output_peer_info_env(management, mdac);
}
@@ -2960,18 +2895,15 @@
}


void
-management_notify_client_cr_response(unsigned mda_k= ey_id,
- = const struct man_def_auth_context *mdac,
- = const struct env_set *es,

- const char *response)+management_notify_client_cr_r= esponse(unsigned mda_key_id, const struct man_def_auth_context *mdac,
+ = const struct env_set *es, const char *response)
{

struct gc_arena gc;
if (manag= ement)
{
gc =3D gc_new();

- = msg(M_CLIENT, ">CLIENT:CR_RESPONSE,%lu,%u,%s",
- mdac->cid, mda_key_id= , response);

+ = msg(M_CLIENT, ">CLIENT:CR_RESPONSE,%lu,%u,%s", mdac->cid, = mda_key_id, response);
man_output_extra_env(manage= ment, "CLIENT");
if (management->conn= ection.env_filter_level > 0)
{
= @@ -2983,8 +2915,7 @@
}

= void
-management_conne= ction_established(struct management *management,
- struct man_def= _auth_context *mdac,
= +management_connection_established(struct management *management, struct ma= n_def_auth_context *mdac,
= const struct env_set *es)
{
mdac-&g= t;flags |=3D DAF_CONNECTION_ESTABLISHED;
@@ -2994,8 +2925,7= @@
}

void
-management_notify_client_close(str= uct management *management,

- struct man_def_auth_context *mdac,
+management_notify_clien= t_close(struct management *management, struct man_def_auth_context *mdac,
const struct env_set *es)
{
if ((mdac->flags & DAF_INITIAL= _AUTH) && !(mdac->flags & DAF_CONNECTION_CLOSED))
= @@ -3007,18 +2937,14 @@
}
void
-manageme= nt_learn_addr(struct management *management,
- struct man_def_auth_context *m= dac,
- = const struct mroute_addr *addr,
- const bool primary)
+management_learn_addr(struct managemen= t *management, struct man_def_auth_context *mdac,
+ const struct mroute_add= r *addr, const bool primary)
{
struct= gc_arena gc =3D gc_new();
if ((mdac->flags & D= AF_INITIAL_AUTH) && !(mdac->flags & DAF_CONNECTION_CLOSED))<= /span>
{
= - msg(M_CLIENT, ">CLIENT:ADDRESS,%lu,%s,%d",
= - mdac->cid,=
- mroute_addr_prin= t_ex(addr, MAPF_SUBNET, &gc),
- BOOL_CAST(primary));
+ msg(M_CLIENT, ">CLIENT:ADDRESS,%lu= ,%s,%d", mdac->cid,
+ mroute_addr_print_ex(addr, MAPF_SUBNET, &gc), BOOL_= CAST(primary));
}
gc_free(&gc= );
}
@@ -3042,7 +2968,10 @@

if (man->connection.echo_realtime) {
- = out =3D log_entry_print(&e, LOG_PRINT_INT_DATE|LOG_PRINT_ECHO_= PREFIX|LOG_PRINT_CRLF|MANAGEMENT_ECHO_FLAGS, &gc);
+ out =3D log_entry_print(&= ;e,
+ = LOG_PRINT_INT_DATE | LOG_PRINT_ECHO_PREFIX | LOG_PRINT_CR= LF
+ = | MANAGEMENT_ECHO_FLAGS,
+ &gc);
}

if (out)
@@ -3061,8 +2990,7 @@
* If we are runn= ing management over the tunnel,
* this is the place t= o initialize the connection.
*/
- if (man->settings.management_over_tu= nnel
- &&= ; man->connection.state =3D=3D MS_INITIAL)
+ if (man->settings.management_over_tunnel &= amp;& man->connection.state =3D=3D MS_INITIAL)
= {
/* listen on our local TUN/TAP IP address */
struct in_addr ia;
@@ -3071,12 +2999,= 11 @@

ia.s_addr =3D htonl(tun_lo= cal_ip);
inet_ntop(AF_INET, &ia, buf, sizeof(b= uf));
- ret =3D = openvpn_getaddrinfo(GETADDR_PASSIVE, buf, NULL, 0, NULL,
- AF_INE= T, &man->settings.local);
- ASSERT(ret=3D=3D0);
+ ret =3D
+ openvpn_getaddrinfo(GETADDR_PASSIVE, buf, NULL, = 0, NULL, AF_INET, &man->settings.local);
+ ASSERT(ret =3D=3D 0);
= man_connection_init(man);
}
-
}

void
@@ -3124,9 +3051,7 @@
= #ifdef _WIN32

void
-management_socket_set(struct management *ma= n,
- = struct event_set *es,
+management_socket_set(struct management *man, struct event_= set *es, void *arg,
unsigned int *pe= rsistent)
{
if (man->connection.st= ate !=3D MS_INITIAL)
@@ -3153,7 +3078,7 @@
= case MS_CC_WAIT_WRITE:
if (ma= n_persist_state(persistent, 3))
{- event_ctl(= es, ev, EVENT_READ|EVENT_WRITE, arg);
+ event_ctl(es, ev, EVENT_READ | EVENT_= WRITE, arg);
}
= break;

@@ -3186,7 +3111,8 @@=
net_event_win32_clear_selected_events(&m= an->connection.ne32, FD_ACCEPT);
}
}
- else if (man->connection.state =3D=3D MS_CC_WAIT_READ |= | man->connection.state =3D=3D MS_CC_WAIT_WRITE)
+ else if (man->connection.s= tate =3D=3D MS_CC_WAIT_READ
+ || man->connection.state =3D=3D MS_CC_WAIT_= WRITE)
{
if (= net_events & FD_READ)
{
@@ -3213,9 +3139,7 @@

#else /* ifdef _WIN32 */
void
-management_socket_set(struct management *man,
- struct event_set *e= s,
- = void *arg,
+manage= ment_socket_set(struct management *man, struct event_set *es, void *arg,
unsigned int *persistent)
{

switch (man->connection.state)
@@ -3382,7 +3306,8 @@

* Process management event loop = outside primary event loop
*/
static int=
-man_standalone_event_= loop(struct management *man, volatile int *signal_received, const time_t ex= pire)
+man_standalone= _event_loop(struct management *man, volatile int *signal_received,+ co= nst time_t expire)
{
int status =3D -= 1;
if (man_standalone_ok(man))
@@ -339= 6,18 +3321,16 @@
return status;
}

-#define= MWCC_PASSWORD_WAIT (1<<0)
-#define MWCC_HOLD_WAIT (1<<1)
-#define MWCC_OTHER_WAIT (1<<2)=
+#define MWCC_PASSWORD_WAIT= (1 << 0)
+#def= ine MWCC_HOLD_WAIT (1 << 1)
+#define MWCC_OTHER_WAIT (1 << 2)

/*
* Block until client connects
*/
static void
-man_wait_for_client_connection(struct management *m= an,
- = volatile int *signal_received,
- const time_t expire,
- = unsigned int flags)
+man_wait_for_client_connection(struct management *man, volatile int= *signal_received,
+ = const time_t expire, unsigned int flags)
{
ASSERT(man_standalone_ok(man));<= br> if (man->connection.state =3D=3D MS_LISTEN)
@@ -3492,11 +3415,8 @@

* Get a username/password from m= anagement channel in standalone mode.
*/
= bool
-management_query= _user_pass(struct management *man,
- struct user_pass *up,
- const ch= ar *type,

- = const unsigned int flags,
- const char *static_challenge)=
+management_query_us= er_pass(struct management *man, struct user_pass *up, const char *type,
+ = const unsigned int flags, const char *static_challenge)
{

struct gc_arena gc =3D gc_new();
= bool ret =3D false;
@@ -3545,10 +3465,7 @@
sc =3D static_challenge;

= }
}
- buf_printf(&alert_msg, ">%s:Need '%s' %s= ",
- = prefix,
- = type,
- = alert_type);
+ buf_printf(&alert_msg, ">%s:Need '%s' %s&= quot;, prefix, type, alert_type);

= if (flags & (GET_USER_PASS_NEED_OK | GET_USER_PASS_NEED_STR))<= br> {
@@ -3559,7 +3476,7 @@
= {
buf_printf(&alert_msg, " SC= :%d,%s",
BOOL_CAST(flags &= GET_USER_PASS_STATIC_CHALLENGE_ECHO)
- |(BOOL_CAST(flags & GET_USER_PAS= S_STATIC_CHALLENGE_CONCAT) << 1),
+ | (BOOL_CAST(flags & GET= _USER_PASS_STATIC_CHALLENGE_CONCAT) << 1),
= sc);
}

<= span>@@ -3624,8 +3541,8 @@

}

<= span> static int

-manag= ement_query_multiline(struct management *man,
- const char *b64_data, co= nst char *prompt, const char *cmd, int *state, struct buffer_list **input)<= /span>
+management_query_mul= tiline(struct management *man, const char *b64_data, const char *prompt,
+ = const char *cmd, int *state, struct buffer_list **input)
{

struct gc_arena gc =3D gc_new();
int ret =3D 0;

@@ -3644,12 +3561,12 @@

if (b64_data)
{
- alert_msg =3D a= lloc_buf_gc(strlen(b64_data)+strlen(prompt)+3, &gc);
+ alert_msg =3D alloc_buf_gc= (strlen(b64_data) + strlen(prompt) + 3, &gc);
= buf_printf(&alert_msg, ">%s:%s", prompt, b64_data);
}
else
= {
- ale= rt_msg =3D alloc_buf_gc(strlen(prompt)+3, &gc);
+ alert_msg =3D alloc_buf_gc(st= rlen(prompt) + 3, &gc);
buf_printf(&al= ert_msg, ">%s", prompt);
}
=
@@ -3702,8 +3619,9 @@

<= span> static char *

/* returns allocated base64 signature = */
-management_query_mu= ltiline_flatten_newline(struct management *man,
- const = char *b64_data, const char *prompt, const char *cmd, int *state, struct buf= fer_list **input)
+ma= nagement_query_multiline_flatten_newline(struct management *man, const char= *b64_data,
+ = const char *prompt, const char *cmd, int= *state,
+ = struct buffer_list **input)
{

int ok;
char *result =3D NULL= ;
@@ -3716,7 +3634,7 @@
buf =3D bu= ffer_list_peek(*input);
if (buf && BLEN(bu= f) > 0)
{
- result =3D (char *) malloc(BLEN(buf)+1);=
+ result =3D (ch= ar *)malloc(BLEN(buf) + 1);
check_malloc_retur= n(result);
memcpy(result, buf->data, BLEN(b= uf));
result[BLEN(buf)] =3D '\0';
@@ -3731,8 +3649,8 @@

static= char *
/* returns allocated base64 signature */-management_query_multiline_flat= ten(struct management *man,
- const char *b64_data, const char *= prompt, const char *cmd, int *state, struct buffer_list **input)
= +management_query_multiline_fla= tten(struct management *man, const char *b64_data, const char *prompt,
+ = const char *cmd, int *state, struct buffer_list **input)<= br> {
int ok;
char *result = =3D NULL;
@@ -3745,7 +3663,7 @@
bu= f =3D buffer_list_peek(*input);
if (buf &&= BLEN(buf) > 0)
{
- result =3D (char *) malloc(BLEN(buf)+1)= ;
+ result= =3D (char *)malloc(BLEN(buf) + 1);
check_mall= oc_return(result);
memcpy(result, buf->data= , BLEN(buf));
result[BLEN(buf)] =3D '\0= 9;;
@@ -3760,8 +3678,7 @@

char *

/* returns allocated base64 signature */-management_query_pk_sig(struct= management *man, const char *b64_data,
- const char *algorithm)
= +management_query_pk_sig(struct= management *man, const char *b64_data, const char *algorithm)
{

const char *prompt =3D "PK_SIGN";
const char *desc =3D "pk-sign";
@@ -3773,15 +3690,15 @@

desc =3D "rsa-sign&q= uot;;
}

- buf_write(&buf_data, b64_data, (int) strle= n(b64_data));
+ bu= f_write(&buf_data, b64_data, (int)strlen(b64_data));
= if (man->connection.client_version > 2)
{
- buf_write(&bu= f_data, ",", (int) strlen(","));
- buf_write(&buf_data, algorithm,= (int) strlen(algorithm));
+ buf_write(&buf_data, ",", (int)strlen(",&= quot;));
+ buf= _write(&buf_data, algorithm, (int)strlen(algorithm));
= }
- char *ret = =3D management_query_multiline_flatten(man,
- (c= har *)buf_bptr(&buf_data), prompt, desc,
- &= amp;man->connection.ext_key_state, &man->connection.ext_key_input= );
+ char *ret =3D= management_query_multiline_flatten(man, (char *)buf_bptr(&buf_data), p= rompt, desc,
+ = &man->connection.ext_key= _state,
+ = &man->connection.ext_key_inpu= t);
free_buf(&buf_data);
retu= rn ret;
}
@@ -3792,12 +3709,12 @@ const char prompt_1[] =3D "NEED-CERTIFICATE:";
struct buffer buf_prompt =3D alloc_buf(strlen(cert_name) + = 20);
buf_write(&buf_prompt, prompt_1, strlen(promp= t_1));
- buf_write(&= amp;buf_prompt, cert_name, strlen(cert_name)+1); /* +1 for \0 */
= + buf_write(&buf_prompt,= cert_name, strlen(cert_name) + 1); /* +1 for \0 */

char *result;
- result =3D management_query_multiline_flatten_newline(managemen= t,
- = NULL, (char *)buf_bptr(&buf_prompt= ), "certificate",
- &man->= connection.ext_cert_state, &man->connection.ext_cert_input);<= br>+ result =3D management_q= uery_multiline_flatten_newline(
+ management, NULL, (char *)buf_bptr(&buf_prompt), &q= uot;certificate",
- man->persist.standalone_disabled =3D false; /* Thi= s is so M_CLIENT messages will be correctly passed through msg() */<= br>+ man->persist.sta= ndalone_disabled =3D
= + false; /* This is so M_CLIENT messages will be correctly passe= d through msg() */
man->persist.special_state_m= sg =3D NULL;
man->settings.mansig |=3D MANSIG_I= GNORE_USR1_HUP;

@@ -3903,7 +3821,7 @@
int i;
for (i =3D 0; i < len; ++i= )
{
+ if (buf[i] = && char_class(buf[i], (CC_PRINT | CC_NEWLINE)))
= {
if (!buf_write_u8(&cl->buf, buf= [i]))
{
@@ -3987,10 +3905,16 @= @
}
if (flags & LOG_PRINT_REM= OTE_IP)
{
- buf_printf(&out, ",%s", (!addr_defined(&= e->remote_sock) ? "," :
- print_sockaddr_ex(&e-&g= t;remote_sock.addr.sa, ",", PS_DONT_SHOW_FAMILY|PS_SHOW_PORT, gc)= ));
- buf_printf= (&out, ",%s", (!addr_defined(&e->local_sock) ? ",= " :
- = print_sockaddr_ex(&e->local_sock.addr.sa, "= ,", PS_DONT_SHOW_FAMILY|PS_SHOW_PORT, gc)));
+ buf_printf(&out, ",%s",=
+ = (!addr_defined(&e->remote_sock)
+ ? ","
+ : print_sock= addr_ex(&e->remote_sock.addr.sa, ",",
+ = PS_DONT_SHOW_FAMILY | PS_SHOW_PORT, gc)));
+ buf_printf(&out, ",%s",
+ (!a= ddr_defined(&e->local_sock)
+ ? ","
+ : print_sockaddr= _ex(&e->local_sock.addr.sa, ",",
+ P= S_DONT_SHOW_FAMILY | PS_SHOW_PORT, gc)));
}
= if (flags & LOG_PRINT_LOCAL_IP && !IN6_IS_ADDR_UNSPE= CIFIED(&e->local_ip6))
{
@@ -41= 43,8 +4067,7 @@
void
management_check_byt= ecount(struct context *c, struct management *man, struct timeval *timeval)<= /span>
{
- = if (event_timeout_trigger(&man->connection.bytecount_update_interva= l,
- = timeval, ETT_DEFAULT))
+ if (event_timeout_trigger(&man->connection.bytecou= nt_update_interval, timeval, ETT_DEFAULT))
{ counter_type dco_read_bytes =3D 0;
= counter_type dco_write_bytes =3D 0;
@@ -4181,7 +4104,7 @@<= /span>
}
}

-#else /* ifdef ENABLE_MANAGEMENT */<= /span>
+#else /* ifdef ENABL= E_MANAGEMENT */

#include "win32.h&q= uot;
void
diff --git a/src/openvpn/manage.= h b/src/openvpn/manage.h
index 36a1905..083caf5 100644
--- a/src/openvpn/manage.h
+++ b/src/openvpn/ma= nage.h
@@ -24,24 +24,24 @@
#define MANAGE_= H

/* management_open flags */
= -#define MF_SERVER (1&= lt;<0)
-#define MF_Q= UERY_PASSWORDS (1<<1)
-#define MF_HOLD (1<<2)
-#define MF_SIGNAL (1<<3)

-#define MF_FORGET_DISCONNEC= T (1<<4)
-#define= MF_CONNECT_AS_CLIENT (1<<5)
-#define MF_CLIENT_AUTH (1<<6)
+#define MF_SERVER (1 <= ;< 0)
+#define MF_= QUERY_PASSWORDS (1 << 1)
+#define MF_HOLD (1 << 2)+#define MF_SIGNAL = (1 << 3)
= +#define MF_FORGET_DISCONNECT (1 << 4)
+#define MF_CONNECT_AS_CLIENT (1 <<= 5)
+#define MF_CLIEN= T_AUTH (1 << 6)
/* #define MF_CLIENT_PF = (1<<7) *REMOVED FEATURE* */
-#define MF_UNIX_SOCK (1<<8)<= br>-#define MF_EXTERNAL_KEY = (1<<9)
-#d= efine MF_EXTERNAL_KEY_NOPADDING (1<<10)
-#define MF_EXTERNAL_KEY_PKCS1PAD (1<<11)=
-#define MF_UP_DOWN = (1<<12)
-#define MF_QUERY_REMOTE (1<<13)
-#define MF_QUERY_PROXY (1&l= t;<14)
-#define MF_E= XTERNAL_CERT (1<<15)
-#define MF_EXTERNAL_KEY_PSSPAD (1<<16)-#define MF_EXTERNAL_KEY_DIGEST = (1<<17)
+#= define MF_UNIX_SOCK (1 << 8)
+#define MF_EXTERNAL_KEY (1 << 9= )
+#define MF_EXTERNA= L_KEY_NOPADDING (1 << 10)
+#define MF_EXTERNAL_KEY_PKCS1PAD (1 << 11)
+#define MF_UP_DOWN = (1 << 12)

+#de= fine MF_QUERY_REMOTE (1 << 13)
+#define MF_QUERY_PROXY (1 << 14= )
+#define MF_EXTERNA= L_CERT (1 << 15)
+#define MF_EXTERNAL_KEY_PSSPAD (1 << 16)
+#define MF_EXTERNAL_KEY_DIGEST = (1 << 17)



#ifde= f ENABLE_MANAGEMENT
@@ -51,21 +51,22 @@
#i= nclude "socket.h"
#include "mroute.h"<= /span>

-#def= ine MANAGEMENT_VERSION 5
-#define MANAGEMENT_N_PASSWORD_RETRIES 3
-#define MANAGEMENT_LOG_= HISTORY_INITIAL_SIZE 100
-#define MANAGEMENT_ECHO_BUFFER_SIZE 100
-#define MANAGEMENT_STATE_BUFFER_SIZE = 100
+#define MANA= GEMENT_VERSION 5
+#define MANAGEMENT_N_PASSWORD_RETRIES 3
+#define MANAGEMENT_LOG_HISTORY_INIT= IAL_SIZE 100

+#define= MANAGEMENT_ECHO_BUFFER_SIZE 100
+#define MANAGEMENT_STATE_BUFFER_SIZE 100=

/*
* Management-interface-ba= sed deferred authentication
*/
-struct man_def_auth_context {
+struct man_def_auth_context
= +{
unsigne= d long cid;

-#define DAF_CONNECTION_ESTABLISHED (1<<0)
-#define DAF_CONNECTION_CLOSED (1<= <1)
-#define DAF_INI= TIAL_AUTH (1<<2)
+#define DAF_CONNECTION_ESTABLISHED (1 << 0)
+#define DAF_CONNECTION_CLOSED = (1 << 1)

+#d= efine DAF_INITIAL_AUTH (1 << 2)
unsign= ed int flags;

unsigned int mda_key_i= d_counter;
@@ -98,7 +99,8 @@
* Manage log= file history
*/

-union log_entry_union {
+union log_entry_union
+{
unsigned int m= sg_flags;
int state;
int intval;<= /span>
@@ -115,23 +117,23 @@
union log_entry_= union u;
};

-#define LOG_PRINT_LOG_PREFIX (1<<0)=
-#define LOG_PRINT_ECHO_PREFI= X (1<<1)
-#defin= e LOG_PRINT_STATE_PREFIX (1<<2)
+#define LOG_PRINT_LOG_PREFIX (1 << 0)
<= span style=3D"color: hsl(120, 100%, 40%);">+#define LOG_PRINT_ECHO_PREFIX = (1 << 1)

+#defi= ne LOG_PRINT_STATE_PREFIX (1 << 2)

-#define LOG_PRINT_INT_DATE (1<&= lt;3)
-#define LOG_PRIN= T_MSG_FLAGS (1<<4)
-#define LOG_PRINT_STATE (1<<5)
-#define LOG_PRINT_LOCAL_IP (1<<6)
+#define LOG_PRINT_INT_D= ATE (1 << 3)
+= #define LOG_PRINT_MSG_FLAGS (1 << 4)
+#define LOG_PRINT_STATE (1 << 5)+#define LOG_PRINT_LOCAL_IP (= 1 << 6)

-#define LOG_PRINT_CRLF (1<<7)
-#define LOG_FATAL_NOTIFY (1<<8)=
+#define LOG_PRINT_C= RLF (1 << 7)
= +#define LOG_FATAL_NOTIFY (1 << 8)

-#define LOG_PRINT_INTVAL (1<&= lt;9)
+#define LOG_PR= INT_INTVAL (1 << 9)

-#define LOG_PRINT_REMOTE_IP (1<<10)+#define LOG_PRINT_REMOTE_IP = (1 << 10)

-#define LOG_ECHO_TO_LOG (1<<11)
+#define LOG_ECHO_TO_LOG (1 << 11= )

const char *log_entry_print(const stru= ct log_entry *e, unsigned int flags, struct gc_arena *gc);
=
@@ -173,32 +175,25 @@
{
= void *arg;

-#define MCF_SERVER (1<<0) /* is OpenVPN being run as a s= erver? */
+#define MC= F_SERVER (1 << 0) /* is OpenVPN being run as a server? */
<= span> unsigned int flags;


- void (*status) (void *arg, const int version,= struct status_output *so);
- void (*show_net) (void *arg, const int msglevel);
- int (*kill_by_cn) (void *arg, con= st char *common_name);

= - int (*kill_by_addr) (void *arg, const in_addr_t addr, const int port, = const int proto);
- = void (*delete_event) (void *arg, event_t event);
- int (*n_clients) (void *arg);
- bool (*send_cc_message) (void *a= rg, const char *message, const char *parameter);

+ void (*status)(void *arg, const int versio= n, struct status_output *so);
+ void (*show_net)(void *arg, const int msglevel);
+ int (*kill_by_cn)(void *arg,= const char *common_name);

+ int (*kill_by_addr)(void *arg, const in_addr_t addr, const int p= ort, const int proto);
+ int (*n_clients)(void *arg);<= br>+ bool (*send_cc_message)= (void *arg, const char *message, const char *parameter);
= bool (*kill_by_cid)(void *arg, const unsigned long cid, const char *kill= _msg);
- bool (*clie= nt_auth) (void *arg,
- = const unsigned long cid,
- const unsigned int mda_= key_id,
- = const bool auth,
- const char *reason,
- const char *client_re= ason,
- = struct buffer_list *cc_config); /* ownership transferred */=
- bool (*client_pending_au= th) (void *arg,
- = const unsigned long cid,
- const unsi= gned int kid,
- = const char *extra,
- unsigned int timeout= );
- char *(*get_pee= r_info) (void *arg, const unsigned long cid);
+ bool (*client_auth)(void *arg, const unsigned= long cid, const unsigned int mda_key_id,
+ const bool auth, const char *= reason, const char *client_reason,
+ struct buffer_list *cc_config); /* o= wnership transferred */
+ bool (*client_pending_auth)(void *arg, const unsigned long cid, con= st unsigned int kid,
= + const char *extra, unsigned int timeout);<= /span>
+ char *(*get_peer= _info)(void *arg, const unsigned long cid);
bool (*pro= xy_cmd)(void *arg, const char **p);
- bool (*remote_cmd) (void *arg, const char **p);+ bool (*remote_cmd)(void *= arg, const char **p);
#ifdef TARGET_ANDROID
int (*network_change)(void *arg, bool samenetwork);

= #endif
@@ -220,7 +215,8 @@
* = connections.
*/

= -struct man_persist {
<= span style=3D"color: hsl(120, 100%, 40%);">+struct man_persist

+{

bool defi= ned;

struct log_history *log;=
@@ -240,7 +236,8 @@
counter_type bytes_out;<= /span>
};

-struct man_settings {
+struct man_settings
+{
bool defined;
= unsigned int flags; /* MF_x flags */
struct addrinfo = *local;
@@ -256,9 +253,9 @@
int client= _gid;

/* flags for handling the manageme= nt interface "signal" command */
-#define MANSIG_IGNORE_USR1_HUP (1<<0)-#define MANSIG_MAP_USR1_TO_HUP = (1<<1)
-#define = MANSIG_MAP_USR1_TO_TERM (1<<2)
+#define MANSIG_IGNORE_USR1_HUP (1 << 0)
<= span style=3D"color: hsl(120, 100%, 40%);">+#define MANSIG_MAP_USR1_TO_HUP = (1 << 1)

+#def= ine MANSIG_MAP_USR1_TO_TERM (1 << 2)
unsigned in= t mansig;
};

@@ -270,12 = +267,13 @@
#define UP_QUERY_NEED_STR 4
<= /span>
/* states */
-#define MS_INITIAL 0 /* all sockets are closed */<= br>-#define MS_LISTEN 1= /* no client is connected */
-#define MS_CC_WAIT_READ 2 /* client is connected, waiting for= read on socket */
-#de= fine MS_CC_WAIT_WRITE 3 /* client is connected, waiting for ability to = write to socket */
+#= define MS_INITIAL 0 /* all sockets are closed */
+#define MS_LISTEN 1 /* no client = is connected */
+#def= ine MS_CC_WAIT_READ 2 /* client is connected, waiting for read on socket *= /
+#define MS_CC_WAIT= _WRITE 3 /* client is connected, waiting for ability to write to socket */<= /span>

-stru= ct man_connection {
+= struct man_connection
+{
int state;

= socket_descriptor_t sd_top;
@@ -344,16 +342,10 @@
struct management *management_init(void);<= br>
-bool manage= ment_open(struct management *man,
- const char *addr,
- const char *port,<= br>- const ch= ar *pass_file,
- = const char *client_user,
- const char *client_group,
<= span style=3D"color: hsl(0, 100%, 40%);">- const int lo= g_history_cache,

- = const int echo_buffer_size,
- const int state_buffer_size,
- cons= t int remap_sigusr1,
= +bool management_open(struct management *man, const char *addr, const char = *port,
+ = const char *pass_file, const char *client_user, const char *client_= group,
+ = const int log_history_cache, const int echo_buffer_size,
= + const int= state_buffer_size, const int remap_sigusr1,
= const unsigned int flags);

void = management_close(struct management *man);
@@ -362,28 +354,2= 2 @@

void management_pre_tunnel_close(st= ruct management *man);

-void management_socket_set(struct management *man,
- = struct event_set *es,
-= void *arg,
+void management_socket_set(struct management *man, struct= event_set *es, void *arg,
unsi= gned int *persistent);

void management_i= o(struct management *man);

-void management_set_callback(struct management *man,=
- = const struct management_callback *cb);
+void management_set_callback(struct management *= man, const struct management_callback *cb);

void management_clear_callback(struct management *man);


-bool management_que= ry_user_pass(struct management *man,
- struct user_pass *up,=
- = const char *type,
-= const unsigned int flags,
- const c= har *static_challenge);
+bool management_query_user_pass(struct management *man, struct user_pas= s *up, const char *type,
+ const unsigned int flags, const char *= static_challenge);

#ifdef TARGET_ANDROID=
bool management_android_control(struct management *man, c= onst char *command, const char *msg);

-#define ANDROID_KEEP_OLD_TUN 1
= +#define ANDROID_KEEP_OLD_TUN = 1
#define ANDROID_OPEN_BEFORE_CLOSE 2
= int managment_android_persisttun_action(struct management *man);
@@ -397,7 +383,8 @@

void management_up_down(struct management *man, const char *updown, co= nst struct env_set *es);


-void management_notify(struct management *man, const c= har *severity, const char *type, const char *text);
+void management_notify(struct management = *man, const char *severity, const char *type,
+ const char *text);<= br>
void management_notify_generic(struct managemen= t *man, const char *str);

@@ -407,25 +394= ,19 @@
const st= ruct env_set *es);

void management_conne= ction_established(struct management *management,
- struct ma= n_def_auth_context *mdac,
- const struct env_set *es);
+ = struct man_def_auth_context *mdac, const struct env_set *es);=

void management_notify_client_close(str= uct management *management,
- struct man_def_auth_context *mdac= ,
- = const struct env_set *es);
+ struct man_def_a= uth_context *mdac, const struct env_set *es);

<= span style=3D"color: hsl(0, 100%, 40%);">-void management_learn_addr(struct= management *management,

- const= struct mroute_addr *addr,
- const bool primary);
+void management_learn_addr(struct managem= ent *management, struct man_def_auth_context *mdac,
+ const struct m= route_addr *addr, const bool primary);

v= oid management_notify_client_cr_response(unsigned mda_key_id,
const struct man_def_auth_con= text *mdac,

- = const struct env_set *es,
- = const char *response);
+ const struct env_set *es, c= onst char *response);

-char *management_query_pk_sig(struct management *man, con= st char *b64_data,
- = const char *algorithm);
+char *management_query_pk_sig(struct managem= ent *man, const char *b64_data, const char *algorithm);

char *management_query_cert(struct management *man, const c= har *cert_name);

@@ -465,30 +446,28 @@
*/

/* client/server stat= es */
-#define OPENVPN_= STATE_INITIAL 0 /* Initial, undefined state */
-#define OPENVPN_STATE_CONNECTING 1 /* M= anagement interface has been initialized */
-#define OPENVPN_STATE_ASSIGN_IP 2 /* Assigning I= P address to virtual network interface */
-#define OPENVPN_STATE_ADD_ROUTES 3 /* Adding routes= to system */
-#define = OPENVPN_STATE_CONNECTED 4 /* Initialization sequence completed */
-#define OPENVPN_STATE_RECO= NNECTING 5 /* Restart */
-#define OPENVPN_STATE_EXITING 6 /* Exit */
+#define OPENVPN_STATE_INITIAL 0 /* = Initial, undefined state */
+#define OPENVPN_STATE_CONNECTING 1 /* Management interface has be= en initialized */
+#d= efine OPENVPN_STATE_ASSIGN_IP 2 /* Assigning IP address to virtual netwo= rk interface */
+#def= ine OPENVPN_STATE_ADD_ROUTES 3 /* Adding routes to system */
+#define OPENVPN_STATE_CONNECTED = 4 /* Initialization sequence completed */

+#define OPENVPN_STATE_RECONNECTING 5 /* Restart */=
+#define OPENVPN_STA= TE_EXITING 6 /* Exit */

/* client-o= nly states */
-#define = OPENVPN_STATE_WAIT 7 /* Waiting for initial response from server = */
-#define OPENVPN_STA= TE_AUTH 8 /* Authenticating with server */
-#define OPENVPN_STATE_GET_CONFIG 9 /* D= ownloading configuration from server */
-#define OPENVPN_STATE_RESOLVE 10 /* DNS lookup */
-#define OPENVPN_STATE_T= CP_CONNECT 11 /* Connecting to TCP server */
-#define OPENVPN_STATE_AUTH_PENDING 12 /* Waiting = in auth-pending mode
- = * technically variant of GET_CONFIG = */
+#define OPENVPN_S= TATE_WAIT 7 /* Waiting for initial response from server */+#define OPENVPN_STATE_AUTH = 8 /* Authenticating with server */
+#define OPENVPN_STATE_GET_CONFIG 9 /* Downloading c= onfiguration from server */
+#define OPENVPN_STATE_RESOLVE 10 /* DNS lookup */
+#define OPENVPN_STATE_TCP_CONNECT= 11 /* Connecting to TCP server */

+#define OPENVPN_STATE_AUTH_PENDING = \
+ 12 = /* Waiting in auth-pending mode \
+ = * technically variant of GET_CONFIG */


-#define OPENVPN_STATE_CLIENT_BASE = 7 /* Base index of client-only states */

+#define OPENVPN_STATE_CLIENT_BASE 7 /* Base index o= f client-only states */

-void management_set_state(struct management *man,
- c= onst int state,
- = const char *detail,
- const in_addr_t *tun_local_ip,<= /span>
- = const struct in6_addr *tun_local_ip6,
+void management_set_state(struct management *man, con= st int state, const char *detail,
+ const in_addr_t *tun_local_ip, cons= t struct in6_addr *tun_local_ip6,
= const struct openvpn_sockaddr *local_addr,
= const struct openvpn_sockaddr *remote_addr);
=
@@ -513,15 +492,10 @@
* These functions = drive the bytecount in/out counters.
*/
=
-void
-management_check_bytecount(struct cont= ext *c,
- = struct management *man,
- struct timeval *timeval);<= br>+void management_check_bytec= ount(struct context *c, struct management *man, struct timeval *timeval);

static inline void
-management_bytes_client(struct management *= man,
- = const int size_in,
- const int size_out)
+management_bytes_client(struct management *man,= const int size_in, const int size_out)
{
= if (!(man->persist.callback.flags & MCF_SERVER))
{

@@ -530,27 +504,24 @@
}
}

-void
-man_byt= ecount_output_server(const counter_type *bytes_in_total,
- const counte= r_type *bytes_out_total,
+void man_bytecount_output_se= rver(const counter_type *bytes_in_total,
+ const counter_type *b= ytes_out_total,
+ = struct man_def_auth_context *mdac);
=
static inline void
-management_bytes_server(struct management *man,
- con= st counter_type *bytes_in_total,
- const counter_type *bytes_out_total,
- s= truct man_def_auth_context *mdac)
+management_bytes_server(struct management *man, const counter= _type *bytes_in_total,
- = && (mdac->flags & (DAF_CONNECTION_ESTABLISHED | DAF_CON= NECTION_CLOSED)) =3D=3D DAF_CONNECTION_ESTABLISHED)
+ && (mdac->flags & = (DAF_CONNECTION_ESTABLISHED | DAF_CONNECTION_CLOSED))
+ =3D=3D DAF_CONNECTION_ESTA= BLISHED)
{
man_bytecount_outp= ut_server(bytes_in_total, bytes_out_total, mdac);
}
}

-void
-man_= persist_client_stats(struct management *man, struct context *c);
= +void man_persist_client_stats(= struct management *man, struct context *c);

#endif /* ifdef ENABLE_MANAGEMENT */


= diff --git a/src/openvpn/mbedtls_compat.h b/src/openvpn/mbedtls_compat.h
index 655c48f..62ed257 100644
--- a/src/openv= pn/mbedtls_compat.h
+++ b/src/openvpn/mbedtls_compat.h
@@ -48,7 +48,7 @@
#include <mbedtls/x509_cr= t.h>

#ifdef HAVE_PSA_CRYPTO_H<= br>- #include <psa/crypto.h= >
+#include <ps= a/crypto.h>
#endif

#= if MBEDTLS_VERSION_NUMBER >=3D 0x03000000
@@ -89,8 +89,7= @@
* an error code.
*/
static inline int

-mb= edtls_compat_ctr_drbg_update(mbedtls_ctr_drbg_context *ctx,
- const = unsigned char *additional,

+mbedtls_compat_ctr_drbg_update(mbedtls_ctr_drbg_context *ctx, const = unsigned char *additional,
= size_t add_len)
{
#if MBEDTLS_VERSION_NUM= BER > 0x03000000
@@ -115,8 +114,7 @@
}<= /span>

static inline int
-mbedtls_compat_pk_parse_key(mbedtls_pk_cont= ext *ctx,
- = const unsigned char *key, size_t keylen,
+mbedtls_compat_pk_parse_key(mbedtls_pk= _context *ctx, const unsigned char *key, size_t keylen,
= const unsigned char *pwd, size_t pwdlen, int (*f_rng)(void *, unsigned char *, = size_t), void *p_rng)
{
@@ -128,8 +126,7 @= @
}

static inline int
-mbedtls_compat_pk_parse= _keyfile(mbedtls_pk_context *ctx,
- const char *path, const char *p= assword,
+mbedtls_com= pat_pk_parse_keyfile(mbedtls_pk_context *ctx, const char *path, const char = *password,
int (*f_rng)(vo= id *, unsigned char *, size_t), void *p_rng)
{
<= span> #if MBEDTLS_VERSION_NUMBER < 0x03020100

@@ -140,8 = +137,9 @@
}

#if MBEDTLS= _VERSION_NUMBER < 0x03020100
-typedef enum {
+typedef enum
+{
+ MBEDTLS_SSL_VERSION= _UNKNOWN, /*!< Context not in use or version not yet negotiated.= */
MBEDTLS_SSL_VERSION_TLS1_2 =3D 0x0303, /*!< (D)= TLS 1.2 */
MBEDTLS_SSL_VERSION_TLS1_3 =3D 0x0304, /*!&= lt; (D)TLS 1.3 */
} mbedtls_ssl_protocol_version;diff --git a/src/openvpn/mbuf.c b/src/openvpn/mbuf.c
index 76f2e58..0750fec 100644

--- a/src/openvpn/mbuf.c
+++ b/src/openvpn/mbuf.c
@@ -50,7 +50,7 @@
if (ms)
{
= int i;
- for (i = =3D 0; i < (int) ms->len; ++i)
+ for (i =3D 0; i < (int)ms->len; ++i)<= br> {
struct mbuf_item *item =3D= &ms->array[MBUF_INDEX(ms->head, i, ms->capacity)];
= mbuf_free_buf(item->buffer);
@@ -134,= 7 +134,7 @@
if (ms)
{
<= span> int i;

- = for (i =3D 0; i < (int) ms->len; ++i)
+ for (i =3D 0; i < (int)ms->len= ; ++i)
{
struct mbuf_= item *item =3D &ms->array[MBUF_INDEX(ms->head, i, ms->capacity= )];
if (item->instance)
@@ = -153,7 +153,7 @@
if (ms)
{=
int i;
- for (i =3D 0; i < (int) ms->len; ++i)
+ for (i =3D 0; i < (int)ms-&g= t;len; ++i)
{
struct = mbuf_item *item =3D &ms->array[MBUF_INDEX(ms->head, i, ms->cap= acity)];
if (item->instance =3D=3D mi)
diff --git a/src/openvpn/mbuf.h b/src/openvpn/mbuf.h
= index 8cc7ab1..7f8c1b7 100644
--- a/src/openvpn/mbuf.= h
+++ b/src/openvpn/mbuf.h
@@ -35,14 +35,14= @@

struct multi_instance;

-#define MBUF_INDE= X(head, offset, size) (((head) + (offset)) & ((size)-1))
+#define MBUF_INDEX(head, offset, s= ize) (((head) + (offset)) & ((size) - 1))


<= span> struct mbuf_buffer

{
struct buf= fer buf;
int refcount;

-#define MF_UNICAST (1<<0)
+#define MF_UNICAST (1 &= lt;< 0)
unsigned int flags;
};

@@ -90,7 +90,7 @@
static in= line int
mbuf_maximum_queued(const struct mbuf_set *ms)
{
- r= eturn (int) ms->max_queued;
+ return (int)ms->max_queued;
}
=
struct multi_instance *mbuf_peek_dowork(struct mbu= f_set *ms);
diff --git a/src/openvpn/memdbg.h b/src/openvpn= /memdbg.h
index 9f8ff11..738a775 100644
---= a/src/openvpn/memdbg.h
+++ b/src/openvpn/memdbg.h@@ -38,7 +38,8 @@
* from uninitialized data, we n= eed to untaint it before use --
* otherwise we will get a= lot of useless warnings.
*
- * valgrind --tool=3Dmemcheck --error-limit=3Dno = --suppressions=3Ddebug/valgrind-suppress --gen-suppressions=3Dyes ./openvpn= ...
+ * valgrind -= -tool=3Dmemcheck --error-limit=3Dno --suppressions=3Ddebug/valgrind-suppres= s
+ * --gen-suppressi= ons=3Dyes ./openvpn ...
*/

#ifdef USE_VALGRIND

@@ -47,7 +48,7 @@
=
#define VALGRIND_MAKE_READABLE(addr, len)

-#else /* ifdef US= E_VALGRIND */
+#else = /* ifdef USE_VALGRIND */

#define VALGRIN= D_MAKE_READABLE(addr, len)

@@ -85,7 +86,8= @@

#include <dmalloc.h>
-#define openv= pn_dmalloc(file, line, size) dmalloc_malloc((file), (line), (size), DMALLOC= _FUNC_MALLOC, 0, 0)
+= #define openvpn_dmalloc(file, line, size) \
+ dmalloc_malloc((file), (line), (size), DMALLOC_= FUNC_MALLOC, 0, 0)

/*
= * This #define will put the line number of the log
diff --g= it a/src/openvpn/misc.c b/src/openvpn/misc.c
index 5776d6a.= .17f7706 100644
--- a/src/openvpn/misc.c
++= + b/src/openvpn/misc.c
@@ -84,7 +84,7 @@
<= /span>
uint8_t rnd_bytes[n_rnd_bytes];
c= onst char *rnd_str;
- = struct buffer hname =3D alloc_buf_gc(strlen(hostname)+sizeof(rnd_bytes)*2= +4, gc);
+ struct = buffer hname =3D alloc_buf_gc(strlen(hostname) + sizeof(rnd_bytes) * 2 + 4,= gc);

prng_bytes(rnd_bytes, sizeof(r= nd_bytes));
rnd_str =3D format_hex_ex(rnd_bytes, sizeo= f(rnd_bytes), 40, 0, NULL, gc);
@@ -118,7 +118,9 @@<= br> }
else
= {
- msg(M_FA= TAL, "ERROR: could not read %s username/password/ok/string from manage= ment interface", prefix);
+ msg(M_FATAL,
+ "ERROR: could not read %s username/pas= sword/ok/string from management interface",
+ prefix);
= }
}
return true;
@@ -134,7 +136,8 @@

* @param auth_challenge The authe= ntication challenge string to parse. Can't be NULL.
*= @param gc The gc_arena structure for memory allocation.=
*
- * @retu= rn A pointer to the parsed auth_challenge_info structure, or = NULL if parsing fails.
+ * fails.
*/
static struct auth_c= hallenge_info *
parse_auth_challenge(const char *auth_chal= lenge, struct gc_arena *gc)
@@ -143,7 +146,7 @@
<= span>

struct auth_challenge_info *ac;
const int len =3D strlen(auth_challenge);

- char *work =3D (char *) gc_malloc(len+1, fals= e, gc);
+ char *wo= rk =3D (char *)gc_malloc(len + 1, false, gc);
char *cp= ;

struct buffer b;
@= @ -191,7 +194,7 @@
{
return N= ULL;
}
- ac->user =3D (char *) gc_malloc(strlen(work)+1, true, gc);
+ ac->user =3D (ch= ar *)gc_malloc(strlen(work) + 1, true, gc);
openvpn_ba= se64_decode(work, (void *)ac->user, -1);

/* parse challenge text */

@@ -207,11 +210,8 @@
*/

bool
-get_user_pass_cr(struct user_pass *up,<= /span>
- const= char *auth_file,
- = const char *prefix,
- const unsigned int flags,
- const char *auth_challenge= )
+get_user_pass_cr(s= truct user_pass *up, const char *auth_file, const char *prefix,
<= span style=3D"color: hsl(120, 100%, 40%);">+ const unsigned= int flags, const char *auth_challenge)

{
= struct gc_arena gc =3D gc_new();

@@ = -232,8 +232,7 @@
/*
* Ge= t username/password from management interface?
*/=
- if (managemen= t
- &&am= p; (!from_authfile && (flags & GET_USER_PASS_MANAGEMENT))
+ if (management &a= mp;& (!from_authfile && (flags & GET_USER_PASS_MANAGEMENT))=
&& management_query_user_pass_enabled= (management))
{
respo= nse_from_stdin =3D false;
@@ -244,118 +243,119 @@ }
else
#endif /* = ifdef ENABLE_MANAGEMENT */
- /*
- = * Get NEED_OK confirmation from the console
- */
- if (flags & GET_USER_PASS_NEED_OK)
- {

- struct buffer user_prompt =3D alloc= _buf_gc(128, &gc);
= -
- buf_prin= tf(&user_prompt, "NEED-OK|%s|%s:", prefix, up->username);<= /span>
- if (!query= _user_SINGLE(BSTR(&user_prompt), BLEN(&user_prompt),
- u= p->password, USER_PASS_LEN, false))

- {
- msg(M_FATAL, "ERROR: could not read %s ok-con= firmation from stdin", prefix);
- }
-
- if= (!strlen(up->password))
- {
- = strcpy(up->password, "ok");
- }
- }
- else if (flags & GET_USER_PASS_INLINE_CREDS)
- {
- struct buffer buf;- buf_set_read(&= buf, (uint8_t *) auth_file, strlen(auth_file) + 1);
- if (!(flags & GET_USER_PASS= _PASSWORD_ONLY))
- = {
- = buf_parse(&buf, '\n', up->username, USER_PASS_LEN);
- }
- buf_parse(&buf, = 9;\n', up->password, USER_PASS_LEN);

-
= - if (strlen(up->password) =3D=3D 0)
- {
- password_from_stdin =3D 1;
<= span style=3D"color: hsl(0, 100%, 40%);">- }

- }
- /*
- * Read from auth file unless this is a dynamic challeng= e request.
- */=
- else if (from= _authfile && !(flags & GET_USER_PASS_DYNAMIC_CHALLENGE))=
- {
= /*
- = * Try to get username/password from a file.
+ * Get NEED_OK confirmation from t= he console
*/
- FILE *fp;
- char password_buf[USER_PASS_LEN] =3D { &#= 39;\0' };
-<= br>- fp =3D platform_f= open(auth_file, "r");
- if (!fp)
+ if (flags & GET_USER_PASS_NEED_OK)
{

- = msg(M_ERR, "Error opening '%s' auth file: %s"= , prefix, auth_file);
-= }
+ = struct buffer user_prompt =3D alloc_buf_gc(128, &gc);<= br>
- = if ((flags & GET_USER_PASS_PASSWORD_ONLY) =3D=3D 0)
- {
- /* Read username first */=
- if (fgets(up= ->username, USER_PASS_LEN, fp) =3D=3D NULL)
+ buf_printf(&user_prompt, &qu= ot;NEED-OK|%s|%s:", prefix, up->username);
+ if (!query_user_SINGLE(BSTR(= &user_prompt), BLEN(&user_prompt), up->password,
+ = USER_PASS_LEN, false))

{
- msg(M_FATAL, &q= uot;Error reading username from %s authfile: %s",

- prefix,
= + msg(M_FATA= L, "ERROR: could not read %s ok-confirmation from stdin", prefix)= ;
+ }<= /span>
+
+ if (!strlen(up->pass= word))
+ = {
+ = strcpy(up->password, "ok");
+ }
+ }
+ else if (flags & GET_USER_PASS_INLINE_CRE= DS)
+ {
+ struct= buffer buf;
+ = buf_set_read(&buf, (uint8_t *)auth_file, strlen(auth_file) + 1= );
+ i= f (!(flags & GET_USER_PASS_PASSWORD_ONLY))
+ {
+ buf_parse(&buf, '\n= 9;, up->username, USER_PASS_LEN);
+ }
+ buf_parse(&buf, '\n', up->pas= sword, USER_PASS_LEN);
+ = if (strlen(up->password) =3D=3D 0)
+ {
+ password_from_stdin =3D 1;
+ }

+ }

+ /*
+ * Read from auth file unless thi= s is a dynamic challenge request.
+ */
+ else if (from_authfile && !(flags & GET_U= SER_PASS_DYNAMIC_CHALLENGE))
+ {
+ * Try to get username/password from a file.
+ */

+ FILE *fp;
=
+ char passw= ord_buf[USER_PASS_LEN] =3D { '\0' };
+
+ fp =3D platform_fopen(auth_file, "r");
+ if (!fp)=
+ {
+ m= sg(M_ERR, "Error opening '%s' auth file: %s", prefix, aut= h_file);
+ = }
+
+ if ((flags &= GET_USER_PASS_PASSWORD_ONLY) =3D=3D 0)

+ {
+ /* Read username first */
<= span style=3D"color: hsl(120, 100%, 40%);">+ if (fgets(u= p->username, USER_PASS_LEN, fp) =3D=3D NULL)

+ {
+ msg(M_FATAL, "Er= ror reading username from %s authfile: %s", prefix,
+ auth_file)= ;
+ = }
+ = }
+ ch= omp(up->username);
+
+ i= f (fgets(password_buf, USER_PASS_LEN, fp) !=3D NULL)
+ {
+ chomp(password_buf);<= /span>
+ }
+
+ if (flags & GET_USER_= PASS_PASSWORD_ONLY && !password_buf[0])
+ {
+ msg(M_FATAL, "Error read= ing password from %s authfile: %s", prefix, auth_file);
+ }

+
+ if (password_buf[0])
+ {
+ strncpy(up->passw= ord, password_buf, USER_PASS_LEN);
+ }
+ /* The auth-file does not have the password: g= et both username
+ = * and password from the management interface if possible.
+ * Othe= rwise set to read password from console.
+ */
+#if defined(ENABLE_MANAGEMENT)
+ else if (management &= & (flags & GET_USER_PASS_MANAGEMENT)
+ && management_que= ry_user_pass_enabled(management))
+ {
+ msg(D_LOW,
+ "No password found in %= s authfile '%s'. Querying the management interface",+ prefi= x, auth_file);
+ = if (!auth_user_pass_mgmt(up, prefix, flags, auth_challenge))=
+ = {
+ = fclose(fp);
+ = return false;
+ }
+ }
+#endif
+ else
+ {
+ }
+
+ fclose(fp);
+
+ = if (!(flags & GET_USER_PASS_PASSWORD_ONLY) && str= len(up->username) =3D=3D 0)
+ {
+ msg(M_FATAL, "ERROR: username from %s aut= hfile '%s' is empty", prefix,
= auth_file);
}
= }
- = chomp(up->username);
-
- if (f= gets(password_buf, USER_PASS_LEN, fp) !=3D NULL)
- {
- chomp(password_buf);
- }
-
- if (flags & GET_USER_PASS_PASSWORD_ONLY && !pa= ssword_buf[0])
- = {
- = msg(M_FATAL, "Error reading password from %s authfile: %s", pref= ix, auth_file);
- = }
-
- if (password_buf[0])
- {
= - strncpy(up->p= assword, password_buf, USER_PASS_LEN);
- }
- /* The auth-file does not have the password: get both = username
- = * and password from the management interface if possible.
- * Otherwise set to read pa= ssword from console.
- = */
-#if def= ined(ENABLE_MANAGEMENT)
- else if (management
- && (flags & GET_USER_PASS_MANA= GEMENT)
- = && management_query_user_pass_enabled(management))- {
- msg(D_LOW, "No pas= sword found in %s authfile '%s'. Querying the management interface&= quot;, prefix, auth_file);
- if (!auth_user_pass_mgmt(up, prefix, flags, auth_chall= enge))
- = {
- = fclose(fp);
- = return false;
- = }
-#endif
else
{
- password_from_stdi= n =3D 1;

+ = username_from_stdin =3D true;
+ password_from_stdin =3D true;
}


- fclose(fp);
-
- = if (!(flags & GET_USER_PASS_PASSWORD_ONLY) && strlen(up-&= gt;username) =3D=3D 0)
= - {
- = msg(M_FATAL, "ERROR: username from %s authfile '%s' i= s empty", prefix, auth_file);
- }
- }
- = else
- {=
- username_from_st= din =3D true;
- = password_from_stdin =3D true;
- }
-=
/*
* Get username/passw= ord from standard input?
*/
@@ -3= 67,15 +367,15 @@
struct auth_challenge_inf= o *ac =3D parse_auth_challenge(auth_challenge, &gc);
= if (ac)
{
- char *response =3D = (char *) gc_malloc(USER_PASS_LEN, false, &gc);
+ char *response =3D (char= *)gc_malloc(USER_PASS_LEN, false, &gc);
= struct buffer packed_resp, challenge;

- challenge =3D = alloc_buf_gc(14+strlen(ac->challenge_text), &gc);

+ challenge =3D allo= c_buf_gc(14 + strlen(ac->challenge_text), &gc);
= buf_printf(&challenge, "CHALLENGE: %s", ac-&= gt;challenge_text);
buf_set_write(&= ;packed_resp, (uint8_t *)up->password, USER_PASS_LEN);
=
- i= f (!query_user_SINGLE(BSTR(&challenge), BLEN(&challenge),- = response, USER_PASS_LEN, BOOL_CAST(ac->flags&CR_ECHO)))<= /span>
+ = if (!query_user_SINGLE(BSTR(&challenge), BLEN(&challenge), response= ,
+ = USER_PASS_LEN, BOOL_CAST(ac->flags & CR_ECH= O)))
{
= msg(M_FATAL, "ERROR: could not read challenge response from = stdin");
}
@@ -39= 9,17 +399,17 @@

if (user= name_from_stdin && !(flags & GET_USER_PASS_PASSWORD_ONLY))
{
- query_user_add(BSTR(&user_prompt), BLEN(&a= mp;user_prompt),
- = up->username, USER_PASS_LEN, true);=
+ query_= user_add(BSTR(&user_prompt), BLEN(&user_prompt), up->username,
+ = USER_PASS_LEN, true);
}

if (password_from_stdin)
{
- query_user_add(BSTR(&pass_prompt), BLEN(&= amp;pass_prompt),
- = up->password, USER_PASS_LEN, false);
+ quer= y_user_add(BSTR(&pass_prompt), BLEN(&pass_prompt), up->password,=
+ = USER_PASS_LEN, false);
}

- = if (!query_user_exec() )
+ if (!query_user_exec())
= {
msg(M_FATAL, "ERR= OR: Failed retrieving username or password");
= }
@@ -423,17 +423,18 @@
= }

#ifdef ENABLE_MANAGEMENT=
- if (auth_cha= llenge && (flags & GET_USER_PASS_STATIC_CHALLENGE) && r= esponse_from_stdin)
+= if (auth_challenge && (flags & GET_USER_PASS_ST= ATIC_CHALLENGE)
+ = && response_from_stdin)
= {
- = char *response =3D (char *) gc_malloc(USER_PASS_LEN, false, &gc);=
+ = char *response =3D (char *)gc_malloc(USER_PASS_LEN, false, &gc);
struct buffer packed_resp, challenge;
char *pw64 =3D NULL, *resp64 =3D NULL;

- = challenge =3D alloc_buf_gc(14+strlen(auth_challenge), &gc);=
+ = challenge =3D alloc_buf_gc(14 + strlen(auth_challenge), &gc); buf_printf(&challenge, "CHALLENGE: %s= ", auth_challenge);

- if (!query_user_SINGLE(BSTR(&c= hallenge), BLEN(&challenge),
- response, USER_PASS_L= EN,
+ = if (!query_user_SINGLE(BSTR(&challenge), BLEN(&challenge), resp= onse,
+ = USER_PASS_LEN,
= BOOL_CAST(flags & GET_USER_PASS_STATIC_CHA= LLENGE_ECHO)))
{
= msg(M_FATAL, "ERROR: could not retrieve static cha= llenge response");
@@ -456,7 +457,8 @@
{

if (strlen= (up->password) + strlen(response) >=3D USER_PASS_LEN)
{

- msg(M_FATAL, "ERROR: could not conca= tenate password/static_response: string too long");
+ msg(M_FATA= L,
+ = "ERROR: could not concatenate password/static_response:= string too long");
}<= br> strncat(up->password, response, USER_P= ASS_LEN - strlen(up->password) - 1);
= }
@@ -499,7 +501,8 @@
*/=
if (!warn_shown)
{
- msg(M_WARN, "WARN= ING: this configuration may cache passwords in memory -- use the auth-nocac= he option to prevent this");

+ msg(M_WARN,
+ "WARNING: this configuration may cac= he passwords in memory -- use the auth-nocache option to prevent this"= );
warn_shown =3D true;
= }
}
@@ -594,7 +597,7 @@
<= span> char **ret =3D NULL;

int i =3D 0;
=
- buf_set_re= ad(&buf, (const uint8_t *) str, strlen(str));
+ buf_set_read(&buf, (const uint8_t *)s= tr, strlen(str));
while (buf_parse(&buf, '\n&#= 39;, line, sizeof(line)))
{
+= +len;
@@ -603,7 +606,7 @@
/* alloc ret= urn array */
ALLOC_ARRAY_CLEAR_GC(ret, char *, len + 1= , gc);

+ buf_set_read(&buf, (= const uint8_t *)str, strlen(str));
while (buf_parse(&a= mp;buf, '\n', line, sizeof(line)))
{ chomp(line);
@@ -668,12 +671,12 @@ const char *
sanitize_control_message(const char = *src, struct gc_arena *gc)
{
- char *ret =3D gc_malloc(strlen(src)+1, false, g= c);
+ char *ret = =3D gc_malloc(strlen(src) + 1, false, gc);
char *dest = =3D ret;
bool redact =3D false;
i= nt skip =3D 0;

- for (;; )
+ for (;;)
{
const cha= r c =3D *src;
if (c =3D=3D '\0')@@ -690,8 +693,7 @@
skip =3D 4;<= br> redact =3D true;
}- else if (!check_debug_l= evel(D_SHOW_KEYS)
- = && (c =3D=3D 'a' && !strncmp(src, &quo= t;auth-token ", 11)))
+ else if (!check_debug_level(D_SHOW_KEYS) && (c =3D= =3D 'a' && !strncmp(src, "auth-token ", 11)))
{
/* Unless --verb is 7 = or higher (D_SHOW_KEYS), hide
* the auth-toke= n value coming in the src string
@@ -755,8 +757,7 @@=

case 2:
= /* after the '=3D', replace non-printable or shell meta with= '_' */
- = if (!isprint(c) || isspace(c)
- || c =3D=3D '$' || c =3D=3D &= #39;(' || c =3D=3D '`')
+ if (!isprint(c) || isspace(c) || c =3D=3D &= #39;$' || c =3D=3D '(' || c =3D=3D '`')
{

*line =3D '_&#= 39;;
}
@@ -771,12 +772,12 = @@
{
char line[256];
= struct buffer buf;
- buf_set_read(&buf, (const uint8_t *) peer_info, strlen(peer_info)= );
+ buf_set_read(= &buf, (const uint8_t *)peer_info, strlen(peer_info));
= while (buf_parse(&buf, '\n', line, sizeof(line))) {
chomp(line);
= if (validate_peer_info_line(line)
- && (strncmp(line, "IV_", 3) =3D= =3D 0 || strncmp(line, "UV_", 3) =3D=3D 0) )
+ && (strncmp(line, &q= uot;IV_", 3) =3D=3D 0 || strncmp(line, "UV_", 3) =3D=3D 0))<= /span>
{
msg(M_INFO, "p= eer info: %s", line);
env_set_add(es, lin= e);
diff --git a/src/openvpn/misc.h b/src/openvpn/misc.h
index eb2449c..1b10cd9 100644
--- a/src/openv= pn/misc.h
+++ b/src/openvpn/misc.h
@@ -42,8= +42,7 @@

const char **make_arg_array(co= nst char *first, const char *parms, struct gc_arena *gc);
=
-const char **make_ext= ended_arg_array(char **p, bool is_inline,
- struct gc_arena *g= c);
+const char **mak= e_extended_arg_array(char **p, bool is_inline, struct gc_arena *gc);=

/* prepend a random prefix to hostname */
const char *hostname_randomize(const char *hostname, struct gc= _arena *gc);
@@ -76,9 +75,10 @@
/*<= br> * Challenge response info on client as pushed by server.<= br> */
-struct a= uth_challenge_info {
-#= define CR_ECHO (1<<0) /* echo response when typed by user */
-#define CR_RESPONSE (1<= ;<1) /* response needed */
+struct auth_challenge_info
+{
+= #define CR_ECHO (1 << 0) /* echo response when typed by user */
+#define CR_RESPONSE (= 1 << 1) /* response needed */
unsigned int flags= ;

const char *user;
= @@ -89,38 +89,43 @@
/*
* Challenge respo= nse info on client as pushed by server.
*/
-struct static_challenge_info {
-#define SC_ECHO (1<&= lt;0) /* echo response when typed by user */
-#define SC_CONCAT (1<<1) /* concatenate pa= ssword and response and do not base64 encode */
+struct static_challenge_info
+{
+#define SC_ECHO (1 << 0) /* echo response when t= yped by user */
+#def= ine SC_CONCAT (1 << 1) /* concatenate password and response and do no= t base64 encode */
unsigned int flags;

const char *challenge_text;
};

#else /* ifdef ENABLE_MANAGEMENT */=
-struct auth_challenge_info {= };
-struct static_chall= enge_info {};
+struct= auth_challenge_info
= +{
+};
+struct static_challenge_info
+{
+};
#endif /* ifdef ENABL= E_MANAGEMENT */

/*
* F= lags for get_user_pass and management_query_user_pass
*/<= /span>
-#define GET_USER_PASS_= MANAGEMENT (1<<0)
+#define GET_USER_PASS_MANAGEMENT (1 << 0) /* GET_USER_PASS_SENSITIVE (1<<1) not used anymore */
-#define GET_USER_PASS_PA= SSWORD_ONLY (1<<2)
-#define GET_USER_PASS_NOFATAL (1<&= lt;4)
-#define GET_USER= _PASS_NEED_STR (1<<5)
-#define GET_USER_PASS_PREVIOUS_CREDS_FAILED (1<<6)<= br>+#define GET_USER_PASS_PASSW= ORD_ONLY (1 << 2)
+#define GET_USER_PASS_NEED_OK (1 << 3)

+#define GET_USER_PASS_NO= FATAL (1 << 4)
+#define GET_USER_PASS_NEED_STR (1 << 5)
+#define GET_USER_PASS= _PREVIOUS_CREDS_FAILED (1 << 6)

-#define GET_USER_PASS_DYNAMIC_CHALLENGE = (1<<7) /**< CRV1 protocol -- dynamic challenge */
<= span style=3D"color: hsl(0, 100%, 40%);">-#define GET_USER_PASS_STATIC_CHAL= LENGE (1<<8) /**< SCRV1 protocol -- static challenge */
-#define GET_USER_PASS_STAT= IC_CHALLENGE_ECHO (1<<9) /**< SCRV1 protocol -- echo response */<= /span>
+#define GET_USER_PAS= S_DYNAMIC_CHALLENGE (1 << 7) /**< CRV1 protocol -- dynamic ch= allenge */
+#define G= ET_USER_PASS_STATIC_CHALLENGE (1 << 8) /**< SCRV1 protocol --= static challenge */
= +#define GET_USER_PASS_STATIC_CHALLENGE_ECHO (1 << 9) /**< SCRV1 p= rotocol -- echo response */

/** indicate= s that auth_file is actually inline creds */
-#define GET_USER_PASS_INLINE_CREDS (1<<10)
+#define GET_USER_PASS_I= NLINE_CREDS (1 << 10)
/** indicates passw= ord and response should be concatenated */
-#define GET_USER_PASS_STATIC_CHALLENGE_CONCAT (1<&l= t;11)
+#define GET_US= ER_PASS_STATIC_CHALLENGE_CONCAT (1 << 11)
/**
* Retrieves the user credentials from various= sources depending on the flags.
@@ -132,11 +137,8 @@
* @param auth_challenge The authentication challenge string.
* @return true if the user credentials were successfully r= etrieved, false otherwise.
*/
-bool get_user_pass_cr(struct user_pass *up,
- const= char *auth_file,
- = const char *prefix,
- const unsigned int flags,
<= span style=3D"color: hsl(0, 100%, 40%);">- const char = *auth_challenge);

+bo= ol get_user_pass_cr(struct user_pass *up, const char *auth_file, const char= *prefix,
+ = const unsigned int flags, const char *auth_challenge);
/**
* Retrieves the user crede= ntials from various sources depending on the flags.
@@ -148= ,9 +150,7 @@
* @return true if the user credentials were = successfully retrieved, false otherwise.
*/
static inline bool

= -get_user_pass(struct user_pass *up,
- const char *auth_file,
- const char *prefix,+get_user_pass(struct user_pas= s *up, const char *auth_file, const char *prefix,
= const unsigned int flags)
{
ret= urn get_user_pass_cr(up, auth_file, prefix, flags, NULL);
@= @ -205,29 +205,24 @@
/**
* Prepend a dir= ectory to a path.
*/
-struct buffer
-prepend_dir(const char *dir, const char *path, struct gc_arena *gc= );
+struct buffer pre= pend_dir(const char *dir, const char *path, struct gc_arena *gc);
/**
* Encrypt username and pass= word buffers in user_pass
*/
-void
-protect_user_pass(struct user_pass *up);
+void protect_user_pass(struct user_pass *up);<= /span>

/**
* Decrypt username= and password buffers in user_pass
*/
-void
-unprotect_user_pass(struct user_pass *up);
+void unprotect_user_pass(struct use= r_pass *up);



-#define _STRINGIFY(S) #S
+#define _STRINGIFY(S) #S
= /* *INDENT-OFF* - uncrustify need to ignore this macro */
= -#define MAC_FMT _STRINGIFY(%02hh= x:%02hhx:%02hhx:%02hhx:%02hhx:%02hhx)
+#define MAC_FMT _STRINGIFY(%02hhx:%02hhx:%02h= hx:%02hhx:%02hhx:%02hhx)
/* *INDENT-ON* */
-#define MAC_PRINT_ARG(_mac) _mac[0], = _mac[1], _mac[2], \

- = _mac[3], _mac[4], _mac[5]
-#define MAC_SCAN_ARG(_mac) &_mac[0], &_mac[1], &_mac[2],= \
- &_mac[3], &= amp;_mac[4], &_mac[5]
+#define MAC_PRINT_ARG(_mac) _mac[0], _mac[1], _mac[2], _mac[3], _mac[= 4], _mac[5]
+#define = MAC_SCAN_ARG(_mac) &_mac[0], &_mac[1], &_mac[2], &_mac[3],= &_mac[4], &_mac[5]

#endif /* if= ndef MISC_H */
diff --git a/src/openvpn/mroute.c b/src/open= vpn/mroute.c
index b14be7e..a598037 100644
= --- a/src/openvpn/mroute.c
+++ b/src/openvpn/mroute.c
@@ -47,14 +47,13 @@
static inline bool is_mac_mcast_addr(const uint8_t *mac)
{- return (bool) (mac[0] &= 1);
+ return (boo= l)(mac[0] & 1);
}

s= tatic inline bool
is_mac_mcast_maddr(const struct mroute_a= ddr *addr)
{
- return (addr->type & MR_ADDR_MASK) =3D=3D MR_ADDR_ETHER<= /span>
- && = is_mac_mcast_addr(addr->ether.addr);
+ return (addr->type & MR_ADDR_MASK) =3D=3D MR= _ADDR_ETHER && is_mac_mcast_addr(addr->ether.addr);
}


/*
@@ -81,8 +80,7= @@
}

/* only n= etworkss shorter than 8 bits are allowed to be all 0s. */
- if (all_zeros
- && !((addr->type & M= R_WITH_NETBITS) && (addr->netbits < 8)))
+ if (all_zeros && !((addr->= ;type & MR_WITH_NETBITS) && (addr->netbits < 8)))<= br> {
msg(D_MULTI_LOW, "Can't l= earn %s: network is all 0s, but netbits >=3D 8",
= mroute_addr_print(addr, gc));
@@ -91,8 +89,7 @@<= /span>

if (all_ones)
{=
- msg(D_MULTI_L= OW, "Can't learn %s: network is all 1s",
- mroute_addr_print(addr, gc));<= /span>
+ msg(D_MULTI_= LOW, "Can't learn %s: network is all 1s", mroute_addr_print(a= ddr, gc));
return false;
}

@@ -147,8 +144,7 @@


unsigned int
-mroute_extract_addr_ip(struct mroute_addr *src, struct= mroute_addr *dest,
- = const struct buffer *buf)
+mroute_extract_addr_ip(struct mroute_addr *src, = struct mroute_addr *dest, const struct buffer *buf)
{
unsigned int ret =3D 0;
if (BLEN(buf)= >=3D 1)
@@ -156,9 +152,9 @@
sw= itch (OPENVPN_IPH_GET_VER(*BPTR(buf)))
{ case 4:
- if (BLEN(buf) >=3D (int) sizeof(struct openvpn_iph= dr))
+ = if (BLEN(buf) >=3D (int)sizeof(struct openvpn_iphdr))
= {
- = const struct openvpn_iphdr *ip =3D (const struct openvpn_ip= hdr *) BPTR(buf);
+ = const struct openvpn_iphdr *ip =3D (const struct openvpn_= iphdr *)BPTR(buf);

m= route_get_in_addr_t(src, ip->saddr, 0);
= mroute_get_in_addr_t(dest, ip->daddr, 0);
@@ -180,1= 0 +176,10 @@
break;

case 6:
- if (BLEN(buf) >=3D (int) sizeof(struct openvp= n_ipv6hdr))
+ = if (BLEN(buf) >=3D (int)sizeof(struct openvpn_ipv6hdr)) {
- const struct openvpn_ipv6hdr *ipv6 =3D (const stru= ct openvpn_ipv6hdr *) BPTR(buf);
-#if 0 /* very basic debug */+ const str= uct openvpn_ipv6hdr *ipv6 =3D (const struct openvpn_ipv6hdr *)BPTR(buf);
+#if 0 /* very basic de= bug */
struct gc_arena gc =3D gc_new()= ;
msg( M_INFO, "IPv6 packet! src= =3D%s, dst=3D%s",
print_in6_= addr( ipv6->saddr, 0, &gc ),
@@ -212,9 +208,7 @@
}

static void
-mroute_copy_ether_to_addr(struct m= route_addr *maddr,

- = const uint8_t *ether_addr,
- uint16_t vid)<= br>+mroute_copy_ether_to_addr(s= truct mroute_addr *maddr, const uint8_t *ether_addr, uint16_t vid) {
maddr->type =3D MR_ADDR_ETHER; maddr->netbits =3D 0;
@@ -225,15 +219,13 @@<= /span>
}

unsigned int-mroute_extract_addr_ether(stru= ct mroute_addr *src,
- = struct mroute_addr *dest,
- uint16_t vid,=
+mroute_extract_addr_ether(= struct mroute_addr *src, struct mroute_addr *dest, uint16_t vid,
= const struct buffer *buf)
= {
unsigned int ret =3D 0;
- if (BLEN(buf) >=3D (int) sizeof(struct ope= nvpn_ethhdr))
+ if= (BLEN(buf) >=3D (int)sizeof(struct openvpn_ethhdr))
= {
- const stru= ct openvpn_ethhdr *eth =3D (const struct openvpn_ethhdr *) BPTR(buf);
+ const struct open= vpn_ethhdr *eth =3D (const struct openvpn_ethhdr *)BPTR(buf);
if (src)

{
= mroute_copy_ether_to_addr(src, eth->source, vid);
@@ -= 250,7 +242,6 @@
}

ret |=3D MROUTE_EXTRACT_SUCCEEDED;

-
}
return= ret;
}
@@ -260,8 +251,7 @@
* to a struct mroute_addr (addr).

*/
= bool
-mroute_extract_o= penvpn_sockaddr(struct mroute_addr *addr,
- const struct openvpn_so= ckaddr *osaddr,
+mrou= te_extract_openvpn_sockaddr(struct mroute_addr *addr, const struct openvpn_= sockaddr *osaddr,
bool use= _port)
{
switch (osaddr->addr.sa.s= a_family)
@@ -335,7 +325,7 @@
}=
else if ((ma->type & MR_ADDR_MASK) =3D=3D MR_ADDR_IPV= 6)
{
- int byte =3D sizeof(ma->v6.addr) - 1; /* rightmost byte = in address */
+ = int byte =3D sizeof(ma->v6.addr) - 1; /* rightmost byte in address */<= /span>
int bits_to_clear =3D 128 - ma->netbits;=

while (byte >=3D 0 && bits_= to_clear > 0)
@@ -351,7 +341,7 @@
= bits_to_clear =3D 0;
}
}

- = ASSERT( bits_to_clear =3D=3D 0 );
+ ASSERT(bits_to_clear =3D=3D 0);
= }
else
{
@@ -367= ,29 +357,24 @@
uint32_t
mroute_addr_hash_= function(const void *key, uint32_t iv)
{
- return hash_func(mroute_addr_hash_p= tr((const struct mroute_addr *) key),
- mroute_addr_hash_len((const struct mro= ute_addr *) key),
- = iv);
+ return hash_func(mroute_addr_hash_ptr((const struct mroute_addr *)key= ),
+ = mroute_addr_hash_len((const struct mroute_addr *)key), iv);
<= span> }


bool
mroute_add= r_compare_function(const void *key1, const void *key2)
{
- return mroute_addr_= equal((const struct mroute_addr *) key1,
- (const struct mroute_addr *= ) key2);
+ return = mroute_addr_equal((const struct mroute_addr *)key1, (const struct mroute_ad= dr *)key2);
}

const cha= r *
-mroute_addr_print(= const struct mroute_addr *ma,
- struct gc_arena *gc)
+mroute_addr_print(const struct mroute_addr *ma, = struct gc_arena *gc)
{
return mroute_= addr_print_ex(ma, MAPF_IA_EMPTY_IF_UNDEF, gc);
}
const char *
-mroute_addr_print_ex(const struct mroute_addr *ma,<= br>- const un= signed int flags,
- = struct gc_arena *gc)
+mroute_addr_print_ex(const struct mroute_addr *ma, const = unsigned int flags, struct gc_arena *gc)
{
struct buffer out =3D alloc_buf_gc(64, gc);

if (= ma)
@@ -399,8 +384,8 @@
switch (ma= ddr.type & MR_ADDR_MASK)
{
= case MR_ADDR_ETHER:
- buf_printf(&out, "%s", format_hex_ex(= ma->ether.addr,
- = sizeof(ma->ether.addr)= , 0, 1, ":", gc));
+ buf_printf(&out, "%s",
+ format= _hex_ex(ma->ether.addr, sizeof(ma->ether.addr), 0, 1, ":", = gc));

buf_printf(&out, "@%hu"= ;, ma->ether.vid);
break;

@@ -418,8 +403,10 @@
= {
buf_printf(&out, "[AF_INET]= ");
}
- buf_printf(&out, "%s", = print_in_addr_t(ntohl(maddr.v4.addr),
- (fla= gs & MAPF_IA_EMPTY_IF_UNDEF) ? IA_EMPTY_IF_UNDEF : 0, gc));
<= span style=3D"color: hsl(120, 100%, 40%);">+ buf_printf(&= ;out, "%s",

+ print_in_addr_t(ntohl(maddr.v4.addr),+ = (flags & MAPF_IA_EMPTY_IF_UNDEF) ? IA_EMPTY_IF_UNDEF : 0= ,
+ = gc));
if (maddr.t= ype & MR_WITH_NETBITS)
{
if (flags & MAPF_SUBNET)

@@ -44= 9,10 +436,10 @@
{
= buf_printf(&out, "[AF_INET6]");
= }
- = if (IN6_IS_ADDR_V4MAPPED( &maddr.v6.addr ) )
+ if (IN6_IS_ADDR_V= 4MAPPED(&maddr.v6.addr))

{
<= span style=3D"color: hsl(0, 100%, 40%);">- buf_printf(&a= mp;out, "%s", print_in_addr_t(maddr.v4mappedv6.addr,

- = IA_NET_ORDER, gc));

+ buf_printf(&out, "%s&= quot;,
+ = print_in_addr_t(maddr.v4mappedv6.addr, IA_NET_ORDER, gc))= ;
}
else = if (maddr.type & MR_WITH_PORT)
{
@@ -508,7 +495,7 @@
{
= if (mh->net_len_refcount[i] > 0)
{
- mh->net_len[= j++] =3D (uint8_t) i;
+ mh->net_len[j++] =3D (uint8_t)i;
= }
}
mh->n_net_len =3D j;
diff --git a/src/openvpn/mroute.h b/src/openvpn/mroute.h<= br>index e06d272..5b0c694 100644
--- a/src/openvpn/mr= oute.h
+++ b/src/openvpn/mroute.h
@@ -29,22= +29,22 @@

#include <stddef.h>

-#define= IP_MCAST_SUBNET_MASK ((in_addr_t)240<<24)
-#define IP_MCAST_NETWORK ((in_addr_t)224&l= t;<24)
+#define IP= _MCAST_SUBNET_MASK ((in_addr_t)240 << 24)
+#define IP_MCAST_NETWORK ((in_addr_t)224 &l= t;< 24)

/* Return status values for m= route_extract_addr_from_packet */

-#define MROUTE_EXTRACT_SUCCEEDED (1<<= 0)
-#define MROUTE_EXTR= ACT_BCAST (1<<1)
-#define MROUTE_EXTRACT_MCAST (1<<2)
-#define MROUTE_EXTRACT_IGMP (1<<3)<= /span>
+#define MROUTE_EXTRA= CT_SUCCEEDED (1 << 0)
+#define MROUTE_EXTRACT_BCAST (1 << 1)
+#define MROUTE_EXTRACT_MCAST (1 <= ;< 2)
+#define MRO= UTE_EXTRACT_IGMP (1 << 3)

-#define MROUTE_SEC_EXTRACT_SUCCEEDED (1<= ;<(0+MROUTE_SEC_SHIFT))
-#define MROUTE_SEC_EXTRACT_BCAST (1<<(1+MROUTE_SEC_SHIFT))
-#define MROUTE_SEC_EXTR= ACT_MCAST (1<<(2+MROUTE_SEC_SHIFT))
-#define MROUTE_SEC_EXTRACT_IGMP (1<<(3+M= ROUTE_SEC_SHIFT))
+#d= efine MROUTE_SEC_EXTRACT_SUCCEEDED (1 << (0 + MROUTE_SEC_SHIFT))
+#define MROUTE_SEC_EXTRA= CT_BCAST (1 << (1 + MROUTE_SEC_SHIFT))
+#define MROUTE_SEC_EXTRACT_MCAST (1 <&l= t; (2 + MROUTE_SEC_SHIFT))
+#define MROUTE_SEC_EXTRACT_IGMP (1 << (3 + MROUTE_SEC_SHI= FT))

= -#define MROUTE_SEC_SHIFT 4
+#define MROUTE_SEC_SHIFT 4

/*

* Choose the largest address possible with@@ -56,60 +56,64 @@
/*
* Address= Types
*/
-#define MR_ADDR_NONE 0
-#define MR_ADDR_ETHER 1
-#define MR_ADDR_IPV4 2-#define MR_ADDR_IPV6 = 3
-#define MR_ADDR_M= ASK 3
+#d= efine MR_ADDR_NONE 0
+#define MR_ADDR_ETHER 1
+#define MR_ADDR_IPV4 2
+#define MR_ADDR_IPV6 3
+#define MR_ADDR_MASK 3

/*= Address type mask indicating that port # is part of address */
<= span style=3D"color: hsl(0, 100%, 40%);">-#define MR_WITH_PORT = 4

+#define MR_WITH_PO= RT 4

/* Address type mask indicating tha= t netbits is part of address */
-#define MR_WITH_NETBITS 8
+#define MR_WITH_NETBITS 8
=
/* Indicates than IPv4 addr was extracted from ARP packet */
-#define MR_ARP = 16
+#define M= R_ARP 16

/* Address type mask indicating= that proto # is part of address */
-#define MR_WITH_PROTO 32
+#define MR_WITH_PROTO 32

-struct mroute_addr {
- uint8_t len; /* le= ngth of address */
+s= truct mroute_addr
+{<= /span>
+ uint8_t len; = /* length of address */
uint8_t proto;
- uint8_t type; /* MR_ADDR/MR_WI= TH flags */

+ uint= 8_t type; /* MR_ADDR/MR_WITH flags */
uint8_t netbi= ts; /* number of bits in network part of address,
= * valid if MR_WITH_NETBITS is set */
- union {
+ union
+ {
uint8_t raw_addr[MR_MAX_ADDR_LEN]= ; /* actual address */
= - struct {
+ = struct
+ = {
uint8_t addr[OPENVPN_ETH_ALEN];
<= span> uint16_t vid;

} ether;- struct {
- in_addr_t addr; /* _= network order_ IPv4 address */

- in_port_t port; /* _network order_ TCP/UDP port */=
+ struct
+ {
+ in_addr_t addr; /* _ne= twork order_ IPv4 address */

+ in_port_t port; /* _network order_ TCP/UDP port */
} v4;
- struct {
+ = {
struct in6_addr addr;
- in_port_t port; /* _ne= twork order_ TCP/UDP port */
+ in_port_t port; /* _network order_ TCP/UDP port */
} v6;
- struct {
+ = {
uint8_t prefix[12];
- in_addr_t addr; /* _netw= ork order_ IPv4 address */
+ in_addr_t addr; /* _network order_ IPv4 address */
} v4mappedv6;
};
= };

/* Double-check that struct packing w= orks as expected */
-st= atic_assert(offsetof(struct mroute_addr, v4.port) =3D=3D
- offsetof(struct mroute_add= r, v4) + 4,
+static_a= ssert(offsetof(struct mroute_addr, v4.port) =3D=3D offsetof(struct mroute_a= ddr, v4) + 4,
"Unexpected struct packin= g of v4");
-static= _assert(offsetof(struct mroute_addr, v6.port) =3D=3D
- offsetof(struct mroute_addr, = v6) + 16,
+static_ass= ert(offsetof(struct mroute_addr, v6.port) =3D=3D offsetof(struct mroute_add= r, v6) + 16,
"Unexpected struct packing= of v6");
-static_= assert(offsetof(struct mroute_addr, v4mappedv6.addr) =3D=3D
- offsetof(struct mroute_= addr, v4mappedv6) + 12,

+static_assert(offsetof(struct mroute_addr, v4mappedv6.addr)
<= span style=3D"color: hsl(120, 100%, 40%);">+ =3D=3D offset= of(struct mroute_addr, v4mappedv6) + 12,

&qu= ot;Unexpected struct packing of v4mappedv6");
=
/*
@@ -120,22 +124,21 @@
/*
* Used to help maintain CIDR routing table.
= */
-struct mroute_hel= per {
- unsigned int= cache_generation; /* incremented when route added */
- int ageable_ttl_secs; /* host ro= ute cache entry time-to-live*/
- int n_net_len; /* length of net_len array */
- uint8_t net_len[MR_HE= LPER_NET_LEN]; /* CIDR netlengths in descending order */
+struct mroute_helper

+{

+ unsigned int cache_generation; /* incr= emented when route added */
+ int ageable_ttl_secs; /* host route cache en= try time-to-live*/
+ = int n_net_len; /* length of net_len array */
+ uint8_t net_len[M= R_HELPER_NET_LEN]; /* CIDR netlengths in descending order */ int net_len_refcount[MR_HELPER_NET_LEN]; /* refcount of each ne= tlength */
};

struct op= envpn_sockaddr;

bool mroute_extract_open= vpn_sockaddr(struct mroute_addr *addr,
- const struct openvpn_= sockaddr *osaddr,
- = bool use_port);
+ const str= uct openvpn_sockaddr *osaddr, bool use_port);

<= span style=3D"color: hsl(0, 100%, 40%);">-bool mroute_learnable_address(con= st struct mroute_addr *addr,

- struct gc_arena *gc);
+bool mroute_learnable_address(const = struct mroute_addr *addr, struct gc_arena *gc);
uint32_t mroute_addr_hash_function(const void *key, uint32_t iv);

@@ -143,15 +146,13 @@

void mroute_addr_init(struct mroute_addr *addr);
<= span>

-const char *mro= ute_addr_print(const struct mroute_addr *ma,
- struct gc_arena *gc);<= /span>
+const char *mroute_a= ddr_print(const struct mroute_addr *ma, struct gc_arena *gc);

-#define MAPF_SUBN= ET (1<<0)
-#define MAPF_IA_EMPTY_IF_UNDEF (1<<1)
-#define MAPF_SHOW_ARP (1<<2)
-#define MAPF_SHOW_FAMILY = (1<<3)
-cons= t char *mroute_addr_print_ex(const struct mroute_addr *ma,
- const= unsigned int flags,
= +#define MAPF_SUBNET (1 << 0)
+#define MAPF_IA_EMPTY_IF_UNDEF (1 << 1)
+#define MAPF_SHOW_ARP = (1 << 2)
+#define MAPF_SHOW_FAMILY (1 << 3)
+const char *mroute_addr_print_ex(const struct= mroute_addr *ma, const unsigned int flags,
= struct gc_arena *gc);

= void mroute_addr_mask_host_bits(struct mroute_addr *ma);
@= @ -164,25 +165,19 @@

void mroute_helper_= del_iroute46(struct mroute_helper *mh, int netbits);

-unsigned int mroute_extrac= t_addr_ip(struct mroute_addr *src,
- struct mroute_addr *dest,<= /span>
+unsigned int mroute_= extract_addr_ip(struct mroute_addr *src, struct mroute_addr *dest, const struct buffer *buf);

-unsigne= d int mroute_extract_addr_ether(struct mroute_addr *src,
- s= truct mroute_addr *dest,
- co= nst struct buffer *buf);
+unsigned int mroute_extract_addr_ether(struct mroute_addr *src, struct= mroute_addr *dest,
+= uint16_t vid, const struct buffer *b= uf);

/*
* Given a raw = packet in buf, return the src and dest
* addresses of the= packet.
*/
static inline unsigned int
-mroute_extract_addr_fro= m_packet(struct mroute_addr *src,
- struct mroute_addr *dest,
- = uint16_t vid,
- = const struct buffer *buf,
- int tunnel= _type)
+mroute_extrac= t_addr_from_packet(struct mroute_addr *src, struct mroute_addr *dest, uint1= 6_t vid,
+ = const struct buffer *buf, int tunnel_type)
<= span> {

unsigned int ret =3D 0;
v= erify_align_4(buf);
@@ -232,13 +227,13 @@
= mroute_addr_hash_ptr(const struct mroute_addr *a)
{=
/* NOTE: depends on ordering of struct mroute_addr */=
- return (uint8_t *) &= a->proto;
+ ret= urn (uint8_t *)&a->proto;
}

static inline uint32_t
mroute_addr_hash_len(co= nst struct mroute_addr *a)
{
- return (uint32_t) a->len + 3;
+ return (uint32_t)a->len + 3= ;

}

static inline void<= /span>
diff --git a/src/openvpn/mss.c b/src/openvpn/mss.cindex 96a9af0..32cd3f8 100644
--- a/src/openvpn/mss= .c
+++ b/src/openvpn/mss.c
@@ -48,27 +48,24= @@
const struct openvpn_iphdr *pip;
= int hlen;

- if (BLEN(buf) < (int) sizeof(struct openvpn_iphdr))=
+ if (BLEN(buf) < (in= t)sizeof(struct openvpn_iphdr))
{
= return;
}

= verify_align_4(buf);
- = pip =3D (struct openvpn_iphdr *) BPTR(buf);
+ pip =3D (struct openvpn_iphdr *)BPTR(buf);

hlen =3D OPENVPN_IPH_GET_LEN(pip->= version_len);

- if (pip->protocol =3D=3D OPENVPN_IPPROTO_TCP
- && ntohs(pip->to= t_len) =3D=3D BLEN(buf)

- && (ntohs(pip->frag_off) & OPENVPN_IP_OFFMASK) =3D= =3D 0
- &&am= p; hlen <=3D BLEN(buf)
- && BLEN(buf) - hlen
- >=3D (int) sizeof(struct openvpn_tcphdr))
+ if (pip->protocol= =3D=3D OPENVPN_IPPROTO_TCP && ntohs(pip->tot_len) =3D=3D BLEN(b= uf)
+ &&am= p; (ntohs(pip->frag_off) & OPENVPN_IP_OFFMASK) =3D=3D 0 && h= len <=3D BLEN(buf)
+ && BLEN(buf) - hlen >=3D (int)sizeof(struct openvpn_tc= phdr))
{
struct buffer newbuf= =3D *buf;
if (buf_advance(&newbuf, hlen))
{
- struct openvpn_tcphdr *tc =3D (struct openvpn_tcphdr *) BPTR(= &newbuf);
+ = struct openvpn_tcphdr *tc =3D (struct openvpn_tcphdr *)BPTR(&newb= uf);
if (tc->flags & OPENVPN_TCPH_SYN_M= ASK)
{
mss_fi= xup_dowork(&newbuf, maxmss);
@@ -88,18 +85,18 @@=
const struct openvpn_ipv6hdr *pip6;
str= uct buffer newbuf;

- if (BLEN(buf) < (int) sizeof(struct openvpn_ipv6hdr))=
+ if (BLEN(buf) &= lt; (int)sizeof(struct openvpn_ipv6hdr))
{
<= span> return;

}

verify_align_4(buf);

- pip6 =3D (struct openvpn_ipv6hdr *) BPTR(buf);
+ pip6 =3D (struct openvpn_ipv6hdr= *)BPTR(buf);

/* do we have the full= IPv6 packet?
* "payload_len" does not incl= ude IPv6 header (+40 bytes)
*/
- if (BLEN(buf) !=3D (int) ntohs(pip6->= ;payload_len)+40)
+ = if (BLEN(buf) !=3D (int)ntohs(pip6->payload_len) + 40)
{

return;
}
<= span>@@ -123,13 +120,12 @@

* verify remainder is larg= e enough to contain a full TCP header
*/
newbuf =3D *buf;

- if (buf_advance( &newbuf, 40 )
- && BLEN(&newbuf) >=3D (int) siz= eof(struct openvpn_tcphdr))
+ if (buf_advance(&newbuf, 40) && BLEN(&newbuf) &= gt;=3D (int)sizeof(struct openvpn_tcphdr))
{- struct openvpn_tcphdr *= tc =3D (struct openvpn_tcphdr *) BPTR(&newbuf);
+ struct openvpn_tcphdr *tc =3D (st= ruct openvpn_tcphdr *)BPTR(&newbuf);
if (tc-&g= t;flags & OPENVPN_TCPH_SYN_MASK)
{
<= span style=3D"color: hsl(0, 100%, 40%);">- mss_fixup_dowork(&= ;newbuf, maxmss-20);

= + mss_fixup_dowork(&newbuf, maxmss - 20);
= }
}
}
@@ -148,= 25 +144,22 @@
int accumulate;
str= uct openvpn_tcphdr *tc;

- if (BLEN(buf) < (int) sizeof(struct openvpn_tcph= dr))
+ if (BLEN(bu= f) < (int)sizeof(struct openvpn_tcphdr))
{ return;
}
verify_align_4(buf);
- tc =3D (struct openvpn_tcphdr *) BPTR(buf);
+ tc =3D (struct openvpn_tcphdr *)= BPTR(buf);
hlen =3D OPENVPN_TCPH_GET_DOFF(tc->doff_= res);

/* Invalid header length or he= ader without options. */
- || hlen > BLEN(buf))
+ if (hlen <=3D (int= )sizeof(struct openvpn_tcphdr) || hlen > BLEN(buf))
= {
return;
}
=
- for (olen =3D hl= en - (int) sizeof(struct openvpn_tcphdr),
- opt =3D (uint8_t *)(tc + 1);
- olen > 1;
+ for (olen =3D hlen - (int)sizeof(= struct openvpn_tcphdr), opt =3D (uint8_t *)(tc + 1); olen > 1; olen -=3D optlen, opt +=3D optlen)
{<= /span>
if (*opt =3D=3D OPENVPN_TCPOPT_EOL)
@@ -196,8 +189,8 @@

{
= dmsg(D_MSS, "MSS: %" PRIu16 " -> %&quo= t; PRIu16, mssval, maxmss);
accumulate= =3D htons(mssval);
- = opt[2] =3D (uint8_t)((maxmss>>8)&0xff);<= br>- opt[3] = =3D (uint8_t)(maxmss&0xff);
+ opt[2] =3D (uint8_t)((maxmss >> 8) &a= mp; 0xff);
+ = opt[3] =3D (uint8_t)(maxmss & 0xff);
= accumulate -=3D htons(maxmss);
= ADJUST_CHECKSUM(accumulate, tc->check);
= }
@@ -227,8 +220,7 @@
}
=
static size_t
-get_ip_encap_overhead(const struct options *options,
- const= struct link_socket_info *lsi)
+get_ip_encap_overhead(const struct options *options, const struc= t link_socket_info *lsi)
{
/* Add the= overhead of the encapsulating IP packets */
sa_family= _t af;
@@ -252,8 +244,7 @@
}

static void
-frame_calculate_fragment(struct frame *frame, struct key_type *= kt,
- = const struct options *options,
+frame_calculate_fragment(struct frame *frame, struct key_= type *kt, const struct options *options,
= struct link_socket_info *lsi)
{
#= if defined(ENABLE_FRAGMENT)
@@ -283,8 +274,7 @@
<= span> }


static void
-frame_calculate_mssfix(struct frame *frame= , struct key_type *kt,
= - const struct options *options,
+frame_calculate_mssfix(struct frame *fra= me, struct key_type *kt, const struct options *options,
= struct link_socket_info *lsi)
{
if (options->ce.mssfix_fixed)
@@ -326,13= +316,10 @@
/* This is the target value our payload ne= eds to be smaller */
size_t target =3D options->ce.= mssfix - overhead;
frame->mss_fix =3D (uint16_t)(ad= just_payload_max_cbc(kt, target) - payload_overhead);
-
-
}

void
-frame_calculate_dynamic(st= ruct frame *frame, struct key_type *kt,
- const struct options *options,
+frame_calculate_dynami= c(struct frame *frame, struct key_type *kt, const struct options *options,<= /span>
struct link_socket_info *lsi)
{
if (options->ce.fragment > 0)
@@ -363,30 +350,29 @@
int encap_overhead = =3D datagram_overhead(af, proto);

/*= check if mssfix and fragment need to be adjusted */
- if (pmtu < o->ce.mssfix- || (o->ce.mssfix_enc= ap && pmtu < o->ce.mssfix + encap_overhead))
+ if (pmtu < o->ce.mssfix ||= (o->ce.mssfix_encap && pmtu < o->ce.mssfix + encap_overhe= ad))
{
const char *mtustr =3D= o->ce.mssfix_encap ? " mtu" : "";
- msg(D_MTU_INFO, "Note adju= sting 'mssfix %d%s' to 'mssfix %d mtu' "
- "according to path= MTU discovery", o->ce.mssfix,

- mtustr, pmtu);
+ msg(D_MTU_INFO,
+ "Note adjusting 'mssfix %d= %s' to 'mssfix %d mtu' "
+ "according to path MTU discovery&quo= t;,
+ o-&g= t;ce.mssfix, mtustr, pmtu);
o->ce.mssfix =3D pm= tu;
o->ce.mssfix_encap =3D true;
frame_calculate_dynamic(&c->c2.frame, &c->c1.ks.ke= y_type, o, lsi);

}

= #if defined(ENABLE_FRAGMENT)
- if (pmtu < o->ce.fragment
- || (o->ce.fragment_encap && pmtu &l= t; o->ce.fragment + encap_overhead))
+ if (pmtu < o->ce.fragment || (o->ce.fragme= nt_encap && pmtu < o->ce.fragment + encap_overhead)) {
const char *mtustr =3D o->ce.fra= gment_encap ? " mtu" : "";
- msg(D_MTU_INFO, "Note adjusting '= fragment %d%s' to 'fragment %d mtu' "
- "according to path MTU di= scovery", o->ce.fragment,
- mtustr, pmtu);
+ msg(D_MTU_INFO,
+ "Note adjusting 'fragment %d%s&= #39; to 'fragment %d mtu' "
+ "according to path MTU discovery"= ;,
+ o->= ;ce.fragment, mtustr, pmtu);
o->ce.fragment =3D= pmtu;
o->ce.fragment_encap =3D true;- frame_calculate_dynamic= (&c->c2.frame_fragment, &c->c1.ks.key_type,
- o, lsi)= ;
+ frame_calc= ulate_dynamic(&c->c2.frame_fragment, &c->c1.ks.key_type, o, l= si);
}
#endif
}
diff --git a/src/openvpn/mss.h b/src/openvpn/mss.h
index 1b1eafb..05f12a7 100644

--- a/src/openvpn/mss.h
+++ b/src/openvpn/mss.h
@@ -36,8 +36,7 @@

/** Set the --mssfix option. */
= void frame_calculate_dynamic(struct frame *frame, struct key_type *k= t,
- = const struct options *options,
- struct link_socket_info *ls= i);
+ = const struct options *options, struct link_socket_info *lsi);<= /span>

/**
* Checks and adjus= ts the fragment and mssfix value according to the
diff --gi= t a/src/openvpn/mstats.c b/src/openvpn/mstats.c
index d9ece= e3..bd6316c 100644
--- a/src/openvpn/mstats.c
+++ b/src/openvpn/mstats.c

@@ -83,7 +83,7 @@
<= span> }


/* mmap the file */
- data =3D mmap(NULL, si= zeof(struct mmap_stats), PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);+ data =3D mmap(NULL, size= of(struct mmap_stats), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); if (data =3D=3D MAP_FAILED)
{
<= span> msg(M_ERR, "mstats_open: write error: %s", fn);
diff --git a/src/openvpn/mstats.h b/src/openvpn/mstats.h
index b9f33b6..c38b0f2 100644
--- a/src/openvpn/= mstats.h
+++ b/src/openvpn/mstats.h
@@ -30,= 7 +30,8 @@
#include "basic.h"
<= /span>
/* this struct is mapped to the file */
-struct mmap_stats {
+struct mmap_stats
+{
counter_type link_= read_bytes; /* counter_type can be assumed to be a uint64_t */
counter_type link_write_bytes;

int n_clients;=
diff --git a/src/openvpn/mtcp.c b/src/openvpn/mtcp.c
index 9781724..81310a2 100644
--- a/src/openvpn/= mtcp.c
+++ b/src/openvpn/mtcp.c
@@ -66,8 +6= 6,9 @@

if (he)
= {
- = struct multi_instance *oldmi =3D (struct multi_instance *) he->value;
- msg(D_MULTI_= LOW, "MULTI TCP: new incoming client address matches existing client a= ddress -- new client takes precedence");
+ struct multi_instance *oldmi =3D (str= uct multi_instance *)he->value;
+ msg(D_MULTI_LOW,
+ "MULTI TCP: new incoming clien= t address matches existing client address -- new client takes precedence&qu= ot;);
oldmi->did_real_hash =3D false;
multi_close_instance(m, oldmi, false);
he->key =3D &mi->real;

@@ -108,1= 2 +109,10 @@
ASSERT(mi->context.c2.link_sockets[0]-= >info.lsa);
ASSERT(mi->context.c2.link_sockets[0= ]->mode =3D=3D LS_MODE_TCP_ACCEPT_FROM);
ASSERT(mi-= >context.c2.link_sockets[0]->info.lsa->actual.dest.addr.sa.sa_fami= ly =3D=3D AF_INET
- = || mi->context.c2.link_sockets[0]->info.lsa->actual.dest.ad= dr.sa.sa_family =3D=3D AF_INET6
- );
+ || mi->context.c2.link_sockets[0]->info.lsa->actual= .dest.addr.sa.sa_family =3D=3D AF_INET6);
mi->real.= proto =3D mi->context.c2.link_sockets[0]->info.proto;
- if (!mroute_extract_openvpn_socka= ddr(&mi->real,

-= &mi->context.c2.link_socket= s[0]->info.lsa->actual.dest,
- true))
+ if (!mroute_extract_openvpn_so= ckaddr(

+ = &mi->real, &mi->context.c2.link_sockets[0]->info.lsa->a= ctual.dest, true))
{
msg(D_MU= LTI_ERRORS, "MULTI TCP: TCP client address is undefined");=
return false;
@@ -149,7 +148,8 @@=
}

bool
-multi_tcp_process_outgoing_link_ready(struc= t multi_context *m, struct multi_instance *mi, const unsigned int mpp_flags= )
+multi_tcp_process_= outgoing_link_ready(struct multi_context *m, struct multi_instance *mi,
+ = const unsigned int mpp_flags)
{
<= span> struct mbuf_item item;

bool ret =3D true;
diff --git a/src/openvpn/mtcp.h b/src/openvpn/mtcp.hindex 5158427d..f4b806c 100644
--- a/src/openvpn/mt= cp.h
+++ b/src/openvpn/mtcp.h
@@ -39,9 +39,= 11 @@

void multi_tcp_instance_specific_f= ree(struct multi_instance *mi);

-bool multi_tcp_process_outgoing_link(struct mul= ti_context *m, bool defer, const unsigned int mpp_flags);
+bool multi_tcp_process_outgoing_link(= struct multi_context *m, bool defer,
+ const unsigned int mp= p_flags);

-bool multi_tcp_process_outgoing_link_ready(struct multi_context *m, s= truct multi_instance *mi, const unsigned int mpp_flags);
+bool multi_tcp_process_outgoing_link_r= eady(struct multi_context *m, struct multi_instance *mi,
+ = const unsigned int mpp_flags);

stru= ct multi_instance *multi_create_instance_tcp(struct multi_context *m, struc= t link_socket *sock);

diff --git a/src/op= envpn/mtu.c b/src/openvpn/mtu.c
index 7245f95..c9d3389 1006= 44
--- a/src/openvpn/mtu.c
+++ b/src/openvp= n/mtu.c
@@ -38,8 +38,7 @@

/* allocate a buffer for socket or tun layer */

void
-alloc_buf_sock_tun(struct= buffer *buf,
- = const struct frame *frame)
+alloc_buf_sock_tun(struct buffer *buf, const struct frame= *frame)
{
/* allocate buffer for ove= rlapped I/O */
*buf =3D alloc_buf(BUF_SIZE(frame));
@@ -59,8 +58,7 @@
}
=
size_t
-fram= e_calculate_protocol_header_size(const struct key_type *kt,
- = const struct options *options,

+frame_calculate_protocol_header_size(const struct key_type *kt, = const struct options *options,
= bool occ)
{
/* Sum of all t= he overhead that reduces the usable packet size */
@@ -97,8= +95,7 @@


size_t
-frame_calculate_payload_ove= rhead(size_t extra_tun,
- const struct options *options,+frame_calculate_payload_overh= ead(size_t extra_tun, const struct options *options,
= const struct key_type *kt)
{
size_t overhead =3D 0;
@@ -138,8 +135,7= @@
}

size_t
= -frame_calculate_payload_size(con= st struct frame *frame,
- const struct options *options,
+frame_calculate_payload_size(cons= t struct frame *frame, const struct options *options,

= const struct key_type *kt)
{
size_t payload_size =3D options->ce.tun_mtu;
= @@ -174,7 +170,7 @@
* overhead */
/* overhead of BF-CBC: 64 bit block size,= 64 bit IV size */
- = overhead +=3D 64/8 + 64/8;
+ overhead +=3D 64 / 8 + 64 / 8;
= /* set ciphername to none, so its size does get added in the
* fake_kt and the cipher is not tried to be resolved */
=
ciphername =3D "none";
@@ -191= ,9 +187,7 @@
}

void
-frame_print(const struct = frame *frame,
- = int level,
- = const char *prefix)
+frame_print(const struct frame *frame, int level, const char *prefix)<= /span>
{
struct gc_arena gc =3D gc_new();
struct buffer out =3D alloc_buf_gc(256, &gc);=
@@ -229,19 +223,18 @@
{
= #if defined(IP_MTU_DISCOVER)
case AF_INET:
- if (sets= ockopt(sd, IPPROTO_IP, IP_MTU_DISCOVER,
- (void *) &mtu_type, si= zeof(mtu_type)))
+ = if (setsockopt(sd, IPPROTO_IP, IP_MTU_DISCOVER, (void *)&m= tu_type,
+ = sizeof(mtu_type)))
{
- msg= (M_ERR, "Error setting IP_MTU_DISCOVER type=3D%d on TCP/UDP socket&quo= t;,
- = mtu_type);
+ = msg(M_ERR, "Error setting IP_MTU_DISCOVER type=3D%d o= n TCP/UDP socket", mtu_type);
}
break;

#endi= f
#if defined(IPV6_MTU_DISCOVER)
= case AF_INET6:
- = if (setsockopt(sd, IPPROTO_IPV6, IPV6_MTU_DISCOVER,
= - (= void *) &mtu_type, sizeof(mtu_type)))
+ if (setsockopt(sd, IPPROTO_IPV6, IPV6= _MTU_DISCOVER, (void *)&mtu_type,
+ sizeof(mtu_type)))<= br> {
msg(M_ERR,= "Error setting IPV6_MTU_DISCOVER type=3D%d on TCP6/UDP6 socket",=
mtu_type);
@@ -27= 2,13 +265,11 @@
{
return IP_P= MTUDISC_DONT;
}
- msg(M_FATAL,
- "invalid --mtu-disc type: '%s' -- valid type= s are 'yes', 'maybe', or 'no'",
- name);

-#else /* if defined(IP_PMTUDISC_DONT) &= ;& defined(IP_PMTUDISC_WANT) && defined(IP_PMTUDISC_DO) */
+ msg(M_FATAL, "i= nvalid --mtu-disc type: '%s' -- valid types are 'yes', '= ;maybe', or 'no'", name);
+#else /* if defined(IP_PMTUDISC_DONT) && def= ined(IP_PMTUDISC_WANT) && defined(IP_PMTUDISC_DO) */
msg(M_FATAL, MTUDISC_NOT_SUPPORTED_MSG);

#endif
- return -1; = /* NOTREACHED */
+ return -1; /* NOTREACHED */
}

#if EXTENDED_SOCKET_ERROR_CAPABILITY
@@ -300= ,7 +291,7 @@
struct sock_extended_err *e;
struct sockaddr_storage addr;

struct buffer o= ut =3D alloc_buf_gc(256, gc);
- char *cbuf =3D (char *) gc_malloc(256, false, gc);
+ char *cbuf =3D (char *)gc_ma= lloc(256, false, gc);


*mtu =3D 0;

@@ -309,7 +300,7 @@
= memset(&rcvbuf, -1, sizeof(rcvbuf));
iov.iov= _base =3D &rcvbuf;
iov.iov_len =3D sizeof(rcvb= uf);
- msg.msg_n= ame =3D (uint8_t *) &addr;
+ msg.msg_name =3D (uint8_t *)&addr;
= msg.msg_namelen =3D sizeof(addr);
msg.msg_= iov =3D &iov;
msg.msg_iovlen =3D 1;
= @@ -331,7 +322,7 @@
{
= if (cmsg->cmsg_type =3D=3D IP_RECVERR)
= {
- = e =3D (struct sock_extended_err *) CMSG_DATA(cmsg);+ e =3D (s= truct sock_extended_err *)CMSG_DATA(cmsg);
= }
else
{=
@@ -342,7 +333,7 @@
{<= br> if (cmsg->cmsg_type =3D=3D IPV6_RECVERR)
{
- e =3D (struct sock_extended_err *) CMSG_DATA(cm= sg);
+ = e =3D (struct sock_extended_err *)CMSG_DATA(cmsg);
= }
else
= {
@@ -405,7 +396,7 @@
/* s= ee "man 7 ip" (on Linux)
* this works on IP= v4 and IPv6(-dual-stack) sockets (v4-mapped)
*/
- if (setsockopt(sd, SOL_= IP, IP_RECVERR, (void *) &on, sizeof(on)) !=3D 0)
+ if (setsockopt(sd, SOL_IP, IP_RECVERR= , (void *)&on, sizeof(on)) !=3D 0)
{
msg(M_WARN | M_ERRNO,

"Note: = enable extended error passing on TCP/UDP socket failed (IP_RECVERR)");=
@@ -414,7 +405,7 @@
* this only work= s on IPv6 sockets
*/
if (proto_a= f =3D=3D AF_INET6
- = && setsockopt(sd, IPPROTO_IPV6, IPV6_RECVERR, (void *) &on,= sizeof(on)) !=3D 0)
= + && setsockopt(sd, IPPROTO_IPV6, IPV6_RECVERR, (void *)&= ;on, sizeof(on)) !=3D 0)
{
ms= g(M_WARN | M_ERRNO,
"Note: enable extende= d error passing on TCP/UDP socket failed (IPV6_RECVERR)");
<= span>diff --git a/src/openvpn/mtu.h b/src/openvpn/mtu.h

ind= ex 64fd5b9..925ef0b 100644
--- a/src/openvpn/mtu.h+++ b/src/openvpn/mtu.h
@@ -50,38 +50,38 @@<= br> /*
* Standard ethernet MTU
*/=
-#define ETHERNET_MTU = 1500
+#define E= THERNET_MTU 1500

/*
* = It is a fatal error if mtu is less than
* this value for = tun device.
*/
-#define TUN_MTU_MIN 100
+#define TUN_MTU_MIN 100

<= span> /*

* Default MTU of network over which tunnel data = will pass by TCP/UDP.
*/
-#define LINK_MTU_DEFAULT 1500
+#define LINK_MTU_DEFAULT 1500
<= span>

/*
* Default MTU of tunnel device= .
*/
= -#define TUN_MTU_DEFAULT 1500
+#define TUN_MTU_DEFAULT 1500

/*

* MTU Defaults for TAP devices
*/<= /span>
-#define TAP_MTU_EXTRA_= DEFAULT 32
+#define = TAP_MTU_EXTRA_DEFAULT 32

/*
* Default MSSFIX value, used for reducing TCP MTU size

*/

-#define MSSFIX_= DEFAULT 1492
+#de= fine MSSFIX_DEFAULT 1492

/*
* Default maximum size of control channel packets

*= /
-#define TLS_MTU_DEFA= ULT 1250
+#define = TLS_MTU_DEFAULT 1250

/*
= * Alignment of payload data such as IP packet or
@@ -94,6= 2 +94,64 @@
/**
* Packet geometry parame= ters.
*/
-struct frame {
- = struct {
+struct fr= ame
+{
+ struct

+ {
/* This st= ruct holds all the information about the buffers that are
= * allocated to match this frame */
- int payload_size; /**< the maximum s= ize that a payload that our
- * buffers can hold from either tun= device
- = * or network link.
- */
+ int payload_size; /**< the max= imum size that a payload that our
+ * buffers can hold from either t= un device
+ = * or network link.
+ */

- int h= eadroom; /**< the headroom in the buffer, this is choosen
- = * to allow all potential header to be added
- * before= the packet */
+ = int headroom; /**< the headroom in the buffer, this is choosen=
+ * = to allow all potential header to be added
+ * before the packet */

- = int tailroom; /**< the tailroom in the buffer. Chosen large
- = * enough to also accompany any extrea header
- * or = work space required by
= - * decryption/encryption or compression.= */
+ int tail= room; /**< the tailroom in the buffer. Chosen large
+ * enough to also= accompany any extrea header
+ * or work space required by
+ * decrypti= on/encryption or compression. */

} buf;

- uint16_t mss_f= ix; /**< The actual MSS value that should be
- * wr= itten to the payload packets. This
- * is the value for IPv4 TCP= packets. For
- = * IPv6 packets another 20 bytes must
<= span style=3D"color: hsl(0, 100%, 40%);">- = * be subtracted */

= + uint16_t mss_fix; /**< The actual MSS value that should be
+ = * written to the payload packets. This
+ * is the value for = IPv4 TCP packets. For
+ * IPv6 packets another 20 bytes must=
+ = * be subtracted */

- int max_fragment_size; /**< The maximum size= of a fragment.
- = * Fragmentation is done on the unencrypted
- = * payload after (potential) compression. So
- * this value s= pecifies the maximum payload
- * size that can be send in a single= fragment
- = */
+ int max_fragment_size; /**< The maximum size of a fragment.
+ = * Fragmentation is done on the unencrypted
+ * payload after (pot= ential) compression. So
+ * this value specifies the maximum payload<= /span>
+ = * size that can be send in a single fragment
+ */
=
- int tun_mt= u; /**< the (user) configured tun-mtu. This is used
- = * in configuring the tun interface or
- * in calculation= s that use the desired size
- * of the payload in the buffer.
- = *
- = * This variable is also used in control
<= span style=3D"color: hsl(0, 100%, 40%);">- = * frame context to set the desired maximum

- * control frame p= ayload (although most of
- */
- int tun_max_mtu; = /**< the maximum tun-mtu size the buffers are
- * are s= ized for. This is the upper bound that
- * a server can push as = MTU */
+ int tun_m= tu; /**< the (user) configured tun-mtu. This is used+ *= in configuring the tun interface or
+ * in calculations that use= the desired size
+ = * of the payload in the buffer.
+ *
+ = * This variable is also used in control
+ * frame context to s= et the desired maximum
+ = * code ignores it)
+ */
+ int tun_max_mtu; /**< the maximum tun-mtu = size the buffers are
= + * are sized for. This is the upper bound tha= t
+ = * a server can push as MTU */

- int extra_tun; /**&l= t; Maximum number of bytes in excess of

- * the tun/tap MTU that= might be read
- = * from or written to the virtual
- * = tun/tap network interface.

- *
- * Only set with the o= ption --tun-mtu-extra
-= * which defaults to 0 for tun and 32
- = * (\c TAP_MTU_EXTRA_DEFAULT) for tap.
- * */+ int extra_tun; /*= *< Maximum number of bytes in excess of
+ * the tun/tap MTU that= might be read
+ = * from or written to the virtual
+ * tun/t= ap network interface.
+ *
+ * Only set with the option --tun-= mtu-extra
+ = * which defaults to 0 for tun and 32
+ * (\c TA= P_MTU_EXTRA_DEFAULT) for tap.
+ * */
};
=
/* Forward declarations, to prevent includes */
@@ -174,9 +176,7 @@
* Function prototypes.<= /span>
*/

-void frame_print(const struct frame *frame,
- int level,
- const char *p= refix);
+void frame_p= rint(const struct frame *frame, int level, const char *prefix);
<= span>

void set_mtu_discover_type(socket_descriptor_t sd, = int mtu_type, sa_family_t proto_af);

@@ -= 194,10 +194,8 @@
*
* * [IP][UDP][OPENV= PN PROTOCOL HEADER][ **PAYLOAD incl compression header** ]
= */
-size_t
= -frame_calculate_payload_size(con= st struct frame *frame,
- const struct options *options,
- const = struct key_type *kt);

+size_t frame_calculate_payload_size(const struct frame *frame, const stru= ct options *options,
= + const struct key_type *kt);
=
/**
* Calculates the size of the= payload overhead according to tun-mtu and
@@ -215,10 +213,= 8 @@
*
* * [IP][UDP][OPENVPN PROTOCOL = HEADER][ **PAYLOAD incl compression header** ]
*/<= br>-size_t
-frame_calculate_payload_overhead(size_t ext= ra_tun,
- = const struct options *options,
- const struct k= ey_type *kt);
+size_t= frame_calculate_payload_overhead(size_t extra_tun, const struct options *o= ptions,
+ = const struct key_type *kt);


/**
@@ -236,10 +232,8 @@<= /span>
* @param occ Use the calculation for the OCC li= nk-mtu
* @return size of the overhead in byt= es
*/
-size_t
-frame_calcula= te_protocol_header_size(const struct key_type *kt,
- const str= uct options *options,
-= bool occ);
+size_t frame_calculate_protocol_header_size(con= st struct key_type *kt,
+ const struct options *optio= ns, bool occ);

/**
* C= alculate the link-mtu to advertise to our peer. The actual value is not
@@ -248,23 +242,18 @@
* value they expect. = This assumes that the traditional cipher/auth directives
= * in the config match the config of the peer.
*/<= br>-size_t
-calc_options_string_link_mtu(const struct o= ptions *options,
- = const struct frame *frame);
+size_t calc_options_string_link_mtu(const= struct options *options, const struct frame *frame);

/**
* Return the size of the packet ID size= that is currently in use by cipher and
* options for the= data channel.
*/
-unsigned int
-calc_packet_id_size_dc(const struct options *options,
- const struct ke= y_type *kt);
+unsigne= d int calc_packet_id_size_dc(const struct options *options, const struct ke= y_type *kt);

/*
* allo= cate a buffer for socket or tun layer
*/
-void alloc_buf_sock_tun(struct buffer = *buf,
- = const struct frame *frame);
+void alloc_buf_sock_tun(struct buffer *buf, const struct fr= ame *frame);

/*
* EXTE= NDED_SOCKET_ERROR_CAPABILITY functions -- print extra error info
= diff --git a/src/openvpn/mudp.c b/src/openvpn/mudp.c
= index 5755273..7259a4b 100644
--- a/src/openvpn/mudp.c
+++ b/src/openvpn/mudp.c
@@ -38,18 +38,15 @@
#endif

static void=
-send_hmac_reset_packet(struc= t multi_context *m,
- = struct tls_pre_decrypt_state *state,
- struct tls_auth_= standalone *tas,
- = struct session_id *sid,
+send_hmac_reset_packet(struct multi_context *m, struc= t tls_pre_decrypt_state *state,
+ struct tls_auth_standalone *tas, struct = session_id *sid,
bool request_resen= d_wkc)
{
reset_packet_id_send(&st= ate->tls_wrap_tmp.opt.packet_id.send);
state->tl= s_wrap_tmp.opt.packet_id.rec.initialized =3D true;
uin= t8_t header =3D 0 | (P_CONTROL_HARD_RESET_SERVER_V2 << P_OPCODE_SHIFT= );
struct buffer buf =3D tls_reset_standalone(&sta= te->tls_wrap_tmp, tas, sid,
- &state->peer_s= ession_id, header,
- = request_resend_wkc);
+ = &state->peer_session_id, header, request_resend_wkc);

struct context *c =3D &m->top;=

@@ -65,8 +62,7 @@

/* Returns true if this packet should create a new session */<= /span>
static bool
-do_pre_decrypt_check(struct multi_context *m,
- struct tls_pre_decrypt= _state *state,
+do_pr= e_decrypt_check(struct multi_context *m, struct tls_pre_decrypt_state *stat= e,
struct mroute_addr addr) {
ASSERT(m->top.c2.tls_auth_standalone);

@@ -108,8 +104,8 @@
if (early_neg_su= pport)
{
/* Calculate= the session ID HMAC for our reply and create reset packet */
- struct session_id sid = =3D calculate_session_id_hmac(state->peer_session_id,

- = from, hmac, handwindow, 0);
+ struct session_id sid =3D<= br>+ calculate_s= ession_id_hmac(state->peer_session_id, from, hmac, handwindow, 0);
send_hmac_reset_packet(m, state, tas, &sid, tru= e);

return false;
= @@ -124,8 +120,10 @@
{
= struct gc_arena gc =3D gc_new();
= const char *peer =3D print_link_socket_actual(&m->top.c2.from= , &gc);
- = msg(D_MULTI_DEBUG, "tls-crypt-v2 force-cookie is enabled, "=
- &= quot;ignoring connection attempt from old client (%s)", peer);<= br>+ msg(D_MULTI= _DEBUG,
+ = "tls-crypt-v2 force-cookie is enabled, "
+ "ignoring c= onnection attempt from old client (%s)",
+ peer);
= gc_free(&gc);
return false;=
}
@@ -138,14 +136,13 @@
else if (verdict =3D=3D VERDICT_VALID_RESET_V2)
<= span> {

/* Calculate the session ID HMAC for o= ur reply and create reset packet */
- struct session_id sid =3D calculate_session_id_hmac(s= tate->peer_session_id,
- from, hmac, h= andwindow, 0);
+ = struct session_id sid =3D
+ calculate_session_id_hmac(state->peer_session_id, f= rom, hmac, handwindow, 0);

send_= hmac_reset_packet(m, state, tas, &sid, false);
=
/* We have a reply do not create a new session */=
return false;
-
}
else if (verdict = =3D=3D VERDICT_VALID_CONTROL_V1 || verdict =3D=3D VERDICT_VALID_ACK_V1
|| verdict =3D=3D VERDICT_VALID_WKC_V1)@@ -157,7 +154,7 @@
bool ret =3D check_sess= ion_id_hmac(state, from, hmac, handwindow);

const char *peer =3D print_link_socket_actual(&m->top.c2= .from, &gc);

- = uint8_t pkt_firstbyte =3D *BPTR( &m->top.c2.buf);
+ uint8_t pkt_firstbyte =3D *= BPTR(&m->top.c2.buf);

int op =3D pkt_firstb= yte >> P_OPCODE_SHIFT;

if = (!ret)
@@ -167,8 +164,10 @@
}
else
{
- msg(D_MULTI_DEBUG, "Valid = packet (%s) with HMAC challenge from peer (%s), "
- "accepting new connec= tion.", packet_opcode_name(op), peer);
+ msg(D_MULTI_DEBUG,
+ "Valid packet (%s) = with HMAC challenge from peer (%s), "
+ "accepting new connection."= ;,
+ p= acket_opcode_name(op), peer);
}
= gc_free(&gc);

@@ -186,18 +185,= 16 @@
*/

struct multi_= instance *
-multi_get_c= reate_instance_udp(struct multi_context *m, bool *floated,
- struct l= ink_socket *sock)
+mu= lti_get_create_instance_udp(struct multi_context *m, bool *floated, struct = link_socket *sock)
{
struct gc_arena = gc =3D gc_new();
- s= truct mroute_addr real =3D {0};
+ struct mroute_addr real =3D { 0 };
str= uct multi_instance *mi =3D NULL;
struct hash *hash =3D= m->hash;
real.proto =3D sock->info.proto;
m->hmac_reply_ls =3D sock;

<= span style=3D"color: hsl(0, 100%, 40%);">- if (mroute_extract_openvpn_so= ckaddr(&real, &m->top.c2.from.dest, true)

- && m->top.c2.buf.len >= ; 0)
+ if (mroute_= extract_openvpn_sockaddr(&real, &m->top.c2.from.dest, true) &= ;& m->top.c2.buf.len > 0)
{
= struct hash_element *he;
const uint32_t h= v =3D hash_value(hash, &real);
@@ -217,14 +214,16 @@
{
/* Floating o= n TCP will never be possible, so ensure we only process
= * UDP clients */
- if (m->instances[peer_id]->context.c2.link_= sockets[0]->info.proto =3D=3D sock->info.proto)
+ if (m->instances[peer_= id]->context.c2.link_sockets[0]->info.proto
+ =3D=3D sock->info.prot= o)
{
= mi =3D m->instances[peer_id];
*floa= ted =3D !link_socket_actual_match(&mi->context.c2.from, &m->t= op.c2.from);

if (*fl= oated)
{
- /* reset prefix, since here= we are not sure peer is the one it claims to be */
+ /* reset prefix, = since here we are not sure peer is the one it claims to be
+ */ ungenerate_prefix(mi);
= msg(D_MULTI_MEDIUM, "Float requested for peer %&= quot; PRIu32 " to %s", peer_id,
= mroute_addr_print(&real, &gc));
@@ -237= ,19 +236,20 @@
he =3D hash_lookup_fast(hash, b= ucket, &real, hv);
if (he)
{

- = mi =3D (struct multi_instance *) he->value;
+ mi =3D (struct multi_i= nstance *)he->value;
}
= }

/* we have no existing mu= lti instance for this connection */
if (!mi)
{
-= struct tls_pre_decrypt_state state =3D {0};
+ struct tls_pre_decrypt_stat= e state =3D { 0 };
if (m->deferred_shutdown= _signal.signal_received)
{
= msg(D_MULTI_ERRORS,
&quo= t;MULTI: Connection attempt from %s ignored while server is "- "shut= ting down", mroute_addr_print(&real, &gc));
+ "shutting dow= n",
+ = mroute_addr_print(&real, &gc));
= }
else if (do_pre_decrypt_check(m, &sta= te, real))
{
@@ -277,7 +277,8 = @@
&& session_id_defin= ed((&state.peer_session_id)))
= {
mi->context.c2.tls_multi-= >n_sessions++;
- = struct tls_session *session =3D &mi->context= .c2.tls_multi->session[TM_INITIAL];
+ struct tls_session *session = =3D
+ = &mi->context.c2.tls_multi->session[TM_INITIAL];
session_skip_to_pre_start(sessi= on, &state, &m->top.c2.from);
= }
}
@@ -297,9 += 298,7 @@
{
const char= *status =3D mi ? "[ok]" : "[failed]";
=
- dmsg(D_M= ULTI_DEBUG, "GET INST BY REAL: %s %s",
- mroute_addr_print(&real, &a= mp;gc),
- = status);
+ = dmsg(D_MULTI_DEBUG, "GET INST BY REAL: %s %s", mroute_addr_pr= int(&real, &gc), status);
}
#endif

}
@@ -339,8 +338,8 @@=
{
const unsigned int status =3D m->multi= _io->udp_flags;
const unsigned int mpp_flags =3D m-= >top.c2.fast_io
- = ? (MPP_CONDITIONAL_PRE_SELECT | MPP_CLOSE_O= N_SIGNAL)
- = : (MPP_PRE_SELECT | MPP_CLOSE_ON_SIGNAL);
= + = ? (MPP_CONDITIONAL_PRE_SELECT | MPP_CLOSE_ON_SIGNAL)
+ = : (MPP_PRE_SELECT | MPP_CLOSE_ON_SIGNAL);

#ifdef MULTI_DEBUG_EVENT_LOOP
char buf[16];
@@ -369,7 +368,7 @@
#endif /* ifdef MULTI_DE= BUG_EVENT_LOOP */

#ifdef ENABLE_MANAGEME= NT
- if (status &= ; (MANAGEMENT_READ|MANAGEMENT_WRITE))
+ if (status & (MANAGEMENT_READ | MANAGEMENT_WRITE)= )
{
ASSERT(management);
management_io(management);
diff --git a= /src/openvpn/multi.c b/src/openvpn/multi.c
index a306b12..8= b352e9 100644
--- a/src/openvpn/multi.c
+++= b/src/openvpn/multi.c
@@ -91,9 +91,7 @@
}=

static bool
-learn_address_script(const struct multi_context *= m,
- = const struct multi_instance *mi,
- const char *op,
+learn_address_script(const struct multi_conte= xt *m, const struct multi_instance *mi, const char *op,
= const struct mroute_addr *addr)
{
struct gc_arena gc =3D gc_new();
@@ -124,14= +122,13 @@
if (plugin_defined(plugins, OPENVPN_PLUGIN= _LEARN_ADDRESS))
{
struct arg= v argv =3D argv_new();
= - argv_printf(&argv, "%s %s",
- op,
- mroute_addr_print(addr,= &gc));
+ = argv_printf(&argv, "%s %s", op, mroute_addr_print(addr, &= gc));
if (mi)
{ argv_printf_cat(&argv, "%s", tls_common_n= ame(mi->context.c2.tls_multi, false));
}=
- if (plugin_call(plug= ins, OPENVPN_PLUGIN_LEARN_ADDRESS, &argv, NULL, es) !=3D OPENVPN_PLUGIN= _FUNC_SUCCESS)
+ = if (plugin_call(plugins, OPENVPN_PLUGIN_LEARN_ADDRESS, &argv, NULL, = es)
+ !=3D= OPENVPN_PLUGIN_FUNC_SUCCESS)
{
= msg(M_WARN, "WARNING: learn-address plugin call failed"= ;);
ret =3D false;
@@ -164,8 += 161,7 @@
multi_ifconfig_pool_persist(struct multi_context = *m, bool force)
{
/* write pool data = to file */
- if (m-&= gt;ifconfig_pool
- = && m->top.c1.ifconfig_pool_persist
+ if (m->ifconfig_pool && m->t= op.c1.ifconfig_pool_persist
&& (force || i= fconfig_pool_write_trigger(m->top.c1.ifconfig_pool_persist)))
= {
ifconfig_pool_write(m->top.c1.ifco= nfig_pool_persist, m->ifconfig_pool);
@@ -173,9 +169,7 @= @
}

static void<= br>-multi_reap_range(const struct= multi_context *m,
- = int start_bucket,
- int end_bucket)
+multi_reap_range(const struct multi_context *m, int = start_bucket, int end_bucket)
{
struc= t gc_arena gc =3D gc_new();
struct hash_iterator hi;
@@ -191,11 +185,10 @@
hash_iterator_ini= t_range(m->vhash, &hi, start_bucket, end_bucket);
= while ((he =3D hash_iterator_next(&hi)) !=3D NULL)
= {
- struct m= ulti_route *r =3D (struct multi_route *) he->value;
+ struct multi_route *r =3D (struc= t multi_route *)he->value;
if (!multi_route_def= ined(m, r))
{
- dmsg(D_MULTI_DEBUG, "MULTI: REAP DEL %s&q= uot;,
- = mroute_addr_print(&r->addr, &gc));
+ dmsg(D_MULTI_DEBUG, "MULTI: REA= P DEL %s", mroute_addr_print(&r->addr, &gc));
learn_address_script(m, NULL, "delete", &r-&g= t;addr);

multi_route_del(r);
= hash_iterator_delete_element(&hi);
@@ -256,= 7 +249,7 @@
cid_hash_function(const void *key, uint32_t iv= )
{
const unsigned long *k =3D (const= unsigned long *)key;
-= return (uint32_t) *k;
+ return (uint32_t)*k;
}
<= br> static bool
@@ -295,8 +288,7 @@
= struct multi_context *m =3D t->multi;
int dev = =3D DEV_TYPE_UNDEF;

- msg(D_MULTI_LOW, "MULTI: multi_init called, r=3D%d= v=3D%d",
- = t->options.real_hash_size,
+ msg(D_MULTI_LOW, "MULTI: multi_init called, r=3D%d v=3D= %d", t->options.real_hash_size,
t->opti= ons.virtual_hash_size);

/*@@ -315,18 +307,14 @@
* to determine which cli= ent sent an incoming packet
* which is seen on the TC= P/UDP socket.
*/
- m->hash =3D hash_init(t->options.real_hash_size,=
- = get_random(),
- = mroute_addr_hash_function,
+ m->hash =3D hash_init(t->options.real_h= ash_size, get_random(), mroute_addr_hash_function,
= mroute_addr_compare_function);
/*
* Virtual address hash table. Used to= determine
* which client to route a packet to.
*/
- = m->vhash =3D hash_init(t->options.virtual_hash_size,
- get_random(= ),

- = mroute_addr_hash_function,
+ m->vhash =3D hash_init(t->options.virtual_hash_size,= get_random(), mroute_addr_hash_function,
= mroute_addr_compare_function);

= /*
@@ -334,16 +322,10 @@
* bucket= size of one so that it can be used
* for fast iterat= ion through the list.
*/
- m->iter =3D hash_init(1,
- get_random(),
- = mroute_addr_hash_function,
- mroute_addr_compare_function);
+ m->iter =3D hash_init(1, get= _random(), mroute_addr_hash_function, mroute_addr_compare_function);
=

#ifdef ENABLE_MANAGEMENT
- m->cid_hash =3D hash_init(t->opti= ons.real_hash_size,
- = 0,
- cid_hash_function,
- cid_compare_fun= ction);
+ m->ci= d_hash =3D hash_init(t->options.real_hash_size, 0, cid_hash_function, ci= d_compare_function);
#endif

#ifdef ENABLE_ASYNC_PUSH

@@ -351,10 +333,8 @@ * Mapping between inotify watch descriptors and
* multi_instances.

*/
- m->inotify_watchers =3D hash_init(t-= >options.real_hash_size,
- get_random(),
- int_h= ash_function,
- = int_compare_function);
+ m->inotify_watchers =3D
+ hash_init(t->options.r= eal_hash_size, get_random(), int_hash_function, int_compare_function);
#endif

/*
@@ -367,10 +347,9 @@

* Limit frequency of incoming= connections to control
* DoS.
= */
- m->new_conne= ction_limiter =3D frequency_limit_init(t->options.cf_max,
- = t->options.cf_per);

- m->initial_rate_limiter =3D initial_rate_limit_ini= t(t->options.cf_initial_max,
- t->optio= ns.cf_initial_per);
+= m->new_connection_limiter =3D frequency_limit_init(t->options.cf_= max, t->options.cf_per);
+ m->initial_rate_limiter =3D
+ initial_rate_limit_init(t->options.cf_ini= tial_max, t->options.cf_initial_per);

= /*
* Allocate broadcast/multicast buffer list
@@ -387,8 +366,7 @@
* differently based= on whether a tun or tap style
* tunnel.
*/

- if (t= ->options.ifconfig_pool_defined
- || t->options.ifconfig_ipv6_pool_defined)+ if (t->options.ifconfi= g_pool_defined || t->options.ifconfig_ipv6_pool_defined)
{

int pool_type =3D IFCONFIG_POOL_INDIV;

@@ -397,14 +375,11 @@
= pool_type =3D IFCONFIG_POOL_30NET;
}=

- m-= >ifconfig_pool =3D ifconfig_pool_init(t->options.ifconfig_pool_define= d,
- = pool_type,
- t->options= .ifconfig_pool_start,
-= t->options.ifconfig_pool_e= nd,
- = t->options.duplicate_cn,
- = t->options.ifconfig_ipv6_pool_defined,
- t-&g= t;options.ifconfig_ipv6_pool_base,
- t->options.if= config_ipv6_pool_netbits );
+ m->ifconfig_pool =3D ifconfig_pool_init(
+ t->options.ifconfig_= pool_defined, pool_type, t->options.ifconfig_pool_start,

+ t->options.ifconfig_= pool_end, t->options.duplicate_cn,

+ t->options.ifconfig_ipv6_pool_defined, t-&= gt;options.ifconfig_ipv6_pool_base,
+ t->options.ifconfig_ipv6_pool_netbits);

/* reload pool data from file */
if (t->c1.ifconfig_pool_persist)
@= @ -454,7 +429,8 @@
/* initialize stale routes check ti= mer */
if (t->options.stale_routes_check_interval &= gt; 0)
{
- msg(M_INFO, "Initializing stale route check timer to r= un every %i seconds and to removing routes with activity timeout older than= %i seconds",
+ = msg(M_INFO,
+ = "Initializing stale route check timer to run every %i secon= ds and to removing routes with activity timeout older than %i seconds"= ,
t->options.stale_routes_check_interval, t= ->options.stale_routes_ageing_time);
event_time= out_init(&m->stale_routes_check_et, t->options.stale_routes_check= _interval, 0);
}
@@ -475,8 +451,7 @@
buf_printf(&out, "%s/", cn);
}
buf_printf(&out, "= %s", mroute_addr_print(&mi->real, gc));
- if (mi->context.c2.tls_multi
- && ch= eck_debug_level(D_DCO_DEBUG)
+ if (mi->context.c2.tls_multi && check_debug_lev= el(D_DCO_DEBUG)
&& dco_enabled(&mi= ->context.options))
{
= buf_printf(&out, " peer-id=3D%d", mi->context.c2.tls_m= ulti->peer_id);
@@ -523,8 +498,7 @@
* = CIDR netlengths.
*/
static void-multi_del_iroutes(struct multi= _context *m,
- = struct multi_instance *mi)
+multi_del_iroutes(struct multi_context *m, struct multi_ins= tance *mi)
{
const struct iroute *ir;=
const struct iroute_ipv6 *ir6;
@@ -58= 0,7 +554,9 @@

if (plugin_defined(mi-= >context.plugins, OPENVPN_PLUGIN_CLIENT_DISCONNECT))
= {
- if (plugin= _call(mi->context.plugins, OPENVPN_PLUGIN_CLIENT_DISCONNECT, NULL, NULL,= mi->context.c2.es) !=3D OPENVPN_PLUGIN_FUNC_SUCCESS)
+ if (plugin_call(mi->context= .plugins, OPENVPN_PLUGIN_CLIENT_DISCONNECT, NULL, NULL,
+ mi->context.= c2.es)
+ != =3D OPENVPN_PLUGIN_FUNC_SUCCESS)
{
msg(M_WARN, "WARNING: client-disconnect plugin call fail= ed");

}
@@ -603,9 +579,7 @@
}

void
-multi_close_instance(struct multi_conte= xt *m,
- = struct multi_instance *mi,
- bool shutdown)
+multi_close_instance(struct multi_context *m, st= ruct multi_instance *mi, bool shutdown)
{
= perf_push(PERF_MULTI_CLOSE_INSTANCE);

@@ -650,7 +624,7 @@

#ifdef ENABLE_ASYNC_PUSH
<= span> if (mi->inotify_watch !=3D -1)

{<= /span>
- hash_remov= e(m->inotify_watchers, (void *) (unsigned long)mi->inotify_watch);
+ hash_remov= e(m->inotify_watchers, (void *)(unsigned long)mi->inotify_watch);
mi->inotify_watch =3D -1;
= }
#endif
@@ -660,7 +634,7 @@ m->instances[mi->context.c2.tls_multi->peer_i= d] =3D NULL;
}

- schedule_remove_entry(m->sch= edule, (struct schedule_entry *) mi);
+ schedule_remove_entry(m->schedule, (struct sch= edule_entry *)mi);

ifconfig_pool= _release(m->ifconfig_pool, mi->vaddr_handle, false);
=
@@ -717,7 +691,7 @@
hash_iterato= r_init(m->iter, &hi);
while ((he =3D hash_i= terator_next(&hi)))
{
- struct multi_instance *mi =3D (str= uct multi_instance *) he->value;
+ struct multi_instance *mi =3D (struct multi_ins= tance *)he->value;
mi->did_iter =3D fals= e;
multi_close_instance(m, mi, true); }
@@ -789,7 +763,9 @@

if (hash_n_elements(m->hash) >=3D m->max_client= s)
{
- msg(D_MULTI_ERRORS, "MULTI: new incoming connection would = exceed maximum number of clients (%d)", m->max_clients);
= + msg(D_MULTI_ERRORS,
+ "MULT= I: new incoming connection would exceed maximum number of clients (%d)"= ;,
+ m->= ;max_clients);
goto err;
}

@@ -879,7 +855,7 @@
= while ((he =3D hash_iterator_next(&hi)))
= {
struct gc_arena gc =3D gc_new();
- const st= ruct multi_instance *mi =3D (struct multi_instance *) he->value;<= br>+ const struc= t multi_instance *mi =3D (struct multi_instance *)he->value;
<= span>

if (!mi->halt)
= {
@@ -900,21 +876,19 @@
= while ((he =3D hash_iterator_next(&hi)))
= {
struct gc_arena gc =3D gc_new()= ;
- cons= t struct multi_route *route =3D (struct multi_route *) he->value;=
+ const stru= ct multi_route *route =3D (struct multi_route *)he->value;

if (multi_route_defined(m, route))
{
const= struct multi_instance *mi =3D route->instance;
= const struct mroute_addr *ma =3D &route->addr;- char flags= [2] =3D {0, 0};
+ = char flags[2] =3D { 0, 0 };

if (route->flags & MULTI_ROUTE_CACHE)
=
{
f= lags[0] =3D 'C';
}
<= span style=3D"color: hsl(0, 100%, 40%);">- status_printf= (so, "%s%s,%s,%s,%s",

- mroute_addr_print(ma, &gc),=
- = flags,
+= status_printf(so, "%s%s,%s,%s,%s", mroute_add= r_print(ma, &gc), flags,
= tls_common_name(mi->context.c2.tls_multi, false),
= mroute_addr_print(&mi->real, &= gc),
time_string(route-&= gt;last_reference, 0, false, &gc));
@@ -926,8 +900,7 @@=
status_printf(so, "GLOBAL STATS");<= /span>
if (m->mbuf)
{=
- statu= s_printf(so, "Max bcast/mcast queue length,%d",
- mbuf_maxi= mum_queued(m->mbuf));
+ status_printf(so, "Max bcast/mcast queue length,%= d", mbuf_maximum_queued(m->mbuf));
}

status_printf(so, "END&q= uot;);
@@ -940,69 +913,77 @@
= * Status file version 2 and 3
*/
status_printf(so, "TITLE%c%s", sep, title_string= );

- status_= printf(so, "TIME%c%s%c%u", sep, time_string(now, 0, false, &g= c_top), sep, (unsigned int)now);
- status_printf(so, "HEADER%cCLIENT_LIST%cCommon = Name%cReal Address%cVirtual Address%cVirtual IPv6 Address%cBytes Received%c= Bytes Sent%cConnected Since%cConnected Since (time_t)%cUsername%cClient ID%= cPeer ID%cData Channel Cipher",
- sep, sep, sep, sep, sep, sep, sep,= sep, sep, sep, sep, sep, sep);
+ status_printf(so, "TIME%c%s%c%u", sep, ti= me_string(now, 0, false, &gc_top), sep,
+ (unsigned int)now);
+ status_printf= (
+ so= ,
+ &q= uot;HEADER%cCLIENT_LIST%cCommon Name%cReal Address%cVirtual Address%cVirtua= l IPv6 Address%cBytes Received%cBytes Sent%cConnected Since%cConnected Sinc= e (time_t)%cUsername%cClient ID%cPeer ID%cData Channel Cipher",=
+ sep, sep, = sep, sep, sep, sep, sep, sep, sep, sep, sep, sep, sep);
= hash_iterator_init(m->hash, &hi);
= while ((he =3D hash_iterator_next(&hi)))
= {
struct gc_arena gc =3D gc_new();
- const str= uct multi_instance *mi =3D (struct multi_instance *) he->value;+ const struct= multi_instance *mi =3D (struct multi_instance *)he->value;

if (!mi->halt)
= {
- = status_printf(so, "CLIENT_LIST%c%s%c%s%c%s%c%s%c" = counter_format "%c" counter_format "%c%s%c%u%c%s%c"
+ sta= tus_printf(
+ = so,
+= "CLIENT_LIST%c%s%c%s%c%s%c%s%c" counter_f= ormat "%c" counter_format
+ "%c%s%c%u%c%s%c" #ifdef ENABLE_MANAGEMENT
- "%lu"
+ "%lu= "

#else
- ""
+ ""
#endif
- = "%c%" PRIu32 "%c%s",
- = sep, tls_common_name(mi->context.c2.tls_multi, false),=
- = sep, mroute_addr_print(&mi->real, &gc),
- sep, p= rint_in_addr_t(mi->reporting_addr, IA_EMPTY_IF_UNDEF, &gc),- = sep, print_in6_addr(mi->reporting_addr_ipv6, IA_EMPTY_IF_UNDEF, &= ;gc),
- = sep, mi->context.c2.link_read_bytes + mi->context.c= 2.dco_read_bytes,
- = sep, mi->context.c2.link_write_bytes + mi-= >context.c2.dco_write_bytes,
- sep, time_string(mi->created= , 0, false, &gc),
-= sep, (unsigned int)mi->created,=
- = sep, tls_username(mi->context.c2.tls_multi, false),
+ "%c%&= quot; PRIu32 "%c%s",

+ sep, tls_common_name(mi->context.c2.t= ls_multi, false), sep,
+ = print_in_addr_t(mi->reporting_addr, IA_EMPTY_IF_UNDEF, &gc), = sep,
+ = print_in6_addr(mi->reporting_addr_ipv6, IA_EMPTY_IF_UNDEF, &= ;gc), sep,
+ = mi->context.c2.link_read_bytes + mi->context.c2.dco_re= ad_bytes, sep,
+ = mi->context.c2.link_write_bytes + mi->context.c2.d= co_write_bytes, sep,
= + time_string(mi->created, 0, false, &gc), se= p, (unsigned int)mi->created,
+ sep, tls_username(mi->context.c2.tl= s_multi, false),
#ifdef ENABLE_MANAGEMENT
- sep,= mi->context.c2.mda_context.cid,
+ sep, mi->context.c2.mda_context.= cid,
#else
- sep,
+ sep,
#end= if
- = sep, mi->context.c2.tls_multi ? mi->context.c2.tls_mul= ti->peer_id : UINT32_MAX,
- sep, translate_cipher_name_to_open= vpn(mi->context.options.ciphername));
+ sep,
+ mi->context.c2.tls= _multi ? mi->context.c2.tls_multi->peer_id : UINT32_MAX,
+ sep, tra= nslate_cipher_name_to_openvpn(mi->context.options.ciphername));
}
gc_free(&gc= );
}
hash_iterato= r_free(&hi);

- status_printf(so, "HEADER%cROUTING_TABLE%cVir= tual Address%cCommon Name%cReal Address%cLast Ref%cLast Ref (time_t)",=
- = sep, sep, sep, sep, sep, sep);
+ status_printf(
+ so,
+ "HEADER%cROUTING_TABLE%cVirtual= Address%cCommon Name%cReal Address%cLast Ref%cLast Ref (time_t)",
+ sep, se= p, sep, sep, sep, sep);
hash_iterator_init(m-&= gt;vhash, &hi);
while ((he =3D hash_iterat= or_next(&hi)))
{
= struct gc_arena gc =3D gc_new();
- const struct multi_route *route =3D (str= uct multi_route *) he->value;
+ const struct multi_route *route =3D (struct mu= lti_route *)he->value;

= if (multi_route_defined(m, route))
{
const struct multi_instance *mi =3D route= ->instance;
const struct mroute_add= r *ma =3D &route->addr;
- char flags[2] =3D {0, 0};
+ char flags[2] =3D { = 0, 0 };

if (route-&g= t;flags & MULTI_ROUTE_CACHE)
{
flags[0] =3D 'C';
<= span> }

- status_printf(so, "ROUTING_TABLE%c%s%s%c%s%c= %s%c%s%c%u",
- = sep, mroute_addr_print(ma, &gc), flags,
- = sep, tls_common_name(mi->context.c2.tls_multi, false),=
- = sep, mroute_addr_print(&mi->real, &gc),
- sep, t= ime_string(route->last_reference, 0, false, &gc),
- sep, (= unsigned int)route->last_reference);
+ status_printf(so, "ROUTING_TAB= LE%c%s%s%c%s%c%s%c%s%c%u", sep,
+ mroute_addr_print(ma, &a= mp;gc), flags, sep,
+= tls_common_name(mi->context.c2.tls_mul= ti, false), sep,
+ = mroute_addr_print(&mi->real, &gc)= , sep,
+ = time_string(route->last_reference, 0, false, &g= c), sep,
+ = (unsigned int)route->last_reference);
<= span> }

gc_free(&gc);<= /span>
}
@@ -1010,11 +991,12 @@

if (m->mbuf)
= {
- = status_printf(so, "GLOBAL_STATS%cMax bcast/mcast queue length%= c%d",
- = sep, sep, mbuf_maximum_queued(m->mbuf));
+ status_printf(so= , "GLOBAL_STATS%cMax bcast/mcast queue length%c%d", sep, sep,
+ = mbuf_maximum_queued(m->mbuf));
}

- = status_printf(so, "GLOBAL_STATS%cdco_enabled%c%d", sep, sep,= dco_enabled(&m->top.options));
+ status_printf(so, "GLOBAL_STATS%cdco_en= abled%c%d", sep, sep,
+ dco_enabled(&m->top.options));
status_printf(so, "END");
}

else
@@ -1024,19 +100= 6,22 @@

#ifdef PACKET_TRUNCATION_CHECK
{
- status_printf(so, "HEADER,ERRORS,Common Name,TUN Read = Trunc,TUN Write Trunc,Pre-encrypt Trunc,Post-decrypt Trunc");+ status_printf(
+ so,
+ "= ;HEADER,ERRORS,Common Name,TUN Read Trunc,TUN Write Trunc,Pre-encrypt Trunc= ,Post-decrypt Trunc");
hash_iterator_init= (m->hash, &hi);
while ((he =3D hash_ite= rator_next(&hi)))
{
= struct gc_arena gc =3D gc_new();
- const struct multi_instance *mi =3D (= struct multi_instance *) he->value;
+ const struct multi_instance *mi =3D (str= uct multi_instance *)he->value;

= if (!mi->halt)
{
<= span style=3D"color: hsl(0, 100%, 40%);">- status_printf= (so, "ERRORS,%s," counter_format "," counter_format &qu= ot;," counter_format "," counter_format,

+ status_printf(so,
+ = "ERRORS,%s," counter_format "," counter_fo= rmat "," counter_format
+ "," counter_forma= t,
tls_common_name(mi-&g= t;context.c2.tls_multi, false),
- m->top.c2.n_trunc_tun_read,<= /span>
- = mi->context.c2.n_trunc_tun_write,
+ m->top.c2= .n_trunc_tun_read, mi->context.c2.n_trunc_tun_write,
= mi->context.c2.n_trunc_pre_encrypt,
mi->context.c2.n_trunc_po= st_decrypt);
}
@@ -1067,9 = +1052,7 @@
* or NULL if none.
*/=
static struct multi_instance *
-multi_learn_addr(struct multi_context *m,
- struct multi_insta= nce *mi,

- = const struct mroute_addr *addr,
+multi_learn_addr(struct multi_context *m, struct multi_inst= ance *mi, const struct mroute_addr *addr,
= const unsigned int flags)
{
struct h= ash_element *he;
@@ -1083,7 +1066,7 @@
= he =3D hash_lookup_fast(m->vhash, bucket, addr, hv);
= if (he)
{
- oldroute =3D (struct multi_route *) he->value;
+ oldroute =3D (str= uct multi_route *)he->value;
}
= if (oldroute && multi_route_defined(m, oldroute))
= {
@@ -1141,10 +1124,8 @@
= }
}

- msg(D_MULTI_LOW, "MULTI: Learn%s: %s = -> %s",
- = learn_succeeded ? "" : " FAILED",
- mroute_addr_print(&ne= wroute->addr, &gc),

- multi_instance_string(mi, false, &gc));
+ msg(D_MULTI_LOW, "MUL= TI: Learn%s: %s -> %s", learn_succeeded ? "" : " FAI= LED",

+ = mroute_addr_print(&newroute->addr, &gc), multi_instance_strin= g(mi, false, &gc));

if (!lea= rn_succeeded)
{
@@ -1160,8 +1141,7= @@
* Get client instance based on virtual address.
*/
static struct multi_instance *
<= span style=3D"color: hsl(0, 100%, 40%);">-multi_get_instance_by_virtual_add= r(struct multi_context *m,

- const struct mroute_addr *addr,
+multi_get_instance_by_v= irtual_addr(struct multi_context *m, const struct mroute_addr *addr,=
bool cidr_routing)
= {
struct multi_route *route;
@@= -1173,7 +1153,7 @@
return NULL;
= }

- route =3D (struct multi_route *) hash_lookup(m->vhash, addr);
+ route =3D (struct mu= lti_route *)hash_lookup(m->vhash, addr);

/* does host route (possible cached) exist? */

= if (route && multi_route_defined(m, route))
@@ -11= 97,13 +1177,13 @@
mroute_addr_mask_host_bits(&= amp;tryaddr);

/* look up a p= ossible route with netbits netmask */
- route =3D (struct multi_route *) hash_lookup(m-= >vhash, &tryaddr);
+ route =3D (struct multi_route *)hash_lookup(m->vhash, = &tryaddr);

if (route &am= p;& multi_route_defined(m, route))
{
/* found an applicable route, cache host route = */
struct multi_instance *mi =3D route->= ;instance;
- = multi_learn_addr(m, mi, addr, MULTI_ROUTE_CACHE|MULTI_ROUTE_AGEABLE);<= /span>
+ mult= i_learn_addr(m, mi, addr, MULTI_ROUTE_CACHE | MULTI_ROUTE_AGEABLE);<= br> ret =3D mi;
brea= k;
}
@@ -1217,15 +1197,12 @@
const char *addr_text =3D mroute_addr_print(addr, &= amp;gc);
if (ret)
{
- dmsg(D_MULTI_DE= BUG, "GET INST BY VIRT: %s -> %s via %s",
- addr_text,
- multi_instance_stri= ng(ret, false, &gc),

+ dmsg(D_MULTI_= DEBUG, "GET INST BY VIRT: %s -> %s via %s", addr_text,<= br>+ multi_inst= ance_string(ret, false, &gc), mroute_addr_print(&route->addr, &a= mp;gc));
}
else {
- = dmsg(D_MULTI_DEBUG, "GET INST BY VIRT: %s [failed]",
- addr_text= );
+ dmsg(= D_MULTI_DEBUG, "GET INST BY VIRT: %s [failed]", addr_text);
}
gc_free(&gc);
= }
@@ -1239,14 +1216,12 @@
* He= lper function to multi_learn_addr().
*/
= static struct multi_instance *
-multi_learn_in_addr_t(struct multi_context *m,
- struct multi_instan= ce *mi,
- = in_addr_t a,
- = int netbits, /* -1 if host route, otherwise # of netw= ork bits in address */
+ = int netbits, /* -1 if host route, otherwise # of network b= its in address */
bool primary)
{
struct openvpn_sockaddr remote_si;
- struct mroute_addr add= r =3D {0};
+ struc= t mroute_addr addr =3D { 0 };

CLEAR(= remote_si);
remote_si.addr.in4.sin_family =3D AF_INET;=
@@ -1257,7 +1232,7 @@
if (netbits >= ;=3D 0)
{
addr.type |=3D MR_W= ITH_NETBITS;
- a= ddr.netbits =3D (uint8_t) netbits;
+ addr.netbits =3D (uint8_t)netbits;
= }

struct multi_instance *owner = =3D multi_learn_addr(m, mi, &addr, 0);
@@ -1272,7 +1247= ,7 @@
/* "primary" is the VPN ifconfig a= ddress of the peer and already
* known to DCO, so= only install "extra" iroutes (primary =3D false)
*/

- = ASSERT(netbits >=3D 0); /* DCO requires populated netbits */
+ ASSERT(netbit= s >=3D 0); /* DCO requires populated netbits */
= dco_install_iroute(m, mi, &addr);
}

@@ -1280,13 +1255,11 @@
}
<= span>

static struct multi_instance *
-multi_learn_in6_addr(struct multi_context = *m,
- = struct multi_instance *mi,
- struct in6_addr a6,
- int netbits, /* -1 if hos= t route, otherwise # of network bits in address */
+multi_learn_in6_addr(struct multi_context *m= , struct multi_instance *mi, struct in6_addr a6,
+ int netbits, /* -1 if hos= t route, otherwise # of network bits in address */
= bool primary)
{
- struct mroute_addr addr =3D {0};
+ struct mroute_addr addr =3D {= 0 };


addr.len =3D 16;
addr.type =3D MR_ADDR_IPV6;

@@ -1296,8 +1269,8 @@
if (netbits >=3D 0)
{ addr.type |=3D MR_WITH_NETBITS;
- addr.netbits =3D (uint8_t) netbits;
- mroute_addr_mask_ho= st_bits( &addr );
+ addr.netbits =3D (uint8_t)netbits;
+ mroute_addr_mask_host_bits(&addr);
}

struct multi_ins= tance *owner =3D multi_learn_addr(m, mi, &addr, 0);
@@ = -1312,7 +1285,7 @@
/* "primary" is the V= PN ifconfig address of the peer and already
* kno= wn to DCO, so only install "extra" iroutes (primary =3D false)

*/
- ASSERT(netbits >=3D 0); /* DCO requires populated= netbits */
+ = ASSERT(netbits >=3D 0); /* DCO requires populated netbits */
<= span> dco_install_iroute(m, mi, &addr);

}<= /span>

@@ -1324,8 +1297,7 @@
*= to internal routing table.
*/
static vo= id
-multi_add_iroutes(s= truct multi_context *m,
- struct multi_instance *mi)
+multi_add_iroutes(struct multi_context *m, struc= t multi_instance *mi)
{
struct gc_are= na gc =3D gc_new();
const struct iroute *ir;@@ -1338,15 +1310,13 @@
if (ir->netb= its >=3D 0)
{
= msg(D_MULTI_LOW, "MULTI: internal route %s/%d -> %s",
- print_= in_addr_t(ir->network, 0, &gc),
- ir->netbits,
+ print_in_addr_t(ir-&g= t;network, 0, &gc), ir->netbits,
= multi_instance_string(mi, false, &gc));
= }
else
{ msg(D_MULTI_LOW, "MULTI: internal route %s -&= gt; %s",
- = print_in_addr_t(ir->network, 0, &gc),
- multi_instance_strin= g(mi, false, &gc));
+ print_in_addr_t(ir->network, 0, &gc), multi_= instance_string(mi, false, &gc));
}=

mroute_helper_add_iroute46(m->r= oute_helper, ir->netbits);
@@ -1356,8 +1326,7 @@<= br> for (ir6 =3D mi->context.options.iroutes_ipv6; ir6 != =3D NULL; ir6 =3D ir6->next)
{
= msg(D_MULTI_LOW, "MULTI: internal route %s/%d -> %s&qu= ot;,
- p= rint_in6_addr(ir6->network, 0, &gc),
- ir6->netbits,
+ print_in6_addr(ir6->n= etwork, 0, &gc), ir6->netbits,
mult= i_instance_string(mi, false, &gc));

= mroute_helper_add_iroute46(m->route_helper, ir6->netbits)= ;
@@ -1387,7 +1356,7 @@
hash_i= terator_init(m->iter, &hi);
while ((he = =3D hash_iterator_next(&hi)))
{
= - struct multi_ins= tance *mi =3D (struct multi_instance *) he->value;
+ struct multi_instance *mi= =3D (struct multi_instance *)he->value;
= if (mi !=3D new_mi && !mi->halt)
= {
const char *cn =3D tls_common_na= me(mi->context.c2.tls_multi, true);
@@ -1404,7 +1373,9 @= @

if (count)
{

- = msg(D_MULTI_LOW, "MULTI: new connection by client '%s= 9; will cause previous active sessions by this client to be dropped. Remem= ber to use the --duplicate-cn option if you want multiple clients using the= same certificate or username to concurrently connect.", new_cn);
+ msg(D_MU= LTI_LOW,
+ = "MULTI: new connection by client '%s' will cause prev= ious active sessions by this client to be dropped. Remember to use the --d= uplicate-cn option if you want multiple clients using the same certificate = or username to concurrently connect.",
+ new_cn);
= }
}
}
= @@ -1413,7 +1384,6 @@
static void
check_s= tale_routes(struct multi_context *m)
{
-
struct gc_arena gc = =3D gc_new();
struct hash_iterator hi;
struct hash_element *he;

@@ -1422,8 +1392,9 @@=
hash_iterator_init_range(m->vhash, &hi, 0, hash_n_buc= kets(m->vhash));
while ((he =3D hash_iterator_next(= &hi)) !=3D NULL)
{
- struct multi_route *r =3D (struct multi_route= *) he->value;
- = if (multi_route_defined(m, r) && difftime(now, r->last_refer= ence) >=3D m->top.options.stale_routes_ageing_time)
+ struct multi_route *r =3D (st= ruct multi_route *)he->value;
+ if (multi_route_defined(m, r)
+ && difftime(now, r->l= ast_reference) >=3D m->top.options.stale_routes_ageing_time) {
dmsg(D_MULTI_DEBUG, "M= ULTI: Deleting stale route for address '%s'",
= mroute_addr_print(&r->addr, &gc));
<= span>@@ -1446,7 +1417,8 @@

const struct options *o =3D= &c->options;
if (o->push_ifconfig_constrain= t_defined && c->c2.push_ifconfig_defined)
{=
- return (o->= ;push_ifconfig_constraint_netmask & c->c2.push_ifconfig_local) =3D= =3D o->push_ifconfig_constraint_network;
+ return (o->push_ifconfig_constraint_netm= ask & c->c2.push_ifconfig_local)
+ =3D=3D o->push_ifconfig_constraint_ne= twork;
}
else
= {
@@ -1480,7 +1452,8 @@

mi->context.c2.push_ifconfig_defined =3D true;

mi->context.c2.push_ifconfig_local =3D mi->context.options.= push_ifconfig_local;

- = mi->context.c2.push_ifconfig_remote_netmask =3D mi->context.op= tions.push_ifconfig_remote_netmask;
+ mi->context.c2.push_ifconfig_remote_netmask =3D<= /span>
+ mi->c= ontext.options.push_ifconfig_remote_netmask;
mi-&g= t;context.c2.push_ifconfig_local_alias =3D mi->context.options.push_ifco= nfig_local_alias;

/* the current= implementation does not allow "static IPv4, pool IPv6",@@ -1490,7 +1463,8 @@
if (mi->context.o= ptions.ifconfig_ipv6_pool_defined
&& != mi->context.options.push_ifconfig_ipv6_defined)
= {
- msg( M_= INFO, "MULTI_sva: WARNING: if --ifconfig-push is used for IPv4, automa= tic IPv6 assignment from --ifconfig-ipv6-pool does not work. Use --ifconfi= g-ipv6-push for IPv6 then." );
+ msg(M_INFO,
+ "MULTI_sva: WARNING: if --ifconfig= -push is used for IPv4, automatic IPv6 assignment from --ifconfig-ipv6-pool= does not work. Use --ifconfig-ipv6-push for IPv6 then.");
= }
}
else if (m->= ;ifconfig_pool && mi->vaddr_handle < 0) /* otherwise, choose = a pool address */
@@ -1505,30 +1479,33 @@
= }

CLEAR(remote_ipv6);
- mi->vaddr_han= dle =3D ifconfig_pool_acquire(m->ifconfig_pool, &local, &remote,= &remote_ipv6, cn);
+ mi->vaddr_handle =3D
+ ifconfig_pool_acquire(m->ifconfig_pool, &= ;local, &remote, &remote_ipv6, cn);
if (mi= ->vaddr_handle >=3D 0)
{
= const int tunnel_type =3D TUNNEL_TYPE(mi->context.c1.tuntap);<= /span>
const int tunnel_topology =3D TUNNEL_TOPOLOGY(= mi->context.c1.tuntap);

- msg( M_INFO, "MULTI_sva: pool retur= ned IPv4=3D%s, IPv6=3D%s",
- (mi->context.options.ifconfig_pool_defined
- ? prin= t_in_addr_t(remote, 0, &gc)
- : "(Not enabled)"),
- (mi->context.option= s.ifconfig_ipv6_pool_defined
- ? print_in6_addr( remote_ipv6, 0, &gc )=
- : "(N= ot enabled)") );
+ msg(M_INFO, "MULTI_sva: pool returned IPv4=3D%s, IPv6=3D= %s",
+ = (mi->context.options.ifconfig_pool_defined ? print_in_addr_t(remot= e, 0, &gc)
+ = : "(Not enabled)= "),
+ = (mi->context.options.ifconfig_ipv6_pool_defined
+ ? print_in6_addr(r= emote_ipv6, 0, &gc)
+ : "(Not enabled)"));

if (mi->context.options.ifconfig_pool_define= d)
{
/* set p= ush_ifconfig_remote_netmask from pool ifconfig address(es) */
mi->context.c2.push_ifconfig_local =3D remote;
- if (tunnel_= type =3D=3D DEV_TYPE_TAP || (tunnel_type =3D=3D DEV_TYPE_TUN && tun= nel_topology =3D=3D TOP_SUBNET))
+ if (tunnel_type =3D=3D DEV_TYPE_TAP
= + || (tunnel= _type =3D=3D DEV_TYPE_TUN && tunnel_topology =3D=3D TOP_SUBNET))
{
- mi->context.c2.push_ifconfig_remote_netma= sk =3D mi->context.options.ifconfig_pool_netmask;
+ mi->context.c2.pus= h_ifconfig_remote_netmask =3D
+ mi->context.options.ifconfig_pool_netm= ask;
if (!mi->context.c2.push_ifcon= fig_remote_netmask)
{
- mi->context= .c2.push_ifconfig_remote_netmask =3D mi->context.c1.tuntap->remote_ne= tmask;
+ = mi->context.c2.push_ifconfig_remote_netmask =3D
+ mi-&g= t;context.c1.tuntap->remote_netmask;

= }
}
els= e if (tunnel_type =3D=3D DEV_TYPE_TUN)
@@ -1558,8 +1535,7 @= @
if (mi->context.options.ifconfig_ipv6_poo= l_defined)
{
= mi->context.c2.push_ifconfig_ipv6_local =3D remote_ipv6;
- mi->context.c2.pus= h_ifconfig_ipv6_remote =3D

- mi->context.c1.tuntap->local_ipv6;+ mi->contex= t.c2.push_ifconfig_ipv6_remote =3D mi->context.c1.tuntap->local_ipv6;=
mi->context.c2.push_ifconfig_ipv6_netb= its =3D
mi->context.options.ifconfi= g_ipv6_netbits;
mi->context.c2.push_ifc= onfig_ipv6_defined =3D true;
@@ -1580,17 +1556,14 @@=
*/
if (mi->context.options.push_ifc= onfig_ipv6_defined)
{
- mi->context.c2.push_ifconfig_ipv6_local =3D=
- mi->co= ntext.options.push_ifconfig_ipv6_local;
- mi->context.c2.push_ifconfig_ipv6_remote =3D
- mi->cont= ext.options.push_ifconfig_ipv6_remote;
- mi->context.c2.push_ifconfig_ipv6_netbits =3D
- mi->cont= ext.options.push_ifconfig_ipv6_netbits;
+ mi->context.c2.push_ifconfig_ipv6_local =3D = mi->context.options.push_ifconfig_ipv6_local;
+ mi->context.c2.push_ifconfig_ipv6_r= emote =3D mi->context.options.push_ifconfig_ipv6_remote;
+ mi->context.c2.push_ifco= nfig_ipv6_netbits =3D mi->context.options.push_ifconfig_ipv6_netbits;
mi->context.c2.push_ifconfig_ipv6_defined =3D tru= e;

- = msg( M_INFO, "MULTI_sva: push_ifconfig_ipv6 %s/%d",=
- print_in6_addr(= mi->context.c2.push_ifconfig_ipv6_local, 0, &gc ),
- mi->context.c2.push_if= config_ipv6_netbits );
+ print_in6_a= ddr(mi->context.c2.push_ifconfig_ipv6_local, 0, &gc),
+ mi->context.c2.push= _ifconfig_ipv6_netbits);

}
gc_free(&gc);
@@ -1611,24 +1584,19 @@
const int tunnel_type =3D TUNNEL_TYPE(mi->context.c1= .tuntap);
const int tunnel_topology =3D TUNNEL_TOP= OLOGY(mi->context.c1.tuntap);

- setenv_in_addr_t(mi->context.c2.es,=
- = "ifconfig_pool_remote_ip",
- mi->context.c2.push_ifconfig= _local,
- = SA_SET_IF_NONZERO);
+ setenv_in_addr_t(mi->context.c2.es, "ifconfig_po= ol_remote_ip",
+= mi->context.c2.push_ifconfig_local, SA_SET_IF_N= ONZERO);

- if (tunnel_type =3D=3D DEV_TYPE_TAP || (tunnel_type =3D=3D DEV= _TYPE_TUN && tunnel_topology =3D=3D TOP_SUBNET))
+ if (tunnel_type =3D=3D DEV_TYP= E_TAP
+ ||= (tunnel_type =3D=3D DEV_TYPE_TUN && tunnel_topology =3D=3D TOP_SUB= NET))
{
- setenv_in_addr_t(mi->context.c2.es,
- "= ifconfig_pool_netmask",

- mi->context.c2.push_ifconfig_remote_= netmask,
- = SA_SET_IF_NONZERO);
+ setenv_in_addr_t(mi->context.c2.es, "if= config_pool_netmask",
+ mi->context.c2.push_ifconfig_remote_= netmask, SA_SET_IF_NONZERO);
}
= else if (tunnel_type =3D=3D DEV_TYPE_TUN)
{<= /span>
- setenv_in_= addr_t(mi->context.c2.es,
- "ifconfig_pool_local_ip",
- = mi->context.c2.push_ifconfig_remote_netmask,
- SA_SET_IF_NONZ= ERO);
+ se= tenv_in_addr_t(mi->context.c2.es, "ifconfig_pool_local_ip",
+ = mi->context.c2.push_ifconfig_remote_netmask, SA_SET_IF_NONZERO);<= /span>
}
}
<= br>@@ -1638,16 +1606,11 @@

if = (mi->context.c2.push_ifconfig_ipv6_defined)
{
- setenv_in6_addr(mi-= >context.c2.es,
- = "ifconfig_pool_remote",
- &mi->contex= t.c2.push_ifconfig_ipv6_local,
- SA_SET_IF_NONZERO);
- setenv_in6_addr(mi->context.c2.e= s,
- = "ifconfig_pool_local",
- &mi->context.c2.push_ifconfi= g_ipv6_remote,
- = SA_SET_IF_NONZERO);
- setenv_int(mi->context.c2.es,
- "ifconfig_pool_ip= 6_netbits",
+ = setenv_in6_addr(mi->context.c2.es, "ifconfig_pool_remote"= ,
+ = &mi->context.c2.push_ifconfig_ipv6_local, SA_SET_IF_NONZERO);<= /span>
+ setenv_in6_a= ddr(mi->context.c2.es, "ifconfig_pool_local",
+ &mi->= context.c2.push_ifconfig_ipv6_remote, SA_SET_IF_NONZERO);
+ setenv_int(mi->context.c2.= es, "ifconfig_pool_ip6_netbits",
= mi->context.c2.push_ifconfig_ipv6_netbits);
}
}
@@ -1656,20 +1619,14 @@
= * Called after client-connect script is called
*/=
static void
= -multi_client_connect_post(struct multi_context *m,
- struct multi_inst= ance *mi,
- = const char *dc_file,
+multi_client_connect_post(struct multi_context *m, struct mu= lti_instance *mi, const char *dc_file,
= unsigned int *option_types_found)
{
/* Did script generate a dynamic config file? */

= if (platform_test_file(dc_file))
{
- options_server_import(&mi-&g= t;context.options,
- = dc_file,
- D_IMPORT_ERRORS|M_OPTERR,
- = CLIENT_CONNECT_OPT_MASK,
- option_types_found,
- mi->cont= ext.c2.es);
+ = options_server_import(&mi->context.options, dc_file, D_IMPORT_ERRORS= | M_OPTERR,
+ = CLIENT_CONNECT_OPT_MASK, option_types_found, mi->= context.c2.es);

/*
* If the --client-connect script generates a config file
@@ -1688,10 +1645,8 @@
* Called after client-c= onnect plug-in is called
*/
static void<= /span>
-multi_client_connect_p= ost_plugin(struct multi_context *m,
- struct multi_instance *mi,
- = const struct plugin_return *pr,
- unsigned int *option_t= ypes_found)
+multi_cl= ient_connect_post_plugin(struct multi_context *m, struct multi_instance *mi= ,
+ = const struct plugin_return *pr, unsigned int *option_types_f= ound)
{
struct plugin_return config;<= /span>

@@ -1705,12 +1660,9 @@
= {
if (config.list[i] && config.= list[i]->value)
{
- options_string_import(&mi-&= gt;context.options,
- = config.list[i]->value,
- = D_IMPORT_ERRORS|M_OPTERR,

- CLIENT_CONNECT_OPT_MASK,
- = option_types_found,
- mi->context.c2.es);
+ options_s= tring_import(&mi->context.options, config.list[i]->value,<= br>+ = D_IMPORT_ERRORS | M_OPTERR, CLIENT_CONNECT_OPT_MASK,
<= span style=3D"color: hsl(120, 100%, 40%);">+ = option_types_found, mi->context.c2.es);

= }
}

@@ -1732= ,9 +1684,7 @@
* Called to load management-derived client-= connect config
*/
enum client_connect_re= turn
-multi_client_conn= ect_mda(struct multi_context *m,
- struct multi_instance *mi,
- bool defe= rred,

+multi_client_c= onnect_mda(struct multi_context *m, struct multi_instance *mi, bool deferre= d,
unsigned int *option_types_fou= nd)
{
/* We never return CC_RET_DEFER= RED */
@@ -1747,12 +1697,8 @@
for = (be =3D mi->cc_config->head; be !=3D NULL; be =3D be->next)=
{
const char *opt =3D BSTR(= &be->buf);
- = options_string_import(&mi->context.options,
- opt,=
- = D_IMPORT_ERRORS|M_OPTERR,
- CLIENT_CONNECT_OPT_MASK,=
- = option_types_found,
- mi->context.c2.es);<= br>+ options_string_= import(&mi->context.options, opt, D_IMPORT_ERRORS | M_OPTERR,=
+ = CLIENT_CONNECT_OPT_MASK, option_types_found, mi->context.c2.es);=
}

/*
@@ -1817,9 +1763,9 @@
else if (dco_enab= led(o))
{
msg(M_INFO, "C= lient does not support DATA_V2. Data channel offloading "
- "requires DATA_V2= . Dropping client.");

+ "requires DATA_V2. Dropping client.");=
auth_set_client_reason(tls_multi, "Data chan= nel negotiation "
= - "failed (missing DATA_V2)");
+ = "failed (missing DATA_V2)");
= return false;
}

@@ -1828,8 +1774,8 @@

if (proto & IV_PROTO_NCP_= P2P)
{
msg(M_WARN, "Note= : peer reports running in P2P mode (no --pull/--client "
- "option). It will = not negotiate ciphers with this server. "

- "Expect this connection to fail.&= quot;);
+ = "option). It will not negotiate ciphers with this server. &quo= t;
+ = "Expect this connection to fail.");
}


if (proto & IV_PROTO_REQUEST_PUSH)<= /span>
@@ -1844,11 +1790,11 @@
else if (o->= ;force_key_material_export)
{
= msg(M_INFO, "PUSH: client does not support TLS Keying Material "=
- "Exp= orters but --force-tls-key-material-export is enabled.");
+ "Export= ers but --force-tls-key-material-export is enabled.");

auth_set_client_reason(tls_multi, "Client incompatible with = this "

- = "server. Keying Material Exporters (RFC 5705) &qu= ot;
- = "support missing. Upgrade to a client that "<= br>- = "supports this feature (OpenVPN 2.6.0+).");
+ = "server. Keying Material Exporters (RFC 5705) "
+ = "support missing. Upgrade to a client that "

+ = "supports this feature (OpenVPN 2.6.0+).");

<= span> return false;

}
if = (proto & IV_PROTO_DYN_TLS_CRYPT)
@@ -1869,10 +1815,11 @= @
*/
if (get_primary_key(tls_mul= ti)->crypto_options.key_ctx_bi.initialized)
{
- msg(M_INFO, "P= USH: client wants to negotiate cipher (NCP), but "
+ msg(M_INFO,
+ "PUSH: client wants to= negotiate cipher (NCP), but "
"serv= er has already generated data channel keys, "
= "re-sending previously negotiated cipher '%s'",
- o->cipherna= me );
+ o-= >ciphername);
return true;
= }

@@ -1880,14 +1827,13 @@
* Push the first cipher from --data-ciphers to the client that
* the client announces to be supporting.
= */
- char *pus= h_cipher =3D ncp_get_best_cipher(o->ncp_ciphers, peer_info,
- = tls_multi->remote_ciphername,

- &o->= ;gc);
+ char *push= _cipher =3D
+ = ncp_get_best_cipher(o->ncp_ciphers, peer_info, tls_multi->remote_ciph= ername, &o->gc);
if (push_cipher)
{

/* Enable epoch data key format if suppo= rted and AEAD cipher in use */
- if (tls_multi->session[TM_ACTIVE].opt->data_epoch_su= pported
- &a= mp;& (proto & IV_PROTO_DATA_EPOCH) && cipher_kt_mode_aead(p= ush_cipher))
+ = if (tls_multi->session[TM_ACTIVE].opt->data_epoch_supported &&am= p; (proto & IV_PROTO_DATA_EPOCH)
+ && cipher_kt_mode_aead(push_cipher))
{
o->imported_proto= col_flags |=3D CO_EPOCH_DATA_KEY_FORMAT;
}<= br>@@ -1908,16 +1854,17 @@
* side, in this situ= ation we fail the auth*/
if (strlen(peer_ciphers) >= 0)
{
- msg(M_INFO, "PUSH: No common cipher between server and cl= ient. "
+ = msg(M_INFO,
+ = "PUSH: No common cipher between server and client. "<= br> "Server data-ciphers: '%s'%s, client sup= ported ciphers '%s'",
o->ncp_c= iphers_conf, ncp_expanded_ciphers(o, &gc), peer_ciphers);
}

else if (tls_multi->remote_ciphername)
{
- = msg(M_INFO, "PUSH: No common cipher between server and client. = "
+ msg(M= _INFO,
+ &= quot;PUSH: No common cipher between server and client. "
"Server data-ciphers: '%s'%s, client supports = cipher '%s'",

- o->ncp_ciphers_conf, ncp_expanded_ciphers(o, &gc),<= /span>
- tls_multi-= >remote_ciphername);
+ o->ncp_ciphers_conf, ncp_expanded_ciphers(o, &gc), t= ls_multi->remote_ciphername);
}
= else
{
@@ -1925,20 +1872,22 @@

if (o->enable_ncp_fallback &&a= mp; !tls_multi->remote_ciphername)
{
= - msg(M_INFO, "Us= ing data channel cipher '%s' since "
- "--data-ciphers-fallback i= s set.", o->ciphername);
+ msg(M_INFO,
+ "Using data channel cipher '%s= 9; since "
+ = "--data-ciphers-fallback is set.",
+ o->ciphername);
ret =3D true;
} else
{
= msg(M_INFO, "Use --data-ciphers-fallback with the cipher the "=
- "= ;client is using if you want to allow the client to connect");<= br>+ &qu= ot;client is using if you want to allow the client to connect");
}
}
if (!ret)=
{
auth_set_client_reason(tls= _multi, "Data channel cipher negotiation "
- "failed= (no shared cipher)");
+ "failed (no shared c= ipher)");
}

= gc_free(&gc);
@@ -1961,8 +1910,7 @@
= setenv_del(mi->context.c2.es, "client_connect_deferred_file&quo= t;);
if (!platform_unlink(ccs->deferred_ret_file))<= /span>
{
= - msg(D_MULTI_ERRORS, "MULTI: problem deleting temporary file: = %s",
- = ccs->deferred_ret_file);
+ msg(D_MULTI_ERRORS, "MULTI: problem deleting temporary= file: %s", ccs->deferred_ret_file);
}<= br> free(ccs->deferred_ret_file);
ccs->= ;deferred_ret_file =3D NULL;
@@ -1993,8 +1941,7 @@ }
ccs->deferred_ret_file =3D string_al= loc(fn, NULL);

- setenv_str(mi->context.c2.es, "client_connect_deferr= ed_file",
- = ccs->deferred_ret_file);
+ setenv_str(mi->context.c2.es, "client_connect_d= eferred_file", ccs->deferred_ret_file);
gc_free(&gc);
return true;
<= span>@@ -2045,7 +1992,7 @@

default:
/* We received an unknown/unexpected value. Assume failure.= */

msg(M_WARN, "WARNING: Unknown/unexpec= ted value in deferred "
- "client-connect resultfile");
+ "cl= ient-connect resultfile");

ret =3D CC_RET= _FAILED;
}
fclose(fp);
= @@ -2067,8 +2014,7 @@
setenv_del(mi->cont= ext.c2.es, "client_connect_config_file");
= if (!platform_unlink(ccs->config_file))
{
- msg(D_MULTI_E= RRORS, "MULTI: problem deleting temporary file: %s",
- ccs->config_fil= e);

+ msg(= D_MULTI_ERRORS, "MULTI: problem deleting temporary file: %s", ccs= ->config_file);
}
free= (ccs->config_file);
ccs->config_file =3D NUL= L;
@@ -2102,18 +2048,15 @@
} ccs->config_file =3D string_alloc(fn, NULL);

- setenv_str(mi-&= gt;context.c2.es, "client_connect_config_file",
- ccs->config_file);
+ setenv_str(mi->= context.c2.es, "client_connect_config_file", ccs->config_file)= ;

gc_free(&gc);
= return true;
}

sta= tic enum client_connect_return
-multi_client_connect_call_plugin_v1(struct multi_context *m,
- = struct multi_instance *mi,
- bool deferred,
= - = unsigned int *option_types_found)
+multi_client_connect_call_plugin_v1(struct multi_context = *m, struct multi_instance *mi,
+ bool deferred, unsigned int = *option_types_found)
{
enum client_co= nnect_return ret =3D CC_RET_SKIPPED;
#ifdef ENABLE_PLUGIN<= /span>
@@ -2131,8 +2074,7 @@
if (!deferre= d)
{
call =3D OPENVPN= _PLUGIN_CLIENT_CONNECT;
- if (!ccs_gen_config_file(mi)
- || !ccs_gen_deferred_ret_file(mi))
+ if (!ccs_ge= n_config_file(mi) || !ccs_gen_deferred_ret_file(mi))
= {
ret =3D CC_RET_FAILED;
= goto cleanup;
@@ -2147,8 +2089,7 @@<= /span>
}

argv_= printf(&argv, "%s", ccs->config_file);
- int plug_ret =3D plugin_call(mi-&= gt;context.plugins, call,
- &argv, NULL, mi->context.c2.e= s);
+ int plug= _ret =3D plugin_call(mi->context.plugins, call, &argv, NULL, mi->= context.c2.es);
if (plug_ret =3D=3D OPENVPN_PLUGIN= _FUNC_SUCCESS)
{
ret = =3D CC_RET_SUCCEEDED;
@@ -2188,8 +2129,7 @@
/* if we still think we have succeeded, do postprocessing */
if (ret =3D=3D CC_RET_SUCCEEDED)
= {
- mult= i_client_connect_post(m, mi, ccs->config_file,
- option_ty= pes_found);
+ = multi_client_connect_post(m, mi, ccs->config_file, option_types_foun= d);
}
cleanup:
= argv_free(&argv);
@@ -2205,10 +2145,8 @@<= br> }

static enum client_connect_r= eturn
-multi_client_con= nect_call_plugin_v2(struct multi_context *m,
- struct multi_ins= tance *mi,
- = bool deferred,
- unsigned int *option_= types_found)
+multi_c= lient_connect_call_plugin_v2(struct multi_context *m, struct multi_instance= *mi,
+ = bool deferred, unsigned int *option_types_found)
{
enum client_connect_return ret =3D CC_R= ET_SKIPPED;
#ifdef ENABLE_PLUGIN
@@ -2216,= 8 +2154,7 @@
ASSERT(mi);
ASSERT(o= ption_types_found);

- int call =3D deferred ? OPENVPN_PLUGIN_CLIENT_CONNECT_D= EFER_V2 :
- = OPENVPN_PLUGIN_CLIENT_CONNECT_V2;
+ int call =3D deferred ? OPENVPN_PLUGIN_CLIENT_CONNECT_= DEFER_V2 : OPENVPN_PLUGIN_CLIENT_CONNECT_V2;
/* V2 cal= lback, use a plugin_return struct for passing back return info */ if (plugin_defined(mi->context.plugins, call))
{

@@ -2225,8 +2162,7 @@
plugin_return_init(&pr);

- int plug_ret =3D plugin_ca= ll(mi->context.plugins, call,

- NULL, &pr, mi->context= .c2.es);
+ int= plug_ret =3D plugin_call(mi->context.plugins, call, NULL, &pr, mi-&= gt;context.c2.es);
if (plug_ret =3D=3D OPENVPN_PLU= GIN_FUNC_SUCCESS)
{
m= ulti_client_connect_post_plugin(m, mi, &pr, option_types_found);=
@@ -2235,13 +2171,12 @@
else if (plug_re= t =3D=3D OPENVPN_PLUGIN_FUNC_DEFERRED)
{ ret =3D CC_RET_DEFERRED;
- if (!(plugin_defined(mi->context.plug= ins,
- = OPENVPN_PLUGIN_CLIENT_CONNECT_DEFER_V2)))
+ if (!(plugin_defined(mi-&= gt;context.plugins, OPENVPN_PLUGIN_CLIENT_CONNECT_DEFER_V2)))
{

msg(M_WARN, "A plug= in that defers from the "
- "OPENVPN_PLUGIN_CLIENT_CONNECT_V2 call mu= st also "
- = "declare support for "
- "OPENVPN_PLUGIN_CLIENT_CON= NECT_DEFER_V2");
+ "OPENVPN_PLUGIN_CLIENT_CONNECT_V2 call m= ust also "
+ = "declare support for "
+ "OPEN= VPN_PLUGIN_CLIENT_CONNECT_DEFER_V2");
= ret =3D CC_RET_FAILED;
}
= }
@@ -2259,8 +2194,7 @@
}
<= span>

static enum client_connect_return
-multi_client_connect_script_deferred(st= ruct multi_context *m,
= - struct multi_instance *mi,
= +multi_client_connect_script_de= ferred(struct multi_context *m, struct multi_instance *mi,
= unsigned int *option_types_found)
{
ASSERT(mi);
@@ -2285,8= +2219,7 @@
if (ret =3D=3D CC_RET_SUCCEEDED) {
ccs_delete_deferred_ret_file(mi);
- multi_client_con= nect_post(m, mi, ccs->config_file,
- option_types_found);
+ multi_client_con= nect_post(m, mi, ccs->config_file, option_types_found);
= ccs_delete_config_file(mi);
}
if (ret =3D=3D CC_RET_FAILED)

@@ -2302,9 +2235,7 @@
* Runs the --client-connect script if one is defined.
*/
static enum client_connect_return<= br>-multi_client_connect_call_scr= ipt(struct multi_context *m,
- struct multi_instance *mi,- = bool deferred,
+mu= lti_client_connect_call_script(struct multi_context *m, struct multi_instan= ce *mi, bool deferred,
un= signed int *option_types_found)
{
if = (deferred)
@@ -2324,8 +2255,7 @@
setenv_str(mi->context.c2.es, "script_type", = "client-connect");

- if (!ccs_gen_config_file(mi)
- || !ccs_gen_deferred_re= t_file(mi))

+ = if (!ccs_gen_config_file(mi) || !ccs_gen_deferred_ret_file(mi))
<= span> {

ret =3D CC_RET_FAILED;<= br> goto cleanup;
@@ -2342,8 +2272,7 @@
}
else
<= span> {

- = multi_client_connect_post(m, mi, ccs->config_file,<= br>- = option_types_found);
+ multi_client_connect_post(m, mi, ccs->conf= ig_file, option_types_found);
ret =3D CC_R= ET_SUCCEEDED;
}
}
@@ -2364,8 +2293,7 @@
}

static bool
-multi_client_setup_dco_initial(struct multi_context *m,
- struct= multi_instance *mi,

= +multi_client_setup_dco_initial(struct multi_context *m, struct multi_insta= nce *mi,
struct gc_arena *g= c)
{
if (!dco_enabled(&mi->con= text.options))
@@ -2376,8 +2304,8 @@
i= nt ret =3D dco_multi_add_new_peer(m, mi);
if (ret <= 0)
{
- msg(D_DCO, "Cannot add peer to DCO for %s: %s (%d)",=
- multi_ins= tance_string(mi, false, gc), strerror(-ret), ret);
+ msg(D_DCO, "Cannot add peer to = DCO for %s: %s (%d)", multi_instance_string(mi, false, gc),
= + strerror(-ret), re= t);
return false;
}
@@ -2398,9 +2326,8 @@
}
#endif
struct tls_session *session =3D &am= p;c->c2.tls_multi->session[TM_ACTIVE];
- if (!tls_session_update_crypto_params(c->c2.t= ls_multi, session, &c->options,
- &c->c2.fr= ame, frame_fragment,
- = get_link_socket_info(c),+ if (!tls_session_update_c= rypto_params(c->c2.tls_multi, session, &c->options, &c->c2= .frame,
+ = frame_fragment, get_link_socket_info(c),
&c->c1.tuntap= ->dco))
{
msg(D_TLS_ERRORS= , "TLS Error: initializing data channel failed");
@@ -2412,8 +2339,7 @@

}

static void

-multi_cl= ient_connect_late_setup(struct multi_context *m,
- struct multi_ins= tance *mi,
+multi_cli= ent_connect_late_setup(struct multi_context *m, struct multi_instance *mi,<= /span>
const unsigned int option_= types_found)
{
ASSERT(m);
<= span>@@ -2430,7 +2356,8 @@

*/
if= (!mi->context.c2.push_ifconfig_defined)
{- msg(D_MULTI_ERRORS, &q= uot;MULTI: no dynamic or static remote "
+ msg(D_MULTI_ERRORS,
+ "MULTI: no dynamic or st= atic remote "
"--ifconfig address is= available for %s",
multi_instance_string= (mi, false, &gc));
}
@@ -2446,7 +2= 373,8 @@
print_in_addr_t(mi->context.option= s.push_ifconfig_constraint_netmask, 0, &gc);
/* JYFIXME -- this should cause the connection to fail */<= /span>
- msg(D_MULTI_ER= RORS, "MULTI ERROR: primary virtual IP for %s (%s) "
+ msg(D_MULTI_ERRORS,
+ "MULTI = ERROR: primary virtual IP for %s (%s) "
&= quot;violates tunnel network/netmask constraint (%s/%s)",
multi_instance_string(mi, false, &gc),

print_in_addr_t(mi->context.c2.push_ifconfig_local, 0, &am= p;gc),

@@ -2490,9 +2418,7 @@
{<= br> if (mi->context.c2.push_ifconfig_defined)
{

- = multi_learn_in_addr_t(m, mi,
- mi->context.c2.push_ifconf= ig_local,
- = -1, true);
+ multi_learn_in_addr_t(m, mi, mi->context.c2.pus= h_ifconfig_local, -1, true);
msg(D_MULTI_LOW, = "MULTI: primary virtual IP for %s: %s",
= multi_instance_string(mi, false, &gc),
= print_in_addr_t(mi->context.c2.push_ifconfig_local, 0, &gc)= );
@@ -2500,15 +2426,12 @@

if (mi->context.c2.push_ifconfig_ipv6_defined)

{

- = multi_learn_in6_addr(m, mi,
- mi->context.c2.push_ifconfig_i= pv6_local,
- = -1, true);
+ multi_learn_in6_addr(m, mi, mi->context.c2.push= _ifconfig_ipv6_local, -1, true);
/* TODO: find= out where addresses are "unlearned"!! */
= const char *ifconfig_local_ipv6 =3D
= print_in6_addr(mi->context.c2.push_ifconfig_ipv6_local, 0, &gc);
msg(D_MULTI_LOW, "MULTI: primary virtual IPv= 6 for %s: %s",
- = multi_instance_string(mi, false, &gc),
- ifconfig_local_ipv6);
+ multi_= instance_string(mi, false, &gc), ifconfig_local_ipv6);
= }

/* add routes locally= , pointing to new client, if
@@ -2524,7 +2447,8 @@ }
else if (mi->context.options.iroutes= )
{
+ = msg(D_MULTI_ERRORS,
+ "MULTI: --iroute options rejected for %s -- iroute = "
"only works with tun-style tunnels= ",
multi_instance_string(mi, false, &= gc));
}
@@ -2538,8 +2462,7 @@ }

static void
-multi_client_connect_early_setup(struct= multi_context *m,
- = struct multi_instance *mi)
+multi_client_connect_early_setup(struc= t multi_context *m, struct multi_instance *mi)
{ ASSERT(mi->context.c1.tuntap);
/*
@@ -2574,10 +2497,8 @@
* ccd/script to do com= pression on a special client.
*/
static = enum client_connect_return
-multi_client_connect_compress_migrate(struct multi_context *m,<= br>- = struct multi_instance *mi,
- bool deferred,- = unsigned int *option_types_found)
+multi_client_connect_compress_migrate(struct multi_co= ntext *m, struct multi_instance *mi,
+ bool deferred, unsig= ned int *option_types_found)
{
#ifdef USE= _COMP
struct options *o =3D &mi->context.option= s;
@@ -2608,9 +2529,7 @@
* --client-confi= g-dir directory.
*/
static enum client_c= onnect_return
-multi_cl= ient_connect_source_ccd(struct multi_context *m,
- struct multi_ins= tance *mi,
- = bool deferred,
+multi_client_connect_source_ccd(struct multi_context *m, st= ruct multi_instance *mi, bool deferred,
= unsigned int *option_types_found)
{ /* Since we never return a CC_RET_DEFERRED, this indicates a s= erious
@@ -2624,12 +2543,10 @@

= const char *ccd_client =3D
plat= form_gen_path(mi->context.options.client_config_dir,
- tls_common_= name(mi->context.c2.tls_multi, false),
- &gc);
+ tls_c= ommon_name(mi->context.c2.tls_multi, false), &gc);

=
const char *ccd_default =3D
- platform_gen_path(mi->contex= t.options.client_config_dir,
- CCD_DEFAULT, &gc);
+ platform_gen_path(mi-&g= t;context.options.client_config_dir, CCD_DEFAULT, &gc);



/* try common-name file */
@@ -2645,12 +2562,8 @@

= if (ccd_file)
{
- options_server_import(&mi->conte= xt.options,
- = ccd_file,
- D_IMPORT_ERRORS|M_OPTERR,
- = CLIENT_CONNECT_OPT_MASK,
- option_types_found,- = mi->context.c2.es);
+ options_server_import(&mi->context.options, ccd_fi= le, D_IMPORT_ERRORS | M_OPTERR,
+ CLIENT_CONNECT_OPT_MASK, opti= on_types_found, mi->context.c2.es);
/*
* Select a virtual address from either --ifconfig= -push in
* --client-config-dir file or --ifco= nfig-pool.
@@ -2666,9 +2579,9 @@
retur= n ret;
}

-typedef enum client_connect_return (*multi_client_con= nect_handler)
- (str= uct multi_context *m, struct multi_instance *mi,
- bool from_deferred, unsigned int *option_typ= es_found);
+typedef e= num client_connect_return (*multi_client_connect_handler)(
+ struct multi_context *m, struct = multi_instance *mi, bool from_deferred,
+ unsigned int *option_types_found);
=
static const multi_client_connect_handler client_connect= _handlers[] =3D {
multi_client_connect_compress_migrat= e,
@@ -2694,9 +2607,9 @@
if (!multi-&g= t;locked_username)
{
msg(D_MU= LTI_ERRORS, "MULTI: Ignoring override-username as no "
= - "user/password = method is enabled. Enable "
- "--management-client-auth, --auth-user-pass-ver= ify, or a "
- = "plugin with user/password verify capability.");+ &= quot;user/password method is enabled. Enable "
+ "--manag= ement-client-auth, --auth-user-pass-verify, or a "
+ "plugi= n with user/password verify capability.");
re= turn false;
}

@@ -27= 27,16 +2640,15 @@
{
s= truct user_pass up;
CLEAR(up);
- strncpynt(up.username, mu= lti->locked_username,

+ strncpynt(up.username, multi->loc= ked_username, sizeof(up.username));

= generate_auth_token(&up, multi);
}

- = msg(D_MULTI_LOW, "MULTI: Note, override-username changes username &qu= ot;
+ msg(D_MU= LTI_LOW,
+ = "MULTI: Note, override-username changes username "
"from '%s' to '%s'",

- multi->locked_origi= nal_username,

- = multi->locked_username);
+ multi->locked_original_username, multi->locke= d_username);
}
return true;
}
@@ -2767,8 +2679,7 @@
bo= ol from_deferred =3D (mi->context.c2.tls_multi->multi_state !=3D CAS_= PENDING);

int *cur_handler_index =3D= &mi->client_connect_defer_state.cur_handler_index;
- unsigned int *option_types_found = =3D
- &mi-&g= t;client_connect_defer_state.option_types_found;
+ unsigned int *option_types_found =3D &= mi->client_connect_defer_state.option_types_found;

/* We are called for the first time */
= if (!from_deferred)
@@ -2783,12 +2694,10 @@

bool cc_succeeded =3D true;

- while (cc_succeeded<= /span>
- && = client_connect_handlers[*cur_handler_index] !=3D NULL)
+ while (cc_succeeded && clien= t_connect_handlers[*cur_handler_index] !=3D NULL)
{
enum client_connect_return ret;
- ret =3D client_connect_handlers[*c= ur_handler_index](m, mi, from_deferred,
- = option_types_found);
+ ret =3D client_connect_handlers[*cur_handler_index](m, mi, from_d= eferred, option_types_found);

fr= om_deferred =3D false;

@@ -2836,7 +2745,7= @@
if (mi->context.options.disable)
= {
msg(D_MULTI_ERRORS, "MUL= TI: client has been rejected due to "
- "'disable' directive"= ;);
+ = "'disable' directive");
= cc_succeeded =3D false;
}

@@ -2889,8 +2798,8 @@
#ifdef ENABLE_= MANAGEMENT
if (management)
{
- management_connect= ion_established(management,
- &mi->context.c2.mda_= context, mi->context.c2.es);
+ management_connection_established(management, &mi-&= gt;context.c2.mda_context,
+ mi->context.c2.es);
}
#endif
}
@@ -2912,13 +2821,14 @@

while (buffer_i < r)
{
/* parse inotify events */
- struct inotify_e= vent *pevent =3D (struct inotify_event *) &buffer[buffer_i];
= + struct inotify_event *= pevent =3D (struct inotify_event *)&buffer[buffer_i];
= size_t event_size =3D sizeof(struct inotify_event) + pevent->len= ;
buffer_i +=3D event_size;

msg(D_MULTI_DEBUG, "MULTI: modified fd %d, mask %= d", pevent->wd, pevent->mask);

- struct multi_instance *mi =3D= hash_lookup(m->inotify_watchers, (void *) (unsigned long) pevent->wd= );

+ struct mu= lti_instance *mi =3D
= + hash_lookup(m->inotify_watchers, (void *)(unsigned long)pev= ent->wd);

if (pevent->mask= & IN_CLOSE_WRITE)
{
@@ -2937,= 7 +2847,7 @@
/* this event is _always_ fired w= hen watch is removed or file is deleted */
if = (mi)
{
- hash_remove(m->inotify_watchers, (void *) = (unsigned long) pevent->wd);
+ hash_remove(m->inotify_watchers, (void *)(un= signed long)pevent->wd);
mi->inotify= _watch =3D -1;
}
}
@@ -2954,9 +2864,7 @@
* instance. */
void
-multi_add_mbuf(struct multi_context *m,
- struct multi_instance *mi,
- struct m= buf_buffer *mb)
+mult= i_add_mbuf(struct multi_context *m, struct multi_instance *mi, struct mbuf_= buffer *mb)
{
if (multi_output_queue_= ready(m, mi))
{
@@ -2975,9 +2883,7 @@<= /span>
* Add a packet to a client instance output queue.<= br> */
static inline void
-multi_unicast(struct multi_context *m,- const struct buf= fer *buf,
- = struct multi_instance *mi)
+multi_unicast(struct multi_context *m, const struct buffer *buf, s= truct multi_instance *mi)
{
struct mb= uf_buffer *mb;

@@ -2994,10 +2900,8 @@
* Broadcast a packet to all clients.
*/
static void
-multi_bcast(struct multi_context *m,
- const struct buffer *buf,
- const struct multi_instance= *sender_instance,
- = uint16_t vid)
+ const struct mult= i_instance *sender_instance, uint16_t vid)
{
struct hash_iterator hi;

struct hash_element *= he;
@@ -3015,7 +2919,7 @@

while ((he =3D hash_iterator_next(&hi)))

= {
- mi = =3D (struct multi_instance *) he->value;
+ mi =3D (struct multi_instance *)he->= value;
if (mi !=3D sender_instance && = !mi->halt)
{
= if (vid !=3D 0 && vid !=3D mi->context.options.vlan_pvid)
@@ -3073,29 +2977,24 @@
tv_add(&mi-&g= t;wakeup, &mi->context.c2.timeval);

/* tell scheduler to wake us up at some point in the future */
- schedule_add_entry(m-&g= t;schedule,
- = (struct schedule_entry *) mi,
- &mi->wakeup,
<= span style=3D"color: hsl(120, 100%, 40%);">+ schedule_add_entry(m->sc= hedule, (struct schedule_entry *)mi, &mi->wakeup,

= compute_wakeup_sigma(&mi->context.c2.timeval))= ;
}

#if defined(ENABLE_= ASYNC_PUSH)
static void
-add_inotify_file_watch(struct multi_context *m, struct m= ulti_instance *mi,
- = int inotify_fd, const char *file)
+add_inotify_file_watch(struct multi_conte= xt *m, struct multi_instance *mi, int inotify_fd,
+ const char *file)
{
/* watch acf file */
- long watch_descriptor =3D inotify_ad= d_watch(inotify_fd, file,
- IN_CLOSE_WRITE | IN_ONESH= OT);
+ long watch_= descriptor =3D inotify_add_watch(inotify_fd, file, IN_CLOSE_WRITE | IN_ONES= HOT);
if (watch_descriptor >=3D 0)
= {
if (mi->inotify_watch !=3D -1) {
- = hash_remove(m->inotify_watchers,
- (void *) (unsigned long)mi-&g= t;inotify_watch);
+ = hash_remove(m->inotify_watchers, (void *)(unsigned long)mi->= ;inotify_watch);
}
- hash_add(m->inotify_watchers, (const uintp= tr_t *)watch_descriptor,
+ hash_add(m->inotify_watchers, (const uintptr_t *)watc= h_descriptor, mi, true);
mi->inotify_watch =3D = watch_descriptor;
}
else@@ -3117,7 +3016,9 @@
{
bool = ret =3D true;

- if (!IS_SIG(&mi->context) && ((flags & MPP= _PRE_SELECT) || ((flags & MPP_CONDITIONAL_PRE_SELECT) && !ANY_O= UT(&mi->context))))
+ if (!IS_SIG(&mi->context)
+ && ((flags & MPP_PRE_SELECT)
+ || ((flags= & MPP_CONDITIONAL_PRE_SELECT) && !ANY_OUT(&mi->context)= )))
{
#if defined(ENABLE_ASYNC_PUSH)<= /span>
bool was_unauthenticated =3D true;
@@ -3142,14 +3043,12 @@

if (ks && ks->= plugin_auth.auth_control_file && was_unauthenticated
&& (ks->authenticated =3D=3D KS_AUTH_DEFERRED))
{
- add_inotify_file_watch(m, mi, m->top.c2.inotify_fd,

- = ks->plugin_auth.auth_control_file);
+ add_inotify_file_watch(m, mi, m->= ;top.c2.inotify_fd, ks->plugin_auth.auth_control_file);
= }
if (ks && ks->script_auth.au= th_control_file && was_unauthenticated
= && (ks->authenticated =3D=3D KS_AUTH_DEFERRED))
{

- = add_inotify_file_watch(m, mi, m->top.c2.inotify_fd,
- ks-&g= t;script_auth.auth_control_file);
+ add_inotify_file_watch(m, mi, m->top.c2.inotif= y_fd, ks->script_auth.auth_control_file);
}
#endif

@@ -3167,8 +3066,7 @= @
&& mi->client_connect_defer_s= tate.deferred_ret_file)
{
= add_inotify_file_watch(m, mi, m->top.c2.inotify_fd,<= br>- = mi->client_connect_defer_state.
- deferred_ret_= file);
+ = mi->client_connect_defer_state.deferred_ret_fi= le);
}
#endif
/* tell scheduler to wake us up at some point in the future *= /

@@ -3190,14 +3088,10 @@
multi_se= t_pending(m, ANY_OUT(&mi->context) ? mi : NULL);

#ifdef MULTI_DEBUG_EVENT_LOOP
- printf("POST %s[%d] to=3D%d lo=3D%d/%d= w=3D%" PRIi64 "/%ld\n",
- id(mi),
- (int) (mi =3D=3D m->pending),- mi ? mi->con= text.c2.to_tun.len : -1,
+ printf("POST %s[%d] to= =3D%d lo=3D%d/%d w=3D%" PRIi64 "/%ld\n", id(mi), (int)(mi = =3D=3D m->pending),
- (int64= _t)mi->context.c2.timeval.tv_sec,
- (long)mi->context.c2.timeval.tv_usec);
+ (int64_t= )mi->context.c2.timeval.tv_sec, (long)mi->context.c2.timeval.tv_usec)= ;
#endif
}
@@ -3218,10 +3112,9 @@
* updates hashtables in mu= lti_context.
*/
static void
-multi_process_float(struct multi_c= ontext *m, struct multi_instance *mi,

- struct link_socket *sock)
+multi_process_float(struct multi_= context *m, struct multi_instance *mi, struct link_socket *sock)

= {
- struct mr= oute_addr real =3D {0};
+ struct mroute_addr real =3D { 0 };
struct hash= *hash =3D m->hash;
struct gc_arena gc =3D gc_new()= ;

@@ -3243,7 +3136,7 @@
= struct hash_element *he =3D hash_lookup_fast(hash, bucket, &real, h= v);
if (he)
{
- struct multi_instance *ex_mi =3D = (struct multi_instance *) he->value;
+ struct multi_instance *ex_mi =3D (struct multi_= instance *)he->value;

struct = tls_multi *m1 =3D mi->context.c2.tls_multi;
str= uct tls_multi *m2 =3D ex_mi->context.c2.tls_multi;
@@ -3= 265,23 +3158,23 @@
*/
if= (m1->peer_id =3D=3D m2->peer_id)
{- msg(M_WARN, "= disallowing peer %" PRIu32 " (%s) from floating to "<= br>+ msg(M_WARN,
+ "d= isallowing peer %" PRIu32 " (%s) from floating to " "its own address (%s)",
= m1->peer_id, tls_common_name(mi->context.c2.tls_mult= i, false),
mroute_addr_print(&mi->r= eal, &gc));
goto done;
= }

- msg(D_MULTI_LOW, "closing instance %s due to float collisi= on with %s "
+ = msg(D_MULTI_LOW,
- multi_instan= ce_string(ex_mi, false, &gc),
- multi_instance_string(mi, false, &gc));<= br>+ multi_instance_= string(ex_mi, false, &gc), multi_instance_string(mi, false, &gc));<= /span>
multi_close_instance(m, ex_mi, false);
<= span> }


msg(D_MULTI_MEDIUM, &quo= t;peer %" PRIu32 " (%s) floated from %s to %s",
- mi->context.c2.tls_mult= i->peer_id,

- = tls_common_name(mi->context.c2.tls_multi, false),
+ mi->context.c2.tls_multi->p= eer_id, tls_common_name(mi->context.c2.tls_multi, false),
mroute_addr_print_ex(&mi->real, MAPF_SHOW_FAMILY, &gc= ),

mroute_addr_print_ex(&real, MAPF_SHOW_FAMIL= Y, &gc));

@@ -3327,7 +3220,8 @@
multi_close_instance(m, mi, false);
}

-#if (def= ined(ENABLE_DCO) && (defined(TARGET_LINUX) || defined(TARGET_FREEBS= D))) || defined(ENABLE_MANAGEMENT)
+#if (defined(ENABLE_DCO) && (defined(TARGET_LINUX) |= | defined(TARGET_FREEBSD))) \
+ || defined(ENABLE_MANAGEMENT)
static void
multi_signal_instance(struct multi_context *m, struct multi_= instance *mi, const int sig)
{
@@ -3338,8 = +3232,7 @@

#if defined(ENABLE_DCO)
static void
-process_incoming_del_peer(struct multi_context *m, struct multi_instance = *mi,
- = dco_context_t *dco)
+process_incoming_del_peer(struct multi_context *m, struct multi_in= stance *mi, dco_context_t *dco)
{
con= st char *reason =3D "ovpn-dco: unknown reason";
= switch (dco->dco_del_peer_reason)
@@ -3436,9 +3329,1= 0 @@
*/
msglevel= =3D D_DCO_DEBUG;
}
- msg(msglevel, "Received DCO message for= unknown peer-id: %d, "
- "type %d, del_peer_reason %d", peer_id, dco-&g= t;dco_message_type,
- = dco->dco_del_peer_reason);
+ msg(msglevel,
+ "Received DCO message for unknown pe= er-id: %d, "
+ = "type %d, del_peer_reason %d",
+ peer_id, dco->dco_message_typ= e, dco->dco_del_peer_reason);
}

dco->dco_message_type =3D 0;
@@ -352= 8,11 +3422,8 @@
if (TUNNEL_TYPE(m->top.c1.t= untap) =3D=3D DEV_TYPE_TUN)
{
= /* extract packet source and dest addresses */
<= span style=3D"color: hsl(0, 100%, 40%);">- mroute_flags =3D = mroute_extract_addr_from_packet(&src,

- = &dest,
- = 0,
- = &c->c2.to_tun,

- = DEV_TYPE_TUN);
+ mroute_flags =3D
+ mroute_extract_addr_from_packe= t(&src, &dest, 0, &c->c2.to_tun, DEV_TYPE_TUN);

/* drop packet if extract failed */<= /span>
if (!(mroute_flags & MROUTE_EXTRACT_SU= CCEEDED))
@@ -3543,14 +3434,15 @@
= else if (multi_get_instance_by_virtual_addr(m, &src, true) !=3D= m->pending)
{
= /* IPv6 link-local address (fe80::xxx)? */
- if ( (src.type & = MR_ADDR_MASK) =3D=3D MR_ADDR_IPV6
- && IN6_IS_ADDR_LINKLOCAL(&= src.v6.addr) )
+ = if ((src.type & MR_ADDR_MASK) =3D=3D MR_ADDR_IPV6=
+ &a= mp;& IN6_IS_ADDR_LINKLOCAL(&src.v6.addr))
= {
/* do nothing, for n= ow. TODO: add address learning */
}
else
= {
- = msg(D_MULTI_DROPPED, "MULTI: bad source address from client [%s= ], packet dropped",
+ msg(D_MULTI_DROPPED,
+ "MULTI: bad = source address from client [%s], packet dropped",
= mroute_addr_print(&src, &gc));
<= span> }

c->c2.t= o_tun.len =3D 0;
@@ -3599,11 +3491,8 @@
= }
}
= /* extract packet source and dest addresses */
- mroute_flags =3D mrou= te_extract_addr_from_packet(&src,

- = &dest,
- = vid,
- = &c->c2.to_tun,

- = DEV_TYPE_TAP);
+ mroute_flags =3D
+ mroute_extract_addr_from_packet(= &src, &dest, vid, &c->c2.to_tun, DEV_TYPE_TAP);

if (mroute_flags & MROUTE_EXTRAC= T_SUCCEEDED)
{
@@ -3612,7 = +3501,7 @@
/* check for broadcast = */
if (m->enable_c2c) {
- if (mroute_flags & (MROUTE_EXTR= ACT_BCAST|MROUTE_EXTRACT_MCAST))
+ if (mroute_flags & (MROUTE_EXT= RACT_BCAST | MROUTE_EXTRACT_MCAST))
= {
multi_bcast(m, &am= p;c->c2.to_tun, m->pending, vid);
= }
@@ -3632,7 +3521,8 @@
= }
else
= {
- = msg(D_MULTI_DROPPED, "MULTI: bad source address = from client [%s], packet dropped",
+ msg(D_MULTI_DROPPED,
= + &q= uot;MULTI: bad source address from client [%s], packet dropped",
mroute_addr_print(&src, &gc= ));
c->c2.to_tun.len =3D 0;
}
@@ -3666,7 +3556,7 @@
if (BLEN(&m->top.c2.buf) > 0)
{

unsigned int mroute_flags;
- struct mroute_addr src =3D {0= }, dest =3D {0};

+ = struct mroute_addr src =3D { 0 }, dest =3D { 0 };
= const int dev_type =3D TUNNEL_TYPE(m->top.c1.tuntap);
int16_t vid =3D 0;


@@ -3693,2= 5 +3583,22 @@
* the appropriate multi_instance ob= ject.
*/

- mroute_flags =3D mroute_extract_add= r_from_packet(&src,
- &dest,<= br>- = vid,
- &m->= top.c2.buf,
- = dev_type);
+ mroute_flags =3D mroute_extract= _addr_from_packet(&src, &dest, vid, &m->top.c2.buf, dev_type= );

if (mroute_flags & MROUTE= _EXTRACT_SUCCEEDED)
{
= struct context *c;

/* broad= cast or multicast dest addr? */
- if (mroute_flags & (MROUTE_EXTRACT_BCAST|MROUTE_E= XTRACT_MCAST))
+ = if (mroute_flags & (MROUTE_EXTRACT_BCAST | MROUTE_EXTRACT_MCAST)= )
{
/* for no= w, treat multicast as broadcast */
multi_b= cast(m, &m->top.c2.buf, NULL, vid);
}
else
{
<= span style=3D"color: hsl(0, 100%, 40%);">- multi_set_pending= (m, multi_get_instance_by_virtual_addr(m, &dest, dev_type =3D=3D DEV_TY= PE_TUN));

+ = multi_set_pending(
+ m, multi_get_instance_by_virtual_addr(m, &dest= , dev_type =3D=3D DEV_TYPE_TUN));

= if (m->pending)
{
<= span>@@ -3729,7 +3616,8 @@

else
{
= /* drop packet */
- msg(D_MULTI_DROPPED, "MULTI: packet= dropped due to output saturation (multi_process_incoming_tun)");
+ = msg(D_MULTI_DROPPED,
+ "MULTI: packet dropped due to out= put saturation (multi_process_incoming_tun)");
= buf_reset_len(&c->c2.buf);
= }
}
@@ -3763,7 +3651,8 @@


set_pr= efix(item.instance);
item.instance->context.c2.= buf =3D item.buffer->buf;
- if (item.buffer->flags & MF_UNICAST) /* --mssfix does= n't make sense for broadcast or multicast */
+ if (item.buffer->flags
+ & MF_UNICAST) /*= --mssfix doesn't make sense for broadcast or multicast */

{

pip_flags |=3D PIP_MSSFIX;
}
@@ -3801,7 +3690,8 @@
{

if (m->earliest_wakeup =3D=3D (struct = multi_instance *)&m->deferred_shutdown_signal)
= {
- sche= dule_remove_entry(m->schedule, (struct schedule_entry *) &m->defe= rred_shutdown_signal);
+ (struct= schedule_entry *)&m->deferred_shutdown_signal);
= throw_signal(m->deferred_shutdown_signal.signal_received);
}
else
@@ -3= 844,9 +3734,9 @@
route_quota_exceeded(const struct multi_i= nstance *mi)
{
struct gc_arena gc =3D= gc_new();
- msg(D_R= OUTE_QUOTA, "MULTI ROUTE: route quota (%d) exceeded for %s (see --max-= routes-per-client option)",
- mi->context.options.max_routes_per_client,
= - multi_instance_string(mi= , false, &gc));
+= msg(D_ROUTE_QUOTA,
+ mi->context.options.max_routes_per_client, multi_ins= tance_string(mi, false, &gc));
gc_free(&gc);
}

@@ -3869,8 +3759,7 @@
parm.packet_size =3D min_int(parm.packet_size, m-&g= t;top.c2.frame.buf.payload_size);

= msg(D_GREMLIN, "GREMLIN_FLOOD_CLIENTS: flooding clients with %d pack= ets of size %d",
-= parm.n_packets,
- parm.packet_size);
+ parm.n_packets, parm.packet_size);
<= span>

for (i =3D 0; i < parm.packet_size; ++i)=
{
@@ -3958,10 +3847,11 @@<= br> hash_iterator_init(m->iter, &hi);
= while ((he =3D hash_iterator_next(&hi)))
{=
- struct multi_instanc= e *mi =3D (struct multi_instance *) he->value;
+ struct multi_instance *mi =3D (struct= multi_instance *)he->value;
if (!mi->halt &= amp;& proto_is_dgram(mi->context.c2.link_sockets[0]->info.proto))=
{
- send_control_channel_string(&mi->context, next_ser= ver ? "RESTART,[N]" : "RESTART", D_PUSH);
+ send_control_channel_= string(&mi->context, next_server ? "RESTART,[N]" : "R= ESTART",

+ = D_PUSH);
mul= ti_schedule_context_wakeup(m, mi);
}
}

@@ -3975,8 +3865,7 @@
m->deferred_shutdown_signal.signal_received =3D m->top.si= g->signal_received;

- schedule_add_entry(m->schedule,
- (struct schedule= _entry *) &m->deferred_shutdown_signal,
+ schedule_add_entry(m->schedule, (struct s= chedule_entry *)&m->deferred_shutdown_signal,
= &m->deferred_shutdown_signal.wakeup,
compute_wakeup_sigma(&m->deferred_shutdow= n_signal.wakeup));


@@ -3997,8 +3886,7 @@<= /span>
status_close(so);
return = false;
}
- else if (has_udp_in_local_list(&m->top.options)- && is_exi= t_restart(m->top.sig->signal_received)
+ else if (has_udp_in_local_list(&m->top.= options) && is_exit_restart(m->top.sig->signal_received)
&& (m->deferred_shutdown_signal.signal= _received =3D=3D 0)
&& m->top.opti= ons.ce.explicit_exit_notification !=3D 0)
{
= @@ -4016,7 +3904,7 @@
static void
m= anagement_callback_status(void *arg, const int version, struct status_outpu= t *so)
{
- struct multi_context *m =3D (struct multi_context *) arg;+ struct multi_context *m = =3D (struct multi_context *)arg;

if = (!version)
{
@@ -4031,14 +3919,14 @@
static int
management_callback_n_clients(v= oid *arg)
{
- struct multi_context *m =3D (struct multi_context *) arg;=
+ struct multi_context *= m =3D (struct multi_context *)arg;
return m->n_clie= nts;
}

static int
management_callback_kill_by_cn(void *arg, const char *del_cn)
{
- = struct multi_context *m =3D (struct multi_context *) arg;
+ struct multi_context *m =3D (stru= ct multi_context *)arg;
struct hash_iterator hi;
struct hash_element *he;
int count =3D= 0;
@@ -4046,7 +3934,7 @@
hash_iterato= r_init(m->iter, &hi);
while ((he =3D hash_itera= tor_next(&hi)))
{
- struct multi_instance *mi =3D (struct multi_in= stance *) he->value;
+ struct multi_instance *mi =3D (struct multi_instance *)he->v= alue;
if (!mi->halt)
{=
const char *cn =3D tls_common_name(mi->con= text.c2.tls_multi, false);
@@ -4062,10 +3950,9 @@ }

static int
-management_callback_kill_by_addr(void *ar= g, const in_addr_t addr,
+management_callback_kill_b= y_addr(void *arg, const in_addr_t addr, const int port, const int proto)
{
- s= truct multi_context *m =3D (struct multi_context *) arg;
+ struct multi_context *m =3D (struc= t multi_context *)arg;
struct hash_iterator hi;=
struct hash_element *he;
struct openvpn= _sockaddr saddr;
@@ -4082,7 +3969,7 @@
= hash_iterator_init(m->iter, &hi);
whil= e ((he =3D hash_iterator_next(&hi)))
{<= br>- struct multi_inst= ance *mi =3D (struct multi_instance *) he->value;
+ struct multi_instance *mi =3D= (struct multi_instance *)he->value;
if (!m= i->halt && mroute_addr_equal(&maddr, &mi->real))
{
multi_signal_in= stance(m, mi, SIGTERM);
@@ -4097,7 +3984,7 @@
static void

management_delete_event(void *arg, event_t= event)
{
- struct multi_context *m =3D (struct multi_context *) arg;+ struct multi_context *m = =3D (struct multi_context *)arg;
if (m->multi_io)
{
multi_tcp_delete_event(m->= ;multi_io, event);
@@ -4109,7 +3996,7 @@
{=
if (m)
{
- struct multi_instance *mi =3D (stru= ct multi_instance *) hash_lookup(m->cid_hash, &cid);
+ struct multi_instance *mi = =3D (struct multi_instance *)hash_lookup(m->cid_hash, &cid);
<= br> if (mi && !mi->halt)
= {
return mi;
@@ -4121,7 +4008,= 7 @@
static bool
management_kill_by_cid(v= oid *arg, const unsigned long cid, const char *kill_msg)
{=
- struct multi_cont= ext *m =3D (struct multi_context *) arg;
+ struct multi_context *m =3D (struct multi_context = *)arg;
struct multi_instance *mi =3D lookup_by_cid(m, = cid);
if (mi)
{
@= @ -4136,13 +4023,10 @@
}

static bool

-manageme= nt_client_pending_auth(void *arg,
- const unsigned long cid,<= br>- = const unsigned int mda_key_id,
- const char *extra,
- unsig= ned int timeout)

+man= agement_client_pending_auth(void *arg, const unsigned long cid, const unsig= ned int mda_key_id,
+= const char *extra, unsigned int timeout)
{
- st= ruct multi_context *m =3D (struct multi_context *) arg;
+ struct multi_context *m =3D (struct= multi_context *)arg;
struct multi_instance *mi =3D lo= okup_by_cid(m, cid);

if (mi)<= br>@@ -4164,8 +4048,7 @@
}
=
/* sends INFO_PRE and AUTH_PENDING messages to cl= ient */
- bool r= et =3D send_auth_pending_messages(multi, session, extra,
- = timeout);
+ = bool ret =3D send_auth_pending_messages(multi, session, extra, timeout)= ;
reschedule_multi_process(&mi->context);
multi_schedule_context_wakeup(m, mi);
return ret;

@@ -4175,15 +4058,11 @@
<= span>


static bool
-management_client_auth(void *arg,- const un= signed long cid,
- = const unsigned int mda_key_id,
- const bool auth,- const c= har *reason,
- = const char *client_reason,
- struct buffer_list *cc_config) /= * ownership transferred */
+management_client_auth(void *arg, const unsigned long cid, const uns= igned int mda_key_id,
+ const bool auth, const char *reason, const char *c= lient_reason,
+ = struct buffer_list *cc_config) /* ownership transferred */=
{
- = struct multi_context *m =3D (struct multi_context *) arg;
+ struct multi_context *m =3D (st= ruct multi_context *)arg;

struct multi_instance *mi = =3D lookup_by_cid(m, cid);
bool cc_config_owned =3D tr= ue;
bool ret =3D false;
@@ -4203,7 +40= 82,8 @@
}
else if= (reason)
{
- msg(D_MULTI_LOW, "MULTI: connection= rejected: %s, CLI:%s", reason, np(client_reason));
+ msg(D_MULTI_LOW, "= ;MULTI: connection rejected: %s, CLI:%s", reason,
+ np(client_reason));<= /span>
}
}
= }
@@ -4217,7 +4097,7 @@
static char *<= /span>
management_get_peer_info(void *arg, const unsigned long ci= d)
{
-= struct multi_context *m =3D (struct multi_context *) arg;
+ struct multi_context *m =3D (= struct multi_context *)arg;

struct multi_instance *mi = =3D lookup_by_cid(m, cid);
char *ret =3D NULL;<= br>
@@ -4361,7 +4241,7 @@
tunnel_server_loop(&multi);

- #ifdef ENABLE_ASYNC_PUSH
+#ifdef ENABLE_ASYNC_PUSH<= /span>
close(top->c2.inotify_fd);
#endif<= /span>

@@ -4375,5 +4255,4 @@
= multi_uninit(&multi);
multi_top_free(&multi)= ;
close_instance(top);
-
}
diff --git a/src/= openvpn/multi.h b/src/openvpn/multi.h
index 3c3db97..e87e46= 5 100644
--- a/src/openvpn/multi.h
+++ b/sr= c/openvpn/multi.h
@@ -99,27 +99,28 @@
* p= age describes the role the structure plays when OpenVPN is running in
* server-mode.
*/
-struct multi_instance {
- struct schedule_entry se; /* this must be= the first element of the structure,
- * We cast between this and s= chedule_entry so the
- = * beginning of the struct must be identical = */
+struct multi_inst= ance
+{
+ struct schedule_entry se; /* = this must be the first element of the structure,

+ * We cast betwe= en this and schedule_entry so the
+ * beginning of the struct must= be identical */

- struct event_arg ev_arg; /**< this struct will store = a pointer to either mi or
- * link_socket, depending on the event t= ype, to keep
- = * it accessible it's placed within the same stru= ct
- = * it points to. */
+ struct event_arg ev_arg; /**< this struct will store a = pointer to either mi or
+ * link_socket, depending on the event ty= pe, to keep
+ = * it accessible it's placed within the same stru= ct
+ = * it points to. */

str= uct gc_arena gc;
bool halt;
int r= efcount;
- int route= _count; /* number of routes (including cached routes) owned by th= is instance */
- tim= e_t created; /**< Time at which a VPN tunnel instance=
- = * was created. This parameter is set
- * by the \c multi= _create_instance()
- = * function. */
- struct timeval wakeup; /* absolute time */=
- struct mroute_add= r real; /**< External network address of the
- * remote pe= er. */
+ int route= _count; /* number of routes (including cached routes) owned by this= instance */
+ tim= e_t created; /**< Time at which a VPN tunnel instance+ = * was created. This parameter is set
+ * by the \c multi_crea= te_instance()
+ = * function. */
+ struct timeval wakeup; /* absolute time */
+ struct mroute_addr re= al; /**< External network address of the
+ * remote peer. */
ifconfig_pool_handle vaddr_handle;
= char msg_prefix[MULTI_PREFIX_MAX_LENGTH];

@@ -128,7 +129,7 @@

struct mbuf_set *tcp_link_out_de= ferred;
bool socket_set_called;

- in_addr_t reporting_ad= dr; /* IP address shown in status listing */
+ in_addr_t reporting_addr; /* IP= address shown in status listing */
struct in6_addr re= porting_addr_ipv6; /* IPv6 address in status listing */

bool did_real_hash;
@@ -138,10 +139,10 = @@
struct buffer_list *cc_config;
#en= dif
bool did_iroutes;
- int n_clients_delta; /* added to multi_context.n_c= lients when instance is closed */
+ int n_clients_delta; /* added to multi_context.n_clien= ts when instance is closed */

- struct context context; /**< The conte= xt structure storing state
- * for this VPN tunnel. */+ struct context context; /= **< The context structure storing state
+ * for this VPN tunnel= . */
struct client_connect_defer_state client_connect_= defer_state;
#ifdef ENABLE_ASYNC_PUSH
= int inotify_watch; /* watch descriptor for acf */
@@ -159,= 22 +160,23 @@
* page describes the role the structure pla= ys when OpenVPN is running in
* server-mode.
*/

-struct multi_= context {
- struct m= ulti_instance **instances; /**< Array of multi_instances. An instance c= an be
- = * accessed using peer-id as an index. */+struct multi_context+{
+ struct multi_instance **instances; /**<= Array of multi_instances. An instance can be
+ * accesse= d using peer-id as an index. */

- struct hash *hash; /**< VPN tun= nel instances indexed by real
- * address of the remote peer. */=
- struct hash *vhas= h; /**< VPN tunnel instances indexed by
- * virtual a= ddress of remote hosts. */
- struct hash *iter; /**< VPN tunnel instances indexed b= y real
- = * address of the remote peer, optimized
- * = for iteration. */

+ = struct hash *hash; /**< VPN tunnel instances indexed b= y real
+ = * address of the remote peer. */
+ struct hash *vhash; = /**< VPN tunnel instances indexed by

+ * virtu= al address of remote hosts. */
+ struct hash *iter; /**< VPN tunnel instan= ces indexed by real
+= * address of the remote peer, opt= imized
+ = * for iteration. */
struc= t schedule *schedule;
-= struct mbuf_set *mbuf; /**< Set of buffers for passing data
- = * channel packets between VPN tunnel
- * instances. */=
- struct multi_io *= multi_io; /**< I/O state and events tracker */
+ struct mbuf_set *mbuf; /*= *< Set of buffers for passing data
+ * channel packe= ts between VPN tunnel
+ * instances. */
+ struct multi_io *multi_io; = /**< I/O state and events tracker */

struct ifc= onfig_pool *ifconfig_pool;
struct frequency_limit *new= _connection_limiter;
struct initial_packet_rate_limit = *initial_rate_limiter;
@@ -198,8 +200,8 @@
= struct context_buffers *context_buffers;
time_t p= er_second_trigger;

- struct context top; /**< Storage structure fo= r process-wide
- = * configuration. */
+ struct context top; /**< Storage structu= re for process-wide
+= * configuration. */

= struct buffer hmac_reply;
struct link_socke= t_actual *hmac_reply_dest;
@@ -237,8 +239,8 @@
struct mroute_addr addr;

struct multi_instanc= e *instance;

-#define MULTI_ROUTE_CACHE (1<<0)
-#define MULTI_ROUTE_AGEABLE (1<<1)=
+#define MULTI_ROUTE_CACHE = (1 << 0)
+#de= fine MULTI_ROUTE_AGEABLE (1 << 1)
unsigned int f= lags;

unsigned int cache_generation;=
@@ -262,17 +264,18 @@
* Called by mtcp.c= , mudp.c, or other (to be written) protocol drivers
*/


-struct= multi_instance *multi_create_instance(struct multi_context *m, const struc= t mroute_addr *real,
= +struct multi_instance *multi_create_instance(struct multi_context *m,
+ = const struct mroute_addr *real,
= struct link_socket *sock);
void multi_close_instance(struct multi_context *= m, struct multi_instance *mi, bool shutdown);

<= span> bool multi_process_timeout(struct multi_context *m, const unsigned in= t mpp_flags);


-#define MPP_PRE_SELECT (1<<0)
-#define MPP_CONDITIONAL_PRE_SELECT (1&l= t;<1)
-#define MPP_C= LOSE_ON_SIGNAL (1<<2)
-#define MPP_RECORD_TOUCH (1<<3)
+#define MPP_PRE_SELECT = (1 << 0)

+#def= ine MPP_CONDITIONAL_PRE_SELECT (1 << 1)
+#define MPP_CLOSE_ON_SIGNAL (1 << 2)=
+#define MPP_RECORD_= TOUCH (1 << 3)

/*****************************************************************= *********/
@@ -297,7 +300,8 @@
* signa= l during processing.
* - False, if the VPN tunnel instan= ce \a mi was closed.
*/
-bool multi_process_post(struct multi_context *m, struct= multi_instance *mi, const unsigned int flags);
+bool multi_process_post(struct multi_context *m= , struct multi_instance *mi,
+ const unsigned int flags);

/**
* Process an incoming DCO message= (from kernel space).
@@ -334,8 +338,8 @@
= * @param mpp_flags - Fast I/O optimization flags.
* @= param sock - Socket where the packet was received.
= */
-bool multi_proces= s_incoming_link(struct multi_context *m, struct multi_instance *instance, c= onst unsigned int mpp_flags,
- struct link_socket *sock);+bool multi_process_incoming_= link(struct multi_context *m, struct multi_instance *instance,
+ = const unsigned int mpp_flags, struct link_socket *sock);

=

/**
@@ -360,9 +364,7 @@=

struct multi_instance *multi_get_queue(= struct mbuf_set *ms);

-void multi_add_mbuf(struct multi_context *m,
- struct multi_i= nstance *mi,

- = struct mbuf_buffer *mb);
+void multi_add_mbuf(struct multi_context *m, struct multi_i= nstance *mi, struct mbuf_buffer *mb);

vo= id multi_ifconfig_pool_persist(struct multi_context *m, bool force);=

@@ -388,8 +390,7 @@
* Return = true if our output queue is not full
*/
= static inline bool
-mul= ti_output_queue_ready(const struct multi_context *m,
- const struct multi= _instance *mi)
+multi= _output_queue_ready(const struct multi_context *m, const struct multi_insta= nce *mi)
{
if (mi->tcp_link_out_de= ferred)
{
@@ -485,8 +486,7 @@ }

static inline bool
= -multi_route_defined(const struct= multi_context *m,
- = const struct multi_route *r)
+multi_route_defined(const struct multi_context *m= , const struct multi_route *r)
{
if (= r->instance->halt)
{
@@ -511,8 += 511,7 @@
/*
* Takes prefix away from mul= ti_instance.
*/
-void
-ungen= erate_prefix(struct multi_instance *mi);
+void ungenerate_prefix(struct multi_instance *mi);

/*
* Set a msg() function= prefix with our current client instance ID.
@@ -548,10 +54= 7,10 @@
* don't want to reap in a single pass.=
*/

-#define REAP_MAX_WAKEUP 10 /* Do reap pass at least once per = n seconds */
-#define R= EAP_DIVISOR 256 /* How many passes to cover whole hash table */=
-#define REAP_MIN 16= /* Minimum number of buckets per pass */
-#define REAP_MAX 1024 /* Maximum number of buc= kets per pass */
+#de= fine REAP_MAX_WAKEUP 10 /* Do reap pass at least once per n seconds */
+#define REAP_DIVISOR = 256 /* How many passes to cover whole hash table */
+#define REAP_MIN 16 /* Minimum = number of buckets per pass */
+#define REAP_MAX 1024 /* Maximum number of buckets per pas= s */

/*
* Mark a cache= d host route for deletion after this
@@ -596,7 +595,7 @@
struct timeval tv, current;

= CLEAR(tv);
-= m->earliest_wakeup =3D (struct multi_instance *) schedule_get_earlie= st_wakeup(m->schedule, &tv);
+ m->earliest_wakeup =3D (struct multi_instance *)sche= dule_get_earliest_wakeup(m->schedule, &tv);
if = (m->earliest_wakeup)
{
ASS= ERT(!openvpn_gettimeofday(&current, NULL));
@@ -641,9 += 640,7 @@

ASSERT(mi);
#ifdef MULTI_DEBUG_EVENT_LOOP

- printf("%s -> TUN len=3D%d\n",
- id(mi),
- mi->context.c2.to_tun.len);<= /span>
+ printf("%s = -> TUN len=3D%d\n", id(mi), mi->context.c2.to_tun.len); #endif
set_prefix(mi);
v= lan_process_outgoing_tun(m, mi);
@@ -653,12 +650,13 @@
return ret;
}
-#define CLIENT_CONNECT_OPT_MASK= (OPT_P_INSTANCE | OPT_P_INHERIT \
- |OPT_P_PUSH | OPT_P_TIMER |= OPT_P_CONFIG \
- = |OPT_P_ECHO | OPT_P_COMP | OPT_P_SOCKFLAGS)
+#define CLIENT_CONNECT= _OPT_MASK \
+ (OPT_P_INSTANCE | OP= T_P_INHERIT | OPT_P_PUSH | OPT_P_TIMER | OPT_P_CONFIG | OPT_P_ECHO \=
+ | OPT_P_COMP | OPT_P_= SOCKFLAGS)

static inline bool
= -multi_process_outgoing_link_dowo= rk(struct multi_context *m, struct multi_instance *mi, const unsigned int m= pp_flags)
+multi_proc= ess_outgoing_link_dowork(struct multi_context *m, struct multi_instance *mi= ,
+ = const unsigned int mpp_flags)
{ bool ret =3D true;
set_prefix(mi);<= br>diff --git a/src/openvpn/multi_io.c b/src/openvpn/multi_io.c
index 82f8372..ece789c 100644
--- a/src/openvpn/= multi_io.c
+++ b/src/openvpn/multi_io.c
@@ = -39,12 +39,12 @@
/*
* Special tags passe= d to event.[ch] functions
*/
-#define MULTI_IO_SOCKET ((void *)1)-#define MULTI_IO_TUN ((= void *)2)
-#define MULT= I_IO_SIG ((void *)3) /* Only on Windows */
-#define MULTI_IO_MANAGEMENT ((void *)4)=
+#define MULTI_IO_SOCKET = ((void *)1)
+= #define MULTI_IO_TUN ((void *)2)
+#define MULTI_IO_SIG ((void *)3) /* = Only on Windows */
+#= define MULTI_IO_MANAGEMENT ((void *)4)
#define MULTI= _IO_FILE_CLOSE_WRITE ((void *)5)
-#define MULTI_IO_DCO ((void *)6)
+#define MULTI_IO_DCO ((void *)6= )

struct ta_iow_flags
{=
@@ -127,7 +127,8 @@
wait_signal(multi= _io->es, MULTI_IO_SIG);
ALLOC_ARRAY(multi_io->es= r, struct event_set_return, multi_io->maxevents);
*= maxclients =3D max_int(min_int(multi_io->maxevents - extra_events, *maxc= lients), 1);
- msg(D= _MULTI_LOW, "MULTI IO: MULTI_IO INIT maxclients=3D%d maxevents=3D%d&qu= ot;, *maxclients, multi_io->maxevents);
+ msg(D_MULTI_LOW, "MULTI IO: MULTI_IO INIT m= axclients=3D%d maxevents=3D%d", *maxclients,
+ multi_io->maxevents);
return multi_io;

}

@@ -142,18 +143,13 @@

mi->socket_set_called =3D= true;
if (proto_is_dgram(mi->context.c2.link_socke= ts[0]->info.proto))
{
- socket_set(mi->context.c2.link_sockets[0= ],
- = m->multi_io->es,
= - EVENT_READ,
- &mi->context.c2.link_sockets[0]->ev_= arg,
- = NULL);
+ soc= ket_set(mi->context.c2.link_sockets[0], m->multi_io->es, EVENT_REA= D,
+ = &mi->context.c2.link_sockets[0]->ev_arg, NULL);
}

else
{
- socket_set(mi->context.c2.lin= k_sockets[0],
- = m->multi_io->es,
- mbuf_defined(mi->tcp_link_out_deferred) ?= EVENT_WRITE : EVENT_READ,
- &mi->ev_arg,
+ socket_set(mi->context.c2.link_sockets[0= ], m->multi_io->es,
+ mbuf_defined(mi->tcp_link_out_deferred) ? EVENT= _WRITE : EVENT_READ, &mi->ev_arg,
= &mi->tcp_rwflags);
}
}
@@ -197,7 +193,8 @@
#ifdef ENABLE_MANAGEMENT
if (management)
{
- management_socket_set(managemen= t, m->multi_io->es, MULTI_IO_MANAGEMENT, &m->multi_io->mana= gement_persist_flags);
+ = &m->multi_io->management_persist_flags);<= /span>
}
#endif

= @@ -206,7 +203,8 @@
event_ctl(m->multi_io->= ;es, m->top.c2.inotify_fd, EVENT_READ, MULTI_IO_FILE_CLOSE_WRITE);
#endif

- status =3D event_wait(m->multi_io->es, &m->= top.c2.timeval, m->multi_io->esr, m->multi_io->maxevents);
+ status =3D+ event_wait(m->mult= i_io->es, &m->top.c2.timeval, m->multi_io->esr, m->multi= _io->maxevents);
update_time();
= m->multi_io->n_esr =3D 0;
if (status > 0)
@@ -217,13 +215,13 @@
}

static int
-multi_io_wait_lite(struct multi_context *m, struct multi_instance *mi,= const int action, bool *tun_input_pending)
+multi_io_wait_lite(struct multi_context *m, struct = multi_instance *mi, const int action,
+ bool *tun_input_pending)
{

struct context *c =3D multi_get_context(m, mi);<= /span>
unsigned int looking_for =3D 0;

- dmsg(D_MULTI_DEBUG, &q= uot;MULTI IO: multi_io_wait_lite a=3D%s mi=3D" ptr_format,
<= span style=3D"color: hsl(0, 100%, 40%);">- pract(action),
+ dmsg(D_MULTI_DEBUG, "= ;MULTI IO: multi_io_wait_lite a=3D%s mi=3D" ptr_format, pract(action),=
(ptr_type)mi);

tv_clear(&c->c2.timeval); /* ZERO-TIMEOUT */

@= @ -254,7 +252,7 @@

case TA_SOCKE= T_WRITE:
looking_for =3D SOCKET_WRITE;<= br>- io_wait(c, IOW_TO= _LINK|IOW_READ_TUN_FORCE);
+ io_wait(c, IOW_TO_LINK | IOW_READ_TUN_FORCE);
= break;

defaul= t:
@@ -290,12 +288,11 @@
static struct mul= ti_instance *
multi_io_dispatch(struct multi_context *m, s= truct multi_instance *mi, const int action)
{
- const unsigned int mpp_flags = =3D MPP_PRE_SELECT|MPP_RECORD_TOUCH;

+ const unsigned int mpp_flags =3D MPP_PRE_SELECT | MPP_= RECORD_TOUCH;
struct multi_instance *touched =3D mi;
m->mpp_touched =3D &touched;

- dmsg(D_MULTI_DEBUG,= "MULTI IO: multi_io_dispatch a=3D%s mi=3D" ptr_format,- pract(action),<= br>+ dmsg(D_MULTI_DEBUG, &qu= ot;MULTI IO: multi_io_dispatch a=3D%s mi=3D" ptr_format, pract(action)= ,
(ptr_type)mi);

switch (action)

@@ -318,8 +315,7 @@
= clear_prefix();
if (!IS_SIG(&= mi->context))
{
- multi_process_incoming_link(m, mi= , mpp_flags,
- = mi->context.c2.link_sockets[0]);
+ multi_pr= ocess_incoming_link(m, mi, mpp_flags, mi->context.c2.link_sockets[0]);
if (!IS_SIG(&mi->context)) {
stream_buf_r= ead_setup(mi->context.c2.link_sockets[0]);
@@ -372,9 +36= 8,9 @@
struct context *c =3D multi_get_context(m, mi);=
int newaction =3D TA_UNDEF;
<= br>-#define MTP_NONE 0
-#define MTP_TUN_OUT = (1<<0)
-#define = MTP_LINK_OUT (1<<1)
+#define MTP_NONE 0
+#define MTP_TUN_OUT (1 << 0)
+#define MTP_LINK_OUT (1 << 1)
= unsigned int flags =3D MTP_NONE;

if (TUN_OUT(c))

@@ -388,7 +384,7 @@

switch (flags)
{
- case MTP_TUN_OUT|MTP_LINK_O= UT:

+ case MTP= _TUN_OUT | MTP_LINK_OUT:
case MTP_TUN_OUT:<= br> newaction =3D TA_TUN_WRITE;
= break;
@@ -412,16 +408,13 @@
{=
struct gc_arena gc =3D gc_new();
msg(M_FATAL, "MULTI IO: multi_io_post bad state, mi= =3D%s flags=3D%d",

- multi_instance_string(mi, false, &gc),
- flags);

+ multi_instance_s= tring(mi, false, &gc), flags);

gc_free(&am= p;gc);
break;
}
}

- dmsg(D_MULTI_DEBUG, "MULTI IO: multi_io_post %s ->= ; %s",
- p= ract(action),
- = pract(newaction));
+= dmsg(D_MULTI_DEBUG, "MULTI IO: multi_io_post %s -> %s", pr= act(action), pract(newaction));

retu= rn newaction;
}
@@ -500,47 +493,47 @@
}
else
#endif

- = /* incoming data on TUN? */
- if (e->arg =3D=3D MULTI_IO_TUN)
- {
- if (e->rwflags & EVENT_WRITE= )
+ /*= incoming data on TUN? */
+ if (e->arg =3D=3D MULTI_IO_TUN)
= {
- = multi_io_action(m, NULL, TA_TUN_WRITE, false);
+ if (e->rwf= lags & EVENT_WRITE)

+ {
+ multi_io_action(m, NULL, TA_TUN_WRITE, false)= ;
+ = }
+ = else if (e->rwflags & EVENT_READ)
+ {
+ multi_io_action(m, NULL,= TA_TUN_READ, false);
+ }
}
- else if (e->rwflags= & EVENT_READ)
+ = /* new incoming TCP client attempting to connect? */<= br>+ else if (e-= >arg =3D=3D MULTI_IO_SOCKET)
{- multi_io_a= ction(m, NULL, TA_TUN_READ, false);
+ struct multi_instance *mi;
+ ASSERT(m->= ;top.c2.link_sockets[0]);

+ socket_reset_listen_persistent(m->top.c2.link_= sockets[0]);
+ = mi =3D multi_create_instance_tcp(m, m->top.c2.link_sockets[= 0]);
+ = if (mi)
+ = {
+ = multi_io_action(m, mi, TA_INITIAL, false);
+ }

<= span> }

- }
- = /* new incoming TCP client attempting to connect? */
- else if (e->arg =3D=3D = MULTI_IO_SOCKET)
- = {
- = struct multi_instance *mi;
- ASSERT(m->top.c2.link_sockets[0]);
- socket_reset_listen= _persistent(m->top.c2.link_sockets[0]);

- mi =3D multi_create_instance_tcp(m, m-= >top.c2.link_sockets[0]);
- if (mi)
- {
- multi_io_action(m, mi, TA_INITIAL, false);<= br>- }
<= span style=3D"color: hsl(0, 100%, 40%);">- }

#i= f defined(ENABLE_DCO)
-= /* incoming data on DCO? */
- else if (e->arg =3D=3D MULTI_IO_DCO)
- {
- multi_process_incom= ing_dco(m);

- = }
+ = /* incoming data on DCO? */
+ else if (e->arg =3D=3D MULTI_IO_DCO)
<= span style=3D"color: hsl(120, 100%, 40%);">+ {

+ multi_process= _incoming_dco(m);

+ = }
#endif
- /* signal received? */
- else if (e->arg =3D=3D MULTI= _IO_SIG)
- {=
- get_s= ignal(&m->top.sig->signal_received);
- }
+ /* signal received? */
+ else if (e->arg = =3D=3D MULTI_IO_SIG)
= + {
+ = get_signal(&m->top.sig->signal_received);
+ }=
#ifdef ENABLE_ASYNC_PUSH
- else if (e->arg =3D=3D MULTI_IO_FILE_CLOSE_WRI= TE)
- {
- multi_proc= ess_file_closed(m, MPP_PRE_SELECT | MPP_RECORD_TOUCH);
- }
+ else if (e->arg =3D=3D MULTI_= IO_FILE_CLOSE_WRITE)
= + {
+ = multi_process_file_closed(m, MPP_PRE_SELECT | MPP_RECORD= _TOUCH);
+ = }
#endif
}
= if (IS_SIG(&m->top))
@@ -569,9 +562,7 @@

do
{
- dmsg(D_MULTI_DEBUG, "M= ULTI IO: multi_io_action a=3D%s p=3D%d",

- pract(action),
- poll);
+ dmsg(D_MULTI_DEBUG, "MULTI I= O: multi_io_action a=3D%s p=3D%d", pract(action), poll);

/*
* If TA_SOCKET_R= EAD_RESIDUAL, it means we still have pending
@@ -590,7 +581= ,8 @@
action =3D multi_io_wait_lite(m, mi, act= ion, &tun_input_pending);
if (action =3D= =3D TA_UNDEF)
{
- msg(M_FATAL, "MULTI IO: I/O wai= t required blocking in multi_io_action, action=3D%d", orig_action);
+ msg(M_= FATAL, "MULTI IO: I/O wait required blocking in multi_io_action, actio= n=3D%d",
+ = orig_action);
}
= }

diff --git a/src/openvpn/netwo= rking.h b/src/openvpn/networking.h
index eccd8d2..6c253f9 1= 00644
--- a/src/openvpn/networking.h
+++ b/= src/openvpn/networking.h
@@ -101,8 +101,8 @@
*

* @return 0 on success, negative error cod= e on error
*/
-int net_iface_new(openvpn_net_ctx_t *ctx, const openvpn_net_iface= _t *iface,
- = const char *type, void *arg);
+int net_iface_new(openvpn_net_ctx_t *ctx, const openvpn_ne= t_iface_t *iface, const char *type,
+ void *arg);

<= span> /**

* Retrieve the interface type
@= @ -113,8 +113,7 @@
*
* @return = 0 on success, a negative error code otherwise
*/<= br>-int net_iface_type(openvpn_ne= t_ctx_t *ctx, const char *iface,
- char type[IFACE_TYPE_LEN_MAX]);
+int net_iface_type(openvpn_net_ct= x_t *ctx, const char *iface, char type[IFACE_TYPE_LEN_MAX]);


/**
* Remove an interface
= @@ -134,8 +133,7 @@
*
* @return = 0 on success, a negative error code otherwise
*/<= /span>
-int net_iface_up(openv= pn_net_ctx_t *ctx, const openvpn_net_iface_t *iface,
- bool up);
+int net_iface_up(openvpn_net_ctx_t *= ctx, const openvpn_net_iface_t *iface, bool up);
/**
* Set the MTU for an interface
@@ -146,8 +144,7 @@

*
* @return = 0 on success, a negative error code otherwise
*/
-int net_iface_mtu_set(ope= nvpn_net_ctx_t *ctx,
- = const openvpn_net_iface_t *iface, uint32_t mtu);
+int net_iface_mtu_set(ope= nvpn_net_ctx_t *ctx, const openvpn_net_iface_t *iface, uint32_t mtu);

/**
* Set the Link Layer (E= thernet) address of the TAP interface
@@ -158,8 +155,7 @@
*
* @return 0 on success, a neg= ative error code otherwise
*/
-int net_addr_ll_set(openvpn_net_ctx_t *ctx, const= openvpn_net_iface_t *iface,
- uint8_t *addr);
+int net_addr_ll_set(openvpn_net_ctx_t *ctx, const op= envpn_net_iface_t *iface, uint8_t *addr);

/**

* Add an IPv4 address to an interface
@@ -171,8 +167,8 @@

*
* @return = 0 on success, a negative error code otherwise
*/
-int net_addr_v4_add(openv= pn_net_ctx_t *ctx, const openvpn_net_iface_t *iface,
- const in_addr_t *addr, = int prefixlen);
+int = net_addr_v4_add(openvpn_net_ctx_t *ctx, const openvpn_net_iface_t *iface, c= onst in_addr_t *addr,
+ int prefixlen);

/*= *
* Add an IPv6 address to an interface
@= @ -197,8 +193,8 @@
*
* @return = 0 on success, a negative error code otherwise
*/<= br>-int net_addr_v4_del(openvpn_n= et_ctx_t *ctx, const openvpn_net_iface_t *iface,
- const in_addr_t *addr, int p= refixlen);
+int net_a= ddr_v4_del(openvpn_net_ctx_t *ctx, const openvpn_net_iface_t *iface, const = in_addr_t *addr,
+ = int prefixlen);

/**
* Remove an IPv6 from an interface
@@ -222,8= +218,7 @@
*
* @return 0 on su= ccess, a negative error code otherwise
*/
-int net_addr_ptp_v4_add(openvpn_net_c= tx_t *ctx,

- = const openvpn_net_iface_t *iface,
+int net_addr_ptp_v4_add(openvpn_net_ctx_t *ctx, = const openvpn_net_iface_t *iface,
= const in_addr_t *local, const in_addr_t *remote);
<= br> /**
@@ -236,8 +231,7 @@
*
* @return 0 on success, a negative error code otherwi= se
*/
-int net_addr_ptp_v4_del(openvpn_net_ctx_t *ctx,
- const openvpn_net_iface= _t *iface,
+int net_a= ddr_ptp_v4_del(openvpn_net_ctx_t *ctx, const openvpn_net_iface_t *iface,
const in_addr_t *local, const in_add= r_t *remote);

#endif /* ENABLE_SITNL || = ENABLE_IPROUTE */
@@ -257,9 +251,8 @@
*
* @return 0 on success, a negative error code oth= erwise
*/
-int net_route_v4_add(openvpn_net_ctx_t *ctx, const in_addr_t *dst,
- int= prefixlen, const in_addr_t *gw,
- const openvpn_net_iface_t *iface, uint32_t = table,
+int net_route= _v4_add(openvpn_net_ctx_t *ctx, const in_addr_t *dst, int prefixlen,=
+ const= in_addr_t *gw, const openvpn_net_iface_t *iface, uint32_t table, int metric);

/**

@@ -276,10 +269,9 @@
*
* @return 0 on success, a negative error code otherwise
*/
-int n= et_route_v6_add(openvpn_net_ctx_t *ctx, const struct in6_addr *dst,<= br>- int pref= ixlen, const struct in6_addr *gw,
- const openvpn_net_iface_t *iface,- uint32_t = table, int metric);
+= int net_route_v6_add(openvpn_net_ctx_t *ctx, const struct in6_addr *dst, in= t prefixlen,
+ = const struct in6_addr *gw, const openvpn_net_iface_t *iface, = uint32_t table,
+ = int metric);

/**=
* Delete a route for an IPv4 address/network
@@= -295,9 +287,8 @@
*
* @return = 0 on success, a negative error code otherwise
*/-int net_route_v4_del(openvpn_n= et_ctx_t *ctx, const in_addr_t *dst,
- int prefixlen, const in_addr_t *gw,
- cons= t openvpn_net_iface_t *iface, uint32_t table,
+int net_route_v4_del(openvpn_net_ctx_t *ctx, cons= t in_addr_t *dst, int prefixlen,
+ const in_addr_t *gw, const openvpn_net_if= ace_t *iface, uint32_t table,
int met= ric);

/**
@@ -314,10 +30= 5,9 @@
*
* @return 0 on succes= s, a negative error code otherwise
*/
-int net_route_v6_del(openvpn_net_ctx_t *c= tx, const struct in6_addr *dst,
- int prefixlen, const struct in6_addr *gw,

- con= st openvpn_net_iface_t *iface,
- uint32_t table, int metric);
+int net_route_v6_del(openvpn_net_ctx= _t *ctx, const struct in6_addr *dst, int prefixlen,
+ const struct in6_add= r *gw, const openvpn_net_iface_t *iface, uint32_t table,
+ int metric);

#endif /* ENABLE_SITNL || ENABLE_IPROUTE || = TARGET_FREEBSD */

@@ -334,8 +324,8 @@
*
* @return 0 on success, a n= egative error code otherwise
*/
-int net_route_v4_best_gw(openvpn_net_ctx_t *ctx= , const in_addr_t *dst,
- in_addr_t *best_gw, openvpn_net_iface_t *best_if= ace);
+int net_route_= v4_best_gw(openvpn_net_ctx_t *ctx, const in_addr_t *dst, in_addr_t *best_gw= ,
+ = openvpn_net_iface_t *best_iface);

= /**
* Retrieve the gateway and outgoing interface for th= e specified IPv6
@@ -349,8 +339,7 @@
* @r= eturn 0 on success, a negative error code otherwise
= */
int net_route_v6_best_gw(openvpn_net_ctx_t *ctx= , const struct in6_addr *dst,
- struct in6_addr *best_gw,
- openvpn_net_i= face_t *best_iface);
= + struct in6_addr *best_gw, openvpn_net_iface_t *be= st_iface);

#endif /* ENABLE_SITNL || ENA= BLE_IPROUTE */

diff --git a/src/openvpn/n= etworking_freebsd.c b/src/openvpn/networking_freebsd.c
inde= x 1c94756..b47444c 100644
--- a/src/openvpn/networking_free= bsd.c
+++ b/src/openvpn/networking_freebsd.c
@@ -9,9 +9,8 @@

#if defined(TARGET_FREEBSD)

static int
-net_route_v4(const char *op, const in_addr_t *dst, int prefixle= n,
- const = in_addr_t *gw, const char *iface, uint32_t table,
- int metric)
+net_route_v4(const char *op, const in_add= r_t *dst, int prefixlen, const in_addr_t *gw,
+ const char *iface, uint32_t table, i= nt metric)
{
char buf1[INET_ADDRSTRLE= N], buf2[INET_ADDRSTRLEN];
in_addr_t _dst, _gw;=
@@ -21,16 +20,12 @@
_dst =3D ntohl(*dst);
_gw =3D ntohl(*gw);

- argv_printf(&argv, "%s %s -= net %s/%d %s -fib %d",
- ROUTE_PATH, op,
- inet_ntop(AF_INET, &_dst, buf1, sizeof(= buf1)),
- = prefixlen,
- = inet_ntop(AF_INET, &_gw, buf2, sizeof(buf2)),
- table);
+ argv_printf(&argv, "%s = %s -net %s/%d %s -fib %d", ROUTE_PATH, op,
+ inet_ntop(AF_INET, &_dst, b= uf1, sizeof(buf1)), prefixlen,
+ inet_ntop(AF_INET, &_gw, buf2, sizeof(buf2))= , table);

argv_msg(M_INFO, &argv= );
- status =3D open= vpn_execve_check(&argv, NULL, 0,
- "ERROR: FreeBSD route= command failed");
+ status =3D openvpn_execve_check(&argv, NULL, 0, "ERROR: Fr= eeBSD route command failed");

a= rgv_free(&argv);

@@ -38,24 +33,19 @@<= /span>
}

static int
= -net_route_v6(const char *op, con= st struct in6_addr *dst,
- uint32_= t table, int metric)
= +net_route_v6(const char *op, const struct in6_addr *dst, int prefixlen, co= nst struct in6_addr *gw,
+ const char *iface, uint32_t table, int metric)
= {
char buf1[INET6_ADDRSTRLEN], buf2[INET6_ADDRS= TRLEN];
struct argv argv =3D argv_new();
bool status;


- argv_printf(&argv, "%s -6 %s -net %s/%d %s -f= ib %d",
- = ROUTE_PATH, op,
= - inet_ntop(AF_INET6, dst, buf1, sizeof(buf1)),
- prefixlen,
<= br>- inet_ntop(AF_= INET6, gw, buf2, sizeof(buf2)),
- table);
+ argv_printf(&argv, "%s -6 %s -net %s/%d %s -fib = %d", ROUTE_PATH, op,
+ inet_ntop(AF_INET6, dst, buf1, sizeof(buf1)), prefixl= en,
+ = inet_ntop(AF_INET6, gw, buf2, sizeof(buf2)), table);

argv_msg(M_INFO, &argv);
- status =3D openvpn_execve_check(&argv, NULL= , 0,
- = "ERROR: FreeBSD route command failed");+ status =3D openvpn_execv= e_check(&argv, NULL, 0, "ERROR: FreeBSD route command failed"= );

argv_free(&argv);
<= span>

@@ -63,33 +53,29 @@
}

int
-net_route_v4_add(openvpn_net_ctx_t *ctx, const in_addr_t *dst, int pref= ixlen,
- = const in_addr_t *gw, const char *iface, uint32_t table,
- int metric)
= +net_route_v4_add(openvpn_net_c= tx_t *ctx, const in_addr_t *dst, int prefixlen, const in_addr_t *gw,=
+ const cha= r *iface, uint32_t table, int metric)
{
= return net_route_v4("add", dst, prefixlen, gw, iface, table, m= etric);
}

int-net_route_v6_add(openvpn_net_ct= x_t *ctx, const struct in6_addr *dst,
- int prefixlen, const struct in6_addr *gw, = const char *iface,
- = uint32_t table, int metric)
+net_route_v6_add(openvpn_net_ctx_t *ctx, const struct= in6_addr *dst, int prefixlen,
+ const struct in6_addr *gw, const char *iface, u= int32_t table, int metric)
{
return n= et_route_v6("add", dst, prefixlen, gw, iface, table, metric);
}

int
-net_route_v4_del(openvpn_net_ctx_t *ctx, c= onst in_addr_t *dst, int prefixlen,
- const in_addr_t *gw, const char *iface, uint= 32_t table,
- = int metric)
+n= et_route_v4_del(openvpn_net_ctx_t *ctx, const in_addr_t *dst, int prefixlen= , const in_addr_t *gw,
-ne= t_route_v6_del(openvpn_net_ctx_t *ctx, const struct in6_addr *dst,- int prefixlen= , const struct in6_addr *gw, const char *iface,
- uint32_t table, int metric)
+net_route_v6_del(openvpn= _net_ctx_t *ctx, const struct in6_addr *dst, int prefixlen,
+ const struct in6_a= ddr *gw, const char *iface, uint32_t table, int metric)

{<= /span>
return net_route_v6("del", dst, prefixlen, g= w, iface, table, metric);
}
diff --git a/s= rc/openvpn/networking_iproute2.c b/src/openvpn/networking_iproute2.c=
index ec8ab1e..0635b5d 100644
--- a/src/openvpn/n= etworking_iproute2.c
+++ b/src/openvpn/networking_iproute2.= c
@@ -61,8 +61,7 @@
}

int
-net= _iface_new(openvpn_net_ctx_t *ctx, const char *iface, const char *type,
- void *arg)<= /span>
+net_iface_new(openvp= n_net_ctx_t *ctx, const char *iface, const char *type, void *arg) {
struct argv argv =3D argv_new();
<= span>

@@ -76,8 +75,7 @@
}

int
-net_iface_type(openvpn_net_ctx_t *ctx, const char *iface,
- char type[IFACE_TYPE_L= EN_MAX])

+net_iface_t= ype(openvpn_net_ctx_t *ctx, const char *iface, char type[IFACE_TYPE_LEN_MAX= ])
{
/* not supported by iproute2 */<= /span>
msg(M_WARN, "%s: operation not supported by iprou= te2 backend", __func__);
@@ -102,8 +100,7 @@ {
struct argv argv =3D argv_new();
<= span>

- argv_printf= (&argv, "%s link set dev %s %s", iproute_path, iface,<= br>- up ? "up= " : "down");
+ argv_printf(&argv, "%s link set dev %s %s", iprou= te_path, iface, up ? "up" : "down");
= argv_msg(M_INFO, &argv);
openvpn_execve_check(&= amp;argv, ctx->es, S_FATAL, "Linux ip link set failed");

@@ -117,8 +114,7 @@
{<= br> struct argv argv =3D argv_new();

= - argv_printf(&argv, "= ;%s link set dev %s up mtu %d", iproute_path, iface,
- mtu);
+ argv_printf(&argv, "%s l= ink set dev %s up mtu %d", iproute_path, iface, mtu);
= argv_msg(M_INFO, &argv);
openvpn_execve_check= (&argv, ctx->es, S_FATAL, "Linux ip link set failed");

@@ -128,19 +124,16 @@
}

int
-net_addr_ll_set(openvpn_net_ctx_t *ctx, const openvpn_net_ifa= ce_t *iface,
- = uint8_t *addr)
+net_addr_ll_set(openvpn_net_ctx_t *ctx, const openvpn_net_iface_t *iface,= uint8_t *addr)
{
struct argv argv = =3D argv_new();
int ret =3D 0;

- argv_printf(&argv,<= /span>
- "= %s link set addr " MAC_FMT " dev %s",
- iproute_path, MAC_PRINT_ARG= (addr), iface);
+ = argv_printf(&argv, "%s link set addr " MAC_FMT " dev %s&= quot;, iproute_path, MAC_PRINT_ARG(addr),
+ iface);

<= span> argv_msg(M_INFO, &argv);

- if (!openvpn_execve_check(&argv, ctx->es, 0,
- = "Linux ip link set addr failed"))
+ if (!openvpn_execve_check(&argv, ctx-= >es, 0, "Linux ip link set addr failed"))
= {
ret =3D -1;
}
@@ -151,15 +144,13 @@

}

int

-net_addr_v4_a= dd(openvpn_net_ctx_t *ctx, const char *iface,
- const in_addr_t *addr, int prefixle= n)
+net_addr_v4_add(o= penvpn_net_ctx_t *ctx, const char *iface, const in_addr_t *addr, int prefix= len)
{
struct argv argv =3D argv_new(= );

const char *addr_str =3D print_in= _addr_t(*addr, 0, &ctx->gc);

- argv_printf(&argv, "%s addr ad= d dev %s %s/%d", iproute_path, iface,
- addr_str, prefixlen);
+ argv_printf(&argv, "%s = addr add dev %s %s/%d", iproute_path, iface, addr_str, prefixlen);
argv_msg(M_INFO, &argv);
openvpn= _execve_check(&argv, ctx->es, S_FATAL, "Linux ip addr add faile= d");

@@ -169,17 +160,15 @@ }

int
-net_addr_v6_add(openvpn_net_ctx_t *ctx, const ch= ar *iface,
- = const struct in6_addr *addr, int prefixlen)
+net_addr_v6_add(openvpn_net_ctx_t *ctx, const = char *iface, const struct in6_addr *addr,
+ int prefixlen)
{
struct argv argv =3D argv_new();
cha= r *addr_str =3D (char *)print_in6_addr(*addr, 0, &ctx->gc);
- argv_pri= ntf(&argv, "%s -6 addr add %s/%d dev %s", iproute_path, addr_= str,
- p= refixlen, iface);
+ = argv_printf(&argv, "%s -6 addr add %s/%d dev %s", iproute_p= ath, addr_str, prefixlen, iface);
argv_msg(M_INFO, &am= p;argv);
- openvpn_e= xecve_check(&argv, ctx->es, S_FATAL,
- "Linux ip -6 addr add f= ailed");
+ op= envpn_execve_check(&argv, ctx->es, S_FATAL, "Linux ip -6 addr a= dd failed");

argv_free(&arg= v);

@@ -187,14 +176,12 @@
}


int
-net_addr_v4_del(openvpn_net_ctx_t *ctx, const char *if= ace,
- c= onst in_addr_t *addr, int prefixlen)
+net_addr_v4_del(openvpn_net_ctx_t *ctx, const char *iface,= const in_addr_t *addr, int prefixlen)
{
= struct argv argv =3D argv_new();
const char *addr_= str =3D print_in_addr_t(*addr, 0, &ctx->gc);

- argv_printf(&argv, = "%s addr del dev %s %s/%d", iproute_path, iface,
- addr_str, prefixlen);<= /span>
+ argv_printf(&= ;argv, "%s addr del dev %s %s/%d", iproute_path, iface, addr_str,= prefixlen);

argv_msg(M_INFO, &a= rgv);
openvpn_execve_check(&argv, ctx->es, 0, &= quot;Linux ip addr del failed");
@@ -205,14 +192,13 @@=
}

int
-net_addr_v6_del(openvpn_net_ctx_t *ctx= , const char *iface,
- = const struct in6_addr *addr, int prefixlen)
+net_addr_v6_del(openvpn_net_ctx_t *c= tx, const char *iface, const struct in6_addr *addr,
+ int prefixlen)
= {
struct argv argv =3D argv_new();
char *addr_str =3D (char *)print_in6_addr(*addr, 0, &ctx->g= c);


-= argv_printf(&argv, "%s -6 addr del %s/%d dev %s", iproute= _path,
- = addr_str, prefixlen, iface);
+ argv_printf(&argv, "%s -6 addr del %s/%d dev %s"= ;, iproute_path, addr_str, prefixlen, iface);
argv_msg= (M_INFO, &argv);
openvpn_execve_check(&argv, c= tx->es, 0, "Linux ip -6 addr del failed");

@@ -222,15 +208,15 @@
}

int
-ne= t_addr_ptp_v4_add(openvpn_net_ctx_t *ctx, const char *iface,
- const in_addr_t = *local, const in_addr_t *remote)

+net_addr_ptp_v4_add(openvpn_net_ctx_t *ctx, const char *iface,= const in_addr_t *local,
+ const in_addr_t *remote)
{=
struct argv argv =3D argv_new();
const = char *local_str =3D print_in_addr_t(*local, 0, &ctx->gc);
= const char *remote_str =3D print_in_addr_t(*remote, 0, &ctx-= >gc);

- argv_printf(&argv, "%s addr add dev %s local %s peer %s&q= uot;, iproute_path,
- = iface, local_str, remote_str);
+ argv_printf(&argv, "%s addr add dev %= s local %s peer %s", iproute_path, iface, local_str,
+ remote_str); argv_msg(M_INFO, &argv);
openvpn_exec= ve_check(&argv, ctx->es, S_FATAL, "Linux ip addr add failed&quo= t;);

@@ -240,15 +226,15 @@
}


int
-net_addr_ptp_v4_del(openvpn_net_ctx_t *ctx, const cha= r *iface,
- = const in_addr_t *local, const in_addr_t *remote)
+net_addr_ptp_v4_del(openvpn_net_ctx_t = *ctx, const char *iface, const in_addr_t *local,
+ const in_addr_t *remote)
{
struct argv argv =3D argv_new();
const char *local_str =3D print_in_addr_t(*local, 0, &= ;ctx->gc);
const char *remote_str =3D print_in_addr= _t(*remote, 0, &ctx->gc);

- argv_printf(&argv, "%s addr del d= ev %s local %s peer %s", iproute_path,
- iface, local_str, remote_str);=
+ argv_printf(&argv,= "%s addr del dev %s local %s peer %s", iproute_path, iface, loca= l_str,
+ = remote_str);
argv_msg(M_INFO, &argv); openvpn_execve_check(&argv, ctx->es, 0, "Linux ip a= ddr del failed");

@@ -258,9 +244,8 @= @
}

int
-net_route_v4_add(openvpn_net_ctx_t *c= tx, const in_addr_t *dst, int prefixlen,

- const in_addr_t *gw, const char *iface,= uint32_t table,
- = int metric)
+net_route_v4_add(openvpn_net_ctx_t *ctx, const in_addr_t *dst, int pref= ixlen, const in_addr_t *gw,
+ const char *iface, uint32_t table, int metric)
{
struct argv argv =3D argv_new();
const char *dst_str =3D print_in_addr_t(*dst, 0, &ctx-&= gt;gc);
@@ -297,16 +282,14 @@
}
=
int
-net_route_v6_add(openvpn_net_ctx_t *ctx, const struct in6_addr *dst,=
- int = prefixlen, const struct in6_addr *gw, const char *iface,
- uint32_t table, int met= ric)
+net_route_v6_ad= d(openvpn_net_ctx_t *ctx, const struct in6_addr *dst, int prefixlen,=
+ const str= uct in6_addr *gw, const char *iface, uint32_t table, int metric)
= {
struct argv argv =3D argv_new();
char *dst_str =3D (char *)print_in6_addr(*dst, 0, &ctx->gc)= ;

int ret =3D 0;

- argv_printf(&argv, "%s -6 ro= ute add %s/%d dev %s", iproute_path, dst_str,
- prefixlen, iface);
<= span style=3D"color: hsl(120, 100%, 40%);">+ argv_printf(&argv, &quo= t;%s -6 route add %s/%d dev %s", iproute_path, dst_str, prefixlen, ifa= ce);


if (gw)
{<= /span>
@@ -332,9 +315,8 @@
}

int
-net= _route_v4_del(openvpn_net_ctx_t *ctx, const in_addr_t *dst, int prefixlen,<= /span>
- const= in_addr_t *gw, const char *iface, uint32_t table,
- int metric)
+net_route_v4_del(openvpn_net_ctx_t *c= tx, const in_addr_t *dst, int prefixlen, const in_addr_t *gw,
+ const char *ifac= e, uint32_t table, int metric)

{
stru= ct argv argv =3D argv_new();
const char *dst_str =3D p= rint_in_addr_t(*dst, 0, &ctx->gc);
@@ -359,16 +341,1= 4 @@
}

int
-net_route_v6_del(openvpn_net_ctx_t= *ctx, const struct in6_addr *dst,

- int prefixlen, const struct in6_addr *gw, con= st char *iface,
- = uint32_t table, int metric)
+net_route_v6_del(openvpn_net_ctx_t *ctx, const struct in= 6_addr *dst, int prefixlen,
+ const struct in6_addr *gw, const char *iface, uint= 32_t table, int metric)
{
struct argv= argv =3D argv_new();
char *dst_str =3D (char *)print_= in6_addr(*dst, 0, &ctx->gc);
int ret =3D 0;

- arg= v_printf(&argv, "%s -6 route del %s/%d dev %s", iproute_path,= dst_str,
- = prefixlen, iface);
-#define SITNL_ADDATTR(_msg, _max_size, _att= r, _data, _size) \
- { \<= /span>
+#define SITNL_ADDATT= R(_msg, _max_size, _attr, _data, _size) \
+ { = \
if (sitnl_addattr(_msg,= _max_size, _attr, _data, _size) < 0) \
- { = \
- = goto err; \
<= span style=3D"color: hsl(0, 100%, 40%);">- } = \

+ { = \
+ = goto err; \
<= span style=3D"color: hsl(120, 100%, 40%);">+ } = \

}

#define SITNL_NEST(_msg, _max_size, _attr) = \
@@ -58,8 +58,8 @@
_nest; = \
})
<= span>

-#define SITNL_N= EST_END(_msg, _nest) \
- { = \
+#define SITNL_NEST_END(_msg, _nest) = \
+ = { \
_nest->rta_len =3D (void *)sitnl_nlmsg_tail(_msg) -= (void *)_nest; \
}

= @@ -73,7 +73,7 @@
* The only way out to avoid any warning= /error is to force the function to
* not be inline'd.=
*/
-= static __attribute__ ((noinline)) void *
+static __attribute__((noinline)) void *
sitnl_nlmsg_tail(const struct nlmsghdr *nlh)

{ return (unsigned char *)nlh + NLMSG_ALIGN(nlh->nlmsg_len);<= /span>
@@ -83,7 +83,8 @@
* Generic address data = structure used to pass addresses and prefixes as
* argume= nt to AF family agnostic functions
*/
-typedef union {
+typedef union
+{
in_addr_t ipv4;
struct in6_addr ipv6;

} inet_address_t;@@ -91,7 +92,8 @@
/**
* Link stat= e request message
*/
-struct sitnl_link_req {
+struct sitnl_link_req
+{
struct nlmsghdr n;
= struct ifinfomsg i;
char buf[256];@@ -100,7 +102,8 @@
/**
* Addres= s request message
*/
-struct sitnl_addr_req {
+struct sitnl_addr_req
+{
struct nlmsghdr n;
= struct ifaddrmsg i;
char buf[256];@@ -109,7 +112,8 @@
/**
* Route = request message
*/
-struct sitnl_route_req {
+struct sitnl_route_req
+{
struct nlmsghdr n;
= struct rtmsg r;
char buf[256];
@@ -120,7 +124,8 @@

/**
* Object ret= urned by route request operation
*/
-struct sitnl_route_data_cb {
+struct sitnl_route_data_cb
<= br>+{
unsi= gned int iface;
inet_address_t gw;
};=
@@ -129,16 +134,14 @@
* Helper function = used to easily add attributes to a rtnl message
*/=
static int
-= sitnl_addattr(struct nlmsghdr *n, int maxlen, int type, const void *data,
- int alen)=
+sitnl_addattr(struc= t nlmsghdr *n, int maxlen, int type, const void *data, int alen)
= {
int len =3D RTA_LENGTH(alen);
struct rtattr *rta;


if ((int)(= NLMSG_ALIGN(n->nlmsg_len) + RTA_ALIGN(len)) > maxlen)
{

- msg(M_= WARN, "%s: rtnl: message exceeded bound of %d", __func__,<= br>- maxlen);+ msg(M_WARN, "%s= : rtnl: message exceeded bound of %d", __func__, maxlen);
return -EMSGSIZE;

}

@@ -240,8 +243,8 @@
* Send Netlink message a= nd run callback on reply (if specified)
*/
static int

-sitnl_se= nd(struct nlmsghdr *payload, pid_t peer, unsigned int groups,
- sitnl_parse_reply_cb cb,= void *arg_cb)

+sitnl= _send(struct nlmsghdr *payload, pid_t peer, unsigned int groups, sitnl_pars= e_reply_cb cb,
+ = void *arg_cb)
{
int len, rem_le= n, fd, ret, rcv_len;
struct sockaddr_nl nladdr;=
@@ -249,13 +252,11 @@
struct nlmsghdr *h;
unsigned int seq;
char buf[1024 * 1= 6];
- struct iovec i= ov =3D
- {+ struct iovec iov =3D {
.iov_base =3D payload,
.iov= _len =3D payload->nlmsg_len,
};
- struct msghdr nlmsg =3D
- {

+ struct msghdr nlmsg =3D {
= .msg_name =3D &nladdr,
.msg_namelen =3D = sizeof(nladdr),
.msg_iov =3D &iov,
<= span>@@ -334,8 +335,8 @@


if (nlm= sg.msg_namelen !=3D sizeof(nladdr))
{
- msg(M_WARN, "%s: = sender address length: %u (expected %zu)",

- __func__, nlmsg.msg_namelen, size= of(nladdr));
+ = msg(M_WARN, "%s: sender address length: %u (expected %zu)", = __func__, nlmsg.msg_namelen,
+ sizeof(nladdr));
ret = =3D -EIO;
goto out;
}=
@@ -359,17 +360,18 @@
got= o out;
}

-/* if (((int)nladdr.nl_pid != =3D peer) || (h->nlmsg_pid !=3D nladdr.nl_pid)
- * || (h->nlmsg_seq !=3D seq))=
- * {=
- * rcv_len -= =3D NLMSG_ALIGN(len);
-= * h =3D (struct nlmsghdr *)((char *)h + NLMSG_ALIGN(len));
- * msg(M_= DEBUG, "%s: skipping unrelated message. nl_pid:%d (peer:%d) nl_msg_pid= :%d nl_seq:%d seq:%d",
- * __func__, (int)nladdr.nl_pid, peer, h->nlmsg_= pid,
- * = h->nlmsg_seq, seq);
- * continue;
- * }
+ /= * if (((int)nladdr.nl_pid !=3D peer) || (h->nlmsg_pid !=3D nl= addr.nl_pid)
+ = * || (h->nlmsg_seq !=3D seq))
+ * {
+ * rcv_l= en -=3D NLMSG_ALIGN(len);

+ * h =3D (struct nlmsghdr *)((char *)h + NL= MSG_ALIGN(len));
+ = * msg(M_DEBUG, "%s: skipping unrelated message= . nl_pid:%d (peer:%d)
+ * nl_msg_pid:%d nl_seq:%d seq:%d",
+ * __func_= _, (int)nladdr.nl_pid, peer, h->nlmsg_pid,
+ * h->nlmsg_seq,= seq);
+ = * continue;
+ * }
+ */

= if (h->nlmsg_type =3D=3D NLMSG_DONE)
{
@@ -401,8 +403,8 @@
}
else
= {
- = msg(M_WARN, "%s: rtnl: generic error (%d): %s",
- __func= __, err->error, strerror(-err->error));

+ msg(M_WARN, "%s: rtn= l: generic error (%d): %s", __func__, err->error,
+ strerror(= -err->error));
ret =3D err->= error;
}
= }
@@ -446,7 +448,8 @@
return ret;<= /span>
}

-typedef struct {
+typedef struct
+{
int addr_size;
inet_addr= ess_t gw;
char iface[IFNAMSIZ];
@@ -50= 8,8 +511,7 @@

if (!if_indextoname(if= index, res->iface))
{
- msg(M_WARN | M_ERRNO, "%s: rtnl: can&#= 39;t get ifname for index %d",
- __func__, ifindex);
+ msg(M_WARN | M_ERRNO, "%s: rtnl: can= 't get ifname for index %d", __func__, ifindex);
= return -1;
}

@@ -522,8 +524,8 @@

}

= static int
-sitnl_route= _best_gw(sa_family_t af_family, const inet_address_t *dst,
- void *best_gw, cha= r *best_iface)
+sitnl= _route_best_gw(sa_family_t af_family, const inet_address_t *dst, void *best= _gw,
+ = char *best_iface)
{
struct sitnl= _route_req req;
route_res_t res;
@@ -5= 85,15 +587,14 @@
strncpy(best_iface, res.iface, IFNAMS= IZ);
err:
return ret;
-

}
=
/* used by iproute2 implementation too */
int

-net_route_v6_bes= t_gw(openvpn_net_ctx_t *ctx, const struct in6_addr *dst,
- struct in6_addr *be= st_gw, char *best_iface)
+net_route_v6_best_gw(openvpn_net_ctx_t *ctx, const struct in6_addr *ds= t, struct in6_addr *best_gw,
+ char *best_iface)
{- inet_address_t dst_v6 =3D = {0};
+ inet_addres= s_t dst_v6 =3D { 0 };
char buf[INET6_ADDRSTRLEN];
int ret;

@@ -602,8 +603,= 7 @@
dst_v6.ipv6 =3D *dst;
}<= /span>

- = msg(D_ROUTE, "%s query: dst %s", __func__,
- inet_ntop(AF_INET6, &dst_v6.ipv= 6, buf, sizeof(buf)));
-
}
=
/* used by iproute2 implementation too */ int
-net_route= _v4_best_gw(openvpn_net_ctx_t *ctx, const in_addr_t *dst,
- in_addr_t *best_gw= , char *best_iface)
+= net_route_v4_best_gw(openvpn_net_ctx_t *ctx, const in_addr_t *dst, in_addr_= t *best_gw,
+ = char *best_iface)
{
- inet_address_t dst_v4 =3D {0};
+ inet_address_t dst_v4 =3D { = 0 };

char buf[INET_ADDRSTRLEN];
i= nt ret;

@@ -632,8 +631,7 @@
dst_v4.ipv4 =3D htonl(*dst);

}
<= span>

- msg(D_ROUTE= , "%s query: dst %s", __func__,
- inet_ntop(AF_INET, &dst_v4.ipv4, buf, sizeo= f(buf)));
+ msg(D_= ROUTE, "%s query: dst %s", __func__, inet_ntop(AF_INET, &dst_= v4.ipv4, buf, sizeof(buf)));

ret =3D= sitnl_route_best_gw(AF_INET, &dst_v4, best_gw, best_iface);
= if (ret < 0)
@@ -669,8 +667,7 @@
ifindex =3D if_nametoindex(iface);

if (ifinde= x =3D=3D 0)
{
- msg(M_WARN, "%s: rtnl: cannot get ifindex for %s:= %s", __func__, iface,
- strerror(errno));
+ msg(M_WARN, "%s: rtnl: cannot get ifindex for = %s: %s", __func__, iface, strerror(errno));
r= eturn -ENOENT;
}

@@ = -696,8 +693,7 @@
}

int<= /span>
-net_iface_mtu_set(open= vpn_net_ctx_t *ctx, const char *iface,
- uint32_t mtu)
+net_iface_mtu_set(openvpn_net_ctx_t *ctx, cons= t char *iface, uint32_t mtu)
{
struct= sitnl_link_req req;
int ifindex, ret =3D -1;@@ -707,8 +703,7 @@
ifindex =3D if_nametoindex= (iface);
if (ifindex =3D=3D 0)
{<= /span>
- msg(M_WARN | M= _ERRNO, "%s: rtnl: cannot get ifindex for %s", __func__,- iface);
= + msg(M_WARN | M_ERRNO, = "%s: rtnl: cannot get ifindex for %s", __func__, iface); return -1;
}
=
@@ -729,8 +724,7 @@
}
int
-net_addr_= ll_set(openvpn_net_ctx_t *ctx, const openvpn_net_iface_t *iface,
= - uint8_t *addr)
+net_addr_ll_set(openv= pn_net_ctx_t *ctx, const openvpn_net_iface_t *iface, uint8_t *addr)<= br> {
struct sitnl_link_req req;
int ifindex, ret =3D -1;

@@ -740,8 +734,7 @@ ifindex =3D if_nametoindex(iface);
if (if= index =3D=3D 0)
{
- msg(M_WARN | M_ERRNO, "%s: rtnl: cannot get i= findex for %s", __func__,
- iface);
+ msg(M_WARN | M_ERRNO, "%s: rtnl: cannot get ifindex f= or %s", __func__, iface);
return -1; }

@@ -754,8 +747,7 @@=

SITNL_ADDATTR(&req.n, sizeof(req), IFL= A_ADDRESS, addr, OPENVPN_ETH_ALEN);

- msg(M_INFO, "%s: lladdr " MAC= _FMT " for %s", __func__, MAC_PRINT_ARG(addr),
- iface);
+ msg(M_INFO, "%s: lladdr " MAC_= FMT " for %s", __func__, MAC_PRINT_ARG(addr), iface);
<= span>

ret =3D sitnl_send(&req.n, 0, 0, NULL, NULL= );
err:
@@ -764,8 +756,7 @@

static int
sitnl_addr_set(int cmd, ui= nt32_t flags, int ifindex, sa_family_t af_family,
- const inet_address_t *local, con= st inet_address_t *remote,
- int prefixlen)
+ const inet_address_t *local, const inet_addre= ss_t *remote, int prefixlen)
{
struct= sitnl_addr_req req;
uint32_t size;
@@= -791,8 +782,7 @@
break;

default:
- msg(M_WARN, "%s: rtnl: unknown address family %d&= quot;, __func__,
- = af_family);
-sitnl_addr_ptp_add(sa_family_t af_fam= ily, const char *iface,
- const inet_address_t *local,
+sitnl_addr_ptp_add(sa_family_t af_family, con= st char *iface, const inet_address_t *local,
= const inet_address_t *remote)
{
= int ifindex;
@@ -848,18 +837,16 @@
if= index =3D if_nametoindex(iface);
if (ifindex =3D=3D 0)=
{
- msg(M_WARN, "%s: cannot get ifindex for %s: %s", __func= __, np(iface),
- = strerror(errno));
- return sitnl_addr_set(RTM_NEWADDR, NLM_F_CREATE | NL= M_F_REPLACE, ifindex,
-= af_family, local, remote, 0);
+ return sitnl_addr_set(RTM_NEWADDR, = NLM_F_CREATE | NLM_F_REPLACE, ifindex, af_family, local,
+ remote, 0);<= /span>
}

static int
= -sitnl_addr_ptp_del(sa_family_t a= f_family, const char *iface,
- const inet_address_t *local)
+sitnl_addr_ptp_del(sa_family_t af_family= , const char *iface, const inet_address_t *local)
{=
int ifindex;

@@ -890,9 +87= 7,8 @@
}

static int
-sitnl_route_set(int cmd, = uint32_t flags, int ifindex, sa_family_t af_family,
- const void *dst, int prefix= len,
- c= onst void *gw, enum rt_class_t table, int metric,
+sitnl_route_set(int cmd, uint32_t flags, int = ifindex, sa_family_t af_family, const void *dst,
+ int prefixlen, const void *gw,= enum rt_class_t table, int metric,
enum r= t_scope_t scope, int protocol, int type)
{
struct sitnl_route_req req;

@@ -960,8 +946,7 @@
}

static int
-sitnl_addr_add(sa_family_t af_family,= const char *iface,

- = const inet_address_t *addr, int prefixlen)
+sitnl_addr_add(sa_family_t af_family, c= onst char *iface, const inet_address_t *addr, int prefixlen)
{

int ifindex;

@@= -984,52 +969,47 @@
ifindex =3D if_nametoindex(iface);=
if (ifindex =3D=3D 0)
{- msg(M_WARN | M_ERRNO, = "%s: rtnl: cannot get ifindex for %s", __func__,
- iface);
+ msg(M_WARN | M_ERRNO, "%s= : rtnl: cannot get ifindex for %s", __func__, iface);
= return -ENOENT;
}
- return sitnl_addr_set(RTM_N= EWADDR, NLM_F_CREATE | NLM_F_REPLACE, ifindex,
- af_family, addr, NULL, p= refixlen);
-}-
-static int
-sitnl_addr_del(sa_family_t af_family, const char *iface, inet_a= ddress_t *addr,
- = int prefixlen)
-{
- int ifindex;
-
- switch (af_family)
- {
- case AF_INET:
- case AF_INET6:
- break;
-
- = default:
- = return -EINVAL;
- }=
-
- if (!iface)
- {
- msg(M_WARN, "%s: passed NULL interface", __fun= c__);
- return -= EINVAL;
- }-
- ifindex =3D if_nametoindex(iface);
- if (ifindex =3D=3D 0)
- {
- msg(M_WARN | M_ERRNO, "%s: rtnl: = cannot get ifindex for %s", __func__,
- iface);
- return -ENOENT;
- }
-
- return sitnl= _addr_set(RTM_DELADDR, 0, ifindex, af_family, addr, NULL,
+ return sitnl_addr_set(RTM_NEWADDR= , NLM_F_CREATE | NLM_F_REPLACE, ifindex, af_family, addr, NULL,
<= span> prefixlen);

}

+static int
+sitnl_addr_del(sa_famil= y_t af_family, const char *iface, inet_address_t *addr, int prefixlen)
+{
+ int ifindex;
+
+ switch (af_family)
+ {
= + case AF_INET:
+ break;
+
+ defaul= t:
+ retur= n -EINVAL;
+ }
+
+ if (!iface)
+ {
+ msg(M_WARN, "%s: passed NULL interface", = __func__);
+ r= eturn -EINVAL;
+ }=
+
+ ifindex =3D if_nametoindex(iface);=
+ if (ifindex =3D= =3D 0)
+ {<= br>+ msg(M_WARN | M_ERRN= O, "%s: rtnl: cannot get ifindex for %s", __func__, iface);
+ return -ENOENT;
+ }
+

+ return sitnl_addr_set(RTM_DELADDR, 0, ifindex, af_= family, addr, NULL, prefixlen);
+}
+
int
-net_ad= dr_v4_add(openvpn_net_ctx_t *ctx, const char *iface,
- const in_addr_t *addr, int = prefixlen)
+net_addr_= v4_add(openvpn_net_ctx_t *ctx, const char *iface, const in_addr_t *addr, in= t prefixlen)
{
inet_address_t addr_v4= =3D { 0 };
char buf[INET_ADDRSTRLEN];
@@ -1041,15 +1021,15 @@


addr_v4.ipv= 4 =3D htonl(*addr);

- msg(M_INFO, "%s: %s/%d dev %s", __func__,
- inet_ntop(AF_INET= , &addr_v4.ipv4, buf, sizeof(buf)), prefixlen, iface);
+ msg(M_INFO, "%s: %s/%d dev = %s", __func__, inet_ntop(AF_INET, &addr_v4.ipv4, buf, sizeof(buf))= ,
+ prefixlen,= iface);

return sitnl_addr_add(AF_IN= ET, iface, &addr_v4, prefixlen);
}

int
-ne= t_addr_v6_add(openvpn_net_ctx_t *ctx, const char *iface,
- const struct in6_addr *a= ddr, int prefixlen)
+= net_addr_v6_add(openvpn_net_ctx_t *ctx, const char *iface, const struct in6= _addr *addr,
+ = int prefixlen)
{
inet_addres= s_t addr_v6 =3D { 0 };
char buf[INET6_ADDRSTRLEN];
@@ -1061,15 +1041,14 @@

= addr_v6.ipv6 =3D *addr;

- msg(M_INFO, "%s: %s/%d dev %s", __func__= ,
- inet_ntop(AF= _INET6, &addr_v6.ipv6, buf, sizeof(buf)), prefixlen, iface);
= + msg(M_INFO, "%s: %s/%= d dev %s", __func__, inet_ntop(AF_INET6, &addr_v6.ipv6, buf, sizeo= f(buf)),
+ pre= fixlen, iface);

return sitnl_addr_ad= d(AF_INET6, iface, &addr_v6, prefixlen);
}
<= span>

int
-net_addr_v4_del(openvpn_net_ctx_t *ctx, const char *iface,
= - const in_addr_t = *addr, int prefixlen)
+net_addr_v4_del(openvpn_net_ctx_t *ctx, const char *iface, const in_addr_= t *addr, int prefixlen)
{
inet_addres= s_t addr_v4 =3D { 0 };
char buf[INET_ADDRSTRLEN];
@@ -1081,15 +1060,15 @@

= addr_v4.ipv4 =3D htonl(*addr);

- msg(M_INFO, "%s: %s dev %s", __fun= c__,
- inet_ntop= (AF_INET, &addr_v4.ipv4, buf, sizeof(buf)), iface);
+ msg(M_INFO, "%s: %s dev %s&quo= t;, __func__, inet_ntop(AF_INET, &addr_v4.ipv4, buf, sizeof(buf)),
+ iface);
return sitnl_addr_del(AF_INET, iface, &a= ddr_v4, prefixlen);
}

i= nt
-net_addr_v6_del(ope= nvpn_net_ctx_t *ctx, const char *iface,
- const struct in6_addr *addr, int prefixle= n)
+net_addr_v6_del(o= penvpn_net_ctx_t *ctx, const char *iface, const struct in6_addr *addr,
+ int pref= ixlen)
{
inet_address_t addr_v6 =3D {= 0 };
char buf[INET6_ADDRSTRLEN];
@@ -= 1101,15 +1080,15 @@

addr_v6.ipv6 =3D= *addr;

- msg(M_INFO, "%s: %s/%d dev %s", __func__,
- inet_ntop(AF_INET6, &addr= _v6.ipv6, buf, sizeof(buf)), prefixlen, iface);

+ msg(M_INFO, "%s: %s/%d dev %s", _= _func__, inet_ntop(AF_INET6, &addr_v6.ipv6, buf, sizeof(buf)),+ prefixlen, iface);

return sitnl_addr_del(AF_INET6, iface= , &addr_v6, prefixlen);
}

= int
-net_addr_pt= p_v4_add(openvpn_net_ctx_t *ctx, const char *iface,
- const in_addr_t *local,= const in_addr_t *remote)
+net_addr_ptp_v4_add(openvpn_net_ctx_t *ctx, const char *iface, const = in_addr_t *local,
+ = const in_addr_t *remote)
{
inet_address_t local_v4 =3D { 0 };

inet_addres= s_t remote_v4 =3D { 0 };
@@ -1136,8 +1115,8 @@
}


int
-net_addr_ptp_v4_del(openvpn_net_ctx_t *ctx, const c= har *iface,
- = const in_addr_t *local, const in_addr_t *remote)
+net_addr_ptp_v4_del(openvpn_net_ctx_= t *ctx, const char *iface, const in_addr_t *local,
+ const in_addr_t *remote)=
{
inet_address_t local_v4 =3D { 0 };=
char buf[INET6_ADDRSTRLEN];
@@ -1150,= 15 +1129,15 @@

local_v4.ipv4 =3D hto= nl(*local);

- msg(M_INFO, "%s: %s dev %s", __func__,
- inet_ntop(AF_INET, &loca= l_v4.ipv4, buf, sizeof(buf)), iface);

+ msg(M_INFO, "%s: %s dev %s", __func__, inet= _ntop(AF_INET, &local_v4.ipv4, buf, sizeof(buf)),
+ iface);
<= br> return sitnl_addr_ptp_del(AF_INET, iface, &local_v4);
}

static int
-sitnl_route_add(const char *iface, = sa_family_t af_family, const void *dst,

- int prefixlen, const void *gw, uint32_t t= able, int metric)
+si= tnl_route_add(const char *iface, sa_family_t af_family, const void *dst, in= t prefixlen,
+ = const void *gw, uint32_t table, int metric)
{
enum rt_scope_t scope =3D RT_SCOPE_UNIVERSE;
int ifindex =3D 0;

@@ -1168,8 +1147,7 @@ ifindex =3D if_nametoindex(iface);
= if (ifindex =3D=3D 0)
{
- msg(M_WARN | M_ERRNO, "%s: rtn= l: can't get ifindex for %s",
- __func__, iface);
+ msg(M_WARN | M_ERRNO, "%s: = rtnl: can't get ifindex for %s", __func__, iface);
return -ENOENT;

}
= }
@@ -1184,15 +1162,13 @@
scope= =3D RT_SCOPE_LINK;
}

- return sitnl_route_set(RTM_NEWRO= UTE, NLM_F_CREATE, ifindex,

- af_family, dst, prefixlen, gw, table, metr= ic, scope,
- = RTPROT_BOOT, RTN_UNICAST);
+ return sitnl_route_set(RTM_NEWROUTE, NLM_F_CREAT= E, ifindex, af_family, dst, prefixlen, gw,
+ table, metric, scope, RTP= ROT_BOOT, RTN_UNICAST);
}

int

-net_route_v4_ad= d(openvpn_net_ctx_t *ctx, const in_addr_t *dst, int prefixlen,
- const in_addr_t *= gw, const char *iface,

= - uint32_t table, int metric)
+net_route_v4_add(openvpn_net_ctx_t *ctx, const in= _addr_t *dst, int prefixlen, const in_addr_t *gw,
+ const char *iface, uint32_t = table, int metric)
{
in_addr_t *dst_p= tr =3D NULL, *gw_ptr =3D NULL;
in_addr_t dst_be =3D 0,= gw_be =3D 0;
@@ -1212,18 +1188,15 @@
= }

msg(D_ROUTE, "%s: %s/%d via %= s dev %s table %d metric %d", __func__,
- inet_ntop(AF_INET, &dst_be, dst_str, siz= eof(dst_str)),
- = prefixlen, inet_ntop(AF_INET, &gw_be, gw_str, sizeof(gw_str)),<= br>- np(iface), table, met= ric);
+ inet_n= top(AF_INET, &dst_be, dst_str, sizeof(dst_str)), prefixlen,
<= span style=3D"color: hsl(120, 100%, 40%);">+ inet_ntop(AF_INET, &= ;gw_be, gw_str, sizeof(gw_str)), np(iface), table, metric);


- return sitnl_ro= ute_add(iface, AF_INET, dst_ptr, prefixlen, gw_ptr, table,
- metric);
+ return sitnl_route= _add(iface, AF_INET, dst_ptr, prefixlen, gw_ptr, table, metric);
= }

int
-net_route_v6_add(openvpn_net_ctx_t *ctx, const st= ruct in6_addr *dst,
- = int prefixlen, const struct in6_addr *gw,
- const char *iface, uint= 32_t table, int metric)
+net_route_v6_add(openvpn_net_ctx_t *ctx, const struct in6_addr *dst, in= t prefixlen,
+ = const struct in6_addr *gw, const char *iface, uint32_t table, int= metric)
{
inet_address_t dst_v6 =3D = { 0 };
inet_address_t gw_v6 =3D { 0 };
@@ -1241,18 +1214,15 @@

}
msg(D_ROUTE, "%s: %s/%d via %s dev %s table %d metric %d&q= uot;, __func__,
- = inet_ntop(AF_INET6, &dst_v6.ipv6, dst_str, sizeof(dst_str)),- prefixlen, inet_ntop(A= F_INET6, &gw_v6.ipv6, gw_str, sizeof(gw_str)),
- np(iface), table, metric);
<= span style=3D"color: hsl(120, 100%, 40%);">+ inet_ntop(AF_INET6, &am= p;dst_v6.ipv6, dst_str, sizeof(dst_str)), prefixlen,

+ inet_ntop(AF_INET6, &gw_v6.ip= v6, gw_str, sizeof(gw_str)), np(iface), table, metric);

- return sitnl_route_= add(iface, AF_INET6, dst, prefixlen, gw, table,
- metric);
+ return sitnl_route_add(iface,= AF_INET6, dst, prefixlen, gw, table, metric);

}
static int
-sitnl_route_del(const char *iface, sa_family_t af_family, in= et_address_t *dst,
- = int prefixlen, inet_address_t *gw, uint32_t table,
<= span style=3D"color: hsl(0, 100%, 40%);">- int metric)
+sitnl_route_del(const cha= r *iface, sa_family_t af_family, inet_address_t *dst, int prefixlen,=
+ inet_addre= ss_t *gw, uint32_t table, int metric)
{
= int ifindex =3D 0;

@@ -1261,8 +1231,7 = @@
ifindex =3D if_nametoindex(iface);
if (ifindex =3D=3D 0)

{
- msg(M_WARN | M_ERRNO, &= quot;%s: rtnl: can't get ifindex for %s",

- __func__, iface);
+ msg(M_WARN | M_ERRNO= , "%s: rtnl: can't get ifindex for %s", __func__, iface);
return -ENOENT;
}=
}
@@ -1272,14 +1241,13 @@
= table =3D RT_TABLE_MAIN;
}

- return sitnl_route_s= et(RTM_DELROUTE, 0, ifindex, af_family, dst, prefixlen,
- gw, table, met= ric, RT_SCOPE_NOWHERE, 0, 0);
+ return sitnl_route_set(RTM_DELROUTE, 0, ifindex, af_family, d= st, prefixlen, gw, table, metric,
+ RT_SCOPE_NOWHERE, 0, 0); }

int
-net_route_v4_del(openvpn_net_ctx_t *ctx, const i= n_addr_t *dst, int prefixlen,
- const in_addr_t *gw, const char *iface, uint32_t t= able,
- = int metric)
+net_rou= te_v4_del(openvpn_net_ctx_t *ctx, const in_addr_t *dst, int prefixlen, cons= t in_addr_t *gw,
+ = const char *iface, uint32_t table, int metric)
{

inet_address_t dst_v4 =3D { 0 };
= inet_address_t gw_v4 =3D { 0 };
@@ -1297,18 +1265,15 @= @
}

msg(D_ROUTE= , "%s: %s/%d via %s dev %s table %d metric %d", __func__,<= br>- inet_ntop(AF_INET, &a= mp;dst_v4.ipv4, dst_str, sizeof(dst_str)),
- prefixlen, inet_ntop(AF_INET, &gw_v4.ipv4,= gw_str, sizeof(gw_str)),
- np(iface), table, metric);
+ inet_ntop(AF_INET, &dst_v4.ipv4, dst_str, si= zeof(dst_str)), prefixlen,
+ inet_ntop(AF_INET, &gw_v4.ipv4, gw_str, sizeof(gw_str)),= np(iface), table, metric);

- return sitnl_route_del(iface, AF_INET, &dst= _v4, prefixlen, &gw_v4, table,
- metric);
+ return sitnl_route_del(iface, AF_INET, &am= p;dst_v4, prefixlen, &gw_v4, table, metric);
}<= br>
int
-net_route_v6_del(openvpn_net_ctx_t *ctx, const struct in6_addr *d= st,
- i= nt prefixlen, const struct in6_addr *gw,
- const char *iface, uint32_t table, int = metric)
+net_route_v6= _del(openvpn_net_ctx_t *ctx, const struct in6_addr *dst, int prefixlen,
+ const = struct in6_addr *gw, const char *iface, uint32_t table, int metric)<= br> {
inet_address_t dst_v6 =3D { 0 }; inet_address_t gw_v6 =3D { 0 };
@@ -1326,20 +12= 91,17 @@
}

msg(= D_ROUTE, "%s: %s/%d via %s dev %s table %d metric %d", __func__,<= /span>
- inet_ntop(AF_I= NET6, &dst_v6.ipv6, dst_str, sizeof(dst_str)),
- prefixlen, inet_ntop(AF_INET6, &gw= _v6.ipv6, gw_str, sizeof(gw_str)),
- np(iface), table, metric);
+ inet_ntop(AF_INET6, &dst_v6.ipv6, d= st_str, sizeof(dst_str)), prefixlen,
+ inet_ntop(AF_INET6, &gw_v6.ipv6, gw_str, sizeo= f(gw_str)), np(iface), table, metric);

- return sitnl_route_del(iface, AF_INE= T6, &dst_v6, prefixlen, &gw_v6,
- table, metric);
+ return sitnl_route_del(iface, = AF_INET6, &dst_v6, prefixlen, &gw_v6, table, metric);

}



int
-net_iface_new(openvpn_net_ctx_t *c= tx, const char *iface, const char *type,

- void *arg)
+net_iface_new(openvpn_net_ctx_t *ctx, const char *i= face, const char *type, void *arg)
{
- struct sitnl_link_req req =3D { };
+ struct sitnl_link_re= q req =3D {};
int ret =3D -1;
=
ASSERT(iface);
@@ -1357,8 +1319,7 @@<= br> {
dco_context_t *dco =3D arg;=
struct rtattr *data =3D SITNL_NEST(&req.n, sizeof(re= q), IFLA_INFO_DATA);
- = SITNL_ADDATTR(&req.n, sizeof(req), IFLA_OVPN_MODE, &dco->= ifmode,
- = sizeof(uint8_t));
+ SITNL_ADDATTR(&req.n, sizeof(req), IFLA_OVPN_MODE, &d= co->ifmode, sizeof(uint8_t));
SITNL_NEST_END(&a= mp;req.n, data);
}
#endif
<= span>@@ -1366,7 +1327,7 @@


req.i.ifi= _family =3D AF_PACKET;

- msg(D_ROUTE, "%s: add %s type %s", __func_= _, iface, type);
+ = msg(D_ROUTE, "%s: add %s type %s", __func__, iface, type);

ret =3D sitnl_send(&req.n, 0, 0, NUL= L, NULL);
err:
@@ -1374,8 +1335,8 @@
}

static int
-sitnl_parse_rtattr_flags(struct rtatt= r *tb[], int max, struct rtattr *rta,

- int len, unsigned short flags)
+sitnl_parse_rtattr_flag= s(struct rtattr *tb[], int max, struct rtattr *rta, int len,
+ unsigned = short flags)

{
unsigned short type;

@@ -1395,8 +1356,7 @@

if (len)
{
- msg(D_ROUTE, "%s: %d bytes not pa= rsed! (rta_len=3D%d)", __func__, len,
- rta->rta_len);
+ msg(D_ROUTE, "%s: %d bytes not = parsed! (rta_len=3D%d)", __func__, len, rta->rta_len);
}


return 0;
@@ -1409,8 +1369,7 @@

}

#define sitnl_parse_rtattr_nested(tb, max, rta) \

- (sitnl_parse_rtattr_flags(tb, max, RTA_= DATA(rta), RTA_PAYLOAD(rta), \
- NLA_F_NESTED))
+ (sitnl_parse_rtattr_flags(tb, max, RT= A_DATA(rta), RTA_PAYLOAD(rta), NLA_F_NESTED))

<= span> static int

sitnl_type_save(struct nlmsghdr *n, void = *arg)
@@ -1430,8 +1389,7 @@
{ struct rtattr *tb_link[IFLA_INFO_MAX + 1];

- ret =3D sit= nl_parse_rtattr_nested(tb_link, IFLA_INFO_MAX,
- tb[IFLA_LI= NKINFO]);
+ re= t =3D sitnl_parse_rtattr_nested(tb_link, IFLA_INFO_MAX, tb[IFLA_LINKINFO]);=
if (ret < 0)
{=
return ret;
@@ -1449,10 +1407,9 @@
}

int
-net_iface_type(openvpn_net_ctx_t *ctx, c= onst char *iface,
- = char type[IFACE_TYPE_LEN_MAX])
+net_iface_type(openvpn_net_ctx_t *ctx, const char *if= ace, char type[IFACE_TYPE_LEN_MAX])
{
- struct sitnl_link_req req =3D { };
+ struct sitnl_link_r= eq req =3D {};
int ifindex =3D if_nametoindex(iface);<= /span>

if (!ifindex)
@@ -14= 72,8 +1429,7 @@
int ret =3D sitnl_send(&req.n, 0, = 0, sitnl_type_save, type);
if (ret < 0)
<= span> {

- ms= g(D_ROUTE, "%s: cannot retrieve iface %s: %s (%d)", __func__, ifa= ce,
- strerr= or(-ret), ret);
+ = msg(D_ROUTE, "%s: cannot retrieve iface %s: %s (%d)", __func_= _, iface, strerror(-ret), ret);
return ret;=
}

@@ -1485,7 +1441,7 @@
int
net_iface_del(openvpn_net_ctx_t *ctx, c= onst char *iface)
{
- struct sitnl_link_req req =3D { };
+ struct sitnl_link_req req =3D {};
int ifindex =3D if_nametoindex(iface);
<= /span>
if (!ifindex)
diff --git a/src/openvpn= /ntlm.c b/src/openvpn/ntlm.c
index 94e5d95..dc5c93f 100644<= /span>
--- a/src/openvpn/ntlm.c
+++ b/src/openvpn/= ntlm.c
@@ -44,15 +44,14 @@
#ifdef _MSC_VER=
/* MS compilers */
#define UINTEGER64 __= int64
-#define UINT64(c= ) c ## Ui64
+#define = UINT64(c) c##Ui64
#else
/* Non MS compil= ers */
#define UINTEGER64 unsigned long long
-#define UINT64(c) c ## LL
+#define UINT64(c) c##LL
#endif


-
static void
<= span> gen_md4_hash(const uint8_t *data, int data_len, uint8_t *result)
{
@@ -64,8 +63,7 @@
}<= br>
static void
-gen_hmac_md5(const uint8_t *data, int data_len, const uin= t8_t *key,
- = uint8_t *result)
+g= en_hmac_md5(const uint8_t *data, int data_len, const uint8_t *key, uint8_t = *result)
{
hmac_ctx_t *hmac_ctx =3D h= mac_ctx_new();

@@ -91,13 +89,13 @@=

/* store little endian value */
= timestamp[0] =3D timestamp_ull & UINT64(0xFF);
- timestamp[1] =3D (timestamp_ull= >> 8) & UINT64(0xFF);

- timestamp[2] =3D (timestamp_ull >> 16) & UINT64= (0xFF);
- timestamp[= 3] =3D (timestamp_ull >> 24) & UINT64(0xFF);
- timestamp[4] =3D (timestamp_ull >= > 32) & UINT64(0xFF);
- timestamp[5] =3D (timestamp_ull >> 40) & UINT64(0xFF)= ;
- timestamp[6] =3D= (timestamp_ull >> 48) & UINT64(0xFF);
- timestamp[7] =3D (timestamp_ull >> 5= 6) & UINT64(0xFF);
+ timestamp[2] =3D (ti= mestamp_ull >> 16) & UINT64(0xFF);
+ timestamp[3] =3D (timestamp_ull >> 24) &= amp; UINT64(0xFF);
+ = timestamp[4] =3D (timestamp_ull >> 32) & UINT64(0xFF);<= br>+ timestamp[5] =3D (times= tamp_ull >> 40) & UINT64(0xFF);
+ timestamp[6] =3D (timestamp_ull >> 48) &= ; UINT64(0xFF);
+ = timestamp[7] =3D (timestamp_ull >> 56) & UINT64(0xFF);
= }

static void
@@ = -106,7 +104,7 @@
/* Generates 8 random bytes to be use= d as client nonce */
int i;
- for (i =3D 0; i<8; i++)=
+ for (i =3D 0; i= < 8; i++)
{
nonce[i] =3D = (unsigned char)get_random();
}
@@ -152= ,8 +150,8 @@
}

static v= oid
-add_security_buffe= r(int sb_offset, void *data, int length,
- unsigned char *msg_buf, int *msg_buf= pos, size_t msg_bufsize)
+add_security_buffer(int sb_offset, void *data, int length, unsigned ch= ar *msg_buf, int *msg_bufpos,
+ size_t msg_bufsize)
{=
if (*msg_bufpos + length > msg_bufsize)
= {
@@ -188,8 +186,7 @@
}

const char *
-ntlm_phase_3(const struct http_proxy_info *p, const char *phase= _2,
- struc= t gc_arena *gc)
+ntlm= _phase_3(const struct http_proxy_info *p, const char *phase_2, struct gc_ar= ena *gc)
{
/* NTLM handshake *
@@ -205,13 +202,13 @@
= int i, ret_val;

uint8_t ntlmv2_respo= nse[256];
- char use= rdomain_u[256]; /* for uppercase unicode username and domain */<= br>- char userdomain[128]; = /* the same as previous but ascii */
+ char userdomain_u[256]; /* for uppercase unicode us= ername and domain */
= + char userdomain[128]; /* the same as previous but ascii */ uint8_t ntlmv2_hash[MD5_DIGEST_LENGTH];
ui= nt8_t ntlmv2_hmacmd5[16];
- uint8_t *ntlmv2_blob =3D ntlmv2_response + 16; /* inside ntlmv2= _response, length: 128 */
+ uint8_t *ntlmv2_blob =3D ntlmv2_response + 16; /* inside ntlmv2_r= esponse, length: 128 */
int ntlmv2_blob_size =3D 0;
- int phase3_bufpos = =3D 0x40; /* offset to next security buffer data to be added */<= br>+ int phase3_bufpos =3D 0= x40; /* offset to next security buffer data to be added */
= size_t len;

char domain[128];
@@ -225,20 +222,20 @@
separator =3D str= chr(p->up.username, '\\');
if (separator = =3D=3D NULL)
{
- strncpy(username, p->up.username, sizeof(username)= -1);
- username[= sizeof(username)-1] =3D 0;
+ strncpy(username, p->up.username, sizeof(username) - 1);<= /span>
+ username[siz= eof(username) - 1] =3D 0;
domain[0] =3D 0;<= br> }
else
{
= - strncpy(username, separa= tor+1, sizeof(username)-1);
- username[sizeof(username)-1] =3D 0;
+ strncpy(username, separator + 1, size= of(username) - 1);
+ = username[sizeof(username) - 1] =3D 0;
len = =3D separator - p->up.username;
if (len > si= zeof(domain) - 1)
{
l= en =3D sizeof(domain) - 1;
}
- strncpy(domain, p->up.username, = len);
+ strnc= py(domain, p->up.username, len);
domain[len] = =3D 0;
}

@@ -264,9 += 261,9 @@
}

/* e= xtract the challenge from bytes 24-31 */
- for (i =3D 0; i<8; i++)
+ for (i =3D 0; i < 8; i++)
{

- cha= llenge[i] =3D buf2[i+24];
+ challenge[i] =3D buf2[i + 24];
}<= br>
/* Generate NTLMv2 response */
@@ -284,17 +281,16 @@

msg(M_INFO, "NTLM: = Username or domain too long");
}
= unicodize(userdomain_u, userdomain);
- gen_hmac_md5((uint8_t *)userdomain_u, 2 * strlen(us= erdomain), md4_hash,
- = ntlmv2_hash);
+ gen_hmac_md5((uint8_t *)userdomain_u, 2 * strlen(userdomain),= md4_hash, ntlmv2_hash);

/* NTLMv2 B= lob */
- memset(ntlm= v2_blob, 0, 128); /* Clear blob buffer */
= - ntlmv2_blob[0x00] =3D 1; = /* Signature */
- ntlmv2_blob[0x01] =3D 1; = /* Signature */
- = ntlmv2_blob[0x04] =3D 0; /* Reserved */
- gen_timestamp(&ntlm= v2_blob[0x08]); /* 64-bit Timestamp */
- gen_nonce(&ntlmv2_blob[0x10]); = /* 64-bit Client Nonce */
- ntlmv2_blob[0x18] =3D 0; = /* Unknown, zero should work */
+ memset(ntlmv2_blob, 0, 128); /* Clear blob buff= er */
+ ntlmv2_blo= b[0x00] =3D 1; /* Signature */
+ ntlmv2_blob[0x01] =3D 1; /* Signatur= e */
+ ntlmv2_blob= [0x04] =3D 0; /* Reserved */
+ gen_timestamp(&ntlmv2_blob[0x08]); /* 64-bit T= imestamp */
+ gen_= nonce(&ntlmv2_blob[0x10]); /* 64-bit Client Nonce */
+ ntlmv2_blob[0x18] =3D 0; = /* Unknown, zero should work */


= /* Add target information block to the blob */
<= br>@@ -311,11 +307,11 @@
* byte order on the wi= re for the NTLM header is LE.
*/
= const size_t hoff =3D 0x14;
- unsigned long flags =3D buf2[hoff] | (buf2[hoff + 1] << 8)=
- = |(buf2[hoff + 2] << 16) | (buf2[hoff + 3] << 24);+ unsigned long flags =3D<= /span>
+ buf2[hoff] |= (buf2[hoff + 1] << 8) | (buf2[hoff + 2] << 16) | (buf2[hoff + = 3] << 24);
if ((flags & 0x00800000) =3D=3D 0= x00800000)
{
- tib_len =3D buf2[0x28]; /* Get Target Inform= ation block size */
+= tib_len =3D buf2[0x28]; /* Get Target Information block size */
if (tib_len + 0x1c + 16 > sizeof(ntlmv2_response))=
{
msg(M_WARN, "= NTLM: target information buffer too long for response (len=3D%d)", tib= _len);
@@ -327,7 +323,9 @@
uin= t8_t tib_pos =3D buf2[0x2c];
if (tib_pos + tib= _len > sizeof(buf2))
{
- msg(M_ERR, "NTLM: pha= se 2 response from server too long (need %d bytes at offset %u)", tib_= len, tib_pos);
+ = msg(M_ERR,
+ "NTLM: phase 2 response from server too long (ne= ed %d bytes at offset %u)",
+ tib_len, tib_pos);
= return NULL;
}
= /* Get Target Information block pointer */
@@ -351,= 41 +349,38 @@
memcpy(&ntlmv2_response[8], challeng= e, 8);

/* hmac-md5 */
- gen_hmac_md5(&ntlmv2_respons= e[8], ntlmv2_blob_size + 8, ntlmv2_hash,

- ntlmv2_hmacmd5);
+ gen_hmac_md5(&ntlmv2_response[8],= ntlmv2_blob_size + 8, ntlmv2_hash, ntlmv2_hmacmd5);

/* Add hmac-md5 result to the blob.
= * Note: This overwrites challenge previously written at
= * ntlmv2_response[8..15] */
memcpy(ntlmv2_response,= ntlmv2_hmacmd5, MD5_DIGEST_LENGTH);

- memset(phase3, 0, sizeof(phase3)); = /* clear reply */
= + memset(phase3, 0, sizeof(phase3)); /* clear reply */

- strcpy((char *)= phase3, "NTLMSSP\0"); /* signature */
- phase3[8] =3D 3; /* type 3 */
+ strcpy((char *)phase3= , "NTLMSSP\0"); /* signature */
+ phase3[8] =3D 3; /* type 3 = */

/* NTLMv2 response */
<= span style=3D"color: hsl(0, 100%, 40%);">- add_security_buffer(0x14, ntl= mv2_response, ntlmv2_blob_size + 16,

- phase3, &phase3_bufpos, sizeof(p= hase3));
+ add_sec= urity_buffer(0x14, ntlmv2_response, ntlmv2_blob_size + 16, phase3, &pha= se3_bufpos,
+ = sizeof(phase3));

/* = username in ascii */
- = add_security_buffer(0x24, username, strlen(username), phase3,
= - &pha= se3_bufpos, sizeof(phase3));
+ add_security_buffer(0x24, username, strlen(username), phase3, = &phase3_bufpos, sizeof(phase3));

= /* Set domain. If <domain> is empty, default domain will be used
* (i.e. proxy's domain) */
add_= security_buffer(0x1c, domain, strlen(domain), phase3, &phase3_bufpos, s= izeof(phase3));

/* other security bu= ffers will be empty */
= - phase3[0x10] =3D phase3_bufpos; /* lm not used */
- phase3[0x30] =3D phase3_bufpos; = /* no workstation name supplied */
- phase3[0x38] =3D phase3_bufpos; /* no session key */=
+ phase3[0x10] = =3D phase3_bufpos; /* lm not used */
+ phase3[0x30] =3D phase3_bufpos; /* no workstation name= supplied */
+ pha= se3[0x38] =3D phase3_bufpos; /* no session key */
<= br> /* flags */
phase3[0x3c] =3D 0x02; /* ne= gotiate oem */
phase3[0x3d] =3D 0x02; /* negotiate ntl= m */

= - return ((const char *)make_base64_string2((unsigned char *)phase3,
- = phase3_bufpos, gc));
+ return ((const char *)make_base64_string2((unsign= ed char *)phase3, phase3_bufpos, gc));
}
= #endif /* if NTLM */
diff --git a/src/openvpn/occ.c b/src/o= penvpn/occ.c
index 00b2fa4..8821a06 100644
= --- a/src/openvpn/occ.c
+++ b/src/openvpn/occ.c
<= span>@@ -51,95 +51,93 @@

* OCC_STRING_SIZE must be set to= sizeof (occ_magic)
*/

-const uint8_t occ_magic[] =3D {=
- 0x28, 0x7f, 0x34, 0x6b, = 0xd4, 0xef, 0x7a, 0x81,
- 0x2d, 0x56, 0xb8, 0xd3, 0xaf, 0xc5, 0x45, 0x9c
-};
+const uint8_t occ_magic[] =3D { 0x28, 0x7f, 0x34, 0x6b, 0xd4= , 0xef, 0x7a, 0x81,
+= 0x2d, 0x56, 0xb8, 0xd3, 0xaf, 0xc5, 0x45, 0x9= c };

static const struct mtu_load_test m= tu_load_test_sequence[] =3D {

- {OCC_MTU_LOAD_REQUEST, -1000},
- {OCC_MTU_LOAD, -1000},
- {OCC_MTU_LOAD_REQUEST, -100= 0},
- {OCC_MTU_LOAD,= -1000},
- {OCC_MTU_= LOAD_REQUEST, -1000},
-= {OCC_MTU_LOAD, -1000},
+ { OCC_MTU_LOAD_REQUEST, -1000 },
+ { OCC_MTU_LOAD, -1000 },
+ { OCC_MTU_LOAD_REQUEST, -1000 },
+ { OCC_MTU_LOAD, -100= 0 },
+ { OCC_MTU_L= OAD_REQUEST, -1000 },
+ { OCC_MTU_LOAD, -1000 },

- {OCC_MTU_LOAD_REQUEST, -750},
- {OCC_MTU_LOAD, -750},

= - {OCC_MTU_LOAD_REQUEST, -750}= ,
- {OCC_MTU_LOAD, -= 750},
- {OCC_MTU_LOA= D_REQUEST, -750},
- = {OCC_MTU_LOAD, -750},
+ { OCC_MTU_LOAD_REQUEST, -750 },
+ { OCC_MTU_LOAD, -750 },
+ { OCC_MTU_LOAD_REQUEST, -750 },
+ { OCC_MTU_LOAD, -750 },
+ { OCC_MTU_LOAD_REQUES= T, -750 },
+ { OCC= _MTU_LOAD, -750 },

- {OCC_MTU_LOAD_REQUEST, -500},
- {OCC_MTU_LOAD, -500},
- {OCC_MTU_LOAD_REQUEST, -500},- {OCC_MTU_LOAD, -500},
- {OCC_MTU_LOAD_REQUEST, = -500},
- {OCC_MTU_LO= AD, -500},
+ { OCC= _MTU_LOAD_REQUEST, -500 },
+ { OCC_MTU_LOAD, -500 },
+ { OCC_MTU_LOAD_REQUEST, -500 },
+ { OCC_MTU_LOAD, -500 },
+ { OCC_MTU_LOAD_REQUEST, -500 },<= /span>
+ { OCC_MTU_LOAD, = -500 },

- {OCC_MTU_LOAD_REQUEST, -400},
- {OCC_MTU_LOAD, -400},
- {OCC_MTU_LOAD_REQUEST, -400},
- {OCC_MTU_LOAD, -400},
- {OCC_MTU_LOAD_REQUEST, -400},
- {OCC_MTU_LOAD, -400},
+ { OCC_MTU_LOAD_RE= QUEST, -400 },
+ {= OCC_MTU_LOAD, -400 },
+ { OCC_MTU_LOAD, -400 },
+ { OCC_MTU_LOAD_REQUEST, -400 },
+ { OCC_MTU_LOAD, -400 },

- {OCC= _MTU_LOAD_REQUEST, -300},
- {OCC_MTU_LOAD, -300},
- {OCC_MTU_LOAD_REQUEST, -300},
- {OCC_MTU_LOAD, -300},
- {OCC_MTU_LOAD_REQUEST, -300},
- {OCC_MTU_LOAD, -300},
+ { OCC_MTU_LOAD_REQUEST, -300 = },

+ { OCC_MTU_LOA= D, -300 },
+ { OCC= _MTU_LOAD_REQUEST, -300 },
+ { OCC_MTU_LOAD, -300 },
+ { OCC_MTU_LOAD_REQUEST, -300 },
+ { OCC_MTU_LOAD, -300 },
=
- {OCC_MTU_LOAD_RE= QUEST, -200},
- {OCC= _MTU_LOAD, -200},
- = {OCC_MTU_LOAD_REQUEST, -200},
- {OCC_MTU_LOAD, -200},
- {OCC_MTU_LOAD_REQUEST, -200},
- {OCC_MTU_LOAD, -200},
+ { OCC_MTU_LOAD_REQUEST, -200 },+ { OCC_MTU_LOAD, -200 },
+ { OCC_MTU_LOAD_RE= QUEST, -200 },
+ {= OCC_MTU_LOAD, -200 },
+ { OCC_MTU_LOAD, -200 },

= - {OCC_MTU_LOAD_REQUEST, -150}= ,
- {OCC_MTU_LOAD, -= 150},
- {OCC_MTU_LOA= D_REQUEST, -150},
- = {OCC_MTU_LOAD, -150},
-= {OCC_MTU_LOAD_REQUEST, -150},
- {OCC_MTU_LOAD, -150},
+ { OCC_MTU_LOAD_REQUEST, -150 },
+ { OCC_MTU_LOAD, -150 },
+ { OCC_MTU_LOAD_REQUEST, -150 = },

+ { OCC_MTU_LOA= D, -150 },
+ { OCC= _MTU_LOAD_REQUEST, -150 },
+ { OCC_MTU_LOAD, -150 },

- {OCC_MTU_LOAD_REQUEST, -100},- {OCC_MTU_LOAD, -100},
- {OCC_MTU_LOAD_REQUEST, = -100},
- {OCC_MTU_LO= AD, -100},
- {OCC_MT= U_LOAD_REQUEST, -100},
= - {OCC_MTU_LOAD, -100},
+ { OCC_MTU_LOAD_REQUEST, -100 },
+ { OCC_MTU_LOAD, -100 },
+ { OCC_MTU_LOAD_REQUEST, -100 },+ { OCC_MTU_LOAD, -100 },<= /span>
+ { OCC_MTU_LOAD_R= EQUEST, -100 },
+ = { OCC_MTU_LOAD, -100 },

- {OCC_MTU_LOAD_REQUEST, -50},
- {OCC_MTU_LOAD, -50},
- {OCC_MTU_LOAD_REQUEST, -50},<= br>- {OCC_MTU_LOAD, -50},
- {OCC_MTU_LOAD_REQUEST,= -50},
- {OCC_MTU_LO= AD, -50},
+ { OCC_= MTU_LOAD_REQUEST, -50 },
+ { OCC_MTU_LOAD, -50 },
+ { OCC_MTU_LOAD_REQUEST, -50 },
+ { OCC_MTU_LOAD, -50 },
+ { OCC_MTU_LOAD_REQUEST, -50 },=
+ { OCC_MTU_LOAD, -50 },=

- = {OCC_MTU_LOAD_REQUEST, 0},
- {OCC_MTU_LOAD, 0},
- {OCC_MTU_LOAD_REQUEST, 0},
- {OCC_MTU_LOAD, 0},
- {OCC_MTU_LOAD_REQUEST, 0},
- {OCC_MTU_LOAD, 0},
+ { OCC_MTU_LOAD_REQUEST, 0 },
+ { OCC_MTU_LOAD, 0 },
+ { OCC_MTU_LOAD_REQUEST, = 0 },
+ { OCC_MTU_L= OAD, 0 },
+ { OCC_= MTU_LOAD_REQUEST, 0 },
- {OCC_MTU_REQUEST, 0},
- {OCC_MTU_REQUEST, 0},
- {OCC_MTU_REQUEST, 0},
- {OCC_MTU_REQUEST, 0},
- {OCC_MTU_REQUEST, 0},
- {OCC_MTU_REQUEST, 0},
- {OCC_MTU_REQUEST, 0},
- {OCC_MTU_REQUEST, 0= },
- {OCC_MTU_REQUES= T, 0},
- {OCC_MTU_RE= QUEST, 0},
+ { OCC= _MTU_REQUEST, 0 },
+ = { OCC_MTU_REQUEST, 0 },
+ { OCC_MTU_REQUEST, 0 },
+ { OCC_MTU_REQUEST, 0 },
+ { OCC_MTU_REQUEST, 0 },
+ { OCC_MTU_REQUEST, 0 },
+ { OCC_MTU_REQUEST, 0 },+ { OCC_MTU_REQUEST, 0 },<= /span>
+ { OCC_MTU_REQUES= T, 0 },
+ { OCC_MT= U_REQUEST, 0 },

- {-1, 0}
+ { -1, 0 }
};

vo= id
@@ -155,15 +153,12 @@
*/
msg(D_SHOW_OCC,
= "NOTE: failed to obtain options consistency info from peer -- "=
- "= ;this could occur if the remote peer is running a version of "<= br>- PACKAGE_NAME<= /span>
- "= before 1.5-beta8 or if there is a network connectivity problem, and will n= ot necessarily prevent "
- PACKAGE_NAME
+ "this could occur if the remote peer = is running a version of " PACKAGE_NAME
+ " before 1.5-beta8 or if there= is a network connectivity problem, and will not necessarily prevent "= PACKAGE_NAME
" from running (" = counter_format " bytes received from peer, " counter_format
" bytes authenticated data channel traffic= ) -- you can disable the options consistency "
= "check with --disable-occ.",
- c->c2.link_read_bytes,=
- c->c2.lin= k_read_bytes_auth);
+= c->c2.link_read_bytes, c->c2.link_read_bytes_auth);
}
event_timeout_clear(&= ;c->c2.occ_interval);
}
@@ -196,16 = +191,17 @@
if (entry->op >=3D 0)
<= span> {

c->c2.occ_op =3D entry->= op;
- size_t= payload_size =3D frame_calculate_payload_size(&c->c2.frame,<= br>- = &c->options, &c->c1.ks.key_= type);
- siz= e_t header_size =3D frame_calculate_protocol_header_size(&c->c1.ks.k= ey_type, &c->options, false);
+ size_t payload_size =3D
+ frame_calculate_payload_s= ize(&c->c2.frame, &c->options, &c->c1.ks.key_type);
+ size_t hea= der_size =3D
+ = frame_calculate_protocol_header_size(&c->c1.ks.key_type, &a= mp;c->options, false);

c-= >c2.occ_mtu_load_size =3D payload_size + header_size;
= }
else
{- msg(M_INFO,<= br>- "NOTE: f= ailed to empirically measure MTU (requires " PACKAGE_NAME " 1.5 o= r higher at other end of connection).");
+ msg(M_INFO, "NOTE: failed to emp= irically measure MTU (requires " PACKAGE_NAME
+ " 1.5 or higher= at other end of connection).");
event_ti= meout_clear(&c->c2.occ_mtu_load_test_interval);
= c->c2.occ_mtu_load_n_tries =3D 0;
}
@@ -308,10 +304,8 @@
proto_hdr = =3D frame_calculate_protocol_header_size(kt, &c->options, false);

need_to_add =3D min_int(c->= c2.occ_mtu_load_size, c->c2.frame.buf.payload_size)
- - OCC_STRING_SIZ= E
- = - sizeof(uint8_t) /* occ opcode */
- - payload_hdr
- - proto_= hdr;

+ = - OCC_STRING_SIZE - sizeof(uint8_t) /* occ opcode */
<= span style=3D"color: hsl(120, 100%, 40%);">+ - pay= load_hdr - proto_hdr;


while = (need_to_add > 0)
{
@@ -325= ,13 +319,8 @@
--need_to_add;
}

dmsg(D_PACKET_CONTENT, "= ;SENT OCC_MTU_LOAD min_int(%d,%d)-%d-%d-%d-%d) size=3D%d",
<= span style=3D"color: hsl(0, 100%, 40%);">- c->c2.occ_mtu= _load_size,

- = c->c2.frame.buf.payload_size,
- OCC_STRING_SIZE,
- (int) sizeof(uint8_t),

- (int) pa= yload_hdr,
- = (int) proto_hdr,
= - BLEN(&c->c2.buf));
+ c->c2.occ_mtu_load_size, c->= c2.frame.buf.payload_size, OCC_STRING_SIZE,
+ (int)sizeof(uint8_t), (int)payload= _hdr, (int)proto_hdr, BLEN(&c->c2.buf));
= doit =3D true;
}
break;=
@@ -387,12 +376,10 @@
dmsg(D_= PACKET_CONTENT, "RECEIVED OCC_REPLY");
= if (c->options.occ && !TLS_MODE(c) && c->c2.option= s_string_remote)
{
- if (!options_cmp_equal_safe((char= *) BPTR(&c->c2.buf),
- c->c2.options_string_= remote,
+ = if (!options_cmp_equal_safe((char *)BPTR(&c->c2.buf), c->c2.o= ptions_string_remote,
= c->c2.buf.len))
{
- options_warning= _safe((char *) BPTR(&c->c2.buf),

- c->c2.options= _string_remote,
+ = options_warning_safe((char *)BPTR(&c->c2.buf), c->= ;c2.options_string_remote,
= c->c2.buf.len);
}
<= span> }

@@ -403,22 +390,20 @@
= dmsg(D_PACKET_CONTENT, "RECEIVED OCC_MTU_REPLY");
c->c2.max_recv_size_remote =3D buf_read_u16(&a= mp;c->c2.buf);
c->c2.max_send_size_remot= e =3D buf_read_u16(&c->c2.buf);
- if (c->options.mtu_test
- && c->c2.max_r= ecv_size_remote > 0
- msg(M_INFO, "NOTE: Emp= irical MTU test completed [Tried,Actual] local->remote=3D[%d,%d] remote-= >local=3D[%d,%d]",
- c->c2.max_send_size_local,
- c->c2.max_recv_size= _remote,
- = c->c2.max_send_size_remote,
- c->c2.max_recv_size_local);- if (!c->opt= ions.ce.fragment
- = && (proto_is_dgram(c->options.ce.proto))+ msg(M_INFO,<= /span>
+ = "NOTE: Empirical MTU test completed [Tried,Actual] local->remote=3D= [%d,%d] remote->local=3D[%d,%d]",
+ c->c2.max_send_size_local, c-&= gt;c2.max_recv_size_remote,
+ c->c2.max_send_size_remote, c->c2.max_rec= v_size_local);
+ = if (!c->options.ce.fragment && (proto_is_dgram(c->= options.ce.proto))
&& c->c2= .max_send_size_local > TUN_MTU_MIN
= && (c->c2.max_recv_size_remote < c->c2.max_send_size_local=
|| c->c2.max_recv_size_local &= lt; c->c2.max_send_size_remote))
{
- msg(M_= INFO, "NOTE: This connection is unable to accommodate a UDP packet siz= e of %d. Consider using --fragment or --mssfix options as a workaround.&quo= t;,
+ = msg(M_INFO,
+ = "NOTE: This connection is unable to accommodate a = UDP packet size of %d. Consider using --fragment or --mssfix options as a w= orkaround.",
c->c2.max_sen= d_size_local);
}
= }
diff --git a/src/openvpn/occ.h b/src/openvpn/occ.h
index d5f208e..369d94e 100644
--- a/src/openv= pn/occ.h
+++ b/src/openvpn/occ.h
@@ -32,8 += 32,8 @@
* OCC (OpenVPN Configuration Control) protocol op= codes.
*/

-#define OCC_REQUEST 0 /* request options = string from peer */
-#d= efine OCC_REPLY 1 /* deliver options string to peer */+#define OCC_REQUEST 0 /* req= uest options string from peer */
+#define OCC_REPLY 1 /* deliver options string to peer */

/*
* Send an OCC_REQUEST = once every OCC_INTERVAL
@@ -48,11 +48,12 @@
/*

* Other OCC protocol opcodes used to estimate the MT= U empirically.
*/
-#define OCC_MTU_LOAD_REQUEST 2 /* Ask peer to send a= big packet to us */
-#= define OCC_MTU_LOAD 3 /* Send a big packet to peer */
-#define OCC_MTU_REQUEST = 4 /* Ask peer to tell us the largest
- * packe= t it has received from us so far */
-#define OCC_MTU_REPLY 5 /* Send largest packe= t size to peer */
+#d= efine OCC_MTU_LOAD_REQUEST 2 /* Ask peer to send a big packet to us */
+#define OCC_MTU_LOAD = 3 /* Send a big packet to peer */
+#define OCC_MTU_REQUEST = \
+ 4 = /* Ask peer to tell us the largest \
+ * p= acket it has received from us so far */

+#define OCC_MTU_REPLY 5 /* Send largest packet s= ize to peer */

/*
* Pr= ocess one command from mtu_load_test_sequence
@@ -63,7 +64,= 7 @@
/*
* Send an exit message to remote= .
*/
= -#define OCC_EXIT 6
+#define OCC_EXIT 6

/*
* Used to conduct a load test command sequence
@@ -71,10 +72,10 @@

*/
struct mtu_load= _test
{
- int delta; = /* determine packet size to send by using
- * this delta agains= t currently
- = * configured MTU */
+ int op; /* OCC opcode to send to peer */
+ int delta; /* determ= ine packet size to send by using
+ * this delta against currently
+ * configured MTU */=

};

extern const uint8_= t occ_magic[];
@@ -110,8 +111,7 @@
check_s= end_occ_req(struct context *c)
{
if (= event_timeout_defined(&c->c2.occ_interval)
- && event_timeout_trigger(&c= ->c2.occ_interval,
-= &c->c2.timeval,
+ && event_timeout_trigge= r(&c->c2.occ_interval, &c->c2.timeval,
= (!TO_LINK_DEF(c) && c->c2.occ_op <= ; 0) ? ETT_DEFAULT : 0))
{
ch= eck_send_occ_req_dowork(c);
@@ -125,8 +125,7 @@
<= span> check_send_occ_load_test(struct context *c)

{=
if (event_timeout_defined(&c->c2.occ_mtu_load_test_in= terval)
- &&= amp; event_timeout_trigger(&c->c2.occ_mtu_load_test_interval,=
- = &c->c2.timeval,
+ && event_timeout_trigger(&c->c2.occ_mtu_load= _test_interval, &c->c2.timeval,
= (!TO_LINK_DEF(c) && c->c2.occ_op < 0) ? ETT_DEF= AULT : 0))
{
check_send_occ_l= oad_test_dowork(c);
diff --git a/src/openvpn/openssl_compat= .h b/src/openvpn/openssl_compat.h
index 20f612e..143a3cf 10= 0644
--- a/src/openvpn/openssl_compat.h
+++= b/src/openvpn/openssl_compat.h
@@ -67,15 +67,16 @@<= br> }
}

-#define EVP_CTRL_AEAD_SET_TAG = EVP_CTRL_GCM_SET_TAG
= -#define EVP_CTRL_AEAD_GET_TAG EVP_CTRL_GCM_GET_TAG+#define EVP_CTRL_AEAD_SET_TA= G EVP_CTRL_GCM_SET_TAG
-#define RSA_F_RSA_OSSL= _PRIVATE_ENCRYPT RSA_F_RSA_EAY_PRIVATE_ENCRYPT
+#define RSA_F_RSA_OSSL_PRIVATE_ENCRYPT RS= A_F_RSA_EAY_PRIVATE_ENCRYPT
#endif

-#if defined(LIBRESSL_VERSIO= N_NUMBER) && LIBRESSL_VERSION_NUMBER < 0x3050400fL || defined(OP= ENSSL_IS_AWSLC)
+#if = defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER < 0x= 3050400fL \
+ || d= efined(OPENSSL_IS_AWSLC)
#define SSL_get_peer_tmp_key SSL_= get_server_tmp_key
#endif

@@ -85,10 +86,8 @@

/* Note that this is not a perfect em= ulation of the new function but
* is good enough for our = case of printing certificate details during
* handshake *= /
-static inline=
-int
-EVP_PKEY_get_group_name(EVP_PKEY *pkey, char *= gname, size_t gname_sz,
- size_t *gname_len)
+static inline int
+EVP_PKEY_get_group_name(EVP_PKEY *pkey, char *gname,= size_t gname_sz, size_t *gname_len)
{
= const EC_KEY *ec =3D EVP_PKEY_get0_EC_KEY(pkey);
if = (ec =3D=3D NULL)
@@ -117,13 +116,12 @@
#en= dif /* if OPENSSL_VERSION_NUMBER < 0x30000000L && !defined(OPENS= SL_NO_EC) */

#if OPENSSL_VERSION_NUMBER = < 0x30000000L
-#defi= ne EVP_MD_get0_name EVP_MD_name
-#define EVP_CIPHER_get0_name EVP_CIPHER_name
+#define EVP_MD_get0_name EVP_MD_n= ame
+#define EVP_CIPH= ER_get0_name EVP_CIPHER_name
#define EVP_CIPHER_CTX_get= _mode EVP_CIPHER_CTX_mode

/** Reduce SSL= _CTX_new_ex() to SSL_CTX_new() for OpenSSL < 3 */
-#define SSL_CTX_new_ex(libctx, propq, metho= d) \
- = SSL_CTX_new((method))
+#define SSL_CTX_new_ex(libctx, propq, method) SSL_CTX_new((method))

/* Some safe typedefs to avoid too many ifd= efs */
typedef void OSSL_LIB_CTX;
@@ -160,= 9 +158,7 @@
}

static in= line unsigned long
-ERR= _get_error_all(const char **file, int *line,
- const char **func,
- const char **data, = int *flags)

+ERR_get_= error_all(const char **file, int *line, const char **func, const char **dat= a, int *flags)
{
static const char *e= mpty =3D "";
*func =3D empty;
@@ -172,13 +168,13 @@


#endif /* OPENSS= L_VERSION_NUMBER < 0x30000000L */

-#if OPENSSL_VERSION_NUMBER < 0x30500000= && (!defined(LIBRESSL_VERSION_NUMBER) || LIBRESSL_VERSION_NUMBER &= gt; 0x3050400fL)
+#if= OPENSSL_VERSION_NUMBER < 0x30500000 \
+ && (!defined(LIBRESSL_VERSION_NUMBER) || = LIBRESSL_VERSION_NUMBER > 0x3050400fL)
static inline in= t
SSL_get0_peer_signature_name(SSL *ssl, const char **siga= lg)
{
int peer_sig_nid;
- if (SSL_get_peer_signature_nid(= ssl, &peer_sig_nid)

- && peer_sig_nid !=3D NID_undef)
+ if (SSL_get_peer_signature_nid(ssl, &= peer_sig_nid) && peer_sig_nid !=3D NID_undef)
= {
*sigalg =3D OBJ_nid2sn(peer_sig_nid);
= return 1;
@@ -194,7 +190,8 @@
*sigalg =3D NULL;

return 0;
}<= /span>
-#endif /* if OPENSSL_V= ERSION_NUMBER < 0x30500000 && (!defined(LIBRESSL_VERSION_NUMBER)= || LIBRESSL_VERSION_NUMBER > 0x3050400fL) */
+#endif /* if OPENSSL_VERSION_NUMBER < 0x305= 00000 && (!defined(LIBRESSL_VERSION_NUMBER) || \
+ LIBRESSL_VERSION_NUMBER >= 0x3050400fL) */

#if OPENSSL_VERSION_NUM= BER < 0x30200000L && OPENSSL_VERSION_NUMBER >=3D 0x30000000L<= /span>
static inline const char *
diff --git a/sr= c/openvpn/openvpn.c b/src/openvpn/openvpn.c
index 99c420a..= f1e1f76 100644
--- a/src/openvpn/openvpn.c
= +++ b/src/openvpn/openvpn.c
@@ -119,8 +119,7 @@
<= span> * printing depends on it */

for (int j =3D = 1; j < MAX_PARMS && c->options.providers.names[j]; j++)
{
- = c->options.providers.providers[j] =3D
- crypto_load_provider(c->options.provi= ders.names[j]);
+ = c->options.providers.providers[j] =3D crypto_load_provider(c->opt= ions.providers.names[j]);
}
}<= br>
@@ -129,8 +128,7 @@
{ for (int j =3D 1; j < MAX_PARMS && c->options.pro= viders.providers[j]; j++)
{
- crypto_unload_provider(c->options.pro= viders.names[j],
- = c->options.providers.providers[j]);
= + crypto_unload_provider= (c->options.providers.names[j], c->options.providers.providers[j]);
}
net_ctx_free(&c->net_ctx)= ;
}
@@ -156,14 +154,15 @@
= * @param argc - Commandline argument count.
* @param ar= gv - Commandline argument values.
*/
-static
-int
+static int
openvpn_main(int argc, char *argv[]) {
struct context c;
<= br> #if PEDANTIC
= - fprintf(stderr, "Sorry, I was built with --enable-pedantic and I = am incapable of doing any real work!\n");
+ fprintf(
+ stderr,
+ "Sorry, I was built with --enable-pedantic and= I am incapable of doing any real work!\n");
retu= rn 1;
#endif

@@ -332,15 = +331,13 @@

/* pass resta= rt status to management subsystem */
signa= l_restart_status(c.sig);
- = while (signal_reset(c.sig, SIGUSR1) =3D=3D SIGUSR1);
+ } while (signal_reset(c= .sig, SIGUSR1) =3D=3D SIGUSR1);


= env_set_destroy(c.es);
uninit_options(&= ;c.options);
gc_reset(&c.gc);
uninit_early(&c);

- }
- while (signal_reset(c.sig, SIGHUP) =3D=3D SIGHUP);
<= span style=3D"color: hsl(120, 100%, 40%);">+ } while (signal_reset(c= .sig, SIGHUP) =3D=3D SIGHUP);

}

context_gc_free(&c);
@@ -365,7 +362,7 = @@
int ret;
int i;

- if ((argv =3D = calloc(argc+1, sizeof(char *))) =3D=3D NULL)
+ if ((argv =3D calloc(argc + 1, sizeof(char *))= ) =3D=3D NULL)
{
return 1;
}
diff --git a/src/openvpn/openvpn.h b/s= rc/openvpn/openvpn.h
index 004cbc7..cd99cd4 100644--- a/src/openvpn/openvpn.h
+++ b/src/openvpn/openv= pn.h
@@ -69,7 +69,7 @@
* renegotiatio= n key */
struct key2 original_wrap_keydata;
= struct key_ctx tls_crypt_v2_server_key;
- struct buffer tls_crypt_v2_wkc; = /**< Wrapped client key */
+ struct buffer tls_crypt_v2_wkc; /**< Wrapped client key = */
struct key_ctx auth_token_key;
};<= /span>

@@ -169,10 +169,10 @@
= /* persist crypto sequence number to/from file */
st= ruct packet_id_persist pid_persist;

- struct tuntap *tuntap; /**< Tun= /tap virtual network interface. */
- bool tuntap_owned; /**< Whether the tun/tap in= terface should
- = * be cleaned up when this %context is- = * cleaned up. */
= + struct tuntap *tuntap; /**< Tun/tap virtual network interface. */
+ bool tuntap_owned= ; /**< Whether the tun/tap interface should
+ * be cleaned u= p when this %context is
+ * cleaned up. */
=
struct route_list *route_list;
/**< = List of routing information. See the
@@ -208,8 +208,7 @@
static inline bool
is_cas_pending(enum mult= i_status cas)
{
- return cas =3D=3D CAS_PENDING || cas =3D=3D CAS_PENDING_DEFE= RRED
- || cas= =3D=3D CAS_PENDING_DEFERRED_PARTIAL;
+ return cas =3D=3D CAS_PENDING || cas =3D=3D CAS_PENDI= NG_DEFERRED || cas =3D=3D CAS_PENDING_DEFERRED_PARTIAL;
}<= /span>

/**
@@ -223,9 +222,9 @@<= /span>
*/
struct context_2
{
- struct gc_arena gc;= /**< Garbage collection arena for
- * allocations do= ne in the level 2 scope
- * of this context_2 structure. */
+ struct gc_arena gc; = /**< Garbage collection arena for
+ * allocations done in the level= 2 scope
+ = * of this context_2 structure. */
<= br> /* our global wait events */
struct even= t_set *event_set;
@@ -240,13 +239,13 @@

bool link_socket_owned;

- const struct link_socket *accep= t_from; /* possibly do accept() on a parent link_socket */

+ const struct link_socket *accept= _from; /* possibly do accept() on a parent link_socket */

- struct link_soc= ket_actual *to_link_addr; /* IP address of remote */
- struct link_socket_actual from; = /* address of incoming datagram */
+ struct link_socket_actual *to_link_addr; /* IP ad= dress of remote */
+ = struct link_socket_actual from; /* address of incoming datagram= */

/* MTU frame parameters */
- struct frame frame; = /* Active frame parameters */
+ struct frame frame; /* Active frame para= meters */

#ifdef ENABLE_FRAGMENT<= br> /* Object to handle advanced MTU negotiation and datagram fra= gmentation */
@@ -297,7 +296,7 @@
char= *options_string_local;
char *options_string_remote;

- i= nt occ_op; /* INIT to -1 */
+ int occ_op; /* INIT to -1 */
= int occ_n_tries;
struct event_timeout occ_interval;=

@@ -305,11 +304,11 @@
= * Keep track of maximum packet size received so far
= * (of authenticated packets).
*/
- int original_recv_size; /* temp= orary */
- int max_r= ecv_size_local; /* max packet size received */
- int max_recv_size_remote; /* max packet s= ize received by remote */
- int max_send_size_local; /* max packet size sent */
- int max_send_size_remote; /*= max packet size sent by remote */

+ int original_recv_size; /* temporary */
+ int max_recv_size_local; /* m= ax packet size received */

+ int max_recv_size_remote; /* max packet size received by remote = */
+ int max_send_= size_local; /* max packet size sent */
+ int max_send_size_remote; /* max packet size sent b= y remote */


/* rem= ote wants us to send back a load test packet of this size */
@@ -473,63 +472,67 @@

*/
struct contex= t
{
- = struct options options; /**< Options loaded from command line or<= /span>
- = * configuration file. */
+ struct options options; /**< Options loaded from c= ommand line or
+ = * configuration file. */
=
- bool first_time; = /**< True on the first iteration of
- * OpenVPN's mai= n loop. */
+ bool = first_time; /**< True on the first iteration of
+ * Open= VPN's main loop. */

/* context m= odes */
-#define CM_P2P= 0 /* standalone point-to-point session or client */
= -#define CM_TOP 1 /* = top level of a multi-client or point-to-multipoint server */
-#define CM_TOP_CLONE 2 /* clon= e of a CM_TOP context for one thread */

-#define CM_CHILD_UDP 3 /* child context of a CM_TOP= or CM_THREAD */
-#defi= ne CM_CHILD_TCP 4 /* child context of a CM_TOP or CM_THREAD */=
- int mode; = /**< Role of this context within the
- * OpenVPN process.= Valid values are \c
-= * CM_P2P, \c CM_TOP, \c CM_TOP_CLONE,
- = * \c CM_CHILD_UDP, and \c CM_CHILD_TCP. */
+#define CM_P2P 0 /* stand= alone point-to-point session or client */
+#define CM_TOP 1 /* top level of a mu= lti-client or point-to-multipoint server */
+#define CM_TOP_CLONE 2 /* clone of a CM_T= OP context for one thread */
+#define CM_CHILD_UDP 3 /* child context of a CM_TOP or C= M_THREAD */
+#define = CM_CHILD_TCP 4 /* child context of a CM_TOP or CM_THREAD */
+ int mode; = /**< Role of this context within the
+ * OpenVPN p= rocess. Valid values are \c
+ * CM_P2P, \c CM_TOP, \c CM_TOP= _CLONE,
+ = * \c CM_CHILD_UDP, and \c CM_CHILD_TCP. */
struct multi_context *multi; /**< Pointer= to the main P2MP context.
= * Non-NULL only when mode =3D=3D CM_TOP. */
- struct gc_arena gc; = /**< Garbage collection arena for
- * allocations done in t= he scope of this
- = * context structure. */
+ struct gc_arena gc; /**< = Garbage collection arena for
+ * allocations done in the scop= e of this
+ = * context structure. */
<= br>- struct env_set *es; = /**< Set of environment variables. */
+ struct env_set *es; /**< Set of env= ironment variables. */

- openvpn_net_ctx_t net_ctx; /**< Networking API o= paque context */
+ = openvpn_net_ctx_t net_ctx; /**< Networking API opaque context */

- stru= ct signal_info *sig; /**< Internal error signaling object. */<= br>+ struct signal_info *sig= ; /**< Internal error signaling object. */
<= br> struct plugin_list *plugins; /**< List of plug-ins. */
- bool plugins_owned; = /**< Whether the plug-ins should be
- * cleaned up whe= n this %context is
- = * cleaned up. */
+ bool plugins_owned; /**< Wheth= er the plug-ins should be
+ * cleaned up when this %context i= s
+ = * cleaned up. */

- bool did_we_daemonize; /**< Whe= ther demonization has already
- * taken place. */
+ bool did_we_daemonize; /= **< Whether demonization has already

+ * taken place. */

struct context_persist persist;
/**< Persistent %context. */
- struct context_0 *c0; /**< Level 0 %= context. */
- struct= context_1 c1; /**< Level 1 %context. */
- struct context_2 c2; /**< Level = 2 %context. */
+ s= truct context_0 *c0; /**< Level 0 %context. */
+ struct context_1 c1; /**< Level 1 %co= ntext. */
+ struct= context_2 c2; /**< Level 2 %context. */
};
=
/*
* Check for a signal when ins= ide an event loop
*/
-#define EVENT_LOOP_CHECK_SIGNAL(c, func, arg) \- if (IS_SIG(c)) = \
- {= \
- const int brk =3D func(arg); \<= br>- perf_pop(); = \
- = if (brk) { \
- break;} \<= /span>
- else { = \
- continue;} \
+#define EVENT_LOOP_CHECK_SIGNAL(c, fun= c, arg) \
+ if (IS= _SIG(c)) \
+ { \+ const int brk =3D fun= c(arg); \
= + perf_pop(); \
+ if (brk) = \
+ { = \
+ break; \
+ } = \
+ e= lse \
+ { \+ continue; = \
+= } \
}

/*
@@ -537,14 +540,15 @@
* have been compiled in.
*/

-#define TLS_MODE(c= ) ((c)->c2.tls_multi !=3D NULL)
-#define PROTO_DUMP_FLAGS (check_debug_level(D_LINK_RW_VERBOSE)= ? (PD_SHOW_DATA|PD_VERBOSE) : 0)
-#define PROTO_DUMP(buf, gc) protocol_dump((buf), \
- = PROTO_DUMP_FLAGS \

- |(c->c2.tls_multi ? PD_= TLS : 0) \
- = |(c->options.tls_auth_file ? md_kt_size= (c->c1.ks.key_type.digest) : 0) \
- |(c->options.tl= s_crypt_file || c->options.tls_crypt_v2_file ? PD_TLS_CRYPT : 0), \
- = gc)
+= #define TLS_MODE(c) ((c)->c2.tls_multi !=3D NULL)
+#define PROTO_DUMP_FLAGS (check_debug= _level(D_LINK_RW_VERBOSE) ? (PD_SHOW_DATA | PD_VERBOSE) : 0)
+#define PROTO_DUMP(buf, gc) = \

+ protocol_dump( = \

+ (buf), = \

<= span style=3D"color: hsl(120, 100%, 40%);">+ PROTO_DUMP_FLAGS | (c-&= gt;c2.tls_multi ? PD_TLS : 0) \
<= br>+ | (c->option= s.tls_auth_file ? md_kt_size(c->c1.ks.key_type.digest) : 0) \<= /span>
+ | (c->= ;options.tls_crypt_file || c->options.tls_crypt_v2_file ? PD_TLS_CRYPT := 0), \
+ gc)

/* this represents "disabled peer-id= " */
#define MAX_PEER_ID 0xFFFFFF
dif= f --git a/src/openvpn/options.c b/src/openvpn/options.c
ind= ex 67139b8..672b954 100644
--- a/src/openvpn/options.c
+++ b/src/openvpn/options.c
@@ -67,8 +67,7 @@
#include "memdbg.h"
#include &qu= ot;options_util.h"

-const char title_string[] =3D
- PACKAGE_STRING
+const char title_string[] =3D PACKAGE_STRING
#ifdef CONFIGURE_GIT_REVISION
" [gi= t:" CONFIGURE_GIT_REVISION CONFIGURE_GIT_FLAGS "]" #endif
@@ -114,7 +113,7 @@
#ifdef = CONFIGURE_GIT_REVISION
" built on " __DATE__=
#endif
+ ;
#ifndef ENABLE_SMALL

= @@ -698,7 +697,7 @@
" = cache until token is removed.\n"
&quo= t;--pkcs11-id-management : Acquire identity from management interf= ace.\n"
"--pkcs11-id serialized-id 'id&#= 39; : Identity to use, get using standalone --show-pkcs11-ids\n"
-#endif /*= ENABLE_PKCS11 */
+#e= ndif /* ENABLE_PKCS11 */
"\n"
"SSL Library information:\n"

"--= show-ciphers : Show cipher algorithms to use with --cipher option.\n"=
@@ -787,13 +786,13 @@
"--show-pk= cs11-ids provider [cert_private] : Show PKCS#11 available ids.\n"
#endif
" = --verb option can be added *BEFORE* this.\n"-#endif = /* ENABLE_PKCS11 */
= +#endif /* ENABLE_PKCS11 */
"\n"
<= span> "General Standalone Options:\n"

#ifdef= ENABLE_DEBUG
"--show-gateway [address]: Show inf= o about gateway [to v4/v6 address].\n"
#endif<= br>-;
+ ;

#endif= /* !ENABLE_SMALL */

@@ -894,7 +893,7 @@<= /span>
#endif
#ifdef ENABLE_PKCS11
o->pkcs11_pin_cache_period =3D -1;

-#endif /* ENABLE_PKCS11 */<= br>+#endif /* ENABLE_PKCS11 */<= /span>

/* P2MP server context features */
o->auth_token_generate =3D false;
@@= -909,7 +908,7 @@
/* Error out if we can't fin= d a valid temporary directory, which should
* be = very unlikely. */
msg(M_USAGE, "Could not fin= d a suitable temporary directory."
- " (GetTempPath() failed). Consider usin= g --tmp-dir");
+= " (GetTempPath() failed). Consider using --tmp-d= ir");
}
#else /* ifdef _WIN32 *= /
/* Non-windows platforms use $TMPDIR, and if not set= , default to '/tmp' */
@@ -972,23 +971,19 @@=
}

#define SHOW_PARM(name, val= ue, format) msg(D_SHOW_PARMS, " " #name " =3D " format= , (value))
-#define SHO= W_STR(var) SHOW_PARM(var, (o->var ? o->var : "[UNDEF]"= ;), "'%s'")
-#define SHOW_STR_INLINE(var) SHOW_PARM(var, \
- = o->var ## _inline ? "[INLINE]" : \
- (o-&g= t;var ? o->var : "[UNDEF]"), \
- "'= %s'")
-#define= SHOW_INT(var) SHOW_PARM(var, o->var, "%d")
-#define SHOW_UINT(var) SHOW_P= ARM(var, o->var, "%u")

-#define SHOW_INT64(var) SHOW_PARM(var, o->var, "%= " PRIi64)
-#define= SHOW_UNSIGNED(var) SHOW_PARM(var, o->var, "0x%08x")-#define SHOW_BOOL(var) SH= OW_PARM(var, (o->var ? "ENABLED" : "DISABLED"), &quo= t;%s");
+#define= SHOW_STR(var) SHOW_PARM(var, (o->var ? o->var : &qu= ot;[UNDEF]"), "'%s'")
+#define SHOW_STR_INLINE(var) \
+ SHOW_PARM(var, o->var##_inline ?= "[INLINE]" : (o->var ? o->var : "[UNDEF]"), &quo= t;'%s'")
+#define SHOW_INT(var) SHOW_PARM(var, o->var, "%d")
+#define SHOW_UINT(var) = SHOW_PARM(var, o->var, "%u")
+#define SHOW_INT64(var) SHOW_PARM(var, o->va= r, "%" PRIi64)
+#define SHOW_UNSIGNED(var) SHOW_PARM(var, o->var, "0x%08x"= ;)
+#define SHOW_BOOL= (var) SHOW_PARM(var, (o->var ? "ENABLED" : "DISABLED&= quot;), "%s");

#endif /* ifnde= f ENABLE_SMALL */

static void
= -setenv_connection_entry(struct e= nv_set *es,
- = const struct connection_entry *e,
- const int i)
+setenv_connection_entry(struct e= nv_set *es, const struct connection_entry *e, const int i)

= {
setenv_str_i(es, "remote", e->remote, = i);
setenv_str_i(es, "remote_port", e->re= mote_port, i);
@@ -1006,9 +1001,7 @@
}

static void
-setenv_local_entry(struct env_set *es,
- const struct loca= l_entry *e,

- = const int i)
+setenv_local_entry(struct env_set *es, const struct local_entry *e, const= int i)
{
setenv_str_i(es, "prot= o", proto2ascii(e->proto, AF_UNSPEC, false), i);
= setenv_str_i(es, "local", e->local, i);
@@ = -1030,7 +1023,7 @@
int i;
= for (i =3D 0; i < o->connection_list->len; ++i)
= {
- = setenv_connection_entry(es, o->connection_list->array[i], i+1);
+ setenv_connec= tion_entry(es, o->connection_list->array[i], i + 1);
= }
}
else
@@ -1042,7 +1035,7 @@

{
for = (int i =3D 0; i < o->ce.local_list->len; i++)
= {
- set= env_local_entry(es, o->ce.local_list->array[i], i+1);
+ setenv_local_entry(es, = o->ce.local_list->array[i], i + 1);

}=
}
}
@@ -1087,12 +1080,12 @@=
for (current =3D *list, prev =3D NULL; current !=3D N= ULL; current =3D current->next)
{
= char *tmp_value =3D NULL;
- if (!strncmp(current->string, "foreign_option_&= quot;, sizeof("foreign_option_")-1))
+ if (!strncmp(current->string, "f= oreign_option_", sizeof("foreign_option_") - 1))
<= span> {

tmp_value =3D strchr(current-&= gt;string, '=3D');
if (tmp_value &= & ++tmp_value)
{
- if (!strncmp(tmp_value, "d= hcp-option ", sizeof("dhcp-option ")-1))
+ if (!strncmp(tmp_value,= "dhcp-option ", sizeof("dhcp-option ") - 1)) {
if (prev)
{
@@ -1156,18 +1149,18 @= @
}

static bool<= br>-ipv6_addr_safe_hexplusbits( c= onst char *ipv6_prefix_spec )
+ipv6_addr_safe_hexplusbits(const char *ipv6_prefix_spec) {
struct in6_addr t_addr;
= unsigned int t_bits;

- return get_ipv6_addr( ipv6_prefix_spec, &t_addr,= &t_bits, M_WARN );
+ return get_ipv6_addr(ipv6_prefix_spec, &t_addr, &t_bits, M_= WARN);
}

static char *<= /span>
string_substitute(const char *src, int from, int to, struc= t gc_arena *gc)
{
- char *ret =3D (char *) gc_malloc(strlen(src) + 1, true, gc= );
+ char *ret =3D= (char *)gc_malloc(strlen(src) + 1, true, gc);
char *d= est =3D ret;
char c;

@@ -1179,8 +1172,7 @@

c =3D to;
}

*dest++ =3D c;
- }
- while (c);
+ } while (c);
return ret;
}


@@ -1208,9 +1200,7 @@
while (*cp && i < nbytes)

{ /* valid segments consist of exactly two hex digits, then = ':' or EOS */
-= if (!isxdigit(cp[0])
- || !isxdigit(cp[1])
- || (cp[2] !=3D ':' && cp[2] != =3D '\0')
+ = if (!isxdigit(cp[0]) || !isxdigit(cp[1]) || (cp[2] !=3D ':' &= amp;& cp[2] !=3D '\0')
|| sscanf(c= p, "%x", &byte) !=3D 1)
{
= msg(msglevel, "format error in hash fingerprint: %s= ", str);
@@ -1228,7 +1218,8 @@
}<= /span>
if (i < nbytes)
{
- msg(msglevel, "hash f= ingerprint is wrong length - expected %d bytes, got %d: %s", nbytes, i= , str);

+ msg(= msglevel, "hash fingerprint is wrong length - expected %d bytes, got %= d: %s", nbytes, i,
+ str);
}
else if (= term !=3D '\0')
{
@@ -1248,8 += 1239,7 @@
* @param gc The returned list items = will be allocated in this gc
*/
static s= truct verify_hash_list *
- = struct gc_arena *gc)
+parse_hash_fingerprint_multiline(const char *str, int nbyte= s, int msglevel, struct gc_arena *gc)
{
= struct gc_arena gc_temp =3D gc_new();
char *lines = =3D string_alloc(str, &gc_temp);
@@ -1270,8 +1260,7 @@<= /span>
continue;
}
- struc= t verify_hash_list *hash =3D parse_hash_fingerprint(line, nbytes,- = msglevel, gc);
+ struct verify_hash_list *hash =3D parse_= hash_fingerprint(line, nbytes, msglevel, gc);

<= span> if (!hash)

{
@@ -129= 6,7 +1285,7 @@
int i;
for (i =3D = 0; i < len; ++i)
{
- msg(D_SHOW_PARMS, " %s[%d] =3D %s",= name, i, array[i] );
+ msg(D_SHOW_PARMS, " %s[%d] =3D %s", name, i, array[i])= ;
}
}

@@ -1307,10 +1296,7 @@

int i;
= for (i =3D 0; i < len; ++i)
{
- msg(D_SHOW_PARMS, " %s[%d] = =3D %s",
- = name,
- = i,
- print_i= n_addr_t(array[i], 0, &gc));
+ msg(D_SHOW_PARMS, " %s[%d] =3D %s", name, i= , print_in_addr_t(array[i], 0, &gc));
}
= gc_free(&gc);
}
@@ -1356,14= +1342,13 @@
}
}
sta= tic void
-dhcp_option_a= ddress_parse(const char *name, const char *parm, in_addr_t *array, int *len= , int msglevel)
+dhcp= _option_address_parse(const char *name, const char *parm, in_addr_t *array,= int *len,
+ = int msglevel)
{
if (= *len >=3D N_DHCP_ADDR)
{
- msg(msglevel, "--dhcp-option %s: ma= ximum of %d %s servers can be specified",
- name,
- N_DHCP_ADDR,
- name);
+ msg(msglevel, "--dhcp-option %s: maximu= m of %d %s servers can be specified", name,
+ N_DHCP_ADDR, name);
}

else
{
@= @ -1408,12 +1393,15 @@

msg(D_SHOW_PA= RMS, " server_network =3D %s", print_in_addr_t(o->server_netw= ork, 0, &gc));
msg(D_SHOW_PARMS, " server_ne= tmask =3D %s", print_in_addr_t(o->server_netmask, 0, &gc));
- msg(D_SHOW_PARMS, &qu= ot; server_network_ipv6 =3D %s", print_in6_addr(o->server_network_= ipv6, 0, &gc) );
= + msg(D_SHOW_PARMS, " server_network_ipv6 =3D %s", print_in6_= addr(o->server_network_ipv6, 0, &gc));
SHOW_INT= (server_netbits_ipv6);
msg(D_SHOW_PARMS, " serve= r_bridge_ip =3D %s", print_in_addr_t(o->server_bridge_ip, 0, &g= c));
- msg(D_SHOW_PA= RMS, " server_bridge_netmask =3D %s", print_in_addr_t(o->serv= er_bridge_netmask, 0, &gc));
- msg(D_SHOW_PARMS, " server_bridge_pool_start =3D %s&qu= ot;, print_in_addr_t(o->server_bridge_pool_start, 0, &gc));- msg(D_SHOW_PARMS, " = server_bridge_pool_end =3D %s", print_in_addr_t(o->server_bridge_po= ol_end, 0, &gc));
+ msg(D_SHOW_PARMS, " server_bridge_netmask =3D %s",<= br>+ print_in_addr_t(o-&= gt;server_bridge_netmask, 0, &gc));
+ msg(D_SHOW_PARMS, " server_bridge_pool_start = =3D %s",
+ = print_in_addr_t(o->server_bridge_pool_start, 0, &gc));
<= span style=3D"color: hsl(120, 100%, 40%);">+ msg(D_SHOW_PARMS, " s= erver_bridge_pool_end =3D %s",

+ print_in_addr_t(o->server_bridge_pool_end, 0, &a= mp;gc));
if (o->push_list.head)
= {
const struct push_entry *e =3D o->push_list= .head;
@@ -1427,13 +1415,16 @@
}
}
SHOW_BOOL(ifconfig_pool_defined)= ;
- msg(D_SHOW_PARMS= , " ifconfig_pool_start =3D %s", print_in_addr_t(o->ifconfig_= pool_start, 0, &gc));
+ msg(D_SHOW_PARMS, " ifconfig_pool_start =3D %s",
+ print_in_addr_t(o= ->ifconfig_pool_start, 0, &gc));
msg(D_SHOW_PAR= MS, " ifconfig_pool_end =3D %s", print_in_addr_t(o->ifconfig_= pool_end, 0, &gc));
- msg(D_SHOW_PARMS, " ifconfig_pool_netmask =3D %s", print_i= n_addr_t(o->ifconfig_pool_netmask, 0, &gc));
+ msg(D_SHOW_PARMS, " ifconfig_po= ol_netmask =3D %s",
+ print_in_addr_t(o->ifconfig_pool_netmask, 0, &gc));
SHOW_STR(ifconfig_pool_persist_filename);
SHOW_INT(ifconfig_pool_persist_refresh_freq);

SH= OW_BOOL(ifconfig_ipv6_pool_defined);
- msg(D_SHOW_PARMS, " ifconfig_ipv6_pool_base =3D %s= ", print_in6_addr(o->ifconfig_ipv6_pool_base, 0, &gc));<= br>+ msg(D_SHOW_PARMS, "= ; ifconfig_ipv6_pool_base =3D %s",
+ print_in6_addr(o->ifconfig_ipv6_pool_base, = 0, &gc));
SHOW_INT(ifconfig_ipv6_pool_netbits);
SHOW_INT(n_bcast_buf);
SHOW_INT(tcp= _queue_limit);
@@ -1447,11 +1438,15 @@
= SHOW_BOOL(ccd_exclusive);
SHOW_STR(tmp_dir); SHOW_BOOL(push_ifconfig_defined);
- msg(D_SHOW_PARMS, " push_ifconfig_local = =3D %s", print_in_addr_t(o->push_ifconfig_local, 0, &gc));
- msg(D_SHOW_PARMS, &quo= t; push_ifconfig_remote_netmask =3D %s", print_in_addr_t(o->push_i= fconfig_remote_netmask, 0, &gc));
+ msg(D_SHOW_PARMS, " push_ifconfig_local =3D %s&= quot;,
+ print= _in_addr_t(o->push_ifconfig_local, 0, &gc));
+ msg(D_SHOW_PARMS, " push_ifconf= ig_remote_netmask =3D %s",
+ print_in_addr_t(o->push_ifconfig_remote_netmask, 0, = &gc));
SHOW_BOOL(push_ifconfig_ipv6_defined);
- msg(D_SHOW_PARMS, &quo= t; push_ifconfig_ipv6_local =3D %s/%d", print_in6_addr(o->push_ifc= onfig_ipv6_local, 0, &gc), o->push_ifconfig_ipv6_netbits );- msg(D_SHOW_PARMS, " = push_ifconfig_ipv6_remote =3D %s", print_in6_addr(o->push_ifconfig_= ipv6_remote, 0, &gc));
+ msg(D_SHOW_PARMS, " push_ifconfig_ipv6_local =3D %s/%d&quo= t;,
+ print_in= 6_addr(o->push_ifconfig_ipv6_local, 0, &gc), o->push_ifconfig_ipv= 6_netbits);
+ msg(= D_SHOW_PARMS, " push_ifconfig_ipv6_remote =3D %s",
+ print_in6_addr(o->push= _ifconfig_ipv6_remote, 0, &gc));

SHOW_BOOL(enable_= c2c);
SHOW_BOOL(duplicate_cn);
SH= OW_INT(cf_max);
@@ -1484,16 +1479,13 @@
#e= ndif /* ! ENABLE_SMALL */

static void
-option_iroute(struct opt= ions *o,
- = const char *network_str,
- const char *netmask_str,
- int msglevel)
+option_iroute(struct options *o, const char *n= etwork_str, const char *netmask_str, int msglevel)
{
struct iroute *ir;

A= LLOC_OBJ_GC(ir, struct iroute, &o->gc);
ir->= network =3D getaddr(GETADDR_HOST_ORDER, network_str, 0, NULL, NULL);=
- ir->netbits =3D 32; = /* host route if no netmask given */
+ ir->netbits =3D 32; /* host route if no ne= tmask given */

if (netmask_str)
{
@@ -1502,8 +1494,7 @@
<= /span>
if (ir->netbits < 0)
= {
- msg(ms= glevel, "in --iroute %s %s : Bad network/subnet specification",
- network= _str,
+ ms= g(msglevel, "in --iroute %s %s : Bad network/subnet specification"= ;, network_str,
netmask_str);
return;

}
@@ -151= 4,18 +1505,15 @@
}

stat= ic void
-option_iroute_= ipv6(struct options *o,
- const char *prefix_str,
- int msglevel)
+option_iroute_ipv6(struct options *o, c= onst char *prefix_str, int msglevel)
{
= struct iroute_ipv6 *ir;

ALLOC_OBJ_= GC(ir, struct iroute_ipv6, &o->gc);

- if (!get_ipv6_addr(prefix_str, &= amp;ir->network, &ir->netbits, msglevel ))

+ if (!get_ipv6_addr(prefix_str, &i= r->network, &ir->netbits, msglevel))
{
- msg(msglevel, "= ;in --iroute-ipv6 %s: Bad IPv6 prefix specification",
- prefix_str);
+ msg(msglevel, "in --= iroute-ipv6 %s: Bad IPv6 prefix specification", prefix_str);
return;
}

= @@ -1548,17 +1536,16 @@
SHOW_BOOL(nocache);
SHOW_STR(http_version);
SHOW_STR(user= _agent);
- for (i = =3D 0; i < MAX_CUSTOM_HTTP_HEADER && o->custom_headers[i].nam= e; i++)
+ for (i = =3D 0; i < MAX_CUSTOM_HTTP_HEADER && o->custom_headers[i].nam= e; i++)
{
if (o->custom_he= aders[i].content)
{
- msg(D_SHOW_PARMS, " custom_header[= %d] =3D %s: %s", i,
+ = msg(D_SHOW_PARMS, " custom_header[%d] =3D %s: %s", i, o->cust= om_headers[i].name,
+= o->custom_headers[i].content);
= }
else
{
- msg(D_SHOW_PARMS, " = custom_header[%d] =3D %s", i,
- o->custom_headers[i].name);
+ msg(D_SHOW_PARMS, "= ; custom_header[%d] =3D %s", i, o->custom_headers[i].name);
=
}
}
msg(D_SHOW= _PARMS, "END http_proxy");
@@ -1615,7 +1602,8 @@<= /span>
for (int i =3D 0; i < o->local_list->len; i++= )
{
msg(D_SHOW_PARMS, " = [%s]:%s-%s", o->local_list->array[i]->local,
- o->local_list->ar= ray[i]->port, proto2ascii(o->local_list->array[i]->proto, o->= ;af, false));

+ = o->local_list->array[i]->port,
+ proto2ascii(o->local_list->arra= y[i]->proto, o->af, false));
}
= SHOW_STR(remote);
SHOW_STR(remote_port);@@ -1652,8 +1640,7 @@
SHOW_INT(explicit_exit_no= tification);

SHOW_STR_INLINE(tls_aut= h_file);
- SHOW_PARM= (key_direction, keydirection2ascii(o->key_direction, false, true),
- "%s"= ;);
+ SHOW_PARM(ke= y_direction, keydirection2ascii(o->key_direction, false, true), "%s= ");
SHOW_STR_INLINE(tls_crypt_file);
SHOW_STR_INLINE(tls_crypt_v2_file);

}
<= span>@@ -1908,7 +1895,7 @@

SHOW_INT(ns_cert_type);
{
int i;
- for (i =3D 0; i<MAX_PARMS; i++)<= /span>
+ for (i =3D 0= ; i < MAX_PARMS; i++)
{
= SHOW_INT(remote_cert_ku[i]);
}
@@ -1920,12 +1907,11 @@

SHOW_INT(verify_hash_de= pth);
struct gc_arena gc =3D gc_new();
<= span> struct verify_hash_list *hl =3D o->verify_hash;

= - int digest_len =3D (o-&g= t;verify_hash_algo =3D=3D MD_SHA1) ? SHA_DIGEST_LENGTH :
- SHA256_DIGEST_L= ENGTH;
+ int d= igest_len =3D
+ = (o->verify_hash_algo =3D=3D MD_SHA1) ? SHA_DIGEST_LENGTH : SHA256_= DIGEST_LENGTH;
while (hl)
= {
- char *s= =3D format_hex_ex(hl->hash, digest_len, 0,
- 1, ":&quo= t;, &gc);
+ = char *s =3D format_hex_ex(hl->hash, digest_len, 0, 1, ":"= ;, &gc);
SHOW_PARM(verify_hash, s, "%= s");
hl =3D hl->next;
= }
@@ -1951,36 +1937,38 @@
#ifdef = ENABLE_PKCS11
{
int i;=
- for (i =3D 0; i<M= AX_PARMS && o->pkcs11_providers[i] !=3D NULL; i++)
+ for (i =3D 0; i < MAX_= PARMS && o->pkcs11_providers[i] !=3D NULL; i++)

= {
SHOW_PARM(pkcs11_providers, o->p= kcs11_providers[i], "%s");
}
<= span> }

{
int i;- for (i =3D 0; i<MAX= _PARMS; i++)
+ = for (i =3D 0; i < MAX_PARMS; i++)
{
= - SHOW_PARM(pkcs11_pro= tected_authentication, o->pkcs11_protected_authentication[i] ? "ENA= BLED" : "DISABLED", "%s");
+ SHOW_PARM(pkcs11_protected_au= thentication,
+ = o->pkcs11_protected_authentication[i] ? "ENABLED&qu= ot; : "DISABLED", "%s");
}
}
{
int i;<= /span>
- for (i =3D 0; = i<MAX_PARMS; i++)
= + for (i =3D 0; i < MAX_PARMS; i++)
{
SHOW_PARM(pkcs11_private_mode, o->pkcs11_priv= ate_mode[i], "%08x");
}
= }
{
int i;
- for (i =3D 0; i<MAX_PARM= S; i++)

+ for = (i =3D 0; i < MAX_PARMS; i++)
{
- SHOW_PARM(pkcs11_cert_pri= vate, o->pkcs11_cert_private[i] ? "ENABLED" : "DISABLED&q= uot;, "%s");

+ "%s");
= }
}
SHOW_INT(pkcs1= 1_pin_cache_period);
SHOW_STR(pkcs11_id);
SHOW_BOOL(pkcs11_id_management);

-#endif /* ENABLE_PKCS11 */
<= span style=3D"color: hsl(120, 100%, 40%);">+#endif /* ENABLE_PKCS11 */

show_p2mp_parms(o);

@@ -2001,9 +1989,7 @@
#ifdef ENABLE_MANAGEME= NT

static struct http_proxy_options *
-parse_http_proxy_overrid= e(const char *server,
-= const char *port,
- const char *flags,+parse_http_proxy_override(co= nst char *server, const char *port, const char *flags,
= struct gc_arena *gc)
{
if (server && port)

@@ -2058,7 +2044,8 @@<= /span>
}
else
{
- msg(M_WARN, "= ;Note: option http-proxy-override ignored because no TCP-based connection p= rofiles are defined");
+ msg(M_WARN,
+ "Note: option http-proxy-override ignored because = no TCP-based connection profiles are defined");
}=
}

@@ -2075,8 +2062,7 @@=
}

static struct local_= entry *
-alloc_local_en= try(struct connection_entry *ce, const int msglevel,
- struct gc_arena *gc)
+alloc_local_entry(struct= connection_entry *ce, const int msglevel, struct gc_arena *gc)
<= span> {

struct local_list *l =3D alloc_local_list_if_u= ndef(ce, gc);
struct local_entry *e;
@= @ -2089,7 +2075,9 @@
struct local_entry **new_arra= y =3D gc_realloc(l->array, new_cap * elem_size, gc);
= if (!new_array)
{
- msg(msglevel, "Unable to proces= s more local options: out of memory. Number of entries =3D %d", l->= len);
+ ms= g(msglevel,
+ = "Unable to process more local options: out of memory. Number o= f entries =3D %d",
+ l->len);
return NULL;
}

@@ -2123,10 +21= 11,13 @@
if (l->len =3D=3D l->capacity) {
int capacity =3D l->capacity + C= ONNECTION_LIST_SIZE;
- = struct connection_entry **ce =3D gc_realloc(l->array, capacity*si= zeof(struct connection_entry *), &options->gc);
+ struct connection_entry **ce =3D=
+ gc_real= loc(l->array, capacity * sizeof(struct connection_entry *), &options= ->gc);
if (ce =3D=3D NULL)
= {
- msg= (msglevel, "Unable to process more connection options: out of memory. = Number of entries =3D %d", l->len);
+ msg(msglevel,
+ "Unable to process more = connection options: out of memory. Number of entries =3D %d",+ l->len);<= /span>
return NULL;
}=
l->array =3D ce;
@@ -2156,10 +2147,13= @@
if (l->len =3D=3D l->capacity)
{

int capacity =3D l->capacity + CONNEC= TION_LIST_SIZE;
- = struct remote_entry **re =3D gc_realloc(l->array, capacity*sizeof(stru= ct remote_entry *), &options->gc);
+ struct remote_entry **re =3D
+ gc_realloc(l->array, = capacity * sizeof(struct remote_entry *), &options->gc);
<= span> if (re =3D=3D NULL)

{
- msg(msglevel, "Unab= le to process more remote options: out of memory. Number of entries =3D %d&= quot;, l->len);

+ = msg(msglevel,
+ "Unable to process more remote options: out of me= mory. Number of entries =3D %d",
+ l->len);
= return NULL;
}
l->arra= y =3D re;
@@ -2223,8 +2217,7 @@
}
static void
-connection_entry_preload_key(const char **key_file, bool *= key_inline,
- = struct gc_arena *gc)
+connection_entry_preload_key(const char **key_file, boo= l *key_inline, struct gc_arena *gc)
{
= if (key_file && *key_file && !(*key_inline))
{

@@ -2234,7 +2227,7 @@
= msg(M_FATAL, "Cannot pre-load keyfile (%s)", *key_file);=
}

- *key_file =3D (const char *) in.data;
+ *key_file =3D (const cha= r *)in.data;

*key_inline =3D true;
}

}
@@ -2249,13 +2242,11 @@ }
#endif

- if (options->verify_hash_no_ca
- || options->p= kcs12_file
- || = options->ca_file
+= if (options->verify_hash_no_ca || options->pkcs12_file || options= ->ca_file
#ifndef ENABLE_CRYPTO_MBEDTLS
|| options->ca_path

#endif
- )
+ )
{
= return;
}
@@ -2268,14 +2259,19 @@<= /span>
msg(M_USAGE, "%s", str);
}<= /span>

-#def= ine MUST_BE_UNDEF(parm, parm_name) \
- if (options->parm !=3D defaults.parm) { msg(M_USAGE, = use_err, parm_name); }
+ if (options->parm !=3D defaults.parm) \=
+ { = \
+ msg(M_USAGE, use_err, parm_name); \
+ }
#define MUST_BE_FALSE(c= ondition, parm_name) \
= - if (condition) { msg(M_USAGE, use_err, parm_name); }
+ if (condition) = \
+ { = \
+ msg(M_USAGE, use_err, parm_name); \
+ }


= static void
-opt= ions_postprocess_verify_ce(const struct options *options,
- const str= uct connection_entry *ce)
+options_postprocess_verify_ce(const struct options *options, const st= ruct connection_entry *ce)
{
struct o= ptions defaults;
int dev =3D DEV_TYPE_UNDEF;@@ -2303,9 +2299,8 @@
*/
= if (ce->proto =3D=3D PROTO_TCP)
{
- msg(M_USAGE,
- "--proto tcp is ambiguo= us in this context. Please specify "
- "--proto tcp-server or --proto tcp-cli= ent");
+ = msg(M_USAGE, "--proto tcp is ambiguous in this context. Please specify= "
+ = "--proto tcp-server or --proto tcp-client");
<= span> }


/*
@@ -2= 345,16 +2340,13 @@
if (string_defined_equal(ce->rem= ote, options->ifconfig_local)
|| string_defined= _equal(ce->remote, options->ifconfig_remote_netmask))
{

- msg(M_= USAGE,
- &qu= ot;--local and --remote addresses must be distinct from --ifconfig "
- "addre= sses");
+ = msg(M_USAGE, "--local and --remote addresses must be distinct from --= ifconfig "
+ = "addresses");
}
<= span>

- if (string_= defined_equal(options->ifconfig_local,
- options->ifconfig_remot= e_netmask))
+ if (= string_defined_equal(options->ifconfig_local, options->ifconfig_remot= e_netmask))
{
- msg(M_USAGE,
- "local and remote/netmask --ifconfig addresses= must be different");
+ msg(M_USAGE, "local and remote/netmask --ifconfig addre= sses must be different");
}

if (ce->bind_defined && !ce->bind_local)
@@ -2364,8 +2356,7 @@

= if (ce->local_port_defined && !ce->bind_local)
{

- msg(M= _USAGE,
- &q= uot;--lport and --nobind don't make sense when used together");
+ msg(M_USAGE, &= quot;--lport and --nobind don't make sense when used together");
}

if (!ce->re= mote && !ce->bind_local)
@@ -2377,8 +2368,7 @@
{
struct local_entry *le =3D c= e->local_list->array[i];

- if (proto_is_net(le->proto)- && string_d= efined_equal(le->local, ce->remote)
+ if (proto_is_net(le->proto) && str= ing_defined_equal(le->local, ce->remote)
= && string_defined_equal(le->port, ce->remote_port)) {
msg(M_USAGE, "--remote= and one of the --local addresses are the same");
@@ -= 2404,7 +2394,8 @@
&& (options->manageme= nt_flags
|| options->management_log_history= _cache !=3D defaults.management_log_history_cache))
{<= /span>
- msg(M_USAGE, &= quot;--management is not specified, however one or more options which modif= y the behavior of --management were specified");
+ msg(M_USAGE,
+ "--management is not sp= ecified, however one or more options which modify the behavior of --managem= ent were specified");
}
<= br> if ((options->management_client_user || options->manage= ment_client_group)
@@ -2413,24 +2404,21 @@
= msg(M_USAGE, "--management-client-(user|group) can only be us= ed on unix domain sockets");
}
<= /span>
- if (options->ma= nagement_addr
- = && !(options->management_flags & MF_UNIX_SOCK)
+ if (options->management_ad= dr && !(options->management_flags & MF_UNIX_SOCK)

= && (!options->management_user_pass))
{

msg(M_WARN, "WARNING: Using --mana= gement on a TCP port WITHOUT "
- "passwords is STRONGLY discouraged and consi= dered insecure");
- if ((tls_version_max() >=3D TLS_VER_1_3)
- && (options->manage= ment_flags & MF_EXTERNAL_KEY)
- && !(options->management_flags & (MF_EXT= ERNAL_KEY_NOPADDING))
-= )
+ if ((t= ls_version_max() >=3D TLS_VER_1_3) && (options->management_fl= ags & MF_EXTERNAL_KEY)
+ && !(options->management_flags & (MF_EXTERNAL= _KEY_NOPADDING)))
{
msg(M_FAT= AL, "management-external-key with TLS 1.3 or later requires "
- "nopaddi= ng argument/support");
+ "nopadding argument/support");
}
#endif
/*@@ -2438,7 +2426,8 @@
*/

#ifdef _WIN32
- if (dev =3D=3D DEV_TYPE_TUN && !(pull || (options->ifc= onfig_local && options->ifconfig_remote_netmask)))
+ if (dev =3D=3D DEV_TYPE_TUN
+ && !(= pull || (options->ifconfig_local && options->ifconfig_remote_= netmask)))
{
msg(M_USAGE, &qu= ot;On Windows, --ifconfig is required when --dev tun is used");=
}
@@ -2454,14 +2443,13 @@
= const char *prefix =3D "Some --dhcp-option or --dns options req= uire DHCP server";
if (options->windows_dr= iver !=3D WINDOWS_DRIVER_TAP_WINDOWS6)
{- msg(M_USAGE, "= %s, which is not supported by the selected %s driver",
- prefix, print_tun_bac= kend_driver(options->windows_driver));

+ msg(M_USAGE, "%s, which is not suppo= rted by the selected %s driver", prefix,
+ print_tun_backend_driver(options-= >windows_driver));
}
e= lse if (options->tuntap_options.ip_win32_type !=3D IPW32_SET_DHCP_MASQ
&& options->tuntap_options.ip_w= in32_type !=3D IPW32_SET_ADAPTIVE)
{
- msg(M_USAGE, "%s, = which requires --ip-win32 dynamic or adaptive",

- prefix);
+ msg(M_USAGE, "%s, whi= ch requires --ip-win32 dynamic or adaptive", prefix);
= }
}
#endif /* ifdef _WIN32 *= /
@@ -2484,21 +2472,18 @@

if ((ce->http_proxy_options) && ce->proto !=3D PROTO_TC= P_CLIENT)

{
- 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_optio= ns) && !ce->http_proxy_options->server)
= {
- msg(M_USAGE,=
- "--h= ttp-proxy not specified but other http proxy options present");=
+ msg(M_USAGE, "= ;--http-proxy not specified but other http proxy options present");
}

if (ce->http= _proxy_options && ce->socks_proxy_server)
{=
- msg(M_USAGE,<= /span>
- "--ht= tp-proxy can not be used together with --socks-proxy");
+ msg(M_USAGE, "--http-= proxy can not be used together with --socks-proxy");

= }

if (ce->socks_proxy_server = && ce->proto =3D=3D PROTO_TCP_SERVER)
@@ -2518,7= +2503,8 @@
{
const char use_= err[] =3D "--%s cannot be used with --mode server.";

-#define USAGE_VA= LID_SERVER_PROTOS "--mode server currently only supports " \
+#define USAGE_VALID_SERV= ER_PROTOS \
- &quo= t;(--proto values of tcp-server, tcp4-server, or tcp6-server)");
+ = "(--proto values of tcp-server, tcp4-server, or tcp6-server)");
}
#endif
= if (!options->tls_server)
@@ -2555,8 +2541,7 @@ /* <connection> blocks force to have a remote embedd= ed, so we check
* for the --remote and bail out i= f it is present
*/
- if (options->connection_list->len >= 1
- || optio= ns->connection_list->array[0]->remote)
+ if (options->connection_list->len= > 1 || options->connection_list->array[0]->remote)
<= span> {

msg(M_USAGE, "<connect= ion> cannot be used with --mode server");
= }
@@ -2564,9 +2549,8 @@
MUST_BE_UN= DEF(shaper, "shaper");
if (options->i= pchange)
{
- msg(M_USAGE,
- "--ipchange cannot be used with --mod= e server (use "
- = "--client-connect instead)");
+ msg(M_USAGE, "--ipchang= e cannot be used with --mode server (use "
+ "--client-connect= instead)");
}
if (!= (proto_is_dgram(ce->proto) || ce->proto =3D=3D PROTO_TCP_SERVER))
{
@@ -2574,20 +2558,23 @@
<= span> }

if (!proto_is_udp(ce->proto) &a= mp;& (options->cf_max || options->cf_per))
= {
- msg(M= _USAGE, "--connect-freq only works with --mode server --proto udp. Tr= y --max-clients instead.");
+ msg(M_USAGE,
+ "--connect-freq only works with --mo= de server --proto udp. Try --max-clients instead.");
= }
- if = (!(dev =3D=3D DEV_TYPE_TAP || (dev =3D=3D DEV_TYPE_TUN && options-&= gt;topology =3D=3D TOP_SUBNET)) && options->ifconfig_pool_netmas= k)
+ if (!(dev= =3D=3D DEV_TYPE_TAP || (dev =3D=3D DEV_TYPE_TUN && options->top= ology =3D=3D TOP_SUBNET))
+ && options->ifconfig_pool_netmask)
<= span> {

- = msg(M_USAGE, "The third parameter to --ifconfig-pool (netmask) i= s only valid in --dev tap mode");
+ msg(M_USAGE,
+ "The third parameter to --ifco= nfig-pool (netmask) is only valid in --dev tap mode");
}

if (options->routes && (opt= ions->routes->flags & RG_ENABLE))
{
- msg(M_USAGE, &= quot;--redirect-gateway cannot be used with --mode server (however --push \= "redirect-gateway\" is fine)");
+ msg(M_USAGE,
+ "--redirect-gateway = cannot be used with --mode server (however --push \"redirect-gateway\&= quot; is fine)");
}
= MUST_BE_UNDEF(route_delay_defined, "route-delay");
MUST_BE_UNDEF(up_delay, "up-delay");

- if (!options->ifconfig_pool_= defined
- &a= mp;& !options->ifconfig_ipv6_pool_defined
+ if (!options->ifconfig_pool_defined= && !options->ifconfig_ipv6_pool_defined
= && options->ifconfig_pool_persist_filename)
{

msg(M_USAGE,
@@ -= 2600,7 +2587,8 @@
MUST_BE_UNDEF(allow_recursive_ro= uting, "allow-recursive-routing");
if (o= ptions->auth_user_pass_file)
{
- msg(M_USAGE, "--auth-= user-pass cannot be used with --mode server (it should be used on the clien= t side only)");
= + msg(M_USAGE,
+ "--auth-user-pass cannot be used with --mode ser= ver (it should be used on the client side only)");
= }
if (options->ccd_exclusive && != options->client_config_dir)
{
@= @ -2609,24 +2597,24 @@
if (options->auth_token_= generate && !options->renegotiate_seconds)
= {
msg(M_USAGE, "--auth-gen-token need= s a non-infinite "
- "--renegotiate_seconds setting");
+ "--= renegotiate_seconds setting");

}
if (options->auth_token_generate && options->aut= h_token_renewal

&& options->auth_to= ken_renewal < 2 * options->handshake_window)
= {
- msg(M_U= SAGE, "--auth-gen-token renewal time needs to be at least "
+ msg(M_USAGE,<= /span>
+ &quo= t;--auth-gen-token renewal time needs to be at least "
" two times --hand-window (%d).",

options->handshake_window);

-
}
- if (!options->auth_user_pass_= verify_script
- = && !PLUGIN_OPTION_LIST(options)
+ if (!options->auth_user_pass_verify_scri= pt && !PLUGIN_OPTION_LIST(options)
&am= p;& !MAN_CLIENT_AUTH_ENABLED(options))
{
- const char *use= _err =3D "--%s must be used with --management-client-auth, an --auth-u= ser-pass-verify script, or plugin";
+ const char *use_err =3D
+ "--%s must be use= d with --management-client-auth, an --auth-user-pass-verify script, or plug= in";

MUST_BE_FALSE(opti= ons->ssl_flags
- = & (SSLF_CLIENT_CERT_NOT_REQUIRED|SSLF_CLIENT_CERT= _OPTIONAL),
+ = & (SSLF_CLIENT_CERT_NOT_REQUIRED | SSLF_CLIENT_CE= RT_OPTIONAL),
"verify-clien= t-cert none|optional");
MUST_BE_FALSE(opt= ions->ssl_flags & SSLF_USERNAME_AS_COMMON_NAME,
= "username-as-common-name");
@@ -2668,7 +2656,7 @@

MUST_BE_UNDEF(cf_max, &quo= t;connect-freq");
MUST_BE_UNDEF(cf_per, "= ;connect-freq");
MUST_BE_FALSE(options->ss= l_flags
- = & (SSLF_CLIENT_CERT_NOT_REQUIRED|SSLF_CLIENT_CERT_OPTIONAL),
+ = & (SSLF_CLIENT_CERT_NOT_REQUIRED | SSLF_CLIENT_CERT_OPTIONAL),
"verify-client-cert");<= br> MUST_BE_FALSE(options->ssl_flags & SSLF_USERNAME_A= S_COMMON_NAME, "username-as-common-name");
= MUST_BE_FALSE(options->ssl_flags & SSLF_AUTH_USER_PASS_OPTIONAL, = "auth-user-pass-optional");
@@ -2676,15 +2664,16 = @@
if (options->server_flags & SF_TCP_NODEL= AY_HELPER)
{
msg(M_WA= RN, "WARNING: setting tcp-nodelay on the client side will not "
- "a= ffect the server. To have TCP_NODELAY in both direction use "- "tcp-node= lay in the server configuration instead.");
+ "affect the serve= r. To have TCP_NODELAY in both direction use "
+ "tcp-nodelay= in the server configuration instead.");
}
MUST_BE_UNDEF(auth_user_pass_verify_script, "au= th-user-pass-verify");
MUST_BE_UNDEF(auth_tok= en_generate, "auth-gen-token");
#if PORT_SHARE
if (options->port_share_host || options->port= _share_port)
{
- msg(M_USAGE, "--port-share requires TCP = server mode (--mode server --proto tcp-server)");
+ msg(M_USAGE,
+ "--port-share = requires TCP server mode (--mode server --proto tcp-server)");
<= br> }
#endif
MUST_B= E_UNDEF(stale_routes_check_interval, "stale-routes-check");
@@ -2697,8 +2686,7 @@
/*
= * SSL/TLS mode sanity checks.
*/
- if (options->tls_server + optio= ns->tls_client
- = + (options->shared_secret_file !=3D NULL) > 1)
+ if (options->tls_server + optio= ns->tls_client + (options->shared_secret_file !=3D NULL) > 1)
{
msg(M_USAGE, "specify only= one of --tls-server, --tls-client, or --secret");
= }
@@ -2712,29 +2700,26 @@
}

msg(msglevel, "DEPRECATION: No = tls-client or tls-server option in "
- "configuration detected. OpenVPN 2.8 w= ill remove the "
-= "functionality to run a VPN without TLS. "
= - "See the exampl= es section in the manual page for "
- "examples of a similar quick setup with= peer-fingerprint. "
- "OpenVPN 2.7 allows using this configuration when usin= g "
- &= quot;--allow-deprecated-insecure-static-crypto but you should move "
- "to a = proper configuration using TLS as soon as possible."
- );
+ "configuration de= tected. OpenVPN 2.8 will remove the "
+ "functionality to run a V= PN without TLS. "
+ = "examples of a similar quick setup with peer-fingerprint.= "
+ = "OpenVPN 2.7 allows using this configuration when using &quo= t;
+ = "--allow-deprecated-insecure-static-crypto but you should move &q= uot;
+ = "to a proper configuration using TLS as soon as possible."= );
}

- if (options->ssl_flags & (SSLF_CLIENT_CERT= _NOT_REQUIRED|SSLF_CLIENT_CERT_OPTIONAL))
+ if (options->ssl_flags & (SSLF_CLIENT_CERT= _NOT_REQUIRED | SSLF_CLIENT_CERT_OPTIONAL))
{ msg(M_WARN, "WARNING: POTENTIALLY DANGEROUS OPTION &q= uot;
- "= ;--verify-client-cert none|optional "
- "may accept clients which do not pres= ent a certificate");
+ "--verify-client-cert none|optional "
+ &= quot;may accept clients which do not present a certificate"); }

const int tls_version= _max =3D
- (opti= ons->ssl_flags >> SSLF_TLS_VERSION_MAX_SHIFT)
- & SSLF_TLS_VERSION_MAX_MASK;
+ (options->= ssl_flags >> SSLF_TLS_VERSION_MAX_SHIFT) & SSLF_TLS_VERSION_MAX_M= ASK;
const int tls_version_min =3D
- (options->ssl_flags >> S= SLF_TLS_VERSION_MIN_SHIFT)
- & SSLF_TLS_VERSION_MIN_MASK;
+ (options->ssl_flags >> SSLF_TLS_= VERSION_MIN_SHIFT) & SSLF_TLS_VERSION_MIN_MASK;

if (tls_version_max > 0 && tls_version_max < = tls_version_min)
{
@@ -2751,20 +2736,2= 4 @@
}
else if (!options-= >pkcs11_providers[0] && options->pkcs11_id_management)=
{
- = msg(M_WARN, "Option pkcs11-id-management is ignored as no p= kcs11-providers are specified");
+ msg(M_WARN,
+ "Option pkcs11-id-management is = ignored as no pkcs11-providers are specified");
= }

if (options->pkcs11_prov= iders[0])
{
if (optio= ns->pkcs11_id_management && options->pkcs11_id !=3D NULL)
{
- msg(M_USAGE, "Parameter --pkcs11-id cannot be us= ed when --pkcs11-id-management is also specified.");
+ msg(M_USAGE,+ "Pa= rameter --pkcs11-id cannot be used when --pkcs11-id-management is also spec= ified.");
}
= if (!options->pkcs11_id_management && options->pkcs11_id =3D= =3D NULL)
{
- msg(M_USAGE, "Parameter --pkcs11-id= or --pkcs11-id-management should be specified.");
+ msg(M_USAGE,
= + "Para= meter --pkcs11-id or --pkcs11-id-management should be specified.");
}
- const char use_err[] =3D "Parameter --%s cannot be = used when --pkcs11-provider is also specified.";
+ const char use_err[] =3D
+ "Pa= rameter --%s cannot be used when --pkcs11-provider is also specified."= ;
MUST_BE_UNDEF(cert_file, "cert");<= /span>
MUST_BE_UNDEF(priv_key_file, "key");=
MUST_BE_UNDEF(pkcs12_file, "pkcs12"= );
@@ -2777,9 +2766,10 @@
else
#endif /* ifdef ENABLE_PKCS11 */
#ifdef ENAB= LE_CRYPTOAPI
- i= f (options->cryptoapi_cert)
+ if (options->cryptoapi_cert)
= {
- con= st char use_err[] =3D "Parameter --%s cannot be used when --cryptoapic= ert is also specified.";
+ const char use_err[] =3D
+ "Parameter --%s cannot be u= sed when --cryptoapicert is also specified.";
= MUST_BE_UNDEF(cert_file, "cert");
= MUST_BE_UNDEF(priv_key_file, "key");
= MUST_BE_UNDEF(pkcs12_file, "pkcs12");
@@ -278= 8,7 +2778,7 @@
}
else
#endif
- = if (options->pkcs12_file)
+ if (options->pkcs12_file)
= {
#ifdef ENABLE_CRYPTO_MBEDTLS
= msg(M_USAGE, "Parameter --pkcs12 cannot be used with the mbed= TLS version of OpenVPN.");
@@ -2799,7 +2789,7 @@
MUST_BE_UNDEF(priv_key_file, "key");
MUST_BE_FALSE(options->management_flags & = MF_EXTERNAL_KEY, "management-external-key");
= MUST_BE_FALSE(options->management_flags & MF_EXTERNAL_CERT,= "management-external-cert");
-#endif /* ifdef ENABLE_CRYPTO_MBEDTLS */
+#endif /* ifdef ENABLE_CRYPTO_= MBEDTLS */
}
else /* cert= /key from none of pkcs11, pkcs12, cryptoapi */
{
@@ -2815,24 +2805,25 @@
}
else if (!(options->management_flags &am= p; MF_EXTERNAL_KEY))
{
- msg(M_USAGE, "--= management-external-cert must be used with --management-external-key")= ;
+ = msg(M_USAGE,
+ = "--management-external-cert must be used with --man= agement-external-key");
}
<= span> }

if (pull)
= {
-=
const int sum =3D
= ((options->cert_file !=3D NULL) || (options->management_flags = & MF_EXTERNAL_CERT))
+ + ((options->priv_key_fil= e !=3D NULL)
+ = || (options->management_flags & MF_EXTERNAL_KEY));

if (sum =3D=3D 0)<= br> {
if (!optio= ns->auth_user_pass_file)
{ msg(M_USAGE, "No client-side authenti= cation method is "
- "specified. You must use either "<= /span>
- = "--cert/--key, --pkcs12, or "
- "--auth-user-pass&= quot;);
+ = "specified. You must use either "
+ = "--cert/--key, --pkcs12, or "
+ &quo= t;--auth-user-pass");
} }
else if (sum != =3D 2)
@@ -2844,11 +2835,13 @@
= {
if (!(options->management_flags &= ; MF_EXTERNAL_CERT))
{
- notnull(options->c= ert_file, "certificate file (--cert) or PKCS#12 file (--pkcs12)")= ;
+ = notnull(options->cert_file,
+ "certificate file (--cert) or= PKCS#12 file (--pkcs12)");
}<= br> if (!(options->management_flags & MF_EXTER= NAL_KEY))
{
- notnull(options->priv_key_fil= e, "private key file (--key) or PKCS#12 file (--pkcs12)");=
+ notnul= l(options->priv_key_file,
+ "private key file (--key) or PKCS= #12 file (--pkcs12)");
}
}

}
@@ -2859,7 +2= 852,8 @@
if (options->tls_client && ce-= >tls_crypt_v2_file
&& (ce->tls_a= uth_file || ce->tls_crypt_file))
{
- msg(M_USAGE, "--t= ls-crypt-v2, --tls-auth and --tls-crypt are mutually exclusive in client mo= de");

+ = msg(M_USAGE,
+ = "--tls-crypt-v2, --tls-auth and --tls-crypt are mutually e= xclusive in client mode");
}
= }
else
@@ -2988,12 +2982,12 @@
if (ce->af =3D=3D AF_INET6)
= {
msg(M_INFO, "WARNING: '--proto = udp6' is not compatible with "
- "'--socks-proxy' today. For= cing IPv4 mode." );
+ "'--socks-proxy' today. Forcing = IPv4 mode.");
}
else=
{
msg(M_INFO, "= NOTICE: dual-stack mode for '--proto udp' does not "- "work corr= ectly with '--socks-proxy' today. Forcing IPv4." );+ "= ;work correctly with '--socks-proxy' today. Forcing IPv4.");<= /span>
}
ce->af =3D AF_INET;<= /span>
}
@@ -3027,7 +3021,7 @@
}

else
#endif- if (ce->tun_mtu_def= ined)
+ if= (ce->tun_mtu_defined)
{
= if (o->ce.tun_mtu =3D=3D TUN_MTU_DEFAULT)
= {
@@ -3070,12 +3064,9 @@
/* Pre-= cache tls-auth/crypt(-v2) key file if
* keys were not= already embedded in the config file.
*/
- connection_entry_preload_key(&= amp;ce->tls_auth_file,

- &ce->tls_auth_file_inline, &= ;o->gc);
- connec= tion_entry_preload_key(&ce->tls_crypt_file,
- &ce->t= ls_crypt_file_inline, &o->gc);
- connection_entry_preload_key(&ce->tls_crypt_v2_f= ile,
- = &ce->tls_crypt_v2_file_inline, &o->gc);
+ connection_entry_prel= oad_key(&ce->tls_auth_file, &ce->tls_auth_file_inline, &o= ->gc);
+ connec= tion_entry_preload_key(&ce->tls_crypt_file, &ce->tls_crypt_fi= le_inline, &o->gc);
+ connection_entry_preload_key(&ce->tls_crypt_v2_file, &= ;ce->tls_crypt_v2_file_inline, &o->gc);
<= br>
if (!proto_is_udp(ce->proto) && = ce->explicit_exit_notification)
@@ -3106,10 +3097,8 @@
static void
remap_redirect_gateway_flags(s= truct options *opt)
{
- if (opt->routes
- && opt->route_method =3D=3D ROUTE_METH= OD_SERVICE
- &am= p;& opt->routes->flags & RG_REROUTE_GW
- && !(opt->routes->fla= gs & RG_DEF1))
+ = if (opt->routes && opt->route_method =3D=3D ROUTE_METHOD_S= ERVICE
+ &= & opt->routes->flags & RG_REROUTE_GW && !(opt->rou= tes->flags & RG_DEF1))
{
= msg(M_INFO, "Flag 'def1' added to --redirect-gateway (iserv= ice is in use)");
opt->routes->flags |= =3D RG_DEF1;
@@ -3288,8 +3277,7 @@
/* = If p11-kit is present on the system then load its p11-kit-proxy.so * by default if the user asks for PKCS#11 without otherwise s= pecifying
* the module to use. */
- if (!options->pkcs11_providers[0]<= /span>
- && (op= tions->pkcs11_id || options->pkcs11_id_management))
+ if (!options->pkcs11_providers= [0] && (options->pkcs11_id || options->pkcs11_id_management))=
{
options->pkcs11_provide= rs[0] =3D DEFAULT_PKCS11_MODULE;
}
@@ = -3317,8 +3305,8 @@
if (dco_enabled(o) && o->= ;enable_c2c)
{
msg(M_WARN, &q= uot;Note: --client-to-client has no effect when using data "- "channel offlo= ad: packets are always sent to the VPN "
- "interface and then routed based o= n the system routing table");
+ "channel offload: packets are alway= s sent to the VPN "
+ "interface and then routed based on the syste= m routing table");
}
}
@@ -3348,17 +3336,19 @@
= * parts of OpenVPN assert that the ciphername is set */
= o->ciphername =3D "BF-CBC";

= - msg(M_INFO, "Note: = --cipher is not set. OpenVPN versions before 2.5 "
+ msg(M_INFO,
+ "Note: --cipher is not= set. OpenVPN versions before 2.5 "
"= ;defaulted to BF-CBC as fallback when cipher negotiation "
<= span> "failed in this case. If you need this fallback plea= se add "

"'--data-ciphers-fallba= ck BF-CBC' to your configuration "
&q= uot;and/or add BF-CBC to --data-ciphers. E.g. "
- "--data-ciphers %s:BF-CBC&= quot;, o->ncp_ciphers_conf);
+ "--data-ciphers %s:BF-CBC",
+ o->ncp_ciphers_con= f);

}
- else if (!o->enable_ncp_fallback
- && !tls_item_in_cipher_list(o-&= gt;ciphername, o->ncp_ciphers))
+ else if (!o->enable_ncp_fallback && !tls_item= _in_cipher_list(o->ciphername, o->ncp_ciphers))
= {
- msg(M_WARN, = "DEPRECATED OPTION: --cipher set to '%s' but missing in "=
+ msg(M_WARN,=
+ "D= EPRECATED OPTION: --cipher set to '%s' but missing in "=
"--data-ciphers (%s). OpenVPN ignores --cipher = for cipher "
"negotiations. ",<= /span>
o->ciphername, o->ncp_ciphers_conf);
@@ -3394,12 +3384,10 @@
options_set_backwards= _compatible_options(struct options *o)
{
= /* TLS min version is not set */
- int tls_ver_min =3D (o->ssl_flags >> SSLF_TLS_V= ERSION_MIN_SHIFT)
- = & SSLF_TLS_VERSION_MIN_MASK;
+ int tls_ver_min =3D (o->ssl_flags >= ;> SSLF_TLS_VERSION_MIN_SHIFT) & SSLF_TLS_VERSION_MIN_MASK; if (tls_ver_min =3D=3D 0)
{
- int tls_ver_max =3D (o->= ssl_flags >> SSLF_TLS_VERSION_MAX_SHIFT)

- & SSLF_TLS_VERSION_M= AX_MASK;
+ int= tls_ver_max =3D (o->ssl_flags >> SSLF_TLS_VERSION_MAX_SHIFT) &= ; SSLF_TLS_VERSION_MAX_MASK;
if (need_compatibilit= y_before(o, 20307))
{
= /* 2.3.6 and earlier have TLS 1.0 only, set minimum to TLS 1.0 */@@ -3455,7 +3443,7 @@
o->comp.flags= =3D COMP_F_ALLOW_STUB_ONLY | COMP_F_ADVERTISE_STUBS_ONLY;
= }
}
-#else /* ifdef USE_COMP */
+#else /* ifdef USE_COMP */
o->c= omp.flags =3D COMP_F_ALLOW_NOCOMP_ONLY;
#endif
<= span> }

@@ -3466,17 +3454,16 @@
if (!c= heck_tls_prf_working())
{
msg= (D_TLS_ERRORS, "Warning: TLS 1.0 PRF with MD5+SHA1 PRF is not "
- "suppo= rted by the TLS library. Your system does not support this "- "calculation a= nymore or your security policy (e.g. FIPS 140-2) "
- "forbids it. Connections= will only work with peers running "
- "OpenVPN 2.6.0 or higher)");
+ = "supported by the TLS library. Your system does not support this &qu= ot;
+ = "calculation anymore or your security policy (e.g. FIPS 140-= 2) "
+ = "forbids it. Connections will only work with peers run= ning "
+ = "OpenVPN 2.6.0 or higher)");
= if (o->mode =3D=3D MODE_SERVER)
{=
msg(M_WARN, "Automatically enabling option &quo= t;
- &qu= ot;--force-tls-key-material-export");
+ "--force-tls-key-materi= al-export");
o->force_key_material_exp= ort =3D true;
}
-
}
}

@@ -3521,9 +3508,9 @@
#if defined(_WI= N32)
if (tt->ip_win32_type !=3D IPW32_SET_DHCP_MASQ= && tt->ip_win32_type !=3D IPW32_SET_ADAPTIVE)
= {
- return; = /* Not in DHCP mode */
+ return; /* Not in DHCP mode */
}=
-#endif /* if defined(_WIN32)= */
+#endif = /* if defined(_WIN32) */

/* Copy --d= ns options to tuntap_options */

@@ -3559,= 8 +3546,7 @@
}
}
if ((s->transport && s->transport !=3D D= NS_TRANSPORT_PLAIN)
- = || (s->dnssec && s->dnssec !=3D DNS_SECURITY_NO)
- || non_stand= ard_server_port)
+ = || (s->dnssec && s->dnssec !=3D DNS_SECURITY_NO) || = non_standard_server_port)
{
= /* Skip servers requiring unsupported config to be set */
= s =3D s->next;
@@ -3593,7 +3579,7 @@<= /span>
}
}

-#else /* if defined(_WIN32) || define= d(TARGET_ANDROID) */

= +#else /* if defined(_WIN32) || defined(TARGET_ANDROID) */

/**
* @brief Postprocess DNS related = settings
@@ -3715,8 +3701,7 @@
= }
}
if ((s-&= gt;transport && s->transport !=3D DNS_TRANSPORT_PLAIN)- || (s->dnsse= c && s->dnssec !=3D DNS_SECURITY_NO)
- || non_standard_server_port)
+ || (s-&g= t;dnssec && s->dnssec !=3D DNS_SECURITY_NO) || non_standard_serv= er_port)
{
/*= Skip servers requiring unsupported config to be set */
= s =3D s->next;
@@ -3852,7 +3837,7 @@
{
/* DH file is only meaningful in= a tls-server context. */
msg(M_WARN, "WARNIN= G: Ignoring option 'dh' in tls-client mode, please only "
- "include = this in your server configuration");
+ "include this in your server= configuration");
o->dh_file =3D NULL;
}
#if ENABLE_MANAGEMENT
= @@ -3861,25 +3846,23 @@
options_postprocess_http_p= roxy_override(o);
}
#endif
= - if (!o->ca_file &&= ; !o->ca_path && o->verify_hash
- && o->verify_hash_depth =3D=3D 0= )
+ if (!o->ca_= file && !o->ca_path && o->verify_hash && o-&g= t;verify_hash_depth =3D=3D 0)
{
= msg(M_INFO, "Using certificate fingerprint to verify peer (no CA &q= uot;
- "= ;option set). ");
- "incompatible with each other= .");
+ = "incompatible with each other.");
= }

if (dco_enabled(o))
{

/* check if any option should force disa= bling DCO */
- o= ->disable_dco =3D !dco_check_option(D_DCO, o)
- || !dco_check_startup_o= ption(D_DCO, o);
+ = o->disable_dco =3D !dco_check_option(D_DCO, o) || !dco_check_startu= p_option(D_DCO, o);
}
#ifdef USE_COMP=
if (dco_enabled(o))
@@ -3897,7 +3880,= 8 @@
{
if (o->windows_driv= er =3D=3D DRIVER_DCO)
{
- msg(M_WARN, "Option --windows-d= river ovpn-dco is ignored because Data Channel Offload is disabled");<= /span>
+ msg(M_WA= RN,
+ = "Option --windows-driver ovpn-dco is ignored because Data Channel Offl= oad is disabled");
o->windows_driver = =3D WINDOWS_DRIVER_TAP_WINDOWS6;
}
else if (o->windows_driver =3D=3D WINDOWS_DRIVER_UNSPECIFIED)<= /span>
@@ -3909,7 +3893,7 @@
if (dco_enabled(= o) && o->dev_node)
{
= msg(M_WARN, "Note: ignoring --dev-node as it has no effect when usi= ng "
- = "data channel offload");
+ "data channel offload");

o->dev_node =3D NULL;
}<= br> #endif /* _WIN32 */
@@ -3947,14 +3931,14 @@
* Check file/directory sanity
*
<= span> */

-#ifndef ENAB= LE_SMALL /* Expect people using the stripped down version to know what the= y do */
+#ifndef ENAB= LE_SMALL /* Expect people using the stripped down version to know what they= do */

-#define = CHKACC_DIRPATH (1<<1) /**< Check for directory presence where a= file should reside */
= -#define CHKACC_FILEXSTWR (1<<2) /**< If file exists, is it writa= ble? */
-#define CHKACC= _ACPTSTDIN (1<<3) /**< If filename is stdin, it's allowed and= "exists" */
= -#define CHKACC_PRIVATE (1<<4) /**< Warn if this (private) file= is group/others accessible */
-#define CHKACC_ACCEPT_URI (1<<5) /**< Do not check URIs, = unless they start with file: */
+#define CHKACC_FILE (1 << 0) /**< Check for a fi= le/directory presence */
+#define CHKACC_DIRPATH (1 << 1) /**< Check for directory p= resence where a file should reside */
+#define CHKACC_FILEXSTWR (1 << 2) /**< If file = exists, is it writable? */
+#define CHKACC_ACPTSTDIN (1 << 3) /**< If filename is stdi= n, it's allowed and "exists" */
+#define CHKACC_PRIVATE (1 << 4) /**< = Warn if this (private) file is group/others accessible */
+#define CHKACC_ACCEPT_URI (1 <<= 5) /**< Do not check URIs, unless they start with file: */

static bool
check_file_access(const= int type, const char *file, const int mode, const char *opt)
@@ -3970,7 +3954,7 @@

/* If stdin is allowed and th= e file name is 'stdin', then do no
* further = checks as stdin is always available
*/
- if ( (type & CHKACC_ACPTSTDI= N) && streq(file, "stdin") )

+ if ((type & CHKACC_ACPTSTDIN) &&= streq(file, "stdin"))
{
= return false;
}
@@ -3993,10 +397= 7,11 @@
/* Is the directory path leading to the given = file accessible? */
if (type & CHKACC_DIRPATH)
{
- = char *fullpath =3D string_alloc(file, NULL); /* POSIX dirname() imple= mentation may modify its arguments */
+ char *fullpath =3D
+ string_alloc(file, NULL); /* POSIX dir= name() implementation may modify its arguments */
= char *dirpath =3D dirname(fullpath);

- if (platform_access(dirpath, mode|= X_OK) !=3D 0)
+ = if (platform_access(dirpath, mode | X_OK) !=3D 0)
= {
errcode =3D errno;
= }
@@ -4004,13 +3989,13 @@
}
/* Is the file itself accessible? */<= br>- if (!errcode && (= type & CHKACC_FILE) && (platform_access(file, mode) !=3D 0) )
+ if (!errcode &= ;& (type & CHKACC_FILE) && (platform_access(file, mode) != =3D 0))
{
errcode =3D errno;<= /span>
}

/* If the fil= e exists and is accessible, is it writable? */
- if (!errcode && (type & CHKACC_FIL= EXSTWR) && (platform_access(file, F_OK) =3D=3D 0) )
+ if (!errcode && (type &= amp; CHKACC_FILEXSTWR) && (platform_access(file, F_OK) =3D=3D 0))
{
if (platform_access(file, W_= OK) !=3D 0)
{
@@ -4029,7 +4014,7 @= @
#ifndef _WIN32
else
<= span> {

- = if (st.st_mode & (S_IRWXG|S_IRWXO))
+ if (st.st_mode & (S_IRWXG | S_IRW= XO))
{
msg(M_= WARN, "WARNING: file '%s' is group or others accessible",= file);
}
@@ -4052,7 +4037,8 @= @
* otherwise it will look for the file inside the given = chroot directory instead.
*/
static bool=
-check_file_access_chr= oot(const char *chroot, const int type, const char *file, const int mode, c= onst char *opt)
+chec= k_file_access_chroot(const char *chroot, const int type, const char *file, = const int mode,
+ = const char *opt)
{
= bool ret =3D false;

@@ -4085,9 +4071,8= @@
* the file is inline (and therefore there is no acces= s to check)
*/
static bool
-check_file_access_chroot_inline(boo= l is_inline, const char *chroot,

- const int type, const char *file= ,
- = const int mode, const char *opt)
+check_file_access_chroot_inline(bool is_inline, co= nst char *chroot, const int type,
+ const char *file, const int m= ode, const char *opt)
{
if (is_inline= )
{
@@ -4102,8 +4087,8 @@
* is inline (and therefore there is no access to check)

*/

static bool
-check_file_access_inline(bool is_inline, const int type, con= st char *file,
- = const int mode, const char *opt)
+check_file_access_inline(bool is_inline, con= st int type, const char *file, const int mode,
+ const char *opt)=
{
if (is_inline)
{
@@ -4156,8 +4141,7 @@
}
= else
{
- msg(M_NOPREFIX|M_OPTERR, "%s fails with '%s'= : No path to executable.",
- opt, command);
+ msg(M_NOPREFIX | M_OPTERR, "%s fails with = 9;%s': No path to executable.", opt, command);
= return_code =3D true;
}
=
@@ -4176,55 +4160,51 @@
bool errs =3D false;=

/* ** SSL/TLS/crypto related files = ** */
- errs |=3D ch= eck_file_access_inline(options->dh_file_inline, CHKACC_FILE,
<= span style=3D"color: hsl(0, 100%, 40%);">- = options->dh_file, R_OK, "--dh");

+ errs |=3D check_file_access_inline(option= s->dh_file_inline, CHKACC_FILE, options->dh_file, R_OK,
+ = "--dh");


if (!options-= >verify_hash_no_ca)
{
- errs |=3D check_file_access_inline(options-= >ca_file_inline, CHKACC_FILE,
- options->ca_file, R_= OK, "--ca");
+ R_OK, "--ca"= ;);
}

- errs |=3D check_file_access_chroot(options->c= hroot_dir, CHKACC_FILE,
- options->ca_path, R_OK, "--c= apath");
+ er= rs |=3D check_file_access_chroot(options->chroot_dir, CHKACC_FILE, optio= ns->ca_path, R_OK,
+ "--capath");

- errs |=3D che= ck_file_access_inline(options->cert_file_inline, CHKACC_FILE|CHKACC_ACCE= PT_URI,
+ errs |= =3D check_file_access_inline(options->cert_file_inline, CHKACC_FILE | CH= KACC_ACCEPT_URI,
opti= ons->cert_file, R_OK, "--cert");

<= span> errs |=3D check_file_access_inline(options->extra_certs_file, = CHKACC_FILE,

- = options->extra_certs_file, R_OK,
<= span style=3D"color: hsl(0, 100%, 40%);">- = "--extra-certs");

+ options->extra_certs_fi= le, R_OK, "--extra-certs");

= if (!(options->management_flags & MF_EXTERNAL_KEY))
{

errs |=3D check_file_access_inline(option= s->priv_key_file_inline,
- CHKACC_FILE|CHKACC_PRIVATE|C= HKACC_ACCEPT_URI,
+ = CHKACC_FILE | CHKACC_PRIVATE | CHKAC= C_ACCEPT_URI,
opt= ions->priv_key_file, R_OK, "--key");
}

- er= rs |=3D check_file_access_inline(options->pkcs12_file_inline,
= - = CHKACC_FILE|CHKACC_PRIVATE,
+ errs |=3D check_file_access_inline(options->pkcs12_file= _inline, CHKACC_FILE | CHKACC_PRIVATE,
= options->pkcs12_file, R_OK, "--pkcs12");

if (options->ssl_flags & SSLF_CR= L_VERIFY_DIR)
{
- errs |=3D check_file_access_chroot(options->chroo= t_dir, CHKACC_FILE,
- = options->crl_file, R_OK|X_OK,
- = "--crl-verify directory");
+ errs |=3D check_file_access_chroo= t(options->chroot_dir, CHKACC_FILE, options->crl_file,
+ = R_OK | X_OK, "--crl-verify directory");

= }
else
{
- errs |=3D check_file_access_chroot_= inline(options->crl_file_inline,
- options->c= hroot_dir,
- = CHKACC_FILE, options->crl_file,
- = R_OK, "--crl-verify");
+ errs |=3D
+ check_file_access_chroot_inli= ne(options->crl_file_inline, options->chroot_dir,
+ = CHKACC_FILE, options->crl_file, R_OK, "--crl-verify");
}

if (options->= ;tls_export_peer_cert_dir)
{
- errs |=3D check_file_access_chroot(opti= ons->chroot_dir, CHKACC_FILE,
- options->tls_export_= peer_cert_dir,
- = W_OK, "--tls-export-cert");
+ errs |=3D
+ check_file_ac= cess_chroot(options->chroot_dir, CHKACC_FILE,
+ options-&= gt;tls_export_peer_cert_dir, W_OK, "--tls-export-cert"); }

ASSERT(options->co= nnection_list);
@@ -4232,55 +4212,46 @@
= {
struct connection_entry *ce =3D options->co= nnection_list->array[i];

- errs |=3D check_file_access_inline(ce->t= ls_auth_file_inline,
- = CHKACC_FILE|CHKACC_PRIVATE,<= br>- = ce->tls_auth_file, R_OK,
- "--tls-auth= ");
- errs = |=3D check_file_access_inline(ce->tls_crypt_file_inline,
- = CHKACC_FILE|CHKACC_PRIVATE,

- ce->tls_crypt_file, R= _OK,
- = "--tls-crypt");
- errs |=3D check_file_access_inline(ce-&= gt;tls_crypt_v2_file_inline,
- CHKACC_FILE|CHKACC_PRIVATE,=
- = ce->tls_crypt_v2_file, R_OK,
- &q= uot;--tls-crypt-v2");
+ errs |=3D check_file_access_inline(ce->tls_auth_file_inli= ne, CHKACC_FILE | CHKACC_PRIVATE,
+ ce->tls_auth_file= , R_OK, "--tls-auth");
+ errs |=3D check_file_access_inline(ce->tls_crypt_fi= le_inline, CHKACC_FILE | CHKACC_PRIVATE,
+ ce->tls_cr= ypt_file, R_OK, "--tls-crypt");
+ errs |=3D check_file_access_inline(ce->tls= _crypt_v2_file_inline, CHKACC_FILE | CHKACC_PRIVATE,
+ = ce->tls_crypt_v2_file, R_OK, "--tls-crypt-v2");
}


- errs |=3D check_file_access_inline(options->shared_secret_file_= inline,
- = CHKACC_FILE|CHKACC_PRIVATE,
- options-&= gt;shared_secret_file, R_OK,
- "--secret");+ errs |=3D
+ check_file_access_inline(o= ptions->shared_secret_file_inline, CHKACC_FILE | CHKACC_PRIVATE,
<= br>+ = options->shared_secret_file, R_OK, "--secret");
- errs |= =3D check_file_access(CHKACC_DIRPATH|CHKACC_FILEXSTWR,
- options->= packet_id_file, R_OK|W_OK, "--replay-persist");
+ errs |=3D check_file_access(CHKAC= C_DIRPATH | CHKACC_FILEXSTWR, options->packet_id_file,
+ R_OK | = W_OK, "--replay-persist");

= /* ** Password files ** */
- errs |=3D check_file_access(CHKACC_FILE|CHKACC_ACPTSTDIN|CHKACC_P= RIVATE,
+ errs |= =3D check_file_access(CHKACC_FILE | CHKACC_ACPTSTDIN | CHKACC_PRIVATE,
options->key_pass_file, R_OK,= "--askpass");
#ifdef ENABLE_MANAGEMENT- errs |=3D check_file_acces= s(CHKACC_FILE|CHKACC_ACPTSTDIN|CHKACC_PRIVATE,
- options->manageme= nt_user_pass, R_OK,
- = "--management user/password file");
+ errs |=3D<= br>+ check_file_access(C= HKACC_FILE | CHKACC_ACPTSTDIN | CHKACC_PRIVATE,
+ options->managemen= t_user_pass, R_OK, "--management user/password file");
= #endif /* ENABLE_MANAGEMENT */
errs |=3D check_= file_access_inline(options->auth_user_pass_file_inline,
- C= HKACC_FILE|CHKACC_ACPTSTDIN|CHKACC_PRIVATE,
- options->auth= _user_pass_file, R_OK,
= - "--auth-user-pass");=
+ = CHKACC_FILE | CHKACC_ACPTSTDIN | CHKACC_PRIVATE,
+ = options->auth_user_pass_file, R_OK, "--auth-user-pass");
/* ** System related ** */
- errs |=3D check_file_access(CHKACC_FILE, options= ->chroot_dir,
- = R_OK|X_OK, "--chroot directory");=
- errs |=3D check_file_acc= ess(CHKACC_DIRPATH|CHKACC_FILEXSTWR, options->writepid,
- R_OK|W_O= K, "--writepid");
+ errs |=3D check_file_access(CHKACC_FILE, options->chroot_dir= , R_OK | X_OK, "--chroot directory");
+ errs |=3D check_file_access(CHKACC_DIRPATH = | CHKACC_FILEXSTWR, options->writepid, R_OK | W_OK,
+ "--wr= itepid");

/* ** Log related ** = */
- errs |=3D check= _file_access(CHKACC_DIRPATH|CHKACC_FILEXSTWR, options->status_file,
- = R_OK|W_OK, "--status");
+ errs |=3D check_file_access(CHKACC_DIRPATH | CHKACC_F= ILEXSTWR, options->status_file, R_OK | W_OK,
+ "--status&qu= ot;);

/* ** Config related ** */
errs |=3D check_file_access_chroot(options->chroot_dir= , CHKACC_FILE, options->client_config_dir,
- R_OK|X_OK, &qu= ot;--client-config-dir");
+ R_OK | X_OK, "--client= -config-dir");
errs |=3D check_file_access_chroot= (options->chroot_dir, CHKACC_FILE, options->tmp_dir,
- R= _OK|W_OK|X_OK, "Temporary directory (--tmp-dir)");
+ = R_OK | W_OK | X_OK, "Temporary directory (--tmp-dir)");
=

if (errs)
{@@ -4366,12 +4337,8 @@
* the other e= nd of the connection]
*/
char *-options_string(const struct op= tions *o,
- = const struct frame *frame,
- struct tuntap *tt,
- openvpn_net_ctx_t *ctx,
- bool remote,
= - struct gc_arena *= gc)
+options_string(c= onst struct options *o, const struct frame *frame, struct tuntap *tt,

+ openvpn_ne= t_ctx_t *ctx, bool remote, struct gc_arena *gc)
{ struct buffer out =3D alloc_buf(OPTION_LINE_SIZE);
<= span> bool tt_local =3D false;

@@ -4387,8 +4354,7 @@
* cipher (p2p) or have a fallback cipher configured for= older non
* ncp clients. But not sending it will mak= e even 2.4 complain
* about it being missing. So stil= l send it. */
- buf_= printf(&out, ",link-mtu %u",
- (unsigned int) calc_options_string_link= _mtu(o, frame));
+ = buf_printf(&out, ",link-mtu %u", (unsigned int)calc_options_= string_link_mtu(o, frame));

if (o-&g= t;ce.occ_mtu !=3D 0)
{
@@ -4399,7 +436= 5,7 @@
buf_printf(&out, ",tun-mtu %d"= ;, frame->tun_mtu);
}

<= span style=3D"color: hsl(0, 100%, 40%);">- buf_printf(&out, ",p= roto %s", proto_remote(o->ce.proto, remote));

+ buf_printf(&out, ",proto %s= ", proto_remote(o->ce.proto, remote));

= bool p2p_nopull =3D o->mode =3D=3D MODE_POINT_TO_POINT &&= amp; !PULL_DEFINED(o);
/* send tun_ipv6 only in peer2p= eer mode - in client/server mode, it
@@ -4416,20 +4382,9 @@=
*/
if (!tt)
= {
- tt =3D ini= t_tun(o->dev,
- = o->dev_type,
- o->topology,
- o->ifconfig_local,
- o-&g= t;ifconfig_remote_netmask,
- o->ifconfig_ipv6_local,
- o->ifconfig_ipv6_n= etbits,
- = o->ifconfig_ipv6_remote,
- NULL,
- NULL,
- false,
- NULL,
- ctx,
- NULL);
+ tt =3D init_tu= n(o->dev, o->dev_type, o->topology, o->ifconfig_local,+ o->= ifconfig_remote_netmask, o->ifconfig_ipv6_local, o->ifconfig_ipv6_net= bits,
+ = o->ifconfig_ipv6_remote, NULL, NULL, false, NULL, ctx, NULL);
if (tt)
{
= tt_local =3D true;
@@ -4453,7 +4408,8 @@=
#ifdef USE_COMP
if (o->comp.alg !=3D COM= P_ALG_UNDEF)
{
- buf_printf(&out, ",comp-lzo"); /* for c= ompatibility, this simply indicates that compression context is active, not= necessarily LZO per-se */
+ buf_printf(&out, ",comp-lzo"); /* for compatib= ility, this simply indicates that compression
+ context= is active, not necessarily LZO per-se */
}
= #endif

@@ -4485,10 +4441,7 @@
{
struct key_type kt;
<= span>

- ASSERT(= (o->shared_secret_file !=3D NULL)
- + (TLS_CLIENT =3D=3D true)
- + (TLS_SERVER =3D=3D true= )
- <= =3D 1);
+ ASSE= RT((o->shared_secret_file !=3D NULL) + (TLS_CLIENT =3D=3D true) + (TLS_S= ERVER =3D=3D true) <=3D 1);

/= * Skip resolving BF-CBC to allow SSL libraries without BF-CBC
* to work here in the default configuration */

@@ -4597,8 +4550,7 @@

}

static const char *

-= options_warning_extract_parm1(const char *option_string,
- struct gc_= arena *gc_ret)
+optio= ns_warning_extract_parm1(const char *option_string, struct gc_arena *gc_ret= )
{
struct gc_arena gc =3D gc_new();<= /span>
struct buffer b =3D string_alloc_buf(option_string, &a= mp;gc);
@@ -4612,24 +4564,16 @@
}
static void
-options_warning_safe_scan2(const int msglevel,
<= span style=3D"color: hsl(0, 100%, 40%);">- const = int delim,

- = const bool report_inconsistent,
- const char *p1,=
- c= onst struct buffer *b2_src,
- const char *b1_name,
+options_warning_safe_scan2(const int msgl= evel, const int delim, const bool report_inconsistent,
+ const char *p= 1, const struct buffer *b2_src, const char *b1_name,
= const char *b2_name)
{
/* We will stop sending 'key-method', 'keydir', = 9;proto' and 'tls-auth' in

* OCC in a fut= ure version (because it's not useful). To reduce questions
* when interoperating, we no longer printing a warning about it.<= /span>
*/
- || strprefix(p1, "keydir ")
- || strprefix(p1= , "proto ")
-= || streq(p1, "tls-auth")
- || strprefix(p1, "tun-ipv6")<= br>- || strprefix(p1, &quo= t;cipher "))
+ = if (strprefix(p1, "key-method ") || strprefix(p1, "keydir = ") || strprefix(p1, "proto ")
+ || streq(p1, "tls-auth") || strp= refix(p1, "tun-ipv6") || strprefix(p1, "cipher "))
{
return;
}<= /span>
@@ -4656,10 +4600,7 @@
= if (report_inconsistent)
{
= msg(msglevel, "WARNING: '%s' is= used inconsistently, %s=3D'%s', %s=3D'%s'",- saf= e_print(p1_prefix, &gc),
- b1_name,
- safe_print(p1, &gc),<= /span>
- = b2_name,
+ = safe_print(p1_prefix, &gc), b1_name, safe_print(= p1, &gc), b2_name,
safe_pr= int(p2, &gc));
}
= goto done;
@@ -4668,11 +4609,7 @@
}

msg(msglev= el, "WARNING: '%s' is present in %s config but missing in %s c= onfig, %s=3D'%s'",
- safe_print(p1_prefix, &gc),
- b1_name,
- b2_name,
- b1_name,
- safe_print(p1, &gc));
+ safe_print(p1= _prefix, &gc), b1_name, b2_name, b1_name, safe_print(p1, &gc));

done:
gc_free(&= ;gc);
@@ -4680,13 +4617,9 @@
}
<= span>

static void
-options_warning_safe_scan1(const int msglevel,
- const int= delim,

- = const bool report_inconsistent,
- const struct buffer *b1_s= rc,
- = const struct buffer *b2_src,
- const char *b1_name,
<= span style=3D"color: hsl(0, 100%, 40%);">- const = char *b2_name)

+optio= ns_warning_safe_scan1(const int msglevel, const int delim, const bool repor= t_inconsistent,
+ = const struct buffer *b1_src, const struct buffer *b2= _src,
+ = const char *b1_name, const char *b2_name)
{
struct gc_arena gc =3D gc_new();
s= truct buffer b =3D *b1_src;
@@ -4694,7 +4627,8 @@
while (buf_parse(&b, delim, p, OPTION_PAR= M_SIZE))
{
- options_warning_safe_scan2(msglevel, delim, report_incons= istent, p, b2_src, b1_name, b2_name);
+ options_warning_safe_scan2(msglevel, delim, repor= t_inconsistent, p, b2_src, b1_name,
+ b2_name);
}


gc_free(&gc);@@ -4714,13 +4648,9 @@
buf_printf(&loca= l, "version %s", expected);
buf_printf(&= amp;remote, "version %s", actual);

- options_warning_safe_scan1= (msglevel, ',', true,

- &local, &remote,<= br>- = "local", "remote");
+ options_warning_safe_scan1(msglevel, '= ;,', true, &local, &remote, "local", "remote&quo= t;);

= - options_warning_safe_scan1(msglevel, ',', false,- = &remote, &local,
- "remote", "local&q= uot;);
+ optio= ns_warning_safe_scan1(msglevel, ',', false, &remote, &local= , "remote", "local");
}
=
gc_free(&gc);
@@ -4759,13 = +4689,12 @@
options_string_version(const char *s, struct g= c_arena *gc)
{
struct buffer out =3D = alloc_buf_gc(4, gc);
- = strncpynt((char *) BPTR(&out), s, 3);
+ strncpynt((char *)BPTR(&out), s, 3);
return BSTR(&out);
}
=
char *
- = struct gc_arena *gc)
+options_string_extract_option(const char *options_string, = const char *opt_name, struct gc_arena *gc)
{
char *ret =3D NULL;

const size_t opt_name_len = =3D strlen(opt_name);
@@ -4773,14 +4702,14 @@
const char *p =3D options_string;

while (p)

{
- = if (0 =3D=3D strncmp(p, opt_name, opt_name_len)
- && strlen(p) > (opt= _name_len+1) && p[opt_name_len] =3D=3D ' ')
+ if (0 =3D=3D strncmp(p, opt= _name, opt_name_len) && strlen(p) > (opt_name_len + 1)
+ && p[opt_= name_len] =3D=3D ' ')
{
= /* option found, extract value */
- const char *start =3D &p[opt_name_le= n+1];
+ co= nst char *start =3D &p[opt_name_len + 1];
= const char *end =3D strchr(p, ',');
si= ze_t val_len =3D end ? end - start : strlen(start);
- ret =3D gc_malloc(val_len+1, tr= ue, gc);
+ = ret =3D gc_malloc(val_len + 1, true, gc);
mem= cpy(ret, start, val_len);
break;
}

@@ -4912,20 +4841,13 @@
= struct options o;
init_options(&o, true);
- fprintf(= fp, usage_message,
- = title_string,
= - o.ce.connect_retry_seconds,
- o.ce.connect_retry_seconds_max,
- o.ce.local_port, o.ce.= remote_port,

- = TUN_MTU_DEFAULT, TAP_MTU_EXTRA_DEFAULT,
- o.verbosity,
- o.authname,
- o.replay_window, o.replay_time,
- o.tls_timeout, = o.renegotiate_seconds,
= - o.handshake_window, o.transition_window);
+ fprintf(fp, usage_message, title_str= ing, o.ce.connect_retry_seconds,
+ o.ce.connect_retry_seconds_max, o.ce.local_port, o= .ce.remote_port, TUN_MTU_DEFAULT,
+ TAP_MTU_EXTRA_DEFAULT, o.verbosity, o.authname, o= .replay_window, o.replay_time,
+ o.tls_timeout, o.renegotiate_seconds, o.handshake_wi= ndow, o.transition_window);
fflush(fp);

-#endif /* ENABLE_S= MALL */
+#endif = /* ENABLE_SMALL */

openvpn_exit(OPENVPN_EXIT_STATUS_USAGE); /* exit point */
}
@@ -4933,7 +4855,7 @@
vo= id
usage_small(void)
{
- msg(M_WARN|M_NOPREFIX, "Use --h= elp for more information.");
+ msg(M_WARN | M_NOPREFIX, "Use --help for more inform= ation.");
openvpn_exit(OPENVPN_EXIT_STATUS_USAGE)= ; /* exit point */
}

@@ = -4966,8 +4888,7 @@
#define LZO_LIB_VER_STR "", &= quot;"
#endif

- msg(flags, "library versions: %s%s= %s", get_ssl_library_version(),
- LZO_LIB_VER_STR);
+ msg(flags, "library versions: %s%s%s", g= et_ssl_library_version(), LZO_LIB_VER_STR);

#undef LZO_LIB_VER_STR

}
@@ -4975,20 += 4896,20 @@
static void
usage_version(void= )
{
- = msg(M_INFO|M_NOPREFIX, "%s", title_string);
- show_library_versions( M_INFO|M_NOPR= EFIX );
+ msg(M_IN= FO | M_NOPREFIX, "%s", title_string);
+ show_library_versions(M_INFO | M_NOPREFIX);=
#ifdef _WIN32
- show_windows_version( M_INFO|M_NOPREFIX );
+ show_windows_version(M_INFO | M_NO= PREFIX);
#endif
show_dco_version(M_IN= FO | M_NOPREFIX);
- = msg(M_INFO|M_NOPREFIX, "Originally developed by James Yonan");
- msg(M_INFO|M_NOPREFI= X, "Copyright (C) 2002-2025 OpenVPN Inc <sales@...515...>")= ;
+ msg(M_INFO | M= _NOPREFIX, "Originally developed by James Yonan");
+ msg(M_INFO | M_NOPREFIX, "= ;Copyright (C) 2002-2025 OpenVPN Inc <sales@...515...>");
=
#ifndef ENABLE_SMALL
#ifdef CONFIGURE_DEFINES
- msg(M_INFO|M_NOPREF= IX, "Compile time defines: %s", CONFIGURE_DEFINES);
+ msg(M_INFO | M_NOPREFIX, &quo= t;Compile time defines: %s", CONFIGURE_DEFINES);

#end= if
#ifdef CONFIGURE_SPECIAL_BUILD
- msg(M_INFO|M_NOPREFIX, "special build= : %s", CONFIGURE_SPECIAL_BUILD);
+ msg(M_INFO | M_NOPREFIX, "special build: %s"= ;, CONFIGURE_SPECIAL_BUILD);
#endif
#endi= f
openvpn_exit(OPENVPN_EXIT_STATUS_GOOD);
@@ -5024,7 +4945,7 @@

}
#endif=

-#ifdef _WI= N32 /* This function is only used when compiling on Windows */
<= span style=3D"color: hsl(120, 100%, 40%);">+#ifdef _WIN32 /* This function = is only used when compiling on Windows */

static unsigned = int
atou(const char *str)
{
@@ -5041,13 +4962,8 @@

}

int

-parse_line(co= nst char *line,
- = char *p[],
- = const int n,
- = const char *file,
- int msglevel,
- struct gc_arena *gc)
+parse_line(const char *line, char *p[], const in= t n, const char *file, const int line_num,
+ int msglevel, struct gc_arena *gc)=
{
const int STATE_INITIAL =3D 0;
= const int STATE_READING_QUOTED_PARM =3D 1;
@@ -5= 156,9 +5072,13 @@
if (!(out =3D=3D '\\= ' || out =3D=3D '\"' || space(out)))
= {
#ifdef ENABLE_SMALL
- msg(msglevel, "%sOpti= ons warning: Bad backslash ('\\') usage in %s:%d", error_prefi= x, file, line_num);
+= msg(msglevel, "%sOptions warning: Bad backslash (&= #39;\\') usage in %s:%d",
+ error_prefix, file, line_num);
#else
- = msg(msglevel, "%sOptions warning: Bad backslash ('= \\') usage in %s:%d: remember that backslashes are treated as shell-esc= apes and if you need to pass backslash characters as part of a Windows file= name, you should use double backslashes such as \"c:\\\\" PACKAGE= "\\\\static.key\"", error_prefix, file, line_num);+ msg(msgl= evel,
+ = "%sOptions warning: Bad backslash ('\\') usage in %s= :%d: remember that backslashes are treated as shell-escapes and if you need= to pass backslash characters as part of a Windows filename, you should use= double backslashes such as \"c:\\\\" PACKAGE
+ "\\\\stati= c.key\"",
+= error_prefix, file, line_num);
#en= dif
return 0;
= }
@@ -5173,7 +5093,7 @@
= {
parm[SIZE(parm) - 1] =3D 0; msg(msglevel, "%sOptions error: Parameter at %= s:%d is too long (%d chars max): %s",
- error_prefix, file, line_num, (int= ) SIZE(parm), parm);
= + error_prefix, file, line_num, (int)SIZE(parm), parm);<= /span>
return 0;
}
parm[parm_len++] =3D out;
@@ -5= 189,17 +5109,20 @@

if (state =3D=3D = STATE_READING_QUOTED_PARM)
{
- msg(msglevel, "%sOptions error: No= closing quotation (\") in %s:%d", error_prefix, file, line_num);=
+ msg(msgleve= l, "%sOptions error: No closing quotation (\") in %s:%d", er= ror_prefix, file,
+ = line_num);
return 0;
= }
if (state =3D=3D STATE_READING_SQUOTED_PARM)
{
- = msg(msglevel, "%sOptions error: No closing single quotation (\'= ;) in %s:%d", error_prefix, file, line_num);
+ msg(msglevel, "%sOptions error: = No closing single quotation (\') in %s:%d", error_prefix,+ file, line_num);=
return 0;
}
= if (state !=3D STATE_INITIAL)
{
- msg(msglevel, "%sOptions e= rror: Residual parse state (%d) in %s:%d", error_prefix, state, file, = line_num);
+ m= sg(msglevel, "%sOptions error: Residual parse state (%d) in %s:%d"= ;, error_prefix, state,
+ file, line_num);
return 0;<= br> }
#if 0
@@ -5223,11 +5146,13= @@
}
}

<= span style=3D"color: hsl(0, 100%, 40%);">-struct in_src {

-#define IS_TYPE_FP 1
+struct in_src
+{
+#define IS_TYPE_FP 1
#define IS_TYPE_BUF 2
int type;
- union {
+= union
+ {
FILE *fp;
struct buffer *mult= iline;
} u;
@@ -5243,7 +5168,7 @@
else if (is->type =3D=3D IS_TYPE_BUF)
= {
bool status =3D buf_parse(is->u.multiline= , '\n', line, size);
- if ((int) strlen(line) + 1 < size)
+ if ((int)strlen(line) + 1 < si= ze)
{
strcat(line, &q= uot;\n");
}
@@ -5257,11 +5182= ,10 @@
}

static char *<= /span>
-read_inline_file(struc= t in_src *is, const char *close_tag,
- int *num_lines, struct gc_arena *gc)=
+read_inline_file(struct in= _src *is, const char *close_tag, int *num_lines, struct gc_arena *gc)
{
char line[OPTION_LINE_SIZE];
<= span style=3D"color: hsl(0, 100%, 40%);">- struct buffer buf =3D alloc_b= uf(8*OPTION_LINE_SIZE);

+ struct buffer buf =3D alloc_buf(8 * OPTION_LINE_SIZE);
char *ret;

bool endtagfound =3D false;=

@@ -5279,7 +5203,7 @@
= endtagfound =3D true;
break;
}

- = if (!buf_safe(&buf, strlen(line)+1))
+ if (!buf_safe(&buf, strlen(line) + 1))
{
/* Increase buffer siz= e */
struct buffer buf2 =3D alloc_buf(buf.capa= city * 2);
@@ -5309,7 +5233,7 @@
if (p= [0] && !p[1])
{
char = *arg =3D p[0];
- = if (arg[0] =3D=3D '<' && arg[strlen(arg)-1] =3D=3D '= ;>')
+ = if (arg[0] =3D=3D '<' && arg[strlen(arg) - 1] =3D=3D = 9;>')
{
struct= buffer close_tag;

@@ -5335,8 +5259,7 @@<= /span>
}

static int
= -check_inline_file_via_buf(struct= buffer *multiline, char *p[],
- struct gc_arena *gc)
+check_inline_file_via_buf(struct buffer= *multiline, char *p[], struct gc_arena *gc)
{
<= span> struct in_src is;

is.type =3D IS_TYPE_BUF;
@@ -5344,60 +5267,31 @@
return check_in= line_file(&is, p, gc);
}

<= span style=3D"color: hsl(0, 100%, 40%);">-static void

-add_option(struct options *options,<= br>- char *p[],<= br>- bool is_inline,
- const char *f= ile,
- int li= ne,
- const i= nt level,
- c= onst int msglevel,
- = const unsigned int permission_mask,
- unsigned int *option_types_found,- struct env_set *es)= ;
+static void add_op= tion(struct options *options, char *p[], bool is_inline, const char *file,<= /span>
+ = int line, const int level, const int msglevel,
+ const unsigned int per= mission_mask, unsigned int *option_types_found,
+ struct env_set *es);
+
+static void remove_option(struct context = *c, struct options *options, char *p[], bool is_inline,
+ const char *f= ile, int line, const int msglevel,
+ const unsigned int permission_mask= , unsigned int *option_types_found,
+ struct env_set *es);
+

+static void update_option(struct context *c, struct= options *options, char *p[], bool is_inline,
+ const char *file, int l= ine, const int level, const int msglevel,
+ const unsigned int permissi= on_mask, unsigned int *option_types_found,
+ struct env_set *es, unsign= ed int *update_options_found);

static vo= id
-remove_option(struc= t context *c,
- = struct options *options,
- char *p[],
- bool is_inline,
- const char *file,
- int line,
- const int msglevel,<= br>- const unsigned = int permission_mask,
- = unsigned int *option_types_found,
- struct env_set *es);
-

-static void
-update_option(struct context *c,
- struct options *options,
- char *p[],
- bool is_inline,
<= br>- const char *fil= e,
- int l= ine,
- con= st int level,
- = const int msglevel,
- const unsigned int permission_mask,
- unsigned int *option_types_fo= und,
- str= uct env_set *es,
- = unsigned int *update_options_found);
-
-read_co= nfig_file(struct options *options,
- const char *file,
- int level,
- const char *top_file,
- const int= top_line,
- = const int msglevel,
- const unsigned int permission_mask,
- unsigned int *option_ty= pes_found,
- = struct env_set *es)
+read_config_file(struct options *options, const char *file, int level= , const char *top_file,
+ const int top_line, const int msglevel, const unsigned= int permission_mask,
+ unsigned int *option_types_found, struct env_set *es)
{
const int max_recursive_levels =3D 10= ;
FILE *fp;
int line_num;<= br>- char line[OPTION_LINE_SIZ= E+1];
- char *p[MAX_= PARMS+1];
+ char l= ine[OPTION_LINE_SIZE + 1];
+ char *p[MAX_PARMS + 1];

+= +level;
if (level <=3D max_recursive_levels)=
@@ -5420,7 +5314,8 @@
++line_num= ;
if (strlen(line) =3D=3D OPTION_LINE_SIZE= )
{
- msg(msglevel, "In %s:%d: Maximum op= tion line length (%d) exceeded, line starts with %s",
+ msg(msglevel,
+ = "In %s:%d: Maximum option line length (%d) exceeded, line starts wit= h %s",
file, line_num, OPTION= _LINE_SIZE, line);
}

@@ -5429,13 +5324,13 @@
{
offset =3D 3;
= }
- = if (parse_line(line + offset, p, SIZE(p)-1, file, line_num, msglevel, &am= p;options->gc))
+ = if (parse_line(line + offset, p, SIZE(p) - 1, file, line_num= , msglevel,
+ = &options->gc))
= {
bypass_doubledash(&p[0]);
int lines_inline =3D check_inline_file_vi= a_fp(fp, p, &options->gc);
- add_option(options, p, lines_inline, file, = line_num, level,
- = msglevel, permission_mask, option_types_found,
- = es);
+ = add_option(options, p, lines_inline, file, line_num, level, msg= level,
+ = permission_mask, option_types_found, es);
line_num +=3D lines_inline;

= }
}
@@ -5446,25 +5341,= 24 @@
}
else
{

- = msg(msglevel, "In %s:%d: Error opening configuration file: %s&quo= t;, top_file, top_line, file);
+ msg(msglevel, "In %s:%d: Error opening configur= ation file: %s", top_file, top_line,
+ file);
}
}
else
{=
- msg(msglevel, "= In %s:%d: Maximum recursive include levels exceeded in include attempt of f= ile %s -- probably you have a configuration file that tries to include itse= lf.", top_file, top_line, file);
+ msg(msglevel,
+ "In %s:%d: Maximum recursive include l= evels exceeded in include attempt of file %s -- probably you have a configu= ration file that tries to include itself.",
+ top_file, top_line, file);<= br> }
secure_memzero(line, sizeof(line));
CLEAR(p);
}
static void
-re= ad_config_string(const char *prefix,
- struct options *options,
- const char *config,=
- co= nst int msglevel,
- = const unsigned int permission_mask,
- unsigned int *option_types_= found,
- = struct env_set *es)
+read_config_string(const char *prefix, struct options *options, const c= har *config,
+ = const int msglevel, const unsigned int permission_mask,<= br>+ unsigned= int *option_types_found, struct env_set *es)
{
= char line[OPTION_LINE_SIZE];
struct buffer = multiline;
@@ -5474,15 +5368,15 @@
=
while (buf_parse(&multiline, '\n', line, sizeof(= line)))
{
- char *p[MAX_PARMS+1];
+ char *p[MAX_PARMS + 1];
= CLEAR(p);
++line_num;
- if (parse_line(line, p, SIZE(p)-1, prefix= , line_num, msglevel, &options->gc))
+ if (parse_line(line, p, SIZE(p) - 1, prefix= , line_num, msglevel, &options->gc))
{
bypass_doubledash(&p[0]);
= int lines_inline =3D check_inline_file_via_buf(&multiline, p, = &options->gc);
-= add_option(options, p, lines_inline, prefix, line_num, 0, msgle= vel,
- = permission_mask, option_types_found, es);
+ add_option(options, p, lines_inline= , prefix, line_num, 0, msglevel, permission_mask,
+ option_types_found, es= );
line_num +=3D lines_inline;
}

CLEAR(p);
@@ -5491,13 = +5385,8 @@
}

void
-parse_argv(struct options *= options,
- co= nst int argc,
- = char *argv[],
- = const int msglevel,
- const unsigned int permission_mask,
- unsigned int *option_types_found,
- struct env_s= et *es)
+parse_argv(s= truct options *options, const int argc, char *argv[], const int msglevel,
+ const unsi= gned int permission_mask, unsigned int *option_types_found, struct env_set = *es)
{
/* usage message */
= if (argc <=3D 1)
@@ -5508,24 +5397,26 @@
/* config filename specified only? */
= if (argc =3D=3D 2 && strncmp(argv[1], "--", 2)) {
- = char *p[MAX_PARMS+1];
- = add_option(options, p, false, NULL, 0, 0, msglevel, permission_mask,
- option= _types_found, es);
+ = add_option(options, p, false, NULL, 0, 0, msglevel, permission_mask,= option_types_found,
= + es);
}
else
{
/* parse command line */
for (int i =3D 1; i < argc; ++i)
= {
- = char *p[MAX_PARMS+1];
+ char *p[MAX_PARMS + 1];
CLEAR(p)= ;
p[0] =3D argv[i];
= if (strncmp(p[0], "--", 2))
{
- msg(msgle= vel, "I'm trying to parse \"%s\" as an --option paramete= r but I don't see a leading '--'", p[0]);
+ msg(msglevel,=
+ "= I'm trying to parse \"%s\" as an --option parameter but I don= 't see a leading '--'",
+ p[0]);
= }
else
{=
@@ -5548,31 +5439,27 @@
}
}
}
<= span style=3D"color: hsl(0, 100%, 40%);">- add_option(options, p= , false, NULL, 0, 0, msglevel, permission_mask,

- option_types_found, es);
+ add_optio= n(options, p, false, NULL, 0, 0, msglevel, permission_mask, option_types_fo= und,
+ = es);
i +=3D j - 1;
= }
}
}
<= br> bool
-apply_p= ush_options(struct context *c,
- struct options *options,
- struct buffer *buf,
- unsigne= d int permission_mask,
= - unsigned int *option_types_found,
- struct env_set *es,
- bool is= _update)
+apply_push_= options(struct context *c, struct options *options, struct buffer *buf,
+ unsi= gned int permission_mask, unsigned int *option_types_found,
+ struct env_set *= es, bool is_update)

{
char line[OPTIO= N_PARM_SIZE];
int line_num =3D 0;
= const char *file =3D "[PUSH-OPTIONS]";
- const int msglevel =3D D_PUSH_ERRORS|M_OPTE= RR;
+ const int ms= glevel =3D D_PUSH_ERRORS | M_OPTERR;
unsigned int upda= te_options_found =3D 0;

while (buf_p= arse(buf, ',', line, sizeof(line)))
{- char *p[MAX_PARMS+1];<= /span>
+ char *p[MAX_= PARMS + 1];
CLEAR(p);
++l= ine_num;
unsigned int push_update_option_flags =3D= 0;
@@ -5602,22 +5489,22 @@
re= turn false; /* Cause push/pull error and stop push processing */
= }

- if (parse_line(&line[i], p, SIZE(p)-1, file, line_= num, msglevel, &options->gc))
+ if (parse_line(&line[i], p, SIZE(p) - 1, file,= line_num, msglevel, &options->gc))
{
if (!is_update)
{
- add_option= (options, p, false, file, line_num, 0, msglevel,
- permission_mask, opti= on_types_found, es);
= + add_option(options, p, false, file, line_num, 0, msglevel,= permission_mask,
+ = option_types_found, es);
= }
else if (push_update_option_flags & = PUSH_OPT_TO_REMOVE)
{
- remove_option(c, options, p, f= alse, file, line_num, msglevel,
- permission_mask, option_types_found= , es);
+ = remove_option(c, options, p, false, file, line_num, msglevel, permission= _mask,
+ = option_types_found, es);
}
else
{
- update_option(c, o= ptions, p, false, file, line_num, 0, msglevel,

- permission_mask, opt= ion_types_found, es, &update_options_found);
+ update_option(c, options, p, f= alse, file, line_num, 0, msglevel, permission_mask,
+ option_type= s_found, es, &update_options_found);
}
}
}
@@ -5625,54 = +5512,37 @@
}

void
-options_server_import(stru= ct options *o,
- = const char *filename,
- int msglevel,
- unsigned int permission_= mask,
- = unsigned int *option_types_found,
+options_server_import(struct options *o, const char *fi= lename, int msglevel,
+ unsigned int permission_mask, unsigned int *option_= types_found,
struct env_set *es)
{
msg(D_PUSH, "OPTIONS IMPORT: read= ing client specific options from: %s", filename);
- read_config_file(o,
- filename,- 0,<= br>- filename= ,
- = 0,
- = msglevel,
- = permission_mask,
- option_types_found,
+ read_config_file(o, filename, 0, filename, = 0, msglevel, permission_mask, option_types_found,
= es);
}

voi= d
-options_string_impor= t(struct options *options,
- const char *config,
- const int msglevel,- const un= signed int permission_mask,
- unsigned int *option_types_found,
+options_string_import(struct opti= ons *options, const char *config, const int msglevel,

+ const unsigned int = permission_mask, unsigned int *option_types_found,
= struct env_set *es)
{
- read_config_string("[CONFIG-STRING= ]", options, config, msglevel, permission_mask, option_types_found, es= );
+ read_config_s= tring("[CONFIG-STRING]", options, config, msglevel, permission_ma= sk,
+ = option_types_found, es);
}
=
-#define VERIFY_PERMISSION(ma= sk) { \
- if (!verify_permission(p[0], file, lin= e, (mask), permission_mask, \
- option_types_found, msglevel,= options, is_inline)) \
- { = \
- = goto err; \
- } = \
-}
+#define VERIFY_PERMISSION(mask) = \
+ { = \
+ if (!verify_permission(p[0], file, line, (mask),= permission_mask, option_types_found, \
+ msglevel, options, is_in= line)) \
+ { = \
+ goto err; = \
+ } = \
+ }

static boo= l
-verify_permission(co= nst char *name,
- = const char *file,
- int line,
- const unsigned int type,
- const unsigned int all= owed,
- = unsigned int *found,
= - const int msglevel,
- struct options *options,
- bool is_inline)
+verify_permission(const= char *name, const char *file, int line, const unsigned int type,+ const unsig= ned int allowed, unsigned int *found, const int msglevel,
+ struct options *opt= ions, bool is_inline)
{
if (!(type &a= mp; allowed))
{
@@ -5682,8 +5552,7 @@<= /span>

if (is_inline && !(type &= ; OPT_P_INLINE))
{
- msg(msglevel, "option '%s' is not ex= pected to be inline (%s:%d)", name,
- file, line);
+ msg(msglevel, "option '%s' is = not expected to be inline (%s:%d)", name, file, line);
return false;

}

= @@ -5700,12 +5569,12 @@
* connection_list

*/

- if ((type & OPT_P_CONNECTION) && options-&g= t;connection_list
- = && !(allowed & OPT_P_PULL_MODE))
+ if ((type & OPT_P_CONNECTION) &&am= p; options->connection_list && !(allowed & OPT_P_PULL_MODE))=
{
if (file)
= {
- = msg(M_WARN, "Option '%s' in %s:%d is ignored by previous <= connection> blocks ", name, file, line);
+ msg(M_WARN, "Option '%s&#= 39; in %s:%d is ignored by previous <connection> blocks ", name,=
+ fil= e, line);
}
else {
@@ -5721,13 +5590,10 @@
= * many parameters.
*/

-#define NM_QUOTE_HINT (1<<0)
+#define NM_QUOTE_HINT = (1 << 0)

static bool
-no_more_than_n_args(const int msgle= vel,

- = char *p[],
- = const int max,
- const unsigned int flags)
+no_more_than_n_args(const int msglevel, char= *p[], const int max, const unsigned int flags)
{ const int len =3D string_array_len((const char **)p);
@@ -5738,11 +5604,11 @@
<= br> if (len > max)
{
- msg(msglevel, "the --%s direc= tive should have at most %d parameter%s.%s",
- p[0],
- max - 1,
+ msg(msglevel, "the --%s directive sho= uld have at most %d parameter%s.%s", p[0], max - 1,
= max >=3D 3 ? "s" : "",
- (flags & NM_QUOTE_HINT) = ? " To pass a list of arguments as one of the parameters, try enclosi= ng them in double quotes (\"\")." : "");+ (flags & NM_Q= UOTE_HINT)
+ = ? " To pass a list of arguments as one of the parameters, try = enclosing them in double quotes (\"\")."
+ : "");=
return false;
}
= else
@@ -5758,10 +5624,10 @@
}
#define RESET_OPTION_ROUTES(option_ptr, field) \<= /span>
- if (option_ptr) = \
= - { \
- option_ptr->field =3D NULL; \
- option_ptr->= flags =3D 0; \
+ if (option_ptr) \
+ { = \
+ op= tion_ptr->field =3D NULL; \
+ option_ptr->flags =3D 0; = \
}

/**
= @@ -5780,20 +5646,14 @@
* @param line The line numb= er where the function is called.
* @param msglevel The me= ssage level.
* @param permission_mask The permission mask= used by VERIFY_PERMISSION().
- * @param option_types_found A pointer to the variable where the fl= ags corresponding to the options found are stored.
+ * @param option_types_found A pointer to th= e variable where the flags corresponding to the options
+ * found are stored.
= * @param es The environment set structure.
*/
<= span> static void

-remo= ve_option(struct context *c,
- struct options *options,
- char *p[],
- bool is_inline,
- const char *file,- int line,=
- const int msgl= evel,
- co= nst unsigned int permission_mask,
- unsigned int *option_types_found,
- struct env_set *es)
+remove_option(struct co= ntext *c, struct options *options, char *p[], bool is_inline,
+ const char *file, i= nt line, const int msglevel, const unsigned int permission_mask,

= + unsigned int *op= tion_types_found, struct env_set *es)
{
= int msglevel_fc =3D msglevel_forward_compatible(options, msglevel);

@@ -5815,9 +5675,8 @@
= VERIFY_PERMISSION(OPT_P_ROUTE);
if (c->c1.rou= te_list)
{
- delete_routes_v4(c->c1.route_list, c->c1.tu= ntap,
- = ROUTE_OPTION_FLAGS(&c->options),
- es, &c->= ;net_ctx);
+ = delete_routes_v4(c->c1.route_list, c->c1.tuntap, ROUTE_OPTION_FLAG= S(&c->options), es,
+ &c->net_ctx);
= RESET_OPTION_ROUTES(options->routes, routes);
}

}
@@ -5826,8 +5685,7 @@
VERIFY_PERMISSION(OPT_P_ROUTE);
= if (c->c1.route_ipv6_list)
{
- delete_routes_v6(c->= c1.route_ipv6_list, c->c1.tuntap,

- ROUTE_OPTION_FLAGS(&c->o= ptions),
+ = delete_routes_v6(c->c1.route_ipv6_list, c->c1.tuntap, ROUTE_OPTION_F= LAGS(&c->options),
es,= &c->net_ctx);
RESET_OPTION_ROUTES(opti= ons->routes_ipv6, routes_ipv6);
}
@@ -5874,7 +5732,7 @@

}
else i= f (streq(p[0], "tun-mtu") && !p[1])
= {
- VERIFY_PERMI= SSION(OPT_P_PUSH_MTU|OPT_P_CONNECTION);
+ VERIFY_PERMISSION(OPT_P_PUSH_MTU | OPT_P_CONNEC= TION);
options->ce.tun_mtu =3D TUN_MTU_DEFAULT;=
options->ce.tun_mtu_defined =3D false;<= br> options->ce.occ_mtu =3D 0;
@@ -5942,7 = +5800,9 @@
break;
= }
}
- msg(msglevel_unknown, "Unrecognized option or miss= ing or extra parameter(s) in %s:%d: -%s (%s)", file, line, p[0], PACKA= GE_VERSION);
+ = msg(msglevel_unknown,
+ p[0], PACKAGE_VERSION);
}=
return;
err:
@@ -595= 6,7 +5816,8 @@
rol_check_alloc(options);
if (pull_mode)

{
- if (!ip_or_dns_addr_safe(p[1], options->= allow_pull_fqdn) && !is_special_addr(p[1])) /* FQDN -- may be DNS n= ame */
+ if (!= ip_or_dns_addr_safe(p[1], options->allow_pull_fqdn)
+ && !is_special_addr(= p[1])) /* FQDN -- may be DNS name */
{
<= span> msg(msglevel, "route parameter network/IP '%s= 9; must be a valid address", p[1]);

retur= n false;
@@ -5966,7 +5827,8 @@
= msg(msglevel, "route parameter netmask '%s' must be an IP add= ress", p[2]);
return false;
}

- = if (p[3] && !ip_or_dns_addr_safe(p[3], options->allow_pull_fqdn)= && !is_special_addr(p[3])) /* FQDN -- may be DNS name */+ if (p[3] && != ip_or_dns_addr_safe(p[3], options->allow_pull_fqdn)
+ && !is_special_addr(= p[3])) /* FQDN -- may be DNS name */
{
<= span> msg(msglevel, "route parameter gateway '%s' = must be a valid address", p[3]);

return f= alse;
@@ -6002,7 +5864,8 @@
{
if (streq(p[1], "search-domains") && p[2])
{
- = dns_domain_list_append(&options->dns_options.search_domains, &am= p;p[2], &options->dns_options.gc);
+ dns_domain_list_append(&options->dns_o= ptions.search_domains, &p[2],
+ &options->dns_options.g= c);
}
else if (streq(p[1], "= server") && p[2] && p[3] && p[4])
{

@@ -6013,7 +5876,8 @@
= return false;
}

- struct dns_server *server = =3D dns_server_get(&options->dns_options.servers, priority, &opt= ions->dns_options.gc);

+ struct dns_server *server =3D
+ dns_server_get(&options->dns_opt= ions.servers, priority, &options->dns_options.gc);
=
if (streq(p[3], "address") && p= [4])
{
@@ -6021,7 +5885,8 @@
{
if (!dns_server_= addr_parse(server, p[i]))
{
- msg(msglevel, &q= uot;--dns server %ld: malformed address or maximum exceeded '%s'&qu= ot;, priority, p[i]);

+ msg(msglevel, "--dns server %ld: malformed addre= ss or maximum exceeded '%s'",
+ priority, p[i]);
<= span> return false;

}<= /span>
}
@@ -6076,7 +5941,9 @@=
}
else
= {
- msg(msg= level, "--dns server %ld: unknown option type '%s' or missing = or unknown parameter", priority, p[3]);
+ msg(msglevel,
+ "--dns server %ld: unkn= own option type '%s' or missing or unknown parameter",<= br>+ priority, p= [3]);
return false;
}=
}
@@ -6092,7 +5959,8 @@
* @brief Processes an option to update. It first checks whether it has= already

* received an option of the same type wit= hin the same update message.
* If the option has a= lready been received, it calls add_option().
- * Otherwise, it deletes all existing values = related to that option before calling add_option().
+ * Otherwise, it deletes all exist= ing values related to that option before calling
+ * add_option().
* * @param c The context structure.
* @param optio= ns A pointer to the options structure.
@@ -6103,24 +5971,18= @@
* @param level The level of the option.
* @param msglevel The message level for logging.

* @= param permission_mask The permission mask used by VERIFY_PERMISSION().
- * @param option_types_fou= nd A pointer to the variable where the flags corresponding to the options f= ound are stored.
+ * = @param option_types_found A pointer to the variable where the flags corresp= onding to the options
+ * found are stored.
* @param es The environment set st= ructure.
- * @param upd= ate_options_found A pointer to the variable where the flags corresponding t= o the update options found are stored,
- * used to check if an option = of the same type has already been processed by update_option() within the s= ame push-update message.
+ * @param update_options_found A pointer to the variable where the fla= gs corresponding to the update
+ * options found are stored, used to check if an option of the s= ame type has already been processed
+ * by update_option() within the same push-update message.<= /span>
*/
static void
-update_option(struct context *c,
- struct options *option= s,

- char = *p[],
- bo= ol is_inline,
- = const char *file,
- int line,
- const int level,
- const int msglevel,
- const unsigned int permission_mask,<= /span>
- unsigned= int *option_types_found,
- struct env_set *es,
- unsigned int *update_options_found)+update_option(struct context = *c, struct options *options, char *p[], bool is_inline,
+ const char *file, int lin= e, const int level, const int msglevel,
+ const unsigned int permission_mask, unsig= ned int *option_types_found,
+ struct env_set *es, unsigned int *update_options_fou= nd)
{
const bool pull_mode =3D BOOL_C= AST(permission_mask & OPT_P_PULL_MODE);
ASSERT(MAX= _PARMS >=3D 7);
@@ -6136,8 +5998,7 @@
= }
if (c->c1.route_list) {
= - delete_routes_v4(c->c1.route_list, c->c1.tuntap,
- = ROUTE_OPTION_FLAGS(&c->options),
+ delete_routes_v4(c->c1.route= _list, c->c1.tuntap, ROUTE_OPTION_FLAGS(&c->options),
<= span> es, &c->net_ctx);

<= span> RESET_OPTION_ROUTES(options->routes, routes);
}
@@ -6156,8 +6017,7 @@
= if (c->c1.route_ipv6_list)
= {
delete_routes_v6(c->c1.route_ipv6_= list, c->c1.tuntap,
= - ROUTE_OPTION_FLAGS(&c->options),
- = es, &c->net_ctx);
+ ROUTE_OPTION_FLAGS(&c-&= gt;options), es, &c->net_ctx);
RESE= T_OPTION_ROUTES(options->routes_ipv6, routes_ipv6);
= }
*update_options_found |=3D OPT_P_U_= ROUTE6;
@@ -6229,7 +6089,7 @@
= *update_options_found |=3D OPT_P_U_DHCP;
}<= br> }
-#else = /* if defined(_WIN32) || defined(TARGET_ANDROID) */
+#else /* if defined(_WIN32) || defined(T= ARGET_ANDROID) */
else if (streq(p[0], "dhcp-opti= on") && p[1] && !p[3])
{ if (!(*update_options_found & OPT_P_U_DHCP))@@ -6240,8 +6100,7 @@
}
= }
#endif /* if defined(_WIN32) || defined(TARGET_ANDROID= ) */
- add_option(op= tions, p, is_inline, file, line,
- level, msglevel, permission_mask,
+ add_option(options, p, is_inlin= e, file, line, level, msglevel, permission_mask,

= option_types_found, es);
return;
err:

@@ -6249,16 +6108,15 @@
}
static void
-set_user_script(struct options *options,
- const char **script,
- const cha= r *new_script,
- = const char *type,
- bool in_chroot)
+set_user_script(struct options *options, const char **scri= pt, const char *new_script,
+ const char *type, bool in_chroot)
= {
if (*script)
{
- msg(M_WARN, "Multiple --%= s scripts defined. "
- "The previously configured script is overridden."= ;, type);
+ ms= g(M_WARN,
+ = "Multiple --%s scripts defined. "
+ "The previously configured scri= pt is overridden.",
+ type);
}
*script= =3D new_script;
options->user_script_used =3D true= ;
@@ -6266,14 +6124,12 @@
#ifndef ENABLE_S= MALL
{
char script_name[100];=
- snprintf(scri= pt_name, sizeof(script_name),
- "--%s script", type);
+ snprintf(script_name, sizeof(s= cript_name), "--%s script", type);

if (check_cmd_access(*script, script_name, (in_chroot ? option= s->chroot_dir : NULL)))

{
= msg(M_USAGE, "Please correct this error.");
}

-<= br> }
#endif
}
= @@ -6284,9 +6140,9 @@
if (comp_non_stub_enabled(info))=
{
msg(M_WARN, "WARNING:= Compression for receiving enabled. "
- "Compression has been used in the pas= t to break encryption. "
- "Compression support is deprecated and we recommen= d to disable "
- = "it completely.");
+ "Compression has been used in t= he past to break encryption. "
+ "Compression support is deprecated= and we recommend to disable "
+ "it completely.");
= }
}

@@ -6306,= 16 +6162,9 @@
}

static = void
-add_option(struct= options *options,
- = char *p[],
- = bool is_inline,
- const char *file,
- int line,
- const int level,
- const int msglevel,
- const unsigned int permission_mask,
- unsigned int *op= tion_types_found,
- = struct env_set *es)
+add_option(struct options *options, char *p[], bool is_inline, const= char *file, int line,
+ = unsigned int *option_types_found, struct env_set *es)
{=
struct gc_arena gc =3D gc_new();
= const bool pull_mode =3D BOOL_CAST(permission_mask & OPT_P_PULL_MODE);=
@@ -6367,7 +6216,8 @@
options= ->config =3D p[1];
}
- read_config_file(optio= ns, p[1], level, file, line, msglevel, permission_mask, option_types_found,= es);
+ read_c= onfig_file(options, p[1], level, file, line, msglevel, permission_mask,
+ = option_types_found, es);
}
#if defi= ned(ENABLE_DEBUG) && !defined(ENABLE_SMALL)
el= se if (streq(p[0], "show-gateway") && !p[2])
@@ -6420,9 +6270,7 @@

* can potentially i= nclude security-sensitive strings */
if (p[1] = && strncmp(p[1], "msg", 3) =3D=3D 0)
= {
- = msg(M_INFO, "%s:%s",
- pull_mode ? "ECHO-PULL" : "= ;ECHO",
- = BSTR(&string));
+ msg(M_INFO, "%s:%s", pull_mode ? "= ;ECHO-PULL" : "ECHO", BSTR(&string));
= }
#ifdef ENABLE_MANAGEMENT
= if (management)
@@ -6537,8 +6385,7 @@
* When no option is present, assume that only PKCS1
* padding is supported
*/=
- if (!(options->ma= nagement_flags
- = &(MF_EXTERNAL_KEY_NOPADDING | MF_EXTERNAL_KEY_PKCS1PAD)))=
+ if (!(options->= management_flags & (MF_EXTERNAL_KEY_NOPADDING | MF_EXTERNAL_KEY_PKCS1PA= D)))
{
options->ma= nagement_flags |=3D MF_EXTERNAL_KEY_PKCS1PAD;
}
@@ -6615,7 +6462,8 @@
else if (streq(p[0= ], "windows-driver") && p[1] && !p[2])
= {
VERIFY_PERMISSION(OPT_P_GENERAL);
- msg(M_WARN, "= ;DEPRECATED OPTION: windows-driver: In OpenVPN 2.7, the default Windows dri= ver is ovpn-dco. "
+ msg(M_WARN,
+ "DEPRECATED OPTION: windows-driver: In OpenVPN 2.7, th= e default Windows driver is ovpn-dco. "
&= quot;If incompatible options are used, OpenVPN will fall back to tap-window= s6. Wintun support has been removed.");
}<= br> #endif
@@ -6650,7 +6498,8 @@
= {
if (!pull_mode)
{
- msg(M_WARN, &q= uot;Note: option tun-ipv6 is ignored because modern operating systems do no= t need special IPv6 tun handling anymore.");
+ msg(M_WARN,
+ "Note: option tun-ip= v6 is ignored because modern operating systems do not need special IPv6 tun= handling anymore.");
}
= }
#ifdef ENABLE_IPROUTE
@@ -6663,7 +6512,8= @@
else if (streq(p[0], "ifconfig") &&a= mp; p[1] && p[2] && !p[3])
{ VERIFY_PERMISSION(OPT_P_UP);
- if (ip_or_dns_addr_safe(p[1], options->al= low_pull_fqdn) && ip_or_dns_addr_safe(p[2], options->allow_pull_= fqdn)) /* FQDN -- may be DNS name */
+ if (ip_or_dns_addr_safe(p[1], options->allow_pu= ll_fqdn)
+ = && ip_or_dns_addr_safe(p[2], options->allow_pull_fqdn)) /* FQDN= -- may be DNS name */
{
= options->ifconfig_local =3D p[1];
optio= ns->ifconfig_remote_netmask =3D p[2];
@@ -6679,12 +6529,= 12 @@
unsigned int netbits;

VERIFY_PERMISSION(OPT_P_UP);
- if (get_ipv6_addr( p[1], NULL, &net= bits, msglevel )
- = && ipv6_addr_safe( p[2] ) )
+ if (get_ipv6_addr(p[1], NULL, &netbits, = msglevel) && ipv6_addr_safe(p[2]))
{
if (netbits < 64 || netbits > 124)
= {
- = msg( msglevel, "ifconfig-ipv6: /netbits must be between= 64 and 124, not '/%d'", netbits );
+ msg(msglevel, "ifconfig-i= pv6: /netbits must be between 64 and 124, not '/%d'",+ netbits)= ;
goto err;
}=

@@ -6712,7 +6562,7 @@
= {
struct local_entry *e;

- VERIFY_PERMISSION(= OPT_P_GENERAL|OPT_P_CONNECTION);
+ VERIFY_PERMISSION(OPT_P_GENERAL | OPT_P_CONNECTION);

e =3D alloc_local_entry(&opti= ons->ce, M_USAGE, &options->gc);
ASSERT(= e);
@@ -6742,7 +6592,7 @@
}
= else if (streq(p[0], "connection") && p[1] &am= p;& !p[3])
{
- VERIFY_PERMISSION(OPT_P_GENERAL|OPT_P_INLINE);
+ VERIFY_PERMISSIO= N(OPT_P_GENERAL | OPT_P_INLINE);
if (is_inline)
{
struct options sub;
@@ -6750,11 +6600,12 @@

= init_options(&sub, true);
sub.c= e =3D options->ce;
-= read_config_string("[CONNECTION-OPTIONS]", &sub, = p[1], msglevel,
- = OPT_P_CONNECTION, option_types_found, es);<= br>+ read_config_str= ing("[CONNECTION-OPTIONS]", &sub, p[1], msglevel, OPT_P_CONNE= CTION,
+ = option_types_found, es);
if = (!sub.ce.remote)
{
- msg(msglevel, "Each 'con= nection' block must contain exactly one 'remote' directive"= ;);
+ = msg(msglevel,
+ = "Each 'connection' block must contain exactly on= e 'remote' directive");
unini= t_options(&sub);
goto err;
<= span> }

@@ -6785,16 +6636,14 @@
}


/* add number of opt= ions already ignored */
- for (i =3D 0; options->ignore_unknown_option
- && options->ign= ore_unknown_option[i]; i++)
+ for (i =3D 0; options->ignore_unknown_option && = options->ignore_unknown_option[i]; i++)
{
numignored++;
}
=
/* Allocate array */
- ALLOC_ARRAY_GC(ignore, const char *= , numignored+1, &options->gc);
- for (i =3D 0; options->ignore_unknown_option
- && o= ptions->ignore_unknown_option[i]; i++)
+ ALLOC_ARRAY_GC(ignore, const char *, numignor= ed + 1, &options->gc);
+ for (i =3D 0; options->ignore_unknown_option &&= ; options->ignore_unknown_option[i]; i++)
{
ignore[i] =3D options->ignore_unknown_option[i= ];
}
@@ -6804,9 +6653,9 @@<= br> for (j =3D 1; p[j]; j++)
{
/* Allow the user to specify ignore-unknown-option = --opt too */
- = if (p[j][0]=3D=3D'-' && p[j][1]=3D=3D'-')=
+ if (p[j][0] = =3D=3D '-' && p[j][1] =3D=3D '-')
= {
- = options->ignore_unknown_option[i] =3D (p[j]+2);
+ options->ignore_u= nknown_option[i] =3D (p[j] + 2);
}
<= span> else

{
@@ -6= 835,7 +6684,7 @@
re.proto =3D -1;
= re.af =3D 0;

- VERIFY_PERMISSION(OPT_P_GENERAL|OPT_P_CONNECTION)= ;
+ VERIFY_PER= MISSION(OPT_P_GENERAL | OPT_P_CONNECTION);
re.remo= te =3D p[1];
if (p[2])
{<= /span>
@@ -6846,9 +6695,7 @@
cons= t sa_family_t af =3D ascii2af(p[3]);
if (p= roto < 0)
{
- msg(msglevel,
- "remote:= bad protocol associated with host %s: '%s'",

- p[1], p[3]);
+ m= sg(msglevel, "remote: bad protocol associated with host %s: '%s= 9;", p[1], p[3]);
goto err;
}
re.proto =3D= proto;
@@ -6894,7 +6741,7 @@
}=
else if (streq(p[0], "connect-retry") && p= [1] && !p[3])
{
- VERIFY_PERMISSION(OPT_P_GENERAL|OPT_P_CONNEC= TION);
+ VERIF= Y_PERMISSION(OPT_P_GENERAL | OPT_P_CONNECTION);
op= tions->ce.connect_retry_seconds =3D positive_atoi(p[1], msglevel);
/*
* Limit the base value of = retry wait interval to 16 bits to avoid
@@ -6913,15 +6760,1= 5 @@
max_int(positive_atoi(p[2], msglevel)= , options->ce.connect_retry_seconds);
}<= br> }
- el= se if ((streq(p[0], "connect-timeout") || streq(p[0], "serve= r-poll-timeout"))
= - && p[1] && !p[2])
+ else if ((streq(p[0], "connect-timeout= ") || streq(p[0], "server-poll-timeout")) && p[1]
+ &&= ; !p[2])
{
- VERIFY_PERMISSION(OPT_P_GENERAL|OPT_P_CONNECTION);=
+ VERIFY_PERMISSION(= OPT_P_GENERAL | OPT_P_CONNECTION);
options->ce.= connect_timeout =3D positive_atoi(p[1], msglevel);
}
else if (streq(p[0], "connect-retry-max") &am= p;& p[1] && !p[2])
{
- VERIFY_PERMISSION(OPT_P_GENERAL|OPT= _P_CONNECTION);
+ = VERIFY_PERMISSION(OPT_P_GENERAL | OPT_P_CONNECTION);
= options->connect_retry_max =3D positive_atoi(p[1], msglevel);
}
else if (streq(p[0], "ipchang= e") && p[1])
@@ -6931,14 +6778,12 @@ {
goto err;
= }
- set_u= ser_script(options,
- = &options->ipchange,
- string_substitute(p[1], = ',', ' ', &options->gc),
- "ipchange", tru= e);
+ set_user= _script(options, &options->ipchange,
+ string_substitute(p[1], = 9;,', ' ', &options->gc), "ipchange", true);
}
else if (streq(p[0], "float= ") && !p[1])
{
- VERIFY_PERMISSION(OPT_P_GENERAL|OPT_P_CO= NNECTION);
+ V= ERIFY_PERMISSION(OPT_P_GENERAL | OPT_P_CONNECTION);
= options->ce.remote_float =3D true;
}
#ifdef ENABLE_DEBUG

@@ -7026,7 +6871,9 @@
{

if (!didit)
= {
- = msg(M_WARN, "WARNING: Multiple --daemon directives specified, ig= noring --daemon %s. (Note that initscripts sometimes add their own --daemon= directive.)", p[1]);
+ msg(M_WARN,
+ "WARNING: Multiple --daemon directi= ves specified, ignoring --daemon %s. (Note that initscripts sometimes add t= heir own --daemon directive.)",
+ p[1]);
= goto err;
}
}
@@ -7088,7 +6935,8 @@
/* Warn when a de= bug verbosity is supplied when built without debug support */
if (options->verbosity >=3D 7)

{=
- msg(M_WAR= N, "NOTE: debug verbosity (--verb %d) is enabled but this build lacks = debug support.",
+ msg(M_WARN,
+ "NOTE: debug verbosity (--verb %d) is enabled bu= t this build lacks debug support.",
o= ptions->verbosity);
}
#endif
@@ -7144,13 +6992,13 @@
}
else if ((streq(p[0], "link-mtu") || streq(p[0], "ud= p-mtu")) && p[1] && !p[2])

{
- VERIFY_PERMISSION(= OPT_P_MTU|OPT_P_CONNECTION);
+ VERIFY_PERMISSION(OPT_P_MTU | OPT_P_CONNECTION); options->ce.link_mtu =3D positive_atoi(p[1], msglevel);<= /span>
options->ce.link_mtu_defined =3D true; }
else if (streq(p[0], "tun-mtu"= ;) && p[1] && !p[3])
{
- VERIFY_PERMISSION(OPT_P_PUSH_= MTU|OPT_P_CONNECTION);

- VERIFY_PERMISSION(OPT_P_MTU|OP= T_P_CONNECTION);
+ = VERIFY_PERMISSION(OPT_P_MTU | OPT_P_CONNECTION);
= int max_mtu =3D positive_atoi(p[1], msglevel);
= if (max_mtu < 68 || max_mtu > 65536)
{
@@ -7177,22 +7025,23 @@
}
= else if (streq(p[0], "tun-mtu-extra") && p[1] &&= amp; !p[2])
{
- VERIFY_PERMISSION(OPT_P_MTU|OPT_P_CONNECTION);<= br>+ VERIFY_PERMISSION(O= PT_P_MTU | OPT_P_CONNECTION);
options->ce.tun_m= tu_extra =3D positive_atoi(p[1], msglevel);
option= s->ce.tun_mtu_extra_defined =3D true;
}
<= span> else if (streq(p[0], "max-packet-size") && p[1]= && !p[2])

{
- VERIFY_PERMISSION(OPT_P_MTU|OPT_P_CONNECTION);<= /span>
+ VERIFY_PERMI= SSION(OPT_P_MTU | OPT_P_CONNECTION);
int maxmtu = =3D positive_atoi(p[1], msglevel);
options->ce.= tls_mtu =3D constrain_int(maxmtu, TLS_CHANNEL_MTU_MIN, TLS_CHANNEL_BUF_SIZE= );

if (maxmtu < TLS_CHANNEL_M= TU_MIN || maxmtu > TLS_CHANNEL_BUF_SIZE)
{
- msg(M_WARN, &q= uot;Note: max-packet-size value outside of allowed "
+ msg(M_WARN,
+ "Note: max-p= acket-size value outside of allowed "

= "control channel packet size (%d to %d), will use %d "- "instead.&= quot;, TLS_CHANNEL_MTU_MIN, TLS_CHANNEL_BUF_SIZE,
- options->ce.tls_mtu);=
+ "inst= ead.",
+ = TLS_CHANNEL_MTU_MIN, TLS_CHANNEL_BUF_SIZE, options->ce.tls_mtu);=
}

/* a= lso set mssfix maxmtu mtu */
@@ -7203,13 +7052,13 @@=
#ifdef ENABLE_FRAGMENT
else if (streq(p[0],= "mtu-dynamic"))
{
- VERIFY_PERMISSION(OPT_P_MTU|OPT_P_CONNE= CTION);
+ VERI= FY_PERMISSION(OPT_P_MTU | OPT_P_CONNECTION);
msg(m= sglevel, "--mtu-dynamic has been replaced by --fragment");=
goto err;
}
el= se if (streq(p[0], "fragment") && p[1] && !p[3])<= /span>
{
= - VERIFY_PERMISSION(OPT_P_MTU|OPT_P_CONNECTION);
+ VERIFY_PERMISSION(OPT_P_MTU | O= PT_P_CONNECTION);
options->ce.fragment =3D posi= tive_atoi(p[1], msglevel);

if (o= ptions->ce.fragment < 68)
@@ -7230,7 +7079,7 @@
#endif /* ifdef ENABLE_FRAGMENT */
else if= (streq(p[0], "mtu-disc") && p[1] && !p[2])
{
- = VERIFY_PERMISSION(OPT_P_MTU|OPT_P_CONNECTION);
+ VERIFY_PERMISSION(OPT_P_MTU | OPT_P_= CONNECTION);
options->ce.mtu_discover_type =3D = translate_mtu_discover_type_name(p[1]);
}
else if (streq(p[0], "mtu-test") && !p[1])
@@ -7301,20 +7150,19 @@
shaper =3D atoi= _warn(p[1], msglevel);
if (shaper < SHAPER_MIN = || shaper > SHAPER_MAX)
{
- msg(msglevel, "Bad shaper = value, must be between %d and %d",
- SHAPER_MIN, SHAPER_MAX);
+ msg(msglevel, "Bad = shaper value, must be between %d and %d", SHAPER_MIN, SHAPER_MAX);
goto err;
}
options->shaper =3D shaper;

} else if (streq(p[0], "port") && p[1] &&a= mp; !p[2])
{
- VERIFY_PERMISSION(OPT_P_GENERAL|OPT_P_CONNECTION);
+ VERIFY_PERMISSIO= N(OPT_P_GENERAL | OPT_P_CONNECTION);
options->c= e.local_port =3D options->ce.remote_port =3D p[1];
= }
else if (streq(p[0], "lport") && p= [1] && !p[2])
{
- VERIFY_PERMISSION(OPT_P_GENERAL|OPT_P_CONNEC= TION);
+ VERIF= Y_PERMISSION(OPT_P_GENERAL | OPT_P_CONNECTION);
/* only trigger bind() if port is not 0 (or --local is used= ) */
if (!streq(p[1], "0"))
@@ -7325,22 +7173,21 @@

}
els= e if (streq(p[0], "rport") && p[1] && !p[2])
{
- = VERIFY_PERMISSION(OPT_P_GENERAL|OPT_P_CONNECTION);
+ VERIFY_PERMISSION(OPT_P_GENERAL= | OPT_P_CONNECTION);
options->ce.remote_port = =3D p[1];
}
else if (streq(p[0], = "bind") && !p[2])
{
- VERIFY_PERMISSION(OPT_P_GENERA= L|OPT_P_CONNECTION);
= + VERIFY_PERMISSION(OPT_P_GENERAL | OPT_P_CONNECTION);
options->ce.bind_defined =3D true;

= if (p[1] && streq(p[1], "ipv6only"))
= {
options->ce.bind_ipv6_only =3D true;=
}
-
}
else if (streq(p[0], &qu= ot;nobind") && !p[1])
{
- VERIFY_PERMISSION(OPT_P_GENERAL= |OPT_P_CONNECTION);
+= VERIFY_PERMISSION(OPT_P_GENERAL | OPT_P_CONNECTION);
options->ce.bind_local =3D false;

}
else if (streq(p[0], "fast-io") && !p[1]= )
@@ -7358,11 +7205,12 @@
opti= ons->inactivity_minimum_bytes =3D (val < 0) ? 0 : val;
if (options->inactivity_minimum_bytes > INT_MAX)
{
- msg(M_WARN, "WARNING: '--inactive' with a = 'bytes' value"
+ msg(M_WARN,
+ "WARNING: '--inactive' wit= h a 'bytes' value"
"= >2 Gbyte was silently ignored in older versions. If "
<= span> " your VPN exits unexpectedly with 'Inac= tivity timeout'"

" in %d= seconds, revisit this value.",
- options->inactivity_timeout );=
+ option= s->inactivity_timeout);
}
= }
}
@@ -7375,14 +7223,12 @@
{
int proto;
= sa_family_t af;
= - VERIFY_PERMISSION(OPT_P_GENERAL|OPT_P_CONNECTION);
+ VERIFY_PERMISSION(OPT_P_GEN= ERAL | OPT_P_CONNECTION);

proto =3D ascii2proto(p[= 1]);
af =3D ascii2af(p[1]);
= if (proto < 0)
{
- msg(msglevel,
- "Bad protocol: '%s= '. Allowed protocols with --proto option: %s",
- p[1],
+ msg(msglevel, "Bad pro= tocol: '%s'. Allowed protocols with --proto option: %s", p[1],=
proto2ascii_all(&gc));
goto err;

}
@@ -740= 5,7 +7251,7 @@
{
struct http_= proxy_options *ho;

- VERIFY_PERMISSION(OPT_P_GENERAL|OPT_P_CONNECTION);
+ VERIFY_PERMIS= SION(OPT_P_GENERAL | OPT_P_CONNECTION);

= {
if (!p[2])
@@ -7451,= 29 +7297,30 @@
else if (streq(p[0], "http-proxy-u= ser-pass") && p[1])
{
= struct http_proxy_options *ho;
- VERIFY_PERMISSION(OPT_P_GENERAL|OPT_P_INLINE);
+ VERIFY_PERMISSION= (OPT_P_GENERAL | OPT_P_INLINE);
ho =3D init_http_p= roxy_options_once(&options->ce.http_proxy_options, &options->= gc);
ho->auth_file_up =3D p[1];
ho->inline_creds =3D is_inline;

}<= br> else if (streq(p[0], "http-proxy-retry") || streq(p= [0], "socks-proxy-retry"))
{
- VERIFY_PERMISSION(OPT_P_GENER= AL|OPT_P_CONNECTION);

+ VERIFY_PERMISSION(OPT_P_GENERAL | OPT_P_CONNECTION);
msg(M_WARN, "DEPRECATED OPTION: http-proxy-retry and sock= s-proxy-retry: "

-= "In OpenVPN 2.4 proxy connection retries are handled like = regular connections. "
- "Use connect-retry-max 1 to get a similar behavior a= s before.");
+ = "In OpenVPN 2.4 proxy connection retries are handled= like regular connections. "
+ "Use connect-retry-max 1 to get a si= milar behavior as before.");
}
= else if (streq(p[0], "http-proxy-timeout") && p[1] &am= p;& !p[2])
{
- VERIFY_PERMISSION(OPT_P_GENERAL|OPT_P_CONNECTION);<= /span>
- msg(M_WARN, &q= uot;DEPRECATED OPTION: http-proxy-timeout: In OpenVPN 2.4 the timeout until= a connection to a "
+ VERIFY_PERMISSION(OPT_P_GENERAL | OPT_P_CONNECTION);+ msg(M_WARN,+ "DEPRECATED= OPTION: http-proxy-timeout: In OpenVPN 2.4 the timeout until a connection = to a "
"server is established is man= aged with a single timeout set by connect-timeout");
= }
else if (streq(p[0], "http-proxy-option&quo= t;) && p[1] && !p[4])
{
struct http_proxy_options *ho;


- VERIFY_PERMISSION(OPT_P_GENER= AL|OPT_P_CONNECTION);

+ VERIFY_PERMISSION(OPT_P_GENERAL | OPT_P_CONNECTION);
ho =3D init_http_proxy_options_once(&options->ce.http_p= roxy_options, &options->gc);


= if (streq(p[1], "VERSION") && p[2] && !p[3])<= /span>
@@ -7503,7 +7350,8 @@
}=
if (!custom_header)
{
- msg(msg= level, "Cannot use more than %d http-proxy-option CUSTOM-HEADER : '= ;%s'", MAX_CUSTOM_HTTP_HEADER, p[1]);
+ msg(msglevel, "Cannot use m= ore than %d http-proxy-option CUSTOM-HEADER : '%s'",+ MAX_CUSTO= M_HTTP_HEADER, p[1]);
}
= else
{
@@ -7520,7 +7368= ,7 @@
}
else if (streq(p[0], &quo= t;socks-proxy") && p[1] && !p[4])
= {
- VERIFY_PERM= ISSION(OPT_P_GENERAL|OPT_P_CONNECTION);
+ VERIFY_PERMISSION(OPT_P_GENERAL | OPT_P_CONNECT= ION);

if (p[2])
= {
@@ -7563,7 +7411,7 @@
}
else if (streq(p[0], "explicit-exit-notify") &a= mp;& !p[2])
{
- VERIFY_PERMISSION(OPT_P_GENERAL|OPT_P_CONNECTION|O= PT_P_EXPLICIT_NOTIFY);
- = "Keys are now always persisted across restarts. ");
+ "= ;Keys are now always persisted across restarts. ");
= }
else if (streq(p[0], "persist-local-ip"= ) && !p[1])
{
@@ -7615,7 +7463= ,8 @@
{
goto err;
}
- add_route_to_option_list(options->routes, p[1], p[2], p[3], p[= 4], options->route_default_table_id);
+ add_route_to_option_list(options->routes, p= [1], p[2], p[3], p[4],
- add_route_ipv6_to_option_list(optio= ns->routes_ipv6, p[1], p[2], p[3], options->route_default_table_id);<= /span>
+ add_route_ip= v6_to_option_list(options->routes_ipv6, p[1], p[2], p[3],
+ = options->route_default_table_id);

}
<= span> else if (streq(p[0], "max-routes") && !p[2])
{
msg(M_WARN, "DEPRECATED = OPTION: --max-routes option ignored. "
- "The number of routes is unlimited a= s of OpenVPN 2.4. "
- "pl= ease remove it from your configuration.");
+ "The number of routes = is unlimited as of OpenVPN 2.4. "
+ "This option will be removed in= a future version, "
+ "please remove it from your configuration.&q= uot;);
}
else if (streq(p[0], &qu= ot;route-gateway") && p[1] && !p[2])
= {
@@ -7642,7 +7492,8 @@
}
else
{
- if (ip_or_dns_addr_safe(p[1], o= ptions->allow_pull_fqdn) || is_special_addr(p[1])) /* FQDN -- may be DNS= name */
+ = if (ip_or_dns_addr_safe(p[1], options->allow_pull_fqdn)
+ || is_special_addr(= p[1])) /* FQDN -- may be DNS name */

{<= br> options->route_default_gateway =3D p[1];
}
@@ -7703,10 +7554,7 @@
= {
goto err;
= }
- set_us= er_script(options,
- = &options->route_predown_script,
- p[1],
<= br>- "= ;route-pre-down", true);
+ set_user_script(options, &options->route_predown_s= cript, p[1], "route-pre-down", true);
}
else if (streq(p[0], "route-noexec") && = !p[1])
{
@@ -7757,11 +7605,10 @@

if (options->routes->flags &= ; RG_ENABLE)
{
- msg(M_WARN,
- "WARNING: You have specified redir= ect-gateway and "
= - "redirect-private at the same time (or the same optio= n "
- = "multiple times). This is not well supported and may lead to "=
- "= ;unexpected results");
+ msg(M_WARN, "WARNING: You have specified redirect-= gateway and "
+ = "redirect-private at the same time (or the same= option "
+ = "multiple times). This is not well supported and ma= y lead to "
+ = "unexpected results");
= }

options->routes->fla= gs |=3D RG_ENABLE;
@@ -7861,8 +7708,7 @@
= unsigned int major, minor, patch;
if (!(ssc= anf(p[1], "%u.%u.%u", &major, &minor, &patch) =3D=3D = 3))
{
- msg(msglevel, "cannot parse version number for --= compat-mode: %s",
= - p[1]);
+ msg(msglevel, "cannot parse version number for --compa= t-mode: %s", p[1]);
goto err;
<= span> }


@@ -7880,14 +7726,13 @@
}
else if (streq(p[0], "mssfi= x") && !p[3])
{
- VERIFY_PERMISSION(OPT_P_GENERAL|OPT_P_C= ONNECTION);
+ = VERIFY_PERMISSION(OPT_P_GENERAL | OPT_P_CONNECTION);
= if (p[1])
{
int ms= sfix =3D positive_atoi(p[1], msglevel);
/* can= be 0, but otherwise it needs to be high enough so we can
= * substract room for headers. */
- if (mssfix !=3D 0
- && (mssfix < TLS= _CHANNEL_MTU_MIN || mssfix > UINT16_MAX))
+ if (mssfix !=3D 0 && (mssfix &= lt; TLS_CHANNEL_MTU_MIN || mssfix > UINT16_MAX))
= {
msg(msglevel, "--mssfix value= '%s' is invalid", p[1]);
got= o err;
@@ -7963,15 +7808,14 @@
uns= igned int netbits =3D 0;

VERIFY_= PERMISSION(OPT_P_GENERAL);
- if (!get_ipv6_addr(p[1], &network, &netbits, lev) )
+ if (!get_ipv6_= addr(p[1], &network, &netbits, lev))
{
msg(msglevel, "error parsing --server-ipv6 p= arameter");
goto err;
= }
if (netbits < 64 || netbits > 124)
{
- msg(msglevel,
- "--server-ipv6 settings: network must be betwe= en /64 and /124 (not /%d)",
+ msg(msglevel, "--server-ipv6 settings: networ= k must be between /64 and /124 (not /%d)",
= netbits);

goto err;
@@ -8076,7 +7920,7 @@
unsigned int n= etbits =3D 0;

VERIFY_PERMISSION(= OPT_P_GENERAL);
- = if (!get_ipv6_addr(p[1], &network, &netbits, lev ) )
+ if (!get_ipv6_addr(p[1],= &network, &netbits, lev))

{
msg(msglevel, "error parsing --ifconfig-ipv6-pool para= meters");

goto err;
@@ -8= 165,7 +8009,8 @@
else if (streq(p[0], "client-cer= t-not-required") && !p[1])
{
VERIFY_PERMISSION(OPT_P_GENERAL);

- msg(M_FATAL, "REMOVED OPTION: --clien= t-cert-not-required, use '--verify-client-cert none' instead")= ;
+ msg(M_FATA= L,
+ "= ;REMOVED OPTION: --client-cert-not-required, use '--verify-client-cert = none' instead");
}
else = if (streq(p[0], "verify-client-cert") && !p[2]) {
@@ -8186,7 +8031,8 @@
= }
else if (!streq(p[1], "require&qu= ot;))
{
- msg(msglevel, "parameter to --verify-cl= ient-cert must be 'none', 'optional' or 'require'&q= uot;);
+ = msg(msglevel,
+ = "parameter to --verify-client-cert must be 'none&= #39;, 'optional' or 'require'");
= goto err;
}
= }
@@ -8205,7 +8051,7 @@
{ VERIFY_PERMISSION(OPT_P_GENERAL);
= msg(M_INFO, "DEPRECATION: opt-verify is deprecated and will be removed= "
- &q= uot;in OpenVPN 2.7");
+ "in OpenVPN 2.7");
= options->ssl_flags |=3D SSLF_OPT_VERIFY;
}
else if (streq(p[0], "auth-user-pass-verify") = && p[1])
@@ -8227,18 +8073,19 @@
= }
else
= {
- msg= (msglevel, "second parm to --auth-user-pass-verify must be 'via-en= v' or 'via-file'");
+ msg(msglevel,
+ "second parm to --auth-= user-pass-verify must be 'via-env' or 'via-file'");
goto err;
}
}
else
= {
- msg(= msglevel, "--auth-user-pass-verify requires a second parameter ('v= ia-env' or 'via-file')");
+ msg(msglevel,
+ "--auth-user-pass-verify = requires a second parameter ('via-env' or 'via-file')"= );
goto err;
}=
- set_user_script(opti= ons,
- = &options->auth_user_pass_verify_script,
- p[1], "auth-us= er-pass-verify", true);
+ set_user_script(options, &options->auth_user_pass_v= erify_script, p[1],
+= "auth-user-pass-verify", true); }
else if (streq(p[0], "auth-gen-toke= n"))
{
@@ -8262,14 +8109,12 @@
msg(msglevel, "Invalid argument to auth= -gen-token: %s (%d)", p[i], i);
}<= br> }
-
}
else if (streq(p[0], "auth-= gen-token-secret") && p[1] && !p[2])
= {
- VERIFY_P= ERMISSION(OPT_P_GENERAL|OPT_P_INLINE);
+ VERIFY_PERMISSION(OPT_P_GENERAL | OPT_P_INLINE);=
options->auth_token_secret_file =3D p[1];
options->auth_token_secret_file_inline =3D is_inlin= e;
-
= }
else if (streq(p[0], "client-connect") = && p[1])
{
@@ -8278,8 +8123,7 = @@
{
goto err;=
}
- = set_user_script(options, &options->client_connect_script,
- p= [1], "client-connect", true);
+ set_user_script(options, &options->clien= t_connect_script, p[1], "client-connect", true);
= }
else if (streq(p[0], "client-crresponse&qu= ot;) && p[1])
{
@@ -8288,8 +81= 32,8 @@
{
goto err;
}
- set_user_script(options, &options->client_crresponse_scr= ipt,
- = p[1], "client-crresponse", true);
+ set_user_script(options, &option= s->client_crresponse_script, p[1], "client-crresponse",=
+ tr= ue);
}
else if (streq(p[0], "= ;client-disconnect") && p[1])
{@@ -8298,8 +8142,8 @@
{
= goto err;
}
- set_user_script(options, &options->= client_disconnect_script,
- p[1], "client-disconnect", true);
+ set_user_script= (options, &options->client_disconnect_script, p[1], "client-dis= connect",
+ = true);
}
else = if (streq(p[0], "learn-address") && p[1])
{

@@ -8308,8 +8152,7 @@
{
goto err;
}
<= span style=3D"color: hsl(0, 100%, 40%);">- set_user_script(options, = &options->learn_address_script,

- p[1], "learn-address", t= rue);
+ set_us= er_script(options, &options->learn_address_script, p[1], "learn= -address", true);
}
else if = (streq(p[0], "tmp-dir") && p[1] && !p[2])<= br> {
@@ -8384,8 +8227,8 @@
= in_addr_t local, remote_netmask;

= VERIFY_PERMISSION(OPT_P_INSTANCE);
- local =3D getaddr(GETADDR_HOST_ORDER|GETADDR_RESO= LVE, p[1], 0, NULL, NULL);
- remote_netmask =3D getaddr(GETADDR_HOST_ORDER|GETADDR_RESOLVE,= p[2], 0, NULL, NULL);
+ = remote_netmask =3D getaddr(GETADDR_HOST_ORDER | GETADDR_RESOLVE, p[2], 0,= NULL, NULL);
if (local && remote_netmask)=
{
options->push_i= fconfig_defined =3D true;
@@ -8393,7 +8236,8 @@
<= span> options->push_ifconfig_remote_netmask =3D remote_netma= sk;

if (p[3])
{
- options= ->push_ifconfig_local_alias =3D getaddr(GETADDR_HOST_ORDER|GETADDR_RESOL= VE, p[3], 0, NULL, NULL);
+ options->push_ifconfig_local_alias =3D
<= span style=3D"color: hsl(120, 100%, 40%);">+ getaddr(GET= ADDR_HOST_ORDER | GETADDR_RESOLVE, p[3], 0, NULL, NULL);

= }
}
else
@@ -8407,7 +8251,7 @@
in_addr_t network= , netmask;

VERIFY_PERMISSION(OPT= _P_GENERAL);
- n= etwork =3D getaddr(GETADDR_HOST_ORDER|GETADDR_RESOLVE, p[1], 0, NULL, NULL)= ;
+ network = =3D getaddr(GETADDR_HOST_ORDER | GETADDR_RESOLVE, p[1], 0, NULL, NULL);
netmask =3D getaddr(GETADDR_HOST_ORDER, p[2], 0, NULL= , NULL);
if (network && netmask) {
@@ -8428,7 +8272,7 @@

VERIFY_PERMISSION(OPT_P_INSTANCE);
=
- if (!get_ipv= 6_addr( p[1], &local, &netbits, msglevel ) )
+ if (!get_ipv6_addr(p[1], &loc= al, &netbits, msglevel))
{
= msg(msglevel, "cannot parse --ifconfig-ipv6-push addresses&q= uot;);
goto err;
@@ -8436,19 += 8280,19 @@

if (p[2])
<= span> {

- = if (!get_ipv6_addr( p[2], &remote, NULL, msglevel ) )
<= span style=3D"color: hsl(120, 100%, 40%);">+ if (!get_ipv6_addr(= p[2], &remote, NULL, msglevel))

{- msg( msglevel,= "cannot parse --ifconfig-ipv6-push addresses");
+ msg(msglevel, "= cannot parse --ifconfig-ipv6-push addresses");
= goto err;
}
= }
else
{
if (!options->ifconfig_ipv6_local

- || !get_ipv6_addr( options->= ;ifconfig_ipv6_local, &remote,
- NULL, msglevel ) )+ || !get_ipv6= _addr(options->ifconfig_ipv6_local, &remote, NULL, msglevel))=
{
+ msg(msglevel,
+ &q= uot;second argument to --ifconfig-ipv6-push missing and no global --ifconfi= g-ipv6 address set");
goto err;
}
}
@@ -84= 69,8 +8313,10 @@
VERIFY_PERMISSION(OPT_P_INSTANCE)= ;
if (strlen(p[1]) > USER_PASS_LEN)
<= span> {

- = msg(msglevel, "override-username exceeds the maximum length of %= d "
- = "characters", USER_PASS_LEN);
+ msg(msglevel,
+ "override-username exceed= s the maximum length of %d "
+ "characters",
+ USER_PASS_LEN);
/* disable the connection since ignor= ing the request to
* set another username mig= ht cause serious problems */
@@ -8506,7 +8352,7 @@ msg(msglevel, "--stale-routes-check aging time an= d check interval must be >=3D 1");
got= o err;
}
- options->stale_routes_ageing_time =3D ageing_time;<= /span>
+ options->= stale_routes_ageing_time =3D ageing_time;
options-= >stale_routes_check_interval =3D check_interval;
}<= /span>

@@ -8527,7 +8373,7 @@
= }
else if (streq(p[0], "auth-user-pass") &= amp;& !p[2])
{
- VERIFY_PERMISSION(OPT_P_GENERAL|OPT_P_INLINE);
+ VERIFY_PERMISS= ION(OPT_P_GENERAL | OPT_P_INLINE);
if (p[1])
{
options->auth_user_pa= ss_file =3D p[1];
@@ -8568,15 +8414,15 @@
= #ifdef _WIN32
VERIFY_PERMISSION(OPT_P_GENERAL);
HANDLE process =3D GetCurrentProcess();
- HANDLE handle =3D (HANDLE)= ((intptr_t) atoll(p[1]));

- if (!DuplicateHandle(process, handle, process, &options-&g= t;msg_channel, 0,
- = FALSE, DUPLICATE_CLOSE_SOURCE | DUPLICATE_SAME_ACC= ESS))
+ HANDLE= handle =3D (HANDLE)((intptr_t)atoll(p[1]));
+ if (!DuplicateHandle(process, handle, proc= ess, &options->msg_channel, 0, FALSE,
+ DUPLICATE_CLOSE_SOURC= E | DUPLICATE_SAME_ACCESS))
{
= msg(msglevel, "could not duplicate service pipe handle")= ;
goto err;
}<= br> options->route_method =3D ROUTE_METHOD_SERVICE;=
-#else /* ifdef _WIN32 */
+#else /* ifdef _WIN32 = */
msg(msglevel, "--msg-channel is only suppo= rted on Windows");
goto err;
= #endif
@@ -8588,8 +8434,8 @@
if (= streq(p[1], "env"))
{
= msg(M_INFO, "NOTE: --win-sys env is default from OpenVPN 2.= 3. "
- = "This entry will now be ignored. "
- "Please remove this entry= from your configuration file.");
+ "This entry will now be ign= ored. "
+ = "Please remove this entry from your configuration fi= le.");
}
else=
{
@@ -8626,9 +8472,7 @@
=
if (index < 0)
{
- msg(msglevel,=
- "= ;Bad --ip-win32 method: '%s'. Allowed methods: %s",- p[1],+ msg(msglevel, &qu= ot;Bad --ip-win32 method: '%s'. Allowed methods: %s", p[1],
ipset2ascii_all(&gc));
= goto err;
}
@@ -8648,= 7 +8492,9 @@

if (!(o= ffset > -256 && offset < 256))
= {
- = msg(msglevel, "--ip-win32 dynamic [offset] [lease-time]: of= fset (%d) must be > -256 and < 256", offset);
+ msg(msglevel,<= /span>
+ = "--ip-win32 dynamic [offset] [lease-time]: offset (%d) must be= > -256 and < 256",
+ offset);
= goto err;
}

@@ -8663,7 +8509,9 @@
= lease_time =3D atoi_warn(p[3], msglevel);
= if (lease_time < min_lease)
= {
- = msg(msglevel, "--ip-win32 dynamic [offset] [lease-time]: lease = time parameter (%d) must be at least %d seconds", lease_time, min_leas= e);
+ = msg(msglevel,
+ "--ip-win32 dynamic [offset] [lease-time= ]: lease time parameter (%d) must be at least %d seconds",
<= span style=3D"color: hsl(120, 100%, 40%);">+ lea= se_time, min_lease);

goto err;
}
to= ->dhcp_lease_time =3D lease_time;
@@ -8803,10 +8651,11 @= @
#endif
else
= {
- ms= g(msglevel, "--dhcp-option: unknown option type '%s' or missin= g or unknown parameter", p[1]);
+ msg(msglevel, "--dhcp-option: unknown opt= ion type '%s' or missing or unknown parameter",
+ p[1]);

<= span> goto err;

}
-#else /* if defined(_WIN32) || defined(TAR= GET_ANDROID) */
+#els= e /* if defined(_WIN32) || defined(TARGET_ANDROID) */
= setenv_foreign_option(options, p[1], p[2], es);
#endi= f /* if defined(_WIN32) || defined(TARGET_ANDROID) */

@@ -8821,14 +8670,14 @@
else if (streq(p[= 0], "show-adapters") && !p[1])
{
VERIFY_PERMISSION(OPT_P_GENERAL);
- show_tap_win_adapters(M_INFO|M_NO= PREFIX, M_WARN|M_NOPREFIX);
+ show_tap_win_adapters(M_INFO | M_NOPREFIX, M_WARN | M_NOPRE= FIX);
openvpn_exit(OPENVPN_EXIT_STATUS_GOOD); /* e= xit point */
}
else if (streq(p[0= ], "show-net") && !p[1])
{ VERIFY_PERMISSION(OPT_P_GENERAL);
- show_routes(M_INFO|M_NOPREFIX);<= br>- show_adapters(M_INFO|= M_NOPREFIX);
+ = show_routes(M_INFO | M_NOPREFIX);
+ show_adapters(M_INFO | M_NOPREFIX);
= openvpn_exit(OPENVPN_EXIT_STATUS_GOOD); /* exit point */ }
else if (streq(p[0], "show-net-up&q= uot;) && !p[1])
@@ -8977,19 +8826,20 @@
<= span>

if (streq(p[1], "no"))
= {
- = options->comp.flags =3D
- COMP_F_ALLOW_STUB_ONLY|COMP_F_ADVERTISE_STUBS_O= NLY;
+ opt= ions->comp.flags =3D COMP_F_ALLOW_STUB_ONLY | COMP_F_ADVERTISE_STUBS_ONL= Y;
if (comp_non_stub_enabled(&options->= comp))
{
msg(= msglevel, "'--allow-compression no' conflicts with "
- "= enabling compression");
+ " enabling compression");=
}
}
= else if (options->comp.flags & COMP_F_ALLOW_STUB_ONLY)
{
/* Also printed on a pu= sh to hint at configuration problems */
- msg(msglevel, "Cannot set allow-compress= ion to '%s' "
- "after set to 'no'", p[1]);+ msg(msglevel,
+ "= Cannot set allow-compression to '%s' "
+ "after set to 'n= o'",
+ = p[1]);
goto err;
= }
else if (streq(p[1], "asym"))
@@ -8998,15 +8848,18 @@
}
= else if (streq(p[1], "yes"))
= {
- msg(= M_WARN, "DEPRECATED OPTION: \"--allow-compression yes\" has = been removed. "
= + msg(M_WARN,
+ "DEPRECATED OPTION: \"--allow-compression ye= s\" has been removed. "
"We= will use \"asym\" mode instead. See the manual page for more inf= ormation.");

options-&g= t;comp.flags |=3D COMP_F_ALLOW_ASYM;
}
<= span> else

{
- msg(msglevel, "bad allow-compressi= on option: %s -- "
- "must be 'yes', 'no', or 'asym&#= 39;", p[1]);
+ = msg(msglevel,
+ "bad allow-compression option: %s -- "=
+ "must= be 'yes', 'no', or 'asym'",
+ p[1]);
goto err;

}
}<= /span>
@@ -9030,7 +8883,8 @@
*/
else if (!(streq(p[1], "yes") || streq(p= [1], "adaptive")))
{
- msg(msglevel, "b= ad comp-lzo option: %s -- must be 'yes', 'no', or 'adap= tive'", p[1]);

+ msg(msglevel, "bad comp-lzo option: %s -- must be = 'yes', 'no', or 'adaptive'",
+ p[1]);
= goto err;
}
<= span> }

@@ -9052,7 +8906,7 @@
= if (streq(alg, "stub"))
{
= options->comp.alg =3D COMP_ALG_STUB;
- options->comp.flags |= =3D (COMP_F_SWAP|COMP_F_ADVERTISE_STUBS_ONLY);
+ options->comp.flags |=3D (COMP_F_= SWAP | COMP_F_ADVERTISE_STUBS_ONLY);
}
<= span> else if (streq(alg, "stub-v2"))

= {
@@ -9105,7 +8959,7 @@
{=
int key_direction;

- VERIFY_PERMISSION(OPT_P_GENERAL|O= PT_P_CONNECTION);
+ = VERIFY_PERMISSION(OPT_P_GENERAL | OPT_P_CONNECTION);
=
key_direction =3D ascii2keydirection(msglevel, p= [1]);
if (key_direction >=3D 0)
@@ -9127,7 +8981,7 @@

else if (streq(p[0], "secr= et") && p[1] && !p[3])
{ msg(M_WARN, "DEPRECATED OPTION: The option --secret i= s deprecated.");
-= VERIFY_PERMISSION(OPT_P_GENERAL|OPT_P_INLINE);
+ VERIFY_PERMISSION(OPT_P_GENERAL = | OPT_P_INLINE);
options->shared_secret_file = =3D p[1];
options->shared_secret_file_inline = =3D is_inline;
if (!is_inline && p[2])
@@ -9149,7 +9003,6 @@
{
= VERIFY_PERMISSION(OPT_P_GENERAL);
options-= >allow_deprecated_insecure_static_crypto =3D true;
-
}
= else if (streq(p[0], "genkey") && !p[4])
{

@@ -9161,8 +9014,7 @@
}
else
{
- if (streq(p[1], "secret&= quot;) || streq(p[1], "tls-auth")
- || streq(p[1], "tls-crypt")= )
+ if (st= req(p[1], "secret") || streq(p[1], "tls-auth") || streq= (p[1], "tls-crypt"))
{
options->genkey_type =3D GENKEY_SECRET;

}

@@ -9186,7 +9038,6 @@
= {
msg(msglevel, "unknown -= -genkey type: %s", p[1]);
}
-

}<= br> if (p[2])
{
@@ -= 9200,23 +9051,22 @@
}
else if (st= req(p[0], "cipher") && p[1] && !p[2])
<= span> {

- VE= RIFY_PERMISSION(OPT_P_NCP|OPT_P_INSTANCE);
+ VERIFY_PERMISSION(OPT_P_NCP | OPT_P_INSTANCE= );
options->ciphername =3D p[1];
}

else if (streq(p[0], "data-ciphers-fallb= ack") && p[1] && !p[2])
{<= br>- VERIFY_PERMISSION(OPT= _P_GENERAL|OPT_P_INSTANCE);
+ VERIFY_PERMISSION(OPT_P_GENERAL | OPT_P_INSTANCE); options->ciphername =3D p[1];
= options->enable_ncp_fallback =3D true;
}
= - else if ((streq(p[0], "= data-ciphers") || streq(p[0], "ncp-ciphers"))
- && p[1] &&a= mp; !p[2])

+ else = if ((streq(p[0], "data-ciphers") || streq(p[0], "ncp-ciphers= ")) && p[1] && !p[2])
{- VERIFY_PERMISSION(OPT_P= _GENERAL|OPT_P_INSTANCE);
+ VERIFY_PERMISSION(OPT_P_GENERAL | OPT_P_INSTANCE);
= if (streq(p[0], "ncp-ciphers"))
= {
msg(M_INFO, "Note: Treating opti= on '--ncp-ciphers' as "
- " '--data-ciphers' (renamed in = OpenVPN 2.5).");
+ " '--data-ciphers' (renamed in OpenV= PN 2.5).");
}
option= s->ncp_ciphers =3D p[1];
}
@@ -9278= ,7 +9128,7 @@
VERIFY_PERMISSION(OPT_P_GENERAL);
/* always error out, this breaks the connection */
msg(M_FATAL, "--no-replay was removed in OpenV= PN 2.7. "
- = "Update your configuration.");
+ "Update your configurat= ion.");
}
else if (streq(p[0= ], "replay-window") && !p[3])
{
@@ -9291,9 +9141,7 @@
if (!(MIN_SE= Q_BACKTRACK <=3D replay_window && replay_window <=3D MAX_SEQ_= BACKTRACK))
{
= msg(msglevel, "replay-window window size parameter (%d) must be betwe= en %d and %d",
- = replay_window,
- MIN_SEQ_BACKTRACK,
- MAX_SEQ_BACKTRACK);<= br>+ replay_= window, MIN_SEQ_BACKTRACK, MAX_SEQ_BACKTRACK);
= goto err;
}
= options->replay_window =3D replay_window;
@@ -9305,10 +9= 153,9 @@
replay_time =3D atoi_warn(p[2], m= sglevel);
if (!(MIN_TIME_BACKTRACK <=3D= replay_time && replay_time <=3D MAX_TIME_BACKTRACK))
= {
- replay_time,
- MIN_TIME_BACKTRA= CK,
- = MAX_TIME_BACKTRACK);
+ msg(msglevel,
+ "replay-window time windo= w parameter (%d) must be between %d and %d",
+ replay_time, MIN_TIME= _BACKTRACK, MAX_TIME_BACKTRACK);
goto = err;
}
op= tions->replay_time =3D replay_time;
@@ -9377,8 +9224,8 @= @
{
VERIFY_PERMISSION(OPT_P_G= ENERAL);
msg(M_WARN, "Consider setting groups= /curves preference with "
- "tls-groups instead of forcing a specific curve w= ith "
- = "ecdh-curve.");
+ "tls-groups instead of forcing a specific c= urve with "
+ = "ecdh-curve.");
options= ->ecdh_curve =3D p[1];
}
else = if (streq(p[0], "tls-server") && !p[1])
@= @ -9393,7 +9240,7 @@
}
else if (s= treq(p[0], "ca") && p[1] && !p[2])
{

- VERIF= Y_PERMISSION(OPT_P_GENERAL|OPT_P_INLINE);
+ VERIFY_PERMISSION(OPT_P_GENERAL | OPT_P_INLIN= E);
options->ca_file =3D p[1];
= options->ca_file_inline =3D is_inline;
}
@@ -9406,33 +9253,33 @@
#endif /* ENABLE_CR= YPTO_MBEDTLS */
else if (streq(p[0], "dh") &= amp;& p[1] && !p[2])
{
- VERIFY_PERMISSION(OPT_P_GENERAL|O= PT_P_INLINE);
+ = VERIFY_PERMISSION(OPT_P_GENERAL | OPT_P_INLINE);
= options->dh_file =3D p[1];
options->dh_file= _inline =3D is_inline;
}
else if = (streq(p[0], "cert") && p[1] && !p[2])
= {
- V= ERIFY_PERMISSION(OPT_P_GENERAL|OPT_P_INLINE);
+ VERIFY_PERMISSION(OPT_P_GENERAL | OPT_P_I= NLINE);
options->cert_file =3D p[1];
= options->cert_file_inline =3D is_inline;
= }
else if (streq(p[0], "extra-certs") &= amp;& p[1] && !p[2])
{
- VERIFY_PERMISSION(OPT_P_GENERAL|O= PT_P_INLINE);
+ = VERIFY_PERMISSION(OPT_P_GENERAL | OPT_P_INLINE);
= options->extra_certs_file =3D p[1];
options-&g= t;extra_certs_file_inline =3D is_inline;
}
<= span> else if ((streq(p[0], "verify-hash") && p[1] &a= mp;& !p[3])

|| (streq(p[0], "peer-fi= ngerprint") && p[1] && !p[2]))
{<= /span>
- VERIFY_PERMISS= ION(OPT_P_GENERAL|OPT_P_INLINE);
+ VERIFY_PERMISSION(OPT_P_GENERAL | OPT_P_INLINE);

int verify_hash_depth =3D 0; if (streq(p[0], "verify-hash"))
= {
msg(M_WARN, "DEPRECATED OPTION= : The option --verify-hash is deprecated. "
- "You should switch to the e= ither use the level 1 certificate as "
- "--ca option, use --tls-verify o= r use --peer-fingerprint");
+ "You should switch to the either = use the level 1 certificate as "
+ "--ca option, use --tls-veri= fy or use --peer-fingerprint");
/* verify= level 1 cert, i.e. the CA that signed the leaf cert */
= verify_hash_depth =3D 1;
}
@@ -9443,8 +9290,10 @@


if (op= tions->verify_hash && options->verify_hash_depth !=3D verify_= hash_depth)
{
- msg(msglevel, "ERROR: Setting %s not allo= wed. --verify-hash and"
- " --peer-fingerprint are mutually exclusive&quo= t;, p[0]);
+ = msg(msglevel,
+ = "ERROR: Setting %s not allowed. --verify-hash and"
+ "= ; --peer-fingerprint are mutually exclusive",
+ p[0]);
= goto err;
}

@@ -9457,15 +9306,16 @@

}
= else if (p[2] && !streq(p[2], "SHA256"))
{
- msg(msglevel, "invalid or unsupported hashing al= gorithm: %s "
- = "(only SHA1 and SHA256 are supported)", p[2]);
+ msg(m= sglevel,
+ = "invalid or unsupported hashing algorithm: %s "+ "(o= nly SHA1 and SHA256 are supported)",
+ p[2]);
= goto err;
}
}<= /span>

struct verify_hash_list *newlist= ;
- newlist =3D = parse_hash_fingerprint_multiline(p[1], digest_len,
- = msglevel, &options->gc);
+ newlist =3D parse_hash_fingerprint_multiline(p[1],= digest_len, msglevel, &options->gc);

/* Append the new list to the end of our current list */
if (!options->verify_hash)
@@ -9494,= 7 +9344,7 @@
#endif
else if (streq(p[= 0], "key") && p[1] && !p[2])
= {
- VERIFY_PERM= ISSION(OPT_P_GENERAL|OPT_P_INLINE);
+ VERIFY_PERMISSION(OPT_P_GENERAL | OPT_P_INLINE);

options->priv_key_file =3D p[1];
= options->priv_key_file_inline =3D is_inline;
= }
@@ -9517,8 +9367,7 @@
}
#endif

- options->ssl_flags &=3D
- ~(SSLF_TLS_VERSION_MIN_MASK <= ;< SSLF_TLS_VERSION_MIN_SHIFT);
+ options->ssl_flags &=3D ~(SSLF_TLS_VERSION_MI= N_MASK << SSLF_TLS_VERSION_MIN_SHIFT);
optio= ns->ssl_flags |=3D (ver << SSLF_TLS_VERSION_MIN_SHIFT);
= }
else if (streq(p[0], "tls-version-ma= x") && p[1] && !p[2])
@@ -9531,14 +938= 0,13 @@
msg(msglevel, "unknown tls-versio= n-max parameter: %s", p[1]);
goto err;
}
- ~(SSLF_TLS_VERSION_MAX_MASK << SSLF_T= LS_VERSION_MAX_SHIFT);
- = VERIFY_PERMISSION(OPT_P_GENERAL|OPT_P_INLINE);
+ VERIFY_PERMISSION(OPT_P_GENERAL | OPT= _P_INLINE);
options->pkcs12_file =3D p[1];
options->pkcs12_file_inline =3D is_inline; }
@@ -9611,10 +9459,9 @@
= VERIFY_PERMISSION(OPT_P_GENERAL);
options->= tls_groups =3D p[1];
}
- else if (streq(p[0], "crl-verify") &= ;& p[1] && ((p[2] && streq(p[2], "dir"))
- = || !p[2]))
+ else if (streq(p[0], "crl-verify") &&= p[1] && ((p[2] && streq(p[2], "dir")) || !p[2]))=
{
- VERIFY_PERMISSION(OPT_P_GENERAL|OPT_P_INLINE);
+ VERIFY_PERMISSION(OPT_P_GENERA= L | OPT_P_INLINE);
if (p[2] && streq(p[2],= "dir"))
{
= options->ssl_flags |=3D SSLF_CRL_VERIFY_DIR;
@@ -9630,8 = +9477,7 @@
goto err;
= }
set_user_script(options, &options->tls_ve= rify,
- = string_substitute(p[1], ',', ' ', &options->= gc),
- = "tls-verify", true);
+ string_substitute(p[1], ',= 9;, ' ', &options->gc), "tls-verify", true);
}
else if (streq(p[0], "tls-expor= t-cert") && p[1] && !p[2])
{
@@ -9642,14 +9488,14 @@
{
= VERIFY_PERMISSION(OPT_P_GENERAL);
msg(msg= level, "--compat-names was removed in OpenVPN 2.5. "
- "Update your conf= iguration.");

+ = "Update your configuration.");
goto err;

}
else if (= streq(p[0], "no-name-remapping") && !p[1])
{

VERIFY_PERMISSION(OPT_P_GENERAL);<= br> msg(msglevel, "--no-name-remapping was removed in Op= enVPN 2.5. "
- = "Update your configuration.");
+ "Update your config= uration.");
goto err;
}<= /span>
else if (streq(p[0], "verify-x509-name") &am= p;& p[1] && strlen(p[1]) && !p[3])
@@ -= 9708,7 +9554,7 @@
size_t j;
= for (j =3D 1; j < MAX_PARMS && p[j] !=3D NULL; ++j) {
- = sscanf(p[j], "%x", &(options->remote_cert_ku[j-1])= );
+ sscan= f(p[j], "%x", &(options->remote_cert_ku[j - 1])); }
if (j =3D=3D 1)
{

@@ -9793,7 +9639,7 @@
{
int key_direction =3D -1;
- VERIFY_PERMISSION(OPT_= P_GENERAL|OPT_P_CONNECTION|OPT_P_INLINE);
+ VERIFY_PERMISSION(OPT_P_GENERAL | OPT_P_CONNE= CTION | OPT_P_INLINE);

if (permi= ssion_mask & OPT_P_GENERAL)
{
= @@ -9809,7 +9655,6 @@
}
= options->key_direction =3D key_direction;
}

-
}
else if (permission_mask &am= p; OPT_P_CONNECTION)
{
@@ -9830,7 = +9675,7 @@
}
else if (streq(p[0],= "tls-crypt") && p[1] && !p[3])
= {
- VERIFY_P= ERMISSION(OPT_P_GENERAL|OPT_P_CONNECTION|OPT_P_INLINE);
+ VERIFY_PERMISSION(OPT_P_GENERAL= | OPT_P_CONNECTION | OPT_P_INLINE);
if (permissio= n_mask & OPT_P_GENERAL)
{
= options->tls_crypt_file =3D p[1];
@@ -9844,7 +9= 689,7 @@
}
else if (streq(p[0], &= quot;tls-crypt-v2") && p[1] && !p[3])
= {
- VERIFY_= PERMISSION(OPT_P_GENERAL|OPT_P_CONNECTION|OPT_P_INLINE);
+ VERIFY_PERMISSION(OPT_P_GENERA= L | OPT_P_CONNECTION | OPT_P_INLINE);
if (permissi= on_mask & OPT_P_GENERAL)
{
= options->tls_crypt_v2_file =3D p[1];
@@ -9887,= 19 +9732,19 @@
{
char= *s =3D p[j];

- if (strncmp("ext:", s, 4) =3D=3D 0 &&am= p; !x509_username_field_ext_supported(s+4))
+ if (strncmp("ext:", s, 4) =3D= =3D 0 && !x509_username_field_ext_supported(s + 4))
{

msg(msglevel, "Unsupp= orted x509-username-field extension: %s", s);
= }
- opt= ions->x509_username_field[j-1] =3D p[j];
+ options->x509_username_field[j - 1] = =3D p[j];
}
}
#endif /* ENABLE_X509ALTUSERNAME */

#ifdef ENABLE_PKCS11=
else if (streq(p[0], "show-pkcs11-ids") &am= p;& !p[3])
{
- char *provider =3D p[1];
- bool cert_private =3D (p[2] =3D=3D NULL= ? false : (atoi_warn(p[2], msglevel) !=3D 0 ));
+ char *provider =3D p[1];
+ bool cert_private =3D (p[= 2] =3D=3D NULL ? false : (atoi_warn(p[2], msglevel) !=3D 0));


#ifdef DEFAULT_PKCS11_MODULE
= if (!provider)
@@ -9940,7 +9785,7 @@

for (j =3D 1; j < MAX_PARMS && p[j] !=3D N= ULL; ++j)
{
- options->pkcs11_providers[j-1] =3D p[j];
+ options->= pkcs11_providers[j - 1] =3D p[j];
}
}

else if (streq(p[0], "pkcs11-protected-a= uthentication"))
@@ -9951,7 +9796,8 @@

for (j =3D 1; j < MAX_PARMS && p[j] = !=3D NULL; ++j)
{
- options->pkcs11_protected_authenticatio= n[j-1] =3D atoi_warn(p[j], msglevel) !=3D 0 ? 1 : 0;
+ options->pkcs11_protected_= authentication[j - 1] =3D
+ atoi_warn(p[j], msglevel) !=3D 0 ? 1 : 0;
<= span> }

}
else if (streq(= p[0], "pkcs11-private-mode") && p[1])
@@ = -9962,7 +9808,7 @@

for (j =3D 1;= j < MAX_PARMS && p[j] !=3D NULL; ++j)
= {
- sscanf(p= [j], "%x", &(options->pkcs11_private_mode[j-1]));+ sscanf(p[j], &qu= ot;%x", &(options->pkcs11_private_mode[j - 1]));
}

}
else if (streq(p[0= ], "pkcs11-cert-private"))
@@ -9973,7 +9819,7 @@<= /span>

for (j =3D 1; j < MAX_PARMS &= amp;& p[j] !=3D NULL; ++j)
{
- options->pkcs11_cert_pri= vate[j-1] =3D (bool) (atoi_warn(p[j], msglevel));
+ options->pkcs11_cert_private[j= - 1] =3D (bool)(atoi_warn(p[j], msglevel));
}
}
else if (streq(p[0], "pkcs11-= pin-cache") && p[1] && !p[2])
@@ -1001= 9,13 +9865,13 @@
if (strncmp(p[1], "EXPORTER&= quot;, 8))
{
msg(msgl= evel, "Keying material exporter label must begin with "- "\"EX= PORTER\"");
+ "\"EXPORTER\"");
= goto err;
}
= if (streq(p[1], EXPORT_KEY_DATA_LABEL))
{
- msg(msglevel= , "Keying material exporter label must not be '"
- EXPORT_KEY_DATA_LA= BEL "'.");

+ msg(msglevel,
+ "Keying material exporter label must not be= '" EXPORT_KEY_DATA_LABEL "'.");
= }
if (ekm_length < 16 || ekm_length > = 4095)
{
@@ -10069,13 +9915,12 @@
}
else if (streq(p[0], "vlan-= pvid") && p[1] && !p[2])
{=
- VERIFY_PERMISSION(OP= T_P_GENERAL|OPT_P_INSTANCE);
+ VERIFY_PERMISSION(OPT_P_GENERAL | OPT_P_INSTANCE);<= br> options->vlan_pvid =3D positive_atoi(p[1], msglevel);<= /span>
if (options->vlan_pvid < OPENVPN_8021Q_MIN_V= ID
|| options->vlan_pvid > OPENVPN_8021Q= _MAX_VID)
{
- msg(msglevel,
- "the parameter of --vlan-pvid param= eters must be >=3D %u and <=3D %u",
+ msg(msglevel, "the parameter of= --vlan-pvid parameters must be >=3D %u and <=3D %u",
= OPENVPN_8021Q_MIN_VID, OPENVPN_8021Q_MAX_VID);
goto err;
}
@@ -10096,11 +9941,14 @@

}
= if (file)
{
- msg(msglevel_unknown, "Unrecognized opt= ion or missing or extra parameter(s) in %s:%d: %s (%s)", file, line, p= [0], PACKAGE_VERSION);
+ "Unrecognized option or missing or ex= tra parameter(s) in %s:%d: %s (%s)", file,
+ line, p[0], PACKAGE_VERSION);
}
else
= {
- ms= g(msglevel_unknown, "Unrecognized option or missing or extra parameter= (s): --%s (%s)", p[0], PACKAGE_VERSION);
+ msg(msglevel_unknown, "Unrecogni= zed option or missing or extra parameter(s): --%s (%s)",
+ p[0], PACKAGE_VER= SION);

}
}
e= rr:
diff --git a/src/openvpn/options.h b/src/openvpn/option= s.h
index dbd50f0..51468dd 100644
--- a/src= /openvpn/options.h
+++ b/src/openvpn/options.h
@@ -121,33 +121,34 @@

const char *socks_proxy_port= ;
const char *socks_proxy_authfile;
<= /span>
- int tun_mtu; = /* MTU of tun device */
- int occ_mtu; /* if non-null, this is the MTU we announce t= o peers in OCC */
- = int tun_mtu_max; /* maximum MTU that can be pushed */
+ int tun_mtu; /* MTU of t= un device */
+ int= occ_mtu; /* if non-null, this is the MTU we announce to peers in = OCC */
+ int tun_m= tu_max; /* maximum MTU that can be pushed */
<= br> bool tun_mtu_defined; /* true if user overriding parm with co= mmand line option */
int tun_mtu_extra;
bool tun_mtu_extra_defined;

- int link_mtu; /* MTU of device over which tunnel pa= ckets pass via TCP/UDP */
+ int link_mtu; /* MTU of device over which tunnel packets= pass via TCP/UDP */
bool link_mtu_defined; /* true if= user overriding parm with command line option */
- int tls_mtu; /* Maximum MTU for the= control channel messages */
+ int tls_mtu; /* Maximum MTU for the control channel = messages */

/* Advanced MTU negotiat= ion and datagram fragmentation options */
int mtu_disc= over_type; /* used if OS supports setting Path MTU discovery options on soc= ket */

- bool fragment_encap; /* true if= --fragment had the "mtu" parameter to
- * include overhead fro= m IP and TCP/UDP encapsulation */
- int mssfix; /* Upper bound on TCP MSS */- bool mssfix_default; /* tru= e if --mssfix should use the default parameters */
- bool mssfix_encap; /* true if --mssfix h= ad the "mtu" parameter to include
- * overhead from IP and TCP/= UDP encapsulation */
- = bool mssfix_fixed; /* use the mssfix value without any encapsulation a= djustments */
+ in= t fragment; /* internal fragmentation size */
+ bool fragment_encap; /* true if --= fragment had the "mtu" parameter to
+ * include overhead fr= om IP and TCP/UDP encapsulation */
+ int mssfix; /* Upper bound on TCP MSS */
+ bool mssfix_default;= /* true if --mssfix should use the default parameters */
+ bool mssfix_encap; /* true = if --mssfix had the "mtu" parameter to include

+ * overhead= from IP and TCP/UDP encapsulation */
+ bool mssfix_fixed; /* use the mssfix value withou= t any encapsulation adjustments */

- int explicit_exit_notification; /* Expl= icitly tell peer when we are exiting via OCC_EXIT or [RESTART] message */
+ int explicit_exit= _notification; /* Explicitly tell peer when we are exiting via OCC_EXIT or<= /span>
+ = [RESTART] message */

-#define CE_DISABLED (1<<0)=
-#define CE_MAN_QUERY_PROXY (= 1<<1)
+#define = CE_DISABLED (1 << 0)
+#define CE_MAN_QUERY_PROXY (1 << 1)
#define CE_MAN_QUERY_REMOTE_UNDEF 0
#define= CE_MAN_QUERY_REMOTE_QUERY 1
#define CE_MAN_QUERY_REMOTE_= ACCEPT 2
@@ -230,7 +231,8 @@
char port= [RH_PORT_LEN];
};

-enum genkey_type {
+enum genkey_type
+{
GENKEY_SECRET, GENKEY_TLS_CRYPTV2_CLIENT,
GENKEY_TLS_CRYP= TV2_SERVER,
@@ -337,32 +339,32 @@
<= br> bool mlock;

- int keepalive_ping; /* a proxy for ping/p= ing-restart */
+ i= nt keepalive_ping; /* a proxy for ping/ping-restart */
= int keepalive_timeout;

- int inactivity_timeout; /* --inactive */=
+ int inactivity_timeout= ; /* --inactive */
int64_t inactivity_minimum_bytes;

- i= nt session_timeout; /* Force-kill session after n seconds */<= br>+ int session_timeout; = /* Force-kill session after n seconds */

- int ping_send_timeout; /* Se= nd a TCP/UDP ping to remote every n seconds */

- int ping_rec_timeout; /* Expect a TCP/UD= P ping from remote at least once every n seconds */
- bool ping_timer_remote; /* Run ping= timer only if we have a remote address */
+ int ping_send_timeout; /* Send a TCP/UDP ping t= o remote every n seconds */
+ int ping_rec_timeout; /* Expect a TCP/UDP ping from remote at= least once every n seconds */
+ bool ping_timer_remote; /* Run ping timer only if we have a = remote address */

#define PING_UNDEF 0=
#define PING_EXIT 1
#define PING_REST= ART 2
int ping_rec_timeout_action; /* What action to t= ake on ping_rec_timeout (exit or restart)? */

<= span style=3D"color: hsl(0, 100%, 40%);">- bool persist_tun; /= * Don't close/reopen TUN/TAP dev on SIGUSR1 or PING_RESTART */
- bool persist_local_ip; = /* Don't re-resolve local address on SIGUSR1 or PING_RESTART */
- bool persist_remote_ip;= /* Don't re-resolve remote address on SIGUSR1 or PING_RESTART */
+ bool persist_tun;= /* Don't close/reopen TUN/TAP dev on SIGUSR1 or PING_RESTAR= T */
+ bool persis= t_local_ip; /* Don't re-resolve local address on SIGUSR1 or PING_= RESTART */
+ bool = persist_remote_ip; /* Don't re-resolve remote address on SIGUSR1 o= r PING_RESTART */

#if PASSTOS_CAPABILITY=
bool passtos;
#endif

- int resolve_ret= ry_seconds; /* If hostname resolve fails, retry for n seconds */+ int resolve_retry_seconds= ; /* If hostname resolve fails, retry for n seconds */
= bool resolve_in_advance;
const char *ip_remote_hint;<= /span>

@@ -433,7 +435,7 @@
= int route_delay_window;
bool route_delay_defined;
struct route_option_list *routes;
- struct route_ipv6_option_list *routes_ipv6= ; /* IPv6 */
+ struct route_ipv6_option_list *routes_ipv6; /* IPv6 */<= br> bool block_ipv6;
bool route_nopull;
bool route_gateway_via_dhcp;
@@ -468,13 +4= 70,13 @@
bool server_defined;
in_= addr_t server_network;
in_addr_t server_netmask;
- bool server_ipv6_define= d; /* IPv6 */
- struct in6_addr server_network_ipv6; /= * IPv6 */
- unsigned= int server_netbits_ipv6; /* IPv6 */
+ bool server_ipv6_defined; = /* IPv6 */
+ stru= ct in6_addr server_network_ipv6; /* IPv6 */
+ unsigned int server_netbits_ipv6; /* IPv6 */=

-#de= fine SF_NOPOOL (1<<0)
-#define SF_TCP_NODELAY_HELPER (1<<1)
-#define SF_NO_PUSH_ROUTE_GATEWAY (1<<2)
+#define SF_NOPOOL = (1 << 0)
+#define SF_TCP_NODELAY_HELPER (1 << 1)
+#define SF_NO_PUSH_ROUTE_GATEWAY (1 <&= lt; 2)
unsigned int server_flags;

bool server_bridge_proxy_dhcp;
@@ -493,9= +495,9 @@
const char *ifconfig_pool_persist_filename;=
int ifconfig_pool_persist_refresh_freq;

- bool ifconfig= _ipv6_pool_defined; /* IPv6 */
- struct in6_addr ifconfig_ipv6_pool_base; = /* IPv6 */
- = int ifconfig_ipv6_pool_netbits; /* IPv6 */
= + bool ifconfig_ipv6_pool_de= fined; /* IPv6 */
+ struct in6_addr ifconfig_ipv6_pool_base; /* IPv6 */
+ int ifconfig_ipv6_pool_netbit= s; /* IPv6 */


int real_hash= _size;
int virtual_hash_size;
@@ -510,= 7 +512,7 @@
int n_bcast_buf;
int = tcp_queue_limit;
struct iroute *iroutes;
- struct iroute_ipv6 *iroutes_ipv= 6; /* IPv6 */

+ struct iroute_ipv6 *iroutes_ipv6; /* IPv6 */
bool push_ifconfig_defined;

in_addr_t push_ifco= nfig_local;
in_addr_t push_ifconfig_remote_netmask;
@@ -518,12 +520,12 @@
bool push_ifconfig= _constraint_defined;
in_addr_t push_ifconfig_constrain= t_network;
in_addr_t push_ifconfig_constraint_netmask;=
- bool push_ifconfi= g_ipv4_blocked; /* IPv4 */
- bool push_ifconfig_ipv6_defined; = /* IPv6 */
- st= ruct in6_addr push_ifconfig_ipv6_local; /* IPv6 */
- int push_ifconfig_ipv6_netbits; = /* IPv6 */

- struct in6_addr push_ifconfig_ipv6_remote; /* IPv6 */=
- bool push_ifconfi= g_ipv6_blocked; /* IPv6 */
+ bool push_ifconfig_ipv4_blocked; /*= IPv4 */
+ bool pu= sh_ifconfig_ipv6_defined; /* IPv6 */
+ struct in6_addr push_ifconfig_ipv6_local; /= * IPv6 */
+ int pu= sh_ifconfig_ipv6_netbits; /* IPv6 */
+ struct in6_addr push_ifconfig_ipv6_remote; = /* IPv6 */
+ bool = push_ifconfig_ipv6_blocked; /* IPv6 */
bool = enable_c2c;
bool duplicate_cn;

@@ -572,8 +574,8 @@
bool allow_deprecated_i= nsecure_static_crypto;
int key_direction;
const char *ciphername;

- bool enable_ncp_fallback; /**< If defined fall back = to
- = * ciphername if NCP fails */
+ bool enable_ncp_fallback; /**< If defined f= all back to
+ = * ciphername if NCP fails */
/*= * The original ncp_ciphers specified by the user in the configuration*/
const char *ncp_ciphers_conf;
const = char *ncp_ciphers;
@@ -727,40 +729,40 @@
/= *
* Option classes.
*/
-#define OPT_P_GENERAL (1<&l= t;0)
-#define OPT_P_UP = (1<<1)
-#define OPT_P_ROUTE (1<<2)
-#define OPT_P_DHCPDNS (1<<3) /* i= ncludes ip windows options like */
-#define OPT_P_SCRIPT (1<<4)
-#define OPT_P_SETENV (1<<5= )
-#define OPT_P_SHAPER= (1<<6)
= -#define OPT_P_TIMER (1<<7)
-#define OPT_P_PERSIST (1<<8)
= -#define OPT_P_PERSIST_IP (1= <<9)
-#define OPT= _P_COMP (1<<10) /* TODO */
-#define OPT_P_MESSAGES (1<<11)-#define OPT_P_NCP (= 1<<12) /**< Negotiable crypto parameters */
-#define OPT_P_TLS_PARMS (1<<13)= /* TODO */
-#define OP= T_P_MTU (1<<14) /* TODO */
-#define OPT_P_NICE (1<<15)-#define OPT_P_PUSH = (1<<16)
-#define = OPT_P_INSTANCE (1<<17) /**< allowed in ccd, client-connect = etc*/
-#define OPT_P_CO= NFIG (1<<18)
-#define OPT_P_EXPLICIT_NOTIFY (1<<19)
-#define OPT_P_ECHO (1<<20)
-#define OPT_P_INHERIT = (1<<21)
-#de= fine OPT_P_ROUTE_EXTRAS (1<<22)
-#define OPT_P_PULL_MODE (1<<23)
-#define OPT_P_PLUGIN (1&l= t;<24)

-#define OPT_= P_SOCKBUF (1<<25)
-#define OPT_P_SOCKFLAGS (1<<26)
-#define OPT_P_CONNECTION (1<<27)=
-#define OPT_P_PEER_ID= (1<<28)
= -#define OPT_P_INLINE (1<<29)
-#define OPT_P_PUSH_MTU (1<<30)-#define OPT_P_ROUTE_TABLE = (1<<31)
+#defin= e OPT_P_GENERAL (1 << 0)
+#define OPT_P_UP (1 << 1)
<= span style=3D"color: hsl(120, 100%, 40%);">+#define OPT_P_ROUTE (= 1 << 2)

+#defin= e OPT_P_DHCPDNS (1 << 3) /* includes ip windows options like = */
+#define OPT_P_SCR= IPT (1 << 4)
+#define OPT_P_SETENV (1 << 5)
+#define OPT_P_SHAPER (1 <<= 6)
+#define OPT_P_TI= MER (1 << 7)
+#define OPT_P_PERSIST (1 << 8)
+#define OPT_P_PERSIST_IP (1 <<= 9)
+#define OPT_P_CO= MP (1 << 10) /* TODO */
+#define OPT_P_MESSAGES (1 << 11)+#define OPT_P_NCP = (1 << 12) /**< Negotiable crypto parameters */
+#define OPT_P_TLS_PARMS (1 <= < 13) /* TODO */
+= #define OPT_P_MTU (1 << 14) /* TODO */
+#define OPT_P_NICE (1 <&= lt; 15)
+#define OPT_= P_PUSH (1 << 16)
+#define OPT_P_INSTANCE (1 << 17) /**< allowed= in ccd, client-connect etc*/
+#define OPT_P_CONFIG (1 << 18)
+#define OPT_P_EXPLICIT_NOTIFY (1 <&l= t; 19)
+#define OPT_P= _ECHO (1 << 20)
+#define OPT_P_INHERIT (1 << 21)
+#define OPT_P_ROUTE_EXTRAS (1 <= ;< 22)
+#define OP= T_P_PULL_MODE (1 << 23)
+#define OPT_P_PLUGIN (1 << 24)
+#define OPT_P_SOCKBUF (1 = << 25)

+#define= OPT_P_SOCKFLAGS (1 << 26)
+#define OPT_P_CONNECTION (1 << 27)
= +#define OPT_P_PEER_ID = (1 << 28)
+#def= ine OPT_P_INLINE (1 << 29)
+#define OPT_P_PUSH_MTU (1 << 30)<= br>+#define OPT_P_ROUTE_TABLE = (1 << 31)

-#define OPT_P_DEFAULT (~(OPT_P_INSTANCE|OPT_P_PULL_MODE))<= /span>
+#define OPT_P_DEFAUL= T (~(OPT_P_INSTANCE | OPT_P_PULL_MODE))

= #define PULL_DEFINED(opt) ((opt)->pull)
#define PUSH_DE= FINED(opt) ((opt)->push_list)
@@ -796,18 +798,18 @@
/*
* some PUSH_UPDATE options
*/

-#define OPT_P_U= _ROUTE (1<<0)
-#define OPT_P_U_ROUTE6 (1<<1)
-#define OPT_P_U_DNS (1<<2= )
-#define OPT_P_U_DHCP= (1<<3)
+#define OPT_P_U_ROUTE (1 << 0)
+#define OPT_P_U_ROUTE6= (1 << 1)
+#define OPT_P_U_DHCP (1 << 3)
+#define OPT_P_U_REDIR_= GATEWAY (1 << 4)

struct pull_filte= r
{
-#= define PUF_TYPE_UNDEF 0 /**< undefined filter type */
-#define PUF_TYPE_ACCEPT 1 /**<= filter type to accept a matching option */

-#define PUF_TYPE_IGNORE 2 /**< filter type to i= gnore a matching option */
-#define PUF_TYPE_REJECT 3 /**< filter type to reject and trigger= SIGUSR1 */
+#define = PUF_TYPE_UNDEF 0 /**< undefined filter type */
+#define PUF_TYPE_ACCEPT 1 /**< filter typ= e to accept a matching option */
+#define PUF_TYPE_IGNORE 2 /**< filter type to ignore a matc= hing option */
+#defi= ne PUF_TYPE_REJECT 3 /**< filter type to reject and trigger SIGUSR1 */
int type;
int size;
char *pattern;

@@ -820,12 +822,8 @@
= struct pull_filter *tail;
};
=
-void parse_argv(struct optio= ns *options,
- = const int argc,
= - char *argv[],
- const int msglevel,
- const unsigned int permission_mask,<= /span>
- unsign= ed int *option_types_found,
+void parse_argv(struct options *options, const int argc, char *argv= [], const int msglevel,
+ const unsigned int permission_mask, unsigned int *optio= n_types_found,
struct env_set *es);=

void notnull(const char *arg, const char *desc= ription);
@@ -853,12 +851,8 @@

= const char *options_string_version(const char *s, struct gc_arena *g= c);

-= char *options_string(const struct options *o,
- const struct frame *frame,
- stru= ct tuntap *tt,
- = openvpn_net_ctx_t *ctx,
- bool remote,
- struct gc_arena *gc);
+char *options_string(con= st struct options *o, const struct frame *frame, struct tuntap *tt,<= br>+ openvp= n_net_ctx_t *ctx, bool remote, struct gc_arena *gc);

bool options_cmp_equal_safe(char *actual, const char *expected= , size_t actual_n);

@@ -878,8 +872,8 @@
* @return gc-allocated value of option with name opt_name = if option was found,
* or NULL otherwise.<= br> */
-char *op= tions_string_extract_option(const char *options_string,
- const= char *opt_name, struct gc_arena *gc);
+char *options_string_extract_option(const char *options_= string, const char *opt_name,
+ struct gc_arena *gc);<= br>

void options_postprocess(stru= ct options *options, struct env_set *es);
@@ -888,34 +882,2= 2 @@

void pre_connect_restore(struct opt= ions *o, struct gc_arena *gc);

-bool apply_push_options(struct context *c,
- str= uct options *options,
-= struct buffer *buf,
- unsigned int permission_mask,=
- = unsigned int *option_types_found,
- struct env_set *es,
- bool is_update= );
+bool apply_push_o= ptions(struct context *c, struct options *options, struct buffer *buf,
+ = unsigned int permission_mask, unsigned int *option_types_found,
<= span style=3D"color: hsl(120, 100%, 40%);">+ struct = env_set *es, bool is_update);


void optio= ns_detach(struct options *o);

-void options_server_import(struct options *o,
- = const char *filename,
- int msglevel,
- unsigned int permission_mas= k,
- = unsigned int *option_types_found,
+void options_server_import(struct options *o, const c= har *filename, int msglevel,
+ unsigned int permission_mask, unsigned = int *option_types_found,
struct= env_set *es);

void pre_pull_default(str= uct options *o);

void rol_check_alloc(st= ruct options *options);

-int parse_line(const char *line,
- char *p[],
- const int n,
<= span style=3D"color: hsl(0, 100%, 40%);">- const char *file,<= /span>
- const i= nt line_num,
- = int msglevel,
- = struct gc_arena *gc);
+int parse_line(const char *line, char *p[], const int n, con= st char *file, const int line_num,
+ int msglevel, struct gc_arena *gc);
/*
* parse/print topology codin= g
@@ -939,11 +921,8 @@

c= onst char *auth_retry_print(void);

-void options_string_import(struct options *= options,
- = const char *config,
- const int msglevel,
- const unsig= ned int permission_mask,
+void options_string_import(stru= ct options *options, const char *config, const int msglevel,
+ const u= nsigned int permission_mask, unsigned int *option_types_found,

struct env_set *es);


bool key_is_external(const struct options *options);diff --git a/src/openvpn/options_util.c b/src/openvpn/options_util.c=
index e469c28..5251b21 100644
--- a/src/op= envpn/options_util.c
+++ b/src/openvpn/options_util.c
@@ -124,12 +124,11 @@

if = (i < 0 || *endptr !=3D '\0' || i > INT_MAX)
= {
- msg(msgl= evel, "Cannot parse argument '%s' as non-negative integer"= ;,
- str);
+ msg(msglevel,= "Cannot parse argument '%s' as non-negative integer", st= r);
i =3D 0;
}

- return (int) i= ;
+ return (int)i;=
}

int
= @@ -144,27 +143,17 @@
i =3D 0;
= }

-= return (int) i;
+= return (int)i;
}

-static const char *updatable_options[] = =3D {
- "block-= ipv6",
- "= block-outside-dns",
- "dns",
- "ifconfig",
- "ifconfig-ipv6",
- "push-continuation",
- "redirect-gateway",=
- "redirect-private&q= uot;,
- "route&= quot;,
- "route= -gateway",
- &q= uot;route-ipv6",
-= "route-metric",
- "topology",
- "tun-mtu",
- "keepalive"
-};
+static const char *updatable_options[] =3D { "block-ipv6", = "block-outside-dns",
+ "dhcp-option&= quot;, "dns",
+ "ifconfig", = "ifconfig-ipv6",
+ "push-conti= nuation", "redirect-gateway",
+ "r= edirect-private", "route",
+ "rou= te-gateway", "route-ipv6",
+ "= route-metric", "topology",
+ "= ;tun-mtu", "keepalive" };
=
bool
check_push_update_option_flags(char *line,= int *i, unsigned int *flags)
@@ -196,7 +185,7 @@ }

size_t len =3D strlen(= &line[*i]);
- in= t count =3D sizeof(updatable_options)/sizeof(char *);
+ int count =3D sizeof(updatable_option= s) / sizeof(char *);
for (int j =3D 0; j < count; += +j)
{
size_t opt_len =3D strl= en(updatable_options[j]);
diff --git a/src/openvpn/options_= util.h b/src/openvpn/options_util.h
index 23fd78d..6f81b1e = 100644
--- a/src/openvpn/options_util.h
+++= b/src/openvpn/options_util.h
@@ -26,28 +26,24 @@
#include "options.h"
<= /span>
-const char *-parse_auth_failed_temp(struct o= ptions *o, const char *reason);
+const char *parse_auth_failed_temp(struct options *o, const cha= r *reason);


/** Checks= if the string is a valid integer by checking if it can be
= * converted to an integer */
-bool
-valid_i= nteger(const char *str, bool positive);
+bool valid_integer(const char *str, bool positive);

/**
* Converts a str to a= positive number if the string represents a postive
* int= eger number. Otherwise print a warning with msglevel and return 0 */
-int=
-positive_atoi(const char *st= r, int msglevel);
+in= t positive_atoi(const char *str, int msglevel);
/**
* Converts a str to an integer if the string = can be represented as an
* integer number. Otherwise prin= t a warning with msglevel and return 0
*/
-int

-atoi_warn(const char *str, int msglevel);
+int atoi_warn(const char *str, in= t msglevel);


/**
* Fil= ter an option line by all pull filters.
@@ -57,9 +53,7 @@
* reject, SIGUSR1 is triggered and the return value is fal= se.
* In that case the caller must end the push processin= g.
*/
-bool
-apply_pull_filt= er(const struct options *o,
- char *line);
+bool apply_pull_filter(const struct options *o, char *line= );

/**
* @brief Checks= the formatting and validity of options inside push-update messages.=
@@ -89,7 +83,6 @@
* - The `line` parame= ter is empty or `NULL`.
* - The `?` flag is absen= t and the option is not updatable.
*/
-bool
-check_push_update_option_flags(char *line, int *i, unsigne= d int *flags);
+bool = check_push_update_option_flags(char *line, int *i, unsigned int *flags);

#endif /* ifndef OPTIONS_UTIL_H_ */=
diff --git a/src/openvpn/otime.c b/src/openvpn/otime.c
= index d6b9c2c..717f749 100644
--- a/src/openvpn/otime= .c
+++ b/src/openvpn/otime.c
@@ -83,9 +83,7= @@
tv_string(const struct timeval *tv, struct gc_arena *g= c)
{
struct buffer out =3D alloc_buf_= gc(64, gc);
- buf_pr= intf(&out, "[%" PRIi64 "/%ld]",
- (int64_t)tv->tv_sec,
- (long)tv-= >tv_usec);
+ bu= f_printf(&out, "[%" PRIi64 "/%ld]", (int64_t)tv->= ;tv_sec, (long)tv->tv_usec);
return BSTR(&out);=
}

@@ -97,10 +95,7 @@
const char *
tv_string_abs(const struct tim= eval *tv, struct gc_arena *gc)
{
- return time_string((time_t) tv->tv_sec,<= /span>
- = (long) tv->tv_usec,
- true,
- gc);
+ return time_string((time_t)tv->tv_sec, (long)tv->= ;tv_usec, true, gc);
}

= /* format a time_t as ascii, or use current time if 0 */
@@= -124,9 +119,8 @@
t =3D tv.tv_sec;
= struct tm *tm =3D localtime(&t);

- buf_printf(&out, "%04d-%02d= -%02d %02d:%02d:%02d",
- tm->tm_year+1900, tm->tm_mon+1, tm->tm_mday,<= /span>
- tm->= tm_hour, tm->tm_min, tm->tm_sec);
+ buf_printf(&out, "%04d-%02d-%02d %02d:%02d= :%02d", tm->tm_year + 1900, tm->tm_mon + 1,
+ tm->tm_mday, tm->tm= _hour, tm->tm_min, tm->tm_sec);

= if (show_usec && tv.tv_usec)
{
@@ -196,9 +190,7 @@

t =3D time(NULL); gettimeofday(&tv, NULL);
#if 1<= br>- msg(M_INFO, "t= =3D%" PRIi64 " s=3D%" PRIi64 " us=3D%ld",- (int64_t)t,=
- (int64_t)tv.tv_s= ec,
+ msg(M_IN= FO, "t=3D%" PRIi64 " s=3D%" PRIi64 " us=3D%ld"= ;, (int64_t)t, (int64_t)tv.tv_sec,
(long)tv.tv= _usec);
#endif
}
diff= --git a/src/openvpn/otime.h b/src/openvpn/otime.h
index 29= e8046..5c700bb 100644
--- a/src/openvpn/otime.h
<= span>+++ b/src/openvpn/otime.h

@@ -236,7 +236,7 @@ dest->tv_usec =3D usec;
}
=
-#define TV_WITHIN_SI= GMA_MAX_SEC 600
+#def= ine TV_WITHIN_SIGMA_MAX_SEC 600
#define TV_WITHIN_SIGMA_M= AX_USEC (TV_WITHIN_SIGMA_MAX_SEC * 1000000)

/*

@@ -259,7 +259,7 @@
{
if (at > current)

{
- const interval_t delta =3D (interva= l_t) (at - current);
= + const interval_t delta =3D (interval_t)(at - current);
<= span> if (delta < *wakeup)

{
= *wakeup =3D delta;
diff --git a/src/open= vpn/ovpn_dco_freebsd.h b/src/openvpn/ovpn_dco_freebsd.h
ind= ex 7eb643b..6006b54 100644
--- a/src/openvpn/ovpn_dco_freeb= sd.h
+++ b/src/openvpn/ovpn_dco_freebsd.h
@= @ -32,42 +32,46 @@
#include <netinet/in.h>
/* Maximum size of an ioctl request. */-#define OVPN_MAX_REQUEST_SIZE = 4096
+#define OVPN_M= AX_REQUEST_SIZE 4096

-enum ovpn_notif_type {
+enum ovpn_notif_type
+{
OVPN_NOTIF_DEL_PEER,
= OVPN_NOTIF_ROTATE_KEY,
OVPN_NOTIF_FLOAT,
};

-enum ovpn_del_reason {
- OVPN_DEL_REASON_REQUESTED =3D 0,
- OVPN_DEL_REASON_TIMEOUT =3D= 1
+enum ovpn_del_rea= son
+{
+ OVPN_DEL_REASON_REQUESTED =3D = 0,

+ OVPN_DEL_REAS= ON_TIMEOUT =3D 1
};

-enum ovpn_key_slot {
- OVPN_KEY_SLOT_PRIMARY =3D 0,+enum ovpn_key_slot+{
+ OVPN_KEY_SLOT_PRIMARY =3D 0,
OVPN_KEY_SLOT_SECONDARY =3D 1

};
<= /span>
-enum ovpn_key_cipher {=
- OVPN_CIPHER_ALG_N= ONE =3D 0,
- OVPN_CIPHER_ALG_AES_GCM =3D 1,
- OVPN_CIPHER_ALG_CHACHA20_POLY1305 = =3D 2
+enum ovp= n_key_cipher
+{
+ OVPN_CIPHER_ALG_NONE = =3D 0,
+ OVPN_CIPH= ER_ALG_AES_GCM =3D 1,
+ OVPN_CIPHER_ALG_CHACHA20_POLY1305 =3D 2
};
-#define OVPN_= NEW_PEER _IO('D', 1)
-#define OVPN_DEL_PEER _IO('D', 2)=
-#define OVPN_GET_STATS = _IO('D', 3)
-#define OVPN_NEW_KEY _IO('D', 4)
-#define OVPN_SWAP_KEYS _IO('D&= #39;, 5)
-#define OVPN_= DEL_KEY _IO('D', 6)
-#define OVPN_SET_PEER _IO('D', 7)=
-#define OVPN_START_VPN = _IO('D', 8)
-#define OVPN_SEND_PKT _IO('D', 9)
-#define OVPN_POLL_PKT _IO('D&= #39;, 10)
-#define OVPN= _GET_PKT _IO('D', 11)
-#define OVPN_SET_IFMODE _IO('D', 12)
-#define OVPN_GET_PEER_STA= TS _IO('D', 13)
+#define OVPN_NEW_PEER _IO('D', 1)
+#define OVPN_DEL_PEER _IO('D&= #39;, 2)
+#define OVP= N_GET_STATS _IO('D', 3)
+#define OVPN_NEW_KEY _IO('D', 4)
= +#define OVPN_SWAP_KEYS _I= O('D', 5)
+#d= efine OVPN_DEL_KEY _IO('D', 6)
+#define OVPN_SET_PEER _IO('D', 7)
+#define OVPN_START_VP= N _IO('D', 8)
+#define OVPN_SEND_PKT _IO('D', 9)
+#define OVPN_POLL_PKT _IO('D&#= 39;, 10)
+#define OVP= N_GET_PKT _IO('D', 11)
+#define OVPN_SET_IFMODE _IO('D', 12)+#define OVPN_GET_PEER_STATS = _IO('D', 13)

#endif /* ifndef _N= ET_IF_OVPN_H_ */
diff --git a/src/openvpn/packet_id.c b/src= /openvpn/packet_id.c
index e6ca601..09696db 100644--- a/src/openvpn/packet_id.c
+++ b/src/openvpn/pac= ket_id.c
@@ -53,20 +53,15 @@
#define SEQ_E= XPIRED ((time_t)1)

#ifdef ENABLE_DEBUG
-static void packet_id_d= ebug_print(int msglevel,
- = const struct packet_id_net *pin,
- const char *message,
+static void packet_id_de= bug_print(int msglevel, const struct packet_id_rec *p,
+ const = struct packet_id_net *pin, const char *message,
= packet_id_print_type value);

#endif /* ENABLE_DEBUG */

s= tatic inline void
-pack= et_id_debug(int msglevel,
- const struct packet_id_rec *p,
- const struct packet_id_net *pi= n,
- con= st char *message,
- = uint64_t value)
+packet_id_debug(int msglevel, const struct packet_id_rec *p, const = struct packet_id_net *pin,
+ const char *message, uint64_t value)
{

#ifdef ENABLE_DEBUG
if (unlikely(= check_debug_level(msglevel)))
@@ -77,7 +72,8 @@
<= span> }


static void
-packet_id_init_recv(struct packet_id_rec *= rec, int seq_backtrack, int time_backtrack, const char *name, int unit)
+packet_id_init_recv(str= uct packet_id_rec *rec, int seq_backtrack, int time_backtrack,
+ const char *= name, int unit)

{
rec->name =3D na= me;
rec->unit =3D unit;
@@ -92,10 += 88,10 @@
rec->initialized =3D true;
}

void
-packet_id_init(struct packet_id *p, int seq_backtrack, int time_backtra= ck, const char *name, int unit)
+packet_id_init(struct packet_id *p, int seq_backtrack, int time= _backtrack, const char *name,
+ int unit)
{
- dmsg(D_PID_DEBUG, "PID packet_id_i= nit seq_backtrack=3D%d time_backtrack=3D%d",
- seq_backtrack,
+ dmsg(D_PID_DEBUG, "PID packet_id= _init seq_backtrack=3D%d time_backtrack=3D%d", seq_backtrack, time_backtrack);

A= SSERT(p);
@@ -118,8 +114,7 @@

<= span> /* Reinitalise the source */

CLEAR(*src);
- packet_id_init_recv(= src, dest->seq_backtrack, dest->time_backtrack,
- dest->name, dest= ->unit);
+ pack= et_id_init_recv(src, dest->seq_backtrack, dest->time_backtrack, dest-= >name, dest->unit);
}

void

@@ -145,10 +140,8 @@
* = If time value increases, start a new sequence list of number
* sequence for the new time point.

*/=
- if (!CIRC_LIS= T_SIZE(p->seq_list)
= - || pin->time > p->time
- || (pin->id >=3D p->seq_backtra= ck
- &am= p;& pin->id - p->seq_backtrack > p->id))
+ if (!CIRC_LIST_SIZE(p->seq_= list) || pin->time > p->time
+ || (pin->id >=3D p->seq_backtrack &a= mp;& pin->id - p->seq_backtrack > p->id))
= {
p->time =3D pin->time;<= br> p->id =3D 0;
@@ -163,15 +156,14 @@=
#ifdef PID_SIMULATE_BACKTRACK
= || (get_random() % 64) < 31
#endif
- )

+ )
{
CIRC_LIST_PUSH(p->seq_list, SEQ_UNSEEN);
++p->id;
}

diff =3D p->id - pin->id;
- if (diff < CIRC_LIST_SI= ZE(p->seq_list)

- = && local_now > SEQ_EXPIRED)
+ if (diff < CIRC_LIST_SIZE(p->seq_= list) && local_now > SEQ_EXPIRED)
{
CIRC_LIST_ITEM(p->seq_list, diff) =3D local_no= w;
}
@@ -220,8 +212,7 @@ * it is a replay.
*/
bool
-packet_id_test(struct packe= t_id_rec *p,
- = const struct packet_id_net *pin)
+packet_id_test(struct packet_id_rec *p, const struct pac= ket_id_net *pin)
{
uint64_t diff;

@@ -257,10 +248,11 @@
= if (diff > p->max_backtrack_stat)
= {
p->max_backtrack_stat =3D diff;
- packet_id_= debug(D_PID_DEBUG_LOW, p, pin, "PID_ERR replay-window backtrack occurr= ed", p->max_backtrack_stat);
+ packet_id_debug(D_PID_DEBUG_LOW, p, pin, &= quot;PID_ERR replay-window backtrack occurred",
+ p->max= _backtrack_stat);
}
- if (diff >=3D (= packet_id_type) CIRC_LIST_SIZE(p->seq_list))
+ if (diff >=3D (packet_id_type)CI= RC_LIST_SIZE(p->seq_list))
{
packet_id_debug(D_PID_DEBUG_LOW, p, pin, "PID_ERR l= arge diff", diff);

return false;
@@ -285,7 +277,7 @@
packet_id_debu= g(D_PID_DEBUG_LOW, p, pin, "PID_ERR time backtrack", 0); return false;
}
- else = /* time moved forward */

+ else /* time moved forward */
{
return true;
}
= @@ -306,7 +298,7 @@
{
= return false;
}
- else /* time moved= forward */
+ = else /* time moved forward */
{
= return pin->id =3D=3D 1;
}@@ -382,8 +374,7 @@
}

<= span> bool

-packet_id_w= rite(struct packet_id_send *p, struct buffer *buf, bool long_form,- bool prepend)<= /span>
+packet_id_write(stru= ct packet_id_send *p, struct buffer *buf, bool long_form, bool prepend)
{
if (!packet_id_send_update(p, long_for= m))
{
@@ -431,8 +422,7 @@
buf_printf(&out, "[ #" packet_id_format, (packet_id_= print_type)pin->id);

if (print_timestamp &&= pin->time)
{
- buf_printf(&out, " / time =3D (" pack= et_id_format ") %s",
- (packet_id_print_type)pin->time,
<= span style=3D"color: hsl(120, 100%, 40%);">+ buf_printf(&out, &q= uot; / time =3D (" packet_id_format ") %s", (packet_id_print= _type)pin->time,

time_string(pin->= ;time, 0, false, gc));
}

<= span>@@ -472,13 +462,10 @@

if (!packet_id_persist_enab= led(p))
{
/* open packet-id p= ersist file for both read and write */
- p->fd =3D platform_open(filename,
- O_CRE= AT | O_RDWR | O_BINARY,

- S_IRUSR | S_IWUSR);
+ p->fd =3D platform_open(filena= me, O_CREAT | O_RDWR | O_BINARY, S_IRUSR | S_IWUSR);
= if (p->fd =3D=3D -1)
{
- msg(D_PID_PERSIST | M_ERRNO,
- "Ca= nnot open --replay-persist file %s for read/write",
+ msg(D_PID_PERSIST | M_ERRN= O, "Cannot open --replay-persist file %s for read/write",<= br> filename);
}
<= span> else

@@ -499,14 +486,12 @@
= {
p->time =3D p->time_las= t_written =3D image.time;
p->id =3D p-&= gt;id_last_written =3D image.id;
- dmsg(D_PID_PERSIST_DEBUG, "PID Persist Read= from %s: %s",
- = p->filename, packet_id_persist_print(p, &gc));
+ dmsg(D= _PID_PERSIST_DEBUG, "PID Persist Read from %s: %s", p->filenam= e,
+ = packet_id_persist_print(p, &gc));
}
else if (n =3D=3D -1)
= {
- m= sg(D_PID_PERSIST | M_ERRNO,
- "Read error on --replay-persist file %s"= ;,
- = p->filename);
+ = msg(D_PID_PERSIST | M_ERRNO, "Read error on --replay-per= sist file %s", p->filename);
}<= br> }
}
@@ -517,8 +502,8= @@
void
packet_id_persist_save(struct pa= cket_id_persist *p)
{
- if (packet_id_persist_enabled(p) && p->time= && (p->time !=3D p->time_last_written
- = || p->id !=3D p->id_last_written))
+ if (packet_id_persist_enabled(p) &&am= p; p->time
+ = && (p->time !=3D p->time_last_written || p->id !=3D p-&g= t;id_last_written))
{
struct = packet_id_persist_file_image image;
ssize_t n;
@@ -535,20 +520,18 @@
{ p->time_last_written =3D p->time;
<= span> p->id_last_written =3D p->id;

- dmsg(D_PID_PERSIST_DEBU= G, "PID Persist Write to %s: %s",
- p->filename, packet_id_persis= t_print(p, &gc));
+ dmsg(D_PID_PERSIST_DEBUG, "PID Persist Write to %s: = %s", p->filename,
+ packet_id_persist_print(p, &gc));
= }
else
= {
- = msg(D_PID_PERSIST | M_ERRNO,
- "Cannot write to --replay-persist file= %s",
+ = msg(D_PID_PERSIST | M_ERRNO, "Cannot write to --replay-persist = file %s",
p->filename);=
}
}
= else
{
- msg(D_PID_PERSIST | M_ERRNO,
- "Cannot seek to beginn= ing of --replay-persist file %s",
+ msg(D_PID_PERSIST | M_ERRNO, "Cannot se= ek to beginning of --replay-persist file %s",
= p->filename);
}
= gc_free(&gc);
@@ -578,8 +561,7 @@
= buf_printf(&out, " #" packet_id_format, (packet_id_pri= nt_type)p->id);
if (p->time)
{

- = buf_printf(&out, " / time =3D (" packet_id_format ") %= s",
- = (packet_id_print_type)p->time,
+ buf_printf(&out, " / time =3D = (" packet_id_format ") %s", (packet_id_print_type)p->time= ,
time_string(p->time, 0, false,= gc));
}
}
@@= -591,11 +573,8 @@
#ifdef ENABLE_DEBUG

static void
-packet_id_debug_print(int msglevel,
- const struct packet_id_rec *p,
- co= nst struct packet_id_net *pin,
- const char *message,
- packet_id_print_type = value)
+packet_id_deb= ug_print(int msglevel, const struct packet_id_rec *p, const struct packet_i= d_net *pin,
+ = const char *message, packet_id_print_type value)
{

struct gc_arena gc =3D gc_new();
struct buffer out =3D alloc_buf_gc(256, &gc);

@@= -648,23 +627,13 @@
buf_printf(&out, " %&= quot; PRIi64 ":" packet_id_format, (int64_t)pin->time, pin->= ;id);
}

- buf_printf(&out, " t=3D%" PRIi64= "[%d]",
- = (int64_t)prev_now,
- (int)(prev_now - tv.tv_sec));
+ buf_printf(&out, " t=3D%&quo= t; PRIi64 "[%d]", (int64_t)prev_now, (int)(prev_now - tv.tv_sec))= ;

- = buf_printf(&out, " r=3D[%d,%" PRIu64 ",%d,%" PRIu= 64 ",%d]",
- = (int)(p->last_reap - tv.tv_sec),
- p->seq_backtrack,
<= span style=3D"color: hsl(0, 100%, 40%);">- p->time_backtra= ck,

- p-&= gt;max_backtrack_stat,
= - (int)p->initialized);
+ buf_printf(&out, " r=3D[%d,%" PRIu64= ",%d,%" PRIu64 ",%d]", (int)(p->last_reap - tv.tv_s= ec),
+ = p->seq_backtrack, p->time_backtrack, p->max_backtrack_stat, (int)p= ->initialized);
if (sl !=3D NULL)
= {
- buf_prin= tf(&out, " sl=3D[%d,%d,%d,%d]",
- sl->x_head,
- sl->x_size,
- sl->x= _cap,
- = sl->x_sizeof);
= + buf_printf(&out, " sl=3D[%d,%d,%d,%d]", sl->x_hea= d, sl->x_size, sl->x_cap, sl->x_sizeof);
}


@@ -704,7 +673,7 @@
/* Highest 16 bits of packet id is the epoch.
*

* The lower 48 bits are the per-epoch pack= et id counter. */
- = uint64_t net_id =3D ((uint64_t) epoch) << 48 | p->id;
+ uint64_t net_id =3D ((uint64= _t)epoch) << 48 | p->id;


/*= convert to network order. This ensures that the highest bytes
* also become the first ones on the wire*/

diff -= -git a/src/openvpn/packet_id.h b/src/openvpn/packet_id.h
in= dex 8bb6951..a7eb256 100644
--- a/src/openvpn/packet_id.h
+++ b/src/openvpn/packet_id.h
@@ -43,11 +43,= 11 @@
* These are ephemeral and are never saved to a file= .
*/
typedef uint32_t packet_id_type;
-#define PACKET_ID_MAX = UINT32_MAX
-#defin= e PACKET_ID_EPOCH_MAX 0x0000ffffffffffffull
+#define PACKET_ID_MAX UINT32_MAX
<= span style=3D"color: hsl(120, 100%, 40%);">+#define PACKET_ID_EPOCH_MAX 0x0= 000ffffffffffffull

/** Mask of the bits that contain the 4= 8-bit of the per-epoch packet
* counter in the packet id*= /
-#define PACKET_ID_MA= SK 0x0000ffffffffffffull
+#define PACKET_ID_MASK 0x0000ffffffffffffull
typedef uint32_t net_time_t;


/*
@@ -81,8 +81,8 @@
* sequence number due to pac= kets arriving
* out of order.
*/=
-#define MIN_SEQ_BACKTRACK 0<= /span>
-#define MAX_SEQ_BACKTR= ACK 65536
+#define MI= N_SEQ_BACKTRACK 0
+#define MAX_SEQ_BACKTRACK 65536
#define DEFAULT_SEQ_= BACKTRACK 64

/*
@@ -90,8= +90,8 @@
* seconds due to packets arriving
* out of order.

*/
-#define MIN_TIME_BACKTRACK 0
-#define MAX_TIME_BACKTRACK 600
+#define MIN_TIME_BACKTRACK 0
+#define MAX_TIME_BACKTRA= CK 600
#define DEFAULT_TIME_BACKTRACK 15

/*
@@ -112,14 +112,14 @@
*/

struct packet_id_rec
{- time_t last_reap; /= * last call of packet_id_reap */
- time_t time; /* highest time stamp received */<= /span>
- uint64_t id; = /* highest sequence number received */
- uint64_t seq_backtrack; /* set from --replay= -window */
- int tim= e_backtrack; /* set from --replay-window */
- uint64_t max_backtrack_stat; /* maximum b= acktrack seen so far */
- bool initialized; /* true if packet_id_init was called */
- struct seq_list *seq_= list; /* packet-id "memory" */
+ time_t last_reap; /* last call of packe= t_id_reap */
+ tim= e_t time; /* highest time stamp received */
+ uint64_t id; /*= highest sequence number received */

+ uint64_t seq_backtrack; /* set from --replay-wind= ow */
+ int time_b= acktrack; /* set from --replay-window */
+ uint64_t max_backtrack_stat; /* maximum b= acktrack seen so far */
+ bool initialized; /* true if packet_id_init was called *= /
+ struct seq_lis= t *seq_list; /* packet-id "memory" */
cons= t char *name;
int unit;
};
= @@ -132,16 +132,16 @@
{
const c= har *filename;
int fd;
- time_t time; /* time stamp */- packet_id_type id; /* s= equence number */
+ = time_t time; /* time stamp */
+ packet_id_type id; /* sequence number */
time_t time_last_written;

packet_id_type id_l= ast_written;
};

struct = packet_id_persist_file_image
{
- time_t time; /* time stamp */
- packet_id_type id; = /* sequence number */
+ time_t time; /* time stamp */
+ packet_id_type id; /* sequence number */ };

/*
@@ -201,7= +201,8 @@
struct packet_id_rec rec;
= };

-v= oid packet_id_init(struct packet_id *p, int seq_backtrack, int time_backtra= ck, const char *name, int unit);
+void packet_id_init(struct packet_id *p, int seq_backtrack, in= t time_backtrack, const char *name,
+ int unit);

= void packet_id_free(struct packet_id *p);
@@ -209,16 +210,13 @@
* Move the packet id recv s= tructure from \c src to \c dest. \c src will
* be reiniti= alised. \c dest will be freed before the move.
*/<= br>-void
-packet_id_move_recv(struct packet_id_rec *dest= , struct packet_id_rec *src);
+void packet_id_move_recv(struct packet_id_rec *dest, struct packe= t_id_rec *src);

/* should we accept an i= ncoming packet id ? */
= -bool packet_id_test(struct packet_id_rec *p,
- const struct packet_id_net *pin= );
+bool packet_id_te= st(struct packet_id_rec *p, const struct packet_id_net *pin);

/* change our current state to reflect an accepted pa= cket id */
-void packet= _id_add(struct packet_id_rec *p,
- const struct packet_id_net *pin);
<= span style=3D"color: hsl(120, 100%, 40%);">+void packet_id_add(struct packe= t_id_rec *p, const struct packet_id_net *pin);


= /* expire TIME_BACKTRACK sequence numbers */
void p= acket_id_reap(struct packet_id_rec *p);
@@ -262,8 +260,7 @@=
*
* @return true if successful, false = otherwise.
*/
-bool packet_id_write(struct packet_id_send *p, struct buffer *buf= ,
- = bool long_form, bool prepend);
+bool packet_id_write(struct packet_id_send *p, struct buffer *b= uf, bool long_form, bool prepend);

/*
* Inline functions.
@@ -309,7 +306,8 @@
p->id =3D 0;
}

-const char *packet_id_net_= print(const struct packet_id_net *pin, bool print_timestamp, struct gc_aren= a *gc);
+const char *= packet_id_net_print(const struct packet_id_net *pin, bool print_timestamp,<= /span>
+ = struct gc_arena *gc);

static= inline int
packet_id_size(bool long_form)
@@ -340,8 +338,7 @@

* @param buf buffer to write t= he packet id/epoch to
* @return false if the pac= ket id space is exhausted and cannot be written
*/=
-bool
-packet_id_write_epoch(struct packet_id_send= *p, uint16_t epoch, struct buffer *buf);
+bool packet_id_write_epoch(struct packet_id_send *p, = uint16_t epoch, struct buffer *buf);

/**=
* Reads the packet ID containing both the epoch and the = per-epoch counter
@@ -350,7 +347,6 @@
* @= param buf buffer to read the packet id from.
* @retur= n 0 for an error/invalid id, epoch otherwise
*/
-uint16_t
-packet_id_read_epoch(struct packet_id= _net *p, struct buffer *buf);

+uint16_t packet_id_read_epoch(struct packet_id_net *p, struct buf= fer *buf);

#endif /* PACKET_ID_H */
diff --git a/src/openvpn/perf.c b/src/openvpn/perf.c
= index 580e0fe..51c1a97 100644
--- a/src/openvpn/perf.= c
+++ b/src/openvpn/perf.c
@@ -35,34 +35,32= @@

#include "memdbg.h"=

-static con= st char *metric_names[] =3D {
- "PERF_BIO_READ_PLAINTEXT",
- "PERF_BIO_WRITE_PLAINTEXT",=
- "PERF_BIO_READ_CIPH= ERTEXT",
- &quo= t;PERF_BIO_WRITE_CIPHERTEXT",
- "PERF_TLS_MULTI_PROCESS",
- "PERF_IO_WAIT",
- "PERF_EVENT_LOOP",
- "PERF_MULTI_CRE= ATE_INSTANCE",
- = "PERF_MULTI_CLOSE_INSTANCE",
- "PERF_MULTI_SHOW_STATS",
- "PERF_MULTI_BCAST",
- "PERF_MULTI_MCAST&= quot;,
- "PERF_= SCRIPT",
- &quo= t;PERF_READ_IN_LINK",
- "PERF_PROC_IN_LINK",
- "PERF_READ_IN_TUN",
- "PERF_PROC_IN_TUN",- "PERF_PROC_OUT_LINK&qu= ot;,
- "PERF_PR= OC_OUT_TUN",
- = "PERF_PROC_OUT_TUN_MTCP"
-};
+stat= ic const char *metric_names[] =3D { "PERF_BIO_READ_PLAINTEXT",
+ = "PERF_BIO_WRITE_PLAINTEXT",
+ &qu= ot;PERF_BIO_READ_CIPHERTEXT",
+ "PERF_BIO_WRITE_C= IPHERTEXT",
+ = "PERF_TLS_MULTI_PROCESS",
+ = "PERF_IO_WAIT",
+ "PERF_EVENT_= LOOP",
+ = "PERF_MULTI_CREATE_INSTANCE",
+ = "PERF_MULTI_CLOSE_INSTANCE",
+ &qu= ot;PERF_MULTI_SHOW_STATS",
+ "PERF_MULTI_BCAST&qu= ot;,
+ = "PERF_MULTI_MCAST",
+ &qu= ot;PERF_SCRIPT",
+ "PERF_READ_IN_LINK",
+ = "PERF_PROC_IN_LINK",
+ "PERF_R= EAD_IN_TUN",
+ = "PERF_PROC_IN_TUN",+ = "PERF_PROC_OUT_LINK",
+ "PERF_PROC_= OUT_TUN",
+ = "PERF_PROC_OUT_TUN_MTCP" };

struct perf
{
-#define PS_INITIAL 0
-#define PS_METER_RUNNING = 1
-#define PS_METE= R_INTERRUPTED 2
+#de= fine PS_INITIAL 0
+#define PS_METER_RUNNING 1
+#define PS_METER_INTERRUPTED 2
int = state;

struct timeval start;<= br>@@ -138,8 +136,7 @@
{
const = int sindex =3D get_stack_index(0);
const int newlen = =3D get_stack_index(1);
- if (sindex >=3D 0 && newlen >=3D 0
- && pindex >=3D 0 &&= amp; pindex < PERF_N)
+ if (sindex >=3D 0 && newlen >=3D 0 && pindex= >=3D 0 && pindex < PERF_N)
{
= int i;
for (i =3D 0; i < sindex;= ++i)
@@ -147,8 +144,7 @@
if (= perf_set.stack[i] =3D=3D pindex)
{
<= span> perf_print_state(M_INFO);

- msg(M_FATAL, "PERF: push_per= f_index %s failed",
+ msg(M_FATAL, "PERF: push_pe= rf_index %s failed", metric_names[pindex]);
= }
}

@@ -180,9= +176,7 @@
{
if (p->state !=3D wan= ted)
{
- msg(M_FATAL, "PERF: bad state actual=3D%d wanted=3D%d&qu= ot;,
- p->= ;state,
- wa= nted);
+ msg(M= _FATAL, "PERF: bad state actual=3D%d wanted=3D%d", p->state, w= anted);
}
}
<= br>@@ -191,7 +185,7 @@
{
struct= timeval current;
ASSERT(!gettimeofday(&current, N= ULL));
- p->sofar= +=3D (double) tv_subtract(&current, &p->start, 600) / 1000000.0= ;
+ p->sofar += =3D (double)tv_subtract(&current, &p->start, 600) / 1000000.0;
tv_clear(&p->start);
}
@@ -287,7 +281,8 @@
if (= p->count > 0.0)
{
= const double mean =3D p->sum / p->count;
- msg(M_INFO, "%s n=3D%.0f mean= =3D%.3f max=3D%.3f", metric_names[i], p->count, mean*1000.0, p->= max*1000.0);
+ = msg(M_INFO, "%s n=3D%.0f mean=3D%.3f max=3D%.3f", metric_nam= es[i], p->count, mean * 1000.0,
+ p->max * 1000.0);
= }
}
}
@@ -303,15 +2= 98,8 @@
{
const int j =3D per= f_set.stack[i];
const struct perf *p =3D &perf= _set.perf[j];
- = msg(lev, "[%d] %s state=3D%d start=3D%s sofar=3D%f sum=3D%f max=3D%f c= ount=3D%f",
- = i,
- = metric_names[j],
- = p->state,
- = tv_string(&p->start, &gc),
- p->sofar,
- p->sum,
- p->max,
- p->count);
+ msg(lev, "[%d] %s state= =3D%d start=3D%s sofar=3D%f sum=3D%f max=3D%f count=3D%f", i, metric_n= ames[j],
+ = p->state, tv_string(&p->start, &gc), p->sofar, p->sum,= p->max, p->count);
}
gc_fr= ee(&gc);
}
diff --git a/src/openvpn/pe= rf.h b/src/openvpn/perf.h
index 7b35b5e..2a178a1 100644

--- a/src/openvpn/perf.h
+++ b/src/openvpn/per= f.h
@@ -34,27 +34,27 @@
/*
* Metrics

*/
-#define PERF_BIO_READ_PLAINTEXT 0
-#define PERF_BIO_WRITE_PLAINTEXT 1-#define PERF_BIO_READ_CIPHERTEX= T 2
-#define PERF_BI= O_WRITE_CIPHERTEXT 3
= -#define PERF_TLS_MULTI_PROCESS 4
-#define PERF_IO_WAIT 5
-#define PERF_EVENT_LOOP 6
-#define PERF_MULTI_CREATE_= INSTANCE 7
-#define PE= RF_MULTI_CLOSE_INSTANCE 8
-#define PERF_MULTI_SHOW_STATS 9
-#define PERF_MULTI_BCAST 10
-#define PERF_MULTI_MCAST = 11

-#define PERF_SCRIPT= 12
-#d= efine PERF_READ_IN_LINK 13
-#define PERF_PROC_IN_LINK 14
-#define PERF_READ_IN_TUN 15
-#define PERF_PROC_IN_TUN = 16
-#define P= ERF_PROC_OUT_LINK 17
-#define PERF_PROC_OUT_TUN 18
-#define PERF_PROC_OUT_TUN_MTCP 19
<= span style=3D"color: hsl(0, 100%, 40%);">-#define PERF_N = 20

+#define PERF_B= IO_READ_PLAINTEXT 0
+#define PERF_BIO_READ_CIPHERTEXT 2
+#define PERF_BIO_WRITE_CIPHERTEXT 3
+#define PERF_TLS_MULT= I_PROCESS 4
+#def= ine PERF_IO_WAIT 5
+#define PERF_EVENT_LOOP 6
+#define PERF_MULTI_CREATE_INSTANCE 7+#define PERF_MULTI_CLOSE_INS= TANCE 8
+#define PER= F_MULTI_SHOW_STATS 9
+#define PERF_MULTI_BCAST 10
+#define PERF_MULTI_MCAST 11
+#define PERF_SCRIPT = 12

+#define PERF_RE= AD_IN_LINK 13
+#define PERF_READ_IN_TUN 15
+#define PERF_PROC_IN_TUN 1= 6
+#define PERF_PROC_= OUT_LINK 17
+= #define PERF_PROC_OUT_TUN 18
+#define PERF_PROC_OUT_TUN_MTCP 19
+#define PERF_N 20

#ifdef ENABLE_PERFORMANCE_METRICS<= br>
@@ -63,7 +63,7 @@
/*
= * Stack size
*/
-#define STACK_N 64
+#define STACK_N 64

void perf_push(int type);

di= ff --git a/src/openvpn/ping.c b/src/openvpn/ping.c
index 50= f255a..b9c0b96 100644
--- a/src/openvpn/ping.c
+++ b/src/openvpn/ping.c

@@ -38,10 +38,8 @@
<= span> *

* PING_STRING_SIZE must be sizeof (ping_string)<= /span>
*/
-c= onst uint8_t ping_string[] =3D {
- 0x2a, 0x18, 0x7b, 0xf3, 0x64, 0x1e, 0xb4, 0xcb,
- 0x07, 0xed, 0x2d, 0x0a, 0x98, = 0x1f, 0xc7, 0x48

-};
+const uint8_t ping_str= ing[] =3D { 0x2a, 0x18, 0x7b, 0xf3, 0x64, 0x1e, 0xb4, 0xcb,
+ 0x0= 7, 0xed, 0x2d, 0x0a, 0x98, 0x1f, 0xc7, 0x48 };


= void
trigger_ping_timeout_signal(struct context *c)=
@@ -50,8 +48,7 @@
switch (c->optio= ns.ping_rec_timeout_action)
{
= case PING_EXIT:
- = msg(M_INFO, "%sInactivity timeout (--ping-exit), exiting",=
- forma= t_common_name(c, &gc));
+ msg(M_INFO, "%sInactivity timeout (--ping-exit), e= xiting", format_common_name(c, &gc));
= register_signal(c->sig, SIGTERM, "ping-exit");
break;


diff --git a/src/op= envpn/ping.h b/src/openvpn/ping.h
index 29ee2f2..48d4c0a 10= 0644
--- a/src/openvpn/ping.h
+++ b/src/ope= nvpn/ping.h
@@ -29,7 +29,7 @@
/* * Initial default --ping-restart before --pull
*= /
-#define PRE_PULL_INI= TIAL_PING_RESTART 120 /* in seconds */
+#define PRE_PULL_INITIAL_PING_RESTART 120 /* in seconds= */

extern const uint8_t ping_string[];<= /span>

@@ -59,11 +59,11 @@
chec= k_ping_restart(struct context *c)
{
i= f (c->options.ping_rec_timeout
- && event_timeout_trigger(&c->c2.ping_rec= _interval,
- = &c->c2.timeval,
+ && event_timeout_trigger(&c-&g= t;c2.ping_rec_interval, &c->c2.timeval,
= (!c->options.ping_timer_remote
= || link_socket_actual_defined(&c->c1= .link_socket_addrs[0].actual))
- ? ETT_DEFAULT : 15))
+ = ? ETT_DEFAULT

+ = : 15))
{ trigger_ping_timeout_signal(c);
}
@@ -76,8 +76,7 @@
check_ping_send(struct conte= xt *c)
{
if (c->options.ping_send_= timeout
- &&= amp; event_timeout_trigger(&c->c2.ping_send_interval,
- &am= p;c->c2.timeval,

+= && event_timeout_trigger(&c->c2.ping_send_interval, = &c->c2.timeval,
!T= O_LINK_DEF(c) ? ETT_DEFAULT : 1))
{
= check_ping_send_dowork(c);
diff --git a/src/openvpn/= pkcs11.c b/src/openvpn/pkcs11.c
index 0177b18..dfc87f6 1006= 44
--- a/src/openvpn/pkcs11.c
+++ b/src/ope= nvpn/pkcs11.c
@@ -39,51 +39,41 @@
#include= "console.h"
#include "pkcs11_backend.h&quo= t;

-s= tatic
-time_t+static time_t
__mytime(void)

{
return openvpn_tim= e(NULL);
}

#if !defined= (_WIN32)
-static=
-int
+static int
__mygettimeofday= (struct timeval *tv)
{
return gettime= ofday(tv, NULL);
}
#endif

-static
-void

+static void
__mysleep(const unsi= gned long usec)
{
#if defined(_WIN32)
- Sleep(usec/1000);
+ Sleep(usec / 1000);=
#else
usleep(usec);
= #endif
}


-static pkcs11h_engine_system_t s_p= kcs11h_sys_engine =3D {

- malloc,
- free= ,
- __mytime,=
- __mysleep,
+static pkcs11h_engine_system_t s_= pkcs11h_sys_engine =3D { malloc, free, __mytime, __mysleep,

#if defined(_WIN32)

-= NULL
+ = NULL
#else
- __mygettimeofday
+ = __mygettimeofday
#endif
};

-static
-= unsigned
-_pkcs11_msg_p= kcs112openvpn(
- con= st unsigned flags
- = )
+static unsigned
+_pkcs11_msg_pkcs112ope= nvpn(const unsigned flags)
{
unsigned= openvpn_flags;

@@ -121,11 +111,8 @@
return openvpn_flags;
}
=
-static
-unsigned

-_pkcs11_msg_openvpn2pkcs11(
- const unsigned flags
- )
+static unsigned
+_pkcs11_msg_openvpn2pkcs11(const unsigned flags) {
unsigned pkcs11_flags;

@@ -161,33 +148,23 @@
return pkcs11_flags= ;
}

-static
-void
-_pkcs11_openvpn= _log(
- void *const = global_data,
- unsig= ned flags,
- const c= har *const szFormat,
- = va_list args
- )<= /span>
+static void+_pkcs11_openvpn_log(void *co= nst global_data, unsigned flags, const char *const szFormat,
+ va_list args)<= /span>
{
- = char Buffer[10*1024];
- Buffer[sizeof(Buffer)-1] =3D 0;
+ Buffer[sizeof(Buffer) - 1] =3D 0;

msg(_pkcs11_msg_pkcs112openvpn(flags), "%s&qu= ot;, Buffer);
}

-static
-PKCS11H_BOOL
-_pkcs11_openvpn_token_prompt(
- void *const global_data,
- void *const user_data,
- const pkcs11h_token_id_t token,
- const unsigned retry

<= span style=3D"color: hsl(0, 100%, 40%);">- )

+static PKCS11H_BOOL
+_pkcs11_openvpn_token_prompt(void *const global= _data, void *const user_data,
+ const pkcs11h_token_id_t token, cons= t unsigned retry)
{
struct user_pass = token_resp;

@@ -195,26 +172,16 @@<= br> (void)user_data;
(void)retry;
=
- ASSERT(tok= en!=3DNULL);
+ ASS= ERT(token !=3D NULL);

CLEAR(token_re= sp);
token_resp.defined =3D false;
= token_resp.nocache =3D true;
- snprintf(
= - token_resp.username,
- sizeof(token_resp.username),
- "Please insert %s token",- token->label=
- );
+ snprintf(token_resp.username, siz= eof(token_resp.username), "Please insert %s token",
+ token->label);

- if= (
- !get_user_p= ass(
- &= token_resp,
- = NULL,
- &q= uot;token-insertion-request",
- GET_USER_PASS_MANAGEMENT|GET_USER_PASS_NEED_OK|GET= _USER_PASS_NOFATAL
- = )
- )
+ if (!get_user_pas= s(&token_resp, NULL, "token-insertion-request",
+ GET_USER_P= ASS_MANAGEMENT | GET_USER_PASS_NEED_OK | GET_USER_PASS_NOFATAL))

= {
return false;
}<= /span>
@@ -224,16 +191,10 @@
}
}


= -static
-PKCS11H_BOOL
-_pkcs11_openvpn_pin_pro= mpt(
- void *const g= lobal_data,
- void *= const user_data,
- c= onst pkcs11h_token_id_t token,
- const unsigned retry,
- char *const pin,
- const size_t pin_max
- )
= +static PKCS11H_BOOL
= +_pkcs11_openvpn_pin_prompt(void *const global_data, void *const user_data,=
+ = const pkcs11h_token_id_t token, const unsigned retry, char *const p= in,
+ = const size_t pin_max)
{
st= ruct user_pass token_pass;
char prompt[1024];@@ -243,21 +204,16 @@
(void)user_data;<= br> (void)retry;

- ASSERT(token!=3DNULL);
+ ASSERT(token !=3D NULL);
=
snprintf(prompt, sizeof(prompt), "%s token"= ;, token->label);

token_pass.defi= ned =3D false;
token_pass.nocache =3D true;
=
- if (
- !get_user_pass(

- &token_pa= ss,
- NULL,<= /span>
- prompt,
- GET_USER_PAS= S_MANAGEMENT|GET_USER_PASS_PASSWORD_ONLY|GET_USER_PASS_NOFATAL
- )

- )
+ if (!get_user_pass(&token_pass, NULL, prompt= ,
+ = GET_USER_PASS_MANAGEMENT | GET_USER_PASS_PASSWORD_ONLY
+ | GET_US= ER_PASS_NOFATAL))

{
return fa= lse;
}
@@ -278,21 +234,16 @@ }

bool
-pkcs11_initialize(
- const bool protected_auth,
- const int nPINCachePeriod
<= span style=3D"color: hsl(0, 100%, 40%);">- )

+pkcs11_initialize(const bool protected_auth, co= nst int nPINCachePeriod)
{
CK_RV rv = =3D CKR_FUNCTION_FAILED;

- dmsg(
- D_PKCS11_DEBUG,
- "PKCS#11: pkcs11_initialize - entered"<= br>- );
+ dmsg(D_PKCS11_DEBUG, "PKCS#11= : pkcs11_initialize - entered");

= if ((rv =3D pkcs11h_engine_setSystem(&s_pkcs11h_sys_engine)) !=3D CKR= _OK)
{
- msg(M_FATAL, "PKCS#11: Cannot initialize system engine %= ld-'%s'", rv, pkcs11h_getMessage(rv));
+ msg(M_FATAL, "PKCS#11: Canno= t initialize system engine %ld-'%s'", rv,
+ pkcs11h_getMessage(rv));
goto cleanup;
}
=
@@ -330,7 +281,8 @@

= if ((rv =3D pkcs11h_setProtectedAuthentication(protected_auth)) !=3D CKR_= OK)
{
- msg(M_FATAL, "PKCS#11: Cannot set protected authenticatio= n mode %ld-'%s'", rv, pkcs11h_getMessage(rv));
+ msg(M_FATAL, "PKCS#11:= Cannot set protected authentication mode %ld-'%s'", rv,
+ pkcs11h_getMe= ssage(rv));
goto cleanup;
}

@@ -343,12 +295,8 @@
= rv =3D CKR_OK;

cleanup:
- dmsg(
- D_PKCS11_DEBUG,
- "PKCS#11: pkcs11_initialize - retur= n %ld-'%s'",
- rv,
- = pkcs11h_getMessage(rv)
+ dm= sg(D_PKCS11_DEBUG, "PKCS#11: pkcs11_initialize - return %ld-'%s= 9;", rv,
+ = pkcs11h_getMessage(rv));

return r= v =3D=3D CKR_OK;
}
@@ -356,105 +304,85 @@<= /span>
void
pkcs11_terminate(void)
{

- dmsg(=
- D_PKCS11_DEBUG,
- "PKCS#11: pkc= s11_terminate - entered"
- );
+ = dmsg(D_PKCS11_DEBUG, "PKCS#11: pkcs11_terminate - entered");

pkcs11h_terminate();
=
- dmsg(
= - D_PKCS11_DEBUG,- "PKCS#11: pkcs11_= terminate - return"
+ dm= sg(D_PKCS11_DEBUG, "PKCS#11: pkcs11_terminate - return");<= br> }

bool
-pkcs11_addProvider(
- const char *const provider,
<= span style=3D"color: hsl(0, 100%, 40%);">- const bool protected_auth,
- const unsigned priva= te_mode,
- const boo= l cert_private
- )
+pkcs11_addProvider(co= nst char *const provider, const bool protected_auth,
+ const unsigned private= _mode, const bool cert_private)
{
CK_= RV rv =3D CKR_OK;

- ASSERT(provider!=3DNULL);
+ ASSERT(provider !=3D NULL);

- dmsg(
- D_PKCS11_DEBUG,

<= span style=3D"color: hsl(0, 100%, 40%);">- "PKCS#11: pkcs11_add= Provider - entered - provider=3D'%s', private_mode=3D%08x",
- provider,=
- private_mode<= br>- );
+ dmsg(D_PKCS11_DEBUG, "PKCS#11= : pkcs11_addProvider - entered - provider=3D'%s', private_mode=3D%0= 8x",
+ p= rovider, private_mode);

- msg(
- M_INFO,
= - "PKCS#11: Adding PKCS#11 provider '%s'",<= br>- provider
- );

+ msg(M_INFO, "PKCS#11: Adding PKC= S#11 provider '%s'", provider);

-#if PKCS11H_VERSION >=3D ((1<= ;<16) | (28<<8) | (0<<0))

+#if PKCS11H_VERSION >=3D ((1 << 16) | (28 <= ;< 8) | (0 << 0))
if ((rv =3D pkcs11h_registe= rProvider(provider)) !=3D CKR_OK)
{
- msg(M_WARN, "PKCS#11: Canno= t register provider '%s' %ld-'%s'", provider, rv, pkcs= 11h_getMessage(rv));
= + msg(M_WARN, "PKCS#11: Cannot register provider '%s' %= ld-'%s'", provider, rv,
+ pkcs11h_getMessage(rv));
= }
else
{
= PKCS11H_BOOL allow_protected_auth =3D protected_auth;
= PKCS11H_BOOL cert_is_private =3D cert_private;

- rv =3D pkcs11h_setP= roviderProperty(provider, PKCS11H_PROVIDER_PROPERTY_LOCATION, provider, str= len(provider) + 1);
+= rv =3D pkcs11h_setProviderProperty(provider, PKCS11H_PROVIDER_PROPE= RTY_LOCATION, provider,
+ strlen(provider) + 1);<= br>
if (rv =3D=3D CKR_OK)
= {
- = rv =3D pkcs11h_setProviderProperty(provider, PKCS11H_PROVIDER_PROPERTY_ALLO= W_PROTECTED_AUTH, &allow_protected_auth, sizeof(allow_protected_auth));=
+ rv =3D = pkcs11h_setProviderProperty(provider,
+ PKCS11H_PROV= IDER_PROPERTY_ALLOW_PROTECTED_AUTH,
+ &allow_pro= tected_auth, sizeof(allow_protected_auth));
}
if (rv =3D=3D CKR_OK)
{
- rv =3D pkcs11h_= setProviderProperty(provider, PKCS11H_PROVIDER_PROPERTY_MASK_PRIVATE_MODE, = &private_mode, sizeof(private_mode));
+ rv =3D pkcs11h_setProviderProperty(provid= er, PKCS11H_PROVIDER_PROPERTY_MASK_PRIVATE_MODE,
+ &= amp;private_mode, sizeof(private_mode));
}<= br> if (rv =3D=3D CKR_OK)
{- rv =3D pkcs11h_set= ProviderProperty(provider, PKCS11H_PROVIDER_PROPERTY_CERT_IS_PRIVATE, &= cert_is_private, sizeof(cert_is_private));
+ rv =3D pkcs11h_setProviderProperty(provi= der, PKCS11H_PROVIDER_PROPERTY_CERT_IS_PRIVATE,
+ &a= mp;cert_is_private, sizeof(cert_is_private));
}
#if defined(WIN32) && defined(PKCS11H_PROVIDER_PROPE= RTY_LOADER_FLAGS)
if (rv =3D=3D CKR_OK && = platform_absolute_pathname(provider))
{
= - unsigned loader_flag= s =3D LOAD_LIBRARY_SEARCH_DEFAULT_DIRS | LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR;<= /span>
- rv =3D pkc= s11h_setProviderProperty(provider, PKCS11H_PROVIDER_PROPERTY_LOADER_FLAGS, = &loader_flags, sizeof(loader_flags));
+ unsigned loader_flags =3D
+ LOAD_LIBRARY_SEARCH= _DEFAULT_DIRS | LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR;

+ rv =3D pkcs11h_setProviderPropert= y(provider, PKCS11H_PROVIDER_PROPERTY_LOADER_FLAGS,
+ = &loader_flags, sizeof(loader_flags));
}
#endif

if (rv != =3D CKR_OK || (rv =3D pkcs11h_initializeProvider(provider)) !=3D CKR_OK)
{
+ msg(M_WARN, &= quot;PKCS#11: Cannot initialize provider '%s' %ld-'%s'"= ;, provider, rv,
+ = pkcs11h_getMessage(rv));
pkcs11h_= removeProvider(provider);
}
}=
#else /* if PKCS11H_VERSION >=3D ((1<<16) | (28= <<8) | (0<<0)) */
- if (
- = (rv =3D pkcs11h_addProvider(
- provider,
- provider,
- protected_auth,
- private_mode,
- PKCS11H_SLOTEVENT_METHOD_AUTO,<= br>- 0,
- cert_private
- )) !=3D CKR_OK
- )
+ if ((rv =3D pkcs11h_addProvider= (provider, provider, protected_auth, private_mode,

+ PKCS11H_SL= OTEVENT_METHOD_AUTO, 0, cert_private))
+ !=3D CKR_OK)
{
- msg(M_WARN, "PKCS#11:= Cannot initialize provider '%s' %ld-'%s'", provider, = rv, pkcs11h_getMessage(rv));

+ msg(M_WARN, "PKCS#11: Cannot initialize provider '= ;%s' %ld-'%s'", provider, rv,
+ pkcs11h_getMessage(rv));
<= span> }

#endif /* if PKCS11H_VERSION >=3D ((1<&l= t;16) | (28<<8) | (0<<0)) */

- dmsg(
- D_PKCS11_DEBUG,
- "PKCS#11: pkcs11_addProvider - retu= rn rv=3D%ld-'%s'",
- rv,
-= pkcs11h_getMessage(rv)
- );
+= dmsg(D_PKCS11_DEBUG, "PKCS#11: pkcs11_addProvider - return rv=3D%l= d-'%s'", rv,
+ pkcs11h_getMessage(rv));

= return rv =3D=3D CKR_OK;
}
@@ -473,20 = +401,11 @@
CK_RV rv =3D CKR_OK;
i= nt count =3D 0;

- dmsg(
-= D_PKCS11_DEBUG,
- "PKCS#11: pkcs11_management_id_count - entered"<= br>- );
+ dmsg(D_PKCS11_DEBUG, "PKCS#11= : pkcs11_management_id_count - entered");

= - if (
- (rv =3D pkcs11h_certificate_enumCer= tificateIds(
- = PKCS11H_ENUM_METHOD_CACHE_EXIST,
- NULL,
- PKCS11H_PROMPT_MASK_ALLOW_ALL,
- NULL,
- &id_list
- )) !=3D CKR_OK
<= span style=3D"color: hsl(0, 100%, 40%);">- )

+ if ((rv =3D pkcs11h_certificate_enumC= ertificateIds(PKCS11H_ENUM_METHOD_CACHE_EXIST, NULL,
+ = PKCS11H_PROMPT_MASK_ALLOW_ALL, NULL, &id_list))
<= span style=3D"color: hsl(120, 100%, 40%);">+ !=3D CKR_OK)

= {
msg(M_WARN, "PKCS#11: Cannot get= certificate list %ld-'%s'", rv, pkcs11h_getMessage(rv));
goto cleanup;
@@ -502,21 +421,13 @@
pkcs11h_certificate_freeCertificateIdList(id_list);
id_list =3D NULL;

- dmsg(
- D_PKCS11_DEBUG,
- "PKCS#11: pkcs11_management_id_count - r= eturn count=3D%d",
- count
- = );
+ dmsg(D_PKCS= 11_DEBUG, "PKCS#11: pkcs11_management_id_count - return count=3D%d&quo= t;, count);

return count;
= }

bool
-pkcs11_management_id_get(
- const int index,
- char **id,
- char **base64
- )
+pkcs11_management_id_get(const int index, char **id, char **base64)<= /span>
{
pkcs11h_certificate_id_list_t id_li= st =3D NULL;
pkcs11h_certificate_id_list_t entry =3D N= ULL;
@@ -533,27 +444,17 @@
int count = =3D 0;
bool success =3D false;

- ASSERT(id!=3DNULL);
- ASSERT(base64!=3DNULL= );
+ ASSERT(id != =3D NULL);
+ ASSER= T(base64 !=3D NULL);

- dmsg(
- D_PKCS11_DEBUG,
- "PKCS#11: pkcs11_management_id_get - entered index=3D%d= ",
- index<= /span>
- );
<= span style=3D"color: hsl(120, 100%, 40%);">+ dmsg(D_PKCS11_DEBUG, "= PKCS#11: pkcs11_management_id_get - entered index=3D%d", index);

*id =3D NULL;
*base6= 4 =3D NULL;

- if (
- = (rv =3D pkcs11h_certificate_enumCertificateIds(
- PKCS11H_ENUM_METHOD_CACHE_EXIST,<= /span>
- NULL,
- PKCS11H_PROM= PT_MASK_ALLOW_ALL,
- = NULL,
- = &id_list
- = )) !=3D CKR_OK
- )
+ if= ((rv =3D pkcs11h_certificate_enumCertificateIds(PKCS11H_ENUM_METHOD_CACHE_= EXIST, NULL,
+ = PKCS11H_PROMPT_MASK_ALLOW_ALL= , NULL, &id_list))
- dmsg(
- D_PKCS11_DEBUG,
- "PKCS#11: pkcs11_management_id_get - no = certificate at index=3D%d",
- index
- );
+ dmsg(D_PKCS11_DEBUG, "PKCS#11: pkcs11_management_id_get - no= certificate at index=3D%d",
+ index);
goto cleanup;
}

- if (
- (rv =3D pkcs11h_certificate_serializeCertificateId(
= - NULL,
- &max,

- entry->certificate= _id

- )) != =3D CKR_OK
- )
+ if ((rv =3D pkcs1= 1h_certificate_serializeCertificateId(NULL, &max, entry->certificate= _id))
+ !=3D C= KR_OK)
{
- msg(M_WARN, "PKCS#11: Cannot serialize certificate id = %ld-'%s'", rv, pkcs11h_getMessage(rv));
+ msg(M_WARN, "PKCS#11: Cannot= serialize certificate id %ld-'%s'", rv,
+ pkcs11h_getMessage(rv));
goto cleanup;
}
=
@@ -595,39 +489,24 @@
goto cleanu= p;
}

- if (
- (rv =3D pkcs11h_certificate_serializeCertificateId(=
- internal_id,
- &max,
- entry->= certificate_id
- = )) !=3D CKR_OK
- = )
+ if ((rv= =3D pkcs11h_certificate_serializeCertificateId(internal_id, &max, entr= y->certificate_id))
- msg(M_WARN, "PKCS#11: Cannot serializ= e certificate id %ld-'%s'", rv, pkcs11h_getMessage(rv));
+ msg(M_WARN, "= ;PKCS#11: Cannot serialize certificate id %ld-'%s'", rv,
+ pkcs11h_getMe= ssage(rv));
goto cleanup;
}

- i= f (
- (rv =3D pk= cs11h_certificate_create(
- entry->certificate_id,
- NULL,
- PKCS11H_PROMPT_MASK_ALLOW_ALL,
- PKCS11H_PIN_CACHE_INFI= NITE,

- &am= p;certificate
- = )) !=3D CKR_OK
- = )
+ if ((rv = =3D pkcs11h_certificate_create(entry->certificate_id, NULL, PKCS11H_PROM= PT_MASK_ALLOW_ALL,
+ = PKCS11H_PIN_CACHE_INFINITE, &ce= rtificate))
+ = !=3D CKR_OK)
{
msg(M_WARN, &q= uot;PKCS#11: Cannot get certificate %ld-'%s'", rv, pkcs11h_get= Message(rv));
goto cleanup;
}=

- = if (
- (rv =3D = pkcs11h_certificate_getCertificateBlob(
- certificate,
- NULL,
- &certificate_blob_size
- )) !=3D CKR_OK
= - )
+ if ((rv =3D pkcs11h_certificate_getCe= rtificateBlob(certificate, NULL, &certificate_blob_size))
+ !=3D CKR_OK)

{

msg(M_WARN, "PKCS#11: Cannot get c= ertificate blob %ld-'%s'", rv, pkcs11h_getMessage(rv));=
goto cleanup;
@@ -639,13 +518,9 @@
goto cleanup;
}
<= /span>
- if (
- (rv =3D pkcs11h_certificate= _getCertificateBlob(

- = certificate,
- &certificate_blob_size
- )) !=3D CKR_OK
- )

+ if ((rv =3D pkcs11h_certificate_getCertific= ateBlob(certificate, certificate_blob,
+ &am= p;certificate_blob_size))
+ !=3D CKR_OK)
{
= msg(M_WARN, "PKCS#11: Cannot get certificate blob %ld-'%s'&quo= t;, rv, pkcs11h_getMessage(rv));
goto cleanup;
@@ -677,22 +552,15 @@
free(certificate_bl= ob);
certificate_blob =3D NULL;

- dmsg(
- D_PKCS11_DEBUG,
- "PKCS#11: pkcs11_manage= ment_id_get - return success=3D%d, id=3D'%s'",

- success ? 1 : 0,

- *id

- );
+ dmsg(D_PKCS11_DEBUG, "PKCS#11: pkcs11_manag= ement_id_get - return success=3D%d, id=3D'%s'",
+ success ? 1 : 0, *id);

return success;
}

int
-tls_ctx_use_pkcs11(
- struct tls_root_ctx *const ssl_ctx,
- bool pkcs11_id_management,
- const char *const pkcs11_id
- )
+tls_ctx_use_pkcs11(struct tls_root_ctx= *const ssl_ctx, bool pkcs11_id_management,
+ const char *const pkcs11_id)
{
pkcs11h_certificate_id_t certificate_i= d =3D NULL;
pkcs11h_certificate_t certificate =3D NULL= ;
@@ -700,16 +568,13 @@

= bool ok =3D false;

- ASSERT(ssl_ctx!=3DNULL);
- ASSERT(pkcs11_id_management || pkcs11_id!=3DN= ULL);
+ ASSERT(ssl= _ctx !=3D NULL);
+ = ASSERT(pkcs11_id_management || pkcs11_id !=3D NULL);

dmsg(
D_PKCS11_DEBUG,
= "PKCS#11: tls_ctx_use_pkcs11 - entered - ssl_ctx=3D%p, = pkcs11_id_management=3D%d, pkcs11_id=3D'%s'",
- (void *)ssl_ctx,
- pkcs11_id_management ? 1 : = 0,

- pkcs11_id
- );
+ (void *)ssl_ctx, pkcs11_= id_management ? 1 : 0, pkcs11_id);


i= f (pkcs11_id_management)
{
@@ -719,30 = +584,17 @@

id_resp.defined =3D f= alse;
id_resp.nocache =3D true;
- snprintf(
- id_resp.username,
- sizeof(id_resp.username= ),

- "P= lease specify PKCS#11 id to use"
- );
+ snprintf(id_resp.username, sizeof(id_resp.username), &qu= ot;Please specify PKCS#11 id to use");

- if (

- !get_user_pass(
- &id_resp,
<= br>- NULL,<= br>- "pkcs11-= id-request",
- = GET_USER_PASS_MANAGEMENT|GET_USER_PASS_NEED_STR|GET_USER_PASS_N= OFATAL
- = )
- )
+ if (!get_user_pas= s(&id_resp, NULL, "pkcs11-id-request",
+ GET_USER_PASS_= MANAGEMENT | GET_USER_PASS_NEED_STR
+ | GET_USER_PASS_NOFATAL))
{
goto cleanup;<= br> }

- if (
- (rv =3D pkcs11h_certificate_deserializeCertificateId(
- &ce= rtificate_id,
- = id_resp.password
- )) !=3D CKR_OK
- )
+ if ((rv =3D pkcs11h_certificate_deserializeCertificateId(&a= mp;certificate_id, id_resp.password))
+ !=3D CKR_OK)
{
msg(M_WARN, "PKCS#11: Cannot deserialize id %l= d-'%s'", rv, pkcs11h_getMessage(rv));
= goto cleanup;
@@ -750,38 +602,23 @@
= }
else
{
- if (
- (rv =3D pkcs11h_certificate_deserializeC= ertificateId(
- = &certificate_id,
- pkcs11_id
- )) !=3D CKR_OK
- )
+ if ((rv =3D pkcs11h_certificate_deserializeCertifi= cateId(&certificate_id, pkcs11_id))
+ !=3D CKR_OK)
{
msg(M_WARN, "PKCS#11: Cannot deserialize id = %ld-'%s'", rv, pkcs11h_getMessage(rv));
= goto cleanup;
}
}

- if (=
- (rv =3D pkcs1= 1h_certificate_create(
= - certificate_id,
- NULL,
- PKCS11H_PROMPT_MASK_ALLOW_ALL,
- PKCS11H_PIN_CACHE_INFINITE,<= br>- &certificate=
- )) !=3D = CKR_OK
- )
+ if ((rv =3D pkcs11h_c= ertificate_create(certificate_id, NULL, PKCS11H_PROMPT_MASK_ALLOW_ALL,
+ = PKCS11H_PIN_CACHE_INFINITE, &certificate))
<= span style=3D"color: hsl(120, 100%, 40%);">+ !=3D CKR_OK)

= {
msg(M_WARN, "PKCS#11: Cannot get= certificate %ld-'%s'", rv, pkcs11h_getMessage(rv)); goto cleanup;
}

- if (
- (pkcs11_init_tls_session(
- certificate,
- ssl_ctx
- ))- )
+ if ((pkcs11_init_tls_session(certifi= cate, ssl_ctx)))
{
/* Handled= by SSL context free */
certificate =3D NULL;
@@ -805,26 +642,15 @@
certificate_id = =3D NULL;
}

- dmsg(
- D_PKCS11_DEBUG,
- "PKCS#11: tls_ctx_use_pkcs11 - return ok=3D= %d, rv=3D%ld",
- = ok ? 1 : 0,
- = rv
- );
+ dmsg(D_PKCS11_DEBUG,= "PKCS#11: tls_ctx_use_pkcs11 - return ok=3D%d, rv=3D%ld", ok ? 1= : 0, rv);

return ok ? 1 : 0;=
}

-static
-PKCS11= H_BOOL
-_pkcs11_openvpn= _show_pkcs11_ids_pin_prompt(
- void *const global_data,
- void *const user_data,
- const pkcs11h_token_id_t token,
- const unsigned retry,
- char *const pin,
- const size_t pin_max
- )

+static PKCS11H_BOOL
+_pkcs11_openvpn_show_pkcs11_ids_pin_prompt(void *c= onst global_data, void *const user_data,
+ const pkcs1= 1h_token_id_t token, const unsigned retry,
+ char *con= st pin, const size_t pin_max)
{
struc= t gc_arena gc =3D gc_new();
struct buffer pass_prompt = =3D alloc_buf_gc(128, &gc);
@@ -833,11 +659,10 @@
(void)user_data;
(void)retry;
- ASSERT(t= oken!=3DNULL);
+ A= SSERT(token !=3D NULL);

buf_printf(&= amp;pass_prompt, "Please enter '%s' token PIN or 'cancel&#= 39;: ", token->display);
- if (!query_user_SINGLE(BSTR(&pass_prompt), BLEN(&pas= s_prompt),
- = pin, pin_max, false))
+ if (!query_user_SINGLE(BSTR(&pass_prompt), BLEN(&= amp;pass_prompt), pin, pin_max, false))
{
msg(M_FATAL, "Could not retrieve the PIN");
}
@@ -855,10 +680,7 @@
}

void
-show_pkcs11_ids(
- const char *const provider,
- bool cert_private
- )
+show_pkcs11_ids(const char *const provider, bool cert_private)<= br> {
struct gc_arena gc =3D gc_new(); pkcs11h_certificate_id_list_t user_certificates =3D NULL;
@@ -881,7 +703,8 @@

if ((= rv =3D pkcs11h_setProtectedAuthentication(TRUE)) !=3D CKR_OK)
{

- msg(= M_FATAL, "PKCS#11: Cannot set protected authentication %ld-'%s'= ;", rv, pkcs11h_getMessage(rv));
+ msg(M_FATAL, "PKCS#11: Cannot set protected = authentication %ld-'%s'", rv,
+ pkcs11h_getMessage(rv));
goto cleanup;

}

= @@ -897,118 +720,77 @@
goto cleanup;<= br> }

- if (
- = (rv =3D pkcs11h_certificate_enumCertificateIds(
- PKCS11H_ENUM_METHOD_CACHE_EXI= ST,
- NULL,=
- PKCS11H_= PROMPT_MASK_ALLOW_ALL,
= - NULL,
- = &user_certificates
- )) !=3D CKR_OK
- )
+ if ((rv =3D pkcs11h_certificate_enumCertificateIds(PKCS11H_ENUM= _METHOD_CACHE_EXIST, NULL,
+ PKCS11H_PROMPT_= MASK_ALLOW_ALL, NULL,
+ &user_certificat= es))
+ !=3D CK= R_OK)
{
msg(M_FATAL, "PK= CS#11: Cannot enumerate certificates %ld-'%s'", rv, pkcs11h_ge= tMessage(rv));
goto cleanup;
= }

- = msg(
- M_INFO|= M_NOPREFIX|M_NOLF,
- = (
- &qu= ot;\n"
- = "The following objects are available for use.\n"
- "Each object shown = below may be used as parameter to\n"

- "--pkcs11-id option please remember to= use single quote mark.\n"
- )
- = );
+ msg(M_I= NFO | M_NOPREFIX | M_NOLF,
+ ("\n"
+ "The following objects are available for use.\n&qu= ot;
+ "E= ach object shown below may be used as parameter to\n"
+ "--pkcs11-id option pl= ease remember to use single quote mark.\n"));
for= (current =3D user_certificates; current !=3D NULL; current =3D current->= ;next)
{
pkcs11h_certificate_= t certificate =3D NULL;
char *dn =3D NULL;<= br>- char serial[1024] =3D= {0};
+ char s= erial[1024] =3D { 0 };
char *ser =3D NULL;<= br> size_t ser_len =3D 0;

- if (
- (rv =3D pkcs11h_certificate_serializ= eCertificateId(
- = NULL,
- = &ser_len,
- current->certificate_id
- )) !=3D CKR_OK
- )
+ if ((rv =3D pkcs11h_certificate_seria= lizeCertificateId(NULL, &ser_len,
+ = current->certificate_id))
+ !=3D CKR_OK)
{
= - msg(M_FATAL, "P= KCS#11: Cannot serialize certificate %ld-'%s'", rv, pkcs11h_ge= tMessage(rv));
+ = msg(M_FATAL, "PKCS#11: Cannot serialize certificate %ld-'%s= '", rv,
+ = pkcs11h_getMessage(rv));
goto cle= anup1;
}

- if (
- rv =3D=3D CKR_OK
- && (ser =3D (char *)mal= loc(ser_len)) =3D=3D NULL
- )
+ = if (rv =3D=3D CKR_OK && (ser =3D (char *)malloc(ser_len)) =3D= =3D NULL)
{
msg(M_FAT= AL, "PKCS#11: Cannot allocate memory");
= goto cleanup1;
}

<= span style=3D"color: hsl(0, 100%, 40%);">- if (

- (rv =3D pkcs11h_certificate_se= rializeCertificateId(
-= ser,
-= &ser_len,
- current->certificate_id
- )) !=3D CKR_OK
<= span style=3D"color: hsl(0, 100%, 40%);">- )

+ if ((rv =3D
+ pkcs11h_certificate_se= rializeCertificateId(ser, &ser_len, current->certificate_id))=
+ !=3D CKR_OK)
{
- msg(M_FATAL, "PKCS#11: Cannot serialize certificate %l= d-'%s'", rv, pkcs11h_getMessage(rv));
+ msg(M_FATAL, "PKCS#11: Cann= ot serialize certificate %ld-'%s'", rv,
+ pkcs11h_getMessage(rv));<= /span>
goto cleanup1;
}

- = if (
- (rv = =3D pkcs11h_certificate_create(
- current->certificate_id,
- NULL,
- PKCS11H_PROMPT_MASK_ALLO= W_ALL,
- = PKCS11H_PIN_CACHE_INFINITE,
- &certificate
- ))
- )
+ if ((rv =3D pkcs11h_certificate_create(current->cert= ificate_id, NULL,
+ = PKCS11H_PROMPT_MASK_ALLOW_ALL,
+ = PKCS11H_PIN_CACHE_INFINITE, &certificate)))
{
msg(M_FATAL, "PKC= S#11: Cannot create certificate %ld-'%s'", rv, pkcs11h_getMess= age(rv));
goto cleanup1;
= }

- if (
- = (dn =3D pkcs11_certificate_dn(
- certificate,
- &gc
- )) =3D=3D NULL
- )
+ if ((dn =3D pkcs11_certificate_dn(cert= ificate, &gc)) =3D=3D NULL)
{
= goto cleanup1;
}

- if (
<= span style=3D"color: hsl(0, 100%, 40%);">- (pkcs11_certificate_s= erial(

- = certificate,
- = serial,
- = sizeof(serial)
- ))
- )
+ = if ((pkcs11_certificate_serial(certificate, serial, sizeof(serial))))=
{
goto cleanup1;
}

- msg(
- M_INFO|M_NOPREFIX|M_NOLF,
- (
- "\n"
- "Certificate\n"
- " = DN: %s\n"
- " Serial: %s\n"
- " Seria= lized id: %s\n"

-= ),
- = dn,
- s= erial,
- ser=
- );=
+ msg(M_INFO | M_NOP= REFIX | M_NOLF,
+ = ("\n"
+ "Certificate\n"
+ " DN: %s\n"=
+ "= Serial: %s\n"
+ " Serialized id: %s\n"),=
+ dn, serial, se= r);

cleanup1:
diff --git a/src/openvpn/pkcs11.h b/src/openvpn/pkcs11.h
= index 644d7ce..d431db1 100644
--- a/src/openvpn/pkcs1= 1.h
+++ b/src/openvpn/pkcs11.h
@@ -27,49 +2= 7,24 @@

#include "ssl_common.h"= ;

-bo= ol
-pkcs11_initialize(<= /span>
- const bool fProtec= tedAuthentication,
- = const int nPINCachePeriod
- );
+bool pkc= s11_initialize(const bool fProtectedAuthentication, const int nPINCachePeri= od);

= -void
-pkcs11_terminate= (void);
+void pkcs11_= terminate(void);

-bool
-pkcs= 11_addProvider(
- co= nst char *const provider,
- const bool fProtectedAuthentication,
- const unsigned private_mode,
- const bool fCertIsPrivate
<= span style=3D"color: hsl(0, 100%, 40%);">- );

+bool pkcs11_addProvider(const char *const prov= ider, const bool fProtectedAuthentication,
+ const unsigned private_mode,= const bool fCertIsPrivate);

-int
-pkcs11_logout(void);
+int pkcs11_logout(void);

-int
-pkcs11_management_id_count(void);
+int pkcs11_management_id_count(void);

-bool
<= span style=3D"color: hsl(0, 100%, 40%);">-pkcs11_management_id_get(
<= br>- const int index,- char **id,
- char **base64

- );
+bool pkcs11_management_id_get(const int index, char **= id, char **base64);

-int
-tl= s_ctx_use_pkcs11(
- = struct tls_root_ctx *const ssl_ctx,
- bool pkcs11_id_management,
- const char *const pkcs11_id
- );
+int tls_ctx_use_pkcs11(struct tls_root_ctx *const ssl_c= tx, bool pkcs11_id_management,
+ const char *const pkcs11_id);
<= span>

-void
= -show_pkcs11_ids(
- const char *const provider,
- bool cert_private
- );
+void show_pkcs11_ids(const char *const p= rovider, bool cert_private);

-#endif /* ENABLE_PKCS11 */=
+#endif /* ENABLE_PKCS11 */=

-#en= dif /* OPENVPN_PKCS11H_H */
+#endif /* OPENVPN_PKCS11H_H */
dif= f --git a/src/openvpn/pkcs11_backend.h b/src/openvpn/pkcs11_backend.h
index f65ba3f..caa0735 100644
--- a/src/openvpn/= pkcs11_backend.h
+++ b/src/openvpn/pkcs11_backend.h<= br>@@ -56,8 +56,7 @@
*
* @return = 1 on failure, 0 on success
*/
-int pkcs11_certificate_serial(pkcs11= h_certificate_t certificate, char *serial,

- size_t serial_len);
+int pkcs11_certificate_s= erial(pkcs11h_certificate_t certificate, char *serial, size_t serial_len);<= /span>

/**
* Load PKCS #11 Ce= rtificate's information into the given TLS context
@@ -= 67,8 +66,7 @@
*
* @return = 1 on failure, 0 on success
*/
-int pkcs11_init_tls_session(pkcs11h_certificate_t= certificate,
- = struct tls_root_ctx *const ssl_ctx);
+int pkcs11_init_tls_session(pkcs11h_ce= rtificate_t certificate, struct tls_root_ctx *const ssl_ctx);

#endif /* defined(ENABLE_PKCS11) */
= #endif /* PKCS11_BACKEND_H_ */
diff --git a/src/openvpn/pkc= s11_mbedtls.c b/src/openvpn/pkcs11_mbedtls.c
index d1c8957.= .245aa8d 100644
--- a/src/openvpn/pkcs11_mbedtls.c+++ b/src/openvpn/pkcs11_mbedtls.c
@@ -46,16 +46,14= @@
size_t cert_blob_size =3D 0;
= bool ret =3D false;

- if (pkcs11h_certificate_getCertificateBlob(pkcs11_cert,= NULL,
- = &cert_blob_size) !=3D CKR_OK)+ if (pkcs11h_certificate_g= etCertificateBlob(pkcs11_cert, NULL, &cert_blob_size) !=3D CKR_OK)
{
msg(M_WARN, "PKCS#11: Cann= ot retrieve certificate object size");
goto c= leanup;
}

check= _malloc_return((cert_blob =3D calloc(1, cert_blob_size)));
- if (pkcs11h_certificate_getCertifi= cateBlob(pkcs11_cert, cert_blob,
- &cert_blob_si= ze) !=3D CKR_OK)
+ = if (pkcs11h_certificate_getCertificateBlob(pkcs11_cert, cert_blob, &ce= rt_blob_size) !=3D CKR_OK)
{
= msg(M_WARN, "PKCS#11: Cannot retrieve certificate object");
goto cleanup;
@@ -74,16 +72,14 @@
}

static bool
-pkcs11_sign(void *pkcs11_cert, const= void *src, size_t src_len,

- void *dst, size_t dst_len)
+pkcs11_sign(void *pkcs11_cert, const void *src, si= ze_t src_len, void *dst, size_t dst_len)
{
- return CKR_OK =3D=3D pkcs11h_cert= ificate_signAny(pkcs11_cert, CKM_RSA_PKCS,

- src, = src_len, dst, &dst_len);
+ return CKR_OK
+ =3D=3D pkcs11h_certificate_signAny(pkcs11_cert, CKM_RSA_P= KCS, src, src_len, dst, &dst_len);
}
=
int
-= pkcs11_init_tls_session(pkcs11h_certificate_t certificate,
- struct tls_roo= t_ctx *const ssl_ctx)
+pkcs11_init_tls_session(pkcs11h_certificate_t certificate, struct tls_roo= t_ctx *const ssl_ctx)
{
ASSERT(NULL != =3D ssl_ctx);

@@ -130,8 +126,7 @@<= br> }

int
-pkcs11_certificate_serial(pkcs11h_certificate_= t cert, char *serial,
-= size_t serial_len)
+pkcs11_certificate_serial(pkcs11h_certificate_t ce= rt, char *serial, size_t serial_len)
{
= int ret =3D 1;
mbedtls_x509_crt mbed_crt =3D { 0 };<= /span>
diff --git a/src/openvpn/pkcs11_openssl.c b/src/openvpn/pkc= s11_openssl.c
index 489aa35..a912747 100644
--- a/src/openvpn/pkcs11_openssl.c

+++ b/src/openvpn/pkcs1= 1_openssl.c
@@ -43,18 +43,21 @@
#ifdef HAV= E_XKEY_PROVIDER
static XKEY_EXTERNAL_SIGN_fn xkey_pkcs11h_= sign;

-#if PKCS11H_VERSION > ((1<<16) | (27<<8)) /* version > = 1.27 */
+#if PKCS11H_= VERSION > ((1 << 16) | (27 << 8)) /* version > 1.27 */

/* Table linking OpenSSL digest NID with C= KM and CKG constants in PKCS#11 */
-#define MD_TYPE(n) {NID_sha ## n, CKM_SHA ## n, CKG_MGF1_SHA #= # n}
+#define MD_TYPE= (n) { NID_sha##n, CKM_SHA##n, CKG_MGF1_SHA##n }
static con= st struct
{
int nid;
= unsigned long ckm_id;
unsigned long mgf_id;
-} mdtypes[] =3D {MD_TYPE(22= 4), MD_TYPE(256), MD_TYPE(384), MD_TYPE(512),
- {NID_sha1, CKM_SHA_1, CKG_MGF1_SHA1}= , /* SHA_1 naming is an oddity */
- {NID_undef, 0, 0}};
+} mdtypes[] =3D { MD_TYPE(224),
+ MD_TYPE(256),=
+ MD_TYPE(38= 4),
+ = MD_TYPE(512),
+ = { NID_sha1, CKM_SHA_1, CKG_MGF1_SHA1 }, /* SHA_1 naming is an odd= ity */
+ = { NID_undef, 0, 0 } };

/* From sigalg= , derive parameters for pss signature and fill in pss_params.
* Its of type CK_RSA_PKCS_PSS_PARAMS struct with three fields to be f= illed in:

@@ -62,15 +65,13 @@
* where has= hAlg is CKM_SHA256 etc., mgf is CKG_MGF1_SHA256 etc.
*/
static int
-set_pss_params(CK_RSA_PKCS_PSS_PARAMS *pss_params, XKEY_SIGALG sigalg,=
- pkcs11= h_certificate_t cert)
+set_pss_params(CK_RSA_PKCS_PSS_PARAMS *pss_params, XKEY_SIGALG sigalg, pk= cs11h_certificate_t cert)
{
int ret = =3D 0;
X509 *x509 =3D NULL;
EVP_P= KEY *pubkey =3D NULL;

- if ((x509 =3D pkcs11h_openssl_getX509(cert)) =3D=3D N= ULL
- || (pubkey= =3D X509_get0_pubkey(x509)) =3D=3D NULL)
+ if ((x509 =3D pkcs11h_openssl_getX509(cert)) =3D= =3D NULL || (pubkey =3D X509_get0_pubkey(x509)) =3D=3D NULL)
{

msg(M_WARN, "PKCS#11: Unable get pub= lic key");
goto cleanup;
@@ -= 90,8 +91,10 @@
const EVP_MD *md =3D EVP_get_digestbyna= me(sigalg.mdname);
if (!md)
{
- msg(M_WARN, "= ;WARN: set_pss_params: EVP_get_digestbyname returned NULL "
= - "for mdname =3D= <%s>", sigalg.mdname);
+ msg(M_WARN,
+ "WARN: set_pss_params: EVP_get_digestbyname= returned NULL "
+ "for mdname =3D <%s>",
+ sigalg.mdname);
goto cleanup;

}
int m= dsize =3D EVP_MD_get_size(md);
@@ -108,14 +111,16 @@=

if (saltlen < 0 || pss_params->hashA= lg =3D=3D 0)
{
- msg(M_WARN, "WARN: invalid RSA_PKCS1_PSS paramet= ers: saltlen =3D <%s> "
- "mdname =3D <%s>.", sigalg.saltlen= , sigalg.mdname);
+ = msg(M_WARN,
+ = "WARN: invalid RSA_PKCS1_PSS parameters: saltlen =3D <%s&= gt; "
+ = "mdname =3D <%s>.",
+ sigalg.saltlen, sigalg.mdname);
goto cleanup;

}
- pss_params->sLen =3D (unsigned long) sal= tlen; /* saltlen >=3D 0 at this point */
+ pss_params->sLen =3D (unsigned long)saltlen;= /* saltlen >=3D 0 at this point */

- msg(D_XKEY, "set_pss_params: sL= en =3D %lu, hashAlg =3D %lu, mgf =3D %lu",
- pss_params->sLen, pss_params->hashA= lg, pss_params->mgf);
+ msg(D_XKEY, "set_pss_params: sLen =3D %lu, hashAlg =3D %lu, m= gf =3D %lu", pss_params->sLen,
+ pss_params->hashAlg, pss_params->mgf);

ret =3D 1;

= @@ -138,14 +143,14 @@
* is PSS in which case we ret= urn an error.
*/
static CK_RV
= -pkcs11h_certificate_signAny_ex(c= onst pkcs11h_certificate_t cert,
- const CK_MECHANISM *mech, const u= nsigned char *tbs,
- = size_t tbslen, unsigned char *sig, size_t *sigl= en)
+pkcs11h_certific= ate_signAny_ex(const pkcs11h_certificate_t cert, const CK_MECHANISM *mech,<= /span>
+ = const unsigned char *tbs, size_t tbslen, unsigned char *sig,
+ = size_t *siglen)
{
if (mech-&g= t;mechanism =3D=3D CKM_RSA_PKCS_PSS)
{
msg(M_NONFATAL, "PKCS#11: Error: PSS padding is not supporte= d by "

- = "this version of pkcs11-helper library.");
+ "this versi= on of pkcs11-helper library.");
return CKR_ME= CHANISM_INVALID;
}
return pkcs11h= _certificate_signAny(cert, mech->mechanism, tbs, tbslen, sig, siglen);
@@ -158,12 +163,12 @@
* We support ECDSA, = RSA_NO_PADDING, RSA_PKCS1_PADDING, RSA_PKCS_PSS_PADDING
*= /
static int
-xkey_pkcs11h_sign(void *handle, unsigned char *sig,
- size_t *siglen, con= st unsigned char *tbs, size_t tbslen, XKEY_SIGALG sigalg)

+xkey_pkcs11h_sign(void *handle, unsig= ned char *sig, size_t *siglen, const unsigned char *tbs,
+ size_t tbslen, XKEY_= SIGALG sigalg)
{
pkcs11h_certificate_= t cert =3D handle;
- = CK_MECHANISM mech =3D {CKM_RSA_PKCS, NULL, 0}; /* default value */<= br>- CK_RSA_PKCS_PSS_PARAMS ps= s_params =3D {0};
+ = CK_MECHANISM mech =3D { CKM_RSA_PKCS, NULL, 0 }; /* default value */
+ CK_RSA_PKCS_PSS_PARA= MS pss_params =3D { 0 };

unsigned ch= ar buf[EVP_MAX_MD_SIZE];
size_t buflen =3D 0;@@ -178,7 +183,7 @@
if (xkey_digest(tbs, t= bslen, buf, &buflen, sigalg.mdname))
{<= br> tbs =3D buf;
- tbslen =3D (size_t) buflen;
+ tbslen =3D (size_t)buflen;
sigalg.op =3D "Sign";
= }
else
@@ -194,8 +199,7 @= @
}
else if (!strcmp(sigalg.keyty= pe, "RSA"))
{
- msg(D_XKEY, "xkey_pkcs11h_sign: signing= with RSA key: padmode =3D %s",
- sigalg.padmode);
+ msg(D_XKEY, "xkey_pkcs11h_sign: signin= g with RSA key: padmode =3D %s", sigalg.padmode);
= if (!strcmp(sigalg.padmode, "none"))
= {
mech.mechanism =3D CKM_RSA_X_509;@@ -230,11 +234,10 @@
}
e= lse
{
- ASSERT(0); /* coding error -- we couldnt have created any suc= h key */
+ ASS= ERT(0); /* coding error -- we couldnt have created any such key */ }

- if (CKR_OK !=3D pkcs11h_certificate_signAny_ex(cert, &me= ch,
- = tbs, tbslen, sig, siglen))
+ if (CKR_OK !=3D pkcs11h_certifica= te_signAny_ex(cert, &mech, tbs, tbslen, sig, siglen))
= {
return 0;
}
<= span>@@ -244,7 +247,7 @@

}
/* For EC keys, pkcs11 returns signature as r|s: convert to der= encoded */
- int de= rlen =3D ecdsa_bin2der(sig, (int) *siglen, siglen_max);
+ int derlen =3D ecdsa_bin2der(sig, (= int)*siglen, siglen_max);

if (derlen= <=3D 0)
{
@@ -274,8 +277,7 @@
* other xkey_load_.. routines
*/
static int
-xkey_load_from_pkcs11h(pkcs11h_certificate_t certif= icate,
- = struct tls_root_ctx *const ctx)
+xkey_load_from_pkcs11h(pkcs11h_certificate_t certificat= e, struct tls_root_ctx *const ctx)
{
= int ret =3D 0;

@@ -326,10 +328,8 @@
#endif /* HAVE_XKEY_PROVIDER */

int

-pkcs11_init_tl= s_session(pkcs11h_certificate_t certificate,
- struct tls_root_ctx *const s= sl_ctx)
+pkcs11_init_= tls_session(pkcs11h_certificate_t certificate, struct tls_root_ctx *const s= sl_ctx)
{
-
#ifdef HAVE_XKEY_PROVIDER
retur= n (xkey_load_from_pkcs11h(certificate, ssl_ctx) =3D=3D 0); /* inverts the r= eturn value */
#else
@@ -403,7 +403,7 @@
openssl_session =3D NULL;
}
return ret;
-#endif /* ifdef HAVE_XKEY_PROVIDER */
+#endif = /* ifdef HAVE_XKEY_PROVIDER */
}
char *
@@ -429,8 +429,7 @@=
}

int
-pkcs11_certificate_serial(pkcs11h_certifica= te_t certificate, char *serial,
- size_t serial_len)
+pkcs11_certificate_serial(pkcs11h_certif= icate_t certificate, char *serial, size_t serial_len)
{
X509 *x509 =3D NULL;
BIO *bio =3D N= ULL;
@@ -450,9 +449,9 @@
}
<= span>

i2a_ASN1_INTEGER(bio, X509_get_serialNumber(x50= 9));
- n =3D BIO_rea= d(bio, serial, serial_len-1);
+ n =3D BIO_read(bio, serial, serial_len - 1);
=
- if (n<0)
+ if (n < 0)=
{
serial[0] =3D '\x0';
}
diff --git a/src/openvpn/platform.c b/sr= c/openvpn/platform.c
index 623daaa..880d14e 100644--- a/src/openvpn/platform.c
+++ b/src/openvpn/plat= form.c
@@ -66,8 +66,10 @@
msg(= M_ERR, "cd to '%s' failed", top);
= }
msg(M_INFO, "chroot to '%s' and c= d to '%s' succeeded", path, top);
-#else /* ifdef HAVE_CHROOT */
- msg(M_FATAL, "Sorry but I ca= n't chroot to '%s' because this operating system doesn't ap= pear to support the chroot() system call", path);
+#else /* ifdef HAVE_CHROOT */
= + msg(M_FATAL,+ "Sorry but I= can't chroot to '%s' because this operating system doesn't= appear to support the chroot() system call",
+ path);
#endif
}
}
@@ -94,8 +96,10 @@=
}
state->username =3D= username;
ret =3D true;
-#else /* if defined(HAVE_GETPWNAM) && = defined(HAVE_SETUID) */
- msg(M_FATAL, "cannot get UID for user %s -- platform lacks g= etpwname() or setuid() system calls", username);
+#else /* if defined(HAVE_GETPWNAM) &&= amp; defined(HAVE_SETUID) */
+ msg(M_FATAL,
+ "cannot get UID for user %s -- platform lacks ge= tpwname() or setuid() system calls",
+ username);
#endif=
}
return ret;
@@ -138,8= +142,10 @@
}
state->g= roupname =3D groupname;
ret =3D true;
-#else /* if defined(HAVE_GETGRNAM= ) && defined(HAVE_SETGID) */

- msg(M_FATAL, "cannot get GID for group %s -- pl= atform lacks getgrnam() or setgid() system calls", groupname);<= br>+#else /* if defined(HAVE_GE= TGRNAM) && defined(HAVE_SETGID) */
+ msg(M_FATAL,
+ "cannot get GID for group %s -- pl= atform lacks getgrnam() or setgid() system calls",
+ groupname);
#endif

}
return ret;
= @@ -214,8 +220,7 @@
*/
void=
platform_user_group_set(const struct platform_state_user *user_s= tate,
- = const struct platform_state_group *group_state,
- struct context *c= )
+ = const struct platform_state_group *group_state, struct context *c)
{
int keep_caps =3D need_keep_caps(c);<= /span>
unsigned int err_flags =3D (keep_caps > 0) ? M_FATA= L : M_NONFATAL;
@@ -258,8 +263,8 @@
{<= /span>
/* -4 and -6 mean failure of setuid/gid respective= ly.
* There is no point for us to continue if tho= se failed. */
- = msg(M_ERR, "capng_change_id('%s','%s') failed: %d"= ;,
- user_st= ate->username, group_state->groupname, res);
+ msg(M_ERR, "capng_change_id(= 9;%s','%s') failed: %d", user_state->username,+ group_state->= groupname, res);
}
else if (res = =3D=3D -3)
{
@@ -294,7 +299,7 @@
{
msg(M_ERR, "Clearing KEEPCA= PS flag failed");
}
-#endif /* HAVE_LIBCAPNG */
+#endif /* HAVE_LIBCAPNG */

if (keep_caps)
{
@@ -321,7 +326,7 @@

{
= msg(M_INFO, "nice %d succeeded", niceval);
= }
-#else /* if= def HAVE_NICE */
+#el= se /* ifdef HAVE_NICE */
msg(M_WARN, "WARNING= : nice %d failed (function not implemented)", niceval);
#endif

}
@@ -332,9 +337,9 @@=
platform_getpid(void)
{
#ifdef= _WIN32
- return (un= signed int) GetCurrentProcessId();
+ return (unsigned int)GetCurrentProcessId();
#else

- return = (unsigned int) getpid();
+ return (unsigned int)getpid();
#endif
<= span> }


@@ -354,12 +359,11 @@
<= span> else

{
msg(M_INFO, = "mlock: MEMLOCK limit: soft=3D%ld KB, hard=3D%ld KB",
<= span style=3D"color: hsl(0, 100%, 40%);">- ((long int) rl.rlim_c= ur) / 1024, ((long int) rl.rlim_max) / 1024);

- if (rl.rlim_cur < MIN_LOCKED_MEM_MB*1024= *1024)
+ (= (long int)rl.rlim_cur) / 1024, ((long int)rl.rlim_max) / 1024);
<= span style=3D"color: hsl(120, 100%, 40%);">+ if (rl.rlim_cur < MI= N_LOCKED_MEM_MB * 1024 * 1024)

{
- msg(M_INFO, "mlock: RL= IMIT_MEMLOCK < %d MB, increase limit",
- MIN_LOCKED_MEM_MB);
- rl.rlim_cur =3D MIN_LOCK= ED_MEM_MB*1024*1024;

= + msg(M_INFO, "mlock: RLIMIT_MEMLOCK < %d MB, increase l= imit", MIN_LOCKED_MEM_MB);
+ rl.rlim_cur =3D MIN_LOCKED_MEM_MB * 1024 * 1024;
if (rl.rlim_max < rl.rlim_cur)
{

rl.rlim_max =3D rl.rlim_c= ur;
@@ -397,10 +401,10 @@
res =3D _wch= dir(wide_string(dir, &gc));
gc_free(&gc);
return res;
-#else /* ifdef _WIN32 */
+#else /* ifdef _WIN32 */
#ifdef HAVE_CHDIR
return chdir(dir);
-#else /* ifdef HAVE_CHDIR */
+#else /* ifdef HAVE_CHDIR */
= return -1;
#endif
#endif
@@ -550,9 +554,8 @@

{
++atte= mpts;

- if (!snprintf(fname, sizeof(fname), fname_fmt, max_prefix_len,
- pr= efix, (unsigned long) get_random(),
- (unsigned long) get_random()))+ if (!snprintf(fname,= sizeof(fname), fname_fmt, max_prefix_len, prefix,
+ (unsigned long)get_ran= dom(), (unsigned long)get_random()))
{
<= span> msg(M_WARN, "ERROR: temporary filename too long"= ;);

return NULL;
@@ -576,8 +57= 9,7 @@
else if (fd =3D=3D -1 && errno !=3D= EEXIST)
{
/* Somethi= ng else went wrong, no need to retry. */
- msg(M_WARN | M_ERRNO, "Could not creat= e temporary file '%s'",
- retfname);
+ msg(M_WARN | M_ERRNO, "Could not cre= ate temporary file '%s'", retfname);
= return NULL;
}
}@@ -590,12 +592,12 @@
* Put a directory and filen= ame together.
*/
const char *
= -platform_gen_path(const char *di= rectory, const char *filename,
- struct gc_arena *gc)
+platform_gen_path(const char *directory, const = char *filename, struct gc_arena *gc)
{
#i= fdef _WIN32
- const = int CC_PATH_RESERVED =3D CC_LESS_THAN|CC_GREATER_THAN|CC_COLON
- |= CC_DOUBLE_QUOTE|CC_SLASH|CC_BACKSLASH|CC_PIPE|CC_QUESTION_MARK|CC_ASTERISK;=

+ const int CC_PA= TH_RESERVED =3D CC_LESS_THAN | CC_GREATER_THAN | CC_COLON | CC_DOUBLE_QUOTE=
+ = | CC_SLASH | CC_BACKSLASH | CC_PIPE | CC_QUESTION_MARK=
+ = | CC_ASTERISK;
#else
const int= CC_PATH_RESERVED =3D CC_SLASH;
#endif
@@ = -607,13 +609,11 @@

const char *safe_= filename =3D string_mod_const(filename, CC_PRINT, CC_PATH_RESERVED, '_&= #39;, gc);

- if (safe_filename
- && strcmp(safe_filename, ".")
- && strcmp(safe_fil= ename, "..")

- = )
+ )
{
const size_t outsize =3D strlen(= safe_filename) + (directory ? strlen(directory) : 0) + 16;
= struct buffer out =3D alloc_buf_gc(outsize, gc);
@= @ -671,14 +671,12 @@
{
= if (errno =3D=3D EACCES)
{
- msg( M_WARN | M_ERRNO, = "Could not access file '%s'", filename);
+ msg(M_WARN | M_ERRNO= , "Could not access file '%s'", filename);
}

}
}
- dmsg(D_T= EST_FILE, "TEST FILE '%s' [%d]",
- filename ? filename : "UNDEF&quo= t;,
- ret);
+ dmsg(D_TEST_FILE, &= quot;TEST FILE '%s' [%d]", filename ? filename : "UNDEF&q= uot;, ret);

return ret;
}

diff --git a/src/openvpn/platform.h b/src/openvpn/pl= atform.h
index 18ea97d..f1a2b01 100644
--- = a/src/openvpn/platform.h
+++ b/src/openvpn/platform.h
@@ -59,7 +59,8 @@

/* Get/Set = UID of process */

-struct platform_state_user {
+struct platform_state_user
+{
#if defined(HAVE_GETPWNAM)= && defined(HAVE_SETUID)
const char *username;=
uid_t uid;
@@ -70,7 +71,8 @@
/* Get/Set GID of process */

-struct platform_state_g= roup {
+struct platfo= rm_state_group
+{
#if defined(HAVE_GETGRNAM) && defined(HAVE_SETGID)
const char *groupname;
gid_t gid;
@@ -84,8 +86,7 @@
bool platform_group_get(c= onst char *groupname, struct platform_state_group *state);
=
void platform_user_group_set(const struct platform_state= _user *user_state,
- = const struct platform_state_group *group_state,
- = struct context *c);
+ const struct platform_state_group *group= _state, struct context *c);


<= span> /*

@@ -116,7 +117,7 @@

unsigned int platform_getpid(void);


-void platform_mlockall(bool print_msg)= ; /* Disable paging */
+void platform_mlockall(bool print_msg); /* Disable paging */
=
int platform_chdir(const char *dir);

@@ -152,8 +153,7 @@
= struct gc_arena *gc);

/** Put a directory and filename together. */

-const char *platform_gen_path(const char *direct= ory, const char *filename,
- struct gc_arena *gc);
+const char *platform_gen_path(const ch= ar *directory, const char *filename, struct gc_arena *gc);
=
/** Return true if pathname is absolute. */
bool platform_absolute_pathname(const char *pathname);

diff --git a/src/openvpn/plugin.c b/src/openvpn/plugin.c

i= ndex 12912c0..e65a3bc 100644
--- a/src/openvpn/plugin.c
+++ b/src/openvpn/plugin.c
@@ -44,7 +44,7 @@
#include "win32.h"
#include &quo= t;memdbg.h"

-#define PLUGIN_SYMBOL_REQUIRED (1<<0)
+#define PLUGIN_SYMBOL_REQUIRED (1 <= < 0)

/* used only for program aborts = */
static struct plugin_common *static_plugin_common =3D N= ULL; /* GLOBAL */
@@ -152,7 +152,7 @@
stat= ic inline unsigned int
plugin_supported_types(void)=
{
- retur= n ((1<<OPENVPN_PLUGIN_N)-1);
+ return ((1 << OPENVPN_PLUGIN_N) - 1);
}


struct plugin_option_list *
@@ -164,8 +164,7 @@
}
<= br> bool
-plugin_= option_list_add(struct plugin_option_list *list, char **p,
- struct gc_arena= *gc)
+plugin_option_= list_add(struct plugin_option_list *list, char **p, struct gc_arena *gc)
{
if (list->n < MAX_PLUGINS)
{
@@ -193,7 +192,8 @@
= for (i =3D 0; i < list->n; ++i)
{
const struct plugin_option *o =3D &list->plugins[i];
- msg(msglevel, &qu= ot; plugin[%d] %s '%s'", i, o->so_pathname, print_argv(o-&= gt;argv, &gc, PA_BRACKET));
+ msg(msglevel, " plugin[%d] %s '%s'",= i, o->so_pathname,
-libdl_resolve_symbol(void *handle, void **dest, const char *symb= ol, const char *plugin_name, const unsigned int flags)
+libdl_resolve_symbol(void *handle, void = **dest, const char *symbol, const char *plugin_name,
+ const unsigned int f= lags)
{
*dest =3D dlsym(handle, symbo= l);
if ((flags & PLUGIN_SYMBOL_REQUIRED) &&= ; !*dest)
{
- msg(M_FATAL, "PLUGIN: could not find required symbo= l '%s' in plugin shared object %s: %s", symbol, plugin_name, d= lerror());
+ m= sg(M_FATAL, "PLUGIN: could not find required symbol '%s' in pl= ugin shared object %s: %s",
+ symbol, plugin_name, dlerror());
= }
}

#else /* ifnde= f _WIN32 */

static void
-dll_resolve_symbol(HMODULE module, voi= d **dest, const char *symbol, const char *plugin_name, const unsigned int f= lags)
+dll_resolve_sy= mbol(HMODULE module, void **dest, const char *symbol, const char *plugin_na= me,
+ = const unsigned int flags)
{
*dest = =3D GetProcAddress(module, symbol);
if ((flags & P= LUGIN_SYMBOL_REQUIRED) && !*dest)
{
= - msg(M_FATAL, "PLUGI= N: could not find required symbol '%s' in plugin DLL %s", symb= ol, plugin_name);
+ = msg(M_FATAL, "PLUGIN: could not find required symbol '%s'= ; in plugin DLL %s", symbol,
+ plugin_name);
}
}


@@ -254,8 +258,7 @@
* was parsed.

*
*/
- if (!platform_absolute= _pathname(p->so_pathname)
- && p->so_pathname[0] !=3D '.')
= + if (!platform_absolute_pat= hname(p->so_pathname) && p->so_pathname[0] !=3D '.')<= /span>
{
char full[PATH_MAX];=

@@ -269,24 +272,29 @@
}
if (!p->handle)
{
- msg(M_ERR, "PLUGIN_INIT= : could not load plugin shared object %s: %s", p->so_pathname, dler= ror());

+ msg(= M_ERR, "PLUGIN_INIT: could not load plugin shared object %s: %s",= p->so_pathname,
+= dlerror());
}

= -#define PLUGIN_SYM(var, name, fl= ags) libdl_resolve_symbol(p->handle, (void *)&p->var, name, p->= ;so_pathname, flags)
= +#define PLUGIN_SYM(var, name, flags) \
+ libdl_resolve_symbol(p->handle, (void *)&p-&= gt;var, name, p->so_pathname, flags)

-#else /* ifndef _WIN32 */
+#else /* ifndef _WIN32 */
=

WCHAR *wpath =3D wide_string(p->so_path= name, &gc);
- WC= HAR normalized_plugin_path[MAX_PATH] =3D {0};
+ WCHAR normalized_plugin_path[MAX_PATH] =3D { = 0 };
/* Normalize the plugin path, converting any rela= tive paths to absolute paths. */
if (!GetFullPathNameW= (wpath, MAX_PATH, normalized_plugin_path, NULL))
{
- msg(M_ERR, "= PLUGIN_INIT: could not load plugin DLL: %ls. Failed to normalize plugin pat= h.", wpath);
+ = msg(M_ERR, "PLUGIN_INIT: could not load plugin DLL: %ls. Failed = to normalize plugin path.",
+ wpath);
}

if (!plugin_in_trusted_dir(normalized_plugin_path))
{
- = msg(M_FATAL, "PLUGIN_INIT: could not load plugin DLL: %ls. The D= LL is not in a trusted directory.", normalized_plugin_path);+ msg(M_FATAL,+ "PLUGIN_INI= T: could not load plugin DLL: %ls. The DLL is not in a trusted directory.&q= uot;,
+ no= rmalized_plugin_path);
}

<= span> p->module =3D LoadLibraryW(normalized_plugin_path);

= @@ -295,7 +303,8 @@
msg(M_ERR, "PLUGIN_= INIT: could not load plugin DLL: %ls", normalized_plugin_path);=
}

-#define PLUGIN_SYM(var, name, flags) dll_resolve_symbol(p->= module, (void *)&p->var, name, p->so_pathname, flags)
<= span style=3D"color: hsl(120, 100%, 40%);">+#define PLUGIN_SYM(var, name, f= lags) \

+ dll_reso= lve_symbol(p->module, (void *)&p->var, name, p->so_pathname, f= lags)

#endif /* ifndef _WIN32 */<= br>
@@ -314,12 +323,14 @@
if (!p->open1 && !p->open2 && !p->ope= n3)
{
- msg(M_FATAL, "PLUGIN: symbol openvpn_plugin_open_vX is un= defined in plugin: %s", p->so_pathname);
+ msg(M_FATAL, "PLUGIN: symbol open= vpn_plugin_open_vX is undefined in plugin: %s",
+ p->so_pathname); }

if (!p->func1 &= & !p->func2 && !p->func3)
{- msg(M_FATAL, "PLU= GIN: symbol openvpn_plugin_func_vX is undefined in plugin: %s", p->= so_pathname);
+ = msg(M_FATAL, "PLUGIN: symbol openvpn_plugin_func_vX is undefined in = plugin: %s",
+ = p->so_pathname);
}

/*
@@ -330,10 +341,9 @@
= const int plugin_needs_version =3D (*p->min_version_required)();<= /span>
if (plugin_needs_version > OPENVPN_PLUGIN_VERSI= ON)
{
- msg(M_FATAL, "PLUGIN_INIT: plugin needs interface= version %d, but this version of OpenVPN only supports version %d: %s"= ,
- plug= in_needs_version,
- = OPENVPN_PLUGIN_VERSION,
- p->so_pathname);
+ msg(M_FATAL,
+ "PLUGIN_INIT: plugi= n needs interface version %d, but this version of OpenVPN only supports ver= sion %d: %s",
+ = plugin_needs_version, OPENVPN_PLUGIN_VERSION, p->so_pathn= ame);
}
}

@@ -348,7 +358,9 @@

i= f (rel)
{
- msg(M_WARN, "WARNING: plugin '%s' specified b= y a relative pathname -- using an absolute pathname would be more secure&qu= ot;, p->so_pathname);
+ msg(M_WARN,
+ "WARNING: plugin '%s' specified by a relative= pathname -- using an absolute pathname would be more secure",<= br>+ p->so_pathna= me);
}

p->in= itialized =3D true;
@@ -427,9 +439,9 @@
st= atic struct openvpn_plugin_callbacks callbacks =3D {
p= lugin_log,
plugin_vlog,
- secure_memzero, /* plugin_secure_memzero= */
- openvpn_base64= _encode, /* plugin_base64_encode */
- openvpn_base64_decode, /* plugin_base64_decode */
+ secure_memzero, = /* plugin_secure_memzero */
+ openvpn_base64_encode, /* plugin_base64_encode */
<= span style=3D"color: hsl(120, 100%, 40%);">+ openvpn_base64_decode, /* p= lugin_base64_decode */

};


@@ -444,10 +456,8 @@
#endif
=
static void
-plugin_open_item(struct plugin *p,
- const struct plugin_option *o,=
- stru= ct openvpn_plugin_string_list **retlist,
- const char **envp,
+plugin_open_item(struct plugin *p, const= struct plugin_option *o,
+ struct openvpn_plugin_string_list **retlist, const c= har **envp,
const int init_point)<= br> {
ASSERT(p->initialized);
@@ -471,19 +481,20 @@

if (p->open3)
= {
struct openvpn_plugin_args_op= en_in args =3D { p->plugin_type_mask,
- = (const char **const) o->argv,
- (const c= har **const) envp,
+ = (const char **const)= o->argv,
+ = (const char **const)envp,
&am= p;callbacks,
= SSLAPI,
= PACKAGE_VERSION,
= OPENVPN_VERSION_MAJOR,
= OPENVPN_VERSION_MINOR,=
- = _OPENVPN_PATCH_LEVEL};
+ = _OPENVPN_PATCH_LEVEL };
str= uct openvpn_plugin_args_open_return retargs;

CLEAR(retargs);

retargs.retur= n_list =3D retlist;
- = if ((*p->open3)(OPENVPN_PLUGINv3_STRUCTVER, &args, &re= targs) =3D=3D OPENVPN_PLUGIN_FUNC_SUCCESS)
+ if ((*p->open3)(OPENVPN_PLUGINv3_STRU= CTVER, &args, &retargs)
+ =3D=3D OPENVPN_PLUGIN_FUNC_SUCCESS)
<= span> {

p->plugin_type_mask= =3D retargs.type_mask;
p->plugin_handl= e =3D retargs.handle;
@@ -506,24 +517,20 @@
ASSERT(0);

}

- msg(D_PLUGIN, "= ;PLUGIN_INIT: POST %s '%s' intercepted=3D%s %s",
- p->so_pathname,
- print_argv(o-&= gt;argv, &gc, PA_BRACKET),
- plugin_mask_string(p->plugin_type_mask, &gc),
+ msg(D_PLUGIN,= "PLUGIN_INIT: POST %s '%s' intercepted=3D%s %s", p->s= o_pathname,
+ = print_argv(o->argv, &gc, PA_BRACKET), plugin_mask_string(p->p= lugin_type_mask, &gc),
(retlist &&= *retlist) ? "[RETLIST]" : "");

if ((p->plugin_type_mask | plugin_supported_types())= !=3D plugin_supported_types())
{
- msg(M_FATAL, "PLUGIN_= INIT: plugin %s expressed interest in unsupported plugin types: [want=3D0x%= 08x, have=3D0x%08x]",
- p->so_pathname,
- p->plugin_type_mask,
- plugin_supported_types(= ));
+ msg(= M_FATAL,
+ = "PLUGIN_INIT: plugin %s expressed interest in unsupported plugin = types: [want=3D0x%08x, have=3D0x%08x]",
+ p->so_pathname, p->plugin_ty= pe_mask, plugin_supported_types());
}

if (p->plugin_handle =3D=3D NULL)<= br> {
- = msg(M_FATAL, "PLUGIN_INIT: plugin initialization function fa= iled: %s",
- = p->so_pathname);
+ msg(M_FATAL, "PLUGIN_INIT: plugin initialization= function failed: %s", p->so_pathname);
}<= /span>

gc_free(&gc);
@@ -531,15 +538,9 @@

}

static int

-plugin_ca= ll_item(const struct plugin *p,
- void *per_client_context,
- const int type,
= - const struct ar= gv *av,
- = struct openvpn_plugin_string_list **retlist,
- const char **envp,
- int certdepth,
- openvpn_= x509_cert_t *current_cert
- )
+ = const struct argv *av, struct openvpn_plugin_string_list **retlist,=
+ co= nst char **envp, int certdepth, openvpn_x509_cert_t *current_cert) {
int status =3D OPENVPN_PLUGIN_FUNC_SUCCESS;=

@@ -563,8 +564,8 @@
= if (p->func3)
{
= struct openvpn_plugin_args_func_in args =3D { type,
- = (const char **const) a.argv,
- = (const char **const) envp,
+ (const cha= r **const)a.argv,
+ = (const char **const)e= nvp,
= p->plugin_handle,
= per_client_context,
= (current_cert ? certdepth : -1),
@@ -578,7 +579,8 @@
}
else if (p->func2)

{
- status =3D (*p->func2)= (p->plugin_handle, type, (const char **)a.argv, envp, per_client_context= , retlist);

+ = status =3D (*p->func2)(p->plugin_handle, type, (const char **)a.a= rgv, envp,
+ = per_client_context, retlist);
= }
else if (p->func1)
= {
@@ -589,17 +591,13 @@
ASS= ERT(0);
}

- msg(D_PLUGIN, "PLUGIN_CALL: PO= ST %s/%s status=3D%d",
- p->so_pathname,
- plugin_type_name(type),
+ msg(D_PLUGIN, "PLUGIN_CALL: POS= T %s/%s status=3D%d", p->so_pathname, plugin_type_name(type),
status);

= if (status =3D=3D OPENVPN_PLUGIN_FUNC_ERROR)
{
msg(M_WARN, "PLUGIN_CALL: plugin function %= s failed with status %d: %s",
- plugin_type_name(type),
- status,
- p->so_pathname);
+ plugin_ty= pe_name(type), status, p->so_pathname);
}

argv_free(&a);
@@= -652,8 +650,7 @@
}

sta= tic void
-plugin_per_cl= ient_init(const struct plugin_common *pc,
- struct plugin_per_client *cli,
+plugin_per_client_ini= t(const struct plugin_common *pc, struct plugin_per_client *cli,
= const int init_point)
{
const int n =3D pc->n;
@@ -662,8 +659,7= @@
for (i =3D 0; i < n; ++i)
= {
const struct plugin *p =3D &pc->plugins[i= ];
- if (p->p= lugin_handle
- = && (init_point < 0 || init_point =3D=3D p->requested_initi= alization_point)
+ = if (p->plugin_handle && (init_point < 0 || init_point = =3D=3D p->requested_initialization_point)
&= amp;& p->client_constructor)
{
cli->per_client_context[i] =3D (*p->client_construct= or)(p->plugin_handle);

@@ -711,8 +707,7 @@

for (i =3D 0; i < list->n; ++i)
<= span> {

- pl= ugin_init_item(&pc->plugins[i],
- &list->plugins[i]);=
+ plugin_init_item(&= amp;pc->plugins[i], &list->plugins[i]);
= pc->n =3D i + 1;
}

@@ -721,11 +716,8 @@

}

static void

-plugin_c= ommon_open(struct plugin_common *pc,
- const struct plugin_option_list *list,
- struc= t plugin_return *pr,
- = const struct env_set *es,
- const int init_point)
+plugin_common_open(struct plugin= _common *pc, const struct plugin_option_list *list,

+ struct plugin_return *= pr, const struct env_set *es, const int init_point)
{
struct gc_arena gc =3D gc_new();
int = i;
@@ -740,10 +732,7 @@

= for (i =3D 0; i < pc->n; ++i)
{
- plugin_open_item(&pc-&= gt;plugins[i],

- = &list->plugins[i],
- pr ? &pr->list[i] : N= ULL,
- = envp,
+ = plugin_open_item(&pc->plugins[i], &list->plugins[i], pr ? &= amp;pr->list[i] : NULL, envp,
= init_point);
}

@@ -7= 82,25 +771,17 @@
}

void=
-plugin_list_open(stru= ct plugin_list *pl,
- = const struct plugin_option_list *list,
- struct plugin_return *pr,<= /span>
- const= struct env_set *es,
- = const int init_point)
+plugin_list_open(struct plugin_list *pl, const struct plu= gin_option_list *list,
-plugin_call_ssl(const struct plugin_list *pl,
- const in= t type,
- = const struct argv *av,
- struct env_set *es,
- int certdepth,<= br>- openvpn_x509_= cert_t *current_cert
- = )
+plu= gin_call_ssl(const struct plugin_list *pl, const int type, const struct arg= v *av,
+ = struct plugin_return *pr, struct env_set *es, int certdepth,
<= span style=3D"color: hsl(120, 100%, 40%);">+ openvpn_x509_ce= rt_t *current_cert)

{
if (pr)<= br> {
@@ -821,23 +802,16 @@

for (i =3D 0; i < n; ++i)
= {
- const i= nt status =3D plugin_call_item(&pl->common->plugins[i],- = pl->per_client.per_client_context[i],
- = type,
- = av,
- pr ?= &pr->list[i] : NULL,
- envp,
- = certdepth,

= - current_cert
- = );

+ = const int status =3D
+ plugin_call_item(&pl->common->plugins[i]= , pl->per_client.per_client_context[i],
+ type, av, pr ? &= ;pr->list[i] : NULL, envp, certdepth, current_cert);
= switch (status)
{
= case OPENVPN_PLUGIN_FUNC_SUCCESS:
= break;

case O= PENVPN_PLUGIN_FUNC_DEFERRED:
- if ((type =3D=3D OPENVPN_PLUGIN_AUTH_USER_PASS_V= ERIFY)
- = && deferred_auth_done)
+ if ((type =3D=3D OPENVPN_PLUGIN_AUT= H_USER_PASS_VERIFY) && deferred_auth_done)
= {
/*
= * Do not allow deferred auth if a deferred auth h= as
@@ -854,13 +828,12 @@
= * error, we bail out and exit the OpenVPN process.
= */
error= =3D true;
- = msg(M_FATAL,
- "Exiting due to multiple authenticatio= n plug-ins "
- = "performing deferred authentication. Only one= "
- = "authentication plug-in doing deferred auth is "
- = "allowed. Ignoring the result and stopping now, "
= - &quo= t;the current authentication result is not to be "
- "trusted= .");
+ = msg(M_FATAL, "Exiting due to multiple authentication plu= g-ins "
+ = "performing deferred authentication. On= ly one "
+ = "authentication plug-in doing deferred = auth is "
+ = "allowed. Ignoring the result and sto= pping now, "
+ = "the current authentication result = is not to be "
+= "trusted.");
break;

}
deferred_auth_done =3D true;
@@ -996,8 +969,7 @@

}

void

-plugin_return_= get_column(const struct plugin_return *src,
- struct plugin_return *dest,<= /span>
+plugin_return_get_co= lumn(const struct plugin_return *src, struct plugin_return *dest, const char *colname)
{
int i;
@@ -1035,10 +1007,7 @@
= msg(msglevel, "PLUGIN #%d (%s)", i, prefix);
while (l)
{
- msg(msglevel, "[%d] = 9;%s' -> '%s'\n",
- ++count,
- l->name,
- l->value);
+ msg(msglevel, "[%d] = 9;%s' -> '%s'\n", ++count, l->name, l->value);
l =3D l->next;
}
}
diff --git a/src/openvpn/plugin.h b/src= /openvpn/plugin.h
index b44cf0d..63999b6 100644
<= span>--- a/src/openvpn/plugin.h

+++ b/src/openvpn/plugin.h<= /span>
@@ -41,17 +41,20 @@

#def= ine MAX_PLUGINS 16

-struct plugin_option {
+struct plugin_option
+{
const char *so_pathname; const char **argv;
};

-struct plugin_option_list {=
+struct plugin_optio= n_list
+{
<= span> int n;

struct plugin_option plugins[MAX_PLUG= INS];
};

-struct plugin {
+struct plugin
+{
bool initialized;
c= onst char *so_pathname;
unsigned int plugin_type_mask;=
@@ -105,8 +108,7 @@

str= uct plugin_option_list *plugin_option_list_new(struct gc_arena *gc);=

-bool plugi= n_option_list_add(struct plugin_option_list *list, char **p,
- struct g= c_arena *gc);

+bool p= lugin_option_list_add(struct plugin_option_list *list, char **p, struct gc_= arena *gc);

#ifndef ENABLE_SMALL<= br> void plugin_option_list_print(const struct plugin_option_list *li= st, int msglevel);
@@ -115,29 +117,20 @@
<= /span>
struct plugin_list *plugin_list_init(const struct plugin_o= ption_list *list);

-void plugin_list_open(struct plugin_list *pl,
- const struct p= lugin_option_list *list,

- const struct env_set *es= ,
- = const int init_point);
+void plugin_list_open(struct plugin_list *pl, const struct plugin_opti= on_list *list,
+ = struct plugin_return *pr, const struct env_set *es, const = int init_point);

struct plugin_list *plu= gin_list_inherit(const struct plugin_list *src);
-int plugin_call_ssl(const stru= ct plugin_list *pl,
- = const int type,
- const struct argv *av,
- struct plugin_return *= pr,
- = struct env_set *es,
-= int current_cert_depth,
- openvpn_x509_cert_t *current_cert=
- )= ;
+int plugin_call_ss= l(const struct plugin_list *pl, const int type, const struct argv *av,
+ stru= ct plugin_return *pr, struct env_set *es, int current_cert_depth,+ openvpn_x= 509_cert_t *current_cert);

void plugin_l= ist_close(struct plugin_list *pl);

bool = plugin_defined(const struct plugin_list *pl, const int type);

-void plugin_retur= n_get_column(const struct plugin_return *src,
- struct plugin_return = *dest,
+void plugin_r= eturn_get_column(const struct plugin_return *src, struct plugin_return *des= t,
const char *colname);

void plugin_return_free(struct plugin_retur= n *pr);
@@ -173,8 +166,14 @@
}
<= span>

#else /* ifdef ENABLE_PLUGIN */
-struct plugin_list { int dummy; };
-struct plugin_return { int = dummy; };
+struct plu= gin_list
+{+ int dummy;
+};

+struct plugin_return
+{
+ int dummy;
+};

static inline bool
= plugin_defined(const struct plugin_list *pl, const int type)
@@ -183,14 +182,9 @@

}

static inline int

-p= lugin_call_ssl(const struct plugin_list *pl,
- const int type,
- const struct argv *av,
- struct pl= ugin_return *pr,
- = struct env_set *es,
- int current_cert_depth,
- openvpn_x509_cert_t *current_cer= t
- )
+plugin_call_ssl(const = struct plugin_list *pl, const int type, const struct argv *av,
+ struct plugin_re= turn *pr, struct env_set *es, int current_cert_depth,

+ openvpn_x509_cert_t *curr= ent_cert)
{
return 0;
}

@@ -198,11 +192,8 @@
#endif /* ENABLE_= PLUGIN */

static inline int
-plugin_call(const struct plugin_li= st *pl,

- co= nst int type,
- = const struct argv *av,
- struct plugin_return *pr,
- struct env_set *es)
+plugin_call(const struct plugin_list *pl,= const int type, const struct argv *av,
+ struct plugin_return *pr, struct env_set *e= s)
{
return plugin_call_ssl(pl, type,= av, pr, es, -1, NULL);
}
diff --git a/src= /openvpn/pool.c b/src/openvpn/pool.c
index bfa43ec..898a045= 100644
--- a/src/openvpn/pool.c
+++ b/src/= openvpn/pool.c
@@ -89,14 +89,11 @@
= * Keep track of a possible allocation to us
= * from an earlier session.
*/
= - if (previous_usage &= lt; 0
- = && common_name
= - && ipe->common_name
+ if (previous_usage < 0 &&= ; common_name && ipe->common_name
= && !strcmp(common_name, ipe->common_name))
= {
previous_usage =3D i;<= br> }
-
}
}

@@ -125,16 +122,14 @@
if (start > end)<= /span>
{
msg(msglevel, "--ifcon= fig-pool start IP [%s] is greater than end IP [%s]",
- print_in_addr_t(start, 0, &= amp;gc),
- p= rint_in_addr_t(end, 0, &gc));
+ print_in_addr_t(start, 0, &gc), print_in_addr= _t(end, 0, &gc));
ret =3D false;
}

if (end - start >=3D IFCONFIG_POOL_MAX)
{
-= msg(msglevel, "--ifconfig-pool address range is too large [%s = -> %s]. Current maximum is %d addresses, as defined by IFCONFIG_POOL_MA= X variable.",
- = print_in_addr_t(start, 0, &gc),
- print_in_addr_t(end, 0, &gc),=
- IFCONFIG_POOL_MA= X);
+ msg(msgl= evel,
+ &q= uot;--ifconfig-pool address range is too large [%s -> %s]. Current maxi= mum is %d addresses, as defined by IFCONFIG_POOL_MAX variable.",
+ print_in_addr= _t(start, 0, &gc), print_in_addr_t(end, 0, &gc), IFCONFIG_POOL_MAX)= ;
ret =3D false;
}
= gc_free(&gc);
@@ -142,10 +137,9 @@ }

struct ifconfig_pool *<= br>-ifconfig_pool_init(const bool= ipv4_pool, enum pool_type type, in_addr_t start,
- in_addr_t end, const bool du= plicate_cn,
- = const bool ipv6_pool, const struct in6_addr ipv6_base,
<= span style=3D"color: hsl(0, 100%, 40%);">- const int ipv6= _netbits )

+ifconfig_= pool_init(const bool ipv4_pool, enum pool_type type, in_addr_t start, in_ad= dr_t end,
+ = const bool duplicate_cn, const bool ipv6_pool, const struct in6_ad= dr ipv6_base,
+ = const int ipv6_netbits)
{
= struct gc_arena gc =3D gc_new();
struct ifconfig_poo= l *pool =3D NULL;
@@ -179,8 +173,7 @@

if (pool_ipv4_size < 2)
{=
- msg(M_FAT= AL, "IPv4 pool size is too small (%d), must be at least 2",
- pool_ipv4_s= ize);
+ ms= g(M_FATAL, "IPv4 pool size is too small (%d), must be at least 2"= , pool_ipv4_size);
}

<= span> msg(D_IFCONFIG_POOL, "IFCONFIG POOL IPv4: base=3D%s size= =3D%d",

@@ -198,10 +191,8 @@
= * 4 bytes, therefore we can just extract that and use it as base in=
* integer form
*/
<= span style=3D"color: hsl(0, 100%, 40%);">- uint32_t base =3D (ipv6_b= ase.s6_addr[12] << 24)

- | (ipv6_base.s6_addr[13] << 16)=
- | (i= pv6_base.s6_addr[14] << 8)
- | ipv6_base.s6_addr[15];
+ uint32_t base =3D (ipv6_bas= e.s6_addr[12] << 24) | (ipv6_base.s6_addr[13] << 16)

= + | (ipv= 6_base.s6_addr[14] << 8) | ipv6_base.s6_addr[15];
= /* some bits of the last 4 bytes may still be part of the network
* portion of the address, therefore we need to set t= hem to 0
*/
@@ -214,7 +205,7 @@
* the following operation first computes mask= =3D0x3fffff and then
* uses mask to extract t= he wanted bits from base
*/
- uint32_t mask =3D (1 <&l= t; (128 - ipv6_netbits) ) - 1;
+ uint32_t mask =3D (1 << (128 - ipv6_netbits)) = - 1;
base &=3D mask;
= }

@@ -232,24 +223,21 @@
if (base =3D=3D 0)

{
= msg(D_IFCONFIG_POOL, "IFCONFIG POOL IPv6: incrementing poo= l start "
- = "to avoid ::0 assignment");
+ "to avoid = ::0 assignment");
base++;
pool->ipv6.base.s6_addr[15]++;

}<= /span>

- = pool_ipv6_size =3D ipv6_netbits >=3D 112
- ? (1 << (128 - ip= v6_netbits)) - base
- = : IFCONFIG_POOL_MAX;
+ pool_ipv6_size =3D
+ ipv6_netbits >=3D 112 ? (1= << (128 - ipv6_netbits)) - base : IFCONFIG_POOL_MAX;

if (pool_ipv6_size < 2)
= {
- msg= (M_FATAL, "IPv6 pool size is too small (%d), must be at least 2",=
- pool_= ipv6_size);
+ = msg(M_FATAL, "IPv6 pool size is too small (%d), must be at least 2= ", pool_ipv6_size);
}

msg(D_IFCONFIG_POOL, "IFCONFIG POOL IPv6: base=3D%= s size=3D%d netbits=3D%d",
- print_in6_addr(pool->ipv6.base, 0, &gc), pool_= ipv6_size,
- = ipv6_netbits);
+ = print_in6_addr(pool->ipv6.base, 0, &gc), pool_ipv6_size, ipv= 6_netbits);

/* if there is no v4= pool, or the v6 pool is smaller, use
* v6 pool s= ize as "unified pool size"
@@ -264,16 +252,20 @@<= /span>
{
if (pool_ipv4_size < poo= l_ipv6_size)
{
- msg(M_INFO, "NOTE: IPv4 pool size is %d,= IPv6 pool size is %d. "
+ msg(M_INFO,
+ "NOTE: IPv4 pool size is %d, IPv6 pool s= ize is %d. "
"IPv4 pool size lim= its the number of clients that can be "
- "served from the pool", po= ol_ipv4_size, pool_ipv6_size);
+ "served from the pool",
+ pool_ipv4_size, po= ol_ipv6_size);

}
else if = (pool_ipv4_size > pool_ipv6_size)
{
<= span style=3D"color: hsl(0, 100%, 40%);">- msg(M_WARN, "WAR= NING: IPv4 pool size is %d, IPv6 pool size is %d. "

+ msg(M_WARN,
+ "WARNING: IPv= 4 pool size is %d, IPv6 pool size is %d. "

= "IPv6 pool size limits the number of clients that can be "<= /span>
"served from the pool. This is likely= a MISTAKE - please check "
- "your configuration", pool_ipv4_size, = pool_ipv6_size);
+ = "your configuration",
+ pool_ipv4_size, pool_ipv6_size);
}
}
@@ -302,7 +294,8 @@
}

= ifconfig_pool_handle
-ifconfig_pool_acquire(struct ifconfig_pool *pool, in_addr_t *local, i= n_addr_t *remote, struct in6_addr *remote_ipv6, const char *common_name)
+ifconfig_pool_acquire(= struct ifconfig_pool *pool, in_addr_t *local, in_addr_t *remote,
= + struct i= n6_addr *remote_ipv6, const char *common_name)
{ int i;

@@ -402,8 +395,7 @@
}

static ifconfig_pool_ha= ndle
-ifconfig_pool_ipv= 6_base_to_handle(const struct ifconfig_pool *pool,
- const struct= in6_addr *in_addr)
+= ifconfig_pool_ipv6_base_to_handle(const struct ifconfig_pool *pool, const s= truct in6_addr *in_addr)
{
ifconfig_p= ool_handle ret;
uint32_t base, addr;
@= @ -422,14 +414,10 @@
}
}

- base= =3D (pool->ipv6.base.s6_addr[12] << 24)
- | (pool->ipv6.base.s6_addr[13] &l= t;< 16)
- = | (pool->ipv6.base.s6_addr[14] << 8)
- | pool->ipv6.base.s6_addr[15];=
+ base =3D (pool->ipv= 6.base.s6_addr[12] << 24) | (pool->ipv6.base.s6_addr[13] << = 16)
+ | (po= ol->ipv6.base.s6_addr[14] << 8) | pool->ipv6.base.s6_addr[15];<= /span>

- = addr =3D (in_addr->s6_addr[12] << 24)
- | (in_addr->s6_addr[13] << 16)=
- | (in_addr= ->s6_addr[14] << 8)
+ addr =3D (in_addr->s6_addr[12] << 24) | (in_addr->= s6_addr[13] << 16) | (in_addr->s6_addr[14] << 8)
<= span> | in_addr->s6_addr[15];


ret =3D addr - base;

@@ -478,14 +466,14 @@ /* IPv6 pools are always INDIV (--linear) */
= if (pool->ipv6.enabled && hand >=3D 0 && hand <= ; pool->size)
{
- ret =3D add_in6_addr( pool->ipv6.base, hand );=
+ ret =3D add= _in6_addr(pool->ipv6.base, hand);
}
return ret;

}

sta= tic void
-ifconfig_pool= _set(struct ifconfig_pool *pool, const char *cn,
- ifconfig_pool_handle h, const = bool fixed)
+ifconfig= _pool_set(struct ifconfig_pool *pool, const char *cn, ifconfig_pool_handle = h,
+ = const bool fixed)
{
struct ifconfig_= pool_entry *e =3D &pool->list[h];
ifconfig_pool= _entry_free(e, true);
@@ -557,7 +545,8 @@
= if (refresh_freq > 0)
{
= ret->fixed =3D false;
- ret->file =3D status_open(filename, refresh_freq, -1, NULL,= STATUS_OUTPUT_READ|STATUS_OUTPUT_WRITE);
+ ret->file =3D
+ status_open(filename, refresh_freq, = -1, NULL, STATUS_OUTPUT_READ | STATUS_OUTPUT_WRITE);
}=
else
{
@@ -640,8= +629,7 @@
* - CN,IP4
= * - CN,,IP6
*/
- if (!buf_parse(&in, ',&= #39;, cn_buf, buf_size)
- || !buf_parse(&in, ',', ip_buf, buf_size))
+ if (!buf_p= arse(&in, ',', cn_buf, buf_size) || !buf_parse(&in, ',&= #39;, ip_buf, buf_size))
{
= continue;
}
@@ -= 651,22 +639,18 @@
if (strlen(ip_buf) > 0)
{
bool v4_ok = =3D true;
- = in_addr_t addr =3D getaddr(GETADDR_HOST_ORDER, ip_buf, 0, &v4_ok,
- = NULL);
+ in_addr_t addr =3D getaddr(GETADDR_HOST_ORDER, ip_buf,= 0, &v4_ok, NULL);

i= f (!v4_ok)
{
- msg(M_WARN, "pool: invalid= IPv4 (%s) for CN=3D%s", ip_buf,
- cn_buf);
+ msg(M_WARN, "pool: in= valid IPv4 (%s) for CN=3D%s", ip_buf, cn_buf);
= }
else
= {
h =3D ifconfig_pool_ip_base_= to_handle(pool, addr);
if (h < 0)
{
- msg(M_WARN,
- "pool: IPv= 4 (%s) out of pool range for CN=3D%s",
- ip_buf, cn_buf);+ msg(= M_WARN, "pool: IPv4 (%s) out of pool range for CN=3D%s", ip_buf, = cn_buf);
}
= }
}
@@ -677,17 +661,14 @= @

if (!get_ipv6_addr(ip6= _buf, &addr6, NULL, M_WARN))
{<= br>- msg(M_WAR= N, "pool: invalid IPv6 (%s) for CN=3D%s", ip6_buf,
- cn_buf);
+ msg= (M_WARN, "pool: invalid IPv6 (%s) for CN=3D%s", ip6_buf, cn_buf);=
}
else
{
h6 = =3D ifconfig_pool_ipv6_base_to_handle(pool, &addr6);
= if (h6 < 0)
{
- = msg(M_WARN,
- = "pool: IPv6 (%s) out of pool range for CN=3D%s"= ,
- = ip6_buf, cn_buf);
+ msg(M_WARN, "pool: IPv6 (%s) out of pool= range for CN=3D%s", ip6_buf, cn_buf);
= }

/* Rely on I= Pv6 if no IPv4 was provided or the one provided
@@ -707,8 += 688,7 @@
*/
if (= (h6 >=3D 0) && (h !=3D h6))
{
- msg(M_WARN,=
- &= quot;pool: IPv4 (%s) and IPv6 (%s) have different offsets! Relying on IPv4&= quot;,
+ = msg(M_WARN, "pool: IPv4 (%s) and IPv6 (%s) have different offsets! = Relying on IPv4",
ip_buf, ip6_buf= );
}

@@ -759= ,7 +739,7 @@
CLEAR(array);
msg(M_INFO | M_NOPREFIX, "************ 1");- for (i =3D 0; i < (int) = SIZE(array); ++i)
+ = for (i =3D 0; i < (int)SIZE(array); ++i)
{=
char *cn;
ifconfig_pool_handle = h;
@@ -777,15 +757,12 @@
break= ;
}
msg(M_INFO | M_NOPREF= IX, "IFCONFIG_POOL TEST pass 1: l=3D%s r=3D%s cn=3D%s",- print_in_addr_t(loc= al, 0, &gc),
- = print_in_addr_t(remote, 0, &gc),
- cn);
+ print_in_addr_t(local, 0, &gc), print_in= _addr_t(remote, 0, &gc), cn);
array[i] =3D h;<= /span>
-
= }

msg(M_INFO | M_NOPREFIX, "***= ********** 2");
- = for (i =3D (int) SIZE(array) / 16; i < (int) SIZE(array) / 8; ++i)
+ for (i =3D (int)SI= ZE(array) / 16; i < (int)SIZE(array) / 8; ++i)
{
msg(M_INFO, "Attempt to release %d cn=3D%s"= ;, array[i], p->list[i].common_name);
if (!ifco= nfig_pool_release(p, array[i]))
@@ -798,13 +775,13 @@
CLEAR(array);

msg(M_= INFO | M_NOPREFIX, "**************** 3");
- for (i =3D 0; i < (int) SIZE(array);= ++i)
+ for (i =3D= 0; i < (int)SIZE(array); ++i)
{
= char *cn;
ifconfig_pool_handle h; in_addr_t local, remote;
char buf[= 256];
- snprintf= (buf, sizeof(buf), "common-name-%d", i+24);
+ snprintf(buf, sizeof(buf), "= common-name-%d", i + 24);
#ifdef DUP_CN
cn =3D NULL;

#else
@@ -816,11 = +793,8 @@
break;
}
msg(M_INFO | M_NOPREFIX, "IFCONFIG_POOL TEST pa= ss 3: l=3D%s r=3D%s cn=3D%s",
- print_in_addr_t(local, 0, &gc),
- print_in_addr_t(remote, = 0, &gc),

- = cn);
+ = print_in_addr_t(local, 0, &gc), print_in_addr_t(remote, 0, &gc), cn= );
array[i] =3D h;
-
}

<= span> ifconfig_pool_free(p);

diff --git a/src/openvpn/p= ool.h b/src/openvpn/pool.h
index 9f50ca9..6cecef0 100644
--- a/src/openvpn/pool.h
+++ b/src/openvpn/po= ol.h
@@ -29,7 +29,7 @@
#include "stat= us.h"

#define IFCONFIG_POOL_MAX = 65536
-#define IFC= ONFIG_POOL_MIN_NETBITS 16
+#define IFCONFIG_POOL_MIN_NETBITS 16

<= span> enum pool_type

{
@@ -48,12 +48,14 @@=
struct ifconfig_pool
{
= bool duplicate_cn;
= - struct {
+ st= ruct
+ { bool enabled;
enum pool_type type;=
in_addr_t base;
} ipv4;

- struct {
+ struct

+ {
bool enabl= ed;
struct in6_addr base;
} i= pv6;
@@ -69,18 +71,18 @@

= typedef int ifconfig_pool_handle;

-struct ifconfig_pool *ifconfig_pool_init(co= nst bool ipv4_pool,
- = enum pool_type type, in_addr_t start= ,
+struct ifconfig_po= ol *ifconfig_pool_init(const bool ipv4_pool, enum pool_type type, in_addr_t= start,
in_addr_t= end, const bool duplicate_cn,
- const bool ipv6_pool,
- = const struct in6_addr ipv6_base,
+ const= bool ipv6_pool, const struct in6_addr ipv6_base,
= const int ipv6_netbits);
=
void ifconfig_pool_free(struct ifconfig_pool *pool);

bool ifconfig_pool_verify_range(const int ms= glevel, const in_addr_t start, const in_addr_t end);

-ifconfig_pool_handle ifcon= fig_pool_acquire(struct ifconfig_pool *pool, in_addr_t *local, in_addr_t *r= emote, struct in6_addr *remote_ipv6, const char *common_name);
+ifconfig_pool_handle ifconfig_po= ol_acquire(struct ifconfig_pool *pool, in_addr_t *local,

+ = in_addr_t *remote, struct in6_addr *remote_ipv6,
+ = const char *common_name);

bool ifconfi= g_pool_release(struct ifconfig_pool *pool, ifconfig_pool_handle hand, const= bool hard);

diff --git a/src/openvpn/pro= to.c b/src/openvpn/proto.c
index 4820602..34b3378 100644
--- a/src/openvpn/proto.c
+++ b/src/openvpn/p= roto.c
@@ -54,8 +54,7 @@
else if (tunn= el_type =3D=3D DEV_TYPE_TAP)
{
= const struct openvpn_ethhdr *eh;
- if (BLEN(buf) < (sizeof(struct openvpn_ethhdr)
- += sizeof(struct openvpn_iphdr)))
+ if (BLEN(buf) < (sizeof(struct openvpn_ethhdr) + siz= eof(struct openvpn_iphdr)))
{
= return false;
}
@@ -71,8 = +70,7 @@
if (proto =3D=3D htons(OPENVPN_ETH_P_8021= Q))
{
const struct op= envpn_8021qhdr *evh;
- = if (BLEN(buf) < (sizeof(struct openvpn_ethhdr)
- + sizeo= f(struct openvpn_iphdr)))

+ if (BLEN(buf) < (sizeof(struct openvpn_ethhdr) + sizeo= f(struct openvpn_iphdr)))
{
= return false;
}
@@ -109,12 +107,12 @@

bool
is_ipv4(int t= unnel_type, struct buffer *buf)
{
- return is_ipv_X( tunnel_type, buf, 4 );
+ return is_ipv_X(tu= nnel_type, buf, 4);
}
bool
is_ipv6(int tunnel_type, struct buffer *buf)

{- return is_ipv_X( tunnel_ty= pe, buf, 6 );
+ re= turn is_ipv_X(tunnel_type, buf, 6);
}


@@ -131,9 +129,8 @@
*= /
for (int i =3D 0; i < len_payload; i +=3D 2)
{
- = sum +=3D (uint16_t)(((payload[i] << 8) & 0xFF00)
= - +((i = + 1 < len_payload) ? (payload[i + 1] & 0xFF) : 0));
-
+ sum +=3D (uint16_t)(((payload[i] << 8) &= ; 0xFF00)
+ = + ((i + 1 < len_payload) ? (payload[i + 1] & 0xFF) := 0));
}

/*
@@ -143,7 +140,6 @@
for (int i =3D 0; i &l= t; addr_len; i +=3D 2)
{
sum = +=3D (uint16_t)((src_addr[i] << 8) & 0xFF00) + (src_addr[i + 1] &= amp; 0xFF);
- }
for (int i =3D 0; i < addr_len; i += =3D 2)
{
@@ -166,17 +162,14 @@<= br> }

/* Take the one'= s complement of sum */
= - return ((uint16_t) ~sum);
+ return ((uint16_t)~sum);
}
=
#ifdef PACKET_TRUNCATION_CHECK
<= br> void
-ipv4_pa= cket_size_verify(const uint8_t *data,
- const int size,
- const int tunnel_= type,
- = const char *prefix,
- counter_type *errors)
+ipv4_packet_size_verify(const uint8_t *da= ta, const int size, const int tunnel_type,
+ const char *prefix, counter_= type *errors)
{
if (size > 0)
{
@@ -192,13 +185,13 @@
= const char *msgstr =3D "PACKET SIZE INFO";
<= span> unsigned int msglevel =3D D_PACKET_TRUNC_DEBUG;

- i= f (BLEN(&buf) < (int) sizeof(struct openvpn_iphdr))
+ if (BLEN(&buf) < = (int)sizeof(struct openvpn_iphdr))
{ return;
}

verify_align_4(&buf);
- pip =3D (struct openvpn_= iphdr *) BPTR(&buf);

+ pip =3D (struct openvpn_iphdr *)BPTR(&buf);
=
hlen =3D OPENVPN_IPH_GET_LEN(pip->v= ersion_len);
totlen =3D ntohs(pip->tot_len)= ;
@@ -213,13 +206,8 @@
}
}

- msg(msglevel, "%s %s: size=3D%d = totlen=3D%d hlen=3D%d errcount=3D" counter_format,
- msgstr,
- prefix,
- BLEN(&buf),
- totlen,
- hlen,
- errors ? = *errors : (counter_type)0);
+ msg(msglevel, "%s %s: size=3D%d totlen=3D%d hlen= =3D%d errcount=3D" counter_format, msgstr,
+ prefix, BLEN(&buf), totlen,= hlen, errors ? *errors : (counter_type)0);
}
}
}
diff --git a/src/open= vpn/proto.h b/src/openvpn/proto.h
index 0942c11..62157fa 10= 0644
--- a/src/openvpn/proto.h
+++ b/src/op= envpn/proto.h
@@ -32,15 +32,15 @@
* Tunne= l types
*/
#define DEV_TYPE_UNDEF 0
-#define DEV_TYPE_TUN 2 = /* point-to-point IP tunnel */
-#define DEV_TYPE_TAP 3 /* ethernet (802.3) tunnel */=
+#define DEV_TYPE_TUN 2 /= * point-to-point IP tunnel */
+#define DEV_TYPE_TAP 3 /* ethernet (802.3) tunnel */
=
/* TUN topologies */

<= span style=3D"color: hsl(0, 100%, 40%);">-#define TOP_UNDEF 0

<= span style=3D"color: hsl(0, 100%, 40%);">-#define TOP_NET30 1

<= span style=3D"color: hsl(0, 100%, 40%);">-#define TOP_P2P 2

<= span style=3D"color: hsl(0, 100%, 40%);">-#define TOP_SUBNET 3

<= span style=3D"color: hsl(120, 100%, 40%);">+#define TOP_UNDEF 0

= +#define TOP_NET30 1+#define TOP_P2P 2+#define TOP_SUBNET 3<= br>
/*
* IP and Ethernet protocol= structs. For portability,
@@ -49,46 +49,45 @@
<= span> * native structs.

*/

<= span style=3D"color: hsl(0, 100%, 40%);">-#define OPENVPN_ETH_ALEN 6 = /* ethernet address length */

+#define OPENVPN_ETH_ALEN 6 /* ethernet address length */
struct openvpn_ethhdr
{
= uint8_t dest[OPENVPN_ETH_ALEN]; /* destination ethernet addr */ uint8_t source[OPENVPN_ETH_ALEN]; /* source ethernet addr */=

-#de= fine OPENVPN_ETH_P_IPV4 0x0800 /* IPv4 protocol */
-#define OPENVPN_ETH_P_IPV6 0x86DD /* I= Pv6 protocol */
-#defin= e OPENVPN_ETH_P_ARP 0x0806 /* ARP protocol */
-#define OPENVPN_ETH_P_8021Q 0x8100 /* 802.1= Q protocol */
+#defin= e OPENVPN_ETH_P_IPV4 0x0800 /* IPv4 protocol */
+#define OPENVPN_ETH_P_IPV6 0x86DD /* = IPv6 protocol */
+#de= fine OPENVPN_ETH_P_ARP 0x0806 /* ARP protocol */
+#define OPENVPN_ETH_P_8021Q 0x8100 /* = 802.1Q protocol */
uint16_t proto; /= * packet type ID field */
};

<= span> struct openvpn_8021qhdr

{
- uint8_t dest[OPENVPN_ETH_ALEN]; /* desti= nation ethernet addr */
- uint8_t source[OPENVPN_ETH_ALEN]; /* source ethernet addr */=
+ uint8_t dest[OPENVPN_E= TH_ALEN]; /* destination ethernet addr */
+ uint8_t source[OPENVPN_ETH_ALEN]; = /* source ethernet addr */

- uint16_t tpid; /* 802.1Q T= ag Protocol Identifier */
+ uint16_t tpid; /* 802.1Q Tag Protocol I= dentifier */
#define OPENVPN_8021Q_MASK_PCP htons(0xE000) = /* mask PCP out of pcp_cfi_vid */
#define OPENVPN_8021Q_MA= SK_CFI htons(0x1000) /* mask CFI out of pcp_cfi_vid */
#de= fine OPENVPN_8021Q_MASK_VID htons(0x0FFF) /* mask VID out of pcp_cfi_vid */=
- uint16_t pcp_cfi_= vid; /* bit fields, see IEEE 802.1Q */
- uint16_t proto; /* = contained packet type ID field */
+ uint16_t pcp_cfi_vid; /* bit fields, s= ee IEEE 802.1Q */
+ = uint16_t proto; /* contained packet type ID fiel= d */
};

/*
* Size difference between a regular Ethernet II header and an Etherne= t II

* header with additional IEEE 802.1Q tagging.=
*/
-#define= SIZE_ETH_TO_8021Q_HDR (sizeof(struct openvpn_8021qhdr) \
- - sizeof= (struct openvpn_ethhdr))
+#define SIZE_ETH_TO_8021Q_HDR (sizeof(struct openvpn_8021qhdr) - sizeo= f(struct openvpn_ethhdr))

/** Version of= IN6_ARE_ADDR_EQUAL that is guaranteed to work for
* una= ligned access. E.g. Linux uses 32bit compares which are
*= not safe if the struct is unaligned. */
-#define OPENVPN_IN6_ARE_ADDR_EQUAL(a, b) \
- (memcmp(a, b, sizeof(struct in= 6_addr)) =3D=3D 0)

+#= define OPENVPN_IN6_ARE_ADDR_EQUAL(a, b) (memcmp(a, b, sizeof(struct in6_add= r)) =3D=3D 0)

-struct openvpn_iphdr {
+struct openvpn_iphdr
+{
#define OPENVPN_IPH_GET_VER(v) (((v) >&= gt; 4) & 0x0F)
#define OPENVPN_IPH_GET_LEN(v) (((v) &a= mp; 0x0F) << 2)
uint8_t version_len;
<= span>@@ -102,9 +101,9 @@


uint8_t ttl= ;

-#d= efine OPENVPN_IPPROTO_IGMP 2 /* IGMP protocol */
-#define OPENVPN_IPPROTO_TCP 6 /* TCP p= rotocol */
-#define OPE= NVPN_IPPROTO_UDP 17 /* UDP protocol */
+#define OPENVPN_IPPROTO_IGMP 2 /* IGMP protocol *= /
+#define OPENVPN_IP= PROTO_TCP 6 /* TCP protocol */
+#define OPENVPN_IPPROTO_UDP 17 /* UDP protocol */<= br> #define OPENVPN_IPPROTO_ICMPV6 58 /* ICMPV6 protocol */ uint8_t protocol;

@@ -117,31 = +116,33 @@
/*
* IPv6 header
*/

-struct openvp= n_ipv6hdr {
+struct o= penvpn_ipv6hdr
+{
uint8_t version_prio;
uint8_t flow_l= bl[3];
uint16_t payload_len;
uint= 8_t nexthdr;
uint8_t hop_limit;

- struct in6_addr saddr= ;
- struct in6_addr= daddr;
+ struct i= n6_addr saddr;
+ s= truct in6_addr daddr;
};

/*

* ICMPv6 header
*/
-struct openvpn_icmp6hdr {

<= span style=3D"color: hsl(0, 100%, 40%);">-#define OPENVPN_ICMP6_DESTINATION= _UNREACHABLE 1

-#= define OPENVPN_ND_ROUTER_SOLICIT 133
-#define OPENVPN_ND_ROUTER_ADVERT = 134
-#define OPE= NVPN_ND_NEIGHBOR_SOLICIT 135
-#define OPENVPN_ND_NEIGHBOR_ADVERT 136<= /span>
-#define OPENVPN_ND_INV= ERSE_SOLICIT 141
-#define OPENVPN_ND_INVERSE_ADVERT 142
<= span style=3D"color: hsl(120, 100%, 40%);">+struct openvpn_icmp6hdr
<= br>+{
+#define OPENVPN_ICMP6_DESTINATION_UNREACHABLE= 1
+#define OPENVPN_N= D_ROUTER_SOLICIT 133
+#define OPENVPN_ND_ROUTER_ADVERT 134
+#define OPENVPN_ND_NEIGHBOR_SOLI= CIT 135

+#d= efine OPENVPN_ND_NEIGHBOR_ADVERT 136
+#define OPENVPN_ND_INVERSE_SOLICIT 1= 41
+#define OPENVPN_N= D_INVERSE_ADVERT 142
uint8_t icmp6_type;
-#define OPENVPN_ICMP6_D= U_NOROUTE 0
-#define OPENVPN_ICMP6_DU_COMMUNICATION_PROHIBTED 1
+#define OPENVPN_ICMP6_DU_NOROUTE= 0

+#= define OPENVPN_ICMP6_DU_COMMUNICATION_PROHIBTED 1
uint= 8_t icmp6_code;
uint16_t icmp6_cksum;
= uint8_t icmp6_dataun[4];
@@ -150,7 +151,8 @@ /*
* UDP header
*/
-struct openvpn_udphdr {

= +struct openvpn_udphdr+{
uint1= 6_t source;
uint16_t dest;
uint16= _t len;
@@ -160,23 +162,24 @@
/* * TCP header, per RFC 793.
*/
-struct openvpn_tcphdr {
- uint16_t source; /* source p= ort */
- uint16_t de= st; /* destination port */
- uint32_t seq; /* sequence number */
- uint32_t ack_seq; /* ackno= wledgement number */

= +struct openvpn_tcphdr
+ uint16_t so= urce; /* source port */
+ uint16_t dest; /* destination port */
+ uint32_t seq; /* sequence number */
+ uint32_t ack_seq;= /* acknowledgement number */

#define OP= ENVPN_TCPH_GET_DOFF(d) (((d) & 0xF0) >> 2)
u= int8_t doff_res;

-#define OPENVPN_TCPH_FIN_MASK (1<<0)
-#define OPENVPN_TCPH_SYN_MASK (1<<1= )
-#define OPENVPN_TCPH= _RST_MASK (1<<2)
= -#define OPENVPN_TCPH_PSH_MASK (1<<3)
-#define OPENVPN_TCPH_ACK_MASK (1<<4)
= -#define OPENVPN_TCPH_URG_MASK (1= <<5)
-#define OPE= NVPN_TCPH_ECE_MASK (1<<6)
-#define OPENVPN_TCPH_CWR_MASK (1<<7)
+#define OPENVPN_TCPH_FIN_MASK (1 <<= 0)
+#define OPENVPN_= TCPH_SYN_MASK (1 << 1)
+#define OPENVPN_TCPH_RST_MASK (1 << 2)
+#define OPENVPN_TCPH_PSH_MASK (1 <<= 3)
+#define OPENVPN_= TCPH_ACK_MASK (1 << 4)
+#define OPENVPN_TCPH_URG_MASK (1 << 5)
+#define OPENVPN_TCPH_ECE_MASK (1 <<= 6)
+#define OPENVPN_= TCPH_CWR_MASK (1 << 7)
uint8_t flags;
=
uint16_t window;
@@ -189,9 +19= 2,11 @@
#define OPENVPN_TCPOPT_MAXSEG 2
= #define OPENVPN_TCPOLEN_MAXSEG 4

-struct ip_tcp_udp_hdr {
+struct ip_tcp_udp_hdr
+{
struct openvpn_i= phdr ip;
- union {
+ union
<= span style=3D"color: hsl(120, 100%, 40%);">+ {

= struct openvpn_tcphdr tcp;
struct openvpn_udphdr u= dp;
} u;
@@ -207,30 +212,36 @@<= br> * subtracting out new words), and "cksum"
* is the checksum value to be updated.

*/-#define ADJUST_CHECKSUM(acc, ck= sum) { \
- int _= acc =3D acc; \
- = _acc +=3D (cksum); \
-= if (_acc < 0) { \
- _acc =3D -_acc; \
+#define ADJUST_CHECKSUM(acc, cksum) \
+ { = \
+ int _acc =3D acc; \
+ _acc +=3D (cksum); = \

+ { = \
+ = _acc =3D -_acc; \
= _acc =3D (_acc >> 16) + (_acc & 0xffff); \
- _acc +=3D _acc >> 16= ; \
- (cksum= ) =3D (uint16_t) ~_acc; \
- } else { \
+ (cksum) =3D (uint16= _t)~_acc; \
+ } \
+ else = \
+ = { \
= _acc =3D (_acc >> 16) + (_acc & 0xffff); \
- _acc +=3D _acc >> 16; \<= /span>
- (cksum) = =3D (uint16_t) _acc; \
= - } \
-}<= br>+ _acc +=3D _acc = >> 16; \
+ (cksum) =3D (uint16_t)_acc; \=
+ } = \
+ }

-#define ADD_CHECKSUM_32(acc, u32) { \
- acc +=3D (u32) & 0xffff; \
<= span style=3D"color: hsl(0, 100%, 40%);">- acc +=3D (u32) >> 1= 6; \

-}
+#define ADD_CHECKSUM_32(acc, u32= ) \

+ { = \
+= acc +=3D (u32) & 0xffff; \
+ acc +=3D (u32) >> 16; \+ }

-#define SUB_CHECKSUM_32(acc= , u32) { \
- acc= -=3D (u32) & 0xffff; \
- acc -=3D (u32) >> 16; \
-}
+#define SUB_CHECKSUM_32(acc, u32) \
+ { \
+ acc -=3D (u32) & 0xffff;= \
+ acc -= =3D (u32) >> 16; \
+ }

/*
* = This returns an ip protocol version of packet inside tun
@@= -245,7 +256,7 @@
if (tunnel_type =3D=3D DEV_TYPE_TUN)=
{
*ip_hdr_offset =3D 0;
- if (likely(BLEN(bu= f) >=3D (int) sizeof(struct openvpn_iphdr)))
+ if (likely(BLEN(buf) >=3D (int)sizeo= f(struct openvpn_iphdr)))
{
= ip_ver =3D OPENVPN_IPH_GET_VER(*BPTR(buf));
= }
@@ -256,7 +267,7 @@
/* for tap = get ip version from eth header */
if (likely(BLEN(= buf) >=3D *ip_hdr_offset))
{
- const struct openvpn_ethhdr = *eh =3D (const struct openvpn_ethhdr *) BPTR(buf);
+ const struct openvpn_ethhdr *eh = =3D (const struct openvpn_ethhdr *)BPTR(buf);
= uint16_t proto =3D ntohs(eh->proto);
if (pr= oto =3D=3D OPENVPN_ETH_P_IPV6)
{
@@ -293,17 +304,12 @@

* @param proto next - header = or IP protocol of the packet
* @return The calculated che= cksum in host order
*/
-uint16_t
-ip_checksum(const sa_family_t af, const uint8_t *payload, const int l= en_payload,
- = const uint8_t *src_addr, const uint8_t *dest_addr, const int proto);
+uint16_t ip_checksum(co= nst sa_family_t af, const uint8_t *payload, const int len_payload,+ const u= int8_t *src_addr, const uint8_t *dest_addr, const int proto);

#ifdef PACKET_TRUNCATION_CHECK
-void ipv4_packet_size_verify(const uint8_t = *data,
- = const int size,
- const int tunnel_type,
- const ch= ar

- = *prefix,
- = counter_type *errors);
+void ipv4_packet_size_verify(const uint8_t *da= ta, const int size, const int tunnel_type,
+ const char *prefix, cou= nter_type *errors);

#endif

diff --git a/src/openvpn/proxy.c b/src/openvpn/proxy.c=
index 393abb4..054cc79 100644
--- a/src/op= envpn/proxy.c
+++ b/src/openvpn/proxy.c
@@ = -39,11 +39,10 @@
#include "memdbg.h"
<= span> #include "forward.h"


-#define UP_TYPE_PROXY "HTTP Pr= oxy"
+#define UP= _TYPE_PROXY "HTTP Proxy"

struc= t http_proxy_options *
= -init_http_proxy_options_once(struct http_proxy_options **hpo,
- struc= t gc_arena *gc)

+init= _http_proxy_options_once(struct http_proxy_options **hpo, struct gc_arena *= gc)
{
if (!*hpo)
= {
@@ -59,13 +58,8 @@
static struct user_p= ass static_proxy_user_pass;

static bool<= /span>
-recv_line(socket_descr= iptor_t sd,
- = char *buf,
- i= nt len,
- cons= t int timeout_sec,
- = const bool verbose,
- struct buffer *lookahead,
- volatile int *signal_received)
+recv_line(socket_descriptor_t sd, c= har *buf, int len, const int timeout_sec, const bool verbose,

+ struct buffer *lookahea= d, volatile int *signal_received)

{
s= truct buffer la;
int lastc =3D 0;
@@ -= 161,7 +155,8 @@
{
= if (verbose)
{
- msg(D_LINK_ERRORS | M_E= RRNO, "recv_line: Non-ASCII character (%d) read on recv()", (int)= c);
+ = msg(D_LINK_ERRORS | M_ERRNO,
+ "recv_line: Non-ASCII character (= %d) read on recv()", (int)c);
}
*lookahead =3D la;
= return false;
@@ -190,11 +185,10 @@
}=

static bool
-send_line(socket_descriptor_t sd,
- const char *buf)

= +send_line(socket_descriptor_t = sd, const char *buf)
{
const ssize_t = size =3D send(sd, buf, strlen(buf), MSG_NOSIGNAL);
- if (size !=3D (ssize_t) strlen(buf))
+ if (size !=3D (ssize_= t)strlen(buf))
{
msg(D_LINK_E= RRORS | M_ERRNO, "send_line: TCP port write failed on send()");
return false;
@@ -203,8 +197,7 @@
}

static bool
= -send_line_crlf(socket_descriptor= _t sd,
- = const char *src)
+sen= d_line_crlf(socket_descriptor_t sd, const char *src)
{
bool ret;

@@ -228,7 +22= 1,7 @@
uint8_t *ret =3D NULL;
cha= r *b64out =3D NULL;
ASSERT(openvpn_base64_encode((cons= t void *)str, src_len, &b64out) >=3D 0);
- ret =3D (uint8_t *) string_alloc(b64out, gc);=
+ ret =3D (uint8_= t *)string_alloc(b64out, gc);
free(b64out);
= return ret;
}
@@ -240,8 +233,7 = @@
}

static const char = *
-username_password_as= _base64(const struct http_proxy_info *p,
- struct gc_arena *gc)<= br>+username_password_as_base64= (const struct http_proxy_info *p, struct gc_arena *gc)
{
struct buffer out =3D alloc_buf_gc(strlen(p->up.user= name) + strlen(p->up.password) + 2, gc);
ASSERT(str= len(p->up.username) > 0);
@@ -285,10 +277,7 @@=
{
flags |=3D GET_USER_PASS_= INLINE_CREDS;
}
- get_user_pass(&static_proxy_user_pass,
- auth_= file,
- = UP_TYPE_PROXY,
- = flags);
+ get_user_pass(&static_proxy_user_pass, auth_file, UP_T= YPE_PROXY, flags);
static_proxy_user_pass.nocache = =3D p->options.nocache;
protect_user_pass(&= static_proxy_user_pass);
}
@@ -325,9 += 314,7 @@
* Consumes all headers.
*/
static int
- int timeout,
<= span style=3D"color: hsl(0, 100%, 40%);">- char **dat= a,

+get_proxy_authent= icate(socket_descriptor_t sd, int timeout, char **data,
= volatile int *signal_received)
{
char buf[256];
@@ -347,22 +334,22 @@
}
if (ret =3D=3D HTTP_AUTH_NON= E && !strncmp(buf, "Proxy-Authenticate: ", 20)) {
- = if (!strncmp(buf+20, "Basic ", 6))
+ if (!strncmp(buf + 20, "= Basic ", 6))
{
= msg(D_PROXY, "PROXY AUTH BASIC: '%s'", buf);
- *data =3D s= tring_alloc(buf+26, NULL);
+ *data =3D string_alloc(buf + 26, NULL);
ret =3D HTTP_AUTH_BASIC;

= }
#if PROXY_DIGEST_AUTH
- else if (!strncmp(buf+20, "Digest "= ;, 7))
+ e= lse if (!strncmp(buf + 20, "Digest ", 7))
= {
msg(D_PROXY, "PROXY AUTH DIGE= ST: '%s'", buf);
- *data =3D string_alloc(buf+27, NULL);
+ *data =3D string_= alloc(buf + 27, NULL);

ret =3D HTTP_AUTH_D= IGEST;
}
#endif
#if NTLM

- = else if (!strncmp(buf+20, "NTLM", 4))
+ else if (!strncmp(buf + 20, &quo= t;NTLM", 4))
{
= msg(D_PROXY, "PROXY AUTH NTLM: '%s'", buf);=
*data =3D NULL;
@@ -385,18 +372,= 16 @@
* Return true on success, or false on parse failure= .
*/
static bool
-get_key_value(const char *str, /* sou= rce string */
- = char *key, /* key stored here */
- char *value, /* value = stored here */
- = int max_key_len,
- int max_value_len,
- const char **endptr) /* next search position *= /
+get_key_value(cons= t char *str, /* source string */
+ char *ke= y, /* key stored here */
+ char *valu= e, /* value stored here */
+ int max_ke= y_len, int max_value_len, const char **endptr) /* next search position */
{
int c;
bool sta= rts_with_quote =3D false;
bool escape =3D false;

- for (= c =3D max_key_len-1; (*str && (*str !=3D '=3D') && = c--); )
+ for (c = =3D max_key_len - 1; (*str && (*str !=3D '=3D') && = c--);)
{
*key++ =3D *str++;
}
@@ -415,7 +400,7 @@
= starts_with_quote =3D true;
}
=
- for (c =3D max_v= alue_len-1; *str && c--; str++)
+ for (c =3D max_value_len - 1; *str && c--; = str++)
{
switch (*str)=
{
@@ -529,7 +514,8 @@
#= if NTLM
else if (!strcmp(o->auth_method_string,= "ntlm"))
{
- msg(M_WARN, "NTLM v1 authenticati= on has been removed in OpenVPN 2.7. Will try to use NTLM v2 authentication.= ");
+ = msg(M_WARN,
+ = "NTLM v1 authentication has been removed in OpenVPN 2.7. Will= try to use NTLM v2 authentication.");
p-= >auth_method =3D HTTP_AUTH_NTLM2;
}
<= span> else if (!strcmp(o->auth_method_string, "ntlm2")= )

@@ -539,8 +525,7 @@
#endif
else

{
- msg(M_FATAL, "ERROR: unknown HTTP au= thentication method: '%s'",
- o->auth_method_string);
+ msg(M_FATAL, "ER= ROR: unknown HTTP authentication method: '%s'", o->auth_met= hod_string);

}
}

@@ -555,7 +540,8 @@
#if !NTLM=
if (p->auth_method =3D=3D HTTP_AUTH_NTLM2)
{

- msg(M= _FATAL, "Sorry, this version of " PACKAGE_NAME " was built w= ithout NTLM Proxy support.");
+ msg(M_FATAL,
+ "Sorry, this version of " PACKAGE_NAM= E " was built without NTLM Proxy support.");
= }
#endif

@@ -570,10 +55= 6,9 @@
}

static bool
-add_proxy_headers(struct= http_proxy_info *p,
- = socket_descriptor_t sd, /* already open to proxy */=
- const char= *host /* openvpn server remote */
- )
+add_proxy_headers(struct http_proxy_info *p, socket_des= criptor_t sd, /* already open to proxy */
+ const char *host = /* openvpn server remote */
+)
{
char buf[= 512];
int i;
@@ -584,12 +569,11 @@
* If content is NULL the whole header is in name<= br> * Also remember if we already sent a Host: header
= */
- for= (i =3D 0; i < MAX_CUSTOM_HTTP_HEADER && p->options.custom_h= eaders[i].name; i++)
= + for (i =3D 0; i < MAX_CUSTOM_HTTP_HEADER && p->options.c= ustom_headers[i].name; i++)
{
= if (p->options.custom_headers[i].content)
{
- snprintf(buf= , sizeof(buf), "%s: %s",
- p->options.custom_headers[i].name,
+ snprintf(bu= f, sizeof(buf), "%s: %s", p->options.custom_headers[i].name,
p->options.custom_headers[i].conten= t);
if (!strcasecmp(p->options.custom_heade= rs[i].name, "Host"))
{
@@ -598,8 +582,7 @@

}
= else
{
- snprintf(buf, sizeof(buf), "%s",
= - p->optio= ns.custom_headers[i].name);
+ snprintf(buf, sizeof(buf), "%s", p->option= s.custom_headers[i].name);
if (!strncasecmp(p-= >options.custom_headers[i].name, "Host:", 5))
= {
host_header_sent =3D true;<= /span>
@@ -626,8 +609,7 @@
/* send User-Agent= string if provided */
if (p->options.user_agent)
{
-= snprintf(buf, sizeof(buf), "User-Agent: %s",
- p->options.use= r_agent);

+ sn= printf(buf, sizeof(buf), "User-Agent: %s", p->options.user_age= nt);
msg(D_PROXY, "Send to HTTP proxy: '%= s'", buf);
if (!send_line_crlf(sd, buf))<= /span>
{
@@ -641,11 +623,10 @@
=
bool
establish_http_proxy_passthr= u(struct http_proxy_info *p,
- socket_descriptor_t sd, /* already op= en to proxy */
- = const char *host, /* openvpn server remote */=
- = const char *port, /* openvpn server port */
- struc= t event_timeout *server_poll_timeout,

- struct buffer *lookahead,
+ = socket_descriptor_t sd, /* already open to proxy */
+ const = char *host, /* openvpn server remote */
+ const char *port, = /* openvpn server port */
+ struct event_timeout *server_poll_= timeout, struct buffer *lookahead,
= struct signal_info *sig_info)
{
= struct gc_arena gc =3D gc_new();
@@ -657,8 +638,7 @@
volatile int *signal_received =3D &sig_info->signal= _received;

/* get user/pass if not p= reviously given */
- = if (p->auth_method =3D=3D HTTP_AUTH_BASIC
- || p->auth_method =3D=3D HTTP_AUTH_DIGES= T
+ if (p->auth= _method =3D=3D HTTP_AUTH_BASIC || p->auth_method =3D=3D HTTP_AUTH_DIGEST=
|| p->auth_method =3D=3D HTTP_AUTH_NTLM2)
{
get_user_pass_http(p, false);
@@ -670,7 +650,8 @@
unprotect_user_= pass(&p->up);
}

- /* are we being called again af= ter getting the digest server nonce in the previous transaction? */
<= br>+ /* are we being called = again after getting the digest server nonce in the previous transaction?
+ */
if (p->auth_method =3D=3D HTTP_AUTH_DIGEST && p->proxy= _authenticate)

{
nparms =3D 1= ;
@@ -679,10 +660,7 @@
else
= {
/* format HTTP CONNECT message */
- snprintf(buf, siz= eof(buf), "CONNECT %s:%s HTTP/%s",
- host,
- port,
- p->options.http_version);
+ snprintf(buf, si= zeof(buf), "CONNECT %s:%s HTTP/%s", host, port, p->options.htt= p_version);

msg(D_PROXY, "S= end to HTTP proxy: '%s'", buf);

@@ -723,8 +701,7 @@

goto error;
}

- snprintf(buf, sizeof(buf), &qu= ot;Proxy-Authorization: NTLM %s",
- ntlm_phase_1(p, &gc));=
+ snprintf(b= uf, sizeof(buf), "Proxy-Authorization: NTLM %s", ntlm_phase_1(p, = &gc));
msg(D_PROXY, "Attempting N= TLM Proxy-Authorization phase 1");
dm= sg(D_SHOW_KEYS, "Send to HTTP proxy: '%s'", buf);<= br> if (!send_line_crlf(sd, buf))
@@ = -748,7 +725,8 @@
}

/* receive reply from proxy */

- if (!recv_line(sd, buf, sizeof(buf), get_serve= r_poll_remaining_time(server_poll_timeout), true, NULL, signal_received))
+ if (!recv_lin= e(sd, buf, sizeof(buf), get_server_poll_remaining_time(server_poll_timeout)= ,
+ = true, NULL, signal_received))
{
goto error;

}
@@ -= 760,7 +738,6 @@

/* parse return = string */
nparms =3D sscanf(buf, "%*s %d"= ;, &status);
-
}

/* check for a &q= uot;407 Proxy Authentication Required" response */
@@ = -779,7 +756,9 @@
char buf2[512];
while (true)

{
- if (!recv_line(sd, bu= f, sizeof(buf), get_server_poll_remaining_time(server_poll_timeout), true, = NULL, signal_received))

+ if (!recv_line(sd, buf, sizeof(buf),
+ get_ser= ver_poll_remaining_time(server_poll_timeout), true, NULL,
+ signal= _received))
{
= goto error;
}
@@ = -810,9 +789,7 @@
/* now send the phase 3 reply= */

/* format HTTP CONNECT m= essage */
- = snprintf(buf, sizeof(buf), "CONNECT %s:%s HTTP/%s",
- host,
- port,
+ snprintf(bu= f, sizeof(buf), "CONNECT %s:%s HTTP/%s", host, port,
p->options.http_version);


msg(D_PROXY, "Send to HTTP proxy: '%s&#= 39;", buf);
@@ -841,7 +818,8 @@
= const char *np3 =3D ntlm_phase_3(p, buf2, &gc);
if (!np3)

{- msg(D_PROXY= , "NTLM Proxy-Authorization phase 3 failed: received corrupted data fr= om proxy server");
+ msg(D_PROXY,
+ "NTLM Proxy-Authorization pha= se 3 failed: received corrupted data from proxy server");
goto error;

}
snprintf(buf, sizeof(buf), "Proxy-Author= ization: NTLM %s", np3);
@@ -860,7 +838,9 @@ }

/* rec= eive reply from proxy */
+ if (!recv_line(sd, buf,= sizeof(buf),
+ = get_server_poll_remaining_time(server_poll_timeout), t= rue, NULL,
+ = signal_received))
{ goto error;
}<= br>@@ -904,7 +884,7 @@
if (!realm ||= !nonce)
{
= msg(D_LINK_ERRORS, "HTTP proxy: digest auth failed, malformed re= sponse "
- = "from server: realm=3D or nonce=3D missing" );
+ = "from server: realm=3D or nonce=3D missing");
goto error;
= }

@@ -914,38 +894,21 @@


/* build the diges= t response */
- = snprintf(uri, sizeof(uri), "%s:%s",
- host,
- port);
+ snprin= tf(uri, sizeof(uri), "%s:%s", host, port);

if (opaque)
{=
- c= onst int len =3D strlen(opaque)+16;
+ const int len =3D strlen(opaque) + 16;<= /span>
opaque_kv =3D gc_malloc(len, false, &a= mp;gc);
snprintf(opaque_kv, len, "= ;, opaque=3D\"%s\"", opaque);
= }

= - DigestCalcHA1(algor,
- username,
- realm,
- = password,
- = nonce,
- (char *)cnonce,
- session_key);=
- Diges= tCalcResponse(session_key,
- nonce,
- nonce_count,
- = (char *)cnonce,
- qop,
- http_method,
- = uri,
- = NULL,
- response);
+ DigestCalcHA1(algor, u= sername, realm, password, nonce, (char *)cnonce, session_key);
+ DigestCalcRespon= se(session_key, nonce, nonce_count, (char *)cnonce, qop,

+ htt= p_method, uri, NULL, response);

= /* format HTTP CONNECT message */
- snprintf(buf, sizeof(buf), "%s %s = HTTP/%s",
- = http_method,
- uri,
+ snprintf(buf, sizeof(buf), "%s %s H= TTP/%s", http_method, uri,
p= ->options.http_version);

= msg(D_PROXY, "Send to HTTP proxy: '%s'", buf);=
@@ -963,17 +926,10 @@
}
/* send digest response */
- int sret = =3D snprintf(buf, sizeof(buf), "Proxy-Authorization: Digest username= =3D\"%s\", realm=3D\"%s\", nonce=3D\"%s\", ur= i=3D\"%s\", qop=3D%s, nc=3D%s, cnonce=3D\"%s\", respons= e=3D\"%s\"%s",
- username,
- realm,<= /span>
- = nonce,
- = uri,
- qop,
- no= nce_count,
- = cnonce,
- response,
- opaq= ue_kv
- = );
+ buf, sizeof(buf),
+ "Proxy-Aut= horization: Digest username=3D\"%s\", realm=3D\"%s\", n= once=3D\"%s\", uri=3D\"%s\", qop=3D%s, nc=3D%s, cnonce= =3D\"%s\", response=3D\"%s\"%s",

+ username, realm, = nonce, uri, qop, nonce_count, cnonce, response, opaque_kv);
if (sret >=3D sizeof(buf))

= {
goto error;
@@= -992,7 +948,9 @@
secure_memzero(buf, size= of(buf));

/* receive rep= ly from proxy */
- = if (!recv_line(sd, buf, sizeof(buf), get_server_poll_remaining_t= ime(server_poll_timeout), true, NULL, signal_received))
+ if (!recv_line(sd, buf,= sizeof(buf),
+ = get_server_poll_remaining_time(server_poll_timeout= ), true, NULL,
+ = signal_received))
= {
goto error;
= }
@@ -1017,10 +975,8 @@
= {
/* figure out what kind of authentication t= he proxy needs */
char *pa =3D NULL;- const int method = =3D get_proxy_authenticate(sd,
- get_server_p= oll_remaining_time(server_poll_timeout),
- &a= mp;pa,
- = signal_received);
+ const int method =3D get_p= roxy_authenticate(
+ = sd, get_server_poll_remaining_time(server_poll_timeout), &am= p;pa, signal_received);
if (method !=3D HTTP_A= UTH_NONE)
{
i= f (pa)
@@ -1029,7 +985,8 @@
= }
if (p->options.auth_retry =3D=3D PA= R_NCT && method =3D=3D HTTP_AUTH_BASIC)
= {
- = msg(D_PROXY, "HTTP proxy: support for basic auth and other clear= text proxy auth methods is disabled");
+ msg(D_PROXY,
+ "HTTP pro= xy: support for basic auth and other cleartext proxy auth methods is disabl= ed");
free(pa);
= goto error;
}@@ -1040,7 +997,8 @@
}
else

{
- msg(D_PROXY, "HTTP proxy: = do not recognize the authentication method required by proxy");=
+ msg(D_PROX= Y,
+ = "HTTP proxy: do not recognize the authentication method required by= proxy");
free(pa);
= goto error;
}
= @@ -1069,7 +1027,8 @@
/* SUCCESS */
<= /span>
/* receive line from proxy and discard */
- if (!recv_line(sd, NULL, 0, ge= t_server_poll_remaining_time(server_poll_timeout), true, NULL, signal_recei= ved))

+ if (!recv_= line(sd, NULL, 0, get_server_poll_remaining_time(server_poll_timeout), true= , NULL,
+ = signal_received))
{
go= to error;
}
@@ -1082,7 +1041,8 @@
{
}

- /* reset queried_creds so that we= don't think that the next creds request is due to an auth error */
+ /* reset queried_cr= eds so that we don't think that the next creds request is due to an aut= h
+ * error */
p->queried_creds =3D false;
<= br> #if 0
diff --git a/src/openvpn/proxy.h b/src/open= vpn/proxy.h
index fcca1ab..be16d83 100644
-= -- a/src/openvpn/proxy.h
+++ b/src/openvpn/proxy.h@@ -34,19 +34,21 @@
#define HTTP_AUTH_NTLM2 4
#define HTTP_AUTH_N 5 /* number of HTTP_AUTH methods */<= /span>

-stru= ct http_custom_header {
+struct http_custom_header
+{
const char *name;
con= st char *content;
};

#d= efine MAX_CUSTOM_HTTP_HEADER 10
-struct http_proxy_options {
+struct http_proxy_options
+{
const char *server; const char *port;

-#define PAR_NO 0 /* don't support any aut= h retries */
-#define P= AR_ALL 1 /* allow all proxy auth protocols */
-#define PAR_NCT 2 /* disable cleartext proxy au= th protocols */
+#def= ine PAR_NO 0 /* don't support any auth retries */
+#define PAR_ALL 1 /* allow all proxy aut= h protocols */
+#defi= ne PAR_NCT 2 /* disable cleartext proxy auth protocols */
= int auth_retry;

const char *auth= _method_string;
@@ -56,11 +58,13 @@
co= nst char *user_agent;
struct http_custom_header custom= _headers[MAX_CUSTOM_HTTP_HEADER];
bool inline_creds; /= * auth_file_up is inline credentials */
- bool first_time; /* indicates if we need to wipe user= creds at the first iteration of the main loop */
+ bool first_time; /* indicates if we nee= d to wipe user creds at the first iteration of the main
+ loop */

bool nocache;
};
<= br>-struct http_proxy_info {
+struct http_proxy_info
+{
= bool defined;
int auth_method;
= struct http_proxy_options options;
@@ -77,12 +81,11 @@
void http_proxy_close(struct http_proxy_info *hp);
<= span>

bool establish_http_proxy_passthru(struct http_prox= y_info *p,
- = socket_descriptor_t sd, /* already open to proxy *= /
- = const char *host, /* openvpn server remote */<= br>- = const char *port, /* openvpn server port */
+ s= ocket_descriptor_t sd, /* already open to proxy */
+ const cha= r *host, /* openvpn server remote */
+ const char *port,= /* openvpn server port */
= struct event_timeout *server_poll_timeout,
- struct b= uffer *lookahead,
- = struct signal_info *sig_info);
+ = struct buffer *lookahead, struct signal_info *sig_info);

=
uint8_t *make_base64_string2(const uint8_t *str, int str= _len, struct gc_arena *gc);

diff --git a/= src/openvpn/ps.c b/src/openvpn/ps.c
index 6c6e5ea..eae03e3 = 100644
--- a/src/openvpn/ps.c
+++ b/src/ope= nvpn/ps.c
@@ -46,24 +46,25 @@
#define COMM= AND_EXIT 11

/* Response codes for ba= ckground -> foreground communication */
-#define RESPONSE_INIT_SUCCEEDED 20
-#define RESPONSE_INIT_FAILED 21
+#define RESPONSE_INIT_= SUCCEEDED 20
+#define= RESPONSE_INIT_FAILED 21

/* * Return values for proxy_connection_io functions
= */

= -#define IOSTAT_EAGAIN_ON_READ 0 /* recv returned EAGAIN */
-#define IOSTAT_EAGAIN_ON_WRITE 1 /= * send returned EAGAIN */

-#define IOSTAT_READ_ERROR 2 /* the other end of our read socket (= pc) was closed */
-#def= ine IOSTAT_WRITE_ERROR 3 /* the other end of our write socket (pc->= counterpart) was closed */
-#define IOSTAT_GOOD 4 /* nothing to report */
+#define IOSTAT_EAGAIN_ON_READ 0= /* recv returned EAGAIN */

+#define IOSTAT_EAGAIN_ON_WRITE 1 /* send returned EAGAIN */<= br>+#define IOSTAT_READ_ERROR = 2 /* the other end of our read socket (pc) was closed */
+#define IOSTAT_WRITE_ERROR 3 /= * the other end of our write socket (pc->counterpart) was closed */
+#define IOSTAT_GOOD = 4 /* nothing to report */

/*
* A foreign (non-OpenVPN) connection we are proxying,<= br> * usually HTTPS
*/
-struct proxy_connection {
+struct proxy_connection
+{
bool defined;<= /span>
struct proxy_connection *next;
st= ruct proxy_connection *counterpart;
@@ -156,11 +157,11 @@
static int
send_control(const socket_descr= iptor_t fd, int code)
{
- unsigned char c =3D (unsigned char) code;
= + unsigned char c =3D (unsig= ned char)code;
const ssize_t size =3D write(fd, &c= , sizeof(c));
if (size =3D=3D sizeof(c))
{

- retu= rn (int) size;
+ = return (int)size;
}
else
{
@@ -182,9 +183,7 @@
* s= end commands, data, and file descriptors to the background process.<= br> */
static void
-port_share_sendmsg(const socket_descriptor_t sd,
- const ch= ar command,
- = const struct buffer *head,
+port_share_sendmsg(const socket_descriptor_t sd, const char= command, const struct buffer *head,
co= nst socket_descriptor_t sd_send)
{
if= (socket_defined(sd))
@@ -196,8 +195,7 @@
= char cmd;
ssize_t status;
=
- dmsg(D_PS_PR= OXY_DEBUG, "PORT SHARE: sendmsg sd=3D%d len=3D%d",
- (int)sd_send,
+ dmsg(D_PS_PROXY_DEBUG= , "PORT SHARE: sendmsg sd=3D%d len=3D%d", (int)sd_send, head ? BLEN(head) : -1);

<= span> CLEAR(mesg);

@@ -218,7 +216,7 @@
mesg.msg_iov =3D iov;


= mesg.msg_controllen =3D cmsg_size();
- mesg.msg_control =3D (char *) malloc(mesg.msg_con= trollen);
+ me= sg.msg_control =3D (char *)malloc(mesg.msg_controllen);
= check_malloc_return(mesg.msg_control);
mesg.= msg_flags =3D 0;

@@ -240,9 +238,9 @@
status =3D sendmsg(sd, &mesg, MSG_NOSIGNAL);
if (status =3D=3D -1)
{=
- msg(M_WARN|M_ERR= NO, "PORT SHARE: sendmsg failed -- unable to communicate with backgrou= nd process (%d,%d,%d,%d)",
- sd, sd_send, sd_null[0], sd_null[1]
- );

+ msg(M_WARN | M_ERRNO,
+ "= PORT SHARE: sendmsg failed -- unable to communicate with background process= (%d,%d,%d,%d)",
+ sd, sd_send, sd_null[0], sd_null[1]);
= }

close_socket_if_defined(= sd_null[0]);
@@ -345,13 +343,13 @@
=
slen =3D sizeof(from.addr);
dlen =3D si= zeof(to.addr);
- if = (!getpeername(pc->sd, (struct sockaddr *) &from.addr.sa, &slen)<= /span>
- && !ge= tsockname(cp->sd, (struct sockaddr *) &to.addr.sa, &dlen))
+ if (!getpeername(pc-&= gt;sd, (struct sockaddr *)&from.addr.sa, &slen)
+ && !getsockname(cp->= sd, (struct sockaddr *)&to.addr.sa, &dlen))
{<= /span>
const char *f =3D print_openvpn_sockaddr(&from= , &gc);
const char *t =3D print_openvpn_sockad= dr(&to, &gc);
-= fnlen =3D strlen(journal_dir) + strlen(t) + 2;
- jfn =3D (char *) malloc(fnlen);
+ fnlen =3D str= len(journal_dir) + strlen(t) + 2;
+ jfn =3D (char *)malloc(fnlen);
= check_malloc_return(jfn);
snprintf(jfn, fnlen, = "%s/%s", journal_dir, t);
dmsg(D_PS_PROX= Y_DEBUG, "PORT SHARE PROXY: client origin %s -> %s", jfn, f);<= /span>
@@ -367,7 +365,7 @@
}
else

{
- msg(M_WARN|M_ERRNO, "PORT SHARE: un= able to write journal file in %s", jfn);
+ msg(M_WARN | M_ERRNO, "PORT SHAR= E: unable to write journal file in %s", jfn);
= free(jfn);
}
}@@ -393,11 +391,13 @@
}
static inline void
-proxy_connection_io_requeue(struct proxy_connection *pc, const int rwf= lags_new, struct event_set *es)
+proxy_connection_io_requeue(struct proxy_connection *pc, const = int rwflags_new,
+ = struct event_set *es)
{ if (socket_defined(pc->sd) && pc->rwflags !=3D rw= flags_new)
{
- /*dmsg (D_PS_PROXY_DEBUG, "PORT SHARE PROXY: reque= ue[%d] rwflags=3D%d", (int)pc->sd, rwflags_new);*/
+ /*dmsg (D_PS_PROXY_DEBUG, &q= uot;PORT SHARE PROXY: requeue[%d] rwflags=3D%d", (int)pc->sd,
+ * rwflags_new);*= /
event_ctl(es, pc->sd, rwflags_new, (void *)pc= );
pc->rwflags =3D rwflags_new;
}

@@ -411,12 +411,9 @@
* on success= and false on failure to connect to server.
*/
= static bool
-pro= xy_entry_new(struct proxy_connection **list,
- struct event_set *es,
- const struct openvpn= _sockaddr server_addr,

= - const socket_descriptor_t sd_client,
- struct buffer *initial_data= ,
- cons= t char *journal_dir)
= +proxy_entry_new(struct proxy_connection **list, struct event_set *es,
+ const st= ruct openvpn_sockaddr server_addr, const socket_descriptor_t sd_client,
+ struct = buffer *initial_data, const char *journal_dir)
{ socket_descriptor_t sd_server;
int status;=
@@ -426,7 +423,7 @@
/* connect to por= t share server */
if ((sd_server =3D socket(server_add= r.addr.sa.sa_family, SOCK_STREAM, IPPROTO_TCP)) < 0)
= {
- msg(M_WARN= |M_ERRNO, "PORT SHARE PROXY: cannot create socket");
+ msg(M_WARN | M_ERRNO, &q= uot;PORT SHARE PROXY: cannot create socket");

= return false;
}
status =3D openv= pn_connect(sd_server, &server_addr.addr.sa, 5, NULL);
@= @ -472,11 +469,12 @@
journal_add(journal_dir, pc, = cp);
}

- dmsg(D_PS_PROXY_DEBUG, "PORT SHARE PROXY: = NEW CONNECTION [c=3D%d s=3D%d]", (int)sd_client, (int)sd_server);
+ dmsg(D_PS_PROXY_DEBU= G, "PORT SHARE PROXY: NEW CONNECTION [c=3D%d s=3D%d]", (int)sd_cl= ient,
+ (int)= sd_server);

/* set initial i/o state= s */
proxy_connection_io_requeue(pc, EVENT_READ, es);<= /span>
- proxy_connection_i= o_requeue(cp, EVENT_READ|EVENT_WRITE, es);
+ proxy_connection_io_requeue(cp, EVENT_READ | EVE= NT_WRITE, es);

return true; }
@@ -488,12 +486,9 @@
* exit, t= rue otherwise.
*/
static bool
= -control_message_from_parent(cons= t socket_descriptor_t sd_control,
- struct proxy_connection **list,
- = struct event_set *es,
- = const int max_initial_buf,
- const char *journal_dir)
+control_message_from_parent(cons= t socket_descriptor_t sd_control, struct proxy_connection **list,
+ s= truct event_set *es, const struct openvpn_sockaddr server_addr,
<= span style=3D"color: hsl(120, 100%, 40%);">+ con= st int max_initial_buf, const char *journal_dir)

{<= br> /* this buffer needs to be large enough to handle the largest= buffer
* that might be returned by the link_socket_r= ead call in read_incoming_link. */
@@ -516,7 +511,7 @@
mesg.msg_iovlen =3D 2;

= mesg.msg_controllen =3D cmsg_size();
- mesg.msg_control =3D (char *) malloc(mesg.msg_contro= llen);
+ mesg.msg_= control =3D (char *)malloc(mesg.msg_controllen);
check= _malloc_return(mesg.msg_control);
mesg.msg_flags =3D 0= ;

@@ -530,10 +525,8 @@
= status =3D recvmsg(sd_control, &mesg, MSG_NOSIGNAL);
if (status !=3D -1)

{
- if (h =3D=3D NULL
- || h->cmsg_len !=3D CMSG_= LEN(sizeof(socket_descriptor_t))
- || h->cmsg_level !=3D SOL_SOCKET
- || h->cmsg_type !=3D= SCM_RIGHTS)

+ = if (h =3D=3D NULL || h->cmsg_len !=3D CMSG_LEN(sizeof(socket_descriptor= _t))
+ || = h->cmsg_level !=3D SOL_SOCKET || h->cmsg_type !=3D SCM_RIGHTS)=
{
msg(M_WARN, "PORT SH= ARE PROXY: received unknown message");
}
@@ -546,12 +539,7 @@
if (status &g= t;=3D 2 && command =3D=3D COMMAND_REDIRECT)
= {
buf.len =3D status - 1;
= - if (proxy_entry_= new(list,
- = es,
- server_addr,
- receiv= ed_fd,
- = &buf,
- journal_dir))
+ if (proxy_entry_new(= list, es, server_addr, received_fd, &buf, journal_dir))
{

CLEAR(buf); /* we = gave the buffer to proxy_entry_new */
}
@@ -610,7 +598,8 @@
*bytes_sent +=3D= status;
if (status !=3D pc->buf.len) {
- = dmsg(D_PS_PROXY_DEBUG, "PORT SHARE PROXY: partial write[%d], t= ried=3D%d got=3D%d", (int)sd, pc->buf.len, status);
+ dmsg(D_PS_PROXY_DEBUG, = "PORT SHARE PROXY: partial write[%d], tried=3D%d got=3D%d", (int)= sd,

+ = pc->buf.len, status);
buf_advance(&pc-= >buf, status);
return IOSTAT_EAGAIN_ON_WRIT= E;
}
@@ -698,9 +687,7 @@ * in the proxied connection.
*/
= static int
-proxy_conn= ection_io_dispatch(struct proxy_connection *pc,
- const int rwflags,
- = struct event_set *es)
+proxy_connection_io_dispatch(struct proxy_connection *pc, const int= rwflags, struct event_set *es)
{
con= st int max_transfer_per_iteration =3D 10000;
struct pr= oxy_connection *cp =3D pc->counterpart;
@@ -739,10 +726,= 8 @@
* This is the main function for the port share proxy= background process.
*/
static void
-port_share_proxy(const str= uct openvpn_sockaddr hostaddr,
- const socket_descriptor_t sd_control,
<= span style=3D"color: hsl(0, 100%, 40%);">- const int max_in= itial_buf,

- = const char *journal_dir)
+port_share_proxy(const struct openvpn_sockaddr hostaddr, const s= ocket_descriptor_t sd_control,
+ const int max_initial_buf, const char *journal_= dir)
{
if (send_control(sd_control, R= ESPONSE_INIT_SUCCEEDED) >=3D 0)
{
@= @ -776,7 +761,8 @@
const struct event_= set_return *e =3D &esr[i];
if (e-&= gt;arg =3D=3D sd_control_marker)
{
- i= f (!control_message_from_parent(sd_control, &list, es, hostaddr, max_in= itial_buf, journal_dir))
+ if (!control_message_from_parent(sd_control, &= amp;list, es, hostaddr,
+ max_initial_bu= f, journal_dir))
{
goto done;

= }
@@ -814,9 +800,7 @@
* share prox= y.
*/
struct port_share *
-port_share_open(const char *host,
- const ch= ar *port,
- = const int max_initial_buf,
+port_share_open(const char *host, const char *port, const int ma= x_initial_buf,
const char *journal_dir)
{
pid_t pid;
@@ -834,9 = +818,9 @@
* Get host's IP address
*/


- status =3D openvpn_getaddrinfo(GETADDR_RESOLVE|GETADDR_FATAL,
- = host, port, 0, NULL, AF_UNSPEC, &ai);
- ASSERT(status=3D=3D0);
+ status =3D
+ openvpn_getaddrinfo(GETADDR_RESOLVE = | GETADDR_FATAL, host, port, 0, NULL, AF_UNSPEC, &ai);
+ ASSERT(status =3D=3D 0);<= br> ASSERT(sizeof(hostaddr.addr) >=3D ai->ai_addrlen);

memcpy(&hostaddr.addr.sa, ai->ai_addr, ai->ai_ad= drlen);
freeaddrinfo(ai);
@@ -982,7 +9= 66,7 @@
bool
is_openvpn_protocol(const st= ruct buffer *buf)
{
- const unsigned char *p =3D (const unsigned char *) BSTR(= buf);
+ const unsi= gned char *p =3D (const unsigned char *)BSTR(buf);
con= st int len =3D BLEN(buf);
if (len >=3D 3) {
@@ -1004,7 +988,7 @@
= * We don't do the 2 byte check for tls-crypt-v2 because it is ver= y
* unrealistic to have only 2 bytes availabl= e.
*/
- return (plen >=3D 336 && plen < (1= 024 + 255));
+ = return (plen >=3D 336 && plen < (1024 + 255)); }
else
{<= /span>
diff --git a/src/openvpn/ps.h b/src/openvpn/ps.h
= index c6f5633..e28c403 100644
--- a/src/openvpn/ps.h<= /span>
+++ b/src/openvpn/ps.h
@@ -29,7 +29,8 @@
#include "buffer.h"
#include &quo= t;ssl.h"

-struct port_share {
+struct port_share
+{
/* Foreground's socket to background pro= cess */
socket_descriptor_t foreground_fd;
<= span>

@@ -39,9 +40,7 @@

= extern struct port_share *port_share;

-struct port_share *port_share_open(const= char *host,
- = const char *port,
- const int max_init= ial_buf,
+struct port= _share *port_share_open(const char *host, const char *port, const int max_i= nitial_buf,
const char = *journal_dir);

void port_share_close(str= uct port_share *ps);
diff --git a/src/openvpn/push.c b/src/= openvpn/push.c
index 3013100..889b268 100644
--- a/src/openvpn/push.c

+++ b/src/openvpn/push.c<= br>@@ -95,7 +95,7 @@

c= ase AR_INTERACT:
ssl_purge_auth(false);
- /* Intention= al [[fallthrough]]; */
- if (authfail_extended<= /span>
- && buf= _string_match_head_str(&buf, "CRV1:") && BLEN(&bu= f))
+ if (authfail= _extended && buf_string_match_head_str(&buf, "CRV1:")= && BLEN(&buf))
{
= ssl_put_auth_challenge(BSTR(&buf));
}
<= span> #endif /* ifdef ENABLE_MANAGEMENT */

-
}

= /*
* Act on received restart message from server<= br> */
void
-server_pushed_signal(struct context *c, const struct buffer *= buffer, const bool restart, const int adv)
+server_pushed_signal(struct context *c, const struct= buffer *buffer, const bool restart,
+ const int adv)
{
if (c->options.pull)
{
= @@ -250,7 +249,8 @@
}
= else
{
- msg(D_PUSH_ERRORS, "WARNING: Received INFO co= mmand is too long, won't notify management client.");
+ msg(D_PUSH_ERRORS,
+ "= ;WARNING: Received INFO command is too long, won't notify management cl= ient.");
}

= gc_free(&gc);
@@ -292,20 +292,18 @@
= * if the server does not push a timeou= t
*/
static void
-parse_auth_pending_keywords(const struct bu= ffer *buffer,
- = unsigned int *server_timeout)
+parse_auth_pending_keywords(const struct buff= er *buffer, unsigned int *server_timeout)
{
struct buffer buf =3D *buffer;


= /* does the buffer start with "AUTH_PENDING," ? */
- if (!buf_advance(&buf, str= len("AUTH_PENDING"))

- || !(buf_read_u8(&buf) =3D=3D ',') || !BLEN(&a= mp;buf))
+ if (!bu= f_advance(&buf, strlen("AUTH_PENDING")) || !(buf_read_u8(&= ;buf) =3D=3D ',') || !BLEN(&buf))
{=
#ifdef ENABLE_MANAGEMENT
if (management= )
{
- management_set_state(management, OPENVPN_STATE_AUTH_PEND= ING,
- = "", NULL, NULL, NULL, NULL);
+ management_set_state(managem= ent, OPENVPN_STATE_AUTH_PENDING, "", NULL, NULL, NULL,
= + = NULL);
}
#endif

@@ -320,8 +318,8 @@
* buf_parse i= s called, as it will insert \0 bytes into the buffer */
= if (management)
{
- management_set_state(management, OPENVPN_STATE_A= UTH_PENDING,
- = BSTR(&buf), NULL, NULL, NULL, NULL);
+ management_set_state(manag= ement, OPENVPN_STATE_AUTH_PENDING, BSTR(&buf), NULL, NULL, NULL,
=
+ = NULL);
}
#endif
<= /span>
@@ -344,17 +342,18 @@

= /* Cap the increase at the maximum time we are willing stay in the=
* pending authentication state */
- unsigned int max_timeout =3D max_uint(c->= ;options.renegotiate_seconds/2,
- c->options.handshake_w= indow);
+ unsigned= int max_timeout =3D
= + max_uint(c->options.renegotiate_seconds / 2, c->options.hand= shake_window);

/* try to parse param= eter keywords, default to hand-winow timeout if the
*= server does not supply a timeout */
unsigned int serv= er_timeout =3D c->options.handshake_window;
parse_a= uth_pending_keywords(buffer, &server_timeout);
=
- msg(D_PUSH, "AUTH_P= ENDING received, extending handshake timeout from %us "
- "to %us", c->op= tions.handshake_window,

- min_uint(max_timeout, server_timeout));
+ msg(D_PUSH,
+ "AUTH_PENDING received, extending ha= ndshake timeout from %us "
+ "to %us",
+ c->options.handshake_window, min_uint(max_ti= meout, server_timeout));

const struc= t key_state *ks =3D get_primary_key(c->c2.tls_multi);
= c->c2.push_request_timeout =3D ks->established + min_uint(max_time= out, server_timeout);
@@ -374,16 +373,16 @@
*

* @return true on success, false on failure.<= br> */
-static b= ool push_option_fmt(struct gc_arena *gc, struct push_list *push_list,
- = int msglevel, const char *fmt, ...)
+static bool push_option_fmt(struct gc_arena *gc, struct pu= sh_list *push_list, int msglevel,
+ const char *fmt, ...)
<= span> #ifdef __GNUC__

#if __USE_MINGW_ANSI_STDIO-__attribute__ ((format(gnu_prin= tf, 4, 5)))
+ __at= tribute__((format(gnu_printf, 4, 5)))
#else
-__attribute__ ((format(__printf__, 4= , 5)))

+ __attribu= te__((format(__printf__, 4, 5)))
#endif
#= endif
-;
+ ;


= /*
* Send auth failed message from server to clien= t.
@@ -403,7 +402,7 @@
static const ch= ar auth_failed[] =3D "AUTH_FAILED";
size_t l= en;

-= len =3D (client_reason ? strlen(client_reason)+1 : 0) + sizeof(auth_fai= led);
+ len =3D (c= lient_reason ? strlen(client_reason) + 1 : 0) + sizeof(auth_failed);=
if (len > PUSH_BUNDLE_SIZE)
{=
len =3D PUSH_BUNDLE_SIZE;
@@ -419,13 +41= 8,12 @@

/* We kill the whole ses= sion, send the AUTH_FAILED to any TLS session
* t= hat might be active */
= - send_control_channel_string_dowork(&c->c2.tls_multi->ses= sion[TM_INITIAL],
- = BSTR(&buf), D_PUSH);
<= span style=3D"color: hsl(0, 100%, 40%);">- send_control_channel_stri= ng_dowork(&c->c2.tls_multi->session[TM_ACTIVE],

- = BSTR(&buf), D_PUSH);
+ send_control_channel_string_dowork(&c->c2.tls_multi= ->session[TM_INITIAL], BSTR(&buf),
+ D_PUSH);
+ send_control_= channel_string_dowork(&c->c2.tls_multi->session[TM_ACTIVE], BSTR(= &buf),
+ = D_PUSH);

reschedule_multi_process(c);

-
}

gc_free(&gc);

@@ -433,8 +431,7 @@


bool
-send_auth_pending_messages(struct tls_multi *tls_multi= ,
- = struct tls_session *session,
+send_auth_pending_messages(struct tls_multi *tls_multi, str= uct tls_session *session,
const= char *extra, unsigned int timeout)
{
= struct key_state *ks =3D &session->key[KS_PRIMARY];
@@ -446,8 +443,8 @@



= /* Calculate the maximum timeout and subtract the time we already waited= */
- unsigned int m= ax_timeout =3D max_uint(tls_multi->opt.renegotiate_seconds/2,
= - = tls_multi->opt.handshake_window);
+ unsigned int max_timeout =3D
+ max_uint(tls_multi->opt.re= negotiate_seconds / 2, tls_multi->opt.handshake_window);
max_timeout =3D max_timeout - (now - ks->initial);

timeout =3D min_uint(max_timeout, timeout);

<= br>@@ -506,17 +503,19 @@
struct gc_arena gc =3D = gc_new();
unsigned int option_types_found =3D 0;

- msg(D= _PUSH, "PUSH: Received control message: '%s'", sanitize_c= ontrol_message(BSTR(buffer), &gc));
+ msg(D_PUSH, "PUSH: Received control message: &= #39;%s'",
+ = sanitize_control_message(BSTR(buffer), &gc));
<= /span>
- int status =3D pro= cess_incoming_push_msg(c, buffer, c->options.pull,
- = pull_permission_mask(c),
+ int status =3D process_incoming_push_msg(c, buffer, c->options.= pull, pull_permission_mask(c),
= &option_types_found);

if (status =3D=3D PUSH_MSG_ERROR)

{
- msg(D_PUSH_ERRORS, "W= ARNING: Received bad push/pull message: %s", sanitize_control_message(= BSTR(buffer), &gc));

+ msg(D_PUSH_ERRORS, "WARNING: Received bad push/pull messa= ge: %s",
+ = sanitize_control_message(BSTR(buffer), &gc));
= }
- else if (statu= s =3D=3D PUSH_MSG_REPLY || status =3D=3D PUSH_MSG_UPDATE || status =3D=3D P= USH_MSG_CONTINUATION)
+ else if (status =3D=3D PUSH_MSG_REPLY || status =3D=3D PUSH_MSG_UPDAT= E
+ || st= atus =3D=3D PUSH_MSG_CONTINUATION)
{
= c->options.push_option_types_found |=3D option_types_found;

@@ -605,17 +604,14 @@
*= /
if (tls_multi->auth_token)
{=
- push_option_f= mt(gc, push_list, M_USAGE, "auth-token %s",
- tls_multi->auth_= token);
+ push= _option_fmt(gc, push_list, M_USAGE, "auth-token %s", tls_multi-&g= t;auth_token);

char *base64user = =3D NULL;
int ret =3D openvpn_base64_encode(tls_mu= lti->locked_username,
- = &base64user);
+ (int)st= rlen(tls_multi->locked_username), &base64user);
= if (ret < USER_PASS_LEN && ret > 0)
= {
- pus= h_option_fmt(gc, push_list, M_USAGE, "auth-token-user %s",=
- = base64user);
+ = push_option_fmt(gc, push_list, M_USAGE, "auth-token-user %s"= , base64user);
}
free(bas= e64user);
}
@@ -631,8 +627,7 @@=
* @return true on success, false on failure.
= */
bool
- struct push_list= *push_list)
+prepare= _push_reply(struct context *c, struct gc_arena *gc, struct push_list *push_= list)
{
struct tls_multi *tls_multi = =3D c->c2.tls_multi;
struct options *o =3D &c-&= gt;options;
@@ -643,14 +638,12 @@
= push_option_fmt(gc, push_list, M_USAGE, "ifconfig-ipv6 %s/%d %s",=
print_in6_addr(c->c2.push_ifco= nfig_ipv6_local, 0, gc),
c->c2.= push_ifconfig_ipv6_netbits,
- print_in6_addr(c->c2.push_ifconfig_ipv6_re= mote,
- = 0, gc));
+ print_in6_addr(c->c2.push_ifconfig_i= pv6_remote, 0, gc));
}

/* ipv4 */

if (c->c2.push_ifconfig_defined = && c->c2.push_ifconfig_local
- && c->c2.push_ifconfig_remote_netmask<= /span>
- && !o-= >push_ifconfig_ipv4_blocked)
+ && c->c2.push_ifconfig_remote_netmask &&= amp; !o->push_ifconfig_ipv4_blocked)
{
in_addr_t ifconfig_local =3D c->c2.push_ifconfig_local;
if (c->c2.push_ifconfig_local_alias)
@@ -659,14 +652,12 @@

}
= push_option_fmt(gc, push_list, M_USAGE, "ifconfig %s %s",
print_in_addr_t(ifconfig_local, 0, gc),=
- = print_in_addr_t(c->c2.push_ifconfig_remote_netmask,
- = 0, gc));
+ = print_in_addr_t(c->c2.push_ifconfig_remote_netmask, 0, gc)= );
}

if (tls_mu= lti->use_peer_id)
{
- push_option_fmt(gc, push_list, M_USAGE, "= ;peer-id %d",
- = tls_multi->peer_id);
+ push_option_fmt(gc, push_list, M_USAGE, &q= uot;peer-id %d", tls_multi->peer_id);
}=
/*
* If server uses --auth-gen-token a= nd we have an auth token
@@ -728,10 +719,11 @@
push_option_fmt(gc, push_list, M_USAGE, "tun-mtu %d"= , o->ce.tun_mtu);

if (client_max_mtu < o->= ;ce.tun_mtu)
{
- msg(M_WARN, "Warning: reported maximum M= TU from client (%d) is lower "
+ msg(M_WARN,
+ "Warning: reported maximum MTU fro= m client (%d) is lower "
"than M= TU used on the server (%d). Add tun-max-mtu %d "
- "to client configurati= on.", client_max_mtu,
- o->ce.tun_mtu, o->ce.tun_mtu);
+ "to client confi= guration.",
+ = client_max_mtu, o->ce.tun_mtu, o->ce.tun_mtu); }
}

= @@ -739,8 +731,7 @@
}

s= tatic bool
-send_push_o= ptions(struct context *c, struct buffer *buf,
- struct push_list *push_list, int = safe_cap,
+send_push_= options(struct context *c, struct buffer *buf, struct push_list *push_list,= int safe_cap,
bool *push_sent, bool *mu= lti_push)
{
struct push_entry *e =3D = push_list->head;
@@ -810,15 +801,13 @@
= buf_printf(&buf, "%s", push_reply_cmd);
=
/* send options which are common to all clients */
- if (!send_push_optio= ns(c, &buf, &c->options.push_list, safe_cap,
- &push_sent= , &multi_push))
+= if (!send_push_options(c, &buf, &c->options.push_list, safe_= cap, &push_sent, &multi_push))
{
goto fail;

}

<= span> /* send client-specific options */

- if (!send_push_options(c, &buf, per_client_p= ush_list, safe_cap,
- = &push_sent, &multi_push))
+ if (!send_push_options(c, &b= uf, per_client_push_list, safe_cap, &push_sent, &multi_push))
{
goto fail;
= }
@@ -828,7 +817,7 @@
buf_printf(&= amp;buf, ",push-continuation 1");
}
- if (BLEN= (&buf) > sizeof(push_reply_cmd)-1)
+ if (BLEN(&buf) > sizeof(push_reply_cmd) - = 1)
{
const bool status =3D se= nd_control_channel_string(c, BSTR(&buf), D_PUSH);
= if (!status)
@@ -863,8 +852,8 @@
}

static void
-push_option_ex(struct gc_arena *gc, struct push_list = *push_list,
- = const char *opt, bool enable, int msglevel)
+push_option_ex(struct gc_arena *gc, struct pus= h_list *push_list, const char *opt, bool enable,
+ int msglevel)
= {
if (!string_class(opt, CC_ANY, CC_COMMA))
= {
@@ -906,8 +895,7 @@
p= ush_reset(o);
while (e)
{=
- push_opti= on_ex(&o->gc, &o->push_list,
- string_alloc(e->option, = &o->gc), true, M_FATAL);
+ push_option_ex(&o->gc, &o->push_list,= string_alloc(e->option, &o->gc), true, M_FATAL);
e =3D e->next;

}
= }
@@ -922,16 +910,16 @@
}
<= span>

static bool
-push_option_fmt(struct gc_arena *gc, struct push_list *push_l= ist,
- i= nt msglevel, const char *format, ...)
+push_option_fmt(struct gc_arena *gc, struct push_list *pu= sh_list, int msglevel, const char *format,
+ ...)
{
va_list arglist;

- char tmp[256] =3D {0};
+ char tmp[256] =3D { 0 };
int len;
va_start(arglist, format);
len =3D vsn= printf(tmp, sizeof(tmp), format, arglist);
va_end(argl= ist);
- if (len >= sizeof(tmp)-1)
+ = if (len > sizeof(tmp) - 1)
{
= return false;
}
@@ -958,7 +946,7 @@=
}

/* ifconfig-= ipv6 is special, as not part of the push list */
- if (streq( p, "ifconfig-ipv6" ))
+ if (streq(p, &quo= t;ifconfig-ipv6"))
{
o-&= gt;push_ifconfig_ipv6_blocked =3D true;
return;
@@ -971,8 +959,7 @@
/* cycle through= the push list */
while (e)
= {
- if (e= ->enable
- = && strncmp( e->option, p, strlen(p) ) =3D=3D 0)
= + if (e->enable &= amp;& strncmp(e->option, p, strlen(p)) =3D=3D 0)
= {
msg(D_PUSH_DEBUG, "PUSH_R= EMOVE removing: '%s'", e->option);
= e->enable =3D false;
@@ -1012,8 +999,7 @@
struct push_list push_list =3D { 0 };
struct gc_arena gc =3D gc_new();

- if (prepare_push_r= eply(c, &gc, &push_list)
- && send_push_reply(c, &push_list))
+ if (prepa= re_push_reply(c, &gc, &push_list) && send_push_reply(c, &am= p;push_list))
{
= ret =3D PUSH_MSG_REQUEST;
c->c2.sent= _push_reply_expiry =3D now + 30;
@@ -1035,9 +1021,9 @@
char line[OPTION_PARM_SIZE];
while (b= uf_parse(buf, ',', line, sizeof(line)))
{
- /* peer-id and aut= h-token might change on restart and this should not trigger reopening tun *= /
- if (strprefi= x(line, "peer-id ")
- || strprefix(line, "auth-token ")
<= span style=3D"color: hsl(120, 100%, 40%);">+ /* peer-id and auth-tok= en might change on restart and this should not trigger reopening tun
=
+ */
+ if (strprefix(line, "= peer-id ") || strprefix(line, "auth-token ")

|| strprefix(line, "auth-token-user "))

<= span> {

continue;
@@ -= 1047,15 +1033,13 @@
{
= continue;
}
- md_ctx_update(ctx, (const uint8_t *) line, strlen(l= ine)+1);
+ md_= ctx_update(ctx, (const uint8_t *)line, strlen(line) + 1);
= }
}

static int
-process_incoming_push_repl= y(struct context *c,
- = unsigned int permission_mask,
- unsigned int= *option_types_found,
-= struct buffer *buf)
+process_incoming_push_reply(struct context *c, = unsigned int permission_mask,
+ unsigned int *option_types_found, str= uct buffer *buf)
{
int ret =3D PUSH_M= SG_ERROR;
const uint8_t ch =3D buf_read_u8(buf);
@@ -1068,22 +1052,15 @@
md_ctx_init= (c->c2.pulled_options_state, "SHA256");
= c->c2.pulled_options_digest_init_done =3D true;
= }
- if (= apply_push_options(c,
-= &c->options,
- buf,
= - p= ermission_mask,
- = option_types_found,
- c->c2.es,+ if (apply_push_optio= ns(c, &c->options, buf, permission_mask, option_types_found, c->c= 2.es,
false))
{

- = push_update_digest(c->c2.pulled_options_state, &buf_orig,=
- = &c->options);
+ push_update_digest(c->c2.pulled_options_state, &buf_= orig, &c->options);
switch (c->optio= ns.push_continuation)
{
= case 0:
case 1:
- md_ctx_final(c-&g= t;c2.pulled_options_state,

- c->c2.pulled_options_digest.digest= );
+ = md_ctx_final(c->c2.pulled_options_state, c->c2.pulled_options_dige= st.digest);
md_ctx_cleanup(c->c2.pu= lled_options_state);
md_ctx_free(c->= ;c2.pulled_options_state);
c->c2.pu= lled_options_state =3D NULL;
@@ -1106,10 +1083,8 @@<= br> }

int
-process_incoming_push_msg(struct context *c,
- = const struct buffer *buffer,
- bool honor_received_options,
= - unsign= ed int permission_mask,
+process_incoming_push_msg(struct context *c, const struct buffer *buffe= r,
+ = bool honor_received_options, unsigned int permission_mask,<= br> unsigned int *option_types_found)
{
struct buffer buf =3D *buffer;@@ -1119,17 +1094,13 @@
c->c2.push_reque= st_received =3D true;
return process_incoming_push= _request(c);
}
- else if (honor_received_options
- && buf_string_compare_adva= nce(&buf, push_reply_cmd))
+ else if (honor_received_options && buf_string_compar= e_advance(&buf, push_reply_cmd))
{
- return process_incoming_push_= reply(c, permission_mask,

- option_types_found, &buf= );
+ return pr= ocess_incoming_push_reply(c, permission_mask, option_types_found, &buf)= ;
}
- && buf_string_compare_advance(&bu= f, push_update_cmd))
= + else if (honor_received_options && buf_string_compare_advance(= &buf, push_update_cmd))
{
- return process_incoming_push_update(c,= permission_mask,
- = option_types_found, &buf);
+ return process_i= ncoming_push_update(c, permission_mask, option_types_found, &buf);
}
else
{<= br>@@ -1152,13 +1123,14 @@
/* cycle through = the push list */
while (e)
= {
- char *= p[MAX_PARMS+1];
+ = char *p[MAX_PARMS + 1];
bool enable = =3D true;

/* parse the push = item */
CLEAR(p);
= if (e->enable
- = && parse_line(e->option, p, SIZE(p)-1, "[PUSH_R= OUTE_REMOVE]", 1, D_ROUTE_DEBUG, &gc))
+ && parse_line(e->opt= ion, p, SIZE(p) - 1, "[PUSH_ROUTE_REMOVE]", 1, D_ROUTE_DEBUG,
+ = &gc))
{
= /* is the push item a route directive? */
= if (p[0] && !strcmp(p[0], "route") && !p[3]= && o->iroutes)
@@ -1166,7 +1138,8 @@
= /* get route parameters */
= bool status1, status2;
= const in_addr_t network =3D getaddr(GETADDR_HOST_ORDER, p[1], 0, &stat= us1, NULL);
- = const in_addr_t netmask =3D getaddr(GETADDR_HOST_ORDER, p[2] ? p[= 2] : "255.255.255.255", 0, &status2, NULL);
+ const in_addr_t n= etmask =3D getaddr(
+= GETADDR_HOST_ORDER, p[2] ? p[2] : "255.255.255= .255", 0, &status2, NULL);

= /* did route parameters parse correctly? */
if (status1 && status2)

@@ -1= 176,7 +1149,9 @@
/* does route mat= ch an iroute? */
for (ir =3D o->= ;iroutes; ir !=3D NULL; ir =3D ir->next)
= {
- = if (network =3D=3D ir->network && netmask =3D= =3D netbits_to_netmask(ir->netbits >=3D 0 ? ir->netbits : 32))
+ = if (network =3D=3D ir->network
+ && netmask
+ = =3D=3D netbits_to_netmask(ir->netbits >=3D 0 ? ir->n= etbits : 32))
{
enable =3D false;

= break;
@@ -1184,8 +1159,7 @@
}
= }
}
- else if (p[0] && !strcmp(p[0], &qu= ot;route-ipv6") && !p[2]
- && o->iroutes_ipv6)
+ else if= (p[0] && !strcmp(p[0], "route-ipv6") && !p[2] &a= mp;& o->iroutes_ipv6)
{
<= span> /* get route parameters */

= struct in6_addr network;
diff --git a/src/op= envpn/push.h b/src/openvpn/push.h
index b6770bc..22b940f 10= 0644
--- a/src/openvpn/push.h
+++ b/src/ope= nvpn/push.h
@@ -34,17 +34,18 @@
#define PU= SH_MSG_ALREADY_REPLIED 6
#define PUSH_MSG_UPDATE = 7

-= #define push_reply_cmd "PUSH_REPLY"
+#define push_reply_cmd "PUSH_REPLY"
#define push_update_cmd "PUSH_UPDATE"

/* Push-update options flags */
-#define PUSH_OPT_TO_REMOVE (1<<0)
-#define PUSH_OPT_OPTIONA= L (1<<1)
+#defi= ne PUSH_OPT_TO_REMOVE (1 << 0)
+#define PUSH_OPT_OPTIONAL (1 << 1)
=
int process_incoming_push_request(struct context *c);

/**
- * @brief Handles the receiving of a push-update message and= applies updates to the specified options.
+ * @brief Handles the receiving of a push-update mes= sage and applies updates to the specified
+ * options.
*
* T= his function processes a push-update message, validating its content and ap= plying updates
* to the options specified in the message.= It also handles split messages if the complete
@@ -63,22 += 64,19 @@
* - `PUSH_MSG_ERROR`: An error occurred during m= essage processing, or the message is invalid.
*/
-int process_= incoming_push_update(struct context *c,
- unsigned int permission_= mask,
- = unsigned int *option_types_found,
- struct buffer= *buf);
+int process_= incoming_push_update(struct context *c, unsigned int permission_mask,
+ = unsigned int *option_types_found, struct buffer *buf);

-int process_inco= ming_push_msg(struct context *c,
- const struct buffer *buffer,
- = bool honor_received_options,
- unsigned int permission_mask,
+int process_incoming_push= _msg(struct context *c, const struct buffer *buffer,
+ bool honor_= received_options, unsigned int permission_mask,
= unsigned int *option_types_found);

bool send_push_request(struct context *c);
=
void receive_auth_failed(struct context *c, const struct = buffer *buffer);

-void server_pushed_signal(struct context *c, const struct buff= er *buffer, const bool restart, const int adv);
+void server_pushed_signal(struct context *c, co= nst struct buffer *buffer, const bool restart,
+ const int adv);=

void receive_exit_message(struct context *c);<= /span>

@@ -92,8 +90,7 @@

void push_option(struct options *o, const char *opt, int msglev= el);

= -void push_options(struct options *o, char **p, int msglevel,
- struct gc_arena *= gc);

+void push_optio= ns(struct options *o, char **p, int msglevel, struct gc_arena *gc);<= br>
void push_reset(struct options *o);
<= span>

@@ -108,10 +105,8 @@
* doc/managem= ent-notes.txt under client-pending-auth for
* more detail= s on message format
*/
-bool
-send_auth_pending_messages(struct tls_multi *tls_multi,
- struct tls_s= ession *session, const char *extra,
- unsigned int timeout);
<= span style=3D"color: hsl(120, 100%, 40%);">+bool send_auth_pending_messages= (struct tls_multi *tls_multi, struct tls_session *session,

+ cons= t char *extra, unsigned int timeout);

vo= id send_restart(struct context *c, const char *kill_msg);
=
@@ -130,7 +125,6 @@
* @param c = The context struct
* @param buffer Buffer conta= ining the control message with AUTH_PENDING
*/
= -void
-receive_auth_pending(struct context *c, const str= uct buffer *buffer);
= +void receive_auth_pending(struct context *c, const struct buffer *buffer);=

#endif /* ifndef PUSH_H */
diff --git a/src/openvpn/push_util.c b/src/openvpn/push_util.c
index b4d1e8b..0862a74 100644
--- a/src/openvpn/pus= h_util.c
+++ b/src/openvpn/push_util.c
@@ -= 5,21 +5,14 @@
#include "push.h"
=
int
= -process_incoming_push_update(struct context *c,
- unsigned int permis= sion_mask,
- = unsigned int *option_types_found,
- struct buffer = *buf)
+process_incomi= ng_push_update(struct context *c, unsigned int permission_mask,
<= span style=3D"color: hsl(120, 100%, 40%);">+ un= signed int *option_types_found, struct buffer *buf)

{
int ret =3D PUSH_MSG_ERROR;
const uin= t8_t ch =3D buf_read_u8(buf);
if (ch =3D=3D ','= ;)
{
- if (apply_push_options(c,
- &c->options,- = buf,
- = permission_mask,
- option_types_found,
- c->= ;c2.es,

+ if (= apply_push_options(c, &c->options, buf, permission_mask, option_type= s_found, c->c2.es,
true)= )
{
switch (c->opt= ions.push_continuation)
diff --git a/src/openvpn/pushlist.h= b/src/openvpn/pushlist.h
index 1b66517..ef4de88 100644
--- a/src/openvpn/pushlist.h
+++ b/src/openvpn= /pushlist.h
@@ -25,13 +25,15 @@
/* parameters to be pushed to peer */

<= span style=3D"color: hsl(0, 100%, 40%);">-struct push_entry {

+struct push_entry

+{

struct push_= entry *next;
bool enable;
const c= har *option;
};

-struct push_list {
+struct push_list
+{
struct push_entry *head;
struct push_entry *tail;
};
<= span>diff --git a/src/openvpn/reflect_filter.c b/src/openvpn/reflect_filter= .c

index 17255f7..071df7c 100644
--- a/src/= openvpn/reflect_filter.c
+++ b/src/openvpn/reflect_filter.c=
@@ -46,10 +46,10 @@
int64_t dropp= ed =3D irl->curr_period_counter - irl->max_per_period;
if (dropped > 0)

{
- msg(D_TLS_DEBUG_LOW, "= Dropped %" PRId64 " initial handshake packets"
- " due to --con= nect-freq-initial %" PRId64 " %d", dropped,

- irl->max_per_period= , irl->period_length);
-
+ msg= (D_TLS_DEBUG_LOW,
+ = "Dropped %" PRId64 " initial handshake packets= "
+ = " due to --connect-freq-initial %" PRId64 " %d",
+ dropped= , irl->max_per_period, irl->period_length);
= }
irl->last_period_reset =3D now;
irl->curr_period_counter =3D 0;

@@ -62,9 +62= ,11 @@

if (over_limit && !ir= l->warning_displayed)
{
- msg(M_WARN, "Note: --connect-freq-in= itial %" PRId64 " %d rate limit "
+ msg(M_WARN,
+ "Note: --connect-freq-initial= %" PRId64 " %d rate limit "
&q= uot;exceeded, dropping initial handshake packets for the next %d "
- "seconds= ", irl->max_per_period, irl->period_length,
+ "seconds",<= br>+ irl->max_per= _period, irl->period_length,
(int)(irl->= last_period_reset + irl->period_length - now));
= irl->warning_displayed =3D true;
}
diff --git a/src/openvpn/reflect_filter.h b/src/openvpn/reflect_filter.h
index e3fb165..0601f4b 100644
--- a/src/open= vpn/reflect_filter.h
+++ b/src/openvpn/reflect_filter.h
@@ -26,7 +26,8 @@

/** struc= t that handles all the rate limiting logic for initial
* = responses */
-struct in= itial_packet_rate_limit {
+struct initial_packet_rate_limit
+{
/** This is a hard limit for pack= ets per seconds. */
int64_t max_per_period;
=
@@ -50,22 +51,19 @@
* checks if t= he connection is still allowed to connect under the rate
= * limit. This also increases the internal counter at the same time */
-bool
-reflect_filter_rate_limit_= check(struct initial_packet_rate_limit *irl);
+bool reflect_filter_rate_limit_check(struct initi= al_packet_rate_limit *irl);

/** * decreases the counter of initial packets seen, so connections t= hat
* successfully completed the three-way handshake do n= ot count against
* the counter of initial connection atte= mpts
*/
-void
-reflect_filte= r_rate_limit_decrease(struct initial_packet_rate_limit *irl);
+void reflect_filter_rate_limit_de= crease(struct initial_packet_rate_limit *irl);


= /**
* allocate and initialize the initial-packet r= ate limiter structure
*/
-struct initial_packet_rate_limit *
-initial_rate_limit_init(int max_per_perio= d, int period_length);
-reliable_pid= _in_range1(const packet_id_type test,
- const packet_id_type base,+reliable_pid_in_range1(const = packet_id_type test, const packet_id_type base,
= const unsigned int extent)
{
= return subtract_pid(test, base) < extent;
@@ -61,8 = +60,7 @@
* verify that test < base + extent while allo= wing for base or test wraparound
*/
stat= ic inline bool
-reliabl= e_pid_in_range2(const packet_id_type test,
- const packet_id_type base,
+reliable_pid_in_range2(c= onst packet_id_type test, const packet_id_type base,
= const unsigned int extent)
{
<= span> if (base + extent >=3D base)

@@ -74,7 +72,7 @@=
}
else
{
- if ((test+0x8000= 0000u) < (base+0x80000000u) + extent)
+ if ((test + 0x80000000u) < (base + 0x800000= 00u) + extent)
{
retu= rn true;
}
@@ -87,8 +85,7 @@

* verify that p1 < p2 while allowing for p1 or p2 wraparou= nd
*/
static inline bool
-reliable_pid_min(const packet_id_type= p1,

- = const packet_id_type p2)
+reliable_pid_min(const packet_id_type p1, const packet_id_type p2)
{
return !reliable_pid_in_range1(p1, p2,= 0x80000000u);
}
@@ -144,8 +141,7 @@


bool
-reliable_ack_read(struct reliable_ack *ack,=
- str= uct buffer *buf, const struct session_id *sid)
+reliable_ack_read(struct reliable_ack *ack, stru= ct buffer *buf, const struct session_id *sid)
{
= struct session_id session_id_remote;
@@ -154,12 +150,11 @@
return false;<= br> }

- if (ack->len >=3D 1 && (!session_id_defined(&= amp;session_id_remote)
= - || !session_id_equal(&session_id_remote, sid= )))
+ if (ack->= len >=3D 1
+ = && (!session_id_defined(&session_id_remote) || !session_id_eq= ual(&session_id_remote, sid)))
{
= struct gc_arena gc =3D gc_new();
- dmsg(D_REL_LOW,
- "ACK read BAD SESSION-ID FROM REMOTE= , local=3D%s, remote=3D%s",
+ dmsg(D_REL_LOW, "ACK read BAD SESSION-ID FROM REM= OTE, local=3D%s, remote=3D%s",
session_i= d_print(sid, &gc), session_id_print(&session_id_remote, &gc));<= /span>
gc_free(&gc);
return = false;
@@ -210,7 +205,7 @@
{
ASSERT(ack->len >=3D n);

/* This loop is= backward to ensure the same order as in ack */
- for (int i =3D n-1; i >=3D 0; i--)<= br>+ for (int i =3D n - 1; i= >=3D 0; i--)
{
packet_id_= type id =3D ack->packet_id[i];

@@ -250= ,9 +245,7 @@
/* write a packet ID acknowledgement record t= o buf, */
/* removing all acknowledged entries from ack */=
bool
= -reliable_ack_write(struct reliable_ack *ack,
- struct reliable_ack *ack_mru,
- struc= t buffer *buf,
+relia= ble_ack_write(struct reliable_ack *ack, struct reliable_ack *ack_mru, struc= t buffer *buf,
const struct session_id = *sid, int max, bool prepend)
{
int i,= j, n;
@@ -284,7 +277,8 @@
packet_= id_type pid =3D ack_mru->packet_id[i];
packet_i= d_type net_pid =3D htonpid(pid);
ASSERT(buf_write(= &sub, &net_pid, sizeof(net_pid)));
- dmsg(D_REL_DEBUG, "ACK write ID " pa= cket_id_format " (ack->len=3D%d, n=3D%d)", (packet_id_print_ty= pe)pid, ack->len, n);
+ dmsg(D_REL_DEBUG, "ACK write ID " packet_id_format &= quot; (ack->len=3D%d, n=3D%d)",
+ (packet_id_print_type)pid, ack->len, n)= ;
}
if (total_acks)
{

@@ -293,7 +287,7 @@
}=
if (n)
{
- for (i =3D 0, j =3D n; j < ack->len; )=
+ for (i =3D = 0, j =3D n; j < ack->len;)
{
ack->packet_id[i++] =3D ack->packet_id[j++];

= }
@@ -494,7 +488,8 @@
r= eturn true;

bad:
- dmsg(D_REL_DEBUG, "ACK " pack= et_id_format " is a replay: %s", (packet_id_print_type)id, reliab= le_print_ids(rel, &gc));
+ dmsg(D_REL_DEBUG, "ACK " packet_id_format " is = a replay: %s", (packet_id_print_type)id,
+ reliable_print_ids(rel, &gc));
gc_free(&gc);
return false;=
}
@@ -513,7 +508,8 @@
g= c_free(&gc);
}

- dmsg(D_REL_DEBUG, "ACK RWBS re= l->size=3D%d rel->packet_id=3D%08x id=3D%08x ret=3D%d", rel->= size, rel->packet_id, id, ret);
+ dmsg(D_REL_DEBUG, "ACK RWBS rel->size=3D%d rel-&= gt;packet_id=3D%08x id=3D%08x ret=3D%d", rel->size,
+ rel->packet_id, id, ret= );

return ret;
}

@@ -630,9 +626,7 @@
}
}

(void)n_active; /* dmsg might not generate co= de */
- dmsg(D_REL_D= EBUG, "ACK reliable_can_send active=3D%d current=3D%d : %s",
- n_active,<= br>- n_current,+ dmsg(D_REL_DEBUG, "A= CK reliable_can_send active=3D%d current=3D%d : %s", n_active, n_curre= nt,
reliable_print_ids(rel, &gc));
=
gc_free(&gc);
@@ -653,8 +6= 47,7 @@
/* If N_ACK_RETRANSMIT later packets have = received ACKs, we assume
* that the packet was lo= st and resend it even if the timeout has
* not ex= pired yet. */
- = if (e->active
- = && (e->n_acks >=3D N_ACK_RETRANSMIT || local_now >= =3D e->next_try))
= + if (e->active && (e->n_acks >=3D N_ACK_RETRANSMIT= || local_now >=3D e->next_try))
{ if (!best || reliable_pid_min(e->packet_id, best->= ;packet_id))
{
@@ -720,9 +713,= 7 @@
}
}

- dmsg(D_REL_DEBUG, &q= uot;ACK reliable_send_timeout %d %s",
- (int) ret,
- reliable_print_ids(rel, &gc));
+ dmsg(D_REL_DEBUG, "ACK = reliable_send_timeout %d %s", (int)ret, reliable_print_ids(rel, &g= c));


gc_free(&gc);
return ret;

@@ -733,8 +724,8 @@
*= /

void
-reliable_mark_active_incoming(struct reliable *rel, str= uct buffer *buf,
- = packet_id_type pid, int opcode)
+reliable_mark_active_incoming(struct r= eliable *rel, struct buffer *buf, packet_id_type pid,
+ int opcode)=
{
for (int i =3D 0; i < rel->s= ize; ++i)
{
@@ -753,11 +744,12 @@
e->next_try =3D 0;
= e->timeout =3D 0;
e->n_acks =3D 0;
- dmsg(D_REL_DEB= UG, "ACK mark active incoming ID " packet_id_format, (packet_id_p= rint_type)e->packet_id);
+ dmsg(D_REL_DEBUG, "ACK mark active incoming ID &qu= ot; packet_id_format,
+ (packet_id_print_type)e->packet_id);
= return;
}
}
- ASSERT(0); = /* buf not found in rel */
+ ASSERT(0); /* buf not found in rel */
}

/*
@@ -782,11 +774,12 @@<= /span>
e->opcode =3D opcode;
= e->next_try =3D 0;
e->timeout = =3D rel->initial_timeout;
- dmsg(D_REL_DEBUG, "ACK mark active outgoing ID &quo= t; packet_id_format, (packet_id_print_type)e->packet_id);
+ dmsg(D_REL_DEBUG, &quo= t;ACK mark active outgoing ID " packet_id_format,

+ (packet_id_print_type)e= ->packet_id);
return;
= }
}
- ASSERT(0); /* buf not found in rel */+ ASSERT(0); /* buf not fou= nd in rel */
}

/* delet= e a buffer previously activated by reliable_mark_active() */
diff --git a/src/openvpn/reliable.h b/src/openvpn/reliable.h

index 6c37d78..89a9b16 100644

--- a/src/openvpn/reliabl= e.h
+++ b/src/openvpn/reliable.h
@@ -40,18 = +40,21 @@
* @{ */


-#define RELIABLE_ACK_SIZ= E 8 /**< The maximum number of packet IDs
- * waiting to = be acknowledged which can
- * be stored in one \c reliable_ack
- = * structure. */
+#define RELIABLE_ACK_SIZE \
+ 8 /**< The maximum number of p= acket IDs \
+ = * waiting to be acknowledged which can \
+ * be stored in one \c reliable_ack \=
+ * structur= e. */

-#define RELIABLE_CAPACITY 12 /**< The maximum number of packets tha= t
- = * the reliability layer for one VPN
- * tunnel in= one direction can store. */
+#define RELIABLE_CAPACITY \
+ 12 /**< The maximum number of = packets that \
+ = * the reliability layer for one VPN \
+ * tunnel in one direction can store. */

-#defi= ne N_ACK_RETRANSMIT 3 /**< We retry sending a packet early if
- = * this many later packets have been
- * ACKed. */=
+#define N_ACK_RETRANSMIT = \
+ 3 /**< We retry sending a packet early if \
+ * this many later packets have b= een \
+ * AC= Ked. */

/**
* The ackn= owledgment structure in which packet IDs are stored for later
@@ -76,9 +79,9 @@

interval_t timeout;
time_t next_try;

packet_id_type packet_id;
- size_t n_acks; /* Nu= mber of acks received for packets with higher PID.
- * Used for fast retransmi= ssion when there were at least
- * N_ACK_RETRANSMIT. */
+ size_t n_acks; /* Number of acks rece= ived for packets with higher PID.
+ * Used for fast retransmission when there= were at least
+ = * N_ACK_RETRANSMIT. */
int opcode;
struct buffer buf;
};
@@ = -93,7 +96,7 @@
interval_t initial_timeout;
<= span> packet_id_type packet_id;

int offset; /**<= ; Offset of the bufs in the reliable_entry array */
- bool hold; /* don't xmit until reli= able_schedule_now is called */
+ bool hold; /* don't xmit until reliable_schedule_now is= called */
struct reliable_entry array[RELIABLE_CAPACI= TY];
};

@@ -120,8 +123,7= @@
* @li True, if processing was successful.
<= span> * @li False, if an error occurs during processing.

= */
-bool reliable_ack_= read(struct reliable_ack *ack,
- struct buffer *buf, const struct session_id= *sid);
+bool reliabl= e_ack_read(struct reliable_ack *ack, struct buffer *buf, const struct sessi= on_id *sid);


/**
@@ -141,9 +143,8 @@
* @li True, if processing = was successful.
* @li False, if an error occurs during pr= ocessing.
*/
-bool
-reliable= _ack_parse(struct buffer *buf, struct reliable_ack *ack,
- struct session_id *se= ssion_id_remote);
+bo= ol reliable_ack_parse(struct buffer *buf, struct reliable_ack *ack,<= br>+ str= uct session_id *session_id_remote);

/**<= /span>
* Remove acknowledged packets from a reliable structure.<= /span>
@@ -212,9 +213,7 @@
* @li True, if proces= sing was successful.
* @li False, if an error occurs duri= ng processing.
*/
-bool reliable_ack_write(struct reliable_ack *ack,
<= span style=3D"color: hsl(0, 100%, 40%);">- struct re= liable_ack *ack_mru,

- = struct buffer *buf,
+bool reliable_ack_write(struct reliable_ack *ack, st= ruct reliable_ack *ack_mru, struct buffer *buf,
= const struct session_id *sid, int max, bool prepend);<= br>
/** @} name Functions for processing outgoing a= cknowledgments */
@@ -337,8 +336,8 @@
* @= param pid The packet's packet ID.
* @param opcode The= packet's opcode.
*/
-void reliable_mark_active_incoming(struct reliable *re= l, struct buffer *buf,
= - packet_id_type pid, int opcode);=
+void reliable_mark_active_= incoming(struct reliable *rel, struct buffer *buf, packet_id_type pid,
+ = int opcode);

/**
* Record a packet ID for later acknowledgment.

@@ -37= 4,7 +373,6 @@
struct reliable_entry *reliable_get_entry_se= quenced(struct reliable *rel);

-
/** * Copies the first n acks from \c ack to \c ack_mru
*

@@ -382,8 +380,7 @@
* @param ack_m= ru The reliable structure to insert the acks into
* @para= m n The number of ACKS to copy
*/
-void
-copy_acks_to_mru(struct reliable_ack *ack, struct reliable_a= ck *ack_mru, int n);
= +void copy_acks_to_mru(struct reliable_ack *ack, struct reliable_ack *ack_m= ru, int n);


/**=
@@ -426,8 +423,7 @@
* @return the number of bu= ffer that are available for sending without
* = breaking ack sequence
* */
-int
-reliable_get_num_output_sequenced_available(struct reliable *rel);
+int reliable_get_num_o= utput_sequenced_available(struct reliable *rel);
/**
* Mark the reliable entry associated with th= e given buffer as
diff --git a/src/openvpn/ring_buffer.h b/= src/openvpn/ring_buffer.h
new file mode 100644
index 0000000..e554296

--- /dev/null
++= + b/src/openvpn/ring_buffer.h
@@ -0,0 +1,124 @@
<= span style=3D"color: hsl(120, 100%, 40%);">+/*

+ * OpenVPN -- An application to securely tunnel= IP networks
+ * = over a single UDP port, with support for SSL/TLS-based
+ * session authentic= ation and key exchange,

+ * packet encryption, packet authentication, and
= + * packet compress= ion.
+ *
+ * Copyright (C) 2002-2024 Open= VPN Inc <sales@...515...>

+ * 2019 Lev Stipakov <lev@...515...>
+ *
+ * This program is free software; you ca= n redistribute it and/or modify
+ * it under the terms of the GNU General Public License versio= n 2
+ * as published= by the Free Software Foundation.
+ *
+ * = This program is distributed in the hope that it will be useful,
= + * but WITHOUT ANY WARRANTY; = without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. = See the
+ * GNU Gene= ral Public License for more details.
+ *
+= * You should have received a copy of the GNU General Public License along=
+ * with this progr= am; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, B= oston, MA 02110-1301 USA.
+ */
++#ifdef _WIN32
+#ifndef OPENVPN_RING_BUFFER_H
+#define OPENVPN_RING_BUFF= ER_H
+
+#include <windows.h>
<= br>+#include <winioctl.h>=
+
+#include <stdint.h>
+#include <stdbool.h>
+
+/*
+ * Values below are taken from Wireguard Windows client
+ * https://github.com/Wir= eGuard/wireguard-go/blob/master/tun/wintun/ring_windows.go#L14
+ */

+#define WINTUN_RING_CAPACITY 0x800000
+#define WINTUN_RING_TRAI= LING_BYTES 0x10000
+#= define WINTUN_MAX_PACKET_SIZE 0xffff
+#define WINTUN_PACKET_ALIGN 4
+
+#define TUN_IOCTL_REGISTER_RINGS \
+ CTL_CODE(51820U, 0x970U, METHOD_BUFFE= RED, FILE_READ_DATA | FILE_WRITE_DATA)
+
+= /**
+ * Wintun ring b= uffer
+ * See https:/= /github.com/WireGuard/wintun#ring-layout
+ */
+struct tun_ring
= +{
+ volatile ULON= G head;
+ volatile= ULONG tail;
+ vol= atile LONG alertable;
+ UCHAR data[WINTUN_RING_CAPACITY + WINTUN_RING_TRAILING_BYTES];=
+};
+
+/**
+ = * Struct for ring buffers registration
+ * See https://github.com/WireGuard/wintun#registering-r= ings
+ */
<= span style=3D"color: hsl(120, 100%, 40%);">+struct tun_register_rings
+{
+ struct
+ {
+ ULONG ring_size;
+ struct tun_ring *ring;
+ HANDLE tail_moved;
+ } send, receive;
+};
+
+s= truct TUN_PACKET_HEADER
+{
+ uint32_t s= ize;
+};
+

+struct TUN_PACKET
+{
+ uint32_t size;
+};
+
+/**+ * Registers ring buffers use= d to exchange data between
+ * userspace openvpn process and wintun kernel driver,
+ * see https://github.com/WireGua= rd/wintun#registering-rings

+ *
+ * @param= device handle to opened wintun device
+ * @param send_ring pointer to = send ring
+ * @param = receive_ring pointer to receive ring
+ * @param send_tail_moved event set by wintun t= o signal openvpn
+ * = that data is available for reading in send ring<= /span>
+ * @param receive_ta= il_moved event set by openvpn to signal wintun
+ * that data has bee= n written to receive ring
+ * @return true if registration is successful, fal= se otherwise - use
+ = * GetLastError()
+ */=
+static inline bool<= /span>
+register_ring_buffer= s(HANDLE device, struct tun_ring *send_ring, struct tun_ring *receive_ring,=
+ = HANDLE send_tail_moved, HANDLE receive_tail_moved)
+{
+ struct tun_register_rings rr;
+ BOOL res;
+ DWORD bytes_returned;
+
+ ZeroMemory(&rr, sizeof(rr));
+
+ rr.send.ring =3D send_ring;
+ rr.send.ring_size =3D sizeof(struct tun_ring);
+ rr.send.tail_moved = =3D send_tail_moved;
= +
+ rr.receive.rin= g =3D receive_ring;
+= rr.receive.ring_size =3D sizeof(struct tun_ring);
+ rr.receive.tail_moved =3D receive_tai= l_moved;
+
= + res =3D DeviceIoControl(de= vice, TUN_IOCTL_REGISTER_RINGS, &rr, sizeof(rr), NULL, 0,
+ &by= tes_returned, NULL);

= +
+ return res != =3D FALSE;
+}<= br>+
+#endif /* ifndef OPENVPN_RING_BUFFER_H */
+#endif /* ifdef _WIN32 *= /
diff --git a/src/openvpn/route.c b/src/openvpn/route.c
index c4f7f95..e504485 100644
--- a/src/openv= pn/route.c
+++ b/src/openvpn/route.c
@@ -46= ,11 +46,11 @@
#include "memdbg.h"

#if defined(TARGET_LINUX) || defined(TARGET_ANDROID)
-#include <linux/rtne= tlink.h> /* RTM_GETROUTE etc. */
+#include <linux/rtnetlink.h> /* RTM_GETROU= TE etc. */
#endif

#if d= efined(TARGET_NETBSD)
-= #include <net/route.h> /* RT_ROUNDUP(), RT_ADVANCE()= */
+#include <net= /route.h> /* RT_ROUNDUP(), RT_ADVANCE() */
#endif

#ifdef _WIN32
@@ -67,7 +67,8 = @@

static int route_ipv6_ipapi(bool add,= const struct route_ipv6 *, const struct tuntap *);

-static int add_route_ipapi(= const struct route_ipv4 *r, const struct tuntap *tt, DWORD adapter_index);<= /span>
+static int add_route= _ipapi(const struct route_ipv4 *r, const struct tuntap *tt,
+ DWORD ad= apter_index);


static bool del_route_ipap= i(const struct route_ipv4 *r, const struct tuntap *tt);

@@ -89,9 +90,7 @@
int i;
for (i =3D 0; i < rb->n_bypass; ++i)

{
- msg(D_ROUTE, &qu= ot;ROUTE: bypass_host_route[%d]=3D%s",
- i,
- print_in_addr_t(rb->bypass[i], 0, &gc));<= /span>
+ msg(D_ROUTE,= "ROUTE: bypass_host_route[%d]=3D%s", i, print_in_addr_t(rb->b= ypass[i], 0, &gc));
}
gc_free= (&gc);
}
@@ -99,9 +98,9 @@
<= span> #endif


/* Route addition return st= atus codes */
-#define = RTA_ERROR 0 /* route addition failed */
-#define RTA_SUCCESS 1 /* route addition succeeded *= /
-#define RTA_EEXIST = 2 /* route not added as it already exists */
+#define RTA_ERROR 0 /* route addition failed *= /
+#define RTA_SUCCES= S 1 /* route addition succeeded */
+#define RTA_EEXIST 2 /* route not added as it already exist= s */

static bool
add_by= pass_address(struct route_bypass *rb, const in_addr_t a)
@@= -169,7 +168,8 @@
}

voi= d
-copy_route_option_li= st(struct route_option_list *dest, const struct route_option_list *src, str= uct gc_arena *a)
+cop= y_route_option_list(struct route_option_list *dest, const struct route_opti= on_list *src,
+ = struct gc_arena *a)
{
= *dest =3D *src;
dest->gc =3D a;
@= @ -177,8 +177,7 @@

void
= copy_route_ipv6_option_list(struct route_ipv6_option_list *dest,- con= st struct route_ipv6_option_list *src,
- struct gc_arena *a)
= + co= nst struct route_ipv6_option_list *src, struct gc_arena *a)
{

*dest =3D *src;
dest->gc = =3D a;
@@ -188,11 +187,8 @@
route_string(c= onst struct route_ipv4 *r, struct gc_arena *gc)
{ struct buffer out =3D alloc_buf_gc(256, gc);
- buf_printf(&out, "ROUTE ne= twork %s netmask %s gateway %s",
- print_in_addr_t(r->network, 0, gc),
- print_in_add= r_t(r->netmask, 0, gc),
- print_in_addr_t(r->gateway, 0, gc)
- );
+ buf_printf(&out, "ROUTE netw= ork %s netmask %s gateway %s", print_in_addr_t(r->network, 0, gc),<= /span>
+ print= _in_addr_t(r->netmask, 0, gc), print_in_addr_t(r->gateway, 0, gc));
if (r->flags & RT_METRIC_DEFINED)
{

buf_printf(&out, " metric %d&quo= t;, r->metric);
@@ -232,10 +228,7 @@
}<= /span>

static bool
-get_special_addr(const struct route_list *rl,
- const cha= r *string,
- = in_addr_t *out,
-= bool *status)
+get_special_addr(const struct route_list *rl, const char *string= , in_addr_t *out, bool *status)
{
if = (status)
{
@@ -270,7 +263,8 @@<= br> }
else
= {
- = msg(M_INFO, PACKAGE_NAME " ROUTE: net_gateway undefined -- una= ble to get default gateway from system");
+ msg(M_INFO, PACKAGE_NAME<= br>+ " = ROUTE: net_gateway undefined -- unable to get default gateway from system&q= uot;);
if (status)
= {
*status =3D false;<= br>@@ -315,15 +309,13 @@
}
<= br> static bool
-= init_route(struct route_ipv4 *r,
- struct addrinfo **network_list,
- const struct route_option *ro,
+init_route(struct rou= te_ipv4 *r, struct addrinfo **network_list, const struct route_option *ro,<= /span>
const struct route_list *rl)
{=
const in_addr_t default_netmask =3D IPV4_NETMASK_HOST= ;
bool status;
int ret;- struct in_addr special =3D = {0};
+ struct in_a= ddr special =3D { 0 };

CLEAR(*r);
r->option =3D ro;
@@ -337,7 +329,7 @@=
/* get_special_addr replaces specialaddr with a speci= al ip addr
* like gw. getaddrinfo is called to conver= t a a addrinfo struct */

- if (get_special_addr(rl, ro->network, (in_addr_= t *) &special.s_addr, &status))
+ if (get_special_addr(rl, ro->network, (in_addr_t= *)&special.s_addr, &status))
{
if (!status)

{
@@ -346,= 13 +338,12 @@
special.s_addr =3D htonl(special.s_a= ddr);
char buf[INET_ADDRSTRLEN];
= inet_ntop(AF_INET, &special, buf, sizeof(buf));
- ret =3D openvpn_getaddrinfo(0= , buf, NULL, 0, NULL,

-= AF_INET, network_list);
+ ret =3D openvpn_getaddrinfo(0= , buf, NULL, 0, NULL, AF_INET, network_list);
}=
else
{
- ret =3D openvpn_getaddrinfo(GETADDR_RESOLVE | = GETADDR_WARN_ON_SIGNAL,
- ro->network, NULL, 0, NULL, AF_INET,= network_list);
+ = ret =3D openvpn_getaddrinfo(GETADDR_RESOLVE | GETADDR_WARN_ON_SIGNAL, r= o->network, NULL, 0,
+ NULL, AF_INET, network_list);<= br> }

status =3D (ret =3D= =3D 0);
@@ -366,13 +357,8 @@

if (is_route_parm_defined(ro->netmask))

{<= /span>
- r->netmask = =3D getaddr(
- = GETADDR_HOST_ORDER
-= | GETADDR_WARN_ON_SIGNAL,
- ro->netmask,
- 0,
- &status,
- NULL);
+ r->netmask =3D
+ getaddr(GETADDR_HOST_ORDER | GETADDR_WAR= N_ON_SIGNAL, ro->netmask, 0, &status, NULL);
= if (!status)
{
goto= fail;
@@ -389,14 +375,8 @@
{ if (!get_special_addr(rl, ro->gateway, &r->gatew= ay, &status))
{
- r->gateway =3D getaddr(
- GETADDR_RESOLVE
- | GETADDR= _HOST_ORDER
- = | GETADDR_WARN_ON_SIGNAL,
- ro->gateway,
- 0,
- &status,
- NULL);
+ r->gateway =3D getaddr(GETADDR_RE= SOLVE | GETADDR_HOST_ORDER | GETADDR_WARN_ON_SIGNAL,
+ ro->g= ateway, 0, &status, NULL);
}
= if (!status)
{
@@ -411,7 += 391,9 @@
}
else {
- = msg(M_WARN, PACKAGE_NAME " ROUTE: " PACKAGE_NAME " n= eeds a gateway parameter for a --route option and no default was specified = by either --route-gateway or --ifconfig options");
+ msg(M_WARN, PACKAGE_NAME
+ "= ROUTE: " PACKAGE_NAME
+ " needs a gateway parameter for a --route opti= on and no default was specified by either --route-gateway or --ifconfig opt= ions");
goto fail;
= }
}
@@ -425,8 +407,7 @@
<= span> if (r->metric < 0)

{ msg(M_WARN, PACKAGE_NAME " ROUTE: route metric for= network %s (%s) must be >=3D 0",
- ro->network,
- ro->metric);
<= span style=3D"color: hsl(120, 100%, 40%);">+ ro->network,= ro->metric);

goto fail;
= }
r->flags |=3D RT_METRIC_DEFINED;
@@ -451,13 +432,12 @@
}

static bool
-init_route_ipv6(struct route_ipv6 *r6,
- const struct route_ipv6_option *r6o,
- const str= uct route_ipv6_list *rl6 )
+init_route_ipv6(struct route_ipv6 *r6, const struct route_ipv6_optio= n *r6o,
+ = const struct route_ipv6_list *rl6)
{
= CLEAR(*r6);

- if (!get_ipv6_addr( r6o->prefix, &r6->network, &a= mp;r6->netbits, M_WARN ))
+ if (!get_ipv6_addr(r6o->prefix, &r6->network, &r= 6->netbits, M_WARN))
{
got= o fail;
}
@@ -465,9 +445,9 @@ /* gateway */
if (is_route_parm_defined(r= 6o->gateway))
{
- if (inet_pton( AF_INET6, r6o->gateway, &r6= ->gateway ) !=3D 1)
- msg( M_WARN, PACKAGE_NAME "ROUTE6: cannot pars= e gateway spec '%s'", r6o->gateway );
+ msg(M_WARN, PACKAGE_NAME &quo= t;ROUTE6: cannot parse gateway spec '%s'", r6o->gateway);
}
}
else = if (rl6->spec_flags & RTSA_REMOTE_ENDPOINT)
@@ -484,= 8 +464,7 @@
if (r6->metric < 0)
{

msg(M_WARN, PACKAGE_NAME "= ROUTE: route metric for network %s (%s) must be >=3D 0",- r6o->prefix,=
- r6o-&= gt;metric);
+ = r6o->prefix, r6o->metric);
goto = fail;
}
r6->flags |=3D= RT_METRIC_DEFINED;
@@ -510,12 +489,8 @@
}=

void
-add_route_to_option_list(struct route_option_list *l,
- = const char *network,
-= const char *netmask,
- const char *gateway,
- co= nst char *metric,
- = int table_id)
+add_route_to_option_list(struct route_option_list *l, const = char *network, const char *netmask,
+ const char *gateway, const char *m= etric, int table_id)
{
struct route_o= ption *ro;
ALLOC_OBJ_GC(ro, struct route_option, l->= ;gc);
@@ -526,15 +501,11 @@
ro->tab= le_id =3D table_id;
ro->next =3D l->routes;
l->routes =3D ro;
-
}

void=
-add_route_ipv6_to_opt= ion_list(struct route_ipv6_option_list *l,
- const char *prefix,
- = const char *gateway,
- int table_id)=
+add_route_ipv6_to_o= ption_list(struct route_ipv6_option_list *l, const char *prefix,
= + = const char *gateway, const char *metric, int table_id)
{
struct route_ipv6_option *ro;
ALLO= C_OBJ_GC(ro, struct route_ipv6_option, l->gc);
@@ -561,9= +532,7 @@
}

void
-route_list_add_vpn_gateway(= struct route_list *rl,
= - struct env_set *es,
- const in_addr_t addr)<= /span>
+route_list_add_vpn_g= ateway(struct route_list *rl, struct env_set *es, const in_addr_t addr)
{
ASSERT(rl);
rl-&g= t;spec.remote_endpoint =3D addr;
@@ -572,8 +541,7 @@=
}

static void
-add_block_local_item(struct route_lis= t *rl,

- = const struct route_gateway_address *gateway,
+add_block_local_item(struct route_list *rl, = const struct route_gateway_address *gateway,
= in_addr_t target)
{
if (rl-&g= t;rgi.gateway.netmask < 0xFFFFFFFF)
@@ -585,11 +553,11 @= @
ALLOC_OBJ_GC(r2, struct route_ipv4, &rl->= gc);

/* split a route into two s= maller blocking routes, and direct them to target */
- l2 =3D ((~gateway->netmask)+1)&g= t;>1;
+ l2 = =3D ((~gateway->netmask) + 1) >> 1;
r1-&g= t;flags =3D RT_DEFINED;
r1->gateway =3D target;=
r1->network =3D gateway->addr & gateway= ->netmask;
- = r1->netmask =3D ~(l2-1);
+ r1->netmask =3D ~(l2 - 1);
r1-&= gt;next =3D rl->routes;
rl->routes =3D r1;

@@ -627,21 +595,15 @@
boo= l
block_local_needed(const struct route_list *rl) {
- const i= nt rgi_needed =3D (RGI_ADDR_DEFINED|RGI_NETMASK_DEFINED);
- return (rl->flags & RG_BLOCK= _LOCAL)
- &am= p;& (rl->rgi.flags & rgi_needed) =3D=3D rgi_needed
- && (rl->spec.= flags & RTSA_REMOTE_ENDPOINT)

- && rl->spec.remote_host_local !=3D TLA_LO= CAL;
+ const int r= gi_needed =3D (RGI_ADDR_DEFINED | RGI_NETMASK_DEFINED);
+ return (rl->flags & RG_BLOCK= _LOCAL) && (rl->rgi.flags & rgi_needed) =3D=3D rgi_needed
+ && = (rl->spec.flags & RTSA_REMOTE_ENDPOINT) && rl->spec.remot= e_host_local !=3D TLA_LOCAL;
}
bool
-init_rout= e_list(struct route_list *rl,
- const struct route_option_list *opt,
- const char *remote_e= ndpoint,

- = int default_metric,
= - in_addr_t remote_host,
- struct env_set *es,
- openvpn_net_ctx_t *ctx)
+init_route_list(struct = route_list *rl, const struct route_option_list *opt,
+ const char *remote_endpoi= nt, int default_metric, in_addr_t remote_host,
+ struct env_set *es, openvpn_net_= ctx_t *ctx)
{
struct gc_arena gc =3D = gc_new();
bool ret =3D true;
@@ -683,1= 4 +645,9 @@
if (is_route_parm_defined(remote_endpoint)= )
{
bool defined =3D false;
- rl->spec.rem= ote_endpoint =3D getaddr(
- GETADDR_RESOLVE
- | GETADDR_HOST_ORDER
- | GETADDR_WARN_ON_SIGNAL,
- remote_endpoint,- 0,
- &defined,
- NULL);

+ rl->spec.remote_endpoint= =3D

+ get= addr(GETADDR_RESOLVE | GETADDR_HOST_ORDER | GETADDR_WARN_ON_SIGNAL, remote_= endpoint,
+ = 0, &defined, NULL);

= if (defined)
{
@@ -758,14 +715,1= 3 @@
* "good enough")
*/
static bool
- const struct in6_ad= dr *host )
+route_ipv= 6_match_host(const struct route_ipv6 *r6, const struct in6_addr *host)
{
unsigned int bits =3D r6->netbits;
int i;
unsigned int mask;
- if (bits= >128)
+ if (bit= s > 128)
{
return false;
}
@@ -783,9 +739,9 @@
= return true;
}

- mask =3D 0xff << (8-bits)= ;

+ mask =3D 0xff = << (8 - bits);

- if ( (r6->network.s6_addr[i] & mask) =3D=3D (ho= st->s6_addr[i] & mask ))
+ if ((r6->network.s6_addr[i] & mask) =3D=3D (host->= ;s6_addr[i] & mask))
{
re= turn true;
}
@@ -794,12 +750,9 @@
}

bool
-init_route_ipv6_list(struct route_ipv6_lis= t *rl6,
- = const struct route_ipv6_option_list *opt6,
- const char *remote_endpoin= t,
- = int default_metric,
-= const struct in6_addr *remote_host_ipv6,
- struct env_set= *es,

+init_route_ipv= 6_list(struct route_ipv6_list *rl6, const struct route_ipv6_option_list *op= t6,
+ = const char *remote_endpoint, int default_metric,
+ const struct in6_add= r *remote_host_ipv6, struct env_set *es,
= openvpn_net_ctx_t *ctx)
{
struct = gc_arena gc =3D gc_new();
@@ -823,7 +776,7 @@
}


msg(D_ROUTE, "GDG6: r= emote_host_ipv6=3D%s",
- remote_host_ipv6 ? print_in6_addr(*remote_host_ipv6, 0, &= ;gc) : "n/a" );
+ remote_host_ipv6 ? print_in6_addr(*remote_host_ipv6, 0, &= gc) : "n/a");

get_default_= gateway_ipv6(&rl6->rgi6, remote_host_ipv6, ctx);
= if (rl6->rgi6.flags & RGI_ADDR_DEFINED)
@@ -838,16= +791,16 @@
dmsg(D_ROUTE, "ROUTE6: default_ga= teway=3DUNDEF");
}

- if (is_route_parm_defined( rem= ote_endpoint ))

+ = if (is_route_parm_defined(remote_endpoint))
{- if (inet_pton( AF_INET= 6, remote_endpoint,
- = &rl6->remote_endpoint_ipv6) =3D=3D 1)+ if (inet_pton(AF_INET= 6, remote_endpoint, &rl6->remote_endpoint_ipv6) =3D=3D 1)
= {
rl6->spec_flags |=3D RTSA_= REMOTE_ENDPOINT;
}
else
{
- msg(M_WARN, PACKAGE_NAME " ROUTE: failed to parse/reso= lve VPN endpoint: %s", remote_endpoint);
+ msg(M_WARN, PACKAGE_NAME " ROUTE= : failed to parse/resolve VPN endpoint: %s",
+ remote_endpoint);
<= span> ret =3D false;

}
}

@@ -877,11 +830,11 @@
= * avoiding routing loops, so ignore this part and let
= * need_remote_ipv6_route always evaluate to false<= br> */
- if (remote_host_ipv6
- && route_ipv6_match_host= ( r6, remote_host_ipv6 ) )
+ if (remote_host_ipv6 && route_ipv6_match_hos= t(r6, remote_host_ipv6))
{
need_remote_ipv6_route =3D true;

- msg(D_ROUTE, "ROU= TE6: %s/%d overlaps IPv6 remote %s, adding host route to VPN endpoint"= ,
+ = msg(D_ROUTE,
+ = "ROUTE6: %s/%d overlaps IPv6 remote %s, adding host= route to VPN endpoint",
prin= t_in6_addr(r6->network, 0, &gc), r6->netbits,
= print_in6_addr(*remote_host_ipv6, 0, &gc));
}
@@ -893,15 +846,15 @@<= br> /* add VPN server host route if needed */
= if (need_remote_ipv6_route)
{
- if ( (rl6->rgi6.flags & (RGI= _ADDR_DEFINED|RGI_IFACE_DEFINED) ) =3D=3D
- (RGI_ADDR_DEFINED|RGI_IFACE_DEFINED) )
+ if ((rl6->rg= i6.flags & (RGI_ADDR_DEFINED | RGI_IFACE_DEFINED))
+ =3D=3D (RGI_ADDR_DEFINED | R= GI_IFACE_DEFINED))
{
= struct route_ipv6 *r6;
ALLOC_OBJ_CLEAR_GC(r6, = struct route_ipv6, &rl6->gc);

= r6->network =3D *remote_host_ipv6;
= r6->netbits =3D 128;
+ if (!(rl6->rgi6.fla= gs & RGI_ON_LINK))
{
= r6->gateway =3D rl6->rgi6.gateway.addr_ipv6;
}

@@ -918,7 +871,8 @@
= }
else
{
<= span style=3D"color: hsl(0, 100%, 40%);">- msg(M_WARN, "ROU= TE6: IPv6 route overlaps with IPv6 remote address, but could not determine = IPv6 gateway address + interface, expect failure\n" );

+ msg(M_WARN,

<= span style=3D"color: hsl(120, 100%, 40%);">+ "ROUTE6: I= Pv6 route overlaps with IPv6 remote address, but could not determine IPv6 g= ateway address + interface, expect failure\n");

= }
}

@@ -927,13 +8= 81,8 @@
}

static bool
-add_route3(in_addr_t ne= twork,
- in_a= ddr_t netmask,
- = in_addr_t gateway,
= - const struct tuntap *tt,
- unsigned int flags,
- const struct route_gateway_info *rgi,
- const struct = env_set *es,
+add_rou= te3(in_addr_t network, in_addr_t netmask, in_addr_t gateway, const struct t= untap *tt,
+ = unsigned int flags, const struct route_gateway_info *rgi, const struct en= v_set *es,
openvpn_net_ctx_t *ctx)
{

struct route_ipv4 r;
@@ -946,18= +895,13 @@
}

static vo= id
-del_route3(in_addr_= t network,
- = in_addr_t netmask,
- = in_addr_t gateway,
- const struct tuntap *tt,
- unsigned int flags,
- const struct route_gateway_info *rgi= ,
- const str= uct env_set *es,
+del= _route3(in_addr_t network, in_addr_t netmask, in_addr_t gateway, const stru= ct tuntap *tt,
+ = unsigned int flags, const struct route_gateway_info *rgi, const struc= t env_set *es,
openvpn_net_ctx_t *ctx) {
struct route_ipv4 r;
C= LEAR(r);
- r.flags = =3D RT_DEFINED|RT_ADDED;
+ r.flags =3D RT_DEFINED | RT_ADDED;
r.network = =3D network;
r.netmask =3D netmask;
= r.gateway =3D gateway;
@@ -965,56 +909,42 @@
<= span> }


static bool
-add_bypass_routes(struct route_bypass *rb,=
- in_= addr_t gateway,
- = const struct tuntap *tt,
- unsigned int flags,
- const struct route_gatewa= y_info *rgi,
- = const struct env_set *es,
- openvpn_net_ctx_t *ctx)
+add_bypass_routes(struct route_bypass *r= b, in_addr_t gateway, const struct tuntap *tt,
+ unsigned int flags, const stru= ct route_gateway_info *rgi,
+ const struct env_set *es, openvpn_net_ctx_t *ctx)=
{
int ret =3D true;
= for (int i =3D 0; i < rb->n_bypass; ++i)
{<= /span>
if (rb->bypass[i])
{
- ret =3D add= _route3(rb->bypass[i], IPV4_NETMASK_HOST, gateway, tt,
- flags | RO= UTE_REF_GW, rgi, es, ctx) && ret;
+ ret =3D add_route3(rb->bypass[i], IPV4= _NETMASK_HOST, gateway, tt, flags | ROUTE_REF_GW,
+ rgi, es, ctx)
+ &= ;& ret;
}
}
return ret;

}

s= tatic void
-del_bypass_= routes(struct route_bypass *rb,
- in_addr_t gateway,
- const struct tuntap *tt,<= br>- unsigned in= t flags,
- = const struct route_gateway_info *rgi,
- const struct env_set *es,
= - openvpn_net_ct= x_t *ctx)
+del_bypass= _routes(struct route_bypass *rb, in_addr_t gateway, const struct tuntap *tt= ,
+ = unsigned int flags, const struct route_gateway_info *rgi,
+ const struct env_se= t *es, openvpn_net_ctx_t *ctx)
{
int = i;
for (i =3D 0; i < rb->n_bypass; ++i) {
if (rb->bypass[i])
{

- = del_route3(rb->bypass[i],
- IPV4_NETMASK_HOST,
- gateway,
<= span style=3D"color: hsl(0, 100%, 40%);">- tt,
=
- flags= | ROUTE_REF_GW,
- = rgi,
= - es,
+ del_route3(rb->bypass[i], IPV4_NETMASK_HOST, gateway= , tt, flags | ROUTE_REF_GW, rgi, es,
= ctx);
}
}
= }

static bool
-redirect_default_route_to_vpn(struct route_list = *rl, const struct tuntap *tt,
- unsigned int flags, const struct env_= set *es,
- = openvpn_net_ctx_t *ctx)
+redirect_default_route_to_vpn(struct route_list *rl, c= onst struct tuntap *tt, unsigned int flags,
+ const struct env_set = *es, openvpn_net_ctx_t *ctx)
{
const = char err[] =3D "NOTE: unable to redirect IPv4 default gateway --"= ;
bool ret =3D true;
@@ -1064,9 +994,8= @@
if ((rl->spec.flags & RTSA_REMO= TE_HOST)
&& rl->spec.remote= _host !=3D IPV4_INVALID_ADDR)
{
= - ret =3D add_= route3(rl->spec.remote_host, IPV4_NETMASK_HOST,
- rl->rg= i.gateway.addr, tt, flags | ROUTE_REF_GW,
- &rl->rgi, e= s, ctx);
+ = ret =3D add_route3(rl->spec.remote_host, IPV4_NETMASK_HOST, rl-= >rgi.gateway.addr,
+ tt, flags | ROUTE_REF_GW, &rl-&g= t;rgi, es, ctx);
if (ret)
{

rl->= iflags |=3D RL_DID_LOCAL;
@@ -1080,20 +1009,23 @@ #endif /* ifndef TARGET_ANDROID */

/* route DHCP/DNS server traffic through original default ga= teway */

- r= et =3D add_bypass_routes(&rl->spec.bypass, rl->rgi.gateway.addr, = tt, flags,
- = &rl->rgi, es, ctx) && ret;+ ret =3D add_bypa= ss_routes(&rl->spec.bypass, rl->rgi.gateway.addr, tt, flags, &= ;rl->rgi, es,
+ = ctx)
+ && ret;

if (rl->flags & RG_REROUTE_GW)
{

if (rl->flags & R= G_DEF1)
{
= /* add new default route (1st component) */
- ret =3D add_route3(0x0000000= 0, 0x80000000, rl->spec.remote_endpoint,
- tt, flags, &= rl->rgi, es, ctx) && ret;
+ ret =3D add_route3(0x00000000, 0x80000= 000, rl->spec.remote_endpoint, tt, flags,
+ &rl->r= gi, es, ctx)
+ = && ret;

= /* add new default route (2nd component) */
- ret =3D add_route3= (0x80000000, 0x80000000, rl->spec.remote_endpoint,
- tt, fl= ags, &rl->rgi, es, ctx) && ret;
+ ret =3D add_route3(0x8000000= 0, 0x80000000, rl->spec.remote_endpoint, tt, flags,
+ &am= p;rl->rgi, es, ctx)
- = del_route3(0, 0, rl->rgi.gateway.addr, tt,
- flags |= ROUTE_REF_GW, &rl->rgi, es, ctx);
+ del_route3(0, 0, rl->rgi.g= ateway.addr, tt, flags | ROUTE_REF_GW, &rl->rgi,
+ es, = ctx);
}

/* add new default route */

- ret =3D add_route3(0, 0= , rl->spec.remote_endpoint, tt,
- flags, &rl->rgi, e= s, ctx) && ret;
+ ret =3D add_route3(0, 0, rl->spec.remote_endpoin= t, tt, flags, &rl->rgi, es, ctx)
+ && ret;
}

}

@@ -1119,9 +1051,8 @@
}

static void
- c= onst struct tuntap *tt, unsigned int flags,
- const struct env_s= et *es,
+undo_redirec= t_default_route_to_vpn(struct route_list *rl, const struct tuntap *tt,
+ = unsigned int flags, const struct env_set *es,
= openvpn_net_ctx_t *ctx)
= {
if (rl && rl->iflags & RL_DID_REDIREC= T_DEFAULT_GATEWAY)
@@ -1129,61 +1060,35 @@
= /* delete remote host route */
if (rl->= ;iflags & RL_DID_LOCAL)
{
- del_route3(rl->spec.remote_= host,
- = IPV4_NETMASK_HOST,
- rl->rgi.gateway.addr,
- tt,
- flags | ROUTE_R= EF_GW,
- = &rl->rgi,
- ctx);
+ del_route3(rl->spec.remote_host, IPV4_NETMA= SK_HOST, rl->rgi.gateway.addr, tt,
+ flags | ROUTE_REF_GW, &rl->= rgi, es, ctx);
rl->iflags &=3D ~RL_DID_= LOCAL;
}

= /* delete special DHCP/DNS bypass route */
- del_bypass_routes(&rl->spec.bypass, r= l->rgi.gateway.addr, tt, flags,
- &rl->rgi, es, ctx);+ del_bypass_routes(&am= p;rl->spec.bypass, rl->rgi.gateway.addr, tt, flags, &rl->rgi, = es, ctx);

if (rl->flags &= RG_REROUTE_GW)
{
if = (rl->flags & RG_DEF1)
{
/* delete default route (1st component) */

- del_route3(0x0000000= 0,

- = 0x80000000,
- = rl->spec.remote_endpoint,
- tt,
- flags,<= /span>
- = &rl->rgi,
-= es,
- ctx);
+ del_route3(0x00000000, 0x80000000, rl= ->spec.remote_endpoint, tt, flags, &rl->rgi,
+ es, ctx);

/* delete default route (2n= d component) */
- = del_route3(0x80000000,
- 0x80000000,
- rl->spec.remote_e= ndpoint,
- = tt,
- = flags,
- &rl->rgi,
- es,
- ctx);
+ del_r= oute3(0x80000000, 0x80000000, rl->spec.remote_endpoint, tt, flags, &= rl->rgi,
+ = es, ctx);
}
else

{
= /* delete default route */
- del_route3(0,
- 0,
- rl->spec.remote_= endpoint,
- = tt,
- = flags,
- &rl->rgi,
- es,
- ctx);
+ del_r= oute3(0, 0, rl->spec.remote_endpoint, tt, flags, &rl->rgi, es, ct= x);
/* restore original default route if t= here was any */
if (rl->rgi.flags &= RGI_ADDR_DEFINED)
{
- add_route3(0, 0, rl->= ;rgi.gateway.addr, tt,
= - flags | ROUTE_REF_GW, &rl->rgi, es, = ctx);
+ = add_route3(0, 0, rl->rgi.gateway.addr, tt, flags | ROUTE_REF_GW, &= amp;rl->rgi, es,
+= ctx);
}
}
}
@@ -= 1193,32 +1098,28 @@
}

b= ool
-add_routes(struct = route_list *rl, struct route_ipv6_list *rl6,
- const struct tuntap *tt, unsigned int fla= gs,
- const s= truct env_set *es, openvpn_net_ctx_t *ctx)
+add_routes(struct route_list *rl, struct route_ipv6_= list *rl6, const struct tuntap *tt,
+ unsigned int flags, const struct env_set *es, op= envpn_net_ctx_t *ctx)
{
bool ret =3D = redirect_default_route_to_vpn(rl, tt, flags, es, ctx);
- if (rl && !(rl->iflags &= ; RL_ROUTES_ADDED) )
= + if (rl && !(rl->iflags & RL_ROUTES_ADDED))
{

struct route_ipv4 *r;
=
if (rl->routes && !tt->did_ifconfig= _setup)
{
- msg(M_INFO, "WARNING: OpenVPN was configured = to add an IPv4 "
+ msg(M_INFO,
+ "WARNING: OpenVPN was configured to add an IPv4 = "
"route. However, no IPv4 has b= een configured for %s, "
"theref= ore the route installation may fail or may not work "
- "as expected.&quo= t;, tt->actual_name);
+ "as expected.",
+ tt->actual_name);
<= span> }


#ifdef ENABLE_MANAGEMENT=
if (management && rl->routes) {
- = management_set_state(management,
- OPENVPN_STATE_ADD_ROUT= ES,
- = NULL,
- = NULL,
- NULL,
- NULL,
+ management_= set_state(management, OPENVPN_STATE_ADD_ROUTES, NULL, NULL, NULL, NULL,
NULL);
= }
#endif
@@ -1233,16 +1134,18 @@
}
rl->iflags |=3D RL_ROUTES= _ADDED;
}
- if (rl6 && !(rl6->iflags & RL_ROUTES_ADDED) )
+ if (rl6 &&= ; !(rl6->iflags & RL_ROUTES_ADDED))
{ struct route_ipv6 *r;

= if (!tt->did_ifconfig_ipv6_setup)
{
- msg(M_INFO, &qu= ot;WARNING: OpenVPN was configured to add an IPv6 "
+ msg(M_INFO,
+ "WARNING: Ope= nVPN was configured to add an IPv6 "

= "route. However, no IPv6 has been configured for %s, "
= "therefore the route installation may fail or m= ay not work "
- = "as expected.", tt->actual_name);
+ "as expected.&= quot;,

+ = tt->actual_name);
}
=
for (r =3D rl6->routes_ipv6; r; r =3D r->next)
@@ -1260,18 +1163,16 @@
}

void
-d= elete_routes(struct route_list *rl, struct route_ipv6_list *rl6,
= - const struct tunta= p *tt, unsigned int flags,
- const struct env_set *es, openvpn_net_ctx_t *ctx)=
+delete_routes(struct route= _list *rl, struct route_ipv6_list *rl6, const struct tuntap *tt,
= + unsigned int fla= gs, const struct env_set *es, openvpn_net_ctx_t *ctx)
{
delete_routes_v4(rl, tt, flags, es, ctx);
delete_routes_v6(rl6, tt, flags, es, ctx);

}=

void
-delete_routes_v4(struct route_list *rl, const struct tuntap *tt= ,
- uns= igned int flags, const struct env_set *es,
- openvpn_net_ctx_t *ctx)
+delete_routes_v4(struct route_lis= t *rl, const struct tuntap *tt, unsigned int flags,

+ const struct env_set *es= , openvpn_net_ctx_t *ctx)
{
if (rl &a= mp;& (rl->iflags & RL_ROUTES_ADDED))
{
@@ -1292,9 +1193,8 @@
}

void
-dele= te_routes_v6(struct route_ipv6_list *rl6, const struct tuntap *tt,- unsigned int = flags, const struct env_set *es,
- openvpn_net_ctx_t *ctx)
+delete_routes_v6(struct route_ipv6_list *= rl6, const struct tuntap *tt, unsigned int flags,
+ const struct env_set *es, op= envpn_net_ctx_t *ctx)
{
if (rl6 &= & (rl6->iflags & RL_ROUTES_ADDED))
{=
@@ -1330,22 +1230,17 @@
static void
print_route_option(const struct route_option *ro, int level)
{
- msg(leve= l, " route %s/%s/%s/%s",
- show_opt(ro->network),
- show_opt(ro->netmask),
- show_opt(ro->gateway),
- show_opt(ro->m= etric));
+ msg(lev= el, " route %s/%s/%s/%s", show_opt(ro->network), show_opt(ro-= >netmask),
+ = show_opt(ro->gateway), show_opt(ro->metric));
}

void
-print_route_options(const struct route_option_list *rol,
- int = level)
+print_route_o= ptions(const struct route_option_list *rol, int level)
{
struct route_option *ro;
if (rol-&= gt;flags & RG_ENABLE)
{
- msg(level, " [redirect_default_gat= eway local=3D%d]",
- (rol->flags & RG_LOCAL) !=3D 0);
+ msg(level, " [redirect_defa= ult_gateway local=3D%d]", (rol->flags & RG_LOCAL) !=3D 0);
}
for (ro =3D rol->routes; ro; ro = =3D ro->next)
{
@@ -1354,8 +1249,7 = @@
}

void
-print_default_gateway(const int msg= level,

- = const struct route_gateway_info *rgi,
+print_default_gateway(const int msglevel, const st= ruct route_gateway_info *rgi,
const = struct route_ipv6_gateway_info *rgi6)
{
= struct gc_arena gc =3D gc_new();
@@ -1486,23 +1380,22 @@=
struct gc_arena gc =3D gc_new();
= if (r6->flags & RT_DEFINED)
{
- struct buffer name1 =3D alloc_= buf_gc( 256, &gc );
- struct buffer val =3D alloc_buf_gc( 256, &gc );
- struct buffer name2 =3D all= oc_buf_gc( 256, &gc );

+ struct buffer name1 =3D alloc_buf_gc(256, &gc);+ struct buffer val = =3D alloc_buf_gc(256, &gc);
+ struct buffer name2 =3D alloc_buf_gc(256, &gc);

- = buf_printf( &name1, "route_ipv6_network_%d", i );
= - buf_printf( &val, &q= uot;%s/%d", print_in6_addr( r6->network, 0, &gc ),
- r6->netbits= );

- setenv_str= ( es, BSTR(&name1), BSTR(&val) );
+ buf_printf(&name1, "route_ipv6_netwo= rk_%d", i);
+ = buf_printf(&val, "%s/%d", print_in6_addr(r6->network,= 0, &gc), r6->netbits);
+ setenv_str(es, BSTR(&name1), BSTR(&val));=

- bu= f_printf( &name2, "route_ipv6_gateway_%d", i );
- setenv_str( es, BSTR(&n= ame2), print_in6_addr( r6->gateway, 0, &gc ));

+ buf_printf(&name2, "rout= e_ipv6_gateway_%d", i);
+ setenv_str(es, BSTR(&name2), print_in6_addr(r6->gat= eway, 0, &gc));

if (r6->f= lags & RT_METRIC_DEFINED)
{
- struct buffer name3 =3D allo= c_buf_gc( 256, &gc );
- buf_printf( &name3, "route_ipv6_metric_%d", i= );
- setenv_= int( es, BSTR(&name3), r6->metric);
+ struct buffer name3 =3D alloc_buf_gc(256= , &gc);
+ = buf_printf(&name3, "route_ipv6_metric_%d", i);
= + setenv_int(es, BST= R(&name3), r6->metric);
}
= }
gc_free(&gc);
@@ -1542,19 +1= 435,15 @@
#define LR_ERROR 2 /* caller should abort addi= ng route */

static int
-local_route(in_addr_t network,- in_addr_t netmask,=
- in_addr_t= gateway,
+local_rout= e(in_addr_t network, in_addr_t netmask, in_addr_t gateway,
= const struct route_gateway_info *rgi)
{

/* set LR_MATCH on local host routes */
- const int rgi_needed =3D (RGI_ADDR_DE= FINED|RGI_NETMASK_DEFINED|RGI_IFACE_DEFINED);
- if (rgi
- && (rgi->flags & rgi_needed) =3D=3D rg= i_needed
- &= & gateway =3D=3D rgi->gateway.addr
+ const int rgi_needed =3D (RGI_ADDR_DEFINED | RGI_= NETMASK_DEFINED | RGI_IFACE_DEFINED);
+ if (rgi && (rgi->flags & rgi_needed) = =3D=3D rgi_needed && gateway =3D=3D rgi->gateway.addr
= && netmask =3D=3D 0xFFFFFFFF)
{=
- if (((network= ^ rgi->gateway.addr) & rgi->gateway.netmask) =3D=3D 0)+ if (((network ^ rgi-= >gateway.addr) & rgi->gateway.netmask) =3D=3D 0)
= {
return LR_MATCH;
= }
@@ -1581,17 +1470,16 @@
static in= line bool
is_on_link(const int is_local_route, const unsig= ned int flags, const struct route_gateway_info *rgi)
{
- return rgi &&= (is_local_route =3D=3D LR_MATCH || ((flags & ROUTE_REF_GW) && = (rgi->flags & RGI_ON_LINK)));
+ return rgi
+ && (is_local_route =3D=3D LR_MATCH+ || ((flags &am= p; ROUTE_REF_GW) && (rgi->flags & RGI_ON_LINK)));
= }
#endif

bool
-add_route(struct route_i= pv4 *r,
- cons= t struct tuntap *tt,
- = unsigned int flags,
- const struct route_gateway_info *rgi, /* may be NULL */
- const struct = env_set *es,
- = openvpn_net_ctx_t *ctx)
+add_route(struct route_ipv4 *r, const struct tuntap *tt, unsigned int = flags,
+ con= st struct route_gateway_info *rgi, /* may be NULL */
+ const struct env_set *es, openv= pn_net_ctx_t *ctx)
{
int status =3D 0= ;
int is_local_route;
@@ -1634,8 +1522= ,8 @@


status =3D R= TA_SUCCESS;
- int re= t =3D net_route_v4_add(ctx, &r->network, netmask_to_netbits2(r->n= etmask),
- = &r->gateway, iface, r->table_id, metric);
+ int ret =3D net_route= _v4_add(ctx, &r->network, netmask_to_netbits2(r->netmask), &r= ->gateway,
+ = iface, r->table_id, metric);
= if (ret =3D=3D -EEXIST)
{
= msg(D_ROUTE, "NOTE: Linux route add command failed because route exist= s");
@@ -1647,7 +1535,7 @@
st= atus =3D RTA_ERROR;
}

-#elif defined (TARGET_ANDROID)
+#elif defined(TARGET_ANDR= OID)
char out[128];

= if (rgi)
@@ -1661,15 +1549,11 @@
= bool ret =3D management_android_control(management, "ROUTE", out)= ;
status =3D ret ? RTA_SUCCESS : RTA_ERROR;
=
-#elif defined = (_WIN32)
+#elif defin= ed(_WIN32)
{
DWORD ai =3D TUN= _ADAPTER_INDEX_INVALID;
- argv_printf(&argv, "%s%s ADD %s MASK %s %s",=
- get_win_= sys_path(),
- = WIN_ROUTE_PATH_SUFFIX,
- network,
- netmask,
- gateway);
+ argv_printf(&argv, "%s%= s ADD %s MASK %s %s", get_win_sys_path(), WIN_ROUTE_PATH_SUFFIX,
+ netwo= rk, netmask, gateway);
if (r->flags & RT_ME= TRIC_DEFINED)
{
argv_= printf_cat(&argv, "METRIC %d", r->metric);
@@ -1695,8 +1579,8 @@

else if ((flags & ROUTE= _METHOD_MASK) =3D=3D ROUTE_METHOD_EXE)
{ netcmd_semaphore_lock();
- bool ret =3D openvpn_execve_check(&a= rgv, es, 0,
- = "ERROR: Windows route add command fa= iled");
+ = bool ret =3D
+ = openvpn_execve_check(&argv, es, 0, "ERROR: Windows r= oute add command failed");
status =3D ret= ? RTA_SUCCESS : RTA_ERROR;
netcmd_semaphore_r= elease();
method =3D "route.exe";
@@ -1709,8 +1593,8 @@
{ msg(D_ROUTE, "Route addition fallback to rout= e.exe");
netcmd_semaphore_lock();
- bool ret = =3D openvpn_execve_check(&argv, es, 0,
- "= ERROR: Windows route add command failed [adaptive]");
+ bool ret =3D openvpn= _execve_check(
+ = &argv, es, 0, "ERROR: Windows route add command fai= led [adaptive]");
status =3D ret ? RT= A_SUCCESS : RTA_ERROR;
netcmd_semaphore_re= lease();
method =3D "route.exe";=
@@ -1727,17 +1611,13 @@
}<= br> }

-#elif defined (TARGET_SOLARIS)
+#elif defined(TARGET_SOLARIS)

/* example: route add 192.0.2.32 -netmask 255.255.255.224 = somegateway */

- argv_printf(&argv, "%s add",
- ROUTE_PATH);
= + argv_printf(&argv, &qu= ot;%s add", ROUTE_PATH);

- argv_printf_cat(&argv, "%s -netmask = %s %s",
- = network,
- = netmask,
- gateway);
+ argv_printf_cat(&argv, "%s -netmask %s %s"= , network, netmask, gateway);

/* Sol= aris can only distinguish between "metric 0" =3D=3D "on-link= on the
* interface where the IP address given is con= figured" and "metric > 0"
@@ -1752,14 +16= 32,12 @@
}

argv= _msg(D_ROUTE, &argv);
- bool ret =3D openvpn_execve_check(&argv, es, 0,
- &= quot;ERROR: Solaris route add command failed");

+ bool ret =3D openvpn_execve_check(&am= p;argv, es, 0, "ERROR: Solaris route add command failed");=
status =3D ret ? RTA_SUCCESS : RTA_ERROR;
<= /span>
#elif defined(TARGET_FREEBSD)

= - argv_printf(&argv, "= ;%s add",
- = ROUTE_PATH);
+ argv_printf(&argv, "%s add", ROUTE_PATH);

#if 0
if (r->flags & RT_M= ETRIC_DEFINED)
@@ -1768,22 +1646,17 @@
= }
#endif

- argv_printf_cat(&argv, "-net %s %s %s&q= uot;,
- = network,
- = gateway,
- = netmask);
+ argv_printf_cat(&argv, "-net %s %s %s", network, = gateway, netmask);

/* FIXME -- add o= n-link support for FreeBSD */

argv_m= sg(D_ROUTE, &argv);
- bool ret =3D openvpn_execve_check(&argv, es, 0,
- &qu= ot;ERROR: FreeBSD route add command failed");
+ bool ret =3D openvpn_execve_check(&a= rgv, es, 0, "ERROR: FreeBSD route add command failed"); status =3D ret ? RTA_SUCCESS : RTA_ERROR;

#elif defined(TARGET_DRAGONFLY)

<= span style=3D"color: hsl(0, 100%, 40%);">- argv_printf(&argv, "= %s add",

- = ROUTE_PATH);
= + argv_printf(&argv, "%s add", ROUTE_PATH);

#if 0
if (r->flags & RT_ME= TRIC_DEFINED)
@@ -1792,22 +1665,17 @@
= }
#endif

- argv_printf_cat(&argv, "-net %s %s %s&qu= ot;,
- = network,
- = gateway,
- = netmask);
+ argv_printf_cat(&argv, "-net %s %s %s", network, g= ateway, netmask);

/* FIXME -- add on= -link support for Dragonfly */

argv_= msg(D_ROUTE, &argv);
- &q= uot;ERROR: DragonFly route add command failed");
+ bool ret =3D openvpn_execve_check(&am= p;argv, es, 0, "ERROR: DragonFly route add command failed");
status =3D ret ? RTA_SUCCESS : RTA_ERROR;
=
#elif defined(TARGET_DARWIN)
- argv_printf(&argv, &quo= t;%s add",
- = ROUTE_PATH);
-= argv_printf_cat(&argv, "-cloning -net %s -netmask %s -inte= rface %s",
- = network,
- netmask,
+ argv_printf_cat(&argv, "-cloning -net %s= -netmask %s -interface %s", network, netmask,
= rgi->iface);
}
= else
{
- argv_printf_cat(&argv, "-net %s %s %s",
- ne= twork,
- = gateway,
- = netmask);
+ argv_printf_cat(&argv, "-net %s %s %s", net= work, gateway, netmask);
}
argv_msg(D_ROUTE, &argv);
- bool ret =3D openvpn_execve_check(&argv, es, 0,=
- = "ERROR: OS X route add command failed");+ bool ret =3D openvpn_exec= ve_check(&argv, es, 0, "ERROR: OS X route add command failed"= );
status =3D ret ? RTA_SUCCESS : RTA_ERROR;
#elif defined(TARGET_OPENBSD) || defined(TARGET_N= ETBSD)

- ROUTE_PATH);
+ argv_printf(&argv, "%s ad= d", ROUTE_PATH);

#if 0
if (r->flags & RT_METRIC_DEFINED)

@@ -1850,= 47 +1711,36 @@
}
#endif

- argv_printf_c= at(&argv, "-net %s %s -netmask %s",
- network,
- gateway,
<= span style=3D"color: hsl(0, 100%, 40%);">- netmask);
+ argv_printf_cat(&am= p;argv, "-net %s %s -netmask %s", network, gateway, netmask);

/* FIXME -- add on-link support for Ope= nBSD/NetBSD */

argv_msg(D_ROUTE, &am= p;argv);
- bool ret = =3D openvpn_execve_check(&argv, es, 0,
- "ERROR: OpenB= SD/NetBSD route add command failed");
+ bool ret =3D openvpn_execve_check(&argv, es,= 0, "ERROR: OpenBSD/NetBSD route add command failed");
= status =3D ret ? RTA_SUCCESS : RTA_ERROR;

#elif defined(TARGET_AIX)

= {
int netbits =3D netmask_to_netbits2(r->net= mask);
- argv_pr= intf(&argv, "%s add -net %s/%d %s",
- ROUTE_PATH,
- network, netbits,= gateway);

+ a= rgv_printf(&argv, "%s add -net %s/%d %s", ROUTE_PATH, network= , netbits, gateway);
argv_msg(D_ROUTE, &argv);=
- bool ret =3D = openvpn_execve_check(&argv, es, 0,
- "ERROR: AIX r= oute add command failed");
+ bool ret =3D openvpn_execve_check(&argv, es, 0, &qu= ot;ERROR: AIX route add command failed");
sta= tus =3D ret ? RTA_SUCCESS : RTA_ERROR;
}

#elif defined(TARGET_HAIKU)
<= br> /* ex: route add /dev/net/ipro1000/0 0.0.0.0 gw 192.168.1.1 n= etmask 128.0.0.0 */
- = argv_printf(&argv, "%s add %s inet %s gw %s netmask %s",
- ROUTE_PA= TH,
- rg= i->iface,
- = network,
- = gateway,
- = netmask);
+ gateway, netmask);
= argv_msg(D_ROUTE, &argv);
- bool ret =3D openvpn_execve_check(&argv, es, 0,
<= span style=3D"color: hsl(0, 100%, 40%);">- = "ERROR: Haiku inet route add command failed");

+ bool ret =3D openvpn_execve_che= ck(&argv, es, 0, "ERROR: Haiku inet route add command failed"= );

status =3D ret ? RTA_SUCCESS : RTA_ERROR;
-#else /* if d= efined(TARGET_LINUX) */
- msg(M_FATAL, "Sorry, but I don't know how to do 'route&#= 39; commands on this operating system. Try putting your routes in a --rout= e-up script");
+= #else /* if defined(TARGET_LINUX) */
+ msg(M_FATAL,
+ "Sorry, but I don't know how to do 'rou= te' commands on this operating system. Try putting your routes in a --= route-up script");
#endif /* if defined(TARGET_LINUX)= */

done:
@@ -1912,7 +17= 62,7 @@


void-route_ipv6_clear_host_bits( str= uct route_ipv6 *r6 )
= +route_ipv6_clear_host_bits(struct route_ipv6 *r6)
{
/* clear host bit parts of route
* (n= eeded if routes are specified improperly, or if we need to
= @@ -1925,24 +1775,25 @@
{
if = (bits_to_clear >=3D 8)
{
- r6->network.s6_addr[byte--] = =3D 0; bits_to_clear -=3D 8;
+ r6->network.s6_addr[byte--] =3D 0;
+ bits_to_clear -=3D 8;
}
else
= {
- r6-= >network.s6_addr[byte--] &=3D (0xff << bits_to_clear); bits_to= _clear =3D 0;
+ = r6->network.s6_addr[byte--] &=3D (0xff << bits_to_clear)= ;
+ bits_t= o_clear =3D 0;
}
}
= }

bool
-add_route_ipv6(struct route_ipv6 *r6, const stru= ct tuntap *tt,
- = unsigned int flags, const struct env_set *es,
- openvpn_net_ctx_t *ctx)
+add_route_ipv6(struct ro= ute_ipv6 *r6, const struct tuntap *tt, unsigned int flags,
+ const struct env_set = *es, openvpn_net_ctx_t *ctx)
{
int st= atus =3D 0;
bool gateway_needed =3D false;
<= span>

- if (!(r6-&g= t;flags & RT_DEFINED) )
+ if (!(r6->flags & RT_DEFINED))
{
return true; /* no error */
}
@@ -1952,10 +1803,10 @@

#= ifndef _WIN32
const char *device =3D tt->actual_nam= e;
- if (r6->ifac= e !=3D NULL) /* vpn server special route */
+ if (r6->iface !=3D NULL) /* vpn= server special route */
{
de= vice =3D r6->iface;
= - if (!IN6_IS_ADDR_UNSPECIFIED(&r6->gateway) )
+ if (!IN6_IS_ADDR_UNSPECIFI= ED(&r6->gateway))

{
= gateway_needed =3D true;
}
@= @ -1963,11 +1814,10 @@
#endif

= route_ipv6_clear_host_bits(r6);
- const char *network =3D print_in6_addr( r6->net= work, 0, &gc);
- = const char *gateway =3D print_in6_addr( r6->gateway, 0, &gc);
+ const char *network = =3D print_in6_addr(r6->network, 0, &gc);
+ const char *gateway =3D print_in6_addr(r6-&= gt;gateway, 0, &gc);

-#if defined(TARGET_DARWIN) \
- || defined(TARGET_FREEBSD) || defined(T= ARGET_DRAGONFLY) \
+#if defined(TARGET_DARWIN) || defined(TARGET_FREEBSD) || defined(TARGET_D= RAGONFLY) \
|| defined(TARGET_OPENBSD) || defined(TARG= ET_NETBSD)

/* the BSD platforms cann= ot specify gateway and interface independently,
@@ -1975,22= +1825,21 @@
* we build a combined "$gateway%$in= terface" gateway string
*/
= if (r6->iface !=3D NULL && gateway_needed
- && IN6_IS_ADDR_LINKLOCAL(&a= mp;r6->gateway) ) /* fe80::...%intf */
+ && IN6_IS_ADDR_LINKLOCAL(&= r6->gateway)) /* fe80::...%intf */
{
- int len =3D strlen(gateway) = + 1 + strlen(r6->iface)+1;

- char *tmp =3D gc_malloc( len, true, &gc );
- snprintf( tmp, len, "= %s%%%s", gateway, r6->iface );

+ int len =3D strlen(gateway) + 1 + strlen(r6->= iface) + 1;
+ = char *tmp =3D gc_malloc(len, true, &gc);
+ snprintf(tmp, len, "%s%%%s", gat= eway, r6->iface);
gateway =3D tmp;
}

#endif

#ifnd= ef _WIN32
- msg(D_RO= UTE, "add_route_ipv6(%s/%d -> %s metric %d) dev %s",- network, r6->netbits= , gateway, r6->metric, device );
+ msg(D_ROUTE, "add_route_ipv6(%s/%d -> %s metric= %d) dev %s", network, r6->netbits, gateway,
+ r6->metric, device); #else
- msg(= D_ROUTE, "add_route_ipv6(%s/%d -> %s metric %d) IF %lu",
- network, r6->net= bits, gateway, r6->metric,
- r6->adapter_index ? r6->adapter_index : tt->adapte= r_index);
+ msg(D_= ROUTE, "add_route_ipv6(%s/%d -> %s metric %d) IF %lu", network= , r6->netbits, gateway,
+ r6->metric, r6->adapter_index ? r6->adapter_index := tt->adapter_index);
#endif
/*
@@ -2004,18 +1853,19 @@
= * interfaces. OTOH, on "tap" interface, we must always set th= e
* gateway unless the route is to be an on-link netw= ork
*/
- if (tt->type =3D=3D DEV_TYPE_TAP
- && !( (r6->flags & RT_METRI= C_DEFINED) && r6->metric =3D=3D 0 ) )
+ if (tt->type =3D=3D DEV_TYPE_TAP &&= amp; !((r6->flags & RT_METRIC_DEFINED) && r6->metric =3D= =3D 0))
{
gateway_needed =3D = true;
}

if (gat= eway_needed && IN6_IS_ADDR_UNSPECIFIED(&r6->gateway))=
{
- = msg(M_WARN, "ROUTE6 WARNING: " PACKAGE_NAME " needs a gat= eway "
+ = msg(M_WARN,
+ = "ROUTE6 WARNING: " PACKAGE_NAME " needs a gateway "=
"parameter for a --route-ipv6 option and= no default was set via "
"--ifconfi= g-ipv6 or --route-ipv6-gateway option. Not installing "
- "IPv6 route to %s/= %d.", network, r6->netbits);

+ "IPv6 route to %s/%d.",
+ network, r6->netb= its);

status =3D 0;
goto = done;
}
@@ -2028,8 +1878,7 @@ }

status =3D RTA_SUCCES= S;
- int ret =3D net= _route_v6_add(ctx, &r6->network, r6->netbits,
- gateway_ne= eded ? &r6->gateway : NULL,
+ int ret =3D net_route_v6_add(ctx, &r6->network, r= 6->netbits, gateway_needed ? &r6->gateway : NULL,
device, r6->table_id, metric);
if (ret =3D=3D -EEXIST)
{
@@ -2042,14 +1891,14 @@

status =3D RTA_ERROR;
}

-#elif defined (TARGET_ANDROID)
+#elif defined(TARGET_ANDROID)
= char out[64];

snprintf(out, sizeo= f(out), "%s/%d %s", network, r6->netbits, device);
<= span>

status =3D management_android_control(managemen= t, "ROUTE6", out);

-#elif defined (_WIN32)
+#elif defined(_WIN32)
<= br> if (tt->options.msg_channel)
{=
@@ -2059,7 +1908,7 @@
{
= status =3D route_ipv6_ipapi(true, r6, tt);
}
-#elif defined (TARGET_SOLA= RIS)
+#elif defined(T= ARGET_SOLARIS)

/* example: route add= -inet6 2001:db8::/32 somegateway 0 */

@@= -2072,11 +1921,7 @@
* use the GW addresses - it seem= s to still work for fe80:: addresses,
* however this = is done internally. NUD maybe?)
*/
- argv_printf(&argv, "%s add= -inet6 %s/%d %s",
- ROUTE_PATH,
- network,
- r6->netbits,
- gateway );
+ argv_printf(&argv, "%s add -inet6 = %s/%d %s", ROUTE_PATH, network, r6->netbits, gateway);

/* on tun (not tap), not "elsewhere"? = -> metric 0 */
if (tt->type =3D=3D DEV_TYPE_TUN = && !r6->iface)
@@ -2085,16 +1930,12 @@ }

argv_msg(D_ROUTE, &= ;argv);
- bool ret = =3D openvpn_execve_check(&argv, es, 0,
- "ERROR: Solar= is route add -inet6 command failed");
+ bool ret =3D openvpn_execve_check(&argv, es,= 0, "ERROR: Solaris route add -inet6 command failed");
= status =3D ret ? RTA_SUCCESS : RTA_ERROR;

#elif defined(TARGET_FREEBSD) || defined(TARGET_DRAGONFLY)

- arg= v_printf(&argv, "%s add -inet6 %s/%d",
- ROUTE_PATH,
- network,

- r6->netbits);
+ argv_printf(&= argv, "%s add -inet6 %s/%d", ROUTE_PATH, network, r6->netbits)= ;

if (gateway_needed)
{

@@ -2106,15 +1947,12 @@
}

argv_msg(D_ROUTE, &argv);- bool ret =3D openvpn_execve= _check(&argv, es, 0,
+ bool ret =3D openvpn_execve_check(&argv, es, 0, "ERROR: *BSD= route add -inet6 command failed");
status =3D re= t ? RTA_SUCCESS : RTA_ERROR;

#elif defin= ed(TARGET_DARWIN)

- argv_printf(&argv, "%s add -inet6 %s -prefixlen = %d",
- = ROUTE_PATH,
- = network, r6->netbits );
+ argv_printf(&argv, "%s add -inet6 %s -prefixl= en %d", ROUTE_PATH, network, r6->netbits);
=
if (gateway_needed)
{
@= @ -2126,58 +1964,45 @@
}

<= span> argv_msg(D_ROUTE, &argv);

- bool ret =3D openvpn_execve_check(&argv, es, 0,
- = "ERROR: MacOS X route add -inet6 command failed");
+ bool ret =3D open= vpn_execve_check(&argv, es, 0, "ERROR: MacOS X route add -inet6 co= mmand failed");
status =3D ret ? RTA_SUCCESS : RT= A_ERROR;

#elif defined(TARGET_OPENBSD)

- a= rgv_printf(&argv, "%s add -inet6 %s -prefixlen %d %s",=
- ROUTE_PATH,<= /span>
- networ= k, r6->netbits, gateway );
+ argv_printf(&argv, "%s add -inet6 %s -prefixlen %d %= s", ROUTE_PATH, network, r6->netbits,
+ gateway);

argv_msg(D_ROUTE, &argv);
- bool ret =3D openvpn_execve_check(&argv, es= , 0,
- = "ERROR: OpenBSD route add -inet6 command failed&quo= t;);
+ bool ret = =3D openvpn_execve_check(&argv, es, 0, "ERROR: OpenBSD route add -= inet6 command failed");
status =3D ret ? RTA_SUCC= ESS : RTA_ERROR;

#elif defined(TARGET_NE= TBSD)

- argv_printf(&argv, "%s add -inet6 %s/%d %s",
= - ROUTE_PATH,
- network, r= 6->netbits, gateway );
+ argv_printf(&argv, "%s add -inet6 %s/%d %s", ROUTE_= PATH, network, r6->netbits, gateway);

= argv_msg(D_ROUTE, &argv);
- bool ret =3D openvpn_execve_check(&argv, es, 0,=
- = "ERROR: NetBSD route add -inet6 command failed");<= br>+ bool ret =3D openvpn_ex= ecve_check(&argv, es, 0, "ERROR: NetBSD route add -inet6 command f= ailed");
status =3D ret ? RTA_SUCCESS : RTA_ERROR= ;

#elif defined(TARGET_AIX)

- argv_printf(= &argv, "%s add -inet6 %s/%d %s",
- ROUTE_PATH,
- network, r6->netbits, ga= teway);
+ argv_pri= ntf(&argv, "%s add -inet6 %s/%d %s", ROUTE_PATH, network, r6-= >netbits, gateway);
argv_msg(D_ROUTE, &argv);
- bool ret =3D openvp= n_execve_check(&argv, es, 0,
- "ERROR: AIX route add c= ommand failed");
+ bool ret =3D openvpn_execve_check(&argv, es, 0, "ERROR: AIX = route add command failed");
status =3D ret ? RTA_= SUCCESS : RTA_ERROR;

#elif defined(TARGE= T_HAIKU)

/* ex: route add /dev/net/i= pro1000/0 inet6 :: gw beef::cafe prefixlen 64 */
- argv_printf(&argv, "%s add %s inet6= %s gw %s prefixlen %d",
- ROUTE_PATH,
- r6->iface,
- network,
- gateway,
- r6->netbits);
+ argv_printf(&argv, "%= s add %s inet6 %s gw %s prefixlen %d", ROUTE_PATH, r6->iface, netwo= rk,

+ = gateway, r6->netbits);
argv_msg(D_ROUTE, &argv)= ;
- bool ret =3D ope= nvpn_execve_check(&argv, es, 0,
- "ERROR: Haiku inet6 = route add command failed");
+ bool ret =3D openvpn_execve_check(&argv, es, 0, "= ERROR: Haiku inet6 route add command failed");
st= atus =3D ret ? RTA_SUCCESS : RTA_ERROR;

= #else /* if defined(TARGET_LINUX) */
- msg(M_FATAL, "Sorry, but I don't know how to d= o 'route ipv6' commands on this operating system. Try putting your= routes in a --route-up script");
+ msg(M_FATAL,
+ "Sorry, but I don't know how to do 'ro= ute ipv6' commands on this operating system. Try putting your routes i= n a --route-up script");
#endif /* if defined(TARGET_= LINUX) */

done:
@@ -2198= ,12 +2023,8 @@
}

static= void
-delete_route(str= uct route_ipv4 *r,
- = const struct tuntap *tt,
- unsigned int flags,
- const struct route_gateway_info *rgi,<= /span>
- const str= uct env_set *es,
- = openvpn_net_ctx_t *ctx)
+delete_route(struct route_ipv4 *r, const struct tuntap *tt, uns= igned int flags,
+ = const struct route_gateway_info *rgi, const struct env_set *es, o= penvpn_net_ctx_t *ctx)
{
#if !defined(TAR= GET_LINUX)
const char *network;
@@ -22= 13,12 +2034,12 @@
#if !defined(TARGET_ANDROID)
<= span> const char *gateway;

#endif
-#else /* if !defined(TARGET_LINUX) */
+#else /* if !defined(TA= RGET_LINUX) */
int metric;
#endif
int is_local_route;

- if ((r->flags & (RT_DEFINED|RT= _ADDED)) !=3D (RT_DEFINED|RT_ADDED))
+ if ((r->flags & (RT_DEFINED | RT_ADDED)) !=3D (= RT_DEFINED | RT_ADDED))
{
ret= urn;
}
@@ -2249,19 +2070,16 @@<= br> metric =3D r->metric;
}
- if (net_r= oute_v4_del(ctx, &r->network, netmask_to_netbits2(r->netmask),
- = &r->gateway, NULL, r->table_id, metric) < 0)
+ if (net_route_v4_del(ctx, &r= ->network, netmask_to_netbits2(r->netmask), &r->gateway, NULL,=
+ = r->table_id, metric)
+ < 0)
{
m= sg(M_WARN, "ERROR: Linux route delete command failed"); }
-#elif de= fined (_WIN32)
+#elif= defined(_WIN32)

- argv_printf(&argv, "%s%s DELETE %s MASK %s %s&quo= t;,
- ge= t_win_sys_path(),
- = WIN_ROUTE_PATH_SUFFIX,
- network,
- netmask,
- gateway);
+ argv_printf(&argv, "%s%s DELETE %s MA= SK %s %s", get_win_sys_path(), WIN_ROUTE_PATH_SUFFIX,
+ network, netmask, ga= teway);

argv_msg(D_ROUTE, &argv)= ;

@@ -2289,7 +2107,8 @@
= {
msg(D_ROUTE, "Route deletion fa= llback to route.exe");
netcmd_semaphore_l= ock();
- ope= nvpn_execve_check(&argv, es, 0, "ERROR: Windows route delete comma= nd failed [adaptive]");
+ openvpn_execve_check(&argv, es, 0,
+ &q= uot;ERROR: Windows route delete command failed [adaptive]");
netcmd_semaphore_release();
}<= /span>
}
@@ -2298,35 +2117,23 @@
ASSERT(0);

}

= -#elif defined (TARGET_SOLARIS)
+#elif defined(TARGET_= SOLARIS)

- argv_printf(&argv, "%s delete %s -netmask %s %s",
- ROUTE_PA= TH,
- ne= twork,
- = netmask,
- = gateway);
+ ar= gv_printf(&argv, "%s delete %s -netmask %s %s", ROUTE_PATH, n= etwork, netmask, gateway);

argv_msg(= D_ROUTE, &argv);
openvpn_execve_check(&argv, e= s, 0, "ERROR: Solaris route delete command failed");

#elif defined(TARGET_FREEBSD)

- argv_printf(&argv,= "%s delete -net %s %s %s",
- ROUTE_PATH,
- network,
- gateway,
- netmask);
+ argv_printf(&argv, "%s delet= e -net %s %s %s", ROUTE_PATH, network, gateway, netmask);

argv_msg(D_ROUTE, &argv);
= openvpn_execve_check(&argv, es, 0, "ERROR: FreeBSD route delete= command failed");

#elif defined(TA= RGET_DRAGONFLY)

- argv_printf(&argv, "%s delete -net %s %s %s",=
- ROUTE= _PATH,
- = network,
- = gateway,
- = netmask);
+ = argv_printf(&argv, "%s delete -net %s %s %s", ROUTE_PATH, ne= twork, gateway, netmask);

argv_msg(D= _ROUTE, &argv);
openvpn_execve_check(&argv, es= , 0, "ERROR: DragonFly route delete command failed");
<= span>@@ -2335,19 +2142,12 @@


if (is_= on_link(is_local_route, flags, rgi))
{
- argv_printf(&argv, "= %s delete -cloning -net %s -netmask %s -interface %s",

- ROUTE_PATH,
- network= ,
- = netmask,
- = rgi->iface);
+ network, netmask, rgi->iface);
}
else
{<= br>- argv_printf(&argv= , "%s delete -net %s %s %s",
- ROUTE_PATH,
- network,
- gateway,
- netmask);
+ argv_printf(&= ;argv, "%s delete -net %s %s %s", ROUTE_PATH, network, gateway, n= etmask);
}

argv= _msg(D_ROUTE, &argv);
@@ -2355,26 +2155,20 @@
#elif defined(TARGET_OPENBSD) || defined(TARGET_N= ETBSD)

- ROUTE= _PATH,
- = network,
- = gateway,
- = netmask);
+ = argv_printf(&argv, "%s delete -net %s %s -netmask %s", ROUTE= _PATH, network, gateway, netmask);

a= rgv_msg(D_ROUTE, &argv);
openvpn_execve_check(&= ;argv, es, 0, "ERROR: OpenBSD/NetBSD route delete command failed"= );

#elif defined(TARGET_ANDROID)<= br> msg(D_ROUTE_DEBUG, "Deleting routes on Android is not po= ssible/not "
- = "needed. The VpnService API allows routes to be set "<= br>- "on connect only= and will clean up automatically.");
+ "needed. The VpnService A= PI allows routes to be set "
+ "on connect only and will clean u= p automatically.");
#elif defined(TARGET_AIX)<= br>
{
int netbits =3D = netmask_to_netbits2(r->netmask);
- argv_printf(&argv, "%s delete -net %s/%d %s&= quot;,
- = ROUTE_PATH,
- = network, netbits, gateway);
+ argv_printf(&argv, "%s delete -net = %s/%d %s", ROUTE_PATH, network, netbits, gateway);
= argv_msg(D_ROUTE, &argv);
openvpn_execve= _check(&argv, es, 0, "ERROR: AIX route delete command failed"= );
}
@@ -2382,17 +2176,14 @@ #elif defined(TARGET_HAIKU)

= /* ex: route delete /dev/net/ipro1000/0 inet 192.168.0.0 gw 192.168.1.1 net= mask 255.255.0.0 */
- = argv_printf(&argv, "%s delete %s inet %s gw %s netmask %s",=
- ROUTE= _PATH,
- = rgi->iface,
- = network,
- = gateway,
-= netmask);
+ argv_printf(&argv, "%s delete %s inet %s gw %s netmask %= s", ROUTE_PATH, rgi->iface, network,
+ gateway, netmask);
argv_msg(D_ROUTE, &argv);

openvpn_execve_che= ck(&argv, es, 0, "ERROR: Haiku inet route delete command failed&qu= ot;);

#else /* if defined(TARGET_LINUX)= */
- msg(M_FATAL, &= quot;Sorry, but I don't know how to do 'route' commands on this= operating system. Try putting your routes in a --route-up script");<= /span>
+ msg(M_FATAL,
+ "Sorry, bu= t I don't know how to do 'route' commands on this operating sys= tem. Try putting your routes in a --route-up script");
#endif /* if defined(TARGET_LINUX) */


= done:
@@ -2404,13 +2195,12 @@
}
void
-delete_route_ipv6(const struct route_ipv6 *r6, const struct tuntap= *tt,
- = const struct env_set *es,
+delete_route_ipv6(const struct route_ipv6 *r6, const struct tuntap = *tt, const struct env_set *es,
openvpn_n= et_ctx_t *ctx)
{
const char *network;=

- = if ((r6->flags & (RT_DEFINED|RT_ADDED)) !=3D (RT_DEFINED|RT_ADDED))=
+ if ((r6->fla= gs & (RT_DEFINED | RT_ADDED)) !=3D (RT_DEFINED | RT_ADDED))
<= span> {

return;
}<= br>@@ -2422,7 +2212,7 @@
#if !defined(TARGET_SOLARIS= )
bool gateway_needed =3D false;
= const char *device =3D tt->actual_name;
- if (r6->iface !=3D NULL) /* vpn se= rver special route */
+ if (r6->iface !=3D NULL) /* vpn server special route */
= {
device =3D r6->iface;
gateway_needed =3D true;

@@ -2431,8 +2221,7 @@=
/* if we used a gateway on "add route", we = also need to specify it on
* delete, otherwise some O= Ses will refuse to delete the route
*/
- if (tt->type =3D=3D DEV_TYPE_= TAP

- &&= !( (r6->flags & RT_METRIC_DEFINED) && r6->metric =3D=3D = 0 ) )
+ if (tt->= ;type =3D=3D DEV_TYPE_TAP && !((r6->flags & RT_METRIC_DEFINE= D) && r6->metric =3D=3D 0))
{
gateway_needed =3D true;

}
@@ -2442,13 +2231,12 @@

struct gc_arena gc =3D gc_new= ();
struct argv argv =3D argv_new();
=
- network =3D print= _in6_addr( r6->network, 0, &gc);
+ network =3D print_in6_addr(r6->network, 0, &= gc);
#if !defined(TARGET_LINUX) && !defined(_WIN32= )
- gateway =3D prin= t_in6_addr( r6->gateway, 0, &gc);
+ gateway =3D print_in6_addr(r6->gateway, 0, &= ;gc);
#endif

-#if defined(TARGET_DARWIN) \
- || defined(TARGET_FREEBSD) || defin= ed(TARGET_DRAGONFLY) \
+#if defined(TARGET_DARWIN) || defined(TARGET_FREEBSD) || defined(TARG= ET_DRAGONFLY) \
|| defined(TARGET_OPENBSD) || defined(= TARGET_NETBSD)

/* the BSD platforms = cannot specify gateway and interface independently,
@@ -245= 6,16 +2244,16 @@
* we build a combined "$gateway= %$interface" gateway string
*/
= if (r6->iface !=3D NULL && gateway_needed
- && IN6_IS_ADDR_LINKLOCAL= (&r6->gateway) ) /* fe80::...%intf */
+ && IN6_IS_ADDR_LINKLOCAL(= &r6->gateway)) /* fe80::...%intf */
{- int len =3D strlen(gate= way) + 1 + strlen(r6->iface)+1;
- char *tmp =3D gc_malloc( len, true, &gc );<= br>- snprintf( tmp, len, &= quot;%s%%%s", gateway, r6->iface );
+ int len =3D strlen(gateway) + 1 + strlen(r6= ->iface) + 1;
+ = char *tmp =3D gc_malloc(len, true, &gc);
+ snprintf(tmp, len, "%s%%%s"= , gateway, r6->iface);
gateway =3D tmp;<= br> }
#endif

- msg(D_ROUTE, "delete_route_ipv= 6(%s/%d)", network, r6->netbits );
+ msg(D_ROUTE, "delete_route_ipv6(%s/%d)"= ;, network, r6->netbits);

#if defined= (TARGET_LINUX)
int metric =3D -1;
@@ -= 2474,14 +2262,14 @@
metric =3D r6->metric;
}

- if (net_route_v6_del(ctx, &r6->network, r6->ne= tbits,
- = gateway_needed ? &r6->gateway : NULL, device, r6->table= _id,
- = metric) < 0)
+ if (net_route_v6_del(ctx, &r6->network, r6->netbits, gate= way_needed ? &r6->gateway : NULL,
+ device, r6->table_id, metr= ic)
+ < 0)<= /span>
{
msg(M_WARN, "ERROR: Li= nux route v6 delete command failed");
}
-#elif defined= (_WIN32)
+#elif defi= ned(_WIN32)

if (tt->options.msg_c= hannel)
{
@@ -2491,25 +2279,18 @@
{
route_ipv6_ipapi(false, r6, tt)= ;
}
+#elif defined(TARGET_SOLARIS)

/* example: route delete -inet6 2001:db8::/32 somegateway */
=

- argv_p= rintf(&argv, "%s delete -inet6 %s/%d %s",
- ROUTE_PATH,
- network,

= - r6->netbits,<= /span>
- gatewa= y );
+ argv_printf= (&argv, "%s delete -inet6 %s/%d %s", ROUTE_PATH, network, r6-= >netbits, gateway);

argv_msg(D_RO= UTE, &argv);
openvpn_execve_check(&argv, es, 0= , "ERROR: Solaris route delete -inet6 command failed");
#elif defined(TARGET_FREEBSD) || defined(TARGET_D= RAGONFLY)

- argv_printf(&argv, "%s delete -inet6 %s/%d",=
- ROUTE_PATH,<= /span>
- networ= k,
- r6-= >netbits );
+ a= rgv_printf(&argv, "%s delete -inet6 %s/%d", ROUTE_PATH, netwo= rk, r6->netbits);

if (gateway_nee= ded)
{
@@ -2525,9 +2306,7 @@
#elif defined(TARGET_DARWIN)

- argv_printf(&arg= v, "%s delete -inet6 %s -prefixlen %d",
- ROUTE_PATH,
- network, r6->netbits )= ;
+ argv_printf(&a= mp;argv, "%s delete -inet6 %s -prefixlen %d", ROUTE_PATH, network= , r6->netbits);

if (gateway_neede= d)
{
@@ -2543,48 +2322,40 @@
#elif defined(TARGET_OPENBSD)

- argv_printf(&ar= gv, "%s delete -inet6 %s -prefixlen %d %s",
- ROUTE_PATH,
- network, r6->netbi= ts, gateway );

+ a= rgv_printf(&argv, "%s delete -inet6 %s -prefixlen %d %s", ROU= TE_PATH, network, r6->netbits,
+ gateway);

= argv_msg(D_ROUTE, &argv);
openvpn_execve_check= (&argv, es, 0, "ERROR: OpenBSD route delete -inet6 command failed&= quot;);

#elif defined(TARGET_NETBSD)

- arg= v_printf(&argv, "%s delete -inet6 %s/%d %s",
- ROUTE_PATH,
= - network, r6->= netbits, gateway );
+= argv_printf(&argv, "%s delete -inet6 %s/%d %s", ROUTE_PAT= H, network, r6->netbits, gateway);

= argv_msg(D_ROUTE, &argv);
openvpn_execve_check(&= amp;argv, es, 0, "ERROR: NetBSD route delete -inet6 command failed&quo= t;);

#elif defined(TARGET_AIX)
- argv_prin= tf(&argv, "%s delete -inet6 %s/%d %s",
- ROUTE_PATH,
- network, r6->netbi= ts, gateway);

+ ar= gv_printf(&argv, "%s delete -inet6 %s/%d %s", ROUTE_PATH, net= work, r6->netbits, gateway);
argv_msg(D_ROUTE, &= ;argv);
openvpn_execve_check(&argv, es, 0, "E= RROR: AIX route add command failed");

#elif defined(TARGET_ANDROID)

msg(D_ROUTE_DEBUG, &q= uot;Deleting routes on Android is not possible/not "
- "needed. The VpnService AP= I allows routes to be set "
- "on connect only and will clean up automatically.&q= uot;);
+ = "needed. The VpnService API allows routes to be set "
+ = "on connect only and will clean up automatically.");
= #elif defined(TARGET_HAIKU)

/= * ex: route delete /dev/net/ipro1000/0 inet6 :: gw beef::cafe prefixlen 64 = */
- argv_printf(&am= p;argv, "%s delete %s inet6 %s gw %s prefixlen %d",
- ROUTE_PATH,
<= br>- r6->iface,=
- netwo= rk,
- ga= teway,
- = r6->netbits);
+ = argv_printf(&argv, "%s delete %s inet6 %s gw %s prefixlen %d&quo= t;, ROUTE_PATH, r6->iface, network,
+ gateway, r6->netbits);
argv_msg(D_ROUTE, &argv);

openvpn_execve_ch= eck(&argv, es, 0, "ERROR: Haiku inet6 route delete command failed&= quot;);

#else /* if defined(TARGET_LINU= X) */
- msg(M_FATAL,= "Sorry, but I don't know how to do 'route ipv6' commands = on this operating system. Try putting your routes in a --route-down script= ");
+ msg(M_F= ATAL,
+ "= Sorry, but I don't know how to do 'route ipv6' commands on this= operating system. Try putting your routes in a --route-down script")= ;
#endif /* if defined(TARGET_LINUX) */
<= /span>
argv_free(&argv);
@@ -2610,13 +238= 1,12 @@
status =3D GetIpForwardTable(NULL, &size, = TRUE);
if (status =3D=3D ERROR_INSUFFICIENT_BUFFER)
{
- = rt =3D (PMIB_IPFORWARDTABLE) gc_malloc(size, false, gc);
<= span style=3D"color: hsl(120, 100%, 40%);">+ rt =3D (PMIB_IPFORWARDT= ABLE)gc_malloc(size, false, gc);

status =3D GetIpF= orwardTable(rt, &size, TRUE);
if (status !=3D = NO_ERROR)
{
msg(D_ROU= TE, "NOTE: GetIpForwardTable returned error: %s (code=3D%u)",
- strerror_= win32(status, gc),
- = (unsigned int)status);
+ strerror_win32(status, gc), (unsigned int)s= tatus);
rt =3D NULL;
= }
}
@@ -2624,9 +2394,7 @@
}


static int
-test_route(const IP_ADAPTER_INFO *adapters,=
- const in_a= ddr_t gateway,
- = DWORD *index)
+te= st_route(const IP_ADAPTER_INFO *adapters, const in_addr_t gateway, DWORD *i= ndex)
{
int count =3D 0;
DWORD i =3D adapter_index_of_ip(adapters, gateway, &count, NUL= L);

@@ -2638,11 +2406,7 @@
}

static void
-test_route_helper(bool *ret,
- int *count,
- int *good,
- int *ambig,
<= span style=3D"color: hsl(0, 100%, 40%);">- const IP_ADAPTE= R_INFO *adapters,

+te= st_route_helper(bool *ret, int *count, int *good, int *ambig, const IP_ADAP= TER_INFO *adapters,
const in_addr_t gate= way)
{
int c;
@@ -270= 2,13 +2466,8 @@
}
}
- msg(D_ROU= TE, "TEST ROUTES: %d/%d succeeded len=3D%d ret=3D%d a=3D%d u/d=3D%s&qu= ot;,
- good,
- count,
= - len,
- (int)ret,
- ambig,
- adapter_up ? "up" : "down&q= uot;);
+ msg(D_ROU= TE, "TEST ROUTES: %d/%d succeeded len=3D%d ret=3D%d a=3D%d u/d=3D%s&qu= ot;, good, count, len,
- dmsg(D= _ROUTE_DEBUG, "GDGR: route[%lu] %s/%s i=3D%d m=3D%d",
<= span style=3D"color: hsl(0, 100%, 40%);">- i,

- print_in_addr_t((i= n_addr_t) net, 0, &gc),

- print_in_addr_t((in_addr_t) mask, 0, &gc),
- (int)index= ,
- (in= t)metric);
+ = dmsg(D_ROUTE_DEBUG, "GDGR: route[%lu] %s/%s i=3D%d m=3D%d", i,=
+ pr= int_in_addr_t((in_addr_t)net, 0, &gc), print_in_addr_t((in_addr_t)mask,= 0, &gc),
+ = (int)index, (int)metric);

= if (!net && !mask && metric < lowest_metric)
{
@@ -2778,8 +2534,7 @@ if (status !=3D NO_ERROR)
{
msg(D_ROUTE, "NOTE: GetBestInterfaceEx returned error: %s = (code=3D%u)",

- = strerror_win32(status, gc),
- (unsigned int)status);
+ strerror_win32(status, gc), (unsi= gned int)status);
goto done;
= }

@@ -2790,13 +2545,11 @@
CLEAR(luid);

SOCKADDR_INET best_src;
<= span> CLEAR(best_src);

- status =3D GetBestRoute2(&luid, best_if_index, NULL,- dest= , 0, best_route, &best_src);
+ status =3D GetBestRoute2(&luid, best_if_index, NULL, d= est, 0, best_route, &best_src);
if (status !=3D NO= _ERROR)
{
msg(D_ROUTE, "= NOTE: GetIpForwardEntry2 returned error: %s (code=3D%u)",
- strerror_win32(status,= gc),

- (uns= igned int)status);
+ = strerror_win32(status, gc), (unsigned int)status);
goto done;

}

<= span>@@ -2887,13 +2640,10 @@

else if (count > 1)
{
msg(M_WARN, "Warning: ro= ute gateway is ambiguous: %s (%d matches)",
- print_in_addr_t(r->gateway, 0, &a= mp;gc),
- co= unt);
+ pr= int_in_addr_t(r->gateway, 0, &gc), count);
}

- dm= sg(D_ROUTE_DEBUG, "DEBUG: route find if: on_tun=3D%d count=3D%d index= =3D%d",
- = on_tun,
- count= ,
+ dmsg(D_ROUTE_D= EBUG, "DEBUG: route find if: on_tun=3D%d count=3D%d index=3D%d", = on_tun, count,
(int)ret);

gc_free(&gc);
@@ -2906,8 +2656,8 @@
* https://msdn.microsoft.com/en-us/library/windows/desktop/a= a814411(v=3Dvs.85).aspx
*/
void-get_default_gateway_ipv6(struc= t route_ipv6_gateway_info *rgi6,
- const struct in6_addr *dest, openvpn_ne= t_ctx_t *ctx)
+get_de= fault_gateway_ipv6(struct route_ipv6_gateway_info *rgi6, const struct in6_a= ddr *dest,
+ = openvpn_net_ctx_t *ctx)
{
= struct gc_arena gc =3D gc_new();
CLEAR(*rgi6);
@@ -2929,23 +2679,19 @@
goto done;
}

- msg( D_ROUTE, "GDG6: II=3D%lu DP=3D%s/%d NH=3D%s= ",
- BestR= oute.InterfaceIndex,
- = print_in6_addr( BestRoute.DestinationPrefix.Prefix.Ipv6.sin6_addr, = 0, &gc),
- = BestRoute.DestinationPrefix.PrefixLength,
- print_in6_addr( BestRoute.NextHop.Ipv6.sin6_ad= dr, 0, &gc) );
- = msg( D_ROUTE, "GDG6: Metric=3D%d, Loopback=3D%d, AA=3D%d, I=3D%d"= ;,
- (int) Best= Route.Metric,
- = (int) BestRoute.Loopback,
- (int) BestRoute.AutoconfigureAddress,
- (int) BestRoute.Immortal );=
+ msg(D_ROUTE, "GDG= 6: II=3D%lu DP=3D%s/%d NH=3D%s", BestRoute.InterfaceIndex,
<= span style=3D"color: hsl(120, 100%, 40%);">+ print_in6_addr(BestRout= e.DestinationPrefix.Prefix.Ipv6.sin6_addr, 0, &gc),

+ BestRoute.DestinationPrefix.Pre= fixLength,
+ p= rint_in6_addr(BestRoute.NextHop.Ipv6.sin6_addr, 0, &gc));
+ msg(D_ROUTE, "GDG6: Metr= ic=3D%d, Loopback=3D%d, AA=3D%d, I=3D%d", (int)BestRoute.Metric,
+ (int)BestRoute.Lo= opback, (int)BestRoute.AutoconfigureAddress, (int)BestRoute.Immortal);

rgi6->gateway.addr_ipv6 =3D BestRoute= .NextHop.Ipv6.sin6_addr;
+ rgi6->adapter_index =3D = BestRoute.InterfaceIndex;
rgi6->flags |=3D RGI_ADDR= _DEFINED | RGI_IFACE_DEFINED;

/* on-= link is signalled by receiving an empty (::) NextHop */
- if (IN6_IS_ADDR_UNSPECIFIED(&Best= Route.NextHop.Ipv6.sin6_addr) )
+ if (IN6_IS_ADDR_UNSPECIFIED(&BestRoute.NextHop.Ipv6.sin= 6_addr))
{
rgi6->flags |= =3D RGI_ON_LINK;
}
@@ -2961,7 +2707,9 = @@
struct gc_arena gc =3D gc_new();
= int ret =3D RTA_ERROR;
DWORD status;
- const DWORD if_index =3D (adapte= r_index =3D=3D TUN_ADAPTER_INDEX_INVALID) ? windows_route_find_if_index(r, = tt) : adapter_index;

= + const DWORD if_index =3D (adapter_index =3D=3D TUN_ADAPTER_INDEX_INVAL= ID)
+ = ? windows_route_find_if_index(r, tt)
+ : adapter_= index;

if (if_index !=3D TUN_ADAPTER= _INDEX_INVALID)
{
@@ -2972,7 +2720,7 @= @
fr.dwForwardPolicy =3D 0;
= fr.dwForwardNextHop =3D htonl(r->gateway);
f= r.dwForwardIfIndex =3D if_index;
- fr.dwForwardType =3D 4; /* the next hop is not the final= dest */
+ fr.= dwForwardType =3D 4; /* the next hop is not the final dest */
fr.dwForwardProto =3D 3; /* PROTO_IP_NETMGMT */

fr.dwForwardAge =3D 0;

fr.dwForwardNext= HopAS =3D 0;
@@ -2985,8 +2733,7 @@
= if ((r->network & r->netmask) !=3D r->network)
{

msg(M_WARN, "Warning: addres= s %s is not a network address in relation to netmask %s",
- print_in_addr_t(r-= >network, 0, &gc),

- print_in_addr_t(r->netmask, 0, &gc));
= + print_in_addr_= t(r->network, 0, &gc), print_in_addr_t(r->netmask, 0, &gc));<= /span>
}

statu= s =3D CreateIpForwardEntry(&fr);
@@ -3002,20 +2749,22 @= @
else
{
= /* failed, try increasing the metric to work around Vista issu= e */
- const= unsigned int forward_metric_limit =3D 2048; /* iteratively retry higher me= trics up to this limit */
+ const unsigned int forward_metric_limit =3D
+ 2048; /* iterativ= ely retry higher metrics up to this limit */


for (; fr.dwForwardMetric1 <=3D forward_metric_limit; += +fr.dwForwardMetric1)

{
- /* try a different forward = type=3D3 ("the next hop is the final dest") in addition to 4.
+ /* try = a different forward type=3D3 ("the next hop is the final dest") i= n addition
+ = * to 4.
* --redirect-gateway over= RRAS seems to need this. */
for (fr.dwFor= wardType =3D 4; fr.dwForwardType >=3D 3; --fr.dwForwardType)
<= span> {

status =3D Cre= ateIpForwardEntry(&fr);
if (status= =3D=3D NO_ERROR)
{
- msg(D_ROUTE, &qu= ot;ROUTE: CreateIpForwardEntry succeeded with dwForwardMetric1=3D%u and dwF= orwardType=3D%u",
= - (unsigned int)fr.dwForwardMetric1,
<= span style=3D"color: hsl(0, 100%, 40%);">- (unsi= gned int)fr.dwForwardType);

+ msg(D_ROUTE,
+ "ROUTE: CreateIpF= orwardEntry succeeded with dwForwardMetric1=3D%u and dwForwardType=3D%u&quo= t;,
+ = (unsigned int)fr.dwForwardMetric1, (unsigned int)fr.dwForwardTy= pe);
ret =3D RTA_SUCCESS; goto doublebreak;
= }
@@ -3035,9 +2784,10 @@
= }
else
= {
- = msg(M_WARN, "ERROR: route addition failed using CreateIpForw= ardEntry: "
- = "%s [status=3D%u if_index=3D%u]", strerror_win= 32(status, &gc),
- = (unsigned int)status, (unsigned int)if_index);
+ msg(M= _WARN,
+ = "ERROR: route addition failed using CreateIpForwardEntry: &= quot;
+ = "%s [status=3D%u if_index=3D%u]",
+ strerror_win32(st= atus, &gc), (unsigned int)status, (unsigned int)if_index);
}

}
= }
@@ -3125,18 +2875,13 @@
retu= rn RTA_ERROR;
}

- route_message_t msg =3D {
- .header =3D {

- (add ? msg_add_route := msg_del_route),

- = sizeof(route_message_t),
- 0
- },
- .= family =3D AF_INET,
- = .prefix.ipv4.s_addr =3D htonl(r->network),
- .gateway.ipv4.s_addr =3D htonl(r-&g= t;gateway),
- .i= face =3D { .index =3D if_index, .name =3D "" },
- .metric =3D (r->flags & = RT_METRIC_DEFINED ? r->metric : -1)
- };
+ route_message_t msg =3D { .header =3D { (add ? msg_add_route : msg_= del_route),
+ = sizeof(route_message_t), 0 },
+ .fami= ly =3D AF_INET,

+ = .prefix.ipv4.s_addr =3D htonl(r->network),
+ = .gateway.ipv4.s_addr =3D htonl(r->gateway),
+ .iface =3D { .ind= ex =3D if_index, .name =3D "" },
+ .metric =3D (r->flags= & RT_METRIC_DEFINED ? r->metric : -1) };
netmask_to_netbits(r->network, r->netmask, &msg.pref= ix_len);
if (msg.prefix_len =3D=3D -1)
@@ -3166,7 +2911,7 @@

fwd_row->Metric =3D ((r->= flags & RT_METRIC_DEFINED) ? r->metric : -1);
f= wd_row->DestinationPrefix.Prefix.si_family =3D AF_INET6;
fwd_row->DestinationPrefix.Prefix.Ipv6.sin6_addr =3D r->network= ;

- fwd_row->Dest= inationPrefix.PrefixLength =3D (UINT8) r->netbits;
+ fwd_row->DestinationPrefix.PrefixL= ength =3D (UINT8)r->netbits;
fwd_row->NextHop.si= _family =3D AF_INET6;
fwd_row->NextHop.Ipv6.sin6_ad= dr =3D r->gateway;
fwd_row->InterfaceIndex =3D r= ->adapter_index ? r->adapter_index : tt->adapter_index;
= @@ -3231,21 +2976,16 @@
do_route_ipv6_service(const = bool add, const struct route_ipv6 *r, const struct tuntap *tt)
{

int status;
- route_message_t msg =3D {
- .header =3D {
- (add ? msg_add_route : msg_del_route)= ,
- sizeof(r= oute_message_t),
- = 0
- },
- .family =3D AF_I= NET6,
- .prefix.= ipv6 =3D r->network,
- .prefix_len =3D r->netbits,
- .gateway.ipv6 =3D r->gateway,
- .iface =3D { .index =3D tt-&g= t;adapter_index, .name =3D "" },

- .metric =3D ( (r->flags & RT_METRIC_DEF= INED) ? r->metric : -1)
- };
+ rout= e_message_t msg =3D { .header =3D { (add ? msg_add_route : msg_del_route),<= /span>
+ = sizeof(route_message_t), 0 },
+ .family =3D AF_IN= ET6,
+ = .prefix.ipv6 =3D r->network,
+ .prefix_len =3D r->= netbits,
+ = .gateway.ipv6 =3D r->gateway,
+ .iface =3D { .ind= ex =3D tt->adapter_index, .name =3D "" },
+ .metric =3D = ((r->flags & RT_METRIC_DEFINED) ? r->metric : -1) };

- if (r->ad= apter_index) /* vpn server special route */
+ if (r->adapter_index) /* vpn s= erver special route */
{
msg.= iface.index =3D r->adapter_index;
}
@@ -3254,8 +2994,7 @@

* The tapdrvr knows about it a= nd will answer neighbor discovery packets.
* (only do= this for routes actually using the tun/tap device)
*= /
- if (tt->type = =3D=3D DEV_TYPE_TUN
- = && msg.iface.index =3D=3D tt->adapter_index)
+ if (tt->type =3D=3D DEV_TY= PE_TUN && msg.iface.index =3D=3D tt->adapter_index)

{

inet_pton(AF_INET6, "fe80::8"= , &msg.gateway.ipv6);
}
@@ -3269,8= +3008,7 @@
status =3D do_route_service(add, &msg,= sizeof(msg), tt->options.msg_channel);
if (status = !=3D RTA_ERROR)
{
- msg(D_ROUTE, "IPv6 route %s via service %s&qu= ot;,
- add ?= "addition" : "deletion",
+ msg(D_ROUTE, "IPv6 route %s via serv= ice %s", add ? "addition" : "deletion",
= (status =3D=3D RTA_SUCCESS) ? "succeeded" : &q= uot;failed because route exists");
}
return status;

@@ -3309,17 +3047,10 @@
<= span> buf_printf(&out, "%s %s %s p=3D%d i=3D%d t=3D%d pr=3D%d = a=3D%d h=3D%d m=3D%d/%d/%d/%d/%d",

pri= nt_in_addr_t(r->dwForwardDest, IA_NET_ORDER, gc),
= print_in_addr_t(r->dwForwardMask, IA_NET_ORDER, gc),- print_in_addr_t(= r->dwForwardNextHop, IA_NET_ORDER, gc),
- (int)r->dwForwardPolicy,
<= span style=3D"color: hsl(0, 100%, 40%);">- (int)r->dwForwa= rdIfIndex,

- = (int)r->dwForwardType,
- (int)r->dwForwardProto,
- (int)r->dwForwardAge,<= br>- (int)r->dwF= orwardNextHopAS,
- = (int)r->dwForwardMetric1,
- (int)r->dwForwardMetric2,
- (int)r->dwForwardM= etric3,

- = (int)r->dwForwardMetric4,
+ print_in_addr_t(r->dwForwardNextHop, IA_NET_ORD= ER, gc), (int)r->dwForwardPolicy,
+ (int)r->dwForwardIfIndex, (int)r->dwF= orwardType, (int)r->dwForwardProto,
+ (int)r->dwForwardAge, (int)r->dwFor= wardNextHopAS, (int)r->dwForwardMetric1,
+ (int)r->dwForwardMetric2, (int)r-= >dwForwardMetric3, (int)r->dwForwardMetric4,
= (int)r->dwForwardMetric5);
return BSTR(&= ;out);
}
@@ -3368,12 +3099,11 @@ * normally on Linux.
* It always fails a= nd "ioctl(SIOCGIFCONF) failed" confuses users
= */
-
}


void
-get_default_gateway_ipv6(struct route_ipv6_gateway_in= fo *rgi6,
- = const struct in6_addr *dest, openvpn_net_ctx_t *ctx)+get_default_gateway_ipv6(stru= ct route_ipv6_gateway_info *rgi6, const struct in6_addr *dest,
+ openvpn= _net_ctx_t *ctx)

{
/* Same for ipv6 *= /

@@ -3437,7 +3167,7 @@
= if (ifr->ifr_addr.sa_family =3D=3D AF_INET)
= {
/* get interface addr */
- addr =3D= ntohl(((struct sockaddr_in *) &ifr->ifr_addr)->sin_addr.s_addr);=
+ add= r =3D ntohl(((struct sockaddr_in *)&ifr->ifr_addr)->sin_addr.s_ad= dr);

/* get interface na= me */
strncpynt(ifreq.ifr_name, ifr->if= r_name, sizeof(ifreq.ifr_name));
@@ -3455,7 +3185,7 @@
if (rgi->flags & RGI_ON_LINK) {
/* check tha= t interface name of current interface
- * matches interface name of best defaul= t route */
+ = * matches interface name of best default route */
if (strcmp(ifreq.ifr_name, best_name))

{

continu= e;
@@ -3479,7 +3209,7 @@
= {
continue;
= }
- = netmask =3D ntohl(((struct sockaddr_in *) &ifreq.ifr_= addr)->sin_addr.s_addr);
+ netmask =3D ntohl(((struct sockaddr_in *)&i= freq.ifr_addr)->sin_addr.s_addr);

= /* check that interface matches default route */ if (((rgi->gateway.addr ^ addr) & netmas= k) !=3D 0)
@@ -3524,22 +3254,22 @@
* netl= ink(3), netlink(7), rtnetlink(7)
* http://www.virtualbox.= org/svn/vbox/trunk/src/VBox/NetworkServices/NAT/rtmon_linux.c
*/

-struct rtreq {=
+struct rtreq=
+{
str= uct nlmsghdr nh;
struct rtmsg rtm;
= char attrbuf[512];
};

= void
-get_default_gate= way_ipv6(struct route_ipv6_gateway_info *rgi6,
- const struct in6_addr *de= st, openvpn_net_ctx_t *ctx)
+get_default_gateway_ipv6(struct route_ipv6_gateway_info *rgi6, cons= t struct in6_addr *dest,
+ openvpn_net_ctx_t *ctx)
{
int flags;

CLEAR(= *rgi6);

- if (net_route_v6_best_gw(ctx, dest, &rgi6->gateway.addr_ipv6= ,
- = rgi6->iface) =3D=3D 0)
+ if (net_route_v6_best_gw(ctx, dest, &rgi6->gatewa= y.addr_ipv6, rgi6->iface) =3D=3D 0)
{
if (!IN6_IS_ADDR_UNSPECIFIED(&rgi6->gateway.addr_ipv6))<= /span>
{
@@ -3564,9 +3294,8 @@
= }
}

-#elif defined(TARGET_DARWIN) || defined(TARGET_= SOLARIS) \
- || d= efined(TARGET_FREEBSD) || defined(TARGET_DRAGONFLY) \
- || defined(TARGET_OPENBSD) || define= d(TARGET_NETBSD)
+#el= if defined(TARGET_DARWIN) || defined(TARGET_SOLARIS) || defined(TARGET_FREE= BSD) \
+ || define= d(TARGET_DRAGONFLY) || defined(TARGET_OPENBSD) || defined(TARGET_NETBSD)

#include <sys/types.h>
#include <sys/socket.h>

@@ -3577,7 +3306,8 @@

#include <ifaddrs.h>
#endif
=
-struct rtmsg {=
+struct rtmsg=
+{
str= uct rt_msghdr m_rtm;
char m_space[512];
};

@@ -3599,26 +3329,30 @@
*/
#if defined(TARGET_DARWIN)
-#define ROUNDUP(a) \
- ((a) > 0 ? (1 + (((a) - 1) | (sizeof= (uint32_t) - 1))) : sizeof(uint32_t))
+#define ROUNDUP(a) ((a) > 0 ? (1 + (((a) - 1) | (sizeo= f(uint32_t) - 1))) : sizeof(uint32_t))
#elif defined(TARGE= T_NETBSD)
#define ROUNDUP(a) RT_ROUNDUP(a)
#else

-#define ROUNDU= P(a) \
- ((a) > 0= ? (1 + (((a) - 1) | (sizeof(long) - 1))) : sizeof(long))
+#define ROUNDUP(a) ((a) > 0 ? (1 += (((a) - 1) | (sizeof(long) - 1))) : sizeof(long))
#endif<= /span>

#if defined(TARGET_SOLARIS)
-#define NEXTADDR(w, u) \
- if (rtm_addrs & (w)) { = \
- l =3D sizeof= (u); memmove(cp, &(u), l); cp +=3D ROUNDUP(l); \
+#define NEXTADDR(w, u) \+ if (rtm_addrs & (w)) = \
+ { = \
+ = l =3D sizeof(u); \
+ memmove(cp, &(u), l); \
+ cp +=3D ROUNDUP(l); \
}


#define ADVANCE(x, n) (x +=3D= ROUNDUP(sizeof(struct sockaddr_in)))
-#else /* if defined(TARGET_SOLARIS) */
-#define NEXTADDR(w, u) \
- if (rtm_addrs & (w)) { \
- l =3D ((struct sock= addr *)&(u))->sa_len; memmove(cp, &(u), l); cp +=3D ROUNDUP(l); = \
+#else /* if define= d(TARGET_SOLARIS) */
= +#define NEXTADDR(w, u) \
+ if (rtm_addrs & (w)) = \
+ { = \
+ l =3D ((struct sockaddr *)&(u))->sa_len; \<= /span>
+ memmove(cp, = &(u), l); \
+ cp +=3D ROUNDUP(l); \
<= span> }


#define ADVANCE(x, n) (x += =3D ROUNDUP((n)->sa_len))
@@ -3637,7 +3371,7 @@ struct sockaddr so_dst, so_mask;
char *cp= =3D m_rtmsg.m_space;
struct sockaddr *gate =3D NULL, = *ifp =3D NULL, *sa;
- = struct rt_msghdr *rtm_aux;
+ struct rt_msghdr *rtm_aux;

= #define rtm m_rtmsg.m_rtm

@@ -3647,7 +33= 81,7 @@
pid =3D getpid();
seq =3D= 0;
#ifdef TARGET_OPENBSD
- rtm_addrs =3D RTA_DST | RTA_NETMASK; /* K= ernel refuses RTA_IFP */
+ rtm_addrs =3D RTA_DST | RTA_NETMASK; /* Kernel refuses RTA_IFP */<= /span>
#else
rtm_addrs =3D RTA_DST | RTA_NET= MASK | RTA_IFP;
#endif
@@ -3688,7 +3422,7 = @@
}
if (write(sockfd, (char *)&a= mp;m_rtmsg, l) < 0)
{
- msg(M_WARN|M_ERRNO, "GDG: problem writ= ing to routing socket");
+ msg(M_WARN | M_ERRNO, "GDG: problem writing to routi= ng socket");
goto done;
= }
do
@@ -3738,7 +3472,7 @@
<= span> if (ifp)

{
= /* get interface name */
- const struct sockaddr_dl *adl =3D (struct sockaddr_dl *)= ifp;
+ co= nst struct sockaddr_dl *adl =3D (struct sockaddr_dl *)ifp;
= if (adl->sdl_nlen && adl->sdl_nlen < sizeof(r= gi->iface))
{
= memcpy(rgi->iface, adl->sdl_data, adl->sdl_nlen);
@@ -3806,15 +3540,14 @@


if (= getifaddrs(&ifap) !=3D 0)
{
- msg(M_WARN|M_ERRNO, "GD= G: getifaddrs() failed");
+ msg(M_WARN | M_ERRNO, "GDG: getifaddrs() failed= ");
goto done;
}=

for (ifa =3D ifap; ifa; ifa =3D= ifa->ifa_next)
{
- if (ifa->ifa_addr !=3D NULL- && ifa= ->ifa_addr->sa_family =3D=3D AF_LINK
- && !strncmp(ifa->ifa_name, = rgi->iface, IFNAMSIZ) )
+ if (ifa->ifa_addr !=3D NULL && ifa->ifa_ad= dr->sa_family =3D=3D AF_LINK
+ && !strncmp(ifa->ifa_name, rgi->i= face, IFNAMSIZ))
{
= struct sockaddr_dl *sdl =3D (struct sockaddr_dl *)ifa->ifa_addr;
memcpy(rgi->hwaddr, LLADDR(sdl), 6);
@@ -3847,10 +3580,9 @@
#endif

void
- const = struct in6_addr *dest, openvpn_net_ctx_t *ctx)
+get_default_gateway_ipv6(struct route_ipv6_gatew= ay_info *rgi6, const struct in6_addr *dest,
+ openvpn_net_ctx_t *ctx)
{
-
struct rtmsg m_rtmsg;
int sockfd =3D = -1;
int seq, l, pid, rtm_addrs;
@@ -38= 66,7 +3598,7 @@
pid =3D getpid();
= seq =3D 0;
#ifdef TARGET_OPENBSD
- rtm_addrs =3D RTA_DST | RTA_NETMASK; = /* Kernel refuses RTA_IFP */
+ rtm_addrs =3D RTA_DST | RTA_NETMASK; /* Kernel refuses RTA= _IFP */
#else
rtm_addrs =3D RTA_DST |= RTA_NETMASK | RTA_IFP;
#endif
@@ -3887,8 = +3619,8 @@
so_dst.sin6_family =3D AF_INET6;
= so_mask.sin6_family =3D AF_INET6;

- if (dest !=3D NULL = /* specific host? */

- && !IN6_IS_ADDR_UNSPECIFIED(dest) )
+ if (dest !=3D NULL /* specific h= ost? */
+ &= ;& !IN6_IS_ADDR_UNSPECIFIED(dest))
{
so_dst.sin6_addr =3D *dest;

/* :: need= s /0 "netmask", host route wants "no netmask */
@@ -3916,15 +3648,14 @@

}
if = (write(sockfd, (char *)&m_rtmsg, l) < 0)
{
- msg(M_WARN|M_ERRNO= , "GDG6: problem writing to routing socket");
+ msg(M_WARN | M_ERRNO, "GDG= 6: problem writing to routing socket");
goto = done;
}

do
{
l =3D read(sockfd, (char *)&= ;m_rtmsg, sizeof(m_rtmsg));
- }
- while = (l > 0 && (rtm.rtm_seq !=3D seq || rtm.rtm_pid !=3D pid));
+ } while (l > 0 &am= p;& (rtm.rtm_seq !=3D seq || rtm.rtm_pid !=3D pid));
<= /span>
close(sockfd);
sockfd =3D -1;
@@ -3967,14 +3698,12 @@
* (KAME enco= des the 16 bit scope_id in s6_addr[2] + [3],
* bu= t for a correct link-local address these must be :0000: )
= */
- if= (gate->sa_len =3D=3D sizeof(struct sockaddr_in6)
- && IN6_IS_ADDR_LINKLOCA= L(&gw) )
+ = if (gate->sa_len =3D=3D sizeof(struct sockaddr_in6) && IN6_IS_A= DDR_LINKLOCAL(&gw))
{
= gw.s6_addr[2] =3D gw.s6_addr[3] =3D 0;
}

- = if (gate->sa_len !=3D sizeof(struct sockaddr_in6)
- || IN6_IS_ADDR_UNSPECIFIED(&= ;gw) )
+ if (g= ate->sa_len !=3D sizeof(struct sockaddr_in6) || IN6_IS_ADDR_UNSPECIFIED(= &gw))
{
rgi6->= flags |=3D RGI_ON_LINK;
}
@@ -3988= ,7 +3717,7 @@
if (ifp)
{<= /span>
/* get interface name */
- const struct sockaddr_dl *adl = =3D (struct sockaddr_dl *) ifp;
+ const struct sockaddr_dl *adl =3D (struct sockaddr_= dl *)ifp;
if (adl->sdl_nlen && adl-= >sdl_nlen < sizeof(rgi6->iface))
{
memcpy(rgi6->iface, adl->sdl_data, adl= ->sdl_nlen);
@@ -4072,15 +3801,15 @@
= address_size +=3D route.gateway->sa_len;
= }

- interface =3D (struct ifreq *)((addr_t)interface + IF_NAMESIZE
- = + sizeof(struct route_entry) + address_size);
+ interface =3D (struct ifreq = *)((addr_t)interface + IF_NAMESIZE + sizeof(struct route_entry)
<= span style=3D"color: hsl(120, 100%, 40%);">+ = + address_size);

}
free(buf= fer);
}

void
= -get_default_gateway_ipv6(struct = route_ipv6_gateway_info *rgi6,
- const struct in6_addr *dest, openvpn_net_= ctx_t *ctx)
+get_defa= ult_gateway_ipv6(struct route_ipv6_gateway_info *rgi6, const struct in6_add= r *dest,
+ = openvpn_net_ctx_t *ctx)
{
= /* TODO: Same for ipv6 with AF_INET6 */
CLEAR(*rgi6= );
@@ -4118,8 +3847,8 @@
CLEAR(*rgi);<= /span>
}
void
-get_default_gateway_ipv6(struct route_ipv6_gateway_info = *rgi6,
- = const struct in6_addr *dest, openvpn_net_ctx_t *ctx)
+get_default_gateway_ipv6(struct = route_ipv6_gateway_info *rgi6, const struct in6_addr *dest,

+ openvpn_ne= t_ctx_t *ctx)

{
msg(D_ROUTE, "no= support for get_default_gateway_ipv6() on this system");
CLEAR(*rgi6);

@@ -4199,7 +3928,8 @@
while (iplist)

{
bool = succeed =3D false;
- = const in_addr_t ip =3D getaddr(GETADDR_HOST_ORDER, iplist->IpAddres= s.String, 0, &succeed, NULL);
+ const in_addr_t ip =3D
+ getaddr(GETADDR_HOST_ORDER, iplist->= ;IpAddress.String, 0, &succeed, NULL);
if (suc= ceed)
{
add_host_rout= e_if_nonlocal(rb, ip);
@@ -4247,7 +3977,7 @@
#else /* if defined(_WIN32) */


stati= c void
-get_bypass_addr= esses(struct route_bypass *rb, const unsigned int flags) /* PLATFORM-SPEC= IFIC */
+get_bypass_a= ddresses(struct route_bypass *rb, const unsigned int flags) /* PLATFORM-SPE= CIFIC */
{
}

= @@ -4268,7 +3998,8 @@
test_local_addr(const in_addr_= t addr, const struct route_gateway_info *rgi)
{
= struct gc_arena gc =3D gc_new();
- const in_addr_t nonlocal_netmask =3D 0x80000000L;= /* routes with netmask <=3D to this are considered non-local */<= br>+ const in_addr_t nonloca= l_netmask =3D
+ = 0x80000000L; /* routes with netmask <=3D to this are considered non-lo= cal */
int ret =3D TLA_NONLOCAL;

/* get full routing table */
@@ -4295,7 += 4026,7 @@
#else /* if defined(_WIN32) */
=
int
= -test_local_addr(const in_addr_t addr, const struct route_gateway_info *rgi= ) /* PLATFORM-SPECIFIC */
+test_local_addr(const in_addr_t addr, const struct route_gateway_inf= o *rgi) /* PLATFORM-SPECIFIC */
{
if = (rgi)
{
diff --git a/src/openvpn/route= .h b/src/openvpn/route.h
index 1a358e32..ea8b767 100644
--- a/src/openvpn/route.h
+++ b/src/openvpn/ro= ute.h
@@ -36,18 +36,18 @@
/*
* Windows route methods

*/
-#define ROUTE_METHOD_ADAPTIVE 0 /* try IP hel= per first then route.exe */
-#define ROUTE_METHOD_IPAPI 1 /* use IP helper API */
<= span style=3D"color: hsl(0, 100%, 40%);">-#define ROUTE_METHOD_EXE 2 = /* use route.exe */

-#= define ROUTE_METHOD_SERVICE 3 /* use the privileged Windows service */
-#define ROUTE_METHOD_MA= SK 3
+#define RO= UTE_METHOD_ADAPTIVE 0 /* try IP helper first then route.exe */
+#define ROUTE_METHOD_IPAPI 1 = /* use IP helper API */

+#define ROUTE_METHOD_EXE 2 /* use route.exe */
+#define ROUTE_METHOD_SERVICE 3 /* use = the privileged Windows service */
+#define ROUTE_METHOD_MASK 3
#endif

/*
* Route add/delete flags= (must stay clear of ROUTE_METHOD bits)
*/
-#define ROUTE_DELETE_FIRST (1<&l= t;2)

-#define ROUTE_REF= _GW (1<<3)
+#define ROUTE_DELETE_FIRST (1 << 2)
+#define ROUTE_REF_GW (1 << 3)<= br>
struct route_bypass
{@@ -59,9 +59,9 @@
struct route_special_addr=
{
/* bits indicating which members below ar= e defined */
-#define R= TSA_REMOTE_ENDPOINT (1<<0)
-#define RTSA_REMOTE_HOST (1<<1)
-#define RTSA_DEFAULT_METRIC (1<<2)=
+#define RTSA_REMOTE= _ENDPOINT (1 << 0)
+#define RTSA_REMOTE_HOST (1 << 1)
+#define RTSA_DEFAULT_METRIC (1 << 2)
unsigned int flags;

= in_addr_t remote_endpoint;
@@ -72,7 +72,8 @@
<= span> int default_metric;

};
<= br>-struct route_option {<= br>+struct route_option<= br>+{
stru= ct route_option *next;
const char *network;
= const char *netmask;
@@ -82,39 +83,43 @@<= br> };

/* redirect-gateway flags *= /
-#define RG_ENABLE = (1<<0)
-#de= fine RG_LOCAL (1<<1)
-#define RG_DEF1 (1<<2)
-#define RG_BYPASS_DHCP (1<<3)
-#define RG_BYPASS_DNS = (1<<4)
-#define R= G_REROUTE_GW (1<<5)
-#define RG_AUTO_LOCAL (1<<6)
-#define RG_BLOCK_LOCAL (1<<7)
<= span style=3D"color: hsl(120, 100%, 40%);">+#define RG_ENABLE (1 <&= lt; 0)

+#define RG_LO= CAL (1 << 1)
+#define RG_DEF1 (1 << 2)
+#define RG_BYPASS_DHCP (1 << 3)
+#define RG_BYPASS_DNS (1 <<= 4)

+#define RG_REROU= TE_GW (1 << 5)
+#define RG_AUTO_LOCAL (1 << 6)
+#define RG_BLOCK_LOCAL (1 << 7)
=
-struct route_option_l= ist {
+struct route_o= ption_list
+{<= br> unsigned int flags; /* RG_x flags */
str= uct route_option *routes;
struct gc_arena *gc;<= br> };

-struct route_ipv6_option {
+struct route_ipv6_option
+{
struct route_ipv6_option *next;=
- const char *prefi= x; /* e.g. "2001:db8:1::/64" */
- const char *gateway; /* e.g. "2= 001:db8:0::2" */
-= const char *metric; /* e.g. "5" */
+ const char *prefix; /* e.g. "= ;2001:db8:1::/64" */
+ const char *gateway; /* e.g. "2001:db8:0::2" */<= br>+ const char *metric; /*= e.g. "5" */
int table_id;
= };

-s= truct route_ipv6_option_list {
- unsigned int flags; /* RG_x flags, see route_option-li= st */
+struct route_i= pv6_option_list
+{
+ unsigned int flags= ; /* RG_x flags, see route_option-list */
struct route= _ipv6_option *routes_ipv6;
struct gc_arena *gc;=
};

-struct route_ipv4 {
-#define RT_DEFINED (1<<0)
-#define RT_ADDED (1<<1)
<= span style=3D"color: hsl(0, 100%, 40%);">-#define RT_METRIC_DEFINED (1<&= lt;2)

+struct route_i= pv4
+{
+#define RT_DEFINED (1 <&= lt; 0)

+#define RT_AD= DED (1 << 1)
+#define RT_METRIC_DEFINED (1 << 2)
struc= t route_ipv4 *next;
unsigned int flags;
const struct route_option *option;

@@ -125,9 +130,10= @@
int metric;
};
<= /span>
-struct route_ipv6 {
+struct route_ipv6
+{
s= truct route_ipv6 *next;
- unsigned int flags; /* RT_ flags, see route_i= pv4 */
+ unsigned = int flags; /* RT_ flags, see route_ipv4 */
struct in6_= addr network;
unsigned int netbits;
= struct in6_addr gateway;
@@ -135,25 +141,27 @@ int table_id;
/* gateway interface */
#ifdef _WIN32
- DWORD adapter_index; /* interface or ~0 if undefined */
+ DWORD adapter_index= ; /* interface or ~0 if undefined */
#else
- char *iface; /* in= terface name (null terminated) */

+ char *iface; /* interface name (null terminated) */
#endif
};

<= /span>
-struct route_gateway_a= ddress {
+struct rout= e_gateway_address
+{<= /span>
in_addr_t addr;
in_addr_t netmask= ;
};

-struct route_gateway_info {
-#define RGI_ADDR_DEFINED (1<<0) /* set i= f gateway.addr defined */
-#define RGI_NETMASK_DEFINED (1<<1) /* set if gateway.netmask de= fined */
-#define RGI_H= WADDR_DEFINED (1<<2) /* set if hwaddr is defined */
-#define RGI_IFACE_DEFINED (1<&= lt;3) /* set if iface is defined */

-#define RGI_OVERFLOW (1<<4) /* set if more in= terface addresses than will fit in addrs */
-#define RGI_ON_LINK (1<<5)
<= span style=3D"color: hsl(120, 100%, 40%);">+struct route_gateway_info
+{
+#define RGI_ADDR_DEFINED (1 << 0= ) /* set if gateway.addr defined */
+#define RGI_NETMASK_DEFINED (1 << 1) /* set if gatewa= y.netmask defined */
= +#define RGI_HWADDR_DEFINED (1 << 2) /* set if hwaddr is defined */<= /span>
+#define RGI_IFACE_DE= FINED (1 << 3) /* set if iface is defined */
+#define RGI_OVERFLOW (1 << 4= ) /* set if more interface addresses than will fit in addrs */
+#define RGI_ON_LINK (1 &= lt;< 5)

unsigned int flags;

/* gateway interface */
@@ -173,17 +181,19 = @@

/* address/netmask pairs bound to= interface */
#define RGI_N_ADDRESSES 8
- int n_addrs; /* len of addrs, may be= 0 */
+ int n_addr= s; /* len of addrs, may be 0 */
struct route_gateway_address addrs[RGI_N_ADDRESSES]; /* l= ocal addresses attached to iface */
};

-struct route_ipv6_gatew= ay_address {
+struct = route_ipv6_gateway_address
+{
struct in6_addr addr_ipv6;
= int netbits_ipv6;
};

-struct route_ipv6_gateway_info {
-/* RGI_ flags used as in ro= ute_gateway_info */
+= struct route_ipv6_gateway_info
+{
+ /* = RGI_ flags used as in route_gateway_info */
unsigned i= nt flags;

/* gateway interface */
@@ -210,45 +220,50 @@

= /* address/netmask pairs bound to interface */
#define RGI= _N_ADDRESSES 8
- int= n_addrs; /* len of addrs, may be 0 */
- struct route_ipv6_gateway_address addrs[RGI_N_ADDRESSE= S]; /* local addresses attached to iface */
+ int n_addrs; /* len of addrs, ma= y be 0 */
+ struct= route_ipv6_gateway_address
+ addrs[RGI_N_ADDRESSES]; /* local addresses attached to ifac= e */
};

-struct route_list {
-#define RL_DID_REDIRECT_DEFAULT_GATEWAY (1<<0)
-#define RL_DID_LOCAL = (1<<1)
-#define RL_ROUTES_ADDED (1<<2)
+struct route_list
+{
+#define RL_DID_REDIRECT_DEFAULT_GATEWAY (1 << 0)
+#define RL_DID_LOCAL = (1 << 1)
+#define RL_ROUTES_ADDED (1 << 2)=
unsigned int iflags;

= struct route_special_addr spec;
struct route_gateway_i= nfo rgi;
- unsigned = int flags; /* RG_x flags */
+ unsigned int flags; /* RG_x flags */
str= uct route_ipv4 *routes;
struct gc_arena gc;
= };

-struct route_ipv6_list {
- unsigned int iflags; /* RL_ flags, see route_li= st */
+struct route_i= pv6_list
+{+ unsigned int iflags; = /* RL_ flags, see route_list */

- unsigned int spec_flags; = /* RTSA_ flags, route_special_addr */

+ unsigned int spec_flags; /* RTSA_ = flags, route_special_addr */
struct in6_addr remote_en= dpoint_ipv6; /* inside tun */
- struct in6_addr remote_host_ipv6; /* --remote address */
+ struct in6_addr remo= te_host_ipv6; /* --remote address */
int default_m= etric;

struct route_ipv6_gateway_inf= o rgi6;
- unsigned i= nt flags; /* RG_x flags, see route_option_list */+ unsigned int flags; /* RG= _x flags, see route_option_list */
struct route_ipv6 *= routes_ipv6;
struct gc_arena gc;
};

/* internal OpenVPN route */
-struct iroute {

+struct iroute
+{
in_addr_t network;
int netbits;
struct iroute *next;
};

-struct iroute_ipv6 {
+struct iroute_ipv6
+{
struct in6_addr network;
unsigned int netbits;

struct iroute_ipv6 *nex= t;
@@ -270,79 +285,58 @@

= struct route_ipv6_option_list *new_route_ipv6_option_list(struct gc_arena = *a);

= -struct route_option_list *clone_route_option_list(const struct route_optio= n_list *src, struct gc_arena *a);
+struct route_option_list *clone_route_option_list(const struc= t route_option_list *src,
+ struct gc_arena *a)= ;

-st= ruct route_ipv6_option_list *clone_route_ipv6_option_list(const struct rout= e_ipv6_option_list *src, struct gc_arena *a);
+struct route_ipv6_option_list *clone_route_ipv6_o= ption_list(
+ cons= t struct route_ipv6_option_list *src, struct gc_arena *a);
=
-void copy_route_opti= on_list(struct route_option_list *dest, const struct route_option_list *src= , struct gc_arena *a);
+ struct gc_arena *a);

void copy_route_ipv6_option_list(struct route_ipv6_option_lis= t *dest,
- = const struct route_ipv6_option_list *src,
- st= ruct gc_arena *a);

+ = const struct route_ipv6_option_list *src, s= truct gc_arena *a);

-void route_ipv6_clear_host_bits( struct route_ipv6 *r6 );
+void route_ipv6_clear= _host_bits(struct route_ipv6 *r6);

-bool add_route_ipv6(struct route_ipv6 *r, c= onst struct tuntap *tt, unsigned int flags, const struct env_set *es, openv= pn_net_ctx_t *ctx);
+= bool add_route_ipv6(struct route_ipv6 *r, const struct tuntap *tt, unsigned= int flags,
+ = const struct env_set *es, openvpn_net_ctx_t *ctx);

-void delete_rout= e_ipv6(const struct route_ipv6 *r, const struct tuntap *tt, const struct en= v_set *es, openvpn_net_ctx_t *ctx);
+void delete_route_ipv6(const struct route_ipv6 *r, const st= ruct tuntap *tt,
+ = const struct env_set *es, openvpn_net_ctx_t *ctx);

bool add_route(struct route_ipv4 *r, const s= truct tuntap *tt, unsigned int flags,
const= struct route_gateway_info *rgi, const struct env_set *es,
= openvpn_net_ctx_t *ctx);

-void add_route_to_option_list(struct r= oute_option_list *l,
- = const char *network,
- const char *netma= sk,
- = const char *gateway,
- const char *metric,
- int ta= ble_id);

+void add_ro= ute_to_option_list(struct route_option_list *l, const char *network, const = char *netmask,
+ = const char *gateway, const char *metric, int table= _id);

-void add_route_ipv6_to_option_list(struct route_ipv6_option_list *l,
- = const char *prefix,
- const char *gateway,
- = const char *metric,

- = int table_id);
+void add_route_ipv6_to_option_list(struct rout= e_ipv6_option_list *l, const char *prefix,
+ const char *gatew= ay, const char *metric, int table_id);

-bool init_route_list(struct route_list *= rl,
- = const struct route_option_list *opt,
- const char *remote_endpoint,<= br>- int defa= ult_metric,
- = in_addr_t remote_host,
- struct env_set *es,
- openvpn_net_ctx_t *ctx= );
+bool init_route_l= ist(struct route_list *rl, const struct route_option_list *opt,
<= span style=3D"color: hsl(120, 100%, 40%);">+ const char= *remote_endpoint, int default_metric, in_addr_t remote_host,

+ struct env_s= et *es, openvpn_net_ctx_t *ctx);


-bool init_route_ipv6_list(struct route_ipv6_li= st *rl6,
- = const struct route_ipv6_option_list *opt6,
- const char *rem= ote_endpoint,
- = int default_metric,
- const struct in6_addr *remote_hos= t,
- = struct env_set *es,
+bool init_route_ipv6_list(struct route_ipv6_list *rl6, const struct = route_ipv6_option_list *opt6,
+ const char *remote_endpoint, int defaul= t_metric,
+ = const struct in6_addr *remote_host, struct env_set *es,
openvpn_net_ctx_t *ctx);
=
-void route_lis= t_add_vpn_gateway(struct route_list *rl,
- struct env_set *es,
- = const in_addr_t addr);
+void route_list_add_vpn_gateway(struct route_list *rl, struct env_= set *es, const in_addr_t addr);

-bool add_routes(struct route_list *rl, struct r= oute_ipv6_list *rl6,
- = const struct tuntap *tt, unsigned int flags,
- const struct env_set = *es, openvpn_net_ctx_t *ctx);

+bool add_routes(struct route_list *rl, struct route_ipv6_list *rl= 6, const struct tuntap *tt,
+ unsigned int flags, const struct env_set *es, openv= pn_net_ctx_t *ctx);

-void delete_routes(struct route_list *rl,
- struct route_ipv6_li= st *rl6,
- = const struct tuntap *tt,
- unsigned int flags,
- const struct env_set *es,
- openvpn= _net_ctx_t *ctx);
+vo= id delete_routes(struct route_list *rl, struct route_ipv6_list *rl6, const = struct tuntap *tt,
+ = unsigned int flags, const struct env_set *es, openvpn_net= _ctx_t *ctx);

-void
-delete_= routes_v4(struct route_list *rl, const struct tuntap *tt,
- unsigned int flags, co= nst struct env_set *es,
- openvpn_net_ctx_t *ctx);
+void delete_routes_v4(struct route_list *rl, const = struct tuntap *tt, unsigned int flags,
+ const struct env_set *es, openvpn_= net_ctx_t *ctx);

-void
-dele= te_routes_v6(struct route_ipv6_list *rl6, const struct tuntap *tt,- unsigned int = flags, const struct env_set *es,
- openvpn_net_ctx_t *ctx);
+void delete_routes_v6(struct route_ipv6_l= ist *rl6, const struct tuntap *tt, unsigned int flags,
+ const struct env_s= et *es, openvpn_net_ctx_t *ctx);

void se= tenv_routes(struct env_set *es, const struct route_list *rl);

@@ -357,16 +351,12 @@
* @param dest = Destination IP address in host byte order.
* @param ctx = Pointer to a platform-specific network context struct.
*/=
-void get_default_gate= way(struct route_gateway_info *rgi,
- in_addr_t dest,
- openvpn_net_ctx_t= *ctx);
+void get_def= ault_gateway(struct route_gateway_info *rgi, in_addr_t dest, openvpn_net_ct= x_t *ctx);

-void get_default_gateway_ipv6(struct route_ipv6_gateway_info *rgi,
- = const struct in6_addr *dest,
+void get_default_gateway_ipv6(struct route_ipv6_gateway_inf= o *rgi, const struct in6_addr *dest,
= openvpn_net_ctx_t *ctx);

-void print_default_gateway(const int msglev= el,
- = const struct route_gateway_info *rgi,
+void print_default_gateway(const int msglevel, c= onst struct route_gateway_info *rgi,
= const struct route_ipv6_gateway_info *rgi6);
=
/*
@@ -381,8 +371,7 @@
int test= _local_addr(const in_addr_t addr, const struct route_gateway_info *rgi);

#ifndef ENABLE_SMALL
-void print_route_options(const struct route= _option_list *rol,
- = int level);
+void print_route_options(const struct route_option_list *rol,= int level);

#endif

@@ -394,7 +383,7 @@

bool t= est_routes(const struct route_list *rl, const struct tuntap *tt);
-#else /* ifd= ef _WIN32 */
+#else /= * ifdef _WIN32 */
static inline bool
test= _routes(const struct route_list *rl, const struct tuntap *tt)
{

@@ -413,7 +402,7 @@
in_addr_t ma= sk =3D 0;
if (netbits > 0 && netbits <= =3D addrlen)
{
- mask =3D IPV4_NETMASK_HOST << (addrlen-netbits)= ;
+ mask =3D I= PV4_NETMASK_HOST << (addrlen - netbits);
}
return mask;
}
diff --git = a/src/openvpn/run_command.c b/src/openvpn/run_command.c
ind= ex ed5b08c..4a1ef22 100644
--- a/src/openvpn/run_command.c<= /span>
+++ b/src/openvpn/run_command.c
@@ -67,7 +6= 7,7 @@
#ifdef _WIN32
case OPENVPN= _EXECVE_ERROR:
buf_printf(&out, "exte= rnal program did not execute -- ");
- /* fall through */
+ /* fall through */
<= /span>
default:
buf_printf(&= amp;out, "returned error code %d", stat);
@@ -126= ,20 +126,16 @@

if (exitcode =3D= =3D OPENVPN_EXECVE_FAILURE)
{
- msg(msglevel, "%scould no= t execute external program (exit code 127)",
- msg_prefix);
+ msg(msglevel, "%scoul= d not execute external program (exit code 127)", msg_prefix); }
else
{=
- msg(msgle= vel, "%sexternal program exited with error status: %d",- msg_prefix, exi= tcode);
+ = msg(msglevel, "%sexternal program exited with error status: %d", = msg_prefix, exitcode);
}
-
}
el= se if (WIFSIGNALED(status))
{
- msg(msglevel, "%sexternal program= received signal %d",
- msg_prefix, WTERMSIG(status));
+ msg(msglevel, "%sexternal program = received signal %d", msg_prefix, WTERMSIG(status));
= }

return false;
@= @ -234,7 +230,8 @@
* Wrapper around openvpn_execve=
*/
int
-openvpn_execve_check(const struct argv *a, const struct env_s= et *es, const unsigned int flags, const char *error_message)
+openvpn_execve_check(const struct = argv *a, const struct env_set *es, const unsigned int flags,

+ const char *e= rror_message)

{
struct gc_arena gc = =3D gc_new();
const int stat =3D openvpn_execve(a, es,= flags);
@@ -260,8 +257,7 @@
}<= br> if (error_message)
{
- msg(((flags & S_FATAL) ? M_FA= TAL : M_WARN), "%s: %s",
- error_message,
+ msg(((flags & S_FATAL) ? M_FATAL : M_WARN),= "%s: %s", error_message,
system_err= or_message(stat, &gc));
}
done:
@@ -276,7 +272,7 @@
* associated with form= atting and parsing a command line.
*/
in= t
-openvpn_popen(const = struct argv *a, const struct env_set *es)
+openvpn_popen(const struct argv *a, const struct env= _set *es)
{
struct gc_arena gc =3D gc= _new();
int ret =3D -1;
@@ -298,20 +29= 4,20 @@
pid =3D fork();
= if (pid =3D=3D (pid_t)0) /* child side */
{

= - close(pipe_stdout[0]); /* Close read end */
+ cl= ose(pipe_stdout[0]); /* Close read end */
= dup2(pipe_stdout[1], 1);
execve(cm= d, argv, envp);
exit(OPENVPN_EXECVE_FA= ILURE);
}
- else if (pid > (pid_t)0) /* p= arent side */
+ = else if (pid > (pid_t)0) /* parent side */
= {
int status =3D 0;

- = close(pipe_stdout[1]); /* Close write end */
<= span style=3D"color: hsl(120, 100%, 40%);">+ close(pipe_= stdout[1]); /* Close write end */

wait= pid(pid, &status, 0);
ret =3D pipe= _stdout[0];
}
- else /* fork failed */
+ else /* f= ork failed */
{
= close(pipe_stdout[0]);
clos= e(pipe_stdout[1]);
diff --git a/src/openvpn/run_command.h b= /src/openvpn/run_command.h
index e703732..4b74f22 100644
--- a/src/openvpn/run_command.h
+++ b/src/ope= nvpn/run_command.h
@@ -27,36 +27,38 @@
#in= clude "env_set.h"

/* Script se= curity */
-#define SSEC= _NONE 0 /* strictly no calling of external programs */
-#define SSEC_BUILT_IN 1 /* only call= built-in programs such as ifconfig, route, netsh, etc.*/

-#define SSEC_SCRIPTS 2 /* allow calli= ng of built-in programs and user-defined scripts */
-#define SSEC_PW_ENV 3 /* allow calling o= f built-in programs and user-defined scripts that may receive a password as= an environmental variable */
+#define SSEC_NONE 0 /* strictly no calling of external progra= ms */
+#define SSEC_B= UILT_IN 1 /* only call built-in programs such as ifconfig, route, netsh, et= c.*/
+#define SSEC_SC= RIPTS 2 /* allow calling of built-in programs and user-defined scripts */<= /span>
+#define SSEC_PW_ENV = = \
+ 3 /* allow c= alling of built-in programs and user-defined scripts that may receive a pas= sword \
+ as = an environmental variable */

-#define OPENVPN_EXECVE_ERROR -1 /* generic e= rror while forking to run an external program */
-#define OPENVPN_EXECVE_NOT_ALLOWED -2 /* externa= l program not run due to script security */
-#define OPENVPN_EXECVE_FAILURE 127 /* exit code pa= ssed back from child when execve fails */
+#define OPENVPN_EXECVE_ERROR -1 /* generic err= or while forking to run an external program */
+#define OPENVPN_EXECVE_NOT_ALLOWED -2 /* extern= al program not run due to script security */
+#define OPENVPN_EXECVE_FAILURE 127 /* exit cod= e passed back from child when execve fails */

<= span> int script_security(void);


void sc= ript_security_set(int level);

/* openvpn= _execve flags */
-#defi= ne S_SCRIPT (1<<0)
-#define S_FATAL (1<<1)
+#define S_SCRIPT (1 << 0)
+#define S_FATAL (1 << 1)=
/** Instead of returning 1/0 for success/fail,
= * return exit code when between 0 and 255 and -1 otherwise */
-#define S_EXITCODE (1<<2)
+#define S_EXITCODE (= 1 << 2)
/** instead of waiting for child process to = exit and report the status,
* return the pid of the child= process */
-#define S_= NOWAITPID (1<<3)
-int openvpn_popen(const struct argv *a, const struct env_se= t *es);
+int openvpn_= popen(const struct argv *a, const struct env_set *es);

bool openvpn_execve_allowed(const unsigned int flags);

-int openv= pn_execve_check(const struct argv *a, const struct env_set *es,
<= span style=3D"color: hsl(0, 100%, 40%);">- const un= signed int flags, const char *error_message);

+int openvpn_execve_check(const struct argv *a, co= nst struct env_set *es, const unsigned int flags,
+ const char *error_me= ssage);


#ifndef WIN32<= /span>
@@ -72,9 +74,7 @@
* @return = true if the process is still running, false if
* = an error condition occurred
*/
-bool
-openvpn_waitpid_check(pid_t pid, const char= *msg_prefix,
- = int msglevel);
+bool openvpn_waitpid_check(pid_t pid, const char *msg_prefix, int = msglevel);

#endif

@@ -83,13 +83,12 @@
* 0 and 255, -1 otherwise=
*/
static inline int
-openvpn_run_script(const struct argv *a,= const struct env_set *es,
- const unsigned int flags, const char *hook)<= br>+openvpn_run_script(const st= ruct argv *a, const struct env_set *es, const unsigned int flags,+ const char= *hook)
{
char msg[256];

- snprintf(msg= , sizeof(msg),
- = "WARNING: Failed running command (%s)", hook);
+ snprintf(msg, sizeof(msg), &= quot;WARNING: Failed running command (%s)", hook);

= return openvpn_execve_check(a, es, flags | S_SCRIPT, msg);
}


diff --git a/src/openvpn/schedule.c = b/src/openvpn/schedule.c
index f89f341..c9fef24 100644
--- a/src/openvpn/schedule.c
+++ b/src/openvpn/= schedule.c
@@ -54,15 +54,12 @@
struct = gc_arena gc =3D gc_new();
if (e)
= {
- dmsg(D_SCHED= ULER, "SCHEDULE: %s wakeup=3D[%s] pri=3D%u",
- caller,
- tv_string_abs(&e->tv, &= amp;gc),
+ dms= g(D_SCHEDULER, "SCHEDULE: %s wakeup=3D[%s] pri=3D%u", caller, tv_= string_abs(&e->tv, &gc),
e->pri= );
}
else
{<= /span>
- dmsg(D_SCHEDUL= ER, "SCHEDULE: %s NULL",
- caller);
+ dmsg(D_SCHEDULER, "SCHEDULE: %s NULL", cal= ler);
}
gc_free(&gc);<= br> }
@@ -84,8 +81,7 @@
* that keys= do not collide.
*/
static inline int
-schedule_entry_compare(c= onst struct schedule_entry *e1,
- const struct schedule_entry *e2)+schedule_entry_compare(const = struct schedule_entry *e1, const struct schedule_entry *e2)
{

if (e1->tv.tv_sec < e2->tv.tv_sec)=
{
@@ -360,12 +356,11 @@

if (s->root)
{
- schedule_insert(s, e); /* tri= vial insert into tree */
+ schedule_insert(s, e); /* trivial insert into tree */ }
else
{
<= span> s->root =3D e; /* tree was empty, we are the first element= */

-
= }
/* This is the magic of the randomized treap alg= orithm which
* keeps the tree balanced. Move the nod= e up the tree until
@@ -446,12 +441,8 @@
= * internally consistent.
*/
int-schedule_debug_entry(const str= uct schedule_entry *e,
= - int depth,
- int *count,
- struct timeval *least,- const stru= ct timeval *min,
- = const struct timeval *max)
+schedule_debug_entry(const struct schedule_entry *e,= int depth, int *count, struct timeval *least,
+ const struct timeval *min, = const struct timeval *max)
{
struct g= c_arena gc =3D gc_new();
int maxdepth =3D depth;
@@ -493,13 +484,13 @@
*least =3D e-= >tv;
}

- d =3D schedule_debug_entry(e->lt= , depth+1, count, least, min, &e->tv);
+ d =3D schedule_debug_entry(e->lt, dept= h + 1, count, least, min, &e->tv);
if (d &g= t; maxdepth)
{
maxdep= th =3D d;
}

- d =3D schedule_debug_entry(e->g= t, depth+1, count, least, &e->tv, max);
+ d =3D schedule_debug_entry(e->gt, dep= th + 1, count, least, &e->tv, max);
if (d &= gt; maxdepth)
{
maxde= pth =3D d;
@@ -576,14 +567,8 @@
if (e)
{
- printf("Verification Phase count=3D%d max= lev=3D%d sru=3D%d ins=3D%d coll=3D%d ls=3D%d l=3D%s",
- count,
- maxlev,
- zz.sru,

- zz.ins,

- zz.coll,

<= span style=3D"color: hsl(0, 100%, 40%);">- zz.lsteps,
<= br>- tv_string(&= ;e->tv, &gc));
+ printf("Verification Phase count=3D%d maxlev=3D%d sru=3D%d = ins=3D%d coll=3D%d ls=3D%d l=3D%s", count,
+ maxlev, zz.sru, zz.ins, zz.coll,= zz.lsteps, tv_string(&e->tv, &gc));
if (!tv_eq(&least, &e->tv))
= {
@@ -604,11 +589,11 @@
for (i = =3D 0; i < size; ++i)
{
co= nst int src =3D get_random() % size;
- struct schedule_entry *tmp =3D array [i];
= + struct schedule_entry = *tmp =3D array[i];
if (i !=3D src)
{

- = array [i] =3D array [src];
- array [src] =3D tmp;
+ array[i] =3D array[src];
+ array[src] =3D tmp;=
}
}
}
@@ -625,14 +610,10 @@

if (e)
= {
printf("%s [%u] e=3D" ptr_format "= ;, p=3D" ptr_format " lt=3D" ptr_format " gt=3D" p= tr_format "\n",
- tv_string(&e->tv, &gc),
- e->pri,
- (ptr_type)e,
<= span style=3D"color: hsl(0, 100%, 40%);">- (ptr_type)e->pa= rent,

- (= ptr_type)e->lt,
+ = tv_string(&e->tv, &gc), e->pri, (ptr_type)e, (p= tr_type)e->parent, (ptr_type)e->lt,
(= ptr_type)e->gt);
- = schedule_print_work(e->lt, indent+1);
- schedule_print_work(e->gt, indent+1);
+ schedule_prin= t_work(e->lt, indent + 1);
+ schedule_print_work(e->gt, indent + 1);
}

else
{
d= iff --git a/src/openvpn/schedule.h b/src/openvpn/schedule.h
index fad3f36..79311c5 100644

--- a/src/openvpn/schedule.h=
+++ b/src/openvpn/schedule.h
@@ -42,8 +42,= 8 @@

struct schedule_entry
{

- struct timev= al tv; /* wakeup time */
- unsigned int pri; /* random treap priority */
+ struct timeval tv= ; /* wakeup time */
+ unsigned int pri; /* random treap priority */<= /span>
struct schedule_entry *parent; /* treap (btree) links = */
struct schedule_entry *lt;
str= uct schedule_entry *gt;
@@ -52,7 +52,7 @@
= struct schedule
{
struct schedule_ent= ry *earliest_wakeup; /* cached earliest wakeup */
- struct schedule_entry *root; /* th= e root of the treap (btree) */
+ struct schedule_entry *root; /* the root of the t= reap (btree) */
};

/* P= ublic functions */
@@ -94,9 +94,7 @@
* an= opaque object.
*/
static inline void
-schedule_add_entry(struc= t schedule *s,
- = struct schedule_entry *e,
- const struct timeval *tv,
+schedule_add_entry(struct schedule= *s, struct schedule_entry *e, const struct timeval *tv,

= unsigned int sigma)
{
= if (!IN_TREE(e) || !sigma || !tv_within_sigma(tv, &e->tv, sigma))=
@@ -114,8 +112,7 @@
* is randomized ever= y time an entry is re-added).
*/
static = inline struct schedule_entry *
-schedule_get_earliest_wakeup(struct schedule *s,
- struct tim= eval *wakeup)
+schedu= le_get_earliest_wakeup(struct schedule *s, struct timeval *wakeup) {
struct schedule_entry *ret;

diff --git a/src/openvpn/session_id.h b/src/openvpn/sess= ion_id.h
index 7c0a968..24e7ab0 100644
--- = a/src/openvpn/session_id.h
+++ b/src/openvpn/session_id.h
@@ -44,8 +44,7 @@
#define SID_SIZE (sizeof(= x_session_id_zero.id))

static inline boo= l
-session_id_equal(con= st struct session_id *sid1,
- const struct session_id *sid2)
+session_id_equal(const struct session_id = *sid1, const struct session_id *sid2)
{
= return !memcmp(sid1->id, sid2->id, SID_SIZE);
}
diff --git a/src/openvpn/shaper.c b/src/openvpn/shaper.c
index 1c8cfb3..fb2621e 100644
--- a/src/openvp= n/shaper.c
+++ b/src/openvpn/shaper.c
@@ -8= 6,6 +86,5 @@
void
shaper_msg(struct shape= r *s)
{
- = s->bytes_per_second);
+ msg(M_INFO, "Output Traffic Shaping initialized at %d bytes = per second", s->bytes_per_second);
}
diff --git a/src/openvpn/shaper.h b/src/openvpn/shaper.h

index 9996b08..4483d15 100644

--- a/src/openvpn/shaper.h
+++ b/src/openvpn/shaper.h
@@ -36,10 +36,10 = @@
* the output direction.
*/
-#define SHAPE= R_MIN 100 /* bytes per second */
+#define SHAPER_MIN 100 /* bytes per second */<= br> #define SHAPER_MAX 100000000

-#define SHAPER_MAX_TIMEOUT 10 /* secon= ds */
+#define SHAPER= _MAX_TIMEOUT 10 /* seconds */

#define SH= APER_USE_FP

@@ -125,11 +125,12 @@<= br> /* compute delay in microseconds */
tv.t= v_sec =3D 0;
#ifdef SHAPER_USE_FP
- tv.tv_usec =3D min_int((int)((double)max_i= nt(nbytes, 100) * s->factor), (SHAPER_MAX_TIMEOUT*1000000));
<= span style=3D"color: hsl(120, 100%, 40%);">+ tv.tv_usec =3D

+ min_int((int)((double)ma= x_int(nbytes, 100) * s->factor), (SHAPER_MAX_TIMEOUT * 1000000));
=
#else
tv.tv_usec =3D s->bytes_per_second=
- ? mi= n_int(max_int(nbytes, 100) * s->factor, (SHAPER_MAX_TIMEOUT*1000000))
- : 0;
+ ?= min_int(max_int(nbytes, 100) * s->factor, (SHAPER_MAX_TIMEOUT * 1000000= ))
+ = : 0;
#endif

if = (tv.tv_usec)
@@ -138,11 +139,9 @@
= tv_add(&s->wakeup, &tv);

#ifd= ef SHAPER_DEBUG
- = dmsg(D_SHAPER_DEBUG, "SHAPER shaper_wrote_bytes bytes=3D%d delay=3D%= ld sec=3D%" PRIi64 " usec=3D%ld",
- nbytes,
- (long)tv.tv_usec,
- (int64_t)s->wakeup.tv_se= c,
- (long)= s->wakeup.tv_usec);
+ "SHAPER shaper_wrote_bytes bytes=3D%d delay= =3D%ld sec=3D%" PRIi64 " usec=3D%ld", nbytes,
+ (long)tv.tv_usec, (in= t64_t)s->wakeup.tv_sec, (long)s->wakeup.tv_usec);

#e= ndif
}
}
diff --git a= /src/openvpn/sig.c b/src/openvpn/sig.c
index 02df5e0..5f5a8= 08 100644
--- a/src/openvpn/sig.c
+++ b/src= /openvpn/sig.c
@@ -43,20 +43,19 @@
=
struct signal_info siginfo_static; /* GLOBAL */
=
-struct signame {
+struct signame+{
int v= alue;
int priority;
const char *u= pper;
const char *lower;
};
-static const = struct signame signames[] =3D {
- { SIGINT, 5, "SIGINT", "sigint"},=
- { SIGTERM, 4, "SIGT= ERM", "sigterm" },
- { SIGHUP, 3, "SIGHUP", "sighup" },
- { SIGUSR1, 2, "S= IGUSR1", "sigusr1" },
- { SIGUSR2, 1, "SIGUSR2", "sigusr2" }=
-};
+static const struct signame signames[]= =3D { { SIGINT, 5, "SIGINT", "sigint" },
+ = { SIGTERM, 4, "SIGTERM", "sigterm" },
<= br>+ = { SIGHUP, 3, "SIGHUP", "sighup" },
+ = { SIGUSR1, 2, "SIGUSR1", "sigusr1" }= ,
+ = { SIGUSR2, 1, "SIGUSR2", "sigusr2&q= uot; } };

/* mask for hard signals from = management or windows */
static unsigned long long ignored= _hard_signals_mask;
@@ -209,8 +208,7 @@
= if (try_throw_signal(&siginfo_static, signum, SIG_SOURCE_SOFT))
{
siginfo_static.signal_text =3D s= ignal_text;
- ms= g(D_SIGNAL_DEBUG, "Throw signal (soft): %s (%s)", signal_name(sig= num, true),
- = signal_text);
+ = msg(D_SIGNAL_DEBUG, "Throw signal (soft): %s (%s)", signal_na= me(signum, true), signal_text);
}
= else
{
@@ -241,8 +239,7 @@
= {
si->source =3D SIG_SOURCE_= CONNECTION_FAILED;
}
- msg(D_SIGNAL_DEBUG, "register signal: = %s (%s)", signal_name(signum, true),
- signal_text);
+ msg(D_SIGNAL_DEBUG, "register signal= : %s (%s)", signal_name(signum, true), signal_text);
= }
else
{
@@ -= 330,7 +327,8 @@
break;

default:
- msg(msglevel, "Unknown signal %d [%s,%s= ] received by %s", si->signal_received, hs, type, t);
+ msg(msglevel, &qu= ot;Unknown signal %d [%s,%s] received by %s", si->signal_received, = hs,

+ = type, t);
break;
= }
}
@@ -365,13 +363,10 @@
if (state >=3D 0)
= {
- ma= nagement_set_state(management,
- state,
- si->signal_t= ext ? si->signal_text : signal_name(si->signal_received, true),
- = NULL,
- = NULL,
- NULL,
- NULL);
<= span style=3D"color: hsl(120, 100%, 40%);">+ management_set_stat= e(management, state,

= + si->signal_text ? si->signal_text
+ = : signal_name(si->signal_received, true),
+ = NULL, NULL, NULL, NULL);
}
}

#endif /* ifdef ENABLE_MANAGEMENT */
= @@ -401,7 +396,7 @@
struct sigaction sa;<= br> CLEAR(sa);

- sigfillset(&block_mask); /* all signals */
+ sigfillset(&blo= ck_mask); /* all signals */
sa.sa_handler =3D signal_= handler;
sa.sa_mask =3D block_mask; /* signals blocke= d inside the handler */
sa.sa_flags =3D SA_RESTART; /*= match with the behaviour of signal() on Linux and BSD */
@= @ -430,9 +425,9 @@
struct sigaction sa;
CLEAR(sa);


- sigfillset(&block_mask); /* all signals */
= + sigfillset(&block_mask= ); /* all signals */
sa.sa_handler =3D signal_handler= ;
- sa.sa_mask =3D b= lock_mask; /* signals blocked inside the handler */
+ sa.sa_mask =3D block_mask; /* signal= s blocked inside the handler */
sa.sa_flags =3D SA_RES= TART; /* match with the behaviour of signal() on Linux and BSD */
signal_mode =3D SM_POST_INIT;
@@ -498,8 +493,10 @@

status_printf(so, "Updated,= %s", time_string(0, 0, false, &gc));
status_p= rintf(so, "TUN/TAP read bytes," counter_format, c->c2.tun_read= _bytes);
status_printf(so, "TUN/TAP write bytes,&= quot; counter_format, c->c2.tun_write_bytes);
- status_printf(so, "TCP/UDP read bytes,&= quot; counter_format, c->c2.link_read_bytes + c->c2.dco_read_bytes);<= /span>
- status_printf(so, = "TCP/UDP write bytes," counter_format, c->c2.link_write_bytes = + c->c2.dco_write_bytes);
+ status_printf(so, "TCP/UDP read bytes," counter_form= at,
+ = c->c2.link_read_bytes + c->c2.dco_read_bytes);
+ status_printf(so, "TCP/UDP writ= e bytes," counter_format,
+ c->c2.link_write_bytes + c->c2.dco_write= _bytes);
status_printf(so, "Auth read bytes,"= ; counter_format, c->c2.link_read_bytes_auth);
#ifdef U= SE_COMP
if (c->c2.comp_context)
@@ = -565,12 +562,13 @@
void
process_explicit_= exit_notification_timer_wakeup(struct context *c)
{=
- if (event_timeout_trigge= r(&c->c2.explicit_exit_notification_interval,
- &c->c2= .timeval,
+ if (ev= ent_timeout_trigger(&c->c2.explicit_exit_notification_interval, &= ;c->c2.timeval,
ETT_DEFAU= LT))
{
- ASSERT(c->c2.explicit_exit_notification_time_wait &&am= p; c->options.ce.explicit_exit_notification);
- if (now >=3D c->c2.explicit_exit_n= otification_time_wait + c->options.ce.explicit_exit_notification)=
+ ASSERT(c->c2.ex= plicit_exit_notification_time_wait
+ && c->options.ce.explicit_exit_not= ification);
+ = if (now >=3D c->c2.explicit_exit_notification_time_wait
+ + c->op= tions.ce.explicit_exit_notification)

{
<= span> event_timeout_clear(&c->c2.explicit_exit_notificat= ion_interval);

register_signal(c->sig, SIGT= ERM, "exit-with-notification");
@@ -608,8 +606,7 = @@
process_sigterm(struct context *c)
{
bool ret =3D true;
- if (c->options.ce.explicit_exit_notification=
- && !c->c2= .explicit_exit_notification_time_wait)
+ if (c->options.ce.explicit_exit_notification &= ;& !c->c2.explicit_exit_notification_time_wait)
= {
process_explicit_exit_notification_init(c);
ret =3D false;
diff --git a/src/openv= pn/sig.h b/src/openvpn/sig.h
index 93219f7..7e5dd9f 100644<= /span>
--- a/src/openvpn/sig.h
+++ b/src/openvpn/s= ig.h
@@ -26,8 +26,8 @@
#include "stat= us.h"
#include "win32.h"
<= /span>
-#define SIG_SOURCE_SOF= T 0
-#define SIG_SOURCE= _HARD 1
+#define SIG_= SOURCE_SOFT 0
+#define SIG_SOURCE_HARD 1
/* CONNECTIO= N_FAILED is also a "soft" status,
* It is throw= n if a connection attempt fails
*/
diff -= -git a/src/openvpn/socket.c b/src/openvpn/socket.c
index 85= 10e1d..8fc10bc 100644
--- a/src/openvpn/socket.c
= +++ b/src/openvpn/socket.c
@@ -60,8 +60,7 @@ * Convert sockflags/getaddr_flags into getaddr_flags
*/

static unsigned int
-sf2gaf(const unsigned int getaddr_flags,
= - const unsigned int sockfl= ags)
+sf2gaf(const un= signed int getaddr_flags, const unsigned int sockflags)
{<= /span>
if (sockflags & SF_HOST_RANDOMIZE)
{

@@ -77,9 +76,8 @@
* Functions rel= ated to the translation of DNS names to IP addresses.
*/<= /span>
static int
-get_addr_generic(sa_family_t af, unsigned int flags, const char *host= name,
- = void *network, unsigned int *netbits,
- int resolve_retry_seconds, struct signal_= info *sig_info,
+get_= addr_generic(sa_family_t af, unsigned int flags, const char *hostname, void= *network,
+ = unsigned int *netbits, int resolve_retry_seconds, struct signal_inf= o *sig_info,
int msglevel)
{

char *endp, *sep, *var_host =3D NULL;
<= span>@@ -108,9 +106,7 @@

break;

default:
- msg(M_WARN,
- "Unsupported AF family passed to get= addrinfo for %s (%d)",
- hostname, af);
+ msg(M_WARN, "Unsupported AF family passed= to getaddrinfo for %s (%d)", hostname, af);
= goto out;
}

@@ -= 122,8 +118,7 @@
var_host =3D strdup(hostname);<= br> if (!var_host)
{
- msg(M_NONFATAL | M_ERRNO,- "Can't all= ocate hostname buffer for getaddrinfo");
+ msg(M_NONFATAL | M_ERRNO, "Can't= allocate hostname buffer for getaddrinfo");
= goto out;
}

@@ -134,= 15 +129,14 @@
bits =3D strtoul(sep + 1, &endp,= 10);
if ((*endp !=3D '\0') || (bits > = max_bits))
{
- msg(msglevel, "IP prefix '%s': inv= alid '/bits' spec (%s)", hostname,
- sep + 1);
+ msg(msglevel, "IP prefix= '%s': invalid '/bits' spec (%s)", hostname, sep + 1);=
goto out;
} *sep =3D '\0';
}

- ret =3D open= vpn_getaddrinfo(flags & ~GETADDR_HOST_ORDER, var_host, NULL,
= - re= solve_retry_seconds, sig_info, af, &ai);
+ ret =3D openvpn_getaddrinfo(flags & ~GETAD= DR_HOST_ORDER, var_host, NULL, resolve_retry_seconds,
+ sig_info, a= f, &ai);
if ((ret =3D=3D 0) && network)
{
struct in6_addr *ip6;<= br>@@ -167,8 +161,7 @@

= default:
/* can't get here because &#= 39;af' was previously checked */
- msg(M_WARN,
- "Unsupported AF family for %s= (%d)", var_host, af);
+ msg(M_WARN, "Unsupported AF family for %s (%d)= ", var_host, af);
goto out; }
}
@@ -191,19 +184,15= @@
}

in_addr_t<= br>-getaddr(unsigned int flags,
- const char *hos= tname,
- int res= olve_retry_seconds,
- = bool *succeeded,
- status =3D get_addr_generic(AF_INET, flags, hostname, &= addr, NULL,
- = resolve_retry_seconds, sig_info,
- M_WARN);
- if (status=3D=3D0)
+ status =3D get_addr= _generic(AF_INET, flags, hostname, &addr, NULL, resolve_retry_seconds,<= /span>
+ = sig_info, M_WARN);
+ if (status =3D=3D 0)
{
= if (succeeded)
{
@@ -222,16= +211,15 @@
}

bool
-get_ipv6_addr(const char *= hostname, struct in6_addr *network,
- unsigned int *netbits, int msglevel)
= +get_ipv6_addr(const char *host= name, struct in6_addr *network, unsigned int *netbits, int msglevel)=
{
- if (g= et_addr_generic(AF_INET6, GETADDR_RESOLVE, hostname, network, netbits,
- 0= , NULL, msglevel) < 0)
+ if (get_addr_generic(AF_INET6, GETADDR_RESOLVE, hostname, network= , netbits, 0, NULL, msglevel)
+ < 0)
{
r= eturn false;
}

- return true; /* parsing = OK, values set */
+ = return true; /* parsing OK, values set */
}

static inline bool
@@ -256,12 +244,8= @@
* otherwise. (like getaddrinfo)
*/<= /span>
static int
-get_cached_dns_entry(struct cached_dns_entry *dns_cache,
- const char *h= ostname,

- = const char *servname,
- int ai_family,
- int resolve_flags,
- struct addrinf= o **ai)

+get_cached_d= ns_entry(struct cached_dns_entry *dns_cache, const char *hostname, const ch= ar *servname,
+ = int ai_family, int resolve_flags, struct addrinfo **ai)
{
struct cached_dns_entry *ph;
= int flags;
@@ -271,10 +255,8 @@
=
for (ph =3D dns_cache; ph; ph =3D ph->next)
{
- = if (streqnull(ph->hostname, hostname)
- && streqnull(ph->servname, se= rvname)
- &a= mp;& ph->ai_family =3D=3D ai_family
- && ph->flags =3D=3D flags)
+ if (streqnull(ph= ->hostname, hostname) && streqnull(ph->servname, servname)
+ &&= ph->ai_family =3D=3D ai_family && ph->flags =3D=3D flags)
{
*ai =3D ph->ai;
return 0;
@@ -285,28 +267,19 @@<= /span>


static int
<= span style=3D"color: hsl(0, 100%, 40%);">-do_preresolve_host(struct context= *c,

- = const char *hostname,
- const char *servname,
- const int af,
+do_preresolve_host(struct context *c, con= st char *hostname, const char *servname, const int af,
= const int flags)
{
st= ruct addrinfo *ai;
int status;

- if (get_cached_dns_entr= y(c->c1.dns_cache,
-= hostname,
- servname,
- af,- f= lags,
- = &ai) =3D=3D 0)
+ if (get_cached_dns_entry(c->c1.dns_cache, hostname, serv= name, af, flags, &ai) =3D=3D 0)
{
= /* entry already cached, return success */
= return 0;
}

- status =3D openvpn_getaddrinfo(flags, h= ostname, servname,
- = c->options.resolve_retry_seconds, NULL,
+ status =3D openvpn= _getaddrinfo(flags, hostname, servname, c->options.resolve_retry_seconds= , NULL,
af, &ai);
if (status =3D=3D 0)
{
@@ -333,7 +306,6 @@

}
<= br> gc_addspecial(ai, &gc_freeaddrinfo_callback, &c-&= gt;gc);
-
}

return status;
}
= @@ -342,10 +314,8 @@
do_preresolve(struct context *c= )
{
struct connection_list *l =3D c-&= gt;options.connection_list;
- const unsigned int preresolve_flags =3D GETADDR_RESOLVE- = |GETADDR_UPDATE_MANAGEMENT_STATE
- |GETADDR_ME= NTION_RESOLVE_RETRY
- = |GETADDR_FATAL;
+ const unsigned int preresolve_flags= =3D GETADDR_RESOLVE | GETADDR_UPDATE_MANAGEMENT_STATE
+ = | GETADDR_MENTION_RESOLVE_RETRY | GETADDR_FATAL;
=

for (int i =3D 0; i < l->len; ++i)
@@ -378,8 +348,7 @@
/* HTTP remote = hostname does not need to be resolved */
if (!ce-&= gt;http_proxy_options)
{
- status =3D do_preresolve_host(c, re= mote, ce->remote_port,
- ce->af, flags);
+ status =3D do_preres= olve_host(c, remote, ce->remote_port, ce->af, flags);

if (status !=3D 0)

{
<= span> goto err;

@@ -389,11 +358,8 @@=
/* Preresolve proxy */
if (ce-&= gt;http_proxy_options)
{
- status =3D do_preresolve_host(c,
- = ce->http_proxy_options->server,
- ce-= >http_proxy_options->port,
- ce->af,
- = preresolve_flags);

+ status =3D do_preresolve_host(c, ce->http_proxy_options-= >server,
+ = ce->http_proxy_options->port, ce->= af, preresolve_flags);

if (s= tatus !=3D 0)
{
@@ -403,11 +36= 9,8 @@

if (ce->socks_proxy_se= rver)
{
- status =3D do_preresolve_host(c,
- c= e->socks_proxy_server,
- ce->socks_proxy_port,=
- = ce->af,
= - flags);
+ status =3D
+ do_preresolve_host(c, ce-= >socks_proxy_server, ce->socks_proxy_port, ce->af, flags);<= br> if (status !=3D 0)
{
goto err;
@@ -433,10 +396,8 @= @
{
g= oto err;
}
-
}
= }
-
}

return;

@@ -= 453,9 +414,11 @@
{
switch (af)=
{
- = case AF_INET: return "[AF_INET]";
+ case AF_INET:
+ return "[AF_INET]";

- = case AF_INET6: return "[AF_INET6]";
+ case AF_INET6:
+ return "[AF_INET6]";
}
return "";
}

@@ -465,17 +428,13 @@
* If resolve= error, try again for resolve_retry_seconds seconds.
*/
int
-op= envpn_getaddrinfo(unsigned int flags,
- const char *hostname,
- const char *servnam= e,
- = int resolve_retry_seconds,
- struct signal_info *sig_info,
- int ai_family,=
+openvpn_getaddrinfo(unsign= ed int flags, const char *hostname, const char *servname,
+ int resolve_retry= _seconds, struct signal_info *sig_info, int ai_family,
= struct addrinfo **res)
{
= struct addrinfo hints;
int status;
- struct signal_info sigrec =3D {0= };

+ struct signal= _info sigrec =3D { 0 };
int msglevel =3D (flags & = GETADDR_FATAL) ? M_FATAL : D_RESOLVE_ERRORS;
struct gc= _arena gc =3D gc_new();
const char *print_hostname;
@@ -500,8 +459,7 @@
msglevel |=3D M_= MSG_VIRT_OUT;
}

- if ((flags & (GETADDR_FATAL_ON_SIG= NAL|GETADDR_WARN_ON_SIGNAL))
- && !sig_info)
+ if ((flags & (GETADDR_FATAL_ON_SIGNAL | GETADDR_WA= RN_ON_SIGNAL)) && !sig_info)
{
sig_info =3D &sigrec;

}
= @@ -533,12 +491,12 @@

status =3D get= addrinfo(hostname, servname, &hints, res);

= - if (status !=3D 0) /* parse = as numeric address failed? */
+ if (status !=3D 0) /* parse as numeric a= ddress failed? */
{
const int= fail_wait_interval =3D 5; /* seconds */
/* Add +4= to cause integer division rounding up (1 + 4) =3D 5, (0+4)/5=3D0 */=
- int resolve_retries = =3D (flags & GETADDR_TRY_ONCE) ? 1 :
- ((resolve_retry_seconds + = 4)/ fail_wait_interval);
+ int resolve_retries =3D
+ (flags & GETADDR_TRY_ONCE) ? 1 : ((resolve= _retry_seconds + 4) / fail_wait_interval);
const c= har *fmt;
int level =3D 0;

@@ -561,8 +519,7 @@
}
=
fmt =3D "RESOLVE: Cannot resolve host addres= s: %s:%s%s (%s)";
= - if ((flags & GETADDR_MENTION_RESOLVE_RETRY)
- && !resolve_retry_se= conds)
+ if ((= flags & GETADDR_MENTION_RESOLVE_RETRY) && !resolve_retry_second= s)
{
fmt =3D "RE= SOLVE: Cannot resolve host address: %s:%s%s (%s)"
= "(I would have retried this name query if you had "= ;
@@ -571,8 +528,8 @@

= if (!(flags & GETADDR_RESOLVE) || status =3D=3D EAI_FAIL)<= br> {
- = msg(msglevel, "RESOLVE: Cannot parse IP address: %s:%s (%s)&= quot;,
- = print_hostname, print_servname, gai_strerror(status));
+ msg(msglevel, "RESOLVE= : Cannot parse IP address: %s:%s (%s)", print_hostname,
+ print_servname, ga= i_strerror(status));

goto done;
}


@@ -581,12 +538,7 @@<= br> {
if (management)
= {
- = management_set_state(management,
- OPENVPN_STAT= E_RESOLVE,
- = NULL,
- NULL,
- NULL,<= /span>
- = NULL,
= + management_set_state(management, OPENVPN_STATE_RESOLVE, NU= LL, NULL, NULL, NULL,
= NULL);
}
}@@ -603,9 +555,8 @@
#endif
= /* try hostname lookup */
hints.ai_flags = &=3D ~AI_NUMERICHOST;
- dmsg(D_SOCKET_DEBUG,
- "GETADDRINFO flags=3D0x%04x ai_family= =3D%d ai_socktype=3D%d",
- flags, hints.ai_family, hints.ai_socktype);=
+ dmsg(D_SOCKET_= DEBUG, "GETADDRINFO flags=3D0x%04x ai_family=3D%d ai_socktype=3D%d&quo= t;, flags,
+ = hints.ai_family, hints.ai_socktype);
s= tatus =3D getaddrinfo(hostname, servname, &hints, res);

if (sig_info)
@@ -616,9 +56= 7,8 @@
/* why are we overwriting SIGUS= R1 ? */
if (signal_reset(sig_info, SIG= USR1) =3D=3D SIGUSR1) /* ignore SIGUSR1 */
= {
- = msg(level,
- = "RESOLVE: Ignored SIGUSR1 signal received du= ring "
- = "DNS resolution attempt");
+ msg(level, "= ;RESOLVE: Ignored SIGUSR1 signal received during "
+ &quo= t;DNS resolution attempt");
}
else
= {
@@ -650,11 +600,7 @@
le= vel =3D D_RESOLVE_ERRORS;
}
<= /span>
- msg(level,=
- fmt,<= /span>
- print_= hostname,
- = print_servname,
- = getaddrinfo_addr_family_name(ai_family),
+ msg(level, fmt, print_hostna= me, print_servname, getaddrinfo_addr_family_name(ai_family),
gai_strerror(status));


if (--resolve_retries <=3D 0)

@@ -679,9 +6= 25,8 @@
/* IP address parse succeeded */ if (flags & GETADDR_RANDOMIZE)
= {
- msg(M_W= ARN,
- &= quot;WARNING: ignoring --remote-random-hostname because the "- "hostname= is an IP address");
+ msg(M_WARN, "WARNING: ignoring --remote-random-hostn= ame because the "
- addr->s_addr =3D htonl(a<<24 | b<<16 | c= <<8 | d);
+ = addr->s_addr =3D htonl(a << 24 | b << 16 | c <<= ; 8 | d);
return OIA_IP; /* good dotted quad *= /
}
}
- if (string_class(dotted_quad, CC_DIGIT|= CC_DOT, 0))
+ if (= string_class(dotted_quad, CC_DIGIT | CC_DOT, 0))
{
return OIA_ERROR; /* probably a badly formatted dotte= d quad */
}
@@ -800,7 +745,7 @@=
/* verify that string will convert to IPv6 address */=
{
struct in6_addr a6;
- return inet_pton( AF_INET6,= ipv6_text_addr, &a6 ) =3D=3D 1;

+ return inet_pton(AF_INET6, ipv6_text_addr, &a6= ) =3D=3D 1;
}
}

@@ -810,7 +755,7 @@
if (addr)
<= span> {

const size_t len =3D strlen(addr);
- return len > 0= && len <=3D 255 && string_class(addr, CC_ALNUM|CC_DASH|= CC_DOT, 0);
+ = return len > 0 && len <=3D 255 && string_class(addr, = CC_ALNUM | CC_DASH | CC_DOT, 0);
}
= else
{
@@ -859,7 +804,7 @@
while ((c =3D *p++))
= {
- if = ( (c >=3D '0' && c <=3D '9') || (c >=3D &#= 39;a' && c <=3D 'f') || (c >=3D 'A' &= & c <=3D 'F') )
+ if ((c >=3D '0' && c <=3D '= ;9') || (c >=3D 'a' && c <=3D 'f') || (c = >=3D 'A' && c <=3D 'F'))
= {
++nnum;
= if (nnum > 2)
@@ -890,8 +835,7 @@
socklen_t len;


len =3D size= of(val);
- if (getso= ckopt(sd, SOL_SOCKET, SO_SNDBUF, (void *) &val, &len) =3D=3D 0
- && len =3D= =3D sizeof(val))
+ = if (getsockopt(sd, SOL_SOCKET, SO_SNDBUF, (void *)&val, &len) =3D= =3D 0 && len =3D=3D sizeof(val))
{
<= span> return val;

}
@@ -903,7 = +847,7 @@
socket_set_sndbuf(socket_descriptor_t sd, int si= ze)
{
#if defined(SOL_SOCKET) && = defined(SO_SNDBUF)
- = if (setsockopt(sd, SOL_SOCKET, SO_SNDBUF, (void *) &size, sizeof(size)= ) !=3D 0)
+ if (se= tsockopt(sd, SOL_SOCKET, SO_SNDBUF, (void *)&size, sizeof(size)) !=3D 0= )
{
msg(M_WARN, "NOTE: s= etsockopt SO_SNDBUF=3D%d failed", size);
}=
@@ -918,8 +862,7 @@
socklen_t len;
len =3D sizeof(val);
- if (getsockopt(sd, SOL_SOCKET, SO_RCVBUF, = (void *) &val, &len) =3D=3D 0
- && len =3D=3D sizeof(val))
+ if (getsockopt(sd, SOL_SOCKET, S= O_RCVBUF, (void *)&val, &len) =3D=3D 0 && len =3D=3D sizeof= (val))
{
return val; }
@@ -931,7 +874,7 @@
socket_= set_rcvbuf(socket_descriptor_t sd, int size)
{
<= span> #if defined(SOL_SOCKET) && defined(SO_RCVBUF)

- if (setsockopt(sd, SOL_SOCKET, SO= _RCVBUF, (void *) &size, sizeof(size)) !=3D 0)

+ if (setsockopt(sd, SOL_SOCKET, SO_RCVBUF= , (void *)&size, sizeof(size)) !=3D 0)
{ msg(M_WARN, "NOTE: setsockopt SO_RCVBUF=3D%d failed&qu= ot;, size);
return false;
@@ -941,= 31 +884,25 @@
}

void
-socket_set_buffers(socke= t_descriptor_t fd, const struct socket_buffer_size *sbs,
- bool reduce_size)
+socket_set_buffers(sock= et_descriptor_t fd, const struct socket_buffer_size *sbs, bool reduce_size)=
{
if (sbs)
{
const int sndbuf_old =3D socket_get_sndbuf(fd);
const int rcvbuf_old =3D socket_get_rcvbuf(fd);=

- if= (sbs->sndbuf
- = && (reduce_size || sndbuf_old < sbs->sndbuf))+ if (sbs->sndbuf &= amp;& (reduce_size || sndbuf_old < sbs->sndbuf))
= {
socket_set_sndbuf(fd, sbs->sndbu= f);
}

- if (sbs->rcvbuf
- && (reduce_size || rcvb= uf_old < sbs->rcvbuf))
+ if (sbs->rcvbuf && (reduce_size || rcvbuf_old &= lt; sbs->rcvbuf))
{
= socket_set_rcvbuf(fd, sbs->rcvbuf);
}<= br>
- msg= (D_OSBUF, "Socket Buffers: R=3D[%d->%d] S=3D[%d->%d]",
- rcvbuf_old,
- socket_get_r= cvbuf(fd),
- = sndbuf_old,
- = socket_get_sndbuf(fd));
+ msg(D_OSBUF, "Socket Buffers: R=3D[%d->%d] S=3D[%d-&= gt;%d]", rcvbuf_old, socket_get_rcvbuf(fd),
+ sndbuf_old, socket_get_sndbuf(fd))= ;
}
}

@@ -977,7 +914,7 @@

socket_set_tcp_nodelay(socket_descr= iptor_t sd, int state)
{
#if defined(_WIN= 32) || (defined(IPPROTO_TCP) && defined(TCP_NODELAY))
- if (setsockopt(sd, IPPROTO_TCP,= TCP_NODELAY, (void *) &state, sizeof(state)) !=3D 0)

+ if (setsockopt(sd, IPPROTO_TCP, T= CP_NODELAY, (void *)&state, sizeof(state)) !=3D 0)
= {
msg(M_WARN, "NOTE: setsockopt TCP_NODELAY= =3D%d failed", state);
return false;@@ -987,7 +924,7 @@
dmsg(D_OSBUF, "So= cket flags: TCP_NODELAY=3D%d succeeded", state);
= return true;
}
-#else /* if defined(_WIN32) || (defined(IPPROTO_TCP) &am= p;& defined(TCP_NODELAY)) */
+#else /* if defined(_WIN32) || (defined(IPPROTO_TCP) &&= ; defined(TCP_NODELAY)) */
msg(M_WARN, "NOTE: set= sockopt TCP_NODELAY=3D%d failed (No kernel support)", state); return false;
#endif
@@ -997,= 7 +934,7 @@
socket_set_mark(socket_descriptor_t sd, int ma= rk)
{
#if defined(TARGET_LINUX) &&= ; HAVE_DECL_SO_MARK
- = if (mark && setsockopt(sd, SOL_SOCKET, SO_MARK, (void *) &mar= k, sizeof(mark)) !=3D 0)
+ if (mark && setsockopt(sd, SOL_SOCKET, SO_MARK, (void *)&a= mp;mark, sizeof(mark)) !=3D 0)
{
= msg(M_WARN, "NOTE: setsockopt SO_MARK=3D%d failed", mark);
}
@@ -1065,8 +1002,7 @@
= /* set SO_REUSEADDR on socket */
{
int on =3D 1;

- (void *) &on, = sizeof(on)) < 0)
+= if (setsockopt(sd, SOL_SOCKET, SO_REUSEADDR, (void *)&on, sizeo= f(on)) < 0)
{
msg(= M_ERR, "TCP: Cannot setsockopt SO_REUSEADDR on TCP socket");
}
@@ -1099,31 +1035,29 @@
if (addrinfo->ai_family =3D=3D AF_INET)

= {
#if defined(HAVE_IN_PKTINFO) && defined(HA= VE_IPI_SPEC_DST)
- = if (setsockopt(sd, SOL_IP, IP_PKTINFO,
- (void *)&pad, sizeof= (pad)) < 0)
+ = if (setsockopt(sd, SOL_IP, IP_PKTINFO, (void *)&pad, sizeof(pad)= ) < 0)
{
m= sg(M_ERR, "UDP: failed setsockopt for IP_PKTINFO");
}

#elif defined(IP_RECVDSTADDR)
= - if (setsockopt(sd, I= PPROTO_IP, IP_RECVDSTADDR,
- (void *)&pad, sizeof(pad)) < 0)
+ if (setsocko= pt(sd, IPPROTO_IP, IP_RECVDSTADDR, (void *)&pad, sizeof(pad)) < 0)
{
msg(M_ERR, &= quot;UDP: failed setsockopt for IP_RECVDSTADDR");
= }
-#else /* i= f defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST) */<= br>+#else /* if defined(HAVE_IN= _PKTINFO) && defined(HAVE_IPI_SPEC_DST) */
#error = ENABLE_IP_PKTINFO is set without IP_PKTINFO xor IP_RECVDSTADDR (fix syshead= .h)
#endif
}
= else if (addrinfo->ai_family =3D=3D AF_INET6)
= {
#ifndef IPV6_RECVPKTINFO /* Some older Darwin platfo= rms require this */
- = if (setsockopt(sd, IPPROTO_IPV6, IPV6_PKTINFO,
- (void *)&= pad, sizeof(pad)) < 0)
+ if (setsockopt(sd, IPPROTO_IPV6, IPV6_PKTINFO, (void *)&a= mp;pad, sizeof(pad)) < 0)
#else
- if (setsockopt(sd, IPPROTO_IPV6= , IPV6_RECVPKTINFO,
- = (void *)&pad, sizeof(pad)) < 0)
<= span style=3D"color: hsl(120, 100%, 40%);">+ if (setsockopt(sd, = IPPROTO_IPV6, IPV6_RECVPKTINFO, (void *)&pad, sizeof(pad)) < 0)
#endif
- = { msg(M_ERR, "UDP: failed setsockopt for IPV6_RECVPKTINFO&qu= ot;);}
+ {=
+ msg= (M_ERR, "UDP: failed setsockopt for IPV6_RECVPKTINFO");+ }
}

}
#endif /* if ENABLE_IP_= PKTINFO */
@@ -1143,14 +1077,12 @@
{
if (sock->socks_proxy && sock->info.p= roto =3D=3D PROTO_UDP)
{
- socket_bind(sock->ctrl_sd, sock-= >info.lsa->bind_local,
- ai_family, "SOCKS", false);=
+ socket_bind(so= ck->ctrl_sd, sock->info.lsa->bind_local, ai_family, "SOCKS&qu= ot;, false);
}
else
{
-= socket_bind(sock->sd, sock->info.lsa->bind_local,
- ai= _family,
- = "TCP/UDP", sock->info.bind_ipv6_only);
+ socket_bind(sock->= ;sd, sock->info.lsa->bind_local, ai_family, "TCP/UDP",
+ = sock->info.bind_ipv6_only);
}
= }
}
@@ -1198,11 +1130,12 @@
= if (sock->bind_dev)
{
= msg(M_INFO, "Using bind-dev %s", sock->bind_dev);
- if (setsockopt(sock= ->sd, SOL_SOCKET, SO_BINDTODEVICE, sock->bind_dev, strlen(sock->bi= nd_dev) + 1) !=3D 0)
= + if (setsockopt(sock->sd, SOL_SOCKET, SO_BINDTODEVICE, sock->= bind_dev,
+ = strlen(sock->bind_dev) + 1)
+ !=3D 0)
{
- msg(M_WARN|M_E= RRNO, "WARN: setsockopt SO_BINDTODEVICE=3D%s failed", sock->bi= nd_dev);
+ = msg(M_WARN | M_ERRNO, "WARN: setsockopt SO_BINDTODEVICE=3D%s failed&q= uot;, sock->bind_dev);
}
-
}
#e= ndif

@@ -1237,9 +1170,7 @@
* Functions used for establishing a TCP stream connection.

*/

static void
-socket_do_listen(socket_descriptor_t sd,
- const struct addrinfo *= local,
- = bool do_listen,
+so= cket_do_listen(socket_descriptor_t sd, const struct addrinfo *local, bool d= o_listen,
bool do_set_nonblock) {
struct gc_arena gc =3D gc_new();
<= span>@@ -1264,9 +1195,7 @@

}

<= span> socket_descriptor_t

-socket_do_accept(socket_descriptor_t sd,
- struct link_socket_actual *act,
- const bo= ol nowait)
+socket_do= _accept(socket_descriptor_t sd, struct link_socket_actual *act, const bool = nowait)
{
/* af_addr_size WILL return= 0 in this case if AFs other than AF_INET
* are compi= led because act is empty here.
@@ -1314,7 +1243,8 @@=
/* only valid if we have remote_len_af!=3D0 */
else if (remote_len_af && remote_len !=3D remote_len_af)
{
- = msg(D_LINK_ERRORS, "TCP: Received strange incoming connection w= ith unknown address length=3D%d", remote_len);
+ msg(D_LINK_ERRORS,
+ "TCP: Received st= range incoming connection with unknown address length=3D%d", remote_le= n);

openvpn_close_socket(new_sd);
= new_sd =3D SOCKET_UNDEFINED;
}
@@ -1331,19 +1261,14 @@

tcp_connection_established(const= struct link_socket_actual *act)
{
st= ruct gc_arena gc =3D gc_new();
- msg(M_INFO, "TCP connection established with %s",
- print_link_socke= t_actual(act, &gc));
+ msg(M_INFO, "TCP connection established with %s", print_= link_socket_actual(act, &gc));
gc_free(&gc);
}

static socket_descript= or_t
-socket_listen_acc= ept(socket_descriptor_t sd,
- struct link_socket_actual *act,
- const char *remot= e_dynamic,
- = const struct addrinfo *local,
- bool do_listen,
- bool nowait,- volatile = int *signal_received)
+socket_listen_accept(socket_descriptor_t sd, struct link_socket_actual *a= ct,
+ = const char *remote_dynamic, const struct addrinfo *local, bool do_list= en,
+ = bool nowait, volatile int *signal_received)
{<= br> struct gc_arena gc =3D gc_new();
/* stru= ct openvpn_sockaddr *remote =3D &act->dest; */
@@ -1= 397,8 +1322,7 @@

if (ai &= ;& !addrlist_match(&remote_verify, ai))
= {
- ms= g(M_WARN,
- = "TCP NOTE: Rejected connection attempt from %s due to --remote= setting",
+ = msg(M_WARN, "TCP NOTE: Rejected connection attempt from %s= due to --remote setting",
print_= link_socket_actual(act, &gc));
if (ope= nvpn_close_socket(new_sd))
{
@@ -1430,10 +1354,7 @@

}

void

-socket_bind(= socket_descriptor_t sd,
- struct addrinfo *local,
- int ai_family,
- const char *prefix,
+socket_bind(socket_descriptor_t sd, struc= t addrinfo *local, int ai_family, const char *prefix,
= bool ipv6only)
{
struct gc_ar= ena gc =3D gc_new();
@@ -1460,33 +1381,30 @@
}

if (!cur)
{
- msg(M_FATAL, "%s: Soc= ket bind failed: Addr to bind has no %s record",

- prefix, addr_family_name(ai_fam= ily));
+ msg(M= _FATAL, "%s: Socket bind failed: Addr to bind has no %s record", = prefix,
+ = addr_family_name(ai_family));
}

if (ai_family =3D=3D AF_INET6)
{
- int v6only =3D ipv= 6only ? 1 : 0; /* setsockopt must have an "int" */
+ int v6only =3D ipv6only ?= 1 : 0; /* setsockopt must have an "int" */


msg(M_INFO, "setsockopt(IPV6_V6ONLY=3D%d)",= v6only);
- if (= setsockopt(sd, IPPROTO_IPV6, IPV6_V6ONLY, (void *) &v6only, sizeof(v6on= ly)))
+ if (se= tsockopt(sd, IPPROTO_IPV6, IPV6_V6ONLY, (void *)&v6only, sizeof(v6only)= ))
{
- msg(M_NONFATAL|M_ERRNO, "Setting IPV6_V6ONLY=3D%d = failed", v6only);
- = msg(M_FATAL | M_ERRNO, "%s: Socket bind failed on local address %s&qu= ot;,
- prefi= x,
+ msg(M_FAT= AL | M_ERRNO, "%s: Socket bind failed on local address %s", prefi= x,
print_sockaddr_ex(local->ai_addr, "= :", PS_SHOW_PORT, &gc));
}
= gc_free(&gc);
}

= int
-openvpn_connect(so= cket_descriptor_t sd,
-= const struct sockaddr *remote,
- int connect_timeout,
+openvpn_connect(socket_descriptor= _t sd, const struct sockaddr *remote, int connect_timeout,

= volatile int *signal_received)
{ int status =3D 0;
@@ -1506,7 +1424,7 @@=
#else
status =3D=3D EINPROGRESS<= br> #endif
- = )
+ ) {
while (true)
= {
@@ -1561,7 +1479,7 @@
= socklen_t len;

len =3D s= izeof(val);
- = if (getsockopt(sd, SOL_SOCKET, SO_ERROR, (void *) &val, &len)= =3D=3D 0
+ = if (getsockopt(sd, SOL_SOCKET, SO_ERROR, (void *)&val, &len) = =3D=3D 0
&& len =3D=3D sizeof(= val))
{
= status =3D val;
@@ -1586,43 +1504,31 @@
=
if (ai->ai_family =3D=3D AF_INET)
{

- actual= ->dest.addr.in4 =3D
= - *((struct sockaddr_in *) ai->ai_addr);
+ actual->dest.addr.in4 =3D *((= struct sockaddr_in *)ai->ai_addr);
}
else if (ai->ai_family =3D=3D AF_INET6)

{
- actual->dest.= addr.in6 =3D
- = *((struct sockaddr_in6 *) ai->ai_addr);
+ actual->dest.addr.in6 =3D *((struct so= ckaddr_in6 *)ai->ai_addr);
}
e= lse
{
ASSERT(0);
}

-
= }

static void
-socket_connect(socket_descriptor_t *sd,
- const st= ruct sockaddr *dest,
- = const int connect_timeout,
+socket_connect(socket_descriptor_t *sd, const struct s= ockaddr *dest, const int connect_timeout,
s= truct signal_info *sig_info)
{
struct= gc_arena gc =3D gc_new();
int status;

- msg(M_INFO, &qu= ot;Attempting to establish TCP connection with %s",
- print_sockaddr(dest, &gc));<= /span>
+ msg(M_INFO, &quo= t;Attempting to establish TCP connection with %s", print_sockaddr(dest= , &gc));

#ifdef ENABLE_MANAGEMENT
if (management)
{
- management_set_state(management= ,
- = OPENVPN_STATE_TCP_CONNECT,
- NULL,
- NULL,
- NULL,<= /span>
- = NULL,
- = NULL);
+ management_set_state(management, OPENVPN_STATE_TCP_CONNECT, = NULL, NULL, NULL, NULL, NULL);
}
#end= if

@@ -1637,9 +1543,8 @@
=
if (status)
{
-
- msg(D_LINK_ERRORS, "TCP: connect to %s failed: = %s",
- = print_sockaddr(dest, &gc), strerror(status));
+ msg(D_LINK_ERRORS, "TCP: connect= to %s failed: %s", print_sockaddr(dest, &gc),
+ strerror(status));
openvpn_close_socket(*sd);
*sd =3D SOCKET_UNDEFINED;

@@ -1647,8 +1552,7 @@=
}
else
{
- msg(M_INFO, &quo= t;TCP connection established with %s",
- print_sockaddr(dest, &gc));+ msg(M_INFO, "TCP= connection established with %s", print_sockaddr(dest, &gc));
}

done:
@@ -1661,15 +1565,12 @@

* such as TCP.
= */

-= static void
-stream_buf= _init(struct stream_buf *sb, struct buffer *buf,
- const unsigned int sockflags, co= nst int proto);
+stat= ic void stream_buf_init(struct stream_buf *sb, struct buffer *buf, const un= signed int sockflags,
+ const int proto);
-static void
-stream_buf_close(struct stream_buf *sb);<= /span>
+static void stream_b= uf_close(struct stream_buf *sb);

-static bool
-stream_buf_added(struct stream_buf *sb, int length_added= );
+static bool strea= m_buf_added(struct stream_buf *sb, int length_added);

/* For stream protocols, allocate a buffer to build up packet= .
* Called after frame has been finalized. */
<= span>@@ -1687,16 +1588,12 @@

if (link_socket_connectio= n_oriented(sock))
{
#ifdef _WIN32
- stream_buf_init(&= amp;sock->stream_buf,
- sock->sockfla= gs,
+ stream_b= uf_init(&sock->stream_buf, &sock->reads.buf_init, sock->so= ckflags,
sock->info.proto);
#else
alloc_buf_sock_tun(&sock-&= gt;stream_buf_data, frame);

- stream_buf_init(&sock->stream_buf,
- = &sock->stream_buf_data,
- sock->sockflags,
+ stream_buf_init(&sock->str= eam_buf, &sock->stream_buf_data, sock->sockflags,
sock->info.proto);

#endif
}
@@ -1710,8 +1607,7 @@
= /* resolve local address if undefined */
if (!sock= ->info.lsa->bind_local)
{
- int flags =3D GETADDR_RESOLVE | GET= ADDR_WARN_ON_SIGNAL
- = |GETADDR_FATAL | GETADDR_PASSIVE;
+ int flags =3D GETADDR_RESOLVE | G= ETADDR_WARN_ON_SIGNAL | GETADDR_FATAL | GETADDR_PASSIVE;
= int status;

if (proto_is_= dgram(sock->info.proto))
@@ -1720,24 +1616,19 @@<= br> }

/* will retu= rn AF_{INET|INET6}from local_host */
- status =3D get_cached_dns_entry(sock->dns_cache,<= /span>
- = sock->local_host,
- sock->local_port,
- = af,
- = flags,
- &sock->inf= o.lsa->bind_local);
+ flags, &sock->in= fo.lsa->bind_local);

if (stat= us)
{
- status =3D openvpn_getaddrinfo(flags, sock->local_h= ost, sock->local_port, 0,
- NULL, af, &sock->inf= o.lsa->bind_local);
+ &sock->info.ls= a->bind_local);
}

<= span style=3D"color: hsl(0, 100%, 40%);">- if (status !=3D0)
<= br>+ if (status !=3D 0)<= /span>
{
- msg(M_FATAL, "getaddrinfo() failed for local \"%= s:%s\": %s",
= - sock->local_host, sock->local_port,
- gai_strerror(status));=
+ msg(M_F= ATAL, "getaddrinfo() failed for local \"%s:%s\": %s", s= ock->local_host,
+= sock->local_port, gai_strerror(status));
}


/* the address famil= y returned by openvpn_getaddrinfo() should be
@@ -1759,9 +1= 650,7 @@
}

static void<= /span>
-resolve_remote(struct = link_socket *sock,
- = int phase,
= - const char **remote_dynamic,
+resolve_remote(struct link_socket *sock, int phase= , const char **remote_dynamic,
struct signa= l_info *sig_info)
{
volatile int *sig= nal_received =3D sig_info ? &sig_info->signal_received : NULL;
@@ -1772,7 +1661,8 @@
{
= if (sock->remote_host)
{
- unsigned int flags =3D sf2= gaf(GETADDR_RESOLVE|GETADDR_UPDATE_MANAGEMENT_STATE, sock->sockflags);
+ unsigned = int flags =3D
+ = sf2gaf(GETADDR_RESOLVE | GETADDR_UPDATE_MANAGEMENT_STATE, sock-&g= t;sockflags);
int retry =3D 0;
int status =3D -1;

struct addrin= fo *ai;
@@ -1819,15 +1709,12 @@
= }


- status =3D get_cached_dns_entry(sock->dns_= cache,
- = sock->remote_host,
- sock-&= gt;remote_port,
- = sock->info.af,
- f= lags, &ai);
+ = status =3D get_cached_dns_entry(sock->dns_cache, sock->remote= _host, sock->remote_port,
+ sock->info.af, flags,= &ai);
if (status)
= {
- = status =3D openvpn_getaddrinfo(flags, sock->remote_host, sock->remo= te_port,
- = retry, sig_info, sock->info.af, &ai)= ;
+ st= atus =3D openvpn_getaddrinfo(flags, sock->remote_host, sock->remote_p= ort, retry,
+ = sig_info, sock->info.af, &ai);<= /span>
}

= if (status =3D=3D 0)
@@ -1835,19 +1722,14 @@
<= span> sock->info.lsa->remote_list =3D ai;

<= span> sock->info.lsa->current_remote =3D ai;

- = dmsg(D_SOCKET_DEBUG,
- flags,
- phase,
- retry,
- signal_received ? *sig= nal_received : -1,
- = status);
+ dmsg(D_SOCKET_DEBUG, "RESOLVE_REMOTE flags=3D0x= %04x phase=3D%d rrs=3D%d sig=3D%d status=3D%d",
+ flags, phase, retry,= signal_received ? *signal_received : -1, status);
= }
if (signal_received && *signal_= received)
{
g= oto done;
}
- if (status!=3D0)
+ if (status !=3D 0)
= {
if (signal_received)=
{
@@ -1874,8 +1756,7 @@ CLEAR(sock->info.lsa->actual);
= if (sock->info.lsa->current_remote)
{
- set_actual_a= ddress(&sock->info.lsa->actual,
- sock->info.lsa->cu= rrent_remote);
+ = set_actual_address(&sock->info.lsa->actual, sock->info.= lsa->current_remote);
}
}<= /span>

@@ -1884,7 +1765,6 @@
}<= /span>


-
struct link_socket *
link_= socket_new(void)
{
@@ -2077,8 +1957,7 @@
}
ASSERT(cur);
<= span> msg(msglevel, "%s link local (bound): %s",
- proto2ascii(sock-&= gt;info.proto, sock->info.af, true),
- print_sockaddr(cur->ai_addr, &gc));
+ proto2asci= i(sock->info.proto, sock->info.af, true), print_sockaddr(cur->ai_a= ddr, &gc));
}
else
= {
@@ -2087,12 +1966,8 @@
}<= /span>

/* print active remote address */
- msg(msglevel, "= %s link remote: %s",
- proto2ascii(sock->info.proto, sock->info.af, true),
- print_link_socket_a= ctual_ex(&sock->info.lsa->actual,
- ":",
- = PS_SHOW_PORT_IF_DEFINED,
- &gc));
+ msg(msglevel, "%s link r= emote: %s", proto2ascii(sock->info.proto, sock->info.af, true),<= /span>
+ print_link_s= ocket_actual_ex(&sock->info.lsa->actual, ":", PS_SHOW_P= ORT_IF_DEFINED, &gc));
gc_free(&gc); }

@@ -2105,26 +1980,17 @@<= br> switch (sock->mode)
{
case LS_MODE_DEFAULT:

- sock->sd =3D socket_listen_accept(sock->sd,
- = &sock->info.lsa->actual,
- = remote_dynamic,
- = sock->info.lsa->bind_local,
- = true,
- false,
- = signal_received);
+= sock->sd =3D
+ socket_listen_accept(sock->sd, &sock->inf= o.lsa->actual, remote_dynamic,
+ sock->info.lsa->bi= nd_local, true, false, signal_received);
break= ;

case LS_MODE_TCP_LISTEN:
- socket_do_liste= n(sock->sd,
- = sock->info.lsa->bind_local,
- true,=
- = false);
+ = socket_do_listen(sock->sd, sock->info.lsa->bind_local, true, fals= e);
break;

= case LS_MODE_TCP_ACCEPT_FROM:
- sock->sd =3D socket_do_accept(sock->sd,
- = &sock->info.lsa->actual,
- fal= se);
+ soc= k->sd =3D socket_do_accept(sock->sd, &sock->info.lsa->actua= l, false);
if (!socket_defined(sock->sd))
{
register_sig= nal(sig_info, SIGTERM, "socket-undefined");
@@ -2= 145,10 +2011,8 @@
bool proxy_retry =3D false; do
{
- socket_connect(&sock->sd,
- sock->info.ls= a->current_remote->ai_addr,
- get_server_poll_remaining_time(sock->= server_poll_timeout),
-= sig_info);
+ socket_connect(&sock->sd, sock->info.lsa-&g= t;current_remote->ai_addr,
+ get_server_poll_remaining_time(sock->se= rver_poll_timeout), sig_info);

i= f (sig_info->signal_received)
{
@@ -2157,21 +2021,14 @@


if (soc= k->http_proxy)
{
- proxy_retry =3D establish_http_proxy_pas= sthru(sock->http_proxy,
- sock->sd,
- = sock->proxy_dest_host,
- = sock->proxy_dest_port,
- = sock->server_poll_timeout,
- &soc= k->stream_buf.residual,
- sig_info);
+ proxy_retry= =3D establish_http_proxy_passthru(
+ sock->http_proxy, sock->sd, sock->= proxy_dest_host, sock->proxy_dest_port,
+ sock->server_poll_timeout, &s= ock->stream_buf.residual, sig_info);
} else if (sock->socks_proxy)
{<= /span>
- establish_= socks_proxy_passthru(sock->socks_proxy,
- sock->sd= ,
- = sock->proxy_dest_host,
- sock-= >proxy_dest_port,
- = sock->server_poll_timeout,
+ establish_s= ocks_proxy_passthru(sock->socks_proxy, sock->sd, sock->proxy_dest_= host,
+ = sock->proxy_dest_port, sock->server_poll= _timeout,
sig_i= nfo);
}
if (proxy_retry)<= /span>
@@ -2181,27 +2038,21 @@
}
} while (proxy_retry);
-
}

static void
phase2_socks_client(struct link_so= cket *sock, struct signal_info *sig_info)
{
- socket_connect(&sock->ctr= l_sd,

- = sock->info.lsa->current_remote->ai_addr,
- get_server_poll_remainin= g_time(sock->server_poll_timeout),
- sig_info);
+ socket_connect(&sock->ctrl_sd, sock-&g= t;info.lsa->current_remote->ai_addr,
+ get_server_poll_remaining_time(so= ck->server_poll_timeout), sig_info);

= if (sig_info->signal_received)
{
return;

}

- establish_socks_proxy_udpassoc(so= ck->socks_proxy,

- = sock->ctrl_sd,
- &sock-&= gt;socks_relay.dest,
- = sock->server_poll_timeout,
<= span style=3D"color: hsl(0, 100%, 40%);">- = sig_info);

+ est= ablish_socks_proxy_udpassoc(sock->socks_proxy, sock->ctrl_sd, &so= ck->socks_relay.dest,
+ sock->server_poll_timeout, sig_i= nfo);

if (sig_info->signal_receiv= ed)
{
@@ -2224,8 +2075,7 @@
=
#if defined(_WIN32)
static void
-create_socket_dco_win(s= truct context *c, struct link_socket *sock,
- struct signal_info *sig_info)
+create_socket_dco_win= (struct context *c, struct link_socket *sock, struct signal_info *sig_info)=
{
/* in P2P mode we must have remote= resolved at this point */
struct addrinfo *remoteaddr= =3D sock->info.lsa->current_remote;
@@ -2273,14 +212= 3,13 @@

/* finalize socket initializatio= n */
void
-link_socket_init_phase2(struct context *c,
- struct link_socket *sock)=
+link_socket_init_ph= ase2(struct context *c, struct link_socket *sock)
{=
const struct frame *frame =3D &c->c2.frame; struct signal_info *sig_info =3D c->sig;

const char *remote_dynamic =3D NULL;
- struct signal_info sig_save =3D {0};=
+ struct signal_i= nfo sig_save =3D { 0 };

ASSERT(sock)= ;
ASSERT(sig_info);
@@ -2305,7 +2154,7= @@
}

/* Second= chance to resolv/create socket */
- resolve_remote(sock, 2, &remote_dynamic, sig_info);
+ resolve_remote(so= ck, 2, &remote_dynamic, sig_info);

= /* If a valid remote has been found, create the socket with its addrinfo= */
#if defined(_WIN32)
@@ -2326,7 +2175,7= @@
/* If we have no --remote and have still not f= igured out the
* protocol family to use we will u= se the first of the bind */

- if (sock->bind_local && !sock-&= gt;remote_host && sock->info.lsa->bind_local)
+ if (sock->bind_local &am= p;& !sock->remote_host && sock->info.lsa->bind_local)<= /span>
{
/* Warn if this is = because neither v4 or v6 was specified
* and = we should not connect a remote */
@@ -2360,7 +2209,6 @@
else if (sock->info.proto =3D=3D PROTO_TCP_CLIENT)
{
phase2_tcp_client(sock, sig_in= fo);
-
= }
else if (sock->info.proto =3D=3D PROTO_UDP &= amp;& sock->socks_proxy)
{
@@ -= 2454,7 +2302,8 @@
}

sta= tic void
-ipchange_fmt(= const bool include_cmd, struct argv *argv, const struct link_socket_info *i= nfo, struct gc_arena *gc)
+ipchange_fmt(const bool include_cmd, struct argv *argv, const struct = link_socket_info *info,
+ struct gc_arena *gc)
{
= const char *host =3D print_sockaddr_ex(&info->lsa->actual.dest= .addr.sa, " ", PS_SHOW_PORT, gc);
if (includ= e_cmd)
@@ -2466,13 +2315,11 @@
{

argv_printf(argv, "%s", host);
}

-
}


void
link_socket= _connection_initiated(struct link_socket_info *info,
- const stru= ct link_socket_actual *act,
- const char *common_name,
<= span style=3D"color: hsl(120, 100%, 40%);">+ = const struct link_socket_actual *act, const char *common_name,

= struct env_set *es)
{

struct gc_arena gc =3D gc_new();
@= @ -2488,7 +2335,8 @@
{
= buf_printf(&out, "[%s] ", common_name);
= }
- buf_pr= intf(&out, "Peer Connection Initiated with %s", print_link_so= cket_actual(&info->lsa->actual, &gc));
+ buf_printf(&out, "Peer C= onnection Initiated with %s",
+ print_link_socket_actual(&info->ls= a->actual, &gc));
msg(M_INFO, "%s"= ;, BSTR(&out));
}

@@ -2500,7 +2348,8 @@

{
str= uct argv argv =3D argv_new();
ipchange_fmt(false, = &argv, info, &gc);
- if (plugin_call(info->plugins, OPENVPN_PLUGIN_IPCHANGE, &am= p;argv, NULL, es) !=3D OPENVPN_PLUGIN_FUNC_SUCCESS)
+ if (plugin_call(info->plugins,= OPENVPN_PLUGIN_IPCHANGE, &argv, NULL, es)
+ !=3D OPENVPN_PLUGIN_FUNC_SUCCESS)
{
msg(M_WARN, "WAR= NING: ipchange plugin call failed");
}=
@@ -2521,8 +2370,7 @@
}
=
void
-link_s= ocket_bad_incoming_addr(struct buffer *buf,
- const struct link_socke= t_info *info,
+link_s= ocket_bad_incoming_addr(struct buffer *buf, const struct link_socket_info *= info,
const struct link_sock= et_actual *from_addr)
{
struct gc_are= na gc =3D gc_new();
@@ -2534,8 +2382,7 @@
= case AF_INET6:
msg(D_LINK_ERRORS,
"TCP/UDP: Incoming packet rejected from %= s[%d], expected peer address: %s (allow this incoming source address/port b= y removing --remote or adding --float)",
- print_link_socket_actual(from_addr,= &gc),
- = (int)from_addr->dest.addr.sa.sa_family,
+ print_link_socket_actual(from_a= ddr, &gc), (int)from_addr->dest.addr.sa.sa_family,
= print_sockaddr_ex(info->lsa->remote_list->ai_addr,= ":", PS_SHOW_PORT, &gc));
/* pr= int additional remote addresses */
for (ai =3D= info->lsa->remote_list->ai_next; ai; ai =3D ai->ai_next)
@@ -2560,16 +2407,16 @@
{
= const struct link_socket_addr *lsa =3D info->lsa;

-/*
- * This logic supports "redirect-gatew= ay" semantic, which
- *
- * Maybe in the future consider PF_INET6 endpoints = also ...
- * by now jus= t ignore it
- *<= br>- * For --remote entries with = multiple addresses this
- * only return the actual endpoint we have successfully connected to
- */
+ /*
+ * This logic supports "redirect-gateway"= ; semantic, which
+ = * makes sense only for PF_INET routes over PF_INET endpoints
<= span style=3D"color: hsl(120, 100%, 40%);">+ *

+ * Maybe in the future consider PF_INET6= endpoints also ...
+= * by now just ignore it
+ *
+ = * For --remote entries with multiple addresses this
+ * only return the actual endpoint we= have successfully connected to
+ */
if (lsa->actual.dest.addr.sa.sa= _family !=3D AF_INET)
{
retur= n IPV4_INVALID_ADDR;
@@ -2581,8 +2428,7 @@
= }
else if (lsa->current_remote)
{

- retur= n ntohl(((struct sockaddr_in *)lsa->current_remote->ai_addr)- ->sin_= addr.s_addr);
+ = return ntohl(((struct sockaddr_in *)lsa->current_remote->ai_addr)-&= gt;sin_addr.s_addr);
}
else
{
@@ -2595,12 +2441,12 @@
= {
const struct link_socket_addr *lsa =3D info->lsa;=

-/* = This logic supports "redirect-gateway" semantic,
- * for PF_INET6 routes over PF_INET6 e= ndpoints
- *
= - * For --remote entries with mul= tiple addresses this
- = * only return the actual endpoint we have successfully connected to<= br>- */
+ /* This logic supports "redirect-gat= eway" semantic,
= + * for PF_INET6 routes over PF_INET6 endpoints
+ *
+ * For --remote entries with multiple addresses th= is
+ * only retur= n the actual endpoint we have successfully connected to
+ */
if (lsa-&g= t;actual.dest.addr.sa.sa_family !=3D AF_INET6)
{
return NULL;
@@ -2631,20 +2477,16 @@
{
if (rwflags & EVENT_READ)=
{
- buf_printf(&out, "S%s",
- (s->rwflags_deb= ug & EVENT_READ) ? "R" : "r");
+ buf_printf(&out, "S= %s", (s->rwflags_debug & EVENT_READ) ? "R" : "r&= quot;);
#ifdef _WIN32
- buf_printf(&out, "%s",- overlapp= ed_io_state_ascii(&s->reads));
+ buf_printf(&out, "%s", overlapp= ed_io_state_ascii(&s->reads));
#endif
}

if (rwflags & EVENT_WRITE)
{
-= buf_printf(&out, "S%s",
- (s->rwflags_debug &am= p; EVENT_WRITE) ? "W" : "w");
+ buf_printf(&out, "S%s&qu= ot;, (s->rwflags_debug & EVENT_WRITE) ? "W" : "w"= ;);
#ifdef _WIN32
- buf_printf(&out, "%s",
- overlapped_i= o_state_ascii(&s->writes));

+ buf_printf(&out, "%s", overlapped_= io_state_ascii(&s->writes));
#endif
}

}
@@ -2671,9 +2513,7 @@
}

static void
<= span style=3D"color: hsl(0, 100%, 40%);">-stream_buf_init(struct stream_buf= *sb,

- = struct buffer *buf,
- = const unsigned int sockflags,
+stream_buf_init(struct stream_buf *sb, struct buffe= r *buf, const unsigned int sockflags,
cons= t int proto)
{
sb->buf_init =3D *b= uf;
@@ -2682,9 +2522,8 @@
sb->resid= ual =3D alloc_buf(sb->maxlen);
sb->error =3D fal= se;
#if PORT_SHARE
- sb->port_share_state =3D ((sockflags & SF_PORT_SHA= RE) && (proto =3D=3D PROTO_TCP_SERVER))
- ? PS_ENABLED- : PS= _DISABLED;
+ sb-&g= t;port_share_state =3D
- sb->buf.offset, sb->buf.len,
- sb->next.offset, sb->next.len,
- sb->len, sb= ->maxlen);
+ = sb->buf.offset, sb->buf.len, sb->next.offset, sb->next.len, = sb->len, sb->maxlen);
ASSERT(sb->next.len >= ; 0);
ASSERT(buf_safe(&sb->buf, sb->next.len= ));
}
@@ -2709,8 +2546,7 @@
static inline void

stream_buf_get_final(struct stream_b= uf *sb, struct buffer *buf)
{
- dmsg(D_STREAM_DEBUG, "STREAM: GET FINAL l= en=3D%d",
- = buf_defined(&sb->buf) ? sb->buf.len : -1);
+ dmsg(D_STREAM_DEBUG, "STREAM: G= ET FINAL len=3D%d", buf_defined(&sb->buf) ? sb->buf.len : -1= );
ASSERT(buf_defined(&sb->buf));
*buf =3D sb->buf;

}
@@ -2718,8 = +2554,7 @@
static inline void
stream_buf_= get_next(struct stream_buf *sb, struct buffer *buf)
{
- dmsg(D_STREAM_DEBUG, &= quot;STREAM: GET NEXT len=3D%d",
- buf_defined(&sb->next) ? sb->next.len : = -1);
+ dmsg(D_STRE= AM_DEBUG, "STREAM: GET NEXT len=3D%d", buf_defined(&sb->ne= xt) ? sb->next.len : -1);
ASSERT(buf_defined(&s= b->next));
*buf =3D sb->next;
}=
@@ -2733,8 +2568,7 @@
ASSERT(buf_= init(&sock->stream_buf.residual, 0));
sock-= >stream_buf.residual_fully_formed =3D stream_buf_added(&sock->str= eam_buf, 0);
dmsg(D_STREAM_DEBUG, "STREAM: RE= SIDUAL FULLY FORMED [%s], len=3D%d",
- sock->stream_buf.residual_fully_formed = ? "YES" : "NO",
- sock->stream_buf.residual.len);
+ sock->stream_buf.= residual_fully_formed ? "YES" : "NO", sock->stream_b= uf.residual.len);

}

= if (!sock->stream_buf.residual_fully_formed)
@@ -27= 45,8 +2579,7 @@
}

stati= c bool
-stream_buf_adde= d(struct stream_buf *sb,
+stream_buf_added(struct stream_buf *sb, int length_added)=
{
dmsg(D_STREAM_DEBUG, "STREAM:= ADD length_added=3D%d", length_added);
if (lengt= h_added > 0)
@@ -2756,7 +2589,7 @@

/* if length unknown, see if we can get the length prefix= from
* the head of the buffer */
- if (sb->len < 0 && sb-&= gt;buf.len >=3D (int) sizeof(packet_size_type))
+ if (sb->len < 0 && sb->= buf.len >=3D (int)sizeof(packet_size_type))
{
packet_size_type net_size;

= @@ -2782,7 +2615,9 @@

if (= sb->len < 1 || sb->len > sb->maxlen)
= {
- msg(M_= WARN, "WARNING: Bad encapsulated packet length from peer (%d), which m= ust be > 0 and <=3D %d -- please ensure that --tun-mtu or --link-mtu = is equal on both peers -- this condition could also indicate a possible act= ive attack on the TCP link -- [Attempting restart...]", sb->len, sb= ->maxlen);
+ = msg(M_WARN,
+ = "WARNING: Bad encapsulated packet length from peer (%d),= which must be > 0 and <=3D %d -- please ensure that --tun-mtu or --l= ink-mtu is equal on both peers -- this condition could also indicate a poss= ible active attack on the TCP link -- [Attempting restart...]",=
+ sb->len= , sb->maxlen);
stream_buf_reset(sb);=
sb->error =3D true;
= return false;
@@ -2799,8 +2634,7 @@
= ASSERT(buf_copy_excess(&sb->residual, &sb->buf, sb->= len));
}
dmsg(D_STREAM_DE= BUG, "STREAM: ADD returned TRUE, buf_len=3D%d, residual_len=3D%d"= ,
- BLEN(&a= mp;sb->buf),
- = BLEN(&sb->residual));
+ BLEN(&sb->buf), BLEN(&sb->residu= al));
return true;
} else
@@ -2831,7 +2665,7 @@
= init_net_event_win32(&s->listen_handle, FD_ACCEPT, s->sd, 0= );
}
return &s->listen_han= dle;
-#else /* ifdef _= WIN32 */
+#else /* if= def _WIN32 */
return s->sd;
#endif=
}
@@ -2841,9 +2675,7 @@
= */

const char *
-print_sockaddr_ex(const struct sockaddr *sa= ,
- co= nst char *separator,
- = const unsigned int flags,
+print_sockaddr_ex(const struct sockaddr *sa, const c= har *separator, const unsigned int flags,
= struct gc_arena *gc)
{
struct buffe= r out =3D alloc_buf_gc(128, gc);
@@ -2861,7 +2693,7 @@
buf_puts(&out, "[AF_INET]");
}
salen =3D sizeof(s= truct sockaddr_in);
- = addr_is_defined =3D ((struct sockaddr_in *) sa)->sin_addr.s_ad= dr !=3D 0;
+ = addr_is_defined =3D ((struct sockaddr_in *)sa)->sin_addr.s_addr !=3D = 0;
break;

= case AF_INET6:
@@ -2870,7 +2702,7 @@
buf_puts(&out, "[AF_INET6]");

}

salen =3D sizeof(struct sock= addr_in6);
- = addr_is_defined =3D !IN6_IS_ADDR_UNSPECIFIED(&((struct sockaddr_in6 *)= sa)->sin6_addr);
= + addr_is_defined =3D !IN6_IS_ADDR_UNSPECIFIED(&((struct soc= kaddr_in6 *)sa)->sin6_addr);
break;<= br>
case AF_UNSPEC:
@@ -288= 7,10 +2719,10 @@
ASSERT(0);
= }

= - status =3D getnameinfo(sa, salen, hostaddr, sizeof(hostaddr),- servn= ame, sizeof(servname), NI_NUMERICHOST | NI_NUMERICSERV);
+ status =3D getnameinfo(sa, salen, = hostaddr, sizeof(hostaddr), servname, sizeof(servname),
+ NI_NUMERICHOST= | NI_NUMERICSERV);

- if (status!=3D0)
+ if (status !=3D 0)
{
buf_printf(&out, "[nameinfo() err: %s]", gai_str= error(status));

return BSTR(&out);
<= span>@@ -2924,7 +2756,7 @@

const char *
p= rint_link_socket_actual(const struct link_socket_actual *act, struct gc_are= na *gc)
{
- return print_link_socket_actual_ex(act, ":", PS_SHOW_POR= T|PS_SHOW_PKTINFO, gc);
+ return print_link_socket_actual_ex(act, ":", PS_SHOW_PORT= | PS_SHOW_PKTINFO, gc);
}

#ifndef IF_NAMESIZE

@@ -2932,10 +2764,8 @@
#endif


const char *
-print_link_socket_actual_ex(const str= uct link_socket_actual *act,

- const char *separator,
- const unsig= ned int flags,
- = struct gc_arena *gc)
+print_link_socket_actual_ex(const struct link_socket_= actual *act, const char *separator,
+ const unsigned int flags, struc= t gc_arena *gc)
{
if (act)
= {
@@ -2959,12 +2789,11 @@
#elif= defined(IP_RECVDSTADDR)
sa.addr.in4.s= in_addr =3D act->pi.in4;
ifname[0] = =3D 0;
-#else /* if de= fined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST) */
<= span style=3D"color: hsl(120, 100%, 40%);">+#else /* if defined(HAVE_IN_PKT= INFO) && defined(HAVE_IPI_SPEC_DST) */

#error ENAB= LE_IP_PKTINFO is set without IP_PKTINFO xor IP_RECVDSTADDR (fix syshead.h)<= /span>
#endif
buf_printf(&am= p;out, " (via %s%%%s)",
- print_sockaddr_ex(&sa.addr.s= a, separator, 0, gc),
-= ifname);
+ print_sockaddr_ex(&s= a.addr.sa, separator, 0, gc), ifname);
}
break;

@@= -2976,8 +2805,9 @@
sin6.sin6_family = =3D AF_INET6;
sin6.sin6_addr =3D act-&= gt;pi.in6.ipi6_addr;
if_indextoname(ac= t->pi.in6.ipi6_ifindex, ifname);
- if (getnameinfo((struct sockaddr *)&s= in6, sizeof(struct sockaddr_in6),
- buf, sizeof(buf), NULL, 0, = NI_NUMERICHOST) =3D=3D 0)
+ if (getnameinfo((struct sockaddr *)&sin6, siz= eof(struct sockaddr_in6), buf,
+ sizeof(buf), NULL, 0, NI_NUM= ERICHOST)
+ = =3D=3D 0)
{
buf_printf(&out, " (via %s%%%s)"= , buf, ifname);

}
@@ -= 3027,8 +2857,7 @@
{
char *out =3D gc_= malloc(INET6_ADDRSTRLEN, true, gc);

- if (memcmp(&a6, &in6addr_any, s= izeof(a6)) !=3D 0
- = || !(flags & IA_EMPTY_IF_UNDEF))
+ if (memcmp(&a6, &in6addr_any, sizeof(a6)) = !=3D 0 || !(flags & IA_EMPTY_IF_UNDEF))
{ inet_ntop(AF_INET6, &a6, out, INET6_ADDRSTRLEN);
}
@@ -3050,30 +2879,31 @@
= * (add in steps of 8 bits, taking overflow into next round)
*/

struct in6_addr
-add_in6_addr( struct in6_addr base, uint32_t add )=
+add_in6_addr(struct in6_ad= dr base, uint32_t add)
{
int i;

- for (= i =3D 15; i>=3D0 && add > 0; i--)
+ for (i =3D 15; i >=3D 0 && add &= gt; 0; i--)
{
register int ca= rry;
register uint32_t h;
=
- h =3D (unsigned char= ) base.s6_addr[i];
- = base.s6_addr[i] =3D (h+add) & UINT8_MAX;
+ h =3D (unsigned char)base.s6_addr[i];=
+ base.s6_add= r[i] =3D (h + add) & UINT8_MAX;

= /* using explicit carry for the 8-bit additions will catch
* 8-bit and(!) 32-bit overruns nicely

= */
- carry = =3D ((h & 0xff) + (add & 0xff)) >> 8;
- add =3D (add>>8) + carry;
+ carry =3D ((h &= amp; 0xff) + (add & 0xff)) >> 8;
+ add =3D (add >> 8) + carry;
= }
return base;
}
/* set environmental variables for ip/port in *ad= dr */
void
-setenv_sockaddr(struct env_set *es, const char *name_prefix, const st= ruct openvpn_sockaddr *addr, const unsigned int flags)
+setenv_sockaddr(struct env_set *es, cons= t char *name_prefix, const struct openvpn_sockaddr *addr,
+ const unsigned int fl= ags)
{
char name_buf[256];
=
@@ -3101,11 +2931,10 @@
= break;

case AF_INET6:- if (IN6_IS_ADDR_V4= MAPPED( &addr->addr.in6.sin6_addr ))
+ if (IN6_IS_ADDR_V4MAPPED(&addr->= addr.in6.sin6_addr))
{
= struct in_addr ia;
- memcpy(&ia.s_addr, &addr->addr.in6.sin6_a= ddr.s6_addr[12],
- = sizeof(ia.s_addr));
+ memcpy(&ia.s_addr, &addr->addr= .in6.sin6_addr.s6_addr[12], sizeof(ia.s_addr));
= snprintf(name_buf, sizeof(name_buf), "%s_ip", name_prefix);=
inet_ntop(AF_INET, &ia, buf, sizeof(b= uf));
}
@@ -3126,7 +2955,8 @@<= /span>
}

void
-setenv_in_addr_t(struct env_set *es, c= onst char *name_prefix, in_addr_t addr, const unsigned int flags)+setenv_in_addr_t(struct env_s= et *es, const char *name_prefix, in_addr_t addr,
+ const unsigned int flags)
{
if (addr || !(flags & SA_SET_IF_NO= NZERO))
{
@@ -3139,9 +2969,7 @@=
}

void
-setenv_in6_addr(struct env_set *es,<= br>- const char *n= ame_prefix,
- = const struct in6_addr *addr,
+setenv_in6_addr(struct env_set *es, const char *name_prefix,= const struct in6_addr *addr,
const unsign= ed int flags)
{
if (!IN6_IS_ADDR_UNSP= ECIFIED(addr) || !(flags & SA_SET_IF_NONZERO))
@@ -3155= ,10 +2983,8 @@
}

void
-setenv_link_socket_actu= al(struct env_set *es,
= - const char *name_prefix,
- const struct link= _socket_actual *act,
- = const unsigned int flags)
+setenv_link_socket_actual(struct env_set *es= , const char *name_prefix,
+ const struct link_socket_actual *act, cons= t unsigned int flags)
{
setenv_sockad= dr(es, name_prefix, &act->dest, flags);
}@@ -3167,7 +2993,8 @@
* Convert protocol names bet= ween index and ascii form.
*/
-struct proto_names {
= +struct proto_names
<= span style=3D"color: hsl(120, 100%, 40%);">+{

const ch= ar *short_form;
const char *display_form;
sa_family_t proto_af;

@@ -3176,22 +3003,22 @@

/* Indexed by PROTO_x */
st= atic const struct proto_names proto_names[] =3D {
- {"proto-uninitialized", "pro= to-NONE", AF_UNSPEC, PROTO_NONE},
+ { "proto-uninitialized", "proto-NONE&= quot;, AF_UNSPEC, PROTO_NONE },
/* try IPv4 and IPv6 (= client), bind dual-stack (server) */
- {"udp", "UDP", AF_UNSPEC, PR= OTO_UDP},
- {"t= cp-server", "TCP_SERVER", AF_UNSPEC, PROTO_TCP_SERVER},
- {"tcp-client&quo= t;, "TCP_CLIENT", AF_UNSPEC, PROTO_TCP_CLIENT},
- {"tcp", "TC= P", AF_UNSPEC, PROTO_TCP},
+ { "udp", "UDP", AF_UNSPEC, PROTO_UDP },=
+ { "tcp-ser= ver", "TCP_SERVER", AF_UNSPEC, PROTO_TCP_SERVER },+ { "tcp-client",= "TCP_CLIENT", AF_UNSPEC, PROTO_TCP_CLIENT },
+ { "tcp", "TCP",= AF_UNSPEC, PROTO_TCP },
/* force IPv4 */
- {"udp4", &quo= t;UDPv4", AF_INET, PROTO_UDP},

- {"tcp4-server", "TCPv4_SERVER", AF_IN= ET, PROTO_TCP_SERVER},
= - {"tcp4-client", "TCPv4_CLIENT", AF_INET, PROTO_TCP= _CLIENT},
- {"t= cp4", "TCPv4", AF_INET, PROTO_TCP},
+ { "udp4", "UDPv4&q= uot;, AF_INET, PROTO_UDP },
+ { "tcp4-server", "TCPv4_SERVER", AF_INET, P= ROTO_TCP_SERVER },
+ = { "tcp4-client", "TCPv4_CLIENT", AF_INET, PROTO_TCP_= CLIENT },
+ { &quo= t;tcp4", "TCPv4", AF_INET, PROTO_TCP },
= /* 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_IN= ET6, PROTO_TCP},
+ = { "udp6", "UDPv6", AF_INET6, PROTO_UDP },
+ { "tcp6-server", &= quot;TCPv6_SERVER", AF_INET6, PROTO_TCP_SERVER },

+ { "tcp6-client", "TCP= v6_CLIENT", AF_INET6, PROTO_TCP_CLIENT },
+ { "tcp6", "TCPv6", AF_IN= ET6, PROTO_TCP },
};

in= t
@@ -3262,9 +3089,11 @@
{
switch (af)

{
- case AF_INET: return "AF_INET";
+ case AF_INET:
+ return &quo= t;AF_INET";

- case AF_INET6: return "AF_INET6";
= + case AF_INET6:<= br>+ return "AF= _INET6";
}
return "AF_U= NSPEC";
}
@@ -3290,13 +3119,11 @@
return "UDPv4";
}

- if (= (remote && proto =3D=3D PROTO_TCP_CLIENT)
- || (!remote && proto =3D=3D P= ROTO_TCP_SERVER))
+ = if ((remote && proto =3D=3D PROTO_TCP_CLIENT) || (!remote &&a= mp; proto =3D=3D PROTO_TCP_SERVER))
{
= return "TCPv4_SERVER";
}
= - if ( (remote && prot= o =3D=3D PROTO_TCP_SERVER)
- || (!remote && proto =3D=3D PROTO_TCP_CLIENT))=
+ if ((remote &&= proto =3D=3D PROTO_TCP_SERVER) || (!remote && proto =3D=3D PROTO_T= CP_CLIENT))
{
return "TC= Pv4_CLIENT";
}
@@ -3312,9 +3139,9= @@
void
bad_address_length(int actual, i= nt expected)
{
- msg(M_FATAL, "ERROR: received strange incoming packet wi= th an address length of %d -- we only accept address lengths of %d.",<= /span>
- actual,=
- expected);+ msg(M_FATAL,
+ "ERROR: received st= range incoming packet with an address length of %d -- we only accept addres= s lengths of %d.",

+ actual, expected);
}
<= br> /*
@@ -3322,8 +3149,7 @@
*/

int
-link_socket_read_tcp(struct link_socket *sock,
- struct buffer *= buf)

+link_socket_rea= d_tcp(struct link_socket *sock, struct buffer *buf)
{
int len =3D 0;

@@ -3336,= 9 +3162,9 @@
*/
if (sock= ->sd =3D=3D SOCKET_UNDEFINED)
{
- msg(M_INFO, "BUG: li= nk_socket_read_tcp(): sock->sd=3D=3D-1, reset client instance" );
- sock->st= ream_reset =3D true; /* reset client instance */
- return buf->len =3D = 0; /* nothing to read */

+ msg(M_INFO, "BUG: link_socket_read= _tcp(): sock->sd=3D=3D-1, reset client instance");
+ sock->stream_reset = =3D true; /* reset client instance */
+ return buf->len =3D 0; /* nothing to= read */
}

#ifd= ef _WIN32
@@ -3381,24 +3207,23 @@
* both = IPv4 and IPv6 destination addresses, plus padding (see RFC 2292)
= */
#if defined(HAVE_IN_PKTINFO) && defined= (HAVE_IPI_SPEC_DST)
-#d= efine PKTINFO_BUF_SIZE max_int( CMSG_SPACE(sizeof(struct in6_pktinfo)), \
- = CMSG_SPACE(sizeof(struct in_pktinfo)) )
+#define PKTINFO_BUF_SIZE \
+ max_int(CMSG_SPACE(sizeof(struct = in6_pktinfo)), CMSG_SPACE(sizeof(struct in_pktinfo)))
#els= e
-#define PKTINFO_BUF_= SIZE max_int( CMSG_SPACE(sizeof(struct in6_pktinfo)), \
- CMSG_SP= ACE(sizeof(struct in_addr)) )
+#define PKTINFO_BUF_SIZE \
+ max_int(CMSG_SPACE(sizeof(struct in6_pktinfo)), CMSG_S= PACE(sizeof(struct in_addr)))
#endif

static socklen_t
-link_socket_read_udp_posix_recvmsg(struct link_socket *sock,
- = struct buffer *buf,
+link_socket_read_udp_posix_recvmsg(struct link_socket *sock, struct= buffer *buf,
struct li= nk_socket_actual *from)
{
struct iove= c iov;
uint8_t pktinfo_buf[PKTINFO_BUF_SIZE];- struct msghdr mesg =3D {0}= ;
+ struct msghdr = mesg =3D { 0 };
socklen_t fromlen =3D sizeof(from->= dest.addr);

- ASSERT(sock->sd >=3D 0); /* can'= t happen */
+ ASSE= RT(sock->sd >=3D 0); /* can't happen */
<= br> iov.iov_base =3D BPTR(buf);
iov.iov_len = =3D buf_forward_capacity_total(buf);
@@ -3414,43 +3239,40 @= @
struct cmsghdr *cmsg;
f= romlen =3D mesg.msg_namelen;
cmsg =3D CMSG_FIRSTHD= R(&mesg);
- = if (cmsg !=3D NULL
- = && CMSG_NXTHDR(&mesg, cmsg) =3D=3D NULL
+ if (cmsg !=3D NULL &&a= mp; CMSG_NXTHDR(&mesg, cmsg) =3D=3D NULL

#if defined(H= AVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST)
- && cmsg->cmsg_level = =3D=3D SOL_IP
- = && cmsg->cmsg_type =3D=3D IP_PKTINFO
- && cmsg->cmsg_len &g= t;=3D CMSG_LEN(sizeof(struct in_pktinfo)) )
+ && cmsg->cmsg_level =3D=3D S= OL_IP && cmsg->cmsg_type =3D=3D IP_PKTINFO
+ && cmsg->cmsg_len = >=3D CMSG_LEN(sizeof(struct in_pktinfo)))
#elif defined= (IP_RECVDSTADDR)
- = && cmsg->cmsg_level =3D=3D IPPROTO_IP
- && cmsg->cmsg_type= =3D=3D IP_RECVDSTADDR
= - && cmsg->cmsg_len >=3D CMSG_LEN(sizeof(struct in= _addr)) )
-#else /* if= defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST) */+ && cmsg-= >cmsg_level =3D=3D IPPROTO_IP && cmsg->cmsg_type =3D=3D IP_RE= CVDSTADDR
+ = && cmsg->cmsg_len >=3D CMSG_LEN(sizeof(struct in_addr)))
+#else /* if defined(HA= VE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST) */
#e= rror ENABLE_IP_PKTINFO is set without IP_PKTINFO xor IP_RECVDSTADDR (fix sy= shead.h)
#endif
{
#if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST)
=
- struct in_pktinf= o *pkti =3D (struct in_pktinfo *) CMSG_DATA(cmsg);
+ struct in_pktinfo *pkti =3D (str= uct in_pktinfo *)CMSG_DATA(cmsg);
from->pi.= in4.ipi_ifindex =3D pkti->ipi_ifindex;
from= ->pi.in4.ipi_spec_dst =3D pkti->ipi_spec_dst;
#elif = defined(IP_RECVDSTADDR)
- from->pi.in4 =3D *(struct in_addr *) CMSG_DATA(cmsg);
-#else /* if defined(HAVE_= IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST) */
+ from->pi.in4 =3D *(struct = in_addr *)CMSG_DATA(cmsg);
+#else /* if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPE= C_DST) */
#error ENABLE_IP_PKTINFO is set without IP_PKTIN= FO xor IP_RECVDSTADDR (fix syshead.h)
#endif
}

- = else if (cmsg !=3D NULL
- && CMSG_NXTHDR(&mesg, cmsg) =3D=3D NULL
- &&= ; cmsg->cmsg_level =3D=3D IPPROTO_IPV6
- && cmsg->cmsg_type =3D=3D I= PV6_PKTINFO
- = && cmsg->cmsg_len >=3D CMSG_LEN(sizeof(struct in6_pkti= nfo)) )
+ else= if (cmsg !=3D NULL && CMSG_NXTHDR(&mesg, cmsg) =3D=3D NULL
+ &&= amp; cmsg->cmsg_level =3D=3D IPPROTO_IPV6 && cmsg->cmsg_type = =3D=3D IPV6_PKTINFO
+= && cmsg->cmsg_len >=3D CMSG_LEN(sizeof(struc= t in6_pktinfo)))
{
- struct in6_pktinfo *pkti6 =3D (struct in6= _pktinfo *) CMSG_DATA(cmsg);
+ struct in6_pktinfo *pkti6 =3D (struct in6_pktinfo *)CM= SG_DATA(cmsg);
from->pi.in6.ipi6_ifindex = =3D pkti6->ipi6_ifindex;
from->pi.in6.ip= i6_addr =3D pkti6->ipi6_addr;
}
else if (cmsg !=3D NULL)

{
- msg(M_WARN, "CMSG = received that cannot be parsed (cmsg_level=3D%d, cmsg_type=3D%d, cmsg=3Dlen= =3D%d)", (int)cmsg->cmsg_level, (int)cmsg->cmsg_type, (int)cmsg-= >cmsg_len );

+ = msg(M_WARN,
+= "CMSG received that cannot be parsed (cmsg_level=3D%d,= cmsg_type=3D%d, cmsg=3Dlen=3D%d)",
+ (int)cmsg->cmsg_level, (int)cmsg-&g= t;cmsg_type, (int)cmsg->cmsg_len);
}
= }

@@ -3459,15 +3281,14 @@
#endif /* if ENABLE_IP_PKTINFO */

= int
-link_socket= _read_udp_posix(struct link_socket *sock,
- struct buffer *buf,+link_socket_read_udp_posix(s= truct link_socket *sock, struct buffer *buf,
= struct link_socket_actual *from)
{ socklen_t fromlen =3D sizeof(from->dest.addr);
socklen_t expectedlen =3D af_addr_size(sock->info.af);
addr_zero_host(&from->dest);
- ASSERT(sock->sd >=3D = 0); /* can't happen */
+ ASSERT(sock->sd >=3D 0); /* can't= happen */

#if ENABLE_IP_PKTINFO<= br> /* Both PROTO_UDPv4 and PROTO_UDPv6 */
@@ -34= 78,8 +3299,8 @@
else
#endif {
- = buf->len =3D recvfrom(sock->sd, BPTR(buf), buf_forward_capacity(buf),= 0,
- = &from->dest.addr.sa, &fromlen);
+ buf->len =3D recvfrom(sock->= ;sd, BPTR(buf), buf_forward_capacity(buf), 0, &from->dest.addr.sa,
+ = &fromlen);
}
/* FIXME:= won't do anything when sock->info.af =3D=3D AF_UNSPEC */
= if (buf->len >=3D 0 && expectedlen && from= len !=3D expectedlen)
@@ -3496,9 +3317,7 @@
*/


ssize_t
-link_socket_write_tcp(struct link_socket *sock,<= /span>
- = struct buffer *buf,
- = struct link_socket_actual *to)
+link_socket_write_tcp(struct link_socket *so= ck, struct buffer *buf, struct link_socket_actual *to)
{
packet_size_type len =3D BLEN(buf);
= dmsg(D_STREAM_DEBUG, "STREAM: WRITE %d offset=3D%d", (int)len, = buf->offset);
@@ -3515,8 +3334,7 @@
#if= ENABLE_IP_PKTINFO

ssize_t
-link_socket_write_udp_posix_sendmsg= (struct link_socket *sock,

- struct buffer *buf,
+link_socket_write_udp_posix_sendms= g(struct link_socket *sock, struct buffer *buf,

= struct link_socket_actual *to)
{=
struct iovec iov;
@@ -3544,19 +3362,1= 9 @@
cmsg->cmsg_type =3D IP_PKTINFO;=
{
struct in_pktinfo= *pkti;
- = pkti =3D (struct in_pktinfo *) CMSG_DATA(cmsg);
+ pkti =3D (struct in_pktinfo *= )CMSG_DATA(cmsg);
pkti->ipi_ifindex =3D= to->pi.in4.ipi_ifindex;
pkti->ipi_s= pec_dst =3D to->pi.in4.ipi_spec_dst;
pk= ti->ipi_addr.s_addr =3D 0;
}
#elif defined(IP_RECVDSTADDR)

- ASSERT( CMSG_SPACE(sizeof(struct in_addr)) <=3D s= izeof(pktinfo_buf) );
+ ASSERT(CMSG_SPACE(sizeof(struct in_addr)) <=3D sizeof(pkti= nfo_buf));
mesg.msg_controllen =3D CMSG_SPACE(= sizeof(struct in_addr));
cmsg =3D CMSG_FIRSTHD= R(&mesg);
cmsg->cmsg_len =3D CMSG_LEN(s= izeof(struct in_addr));
cmsg->cmsg_level = =3D IPPROTO_IP;
cmsg->cmsg_type =3D IP_RECV= DSTADDR;
- *= (struct in_addr *) CMSG_DATA(cmsg) =3D to->pi.in4;
+ *(struct in_addr *)CMSG_DATA(= cmsg) =3D to->pi.in4;
#else /* if defined(HAVE_IN_PKTI= NFO) && defined(HAVE_IPI_SPEC_DST) */
#error ENABL= E_IP_PKTINFO is set without IP_PKTINFO xor IP_RECVDSTADDR (fix syshead.h)
#endif /* if defined(HAVE_IN_PKTINFO) && defined(HA= VE_IPI_SPEC_DST) */
@@ -3569,7 +3387,7 @@
= mesg.msg_name =3D &to->dest.addr.sa;
= mesg.msg_namelen =3D sizeof(struct sockaddr_in6);

- ASSERT(= CMSG_SPACE(sizeof(struct in6_pktinfo)) <=3D sizeof(pktinfo_buf) );
+ ASSERT(CMSG_= SPACE(sizeof(struct in6_pktinfo)) <=3D sizeof(pktinfo_buf));
<= span> mesg.msg_control =3D pktinfo_buf;

= mesg.msg_controllen =3D CMSG_SPACE(sizeof(struct in6_pktinfo));
mesg.msg_flags =3D 0;
@@ -3578,13 += 3396,14 @@
cmsg->cmsg_level =3D IPPROTO_IPV= 6;
cmsg->cmsg_type =3D IPV6_PKTINFO;=

- = pkti6 =3D (struct in6_pktinfo *) CMSG_DATA(cmsg);
+ pkti6 =3D (struct in6_pktinfo= *)CMSG_DATA(cmsg);
pkti6->ipi6_ifindex =3D= to->pi.in6.ipi6_ifindex;
pkti6->ipi6_ad= dr =3D to->pi.in6.ipi6_addr;
break;<= br> }

- default: ASSERT(0);
+ default:
+ ASSERT(0);
} return sendmsg(sock->sd, &mesg, 0);
}<= /span>
@@ -3643,8 +3462,8 @@

= if (socket_is_dco_win(sock))
{
- status =3D ReadFile((HA= NDLE)sock->sd, wsabuf[0].buf, wsabuf[0].len,

- &sock->reads= .size, &sock->reads.overlapped);
+ status =3D ReadFile((HANDLE)sock->sd, ws= abuf[0].buf, wsabuf[0].len, &sock->reads.size,
+ &sock-&= gt;reads.overlapped);
/* Readfile status is in= verted from WSARecv */
status =3D !status;
}
@@ -3652,28 +3471,15 @@
<= span> {

sock->reads.addr_defined = =3D true;
sock->reads.addrlen =3D sizeof(so= ck->reads.addr6);
- = status =3D WSARecvFrom(
- sock->sd,
- wsabuf,
- 1,
- &sock->reads.size,
- &sock->reads.= flags,

- = (struct sockaddr *) &sock->reads.addr,
- &sock->reads.addrlen,
- &sock-&= gt;reads.overlapped,
- = NULL);
+ status =3D WSARecvFrom(sock->sd, wsabuf, 1, &sock->= reads.size, &sock->reads.flags,
+ (struct sockaddr *)&= ;sock->reads.addr, &sock->reads.addrlen,
+ &sock-&= gt;reads.overlapped, NULL);
}
= else if (proto_is_tcp(sock->info.proto))
{=
sock->reads.addr_defined =3D false;=
- status =3D WSARe= cv(
- so= ck->sd,
- = wsabuf,
- = 1,
- = &sock->reads.size,
- &sock->reads.flags,
- &sock->reads.overlapped= ,
- NULL= );
+ statu= s =3D WSARecv(sock->sd, wsabuf, 1, &sock->reads.size, &sock-&= gt;reads.flags,
+ = &sock->reads.overlapped, NULL);
<= span> }

else
{
@@ -3696,8 +3502,7 @@
sock->r= eads.status =3D 0;

dmsg(D_WI= N32_IO, "WIN32 I/O: Socket Receive immediate return [%d,%d]",
- (int) ws= abuf[0].len,
- = (int) sock->reads.size);
+ (int)wsabuf[0].len, (int)sock->reads.si= ze);
}
else
{

@@ -3706,8 +3511,7 @@
= {
sock->reads.iostate =3D IOSTATE= _QUEUED;
sock->reads.status =3D status;=
- dmsg(= D_WIN32_IO, "WIN32 I/O: Socket Receive queued [%d]",
- (int) wsabuf[= 0].len);

+ = dmsg(D_WIN32_IO, "WIN32 I/O: Socket Receive queued [%d]", (i= nt)wsabuf[0].len);
}
= else /* error occurred */
{
@@ -3715,8 +3519,7 @@

ASSERT(SetEvent(so= ck->reads.overlapped.hEvent));
sock->= ;reads.iostate =3D IOSTATE_IMMEDIATE_RETURN;
= sock->reads.status =3D status;
- dmsg(D_WIN32_IO, "WIN32 I/O: Socket Rec= eive error [%d]: %s",
- (int) wsabuf[0].len,
+ dmsg(D_WIN32_IO, "WIN32 I/O= : Socket Receive error [%d]: %s", (int)wsabuf[0].len,
= strerror_win32(status, &gc));
= gc_free(&gc);
}
@@ -3748,12 +3551,11 @@


if (= socket_is_dco_win(sock))
{
- status =3D WriteFile((HANDLE)so= ck->sd, wsabuf[0].buf, wsabuf[0].len,
- &sock->writes.size= , &sock->writes.overlapped);
+ status =3D WriteFile((HANDLE)sock->sd, wsabu= f[0].buf, wsabuf[0].len, &sock->writes.size,
+ &sock-= >writes.overlapped);

/* W= riteFile status is inverted from WSASendTo */
= status =3D !status;
-
}
else if (proto_is_udp(so= ck->info.proto))
{
@@ -3770,30 = +3572,17 @@
sock->writes.addrlen =3D si= zeof(sock->writes.addr);
}
=
- status = =3D WSASendTo(
- = sock->sd,
-= wsabuf,
- 1,
- = &sock->writes.size,
- sock->writes.flags,
- (struct sockaddr *) &a= mp;sock->writes.addr,
- &sock->writes.overlapped,
- NULL);
+ status =3D = WSASendTo(sock->sd, wsabuf, 1, &sock->writes.size, sock->write= s.flags,
+ = (struct sockaddr *)&sock->writes.addr, sock->= writes.addrlen,
+ = &sock->writes.overlapped, NULL); }
else if (proto_is_tcp(sock->= info.proto))
{
/* des= tination address for TCP writes was established on connection initiation */=
sock->writes.addr_defined =3D false;

- = status =3D WSASend(
= - sock->sd,
- wsabuf,
- 1,
- &sock->writes.size,
- sock->writes.flags,- &sock->= writes.overlapped,
- = NULL);
+= status =3D WSASend(sock->sd, wsabuf, 1, &sock->writes= .size, sock->writes.flags,
+ &sock->writes.overlapped, NUL= L);
}
else
{

@@ -3810,9 +3599,8 @@
=
sock->writes.status =3D 0;

- dmsg(D_WIN32_I= O, "WIN32 I/O: Socket Send immediate return [%d,%d]",
<= span style=3D"color: hsl(0, 100%, 40%);">- (int) wsabuf[0].= len,

- = (int) sock->writes.size);
+ dmsg(D_WIN32_IO, "WIN32 I/O: Socket Send immediat= e return [%d,%d]", (int)wsabuf[0].len,
+ (int)sock->writes.size);=
}
else
= {
@@ -3822,8 +3610,7 @@
{
sock->writes.iostate =3D IOSTATE_QUEUED;
sock->writes.status =3D status;- dmsg(D_WIN32_I= O, "WIN32 I/O: Socket Send queued [%d]",
- (int) wsabuf[0].len);
+ dmsg(D_= WIN32_IO, "WIN32 I/O: Socket Send queued [%d]", (int)wsabuf[0].le= n);
}
else /* err= or occurred */
{
@@ -3832,8 +3= 619,7 @@
sock->writes.iostate =3D IOSTA= TE_IMMEDIATE_RETURN;
sock->writes.statu= s =3D status;

- dmsg(D_WIN32_IO, "WIN32 I/O: Socket Send err= or [%d]: %s",
- = (int) wsabuf[0].len,
+ dmsg(D_WIN32_IO, "WIN32 I/O: Socket= Send error [%d]: %s", (int)wsabuf[0].len,
= strerror_win32(status, &gc));

gc_free(&gc);

@@ -3905,7 +3691,9 @= @
sa_len =3D sizeof(struct sockaddr_in);
if (buf_len(buf) < sa_len)
= {
- = msg(M_FATAL, "ERROR: received incoming packet with too short lengt= h of %d -- must be at least %d.", buf_len(buf), sa_len);
+ msg(M_FATAL,
+ &quo= t;ERROR: received incoming packet with too short length of %d -- must be at= least %d.",
+ = buf_len(buf), sa_len);
}

memcpy(dst, sa, sa_len);
= buf_advance(buf, sa_len);
@@ -3915,14 +3703,17 @@
sa_len =3D sizeof(struct sockaddr_in6);
= if (buf_len(buf) < sa_len)
= {
- m= sg(M_FATAL, "ERROR: received incoming packet with too short length of = %d -- must be at least %d.", buf_len(buf), sa_len);
+ msg(M_FATAL,+ "ERR= OR: received incoming packet with too short length of %d -- must be at leas= t %d.",
+ = buf_len(buf), sa_len);
} memcpy(dst, sa, sa_len);
= buf_advance(buf, sa_len);
break;

default:
- msg(M_FATAL, "ERROR: received incoming pa= cket with invalid address family %d.", sa->sa_family);
+ msg(M_FATAL, "E= RROR: received incoming packet with invalid address family %d.",
+ sa->sa= _family);
}

ret= urn sa_len;
@@ -3930,9 +3721,7 @@
<= br> /* Returns the number of bytes successfully read */
int

-sockethandle_f= inalize(sockethandle_t sh,
- struct overlapped_io *io,
- struct buffer *buf,
+sockethandle_finalize= (sockethandle_t sh, struct overlapped_io *io, struct buffer *buf, struct link_socket_actual *from)
{

int ret =3D -1;
@@ -4025,10 +38= 14,7 @@
*/

unsigned in= t
-socket_set(struct li= nk_socket *s,
- = struct event_set *es,
- void *arg,
+socket_set(struct link_socket *s, struct event_set *es, uns= igned int rwflags, void *arg,
unsigned int *per= sistent)
{
if (s)
@@ = -4108,20 +3894,15 @@
}

= void
-socket_bind_unix(= socket_descriptor_t sd,
- struct sockaddr_un *local,
- const char *prefix)
+socket_bind_unix(socket_descriptor= _t sd, struct sockaddr_un *local, const char *prefix)

{
struct gc_arena gc =3D gc_new();
co= nst mode_t orig_umask =3D umask(0);

- if (bind(sd, (struct sockaddr *) local,= sizeof(struct sockaddr_un)))
+ if (bind(sd, (struct sockaddr *)local, sizeof(struct sockaddr= _un)))
{
- msg(M_FATAL | M_ERRNO,
- "%s: Socket bind[%d] failed on unix domai= n socket %s",
- = prefix,
- = (int)sd,
- = sockaddr_unix_name(local, "NULL"));
+ msg(M_FATAL | M_ERRNO, "%s: = Socket bind[%d] failed on unix domain socket %s", prefix,
+ (int)sd, sockaddr_un= ix_name(local, "NULL"));

}
=
umask(orig_umask);
@@ -4129,14 +3910,= 13 @@
}

socket_descript= or_t
-socket_accept_uni= x(socket_descriptor_t sd,
- struct sockaddr_un *remote)
+socket_accept_unix(socket_descriptor_t sd, s= truct sockaddr_un *remote)
{
socklen_= t remote_len =3D sizeof(struct sockaddr_un);
socket_de= scriptor_t ret;

CLEAR(*remote);
- ret =3D accept(sd, (st= ruct sockaddr *) remote, &remote_len);
+ ret =3D accept(sd, (struct sockaddr *)remote, &a= mp;remote_len);
if (ret >=3D 0)
= {
/* set socket file descriptor to not pass acro= ss execs, so that
@@ -4147,10 +3927,9 @@
}=

int
-socket_connect_unix(socket_descriptor_t sd,
- struct sockaddr= _un *remote)

+socket_= connect_unix(socket_descriptor_t sd, struct sockaddr_un *remote)
= {
- int statu= s =3D connect(sd, (struct sockaddr *) remote, sizeof(struct sockaddr_un));<= /span>
+ int status =3D c= onnect(sd, (struct sockaddr *)remote, sizeof(struct sockaddr_un)); if (status)
{
st= atus =3D openvpn_errno();
diff --git a/src/openvpn/socket.h= b/src/openvpn/socket.h
index f30411d..ed37590 100644
--- a/src/openvpn/socket.h
+++ b/src/openvpn/soc= ket.h
@@ -64,7 +64,8 @@
struct openvpn_soc= kaddr
{
/*int dummy;*/ /* add offset = to force a bug if sa not explicitly dereferenced */
- union {
+ union
+ {
struct sockaddr sa;
= struct sockaddr_in in4;
struct sock= addr_in6 in6;
@@ -72,7 +73,8 @@
};<= br>
/* struct to hold preresolved host names */
-struct cached_dns_entry {=
+struct cached_dns_e= ntry
+{
const char *hostname;

const char *servname;
int ai_family;
@@ -88,7 +90,8 @@<= br>
struct openvpn_sockaddr dest;
#if ENABLE_IP_PKTINFO

- union {
+ = union
+ { #if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST)=
struct in_pktinfo in4;
#elif def= ined(IP_RECVDSTADDR)
@@ -103,9 +106,9 @@
s= truct link_socket_addr
{
struct addri= nfo *bind_local;
- s= truct addrinfo *remote_list; /* complete remote list */
- struct addrinfo *current_remote; /* r= emote used in the
- = * current connection attempt */+ struct addrinfo *remote_l= ist; /* complete remote list */
+ struct addrinfo *current_remote; /* remote used in the=
+ = * current connection attempt */
st= ruct link_socket_actual actual; /* reply to this address */
};


@@ -116,10 +119,10 @@
const char *ipchange_command;

const struct plug= in_list *plugins;
bool remote_float;
- int proto; /* Prot= ocol (PROTO_x defined below) */
- sa_family_t af; /* Address family like AF= _INET, AF_INET6 or AF_UNSPEC*/
+ int proto; /* Protocol (PROTO_x defined below) */
+ sa_family_t af; /* = Address family like AF_INET, AF_INET6 or AF_UNSPEC*/
b= ool bind_ipv6_only;
- = int mtu_changed; /* Set to true when mtu value is changed */
+ int mtu_changed; = /* Set to true when mtu value is changed */
};
<= span>

/*
@@ -135,7 +138,7 @@

struct buffer buf;
struct b= uffer next;
- int le= n; /* -1 if not yet known */
+ int len; /* -1 if not yet known */

bool error; /* if true, fatal TCP error has occurred,
* requiring that connection be restarted */<= /span>
@@ -163,10 +166,8 @@
* @param sbs = new sizes.
* @param reduce_size apply the new size e= ven if smaller than current one
*/
-void
-socket_set_buffers(socket_descriptor_t fd,
- const struct socket_= buffer_size *sbs,
- = bool reduce_size);
+void socket_set_buffers(socket_descriptor_t fd, const struct = socket_buffer_size *sbs,
+ bool reduce_size);
/*
* This is the main socket structure used by Op= enVPN. The SOCKET_
@@ -177,10 +178,10 @@
= {
struct link_socket_info info;

- struct event_arg ev_ar= g; /**< this struct will store a pointer to either mi or
- * l= ink_socket, depending on the event type, to keep

- * it accessible = it's placed within the same struct
- * it points to. */<= br>+ struct event_arg ev_arg= ; /**< this struct will store a pointer to either mi or
+ * link= _socket, depending on the event type, to keep
+ * it accessible it&= #39;s placed within the same struct
+ * it points to. */
=
socket_descriptor_t sd;
s= ocket_descriptor_t ctrl_sd; /* only used for UDP over Socks */
@@ -205,9 +206,9 @@

struct cached_dns_entry *dns_c= ache;
bool bind_local;

-#define LS_MODE_DEFAULT 0=

-#define LS_MODE_TCP_L= ISTEN 1
-#define= LS_MODE_TCP_ACCEPT_FROM 2
+#define LS_MODE_DEFAULT 0
+#define LS_MODE_TCP_LISTEN 1
+#define LS_MODE_TCP_ACCEPT_FROM 2
int mode;

int resol= ve_retry_seconds;
@@ -215,15 +216,15 @@

struct socket_buffer_size socket_buffer_sizes;
- int mtu;= /* OS discovered MTU, or 0 if unknown */
+ int mtu; /* OS discovered MTU,= or 0 if unknown */


-#define SF_USE_IP_PKTINFO (1<<0)
-#define SF_TCP_NODELAY (1<<1)=
-#define SF_PORT_SHARE (1<= <2)
-#define SF_HOST= _RANDOMIZE (1<<3)
-#define SF_GETADDRINFO_DGRAM (1<<4)
-#define SF_DCO_WIN (1<<5)
-#define SF_PREPEND_SA (1<<6)+#define SF_USE_IP_PKTINFO = (1 << 0)
+#def= ine SF_TCP_NODELAY (1 << 1)
+#define SF_PORT_SHARE (1 << 2)
<= span style=3D"color: hsl(120, 100%, 40%);">+#define SF_HOST_RANDOMIZE (1= << 3)

+#define= SF_GETADDRINFO_DGRAM (1 << 4)
+#define SF_DCO_WIN (1 << 5)
+#define SF_PREPEND_SA (1 &l= t;< 6)

unsigned int sockflags;
= int mark;
const char *bind_dev;
@@ -2= 77,12 +278,13 @@

int socket_recv_queue(s= truct link_socket *sock, int maxsize);

-int socket_send_queue(struct link_socket= *sock,
- = struct buffer *buf,
+int socket_send_queue(struct link_socket *sock, struct buffer *buf,=
const struct link_socket_actual *to= );

-t= ypedef struct {
- un= ion {
+typedef struct=
+{
+ union
+ {
SOCKET s;=
HANDLE h;
};
@@ -29= 0,17 +292,15 @@
bool prepend_sa; /* are incoming packe= ts prepended with sockaddr? */
} sockethandle_t;
-int sockethan= dle_finalize(sockethandle_t sh,
- struct overlapped_io *io,
- struct bu= ffer *buf,

+int socke= thandle_finalize(sockethandle_t sh, struct overlapped_io *io, struct buffer= *buf,
struct link_socket_actual= *from);

static inline BOOL
SocketHandleGetOverlappedResult(sockethandle_t sh, struct overlapped_i= o *io)

{
- return sh.is_handle ?
- GetOverlappedResult(sh.h, &io->overlapped, &i= o->size, FALSE) :
- = WSAGetOverlappedResult(sh.s, &io->overlapped, &io->= size, FALSE, &io->flags);
+ return sh.is_handle
+ ? GetOverlappedResult(sh.h, &io->ove= rlapped, &io->size, FALSE)
+ : WSAGetOverlappedResult(sh.s, &io->ove= rlapped, &io->size, FALSE, &io->flags);
}

static inline int
@@ -321,= 7 +321,7 @@
sh.is_handle ? SetLastError(ERROR_INVALID_= FUNCTION) : WSASetLastError(WSAEINVAL);
}
=
-#else /* ifdef _WIN= 32 */
+#else /* ifdef= _WIN32 */

#define openvpn_close_socket(= s) close(s)

@@ -329,29 +329,19 @@<= br>
struct link_socket *link_socket_new(void);

-void soc= ket_bind(socket_descriptor_t sd,
- struct addrinfo *local,
- int af_family,
<= span style=3D"color: hsl(0, 100%, 40%);">- const char *pref= ix,

+void socket_bind= (socket_descriptor_t sd, struct addrinfo *local, int af_family, const char = *prefix,
bool ipv6only);
=
-int openvpn_connect(= socket_descriptor_t sd,
- const struct sockaddr *remote,
- int connect_timeout,
+int openvpn_connect(so= cket_descriptor_t sd, const struct sockaddr *remote, int connect_timeout,
volatile int *signal_received);<= br>

-
/*
* Initialize link_socket obje= ct.
*/
-link_socket_in= it_phase1(struct context *c,
- int sock_index,
- int mode);
+void link_socket_init_phase1(struct= context *c, int sock_index, int mode);


-void link_socket_init_phase2(struct con= text *c,
- = struct link_socket *sock);
+void link_socket_init_phase2(struct context *c, stru= ct link_socket *sock);

void do_preresolv= e(struct context *c);

@@ -359,75 +349,57 = @@

void sd_close(socket_descriptor_t *sd= );

-#= define PS_SHOW_PORT_IF_DEFINED (1<<0)
-#define PS_SHOW_PORT (1<<1)-#define PS_SHOW_PKTINFO = (1<<2)
-#define= PS_DONT_SHOW_ADDR (1<<3)
-#define PS_DONT_SHOW_FAMILY (1<<4)
+#define PS_SHOW_PORT_IF_DEFINED (1= << 0)

+#define= PS_SHOW_PORT (1 << 1)
+#define PS_SHOW_PKTINFO (1 << 2)+#define PS_DONT_SHOW_ADDR = (1 << 3)
+#= define PS_DONT_SHOW_FAMILY (1 << 4)

<= span style=3D"color: hsl(0, 100%, 40%);">-const char *print_sockaddr_ex(con= st struct sockaddr *addr,

- const char *separator,
- const unsi= gned int flags,
- = struct gc_arena *gc);
+const char *print_sockaddr_ex(const struct sockad= dr *addr, const char *separator,
+ const unsigned int flags, struct= gc_arena *gc);

-static inline
-const char *
-print= _openvpn_sockaddr(const struct openvpn_sockaddr *addr,
- struct gc_arena *gc= )
+static inline cons= t char *
+print_openv= pn_sockaddr(const struct openvpn_sockaddr *addr, struct gc_arena *gc)
{
return print_sockaddr_ex(&addr->a= ddr.sa, ":", PS_SHOW_PORT, gc);
}

-static inline
-const char *
-print_sockaddr(const struct sockadd= r *addr,

- = struct gc_arena *gc)
+print_sockaddr(const struct sockaddr *addr, struct gc_arena *gc)<= /span>
{
return print_sockaddr_ex(addr, &quo= t;:", PS_SHOW_PORT, gc);
}

+const char= *print_link_socket_actual_ex(const struct link_socket_actual *act, const c= har *separator,
+ = const unsigned int flags, struct gc_are= na *gc);

-const char *print_link_socket_actual_ex(const struct link_socket_actua= l *act,
- = const char *separator,
- const un= signed int flags,
- = struct gc_arena *gc);
-
-const char *print_link_socket_actual(const struct link_socke= t_actual *act,
- = struct gc_arena *gc);
+const char *print_link_socket_actual(cons= t struct link_socket_actual *act, struct gc_arena *gc);


-#defi= ne IA_EMPTY_IF_UNDEF (1<<0)
-#define IA_NET_ORDER (1<<1)
+#define IA_EMPTY_IF_UNDEF (1 << 0)
+#define IA_NET_ORDER = (1 << 1)
const char *print_in_addr_t(in_addr_t ad= dr, unsigned int flags, struct gc_arena *gc);

<= span> const char *print_in6_addr(struct in6_addr addr6, unsigned int flags,= struct gc_arena *gc);


const char *print= _in_port_t(in_port_t port, struct gc_arena *gc);
-struct in6_addr add_in6_addr( = struct in6_addr base, uint32_t add );
+struct in6_addr add_in6_addr(struct in6_addr base, uint32= _t add);

-#define SA_IP_PORT (1<<0)
-#define SA_SET_IF_NONZERO (1<<1)
-void setenv_sockaddr(struct env_set = *es,

- = const char *name_prefix,
- const struct openvpn_sockaddr *addr,
= - const unsig= ned int flags);
+#def= ine SA_IP_PORT (1 << 0)
+#define SA_SET_IF_NONZERO (1 << 1)
+void setenv_sockaddr(struct env_set *= es, const char *name_prefix,
+ const struct openvpn_sockaddr *addr, const un= signed int flags);

-void setenv_in_addr_t(struct env_set *es,
- const char *name_p= refix,
- = in_addr_t addr,
-vo= id setenv_in6_addr(struct env_set *es,
- const char *name_prefix,
- const struct = in6_addr *addr,

+void= setenv_in6_addr(struct env_set *es, const char *name_prefix, const struct = in6_addr *addr,
const unsigned int fl= ags);

-void setenv_link_socket_actual(struct env_set *es,
- const char *= name_prefix,
- = const struct link_socket_actual *act,
- const = unsigned int flags);

= +void setenv_link_socket_actual(struct env_set *es, const char *name_prefix= ,
+ = const struct link_socket_actual *act, const unsigned int flags= );

void bad_address_length(int actual, i= nt expected);

@@ -437,20 +409,16 @@
#define IPV4_INVALID_ADDR 0xffffffff
in_addr_t= link_socket_current_remote(const struct link_socket_info *info);
-const struct = in6_addr *link_socket_current_remote_ipv6
- (const struct link_socket_info *info);
+const struct in6_addr *link_sock= et_current_remote_ipv6(const struct link_socket_info *info);


void link_socket_connection_initiated(struct link_sock= et_info *info,
const= struct link_socket_actual *addr,
- const char *common_name,<= /span>
- = struct env_set *es);
+ const char *common_n= ame, struct env_set *es);

-void link_socket_bad_incoming_addr(struct buffer *buf= ,
- = const struct link_socket_info *info,
+void link_socket_bad_incoming_addr(struct= buffer *buf, const struct link_socket_info *info,
= const struct link_socket_actual *from_addr);

-void s= et_actual_address(struct link_socket_actual *actual,
- struct addrinfo *ai= );
+void set_actual_a= ddress(struct link_socket_actual *actual, struct addrinfo *ai);
<= span>

void link_socket_bad_outgoing_addr(void);
@@ -465,9 +433,9 @@
*/
/* return values of openvpn_inet_aton */-#define OIA_HOSTNAME 0
-#define OIA_IP 1
-#define OIA_ERROR -1=
+#define OIA_HOSTNAM= E 0
+#define OIA_IP = 1
+#define OIA_E= RROR -1
int openvpn_inet_aton(const char *dotted_quad, = struct in_addr *addr);

/* integrity vali= dation on pulled options */
@@ -481,23 +449,18 @@
socket_descriptor_t create_socket_tcp(struct addr= info *);

-socket_descriptor_t socket_do_accept(socket_descriptor_t sd,- = struct link_socket_actual *act,
+socket_descriptor_t socket_do_accept(socket_descriptor_t = sd, struct link_socket_actual *act,
= const bool nowait);

#if U= NIX_SOCK_SUPPORT

socket_descriptor_t cre= ate_socket_unix(void);

-void socket_bind_unix(socket_descriptor_t sd,
= - struct soc= kaddr_un *local,
- = const char *prefix);
+void socket_bind_unix(socket_descriptor_t sd, struct sock= addr_un *local, const char *prefix);

-socket_descriptor_t socket_accept_unix(soc= ket_descriptor_t sd,
- = struct sockaddr_un *remote);+socket_descriptor_t socket_a= ccept_unix(socket_descriptor_t sd, struct sockaddr_un *remote);
<= span>

-int socket_conn= ect_unix(socket_descriptor_t sd,
- struct sockaddr_un *remote);
<= span style=3D"color: hsl(120, 100%, 40%);">+int socket_connect_unix(socket_= descriptor_t sd, struct sockaddr_un *remote);


<= span> void sockaddr_unix_init(struct sockaddr_un *local, const char *path);=


@@ -513,20 +476,20 @@
= * DNS resolution
*/

-#define GETADDR_RESOLVE (1&= lt;<0)
-#define GETA= DDR_FATAL (1<<1)
-#define GETADDR_HOST_ORDER (1<<2)<= br>-#define GETADDR_MENTION_RESOL= VE_RETRY (1<<3)
-= #define GETADDR_FATAL_ON_SIGNAL (1<<4)
-#define GETADDR_WARN_ON_SIGNAL (1<&l= t;5)
-#define GETADDR_M= SG_VIRT_OUT (1<<6)
-#define GETADDR_TRY_ONCE (1<<7)
-#define GETADDR_UPDATE_MANAGEMENT_= STATE (1<<8)

-#de= fine GETADDR_RANDOMIZE (1<<9)
-#define GETADDR_PASSIVE (1<<1= 0)
-#define GETADDR_DAT= AGRAM (1<<11)
+#define GETADDR_RESOLVE (1 << 0)<= br>+#define GETADDR_FATAL = (1 << 1)
+#define GETADDR_HOST_ORDER (1 << 2)
+#define GETADDR_MENTION_RESOLVE_= RETRY (1 << 3)

+#define GETADDR_WARN_ON_SIGNAL = (1 << 5)
+#d= efine GETADDR_MSG_VIRT_OUT (1 << 6)
+#define GETADDR_TRY_ONCE (= 1 << 7)
+#defin= e GETADDR_UPDATE_MANAGEMENT_STATE (1 << 8)
+#define GETADDR_RANDOMIZE (1 <= ;< 9)
+#define GET= ADDR_PASSIVE (1 << 10)
+#define GETADDR_DATAGRAM (1 <<= ; 11)

-#define GETADDR_CACHE_MASK (GETADDR_DATAGRAM|GETADDR_PASSIVE= )
+#define GETADDR_CA= CHE_MASK (GETADDR_DATAGRAM | GETADDR_PASSIVE)

<= span> /**

* Translate an IPv4 addr or hostname from strin= g form to in_addr_t
@@ -534,24 +497,17 @@
= * In case of resolve error, it will try again for
* reso= lve_retry_seconds seconds.
*/
-in_addr_t getaddr(unsigned int flags,
<= span style=3D"color: hsl(0, 100%, 40%);">- const char *hos= tname,

- = int resolve_retry_seconds,
- bool *succeeded,
- struct signal_info *sig_info);
+in_addr_t getaddr(unsigne= d int flags, const char *hostname, int resolve_retry_seconds,
+ bool *succeeded= , struct signal_info *sig_info);


/**
* Translate an IPv6 addr or hostname from string form to in6= _addr
*/
-bool get_ipv6_addr(const char *hostname, struct in6_addr *network,
- unsign= ed int *netbits, int msglevel);
+bool get_ipv6_addr(const char *hostname, struct in6_addr *netwo= rk, unsigned int *netbits,
+ int msglevel);

-int openvpn_getaddrinfo(unsigned int f= lags,
- = const char *hostname,
- const char *servname,
- int resolve_retry_s= econds,
- = struct signal_info *sig_info,
- int ai_family,
+int openvpn_getaddrinfo(unsigned int f= lags, const char *hostname, const char *servname,
+ int resolve_retry_sec= onds, struct signal_info *sig_info, int ai_family,
= struct addrinfo **res);

= /*
@@ -562,8 +518,9 @@
* Use enum's = instead of #define to allow for easier
* optional proto s= upport
*/
-enum proto_num {
= - PROTO_NONE, /* catch for uninitialized */
+enum proto_num
+{
+ PROTO_NONE, /* catch for uninitialized */
= PROTO_UDP,
PROTO_TCP,
PROTO_TCP_S= ERVER,
@@ -665,11 +622,14 @@
}<= br> switch (addr->addr.sa.sa_family)
{
- case AF_INET: re= turn addr->addr.in4.sin_addr.s_addr !=3D 0;
+ case AF_INET:
+ return addr->addr.in4.sin_addr.= s_addr !=3D 0;

- case AF_INET6: return !IN6_IS_ADDR_UNSPECIFIED(&addr= ->addr.in6.sin6_addr);
+ case AF_INET6:
+ return !IN6_IS_ADDR_UNSPECIFIED(&addr->addr.in6= .sin6_addr);

- default: return 0;
+ default:
+ return 0;
}
= }

@@ -705,17 +665,21 @@
= switch (lsa->dest.addr.sa.sa_family)
{ #if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST)=
- case AF_INET:= return lsa->pi.in4.ipi_spec_dst.s_addr !=3D 0;
+ case AF_INET:
+ return lsa->pi.in4.ipi_spe= c_dst.s_addr !=3D 0;

#elif defined(IP_RE= CVDSTADDR)
- cas= e AF_INET: return lsa->pi.in4.s_addr !=3D 0;
+ case AF_INET:
+ return lsa->pi.in4.s_addr !=3D= 0;

#endif
- case AF_INET6: return !IN6_IS_ADDR_UNSPECIF= IED(&lsa->pi.in6.ipi6_addr);
+ case AF_INET6:
+ return !IN6_IS_ADDR_UNSPECIFIED(&lsa->= ;pi.in6.ipi6_addr);

- default: return 0;
+ default:
+ return 0;
}
= -#else /* if ENABLE_IP_PKTINFO *= /
+#else /* if ENABLE= _IP_PKTINFO */
ASSERT(0);
#endif
return false;
@@ -751,14 +715,16 @@=
switch (a1->addr.sa.sa_family)
= {
case AF_INET:
- if (a1->addr.in4.sin_addr.s_ad= dr =3D=3D ((struct sockaddr_in *)curele->ai_addr)->sin_addr.s_addr)
+ if (a= 1->addr.in4.sin_addr.s_addr
+ =3D=3D ((struct sockaddr_in *)curele->ai_= addr)->sin_addr.s_addr)
{
return true;

}
break;

= case AF_INET6:
- if (IN6_ARE_ADDR_EQUAL(&a1->addr.in6.sin6_addr, &a= mp;((struct sockaddr_in6 *) curele->ai_addr)->sin6_addr))
<= span style=3D"color: hsl(120, 100%, 40%);">+ if (IN6_ARE_ADD= R_EQUAL(&a1->addr.in6.sin6_addr,

+ &((struct so= ckaddr_in6 *)curele->ai_addr)->sin6_addr))
= {
return true;
= }
@@ -781,7 +747,8 @@
= {
case AF_INET:
= if (curele->ai_family =3D=3D AF_INET
- && a1->addr.in4.si= n_addr.s_addr =3D=3D ((struct sockaddr_in *)curele->ai_addr)->sin_add= r.s_addr
+ = && a1->addr.in4.sin_addr.s_addr
+ =3D=3D ((struc= t sockaddr_in *)curele->ai_addr)->sin_addr.s_addr
= && a1->addr.in4.sin_port =3D=3D ((struct socka= ddr_in *)curele->ai_addr)->sin_port)
= {
return true;
@@ -79= 0,8 +757,10 @@

case AF_INET6= :
if (curele->ai_family =3D=3D AF_INET6=
- &= amp;& IN6_ARE_ADDR_EQUAL(&a1->addr.in6.sin6_addr, &((struct = sockaddr_in6 *) curele->ai_addr)->sin6_addr)
- && a1->addr.in6= .sin6_port =3D=3D ((struct sockaddr_in6 *) curele->ai_addr)->sin6_por= t)
+ = && IN6_ARE_ADDR_EQUAL(&a1->addr.in6.sin6_addr,
= + = &((struct sockaddr_in6 *)curele->ai_addr)->sin6_addr)=
+ = && a1->addr.in6.sin6_port
+ =3D=3D ((struct sockaddr_in6 *= )curele->ai_addr)->sin6_port)
{
return true;
= }
@@ -805,7 +774,6 @@
}


-=
static inline bool
addr_port_match(const= struct openvpn_sockaddr *a1, const struct openvpn_sockaddr *a2)
= {
@@ -824,24 +792,19 @@
}
static inline bool
-addr_match_proto(const struct openvpn_sockaddr *a1,<= /span>
- const= struct openvpn_sockaddr *a2,
+addr_match_proto(const struct openvpn_sockaddr *a1, const struct = openvpn_sockaddr *a2,
const int proto)
{
- r= eturn link_socket_proto_connection_oriented(proto)
- ? addr_match(a1, a2)
- : addr_port_match(a1, a2)= ;

+ return link_so= cket_proto_connection_oriented(proto) ? addr_match(a1, a2)
+ = : addr_port_match(a1, a2);
}

static inline bool
-addrlist_match_proto(const struct = openvpn_sockaddr *a1,

-= struct addrinfo *addr_list,
- const int proto)
= +addrlist_match_proto(const str= uct openvpn_sockaddr *a1, struct addrinfo *addr_list, const int proto)
{
- ret= urn link_socket_proto_connection_oriented(proto)
- ? addrlist_match(a1, addr_list)
- : addrlist_port_= match(a1, addr_list);
+ return link_socket_proto_connection_oriented(proto) ? addrlist_match(= a1, addr_list)
+ = : addrlist_port_match(a1= , addr_list);
}

static = inline void
@@ -864,9 +827,11 @@
{<= br> switch (af)
{
- case AF_INET: return sizeof(struct socka= ddr_in);
+ cas= e AF_INET:
+ = return sizeof(struct sockaddr_in);

- case AF_INET6: return sizeof(stru= ct sockaddr_in6);
+ = case AF_INET6:
= + return sizeof(struct sockaddr_in6);
default:
#if 0
@@ -889,8 = +854,7 @@
static inline bool
socket_forei= gn_protocol_detected(const struct link_socket *sock)
{
- return link_socket_co= nnection_oriented(sock)
- && sock->stream_buf.port_share_state =3D=3D PS_FORE= IGN;
+ return link= _socket_connection_oriented(sock) && sock->stream_buf.port_share= _state =3D=3D PS_FOREIGN;
}

static inline const struct buffer *

@@ -931,8 +895,7 @= @
}

static inline bool<= /span>
-link_socket_verify_inc= oming_addr(struct buffer *buf,
- const struct link_socket_info *in= fo,
+link_socket_veri= fy_incoming_addr(struct buffer *buf, const struct link_socket_info *info,
const struct link_socket_a= ctual *from_addr)
{
if (buf->len &= gt; 0)
@@ -959,8 +922,7 @@
}

static inline void
-link_socket_get_outgoing_addr(struct buffer *buf,=
- = const struct link_socket_info *info,
+link_socket_get_outgoing_addr(struct buffer *buf, const = struct link_socket_info *info,
= struct link_socket_actual **act)
{
= if (buf->len > 0)
@@ -980,23 +942,18 @@
}


static inline void
-link_socket_set_outgoing_addr(struct= link_socket_info *info,

- = const char *common_name,
- struct env_set *es)
+link_socket_set_outgoing_addr(struct l= ink_socket_info *info, const struct link_socket_actual *act,
+ cons= t char *common_name, struct env_set *es)

{
struct link_socket_addr *lsa =3D info->lsa;

i= f (
/* new or changed address? */
= (!info->connection_established
- || !addr_match_proto(&act->dest, &= lsa->actual.dest, info->proto)
- )
+ || !addr_match_proto(&act->dest, &lsa->actual.d= est, info->proto))
&&
= /* address undef or address =3D=3D remote or --float */
<= span> (info->remote_float

- || (!lsa->remote_list || addrlist_match_proto(&a= mp;act->dest, lsa->remote_list, info->proto))
- )
- )
+ || (!lsa->remote_list || addrlist_match_proto(&a= ct->dest, lsa->remote_list, info->proto))))
{=
link_socket_connection_initiated(info, act, commo= n_name, es);
}
@@ -1032,14 +989,12 @@<= /span>
* Socket Read Routines
*/

-int link_socket_r= ead_tcp(struct link_socket *sock,
- struct buffer *buf);
+int link_socket_read_tcp(struct link_= socket *sock, struct buffer *buf);

#ifde= f _WIN32

static inline int
-link_socket_read_udp_win32(struct l= ink_socket *sock,

- = struct buffer *buf,
+link_socket_read_udp_win32(struct link_socket *sock,= struct buffer *buf,
struct lin= k_socket_actual *from)
{
sockethandle= _t sh =3D { .s =3D sock->sd };
@@ -1054,17 +1009,14 @@

#else /* ifdef _WIN32 */

-int link_socket_rea= d_udp_posix(struct link_socket *sock,
- struct buffer *buf,+int link_socket_read_udp_pos= ix(struct link_socket *sock, struct buffer *buf,
= struct link_socket_actual *from);

#endif /* ifdef _WIN32 */

/* read a TCP or UDP packet from link */

static inline i= nt
-link_socket_read(st= ruct link_socket *sock,
- struct buffer *buf,
- struct link_socket_actual *from)+link_socket_read(struct link= _socket *sock, struct buffer *buf, struct link_socket_actual *from)<= br> {
if (proto_is_udp(sock->info.proto) || s= ocket_is_dco_win(sock))
/* unified UDPv4 and UDPv6, fo= r DCO-WIN the kernel
@@ -1096,16 +1048,13 @@
* Socket Write routines

*/
-ssize_t link_socket_write_tcp(= struct link_socket *sock,
- struct buffer *buf,
+ssize_t link_socket_write_tcp(struct link= _socket *sock, struct buffer *buf,
= struct link_socket_actual *to);

#= ifdef _WIN32

static inline int-link_socket_write_win32(struct = link_socket *sock,
- = struct buffer *buf,
- struct link_socket_actual *to)
+link_socket_write_win= 32(struct link_socket *sock, struct buffer *buf, struct link_socket_actual = *to)
{
int err =3D 0;
int status =3D 0;

@@ -1144,16 +1093,14 @@
<= span> }

}

-#else /* ifdef _WIN32 */
+#else /* ifdef _WIN32 */
=
-ssize_t link_socket_= write_udp_posix_sendmsg(struct link_socket *sock,
- str= uct buffer *buf,
+ssi= ze_t link_socket_write_udp_posix_sendmsg(struct link_socket *sock, struct b= uffer *buf,
st= ruct link_socket_actual *to);

static inline ssize_t
-link_socket_write_udp_posix(struct link_socket *sock,
- struct = buffer *buf,

+link_so= cket_write_udp_posix(struct link_socket *sock, struct buffer *buf, struct link_socket_actual *to)<= br> {
#if ENABLE_IP_PKTINFO
@@ -1164= ,14 +1111,12 @@
}
else
= #endif
- retu= rn sendto(sock->sd, BPTR(buf), BLEN(buf), 0,
- (struct sockaddr *) &to->= ;dest.addr.sa,
- = (socklen_t) af_addr_size(to->dest.addr.sa.sa_family));=
+ return sendto(sock= ->sd, BPTR(buf), BLEN(buf), 0, (struct sockaddr *)&to->dest.addr.= sa,
+ = (socklen_t)af_addr_size(to->dest.addr.sa.sa_family));
}


static inline ssize_t
<= span style=3D"color: hsl(0, 100%, 40%);">-link_socket_write_tcp_posix(struc= t link_socket *sock,

- = struct buffer *buf)
+link_socket_write_tcp_posix(struct link_socket *= sock, struct buffer *buf)
{
return se= nd(sock->sd, BPTR(buf), BLEN(buf), MSG_NOSIGNAL);
}
@@ -1179,9 +1124,7 @@
#endif /* ifdef _WIN32 = */

static inline ssize_t
-link_socket_write_udp(struct link_soc= ket *sock,

- = struct buffer *buf,
- struct link_socket_actual *to)
+link_socket_write_udp(struct link= _socket *sock, struct buffer *buf, struct link_socket_actual *to)
{
#ifdef _WIN32
return link_s= ocket_write_win32(sock, buf, to);
@@ -1192,9 +1135,7 @@

/* write a TCP or UDP packet to link */
static inline ssize_t
-link_socket_write(struct link_socket *sock,
- struct buffer *buf,
- struc= t link_socket_actual *to)
+link_socket_write(struct link_socket *sock, struct buffer *buf, struc= t link_socket_actual *to)
{
if (proto= _is_udp(sock->info.proto) || socket_is_dco_win(sock))
= {
@@ -1222,7 +1163,7 @@
{
if (sock && ipbuf)

{
- struct openvpn_iphdr *iph =3D (= struct openvpn_iphdr *) BPTR(ipbuf);
+ struct openvpn_iphdr *iph =3D (struct openvpn_iphd= r *)BPTR(ipbuf);
sock->ptos =3D iph->tos;
sock->ptos_defined =3D true;
= }
@@ -1266,17 +1207,11 @@

event_t socket_listen_event_handle(struct link_socket *sock);

=
-unsigned int
-socket_set(struct link_= socket *sock,
- = struct event_set *es,
- void *arg,
- unsigned int *persistent);
+unsigned int socket_set(struct link_socke= t *sock, struct event_set *es, unsigned int rwflags,
+ void *arg, unsign= ed int *persistent);

static inline void<= /span>
-socket_set_listen_pers= istent(struct link_socket *sock,
- struct event_set *es,
- void *= arg)

+socket_set_list= en_persistent(struct link_socket *sock, struct event_set *es, void *arg)
{
if (sock && !sock->listen_= persistent_queued)
{
diff --git a/src/= openvpn/socks.c b/src/openvpn/socks.c
index 6192c39..481d3f= b 100644
--- a/src/openvpn/socks.c
+++ b/sr= c/openvpn/socks.c
@@ -45,12 +45,10 @@

#include "memdbg.h"

-#define UP_TYPE_SOCKS &qu= ot;SOCKS Proxy"

= +#define UP_TYPE_SOCKS "SOCKS Proxy"

= struct socks_proxy_info *
-socks_proxy_new(const char *server,
- const char *port,
- const char *authfile)<= /span>
+socks_proxy_new(cons= t char *server, const char *port, const char *authfile)
{<= /span>
struct socks_proxy_info *p;
@@ -83,8 +81,7 @@
}

static bool

-socks= _username_password_auth(struct socks_proxy_info *p,
- socket_descrip= tor_t sd,
+socks_user= name_password_auth(struct socks_proxy_info *p, socket_descriptor_t sd,
struct event_timeout *server_poll= _timeout,
volatile int *signa= l_received)
{
@@ -102,24 +99,23 @@<= br> goto cleanup;
}

- if ( (strlen(creds.u= sername) > 255) || (strlen(creds.password) > 255) )
+ if ((strlen(creds.username) > = 255) || (strlen(creds.password) > 255))
{- msg(M_NONFATAL,<= br>- "SOCKS usern= ame and/or password exceeds 255 characters. "
- "Authentication not possib= le.");
+ = msg(M_NONFATAL, "SOCKS username and/or password exceeds 255 characters= . "
+ = "Authentication not possible.");
= goto cleanup;
}

- int sret =3D snprintf(to_send, = sizeof(to_send), "\x01%c%s%c%s",

- (int) strlen(creds.username), = creds.username,
- = (int) strlen(creds.password), creds.password);
= + int sret =3D snprintf(to_s= end, sizeof(to_send), "\x01%c%s%c%s", (int)strlen(creds.username)= ,
+ = creds.username, (int)strlen(creds.password), creds.password);<= br> ASSERT(sret <=3D sizeof(to_send));

size =3D send(sd, to_send, strlen(to_send), MSG_NOSIGNAL);<= /span>

if (size !=3D strlen(to_send))
{
- = msg(D_LINK_ERRORS | M_ERRNO, "socks_username_password_auth: TCP po= rt write failed on send()");
+ msg(D_LINK_ERRORS | M_ERRNO,
+ "socks_username_password_au= th: TCP port write failed on send()");
goto c= leanup;
}

@@ -147,14= +143,16 @@
/* timeout? */
= if (status =3D=3D 0)
{
- msg(D_LINK_ERRORS | M_ERRNO, "= socks_username_password_auth: TCP port read timeout expired");<= br>+ msg(D_LINK_ERRO= RS | M_ERRNO,
+ = "socks_username_password_auth: TCP port read timeout expired= ");
goto cleanup;
= }

/* error */
= if (status < 0)
{
- msg(D_LINK_ERRORS | M_ERRNO, &= quot;socks_username_password_auth: TCP port read failed on select()");=
+ msg(D_L= INK_ERRORS | M_ERRNO,
+ "socks_username_password_auth: TCP port read failed = on select()");
goto cleanup;
}


@@ -164,7 +162,8 @@=
/* error? */
if (size !=3D 1)
{
- msg(D_LINK_ERRORS | M_ERRNO, "socks_username_password_= auth: TCP port read failed on recv()");
+ msg(D_LINK_ERRORS | M_ERRNO,+ "socks_u= sername_password_auth: TCP port read failed on recv()");
goto cleanup;

}
<= /span>
@@ -187,10 +186,8 @@
}

static bool
-socks_handshake(struct socks_proxy_info *p,
- socket_descriptor_t sd,<= br>- struct event_= timeout *server_poll_timeout,
- volatile int *signal_received)
+socks_handshake(struct socks_proxy_info = *p, socket_descriptor_t sd,
+ struct event_timeout *server_poll_timeout, volatile= int *signal_received)
{
char buf[2];=
int len =3D 0;
@@ -201,7 +198,6 @@
if (p->authfile[0])
{
= method_sel[2] =3D 0x02; /* METHODS =3D [2 (plain login)] */<= /span>
-
= }
size =3D send(sd, method_sel, sizeof(method_sel), MS= G_NOSIGNAL);
if (size !=3D sizeof(method_sel))<= br>@@ -282,7 +278,8 @@
case 2: /* login/pass= word */
if (!p->authfile[0])
{

- = msg(D_LINK_ERRORS, "socks_handshake: server asked for usern= ame/login auth but we were "
+ msg(D_LINK_ERRORS,
+ "socks_handshake: ser= ver asked for username/login auth but we were "
= "not provided any credentials");
= return false;
}
@@ -303,15 +300,13 @@

}

static bool

-recv_so= cks_reply(socket_descriptor_t sd,
- struct openvpn_sockaddr *addr,
- struct event_timeout= *server_poll_timeout,

= - volatile int *signal_received)
+recv_socks_reply(socket_descriptor_t sd, struc= t openvpn_sockaddr *addr,
+ struct event_timeout *server_poll_timeout, volatile = int *signal_received)
{
char atyp =3D= '\0';
int alen =3D 0;
in= t len =3D 0;
- char = buf[270]; /* 4 + alen(max 256) + 2 */
+ char buf[270]; /* 4 + alen(max 256) + 2 = */

if (addr !=3D NULL)
{

@@ -379,18 +374,18 @@
{<= /span>
switch (atyp)
{
- case &#= 39;\x01': /* IP V4 */
+ case '\x01': /* IP V4 */
= alen =3D 4;
break;=

- = case '\x03': /* DOMAINNAME */
+ case '\x03': /* D= OMAINNAME */
/* RFC 1928, section 5: 1= byte length, <n> bytes name,
*= so the total "address length" is (length+1)
= */
- = alen =3D (unsigned char) c + 1;
+ alen =3D (unsigned char)= c + 1;
break;
=
- case '\x= 04': /* IP V6 */
+ case '\x04': /* IP V6 */
= alen =3D 16;
break;

@@ -421,8 +416,7 @@
= memcpy(&addr->addr.in4.sin_addr, buf + 4, sizeof(addr->addr.in4.= sin_addr));
memcpy(&addr->addr.in4.sin_port= , buf + 8, sizeof(addr->addr.in4.sin_port));
st= ruct gc_arena gc =3D gc_new();
- msg(M_INFO, "SOCKS proxy wants us to send UDP to %s&q= uot;,
- prin= t_openvpn_sockaddr(addr, &gc));
+ msg(M_INFO, "SOCKS proxy wants us to send UDP = to %s", print_openvpn_sockaddr(addr, &gc));
= gc_free(&gc);
}

@@ -435,12 +429,12 @@

{
int port = =3D 0;
port =3D atoi(servname);
- if (port >0 && port < 655= 36)
+ if (port >= ; 0 && port < 65536)
{
= return port;
}

- struct servent *service;+ struct servent *service;=
service =3D getservbyname(servname, NULL);
= if (service)
{
@@ -452,9 +4= 46,9 @@

void
establish_= socks_proxy_passthru(struct socks_proxy_info *p,
- socket_descriptor= _t sd, /* already open to proxy */
- const char *host, /* op= envpn server remote */
= - const char *servname, /* openvpn server = port */
+ = socket_descriptor_t sd, /* already open to proxy */
+ = const char *host, /* openvpn server remote */
+ const= char *servname, /* openvpn server port */
= struct event_timeout *server_poll_timeout,
struct signal_info *sig_info)

<= span> {

@@ -467,32 +461,34 @@
}=

/* format Socks CONNECT message */<= br>- buf[0] =3D '\x05'= ; /* VER =3D 5 */
- buf[1] =3D '\x01'; /* CMD =3D 1 (CONNECT) */<= /span>
- buf[2] =3D '\x= 00'; /* RSV */
- buf[3] =3D '\x03'; /* ATYP =3D 3 (DOMAINNAME= ) */
+ buf[0] =3D = '\x05'; /* VER =3D 5 */
+ buf[1] =3D '\x01'; /* CMD =3D 1 (CONNECT) */=
+ buf[2] =3D '\x00&#= 39;; /* RSV */
+ b= uf[3] =3D '\x03'; /* ATYP =3D 3 (DOMAINNAME) */

len =3D strlen(host);
len =3D (5 += len + 2 > sizeof(buf)) ? (sizeof(buf) - 5 - 2) : len;
=
- buf[4] =3D (char)= len;
+ buf[4] =3D= (char)len;
memcpy(buf + 5, host, len);

int port =3D port_from_servname(servname);<= br>- if (port =3D=3D0)<= br>+ if (port =3D=3D 0)
{
- = msg(D_LINK_ERRORS, "establish_socks_proxy_passthrough: Cannot con= vert %s to port number", servname);
+ msg(D_LINK_ERRORS, "establish_socks_proxy= _passthrough: Cannot convert %s to port number",
+ servname);
= goto error;
}

- buf[5 + len] =3D (char) (port >= ;> 8);

- buf[5 + = len + 1] =3D (char) (port & 0xff);
+ buf[5 + len] =3D (char)(port >> 8);
= + buf[5 + len + 1] =3D (char= )(port & 0xff);

{
const ssize_t size =3D send(sd, buf, 5 + len + 2, MSG_NOSIGNAL);=

if ((int)size !=3D 5 + (int)len + 2)
{

- = msg(D_LINK_ERRORS | M_ERRNO, "establish_socks_proxy_passthru: TCP= port write failed on send()");
+ msg(D_LINK_ERRORS | M_ERRNO,
+ "establish_socks= _proxy_passthru: TCP port write failed on send()");
= goto error;
}
}
@@ -514,7 +510,7 @@

void
establish_socks_proxy_udpassoc(struct socks_proxy_info *p,<= /span>
- = socket_descriptor_t ctrl_sd, /* already open to proxy */+ = socket_descriptor_t ctrl_sd, /* already open to proxy */
struct openvpn_sockaddr *relay_addr,
struct event_timeout *server_pol= l_timeout,
struct signal_in= fo *sig_info)
@@ -528,12 +524,12 @@
= /* send Socks UDP ASSOCIATE message */
/* VER = =3D 5, CMD =3D 3 (UDP ASSOCIATE), RSV =3D 0, ATYP =3D 1 (IP V4),
= * BND.ADDR =3D 0, BND.PORT =3D 0 */
- const ssize_t size =3D send(ctrl_sd= ,
- = "\x05\x03\x00\x01\x00\x00\x00\x00\x00\x00",<= br>- = 10, MSG_NOSIGNAL);
+ const ssize_t size =3D
+ send(ctrl_sd, "\x05\x03\x00\x01\x00\x00\x00= \x00\x00\x00", 10, MSG_NOSIGNAL);
if (size != =3D 10)
{
- msg(D_LINK_ERRORS | M_ERRNO, "establish_socks= _proxy_passthru: TCP port write failed on send()");
+ msg(D_LINK_ERRORS | M_ERRN= O,
+ &= quot;establish_socks_proxy_passthru: TCP port write failed on send()")= ;
goto error;
}
}
@@ -560,8 +556,7 @@
* R= un after UDP read.
*/
void
-socks_process_incoming_udp(struct b= uffer *buf,

- = struct link_socket_actual *from)
+socks_process_incoming_udp(struct buffer *buf= , struct link_socket_actual *from)
{
= int atyp;

@@ -577,7 +572,7 @@
<= span> }


atyp =3D buf_read_u8(buf= );
- if (atyp !=3D 1= ) /* ATYP =3D=3D 1 (IP V4) */
+ if (atyp !=3D 1) /* ATYP =3D=3D 1 (IP V4) */
{
goto error;
= }
@@ -599,8 +594,7 @@
* Returns the si= ze of the header.
*/
int
-socks_process_outgoing_udp(struct buf= fer *buf,

- = const struct link_socket_actual *to)
+socks_process_outgoing_udp(struct buffer = *buf, const struct link_socket_actual *to)
{
/*

* Get a 10 byte subset buffer prepended to= buf --
@@ -612,8 +606,8 @@
/* crash i= f not enough headroom in buf */
ASSERT(buf_defined(&am= p;head));

- buf_write_u16(&head, 0); /* RSV =3D 0 */
- buf_write_u8(&head, 0); /* = FRAG =3D 0 */
+ bu= f_write_u16(&head, 0); /* RSV =3D 0 */
+ buf_write_u8(&head, 0); /* FRAG =3D= 0 */
buf_write_u8(&head, '\x01'); /* ATYP= =3D 1 (IP V4) */
buf_write(&head, &to->des= t.addr.in4.sin_addr, sizeof(to->dest.addr.in4.sin_addr));
buf_write(&head, &to->dest.addr.in4.sin_port, sizeof(to-&= gt;dest.addr.in4.sin_port));

diff --git a/src/openvpn/socks= .h b/src/openvpn/socks.h
index 985745b..b5a69b9 100644
--- a/src/openvpn/socks.h
+++ b/src/openvpn/soc= ks.h
@@ -33,7 +33,8 @@
struct openvpn_sock= addr;
struct link_socket_actual;
<= br>-struct socks_proxy_info {
+struct socks_proxy_info=
+{
= bool defined;

char server[128];<= /span>
@@ -41,29 +42,26 @@
char authfile[256]= ;
};

-struct socks_proxy_info *socks_proxy_new(const char *serv= er,
- = const char *port,
+struct socks_proxy_info *socks_proxy_new(const char *s= erver, const char *port,
= const char *authfile);

void sock= s_proxy_close(struct socks_proxy_info *sp);

void establish_socks_proxy_passthru(struct socks_proxy_info *p,
<= br>- = socket_descriptor_t sd, /* already open to proxy */
- c= onst char *host, /* openvpn server remote */

- const c= har *servname, /* openvpn server port */
+ socket_de= scriptor_t sd, /* already open to proxy */
+ const char *host= , /* openvpn server remote */
+ const char *servname, = /* openvpn server port */
= struct event_timeout *server_poll_timeout,
= struct signal_info *sig_info);
<= /span>
void establish_socks_proxy_udpassoc(struct socks_proxy_inf= o *p,
- = socket_descriptor_t ctrl_sd, /* already open to proxy = */
+ = socket_descriptor_t ctrl_sd, /* already open to proxy */=
struct openvpn_sockad= dr *relay_addr,
struct= event_timeout *server_poll_timeout,
= struct signal_info *sig_info);

<= span style=3D"color: hsl(0, 100%, 40%);">-void socks_process_incoming_udp(s= truct buffer *buf,

- = struct link_socket_actual *from);
+void socks_process_incoming_udp(= struct buffer *buf, struct link_socket_actual *from);


-int socks_process_outgoin= g_udp(struct buffer *buf,
- const struct link_socket_actual *to);
+int socks_process_outg= oing_udp(struct buffer *buf, const struct link_socket_actual *to);
#endif /* ifndef SOCKS_H */
diff= --git a/src/openvpn/ssl.c b/src/openvpn/ssl.c
index 06621b= d..b7db1e7 100644
--- a/src/openvpn/ssl.c
+= ++ b/src/openvpn/ssl.c
@@ -74,20 +74,20 @@
= static int tls_packets_generated; /* GLOBAL */
static int= tls_packets_sent; /* GLOBAL */

-#define INCR_SENT ++tls_packets_sent=
-#define INCR_GENERATE= D ++tls_packets_generated
-#define INCR_SUCCESS ++tls_handshake_success
-#define INCR_ERROR ++tls_handshake_err= or
+#define INCR_SENT= ++tls_packets_sent
+#define INCR_GENERATED ++tls_packets_generated
+#define INCR_SUCCESS ++tls_handshake_su= ccess
+#define INCR_E= RROR ++tls_handshake_error

void
show_tls_performance_stats(void)
{
= msg(D_TLS_DEBUG_LOW, "TLS Handshakes, success=3D%f%% (good= =3D%d, bad=3D%d), retransmits=3D%f%%",
- (double) tls_handshake_success / (tls_handsha= ke_success + tls_handshake_error) * 100.0,
+ (double)tls_handshake_success / (tls_handsha= ke_success + tls_handshake_error) * 100.0,
tls_han= dshake_success, tls_handshake_error,
- (double) (tls_packets_sent - tls_packets_generated) = / tls_packets_generated * 100.0);
+ (double)(tls_packets_sent - tls_packets_generated) / = tls_packets_generated * 100.0);
}
-#else /* ifdef MEASURE_TLS_HANDSHAKE_STATS */=
+#else /* ifdef MEAS= URE_TLS_HANDSHAKE_STATS */

#define INCR_= SENT
#define INCR_GENERATED
@@ -111,7 +111= ,7 @@
if (*reneg_bytes =3D=3D -1) /* Not user-spec= ified */
{
msg(M_WARN= , "WARNING: cipher with small block size in use, "
- "reducing reneg= -bytes to 64MB to mitigate SWEET32 attacks.");

+ "reducing re= neg-bytes to 64MB to mitigate SWEET32 attacks.");
= *reneg_bytes =3D 64 * 1024 * 1024;
}
}
@@ -129,9 +129,10 @@

/* set limit to 7/8 of the limit so the renegotiation c= an succeed before
* we go over the limit */- limit =3D limit/8 * 7;
+ limit =3D limit / 8 = * 7;

= - msg(D_SHOW_KEYS, "Note: AEAD cipher %s will trigger a renegotiati= on"
+ msg(D_S= HOW_KEYS,
+ &q= uot;Note: AEAD cipher %s will trigger a renegotiation"
" at a sum of %" PRIi64 " blocks and packets."= ;,

ciphername, limit);
return= limit;
@@ -152,8 +153,7 @@
overhead += =3D 10;

/* tls-auth and tls-crypt */=
- overhead +=3D max= _int(tls_crypt_buf_overhead(),
- packet_id_size(true) + OPENVPN_MAX_HMAC_SI= ZE);
+ overhead += =3D max_int(tls_crypt_buf_overhead(), packet_id_size(true) + OPENVPN_MAX_HM= AC_SIZE);

/* TCP length field and op= code */
overhead +=3D 3;
@@ -217,8 +21= 7,7 @@
/* Add the typical UDP overhead for an IPv6 UDP= packet. TCP+IPv6 has a
* larger overhead but the ris= k of a TCP connection getting dropped because
* we tr= y to send a too large packet is basically zero */
- overhead +=3D datagram_overhead(session->= ;untrusted_addr.dest.addr.sa.sa_family,
- PROTO_UDP);
<= span style=3D"color: hsl(120, 100%, 40%);">+ overhead +=3D datagram_over= head(session->untrusted_addr.dest.addr.sa.sa_family, PROTO_UDP);
<= br>
return overhead;
}<= br>@@ -252,7 +251,8 @@
unprotect_user_pass(&= passbuf);
if (!strlen(passbuf.password))
{

- get_= user_pass(&passbuf, auth_file, UP_TYPE_PRIVATE_KEY, GET_USER_PASS_MANAG= EMENT|GET_USER_PASS_PASSWORD_ONLY);
+ get_user_pass(&passbuf, auth_file, UP_TYPE_PRIV= ATE_KEY,
+ = GET_USER_PASS_MANAGEMENT | GET_USER_PASS_PASSWORD_ONLY);<= br> }
}

@@ -29= 1,8 +291,7 @@
}

void
-auth_user_pass_setup(con= st char *auth_file, bool is_inline,
- const struct static_challenge_info *sci)=
+auth_user_pass_setu= p(const char *auth_file, bool is_inline, const struct static_challenge_info= *sci)
{
unsigned int flags =3D GET_U= SER_PASS_MANAGEMENT;

@@ -308,11 +307,7 @@=
if (auth_challenge) /* dynamic challenge/response= */
{
flags |=3D GET_= USER_PASS_DYNAMIC_CHALLENGE;
- get_user_pass_cr(&auth_user_pass,
- auth_file,<= /span>
- = UP_TYPE_AUTH,
- = flags,
- auth_challenge);
+ get_user_pass_cr(&au= th_user_pass, auth_file, UP_TYPE_AUTH, flags, auth_challenge);
}

else if (sci) /* static challenge r= esponse */
{
@@ -325,11 +320,7 @@<= /span>
{
flags |=3D = GET_USER_PASS_STATIC_CHALLENGE_CONCAT;
}
- get_user_pass_c= r(&auth_user_pass,
= - auth_file,
- UP_TYPE_AUTH,
- flags,=

- = sci->challenge_text);
+ get_user_pass_cr(&auth_user_pass, auth_file, U= P_TYPE_AUTH, flags, sci->challenge_text);
}
else
#endif /* ifdef ENABLE_MANAGEME= NT */
@@ -468,11 +459,10 @@
* @param crl_= file_inline True if crl_file is an inline CRL.
*/<= br> static void
-= tls_ctx_reload_crl(struct tls_root_ctx *ssl_ctx, const char *crl_file,
- bool cr= l_file_inline)
+tls_c= tx_reload_crl(struct tls_root_ctx *ssl_ctx, const char *crl_file, bool crl_= file_inline)
{
/* if something goes w= rong with stat(), we'll store 0 as mtime */
- platform_stat_t crl_stat =3D {0};
<= span style=3D"color: hsl(120, 100%, 40%);">+ platform_stat_t crl_stat = =3D { 0 };


/*
= * an inline CRL can't change at runtime, therefore there is no need to<= /span>
@@ -536,11 +526,10 @@

= if (options->dh_file)
{
- tls_ctx_load_dh_params(new_= ctx, options->dh_file,
- options->dh_file_inline);<= br>+ tls_ctx_load_dh= _params(new_ctx, options->dh_file, options->dh_file_inline); }
}
- else /* if client */<= br>+ else /* if client */
{
tls_ctx_client_new(new_ctx);<= /span>
}
@@ -567,8 +556,9 @@
=
if (options->pkcs12_file)
{<= /span>
- if (0 !=3D tls= _ctx_load_pkcs12(new_ctx, options->pkcs12_file,
- options-&= gt;pkcs12_file_inline, !options->ca_file))
+ if (0
+ !=3D tls_ctx_load_pkcs12(new_ctx, options-&= gt;pkcs12_file, options->pkcs12_file_inline,
+ !options->= ;ca_file))
{
goto err= ;
}
@@ -593,8 +583,7 @@
= #ifdef ENABLE_MANAGEMENT
else if (options->m= anagement_flags & MF_EXTERNAL_CERT)
{
- char *cert =3D management_= query_cert(management,

= - options->management_certific= ate);
+ char *= cert =3D management_query_cert(management, options->management_certifica= te);
tls_ctx_load_cert_file(new_ctx, cert, true);<= /span>
free(cert);
}
@@ -606,8 +595,9 @@


if (options->= ;priv_key_file)
{
- if (0 !=3D tls_ctx_load_priv_file(new_ctx, options= ->priv_key_file,
- = options->priv_key_file_inline))
+ if (0+ !=3D tls_ctx_loa= d_priv_file(new_ctx, options->priv_key_file,
+ options-&= gt;priv_key_file_inline))
{
= goto err;
}
@@ -625,15 +615= ,16 @@

if (options->ca_file || op= tions->ca_path)
{
- tls_ctx_load_ca(new_ctx, options->ca_file, o= ptions->ca_file_inline,
- options->ca_path, options->tls_server);<= /span>
+ tls_ctx_load= _ca(new_ctx, options->ca_file, options->ca_file_inline, options->c= a_path,
+ = options->tls_server);
}

/* Load extra certificates that are part of our own= certificate
* chain but shouldn't be included in= the verify chain */
if (options->extra_certs_file)=
{
- tls_ctx_load_extra_certs(new_ctx, options->extra_certs_file, o= ptions->extra_certs_file_inline);
+ tls_ctx_load_extra_certs(new_ctx, options->extr= a_certs_file,
+ = options->extra_certs_file_inline);
= }

/* Check certificate no= tBefore and notAfter */
@@ -777,9 +768,8 @@
for (int i =3D 0; i < KEY_SCAN_SIZE; ++i)

{
struct key_state *ks =3D get_key_scan(multi, i);
- buf_printf(&= out, " [key#%d state=3D%s auth=3D%s id=3D%d sid=3D%s]", i,=
- state_nam= e(ks->state), ks_auth_name(ks->authenticated),
- ks->key_id,+ buf_printf(&out, = " [key#%d state=3D%s auth=3D%s id=3D%d sid=3D%s]", i, state_name(= ks->state),
+ = ks_auth_name(ks->authenticated), ks->key_id,
= session_id_print(&ks->session_id_remote, g= c));
}

@@ -832,8 +82= 2,7 @@
* Build TLS object that reads/writes ciphertex= t
* to/from memory BIOs.
*/
- key_state_ssl_init(&a= mp;ks->ks_ssl, &session->opt->ssl_ctx, session->opt->ser= ver,
- = session);
+ = key_state_ssl_init(&ks->ks_ssl, &session->opt->ssl_ctx, se= ssion->opt->server, session);

= /* Set control-channel initiation mode */
ks->initi= al_opcode =3D session->initial_opcode;
@@ -869,14 +858,1= 2 @@
session->opt->frame.buf.headr= oom, TLS_RELIABLE_N_SEND_BUFFERS,
ks->= ;key_id ? false : session->opt->xmit_hold);
reli= able_init(ks->rec_reliable, BUF_SIZE(&session->opt->frame),
- sessio= n->opt->frame.buf.headroom, TLS_RELIABLE_N_REC_BUFFERS,
- false);
+ session->= ;opt->frame.buf.headroom, TLS_RELIABLE_N_REC_BUFFERS, false);
= reliable_set_timeout(ks->send_reliable, session->opt->p= acket_timeout);

/* init packet ID tr= acker */
- packet_id= _init(&ks->crypto_options.packet_id,
- session->opt->replay_window,= session->opt->replay_time, "SSL",
- ks->key_id);
<= span style=3D"color: hsl(120, 100%, 40%);">+ packet_id_init(&ks->= crypto_options.packet_id, session->opt->replay_window,

+ session->opt= ->replay_time, "SSL", ks->key_id);

=
ks->crypto_options.pid_persist =3D NULL;
=
@@ -888,11 +875,10 @@
* Attempt CRL= reload before TLS negotiation. Won't be performed if
= * the file was not modified since the last reload
= */
- if (session-&= gt;opt->crl_file
- = && !(session->opt->ssl_flags & SSLF_CRL_VERIFY_DIR)= )
+ if (session-&g= t;opt->crl_file && !(session->opt->ssl_flags & SSLF_CR= L_VERIFY_DIR))
{
- tls_ctx_reload_crl(&session->opt->ssl_ctx= ,
- = session->opt->crl_file, session->opt->crl_file_inline);<= /span>
+ tls_ctx_relo= ad_crl(&session->opt->ssl_ctx, session->opt->crl_file,
+ = session->opt->crl_file_inline);
}
<= span> }


@@ -963,7 +949,7 @@
#ifdef ENABLE_MANAGEMENT

|| management_ena= ble_def_auth(management)
#endif
- );
+ );
}

@@ -1012,8 +998,8 @@
}=
else
{
- session->initial_opcode =3D session->opt= ->tls_crypt_v2 ?
- = P_CONTROL_HARD_RESET_CLIENT_V3 : P_CONTROL_= HARD_RESET_CLIENT_V2;
+ session->initial_opcode =3D session->opt->tls_crypt_v2 ?= P_CONTROL_HARD_RESET_CLIENT_V3
+ : = P_CONTROL_HARD_RESET_CLIENT_V2;
}

/* Initialize control channel authentication parameters = */
@@ -1021,10 +1007,8 @@
session->= tls_wrap.work =3D alloc_buf(BUF_SIZE(&session->opt->frame));

/* initialize packet ID replay window fo= r --tls-auth */
- pa= cket_id_init(&session->tls_wrap.opt.packet_id,
- session->opt->repl= ay_window,
- = session->opt->replay_time,
- "TLS_WRAP", session->key= _id);
+ packet_id_= init(&session->tls_wrap.opt.packet_id, session->opt->replay_wi= ndow,
+ = session->opt->replay_time, "TLS_WRAP", session->key= _id);

/* If we are using tls-crypt-v= 2 we manipulate the packet id to be (ab)used
* to ind= icate early protocol negotiation */
@@ -1035,8 +1019,7 @@
}

/* load most r= ecent packet-id to replay protect on --tls-auth */
- packet_id_persist_load_obj(session->tls= _wrap.opt.pid_persist,
= - &session->tls_wrap.opt.packet_id);
+ packet_id_persist= _load_obj(session->tls_wrap.opt.pid_persist, &session->tls_wrap.o= pt.packet_id);

key_state_init(sessio= n, &session->key[KS_PRIMARY]);

@@ = -1094,9 +1077,7 @@
move_session(struct tls_multi *multi, i= nt dest, int src, bool reinit_src)
{
= msg(D_TLS_DEBUG_LOW, "TLS: move_session: dest=3D%s src=3D%s reinit_src= =3D%d",
- s= ession_index_name(dest),
- reinit_src);
+ session_index_name(dest), session_index_name(src), r= einit_src);
ASSERT(src !=3D dest);
= ASSERT(src >=3D 0 && src < TM_SIZE);
A= SSERT(dest >=3D 0 && dest < TM_SIZE);
@@ -120= 0,8 +1181,7 @@
*/

stru= ct tls_auth_standalone *
- struct gc_a= rena *gc)
+tls_auth_s= tandalone_init(struct tls_options *tls_options, struct gc_arena *gc)=
{
struct tls_auth_standalone *tas;
@@ -1242,9 +1222,7 @@
* sets.
*/
void
-tls_multi_init_set_options(struct tls_multi *multi,
- = const char *local,
- = const char *remote)
+tls_multi_init_set_options(struct tls_multi *mult= i, const char *local, const char *remote)
{
/* initialize options string */

multi->opt.l= ocal_options =3D local;
@@ -1290,8 +1268,7 @@
*/


static void
-key_source_print(const struct key_source *= k,
- co= nst char *prefix)
+ke= y_source_print(const struct key_source *k, const char *prefix)
{

struct gc_arena gc =3D gc_new();

@@ -1299,17 +1276,11 @@
VALGRIND_M= AKE_READABLE((void *)k->random1, sizeof(k->random1));
VALGRIND_MAKE_READABLE((void *)k->random2, sizeof(k->random2));=


- = dmsg(D_SHOW_KEY_SOURCE,
- prefix,
+ dmsg(D_SHOW_KEY_SOURCE, "%s pre_master: %s"= , prefix,
format_hex(k->pre_master, sizeof(k-&= gt;pre_master), 0, &gc));
- dmsg(D_SHOW_KEY_SOURCE,
- "%s random1: %s",
- prefix,
+ dmsg(D_SHOW_KEY_SOURCE, "%s random1: %s&= quot;, prefix,
format_hex(k->random1, sizeof(k= ->random1), 0, &gc));
- dmsg(D_SHOW_KEY_SOURCE,
- "%s random2: %s",
- prefix,
+ dmsg(D_SHOW_KEY_SOURCE, "%s random2: %s&q= uot;, prefix,
format_hex(k->random2, sizeof(k-= >random2), 0, &gc));

gc_free(= &gc);
@@ -1323,24 +1294,15 @@
}=

static bool
-openvpn_PRF(const uint8_t *secret,
- int secret_len,
- const char *label,
=
- const uint8_t *c= lient_seed,
- = int client_seed_len,
= - const uint8_t *server_seed,
- int server_seed_len,
- const struct session_id *client= _sid,
- cons= t struct session_id *server_sid,
- uint8_t *output,
- int output_len)
+openvpn_PRF(const uint8_t *secret, int secret_len= , const char *label, const uint8_t *client_seed,
+ int client_seed_len, const uint8_t= *server_seed, int server_seed_len,
+ const struct session_id *client_sid, const stru= ct session_id *server_sid,
+ uint8_t *output, int output_len)
{
/* concatenate seed components */
=
- struct buffer seed =3D a= lloc_buf(strlen(label)
= - + client_seed_len
- + server= _seed_len
- = + SID_SIZE * 2);
+ struct buffer seed =3D
+ alloc_buf(strlen(label) + client_seed_le= n + server_seed_len + SID_SIZE * 2);

= ASSERT(buf_write(&seed, label, strlen(label)));
A= SSERT(buf_write(&seed, client_seed, client_seed_len));
= @@ -1356,8 +1318,7 @@
}

/* compute PRF */

- bool ret =3D ssl_tls1_PRF(BPTR(&seed), BLEN(&seed), secret= , secret_len,
- = output, output_len);
+ bool ret =3D ssl_tls1_PRF(BPTR(&seed), BLEN(&a= mp;seed), secret, secret_len, output, output_len);
=
buf_clear(&seed);
free_buf(&see= d);
@@ -1367,11 +1328,8 @@
}

static void
-init_epoch_keys(struct key_state *ks,
- struct tls_multi *multi,=
- const struct= key_type *key_type,
- = bool server,
- struct key2 *key2)
+init_epoch_keys(struct key_state *ks, struct tls_multi= *multi, const struct key_type *key_type,
+ bool server, struct key2 *key2)
{
/* For now we hardcode this to be 16 for= the software based data channel
* DCO based implemen= tations/HW implementation might adjust this number
@@ -1402= ,19 +1360,15 @@
* b) They let userspace do the key de= rivation and pass all the individual
* keys to the DC= O layer.
* */
- epoch_init_key_ctx(co, key_type, &e1_send, &e1_re= cv, future_key_count);
+ epoch_init_key_ctx(co, key_type, &e1_send, &e1_recv, future= _key_count);

secure_memzero(&e1_= send, sizeof(e1_send));
secure_memzero(&e1_recv, s= izeof(e1_recv));
}

stat= ic void
-init_key_conte= xts(struct key_state *ks,
- struct tls_multi *multi,
- const struct key_type *key_type,=
- boo= l server,
- = struct key2 *key2,
+init_key_contexts(struct key_state *ks, struct tls_multi= *multi, const struct key_type *key_type,
+ bool server, struct key2 *key2, boo= l dco_enabled)
{
struct key_ctx_bi *k= ey =3D &ks->crypto_options.key_ctx_bi;

<= span>@@ -1428,12 +1382,10 @@

msg(M_FATAL, &quo= t;FATAL: DCO does not support --auth");
}

- = int ret =3D init_key_dco_bi(multi, ks, key2, key_direction,
- ke= y_type->cipher, server);

+ int ret =3D init_key_dco_bi(multi, ks, key2, key_direction,= key_type->cipher, server);
if (ret < 0)
{
- msg(M_FATAL, "Impossible to install key material in DCO:= %s",
- = strerror(-ret));
+ msg(M_FATAL, "Impossible to install key material in DCO:= %s", strerror(-ret));
}

/* encrypt/decrypt context are unused with DCO */
@@ -1445,7 +1397,8 @@
{
= if (!cipher_kt_mode_aead(key_type->cipher))
= {
- ms= g(M_FATAL, "AEAD cipher (currently %s) "
+ msg(M_FATAL,
+ "AEAD cipher (curr= ently %s) "
"required for epoch = data format.",
cipher_kt_name(key_typ= e->cipher));
}
@@ -1461,8 +1414= ,8 @@
generate_key_expansion_tls_export(struct tls_session= *session, struct key2 *key2)
{
if (!= key_state_export_keying_material(session, EXPORT_KEY_DATA_LABEL,
= - = strlen(EXPORT_KEY_DATA_LABEL),
- key2->keys,= sizeof(key2->keys)))
+ strlen(EXPORT_KEY_DATA_LABEL= ), key2->keys,
+ = sizeof(key2->keys)))
<= span> {

return false;
}
@@ -1479,42 +1432,28 @@
const struct ke= y_state *ks =3D &session->key[KS_PRIMARY];
cons= t struct key_source2 *key_src =3D ks->key_src;
<= br>- const struct session_id *= client_sid =3D session->opt->server ?
- &ks->= ;session_id_remote : &session->session_id;
- const struct session_id *server_sid =3D !se= ssion->opt->server ?
- &ks->session_id_remot= e : &session->session_id;
+ const struct session_id *client_sid =3D
+ session->opt->server ? &= amp;ks->session_id_remote : &session->session_id;
+ const struct session_id *server= _sid =3D

+ !se= ssion->opt->server ? &ks->session_id_remote : &session->= ;session_id;

/* debugging print of s= ource key material */
key_source2_print(key_src);

/* compute master secret */
- if (!openvpn_PRF(key_src->c= lient.pre_master,

- = sizeof(key_src->client.pre_master),
- KEY_EXPANSION_ID &qu= ot; master secret",
- sizeof(key_src->cli= ent.random1),
- = key_src->server.random1,
- sizeof(key_src->server.random1),=
- = NULL,
- = NULL,
- = master,
- = sizeof(master)))
+ if (!openvpn_PRF(key_src->client.pre_master, sizeof(ke= y_src->client.pre_master),
+ KEY_EXPANSION_ID " master secret",= key_src->client.random1,
+ sizeof(key_src->client.random1), key_src-&= gt;server.random1,
+ = sizeof(key_src->server.random1), NULL, NULL, master,= sizeof(master)))
{
return fa= lse;
}

/* compu= te key expansion */
- = if (!openvpn_PRF(master,
- sizeof(master),
- KEY_EXPANSION_ID " key expans= ion",
- = key_src->client.random2,
- sizeof(key_src->client.random2),
- key= _src->server.random2,
- client_sid,
- serve= r_sid,
- = (uint8_t *)key2->keys,
- sizeof(key2->keys)))
+ if (!openvpn_PRF(master, sizeof(mast= er), KEY_EXPANSION_ID " key expansion",
+ key_src->client.rando= m2, sizeof(key_src->client.random2),
+ key_src->server.random2, sizeof= (key_src->server.random2), client_sid,
+ server_sid, (uint8_t *)key2->= keys, sizeof(key2->keys)))
{
= return false;
}
@@ -1530,8 +1469,7 = @@
* master key.
*/
st= atic bool
-generate_key= _expansion(struct tls_multi *multi, struct key_state *ks,
- struct tls_sessi= on *session)
+generat= e_key_expansion(struct tls_multi *multi, struct key_state *ks, struct tls_s= ession *session)
{
struct key_ctx_bi = *key =3D &ks->crypto_options.key_ctx_bi;
bool r= et =3D false;
@@ -1558,17 +1496,16 @@
= if (!generate_key_expansion_openvpn_prf(session, &key2))
= {
msg(D_TLS_ERRORS, "TLS E= rror: PRF calculation failed. Your system "
- "might not support the old = TLS 1.0 PRF calculation anymore or "
- "the policy does not allow it (e.g= . running in FIPS mode). "
- "The peer did not announce support for the m= odern TLS Export "
- "feature that replaces the TLS 1.0 PRF (requires Ope= nVPN "
- = "2.6.x or higher)");
+ "might not support the = old TLS 1.0 PRF calculation anymore or "
+ "the policy do= es not allow it (e.g. running in FIPS mode). "
+ "The p= eer did not announce support for the modern TLS Export "
+ &qu= ot;feature that replaces the TLS 1.0 PRF (requires OpenVPN "
+ = "2.6.x or higher)");
goto exit;
}
}

= - key2_print(&key2, &s= ession->opt->key_type,
- "Master Encrypt", "Master Decrypt"= ;);
+ key2_print(&= amp;key2, &session->opt->key_type, "Master Encrypt", &q= uot;Master Decrypt");

/* check = for weak keys */
for (int i =3D 0; i < 2; ++i)
@@ -1580,8 +1517,7 @@
}
}


- init_key_contexts(ks, multi, &session->opt->key_type, se= rver, &key2,
- = session->opt->dco_enabled);
+ init_key_contexts(ks, multi, &sessio= n->opt->key_type, server, &key2, session->opt->dco_enabled)= ;
ret =3D true;

exi= t:
@@ -1597,11 +1533,10 @@
* can thus be = called only once per session.
*/
bool
-tls_session_generate_dat= a_channel_keys(struct tls_multi *multi,
- struct tls_session= *session)
+tls_sessi= on_generate_data_channel_keys(struct tls_multi *multi, struct tls_session *= session)
{
bool ret =3D false;=
- struct key_state *ks =3D= &session->key[KS_PRIMARY]; /* primary key */
+ struct key_state *ks =3D &sessio= n->key[KS_PRIMARY]; /* primary key */

= if (ks->authenticated <=3D KS_AUTH_FALSE)
{=
@@ -1616,8 +1551,7 @@
msg(D_TLS_E= RRORS, "TLS Error: generate_key_expansion failed");
goto cleanup;

}
- tls_limit_reneg_bytes(session->opt->ke= y_type.cipher,
- = &session->opt->renegotiate_bytes);
<= span style=3D"color: hsl(120, 100%, 40%);">+ tls_limit_reneg_bytes(sessi= on->opt->key_type.cipher, &session->opt->renegotiate_bytes)= ;


session->opt->aead_usage_lim= it =3D tls_get_limit_aead(session->opt->key_type.cipher);
<= span>

@@ -1631,23 +1565,18 @@
}
bool
-tls_session_update_crypto_params_do_work(struct tls_multi *multi,<= /span>
- = struct tls_session *session,
- struct o= ptions *options,
- = struct frame *frame,
- = struct frame *frame_fragment,
- struct link_socket_info *= lsi,
+tls_session_upd= ate_crypto_params_do_work(struct tls_multi *multi, struct tls_session *sess= ion,
+ = struct options *options, struct frame *frame,
+ = struct frame *frame_fragment, struct link_socket_info *ls= i,
dco_context_t = *dco)
{
if (session->key[KS_PRIMAR= Y].crypto_options.key_ctx_bi.initialized)
{
= /* keys already generated, nothing to do */
= return true;
-=
}

- init_key_type(&session->opt->key_type, op= tions->ciphername,
-= options->authname, true, true);
+ init_key_type(&session->opt-&g= t;key_type, options->ciphername, options->authname, true, true);

bool packet_id_long_form =3D cipher_kt_m= ode_ofb_cfb(session->opt->key_type.cipher);
sess= ion->opt->crypto_flags &=3D ~(CO_PACKET_ID_LONG_FORM);
= @@ -1691,10 +1620,8 @@
* mssfix are set to = update in-kernel config */
if (options->ping_se= nd_timeout || frame->mss_fix)
{
- int ret =3D dco_set_peer(= dco, multi->dco_peer_id,

- options->ping_send_timeout,
- = options->ping_rec_timeout,
- frame->mss_fix);
+ int ret = =3D dco_set_peer(dco, multi->dco_peer_id, options->ping_send_timeout,=
+ = options->ping_rec_timeout, frame->mss_fix); if (ret < 0)
{ msg(D_DCO, "Cannot set DCO peer parameters fo= r peer (id=3D%u): %s",
@@ -1707,11 +1634,9 @@ }

bool
-tls_session_update_crypto_params(struct tls_mu= lti *multi,
- = struct tls_session *session,
+tls_session_update_crypto_params(struct t= ls_multi *multi, struct tls_session *session,
= struct options *options, struct frame *frame,- = struct frame *frame_fragment,
- struct link_socket_info *lsi,
+ = struct frame *frame_fragment, struct link_socket_info *lsi,
dco_context_t *dco) {
if (!check_session_cipher(session, options)= )
@@ -1722,19 +1647,18 @@
/* Import cr= ypto settings that might be set by pull/push */
sessio= n->opt->crypto_flags |=3D options->imported_protocol_flags;=

- return= tls_session_update_crypto_params_do_work(multi, session, options,- = frame, frame_fragment, lsi, dco);
+ return tls_session_update_crypto_pa= rams_do_work(multi, session, options, frame, frame_fragment,
+ = lsi, dco);

}

static bool
-random_bytes_to_buf(struct buffer *buf,
- uint8_t *out,<= br>- int outle= n)
+random_bytes_to_b= uf(struct buffer *buf, uint8_t *out, int outlen)
{<= br> if (!rand_bytes(out, outlen))
{- msg(M_FATAL, "ERR= OR: Random number generator cannot obtain entropy for key generation [SSL]&= quot;);
+ msg(= M_FATAL,
+ = "ERROR: Random number generator cannot obtain entropy for key generat= ion [SSL]");
}
if (!buf_writ= e(buf, out, outlen))
{
@@ -1744,9 +166= 8,7 @@
}

static bool
-key_source2_randomize_wr= ite(struct key_source2 *k2,
- struct buffer *buf,
- bool server)
+key_source2_randomize_= write(struct key_source2 *k2, struct buffer *buf, bool server)
{

struct key_source *k =3D &k2->client;
if (server)
@@ -1777,9 +1699,7 @@=
}

static int
-key_source2_read(struct key_source2 *k= 2,
- st= ruct buffer *buf,
- = bool server)
+key_source2_read(struct key_source2 *k2, struct buffer *buf, bool ser= ver)
{
struct key_source *k =3D &= k2->client;

@@ -1829,10 +1749,10 @@
static void
key_state_soft_reset(struct tls= _session *session)
{
- struct key_state *ks =3D &session->key[KS_PRIMAR= Y]; /* primary key */
+ struct key_state *ks =3D &session->key[KS_PRIMARY]; = /* primary key */
struct key_state *ks_lame =3D &= ;session->key[KS_LAME_DUCK]; /* retiring key */
=
- ks->must_die =3D now = + session->opt->transition_window; /* remaining lifetime of old key *= /
+ ks->must_di= e =3D now + session->opt->transition_window; /* remaining lifetime= of old key */
key_state_free(ks_lame, false);<= br> *ks_lame =3D *ks;

@@ -1905,= 7 +1825,7 @@
{
return -len;
}
-= str[len-1] =3D '\0';
+ str[len - 1] =3D '\0';
return= len;
}

@@ -1919,14 +183= 9,14 @@
{
return NULL;=
}
- s= tr =3D (char *) malloc(len);
+ str =3D (char *)malloc(len);
check_malloc= _return(str);
if (!buf_read(buf, str, len))
= {
free(str);
r= eturn NULL;
}
- str[len-1] =3D '\0';
+ str[len - 1] =3D '\0';
return str;

}

@@ = -2019,7 +1939,6 @@
if (tls_item_in_cipher_list= ("AES-128-GCM", session->opt->config_ncp_ciphers) && tls_item_in_cipher_list("AES-256-GC= M", session->opt->config_ncp_ciphers))
= {
-
buf_printf(&out, "IV_NCP=3D2\n");
}
}
@@ -2058,7= +1977,7 @@
{
= buf_printf(&out, "IV_HWADDR=3D%s\n", format_hex_ex(rgi.hwadd= r, 6, 0, 1, ":", &gc));
}=
- buf_printf(&= out, "IV_SSL=3D%s\n", get_ssl_library_version() );
+ buf_printf(&out, &= quot;IV_SSL=3D%s\n", get_ssl_library_version());

#if = defined(_WIN32)
buf_printf(&out, "IV_= PLAT_VER=3D%s\n", win32_version_string(&gc));
#el= se
@@ -2080,8 +1999,7 @@
= || strncmp(e->string, "IV_PLAT_VER=3D", sizeof("= ;IV_PLAT_VER=3D") - 1) =3D=3D 0)
= && session->opt->push_peer_info_detail > 2) || (strncmp(e->string, "IV_GUI_VE= R=3D", sizeof("IV_GUI_VER=3D") - 1) =3D=3D 0)
- || (strncmp= (e->string, "IV_SSO=3D", sizeof("IV_SSO=3D") - 1) = =3D=3D 0)

- = )
+ = || (strncmp(e->string, "IV_SSO=3D", sizeof= ("IV_SSO=3D") - 1) =3D=3D 0))
= && buf_safe(&out, strlen(e->string) + 1))
{

buf_pri= ntf(&out, "%s\n", e->string);
@@ -2128,7 += 2046,7 @@
static bool
key_method_2_write(= struct buffer *buf, struct tls_multi *multi, struct tls_session *session)
{
- = struct key_state *ks =3D &session->key[KS_PRIMARY]; /* primary = key */
+ struct ke= y_state *ks =3D &session->key[KS_PRIMARY]; /* primary key */<= br>
ASSERT(buf_init(buf, 0));
=
@@ -2163,7 +2081,7 @@
} else
#endif
- if (!write_string(buf, session->opt->l= ocal_options, TLS_OPTIONS_LEN))
+ if (!write_string(buf, session->opt->local_op= tions, TLS_OPTIONS_LEN))
{
= goto error;
}
@@ -2174,8 +20= 92,7 @@
{
#ifdef ENABLE_MANAGEMENT
auth_user_pass_setup(session->opt->auth_user_p= ass_file,
- = session->opt->auth_user_pass_file_inline,
= - ses= sion->opt->sci);
- if (session->opt->server &= ;& session->opt->mode !=3D MODE_SERVER
- && ks->key_id =3D=3D 0)
+ if (session->opt-&= gt;server && session->opt->mode !=3D MODE_SERVER && k= s->key_id =3D=3D 0)
{
/* t= ls-server option set and not P2MP server, so we
*= are a P2P client running in tls-server mode */
@@ -2253,18= +2169,16 @@
struct gc_arena gc =3D gc_new();

unsigned char *ekm =3D gc_malloc(ses= sion->opt->ekm_size, true, &gc);
- if (key_state_export_keying_material(session,<= /span>
- = session->opt->ekm_label,
- = session->opt->ekm_label_size,
- ekm, session-&= gt;opt->ekm_size))
+ if (key_state_export_keying_material(session, session->opt->= ;ekm_label,
+ = session->opt->ekm_label_size, ek= m,
+ = session->opt->ekm_size))
= {
unsigned int len =3D (size * 2) + 2= ;

const char *key =3D format= _hex_ex(ekm, size, len, 0, NULL, &gc);
set= env_str(session->opt->es, "exported_keying_material", key);=

- = dmsg(D_TLS_DEBUG_MED, "%s: exported keying material: %s"= ,
- __f= unc__, key);
+ = dmsg(D_TLS_DEBUG_MED, "%s: exported keying material: %s", __= func__, key);
secure_memzero(ekm, size);
}
else
@@ -228= 3,7 +2197,7 @@
static bool
key_method_2_r= ead(struct buffer *buf, struct tls_multi *multi, struct tls_session *sessio= n)
{
-= struct key_state *ks =3D &session->key[KS_PRIMARY]; /* prim= ary key */
+ struc= t key_state *ks =3D &session->key[KS_PRIMARY]; /* primary key */

struct gc_arena gc =3D gc_new();=
char *options;
@@ -2295,8 +2209,7 @@<= br> /* discard leading uint32 */
if (!buf_ad= vance(buf, 4))
{
- msg(D_TLS_ERRORS, "TLS ERROR: Plaintext buffer= too short (%d bytes).",
- buf->len);
+ msg(D_TLS_ERRORS, "TLS ERROR: Plaintext buffer t= oo short (%d bytes).", buf->len);
goto err= or;
}

@@ -2304,8 +22= 17,7 @@
int key_method_flags =3D buf_read_u8(buf);
if ((key_method_flags & KEY_METHOD_MASK) !=3D 2)
{
- = msg(D_TLS_ERRORS,
= - "TLS ERROR: Unknown key_method/flags=3D%d received from r= emote host",
+ = msg(D_TLS_ERRORS, "TLS ERROR: Unknown key_method/flags=3D%d rece= ived from remote host",
key_method_flags)= ;
goto error;
}
@@ -2313,7 +2225,8 @@

/* get key source material (n= ot actual keys yet) */
if (!key_source2_read(ks->ke= y_src, buf, session->opt->server))
{
<= span style=3D"color: hsl(0, 100%, 40%);">- msg(D_TLS_ERRORS, "T= LS Error: Error reading remote data channel key source entropy from plainte= xt buffer");

+ = msg(D_TLS_ERRORS,
+ "TLS Error: Error reading remote data channel key sour= ce entropy from plaintext buffer");
goto erro= r;
}

@@ -2343,13 +22= 56,11 @@
}

free= (multi->remote_ciphername);
- multi->remote_ciphername =3D
- options_string_extract_option(options, "= ;cipher", NULL);
+ multi->remote_ciphername =3D options_string_extract_option(options= , "cipher", NULL);
multi->remote_usescomp= =3D strstr(options, ",comp-lzo,");

<= span> /* In OCC we send '[null-cipher]' instead 'none' = */

- if (multi->r= emote_ciphername
- = && strcmp(multi->remote_ciphername, "[null-cipher]"= ) =3D=3D 0)
+ if (= multi->remote_ciphername && strcmp(multi->remote_ciphername, = "[null-cipher]") =3D=3D 0)
{
free(multi->remote_ciphername);

multi= ->remote_ciphername =3D string_alloc("none", NULL);
= @@ -2357,10 +2268,10 @@

if (us= ername_len < 0 || password_len < 0)
{
= - msg(D_TLS_ERRORS, "= TLS Error: Username (%d) or password (%d) too long",
- abs(username_len), abs(pass= word_len));
+ = msg(D_TLS_ERRORS, "TLS Error: Username (%d) or password (%d) too long&= quot;, abs(username_len),
+ abs(password_len));
auth_set_cli= ent_reason(multi, "Username or password is too long. "
= - &= quot;Maximum length is 128 bytes");
+ "Maximum le= ngth is 128 bytes");

/* tre= at the same as failed username/password and do not error
= * out (goto error) to sent an AUTH_FAILED back to the client */
@@ -2386,8 +2297,7 @@
/* Session veri= fication should have occurred during TLS negotiation*/
= if (!session->verified)
{
- msg(D_TLS_ERRORS,- "TLS Erro= r: Certificate verification failed (key-method 2)");
+ msg(D_TLS_ERRORS, "T= LS Error: Certificate verification failed (key-method 2)");
= goto error;
}
= ks->authenticated =3D KS_AUTH_TRUE;
@@ -2410,7 += 2320,7 @@
if (multi->opt.comp_options.flags &am= p; COMP_F_MIGRATE && multi->remote_usescomp)
= {
msg(D_PUSH, "Note: 'compress = migrate' detected remote peer "
- "with compression enabled.");<= /span>
+ = "with compression enabled.");
re= mote_options =3D options_string_compat_lzo(remote_options, &gc);=
}
#endif
@@ -2419,7 +23= 29,8 @@

if (session->opt->= ssl_flags & SSLF_OPT_VERIFY)
{
- msg(D_TLS_ERRORS, "O= ption inconsistency warnings triggering disconnect due to --opt-verify"= ;);

+ msg(= D_TLS_ERRORS,
+ = "Option inconsistency warnings triggering disconnect due to = --opt-verify");
ks->authenticated =3D = KS_AUTH_FALSE;
}
}
= @@ -2435,7 +2346,9 @@
{
= export_user_keying_material(session);

- if (plugin_call(session->opt-= >plugins, OPENVPN_PLUGIN_TLS_FINAL, NULL, NULL, session->opt->es) = !=3D OPENVPN_PLUGIN_FUNC_SUCCESS)
+ if (plugin_call(session->opt->plugins, OPENVPN_= PLUGIN_TLS_FINAL, NULL, NULL,
+ session->opt->es)
+ !=3D OPENVPN_PLUGIN_FUNC_= SUCCESS)
{
ks->aut= henticated =3D KS_AUTH_FALSE;
}
@@= -2485,8 +2398,8 @@
* @return if the state change was suc= cesful
*/
static bool
-session_move_pre_start(const struct tls_= session *session,
- = struct key_state *ks, bool skip_initial_send)
= +session_move_pre_start(const s= truct tls_session *session, struct key_state *ks,
+ bool skip_initial_send= )
{
struct buffer *buf =3D reliable_g= et_buf_output_sequenced(ks->send_reliable);
if (!bu= f)
@@ -2519,17 +2432,10 @@
#ifdef ENABLE_M= ANAGEMENT
if (management && ks->initial_opc= ode !=3D P_CONTROL_SOFT_RESET_V1)
{
- management_set_state(management,=
- = OPENVPN_STATE_WAIT,
- NULL,
- NULL,
- NULL,- N= ULL,
- = NULL);
+ = management_set_state(management, OPENVPN_STATE_WAIT, NULL, NULL, NUL= L, NULL, NULL);
}
#endif
return true;

-=
}

/**
= @@ -2538,8 +2444,7 @@
*/
static void
session_move_active(struct tls_multi *multi, struct tls_sessi= on *session,
- = struct link_socket_info *to_link_socket_info,
- struct key_state *ks= )
+ = struct link_socket_info *to_link_socket_info, struct key_state *ks)
{
dmsg(D_TLS_DEBUG_MED, "STATE S_ACTI= VE");

@@ -2554,8 +2459,8 @@ INCR_SUCCESS;

/* Set ou= tgoing address for data channel packets */
- link_socket_set_outgoing_addr(to_link_socket_info,= &ks->remote_addr,
- session->common_name, session->= opt->es);
+ lin= k_socket_set_outgoing_addr(to_link_socket_info, &ks->remote_addr, se= ssion->common_name,
-session_skip_to_pre_start(struct tls_session *session,- struc= t tls_pre_decrypt_state *state,
+session_skip_to_pre_start(struct tls_session *session, struct t= ls_pre_decrypt_state *state,
str= uct link_socket_actual *from)
{
struc= t key_state *ks =3D &session->key[KS_PRIMARY];
@@ -2= 656,8 +2560,7 @@
* Returns false if an error is encounter= ed that should abort the session.
*/
sta= tic bool
-read_incoming= _tls_ciphertext(struct buffer *buf, struct key_state *ks,
- bool *cont= inue_tls_process)
+re= ad_incoming_tls_ciphertext(struct buffer *buf, struct key_state *ks, bool *= continue_tls_process)
{
int status = =3D 0;
if (buf->len)
@@ -2665,8 +25= 68,7 @@
status =3D key_state_write_ciphertext(&= ;ks->ks_ssl, buf);
if (status =3D=3D -1)=
{
- = msg(D_TLS_ERRORS,
- "TLS Error: Incoming Ciphertext -> TLS objec= t write error");
+ msg(D_TLS_ERRORS, "TLS Error: Incoming Ciphertext -> = TLS object write error");
return false;
}
}
@@ -2686,1= 4 +2588,13 @@
static bool
control_packet_= needs_wkc(const struct key_state *ks)
{
- return (ks->crypto_options.flags = & CO_RESEND_WKC)
- = && (ks->send_reliable->packet_id =3D=3D 1);<= br>+ return (ks->crypto_o= ptions.flags & CO_RESEND_WKC) && (ks->send_reliable->pack= et_id =3D=3D 1);
}


static bool
-read_incoming_tls_plaintext(struct key_state *ks, struct buffer *buf,
- = interval_t *wakeup, bool *continue_tls_process)
+read_incoming_tls_plaintext(struct key_st= ate *ks, struct buffer *buf, interval_t *wakeup,
+ bool *continue_tls= _process)
{
ASSERT(buf_init(buf, 0));=

@@ -2748,7 +2649,8 @@
= * if we have a large wrapped client key. */
if (ma= xlen < 16)
{
- msg(D_TLS_ERRORS, "Warning: --max-packet-size (= %d) setting too low. "
+ msg(D_TLS_ERRORS,
+ "Warning: --max-packet-size (%d) setting too= low. "
"Sending minimum sized packe= t.",
session->opt->frame.tun_mtu);<= /span>
maxlen =3D 16;
@@ -2765,8 +2667,7 = @@

if (status =3D=3D -1)
<= span> {

- ms= g(D_TLS_ERRORS,
- = "TLS Error: Ciphertext -> reliable TCP/UDP transport read err= or");
+ m= sg(D_TLS_ERRORS, "TLS Error: Ciphertext -> reliable TCP/UDP transpo= rt read error");
gc_free(&gc);
= return false;
}
@@ -282= 2,12 +2723,9 @@
}

stati= c bool
-tls_process_sta= te(struct tls_multi *multi,
- struct tls_session *session,
- struct buffer *to_link,
+tls_process_state(str= uct tls_multi *multi, struct tls_session *session, struct buffer *to_link,<= /span>
struct link_socket_actual **to_link_addr= ,
- st= ruct link_socket_info *to_link_socket_info,
- interval_t *wakeup)
+ struct link_socke= t_info *to_link_socket_info, interval_t *wakeup)

{<= br> /* This variable indicates if we should call this method
* again to process more incoming/outgoing TLS state/data<= /span>
@@ -2836,7 +2734,7 @@
* should only b= e done after the outer loop (sending packets etc.)
* = has run once more */
bool continue_tls_process =3D fal= se;
- struct key_sta= te *ks =3D &session->key[KS_PRIMARY]; /* primary key */<= br>+ struct key_state *ks = =3D &session->key[KS_PRIMARY]; /* primary key */

/* Initial handshake */
if (ks->= ;state =3D=3D S_INITIAL)
@@ -2886,8 +2784,7 @@
struct buffer b =3D *buf;

INCR_SENT;<= /span>

- = write_control_auth(session, ks, &b, to_link_addr, opcode,- CONT= ROL_SEND_ACK_MAX, true);
+ write_control_auth(session, ks, &b, to_link_addr, opcode, = CONTROL_SEND_ACK_MAX, true);
*to_link =3D b;
dmsg(D_TLS_DEBUG, "Reliable -> TCP/UDP");<= /span>

@@ -2943,8 +2840,9 @@

/* Send Key */
buf =3D &ks->= ;plaintext_write_buf;
-= if (!buf->len && ((ks->state =3D=3D S_START && !s= ession->opt->server)
- || (ks->state =3D=3D S_GOT_KEY && ses= sion->opt->server)))
+ if (!buf->len
+ && ((ks->state =3D=3D S_START && !sessio= n->opt->server)
+ || (ks->state =3D=3D S_GOT_KEY && session->opt-= >server)))
{
if (!key_meth= od_2_write(buf, multi, session))
{
@@ -2979,8 +2877,7 @@

int status =3D key_state_wr= ite_plaintext(&ks->ks_ssl, buf);
if (status= =3D=3D -1)
{
- msg(D_TLS_ERRORS,
- "TLS ERROR: Outgoing Plaintex= t -> TLS object write error");
+ msg(D_TLS_ERRORS, "TLS ERROR: Outgoing = Plaintext -> TLS object write error");
= goto error;
}
if (status= =3D=3D 1)
@@ -3027,15 +2924,13 @@
}

/* Byte limit */
- if (session->opt->renegotiate_by= tes > 0
- &am= p;& ks->n_bytes >=3D session->opt->renegotiate_bytes)
+ if (session->opt-&= gt;renegotiate_bytes > 0 && ks->n_bytes >=3D session->o= pt->renegotiate_bytes)
{
r= eturn true;
}

/= * Packet limit */
- = if (session->opt->renegotiate_packets
- && ks->n_packets >=3D session-&= gt;opt->renegotiate_packets)
+ if (session->opt->renegotiate_packets && ks-&= gt;n_packets >=3D session->opt->renegotiate_packets)
{

return true;
}
@@ -3102,14 +2997,11 @@
* want to send to our= peer.
*/
static bool
-tls_process(struct tls_multi *multi,
- struct tls_se= ssion *session,
- = struct buffer *to_link,
- struct link_socket_actual **to_link_addr,
- struct link_socket_info= *to_link_socket_info,

+ = struct link_socket_actual **to_link_addr, struct link_socket_info= *to_link_socket_info,
interval_t *wakeup)
{
- st= ruct key_state *ks =3D &session->key[KS_PRIMARY]; /* primary ke= y */
+ struct key_= state *ks =3D &session->key[KS_PRIMARY]; /* primary key */
struct key_state *ks_lame =3D &session->key[KS_LA= ME_DUCK]; /* retiring key */

/* Make= sure we were initialized and that we're not in an error state */
@@ -3118,21 +3010,18 @@
ASSERT(session_id_d= efined(&session->session_id));

= /* Should we trigger a soft reset? -- new key, keeps old key for a while = */
- if (ks->stat= e >=3D S_GENERATED_KEYS
- && should_trigger_renegotiation(session, ks))+ if (ks->state >=3D= S_GENERATED_KEYS && should_trigger_renegotiation(session, ks))
{
- = msg(D_TLS_DEBUG_LOW, "TLS: soft reset sec=3D%d/%d bytes=3D"= counter_format
- = "/%" PRIi64 " pkts=3D" counter_format "/%&qu= ot; PRIi64
- = " aead_limit_send=3D%" PRIu64 "/%" PRIu64
- " aead_limit_recv= =3D%" PRIu64 "/%" PRIu64,

- (int) (now - ks->established), session-&g= t;opt->renegotiate_seconds,
- ks->n_bytes, session->opt->renegotiate_bytes,=
- ks->n_= packets, session->opt->renegotiate_packets,
+ msg(D_TLS_DEBUG_LOW,
+ "TLS: soft reset se= c=3D%d/%d bytes=3D" counter_format "/%" PRIi64 " pkts= =3D" counter_format
+ "/%" PRIi64 " aead_limit_send=3D%" PRI= u64 "/%" PRIu64 " aead_limit_recv=3D%" PRIu64+ "/%" PR= Iu64,
+ (i= nt)(now - ks->established), session->opt->renegotiate_seconds, ks-= >n_bytes,
+ = session->opt->renegotiate_bytes, ks->n_packets, session->o= pt->renegotiate_packets,
ks->crypto_opti= ons.key_ctx_bi.encrypt.plaintext_blocks + ks->n_packets,
session->opt->aead_usage_limit,

= ks->crypto_options.key_ctx_bi.decrypt.plaintext_blocks + ks->n_= packets,
- s= ession->opt->aead_usage_limit
- );
+ session->opt->aead_usage_limit);
key_state_soft_reset(session);

}
<= span>

@@ -3149,19 +3038,15 @@
upd= ate_time();

dmsg(D_TLS_DEBUG, &q= uot;TLS: tls_process: chg=3D%d ks=3D%s lame=3D%s to_link->len=3D%d wakeu= p=3D%d",
- = continue_tls_process,
- state_name(ks->state),
- state_name(ks_lame->state),- to_link->len,
+ continue= _tls_process, state_name(ks->state), state_name(ks_lame->state), to_l= ink->len,
*wakeup);
- continue_tls_process =3D tls_proces= s_state(multi, session, to_link, to_link_addr,
- t= o_link_socket_info, wakeup);
+ continue_tls_process =3D
+ tls_process_state(multi, session, to_link= , to_link_addr, to_link_socket_info, wakeup);

<= span> if (ks->state =3D=3D S_ERROR)

{
return false;
}=
-
}

update_time();
@@ -3192,= 8 +3077,7 @@
{
struct= buffer buf =3D ks->ack_write_buf;
ASSERT(b= uf_init(&buf, multi->opt.frame.buf.headroom));
- write_control_auth(session, ks,= &buf, to_link_addr, P_ACK_V1,
- RELIABLE_ACK_SIZE, false);
+ write_contro= l_auth(session, ks, &buf, to_link_addr, P_ACK_V1, RELIABLE_ACK_SIZE, fa= lse);
*to_link =3D buf;
= dmsg(D_TLS_DEBUG, "Dedicated ACK -> TCP/UDP"); }
@@ -3202,8 +3086,7 @@
= /* When should we wake up again? */
if (ks->stat= e >=3D S_INITIAL || ks->state =3D=3D S_ERROR_PRE)
= {
- compute_ea= rliest_wakeup(wakeup,
-= reliable_send_timeout(ks->send_reliable)= );
+ compute_e= arliest_wakeup(wakeup, reliable_send_timeout(ks->send_reliable));=

if (ks->must_negotiate)
<= span> {

@@ -3213,8 +3096,7 @@

if (ks->established && session->opt->ren= egotiate_seconds)
{
- compute_earliest_wakeup(wakeup,
- ks->= ;established + session->opt->renegotiate_seconds - now);
+ compute_earliest_wakeup(= wakeup, ks->established + session->opt->renegotiate_seconds - now)= ;

}

dmsg(D_TLS_= DEBUG, "TLS: tls_process: timeout set to %d", *wakeup);@@ -3260,7 +3142,7 @@
if (session->tls_wrap.= work.data =3D=3D dataptr)
{
m= sg(M_INFO, "Warning buffer of freed TLS session is "
- "still in use (tl= s_wrap.work.data)");

+ "still in use (tls_wrap.work.data)");
goto used;
}
=
@@ -3278,7 +3160,8 @@
*/<= br> if (!ks->send_reliable)
{
- msg(M_FATAL, = "ERROR: session->key[%d]->send_reliable is NULL "+ msg(M_FATAL,
+ "ER= ROR: session->key[%d]->send_reliable is NULL "
= "while key state is %s. Exiting.",
i, state_name(ks->state));

}=
@@ -3287,7 +3170,8 @@
{ if (ks->send_reliable->array[j].buf.data =3D=3D d= ataptr)
{
- msg(M_INFO, "Warning buffer of freed = TLS session is still in"
+ msg(M_INFO,
+ "Warning buffer of freed TLS ses= sion is still in"
" use (ses= sion->key[%d].send_reliable->array[%d])",
= i, j);

@@ -3310,11 +3194,9= @@
*/

int
<= span style=3D"color: hsl(0, 100%, 40%);">-tls_multi_process(struct tls_mult= i *multi,

- = struct buffer *to_link,
+tls_multi_process(struct tls_multi *multi, struct buffer *to_link= ,
struct link_socket_actual **to_link_ad= dr,
- = struct link_socket_info *to_link_socket_info,
- interval_t *wakeup)
+ struct link_soc= ket_info *to_link_socket_info, interval_t *wakeup)

{
struct gc_arena gc =3D gc_new();
int a= ctive =3D TLSMP_INACTIVE;
@@ -3338,29 +3220,26 @@ /* set initial remote address. This triggers connecting wit= h that
* session. So we only do that if the TM_AC= TIVE session is not
* established */
- if (i =3D=3D TM_INITIAL &a= mp;& ks->state =3D=3D S_INITIAL

- && get_primary_key(multi)->state &l= t;=3D S_INITIAL
+ = if (i =3D=3D TM_INITIAL && ks->state =3D=3D S_INITIAL &&= amp; get_primary_key(multi)->state <=3D S_INITIAL
= && link_socket_actual_defined(&to_link_socket_info-&g= t;lsa->actual))
{
= ks->remote_addr =3D to_link_socket_info->lsa->actual;
}


dmsg(D_TLS_DEBUG,=
- "TL= S: tls_multi_process: i=3D%d state=3D%s, mysid=3D%s, stored-sid=3D%s, store= d-ip=3D%s",
- = i,
- = state_name(ks->state),
- session_id_print(&session->session_id, &gc),<= /span>
+ "T= LS: tls_multi_process: i=3D%d state=3D%s, mysid=3D%s, stored-sid=3D%s, stor= ed-ip=3D%s", i,
= + state_name(ks->state), session_id_print(&session->s= ession_id, &gc),
session_id_print(&ks= ->session_id_remote, &gc),
print_link_= socket_actual(&ks->remote_addr, &gc));
<= br>- if ((ks->state >= ;=3D S_INITIAL || ks->state =3D=3D S_ERROR_PRE) && link_socket_= actual_defined(&ks->remote_addr))
+ if ((ks->state >=3D S_INITIAL || ks->= state =3D=3D S_ERROR_PRE)
+ && link_socket_actual_defined(&ks->remote_= addr))
{
struct link_= socket_actual *tla =3D NULL;

= update_time();

- if (tls_process(multi, session, to_link, &tla,<= /span>
- = to_link_socket_info, wakeup))
+ if (tls_process(multi, session, to_link, &t= la, to_link_socket_info, wakeup))
{
= active =3D TLSMP_ACTIVE;
= }
@@ -3386,14 +3265,12 @@
{<= /span>
++multi->n_soft_errors;

- if = (i =3D=3D TM_ACTIVE
- = || (i =3D=3D TM_INITIAL && get_primary_key(multi)= ->state < S_ACTIVE))
+ if (i =3D=3D TM_ACTIVE || (i =3D=3D TM_INITIAL &= & get_primary_key(multi)->state < S_ACTIVE))
= {
error =3D true;<= br> }

- if (i =3D=3D TM_ACTIVE
- && ks_= lame->state >=3D S_GENERATED_KEYS

+ if (i =3D=3D TM_ACTIVE && ks_la= me->state >=3D S_GENERATED_KEYS
= && !multi->opt.single_session)
= {
move_session(multi, TM_LAME_DUCK, TM= _ACTIVE, true);
@@ -3425,8 +3302,8 @@
= if (ks->state =3D=3D S_ACTIVE && ks->authenticated =3D=3D= KS_AUTH_TRUE)
{
/* S= ession is now fully authenticated.
- * tls_session_generate_data_channel_keys will move= ks->state
- = * from S_ACTIVE to S_GENERATED_KEYS */
+ * tls_session_generate_data_channel_key= s will move ks->state
+ * from S_ACTIVE to S_GENERATED_KEYS */
= if (!tls_session_generate_data_channel_keys(multi, session))
{
msg(D_TLS_ERRO= RS, "TLS Error: generate_key_expansion failed");
= @@ -3471,7 +3348,8 @@
{
move_= session(multi, TM_ACTIVE, TM_INITIAL, true);
tas = =3D tls_authentication_status(multi);
- msg(D_TLS_DEBUG_LOW, "TLS: tls_multi_process: = initial untrusted "
+ msg(D_TLS_DEBUG_LOW,
+ "TLS: tls_multi_process: initial untrusted &= quot;
"session promoted to %strusted"= ;,
tas =3D=3D TLS_AUTHENTICATION_SUCCEEDED ? &= quot;" : "semi-");

@@ -352= 8,8 +3406,8 @@
* try to generate a sensible error message= and print it
*/
static void
<= span style=3D"color: hsl(0, 100%, 40%);">-print_key_id_not_found_reason(str= uct tls_multi *multi,

-= const struct link_socket_actual *from, int ke= y_id)
+print_key_id_n= ot_found_reason(struct tls_multi *multi, const struct link_socket_actual *f= rom,
+ = int key_id)
{
struct g= c_arena gc =3D gc_new();
const char *source =3D print_= link_socket_actual(from, &gc);
@@ -3547,17 +3425,14 @@<= /span>
* session but has not generated keys. */ if (ks->state >=3D S_INITIAL && ks->state= < S_GENERATED_KEYS)
{
- msg(D_MULTI_DROPPED,
- "Key %s [%d] n= ot initialized (yet), dropping packet.",

- source, key_id);
+ msg(D_MULTI_DROPPED, "= ;Key %s [%d] not initialized (yet), dropping packet.", source,<= br>+ key_id);
gc_free(&gc);
r= eturn;
}
if (ks->state= >=3D S_ACTIVE && ks->authenticated !=3D KS_AUTH_TRUE)=
{
- = msg(D_MULTI_DROPPED,
- "Key %s [%d] not authorized%s, dropping pack= et.",
- = source, key_id,
= + msg(D_MULTI_DROPPED, "Key %s [%d] not authorized%s, dropp= ing packet.", source, key_id,
(ks->= ;authenticated =3D=3D KS_AUTH_DEFERRED) ? " (deferred)" : "&= quot;);
gc_free(&gc);
= return;
@@ -3567,8 +3442,7 @@
= msg(D_TLS_ERRORS,
"TLS Error: local/remote T= LS keys are out of sync: %s "
"(received= key id: %d, known key ids: %s)",
- source, key_id,
- print_key_id(multi, &gc));
+ source, key_id, print_key_id(= multi, &gc));
gc_free(&gc);
}=

@@ -3580,11 +3454,8 @@
= * AEAD ciphers to the start of the authenticated data.
*= /
static inline void
-handle_data_channel_packet(struct tls_multi *multi,<= br>- co= nst struct link_socket_actual *from,
- struct buffer *buf,
- struct c= rypto_options **opt,

- = bool floated,
+handle_data_channel_packet(struct tls_multi *multi, con= st struct link_socket_actual *from,
+ struct buffer *buf, struct crypt= o_options **opt, bool floated,
= const uint8_t **ad_start)
{
struct gc= _arena gc =3D gc_new();
@@ -3630,7 +3501,8 @@
{

if (buf->len < 4)<= /span>
{
- msg(D_TLS_ERRORS, "Protocol error: re= ceived P_DATA_V2 from %s but length is < 4",
+ msg(D_TLS_ERRORS,
+ = "Protocol error: received P_DATA_V2 from %s but length is < 4"= ;,
print_link_socket_actual(from, = &gc));
++multi->n_soft_errors;<= /span>
goto done;
@@ -3640,9 = +3512,8 @@

++ks->n_packet= s;
ks->n_bytes +=3D buf->len;
= - dmsg(D_TLS_KEYSELECT= ,
- &qu= ot;TLS: tls_pre_decrypt, key_id=3D%d, IP=3D%s",
- key_id, print_link_socket_= actual(from, &gc));
+ dmsg(D_TLS_KEYSELECT, "TLS: tls_pre_decrypt, key_id=3D= %d, IP=3D%s", key_id,
+ print_link_socket_actual(from, &gc)); gc_free(&gc);
return;<= /span>
}
@@ -3683,14 +3554,9 @@ */

bool
-tls_pre_decrypt(struct tls_multi *multi,
- const st= ruct link_socket_actual *from,
- struct buffer *buf,
- struct crypto_options **opt,<= br>- bool floated,=
- const= uint8_t **ad_start)
= +tls_pre_decrypt(struct tls_multi *multi, const struct link_socket_actual *= from, struct buffer *buf,
+ struct crypto_options **opt, bool floated, const uint= 8_t **ad_start)
{
-
if (buf->len <=3D 0)
{

buf->len =3D 0;
@@ -3= 717,18 +3583,16 @@
/* control channel packet */=
bool do_burst =3D false;
bool new_link = =3D false;
- struct = session_id sid; /* remote session ID */
+ struct session_id sid; /* remote session ID= */

/* verify legal opcode */=
if (op < P_FIRST_OPCODE || op > P_LAST_OPCODE)<= br> {
- = if (op =3D=3D P_CONTROL_HARD_RESET_CLIENT_V1
- || op =3D=3D P_CONTROL_HARD_RESET_SERV= ER_V1)
+ if (o= p =3D=3D P_CONTROL_HARD_RESET_CLIENT_V1 || op =3D=3D P_CONTROL_HARD_RESET_S= ERVER_V1)
{
msg(D_TLS= _ERRORS, "Peer tried unsupported key-method 1");
= }
- msg= (D_TLS_ERRORS,
- = "TLS Error: unknown opcode received from %s op=3D%d",=
+ msg(D_TLS_ERRORS, = "TLS Error: unknown opcode received from %s op=3D%d",
<= span> print_link_socket_actual(from, &gc), op);

<= span> goto error;

}
@@ -3737,8= +3601,8 @@
if (is_hard_reset_method2(op))
<= span> {

/* verify client -> server or serve= r -> client connection */
- if (((op =3D=3D P_CONTROL_HARD_RESET_CLIENT_V2
- || op =3D=3D P_CONTRO= L_HARD_RESET_CLIENT_V3) && !multi->opt.server)

+ if (((op =3D=3D P_CONTROL_HAR= D_RESET_CLIENT_V2 || op =3D=3D P_CONTROL_HARD_RESET_CLIENT_V3)
+ && !multi-&= gt;opt.server)

|| ((op =3D=3D P_CONTROL_HARD_R= ESET_SERVER_V2) && multi->opt.server))
= {
msg(D_TLS_ERRORS,
@@ -3751,8= +3615,8 @@
/*
* Authenticate Pa= cket
*/
- dmsg(D_TLS_DEBUG, "TLS: control channel, op=3D%s, IP=3D%s&= quot;,
- packet= _opcode_name(op), print_link_socket_actual(from, &gc));
+ dmsg(D_TLS_DEBUG, "TLS: co= ntrol channel, op=3D%s, IP=3D%s", packet_opcode_name(op),

+ print_link_socket_actua= l(from, &gc));


/* get remote ses= sion-id */
{
@@ -3760,8 +3624,7 @@
buf_advance(&tmp, 1);
if= (!session_id_read(&sid, &tmp) || !session_id_defined(&sid))
{
- "TLS Error: session-id not found in packet = from %s",
+ = msg(D_TLS_ERRORS, "TLS Error: session-id not found in packet fr= om %s",
print_link_socket_actual(from= , &gc));
goto error;
= }
@@ -3774,29 +3637,25 @@
stru= ct tls_session *session =3D &multi->session[i];
= struct key_state *ks =3D &session->key[KS_PRIMARY];
<= span>

- dmsg(D_= TLS_DEBUG,
- = "TLS: initial packet test, i=3D%d state=3D%s, mysid=3D%s, rec-sid=3D= %s, rec-ip=3D%s, stored-sid=3D%s, stored-ip=3D%s",
- i,
- state_name(ks->state),- session_id_print(= &session->session_id, &gc),
- session_id_print(&sid, &gc),- print_link_socket= _actual(from, &gc),
- session_id_print(&ks->session_id_remote, &gc),
- print_link_= socket_actual(&ks->remote_addr, &gc));
+ dmsg(
+ D_TLS_DEBUG,
+ "TLS: initial packet test, i= =3D%d state=3D%s, mysid=3D%s, rec-sid=3D%s, rec-ip=3D%s, stored-sid=3D%s, s= tored-ip=3D%s",
= + i, state_name(ks->state), session_id_print(&session->= ;session_id, &gc),
+ = session_id_print(&ks->session_id_remote, &gc),<= br>+ print_link_sock= et_actual(&ks->remote_addr, &gc));

<= span> if (session_id_equal(&ks->session_id_remote, &sid)= )

/* found a match */
{
if (i =3D=3D TM_LAME_DUCK)
= {
- = msg(D_TLS_ERRORS,
= - "TLS ERROR: received control packet with stale se= ssion-id=3D%s",
= + msg(D_TLS_ERRORS, "TLS ERROR: received control packet= with stale session-id=3D%s",
ses= sion_id_print(&sid, &gc));
goto er= ror;
}
- dmsg(D_TLS_DEBUG,
- "TLS: found match, session[%d],= sid=3D%s",
- = i, session_id_print(&sid, &gc));
+ dmsg(D_TLS_DEBUG, "TLS: = found match, session[%d], sid=3D%s", i,
+ session_id_print(&sid, &g= c));
break;
}<= br> }
@@ -3827,8 +3686,8 @@
= goto error;
}

= - if (!read_control_auth(b= uf, tls_session_get_tls_wrap(session, key_id), from,
- session->= opt, true))
+ = if (!read_control_auth(buf, tls_session_get_tls_wrap(session, key_id), from= , session->opt,
+ = true))
{
<= span> goto error;

}
@@= -3836,13 +3695,7 @@
#ifdef ENABLE_MANAGEMENT
if (management)

{
- management_set_state(manageme= nt,
- = OPENVPN_STATE_AUTH,
- NULL,
- NULL,
- = NULL,
- = NULL,
- NULL);
+ management_set_state(management, OP= ENVPN_STATE_AUTH, NULL, NULL, NULL, NULL, NULL);
}=
#endif

@@ -3852,10 +370= 5,8 @@
*
* Without --tl= s-auth, we leave authentication entirely up to TLS.
= */
- msg(D_TL= S_DEBUG_LOW,
- = "TLS: Initial packet from %s, sid=3D%s",
- print_link_socket_actual(from, = &gc),
- = session_id_print(&sid, &gc));
+ msg(D_TLS_DEBUG_LOW, "TLS: Initial packet fr= om %s, sid=3D%s",
- msg(D_TLS_ERRO= RS,
- &q= uot;TLS Error: Unroutable control packet received from %s (si=3D%d op=3D%s)= ",
- = print_link_socket_actual(from, &gc),
- i,
- packet_opcode_name(op));
+ msg(D_TLS_ERRORS, "= TLS Error: Unroutable control packet received from %s (si=3D%d op=3D%s)&quo= t;,
+ = print_link_socket_actual(from, &gc), i, packet_opcode_name(op));=
goto error;
}

@@ -3897,17 +3745,16 @@
*/
if (op =3D=3D P_CONTROL_SOFT_RESET_V1 && ks= ->state >=3D S_GENERATED_KEYS)
{
<= span style=3D"color: hsl(0, 100%, 40%);">- if (!read_control_aut= h(buf, tls_session_get_tls_wrap(session, key_id),

- from, sessio= n->opt, false))
+ = if (!read_control_auth(buf, tls_session_get_tls_wrap(session, ke= y_id), from,
+ = session->opt, false))
= {
goto error;
= }

key_state_soft_res= et(session);

- dmsg(D_TLS_DEBUG,
- "TLS: received P_CONTROL_SOFT_RESET_= V1 s=3D%d sid=3D%s",
- i, session_id_print(&sid, &gc));
+ dmsg(D_TLS_DEBUG, &qu= ot;TLS: received P_CONTROL_SOFT_RESET_V1 s=3D%d sid=3D%s", i,
+ session_id_= print(&sid, &gc));
}
= else
{
@@ -3928,8 +3775,8 @@
do_burst =3D true;
= }

- = from, session->opt, initial_packet))
<= span style=3D"color: hsl(120, 100%, 40%);">+ if (!read_control_a= uth(buf, tls_session_get_tls_wrap(session, key_id), from,

+ se= ssion->opt, initial_packet))
{
/* if an initial packet in read_control_auth, we rathe= r

* error out than anything else */
@@ -3940,9 +3787,8 @@
goto erro= r;
}

- dmsg(D_TLS_DEBUG,
- "TLS: receive= d control channel packet s#=3D%d sid=3D%s",

- i, session_id_print(&sid, &= amp;gc));
+ = dmsg(D_TLS_DEBUG, "TLS: received control channel packet s#=3D%d sid= =3D%s", i,
+ = session_id_print(&sid, &gc));
= }
}

@@ -3994,9 +384= 0,8 @@
/* Check key_id */
if (ks-= >key_id !=3D key_id)
{
- msg(D_TLS_ERRORS,
- "TLS ERROR: local/remote key = IDs out of sync (%d/%d) ID: %s",
- ks->key_id, key_id, print_key_id(multi, &= ;gc));
+ msg(D= _TLS_ERRORS, "TLS ERROR: local/remote key IDs out of sync (%d/%d) ID: = %s", ks->key_id,
+ key_id, print_key_id(multi, &gc));
= goto error;
}

= @@ -4010,8 +3855,7 @@

if (!relia= ble_ack_read(&send_ack, buf, &session->session_id))
{

- = msg(D_TLS_ERRORS,
= - "TLS Error: reading acknowledgement record from packe= t");
+ = msg(D_TLS_ERRORS, "TLS Error: reading acknowledgement record from pa= cket");
goto error;
= }
reliable_send_purge(ks->send_reliable, &a= mp;send_ack);
@@ -4034,14 +3878,14 @@
= ASSERT(in);
if (!buf_c= opy(in, buf))
{
- msg(D_MULTI_DROPPED= ,
- = "Incoming control channel packet too big, dropping.");
+ = msg(D_MULTI_DROPPED, "Incoming control channel packet too big, dropp= ing.");
goto error; }
reliable= _mark_active_incoming(ks->rec_reliable, in, id, op);
= }

- /* Process outgoing acknowledgment for packet j= ust received, even if it's a replay */
+ /* Process outgoing acknowledgment f= or packet just received, even if it's a replay
+ */
= reliable_ack_acknowledge_packet_id(ks->rec_ack, id);
= }
}
@@ -4090,8 = +3934,7 @@

/* Choose the key with which = to encrypt a data packet */
void
-tls_pre_encrypt(struct tls_multi *multi,=
- struct buffe= r *buf, struct crypto_options **opt)
+tls_pre_encrypt(struct tls_multi *multi, struct buffer *bu= f, struct crypto_options **opt)
{
mul= ti->save_ks =3D NULL;
if (buf->len <=3D 0)
@@ -4146,8 +3989,7 @@

= ASSERT(ks);

- peer =3D htonl(((P_DATA_V2 << P_OPCODE_SHIFT) | ks->ke= y_id) << 24
- = | (multi->peer_id & 0xFFFFFF));
+ peer =3D htonl(((P_DATA_V2 << P= _OPCODE_SHIFT) | ks->key_id) << 24 | (multi->peer_id & 0xFF= FFFF));
ASSERT(buf_write_prepend(buf, &peer, 4));<= /span>
}

@@ -4172,9 +4014,7 @@<= /span>
*/

bool
-tls_send_payload(struct key_state *k= s,

- co= nst uint8_t *data,
- = int size)
+tls_send_payload(struct key_state *ks, const uint8_t *data, int size)
{
bool ret =3D false;
=
@@ -4206,8 +4046,7 @@
}
=
bool
-tls_rec_payload(struct tls_multi *multi,
- struct buffer *buf)
+tls_rec_payload(struct tls_multi *mult= i, struct buffer *buf)
{
bool ret =3D= false;

@@ -4260,8 +4099,7 @@
<= span> }


void
-show_available_tls_ciphers(const char *cipher_lis= t,
- = const char *cipher_list_tls13,
+show_available_tls_ciphers(const char *cipher_list, cons= t char *cipher_list_tls13,
cons= t char *tls_cert_profile)
{
printf(&q= uot;Available TLS Ciphers, listed in order of preference:\n");<= br>@@ -4278,8 +4116,7 @@
printf("\n"
"Be aware that that whether a cipher suite = in this list can actually work\n"
"de= pends on the specific setup of both peers. See the man page entries of\n&qu= ot;
- "-= -tls-cipher and --show-tls for more details.\n\n"
- );
+ "--tls-cipher and --show-tls for= more details.\n\n");
}

<= span> /*

@@ -4385,7 +4222,8 @@
}
if (flags & PD_VERBOSE)
= {
- buf_pr= intf(&out, " tls_crypt_hmac=3D%s", format_hex(tls_crypt_hmac,= TLS_CRYPT_TAG_SIZE, 0, gc));
+ buf_printf(&out, " tls_crypt_hmac=3D%s"= ,
+ = format_hex(tls_crypt_hmac, TLS_CRYPT_TAG_SIZE, 0, gc));
}

/*
* Remain= der is encrypted and optional wKc
diff --git a/src/openvpn/= ssl.h b/src/openvpn/ssl.h
index b952cd9..976808d 100644
--- a/src/openvpn/ssl.h
+++ b/src/openvpn/ssl.= h
@@ -57,9 +57,10 @@
/*
= * Various timeouts
*/
-#define TLS_MULTI_REFRESH 15 /* call tls_multi_process= once every n seconds */
- = * every packet sent/received action */+#define TLS_MULTI_REFRESH 15= /* call tls_multi_process once every n seconds */
+#define TLS_MULTI_HORIZON = \
+ 2 /* call tls_multi_proc= ess frequently for n seconds after \
+ * every packet sent/received= action */

/*
* Buffer= sizes (also see mtu.h).
@@ -77,49 +78,49 @@
* as reserved for this reason */


/**= Support P_DATA_V2 */
-= #define IV_PROTO_DATA_V2 (1<<1)
+#define IV_PROTO_DATA_V2 (1 << 1)
=
/** Assume client will send a push request and ser= ver does not need
* to wait for a push-request to send a = push-reply */
-#define = IV_PROTO_REQUEST_PUSH (1<<2)
+#define IV_PROTO_REQUEST_PUSH (1 << 2)

/** Supports key derivation via TLS key material expo= rter [RFC5705] */
-#def= ine IV_PROTO_TLS_KEY_EXPORT (1<<3)
+#define IV_PROTO_TLS_KEY_EXPORT (1 << 3)<= br>
/** Supports signaling keywords with AUTH_PENDI= NG, e.g. timeout=3Dxy */
+#define IV_PROTO_AUTH_PENDING_KW (1 << 4= )

/** Support doing NCP in P2P mode. Thi= s mode works by both peers looking at
* each other's = IV_ variables and deterministically deciding both on the same
* result. */

-#def= ine IV_PROTO_NCP_P2P (1<<5)
+#define IV_PROTO_NCP_P2P (1 << 5)

/** Supports the --dns option introduced in version 2= .6. Not sent anymore. */
+#define IV_PROTO_DNS_OPTION (1 << 6)

/** Support for explicit exit notify via co= ntrol channel
* This also includes support for the proto= col-flags pushed option */
-#define IV_PROTO_CC_EXIT_NOTIFY (1<<7)
+#define IV_PROTO_CC_EXIT_NOTIFY (1 << = 7)

/** Support for AUTH_FAIL,TEMP messag= es */
-#define IV_PROTO= _AUTH_FAIL_TEMP (1<<8)
+#define IV_PROTO_AUTH_FAIL_TEMP (1 << 8)
<= /span>
/** Support to dynamic tls-crypt (renegotiation with TLS-E= KM derived tls-crypt key) */
-#define IV_PROTO_DYN_TLS_CRYPT (1<<9)
+#define IV_PROTO_DYN_TLS_CRYPT (1 <<= ; 9)

/** Support the extended packet id = and epoch format for data channel packets */
-#define IV_PROTO_DATA_EPOCH (1<<10)
+#define IV_PROTO_DATA_EPO= CH (1 << 10)

/** Supports the --dn= s option after all the incompatible changes */
-#define IV_PROTO_DNS_OPTION_V2 (1<<11)
+#define IV_PROTO_DNS_OP= TION_V2 (1 << 11)

/** Supports pus= h-update */
-#define IV= _PROTO_PUSH_UPDATE (1<<12)
+#define IV_PROTO_PUSH_UPDATE (1 << 12)

/* Default field in X509 to be username */
= #define X509_USERNAME_FIELD_DEFAULT "CN"
=
-#define KEY_METHOD_2 = 2
+#define KEY_METHO= D_2 2

/* key method taken from lower 4 b= its */
#define KEY_METHOD_MASK 0x0F
@@ -20= 6,9 +207,7 @@
* Used to verify compatibility of local and= remote option
* sets.
*/
-void tls_multi_init_set_options(str= uct tls_multi *multi,

-= const char *local,
- const char *re= mote);
+void tls_mult= i_init_set_options(struct tls_multi *multi, const char *local, const char *= remote);

/**
* Cleanup= a \c tls_multi structure and free associated memory
@@ -22= 8,9 +227,9 @@

/** @} addtogroup control_= processor */

-#define TLSMP_INACTIVE 0
-#define TLSMP_ACTIVE 1
-#define TLSMP_KILL 2
+#define TLSMP_INACTIVE 0
+#define TLSMP_ACTIVE 1
+#define TLSMP_KILL 2
#define TLSMP_RECONNECT 3


/*@@ -239,11 +238,9 @@
* Basically decides if we sho= uld call tls_process for
* the active or untrusted sessio= ns.
*/
- struct buffer *to_link,
+int tls_multi_process= (struct tls_multi *multi, struct buffer *to_link,
= struct link_socket_actual **to_link_addr,
- struct link_socket_= info *to_link_socket_info,
- interval_t *wakeup);
+ struct link_socket_info *= to_link_socket_info, interval_t *wakeup);


/******************************************************= ********************/
@@ -299,11 +296,8 @@
= * @li False if the packet is a data channel packet, or if an error=
* occurred during processing of a control channel packet.
*/
-bo= ol tls_pre_decrypt(struct tls_multi *multi,
- const struct link_socket_actual = *from,
- = struct buffer *buf,
- struct crypto_options **opt,
- bool floated,+bool tls_pre_decrypt(struct = tls_multi *multi, const struct link_socket_actual *from,
+ struct buffer *bu= f, struct crypto_options **opt, bool floated,
= const uint8_t **ad_start);


@@ -325,8 +319,7 @@
* @param buf - The buffe= r containing the outgoing packet.
* @param opt - Returns = a crypto options structure with the security parameters.
= */
-void tls_pre_encryp= t(struct tls_multi *multi,
- struct buffer *buf, struct crypto_options **opt);=
+void tls_pre_encryp= t(struct tls_multi *multi, struct buffer *buf, struct crypto_options **opt)= ;

/**
* Selects the pr= imary encryption that should be used to encrypt data of an
= @@ -351,8 +344,7 @@
*
* @ingroup data_c= rypto
*/
-void
-tls_prepend_= opcode_v1(const struct tls_multi *multi, struct buffer *buf);
+void tls_prepend_opcode_v1(const = struct tls_multi *multi, struct buffer *buf);


<= span> /**

* Prepend an OpenVPN data channel P_DATA_V2 hea= der to the packet. The
@@ -370,8 +362,7 @@
*

* @ingroup data_crypto
*/-void
-tls_prepend_opcode_v2(const struct tls_multi *m= ulti, struct buffer *buf);
+void tls_prepend_opcode_v2(const struct tls_multi *multi, struct buf= fer *buf);

/**
* Perfo= rm some accounting for the key state used.
@@ -435,15 +426,= 12 @@
/*
* Send a payload over the TLS c= ontrol channel
*/
-bool tls_send_payload(struct key_state *ks,
- const uint8_t *da= ta,
- = int size);
+bool = tls_send_payload(struct key_state *ks, const uint8_t *data, int size);

/*
* Receive a payload thr= ough the TLS control channel
*/
-bool tls_rec_payload(struct tls_multi *multi,
- st= ruct buffer *buf);
+b= ool tls_rec_payload(struct tls_multi *multi, struct buffer *buf);
/**
* Updates remote address in= TLS sessions.
@@ -451,8 +439,7 @@
* @par= am multi - Tunnel to update
* @param addr - new address
*/
-vo= id tls_update_remote_addr(struct tls_multi *multi,
- const struct link_= socket_actual *addr);
+void tls_update_remote_addr(struct tls_multi *multi, const struct link_so= cket_actual *addr);

/**
= * Update TLS session crypto parameters (cipher and auth) and derive data<= /span>
@@ -472,12 +459,9 @@
*
= * @return true if updating succeeded or keys are already generated, false o= therwise.
*/
-bool tls_session_update_crypto_params(struct tls_multi *multi,
- = struct tls_session *session,
- struct options *o= ptions,
- = struct frame *frame,
- struct frame *= frame_fragment,
- = struct link_socket_info *lsi,
+bool tls_session_update_crypto_pa= rams(struct tls_multi *multi, struct tls_session *session,

+ = struct options *options, struct frame *frame,
+ struct fr= ame *frame_fragment, struct link_socket_info *lsi,
= dco_context_t *dco);

/*
@@ -536,14 +520,12 @@
* pr= otocol_dump() flags
*/
#define PD_TLS_AU= TH_HMAC_SIZE_MASK 0xFF
= -#define PD_SHOW_DATA (1<<8)
-#define PD_TLS (1<<9)<= /span>
-#define PD_VERBOSE = (1<<10)
-#define PD_TLS_CRYPT (1<<11)
+#define PD_SHOW_DATA (1 <= ;< 8)
+#define PD_= TLS (1 << 9)
+#define PD_VERBOSE (1 << 10)
+#define PD_TLS_CRYPT = (1 << 11)

-const char *protocol_dump(struct buffer *buffer,
- = unsigned int flags,
- = struct gc_arena *gc);
+const char *protocol_dump(struct buffer *buffer, = unsigned int flags, struct gc_arena *gc);

/*

* debugging code
@@ -569,10 +551,8 @= @
* @param cipher_list_tls13 list of allowed TLS 1.3+ cip= her, or NULL
* @param tls_cert_profile TLS certificate c= rypto profile name.
*/
-void
-show_available_tls_ciphers(const char *cipher_list,
- const char *ciph= er_list_tls13,
- = const char *tls_cert_profile);
+void show_available_tls_ciphers(const char *= cipher_list, const char *cipher_list_tls13,
+ const char *tls_cer= t_profile);


/**=
@@ -581,25 +561,19 @@
* This erases the source = material used to generate the data channel keys, and
* ca= n thus be called only once per session.
*/
-bool

-tls_session_generate_data_channel_keys(struct tls_mul= ti *multi,
- = struct tls_session *session);
+bool tls_session_generate_data_channe= l_keys(struct tls_multi *multi, struct tls_session *session);

-void
-tls_session_soft_reset(struct tls_= multi *multi);

+void = tls_session_soft_reset(struct tls_multi *multi);
/**
* Load ovpn.xkey provider used for external = key signing
*/
-void
-load_x= key_provider(void);
+= void load_xkey_provider(void);

/* Specia= l method to skip the three way handshake RESET stages. This is
* used by the HMAC code when seeing a packet that matches the previou= s

* HMAC based stateless server state */
-bool
-session_skip_to_pre_start(struct tls_session *session,<= /span>
- = struct tls_pre_decrypt_state *state,
- struct link_socket_actual *fro= m);
+bool session_ski= p_to_pre_start(struct tls_session *session, struct tls_pre_decrypt_state *s= tate,
+ = struct link_socket_actual *from);
=
#endif /* ifndef OPENVPN_SSL_H */
diff --git a/s= rc/openvpn/ssl_backend.h b/src/openvpn/ssl_backend.h
index = 8023fed..da3e1e1 100644
--- a/src/openvpn/ssl_backend.h
+++ b/src/openvpn/ssl_backend.h
@@ -101,11 +10= 1,11 @@
* if a parse error should be= flagged.
*/
#define TLS_VER_BAD -1
-#define TLS_VER_UNSPEC = 0 /* default */
-#defi= ne TLS_VER_1_0 1
-#= define TLS_VER_1_1 2
-#define TLS_VER_1_3 4
+#define TLS_VER_UNSPEC 0 /* default */
+#define TLS_VER_1_0 1
+#define TLS_VER_1_1 2
<= span style=3D"color: hsl(120, 100%, 40%);">+#define TLS_VER_1_2 3
=
+#define TLS_VER_1_3 4
int tls_version_parse(const char *vstr, const char *extra);=

/**
@@ -218,8 +218,7 @@=
* of inline files. * @param dh_file_inline True if dh_file is an inline file.=
*/
-= void tls_ctx_load_dh_params(struct tls_root_ctx *ctx, const char *dh_file,<= /span>
- = bool dh_file_inline);
+void tls_ctx_load_dh_params(struct tls_root_ctx *ctx, const char *d= h_file, bool dh_file_inline);

/**=
* Load Elliptic Curve Parameters, and load them into the librar= y-specific
@@ -228,8 +227,7 @@
* @param c= tx TLS context to use
* @param curve_name The = name of the elliptic curve to load.
*/
-void tls_ctx_load_ecdh_params(struct tls= _root_ctx *ctx, const char *curve_name
- );
+void tls_ctx_load_ecdh_params(struct tls_root= _ctx *ctx, const char *curve_name);

/**<= /span>
* Load PKCS #12 file for key, cert and (optionally) CA ce= rts, and add to
@@ -246,8 +244,8 @@
* @re= turn 1 if an error occurred, 0 if parsing was * successful.
*/
-int tls_ctx_load_pkcs12= (struct tls_root_ctx *ctx, const char *pkcs12_file,
- bool pkcs12_file_in= line, bool load_ca_file);
+int tls_ctx_load_pkcs12(struct tls_root_ctx *ctx, const char *pkcs12_= file, bool pkcs12_file_inline,
+ bool load_ca_file);

/**
* Use Windows cryptoapi for key and ce= rt, and add to library-specific TLS
@@ -271,8 +269,7 @@
* of inline files.
* @param cert_file_inline True if cert_file is an inline file.
*/
-vo= id tls_ctx_load_cert_file(struct tls_root_ctx *ctx, const char *cert_file,<= /span>
- = bool cert_file_inline);
+void tls_ctx_load_cert_file(struct tls_root_ctx *ctx, const char = *cert_file, bool cert_file_inline);

/**<= /span>
* Load private key file into the given TLS context.
@@ -318,8 +315,8 @@
* = connection and should use the CA for verifying
* = client certificates
*/-void tls_ctx_load_ca(struct tl= s_root_ctx *ctx, const char *ca_file,
- bool ca_file_inline, const char *ca_pa= th, bool tls_server);
+void tls_ctx_load_ca(struct tls_root_ctx *ctx, const char *ca_file, bool = ca_file_inline,
+ = const char *ca_path, bool tls_server);

/**
* Load extra certificate authority ce= rtificates from the given file or path.
@@ -334,8 +331,7 @@=
* @param extra_certs_file_inline True if extra_cer= ts_file is an inline
* = file.
*/
-void tls_ctx_load_extra_certs(struct tls_root_ctx *ctx,
<= span style=3D"color: hsl(0, 100%, 40%);">- con= st char *extra_certs_file,

+void tls_ctx_load_extra_certs(struct tls_root_ctx *ctx, const char *= extra_certs_file,
bool extra= _certs_file_inline);

#ifdef ENABLE_CRYPT= O_MBEDTLS
@@ -364,15 +360,14 @@
* @param = is_server Initialise a server?
* @param session = The session associated with the given key_state
*/
-void key_state_ssl_init(str= uct key_state_ssl *ks_ssl,
- const struct tls_root_ctx *ssl_ctx, bool is_se= rver, struct tls_session *session);
+void key_state_ssl_init(struct key_state_ssl *ks_ssl, const= struct tls_root_ctx *ssl_ctx,
+ bool is_server, struct tls_session *sess= ion);

/**
* Sets a TLS= session to be shutdown state, so the TLS library will generate
<= span> * a shutdown alert.

*/
-void
-key_state_ssl_shutdown(struct key_state_ssl *ks_ssl);
+void key_state_ssl_shutdown(stru= ct key_state_ssl *ks_ssl);


/** * Free the SSL channel part of the given key state.
@@ -389,12 +384,12 @@

* an array c= ontaining the inline CRL.
* @param crl_inline True if = crl_file is an inline CRL.
*/
-void backend_tls_ctx_reload_crl(struct tls_root_c= tx *ssl_ctx,
- = const char *crl_file, bool crl_inline);
+void backend_tls_ctx_reload_crl(= struct tls_root_ctx *ssl_ctx, const char *crl_file,

+ bool crl_= inline);

-#define EXPORT_KEY_DATA_LABEL "EXPORTER-OpenVPN-datakeys&qu= ot;
-#define EXPORT_P2P= _PEERID_LABEL "EXPORTER-OpenVPN-p2p-peerid"
-#define EXPORT_DYNAMIC_TLS_CRYPT_LABEL = "EXPORTER-OpenVPN-dynamic-tls-crypt"
+#define EXPORT_KEY_DATA_LABEL "EX= PORTER-OpenVPN-datakeys"
+#define EXPORT_P2P_PEERID_LABEL "EXPORTER-OpenVPN-p2p= -peerid"
+#defin= e EXPORT_DYNAMIC_TLS_CRYPT_LABEL "EXPORTER-OpenVPN-dynamic-tls-crypt&q= uot;
/**
* Keying Material Exporters [RF= C 5705] allows additional keying material to be
* derived= from existing TLS channel. This exported keying material can then be
@@ -407,10 +402,8 @@
* @param ekm_size The= size of ekm, in bytes
* @returns true if expo= rting succeeded, false otherwise
*/
-bool
-key_state_export_keying_material(struct tls_session *session= ,
- = const char *label, size_t label_size,
- void *ekm, si= ze_t ekm_size);
+bool= key_state_export_keying_material(struct tls_session *session, const char *= label,
+ = size_t label_size, void *ekm, size_t ekm_size);


/*****************************************= *********************************/
/** @addtogroup control= _tls
@@ -453,8 +446,7 @@
* again later = to retry.
* - \c -1: An error occurred.
= */
-int key_state_writ= e_plaintext_const(struct key_state_ssl *ks_ssl,
- const uint8_t= *data, int len);
+in= t key_state_write_plaintext_const(struct key_state_ssl *ks_ssl, const uint8= _t *data, int len);

/**
= * Extract ciphertext data from the TLS module.
@@ -499,8 = +491,7 @@
* again later to retry.
* -= \c -1: An error occurred.
*/
-int key_state_write_ciphertext(struct key_state_s= sl *ks_ssl,
- = struct buffer *buf);
+int key_state_write_ciphertext(struct key_state_ssl *= ks_ssl, struct buffer *buf);

/**<= br> * Extract plaintext data from the TLS module.
@@= -548,10 +539,8 @@
* @param tls13 Select if &= lt;=3DTLS1.2 or TLS1.3+ ciphers
* = should be shown
*/
-void
-= show_available_tls_ciphers_list(const char *cipher_list,
- const ch= ar *tls_cert_profile,
-= bool tls13);
+void show_available_tls_ciphers_list(const char *c= ipher_list, const char *tls_cert_profile,
+ bool tls13);

/**
* Show the available = elliptic curves in the crypto library
diff --git a/src/open= vpn/ssl_common.h b/src/openvpn/ssl_common.h
index 1fdc187..= cd5293a 100644
--- a/src/openvpn/ssl_common.h
+++ b/src/openvpn/ssl_common.h

@@ -117,15 +117,16 @@
* \ref key_generation "data channel key generation"= ;.
* @ingroup control_processor
*/
-struct key_source {=
- uint8_t pre_master[48]; = /**< Random used for master secret
- * generation, provid= ed only by client
- = * OpenVPN peer. */
- uint8_t random1[32]; /**< Seed us= ed for master secret
- = * generation, provided by both client
- = * and server. */
- uint8_t random2[32]; /**< Seed used for key expansion, p= rovided
- = * by both client and server. */
+struct key_source
+{
+ uint8_t pre_master[48]; /**< Random used for master = secret
+ = * generation, provided only by client
+ * OpenVP= N peer. */
+ uint8= _t random1[32]; /**< Seed used for master secret
+ * generat= ion, provided by both client
+ * and server. */
+ uint8_t random2[32]; /**< Se= ed used for key expansion, provided
+ * by both client and server.= */
};


@@ -134,9 +135,10 @@

* 2 \ref key_generation "data = channel key generation".
* @ingroup control_processo= r
*/
= -struct key_source2 {
-= struct key_source client; /**< Random provided by client. */
- struct key_source serve= r; /**< Random provided by server. */
+struct key_source2
+{
+ struct key_source client; /**< Random provided by client. */
+ struct key_source s= erver; /**< Random provided by server. */
};
=

@@ -147,15 +149,16 @@
<= span> * being set to KS_AUTH_TRUE or KS_AUTH_FALSE

* Onl= y KS_AUTH_TRUE is fully authenticated
*/
-enum ks_auth_state {
- KS_AUTH_FALSE, /**< K= ey state is not authenticated */
- KS_AUTH_DEFERRED, /**< Key state authentication = is being deferred,
- = * by async auth */
- KS_AUTH_TRUE /**< Key state is= authenticated. TLS and user/pass
- * succeeded. This includes AUTH_= PENDING/OOB
- = * authentication as those hold the
- * connecti= on artificially in KS_AUTH_DEFERRED
- */
+enum ks_auth_state
+{
+ KS_AUTH_FALSE, /**< Key state is not authenticated */
+ KS_AUTH_DEFERRED,= /**< Key state authentication is being deferred,
+ * by async auth */=
+ KS_AUTH_TRUE = /**< Key state is authenticated. TLS and user/pass
+ * succeeded. Th= is includes AUTH_PENDING/OOB
+ * authentication as those hold the+ * con= nection artificially in KS_AUTH_DEFERRED
+ */
};
struct auth_deferred_status
@@ -= 168,14 +171,16 @@

/* key_state_test_auth= _control_file return values, these specify the
* current = status of a deferred authentication */
-enum auth_deferred_result {
- ACF_PENDING, /**< deferred auth still pe= nding */
- ACF_SUCCE= EDED, /**< deferred auth has suceeded */
- ACF_DISABLED, /**< deferred auth is not= used */
- ACF_FAILE= D /**< deferred auth has failed */
+enum auth_deferred_result
+{
+ ACF_PENDING, /**< deferred auth still pending */
+ ACF_SUCCEEDED, /**&l= t; deferred auth has suceeded */
+ ACF_DISABLED, /**< deferred auth is not used */=
+ ACF_FAILED /**<= deferred auth has failed */
};
-enum dco_key_status {+enum dco_key_status+{
DCO_N= OT_INSTALLED,
DCO_INSTALLED_PRIMARY,
= DCO_INSTALLED_SECONDARY
@@ -219,34 +224,34 @@
struct key_state_ssl ks_ssl; /* contains SSL = object and BIOs for the control channel */

- time_t initial; /* w= hen we created this session */

- time_t established; /* when our state went S_ACTIVE */=
- time_t must_negot= iate; /* key negotiation times out if not finished before this time */=
- time_t must_die; = /* this object is destroyed at this time */
- time_t peer_last_packet; /* Last ti= me we received a packet in this control session */
+ time_t initial; /* when we = created this session */
+ time_t established; /* when our state went S_ACTIVE */
+ time_t must_negotia= te; /* key negotiation times out if not finished before this time */<= /span>
+ time_t must_die;= /* this object is destroyed at this time */
+ time_t peer_last_packet; /* La= st time we received a packet in this control session */

- int initial_opcode;= /* our initial P_ opcode */
- struct session_id session_id_remote; /* peer's rando= m session ID */
+ = int initial_opcode; /* our initial P_ opcode */
+ struct session_id session_id_remot= e; /* peer's random session ID */
struct link_so= cket_actual remote_addr; /* peer's IP addr */
<= br>- struct crypto_options cry= pto_options;/* data channel crypto options */
+ struct crypto_options crypto_options; /* dat= a channel crypto options */

- struct key_source2 *key_src; /* source en= tropy for key expansion */
+ struct key_source2 *key_src; /* source entropy for key= expansion */

struct buffer plaintex= t_read_buf;
struct buffer plaintext_write_buf;<= br> struct buffer ack_write_buf;

struct reliable *send_reliable; /* holds a copy of outgoing packets = until ACK received */

-= struct reliable *rec_reliable; /* order incoming ciphertext packets bef= ore we pass to TLS */
-= struct reliable_ack *rec_ack; /* buffers all packet IDs we want to ACK = back to sender */
- = struct reliable_ack *lru_acks; /* keeps the most recently acked packages*/<= /span>
+ struct reliable = *rec_reliable; /* order incoming ciphertext packets before we pass to TLS = */
+ struct reliab= le_ack *rec_ack; /* buffers all packet IDs we want to ACK back to sender = */
+ struct reliab= le_ack *lru_acks; /* keeps the most recently acked packages*/

/** Holds outgoing message for the control chann= el until ks->state reaches
* S_ACTIVE */ struct buffer_list *paybuf;
- counter_type n_bytes; /* how many byte= s sent/recvd since last key exchange */
- counter_type n_packets; /* how many pack= ets sent/recvd since last key exchange */
+ counter_type n_bytes; /* how many bytes sent/re= cvd since last key exchange */
+ counter_type n_packets; /* how many packets sent/recvd since= last key exchange */

/*
<= span> * If bad username/password, TLS connection will come up but '= ;authenticated' will be false.

@@ -269,19 +274,20 @@
/** Control channel wrapping (--tls-auth/--tls-crypt) contex= t */
struct tls_wrap_ctx
{
- enum {

- TLS_WRAP_NONE =3D 0, /**< No control= channel wrapping */
- = TLS_WRAP_AUTH, /**< Control channel authentication */
= - TLS_WRAP_CRYPT, /**< = Control channel encryption and authentication */
- } mode; /**< Control = channel wrapping mode */
- struct buffer work; /**<= ; Work buffer (only for --tls-crypt) */
- struct key_ctx tls_crypt_v2_server_key; /**< Decr= ypts client keys */
- = const struct buffer *tls_crypt_v2_wkc; /**< Wrapped client key,
- = * sent to server */
- struct buffer tls_crypt_v2_metadata; /**< Re= ceived from client */
-= bool cleanup_key_ctx; /**< opt.key_ctx_bi is owne= d by
- = * this context */
+ enum
+ {
+ TLS_WRAP_NONE =3D 0, /**< No control channe= l wrapping */
+ = TLS_WRAP_AUTH, /**< Control channel authenticatio= n */
+ TLS_WRA= P_CRYPT, /**< Control channel encryption and authent= ication */
+ } mod= e; /**< Control channel wrapping mode */=
+ struct crypto_o= ptions opt; /**< Crypto state */
+ struct buffer work; /*= *< Work buffer (only for --tls-crypt) */
+ struct key_ctx tls_crypt_v2_server_key; /**<= Decrypts client keys */
+ const struct buffer *tls_crypt_v2_wkc; /**< Wrapped client key= ,
+ = * sent to server */
+ struct buffer tls_crypt_v2_metadata; /*= *< Received from client */
+ bool cleanup_key_ctx; /**< opt.key_ctx_b= i is owned by
+ = * this context */
= /** original key data to be xored in to the key for dynamic tls-crypt.=
*
* We keep the original key d= ata to ensure that the newly generated key
@@ -363,8 +369,8= @@
/* struct crypto_option flags */
= unsigned int crypto_flags;

- int replay_window; /* --repl= ay-window parm */
- = int replay_time; /* --replay-window parm */
+ int replay_window; /* --repla= y-window parm */

+ = int replay_time; /* --replay-window parm */

= const char *config_ciphername;
const char *= config_ncp_ciphers;
@@ -392,9 +398,9 @@
= const char *auth_user_pass_file;
bool auth_user_pass= _file_inline;

- bool auth_token_generate; /**< Generate auth-tokens on s= uccessful
- = * user/pass auth,seet via
- * options->aut= h_token_generate. */
= + bool auth_token_generate; /**< Generate auth-tokens on successful<= /span>
+ = * user/pass auth,seet via
+ * options->auth_token_= generate. */
bool auth_token_call_auth; /**< always= call normal authentication */
unsigned int auth_token= _lifetime;
unsigned int auth_token_renewal;
= @@ -415,17 +421,17 @@
#endif

/* configuration file SSL-related boolean and low-permutati= on options */
-#define = SSLF_CLIENT_CERT_NOT_REQUIRED (1<<0)
-#define SSLF_CLIENT_CERT_OPTIONAL (1<<1)
-#define SSLF_USERNAME_AS_= COMMON_NAME (1<<2)
-#define SSLF_AUTH_USER_PASS_OPTIONAL (1<<3)
-#define SSLF_OPT_VERIFY (1&l= t;<4)
-#define SSLF_= CRL_VERIFY_DIR (1<<5)
+#define SSLF_CLIENT_CERT_NOT_REQUIRED (1 << 0)
+#define SSLF_CLIENT_CERT= _OPTIONAL (1 << 1)
+#define SSLF_USERNAME_AS_COMMON_NAME (1 << 2)
+#define SSLF_AUTH_USER_PASS_OPTIO= NAL (1 << 3)

+= #define SSLF_OPT_VERIFY (1 << 4)
+#define SSLF_CRL_VERIFY_DIR (1 = << 5)
#define SSLF_TLS_VERSION_MIN_SHIFT 6=
-#define SSLF_TLS_VERSION_MIN= _MASK 0xF /* (uses bit positions 6 to 9) */
+#define SSLF_TLS_VERSION_MIN_MASK 0xF /* (= uses bit positions 6 to 9) */
#define SSLF_TLS_VERSION_MAX= _SHIFT 10
-#define S= SLF_TLS_VERSION_MAX_MASK 0xF /* (uses bit positions 10 to 13) */
-#define SSLF_TLS_DEBUG_ENAB= LED (1<<14)
+#define SSLF_TLS_VERSION_MAX_MASK 0xF /* (uses bit positions 10 to= 13) */
+#define SSLF= _TLS_DEBUG_ENABLED (1 << 14)
unsigned int= ssl_flags;

#ifdef ENABLE_MANAGEMENT
@@ -456,10 +462,11 @@
* This is the index o= f \c tls_session.key
*
* @{ */<= br>-#define KS_PRIMARY 0 = /**< Primary %key state index. */
-#define KS_LAME_DUCK 1 /**< %Key state index = that will retire
- = * soon. */
-#define KS_SIZE 2 /**< Size of the \c t= ls_session.key array. */
+#define KS_PRIMARY 0 /**< Primary %key state index. */
+#define KS_LAME_DUCK = \

+ 1 /**< %Key state index that will retire \<= /span>
+ = * soon. */
+#defi= ne KS_SIZE 2 /**< Size of the \c tls_session.key array. */
= /** @} name Index of key_state objects within a tls_session structur= e */
/** @} addtogroup control_processor */

@@ -494,7 +501,7 @@
* tls_wrap_re= neg.mode is TLS_WRAP_CRYPT, otherwise ignore it */
str= uct tls_wrap_ctx tls_wrap_reneg;

- int initial_opcode; /* our initial= P_ opcode */
+ in= t initial_opcode; /* our initial P_ opcode */
= struct session_id session_id; /* our random session ID */

/**
@@ -510,7 +517,7 @@
<= span>

struct cert_hash_set *cert_hash_set;
=
- bool verif= ied; /* true if peer certificate was verified against CA */
+ bool verified; /* = true if peer certificate was verified against CA */

/* not-yet-authenticated incoming client */
struct link_socket_actual untrusted_addr;

@@ -535,12 = +542,14 @@
* is being negotiated.
*
* @{ */
-#define TM_INITIAL 1 = /**< As yet un-trusted \c tls_session
- * being negotiate= d. */
-#define TM_LAME_= DUCK 2 /**< Old \c tls_session. */
-#define TM_SIZE 3 /**< Size of th= e \c tls_multi.session
= - * array. */
+#define TM_ACTIVE 0 /**< Active \c tls_se= ssion. */
+#define TM= _INITIAL \
+ 1 /**< As yet un-= trusted \c tls_session \
+ * being negotiated. */
+#define TM_LAME_DUCK 2 /**< Old \c tls= _session. */
+#define= TM_SIZE \
+ 3 /**< Size of = the \c tls_multi.session \
+ * array. */
/** @} name I= ndex of tls_session objects within a tls_multi structure */
/** @} addtogroup control_processor */


= @@ -612,7 +621,7 @@
* used by tls_pre_encrypt to comm= unicate the encrypt key
* to tls_post_encrypt()
*/
- = struct key_state *save_ks; /* temporary pointer used between pre/post ro= utines */
+ struct= key_state *save_ks; /* temporary pointer used between pre/post routines */=

/*
* Used to = return outgoing address from
@@ -620,8 +629,8 @@
= */
struct link_socket_actual to_link_addr;=

- = int n_sessions; /**< Number of sessions negotiated thus
- = * far. */
+= int n_sessions; /**< Number of sessions negotiated thus
+ * far. */=

enum multi_status multi_state;

/*
@@ -692,8 +701,8 @@
= uint32_t peer_id;
bool use_peer_id;
=
- char *remote_cip= hername; /**< cipher specified in peer's config file */- bool remote_usescomp; = /**< remote announced comp-lzo in OCC string */
+ char *remote_ciphername; /**< ciph= er specified in peer's config file */
+ bool remote_usescomp; /**< remote announced= comp-lzo in OCC string */

/*=
* Our session objects.
diff --git a/src/ope= nvpn/ssl_mbedtls.c b/src/openvpn/ssl_mbedtls.c
index 22e777= b..635b53c 100644
--- a/src/openvpn/ssl_mbedtls.c+++ b/src/openvpn/ssl_mbedtls.c
@@ -52,35 +52,28 @@<= /span>
#include <mbedtls/version.h>

#if MBEDTLS_VERSION_NUMBER >=3D 0x02040000
- #include <mbedtls/net_sockets.h&= gt;
+#include <mbe= dtls/net_sockets.h>
#else
- #include <mbedtls/net.h>
+#include <mbedtls/net.h>
#endif

#include <mbedtls/= oid.h>
#include <mbedtls/pem.h>
=
-static const mbedtls_= x509_crt_profile openvpn_x509_crt_profile_legacy =3D
-{
+static const mbedtls_x509_crt_profile openvpn_x509_crt_profil= e_legacy =3D {
/* Hashes from SHA-1 and above */
- MBEDTLS_X509_ID_FLAG( M= BEDTLS_MD_SHA1 )
- |= MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_RIPEMD160 )
- |MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA224 )
- |MBEDTLS_X509_ID_FLAG( = MBEDTLS_MD_SHA256 )
- = |MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA384 )
- |MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA512 ),
+ MBEDTLS_X509_ID_FLAG= (MBEDTLS_MD_SHA1) | MBEDTLS_X509_ID_FLAG(MBEDTLS_MD_RIPEMD160)
+ | MBEDTLS_X509_ID_FLAG(M= BEDTLS_MD_SHA224) | MBEDTLS_X509_ID_FLAG(MBEDTLS_MD_SHA256)

+ | MBEDTLS_X509_ID_FLAG(MBED= TLS_MD_SHA384) | MBEDTLS_X509_ID_FLAG(MBEDTLS_MD_SHA512),

= 0xFFFFFFF, /* Any PK alg */
0xFFFFFFF, /* Any c= urve */
1024, /* RSA-1024 and larger */
};

-static const mbedtls_x509_crt_profile openvpn_x509_crt_profile_p= referred =3D
-{<= br>+static const mbedtls_x509_c= rt_profile openvpn_x509_crt_profile_preferred =3D {
/*= SHA-2 and above */
- = MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA224 )
- |MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA256 )=
- |MBEDTLS_X509_ID_FLAG( M= BEDTLS_MD_SHA384 )
- = |MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA512 ),
+ MBEDTLS_X509_ID_FLAG(MBEDTLS_MD_SHA224) | MBED= TLS_X509_ID_FLAG(MBEDTLS_MD_SHA256)
+ | MBEDTLS_X509_ID_FLAG(MBEDTLS_MD_SHA384) | MBEDTLS= _X509_ID_FLAG(MBEDTLS_MD_SHA512),
0xFFFFFFF, /* Any PK= alg */
0xFFFFFFF, /* Any curve */
2048, /* RSA-2048 and larger */

@@ -184,9 +17= 7,8 @@
* Mbed TLS stores this callback in the mbedtls_ssl= _config struct and it
* is used in the mbedtls_ssl_contex= ts set up from that config. */
int
-mbedtls_ssl_export_keys_cb(void *p_expkey, = const unsigned char *ms,
- = size_t keylen, size_t ivlen,
+mbedtls_ssl_export_keys_cb(void *p_expkey, const unsigned char *ms= , const unsigned char *kb,
+ size_t maclen, size_t keylen, size_t ivle= n,
const unsigned char client_r= andom[32],
const unsigned char = server_random[32],
mbedtls_tls_= prf_types tls_prf_type)
@@ -195,8 +187,8 @@
struct key_state_ssl *ks_ssl =3D &session->key[KS_PRIMARY].ks_= ssl;

struct tls_key_cache *cache =3D &ks_ssl->t= ls_key_cache;

- static_assert(sizeof(ks_ssl->ctx->session->master)
- =3D= =3D sizeof(cache->master_secret), "master size mismatch");
+ static_assert(sizeo= f(ks_ssl->ctx->session->master) =3D=3D sizeof(cache->master_sec= ret),
+ = "master size mismatch");

= memcpy(cache->client_server_random, client_random, 32);
memcpy(cache->client_server_random + 32, server_random, 32);
@@ -218,10 +210,8 @@
* mbedtls_ssl_config. I= t is placed in the mbedtls_ssl_context after it
* has bee= n set up. */
void
-mbedtls_ssl_export_keys_cb(void *p_expkey,
- mbedtls_ssl_ke= y_export_type type,
- = const unsigned char *secret,
- size_t secret_le= n,
+mbedtls_ssl_expor= t_keys_cb(void *p_expkey, mbedtls_ssl_key_export_type type,
+ const un= signed char *secret, size_t secret_len,

= const unsigned char client_random[32],
= const unsigned char server_random[32],
= mbedtls_tls_prf_types tls_prf_type)
@@ -241,8 +231,7 @@

* a different value, something = is wrong with mbed TLS. */
if (secret_len !=3D sizeof(= cache->master_secret))
{
- msg(M_FATAL,
- "ERROR: Incorrect TLS 1.2 master= secret length: Got %zu, expected %zu",
+ msg(M_FATAL, "ERROR: Incorrect TLS 1.= 2 master secret length: Got %zu, expected %zu",
= secret_len, sizeof(cache->master_secret));
}=

@@ -257,8 +246,7 @@


bool
-key_state_export_keying_material(struct tls_session *sessio= n,
- = const char *label, size_t label_size,
+key_state_export_keying_material(struct t= ls_session *session, const char *label, size_t label_size,
= void *ekm, size_t ekm_size)
{

ASSERT(strlen(label) =3D=3D label_size);<= br>@@ -267,7 +255,8 @@
/* Our version of mbed TL= S has a built-in TLS-Exporter. */

mb= edtls_ssl_context *ctx =3D session->key[KS_PRIMARY].ks_ssl.ctx;- if (mbed_ok(mbedtls_ssl_ex= port_keying_material(ctx, ekm, ekm_size, label, label_size, NULL, 0, 0)))
+ if (mbed_ok(
+ mbedtls_ssl_= export_keying_material(ctx, ekm, ekm_size, label, label_size, NULL, 0, 0)))=
{
return true;
}

@@ -287,10 +276,8 @@
}

int ret =3D mbedtls_ssl_tls_prf(cache->= ;tls_prf_type, cache->master_secret,
- sizeof(cache->master= _secret),
- = label, cache->client_server_random,
- si= zeof(cache->client_server_random),

- ekm, ekm_size);+ = sizeof(cache->master_secret), label, cache->client_server_random= ,
+ = sizeof(cache->client_server_random), ekm, ekm_size);

if (mbed_ok(ret))
= {
@@ -301,7 +288,7 @@
secure_memze= ro(ekm, session->opt->ekm_size);
return fals= e;
}
-#endif /* defined(MBEDTLS_SSL_KEYING_MATERIAL_EXPORT) */
+#endif /* defined(MBEDTLS_SSL_KEY= ING_MATERIAL_EXPORT) */

}

bool

@@ -324,7 +311,8 @@
if (0 !=3D= strcmp(cipher_name, pair->iana_name))
{
= /* Deprecated name found, notify user */
- msg(M_WARN, "Deprecated ciph= er suite name '%s', please use IANA name '%s'", pair-&= gt;openssl_name, pair->iana_name);
+ msg(M_WARN, "Deprecated cipher suite name &#= 39;%s', please use IANA name '%s'",
+ pair->openssl_name, pair-&= gt;iana_name);
}

= return pair->iana_name;
@@ -339,8 +327,10 @@ return;
}

= - msg(M_WARN, "mbed TLS d= oes not support setting tls-ciphersuites. "
- "Ignoring TLS 1.3 cipher list: %s&q= uot;, ciphers);
+ = msg(M_WARN,
+ = "mbed TLS does not support setting tls-ciphersuites. "
= + "Ignoring TLS 1.3= cipher list: %s",
+ ciphers);
}

= void
@@ -359,7 +349,7 @@
int cipher_c= ount =3D get_num_elements(ciphers, ':');
/* Allocate an array for them */
- ALLOC_ARRAY_CLEAR(ctx->allowed_ciphers, int,= cipher_count+1)
+ = ALLOC_ARRAY_CLEAR(ctx->allowed_ciphers, int, cipher_count + 1)
/* Parse allowed ciphers, getting IDs */
int i =3D 0;
@@ -368,8 +358,7 @@ token =3D strtok(tmp_ciphers, ":");
= while (token)
{
- ctx->allowed_ciphers[i] =3D mbedtls_ssl_get_= ciphersuite_id(
- = tls_translate_cipher_name(token));
+ ctx->allowed_ciphers[i] =3D mbedtls_ssl_get= _ciphersuite_id(tls_translate_cipher_name(token));
= if (0 !=3D ctx->allowed_ciphers[i])
{ i++;
@@ -382,8 +371,7 @@
void

tls_ctx_set_cert_profile(struct tls_root_ctx *ctx= , const char *profile)
{
- if (!profile || 0 =3D=3D strcmp(profile, "lega= cy")
- || 0= =3D=3D strcmp(profile, "insecure"))
+ if (!profile || 0 =3D=3D strcmp(profile, &qu= ot;legacy") || 0 =3D=3D strcmp(profile, "insecure"))<= br> {
ctx->cert_profile =3D openvpn_x= 509_crt_profile_legacy;
}
@@ -418,8 +4= 06,7 @@
const char *token;
while = ((token =3D strsep(&tmp_groups, ":")))
{=
- const mbedtls= _ecp_curve_info *ci =3D
- mbedtls_ecp_curve_info_from_name(token);
+ const mbedtls_ecp_curve_info *ci= =3D mbedtls_ecp_curve_info_from_name(token);
if (= !ci)
{
msg(M_WARN, &q= uot;Warning unknown curve/group specified: %s", token);
@@ -461,13 +448,11 @@

}

void

-tls_ctx_load_d= h_params(struct tls_root_ctx *ctx, const char *dh_file,
- bool dh_inline)
+tls_ctx_load_dh_params= (struct tls_root_ctx *ctx, const char *dh_file, bool dh_inline)
<= span> {

if (dh_inline)
{- if (!mbed_ok(mbedtls_d= hm_parse_dhm(ctx->dhm_ctx,
- (const unsigned char *) = dh_file,
+ if = (!mbed_ok(mbedtls_dhm_parse_dhm(ctx->dhm_ctx, (const unsigned char *)dh_= file,
strlen(dh= _file) + 1)))
{
msg(M= _FATAL, "Cannot read inline DH parameters");
@@ -= 482,24 +467,23 @@
}

= msg(D_TLS_DEBUG_LOW, "Diffie-Hellman initialized with " coun= ter_format " bit key",
- (counter_type) mbedtls_dhm_get_bitlen(ctx->dhm_ctx));=
+ (counter_ty= pe)mbedtls_dhm_get_bitlen(ctx->dhm_ctx));
}
<= span>

void
-tls_ctx_load_ecdh_params(struct tls_root_ctx *ctx, const char *curve= _name
- = )
+tls_ctx_l= oad_ecdh_params(struct tls_root_ctx *ctx, const char *curve_name) {
if (NULL !=3D curve_name)
= {
msg(M_WARN, "WARNING: mbed TLS builds do= not support specifying an "
- "ECDH curve with --ecdh-curve, using default c= urves. Use "
- = "--tls-groups to specify curves.");
+ "ECDH curve with= --ecdh-curve, using default curves. Use "
+ "--tls-groups to speci= fy curves.");
}
}

int
- boo= l pkcs12_file_inline, bool load_ca_file)
+tls_ctx_load_pkcs12(struct tls_root_ctx *ctx, const ch= ar *pkcs12_file, bool pkcs12_file_inline,
+ bool load_ca_file)
{

msg(M_FATAL, "PKCS #12 files not yet support= ed for mbed TLS.");
return 0;
@@ = -514,8 +498,7 @@
#endif /* _WIN32 */

void
-tls= _ctx_load_cert_file(struct tls_root_ctx *ctx, const char *cert_file,=
- bool = cert_inline)
+tls_ctx= _load_cert_file(struct tls_root_ctx *ctx, const char *cert_file, bool cert_= inline)
{
ASSERT(NULL !=3D ctx);

@@ -526,8 +509,7 @@
<= br> if (cert_inline)
{
- if (!mbed_ok(mbedtls_x509_crt_parse= (ctx->crt_chain,
- = (const unsigned char *)cert_file,=
+ if (!mbed_o= k(mbedtls_x509_crt_parse(ctx->crt_chain, (const unsigned char *)cert_fil= e,
strlen(cert= _file) + 1)))
{
msg(M= _FATAL, "Cannot load inline certificate file");
@= @ -543,8 +525,7 @@
}

in= t
-tls_ctx_load_priv_fi= le(struct tls_root_ctx *ctx, const char *priv_key_file,
- bool priv_key_inli= ne)
+tls_ctx_load_pri= v_file(struct tls_root_ctx *ctx, const char *priv_key_file, bool priv_key_i= nline)
{
int status;
= ASSERT(NULL !=3D ctx);
@@ -556,40 +537,29 @@
if (priv_key_inline)
{
- status =3D mbed= tls_compat_pk_parse_key(ctx->priv_key,
- (const uns= igned char *) priv_key_file,
+ status =3D mbedtls_compat_pk_parse_key(ctx->priv_key, (= const unsigned char *)priv_key_file,
= strlen(priv_key_file) + 1, NULL, 0,
- = mbedtls_ctr_drbg_random,

- rand_ctx_get());
+ = mbedtls_ctr_drbg_random, rand_ctx_get());
=
if (MBEDTLS_ERR_PK_PASSWORD_REQUIRED =3D= =3D status)
{
- char passbuf[512] =3D {0};
+ char passbuf[512] =3D { 0 }= ;
pem_password_callback(passbuf, 512, 0, NULL)= ;
- status = =3D mbedtls_compat_pk_parse_key(ctx->priv_key,
- = (const unsigned char *) priv_key_file,
- strlen(= priv_key_file) + 1,
- = (unsigned char *) passbuf,
- = strlen(passbuf),
- mbedt= ls_ctr_drbg_random,
- = rand_ctx_get());
<= span style=3D"color: hsl(120, 100%, 40%);">+ status =3D mbedtls_= compat_pk_parse_key(

= + ctx->priv_key, (const unsigned char *)priv_key_file, st= rlen(priv_key_file) + 1,
+ (unsigned char *)passbuf, strlen(passbuf), mbedtls_ctr= _drbg_random, rand_ctx_get());
}
= }
else
{
- status =3D mbedtls_compat_pk_parse= _keyfile(ctx->priv_key,
- priv_key_file,=
- = NULL,
- mbedtls_ctr_drbg_rand= om,
- = rand_ctx_get());
+ status =3D mbedtls_compat_pk_parse_keyf= ile(ctx->priv_key, priv_key_file, NULL,
+ mbe= dtls_ctr_drbg_random, rand_ctx_get());
if (MBEDTLS= _ERR_PK_PASSWORD_REQUIRED =3D=3D status)
{<= br>- char passbuf[512]= =3D {0};
+ = char passbuf[512] =3D { 0 };
pem_password_ca= llback(passbuf, 512, 0, NULL);
- status =3D mbedtls_compat_pk_parse_keyfile(ctx->pri= v_key,
- = priv_key_file, passbuf,
- = mbedtls_ctr_drbg_random,

- r= and_ctx_get());
+ = status =3D mbedtls_compat_pk_parse_keyfile(ctx->priv_key, priv_k= ey_file, passbuf,
+ = mbedtls_ctr_drbg_random,= rand_ctx_get());
}
}<= br> if (!mbed_ok(status))
@@ -605,10 +575,8 @@
return 1;
}

- if (!mbed_ok(mbedtl= s_compat_pk_check_pair(&ctx->crt_chain->pk,
- = ctx->priv_key,
- = mbedtls_ctr_drbg_random,
- = rand_ctx_get())))
+ if (!mbed_ok(mbedtls_compat_pk_check_pair(&ctx->= ;crt_chain->pk, ctx->priv_key,
+ mbedtls_ctr_= drbg_random, rand_ctx_get())))
{
= msg(M_WARN, "Private key does not match the certificate");
return 1;
@@ -636,13 +604,12 @@
* @return 0 on success, non-zero mbed TLS error code on failu= re.
*/
static inline int
-external_pkcs1_sign( void *ctx_voidpt= r,

- = int (*f_rng)(void *, unsigned char *, size_t), void *p_rng,
+external_pkcs1_sign(void *ctx_voi= dptr, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng,
#if MBEDTLS_VERSION_NUMBER < 0x03020100
- int mode,
+ int mode,
#endif
- = mbedtls_md_type_t md_alg, unsigned int hashlen, const uns= igned char *hash,
- = unsigned char *sig )
+ mbedtls_md_type_t md_alg, unsigned in= t hashlen, const unsigned char *hash,
+ unsigned char *sig)
= {
struct external_context *const ctx =3D ctx_voidptr;<= /span>
int rv;
@@ -670,23 +637,22 @@ */
if (md_alg !=3D MBEDTLS_MD_NONE)
{
- = const mbedtls_md_info_t *md_info =3D mbedtls_md_info_from_type( md_alg= );
+ const mb= edtls_md_info_t *md_info =3D mbedtls_md_info_from_type(md_alg);
<= span> if (md_info =3D=3D NULL)

{- return( MBEDTLS_ERR= _RSA_BAD_INPUT_DATA );
- if (!mbed_ok(mbedtls_oid_get_oid_by_md( md_alg, &oid, &= oid_size )))
+ = if (!mbed_ok(mbedtls_oid_get_oid_by_md(md_alg, &oid, &oid_size)))<= /span>
{
- return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
+ return (MBEDTLS_ERR_RSA_= BAD_INPUT_DATA);
}

- hashlen =3D mbedtls_md_get_= size( md_info );

+ = hashlen =3D mbedtls_md_get_size(md_info);
asn= _len =3D 10 + oid_size;
}

= - if ((SIZE_MAX - hashlen) <= ; asn_len
- || c= tx->signature_length < (asn_len + hashlen))
+ if ((SIZE_MAX - hashlen) < asn_len || = ctx->signature_length < (asn_len + hashlen))
{
return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
}

@@ -705,12 +671,12 @@
= * Digest ::=3D OCTET STRING
*/
= *p++ =3D MBEDTLS_ASN1_SEQUENCE | MBEDTLS_ASN1_CONSTRUCTED;- *p++ =3D (unsigned char= ) ( 0x08 + oid_size + hashlen );
+ *p++ =3D (unsigned char)(0x08 + oid_size + hashlen);
*p++ =3D MBEDTLS_ASN1_SEQUENCE | MBEDTLS_ASN1_CONST= RUCTED;
- *p++ = =3D (unsigned char) ( 0x04 + oid_size );
+ *p++ =3D (unsigned char)(0x04 + oid_size);
*p++ =3D MBEDTLS_ASN1_OID;
*= p++ =3D oid_size & 0xFF;
- memcpy( p, oid, oid_size );
+ memcpy(p, oid, oid_size);
= p +=3D oid_size;
*p++ =3D MBEDTLS_ASN1_NULL= ;
*p++ =3D 0x00;
@@ -725,8 +691,7 = @@
memcpy(p, hash, hashlen);
<= br> /* Call external signature function */
- if (!ctx->sign(ctx->sign_ctx, to_= sign, asn_len + hashlen, sig,
- ctx->signature_length))
+ if (!ctx->sign(ctx->sign_ctx, t= o_sign, asn_len + hashlen, sig, ctx->signature_length))
= {
rv =3D MBEDTLS_ERR_RSA_PRIVATE_FAILED;
goto done;
@@ -748,8 +713,8 @@<= br> }

int
-tls_ctx_use_external_signing_func(struct tls_r= oot_ctx *ctx,
- = external_sign_func sign_func, void *sign_ctx)
+tls_ctx_use_external_si= gning_func(struct tls_root_ctx *ctx, external_sign_func sign_func,+ = void *sign_ctx)
{
ASSERT(NULL != =3D ctx);

@@ -762,7 +727,7 @@
<= span> if (mbedtls_pk_get_type(&ctx->crt_chain->pk) !=3D MBEDT= LS_PK_RSA)

{
msg(M_WARN, &quo= t;ERROR: external key with mbed TLS requires a "
- "certificate with an RSA k= ey.");
+ = "certificate with an RSA key.");
= return 1;
}

@@ = -771,8 +736,8 @@
ctx->external_key.sign_ctx =3D sig= n_ctx;

ALLOC_OBJ_CLEAR(ctx->priv_= key, mbedtls_pk_context);
- if (!mbed_ok(mbedtls_pk_setup_rsa_alt(ctx->priv_key, &ctx-&g= t;external_key,
- = NULL, external_pkcs1_sign, external_key= _len)))
+ if (!mbe= d_ok(mbedtls_pk_setup_rsa_alt(ctx->priv_key, &ctx->external_key, = NULL,
+ = external_pkcs1_sign, external_key_len)))=
{
return 1;
}<= /span>
@@ -783,8 +748,7 @@
#ifdef ENABLE_MANAGEME= NT
/** Query the management interface for a signature, see= external_sign_func. */
static bool
-management_sign_func(void *sign_ctx, const = void *src, size_t src_len,
- void *dst, size_t dst_len)
+management_sign_func(void *sign_ctx, cons= t void *src, size_t src_len, void *dst, size_t dst_len)
{<= /span>
bool ret =3D false;
char *src_b64= =3D NULL;
@@ -799,8 +763,7 @@
* We o= nly support RSA external keys and PKCS1 signatures at the moment
= * in mbed TLS, so the signature parameter is hardcoded to this = encoding
*/
- if (!(dst_b64 =3D management_query_pk_sig(management, src_b= 64,
- = "RSA_PKCS1_PADDING")))
+ if (!(dst_b64 =3D management_que= ry_pk_sig(management, src_b64, "RSA_PKCS1_PADDING")))
<= span> {

goto cleanup;
}
@@ -827,8 +790,8 @@
#endif /* ifdef ENABLE_= MANAGEMENT */

void
-tls_ctx_load_ca(struct tls_root_ctx *ctx, c= onst char *ca_file,
- = bool ca_inline, const char *ca_path, bool tls_server)<= br>+tls_ctx_load_ca(struct tls_= root_ctx *ctx, const char *ca_file, bool ca_inline, const char *ca_path,
+ bool t= ls_server)
{
if (ca_path)
<= span> {

@@ -837,8 +800,7 @@
if (ca_file && ca_inline)
{=
- if (!mbed_ok(mbedtls= _x509_crt_parse(ctx->ca_chain,
- (const unsigned cha= r *) ca_file,
+ = if (!mbed_ok(mbedtls_x509_crt_parse(ctx->ca_chain, (const unsigned cha= r *)ca_file,
s= trlen(ca_file) + 1)))
{
= msg(M_FATAL, "Cannot load inline CA certificates");
= @@ -867,8 +829,7 @@

if (extra_= certs_inline)
{
- if (!mbed_ok(mbedtls_x509_crt_parse(ctx->crt_chai= n,
- = (const unsigned char *) extra_certs_file,+ if (!mbed_ok(mbedtls= _x509_crt_parse(ctx->crt_chain, (const unsigned char *)extra_certs_file,=
strlen(extra_= certs_file) + 1)))
{
= msg(M_FATAL, "Cannot load inline extra-certs file");
@@ -916,7 +877,7 @@

}

static int

-endless_= buf_read( endless_buffer *in, unsigned char *out, size_t out_len )+endless_buf_read(endless_buf= fer *in, unsigned char *out, size_t out_len)
{
<= span> size_t read_len =3D 0;


@@ -931,= 8 +892,7 @@
if (block_len <=3D out_len - read_l= en)
{
buffer_entry *c= ur_entry =3D in->first_block;
- memcpy(out + read_len, cur_entry->data + in->d= ata_start,
- = block_len);
+= memcpy(out + read_len, cur_entry->data + in->data_start, = block_len);

read_len +=3D bl= ock_len;

@@ -948,8 +908,7 @@
}

else
{
- memcpy(out + = read_len, in->first_block->data + in->data_start,
- out_len - read_len)= ;
+ memcpy= (out + read_len, in->first_block->data + in->data_start, out_len -= read_len);
in->data_start +=3D out_len - r= ead_len;
read_len =3D out_len;
}

@@ -959,7 +918,7 @@
}
static int
-endless_buf_write( endless_buffer *out, const unsigned char= *in, size_t len )
+e= ndless_buf_write(endless_buffer *out, const unsigned char *in, size_t len)<= /span>
{
buffer_entry *new_block =3D malloc(= sizeof(buffer_entry));
if (NULL =3D=3D new_block)
@@ -995,22 +954,21 @@
}

static int
-ssl_bio_read( void *ctx, unsigned char *out, size_t out_len)
+ssl_bio_read(void *ctx, unsigned= char *out, size_t out_len)

{
- bio_ctx *my_ctx =3D (bio_ctx *) ctx;+ bio_ctx *my_ctx =3D (bio_= ctx *)ctx;
return endless_buf_read(&my_ctx->in,= out, out_len);
}

stati= c int
-ssl_bio_write( v= oid *ctx, const unsigned char *in, size_t in_len)
+ssl_bio_write(void *ctx, const unsigned char = *in, size_t in_len)
{
- bio_ctx *my_ctx =3D (bio_ctx *) ctx;
+ bio_ctx *my_ctx =3D (bio_ctx *)ct= x;
return endless_buf_write(&my_ctx->out, in, i= n_len);
}

static void
-my_debug( void *ctx, in= t level, const char *file, int line,
- const char *str )
+my_debug(void *ctx, int level, const char *file, int= line, const char *str)
{
int my_logl= evel =3D (level < 3) ? D_TLS_DEBUG_MED : D_TLS_DEBUG;
= msg(my_loglevel, "mbed TLS msg (%s:%d): %s", file, line, str);=
@@ -1022,8 +980,8 @@
void
tls_ctx_personalise_random(struct tls_root_ctx *ctx)

{
- static char old_sha= 256_hash[32] =3D {0};
-= unsigned char sha256_hash[32] =3D {0};
+ static char old_sha256_hash[32] =3D { 0 };
+ unsigned char sha256_= hash[32] =3D { 0 };
mbedtls_ctr_drbg_context *cd_ctx = =3D rand_ctx_get();

if (NULL !=3D ct= x->crt_chain)
@@ -1055,7 +1013,7 @@
#el= if defined(MBEDTLS_SSL_PROTO_TLS1_2)
return TLS_VER_1_= 2;
#else
- #error mbedtls is compiled without support for TLS 1.2 or 1.3
+#error mbedtls is compile= d without support for TLS 1.2 or 1.3
#endif
}


@@ -1088,8 +1046,7 @@
}


void
-backend_tls_ctx_reload_crl(struct tls_root_ctx *ctx,= const char *crl_file,
= - bool crl_inline)
+backend_tls_ctx_reload_crl(struct tls_root_ctx *ct= x, const char *crl_file, bool crl_inline)
{
ASSERT(crl_file);


@@ -1101,8 +1058= ,7 @@

if (crl_inline)
{

- if (!= mbed_ok(mbedtls_x509_crl_parse(ctx->crl,
- (const un= signed char *)crl_file,
+ if (!mbed_ok(mbedtls_x509_crl_parse(ctx->crl, (const unsigne= d char *)crl_file,
= strlen(crl_file) + 1)))
{
= msg(M_WARN, "CRL: cannot parse inline CRL");
= @@ -1124,8 +1080,7 @@
}

= void
-key_state_= ssl_init(struct key_state_ssl *ks_ssl,
- const struct tls_root_ctx *ssl_ctx, boo= l is_server,
+key_sta= te_ssl_init(struct key_state_ssl *ks_ssl, const struct tls_root_ctx *ssl_ct= x, bool is_server,
struct tls_session *= session)
{
ASSERT(NULL !=3D ssl_ctx);=
@@ -1135,8 +1090,8 @@
/* Initialise S= SL config */
ALLOC_OBJ_CLEAR(ks_ssl->ssl_config, mb= edtls_ssl_config);
mbedtls_ssl_config_init(ks_ssl->= ssl_config);
- mbedt= ls_ssl_config_defaults(ks_ssl->ssl_config, ssl_ctx->endpoint,<= br>- = MBEDTLS_SSL_TRANSPORT_STREAM, MBEDTLS_SSL_PRESET_DEFAULT);
+ mbedtls_ssl_config_defaults(k= s_ssl->ssl_config, ssl_ctx->endpoint, MBEDTLS_SSL_TRANSPORT_STREAM,
+ = MBEDTLS_SSL_PRESET_DEFAULT);
#ifdef MBEDTLS_DEB= UG_C
/* We only want to have mbed TLS generate debug l= evel logging when we would
* also display it.<= br>@@ -1152,8 +1107,7 @@
}
#end= if
mbedtls_ssl_conf_dbg(ks_ssl->ssl_config, my_debu= g, NULL);
- mbedtls_= ssl_conf_rng(ks_ssl->ssl_config, mbedtls_ctr_drbg_random,
- rand_ctx_ge= t());

+ mbedtls_ss= l_conf_rng(ks_ssl->ssl_config, mbedtls_ctr_drbg_random, rand_ctx_get());=

mbedtls_ssl_conf_cert_profile(ks_ss= l->ssl_config, &ssl_ctx->cert_profile);
<= br>@@ -1168,8 +1122,8 @@
}

/* Disable TLS renegotiations if the mbedtls library supp= orts that feature.
- = * OpenVPN's renegotiation creates new SSL sessions and does not depend= on
- * this feature= and TLS renegotiations have been problematic in the past. */
+ * OpenVPN's renegotiatio= n creates new SSL sessions and does not depend on

+ * this feature and TLS renegotiations ha= ve been problematic in the past. */
#if defined(MBEDTLS_SS= L_RENEGOTIATION)
mbedtls_ssl_conf_renegotiation(ks_ssl= ->ssl_config, MBEDTLS_SSL_RENEGOTIATION_DISABLED);
#end= if /* MBEDTLS_SSL_RENEGOTIATION */
@@ -1186,12 +1140,10 @@<= /span>
/* Initialise authentication information */
= if (is_server)
{
- mbed_ok(mbedtls_ssl_conf_dh_param_ctx(ks= _ssl->ssl_config,
- = ssl_ctx->dhm_ctx));<= br>+ mbed_ok(mbedtls_ssl= _conf_dh_param_ctx(ks_ssl->ssl_config, ssl_ctx->dhm_ctx));
= }

- mbed_ok(mbedtls_ssl_conf_own_cert(ks_ssl->ssl_config, ssl_c= tx->crt_chain,
- = ssl_ctx->priv_key));
+ mbed_ok(mbedtls_ssl_conf_own_cert= (ks_ssl->ssl_config, ssl_ctx->crt_chain, ssl_ctx->priv_key));

/* Initialise SSL verification */=
if (session->opt->ssl_flags & SSLF_CLIENT_CERT_OPT= IONAL)
@@ -1210,8 +1162,7 @@
/* Initia= lize minimum TLS version */
{
= const int configured_tls_version_min =3D
- (session->opt->ssl_flags >> SSL= F_TLS_VERSION_MIN_SHIFT)
+ (session->opt->ssl_flags >&= gt; SSLF_TLS_VERSION_MIN_SHIFT) & SSLF_TLS_VERSION_MIN_MASK;
=
/* default to TLS 1.2 */
= mbedtls_ssl_protocol_version version =3D MBEDTLS_SSL_VERSION_TLS1_2= ;
@@ -1227,8 +1178,7 @@
/* Initialize = maximum TLS version */
{
cons= t int configured_tls_version_max =3D
- (session->opt->ssl_flags >> SSLF_TLS= _VERSION_MAX_SHIFT)
- = &SSLF_TLS_VERSION_MAX_MASK;
+ (session->opt->ssl_flags >> S= SLF_TLS_VERSION_MAX_SHIFT) & SSLF_TLS_VERSION_MAX_MASK;

mbedtls_ssl_protocol_version version =3D MBEDTL= S_SSL_VERSION_UNKNOWN;

@@ -1245,10 +1195,= 10 @@
mbedtls_ssl_conf_max_tls_version(ks_ssl->= ssl_config, version);
}

-#if defined(HAVE_MBEDTLS_SSL_CONF_= EXPORT_KEYS_EXT_CB) && !defined(MBEDTLS_SSL_KEYING_MATERIAL_EXPORT)=

+#if defined(HAVE_MB= EDTLS_SSL_CONF_EXPORT_KEYS_EXT_CB) \
+ && !defined(MBEDTLS_SSL_KEYING_MATERIAL_EXPORT= )
/* Initialize keying material exporter, old style. *= /
- mbedtls_ssl_conf= _export_keys_ext_cb(ks_ssl->ssl_config,
- mbedtls_ssl_ex= port_keys_cb, session);
+ mbedtls_ssl_conf_export_keys_ext_cb(ks_ssl->ssl_config, mbedtls_= ssl_export_keys_cb, session);
#endif

/* Initialise SSL context */
@@ -1267,8 += 1217,7 @@

/* Initialise BIOs */
ALLOC_OBJ_CLEAR(ks_ssl->bio_ctx, bio_ctx);
- mbedtls_ssl_set_bio(ks_ssl->= ;ctx, ks_ssl->bio_ctx, ssl_bio_write,

- ssl_bio_read, NULL);
<= span style=3D"color: hsl(120, 100%, 40%);">+ mbedtls_ssl_set_bio(ks_ssl-= >ctx, ks_ssl->bio_ctx, ssl_bio_write, ssl_bio_read, NULL);

= }


@@ -1317,7 +12= 66,7 @@

if (1 =3D=3D retval)<= br> {
- = memset(BPTR(buf), 0, BLEN(buf)); /* erase data just written */+ memset(BPTR(buf), 0, = BLEN(buf)); /* erase data just written */
buf->= len =3D 0;
}

@@ -135= 0,16 +1299,14 @@
{
re= turn 0;
}
- mbed_log_err(D_TLS_ERRORS, retval,
- "TLS ERROR: wri= te tls_write_plaintext_const error");
+ mbed_log_err(D_TLS_ERRORS, retval, "TLS= ERROR: write tls_write_plaintext_const error");
= return -1;
}

= if (retval !=3D len)
{
- msg(D_TLS_ERRORS,
- "TLS ERROR: write tls_write_pl= aintext_const incomplete %d/%d",
- retval, len);
+ msg(D_TLS_ERRORS, "TLS ERROR: write tls_= write_plaintext_const incomplete %d/%d", retval,
+ len);
= perf_pop();
return -1;
}
@@ -1446,15 +1393,14 @@
{
= return 0;
}
- mbed_log_err(D_TLS_ERRORS, retval= ,
- = "TLS ERROR: write tls_write_ciphertext error");
+ mbed_log_err(D_TLS_ERRORS, r= etval, "TLS ERROR: write tls_write_ciphertext error");
= return -1;
}
if (retval !=3D buf->len)
{
= - msg(D_TLS_ERRORS, "= TLS ERROR: write tls_write_ciphertext incomplete %d/%d",
- retval, buf->len);
+ msg(D_TLS_ERR= ORS, "TLS ERROR: write tls_write_ciphertext incomplete %d/%d", re= tval,
+ bu= f->len);
perf_pop();
r= eturn -1;
}
@@ -1462,7 +1408,7 @@
/* successful write */
dmsg(D_HANDSHA= KE_VERBOSE, "write tls_write_ciphertext %d bytes", retval);

- memse= t(BPTR(buf), 0, BLEN(buf)); /* erase data just written */
+ memset(BPTR(buf), 0, BLEN(buf));= /* erase data just written */
buf->len =3D 0;

perf_pop();
@@ -1534,25 = +1480,20 @@
char s2[256];

= s1[0] =3D s2[0] =3D 0;
- snprintf(s1, sizeof(s1), "%s %s, cipher %s",
- prefix,
- mbedtls_ssl_ge= t_version(ks_ssl->ctx),
+ snprintf(s1, sizeof(s1), "%s %s, cipher %s", prefix, m= bedtls_ssl_get_version(ks_ssl->ctx),
mbedt= ls_ssl_get_ciphersuite(ks_ssl->ctx));

= cert =3D mbedtls_ssl_get_peer_cert(ks_ssl->ctx);
= if (cert !=3D NULL)
{
- snprintf(s2, sizeof(s2), ", %u bit key= ",
- = (unsigned int) mbedtls_pk_get_bitlen(&cert->pk));
+ snprintf(s2, sizeof(s2), &q= uot;, %u bit key", (unsigned int)mbedtls_pk_get_bitlen(&cert->p= k));

}

msg(D_HA= NDSHAKE, "%s%s", s1, s2);
}

void
-sh= ow_available_tls_ciphers_list(const char *cipher_list,
- const char= *tls_cert_profile,
- = bool tls13)
+show_available_tls_ciphers_list(const char *cipher_li= st, const char *tls_cert_profile, bool tls13)
{
= if (tls13)
{
@@ -1603,8 +15= 44,8 @@
{
static char mbedtls_version= [30];
unsigned int pv =3D mbedtls_version_get_number()= ;
- snprintf(mbedtls= _version, sizeof(mbedtls_version), "mbed TLS %d.%d.%d",- (pv>>24)&= ;0xff, (pv>>16)&0xff, (pv>>8)&0xff );
+ snprintf(mbedtls_version, sizeof(= mbedtls_version), "mbed TLS %d.%d.%d", (pv >> 24) & 0xf= f,
+ (pv = >> 16) & 0xff, (pv >> 8) & 0xff);
= return mbedtls_version;
}

diff --git a/src/openvpn/ssl_mbedtls.h b/src/openvpn/ssl_mbedtls.h
=
index fba766b..513a07e 100644
--- a/src/openvpn/s= sl_mbedtls.h
+++ b/src/openvpn/ssl_mbedtls.h
@@ -43,19 +43,22 @@


typedef struct _bu= ffer_entry buffer_entry;

-struct _buffer_entry {
+struct _buffer_entry
+{
size_t length;
uint8_t *data;

buffer_entry *next_block;
};

-typedef struct {
+typedef struct
+{
size_t data_start;
buffer_e= ntry *first_block;
buffer_entry *last_block; } endless_buffer;

-typedef struct {
+typedef struct
+{
endless_buffer in;
= endless_buffer out;
} bio_ctx;
@@ -73,12= +76,12 @@
*
* @return true if signing = succeeded, false otherwise.
*/
-typedef bool (*external_sign_func)(
- void *sign_ctx, const void *sr= c, size_t src_size,

- = void *dst, size_t dst_size);
+typedef bool (*external_sign_func)(void *sign_ctx, const void *s= rc, size_t src_size, void *dst,
+ size_t dst_size);
=
/** Context used by external_pkcs1_sign() */
-struct external_context {
+struct external_conte= xt
+{
size_t signature_length;

external_sign_func sign= ;
void *sign_ctx;
@@ -91,13 +94,16 @@<= /span>
*
* The constants 64 and 48 are inheren= t to TLS 1.2. For TLS 1.3, it is not
* possible to obtain= the exporter master secret from mbed TLS. */
-struct tls_key_cache {
+struct tls_key_cache
+{
unsigned char client_ser= ver_random[64];
mbedtls_tls_prf_types tls_prf_type;
unsigned char master_secret[48];
};

-#else /* !defined(MBEDTL= S_SSL_KEYING_MATERIAL_EXPORT) */
-struct tls_key_cache { };
+#else /* !defined(MBEDTLS_SSL_KEYING_MATERIAL_EXPORT) */
+struct tls_key_cache<= /span>
+{
+};
#endif
<= span>

/**
@@ -106,30 +112,32 @@ *
* Either \c priv_key_pkcs11 or \c priv_key mus= t be filled in.
*/
-struct tls_root_ctx {
- bool initialised; /**< True if the context = has been initialised */
+struct tls_root_ctx
+{
+ bool initi= alised; /**< True if the context has been initialis= ed */

- int endpoint; /**< Whether or not this is a server o= r a client */
+ in= t endpoint; /**< Whether or not this is a serve= r or a client */

- mbedtls_dhm_context *dhm_ctx; /**< Diffie-Helmann= -Merkle context */
- = mbedtls_x509_crt *crt_chain; /**< Local Certificate chain */
- mbedtls_x509_crt *ca_= chain; /**< CA chain for remote verification */
- mbedtls_pk_context *priv_key; = /**< Local private key */
- mbedtls_x509_crl *crl; /**< Certificate Revoca= tion List */
- time_= t crl_last_mtime; /**< CRL last modification time */=
- off_t crl_last_size; = /**< size of last loaded CRL */
+ mbedtls_dhm_context *dhm_ctx; /**&l= t; Diffie-Helmann-Merkle context */
+ mbedtls_x509_crt *crt_chain; /**< Local Ce= rtificate chain */
+ = mbedtls_x509_crt *ca_chain; /**< CA chain for remote verif= ication */
+ mbedt= ls_pk_context *priv_key; /**< Local private key */
+ mbedtls_x509_crl *crl; = /**< Certificate Revocation List */

+ time_t crl_last_mtime; /*= *< CRL last modification time */
+ off_t crl_last_size; /**< size of = last loaded CRL */
#ifdef ENABLE_PKCS11
- pkcs11h_certificate_t pkcs11_cert; = /**< PKCS11 certificate */
+ pkcs11h_certificate_t pkcs11_cert; /**< PKCS11 certifi= cate */
#endif
- struct external_context external_key; /**< External key co= ntext */
- int *allo= wed_ciphers; /**< List of allowed ciphers for this connection */
- mbedtls_compat_grou= p_id *groups; /**< List of allowed groups for this connection */
+ struct external_con= text external_key; /**< External key context */
+ int *allowed_ciphers; = /**< List of allowed ciphers for this connection */
+ mbedtls_compat_group_id *groups; = /**< List of allowed groups for this connection */
= mbedtls_x509_crt_profile cert_profile; /**< Allowed certificate typ= es */
};

-struct key_state_ssl {
- mbedtls_ssl_config *ssl_config; /**< mbed= TLS global ssl config */
+struct key_sta= te_ssl
+{
<= span style=3D"color: hsl(120, 100%, 40%);">+ mbedtls_ssl_config *ssl_con= fig; /**< mbedTLS global ssl config */

+ mbedtls_ssl_context *ctx; /**< mbedTLS c= onnection context */
bio_ctx *bio_ctx;

struct tls_key_cache tls_key_cache;
@@ -145,8 +153,7 @@

*
* @return = 0 if successful, 1 if an error occurred.
*= /
-int tls_ctx_use_exte= rnal_signing_func(struct tls_root_ctx *ctx,
- external_sign_f= unc sign_func,
+int t= ls_ctx_use_external_signing_func(struct tls_root_ctx *ctx, external_sign_fu= nc sign_func,
void *= sign_ctx);

static inline void
= diff --git a/src/openvpn/ssl_ncp.c b/src/openvpn/ssl_ncp.c
= index 62fef42..5e094a2 100644
--- a/src/openvpn/ssl_n= cp.c
+++ b/src/openvpn/ssl_ncp.c
@@ -82,8 += 82,7 @@
{
return false;
}
- = else if (tls_peer_info_ncp_ver(peer_info) >=3D 2
- || strstr(peer_info, "IV_= CIPHERS=3D"))
+ = else if (tls_peer_info_ncp_ver(peer_info) >=3D 2 || strstr(peer_info,= "IV_CIPHERS=3D"))
{
= return true;
}
@@ -98,7 +97,7 @@
{
bool error_found =3D false;
=
- struct buf= fer new_list =3D alloc_buf(MAX_NCP_CIPHERS_LENGTH);
+ struct buffer new_list =3D alloc_buf(= MAX_NCP_CIPHERS_LENGTH);

char *const= tmp_ciphers =3D string_alloc(list, NULL);
const char = *token =3D strtok(tmp_ciphers, ":");
@@ -126,22 += 125,23 @@
if (nonecipher)
= {
msg(M_WARN, "WARNING: cipher 'none= ' specified for --data-ciphers. "
- "This allows negotiation of NO en= cryption and "
- = "tunnelled data WILL then be transmitted in clear text &= quot;
- = "over the network! "
- "PLEASE DO RECONSIDER THIS SETTING!");
+ = "This allows negotiation of NO encryption and "
+ "tunn= elled data WILL then be transmitted in clear text "

+ "over the= network! "
+ = "PLEASE DO RECONSIDER THIS SETTING!");
}
if (!nonecipher && != cipher_valid(token))
{
= msg(M_WARN, "Unsupported %scipher in --data-ciphers: %s", optst= r, token);
error_found =3D error_found || !opt= ional;
}
- else if (!nonecipher && !cipher_kt_mode_aead(to= ken)
- = && !cipher_kt_mode_cbc(token)
+ else if (!nonecipher && !cipher_kt_mode_a= ead(token) && !cipher_kt_mode_cbc(token)
= && !cipher_kt_mode_ofb_cfb(token))
= {
- msg(M_W= ARN, "Unsupported %scipher algorithm '%s'. It does not use &qu= ot;
- &q= uot;CFB, OFB, CBC, or a supported AEAD mode", optstr, token);+ msg(M_WARN,
+ "Un= supported %scipher algorithm '%s'. It does not use "+ "CFB, OF= B, CBC, or a supported AEAD mode",
+ optstr, token);
= error_found =3D error_found || !optional;
}<= /span>
else
@@ -154,7 +154,7 @@ ovpn_cipher_name =3D "none";
}


- if (buf_len(&new_list)> 0)
+ if (buf_len(&new_l= ist) > 0)

{
= /* The next if condition ensure there is always space for
* a :

@@ -163,11 +163,10 @@
}


/* Ensure= buffer has capacity for cipher name + : + \0 */
- if (!(buf_forward_capacity(&new_= list) >
- = strlen(ovpn_cipher_name) + 2))
+ if (!(buf_forward_capacity(&new_list) >= ; strlen(ovpn_cipher_name) + 2))
{
<= span> msg(M_WARN, "Length of --data-ciphers is over th= e "

- = "limit of 127 chars");
+ "limit of 127 chars&qu= ot;);
error_found =3D true;
}

else
@@ -179,= 7 +178,6 @@
}


-
char= *ret =3D NULL;
if (!error_found && buf_len(&a= mp;new_list) > 0)
{
@@ -200,8 +198,= 7 @@
size_t newlen =3D strlen(o->ncp_ciphers) + 1 += strlen(ciphername) + 1;
char *ncp_ciphers =3D gc_mall= oc(newlen, false, &o->gc);

- ASSERT(snprintf(ncp_ciphers, newlen, &q= uot;%s:%s", o->ncp_ciphers,
- ciphername));
+ ASSERT(snprintf(ncp_ciphers, newlen, "= %s:%s", o->ncp_ciphers, ciphername));
o->nc= p_ciphers =3D ncp_ciphers;
}

<= span>@@ -233,7 +230,7 @@

{
re= turn iv_ciphers;
}
- else if (tls_peer_info_ncp_ver(peer_info)>=3D2)
+ else if (tls_peer_= info_ncp_ver(peer_info) >=3D 2)
{
= /* If the peer announces IV_NCP=3D2 then it supports the AES GCM
* ciphers */
@@ -246,8 +243,8 @@
}

char *
-ncp_get_best_cipher(const char *server= _list, const char *peer_info,
- const char *remote_cipher, struct gc_arena *gc)=
+ncp_get_best_cipher= (const char *server_list, const char *peer_info, const char *remote_cipher,=
+ = struct gc_arena *gc)
{
/*
= * The gc of the parameter is tied to the VPN session, create a<= /span>
@@ -262,8 +259,7 @@
/* non-NCP clients= without OCC? "assume nothing" */
/* For cl= ient doing the newer version of NCP (that send IV_CIPHERS)
= * we cannot assume that they will accept remote_cipher */
<= span style=3D"color: hsl(0, 100%, 40%);">- if (remote_cipher =3D=3D NULL=

- || (peer_info= && strstr(peer_info, "IV_CIPHERS=3D")))
+ if (remote_cipher =3D=3D NULL ||= (peer_info && strstr(peer_info, "IV_CIPHERS=3D")))
{
remote_cipher =3D "";<= /span>
}
@@ -273,8 +269,7 @@
= const char *token;
while ((token =3D strsep(&= tmp_ciphers, ":")))
{
- if (tls_item_in_cipher_list(token, = peer_ncp_list)
- = || streq(token, remote_cipher))
+ if (tls_item_in_cipher_list(token, peer_ncp_list) = || streq(token, remote_cipher))
{
= break;
}
@@ -302,8 +2= 97,7 @@
static bool
tls_poor_mans_ncp(str= uct options *o, const char *remote_ciphername)
{- if (remote_ciphername
- && tls_item= _in_cipher_list(remote_ciphername, o->ncp_ciphers))
+ if (remote_ciphername && tls= _item_in_cipher_list(remote_ciphername, o->ncp_ciphers))
{

o->ciphername =3D string_alloc(remote_c= iphername, &o->gc);
msg(D_TLS_DEBUG_LOW, &q= uot;Using peer cipher '%s'", o->ciphername);
@@ -338,29 +332,27 @@

/* We failed negotiation, give= appropriate error message */
if (c->c2.tls_multi-&= gt;remote_ciphername)
{
- msg(D_TLS_ERRORS, "OPTIONS ERROR: faile= d to negotiate "
+ msg(D_TLS_ERRORS,
+ "OPTIONS ERROR: failed to negotiate "<= br> "cipher with server. Add the server's "= ;
"cipher ('%s') to --data-cipher= s (currently '%s'), e.g."
"-= -data-ciphers %s:%s if you want to connect to this server.",- c->c2.tls_multi-= >remote_ciphername,
= - c->options.ncp_ciphers_conf, c->options.ncp_ciphers_conf= ,
- c->c2= .tls_multi->remote_ciphername);
+ c->c2.tls_multi->remote_ciphername, c->= options.ncp_ciphers_conf,
+ c->options.ncp_ciphers_conf, c->c2.tls_multi->re= mote_ciphername);
return false;
-
}
= else
{
msg(D_TLS_ERRORS,= "OPTIONS ERROR: failed to negotiate "
- "cipher with server. Configure = "
- &qu= ot;--data-ciphers-fallback if you want to connect "
- "to this server.")= ;
+ = "cipher with server. Configure "
+ "--data-ciphe= rs-fallback if you want to connect "
+ "to this server."= );
return false;
}
= }

const char *
-get_p2p_ncp_cipher(struct tls_session *s= ession, const char *peer_info,
- struct gc_arena *gc)
+get_p2p_ncp_cipher(struct tls_session *session= , const char *peer_info, struct gc_arena *gc)
{
= /* we use a local gc arena to keep the temporary strings needed = by strsep */
struct gc_arena gc_local =3D gc_new();
@@ -410,8 +402,7 @@
}

static void
- = const char *common_cipher)
+p2p_ncp_set_options(struct tls_multi *multi, struct tls_session *ses= sion, const char *common_cipher)
{
/*= will return 0 if peer_info is null */
const unsigned = int iv_proto_peer =3D extract_iv_proto(multi->peer_info);
@@ -433,8 +424,8 @@

session->opt->crypto_f= lags |=3D CO_USE_CC_EXIT_NOTIFY;
}

- if (session->opt= ->data_epoch_supported && (iv_proto_peer & IV_PROTO_DATA_EPO= CH)
- &&= common_cipher && cipher_kt_mode_aead(common_cipher))
+ if (session->opt->data_= epoch_supported && (iv_proto_peer & IV_PROTO_DATA_EPOCH) &&= amp; common_cipher

+ = && cipher_kt_mode_aead(common_cipher))
= {
session->opt->crypto_flags |=3D CO_EPOCH_D= ATA_KEY_FORMAT;
}
@@ -457,20 +448,18 @= @

uint8_t peerid[3];<= br> if (!key_state_export_keying_material(session, EXPORT= _P2P_PEERID_LABEL,
- = strlen(EXPORT_P2P_PEERID_LAB= EL),
- = &peerid, 3))
+ = strlen(EXPORT_P2P_PEERID_LABEL), &peerid, 3))
= {
/* Non DCO setup might still wo= rk but also this should never
* happen or= very likely the TLS encryption key exporter will
= * also fail */
msg(M_NONFATAL, &q= uot;TLS key export for P2P peer id failed. "
- "Continuing anyway, ex= pect problems");
+ "Continuing anyway, expect problems&= quot;);
}
else
{
multi->pee= r_id =3D (peerid[0] << 16) + (peerid[1] << 8) + peerid[2];
}
-
}
}
= if (iv_proto_peer & IV_PROTO_DYN_TLS_CRYPT)
@@ -511,1= 2 +500,11 @@
common_cipher =3D BSTR(&out);
}

- msg(D_TLS_DEBUG_LOW, "P2P mode NCP negotiation res= ult: "
+ msg(= D_TLS_DEBUG_LOW,
+ = "P2P mode NCP negotiation result: "
= "TLS_export=3D%d, DATA_v2=3D%d, peer-id %d, epoch=3D%d, cipher=3D%s&q= uot;,
- (bool)(s= ession->opt->crypto_flags & CO_USE_TLS_KEY_MATERIAL_EXPORT),
- multi->use_peer= _id,
- multi->= ;peer_id,
- (boo= l)(session->opt->crypto_flags & CO_EPOCH_DATA_KEY_FORMAT),=
+ (bool)(session->= ;opt->crypto_flags & CO_USE_TLS_KEY_MATERIAL_EXPORT), multi->use_= peer_id,
+ mul= ti->peer_id, (bool)(session->opt->crypto_flags & CO_EPOCH_DATA= _KEY_FORMAT),
common_cipher);

gc_free(&gc);
@@ -526,16 +514,15 @@<= /span>
bool
check_session_cipher(struct tls_sess= ion *session, struct options *options)
{
- bool cipher_allowed_as_fallback =3D= options->enable_ncp_fallback
- && streq(options-&= gt;ciphername, session->opt->config_ciphername);
+ bool cipher_allowed_as_fallback =3D<= /span>
+ options->= enable_ncp_fallback && streq(options->ciphername, session->op= t->config_ciphername);

if (!sessi= on->opt->server && !cipher_allowed_as_fallback
&& !tls_item_in_cipher_list(options->ciphername, opti= ons->ncp_ciphers))

{
struc= t gc_arena gc =3D gc_new();
msg(D_TLS_ERRORS, &quo= t;Error: negotiated cipher not allowed - %s not in %s%s",
- options->ciphername= , options->ncp_ciphers_conf,

- ncp_expanded_ciphers(options, &gc));
+ options->cipherna= me, options->ncp_ciphers_conf, ncp_expanded_ciphers(options, &gc));<= /span>
/* undo cipher push, abort connection setup */
options->ciphername =3D session->opt->config= _ciphername;
gc_free(&gc);
@@ = -576,7 +563,7 @@
const char *after_default =3D def + s= trlen(search);
buf_write(&ncp_ciphers_buf, after_d= efault, strlen(after_default));

- o->ncp_ciphers =3D (char *) ncp_ciphers;=
+ o->ncp_ciphe= rs =3D (char *)ncp_ciphers;
}

= /**
@@ -587,8 +574,8 @@
void=
options_postprocess_setdefault_ncpciphers(struct options *o)
{
- bo= ol default_in_cipher_list =3D o->ncp_ciphers
- && tls_= item_in_cipher_list("DEFAULT", o->ncp_ciphers);
+ bool default_in_cipher_list = =3D

+ o->nc= p_ciphers && tls_item_in_cipher_list("DEFAULT", o->ncp= _ciphers);

/* preserve the values th= at the user put into the configuration */
o->ncp_ci= phers_conf =3D o->ncp_ciphers;
diff --git a/src/openvpn/= ssl_ncp.h b/src/openvpn/ssl_ncp.h
index b01cd87..2b2ff85 10= 0644
--- a/src/openvpn/ssl_ncp.h
+++ b/src/= openvpn/ssl_ncp.h
@@ -38,8 +38,7 @@
* Ret= urns whether the client supports NCP either by
* announci= ng IV_NCP>=3D2 or the IV_CIPHERS list
*/
-bool

-tls_peer_supports_ncp(const char *peer_info);=
+bool tls_peer_supports_ncp= (const char *peer_info);

/* forward decl= aration to break include dependency loop */
struct context= ;
@@ -50,8 +49,7 @@
*
*= @return Wether the client NCP process suceeded or failed
= */
-bool
-check_pull_client_ncp(struct conte= xt *c, int found);

+b= ool check_pull_client_ncp(struct context *c, int found);
<= /span>
/**
* Iterates through the ciphers in se= rver_list and return the first
@@ -73,9 +71,8 @@
= * @returns NULL if no common cipher is available, otherwise the bes= t common
* cipher
*/
-char *
-ncp_get_best_cipher(const char *server_list, const char= *peer_info,
- = const char *remote_cipher, struct gc_arena *gc);
+char *ncp_get_best_cipher(const cha= r *server_list, const char *peer_info, const char *remote_cipher,
+ str= uct gc_arena *gc);


/**=
@@ -86,8 +83,7 @@
* or allocated via gc.= If no information is available an empty string
* ("= ") is returned.
*/
-const char *
-tls_peer_ncp_list(const char *peer_info, struct gc_arena *gc);
+const char *tls_peer_= ncp_list(const char *peer_info, struct gc_arena *gc);

/**
* Check whether the ciphers in the supp= lied list are supported.
@@ -102,8 +98,7 @@
* is short than MAX_NCP_CIPHERS_LENGTH. NULL
=
* otherwise.
*/-char *
-mutate_ncp_cipher_list(const char *list, st= ruct gc_arena *gc);
+= char *mutate_ncp_cipher_list(const char *list, struct gc_arena *gc);=

/**
* Appends the cipher spe= cified by the ciphernamer parameter to to
@@ -147,17 +142,1= 5 @@
* @param gc gc arena that will be used to= allocate the returned cipher
* @return comm= on cipher if one exist.
*/
-const char *
-get_p2p_ncp_cipher(struct tls_session *session, const char *p= eer_info,
- = struct gc_arena *gc);
+const char *get_p2p_ncp_cipher(struct tls_session *session, const = char *peer_info,
+ = struct gc_arena *gc);
<= br>
/**
* Checks if the cipher is= allowed, otherwise returns false and reset the
* cipher = to the config cipher.
*/
-bool
-check_session_cipher(struct tls_session *session, struct options *optio= ns);
+bool check_sess= ion_cipher(struct tls_session *session, struct options *options);
/**
* Checks for availability o= f Chacha20-Poly1305 and sets
@@ -167,8 +160,7 @@
= * If DEFAULT is in the ncp_cipher string, it will be replaced
* by the default cipher string as defined above.
*/

-void-options_postprocess_setdefault_= ncpciphers(struct options *o);
+void options_postprocess_setdefault_ncpciphers(struct options *o= );

/** returns the o->ncp_ciphers in = brackets, e.g.
* (AES-256-GCM:CHACHA20-POLY1305) if o-&g= t;ncp_ciphers_conf
@@ -176,6 +168,5 @@
*<= /span>
* The returned string will be allocated in the passed \c= gc
*/
-ncp_ex= panded_ciphers(struct options *o, struct gc_arena *gc);
+const char *ncp_expanded_ciphers(struct= options *o, struct gc_arena *gc);
#endif /* ifndef OPENVP= N_SSL_NCP_H */
diff --git a/src/openvpn/ssl_openssl.c b/src= /openvpn/ssl_openssl.c
index 1c1649f..1948d12 100644=
--- a/src/openvpn/ssl_openssl.c
+++ b/src/openvpn= /ssl_openssl.c
@@ -113,7 +113,7 @@
if = (ERR_peek_error() !=3D 0)
{
c= rypto_msg(M_WARN, "Warning: TLS server context initialisation "
- &quo= t;has warnings.");
+ "has warnings.");
= }
}

@@ -131,7 +131,= 7 @@
if (ERR_peek_error() !=3D 0)
= {
crypto_msg(M_WARN, "Warning: TLS client co= ntext initialisation "
- "has warnings.");
+ "has warn= ings.");
}
}

@@ -152,15 +152,13 @@
}

bool
-k= ey_state_export_keying_material(struct tls_session *session,
- con= st char *label, size_t label_size,

+key_state_export_keying_material(struct tls_session *session= , const char *label, size_t label_size,
= void *ekm, size_t ekm_size)

{

SSL *ssl =3D session->key[KS_PRIMARY].ks_ssl.s= sl;

-= if (SSL_export_keying_material(ssl, ekm, ekm_size, label,
- = label_size, NULL, 0, 0) =3D=3D 1)

+ if (SSL_export_keying_material(ssl, ekm, ekm_size, label,= label_size, NULL, 0, 0) =3D=3D 1)
{
= return true;
}
@@ -184,16 +182= ,15 @@
if (where & SSL_CB_LOOP)
= {
dmsg(D_HANDSHAKE_VERBOSE, "SSL state (%s= ): %s",
- = where & SSL_ST_CONNECT ? "connect" :
- where &SSL_ST_ACCEPT ? &q= uot;accept" :
- = "undefined", SSL_state_string_long(s));
+ where & SSL_ST_CON= NECT ? "connect"

+ : where & SSL_ST_ACCEPT ? "accept"
+ = : "undefined",
+ SSL_state_string_long(s));
= }
else if (where & SSL_CB_ALERT)
{

- dmsg(= D_TLS_DEBUG_LOW, "%s %s SSL alert: %s",
- where & SSL_CB_READ ? "Re= ceived" : "Sent",
- SSL_alert_type_string_long(ret),
- SSL_alert_desc_string_long(= ret));
+ dmsg(= D_TLS_DEBUG_LOW, "%s %s SSL alert: %s", where & SSL_CB_READ ?= "Received" : "Sent",
+ SSL_alert_type_string_long(ret), SSL_ale= rt_desc_string_long(ret));
}
}=

@@ -232,7 +229,7 @@
return= TLS_VER_1_2;
#elif defined(TLS1_1_VERSION) || defined(SSL= _OP_NO_TLSv1_1)
return TLS_VER_1_1;
-#else /* if defined(TLS1_3_VERSION) */<= /span>
+#else /* if defined(= TLS1_3_VERSION) */
return TLS_VER_1_0;
#endif

}
@@ -278,10 +275,10 @@ static bool
tls_ctx_set_tls_versions(struct tls_ro= ot_ctx *ctx, unsigned int ssl_flags)
{
- int tls_ver_min =3D openssl_tls_versi= on(
- (ssl_flags= >> SSLF_TLS_VERSION_MIN_SHIFT) & SSLF_TLS_VERSION_MIN_MASK);
- int tls_ver_max =3D o= penssl_tls_version(
- = (ssl_flags >> SSLF_TLS_VERSION_MAX_SHIFT) & SSLF_TLS_VERSIO= N_MAX_MASK);
+ int= tls_ver_min =3D
+ = openssl_tls_version((ssl_flags >> SSLF_TLS_VERSION_MIN_SHIFT) &a= mp; SSLF_TLS_VERSION_MIN_MASK);
+ int tls_ver_max =3D
+ openssl_tls_version((ssl_flags >> SSLF_TLS_VE= RSION_MAX_SHIFT) & SSLF_TLS_VERSION_MAX_MASK);
=
if (!tls_ver_min)
{
@@ = -372,7 +369,8 @@
for (; begin_of_cipher < strlen(ci= phers); begin_of_cipher =3D end_of_cipher)
{ end_of_cipher +=3D strcspn(&ciphers[begin_of_cipher], &= quot;:");
- = cipher_pair =3D tls_get_cipher_name_pair(&ciphers[begin_of_cipher], en= d_of_cipher - begin_of_cipher);
+ cipher_pair =3D
+ tls_get_cipher_name_pair(&ciphers[begin_of_= cipher], end_of_cipher - begin_of_cipher);

if (NULL =3D=3D cipher_pair)

{@@ -393,11 +391,13 @@
current_cipher_l= en =3D strlen(current_cipher);

= if (end_of_cipher - begin_of_cipher =3D=3D current_cipher_len
= - && 0 != =3D memcmp(&ciphers[begin_of_cipher], cipher_pair->iana_name,=
- = end_of_cipher - begin_of_cipher))
+ && 0
+ !=3D memcmp(&ciphers[b= egin_of_cipher], cipher_pair->iana_name,
+ end_of_cipher - be= gin_of_cipher))
{
= /* Non-IANA name used, show warning */
- msg(M_WARN, "Deprecated TLS ciph= er name '%s', please use IANA name '%s'", cipher_pair-= >openssl_name, cipher_pair->iana_name);
+ msg(M_WARN, "Deprecated TLS = cipher name '%s', please use IANA name '%s'",+ cipher_p= air->openssl_name, cipher_pair->iana_name);
= }
}

@@ -405,= 8 +405,7 @@
if ((SIZE_MAX - openssl_ciphers_len) &= lt; current_cipher_len
|| (len - 1) < (open= ssl_ciphers_len + current_cipher_len))
{- msg(M_FATAL,=
- "Failed= to set restricted TLS cipher list, too long (>%d).",
+ msg(M_FATAL, "Fa= iled to set restricted TLS cipher list, too long (>%d).",
(int)(len - 1));
}<= br>
@@ -421,7 +420,7 @@

= if (openssl_ciphers_len > 0)
{- openssl_ciphers[openssl= _ciphers_len-1] =3D '\0';
+ openssl_ciphers[openssl_ciphers_len - 1] =3D '\0&= #39;;
}
}
@@ -431,17 +430,18 @@
if (ciphers =3D=3D NULL)<= /span>
{
/* Use sane default TLS cip= her list */
- if= (!SSL_CTX_set_cipher_list(ctx->ctx,
- /* Use openssl's= default list as a basis */
- "DEFAULT"
- = /* Disable export ciphers and openssl's 'low' and 'mediu= m' ciphers */

- = ":!EXP:!LOW:!MEDIUM"
<= span style=3D"color: hsl(0, 100%, 40%);">- = /* Disable static (EC)DH keys (no forward secrecy) */

- &q= uot;:!kDH:!kECDH"
= - /* Disable DSA private keys */=
- = ":!DSS"
- /* Disable unsupported TLS modes = */
- = ":!PSK:!SRP:!kRSA"))
+ if (!SSL_CTX_set_cipher_list(+ ctx->ctx,=
+ /* = Use openssl's default list as a basis */
+ "DEFAULT"
+ /* Disable export = ciphers and openssl's 'low' and 'medium' ciphers */
+ ":= !EXP:!LOW:!MEDIUM"
+ /* Disable static (EC)DH keys (no forward secrecy) */
+ "= ;:!kDH:!kECDH"
+= /* Disable DSA private keys */
+ ":!DSS"
+ /* Disable unsuppo= rted TLS modes */

+ = ":!PSK:!SRP:!kRSA"))
{
crypto_msg(M_FATAL, "Failed to set default T= LS cipher list.");
}
@@ -461,= 8 +461,7 @@
}

static vo= id
-convert_tls13_list_= to_openssl(char *openssl_ciphers, size_t len,
- const char *ciphers)<= /span>
+convert_tls13_list_t= o_openssl(char *openssl_ciphers, size_t len, const char *ciphers) {
/*
* OpenSSL (and offi= cial IANA) cipher names have _ in them. We
@@ -471,9 +470,8= @@
*/
if (strlen(ciphers) >= =3D (len - 1))
{
- msg(M_FATAL,
- "Failed to set restricted TLS 1.3 cipher li= st, too long (>%d).",
- (int) (len - 1));
+ msg(M_FATAL, "Failed to set restricted TLS 1= .3 cipher list, too long (>%d).",
+ (int)(len - 1));
}

strncpy(openssl_ciphers, ciphers, len= );
@@ -498,20 +496,19 @@
}
<= span>

#if !defined(TLS1_3_VERSION)
- crypto_msg(M_WARN, "Not compiled w= ith OpenSSL 1.1.1 or higher. "
+ crypto_msg(M_WARN,
+ "Not compiled with OpenSSL 1.1.1 or = higher. "
"Ignoring TLS 1.3 only = tls-ciphersuites '%s' setting.",
= ciphers);
#else
ASSERT(NULL !=3D c= tx);

char openssl_ciphers[4096];
- convert_tls13_list_to= _openssl(openssl_ciphers, sizeof(openssl_ciphers),
- ciphers);
+ convert_tls13_list= _to_openssl(openssl_ciphers, sizeof(openssl_ciphers), ciphers);
<= span>

if (!SSL_CTX_set_ciphersuites(ctx->ctx, open= ssl_ciphers))
{
- crypto_msg(M_FATAL, "Failed to set restricted T= LS 1.3 cipher list: %s",
- openssl_ciphers);
+ crypto_msg(M_FATAL, "Failed to set re= stricted TLS 1.3 cipher list: %s", openssl_ciphers);
= }
#endif
}
@@ -520,7 = +517,7 @@
tls_ctx_set_cert_profile(struct tls_root_ctx *ct= x, const char *profile)
{
#if OPENSSL_VER= SION_NUMBER > 0x10100000L \
- && (!defined(LIBRESSL_VERSION_NUMBER) || LIBRESSL_VERS= ION_NUMBER > 0x3060000fL)
+ && (!defined(LIBRESSL_VERSION_NUMBER) || LIBRESSL_VER= SION_NUMBER > 0x3060000fL)
/* OpenSSL does not have= certificate profiles, but a complex set of
* callbac= ks that we could try to implement to achieve something similar.
<= span> * For now, use OpenSSL's security levels to achieve similar = (but not equal)

@@ -549,8 +546,10 @@
#else= /* if OPENSSL_VERSION_NUMBER > 0x10100000L */
if = (profile)
{
- msg(M_WARN, "WARNING: OpenSSL 1.1.0 and LibreSSL do= not support "
- = "--tls-cert-profile, ignoring user-set profile: '%s'= ", profile);
+ = msg(M_WARN,
+ = "WARNING: OpenSSL 1.1.0 and LibreSSL do not support "
+ "--t= ls-cert-profile, ignoring user-set profile: '%s'",
<= span style=3D"color: hsl(120, 100%, 40%);">+ profile);
}
#endif /* if OPENSSL_VERSION_NUMBER > 0x1= 0100000L */
}
@@ -602,15 +601,13 @@=

if (!SSL_CTX_set1_groups(ctx->ctx, glis= t, glistlen))
{
- crypto_msg(M_FATAL, "Failed to set allowed TLS = group list: %s",
-= groups);
+ crypto_msg(M_FATAL, "Failed to set allowed TLS group l= ist: %s", groups);
}
gc_free= (&gc);
#else /* if OPENSSL_VERSION_NUMBER < 0x3000= 0000L */
if (!SSL_CTX_set1_groups_list(ctx->ctx, gr= oups))
{
- crypto_msg(M_FATAL, "Failed to set allowed TLS group l= ist: %s",
- = groups);
= + crypto_msg(M_FATAL, "Failed to set allowed TLS group list: %s= ", groups);
}
#endif /* if OPENS= SL_VERSION_NUMBER < 0x30000000L */
}
@@= -652,8 +649,7 @@
}

voi= d
-tls_ctx_load_dh_para= ms(struct tls_root_ctx *ctx, const char *dh_file,
- bool dh_file_inline)
+tls_ctx_load_dh_params(= struct tls_root_ctx *ctx, const char *dh_file, bool dh_file_inline)<= br> {
BIO *bio;

@@ -689,8 +685,7 @@

crypto_msg(M_FATAL, "SS= L_CTX_set0_tmp_dh_pkey");
}

- msg(D_TLS_DEBUG_LOW, = "Diffie-Hellman initialized with %d bit key",
- 8 * EVP_PKEY_get_size(dh));
+ msg(D_TLS_DEBUG_LOW, = "Diffie-Hellman initialized with %d bit key", 8 * EVP_PKEY_get_si= ze(dh));
#else /* if OPENSSL_VERSION_NUMBER >=3D 0x300= 00000L */
DH *dh =3D PEM_read_bio_DHparams(bio, NULL, = NULL, NULL);
BIO_free(bio);
@@ -705,8 = +700,7 @@
crypto_msg(M_FATAL, "SSL_CTX_set_tm= p_dh");
}

- msg(D_TLS_DEBUG_LOW, "Diffie-Hellm= an initialized with %d bit key",
- 8 * DH_size(dh));
+ msg(D_TLS_DEBUG_LOW, "Diffie-Hellman initial= ized with %d bit key", 8 * DH_size(dh));

<= span> DH_free(dh);

#endif /* if OPENSSL_VERSION_NUMBER= >=3D 0x30000000L */
@@ -719,8 +713,8 @@
if (curve_name !=3D NULL)

{
= msg(M_WARN, "WARNING: OpenSSL 3.0+ builds do not support specifyi= ng an "
- = "ECDH curve with --ecdh-curve, using default curves. Use "
- "--tls-g= roups to specify groups.");
+ "ECDH curve with --ecdh-curve, using = default curves. Use "
+ "--tls-groups to specify groups.");
}
#elif !defined(OPENSSL_NO_EC)<= br> int nid =3D NID_undef;
@@ -753,10 +747,9 @@
{
/* Creating key failed, fall= back on sane default */
ecdh =3D EC_KEY_new_by_cu= rve_name(NID_secp384r1);
- "e= xtract curve from certificate" : "use supplied curve";
- msg(D_TLS_DEBUG_LOW= ,
- "Fa= iled to %s (%s), using secp384r1 instead.", source, sname);
= + const char *source =3D=
+ (NULL = =3D=3D curve_name) ? "extract curve from certificate" : "use= supplied curve";
- " Skipping ECDH p= arameter loading.");
+ " Skipping ECDH parameter loading.");=
#endif /* OPENSSL_NO_EC */
}
<= /span>
@@ -794,7 +787,8 @@
{
struct user_pass up;

CLEAR(up= );
- get_use= r_pass(&up, NULL, "PKCS#11 token", GET_USER_PASS_MANAGEMENT|G= ET_USER_PASS_PASSWORD_ONLY);
+ get_user_pass(&up, NULL, "PKCS#11 token"= ,
+ = GET_USER_PASS_MANAGEMENT | GET_USER_PASS_PASSWORD_ONLY);
= UI_set_result(ui, uis, up.password);
= purge_user_pass(&up, true);
}=
@@ -845,12 +839,11 @@
{
= return NULL;
}
- pkey =3D PEM_read_bio_PrivateKey(in, NULL,- = SSL_CTX_get_default_passwd_cb(ssl_ctx),
+ pkey =3D PEM_read_bio_PrivateKey(in, NULL, SSL_= CTX_get_default_passwd_cb(ssl_ctx),
= SSL_CTX_get_default_passwd_cb_userdata(ssl_ctx));
BIO_free(in);


-#else /* defined(HAVE_OPENSSL_STORE_API) */
+#else /* defined(HAVE_OPENSSL_S= TORE_API) */


OSSL_STORE_CTX *store_c= tx =3D NULL;
OSSL_STORE_INFO *info =3D NULL;@@ -863,8 +856,7 @@
}
UI_m= ethod_set_reader(ui_method, ui_reader);

- store_ctx =3D OSSL_STORE_open_ex(ur= i, tls_libctx, NULL, ui_method, ssl_ctx,
- NULL, NULL, NULL);
+ store_ctx =3D OSSL= _STORE_open_ex(uri, tls_libctx, NULL, ui_method, ssl_ctx, NULL, NULL, NULL)= ;
if (!store_ctx)
{
goto end;

@@ -904,8 +896,8 @@
= }

int
-tls_ctx_load_pkcs12(struct tls_root_ctx *ctx, const char= *pkcs12_file,
- = bool pkcs12_file_inline, bool load_ca_file)
+tls_ctx_load_pkcs12(struct tls_root_ct= x *ctx, const char *pkcs12_file, bool pkcs12_file_inline,
+ bool load_ca_file= )
{
FILE *fp;
EV= P_PKEY *pkey;
@@ -920,8 +912,7 @@
if (= pkcs12_file_inline)
{
BIO *b6= 4 =3D BIO_new(BIO_f_base64());
- BIO *bio =3D BIO_new_mem_buf((void *) pkcs12_file,<= br>- = (int) strlen(pkcs12_file));
+ BIO *bio =3D BIO_new_mem_buf((void *)pkcs12_file, (in= t)strlen(pkcs12_file));
ASSERT(b64 && bio)= ;
BIO_push(b64, bio);
p12= =3D d2i_PKCS12_bio(b64, NULL);
@@ -956,7 +947,7 @@<= br> if (!PKCS12_parse(p12, password, &pkey, &cert, &a= mp;ca))
{
crypto_msg(= M_WARN, "Decoding PKCS12 failed. Probably wrong password "=
- "= ;or unsupported/legacy encryption");
+ "or unsupported/l= egacy encryption");
#ifdef ENABLE_MANAGEMENT if (management && (ERR_GET_REASON(ERR_peek_err= or()) =3D=3D PKCS12_R_MAC_VERIFY_FAILURE))
{
@@ -1002,11 +993,13 @@
X509= _STORE *cert_store =3D SSL_CTX_get_cert_store(ctx->ctx);
if (!X509_STORE_add_cert(cert_store, sk_X509_value(ca, i)= ))

{
- crypto_msg(M_FATAL, "Cannot add ce= rtificate to certificate chain (X509_STORE_add_cert)");
+ crypto_msg(M_F= ATAL,

+ = "Cannot add certificate to certificate chain (X509_ST= ORE_add_cert)");
}
= if (!SSL_CTX_add_client_CA(ctx->ctx, sk_X509_value(ca, i)= ))
{
- crypto_msg(M_FATAL, "Cannot add ce= rtificate to client CA list (SSL_CTX_add_client_CA)");
+ crypto_msg(M_FA= TAL,

+ = "Cannot add certificate to client CA list (SSL_CTX_add= _client_CA)");
}
= }
}
@@ -1024,7 +1017,9 @@=
{
if (!SSL_C= TX_add_extra_chain_cert(ctx->ctx, sk_X509_value(ca, i)))
{

- = crypto_msg(M_FATAL, "Cannot add extra certificate to= chain (SSL_CTX_add_extra_chain_cert)");
+ crypto_msg(
+ M_FATAL,

+ = "Cannot add extra certificate to chain (SSL_CTX_add_extra_chain_cert)&= quot;);
}
}
}
@@ -1041,7 +1036,8 @@
<= span> /* Load Certificate and Private Key */

if (!= SSL_CTX_use_CryptoAPI_certificate(ctx->ctx, cryptoapi_cert))
<= span> {

- cr= ypto_msg(M_FATAL, "Cannot load certificate \"%s\" from Micro= soft Certificate Store", cryptoapi_cert);
+ crypto_msg(M_FATAL, "Cannot load ce= rtificate \"%s\" from Microsoft Certificate Store",+ cryptoapi= _cert);
}
}
#endif /= * ENABLE_CRYPTOAPI */
@@ -1059,8 +1055,7 @@
* is found in the buffer. If loading more certificates is<= /span>
* optional, break without raising an error
*/
- if (optional
- && ERR_GET_REASON(ERR_peek_error()) = =3D=3D PEM_R_NO_START_LINE)
+ if (optional && ERR_GET_REASON(ERR_peek_error()= ) =3D=3D PEM_R_NO_START_LINE)
{
/* remove that error from error stack */

(void)ERR_get_error();

@@ -1109,8 +1104,8= @@
}
UI_method_set_reader(ui_met= hod, ui_reader);

- store_ctx =3D OSSL_STORE_open_ex(uri, tls_libctx, NULL, ui= _method, tls_ctx->ctx,
- NULL, NULL, NULL);
+ store_ctx =3D
+ OSSL_STORE_open_ex(uri, tls_lib= ctx, NULL, ui_method, tls_ctx->ctx, NULL, NULL, NULL);
= if (!store_ctx)
{
goto en= d;
@@ -1187,14 +1182,13 @@
UI_destroy_= method(ui_method);
OSSL_STORE_INFO_free(info);<= br> OSSL_STORE_close(store_ctx);
-#else /* defined(HAVE_OPENSSL_STORE_API */
<= span style=3D"color: hsl(120, 100%, 40%);">+#else /* defined(HAVE_OPENSSL_= STORE_API */

ASSERT(0);
#endif /* def= ined(HAVE_OPENSSL_STORE_API */
}
<= br> static void
-= tls_ctx_load_cert_pem_file(struct tls_root_ctx *ctx, const char *cert_file,=
- = bool cert_file_inline)
+tls_ctx_load_cert_pem_file(struct tls_root_ctx *ctx, const char *c= ert_file, bool cert_file_inline)
{
BI= O *in =3D NULL;
X509 *x =3D NULL;
@@ -= 1204,11 +1198,11 @@

if (cert_file_in= line)
{
- in =3D BIO_new_mem_buf((char *) cert_file, -1);
+ in =3D BIO_new_mem_buf((= char *)cert_file, -1);

}
else
{
- = in =3D BIO_new_file((char *) cert_file, "r");
+ in =3D BIO_new_file((char= *)cert_file, "r");

}

if (in =3D=3D NULL)
@@ -1217,8 +1211,7 @@<= /span>
goto end;
}
=
- x =3D PEM_read_bi= o_X509(in, NULL,
- = SSL_CTX_get_default_passwd_cb(ctx->ctx),
= + x =3D PEM_read_bio_X509(in= , NULL, SSL_CTX_get_default_passwd_cb(ctx->ctx),
= SSL_CTX_get_default_passwd_cb_userdata(ctx->ctx));
if (x =3D=3D NULL)
{
@@ -1255,8 +1248,7 @@

}

void

-tls_ctx_load_= cert_file(struct tls_root_ctx *ctx, const char *cert_file,
- bool cert_file_= inline)
+tls_ctx_load= _cert_file(struct tls_root_ctx *ctx, const char *cert_file, bool cert_file_= inline)
{
if (cert_uri_supported() &a= mp;& !cert_file_inline)
{
@@ -1283= ,13 +1275,12 @@

if (priv_key_file_in= line)
{
- in =3D BIO_new_mem_buf((char *) priv_key_file, -1);+ in =3D BIO_new_mem_b= uf((char *)priv_key_file, -1);
if (in =3D=3D NULL)=
{
goto end; }
- = pkey =3D PEM_read_bio_PrivateKey(in, NULL,
- SSL_CTX_ge= t_default_passwd_cb(ctx->ctx),
+ pkey =3D PEM_read_bio_PrivateKey(in, NULL, SSL_CTX_ge= t_default_passwd_cb(ctx->ctx),
= SSL_CTX_get_default_passwd_cb_userdata(ctx->ctx));=
}
else
@@ -1324,8 +1315= ,7 @@
}

void
= -backend_tls_ctx_reload_crl(struc= t tls_root_ctx *ssl_ctx, const char *crl_file,
- bool crl_inline)=
+backend_tls_ctx_reload_crl= (struct tls_root_ctx *ssl_ctx, const char *crl_file, bool crl_inline)
{
BIO *in =3D NULL;

@@ -1354,7 +1344,7 @@

if= (crl_inline)
{
- in =3D BIO_new_mem_buf((char *) crl_file, -1);
+ in =3D BIO_new_me= m_buf((char *)crl_file, -1);
}
el= se
{
@@ -1363,8 +1353,7 @@
<= span>

if (in =3D=3D NULL)
{
- msg(M_WARN, "= CRL: cannot read: %s",
- print_key_filename(crl_file, crl_inline));
+ msg(M_WARN, "CRL: can= not read: %s", print_key_filename(crl_file, crl_inline));

goto end;

}

<= span>@@ -1477,9 +1466,8 @@

* @return signatu= re length or -1 on error.
*/
static int<= /span>
-get_sig_from_man(const= unsigned char *dgst, unsigned int dgstlen,
- unsigned char *sig, unsigned int sig= len,
- = const char *algorithm)
+ = unsigned int siglen, const char *algorithm)
{
char *in_b64 =3D NULL;
char *out_b= 64 =3D NULL;
@@ -1490,7 +1478,6 @@
if = (management && bencret > 0)
{
out_b64 =3D management_query_pk_sig(management, in_b64, algorit= hm);

-
= }
if (out_b64)
{
<= span>@@ -1504,8 +1491,7 @@


/* sign arbit= rary data */
static int
-rsa_priv_enc(int flen, const unsigned char *from, unsign= ed char *to, RSA *rsa,
= - int padding)
+rsa_priv_enc(int flen, const unsigned char *from, unsigned char *to,= RSA *rsa, int padding)
{
unsigned in= t len =3D RSA_size(rsa);
int ret =3D -1;
@@ -1533,8 +1519,7 @@

ASSERT(NULL !=3D pub_rsa);

/* allocate custom RSA method object *= /
- rsa_meth =3D RSA= _meth_new("OpenVPN external private key RSA Method",
- RSA_ME= THOD_FLAG_NO_CHECK);

= + rsa_meth =3D RSA_meth_new("OpenVPN external private key RSA Metho= d", RSA_METHOD_FLAG_NO_CHECK);
check_malloc_retur= n(rsa_meth);
RSA_meth_set_pub_enc(rsa_meth, rsa_pub_en= c);
RSA_meth_set_pub_dec(rsa_meth, rsa_pub_dec);
@@ -1594,7 +1579,7 @@
{
/*= release the method structure */
const EC_KEY_METHOD *= ec_meth =3D EC_KEY_get_method(ec);
- EC_KEY_METHOD_free((EC_KEY_METHOD *) ec_meth);
<= span style=3D"color: hsl(120, 100%, 40%);">+ EC_KEY_METHOD_free((EC_KEY_= METHOD *)ec_meth);

}

/*= EC_KEY_METHOD callback: sign().
@@ -1633,8 +1618,8 @@
* struct or NULL on error.
*/
static ECDSA_SIG *

= -ecdsa_sign_sig(const unsigned char *dgst, int dgstlen, const BIGNUM *in_ki= nv,
- con= st BIGNUM *in_r, EC_KEY *ec)
+ecdsa_sign_sig(const unsigned char *dgst, int dgstlen, const BIGNU= M *in_kinv, const BIGNUM *in_r,
+ EC_KEY *ec)
{
= ECDSA_SIG *ecsig =3D NULL;
unsigned int len =3D EC= DSA_size(ec);
@@ -1732,8 +1717,7 @@

#ifdef HAVE_XKEY_PROVIDER
EVP_PKEY *privke= y =3D xkey_load_management_key(tls_libctx, pkey);
- if (!privkey
- || !SSL_CTX_use_PrivateKey(ctx->ctx, priv= key))
+ if (!privk= ey || !SSL_CTX_use_PrivateKey(ctx->ctx, privkey))
{=
EVP_PKEY_free(privkey);
= goto cleanup;
@@ -1742,7 +1726,7 @@
#else = /* ifdef HAVE_XKEY_PROVIDER */
#if OPENSSL_VERSION_NUMBER= < 0x30000000L
if (EVP_PKEY_id(pkey) =3D=3D EVP_PKE= Y_RSA)
-#else /* OPENSS= L_VERSION_NUMBER < 0x30000000L */
+#else /* OPENSSL_VERSION_NUMBER < 0x30000000L */
if (EVP_PKEY_is_a(pkey, "RSA"))
= #endif /* OPENSSL_VERSION_NUMBER < 0x30000000L */
{=
@@ -1754,7 +1738,7 @@
#if !defined(OPENSS= L_NO_EC)
#if OPENSSL_VERSION_NUMBER < 0x30000000L
else if (EVP_PKEY_id(pkey) =3D=3D EVP_PKEY_EC)
-#else /* OPENSSL_VERSION_NUMBER &l= t; 0x30000000L */

+#e= lse /* OPENSSL_VERSION_NUMBER < 0x30000000L */
els= e if (EVP_PKEY_is_a(pkey, "EC"))
#endif /* OPENS= SL_VERSION_NUMBER < 0x30000000L */
{
@@ -1796,8 +1780,8 @@

}

void

-tls_ctx_load_c= a(struct tls_root_ctx *ctx, const char *ca_file,
- bool ca_file_inline, const char = *ca_path, bool tls_server)
+tls_ctx_load_ca(struct tls_root_ctx *ctx, const char *ca_file, bool = ca_file_inline,
+ = const char *ca_path, bool tls_server)
{=
STACK_OF(X509_INFO) *info_stack =3D NULL;
= STACK_OF(X509_NAME) *cert_names =3D NULL;
@@ -1892,8 +18= 76,7 @@
{
= crypto_msg(M_WARN,
= "Cannot load CA certificate file %s (entry %d did not validat= e)",
- = print_key_filename(ca_file, ca_file_inline),<= br>- = added);
+ = print_key_filename(ca_file, ca_file_inline), a= dded);
}
= prev =3D cnum;
}
@= @ -1909,8 +1892,7 @@

if (!added)=
{
- crypto_msg(M_FATAL,
- "Cannot load CA certificate fil= e %s (no entries were read)",
+ crypto_msg(M_FATAL, "Cannot load CA certifi= cate file %s (no entries were read)",
= print_key_filename(ca_file, ca_file_inline));
= }

@@ -1918,10 +1900,10 @@
<= span> {

if (cnum !=3D added) {
-= crypto_msg(M_FATAL, "Cannot load CA certificate file %= s (only %d "
+ = crypto_msg(M_FATAL,
+ "Cannot load CA certificate f= ile %s (only %d "
"of= %d entries were valid X509 names)",
- print_key_filename(ca_file, = ca_file_inline), cnum,
= - added);
+ print_key_filename(ca_file, ca_f= ile_inline), cnum, added);
}
= }

@@ -1961,9 +1943,7 @@ if (in =3D=3D NULL)
{
= crypto_msg(M_FATAL, "Cannot load extra-certs file: %s",
- print_k= ey_filename(extra_certs_file,
- extra_certs_file_inline));
-
+ print_key_filename(ext= ra_certs_file, extra_certs_file_inline));
}
= else
{
@@ -1988,10 +1968,10= @@

#warning BIO_DEBUG defined
-static FILE *= biofp; /* GLOBAL */
-static bool biofp_toggle; /* = GLOBAL */
-static time_= t biofp_last_open; /* GLOBAL */
-static const int biofp_reopen_interval =3D 600; = /* GLOBAL */
+static = FILE *biofp; /* GLOBAL */
+static bool biofp_toggle; = /* GLOBAL */
+st= atic time_t biofp_last_open; /* GLOBAL */
+static const int biofp_reopen_interval= =3D 600; /* GLOBAL */

static void
close_biofp(void)
@@ -2031,8 +2011,8 @@<= br> if (len > 0)
{
= open_biofp();
- = fprintf(biofp, "BIO_%s %s time=3D%" PRIi64 " bio=3D"= ptr_format " len=3D%d data=3D%s\n",
- mode, desc, (int64_t)time(NULL), (= ptr_type)bio, len, format_hex(buf, len, 0, &gc));
+ fprintf(biofp, "BIO_%s %s ti= me=3D%" PRIi64 " bio=3D" ptr_format " len=3D%d data=3D%= s\n", mode, desc,
- fprintf(biofp, "BIO %s time=3D%" PRI= i64 " bio=3D" ptr_format "\n",
- mode, (int64_t)time(NULL), (ptr_ty= pe)bio);
+ fprintf= (biofp, "BIO %s time=3D%" PRIi64 " bio=3D" ptr_format &= quot;\n", mode, (int64_t)time(NULL),
+ (ptr_type)bio);
fflu= sh(biofp);
}

@@ -2082,13= +2062,12 @@
}
else if (i= !=3D size)
{
- crypto_msg(D_TLS_ERRORS, "TLS ERROR: BIO = write %s incomplete %d/%d",
- desc, i, size);
+ crypto_msg(D_TLS_ERRORS, "TL= S ERROR: BIO write %s incomplete %d/%d", desc, i, size);
ret =3D -1;

ERR_clear_error();=
}
else
- { /* succ= essful write */
+ = { /* successful write */
dmsg(D_HANDSHAKE_= VERBOSE, "BIO write %s %d bytes", desc, i);
= ret =3D 1;
}
@@ -2104,9 +2= 083,9 @@
static void
bio_write_post(const= int status, struct buffer *buf)
{
- if (status =3D=3D 1) /* success status = return from bio_write? */
+ if (status =3D=3D 1) /* success status return= from bio_write? */
{
- memset(BPTR(buf), 0, BLEN(buf)); /* erase dat= a just written */
+ = memset(BPTR(buf), 0, BLEN(buf)); /* erase data just written */=
buf->len =3D 0;
}
}

@@ -2132,7 +2111,7 @@
*/<= br> int i =3D BIO_read(bio, BPTR(buf), len);

- VALGRIND_MAKE_READAB= LE((void *) &i, sizeof(i));
+ VALGRIND_MAKE_READABLE((void *)&i, sizeof(i));
#ifdef BIO_DEBUG
bio_debug_= data("read", bio, BPTR(buf), i, desc);
@@ -2154,1= 7 +2133,18 @@
buf->len =3D 0;
= }
else
- { /* successful read */
+ { /* successful read */
<= br> dmsg(D_HANDSHAKE_VERBOSE, "BIO read %s %d bytes"= ;, desc, i);
buf->len =3D i;
= ret =3D 1;
- = VALGRIND_MAKE_READABLE((void *) BPTR(buf), BLEN(buf));
+ VALGRIND_MAKE_READABLE((void= *)BPTR(buf), BLEN(buf));
}
retur= n ret;
}

void-key_state_ssl_init(struct key_s= tate_ssl *ks_ssl, const struct tls_root_ctx *ssl_ctx, bool is_server, struc= t tls_session *session)
+key_state_ssl_init(struct key_state_ssl *ks_ssl, const struct tls_root_= ctx *ssl_ctx, bool is_server,
+ struct tls_session *session)
= {
ASSERT(NULL !=3D ssl_ctx);
ASSE= RT(ks_ssl);
@@ -2232,8 +2212,7 @@
<= br> ASSERT(NULL !=3D ks_ssl);

- ret =3D bio_write(ks_ssl->ssl_bi= o, BPTR(buf), BLEN(buf),
+ ret =3D bio_write(ks_ssl->ssl_b= io, BPTR(buf), BLEN(buf), "tls_write_plaintext");
bio_write_post(ret, buf);


perf= _pop();
@@ -2337,7 +2316,7 @@
type= =3D OBJ_nid2sn(typeid);

/* Open= SSL reports rsaEncryption, dsaEncryption and
- * id-ecPublicKey, map these values to nicer = ones */
+ * i= d-ecPublicKey, map these values to nicer ones */
i= f (typeid =3D=3D EVP_PKEY_RSA)
{
= type =3D "RSA";
@@ -2355,7 +2334,7 @@=
{
type =3D "unk= nown type";
}
-#else /* OpenSSL >=3D 3 */
+#else /* OpenSSL >=3D 3 */
= type =3D EVP_PKEY_get0_type_name(pkey);
= if (type =3D=3D NULL)
{
@@ -2= 364,8 +2343,7 @@
#endif /* if OPENSSL_VERSION_NUMBER < = 0x30000000L */
}

- snprintf(buf, buflen, "%d bits %= s%s",
- = EVP_PKEY_bits(pkey), type, curve);
+ snprintf(buf, buflen, "%d bits %s%s", EVP_PK= EY_bits(pkey), type, curve);
}
/**
@@ -2385,12 +2363,10 @@
in= t signature_nid =3D X509_get_signature_nid(cert);
if (= signature_nid !=3D 0)
{
- snprintf(sig, sizeof(sig), ", signature= : %s",
- = OBJ_nid2sn(signature_nid));
+ snprintf(sig, sizeof(sig), ", signature: %s&quo= t;, OBJ_nid2sn(signature_nid));
}

- snprintf(buf, buflen= , ", peer certificate: %s%s",
- pkeybuf, sig);
+ snprintf(buf, buflen, ", peer certificat= e: %s%s", pkeybuf, sig);

EVP_PK= EY_free(pkey);
}
@@ -2408,8 +2384,7 @@
char pkeybuf[128] =3D { 0 };
print_p= key_details(pkey, pkeybuf, sizeof(pkeybuf));

- snprintf(buf, buflen, ", = peer temporary key: %s",

- pkeybuf);
+ snprintf(buf, buflen, ", peer temporary key: %s", = pkeybuf);

EVP_PKEY_free(pkey);
}
@@ -2471,8 +2446,7 @@
||= (defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER >= =3D 0x3090000fL)
/* LibreSSL 3.7.x and 3.8.x implement= this function but do not export it
* and fail linkin= g with an unresolved symbol */
- if (SSL_get_peer_signature_type_nid(ssl, &peer_sig_type_ni= d)
- && = peer_sig_type_nid !=3D NID_undef)
+ if (SSL_get_peer_signature_type_nid(ssl, &peer_sig_ty= pe_nid) && peer_sig_type_nid !=3D NID_undef)
{=
peer_sig_type =3D get_sigtype(peer_sig_type_nid);=
}
@@ -2483,8 +2457,7 @@
return;

}

- snprintf(buf, buflen, ", pe= er signing digest/type: %s %s",

- peer_sig, peer_sig_type);
+ snprintf(buf, buflen, ", peer si= gning digest/type: %s %s", peer_sig, peer_sig_type);
= }

#if OPENSSL_VERSION_NUMBER >=3D 0x3= 0000000L
@@ -2522,11 +2495,8 @@
s1[0] =3D s2[0] =3D s3[0] =3D s4[0] =3D s5[0] =3D 0;
= ciph =3D SSL_get_current_cipher(ks_ssl->ssl);
- snprintf(s1, sizeof(s1), "%s= %s, cipher %s %s",

- SSL_get_version(ks_ssl->ssl),
- SSL_CIPHER_get_version(ciph),=
- SSL_CIPHER_get_= name(ciph));
+ snp= rintf(s1, sizeof(s1), "%s %s, cipher %s %s", prefix, SSL_get_vers= ion(ks_ssl->ssl),
= + SSL_CIPHER_get_version(ciph), SSL_CIPHER_get_name(ciph));
X509 *cert =3D SSL_get_peer_certificate(ks_ssl->ssl);<= /span>

if (cert)
@@ -2544,9= +2514,7 @@
}

void
-show_available_tls_ciphers= _list(const char *cipher_list,
- const char *tls_cert_profile,
- = bool tls13)
+sh= ow_available_tls_ciphers_list(const char *cipher_list, const char *tls_cert= _profile, bool tls13)
{
struct tls_ro= ot_ctx tls_ctx;

@@ -2559,8 +2527,7 @@
#if defined(TLS1_3_VERSION)
if (tls13)
{
-= SSL_CTX_set_min_proto_version(tls_ctx.ctx,
- openssl_= tls_version(TLS_VER_1_3));
+ SSL_CTX_set_min_proto_version(tls_ctx.ctx, openssl_tls_versi= on(TLS_VER_1_3));
tls_ctx_restrict_ciphers_tls13(&= amp;tls_ctx, cipher_list);
}
else=
@@ -2599,8 +2566,7 @@
else if (NU= LL =3D=3D pair)
{
/* = No translation found, print warning */
- printf("%s (No IANA name known to OpenVPN= , use OpenSSL name.)\n",
- cipher_name);
+ printf("%s (No IANA name known to Ope= nVPN, use OpenSSL name.)\n", cipher_name);
}<= /span>
else
{
@@= -2638,7 +2604,7 @@
for (n =3D 0; n < crv_len; = n++)
{
const char *sn= ame;
- sname= =3D OBJ_nid2sn(curves[n].nid);
+ sname =3D OBJ_nid2sn(curves[n].nid);
if (sname =3D=3D NULL)

{
sname =3D "";
@@ -26= 54,7 +2620,7 @@
free(curves);
#else = /* ifndef OPENSSL_NO_EC */
msg(M_WARN, "Your Open= SSL library was built without elliptic curve support. "
- "No curves available.&q= uot;);

+ = "No curves available.");
#endif /* ifndef OPE= NSSL_NO_EC */
}

@@ -2678= ,7 +2644,7 @@
static int
provider_unload(= OSSL_PROVIDER *prov, void *unused)
{
- (void) unused;
+ (void)unused;
OSSL_= PROVIDER_unload(prov);
return 1;
}
@@ -2716,7 +2682,7 @@
if (!OSSL_PROV= IDER_load(tls_libctx, "ovpn.xkey"))
{
msg(M_NONFATAL, "ERROR: failed loading exte= rnal key provider: "
- "Signing with external keys will not work.");=
+ = "Signing with external keys will not work.");
= }
}

d= iff --git a/src/openvpn/ssl_openssl.h b/src/openvpn/ssl_openssl.hindex 966bb44..08a3d53 100644
--- a/src/openvpn/ssl_= openssl.h
+++ b/src/openvpn/ssl_openssl.h
@= @ -36,17 +36,19 @@
* Structure that wraps the TLS context= . Contents differ depending on the
* SSL library used.
*/
-str= uct tls_root_ctx {
+s= truct tls_root_ctx
+{=
SSL_CTX *ctx;
time_t crl_last_mt= ime;
off_t crl_last_size;
};
-struct key_s= tate_ssl {
- SSL *ss= l; /* SSL object -- new obj created for each new key */
- BIO *ssl_bio; = /* read/write plaintext from here */
- BIO *ct_in; /* write ci= phertext to here */
- = BIO *ct_out; /* read ciphertext from here */
+struct key_state_ssl
+{
+ SSL *ssl; /* SSL object -- new ob= j created for each new key */
+ BIO *ssl_bio; /* read/write plaintext from here */
= + BIO *ct_in; /* write cip= hertext to here */
+ = BIO *ct_out; /* read ciphertext from here */
};=

/**
diff --git a/src/openvpn/s= sl_pkt.c b/src/openvpn/ssl_pkt.c
index e730e33..b901f87 100= 644
--- a/src/openvpn/ssl_pkt.c
+++ b/src/o= penvpn/ssl_pkt.c
@@ -61,8 +61,7 @@
{
ASSERT(co);

- const struct key_ctx *ctx =3D (incoming ? &= co->key_ctx_bi.decrypt :
- &co->key_ctx_bi.encrypt);
+ const struct key_ct= x *ctx =3D (incoming ? &co->key_ctx_bi.decrypt : &co->key_ctx= _bi.encrypt);
ASSERT(ctx->hmac);
<= /span>
{
@@ -120,8 +119,7 @@
= tls_wrap_control(struct tls_wrap_ctx *ctx, uint8_t header, struct buffer *= buf,
struct session_id *session_id)
{
- if (= ctx->mode =3D=3D TLS_WRAP_AUTH
- || ctx->mode =3D=3D TLS_WRAP_NONE)
+ if (ctx->mode =3D=3D TLS_WRAP_= AUTH || ctx->mode =3D=3D TLS_WRAP_NONE)
{ ASSERT(session_id_write_prepend(session_id, buf)); ASSERT(buf_write_prepend(buf, &header, sizeof(header))= );
@@ -148,8 +146,7 @@
if ((header= >> P_OPCODE_SHIFT) =3D=3D P_CONTROL_HARD_RESET_CLIENT_V3
<= span> || (header >> P_OPCODE_SHIFT) =3D=3D P_CONTROL_WKC_= V1)

{
- if (!buf_copy(&ctx->work,
- ctx->tls_crypt= _v2_wkc))
+ = if (!buf_copy(&ctx->work, ctx->tls_crypt_v2_wkc))
{

msg(D_TLS_ERRORS, "= Could not append tls-crypt-v2 client key");
= buf->len =3D 0;
@@ -164,12 +161,8 @@
}


void
-write_control_auth(struct tls_session *session,
- struc= t key_state *ks,
- = struct buffer *buf,
- struct link_socket_actual **to_link_addr,
- int o= pcode,
- = int max_ack,
+wri= te_control_auth(struct tls_session *session, struct key_state *ks, struct b= uffer *buf,
+ = struct link_socket_actual **to_link_addr, int opcode, int max_ac= k,
bool prepend_ack)
{=
uint8_t header =3D ks->key_id | (opcode << P= _OPCODE_SHIFT);
@@ -184,34 +177,30 @@
= }

ASSERT(link_socket_actual_defined(= &ks->remote_addr));
- ASSERT(reliable_ack_write
- (ks->rec_ack, ks->lru_acks, buf, &ks-= >session_id_remote,
= - max_ack, prepend_ack));
+ ASSERT(reliable_ack_write(ks->rec_ack, ks->lr= u_acks, buf, &ks->session_id_remote, max_ack,
+ prepend_ack= ));

msg(D_TLS_DEBUG, "%s(): %s&= quot;, __func__, packet_opcode_name(opcode));

<= span style=3D"color: hsl(0, 100%, 40%);">- tls_wrap_control(tls_session_= get_tls_wrap(session, ks->key_id), header, buf, &session->session= _id);

+ tls_wrap_c= ontrol(tls_session_get_tls_wrap(session, ks->key_id), header, buf,
+ &= ;session->session_id);

*to_link_a= ddr =3D &ks->remote_addr;
}

bool
-read_= control_auth(struct buffer *buf,
- struct tls_wrap_ctx *ctx,
- const struct link_socket= _actual *from,
- = const struct tls_options *opt,
+read_control_auth(struct buffer *buf, struct tls_wrap= _ctx *ctx,
+ = const struct link_socket_actual *from, const struct tls_options *o= pt,
bool initial_packet)
{

struct gc_arena gc =3D gc_new();
= bool ret =3D false;

const uint8_= t opcode =3D *(BPTR(buf)) >> P_OPCODE_SHIFT;
- if ((opcode =3D=3D P_CONTROL_HARD_RESET_CL= IENT_V3
- || op= code =3D=3D P_CONTROL_WKC_V1)
+ if ((opcode =3D=3D P_CONTROL_HARD_RESET_CLIENT_V3 || opcode = =3D=3D P_CONTROL_WKC_V1)
&& !tls_crypt_v2_= extract_client_key(buf, ctx, opt, initial_packet))
{
- msg(D_TLS_ERROR= S,
- "T= LS Error: can not extract tls-crypt-v2 client key from %s",
= + msg(D_TLS_ERRORS, &quo= t;TLS Error: can not extract tls-crypt-v2 client key from %s",<= br> print_link_socket_actual(from, &gc));
<= span> goto cleanup;

}
@@ -223,= 8 +212,7 @@
/* move the hmac record to the front o= f the packet */
if (!swap_hmac(buf, &ctx->o= pt, true))
{
- msg(D_TLS_ERRORS,
- "TLS Error: cannot locate HMAC= in incoming packet from %s",
+ msg(D_TLS_ERRORS, "TLS Error: cannot locate= HMAC in incoming packet from %s",
pr= int_link_socket_actual(from, &gc));
gc_fre= e(&gc);
return false;
@@ -= 235,12 +223,10 @@
openvpn_decrypt(buf, null, &= ctx->opt, NULL, BPTR(buf));
if (!buf->len)
{
- msg(D_TLS_ERRORS,
- "TLS Error: incoming packet authentication= failed from %s",
= -
}
else if (ctx->mode =3D=3D = TLS_WRAP_CRYPT)
{
@@ -304,17 +290,14 @= @
* on the UDP port listener in --mode server mode.
*/
enum first_packet_verdict
-tls_pre_decrypt_lite(const struct tls_= auth_standalone *tas,
-= struct tls_pre_decrypt_state *state,
- const struct link_= socket_actual *from,
- = const struct buffer *buf)
+tls_pre_decrypt_lite(const struct tls_auth_standa= lone *tas, struct tls_pre_decrypt_state *state,
+ const struct link_socket_a= ctual *from, const struct buffer *buf)
{
= struct gc_arena gc =3D gc_new();
/* A packet needs= to have at least an opcode and session id */
if (buf-= >len < (1 + SID_SIZE))
{
- dmsg(D_TLS_STATE_ERRORS,
= - "TLS State Err= or: Too short packet (length %d) received from %s",
+ dmsg(D_TLS_STATE_ERRORS, &quo= t;TLS State Error: Too short packet (length %d) received from %s",
buf->len, print_link_socket_actual(from, &am= p;gc));
goto error;
}<= br>@@ -328,27 +311,21 @@
* scrutinize carefully= */

/* Allow only the reset packet o= r the first packet of the actual handshake. */
- if (op !=3D P_CONTROL_HARD_RESET_CLIENT_V2
- && op != =3D P_CONTROL_HARD_RESET_CLIENT_V3
- && op !=3D P_CONTROL_V1
- && op !=3D P_CONTROL_WKC_V1=
- && op= !=3D P_ACK_V1)
+ = if (op !=3D P_CONTROL_HARD_RESET_CLIENT_V2 && op !=3D P_CONTROL_HAR= D_RESET_CLIENT_V3
+ = && op !=3D P_CONTROL_V1 && op !=3D P_CONTROL_WKC_V1 &= amp;& op !=3D P_ACK_V1)
{
= /*
* This can occur due to bogus data or DoS pac= kets.
*/
- dmsg(D_TLS_STATE_ERRORS,
- "TLS State Error: No TLS state fo= r client %s, opcode=3D%d",
- print_link_socket_actual(from, &gc),
<= span style=3D"color: hsl(0, 100%, 40%);">- op);

+ dmsg(D_TLS_STATE_ERRORS, &q= uot;TLS State Error: No TLS state for client %s, opcode=3D%d",
<= br>+ print_link_soc= ket_actual(from, &gc), op);
goto error;=
}

if (key_id !=3D 0)<= /span>
{
dmsg(D_TLS_STATE_ERRORS,
- "TLS S= tate Error: Unknown key ID (%d) received from %s -- 0 was expected",
- key_id,
+ "TLS= State Error: Unknown key ID (%d) received from %s -- 0 was expected",= key_id,
print_link_socket_actual(from, &= gc));
goto error;
}@@ -360,8 +337,7 @@
if (!session_id_read(&s= tate->peer_session_id, &tmp)
|| !session_id= _defined(&state->peer_session_id))
{
= - msg(D_TLS_ERRORS,=
- "TLS Error:= session-id not found in packet from %s",
+ msg(D_TLS_ERRORS, "TLS Error: sessi= on-id not found in packet from %s",
print= _link_socket_actual(from, &gc));
goto error;
}
@@ -372,8 +348,7 @@
= /* HMAC test and unwrapping the encrypted part of the control message
* into newbuf or just setting newbuf to point to the s= tart of control
* message */
- bool status =3D read_control_auth(&sta= te->newbuf, &state->tls_wrap_tmp,
- from, NULL, true)= ;
+ bool status = =3D read_control_auth(&state->newbuf, &state->tls_wrap_tmp, f= rom, NULL, true);

if (!status)
{
@@ -425,11 +400,8 @@


struct buffer
-tls_reset_standalone(struct tls_wrap_ctx *ctx,
- stru= ct tls_auth_standalone *tas,
- struct session_id *own_sid,
- struct session_id *r= emote_sid,
- = uint8_t header,
+tls_reset_standalone(struct tls_wrap_ctx *ctx, struct tls_auth_standa= lone *tas,
+ = struct session_id *own_sid, struct session_id *remote_sid, uint= 8_t header,
bool request_resend_wkc)<= /span>
{
/* Copy buffer here to point at the= same data but allow tls_wrap_control
@@ -484,12 +456,11 @@=
}

struct session_id
-calculate_session_id_hma= c(struct session_id client_sid,
- const struct openvpn_sockaddr *from,
- = hmac_ctx_t *hmac,
- = int handwindow, int offset)
+calculate_session_id_hmac(struct session_= id client_sid, const struct openvpn_sockaddr *from,
+ hmac_ctx_t *hma= c, int handwindow, int offset)
{
- union {
+ union
+ {
uint8_t hmac_result[SHA256_DIGEST_= LENGTH];
struct session_id sid;
= } result;
@@ -497,23 +468,22 @@
/* = Get the valid time quantisation for our hmac,
* we di= vide time by handwindow/2 and allow the previous
* an= d future session time if specified by offset */
- uint32_t session_id_time =3D ntohl(now/((hand= window+1)/2) + offset);
+ uint32_t session_id_time =3D ntohl(now / ((handwindow + 1) / 2) + o= ffset);

hmac_ctx_reset(hmac);=
/* We do not care about endian here since it does not need t= o be
* portable */
- hmac_ctx_update(hmac, (const uint8_t *) &session= _id_time,
- = sizeof(session_id_time));
+ hmac_ctx_update(hmac, (const uint8_t *)&session_id_ti= me, sizeof(session_id_time));

/* add= client IP and port */
switch (from->addr.sa.sa_fam= ily)
{
case AF_INET:- hmac_ctx_update(hm= ac, (const uint8_t *) &from->addr.in4, sizeof(struct sockaddr_in));<= /span>
+ hmac_ctx= _update(hmac, (const uint8_t *)&from->addr.in4, sizeof(struct sockad= dr_in));
break;

case AF_INET6:

- hmac_ctx_update(hmac, (const uint8_t *) &from->add= r.in6, sizeof(struct sockaddr_in6));
+ hmac_ctx_update(hmac, (const uint8_t *)&fr= om->addr.in6, sizeof(struct sockaddr_in6));
= break;
}

@@ -526,10= +496,8 @@
}

bool
-check_session_id_hmac(struc= t tls_pre_decrypt_state *state,
- const struct openvpn_sockaddr *from,=
- hmac_c= tx_t *hmac,
- = int handwindow)
+check_session_id_hmac(struct tls_pre_decrypt_state *state, const st= ruct openvpn_sockaddr *from,
+ hmac_ctx_t *hmac, int handwindow)
= {
if (!from)
{
<= span>@@ -574,7 +542,7 @@

}
/* include the NUL byte and ensure NUL termination */- cmdlen +=3D 1;
<= span style=3D"color: hsl(120, 100%, 40%);">+ cmdlen +=3D 1;


/* Construct a buffer that only holds the curren= t command and
* its closing NUL byte */
diff --git a/src/openvpn/ssl_pkt.h b/src/openvpn/ssl_pkt.h

index 1e9f4e9..8fe4880 100644

--- a/src/openvpn/ssl_pkt.= h
+++ b/src/openvpn/ssl_pkt.h
@@ -35,40 +35= ,40 @@
#include "ssl_common.h"
=
/* packet opcode (high 5 bits) and key-id (low 3 bits) ar= e combined in one byte */
-#define P_KEY_ID_MASK 0x07
-#define P_OPCODE_SHIFT 3+#define P_KEY_ID_MASK 0x07<= /span>
+#define P_OPCODE_SHI= FT 3

/* packet opcodes -- the V1 is inte= nded to allow protocol changes in the future */
-#define P_CONTROL_HARD_RESET_CLIENT_V1 1 /* i= nitial key from client, forget previous state */
-#define P_CONTROL_HARD_RESET_SERVER_V1 2 /* = initial key from server, forget previous state */
-#define P_CONTROL_SOFT_RESET_V1 3 /*= new key, graceful transition from old to new key */
-#define P_CONTROL_V1 4 = /* control channel packet (usually TLS ciphertext) */
-#define P_ACK_V1 5 = /* acknowledgement for packets received */
-#define P_DATA_V1 6 /* da= ta channel packet */
-#= define P_DATA_V2 9 /* data channel packet with pee= r-id */
+#define P_CO= NTROL_HARD_RESET_CLIENT_V1 1 /* initial key from client, forget previous st= ate */
+#define P_CON= TROL_HARD_RESET_SERVER_V1 2 /* initial key from server, forget previous sta= te */
+#define P_CONT= ROL_SOFT_RESET_V1 3 /* new key, graceful transition from old to new = key */
+#define P_CON= TROL_V1 4 /* control channel packet (usually TLS cipherte= xt) */
+#define P_ACK= _V1 5 /* acknowledgement for packets received */
+#define P_DATA_V1 = 6 /* data channel packet */
+#define P_DATA_V2 9 /* data cha= nnel packet with peer-id */

/* indicates= key_method >=3D 2 */
-#define P_CONTROL_HARD_RESET_SERVER_V2 8 /* initial key from server= , forget previous state */
+#define P_CONTROL_HARD_RESET_CLIENT_V2 7 /* initial key from client,= forget previous state */
+#define P_CONTROL_HARD_RESET_SERVER_V2 8 /* initial key from server, = forget previous state */

/* indicates ke= y_method >=3D 2 and client-specific tls-crypt key */
-#define P_CONTROL_HARD_RESET_CLIENT_V3 10= /* initial key from client, forget previous state */
+#define P_CONTROL_HARD_RESET_CLIENT_V3= 10 /* initial key from client, forget previous state */
<= /span>
/* Variant of P_CONTROL_V1 but with appended wrapped key
* like P_CONTROL_HARD_RESET_CLIENT_V3 */
-#define P_CONTROL_WKC_V1 = 11
+#define P_CONTROL= _WKC_V1 11

/* define the range of legal = opcodes
* Since we do no longer support key-method 1 we c= onsider
* the v1 op codes invalid */
-#define P_FIRST_OPCODE 3
-#define P_LAST_OPCODE = 11
+#= define P_FIRST_OPCODE 3
+#define P_LAST_OPCODE 11

/*<= br> * Define number of buffers for send and receive in the reliabili= ty layer.
*/
-#define TLS_RELIABLE_N_SEND_BUFFERS 6 /* also window size for rel= iability layer */
-#def= ine TLS_RELIABLE_N_REC_BUFFERS 12
+#define TLS_RELIABLE_N_SEND_BUFFERS 6 /* also window size f= or reliability layer */
+#define TLS_RELIABLE_N_REC_BUFFERS 12

/*

* Used in --mode server mode to check tls-auth sign= ature on initial
@@ -81,7 +81,8 @@
str= uct frame frame;
};

-enum first_packet_verdict {
+enum first_packet_verdict
+{
/** T= his packet is a valid reset packet from the peer (all but tls-crypt-v2) */<= /span>
VERDICT_VALID_RESET_V2,
/** This = is a valid v3 reset (tls-crypt-v2) */
@@ -101,7 +102,8 @@
* struct that stores the temporary data for the tls lite d= ecrypt
* functions
*/
-struct tls_pre_decrypt_state {+struct tls_pre_decrypt_state=
+{
= struct tls_wrap_ctx tls_wrap_tmp;
struct buffer ne= wbuf;
struct session_id peer_session_id;
@@ -144,11 +146,10 @@

* @li False if the packet is not= valid, did not pass the HMAC firewall
* test, or som= e other error occurred.
*/
-enum first_packet_verdict
-tls_pre_decrypt_lite(const struct tls_auth_stand= alone *tas,
- = struct tls_pre_decrypt_state *state,
- const struct link_socket_act= ual *from,
- = const struct buffer *buf);
+enum first_packet_verdict tls_pre_decrypt_lite(const struc= t tls_auth_standalone *tas,
+ struct tls_pre_decry= pt_state *state,
+ = const struct link_socket_actual= *from,
+ = const struct buffer *buf);

/* Creates an SHA256 HMAC context with a random key t= hat is used for the
* session id.
@@ -170= ,11 +171,9 @@
* @param offset offset to 'now&#= 39; to use
* @return the expected server ses= sion id
*/
-struct session_id
- const struct= openvpn_sockaddr *from,
- int handwindow, int offs= et);
+struct session_= id calculate_session_id_hmac(struct session_id client_sid,
+ = const struct openvpn_sockaddr *from, hmac_ctx_t *hmac,
+ = int handwindow, int offset);


= /**
* Checks if a control packet has a correct HMAC serv= er session id
@@ -185,24 +184,15 @@
* @pa= ram handwindow the quantisation of the current time
* = @return the expected server session id
*/
-bool
-check_session_id_hmac(struct tls_pre_decr= ypt_state *state,
- = const struct openvpn_sockaddr *from,
- hmac_ctx_t *hmac,
- in= t handwindow);
+bool = check_session_id_hmac(struct tls_pre_decrypt_state *state, const struct ope= nvpn_sockaddr *from,
= + hmac_ctx_t *hmac, int handwindow);

/*
* Write a control channel authe= ntication record.
*/
-void
-= write_control_auth(struct tls_session *session,
- struct key_state *ks,- struct buff= er *buf,
- = struct link_socket_actual **to_link_addr,
- int opcode,
- int max_ack,- bool prepen= d_ack);
-
+void write_control_auth(struct tl= s_session *session, struct key_state *ks, struct buffer *buf,

+ struct li= nk_socket_actual **to_link_addr, int opcode, int max_ack,

+ bool prepend_= ack);


/**
@@ -214,12 +204,9 @@

* @param initial_packet wheth= er this is the initial packet for the connection
* @retur= n if the packet was successfully processed
*/

-bool
<= span style=3D"color: hsl(0, 100%, 40%);">-read_control_auth(struct buffer *= buf,

- = struct tls_wrap_ctx *ctx,
- const struct link_socket_actual *from,
- const struct tls_= options *opt,

- = bool initial_packet);
+bool read_control_auth(struct buffer *buf, struct tls_wrap_ctx = *ctx,
+ = const struct link_socket_actual *from, const struct tls_options *o= pt,
+ = bool initial_packet);


= /**
@@ -227,13 +214,9 @@
* from th= e tls pre decrypt state.
*
*/-struct buffer
-tls_reset_standalone(struct tls_wrap_ct= x *ctx,
- = struct tls_auth_standalone *tas,
- struct session_id *own_sid,- struct se= ssion_id *remote_sid,
-= uint8_t header,
- bool request_resend_wkc);
+struct buffer tls_reset_standalon= e(struct tls_wrap_ctx *ctx, struct tls_auth_standalone *tas,

+ = struct session_id *own_sid, struct session_id *remote_sid,

+ = uint8_t header, bool request_resend_wkc);



/**
@@ -246,8 +229,7 @@
* with length 0 if there is no message or the message has
* invalid characters.
*/
-struct buffer
= -extract_command_buffer(struct bu= ffer *buf, struct gc_arena *gc);
+struct buffer extract_command_buffer(struct buffer *buf, struc= t gc_arena *gc);

static inline const cha= r *
packet_opcode_name(int op)
@@ -323,14 = +305,14 @@
* but the network time part of the packet id t= akes care of that. And
* this is also a rather theoretica= l scenario as it still needs more than
* 2^31 control cha= nnel packets to happen */
-#define EARLY_NEG_MASK 0xff000000
-#define EARLY_NEG_START 0x0f000000<= br>+#define EARLY_NEG_MASK 0xf= f000000
+#define EARL= Y_NEG_START 0x0f000000


= /* Early negotiation that part of the server response in the RESET_V2 pack= et.
* Since clients that announce early negotiation suppo= rt will treat the payload
* of reset packets special and = parse it as TLV messages.
* as TLV (type, length, value) = */
-#define TLV_TYPE_EA= RLY_NEG_FLAGS 0x0001
-#define EARLY_NEG_FLAG_RESEND_WKC 0x0001
+#define TLV_TYPE_EARLY_NEG_FLAGS 0x0001<= /span>
+#define EARLY_NEG_FL= AG_RESEND_WKC 0x0001
#endif /* ifndef SSL_PKT_H */<= br>diff --git a/src/openvpn/ssl_util.c b/src/openvpn/ssl_util.c

index 6e00630..918a1f1 100644
--- a/src/openvpn/= ssl_util.c
+++ b/src/openvpn/ssl_util.c
@@ = -28,8 +28,7 @@
#include "ssl_util.h"
<= span>

char *
-extract_var_peer_info(const char *peer_info, const char *var,
- stru= ct gc_arena *gc)
+ext= ract_var_peer_info(const char *peer_info, const char *var, struct gc_arena = *gc)
{
if (!peer_info)
{

@@ -77,8 +76,10 @@
options_string= _compat_lzo(const char *options, struct gc_arena *gc)
{
/* Example string without and with comp-lzo, i.e. input/= output of this function */
- /* w/o comp: 'V4,dev-type tun,link-mtu 1457,tun-mtu 1400,proto= UDPv4,auth SHA1,keysize 128,key-method 2,tls-server' */
- /* comp-lzo: 'V4,dev-type tu= n,link-mtu 1458,tun-mtu 1400,proto UDPv4,comp-lzo,auth SHA1,keysize 128,key= -method 2,tls-server' */

+ /* w/o comp: 'V4,dev-type tun,link-mtu 1457,tun-mtu 1400,p= roto UDPv4,auth SHA1,keysize
+ * 128,key-method 2,tls-server' */
+ /* comp-lzo: 'V4,dev-type tun,lin= k-mtu 1458,tun-mtu 1400,proto UDPv4,comp-lzo,auth SHA1,keysize
+ * 128,key-method 2,tls-serv= er' */


/* Note: since this funct= ion is used only in a very limited scope it makes
* a= ssumptions how the string looks. Since we locally generated the string
@@ -118,146 +119,156 @@
* SSL/TLS Cipher suit= e name translation table
*/
static const= tls_cipher_name_pair tls_cipher_name_translation_table[] =3D {
<= span style=3D"color: hsl(0, 100%, 40%);">- {"ADH-SEED-SHA", &q= uot;TLS-DH-anon-WITH-SEED-CBC-SHA"},

- {"AES128-GCM-SHA256", "TLS-RSA-WITH-= AES-128-GCM-SHA256"},
- {"AES128-SHA256", "TLS-RSA-WITH-AES-128-CBC-SHA256&= quot;},
- {"AES= 128-SHA", "TLS-RSA-WITH-AES-128-CBC-SHA"},
- {"AES256-GCM-SHA384", &qu= ot;TLS-RSA-WITH-AES-256-GCM-SHA384"},
- {"AES256-SHA256", "TLS-RSA-WITH-AES= -256-CBC-SHA256"},
- {"AES256-SHA", "TLS-RSA-WITH-AES-256-CBC-SHA"},
- {"CAMELLIA128-= SHA256", "TLS-RSA-WITH-CAMELLIA-128-CBC-SHA256"},
= - {"CAMELLIA128-SHA"= , "TLS-RSA-WITH-CAMELLIA-128-CBC-SHA"},
- {"CAMELLIA256-SHA256", "TLS-= RSA-WITH-CAMELLIA-256-CBC-SHA256"},
- {"CAMELLIA256-SHA", "TLS-RSA-WITH-CAM= ELLIA-256-CBC-SHA"},
- {"DES-CBC3-SHA", "TLS-RSA-WITH-3DES-EDE-CBC-SHA"= ;},
- {"DES-CBC= -SHA", "TLS-RSA-WITH-DES-CBC-SHA"},
- {"DH-DSS-SEED-SHA", "TLS-DH= -DSS-WITH-SEED-CBC-SHA"},
- {"DHE-DSS-AES128-GCM-SHA256", "TLS-DHE-DSS-WITH= -AES-128-GCM-SHA256"},
- {"DHE-DSS-AES128-SHA256", "TLS-DHE-DSS-WITH-AES-12= 8-CBC-SHA256"},
- = {"DHE-DSS-AES128-SHA", "TLS-DHE-DSS-WITH-AES-128-CBC-SHA&= quot;},
- {"DHE= -DSS-AES256-GCM-SHA384", "TLS-DHE-DSS-WITH-AES-256-GCM-SHA384&quo= t;},
- {"DHE-DS= S-AES256-SHA256", "TLS-DHE-DSS-WITH-AES-256-CBC-SHA256"},
- {"DHE-DSS-AES25= 6-SHA", "TLS-DHE-DSS-WITH-AES-256-CBC-SHA"},
- {"DHE-DSS-CAMELLIA128-SHA256= ", "TLS-DHE-DSS-WITH-CAMELLIA-128-CBC-SHA256"},

- {"DHE-DSS-CAMELLIA128-SHA= ", "TLS-DHE-DSS-WITH-CAMELLIA-128-CBC-SHA"},

- {"DHE-DSS-CAMELLIA256-SHA256= ", "TLS-DHE-DSS-WITH-CAMELLIA-256-CBC-SHA256"},

- {"DHE-DSS-CAMELLIA256-SHA= ", "TLS-DHE-DSS-WITH-CAMELLIA-256-CBC-SHA"},

- {"DHE-DSS-SEED-SHA", &q= uot;TLS-DHE-DSS-WITH-SEED-CBC-SHA"},

- {"DHE-RSA-AES128-GCM-SHA256", "TLS-D= HE-RSA-WITH-AES-128-GCM-SHA256"},
- {"DHE-RSA-AES128-SHA256", "TLS-DHE-RSA-= WITH-AES-128-CBC-SHA256"},
- {"DHE-RSA-AES128-SHA", "TLS-DHE-RSA-WITH-AES-1= 28-CBC-SHA"},
- = {"DHE-RSA-AES256-GCM-SHA384", "TLS-DHE-RSA-WITH-AES-256-GCM= -SHA384"},
- {&= quot;DHE-RSA-AES256-SHA256", "TLS-DHE-RSA-WITH-AES-256-CBC-SHA256= "},
- {"DH= E-RSA-AES256-SHA", "TLS-DHE-RSA-WITH-AES-256-CBC-SHA"},
- {"DHE-RSA-CAMELLI= A128-SHA256", "TLS-DHE-RSA-WITH-CAMELLIA-128-CBC-SHA256"},
- {"DHE-RSA-CAME= LLIA128-SHA", "TLS-DHE-RSA-WITH-CAMELLIA-128-CBC-SHA"},
- {"DHE-RSA-CAMELLI= A256-SHA256", "TLS-DHE-RSA-WITH-CAMELLIA-256-CBC-SHA256"},
- {"DHE-RSA-CAME= LLIA256-SHA", "TLS-DHE-RSA-WITH-CAMELLIA-256-CBC-SHA"},
- {"DHE-RSA-CHACHA2= 0-POLY1305", "TLS-DHE-RSA-WITH-CHACHA20-POLY1305-SHA256"},
- {"DHE-RSA-SEED= -SHA", "TLS-DHE-RSA-WITH-SEED-CBC-SHA"},
- {"DH-RSA-SEED-SHA", "T= LS-DH-RSA-WITH-SEED-CBC-SHA"},
- {"ECDH-ECDSA-AES128-GCM-SHA256", "TLS-ECDH= -ECDSA-WITH-AES-128-GCM-SHA256"},
- {"ECDH-ECDSA-AES128-SHA256", "TLS-ECDH-= ECDSA-WITH-AES-128-CBC-SHA256"},
- {"ECDH-ECDSA-AES128-SHA", "TLS-ECDH-ECDS= A-WITH-AES-128-CBC-SHA"},
- {"ECDH-ECDSA-AES256-GCM-SHA384", "TLS-ECDH-ECDS= A-WITH-AES-256-GCM-SHA384"},
- {"ECDH-ECDSA-AES256-SHA256", "TLS-ECDH-ECDSA= -WITH-AES-256-CBC-SHA256"},
- {"ECDH-ECDSA-AES256-SHA384", "TLS-ECDH-ECDSA-= WITH-AES-256-CBC-SHA384"},
- {"ECDH-ECDSA-AES256-SHA", "TLS-ECDH-ECDSA-WITH= -AES-256-CBC-SHA"},
- {"ECDH-ECDSA-CAMELLIA128-SHA", "TLS-ECDH-ECD= SA-WITH-CAMELLIA-128-CBC-SHA"},
- {"ECDH-ECDSA-CAMELLIA256-SHA256", "TLS-EC= DH-ECDSA-WITH-CAMELLIA-256-CBC-SHA256"},
- {"ECDH-ECDSA-CAMELLIA256-SHA", "= TLS-ECDH-ECDSA-WITH-CAMELLIA-256-CBC-SHA"},
- {"ECDH-ECDSA-DES-CBC3-SHA", "= TLS-ECDH-ECDSA-WITH-3DES-EDE-CBC-SHA"},
- {"ECDH-ECDSA-DES-CBC-SHA", "TLS-E= CDH-ECDSA-WITH-DES-CBC-SHA"},
- {"ECDH-ECDSA-RC4-SHA", "TLS-ECDH-ECDSA-WITH= -RC4-128-SHA"},
- = {"ECDHE-ECDSA-AES128-GCM-SHA256", "TLS-ECDHE-ECDSA-WITH-A= ES-128-GCM-SHA256"},
- {"ECDHE-ECDSA-AES128-SHA256", "TLS-ECDHE-ECDSA-WITH-= AES-128-CBC-SHA256"},
- {"ECDHE-ECDSA-AES128-SHA384", "TLS-ECDHE-ECDSA-WITH= -AES-128-CBC-SHA384"},
- {"ECDHE-ECDSA-AES128-SHA", "TLS-ECDHE-ECDSA-WITH-A= ES-128-CBC-SHA"},
= - {"ECDHE-ECDSA-AES256-GCM-SHA384", "TLS-ECDHE-ECDSA-WITH= -AES-256-GCM-SHA384"},
- {"ECDHE-ECDSA-AES256-SHA256", "TLS-ECDHE-ECDSA-WIT= H-AES-256-CBC-SHA256"},
- {"ECDHE-ECDSA-AES256-SHA384", "TLS-ECDHE-ECDSA-WI= TH-AES-256-CBC-SHA384"},
- {"ECDHE-ECDSA-AES256-SHA", "TLS-ECDHE-ECDSA-WITH= -AES-256-CBC-SHA"},
- {"ECDHE-ECDSA-CAMELLIA128-SHA", "TLS-ECDHE= -ECDSA-WITH-CAMELLIA-128-CBC-SHA"},
- {"ECDHE-ECDSA-CAMELLIA256-SHA256", "T= LS-ECDHE-ECDSA-WITH-CAMELLIA-256-CBC-SHA256"},
- {"ECDHE-ECDSA-CAMELLIA256-SHA"= ;, "TLS-ECDHE-ECDSA-WITH-CAMELLIA-256-CBC-SHA"},
- {"ECDHE-ECDSA-CHACHA20-POLY13= 05", "TLS-ECDHE-ECDSA-WITH-CHACHA20-POLY1305-SHA256"},
- {"ECDHE-ECDSA-DES-= CBC3-SHA", "TLS-ECDHE-ECDSA-WITH-3DES-EDE-CBC-SHA"},<= br>- {"ECDHE-ECDSA-DES-CB= C-SHA", "TLS-ECDHE-ECDSA-WITH-DES-CBC-SHA"},
- {"ECDHE-ECDSA-RC4-SHA",= "TLS-ECDHE-ECDSA-WITH-RC4-128-SHA"},

- {"ECDHE-RSA-AES128-GCM-SHA256", &qu= ot;TLS-ECDHE-RSA-WITH-AES-128-GCM-SHA256"},
- {"ECDHE-RSA-AES128-SHA256", "= TLS-ECDHE-RSA-WITH-AES-128-CBC-SHA256"},
- {"ECDHE-RSA-AES128-SHA384", "TLS= -ECDHE-RSA-WITH-AES-128-CBC-SHA384"},
- {"ECDHE-RSA-AES128-SHA", "TLS-ECDHE= -RSA-WITH-AES-128-CBC-SHA"},
- {"ECDHE-RSA-AES256-GCM-SHA384", "TLS-ECDHE-R= SA-WITH-AES-256-GCM-SHA384"},
- {"ECDHE-RSA-AES256-SHA256", "TLS-ECDHE-RSA-= WITH-AES-256-CBC-SHA256"},
- {"ECDHE-RSA-AES256-SHA384", "TLS-ECDHE-RSA-WIT= H-AES-256-CBC-SHA384"},
- {"ECDHE-RSA-AES256-SHA", "TLS-ECDHE-RSA-WITH-AES-= 256-CBC-SHA"},
- = {"ECDHE-RSA-CAMELLIA128-SHA256", "TLS-ECDHE-RSA-WITH-CAMEL= LIA-128-CBC-SHA256"},
- {"ECDHE-RSA-CAMELLIA128-SHA", "TLS-ECDHE-RSA-WITH-C= AMELLIA-128-CBC-SHA"},
- {"ECDHE-RSA-CAMELLIA256-SHA256", "TLS-ECDHE-RSA-WI= TH-CAMELLIA-256-CBC-SHA256"},
- {"ECDHE-RSA-CAMELLIA256-SHA", "TLS-ECDHE-RS= A-WITH-CAMELLIA-256-CBC-SHA"},
- {"ECDHE-RSA-CHACHA20-POLY1305", "TLS-ECDHE= -RSA-WITH-CHACHA20-POLY1305-SHA256"},
- {"ECDHE-RSA-DES-CBC3-SHA", "TLS-ECD= HE-RSA-WITH-3DES-EDE-CBC-SHA"},
- {"ECDHE-RSA-DES-CBC-SHA", "TLS-ECDHE-RSA-= WITH-DES-CBC-SHA"},
- {"EC= DH-RSA-AES128-GCM-SHA256", "TLS-ECDH-RSA-WITH-AES-128-GCM-SHA256&= quot;},
- {"ECD= H-RSA-AES128-SHA256", "TLS-ECDH-RSA-WITH-AES-128-CBC-SHA256"= },
- {"ECDH-RSA= -AES128-SHA384", "TLS-ECDH-RSA-WITH-AES-128-CBC-SHA384"},
- {"ECDH-RSA-AES1= 28-SHA", "TLS-ECDH-RSA-WITH-AES-128-CBC-SHA"},
- {"ECDH-RSA-AES256-GCM-SHA3= 84", "TLS-ECDH-RSA-WITH-AES-256-GCM-SHA384"},

- {"ECDH-RSA-AES256-SHA256&qu= ot;, "TLS-ECDH-RSA-WITH-AES-256-CBC-SHA256"},

- {"ECDH-RSA-AES256-SHA384", = "TLS-ECDH-RSA-WITH-AES-256-CBC-SHA384"},
- {"ECDH-RSA-AES256-SHA", "TL= S-ECDH-RSA-WITH-AES-256-CBC-SHA"},
- {"ECDH-RSA-CAMELLIA128-SHA256", "TLS-E= CDH-RSA-WITH-CAMELLIA-128-CBC-SHA256"},
- {"ECDH-RSA-CAMELLIA128-SHA", "TLS= -ECDH-RSA-WITH-CAMELLIA-128-CBC-SHA"},
- {"ECDH-RSA-CAMELLIA256-SHA256", "T= LS-ECDH-RSA-WITH-CAMELLIA-256-CBC-SHA256"},
- {"ECDH-RSA-CAMELLIA256-SHA", "= ;TLS-ECDH-RSA-WITH-CAMELLIA-256-CBC-SHA"},
- {"ECDH-RSA-DES-CBC3-SHA", "TLS= -ECDH-RSA-WITH-3DES-EDE-CBC-SHA"},
- {"ECDH-RSA-DES-CBC-SHA", "TLS-ECDH-RSA= -WITH-DES-CBC-SHA"},
- {"ECDH-RSA-RC4-SHA", "TLS-ECDH-RSA-WITH-RC4-128-SHA&= quot;},
- {"EDH= -DSS-DES-CBC3-SHA", "TLS-DHE-DSS-WITH-3DES-EDE-CBC-SHA"},
- {"EDH-DSS-DES-C= BC-SHA", "TLS-DHE-DSS-WITH-DES-CBC-SHA"},
- {"EDH-RSA-DES-CBC3-SHA", &= quot;TLS-DHE-RSA-WITH-3DES-EDE-CBC-SHA"},
- {"EDH-RSA-DES-CBC-SHA", "TLS-DH= E-RSA-WITH-DES-CBC-SHA"},
- {"EXP-DES-CBC-SHA", "TLS-RSA-EXPORT-WITH-DES40-= CBC-SHA"},
- {&= quot;EXP-EDH-DSS-DES-CBC-SHA", "TLS-DH-DSS-EXPORT-WITH-DES40-CBC-= SHA"},
- {"= ;EXP-EDH-RSA-DES-CBC-SHA", "TLS-DH-RSA-EXPORT-WITH-DES40-CBC-SHA&= quot;},
- {"EXP= -RC2-CBC-MD5", "TLS-RSA-EXPORT-WITH-RC2-CBC-40-MD5"},=
- {"EXP-RC4-MD5"= , "TLS-RSA-EXPORT-WITH-RC4-40-MD5"},
- {"NULL-MD5", "TLS-RSA-WITH-NULL= -MD5"},
- {&quo= t;NULL-SHA256", "TLS-RSA-WITH-NULL-SHA256"},
- {"NULL-SHA", "TLS-= RSA-WITH-NULL-SHA"},

- {"PSK-3DES-EDE-CBC-SHA", "TLS-PSK-WITH-3DES-EDE-CBC-= SHA"},
- {"= ;PSK-AES128-CBC-SHA", "TLS-PSK-WITH-AES-128-CBC-SHA"},
- {"PSK-AES256-CBC-S= HA", "TLS-PSK-WITH-AES-256-CBC-SHA"},
- {"PSK-RC4-SHA", "TLS-PSK= -WITH-RC4-128-SHA"},
- {"RC4-MD5", "TLS-RSA-WITH-RC4-128-MD5"},=
- {"RC4-SHA", &q= uot;TLS-RSA-WITH-RC4-128-SHA"},
- {"SEED-SHA", "TLS-RSA-WITH-SEED-CBC-SHA&q= uot;},
- {"SRP-= DSS-3DES-EDE-CBC-SHA", "TLS-SRP-SHA-DSS-WITH-3DES-EDE-CBC-SHA&quo= t;},
- {"SRP-DS= S-AES-128-CBC-SHA", "TLS-SRP-SHA-DSS-WITH-AES-128-CBC-SHA"},=
- {"SRP-DSS-AE= S-256-CBC-SHA", "TLS-SRP-SHA-DSS-WITH-AES-256-CBC-SHA"},
- {"SRP-RSA-3DES-E= DE-CBC-SHA", "TLS-SRP-SHA-RSA-WITH-3DES-EDE-CBC-SHA"},
- {"SRP-RSA-AES-128-= CBC-SHA", "TLS-SRP-SHA-RSA-WITH-AES-128-CBC-SHA"},- {"SRP-RSA-AES-256-CBC-= SHA", "TLS-SRP-SHA-RSA-WITH-AES-256-CBC-SHA"},
+ { "ADH-SEED-SHA", &= quot;TLS-DH-anon-WITH-SEED-CBC-SHA" },

+ { "AES128-GCM-SHA256", "TLS-RSA-= WITH-AES-128-GCM-SHA256" },
+ { "AES128-SHA256", "TLS-RSA-WITH-AES-128-CB= C-SHA256" },
+ = { "AES128-SHA", "TLS-RSA-WITH-AES-128-CBC-SHA" },
+ { "AES256-GCM-= SHA384", "TLS-RSA-WITH-AES-256-GCM-SHA384" },
+ { "AES256-SHA256", &= quot;TLS-RSA-WITH-AES-256-CBC-SHA256" },

+ { "AES256-SHA", "TLS-RSA-WITH-= AES-256-CBC-SHA" },
+ { "CAMELLIA128-SHA256", "TLS-RSA-WITH-CAMELLIA-128-= CBC-SHA256" },
+= { "CAMELLIA128-SHA", "TLS-RSA-WITH-CAMELLIA-128-CBC-SHA&= quot; },
+ { "= ;CAMELLIA256-SHA256", "TLS-RSA-WITH-CAMELLIA-256-CBC-SHA256"= },
+ { "CAME= LLIA256-SHA", "TLS-RSA-WITH-CAMELLIA-256-CBC-SHA" },<= br>+ { "DES-CBC3-SHA&qu= ot;, "TLS-RSA-WITH-3DES-EDE-CBC-SHA" },
+ { "DES-CBC-SHA", "TLS-RSA-= WITH-DES-CBC-SHA" },
+ { "DH-DSS-SEED-SHA", "TLS-DH-DSS-WITH-SEED-CBC-SHA= " },
+ { &quo= t;DHE-DSS-AES128-GCM-SHA256", "TLS-DHE-DSS-WITH-AES-128-GCM-SHA25= 6" },
+ { &qu= ot;DHE-DSS-AES128-SHA256", "TLS-DHE-DSS-WITH-AES-128-CBC-SHA256&q= uot; },
+ { "= DHE-DSS-AES128-SHA", "TLS-DHE-DSS-WITH-AES-128-CBC-SHA" },
+ { "DHE-DSS-A= ES256-GCM-SHA384", "TLS-DHE-DSS-WITH-AES-256-GCM-SHA384" },<= /span>
+ { "DHE-DSS-= AES256-SHA256", "TLS-DHE-DSS-WITH-AES-256-CBC-SHA256" },
+ { "DHE-DSS-AES= 256-SHA", "TLS-DHE-DSS-WITH-AES-256-CBC-SHA" },
+ { "DHE-DSS-CAMELLIA128-= SHA256", "TLS-DHE-DSS-WITH-CAMELLIA-128-CBC-SHA256" },
+ { "DHE-DSS-CAMEL= LIA128-SHA", "TLS-DHE-DSS-WITH-CAMELLIA-128-CBC-SHA" },
+ { "DHE-DSS-CAME= LLIA256-SHA256", "TLS-DHE-DSS-WITH-CAMELLIA-256-CBC-SHA256" = },
+ { "DHE-D= SS-CAMELLIA256-SHA", "TLS-DHE-DSS-WITH-CAMELLIA-256-CBC-SHA"= },
+ { "DHE-= DSS-SEED-SHA", "TLS-DHE-DSS-WITH-SEED-CBC-SHA" },
= + { "DHE-RSA-AES128-GCM= -SHA256", "TLS-DHE-RSA-WITH-AES-128-GCM-SHA256" },+ { "DHE-RSA-AES128-SH= A256", "TLS-DHE-RSA-WITH-AES-128-CBC-SHA256" },
+ { "DHE-RSA-AES128-SHA&q= uot;, "TLS-DHE-RSA-WITH-AES-128-CBC-SHA" },

+ { "DHE-RSA-AES256-GCM-SHA384&quo= t;, "TLS-DHE-RSA-WITH-AES-256-GCM-SHA384" },
+ { "DHE-RSA-AES256-SHA256",= "TLS-DHE-RSA-WITH-AES-256-CBC-SHA256" },
+ { "DHE-RSA-AES256-SHA", &qu= ot;TLS-DHE-RSA-WITH-AES-256-CBC-SHA" },
+ { "DHE-RSA-CAMELLIA128-SHA256", &quo= t;TLS-DHE-RSA-WITH-CAMELLIA-128-CBC-SHA256" },
+ { "DHE-RSA-CAMELLIA128-SHA"= , "TLS-DHE-RSA-WITH-CAMELLIA-128-CBC-SHA" },
+ { "DHE-RSA-CAMELLIA256-SHA256&q= uot;, "TLS-DHE-RSA-WITH-CAMELLIA-256-CBC-SHA256" },
+ { "DHE-RSA-CAMELLIA256-S= HA", "TLS-DHE-RSA-WITH-CAMELLIA-256-CBC-SHA" },

+ { "DHE-RSA-CHACHA20-POL= Y1305", "TLS-DHE-RSA-WITH-CHACHA20-POLY1305-SHA256" },
+ { "DHE-RSA-SEED-= SHA", "TLS-DHE-RSA-WITH-SEED-CBC-SHA" },
+ { "DH-RSA-SEED-SHA", &quo= t;TLS-DH-RSA-WITH-SEED-CBC-SHA" },
+ { "ECDH-ECDSA-AES128-GCM-SHA256", "T= LS-ECDH-ECDSA-WITH-AES-128-GCM-SHA256" },
+ { "ECDH-ECDSA-AES128-SHA256", &quo= t;TLS-ECDH-ECDSA-WITH-AES-128-CBC-SHA256" },
+ { "ECDH-ECDSA-AES128-SHA", &quo= t;TLS-ECDH-ECDSA-WITH-AES-128-CBC-SHA" },
+ { "ECDH-ECDSA-AES256-GCM-SHA384", = "TLS-ECDH-ECDSA-WITH-AES-256-GCM-SHA384" },
+ { "ECDH-ECDSA-AES256-SHA256"= ;, "TLS-ECDH-ECDSA-WITH-AES-256-CBC-SHA256" },
+ { "ECDH-ECDSA-AES256-SHA384&q= uot;, "TLS-ECDH-ECDSA-WITH-AES-256-CBC-SHA384" },
+ { "ECDH-ECDSA-AES256-SHA&q= uot;, "TLS-ECDH-ECDSA-WITH-AES-256-CBC-SHA" },

+ { "ECDH-ECDSA-CAMELLIA128-SHA= 256", "TLS-ECDH-ECDSA-WITH-CAMELLIA-128-CBC-SHA256" },
+ { "ECDH-ECDSA-CA= MELLIA128-SHA", "TLS-ECDH-ECDSA-WITH-CAMELLIA-128-CBC-SHA" }= ,
+ { "ECDH-E= CDSA-CAMELLIA256-SHA256", "TLS-ECDH-ECDSA-WITH-CAMELLIA-256-CBC-S= HA256" },
+ {= "ECDH-ECDSA-CAMELLIA256-SHA", "TLS-ECDH-ECDSA-WITH-CAMELLIA= -256-CBC-SHA" },
+ { "ECDH-ECDSA-DES-CBC3-SHA", "TLS-ECDH-ECDSA-WITH-3DES= -EDE-CBC-SHA" },
+ { "ECDH-ECDSA-DES-CBC-SHA", "TLS-ECDH-ECDSA-WITH-DES-C= BC-SHA" },
+ = { "ECDH-ECDSA-RC4-SHA", "TLS-ECDH-ECDSA-WITH-RC4-128-SHA&quo= t; },
+ { "EC= DHE-ECDSA-AES128-GCM-SHA256", "TLS-ECDHE-ECDSA-WITH-AES-128-GCM-S= HA256" },
+ {= "ECDHE-ECDSA-AES128-SHA256", "TLS-ECDHE-ECDSA-WITH-AES-128-= CBC-SHA256" },
+= { "ECDHE-ECDSA-AES128-SHA384", "TLS-ECDHE-ECDSA-WITH-AES= -128-CBC-SHA384" },
+ { "ECDHE-ECDSA-AES128-SHA", "TLS-ECDHE-ECDSA-WITH-A= ES-128-CBC-SHA" },
+ { "ECDHE-ECDSA-AES256-GCM-SHA384", "TLS-ECDHE-ECDSA-= WITH-AES-256-GCM-SHA384" },
+ { "ECDHE-ECDSA-AES256-SHA256", "TLS-ECDHE-E= CDSA-WITH-AES-256-CBC-SHA256" },
+ { "ECDHE-ECDSA-AES256-SHA384", "TLS-EC= DHE-ECDSA-WITH-AES-256-CBC-SHA384" },
+ { "ECDHE-ECDSA-AES256-SHA", "TLS-= ECDHE-ECDSA-WITH-AES-256-CBC-SHA" },
+ { "ECDHE-ECDSA-CAMELLIA128-SHA256", &qu= ot;TLS-ECDHE-ECDSA-WITH-CAMELLIA-128-CBC-SHA256" },
+ { "ECDHE-ECDSA-CAMELLIA128-SH= A", "TLS-ECDHE-ECDSA-WITH-CAMELLIA-128-CBC-SHA" },+ { "ECDHE-ECDSA-CAMEL= LIA256-SHA256", "TLS-ECDHE-ECDSA-WITH-CAMELLIA-256-CBC-SHA256&quo= t; },
+ { "EC= DHE-ECDSA-CAMELLIA256-SHA", "TLS-ECDHE-ECDSA-WITH-CAMELLIA-256-CB= C-SHA" },
+ {= "ECDHE-ECDSA-CHACHA20-POLY1305", "TLS-ECDHE-ECDSA-WITH-CHAC= HA20-POLY1305-SHA256" },
+ { "ECDHE-ECDSA-DES-CBC3-SHA", "TLS-ECDHE-ECDSA= -WITH-3DES-EDE-CBC-SHA" },
+ { "ECDHE-ECDSA-DES-CBC-SHA", "TLS-ECDHE-ECDS= A-WITH-DES-CBC-SHA" },
+ { "ECDHE-ECDSA-RC4-SHA", "TLS-ECDHE-ECDSA-WITH-R= C4-128-SHA" },
+= { "ECDHE-RSA-AES128-GCM-SHA256", "TLS-ECDHE-RSA-WITH-AES= -128-GCM-SHA256" },
+ { "ECDHE-RSA-AES128-SHA256", "TLS-ECDHE-RSA-WITH-AE= S-128-CBC-SHA256" },
+ { "ECDHE-RSA-AES128-SHA384", "TLS-ECDHE-RSA-WITH-A= ES-128-CBC-SHA384" },
+ { "ECDHE-RSA-AES128-SHA", "TLS-ECDHE-RSA-WITH-AES= -128-CBC-SHA" },
+ { "ECDHE-RSA-AES256-GCM-SHA384", "TLS-ECDHE-RSA-WITH-A= ES-256-GCM-SHA384" },
+ { "ECDHE-RSA-AES256-SHA256", "TLS-ECDHE-RSA-WITH-= AES-256-CBC-SHA256" },
+ { "ECDHE-RSA-AES256-SHA384", "TLS-ECDHE-RSA-WITH= -AES-256-CBC-SHA384" },
+ { "ECDHE-RSA-AES256-SHA", "TLS-ECDHE-RSA-WITH-A= ES-256-CBC-SHA" },
+ { "ECDHE-RSA-CAMELLIA128-SHA256", "TLS-ECDHE-RSA-WIT= H-CAMELLIA-128-CBC-SHA256" },
+ { "ECDHE-RSA-CAMELLIA128-SHA", "TLS-ECDHE= -RSA-WITH-CAMELLIA-128-CBC-SHA" },
+ { "ECDHE-RSA-CAMELLIA256-SHA256", "T= LS-ECDHE-RSA-WITH-CAMELLIA-256-CBC-SHA256" },
+ { "ECDHE-RSA-CAMELLIA256-SHA",= "TLS-ECDHE-RSA-WITH-CAMELLIA-256-CBC-SHA" },
+ { "ECDHE-RSA-CHACHA20-POLY1305= ", "TLS-ECDHE-RSA-WITH-CHACHA20-POLY1305-SHA256" },+ { "ECDHE-RSA-DES-CB= C3-SHA", "TLS-ECDHE-RSA-WITH-3DES-EDE-CBC-SHA" },
= + { "ECDHE-RSA-DES-CBC-= SHA", "TLS-ECDHE-RSA-WITH-DES-CBC-SHA" },
+ { "ECDHE-RSA-RC4-SHA", &= quot;TLS-ECDHE-RSA-WITH-RC4-128-SHA" },
+ { "ECDH-RSA-AES128-GCM-SHA256", &quo= t;TLS-ECDH-RSA-WITH-AES-128-GCM-SHA256" },
+ { "ECDH-RSA-AES128-SHA256", "= ;TLS-ECDH-RSA-WITH-AES-128-CBC-SHA256" },
+ { "ECDH-RSA-AES128-SHA384", "= TLS-ECDH-RSA-WITH-AES-128-CBC-SHA384" },
+ { "ECDH-RSA-AES128-SHA", "TLS-= ECDH-RSA-WITH-AES-128-CBC-SHA" },
+ { "ECDH-RSA-AES256-GCM-SHA384", "TLS-= ECDH-RSA-WITH-AES-256-GCM-SHA384" },
+ { "ECDH-RSA-AES256-SHA256", "TLS-E= CDH-RSA-WITH-AES-256-CBC-SHA256" },
+ { "ECDH-RSA-AES256-SHA384", "TLS-EC= DH-RSA-WITH-AES-256-CBC-SHA384" },
+ { "ECDH-RSA-AES256-SHA", "TLS-ECDH-R= SA-WITH-AES-256-CBC-SHA" },
+ { "ECDH-RSA-CAMELLIA128-SHA256", "TLS-ECDH-= RSA-WITH-CAMELLIA-128-CBC-SHA256" },
+ { "ECDH-RSA-CAMELLIA128-SHA", "TLS= -ECDH-RSA-WITH-CAMELLIA-128-CBC-SHA" },
+ { "ECDH-RSA-CAMELLIA256-SHA256", &qu= ot;TLS-ECDH-RSA-WITH-CAMELLIA-256-CBC-SHA256" },
+ { "ECDH-RSA-CAMELLIA256-SHA"= ;, "TLS-ECDH-RSA-WITH-CAMELLIA-256-CBC-SHA" },
+ { "ECDH-RSA-DES-CBC3-SHA"= ;, "TLS-ECDH-RSA-WITH-3DES-EDE-CBC-SHA" },
+ { "ECDH-RSA-DES-CBC-SHA", &= quot;TLS-ECDH-RSA-WITH-DES-CBC-SHA" },
+ { "ECDH-RSA-RC4-SHA", "TLS-ECDH-= RSA-WITH-RC4-128-SHA" },
+ { "EDH-DSS-DES-CBC3-SHA", "TLS-DHE-DSS-WITH-3D= ES-EDE-CBC-SHA" },
+ { "EDH-DSS-DES-CBC-SHA", "TLS-DHE-DSS-WITH-DES-CBC-S= HA" },
+ { &q= uot;EDH-RSA-DES-CBC3-SHA", "TLS-DHE-RSA-WITH-3DES-EDE-CBC-SHA&quo= t; },
+ { "ED= H-RSA-DES-CBC-SHA", "TLS-DHE-RSA-WITH-DES-CBC-SHA" },=
+ { "EXP-DES-CBC-SH= A", "TLS-RSA-EXPORT-WITH-DES40-CBC-SHA" },
+ { "EXP-EDH-DSS-DES-CBC-SHA&q= uot;, "TLS-DH-DSS-EXPORT-WITH-DES40-CBC-SHA" },
+ { "EXP-EDH-RSA-DES-CBC-SHA&q= uot;, "TLS-DH-RSA-EXPORT-WITH-DES40-CBC-SHA" },
+ { "EXP-RC2-CBC-MD5", &q= uot;TLS-RSA-EXPORT-WITH-RC2-CBC-40-MD5" },
+ { "EXP-RC4-MD5", "TLS-RSA-EX= PORT-WITH-RC4-40-MD5" },
+ { "NULL-MD5", "TLS-RSA-WITH-NULL-MD5" },<= /span>
+ { "NULL-SHA= 256", "TLS-RSA-WITH-NULL-SHA256" },
+ { "NULL-SHA", "TLS-RSA-WI= TH-NULL-SHA" },
= + { "PSK-3DES-EDE-CBC-SHA", "TLS-PSK-WITH-3DES-EDE-CBC-SH= A" },
+ { &qu= ot;PSK-AES128-CBC-SHA", "TLS-PSK-WITH-AES-128-CBC-SHA" },
+ { "PSK-AES256= -CBC-SHA", "TLS-PSK-WITH-AES-256-CBC-SHA" },
+ { "PSK-RC4-SHA", &quo= t;TLS-PSK-WITH-RC4-128-SHA" },

+ { "RC4-MD5", "TLS-RSA-WITH-RC4-128-MD5&q= uot; },
+ { "= RC4-SHA", "TLS-RSA-WITH-RC4-128-SHA" },
+ { "SEED-SHA", "TLS-RS= A-WITH-SEED-CBC-SHA" },
+ { "SRP-DSS-3DES-EDE-CBC-SHA", "TLS-SRP-SHA-DSS-= WITH-3DES-EDE-CBC-SHA" },
+ { "SRP-DSS-AES-128-CBC-SHA", "TLS-SRP-SHA-DSS= -WITH-AES-128-CBC-SHA" },
+ { "SRP-DSS-AES-256-CBC-SHA", "TLS-SRP-SHA-DSS= -WITH-AES-256-CBC-SHA" },
+ { "SRP-RSA-3DES-EDE-CBC-SHA", "TLS-SRP-SHA-RS= A-WITH-3DES-EDE-CBC-SHA" },
+ { "SRP-RSA-AES-128-CBC-SHA", "TLS-SRP-SHA-R= SA-WITH-AES-128-CBC-SHA" },
+ { "SRP-RSA-AES-256-CBC-SHA", "TLS-SRP-SHA-R= SA-WITH-AES-256-CBC-SHA" },
#ifdef ENABLE_CRYPTO_OPEN= SSL
/* OpenSSL-specific group names */
- {"DEFAULT", "DEFAU= LT"},

- {"= ALL", "ALL"},
- {"HIGH", "HIGH"}, {"!HIGH", "= !HIGH"},
- {&qu= ot;MEDIUM", "MEDIUM"}, {"!MEDIUM", "!MEDIUM&q= uot;},
- {"LOW&= quot;, "LOW"}, {"!LOW", "!LOW"},
- {"ECDH", "ECDH&= quot;}, {"!ECDH", "!ECDH"},

- {"ECDSA", "ECDSA"}, {&quo= t;!ECDSA", "!ECDSA"},
- {"EDH", "EDH"}, {"!EDH", &= quot;!EDH"},
- = {"EXP", "EXP"}, {"!EXP", "!EXP"},
- {"RSA", &= quot;RSA"}, {"!RSA", "!RSA"},
- {"kRSA", "kRSA"}, = {"!kRSA", "!kRSA"},
- {"SRP", "SRP"}, {"!SRP"= , "!SRP"},
= + { "DEFAULT", "DEFAULT" },
+ { "ALL", "ALL" },
+ { "HIGH"= , "HIGH" },
+ { "!HIGH", "!HIGH" },
+ { "MEDIUM", "MEDIUM" },=
+ { "!MEDIUM= ", "!MEDIUM" },
+ { "LOW", "LOW" },
+ { "!LOW", "!LOW" = },
+ { "ECDH&= quot;, "ECDH" },
+ { "!ECDH", "!ECDH" },
+ { "ECDSA", "ECDSA"= ; },
+ { "!EC= DSA", "!ECDSA" },
+ { "EDH", "EDH" },
+ { "!EDH", "!EDH"= },
+ { "EXP&= quot;, "EXP" },
+ { "!EXP", "!EXP" },
+ { "RSA", "RSA" },
+ { "!RSA",= "!RSA" },
= + { "kRSA", "kRSA" },
+ { "!kRSA", "!kRSA" },
+ { "SRP", &= quot;SRP" },
+ = { "!SRP", "!SRP" },
#endif- {NULL, NULL}
+ { NULL, NULL }

};


const tls_cipher_name_pair *=
diff --git a/src/openvpn/ssl_util.h b/src/openvpn/ssl_util.h
index 189b1d0..007ed69 100644
--- a/src/openvpn= /ssl_util.h
+++ b/src/openvpn/ssl_util.h
@@= -43,8 +43,7 @@
* @return The content of the variable as= NULL terminated string or NULL if the
* variabl= e cannot be found.
*/
-char *extract_var_peer_info(const char *peer_info, const = char *var,
- = struct gc_arena *gc);
+char *extract_var_peer_info(const char *peer_info, const= char *var, struct gc_arena *gc);

/**
* Extracts the IV_PROTO variable and returns its value or 0=
@@ -74,7 +73,11 @@
* @param cipher_name = Can be either OpenSSL or IANA cipher name
* @return = tls_cipher_name_pair* if found, NULL otherwise
= */
-typedef struct { co= nst char *openssl_name; const char *iana_name; } tls_cipher_name_pair;
+typedef struct+{
+ const char *openssl_name;
+ const char *iana_name;
= +} tls_cipher_name_pair;=
const tls_cipher_name_pair *tls_get_cipher_name_pair(const char = *cipher_name, size_t len);

/**@@ -88,7 +91,6 @@
* @param delimiter the delim= iter to count, typically ':'
* @return = occrrences of delimiter + 1
*/
-int
-get_num_elements(const char *string, char delimiter);<= br>+int get_num_elements(const = char *string, char delimiter);

#endif /*= ifndef SSL_UTIL_H_ */
diff --git a/src/openvpn/ssl_verify.= c b/src/openvpn/ssl_verify.c
index 82337cf..6f85dca 100644<= /span>
--- a/src/openvpn/ssl_verify.c
+++ b/src/op= envpn/ssl_verify.c
@@ -149,11 +149,12 @@
= /* If the username has been overridden, we accept both the original<= /span>
* username and the changed username */
= if (strcmp(username, multi->locked_username) !=3D 0
- && (!m= ulti->locked_original_username || strcmp(username, multi->locked_orig= inal_username) !=3D 0))
+ && (!multi->locked_original_username
<= span style=3D"color: hsl(120, 100%, 40%);">+ || strcmp(usern= ame, multi->locked_original_username) !=3D 0))

= {
- msg(D_TL= S_ERRORS, "TLS Auth Error: username attempted to change from '%s&#= 39; to '%s' -- tunnel disabled",
- multi->locked_username,- username);
+ msg(D_TLS_E= RRORS,
+ = "TLS Auth Error: username attempted to change from '%s' to = '%s' -- tunnel disabled",
+ multi->locked_username, username);

/* disable the tunnel */
tls_deauthenticate(multi);
@@ -239,= 8 +240,8 @@
{
= continue;
}
- else if (ch1 && ch2 && !mem= cmp(ch1->sha256_hash, ch2->sha256_hash,
- sizeof(c= h1->sha256_hash)))
+ else if (ch1 && ch2
+ && !memcmp(ch1->sha25= 6_hash, ch2->sha256_hash, sizeof(ch1->sha256_hash)))
= {
continue;
= }
@@ -275,8 +276,7 @@
= if (ch)
{
= ALLOC_OBJ(dest->ch[i], struct cert_hash);
- memcpy(dest->ch[i]->sha256_ha= sh, ch->sha256_hash,
- sizeof(dest->ch[i]->sha256_hash));+ memcpy(dest-&= gt;ch[i]->sha256_hash, ch->sha256_hash, sizeof(dest->ch[i]->sha= 256_hash));
}
}
}
@@ -320,22 +320,21 @@
*= @param subject the peer's extracted common name
*/
static result_t
-verify_peer_cert(const struct tls_options *opt, openvpn_x509_cert= _t *peer_cert,
- = const char *subject, const char *common_name)
+verify_peer_cert(const struct tls_optio= ns *opt, openvpn_x509_cert_t *peer_cert, const char *subject,
+ const char *comm= on_name)

{
/* verify certificate nsCe= rtType */
if (opt->ns_cert_type !=3D NS_CERT_CHECK_= NONE)
{
if (SUCCESS =3D=3D x5= 09_verify_ns_cert_type(peer_cert, opt->ns_cert_type))
= {
- m= sg(D_HANDSHAKE, "VERIFY OK: nsCertType=3D%s",
- print_nsCertType(opt->= ns_cert_type));
+ = msg(D_HANDSHAKE, "VERIFY OK: nsCertType=3D%s", print_nsCe= rtType(opt->ns_cert_type));
}
= else
{
- msg(D_HANDSHAKE, "VERIFY nsCertType ERRO= R: %s, require nsCertType=3D%s",
- subject, print_nsCertType(opt->ns_cert_t= ype));
- ret= urn FAILURE; /* Reject connection */
+ msg(D_HANDSHAKE, "VERIFY nsCe= rtType ERROR: %s, require nsCertType=3D%s", subject,
+ print_nsCertType(opt-= >ns_cert_type));
+= return FAILURE; /* Reject connection */
= }
}

@@ -349,7 +348= ,7 @@
else
{
msg(D_HANDSHAKE, "VERIFY KU ERROR");

<= span style=3D"color: hsl(0, 100%, 40%);">- return FAILURE; = /* Reject connection */

+ return FAILURE; /* Reject connection */
}

}

@@ = -363,28 +362,27 @@
else
{=
msg(D_HANDSHAKE, "VERIFY EKU ERROR"= );
- return = FAILURE; /* Reject connection */
+ return FAILURE; /* Reject connection *= /
}
}

/* verify X509 name or username against --verify-x509-[user= ]name */
if (opt->verify_x509_type !=3D VERIFY_X509= _NONE)
{
- if ( (opt->verify_x509_type =3D=3D VERIFY_X509_SUBJECT_D= N
- &&= amp; strcmp(opt->verify_x509_name, subject) =3D=3D 0)
- || (opt->verify_x509_typ= e =3D=3D VERIFY_X509_SUBJECT_RDN
- && strcmp(opt->verify_x509_name, com= mon_name) =3D=3D 0)
- = || (opt->verify_x509_type =3D=3D VERIFY_X509_SUBJECT_RDN_PREF= IX
- &a= mp;& strncmp(opt->verify_x509_name, common_name,
- strlen(opt-&g= t;verify_x509_name)) =3D=3D 0) )
+ if ((opt->verify_x509_type =3D=3D VERIFY_X509_SUBJE= CT_DN
+ &= amp;& strcmp(opt->verify_x509_name, subject) =3D=3D 0)
+ || (opt->verify_x5= 09_type =3D=3D VERIFY_X509_SUBJECT_RDN

+ && strcmp(opt->verify_x509_na= me, common_name) =3D=3D 0)
+ || (opt->verify_x509_type =3D=3D VERIFY_X509_SUBJECT_= RDN_PREFIX
+ = && strncmp(opt->verify_x509_name, common_name, strlen(opt= ->verify_x509_name)) =3D=3D 0))
{
msg(D_HANDSHAKE, "VERIFY X509NAME OK: %s", subjec= t);

}
else
{

- = msg(D_HANDSHAKE, "VERIFY X509NAME ERROR: %s, must be %s",
- subject, o= pt->verify_x509_name);
- return FAILURE; /* Reject connection */<= br>+ msg(D_HANDSHAKE= , "VERIFY X509NAME ERROR: %s, must be %s", subject,
+ opt->verify_x5= 09_name);

+ = return FAILURE; /* Reject connection */
}=
}

@@ -397,8 +395,7 @@
*/
static void
verify_cert_= set_env(struct env_set *es, openvpn_x509_cert_t *peer_cert, int cert_depth,=
- c= onst char *subject,
- = const struct x509_track *x509_track)
+ const char *subject,= const struct x509_track *x509_track)
{
= char envname[64];
char *serial =3D NULL;
= @@ -424,13 +421,10 @@
struct buffer sha256 = =3D x509_get_sha256_fingerprint(peer_cert, &gc);

snprintf(envname, sizeof(envname), "tls_digest_%d= ", cert_depth);
- = setenv_str(es, envname,
- format_hex_ex(BPTR(&sha1), BLEN(&sha1),= 0, 1, ":", &gc));
+ setenv_str(es, envname, format_hex_ex(BPTR(&sha1),= BLEN(&sha1), 0, 1, ":", &gc));
<= br>- snprintf(envname, siz= eof(envname), "tls_digest_sha256_%d",
- cert_depth);
- setenv_str(es, envname,- format_hex_e= x(BPTR(&sha256), BLEN(&sha256), 0, 1, ":", &gc));
+ snprintf(envnam= e, sizeof(envname), "tls_digest_sha256_%d", cert_depth);+ setenv_str(es, envna= me, format_hex_ex(BPTR(&sha256), BLEN(&sha256), 0, 1, ":"= , &gc));
}

= /* export serial number as environmental variable */
@@ -47= 4,8 +468,8 @@
* call --tls-verify plug-in(s)
*/

static result_t
-verify_cert_call_plugin(const struct plugin_list *plugi= ns, struct env_set *es,
- int cert_depth, openvpn_x509_cert_t *cert, char *= subject)
+verify_cert= _call_plugin(const struct plugin_list *plugins, struct env_set *es, int cer= t_depth,
+ = openvpn_x509_cert_t *cert, char *subject)
{
if (plugin_defined(plugins, OPENVPN_PLUGIN_TLS_VERIFY))=
{
@@ -484,20 +478,19 @@

argv_printf(&argv, "%d %s", cer= t_depth, subject);

- ret =3D plugin_call_ssl(plugins, OPENVPN_PLUGIN_TLS_= VERIFY, &argv, NULL, es, cert_depth, cert);
+ ret =3D
+ plugin_call_ssl(plugins, OPENVPN_PLUGIN= _TLS_VERIFY, &argv, NULL, es, cert_depth, cert);

argv_free(&argv);

if (ret =3D=3D OPENVPN_PLUGIN_FUNC_SUCCESS)

= {
- msg= (D_HANDSHAKE, "VERIFY PLUGIN OK: depth=3D%d, %s",
- cert_depth, subject);=

+ msg(D_H= ANDSHAKE, "VERIFY PLUGIN OK: depth=3D%d, %s", cert_depth, subject= );
}
else
{

- = msg(D_HANDSHAKE, "VERIFY PLUGIN ERROR: depth=3D%d, %s",<= br>- cert_depth, s= ubject);
- r= eturn FAILURE; /* Reject connection */
+ msg(D_HANDSHAKE, "VERIFY PL= UGIN ERROR: depth=3D%d, %s", cert_depth, subject);
+ return FAILURE; /* Reject c= onnection */
}
}
return SUCCESS;

@@ -507,8 +500,8 @@
* run --tls-verify script

*/
static = result_t
-verify_cert_c= all_command(const char *verify_command, struct env_set *es,
- int cert_dep= th, char *subject)

+v= erify_cert_call_command(const char *verify_command, struct env_set *es, int= cert_depth,
+ = char *subject)
{
in= t ret;
struct gc_arena gc =3D gc_new();
@@ -527,22 +520,20 @@


if (ret)
{
- = msg(D_HANDSHAKE, "VERIFY SCRIPT OK: depth=3D%d, %s",=
- cert_depth, subj= ect);
+ msg(D_= HANDSHAKE, "VERIFY SCRIPT OK: depth=3D%d, %s", cert_depth, subjec= t);
return SUCCESS;
}<= br>
- msg(D_H= ANDSHAKE, "VERIFY SCRIPT ERROR: depth=3D%d, %s",
- cert_depth, subject);- return FAILURE; = /* Reject connection */
+ msg(D_HANDSHAKE, "VERIFY SCRIPT ERROR: depth=3D%d, %s",= cert_depth, subject);
-verify_check_crl_dir(const char= *crl_dir, openvpn_x509_cert_t *cert,
- const char *subject, int cert_depth)
+verify_check_crl_dir(= const char *crl_dir, openvpn_x509_cert_t *cert, const char *subject,=
+ int c= ert_depth)
{
result_t ret =3D FAILURE= ;
char fn[256];
@@ -552,8 +543,8 @@
char *serial =3D backend_x509_get_serial(cert, &gc);=
if (!serial)
{
- msg(D_HANDSHAKE, "VERIFY C= RL: depth=3D%d, %s, serial number is not available",
- cert_depth, subject);
+ msg(D_HANDSHAKE, = "VERIFY CRL: depth=3D%d, %s, serial number is not available", cer= t_depth,
+ = subject);
goto cleanup;
}

@@ -565,8 +556,8 @@
fd= =3D platform_open(fn, O_RDONLY, 0);
if (fd >=3D 0)=
{
- msg(D_HANDSHAKE, "VERIFY CRL: depth=3D%d, %s, serial=3D%s is= revoked",
- = cert_depth, subject, serial);
+ msg(D_HANDSHAKE, "VERIFY CRL: depth=3D%d, %s, = serial=3D%s is revoked", cert_depth, subject,
+ serial);
= goto cleanup;
}

@@= -600,8 +591,10 @@
char *subject =3D x509_get_subject(= cert, &gc);
if (!subject)
{
- msg(D_TLS_ERROR= S, "VERIFY ERROR: depth=3D%d, could not extract X509 "
= - "subject string= from certificate", cert_depth);
+ msg(D_TLS_ERRORS,
+ "VERIFY ERROR: depth=3D%d, could n= ot extract X509 "
+ cert_depth);
= goto cleanup;
}

@@ -613,19 +606,19 @@
struct buffer buf =3D= alloc_buf_gc(256, &gc);
for (int i =3D 0; opt->= ;x509_username_field[i] !=3D NULL; i++)
{
- char username[TLS_USERNAME= _LEN+1] =3D {0}; /* null-terminated */

+ char username[TLS_USERNAME_LEN + 1] =3D { 0 }; /= * null-terminated */

- if (SUCCESS !=3D backend_x509_get_username(usernam= e, sizeof(username),
- = opt->x509_username_field= [i], cert))
+ = if (SUCCESS
+ = !=3D backend_x509_get_username(username, sizeof(username), opt->x509= _username_field[i],
+= cert))
{<= /span>
if (!cert_depth)
= {
- msg(= D_TLS_ERRORS, "VERIFY ERROR: could not extract %s from X509 "
+ msg(D_T= LS_ERRORS,
+ = "VERIFY ERROR: could not extract %s from X509 "=
"subject string ('%s') -- note = that the field length is "
"= limited to %d characters",
- opt->x509_username_field[i],
- subject,
=
- TLS_USER= NAME_LEN);
+ = opt->x509_username_field[i], subject, TLS_USERNAME_LEN);
goto cleanup;
}
break;
@@ -634,11 +627,11 @@
{
if (!cert_depth)
{
- msg(D_TLS_ERRORS, "VERIFY ERROR: could not append= %s from X509 "
= + msg(D_TLS_ERRORS,
+ "VERIFY ERROR: could not append %s = from X509 "
"certificate -- = note that the username length is "
= "limited to %d characters",
- opt->x509_username_field[i],
- buf.cap= acity - 1);
+ = opt->x509_username_field[i], buf.capacity - 1);
goto cleanup;

} break;
@@ -648,8 +641,10 @@
<= span> char *common_name =3D BSTR(&buf);

if (!c= ommon_name)
{
- msg(D_TLS_ERRORS, "VERIFY ERROR: depth=3D%d, coul= d not extract X509 "
- "username string from certificate", cert_depth);<= /span>
+ msg(D_TLS_ER= RORS,
+ &q= uot;VERIFY ERROR: depth=3D%d, could not extract X509 "
+ "username string f= rom certificate",

- msg(D_TLS_ERRORS, "TLS= Error: Convoluted certificate chain detected with depth [%d] greater than = %d", cert_depth, MAX_CERT_DEPTH);
- goto cleanup; /* Reject connecti= on */
+ msg(D_= TLS_ERRORS,
+ = "TLS Error: Convoluted certificate chain detected with depth [%d] = greater than %d",
+ goto cleanup; /* Reject connection */
}

if (cert_depth =3D= =3D opt->verify_hash_depth && opt->verify_hash)
{

- stru= ct buffer cert_fp =3D {0};
+ struct buffer cert_fp =3D { 0 };
switch (opt->verify_hash_algo)
= {
@@ -683,8 +680,10 @@
* = value in an enumerated type. So if this unlikely scenario
= * happens, consider this a failure
= */
- = msg(M_WARN, "Unexpected invalid algorithm used with "
- &quo= t;--verify-hash (%i)", opt->verify_hash_algo);
+ msg(M_WARN,
+ "Unexpe= cted invalid algorithm used with "

+ "--verify-hash (%i)",
+ opt= ->verify_hash_algo);
ret =3D FAILURE;
goto cleanup;
}
@@ -693,8 +692,7 @@

= while (current_hash)
{
- if (memcmp_constant_time(BPTR(&= cert_fp), current_hash->hash,
- BLEN(&cert_fp)) =3D=3D = 0)
+ if (m= emcmp_constant_time(BPTR(&cert_fp), current_hash->hash, BLEN(&ce= rt_fp)) =3D=3D 0)
{
= break;
}
@@ -703,11 +70= 1,12 @@

if (!current_hash)
{
-= const char *hex_fp =3D format_hex_ex(BPTR(&cert_fp), BLEN(&= amp;cert_fp),
- = 0, 1, ":", &gc);
- msg(D_TLS_ERROR= S, "TLS Error: --tls-verify/--peer-fingerprint "
+ const char *hex_fp =3D f= ormat_hex_ex(BPTR(&cert_fp), BLEN(&cert_fp), 0, 1, ":", &= amp;gc);
+ = msg(D_TLS_ERRORS,
+ = "TLS Error: --tls-verify/--peer-fingerprint "
"certificate hash verification failed. (g= ot certificate "
-= "fingerprint: %s)", hex_fp);
+ "fingerprint: %s)&q= uot;,
+ = hex_fp);
goto cleanup;
= }
}
@@ -722,14 +721,14 @@
if (opt->export_peer_cert_dir)
= {
- p= em_export_fname =3D platform_create_temp_file(opt->export_peer_cert_dir,=
- = "pef", &gc);
+ pem_export_fname =3D platfor= m_create_temp_file(opt->export_peer_cert_dir, "pef", &gc);=

- = if (!pem_export_fname
- || !verify_cert_cert_export_env(opt->es, cert, pem_expo= rt_fname))
+ i= f (!pem_export_fname || !verify_cert_cert_export_env(opt->es, cert, pem_= export_fname))
{
- msg(D_TLS_ERRORS, "TLS Error: Failed t= o export certificate for "
- "--tls-export-cert in %s", opt->expo= rt_peer_cert_dir);
+ = msg(D_TLS_ERRORS,
+ "TLS Error: Failed to export certificate for = "
+ = "--tls-export-cert in %s",
+ opt->export_peer_cert_dir); goto cleanup;
}
}

@@ -752,8 +751,8 @@
}=

/* run --tls-verify script */
- if (opt->verify_command &am= p;& SUCCESS !=3D verify_cert_call_command(opt->verify_command,
- = opt->es, cert_depth, subject))
+ if (opt->verif= y_command
+ &a= mp;& SUCCESS !=3D verify_cert_call_command(opt->verify_command, opt-= >es, cert_depth, subject))
{
= goto cleanup;
}
@@ -786,7 +785,7 @@=
verify_cert_cert_delete_env(opt->es, pem_export_fn= ame);
if (ret !=3D SUCCESS)
{
- tls_clear_error()= ; /* always? */
+ = tls_clear_error(); /* always? */
sessi= on->verified =3D false; /* double sure? */
}=

@@ -796,9 +795,9 @@
}
/* *********************************************= ******************************
-* Functions for the management of deferred authentication when usi= ng
-* user/password aut= hentication.
-*********= ****************************************************************** */
+ * Functions for the mana= gement of deferred authentication when using
+ * user/password authentication.
+ ************************************= *************************************** */

void

auth_set_client_reason(struct tls_multi *multi, co= nst char *client_reason)
@@ -884,15 +883,13 @@
* @returns false The file had an invlaid format or another error oc= cured

*/
static bool
-key_state_check_auth_pending_file(struct = auth_deferred_status *ads,
- struct tls_multi *multi,
<= span style=3D"color: hsl(120, 100%, 40%);">+key_state_check_auth_pending_fi= le(struct auth_deferred_status *ads, struct tls_multi *multi,

struct tls_session *session)
{
bool ret =3D true;
if = (ads->auth_pending_file)
{
- struct buffer_list *lines =3D buffer_l= ist_file(ads->auth_pending_file,
- 1024);
+ struct buffer= _list *lines =3D buffer_list_file(ads->auth_pending_file, 1024);<= br> if (lines && lines->head)
= {
/* Must have at least three lines. furt= her lines are ignored for
@@ -900,7 +897,7 @@
if (!lines->head || !lines->head->next || !lines-&= gt;head->next->next)

{
= msg(M_WARN, "auth pending control file is not at least= "
- = "three lines long.");
+ "three lines long."= );
buffer_list_free(lines);
return false;

}
<= span>@@ -927,10 +924,13 @@

char buf[128];<= /span>
snprintf(buf, sizeof(buf),
"Authentication failed, required pending au= th "

- = "method '%s' not supported", pending_method)= ;
+ = "method '%s' not supported",
+ pending_method);=
auth_set_client_reason(multi, buf);
- msg(M_INFO,= "Client does not supported auth pending method "
- "'%s'= ;", pending_method);

+ msg(M_INFO,
+ "Client does not supported auth pend= ing method "
+ = "'%s'",
+ pending_method);
ret =3D false;

}
= else
@@ -975,8 +975,7 @@
* @return true if file creation was successful

*/
static bool
-key_state_gen_auth_control_files(struct auth_deferred_status *ads,
- = const struct tls_options *opt)
+key_state_gen_auth_control_files(struct auth_deferred_sta= tus *ads, const struct tls_options *opt)
{
struct gc_arena gc =3D gc_new();


@@= -1017,7 +1016,6 @@
{
= ret =3D BSTR(&reason);
}
-
}
= return ret;
}
@@ -1088,8 +1086,7 @@
#endif
ASSERT(auth_plugin < 4 &am= p;& auth_script < 4 && auth_man < 4);

- if (auth_plugin= =3D=3D ACF_FAILED || auth_script =3D=3D ACF_FAILED
- || auth_man =3D=3D ACF_FAILED)<= /span>
+ if (auth_plu= gin =3D=3D ACF_FAILED || auth_script =3D=3D ACF_FAILED || auth_man =3D=3D A= CF_FAILED)
{
ks->a= uthenticated =3D KS_AUTH_FALSE;
return;=
@@ -1122,7 +1119,7 @@
* with no caching (0) her= e as well to have the same super quick initial
* reaction= .
*/
= -static time_t cache_intervals[] =3D {0, 0, 0, 0, 0, 1, 1, 2, 2, 4, 8};
+static time_t cache_int= ervals[] =3D { 0, 0, 0, 0, 0, 1, 1, 2, 2, 4, 8 };
<= br> /**
* uses cache_intervals times to determine i= f we should update the
@@ -1189,8 +1186,10 @@
{

struct gc_arena gc =3D gc_new();<= br> const struct key_state *ks =3D get_primary_key(multi);
- const char *plug= in_message =3D key_state_check_auth_failed_message_file(&ks->plugin_= auth, &gc);
- = const char *script_message =3D key_state_check_auth_failed_message_file(&= amp;ks->script_auth, &gc);
+ const char *plugin_message =3D
+ key_state_check_auth_failed_m= essage_file(&ks->plugin_auth, &gc);
+ const char *script_message =3D+ key_state_check_a= uth_failed_message_file(&ks->script_auth, &gc);
=
if (plugin_message)
{
@@ -1234,7 +1233,8 @@
* to indicate auth f= ailure/success.
*/
bool
-tls_authenticate_key(struct tls_multi = *multi, const unsigned int mda_key_id, const bool auth, const char *client_= reason)
+tls_authenti= cate_key(struct tls_multi *multi, const unsigned int mda_key_id, const bool= auth,
+ = const char *client_reason)
{
= bool ret =3D false;
if (multi)
@@ -127= 0,8 +1270,7 @@
* Check if the script/plugin left a messag= e in the auth failed message
* file and relay it to the u= ser */
static void
-check_for_client_reason(struct tls_multi *multi,
- struct aut= h_deferred_status *status)

+check_for_client_reason(struct tls_multi *multi, struct auth_deferre= d_status *status)
{
struct gc_arena g= c =3D gc_new();
const char *msg =3D key_state_check_au= th_failed_message_file(status, &gc);
@@ -1292,7 +1291,7= @@
struct argv argv =3D argv_new();
= const char *tmp_file =3D "";
int retval = =3D OPENVPN_PLUGIN_FUNC_ERROR;
- struct key_state *ks =3D &session->key[KS_PRIMARY]; = /* primary key */
+= struct key_state *ks =3D &session->key[KS_PRIMARY]; /* primary k= ey */

/* Set environmental variables= prior to calling script */
setenv_str(session->opt= ->es, "script_type", "user-pass-verify");
= @@ -1304,8 +1303,7 @@
{
= struct status_output *so;

- tmp_file =3D platform_create_temp_file(sessi= on->opt->tmp_dir, "up",
- &gc);
+ tmp_file =3D p= latform_create_temp_file(session->opt->tmp_dir, "up", &= gc);
if (tmp_file)
{
so =3D status_open(tmp_file, 0, -1, NULL, STATUS_O= UTPUT_WRITE);
@@ -1330,15 +1328,17 @@
= /* pre-create files for deferred auth control */
if (!= key_state_gen_auth_control_files(&ks->script_auth, session->opt))=
{
- msg(D_TLS_ERRORS, "TLS Auth Error (%s): "
- "could not create = deferred auth control file", __func__);

+ msg(D_TLS_ERRORS,
+ "TLS Auth Error (%s): "= ;
+ "= could not create deferred auth control file",
+ __func__);
= retval =3D OPENVPN_PLUGIN_FUNC_ERROR;
goto err= or;
}

/* call c= ommand */
- int scri= pt_ret =3D openvpn_run_script(&argv, session->opt->es, S_EXITCODE= ,
- = "--auth-user-pass-verify");
+ int script_ret =3D
+ openvpn_run_script(&ar= gv, session->opt->es, S_EXITCODE, "--auth-user-pass-verify"= );

switch (script_ret)
{ case 0:
@@ -1358,13 +1358,11 @@
= {
/* Check if we the plugin has written= the pending auth control
* file and send the pen= ding auth to the client */
- if (!key_state_check_auth_pending_file(&ks->script_auth= ,
- = multi, session))
+ if (!key_state_check_auth_pending_file(&= ;ks->script_auth, multi, session))
{
= retval =3D OPENVPN_PLUGIN_FUNC_ERROR;
= key_state_rm_auth_control_files(&ks->script_auth);=
}
-<= /span>
}
else
{
@@ -1395,8 +1393,8 @@
struct tls_session = *session =3D &multi->session[TM_ACTIVE];
setenv= _str(session->opt->es, "crresponse", cr_response);
- plugin_c= all(session->opt->plugins, OPENVPN_PLUGIN_CLIENT_CRRESPONSE, NULL,
- NULL, se= ssion->opt->es);
+ = session->opt->es);

= setenv_del(session->opt->es, "crresponse");
<= span> }

@@ -1405,7 +1403,6 @@
void<= br> verify_crresponse_script(struct tls_multi *multi, const char *cr_= response)
{
-
struct tls_session *session =3D &multi->= ;session[TM_ACTIVE];

if (!session-&g= t;opt->client_crresponse_script)
@@ -1425,8 +1422,7 @@

if (tmp_file)
{<= /span>
- struct status_= output *so =3D status_open(tmp_file, 0, -1, NULL,
- = STATUS_OUTPUT_WRITE);
+ struct status_output *so =3D status_open(tmp_file, 0, -1, NULL, S= TATUS_OUTPUT_WRITE);
status_printf(so, "%s&qu= ot;, cr_response);
if (!status_close(so)) {
@@ -1463,7 +1459,7 @@
= const struct user_pass *up)
{
int retval =3D OPENVPN_PLUGIN_FUNC_ERROR;
- struct key_state *ks =3D &sessi= on->key[KS_PRIMARY]; /* primary key */
+ struct key_state *ks =3D &session->ke= y[KS_PRIMARY]; /* primary key */

/* = set password in private env space */
setenv_str(sessio= n->opt->es, "password", up->password);
@= @ -1471,13 +1467,16 @@
/* generate filename for deferr= ed auth control file */
if (!key_state_gen_auth_contro= l_files(&ks->plugin_auth, session->opt))
{
- msg(D_TLS_ERROR= S, "TLS Auth Error (%s): "
- "could not create deferred auth control fil= e", __func__);
+= msg(D_TLS_ERRORS,
+ "TLS Auth Error (%s): "
+ "could not create deferr= ed auth control file",
+ __func__);
return retval;
}

/* call command *= /
- retval =3D plugi= n_call(session->opt->plugins, OPENVPN_PLUGIN_AUTH_USER_PASS_VERIFY, N= ULL, NULL, session->opt->es);
+ retval =3D plugin_call(session->opt->plugins, OPE= NVPN_PLUGIN_AUTH_USER_PASS_VERIFY, NULL, NULL,
+ session->opt->es)= ;

if (retval =3D=3D OPENVPN_PLUGIN_F= UNC_DEFERRED)
{
@@ -1516,18 +1515,18 @= @
#define KMDA_DEF 3

static int

-verify_us= er_pass_management(struct tls_session *session,
- const struct user_pas= s *up)
+verify_user_p= ass_management(struct tls_session *session, const struct user_pass *up)
{
int retval =3D KMDA_ERROR;
<= span style=3D"color: hsl(0, 100%, 40%);">- struct key_state *ks =3D &= ;session->key[KS_PRIMARY]; /* primary key */

+ struct key_state *ks =3D &session= ->key[KS_PRIMARY]; /* primary key */

= /* set username/password in private env space */
s= etenv_str(session->opt->es, "password", up->password);

if (management)
= {
- management_n= otify_client_needing_auth(management, ks->mda_key_id, session->opt-&g= t;mda_context, session->opt->es);
+ management_notify_client_needing_auth(managemen= t, ks->mda_key_id, session->opt->mda_context,
+ = session->opt->es);
}

setenv_del(session->opt->es, "password");=
@@ -1539,8 +1538,7 @@
#endif /* ifdef ENA= BLE_MANAGEMENT */

static bool
= -set_verify_user_pass_env(struct = user_pass *up, struct tls_multi *multi,
- struct tls_session *session)
+set_verify_user_pass_en= v(struct user_pass *up, struct tls_multi *multi, struct tls_session *sessio= n)
{
/* Is username defined? */
if ((session->opt->ssl_flags & SSLF_AUTH_USER_PAS= S_OPTIONAL) || strlen(up->username))
@@ -1576,7 +1574,8 = @@
msg(D_TLS_ERRORS,
= "TLS Auth Error: --username-as-common name specified and "=
"username is longer than the maximum permitted = Common Name "
- = "length of %d characters", TLS_USERNAME_LEN);
= + "length of %d= characters",
+ = TLS_USERNAME_LEN);
return false;=
}
else
@@ -1592,10 +159= 1,9 @@
* result of the username/password verification
*/
void
-verify_user_pass(struct user_pass *up, struct tls_multi *= multi,
- = struct tls_session *session)
+verify_user_pass(struct user_pass *up, struct tls_multi *multi, = struct tls_session *session)
{
- struct key_state *ks =3D &session->key= [KS_PRIMARY]; /* primary key */
+ struct key_state *ks =3D &session->key[KS_PRIMA= RY]; /* primary key */

ASSERT(up &am= p;& !up->protected);

@@ -1623,9 +1= 621,10 @@
if (multi->locked_original_username
&& strncmp(up->username, multi->locked_or= iginal_username, sizeof(up->username)) =3D=3D 0)
{<= /span>
- msg(D_MULTI_LO= W, "TLS: Replacing client provided username '%s' with "
- "usern= ame from override-user '%s'", up->username,
- multi->locked_username= );

+ msg(D_MUL= TI_LOW,
+ = "TLS: Replacing client provided username '%s' with "
+ "userna= me from override-user '%s'",
+ up->username, multi->locked_usernam= e);
strncpy(up->username, multi->locked_user= name, sizeof(up->username));
}

@@ -1661,7 +1660,8 @@
* We do n= ot want the EXPIRED or EMPTY USER flags here so check
= * for equality with AUTH_TOKEN_HMAC_OK
= */
- msg(= M_WARN, "TLS: Username/auth-token authentication "
+ msg(M_WARN,

= + "TLS: Use= rname/auth-token authentication "
&qu= ot;succeeded for username '%s'",
= up->username);
skip_auth =3D true;
@@ -1670,8 +1670,10 @@
{
wipe_auth_token(multi);

ks->= ;authenticated =3D KS_AUTH_FALSE;
- msg(M_WARN, "TLS: Username/auth-token authenti= cation "
- = "failed for username '%s'", up->username);
+ msg(M_WARN,=
+ &qu= ot;TLS: Username/auth-token authentication "
+ "failed for username = 9;%s'",
+ = up->username);
return;<= br> }
}
@@ -1716,14 +171= 8,14 @@
bool plugin_ok =3D plugin_status =3D=3D OPENVP= N_PLUGIN_FUNC_SUCCESS
|| plugin_statu= s =3D=3D OPENVPN_PLUGIN_FUNC_DEFERRED;

- bool script_ok =3D script_status = =3D=3D OPENVPN_PLUGIN_FUNC_SUCCESS
- || script_status =3D=3D OPENVPN_PLUGIN_F= UNC_DEFERRED;
+ bo= ol script_ok =3D script_status =3D=3D OPENVPN_PLUGIN_FUNC_SUCCESS+ || scrip= t_status =3D=3D OPENVPN_PLUGIN_FUNC_DEFERRED;

<= span> if (script_ok && plugin_ok && tls_lock_username(m= ulti, up->username)

#ifdef ENABLE_MANAGEMENT
= && man_def_auth !=3D KMDA_ERROR
#en= dif
- )+ )
{=
ks->authenticated =3D KS_AUTH_TRUE;
= if (plugin_status =3D=3D OPENVPN_PLUGIN_FUNC_DEFERRED=
@@ -1757,8 +1759,7 @@
* to store th= e auth-token in multi->auth_token, so
* th= e initial timestamp and session id can be extracted from it
*/

- = if (!multi->auth_token
- && (ks->auth_token_state_flags &= AUTH_TOKEN_HMAC_OK)
= + if (!multi->auth_token && (ks->auth_token_state_= flags & AUTH_TOKEN_HMAC_OK)
&&= !(ks->auth_token_state_flags & AUTH_TOKEN_EXPIRED))
{

multi->auth_token =3D s= trdup(up->password);
@@ -1772,8 +1773,7 @@
}


msg(D_HANDSHAKE, &= quot;TLS: Username/Password authentication %s for username '%s' %s&= quot;,
- (ks= ->authenticated =3D=3D KS_AUTH_DEFERRED) ? "deferred" : "= succeeded",
- = up->username,
+ (ks->authenticated =3D=3D KS_AUTH_DEFERRED) ? "defe= rred" : "succeeded", up->username,
= (session->opt->ssl_flags & SSLF_USERNAME_AS_COMMON_NAME) ?= "[CN SET]" : "");
}
else

@@ -1786,7 +1786,7 @@
void
verify_final_auth_checks(struct tls_multi *multi, struct tls= _session *session)
{
- struct key_state *ks =3D &session->key[KS_PRIMAR= Y]; /* primary key */
+ struct key_state *ks =3D &session->key[KS_PRIMARY]; /* pr= imary key */

/* While it shouldn'= ;t really happen, don't allow the common name to be NULL */
<= span> if (!session->common_name)

@@ -1800,9 +1800,9 = @@
const char *cn =3D session->common_name;
if (cn && strcmp(cn, multi->locked_cn))
{
- multi-&= gt;locked_cn,
- = cn);
+ = msg(D_TLS_ERRORS,
+ multi->locked_cn= , cn);

/* change the common = name back to its original value and disable the tunnel */
= set_common_name(session, multi->locked_cn);
= @@ -1816,7 +1816,8 @@
const struct cert_hash_set *= chs =3D session->cert_hash_set;
if (chs &&a= mp; !cert_hash_compare(chs, multi->locked_cert_hash_set))
{

- = msg(D_TLS_ERRORS, "TLS Auth Error: TLS object CN=3D%s client-provid= ed SSL certs unexpectedly changed during mid-session reauth",+ msg(D_TLS_ERRORS= ,
+ &q= uot;TLS Auth Error: TLS object CN=3D%s client-provided SSL certs unexpected= ly changed during mid-session reauth",
= session->common_name);

= /* disable the tunnel */
@@ -1830,15 +1831,14 @@
= struct gc_arena gc =3D gc_new();
const char *cn =3D session->common_name;
- const char *path =3D platform= _gen_path(session->opt->client_config_dir_exclusive,

- = cn, &gc);
= + const char *path =3D platform_gen_path(session->opt->client_= config_dir_exclusive, cn, &gc);
if (!cn || !st= rcmp(cn, CCD_DEFAULT) || !platform_test_file(path))
= {
ks->authenticated =3D KS_AUTH_FALSE;
wipe_auth_token(multi);
- msg(D_TLS_ERRORS, "TLS Auth E= rror: --client-config-dir authentication failed for common name '%s'= ; file=3D'%s'",
- session->common_name,
- path ? path : "UNDEF");=
+ msg(D_T= LS_ERRORS,
+ = "TLS Auth Error: --client-config-dir authentication failed for = common name '%s' file=3D'%s'",
+ session->common_name, = path ? path : "UNDEF");
}

gc_free(&gc);
@@ -1852,8 += 1852,7 @@
while (item)
{ struct env_item *next =3D item->next;
- if (item->string
<= span style=3D"color: hsl(0, 100%, 40%);">- && 0 =3D=3D s= trncmp("X509_", item->string, strlen("X509_")))
+ if (item->str= ing && 0 =3D=3D strncmp("X509_", item->string, strlen(= "X509_")))
{
= env_set_del(es, item->string);
}
diff --git a/src/openvpn/ssl_verify.h b/src/openvpn/ssl_verify.h
=
index 76f1e24..fdf6bb5 100644
--- a/src/openvpn/s= sl_verify.h
+++ b/src/openvpn/ssl_verify.h
= @@ -54,25 +54,27 @@
#define TLS_USERNAME_LEN 64
=
/** Structure containing the hash for a single cer= tificate */
-struct cer= t_hash {
- unsigned = char sha256_hash[256/8];
+struct cert_hash
+{
+ unsigned cha= r sha256_hash[256 / 8];
};

/** Structure containing the hashes for a full certificate chain */
-struct cert_hash_set {
+struct cert_hash_set
+{
= struct cert_hash *ch[MAX_CERT_DEPTH]; /**< Array of certificate hashes= */
};

-#define VERIFY_X509_NONE 0
-#define VERIFY_X509_SUBJECT_DN = 1

-#define VERIFY_= X509_SUBJECT_RDN 2
-#define VERIFY_X509_SUBJECT_RDN_PREFIX 3
+#define VERIFY_X509_NONE 0<= br>+#define VERIFY_X509_SUBJECT= _DN 1
+#defin= e VERIFY_X509_SUBJECT_RDN 2
+#define VERIFY_X509_SUBJECT_RDN_PREFIX 3

enum tls_auth_status
{
- TLS_AUTHENTICATION_SUCCEEDED=3D0,
- TLS_AUTHENTICATION_FA= ILED=3D1,
- TLS_AUTH= ENTICATION_DEFERRED=3D2
+ TLS_AUTHENTICATION_SUCCEEDED =3D 0,
+ TLS_AUTHENTICATION_FAILED =3D 1,
+ TLS_AUTHENTICATION_DEFERRED = =3D 2

};

/**
= @@ -91,8 +93,7 @@
*
* @return = Current authentication status of the tls_multi
= */
-enum tls_auth_statu= s
-tls_authentication_s= tatus(struct tls_multi *multi);
+enum tls_auth_status tls_authentication_status(struct tls_multi= *multi);

/** Check whether the \a ks \c= key_state has finished the key exchange part
* of the O= penVPN hand shake. This is that the key_method_2read/write
= @@ -155,8 +156,7 @@
* @param session The session to= set the common name for
* @param common_name The name = to set the common name to
*/
-void
-set_common_name(struct tls_session *session, const char *common_nam= e);
+void set_common_= name(struct tls_session *session, const char *common_name);

/**
* Returns the username field for = the given tunnel
@@ -187,8 +187,7 @@
* @p= aram session The current TLS session
*
*/

-void verify_u= ser_pass(struct user_pass *up, struct tls_multi *multi,
- struct tls_session = *session);
+void veri= fy_user_pass(struct user_pass *up, struct tls_multi *multi, struct tls_sess= ion *session);


/**
@@ -203,8 +202,7 @@
* @return t= rue if name is under limit or username-as-common-name
* = is not active
*/
-bool ssl_verify_username_length(struct tls= _session *session,
- = const char *username);
+bool ssl_verify_username_length(struct tl= s_session *session, const char *username);

/**

* Runs the --client-crresponse script if one is de= fined.
@@ -214,8 +212,7 @@
* the files fo= r the deferred auth like the management commands.
*
*/
-void
-verify_crresponse_scrip= t(struct tls_multi *multi, const char *cr_response);
+void verify_crresponse_script(struct tls_= multi *multi, const char *cr_response);

= /**
* Call the plugin OPENVPN_PLUGIN_CLIENT_CRRESPONSE.
@@ -224,8 +221,7 @@
* that it does not dir= ectly participate in the authentication but rather
* shou= ld set the files for the deferred auth like the management commands.=
*/
-void
-verify_crresponse_plugin= (struct tls_multi *multi, const char *cr_response);
+void verify_crresponse_plugin(struct tls_= multi *multi, const char *cr_response);

= /**
* Perform final authentication checks, including lock= ing of the cn, the allowed
@@ -242,7 +238,7 @@
{

const struct x509_track *next;
= const char *name;
= -#define XT_FULL_CHAIN (1<<0)
+#define XT_FULL_CHAIN (1 << 0)
u= nsigned int flags;
int nid;
};=
@@ -251,11 +247,11 @@
* Certificate checking fo= r verify_nsCertType
*/
/** Do not perfor= m Netscape certificate type verification */
-#define NS_CERT_CHECK_NONE (0)
+#define NS_CERT_CHECK_NONE (0) /** Do not perform Netscape certificate type verification */
-#define NS_CERT_CHECK_SERVE= R (1<<0)
+#defi= ne NS_CERT_CHECK_SERVER (1 << 0)
/** Do not perform = Netscape certificate type verification */
-#define NS_CERT_CHECK_CLIENT (1<<1)
+#define NS_CERT_CHECK_CLIENT (1 &= lt;< 1)


/** Require keyUsage to be pr= esent in cert (0xFFFF is an invalid KU value) */
#define O= PENVPN_KU_REQUIRED (0xFFFF)
@@ -264,7 +260,8 @@
<= span> * TODO: document

*/
#ifdef ENABLE= _MANAGEMENT
-bool tls_a= uthenticate_key(struct tls_multi *multi, const unsigned int mda_key_id, con= st bool auth, const char *client_reason);
+bool tls_authenticate_key(struct tls_multi *multi, co= nst unsigned int mda_key_id, const bool auth,
+ const char *client_reas= on);

#endif

= diff --git a/src/openvpn/ssl_verify_backend.h b/src/openvpn/ssl_verif= y_backend.h
index 03f591c..a0559c9 100644
-= -- a/src/openvpn/ssl_verify_backend.h
+++ b/src/openvpn/ssl= _verify_backend.h
@@ -32,7 +32,11 @@
/**
* Result of verification function
*/
-typedef enum { SUCCESS = =3D 0, FAILURE =3D 1 } result_t;
+typedef enum
+{
+ SUCCESS = =3D 0,
+ FAILURE = =3D 1
+} result_t;

/*
* Backend support fun= ctions.
@@ -94,8 +98,7 @@
*
* @return a string containing the certificate fingerprint=

*/
-= struct buffer x509_get_sha1_fingerprint(openvpn_x509_cert_t *cert,- = struct gc_arena *gc);
+struct buffer x509_get_sha1_fingerprint(openvpn_x509_cert_t *ce= rt, struct gc_arena *gc);

/**
= * Retrieve the certificate's SHA256 fingerprint.
@@ -105,8 +108,7 @@

*
* @return = a string containing the certificate fingerprint
*= /
-struct buffer x509_g= et_sha256_fingerprint(openvpn_x509_cert_t *cert,
- struct= gc_arena *gc);
+stru= ct buffer x509_get_sha256_fingerprint(openvpn_x509_cert_t *cert, struct gc_= arena *gc);

/*
* Retri= eve the certificate's username from the specified field.
@@ -121,8 +123,8 @@

*
* @return = \c FAILURE, \c or SUCCESS
*/
-result_t backend_x509_get_username(char *c= ommon_name, int cn_len,
- char *x509_username_field, openvpn_x50= 9_cert_t *peer_cert);
+result_t backend_x509_get_username(char *common_name, int cn_len, char *x= 509_username_field,
+= openvpn_x509_cert_t *peer_cert);<= br>
#ifdef ENABLE_X509ALTUSERNAME
= /**
@@ -157,8 +159,7 @@
* @return = String representation of the certificate's serial number * in hex notation, or NULL on error.<= br> */
-char *ba= ckend_x509_get_serial_hex(openvpn_x509_cert_t *cert,
- struct gc= _arena *gc);
+char *b= ackend_x509_get_serial_hex(openvpn_x509_cert_t *cert, struct gc_arena *gc);=

/*
* Write the certif= icate to the file in PEM format.
@@ -168,8 +169,7 @@=
*
* @return \c FAILURE, \c or SU= CCESS
*/
-result_t backend_x509_write_pem(openvpn_x509_cert_t *cert,
<= span style=3D"color: hsl(0, 100%, 40%);">- c= onst char *filename);

+result_t backend_x509_write_pem(openvpn_x509_cert_t *cert, const char *fi= lename);

/*
* Save X50= 9 fields to environment, using the naming convention:
@@ -1= 93,8 +193,8 @@
* @param gc Garbage collection = arena for temp data
*
*/
-void x509_track_add(const struct x50= 9_track **ll_head, const char *name,

- int msglevel, struct gc_arena *gc);
+void x509_track_add(cons= t struct x509_track **ll_head, const char *name, int msglevel,
+ struct gc_ar= ena *gc);


/*
* Save X5= 09 fields to environment, using the naming convention:
@@ -= 216,8 +216,8 @@
* @param cert_depth Depth of the certi= ficate
* @param cert Certificate to set the envi= ronment for
*/
-void x509_setenv_track(const struct x509_track *xt, struct env_s= et *es,
- = const int depth, openvpn_x509_cert_t *x509);
+void x509_setenv_track(const struct x509_= track *xt, struct env_set *es, const int depth,
+ openvpn_x509_cert_t *x50= 9);

/*
* Check X.509 N= etscape certificate type field, if available.
diff --git a/= src/openvpn/ssl_verify_mbedtls.c b/src/openvpn/ssl_verify_mbedtls.c<= br>index 43bbde5..cfcfb25 100644
--- a/src/openvpn/ss= l_verify_mbedtls.c
+++ b/src/openvpn/ssl_verify_mbedtls.c
@@ -46,10 +46,9 @@
#define MAX_SUBJECT_LENG= TH 256

int
-verify_callback(void *session_obj, mbedtls_x509_crt= *cert, int cert_depth,
- uint32_t *flags)
+verify_callback(void *session_obj, mbedtls_x509_crt *cert, i= nt cert_depth, uint32_t *flags)
{
- struct tls_session *session =3D (struct tl= s_session *) session_obj;
+ struct tls_session *session =3D (struct tls_session *)session_obj= ;
struct gc_arena gc =3D gc_new();

ASSERT(cert);
@@ -71,8 +70,7 @@<= br> * Clearing these flags relies on verify_cert will later = rejecting a
* certificate that has no matching fi= ngerprint.
*/
- uint32_t flags_ignore =3D MBEDTLS_X509_BADCERT_NO= T_TRUSTED
- = | MBEDTLS_X509_BADCERT_EXPIRED
+ uint32_t flags_ignore =3D MBEDTLS_X5= 09_BADCERT_NOT_TRUSTED | MBEDTLS_X509_BADCERT_EXPIRED
= | MBEDTLS_X509_BADCERT_FUTURE;
= *flags =3D *flags & ~flags_ignore;
}
@@ -85,9 +83,10 @@
char *subject =3D x= 509_get_subject(cert, &gc);
char *serial =3D b= ackend_x509_get_serial(cert, &gc);

- ret =3D mbedtls_x509_crt_verify_= info(errstr, sizeof(errstr)-1, "", *flags);
- if (ret <=3D 0 && !snpri= ntf(errstr, sizeof(errstr),
- "Could not retrieve error stri= ng, flags=3D%" PRIx32, *flags))
+ ret =3D mbedtls_x509_crt_verify_info(errstr, sizeo= f(errstr) - 1, "", *flags);
+ if (ret <=3D 0
+ && !snprintf(errstr, sizeof(err= str), "Could not retrieve error string, flags=3D%" PRIx32,=
+ *= flags))
{
errstr[0] = =3D '\0';
}
@@ -98,13 +97,= 15 @@

if (subject)
{

- = msg(D_TLS_ERRORS, "VERIFY ERROR: depth=3D%d, subject=3D%s, serial= =3D%s: %s",
- = cert_depth, subject, serial ? serial : "<not available&g= t;", errstr);
+ = msg(D_TLS_ERRORS, "VERIFY ERROR: depth=3D%d, subject=3D%s, = serial=3D%s: %s", cert_depth,
+ subject, serial ? serial : "<not ava= ilable>", errstr);
}
= else
{
- msg(D_TLS_ERRORS, "VERIFY ERROR: depth=3D%d,= (could not extract X509 "
- "subject string from certificate): %s",= cert_depth, errstr);
+ msg(D_TLS_ERRORS,
+ "VERIFY ERROR: depth=3D%d, (could not extr= act X509 "
+ = "subject string from certificate): %s",
+ cert_depth, errst= r);

}

/= * Leave flags set to non-zero to indicate that the cert is not ok */=
@@ -127,20 +128,18 @@
#endif

result_t
- char *x509_username_= field, mbedtls_x509_crt *cert)
+backend_x509_get_username(char *cn, int cn_len, char *x509_usern= ame_field, mbedtls_x509_crt *cert)
{
= mbedtls_x509_name *name;

- ASSERT( cn !=3D NULL );
+ ASSERT(cn !=3D NULL);

name =3D &cert->subject;
=
/* Find common name */
while (name !=3D= NULL)
{
- if (0 =3D=3D memcmp(name->oid.p, MBEDTLS_OID_AT_CN,
- MB= EDTLS_OID_SIZE(MBEDTLS_OID_AT_CN)))
+ if (0 =3D=3D memcmp(name->oid.p, MBEDTLS_OID_AT_= CN, MBEDTLS_OID_SIZE(MBEDTLS_OID_AT_CN)))
{=
break;
}
@@= -157,13 +156,13 @@
/* Found, extract CN */
= if (cn_len > name->val.len)
{<= br>- memcpy( cn, name->= val.p, name->val.len );
+ memcpy(cn, name->val.p, name->val.len);
cn[name->val.len] =3D '\0';

}
else
{
- memcpy( cn, name->val.p, cn_len);
- cn[cn_len-1] =3D &#= 39;\0';
+ = memcpy(cn, name->val.p, cn_len);
+ cn[cn_len - 1] =3D '\0';
= }

return SUCCESS;
@@ -178,8 +177,7 @@


/* Transform as= n1 integer serial into mbed TLS MPI */
mbedtls_mpi_ini= t(&serial_mpi);
- = if (!mbed_ok(mbedtls_mpi_read_binary(&serial_mpi, cert->serial.p,<= /span>
- = cert->serial.len)))
+ if (!mbed_ok(mbedtls_mpi_read_binary(&serial_= mpi, cert->serial.p, cert->serial.len)))
{
msg(M_WARN, "Failed to retrieve serial from certif= icate.");
goto end;
@@ -210,7= +208,7 @@

buf =3D gc_malloc(len, tr= ue, gc);

- if (mbedtls_x509_serial_gets(buf, len-1, &cert->serial) <= ; 0)
+ if (mbedtls= _x509_serial_gets(buf, len - 1, &cert->serial) < 0)
{

buf =3D NULL;
}
@@ -234,7 +232,7 @@
struct buffer der =3D= {};
buf_set_read(&der, cert->raw.p, cert->r= aw.len);

- if (!crypto_pem_encode("CERTIFICATE", &pem, &de= r, &gc))
+ if = (!crypto_pem_encode("CERTIFICATE", &pem, &der, &gc))<= /span>
{
goto err;
= }
@@ -247,15 +245,13 @@
gc_free(&a= mp;gc);
return SUCCESS;
err:- msg(D_TLS_DEBUG_LOW, "= ;Error writing X509 certificate to file %s",
- filename);
+ msg(D_TLS_DEBUG_LOW, "Error writing X50= 9 certificate to file %s", filename);
gc_free(&am= p;gc);
return FAILURE;
}

static struct buffer
-x509_get_fingerprint(const mbedtls_md_info_t *md_info= , mbedtls_x509_crt *cert,
- struct gc_arena *gc)
+x509_get_fingerprint(const mbedtls_md_info_t *md_= info, mbedtls_x509_crt *cert, struct gc_arena *gc)
{
const size_t md_size =3D mbedtls_md_get_size(md_info);
struct buffer fingerprint =3D alloc_buf_gc(md_size, gc);
@@ -267,26 +263,24 @@
struct buffer<= br> x509_get_sha1_fingerprint(mbedtls_x509_crt *cert, struct gc_arena= *gc)
{
- = cert, gc);
+ return x509_get_fingerprint(mbedtls_md_info_from_type(MBEDTLS_MD_S= HA1), cert, gc);
}

stru= ct buffer
x509_get_sha256_fingerprint(mbedtls_x509_crt *ce= rt, struct gc_arena *gc)
{
- return x509_get_fingerprint(mbedtls_md_info_from_= type(MBEDTLS_MD_SHA256),
+ return x509_get_fingerprint(mbedtls_md_info_f= rom_type(MBEDTLS_MD_SHA256), cert, gc);
}
=
char *
x509_get_subject(mbedtls_x509_cr= t *cert, struct gc_arena *gc)
{
- char tmp_subject[MAX_SUBJECT_LENGTH] =3D {0}= ;
+ char tmp_subje= ct[MAX_SUBJECT_LENGTH] =3D { 0 };
char *subject =3D NU= LL;

int ret =3D 0;
=
- ret =3D mbedtls_x= 509_dn_gets( tmp_subject, MAX_SUBJECT_LENGTH-1, &cert->subject );
+ ret =3D mbedtls_x5= 09_dn_gets(tmp_subject, MAX_SUBJECT_LENGTH - 1, &cert->subject);
if (ret > 0)
{
= /* Allocate the required space for the subject */
@@= -305,7 +299,7 @@
string_mod(value, CC_ANY, CC_CRLF, &= #39;?');
msg(D_X509_ATTR, "X509 ATTRIBUTE nam= e=3D'%s' value=3D'%s' depth=3D%d", name, value, depth)= ;
name_expand_size =3D 64 + strlen(name);
- name_expand =3D (char *) mallo= c(name_expand_size);

= + name_expand =3D (char *)malloc(name_expand_size);
= check_malloc_return(name_expand);
snprintf(name_expan= d, name_expand_size, "X509_%d_%s", depth, name);
= setenv_str(es, name_expand, value);
@@ -318,8 +312,7 @= @
size_t i;
char *val;
=
- if (!(orig= ->tag =3D=3D MBEDTLS_ASN1_UTF8_STRING
- || orig->tag =3D=3D MBEDTLS_ASN1_PRINTABLE_= STRING
+ if (!(ori= g->tag =3D=3D MBEDTLS_ASN1_UTF8_STRING || orig->tag =3D=3D MBEDTLS_AS= N1_PRINTABLE_STRING
|| orig->tag =3D=3D MBEDT= LS_ASN1_IA5_STRING))
{
/* Onl= y support C-string compatible types */
@@ -333,15 +326,15 @= @
return string_alloc("ERROR: embedded nu= ll value", gc);
}
}
- val =3D gc_malloc(orig= ->len+1, false, gc);
+ val =3D gc_malloc(orig->len + 1, false, gc);
= memcpy(val, orig->p, orig->len);
val[orig->= len] =3D '\0';
return val;
}<= /span>

static void
-do_setenv_name(struct env_set *es, const struct x5= 09_track *xt,
- = const mbedtls_x509_crt *cert, int depth, struct gc_arena *gc)=
+do_setenv_name(struct env_= set *es, const struct x509_track *xt, const mbedtls_x509_crt *cert,<= br>+ int depth, s= truct gc_arena *gc)
{
const mbedtls_x= 509_name *xn;
for (xn =3D &cert->subject; xn != =3D NULL; xn =3D xn->next)
@@ -357,7 +350,8 @@ }

void
-x509_track_add(const struct x509_track **ll_hea= d, const char *name, int msglevel, struct gc_arena *gc)
+x509_track_add(const struct x509_track = **ll_head, const char *name, int msglevel,
+ struct gc_arena *gc)
= {
struct x509_track *xt;
ALLOC_O= BJ_CLEAR_GC(xt, struct x509_track, gc);
@@ -372,8 +366,8 @@=
}

void
-x509_setenv_track(const struct x509_t= rack *xt, struct env_set *es,

- const int depth, mbedtls_x509_crt *cert)+x509_setenv_track(const stru= ct x509_track *xt, struct env_set *es, const int depth,
+ mbedtls_x509_crt *cer= t)
{
struct gc_arena gc =3D gc_new();=
while (xt)
@@ -395,8 +389,8 @@=
cert_hash =3D x509_get_sha256_fingerprint(ce= rt, &gc);
}
- fingerprint = =3D format_hex_ex(BPTR(&cert_hash),
- BLEN(&cer= t_hash), 0, 1 | FHE_CAPS, ":", &gc);
+ fingerprint =3D
+ format_hex_e= x(BPTR(&cert_hash), BLEN(&cert_hash), 0, 1 | FHE_CAPS, ":"= ;, &gc);

do_setenv_x509(es, xt->nam= e, fingerprint, depth);
}
= else
@@ -426,29 +420,27 @@

while (name !=3D NULL)
{
- char name_expand[64+8];
+ char name_expan= d[64 + 8];
const char *shortname;
=
- if (0 =3D=3D= mbedtls_oid_get_attr_short_name(&name->oid, &shortname) )
+ if (0 =3D=3D mbed= tls_oid_get_attr_short_name(&name->oid, &shortname))
<= span> {

- = snprintf(name_expand, sizeof(name_expand), "X509_%d_%s",
- cer= t_depth, shortname);
= + snprintf(name_expand, sizeof(name_expand), "X509_%d_%s&qu= ot;, cert_depth, shortname);
}
= else
{
- snprintf(name_expand, sizeof(name_expand), &quo= t;X509_%d_\?\?",
-= cert_depth);
+ snprintf(name_expand, sizeof(name_expand), "= X509_%d_\?\?", cert_depth);
}

for (i =3D 0; i < name->val.len; i++)
{
- if (i >=3D (int) sizeof( s ) - 1)
+ if (i >=3D (int)sizeof(s) - 1= )
{
break;
}

= c =3D name->val.p[i];
- if (c < 32 || c =3D=3D 127 || ( c > 128 && c = < 160 ) )
+ = if (c < 32 || c =3D=3D 127 || (c > 128 && c < 160))
{
s[i] =3D = 9;?';
}
@@ -482,15 +474,13= @@
}

result_t-x509_verify_cert_ku(mbedtls_x5= 09_crt *cert, const unsigned *const expected_ku,
- int expected_len)
= +x509_verify_cert_ku(mbedtls_x5= 09_crt *cert, const unsigned *const expected_ku, int expected_len) {
msg(D_HANDSHAKE, "Validating certifica= te key usage");

if (!mbedtls_x5= 09_crt_has_ext_type(cert, MBEDTLS_X509_EXT_KEY_USAGE))
= {
- msg(D_TLS_E= RRORS,
- &qu= ot;ERROR: Certificate does not have key usage extension");
<= span style=3D"color: hsl(120, 100%, 40%);">+ msg(D_TLS_ERRORS, "= ;ERROR: Certificate does not have key usage extension");

return FAILURE;

}
=
@@ -501,10 +491,9 @@
}

result_t fFound =3D FAILURE;
- for (size_t i =3D 0; SUCCESS !=3D fFound &= & i<expected_len; i++)
+ for (size_t i =3D 0; SUCCESS !=3D fFound && i < ex= pected_len; i++)
{
- if (expected_ku[i] !=3D 0
- && 0 =3D=3D mbedtls_x50= 9_crt_check_key_usage(cert, expected_ku[i]))
+ if (expected_ku[i] !=3D 0 && 0 =3D= =3D mbedtls_x509_crt_check_key_usage(cert, expected_ku[i]))
{

fFound =3D SUCCESS;
}

@@ -542,10 +531,10 @@
= char oid_num_str[1024];
const char *oid_s= tr;

-= if (0 =3D=3D mbedtls_oid_get_extended_key_usage( oid, &oid_= str ))
+ i= f (0 =3D=3D mbedtls_oid_get_extended_key_usage(oid, &oid_str)) {
= - msg(D_HANDSHAKE, "++ Certificate has EKU (str) %s, ex= pects %s",
- = oid_str, expected_oid);
+ msg(D_HANDSHAKE, "++ Certificate has= EKU (str) %s, expects %s", oid_str,
+ expected_oid);
= if (!strcmp(expected_oid, oid_str))
= {
fFound =3D SUCCESS;<= br>@@ -553,11 +542,10 @@
} }

- if (0 < mbedtls_oid_get_numeric_string( oi= d_num_str,
- = sizeof(oid_num_str), oid))<= br>+ if (0 < mbed= tls_oid_get_numeric_string(oid_num_str, sizeof(oid_num_str), oid)) {
= - msg(D_HANDSHAKE, "++ Certificate has EKU (oid) %s, ex= pects %s",
- = oid_num_str, expected_oid);
+ msg(D_HANDSHAKE, "++ Certificate= has EKU (oid) %s, expects %s", oid_num_str,
+ expected_oid);
= if (!strcmp(expected_oid, oid_num_str))
{

fFound =3D SUCC= ESS;
diff --git a/src/openvpn/ssl_verify_mbedtls.h b/src/op= envpn/ssl_verify_mbedtls.h
index 3e380a6..0b2f2d2 100644
--- a/src/openvpn/ssl_verify_mbedtls.h
+++ b/= src/openvpn/ssl_verify_mbedtls.h
@@ -69,8 +69,7 @@ *
* @return The return value is 0 unless a fata= l error occurred.
*/
-int verify_callback(void *session_obj, mbedtls_x509_crt *c= ert, int cert_depth,
- = uint32_t *flags);
+int verify_callback(void *session_obj, mbedtls_x509_crt *c= ert, int cert_depth, uint32_t *flags);

/= ** @} name Function for authenticating a new connection from a remote OpenV= PN peer */

diff --git a/src/openvpn/ssl_v= erify_openssl.c b/src/openvpn/ssl_verify_openssl.c
index 0c= 206e3..6de7e2a 100644
--- a/src/openvpn/ssl_verify_openssl.= c
+++ b/src/openvpn/ssl_verify_openssl.c
@@= -57,7 +57,7 @@
/* get the tls_session pointer */
ssl =3D X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X5= 09_STORE_CTX_idx());
ASSERT(ssl);
- session =3D (struct tls_session *) SSL= _get_ex_data(ssl, mydata_index);
+ session =3D (struct tls_session *)SSL_get_ex_data(ssl, myd= ata_index);
ASSERT(session);
<= br> X509 *current_cert =3D X509_STORE_CTX_get_current_cert(ctx);<= /span>
@@ -81,8 +81,7 @@
{
msg(D_TLS_DEBUG_LOW, "VERIFY WARNING: depth=3D%d, %s: %= s",

X509_STORE_CTX_get_error_depth(ct= x),
- X5= 09_verify_cert_error_string(X509_STORE_CTX_get_error(ctx)),
- subject);

<= span style=3D"color: hsl(120, 100%, 40%);">+ X509_verify_cer= t_error_string(X509_STORE_CTX_get_error(ctx)), subject);

= ret =3D 1;
goto cleanup;
= }
@@ -90,8 +89,8 @@
= /* Remote site specified a certificate, but it's not correct */=
msg(D_TLS_ERRORS, "VERIFY ERROR: depth=3D%d, error= =3D%s: %s, serial=3D%s",
X509_STORE_CTX_g= et_error_depth(ctx),
- = X509_verify_cert_error_string(X509_STORE_CTX_get_error(ctx)),
- subject, ser= ial ? serial : "<not available>");
+ X509_verify_cert_error_string(X5= 09_STORE_CTX_get_error(ctx)), subject,
+ serial ? serial : "<not available>= ;");

ERR_clear_error();

@@ -120,8 +119,7 @@
ret= urn nid =3D=3D NID_subject_alt_name || nid =3D=3D NID_issuer_alt_name;
}

-static
-bool=
+static bool<= br> extract_x509_extension(X509 *cert, char *fieldname, char *out, in= t size)
{
bool retval =3D false;
@@ -129,8 +127,7 @@

if (= !x509_username_field_ext_supported(fieldname))
{
- msg(D_TLS_ERRORS,
- "ERROR= : --x509-username-field 'ext:%s' not supported", fieldname);
+ msg(D_TLS_ERR= ORS, "ERROR: --x509-username-field 'ext:%s' not supported"= ;, fieldname);
return false;
= }

@@ -148,10 +145,10 @@
= numalts =3D sk_GENERAL_NAME_num(extensions);

/* loop through all alternatives */
- for (i =3D 0; i<numalts; i++)=
+ for (i =3D = 0; i < numalts; i++)
{
= /* get a handle to alternative name number i */
- const GENERAL_NAME *name =3D sk= _GENERAL_NAME_value(extensions, i );
+ const GENERAL_NAME *name =3D sk_GENERAL_NAME_v= alue(extensions, i);

switch = (name->type)
{
@@ -174,8 +1= 71,8 @@
break;

default:
- msg(D_TLS_DEBUG, "%s: ignoring gene= ral name field type %i",
- __func__, name->type);
+ msg(D_TLS_DEBUG, = "%s: ignoring general name field type %i", __func__,
+ name->= ;type);

break;
= }
}
@@ -198,8 +195,7 @@
* to contain result is grounds for error).
= */
static result_t
-extract_x509_field_ssl(X509_NAME *x509, const char *field_nam= e, char *out,
- = int size)
+extract_x509_field_ssl(X509_NAME *x509, const char *field_name, char *= out, int size)
{
int lastpos =3D -1;<= /span>
int tmp =3D -1;
@@ -256,13 +252,12 @@<= /span>
}

result_t
-backend_x509_get_username(char *co= mmon_name, int cn_len,

= - char *x509_username_field, X509 *peer_cert)
+backend_x509_get_usernam= e(char *common_name, int cn_len, char *x509_username_field, X509 *peer_cert= )
{
#ifdef ENABLE_X509ALTUSERNAME<= br> if (strncmp("ext:", x509_username_field, 4) =3D=3D = 0)
{
- if (!extract_x509_extension(peer_cert, x509_username_field+4, c= ommon_name, cn_len))
= + if (!extract_x509_extension(peer_cert, x509_username_field + 4, co= mmon_name, cn_len))
{
= return FAILURE;
}
@@ -271,10 +266= ,9 @@
{
ASN1_INTEGER *asn1_i = =3D X509_get_serialNumber(peer_cert);
struct gc_ar= ena gc =3D gc_new();
- = char *serial =3D format_hex_ex(asn1_i->data, asn1_i->length,
- = 0, 1 | FHE_CAPS, NULL, &gc);
+ char *serial =3D format_hex_ex(asn1_i-&g= t;data, asn1_i->length, 0, 1 | FHE_CAPS, NULL, &gc);

- if (!serial= || cn_len <=3D strlen(serial)+2)
+ if (!serial || cn_len <=3D strlen(serial) + 2)<= /span>
{
gc_free(&gc);
return FAILURE;
@@ -284,11 +278= ,12 @@
}
else
#e= ndif /* ifdef ENABLE_X509ALTUSERNAME */
- if (FAILURE =3D=3D extract_x509_field_ssl(X509_get_su= bject_name(peer_cert),
= - x509_username_field, common_name= , cn_len))
- {
- return FAILURE;
- }
+ if (FAILURE
+ =3D=3D extract_x509_field_s= sl(X509_get_subject_name(peer_cert), x509_username_field,
+ = common_name, cn_len))
+ = return FAILURE;
= + }

return SUCCESS; }
@@ -338,8 +333,7 @@
return S= UCCESS;
err:
BIO_free(out);- crypto_msg(D_TLS_DEBUG_LOW,= "Error writing X509 certificate to file %s",
- filename);
+ crypto_msg(D_TLS_DEBUG_LOW, &qu= ot;Error writing X509 certificate to file %s", filename);

return FAILURE;

}

@@ -376,9 +370,9 @@

goto err;
= }

- X509_NAME_print_ex(subject_bio, X509_get_subject_name(cert),- 0, XN_F= LAG_SEP_CPLUS_SPC | XN_FLAG_FN_SN
- |ASN1_STRFLGS_UTF8_CONVERT | ASN1_STRFLG= S_ESC_CTRL);
+ X50= 9_NAME_print_ex(subject_bio, X509_get_subject_name(cert), 0,
+ XN_FLAG_SEP= _CPLUS_SPC | XN_FLAG_FN_SN | ASN1_STRFLGS_UTF8_CONVERT

+ | ASN1_STRFLG= S_ESC_CTRL);

if (BIO_eof(subject_bio= ))
{
@@ -420,7 +414,8 @@
*/


void
-x509_track_add(const struct x509_track **ll_head,= const char *name, int msglevel, struct gc_arena *gc)
+x509_track_add(const struct x509_track **= ll_head, const char *name, int msglevel,
+ struct gc_arena *gc)
{=
struct x509_track *xt;
ALLOC_OBJ= _CLEAR_GC(xt, struct x509_track, gc);
@@ -452,7 +447,7 @@
string_mod(value, CC_ANY, CC_CRLF, '?');=
msg(D_X509_ATTR, "X509 ATTRIBUTE name=3D'%s' va= lue=3D'%s' depth=3D%d", name, value, depth);
= name_expand_size =3D 64 + strlen(name);
- name_expand =3D (char *) malloc(name_expand_size)= ;
+ name_expand = =3D (char *)malloc(name_expand_size);
check_malloc_ret= urn(name_expand);
snprintf(name_expand, name_expand_si= ze, "X509_%d_%s", depth, name);
setenv_str(e= s, name_expand, value);
@@ -487,8 +482,7 @@
fp_buf =3D x509_get_sha256_fingerprint(x509, &= ;gc);

}

- fp_str =3D for= mat_hex_ex(BPTR(&fp_buf), BLEN(&fp_buf), 0,

- = 1 | FHE_CAPS, ":", &gc);
+ fp_str =3D format_hex_ex(BPTR(&f= p_buf), BLEN(&fp_buf), 0, 1 | FHE_CAPS, ":", &gc);=
do_setenv_x509(es, xt->name, fp_str, dept= h);
}
bre= ak;
@@ -595,10 +589,9 @@
conti= nue;
}
name_expand_size = =3D 64 + strlen(objbuf);
+ name_expand =3D (char *)m= alloc(name_expand_size);
check_malloc_return(name_= expand);
- snpri= ntf(name_expand, name_expand_size, "X509_%d_%s", cert_depth,
- objbuf);<= /span>
+ snprintf(nam= e_expand, name_expand_size, "X509_%d_%s", cert_depth, objbuf);
string_mod(name_expand, CC_PRINT, CC_CRLF, '_= 9;);
string_mod((char *)buf, CC_PRINT, CC_CRLF, &#= 39;_');
setenv_str_incr(es, name_expand, (char= *)buf);
@@ -620,8 +613,8 @@
* Un= fortunately, X509_check_purpose() does some weird thing that
* prevent it to take a const argument

= */
- result_t r= esult =3D X509_check_purpose(peer_cert, X509_PURPOSE_SSL_CLIENT, 0) ?
- S= UCCESS : FAILURE;
+ = result_t result =3D
+ X509_check_purpose(peer_cert, X509_PURPOSE_SSL_CLIENT, 0)= ? SUCCESS : FAILURE;

/*<= br> * old versions of OpenSSL allow us to make the less stri= ct check we used to
@@ -636,7 +629,7 @@
= if (result =3D=3D SUCCESS)
{<= br> msg(M_WARN, "X509: Certificate is a client c= ertificate yet it's purpose "
- "cannot be verified (check may fa= il in the future)");
+ "cannot be verified (check may fail = in the future)");
}
= ASN1_BIT_STRING_free(ns);
}
@@ -648,8 +641,8 @@

* Unfortunately, X509_check= _purpose() does some weird thing that
* prevent i= t to take a const argument
*/
- result_t result =3D X509_check_pu= rpose(peer_cert, X509_PURPOSE_SSL_SERVER, 0) ?
- SUCCESS : FAILURE;
+ result_t result = =3D
+ X509= _check_purpose(peer_cert, X509_PURPOSE_SSL_SERVER, 0) ? SUCCESS : FAILURE;<= /span>

/*
* o= ld versions of OpenSSL allow us to make the less strict check we used to
@@ -664,7 +657,7 @@
if (result = =3D=3D SUCCESS)
{
= msg(M_WARN, "X509: Certificate is a server certificate yet it'= ;s purpose "
- = "cannot be verified (check may fail in the future)&quo= t;);
+ = "cannot be verified (check may fail in the future)")= ;
}
ASN1_BIT_STRI= NG_free(ns);
}
@@ -675,8 +668,7 @@=
}

result_t
<= span style=3D"color: hsl(0, 100%, 40%);">-x509_verify_cert_ku(X509 *x509, c= onst unsigned *const expected_ku,

- int expected_len)
+x509_verify_cert_ku(X509 *x509, const unsigne= d *const expected_ku, int expected_len)
{
= ASN1_BIT_STRING *ku =3D X509_get_ext_d2i(x509, NID_key_usage, NULL, NU= LL);

@@ -722,8 +714,7 @@
=
if (fFound !=3D SUCCESS)
{
- msg(D_TLS_ERRORS,<= /span>
- "ERRO= R: Certificate has key usage %04x, expected one of:", nku);
= + msg(D_TLS_ERRORS, &quo= t;ERROR: Certificate has key usage %04x, expected one of:", nku);
for (size_t i =3D 0; i < expected_len && ex= pected_ku[i]; i++)
{
= msg(D_TLS_ERRORS, " * %04x", expected_ku[i]);
@@ = -741,8 +732,7 @@
EXTENDED_KEY_USAGE *eku =3D NULL;
result_t fFound =3D FAILURE;

= - if ((eku =3D (EXTENDED_KEY_U= SAGE *) X509_get_ext_d2i(x509, NID_ext_key_usage,
- = NULL, NULL)) =3D=3D NULL)
+ if ((eku =3D (EXTENDED_KEY_USAGE *)X509_get_ext_d2i(x509,= NID_ext_key_usage, NULL, NULL)) =3D=3D NULL)
{=
msg(D_HANDSHAKE, "Certificate does not have extende= d key usage extension");
}
@@ -75= 8,8 +748,8 @@

if (SUCCESS != =3D fFound && OBJ_obj2txt(szOid, sizeof(szOid), oid, 0) !=3D -1)
{
- msg(D_HANDSHAKE, "++ Certificate has EKU (str) = %s, expects %s",
-= szOid, expected_oid);
+ msg(D_HANDSHAKE, "++ Certificate= has EKU (str) %s, expects %s", szOid,
+ expected_oid);
= if (!strcmp(expected_oid, szOid))
= {
fFound =3D SUCCESS;<= br>@@ -767,8 +757,8 @@
}
if (SUCCESS !=3D fFound && OBJ_obj2txt(szOid, sizeof(= szOid), oid, 1) !=3D -1)

{
- msg(D_HANDSHAKE, "++= Certificate has EKU (oid) %s, expects %s",
- szOid, expected_oid);=
+ msg(D_HAND= SHAKE, "++ Certificate has EKU (oid) %s, expects %s", szOid,
+ expe= cted_oid);
if (!strcmp(expected_oid, szOid= ))
{
= fFound =3D SUCCESS;
diff --git a/src/openvpn/status.c b/src= /openvpn/status.c
index 1f5e67a..34e5a2f 100644
<= span>--- a/src/openvpn/status.c

+++ b/src/openvpn/status.c<= /span>
@@ -48,7 +48,7 @@
case STATUS_OUTP= UT_READ:
return "READ";

- case STA= TUS_OUTPUT_READ|STATUS_OUTPUT_WRITE:
+ case STATUS_OUTPUT_READ | STATUS_OUTPUT_WRITE:
return "READ/WRITE";
<= /span>
default:
@@ -57,11 +57,8 @@=
}

struct status_output *
-status_open(const char *fi= lename,
- co= nst int refresh_freq,
-= const int msglevel,
- const struct virtual_output *vout,
- const unsigned int flags)
+status_open(const char= *filename, const int refresh_freq, const int msglevel,
+ const struct virtual_output= *vout, const unsigned int flags)
{
s= truct status_output *so =3D NULL;
if (filename || msgl= evel >=3D 0 || vout)
@@ -78,21 +75,16 @@
switch (so->flags)

{ case STATUS_OUTPUT_WRITE:
- so->fd =3D platform_ope= n(filename,
- = O_CREAT | O_TRUNC | O_WRONLY,
- = S_IRUSR | S_IWUSR);

+ so->fd =3D
+ platform_open(filename, O_CR= EAT | O_TRUNC | O_WRONLY, S_IRUSR | S_IWUSR);
= break;

case STAT= US_OUTPUT_READ:
- = so->fd =3D platform_open(filename,
- = O_RDONLY,
- = S_IRUSR | S_IWUSR);
+ so->fd =3D platform_o= pen(filename, O_RDONLY, S_IRUSR | S_IWUSR);
= break;

- case STATUS_OUTPUT_READ|STATUS_OUTPUT_WRITE:
- so->= fd =3D platform_open(filename,
- O_CREAT | O_RDWR,
- = S_IRUSR | S_IWUSR);
+ case STATUS_OUTPUT_READ | STATUS_OUTPUT_WRI= TE:
+ = so->fd =3D platform_open(filename, O_CREAT | O_RDWR, S_IRUSR | S_IWU= SR);
break;
default:
@@ -167,10 +159,10 @@
}
#elif defined(HAVE_CHSIZE)<= br> {
- = const long off =3D (long) lseek(so->fd, (off_t)0, SEEK_CUR);
+ const lon= g off =3D (long)lseek(so->fd, (off_t)0, SEEK_CUR);
= chsize(so->fd, off);
}
-#else /* if defined(HAVE_FTRUNCATE) *= /
+#else /* if define= d(HAVE_FTRUNCATE) */
#warning both ftruncate and chsize fu= nctions appear to be missing from this OS
#endif
@@ -222,7 +214,7 @@
{
<= span> if (so && (so->flags & STATUS_OUTPUT_WRITE))
{
- = char buf[STATUS_PRINTF_MAXLEN+2]; /* leave extra bytes for CR, LF */
+ char buf[STATU= S_PRINTF_MAXLEN + 2]; /* leave extra bytes for CR, LF */
= va_list arglist;
int stat;
=
diff --git a/src/openvpn/status.h b/src/openvpn/status.h<= /span>
index ddbaeef..0c7a869 100644
--- a/src/ope= nvpn/status.h
+++ b/src/openvpn/status.h
@@= -28,10 +28,11 @@
/*
* virtual function = interface for status output
*/
-struct virtual_output {
+struct virtual_output
+{
void *arg;<= br> unsigned int flags_default;
- void (*func) (void *arg, const unsigned int flags, = const char *str);
+ = void (*func)(void *arg, const unsigned int flags, const char *str);
};

static inline void=
@@ -46,8 +47,8 @@

struct statu= s_output
{
-#define STATUS_OUTPUT_READ (1<<0)
-#define STATUS_OUTPUT_WRITE (1<<1)+#define STATUS_OUTPUT_READ (= 1 << 0)
+#defin= e STATUS_OUTPUT_WRITE (1 << 1)
unsigned int flag= s;

char *filename;
@= @ -62,11 +63,8 @@
bool errors;
};

-struct = status_output *status_open(const char *filename,
- const int refr= esh_freq,
- = const int msglevel,
- const struct virtual_= output *vout,
- = const unsigned int flags);
+struct status_output *status_open(const c= har *filename, const int refresh_freq, const int msglevel,
+ co= nst struct virtual_output *vout, const unsigned int flags);

bool status_trigger(struct status_output *so);
@@ -79,12 +77,12 @@
void status_= printf(struct status_output *so, const char *format, ...)
= #ifdef __GNUC__
#if __USE_MINGW_ANSI_STDIO
-__attribute__ ((format(gnu_printf, 2,= 3)))

+ __attribut= e__((format(gnu_printf, 2, 3)))
#else
-__attribute__ ((format(__printf__, 2, 3)))=
+ __attribute__((= format(__printf__, 2, 3)))
#endif
#endif<= /span>
-;
+ ;

= bool status_read(struct status_output *so, struct buffer *buf);
=
diff --git a/src/openvpn/syshead.h b/src/openvpn/sy= shead.h
index e77f313..524923b 100644
--- a= /src/openvpn/syshead.h
+++ b/src/openvpn/syshead.h@@ -28,20 +28,20 @@

/* branch pr= ediction hints */
#if defined(__GNUC__)
-#define likely(x) __builtin_expect= ((x), 1)
-#define unlik= ely(x) __builtin_expect((x), 0)
+#define likely(x) __builtin_expect((x), 1)
+#define unlikely(x) __builtin_expe= ct((x), 0)

#else
-#define likely(x) (x)
-#define unlikely(x) (x)
+#define likely(x) (x)
+#define unlikely(x) (x)
#endif=

#ifdef _WIN32
#include= <windows.h>
#include <winsock2.h>
<= span> #include <tlhelp32.h>

-#define sleep(x) Sleep((x)*1000)
-#define random rand
-#define srandom srand
+#define sleep(x) Sleep((x) * 1000)
+#define random rand
+#define srandom srand

#endif


#ifdef _MSC_VER /* Visual St= udio */
@@ -51,7 +51,7 @@

#if defined(__APPLE__)

#if __ENVIRONMENT_MAC_OS_X_VERSIO= N_MIN_REQUIRED__ >=3D 1070
-#define __APPLE_USE_RFC_3542 1
+#define __APPLE_USE_RFC_3542 1
#endif<= /span>
#endif

@@ -166,10 +166,1= 0 @@
#endif

#if defined= (TARGET_HAIKU)
-#includ= e <SupportDefs.h> /* uint32, etc */
-#include <net/if.h> /* ifconf etc */
-#include <sys/sockio.h= > /* SIOCGRTTABLE, etc */
-#endif /* TARGET_HAIKU */
+#include <SupportDefs.h> /* uint32, etc */
= +#include <net/if.h> = /* ifconf etc */
+#i= nclude <sys/sockio.h> /* SIOCGRTTABLE, etc */
+#endif /* TARGET_HAIKU = */

#ifdef HAVE_ARPA_INET_H
#include <arpa/inet.h>

@@ -183,7 +183,7 @@=
#include <net/if_tap.h>
#endif
=
-#if defined(TA= RGET_LINUX) || defined (TARGET_ANDROID)
+#if defined(TARGET_LINUX) || defined(TARGET_ANDROID)

#ifdef HAVE_LINUX_IF_TUN_H
#include <linux/if_tun.h>

@@ -373,7 +373,9 @@
* Does this platform support linux-style IP_PKTINFO
= * or bsd-style IP_RECVDSTADDR ?
*/
-#if ((defined(HAVE_IN_PKTINFO) &= & defined(IP_PKTINFO)) || defined(IP_RECVDSTADDR)) && defined(H= AVE_MSGHDR) && defined(HAVE_CMSGHDR) && defined(CMSG_FIRSTH= DR) && defined(CMSG_NXTHDR) && defined(HAVE_RECVMSG) &&= amp; defined(HAVE_SENDMSG)

+#if ((defined(HAVE_IN_PKTINFO) && defined(IP_PKTINFO)) || de= fined(IP_RECVDSTADDR)) \
+ && defined(HAVE_MSGHDR) && defined(HAVE_CMSGHDR) &= amp;& defined(CMSG_FIRSTHDR) \
+ && defined(CMSG_NXTHDR) && defined(H= AVE_RECVMSG) && defined(HAVE_SENDMSG)
#define ENAB= LE_IP_PKTINFO 1
#else
#define ENABLE_IP_P= KTINFO 0
@@ -422,10 +424,10 @@
* Director= y separation char
*/
#ifdef _WIN32
-#define PATH_SEPARATOR '= ;\\'
+#define PAT= H_SEPARATOR '\\'
#define PATH_SEPARATOR_STR &q= uot;\\"
#else
-#define PATH_SEPARATOR '/'
+#define PATH_SEPARATOR '/'<= br> #define PATH_SEPARATOR_STR "/"
#endif<= /span>

@@ -434,11 +436,11 @@
*= /
#ifdef _WIN32
#define SOCKET_UNDEFINED = (INVALID_SOCKET)
-#defi= ne SOCKET_PRINTF "%" PRIxPTR
+#define SOCKET_PRINTF "%" PRIxPTR typedef SOCKET socket_descriptor_t;
#else #define SOCKET_UNDEFINED (-1)
-#define SOCKET_PRINTF "%d"
+#define SOCKET_PRINTF "%d"
typedef int socket_descriptor_t;
#endif

@@ -459,7 +461,9 @@
/*
* HTTPS port sharing capability
*/<= br>-#if defined(ENABLE_PORT_SHARE= ) && defined(SCM_RIGHTS) && defined(HAVE_MSGHDR) &&= defined(HAVE_CMSGHDR) && defined(CMSG_FIRSTHDR) && defined= (CMSG_NXTHDR) && defined(HAVE_RECVMSG) && defined(HAVE_SEND= MSG)
+#if defined(ENA= BLE_PORT_SHARE) && defined(SCM_RIGHTS) && defined(HAVE_MSGH= DR) \
+ &&= ; defined(HAVE_CMSGHDR) && defined(CMSG_FIRSTHDR) && define= d(CMSG_NXTHDR) \
+ = && defined(HAVE_RECVMSG) && defined(HAVE_SENDMSG) #define PORT_SHARE 1
#else
#defi= ne PORT_SHARE 0
@@ -493,8 +497,7 @@
/*
* Do we have CryptoAPI capability?
*/
-#if defined(_WIN32) &&= amp; defined(ENABLE_CRYPTO_OPENSSL) \
- && !defined(ENABLE_CRYPTO_WOLFSSL)+#if defined(_WIN32) &&= ; defined(ENABLE_CRYPTO_OPENSSL) && !defined(ENABLE_CRYPTO_WOLFSSL)=
#define ENABLE_CRYPTOAPI
#endif
@@ -521,8 +524,7 @@
/* * Compression support
*/
-#if defined(ENABLE_LZO) || defined(ENABLE_L= Z4) \
- || define= d(ENABLE_COMP_STUB)
+= #if defined(ENABLE_LZO) || defined(ENABLE_LZ4) || defined(ENABLE_COMP_STUB)=
#define USE_COMP
#endif
=
diff --git a/src/openvpn/tls_crypt.c b/src/openvpn/tls_cr= ypt.c
index b0c4291..2892199 100644
--- a/s= rc/openvpn/tls_crypt.c
+++ b/src/openvpn/tls_crypt.c=
@@ -40,9 +40,9 @@
const char *tls_crypt_v2_srv_p= em_name =3D "OpenVPN tls-crypt-v2 server key";
<= /span>
/** Metadata contains user-specified data */
-static const uint8_t TLS_CRYPT_META= DATA_TYPE_USER =3D 0x00;

+static const uint8_t TLS_CRYPT_METADATA_TYPE_USER =3D 0x00;<= /span>
/** Metadata contains a 64-bit unix timestamp in network b= yte order */
-static co= nst uint8_t TLS_CRYPT_METADATA_TYPE_TIMESTAMP =3D 0x01;
+static const uint8_t TLS_CRYPT_MET= ADATA_TYPE_TIMESTAMP =3D 0x01;


static st= ruct key_type
tls_crypt_kt(void)
@@ -57,11= +57,10 @@
}

void
-tls_crypt_init_key(struct k= ey_ctx_bi *key, struct key2 *keydata,
- const char *key_file, bool key_inline, b= ool tls_server)
+tls_= crypt_init_key(struct key_ctx_bi *key, struct key2 *keydata, const char *ke= y_file,
+ = bool key_inline, bool tls_server)
{
- const int key_direction =3D tls_s= erver ?

- = KEY_DIRECTION_NORMAL : KEY_DIRECTION_INVERSE;
+ const int key_direction =3D t= ls_server ? KEY_DIRECTION_NORMAL : KEY_DIRECTION_INVERSE;

= struct key_type kt =3D tls_crypt_kt();
if (!kt.cip= her || !kt.digest)
{
@@ -89,7 +88,6 @@=
{
key->keys[k].hm= ac[j] =3D key->keys[k].hmac[j] ^ other->keys[k].hmac[j];
}

-=
}
}

@@ -9= 8,8 +96,8 @@
{
struct key2 rengokeys;=
if (!key_state_export_keying_material(session, EXPORT= _DYNAMIC_TLS_CRYPT_LABEL,
- strlen(EXPORT_DYNAMIC_TLS_CRY= PT_LABEL),
- = rengokeys.keys, sizeof(rengokeys.keys)))
+ = strlen(EXPORT_DYNAMIC_TLS_CRYPT_LABEL), rengokeys.keys,<= /span>
+ = sizeof(rengokeys.keys)))
{
return false;
}
@@= -111,27 +109,23 @@
session->tls_wrap_reneg.work = =3D alloc_buf(BUF_SIZE(&session->opt->frame));
= session->tls_wrap_reneg.opt.pid_persist =3D NULL;

- packet_id_init(&= ;session->tls_wrap_reneg.opt.packet_id,
- session->opt->replay_window,<= /span>
- ses= sion->opt->replay_time,
- "TLS_WRAP_RENEG", session->key_id);=
+ packet_id_init(= &session->tls_wrap_reneg.opt.packet_id, session->opt->replay_w= indow,
+ = session->opt->replay_time, "TLS_WRAP_RENEG", session-= >key_id);

- if (session->tls_wrap.mode =3D=3D TLS_WRAP_CRYPT
= - || session->tls_wrap.= mode =3D=3D TLS_WRAP_AUTH)
+ if (session->tls_wrap.mode =3D=3D TLS_WRAP_CRYPT || session-&= gt;tls_wrap.mode =3D=3D TLS_WRAP_AUTH)
{
xor_key2(&rengokeys, &session->tls_wrap.original_wra= p_keydata);

}

- const int key_direction =3D session->= ;opt->server ?
- = KEY_DIRECTION_NORMAL : KEY_DIRECTION_INVERSE;
+ const int key_direc= tion =3D session->opt->server ? KEY_DIRECTION_NORMAL : KEY_DIRECTION_= INVERSE;

struct key_direction_state = kds;
key_direction_state_init(&kds, key_direction)= ;

struct key_type kt =3D tls_crypt_k= t();

= - init_key_ctx_bi(&session->tls_wrap_reneg.opt.key_ctx_bi, &r= engokeys, key_direction,
+ init_key_ctx_bi(&sessio= n->tls_wrap_reneg.opt.key_ctx_bi, &rengokeys, key_direction, &kt= ,
+ = "dynamic tls-crypt");
secure_memzero(&= rengokeys, sizeof(rengokeys));

retur= n true;
@@ -139,8 +133,7 @@


bool
-tls_crypt_wrap(const struct buffer *src, struct buffer *dst,- struct crypto_op= tions *opt)
+tls_cryp= t_wrap(const struct buffer *src, struct buffer *dst, struct crypto_options = *opt)
{
const struct key_ctx *ctx =3D= &opt->key_ctx_bi.encrypt;
struct gc_arena gc;<= /span>
@@ -149,12 +142,11 @@
ASSERT(ctx->c= ipher);
ASSERT(ctx->hmac);
ASS= ERT(packet_id_initialized(&opt->packet_id));
- ASSERT(hmac_ctx_size(ctx->hmac) =3D= =3D 256/8);
+ ASSE= RT(hmac_ctx_size(ctx->hmac) =3D=3D 256 / 8);
gc_init(&gc);

- dmsg(D_PACKET_CONTENT, "TLS-CRYPT WRAP F= ROM: %s",
- = format_hex(BPTR(src), BLEN(src), 80, &gc));
+ dmsg(D_PACKET_CONTENT, "TLS-CRYPT WR= AP FROM: %s", format_hex(BPTR(src), BLEN(src), 80, &gc));
/* Get packet ID */
if = (!packet_id_write(&opt->packet_id.send, dst, true, false))@@ -163,15 +155,15 @@
goto err;
<= span> }


- dmsg(D_PACKET_CONTENT, "TLS-CRYPT WRAP AD: %s",
- format_hex(BPTR(ds= t), BLEN(dst), 0, &gc));
+ dmsg(D_PACKET_CONTENT, "TLS-CRYPT WRAP AD: %s", form= at_hex(BPTR(dst), BLEN(dst), 0, &gc));

/* Buffer overflow check */

if (!buf_safe(dst, = BLEN(src) + TLS_CRYPT_BLOCK_SIZE + TLS_CRYPT_TAG_SIZE))
= {
- msg(D_CRYP= T_ERRORS, "TLS-CRYPT WRAP: buffer size error, "
- "sc=3D%d so=3D%d sl=3D= %d dc=3D%d do=3D%d dl=3D%d", src->capacity, src->offset,<= br>- src->len, dst-= >capacity, dst->offset, dst->len);
+ msg(D_CRYPT_ERRORS,
+ "TLS-CRYPT WRAP: buffer = size error, "
+ = "sc=3D%d so=3D%d sl=3D%d dc=3D%d do=3D%d dl=3D%d",
+ src->cap= acity, src->offset, src->len, dst->capacity, dst->offset, dst-&= gt;len);
goto err;
}
@@ -195,15 +187,13 @@
/* Enc= rypt src */
{
int outlen =3D = 0;
- ASSERT(ciph= er_ctx_update(ctx->cipher, BEND(dst), &outlen,
- BPTR(src),= BLEN(src)));
+ = ASSERT(cipher_ctx_update(ctx->cipher, BEND(dst), &outlen, BPTR(src= ), BLEN(src)));
ASSERT(buf_inc_len(dst, outlen));<= /span>
ASSERT(cipher_ctx_final(ctx->cipher, BPTR(dst),= &outlen));
ASSERT(buf_inc_len(dst, outlen));<= /span>
}

- dmsg(D_PACKET_CONTENT, "TLS-CRYPT WRAP TO: %s&q= uot;,
- format_= hex(BPTR(dst), BLEN(dst), 80, &gc));
+ dmsg(D_PACKET_CONTENT, "TLS-CRYPT WRAP TO: %s= ", format_hex(BPTR(dst), BLEN(dst), 80, &gc));

gc_free(&gc);
return true;
@@ -216,8 +206,7 @@
}

bool
-tls_c= rypt_unwrap(const struct buffer *src, struct buffer *dst,
- struct crypto_options = *opt)
+tls_crypt_unwr= ap(const struct buffer *src, struct buffer *dst, struct crypto_options *opt= )
{
static const char error_prefix[] = =3D "tls-crypt unwrap error";
const struct k= ey_ctx *ctx =3D &opt->key_ctx_bi.decrypt;
@@ -228,11= +217,9 @@
ASSERT(opt);
ASSERT(sr= c->len > 0);
ASSERT(ctx->cipher);
<= span style=3D"color: hsl(0, 100%, 40%);">- ASSERT(packet_id_initialized(= &opt->packet_id)

- || (opt->flags & CO_IGNORE_PACKET_ID));
+ ASSERT(packet_id_initialized(&a= mp;opt->packet_id) || (opt->flags & CO_IGNORE_PACKET_ID));
=

- dmsg(D= _PACKET_CONTENT, "TLS-CRYPT UNWRAP FROM: %s",
- format_hex(BPTR(src), BLEN(src),= 80, &gc));
+ = dmsg(D_PACKET_CONTENT, "TLS-CRYPT UNWRAP FROM: %s", format_hex(BP= TR(src), BLEN(src), 80, &gc));

i= f (buf_len(src) < TLS_CRYPT_OFF_CT)
{
@@ -253,8 +240,8 @@

{
= CRYPT_ERROR("cipher reset failed");
= }
- if (!cipher_= ctx_update(ctx->cipher, BPTR(dst), &outlen,
- BPTR(src) + TLS= _CRYPT_OFF_CT, BLEN(src) - TLS_CRYPT_OFF_CT))
+ if (!cipher_ctx_update(ctx->cipher, BP= TR(dst), &outlen, BPTR(src) + TLS_CRYPT_OFF_CT,
+ BLEN(src) = - TLS_CRYPT_OFF_CT))
{
= CRYPT_ERROR("cipher update failed");
}=
@@ -283,10 +270,8 @@

= if (memcmp_constant_time(tag, tag_check, sizeof(tag_check))) {
- = dmsg(D_CRYPTO_DEBUG, "tag : %s",
- format_hex(tag, sizeof(= tag_check), 0, &gc));
- dmsg(D_CRYPTO_DEBUG, "tag_check: %s",
<= span style=3D"color: hsl(0, 100%, 40%);">- format_hex(tag_c= heck, sizeof(tag_check), 0, &gc));

+ dmsg(D_CRYPTO_DEBUG, "tag : %s&quo= t;, format_hex(tag, sizeof(tag_check), 0, &gc));
+ dmsg(D_CRYPTO_DEBUG, "ta= g_check: %s", format_hex(tag_check, sizeof(tag_check), 0, &gc));
CRYPT_ERROR("packet authentication failed&= quot;);
}
}
@= @ -315,30 +300,24 @@
}

= static inline void
-tls= _crypt_v2_load_client_key(struct key_ctx_bi *key, const struct key2 *key2,<= /span>
- = bool tls_server)
+tls_crypt_v2_load_client_key(struct key_ctx_bi *key, const struct key2 = *key2, bool tls_server)
{
- const int key_direction =3D tls_server ?- K= EY_DIRECTION_NORMAL : KEY_DIRECTION_INVERSE;
+ const int key_direction =3D tls_server ? KEY_D= IRECTION_NORMAL : KEY_DIRECTION_INVERSE;
struct key_ty= pe kt =3D tls_crypt_kt();
if (!kt.cipher || !kt.digest= )
{
msg(M_FATAL, "ERROR:= --tls-crypt-v2 not supported");
}
- init_key_ctx_bi(key, key2, key_d= irection, &kt,

- = "Control Channel Encryption");
+ init_key_ctx_bi(key, key2, key_di= rection, &kt, "Control Channel Encryption");
= }

void
tls_crypt_v2_in= it_client_key(struct key_ctx_bi *key, struct key2 *original_key,
= - str= uct buffer *wkc_buf, const char *key_file,
- bool key_inline)+ = struct buffer *wkc_buf, const char *key_file, bool key_inline)
<= span> {

- struct buf= fer client_key =3D alloc_buf(TLS_CRYPT_V2_CLIENT_KEY_LEN
- = + TLS_CRYPT_V2_MAX_WKC_LEN);
+ struct buffer client_key =3D alloc_buf(TLS_CRYPT_V2_CLIENT_KE= Y_LEN + TLS_CRYPT_V2_MAX_WKC_LEN);

- if (!read_pem_key_file(&client_key,= tls_crypt_v2_cli_pem_name,
- key_file, key_inline))
+ if (!read_pem_key_file(&client_= key, tls_crypt_v2_cli_pem_name, key_file, key_inline))
= {
msg(M_FATAL, "ERROR: invalid tls-crypt-v2 = client key format");
}
@@ -356,15= +335,14 @@
}

void
-tls_crypt_v2_init_server_k= ey(struct key_ctx *key_ctx, bool encrypt,
- const char *key_file, bool= key_inline)
+tls_cry= pt_v2_init_server_key(struct key_ctx *key_ctx, bool encrypt, const char *ke= y_file,
+ = bool key_inline)
{
s= truct key srv_key;
struct buffer srv_key_buf;
buf_set_write(&srv_key_buf, (void *)&= ;srv_key, sizeof(srv_key));
- if (!read_pem_key_file(&srv_key_buf, tls_crypt_v2_srv_pem_nam= e,
- = key_file, key_inline))
+ if (!read_pem_key_file(&srv_key_buf, tls_crypt_v2_srv_pe= m_name, key_file, key_inline))
{
= msg(M_FATAL, "ERROR: invalid tls-crypt-v2 server key format")= ;
}
@@ -383,14 +361,13 @@
}


static bool
-tls_crypt_v2_wrap_client_key(struct buffer = *wkc,
- = const struct key2 *src_key,
- const struct buffer *src_me= tadata,
- = struct key_ctx *server_key, struct gc_arena *gc)
<= span style=3D"color: hsl(120, 100%, 40%);">+tls_crypt_v2_wrap_client_key(st= ruct buffer *wkc, const struct key2 *src_key,

+ const struct buffer = *src_metadata, struct key_ctx *server_key,
+ struct gc_arena *gc)
{
cipher_ctx_t *cipher_ctx =3D server_k= ey->cipher;
- str= uct buffer work =3D alloc_buf_gc(TLS_CRYPT_V2_MAX_WKC_LEN
- += cipher_ctx_block_size(cipher_ctx), gc);
+ struct buffer work =3D
+ alloc_buf_gc(TLS_CRYPT_V2_MAX_WKC_LEN += cipher_ctx_block_size(cipher_ctx), gc);

= /* Calculate auth tag and synthetic IV */
uint8_t= *tag =3D buf_write_alloc(&work, TLS_CRYPT_TAG_SIZE);
@= @ -399,8 +376,8 @@
msg(M_WARN, "ERROR: could = not write tag");
return false;
}

- uint16_t = net_len =3D htons(sizeof(src_key->keys) + BLEN(src_metadata)
<= span style=3D"color: hsl(0, 100%, 40%);">- + TL= S_CRYPT_V2_TAG_SIZE + sizeof(uint16_t));

+ uint16_t net_len =3D htons(sizeof(src_key->keys= ) + BLEN(src_metadata) + TLS_CRYPT_V2_TAG_SIZE
+ + sizeof(uint16_t))= ;
hmac_ctx_t *hmac_ctx =3D server_key->hmac;=
hmac_ctx_reset(hmac_ctx);
hmac_ctx_upda= te(hmac_ctx, (void *)&net_len, sizeof(net_len));
@@ -40= 8,16 +385,13 @@
hmac_ctx_update(hmac_ctx, BPTR(src_met= adata), BLEN(src_metadata));
hmac_ctx_final(hmac_ctx, = tag);

- dmsg(D_CRYPTO_DEBUG, "TLS-CRYPT WRAP TAG: %s",
- format_hex(tag, TLS_CRYPT= _TAG_SIZE, 0, gc));

+= dmsg(D_CRYPTO_DEBUG, "TLS-CRYPT WRAP TAG: %s", format_hex(tag= , TLS_CRYPT_TAG_SIZE, 0, gc));

/* Us= e the 128 most significant bits of the tag as IV */
AS= SERT(cipher_ctx_reset(cipher_ctx, tag));

= /* Overflow check (OpenSSL requires an extra block in the dst buffer) = */
- if (buf_forward= _capacity(&work) < (sizeof(src_key->keys)
- + BL= EN(src_metadata)
- = + sizeof(net_len)
+ if (buf_forward_capacity(&work) &= lt; (sizeof(src_key->keys) + BLEN(src_metadata) + sizeof(net_len)=
+ cipher_ctx_block_size(c= ipher_ctx)))
{
msg(M_WARN, &q= uot;ERROR: could not crypt: insufficient space in dst");
@@ -426,11 +400,11 @@


/* Encrypt = */
int outlen =3D 0;
- ASSERT(cipher_ctx_update(cipher_ctx, BEND(&work= ), &outlen,
- = (void *)src_key->keys, sizeof(src_key->keys)))= ;
+ ASSERT(cipher_= ctx_update(cipher_ctx, BEND(&work), &outlen, (void *)src_key->ke= ys,
+ = sizeof(src_key->keys)));
ASSERT(buf_in= c_len(&work, outlen));
- ASSERT(cipher_ctx_update(cipher_ctx, BEND(&work), &outlen,=
- = BPTR(src_metadata), BLEN(src_metadata)));
+ ASSERT(cipher_ctx_update(cipher_ctx, BEND= (&work), &outlen, BPTR(src_metadata),
+ BLEN(src_metadata)))= ;
ASSERT(buf_inc_len(&work, outlen));
ASSERT(cipher_ctx_final(cipher_ctx, BEND(&work), &outlen))= ;

ASSERT(buf_inc_len(&work, outlen));
@@ -441,8 +415,7 @@


static bool
tls_crypt_v2_unwrap_client_key(struct key2 *client_key, struct= buffer *metadata,
- = struct buffer wrapped_client_key,
- stru= ct key_ctx *server_key)

+ struct buffer wrapped_client_key, struct= key_ctx *server_key)
{
const char *e= rror_prefix =3D __func__;
bool ret =3D false;@@ -454,9 +427,8 @@
struct buffer plaintext = =3D { 0 };

dmsg(D_TLS_DEBUG_MED, &qu= ot;%s: unwrapping client key (len=3D%d): %s", __func__,
- BLEN(&wrapped_client_ke= y), format_hex(BPTR(&wrapped_client_key),

- BLEN= (&wrapped_client_key),
- 0, &gc));+ BLEN(&wrapped_cl= ient_key),
+ = format_hex(BPTR(&wrapped_client_key), BLEN(&wrapped_client_key), 0,= &gc));

if (TLS_CRYPT_V2_MAX_WKC= _LEN < BLEN(&wrapped_client_key))
{
<= span>@@ -471,13 +443,12 @@

{
= CRYPT_ERROR("failed to read length");
}
- memcpy(&net_len, B= END(&wrapped_client_key) - sizeof(net_len),
- sizeof(net_len));
+ memcpy(&net_len, BEND(&wrapp= ed_client_key) - sizeof(net_len), sizeof(net_len));

if (ntohs(net_len) !=3D BLEN(&wrapped_client_key))
{
- = dmsg(D_TLS_DEBUG_LOW, "%s: net_len=3D%u, BLEN=3D%i", __func_= _,
- ntohs(= net_len), BLEN(&wrapped_client_key));
+ dmsg(D_TLS_DEBUG_LOW, "%s: net_len=3D%u,= BLEN=3D%i", __func__, ntohs(net_len),
+ BLEN(&wrapped_client_key));=
CRYPT_ERROR("invalid length");
}


@@ -494,8 +465,7 @@
}

buf_set_write(&plaintext, plaintext_buf_= data, sizeof(plaintext_buf_data));
int outlen =3D 0;
- if (!cipher_ctx_upd= ate(server_key->cipher, BPTR(&plaintext), &outlen,
- BPTR(&am= p;wrapped_client_key),

- hmac_ctx_update(server_key->hmac, BPTR(&plaintext= ),
- = BLEN(&plaintext));
+ hmac_ctx_update(server_key->hmac, BPTR(&plaintext), BLEN(&am= p;plaintext));
hmac_ctx_final(server_key->hmac, tag= _check);

if (memcmp_constant_time(ta= g, tag_check, sizeof(tag_check)))
{
- dmsg(D_CRYPTO_DEBUG, "tag = : %s",
- = format_hex(tag, sizeof(tag_check), 0, &gc));
- dmsg(D_CRYPTO_DEBUG, "tag_ch= eck: %s",
- = format_hex(tag_check, sizeof(tag_check), 0, &gc));
+ dmsg(D_CRYPTO_DEBUG, "= ;tag : %s", format_hex(tag, sizeof(tag_check), 0, &gc));
+ dmsg(D_CRYPTO_DE= BUG, "tag_check: %s", format_hex(tag_check, sizeof(tag_check), 0,= &gc));
CRYPT_ERROR("client key authentic= ation error");
msg(D_TLS_DEBUG_LOW, "Thi= s might be a client-key that was generated for "
- "a different tls-crypt-v2 = server key)");
+= "a different tls-crypt-v2 server key)&quo= t;);
}

if (buf_= len(&plaintext) < sizeof(client_key->keys))
@@ -5= 52,8 +519,7 @@
}

static= bool
-tls_crypt_v2_ver= ify_metadata(const struct tls_wrap_ctx *ctx,
- const struct tls_option= s *opt)
+tls_crypt_v2= _verify_metadata(const struct tls_wrap_ctx *ctx, const struct tls_options *= opt)
{
bool ret =3D false;
= struct gc_arena gc =3D gc_new();
@@ -566,8 +532,= 7 @@
goto cleanup;
}
- tmp_file= =3D platform_create_temp_file(opt->tmp_dir, "tls_crypt_v2_metadata= _",
- = &gc);
+ tmp_file =3D platform_create_temp_file(opt->tmp_di= r, "tls_crypt_v2_metadata_", &gc);
if (!= tmp_file || !buffer_write_file(tmp_file, &metadata))
= {
msg(M_WARN, "ERROR: could not write meta= data to file");
@@ -575,8 +540,7 @@
= }

char metadata_type_str[4] =3D {= 0 }; /* Max value: 255 */
- snprintf(metadata_type_str, sizeof(metadata_type_str),
<= span style=3D"color: hsl(0, 100%, 40%);">- "%i", (uin= t8_t) metadata_type);

+ snprintf(metadata_type_str, sizeof(metadata_type_str), "%i"= , (uint8_t)metadata_type);
struct env_set *es =3D env_= set_create(NULL);
setenv_str(es, "script_type&quo= t;, "tls-crypt-v2-verify");
setenv_str(es, &= quot;metadata_type", metadata_type_str);
@@ -611,15 +5= 75,12 @@
}

bool<= br>-tls_crypt_v2_extract_client_k= ey(struct buffer *buf,
= - struct tls_wrap_ctx *ctx,
- const = struct tls_options *opt,
+tls_crypt_v2_extract_client_key(struct = buffer *buf, struct tls_wrap_ctx *ctx,
+ const struct tls_options= *opt, bool initial_packet)
{
if (!ct= x->tls_crypt_v2_server_key.cipher)
{
- msg(D_TLS_ERRORS,

= - "Client wants t= ls-crypt-v2, but no server key present.");
+ msg(D_TLS_ERRORS, "Client wants tl= s-crypt-v2, but no server key present.");
ret= urn false;
}

@@ -633= ,8 +594,7 @@
msg(D_TLS_ERRORS, "Can not read = tls-crypt-v2 client key length");
return fals= e;
}
- memcpy(&net_len, BEND(&wrapped_client_key) - sizeof(net_len= ),
- sizeof(n= et_len));
+ memcpy= (&net_len, BEND(&wrapped_client_key) - sizeof(net_len), sizeof(net_= len));

uint16_t wkc_len =3D ntohs(ne= t_len);
if (!buf_advance(&wrapped_client_key, BLEN= (&wrapped_client_key) - wkc_len))
@@ -657,7 +617,7 @@
* basically transforming the CONTROL_WKC_V1 into a= normal CONTROL_V1
* packet*/
= msg(D_TLS_ERRORS, "control channel security already setup ignori= ng "
- = "wrapped key part of packet.");
+ "wrapped key part of p= acket.");

/* Remove client = key from buffer so tls-crypt code can unwrap message */
= ASSERT(buf_inc_len(buf, -(BLEN(&wrapped_client_key))));@@ -665,10 +625,8 @@
}
=
ctx->tls_crypt_v2_metadata =3D alloc_buf(TLS_CRYPT_V2_MAX= _METADATA_LEN);
- if= (!tls_crypt_v2_unwrap_client_key(&ctx->original_wrap_keydata,
- = &ctx->tls_crypt_v2_metadata,
- wrapped_= client_key,
- = &ctx->tls_crypt_v2_server_key))=
+ if (!tls_crypt_v2_unwr= ap_client_key(&ctx->original_wrap_keydata, &ctx->tls_crypt_v2= _metadata,
+ = wrapped_client_key, &ctx->tls_crypt_v= 2_server_key))
{
msg(D_TLS_ER= RORS, "Can not unwrap tls-crypt-v2 client key");
= secure_memzero(&ctx->original_wrap_keydata, sizeof(ctx->= original_wrap_keydata));
@@ -680,8 +638,7 @@
ctx->cleanup_key_ctx =3D true;

ctx->opt.f= lags |=3D CO_PACKET_ID_LONG_FORM;
memset(&ctx->= opt.key_ctx_bi, 0, sizeof(ctx->opt.key_ctx_bi));
- tls_crypt_v2_load_client_key(&ctx-&= gt;opt.key_ctx_bi,
- = &ctx->original_wrap_keydata, true);
+ tls_crypt_v2_load_= client_key(&ctx->opt.key_ctx_bi, &ctx->original_wrap_keydata,= true);

/* Remove client key from bu= ffer so tls-crypt code can unwrap message */
ASSERT(bu= f_inc_len(buf, -(BLEN(&wrapped_client_key))));
@@ -701,= 16 +658,13 @@
}

void
-tls_crypt_v2_write_clien= t_key_file(const char *filename,
- const char *b64_metadata,
- = const char *server_key_file,
- bool server_key_inline)=
+tls_crypt_v2_write_= client_key_file(const char *filename, const char *b64_metadata,
<= span style=3D"color: hsl(120, 100%, 40%);">+ = const char *server_key_file, bool server_key_inline)

{=
struct gc_arena gc =3D gc_new();
= struct key_ctx server_key =3D { 0 };
struct buffer cl= ient_key_pem =3D { 0 };
- struct buffer dst =3D alloc_buf_gc(TLS_CRYPT_V2_CLIENT_KEY_LEN=
- = + TLS_CRYPT_V2_MAX_WKC_LEN, &gc);
+ struct buffer dst =3D alloc_buf_gc(TLS_CRYPT= _V2_CLIENT_KEY_LEN + TLS_CRYPT_V2_MAX_WKC_LEN, &gc);
= struct key2 client_key =3D { .n =3D 2 };

if (!rand_bytes((void *)client_key.keys, sizeof(client_key.keys)))<= /span>
@@ -726,8 +680,7 @@
size_t b64_len= gth =3D strlen(b64_metadata);
metadata =3D alloc_b= uf_gc(OPENVPN_BASE64_DECODED_LENGTH(b64_length) + 1, &gc);
ASSERT(buf_write(&metadata, &TLS_CRYPT_METADATA_TYPE_U= SER, 1));

- int = decoded_len =3D openvpn_base64_decode(b64_metadata, BEND(&metadata),
- = BCAP(&metadata));
+ int decoded_len =3D openvpn_base64_decode= (b64_metadata, BEND(&metadata), BCAP(&metadata));
= if (decoded_len < 0)
{
= msg(M_FATAL, "ERROR: failed to base64 decode provided met= adata");
@@ -735,9 +688,8 @@
= }
if (decoded_len > TLS_CRYPT_V2_MAX_METADATA_L= EN - 1)
{
- msg(M_FATAL,
- "ERROR: metadata too long (%d bytes, m= ax %u bytes)",
- = decoded_len, TLS_CRYPT_V2_MAX_METADATA_LEN - 1);
+ msg(M_FATAL, "E= RROR: metadata too long (%d bytes, max %u bytes)", decoded_len,
=
+ TLS_CRYPT_= V2_MAX_METADATA_LEN - 1);
goto cleanup;=
}
ASSERT(buf_inc_len(&metad= ata, decoded_len));
@@ -750,18 +702,15 @@
= ASSERT(buf_write(&metadata, &timestamp, sizeof(timestamp)))= ;
}

- tls_crypt_v2_init_server_key(&server_key, true= , server_key_file,
- = server_key_inline);
- if (!tls_crypt_v2_wrap_client_key(&dst,= &client_key, &metadata, &server_key,
- &gc))=
+ tls_crypt_v2_in= it_server_key(&server_key, true, server_key_file, server_key_inline);
+ if (!tls_crypt_v2= _wrap_client_key(&dst, &client_key, &metadata, &server_key,= &gc))
{
msg(M_FATAL, &qu= ot;ERROR: could not wrap generated client key");
= goto cleanup;
}

= /* PEM-encode Kc || WKc */
- if (!crypto_pem_encode(tls_crypt_v2_cli_pem_name, &client= _key_pem, &dst,
- = &gc))
+ if (!crypto_pem_encode(tls_crypt_v2_cli_pem_name, &c= lient_key_pem, &dst, &gc))
{
= msg(M_FATAL, "ERROR: could not PEM-encode client key");
goto cleanup;
@@ -787,17 +736,15 @@=
struct buffer test_wrapped_client_key;
struct key2 keydata;

msg(D_GENKEY, "Testin= g client-side key loading...");
- tls_crypt_v2_init_client_key(&test_client_key, &= keydata, &test_wrapped_client_key,
- client_file, client_inlin= e);
+ tls_crypt_v2= _init_client_key(&test_client_key, &keydata, &test_wrapped_clie= nt_key, client_file,
= + client_inline);
free= _key_ctx_bi(&test_client_key);

/= * Sanity check: unwrap and load client key (as "server") */
- struct buffer test_meta= data =3D alloc_buf_gc(TLS_CRYPT_V2_MAX_METADATA_LEN,
- = &gc);
+ st= ruct buffer test_metadata =3D alloc_buf_gc(TLS_CRYPT_V2_MAX_METADATA_LEN, &= amp;gc);
struct key2 test_client_key2 =3D { 0 };
free_key_ctx(&server_key);
- tls_crypt_v2_init_server_key(&server_key, = false, server_key_file,
- server_key_inline);
+ tls_crypt_v2_init_server_key(&se= rver_key, false, server_key_file, server_key_inline);
= msg(D_GENKEY, "Testing server-side key loading...");
ASSERT(tls_crypt_v2_unwrap_client_key(&test_client_key2, &= test_metadata,

t= est_wrapped_client_key, &server_key));
diff --git a/src= /openvpn/tls_crypt.h b/src/openvpn/tls_crypt.h
index c8bd38= 4..87aa8d2 100644
--- a/src/openvpn/tls_crypt.h
<= span>+++ b/src/openvpn/tls_crypt.h

@@ -85,21 +85,21 @@
#include "session_id.h"
#include &q= uot;ssl_common.h"

-#define TLS_CRYPT_TAG_SIZE (256/8)
-#define TLS_CRYPT_PID_SIZE (sizeof(packet_i= d_type) + sizeof(net_time_t))
-#define TLS_CRYPT_BLOCK_SIZE (128/8)
+#define TLS_CRYPT_TAG_SIZE (256 / 8)
<= span style=3D"color: hsl(120, 100%, 40%);">+#define TLS_CRYPT_PID_SIZE (s= izeof(packet_id_type) + sizeof(net_time_t))

+#define TLS_CRYPT_BLOCK_SIZE (128 / 8)

#define TLS_CRYPT_OFF_PID (1 + SID_SIZE)
<= span> #define TLS_CRYPT_OFF_TAG (TLS_CRYPT_OFF_PID + TLS_CRYPT_PID_SIZE)
-#define TLS_CRYPT_OFF_CT= (TLS_CRYPT_OFF_TAG + TLS_CRYPT_TAG_SIZE)
+#define TLS_CRYPT_OFF_CT (TLS_CRYPT_OFF_TAG + TLS_CR= YPT_TAG_SIZE)

-#define TLS_CRYPT_V2_MAX_WKC_LEN (1024)
+#define TLS_CRYPT_V2_MAX_WKC_LEN (1024)
#define TLS_CRYPT_V2_CLIENT_KEY_LEN (2048 / 8)
#define TLS_CRYPT_V2_SERVER_KEY_LEN (sizeof(struct key))

-#define TLS_CRYPT_V2_TAG_SIZE (TLS_C= RYPT_TAG_SIZE)

-#define= TLS_CRYPT_V2_MAX_METADATA_LEN (unsigned)(TLS_CRYPT_V2_MAX_WKC_LEN \=
- = - (TLS_CRYPT_V2_CLIENT_KEY_LEN + TLS_CRYPT_V2_TAG_SIZE= \
- = + sizeof(uint16_t)))
+#define TLS_CRYPT_V2_TAG_SIZE (TLS_= CRYPT_TAG_SIZE)
+#def= ine TLS_CRYPT_V2_MAX_METADATA_LEN \
+ (unsigned)(TLS_CRYPT_V2_MAX_WKC_LEN \
+ - (TLS_CRYPT_V2_CLIE= NT_KEY_LEN + TLS_CRYPT_V2_TAG_SIZE + sizeof(uint16_t)))


/**
* Initialize a key_ctx_bi structure f= or use with @c --tls-crypt.
@@ -112,8 +112,8 @@
<= span> * otherwise.

* @param tls_ser= ver Must be set to true is this is a TLS server instance.
*/

-void tls_crypt_= init_key(struct key_ctx_bi *key, struct key2 *keydata,
- const char *key_fi= le, bool key_inline, bool tls_server);
+void tls_crypt_init_key(struct key_ctx_bi *key, struct k= ey2 *keydata, const char *key_file,
+ bool key_inline, bool tls_server);<= /span>

/**
* Generates a TLS-= Crypt key to be used with dynamic tls-crypt using the
@@ -1= 24,8 +124,7 @@
* @param session session that will be us= ed for the TLS EKM exporter
* @return true iff g= enerating the key was successful
*/
-bool
-tls_session_generate_dynamic_tls_crypt_key(struct tls_sessio= n *session);
+bool tl= s_session_generate_dynamic_tls_crypt_key(struct tls_session *session);

/**
* Returns the maximum = overhead (in bytes) added to the destination buffer by
@@ -= 144,8 +143,7 @@
*
* @returns true iff w= rapping succeeded.
*/
-bool tls_crypt_wrap(const struct buffer *src, struct buff= er *dst,
- = struct crypto_options *opt);
+bool tls_crypt_wrap(const struct buffer *src, struct buffer= *dst, struct crypto_options *opt);

/**<= /span>
* Unwrap a control channel packet (decrypts, authenticate= s and performs
@@ -158,8 +156,7 @@
* @ret= urns true iff unwrapping succeeded (data authenticated correctly and was
* no replay).
*/
-bool tls_crypt_unwrap(const struct buffer *src= , struct buffer *dst,
-= struct crypto_options *opt);
+bool tls_crypt_unwrap(const struct buffer *s= rc, struct buffer *dst, struct crypto_options *opt);

/**
* Initialize a tls-crypt-v2 server key (= used to encrypt/decrypt client keys).
@@ -173,8 +170,8 @@
* otherwise.
*
*/
-void = tls_crypt_v2_init_server_key(struct key_ctx *key_ctx, bool encrypt,<= br>- = const char *key_file, bool key_inline);
+void tls_crypt_v2_init_server_key(struct key_ctx *= key_ctx, bool encrypt, const char *key_file,
+ bool key_inline)= ;

/**
* Initialize a t= ls-crypt-v2 client key.
@@ -191,10 +188,9 @@
* @param key_inline True if key_file contains an inline key, Fal= se

* otherwise.
= */
-void tls_crypt_v2= _init_client_key(struct key_ctx_bi *key,
- struct key2 *original_= key,
- = struct buffer *wrapped_key_buf,
- const char *ke= y_file, bool key_inline);
+void tls_crypt_v2_init_client_key(struct key_ctx_bi *key, struct key2= *original_key,
+ = struct buffer *wrapped_key_buf, const char *k= ey_file,
+ = bool key_inline);

= /**
* Extract a tls-crypt-v2 client key from a P_CONTROL= _HARD_RESET_CLIENT_V3
@@ -211,10 +207,8 @@
= *
* @returns true if a key was successfully extracted.<= /span>
*/
-b= ool tls_crypt_v2_extract_client_key(struct buffer *buf,
- stru= ct tls_wrap_ctx *ctx,
-= const struct tls_options *opt,<= br>- = bool initial_packet);
+bool tls_crypt_v2_extract_client_key(struct buffer *buf, struct t= ls_wrap_ctx *ctx,
+ = const struct tls_options *opt, bool init= ial_packet);

/**
* Gen= erate a tls-crypt-v2 server key, and write to file.
@@ -233= ,8 +227,7 @@
* @param key_inline True if key_file = contains an inline key, False
* = otherwise.
*/
-void tls_crypt_v2_write_client_key_file(const char *filename,
- = const char *b64_metadata,
+void tls_crypt_v2_write_client_key_file(const char *fi= lename, const char *b64_metadata,
= const char *key_file, bool key_inline);

/** @} */
diff --git a/src/openvpn/tun.c b/= src/openvpn/tun.c
index a96a305..f54b608 100644
<= span>--- a/src/openvpn/tun.c

+++ b/src/openvpn/tun.c=
@@ -84,27 +84,25 @@

#ifdef _WI= N32

-= const static GUID GUID_DEVCLASS_NET =3D { 0x4d36e972L, 0xe325, 0x11ce, { 0x= bf, 0xc1, 0x08, 0x00, 0x2b, 0xe1, 0x03, 0x18 } };
-const static GUID GUID_DEVINTERFACE_NET =3D { 0= xcac88484, 0x7515, 0x4c03, { 0x82, 0xe6, 0x71, 0xa8, 0x7a, 0xba, 0xc3, 0x61= } };
+const static G= UID GUID_DEVCLASS_NET =3D {
+ 0x4d36e972L, 0xe325, 0x11ce, { 0xbf, 0xc1, 0x08, 0x00, 0x2b, 0x= e1, 0x03, 0x18 }
+};<= /span>
+const static GUID GU= ID_DEVINTERFACE_NET =3D {
+ 0xcac88484, 0x7515, 0x4c03, { 0x82, 0xe6, 0x71, 0xa8, 0x7a, 0xba,= 0xc3, 0x61 }
+};

-/* #def= ine SIMULATE_DHCP_FAILED */ /* simulate bad DHCP negotiation */
+/* #define SIMULATE_DHCP_= FAILED */ /* simulate bad DHCP negotiation */

<= span style=3D"color: hsl(0, 100%, 40%);">-#define NI_TEST_FIRST (1<<= 0)

-#define NI_IP_NETMA= SK (1<<1)
-#defi= ne NI_OPTIONS (1<<2)
+#define NI_TEST_FIRST (1 << 0)
+#define NI_IP_NETMASK (1 << 1)
= +#define NI_OPTIONS (1 <&= lt; 2)

- DWORD a= dapter_index,
- = const in_addr_t ip,
- const in_addr_t netmask,=
- c= onst unsigned int flags);
+static void netsh_ifconfig(const struct tuntap_options *to, DWORD ada= pter_index, const in_addr_t ip,
+ const in_addr_t netmask, const unsig= ned int flags);

-static void windows_set_mtu(const int iface_index,
- const = short family,

- = const int mtu);
+static void windows_set_mtu(const int iface_index, const sh= ort family, const int mtu);

-static void netsh_set_dns6_servers(const struct in6= _addr *addr_list,
- = const int addr_len,
+static void netsh_set_dns6_servers(const str= uct in6_addr *addr_list, const int addr_len,
= DWORD adapter_index);

static void netsh_command(const struct argv *a, int n, int msglevel);
@@ -121,15 +119,10 @@
struct gc_arena g= c =3D gc_new();
HANDLE pipe =3D tt->options.msg_cha= nnel;

- address_message_t addr =3D {
- .header =3D {
- (add ? msg_add_address : msg_del_address),<= br>- sizeof(address_me= ssage_t),
- = 0
- },- .family =3D family,

- .iface =3D { .ind= ex =3D tt->adapter_index, .name =3D "" }
- };
+ address_message_t addr =3D { .header =3D { (add ? ms= g_add_address : msg_del_address),
+ sizeof(address_mes= sage_t), 0 },
+ = .family =3D family,
+ .iface =3D { .index= =3D tt->adapter_index, .name =3D "" } };

if (addr.iface.index =3D=3D TUN_ADAPTER_INDEX_INVALID)
{
@@ -141,16 +134,14 @@
{

addr.address.ipv4.s_addr =3D htonl(tt->= local);
addr.prefix_len =3D netmask_to_netbits2(tt= ->adapter_netmask);
= - msg(D_IFCONFIG, "INET address service: %s %s/%d",=
- add ? "add&= quot; : "remove",
+ msg(D_IFCONFIG, "INET address service: %s %s/%d",= add ? "add" : "remove",
p= rint_in_addr_t(tt->local, 0, &gc), addr.prefix_len);
}

else
{
= addr.address.ipv6 =3D tt->local_ipv6;
ad= dr.prefix_len =3D (tt->type =3D=3D DEV_TYPE_TUN) ? 128 : tt->netbits_= ipv6;
- msg(D_IF= CONFIG, "INET6 address service: %s %s/%d",
- add ? "add" : "r= emove",
+ = msg(D_IFCONFIG, "INET6 address service: %s %s/%d", add ? "a= dd" : "remove",
print_in6_addr(= tt->local_ipv6, 0, &gc), addr.prefix_len);
}

@@ -162,8 +153,8 @@
if= (ack.error_number !=3D NO_ERROR)
{
= msg(M_WARN, "TUN: %s address failed using service: %s [status= =3D%u if_index=3D%d]",
- (add ? "adding" : "deleting"), strerr= or_win32(ack.error_number, &gc),
- ack.error_number, addr.iface.index);
<= span style=3D"color: hsl(120, 100%, 40%);">+ (add ? "adding= " : "deleting"), strerror_win32(ack.error_number, &gc), = ack.error_number,

+ = addr.iface.index);
goto out;
<= span> }


@@ -189,15 +180,11 @@<= br>
/* Use dns_cfg_msg with addr_len =3D 0 for = setting only the DOMAIN */
dns_cfg_message_t dns =3D {=
- .header =3D {=
- (add ? ms= g_add_dns_cfg : msg_del_dns_cfg),
- sizeof(dns_cfg_message_t),
- 0
- },
+ .header =3D { (add ? msg_add_dns_cfg : msg_del_dns_cfg)= , sizeof(dns_cfg_message_t), 0 },
.iface =3D { .in= dex =3D tt->adapter_index, .name =3D "" },
- .domains =3D "", /= * set below */
- = .family =3D AF_INET, /* unused */
- .addr_len =3D 0 /* add/delete only the domain, = not DNS servers */
+ = .domains =3D "", /* set below */
+ .family =3D AF_INET, /* unused */=
+ .addr_len = =3D 0 /* add/delete only the domain, not DNS servers */
};


/* interface name is requi= red */
@@ -237,8 +224,8 @@
if (ack.err= or_number !=3D NO_ERROR)
{
ms= g(M_WARN, "TUN: %s DNS domains failed using service: %s [status=3D%u i= f_name=3D%s]",
- = (add ? "adding" : "deleting"), strerror_win32= (ack.error_number, &gc),
- ack.error_number, dns.iface.name);
+ (add ? "adding" : &= quot;deleting"), strerror_win32(ack.error_number, &gc), ack.error_= number,
+ = dns.iface.name);
goto out;
}<= /span>

@@ -265,17 +252,12 @@
= }

/* Use dns_cfg_msg with domain = =3D "" for setting only the DNS servers */
- dns_cfg_message_t dns =3D {
<= span style=3D"color: hsl(0, 100%, 40%);">- .header =3D {

<= span style=3D"color: hsl(0, 100%, 40%);">- (add ? msg_add_dns_cf= g : msg_del_dns_cfg),

-= sizeof(dns_cfg_message_t),
- 0
- },
- = .iface =3D { .index =3D tt->adapter_index, .name =3D "" = },
- .domains = =3D "",
- = .family =3D family,
- .addr_len =3D addr_len
- };
+ = dns_cfg_message_t dns =3D { .header =3D { (add ? msg_add_dns_cfg : msg_de= l_dns_cfg),
+ = sizeof(dns_cfg_message_t), 0 },+ = .iface =3D { .index =3D tt->adapter_index, .name =3D "" },
+ = .domains =3D "",
+ .family =3D family,
= + = .addr_len =3D addr_len };

/* interfa= ce name is required */
strncpy(dns.iface.name, tt->= actual_name, sizeof(dns.iface.name));
@@ -285,8 +267,8 @@
{
addr_len =3D _countof(dns.ad= dr);
dns.addr_len =3D addr_len;
- msg(M_WARN, "Number of %s D= NS addresses sent to service truncated to %d",
- ip_proto_name, addr_len);
+ msg(M_WARN, "= ;Number of %s DNS addresses sent to service truncated to %d", ip_proto= _name,
+ a= ddr_len);
}

for= (int i =3D 0; i < addr_len; ++i)
@@ -337,15 +319,10 @@<= /span>
goto out;
}
=
- wins_cfg_message_= t wins =3D {
- .= header =3D {
- = (add ? msg_add_wins_cfg : msg_del_wins_cfg),
- sizeof(wins_cfg_message_t),- 0
- },
- .iface =3D {.index =3D tt->adapter_inde= x, .name =3D "" },
- .addr_len =3D addr_len
- };
= + sizeof(wins_cfg_message_t), 0 = },
+ = .iface =3D { .index =3D tt->adapter_index, .name =3D &quo= t;" },
+ = .addr_len =3D addr_len };
<= br> /* interface name is required */
strncpy= (wins.iface.name, tt->actual_name, sizeof(wins.iface.name));
<= span>@@ -355,8 +332,7 @@

{
ad= dr_len =3D _countof(wins.addr);
wins.addr_len =3D = addr_len;
- msg(= M_WARN, "Number of WINS addresses sent to service truncated to %d"= ;,
- addr_le= n);
+ msg(M_WA= RN, "Number of WINS addresses sent to service truncated to %d", a= ddr_len);
}

for= (int i =3D 0; i < addr_len; ++i)
@@ -375,8 +351,8 @@
if (ack.error_number !=3D NO_ERROR)
= {
msg(M_WARN, "TUN: %s WINS failed using ser= vice: %s [status=3D%u if_name=3D%s]",
- (add ? "adding" : "deleting= "), strerror_win32(ack.error_number, &gc),
- ack.error_number, wins.iface.na= me);
+ (ad= d ? "adding" : "deleting"), strerror_win32(ack.error_nu= mber, &gc), ack.error_number,
+ wins.iface.name);
goto o= ut;
}

@@ -394,20 +37= 0,15 @@
struct gc_arena gc =3D gc_new();
HANDLE pipe =3D tt->options.msg_channel;

co= nst char *family_name =3D (family =3D=3D AF_INET6) ? "IPv6" : &qu= ot;IPv4";
- set= _mtu_message_t mtu_msg =3D {
- .header =3D {
- msg_set_mtu,
- sizeof(set_mtu_message_t),
- 0
- },
- .iface =3D {.index =3D tt->adapter_index},
- .mtu =3D mtu,

- .family =3D family
- };
+ set_mtu_message_t mtu_msg =3D { .head= er =3D { msg_set_mtu, sizeof(set_mtu_message_t), 0 },
+ .iface = =3D { .index =3D tt->adapter_index },
+ .mtu =3D mtu,=
+ = .family =3D family };
strncpynt(mtu_msg.iface.= name, tt->actual_name, sizeof(mtu_msg.iface.name));
= if (family =3D=3D AF_INET6 && mtu < 1280)
= {
- msg(M_INFO, = "NOTE: IPv6 interface MTU < 1280 conflicts with IETF standards and = might not work");
- family_name, strerror_w= in32(ack.error_number, &gc), ack.error_number, mtu_msg.iface.index);
+ family_nam= e, strerror_win32(ack.error_number, &gc), ack.error_number,
<= span style=3D"color: hsl(120, 100%, 40%);">+ mtu_msg.iface.index= );

}
else
{<= /span>
- msg(M_INFO, &q= uot;%s MTU set to %d on interface %d using service", family_name, mtu,= mtu_msg.iface.index);
+ mtu_msg.iface.index);
ret =3D tr= ue;
}

@@ -441,7 +414= ,8 @@

struct argv argv =3D argv_new(= );
argv_printf(&argv, "%s%s nicconfig where (= InterfaceIndex=3D%ld) call SetDNSDomain '%s'",
- get_win_sys_path(), W= MIC_PATH_SUFFIX, tt->adapter_index, add ? tt->options.domain : "= ");

+ = get_win_sys_path(), WMIC_PATH_SUFFIX, tt->adapter_index,
= + add ? tt->o= ptions.domain : "");
exec_command("WMIC= ", &argv, 1, M_WARN);

argv_= free(&argv);
@@ -479,12 +453,7 @@
= }

create_adapter_message_t msg =3D {=
- .header =3D {=
- msg_creat= e_adapter,
- = sizeof(create_adapter_message_t),
- 0
- },
- = .adapter_type =3D t
+ .header =3D { msg_create_adapter, sizeof(create_adapter_message_t= ), 0 }, .adapter_type =3D t
};

if (!send_msg_iservice(msg_channel, &msg, sizeof(msg), = &ack, "create_adapter"))
@@ -495,7 +464,8 @@<= /span>
if (ack.error_number !=3D NO_ERROR)
= {
msg(M_NONFATAL, "TUN: creating %s adapte= r using service failed: %s [status=3D%u]",
- print_tun_backend_driver(driver_type)= , strerror_win32(ack.error_number, &gc), ack.error_number);
<= span style=3D"color: hsl(120, 100%, 40%);">+ print_tun_backend_d= river(driver_type), strerror_win32(ack.error_number, &gc),

+ ack.error_number);
}
else
{
@@ -511,7 +481,8 @@
#endif /* ifdef _WIN32 */<= /span>

#ifdef TARGET_SOLARIS
-static void solaris_error_close(struct t= untap *tt, const struct env_set *es, const char *actual, bool unplumb_inet6= );
+static void solar= is_error_close(struct tuntap *tt, const struct env_set *es, const char *act= ual,
+ = bool unplumb_inet6);

#i= nclude <stropts.h>
#endif
@@ -582,10= +553,7 @@
* before the device is actually opened.=
*/
const char *
-guess_tuntap_dev(const char *dev,
- const char *dev_type,
- const = char *dev_node,
- = struct gc_arena *gc)
+guess_tuntap_dev(const char *dev, const char *dev_type, const c= har *dev_node, struct gc_arena *gc)
{
#if= def _WIN32
const int dt =3D dev_type_enum(dev, dev_typ= e);
@@ -619,16 +587,17 @@
{
= if (looks_like_netmask)
{- msg(M_WARN, "W= ARNING: Since you are using --dev tun with a point-to-point topology, the s= econd argument to --ifconfig must be an IP address. You are using somethin= g (%s) that looks more like a netmask. %s",
- print_in_addr_t(addr, 0, &gc= ),
- ifc= onfig_warn_how_to_silence);
+ msg(M_WARN,
+ "WARNING: Since you are using --dev tun wi= th a point-to-point topology, the second argument to --ifconfig must be an = IP address. You are using something (%s) that looks more like a netmask. %= s",
+ = print_in_addr_t(addr, 0, &gc), ifconfig_warn_how_to_silence);
}
}
else
{
if (!looks_like_netmask)
{
-= msg(M_WARN, "WARNING: Since you are using subnet topology,= the second argument to --ifconfig must be a netmask, for example something= like 255.255.255.0. %s",
+ msg(M_WARN,
+ "WARNING: Since you are using subnet to= pology, the second argument to --ifconfig must be a netmask, for example so= mething like 255.255.255.0. %s",
ifco= nfig_warn_how_to_silence);
}
= }
@@ -640,10 +609,7 @@
* clash with ifcon= fig addresses or subnet.
*/
static void<= /span>
-check_addr_clash(const= char *name,
- = int type,
- = in_addr_t public,
- in_addr_t local,
+check_addr_clash(const char *name, int type, in_addr= _t public, in_addr_t local,
in_addr_t rem= ote_netmask)
{
struct gc_arena gc =3D= gc_new();
@@ -660,7 +626,7 @@
if = (type =3D=3D DEV_TYPE_TUN)
{
= const in_addr_t test_netmask =3D 0xFFFFFF00;
- const in_addr_t public_net =3D = public &test_netmask;
+ const in_addr_t public_net =3D public & test_netmask;=
const in_addr_t local_net =3D local & tes= t_netmask;
const in_addr_t remote_net =3D remo= te_netmask & test_netmask;

@@ -668,37= +634,28 @@
{
= msg(M_WARN,
"WARNING: --%s addre= ss [%s] conflicts with --ifconfig address pair [%s, %s]. %s",- name,
- print_= in_addr_t(public, 0, &gc),
- print_in_addr_t(local, 0, &gc),
= - print_in_add= r_t(remote_netmask, 0, &gc),
- ifconfig_warn_how_to_silence);
+ name, print_i= n_addr_t(public, 0, &gc), print_in_addr_t(local, 0, &gc),
+ print_in_= addr_t(remote_netmask, 0, &gc), ifconfig_warn_how_to_silence); }

if (p= ublic_net =3D=3D local_net || public_net =3D=3D remote_net)
{

msg(M_WARN,
"WARNING: potential conflict between --%s addre= ss [%s] and --ifconfig address pair [%s, %s] -- this is a warning only that= is triggered when local/remote addresses exist within the same /24 subnet = as --ifconfig endpoints. %s",

- name,
- print_in_addr_t(public, 0, &gc),
- pri= nt_in_addr_t(local, 0, &gc),
- print_in_addr_t(remote_netmask, 0, &gc),=
- i= fconfig_warn_how_to_silence);
+ name, print_in_addr_t(public, 0, &gc), pr= int_in_addr_t(local, 0, &gc),
+ print_in_addr_t(remote_netmask, 0, &g= c), ifconfig_warn_how_to_silence);
} }
else if (type =3D=3D DEV_TYPE_TA= P)
{
- const in_addr_t public_network =3D public &remote_n= etmask;
+ = const in_addr_t public_network =3D public & remote_netmask;
<= span> const in_addr_t virtual_network =3D local & remote_ne= tmask;

if (public_network =3D=3D virtual_netwo= rk)
{
msg(M_W= ARN,
"WARNING: --%s address [%s] = conflicts with --ifconfig subnet [%s, %s] -- local and remote addresses can= not be inside of the --ifconfig subnet. %s",
- name,
- print_in_addr_t(public,= 0, &gc),
- = print_in_addr_t(local, 0, &gc),
- print_in_addr_t(remote_netmas= k, 0, &gc),
- = ifconfig_warn_how_to_silence);
+ name, print_in_addr_t(public, = 0, &gc), print_in_addr_t(local, 0, &gc),
+ print_in_addr_t(remote_net= mask, 0, &gc), ifconfig_warn_how_to_silence);
= }
}
}
@@ = -710,7 +667,7 @@
{
struct gc_arena gc= =3D gc_new();
struct route_gateway_info rgi;- const unsigned int needed = =3D (RGI_ADDR_DEFINED|RGI_NETMASK_DEFINED);
+ const unsigned int needed =3D (RGI_ADDR_DEFINED= | RGI_NETMASK_DEFINED);

get_default= _gateway(&rgi, 0, ctx);
if ((rgi.flags & neede= d) =3D=3D needed)
@@ -718,7 +675,8 @@
= const in_addr_t lan_network =3D rgi.gateway.addr & rgi.gateway.netm= ask;
if (lan_network =3D=3D 0xC0A80000 || lan_netw= ork =3D=3D 0xC0A80100)
{
- msg(M_WARN, "NOTE: your local = LAN uses the extremely common subnet address 192.168.0.x or 192.168.1.x. B= e aware that this might create routing conflicts if you connect to the VPN = server from public locations such as internet cafes that use the same subne= t.");
+ = msg(M_WARN,
+ = "NOTE: your local LAN uses the extremely common subnet addr= ess 192.168.0.x or 192.168.1.x. Be aware that this might create routing co= nflicts if you connect to the VPN server from public locations such as inte= rnet cafes that use the same subnet.");
}
}
gc_free(&gc);
= @@ -736,8 +694,7 @@
{
if (!is= _tun_p2p(tt))
{
- buf_printf(&out, "%s %s",
- pri= nt_in_addr_t(tt->local & tt->remote_netmask, 0, gc),
+ buf_printf(&out,= "%s %s", print_in_addr_t(tt->local & tt->remote_netmas= k, 0, gc),

print_in_addr_t(tt->r= emote_netmask, 0, gc));
}
= else if (tt->type =3D=3D DEV_TYPE_TUN) /* tun p2p topology */@@ -774,20 +731,16 @@
{
= if (rwflags & EVENT_READ)
{
- buf_printf(&out, "= ;T%s",
- = (tt->rwflags_debug & EVENT_READ) ? "R" : &quo= t;r");
+ = buf_printf(&out, "T%s", (tt->rwflags_debug & EVENT= _READ) ? "R" : "r");
#ifdef _WIN32
- buf_printf(&a= mp;out, "%s",
- overlapped_io_state_ascii(&tt->reads));
+ buf_printf(= &out, "%s", overlapped_io_state_ascii(&tt->reads));

#endif
}
i= f (rwflags & EVENT_WRITE)
{
- buf_printf(&out, "T= %s",
- = (tt->rwflags_debug & EVENT_WRITE) ? "W" : "= ;w");
+ = buf_printf(&out, "T%s", (tt->rwflags_debug & EVENT_= WRITE) ? "W" : "w");
#ifdef _WIN32
- buf_printf(&a= mp;out, "%s",
- overlapped_io_state_ascii(&tt->writes));
+ buf_printf= (&out, "%s", overlapped_io_state_ascii(&tt->writes));<= /span>
#endif
}
}
@@ -806,8 +759,7 @@
{
= bool tun_p2p =3D false;

- if (tt->type =3D=3D DEV_TYPE_TAP
- || (tt->type =3D=3D DEV_TY= PE_TUN && tt->topology =3D=3D TOP_SUBNET))

+ if (tt->type =3D=3D DEV_TYPE_TAP |= | (tt->type =3D=3D DEV_TYPE_TUN && tt->topology =3D=3D TOP_SU= BNET))
{
tun_p2p =3D false;
}
@@ -817,7 +769,8 @@
= }
else
{
- msg(M_FATAL, "Error: problem = with tun vs. tap setting"); /* JYFIXME -- needs to be caught earlier, = in init_tun? */
+ = msg(M_FATAL, "Error: problem with tun vs. tap setting"); /* J= YFIXME -- needs to be caught
+ = earlier, in init_tun? */
}
retu= rn tun_p2p;
}
@@ -870,20 +823,16 @@=
* but don't execute yet.
*/
struct tuntap *

-in= it_tun(const char *dev, /* --dev option */
- const char *dev_type, /* --dev-type = option */
- int= topology, /* one of the TOP_x values */
- const char *ifconfig_local_parm, = /* --ifconfig parm 1 */
- const char *ifconfig_remote_netmask_parm, /* --ifconfig p= arm 2 */
- cons= t char *ifconfig_ipv6_local_parm, /* --ifconfig parm 1 IPv6 */<= br>+init_tun(const char *dev, = /* --dev option */
+ const char *dev_type, /= * --dev-type option */
+ co= nst char *ifconfig_local_parm, /* --ifconfig parm 1 */
<= span style=3D"color: hsl(120, 100%, 40%);">+ const char *ifconfig_r= emote_netmask_parm, /* --ifconfig parm 2 */

+ const char *ifconfig_ipv6_local_parm, = /* --ifconfig parm 1 IPv6 */
int ifconfig_ipv6_ne= tbits_parm,
- c= onst char *ifconfig_ipv6_remote_parm, /* --ifconfig parm 2 IPv6 */
- struct addrinfo *= local_public,
- = struct addrinfo *remote_public,
- const bool strict_warn,
- struct env_set *es,
- openvpn_net_ctx_t *ctx,
- struct tuntap *tt)
<= br>+ const char *ifconf= ig_ipv6_remote_parm, /* --ifconfig parm 2 IPv6 */
+ struct addrinfo *local_public, s= truct addrinfo *remote_public, const bool strict_warn,
+ struct env_set *es, openvpn_net= _ctx_t *ctx, struct tuntap *tt)
{
if = (!tt)
{
@@ -905,25 +854,13 @@ * Convert arguments to binary IPv4 addresses.
<= span> */


- tt->local =3D getaddr(
- GETADDR_RESOLVE
- | GETADDR_HOST_ORDER
= - | GETADDR_FATAL_ON_S= IGNAL
- | GE= TADDR_FATAL,
- = ifconfig_local_parm,
- 0,
- = NULL,
- = NULL);
+ tt= ->local =3D
+ = getaddr(GETADDR_RESOLVE | GETADDR_HOST_ORDER | GETADDR_FATAL_ON_SIGN= AL | GETADDR_FATAL,
+= ifconfig_local_parm, 0, NULL, NULL);
<= /span>
- tt->remote_= netmask =3D getaddr(
- = (tun_p2p ? GETADDR_RESOLVE : 0)
- | GETADDR_HOST_ORDER
- | GETADDR_FATAL_ON_SIGNAL
- | GETADDR_FATAL= ,
- ifconfig= _remote_netmask_parm,
-= 0,
- = NULL,
- = NULL);
+ tt-&= gt;remote_netmask =3D getaddr((tun_p2p ? GETADDR_RESOLVE : 0) | GETADDR_HOS= T_ORDER
+ = | GETADDR_FATAL_ON_SIGNAL | GETADDR_FATAL,
+ = ifconfig_remote_netmask_parm, 0, NULL, NULL);

/*
* Look for common = errors in --ifconfig parms
@@ -942,12 +879,9 @@
<= span> {

if (curele->ai_fami= ly =3D=3D AF_INET)
{
- const in_addr_t local = =3D ntohl(((struct sockaddr_in *)curele->ai_addr)->sin_addr.s_addr);<= /span>
- ch= eck_addr_clash("local",
- tt->type,
- = local,

- = tt->local,
- tt->remote_netmask)= ;
+ = const in_addr_t local =3D
+ ntohl(((struct sockaddr_in *)curele->ai_= addr)->sin_addr.s_addr);
+ check_addr_clash("local", tt->type= , local, tt->local, tt->remote_netmask);
= }
}

@@ = -955,12 +889,9 @@
{
= if (curele->ai_family =3D=3D AF_INET)
= {
- = const in_addr_t remote =3D ntohl(((struct sockaddr_in *)curele->ai= _addr)->sin_addr.s_addr);
- check_addr_clash("remote",
<= span style=3D"color: hsl(0, 100%, 40%);">- = tt->type,

- = remote,
- tt->local,=
- = tt->remote_netmask);
+ const in_addr_t remote =3D
+ ntohl(((str= uct sockaddr_in *)curele->ai_addr)->sin_addr.s_addr);

+ check_addr_clas= h("remote", tt->type, remote, tt->local, tt->remote_netm= ask);

}
}
}
@@ -986,15 +917,15 @@

if (ifconfig_ipv6_local_parm && ifconfig_= ipv6_remote_parm)
{
-
/*
*= Convert arguments to binary IPv6 addresses.
*/

- = if (inet_pton( AF_INET6, ifconfig_ipv6_local_parm, &tt->local_ipv= 6 ) !=3D 1
- = || inet_pton( AF_INET6, ifconfig_ipv6_remote_parm, &tt->remote_ipv6= ) !=3D 1)
+ i= f (inet_pton(AF_INET6, ifconfig_ipv6_local_parm, &tt->local_ipv6) != =3D 1
+ ||= inet_pton(AF_INET6, ifconfig_ipv6_remote_parm, &tt->remote_ipv6) != =3D 1)
{
- msg( M_FATAL, "init_tun: problem converting IP= v6 ifconfig addresses %s and %s to binary", ifconfig_ipv6_local_parm, = ifconfig_ipv6_remote_parm );
+ msg(M_FATAL, "init_tun: problem converting IPv6 i= fconfig addresses %s and %s to binary",
+ ifconfig_ipv6_local_parm, ifconfig= _ipv6_remote_parm);
}
tt-= >netbits_ipv6 =3D ifconfig_ipv6_netbits_parm;
@@ -1016,9 +947,7 @@
* Platform specific tun init= ializations
*/
void
-init_tun_post(struct tuntap *tt,- const struct fram= e *frame,
- = const struct tuntap_options *options)
+init_tun_post(struct tuntap *tt, const struct frame *fr= ame, const struct tuntap_options *options)
{
tt->options =3D *options;

#ifdef _WIN32<= br>@@ -1045,8 +974,7 @@
* -> helper function to = simplify code below
*/
static void
-add_route_connected_v6_net(= struct tuntap *tt,
- = const struct env_set *es)
+add_route_connected_v6_net(struct tuntap *tt,= const struct env_set *es)
{
struct r= oute_ipv6 r6;

@@ -1054,8 +982,8 @@=
r6.network =3D tt->local_ipv6;
r6.ne= tbits =3D tt->netbits_ipv6;
r6.gateway =3D tt->l= ocal_ipv6;
- r6.metr= ic =3D 0; /* connected route */
- r6.flags =3D RT_DEFINED | RT_METRIC_D= EFINED;
+ r6.metri= c =3D 0; /* connected route */
+ r6.flags =3D RT_DEFINED | RT_METRIC_DEFINED;
add_route_ipv6(&r6, tt, 0, es, NULL);

}
@@ -1068,15 +996,16 @@
r6.ne= twork =3D tt->local_ipv6;
r6.netbits =3D tt->net= bits_ipv6;
r6.gateway =3D tt->local_ipv6;- r6.metric =3D 0; = /* connected route */
- r6.flags =3D RT_DEFINED | RT_ADDED | RT_METRIC_DEFINED;
+ r6.metric =3D 0; /= * connected route */
= + r6.flags =3D RT_DEFINED | RT_ADDED | RT_METRIC_DEFINED;
route_ipv6_clear_host_bits(&r6);

delete_rou= te_ipv6(&r6, tt, NULL, NULL);
}
-#endif /* if defined(_WIN32) || defined(TAR= GET_DARWIN) || defined(TARGET_NETBSD) || defined(TARGET_OPENBSD) */<= br>+#endif /* if defined(_WIN32= ) || defined(TARGET_DARWIN) || defined(TARGET_NETBSD) || \
+ defined(TARGET_OPENBSD) */=

-#if= defined(TARGET_FREEBSD) || defined(TARGET_DRAGONFLY) \
- || defined(TARGET_NETBSD) || defined= (TARGET_OPENBSD)
+#if= defined(TARGET_FREEBSD) || defined(TARGET_DRAGONFLY) || defined(TARGET_NET= BSD) \
+ || define= d(TARGET_OPENBSD)
/* we can't use true subnet mode on = tun on all platforms, as that
* conflicts with IPv6 (want= s to use ND then, which we don't do),
* but the OSes = want "a remote address that is different from ours"
@@ -1087,11 +1016,11 @@

*/
in_addr_t
-crea= te_arbitrary_remote( struct tuntap *tt )
+create_arbitrary_remote(struct tuntap *tt)
<= span> {

in_addr_t remote;

= - remote =3D (tt->local &am= p; tt->remote_netmask) +1;
+ remote =3D (tt->local & tt->remote_netmask) + 1;

if (remote =3D=3D tt->local)=
{
@@ -1112,8 +1041,8 @@
* = @param ctx the networking API opaque context
*/
static void
-do_ifconfig_ipv6(struct tuntap *tt, const char *ifname, int tun_mtu,
- const s= truct env_set *es, openvpn_net_ctx_t *ctx)
+do_ifconfig_ipv6(struct tuntap *tt, const char *ifna= me, int tun_mtu, const struct env_set *es,
+ openvpn_net_ctx_t *ctx)
<= span> {

#if !defined(TARGET_LINUX)
st= ruct argv argv =3D argv_new();
@@ -1132,16 +1061,14 @@
msg(M_FATAL, "Linux can't bring %s up", = ifname);
}

- if (net_addr_v6_add(ctx, ifname, &tt-&g= t;local_ipv6,
- = tt->netbits_ipv6) < 0)
+ if (net_addr_v6_add(ctx, ifname, &tt->l= ocal_ipv6, tt->netbits_ipv6) < 0)
{
msg(M_FATAL, "Linux can't add IPv6 to interface %s&qu= ot;, ifname);

}
#elif defined(TARGET_= ANDROID)
char out6[64];

- snprintf(out6, sizeof(out6), &= quot;%s/%d %d",

- = ifconfig_ipv6_local, tt->netbits_ipv6, tun_mtu);
<= span style=3D"color: hsl(120, 100%, 40%);">+ snprintf(out6, sizeof(out6)= , "%s/%d %d", ifconfig_ipv6_local, tt->netbits_ipv6, tun_mtu);=

management_android_control(management, "IFCONFIG= 6", out6);
#elif defined(TARGET_SOLARIS)
argv_printf(&argv, "%s %s inet6 unplumb", IFCONFIG_P= ATH, ifname);

@@ -1152,9 +1079,8 @@
{<= /span>
const char *ifconfig_ipv6_remote =3D print_in6_add= r(tt->remote_ipv6, 0, &gc);

- argv_printf(&argv, "%s %s = inet6 plumb %s/%d %s mtu %d up",
- IFCONFIG_PATH, ifname, ifconfig_ipv6_lo= cal,
- = tt->netbits_ipv6, ifconfig_ipv6_remote, tun_mtu);
+ argv_printf(&argv, "%s= %s inet6 plumb %s/%d %s mtu %d up", IFCONFIG_PATH, ifname,
= + ifconfig_i= pv6_local, tt->netbits_ipv6, ifconfig_ipv6_remote, tun_mtu);
<= span> }

else /* tap mode */
{=
@@ -1162,8 +1088,7 @@
argv_printf= (&argv, "%s %s inet6 plumb up", IFCONFIG_PATH, ifname);
argv_msg(M_INFO, &argv);
- if (!openvpn_execve_ch= eck(&argv, es, 0,
-= "Solaris ifconfig IPv6 (prepare) fai= led"))
+ = if (!openvpn_execve_check(&argv, es, 0, "Solaris ifconfig IPv6 (pr= epare) failed"))
{
= solaris_error_close(tt, es, ifname, true);
}
@@ -1177,8 +1102,8 @@
/* static IPv6= addresses need to go to a subinterface (tap0:1)
= * and we cannot set an mtu here (must go to the "parent")<= br> */
-= argv_printf(&argv, "%s %s inet6 addif %s/%d up", IFCO= NFIG_PATH,
- = ifname, ifconfig_ipv6_local, tt->netbits_ipv6 );
+ argv_printf(&argv, &qu= ot;%s %s inet6 addif %s/%d up", IFCONFIG_PATH, ifname, ifconfig_ipv6_l= ocal,

+ = tt->netbits_ipv6);
}
arg= v_msg(M_INFO, &argv);

@@ -1189,23 +11= 14,19 @@

if (tt->type !=3D DEV_TY= PE_TUN)
{
- argv_printf(&argv, "%s %s inet6 mtu %d", IFC= ONFIG_PATH,
- = ifname, tun_mtu);
+ argv_printf(&argv, "%s %s inet6 mtu %d", IFCO= NFIG_PATH, ifname, tun_mtu);
argv_msg(M_INFO, &= ;argv);
openvpn_execve_check(&argv, es, 0, &qu= ot;Solaris ifconfig IPv6 mtu failed");
}-#elif defined(TARGET_OPENBSD) = || defined(TARGET_NETBSD) \
- || defined(TARGET_DARWIN) || defined(TARGET_FREEBSD) \
= - || defined(TARGET_DRAGONFLY)=
- argv_printf(&= argv, "%s %s inet6 %s/%d mtu %d up", IFCONFIG_PATH, ifname,
- ifconfig_ip= v6_local, tt->netbits_ipv6, tun_mtu);
+#elif defined(TARGET_OPENBSD) || defined(TARGET_NETBSD= ) || defined(TARGET_DARWIN) \
+ || defined(TARGET_FREEBSD) || defined(TARGET_DRAGONFLY)
+ argv_printf(&argv= , "%s %s inet6 %s/%d mtu %d up", IFCONFIG_PATH, ifname, ifconfig_= ipv6_local,
+ = tt->netbits_ipv6, tun_mtu);
argv_msg(M_INFO= , &argv);

- openvpn_execve_check(&argv, es, S_FATAL,
- "generic= BSD ifconfig inet6 failed");
+ openvpn_execve_check(&argv, es, S_FATAL, "gener= ic BSD ifconfig inet6 failed");

-#if defined(TARGET_FREEBSD) && __F= reeBSD_version >=3D 1200000 \
- && __FreeBSD_version < 1300000
+#if defined(TARGET_FREEBSD) &&= __FreeBSD_version >=3D 1200000 && __FreeBSD_version < 130000= 0
/* On FreeBSD 12.0-12.4, there is ipv6_activate_all_= interfaces=3D"YES"
* in rc.conf, which is n= ot set by default. If it is *not* set,
* "all n= ew interfaces that are not already up" are configured by
@@ -1224,27 +1145,26 @@

argv_printf(&argv, &quo= t;%s %s inet6 -ifdisabled", IFCONFIG_PATH, ifname);
= argv_msg(M_INFO, &argv);

- openvpn_execve_check(&argv, es, S_FATAL= ,
- = "FreeBSD BSD 'ifconfig inet6 -ifdisabled' failed");<= /span>
+ openvpn_execve_c= heck(&argv, es, S_FATAL, "FreeBSD BSD 'ifconfig inet6 -ifdisab= led' failed");
#endif
#elif defined(TARGET_AIX)
- argv_printf(&argv, "%s %s inet6 %s/%d mtu %d up&qu= ot;, IFCONFIG_PATH, ifname,
- ifconfig_ipv6_local, tt->netbits_ipv6, tun_mtu);
+ argv_printf(&= argv, "%s %s inet6 %s/%d mtu %d up", IFCONFIG_PATH, ifname, ifcon= fig_ipv6_local,
+ = tt->netbits_ipv6, tun_mtu);
argv_msg(M_= INFO, &argv);

/* AIX ifconfig wi= ll complain if it can't find ODM path in env */
es= =3D env_set_create(NULL);
env_set_add(es, "ODMDI= R=3D/etc/objrepos");

- openvpn_execve_check(&argv, es, S_FATAL,
- &= quot;generic BSD ifconfig inet6 failed");
+ openvpn_execve_check(&argv, es, S_FATAL,= "generic BSD ifconfig inet6 failed");
env_set_destroy(es);
-#elif defined (_WIN32)
+#elif defined(_WIN32)
if (tt->option= s.ip_win32_type =3D=3D IPW32_SET_MANUAL)
{
<= span style=3D"color: hsl(0, 100%, 40%);">- msg(M_INFO, "*******= * NOTE: Please manually set the v6 IP of '%s' to %s (if it is not = already set)",

+= msg(M_INFO,
+= "******** NOTE: Please manually set the v6 IP of '%s&= #39; to %s (if it is not already set)",
i= fname, ifconfig_ipv6_local);
}
el= se if (tt->options.msg_channel)
@@ -1275,8 +1195,8 @@
int netbits =3D (tt->type =3D=3D DEV_TYPE_TUN) ? = 128 : tt->netbits_ipv6;

argv_= printf(&argv, "%s%s interface ipv6 set address %lu %s/%d store=3Da= ctive",
- = get_win_sys_path(), NETSH_PATH_SUFFIX, tt->adapter_index,
- ifcon= fig_ipv6_local, netbits);
+ get_win_sys_path(), NETSH_PATH_SUFFIX, tt->ada= pter_index, ifconfig_ipv6_local,
+ netbits);
netsh_c= ommand(&argv, 4, M_FATAL);
if (tt->type =3D= =3D DEV_TYPE_TUN)
{
@@ -1291,8 +12= 11,9 @@
do_dns_domain_wmic(true, tt); }
}
-#else /* platforms we have no IPv6 code for */- msg(M_FATAL, "Sorry, = but I don't know how to do IPv6 'ifconfig' commands on this ope= rating system. You should ifconfig your TUN/TAP device manually or use an = --up script.");
= +#else /* platforms we have no IPv6 code for */
+ msg(M_FATAL,
+ "Sorry, but I don't know how to = do IPv6 'ifconfig' commands on this operating system. You should i= fconfig your TUN/TAP device manually or use an --up script.");<= br> #endif /* outer "if defined(TARGET_xxx)" conditional */=

#if !defined(TARGET_LINUX)
@@ -1311,8 +1232,8 @@

* @param ctx the networki= ng API opaque context
*/
static void
-do_ifconfig_ipv4(struct t= untap *tt, const char *ifname, int tun_mtu,
- const struct env_set *es, openvpn_ne= t_ctx_t *ctx)
+do_ifc= onfig_ipv4(struct tuntap *tt, const char *ifname, int tun_mtu, const struct= env_set *es,
+ = openvpn_net_ctx_t *ctx)
{
#if = !defined(_WIN32) && !defined(TARGET_ANDROID)
/= *
@@ -1347,16 +1268,14 @@

if (tun_p2p)

{
- if (net_addr_ptp_v4_add(ctx, ifname, &tt-&g= t;local,
- = &tt->remote_netmask) < 0)
+ if (net_addr_ptp_v4_add(ctx, ifn= ame, &tt->local, &tt->remote_netmask) < 0)
{

msg(M_FATAL, "Linux can't= add IP to interface %s", ifname);
} }
else
{
<= span style=3D"color: hsl(0, 100%, 40%);">- if (net_addr_v4_add(ctx, = ifname, &tt->local,

- netmask_to_netbits2(tt->remote_netmask)= ) < 0)
+ if= (net_addr_v4_add(ctx, ifname, &tt->local, netmask_to_netbits2(tt-&g= t;remote_netmask)) < 0)
{
= msg(M_FATAL, "Linux can't add IP to interface %s", if= name);
}
@@ -1364,8 +1283,8 @@
#elif defined(TARGET_ANDROID)
char out[6= 4];

-= snprintf(out, sizeof(out), "%s %s %d %s", ifconfig_local,
- ifconfig_rem= ote_netmask, tun_mtu, print_topology(tt->topology));
+ snprintf(out, sizeof(out), "%s= %s %d %s", ifconfig_local, ifconfig_remote_netmask, tun_mtu,+ print_topology(= tt->topology));
management_android_control(manageme= nt, "IFCONFIG", out);

#elif de= fined(TARGET_SOLARIS)
@@ -1376,8 +1295,8 @@
*/

if (tun_p2p)
{- argv_printf(&argv,= "%s %s %s %s mtu %d up", IFCONFIG_PATH, ifname,
- ifconfig_local, if= config_remote_netmask, tun_mtu);
+ argv_printf(&argv, "%s %s %s %s mtu %d up&quo= t;, IFCONFIG_PATH, ifname, ifconfig_local,
+ ifconfig_remote_netmask, tun_mtu= );

argv_msg(M_INFO, &argv);<= /span>
if (!openvpn_execve_check(&argv, es, 0, "= Solaris ifconfig phase-1 failed"))
@@ -1385,19 +1304,1= 6 @@
solaris_error_close(tt, es, ifname, false= );
}

- argv_printf(&argv, "%s %s netmas= k 255.255.255.255", IFCONFIG_PATH,
- ifname);
+ argv_printf(&argv, "%s %s netma= sk 255.255.255.255", IFCONFIG_PATH, ifname);
}
else if (tt->type =3D=3D DEV_TYPE_TUN)
{

- argv_= printf(&argv, "%s %s %s %s netmask %s mtu %d up", IFCONFIG_PA= TH,
- = ifname, ifconfig_local, ifconfig_local,
- ifconfig_remote_netmask, tun_mtu);<= /span>
+ argv_printf(= &argv, "%s %s %s %s netmask %s mtu %d up", IFCONFIG_PATH, ifn= ame,
+ = ifconfig_local, ifconfig_local, ifconfig_remote_netmask, tun_mtu);
}
else /* tap */
= {
- argv_print= f(&argv, "%s %s %s netmask %s up",
- IFCONFIG_PATH, ifname, ifcon= fig_local,
+ a= rgv_printf(&argv, "%s %s %s netmask %s up", IFCONFIG_PATH, if= name, ifconfig_local,
ifconfig_remote_= netmask);
}

@@ -1422= ,7 +1338,7 @@

#elif defined(TARGET_OPENB= SD)

-= in_addr_t remote_end; /* for "virtual" subnet topol= ogy */
+ in_addr_t= remote_end; /* for "virtual" subnet topology */
=
/*
* On OpenBSD, tun interface= s are persistent if created with
@@ -1433,24 +1349,20 @@
/* example: ifconfig tun2 10.2.0.2 10.2.0.1 mtu 1450 net= mask 255.255.255.255 up */
if (tun_p2p)
{

- argv_= printf(&argv,
- = "%s %s %s %s mtu %d netmask 255.255.255.255 up -link0&= quot;,
- = IFCONFIG_PATH, ifname, ifconfig_local,
- ifconfig_remote_netmask, tun_mtu)= ;
+ argv_print= f(&argv, "%s %s %s %s mtu %d netmask 255.255.255.255 up -link0&quo= t;, IFCONFIG_PATH,
+ = ifname, ifconfig_local, ifconfig_remote_netmask, tun_mtu= );
}
else if (tt->type =3D=3D = DEV_TYPE_TUN)
{
- remote_end =3D create_arbitrary_remote( tt );=
- argv_printf(&arg= v, "%s %s %s %s mtu %d netmask %s up -link0",
- IFCONFIG_PATH, ifname= , ifconfig_local,
- = print_in_addr_t(remote_end, 0, &gc), tun_mtu,+ remote_end =3D create= _arbitrary_remote(tt);
+ ifconfig_local, print_in_addr_t(remote_e= nd, 0, &gc), tun_mtu,
ifconfig_rem= ote_netmask);
}
else /* tap */
{
- = argv_printf(&argv, "%s %s %s netmask %s mtu %d link0",=
- I= FCONFIG_PATH, ifname, ifconfig_local,
- ifconfig_remote_netmask, tun_mtu);
+ argv_printf(&= ;argv, "%s %s %s netmask %s mtu %d link0", IFCONFIG_PATH, ifname,=
+ = ifconfig_local, ifconfig_remote_netmask, tun_mtu);
}<= /span>
argv_msg(M_INFO, &argv);
open= vpn_execve_check(&argv, es, S_FATAL, "OpenBSD ifconfig failed"= ;);
@@ -1468,20 +1380,19 @@
}
#elif defined(TARGET_NETBSD)
- in_addr_t remote_end =3D INADDR_ANY; = /* for "virtual" subnet topology */
+ in_addr_t remote_end =3D INADDR_ANY; /* for = "virtual" subnet topology */

= if (tun_p2p)
{
- argv_printf(&argv, "%s %s %s %s mtu %d ne= tmask 255.255.255.255 up",
- IFCONFIG_PATH, ifname, ifconfig_local,=
- ifconfig= _remote_netmask, tun_mtu);
+ argv_printf(&argv, "%s %s %s %s mtu %d netmask 255.= 255.255.255 up", IFCONFIG_PATH, ifname,
+ ifconfig_local, ifconfig_remot= e_netmask, tun_mtu);
}
else if (t= t->type =3D=3D DEV_TYPE_TUN)
{
= remote_end =3D create_arbitrary_remote(tt);
- argv_printf(&argv, "%s %s %s %s= mtu %d netmask %s up", IFCONFIG_PATH,
- ifname, ifconfig_local, print_in_= addr_t(remote_end, 0, &gc),
- tun_mtu, ifconfig_remote_netmask);
= + argv_printf(&argv,= "%s %s %s %s mtu %d netmask %s up", IFCONFIG_PATH, ifname,
+ ifcon= fig_local, print_in_addr_t(remote_end, 0, &gc), tun_mtu,
+ ifconfig_remot= e_netmask);

}
else /* tap */
{
@@ -1490,8 +1401,7 @@
= * so we don't need the "link0" extra parameter to spe= cify we want to do
* tunneling at the ethernet le= vel
*/
- argv_printf(&argv, "%s %s %s netmask %s mtu %d&= quot;,
- = IFCONFIG_PATH, ifname, ifconfig_local,
+ argv_printf(&argv, "%s %s %s netma= sk %s mtu %d", IFCONFIG_PATH, ifname, ifconfig_local,
= ifconfig_remote_netmask, tun_mtu);
= }
argv_msg(M_INFO, &argv);
@@ -1= 517,28 +1427,24 @@
argv_printf(&argv, "%s %s = delete", IFCONFIG_PATH, ifname);
argv_msg(M_INFO,= &argv);
openvpn_execve_check(&argv, es, 0, NU= LL);
- msg(M_INFO,
- "NOTE: Tri= ed to delete pre-existing tun/tap instance -- No Problem if failure");=
+ msg(M_INFO, &qu= ot;NOTE: Tried to delete pre-existing tun/tap instance -- No Problem if fai= lure");


/* ex= ample: ifconfig tun2 10.2.0.2 10.2.0.1 mtu 1450 netmask 255.255.255.255 up = */
if (tun_p2p)
{
- argv_printf(&argv, "= %s %s %s %s mtu %d netmask 255.255.255.255 up",

- IFCONFIG_PATH, ifname, = ifconfig_local,
- = ifconfig_remote_netmask, tun_mtu);
+ argv_printf(&argv, "%s %s %s = %s mtu %d netmask 255.255.255.255 up", IFCONFIG_PATH, ifname,+ ifconfig= _local, ifconfig_remote_netmask, tun_mtu);
} else if (tt->type =3D=3D DEV_TYPE_TUN)
= {
- argv_printf(= &argv, "%s %s %s %s netmask %s mtu %d up",
- IFCONFIG_PATH, ifnam= e, ifconfig_local, ifconfig_local,
- ifconfig_remote_netmask, tun_mtu);<= br>+ argv_printf(&ar= gv, "%s %s %s %s netmask %s mtu %d up", IFCONFIG_PATH, ifname,
+ if= config_local, ifconfig_local, ifconfig_remote_netmask, tun_mtu);
= }
else /* tap */
{
- argv_printf(&= argv, "%s %s %s netmask %s mtu %d up", IFCONFIG_PATH,
<= span style=3D"color: hsl(0, 100%, 40%);">- ifname, ifcon= fig_local, ifconfig_remote_netmask,

- tun_mtu);
+ argv_printf(&argv, "%s %s %s netma= sk %s mtu %d up", IFCONFIG_PATH, ifname, ifconfig_local,
+ ifconfig_remo= te_netmask, tun_mtu);

}

argv_msg(M_INFO, &argv);

@@ -1559,17 +1465,16 = @@
#elif defined(TARGET_FREEBSD) || defined(TARGET_DRAGONF= LY)

/* example: ifconfig tun2 10.2.0= .2 10.2.0.1 mtu 1450 netmask 255.255.255.255 up */
- if (tun_p2p) /* point-to-point tun */
+ if (tun_p2p) /* p= oint-to-point tun */
{
- argv_printf(&argv, "%s %s %s %s mtu = %d netmask 255.255.255.255 up",
- IFCONFIG_PATH, ifname, ifconfig_local,
- ifc= onfig_remote_netmask, tun_mtu);
+ argv_printf(&argv, "%s %s %s %s mtu %d netmask= 255.255.255.255 up", IFCONFIG_PATH, ifname,
+ ifconfig_local, ifconfig_= remote_netmask, tun_mtu);
}
- else /* tun with topology subnet = and tap mode (always subnet) */
+ else /* tun with topology subnet and tap mode (always subne= t) */
{
int netbits =3D netma= sk_to_netbits2(tt->remote_netmask);
- argv_printf(&argv, "%s %s %s/%d mtu %d up= ", IFCONFIG_PATH,
= - ifname, ifconfig_local, netbits, tun_mtu );
= + argv_printf(&argv,= "%s %s %s/%d mtu %d up", IFCONFIG_PATH, ifname, ifconfig_local, = netbits,
+ = tun_mtu);
}

argv_msg(M_INFO, &argv);

@@ -1579,7 +1484,7 @@
{
/* AIX ifconfig will complain= if it can't find ODM path in env */
struct en= v_set *aix_es =3D env_set_create(NULL);
- env_set_add( aix_es, "ODMDIR=3D/etc/objrepos= " );
+ en= v_set_add(aix_es, "ODMDIR=3D/etc/objrepos");

if (tt->type =3D=3D DEV_TYPE_TUN)
{

@@ -1587,23 +1492,23 @@
= }

/* example: ifconfig tap0 17= 2.30.1.1 netmask 255.255.254.0 up */
- argv_printf(&argv, "%s %s %s netmask %s mtu= %d up", IFCONFIG_PATH,
- ifname, ifconfig_local, ifconfig_remote_netmask,= tun_mtu);
+ a= rgv_printf(&argv, "%s %s %s netmask %s mtu %d up", IFCONFIG_P= ATH, ifname, ifconfig_local,
+ ifconfig_remote_netmask, tun_mtu);
<= span>

argv_msg(M_INFO, &argv);
openvpn_execve_check(&argv, aix_es, S_FATAL, "AIX ifcon= fig failed");


env_set_destr= oy(aix_es);
}
-#elif defined (_WIN32)
+#elif defined(_WIN32)
if (tt->optio= ns.ip_win32_type =3D=3D IPW32_SET_MANUAL)
{
= msg(M_INFO,
"******** NOTE= : Please manually set the IP/netmask of '%s' to %s/%s (if it is no= t already set)",
-= ifname, ifconfig_local,
- ifconfig_remote_netmask);
+ ifname, ifconfig_local, ifcon= fig_remote_netmask);
}
- else if (tt->options.ip_win32_type =3D=3D IPW3= 2_SET_DHCP_MASQ || tt->options.ip_win32_type =3D=3D IPW32_SET_ADAPTIVE)<= /span>
+ else if (tt->= options.ip_win32_type =3D=3D IPW32_SET_DHCP_MASQ
+ || tt->options.ip_win32_type = =3D=3D IPW32_SET_ADAPTIVE)
{
= /* Let the DHCP configure the interface. */
}@@ -1618,8 +1523,8 @@
{
= if (tt->options.ip_win32_type =3D=3D IPW32_SET_NETSH)
{

- = netsh_ifconfig(&tt->options, tt->adapter_index, tt->local,
- = tt->adapter_netmask, NI_IP_NETMASK | NI_OPTIONS);
+ netsh_ifconfig(&tt->= ;options, tt->adapter_index, tt->local, tt->adapter_netmask,
+ = NI_IP_NETMASK | NI_OPTIONS);
}
=
do_dns_domain_wmic(true, tt);
@@ = -1636,13 +1541,14 @@
}
#elif defined(= TARGET_HAIKU)
/* example: ifconfig tun/0 inet 1.1.1.1 = 255.255.255.0 mtu 1450 up */
- argv_printf(&argv, "%s %s inet %s %s mtu %d up", I= FCONFIG_PATH,
- = ifname, ifconfig_local, ifconfig_remote_netmask, tun_mtu);+ argv_printf(&argv, &= quot;%s %s inet %s %s mtu %d up", IFCONFIG_PATH, ifname, ifconfig_loca= l,
+ i= fconfig_remote_netmask, tun_mtu);

ar= gv_msg(M_INFO, &argv);
openvpn_execve_check(&a= rgv, es, S_FATAL, "Haiku ifconfig failed");
#els= e /* if defined(TARGET_LINUX) */
- msg(M_FATAL, "Sorry, but I don't know how to do &#= 39;ifconfig' commands on this operating system. You should ifconfig yo= ur TUN/TAP device manually or use an --up script.");
+ msg(M_FATAL,
+ "Sorry, but I don't kno= w how to do 'ifconfig' commands on this operating system. You shou= ld ifconfig your TUN/TAP device manually or use an --up script.");
#endif /* if defined(TARGET_LINUX) */

#if !defined(TARGET_LINUX)
@@ -1653,8 +1559,8 @= @

/* execute the ifconfig command throug= h the shell */
void
-do_ifconfig(struct tuntap *tt, const char *ifname, int tun_m= tu,
- const = struct env_set *es, openvpn_net_ctx_t *ctx)
+do_ifconfig(struct tuntap *tt, const char *ifname, = int tun_mtu, const struct env_set *es,
+ openvpn_net_ctx_t *ctx)
{
msg(D_LOW, "do_ifconfig, ipv4=3D%d, ipv6=3D%d"= ;, tt->did_ifconfig_setup,
tt->did_ifconfig_= ipv6_setup);
@@ -1662,13 +1568,8 @@
#ifdef= ENABLE_MANAGEMENT
if (management)
= {
- management= _set_state(management,
= - OPENVPN_STATE_ASSIGN_IP,
- NULL,<= br>- = &tt->local,
- = &tt->local_ipv6,
- NULL,
- NULL)= ;

+ management= _set_state(management, OPENVPN_STATE_ASSIGN_IP, NULL, &tt->local, &a= mp;tt->local_ipv6,
+ NULL, NULL);
} #endif

@@ -1694,19 +1595,16 @@

if (is_tun_p2p(tt))
= {
- if (net_= addr_ptp_v4_del(ctx, tt->actual_name, &tt->local,
- &= tt->remote_netmask) < 0)

+ if (net_addr_ptp_v4_del(ctx, tt->actual_name, &tt= ->local, &tt->remote_netmask) < 0)
{<= /span>
- msg(M_WARN= , "Linux can't del IP from iface %s",
- tt->actual_name);=
+ msg(M_WARN, &q= uot;Linux can't del IP from iface %s", tt->actual_name);=
}
}
else
{
if (net_addr_v4_del(ctx, tt->= actual_name, &tt->local, netbits) < 0)
{=
- msg(M_WAR= N, "Linux can't del IP from iface %s",
- tt->actual_name);=
+ msg(M_WARN, &q= uot;Linux can't del IP from iface %s", tt->actual_name);=
}
}
#elif defined(= TARGET_FREEBSD)
@@ -1714,8 +1612,7 @@
= const char *ifconfig_local =3D print_in_addr_t(tt->local, 0, &gc);
struct argv argv =3D argv_new();

- argv_printf(&argv,= "%s %s %s -alias", IFCONFIG_PATH,
- tt->actual_name, ifconfig_local);=
+ argv_printf(&am= p;argv, "%s %s %s -alias", IFCONFIG_PATH, tt->actual_name, ifc= onfig_local);
argv_msg(M_INFO, &argv);
<= span> openvpn_execve_check(&argv, NULL, 0, "FreeBSD ip addr de= l failed");


@@ -1729,8 +1626,7 @@
undo_ifconfig_ipv6(struct tuntap *tt, openvpn_net_ctx_t *ctx= )
{
#if defined(TARGET_LINUX)
<= span style=3D"color: hsl(0, 100%, 40%);">- if (net_addr_v6_del(ctx, tt-&= gt;actual_name, &tt->local_ipv6,

- tt->netbits_ipv6) < 0)
+ if (net_addr_v6_del(= ctx, tt->actual_name, &tt->local_ipv6, tt->netbits_ipv6) < = 0)
{
msg(M_WARN, "Linux = can't del IPv6 from iface %s", tt->actual_name);
}

@@ -1739,8 +1635,8 @@
const c= har *ifconfig_ipv6_local =3D print_in6_addr(tt->local_ipv6, 0, &gc);=
struct argv argv =3D argv_new();

- argv_printf(&arg= v, "%s %s inet6 %s/%d -alias", IFCONFIG_PATH,
- tt->actual_name, ifcon= fig_ipv6_local, tt->netbits_ipv6);
+ argv_printf(&argv, "%s %s inet6 %s/%d -alias= ", IFCONFIG_PATH, tt->actual_name,
+ ifconfig_ipv6_local, tt->netbits_= ipv6);

argv_msg(M_INFO, &argv);<= /span>
openvpn_execve_check(&argv, NULL, 0, "FreeBSD= ip -6 addr del failed");
@@ -1830,7 +1726,7 @@=
struct iovec iv[2];
struct open= vpn_iphdr *iph;

- iph =3D (struct openvpn_iphdr *) buf;
+ iph =3D (struct openvpn_iphdr= *)buf;

if (OPENVPN_IPH_GET_VER(= iph->version_len) =3D=3D 6)
{
@= @ -1893,8 +1789,7 @@

#if !(defined(_WIN3= 2) || defined(TARGET_LINUX) || defined(TARGET_SOLARIS))
st= atic void
-open_tun_gen= eric(const char *dev, const char *dev_type, const char *dev_node,- struct tuntap = *tt)
+open_tun_generi= c(const char *dev, const char *dev_type, const char *dev_node, struct tunta= p *tt)
{
char tunname[256]; char dynamic_name[256];
@@ -1924,10 +1819,8 @@<= /span>
#if defined(TARGET_HAIKU)
= sep =3D "/";
#endif
- snprintf(tunname, sizeof(tunname)= ,
- = "/dev/%s%s%d", dev, sep, i);
- snprintf(dynamic_name, sizeof(dynamic= _name),
- = "%s%s%d", dev, sep, i);
+ snprintf(tunname, sizeof(tunname),= "/dev/%s%s%d", dev, sep, i);
+ snprintf(dynamic_name, sizeof(dynamic_n= ame), "%s%s%d", dev, sep, i);
if= ((tt->fd =3D open(tunname, O_RDWR)) > 0)
= {
dynamic_opened =3D true;
@@ -1952,9 +1845,9 @@
if (!dynamic_opened)<= /span>
{
/* has named device existed= before? if so, don't destroy at end */
- if (if_nametoindex( dev ) > 0)
<= span style=3D"color: hsl(120, 100%, 40%);">+ if (if_nametoindex(dev)= > 0)

{
- msg(M_INFO, "TUN/TAP device %s exists previo= usly, keep at program end", dev );
+ msg(M_INFO, "TUN/TAP device %s exists = previously, keep at program end", dev);
t= t->persistent_if =3D true;
}
<= /span>
@@ -1970,14 +1863,13 @@

= /* tt->actual_name is passed to up and down scripts and used as the = ifconfig dev name */
tt->actual_name =3D string_all= oc(dynamic_opened ? dynamic_name : dev, NULL);
-
}
#endif /* !_W= IN32 && !TARGET_LINUX && !TARGET_FREEBSD*/
=
#if defined(TARGET_LINUX) || defined(TARGET_FREEBSD)
static void
-open_tun_dco_generic(const char *dev, const char *dev_type,
<= span style=3D"color: hsl(0, 100%, 40%);">- struct tunta= p *tt, openvpn_net_ctx_t *ctx)

+open_tun_dco_generic(const char *dev, const char *dev_type, stru= ct tuntap *tt,
+ = openvpn_net_ctx_t *ctx)
{
= char dynamic_name[256];
bool dynamic_opened =3D f= alse;
@@ -1994,8 +1886,7 @@
{ for (int i =3D 0; i < 256; ++i)
= {
- snprin= tf(dynamic_name, sizeof(dynamic_name),
- "%s%d", dev, i);
= + snprintf(dynamic_n= ame, sizeof(dynamic_name), "%s%d", dev, i);
= int ret =3D open_tun_dco(tt, ctx, dynamic_name);
= if (ret =3D=3D 0)
{
@@ -2025,14 +1916,12 @@

int ret =3D open_tun_dco(= tt, ctx, dev);
if (ret =3D=3D -EEXIST)
<= span> {

- = msg(M_INFO, "DCO device %s already exists, won't be destroye= d at shutdown",
- = dev);
= + msg(M_INFO, "DCO device %s already exists, won't be d= estroyed at shutdown", dev);
tt->persi= stent_if =3D true;
}
else= if (ret < 0)
{
- msg(M_ERR, "Cannot open DCO device %= s: %s (%d)", dev,
= - strerror(-ret), ret);
+ msg(M_ERR, "Cannot open DCO device %s: = %s (%d)", dev, strerror(-ret), ret);
}=
else
{
@@ -2059= ,7 +1948,7 @@
}
#endif /* !_WIN32 */

-#if defi= ned (TARGET_ANDROID)
= +#if defined(TARGET_ANDROID)
void
open_tu= n(const char *dev, const char *dev_type, const char *dev_node, struct tunta= p *tt,
openvpn_net_ctx_t *ctx)
@@= -2099,7 +1988,7 @@

int android_meth= od =3D managment_android_persisttun_action(management);

- if (oldtunfd >= =3D0 && android_method =3D=3D ANDROID_KEEP_OLD_TUN)
+ if (oldtunfd >=3D 0 &&a= mp; android_method =3D=3D ANDROID_KEEP_OLD_TUN)

{
/* keep the old fd */
opentun= =3D true;
@@ -2210,8 +2099,7 @@
}=
else
{
- msg(M_FATAL, "I don= 9;t recognize device %s as a tun or tap device",
- dev);
+ msg(M_FATAL, "I don'= t recognize device %s as a tun or tap device", dev);
= }

/*
@@ = -2226,7 +2114,7 @@
* Use special ioctl that confi= gures tun/tap device with the parms
* we set in i= fr
*/
- if (ioctl(tt->fd, TUNSETIFF, (void *) &ifr) < 0= )
+ if (ioctl(= tt->fd, TUNSETIFF, (void *)&ifr) < 0)
{<= /span>
msg(M_ERR, "ERROR: Cannot ioctl TUNSETIFF= %s", dev);
}
@@ -2247,7 +213= 5,7 @@
CLEAR(netifr);
= strncpynt(netifr.ifr_name, ifr.ifr_name, IFNAMSIZ);
= netifr.ifr_qlen =3D tt->options.txqueuelen;
- if (ioctl(c= tl_fd, SIOCSIFTXQLEN, (void *) &netifr) >=3D 0)
+ if (ioctl(ctl_fd, SIOCSI= FTXQLEN, (void *)&netifr) >=3D 0)
{=
msg(D_OSBUF, "TUN/TAP TX queue l= ength set to %d", tt->options.txqueuelen);
= }
@@ -2286,13 +2174,13 @@
=
/* TUNSETGROUP appeared in 2.6.23 */
#ifndef TU= NSETGROUP
-#define TUNS= ETGROUP _IOW('T', 206, int)
+#define TUNSETGROUP _IOW('T', 206, int) #endif

void
-tuncfg(const char *dev, const char *dev_ty= pe, const char *dev_node,
- int persist_mode, const char *username, const char *groupname,
- const struct tun= tap_options *options, openvpn_net_ctx_t *ctx)
+tuncfg(const char *dev, const char *dev_type, con= st char *dev_node, int persist_mode,
+ const char *username, const char *groupname, const = struct tuntap_options *options,
+ openvpn_net_ctx_t *ctx)
{
struct tuntap *tt;


@@ -2412,8 +23= 00,7 @@
}
else
= {
- msg(M_FAT= AL, "I don't recognize device %s as a tun or tap device",
- dev);<= br>+ msg(M_FATAL, "= I don't recognize device %s as a tun or tap device", dev);<= br> }

if ((tt->ip_fd = =3D open(ip_node, O_RDWR, 0)) < 0)
@@ -2431,7 +2318,7 @@=
/* get unit number */
if (*ptr)<= /span>
{
= - while (*ptr && !isdigit((int) *ptr))
+ while (*ptr && !isdigit((= int)*ptr))
{
ptr++;
}
@@ -2444,7 +2331,7 @@
<= span> strioc_ppa.ic_len =3D sizeof(ppa);

strioc_pp= a.ic_dp =3D (char *)&ppa;

- if (*ptr =3D=3D '\0') /* no= number given, try dynamic */
+ if (*ptr =3D=3D '\0') /* no number given, try dynamic= */
{
bool found_one =3D fals= e;
while (!found_one && ppa < 64)
@@ -2452,27 +2339,28 @@
int new_ppa= =3D ioctl(tt->fd, I_STR, &strioc_ppa);
= if (new_ppa >=3D 0)
{
- msg( M_INFO, "open_tu= n: got dynamic interface '%s%d'", dev_tuntap_type, new_ppa );<= /span>
+ msg(= M_INFO, "open_tun: got dynamic interface '%s%d'", dev_tun= tap_type, new_ppa);
ppa =3D new_ppa;
found_one =3D true;
= break;
}
if= (errno !=3D EEXIST)
{
- msg(M_ERR, "open_tun: = unexpected error trying to find free %s interface", dev_tuntap_type );=
+ msg= (M_ERR, "open_tun: unexpected error trying to find free %s interface&q= uot;,
+ = dev_tuntap_type);
}
= ppa++;
}
if (!fo= und_one)
{
- msg(M_ERR, "open_tun: could not find free %s= interface, give up.", dev_tuntap_type );
+ msg(M_ERR, "open_tun: could not= find free %s interface, give up.", dev_tuntap_type);
= }
}
- else /* try this particular one */
+ else /* try this = particular one */
{
if ((ppa = =3D ioctl(tt->fd, I_STR, &strioc_ppa)) < 0)
= {
- msg(= M_ERR, "Can't assign PPA for new interface (%s%d)", dev_tunta= p_type, ppa );
+ = msg(M_ERR, "Can't assign PPA for new interface (%s%d)"= , dev_tuntap_type, ppa);
}
}<= /span>

@@ -2489,13 +2377,13 @@
= if (tt->type =3D=3D DEV_TYPE_TUN)
{
<= span> /* Assign ppa according to the unit number returned by tun de= vice */

- if (io= ctl(if_fd, IF_UNITSEL, (char *) &ppa) < 0)
+ if (ioctl(if_fd, IF_UNITSEL, (char *)= &ppa) < 0)
{
m= sg(M_ERR, "Can't set PPA %d", ppa);
= }
}

- tt->actual_name =3D (char *) malloc(32);=
+ tt->actual_name =3D= (char *)malloc(32);
check_malloc_return(tt->actual= _name);

snprintf(tt->actual_name,= 32, "%s%d", dev_tuntap_type, ppa);
@@ -2513,7 +2= 401,7 @@
{
msg(M_ERR,= "Can't set PPA %d", ppa);
}<= br>- if (ioctl(if_fd, SIOC= GLIFFLAGS, &ifr) <0)
+ if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) < 0) {
msg(M_ERR, "Can't g= et flags\n");
}
@@ -2575,7 +2= 463,7 @@

CLEAR(ifr);
strncpynt(ifr.lifr_name, tt->actual_name, sizeof(ifr.lifr_name));<= /span>
- ifr.lifr_ip_muxid = =3D ip_muxid;
+ i= fr.lifr_ip_muxid =3D ip_muxid;
if (tt->type =3D=3D = DEV_TYPE_TAP)
{
ifr.lifr_arp_= muxid =3D arp_muxid;
@@ -2605,8 +2493,7 @@
= if (tt->did_ifconfig_ipv6_setup)
{
<= span> struct argv argv =3D argv_new();

- argv_printf( &argv, "%s %s inet6 = unplumb",
- = IFCONFIG_PATH, tt->actual_name );
+ argv_printf(&argv, "%s %s i= net6 unplumb", IFCONFIG_PATH, tt->actual_name);
= argv_msg(M_INFO, &argv);
openvpn_execve_= check(&argv, NULL, 0, "Solaris ifconfig inet6 unplumb failed"= );
argv_free(&argv);
@@ -2669,= 23 +2556,19 @@
}

static= void
-solaris_error_cl= ose(struct tuntap *tt, const struct env_set *es,
- const char *actual, bool unp= lumb_inet6 )
+solaris= _error_close(struct tuntap *tt, const struct env_set *es, const char *actua= l,
+ = bool unplumb_inet6)
{
struct argv = argv =3D argv_new();

if (unplumb_ine= t6)
{
- argv_printf( &argv, "%s %s inet6 unplumb",
- IFCONF= IG_PATH, actual );
+ = argv_printf(&argv, "%s %s inet6 unplumb", IFCONFIG_PAT= H, actual);
argv_msg(M_INFO, &argv); openvpn_execve_check(&argv, es, 0, "Solaris ifconf= ig inet6 unplumb failed");
}

- argv_printf(&arg= v,
- &qu= ot;%s %s unplumb",
- IFCONFIG_PATH,
- actual);
+ argv_printf(&argv, "%s %s unplumb", IFCON= FIG_PATH, actual);

argv_msg(M_INFO, = &argv);
openvpn_execve_check(&argv, es, 0, &qu= ot;Solaris ifconfig unplumb failed");
@@ -2771,8 +2654= ,7 @@
/* setup command, close tun dev (clears tt->a= ctual_name!), run command
*/
=
- argv_printf(&argv, &= quot;%s %s destroy",
- IFCONFIG_PATH, tt->actual_name);
+ argv_printf(&argv, "%s %s = destroy", IFCONFIG_PATH, tt->actual_name);
=
close_tun_generic(tt);

@@ = -2822,11 +2704,11 @@
if (strcmp(dev, "tap") = =3D=3D 0)
{
struct ifreq ifr;=
- if ((tt->f= d =3D open( "/dev/tap", O_RDWR)) < 0)
+ if ((tt->fd =3D open("/dev/t= ap", O_RDWR)) < 0)
{
= msg(M_FATAL, "Cannot allocate NetBSD TAP dev dynamically"= );
}
- if (ioctl( tt->fd, TAPGIFNAME, (void *)&ifr ) < 0= )
+ if (ioctl(= tt->fd, TAPGIFNAME, (void *)&ifr) < 0)
{=
msg(M_FATAL, "Cannot query NetBSD TAP de= vice name");
}
@@ -2846,15 +2= 728,15 @@

if (tt->fd >=3D 0)
{
-= int i =3D IFF_POINTOPOINT|IFF_MULTICAST;
- ioctl(tt->fd, TUNSIFMODE, &i); = /* multicast on */
+ = int i =3D IFF_POINTOPOINT | IFF_MULTICAST;
+ ioctl(tt->fd, TUNSIFMODE, &i);= /* multicast on */
i =3D 0;
- ioctl(tt->fd, TUNSLMODE, &i)= ; /* link layer mode off */
+ ioctl(tt->fd, TUNSLMODE, &i); /* link layer mode= off */

if (tt->type =3D=3D D= EV_TYPE_TUN)
{
i =3D = 1;
- if (ioc= tl(tt->fd, TUNSIFHEAD, &i) < 0) /* multi-af mode on */
+ if (ioctl(tt-= >fd, TUNSIFHEAD, &i) < 0) /* multi-af mode on */
= {
msg(M_WARN | M_ERRNO, "= ;ioctl(TUNSIFHEAD)");
}
@= @ -2885,8 +2767,7 @@
/* setup command, close tun dev (= clears tt->actual_name!), run command
*/
- argv_prin= tf(&argv, "%s %s destroy",
- IFCONFIG_PATH, tt->actual_name);
+ argv_printf(&arg= v, "%s %s destroy", IFCONFIG_PATH, tt->actual_name);
close_tun_generic(tt);

@@ -2919,7 +2800,7 @@
struct iovec iv[= 2];
struct openvpn_iphdr *iph;

- iph =3D (struct= openvpn_iphdr *) buf;
- if (tt->persistent_if) /* k= eep pre-existing if around */
+ if (tt->persistent_if) /* keep pre-existing if around */
{
close_tun_generic(tt);
free(tt);
@@ -3040,14 +2921,12 @@
/* setup command, close tun dev (clears tt->actual_name!= ), run command
*/

- argv_printf(&argv, "%s %s = destroy",
- = IFCONFIG_PATH, tt->actual_name);
+ argv_printf(&argv, "%s %s destroy&quo= t;, IFCONFIG_PATH, tt->actual_name);

= close_tun_generic(tt);

argv_msg(= M_INFO, &argv);
- = openvpn_execve_check(&argv, NULL, 0,
- "FreeBSD 'destroy tu= n interface' failed (non-critical)");
+ openvpn_execve_check(&argv, NULL, 0, &qu= ot;FreeBSD 'destroy tun interface' failed (non-critical)");

free(tt);
argv_fr= ee(&argv);
@@ -3062,7 +2941,7 @@
= struct iovec iv[2];
struct ip *iph;
<= span>

- iph =3D= (struct ip *) buf;
+= iph =3D (struct ip *)buf;

= if (iph->ip_v =3D=3D 6)
{
@@ = -3157,7 +3036,7 @@
struct iovec iv[2];
<= span> struct ip *iph;


- iph =3D (struct ip *) buf;
+ iph =3D (struct ip *)buf;<= /span>

if (iph->ip_v =3D=3D 6)
{
@@ -3233,16 +3112,14 @@

if (fd < 0)
{
<= span style=3D"color: hsl(0, 100%, 40%);">- msg(M_INFO | M_ERRNO, &qu= ot;Opening utun%d failed (socket(SYSPROTO_CONTROL))",

- utunnum);
+ msg(M_INFO | M_ERRNO, "= Opening utun%d failed (socket(SYSPROTO_CONTROL))", utunnum); return -2;
}
<= br> if (ioctl(fd, CTLIOCGINFO, &ctlInfo) =3D=3D -1) {
close(fd);
- msg(M_INFO | M_ERRNO, "Opening utu= n%d failed (ioctl(CTLIOCGINFO))",
- utunnum);
+ msg(M_INFO | M_ERRNO, "Opening utun%d faile= d (ioctl(CTLIOCGINFO))", utunnum);
return -2;=
}

@@ -3252,7 +3129,= 7 @@
sc.sc_family =3D AF_SYSTEM;
= sc.ss_sysaddr =3D AF_SYS_CONTROL;

- sc.sc_unit =3D utunnum+1;
+ sc.sc_unit =3D utunnum + 1;


/* If the connect i= s successful, a utun%d device will be created, where "%d"<= br>@@ -3260,8 +3137,7 @@

if (c= onnect(fd, (struct sockaddr *)&sc, sizeof(sc)) < 0)
= {
- msg(M_I= NFO | M_ERRNO, "Opening utun%d failed (connect(AF_SYS_CONTROL))",=
- utunnum);=
+ msg(M_INFO = | M_ERRNO, "Opening utun%d failed (connect(AF_SYS_CONTROL))", utu= nnum);
close(fd);
return = -1;
}
@@ -3283,20 +3159,21 @@
/* dev_node is simply utun, do the normal dy= namic utun
* otherwise try to parse the utun number *= /
- if (dev_node &am= p;& (strcmp("utun", dev_node) !=3D 0 ))
+ if (dev_node && (strcmp("= ;utun", dev_node) !=3D 0))
{
= if (sscanf(dev_node, "utun%d", &utunnum) !=3D 1)<= br> {
- = msg(M_FATAL, "Cannot parse 'dev-node %s' please use = 'dev-node utunX'"
- "to use a utun device number X", dev_nod= e);
+ msg(= M_FATAL,
+ = "Cannot parse 'dev-node %s' please use 'dev-node utun= X'"
+ = "to use a utun device number X",
+ dev_node);
}

}


-
CLE= AR(ctlInfo);
- if (s= trlcpy(ctlInfo.ctl_name, UTUN_CONTROL_NAME, sizeof(ctlInfo.ctl_name)) >= =3D
- sizeof(ctl= Info.ctl_name))
+ = if (strlcpy(ctlInfo.ctl_name, UTUN_CONTROL_NAME, sizeof(ctlInfo.ctl_name))<= /span>
+ >=3D size= of(ctlInfo.ctl_name))
{
msg(M= _ERR, "Opening utun: UTUN_CONTROL_NAME too long");
}

@@ -3316,7 +3193,7 @@
= fd =3D utun_open_helper(ctlInfo, utunnum);
/*= Break if the fd is valid,
* or if early init= ialization failed (-2) */
- if (fd !=3D-1)
+ if (fd !=3D -1)
{
break;
}@@ -3352,13 +3229,11 @@
openvpn_net_ctx_t = *ctx)
{
/* If dev_node does not start= start with utun assume regular tun/tap */
- if ((!dev_node && tt->type=3D=3DDEV_TYP= E_TUN)
- || (dev= _node && !strncmp(dev_node, "utun", 4)))
+ if ((!dev_node && tt->= ;type =3D=3D DEV_TYPE_TUN) || (dev_node && !strncmp(dev_node, "= ;utun", 4)))
{
-
/* Check if user has specific = dev_type tap and forced utun with
* dev-node utun= */
- if (tt->= ;type!=3DDEV_TYPE_TUN)
-
/* Use plain dev-node = tun to select /dev/tun style
* Unset dev_node var= iable prior to passing to open_tun_generic to
* l= et open_tun_generic pick the first available tun device */
=
- if (dev_node= && strcmp(dev_node, "tun")=3D=3D0)
+ if (dev_node && strcmp(de= v_node, "tun") =3D=3D 0)
{
dev_node =3D NULL;

}
@@ -3410,11 +3284,9 @@


if (tt->= ;did_ifconfig_ipv6_setup)
{
- const char *ifconfig_ipv6_local =3D
- print_in6_addr= (tt->local_ipv6, 0, &gc);
+ const char *ifconfig_ipv6_local =3D print_in6_addr(tt-= >local_ipv6, 0, &gc);

- argv_printf(&argv, "%s delete -in= et6 %s",
- = ROUTE_PATH, ifconfig_ipv6_local );
+ argv_printf(&argv, "%s delete -= inet6 %s", ROUTE_PATH, ifconfig_ipv6_local);
= argv_msg(M_INFO, &argv);
openvpn_execve_check(= &argv, NULL, 0, "MacOS X 'remove inet6 route' failed (non-= critical)");
}
@@ -3463,44 +3335,= 46 @@

if (tt->type =3D=3D DEV_TYP= E_TUN)
{
- msg(M_FATAL, "no support for 'tun' devices on = AIX" );
+ = msg(M_FATAL, "no support for 'tun' devices on AIX");
}

- if (strncmp( dev, "tap", 3 ) !=3D 0 || dev_no= de)
+ if (strncmp(= dev, "tap", 3) !=3D 0 || dev_node)
{<= br>- msg(M_FATAL, "&#= 39;--dev %s' and/or '--dev-node' not supported on AIX, use '= ;--dev tap0', 'tap1', etc.", dev );
+ msg(M_FATAL,
+ "'--dev %s' and= /or '--dev-node' not supported on AIX, use '--dev tap0', &#= 39;tap1', etc.",
+ dev);
}

= - if (strcmp( dev, "tap&q= uot; ) =3D=3D 0) /* find first free tap dev */
- { = /* (=3D no /dev/tapN node) */

+ if (strcmp(dev, "tap") =3D=3D 0) /* find= first free tap dev */
= - for (i =3D 0; i<99; i++)
+ for (i =3D 0; i < 99; i++)
= {
snprintf(tunname, sizeof(tunname), &quo= t;/dev/tap%d", i);
- if (access( tunname, F_OK ) < 0 && errno =3D=3D EN= OENT)
+ if= (access(tunname, F_OK) < 0 && errno =3D=3D ENOENT)
{

break;
= }
}
if (i &g= t;=3D 99)
{
- msg( M_FATAL, "cannot find unused tap devic= e" );
+ = msg(M_FATAL, "cannot find unused tap device");
}


- snprintf( dynamic_name, sizeof(dynamic_name), "tap%d&q= uot;, i );
+ s= nprintf(dynamic_name, sizeof(dynamic_name), "tap%d", i); dev =3D dynamic_name;
}
- else = /* name given, sanity check */

+ else /* name given, sanity check */
<= span> {

/* ensure that dev name is "tap+&= lt;digits>" *only* */
p =3D &dev[3];
- while (isdigit(= *p) )
+ while = (isdigit(*p))
{
p++;<= /span>
}
if (*p !=3D '\0'= ;)
{
- msg( M_FATAL, "TAP device name must be '--dev = tapNNNN'" );
+ msg(M_FATAL, "TAP device name must be '--dev tapNNNN= '");
}

= snprintf(tunname, sizeof(tunname), "/dev/%s", dev);
@@ -3508,16 +3382,15 @@

= /* pre-existing device?
*/
- if (access( tunname, F_OK ) < 0 &&= ; errno =3D=3D ENOENT)
-
/* tunnel device must be created with 'ifconfig= tapN create'
*/
str= uct argv argv =3D argv_new();
struct env_set *es = =3D env_set_create(NULL);
argv_printf(&argv, &= quot;%s %s create", IFCONFIG_PATH, dev);
argv= _msg(M_INFO, &argv);
+ env_set_add(es, "= ;ODMDIR=3D/etc/objrepos");
openvpn_execve_che= ck(&argv, es, S_FATAL, "AIX 'create tun interface' failed&= quot;);
env_set_destroy(es);
= argv_free(&argv);
@@ -3555,18 +3428,16 @@ */
if (tt->persistent_if)
{

- arg= v_printf(&argv, "%s %s 0.0.0.0 down",
- IFCONFIG_PATH, tt->a= ctual_name);
+ = argv_printf(&argv, "%s %s 0.0.0.0 down", IFCONFIG_PATH, tt-&= gt;actual_name);
}
else {
- = argv_printf(&argv, "%s %s destroy",
- IFCONFIG_PATH, tt->actua= l_name);
+ arg= v_printf(&argv, "%s %s destroy", IFCONFIG_PATH, tt->actual= _name);
}

close= _tun_generic(tt);
argv_msg(M_INFO, &argv);<= br>- env_set_add( es, "OD= MDIR=3D/etc/objrepos" );
+ env_set_add(es, "ODMDIR=3D/etc/objrepos"); openvpn_execve_check(&argv, es, 0, "AIX 'destroy = tap interface' failed (non-critical)");
free(tt);
@@ -3606,13 +3477,8 @@
/* the overlapped read will signal this event on I/O completion= */

ASSERT(ResetEvent(tt->reads.overlapped.hEve= nt));

- status =3D ReadFile(
- tt->hand,
- BPTR(&tt->reads.buf),
- len,
- &tt->reads.size,
- &tt->reads.over= lapped

- );<= /span>
+ status =3D
+ ReadFile(= tt->hand, BPTR(&tt->reads.buf), len, &tt->reads.size, &= ;tt->reads.overlapped);

if (s= tatus) /* operation completed immediately? */
{
@@ -3622,9 +3488,8 @@
tt->rea= ds.iostate =3D IOSTATE_IMMEDIATE_RETURN;
tt-&g= t;reads.status =3D 0;

- dmsg(D_WIN32_IO, "WIN32 I/O: TAP Read im= mediate return [%d,%d]",
- (int) len,
- (int) tt->reads.size);
+ dmsg(D_WIN32_IO, "WIN= 32 I/O: TAP Read immediate return [%d,%d]", (int)len,
+ (int)tt->reads.s= ize);
}
else
{

@@ -3633,8 +3498,7 @@
= {
tt->reads.iostate =3D IOSTATE_= QUEUED;
tt->reads.status =3D err;
- dmsg(D_WIN3= 2_IO, "WIN32 I/O: TAP Read queued [%d]",
- (int) len);
+ dmsg(D_WIN32_IO, = "WIN32 I/O: TAP Read queued [%d]", (int)len);

= }
else /* error occurred */ {
@@ -3642,8 +3506,7 @@
ASSERT(SetEvent(tt->reads.overlapped.hEvent));
=
tt->reads.iostate =3D IOSTATE_IMMEDIATE_RETUR= N;
tt->reads.status =3D err;
= - dmsg(D_WIN32_IO,= "WIN32 I/O: TAP Read error [%d] : %s",
- (int) len,
+ dmsg(D_WIN32_IO, &q= uot;WIN32 I/O: TAP Read error [%d] : %s", (int)len,

= strerror_win32(status, &gc));
= gc_free(&gc);
}
@@ -3668,13 +3531,8 @@

/* the overlapped write w= ill signal this event on I/O completion */
ASSERT(= ResetEvent(tt->writes.overlapped.hEvent));

<= span style=3D"color: hsl(0, 100%, 40%);">- status =3D WriteFile(
- tt->hand,<= /span>
- BPTR(&= tt->writes.buf),
- = BLEN(&tt->writes.buf),
- &tt->writes.size,
- &tt->writes.overlapped<= /span>
- );<= br>+ status =3D WriteFil= e(tt->hand, BPTR(&tt->writes.buf), BLEN(&tt->writes.buf), = &tt->writes.size,
+ &tt->writes.overlapped);
<= span>

if (status) /* operation completed immediat= ely? */
{
@@ -3685,9 +3543,8 @@

tt->writes.status =3D 0;

- = dmsg(D_WIN32_IO, "WIN32 I/O: TAP Write immediate return [%d,%d]&= quot;,
- = BLEN(&tt->writes.buf),
- (int) tt->writes.size);
+ dmsg(D_WIN32_IO, "WIN32 = I/O: TAP Write immediate return [%d,%d]", BLEN(&tt->writes.buf)= ,
+ (= int)tt->writes.size);
}
= else
{
@@ -3696,8 +3553,7 @@
{
tt->writes.= iostate =3D IOSTATE_QUEUED;
tt->writes.= status =3D err;
- = dmsg(D_WIN32_IO, "WIN32 I/O: TAP Write queued [%d]",
- BLE= N(&tt->writes.buf));
+ dmsg(D_WIN32_IO, "WIN32 I/O: TAP Write queued = [%d]", BLEN(&tt->writes.buf));
}
else /* error occurred */
= {
@@ -3705,8 +3561,7 @@
= ASSERT(SetEvent(tt->writes.overlapped.hEvent));
= tt->writes.iostate =3D IOSTATE_IMMEDIATE_RETURN; tt->writes.status =3D err;
- dmsg(D_WIN32_IO, "WIN= 32 I/O: TAP Write error [%d] : %s",
- BLEN(&tt->writes.buf),
+ dmsg(D_WI= N32_IO, "WIN32 I/O: TAP Write error [%d] : %s", BLEN(&tt->= writes.buf),
strerror_win32(err, &= ;gc));
gc_free(&gc);
= }
@@ -3749,11 +3604,13 @@
= struct device_instance_id_interface *first =3D NULL;
s= truct device_instance_id_interface *last =3D NULL;
=
- dev_info_set =3D SetupDi= GetClassDevsEx(&GUID_DEVCLASS_NET, NULL, NULL, DIGCF_PRESENT, NULL, NUL= L, NULL);
+ dev_in= fo_set =3D
+ S= etupDiGetClassDevsEx(&GUID_DEVCLASS_NET, NULL, NULL, DIGCF_PRESENT, NUL= L, NULL, NULL);
if (dev_info_set =3D=3D INVALID_HANDLE= _VALUE)
{
err =3D GetLastErro= r();
- msg(M_FAT= AL, "Error [%u] opening device information set key: %s", (unsigne= d int)err, strerror_win32(err, gc));
+ msg(M_FATAL, "Error [%u] opening device infor= mation set key: %s", (unsigned int)err,
+ strerror_win32(err, gc));
}


msg(D_TAP_WIN_DEBUG, &quo= t;Enumerate device interface lists:");
@@ -3786,7 +364= 3,8 @@
}
}
=
- dev_ke= y =3D SetupDiOpenDevRegKey(dev_info_set, &device_info_data, DICS_FLAG_G= LOBAL, 0, DIREG_DRV, KEY_QUERY_VALUE);
+ dev_key =3D SetupDiOpenDevRegKey(dev_info_set, &= amp;device_info_data, DICS_FLAG_GLOBAL, 0,
+ DIREG_DRV, KE= Y_QUERY_VALUE);
if (dev_key =3D=3D INVALID_HANDLE_= VALUE)
{
continue;
@@ -3794,27 +3652,23 @@

= len =3D sizeof(net_cfg_instance_id);
data_ty= pe =3D REG_SZ;
- = status =3D RegQueryValueEx(dev_key,
- net_cfg_instance_id_string,=
- = NULL,
- = &data_type,
- net_cfg_instance_id= ,
- = &len);
+ status =3D RegQueryValueEx(dev_key, net_cfg_instance_id_string,= NULL, &data_type,
- res =3D SetupDiGe= tDeviceInstanceId(dev_info_set, &device_info_data, device_instance_id, = len, &len);
+ = res =3D SetupDiGetDeviceInstanceId(dev_info_set, &device_info_data,= device_instance_id, len,
+ &len);
= if (!res)
{
g= oto next;
}

= cr =3D CM_Get_Device_Interface_List_Size(&dev_interface_list_size,=
- = (LPGUID)&GUID_DEVINTERFACE_NET,
- = device_instance_id,

+ (LPGUID)&GUI= D_DEVINTERFACE_NET, device_instance_id,
= CM_GET_DEVICE_INTERFACE_LIST_PRESENT);<= br>
if (cr !=3D CR_SUCCESS)
@@ -3824,8 +3678,7 @@


char *dev= _interface_list =3D gc_malloc(dev_interface_list_size, false, gc); cr =3D CM_Get_Device_Interface_List((LPGUID)&GUID_DEVI= NTERFACE_NET, device_instance_id,
- dev_interface_list,
- = dev_interface_list_size,
+ dev_inter= face_list, dev_interface_list_size,
= CM_GET_DEVICE_INTERFACE_LIST_PRESENT);
= if (cr !=3D CR_SUCCESS)
{
@@ -3839,12 +3692,12 @@

{
= struct device_instance_id_interface *dev_iif;
= ALLOC_OBJ_CLEAR_GC(dev_iif, struct device_instance_id_interface, gc);=
- dev_iif-&= gt;net_cfg_instance_id =3D (unsigned char *)string_alloc((char *)net_cfg_in= stance_id, gc);
+ = dev_iif->net_cfg_instance_id =3D
+ (unsigned char *)string_alloc((char= *)net_cfg_instance_id, gc);
dev_iif->devic= e_interface =3D string_alloc(dev_if, gc);

msg(D_TAP_WIN_DEBUG, "NetCfgInstanceId: %s, Device Inter= face: %s",

- = dev_iif->net_cfg_instance_id,
- dev_iif->device_interface);<= br>+ dev_iif->= ;net_cfg_instance_id, dev_iif->device_interface);

/* link into return list */
= if (!first)
@@ -3879,12 +3732,7 @@
= struct tap_reg *last =3D NULL;
int i =3D 0;=

- status= =3D RegOpenKeyEx(
- = HKEY_LOCAL_MACHINE,
- 0,
- K= EY_READ,
- &= adapter_key);
+ st= atus =3D RegOpenKeyEx(HKEY_LOCAL_MACHINE, ADAPTER_KEY, 0, KEY_READ, &ad= apter_key);

if (status !=3D ERROR_SU= CCESS)
{
@@ -3904,34 +3752,19 @@
DWORD data_type;

= len =3D sizeof(enum_name);
- status =3D RegEnumKeyEx(
- adapter_key,
- i,
- enum_name,
- &len,
- NULL,
- NULL,
- NULL,
- NULL);
+ status =3D RegEnumKeyEx(adapter_key, i, enum_name, &len, N= ULL, NULL, NULL, NULL);
if (status =3D=3D ERROR_NO= _MORE_ITEMS)
{
break;=
}
else if (status !=3D E= RROR_SUCCESS)
{
- msg(M_FATAL, "Error enumerating registr= y subkeys of key: %s",
- ADAPTER_KEY);
+ msg(M_FATAL, "Error enumerating registry s= ubkeys of key: %s", ADAPTER_KEY);
}
- snpri= ntf(unit_string, sizeof(unit_string), "%s\\%s",
- ADAPTER_KEY, enum_name= );
+ snprintf(= unit_string, sizeof(unit_string), "%s\\%s", ADAPTER_KEY, enum_nam= e);

-= status =3D RegOpenKeyEx(
- HKEY_LOCAL_MACHINE,
- unit_string,
- 0,
- KEY_READ,
- &unit_key);
+ status =3D RegOpenKeyEx(HKEY_LOCAL_MACHINE= , unit_string, 0, KEY_READ, &unit_key);

if (status !=3D ERROR_SUCCESS)

{
@@ -3940,29 +3773,19 @@
else
= {
len =3D sizeof(component_id);=
- status = =3D RegQueryValueEx(
- = unit_key,
- NULL,
- &data_type,
- (LPBYTE)component_id,- &len);
+ status =3D R= egQueryValueEx(unit_key, component_id_string, NULL, &data_type,<= br>+ = (LPBYTE)component_id, &len);

if (status !=3D ERROR_SUCCESS || data_type !=3D REG_SZ)
{
- dmsg(D_REGISTRY, "Error opening registry key: %s\= \%s",
- = unit_string, component_id_string);
+ dmsg(D_REGISTRY, "Error openi= ng registry key: %s\\%s", unit_string,
+ component_id_string); }
else
= {
len =3D sizeof(net_cfg_instan= ce_id);
- = status =3D RegQueryValueEx(
- unit_key,
- net_cfg_instance_id_string,
<= span style=3D"color: hsl(0, 100%, 40%);">- NULL,
<= br>- &data= _type,
- = net_cfg_instance_id,
- &len);
+ status =3D RegQueryValueEx(unit_key, net_cfg= _instance_id_string, NULL, &data_type,
+ net_cfg_ins= tance_id, &len);

if = (status =3D=3D ERROR_SUCCESS && data_type =3D=3D REG_SZ)
= {
@@ -3996,8 +3819,8 @@
}

las= t =3D reg;

- msg(D_TAP_WIN_DEBUG, "NetCfgInstanceId:= %s, Driver: %s",
= - reg->guid, print_tun_backend_driver(reg->= ;windows_driver));
+ = msg(D_TAP_WIN_DEBUG, "NetCfgInstanceId: %s, Dri= ver: %s", reg->guid,
+ print_tun_backend_driver(reg->windo= ws_driver));
}
= }
}
@@ -4020,12 +384= 3,8 @@
struct panel_reg *last =3D NULL;
int i =3D 0;


- status =3D RegOpenKeyEx(
- HKEY_LOCAL_MACHINE,
- NETWORK_CONNECTIONS_KEY,
- 0,

- KEY_READ,
- &network_connections_key);
<= span style=3D"color: hsl(120, 100%, 40%);">+ status =3D RegOpenKeyEx(HKE= Y_LOCAL_MACHINE, NETWORK_CONNECTIONS_KEY, 0, KEY_READ,

+ &network_c= onnections_key);

if (status !=3D ERR= OR_SUCCESS)
{
@@ -4042,35 +3861,20 @@<= /span>
const WCHAR name_string[] =3D L"Name";

len =3D sizeof(enum_name);=
- status =3D RegEnumKe= yEx(
- netwo= rk_connections_key,
- = i,
- = enum_name,
- = &len,
- = NULL,
- = NULL,
- NULL= ,
- NULL);
+ status =3D Re= gEnumKeyEx(network_connections_key, i, enum_name, &len, NULL, NULL, NUL= L, NULL);
if (status =3D=3D ERROR_NO_MORE_ITEMS)
{
break;
}

else if (status !=3D ERROR_SUCCESS)<= /span>
{
- msg(M_FATAL, "Error enumerating registry subkeys of k= ey: %s",
- = NETWORK_CONNECTIONS_KEY);
+ msg(M_FATAL, "Error enumerating registry sub= keys of key: %s", NETWORK_CONNECTIONS_KEY);
}=

- = snprintf(connection_string, sizeof(connection_string),
- "%s\\%s\\Connec= tion",

+ = snprintf(connection_string, sizeof(connection_string), "%s\\%s\\Connec= tion",
NETWORK_CONNECTIONS_KEY, enum= _name);

- status =3D RegOpenKeyEx(
- HKEY_LOCAL_MACHINE,
- connection_string,
- 0,
- KEY_READ,
- &connection_key);
+ status =3D RegOpenKeyEx(HK= EY_LOCAL_MACHINE, connection_string, 0, KEY_READ, &connection_key);

if (status !=3D ERROR_SUCCESS)

{
@@ -4079,18 +3883,13 @@
else

{
l= en =3D sizeof(name_data);
- status =3D RegQueryValueExW(
- connection_key,
- name_string,
- NULL,

- &name_type,
- (LPBYTE) = name_data,
- = &len);
+ = status =3D RegQueryValueExW(connection_key, name_string, NULL, &= ;name_type,
+ = (LPBYTE)name_data, &len);

if (status !=3D ERROR_SUCCESS || name_type = !=3D REG_SZ)
{
- dmsg(D_REGISTRY, "Error opening = registry key: %s\\%s\\%ls",
- NETWORK_CONNECTIONS_KEY, connection_string,= name_string);
+ = dmsg(D_REGISTRY, "Error opening registry key: %s\\%s\\%ls&q= uot;, NETWORK_CONNECTIONS_KEY,
+ connection_string, name_string);
= }
else
= {
@@ -4143,15 +3942,14 @@
}
if ((local & (~mask)) !=3D (remote & (~mask)))<= /span>
{
= - err =3D "must exist within the same 255.255.255.252 subnet. = This is a limitation of --dev tun when used with the TAP-WIN32 driver"= ;
+ err =3D
+ "must= exist within the same 255.255.255.252 subnet. This is a limitation of --d= ev tun when used with the TAP-WIN32 driver";
= goto error;
}
- if ((local & mask) =3D=3D 0
- || (local & mask) =3D=3D 3- || (remote & mask) = =3D=3D 0
- || (r= emote & mask) =3D=3D 3)
+ if ((local & mask) =3D=3D 0 || (local & mask) =3D=3D 3 = || (remote & mask) =3D=3D 0 || (remote & mask) =3D=3D 3)
= {
- e= rr =3D "cannot use the first or last address within a given 255.255.25= 5.252 subnet. This is a limitation of --dev tun when used with the TAP-WIN= 32 driver";
+ = err =3D
+ = "cannot use the first or last address within a given 255.255.255.= 252 subnet. This is a limitation of --dev tun when used with the TAP-WIN32= driver";
goto error;
}<= /span>

@@ -4159,10 +3957,10 @@
= return;

error:
- msg(M_FATAL, "There is a problem i= n your selection of --ifconfig endpoints [local=3D%s, remote=3D%s]. The lo= cal and remote VPN endpoints %s. Try '" PACKAGE " --show-val= id-subnets' option for more info.",
- print_in_addr_t(local, 0, &gc),- print_in_addr_t(remote= , 0, &gc),
- = err);
+ msg(M_FAT= AL,
+ "Th= ere is a problem in your selection of --ifconfig endpoints [local=3D%s, rem= ote=3D%s]. The local and remote VPN endpoints %s. Try '" PACKAGE=
+ " --sh= ow-valid-subnets' option for more info.",
+ print_in_addr_t(local, 0, &gc), = print_in_addr_t(remote, 0, &gc), err);
gc_free(&am= p;gc);
}

@@ -4186,7 +398= 4,7 @@

for (i =3D 0; i < 256; i += =3D 4)
{
- printf("[%3d,%3d] ", i+1, i+2);
+ printf("[%3d,%3d] "= , i + 1, i + 2);
if (++col > 4)
{

col =3D 0;
@@ -422= 9,7 +4027,8 @@
{
if (= !strcmp(tr->guid, pr->guid))
{- msg(msglev, &qu= ot;'%s' %s %s", pr->name, tr->guid, print_tun_backend_dr= iver(tr->windows_driver));
+ msg(msglev, "'%s' %s %s", pr-&g= t;name, tr->guid,
= + print_tun_backend_driver(tr->windows_driver));
++links;
}=
}
@@ -4267,12 +4066,14 @@

if (warn_panel_dup)
{<= br>- msg(warnlev, "WA= RNING: Some TAP-Windows adapters have duplicate links from the Network Conn= ections control panel");
+ msg(warnlev,
+ "WARNING: Some TAP-Windows adapters have duplic= ate links from the Network Connections control panel");
}


if (warn_panel_null)=
{
- = msg(warnlev, "WARNING: Some TAP-Windows adapters have no link from = the Network Connections control panel");
+ msg(warnlev,
+ "WARNING: Some TAP-Windows adap= ters have no link from the Network Connections control panel");=
}

gc_free(&gc);
@@ -4314,7 +4115,8 @@
}

static const struct tap_reg *
-get_adapter_by_name(const char *name, const struct = tap_reg *tap_reg, const struct panel_reg *panel_reg)
+get_adapter_by_name(const char *name, con= st struct tap_reg *tap_reg,
+ const struct panel_reg *panel_reg)
{

const struct panel_reg *pr;

@@ -4335,8 +4137,8 @@
if (!tap_reg)
{
msg(M_FATAL, "There are n= o TAP-Windows or ovpn-dco adapters "
- "on this system. You should be able t= o create an adapter "
- "by using tapctl.exe utility.");
+ "on this = system. You should be able to create an adapter "

+ "by using tap= ctl.exe utility.");
}
}
@@ -4345,13 +4147,10 @@
* regis= try for the TAP device # =3D device_number.
*/
= static const char *
-get_unspecified_device_guid(const int device_number,
- uint8_t *ac= tual_name,
- = int actual_name_size,
+get_unspecified_device_guid(const int device_number, uin= t8_t *actual_name, int actual_name_size,
= const struct tap_reg *tap_reg_src,
= const struct panel_reg *panel_reg_src,
- enum tun_drive= r_type *windows_driver,
- struct gc_arena *gc)
+ enum tun_driver_= type *windows_driver, struct gc_arena *gc)
{
const struct tap_reg *tap_reg =3D tap_reg_src;

= struct buffer actual =3D clear_buf();
@@ -4411,13 +4210,9 = @@
* returning the GUID and optional actual_name and devi= ce type
*/
static const char *-get_device_guid(const char *nam= e,
- uin= t8_t *actual_name,
- = int actual_name_size,
- enum tun_driver_type *windows_driver,- const struct t= ap_reg *tap_reg,
- = const struct panel_reg *panel_reg,
- struct gc_arena *gc)
+get_device_guid(const char *name, = uint8_t *actual_name, int actual_name_size,

+ enum tun_driver_type *windows_drive= r, const struct tap_reg *tap_reg,
+ const struct panel_reg *panel_reg, struct gc_= arena *gc)
{
struct buffer ret =3D al= loc_buf_gc(256, gc);
struct buffer actual =3D clear_bu= f();
@@ -4487,17 +4282,15 @@

if ((status =3D GetAdaptersInfo(NULL, &size)) !=3D ERROR_BUFFE= R_OVERFLOW)

{
- msg(M_INFO, "GetAdaptersInfo #1 failed (status=3D= %u) : %s",
- = (unsigned int)status,
+ msg(M_INFO, "GetAdaptersInfo #1 failed (status=3D%u) := %s", (unsigned int)status,
strerror_win3= 2(status, gc));
}
else
= {
- p= i =3D (PIP_ADAPTER_INFO) gc_malloc(size, false, gc);
+ pi =3D (PIP_ADAPTER_INFO)gc_mallo= c(size, false, gc);
if ((status =3D GetAdaptersInf= o(pi, &size)) !=3D NO_ERROR)
{
- msg(M_INFO, "GetAdap= tersInfo #2 failed (status=3D%u) : %s",

- (unsigned int)status,
+ msg(M_INFO, "GetA= daptersInfo #2 failed (status=3D%u) : %s", (unsigned int)status,
strerror_win32(status, gc));
= pi =3D NULL;
}
@@ -4516= ,21 +4309,19 @@
{
if ((status= =3D GetPerAdapterInfo(index, NULL, &size)) !=3D ERROR_BUFFER_OVERFLOW)=
{
- msg(M_INFO, "GetPerAdapterInfo #1 failed (status=3D%= u) : %s",
- = (unsigned int)status,
+ msg(M_INFO, "GetPerAdapterInfo #1 failed (statu= s=3D%u) : %s", (unsigned int)status,
= strerror_win32(status, gc));
}
= else
{
- pi =3D (PIP_PER_ADAPTER_INFO) gc_malloc(size, f= alse, gc);
+ = pi =3D (PIP_PER_ADAPTER_INFO)gc_malloc(size, false, gc);
if ((status =3D GetPerAdapterInfo((ULONG)index, pi, &size= )) =3D=3D ERROR_SUCCESS)

{
= return pi;
}
= else
{
- msg(M_INFO, "GetPerAdapterInfo= #2 failed (status=3D%u) : %s",
- (unsigned int)status,
+ msg(M_INFO, "GetP= erAdapterInfo #2 failed (status=3D%u) : %s", (unsigned int)status,
strerror_win32(status, gc));
}

}
@@ -4547,21 += 4338,19 @@

if ((status =3D GetInterf= aceInfo(NULL, &size)) !=3D ERROR_INSUFFICIENT_BUFFER)
= {
- msg(M_IN= FO, "GetInterfaceInfo #1 failed (status=3D%u) : %s",
- (unsigned int)status,<= /span>
+ msg(M_INFO, = "GetInterfaceInfo #1 failed (status=3D%u) : %s", (unsigned int)st= atus,
strerror_win32(status, gc));
<= span> }

else
{
- ii =3D (PIP_INTERFACE_INFO) = gc_malloc(size, false, gc);

+ ii =3D (PIP_INTERFACE_INFO)gc_malloc(size, false, gc);
if ((status =3D GetInterfaceInfo(ii, &size)) =3D= =3D NO_ERROR)
{
retur= n ii;
}
else
{

- = msg(M_INFO, "GetInterfaceInfo #2 failed (status=3D%u) : %s",=
- (unsi= gned int)status,
+ = msg(M_INFO, "GetInterfaceInfo #2 failed (status=3D%u) : %s&qu= ot;, (unsigned int)status,
strerror_win32(= status, gc));
}
}
<= span>@@ -4749,7 +4538,6 @@

else
{=
ret =3D true; /* this can occur when TAP adapter = is bridged */
-<= br> }
return ret;
}<= br>@@ -4773,7 +4561,8 @@
in_addr_t adapt= er_ip, adapter_netmask;
if (get_adapter_ip_net= mask(ai, i, &adapter_ip, &adapter_netmask))
= {
- = if (adapter_ip && adapter_netmask && (ip & adapter_ne= tmask) =3D=3D (adapter_ip & adapter_netmask))
+ if (adapter_ip && ada= pter_netmask
+ = && (ip & adapter_netmask) =3D=3D (adapter_ip &= adapter_netmask))
{
= if (highest_netmask && adapter_netmask > *highes= t_netmask)
{
@@ -4788,= 10 +4577,7 @@
}

DWORD
-adapter_index_of_ip(con= st IP_ADAPTER_INFO *list,
- const in_addr_t ip,
- int *count,
- in_addr_t *netmask)
+adapter_index_of_ip(con= st IP_ADAPTER_INFO *list, const in_addr_t ip, int *count, in_addr_t *netmas= k)
{
struct gc_arena gc =3D gc_new();=
DWORD ret =3D TUN_ADAPTER_INDEX_INVALID;
@@ -4842,11 +4628,8 @@

}
<= br> dmsg(D_ROUTE_DEBUG, "DEBUG: IP Locate: ip=3D%s nm=3D%s i= ndex=3D%d count=3D%d metric=3D%d",
- print_in_addr_t(ip, 0, &gc),
- print_in_addr_t(highest_netm= ask, 0, &gc),

- = (int)ret,
- = count ? *count : -1,
= - lowest_metric);
+ print_in_addr_t(ip, 0, &gc), print_in_addr_t(highest_net= mask, 0, &gc), (int)ret,
+ count ? *count : -1, lowest_metric);

if (ret =3D=3D TUN_ADAPTER_INDEX_INVALID && coun= t)
{
@@ -4867,9 +4650,9 @@
<= span> * is DHCP disabled.

*/
-#define DHCP_STATUS_UNDEF 0=
-#define DHCP_STATUS_E= NABLED 1
-#define DHC= P_STATUS_DISABLED 2
= +#define DHCP_STATUS_UNDEF 0
+#define DHCP_STATUS_ENABLED 1
+#define DHCP_STATUS_DISABLED 2

static int
dhcp_status(DWORD index)@@ -4914,22 +4697,19 @@
DWORD status;<= /span>
const DWORD context =3D ip->Context;=

- = if ((status =3D DeleteIPAddress((ULONG) context)) =3D=3D NO_ERROR)=
+ if ((status = =3D DeleteIPAddress((ULONG)context)) =3D=3D NO_ERROR)
= {
msg(M_INFO, "Successfully d= eleted previously set dynamic IP/netmask: %s/%s",
- ip->IpAddress.Strin= g,
- = ip->IpMask.String);
+ ip->IpAddress.String, ip->IpMask.String);
}
else
{

const char *empty =3D &q= uot;0.0.0.0";
- = if (strcmp(ip->IpAddress.String, empty)
- || strcmp(ip->IpMa= sk.String, empty))
+ = if (strcmp(ip->IpAddress.String, empty) || strcmp(ip->= IpMask.String, empty))
{
- msg(M_INFO, "N= OTE: could not delete previously set dynamic IP/netmask: %s/%s (status=3D%u= )",
- = ip->IpAddress.String,
- ip->IpMask.String,
- (unsigned int= )status);

+ = msg(M_INFO,
+ "NOTE: could not delete previously set dynam= ic IP/netmask: %s/%s (status=3D%u)",
+ ip->IpAddress.String, ip-&= gt;IpMask.String, (unsigned int)status);
}=
}
ip =3D ip->= Next;
@@ -5099,7 +4879,7 @@
} else
{
- msg(M_INFO|M_NOPREFIX, "TAP-Windows device:= %s [Non-admin access allowed]", device_path);
+ msg(M_INFO | M_NOPREFIX, "TA= P-Windows device: %s [Non-admin access allowed]", device_path);=
}
}

@@ -5= 119,7 +4899,8 @@
if (dev_node)
{<= /span>
/* Get the device GUID for the device specified wi= th --dev-node. */
- = device_guid =3D get_device_guid(dev_node, actual_buffer, sizeof(actual_= buffer), NULL, tap_reg, panel_reg, &gc);
+ device_guid =3D get_device_guid(dev_node, = actual_buffer, sizeof(actual_buffer), NULL, tap_reg,
+ pan= el_reg, &gc);

if (!device_gu= id)
{
@@ -5127,20 +4908,11 @@
}

/* Open W= indows TAP-Windows adapter */
- snprintf(device_path, sizeof(device_path), "%s%s%s&quo= t;,
- U= SERMODEDEVICEDIR,
- = device_guid,
+ snprintf(device_path, sizeof(device_path), "%s%s%s"= , USERMODEDEVICEDIR, device_guid,
TAP_WIN= _SUFFIX);

- hand =3D CreateFile(
- device_path,
- MAXIMUM_ALLOWED,
- 0, /* was: FILE_SHARE_READ = */
- 0,
- OPEN_EXISTING,=
- FILE_ATTR= IBUTE_SYSTEM | FILE_FLAG_OVERLAPPED,
- 0
- );
+ hand =3D CreateFile(device_path, MAXIMUM_ALLOWED, 0, /* was: FILE= _SHARE_READ */
+ = 0, OPEN_EXISTING, FILE_ATTRIBUTE_SYSTEM | FILE_FLAG_OV= ERLAPPED, 0);

if (hand =3D=3D IN= VALID_HANDLE_VALUE)
{
@@ -5157,13 = +4929,8 @@
/* Try opening all TAP devices */
while (true)
{
- device_guid =3D get_unspe= cified_device_guid(device_number,

- actual_bu= ffer,
- = sizeof(actual_buffer),
- = tap_reg,

- panel_reg,
- = NULL,
- &gc);<= /span>
+ device_g= uid =3D get_unspecified_device_guid(
+ device_number, actual_buffer, sizeof(actua= l_buffer), tap_reg, panel_reg, NULL, &gc);

= if (!device_guid)
{<= br>@@ -5171,20 +4938,11 @@
}
<= span>

/* Open Windows TAP-Windows adapter */<= /span>
- snprintf(d= evice_path, sizeof(device_path), "%s%s%s",
- USERMODEDEVICEDIR,
- devi= ce_guid,
+ = snprintf(device_path, sizeof(device_path), "%s%s%s", USERMODEDEV= ICEDIR, device_guid,
TAP_WIN_SUFFIX);=

- = hand =3D CreateFile(
- device_path,
- MAXIMUM_ALLOWED,
- 0, /* was: FILE_SHAR= E_READ */
- = 0,
- = OPEN_EXISTING,
- = FILE_ATTRIBUTE_SYSTEM | FILE_FLAG_OVERLAPPED,
- 0
- );
+ hand =3D CreateFile(device_path,= MAXIMUM_ALLOWED, 0, /* was: FILE_SHARE_READ */
+ 0, OPEN_EXISTING,= FILE_ATTRIBUTE_SYSTEM | FILE_FLAG_OVERLAPPED, 0);
=
if (hand =3D=3D INVALID_HANDLE_VALUE)
{

@@ -5222,9 +4980,9 @@
= }
else
{
<= span style=3D"color: hsl(0, 100%, 40%);">- msg(M_WARN, "NOT= E: Release of DHCP-assigned IP address lease on TAP-Windows adapter failed:= %s (code=3D%u)",

= - strerror_win32(status, &gc),
- (unsigned int)status);+ msg(M_WARN,
+ "NO= TE: Release of DHCP-assigned IP address lease on TAP-Windows adapter failed= : %s (code=3D%u)",
+ strerror_win32(status, &gc), (unsigned int)status);=
}
}
=
@@ -5235,7 +4993,8 @@
static bool
dhcp_release(const struct tuntap *tt)

{
- if (tt && tt->options.= ip_win32_type =3D=3D IPW32_SET_DHCP_MASQ && tt->adapter_index != =3D TUN_ADAPTER_INDEX_INVALID)

+ if (tt && tt->options.ip_win32_type =3D=3D IPW32_= SET_DHCP_MASQ
+ = && tt->adapter_index !=3D TUN_ADAPTER_INDEX_INVALID) {
return dhcp_release_by_adapter_index= (tt->adapter_index);
}
@@ -5262,9 += 5021,9 @@
}
else {
- = msg(M_WARN, "WARNING: Failed to renew DHCP IP address lease o= n TAP-Windows adapter: %s (code=3D%u)",
- strerror_win32(status, &gc),
- (unsigned= int)status);
+ = msg(M_WARN,
+ = "WARNING: Failed to renew DHCP IP address lease on TAP-W= indows adapter: %s (code=3D%u)",
+ strerror_win32(status, &gc), (unsigne= d int)status);
}
}
= gc_free(&gc);
@@ -5274,7 +5033,8 @@ static bool
dhcp_renew(const struct tuntap *tt)
{
- = if (tt && tt->options.ip_win32_type =3D=3D IPW32_SET_DHCP_MASQ &= amp;& tt->adapter_index !=3D TUN_ADAPTER_INDEX_INVALID)
+ if (tt && tt->opt= ions.ip_win32_type =3D=3D IPW32_SET_DHCP_MASQ

+ && tt->adapter_index !=3D TUN_= ADAPTER_INDEX_INVALID)
{
retu= rn dhcp_renew_by_adapter_index(tt->adapter_index);
= }
@@ -5320,15 +5080,11 @@
msg(D_TUNTAP= _INFO, "Start ipconfig commands for register-dns...");
= netcmd_semaphore_lock();

- argv_printf(&argv, "%s%s /flus= hdns",
- = get_win_sys_path(),
- WIN_IPCONFIG_PATH_SUFFIX);
+ argv_printf(&argv, "%s%s /flushdns&= quot;, get_win_sys_path(), WIN_IPCONFIG_PATH_SUFFIX);
= argv_msg(D_TUNTAP_INFO, &argv);
openvpn_execve_che= ck(&argv, es, 0, err);

- argv_printf(&argv, "%s%s /registerdns&q= uot;,
- = get_win_sys_path(),
- = WIN_IPCONFIG_PATH_SUFFIX);
+ argv_printf(&argv, "%s%s /registerdns&quo= t;, get_win_sys_path(), WIN_IPCONFIG_PATH_SUFFIX);
arg= v_msg(D_TUNTAP_INFO, &argv);
openvpn_execve_check(= &argv, es, 0, err);
argv_free(&argv);@@ -5429,34 +5185,28 @@
* are cleared first.
*/
static void
-netsh_set_dns6_servers(const struct in6_addr *addr_= list,
- = const int addr_len,
- DWORD adapter_index)
+netsh_set_dns6_servers(const struct in6_addr *= addr_list, const int addr_len, DWORD adapter_index)
{
struct gc_arena gc =3D gc_new();
stru= ct argv argv =3D argv_new();

/* dele= te existing DNS settings from TAP interface */
- argv_printf(&argv, "%s%s interface ip= v6 delete dns %lu all",
- get_win_sys_path(),
- NETSH_PATH_SUFFIX,
- adapter_index);+ argv_printf(&argv, &q= uot;%s%s interface ipv6 delete dns %lu all", get_win_sys_path(),
+ NETSH_PAT= H_SUFFIX, adapter_index);
netsh_command(&argv, 2, = M_FATAL);

for (int i =3D 0; i < a= ddr_len; ++i)
{
- const char *fmt =3D (i =3D=3D 0) ?
- "%s%s in= terface ipv6 set dns %lu static %s"
- : "%s%s interface ipv6 ad= d dns %lu %s";
- = argv_printf(&argv, fmt, get_win_sys_path(),
- NETSH_PATH_SUFFIX, adap= ter_index,
+ c= onst char *fmt =3D (i =3D=3D 0) ? "%s%s interface ipv6 set dns %lu sta= tic %s"
+ = : "%s%s interface ipv6 add dns %lu %s"= ;;
+ argv_prin= tf(&argv, fmt, get_win_sys_path(), NETSH_PATH_SUFFIX, adapter_index,
print_in6_addr(addr_list[i], 0, &gc)= );

/* disable slow address valid= ation */
argv_printf_cat(&argv, "%s"= , "validate=3Dno");

/*= Treat errors while adding as non-fatal as we do not check for duplicates *= /
- netsh_comman= d(&argv, 1, (i=3D=3D0) ? M_FATAL : M_NONFATAL);
+ netsh_command(&argv, 1, (i = =3D=3D 0) ? M_FATAL : M_NONFATAL);
}
=
argv_free(&argv);
@@ -5464,12 +52= 14,8 @@
}

static void
-netsh_ifconfig_options(= const char *type,
- = const in_addr_t *addr_list,
- const int addr_len,<= br>- const = IP_ADDR_STRING *current,
- const bool test_first)
+netsh_ifconfig_options(c= onst char *type, const in_addr_t *addr_list, const int addr_len,
= + const I= P_ADDR_STRING *current, DWORD adapter_index, const bool test_first)<= br> {
struct gc_arena gc =3D gc_new(); struct argv argv =3D argv_new();
@@ -5492,11 +5= 238,8 @@
/* delete existing DNS/WINS settings from TAP= interface */
if (delete_first)
{=
- argv_printf(&= amp;argv, "%s%s interface ip delete %s %lu all",
- get_win_sys_path()= ,
- = NETSH_PATH_SUFFIX,
- = type,
= - adapter_index);
+ argv_printf(&argv, "%s%s interface ip del= ete %s %lu all", get_win_sys_path(),
+ NETSH_PATH_SUFFIX, type, adapter_= index);
netsh_command(&argv, 2, M_FATAL);
}

@@ -5508,15 +5251,10 @= @
{
if (delete_first = || !test_first || !ip_addr_member_of(addr_list[i], current))
{

- = const char *fmt =3D count ?
- "%s%s interface ip = add %s %lu %s"
- = : "%s%s interface ip set %s %lu static= %s";
+ = const char *fmt =3D count ? "%s%s interface ip add %s %lu %s&qu= ot;
+ = : "%s%s interface ip set %s %lu static %s"= ;;

- = argv_printf(&argv, fmt,
- get_win_sys_path(),=
- = NETSH_PATH_SUFFIX,
- = type,
- adapter_index,
+ argv_printf(&argv, fm= t, get_win_sys_path(), NETSH_PATH_SUFFIX, type, adapter_index,
print_in_addr_t(addr_list[i], 0, &gc))= ;


/* disable slow addres= s validation for DNS */
@@ -5531,9 +5269,7 @@
}

else
= {
- = msg(M_INFO, "NETSH: %lu %s %s [already set]",
- adapter_index,
- type,<= /span>
+ msg(= M_INFO, "NETSH: %lu %s %s [already set]", adapter_index, type,
print_in_addr_t(addr_list[i], 0, &gc= ));
}
}
@@ -5562,11 +5298,8 @@

}

static void

-netsh= _ifconfig(const struct tuntap_options *to,
- DWORD adapter_index,
- const in_addr_t ip,
- const in_add= r_t netmask,
- = const unsigned int flags)
+netsh_ifconfig(const struct tuntap_options *to, DWORD adapter_i= ndex, const in_addr_t ip,
+ const in_addr_t netmask, const unsigned int flags)
{
struct gc_arena gc =3D gc_new();
struct argv argv =3D argv_new();
@@ -5584,1= 9 +5317,14 @@
{
if (test_adap= ter_ip_netmask(ai, ip, netmask))
{
- msg(M_INFO, "NETSH: = %lu %s/%s [already set]",

- adapter_index,
- print_in_addr_t(ip, 0, &gc),- print_in_addr_= t(netmask, 0, &gc));
+ msg(M_INFO, "NETSH: %lu %s/%s [already set]", ad= apter_index,
+ = print_in_addr_t(ip, 0, &gc), print_in_addr_t(netmask, 0, &= gc));
}
else
{

/* example: netsh interface ip = set address 42 static 10.3.0.1 255.255.255.0 */
- argv_printf(&argv, "%s%s int= erface ip set address %lu static %s %s",
- get_win_sys_path(),<= br>- NETSH= _PATH_SUFFIX,
- = adapter_index,
- print_in_addr_t(ip, 0, &gc),+ argv_printf(&= argv, "%s%s interface ip set address %lu static %s %s", get_win_s= ys_path(),
+ = NETSH_PATH_SUFFIX, adapter_index, print_in_addr_t(ip, 0, &am= p;gc),
print_in_addr_t(netmask, 0,= &gc));

netsh_command(&a= mp;argv, 4, M_FATAL);
@@ -5610,22 +5338,14 @@
CLEAR(wins[0]);

CLEAR(wins[1]);=

- ne= tsh_ifconfig_options("dns",
- to->dns,
- to->= dns_len,
- = pai ? &pai->DnsServerList : NULL,
- adapter= _index,
- = BOOL_CAST(flags & NI_TEST_FIRST));
+ netsh_ifconfig_options("dn= s", to->dns, to->dns_len, pai ? &pai->DnsServerList : NUL= L,
+ = adapter_index, BOOL_CAST(flags & NI_TEST_FIRST));<= br> if (ai && ai->HaveWins)
= {
init_ip_addr_string2(wins, &ai->Pr= imaryWinsServer, &ai->SecondaryWinsServer);
= }

- = netsh_ifconfig_options("wins",
- to->wins,
- = to->wins_len,
- = ai ? wins : NULL,
- adapter_index,
+ netsh_ifconfig_= options("wins", to->wins, to->wins_len, ai ? wins : NULL, a= dapter_index,
BOOL_CAST(fla= gs & NI_TEST_FIRST));
}
@@ -5639,11 +5359,8 @@
struct argv argv =3D ar= gv_new();

/* example: netsh interfac= e ip set address 42 dhcp */
- argv_printf(&argv,
- "%s%s interface ip set address %lu dhcp&quo= t;,
- ge= t_win_sys_path(),
- = NETSH_PATH_SUFFIX,
- adapter_index);
+ argv_printf(&argv, "%s%s interface ip set= address %lu dhcp", get_win_sys_path(),
+ NETSH_PATH_SUFFIX, adapter_index);=

netsh_command(&argv, 4, M_FATAL= );

@@ -5659,14 +5376,8 @@
struct gc_arena gc =3D gc_new();

HANDLE pipe =3D= tt->options.msg_channel;

- enable_dhcp_message_t dhcp =3D {
- .header =3D {

- msg_enable_dhcp,
=
- sizeof(enable_dh= cp_message_t),
- = 0
- },
- .iface =3D { .inde= x =3D tt->adapter_index, .name =3D "" }
- };
+ enable_dhcp_message_t dhcp =3D { .header =3D { msg_e= nable_dhcp, sizeof(enable_dhcp_message_t), 0 },
+ .iface =3D {= .index =3D tt->adapter_index, .name =3D "" } };

if (!send_msg_iservice(pipe, &dhcp, sizeof(dh= cp), &ack, "Enable_dhcp"))
{
<= span>@@ -5690,8 +5401,7 @@

}

<= span> static void

-wind= ows_set_mtu(const int iface_index, const short family,
- const int mtu)
<= span style=3D"color: hsl(120, 100%, 40%);">+windows_set_mtu(const int iface= _index, const short family, const int mtu)

{
DWORD err =3D 0;

struct gc_arena gc =3D gc_new= ();
@@ -5702,7 +5412,8 @@
ipiface.Inte= rfaceIndex =3D iface_index;
if (family =3D=3D AF_INET6= && mtu < 1280)
{
- msg(M_INFO, "NOTE: IPv6 interface = MTU < 1280 conflicts with IETF standards and might not work");
+ msg(M_INFO,
+ "NOTE: = IPv6 interface MTU < 1280 conflicts with IETF standards and might not wo= rk");
}

er= r =3D GetIpInterfaceEntry(&ipiface);
@@ -5718,12 +5429,= 13 @@

if (err !=3D NO_ERROR)<= br> {
- = msg(M_WARN, "TUN: Setting %s mtu failed: %s [status=3D%lu if_index= =3D%d]",
- = family_name, strerror_win32(err, &gc), err, iface_index);+ msg(M_WARN, "TUN= : Setting %s mtu failed: %s [status=3D%lu if_index=3D%d]", family_name= ,
+ strerr= or_win32(err, &gc), err, iface_index);
} else
{
- msg(M_INFO, "%s MTU set to %d on interface %= d using SetIpInterfaceEntry()", family_name, mtu, iface_index);=
+ msg(M_INFO, "= %s MTU set to %d on interface %d using SetIpInterfaceEntry()", family_= name,
+ mt= u, iface_index);
}
}
=
@@ -5743,13 +5455,16 @@

if (dev_node)

{
- guid =3D get_device_guid(dev_node, BPTR(&a= ctual), BCAP(&actual), NULL, tap_reg, panel_reg, gc);
+ guid =3D
+ get_device_guid(dev_node, BP= TR(&actual), BCAP(&actual), NULL, tap_reg, panel_reg, gc); }
else
{
<= span style=3D"color: hsl(0, 100%, 40%);">- guid =3D get_unspecified_= device_guid(0, BPTR(&actual), BCAP(&actual), tap_reg, panel_reg, NU= LL, gc);

+ gui= d =3D get_unspecified_device_guid(0, BPTR(&actual), BCAP(&actual), = tap_reg, panel_reg,
+= NULL, gc);

- if (get_unspecifi= ed_device_guid(1, NULL, 0, tap_reg, panel_reg, NULL, gc)) /* ambiguous if m= ore than one TAP-Windows adapter */
+ if (get_unspecified_device_guid(1, NULL, 0, tap_reg= , panel_reg, NULL,
+ = gc)) /* ambiguous if more than one T= AP-Windows adapter */
{
= guid =3D NULL;
}
@@ -5757,7 +54= 72,7 @@

if (!guid)
= {
- return &= quot;NULL"; /* not found */
+ return "NULL"; /* not found */ }
else if (strcmp(BSTR(&actual), "= ;NULL"))
{
@@ -5765,7 +5480,7 @@<= /span>
}
else
{
- return guid; = /* no control panel name, return GUID instead */
+ return guid; /* no control panel nam= e, return GUID instead */
}
}<= br>
@@ -5788,13 +5503,10 @@
= if (tt->standby_iter =3D=3D IPW32_SET_ADAPTIVE_TRY_NETSH)
{

msg(M_INFO, "NOTE: now tryi= ng netsh (this may take some time)");
- netsh_ifconfig(&tt->options,=
- t= t->adapter_index,
- = tt->local,
- tt->adapter_netmask,=
- N= I_TEST_FIRST|NI_IP_NETMASK|NI_OPTIONS);
+ netsh_ifconfig(&tt->options, tt->= adapter_index, tt->local, tt->adapter_netmask,
+ NI_TEST_FIRST = | NI_IP_NETMASK | NI_OPTIONS);
}
- else if (tt->standby_iter &g= t;=3D IPW32_SET_ADAPTIVE_TRY_NETSH*2)
+ else if (tt->standby_iter >=3D IPW32_SET_AD= APTIVE_TRY_NETSH * 2)
{
= ret =3D false;
}
@@ -5822,7 +55= 34,8 @@
}

static void
-write_dhcp_u32_array(st= ruct buffer *buf, const int type, const uint32_t *data, const unsigned int = len, bool *error)
+wr= ite_dhcp_u32_array(struct buffer *buf, const int type, const uint32_t *data= ,
+ = const unsigned int len, bool *error)
{
= if (len > 0)
{
@@ -5890,7 +560= 3,7 @@

for (i =3D 0; i < array_le= n; i++)
{
- const char *ptr =3D str_array[i];
+ const char *ptr =3D str_array[i];=

if (strlen(ptr) + len + 1 > = sizeof(tmp_buf))
{
@@ -5909,7 +562= 2,7 @@
{
if (*ptr =3D= =3D '.' || *ptr =3D=3D '\0')
{=
- tmp_b= uf[label_length_pos] =3D (len-label_length_pos)-1;
+ tmp_buf[label_length_pos] = =3D (len - label_length_pos) - 1;
label_le= ngth_pos =3D len;
if (*ptr =3D=3D '\0&= #39;)
{
@@ -5966,9 +5679,7= @@

if (o->domain_search_list_len= > 0)
{
- write_dhcp_search_str(buf, 119, o->domain_search_list,=
- = o->domain_search_list_len,
- &error);
+ write_dhcp_search_str(buf, = 119, o->domain_search_list, o->domain_search_list_len, &error);
}

/* the MS DHCP= server option 'Disable Netbios-over-TCP/IP
@@ -5981,10= +5692,10 @@
msg(M_WARN, "build_dhcp_opti= ons_string: buffer overflow building DHCP options");
= return false;
}
- buf_write_u8(buf, 43);
<= span style=3D"color: hsl(0, 100%, 40%);">- buf_write_u8(buf, 6);/* = total length field */

-= buf_write_u8(buf, 0x001);
- buf_write_u8(buf, 4);/* length of the vendor specifie= d field */
+ b= uf_write_u8(buf, 43);
+ buf_write_u8(buf, 6); /* total length field */
+ buf_write_u8(buf, 0x001);
+ buf_write_u8(buf= , 4); /* length of the vendor specified field */
b= uf_write_u32(buf, 0x002);
}
retur= n !error;
@@ -6081,7 +5792,9 @@
if (dsa =3D=3D local)
{
- msg(M_FATAL, "ERROR: There = is a clash between the --ifconfig local address and the internal DHCP serve= r address -- both are set to %s -- please use the --ip-win32 dynamic option= to choose a different free address from the --ifconfig subnet for the inte= rnal DHCP server", print_in_addr_t(dsa, 0, &gc));
+ msg(M_FATAL,
+ "ERROR: There is a= clash between the --ifconfig local address and the internal DHCP server ad= dress -- both are set to %s -- please use the --ip-win32 dynamic option to = choose a different free address from the --ifconfig subnet for the internal= DHCP server",

+= print_in_addr_t(dsa, 0, &gc));
}

if ((local & netmask) !=3D (dsa &= netmask))
@@ -6099,38 +5812,38 @@
ULO= NG info[3];
DWORD len;
CLEAR(info= );
- if (DeviceIoCon= trol(tt->hand, TAP_WIN_IOCTL_GET_VERSION,
- &info, sizeof(info),
- &= amp;info, sizeof(info), &len, NULL))
+ if (DeviceIoControl(tt->hand, TAP_WIN_IOCTL_GET= _VERSION, &info, sizeof(info), &info,
+ sizeof(info), &len, N= ULL))
{
- msg(D_TUNTAP_INFO, "TAP-Windows Driver Version %d.%d %s= ",
- (i= nt)info[0],
- = (int)info[1],
+ = msg(D_TUNTAP_INFO, "TAP-Windows Driver Version %d.%d %s", (in= t)info[0], (int)info[1],
(info[2] ? "(DEB= UG)" : ""));
-
}
if (!(info[0] =3D=3D TAP= _WIN_MIN_MAJOR && info[1] >=3D TAP_WIN_MIN_MINOR))
{

- msg(= M_FATAL, "ERROR: This version of " PACKAGE_NAME " requires = a TAP-Windows driver that is at least version %d.%d -- If you recently upgr= aded your " PACKAGE_NAME " distribution, a reboot is probably req= uired at this point to get Windows to see the new driver.",
= - TAP_WIN_MIN_MAJOR,
- TAP_WIN_MIN= _MINOR);
+ msg= (M_FATAL,
+ = "ERROR: This version of " PACKAGE_NAME
+ " requires a TAP-Windows= driver that is at least version %d.%d -- If you recently upgraded your &qu= ot; PACKAGE_NAME
+ = " distribution, a reboot is probably required at this point t= o get Windows to see the new driver.",
+ TAP_WIN_MIN_MAJOR, TAP_WIN_MIN_MINOR);<= /span>
}

/* usage of n= umeric constants is ugly, but this is really tied to
= * *this* version of the driver
*/
- if (tt->type =3D=3D DEV_TYPE_TUN
- && info= [0] =3D=3D 9 && info[1] < 8)
+ if (tt->type =3D=3D DEV_TYPE_TUN && info= [0] =3D=3D 9 && info[1] < 8)
{
- msg(M_INFO, "WARNING:= Tap-Win32 driver version %d.%d does not support IPv6 in TUN mode. IPv6 wi= ll not work. Upgrade your Tap-Win32 driver.", (int)info[0], (int)info[= 1]);

+ msg(M_I= NFO,
+ &qu= ot;WARNING: Tap-Win32 driver version %d.%d does not support IPv6 in TUN mo= de. IPv6 will not work. Upgrade your Tap-Win32 driver.",
+ (int)info[0], (int)in= fo[1]);

}

/* ta= p driver 9.8 (2.2.0 and 2.2.1 release) is buggy
*/
- if (tt->type =3D= =3D DEV_TYPE_TUN
- = && info[0] =3D=3D 9 && info[1] =3D=3D 8)
+ if (tt->type =3D=3D DEV_TYPE= _TUN && info[0] =3D=3D 9 && info[1] =3D=3D 8)

{

- msg(= M_FATAL, "ERROR: Tap-Win32 driver version %d.%d is buggy regarding sm= all IPv4 packets in TUN mode. Upgrade your Tap-Win32 driver.", (int)in= fo[0], (int)info[1]);
+ msg(M_FATAL,
+ (int)info= [0], (int)info[1]);
}
}

@@ -6139,43 +5852,33 @@
{
<= span> ULONG mtu =3D 0;

DWORD len;
- if (DeviceIoControl(tt->hand, T= AP_WIN_IOCTL_GET_MTU,
-= &mtu, sizeof(mtu),
- &mtu, sizeof(mtu), &am= p;len, NULL))
+ if= (DeviceIoControl(tt->hand, TAP_WIN_IOCTL_GET_MTU, &mtu, sizeof(mtu)= , &mtu, sizeof(mtu), &len,
+ NULL))
{=
msg(D_MTU_INFO, "TAP-Windows MTU=3D%d", (int)m= tu);
}
}

= static void
-tun= tap_set_ip_addr(struct tuntap *tt,
- const char *device_guid,
- bool dhcp_masq_post)<= /span>
+tuntap_set_ip_addr(s= truct tuntap *tt, const char *device_guid, bool dhcp_masq_post)
<= span> {

struct gc_arena gc =3D gc_new();
const DWORD index =3D tt->adapter_index;


/* flush arp cache */
- if (tt->backend_driver =3D=3D WINDOWS_DRIVER_TAP_WIN= DOWS6
- &&am= p; index !=3D TUN_ADAPTER_INDEX_INVALID)
+ if (tt->backend_driver =3D=3D WINDOWS_DRIVER_TA= P_WINDOWS6 && index !=3D TUN_ADAPTER_INDEX_INVALID)
{

DWORD status =3D -1;

if (tt->options.msg_channel)
= {
ack_message_t ack;
- flush_neighbors_message_t msg = =3D {
- = .header =3D {
- = msg_flush_neighbors,
- sizeof(flush_neighbors_message_t),- 0- },
- .family =3D AF_INE= T,

- .if= ace =3D {.index =3D index, .name =3D "" }
- };
+ flush_neighbors_message_t msg =3D { = .header =3D { msg_flush_neighbors,
+ si= zeof(flush_neighbors_message_t), 0 },
+ .family =3D= AF_INET,
+ = .iface =3D { .index =3D index, .name = =3D "" } };

- if (send_msg_iservice(tt->options.msg_chan= nel, &msg, sizeof(msg),
- &ack, "TUN"))<= br>+ if (send_msg_is= ervice(tt->options.msg_channel, &msg, sizeof(msg), &ack, "T= UN"))
{
= status =3D ack.error_number;
}
@@ -6187,17 +5890,13 @@


if (sta= tus =3D=3D NO_ERROR)
{
- msg(M_INFO, "Successful ARP Flus= h on interface [%lu] %s",
- index,
- device_guid);
+ msg(M_INFO, "Successful ARP Flush on i= nterface [%lu] %s", index, device_guid);
}
else if (status !=3D -1)
{<= /span>
- msg(D_TUNT= AP_INFO, "NOTE: FlushIpNetTable failed on interface [%lu] %s (status= =3D%lu) : %s",
- = index,
- = device_guid,
- status,
- strerror_win32(status, &gc));
+ msg(D_TUNTAP_INFO,=
+ "NOTE= : FlushIpNetTable failed on interface [%lu] %s (status=3D%lu) : %s", i= ndex,
+ = device_guid, status, strerror_win32(status, &gc));
= }

/*
@@ -= 6210,7 +5909,8 @@
/* check dhcp enable status = */
if (dhcp_status(index) =3D=3D DHCP_STATUS_D= ISABLED)
{
- msg(M_WARN, "WARNING: You have selec= ted '--ip-win32 dynamic', which will not work unless the TAP-Window= s TCP/IP properties are set to 'Obtain an IP address automatically'= ");
+ = msg(M_WARN,
+ = "WARNING: You have selected '--ip-win32 dynamic&#= 39;, which will not work unless the TAP-Windows TCP/IP properties are set t= o 'Obtain an IP address automatically'");
= }

/* force an expli= cit DHCP lease renewal on TAP adapter? */
@@ -6232,20 +5932= ,21 @@
if (tt->did_ifconfig_setup && tt->= ;options.ip_win32_type =3D=3D IPW32_SET_IPAPI)
{
DWORD status;
- const char *error_suffix =3D "I am having trouble = using the Windows 'IP helper API' to automatically set the IP addre= ss -- consider using other --ip-win32 methods (not 'ipapi')";<= /span>
+ const char *= error_suffix =3D
+ = "I am having trouble using the Windows 'IP helper API'= ; to automatically set the IP address -- consider using other --ip-win32 me= thods (not 'ipapi')";

= /* couldn't get adapter index */
if (index = =3D=3D TUN_ADAPTER_INDEX_INVALID)
{
- msg(M_FATAL, "ERROR= : unable to get adapter index for interface %s -- %s",

- device_guid,
+ msg(M_FATAL, &qu= ot;ERROR: unable to get adapter index for interface %s -- %s", device_= guid,
error_suffix);
= }

/* check dhcp enable statu= s */
if (dhcp_status(index) =3D=3D DHCP_STATUS_DIS= ABLED)
{
- msg(M_WARN, "NOTE: You have selected (explicit= ly or by default) '--ip-win32 ipapi', which has a better chance of = working correctly if the TAP-Windows TCP/IP properties are set to 'Obta= in an IP address automatically'");
+ msg(M_WARN,
+ "NOTE: You have selected (= explicitly or by default) '--ip-win32 ipapi', which has a better ch= ance of working correctly if the TAP-Windows TCP/IP properties are set to &= #39;Obtain an IP address automatically'");
= }

/* delete previously added I= P addresses which were not
@@ -6253,28 +5954,21 @@ delete_temp_addresses(index);

= /* add a new IP address */
- if ((status =3D AddIPAddress(htonl(tt->local= ),
- = htonl(tt->adapter_netmask),
- index,- = &tt->ipapi_context,
- &tt->ipapi_instance)) = =3D=3D NO_ERROR)
+ = if ((status =3D AddIPAddress(htonl(tt->local), htonl(tt->adapter= _netmask), index,
+ = &tt->ipapi_context, &tt->ipa= pi_instance))
+ = =3D=3D NO_ERROR)
{
- msg(M_INFO, "Succeeded in addi= ng a temporary IP/netmask of %s/%s to interface %s using the Win32 IP Helpe= r API",
- = print_in_addr_t(tt->local, 0, &gc),
- print_in_addr_t(tt->adapter_= netmask, 0, &gc),
-= device_guid
- );
+ msg(M_INFO,
+ "Succeeded in adding a temporary IP/netmask o= f %s/%s to interface %s using the Win32 IP Helper API",
+ print_in_addr_t(tt= ->local, 0, &gc), print_in_addr_t(tt->adapter_netmask, 0, &gc= ),

+ d= evice_guid);
}
else
{
-= msg(M_FATAL, "ERROR: AddIPAddress %s/%s failed on interfac= e %s, index=3D%lu, status=3D%lu (windows error: '%s') -- %s",<= /span>
- print_= in_addr_t(tt->local, 0, &gc),
- print_in_addr_t(tt->adapter_netmask, 0, &= amp;gc),
- = device_guid,
- = index,
- = status,
- = strerror_win32(status, &gc),
- error_suffix);
+ msg(M_FATAL,
+ "ERROR: AddIPA= ddress %s/%s failed on interface %s, index=3D%lu, status=3D%lu (windows err= or: '%s') -- %s",

+ print_in_addr_t(tt->local, 0, &gc), print= _in_addr_t(tt->adapter_netmask, 0, &gc),
+ device_guid, index, status, str= error_win32(status, &gc), error_suffix);
}
tt->ipapi_context_defined =3D true;
}

@@ -6287,11 +5981,11 @@
{<= br> ULONG status =3D TRUE;
DWORD len;=
- if (!DeviceIoControl(tt-= >hand, TAP_WIN_IOCTL_SET_MEDIA_STATUS,
- &status, sizeof(status),
- = &status, sizeof(status), &len, NULL))
+ if (!DeviceIoControl(tt->hand, TAP_WIN_I= OCTL_SET_MEDIA_STATUS, &status, sizeof(status), &status,
= + sizeo= f(status), &len, NULL))
{
- msg(M_WARN, "WARNING: The TAP-Win= dows driver rejected a TAP_WIN_IOCTL_SET_MEDIA_STATUS DeviceIoControl call.= ");
+ msg= (M_WARN,
+ = "WARNING: The TAP-Windows driver rejected a TAP_WIN_IOCTL_SET_MEDIA_S= TATUS DeviceIoControl call.");
}
=
int s =3D tt->options.tap_sleep;
= @@ -6325,17 +6019,16 @@
ep[1] =3D htonl(tt->loc= al & tt->remote_netmask);
ep[2] =3D htonl(t= t->remote_netmask);

- status =3D DeviceIoControl(tt->hand, TAP_WIN_= IOCTL_CONFIG_TUN,
- = ep, sizeof(ep),
- ep, sizeof(ep), &am= p;len, NULL);
+ = status =3D DeviceIoControl(tt->hand, TAP_WIN_IOCTL_CONFIG_TUN, ep, siz= eof(ep), ep, sizeof(ep),
+ &len, NULL);

if (tt->did_ifconfig_setup)
= {
- msg(= status ? M_INFO : M_FATAL, "Set TAP-Windows TUN subnet mode network/lo= cal/netmask =3D %s/%s/%s [%s]",
+ msg(status ? M_INFO : M_FATAL,
+ "Set TAP-Windo= ws TUN subnet mode network/local/netmask =3D %s/%s/%s [%s]",
print_in_addr_t(ep[1], IA_NET_ORDER, &gc),
print_in_addr_t(ep[0], IA_NET_ORDER, &gc),=
- print= _in_addr_t(ep[2], IA_NET_ORDER, &gc),
- status ? "SUCCEEDED" : "= FAILED");
+ = print_in_addr_t(ep[2], IA_NET_ORDER, &gc), status ? "SU= CCEEDED" : "FAILED");
}
<= span> else

{
@@ -6349,11 += 6042,11 @@
ep[0] =3D htonl(tt->local); ep[1] =3D htonl(tt->remote_netmask);
<= /span>
- if (!DeviceIoC= ontrol(tt->hand, TAP_WIN_IOCTL_CONFIG_POINT_TO_POINT,
- ep, sizeof(= ep),
- = ep, sizeof(ep), &len, NULL))
+ if (!DeviceIoControl(tt->hand, TAP_WIN_= IOCTL_CONFIG_POINT_TO_POINT, ep, sizeof(ep), ep,
+ sizeof(ep), &= len, NULL))
{
- msg(M_FATAL, "ERROR: The TAP-Windows driv= er rejected a DeviceIoControl call to set Point-to-Point mode, which is req= uired for --dev tun");
+ msg(M_FATAL,
+ "ERROR: The TAP-Windows driver rejected a= DeviceIoControl call to set Point-to-Point mode, which is required for --d= ev tun");
}
}
=
@@ -6376,7 +6069,9 @@
{=
if (tt->topology =3D=3D TOP_SUBNET)
= {
- = ep[2] =3D dhcp_masq_addr(tt->local, tt->remote_netmask, tt->option= s.dhcp_masq_custom_offset ? tt->options.dhcp_masq_offset : 0);+ ep[2] =3D dhcp_ma= sq_addr(
+ = tt->local, tt->remote_netmask,
+ tt->options.dhcp_masq_custom_offse= t ? tt->options.dhcp_masq_offset : 0);
}=
else
{
@@ -6386= ,7 +6081,9 @@
else
{
ASSERT(tt->type =3D=3D DEV_TYPE_TAP);

- ep[2] =3D dhcp_masq_addr(tt->loc= al, tt->adapter_netmask, tt->options.dhcp_masq_custom_offset ? tt->= ;options.dhcp_masq_offset : 0);
+ ep[2] =3D
+ dhcp_masq_addr(tt->local, tt->adapter_netmask,<= /span>
+ = tt->options.dhcp_masq_custom_offset ? tt->options.dhcp_masq_of= fset : 0);
}

/*= lease time in seconds */
@@ -6395,20 +6092,17 @@ ASSERT(ep[3] > 0);

#ifnde= f SIMULATE_DHCP_FAILED /* this code is disabled to simulate bad DHCP negoti= ation */
- if (!Devi= ceIoControl(tt->hand, TAP_WIN_IOCTL_CONFIG_DHCP_MASQ,
- ep, sizeof(ep),=
- = ep, sizeof(ep), &len, NULL))
+ if (!DeviceIoControl(tt->hand, TAP_WIN_IOCTL_CONFIG= _DHCP_MASQ, ep, sizeof(ep), ep, sizeof(ep),
+ &len, NULL)) {
- = msg(M_FATAL, "ERROR: The TAP-Windows driver rejected a DeviceIoControl= call to set TAP_WIN_IOCTL_CONFIG_DHCP_MASQ mode");
+ msg(M_FATAL,
+ "ERROR: The TAP-Wind= ows driver rejected a DeviceIoControl call to set TAP_WIN_IOCTL_CONFIG_DHCP= _MASQ mode");
}

- msg(M_INFO, "Notified TAP-Wi= ndows driver to set a DHCP IP/netmask of %s/%s on interface %s [DHCP-serv: = %s, lease-time: %d]",

- print_in_addr_t(tt->local, 0, &gc),
- print_in_addr_t(tt->adapter_ne= tmask, 0, &gc),
- = device_guid,
- = print_in_addr_t(ep[2], IA_NET_ORDER, &gc),
- ep[3]
- );
+ msg(M_INFO,
+ "Notified TAP-Windows driver to set a DHCP IP/netma= sk of %s/%s on interface %s [DHCP-serv: %s, lease-time: %d]",+ print_in_addr_t(tt-&= gt;local, 0, &gc), print_in_addr_t(tt->adapter_netmask, 0, &gc),=
+ device_guid= , print_in_addr_t(ep[2], IA_NET_ORDER, &gc), ep[3]);
<= /span>
/* user-supplied DHCP options capability */
= if (tt->options.dhcp_options)
@@ -6417,11 +61= 11,11 @@
if (build_dhcp_options_string(&buf, &= amp;tt->options))
{
= msg(D_DHCP_OPT, "DHCP option string: %s", format_hex(BPTR(&= buf), BLEN(&buf), 0, &gc));
- if (!DeviceIoControl(tt->hand, TAP_WIN_IOCTL_C= ONFIG_DHCP_SET_OPT,
- = BPTR(&buf), BLEN(&buf),
- B= PTR(&buf), BLEN(&buf), &len, NULL))

+ if (!DeviceIoControl(tt->hand, T= AP_WIN_IOCTL_CONFIG_DHCP_SET_OPT, BPTR(&buf),
+ BLEN(&bu= f), BPTR(&buf), BLEN(&buf), &len, NULL))
= {
- = msg(M_FATAL, "ERROR: The TAP-Windows driver rejected a TAP_WIN_IOCT= L_CONFIG_DHCP_SET_OPT DeviceIoControl call");
+ msg(M_FATAL,
+ "ERROR: Th= e TAP-Windows driver rejected a TAP_WIN_IOCTL_CONFIG_DHCP_SET_OPT DeviceIoC= ontrol call");

}
= }
else
@@ -6430,13 +6124,14 @@
}
free_buf(&buf);
}
-#end= if /* ifndef SIMULATE_DHCP_FAILED */
+#endif /* ifndef SIMULATE_DHCP_FAILE= D */

gc_free(&gc);
}


static bool
-tun_try_open_device(struct tuntap *tt, cons= t char *device_guid, const struct device_instance_id_interface *device_inst= ance_id_interface)
+t= un_try_open_device(struct tuntap *tt, const char *device_guid,
+ const struct= device_instance_id_interface *device_instance_id_interface)

{

const char *path =3D NULL;
c= har tuntap_device_path[256];
@@ -6455,8 +6150,7 @@ if (tt->backend_driver =3D=3D DRIVER_DCO) {
char *last_sep =3D s= trrchr(dev_if->device_interface, '\\');
- if (!last_sep
- || strcmp(last_sep= + 1, DCO_WIN_REFERENCE_STRING) !=3D 0)
+ if (!last_sep || strcmp(last_sep + 1, D= CO_WIN_REFERENCE_STRING) !=3D 0)
{<= br> continue;
}<= /span>
@@ -6473,25 +6167,19 @@
else {
/* Open TAP-Windows */
- snprintf(tuntap_device_path= , sizeof(tuntap_device_path), "%s%s%s",

- USERMODEDEVICEDIR,
<= span style=3D"color: hsl(0, 100%, 40%);">- device_guid,
- TAP_WIN_= SUFFIX);
+ snp= rintf(tuntap_device_path, sizeof(tuntap_device_path), "%s%s%s", U= SERMODEDEVICEDIR,
+ = device_guid, TAP_WIN_SUFFIX);
path = =3D tuntap_device_path;
}

= msg(D_TAP_WIN_DEBUG, "Using device interface: %s", pat= h);

-= tt->hand =3D CreateFile(path,
- GENERIC_READ | GENERIC_WRITE,
- = 0, /* was: FILE_SHARE_READ */
- 0,
- OPEN_EXISTING,
<= span style=3D"color: hsl(0, 100%, 40%);">- FILE_AT= TRIBUTE_SYSTEM | FILE_FLAG_OVERLAPPED,

- 0);
+ tt->hand =3D CreateFile(path, GENERIC_REA= D | GENERIC_WRITE, 0, /* was: FILE_SHARE_READ */
+ 0, OPEN_EXISTING, FI= LE_ATTRIBUTE_SYSTEM | FILE_FLAG_OVERLAPPED, 0);
if (tt= ->hand =3D=3D INVALID_HANDLE_VALUE)
{
- msg(D_TUNTAP_INFO | M_ERRNO= , "CreateFile failed on %s device: %s", print_tun_backend_driver(= tt->backend_driver), path);

+ msg(D_TUNTAP_INFO | M_ERRNO, "CreateFile failed on = %s device: %s",
= + print_tun_backend_driver(tt->backend_driver), path);=
return false;
}

@@ -6499,11 +6187,13 @@
}
=
void
= -tun_open_device(struct tuntap *tt, const char *dev_node, const char **devi= ce_guid, struct gc_arena *gc)
+tun_open_device(struct tuntap *tt, const char *dev_node, const ch= ar **device_guid,
+ = struct gc_arena *gc)
{
= const struct tap_reg *tap_reg =3D get_tap_reg(gc);
con= st struct panel_reg *panel_reg =3D get_panel_reg(gc);
- const struct device_instance_id_interfa= ce *device_instance_id_interface =3D get_device_instance_id_interface(gc);<= /span>
+ const struct dev= ice_instance_id_interface *device_instance_id_interface =3D
+ get_device_instance_id_inte= rface(gc);


uint8_t actual_buffer[256= ];

@@ -6515,7 +6205,8 @@
= enum tun_driver_type windows_driver =3D WINDOWS_DRIVER_UNSPECIFIED= ;

/* Get the device GUID for the= device specified with --dev-node. */
- *device_guid =3D get_device_guid(dev_node, actual_b= uffer, sizeof(actual_buffer), &windows_driver, tap_reg, panel_reg, gc);=
+ *device_gui= d =3D get_device_guid(dev_node, actual_buffer, sizeof(actual_buffer),
+ = &windows_driver, tap_reg, panel_reg, gc);

if (!*device_guid)
{
@@ -6524,13 +6215,16 @@

= if (tt->backend_driver !=3D windows_driver)
= {
- msg(= M_FATAL, "Adapter '%s' is using %s driver, %s expected. If you= want to use this device, adjust --windows-driver.",
- dev_node, print_tun_bac= kend_driver(windows_driver), print_tun_backend_driver(tt->backend_driver= ));
+ msg(= M_FATAL,
+ = "Adapter '%s' is using %s driver, %s expected. If you wan= t to use this device, adjust --windows-driver.",
+ dev_node, print_tun_backe= nd_driver(windows_driver),
+ print_tun_backend_driver(tt->backend_driver));
}

if (!tu= n_try_open_device(tt, *device_guid, device_instance_id_interface)) {
- = msg(M_FATAL, "Failed to open %s adapter: %s", print_tun_= backend_driver(tt->backend_driver), dev_node);
+ msg(M_FATAL, "Failed to open= %s adapter: %s",
- *device_guid =3D get_unspeci= fied_device_guid(device_number,
- actual_buf= fer,
- = sizeof(actual_buffer),
- = tap_reg,

- panel_reg,
- = &windows_driver,
- = gc);
+ = *device_guid =3D
+ tap_reg, panel_reg, &w= indows_driver, gc);

if (!*de= vice_guid)
{
= /* try to create an adapter a few times if we have a service pipe handle */=
- if ((= ++adapters_created > 10) || !do_create_adapter_service(tt->options.ms= g_channel, tt->backend_driver))
+ if ((++adapters_created > 10)
<= span style=3D"color: hsl(120, 100%, 40%);">+ || !do_crea= te_adapter_service(tt->options.msg_channel, tt->backend_driver))
{
- msg(M_FATAL, "All %s adapters on this sys= tem are currently in use or disabled.", print_tun_backend_driver(tt-&g= t;backend_driver));
+= msg(M_FATAL, "All %s adapters on this system are c= urrently in use or disabled.",
+ print_tun_backend_driver(tt->bac= kend_driver));
}
= else
{
@@ -6622,10= +6314,7 @@
*/
if (dhcp_= status(tt->adapter_index) !=3D DHCP_STATUS_ENABLED)
= {
- net= sh_ifconfig(&tt->options,
- tt->adapter_index,
- tt->loc= al,

- = tt->adapter_netmask,
+ netsh_ifconfig(&tt->options, tt->adapter= _index, tt->local, tt->adapter_netmask,
= NI_TEST_FIRST | NI_IP_NETMASK | NI_OPTIONS);
}

else
@@ -6686,9 +6375,= 11 @@
if ((tt->options.dhcp_options & DHCP_OPTI= ONS_DHCP_REQUIRED)
&& tt->backend_drive= r !=3D WINDOWS_DRIVER_TAP_WINDOWS6)
{
- msg(M_WARN, "Some --dhcp-= option or --dns options require DHCP server,"
+ msg(M_WARN,
+ "Some --dhcp-option or --dn= s options require DHCP server,"
" wh= ich is not supported by the selected %s driver. They will be"- " ignored.&qu= ot;, print_tun_backend_driver(tt->backend_driver));
+ " ignored.",
+ print_tun_bac= kend_driver(tt->backend_driver));
}

/* dco-win already opened the device, which handle = we treat as socket */
@@ -6701,11 +6392,11 @@

/*netcmd_semaphore_lock ();*/

- msg( M_INFO, "= open_tun");
+ = msg(M_INFO, "open_tun");

= if (tt->type !=3D DEV_TYPE_TAP && tt->type !=3D DEV_TYPE_TUN)=
{
- msg(M_FATAL|M_NOPREFIX, "Unknown virtual device type: '%= s'", dev);
+= msg(M_FATAL | M_NOPREFIX, "Unknown virtual device type: '%= s'", dev);
}

struct gc_arena gc =3D gc_new(); /* used also for device_guid alloca= tion */

@@ -6725,10 +6416,8 @@
{
struct buffer out =3D alloc_buf_gc(256, gc);
= DWORD len;
- if (DeviceIoControl(tt->hand, TAP_WIN_IOCTL_GET_INFO,=
- = BSTR(&out), BCAP(&out),
- BSTR(&out), BCAP(&out),
- = &len, NULL))
+ = if (DeviceIoControl(tt->hand, TAP_WIN_IOCTL_GET_INFO, BSTR(&ou= t), BCAP(&out), BSTR(&out),
+ BCAP(&out), &len, NULL)= )
{
return BSTR(&= out);
}
@@ -6743,10 +6432,8 @@
{
struct buffer out =3D alloc_bu= f(1024);
DWORD len;
- while (DeviceIoControl(tt->hand, TAP_WIN_= IOCTL_GET_LOG_LINE,
- = BSTR(&out), BCAP(&out),
- BSTR(= &out), BCAP(&out),

- &len, NULL))
+ while (DeviceIoControl(tt->han= d, TAP_WIN_IOCTL_GET_LOG_LINE, BSTR(&out), BCAP(&out),
+ B= STR(&out), BCAP(&out), &len, NULL))

{<= /span>
msg(D_TAP_WIN_DEBUG, "TAP-Windows: %s&quo= t;, BSTR(&out));
}
@@ -6764,22= +6451,15 @@
int len =3D ipv6 ? tt->options.dns6_le= n : tt->options.dns_len;
if (len > 0)
= {
- a= rgv_printf(&argv,
-= "%s%s interface %s delete dns %lu all",
- get_win= _sys_path(),
- = NETSH_PATH_SUFFIX,
- ipv6 ? "ipv6" : "ipv4",
- tt-&g= t;adapter_index);
+ = argv_printf(&argv, "%s%s interface %s delete dns %lu all&quo= t;, get_win_sys_path(),
+ NETSH_PATH_SUFFIX, ipv6 ? "ipv6" : "= ipv4", tt->adapter_index);
netsh_command(&= amp;argv, 1, M_WARN);
}

if (!ipv6 && tt->options.wins_len > 0)

{

- argv= _printf(&argv,
- = "%s%s interface ipv4 delete winsservers %lu all"= ,
- = get_win_sys_path(),
- = NETSH_PATH_SUFFIX,
- tt->adapter_index);
+ argv_printf(&argv, "= %s%s interface ipv4 delete winsservers %lu all", get_win_sys_path(),
+ N= ETSH_PATH_SUFFIX, tt->adapter_index);
netsh_com= mand(&argv, 1, M_WARN);
}
=
@@ -6801,13 +6481,8 @@
{
= ifconfig_ip_local =3D print_in_addr_t(tt->local, 0, gc); }
- argv= _printf(&argv,
- = "%s%s interface %s delete address %lu %s store=3Dactive&q= uot;,
- = get_win_sys_path(),
- = NETSH_PATH_SUFFIX,
- ipv6 ? "ipv6" : "ipv4",
- tt->ada= pter_index,
- = ifconfig_ip_local);
+ argv_printf(&argv, "%s%s interface %s delete address %lu= %s store=3Dactive", get_win_sys_path(),
+ NETSH_PATH_SUFFIX, ipv6 ? "i= pv6" : "ipv4", tt->adapter_index, ifconfig_ip_local);
netsh_command(&argv, 1, M_WARN);

argv_free(&argv);
@@ -6885,7 +6560,8= @@
{
/* We didn'= t do ifconfig. */
}
- else if (tt->options.ip_win32_type =3D=3D= IPW32_SET_DHCP_MASQ || tt->options.ip_win32_type =3D=3D IPW32_SET_ADAPT= IVE)
+ else if= (tt->options.ip_win32_type =3D=3D IPW32_SET_DHCP_MASQ
+ || tt->options.ip= _win32_type =3D=3D IPW32_SET_ADAPTIVE)
{ /* We don't have to clean the configuration with DH= CP. */
}
@@ -6912,10 +6588,9 @@
DWORD status;
if ((status = =3D DeleteIPAddress(tt->ipapi_context)) !=3D NO_ERROR)
= {
- = msg(M_WARN, "Warning: DeleteIPAddress[%u] failed on TAP-Windows adapte= r, status=3D%u : %s",
- (unsigned int)tt->ipapi_context,
- (unsigned int)status,
- strerror= _win32(status, &gc));
+ msg(M_WARN,
+ "Warning: DeleteIPAddress[%u] failed on TAP-= Windows adapter, status=3D%u : %s",
+ (unsigned int)tt->ipapi_context, (u= nsigned int)status, strerror_win32(status, &gc));
= }
}

@@ -6934,17 = +6609,14 @@
* Convert --ip-win32 constants between index = and ascii form.
*/

-struct ipset_names {
+struct ipset_names
+{
const char *short_= form;
};

/* Indexed by = IPW32_SET_x */
static const struct ipset_names ipset_names= [] =3D {
- {"ma= nual"},
- {&quo= t;netsh"},
- {&= quot;ipapi"},
- = {"dynamic"},
- {"adaptive"}
+ { "manual" }, { "netsh" }, { "ipapi&q= uot; }, { "dynamic" }, { "adaptive" }
= };

int
@@ -6994,7 +6666,= 7 @@
return BSTR(&out);
}<= br>
-#else /* ge= neric */
+#else = /* generic */

void
open_tun(const char *dev, const char *dev_type, const char *d= ev_node, struct tuntap *tt,
@@ -7024,4 +6696,4 @@ return read(tt->fd, buf, len);
}
=
-#endif /* if d= efined (TARGET_ANDROID) */
+#endif /* if defined (TARGET_ANDROID) */
diff --git a/src/openvpn/tun.h b/src/openvpn/tun.h
index c53fdc0..06fc729 100644

--- a/src/openvpn/tun.h
+++ b/src/openvpn/tun.h
@@ -40,7 +40,8 @@
#include "networking.h"
#include &= quot;dco.h"

-enum tun_driver_type {
+enum tun_driver_type
+{
WINDOWS_DRIVER_UNSPECIFIED,<= br> WINDOWS_DRIVER_TAP_WINDOWS6,
DRIVER_GENE= RIC_TUNTAP,
@@ -67,19 +68,20 @@
#define IP= W32_SET_ADAPTIVE_TRY_NETSH 20

/* bit = flags for DHCP options */
-#define DHCP_OPTIONS_DHCP_OPTIONAL (1<<0)
-#define DHCP_OPTIONS_DHCP_REQUIRED (1<&l= t;1)
+#define DHCP_OP= TIONS_DHCP_OPTIONAL (1 << 0)
+#define DHCP_OPTIONS_DHCP_REQUIRED (1 << 1)
=
-struct tuntap_= options {
+struct tun= tap_options
+{=
/* --ip-win32 options */
bool ip_win32_= defined;

-#define IPW32_SET_MANUAL 0 /* "--ip-win32 manual" */=
-#define IPW32_SET_NET= SH 1 /* "--ip-win32 netsh" */
-#define IPW32_SET_IPAPI 2 /* "--ip= -win32 ipapi" */
-= #define IPW32_SET_DHCP_MASQ 3 /* "--ip-win32 dynamic" */
-#define IPW32_SET_ADAPTIV= E 4 /* "--ip-win32 adaptive" */
-#define IPW32_SET_N 5
+#define IPW32_SET_MANUAL 0 /* &qu= ot;--ip-win32 manual" */
+#define IPW32_SET_NETSH 1 /* "--ip-win32 netsh" */<= /span>
+#define IPW32_SET_IP= API 2 /* "--ip-win32 ipapi" */
+#define IPW32_SET_DHCP_MASQ 3 /* "--ip-win32 = dynamic" */
+#de= fine IPW32_SET_ADAPTIVE 4 /* "--ip-win32 adaptive" */
= +#define IPW32_SET_N 5<= /span>
int ip_win32_type;

= #ifdef _WIN32
@@ -98,14 +100,15 @@
=
int dhcp_options;

- const char *domain; /* DOMAIN (15) */=
+ const char *dom= ain; /* DOMAIN (15) */

const = char *netbios_scope; /* NBS (47) */

- int netbios_node_type; /* NBT 1,2,4,8= (46) */
+ int net= bios_node_type; /* NBT 1,2,4,8 (46) */

-#define N_DHCP_ADDR 4 /* Max = # of addresses allowed for

- * DNS, WINS, etc. */
+#define N_DHCP_ADDR = \
+ 4 /* Max # of= addresses allowed for \
+ * DNS, WINS, etc. */

/* = DNS (6) */
in_addr_t dns[N_DHCP_ADDR];
@@ -147,13 +150,15 @@


#elif defined(TAR= GET_LINUX)

-struct tuntap_options {
+struct tuntap_options
+{
int txqueuelen;
};

#else /* if defined(_WIN32) || defined(TAR= GET_ANDROID) */

-struct tuntap_options {
+struct tuntap_options
+{
int dummy; /* not used */ };

@@ -169,7 +174,8 @@ } afunix_context_t;

#else /* ifn= def WIN32 */
-typedef s= truct {
+typedef stru= ct
+{
int dummy;

} afunix_context_t;
#end= if
@@ -195,11 +201,11 @@
* been set u= p. This does NOT mean ifconfig has been called */
bool= did_ifconfig_ipv6_setup;

- bool persistent_if; /* if existed before,= keep on program end */
+ bool persistent_if; /* if existed before, keep on progra= m end */

struct tuntap_options optio= ns; /* options set on command line */

- char *actual_name; /* actual name of = TUN/TAP dev, usually including unit number */
+ char *actual_name; /* actual name= of TUN/TAP dev, usually including unit number */
<= br> /* ifconfig parameters */
in_addr_t loca= l;
@@ -230,7 +236,7 @@

= int standby_iter;

- #else /* ifdef _WIN32 */
+#else /* ifdef _WIN32 */
i= nt fd; /* file descriptor for TUN/TAP dev */
#endif /* ifd= ef _WIN32 */

@@ -259,13 +265,13 @@=
* Function prototypes
*/

-void open_tun(const char= *dev, const char *dev_type, const char *dev_node,
- struct tuntap *tt, openvpn_net_c= tx_t *ctx);
+void ope= n_tun(const char *dev, const char *dev_type, const char *dev_node, struct t= untap *tt,
+ = openvpn_net_ctx_t *ctx);

void close= _tun(struct tuntap *tt, openvpn_net_ctx_t *ctx);
-void tun_open_device(struct tu= ntap *tt, const char *dev_node,
- const char **device_guid, struct gc_arena *g= c);
+void tun_open_de= vice(struct tuntap *tt, const char *dev_node, const char **device_guid,
+ st= ruct gc_arena *gc);

void close_tun_handl= e(struct tuntap *tt);

@@ -273,37 +279,29 = @@

int read_tun(struct tuntap *tt, uint8= _t *buf, int len);

-void tuncfg(const char *dev, const char *dev_type, const cha= r *dev_node,
- = int persist_mode, const char *username,
- const char *groupname, const struct tuntap= _options *options,
+v= oid tuncfg(const char *dev, const char *dev_type, const char *dev_node, int= persist_mode,
+ = const char *username, const char *groupname, const struct tuntap_opt= ions *options,
openvpn_net_ctx_t *ctx);=

-const char= *guess_tuntap_dev(const char *dev,
- const char *dev_type,
= - con= st char *dev_node,
+c= onst char *guess_tuntap_dev(const char *dev, const char *dev_type, const ch= ar *dev_node,
struct gc_arena= *gc);

- con= st char *dev_type, /* --dev-type option */
- int topology, /* o= ne of the TOP_x values */
- const char *ifconfig_local_parm, /* -= -ifconfig parm 1 */
- = const char *ifconfig_remote_netmask_parm, /* --ifcon= fig parm 2 */
- = const char *ifconfig_ipv6_local_parm, /* --ifconfig pa= rm 1 / IPv6 */
- = int ifconfig_ipv6_netbits_parm, /* --ifconfig p= arm 1 / bits */
- = const char *ifconfig_ipv6_remote_parm, /* --ifconfig = parm 2 / IPv6 */
- = struct addrinfo *local_public,
- struct addrinfo *remote= _public,
- = const bool strict_warn,
- struct env_set *es,
- openvpn_net_ctx_= t *ctx,
+struct tunta= p *init_tun(const char *dev, /* --dev option */
+ = const char *dev_type, /* --dev-type option */<= br>+ int= topology, /* one of the TOP_x values */=
+ co= nst char *ifconfig_local_parm, /* --ifconfig parm 1 */
<= span style=3D"color: hsl(120, 100%, 40%);">+ const c= har *ifconfig_remote_netmask_parm, /* --ifconfig parm 2 */

+ const char *= ifconfig_ipv6_local_parm, /* --ifconfig parm 1 / IPv6 */
+ int ifconf= ig_ipv6_netbits_parm, /* --ifconfig parm 1 / bits */

+ const ch= ar *ifconfig_ipv6_remote_parm, /* --ifconfig parm 2 / IPv6 */

= + struct= addrinfo *local_public, struct addrinfo *remote_public,
+ const bool str= ict_warn, struct env_set *es, openvpn_net_ctx_t *ctx,
= struct tuntap *tt);

-void init_tun_post(struct tuntap *tt,
- cons= t struct frame *frame,
-void do_ifc= onfig_setenv(const struct tuntap *tt,
- struct env_set *es);
+void do_ifconfig_setenv(const stru= ct tuntap *tt, struct env_set *es);


/**<= /span>
* do_ifconfig - configure the tunnel interface
= @@ -314,8 +312,8 @@
* @param es the environm= ent to be used when executing the commands
* @param ctx = the networking API opaque context
*/
-void do_ifconfig(struct tuntap *tt, c= onst char *ifname, int tun_mtu,

- const struct env_set *es, openvpn_net_ctx_t *ctx= );
+void do_ifconfig(= struct tuntap *tt, const char *ifname, int tun_mtu, const struct env_set *e= s,
+ = openvpn_net_ctx_t *ctx);

/**
<= span> * undo_ifconfig - undo configuration of the tunnel interface
<= br>@@ -331,7 +329,8 @@

const char = *dev_type_string(const char *dev, const char *dev_type);
<= /span>
-const char *ifconfig_o= ptions_string(const struct tuntap *tt, bool remote, bool disable, struct gc= _arena *gc);
+const c= har *ifconfig_options_string(const struct tuntap *tt, bool remote, bool dis= able,
+ = struct gc_arena *gc);

bool is_tun_p2p(const struct tuntap *tt);


<= span>@@ -340,8 +339,7 @@

/**
* Return a = string representation of the tun backed driver type
*/
-const char *
<= span style=3D"color: hsl(0, 100%, 40%);">-print_tun_backend_driver(enum tun= _driver_type driver);

+const char *print_tun_backend_driver(enum tun_driver_type driver);=

/*
* Should ifconfig be call= ed before or after
@@ -351,7 +349,7 @@
#de= fine IFCONFIG_BEFORE_TUN_OPEN 0
#define IFCONFIG_AFTER_TUN= _OPEN 1

-#define IFCONFIG_DEFAULT IFCONFIG_AFTER_TUN_OPEN
+#define IFCONFIG_DEFAULT IFCONFIG= _AFTER_TUN_OPEN


static inline int=
ifconfig_order(struct tuntap *tt)
@@ -374,13 +37= 2,13 @@
return IFCONFIG_AFTER_TUN_OPEN;
#elif defined(TARGET_ANDROID)

return IFCONFIG_BEFOR= E_TUN_OPEN;
-#else /* = if defined(TARGET_LINUX) */
+#else /* if defined(TARGET_LINUX) */
return IF= CONFIG_DEFAULT;
#endif
}
=
-#define ROUTE_BEFORE= _TUN 0
-#define ROUTE_A= FTER_TUN 1
+#define R= OUTE_BEFORE_TUN 0
= +#define ROUTE_AFTER_TUN 1
#define ROUTE_ORDER_DEFAULT= ROUTE_AFTER_TUN

static inline int
@@ -441,11 +439,10 @@

bool is= _adapter_up(const struct tuntap *tt, const IP_ADAPTER_INFO *list);
-bool is_ip_i= n_adapter_subnet(const IP_ADAPTER_INFO *ai, const in_addr_t ip, in_addr_t *= highest_netmask);
+bo= ol is_ip_in_adapter_subnet(const IP_ADAPTER_INFO *ai, const in_addr_t ip,
+ = in_addr_t *highest_netmask);

-DWORD adapter_index_of_ip(const IP_ADAPTER= _INFO *list,
- = const in_addr_t ip,
- int *count,
+DWORD adapter_index_of_ip(const IP_ADAPTE= R_INFO *list, const in_addr_t ip, int *count,
= in_addr_t *netmask);

void = show_tap_win_adapters(int msglev, int warnlev);
@@ -599,10 = +596,7 @@
}

static inli= ne void
-tun_set(struct= tuntap *tt,
- s= truct event_set *es,
- = unsigned int rwflags,
- void *arg,
+tun_set(struct tuntap *tt, struct event_set *es, unsigned int rwflags= , void *arg,
unsigned int *persistent)
<= span> {

if (!tuntap_defined(tt) || tuntap_is_dco_win(t= t))
@@ -626,7 +620,6 @@
}
#endif

tt->rwflags_debug =3D rwflags;-
}
=
const char *tun_stat(const struct tuntap *tt, unsi= gned int rwflags, struct gc_arena *gc);
diff --git a/src/op= envpn/tun_afunix.c b/src/openvpn/tun_afunix.c
index ac12070= ..4d48a31 100644
--- a/src/openvpn/tun_afunix.c
<= span>+++ b/src/openvpn/tun_afunix.c

@@ -47,7 +47,6 @@
#include <stdlib.h>


-
stati= c void
tun_afunix_exec_child(const char *dev_node, struct = tuntap *tt, struct env_set *env)
{
@@ -60,= 8 +59,7 @@

argv_printf(&argv, &q= uot;%s", program);

- tt->afunix.childprocess =3D openvpn_execve_check= (&argv, env, S_NOWAITPID,
- msgprefix);
+ tt->afunix.childp= rocess =3D openvpn_execve_check(&argv, env, S_NOWAITPID, msgprefix);
if (!openvpn_waitpid_check(tt->afunix.childprocess, m= sgprefix, M_WARN))
{
tt->a= funix.childprocess =3D 0;
@@ -70,10 +68,7 @@
}


void
-open_tun_afunix(struct options *o,
- int mtu,
- struct tuntap *tt,
- struct = env_set *orig_env)
+o= pen_tun_afunix(struct options *o, int mtu, struct tuntap *tt, struct env_se= t *orig_env)
{
struct gc_arena gc =3D= gc_new();

@@ -81,14 +76,14 @@
= if (!(socketpair(AF_UNIX, SOCK_DGRAM, 0, fds) =3D=3D 0))<= br> {
msg(M_ERR, "Cannot create soc= ket pair for AF_UNIX socket to external "
- "program");
+ "program&quo= t;);
return;
}


/* Ensure that the buffer sizes = are decently sized. Otherwise macOS will
* just have = 2048 */
- struct soc= ket_buffer_size newsizes =3D {65536, 65536 };
+ struct socket_buffer_size newsizes =3D { 6553= 6, 65536 };
socket_set_buffers(fds[0], &newsizes, = false);
socket_set_buffers(fds[1], &newsizes, fals= e);

@@ -167,8 +162,8 @@
= }
#else /* ifndef WIN32 */
void-open_tun_afunix(const char *de= v, const char *dev_type, int mtu,
- struct tuntap *tt, struct env_set env)+open_tun_afunix(const char *= dev, const char *dev_type, int mtu, struct tuntap *tt,
+ struct env_set env)
{
msg(M_ERR, "AF_UNIX socket support= not available on this platform");
}
= diff --git a/src/openvpn/tun_afunix.h b/src/openvpn/tun_afunix.h
= index faca142..3346403 100644
--- a/src/openvpn/tun_a= funix.h
+++ b/src/openvpn/tun_afunix.h
@@ -= 31,31 +31,24 @@
* the user provided taking care of implem= enting the actual tun
* device.
*/
-void
-open_tun_afunix(struct options *o,- int mtu,
- struct tunt= ap *tt,
- = struct env_set *env);
+void open_tun_afunix(struct options *o, int mtu, struct tuntap *tt, str= uct env_set *env);


/**=
* Closes the socket used for the AF_UNIX based device. A= lso sends a
* SIGINT to the child process that was spawne= d to handle the tun device
*/
-void
-close_tun_afunix(struct tuntap *tt);
+void close_tun_afunix(struct tuntap *tt);<= br>
/**
* Writes a packet to a AF= _UNIX based tun device.
*/
-ssize_t
-write_tun_afunix(struct tuntap *tt, uint8_t *buf, int len);=
+ssize_t write_tun_afunix(s= truct tuntap *tt, uint8_t *buf, int len);

/**

* Reads a packet from a AF_UNIX based tun device.
*/
-ss= ize_t
-read_tun_afunix(= struct tuntap *tt, uint8_t *buf, int len);
+ssize_t read_tun_afunix(struct tuntap *tt, uint8_t *= buf, int len);

#endif /* AFUNIX_TUN_H */=

diff --git a/src/openvpn/vlan.c b/src/op= envpn/vlan.c
index 5cc23f4..a6a6e93 100644
= --- a/src/openvpn/vlan.c
+++ b/src/openvpn/vlan.c@@ -52,8 +52,8 @@
static void
vlan= hdr_set_vid(struct openvpn_8021qhdr *hdr, const uint16_t vid)
{

- hdr->pcp_= cfi_vid =3D (hdr->pcp_cfi_vid & ~OPENVPN_8021Q_MASK_VID)
<= span style=3D"color: hsl(0, 100%, 40%);">- | (htons(v= id) & OPENVPN_8021Q_MASK_VID);

+ hdr->pcp_cfi_vid =3D
+ (hdr->pcp_cfi_vid & ~OPENVPN_8021Q_MA= SK_VID) | (htons(vid) & OPENVPN_8021Q_MASK_VID);
}

/*
@@ -96,15 +96,13 @@
/* reject untagged frame */
i= f (c->options.vlan_accept =3D=3D VLAN_ONLY_TAGGED)
= {
- msg(= D_VLAN_DEBUG,
- = "dropping frame without vlan-tag (proto/len 0x%04x)",
+ msg(D_VLAN_= DEBUG, "dropping frame without vlan-tag (proto/len 0x%04x)",
ntohs(ethhdr->proto));
= goto drop;
}

= /* untagged frame is accepted and associated with the global= VID */
- msg(D_= VLAN_DEBUG,
- = "assuming pvid for frame without vlan-tag, pvid: %u (proto/len 0x%04= x)",
+ ms= g(D_VLAN_DEBUG, "assuming pvid for frame without vlan-tag, pvid: %u (p= roto/len 0x%04x)",
c->options.vlan_pvi= d, ntohs(ethhdr->proto));

ret= urn c->options.vlan_pvid;
@@ -125,8 +123,8 @@
= /* VLAN-tagged frame: drop packet */
= if (vid !=3D 0)
{
- msg(D_VLAN_DEBUG, "= dropping frame with vlan-tag, vid: %u (proto/len 0x%04x)",
<= span style=3D"color: hsl(0, 100%, 40%);">- vid, ntohs(vl= anhdr->proto));

+ = msg(D_VLAN_DEBUG, "dropping frame with vlan-tag, vid: %= u (proto/len 0x%04x)", vid,
+ ntohs(vlanhdr->proto));
goto drop;

}

@@ -148,8 +146,7 @@
/* here= we have a proper VLAN tagged frame: perform decapsulation
= * and return embedded VID
*/
- msg(D_VLAN_D= EBUG,
- = "removing vlan-tag from frame: vid: %u, wrapped proto/len: 0x%04x"= ;,
+ msg(D= _VLAN_DEBUG, "removing vlan-tag from frame: vid: %u, wrapped proto/len= : 0x%04x",
vid, ntohs(vlanhdr->pro= to));

/* save inner protocol= to be restored later after decapsulation */
@@ -224,8 +221= ,7 @@
goto drop;
}

- = vlanhdr =3D (struct openvpn_8021qhdr *)buf_prepend(buf,
- = SIZE_ETH_TO_8021Q_HDR);
+ vlanhdr =3D (struct openvpn_8021qhdr *)buf_pr= epend(buf, SIZE_ETH_TO_8021Q_HDR);

= /* Initialise VLAN/802.1q header.
* Move the E= th header so to keep dst/src addresses the same and then
@@= -244,8 +240,8 @@
/* set the VID corresponding to the = current context (client) */
vlanhdr_set_vid(vlanhdr, c= ->options.vlan_pvid);

- msg(D_VLAN_DEBUG, "tagging frame: vid %u (wra= pping proto/len: %04x)",
- c->options.vlan_pvid, vlanhdr->proto);
+ msg(D_VLAN_DEBUG, "taggin= g frame: vid %u (wrapping proto/len: %04x)", c->options.vlan_pvid,<= /span>
+ vlanhdr->= proto);
return;

dro= p:
diff --git a/src/openvpn/vlan.h b/src/openvpn/vlan.h
index 7602585..e2c9c44 100644
--- a/src/openvp= n/vlan.h
+++ b/src/openvpn/vlan.h
@@ -31,13= +31,10 @@
struct multi_context;
struct m= ulti_instance;

-int16_t
-vla= n_decapsulate(const struct context *c, struct buffer *buf);
+int16_t vlan_decapsulate(const stru= ct context *c, struct buffer *buf);


-bool
-vlan_is_tagged(const struct buffer *buf);
+bool vlan_is_tagged(const struct buffe= r *buf);

-void
-vlan_process= _outgoing_tun(struct multi_context *m, struct multi_instance *mi);+void vlan_process_outgoing_t= un(struct multi_context *m, struct multi_instance *mi);

#endif /* VLAN_H */
diff --git a/src/openvp= n/wfp_block.c b/src/openvpn/wfp_block.c
index ce5cef2..506d= 41b 100644
--- a/src/openvpn/wfp_block.c
++= + b/src/openvpn/wfp_block.c
@@ -48,68 +48,33 @@
<= span> #endif


/* c38d57d1-05a7-4c33-904f-= 7fbceee60e82 */
-DEFINE= _GUID(
- FWPM_LAYER_= ALE_AUTH_CONNECT_V4,
- = 0xc38d57d1,
- 0x0= 5a7,
- 0x4c33,
- 0x90, 0x4f, 0x7f, 0xbc,= 0xee, 0xe6, 0x0e, 0x82
- );
+DEFINE_GUID= (FWPM_LAYER_ALE_AUTH_CONNECT_V4, 0xc38d57d1, 0x05a7, 0x4c33, 0x90, 0x4f, 0x= 7f, 0xbc,
+ = 0xee, 0xe6, 0x0e, 0x82);

/* 4a72393b-3= 19f-44bc-84c3-ba54dcb3b6b4 */
-DEFINE_GUID(
- = FWPM_LAYER_ALE_AUTH_CONNECT_V6,
- 0x4a72393b,
- 0x319f,
- = 0x44bc,
- 0x84, 0xc= 3, 0xba, 0x54, 0xdc, 0xb3, 0xb6, 0xb4
- );
+ 0xdc, 0xb3, 0xb6, 0xb4);

= /* d78e1e87-8644-4ea5-9437-d809ecefc971 */
-DEFINE_GUID(
- FWPM_CONDITION_ALE_APP_ID,
- 0xd78e1e87,
- 0x8644,
- 0x4ea5,
- = 0x94, 0x37, 0xd8, 0x09, 0xec, 0xef, 0xc9, 0x71
- );
+DEFINE_GUID(FWPM_CONDITION_ALE_APP_ID, 0xd78e1e87, 0x8644, 0x4e= a5, 0x94, 0x37, 0xd8, 0x09, 0xec,
+ 0xef, 0xc9, 0x71);

/* c35a604d-d22b-4e1a-91b4-68f674ee674b */

-DEFINE_GUID(
- FWPM_CONDITION_IP_REMOTE_PORT,
- 0xc35a604d,
- 0xd22b,
- 0x4e1a,
- 0x91, 0xb4, 0x68, 0xf6, 0x74, 0xee, 0x67, 0x4b
- );
+DEFINE_GUID(FWPM_CONDITION_IP_REMOTE_PORT, 0xc35a604d= , 0xd22b, 0x4e1a, 0x91, 0xb4, 0x68, 0xf6, 0x74,
+ 0xee, 0x67, 0x4b);
=
/* 4cd62a49-59c3-4969-b7f3-bda5d32890a4 */
-DEFINE_GUID(

- FWPM_CONDITION_IP_LOCAL_INTERFACE,
- 0x4cd62a49,
= - 0x59c3,
- 0x4969,
- 0xb7, 0xf3, 0xbd, 0xa5, 0xd3, 0x28, 0x90, 0xa4
- );
+DEFINE_GUID(FWPM_CONDITION_IP_LOCAL_= INTERFACE, 0x4cd62a49, 0x59c3, 0x4969, 0xb7, 0xf3, 0xbd, 0xa5,
+ 0xd3, 0x28, 0x90, 0x= a4);


/* 632ce23b-5167-435c-86d7-e903684a= a80c */
-DEFINE_GUID(
- FWPM_CONDITION_FLAG= S,
- 0x632ce23b,
- 0x5167,
- 0x435c,

- 0x86, 0xd7, 0xe9, 0x03, 0x68, 0x4a, 0xa= 8, 0x0c
- );<= br>+DEFINE_GUID(FWPM_CONDITION_= FLAGS, 0x632ce23b, 0x5167, 0x435c, 0x86, 0xd7, 0xe9, 0x03, 0x68, 0x4a,
+ 0xa8, 0x0c);=

/* UUID of WFP sublayer used by all ins= tances of openvpn
* 2f660d7e-6a37-11e6-a181-001e8c6e04a2 = */
-DEFINE_GUID(=
- OPENVPN_WFP_BLOCK_SUBLAY= ER,
- 0x2f660d7e,
- 0x6a37,
- 0x11e6,

- 0xa1, 0x81, 0x00, 0x1e, 0x8c, 0x6e, 0x0= 4, 0xa2
- );<= br>+DEFINE_GUID(OPENVPN_WFP_BLO= CK_SUBLAYER, 0x2f660d7e, 0x6a37, 0x11e6, 0xa1, 0x81, 0x00, 0x1e, 0x8c,
+ 0x6e, 0x04, = 0xa2);

static WCHAR *FIREWALL_NAME =3D L= "OpenVPN";

@@ -123,7 +88,11 @@<= /span>
}

#define OUT_ON_ERROR(= err, msg) \
- if (er= r) { msg_handler(err, msg); goto out; }
+ if (err) \
+ { \+ msg_handler(err, msg= ); \
+ goto ou= t; \
+ = }

/*
* Add a persist= ent sublayer with specified uuid.
@@ -181,24 +150,21 @@
*/

DWORD
-add_wfp_block_filters(HANDLE *engine_h= andle,
- = int index,
- = const WCHAR *exe_path,
- wfp_block_msg_handler_t msg_handle= r,
- = BOOL dns_only)
+ad= d_wfp_block_filters(HANDLE *engine_handle, int index, const WCHAR *exe_path= ,
+ = wfp_block_msg_handler_t msg_handler, BOOL dns_only)
{<= /span>
- FWPM_SESSION0 sess= ion =3D {0};
+ FWP= M_SESSION0 session =3D { 0 };
FWPM_SUBLAYER0 *sublayer= _ptr =3D NULL;
NET_LUID itf_luid;
= UINT64 filterid;
FWP_BYTE_BLOB *openvpnblob =3D NULL;=
- FWPM_FILTER0 Filt= er =3D {0};
+ FWPM= _FILTER0 Filter =3D { 0 };
FWPM_FILTER_CONDITION0 Cond= ition[2];
- FWPM_FIL= TER_CONDITION0 match_openvpn =3D {0};
- FWPM_FILTER_CONDITION0 match_port_53 =3D {0};- FWPM_FILTER_CONDITION0 matc= h_interface =3D {0};
- = FWPM_FILTER_CONDITION0 match_loopback =3D {0};
- FWPM_FILTER_CONDITION0 match_not_loopback = =3D {0};
+ FWPM_FI= LTER_CONDITION0 match_openvpn =3D { 0 };
+ FWPM_FILTER_CONDITION0 match_port_53 =3D { 0 };
+ FWPM_FILTER_CONDIT= ION0 match_interface =3D { 0 };
+ FWPM_FILTER_CONDITION0 match_loopback =3D { 0 };
= + FWPM_FILTER_CONDITION0 mat= ch_not_loopback =3D { 0 };
DWORD err =3D 0;
=
if (!msg_handler)
@@ -223,8 +1= 89,8 @@
FwpmFreeMemory0((void **)&sublayer_ptr= );
}
else
- { /* Add a new sublayer -- as another = process may add it in the meantime,
- * do not treat "already exists" as an error= */
+ { /* Add a n= ew sublayer -- as another process may add it in the meantime,
+ * do not treat "alrea= dy exists" as an error */

err =3D add_sublaye= r(OPENVPN_WFP_BLOCK_SUBLAYER);

i= f (err =3D=3D FWP_E_ALREADY_EXISTS || err =3D=3D ERROR_SUCCESS)
<= span>@@ -439,8 +405,7 @@

*/

<= span> DWORD

-set_interf= ace_metric(const NET_IFINDEX index, const ADDRESS_FAMILY family,
= - const ULONG= metric)
+set_interfa= ce_metric(const NET_IFINDEX index, const ADDRESS_FAMILY family, const ULONG= metric)
{
DWORD err =3D 0; MIB_IPINTERFACE_ROW ipiface;
diff --git a/src/o= penvpn/wfp_block.h b/src/openvpn/wfp_block.h
index 6de39f5.= .5ca093c 100644
--- a/src/openvpn/wfp_block.h
+++ b/src/openvpn/wfp_block.h

@@ -32,7 +32,7 @@ /* Any value less than 5 should work fine. 3 is chosen without any= real reason. */
#define WFP_BLOCK_IFACE_METRIC 3
-typedef void= (*wfp_block_msg_handler_t) (DWORD err, const char *msg);
+typedef void (*wfp_block_msg_handler_= t)(DWORD err, const char *msg);

DWORD
delete_wfp_block_filters(HANDLE engine);
@@ = -51,8 +51,7 @@
*
* @return positive int= erface metric on success or -1 on error
*/
-int

-get_interface_metric(const NET_IFINDEX index, const AD= DRESS_FAMILY family, int *is_auto);
+int get_interface_metric(const NET_IFINDEX index, const ADD= RESS_FAMILY family, int *is_auto);

/**
* Sets interface metric value for specified interface inde= x.
@@ -65,8 +64,7 @@
*/
=
DWORD
-set_interface_metric(const NET_IFINDEX index, const ADDRESS_FAMILY family= ,
- = const ULONG metric);
+set_interface_metric(const NET_IFINDEX index, const ADDRESS_FAMILY family= , const ULONG metric);

#endif /* ifndef = WFP_BLOCK_H */
#endif /* ifdef _WIN32 */
d= iff --git a/src/openvpn/win32-util.c b/src/openvpn/win32-util.c
<= span>index c23d066..0d6d029 100644

--- a/src/openvpn/win32-= util.c
+++ b/src/openvpn/win32-util.c
@@ -1= 61,7 +161,7 @@
if (WideCharToMultiByte(CP_UTF8, 0, wtm= pdir, -1, NULL, 0, NULL, NULL) > sizeof(tmpdir))
{<= /span>
msg(M_WARN, "Could not get temporary director= y. Path is too long."
- " Consider using --tmp-dir");
+ " Consider = using --tmp-dir");
return NULL;
}


diff --git a/src/openvpn/win32.= c b/src/openvpn/win32.c
index 0524c57..15bcf37 100644
--- a/src/openvpn/win32.c
+++ b/src/openvpn/win3= 2.c
@@ -101,8 +101,7 @@
/**
* Set OpenSSL environment variables to a safe directory

*/

-static void
-set_openssl_env_vars(void)= ;
+static void set_op= enssl_env_vars(void);

void
init_win32(void)

@@ -167,9 +166,7 @@
}=

void
-overlapped_io_init(struct overlapped_io *o,
- const struct fr= ame *frame,

- = BOOL event_state)
+overlapped_io_init(struct overlapped_io *o, const struct frame *fram= e, BOOL event_state)
{
CLEAR(*o);

@@ -219,7 +216,8 @@
*/

void
-init_net_event_win32(struct rw_handle *event, long network_e= vents, socket_descriptor_t sd, unsigned int flags)
+init_net_event_win32(struct rw_handle *event= , long network_events, socket_descriptor_t sd,
+ unsigned int flags)<= br> {
/* manual reset events, initially set to u= nsignaled */

@@ -292,7 +290,8 @@ {
if (!CloseHandle(event->= read))
{
- msg(M_WARN | M_ERRNO, "Warning: CloseH= andle (read) failed in close_net_event_win32");
+ msg(M_WARN | M_ERRNO,
+ &qu= ot;Warning: CloseHandle (read) failed in close_net_event_win32");
}
event->read =3D = NULL;
}
@@ -308,7 +307,8 @@=
{
if (!CloseHandle(event-&g= t;write))
{
- msg(M_WARN | M_ERRNO, "Warning: Clo= seHandle (write) failed in close_net_event_win32");
+ msg(M_WARN | M_ERRNO,<= /span>
+ = "Warning: CloseHandle (write) failed in close_net_event_win32");<= /span>
}
event->write= =3D NULL;
}
@@ -332,7 +332,7 @@
ASSERT(!socket_defined(ne->sd));
= ne->sd =3D sd;
ne->event_mask =3D 0;- init_net_event_win32(&n= e->handle, network_events, sd, NE32_PERSIST_EVENT|NE32_WRITE_EVENT);
+ init_net_event_win3= 2(&ne->handle, network_events, sd, NE32_PERSIST_EVENT | NE32_WRITE_E= VENT);
}

void@@ -406,7 +406,7 @@
ir.Event.KeyEvent.bKeyD= own =3D true;
if (!stdin_handle || !WriteConsoleIn= put(stdin_handle, &ir, 1, &tmp))
{<= br>- msg(M_WARN|M_ERRN= O, "WARN: win_trigger_event: WriteConsoleInput");
+ msg(M_WARN | M_ERRNO, &= quot;WARN: win_trigger_event: WriteConsoleInput");

= }
}
}
@@ -417,7= +417,7 @@
static bool WINAPI
win_ctrl_ha= ndler(DWORD signum)
{
- msg(D_LOW, "win_ctrl_handler: signal received (co= de=3D%lu)", (unsigned long) signum);
+ msg(D_LOW, "win_ctrl_handler: signal receive= d (code=3D%lu)", (unsigned long)signum);

<= span> if (siginfo_static.signal_received =3D=3D SIGTERM)

{

@@ -435,7 +435,7 @@
b= reak;

default:
- msg(D_LOW, "win_ctrl_h= andler: signal (code=3D%lu) not handled", (unsigned long) signum);
+ msg(D_LOW, = "win_ctrl_handler: signal (code=3D%lu) not handled", (unsigned lo= ng)signum);
break;
}
/* pass all other signals to the next handler */@@ -449,9 +449,7 @@
}

<= span> void

-win32_signa= l_open(struct win32_signal *ws,
- int force,
- const char *exit_event_name,
<= span style=3D"color: hsl(120, 100%, 40%);">+win32_signal_open(struct win32_= signal *ws, int force, const char *exit_event_name,

= bool exit_event_initial_state)
{
CLEAR(*ws);

@@ -473,12 +471,10 @@
= if (GetConsoleMode(ws->in.read, &ws->console_mode_sav= e))
{
/* runn= ing on a console */
- = const DWORD new_console_mode =3D ws->console_mode_save
- = & ~(ENABLE_WINDOW_INPUT
- = | ENABLE_PROCESSED_INPUT
- | ENABLE_LINE_INP= UT
- = | ENABLE_ECHO_INPUT
- = | ENABLE_MOUSE_INPUT);
+ const DWORD new_console_mode =3D
+ ws->console_= mode_save

+ = & ~(ENABLE_WINDOW_INPUT | ENABLE_PROCESSED_INPUT | ENABLE_LIN= E_INPUT
+ = | ENABLE_ECHO_INPUT | ENABLE_MOUSE_INPUT);

if (new_console_mode !=3D ws->console_mod= e_save)
{
@@ -501,8 +497,8= @@
* If console open failed, assume we are running
* as a service.
*/
- if ((force =3D=3D WSO_NOFORCE |= | force =3D=3D WSO_FORCE_SERVICE)

- && !HANDLE_DEFINED(ws->in.read) && e= xit_event_name)
+ = if ((force =3D=3D WSO_NOFORCE || force =3D=3D WSO_FORCE_SERVICE) &&= !HANDLE_DEFINED(ws->in.read)
+ && exit_event_name)
{
struct security_attributes sa;
= struct gc_arena gc =3D gc_new();
@@ -513,11 +509,11 @@
msg(M_ERR, "Error: win32_signal_open: init= SA failed");
}

<= span style=3D"color: hsl(0, 100%, 40%);">- ws->in.read =3D Create= EventW(&sa.sa, TRUE, exit_event_initial_state ? TRUE : FALSE,
- = exit_event_nameW);
+ CreateEventW(&sa.sa, TRUE, exit_event_initial_sta= te ? TRUE : FALSE, exit_event_nameW);
if (ws->i= n.read =3D=3D NULL)
{
- msg(M_WARN|M_ERRNO, "NOTE: Create= EventW '%s' failed", exit_event_name);
+ msg(M_WARN | M_ERRNO, "N= OTE: CreateEventW '%s' failed", exit_event_name);
}

else
{
@@ -533,9 +529,9 @@
gc_free(&gc);=
}
/* set the ctrl handler in bot= h console and service modes */
- if (!SetConsoleCtrlHandler((PHANDLER_ROUTINE) win_ctrl_handler= , true))
+ if (!Se= tConsoleCtrlHandler((PHANDLER_ROUTINE)win_ctrl_handler, true))
{

- msg= (M_WARN|M_ERRNO, "WARN: SetConsoleCtrlHandler failed");+ msg(M_WARN | M_ERRNO,= "WARN: SetConsoleCtrlHandler failed");
}
}

@@ -562,8 +558,7 @@
return ir->Event.KeyEvent.wVirtualScanCode;<= br> }

- if ((ir->Event.KeyEvent.dwControlKeyState
- & (LEFT_ALT_PRESSED | R= IGHT_ALT_PRESSED))

+ = if ((ir->Event.KeyEvent.dwControlKeyState & (LEFT_ALT_PRESSED | R= IGHT_ALT_PRESSED))
&& (ir->Event.KeyEve= nt.wVirtualKeyCode !=3D 18))
{
= return ir->Event.KeyEvent.wVirtualScanCode * 256;
@@ -= 625,8 +620,7 @@
{
if (ws->mode =3D= =3D WSO_MODE_SERVICE)
{
- if (HANDLE_DEFINED(ws->in.read)- && WaitForS= ingleObject(ws->in.read, 0) =3D=3D WAIT_OBJECT_0)
+ if (HANDLE_DEFINED(ws->in.read= ) && WaitForSingleObject(ws->in.read, 0) =3D=3D WAIT_OBJECT_0)
{
return true;<= br> }
@@ -683,7 +677,7 @@
{<= /span>
if (ws->mode =3D=3D WSO_MODE_CONSOLE && HAN= DLE_DEFINED(ws->in.read))
{
- msg(M_INFO|M_NOPREFIX, "Press = any key to continue...");
+ msg(M_INFO | M_NOPREFIX, "Press any key to continue= ...");
do
{ WaitForSingleObject(ws->in.read, INFINITE);<= br>@@ -734,7 +728,8 @@
{
= title =3D "";
}
- buf_printf(&out, "[%s] " PACKA= GE_NAME " " PACKAGE_VERSION " F4:EXIT F1:USR1 F2:USR2 F3:HUP= ", title);
+ = buf_printf(&out, "[%s] " PACKAGE_NAME " " PACKAGE_V= ERSION " F4:EXIT F1:USR1 F2:USR2 F3:HUP",
+ title);
= SetConsoleTitle(BSTR(&out));
gc_free(&gc);<= /span>
}
@@ -763,7 +758,7 @@

if (s->hand =3D=3D NULL)
{
- msg(M_WARN|M_ERRNO,= "WARNING: Cannot create Win32 semaphore '%s'", name);
+ msg(M_WARN | M= _ERRNO, "WARNING: Cannot create Win32 semaphore '%s'", na= me);
}
else
= {
@@ -781,9 +776,10 @@
DWORD statu= s;
ASSERT(!s->locked);
=
- dmsg(D_SEMAPHORE_LOW= , "Attempting to lock Win32 semaphore '%s' prior to net shell = command (timeout =3D %d sec)",
- s->name,
- timeout_milliseconds / 1000);
+ dmsg(

+ D_SEMAPHORE_LOW,
+ "Attempting to = lock Win32 semaphore '%s' prior to net shell command (timeout =3D %= d sec)",

+ = s->name, timeout_milliseconds / 1000);
st= atus =3D WaitForSingleObject(s->hand, timeout_milliseconds);
<= span> if (status =3D=3D WAIT_FAILED)

{
@@ -798,8 +794,7 @@
else
{

dmsg(D_SEMAPHORE, "Wait on= Win32 semaphore '%s' timed out after %d milliseconds",=
- s->name,=
- time= out_milliseconds);
+ = s->name, timeout_milliseconds);
= }
}
return ret;
= @@ -814,8 +809,7 @@
dmsg(D_SEMAPHORE, "Releas= ing Win32 semaphore '%s'", s->name);
= if (!ReleaseSemaphore(s->hand, 1, NULL))
{
- msg(M_WARN = | M_ERRNO, "ReleaseSemaphore failed on Win32 semaphore '%s'&qu= ot;,
- s= ->name);
+ = msg(M_WARN | M_ERRNO, "ReleaseSemaphore failed on Win32 semaphore = '%s'", s->name);
}
s->locked =3D false;

}
@@= -906,9 +900,9 @@
nchars +=3D strlen(e->str= ing) + 1;
}

- nchars +=3D strlen(force_path)+1;<= /span>
+ nchars +=3D = strlen(force_path) + 1;

- ret =3D (char *) malloc(nchars);
+ ret =3D (char *)malloc(nch= ars);

check_malloc_return(ret);
<= /span>
p =3D ret;
@@ -919,7 +913,7 @@
strcpy(p, e->string);
= p +=3D strlen(e->string) + 1;
= }
- if (strn= cmp(e->string, "PATH=3D", 5 ) =3D=3D 0)
+ if (strncmp(e->string, &qu= ot;PATH=3D", 5) =3D=3D 0)
{
path_seen =3D true;

}
@@ -928,8 +922,8 @@
/* make sure PATH = is set */
if (!path_seen)
= {
- msg( M_= INFO, "env_block: add %s", force_path );
- strcpy( p, force_path );+ msg(M_INFO, "= ;env_block: add %s", force_path);
+ strcpy(p, force_path);
= p +=3D strlen(force_path) + 1;
}
@@ -975,7 +969,7 @@
{<= br> const char *arg =3D a->argv[i];
= strcpy(work, arg);
-= string_mod(work, CC_PRINT, CC_DOUBLE_QUOTE|CC_CRLF, '_');
+ string_mod(wo= rk, CC_PRINT, CC_DOUBLE_QUOTE | CC_CRLF, '_');
= if (i)
{
buf_pri= ntf(&buf, " ");
@@ -1026,7 +1020,8 @@<= br> start_info.dwFlags =3D STARTF_USESHOWWINDOW; start_info.wShowWindow =3D SW_HIDE;
<= /span>
- if (Create= ProcessW(cmd, cl, NULL, NULL, FALSE, proc_flags, env, NULL, &start_info= , &proc_info))
+ = if (CreateProcessW(cmd, cl, NULL, NULL, FALSE, proc_flags, env, = NULL, &start_info,
- msg(M_WARN|M_ERRNO, &qu= ot;openvpn_execve: GetExitCodeProcess %ls failed", cmd);
+ msg(M_WARN | = M_ERRNO, "openvpn_execve: GetExitCodeProcess %ls failed", cmd);
}
CloseHan= dle(proc_info.hProcess);
}
= else
{
- msg(M_WARN|M_ERRNO, "openvpn_e= xecve: CreateProcess %ls failed", cmd);
+ msg(M_WARN | M_ERRNO, "openvp= n_execve: CreateProcess %ls failed", cmd);
= }
free(env);
gc= _free(&gc);
@@ -1084,7 +1079,8 @@
= status =3D GetModuleFileName(NULL, self_exe, sizeof(self_exe));
<= span> if (status =3D=3D 0 || status =3D=3D sizeof(self_exe))

= {
- m= sg(M_WARN|M_ERRNO, "fork_to_self: CreateProcess failed: cannot get mod= ule name via GetModuleFileName");
+ msg(M_WARN | M_ERRNO,
+ "fork_to_self: CreateProcess = failed: cannot get module name via GetModuleFileName");
goto done;

}

@@ -1101,7 +1097,7 @@

}
else<= /span>
{
= - msg(M_WARN|M_ERRNO, "fork_to_self: CreateProcess failed: %s&q= uot;, cmdline);
+ = msg(M_WARN | M_ERRNO, "fork_to_self: CreateProcess failed: %s"= ;, cmdline);
}

done= :
@@ -1134,7 +1130,8 @@
}
if (status > sizeof(buf) - 1)

{
= - msg(M_FATAL, "Strin= g overflow attempting to read environmental variable %s", SYS_PATH_ENV= _VAR_NAME);
+ = msg(M_FATAL, "String overflow attempting to read environmental variabl= e %s",
+ = SYS_PATH_ENV_VAR_NAME);
}
set= _win_sys_path(buf, es);
}
@@ -1145,7 +1142= ,7 @@
DWORD status =3D GetModuleFileNameW(NULL, path, = size);
if (status =3D=3D 0 || status =3D=3D size)
{
- = msg(M_WARN|M_ERRNO, "cannot get executable path");+ msg(M_WARN | M_ERRNO,= "cannot get executable path");
return f= alse;
}
return true;
@@ -1162,8 +1159,7 @@

}
else<= /span>
{
= - msg(M_WARN, "Error in WFP: %s : %s [status=3D0x%lx]",
- msg, strerro= r_win32(err, &gc), err);
+ msg(M_WARN, "Error in WFP: %s : %s [status=3D0x%lx]&q= uot;, msg, strerror_win32(err, &gc), err);
}

gc_free(&gc);
@@ -117= 6,15 +1172,10 @@
ack_message_t ack;
= struct gc_arena gc =3D gc_new();

- wfp_block_message_t data =3D {- .header =3D {- (add ? msg_add_wfp= _block : msg_del_wfp_block),
- sizeof(wfp_block_message_t),
- 0
- },
- .flags =3D dns_only ? wfp_block_dns : wfp_block_local,
- .iface =3D { .index= =3D index, .name =3D "" }
- };
+ wfp_block_message_t data =3D { .header =3D { (add ? msg_add_wfp_block= : msg_del_wfp_block),
+ = .flags =3D dns_only ? wfp_block_dns : wfp_block_local,<= /span>
+ = .iface =3D { .index =3D index, .name =3D "" } };

if (!send_msg_iservice(pipe, &data,= sizeof(data), &ack, "WFP block"))
{
@@ -1193,9 +1184,10 @@

= if (ack.error_number !=3D NO_ERROR)
{
- msg(M_WARN, "WFP block: %= s block filters using service failed: %s [status=3D0x%x if_index=3D%d]"= ;,
- (add ? = "adding" : "deleting"), strerror_win32(ack.error_number= , &gc),
- = ack.error_number, data.iface.index);
+ msg(M_WARN,
+ "WFP block: %s block filters using serv= ice failed: %s [status=3D0x%x if_index=3D%d]",
+ (add ? "adding" : &= quot;deleting"), strerror_win32(ack.error_number, &gc), ack.error_= number,
+ = data.iface.index);
goto out;
= }

@@ -1226,8 +1218,8 @@
= goto out;
}

- status =3D add_wfp_block_filters(&= amp;m_hEngineHandle, index, openvpnpath,
- win_wfp_msg_handler, = dns_only);
+ statu= s =3D
+ add_wf= p_block_filters(&m_hEngineHandle, index, openvpnpath, win_wfp_msg_handl= er, dns_only);
if (status =3D=3D 0)
= {
int is_auto =3D 0;
@@ -1282,7= +1274,8 @@
return true;
}
=
-typedef enum {=
+typedef enum=
+{
ARC= H_X86,
ARCH_AMD64,
ARCH_ARM64,
@@ -1296,9 +1289,9 @@
*process_arch =3D = ARCH_UNKNOWN;
*host_arch =3D ARCH_NATIVE;

- typedef BOOL= (WINAPI *is_wow64_process2_t)(HANDLE, USHORT *, USHORT *);
- is_wow64_process2_t is_wow64_proc= ess2 =3D (is_wow64_process2_t)

- GetProcAddress(GetModu= leHandle("Kernel32.dll"), "IsWow64Process2");+ typedef BOOL(WINAPI * is_= wow64_process2_t)(HANDLE, USHORT *, USHORT *);
+ is_wow64_process2_t is_wow64_process2 =3D
+ (is_wow64_proc= ess2_t)GetProcAddress(GetModuleHandle("Kernel32.dll"), "IsWo= w64Process2");

USHORT process_m= achine =3D 0;
USHORT native_machine =3D 0;
<= span>@@ -1310,8 +1303,7 @@

if (is_wow64_process2)
{
/* this could be amd64 on arm64= */
- BOOL is_wo= w64 =3D is_wow64_process2(GetCurrentProcess(),
- &pro= cess_machine, &native_machine);
+ BOOL is_wow64 =3D is_wow64_process2(GetCurrentProce= ss(), &process_machine, &native_machine);
= if (is_wow64 && native_machine =3D=3D IMAGE_FILE_MACHINE_ARM64)
{
*host_arch =3D ARCH_AR= M64;
@@ -1323,8 +1315,7 @@
if (is_wow6= 4_process2)
{
/* check if we&= #39;re running on arm64 or amd64 machine */
- BOOL is_wow64 =3D is_wow64_process2(GetCurren= tProcess(),
- = &process_machine, &native_machine);=
+ BOOL is_wow= 64 =3D is_wow64_process2(GetCurrentProcess(), &process_machine, &na= tive_machine);
if (is_wow64)
= {
switch (native_machine)
= @@ -1383,7 +1374,7 @@
}
}
<= span>

-typedef LONG (W= INAPI *RtlGetVersionPtr)(PRTL_OSVERSIONINFOW);
+typedef LONG(WINAPI *RtlGetVersionPtr)(PRTL_OSVE= RSIONINFOW);

const char *
win32_version_string(struct gc_arena *gc)

@@ -1428,18 +1= 419,16 @@
}

bool=
-send_msg_iservice(HANDLE pip= e, const void *data, size_t size,
- ack_message_t *ack, const char *context)
+send_msg_iservice(HANDLE= pipe, const void *data, size_t size, ack_message_t *ack,
+ const char *context= )
{
struct gc_arena gc =3D gc_new();<= /span>
DWORD len;
bool ret =3D true;

- if = (!WriteFile(pipe, data, size, &len, NULL)
- || !ReadFile(pipe, ack, sizeof(*ack), &= len, NULL))
+ if (= !WriteFile(pipe, data, size, &len, NULL) || !ReadFile(pipe, ack, sizeof= (*ack), &len, NULL))
{
- msg(M_WARN, "%s: could not talk to s= ervice: %s [%lu]",
- context ? context : "Unknown",
+ msg(M_WARN, "%s: could not = talk to service: %s [%lu]", context ? context : "Unknown",
strerror_win32(GetLastError(), &gc), GetLas= tError());
ret =3D false;
}
@@ -1487,14 +1476,13 @@
install_pat= h[wcslen(install_path) - 1] =3D L'\0';
}

- stati= c struct {
+ stati= c struct
+ {
WCHAR *name;
WCHAR *value;
- } ossl_env[] =3D {
- {L"OPENSSL_= CONF", L"openssl.cnf"},
- {L"OPENSSL_ENGINES", L"engines"= ;},
- {L"OP= ENSSL_MODULES", L"modules"}
- };
+ } ossl_env[] =3D { { L"OPENSSL_CONF", L"openssl.= cnf" },
+ = { L"OPENSSL_ENGINES", L"engines" },
+ { L&= quot;OPENSSL_MODULES", L"modules" } };

for (size_t i =3D 0; i < SIZE(ossl_env); ++i) {
@@ -1503,7 +1491,7 @@
= _wgetenv_s(&size, NULL, 0, ossl_env[i].name);
= if (size =3D=3D 0)
{
- WCHAR val[MAX_PATH] =3D {0};<= br>+ WCHAR val[MAX_P= ATH] =3D { 0 };
swprintf(val, _countof(val), L= "%ls\\ssl\\%ls", install_path, ossl_env[i].value);
_wputenv_s(ossl_env[i].name, val);

= }
@@ -1524,7 +1512,7 @@
{
if (n > 0)

{
- Sleep(n*1000);
+ Sleep(n * 1000);<= br> }
return;
}=
@@ -1534,9 +1522,8 @@

= while (expire >=3D now)
{
- DWORD status =3D WaitForSingleObjec= t(win32_signal.in.read, (expire-now)*1000);
- if ((status =3D=3D WAIT_OBJECT_0 && w= in32_signal_get(&win32_signal))
- || status =3D=3D WAIT_TIMEOUT)
+ DWORD status =3D WaitForSingle= Object(win32_signal.in.read, (expire - now) * 1000);
+ if ((status =3D=3D WAIT_OBJECT_0 = && win32_signal_get(&win32_signal)) || status =3D=3D WAIT_TIMEO= UT)
{
return;<= br> }
@@ -1547,7 +1534,7 @@
= {
if (expire > now)
{

- = Sleep((expire-now)*1000);
+ Sleep((expire - now) * 1000);
}

return;
= }
@@ -1599,8 +1586,8 @@
}<= br>
/* Check if the plugin path resides within = the plugin/install directory */
- if ((wcslen(normalized_plugin_dir) > 0) && (wcsnic= mp(normalized_plugin_dir,
- plugin_path, w= cslen(normalized_plugin_dir)) =3D=3D 0))
+ if ((wcslen(normalized_plugin_dir) > 0)<= br>+ && (wcsnicm= p(normalized_plugin_dir, plugin_path, wcslen(normalized_plugin_dir)) =3D=3D= 0))
{
return true; }
diff --git a/src/openvpn/win32.h b/src/openvp= n/win32.h
index 34d18c6..dbfa5bc 100644
---= a/src/openvpn/win32.h
+++ b/src/openvpn/win32.h
= @@ -34,12 +34,13 @@
#include "win32-util.h"= ;

/* location of executables */-#define SYS_PATH_ENV_VAR_NAME = "SystemRoot" /* environmental variable name that normally contai= ns the system path */
-= #define NETSH_PATH_SUFFIX "\\system32\\netsh.exe"
<= span style=3D"color: hsl(0, 100%, 40%);">-#define WIN_ROUTE_PATH_SUFFIX &qu= ot;\\system32\\route.exe"

+#define SYS_PATH_ENV_VAR_NAME \
+ "SystemRoot" /* environmental variable= name that normally contains the system path */
+#define NETSH_PATH_SUFFIX "\\system= 32\\netsh.exe"
+= #define WIN_ROUTE_PATH_SUFFIX "\\system32\\route.exe" #define WIN_IPCONFIG_PATH_SUFFIX "\\system32\\ipconfig.exe&qu= ot;
-#define WIN_NET_PA= TH_SUFFIX "\\system32\\net.exe"
-#define WMIC_PATH_SUFFIX "\\system32\\wbem\\wmic.e= xe"
+#define WIN= _NET_PATH_SUFFIX "\\system32\\net.exe"
+#define WMIC_PATH_SUFFIX "\\= system32\\wbem\\wmic.exe"

/*=
* Win32-specific OpenVPN code, targeted at the mingw
= @@ -75,7 +76,8 @@
char old_window_title[256];
};

-struct rw_handle {
+struct rw_handle
+{
HANDLE read;
HANDLE w= rite;
};
@@ -84,8 +86,8 @@
* Event-based notification of incoming TCP connections

= */

-= #define NE32_PERSIST_EVENT (1<<0)
-#define NE32_WRITE_EVENT (1<<1)
+#define NE32_PERSIST_EVENT (1 <<= ; 0)
+#define NE32_WR= ITE_EVENT (1 << 1)

static inline= bool
defined_net_event_win32(const struct rw_handle *even= t)
@@ -93,7 +95,8 @@
return event->= read !=3D NULL;
}

-void init_net_event_win32(struct rw_handle = *event, long network_events, socket_descriptor_t sd, unsigned int flags);
+void init_net_event_w= in32(struct rw_handle *event, long network_events, socket_descriptor_t sd,<= /span>
+ = unsigned int flags);

long reset_ne= t_event_win32(struct rw_handle *event, socket_descriptor_t sd);
<= span>

@@ -149,7 +152,8 @@
/*
* Signal handling

*/
-struct win32_signal {
+struct win32_signal
+{
#define WSO_MODE_UNDEF 0
#define WSO_MODE_SERVICE 1
#define WSO_MODE_C= ONSOLE 2
@@ -169,10 +173,8 @@
#define WSO_= FORCE_SERVICE 1
#define WSO_FORCE_CONSOLE 2

-void win32_signal_= open(struct win32_signal *ws,
- int force, /* set to WSO force parm */
- con= st char *exit_event_name,
- bool exit_event_initial_state);
+void win32_signal_open(struct win32_= signal *ws, int force, /* set to WSO force parm */
+ const char *exit_even= t_name, bool exit_event_initial_state);

= void win32_signal_close(struct win32_signal *ws);
<= br>@@ -198,17 +200,19 @@
* We try to do all Win32 I= /O using overlapped
* (i.e. asynchronous) I/O for a perfo= rmance win.
*/
-struct overlapped_io {
+struct overlapped_io
+{
#define IOSTATE_INITIAL 0=
-#define IOSTATE_QUEUED = 1 /* overlapped I/O has been queued */
-#define IOSTATE_IMMEDIATE_RETURN 2 /* I/O function = returned immediately without queueing */
+#define IOSTATE_QUEUED 1 /* overlapped I/O h= as been queued */
+#d= efine IOSTATE_IMMEDIATE_RETURN 2 /* I/O function returned immediately witho= ut queueing */
int iostate;
OVERL= APPED overlapped;
DWORD size;
DWO= RD flags;
int status;
bool addr_d= efined;
- union {
+ union
+ {

s= truct sockaddr_in addr;
struct sockaddr_in6 addr6;=
};
@@ -217,9 +221,7 @@
struct buffer buf;

};

<= span style=3D"color: hsl(0, 100%, 40%);">-void overlapped_io_init(struct ov= erlapped_io *o,

- = const struct frame *frame,
- BOOL event_state);+void overlapped_io_init(struc= t overlapped_io *o, const struct frame *frame, BOOL event_state);
void overlapped_io_close(struct overlapped_io *o)= ;

@@ -304,14 +306,13 @@
= * and read the result in |ack|. Returns false on communication error.
* The string in |context| is used to prefix error messages.
*/
-bo= ol send_msg_iservice(HANDLE pipe, const void *data, size_t size,
= - ack_messa= ge_t *ack, const char *context);
+bool send_msg_iservice(HANDLE pipe, const void *data, size_t s= ize, ack_message_t *ack,
+ const char *context);
<= br> /*
* Attempt to simulate fork/execve on Windows=
*/
-= int
-openvpn_execve(con= st struct argv *a, const struct env_set *es, const unsigned int flags);
+int openvpn_execve(cons= t struct argv *a, const struct env_set *es, const unsigned int flags);

/* Sleep that can be interrupted by signals = and exit event */
void win32_sleep(const int n);@@ -324,8 +325,7 @@
* @param size Size of `value` = buffer in bytes.
* @return `true` if successful, `false` = otherwise.
*/
-bool
-get_ope= nvpn_reg_value(const WCHAR *key, WCHAR *value, DWORD size);
+bool get_openvpn_reg_value(const WC= HAR *key, WCHAR *value, DWORD size);


/**=
* @brief Checks if a plugin is located in a trusted dire= ctory.
@@ -340,8 +340,7 @@
* @param plugi= n_path Normalized path to the plugin.
* @return \c true i= f the plugin is in a trusted directory and not a UNC path; \c false otherwi= se.
*/
-plugin_in_trus= ted_dir(const WCHAR *plugin_path);
+bool plugin_in_trusted_dir(const WCHAR *plugin_path);=

/**
* Encrypt a region of me= mory using CryptProtectMemory()
@@ -351,8 +350,7 @@<= br> * - len number of bytes to encrypt -- must be a multiple of
* CRYPTPROTECTMEMORY_BLOCK_SIZE =3D 16
*/

-bool-protect_buffer_win32(char *buf= , size_t len);
+bool = protect_buffer_win32(char *buf, size_t len);

/**

* Decrypt a previously encrypted region of memor= y using CryptUnProtectMemory()
@@ -362,8 +360,7 @@ * - len number of bytes to encrypt -- must be a multiple of
* CRYPTPROTECTMEMORY_BLOCK_SIZE =3D 16
*/

-bool-unprotect_buffer_win32(char *bu= f, size_t len);
+bool= unprotect_buffer_win32(char *buf, size_t len);
#endif /* ifndef OPENVPN_WIN32_H */
#endif /* ifde= f _WIN32 */
diff --git a/src/openvpn/xkey_common.h b/src/op= envpn/xkey_common.h
index 111596e..3d65e1f 100644--- a/src/openvpn/xkey_common.h
+++ b/src/openvpn/xk= ey_common.h
@@ -46,12 +46,13 @@
* Struct = to encapsulate signature algorithm parameters to pass
* t= o sign operation.
*/
-typedef struct {
+typedef struct
+{
const char *padmode; /**< "pkcs1&qu= ot;, "pss" or "none" */
- const char *mdname; /**< "SHA256" or= "SHA2-256" etc. */
+ const char *mdname; /**< "SHA256" or "SHA2= -256" etc. */
const char *saltlen; /**< "= digest", "auto" or "max" */
c= onst char *keytype; /**< "EC" or "RSA" */
= - const char *op; /**< = "Sign" or "DigestSign" */
+ const char *op; /**< "Sign"= or "DigestSign" */
} XKEY_SIGALG;

/**
@@ -78,15 +79,14 @@
* before signing. The digest algorithm used (or to be used) is passed = in the sigalg

* structure.
*/-typedef int (XKEY_EXTERNAL_SIGN= _fn)(void *handle, unsigned char *sig, size_t *siglen,
- const = unsigned char *tbs, size_t tbslen,
- XKEY_SIGALG sigalg);
+typedef int(XKEY_EXTERNAL= _SIGN_fn)(void *handle, unsigned char *sig, size_t *siglen,
+ = const unsigned char *tbs, size_t tbslen, XKEY_SIGALG sigalg);

/**

* Signature of private key free function callback= used
* to free the opaque private key handle obtained fr= om the
* backend. Not required for management-external-ke= y.
*/
-typedef void (XKEY_PRIVKEY_FREE_fn)(void *handle);
+typedef void(XKEY_PRIVKEY_FREE_fn)(void *= handle);

/**
* Generat= e an encapsulated EVP_PKEY for management-external-key
@@ -= 115,9 +115,8 @@
* to the required size and false is retur= ned.
*
*/
-bool
-encode_pkcs1(unsigned char *enc, size_t *enc_len, const char *mdname= ,
- const u= nsigned char *tbs, size_t tbslen);
+bool encode_pkcs1(unsigned char *enc, size_t *enc_len, const= char *mdname, const unsigned char *tbs,
+ size_t tbslen);

/**
* Compute message digest
@@ -133,9 +132,8 @@

* On successful return *buflen is = set to the actual size of the result.
* TIP: EVP_MD_MAX_S= IZE should be enough capacity of buf for al algorithms.
*= /
-int
-xkey_digest(const unsigned char *src, = size_t srclen, unsigned char *buf,
- size_t *buflen, const char *mdname);
+int xkey_digest(const unsigned ch= ar *src, size_t srclen, unsigned char *buf, size_t *buflen,

+ const char *mdname)= ;


/**
* Load a generic= external key with custom sign and free ops
@@ -150,9 +148,= 8 @@
* IMPORTANT: a reference to the handle is retained b= y the provider and
* relased by calling free_op. The call= er should not free it.
*/
-EVP_PKEY *
-xkey_load_generic_key(OSSL_LIB_CTX *libctx, void *handle, EVP_PK= EY *pubkey,
- = XKEY_EXTERNAL_SIGN_fn *sign_op, XKEY_PRIVKEY_FREE_fn *free_op);=
+EVP_PKEY *xkey_load= _generic_key(OSSL_LIB_CTX *libctx, void *handle, EVP_PKEY *pubkey,+ = XKEY_EXTERNAL_SIGN_fn *sign_op, XKEY_PRIVKEY_FREE_fn *free_op);<= br>
extern OSSL_LIB_CTX *tls_libctx; /* Global */

@@ -166,7 +163,7 @@
stati= c inline int
xkey_max_saltlen(int modBits, int hLen)
{
- int = emLen =3D (modBits - 1 + 7)/8; /* ceil((modBits - 1)/8) */
+ int emLen =3D (modBits - 1 + 7) = / 8; /* ceil((modBits - 1)/8) */

ret= urn emLen - hLen - 2;
}
@@ -181,8 +178,7 @= @
* @returns the size of the converted signature or <= =3D 0 on error.
* On success, buf is overwritten by its D= ER encoding
*/
-int
-ecdsa_b= in2der(unsigned char *buf, int len, size_t capacity);
+int ecdsa_bin2der(unsigned char *buf, int= len, size_t capacity);

#endif /* HAVE_X= KEY_PROVIDER */

diff --git a/src/openvpn/= xkey_helper.c b/src/openvpn/xkey_helper.c
index 487bfe6..f4= a9948 100644
--- a/src/openvpn/xkey_helper.c
+++ b/src/openvpn/xkey_helper.c

@@ -59,8 +59,8 @@<= br>
/** helper to compute digest */
int

-xkey_digest(cons= t unsigned char *src, size_t srclen, unsigned char *buf,
- size_t *buflen, const char *= mdname)
+xkey_digest(= const unsigned char *src, size_t srclen, unsigned char *buf, size_t *buflen= ,
+ const = char *mdname)
{
dmsg(D_XKEY, "In= xkey_digest");
EVP_MD *md =3D EVP_MD_fetch(NULL,= mdname, NULL); /* from default context */
@@ -70,7 +70,7 @= @
return 0;
}

- unsigned int le= n =3D (unsigned int) *buflen;
+ unsigned int len =3D (unsigned int)*buflen;
= if (EVP_Digest(src, srclen, buf, &len, md, NULL) !=3D 1)
= {
msg(M_WARN, "WARN: xkey_digest: = EVP_Digest failed");
@@ -121,18 +121,17 @@
<= span>

/* UTF8 string pointers in here are only read f= rom, so cast is safe */
OSSL_PARAM params[] =3D {
- {"xkey-origin= ", OSSL_PARAM_UTF8_STRING, (char *) origin, 0, 0},
- {"pubkey", OSSL_PARAM_O= CTET_STRING, &pubkey, sizeof(pubkey), 0},
- {"handle", OSSL_PARAM_OCTET_PTR, = &handle, sizeof(handle), 0},
- {"sign_op", OSSL_PARAM_OCTET_PTR, (void **) &a= mp;sign_op, sizeof(sign_op), 0},
- {"free_op", OSSL_PARAM_OCTET_PTR, (void **) &a= mp;free_op, sizeof(free_op), 0},
- {NULL, 0, NULL, 0, 0}
+ { "xkey-origin", OSSL_PARAM_UTF8_STR= ING, (char *)origin, 0, 0 },
+ { "pubkey", OSSL_PARAM_OCTET_STRING, &pubkey= , sizeof(pubkey), 0 },
+ = { "sign_op", OSSL_PARAM_OCTET_PTR, (void **)&sign_op, sizeo= f(sign_op), 0 },
+ = { "free_op", OSSL_PARAM_OCTET_PTR, (void **)&free_op, si= zeof(free_op), 0 },
+= { NULL, 0, NULL, 0, 0 }
};

/* Do not use EVP_PKEY_new_from_pkey as that will take = keymgmt from pubkey */
EVP_PKEY_CTX *ctx =3D EVP_PKEY_= CTX_new_from_name(libctx, EVP_PKEY_get0_type_name(pubkey), props);- if (!ctx
- || EVP_PKEY_fromdata_init(ctx) = !=3D 1
+ if (!ctx = || EVP_PKEY_fromdata_init(ctx) !=3D 1
|| EVP_PKEY_= fromdata(ctx, &pkey, EVP_PKEY_KEYPAIR, params) !=3D 1)
= {
print_openssl_errors();
@@ = -161,13 +160,12 @@
* @return signature lengt= h or -1 on error.
*/
int
-xkey_management_sign(void *unused, un= signed char *sig, size_t *siglen,

- const unsigned char *tbs, size_t tbslen, X= KEY_SIGALG alg)
+xkey= _management_sign(void *unused, unsigned char *sig, size_t *siglen, const un= signed char *tbs,
+ = size_t tbslen, XKEY_SIGALG alg)
{
- dmsg(D_XKEY, "In x= key_management_sign with keytype =3D %s, op =3D %s",
- alg.keytype, alg.op);+ dmsg(D_XKEY, "In xk= ey_management_sign with keytype =3D %s, op =3D %s", alg.keytype, alg.o= p);

-= (void) unused;
+ = (void)unused;
char alg_str[128];
= unsigned char buf[EVP_MAX_MD_SIZE]; /* for computing digest if required = */
size_t buflen =3D sizeof(buf);
@@ -= 228,8 +226,7 @@
/* For undigested message, add has= halg=3Ddigest parameter */
else
= {
- s= nprintf(alg_str, sizeof(alg_str), "%s,hashalg=3D%s",
- "RSA_PKC= S1_PADDING", alg.mdname);

+ snprintf(alg_str, sizeof(alg_str), "%s,hashalg= =3D%s", "RSA_PKCS1_PADDING", alg.mdname);
= }
}
else if (!strcmp(alg.p= admode, "none") && (flags & MF_EXTERNAL_KEY_NOPADDING= )
@@ -239,13 +236,12 @@
}
else if (!strcmp(alg.padmode, "pss") && (flags &= amp; MF_EXTERNAL_KEY_PSSPAD))

{
- snprintf(alg_str, sizeof(alg_str), = "%s,hashalg=3D%s,saltlen=3D%s",
- "RSA_PKCS1_PSS_PADDING", alg= .mdname, alg.saltlen);
+ alg.mdname, alg.saltlen);
}
else
{<= br>- msg(M_NONFATAL, "= ;RSA padding mode not supported by management-client <%s>",
- alg.padmode);<= /span>
+ msg(M_NONFAT= AL, "RSA padding mode not supported by management-client <%s>&qu= ot;, alg.padmode);
return 0;
= }

@@ -260,7 +256,7 @@
= char *out_b64 =3D NULL;
int len =3D -1;

- int bencret = =3D openvpn_base64_encode(tbs, (int) tbslen, &in_b64);
+ int bencret =3D openvpn_base64_e= ncode(tbs, (int)tbslen, &in_b64);

= if (management && bencret > 0)
{@@ -268,7 +264,7 @@
}
if = (out_b64)
{
- len =3D openvpn_base64_decode(out_b64, sig, (int) *sigle= n);
+ len =3D = openvpn_base64_decode(out_b64, sig, (int)*siglen);
}
free(in_b64);
free(out_b64);
@@ -295,8 +291,8 @@
* to the required size and= false is returned.
*/
bool
-encode_pkcs1(unsigned char *enc, s= ize_t *enc_len, const char *mdname,

- const unsigned char *tbs, size_t tbslen)<= br>+encode_pkcs1(unsigned char = *enc, size_t *enc_len, const char *mdname, const unsigned char *tbs,=
+ size_t tbslen= )
{
ASSERT(enc_len !=3D NULL);=
ASSERT(tbs !=3D NULL);
@@ -309,32 +305,34 @@=
* Also see the table in RFC 8017 section 9.2, Note 1= .
*/

- const unsigned char sha1[] =3D {0x30, 0x21, 0x30= , 0x09, 0x06, 0x05, 0x2b,
- 0x0e, 0x03, 0x02, 0x1a, 0x05, 0x00, 0= x04, 0x14};
- const = unsigned char sha256[] =3D {0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86,= 0x48,
- = 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x05, 0x00, 0x04, = 0x20};
- const unsig= ned char sha384[] =3D {0x30, 0x41, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48= ,
- = 0x01, 0x65, 0x03, 0x04, 0x02, 0x02, 0x05, 0x00, 0x04, 0x30}= ;
- const unsigned c= har sha512[] =3D {0x30, 0x51, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48,
- = 0x01, 0x65, 0x03, 0x04, 0x02, 0x03, 0x05, 0x00, 0x04, 0x40};
- const unsigned char s= ha224[] =3D {0x30, 0x2d, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48,- = 0x01, 0x65, 0x03, 0x04, 0x02, 0x04, 0x05, 0x00, 0x04, 0x1c};- const unsigned char sha512= _224[] =3D {0x30, 0x2d, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48,- = 0x01, 0x65, 0x03, 0x04, 0x02, 0x05, 0x05, 0x00, 0x04, 0x1c};
- const unsigned char sha= 512_256[] =3D {0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48,=
- = 0x01, 0x65, 0x03, 0x04, 0x02, 0x06, 0x05, 0x00, 0x04, 0x20};
+ const unsigned cha= r sha1[] =3D { 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e,
+ = 0x03, 0x02, 0x1a, 0x05, 0x00, 0x04, 0x14 };

+ const unsigned char sha256[] =3D { 0x30, 0x3= 1, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01,
+ 0x65, 0= x03, 0x04, 0x02, 0x01, 0x05, 0x00, 0x04, 0x20 };
+ const unsigned char sha384[] =3D { 0x30, 0= x41, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01,
+ 0x65= , 0x03, 0x04, 0x02, 0x02, 0x05, 0x00, 0x04, 0x30 };
+ const unsigned char sha512[] =3D { 0x= 30, 0x51, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01,
+ = 0x65, 0x03, 0x04, 0x02, 0x03, 0x05, 0x00, 0x04, 0x40 };
+ const unsigned char sha224[] =3D { = 0x30, 0x2d, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01,
+ = 0x65, 0x03, 0x04, 0x02, 0x04, 0x05, 0x00, 0x04, 0x1c };

+ const unsigned char sha512_224[] = =3D { 0x30, 0x2d, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01,+ = 0x65, 0x03, 0x04, 0x02, 0x05, 0x05, 0x00, 0x04, 0x1c };<= br>+ const unsigned char sha= 512_256[] =3D { 0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01,=
+ = 0x65, 0x03, 0x04, 0x02, 0x06, 0x05, 0x00, 0x04, 0x20 = };

- = typedef struct {
+= typedef struct
+ = {
const int nid;
const= unsigned char *header;
size_t sz;
} DIG_INFO;


-#define MAKE_DI(x) {NID_ ## x, x, sizeof(x)}
+#define MAKE_DI(x) { NID_##x, x, siz= eof(x) }

- DIG_INFO dinfo[] =3D {MAKE_DI(sha1), MAKE_DI(sha256), MAKE_DI(sha3= 84),
- = MAKE_DI(sha512), MAKE_DI(sha224), MAKE_DI(sha512_224),
- MAKE_DI(sha= 512_256), {0, NULL, 0}};

+ DIG_INFO dinfo[] =3D {
+ MAKE_DI(sha1), MAKE_DI(sha256), MAKE_DI(sha384), = MAKE_DI(sha512),
= + MAKE_DI(sha224), MAKE_DI(sha512_224), MAKE_DI(sha512_256), { 0, NU= LL, 0 }
+ };

size_t out_len =3D 0;
= bool ret =3D false;
@@ -387,8 +385,7 @@
= /* combine header and digest */
memcpy(enc= , di->header, di->sz);
memcpy(enc + di->s= z, tbs, tbslen);
- = dmsg(D_XKEY, "encode_pkcs1: digest length =3D %zu encoded length = =3D %zu",
- = tbslen, out_len);
+ dmsg(D_XKEY, "encode_pkcs1: digest length =3D %zu encoded = length =3D %zu", tbslen, out_len);
ret =3D tr= ue;
}

@@ -408,9 +405= ,9 @@
ecdsa_bin2der(unsigned char *buf, int len, size_t ca= pacity)
{
ECDSA_SIG *ecsig =3D NULL;<= /span>
- int rlen =3D len/2= ;
+ int rlen =3D l= en / 2;
BIGNUM *r =3D BN_bin2bn(buf, rlen, NULL);
- BIGNUM *s =3D BN_bin2b= n(buf+rlen, rlen, NULL);
+ BIGNUM *s =3D BN_bin2bn(buf + rlen, rlen, NULL);
= if (!r || !s)
{
goto err;=
@@ -427,7 +424,7 @@
}

int derlen =3D i2d_ECDSA_SIG(ecsig, NULL);- if (derlen > (int) capa= city)
+ if (derlen= > (int)capacity)
{
ECDSA_= SIG_free(ecsig);
msg(M_NONFATAL, "Error: DER = encoded ECDSA signature is too long (%d)\n", derlen);
= diff --git a/src/openvpn/xkey_provider.c b/src/openvpn/xkey_provider.c
index edd64d3..1819ab0 100644
--- a/src/openvpn= /xkey_provider.c
+++ b/src/openvpn/xkey_provider.c@@ -46,15 +46,16 @@

typedef stru= ct
{
-= OSSL_LIB_CTX *libctx; /**< a child libctx for our own use */=
+ OSSL_LIB_CTX *libctx; = /**< a child libctx for our own use */
} XKEY_PROVIDER_= CTX;

/* helper to print debug messages *= /
-#define xkey_dmsg(f,= ...) \
- do { = \
- dmsg(f|M_NOLF, "xkey_provider:= In %s: ", __func__); \
- dmsg(f|M_NOPREFIX, __VA_ARGS__); \
- } while(0)+#define xkey_dmsg(f, ...) = \
+ do = \
+ { = \
+ dmsg(f | M_NOLF, "xkey_provider: = In %s: ", __func__); \
+ dmsg(f | M_NOPREFIX, __VA_ARGS__); \
+ } while (0)<= br>
typedef enum
{
@@ -93,7 +94,7 @@

/** keydata handle free function of= backend */
XKEY_PRIVKEY_FREE_fn *free;
XKEY_PROVIDER_CTX *prov;

- int refcount; /**< reference count */
+ int refcount; /**<= reference count */
} XKEY_KEYDATA;

static inline const char *
@@ -128,9 +129,8 @@=
* Helper sign function for native keys
= * Implemented using OpenSSL calls.
*/
-int
-xkey_native_sign(XKEY_KEYDATA *key, unsigned char *sig, si= ze_t *siglen,
- = const unsigned char *tbs, size_t tbslen, XKEY_SIGALG sigalg);
+int xkey_native_sign(XKE= Y_KEYDATA *key, unsigned char *sig, size_t *siglen,
+ const unsigned char = *tbs, size_t tbslen, XKEY_SIGALG sigalg);


/* keymgmt provider */
@@ -150,8 +150,7= @@
static OSSL_FUNC_keymgmt_query_operation_name_fn rsa_k= eymgmt_name;
static OSSL_FUNC_keymgmt_query_operation_name= _fn ec_keymgmt_name;

-static int
-keymgmt_import_helper(XKEY_KEYDATA *key, const OSSL_PARAM params[]);<= /span>
+static int keymgmt_i= mport_helper(XKEY_KEYDATA *key, const OSSL_PARAM params[]);

static XKEY_KEYDATA *
keydata_new(void= )
@@ -273,9 +272,8 @@
int selection_pu= b =3D selection & ~OSSL_KEYMGMT_SELECT_PRIVATE_KEY;

EVP_PKEY_CTX *ctx =3D EVP_PKEY_CTX_new_from_name(key-&g= t;prov->libctx, name, NULL);
- if (!ctx
= - || (EVP_PKEY_fromdata_init(ctx) !=3D 1)
- || (EVP_PKEY_fromdata(ctx, &pkey, se= lection_pub, (OSSL_PARAM *) params) !=3D1))
+ if (!ctx || (EVP_PKEY_fromdata_init(ctx) !=3D 1= )
+ || (EVP_PK= EY_fromdata(ctx, &pkey, selection_pub, (OSSL_PARAM *)params) !=3D 1))
{
msg(M_WARN, "Error: key= mgmt_import failed for key type <%s>", name);
= if (pkey)
@@ -295,10 +293,10 @@
= {
/* create private key */
= pkey =3D NULL;
- = if (EVP_PKEY_fromdata(ctx, &pkey, selection, (OSSL_PARAM *) params)= =3D=3D 1)
+ i= f (EVP_PKEY_fromdata(ctx, &pkey, selection, (OSSL_PARAM *)params) =3D= =3D 1)
{
key->hand= le =3D pkey;
- = key->free =3D (XKEY_PRIVKEY_FREE_fn *) EVP_PKEY_free;
+ key->free =3D (XKEY_= PRIVKEY_FREE_fn *)EVP_PKEY_free;

}
}

EVP_PKEY_CTX_free(ctx);
@@ -41= 9,12 +417,10 @@
{
xkey_dmsg(D_XKEY, &= quot;entry");

- static OSSL_PARAM gettable[] =3D {
- OSSL_PARAM_int(OSSL_PKEY_PARAM_BITS= , NULL),
- OSSL_= PARAM_int(OSSL_PKEY_PARAM_SECURITY_BITS, NULL),
- OSSL_PARAM_int(OSSL_PKEY_PARAM_MAX_SIZE, = NULL),
- OSSL_PA= RAM_END
- };<= br>+ static OSSL_PARAM getta= ble[] =3D { OSSL_PARAM_int(OSSL_PKEY_PARAM_BITS, NULL),
+ OS= SL_PARAM_int(OSSL_PKEY_PARAM_SECURITY_BITS, NULL),
+ OSSL_PA= RAM_int(OSSL_PKEY_PARAM_MAX_SIZE, NULL),
+ OSSL_PARAM_END };=
return gettable;
}
=
@@ -471,14 +467,14 @@
/* only check p= arams we understand and ignore the rest */

p =3D OSSL_PARAM_locate_const(params, "pubkey"); /*setting= pubkey on our keydata */

- if (p && p->data_type =3D=3D OSSL_PARAM_OCTET_STRING
- && p->= data_size =3D=3D sizeof(pkey))
+ if (p && p->data_type =3D=3D OSSL_PARAM_OCTET_STR= ING && p->data_size =3D=3D sizeof(pkey))
{<= /span>
pkey =3D *(EVP_PKEY **)p->data;
ASSERT(pkey);


int id = =3D EVP_PKEY_get_id(pkey);
- if (id !=3D EVP_PKEY_RSA && id !=3D EVP_PKEY_EC &&= amp; id !=3D EVP_PKEY_ED25519 && id !=3D EVP_PKEY_ED448)
= + if (id !=3D EVP_PKEY_R= SA && id !=3D EVP_PKEY_EC && id !=3D EVP_PKEY_ED25519
+ && id= !=3D EVP_PKEY_ED448)
{
= msg(M_WARN, "Error: xkey keymgmt_import: unknown key type (%d)"= ;, id);
return 0;
@@ -493,8 +4= 89,7 @@
}

p =3D= OSSL_PARAM_locate_const(params, "handle"); /*setting privkey */<= /span>
- if (p && p= ->data_type =3D=3D OSSL_PARAM_OCTET_PTR
- && p->data_size =3D=3D sizeof(key-&= gt;handle))
+ if (= p && p->data_type =3D=3D OSSL_PARAM_OCTET_PTR && p->d= ata_size =3D=3D sizeof(key->handle))
{
key->handle =3D *(void **)p->data;

= /* caller should keep the reference alive until we call free */<= br>@@ -502,8 +497,7 @@
}

p =3D OSSL_PARAM_locate_const(params, "sign_op");= /*setting sign_op */
-= if (p && p->data_type =3D=3D OSSL_PARAM_OCTET_PTR
= - && p->data_si= ze =3D=3D sizeof(key->sign))
+ if (p && p->data_type =3D=3D OSSL_PARAM_OCTET_PT= R && p->data_size =3D=3D sizeof(key->sign))
= {
key->sign =3D *(void **)p->data;
ASSERT(key->sign); /* fix your params array */
@@ -511,8 +505,7 @@

/* op= tional parameters */
p =3D OSSL_PARAM_locate_const(par= ams, "free_op"); /*setting free_op */
- if (p && p->data_type =3D=3D OSSL_= PARAM_OCTET_PTR
- = && p->data_size =3D=3D sizeof(key->free))
+ if (p && p->data_type = =3D=3D OSSL_PARAM_OCTET_PTR && p->data_size =3D=3D sizeof(key-&g= t;free))
{
key->free =3D *= (void **)p->data;
}
@@ -586,75 +579= ,80 @@
}

static const O= SSL_DISPATCH rsa_keymgmt_functions[] =3D {
- {OSSL_FUNC_KEYMGMT_NEW, (void (*)(void))keymgmt_ne= w},
- {OSSL_FUNC_KEY= MGMT_FREE, (void (*)(void))keymgmt_free},
- {OSSL_FUNC_KEYMGMT_LOAD, (void (*)(void))keymgmt_lo= ad},
- {OSSL_FUNC_KE= YMGMT_HAS, (void (*)(void))keymgmt_has},
- {OSSL_FUNC_KEYMGMT_MATCH, (void (*)(void))keymgmt_ma= tch},
- {OSSL_FUNC_K= EYMGMT_IMPORT, (void (*)(void))rsa_keymgmt_import},
- {OSSL_FUNC_KEYMGMT_IMPORT_TYPES, (void = (*)(void))keymgmt_import_types},
- {OSSL_FUNC_KEYMGMT_GETTABLE_PARAMS, (void (*)(void))keymgmt_= gettable_params},
- = {OSSL_FUNC_KEYMGMT_GET_PARAMS, (void (*)(void))keymgmt_get_params},<= br>- {OSSL_FUNC_KEYMGMT_SET_PA= RAMS, (void (*)(void))keymgmt_set_params},
- {OSSL_FUNC_KEYMGMT_SETTABLE_PARAMS, (void (*)(void= ))keymgmt_gettable_params}, /* same as gettable */
- {OSSL_FUNC_KEYMGMT_QUERY_OPERATION_NAME= , (void (*)(void))rsa_keymgmt_name},
- {0, NULL }
+ { OSSL_FUNC_KEYMGMT_NEW, (void (*)(void))keymgmt_new },
+ { OSSL_FUNC_KEYMGMT_F= REE, (void (*)(void))keymgmt_free },
+ { OSSL_FUNC_KEYMGMT_LOAD, (void (*)(void))keymgmt_load= },
+ { OSSL_FUNC_= KEYMGMT_HAS, (void (*)(void))keymgmt_has },
+ { OSSL_FUNC_KEYMGMT_MATCH, (void (*)(void))keym= gmt_match },
+ { O= SSL_FUNC_KEYMGMT_IMPORT, (void (*)(void))rsa_keymgmt_import },
+ { OSSL_FUNC_KEYMGMT_IMPORT_T= YPES, (void (*)(void))keymgmt_import_types },

+ { OSSL_FUNC_KEYMGMT_GETTABLE_PARAMS, (void (*= )(void))keymgmt_gettable_params },
+ { OSSL_FUNC_KEYMGMT_GET_PARAMS, (void (*)(void))keymgmt_= get_params },
+ { = OSSL_FUNC_KEYMGMT_SET_PARAMS, (void (*)(void))keymgmt_set_params },<= br>+ { OSSL_FUNC_KEYMGMT_SET= TABLE_PARAMS,
+ = (void (*)(void))keymgmt_gettable_params }, /* same as gettable */+ { OSSL_FUNC_KEYMGMT_QUERY= _OPERATION_NAME, (void (*)(void))rsa_keymgmt_name },
+ { 0, NULL }
};

static const OSSL_DISPATCH ec_keymgmt_functio= ns[] =3D {
- {OSSL_F= UNC_KEYMGMT_NEW, (void (*)(void))keymgmt_new},
- {OSSL_FUNC_KEYMGMT_FREE, (void (*)(void))keymg= mt_free},
- {OSSL_FU= NC_KEYMGMT_LOAD, (void (*)(void))keymgmt_load},
- {OSSL_FUNC_KEYMGMT_HAS, (void (*)(void))keymg= mt_has},
- {OSSL_FUN= C_KEYMGMT_MATCH, (void (*)(void))keymgmt_match},
- {OSSL_FUNC_KEYMGMT_IMPORT, (void (*)(void))e= c_keymgmt_import},
- = {OSSL_FUNC_KEYMGMT_IMPORT_TYPES, (void (*)(void))keymgmt_import_types},
- {OSSL_FUNC_KEYMGMT_G= ETTABLE_PARAMS, (void (*)(void))keymgmt_gettable_params},
- {OSSL_FUNC_KEYMGMT_GET_PARAMS, (voi= d (*)(void))keymgmt_get_params},
- {OSSL_FUNC_KEYMGMT_SET_PARAMS, (void (*)(void))keymgmt_set_p= arams},
- {OSSL_FUNC= _KEYMGMT_SETTABLE_PARAMS, (void (*)(void))keymgmt_gettable_params}, /* sa= me as gettable */
- = {OSSL_FUNC_KEYMGMT_QUERY_OPERATION_NAME, (void (*)(void))ec_keymgmt_name},<= /span>
- {0, NULL }<= br>+ { OSSL_FUNC_KEYMGMT_NEW= , (void (*)(void))keymgmt_new },
+ { OSSL_FUNC_KEYMGMT_FREE, (void (*)(void))keymgmt_free },<= /span>
+ { OSSL_FUNC_KEYM= GMT_LOAD, (void (*)(void))keymgmt_load },
+ { OSSL_FUNC_KEYMGMT_HAS, (void (*)(void))keymgmt_= has },
+ { OSSL_FU= NC_KEYMGMT_MATCH, (void (*)(void))keymgmt_match },
+ { OSSL_FUNC_KEYMGMT_IMPORT, (void (*)(vo= id))ec_keymgmt_import },
+ { OSSL_FUNC_KEYMGMT_IMPORT_TYPES, (void (*)(void))keymgmt_import_t= ypes },
+ { OSSL_F= UNC_KEYMGMT_GETTABLE_PARAMS, (void (*)(void))keymgmt_gettable_params },
+ { OSSL_FUNC_KEYMGMT= _GET_PARAMS, (void (*)(void))keymgmt_get_params },
+ { OSSL_FUNC_KEYMGMT_SET_PARAMS, (void (*= )(void))keymgmt_set_params },
+ { OSSL_FUNC_KEYMGMT_SETTABLE_PARAMS,
+ (void (*)(void))keymgmt_gettable_param= s }, /* same as gettable */
+ { OSSL_FUNC_KEYMGMT_QUERY_OPERATION_NAME, (void (*)(void))ec_ke= ymgmt_name },
+ { = 0, NULL }
};

static con= st OSSL_DISPATCH ed448_keymgmt_functions[] =3D {
- {OSSL_FUNC_KEYMGMT_NEW, (void (*)(void))keym= gmt_new},
- {OSSL_FU= NC_KEYMGMT_FREE, (void (*)(void))keymgmt_free},
- {OSSL_FUNC_KEYMGMT_LOAD, (void (*)(void))keym= gmt_load},
- {OSSL_F= UNC_KEYMGMT_HAS, (void (*)(void))keymgmt_has},
- {OSSL_FUNC_KEYMGMT_MATCH, (void (*)(void))keym= gmt_match},
- {OSSL_= FUNC_KEYMGMT_IMPORT, (void (*)(void))ed448_keymgmt_import},
- {OSSL_FUNC_KEYMGMT_IMPORT_TYPES, = (void (*)(void))keymgmt_import_types},

- {OSSL_FUNC_KEYMGMT_GETTABLE_PARAMS, (void (*)(void))ke= ymgmt_gettable_params},
- {OSSL_FUNC_KEYMGMT_GET_PARAMS, (void (*)(void))keymgmt_get_params},
- {OSSL_FUNC_KEYMGMT_= SET_PARAMS, (void (*)(void))keymgmt_set_params},
- {OSSL_FUNC_KEYMGMT_SETTABLE_PARAMS, (void (*= )(void))keymgmt_gettable_params}, /* same as gettable */
- {0, NULL }

+ { OSSL_FUNC_KEYMGMT_NEW, (void (*)(= void))keymgmt_new },
= + { OSSL_FUNC_KEYMGMT_FREE, (void (*)(void))keymgmt_free },
+ { OSSL_FUNC_KEYMGMT_LOAD, (v= oid (*)(void))keymgmt_load },

+ { OSSL_FUNC_KEYMGMT_HAS, (void (*)(void))keymgmt_has },
+ { OSSL_FUNC_KEYMGMT_M= ATCH, (void (*)(void))keymgmt_match },
+ { OSSL_FUNC_KEYMGMT_IMPORT, (void (*)(void))ed448_ke= ymgmt_import },
+ = { OSSL_FUNC_KEYMGMT_IMPORT_TYPES, (void (*)(void))keymgmt_import_types },
+ { OSSL_FUNC_KEYMG= MT_GETTABLE_PARAMS, (void (*)(void))keymgmt_gettable_params },
+ { OSSL_FUNC_KEYMGMT_GET_PARA= MS, (void (*)(void))keymgmt_get_params },

+ { OSSL_FUNC_KEYMGMT_SET_PARAMS, (void (*)(void))k= eymgmt_set_params },
= + { OSSL_FUNC_KEYMGMT_SETTABLE_PARAMS,
+ (void (*)(void))keymgmt_gettable_params }, /* s= ame as gettable */
+ = { 0, NULL }
};

stati= c const OSSL_DISPATCH ed25519_keymgmt_functions[] =3D {
- {OSSL_FUNC_KEYMGMT_NEW, (void (*)(voi= d))keymgmt_new},
- {= OSSL_FUNC_KEYMGMT_FREE, (void (*)(void))keymgmt_free},
- {OSSL_FUNC_KEYMGMT_LOAD, (void (*)(voi= d))keymgmt_load},
- = {OSSL_FUNC_KEYMGMT_HAS, (void (*)(void))keymgmt_has},
- {OSSL_FUNC_KEYMGMT_MATCH, (void (*)(voi= d))keymgmt_match},
- = {OSSL_FUNC_KEYMGMT_IMPORT, (void (*)(void))ed25519_keymgmt_import},=
- {OSSL_FUNC_KEYMGMT_IMPOR= T_TYPES, (void (*)(void))keymgmt_import_types},
- {OSSL_FUNC_KEYMGMT_GETTABLE_PARAMS, (void (*)= (void))keymgmt_gettable_params},
- {OSSL_FUNC_KEYMGMT_GET_PARAMS, (void (*)(void))keymgmt_get_p= arams},
- {OSSL_FUNC= _KEYMGMT_SET_PARAMS, (void (*)(void))keymgmt_set_params},
- {OSSL_FUNC_KEYMGMT_SETTABLE_PARAMS,= (void (*)(void))keymgmt_gettable_params}, /* same as gettable */
- {0, NULL }
= + { OSSL_FUNC_KEYMGMT_NEW, (= void (*)(void))keymgmt_new },
+ { OSSL_FUNC_KEYMGMT_FREE, (void (*)(void))keymgmt_free },
+ { OSSL_FUNC_KEYMGMT= _LOAD, (void (*)(void))keymgmt_load },
+ { OSSL_FUNC_KEYMGMT_HAS, (void (*)(void))keymgmt_has= },
+ { OSSL_FUNC_= KEYMGMT_MATCH, (void (*)(void))keymgmt_match },
+ { OSSL_FUNC_KEYMGMT_IMPORT, (void (*)(void)= )ed25519_keymgmt_import },
+ { OSSL_FUNC_KEYMGMT_IMPORT_TYPES, (void (*)(void))keymgmt_import= _types },
+ { OSSL= _FUNC_KEYMGMT_GETTABLE_PARAMS, (void (*)(void))keymgmt_gettable_params },
+ { OSSL_FUNC_KEYMG= MT_GET_PARAMS, (void (*)(void))keymgmt_get_params },
+ { OSSL_FUNC_KEYMGMT_SET_PARAMS, (void= (*)(void))keymgmt_set_params },
+ { OSSL_FUNC_KEYMGMT_SETTABLE_PARAMS,
+ (void (*)(void))keymgmt_gettable_pa= rams }, /* same as gettable */
+ { 0, NULL }
};

=
const OSSL_ALGORITHM keymgmts[] =3D {
- {"RSA:rsaEncryption"= , XKEY_PROV_PROPS, rsa_keymgmt_functions, "OpenVPN xkey RSA Key Manage= r"},

- {"R= SA-PSS:RSASSA-PSS", XKEY_PROV_PROPS, rsa_keymgmt_functions, "Open= VPN xkey RSA-PSS Key Manager"},
- {"EC:id-ecPublicKey", XKEY_PROV_PROPS, ec_keym= gmt_functions, "OpenVPN xkey EC Key Manager"},
- {"ED448", XKEY_PROV_PROPS,= ed448_keymgmt_functions, "OpenVPN xkey ED448 Key Manager"},
- {"ED25519", = XKEY_PROV_PROPS, ed25519_keymgmt_functions, "OpenVPN xkey ED25519 Key = Manager"},
- {N= ULL, NULL, NULL, NULL}
+ { "RSA-PSS:RSASSA-PSS", XKEY_PRO= V_PROPS, rsa_keymgmt_functions,
+ "OpenVPN xkey RSA-PSS Key Manager" },+ { "EC:id-ecPublicKey= ", XKEY_PROV_PROPS, ec_keymgmt_functions, "OpenVPN xkey EC Key Ma= nager" },
+ {= "ED448", XKEY_PROV_PROPS, ed448_keymgmt_functions, "OpenVPN= xkey ED448 Key Manager" },
+ { "ED25519", XKEY_PROV_PROPS, ed25519_keymgmt_fu= nctions, "OpenVPN xkey ED25519 Key Manager" },
+ { NULL, NULL, NULL, NULL }<= br> };


@@ -681,29= +679,39 @@
XKEY_SIGALG sigalg;
} XKE= Y_SIGNATURE_CTX;

-static const XKEY_SIGALG default_sigalg =3D { .mdname =3D &quo= t;MD5-SHA1", .saltlen =3D "digest",
- .p= admode =3D "pkcs1", .keytype =3D "RSA"};
+static const XKEY_SIGALG default_s= igalg =3D {

+ .mdn= ame =3D "MD5-SHA1", .saltlen =3D "digest", .padmode =3D= "pkcs1", .keytype =3D "RSA"
+};

-const struct {
+const struct
+{
int nid;
const = char *name;
-} digest_n= ames[] =3D {{NID_md5_sha1, "MD5-SHA1"}, {NID_sha1, "SHA1&quo= t;},
- = {NID_sha224, "SHA224", }, {NID_sha256, "SHA256"}, {N= ID_sha384, "SHA384"},
- {NID_sha512, "SHA512"}, {0, NULL}};=
+} digest_names[] = =3D { { NID_md5_sha1, "MD5-SHA1" },
+ { NID_sha1, "SHA1"= },
+ = {
+ = NID_sha224,
+ "SHA224",
+ },
+ { NID_sha256, "= SHA256" },
+ = { NID_sha384, "SHA384" },
+ { NID_sha512, "= SHA512" },
+ = { 0, NULL } };
/* Use of NIDs as opposed = to EVP_MD_fetch is okay here
* as these are only used for= converting names passed in
* by OpenSSL to const strings= .
*/

-static struct {
+static struct
+{
int id;
const char *na= me;
-} padmode_names[] = =3D {{RSA_PKCS1_PADDING, "pkcs1"},
- {RSA_PKCS1_PSS_PADDING, "p= ss"},
- = {RSA_NO_PADDING, "none"},
- {0, NULL}};
+} padmode_names[] =3D { { RSA_PKCS1_PA= DDING, "pkcs1" },
+ { RSA_PKCS1_PSS_PADDING, "pss" },
+ = { RSA_NO_PADDING, "none" },
+ { 0, NULL } };

-static const char *salt= len_names[] =3D {"digest", "max", "auto", NUL= L};
+static const cha= r *saltlen_names[] =3D { "digest", "max", "auto&qu= ot;, NULL };

/* Return a string literal = for digest name - normalizes
* alternate names like SHA2-= 256 to SHA256 etc.
@@ -724,7 +732,7 @@
= {
i++;
}
- return digest_names[i].name ? digest= _names[i].name : "MD5-SHA1";
+ return digest_names[i].name ? digest_names[i].name := "MD5-SHA1";
}

static void *

@@ -732,7 +740,7 @@
{
xkey_dmsg(D_XKEY, "entry");

- (void) propq; /* unu= sed */
+ (void)pro= pq; /* unused */

XKEY_SIGNATURE_CTX = *sctx =3D OPENSSL_zalloc(sizeof(*sctx));
if (!sctx)
@@ -767,8 +775,7 @@
static OSSL_PARAM se= ttable[] =3D {
OSSL_PARAM_utf8_string(OSSL_SIGNATU= RE_PARAM_PAD_MODE, NULL, 0),
OSSL_PARAM_utf8_strin= g(OSSL_SIGNATURE_PARAM_DIGEST, NULL, 0),
- OSSL_PARAM_utf8_string(OSSL_SIGNATURE_PARAM_PSS_= SALTLEN, NULL, 0),
- = OSSL_PARAM_END
+= OSSL_PARAM_utf8_string(OSSL_SIGNATURE_PARAM_PSS_SALTLEN, NULL, 0), = OSSL_PARAM_END
};

= return settable;
@@ -784,7 +791,7 @@

if (params =3D=3D NULL)
{- return 1; /* not an e= rror */
+ retu= rn 1; /* not an error */
}
p =3D = OSSL_PARAM_locate_const(params, OSSL_SIGNATURE_PARAM_PAD_MODE);
<= span> if (p && p->data_type =3D=3D OSSL_PARAM_UTF8_STRING)
@@ -800,8 +807,7 @@
}
if (sctx->sigalg.padmode =3D=3D NULL)

= {
- msg(M= _WARN, "xkey signature_ctx: padmode <%s>, treating as <none&g= t;",
- = (char *)p->data);
+ msg(M_WARN, "xkey signature_ctx: padmode <%s>, = treating as <none>", (char *)p->data);
= sctx->sigalg.padmode =3D "none";
= }
xkey_dmsg(D_XKEY, "setting padmode as %s= ", sctx->sigalg.padmode);
@@ -834,7 +840,7 @@
}

p =3D OSSL_PARAM_l= ocate_const(params, OSSL_SIGNATURE_PARAM_DIGEST);
- if (p && p->data_type =3D=3D O= SSL_PARAM_UTF8_STRING)
- msg(M_WARN, "xkey_signatu= re_params: unknown saltlen <%s>",
- (char *)p->data);
+ msg(M_WARN, "xkey_= signature_params: unknown saltlen <%s>", (char *)p->data);
sctx->sigalg.saltlen =3D "digest"; = /* most common */
}
xkey_= dmsg(D_XKEY, "setting saltlen to %s", sctx->sigalg.saltlen);
@@ -924,7 +929,8 @@
else if (sign)
{
ret =3D sign(sctx->keydata-&= gt;handle, sig, siglen, tbs, tbslen, sctx->sigalg);
- xkey_dmsg(D_XKEY, "xkey_provi= der: external sign op returned ret =3D %d siglen =3D %d", ret, (int) *= siglen);
+ xke= y_dmsg(D_XKEY, "xkey_provider: external sign op returned ret =3D %d si= glen =3D %d", ret,
+ (int)*siglen);
}
else

{
@@ -979,8 +985,7 @@

}

static int
-signature_digest_sign_init(void *ctx,= const char *mdname,

- = void *provkey, const OSSL_PARAM params[])<= br>+signature_digest_sign_init(= void *ctx, const char *mdname, void *provkey, const OSSL_PARAM params[])
{
xkey_dmsg(D_XKEY, "mdname =3D &l= t;%s>", mdname);

@@ -1022,8 +1027= ,8 @@
}

static int
-signature_digest_sign(void= *ctx, unsigned char *sig, size_t *siglen,
- size_t sigsize, const unsigned c= har *tbs, size_t tbslen)
+signature_digest_sign(void *ctx, unsigned char *sig, size_t *siglen, s= ize_t sigsize,
+ = const unsigned char *tbs, size_t tbslen)
= {
xkey_dmsg(D_XKEY, "entry");

@@ -1072,8 +1077,8 @@
/* Sign digest u= sing native sign function -- will only work for native keys
*/

int
-xkey_native_sign(XKEY_KEYDATA *key, unsigned char *sig, size_t *siglen= ,
- con= st unsigned char *tbs, size_t tbslen, XKEY_SIGALG sigalg)
+xkey_native_sign(XKEY_KEYDATA *key, u= nsigned char *sig, size_t *siglen, const unsigned char *tbs,
+ size_t tbslen, XK= EY_SIGALG sigalg)

{
xkey_dmsg(D_XKEY,= "entry");

@@ -1100,13 +1105,17= @@
OSSL_PARAM params[6];
if (EVP= _PKEY_get_id(pkey) =3D=3D EVP_PKEY_RSA)
{
- params[i++] =3D OSSL_PARAM= _construct_utf8_string(OSSL_SIGNATURE_PARAM_DIGEST, (char *)mdname, 0);
- params[i++] =3D O= SSL_PARAM_construct_utf8_string(OSSL_SIGNATURE_PARAM_PAD_MODE, (char *)padm= ode, 0);
+ par= ams[i++] =3D
+ = OSSL_PARAM_construct_utf8_string(OSSL_SIGNATURE_PARAM_DIGEST, (char *)= mdname, 0);
+ = params[i++] =3D
+ = OSSL_PARAM_construct_utf8_string(OSSL_SIGNATURE_PARAM_PAD_MODE, (ch= ar *)padmode, 0);
if (!strcmp(sigalg.padmode, &quo= t;pss"))
{
- params[i++] =3D OSSL_PARAM_construct_utf8_st= ring(OSSL_SIGNATURE_PARAM_PSS_SALTLEN, (char *) saltlen, 0);
+ params[i++] =3D OSSL_P= ARAM_construct_utf8_string(OSSL_SIGNATURE_PARAM_PSS_SALTLEN,

+ = (char *)saltlen, 0);

= /* same digest for mgf1 */
- params[i++] =3D OSSL_PARAM_construct_utf8_string(OSSL_SIGN= ATURE_PARAM_MGF1_DIGEST, (char *) mdname, 0);
+ params[i++] =3D OSSL_PARAM_construct_= utf8_string(OSSL_SIGNATURE_PARAM_MGF1_DIGEST,
+ = (char *)mdname, 0);
}
= }
params[i++] =3D OSSL_PARAM_construct_end();
@@ -1133,27 +1142,27 @@
}

static const OSSL_DISPATCH signature_functions[] =3D {=
- {OSSL_FUNC_SIGNATURE_NEW= CTX, (void (*)(void))signature_newctx},
- {OSSL_FUNC_SIGNATURE_FREECTX, (void (*)(void))signatu= re_freectx},
- {OSSL= _FUNC_SIGNATURE_SIGN_INIT, (void (*)(void))signature_sign_init},
= - {OSSL_FUNC_SIGNATURE_SIGN, (= void (*)(void))signature_sign},
- {OSSL_FUNC_SIGNATURE_DIGEST_VERIFY_INIT, (void (*)(void))sign= ature_digest_verify_init},
- {OSSL_FUNC_SIGNATURE_DIGEST_VERIFY, (void (*)(void))signature_dige= st_verify},
- {OSSL_= FUNC_SIGNATURE_DIGEST_SIGN_INIT, (void (*)(void))signature_digest_sign_init= },
- {OSSL_FUNC_SIGN= ATURE_DIGEST_SIGN, (void (*)(void))signature_digest_sign},
- {OSSL_FUNC_SIGNATURE_SET_CTX_PARAM= S, (void (*)(void))signature_set_ctx_params},
- {OSSL_FUNC_SIGNATURE_SETTABLE_CTX_PARAMS, (void= (*)(void))signature_settable_ctx_params},
- {OSSL_FUNC_SIGNATURE_GET_CTX_PARAMS, (void (*)(voi= d))signature_get_ctx_params},
- {OSSL_FUNC_SIGNATURE_GETTABLE_CTX_PARAMS, (void (*)(void))signa= ture_gettable_ctx_params},
- {0, NULL }
+= { OSSL_FUNC_SIGNATURE_NEWCTX, (void (*)(void))signature_newctx },
+ { OSSL_FUNC_SIGNATURE= _FREECTX, (void (*)(void))signature_freectx },
+ { OSSL_FUNC_SIGNATURE_SIGN_INIT, (void (*)(v= oid))signature_sign_init },
+ { OSSL_FUNC_SIGNATURE_SIGN, (void (*)(void))signature_sign },
+ { OSSL_FUNC_SIGNA= TURE_DIGEST_VERIFY_INIT, (void (*)(void))signature_digest_verify_init },
+ { OSSL_FUNC_SIGNAT= URE_DIGEST_VERIFY, (void (*)(void))signature_digest_verify },
+ { OSSL_FUNC_SIGNATURE_DIGEST_= SIGN_INIT, (void (*)(void))signature_digest_sign_init },

+ { OSSL_FUNC_SIGNATURE_DIGEST_SIGN,= (void (*)(void))signature_digest_sign },
+ { OSSL_FUNC_SIGNATURE_SET_CTX_PARAMS, (void (*)(v= oid))signature_set_ctx_params },
+ { OSSL_FUNC_SIGNATURE_SETTABLE_CTX_PARAMS, (void (*)(void)= )signature_settable_ctx_params },
+ { OSSL_FUNC_SIGNATURE_GET_CTX_PARAMS, (void (*)(void))sig= nature_get_ctx_params },
+ { OSSL_FUNC_SIGNATURE_GETTABLE_CTX_PARAMS, (void (*)(void))signatu= re_gettable_ctx_params },
+ { 0, NULL }
};

const OSSL_ALGORITHM signatures[] =3D {

- {"RSA:rsaEncryption", XKEY_PROV_PROPS, si= gnature_functions, "OpenVPN xkey RSA Signature"},
- {"ECDSA", XKEY_PROV_PRO= PS, signature_functions, "OpenVPN xkey ECDSA Signature"},
<= br>- {"ED448", XKEY_= PROV_PROPS, signature_functions, "OpenVPN xkey Ed448 Signature"},=
- {"ED25519&qu= ot;, XKEY_PROV_PROPS, signature_functions, "OpenVPN xkey Ed25519 Signa= ture"},
- {NULL= , NULL, NULL, NULL}
+= { "RSA:rsaEncryption", XKEY_PROV_PROPS, signature_functions, = "OpenVPN xkey RSA Signature" },
+ { "ECDSA", XKEY_PROV_PROPS, signature_f= unctions, "OpenVPN xkey ECDSA Signature" },
+ { "ED448", XKEY_PROV_PROPS,= signature_functions, "OpenVPN xkey Ed448 Signature" },+ { "ED25519", XK= EY_PROV_PROPS, signature_functions, "OpenVPN xkey Ed25519 Signature&qu= ot; },
+ { NULL, N= ULL, NULL, NULL }
};

/*= main provider interface */
@@ -1192,8 +1201,7 @@ xkey_dmsg(D_XKEY, "entry");
<= br> static const OSSL_PARAM param_types[] =3D {
- OSSL_PARAM_DEFN(OSSL_PROV_PARAM= _NAME, OSSL_PARAM_UTF8_PTR, NULL, 0),
- OSSL_PARAM_END
+ OSSL_PARAM_DEFN(OSSL_PROV_PARAM_NAME, OSSL_PARAM= _UTF8_PTR, NULL, 0), OSSL_PARAM_END
};

return param_types;
@@ -1228,11 +12= 36,11 @@
}

static const= OSSL_DISPATCH dispatch_table[] =3D {
- {OSSL_FUNC_PROVIDER_GETTABLE_PARAMS, (void (*)(void))ge= ttable_params},
- {O= SSL_FUNC_PROVIDER_GET_PARAMS, (void (*)(void))get_params},
- {OSSL_FUNC_PROVIDER_QUERY_OPERATIO= N, (void (*)(void))query_operation},
- {OSSL_FUNC_PROVIDER_TEARDOWN, (void (*)(void))teardown},=
- {0, NULL}<= br>+ { OSSL_FUNC_PROVIDER_GE= TTABLE_PARAMS, (void (*)(void))gettable_params },
+ { OSSL_FUNC_PROVIDER_GET_PARAMS, (void (*= )(void))get_params },
+ { OSSL_FUNC_PROVIDER_QUERY_OPERATION, (void (*)(void))query_operation= },
+ { OSSL_FUNC_= PROVIDER_TEARDOWN, (void (*)(void))teardown },
+ { 0, NULL }
};

int
diff --git a/src/openvpnmsica/dl= lmain.c b/src/openvpnmsica/dllmain.c
index 7121c02..e7d4a4b= 100644
--- a/src/openvpnmsica/dllmain.c
++= + b/src/openvpnmsica/dllmain.c
@@ -41,10 +41,7 @@ * DLL entry point
*/
BOOL WINAP= I
-DllMain(
<= span style=3D"color: hsl(0, 100%, 40%);">- _In_ HINSTANCE hinstDLL,
- _In_ DWORD dwReason,
- _In_ LPVOID lpReser= ved)
+DllMain(_In_ HI= NSTANCE hinstDLL, _In_ DWORD dwReason, _In_ LPVOID lpReserved)
{

UNREFERENCED_PARAMETER(hinstDLL);
UNREFERENCED_PARAMETER(lpReserved);

@@ -58,12 +55,1= 3 @@
{
return= FALSE;
}
- /* Fall through. */
+ /* Fall through. */
<= /span>
case DLL_THREAD_ATTACH:
{=
/* Create thread local storage data. */
- struct openvpnm= sica_thread_data *s =3D (struct openvpnmsica_thread_data *)calloc(1, sizeof= (struct openvpnmsica_thread_data));
+ struct openvpnmsica_thread_data *s =3D (struct = openvpnmsica_thread_data *)calloc(
+ 1, sizeof(struct openvpnmsica_thread_data));=
if (s =3D=3D NULL)
= {
return FALSE;
@@ -107= ,7 +105,8 @@
/* Secure last error before it is overrid= den. */
DWORD dwResult =3D (flags & M_ERRNO) !=3D = 0 ? GetLastError() : ERROR_SUCCESS;

- struct openvpnmsica_thread_data *s =3D = (struct openvpnmsica_thread_data *)TlsGetValue(openvpnmsica_thread_data_idx= );
+ struct openvp= nmsica_thread_data *s =3D
+ (struct openvpnmsica_thread_data *)TlsGetValue(openvpnmsica_t= hread_data_idx);
if (s->hInstall =3D=3D 0) {
/* No MSI session, no fun. */
@@ -160,16 +159,13 @@

= /* Field 4: The Windows error description. */
LPW= STR szErrMessage =3D NULL;
- if (FormatMessage(
- FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOC= ATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS,
- 0,
- dwResult,
- 0,
- (LPWSTR)&szErrMessage,
- 0,

- NULL) && szEr= rMessage)

+ if= (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER=
+ = | FORMAT_MESSAGE_IGNORE_INSERTS,
+ 0, dwResult, 0, (LPWSTR)&= amp;szErrMessage, 0, NULL)
+ && szErrMessage)
{
- /* Trim traili= ng whitespace. Set terminator after the last non-whitespace character. This= prevents excessive trailing line breaks. */
+ /* Trim trailing whitespace. Set termi= nator after the last non-whitespace character.
+ * This prevents excessive trailing = line breaks. */
for (size_t i =3D 0, i_last = =3D 0;; i++)
{
= if (szErrMessage[i])
@@ -190,6 +186,7 @@
= }
}

- MsiProcessMessage(s->hInstall, (flag= s & M_WARN) ? INSTALLMESSAGE_INFO : INSTALLMESSAGE_ERROR, hRecordProg);=
+ MsiProcessMessa= ge(s->hInstall, (flags & M_WARN) ? INSTALLMESSAGE_INFO : INSTALLMESS= AGE_ERROR,
+ = hRecordProg);
MsiCloseHandle(hRecordProg)= ;
}
diff --git a/src/openvpnmsica/msica_ar= g.c b/src/openvpnmsica/msica_arg.c
index 46bef2b..d750fb0 1= 00644
--- a/src/openvpnmsica/msica_arg.c
++= + b/src/openvpnmsica/msica_arg.c
@@ -51,15 +51,14 @@=


void
-msica_arg_seq_add_head(
- _Inout_ struct msica_arg_seq *seq,
- _In_z_ LPCWSTR argum= ent)
+msica_arg_seq_a= dd_head(_Inout_ struct msica_arg_seq *seq, _In_z_ LPCWSTR argument)<= br> {
size_t argument_size =3D (wcslen(argument)= + 1) * sizeof(WCHAR);
struct msica_arg *p =3D malloc(= sizeof(struct msica_arg) + argument_size);
if (p =3D= =3D NULL)
{
- msg(M_FATAL, "%s: malloc(%u) failed", __FUNCTI= ON__, sizeof(struct msica_arg) + argument_size);
+ msg(M_FATAL, "%s: malloc(%u) fail= ed", __FUNCTION__,
+ sizeof(struct msica_arg) + argument_size);
= }
memcpy(p->val, argument, argument_size);
p->next =3D seq->head;
@@ -72,15 +7= 1,14 @@


void-msica_arg_seq_add_tail(<= br>- _Inout_ struct msica_arg_= seq *seq,
- _Inout_ = LPCWSTR argument)
+ms= ica_arg_seq_add_tail(_Inout_ struct msica_arg_seq *seq, _Inout_ LPCWSTR arg= ument)
{
size_t argument_size =3D (wc= slen(argument) + 1) * sizeof(WCHAR);
struct msica_arg = *p =3D malloc(sizeof(struct msica_arg) + argument_size);
= if (p =3D=3D NULL)
{
- msg(M_FATAL, "%s: malloc(%u) failed&quo= t;, __FUNCTION__, sizeof(struct msica_arg) + argument_size);
+ msg(M_FATAL, "%s: mal= loc(%u) failed", __FUNCTION__,

+ sizeof(struct msica_arg) + argument_size);
}
memcpy(p->val, argument, argumen= t_size);
p->next =3D NULL;
@@ -110,= 10 +108,13 @@

#ifdef _MSC_VER
= #pragma warning(push)
-#pragma warning(disable: 4996) /* Using unsafe string functions: The= space in s and termination of p->val has been implicitly verified at th= e beginning of this function. */
+#pragma warning( = \
+ disable : 4996) /* Using unsafe string functions: Th= e space in s and termination of p->val has \
+ been implicitly verified= at the beginning of this function. */
#endif

- /* Dummy arg= v[0] (i.e. executable name), for CommandLineToArgvW to work correctly when = parsing this string. */
+ /* Dummy argv[0] (i.e. executable name), for CommandLineToArgvW to = work correctly when parsing
+ * this string. */
wcscpy(str, L"x&qu= ot;);

/* Join. */
di= ff --git a/src/openvpnmsica/msica_arg.h b/src/openvpnmsica/msica_arg.h
index c8f7595..858fdb6 100644
--- a/src/openvpn= msica/msica_arg.h
+++ b/src/openvpnmsica/msica_arg.h=
@@ -27,7 +27,7 @@

#ifdef _MSC_= VER
#pragma warning(push)
-#pragma warning(disable: 4200) /* Using zero-sized arr= ays in struct/union. */
+#pragma warning(disable : 4200) /* Using zero-sized arrays in struct/un= ion. */
#endif

<= br>@@ -56,8 +56,7 @@
*
* @param s= eq Pointer to uninitialized argument sequence
*= /
-void
-msica_arg_seq_init(_Inout_ struct msi= ca_arg_seq *seq);

+vo= id msica_arg_seq_init(_Inout_ struct msica_arg_seq *seq);
=

/**
@@ -65,8 +64,7 @@
*
* @param seq Pointer to the = argument sequence
*/
-void
-= msica_arg_seq_free(_Inout_ struct msica_arg_seq *seq);
+void msica_arg_seq_free(_Inout_ struct m= sica_arg_seq *seq);


/*= *
@@ -76,10 +74,7 @@
*
= * @param argument Zero-terminated argument string to insert. */
-void
-msica_arg_seq_add_head(
- _Inout_ struct msica_= arg_seq *seq,
- _In_= z_ LPCWSTR argument);
+void msica_arg_seq_add_head(_Inout_ struct msica_arg_seq *seq, _In_z_ LPC= WSTR argument);


/**
@@ -89,10 +84,7 @@
*
* @p= aram argument Zero-terminated argument string to append.
*/

-void-msica_arg_seq_add_tail(<= br>- _Inout_ struct msica_arg_= seq *seq,
- _Inout_ = LPCWSTR argument);
+v= oid msica_arg_seq_add_tail(_Inout_ struct msica_arg_seq *seq, _Inout_ LPCWS= TR argument);

/**
* Jo= in arguments of the argument sequence into a space delimited string<= br>diff --git a/src/openvpnmsica/msiex.c b/src/openvpnmsica/msiex.c
index 3529e9a..12dc0db 100644
--- a/src/open= vpnmsica/msiex.c
+++ b/src/openvpnmsica/msiex.c
<= span>@@ -34,10 +34,7 @@



UINT

-msi_get_string(=
- _In_ MSIHANDLE hI= nstall,
- _In_z_ LPC= WSTR szName,
- _Out_= LPWSTR *pszValue)
+m= si_get_string(_In_ MSIHANDLE hInstall, _In_z_ LPCWSTR szName, _Out_ LPWSTR = *pszValue)
{
if (pszValue =3D=3D NULL= )
{
@@ -84,7 +81,8 @@
= }
else
{
- SetLastError(uiResult); /* MSDN d= oes not mention MsiGetProperty() to set GetLastError(). But we do have an e= rror code. Set last error manually. */
+ SetLastError(uiResult); /* MSDN does not mention= MsiGetProperty() to set GetLastError(). But
+ we do have an e= rror code. Set last error manually. */
msg(M_NONFA= TAL | M_ERRNO, "%s: MsiGetProperty failed", __FUNCTION__);=
return uiResult;
}
= @@ -92,10 +90,7 @@


UIN= T
-msi_get_record_strin= g(
- _In_ MSIHANDLE = hRecord,
- _In_ unsi= gned int iField,
- _= Out_ LPWSTR *pszValue)
- SetLastError(uiRes= ult); /* MSDN does not mention MsiRecordGetString() to set GetLastError(). = But we do have an error code. Set last error manually. */
+ SetLastError(uiResult); /* MS= DN does not mention MsiRecordGetString() to set GetLastError().
<= span style=3D"color: hsl(120, 100%, 40%);">+ = But we do have an error code. Set last error manually. */

msg(M_NONFATAL | M_ERRNO, "%s: MsiRecordGetString failed&q= uot;, __FUNCTION__);

return uiResult;
}

@@ -150,10 +146,7 @@

UINT
-msi_format_record(
- _In_ MSIHANDLE hInstall,
- _In_ MSIHANDLE hRecord,
- _Out_ LPWSTR *pszValue)
+msi_format_record(_In_ MSIHANDLE hInstall, _In_ = MSIHANDLE hRecord, _Out_ LPWSTR *pszValue)
{
if (pszValue =3D=3D NULL)

{
@@= -200,7 +193,8 @@
}
else {
- = SetLastError(uiResult); /* MSDN does not mention MsiFormatRecord() to set = GetLastError(). But we do have an error code. Set last error manually. */
+ SetLastError(= uiResult); /* MSDN does not mention MsiFormatRecord() to set GetLastError()= .
+ = But we do have an error code. Set last error manually. */<= /span>
msg(M_NONFATAL | M_ERRNO, "%s: MsiFormatRecor= d failed", __FUNCTION__);
return uiResult;
}
@@ -208,11 +202,8 @@
=

UINT
-msi_format_field(
- _In_ MSIHANDLE hInstall,
- _In_ MSIHANDLE hRecord,
- _In_ unsigned int iField,
- _Out_ LPWSTR *pszValue)
<= span style=3D"color: hsl(120, 100%, 40%);">+msi_format_field(_In_ MSIHANDLE= hInstall, _In_ MSIHANDLE hRecord, _In_ unsigned int iField,

+ _Out_ LPWSTR *psz= Value)

{
if (pszValue =3D=3D NULL)
{
@@ -246,7 +237,8 @@
= uiResult =3D MsiRecordSetString(hRecordEx, 0, szValue);
= if (uiResult !=3D ERROR_SUCCESS)
{
- SetLastError(uiResult); /* M= SDN does not mention MsiRecordSetString() to set GetLastError(). But we do = have an error code. Set last error manually. */

+ SetLastError(uiResult); /* MSDN does no= t mention MsiRecordSetString() to set GetLastError().
+ But we= do have an error code. Set last error manually. */
= msg(M_NONFATAL | M_ERRNO, "%s: MsiRecordSetString failed", __FU= NCTION__);
goto cleanup_hRecordEx;
}

diff --git a/src/openvpnmsica/msiex.h b/src/openvpn= msica/msiex.h
index d9afeb5..60c26b5 100644
--- a/src/openvpnmsica/msiex.h

+++ b/src/openvpnmsica/msie= x.h
@@ -37,11 +37,7 @@
*
= * @return ERROR_SUCCESS on success; Win32 error code otherwise
= */
-UINT=
-msi_get_string(
- _In_ MSIHANDLE hInstall,
- _In_z_ LPCWSTR szName,<= /span>
- _Out_ LPWSTR *pszV= alue);
+UINT msi_get_= string(_In_ MSIHANDLE hInstall, _In_z_ LPCWSTR szName, _Out_ LPWSTR *pszVal= ue);


/**
@@ -56,11 +52,8 @@

*
* @return ERROR= _SUCCESS on success; Win32 error code otherwise
*/=
-UINT
-msi_get_record_string(
- _In_ MSIHANDLE hRecord,
- _In_ unsigned int iField,
=
- _Out_ LPWSTR *pszValue);=
+UINT msi_get_record= _string(_In_ MSIHANDLE hRecord, _In_ unsigned int iField,
+ _Out_ LPWS= TR *pszValue);


/**
@@ -78,11 +71,7 @@
*
* @re= turn ERROR_SUCCESS on success; Win32 error code otherwise
= */
-UINT
-msi_format_record(

- _In_ MSIHANDLE hInstall,- _In_ MSIHANDLE hRecord,
- _Out_ LPWSTR *pszValu= e);
+UINT msi_format_= record(_In_ MSIHANDLE hInstall, _In_ MSIHANDLE hRecord, _Out_ LPWSTR *pszVa= lue);


/**
@@ -101,11 +90,7 @@

*
* @return ERR= OR_SUCCESS on success; Win32 error code otherwise
*/
-UINT
-msi_format_field(
- _In_ MSIHANDLE hInstall,
- _In_ MSIHANDLE hRecord,
- _In_ unsigned int iField,
- _Out_ LPWSTR *pszValue= );
+UINT msi_format_f= ield(_In_ MSIHANDLE hInstall, _In_ MSIHANDLE hRecord, _In_ unsigned int iFi= eld,
+ = _Out_ LPWSTR *pszValue);

#endif /= * ifndef MSIHLP_H */
diff --git a/src/openvpnmsica/openvpnm= sica.c b/src/openvpnmsica/openvpnmsica.c
index 8d860e2..777= 9a1e 100644
--- a/src/openvpnmsica/openvpnmsica.c+++ b/src/openvpnmsica/openvpnmsica.c
@@ -59,9 +59,9= @@
*/

/** Amount of t= ick space to reserve for one TAP/TUN adapter creation/deletition. */=
-#define MSICA_ADAPTER_TICK_S= IZE (16 * 1024)
-#define FILE_NEED_REBOOT = L".ovpn_need_reboot"
+#define FILE_NEED_REBOOT L".ovpn_need_reboot"

#define OPENVPN_CONNECT_ADAPTER_SUBSTR L&= quot;OpenVPN Connect"

@@ -77,10 +77,= 7 @@
* @return ERROR_SUCCESS on success; An error code ot= herwise
*/
static UINT
-setup_sequence(
- _In_ MSIHANDLE hInstall,
- _In_z_ LPCWSTR szProperty,
- _In_ struct msica_arg_s= eq *seq)
+setup_seque= nce(_In_ MSIHANDLE hInstall, _In_z_ LPCWSTR szProperty, _In_ struct msica_a= rg_seq *seq)
{
UINT uiResult;<= br> LPWSTR szSequence =3D msica_arg_seq_join(seq);
@@ -110,12 +107,11 @@

static void
_debu= g_popup(_In_z_ LPCSTR szFunctionName)
{
- WCHAR szTitle[0x100], szMessage[0x10= 0+MAX_PATH], szProcessPath[MAX_PATH];
+ WCHAR szTitle[0x100], szMessage[0x100 + MAX_PATH], sz= ProcessPath[MAX_PATH];

/* Compose po= p-up title. The dialog title will contain function name to ease the process=
* locating. Mind that Visual Studio displays window = titles on the process list. */
- swprintf_s(szTitle, _countof(szTitle), L"%hs v%ls",<= /span>
- szFunct= ionName, _L(PACKAGE_VERSION));
+ swprintf_s(szTitle, _countof(szTitle), L"%hs v%ls"= , szFunctionName, _L(PACKAGE_VERSION));

= /* Get process name. */
GetModuleFileName(NULL, sz= ProcessPath, _countof(szProcessPath));
@@ -131,9 +127,7 @@<= /span>
L"If you would like to debug the custom actio= n, attach a debugger to this process and set breakpoints before dismissing = this dialog.\r\n"
L"\r\n" L"If you are not debugging this custom action, you can= safely ignore this message.",
- szProcessName,
- GetCurrentProcessId(),
- szFunctionName);
+ szProcessName, GetCurrentProcessId(), = szFunctionName);

MessageBox(NULL, sz= Message, szTitle, MB_OK);
}
@@ -144,11 +13= 8,8 @@
#endif /* ifdef _DEBUG */
<= br> static void
-= find_adapters(
- _In= _ MSIHANDLE hInstall,
-= _In_z_ LPCWSTR szzHardwareIDs,
- _In_z_ LPCWSTR szAdaptersPropertyName,
- _In_z_ LPCWSTR szActiveAdaptersProper= tyName)
+find_adapter= s(_In_ MSIHANDLE hInstall, _In_z_ LPCWSTR szzHardwareIDs,
+ _In_z_ LPCWSTR szAdapte= rsPropertyName, _In_z_ LPCWSTR szActiveAdaptersPropertyName)
{

UINT uiResult;

= @@ -165,24 +156,26 @@
return;
= }

- = /* Get IPv4/v6 info for all network adapters. Actually, we're intere= sted in link status only: up/down? */
+ /* Get IPv4/v6 info for all network adapters. Actuall= y, we're interested in link status only:
+ * up/down? */
PIP_ADAPTE= R_ADDRESSES pAdapterAdresses =3D NULL;
- ULONG ulAdapterAdressesSize =3D 16*1024;
+ ULONG ulAdapterAdressesSize = =3D 16 * 1024;

for (size_t iteration =3D 0; iteration = < 2; iteration++)
{
pAdapt= erAdresses =3D (PIP_ADAPTER_ADDRESSES)malloc(ulAdapterAdressesSize);=
if (pAdapterAdresses =3D=3D NULL)
= {
msg(M_NONFATAL, "%s: malloc(%u) fail= ed", __FUNCTION__, ulAdapterAdressesSize);
- uiResult =3D ERROR_OUTOFMEMORY; goto = cleanup_pAdapterList;
+ uiResult =3D ERROR_OUTOFMEMORY;
+ goto cleanup_pAdapterList;
= }

ULONG ulResult = =3D GetAdaptersAddresses(
AF_UNSPEC,- GAA_FLAG_SKIP_UNICA= ST | GAA_FLAG_SKIP_ANYCAST | GAA_FLAG_SKIP_MULTICAST | GAA_FLAG_SKIP_DNS_SE= RVER | GAA_FLAG_SKIP_FRIENDLY_NAME | GAA_FLAG_INCLUDE_ALL_INTERFACES,
- NULL,- pAdapterAdresses,
- &ulAdap= terAdressesSize);
+ = GAA_FLAG_SKIP_UNICAST | GAA_FLAG_SKIP_ANYCAST | GAA_FLAG_SKIP_MUL= TICAST
+ = | GAA_FLAG_SKIP_DNS_SERVER | GAA_FLAG_SKIP_FRIENDLY_NAME
+ | GAA_FLAG_INCLUDE_= ALL_INTERFACES,

+ = NULL, pAdapterAdresses, &ulAdapterAdressesSize);

if (ulResult =3D=3D ERROR_SUCCESS)
<= span> {

@@ -192,9 +185,12 @@
= free(pAdapterAdresses);
if (ulResult !=3D ERROR= _BUFFER_OVERFLOW)
{
- SetLastError(ulResult); /* MSDN does not= mention GetAdaptersAddresses() to set GetLastError(). But we do have an er= ror code. Set last error manually. */
+ SetLastError(
+ ulResult); /* MSDN does not mention= GetAdaptersAddresses() to set GetLastError().
+ But we do have an = error code. Set last error manually. */
msg(M_= NONFATAL | M_ERRNO, "%s: GetAdaptersAddresses() failed", __FUNCTI= ON__);
- uiR= esult =3D ulResult; goto cleanup_pAdapterList;
+ uiResult =3D ulResult;
+ goto cleanup_pAdapter= List;

}
}

@@ -207,26 +203,33 @@

= /* Prepare semicolon delimited list of TAP adapter ID(s) and active TAP ad= apter ID(s). */
LPWSTR
- szAdapters =3D (LPWSTR)malloc(adapter_cou= nt * (38 /*GUID*/ + 1 /*separator/terminator*/) * sizeof(WCHAR)),- szAdaptersTail =3D szAd= apters;
+ szAdapte= rs =3D
+ (LPWS= TR)malloc(adapter_count * (38 /*GUID*/ + 1 /*separator/terminator*/) * size= of(WCHAR)),
+ szAd= aptersTail =3D szAdapters;
if (szAdapters =3D=3D NULL)=
{
- msg(M_FATAL, "%s: malloc(%u) failed", __FUNCTION__, ada= pter_count * (38 /*GUID*/ + 1 /*separator/terminator*/) * sizeof(WCHAR));
- uiResult =3D ER= ROR_OUTOFMEMORY; goto cleanup_pAdapterAdresses;
+ msg(M_FATAL, "%s: malloc(%u) faile= d", __FUNCTION__,
+ = uiResult =3D ERROR_OUTOFMEMORY;
+ goto cleanup_pAdapterAdresses;
= }

LPWSTR
- szAdaptersActive =3D (LPWSTR)malloc= (adapter_count * (38 /*GUID*/ + 1 /*separator/terminator*/) * sizeof(WCHAR)= ),
- szAdaptersA= ctiveTail =3D szAdaptersActive;
+ szAdaptersActive =3D
+ (LPWSTR)malloc(adapter_count * (38 /*GUID*/ + 1 /*= separator/terminator*/) * sizeof(WCHAR)),
+ szAdaptersActiveTail =3D szAdaptersActive;=
if (szAdaptersActive =3D=3D NULL)
{
- msg(M_FATAL, &quo= t;%s: malloc(%u) failed", __FUNCTION__, adapter_count * (38 /*GUID*/ += 1 /*separator/terminator*/) * sizeof(WCHAR));
- uiResult =3D ERROR_OUTOFMEMORY; goto clean= up_szAdapters;
+ = msg(M_FATAL, "%s: malloc(%u) failed", __FUNCTION__,
= + adapter_count * (3= 8 /*GUID*/ + 1 /*separator/terminator*/) * sizeof(WCHAR));
+ uiResult =3D ERROR_OUTOFMEMO= RY;
+ goto cle= anup_szAdapters;
}

= for (struct tap_adapter_node *pAdapter =3D pAdapterList; pAdapter; pAda= pter =3D pAdapter->pNext)
{
- /* exclude adapters created by Open= VPN Connect, since they're removed on Connect uninstallation */<= br>+ /* exclude adapters= created by OpenVPN Connect, since they're removed on Connect+ * uninstallation */<= /span>
if (wcsstr(pAdapter->szName, OPENVPN_CONNECT_AD= APTER_SUBSTR))
{
msg(= M_WARN, "%s: skip OpenVPN Connect adapter '%ls'", __FUNCT= ION__, pAdapter->szName);
@@ -250,7 +253,9 @@
= {
OLECHAR szId[38 /*GUID*/ + 1 = /*terminator*/];
GUID guid;
- if (MultiByteToWideChar(CP_A= CP, MB_PRECOMPOSED, p->AdapterName, -1, szId, _countof(szId)) > 0
+ if (MultiBy= teToWideChar(CP_ACP, MB_PRECOMPOSED, p->AdapterName, -1, szId,+ = _countof(szId))
= - szAdaptersTail [0] =3D 0;
+ szAdaptersTail[0] =3D 0;
szAdapter= sActiveTail[0] =3D 0;

/* Set Install= er properties. */
uiResult =3D MsiSetProperty(hInstall= , szAdaptersPropertyName, szAdapters);
if (uiResult != =3D ERROR_SUCCESS)
{
- SetLastError(uiResult); /* MSDN does not mentio= n MsiSetProperty() to set GetLastError(). But we do have an error code. Set= last error manually. */
+ SetLastError(uiResult); /* MS= DN does not mention MsiSetProperty() to set GetLastError(). But
<= span style=3D"color: hsl(120, 100%, 40%);">+ = we do have an error code. Set last error manually. */

+ msg(M_NONFATAL | M_ERRNO, &qu= ot;%s: MsiSetProperty(\"%s\") failed", __FUNCTION__,<= br>+ szAdaptersPrope= rtyName);
goto cleanup_szAdaptersActive; }
uiResult =3D MsiSetProperty(hInstall, sz= ActiveAdaptersPropertyName, szAdaptersActive);
if (uiR= esult !=3D ERROR_SUCCESS)
{
- SetLastError(uiResult); /* MSDN does not= mention MsiSetProperty() to set GetLastError(). But we do have an error co= de. Set last error manually. */
- msg(M_NONFATAL | M_ERRNO, "%s: MsiSetProperty(\"= ;%s\") failed", __FUNCTION__, szActiveAdaptersPropertyName);
+ SetLastError(uiR= esult); /* MSDN does not mention MsiSetProperty() to set GetLastError(). Bu= t
+ = we do have an error code. Set last error manually. */
+ msg(M_NONFATAL |= M_ERRNO, "%s: MsiSetProperty(\"%s\") failed", __FUNCTI= ON__,
+ sz= ActiveAdaptersPropertyName);
goto cleanup_szAdapte= rsActive;
}

@@ -299,= 8 +308,7 @@
}

-UINT __stdcall
-FindSystemInfo(_In_ MSIHANDLE hInstal= l)

+UINT __stdcall Fi= ndSystemInfo(_In_ MSIHANDLE hInstall)
{
#= ifdef DLLEXP_EXPORT
#pragma comment(linker, DLLEXP_EXPORT)=
@@ -312,16 +320,12 @@

= OPENVPNMSICA_SAVE_MSI_SESSION(hInstall);

- find_adapters(

- hInstall,
- L"root\\" _L(TAP_WIN_COM= PONENT_ID) L"\0" _L(TAP_WIN_COMPONENT_ID) L"\0",=
- L"TAPWINDOWS6AD= APTERS",
- = L"ACTIVETAPWINDOWS6ADAPTERS");
- find_adapters(
- hInstall,
- L"ovpn-dco" L"\0",
- L"OVPNDCOADAPTERS",<= /span>
- L"ACTIVEO= VPNDCOADAPTERS");
+ L"TAPWINDOWS6= ADAPTERS", L"ACTIVETAPWINDOWS6ADAPTERS");
+ find_adapters(hInstall,
= + L"ovpn-= dco"
+ = L"\0",
+ L"OVPNDCOADAPTERS", L"ACTIVEOVPNDCOAD= APTERS");

if (bIsCoInitialized)=
{
@@ -331,13 +335,13 @@
}



-UINT __stdcall
-CloseOpenVPNGUI(_In_ MSIHANDLE hInstall)
+UINT __stdcall CloseOpenVPNGUI(_In_ MSIHA= NDLE hInstall)
{
#ifdef DLLEXP_EXPORT
#pragma comment(linker, DLLEXP_EXPORT)
#endi= f
- UNREFERENCED_PAR= AMETER(hInstall); /* This CA is does not interact with MSI session (report = errors, access properties, tables, etc.). */
+ UNREFERENCED_PARAMETER(hInstall); /* This CA i= s does not interact with MSI session (report
+ errors, a= ccess properties, tables, etc.). */

= debug_popup(__FUNCTION__);

@@ -345,7 +349= ,8 @@
HWND hWnd =3D FindWindow(L"OpenVPN-GUI"= ;, NULL);
if (hWnd)
{
<= span style=3D"color: hsl(0, 100%, 40%);">- /* Ask it to close and wa= it for 100ms. Unfortunately, this will succeed only for recent OpenVPN GUI = that do not run elevated. */

+ /* Ask it to close and wait for 100ms. Unfortunately, this= will succeed only for recent
+ * OpenVPN GUI that do not run elevated. */
SendMessage(hWnd, WM_CLOSE, 0, 0);

Sle= ep(100);
}
@@ -354,8 +359,7 @@<= br> }


-UINT __stdcall
-StartOpenVPNGUI(_In_ MSIHANDLE hInstall)
+UINT __stdcall StartOpenVPNGUI(_In_= MSIHANDLE hInstall)

{
#ifdef DLLEXP_EXPO= RT
#pragma comment(linker, DLLEXP_EXPORT)
= @@ -379,7 +383,8 @@
uiResult =3D MsiRecordSetString(hR= ecord, 0, L"\"[#bin.openvpn_gui.exe]\"");
if (uiResult !=3D ERROR_SUCCESS)

{
<= span style=3D"color: hsl(0, 100%, 40%);">- SetLastError(uiResult); /= * MSDN does not mention MsiRecordSetString() to set GetLastError(). But we = do have an error code. Set last error manually. */

+ SetLastError(uiResult); /* MSDN does= not mention MsiRecordSetString() to set GetLastError().
+ But= we do have an error code. Set last error manually. */
= msg(M_NONFATAL | M_ERRNO, "%s: MsiRecordSetString failed", _= _FUNCTION__);
goto cleanup_MsiCreateRecord;=
}
@@ -396,25 +401,26 @@
= if (szPath =3D=3D NULL)
{
= msg(M_FATAL, "%s: malloc(%u) failed", __FUNCTION__, dwP= athSize * sizeof(WCHAR));
- uiResult =3D ERROR_OUTOFMEMORY; goto cleanup_MsiCreateRecor= d;
+ uiRes= ult =3D ERROR_OUTOFMEMORY;
+ goto cleanup_MsiCreateRecord;
}=

uiResult =3D MsiFormatRecord(hI= nstall, hRecord, szPath, &dwPathSize);
} if (uiResult !=3D ERROR_SUCCESS)
{<= br>- SetLastError(uiResult= ); /* MSDN does not mention MsiFormatRecord() to set GetLastError(). But we= do have an error code. Set last error manually. */
+ SetLastError(uiResult); /* MSDN d= oes not mention MsiFormatRecord() to set GetLastError().
+ But= we do have an error code. Set last error manually. */
= msg(M_NONFATAL | M_ERRNO, "%s: MsiFormatRecord failed", __FU= NCTION__);
goto cleanup_malloc_szPath;
<= span> }


/* Launch the OpenVPN GU= I. */
- SHELLEXECUTE= INFO sei =3D {
- = .cbSize =3D sizeof(SHELLEXECUTEINFO),
- .fMask =3D SEE_MASK_FLAG_NO_UI, /* Don't show= error UI, we'll display it. */
- .lpFile =3D szPath,
- .nShow =3D SW_SHOWNORMAL
- };
+ SHELLEXECUTEINFO sei =3D { .cbSize =3D sizeof(SHELLE= XECUTEINFO),
+ = .fMask =3D
+ SEE_MASK_FLAG_NO_UI, /* Don&#= 39;t show error UI, we'll display it. */
+ .lpFile =3D szPath,
+ = .nShow =3D SW_SHOWNORMAL };
if (!ShellExecuteE= x(&sei))
{
uiResult =3D G= etLastError();
@@ -461,12 +467,9 @@
* @re= turn ERROR_SUCCESS on success; An error code otherwise
*/=
static DWORD
-schedule_adapter_create(
- _Inout_ struct msica_arg_seq *seq,
- _Inout_opt_ struct msica_arg_seq *seqRollb= ack,
- _In_z_ LPCWST= R szDisplayName,
- _= In_z_ LPCWSTR szHardwareId,
- _Inout_ int *iTicks)
+schedule_adapter_create(_Inout_ struct msica_arg_seq *seq,
+ _= Inout_opt_ struct msica_arg_seq *seqRollback, _In_z_ LPCWSTR szDisplayName,=
+ = _In_z_ LPCWSTR szHardwareId, _Inout_ int *iTicks)
{
/* Get existing network adapters. */
= struct tap_adapter_node *pAdapterList =3D NULL;
@@ -477,= 28 +480,25 @@
}

= /* Does adapter exist? */
- for (struct tap_adapter_node *pAdapterOther =3D pAdapterList;; pAd= apterOther =3D pAdapterOther->pNext)
+ for (struct tap_adapter_node *pAdapterOther =3D pAd= apterList;;
+ = pAdapterOther =3D pAdapterOther->pNext)
{ if (pAdapterOther =3D=3D NULL)
{<= /span>
/* No adapter with a same name found. */
- WCHAR szArgumen= t[10 /*create=3D""|deleteN=3D""*/ + MAX_PATH /*szDispla= yName*/ + 1 /*|*/ + MAX_PATH /*szHardwareId*/ + 1 /*terminator*/];+ WCHAR szArgument= [10 /*create=3D""|deleteN=3D""*/ + MAX_PATH /*szDisplay= Name*/ + 1 /*|*/
+ = + MAX_PATH /*szHardwareId*/ + 1 /*terminator*/];<= /span>

/* InstallTUNTAPAdapters wil= l create the adapter. */
- szArgument, _countof(szArgument),
- L"create=3D\"%.*= s|%.*s\"",
- = MAX_PATH, szDisplayName,
- MAX_PATH, szHardwareId);
+ swprintf_s(szArgument, _= countof(szArgument), L"create=3D\"%.*s|%.*s\"", MAX_PAT= H,
+ = szDisplayName, MAX_PATH, szHardwareId);
= msica_arg_seq_add_tail(seq, szArgument);

= if (seqRollback)
{
/* InstallTUNTAPAdaptersRollback will delete the adapter= . */

- s= wprintf_s(
- = szArgument, _countof(szArgument),
- L"deleteN=3D\"%.*s\"= ;",
- = MAX_PATH, szDisplayName);
+ swprintf_s(szArgument, _countof(szArgument), L= "deleteN=3D\"%.*s\"", MAX_PATH,
+ szDisplayName)= ;
msica_arg_seq_add_head(seqRollback, szAr= gument);
}

@= @ -513,13 +513,15 @@
if (hwid[0] =3D=3D 0)=
{
/*= This adapter has a different hardware ID. */
- msg(M_NONFATAL, "%s: Adapt= er with name \"%ls\" already exists", __FUNCTION__, pAdapter= Other->szName);
+ = msg(M_NONFATAL, "%s: Adapter with name \"%ls\&= quot; already exists", __FUNCTION__,
+ pAdapterOther->szName);
dwResult =3D ERROR_ALREADY_EXISTS;
goto cleanup_pAdapterList;
= }
else if (wcsicmp(hwid, = szHardwareId) =3D=3D 0)
{
- /* This is an adap= ter with the requested hardware ID. We already have what we want! */=
+ /* Thi= s is an adapter with the requested hardware ID. We already have what we
+ * = want! */
break;
= }
}
@@ -561,13 +563= ,10 @@
* @return ERROR_SUCCESS on success; An error code = otherwise
*/
static DWORD
-schedule_adapter_delete(

<= span style=3D"color: hsl(0, 100%, 40%);">- _Inout_ struct msica_arg_seq = *seq,

- _Inout_opt_ = struct msica_arg_seq *seqCommit,
- _Inout_opt_ struct msica_arg_seq *seqRollback,
- _In_z_ LPCWSTR szDisplayName,
- _In_z_ LPCWSTR szzH= ardwareIDs,
- _Inout= _ int *iTicks)
+sched= ule_adapter_delete(_Inout_ struct msica_arg_seq *seq,
+ _Inout_opt_ struc= t msica_arg_seq *seqCommit,
+ _Inout_opt_ struct msica_arg_seq *seqRollba= ck, _In_z_ LPCWSTR szDisplayName,
+ _In_z_ LPCWSTR szzHardwareIDs, _Inout= _ int *iTicks)
{
/* Get adapters with= given hardware ID. */
struct tap_adapter_node *pAdapt= erList =3D NULL;
@@ -578,42 +577,36 @@
= }

/* Does adapter exist? */<= br>- for (struct tap_adapter_n= ode *pAdapter =3D pAdapterList; pAdapter !=3D NULL; pAdapter =3D pAdapter-&= gt;pNext)
+ for (s= truct tap_adapter_node *pAdapter =3D pAdapterList; pAdapter !=3D NULL;
+ pAdapter =3D pA= dapter->pNext)
{
if (wcsic= mp(szDisplayName, pAdapter->szName) =3D=3D 0)
{=
/* Adapter found. */
- WCHAR szArgument[8 /*disable=3D|en= able=3D|delete=3D*/ + 38 /*{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}*/ + 1 /*t= erminator*/];
+ = WCHAR szArgument[8 /*disable=3D|enable=3D|delete=3D*/
+ + 38 /= *{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}*/ + 1 /*terminator*/];

if (seqCommit && seqRollback)

= {
/* UninstallTUNTAPAdapters will= disable the adapter. */
- szArgument, _countof(szArgument),
- L"disable= =3D" _L(PRIXGUID),

- PRIGUID_PARAM(pAdapter->guid));
+ swprintf_s(szArgument,= _countof(szArgument), L"disable=3D" _L(PRIXGUID),
+ PRIGUID= _PARAM(pAdapter->guid));

msica_arg_seq_= add_tail(seq, szArgument);

= /* UninstallTUNTAPAdaptersRollback will re-enable the adapter. */=
- swprintf_s(<= /span>
- sz= Argument, _countof(szArgument),
- L"enable=3D" _L(PRIXGUID),- PRIGUID_PA= RAM(pAdapter->guid));
+ swprintf_s(szArgument, _countof(szArgument), L"en= able=3D" _L(PRIXGUID),
+ PRIGUID_PARAM(pAdapter->guid));
msica_arg_seq_add_head(seqRollback, szArgument)= ;

/* UninstallTUNTAPAdap= tersCommit will delete the adapter. */
- swprintf_s(
- szArgument, _countof(szArgument)= ,
- = L"delete=3D" _L(PRIXGUID),
- PRIGUID_PARAM(pAdapter->guid));
+ swprintf_= s(szArgument, _countof(szArgument), L"delete=3D" _L(PRIXGUID),
+ = PRIGUID_PARAM(pAdapter->guid));
ms= ica_arg_seq_add_tail(seqCommit, szArgument);
}=
else
{ /* UninstallTUNTAPAdapters will delete the adapter.= */
- sw= printf_s(
- = szArgument, _countof(szArgument),
- L"delete=3D" _L(PRIXGUID)= ,
- = PRIGUID_PARAM(pAdapter->guid));
+ swprintf_s(szArgument, _countof(szArgument),= L"delete=3D" _L(PRIXGUID),
+ PRIGUID_PARAM(pAdapter->gui= d));
msica_arg_seq_add_tail(seq, szArgumen= t);
}

@@ -62= 7,8 +620,7 @@
}

=
-UINT __stdcall
-EvaluateTUNTAPAdapters(_In_ MSIHAND= LE hInstall)

+UINT __= stdcall EvaluateTUNTAPAdapters(_In_ MSIHANDLE hInstall)
{<= /span>
#ifdef DLLEXP_EXPORT
#pragma comment(link= er, DLLEXP_EXPORT)
@@ -641,13 +633,8 @@

OPENVPNMSICA_SAVE_MSI_SESSION(hInstall);

- struct msica_a= rg_seq
- seqInst= all,
- seqInstal= lCommit,
- seqIn= stallRollback,
- = seqUninstall,
- = seqUninstallCommit,
- = seqUninstallRollback;
+ struct msica_arg_seq seqInstall, seqInstallCommit, seqInstallR= ollback, seqUninstall,
- bool bRollbackEnabled =3D MsiEvaluateCondition(hInstall,= L"RollbackDisabled") !=3D MSICONDITION_TRUE;
+ bool bRollbackEnabled =3D+ MsiEvaluateCondition(= hInstall, L"RollbackDisabled") !=3D MSICONDITION_TRUE;
=
/* Open MSI database. */
= MSIHANDLE hDatabase =3D MsiGetActiveDatabase(hInstall);
@@ = -671,7 +659,8 @@
switch (MsiDatabaseIsTablePersistent(= hDatabase, L"TUNTAPAdapter"))
{
case MSICONDITION_FALSE:

- case MSICONDITION_TRUE: break;
+ case MSICONDITION_TRUE:+ break;
default:
uiR= esult =3D ERROR_SUCCESS;
@@ -680,11 +669,14 @@

/* Prepare a query to get a list/view of adapter= s. */
MSIHANDLE hViewST =3D 0;
- LPCWSTR szQuery =3D L"SELECT `Adap= ter`,`DisplayName`,`Condition`,`Component_`,`HardwareId` FROM `TUNTAPAdapte= r`";
+ LPCWST= R szQuery =3D
+ = L"SELECT `Adapter`,`DisplayName`,`Condition`,`Component_`,`HardwareI= d` FROM `TUNTAPAdapter`";
uiResult =3D MsiDatabas= eOpenView(hDatabase, szQuery, &hViewST);
if (uiRes= ult !=3D ERROR_SUCCESS)
{
- SetLastError(uiResult); /* MSDN does not m= ention MsiDatabaseOpenView() to set GetLastError(). But we do have an error= code. Set last error manually. */
+ SetLastError(
+ uiResult); /* MSDN does not mention MsiDatabas= eOpenView() to set GetLastError(). But we
+ do have an error code. Set = last error manually. */
msg(M_NONFATAL | M_ERRNO, = "%s: MsiDatabaseOpenView(\"%ls\") failed", __FUNCTION__= , szQuery);
goto cleanup_hDatabase;
}

@@ -693,7 +685,8 @@
uiResult = =3D MsiViewExecute(hViewST, 0);
if (uiResult !=3D ERRO= R_SUCCESS)
{
- SetLastError(uiResult); /* MSDN does not mention MsiVie= wExecute() to set GetLastError(). But we do have an error code. Set last er= ror manually. */
+ = SetLastError(uiResult); /* MSDN does not mention MsiViewExecute() to s= et GetLastError(). But
- for (;; )
+ for (;;)
{
= /* Fetch one record from the view. */
MSIH= ANDLE hRecord =3D 0;
@@ -719,7 +712,8 @@
= }
else if (uiResult !=3D ERROR_SUCCESS)
{
- SetLastError(uiResult); /* MSDN does not mention MsiViewFetch= () to set GetLastError(). But we do have an error code. Set last error manu= ally. */
+ = SetLastError(uiResult); /* MSDN does not mention MsiViewFetch() to set Get= LastError().
+ = But we do have an error code. Set last erro= r manually. */
msg(M_NONFATAL | M_ERRNO, "= ;%s: MsiViewFetch failed", __FUNCTION__);
= goto cleanup_hRecordProg;
}
@@ -7= 38,8 +732,11 @@
uiResult =3D MsiGetComponentSt= ate(hInstall, szValue, &iInstalled, &iAction);
= if (uiResult !=3D ERROR_SUCCESS)
{
- SetLastE= rror(uiResult); /* MSDN does not mention MsiGetComponentState() to set GetL= astError(). But we do have an error code. Set last error manually. */
- msg(M_NONFA= TAL | M_ERRNO, "%s: MsiGetComponentState(\"%ls\") failed&quo= t;, __FUNCTION__, szValue);
+ SetLastError(uiResult); /* MSDN does not mention Ms= iGetComponentState() to set
+ GetLastError(). But we d= o have an error code. Set last
+ error manually. */
+ msg(M_= NONFATAL | M_ERRNO, "%s: MsiGetComponentState(\"%ls\") faile= d", __FUNCTION__,
- /* `Di= splayName` field type is [Filename](https://docs.microsoft.com/en-us/window= s/win32/msi/filename), which is either "8.3|long name" or "8= .3". */
+ = /* `DisplayName` field type is
+ * [Filename](https://docs.microsoft.com/en-us/windows/= win32/msi/filename), which is either
+ * "8.3|long name" or "8.3". *= /
LPWSTR szDisplayNameEx =3D wcschr(szDisplayName,= L'|');
szDisplayNameEx =3D szDisplayNameE= x !=3D NULL ? szDisplayNameEx + 1 : szDisplayName;
=
@@ -766,7 +765,10 @@
{
goto cleanup_szDisplayName;

= }
- memcpy= _s(szzHardwareIDs, sizeof(szzHardwareIDs) - 2*sizeof(WCHAR) /*requires doub= le zero termination*/, szHwId, wcslen(szHwId)*sizeof(WCHAR));
+ memcpy_s(szzHardwareI= Ds,

+ = sizeof(szzHardwareIDs)
+ - 2 * sizeof(WCHAR) /*requires double zero= termination*/,
+ = szHwId, wcslen(szHwId) * sizeof(WCHAR));
= free(szHwId);
}

@@ -799,7 +801,8 @@

= case MSICONDITION_ERROR:
= uiResult =3D ERROR_INVALID_FIELD;
- msg(M_NONFATAL | M_ERRNO, "%s: = MsiEvaluateCondition(\"%ls\") failed", __FUNCTION__, szValue= );
+ = msg(M_NONFATAL | M_ERRNO, "%s: MsiEvaluateCondition(\"%ls\= ") failed",
+ __FUNCTION__, szValue);
= free(szValue);
= goto cleanup_szDisplayName;
}
<= span>@@ -809,12 +812,10 @@

free(szValue);<= /span>

/* Component is or shoul= d be installed. Schedule adapter creation. */
- if (schedule_adapter_create(=
- &= ;seqInstall,
- = bRollbackEnabled ? &seqInstallRollback : NULL,- szDispl= ayNameEx,
- = szzHardwareIDs,
- &iTicks) !=3D ERROR_SUCCESS)
+ if (schedule_ada= pter_create(&seqInstall,

+ bRollbackEnabled ? &am= p;seqInstallRollback : NULL,
+ szDisplayNameEx, szzHa= rdwareIDs, &iTicks)
+ !=3D ERROR_SUCCESS)
= {
uiResult =3D ERROR_INSTALL_FAILED;=
goto cleanup_szDisplayName;@@ -822,18 +823,16 @@
}
else

{
- /* Component is installed, but = should be degraded to advertised/removed. Schedule adapter deletition.
+ /* Compo= nent is installed, but should be degraded to advertised/removed. Schedule
+ * ad= apter deletition.
*
- * Note: On adapter removal= (product is being uninstalled), we tolerate dwResult error.
- * Better a partial = uninstallation than no uninstallation at all.

+ * Note: On adapter removal (prod= uct is being uninstalled), we tolerate dwResult
+ * error. Better a partial unin= stallation than no uninstallation at all.
= */
- sc= hedule_adapter_delete(
= - &seqUninstall,
- bRollbackEnabled ? &seqUninstallC= ommit : NULL,
- = bRollbackEnabled ? &seqUninstallRollback : NULL,
= - szDisplayNam= eEx,
- = szzHardwareIDs,
- = &iTicks);
+ schedule_adapter_delete(&seqUninstall,
+ = bRollbackEnabled ? &seqUninstallCommit : NULL,+ = bRollbackEnabled ? &seqUninstallRollback : NULL,
<= span style=3D"color: hsl(120, 100%, 40%);">+ = szDisplayNameEx, szzHardwareIDs, &iTicks);

= }

/* Arrange the a= mount of tick space to add to the progress indicator.
@@ -8= 71,12 +870,21 @@
msica_arg_seq_add_tail(&seqUninst= allRollback, str);

/* Store deferred= custom action parameters. */
- if ((uiResult =3D setup_sequence(hInstall, L"InstallTUNTAP= Adapters", &seqInstall )) !=3D ERROR_SUCCESS
- || (uiResult =3D setup_seq= uence(hInstall, L"InstallTUNTAPAdaptersCommit", &seqInstallCo= mmit )) !=3D ERROR_SUCCESS

- || (uiResult =3D setup_sequence(hInstall, L"InstallTUN= TAPAdaptersRollback", &seqInstallRollback )) !=3D ERROR_SUCCESS
- || (uiResult = =3D setup_sequence(hInstall, L"UninstallTUNTAPAdapters", &seq= Uninstall )) !=3D ERROR_SUCCESS
- || (uiResult =3D setup_sequence(hInstall, L"U= ninstallTUNTAPAdaptersCommit", &seqUninstallCommit )) !=3D ERROR_= SUCCESS
- || (ui= Result =3D setup_sequence(hInstall, L"UninstallTUNTAPAdaptersRollback&= quot;, &seqUninstallRollback)) !=3D ERROR_SUCCESS)
+ if ((uiResult =3D setup_sequence(hIn= stall, L"InstallTUNTAPAdapters", &seqInstall))
+ !=3D ERROR_SUCCESS
+ || (uiResult = =3D setup_sequence(hInstall, L"InstallTUNTAPAdaptersCommit", &= ;seqInstallCommit))
+= !=3D ERROR_SUCCESS
+ || (uiResult =3D
+ setup_sequence(hInstall, L"InstallT= UNTAPAdaptersRollback", &seqInstallRollback))
+ !=3D ERROR_SUCCESS=
+ || (uiResult =3D s= etup_sequence(hInstall, L"UninstallTUNTAPAdapters", &seqUnins= tall))
+ = !=3D ERROR_SUCCESS
= + || (uiResult =3D
+ setup_sequence(hInstall, L"UninstallTUNTAPAdapte= rsCommit", &seqUninstallCommit))
+ !=3D ERROR_SUCCESS
+ || (uiResult =3D
+ setup_sequence(hIn= stall, L"UninstallTUNTAPAdaptersRollback", &seqUninstallRollb= ack))

+ = !=3D ERROR_SUCCESS)
{
goto c= leanup_hRecordProg;
}
@@ -916,9 +924,7= @@
* @return TRUE on success; FALSE otherwise
= */
static BOOL
-parse_guid(
- _In_z_ LPCWSTR szArg,
- _Out_ GUID *guid)
+parse_guid(_In_z_ LPCWSTR szArg, _Out_ GUID *guid)
= {
if (swscanf_s(szArg, _L(PRIXGUID), PRIGUID_PA= RAM_REF(*guid)) !=3D 11)
{
@@ -945,7 += 951,8 @@

msg(M_WARN, "%s: Reboo= t required, create reboot indication file \"%ls\"", __FUNCTI= ON__, path);

- HANDLE file =3D CreateFileW(path, GENERIC_WRITE, 0, NULL, CREA= TE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
+ HANDLE file =3D
+ CreateFileW(path, GENERIC_WRITE, 0, NULL, CREA= TE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (file =3D= =3D INVALID_HANDLE_VALUE)
{
m= sg(M_NONFATAL | M_ERRNO, "%s: CreateFile(\"%ls\") failed&quo= t;, __FUNCTION__, path);
@@ -956,8 +963,7 @@
}

}

-UINT __stdcall
-ProcessDeferredAction(_In_ MSIHANDLE hInstall)
<= span style=3D"color: hsl(120, 100%, 40%);">+UINT __stdcall ProcessDeferredA= ction(_In_ MSIHANDLE hInstall)

{
#ifdef D= LLEXP_EXPORT
#pragma comment(linker, DLLEXP_EXPORT)=
@@ -967,13 +973,15 @@

UINT= uiResult;
BOOL bIsCoInitialized =3D SUCCEEDED(CoIniti= alize(NULL));
- WCHA= R tmpDir[MAX_PATH] =3D {0};
+ WCHAR tmpDir[MAX_PATH] =3D { 0 };

<= span> OPENVPNMSICA_SAVE_MSI_SESSION(hInstall);

=
- BOOL bIsCleanup =3D MsiG= etMode(hInstall, MSIRUNMODE_COMMIT) || MsiGetMode(hInstall, MSIRUNMODE_ROLL= BACK);
+ BOOL bIsC= leanup =3D
+ M= siGetMode(hInstall, MSIRUNMODE_COMMIT) || MsiGetMode(hInstall, MSIRUNMODE_R= OLLBACK);

- /* Get sequence arguments. Always Unicode as CommandLineToArgvW()= is available as Unicode-only. */
+ /* Get sequence arguments. Always Unicode as CommandLineT= oArgvW() is available as Unicode-only.
+ */
LPWSTR szSequence =3D NULL;=
uiResult =3D msi_get_string(hInstall, L"CustomAc= tionData", &szSequence);
if (uiResult !=3D ER= ROR_SUCCESS)
@@ -985,7 +993,8 @@
if (s= zArg =3D=3D NULL)
{
uiResult = =3D GetLastError();
- = msg(M_NONFATAL | M_ERRNO, "%s: CommandLineToArgvW(\"%ls\&qu= ot;) failed", __FUNCTION__, szSequence);
+ msg(M_NONFATAL | M_ERRNO, "%s: Comma= ndLineToArgvW(\"%ls\") failed", __FUNCTION__,
+ szSequence);
goto cleanup_szSequence;
}
<= span>

@@ -1037,8 +1046,8 @@
d= wResult =3D tap_create_adapter(NULL, NULL, szHardwareId, &bRebootRequir= ed, &guidAdapter);
if (dwResult =3D=3D ERR= OR_SUCCESS)
{
- /* Set adapter name. May fail on some = machines, but that is not critical - use silent
- * flag to mute messagebox and pr= int error only to log */
+ /* Set adapter name. May fail on some machines, but th= at is not critical - use
+ * silent flag to mute messagebox and print error only= to log */
tap_set_adapter_name(&guidA= dapter, szName, TRUE);
}
= }
@@ -1067,7 +1076,8 @@
if= (dwResult =3D=3D ERROR_SUCCESS)
{
<= span> /* Does the adapter exist? */

- for (struct tap_adapter_nod= e *pAdapter =3D pAdapterList; pAdapter !=3D NULL; pAdapter =3D pAdapter->= ;pNext)
+ = for (struct tap_adapter_node *pAdapter =3D pAdapterList; pAdapter !=3D = NULL;
+ = pAdapter =3D pAdapter->pNext)
{<= /span>
if (wcsicmp(szName, pAdapter->szNam= e) =3D=3D 0)
{
@@ -115= 6,8 +1166,7 @@
return uiResult;
}

-UINT __= stdcall
-CheckAndSchedu= leReboot(_In_ MSIHANDLE hInstall)
+UINT __stdcall CheckAndScheduleReboot(_In_ MSIHANDLE hInstall= )
{
#ifdef DLLEXP_EXPORT
= #pragma comment(linker, DLLEXP_EXPORT)
diff --git a/src/op= envpnmsica/openvpnmsica.h b/src/openvpnmsica/openvpnmsica.h
index d07554f..c3e0445 100644

--- a/src/openvpnmsica/openv= pnmsica.h
+++ b/src/openvpnmsica/openvpnmsica.h
<= span>@@ -50,10 +50,11 @@

/**
* Set MSI s= ession handle in thread local storage.
*/
-#define OPENVPNMSICA_SAVE_MSI_SESSION= (hInstall) \

- { \
- struct openvpnm= sica_thread_data *s =3D (struct openvpnmsica_thread_data *)TlsGetValue(open= vpnmsica_thread_data_idx); \
- s->hInstall =3D (hInstall); \
+#define OPENVPNMSICA_SAVE_MSI_SESSION(hInstall)= \
+ { = \
+ struct openvpnmsica_thread_data *s =3D = \
+ (struct openvpnmsica_thread_data *)TlsGetV= alue(openvpnmsica_thread_data_idx); \
+ s->hInstall =3D (hInstall); = \
}


@@ -62,7 +63,8 @@
= */

#ifdef __cplusplus
-extern "C" {
+extern "C"
+{

#endif
/* Ensure that clang-cl, which does not understan= d the cl specific
@@ -77,90 +79,84 @@
#end= if


-/**
- = * Determines Windows information:
- *
- * - Se= ts `OPENVPNSERVICE` MSI property to PID of OpenVPN Service if running, or i= ts EXE path if
- * co= nfigured for auto-start.
- * - Finds exist= ing TAP-Windows6 adapters and set TAPWINDOWS6ADAPTERS and
- * ACTIVETAPWINDOWS6ADAPTERS properti= es with semicolon delimited list of all installed adapter
- * GUIDs and active adapter GUIDs res= pectively.
- *- * - Finds existing ovpn-dco a= dapters and set OVPNDCOADAPTERS and ACTIVEOVPNDCOADAPTERS properties=
- * with semicolon delimite= d list of all installed adapter GUIDs and active adapter GUIDs
- * respectively.

- *

- * @param hInstall Handle to the installation provi= ded to the DLL custom action
- *
- * @return E= RROR_SUCCESS on success; An error code otherwise
- * See: https://msdn.microsoft.com/en-us= /library/windows/desktop/aa368072.aspx
- */
-D= LLEXP_DECL UINT __stdcall
-FindSystemInfo(_In_ MSIHANDLE hInstall);
+ /**
+ * Determines Windows information:
+ *
+ * - Sets `OPENVPNSERVICE` MSI property to PID of = OpenVPN Service if running, or its EXE path if
+ * configured for auto-start.
+ *

+ * - Finds existing TAP-Windows6 adapters= and set TAPWINDOWS6ADAPTERS and
+ * ACTIVETAPWINDOWS6ADAPTERS properties with semicolon d= elimited list of all installed adapter
+ * GUIDs and active adapter GUIDs respectively.
+ *
+ * - Finds existing ovpn-dco ad= apters and set OVPNDCOADAPTERS and ACTIVEOVPNDCOADAPTERS

+ * properties with semicolon delim= ited list of all installed adapter GUIDs and active adapter
+ * GUIDs respectively.
+ *
+ * @param hInstall Handle to the= installation provided to the DLL custom action
+ *
+ * @return ERROR_SUCCESS on success; An error code other= wise
+ * = See: https://msdn.microsoft.com/en-us/library/windows/desktop/aa368072.aspx=
+ */
<= span style=3D"color: hsl(120, 100%, 40%);">+ DLLEXP_DECL UINT __stdcall = FindSystemInfo(_In_ MSIHANDLE hInstall);


=
-/**
- * Find OpenVPN GUI window and send it= a WM_CLOSE message.
- = *
- * @param hInstall = Handle to the installation provided to the DLL custom action
= - *
- * @return ERROR_SUCCESS on success; An error code = otherwise
- * S= ee: https://msdn.microsoft.com/en-us/library/windows/desktop/aa368072.aspx<= /span>
- */
-DLLEXP_DECL UINT __stdcall
-CloseOpenVPNGUI(_In_ MSIHANDLE hIns= tall);

+ /**
+ * Find OpenVPN GUI w= indow and send it a WM_CLOSE message.
+ *
+ * @param hInstall Handle to the installation provided to the= DLL custom action
+ = *
+ * @return= ERROR_SUCCESS on success; An error code otherwise
+ * See: https://msdn.microsoft.c= om/en-us/library/windows/desktop/aa368072.aspx
+ */
+ DLLEXP_DECL UINT __stdcall CloseOpenVPNGUI(_In_ MSIHANDL= E hInstall);


-/**
- * Launches OpenVPN GUI. It's path is obtained by expanding th= e `[#bin.openvpn_gui.exe]`
- * therefore, its Id field in File table must be "bin.openvpn_gui= .exe".
- *<= br>- * @param hInstall Handl= e to the installation provided to the DLL custom action
- *
- * @return ERROR_SUCCESS on success; An error code otherwise=
- * See: https= ://msdn.microsoft.com/en-us/library/windows/desktop/aa368072.aspx- */
-DLLEXP_DECL UINT __stdcall
-StartOpenVPNGUI(_In_ MSIHANDLE hInstall);
+ /**
+ * Launches OpenVPN GUI. It&#= 39;s path is obtained by expanding the `[#bin.openvpn_gui.exe]`

<= span style=3D"color: hsl(120, 100%, 40%);">+ * therefore, its Id field = in File table must be "bin.openvpn_gui.exe".

+ *
+ * @param hInstall Handle to the installatio= n provided to the DLL custom action
+ *
+ * See: https:/= /msdn.microsoft.com/en-us/library/windows/desktop/aa368072.aspx
<= span style=3D"color: hsl(120, 100%, 40%);">+ */

+ DLLEXP_DECL UINT __stdcall StartOpenV= PNGUI(_In_ MSIHANDLE hInstall);

<= br>-/**
- * Evaluate the TUNTAPAdapter table of the MSI = package database and prepare a list of TAP
- * adapters to install/remove.
- *
- * @param hInstall Handle to the installation provided to= the DLL custom action
= - *
- * @return ERROR_S= UCCESS on success; An error code otherwise
- * See: https://msdn.microsoft.com/en-us/libra= ry/windows/desktop/aa368072.aspx
- */
-DLLEXP_= DECL UINT __stdcall
-Ev= aluateTUNTAPAdapters(_In_ MSIHANDLE hInstall);
+ /**
+ * Evaluate the TUNTAPAdapter table of the MSI package d= atabase and prepare a list of TAP
+ * adapters to install/remove.
+ *
+ * @param hInstall Handle to the installation prov= ided to the DLL custom action
+ *
+ = * @return ERROR_SUCCESS on success; An error code otherwise
+ * See: https://msdn.= microsoft.com/en-us/library/windows/desktop/aa368072.aspx

+ */
+ DLLEXP_DECL UINT __stdcall EvaluateTUNTAPAdap= ters(_In_ MSIHANDLE hInstall);

-/**
- * Perform scheduled deferred action.
= - *
- * @param hInstall Handle to the installation = provided to the DLL custom action
- *
- * @ret= urn ERROR_SUCCESS on success; An error code otherwise
- * See: https://msdn.microsoft.com/= en-us/library/windows/desktop/aa368072.aspx
- */
-DLLEXP_DECL UINT __stdcall
-ProcessDeferredAction(_In_ MSIHANDLE hInstall);
+ /**
+ * Perform scheduled deferred action.+ *
+ * @param hInstall Handle to the= installation provided to the DLL custom action
+ *
+ * @return ERROR_SUCCESS on success; An error code other= wise
+ * = See: https://msdn.microsoft.com/en-us/library/windows/desktop/aa368072.aspx=
+ */
<= span style=3D"color: hsl(120, 100%, 40%);">+ DLLEXP_DECL UINT __stdcall = ProcessDeferredAction(_In_ MSIHANDLE hInstall);


-/**- * Schedule reboot after instal= lation if reboot
- * in= dication file is found in user's temp directory
- *
- * @param hInstall Handle to the installation provided to= the DLL custom action
= - *
- * @return ERROR_S= UCCESS on success; An error code otherwise
- * See: https://msdn.microsoft.com/en-us/libra= ry/windows/desktop/aa368072.aspx
- */
-DLLEXP_= DECL UINT __stdcall
-Ch= eckAndScheduleReboot(_In_ MSIHANDLE hInstall);
+ /**
+ * Schedule reboot after installation if reboot+ * indication file is fo= und in user's temp directory
+ *
+= * @param hInstall Handle to the installation provided to the DLL = custom action
+ *=
+ * @return ERRO= R_SUCCESS on success; An error code otherwise
+ * See: https://msdn.microsoft.com/en= -us/library/windows/desktop/aa368072.aspx
+ */
+ DLLEXP_DECL UINT __stdcall CheckAndScheduleReboot(_In_ MSIHAN= DLE hInstall);

#ifdef __cplusplus=
}
diff --git a/src/openvpnserv/common.c b/src/op= envpnserv/common.c
index 5543c37..a42c65d 100644
= --- a/src/openvpnserv/common.c
+++ b/src/openvpnserv/= common.c
@@ -29,12 +29,11 @@
static DWORD<= /span>
GetRegString(HKEY key, LPCWSTR value, LPWSTR data, DWORD s= ize, LPCWSTR default_value)
{
- LONG status =3D RegGetValue(key, NULL, value, = RRF_RT_REG_SZ,
- = NULL, (LPBYTE) data, &size);
+ LONG status =3D RegGetValue(key, NU= LL, value, RRF_RT_REG_SZ, NULL, (LPBYTE)data, &size);
=
if (status =3D=3D ERROR_FILE_NOT_FOUND && def= ault_value)
{
- size_t len =3D size/sizeof(data[0]);
+ size_t len =3D size / sizeof(= data[0]);
if (swprintf(data, len, default_value))<= /span>
{
status =3D ERROR_SU= CCESS;
@@ -44,7 +43,10 @@
if (status != =3D ERROR_SUCCESS)
{
SetLastE= rror(status);
- = return MsgToEventLog(M_SYSERR, L"Error querying registry value: HKLM\\= SOFTWARE\\" _L(PACKAGE_NAME) L"%ls\\%ls", service_instance, = value);
+ retu= rn MsgToEventLog(
+ = M_SYSERR,
+= L"Error querying registry value: HKLM\\SOFTWARE\\" _L= (PACKAGE_NAME) L"%ls\\%ls",
+ service_instance, value);
= }

return ERROR_SUCCESS;
= @@ -68,7 +70,8 @@
if (status !=3D ERROR_SUCCESS)=
{
SetLastError(status);
- return MsgToEventL= og(M_SYSERR, L"Could not open Registry key HKLM\\%ls not found", = reg_path);
+ r= eturn MsgToEventLog(M_SYSERR, L"Could not open Registry key HKLM\\%ls = not found",
+ = reg_path);
}

/* The default value of REG_KEY is the install path= */
@@ -79,8 +82,7 @@
goto out;
}

- swprintf(default_value, _countof(default_value), L&quo= t;%ls\\bin\\openvpn.exe",
- install_path);
+ swprintf(default_value, _countof(default_value), L&quo= t;%ls\\bin\\openvpn.exe", install_path);
error = =3D GetRegString(key, L"exe_path", s->exe_path, sizeof(s->e= xe_path), default_value);
if (error !=3D ERROR_SUCCESS= )
{
@@ -88,23 +90,20 @@
}


swprintf(default_value, _co= untof(default_value), L"%ls\\config", install_path);
- error =3D GetRegString(key, L&= quot;config_dir", s->config_dir, sizeof(s->config_dir),
- defau= lt_value);
+ error= =3D GetRegString(key, L"config_dir", s->config_dir, sizeof(s-= >config_dir), default_value);
if (error !=3D ERROR_= SUCCESS)
{
goto out; }

swprintf(default_valu= e, _countof(default_value), L"%ls\\bin", install_path);- error =3D GetRegString(key,= L"bin_dir", s->bin_dir, sizeof(s->bin_dir),
- default_val= ue);

+ error =3D G= etRegString(key, L"bin_dir", s->bin_dir, sizeof(s->bin_dir)= , default_value);
if (error !=3D ERROR_SUCCESS)=
{
goto out;
}<= /span>

- = error =3D GetRegString(key, L"config_ext", s->ext_string, size= of(s->ext_string),
-= L".ovpn");
+ error =3D GetRegString(key, L"config_ext= ", s->ext_string, sizeof(s->ext_string), L".ovpn");
if (error !=3D ERROR_SUCCESS)
{
goto out;
@@ -117,8 +116,7 @@<= br> goto out;
}
=
- error =3D GetRegString(k= ey, L"priority", priority, sizeof(priority),
- L"NORMAL_PRI= ORITY_CLASS");
+= error =3D GetRegString(key, L"priority", priority, sizeof(pri= ority), L"NORMAL_PRIORITY_CLASS");
if (error= !=3D ERROR_SUCCESS)
{
goto o= ut;
@@ -131,8 +129,8 @@
}

/* read if present, else use default */- error =3D GetRegString(key= , L"ovpn_admin_group", s->ovpn_admin_group,
- sizeof(s->ov= pn_admin_group), OVPN_ADMIN_GROUP);
+ error =3D GetRegString(key, L"ovpn_admin_group&quo= t;, s->ovpn_admin_group, sizeof(s->ovpn_admin_group),
+ OVPN_ADMIN= _GROUP);

if (error !=3D ERROR_SUCCESS)
{

goto out;
@@ -185,7 +183,8= @@
else
{
= SetLastError(ERROR_INVALID_DATA);
- error =3D MsgToEventLog(M_ERR, L"Log file appen= d flag (given as '%ls') must be '0' or '1'", a= ppend);
+ erro= r =3D MsgToEventLog(M_ERR, L"Log file append flag (given as '%ls&#= 39;) must be '0' or '1'",
+ append); goto out;
}
@@ -204,10 +203,11 @@
LPWSTR tmp =3D NULL;

error =3D GetLastError();
- len =3D FormatMessage(FORMAT_ME= SSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ARGUMEN= T_ARRAY,

+ len =3D= FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM<= /span>
+ = | FORMAT_MESSAGE_ARGUMENT_ARRAY,
= NULL, error, LANG_NEUTRAL, tmp, 0, NULL);
- if (len =3D=3D 0 || (long)= _countof(buf) < (long) len + 14)
+ if (len =3D=3D 0 || (long)_countof(buf) < (long)len= + 14)
{
buf[0] =3D L'\0&= #39;;
}
@@ -244,8 +244,7 @@
= hEventSource =3D RegisterEventSource(NULL, APPNAME);
<= span> if (hEventSource !=3D NULL)

{
- swprintf(msg[0], _countof(ms= g[0]),

- = L"%ls%ls%ls: %ls", APPNAME, service_instance,
+ swprintf(msg[0], _countof(msg= [0]), L"%ls%ls%ls: %ls", APPNAME, service_instance,
(flags & MSG_FLAGS_ERROR) ? L" error" : = L"", err_msg);


va_star= t(arglist, format);
@@ -253,9 +252,9 @@
= va_end(arglist);

const WCH= AR *mesg[] =3D { msg[0], msg[1] };
- ReportEvent(hEventSource, flags & MSG_FLAGS_ERROR = ?
- = EVENTLOG_ERROR_TYPE : EVENTLOG_INFORMATION_TYPE,
- 0, 0, NULL, 2, 0, mesg, NULL= );
+ ReportEve= nt(hEventSource,
+ = flags & MSG_FLAGS_ERROR ? EVENTLOG_ERROR_TYPE : EVENTL= OG_INFORMATION_TYPE, 0, 0,
+ NULL, 2, 0, mesg, NULL);
= DeregisterEventSource(hEventSource);
}

diff --git a/src/openvpnserv/interactive.c b/src/openv= pnserv/interactive.c
index bc63296..0983e59 100644--- a/src/openvpnserv/interactive.c
+++ b/src/openv= pnserv/interactive.c
@@ -40,32 +40,30 @@
#= include "validate.h"
#include "wfp_block.h&= quot;

-#define IO_TIMEOUT 2000 /*ms*/
+#define IO_TIMEOUT 2000 /*ms*/

-#define ERROR_OPENVPN_STARTUP = 0x20000000

-#define = ERROR_STARTUP_DATA 0x20000001
-#define ERROR_MESSAGE_DATA 0x20000002-#define ERROR_MESSAGE_TYPE = 0x20000003
+#de= fine ERROR_OPENVPN_STARTUP 0x20000000
+#define ERROR_STARTUP_DATA 0x20000001
+#define ERROR_MESSAGE_DATA 0x2000= 0002
+#define ERROR_M= ESSAGE_TYPE 0x20000003

static SERVICE= _STATUS_HANDLE service;
static SERVICE_STATUS status =3D {= .dwServiceType =3D SERVICE_WIN32_SHARE_PROCESS };
static = HANDLE exit_event =3D NULL;
static settings_t settings;
static HANDLE rdns_semaphore =3D NULL;
-#define RDNS_TIMEOUT 600 /* seconds to wai= t for the semaphore */
-#define TUN= _IOCTL_REGISTER_RINGS CTL_CODE(51820U, 0x970U, METHOD_BUFFERED, FILE_READ_D= ATA | FILE_WRITE_DATA)
+ CTL_CODE(51820U, 0x970U, METHOD_BUFFERED, FILE_READ_D= ATA | FILE_WRITE_DATA)

-openvpn_service_t interactive_service =3D {
- interactive,

- _L(PACKAGE_NAME) L"ServiceInte= ractive",
- _L(= PACKAGE_NAME) L" Interactive Service",
- SERVICE_DEPENDENCIES,
- SERVICE_AUTO_START
-};
+openvpn_service_t interactive_service =3D { interactive, _L= (PACKAGE_NAME) L"ServiceInteractive",
+ _L(PA= CKAGE_NAME) L" Interactive Service",
+ SERVIC= E_DEPENDENCIES, SERVICE_AUTO_START };


-typedef struct {=
+typedef struct
<= span style=3D"color: hsl(120, 100%, 40%);">+{

WCHAR *d= irectory;
WCHAR *options;
WCHAR *= std_input;
@@ -73,14 +71,16 @@

=
/* Datatype for linked lists */
-typedef struct _list_item {
+typedef struct _list_item
=
+{
str= uct _list_item *next;
LPVOID data;
} = list_item_t;


/* Dataty= pes for undo information */
-typedef enum {
= +typedef enum
+{
address,
route,
= wfp_block,
@@ -93,19 +93,22 @@
} undo_type= _t;
typedef list_item_t *undo_lists_t[_undo_type_max];

-typedef= struct {
+typedef st= ruct
+{
HANDLE engine;

int index;
= int metric_v4;
int metric_v6;
} wfp_= block_data_t;

-typedef struct {
+typedef struct
+{
char itf_name[256];
PWSTR dom= ains;
} dns_domains_undo_data_t;
<= br>-typedef union {
+typedef union

+{
message_header_t= header;
address_message_t address;
= route_message_t route;
@@ -119,7 +122,8 @@
create_adapter_message_t create_adapter;

} pipe_me= ssage_t;

-typedef struct {
+typedef struct
+{
CHAR addresses[NRPT_ADDR_NUM * NRPT_ADDR_SIZE];<= br> WCHAR domains[512]; /* MULTI_SZ string */
= DWORD domains_size; /* bytes in domains */
@@ -142,7 +146= ,7 @@
return NO_ERROR;
}

-typedef BOOL (*m= atch_fn_t) (LPVOID item, LPVOID ctx);
+typedef BOOL (*match_fn_t)(LPVOID item, LPVOID ctx);

static LPVOID
RemoveListIte= m(list_item_t **pfirst, match_fn_t match, LPVOID ctx)
@@ -2= 01,7 +205,8 @@
}


-typedef enum {
+typedef enum

+{
peek,
= read,
write
@@ -248,8 +253,= 7 @@
handles[i + 1] =3D events[i];
}


- res =3D WaitForMultipleObjects(count + 1, handles, FALSE,- = op =3D=3D peek ? INFINITE : IO_TIMEOUT);
+ res =3D WaitForMultipleObjects(count + 1, handle= s, FALSE, op =3D=3D peek ? INFINITE : IO_TIMEOUT);
if = (res !=3D WAIT_OBJECT_0)
{
Ca= ncelIo(pipe);
@@ -309,32 +313,25 @@
{
DWORD result_len;
LPWSTR result =3D L= "0xffffffff\nFormatMessage failed\nCould not return result";
- DWORD_PTR args[] =3D {=
- (DWORD_PTR) e= rror,
- (DWORD_P= TR) func,
- (DWO= RD_PTR) ""
- = };
+ DWORD_PTR = args[] =3D { (DWORD_PTR)error, (DWORD_PTR)func, (DWORD_PTR) "" };=

if (error !=3D ERROR_OPENVPN_STARTU= P)
{
- FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM
- |FORMAT_MESSAGE_ALLO= CATE_BUFFER
- = |FORMAT_MESSAGE_IGNORE_INSERTS,
- 0, error, 0, (LPWSTR) &ar= gs[2], 0, NULL);
+ = FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BU= FFER
+ = | FORMAT_MESSAGE_IGNORE_INSERTS,
+ 0, error, 0, (LPWSTR)&a= rgs[2], 0, NULL);
}

- result_len =3D FormatMessageW(FORM= AT_MESSAGE_FROM_STRING
= - |FORMAT_MESSAGE_ALLOCATE_BUFFER
= - = |FORMAT_MESSAGE_ARGUMENT_ARRAY,
- L"0x%1!08x!\n%2!s!\n%3!s!&qu= ot;, 0, 0,
- = (LPWSTR) &result, 0, (va_list *) args);
= + result_len =3D FormatMessa= geW(
+ FORMAT_= MESSAGE_FROM_STRING | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_ARGUM= ENT_ARRAY,
+ L= "0x%1!08x!\n%2!s!\n%3!s!", 0, 0, (LPWSTR)&result, 0, (va_list= *)args);

WritePipeAsync(pipe, resul= t, (DWORD)(wcslen(result) * 2), count, events);
MsgToE= ventLog(MSG_FLAGS_ERROR, result);

if= (error !=3D ERROR_OPENVPN_STARTUP)
{
- LocalFree((LPVOID) args[2]);
+ LocalFree((LP= VOID)args[2]);
}
if (result_len)<= /span>
{
@@ -355,7 +352,8 @@
= * Returns true on success, false on error with reason set in errmsg.
*/
static BOOL
-ValidateOptions(HANDLE pipe, const WCHAR *workdir, = const WCHAR *options, WCHAR *errmsg, DWORD capacity)
+ValidateOptions(HANDLE pipe, const WCHAR = *workdir, const WCHAR *options, WCHAR *errmsg,
+ DWORD capacity)
= {
WCHAR **argv;
int argc;=
@@ -380,7 +378,7 @@
}

/* Note: argv[0] is the first option */
- if (argc < 1) /* no options */
+ if (argc < 1) = /* no options */
{
ret =3D TR= UE;
goto out;
@@ -395,8 +393,7 @@<= /span>

if (!CheckOption(workdir, 2, arg= v_tmp, &settings))
{
- swprintf(errmsg, capacity, msg1, ar= gv[0], workdir,
- = settings.ovpn_admin_group);
+ swprintf(errmsg, capacity, msg1, argv[0]= , workdir, settings.ovpn_admin_group);
} goto out;
}
@@ -408,17= +405,15 @@
continue;
= }

- = if (!CheckOption(workdir, argc-i, &argv[i], &settings))
+ if (!CheckOption= (workdir, argc - i, &argv[i], &settings))
= {
- if (wcsc= mp(L"--config", argv[i]) =3D=3D 0 && argc-i > 1)
+ if (wcscmp(L&= quot;--config", argv[i]) =3D=3D 0 && argc - i > 1) {
= - swprintf(errmsg, capacity, msg1, argv[i+1], workdir,
- se= ttings.ovpn_admin_group);
+ swprintf(errmsg, capacity, msg1, argv[i + 1], workdir= , settings.ovpn_admin_group);
}
else

{
- swprintf(errmsg, capacity, msg= 2, argv[i],
- = settings.ovpn_admin_group);
+ swprintf(errmsg, capacity, msg2, arg= v[i], settings.ovpn_admin_group);
}
= goto out;
}
@@ = -505,7 +500,7 @@
return TRUE;
=
err:
- su= d->directory =3D NULL; /* caller must not free() */<= br>+ sud->directory =3D N= ULL; /* caller must not free() */
free(data); return FALSE;
}
@@ -580,7 +57= 5,7 @@

InitializeUnicastIpAddressEnt= ry(addr_row);
addr_row->Address =3D sockaddr_inet(m= sg->family, &msg->address);
- addr_row->OnLinkPrefixLength =3D (UINT8) msg->pre= fix_len;
+ addr_ro= w->OnLinkPrefixLength =3D (UINT8)msg->prefix_len;

if (msg->iface.index !=3D -1)
{=
@@ -662,7 +657,7 @@
fwd_row->Proto= col =3D MIB_IPPROTO_NETMGMT;
fwd_row->Metric =3D ms= g->metric;
fwd_row->DestinationPrefix.Prefix =3D= sockaddr_inet(msg->family, &msg->prefix);
- fwd_row->DestinationPrefix.PrefixLen= gth =3D (UINT8) msg->prefix_len;
+ fwd_row->DestinationPrefix.PrefixLength =3D (UINT8)m= sg->prefix_len;
fwd_row->NextHop =3D sockaddr_in= et(msg->family, &msg->gateway);

if (msg->iface.index !=3D -1)

@@ -740,7 +735,7 @@<= /span>
err_str =3D L"Unknown Win32 Error";
if (FormatMessage(FORMAT_MESSAGE_IGNORE_INSE= RTS | FORMAT_MESSAGE_FROM_SYSTEM
- | FORMAT_MESSAGE_ARGUMENT_ARRAY,+ | F= ORMAT_MESSAGE_ARGUMENT_ARRAY,
NULL, = err, 0, buf, sizeof(buf), NULL))
{
= err_str =3D buf;
@@ -767,13 +762,11 @@
err =3D delete_wfp_block_filters(block_data->engine);
<= br> if (block_data->metric_v4 >=3D 0)
= {
- = set_interface_metric(msg->iface.index, AF_INET,
- block_data-&g= t;metric_v4);
+ = set_interface_metric(msg->iface.index, AF_INET, block_data->met= ric_v4);
}
if (block_data= ->metric_v6 >=3D 0)
{
- set_interface_metric(msg->if= ace.index, AF_INET6,
- = block_data->metric_v6);
+ set_interface_metric(msg= ->iface.index, AF_INET6, block_data->metric_v6);
= }
free(block_data);
}
@@ -809,14 +802,12 @@
block_data->= ;engine =3D engine;
block_data->index =3D msg-&= gt;iface.index;
int is_auto =3D 0;
- block_data->metric_v4 =3D = get_interface_metric(msg->iface.index,

- AF= _INET, &is_auto);
+ block_data->metric_v4 =3D get_interface_metric(msg->iface.i= ndex, AF_INET, &is_auto);
if (is_auto)<= br> {
block_data->metric_v4 = =3D 0;
}
- block_data->metric_v6 =3D get_interface_metric(msg-&= gt;iface.index,
- = AF_INET6, &is_auto);
+ block_data->= metric_v6 =3D get_interface_metric(msg->iface.index, AF_INET6, &is_a= uto);
if (is_auto)
{
block_data->metric_v6 =3D 0;
@@= -825,8 +816,7 @@
err =3D AddListItem(&(*lists= )[wfp_block], block_data);
if (!err)
{

- = err =3D set_interface_metric(msg->iface.index, AF_INET,
- = WFP_BLOCK_IFACE_METRIC);

+ err =3D set_interface_metric(msg->iface.index, AF_= INET, WFP_BLOCK_IFACE_METRIC);
if (!err)
{
/* for IPv6, we = intentionally ignore errors, because
@@ -834,8 +824,7 @@
* admin has disabled IPv6 on the tun/tap/dc= o interface
* (if OpenVPN wants IPv6 ifco= nfig, we'll fail there)
*/
= - set_interface_me= tric(msg->iface.index, AF_INET6,
- WFP_BLOCK_IFACE_METRIC);=
+ set= _interface_metric(msg->iface.index, AF_INET6, WFP_BLOCK_IFACE_METRIC);
}
if (err)<= br> {
@@ -880,7 +869,7 @@
DWORD exit_code;

STARTUPINFOW si;
PROCESS_INFORMATION pi;

- DWORD proc_flags =3D CREATE_NO_WINDOW|CREATE_UNICODE_ENVIRONME= NT;
+ DWORD proc_f= lags =3D CREATE_NO_WINDOW | CREATE_UNICODE_ENVIRONMENT;
= WCHAR *cmdline_dup =3D NULL;

ZeroM= emory(&si, sizeof(si));
@@ -890,8 +879,8 @@
<= span>

/* CreateProcess needs a modifiable cmdline: ma= ke a copy */
cmdline_dup =3D _wcsdup(cmdline);<= br>- if (cmdline_dup &&= ; CreateProcessW(argv0, cmdline_dup, NULL, NULL, FALSE,
- pro= c_flags, NULL, NULL, &si, &pi) )
+ if (cmdline_dup
+ && CreateProcessW(argv0, cmdline_dup, = NULL, NULL, FALSE, proc_flags, NULL, NULL, &si, &pi))
{

WaitForSingleObject(pi.hProcess, timeout= ? timeout : INFINITE);
if (!GetExitCodeProcess(pi= .hProcess, &exit_code))
@@ -905,13 +894,12 @@
/* kill without impunity */ TerminateProcess(pi.hProcess, exit_code);
- MsgToEventLog(M_ERR, L&= quot;ExecCommand: \"%ls %ls\" killed after timeout",
<= br>- arg= v0, cmdline);
+ = MsgToEventLog(M_ERR, L"ExecCommand: \"%ls %ls\" killed= after timeout", argv0, cmdline);
} else if (exit_code)
{
- MsgToEventLog(M_ERR, L= "ExecCommand: \"%ls %ls\" exited with status =3D %lu",<= /span>
- = argv0, cmdline, exit_code);
+ MsgToEventLog(M_ERR, L"ExecCommand: \"%ls= %ls\" exited with status =3D %lu", argv0,
+ cmdline, exit_c= ode);
}
else
{

@@ -924,8 +912,7 @@
els= e
{
exit_code =3D GetLastErro= r();
- MsgToEven= tLog(M_SYSERR, L"ExecCommand: could not run \"%ls %ls\" :&qu= ot;,
- = argv0, cmdline);
+ MsgToEventLog(M_SYSERR, L"ExecCommand: could not run \"= %ls %ls\" :", argv0, cmdline);
}
<= span>

free(cmdline_dup);
@@ -950,12 += 937,12 @@
WCHAR *argv0;
W= CHAR *cmdline;
DWORD timeout;
- } cmds [] =3D {
- { ipcfg, L"ipconfig /flushdns&= quot;, timeout },
= + } cmds[] =3D {
+= { ipcfg, L"ipconfig /flushdns", timeout },
{ ipcfg, L"ipconfig /registerdns", timeout },
};

- HANDLE wait_handles[2] =3D {rdns_semaphore, exit_event};
+ HANDLE wait_handle= s[2] =3D { rdns_semaphore, exit_event };

= swprintf(ipcfg, MAX_PATH, L"%ls\\%ls", get_win_sys_path(), L= "ipconfig.exe");

@@ -967,9 +954= ,10 @@
ExecCommand(cmds[i].argv0, cmds[i].cmdl= ine, cmds[i].timeout);
}
= err =3D 0;
- if = (!ReleaseSemaphore(rdns_semaphore, 1, NULL) )
+ if (!ReleaseSemaphore(rdns_semaphore, 1, = NULL))
{
- err =3D MsgToEventLog(M_SYSERR, L"RegisterDNS:= Failed to release regsiter-dns semaphore:");
+ err =3D
+ MsgToEventLog(M_SYSERR, L&qu= ot;RegisterDNS: Failed to release regsiter-dns semaphore:"); }
}
else@@ -1046,7 +1034,7 @@

/* max= cmdline length in wchars -- include room for worst case and some */=
size_t ncmdline =3D wcslen(fmt) + wcslen(if_name) + wcslen(a= ction) + wcslen(addr)
-= +wcslen(addr_static) + 32 + 1;
+ + wcslen(addr_stati= c) + 32 + 1;
cmdline =3D malloc(ncmdline * sizeof(wcha= r_t));
if (!cmdline)
{
= @@ -1078,13 +1066,8 @@
static BOOL
= ApplyGpolSettings32(void)
{
- typedef NTSTATUS (__stdcall *publish_fn_t)(
- DWORD StateNameLo,=
- DWORD StateNa= meHi,
- DWORD Ty= peId,
- DWORD Bu= ffer,
- DWORD Le= ngth,
- DWORD Ex= plicitScope);
+ ty= pedef NTSTATUS(__stdcall * publish_fn_t)(DWORD StateNameLo, DWORD StateName= Hi, DWORD TypeId,
+ = DWORD Buffer, DWORD Length, DW= ORD ExplicitScope);
publish_fn_t RtlPublishWnfStateDat= a;
const DWORD WNF_GPOL_SYSTEM_CHANGES_HI =3D 0x0D891E= 2A;
const DWORD WNF_GPOL_SYSTEM_CHANGES_LO =3D 0xA3BC0= 875;
@@ -1095,13 +1078,14 @@
retur= n FALSE;
}

- RtlPublishWnfStateData =3D (publish_fn_t) G= etProcAddress(ntdll, "RtlPublishWnfStateData");
+ RtlPublishWnfStateData =3D (publi= sh_fn_t)GetProcAddress(ntdll, "RtlPublishWnfStateData"); if (RtlPublishWnfStateData =3D=3D NULL)
{=
return FALSE;
}

- if (RtlPubli= shWnfStateData(WNF_GPOL_SYSTEM_CHANGES_LO, WNF_GPOL_SYSTEM_CHANGES_HI, 0, 0= , 0, 0) !=3D ERROR_SUCCESS)
+ if (RtlPublishWnfStateData(WNF_GPOL_SYSTEM_CHANGES_LO, WNF_GPOL= _SYSTEM_CHANGES_HI, 0, 0, 0, 0)
+ !=3D ERROR_SUCCESS)
{
return FALSE;

}
@@ -1118,= 12 +1102,8 @@
static BOOL
ApplyGpolSettin= gs64(void)
{
- typedef NTSTATUS (*publish_fn_t)(
- INT64 StateName,
- INT64 TypeId,
- INT64 Buffer,
- unsigned int Length,
- INT64 ExplicitScope);
<= span style=3D"color: hsl(120, 100%, 40%);">+ typedef NTSTATUS (*publish_= fn_t)(INT64 StateName, INT64 TypeId, INT64 Buffer,

+ unsigne= d int Length, INT64 ExplicitScope);
publish_fn_t RtlPu= blishWnfStateData;
const INT64 WNF_GPOL_SYSTEM_CHANGES= =3D 0x0D891E2AA3BC0875;

@@ -1133,7 +1113= ,7 @@
return FALSE;
}<= br>
- RtlPubl= ishWnfStateData =3D (publish_fn_t) GetProcAddress(ntdll, "RtlPublishWn= fStateData");
+ = RtlPublishWnfStateData =3D (publish_fn_t)GetProcAddress(ntdll, "Rtl= PublishWnfStateData");
if (RtlPublishWnfStateData= =3D=3D NULL)
{
return FALSE;=
@@ -1183,24 +1163,21 @@
scm =3D OpenS= CManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
if (scm = =3D=3D NULL)
{
- MsgToEventLog(M_ERR, L"%S: OpenSCManager call fa= iled (%lu)",
- = __func__, GetLastError());
+ MsgToEventLog(M_ERR, L"%S: OpenSCMana= ger call failed (%lu)", __func__, GetLastError());
= goto out;
}

= dnssvc =3D OpenServiceA(scm, "Dnscache", SERVICE_PAUSE_CONTINU= E);
if (dnssvc =3D=3D NULL)
{
- MsgToEventLog(M_E= RR, L"%S: OpenService call failed (%lu)",
- __func__, GetLastErro= r());
+ MsgToE= ventLog(M_ERR, L"%S: OpenService call failed (%lu)", __func__, Ge= tLastError());
goto out;
}

SERVICE_STATUS status;
if (ControlService(dnssvc, SERVICE_CONTROL_PARAMCHANGE, &status) = =3D=3D 0)

{
- MsgToEventLog(M_ERR, L"%S: ControlService call fail= ed (%lu)",
- = __func__, GetLastError());
+ MsgToEventLog(M_ERR, L"%S: ControlServi= ce call failed (%lu)", __func__, GetLastError());
= goto out;
}

@@ = -1328,8 +1305,7 @@
*gpol =3D FALSE;
<= /span>
/* Try the group policy search list */
- err =3D RegOpenKeyExA(HKEY_LOCAL_= MACHINE,

- = "SOFTWARE\\Policies\\Microsoft\\Windows NT\\DNSClient"= ,
+ err =3D RegOpe= nKeyExA(HKEY_LOCAL_MACHINE, "SOFTWARE\\Policies\\Microsoft\\Windows NT= \\DNSClient",
0, KEY_ALL_ACCE= SS, key);
if (!err)
{
<= span>@@ -1342,9 +1318,9 @@

}
<= br> /* Try the system-wide search list */
- err =3D RegOpenKeyExA(HKEY_LOCAL_MACHIN= E,
- = "System\\CurrentControlSet\\Services\\TCPIP\\Parameters",
- = 0, KEY_ALL_ACCESS, key);
+ err =3D
+ = RegOpenKeyExA(HKEY_LOCAL_MACHINE, "System\\CurrentControlSet\\Ser= vices\\TCPIP\\Parameters",
+ 0, KEY_ALL_ACCESS, key);
= if (!err)
{
if (HasValid= SearchList(*key))
@@ -1362,9 +1338,10 @@
= if (!iid_err)
{
= HKEY itfs;
- = err =3D RegOpenKeyExA(HKEY_LOCAL_MACHINE,
- "System\\Curren= tControlSet\\Services\\TCPIP\\Parameters\\Interfaces",
- 0, KE= Y_ALL_ACCESS, &itfs);

+ err =3D
+ RegOpenKeyExA(HKEY_LOCAL_MACHINE,
+ "Sys= tem\\CurrentControlSet\\Services\\TCPIP\\Parameters\\Interfaces",
+ = 0, KEY_ALL_ACCESS, &itfs);
if (!err)=
{
err =3D Re= gOpenKeyExW(itfs, iid, 0, KEY_ALL_ACCESS, key);
@@ -1400,8 = +1377,7 @@
{
return F= ALSE;
}
- MsgToEventLog(M_ERR, L"%S: failed to get InitialSea= rchList (%lu)",
- = __func__, err);
+ MsgToEventLog(M_ERR, L"%S: failed to get Init= ialSearchList (%lu)", __func__, err);
}
return TRUE;
@@ -1436,8 +1412= ,7 @@
LSTATUS err =3D RegSetValueExW(key, L"Initi= alSearchList", 0, REG_SZ, (PBYTE)list, size);
if = (err)
{
- MsgToEventLog(M_ERR, L"%S: failed to set InitialSearchL= ist value (%lu)",
= - __func__, err);
+ MsgToEventLog(M_ERR, L"%S: failed to set In= itialSearchList value (%lu)", __func__, err);
= return FALSE;
}

@@ = -1457,7 +1432,7 @@
AddDnsSearchDomains(HKEY key, BOOL have= _list, PCWSTR domains)
{
LSTATUS err;=
- WCHAR list[2048] = =3D {0};
+ WCHAR l= ist[2048] =3D { 0 };
DWORD size =3D sizeof(list);

if (have_list)
@@ -1465,= 8 +1440,8 @@
err =3D RegGetValueW(key, NULL, L&quo= t;SearchList", RRF_RT_REG_SZ, NULL, list, &size);
= if (err)
{
- MsgToEventLog(M_SYSERR, L"%S: could= not get SearchList from registry (%lu)",
- __func__, err);+ MsgToEventLog(M_= SYSERR, L"%S: could not get SearchList from registry (%lu)", __fu= nc__,
+ = err);
return FALSE;
}


@@ -1498,8 +1473,7 @@=
err =3D RegSetValueExW(key, L"SearchList", 0, REG_= SZ, (PBYTE)list, size);
if (err)
= {
- MsgToEventLo= g(M_SYSERR, L"%S: could not set SearchList to registry (%lu)",
- __= func__, err);
+ = MsgToEventLog(M_SYSERR, L"%S: could not set SearchList to registry (= %lu)", __func__, err);
return FALSE; }

@@ -1540,8 +1514,7 @@
err =3D RegSetValueExW(key, L"SearchList", 0, RE= G_SZ, (PBYTE)list, size);
if (err)
= {
- MsgToEvent= Log(M_SYSERR, L"%S: could not set SearchList in registry (%lu)",<= /span>
- = __func__, err);
+ = MsgToEventLog(M_SYSERR, L"%S: could not set SearchList in registry= (%lu)", __func__, err);
goto out;
= }

@@ -1568,8 +1541,7 @@=
err =3D RegGetValueW(key, NULL, L"SearchList", RRF= _RT_REG_SZ, NULL, list, &size);
if (err) {
- = MsgToEventLog(M_SYSERR, L"%S: could not get SearchList from registry (= %lu)",
- = __func__, err);
+ MsgToEventLog(M_SYSERR, L"%S: could not get SearchList= from registry (%lu)", __func__, err);
return= ;
}

@@ -1613,8 +1585= ,7 @@
err =3D RegSetValueExW(key, L"SearchList&qu= ot;, 0, REG_SZ, (PBYTE)list, size);
if (err) {
- = MsgToEventLog(M_SYSERR, L"%S: could not set SearchList in registry (%l= u)",
- = __func__, err);
+ MsgToEventLog(M_SYSERR, L"%S: could not set SearchList i= n registry (%lu)", __func__, err);
}
}


@@ -1732,8 +1703,8 @@
GetInterfacesKey(short family, PHKEY key)

{ PCSTR itfs_key =3D family =3D=3D AF_INET6
- ? "SYSTEM\\CurrentControlSet\\= Services\\Tcpip6\\Parameters\\Interfaces"
- : "SYSTEM\\CurrentControlSet\\Service= s\\Tcpip\\Parameters\\Interfaces";
+ ? "SYSTEM\\CurrentControl= Set\\Services\\Tcpip6\\Parameters\\Interfaces"
+ : "SYSTEM\\= CurrentControlSet\\Services\\Tcpip\\Parameters\\Interfaces";
LSTATUS err =3D RegOpenKeyExA(HKEY_LOCAL_MACH= INE, itfs_key, 0, KEY_ALL_ACCESS, key);
if (err)
@@ -1842,11 +1813,12 @@
return ERROR_ME= SSAGE_DATA;
}

- /* use a non-const reference with limit= ed scope to enforce null-termination of strings from client */
+ /* use a non-const reference= with limited scope to enforce null-termination of strings from

<= span style=3D"color: hsl(120, 100%, 40%);">+ * client */

{

- dns_c= fg_message_t *msgptr =3D (dns_cfg_message_t *) msg;
- msgptr->iface.name[_countof(msg-= >iface.name)-1] =3D '\0';
- msgptr->domains[_countof(msg->domains)-1] =3D = '\0';
+ = dns_cfg_message_t *msgptr =3D (dns_cfg_message_t *)msg;
+ msgptr->iface.name[_counto= f(msg->iface.name) - 1] =3D '\0';
+ msgptr->domains[_countof(msg->domain= s) - 1] =3D '\0';
}
WCHAR iid[64];
@@ -1878,7 +1850,7 @@ err =3D SetDnsSearchDomains(msg->iface.name, NULL, &= amp;gpol, lists);
}
Apply= DnsSettings(gpol);
- = return err; /* job done */
+ return err; /* job done */
}

if (msg->addr_len > 0)
<= span>@@ -2100,8 +2072,7 @@

s--;
= }

- if (inet_ntop(AF_INET6, &in_addrs[i],
- = pos, s) !=3D NULL)
+ = if (inet_ntop(AF_INET6, &in_addrs[i], pos, s) !=3D NULL)
{
*size =3D 0;
return ERROR_MORE_DATA;
@@ = -2188,7 +2159,7 @@
LSTATUS err =3D ERROR_FILE_NOT_FOUN= D;
const DWORD buf_size =3D *size;
= const size_t one_glyph =3D sizeof(*domains);
- PWSTR values[] =3D { L"SearchList", = L"Domain", L"DhcpDomainSearchList", L"DhcpDomain&q= uot;, NULL};
+ PWS= TR values[] =3D { L"SearchList", L"Domain", L"Dhcp= DomainSearchList", L"DhcpDomain", NULL };
<= /span>
for (int i =3D 0; values[i]; i++)
= {
@@ -2284,7 +2255,8 @@
/* Get GUID f= rom string */
if (IIDFromString(iid_str, &iid) != =3D S_OK)
{
- MsgToEventLog(M_SYSERR, L"%S: could not convert int= erface %s GUID string", __func__, iid_str);
+ MsgToEventLog(M_SYSERR, L"%S: cou= ld not convert interface %s GUID string", __func__,
+ iid_str);=
goto out;
}

@@ -2326,8 +2298,7 @@
HKEY v4_itfs =3D INVA= LID_HANDLE_VALUE;
HKEY v6_itfs =3D INVALID_HANDLE_VALU= E;

- = if (!GetInterfacesKey(AF_INET, &v4_itfs)
- || !GetInterfacesKey(AF_INET6, &v6_it= fs))
+ if (!GetInt= erfacesKey(AF_INET, &v4_itfs) || !GetInterfacesKey(AF_INET6, &v6_it= fs))
{
goto out;
}

@@ -2338,8 +2309,8 @@
{
WCHAR itf_guid[MAX_PATH];
DW= ORD itf_guid_len =3D _countof(itf_guid);
- LSTATUS err =3D RegEnumKeyExW(v4_itfs, enum_inde= x++, itf_guid, &itf_guid_len,
- NULL, NULL, NULL, NULL);
+ LSTATUS err = =3D
+ RegE= numKeyExW(v4_itfs, enum_index++, itf_guid, &itf_guid_len, NULL, NULL, N= ULL, NULL);
if (err)
{
if (err !=3D ERROR_NO_MORE_ITEMS)
@@ -2358,7 +2329,8 @@

HKEY v4_itf;
if (RegOpenKeyExW(v4_itfs, itf_guid, 0, KEY_READ, &v4_itf) = !=3D NO_ERROR)

{
- MsgToEventLog(M_SYSERR, L"%S: could no= t open interface %s v4 registry key", __func__, itf_guid);
<= span style=3D"color: hsl(120, 100%, 40%);">+ MsgToEventLog(M_SYS= ERR, L"%S: could not open interface %s v4 registry key", __func__= ,

+ = itf_guid);
goto out;
= }

@@ -2370,7 +2342,8 @@ {
if (err !=3D ERROR_FILE_NOT_= FOUND)
{
- MsgToEventLog(M_SYSERR, L"%S: could no= t read interface %s domain suffix", __func__, itf_guid);
+ MsgToEventLog(M_S= YSERR, L"%S: could not read interface %s domain suffix", __func__= ,

+ = itf_guid);
}
= goto next_itf;
}
@@ -2393,= 7 +2366,8 @@
HKEY v6_itf;
= if (RegOpenKeyExW(v6_itfs, itf_guid, 0, KEY_READ, &v6_itf) != =3D NO_ERROR)
{
- MsgToEventLog(M_SYSERR, L"%S: c= ould not open interface %s v6 registry key", __func__, itf_guid);
+ MsgToEve= ntLog(M_SYSERR, L"%S: could not open interface %s v6 registry key"= ;,
+ = __func__, itf_guid);
goto nex= t_itf;
}
err =3D = GetItfDnsServersV6(v6_itf, v6_addrs, &v6_addrs_size);
@= @ -2441,8 +2415,8 @@
* @return NO_ERROR on success, or Wi= ndows error code
*/
static DWORD<= br>-SetNrptRule(HKEY nrpt_key, PC= WSTR subkey, PCSTR address,
- PCWSTR domains, DWORD dom_size, BOOL dnssec)
+SetNrptRule(HKEY nrpt_key, PCWST= R subkey, PCSTR address, PCWSTR domains, DWORD dom_size,

+ BOOL dnssec)
{

/* Create rule subkey */
DW= ORD err =3D NO_ERROR;
@@ -2461,7 +2435,8 @@
}


/* Set DNS Server address */=
- err =3D RegSetVal= ueExA(rule_key, "GenericDNSServers", 0, REG_SZ, (PBYTE)address, s= trlen(address) + 1);
= + err =3D RegSetValueExA(rule_key, "GenericDNSServers", 0, REG= _SZ, (PBYTE)address,
= + strlen(address) + 1);
if (er= r)
{
goto out;
@@ -2472,21 +2447,24 @@

if (dnssec)
= {
reg_val =3D 1;
- err =3D RegSetValueExA(rule_key, "DNS= SECValidationRequired", 0, REG_DWORD, (PBYTE)&reg_val, sizeof(reg_= val));
+ err = =3D RegSetValueExA(rule_key, "DNSSECValidationRequired", 0, REG_D= WORD, (PBYTE)&reg_val,
+ sizeof(reg_val));
= if (err)
{
goto o= ut;
}

r= eg_val =3D 0;
- = err =3D RegSetValueExA(rule_key, "DNSSECQueryIPSECRequired", 0, R= EG_DWORD, (PBYTE)&reg_val, sizeof(reg_val));
+ err =3D RegSetValueExA(rule_key, "= ;DNSSECQueryIPSECRequired", 0, REG_DWORD, (PBYTE)&reg_val,<= br>+ = sizeof(reg_val));
if (err)
= {
goto out;
}

reg_val =3D 0;
- err =3D RegSetValueExA(rule_key, &= quot;DNSSECQueryIPSECEncryption", 0, REG_DWORD, (PBYTE)&reg_val, s= izeof(reg_val));
+ = err =3D RegSetValueExA(rule_key, "DNSSECQueryIPSECEncryption"= ;, 0, REG_DWORD, (PBYTE)&reg_val,
+ sizeof(reg_val));
= if (err)
{
= goto out;
@@ -2495,7 +2473,8 @@

/* Set NRPT config options */
reg_val= =3D dnssec ? 0x0000000A : 0x00000008;
- err =3D RegSetValueExA(rule_key, "ConfigOptions&q= uot;, 0, REG_DWORD, (const PBYTE)&reg_val, sizeof(reg_val));
= + err =3D RegSetValueExA(rul= e_key, "ConfigOptions", 0, REG_DWORD, (const PBYTE)&reg_val,<= /span>
+ = sizeof(reg_val));
if (err)
{=
goto out;
@@ -2653,7 +2632,8 @@
* remains in the registry even if the last GP-NRPT rul= e is deleted.
*/
static PCSTR gp= ol_key =3D "SOFTWARE\\Policies\\Microsoft\\Windows NT\\DNSClient\\DnsP= olicyConfig";
- = static PCSTR sys_key =3D "SYSTEM\\CurrentControlSet\\Services\\Dnscac= he\\Parameters\\DnsPolicyConfig";
+ static PCSTR sys_key =3D
+ "SYSTEM\\CurrentControlSet\\Servic= es\\Dnscache\\Parameters\\DnsPolicyConfig";
HKEY nrpt;
*gpol =3D TRUE;
@@ -2661,7 +2641,8 @@

if (err =3D=3D ERROR_FILE_NOT_= FOUND)
{
*gpol =3D FALSE;
- err =3D RegCreate= KeyExA(HKEY_LOCAL_MACHINE, sys_key, 0, NULL, 0, KEY_ALL_ACCESS, NULL, &= nrpt, NULL);
+ = err =3D RegCreateKeyExA(HKEY_LOCAL_MACHINE, sys_key, 0, NULL, 0, KEY_ALL_A= CCESS, NULL, &nrpt,
+ NULL);
if (err)<= /span>
{
nrpt =3D INVALID_HA= NDLE_VALUE;
@@ -2763,15 +2744,14 @@
* @re= turn NO_ERROR on success, or a Windows error code
*/
static DWORD
-HandleDNSConfigNrptMessage(const nrpt_dns_cfg_message_t *msg,- DWOR= D ovpn_pid, undo_lists_t *lists)
+HandleDNSConfigNrptMessage(const nrpt_dns_cfg_message_t *msg, = DWORD ovpn_pid, undo_lists_t *lists)
{
= /*
* Use a non-const reference with limited scope t= o
* enforce null-termination of strings from client
*/
{
- nrpt_dns_cfg_message_t *msgptr =3D (nrpt_d= ns_cfg_message_t *) msg;
+ nrpt_dns_cfg_message_t *msgptr =3D (nrpt_dns_cfg_message_t *)m= sg;
msgptr->iface.name[_countof(msg->iface.n= ame) - 1] =3D '\0';
msgptr->search_doma= ins[_countof(msg->search_domains) - 1] =3D '\0';
msgptr->resolve_domains[_countof(msg->resolve_domains) - 1]= =3D '\0';

@@ -2864,7 +2844,8 @@
<= /span>
/* Set NRPT rules */
BOOL dnssec = =3D (msg->flags & nrpt_dnssec) !=3D 0;
- err =3D SetNrptRules(key, msg->addresses, ms= g->resolve_domains, msg->search_domains, dnssec, ovpn_pid);+ err =3D SetNrptRules(key,= msg->addresses, msg->resolve_domains, msg->search_domains, dnssec= ,
+ = ovpn_pid);
if (err)
{=
goto out;
@@ -2907,7 +2888,8 @@ return ERROR_MESSAGE_DATA;
}
- /* use a= non-const reference with limited scope to enforce null-termination of stri= ngs from client */
+ = /* use a non-const reference with limited scope to enforce null-terminat= ion of strings from
+= * client */
{
wins_cfg_m= essage_t *msgptr =3D (wins_cfg_message_t *)msg;
ms= gptr->iface.name[_countof(msg->iface.name) - 1] =3D '\0';
@@ -2934,7 +2916,7 @@

i= f (msg->header.type =3D=3D msg_del_wins_cfg)
{
- goto out; /* job = done */
+ goto= out; /* job done */
}

for (int i =3D 0; i < addr_len; ++i)

@@ -2988,7 = +2970,7 @@
* 10 chars for 32 bit int in decimal and += 1 for NUL
*/
size_t ncmdline =3D= wcslen(fmt) + 10 + 1;
= - wchar_t *cmdline =3D malloc(ncmdline*sizeof(wchar_t));
+ wchar_t *cmdline =3D malloc(ncm= dline * sizeof(wchar_t));

if (!cmdline)
{

err =3D ERROR_OUTOFMEMORY;
@@ -3073,16 +3055,12 @@

}

static VOID

-Handl= eMessage(HANDLE pipe, PPROCESS_INFORMATION proc_info,
- DWORD bytes, DWORD count, LPH= ANDLE events, undo_lists_t *lists)
+HandleMessage(HANDLE pipe, PPROCESS_INFORMATION proc_info, D= WORD bytes, DWORD count,
+ LPHANDLE events, undo_lists_t *lists)
{=
pipe_message_t msg;
ack_message_= t ack =3D {
- .h= eader =3D {
- = .type =3D msg_acknowledgement,
- .size =3D sizeof(ack),
- .message_id =3D -1
- },
+ .header =3D { .type =3D msg_acknowledgement= , .size =3D sizeof(ack), .message_id =3D -1 },
.er= ror_number =3D ERROR_MESSAGE_DATA
};
=
@@ -3264,27 +3242,24 @@
STARTUPINFOW = startup_info;
PROCESS_INFORMATION proc_info; LPVOID user_env =3D NULL;
- WCHAR ovpn_pipe_name[256]; /* The entire pipe name stri= ng can be up to 256 characters long according to MSDN. */
+ WCHAR ovpn_pipe_name[256]; /* The= entire pipe name string can be up to 256 characters long
+ acc= ording to MSDN. */
LPCWSTR exe_path;
= WCHAR *cmdline =3D NULL;
size_t cmdline_size;
undo_lists_t undo_lists;
WCHAR errmsg= [512] =3D L"";

- SECURITY_ATTRIBUTES inheritable =3D {
- .nLength =3D sizeof(inheri= table),

- .lpSec= urityDescriptor =3D NULL,
- .bInheritHandle =3D TRUE
- };
+ SECURITY_ATTRIBUTES inheritable =3D { .nLength =3D sizeof(inheritable= ),
+ = .lpSecurityDescriptor =3D NULL,
+ = .bInheritHandle =3D TRUE };

PACL ovp= n_dacl;
EXPLICIT_ACCESS ea[2];
SE= CURITY_DESCRIPTOR ovpn_sd;
- SECURITY_ATTRIBUTES ovpn_sa =3D {
- .nLength =3D sizeof(ovpn_sa),
- .lpSecurityDescriptor =3D &= ;ovpn_sd,
- .bIn= heritHandle =3D FALSE
-= };
+ SECURITY_= ATTRIBUTES ovpn_sa =3D { .nLength =3D sizeof(ovpn_sa),
+ .lpS= ecurityDescriptor =3D &ovpn_sd,
+ .bInheritHandle =3D FAL= SE };

ZeroMemory(&ea, sizeof(ea)= );
ZeroMemory(&startup_info, sizeof(startup_info))= ;
@@ -3370,7 +3345,8 @@
* OR user is = authorized to run any config.
*/
= if (!ValidateOptions(pipe, sud.directory, sud.options, errmsg, _countof(er= rmsg))
- &&a= mp; !IsAuthorizedUser(ovpn_user->User.Sid, imp_token, settings.ovpn_admi= n_group, settings.ovpn_service_user))
+ && !IsAuthorizedUser(ovpn_user->User.S= id, imp_token, settings.ovpn_admin_group,
+ settings.ovpn_service_us= er))
{
ReturnError(pipe, ERRO= R_STARTUP_DATA, errmsg, 1, &exit_event);
goto = out;
@@ -3382,14 +3358,14 @@
ea[0].grf= Inheritance =3D NO_INHERITANCE;
ea[0].Trustee.TrusteeF= orm =3D TRUSTEE_IS_SID;
ea[0].Trustee.TrusteeType =3D = TRUSTEE_IS_UNKNOWN;
- = ea[0].Trustee.ptstrName =3D (LPWSTR) svc_user->User.Sid;
- ea[1].grfAccessPermissions =3D = READ_CONTROL | SYNCHRONIZE | PROCESS_VM_READ

- |SYNCHRONIZE | PROC= ESS_TERMINATE | PROCESS_QUERY_INFORMATION;
+ ea[0].Trustee.ptstrName =3D (LPWSTR)svc_user->= ;User.Sid;
+ ea[1]= .grfAccessPermissions =3D READ_CONTROL | SYNCHRONIZE | PROCESS_VM_READ | SY= NCHRONIZE
+ = | PROCESS_TERMINATE | PROCESS_QUERY_INFORMATION;
ea[1].grfAccessMode =3D SET_ACCESS;
= ea[1].grfInheritance =3D NO_INHERITANCE;
ea[1].Trustee= .TrusteeForm =3D TRUSTEE_IS_SID;
ea[1].Trustee.Trustee= Type =3D TRUSTEE_IS_UNKNOWN;
- ea[1].Trustee.ptstrName =3D (LPWSTR) ovpn_user->User.Sid;
+ ea[1].Trustee.ptstr= Name =3D (LPWSTR)ovpn_user->User.Sid;

= /* Set owner and DACL of OpenVPN security descriptor */
if (!SetSecurityDescriptorOwner(&ovpn_sd, svc_user->User.Sid,= FALSE))

@@ -3416,8 +3392,8 @@
}

/* use /dev/null for stdout of openvpn (c= lient should use --log for output) */
- stdout_write =3D CreateFile(_L("NUL"), GENERI= C_WRITE, FILE_SHARE_WRITE,
- &inheritable, OPEN_EXISTING, 0, NULL= );
+ stdout_write = =3D CreateFile(_L("NUL"), GENERIC_WRITE, FILE_SHARE_WRITE, &i= nheritable,
+ = OPEN_EXISTING, 0, NULL);
if (std= out_write =3D=3D INVALID_HANDLE_VALUE)
{
ReturnLastError(pipe, L"CreateFile for stdout");
@@ -3432,18 +3408,19 @@
}
=
swprintf(ovpn_pipe_name, _countof(ovpn_pipe_name),
- L"\\\= \.\\pipe\\" _L(PACKAGE) L"%ls\\service_%lu", service_instanc= e, GetCurrentThreadId());
- ovpn_pipe =3D CreateNamedPipe(ovpn_pipe_name,
- PIPE_ACCESS= _DUPLEX | FILE_FLAG_FIRST_PIPE_INSTANCE | FILE_FLAG_OVERLAPPED,
<= span style=3D"color: hsl(0, 100%, 40%);">- P= IPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT, 1, 128, 128, 0, NULL)= ;

+ L&quo= t;\\\\.\\pipe\\" _L(PACKAGE) L"%ls\\service_%lu", service_in= stance,
+ = GetCurrentThreadId());
+ ovpn_pipe =3D CreateNamedPipe(
+ ovpn_pipe_name, PIPE_ACCESS_DUPLEX | FILE_FLAG_F= IRST_PIPE_INSTANCE | FILE_FLAG_OVERLAPPED,
+ PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | = PIPE_WAIT, 1, 128, 128, 0, NULL);
if (ovpn_pipe =3D=3D= INVALID_HANDLE_VALUE)
{
Retu= rnLastError(pipe, L"CreateNamedPipe");
g= oto out;
}

- svc_pipe =3D CreateFile(ovpn_pipe_name, GEN= ERIC_READ | GENERIC_WRITE, 0,
- &inheritable, OPEN_EXISTING, 0, NULL)= ;
+ svc_pipe =3D C= reateFile(ovpn_pipe_name, GENERIC_READ | GENERIC_WRITE, 0, &inheritable= ,
+ = OPEN_EXISTING, 0, NULL);
if (svc_pipe =3D=3D I= NVALID_HANDLE_VALUE)
{
Return= LastError(pipe, L"CreateFile");
@@ -3467,8 +3444,= 8 @@
/* there seem to be no common printf specifier th= at works on all
* mingw/msvc platforms without tricke= ry, so convert to void* and use
* PRIuPTR to print th= at as best compromise */
- = sud.options, (uintptr_t)svc_pipe);
+ swprintf(cmdline, cmdline_size, L"openvpn %ls = --msg-channel %" PRIuPTR, sud.options,
+ (uintptr_t)svc_pipe);
=
if (!CreateEnvironmentBlock(&user_env, imp_token= , FALSE))
{
@@ -3527,7 +3504,10 @@

if (bytes > sizeof(pipe_message_t))
{

/* process at the other side of t= he pipe is misbehaving, shut it down */
- MsgToEventLog(MSG_FLAGS_ERROR, L"OpenVPN= process sent too large payload length to the pipe (%lu bytes), it will be = terminated", bytes);
+ MsgToEventLog(
+ MSG_FLAGS_ERROR,
+ L"OpenVPN process sent too l= arge payload length to the pipe (%lu bytes), it will be terminated",
+ bytes= );
break;
}
@@ -3543,8 +3523,7 @@
else if= (exit_code !=3D 0)
{
WCHAR b= uf[256];
- swpri= ntf(buf, _countof(buf),
- L"OpenVPN exited with error: exit code =3D %lu"= ;, exit_code);
+ = swprintf(buf, _countof(buf), L"OpenVPN exited with error: exit code= =3D %lu", exit_code);
ReturnError(pipe, ERRO= R_OPENVPN_STARTUP, buf, 1, &exit_event);
}<= br> Undo(&undo_lists);
@@ -3607,17 +3586,19 @= @
* allow read/write for authenticated users * deny all access to anonymous
*/
- const WCHAR *sddlString= =3D L"D:(A;OICI;GA;;;S-1-5-18)(D;OICI;0x4;;;S-1-1-0)(A;OICI;GRGW;;;S-= 1-5-11)(D;;GA;;;S-1-5-7)";
+ const WCHAR *sddlString =3D
+ L"D:(A;OICI;GA;;;S-1-5-18)(D;OICI;0x4;= ;;S-1-1-0)(A;OICI;GRGW;;;S-1-5-11)(D;;GA;;;S-1-5-7)";
=
PSECURITY_DESCRIPTOR sd =3D NULL;
- if (!ConvertStringSecurityDescriptor= ToSecurityDescriptor(sddlString, SDDL_REVISION_1, &sd, NULL))+ if (!ConvertStringSecurit= yDescriptorToSecurityDescriptor(sddlString, SDDL_REVISION_1, &sd,
+ = NULL))
{ MsgToEventLog(M_SYSERR, L"ConvertStringSecurityDescrip= torToSecurityDescriptor failed.");
return INV= ALID_HANDLE_VALUE;
}

/* Set up SECURITY_ATTRIBUTES */

- SECURITY_ATTRIBUTES sa =3D {0};
+ SECURITY_ATTRIBUTES sa =3D { 0 };
sa.nLength =3D sizeof(SECURITY_ATTRIBUTES);
sa.lpSecurityDescriptor =3D sd;

sa.bInheritHan= dle =3D FALSE;
@@ -3631,11 +3612,13 @@
= first =3D FALSE;
}

- WCHAR pipe_name[256]; /* The e= ntire pipe name string can be up to 256 characters long according to MSDN. = */

- swprintf(pipe_n= ame, _countof(pipe_name), L"\\\\.\\pipe\\" _L(PACKAGE) L"%ls= \\service", service_instance);
- HANDLE pipe =3D CreateNamedPipe(pipe_name, flags,<= br>- = PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_REJECT_REMOTE_CLIENTS= ,
- = PIPE_UNLIMITED_INSTANCES, 1024, 1024, 0, &sa);
= + WCHAR pipe_name[256]; /* T= he entire pipe name string can be up to 256 characters long according
+ = to MSDN. */
+ = swprintf(pipe_name, _countof(pipe_name), L"\\\\.\\pipe\\" _L(PACK= AGE) L"%ls\\service",
+ service_instance);
+ HANDLE pipe =3D CreateNamedPipe(
+ pipe_name, flags, PIPE_TYP= E_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_REJECT_REMOTE_CLIENTS,

<= span style=3D"color: hsl(120, 100%, 40%);">+ PIPE_UNLIMITED_INSTANCE= S, 1024, 1024, 0, &sa);


LocalFre= e(sd);

@@ -3650,8 +3633,8 @@


static DWORD
-UpdateWaitHandles(LPHANDLE *handles_ptr, LP= DWORD count,
- = HANDLE io_event, HANDLE exit_event, list_item_t *threads)+UpdateWaitHandles(LPHANDLE *= handles_ptr, LPDWORD count, HANDLE io_event, HANDLE exit_event,
<= span style=3D"color: hsl(120, 100%, 40%);">+ list_item_t *= threads)

{
static DWORD size =3D 10;<= /span>
static LPHANDLE handles =3D NULL;
@@ -= 3762,7 +3745,8 @@
PHANDLE handles =3D NULL;
= DWORD handle_count;

- service =3D RegisterServiceCtrlHandlerEx(int= eractive_service.name, ServiceCtrlInteractive, &status);
+ service =3D

+ RegisterServiceCtrlHandlerEx(i= nteractive_service.name, ServiceCtrlInteractive, &status);
if (!service)

{
retu= rn;
@@ -3817,8 +3801,7 @@

while (TRUE)

{
- if (ConnectNamedPipe(pipe, &overlapped) =3D= =3D FALSE
- = && GetLastError() !=3D ERROR_PIPE_CONNECTED
+ if (ConnectNamedPipe(pipe, &o= verlapped) =3D=3D FALSE && GetLastError() !=3D ERROR_PIPE_CONNECTED=
&& GetLastError() !=3D ERROR_IO_PENDI= NG)
{
MsgToEventLog(M= _SYSERR, L"Could not connect pipe");
@@ -3836,11 = +3819,13 @@
error =3D AddListItem(&thr= eads, thread);
if (!error)
{

- = error =3D UpdateWaitHandles(&handles, &handle_cou= nt, io_event, exit_event, threads);
+ error =3D
+ UpdateWaitHandles(&ha= ndles, &handle_count, io_event, exit_event, threads);
= }
if (error)
{

-= ReturnError(pipe, error, L"Insufficient resources = to service new clients", 1, &exit_event);
+ ReturnError(pipe, error,= L"Insufficient resources to service new clients", 1,
<= span style=3D"color: hsl(120, 100%, 40%);">+ = &exit_event);

/* Update wait hand= les again after removing the last worker thread */
= RemoveListItem(&threads, CmpHandle, thread);
UpdateWaitHandles(&handles, &handle_count, = io_event, exit_event, threads);

diff --git a/src/openvpnser= v/service.c b/src/openvpnserv/service.c
index a76dce7..04b2= 0d7 100644
--- a/src/openvpnserv/service.c
= +++ b/src/openvpnserv/service.c
@@ -33,8 +33,7 @@ status->dwControlsAccepted =3D SERVICE_ACCEPT_STOP;
}

- if (status->dwCurrentState =3D=3D SERVICE_RUNNING
- || status->dwC= urrentState =3D=3D SERVICE_STOPPED)
+ if (status->dwCurrentState =3D=3D SERVICE_RUNNING ||= status->dwCurrentState =3D=3D SERVICE_STOPPED)
{
status->dwCheckPoint =3D 0;
= }
@@ -79,16 +78,10 @@

= for (i =3D 0; i < _service_max; i++)
{- service =3D CreateServi= ce(svc_ctl_mgr,
- = openvpn_service[i].name,
- openvpn_servic= e[i].display_name,
- = SERVICE_QUERY_STATUS,
- SERVICE_WIN32_= SHARE_PROCESS,
- = openvpn_service[i].start_type,
- SERVICE_E= RROR_NORMAL,
- = path, NULL, NULL,
- openvpn_service[i].depen= dencies,
- = NULL, NULL);
+ service =3D CreateService(
+ svc_ctl_mgr, openvpn_service[i].name= , openvpn_service[i].display_name,
+ SERVICE_QUERY_STATUS, SERVICE_WIN32_SHARE_PROCES= S, openvpn_service[i].start_type,
+ SERVICE_ERROR_NORMAL, path, NULL, NULL, openvpn_s= ervice[i].dependencies, NULL, NULL);
if (service)<= /span>
{
wprintf(L"%ls = installed.\n", openvpn_service[i].display_name);
@@ -1= 63,8 +156,8 @@
for (i =3D 0; i < _service_max; i++)=
{
openvpn_service_t *ovpn_sv= c =3D &openvpn_service[i];
- service =3D OpenService(svc_ctl_mgr, ovpn_svc->name,
- = DELETE | SERVICE_STOP | SERVICE_QUERY_STATUS);
+ service =3D
+ OpenService(svc_ctl_mgr, ovpn= _svc->name, DELETE | SERVICE_STOP | SERVICE_QUERY_STATUS);
if (service =3D=3D NULL)

{
<= span> wprintf(L"OpenService failed - %ls\n", GetLastE= rrorText());

@@ -228,15 +221,12 @@
* = This is the default.
*/
const SE= RVICE_TABLE_ENTRY dispatchTable_shared[] =3D {
- { interactive_service.name, ServiceStartIn= teractive },
- {= NULL, NULL }
+ = { interactive_service.name, ServiceStartInteractive }, { NULL, NULL }
};

/* Interactive = service only (as a SERVICE_WIN32_OWN_PROCESS) */
- const SERVICE_TABLE_ENTRY dispatchTable_inte= ractive[] =3D {
- = { L"", ServiceStartInteractiveOwn },
- { NULL, NULL }
- };
+ const SERVICE_TABLE_ENTRY dispatchTable_interactive[] = =3D { { L"", ServiceStartInteractiveOwn },
+ = { NULL, NULL } };

= const SERVICE_TABLE_ENTRY *dispatchTable =3D dispatchTable_shared;

@@ -260,7 +250,7 @@
= }
else if (argc > i + 2 && _wcsi= cmp(L"instance", argv[i] + 1) =3D=3D 0)
= {
- = if (_wcsicmp(L"interactive", argv[i+1]) =3D=3D 0)
+ if (_wcsicmp(L"= ;interactive", argv[i + 1]) =3D=3D 0)

= {
dispatchTable =3D dispatchTable_int= eractive;
service_instance =3D argv[i = + 2];
@@ -268,22 +258,28 @@
= }
else
= {
- = MsgToEventLog(M_ERR, L"Invalid argument to -instance <%s>. Servi= ce not started.", argv[i+1]);
+ MsgToEventLog(M_ERR,
+ L&quo= t;Invalid argument to -instance <%s>. Service not started.",
+ = argv[i + 1]);
return 1;
}
}
else

{
= wprintf(L"%ls -install to install the interactive se= rvice\n", APPNAME);
+ wprintf(
+ L&= quot;%ls -start [name] to start the service (name =3D \"interactive\= ") is optional\n",
+ APPNAME);
wpr= intf(L"%ls -remove to remove the service\n", APPNAME);

wprintf(L"\nService r= un-time parameters:\n");
wprintf(L&qu= ot;-instance interactive <id>\n"
= L" Runs the service as an alternate instance.\n"
L" The service settings will be= loaded from\n"
- = L" HKLM\\Software\\" _L(PACKAGE_NAME) L&= quot;<id> registry key, and the service will accept\n"- L"= requests on \\\\.\\pipe\\" _L(PACKAGE) L"<id>\\service n= amed pipe.\n");
= + L" HKLM\\Software\\" _L(
+ PACKA= GE_NAME) L"<id> registry key, and the service will accept\n"= ;

+ = L" requests on \\\\.\\pipe\\" _L(
+ = PACKAGE) L"<id>\\service named pipe.\n"= ;);

return 0;
= }
diff --git a/src/openvpnserv/service.h= b/src/openvpnserv/service.h
index 8989e60..3d3b82b 100644<= /span>
--- a/src/openvpnserv/service.h
+++ b/src/o= penvpnserv/service.h
@@ -33,24 +33,26 @@
#= include <wchar.h>
#include "../tapctl/basic.h&q= uot;

= -#define APPNAME _L(PACKAGE) L"serv"
-#define SERVICE_DEPENDENCIES _L(TAP_WIN_COMPONEN= T_ID) L"\0Dhcp\0\0"
+#define APPNAME _L(PACKAGE) L"serv"=
+#define SERVICE_DEPENDENCI= ES _L(TAP_WIN_COMPONENT_ID) L"\0Dhcp\0\0"

/*
* Message handling
*/
-#define MSG_FLAGS_ERROR = (1<<0)
-#defi= ne MSG_FLAGS_SYS_CODE (1<<1)
-#define M_INFO (0) /* inf= ormational */
-#define = M_SYSERR (MSG_FLAGS_ERROR|MSG_FLAGS_SYS_CODE) /* error + system code */
-#define M_ERR (MSG_F= LAGS_ERROR) /* error */
+#define MSG_FLAGS_ERROR (1 << 0)
= +#define MSG_FLAGS_SYS_CODE (1 = << 1)
+#define = M_INFO (0) /* informational = */
+#define M_SYSERR = (MSG_FLAGS_ERROR | MSG_FLAGS_SYS_CODE) /* error + system code */<= /span>
+#define M_ERR = (MSG_FLAGS_ERROR) /* error */
=
-typedef enum {=
+typedef enum
+{

interactiv= e,
_service_max
} openvpn_service_typ= e;

-t= ypedef struct {
+type= def struct
+{<= br> openvpn_service_type type;
WCHAR *name;<= /span>
WCHAR *display_name;
@@ -59,7 +61,8 @@=
} openvpn_service_t;

#= define MAX_NAME 256
-ty= pedef struct {
+typed= ef struct
+{ WCHAR exe_path[MAX_PATH];
WCHAR config_di= r[MAX_PATH];
WCHAR bin_dir[MAX_PATH];
= diff --git a/src/openvpnserv/validate.c b/src/openvpnserv/validate.c=
index 6ed5bea..59d5b86 100644
--- a/src/openvpnse= rv/validate.c
+++ b/src/openvpnserv/validate.c
@@ -26,8 +26,7 @@

#include <shlwapi.h> #include <lm.h>

-static const WCHAR *white_list[] =3D
-{

+static const WCHAR *white_list[] =3D {
L"auth-retry",

L"config",<= /span>
L"log",
@@ -46,7 +45,7 @@
L"pull-filter",
L"sc= ript-security",

- NULL /* last value */
+ NULL /* last valu= e */
};

static BOOL IsU= serInGroup(PSID sid, const PTOKEN_GROUPS groups, const WCHAR *group_name);<= /span>
@@ -65,7 +64,7 @@
const WCHAR *config_= dir =3D NULL;

/* convert fname to fu= ll path */
- if (Pat= hIsRelativeW(fname) )
+ if (PathIsRelativeW(fname))
{
= swprintf(tmp, _countof(tmp), L"%ls\\%ls", workdir, fname);=
config_file =3D tmp;
@@ -128,7 +1= 27,7 @@
return FALSE;
}

- b =3D= CreateWellKnownSid(WinBuiltinAdministratorsSid, NULL, admin_sid, &sid= _size);
+ b =3D Cr= eateWellKnownSid(WinBuiltinAdministratorsSid, NULL, admin_sid, &sid_siz= e);
if (b)
{
= b =3D LookupAccountSidW(NULL, admin_sid, name, &nlen, domain, &= ;dlen, &snu);
@@ -140,7 +139,8 @@
}

BOOL
-IsAuthorizedUser(PSID sid, const HANDLE token, const WCHAR = *ovpn_admin_group, const WCHAR *ovpn_service_user)
+IsAuthorizedUser(PSID sid, const HANDLE toke= n, const WCHAR *ovpn_admin_group,
+ const WCHAR *ovpn_service_user)
{

const WCHAR *admin_group[2];
= WCHAR username[MAX_NAME];
@@ -171,7 +171,8 @@
= }
else
{
- MsgToEventLog(M_SYSERR, L&q= uot;Failed to get the name of Administrators group. Using the default."= ;);

+ MsgToEve= ntLog(M_SYSERR,
+ = L"Failed to get the name of Administrators group. Us= ing the default.");
/* use the default value = */
admin_group[0] =3D SYSTEM_ADMIN_GROUP; }
@@ -183,7 +184,8 @@
= ret =3D IsUserInGroup(sid, token_groups, admin_group[i]);
= if (ret)
{
- MsgToEventLog(M_INFO, L"Authorizing= user '%ls@%ls' by virtue of membership in group '%ls'"= ;,
+ MsgTo= EventLog(M_INFO,
+ = L"Authorizing user '%ls@%ls' by virtue = of membership in group '%ls'",
= username, domain, admin_group[i]);
= goto out;
}
@@ -265,11 +267,11 @@=
int nloop =3D 0; /* a counter used to not get stuck i= n the do .. while() */

/* first chec= k in the token groups */
+ = if (token_groups && LookupSID(group_name, (PSID)grp_sid, _countof= (grp_sid)))
{
for (DWORD i = =3D 0; i < token_groups->GroupCount; ++i)
{<= /span>
- if (EqualS= id((PSID) grp_sid, token_groups->Groups[i].Sid))
+ if (EqualSid((PSID)grp_sid, t= oken_groups->Groups[i].Sid))
{
return TRUE;

}
= @@ -285,8 +287,8 @@
{
D= WORD nread, nmax;
LOCALGROUP_MEMBERS_INFO_0 *membe= rs =3D NULL;
- e= rr =3D NetLocalGroupGetMembers(NULL, group_name, 0, (LPBYTE *) &members= ,
- = MAX_PREFERRED_LENGTH, &nread, &nmax, &resume)= ;
+ err =3D Ne= tLocalGroupGetMembers(NULL, group_name, 0, (LPBYTE *)&members, MAX_PREF= ERRED_LENGTH,
+ = &nread, &nmax, &resume);=
if ((err !=3D NERR_Success && err !=3D ERROR_MOR= E_DATA))
{
break;
@@ -319,16 +321,13 @@
{
= /* Do not modify argv or *argv -- ideally it should be const WCHAR *const *= , but alas...*/

- if (wcscmp(argv[0], L"--config") =3D=3D 0<= br>- && argc > = 1
- && != CheckConfigPath(workdir, argv[1], s)
- )
+ if (wcscmp(argv[0], L"--config") =3D=3D 0 && arg= c > 1 && !CheckConfigPath(workdir, argv[1], s))
= {
return FALSE;
}=

/* option name starts at 2 characters from= argv[i] */
- if (Op= tionLookup(argv[0] + 2, white_list) =3D=3D -1) /* not found */
= + if (OptionLookup(argv[0] += 2, white_list) =3D=3D -1) /* not found */
{ return FALSE;
}
diff -= -git a/src/openvpnserv/validate.h b/src/openvpnserv/validate.h
index bde1892..6f3bf09 100644

--- a/src/openvpnserv/val= idate.h
+++ b/src/openvpnserv/validate.h
@@= -28,19 +28,20 @@

/* Authorized groups w= ho can use any options and config locations */
#define SYS= TEM_ADMIN_GROUP L"Administrators"
-#define OVPN_ADMIN_GROUP L"OpenVPN Administrator= s" /* may be set in HKLM\Software\OpenVPN\ovpn_admin_group */-#define OVPN_SERVICE_USER L&qu= ot;OpenVPNService" /* may be set in HKLM\Software\OpenVPN\ovpn_service= _user */
+#define OVP= N_ADMIN_GROUP \
+ = L"OpenVPN Administrators" /* may be set in HKLM\Software\OpenVPN\= ovpn_admin_group */
+= #define OVPN_SERVICE_USER \
+ L"OpenVPNService" /* may be set in HKLM\Softw= are\OpenVPN\ovpn_service_user */

/*
* Check whether user is a member of Administrators group or
* the group specified in ovpn_admin_group or
* OpenVPN Virtual Service Account user

*/
= -BOOL
-IsAuthorizedUser(PSID sid, const HANDLE token, co= nst WCHAR *ovpn_admin_group, const WCHAR *ovpn_service_user);
+BOOL IsAuthorizedUser(PSID sid, c= onst HANDLE token, const WCHAR *ovpn_admin_group,

+ const WCHAR *ovpn_servi= ce_user);

-BOOL
-CheckOption= (const WCHAR *workdir, int narg, WCHAR *argv[], const settings_t *s);
+BOOL CheckOption(const WC= HAR *workdir, int narg, WCHAR *argv[], const settings_t *s);

static inline BOOL
IsOption(const WCH= AR *o)
diff --git a/src/plugins/auth-pam/auth-pam.c b/src/p= lugins/auth-pam/auth-pam.c
index bff4767..15169ca 100644
--- a/src/plugins/auth-pam/auth-pam.c
+++ b/s= rc/plugins/auth-pam/auth-pam.c
@@ -99,12 +99,14 @@
#define N_NAME_VALUE 16
=
-struct name_value {+struct name_value
= +{
const c= har *name;
const char *value;
};

-struct n= ame_value_list {
+str= uct name_value_list
+= {
int len;
struct name_value data= [N_NAME_VALUE];
};
@@ -113,7 +115,8 @@
* Used to pass the username/password
* to = the PAM conversation function.
*/
-struct user_pass {
+struct user_pass
+{
int verb;

char username[128];
@@ -126,7 +129= ,8 @@
};

/* Background = process function */
-st= atic void pam_server(int fd, const char *service, int verb, const struct na= me_value_list *name_value_list);
+static void pam_server(int fd, const char *service, int verb,<= /span>
+ = const struct name_value_list *name_value_list);
=

/*
@@ -152,11 +156,11 @@
static int
send_control(int fd, int code)
{
- uns= igned char c =3D (unsigned char) code;
+ unsigned char c =3D (unsigned char)code;
<= span> const ssize_t size =3D write(fd, &c, sizeof(c));

if (size =3D=3D sizeof(c))

{
- return (int) size;
<= span style=3D"color: hsl(120, 100%, 40%);">+ return (int)size;
}
else
{@@ -171,7 +175,7 @@
{
= memset(buffer, 0, len);
ssize_t size =3D read(fd,= buffer, len);
- = buffer[len-1] =3D 0;
+ buffer[len - 1] =3D 0;
if (size >=3D = 1)
{
return size;
@@ -220,7 +224,7 @@
#endif
= if (daemon(0, 0) < 0)
{
- plugin_log(PLOG_ERR|PLOG_E= RRNO, MODULE, "daemonization failed");
+ plugin_log(PLOG_ERR | PLOG_ERRNO, = MODULE, "daemonization failed");
}
#if defined(__APPLE__) && defined(__clang__)
= #pragma clang diagnostic pop
@@ -321,11 +325,11 @@
}
*resp++ =3D '\0';=

- int n = =3D plugin_base64_decode(pass, up->password, sizeof(up->password)-1);=
+ int n =3D plugi= n_base64_decode(pass, up->password, sizeof(up->password) - 1);=
if (n >=3D 0)
{
= up->password[n] =3D '\0';
- n =3D plugin_base64_decode(resp, up->respons= e, sizeof(up->response)-1);
+ n =3D plugin_base64_decode(resp, up->response, sizeof= (up->response) - 1);
if (n >=3D 0) {
up->response[n] =3D '= \0';
@@ -353,8 +357,7 @@
}
<= span>

OPENVPN_EXPORT int
-openvpn_plugin_open_v3(const int v3structver,- struct = openvpn_plugin_args_open_in const *args,
+openvpn_plugin_open_v3(const int v3structver, struct o= penvpn_plugin_args_open_in const *args,
= struct openvpn_plugin_args_open_return *ret)
{=
pid_t pid;
@@ -371,14 +374,15 @@
<= span> /* Check API compatibility -- struct version 5 or higher needed *= /

if (v3structver < 5)
{
- fprintf(stderr, &qu= ot;AUTH-PAM: This plugin is incompatible with the running version of OpenVP= N\n");
+ = fprintf(stderr,
+ = "AUTH-PAM: This plugin is incompatible with the running ve= rsion of OpenVPN\n");
return OPENVPN_PLUGIN_F= UNC_ERROR;
}

/*=
* Allocate our context
*/
- context =3D (struct au= th_pam_context *) calloc(1, sizeof(struct auth_pam_context));
+ context =3D (struct auth_pam_= context *)calloc(1, sizeof(struct auth_pam_context));

= if (!context)
{
goto error;
@@ -426,7 +430,7 @@
{
const int base =3D base_parms + i * 2;

= name_value_list.data[i].name =3D argv[base];
- name_value_list.data[i].value = =3D argv[base+1];
+ = name_value_list.data[i].value =3D argv[base + 1];
}

}

@@ -44= 7,7 +451,7 @@
*/
if (socketpair(= PF_UNIX, SOCK_DGRAM, 0, fd) =3D=3D -1)
{
- plugin_log(PLOG_ERR|PLOG_ER= RNO, MODULE, "socketpair call failed");

+ plugin_log(PLOG_ERR | PLOG_ERRNO, MOD= ULE, "socketpair call failed");
goto err= or;
}

@@ -473,7 +477= ,8 @@
/* don't let future subprocesses inherit= child socket */
if (fcntl(fd[0], F_SETFD, FD_CLOE= XEC) < 0)
{
- plugin_log(PLOG_ERR|PLOG_ERRNO, MODULE, "= ;Set FD_CLOEXEC flag on socket file descriptor failed");
+ plugin_log(PLOG_ERR |= PLOG_ERRNO, MODULE,

= + "Set FD_CLOEXEC flag on socket file descriptor= failed");
}

/* wait for background child process to initialize */

= @@ -481,8 +486,8 @@
if (status =3D=3D RESPON= SE_INIT_SUCCEEDED)
{
= context->foreground_fd =3D fd[0];
- ret->handle =3D (openvpn_plugin_handle_t *) c= ontext;
- pl= ugin_log( PLOG_NOTE, MODULE, "initialization succeeded (fg)" );
+ ret->h= andle =3D (openvpn_plugin_handle_t *)context;
+ plugin_log(PLOG_NOTE, MODULE, "i= nitialization succeeded (fg)");
return OP= ENVPN_PLUGIN_FUNC_SUCCESS;
}
= }
@@ -518,9 +523,10 @@
}
=
OPENVPN_EXPORT int
-openvpn_plugin_func_v1(openvpn_plugin_handle_t handle, const= int type, const char *argv[], const char *envp[])
+openvpn_plugin_func_v1(openvpn_plugin_handle= _t handle, const int type, const char *argv[],
+ const char *envp[])
{
- stru= ct auth_pam_context *context =3D (struct auth_pam_context *) handle;=
+ struct auth_pam_contex= t *context =3D (struct auth_pam_context *)handle;
<= br> if (type =3D=3D OPENVPN_PLUGIN_AUTH_USER_PASS_VERIFY &&am= p; context->foreground_fd >=3D 0)
{
@@ -549,8 +555,7 @@

{
= if (DEBUG(context->verb))
{
= - plugin_log(PLOG_= NOTE, MODULE, "do deferred auth '%s'",
- auth_control_= file);
+ = plugin_log(PLOG_NOTE, MODULE, "do deferred auth '%s'",= auth_control_file);
}
= }
else
@@ -567,7 +572,8 @@
|| send_string(context->foreground_fd, auth_= control_file) =3D=3D -1
|| send_string(con= text->foreground_fd, remote) =3D=3D -1)
{
- plugin_= log(PLOG_ERR|PLOG_ERRNO, MODULE, "Error sending auth info to backgroun= d process");
+ = plugin_log(PLOG_ERR | PLOG_ERRNO, MODULE,
+ "Error = sending auth info to background process");
= }
else
{=
@@ -586,7 +592,8 @@
}
= if (status =3D=3D -1)
= {
- = plugin_log(PLOG_ERR|PLOG_ERRNO, MODULE, "Error receiving auth confi= rmation from background process");
+ plugin_log(PLOG_ERR | PLOG_ERRNO, M= ODULE,
+ = "Error receiving auth confirmation from background p= rocess");
}
= }
}
@@ -597,7 +604,7 @@=
OPENVPN_EXPORT void
openvpn_plugin_close_v1(ope= nvpn_plugin_handle_t handle)
{
- struct auth_pam_context *context =3D (struct = auth_pam_context *) handle;
+ struct auth_pam_context *context =3D (struct auth_pam_context *= )handle;

if (DEBUG(context->verb)= )
{
@@ -609,7 +616,7 @@
/* tell background process to exit */

i= f (send_control(context->foreground_fd, COMMAND_EXIT) =3D=3D -1)<= br> {
- = plugin_log(PLOG_ERR|PLOG_ERRNO, MODULE, "Error signaling bac= kground process to exit");
+ plugin_log(PLOG_ERR | PLOG_ERRNO, MODULE, "Err= or signaling background process to exit");
}<= /span>

/* wait for background process t= o exit */
@@ -628,7 +635,7 @@
OPENVPN_EXPO= RT void
openvpn_plugin_abort_v1(openvpn_plugin_handle_t ha= ndle)
{
+ struct auth= _pam_context *context =3D (struct auth_pam_context *)handle;

/* tell background process to exit */
if (context && context->foreground_fd >=3D 0)
=
@@ -643,10 +650,10 @@
* PAM conversation functi= on
*/
static int
-my_conv(int num_msg, const struct pam_messa= ge **msg_array,
- = struct pam_response **response_array, void *appdata_ptr)
+my_conv(int num_msg, const struct pa= m_message **msg_array, struct pam_response **response_array,
+ void *appdata_ptr)
<= br> {
- const = struct user_pass *up =3D ( const struct user_pass *) appdata_ptr;+ const struct user_pass *u= p =3D (const struct user_pass *)appdata_ptr;
struct pa= m_response *aresp;
int ret =3D PAM_SUCCESS;
=
@@ -670,10 +677,8 @@

if (DEBUG(up->verb))

{
<= span style=3D"color: hsl(0, 100%, 40%);">- plugin_log(PLOG_NOTE,= MODULE, "BACKGROUND: my_conv[%d] query=3D'%s' style=3D%d"= ;,

- = i,
- = msg->msg ? msg->msg : "NULL",
- msg->msg_style);<= /span>
+ plugin_l= og(PLOG_NOTE, MODULE, "BACKGROUND: my_conv[%d] query=3D'%s' st= yle=3D%d", i,
+ = msg->msg ? msg->msg : "NULL", msg->= ;msg_style);
}

= if (up->name_value_list && up->name_value_list->le= n > 0)
@@ -695,10 +700,10 @@
if (DEBUG(up->verb))
= {
- = plugin_log(PLOG_NOTE, MODULE, "BACKGROUND: name matc= h found, query/match-string ['%s', '%s'] =3D '%s'&q= uot;,
- = msg->msg,
- match_name,
- match= _value);
+ = plugin_log(
+ PLOG_NOTE, MODULE,
+ "BACKGRO= UND: name match found, query/match-string ['%s', '%s'] =3D = '%s'",
+= msg->msg, match_name, match_value); }

= if (strstr(match_value, "USERNAME"))
@= @ -711,7 +716,8 @@
}
= else if (strstr(match_value, "COMMONNAME"))
{
- aresp[i].resp =3D searchandreplace(= match_value, "COMMONNAME", up->common_name);
+ aresp[i].resp= =3D
+ = searchandreplace(match_value, "COMMONNAME", up->c= ommon_name);
}
= else if (strstr(match_value, "OTP"))
{

@@ -822,8 +828,7 @@
if (!ret)

{
= plugin_log(PLOG_ERR, MODULE, "BACKGROUND: user '%s' failed t= o authenticate: %s",
- up->username,
- pam_strerror(pamh, status));
+ = up->username, pam_strerror(pamh, status));
}<= /span>

/* Close PAM */
= @@ -844,12 +849,12 @@
*/

static void

-do_defe= rred_pam_auth(int fd, const char *ac_file_name,
- const char *service, const s= truct user_pass *up)
= +do_deferred_pam_auth(int fd, const char *ac_file_name, const char *service= ,
+ = const struct user_pass *up)
{
if (= send_control(fd, RESPONSE_DEFER) =3D=3D -1)
{- plugin_log(PLOG_ERR|PL= OG_ERRNO, MODULE, "BACKGROUND: write error on response socket [4]"= ;);
+ plugin_l= og(PLOG_ERR | PLOG_ERRNO, MODULE, "BACKGROUND: write error on response= socket [4]");
return;
}=

@@ -858,52 +863,50 @@
<= /span>
if (p1 < 0)
{
- plugin_log(PLOG_ERR|PLOG_ERRNO= , MODULE, "BACKGROUND: fork(1) failed");
+ plugin_log(PLOG_ERR | PLOG_ERRNO, MO= DULE, "BACKGROUND: fork(1) failed");
ret= urn;
}
- if (p1 !=3D 0) /* parent */
<= span style=3D"color: hsl(120, 100%, 40%);">+ if (p1 !=3D 0) /* parent */=

{
waitpid(p1, NULL, 0);
- return; = /* parent's job succeeded */
+ return; /* parent's job succeeded= */
}

/* child = */
- close(fd); = /* socketpair no longer needed */
+ close(fd); /* socketpair no long= er needed */

pid_t p2 =3D fork();
if (p2 < 0)
{
- plugin_log(PLOG_ERR|PLOG_ERRNO, = MODULE, "BACKGROUND: fork(2) failed");
+ plugin_log(PLOG_ERR | PLOG_ERRNO, MODU= LE, "BACKGROUND: fork(2) failed");
exit(= 1);
}

- if (p2 !=3D 0) /* new= parent: exit right away */
+ if (p2 !=3D 0) /* new parent: exit right away */
{

exit(0);
}
/* grandchild */
- plugin_log(PLOG_NOTE, MODULE, "BACKGROUND= : deferred auth for '%s', pid=3D%d",
- up->username, (int) getpid() = );
+ plugin_log(PL= OG_NOTE, MODULE, "BACKGROUND: deferred auth for '%s', pid=3D%d= ", up->username,
+ (int)getpid());

= /* the rest is very simple: do PAM, write status byte to file, done */
- int ac_fd =3D open( ac= _file_name, O_WRONLY );
+ int ac_fd =3D open(ac_file_name, O_WRONLY);
if= (ac_fd < 0)
{
- plugin_log(PLOG_ERR|PLOG_ERRNO, MODULE, "cann= ot open '%s' for writing",
- ac_file_name );
+ plugin_log(PLOG_ERR | PLOG_ERRNO,= MODULE, "cannot open '%s' for writing", ac_file_name);
exit(1);
}
= int pam_success =3D pam_auth(service, up);

- if (write( ac_fd, pam_success = ? "1" : "0", 1 ) !=3D 1)

+ if (write(ac_fd, pam_success ? "1" := "0", 1) !=3D 1)
{
- plugin_log(PLOG_ERR|PLOG_ERRNO, MODULE,= "cannot write to '%s'",
- ac_file_name );
+ plugin_log(PLOG_ERR | PLOG_ERRN= O, MODULE, "cannot write to '%s'", ac_file_name);<= br> }
close(ac_fd);
- plugin_log(PLOG_NOTE, MODULE, "BACKGR= OUND: %s: deferred auth: PAM %s",
- up->username, pam_success ? "succee= ded" : "rejected" );
+ plugin_log(PLOG_NOTE, MODULE, "BACKGROUND: %s: def= erred auth: PAM %s", up->username,
+ pam_success ? "succeeded" := "rejected");
exit(0);
}

@@ -934,7 +937,8 @@
*= /
if (!dlopen_pam(pam_so))
{
- plugin_log(PLOG_ER= R, MODULE, "BACKGROUND: could not load PAM lib %s: %s", pam_so, d= lerror());
+ p= lugin_log(PLOG_ERR, MODULE, "BACKGROUND: could not load PAM lib %s: %s= ", pam_so,
+ = dlerror());
send_control(fd, RESPON= SE_INIT_FAILED);
goto done;
}=
@@ -945,7 +949,7 @@
*/
if (send_control(fd, RESPONSE_INIT_SUCCEEDED) =3D=3D -1)

= {
- p= lugin_log(PLOG_ERR|PLOG_ERRNO, MODULE, "BACKGROUND: write error on res= ponse socket [1]");
+ plugin_log(PLOG_ERR | PLOG_ERRNO, MODULE, "BACKGROUND: wr= ite error on response socket [1]");
goto done= ;
}

@@ -977,7 +981,8= @@
|| recv_string(fd, ac_file_name, s= izeof(ac_file_name)) =3D=3D -1
|| recv= _string(fd, up.remote, sizeof(up.remote)) =3D=3D -1)
= {
- = plugin_log(PLOG_ERR|PLOG_ERRNO, MODULE, "BACKGROUND: read e= rror on command channel: code=3D%d, exiting",
+ plugin_log(PLOG_ERR | PL= OG_ERRNO, MODULE,
+ = "BACKGROUND: read error on command channe= l: code=3D%d, exiting",
= command);
goto done;
}

@@ -1012,7 +1017,8 @@
= {
if (send_control(fd,= RESPONSE_VERIFY_SUCCEEDED) =3D=3D -1)
= {
- = plugin_log(PLOG_ERR|PLOG_ERRNO, MODULE, "BACKGROUND: write error = on response socket [2]");
+ plugin_log(PLOG_ERR | PLOG_ERRNO, MODULE= ,
+ = "BACKGROUND: write error on response socket [2]"= );
goto done;
= }
}
@@ -1= 020,7 +1026,8 @@
{
= if (send_control(fd, RESPONSE_VERIFY_FAILED) =3D=3D -1)
{
- plugin_log(PLOG_ERR|PLOG_ERRNO, MODULE,= "BACKGROUND: write error on response socket [3]");
+ plugin_lo= g(PLOG_ERR | PLOG_ERRNO, MODULE,

+ "BACKGROUND: write err= or on response socket [3]");
= goto done;
}
= }
@@ -1031,7 +1038,8 @@
= goto done;

case -1:
- plugin_l= og(PLOG_ERR|PLOG_ERRNO, MODULE, "BACKGROUND: read error on command cha= nnel");
+ = plugin_log(PLOG_ERR | PLOG_ERRNO, MODULE,
+ "BACKGROUND:= read error on command channel");
got= o done;

default:
<= span>diff --git a/src/plugins/auth-pam/pamdl.c b/src/plugins/auth-pam/pamdl= .c

index 02ea71a..c1ecfa0 100644
--- a/src/= plugins/auth-pam/pamdl.c
+++ b/src/plugins/auth-pam/pamdl.c=
@@ -19,14 +19,20 @@

sta= tic void *libpam_h =3D NULL;

-#define RESOLVE_PAM_FUNCTION(x, y, z, err) \
- { \
- union { const void *tpointer; y(*= fn) z; } fptr; \
- = fptr.tpointer =3D dlsym(libpam_h, #x); real_ ## x =3D fptr.fn; \<= br>- if (real_ ## x =3D=3D= NULL) { \
+#define R= ESOLVE_PAM_FUNCTION(x, y, z, err) \=
+ { = \+ union = \
+ { = \
+ const void *tpointer; = \
+ y(*fn) z; = \
+ } fptr; = \
+ = fptr.tpointer =3D dlsym(libpam_h, #x); = \
+ real= _##x =3D fptr.fn; \<= /span>
+ if (real_##x= =3D=3D NULL) \=
+ { = \
= fprintf(stderr, "PAMDL: unable to resolve '%s': %= s\n", #x, dlerror()); \
- return err; \
- } \
+ = } = \
}

int
= @@ -34,7 +40,7 @@
{
if (libpam_= h =3D=3D NULL)
{
- libpam_h =3D dlopen(so, RTLD_GLOBAL|RTLD_NOW);
+ libpam_h =3D dlo= pen(so, RTLD_GLOBAL | RTLD_NOW);
}
= return libpam_h !=3D NULL;
}
@@ -50,16 += 56,13 @@
}

int-pam_start(const char *service_= name, const char *user,
- const struct pam_conv *pam_conversation,
+pam_start(const char *service_name, const= char *user, const struct pam_conv *pam_conversation,
= pam_handle_t **pamh)
{
- int (*real_pam_start)(const char *, const char = *,
- = const struct pam_conv *,
- pam_handle_t **);
- RESOLVE_PAM_FUNCTION(pam_start, int, (c= onst char *, const char *,
- const struct pam_conv *,
- = pam_handle_t **), PAM_ABORT);
+ int (*real_pam_start)(const char *, const ch= ar *, const struct pam_conv *, pam_handle_t **);
+ RESOLVE_PAM_FUNCTION(pam_start, int,
+ = (const char *, const char *, const struct pam_conv *, pam_handle_t **),
+ = PAM_ABORT);
return real_pam_start(service_name, user= , pam_conversation, pamh);
}

<= span>@@ -75,8 +78,7 @@

pam_set_item(pam_handle_t *pamh, in= t item_type, const void *item)
{
int = (*real_pam_set_item)(pam_handle_t *, int, const void *);
- RESOLVE_PAM_FUNCTION(pam_set_item, i= nt,
- = (pam_handle_t *, int, const void *), PAM_ABORT);
+ RESOLVE_PAM_FUNCTION(pam_set_item, = int, (pam_handle_t *, int, const void *), PAM_ABORT);
= return real_pam_set_item(pamh, item_type, item);
}<= br>
@@ -84,9 +86,7 @@
pam_get_item(= const pam_handle_t *pamh, int item_type, const void **item)
{

int (*real_pam_get_item)(const pam_handle_t *, int= , const void **);
- = RESOLVE_PAM_FUNCTION(pam_get_item, int,
- (const pam_handle_t *, int, cons= t void **),
- = PAM_ABORT);
+ RESOLVE_PAM_FUNCTION(pam_get_item, int, (const pam_handle_t *, i= nt, const void **), PAM_ABORT);
return real_pam_get_it= em(pamh, item_type, item);
}

<= span>@@ -94,8 +94,7 @@

pam_fail_delay(pam_handle_t *pamh, = unsigned int musec_delay)
{
int (*rea= l_pam_fail_delay)(pam_handle_t *, unsigned int);
- RESOLVE_PAM_FUNCTION(pam_fail_delay, int, (p= am_handle_t *, unsigned int),
- PAM_ABORT);
+ RESOLVE_PAM_FUNCTION(pam_fail_delay, int, (pam= _handle_t *, unsigned int), PAM_ABORT);
return real_pa= m_fail_delay(pamh, musec_delay);
}

@@ -105,8 +104,7 @@
pam_strerror(pam_handle_t *= pamh, int errnum)
{
const_char_pointe= r (*real_pam_strerror)(pam_handle_t *, int);
- RESOLVE_PAM_FUNCTION(pam_strerror, const_char_po= inter,
- = (pam_handle_t *, int), NULL);
+ RESOLVE_PAM_FUNCTION(pam_strerror, const_char_point= er, (pam_handle_t *, int), NULL);
return real_pam_stre= rror(pamh, errnum);
}

@@= -114,8 +112,7 @@
pam_putenv(pam_handle_t *pamh, const cha= r *name_value)
{
int (*real_pam_puten= v)(pam_handle_t *, const char *);
- RESOLVE_PAM_FUNCTION(pam_putenv, int, (pam_handle_t *, cons= t char *),
- = PAM_ABORT);
+ RESOLVE_PAM_FUNCTION(pam_putenv, int, (pam_handle_t *, const char= *), PAM_ABORT);
return real_pam_putenv(pamh, name_val= ue);
}

@@ -123,8 +120,7 = @@
pam_getenv(pam_handle_t *pamh, const char *name)=
{
const_char_pointer (*real_pam_getenv)(pam= _handle_t *, const char *);
- RESOLVE_PAM_FUNCTION(pam_getenv, const_char_pointer,
- (pam_hand= le_t *, const char *), NULL);

+ RESOLVE_PAM_FUNCTION(pam_getenv, const_char_pointer, (pam_han= dle_t *, const char *), NULL);
return real_pam_getenv(= pamh, name);
}

@@ -133,8= +129,7 @@
pam_getenvlist(pam_handle_t *pamh)
{

char_ppointer (*real_pam_getenvlist)(pam_handle= _t *);
- RESOLVE_PAM= _FUNCTION(pam_getenvlist, char_ppointer, (pam_handle_t *),
- NULL);=
+ RESOLVE_PAM_FUNCTION(p= am_getenvlist, char_ppointer, (pam_handle_t *), NULL);
= return real_pam_getenvlist(pamh);
}

@@ -144,8 +139,7 @@
pam_authenticate(pam_hand= le_t *pamh, int flags)
{
int (*real_p= am_authenticate)(pam_handle_t *, int);
- RESOLVE_PAM_FUNCTION(pam_authenticate, int, (pam_handl= e_t *, int),
- = PAM_ABORT);
+ RESOLVE_PAM_FUNCTION(pam_authenticate, int, (pam_handle_t *, in= t), PAM_ABORT);
return real_pam_authenticate(pamh, fla= gs);
}

@@ -173,8 +167,7 = @@
pam_open_session(pam_handle_t *pamh, int flags)<= br> {
int (*real_pam_open_session)(pam_handle_t = *, int);
- RESOLVE_P= AM_FUNCTION(pam_open_session, int, (pam_handle_t *, int),
- PAM_ABORT);
+ RESOLVE_PAM_FUNCTI= ON(pam_open_session, int, (pam_handle_t *, int), PAM_ABORT);
return real_pam_open_session(pamh, flags);

}=

@@ -182,8 +175,7 @@
pam_close_= session(pam_handle_t *pamh, int flags)
{
= int (*real_pam_close_session)(pam_handle_t *, int);
- RESOLVE_PAM_FUNCTION(pam_close_sessio= n, int, (pam_handle_t *, int),
- PAM_ABORT);
+ RESOLVE_PAM_FUNCTION(pam_close_session, int, = (pam_handle_t *, int), PAM_ABORT);
return real_pam_clo= se_session(pamh, flags);
}

diff --git a/src/plugins/auth-pam/utils.c b/src/plugins/auth-pam/utils.c=

index 6524051..0da162d 100644
--- a/src/pl= ugins/auth-pam/utils.c
+++ b/src/plugins/auth-pam/utils.c
@@ -55,7 +55,8 @@
return NULL;
}

- bool is_potential_integer_overflow =3D (templen =3D=3D = SIZE_MAX) || (templen / tosearchlen !=3D replacewithlen);
+ bool is_potential_integer_overflo= w =3D
+ (templ= en =3D=3D SIZE_MAX) || (templen / tosearchlen !=3D replacewithlen);<= br>
if (is_potential_integer_overflow) {
@@ -67,7 +68,7 @@
const= char *searching =3D tosearch;
char *scratch;
- char tem= p[templen+1];
+ ch= ar temp[templen + 1];
temp[0] =3D 0;
=
scratch =3D strstr(searching, searchfor);
<= span>@@ -78,10 +79,10 @@


while (scra= tch)
{
- strncat(temp, searching, (size_t)(scratch-searching));=
+ strncat(temp, sear= ching, (size_t)(scratch - searching));
strcat(temp= , replacewith);

- searching =3D scratch+strlen(searchfor);
+ searching =3D scratch + st= rlen(searchfor);

scratch =3D strstr(searching, sea= rchfor);
}
return strdup(temp);
diff --git a/src/plugins/auth-pam/utils.h b/src/plugins/auth= -pam/utils.h
index 0b90aee..a733feb 100644
= --- a/src/plugins/auth-pam/utils.h
+++ b/src/plugins/auth-p= am/utils.h
@@ -34,11 +34,10 @@
* @param = searchfor needle to search for in the haystack
* @pa= ram replacewith when a match is found, replace needle with this string
*
- * = @return Returns NULL when any parameter is NULL or the worst-case result is= to large ( >=3D SIZE_MAX).
- * Otherwise it returns a pointer to a new buffer contain= ing the modified input
+ * SIZE_MAX). Otherwise it returns a pointer to a new buffer contain= ing the modified input
*/
-char *
-searchandreplace(const char *tosearch, const char *searchfor, const = char *replacewith);
+= char *searchandreplace(const char *tosearch, const char *searchfor, const c= har *replacewith);

/**
= * Given an environmental variable name, search
@@ -47,10 += 46,10 @@
* @param name Environment variable to look up
* @param envp Environment variable table with all key/val= ue pairs
*
- * @return Returns a pointer to the value of the environment variabl= e if found, otherwise NULL is returned.
+ * @return Returns a pointer to the value of the enviro= nment variable if found, otherwise NULL is
+ * returned.
*/
-const char *
-get_env(const char *name, const char *envp[]);
+const char *get_env(co= nst char *name, const char *envp[]);

/**=
* Return the length of a string array
@@= -58,7 +57,6 @@
* @param array Pointer to the array to = calculate size of
*
*/
-int
-string_array_len(const char *array[]);
+int string_array_len(const char *arra= y[]);

#endif
diff --git = a/src/plugins/down-root/down-root.c b/src/plugins/down-root/down-root.c
index 5f595fd..da476fc 100644
--- a/src/plugin= s/down-root/down-root.c
+++ b/src/plugins/down-root/down-ro= ot.c
@@ -142,7 +142,7 @@
static ssize_t
send_control(int fd, int code)
{
= - unsigned char c =3D (unsigne= d char) code;
+ un= signed char c =3D (unsigned char)code;
const ssize_t s= ize =3D write(fd, &c, sizeof(c));
if (size =3D=3D = sizeof(c))
{
@@ -252,7 +252,7 @@
int ret =3D 0;

pid = =3D fork();
- if (pi= d =3D=3D (pid_t)0) /* child side */
+ if (pid =3D=3D (pid_t)0) /* child side */
<= span> {

execve(argv[0], argv, envp); /* If execve() fails to run, exit child with exit code 127 = */
@@ -263,12 +263,13 @@
warn(&quo= t;DOWN-ROOT: Failed to fork child to run %s", argv[0]);
return -1;

}
- else /* parent side */
+ else /* parent side */
{

if (waitpid(pid, &ret, 0) !=3D pid)
{
/* waitpid does not = return error information via errno */
- fprintf(stderr, "DOWN-ROOT: waitpid() fail= ed, don't know exit code of child (%s)\n", argv[0]);
+ fprintf(stderr, "= ;DOWN-ROOT: waitpid() failed, don't know exit code of child (%s)\n"= ;,

+ = argv[0]);
return -1;
= }
}
@@ -283,7 +284,7 @@
<= span> /*

* Allocate our context
= */
- context = =3D (struct down_root_context *) calloc(1, sizeof(struct down_root_context)= );
+ context =3D (= struct down_root_context *)calloc(1, sizeof(struct down_root_context));
if (!context)
{
= warn("DOWN-ROOT: Could not allocate memory for plug-in context&qu= ot;);
@@ -319,7 +320,7 @@
/* Ignore ar= gv[0], as it contains just the plug-in file name */
fo= r (int i =3D 1; i < string_array_len(argv); i++)
{<= /span>
- context->co= mmand[i-1] =3D (char *) argv[i];
+ context->command[i - 1] =3D (char *)argv[i];=
}

/*
= @@ -333,7 +334,7 @@
}
}

- retur= n (openvpn_plugin_handle_t) context;
+ return (openvpn_plugin_handle_t)context;

error:
free_context(context);
@@ -341,11 +342,13 @@
}

OPENVPN_EXPORT int
-openvpn_plugin_func_v1(openvpn_plugin_handle_t handle, const in= t type, const char *argv[], const char *envp[])
+openvpn_plugin_func_v1(openvpn_plugin_handle_t = handle, const int type, const char *argv[],
+ const char *envp[]) {
- struct = down_root_context *context =3D (struct down_root_context *) handle;<= br>+ struct down_root_contex= t *context =3D (struct down_root_context *)handle;
=
- if (type =3D=3D OPENVPN_= PLUGIN_UP && context->foreground_fd =3D=3D -1) /* fork off a pro= cess to hold onto root */
+ if (type =3D=3D OPENVPN_PLUGIN_UP
+ && context->foreground_fd =3D=3D= -1) /* fork off a process to hold onto root */
{
pid_t pid;
int fd[2];<= br>@@ -409,7 +412,7 @@
daemonize(envp);<= /span>

/* execute the event loop */=
- down_root= _server(fd[1], context->command, (char *const *) envp, context->verb)= ;
+ down_r= oot_server(fd[1], context->command, (char *const *)envp, context->ver= b);

close(fd[1]);
= exit(0);
@@ -431,7 +434,8 @@
<= span> }

if (status =3D=3D -1)
{
- warn("DOWN-ROOT: Error receiving script execution= confirmation from background process");
+ warn(
+ "DOWN-ROOT: Error rece= iving script execution confirmation from background process");<= br> }
}
}
@@ -441,7 +445,7 @@
OPENVPN_EXPORT void
openvpn_plugin_close_v1(openvpn_plugin_handle_t handle)
{
- stru= ct down_root_context *context =3D (struct down_root_context *) handle;
+ struct down_root_con= text *context =3D (struct down_root_context *)handle;

if (DEBUG(context->verb))
{
@@ -472,7 +476,7 @@
OPENVPN_EXPORT void<= br> openvpn_plugin_abort_v1(openvpn_plugin_handle_t handle) {
- struct d= own_root_context *context =3D (struct down_root_context *) handle;+ struct down_root_context= *context =3D (struct down_root_context *)handle;
<= br> if (context && context->foreground_fd >=3D 0)
{
@@ -525,7 +529,7 @@
= switch (command_code)
{
= case COMMAND_RUN_SCRIPT:
- if ( (exit_code =3D run_script(argv, envp)) = =3D=3D 0) /* Succeeded */
+ if ((exit_code =3D run_script(argv, envp)) =3D=3D 0) = /* Succeeded */
{
= if (send_control(fd, RESPONSE_SCRIPT_SUCCEEDED) =3D=3D -1)
{
@@ -535,7 +539,8 @@
}
else /* Fa= iled */
{
- fprintf(stderr, "DOWN-ROOT: B= ACKGROUND: %s exited with exit code %i\n", argv[0], exit_code);=
+ fprint= f(stderr, "DOWN-ROOT: BACKGROUND: %s exited with exit code %i\n",= argv[0],
+ = exit_code);
if (send= _control(fd, RESPONSE_SCRIPT_FAILED) =3D=3D -1)
= {
warn("DOWN-ROOT: = BACKGROUND: write error on response socket [3]");
diff= --git a/src/tapctl/basic.h b/src/tapctl/basic.h
index 571a= e62..620c1ca 100644
--- a/src/tapctl/basic.h
+++ b/src/tapctl/basic.h

@@ -26,14 +26,16 @@
#define UNICODE

#endif

-#define PRIXGUID "{%08= lX-%04hX-%04hX-%02hhX%02hhX-%02hhX%02hhX%02hhX%02hhX%02hhX%02hhX}"
-#define PRIGUID_PARAM(g) = \
- (g).Data1, (g).D= ata2, (g).Data3, (g).Data4[0], (g).Data4[1], (g).Data4[2], (g).Data4[3], (g= ).Data4[4], (g).Data4[5], (g).Data4[6], (g).Data4[7]
-#define PRIGUID_PARAM_REF(g) \
- &(g).Data1, &(g).Data2= , &(g).Data3, &(g).Data4[0], &(g).Data4[1], &(g).Data4[2], = &(g).Data4[3], &(g).Data4[4], &(g).Data4[5], &(g).Data4[6],= &(g).Data4[7]

+#= define PRIXGUID "{%08lX-%04hX-%04hX-%02hhX%02hhX-%02hhX%02hhX%02hhX%02= hhX%02hhX%02hhX}"
+#define PRIGUID_PARAM_REF(g) = \
+ &(g).Data1, &(g).Data2, &= amp;(g).Data3, &(g).Data4[0], &(g).Data4[1], &(g).Data4[2], \
+ &(g).Data= 4[3], &(g).Data4[4], &(g).Data4[5], &(g).Data4[6], &(g).Dat= a4[7]

-#define __L(q) L ## q
-#define _L(q) __L(q)
+#define __L(q) L##q
+#define _L(q) __L(q)

#ifndef _In_

#define _In_
diff --git a= /src/tapctl/error.h b/src/tapctl/error.h
index 3da5674..fb2= 4a61 100644
--- a/src/tapctl/error.h
+++ b/= src/tapctl/error.h
@@ -34,27 +34,27 @@

/* msg() flags */

-#define M_DEBUG_LEVEL (0x0F) /* de= bug level mask */
+#d= efine M_DEBUG_LEVEL (0x0F) /* debug level mask */
<= br>-#define M_FATAL (1&= lt;<4) /* exit program */
-#define M_NONFATAL (1<<5) /* non-fatal = error */
-#define M_WAR= N (1<<6) /* call syslog with LOG_WARNING */=
-#define M_DEBUG (1= <<7)
+#define M= _FATAL (1 << 4) /* exit program */
+#define M_NONFATAL (1 << 5) /* non-fatal er= ror */
+#define M_WAR= N (1 << 6) /* call syslog with LOG_WARNING */
+#define M_DEBUG (1 << 7)

-#define = M_ERRNO (1<<8) /* show errno description */<= br>+#define M_ERRNO (1 <<= 8) /* show errno description */

-#define M_NOMUTE (1<<11= ) /* don't do mute processing */
-#define M_NOPREFIX (1<<12) /* don= 't show date/time prefix */
-#define M_USAGE_SMALL (1<<13) /* fatal options e= rror, call usage_small */
-#define M_MSG_VIRT_OUT (1<<14) /* output message throug= h msg_status_output callback */
-#define M_OPTERR (1<<15) /* print "Opt= ions error:" prefix */
-#define M_NOLF (1<<16) /* don't print new= line */
-#define M_NOI= PREFIX (1<<17) /* don't print instance prefix */
+#define M_NOMUTE = (1 << 11) /* don't do mute processing */
+#define M_NOPREFIX (1 << 12) /* do= n't show date/time prefix */
+#define M_USAGE_SMALL (1 << 13) /* fatal options error,= call usage_small */
= +#define M_MSG_VIRT_OUT (1 << 14) /* output message through msg_statu= s_output callback */
= +#define M_OPTERR (1 << 15) /* print "Options error:"= prefix */
+#define M= _NOLF (1 << 16) /* don't print new line */
+#define M_NOIPREFIX (1 <<= 17) /* don't print instance prefix */


/* flag combinations which are frequently used */

-#define M_ERR (M_FATAL | M_ERRNO)
-#define M_USAGE (M_USAGE_= SMALL | M_NOPREFIX | M_OPTERR)
-#define M_CLIENT (M_MSG_VIRT_OUT | M_NOMUTE | M_NOIPREFIX)=
+#define M_ERR (M_FATAL = | M_ERRNO)
+#define M= _USAGE (M_USAGE_SMALL | M_NOPREFIX | M_OPTERR)
+#define M_CLIENT (M_MSG_VIRT_OUT | M_NOMUTE | M= _NOIPREFIX)


/** Check = muting filter */
@@ -62,18 +62,42 @@

/* Macro to ensure (and teach static analysis tools) we exit o= n fatal errors */
#ifdef _MSC_VER
-#pragma warning(disable: 4127) /* EXIT_FATAL(f= lags) macro raises "warning C4127: conditional expression is constant&= quot; on each non M_FATAL invocation. */
+#pragma warning(disable : 4127) /* EXIT_FATAL(flags) m= acro raises "warning C4127: conditional \
+ expression is= constant" on each non M_FATAL invocation. */
#endif<= /span>
-#define EXIT_FATAL(fla= gs) do { if ((flags) & M_FATAL) {_exit(1);}} while (false)
+#define EXIT_FATAL(flags) \=

+ do = \
+ { = \
+ if ((flags) & M_FATAL) \
+ { \
+ _exit(1); \
+ } = \
+ } while = (false)

-#define msg(flags, ...) do { if (msg_test(flags)) {x_msg((flags), __VA_= ARGS__);} EXIT_FATAL(flags); } while (false)
+#define msg(flags, ...) \<= br>+ do = \
+ = { \
+ if (msg_test(flags)) \
+ { = \

+ = x_msg((flags), __VA_ARGS__); \
+ } \
+ EXIT_FATAL(flags); = \
+ } while (fal= se)
#ifdef ENABLE_DEBUG
-#define dmsg(flags, ...) do { if (msg_test(flags)) {x_ms= g((flags), __VA_ARGS__);} EXIT_FATAL(flags); } while (false)
+#define dmsg(flags, ...) = \

+ do = \
+ { \
+ if (msg_test(flags)) = \
+ { = \
+ x_msg((flags), __VA_ARGS__); \
+ } \
+ EXIT_FATAL(flag= s); \
+= } while (false)
#else
#define dmsg(fl= ags, ...)
#endif

-void x_msg(const unsigned int flags, const = char *format, ...); /* should be called via msg above */
+void x_msg(const unsigned int flag= s, const char *format, ...); /* should be called via msg above */

void x_msg_va(const unsigned int flags, const cha= r *format, va_list arglist);

diff --git a= /src/tapctl/main.c b/src/tapctl/main.c
index 0dec303..031e2= 62 100644
--- a/src/tapctl/main.c
+++ b/src= /tapctl/main.c
@@ -120,9 +120,7 @@
static = void
usage(void)
{
- fwprintf(stderr,
- usage_message,
- title_string);
+ fwprintf(stderr, usage_me= ssage, title_string);
}

= /**
@@ -139,8 +137,10 @@
{
LPOLESTR adapter_id =3D NULL;
StringFromIID((REFIID)&a->guid, &adapter_id);=

- fwpri= ntf(stderr, L"Adapter \"%ls\" already exists (GUID %"
- = L"ls).\n", a->szName, adapter_id);
+ fwprintf(stderr,
+ L"= Adapter \"%ls\" already exists (GUID %"

+ L"ls).\n&q= uot;,
+ = a->szName, adapter_id);
CoTa= skMemFree(adapter_id);
}

@@ -204,8 +204,7 @@
/**
* P= rogram entry point
*/
-int __cdecl
-wmain(int argc, LPCWSTR argv[])
+int __cdecl wmain(int argc, LPCWSTR argv[])
<= span> {

int iResult;
BOOL bReboot= Required =3D FALSE;
@@ -239,8 +238,10 @@
= }
else
{- fwprintf(stderr, L&= quot;Unknown command \"%ls"
- L"\". Please, use \"tap= ctl help\" to list supported commands.\n", argv[2]);
+ fwprintf(stderr,
+ L&= quot;Unknown command \"%ls"
+ L"\". Please, use \"t= apctl help\" to list supported commands.\n",
+ argv[2]); }

return 1;
@@ -263,25 +264,24 @@
}
= else
{
- fwprintf(stderr, L"Un= known option \"%ls"
- L"\". Please, use \"tapctl = help create\" to list supported options. Ignored.\n",
<= span style=3D"color: hsl(0, 100%, 40%);">- argv[i])= ;

+ fw= printf(
+ = stderr,
+ = L"Unknown option \"%ls"
+ L"\". Plea= se, use \"tapctl help create\" to list supported options. Ignored= .\n",
+ = argv[i]);
}
= }

/* Create TUN/TAP adapter. *= /
GUID guidAdapter;
LPOLE= STR szAdapterId =3D NULL;
- DWORD dwResult =3D tap_create_adapter(
- NULL,
- L"Virtual Ethernet",<= br>- szHwId,- &bRebootRequire= d,
- &gu= idAdapter);
+ = DWORD dwResult =3D
+ = tap_create_adapter(NULL, L"Virtual Ethernet", szHwId, = &bRebootRequired, &guidAdapter);
if (dwRes= ult !=3D ERROR_SUCCESS)
{
= fwprintf(stderr, L"Creating TUN/TAP adapter failed (error 0x%x).\= n", dwResult);
- = iResult =3D 1; goto quit;
+ iResult =3D 1;
+ goto quit;
}


/* Get existing network adapters. = */
@@ -294,7 +294,8 @@
goto cr= eate_delete_adapter;
}
- LPWSTR adapter_name =3D= szName ? wcsdup(szName) : get_unique_adapter_name(szHwId, pAdapterList);
+ LPWSTR adapte= r_name =3D
+ = szName ? wcsdup(szName) : get_unique_adapter_name(szHwId, pAdapterList);=
if (adapter_name)
{
/* Check for duplicates when name was specified,
@@ -310,11 +311,13 @@
if (dwRes= ult !=3D ERROR_SUCCESS)
{
= StringFromIID((REFIID)&guidAdapter, &szAdapterId);
- fwprintf(= stderr, L"Renaming TUN/TAP adapter %ls"
+ fwprintf(stderr,
+ L"= Renaming TUN/TAP adapter %ls"

= L" to \"%ls\" failed (error 0x%x).\n",
szAdapterId, adapter_name, dwResult);
CoTaskMemFree(szAdapterId);
- iResult =3D 1; goto quit;
+ iResu= lt =3D 1;
+ = goto quit;
}
}<= /span>

@@ -334,21 +337,19 @@
= fwprintf(stdout, L"%ls\n", szAdapterId);
= CoTaskMemFree(szAdapterId);

- iResult =3D 0; goto quit;+ iResult =3D 0;=
+ goto quit;<= br>
create_delete_adapter:
- tap_delete_adapter(
- NULL,
- &guidAdapter,
- &bRebootRequired);<= /span>
- iResult =3D 1;= goto quit;
+ = tap_delete_adapter(NULL, &guidAdapter, &bRebootRequired);+ iResult =3D 1;=
+ goto quit;<= br> }
else if (wcsicmp(argv[1], L"list&= quot;) =3D=3D 0)
{
WCHAR szzH= wId[0x100] =3D
- = L"root\\" _L(TAP_WIN_COMPONENT_ID) L"\0"- _L(TAP_WIN_COMPONEN= T_ID) L"\0"
-= L"ovpn-dco\0";
+ L"root\\" _L(TAP_WIN_COMPONENT_ID) L= "\0" _L(TAP_WIN_COMPONENT_ID) L"\0"
+ = L"ovpn-dco\0";
<= span>

/* Parse options. */
= for (int i =3D 2; i < argc; i++)
@@ -357,13 +358,17 @= @
{
memset(sz= zHwId, 0, sizeof(szzHwId));
++i;- memcpy_s(szzHwI= d, sizeof(szzHwId) - 2*sizeof(WCHAR) /*requires double zero termination*/, = argv[i], wcslen(argv[i])*sizeof(WCHAR));
+ memcpy_s(szzHwId,
+ sizeof(szzHwId)= - 2 * sizeof(WCHAR) /*requires double zero termination*/,
+ argv[i], wc= slen(argv[i]) * sizeof(WCHAR));
}
else

{
- fwprintf(stderr, L"Unk= nown option \"%ls"
- L"\". Please, use \"tapctl h= elp list\" to list supported options. Ignored.\n",
- argv[i]);
+ fwpri= ntf(
+ = stderr,
+ = L"Unknown option \"%ls"
+ L"\". Pleas= e, use \"tapctl help list\" to list supported options. Ignored.\n= ",
+ = argv[i]);
}
}=

@@ -373,15 +378,18 @@
= if (dwResult !=3D ERROR_SUCCESS)
{ fwprintf(stderr, L"Enumerating TUN/TAP adapters f= ailed (error 0x%x).\n", dwResult);
- iResult =3D 1; goto quit;
+ iResult =3D 1;
+ goto quit;
}

for (struct ta= p_adapter_node *pAdapter =3D pAdapterList; pAdapter; pAdapter =3D pAdapter-= >pNext)
{
LPOLESTR= szAdapterId =3D NULL;
StringFromIID((REFIID)&= amp;pAdapter->guid, &szAdapterId);
- fwprintf(stdout, L"%ls\t%"=
- L"= ls\n", szAdapterId, pAdapter->szName);
+ fwprintf(stdout,
+ L"%ls\t%"= ;
+ = L"ls\n",
+ szAdapterId, pAdapter->szName);
= CoTaskMemFree(szAdapterId);
}
@@ -392,7 +400,9 @@
{=
if (argc < 3)
{
- fwprintf(stderr, L&quo= t;Missing adapter GUID or name. Please, use \"tapctl help delete\"= ; for usage info.\n");

+ fwprintf(
+ stderr,
+ L"Missing adapter GUID or name. Please, = use \"tapctl help delete\" for usage info.\n");
return 1;

}

@@ -405,7 +415,8 @@
if (dwResult = !=3D ERROR_SUCCESS)
{
= fwprintf(stderr, L"Enumerating TUN/TAP adapters failed (error= 0x%x).\n", dwResult);
- iResult =3D 1; goto quit;
+ iResult =3D 1;
+ goto quit; }

for (s= truct tap_adapter_node *pAdapter =3D pAdapterList;; pAdapter =3D pAdapter-&= gt;pNext)
@@ -413,7 +424,8 @@
= if (pAdapter =3D=3D NULL)
{
= fwprintf(stderr, L"\"%ls\" adapte= r not found.\n", argv[2]);
- iResult =3D 1; goto delete_cleanup_pAdapterLi= st;
+ = iResult =3D 1;
+ = goto delete_cleanup_pAdapterList;
= }
else if (wcsicmp(argv[2], pAd= apter->szName) =3D=3D 0)
{
@@ -433,23 +445,26 @@

}

/* Delete the network adapter. */
- DWORD dwResult =3D tap_delete_adap= ter(
- NULL,=
- &guid= Adapter,
- &= amp;bRebootRequired);
+ DWORD dwResult =3D tap_delete_adapter(NULL, &guidAdapter, &am= p;bRebootRequired);
if (dwResult !=3D ERROR_SUCCES= S)
{
- fwprintf(stderr, L"Deleting adapter \"%ls&quo= t;
- = L"\" failed (error 0x%x).\n", argv[2], dwResult);- iResult =3D 1; got= o quit;
+ = fwprintf(stderr,
+ = L"Deleting adapter \"%ls"
+ L"\" = failed (error 0x%x).\n",
+ argv[2], dwResult);
+ iResult =3D 1;
+ goto quit;
}


- iResult =3D 0; goto quit;
+ iResult =3D 0;
+ goto quit;
}<= br> else
{
- fwprintf(stderr, L"Unknown command \"= %ls"
- = L"\". Please, use \"tapctl help\" to list supporte= d commands.\n", argv[1]);
+ fwprintf(stderr,
+ L"Unknown command \"%ls"
+ L&quo= t;\". Please, use \"tapctl help\" to list supported commands= .\n",
+ = argv[1]);
return 1;
}=

@@ -484,16 +499,13 @@
= /* Output system error message (if possible). */
= DWORD dwResult =3D GetLastError();
LPWSTR sz= ErrMessage =3D NULL;
- = if (FormatMessage(
- FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BU= FFER | FORMAT_MESSAGE_IGNORE_INSERTS,
- 0,
- dwResult,
- 0,
- (LPWSTR)&szErrMessage,
- 0,
- NULL) && szErrMessa= ge)
+ if (Form= atMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER
+ = | FORMAT_MESSAGE_IGNORE_INSERTS,
+ 0, dwResult, 0, (LPWSTR)&sz= ErrMessage, 0, NULL)
= + && szErrMessage)
{
= - /* Trim trailing whi= tespace. Set terminator after the last non-whitespace character. This preve= nts excessive trailing line breaks. */
+ /* Trim trailing whitespace. Set terminator = after the last non-whitespace character.
+ * This prevents excessive trailing line b= reaks. */
for (size_t i =3D 0, i_last =3D 0;; = i++)
{
if (sz= ErrMessage[i])
diff --git a/src/tapctl/tap.c b/src/tapctl/t= ap.c
index 96f09ee..09be7e8 100644
--- a/sr= c/tapctl/tap.c
+++ b/src/tapctl/tap.c
@@ -4= 0,10 +40,15 @@
#endif

<= /span>
-const static GUID GUID= _DEVCLASS_NET =3D { 0x4d36e972L, 0xe325, 0x11ce, { 0xbf, 0xc1, 0x08, 0x00, = 0x2b, 0xe1, 0x03, 0x18 } };
+const static GUID GUID_DEVCLASS_NET =3D {
+ 0x4d36e972L, 0xe325, 0x11ce, { 0xbf, 0xc1= , 0x08, 0x00, 0x2b, 0xe1, 0x03, 0x18 }
+};

-const static WCHAR szAdapterRegKeyPathTemplate[] =3D L&qu= ot;SYSTEM\\CurrentControlSet\\Control\\Network\\%ls\\%ls\\Connection";=
-#define ADAPTER_REGKE= Y_PATH_MAX (_countof(L"SYSTEM\\CurrentControlSet\\Control\\Network\\&q= uot;) - 1 + 38 + _countof(L"\\") - 1 + 38 + _countof(L"\\Con= nection"))
+cons= t static WCHAR szAdapterRegKeyPathTemplate[] =3D
+ L"SYSTEM\\CurrentControlSet\\Control\= \Network\\%ls\\%ls\\Connection";
+#define ADAPTER_REGKEY_PATH_MAX = \
+ (_countof(L"SYSTEM\\CurrentControlSet\\Control= \\Network\\") - 1 + 38 + _countof(L"\\") - 1 \
+ + 38 + _countof(L"\\Con= nection"))


/**
* = Dynamically load a library and find a function in it
@@ -15= 4,10 +159,8 @@
*
* @return ERROR_SUCCES= S on success; Win32 error code otherwise
**/
-typedef DWORD (*devop_func_t)(
- _In_ HDEVINFO hDevice= InfoSet,
- _In_ PSP_= DEVINFO_DATA pDeviceInfoData,
- _Inout_ LPBOOL pbRebootRequired);
+typedef DWORD (*devop_func_t)(_In_ HDEVINFO hDevi= ceInfoSet, _In_ PSP_DEVINFO_DATA pDeviceInfoData,
+ _Inout_ LPBOOL = pbRebootRequired);


/**=
@@ -177,10 +180,8 @@
* @return ERROR_SUC= CESS on success; Win32 error code otherwise
**/ static DWORD
-c= heck_reboot(
- _In_ = HDEVINFO hDeviceInfoSet,
- _Inout_ LPBOOL pbRebootRequired)
+check_reboot(_In_ HDEVINFO hDevice= InfoSet, _In_ PSP_DEVINFO_DATA pDeviceInfoData,

+ _Inout_ LPBOOL pbRebootRequired)
{
if (pbRebootRequired =3D=3D NULL)
{
@@ -188,10 +189,7 @@
= }

SP_DEVINSTALL_PARAMS devinstal= l_params =3D { .cbSize =3D sizeof(SP_DEVINSTALL_PARAMS) };
- if (!SetupDiGetDeviceInstallParams= (
- hDeviceI= nfoSet,
- pD= eviceInfoData,
- = &devinstall_params))
+ if (!SetupDiGetDeviceInstallParams(hDeviceInfoSet, pDeviceInf= oData, &devinstall_params))
{
= DWORD dwResult =3D GetLastError();
msg(M_NONF= ATAL | M_ERRNO, "%s: SetupDiGetDeviceInstallParams failed", __FUN= CTION__);
@@ -224,10 +222,8 @@
* @return = ERROR_SUCCESS on success; Win32 error code otherwise
**/<= /span>
static DWORD
-delete_device(
= - _In_ HDEVINFO hDeviceInfoSet,
- _In_ PSP_DEVINFO_DATA pDeviceInfoData,
- _Inout_ LPBOOL pbRebootRequired)
+delete_device(_In_ HDEVI= NFO hDeviceInfoSet, _In_ PSP_DEVINFO_DATA pDeviceInfoData,
+ _Inout_ LPBOOL pbReboo= tRequired)
{
SP_REMOVEDEVICE_PARAMS p= arams =3D
{
@@ -241,11 +237,8 @@
};

/* Set class inst= aller parameters for DIF_REMOVE. */
- if (!SetupDiSetClassInstallParams(
- hDeviceInfoSet,
- pDeviceInfoData,
- &params.ClassI= nstallHeader,
- = sizeof(SP_REMOVEDEVICE_PARAMS)))
+ if (!SetupDiSetClassInstallParams(hDeviceInfoSet, pDev= iceInfoData, &params.ClassInstallHeader,
+ sizeof(SP_RE= MOVEDEVICE_PARAMS)))
{
DWORD = dwResult =3D GetLastError();
msg(M_NONFATAL | M_ER= RNO, "%s: SetupDiSetClassInstallParams failed", __FUNCTION__);
@@ -253,10 +246,7 @@
}
=
/* Call appropriate class installer. */
- if (!SetupDiCallClassInstaller(=

- DIF_REMOV= E,
- hDevice= InfoSet,
- p= DeviceInfoData))
+ = if (!SetupDiCallClassInstaller(DIF_REMOVE, hDeviceInfoSet, pDeviceInfoData= ))
{
DWORD dwResult =3D GetLa= stError();
msg(M_NONFATAL | M_ERRNO, "%s: Set= upDiCallClassInstaller(DIF_REMOVE) failed", __FUNCTION__);
<= span>@@ -288,11 +278,8 @@

* @return ERROR_SUCCESS on succ= ess; Win32 error code otherwise
**/
stat= ic DWORD
-change_device= _state(
- _In_ HDEVI= NFO hDeviceInfoSet,
- = _In_ PSP_DEVINFO_DATA pDeviceInfoData,
- _In_ BOOL bEnable,
- _Inout_ LPBOOL pbRebootRequired)
+change_device_state(_In_ HDEVINFO hDev= iceInfoSet, _In_ PSP_DEVINFO_DATA pDeviceInfoData,
+ _In_ BOOL bEnable, _Inou= t_ LPBOOL pbRebootRequired)
{
SP_PROP= CHANGE_PARAMS params =3D
{
@@ -307,11 = +294,8 @@
};

/*= Set class installer parameters for DIF_PROPERTYCHANGE. */
- if (!SetupDiSetClassInstallParams(=
- hDeviceIn= foSet,
- pDe= viceInfoData,
- = &params.ClassInstallHeader,
- sizeof(SP_PROPCHANGE_PARAMS)))
+ if (!SetupDiSetClassInstallParams(= hDeviceInfoSet, pDeviceInfoData, &params.ClassInstallHeader,
= + = sizeof(SP_PROPCHANGE_PARAMS)))
{
DWORD dwResult =3D GetLastError();

msg= (M_NONFATAL | M_ERRNO, "%s: SetupDiSetClassInstallParams failed",= __FUNCTION__);
@@ -319,13 +303,11 @@
= }

/* Call appropriate class installe= r. */
- if (!SetupDi= CallClassInstaller(
- = DIF_PROPERTYCHANGE,
- hDeviceInfoSet,
- pDeviceInfoData))
+ if (!SetupDiCallClassInstaller(DIF_PROPERTYCHAN= GE, hDeviceInfoSet, pDeviceInfoData))
{
DWORD dwResult =3D GetLastError();

- msg(M_NONFATAL | M_ERRNO, "%s: SetupDi= CallClassInstaller(DIF_PROPERTYCHANGE) failed", __FUNCTION__);<= br>+ msg(M_NONFATAL | M_= ERRNO, "%s: SetupDiCallClassInstaller(DIF_PROPERTYCHANGE) failed"= ,
+ __FUNC= TION__);
return dwResult;
}

@@ -352,10 +334,8 @@
* @= return ERROR_SUCCESS on success; Win32 error code otherwise
**/

static DWORD
-enable_device(
- _In_ HDEVINFO hDeviceInfoSet,
- _In_ PSP_DEVINFO_DATA pDeviceInfoData,
- _Inout_ LPBOOL pbRebootRequire= d)

+enable_device(_In= _ HDEVINFO hDeviceInfoSet, _In_ PSP_DEVINFO_DATA pDeviceInfoData,+ _Inout_ LPBOOL = pbRebootRequired)
{
return change_dev= ice_state(hDeviceInfoSet, pDeviceInfoData, TRUE, pbRebootRequired);<= br> }
@@ -378,10 +358,8 @@
* @retur= n ERROR_SUCCESS on success; Win32 error code otherwise
**= /
static DWORD
-disable_device(
- _In_ HDEVINFO hDeviceInfoSet,
- _In_ PSP_DEVINFO_DATA pDeviceInfoData,
- _Inout_ LPBOOL pbRebootRequired)
+disable_device(_In_ H= DEVINFO hDeviceInfoSet, _In_ PSP_DEVINFO_DATA pDeviceInfoData,
+ _Inout_ LPBOOL pb= RebootRequired)

{
return change_devic= e_state(hDeviceInfoSet, pDeviceInfoData, FALSE, pbRebootRequired); }
@@ -402,10 +380,7 @@
* @return= ERROR_SUCCESS on success; Win32 error code otherwise
*/<= /span>
static DWORD
-get_reg_string(
- _In_ HKEY hKey,
-= _In_ LPCWSTR szName,
+get_reg_string(_In_ HKEY hKey, _In_ LPCWSTR szName, _Out_ LPWSTR= *pszValue)
{
if (pszValue =3D=3D NUL= L)
{
@@ -413,17 +388,13 @@
<= span> }


DWORD dwValueType =3D RE= G_NONE, dwSize =3D 0;
-= DWORD dwResult =3D RegQueryValueEx(
- hKey,
- szName,
- NULL,
- = &dwValueType,
-= NULL,
- = &dwSize);
+ DW= ORD dwResult =3D RegQueryValueEx(hKey, szName, NULL, &dwValueType, NULL= , &dwSize);
if (dwResult !=3D ERROR_SUCCESS)
{
- = SetLastError(dwResult); /* MSDN does not mention RegQueryValueEx() to s= et GetLastError(). But we do have an error code. Set last error manually. *= /
- msg(M_NONFAT= AL | M_ERRNO, "%s: enumerating \"%ls\" registry value failed= ", __FUNCTION__, szName);
+ SetLastError(dwResult); /* MSDN does not mention RegQuer= yValueEx() to set GetLastError().
+ But we do have an error co= de. Set last error manually. */
+ msg(M_NONFATAL | M_ERRNO, "%s: enumerating \"= %ls\" registry value failed", __FUNCTION__,
+ szName);
= return dwResult;
}

@@ -440,17 +411,14 @@

return ERROR_OUT= OFMEMORY;
}

- dwResult =3D RegQueryValue= Ex(
- hK= ey,
- sz= Name,
- = NULL,
- = NULL,
- = (LPBYTE)szValue,
- = &dwSize);
+ dwResult =3D RegQueryValueEx(hKey, szName, NULL, NULL, (LP= BYTE)szValue, &dwSize);
if (dwResult !=3D = ERROR_SUCCESS)
{
- SetLastError(dwResult); /* MSDN doe= s not mention RegQueryValueEx() to set GetLastError(). But we do have an er= ror code. Set last error manually. */
- msg(M_NONFATAL | M_ERRNO, "%s: reading= \"%ls\" registry value failed", __FUNCTION__, szName);
+ SetLastE= rror(
+ = dwResult); /* MSDN does not mention RegQueryValueEx() to set GetLastE= rror(). But
+ = we do have an error code. Set last error manually= . */
+ = msg(M_NONFATAL | M_ERRNO, "%s: reading \"%ls\" registry val= ue failed", __FUNCTION__,
+ szName);
fr= ee(szValue);
return dwResult;
}

@@ -459,12 +427,12 @@
= {
/* Expand the environment str= ings. */
DWORD
- dwSizeExp =3D dwSize * 2,
- dwCou= ntExp =3D
+ = dwSizeExp =3D dwSize * 2, dwCountExp =3D
#ifdef UNIC= ODE
- = dwSizeExp / sizeof(WCHAR);
+ dwSizeExp / sizeof(WCH= AR);
#else
- dwSizeExp / sizeof(WCHAR) - 1; /* Note: ANSI = version requires one extra char. */
+ dwSizeExp / siz= eof(WCHAR)
+ = - 1; /* Note: ANSI version requires one = extra char. */
#endif
LPW= STR szValueExp =3D (LPWSTR)malloc(dwSizeExp);
= if (szValueExp =3D=3D NULL)
@@ -474,13 +442,11 @@
return ERROR_OUTOFMEMORY;
= }

- DWORD dwCountExpResult =3D ExpandEnvironmentS= trings(
- = szValue,
- = szValueExp, dwCountExp
- );
+ DWORD dwCountExpResult =3D ExpandEnvironme= ntStrings(szValue, szValueExp, dwCountExp);
= if (dwCountExpResult =3D=3D 0)
{<= br>- msg(M_NON= FATAL | M_ERRNO, "%s: expanding \"%ls\" registry value faile= d", __FUNCTION__, szName);
+ msg(M_NONFATAL | M_ERRNO, "%s: expandi= ng \"%ls\" registry value failed",
+ __FUNCTION__, szName)= ;
free(szValueExp);
= free(szValue);
retu= rn dwResult;
@@ -511,9 +477,7 @@
= return ERROR_OUTOFMEMORY;
= }

= - dwCountExpResult =3D ExpandEnvironmentStrings(<= br>- szVal= ue,
- = szValueExp, dwCountExp);
+ dwCountExpResult =3D ExpandEnvironmentString= s(szValue, szValueExp, dwCountExp);
fr= ee(szValue);
*pszValue =3D szValueExp;=
return ERROR_SUCCESS;
@@ -527,7 +491,8 @@

}
default:
+ msg(M_NONFATAL, "%s:= \"%ls\" registry value is not string (type %u)", __FUNCTION= __,
+ = dwValueType);
return ERROR_UNSUPPORTED_TYPE;
}
}
@@ -552,11 +517,8 = @@
* @return ERROR_SUCCESS on success; Win32 error code o= therwise
**/
static DWORD
-get_net_adapter_guid(

- _In_ HDEVINFO hDeviceInfoSet,
- _In_ PSP_DEVINFO_DAT= A pDeviceInfoData,
- = _In_ int iNumAttempts,
- _Out_ LPGUID pguidAdapter)
+get_net_adapter_guid(_In_ HDEVINFO hDeviceInfoSet, _In_ PSP_DE= VINFO_DATA pDeviceInfoData,
+ _In_ int iNumAttempts, _Out_ LPGUID pguidAdapt= er)
{
DWORD dwResult =3D ERROR_BAD_AR= GUMENTS;

@@ -566,13 +528,8 @@
<= span> }


/* Open HKEY_LOCAL_MACHI= NE\SYSTEM\CurrentControlSet\Control\Class\<class>\<id> registry= key. */
- HKEY hKey= =3D SetupDiOpenDevRegKey(
- hDeviceInfoSet,
- pDeviceInfoData,
- DICS_FLAG_GLOBAL,
- 0,
-= KEY_READ);
+ = HKEY hKey =3D SetupDiOpenDevRegKey(hDeviceInfoSet, pDeviceInfoData, DICS= _FLAG_GLOBAL, 0,
+ = DIREG_DRV, KEY_READ);
= if (hKey =3D=3D INVALID_HANDLE_VALUE)
{
dwResult =3D GetLastError();

@@ -582,7 +539,8 = @@

while (iNumAttempts > 0)
{
- = /* Query the NetCfgInstanceId value. Using get_reg_string() right on mi= ght clutter the output with error messages while the registry is still bein= g populated. */
+ = /* Query the NetCfgInstanceId value. Using get_reg_string() right on mi= ght clutter the
+ = * output with error messages while the registry is still being populat= ed. */
LPWSTR szCfgGuidString =3D NULL;
= dwResult =3D RegQueryValueEx(hKey, L"NetCfgInstanceId&q= uot;, NULL, NULL, NULL, NULL);
if (dwResult !=3D E= RROR_SUCCESS)
@@ -594,22 +552,24 @@
= continue;
}
=
- SetLastError(dwR= esult); /* MSDN does not mention RegQueryValueEx() to set GetLastError(). B= ut we do have an error code. Set last error manually. */
- msg(M_NONFATAL | M_ERRNO, &q= uot;%s: querying \"NetCfgInstanceId\" registry value failed"= , __FUNCTION__);
+ = SetLastError(
+ do have an error code. Set last error= manually. */
+ = msg(M_NONFATAL | M_ERRNO, "%s: querying \"NetCfgInstanceId\= " registry value failed",
+ __FUNCTION__);
= break;
}

= /* Read the NetCfgInstanceId value now. */
- dwResult =3D get_reg_string(
- hKey,

- L"NetCfgInstanceId"= ;,
- &sz= CfgGuidString);
+ = dwResult =3D get_reg_string(hKey, L"NetCfgInstanceId", &s= zCfgGuidString);
if (dwResult !=3D ERROR_SUCCESS)<= /span>
{
break;
}


- dwResult =3D SUCCEEDED(CLSIDFromString(szCfgGuidString, = (LPCLSID)pguidAdapter)) ? ERROR_SUCCESS : ERROR_INVALID_DATA;
+ dwResult =3D SUCCEEDED(CL= SIDFromString(szCfgGuidString, (LPCLSID)pguidAdapter))

+ ? ERROR_SUCCESS
+ = : ERROR_INVALID_DATA;
free(szCfgGuidString);
break;
}
@@ -641= ,12 +601,9 @@
* @return ERROR_SUCCESS on success; Win32 e= rror code otherwise
**/
static DWORD
-get_device_reg_property(<= /span>
- _In_ HDEVINFO hDev= iceInfoSet,
- _In_ P= SP_DEVINFO_DATA pDeviceInfoData,
- _In_ DWORD dwProperty,
- _Out_opt_ LPDWORD pdwPropertyRegDataType,
- _Out_ LPVOID *ppData)
+get_device_reg_property(_In_ = HDEVINFO hDeviceInfoSet, _In_ PSP_DEVINFO_DATA pDeviceInfoData,
<= span style=3D"color: hsl(120, 100%, 40%);">+ _In_ DW= ORD dwProperty, _Out_opt_ LPDWORD pdwPropertyRegDataType,

+ _Out_ LPVOID = *ppData)
{
DWORD dwResult =3D ERROR_B= AD_ARGUMENTS;

@@ -658,14 +615,9 @@=
/* Try with stack buffer first. */
BYTE= bBufStack[128];
DWORD dwRequiredSize =3D 0;- if (SetupDiGetDeviceRegistr= yProperty(
- = hDeviceInfoSet,
- = pDeviceInfoData,
- dwProperty,
- pdwPropertyRegDataType,
- bBufStack,
- sizeof(bBufStack),
- &dwRequiredSize))
+ if (SetupDiGetDeviceRegistryP= roperty(hDeviceInfoSet, pDeviceInfoData, dwProperty,

+ = pdwPropertyRegDataType, bBufStack, sizeof(bBufStack),
+ = &dwRequiredSize))
{
/* Co= py from stack. */
*ppData =3D malloc(dwRequiredSiz= e);
@@ -691,27 +643,24 @@
= return ERROR_OUTOFMEMORY;
}
<= /span>
- if (SetupD= iGetDeviceRegistryProperty(
- hDeviceInfoSet,
- pDeviceInfoData,
- dwProperty,- pdwPropert= yRegDataType,
- = *ppData,
- = dwRequiredSize,
- &dwRequiredSize))
+ if (SetupDiGetDeviceRegistry= Property(hDeviceInfoSet, pDeviceInfoData, dwProperty,
+ = pdwPropertyRegDataType, *ppData, dwRequiredSize,
+ = &dwRequiredSize))
{
<= span> return ERROR_SUCCESS;

}<= /span>
else
{
= dwResult =3D GetLastError();
- msg(M_NONFATAL | M_ERRNO, &= quot;%s: SetupDiGetDeviceRegistryProperty(%u) failed", __FUNCTION__, d= wProperty);
+ = msg(M_NONFATAL | M_ERRNO, "%s: SetupDiGetDeviceRegistryPropert= y(%u) failed",
+= __FUNCTION__, dwProperty);
= return dwResult;
}
= }
else
{
- msg(M_NONFATAL | M_ERRN= O, "%s: SetupDiGetDeviceRegistryProperty(%u) failed", __FUNCTION_= _, dwProperty);

+ = msg(M_NONFATAL | M_ERRNO, "%s: SetupDiGetDeviceRegistryPropert= y(%u) failed",
+= __FUNCTION__, dwProperty);
ret= urn dwResult;
}
}
<= span>@@ -719,19 +668,13 @@



DWORD

-tap_create_= adapter(
- _In_opt_ = HWND hwndParent,
- _= In_opt_ LPCWSTR szDeviceDescription,
- _In_ LPCWSTR szHwId,
- _Inout_ LPBOOL pbRebootRequired,
- _Out_ LPGUID pguidAdapter)
<= span style=3D"color: hsl(120, 100%, 40%);">+tap_create_adapter(_In_opt_ HWN= D hwndParent, _In_opt_ LPCWSTR szDeviceDescription,

+ _In_ LPCWSTR szHwId, _= Inout_ LPBOOL pbRebootRequired, _Out_ LPGUID pguidAdapter)
= {
DWORD dwResult;
HMODULE libnew= dev =3D NULL;

- if (szHwId =3D=3D NULL
- || pbRebootRequired =3D=3D NULL
- || pguidAdapter =3D=3D NULL)
+ if (szHwId =3D=3D NUL= L || pbRebootRequired =3D=3D NULL || pguidAdapter =3D=3D NULL)
{

return ERROR_BAD_ARGUMENTS;
<= span> }

@@ -747,11 +690,7 @@
/* Get the device class name from GUID. */
= WCHAR szClassName[MAX_CLASS_NAME_LEN];
- if (!SetupDiClassNameFromGuid(
- &GUID_DEVCLASS_NET,<= br>- szClassName,
- _countof(szCla= ssName),
- N= ULL))
+ if (!Setup= DiClassNameFromGuid(&GUID_DEVCLASS_NET, szClassName, _countof(szClassNa= me), NULL))
{
dwResult =3D Ge= tLastError();
msg(M_NONFATAL, "%s: SetupDiCla= ssNameFromGuid failed", __FUNCTION__);
@@ -760,14 +699= ,8 @@

/* Create a new device info el= ement and add it to the device info set. */
SP_DEVINFO= _DATA devinfo_data =3D { .cbSize =3D sizeof(SP_DEVINFO_DATA) };
<= span style=3D"color: hsl(0, 100%, 40%);">- if (!SetupDiCreateDeviceInfo(=

- hDevInfoL= ist,
- szCla= ssName,
- &a= mp;GUID_DEVCLASS_NET,
-= szDeviceDescription,
- hwndParent,
- DICD_GENERATE_ID,
- &devinfo_data))
+ if (!SetupDiCreateDeviceInfo(hDevInfo= List, szClassName, &GUID_DEVCLASS_NET, szDeviceDescription,
<= span style=3D"color: hsl(120, 100%, 40%);">+ = hwndParent, DICD_GENERATE_ID, &devinfo_data))

{<= /span>
dwResult =3D GetLastError();
= msg(M_NONFATAL, "%s: SetupDiCreateDeviceInfo failed", __FUNCT= ION__);
@@ -775,9 +708,7 @@
}
/* Set a device information element as the s= elected member of a device information set. */
- if (!SetupDiSetSelectedDevice(
- hDevInfoList,

<= span style=3D"color: hsl(0, 100%, 40%);">- &devinfo_data))
+ if (!SetupDiSetSe= lectedDevice(hDevInfoList, &devinfo_data))
{
dwResult =3D GetLastError();
m= sg(M_NONFATAL, "%s: SetupDiSetSelectedDevice failed", __FUNCTION_= _);
@@ -785,11 +716,9 @@
}
<= span>

/* Set Plug&Play device hardware ID propert= y. */
- if (!SetupDi= SetDeviceRegistryProperty(
- hDevInfoList,
- &devinfo_data,
- SPDRP_HARDWAREID,
- (const BYTE *)szHwId, (DWORD)((wcslen= (szHwId) + 1) * sizeof(WCHAR))))
+ if (!SetupDiSetDeviceRegistryProperty(hDevInfoList, &d= evinfo_data, SPDRP_HARDWAREID,
+ (const BYTE *)szHwId,<= /span>
+ = (DWORD)((wcslen(szHwId) + 1) * sizeof(WCHAR))))
{
dwResult =3D GetLastError();
msg(M_NONFATAL, "%s: SetupDiSetDeviceRegistryPro= perty failed", __FUNCTION__);
@@ -797,10 +726,7 @@
}

/* Register the = device instance with the PnP Manager */
- if (!SetupDiCallClassInstaller(
- DIF_REGISTERDEVICE,
<= span style=3D"color: hsl(0, 100%, 40%);">- hDevInfoList,
<= br>- &devinfo_data= ))
+ if (!SetupDiC= allClassInstaller(DIF_REGISTERDEVICE, hDevInfoList, &devinfo_data))
{
dwResult =3D GetLastError();
msg(M_NONFATAL, "%s: SetupDiCallClassInstaller= (DIF_REGISTERDEVICE) failed", __FUNCTION__);
@@ -816,1= 0 +742,9 @@
if (!DiInstallDevice(hwndParent, hDevInfoL= ist, &devinfo_data, NULL, 0, pbRebootRequired))
#else<= /span>
/* mingw does not resolve DiInstallDevice, so load it = at run time. */
- ty= pedef BOOL (WINAPI *DiInstallDeviceFn)(HWND, HDEVINFO, SP_DEVINFO_DATA *,
- = SP_DRVINFO_DATA *, DWORD, BOOL *);
- DiInstallDeviceFn installfn- =3D find_function(L&qu= ot;newdev.dll", "DiInstallDevice", &libnewdev);+ typedef BOOL(WINAPI * Di= InstallDeviceFn)(HWND, HDEVINFO, SP_DEVINFO_DATA *, SP_DRVINFO_DATA *,
+ = DWORD, BOOL *);
+ DiInstallDeviceFn installfn =3D find_function(L"n= ewdev.dll", "DiInstallDevice", &libnewdev);

if (!installfn)
{@@ -855,24 +780,20 @@
};
<= /span>
/* Set class installer parameters for DIF_REMOVE. = */
- if (SetupDi= SetClassInstallParams(
= - hDevInfoList,
- &devinfo_data,
- &removedevice_params.ClassInstall= Header,
- = sizeof(SP_REMOVEDEVICE_PARAMS)))
+ if (SetupDiSetClassInstallParams(hDevInfoList, &= devinfo_data,
+ = &removedevice_params.ClassInstallHea= der,
+ = sizeof(SP_REMOVEDEVICE_PARAMS)))
= {
/* Call appropriate class installer= . */
- if (S= etupDiCallClassInstaller(
- DIF_REMOVE,
- hDevInfoList,
- &devinfo_data))+ if (SetupDiCallCl= assInstaller(DIF_REMOVE, hDevInfoList, &devinfo_data))
= {
/* Check if a system reboot= is required. */
check_reboot(hDevInfoList= , &devinfo_data, pbRebootRequired);
}
else
{
- msg(M_NONFATAL | M_E= RRNO, "%s: SetupDiCallClassInstaller(DIF_REMOVE) failed", __FUNCT= ION__);

+ = msg(M_NONFATAL | M_ERRNO, "%s: SetupDiCallClassInstaller(DIF_REMOV= E) failed",
+ = __FUNCTION__);
}
}

else
@@ -912,11 +83= 3,8 @@
* @return ERROR_SUCCESS on success; Win32 error co= de otherwise
**/
static DWORD
= -execute_on_first_adapter(=
- _In_opt_ HWND hwndParent= ,
- _In_ LPCGUID pgu= idAdapter,
- _In_ de= vop_func_t funcOperation,
- _Inout_ LPBOOL pbRebootRequired)
+execute_on_first_adapter(_In_opt_ HWND hwndParent, _In= _ LPCGUID pguidAdapter,
+ _In_ devop_func_t funcOperation, _Inout_ LPBOO= L pbRebootRequired)
{
DWORD dwResult;=

@@ -926,14 +844,8 @@
= }

/* Create a list of network devi= ces. */
- HDEVINFO h= DevInfoList =3D SetupDiGetClassDevsEx(
- &GUID_DEVCLASS_NET,
- NULL,
- hwndParent,
- DIGCF_PRESENT,
- NULL,
- NULL,
- NULL);
+ = HDEVINFO hDevInfoList =3D SetupDiGetClassDevsEx(&GUID_DEVCLASS_NET, NU= LL, hwndParent,
+ = DIGCF_PRESENT, NULL, NULL, NU= LL);
if (hDevInfoList =3D=3D INVALID_HANDLE_VALUE)
{
dwResult =3D GetLastError();
@@ -942,7 +854,8 @@
}
=
/* Retrieve information associated with a device info= rmation set. */
- SP= _DEVINFO_LIST_DETAIL_DATA devinfo_list_detail_data =3D { .cbSize =3D sizeof= (SP_DEVINFO_LIST_DETAIL_DATA) };
+ SP_DEVINFO_LIST_DETAIL_DATA devinfo_list_detail_data =3D {= .cbSize =3D sizeof(
= + SP_DEVINF= O_LIST_DETAIL_DATA) };
if (!SetupDiGetDeviceInfoListDe= tail(hDevInfoList, &devinfo_list_detail_data))
{
dwResult =3D GetLastError();
@@ -95= 5,10 +868,7 @@
{
/* Get the d= evice from the list. */
SP_DEVINFO_DATA devinfo_da= ta =3D { .cbSize =3D sizeof(SP_DEVINFO_DATA) };
- if (!SetupDiEnumDeviceInfo(
- hDevInfoList,
- dwIndex,
- &dev= info_data))
+ = if (!SetupDiEnumDeviceInfo(hDevInfoList, dwIndex, &devinfo_data))
{
if (GetLastError() =3D= =3D ERROR_NO_MORE_ITEMS)
{
@@ = -972,7 +882,8 @@
else
= {
/* Something is wrong with this dev= ice. Skip it. */
- = msg(M_WARN | M_ERRNO, "%s: SetupDiEnumDeviceInfo(%u) failed= ", __FUNCTION__, dwIndex);
+ msg(M_WARN | M_ERRNO, "%s: SetupDiEnumDevi= ceInfo(%u) failed", __FUNCTION__,
+ dwIndex);
= continue;
}
}<= /span>
@@ -1001,23 +912,19 @@

<= /span>
DWORD
= -tap_delete_adapter(
- = _In_opt_ HWND hwndParent,
- _In_ LPCGUID pguidAdapter,
- _Inout_ LPBOOL pbRebootRequired)
+tap_delete_adapter(_In_opt_ HWND hwndPare= nt, _In_ LPCGUID pguidAdapter,
+ _Inout_ LPBOOL pbRebootRequired)
{

return execute_on_first_adapter(hwndParent, pgu= idAdapter, delete_device, pbRebootRequired);
}
<= span>


DWORD
-tap_enable_adapter(
- _In_opt_ HWND hwndParent,
- _In_ LPCGUID pguidAdapter,
- _In_ BOOL bEnable,

<= span style=3D"color: hsl(0, 100%, 40%);">- _Inout_ LPBOOL pbRebootRequir= ed)

+tap_enable_adapt= er(_In_opt_ HWND hwndParent, _In_ LPCGUID pguidAdapter, _In_ BOOL bEnable,<= /span>
+ _= Inout_ LPBOOL pbRebootRequired)
{
- return execute_on_first_adapter(hwndParent= , pguidAdapter, bEnable ? enable_device : disable_device, pbRebootRequired)= ;
+ return execute= _on_first_adapter(hwndParent, pguidAdapter,
+ bEnable ? enabl= e_device : disable_device, pbRebootRequired);
}
=
/* stripped version of ExecCommand in interactive.= c */
@@ -1037,8 +944,8 @@

/* CreateProcess needs a modifiable cmdline: make a copy */
cmdline_dup =3D _wcsdup(cmdline);
- if (cmdline_dup && CreateProcessW(NULL,= cmdline_dup, NULL, NULL, FALSE,
- proc_flags, NULL, NULL, &a= mp;si, &pi))
+ = if (cmdline_dup
+ = && CreateProcessW(NULL, cmdline_dup, NULL, NULL, FALSE, proc_f= lags, NULL, NULL, &si, &pi))
{
WaitForSingleObject(pi.hProcess, INFINITE);

= if (!GetExitCodeProcess(pi.hProcess, &exit_code))
@= @ -1059,10 +966,7 @@
}

= DWORD
-tap_set_adapter_= name(
- _In_ LPCGUID= pguidAdapter,
- _In= _ LPCWSTR szName,
- = _In_ BOOL bSilent)
+t= ap_set_adapter_name(_In_ LPCGUID pguidAdapter, _In_ LPCWSTR szName, _In_ BO= OL bSilent)
{
DWORD dwResult;<= br> int msg_flag =3D bSilent ? M_WARN : M_NONFATAL;
@@ -1083,23 +987,16 @@


/* Render = registry key path. */
WCHAR szRegKey[ADAPTER_REGKEY_PA= TH_MAX];
- swprintf_= s(
- szRegKey, _= countof(szRegKey),
- = szAdapterRegKeyPathTemplate,
- szDevClassNetId,
- szAdapterId);
+ swprintf_s(szRegKey, _countof(szRegKey), szAdapterRegK= eyPathTemplate, szDevClassNetId,
+ szAdapterId);

/* Open network adapter registry key. */

HKEY hK= ey =3D NULL;
- dwRes= ult =3D RegOpenKeyEx(
-= HKEY_LOCAL_MACHINE,
- szRegKey,
- 0,
- K= EY_QUERY_VALUE,
- = &hKey);
+ dw= Result =3D RegOpenKeyEx(HKEY_LOCAL_MACHINE, szRegKey, 0, KEY_QUERY_VALUE, &= amp;hKey);
if (dwResult !=3D ERROR_SUCCESS)
= {
- S= etLastError(dwResult); /* MSDN does not mention RegOpenKeyEx() to set GetLa= stError(). But we do have an error code. Set last error manually. */=
+ SetLastError(dwRes= ult); /* MSDN does not mention RegOpenKeyEx() to set GetLastError(). But
+ = we do have an error code. Set last error manually. */ msg(msg_flag, "%s: RegOpenKeyEx(HKLM, \"%ls\&quo= t;) failed", __FUNCTION__, szRegKey);
goto cl= eanup_szAdapterId;
}
@@ -1142,10 +1039= ,8 @@


DWORD
= -tap_list_adapters(
- _In_opt_ HWND hwndParent,
- _In_opt_ LPCWSTR szzHwI= Ds,
- _Out_ struct t= ap_adapter_node **ppAdapter)
+tap_list_adapters(_In_opt_ HWND hwndParent, _In_opt_ LPCWSTR szzHw= IDs,
+ = _Out_ struct tap_adapter_node **ppAdapter)
{
= DWORD dwResult;

@@ -1155,14 +1= 050,8 @@
}

/* C= reate a list of network devices. */
- HDEVINFO hDevInfoList =3D SetupDiGetClassDevsEx(- &GUID_DEVCLASS_NET= ,
- NULL,=
- hwndParent,- DIGCF_PRESENT,<= br>- NULL,
- NULL,

- NULL);
+ HDEVINFO hDevInfoList =3D SetupDiGetClassDev= sEx(&GUID_DEVCLASS_NET, NULL, hwndParent,
+ = DIGCF_PRESENT, NULL, NULL, NULL);
if (hDevInfoList = =3D=3D INVALID_HANDLE_VALUE)
{
= dwResult =3D GetLastError();
@@ -1171,7 +1060,8 @@=
}

/* Retrieve informa= tion associated with a device information set. */
- SP_DEVINFO_LIST_DETAIL_DATA devinfo_list_de= tail_data =3D { .cbSize =3D sizeof(SP_DEVINFO_LIST_DETAIL_DATA) };+ SP_DEVINFO_LIST_DETAIL_D= ATA devinfo_list_detail_data =3D { .cbSize =3D sizeof(
+ = SP_DEVINFO_LIST_DETAIL_DATA) };
= if (!SetupDiGetDeviceInfoListDetail(hDevInfoList, &devinfo_list_deta= il_data))
{
dwResult =3D GetL= astError();
@@ -1190,10 +1080,7 @@
{
/* Get the device from the list. */
SP_DEVINFO_DATA devinfo_data =3D { .cbSize =3D sizeof(SP_DEVINFO_= DATA) };

- if (!= SetupDiEnumDeviceInfo(
= - hDevInfoList,
- dwIndex,
- &devinfo_data))
+ if (!SetupDiEnumDeviceInfo(hDevInfoList= , dwIndex, &devinfo_data))
{
= if (GetLastError() =3D=3D ERROR_NO_MORE_ITEMS)
= {
@@ -1202,7 +1089,8 @@
= else
{
= /* Something is wrong with this device. Skip it. */
- msg(M_WARN | M_ERRNO, "= ;%s: SetupDiEnumDeviceInfo(%u) failed", __FUNCTION__, dwIndex);=
+ msg(M_WARN= | M_ERRNO, "%s: SetupDiEnumDeviceInfo(%u) failed", __FUNCTION__,=
+ = dwIndex);
continue;
= }
}
@@ -1210,12 +1098,8 @@=
/* Get device hardware ID(s). */
= DWORD dwDataType =3D REG_NONE;
LPWSTR szz= DeviceHardwareIDs =3D NULL;
- dwResult =3D get_device_reg_property(
- hDevInfoList,
- &devinfo_data,- SPDRP_HARDWAREID,<= /span>
- &dwDat= aType,
- (LP= VOID)&szzDeviceHardwareIDs);
+ dwResult =3D get_device_reg_property(hDevInfoList, &am= p;devinfo_data, SPDRP_HARDWAREID,
+ &dwDataType, (= LPVOID)&szzDeviceHardwareIDs);
if (dwResult != =3D ERROR_SUCCESS)
{
= /* Something is wrong with this device. Skip it. */
@@ -127= 1,48 +1155,42 @@

/* Render regis= try key path. */
WCHAR szRegKey[ADAPTER_REGKEY_PAT= H_MAX];
- swprin= tf_s(
- szRe= gKey, _countof(szRegKey),
- szAdapterRegKeyPathTemplate,
- szDevClassNetId,
- szAdapterId);
+ swprintf_s(szRegKey, _countof= (szRegKey), szAdapterRegKeyPathTemplate, szDevClassNetId,
+ szAdapterId);

/* Open network adapter registry key= . */
HKEY hKey =3D NULL;
- dwResult =3D RegOpenKeyEx(
- HKEY_LOCAL_MACHINE,
- szRegKey,
- 0,- KEY_READ,- &hKey);<= br>+ dwResult =3D RegOpe= nKeyEx(HKEY_LOCAL_MACHINE, szRegKey, 0, KEY_READ, &hKey);
if (dwResult !=3D ERROR_SUCCESS)

{
- SetLastError(= dwResult); /* MSDN does not mention RegOpenKeyEx() to set GetLastError(). B= ut we do have an error code. Set last error manually. */
+ SetLastError(dwResult); /*= MSDN does not mention RegOpenKeyEx() to set GetLastError().
+ = But we do have an error code. Set last error manually. */

msg(M_WARN | M_ERRNO, "%s: RegOpenKeyEx(HKLM, \"= %ls\") failed", __FUNCTION__, szRegKey);

= goto cleanup_szAdapterId;
}
=
/* Read adapter name. */
= LPWSTR szName =3D NULL;
- hKey,
- L"Name",
- &szName);
+ dwResult =3D get_reg_string(hKey, L&qu= ot;Name", &szName);
if (dwResult !=3D ERR= OR_SUCCESS)
{
SetLast= Error(dwResult);
- = msg(M_WARN | M_ERRNO, "%s: Cannot determine %ls adapter name&qu= ot;, __FUNCTION__, szAdapterId);
+ msg(M_WARN | M_ERRNO, "%s: Cannot determine %= ls adapter name", __FUNCTION__,
+ szAdapterId);
= goto cleanup_hKey;
}

= /* Append to the list. */
size_t hw= id_size =3D (wcszlen(szzDeviceHardwareIDs) + 1) * sizeof(WCHAR);
= size_t name_size =3D (wcslen(szName) + 1) * sizeof(WCHAR);
- struct tap_adap= ter_node *node =3D (struct tap_adapter_node *)malloc(sizeof(struct tap_adap= ter_node) + hwid_size + name_size);
+ struct tap_adapter_node *node =3D (struct tap_adapt= er_node *)malloc(
+ = sizeof(struct tap_adapter_node) + hwid_size + name_size);<= br> if (node =3D=3D NULL)
{- msg(M_FATAL, "= ;%s: malloc(%u) failed", __FUNCTION__, sizeof(struct tap_adapter_node)= + hwid_size + name_size);
- dwResult =3D ERROR_OUTOFMEMORY; goto cleanup_szName;
+ msg(M_FATAL, = "%s: malloc(%u) failed", __FUNCTION__,
+ sizeof(struct tap_adapter_node= ) + hwid_size + name_size);
+ dwResult =3D ERROR_OUTOFMEMORY;
+ goto cleanup_szName; }

memcpy(&n= ode->guid, &guidAdapter, sizeof(GUID));
@@ -1351,8 += 1229,7 @@


void<= br>-tap_free_adapter_list(=
- _In_ struct tap_adapter_= node *pAdapterList)
+= tap_free_adapter_list(_In_ struct tap_adapter_node *pAdapterList) {
/* Iterate over all nodes of the list. */
while (pAdapterList)
diff --git a/src/ta= pctl/tap.h b/src/tapctl/tap.h
index a0b0561..ee5fb09 100644=
--- a/src/tapctl/tap.h
+++ b/src/tapctl/ta= p.h
@@ -49,12 +49,8 @@
* @return ERROR_SU= CCESS on success; Win32 error code otherwise
**/ DWORD
-tap_cre= ate_adapter(
- _In_o= pt_ HWND hwndParent,
- = _In_opt_ LPCWSTR szDeviceDescription,
- _In_ LPCWSTR szHwId,
- _Inout_ LPBOOL pbRebootRequired,
- _Out_ LPGUID pguidAdapter);=
+tap_create_adapter(_In_opt= _ HWND hwndParent, _In_opt_ LPCWSTR szDeviceDescription,
+ _In_ LPCWSTR szHwId= , _Inout_ LPBOOL pbRebootRequired, _Out_ LPGUID pguidAdapter);


/**
@@ -76,10 +72,= 8 @@
* @return ERROR_SUCCESS on success; Win32 error code= otherwise
**/
DWORD
-tap_delete_adapter(
- _In_opt_ HWND hwndParent,
- _In_ LPCGUID pguidAdapter,
- _Inout_ LPBOOL pbReboo= tRequired);
+tap_dele= te_adapter(_In_opt_ HWND hwndParent, _In_ LPCGUID pguidAdapter,
<= span style=3D"color: hsl(120, 100%, 40%);">+ _Inout_ LPBO= OL pbRebootRequired);



= /**
@@ -103,11 +97,8 @@
* @return ERROR_S= UCCESS on success; Win32 error code otherwise
**/<= br> DWORD
-tap_en= able_adapter(
- _In_= opt_ HWND hwndParent,
-= _In_ LPCGUID pguidAdapter,
- _In_ BOOL bEnable,
- _Inout_ LPBOOL pbRebootRequired);
+tap_enable_adapter(_In_opt_ HWND hwndParent, _I= n_ LPCGUID pguidAdapter, _In_ BOOL bEnable,
+ _Inout_ LPBOOL pbRebootRequired)= ;


/**
= @@ -123,10 +114,7 @@
* @return ERROR_SUCCESS on success; = Win32 error code otherwise
**/
DWORD
-tap_set_adapter_name(
- _In_ LPCGUID pguidAda= pter,
- _In_ LPCWSTR= szName,
- _In_ BOOL= bSilent);
+tap_set_a= dapter_name(_In_ LPCGUID pguidAdapter, _In_ LPCWSTR szName, _In_ BOOL bSile= nt);


/**
@@ -134,9 +122,9 @@

*/
struct tap_ada= pter_node
{
- GUID guid; /**< Adapter GUID */
- LPWSTR szzHardwareIDs; /**< Devi= ce hardware ID(s) */
- = LPWSTR szName; /**< Adapter name */
+ GUID guid; /**< A= dapter GUID */
+ L= PWSTR szzHardwareIDs; /**< Device hardware ID(s) */
<= span style=3D"color: hsl(120, 100%, 40%);">+ LPWSTR szName; = /**< Adapter name */


struct = tap_adapter_node *pNext; /**< Pointer to next adapter */
};

@@ -162,10 +150,8 @@
* @return ERROR= _SUCCESS on success; Win32 error code otherwise
*/=
DWORD
-tap_l= ist_adapters(
- _In_= opt_ HWND hwndParent,
-= _In_opt_ LPCWSTR szzHwIDs,
- _Out_ struct tap_adapter_node **ppAdapterList);
+tap_list_adapters(_In_opt_ HWND hw= ndParent, _In_opt_ LPCWSTR szzHwIDs,

+ _Out_ struct tap_adapter_node **ppAdapte= rList);


/**
= @@ -173,8 +159,6 @@
*
* @param pA= dapterList A pointer to the first adapter in the list to free.
<= span> */

-void<= br>-tap_free_adapter_list(=
- _In_ struct tap_adapter_= node *pAdapterList);
= +void tap_free_adapter_list(_In_ struct tap_adapter_node *pAdapterList);

#endif /* ifndef TAP_H */
= diff --git a/tests/ntlm_support.c b/tests/ntlm_support.c
in= dex 3960cc5..7007051 100644
--- a/tests/ntlm_support.c
+++ b/tests/ntlm_support.c
@@ -49,7 +49,7 @@
crypto_unload_provider("legacy", legacy);
crypto_unload_provider("default", def); #endif
-#else = /* ifdef NTLM */
+#e= lse /* ifdef NTLM */
msg(M_FATAL, "NTLM support n= ot compiled in");
#endif
}diff --git a/tests/unit_tests/example_test/test.c b/tests/unit_tests= /example_test/test.c
index c174025..139e06f 100644--- a/tests/unit_tests/example_test/test.c
+++ b/te= sts/unit_tests/example_test/test.c
@@ -10,7 +10,7 @@=
static int
setup(void **state)
= {
- int *answer = =3D malloc(sizeof(int));
+ int *answer =3D malloc(sizeof(int));

<= span> *answer =3D 42;

*state =3D answer;@@ -29,7 +29,7 @@
static void
null= _test_success(void **state)
{
- (void) state;
+ (void)state;
}
=
static void
@@ -39,8 +39,7 @@
= assert_int_equal(*answer, 42);
}

-__attribute__((unu= sed))
-static void
+__attribute__((unused)) = static void
failing_test(void **state)
{<= /span>
/* This tests fails to test that make check fails */
@@ -53,7 +52,7 @@
const struct CMUnitTe= st tests[] =3D {
cmocka_unit_test(null_test_succes= s),
cmocka_unit_test_setup_teardown(int_test_succe= ss, setup, teardown),
-= /* cmocka_unit_test(failing_test), */
+ /* cmocka_unit_test(failing_test), = */
};

return cm= ocka_run_group_tests_name("success_test", tests, NULL, NULL);
diff --git a/tests/unit_tests/example_test/test2.c b/tests/uni= t_tests/example_test/test2.c
index bb54633..3089432 100644<= /span>
--- a/tests/unit_tests/example_test/test2.c
+++ b/tests/unit_tests/example_test/test2.c

@@ -11,7 +11,7= @@
static void
test_true(void **state)
{
- = (void) state;
+ (v= oid)state;
}

diff --git a/tests/unit_tests/openvpn/cert_data.h b/tests/unit_tests= /openvpn/cert_data.h
index 638af39..9e2974a 100644--- a/tests/unit_tests/openvpn/cert_data.h
+++ b/te= sts/unit_tests/openvpn/cert_data.h
@@ -52,12 +52,11 @@
"srXMaPe0lAea4etMSZsjIRPwGRMXBrwbRmb6iN2Cq40867HdaJoA= ryYig7IiDwSX\n"
"htCbOA6sX+60+FEOYDEx5cmkogl= 633Pw7LJ3ICkyzIrUSEt6BOT1Gsc1eQ=3D=3D\n"
"--= ---END CERTIFICATE-----\n";
-static const char *const key1 =3D
- "-----BEGIN PRIVATE KEY-----\n"=
- "MIGHAgEAMBMGByqGSM= 49AgEGCCqGSM49AwEHBG0wawIBAQQg5Xpw/lLvBrWjAWDq\n"
- "L6dm/4a1or6AQ6O3yXYgw78B23ihRANC= AAR4SRvnSuGdJmPitKbqcFbcgyzsMBlh\n"
- "4wWOrty4I0ZlIXxY2qEnyb3YKz4OdMGzpK7FLfQZehHg6L= GblcLs4EW7\n"
- = "-----END PRIVATE KEY-----\n";
+static const char *const key1 =3D "-----BEGIN PR= IVATE KEY-----\n"
+ "L6dm/4a1or6AQ6O3yX= Ygw78B23ihRANCAAR4SRvnSuGdJmPitKbqcFbcgyzsMBlh\n"
+ "4w= WOrty4I0ZlIXxY2qEnyb3YKz4OdMGzpK7FLfQZehHg6LGblcLs4EW7\n"
+ = "-----END PRIVATE KEY-----\n";

static const char= *const hash1 =3D "A4B74F1D68AF50691F62CBD675E24C8655369567";
static const char *const cname1 =3D "ovpn-test-ec1"= ;

@@ -104,35 +103,34 @@
= "F6MgVGSxl6eylJgDYckvJiAbmcp2PD/LRQQOxQA0yqeAMg2cbdvclETuYD6zoFfu\= n"
"Y8aO7dvDlw=3D=3D\n"
"-----END CERTIFICATE-----\n";

-static const char *const key3 =3D
- "-----BEGIN PRIVATE KEY-----\= n"
- "MIIE= vAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQC7xFoR6fmoyfsJ\n"=
- "IQDKKgbYgFw0MzVuDA= mpRx6KTEihgTchkQx9fHddWbKiOUbcEnQi3LNux7P4QVl/\n"
- "4dRR3skisBug6Vd5LXeBGZqmpu5XZiF4= DgLz1lX21G0aOogFWkie2qGEcso40159\n"
- "x9FBDl5A3sLP18ubeex0pd/BzDFv6SLOTyVWO/GCNc8IX/= i0uN4mLvoVU00SeqwT\n"
- "PnS+CRXrSq4JjGDJLsXl0/PlxkjsgU0yOOA0Z2d8Fzk3wClwP6Hc49BOMWKs= tUIh\n"
- "= ;LbG2DcIv8l29EuEj2w3ju/7gkewol96XQ2twpPvpoVAaiVh/m7hQUcQORQCD6eJc\n"
- "DjOZVCArAgMBA= AECggEACqkuWAAJ3cyCBVWrXs8eDmLTWV9i9DmYvtS75ixIn2rf\n"
- "v3cl12YevN0f6FgKLuqZT3Vqdqq= +DCVhuIIQ9QkKMH8BQpSdE9NCCsFyZ23o8Gtr\n"

- "EQ7ymfecb+RFwYx7NpqWrvZI32VJGArgPZH/zorLT= TGYrAZbmBtHEqRsXOuEDw97\n"
- "slwwcWaa9ztaYC8/N/7fgsnydaCFSaOByRlWuyvSmHvn6ZwLv8ANOsh= Y6fstC0Jb\n"
- = "BW0GpSe9eZPjpl71VT2RtpghqLV5+iAoFDHoT+eZvBospcUGtfcZSU7RrBjKB8+a\n&qu= ot;
- "U1d6hwKh= duVs2peIQzl+FiOSdWriLcsZv79q4sBhsQKBgQDUDVTf5BGJ8apOs/17\n"
= - "YVk+Ad8Ey8sXvsfk49psml= CRa8Z4g0LVXfrP94qzhtl8U5kE9hs3nEF4j/kX1ZWG\n"
- "k11tdsNTZN5x5bbAgEgPA6Ap6J/uto0HS8G0= vSv0lyBymdKA3p/i5Dx+8Nc9cGns\n"
- "LGI9MvviLX7pQFIkvbaCkdKwYwKBgQDirowjWZnm7BgVhF0G1m= 3DY9nQTYYU185W\n"
= - "UESaO5/nVzwUrA+FypJamD+AvmlSuY8rJeQAGAS6nQr9G8/617r+GwJnzRtxC6Vl= \n"
- "4OF= 5BJRsD70oX4CFOOlycMoJ8tzcYVH7NI8KVocjxb+QW82hqSvEwSsvnwwn3eOW\n"
- "nr5u5vIHmQKBgCuc3= lL6Dl1ntdZgEIdau0cUjXDoFUo589TwxBDIID/4gaZxoMJP\n"
- "hPFXAVDxMDPw4azyjSB/47tPKTUsuYc= nMfT8kynIujOEwnSPLcLgxQU5kgM/ynuw\n"
- "qhNpQOwaVRMc7f2RTCMXPBYDpNE/GJn5eu8JWGLpZovEr= eBeoHX0VffvAoGAVrWn\n"
- "+3mxykhzaf+oyg3KDNysG+cbq+tlDVVE+K5oG0kePVYX1fjIBQmJ+QhdJ3y= 9jCbB\n"
- &quo= t;UVveqzeZVXqHEw/kgoD4aZZmsdZfnVnpRa5/y9o1ZDUr50n+2nzUe/u/ijlb77iK\n"<= /span>
- "Is04gnGJNoI3= ZWhdyrSNfXjcYH+bKClu9OM4n7kCgYAorc3PAX7M0bsQrrqYxUS8\n"
- "56UU0YdhAgYitjM7Fm/0iIm0vD= pSevxL9js4HnnsSMVR77spCBAGOCCZrTcI3Ejg\n"

- "xKDYzh1xlfMRjJBuBu5Pd55ZAv9NXFGpsX5SO8fD= ZQJMwpcbQH36+UdqRRFDpjJ0\n"
- "ZbX6nKcJ7jciJVKJds59Jg=3D=3D\n"
- "-----END PRIVATE KEY-----\n&q= uot;;
+static const c= har *const key3 =3D "-----BEGIN PRIVATE KEY-----\n"
+ &= quot;MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQC7xFoR6fmoyfsJ\n&quo= t;

+ = "IQDKKgbYgFw0MzVuDAmpRx6KTEihgTchkQx9fHddWbKiOUbcEnQi3L= Nux7P4QVl/\n"
+ = "4dRR3skisBug6Vd5LXeBGZqmpu5XZiF4DgLz1l= X21G0aOogFWkie2qGEcso40159\n"
+ "x9FBDl5A3sLP18ubeex0pd= /BzDFv6SLOTyVWO/GCNc8IX/i0uN4mLvoVU00SeqwT\n"
+ "PnS+CR= XrSq4JjGDJLsXl0/PlxkjsgU0yOOA0Z2d8Fzk3wClwP6Hc49BOMWKstUIh\n"+ = "LbG2DcIv8l29EuEj2w3ju/7gkewol96XQ2twpPvpoVAaiVh/m7hQUcQORQCD6eJc\= n"
+ = "DjOZVCArAgMBAAECggEACqkuWAAJ3cyCBVWrXs8eDmLTWV9i9= DmYvtS75ixIn2rf\n"
+ "v3cl12YevN0f6FgKLuqZT3Vqdqq+DCVhu= IIQ9QkKMH8BQpSdE9NCCsFyZ23o8Gtr\n"
+ "EQ7ymfecb+RFwYx7N= pqWrvZI32VJGArgPZH/zorLTTGYrAZbmBtHEqRsXOuEDw97\n"
+ "s= lwwcWaa9ztaYC8/N/7fgsnydaCFSaOByRlWuyvSmHvn6ZwLv8ANOshY6fstC0Jb\n"
+ = "BW0GpSe9eZPjpl71VT2RtpghqLV5+iAoFDHoT+eZvBospcUGtfcZSU7RrBjK= B8+a\n"
+ = "U1d6hwKhduVs2peIQzl+FiOSdWriLcsZv79q4sBhsQKB= gQDUDVTf5BGJ8apOs/17\n"
+ "YVk+Ad8Ey8sXvsfk49psmlCRa8Z4= g0LVXfrP94qzhtl8U5kE9hs3nEF4j/kX1ZWG\n"
+ "k11tdsNTZN5x= 5bbAgEgPA6Ap6J/uto0HS8G0vSv0lyBymdKA3p/i5Dx+8Nc9cGns\n"
+ &q= uot;LGI9MvviLX7pQFIkvbaCkdKwYwKBgQDirowjWZnm7BgVhF0G1m3DY9nQTYYU185W\n"= ;

+ = "UESaO5/nVzwUrA+FypJamD+AvmlSuY8rJeQAGAS6nQr9G8/617r+GwJ= nzRtxC6Vl\n"
+ = "4OF5BJRsD70oX4CFOOlycMoJ8tzcYVH7NI8KVoc= jxb+QW82hqSvEwSsvnwwn3eOW\n"
+ "nr5u5vIHmQKBgCuc3lL6Dl1= ntdZgEIdau0cUjXDoFUo589TwxBDIID/4gaZxoMJP\n"
+ "hPFXAVD= xMDPw4azyjSB/47tPKTUsuYcnMfT8kynIujOEwnSPLcLgxQU5kgM/ynuw\n"+ = "qhNpQOwaVRMc7f2RTCMXPBYDpNE/GJn5eu8JWGLpZovEreBeoHX0VffvAoGAVrWn\n= "
+ = "+3mxykhzaf+oyg3KDNysG+cbq+tlDVVE+K5oG0kePVYX1fjIBQ= mJ+QhdJ3y9jCbB\n"
+ "Is04gnGJNoI3ZWhdyr= SNfXjcYH+bKClu9OM4n7kCgYAorc3PAX7M0bsQrrqYxUS8\n"
+ "56= UU0YdhAgYitjM7Fm/0iIm0vDpSevxL9js4HnnsSMVR77spCBAGOCCZrTcI3Ejg\n"
+ = "xKDYzh1xlfMRjJBuBu5Pd55ZAv9NXFGpsX5SO8fDZQJMwpcbQH36+UdqRRFDp= jJ0\n"
+ = "ZbX6nKcJ7jciJVKJds59Jg=3D=3D\n"+ = "-----END PRIVATE KEY-----\n";
static const = char *const hash3 =3D "2463628674E362578113F508BA05F29EF142E979";=
static const char *const cname3 =3D "ovpn-test-rsa1&= quot;;

@@ -162,4 +160,4 @@
static const char *const hash4 =3D "E1401D4497C944783E3D62CDBD2A1F6= 9F5E5071E";

#define cname4 cname3 /* same CN as that = of cert3 */

-#endif /* CERT_DATA_H */
+#endif /* CERT_DATA_H */
diff -= -git a/tests/unit_tests/openvpn/mock_management.c b/tests/unit_tests/openvp= n/mock_management.c
index 9674b45..b24e4c4 100644--- a/tests/unit_tests/openvpn/mock_management.c
+++= b/tests/unit_tests/openvpn/mock_management.c
@@ -42,8 +42,= 7 @@
}

char *-management_query_pk_sig(struct = management *man, const char *b64_data,
- const char *algorithm)
<= span style=3D"color: hsl(120, 100%, 40%);">+management_query_pk_sig(struct = management *man, const char *b64_data, const char *algorithm)

{

return NULL;
}
= diff --git a/tests/unit_tests/openvpn/mock_msg.c b/tests/unit_tests/openvpn= /mock_msg.c
index 5407561..603520b 100644
-= -- a/tests/unit_tests/openvpn/mock_msg.c
+++ b/tests/unit_t= ests/openvpn/mock_msg.c
@@ -71,8 +71,7 @@
= }

void
-x_msg_va(const unsigned int flags, const char *format,<= /span>
- va_list argli= st)
+x_msg_va(const u= nsigned int flags, const char *format, va_list arglist)
{<= /span>
if (flags & M_FATAL)
{=
@@ -107,7 +106,7 @@
/* Keep compiler happy. = Should not happen, mock_assert() does not return */
e= xit(1);
}
-#else /* ifndef NO_CMOCKA */
+#else /* ifndef NO_CMOCKA */
void assert_failed(const char *filename, int line, const char *condition= )
{
diff --git a/tests/unit_tests/openvpn/= mock_msg.h b/tests/unit_tests/openvpn/mock_msg.h
index 40d7= 609..f4ebc23 100644
--- a/tests/unit_tests/openvpn/mock_msg= .h
+++ b/tests/unit_tests/openvpn/mock_msg.h
@@ -35,13 +35,10 @@

extern bool fatal_error_triggered;
extern char mock_msg_buf[MOCK_MSG_BUF];

-void
-mock_set_debug_level(int level);<= br>+void mock_set_debug_level(i= nt level);

-int
-mock_get_de= bug_level(void);
+int= mock_get_debug_level(void);

-void
-mock_set_print_debug_level(int level);
+void mock_set_print_debug_level(int level);

#endif /* MOCK_MSG */
diff -= -git a/tests/unit_tests/openvpn/mock_ssl_dependencies.c b/tests/unit_tests/= openvpn/mock_ssl_dependencies.c
index 2a562fc..7333c47 1006= 44
--- a/tests/unit_tests/openvpn/mock_ssl_dependencies.c
+++ b/tests/unit_tests/openvpn/mock_ssl_dependencies.c
@@ -37,8 +37,8 @@
#include "ssl_verify.h&q= uot;

int
-parse_line(const char *line, char **p, const int n, c= onst char *file,
- = const int line_num, int msglevel, struct gc_arena *gc)
+parse_line(const char *line, char = **p, const int n, const char *file, const int line_num,

+ int msglevel, struct gc_aren= a *gc)
{
/* Dummy function to get the= linker happy, should never be called */
assert_true(f= alse);
diff --git a/tests/unit_tests/openvpn/pkey_test_util= s.c b/tests/unit_tests/openvpn/pkey_test_utils.c
index 5660= 8ea..c9aef46 100644
--- a/tests/unit_tests/openvpn/pkey_tes= t_utils.c
+++ b/tests/unit_tests/openvpn/pkey_test_utils.c<= /span>
@@ -56,14 +56,14 @@
size_t siglen =3D = 0;
int ret =3D 0;

- OSSL_PARAM params[2] =3D {OSSL_PARAM= _END};
+ OSSL_PARA= M params[2] =3D { OSSL_PARAM_END };
const char *mdname= =3D "SHA256";

if (EVP_PKE= Y_get_id(privkey) =3D=3D EVP_PKEY_RSA)
{
const char *padmode =3D "pss"; /* RSA_PSS: for all ot= her params, use defaults */

- params[0] =3D OSSL_PARAM_construct_utf8_string(OSSL_SIGNATURE= _PARAM_PAD_MODE,
- = (char *)padmode, 0);=
+ params[0] =3D
+ OSSL_PARAM_c= onstruct_utf8_string(OSSL_SIGNATURE_PARAM_PAD_MODE, (char *)padmode, 0);
params[1] =3D OSSL_PARAM_construct_end();
= }
else if (EVP_PKEY_get_id(privkey) =3D=3D = EVP_PKEY_EC)
@@ -79,8 +79,7 @@
EVP_PKE= Y_CTX *pctx =3D NULL;
EVP_MD_CTX *mctx =3D EVP_MD_CTX_= new();

- = || EVP_DigestSignInit_ex(mctx, &pctx, mdname, tls_libctx, NULL, priv= key, params) <=3D 0)
+ if (!mctx || EVP_DigestSignInit_ex(mctx, &pctx, mdname, tls_li= bctx, NULL, privkey, params) <=3D 0)
{
/* cmocka assert output for these kinds of failures is hardly = explanatory,

* print a message and assert in call= er. */
@@ -115,7 +114,7 @@
mctx =3D EV= P_MD_CTX_new();
pctx =3D NULL;
if= (!mctx
- || EVP= _DigestVerifyInit_ex(mctx, &pctx, mdname, tls_libctx, NULL, pubkey, pa= rams) <=3D 0)
+ = || EVP_DigestVerifyInit_ex(mctx, &pctx, mdname, tls_libctx, NULL, = pubkey, params) <=3D 0)
{
= print_error("Failed to initialize EVP_DigestVerifyInit_ex()");
goto done;
diff --git a/tests/unit_t= ests/openvpn/test_argv.c b/tests/unit_tests/openvpn/test_argv.c
<= span>index 33b3dec..a65857b 100644

--- a/tests/unit_tests/o= penvpn/test_argv.c
+++ b/tests/unit_tests/openvpn/test_argv= .c
@@ -15,15 +15,15 @@
#include "test= _common.h"

/* Defines for use in th= e tests and the mock parse_line() */
-#define PATH1 "/s p a c e"
-#define PATH2 "/foo bar/baz&= quot;
-#define PARAM1 = "param1"
= -#define PARAM2 "param two"
-#define SCRIPT_CMD "\"" PATH1 PATH2 &q= uot;\"" PARAM1 "\"" PARAM2 "\""
+#define PATH1 &quo= t;/s p a c e"
+#= define PATH2 "/foo bar/baz"
+#define PARAM1 "param1"
+#define PARAM2 "param two= "

+#define SCRIP= T_CMD "\"" PATH1 PATH2 "\"" PARAM1 "\&qu= ot;" PARAM2 "\""

int=
-__wrap_parse_line(con= st char *line, char **p, const int n, const char *file,
- const int line_num, int= msglevel, struct gc_arena *gc)
+__wrap_parse_line(const char *line, char **p, const int n, cons= t char *file, const int line_num,
+ int msglevel, struct gc_arena *gc) {
p[0] =3D PATH1 PATH2;
= p[1] =3D PARAM1;
@@ -201,10 +201,10 @@
= argv_printf_cat(&a, "%s", PARAM2);
argv= _printf_cat(&a, "%d", -1);
argv_printf_c= at(&a, "%u", -1);
- argv_printf_cat(&a, "%lu", 1L );
+ argv_printf_cat(&a, "= %lu", 1L);

output =3D argv_str(&a, &gc, P= A_BRACKET);
assert_string_equal(output, "[" = PATH1 PATH2 "] [" PARAM1 "] [" PARAM2 "]"
- &= quot; [-1] [4294967295] [1]");
+ " [-1] [4294967295] [1= ]");

argv_free(&a);<= br> gc_free(&gc);
diff --git a/tests/unit_tes= ts/openvpn/test_auth_token.c b/tests/unit_tests/openvpn/test_auth_token.c
index 960422c..0c5467e 100644
--- a/tests/un= it_tests/openvpn/test_auth_token.c
+++ b/tests/unit_tests/o= penvpn/test_auth_token.c
@@ -36,7 +36,8 @@
= #include "auth_token.c"
#include "test_com= mon.h"

-struct test_context {
+struct test_context
+{
struct tls_multi multi;
= struct key_type kt;
struct user_pass up;
= @@ -52,10 +53,10 @@
void
auth_set_c= lient_reason(struct tls_multi *multi, const char *reason)
= {
-
}<= /span>

-stat= ic const char *now0key0 =3D "SESS_ID_AT_0123456789abcdefAAAAAAAAAAAAAA= AAAAAAAE5JsQJOVfo8jnI3RL3tBaR5NkE4yPfcylFUHmHSc5Bu";
+static const char *now0key0 =3D
+ "SESS_ID_AT_0123= 456789abcdefAAAAAAAAAAAAAAAAAAAAAE5JsQJOVfo8jnI3RL3tBaR5NkE4yPfcylFUHmHSc5B= u";

static const char *zeroinline = =3D "-----BEGIN OpenVPN auth-token server key-----\n"
<= span> "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n"

@@ -63,21 +64,24 = @@
"AAAAAAAAAAAAAAAAA= AAAAAAAAAAAAAAAAAAAAAAAAAA=3D\n"
= "-----END OpenVPN auth-token server key-----";=

-static con= st char *allx01inline =3D "-----BEGIN OpenVPN auth-token server key---= --\n"
- = "AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQ= EBAQEBAQEBAQEBAQEB\n"
- "AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQ= EBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEB\n"
- "AQEBAQEBAQEBAQ= EBAQEBAQEBAQEBAQEBAQEBAQEBAQE=3D\n"
- "-----END OpenVPN= auth-token server key-----";
+static const char *allx01inline =3D
+ "-----BEGIN OpenVPN auth-token serv= er key-----\n"
+= "AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEB\= n"
+ "AQ= EBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEB\n"
+ "AQEBAQEBAQEBAQ= EBAQEBAQEBAQEBAQEBAQEBAQEBAQE=3D\n"
+ "-----END OpenVPN auth-token server key-----&= quot;;

-= "+mmmf7IQ5cymtMVjKYTWk8IOcYanRlpQmV9Tb= 3EjkHYxueBVDg3yqRgzeBlVGzNLD//rAPiOVhau\n"
- "3NDBjNOQB89= 51bfs7Cc2mYfay92Bh2gRJ5XEM/DMfzCWN+7uU6NWoTTHr4FuojnIQtjtqVAj/JS9\n"
- = "w+dTSp/vYHl+c7uHd19uVRu/qLqV85+rm4tUGIjO7FfYuwyPqwmhuIsi3hs9= QkSimh888FmBpoKY\n"
- "I1KUOgIs= VNs4llACioeXplYekWETR+YkJwDc/A=3D=3D\n"
- "-----END OpenV= PN auth-token server key-----";
+static const char *random_key =3D
+ "-----BEGIN OpenVPN auth-token serv= er key-----\n"
+= "+mmmf7IQ5cymtMVjKYTWk8IOcYanRlpQmV9Tb3EjkHYxueBVDg3yqRgzeBlVGzNLD= //rAPiOVhau\n"
+= "3NDBjNOQB8951bfs7Cc2mYfay92Bh2gRJ5XEM/DMfzCWN+7uU6NWoTTHr4FuojnIQ= tjtqVAj/JS9\n"
+= "w+dTSp/vYHl+c7uHd19uVRu/qLqV85+rm4tUGIjO7FfYuwyPqwmhuIsi3hs9QkSim= h888FmBpoKY\n"
+= "/tbKVTJZmSERKti9KEwtV2eVAR0znN5KW7lCB3mHVAhN7bUpcoDjfCzYIFARxwswT= Fu9gFkwqUMY\n"
+= "I1KUOgIsVNs4llACioeXplYekWETR+YkJwDc/A=3D=3D\n"
+ "-----END OpenVPN auth-= token server key-----";


-static const char *random_token =3D "SESS_ID_= AT_ThhRItzOKNKrh3dfAAAAAFwzHpwAAAAAXDMenDdrq0RoH3dkA1f7O3wO+7kZcx2DusVZrRmF= lWQM9HOb";
+stat= ic const char *random_token =3D
+ "SESS_ID_AT_ThhRItzOKNKrh3dfAAAAAFwzHpwAAAAAXDMenDdrq0= RoH3dkA1f7O3wO+7kZcx2DusVZrRmFlWQM9HOb";

<= span>

static int
@@ -87,7 +91,7 @@=
*state =3D ctx;

struc= t key_parameters key =3D { 0 };
- key.hmac_size =3D MAX_HMAC_KEY_LENGTH; /* 64 byte of 0 */=
+ key.hmac_size = =3D MAX_HMAC_KEY_LENGTH; /* 64 byte of 0 */

ctx->kt =3D auth_token_kt();

if (!ctx->k= t.digest)
@@ -115,7 +119,7 @@
static int
teardown(void **state)
{
- struct test_context *ctx =3D (struc= t test_context *) *state;
+ struct test_context *ctx =3D (struct test_context *)*state;

free_key_ctx(&ctx->multi.opt.auth_= token_key);
wipe_auth_token(&ctx->multi);
@@ -129,23 +133,21 @@
static void
auth_token_basic_test(void **state)

{
- struct test_context *ctx =3D (stru= ct test_context *) *state;
+ struct test_context *ctx =3D (struct test_context *)*state;

generate_auth_token(&ctx->up, &am= p;ctx->multi);
strcpy(ctx->up.password, ctx->= multi.auth_token);
- = assert_int_equal(verify_auth_token(&ctx->up, &ctx->multi, ct= x->session),
- = AUTH_TOKEN_HMAC_OK);
+ assert_int_equal(verify_auth_token(&ctx->up, &am= p;ctx->multi, ctx->session), AUTH_TOKEN_HMAC_OK);
}<= /span>

static void
auth_token_= fail_invalid_key(void **state)
{
- struct test_context *ctx =3D (struct test_c= ontext *) *state;
+ = struct test_context *ctx =3D (struct test_context *)*state;

generate_auth_token(&ctx->up, &ctx->= ;multi);
strcpy(ctx->up.password, ctx->multi.aut= h_token);
- assert_i= nt_equal(verify_auth_token(&ctx->up, &ctx->multi, ctx->ses= sion),
- = AUTH_TOKEN_HMAC_OK);
+ assert_int_equal(verify_auth_token(&ctx->up, &ctx->= ;multi, ctx->session), AUTH_TOKEN_HMAC_OK);

= /* Change auth-token key */
struct key_para= meters key;
@@ -161,15 +163,13 @@
mems= et(&key.hmac, 0, sizeof(key.hmac));
free_key_ctx(&= amp;ctx->multi.opt.auth_token_key);
init_key_ctx(&a= mp;ctx->multi.opt.auth_token_key, &key, &ctx->kt, false, &quo= t;TEST");
- ass= ert_int_equal(verify_auth_token(&ctx->up, &ctx->multi, ctx-&g= t;session),
- = AUTH_TOKEN_HMAC_OK);
-
+ asser= t_int_equal(verify_auth_token(&ctx->up, &ctx->multi, ctx->= session), AUTH_TOKEN_HMAC_OK);
}
<= br> static void
auth_token_test_timeout(void **state= )
{
- = struct test_context *ctx =3D (struct test_context *) *state;
<= span style=3D"color: hsl(120, 100%, 40%);">+ struct test_context *ctx = =3D (struct test_context *)*state;


n= ow =3D 100000;
generate_auth_token(&ctx->up, &a= mp;ctx->multi);
@@ -179,33 +179,31 @@
= ctx->multi.auth_token_initial =3D NULL;

<= span> /* No time has passed */

- assert_int_equal(verify_auth_token(&ctx->up, &c= tx->multi, ctx->session),
- AUTH_TOKEN_HMAC_OK);
+ assert_int_equal(verify_auth_token(&a= mp;ctx->up, &ctx->multi, ctx->session), AUTH_TOKEN_HMAC_OK);

/* Token before validity, should be r= ejected */
now =3D 100000 - 100;
= assert_int_equal(verify_auth_token(&ctx->up, &ctx->multi, ctx= ->session),
- = AUTH_TOKEN_HMAC_OK|AUTH_TOKEN_EXPIRED);
+ AUTH_TOKEN_HMAC_OK |= AUTH_TOKEN_EXPIRED);

/* Token no va= lid for renegotiate_seconds but still for renewal_time */
- now =3D 100000 + 2*ctx->session-= >opt->renegotiate_seconds - 20;
+ now =3D 100000 + 2 * ctx->session->opt->rene= gotiate_seconds - 20;
assert_int_equal(verify_auth_tok= en(&ctx->up, &ctx->multi, ctx->session),
- AUTH_TOKEN_HMAC_OK= |AUTH_TOKEN_EXPIRED);
+ AUTH_TOKEN_HMAC_OK | AUTH_TOKEN_EXPIRED);
=

- now =3D 100000 + 2*ctx->session->opt->auth_token_renewal -= 20;
- assert_int_eq= ual(verify_auth_token(&ctx->up, &ctx->multi, ctx->session)= ,
- = AUTH_TOKEN_HMAC_OK);
+ now =3D 100000 + 2 * ctx->session->opt->auth_token_renewal -= 20;
+ assert_int_= equal(verify_auth_token(&ctx->up, &ctx->multi, ctx->sessio= n), AUTH_TOKEN_HMAC_OK);

/* Token pa= st validity, should be rejected */
- now =3D 100000 + 2*ctx->session->opt->renegotiate= _seconds + 20;
+ n= ow =3D 100000 + 2 * ctx->session->opt->renegotiate_seconds + 20;
assert_int_equal(verify_auth_token(&ctx->up, &am= p;ctx->multi, ctx->session),
- AUTH_TOKEN_HMAC_OK|AUTH_TOKEN_EXPIRED);
+ = AUTH_TOKEN_HMAC_OK | AUTH_TOKEN_EXPIRED);

/* But not when we reached our timeout */

now = =3D 100000 + ctx->session->opt->auth_token_lifetime + 1; assert_int_equal(verify_auth_token(&ctx->up, &ctx-&g= t;multi, ctx->session),
- AUTH_TOKEN_HMAC_OK|AUTH_TOKEN_EXPIRED);+ AUTH_TOK= EN_HMAC_OK | AUTH_TOKEN_EXPIRED);

fr= ee(ctx->multi.auth_token_initial);
ctx->multi.au= th_token_initial =3D NULL;
@@ -223,26 +221,25 @@
=

assert_int_equal(verify_auth= _token(&ctx->up, &ctx->multi, ctx->session),
- AUTH_TOKEN_HMA= C_OK|AUTH_TOKEN_EXPIRED);

+ AUTH_TOKEN_HMAC_OK | AUTH_TOKEN_EXPIRED);=
ctx->multi.opt.auth_token_lifetime =3D 0;

/* Non expiring token should be fine */
<= span style=3D"color: hsl(0, 100%, 40%);">- assert_int_equal(verify_auth_= token(&ctx->up, &ctx->multi, ctx->session),

- AUTH_TOKEN_HMAC= _OK);

+ assert_int= _equal(verify_auth_token(&ctx->up, &ctx->multi, ctx->sessi= on), AUTH_TOKEN_HMAC_OK);
}

static void

zerohmac(char *token)
{<= /span>
- char *hmacstart = =3D token + AUTH_TOKEN_SESSION_ID_LEN
- + strlen(SESSION_ID_PREFIX) + 2*sizeo= f(uint64_t);
+ cha= r *hmacstart =3D
+ = token + AUTH_TOKEN_SESSION_ID_LEN + strlen(SESSION_ID_PREFIX) + 2 * si= zeof(uint64_t);
memset(hmacstart, 0x8d, strlen(hmacsta= rt));
}

static void
auth_token_test_known_keys(void **state)
{
- struct test_context= *ctx =3D (struct test_context *) *state;
+ struct test_context *ctx =3D (struct test_context= *)*state;

now =3D 0;
/* Preload the session id so the same session id is used here */
@@ -257,8 +254,7 @@
assert_string_equal(n= ow0key0, ctx->multi.auth_token);

= strcpy(ctx->up.password, ctx->multi.auth_token);
- assert_int_equal(verify_auth_token(&am= p;ctx->up, &ctx->multi, ctx->session),
- AUTH_TOKEN_HMAC_OK);
+ assert_int_equal(= verify_auth_token(&ctx->up, &ctx->multi, ctx->session), AU= TH_TOKEN_HMAC_OK);
}

st= atic const char *lastsesion_statevalue;
@@ -274,13 +270,12 = @@
void
auth_token_test_session_mismatch(= void **state)
{
- struct test_context *ctx =3D (struct test_context *) *state;=
+ struct test_con= text *ctx =3D (struct test_context *)*state;

/* Generate first auth token and check it is correct */

= generate_auth_token(&ctx->up, &ctx->multi);=
strcpy(ctx->up.password, ctx->multi.auth_token);
- assert_int_equal(verify= _auth_token(&ctx->up, &ctx->multi, ctx->session),- AUTH_TOKE= N_HMAC_OK);
+ asse= rt_int_equal(verify_auth_token(&ctx->up, &ctx->multi, ctx->= ;session), AUTH_TOKEN_HMAC_OK);

char= *token_sessiona =3D strdup(ctx->multi.auth_token);

@@ -289,8 +284,7 @@

ge= nerate_auth_token(&ctx->up, &ctx->multi);
= strcpy(ctx->up.password, ctx->multi.auth_token);
- assert_int_equal(verify_auth_token(&= amp;ctx->up, &ctx->multi, ctx->session),
- AUTH_TOKEN_HMAC_OK);
+ assert_int_equal(= verify_auth_token(&ctx->up, &ctx->multi, ctx->session), AU= TH_TOKEN_HMAC_OK);

assert_int_not_eq= ual(0, memcmp(ctx->multi.auth_token_initial + strlen(SESSION_ID_PREFIX),=
token_sessiona + strle= n(SESSION_ID_PREFIX),
@@ -306,39 +300,37 @@
static void

auth_token_test_empty_user(void **state)
{
- st= ruct test_context *ctx =3D (struct test_context *) *state;
+ struct test_context *ctx =3D (st= ruct test_context *)*state;

CLEAR(ct= x->up.username);
now =3D 0;

generate_auth_token(&ctx->up, &ctx->multi);
strcpy(ctx->up.password, ctx->multi.auth_token);<= /span>
- assert_int_equal(v= erify_auth_token(&ctx->up, &ctx->multi, ctx->session),
- AUTH= _TOKEN_HMAC_OK);
+ = assert_int_equal(verify_auth_token(&ctx->up, &ctx->multi, ct= x->session), AUTH_TOKEN_HMAC_OK);

= now =3D 100000;
assert_int_equal(verify_auth_token(&a= mp;ctx->up, &ctx->multi, ctx->session),
- AUTH_TOKEN_HMAC_OK|AUT= H_TOKEN_EXPIRED);
+ = AUTH_TOKEN_HMAC_OK | AUTH_TOKEN_EXPIRED);
strcpy(ctx->up.username, "test user name");

<= span>

now =3D 0;
assert_int_equa= l(verify_auth_token(&ctx->up, &ctx->multi, ctx->session),<= /span>
- A= UTH_TOKEN_HMAC_OK|AUTH_TOKEN_VALID_EMPTYUSER);
+ AUTH_TOKEN_HMAC_OK | AUTH_T= OKEN_VALID_EMPTYUSER);

strcpy(ctx-&g= t;up.username, "test user name");
now =3D 10= 0000;
assert_int_equal(verify_auth_token(&ctx->= up, &ctx->multi, ctx->session),
- AUTH_TOKEN_HMAC_OK|AUTH_TOKEN_EXPI= RED|AUTH_TOKEN_VALID_EMPTYUSER);
+ AUTH_TOKEN_HMAC_OK | AUTH_TOKEN_EXPIRED |= AUTH_TOKEN_VALID_EMPTYUSER);

zerohm= ac(ctx->up.password);
-= 0);
+ assert_int_equal(verify_auth_token(&ctx->up, &ctx->m= ulti, ctx->session), 0);
}

= static void
auth_token_test_env(void **state)
{
- stru= ct test_context *ctx =3D (struct test_context *) *state;
+ struct test_context *ctx =3D (stru= ct test_context *)*state;

struct key= _state *ks =3D &ctx->multi.session[TM_ACTIVE].key[KS_PRIMARY];

@@ -356,15 +348,16 @@
add= _session_token_env(ctx->session, &ctx->multi, &ctx->up);
assert_string_equal(lastsesion_statevalue, "Authen= ticated");

- ks->auth_token_state_flags =3D AUTH_TOKEN_HMAC_OK|AUTH_T= OKEN_EXPIRED;
+ ks= ->auth_token_state_flags =3D AUTH_TOKEN_HMAC_OK | AUTH_TOKEN_EXPIRED;
add_session_token_env(ctx->session, &ctx->mult= i, &ctx->up);
assert_string_equal(lastsesion_st= atevalue, "Expired");

- ks->auth_token_state_flags =3D AUTH_TOKE= N_HMAC_OK|AUTH_TOKEN_VALID_EMPTYUSER;
+ ks->auth_token_state_flags =3D AUTH_TOKEN_HMAC_OK = | AUTH_TOKEN_VALID_EMPTYUSER;
add_session_token_env(ct= x->session, &ctx->multi, &ctx->up);
a= ssert_string_equal(lastsesion_statevalue, "AuthenticatedEmptyUser"= ;);

-= ks->auth_token_state_flags =3D AUTH_TOKEN_HMAC_OK|AUTH_TOKEN_EXPIRED= |AUTH_TOKEN_VALID_EMPTYUSER;
+ ks->auth_token_state_flags =3D
+ AUTH_TOKEN_HMAC_OK | AUTH_TOKEN_EXPIRED = | AUTH_TOKEN_VALID_EMPTYUSER;
add_session_token_env(ct= x->session, &ctx->multi, &ctx->up);
a= ssert_string_equal(lastsesion_statevalue, "ExpiredEmptyUser");
}
@@ -372,7 +365,7 @@
stati= c void
auth_token_test_random_keys(void **state) {
- struct t= est_context *ctx =3D (struct test_context *) *state;
+ struct test_context *ctx =3D (struct = test_context *)*state;

now =3D 0x5c3= 31e9c;
/* Preload the session id so the same session i= d is used here */
@@ -397,7 +390,7 @@
stat= ic void
auth_token_test_key_load(void **state)
<= span> {

- struct tes= t_context *ctx =3D (struct test_context *) *state;
+ struct test_context *ctx =3D (struct tes= t_context *)*state;

free_key_ctx(&am= p;ctx->multi.opt.auth_token_key);
auth_token_init_s= ecret(&ctx->multi.opt.auth_token_key, zeroinline, true);
<= span>diff --git a/tests/unit_tests/openvpn/test_buffer.c b/tests/unit_tests= /openvpn/test_buffer.c

index 4b3aaf8..0cfb918 100644=
--- a/tests/unit_tests/openvpn/test_buffer.c
+++ = b/tests/unit_tests/openvpn/test_buffer.c
@@ -43,13 +43,13 @= @
assert_false(strprefix("12", "123&quo= t;));
}

-#define testsep ","
+#define testsep ","
#define testnosep ""

-#define teststr1 "one"
-#define teststr2 "two"
-#define teststr3 "three"

+#define teststr1 "= one"
+#define te= ststr2 "two"
+#define teststr3 "three"

-#define assert_buf_equals_str(buf, str)= \
+#define assert_bu= f_equals_str(buf, str) \
assert_int_equal(BLEN(b= uf), strlen(str)); \
assert_memory_equal(BPTR(buf), st= r, BLEN(buf));

@@ -82,9 +82,7 @@ test_buffer_format_hex_ex(void **state)
{<= br> const int input_size =3D 10;
- const uint8_t input[] =3D {
- 0x01, 0x00, 0xff, 0x10, 0xff, 0x00,= 0xf0, 0x0f, 0x09, 0x0a
- };
+ const u= int8_t input[] =3D { 0x01, 0x00, 0xff, 0x10, 0xff, 0x00, 0xf0, 0x0f, 0x09, = 0x0a };
char *output;
struct gc_a= rena gc =3D gc_new();

@@ -113,7 +111,8 @@=
gc_free(&gc);
}
=
-struct test_buffer_l= ist_aggregate_ctx {
+= struct test_buffer_list_aggregate_ctx
+{
struct buffer_list *empty;<= br> struct buffer_list *one_two_three;
struc= t buffer_list *zero_length_strings;
@@ -123,7 +122,7 @@
static int
test_buffer_list_setup(void **sta= te)
{
= - struct test_buffer_list_aggregate_ctx *ctx =3D calloc(1, sizeof(*ctx)= );
+ struct test_b= uffer_list_aggregate_ctx *ctx =3D calloc(1, sizeof(*ctx));
= ctx->empty =3D buffer_list_new();

ctx->one_two_three =3D buffer_list_new();

@@ -188,= 8 +187,7 @@
/* Aggregate the first two elements=
* (add 1 to max_len to test if "three" is not sne= aked in too)
*/
- buffer_list_aggregate_separator(ctx->one_two_three, = strlen(expected) + 1,
-= testsep);
+ buffer_list_aggregate_separator(ctx->one_t= wo_three, strlen(expected) + 1, testsep);
assert_int_e= qual(ctx->one_two_three->size, 2);
struct buffer= *buf =3D buffer_list_peek(ctx->one_two_three);
ass= ert_buf_equals_str(buf, expected);
@@ -201,11 +199,10 @@
struct test_buffer_list_aggregate_ctx *ctx =3D *state;

/* Aggregate all */
- buffer_list_aggregate_separator(ctx= ->one_two_three, 1<<16, testsep);
+ buffer_list_aggregate_separator(ctx->one_two_= three, 1 << 16, testsep);
assert_int_equal(ctx-&= gt;one_two_three->size, 1);
struct buffer *buf =3D = buffer_list_peek(ctx->one_two_three);
- assert_buf_equals_str(buf,
- teststr1 testsep test= str2 testsep teststr3 testsep);
+ assert_buf_equals_str(buf, teststr1 testsep teststr2 testse= p teststr3 testsep);
}

= static void
@@ -214,7 +211,7 @@
struct= test_buffer_list_aggregate_ctx *ctx =3D *state;
/* Aggregate all */
- buffer_list_aggregate_separator(ctx->one_two_three, 1<= <16, testnosep);
+= buffer_list_aggregate_separator(ctx->one_two_three, 1 << 16, t= estnosep);
assert_int_equal(ctx->one_two_three->= size, 1);
struct buffer *buf =3D buffer_list_peek(ctx-= >one_two_three);
assert_buf_equals_str(buf, teststr= 1 teststr2 teststr3);
@@ -227,7 +224,7 @@
= struct buffer_list *bl_zerolen =3D ctx->zero_length_strings;<= br>
/* Aggregate all */
- buffer_list_aggregate_separator(bl_zero= len, 1<<16, testnosep);
+ buffer_list_aggregate_separator(bl_zerolen, 1 << 16, te= stnosep);
assert_int_equal(bl_zerolen->size, 1);
struct buffer *buf =3D buffer_list_peek(bl_zerolen);
assert_buf_equals_str(buf, "");
@@ -240,7 +237,7 @@

struct buffer_list *bl_emptybuffe= rs =3D ctx->empty_buffers;

/* Agg= regate all */
- buff= er_list_aggregate_separator(bl_emptybuffers, 1<<16, testnosep);
+ buffer_list_aggregate= _separator(bl_emptybuffers, 1 << 16, testnosep);
= assert_int_equal(bl_emptybuffers->size, 1);
struct= buffer *buf =3D buffer_list_peek(bl_emptybuffers);
as= sert_int_equal(BLEN(buf), 0);
@@ -344,11 +341,12 @@<= br> assert_string_equal(buf, "There.is...a.nice......year.ol= d.tr..ee.");

strcpy(buf, "= There is \x01 a 'nice' \"1234\"\n year old \ntr\x7f ee!&q= uot;);
- assert_fals= e(string_mod(buf, CC_ALPHA|CC_DIGIT|CC_NEWLINE|CC_SINGLE_QUOTE, CC_DOUBLE_Q= UOTE|CC_BLANK, '.'));
+ assert_false(string_mod(buf, CC_ALPHA | CC_DIGIT | CC_NEWLINE= | CC_SINGLE_QUOTE,
+= CC_DOUBLE_QUOTE | CC_BLANK, '.'));
assert_string_equal(buf, "There.is...a.'nice'= ..1234.\n.year.old.\ntr..ee.");

= strcpy(buf, "There is a \\'nice\\' \"1234\" [*] yea= r old \ntree!");
-= assert_false(string_mod(buf, CC_PRINT, CC_BACKSLASH|CC_ASTERISK, '.= '));
+ assert_= false(string_mod(buf, CC_PRINT, CC_BACKSLASH | CC_ASTERISK, '.'));<= /span>
assert_string_equal(buf, "There is a .'nice.&= #39; \"1234\" [.] year old .tree!");
}

@@ -360,7 +358,7 @@
<= br> struct buffer buf =3D alloc_buf_gc(1024, &gc);
=
- const char= test1[] =3D "There is a nice 1234\x00 year old tree!";+ const char test1[] =3D &= quot;There is a nice 1234\x00 year old tree!";
bu= f_write(&buf, test1, sizeof(test1));

= /* allow the null bytes and string but not the ! */
@@= -432,7 +430,7 @@
struct gc_arena gc =3D gc_new();
struct buffer buf =3D alloc_buf_gc(1024, &gc);=

- const = char test1[] =3D "There is a nice 1234 year old tree!\n\r";
+ const char test1[] = =3D "There is a nice 1234 year old tree!\n\r";
= buf_write(&buf, test1, sizeof(test1));
buf_chom= p(&buf);
/* Check that our own method agrees */
@@ -440,7 +438,7 @@
assert_string_equal(= BSTR(&buf), "There is a nice 1234 year old tree!");
struct buffer buf2 =3D alloc_buf_gc(1024, &am= p;gc);
- const char = test2[] =3D "CR_RESPONSE,MTIx\x0a\x00";
+ const char test2[] =3D "CR_RESPONSE= ,MTIx\x0a\x00";
buf_write(&buf2, test2, sizeo= f(test2));
buf_chomp(&buf2);

@@ -461,26 +459,19 @@
cmocka_unit_tes= t(test_buffer_printf_catrunc),
cmocka_unit_test(te= st_buffer_format_hex_ex),
cmocka_unit_test_setup_t= eardown(test_buffer_list_aggregate_separator_empty,
- tes= t_buffer_list_setup,
- = test_buffer_list_teardown),+ = test_buffer_list_setup, test_buffer_list_teardown),
<= span> cmocka_unit_test_setup_teardown(test_buffer_list_aggregate_se= parator_noop,

- = test_buffer_list_setup,
- t= est_buffer_list_teardown),
+ test_buffer_list_setup, test= _buffer_list_teardown),
cmocka_unit_test_setup_tea= rdown(test_buffer_list_aggregate_separator_two,
- test_buff= er_list_setup,
- = test_buffer_list_teardown),
+ = test_buffer_list_setup, test_buffer_list_teardown),

= cmocka_unit_test_setup_teardown(test_buffer_list_aggregate_separato= r_all,
- = test_buffer_list_setup,
- test_buf= fer_list_teardown),
+= test_buffer_list_setup, test_buffer= _list_teardown),
cmocka_unit_test_setup_teardown(t= est_buffer_list_aggregate_separator_nosep,
- test_buffer_li= st_setup,
- = test_buffer_list_teardown),
+ = test_buffer_list_setup, test_buffer_list_teardown),
= cmocka_unit_test_setup_teardown(test_buffer_list_aggregate_separator_zer= olen,
- = test_buffer_list_setup,
- test_buff= er_list_teardown),
+ = test_buffer_list_setup, test_buffer_= list_teardown),
cmocka_unit_test_setup_teardown(te= st_buffer_list_aggregate_separator_emptybuffers,
- test_buf= fer_list_setup,
- = test_buffer_list_teardown),
+ = test_buffer_list_setup, test_buffer_list_teardown),

= cmocka_unit_test(test_buffer_free_gc_one),
= cmocka_unit_test(test_buffer_free_gc_two),
cmock= a_unit_test(test_buffer_gc_realloc),
diff --git a/tests/uni= t_tests/openvpn/test_crypto.c b/tests/unit_tests/openvpn/test_crypto.c
index 1c3b146..12ddaba 100644
--- a/tests/unit_= tests/openvpn/test_crypto.c
+++ b/tests/unit_tests/openvpn/= test_crypto.c
@@ -156,7 +156,7 @@
cons= t size_t seed_len =3D strlen(seedstr);

<= /span>
- const unsigned cha= r *secret =3D (const unsigned char *) ipsumlorem;
+ const unsigned char *secret =3D (const un= signed char *)ipsumlorem;
size_t secret_len =3D strlen= ((const char *)secret);


@@ -168,18 +168,16 @@

assert_false(ret);
#else

assert_true(ret);
- uint8_t good_prf[32] =3D {0xd9, 0x8c, 0x85,= 0x18, 0xc8, 0x5e, 0x94, 0x69,
- 0x27, 0x91, 0x6a, 0xcf, 0xc2, 0xd5, 0x= 92, 0xfb,
- = 0xb1, 0x56, 0x7e, 0x4b, 0x4b, 0x14, 0x59, 0xe6,
<= span style=3D"color: hsl(0, 100%, 40%);">- 0xa9,= 0x04, 0xac, 0x2d, 0xda, 0xb7, 0x2d, 0x67};

+ uint8_t good_prf[32] =3D { 0xd9, 0x8c, 0x85, 0x= 18, 0xc8, 0x5e, 0x94, 0x69, 0x27, 0x91, 0x6a,
+ 0xcf, 0xc2, 0xd5, 0x= 92, 0xfb, 0xb1, 0x56, 0x7e, 0x4b, 0x4b, 0x14,
+ 0x59, 0xe6, 0xa9, 0x= 04, 0xac, 0x2d, 0xda, 0xb7, 0x2d, 0x67 };
assert_memor= y_equal(good_prf, out, sizeof(out));
#endif
}


= -static uint8_t testkey[20] =3D {0x0b, 0x00};
-static uint8_t goodhash[20] =3D {0x58, 0xea, 0x5a, = 0xf0, 0x42, 0x94, 0xe9, 0x17,
- 0xed, 0x84, 0xb9, 0xf0, 0x83, 0x30, = 0x23, 0xae,
- = 0x8b, 0xa7, 0x7e, 0xb8};
+static uint8_t testkey[20] =3D { 0x0b, 0x00 };
+static uint8_t goodhas= h[20] =3D { 0x58, 0xea, 0x5a, 0xf0, 0x42, 0x94, 0xe9, 0x17, 0xed, 0x84,
+ = 0xb9, 0xf0, 0x83, 0x30, 0x23, 0xae, 0x8b, 0xa7, 0x7e, 0xb8 };

static void
crypto_test_hma= c(void **state)
@@ -192,8 +190,8 @@
me= mcpy(key, testkey, sizeof(key));

hma= c_ctx_init(hmac, key, "SHA1");
- hmac_ctx_update(hmac, (const uint8_t *)ipsumlorem, (= int) strlen(ipsumlorem));
- hmac_ctx_update(hmac, (const uint8_t *)ipsumlorem, (int) strlen(ips= umlorem));
+ hmac_= ctx_update(hmac, (const uint8_t *)ipsumlorem, (int)strlen(ipsumlorem));
+ hmac_ctx_update(hma= c, (const uint8_t *)ipsumlorem, (int)strlen(ipsumlorem));
=
uint8_t hash[20];
hmac_ctx_final= (hmac, hash);
@@ -203,8 +201,8 @@
<= br> /* try again */
hmac_ctx_reset(hmac);
- hmac_ctx_update(hmac= , (const uint8_t *)ipsumlorem, (int) strlen(ipsumlorem));
- hmac_ctx_update(hmac, (const uint8_= t *)ipsumlorem, (int) strlen(ipsumlorem));
+ hmac_ctx_update(hmac, (const uint8_t *)ipsumlore= m, (int)strlen(ipsumlorem));
+ hmac_ctx_update(hmac, (const uint8_t *)ipsumlorem, (int)strlen= (ipsumlorem));
hmac_ctx_final(hmac, hash);
<= span>

assert_memory_equal(hash, goodhash, sizeof(hash= ));
@@ -213,8 +211,8 @@
memset(key, 0x= 55, sizeof(key));

hmac_ctx_reset(hma= c);
- hmac_ctx_updat= e(hmac, (const uint8_t *)ipsumlorem, (int) strlen(ipsumlorem));
<= span style=3D"color: hsl(0, 100%, 40%);">- hmac_ctx_update(hmac, (const = uint8_t *)ipsumlorem, (int) strlen(ipsumlorem));

+ hmac_ctx_update(hmac, (const uint8_t *)ips= umlorem, (int)strlen(ipsumlorem));
+ hmac_ctx_update(hmac, (const uint8_t *)ipsumlorem, (int)= strlen(ipsumlorem));
hmac_ctx_final(hmac, hash);

assert_memory_equal(hash, goodhash, sizeo= f(hash));
@@ -481,22 +479,16 @@
crypto_tes= t_hkdf_expand_testa1(void **state)
{
= /* RFC 5889 A.1 Test Case 1 */
- uint8_t prk[32] =3D
- {0x07, 0x77, 0x09, 0x36, 0x2c, 0x2e, 0x32, 0xdf,
<= span style=3D"color: hsl(0, 100%, 40%);">- 0x0d, 0xdc, 0x3f, 0x0d, 0xc4= , 0x7b, 0xba, 0x63,

- = 0x90, 0xb6, 0xc7, 0x3b, 0xb5, 0x0f, 0x9c, 0x31,
- 0x22, 0xec, 0x84, 0x4a, 0xd7, 0xc2, 0xb3,= 0xe5};
+ uint8_t = prk[32] =3D { 0x07, 0x77, 0x09, 0x36, 0x2c, 0x2e, 0x32, 0xdf, 0x0d, 0xdc, 0= x3f,
+ = 0x0d, 0xc4, 0x7b, 0xba, 0x63, 0x90, 0xb6, 0xc7, 0x3b, 0xb5, 0x0f,<= /span>
+ = 0x9c, 0x31, 0x22, 0xec, 0x84, 0x4a, 0xd7, 0xc2, 0xb3, 0xe5 };
- uint8_t i= nfo[10] =3D {0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5,
- 0xf6, 0xf7, 0xf8, 0xf9};=
+ uint8_t info[10= ] =3D { 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9 };

- uint8= _t okm[42] =3D
- {0x= 3c, 0xb2, 0x5f, 0x25, 0xfa, 0xac, 0xd5, 0x7a,
- 0x90, 0x43, 0x4f, 0x64, 0xd0, 0x36, 0x2f, 0x2a= ,
- 0x2d, 0x2d, 0x0= a, 0x90, 0xcf, 0x1a, 0x5a, 0x4c,
- 0x5d, 0xb0, 0x2d, 0x56, 0xec, 0xc4, 0xc5, 0xbf,
<= span style=3D"color: hsl(0, 100%, 40%);">- 0x34, 0x00, 0x72, 0x08, 0xd5= , 0xb8, 0x87, 0x18,

- = 0x58, 0x65};
+ = uint8_t okm[42] =3D { 0x3c, 0xb2, 0x5f, 0x25, 0xfa, 0xac, 0xd5, 0x7a, 0x90,= 0x43, 0x4f,
+ = 0x64, 0xd0, 0x36, 0x2f, 0x2a, 0x2d, 0x2d, 0x0a, 0x90, 0xcf= , 0x1a,
+ = 0x5a, 0x4c, 0x5d, 0xb0, 0x2d, 0x56, 0xec, 0xc4, 0xc5, 0xbf, 0x3= 4,
+ = 0x00, 0x72, 0x08, 0xd5, 0xb8, 0x87, 0x18, 0x58, 0x65 };

uint8_t out[42];
ovpn_hkdf_= expand(prk, info, sizeof(info), out, sizeof(out));
@@ -508,= 39 +500,28 @@
crypto_test_hkdf_expand_testa2(void **state)=
{
/* RFC 5889 A.2 Test Case 2 */
- uint8_t prk[32] =3D
- {0x06, 0xa6, 0xb8, = 0x8c, 0x58, 0x53, 0x36, 0x1a,
- 0x06, 0x10, 0x4c, 0x9c, 0xeb, 0x35, 0xb4, 0x5c,
- 0xef, 0x76, 0x00, 0x14, 0x90, 0= x46, 0x71, 0x01,

- = 0x4a, 0x19, 0x3f, 0x40, 0xc1, 0x5f, 0xc2, 0x44};
+ uint8_t prk[32] =3D { 0x06, 0xa6, 0xb8, 0x= 8c, 0x58, 0x53, 0x36, 0x1a, 0x06, 0x10, 0x4c,
+ 0x9c, 0xeb, 0x35, 0xb4, 0= x5c, 0xef, 0x76, 0x00, 0x14, 0x90, 0x46,
+ 0x71, 0x01, 0x4a, 0x19, 0x3f, = 0x40, 0xc1, 0x5f, 0xc2, 0x44 };

- uint8_t info[80] =3D
- {0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0x= b6, 0xb7,
- 0xb8, 0= xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf,
- 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7,
- 0xc8, 0xc9, 0xca, 0x= cb, 0xcc, 0xcd, 0xce, 0xcf,
- 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7,
- 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xd= d, 0xde, 0xdf,
- 0x= e0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7,
- 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef= ,
- 0xf0, 0xf1, 0xf= 2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7,
- 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff};
= + uint8_t info[80] =3D { 0xb= 0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xbb,=
+ 0= xbc, 0xbd, 0xbe, 0xbf, 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7,
+ = 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, 0xd0, 0xd1, 0xd2, 0xd3,
+ = 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf,<= /span>
+ = 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xeb= ,
+ = 0xec, 0xed, 0xee, 0xef, 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0x= f7,
+ = 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff };
=
const int L =3D 82;
- uint8_t okm[82] =3D
- {0xb1, 0x1e, 0x39, 0x8d, 0xc8, 0x03, 0x27, 0xa1,=
- 0xc8, 0xe7, 0xf7= , 0x8c, 0x59, 0x6a, 0x49, 0x34,
- 0x4f, 0x01, 0x2e, 0xda, 0x2d, 0x4e, 0xfa, 0xd8,
- 0xa0, 0x50, 0xcc, 0x4c, 0x19,= 0xaf, 0xa9, 0x7c,

- = 0x59, 0x04, 0x5a, 0x99, 0xca, 0xc7, 0x82, 0x72,
- 0x71, 0xcb, 0x41, 0xc6, 0x5e, 0x59, 0x0e, = 0x09,
- 0xda, 0x32,= 0x75, 0x60, 0x0c, 0x2f, 0x09, 0xb8,
- 0x36, 0x77, 0x93, 0xa9, 0xac, 0xa3, 0xdb, 0x71,<= br>- 0xcc, 0x30, 0xc5, 0x81, = 0x79, 0xec, 0x3e, 0x87,
- 0xc1, 0x4c, 0x01, 0xd5, 0xc1, 0xf3, 0x43, 0x4f,
- 0x1d, 0x87};
+ uint8_t okm[82] =3D { 0xb1, 0x1e, 0x39, = 0x8d, 0xc8, 0x03, 0x27, 0xa1, 0xc8, 0xe7, 0xf7, 0x8c,
+ 0x59, 0x6a, 0x49,= 0x34, 0x4f, 0x01, 0x2e, 0xda, 0x2d, 0x4e, 0xfa, 0xd8,
+ 0xa0, 0x50, 0xcc= , 0x4c, 0x19, 0xaf, 0xa9, 0x7c, 0x59, 0x04, 0x5a, 0x99,
+ 0xca, 0xc7, 0x8= 2, 0x72, 0x71, 0xcb, 0x41, 0xc6, 0x5e, 0x59, 0x0e, 0x09,
+ 0xda, 0x32, 0x= 75, 0x60, 0x0c, 0x2f, 0x09, 0xb8, 0x36, 0x77, 0x93, 0xa9,
+ 0xac, 0xa3, 0= xdb, 0x71, 0xcc, 0x30, 0xc5, 0x81, 0x79, 0xec, 0x3e, 0x87,
+ 0xc1, 0x4c, = 0x01, 0xd5, 0xc1, 0xf3, 0x43, 0x4f, 0x1d, 0x87 };
<= br>- uint8_t out[82] =3D {0xaa= };
+ uint8_t out[8= 2] =3D { 0xaa };
ovpn_hkdf_expand(prk, info, sizeof(in= fo), out, L);

assert_memory_equal(ou= t, okm, L);
@@ -550,22 +531,17 @@
crypto_t= est_hkdf_expand_testa3(void **state)
{
= /* RFC 5889 A.3 Test Case 3 */
- uint8_t prk[32] =3D
- {0x19, 0xef, 0x24, 0xa3, 0x2c, 0x71, 0x7b, 0x16,- 0x7f, 0x33, 0xa9, 0x1d, 0x= 6f, 0x64, 0x8b, 0xdf,
-= 0x96, 0x59, 0x67, 0x76, 0xaf, 0xdb, 0x63, 0x77,
- 0xac, 0x43, 0x4c, 0x1c, 0x29, 0x3c, 0x= cb, 0x04};
+ uint8= _t prk[32] =3D { 0x19, 0xef, 0x24, 0xa3, 0x2c, 0x71, 0x7b, 0x16, 0x7f, 0x33= , 0xa9,
+ = 0x1d, 0x6f, 0x64, 0x8b, 0xdf, 0x96, 0x59, 0x67, 0x76, 0xaf, 0xd= b,
+ = 0x63, 0x77, 0xac, 0x43, 0x4c, 0x1c, 0x29, 0x3c, 0xcb, 0x04 };=

uint8_t info[] =3D {};

int L =3D 42;
- uint8_t okm[42] =3D
- {0x8d, 0xa4, 0xe7, 0x75, 0xa5, 0x63, 0xc1, 0x8f,- 0x71, 0x5f, 0x80, 0x2a, 0= x06, 0x3c, 0x5a, 0x31,
= - 0xb8, 0xa1, 0x1f, 0x5c, 0x5e, 0xe1, 0x87, 0x9e,
- 0xc3, 0x45, 0x4e, 0x5f, 0x3c, 0x73, 0x= 8d, 0x2d,
- 0x9d, 0= x20, 0x13, 0x95, 0xfa, 0xa4, 0xb6, 0x1a,
- 0x96, 0xc8};
+ uint8_t okm[42] =3D { 0x8d, 0xa4, 0xe7, 0x75, 0xa5, 0x= 63, 0xc1, 0x8f, 0x71, 0x5f, 0x80,
+ 0x2a, 0x06, 0x3c, 0x5a, 0x31, 0xb8, 0= xa1, 0x1f, 0x5c, 0x5e, 0xe1,
+ 0x87, 0x9e, 0xc3, 0x45, 0x4e, 0x5f, 0x3c, = 0x73, 0x8d, 0x2d, 0x9d,
+ 0x20, 0x13, 0x95, 0xfa, 0xa4, 0xb6, 0x1a, 0x96,= 0xc8 };

uint8_t out[42];
= ovpn_hkdf_expand(prk, info, 0, out, L);
@@ -579,= 23 +555,17 @@
/* tests the HDKF with a label/okm that = OpenVPN itself uses in OpenSSL 3
* HDKF unit test*/

- u= int8_t prk[32] =3D
- = {0x07, 0x77, 0x09, 0x36, 0x2c, 0x2e, 0x32, 0xdf,
- 0x0d, 0xdc, 0x3f, 0x0d, 0xc4, 0x7b, 0xba, = 0x63,
- 0x90, 0xb6,= 0xc7, 0x3b, 0xb5, 0x0f, 0x9c, 0x31,
- 0x22, 0xec, 0x84, 0x4a, 0xd7, 0xc2, 0xb3, 0xe5};=
+ uint8_t prk[32] =3D { = 0x07, 0x77, 0x09, 0x36, 0x2c, 0x2e, 0x32, 0xdf, 0x0d, 0xdc, 0x3f,+ 0x0d,= 0xc4, 0x7b, 0xba, 0x63, 0x90, 0xb6, 0xc7, 0x3b, 0xb5, 0x0f,
+ 0x9c, 0x31= , 0x22, 0xec, 0x84, 0x4a, 0xd7, 0xc2, 0xb3, 0xe5 };


- uint8_t info[18] =3D
- {0x00, 0x1b, 0x0e, 0= x6f, 0x76, 0x70, 0x6e, 0x20,
- 0x75, 0x6e, 0x69, 0x74, 0x20, 0x74, 0x65, 0x73,
- 0x74, 0x00};

+ uint8_t info[18] =3D { 0x00, 0x1b, = 0x0e, 0x6f, 0x76, 0x70, 0x6e, 0x20, 0x75,
+ 0x6e, 0x69, 0x74, 0x20, 0x74= , 0x65, 0x73, 0x74, 0x00 };

int L = =3D 27;
- uint8_t ok= m[27] =3D
- {0x87, 0= x5a, 0x8e, 0xec, 0x18, 0x55, 0x63, 0x80,
- 0xb8, 0xd9, 0x33, 0xed, 0x32, 0x3c, 0x2d, 0xf8,
- 0xe8, 0xec, 0xcf, 0x= 49, 0x72, 0xe6, 0x83, 0xf0,
- 0x6a, 0x83, 0xac };
+ uint8_t okm[27] =3D { 0x87, 0x5a, 0x8e, 0xec, 0x18, 0x55, 0x= 63, 0x80, 0xb8,
+ = 0xd9, 0x33, 0xed, 0x32, 0x3c, 0x2d, 0xf8, 0xe8, 0xec,
+ = 0xcf, 0x49, 0x72, 0xe6, 0x83, 0xf0, 0x6a, 0x83, 0xac };
=
uint8_t out[27];
ovpn_hkdf_expa= nd(prk, info, sizeof(info), out, L);
@@ -606,19 +576,16 @@<= /span>
void
crypto_test_ovpn_label_expand(void *= *state)
{
- uint8_t secret[32] =3D
- {0x07, 0x77, 0x09, 0x36, 0x2c, 0x2e, 0x32, 0xdf,
- 0x0d, 0xdc, 0x3f, 0x0d, 0xc4,= 0x7b, 0xba, 0x63,

- = 0x90, 0xb6, 0xc7, 0x3b, 0xb5, 0x0f, 0x9c, 0x31,
- 0x22, 0xec, 0x84, 0x4a, 0xd7, 0xc2, 0xb3, = 0xe5};
+ uint8_t s= ecret[32] =3D { 0x07, 0x77, 0x09, 0x36, 0x2c, 0x2e, 0x32, 0xdf, 0x0d, 0xdc,= 0x3f,
+ = 0x0d, 0xc4, 0x7b, 0xba, 0x63, 0x90, 0xb6, 0xc7, 0x3b, 0xb5, 0= x0f,
+ = 0x9c, 0x31, 0x22, 0xec, 0x84, 0x4a, 0xd7, 0xc2, 0xb3, 0xe5 };

- c= onst uint8_t *label =3D (const uint8_t *) ("unit test");+ const uint8_t *label =3D= (const uint8_t *)("unit test");
uint8_t out= [16];
ovpn_expand_label(secret, sizeof(secret), label,= 9, NULL, 0, out, sizeof(out));

- uint8_t out_expected[16] =3D
- {0x18, 0x5e, 0xaa, 0x1c, 0x7f, 0= x22, 0x8a, 0xb8,

- = 0xeb, 0x29, 0x77, 0x32, 0x14, 0xd9, 0x20, 0x46};
+ uint8_t out_expected[16] =3D { 0x18, 0x5e,= 0xaa, 0x1c, 0x7f, 0x22, 0x8a, 0xb8,
+ 0xeb, 0x29, 0x77, 0x32, 0= x14, 0xd9, 0x20, 0x46 };

assert_memo= ry_equal(out, out_expected, 16);
}
@@ -630= ,15 +597,13 @@
* openvpn_PRF ifdef maze */

bool
-ossl_expand_label(const uint8_t *secret, size_t secret_len,
<= span style=3D"color: hsl(0, 100%, 40%);">- const uint8_t *= label, size_t label_len,

- uint8_t *out, = uint16_t out_len)
+os= sl_expand_label(const uint8_t *secret, size_t secret_len, const uint8_t *la= bel, size_t label_len,
- con= st uint8_t *label_prefix =3D (const uint8_t *) ("ovpn ");<= br>+ const uint8_t *label_pr= efix =3D (const uint8_t *)("ovpn ");
const s= ize_t label_prefix_len =3D 5;

EVP_KD= F *kdf =3D EVP_KDF_fetch(libctx, OSSL_KDF_NAME_TLS1_3_KDF, properties);
@@ -657,15 +622,12 @@
int mode =3D EVP_PK= EY_HKDEF_MODE_EXPAND_ONLY;

*p++ =3D = OSSL_PARAM_construct_int(OSSL_KDF_PARAM_MODE, &mode);
- *p++ =3D OSSL_PARAM_construct_utf8_= string(OSSL_KDF_PARAM_DIGEST,
- (char *) mdname, 0);
- *p++ =3D OSSL_PARAM_= construct_octet_string(OSSL_KDF_PARAM_KEY,
- (unsigned= char *) secret, hashlen);
- *p++ =3D OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_PREFIX,<= /span>
- = (unsigned char *) label_prefix,
+ *p++ =3D OSSL_PARAM_construct_utf8_s= tring(OSSL_KDF_PARAM_DIGEST, (char *)mdname, 0);
+ *p++ =3D OSSL_PARAM_construct_octet_string= (OSSL_KDF_PARAM_KEY, (unsigned char *)secret, hashlen);
+ *p++ =3D OSSL_PARAM_construct_octet= _string(OSSL_KDF_PARAM_PREFIX, (unsigned char *)label_prefix,
label_prefix_len);
<= br>- *p++ =3D OSSL_PARAM_const= ruct_octet_string(OSSL_KDF_PARAM_LABEL,
- (unsigned ch= ar *) label, label_len);
+ *p++ =3D
+ = OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_LABEL, (unsigned cha= r *)label, label_len);

*p++ =3D OSSL= _PARAM_construct_end();

@@ -680,13 +642,1= 1 @@
void
crypto_test_ovpn_expand_openssl= 3(void **state)
{
- uint8_t secret[32] =3D
- {0x07, 0x77, 0x09, 0x36, 0x2c, 0x2e, 0x32, 0xdf,
- 0x0d, 0xdc, 0x3f, 0x0= d, 0xc4, 0x7b, 0xba, 0x63,
- 0x90, 0xb6, 0xc7, 0x3b, 0xb5, 0x0f, 0x9c, 0x31,
- 0x22, 0xec, 0x84, 0x4a, 0xd7, 0xc2= , 0xb3, 0xe5};
+ u= int8_t secret[32] =3D { 0x07, 0x77, 0x09, 0x36, 0x2c, 0x2e, 0x32, 0xdf, 0x0= d, 0xdc, 0x3f,
+ = 0x0d, 0xc4, 0x7b, 0xba, 0x63, 0x90, 0xb6, 0xc7, 0x3b,= 0xb5, 0x0f,
+ = 0x9c, 0x31, 0x22, 0xec, 0x84, 0x4a, 0xd7, 0xc2, 0xb3, 0= xe5 };

+ const uint8_t *l= abel =3D (const uint8_t *)("unit test");
con= st size_t labellen =3D 9;
uint8_t out[27];
<= span>

@@ -725,11 +685,10 @@
init_key_= type(&data->kt, "AES-128-GCM", "none", true, fal= se);

/* have an epoch key that uses = 0x23 for the key for all bytes */
- struct epoch_key epoch1send =3D { .epoch =3D 1, .epoch_key = =3D {0x23} };
- stru= ct epoch_key epoch1recv =3D { .epoch =3D 1, .epoch_key =3D {0x27} };=
+ struct epoch_key epoch= 1send =3D { .epoch =3D 1, .epoch_key =3D { 0x23 } };
+ struct epoch_key epoch1recv =3D { .ep= och =3D 1, .epoch_key =3D { 0x27 } };

- epoch_init_key_ctx(&data->co, = &data->kt, &epoch1send,
- &epoch1recv, *num_future_keys);
+ epoch_init_key_ctx(= &data->co, &data->kt, &epoch1send, &epoch1recv, *num_= future_keys);

*state =3D data;
return 0;
@@ -913,7 +872,7 @@
void

epoch_test_derive_data_key(void **state) {
- struct = epoch_key e17 =3D { .epoch =3D 17, .epoch_key =3D { 19, 12 }};
+ struct epoch_key e17 =3D { .= epoch =3D 17, .epoch_key =3D { 19, 12 } };

struct key_= type kt =3D { 0 };
struct key_parameters key_parameter= s =3D { 0 };
init_key_type(&kt, "AES-192-GCM&= quot;, "none", true, false);
@@ -924,13 +883,12 @= @
assert_int_equal(key_parameters.cipher_size, 24);
assert_int_equal(key_parameters.hmac_size, 12);
- uint8_t = exp_cipherkey[24] =3D
-= {0xed, 0x85, 0x33, 0xdb, 0x1c, 0x28, 0xac, 0xe4,
- 0x18, 0xe9, 0x00, 0x6a, 0xb2, 0x9c, 0x= 17, 0x41,
- 0x7d, 0= x60, 0xeb, 0xe6, 0xcd, 0x90, 0xbf, 0x0a};
+ uint8_t exp_cipherkey[24] =3D { 0xed, 0x85, 0x33,= 0xdb, 0x1c, 0x28, 0xac, 0xe4,
+ 0x18, 0xe9, 0x00, 0x6a, 0xb2, = 0x9c, 0x17, 0x41,
+ = 0x7d, 0x60, 0xeb, 0xe6, 0xcd, 0x90, 0xbf, 0= x0a };

- {0x86, 0x89, 0x0a, 0xab, 0xf0, 0x32, 0xcb, 0x59, 0xf4, 0xc= f, 0xa3, 0x4e};
+ = uint8_t exp_impl_iv[12] =3D { 0x86, 0x89, 0x0a, 0xab, 0xf0, 0x32,+ = 0xcb, 0x59, 0xf4, 0xcf, 0xa3, 0x4e };

= assert_memory_equal(key_parameters.cipher, exp_cipherkey, sizeof(exp_c= ipherkey));
assert_memory_equal(key_parameters.hmac, e= xp_impl_iv, sizeof(exp_impl_iv));
@@ -960,20 +918,16 @@
cmocka_unit_test(crypto_test_ovpn_expand_openssl3),
cmocka_unit_test_prestate_setup_teardown(crypto_tes= t_epoch_key_generation,
= crypto_test_epoch_setup,
- crypto_t= est_epoch_teardown,
- = &prestate_num16),=
+ = crypto_test_epoch_teardown, &prestate_num16),
cmocka_unit_test_prestate_setup_teardown(crypto_test= _epoch_key_rotation,
= crypto_test_epoch_setup,
- crypto_test= _epoch_teardown,
- = &prestate_num13),+ = crypto_test_epoch_teardown, &prestate_num13),
cmocka_unit_test_prestate_setup_teardown(crypto_test_ep= och_key_receive_lookup,
= crypto_test_epoch_setup,
- crypto_t= est_epoch_teardown,
- = &prestate_num13),=
+ = crypto_test_epoch_teardown, &prestate_num13),
cmocka_unit_test_prestate_setup_teardown(crypto_test= _epoch_key_overflow,
= crypto_test_epoch_setup,
- crypto_test= _epoch_teardown,
- = &prestate_num32),+ = crypto_test_epoch_teardown, &prestate_num32),
cmocka_unit_test(epoch_test_derive_data_key)
= };

diff --git a/tests/unit_tes= ts/openvpn/test_cryptoapi.c b/tests/unit_tests/openvpn/test_cryptoapi.c
index 072cc78..0cfc952 100644
--- a/tests/unit= _tests/openvpn/test_cryptoapi.c
+++ b/tests/unit_tests/open= vpn/test_cryptoapi.c
@@ -31,7 +31,7 @@
#in= clude "xkey_common.h"
#include "cert_data.h= "

+#if defined(HAVE_XKEY_= PROVIDER) && defined(ENABLE_CRYPTOAPI)
#include &l= t;setjmp.h>
#include <cmocka.h>
= #include <openssl/bio.h>
@@ -42,19 +42,18 @@ #include "test_common.h"

#include <cryptoapi.h>

-#include <cryptoapi.c> /* pull-in the whole file to test s= tatic functions */
+#= include <cryptoapi.c> /* pull-in the whole file to test stati= c functions */

struct management *manage= ment; /* global */
static OSSL_PROVIDER *prov[2];
/* mock a management function that xkey_provider= needs */
char *
-management_query_pk_sig(struct management *man, const char *b64= _data,
- = const char *algorithm)
+management_query_pk_sig(struct management *man, const char *b64= _data, const char *algorithm)
{
- (void) man;
- (void) b64_data;
- (void) algorithm;
+ (void)man;
+ (void)b64_data;
+ (void)algorithm;
return NULL;
}

@@ -73,14 +72,12 @@
OSSL_LIB_CTX *tls_libctx;

#i= fndef _countof
-#define= _countof(x) sizeof((x))/sizeof(*(x))
+#define _countof(x) sizeof((x)) / sizeof(*(x))
= #endif

/* test data */
= -static const uint8_t test_hash[]= =3D {
- 0x77, 0x38,= 0x65, 0x00, 0x1e, 0x96, 0x48, 0xc6, 0x57, 0x0b, 0xae,
- 0xc0, 0xb7, 0x96, 0xf9, 0x66, 0x4d, 0x= 5f, 0xd0, 0xb7
-};
+static const uint8_t tes= t_hash[] =3D { 0x77, 0x38, 0x65, 0x00, 0x1e, 0x96, 0x48, 0xc6, 0x57, 0x0b,<= /span>
+ = 0xae, 0xc0, 0xb7, 0x96, 0xf9, 0x66, 0x4d, 0x5f, 0xd0, 0xb7= };

/* valid test strings to test with a= nd without embedded and trailing spaces */
static const ch= ar *valid_str[] =3D {
@@ -101,13 +98,13 @@
= */
static struct test_cert
{
= - const char *const cert; = /* certificate as PEM */
- const char *const key; /* key as unencrypted PE= M */
- const char *c= onst cname; /* common-name */
- const char *const issuer; /* issuer common= -name */
- const cha= r *const friendly_name; /* identifies certs loaded to the store -- keep = unique */
- const ch= ar *hash; /* SHA1 fingerprint */
- int valid; /* non= zero if certificate has not expired */
+ const char *const cert; /* certificate as P= EM */
+ const char= *const key; /* key as unencrypted PEM */
+ const char *const cname; /* c= ommon-name */
+ co= nst char *const issuer; /* issuer common-name */
+ const char *const friendly_name; /*= identifies certs loaded to the store -- keep unique */
+ const char *hash; /*= SHA1 fingerprint */
= + int valid; /* nonzero if certificate has not exp= ired */
} certs[5];

sta= tic bool certs_loaded;
@@ -118,11 +115,11 @@
init_cert_data(void)

{
struct test= _cert certs_local[] =3D {
- {cert1, key1, cname1, "OVPN TEST CA1", "OVPN= Test Cert 1", hash1, 1},
- {cert2, key2, cname2, "OVPN TEST CA2", &qu= ot;OVPN Test Cert 2", hash2, 1},
- {cert3, key3, cname3, "OVPN TEST CA1"= ;, "OVPN Test Cert 3", hash3, 1},
- {cert4, key4, cname4, "OVPN TEST C= A2", "OVPN Test Cert 4", hash4, 0},
- {0}
+ { cert1, key1, cname1, "OVPN TEST CA1&= quot;, "OVPN Test Cert 1", hash1, 1 },
+ { cert2, key2, cname2, "OVPN TEST= CA2", "OVPN Test Cert 2", hash2, 1 },
+ { cert3, key3, cname3, "OVPN= TEST CA1", "OVPN Test Cert 3", hash3, 1 },
+ { cert4, key4, cname4, "= ;OVPN TEST CA2", "OVPN Test Cert 4", hash4, 0 },
<= span style=3D"color: hsl(120, 100%, 40%);">+ { 0 }

= };
assert(sizeof(certs_local) =3D=3D sizeof(certs)= );
memcpy(certs, certs_local, sizeof(certs_local));
@@ -144,20 +141,21 @@
static void
= import_certs(void **state)
{
- (void) state;
+ (void)state;
if (cer= ts_loaded)
{
return; }
init_cert_data();
- user_store =3D CertOpenStore(CERT_STORE= _PROV_SYSTEM, 0, 0, CERT_SYSTEM_STORE_CURRENT_USER
- |CERT_STORE_OPE= N_EXISTING_FLAG, L"MY");
+ user_store =3D
+ CertOpenStore(CERT_STORE_PROV_SYSTEM, 0, 0,+ CERT_SY= STEM_STORE_CURRENT_USER | CERT_STORE_OPEN_EXISTING_FLAG, L"MY");<= /span>
assert_non_null(user_store);
for = (struct test_cert *c =3D certs; c->cert; c++)
{
/* Convert PEM cert & key to pkcs12 and import */=
- const char *p= ass =3D "opensesame"; /* some password */
- const wchar_t *wpass =3D L&quo= t;opensesame"; /* same as a wide string */
+ const char *pass =3D "opensesame= "; /* some password */
+ const wchar_t *wpass =3D L"opensesame"; /* s= ame as a wide string */

X509 *x5= 09 =3D NULL;
EVP_PKEY *pkey =3D NULL;
@@ -191,7 +189,7 @@

return;
}


- CRYPT_DATA_BLOB blob =3D {.cbData =3D 0, .pbData =3D NULL}= ;
+ CRYPT_DATA= _BLOB blob =3D { .cbData =3D 0, .pbData =3D NULL };
= int len =3D i2d_PKCS12(p12, &blob.pbData); /* pbData will be allocate= d by OpenSSL */
if (len <=3D 0)
{

@@ -200,7 +198,7 @@
}<= /span>
blob.cbData =3D len;

<= span style=3D"color: hsl(0, 100%, 40%);">- DWORD flags =3D PKCS12_AL= LOW_OVERWRITE_KEY|PKCS12_ALWAYS_CNG_KSP;

+ DWORD flags =3D PKCS12_ALLOW_OVERWRITE_KEY | P= KCS12_ALWAYS_CNG_KSP;
HCERTSTORE tmp_store =3D PFX= ImportCertStore(&blob, wpass, flags);
PKCS12_f= ree(p12);
OPENSSL_free(blob.pbData);
@@ -228,7 +226,7 @@

static int
cleanup= (void **state)
{
- (void) state;
+ (void)state;
struct gc_arena gc =3D gc_n= ew();
if (user_store) /* delete all certs we imported = */
{
@@ -260,7 +258,7 @@
static void

test_find_cert_bythumb(void **state)
{
- (voi= d) state;
+ (void)= state;
char select_string[64];
st= ruct gc_arena gc =3D gc_new();
const CERT_CONTEXT *ctx= ;
@@ -293,7 +291,7 @@
static void test_find_cert_byname(void **state)
{
<= span style=3D"color: hsl(0, 100%, 40%);">- (void) state;

+ (void)state;

= char select_string[64];
struct gc_arena gc =3D gc_n= ew();
const CERT_CONTEXT *ctx;
@@ -326= ,7 +324,7 @@
static void
test_find_cert_b= yissuer(void **state)
{
- (void) state;
+ (void)state;
char select_string[6= 4];
struct gc_arena gc =3D gc_new();
= const CERT_CONTEXT *ctx;
@@ -359,7 +357,7 @@
= static int
setup_xkey_provider(void **state)=
{
- (void= ) state;
+ (void)s= tate;
/* Initialize providers in a way matching what O= penVPN core does */
tls_libctx =3D OSSL_LIB_CTX_new();=
prov[0] =3D OSSL_PROVIDER_load(tls_libctx, "defa= ult");
@@ -374,7 +372,7 @@
static int=
teardown_xkey_provider(void **state)
{
- (void) state;
+ (void)state; for (size_t i =3D 0; i < _countof(prov); i++)
{

if (prov[i])
@@ -396,7 += 394,7 @@
void
test_cryptoapi_sign(void **= state)
{
- (void) state;
+ (void)state;
char select_string[64];
<= span> X509 *x509 =3D NULL;

EVP_PKEY *privkey =3D N= ULL;
@@ -430,7 +428,7 @@
void
test_ssl_ctx_use_cryptoapicert(void **state)

{=
- (void) state;
= + (void)state;
char select_string[64];


impo= rt_certs(state); /* a no-op if already imported */
@@ -454,= 7 +452,8 @@
/* Use OpenSSL to check that the cert = and private key in ssl_ctx "match" */
if= (!SSL_CTX_check_private_key(ssl_ctx))
{- fail_msg("Cert= ificate and private key in ssl_ctx do not match for <%s>", c->= ;friendly_name);
+ = fail_msg("Certificate and private key in ssl_ctx do not match= for <%s>",
- (void) state;
+ (void)state;
=
for (int i =3D 0; i < _countof(valid_str); i++) {
@@ -512,4 +511,4 @@
retu= rn 0;
}

-#endif /* ifdef HAVE_XKEY_PROVIDER */
+#endif /* ifdef HAVE_XKEY_PROVIDER = */

diff --git a/tests/unit_tests/openvpn/test_misc.c b/test= s/unit_tests/openvpn/test_misc.c
index fb46e99..1857922 100= 644
--- a/tests/unit_tests/openvpn/test_misc.c
+++ b/tests/unit_tests/openvpn/test_misc.c

@@ -44,14 +4= 4,18 @@
{
struct gc_arena gc =3D gc_n= ew();

- const char *input =3D "V4,dev-type tun,link-mtu 1457,tun-mtu 140= 0,proto UDPv4,auth SHA1,keysize 128,key-method 2,tls-server";+ const char *input =3D
+ "V4,dev-t= ype tun,link-mtu 1457,tun-mtu 1400,proto UDPv4,auth SHA1,keysize 128,key-me= thod 2,tls-server";

const char = *output =3D options_string_compat_lzo(input, &gc);

- assert_string_equal(= output, "V4,dev-type tun,link-mtu 1458,tun-mtu 1400,proto UDPv4,auth S= HA1,keysize 128,key-method 2,tls-server,comp-lzo");
+ assert_string_equal(
+ output,

+ "V4,dev-type tun,link-mt= u 1458,tun-mtu 1400,proto UDPv4,auth SHA1,keysize 128,key-method 2,tls-serv= er,comp-lzo");

/* This string i= s has a much too small link-mtu so we should fail on it" */
= - input =3D "V4,dev-type = tun,link-mtu 2,tun-mtu 1400,proto UDPv4,auth SHA1,keysize 128,key-method 2,= tls-server";
+ = input =3D
+ = "V4,dev-type tun,link-mtu 2,tun-mtu 1400,proto UDPv4,auth SHA1,keysize= 128,key-method 2,tls-server";

= output =3D options_string_compat_lzo(input, &gc);

@@ -64,11 +68,14 @@
assert_string_equal(i= nput, output);


- input =3D "V4,dev-type tun,link-mtu 9= 99,tun-mtu 1400,proto UDPv4,auth SHA1,keysize 128,key-method 2,tls-server&q= uot;;
+ input =3D<= /span>
+ "V4,dev= -type tun,link-mtu 999,tun-mtu 1400,proto UDPv4,auth SHA1,keysize 128,key-m= ethod 2,tls-server";
output =3D options_string_co= mpat_lzo(input, &gc);

/* 999 -&g= t; 1000, 3 to 4 chars */
+ assert_= string_equal(
+ = output,
+ &q= uot;V4,dev-type tun,link-mtu 1000,tun-mtu 1400,proto UDPv4,auth SHA1,keysiz= e 128,key-method 2,tls-server,comp-lzo");

= gc_free(&gc);
}
@@ -110,7 += 117,6 @@
}


<= span style=3D"color: hsl(0, 100%, 40%);">-

struct word
{
const char *word;
@@ -= 121,7 +127,7 @@
static uint32_t
word_hash= _function(const void *key, uint32_t iv)
{
- const char *str =3D (const char *)= key;
+ const char= *str =3D (const char *)key;
const int len =3D strlen(= str);
return hash_func((const uint8_t *)str, len, iv);=
}
@@ -161,11 +167,10 @@
= static void
test_list(void **state)
{
-
-/*
- * Test the hash code by implementing a simple
- * word frequency algorithm.
<= span style=3D"color: hsl(0, 100%, 40%);">- */

+ /*
+ * Test the hash code by implementing a simple
<= span style=3D"color: hsl(120, 100%, 40%);">+ * word frequency algorithm= .

+ */
=
struct gc_arena gc =3D gc_new();
struct hash *hash =3D hash_init(10000, get_random(), word_hash_func= tion, word_compare_function);

@@ -174,7 +179,7 @@ printf("hash_init n_buckets=3D%d mask=3D0x%08x\n", ha= sh->n_buckets, hash->mask);

ch= ar wordfile[PATH_MAX] =3D { 0 };
- openvpn_test_get_srcdir_dir(wordfile, PATH_MAX, "/../..= /../COPYRIGHT.GPL" );
+ openvpn_test_get_srcdir_dir(wordfile, PATH_MAX, "/../../../= COPYRIGHT.GPL");

FILE *words = =3D fopen(wordfile, "r");
assert_non_null(wo= rds);
@@ -200,7 +205,7 @@
c = =3D buf[bi++];
if (isalnum(c) || c =3D=3D '= ;_')
{
- assert_true(wbi < (int) sizeof(wordbuf= ));
+ = assert_true(wbi < (int)sizeof(wordbuf));
= wordbuf[wbi++] =3D c;
}
= else
@@ -209,13 +214,13 @@
= {
wordcount++;

- = ASSERT(wbi < (int) sizeof(wordbuf));
+ ASSERT(wbi < (int)sizeof(word= buf));
wordbuf[wbi++] =3D '\0'= ;

/* word is parsed = from stdin */

/* doe= s it already exist in table? */
- struct word *w =3D (struct word *) hash_looku= p(hash, wordbuf);
+ = struct word *w =3D (struct word *)hash_lookup(hash, wordb= uf);

if (w) {
@@ -230,13 +235,13 @@=
w->word =3D string_alloc(wordbuf, &am= p;gc);
w->n =3D 1;
assert_true(hash_add(hash, w->word, w, fals= e));

- = assert_true(hash_add(nhash, w->word, (void *) ((ptr_type )(random= () & 0x0F) + 1), false));
+ assert_true(hash_add(nhash, w->word,
+ = (void *)((ptr_type)(random() & 0x0F) + 1), fals= e));
}
= }
wbi =3D 0;
= }
- }- while (c);
<= span style=3D"color: hsl(120, 100%, 40%);">+ } while (c);

= }

assert_int_equal(wordco= unt, 2971);
@@ -261,7 +266,7 @@
while ((he =3D hash_iterator_next(&hi)))
= {
- = struct word *w =3D (struct word *) he->value;
<= span style=3D"color: hsl(120, 100%, 40%);">+ struct word *w = =3D (struct word *)he->value;

/*printf(= "%6d '%s'\n", w->n, w->word); */
= ++count;
/* check a few wor= ds to match prior results */
@@ -269,19 +274,19 @@ {
assert_int_= equal(w->n, 49);
}
- else if (!strcmp(w->wo= rd, "redistribute"))
+ else if (!strcmp(w->word, "redistribute&= quot;))
{
= assert_int_equal(w->n, 5);
}
- else if (!= strcmp(w->word, "circumstances"))
+ else if (!strcmp(w->word, &qu= ot;circumstances"))
{
assert_int_equal(w->n, 1);

= }
- = else if (!strcmp(w->word, "so"))
+ else if (!strcmp(w->wo= rd, "so"))
{
= assert_int_equal(w->n, 8);
= }
- = else if (!strcmp(w->word, "BECAUSE"))
+ else if (!strcmp(w->wo= rd, "BECAUSE"))
{
assert_int_equal(w->n, 1);

= }
@@ -296,12 +301,12 @@
{
for (ptr_type i =3D 1; i <=3D 16; ++i) {
- = struct hash_element *item =3D hash_lookup_by_value(nhash, (void *) = i);
- hash_r= emove_by_value(nhash, (void *) i);
+ struct hash_element *item =3D hash_lookup_by_val= ue(nhash, (void *)i);
+ hash_remove_by_value(nhash, (void *)i);
= /* check item got removed if it was present before */
if (item)

{
- assert_null(hash_lookup_= by_value(nhash, (void *) i));
+ assert_null(hash_lookup_by_value(nhash, (void *)i= ));
}
}
}

@@ -378,14 +383,12 @@
mock_s= et_debug_level(saved_log_level);
}

-const struct CMUnitTest mis= c_tests[] =3D {
- cm= ocka_unit_test(test_compat_lzo_string),
- cmocka_unit_test(test_auth_fail_temp_no_flags),
- cmocka_unit_test(test_a= uth_fail_temp_flags),
-= cmocka_unit_test(test_auth_fail_temp_flags_msg),
- cmocka_unit_test(test_list),
= - cmocka_unit_test(test_atoi_v= ariants)
-};
= +const struct CMUnitTest misc_t= ests[] =3D { cmocka_unit_test(test_compat_lzo_string),
+ = cmocka_unit_test(test_auth_fail_temp_no_flags),
+ cmock= a_unit_test(test_auth_fail_temp_flags),
+ cmocka_unit_te= st(test_auth_fail_temp_flags_msg),
+ cmocka_unit_test(te= st_list),
+ = cmocka_unit_test(test_atoi_variants) };

int
main(void)
diff --git a/tests/unit_tests/openvpn/test_ncp.c b/tests/unit_tests/ope= nvpn/test_ncp.c

index 941216a..0a1c774 100644
--- a/tests/unit_tests/openvpn/test_ncp.c

+++ b/tests/un= it_tests/openvpn/test_ncp.c
@@ -46,8 +46,7 @@
/* Define this function here as dummy since including the ssl_*.c files=

* leads to having to include even more unrelated code */=
bool
= -key_state_export_keying_material(struct tls_session *session,
- c= onst char *label, size_t label_size,

+key_state_export_keying_material(struct tls_session *sessi= on, const char *label, size_t label_size,
= void *ekm, size_t ekm_size)
{
<= span> ASSERT(0);

@@ -72,8 +71,7 @@
= bool have_blowfish =3D cipher_valid("BF-CBC");
=
assert_string_equal(mutate_ncp_cipher_list("none= ", &gc), "none");
- assert_string_equal(mutate_ncp_cipher_list("AES-256= -GCM:none", &gc),
- "AES-256-GCM:none");
+ assert_string_equal(mutate_ncp_= cipher_list("AES-256-GCM:none", &gc), "AES-256-GCM:none&= quot;);


assert_string_equal(mutate_n= cp_cipher_list(aes_ciphers, &gc), aes_ciphers);

@@ -85,8 +83,7 @@
if (have_chacha &&= ; have_blowfish)
{
assert_str= ing_equal(mutate_ncp_cipher_list(bf_chacha, &gc), bf_chacha);- assert_string_equal(mut= ate_ncp_cipher_list("BF-CBC:CHACHA20-POLY1305", &gc),<= br>- b= f_chacha);
+ a= ssert_string_equal(mutate_ncp_cipher_list("BF-CBC:CHACHA20-POLY1305&qu= ot;, &gc), bf_chacha);
}
else=
{
@@ -98,14 +95,14 @@
aes_ciphers);


= /* Check that optional ciphers work */
- assert_string_equal(mutate_ncp_cipher_list("?= AES-256-GCM:?AES-128-GCM", &gc),
- aes_ciphers);
+ assert_string_equal(mutate_ncp_ci= pher_list("?AES-256-GCM:?AES-128-GCM", &gc), aes_ciphers);

/* All unsupported should still yield = an empty list */
assert_ptr_equal(mutate_ncp_cipher_li= st("?kugelfisch:?grasshopper", &gc), NULL);
=
/* If the last is optional, previous invalid ciphers = should be ignored */
- = assert_ptr_equal(mutate_ncp_cipher_list("Vollbit:Littlebit:AES-256-= CBC:BF-CBC:?nixbit", &gc), NULL);
+ assert_ptr_equal(mutate_ncp_cipher_list("Vo= llbit:Littlebit:AES-256-CBC:BF-CBC:?nixbit", &gc),
+ NULL);
<= br>
/* We do not support CCM ciphers */<= br> assert_ptr_equal(mutate_ncp_cipher_list("AES-256-GCM:AES= -128-CCM", &gc), NULL);
@@ -126,19 +123,19 @@
assert_ptr_equal(mutate_ncp_cipher_list("AES-256-GCM:= vollbit", &gc), NULL);
assert_ptr_equal(mutat= e_ncp_cipher_list("", &gc), NULL);
- assert_ptr_equal(mutate_nc= p_cipher_list(
- = "ChaCha20-Poly1305:ChaCha20-Poly1305:ChaCha20-Poly13= 05:"
- = "ChaCha20-Poly1305:ChaCha20-Poly1305:ChaCha20-Poly1305:&q= uot;
- = "ChaCha20-Poly1305", &gc), NULL);
+ assert_ptr_equal(mutate_ncp_cipher_= list("ChaCha20-Poly1305:ChaCha20-Poly1305:ChaCha20-Poly1305:"
+ = "ChaCha20-Poly1305:ChaCha20-Poly1305:ChaCha20-Pol= y1305:"
+ = "ChaCha20-Poly1305",<= br>+ = &gc),
+ NULL);

#ifde= f ENABLE_CRYPTO_OPENSSL
- assert_string_equal(mutate_ncp_cipher_list("id-aes128-GCM:id-aes= 256-GCM",
- = &gc), "AES-128-GCM:AES-256= -GCM");
+ ass= ert_string_equal(mutate_ncp_cipher_list("id-aes128-GCM:id-aes256-GCM&q= uot;, &gc),
+ = "AES-128-GCM:AES-256-GCM");
= #else
if (have_blowfish)
{=
- assert_string_equal(= mutate_ncp_cipher_list("BLOWFISH-CBC",
- = &gc), "BF-CBC");
+ assert_string_equal(mutate_ncp_cipher_list("BLOW= FISH-CBC", &gc), "BF-CBC");
}
#endif
gc_free(&gc);
@= @ -192,37 +189,28 @@
const char *serverlist =3D "= CHACHA20_POLY1305:AES-128-GCM";
const char *serve= rlistbfcbc =3D "CHACHA20_POLY1305:AES-128-GCM:BF-CBC:none";

- best_= cipher =3D ncp_get_best_cipher(serverlist,
- "IV_YOLO=3D= NO\nIV_BAR=3D7",
-= "BF-CBC", &gc);<= br>+ best_cipher =3D ncp_get= _best_cipher(serverlist, "IV_YOLO=3DNO\nIV_BAR=3D7", "BF-CBC= ", &gc);

assert_ptr_equal(b= est_cipher, NULL);


- best_cipher =3D ncp_get_best_cipher(se= rverlistbfcbc,
- = "IV_YOLO=3DNO\nIV_BAR=3D7",=
- = "BF-CBC", &gc);
+ best_cipher =3D ncp_get_best_cipher(serverlistbfcbc= , "IV_YOLO=3DNO\nIV_BAR=3D7", "BF-CBC", &gc);

assert_string_equal(best_cipher, "BF= -CBC");


- best_cipher =3D ncp_get_best_cipher(serverli= st,
- = "IV_NCP=3D1\nIV_BAR=3D7",
- &qu= ot;AES-128-GCM", &gc);
+ best_cipher =3D ncp_get_best_cipher(serverlist, "IV_NC= P=3D1\nIV_BAR=3D7", "AES-128-GCM", &gc);

assert_string_equal(best_cipher, "AES-128-GCM&= quot;);

- best_cipher =3D ncp_get_best_cipher(serverlist, NULL,
- = "AES-128-GCM", &gc);

+ best_cipher =3D ncp_get_best_cipher(serverlist, NULL,= "AES-128-GCM", &gc);

= assert_string_equal(best_cipher, "AES-128-GCM");
=
- best_cipher =3D = ncp_get_best_cipher(serverlist, NULL,
- "none", &am= p;gc);
+ best_ciph= er =3D ncp_get_best_cipher(serverlist, NULL, "none", &gc);
assert_ptr_equal(best_cipher, NULL);

- best_cipher =3D ncp= _get_best_cipher(serverlistbfcbc, NULL,
- "none", &= amp;gc);
+ best_ci= pher =3D ncp_get_best_cipher(serverlistbfcbc, NULL, "none", &= gc);
assert_string_equal(best_cipher, "none"= );

best_cipher =3D ncp_get_best_ciph= er(serverlist, NULL, NULL, &gc);
@@ -240,28 +228,23 @@<= /span>

const char *serverlist =3D "CHA= CHA20_POLY1305:AES-128-GCM:AES-256-GCM";

<= span style=3D"color: hsl(0, 100%, 40%);">- best_cipher =3D ncp_get_best_= cipher(serverlist,

- = "IV_YOLO=3DNO\nIV_NCP=3D2\nIV_BAR= =3D7",
- = "BF-CBC", &gc);
+ best_cipher =3D ncp_get_best_ciph= er(serverlist, "IV_YOLO=3DNO\nIV_NCP=3D2\nIV_BAR=3D7", "BF-C= BC", &gc);

assert_string_eq= ual(best_cipher, "AES-128-GCM");

/* Best cipher is in --cipher of client */

- best_cipher =3D ncp_get_best_cipher(serverl= ist, "IV_NCP=3D2\nIV_BAR=3D7",
- "CHACHA20_POL= Y1305", &gc);
- = best_cipher =3D ncp_get_best_cipher(serverlist, "IV_CIPHERS=3DAES-128-= GCM",
- = "AES-256-CBC", &gc);
+ best_cipher =3D ncp_get_best_= cipher(serverlist, "IV_CIPHERS=3DAES-128-GCM", "AES-256-CBC&= quot;, &gc);



a= ssert_string_equal(best_cipher, "AES-128-GCM");
=
/* IV_NCP=3D2 should be ignored if IV_CIPHERS is sent= */
- best_cipher = =3D ncp_get_best_cipher(serverlist,
- "IV_FOO=3D7\nIV_CI= PHERS=3DAES-256-GCM\nIV_NCP=3D2",
+ best_cipher =3D ncp_get_best_cipher(serverlist, &quo= t;IV_FOO=3D7\nIV_CIPHERS=3DAES-256-GCM\nIV_NCP=3D2",
= "AES-256-CBC", &gc);

assert_string_equal(best_cipher, "= ;AES-256-GCM");
@@ -312,11 +295,14 @@
=
if (have_chacha)
{
- assert_string_equal(o.ncp_= ciphers, "BF-CBC:AES-256-GCM:AES-128-GCM:CHACHA20-POLY1305:AES-128-CBC= :AES-256-CBC");

= + assert_string_equal(
+ o.ncp_ciphers,
+ "BF-CBC:AES-256-GCM:AES-128-GCM:CHACHA20-= POLY1305:AES-128-CBC:AES-256-CBC");
}
<= span> else

{
- assert_string_equal(o.ncp_ciphers, "BF-CBC:AES= -256-GCM:AES-128-GCM:AES-128-CBC:AES-256-CBC");
+ assert_string_equal(o.ncp_ciphers= ,
+ = "BF-CBC:AES-256-GCM:AES-128-GCM:AES-128-CBC:AES-256-CBC"= ;);
}
assert_string_equal(o.ncp_c= iphers_conf, "BF-CBC:DEFAULT:AES-128-CBC:AES-256-CBC");
@@ -326,7 +312,8 @@

if (have_chacha)

{
- assert_string_equal(o.ncp_ciphers, "= ;AES-256-GCM:AES-128-GCM:CHACHA20-POLY1305:AES-128-CBC:AES-192-CBC");<= /span>
+ assert_strin= g_equal(o.ncp_ciphers,
- assert_string_eq= ual(o.ncp_ciphers, "AES-192-GCM:AES-128-CBC:AES-256-GCM:AES-128-GCM:CH= ACHA20-POLY1305");
+ assert_string_equal(o.ncp_ciphers,
+ "AES-192-GCM:AE= S-128-CBC:AES-256-GCM:AES-128-GCM:CHACHA20-POLY1305");
}

else
{
@@= -355,7 +343,7 @@
test_ncp_expand(void **state)
= {
bool have_chacha =3D cipher_valid("CHACH= A20-POLY1305");
- = struct options o =3D {0};
+ struct options o =3D { 0 };

= o.gc =3D gc_new();
struct gc_arena gc =3D gc_new(= );
diff --git a/tests/unit_tests/openvpn/test_networking.c = b/tests/unit_tests/openvpn/test_networking.c
index 0434707.= .f2da83e 100644
--- a/tests/unit_tests/openvpn/test_network= ing.c
+++ b/tests/unit_tests/openvpn/test_networking.c
@@ -110,12 +110,10 @@
printf("\n"= ;);

return net_route_v4_add(NULL, &a= mp;dst, prefixlen, NULL, iface, 0, metric);
-
}

static int

-net__rout= e_v4_add_gw(const char *dst_str, int prefixlen, const char *gw_str,<= br>- int metr= ic)
+net__route_v4_ad= d_gw(const char *dst_str, int prefixlen, const char *gw_str, int metric)
{
in_addr_t dst, gw;
= int ret;
@@ -140,8 +138,7 @@
dst = =3D ntohl(dst);
gw =3D ntohl(gw);

- printf("CMD: ip= route add %s/%d dev %s via %s", dst_str, prefixlen, iface,
= - gw_str);
+ printf("CMD: ip route a= dd %s/%d dev %s via %s", dst_str, prefixlen, iface, gw_str);
if (metric > 0)
{
= printf(" metric %d", metric);
@@ -176,12 +173= ,10 @@
printf("\n");

return net_route_v6_add(NULL, &dst, prefixlen, NULL, if= ace, 0, metric);
-
}

static int
-net__route_v6_add_gw(const char *dst= _str, int prefixlen, const char *gw_str,

- int metric)
+net__route_v6_add_gw(const char *dst_str,= int prefixlen, const char *gw_str, int metric)
{ struct in6_addr dst, gw;
int ret;<= br>@@ -203,8 +198,7 @@
return -1;
= }

- printf("CMD: ip -6 route add %s/%d dev %s via %s", d= st_str, prefixlen,
- = iface, gw_str);
+ printf("CMD: ip -6 route add %s/%d dev %s via %s", dst_st= r, prefixlen, iface, gw_str);
if (metric > 0)
{
printf(" metric %d", m= etric);
diff --git a/tests/unit_tests/openvpn/test_packet_i= d.c b/tests/unit_tests/openvpn/test_packet_id.c
index 084db= 5e..d623c3d 100644
--- a/tests/unit_tests/openvpn/test_pack= et_id.c
+++ b/tests/unit_tests/openvpn/test_packet_id.c
@@ -36,8 +36,10 @@
#include "reliable.h&= quot;
#include "test_common.h"
=
-struct test_packet_id= _write_data {
- stru= ct {
+struct test_pac= ket_id_write_data
+{<= /span>
+ struct+ {
= uint32_t buf_id;
uint32_t buf_time;
} test_buf_data;

@@ -49,15 +51,14 @@
static int

test_packet_id_write_setup(void **state)
{
- s= truct test_packet_id_write_data *data =3D
- calloc(1, sizeof(struct test_packet_id_write_da= ta));
+ struct tes= t_packet_id_write_data *data =3D calloc(1, sizeof(struct test_packet_id_wri= te_data));

if (!data)
{

return -1;
}<= br>
- data-&g= t;test_buf.data =3D (void *) &data->test_buf_data;
+ data->test_buf.data =3D (void = *)&data->test_buf_data;
data->test_buf.capac= ity =3D sizeof(data->test_buf_data);
data->gc = =3D gc_new();

@@ -162,7 +163,6 @@<= br> static void
test_get_num_output_sequenced_availa= ble(void **state)
{
-
struct reliable *rel =3D malloc(sizeof= (struct reliable));
reliable_init(rel, 100, 50, 8, fal= se);

@@ -180,14 +180,14 @@
/* test ids close to int/unsigned int barrier */


rel->array[5].active =3D true;
- rel->array[5].packet_id =3D (0x80000= 000u -3);
+ rel-&g= t;array[5].packet_id =3D (0x80000000u - 3);
rel->ar= ray[6].active =3D false;
+ rel->packet_id =3D (0x80000000u - 1);

assert_int_equal(6, reliable_get_num_ou= tput_sequenced_available(rel));

rel-= >array[5].active =3D true;
- rel->array[5].packet_id =3D (0x80000000u -3);
+ rel->array[5].packet_id =3D= (0x80000000u - 3);

rel->packet_id =3D 0x80000001u;=

assert_int_equal(4, reliable_get_nu= m_output_sequenced_available(rel));
@@ -195,7 +195,7 @@

/* test wrapping */
= rel->array[5].active =3D true;
- rel->array[5].packet_id =3D (0xffffffffu -3);+ rel->array[5].packet_= id =3D (0xffffffffu - 3);
rel->array[6].active =3D = false;
rel->packet_id =3D (0xffffffffu - 1);=

@@ -223,7 +223,7 @@
assert= _true(packet_id_write_epoch(&data->pis, 0x23, &buf));
=
assert_int_equal(buf.len, 8);
- uint8_t expected_header[8] =3D { 0= x00, 0x23, 0, 0, 0, 0, 0, 1};
+ uint8_t expected_header[8] =3D { 0x00, 0x23, 0, 0, 0, 0, 0, 1= };
assert_memory_equal(BPTR(&buf), expected_heade= r, 8);

/* too small buffer should er= ror out */
@@ -234,7 +234,7 @@
data-&g= t;pis.id =3D 0xfa079ab9d2e8;
struct buffer buf_48 =3D = alloc_buf_gc(128, &data->gc);
assert_true(packe= t_id_write_epoch(&data->pis, 0xfffe, &buf_48));
- uint8_t expected_header_48[8] =3D = { 0xff, 0xfe, 0xfa, 0x07, 0x9a, 0xb9, 0xd2, 0xe9};
+ uint8_t expected_header_48[8] =3D { 0xff= , 0xfe, 0xfa, 0x07, 0x9a, 0xb9, 0xd2, 0xe9 };
assert_m= emory_equal(BPTR(&buf_48), expected_header_48, 8);

/* test writing/checking the 48 bit per epoch packet cou= nter
@@ -242,7 +242,7 @@
data->pis.= id =3D 0xfffffffffffe;
struct buffer buf_of =3D alloc_= buf_gc(128, &data->gc);
assert_true(packet_id_w= rite_epoch(&data->pis, 0xf00f, &buf_of));
- uint8_t expected_header_of[8] =3D { 0xf= 0, 0x0f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff};
+ uint8_t expected_header_of[8] =3D { 0xf0, 0x0= f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff };
assert_memory= _equal(BPTR(&buf_of), expected_header_of, 8);
<= br> /* This is go over 2^48 - 1 and should error out. */@@ -264,9 +264,9 @@
static void
t= est_copy_acks_to_lru(void **state)
{
- struct reliable_ack ack =3D { .len =3D = 4, .packet_id =3D {2, 1, 3, 2} };
+ struct reliable_ack ack =3D { .len =3D 4, .packet_id =3D = { 2, 1, 3, 2 } };

- struct reliable_ack mru_ack =3D {0 };
+ struct reliable_ack mru_ack =3D { 0= };

/* Test copying to empty ack str= ucture */
copy_acks_to_mru(&ack, &mru_ack, 4);=
@@ -292,7 +292,7 @@

= /* Adding just two packets shoudl ignore the 42 in array and
* reorder the order in the MRU */

- struct reliable_ack ack2 =3D { .len =3D 3, .packet= _id =3D {3, 2, 42} };
+ struct reliable_ack ack2 =3D { .len =3D 3, .packet_id =3D { 3, 2, 42 = } };
copy_acks_to_mru(&ack2, &mru_ack2, 2);
assert_int_equal(mru_ack2.packet_id[0], 3);
assert_int_equal(mru_ack2.packet_id[1], 2);

@@ -31= 3,12 +313,12 @@
assert_int_equal(mru_ack.packet_id[1],= 1);
assert_int_equal(mru_ack.packet_id[2], 3);=

- struct= reliable_ack ack3 =3D { .len =3D 7, .packet_id =3D {5, 6, 7, 8, 9, 10, 11}= };
+ struct reliab= le_ack ack3 =3D { .len =3D 7, .packet_id =3D { 5, 6, 7, 8, 9, 10, 11 } };

/* Adding multiple acks tests if the = a full array is handled correctly */
copy_acks_to_mru(= &ack3, &mru_ack, 7);

- struct reliable_ack expected_ack =3D { .len = =3D 8, .packet_id =3D {5, 6, 7, 8, 9, 10, 11, 2}};
+ struct reliable_ack expected_ack =3D { .= len =3D 8, .packet_id =3D { 5, 6, 7, 8, 9, 10, 11, 2 } };
= assert_int_equal(mru_ack.len, expected_ack.len);

assert_memory_equal(mru_ack.packet_id, expected_ack.packet= _id, sizeof(expected_ack.packet_id));
@@ -329,26 +329,19 @@=
{
openvpn_unit_test_setup();<= br> const struct CMUnitTest tests[] =3D {
- cmocka_unit_test_setup_teardown(tes= t_packet_id_write_short,
+ cmocka_unit_test= _setup_teardown(test_packet_id_write_short, test_packet_id_write_setup,
test_packet_id_write_= teardown),
- cmo= cka_unit_test_setup_teardown(test_packet_id_write_long,
- t= est_packet_id_write_setup,
+ cmocka_unit_test_setup_teardown(test_packet_id_write_long, t= est_packet_id_write_setup,
= test_packet_id_write_teardown),
cmocka_un= it_test_setup_teardown(test_packet_id_write_short_prepend,
- = test_packet_id_write_setup,
- test_packet_id_write_teardo= wn),
+ = test_packet_id_write_setup, test_packet_id_write_t= eardown),
cmocka_unit_test_setup_teardown(test_pac= ket_id_write_long_prepend,
- test_packet_id_write_setup,
+ = test_packet_id_write_setup, test_packet_id_write_teardown= ),
+ cmocka_un= it_test_setup_teardown(test_packet_id_write_short_wrap, test_packet_id_writ= e_setup,
test_pack= et_id_write_teardown),
= - cmocka_unit_test_setup_teardown(test_packet_id_write_short_wrap,
- = test_packet_id_write_setup,
+ cmocka_unit_test_setup_teardown(test_packe= t_id_write_long_wrap, test_packet_id_write_setup,
= test_packet_id_write_teardown),
<= span style=3D"color: hsl(0, 100%, 40%);">- cmocka_unit_test_setup_te= ardown(test_packet_id_write_long_wrap,

- test_packet_id_wri= te_setup,
- = test_packet_id_write_teardown),
- cmocka_unit_test_setup_teardo= wn(test_packet_id_write_epoch,

- test_packet_id_write_setup= ,
+ cmocka_uni= t_test_setup_teardown(test_packet_id_write_epoch, test_packet_id_write_setu= p,
test_packet_id_= write_teardown),

cmocka_unit_tes= t(test_get_num_output_sequenced_available),
diff --git a/te= sts/unit_tests/openvpn/test_pkcs11.c b/tests/unit_tests/openvpn/test_pkcs11= .c
index 591a457..56125df 100644
--- a/test= s/unit_tests/openvpn/test_pkcs11.c
+++ b/tests/unit_tests/o= penvpn/test_pkcs11.c
@@ -39,8 +39,8 @@
#in= clude "test_common.h"

#define = token_name "Test Token"
-#define PIN "12345"
-#define HASHSIZE 20
+#define PIN "12345"
+#define HASHSIZE 20
=

struct management *management; /* glob= al */
@@ -58,8 +58,8 @@

= /* stubs for some unused functions instead of pulling in too many dependenc= ies */
int
-parse_line(const char *line, char **p, const int n, const char *file,=
- const int = line_num, int msglevel, struct gc_arena *gc)
+parse_line(const char *line, char **p, const int n= , const char *file, const int line_num,
+ int msglevel, struct gc_arena *gc) {
assert_true(0);
return = 0;
@@ -91,45 +91,43 @@
void
query_user_add(char *prompt, size_t prompt_len, char *resp, size_t resp_= len, bool echo)

{
- (void) prompt;
- (void) prompt_len;
- (void) resp;
- (void) resp_len;
- (void) echo;
+ (void)prompt;
+= (void)prompt_len;
+ (void)resp;
+ = (void)resp_len;
+ = (void)echo;
assert_true(0);
}
void
purge_user_pass(struct user_pass *up, con= st bool force)
{
- (void) force;
+ (void)force;
secure_memzero(up, sizeof(*= up));
}

char *-management_query_pk_sig(struct= management *man, const char *b64_data,
- const char *algorithm)
= +management_query_pk_sig(struct= management *man, const char *b64_data, const char *algorithm)
{

- (void) man;=
- (void) b64_data;<= /span>
- (void) algorithm;<= /span>
+ (void)man;
+ (void)b64_data;
+ (void)algorithm;
return NULL;
}
-int
-digest_sign_verify(EVP_PKEY *privkey, EVP_PKEY *= pubkey);
+int digest_= sign_verify(EVP_PKEY *privkey, EVP_PKEY *pubkey);
<= br> /* Test certificate database: data for cert1, cert2 .. key1, key2= etc.
* are defined in cert_data.h
*/
static struct test_cert
{
- const char *const cert; = /* certificate as PEM */
- const char *const key; /* key as unencrypted PEM */
- const char *const c= name; /* common-name */
- const char *const issuer; /* issuer common-name = */
- const char *con= st friendly_name; /* identifies certs loaded to the store -- keep unique= */
- uint8_t hash[H= ASHSIZE]; /* SHA1 fingerprint: computed and filled in later */<= /span>
- char *p11_id; = /* PKCS#11 id -- filled in later */
+ const char *const cert; /* c= ertificate as PEM */
= + const char *const key; /* key as unencrypted PEM */+ const char *const cname;= /* common-name */
+ const char *const issuer; /* issuer common-name */=
+ const char *const frie= ndly_name; /* identifies certs loaded to the store -- keep unique */=
+ uint8_t hash[HASHSIZE]= ; /* SHA1 fingerprint: computed and filled in later */
<= span style=3D"color: hsl(120, 100%, 40%);">+ char *p11_id; = /* PKCS#11 id -- filled in later */

} certs[5];

static bool pkcs11_id_management;
= @@ -144,11 +142,11 @@
init_cert_data(void) {
struct test_cert certs_local[] =3D {<= br>- {cert1, key1, cname= 1, "OVPN TEST CA1", "OVPN Test Cert 1", {0}, NULL},=
- {cert2, key2= , cname2, "OVPN TEST CA2", "OVPN Test Cert 2", {0},= NULL},
- {cert= 3, key3, cname3, "OVPN TEST CA1", "OVPN Test Cert 3"= ;, {0}, NULL},
- = {cert4, key4, cname4, "OVPN TEST CA2", "OVPN Test Cer= t 4", {0}, NULL},
+ = { cert1, key1, cname1, "OVPN TEST CA1", "OVPN Test Cert 1= ", { 0 }, NULL },
+ { cert3, key3, cname3, "OVPN TEST CA1", "= OVPN Test Cert 3", { 0 }, NULL },
+ { cert4, key4, cname4, "OVPN TEST CA2"= , "OVPN Test Cert 4", { 0 }, NULL },
+ { 0 }
};
= assert(sizeof(certs_local) =3D=3D sizeof(certs));
memcpy(certs, certs_local, sizeof(certs_local));

@@ = -159,9 +157,9 @@
get_user_pass_cr(struct user_pass *up, co= nst char *auth_file, const char *prefix,
= const unsigned int flags, const char *unused)
{
= - (void) unused;
+ (void)unused;

bool ret =3D true;

+ if (!strcmp(prefix, "pkcs11-id-request") && f= lags & GET_USER_PASS_NEED_STR)
{
= assert_true(pkcs11_id_management);
strncpy= nt(up->password, pkcs11_id_current, sizeof(up->password));
= @@ -195,15 +193,16 @@
static int
in= it(void **state)
{
- (void) state;
+ (void)state;

- umask(0077); /* ensure all files and director= ies we create get user only access */
+ umask(0077); /* ensure all files and directories we c= reate get user only access */
char config[256];=

init_cert_data();
if = (!mkdtemp(softhsm2_tokens_path))
{
- fail_msg("make tmpdir using = template <%s> failed (error =3D %d)", softhsm2_tokens_path, errn= o);
+ fail_msg= ("make tmpdir using template <%s> failed (error =3D %d)", s= ofthsm2_tokens_path,
= + errno);
}
int fd =3D mkstemp(softhsm2_conf_path);
@@ -21= 1,8 +210,7 @@
{
fail_msg(&quo= t;make tmpfile using template <%s> failed (error =3D %d)", softh= sm2_conf_path, errno);
}
- snprintf(config, sizeof(config), "director= ies.tokendir=3D%s/",
- softhsm2_tokens_path);
+ snprintf(config, sizeof(config), "directories.= tokendir=3D%s/", softhsm2_tokens_path);
assert_in= t_equal(write(fd, config, strlen(config)), strlen(config));
close(fd);


@@ -260,14 +258,16 @@
argv_free(&a);
a =3D ar= gv_new();
/* Use numcerts+1 as a unique id of the = object -- same id for matching cert and key */
- argv_printf(&a, "%s --provider %= s --load-certificate %s --label \"%s\" --id %08x --login --write&= quot;,
- = P11TOOL_PATH, SOFTHSM2_MODULE_PATH, cert, c->friendly_name, num_cer= ts+1);
+ argv_= printf(
+ = &a, "%s --provider %s --load-certificate %s --label \"%s\&quo= t; --id %08x --login --write",
+ P11TOOL_PATH, SOFTHSM2_MODULE_PATH, cert, c->= ;friendly_name, num_certs + 1);
assert_true(openvp= n_execve_check(&a, es, 0, "Failed to upload certificate into token= "));

argv_free(&a);
a =3D argv_new();
- argv_printf(&a, "%s --provider %s --load= -privkey %s --label \"%s\" --id %08x --login --write",
- P11TOOL= _PATH, SOFTHSM2_MODULE_PATH, key, c->friendly_name, num_certs+1);=
+ argv_printf(&a= ,
+ = "%s --provider %s --load-privkey %s --label \"%s\" --id %0= 8x --login --write",
+ P11TOOL_PATH, SOFTHSM2_MODULE_PATH, key, c->fr= iendly_name, num_certs + 1);
assert_true(openvpn_e= xecve_check(&a, es, 0, "Failed to upload key into token"));

assert_int_equal(ftruncate(cert_f= d, 0), 0);
@@ -288,7 +288,7 @@
static int<= /span>
cleanup(void **state)
{
- (void) state;
+ (void)state;
str= uct argv a =3D argv_new();

argv_prin= tf(&a, "%s --delete-token --token \"%s\"", SOFTHSM2= _UTIL_PATH, token_name);
@@ -410,7 +410,7 @@
static void

test_tls_ctx_use_pkcs11(void **state)
{
- (voi= d) state;
+ (void)= state;
struct tls_root_ctx tls_ctx =3D {};
<= span> uint8_t sha1[HASHSIZE];

for (struct test_cer= t *c =3D certs; c->cert; c++)
@@ -451,7 +451,8 @@=
#else
if (!SSL_CTX_check_private_key(tl= s_ctx.ctx))
{
- fail_msg("Certificate and private key in = ssl_ctx do not match for <%s>", c->friendly_name);
= + fail_msg("Cer= tificate and private key in ssl_ctx do not match for <%s>",
+ c-&= gt;friendly_name);
return;
= }
#endif
@@ -472,10 +473,8 @@=
{
openvpn_unit_test_setup();
const struct CMUnitTest tests[] =3D {

- cmocka_unit_test_setup_teardown(test_pkcs11_= ids, setup_pkcs11,
- = teardown_pkcs11),
- cmocka_unit_test_setup_teardown(te= st_tls_ctx_use_pkcs11, setup_pkcs11,
- teardown_pkcs11),
+ cmocka_unit_te= st_setup_teardown(test_pkcs11_ids, setup_pkcs11, teardown_pkcs11),+ cmocka_unit_test_set= up_teardown(test_tls_ctx_use_pkcs11, setup_pkcs11, teardown_pkcs11),=
cmocka_unit_test_setup_teardown(test_tls_ctx_use_pkcs11_= _management, setup_pkcs11,
= teardown_pkcs11),
};
diff --g= it a/tests/unit_tests/openvpn/test_pkt.c b/tests/unit_tests/openvpn/test_pk= t.c
index 46206fe..3823d39 100644
--- a/tes= ts/unit_tests/openvpn/test_pkt.c
+++ b/tests/unit_tests/ope= nvpn/test_pkt.c
@@ -44,8 +44,8 @@
#include= "reliable.h"

int
-parse_line(const char *line, char = **p, const int n, const char *file,

- const int line_num, int msglevel, struct gc_arena = *gc)
+parse_line(cons= t char *line, char **p, const int n, const char *file, const int line_num,<= /span>
+ int msgle= vel, struct gc_arena *gc)
{
/* Dummy = function to get the linker happy, should never be called */
assert_true(false);

@@ -55,8 +55,7 @@
/* Define this function here as dummy since including the ssl_*.c files
* leads to having to include even more unrelated code */
bool
-k= ey_state_export_keying_material(struct tls_session *session,
- con= st char *label, size_t label_size,

+key_state_export_keying_material(struct tls_session *session= , const char *label, size_t label_size,
= void *ekm, size_t ekm_size)
{
ASSERT(0);

@@ -89,104 +88,73 @@
= "-----END OpenVPN Static key V1-----\n"
"</tls-auth>\n";<= /span>

-cons= t uint8_t client_reset_v2_none[] =3D
-{ 0x38, 0x68, 0x91, 0x92, 0x3f, 0xa3, 0x10, 0x34,- 0x37, 0x00, 0x00, 0x00, 0x00,= 0x00 };
+const uint8= _t client_reset_v2_none[] =3D { 0x38, 0x68, 0x91, 0x92, 0x3f, 0xa3, 0x10,
+ = 0x34, 0x37, 0x00, 0x00, 0x00, 0x00, 0x00 };
<= span>

-const uint8_t c= lient_reset_v2_tls_auth[] =3D
-{ 0x38, 0xde, 0x69, 0x4c, 0x5c, 0x7b, 0xfb, 0xa2,
- 0x74, 0x93, 0x53, 0x7c, 0x1d, 0xed, 0= x4e, 0x78,
- 0x15, 0x2= 9, 0xae, 0x7c, 0xfe, 0x4b, 0x8c, 0x6d,
- 0x6b, 0x2b, 0x51, 0xf0, 0x5a, 0x00, 0x00, 0x00,- 0x01, 0x61, 0xd3, 0xbf, 0x6c= , 0x00, 0x00, 0x00,
- = 0x00, 0x00};
+const u= int8_t client_reset_v2_tls_auth[] =3D { 0x38, 0xde, 0x69, 0x4c, 0x5c, 0x7b,= 0xfb, 0xa2, 0x74,
+ = 0x93, 0x53, 0x7c, 0x1d, 0xed, 0= x4e, 0x78, 0x15, 0x29,
+ 0xf0, 0x5a, 0x00, 0x00,= 0x00, 0x01, 0x61, 0xd3, 0xbf,
+ 0x6c, 0x00, 0x00, 0= x00, 0x00, 0x00 };

-const uint8_t client_reset_v2_tls_crypt[] =3D
-{0x38, 0xf4, 0x19, 0xcb, 0x12, 0xd1,= 0xf9, 0xe4,

- 0x8f, 0x= 00, 0x00, 0x00, 0x01, 0x61, 0xd3, 0xf8,
- 0xe1, 0x33, 0x02, 0x06, 0xf5, 0x68, 0x02, 0xbe,- 0x44, 0xfb, 0xed, 0x90, 0x50,= 0x64, 0xe3, 0xdb,
- 0x= 43, 0x41, 0x6b, 0xec, 0x5e, 0x52, 0x67, 0x19,
- 0x46, 0x2b, 0x7e, 0xb9, 0x0c, 0x96, 0xde, 0xfc,
- 0x9b, 0x05, 0xc4, 0x48,= 0x79, 0xf7};
+const = uint8_t client_reset_v2_tls_crypt[] =3D {
+ 0x38, 0xf4, 0x19, 0xcb, 0x12, 0xd1, 0xf9, 0xe4, 0= x8f, 0x00, 0x00, 0x00, 0x01, 0x61,
+ 0xd3, 0xf8, 0xe1, 0x33, 0x02, 0x06, 0xf5, 0x68, 0x02, 0x= be, 0x44, 0xfb, 0xed, 0x90,
+ 0x50, 0x64, 0xe3, 0xdb, 0x43, 0x41, 0x6b, 0xec, 0x5e, 0x52, 0x6= 7, 0x19, 0x46, 0x2b,
= + 0x7e, 0xb9, 0x0c, 0x96, 0xde, 0xfc, 0x9b, 0x05, 0xc4, 0x48, 0x79, 0xf7=
+};
=
/* Valid tls-auth client CONTROL_V1 packet with random s= erver id */
const uint8_t client_ack_tls_auth_randomid[] = =3D {
- 0x20, 0x14, = 0x01, 0x4e, 0xbc, 0x80, 0xc6, 0x14,
- 0x2b, 0x7b, 0xc8, 0x76, 0xfb, 0xc5, 0x2e, 0x27,- 0xb1, 0xc5, 0x07, 0x35, 0x5= b, 0xb6, 0x00, 0x6b,
- = 0xae, 0x71, 0xba, 0x4e, 0x38, 0x00, 0x00, 0x00,
- 0x03, 0x61, 0xd3, 0xff, 0x53, 0x00, 0x00, = 0x00,
- 0x00, 0x01, = 0x16, 0x03, 0x01, 0x01, 0x0c, 0x01,
- 0x00, 0x01, 0x08, 0x03, 0x03, 0x8c, 0xaa, 0xac,- 0x3a, 0x1a, 0x07, 0xbd, 0xe= 7, 0xb7, 0x50, 0x06,
- = 0x9b, 0x94, 0x0c, 0x34, 0x4b, 0x5a, 0x35, 0xca,
- 0xc4, 0x79, 0xbd, 0xc9, 0x09, 0xb0, 0x7b, = 0xd9,
- 0xee, 0xbb, = 0x7d, 0xe7, 0x25, 0x20, 0x39, 0x38,
- 0xe2, 0x18, 0x33, 0x36, 0x14, 0x9f, 0x34, 0xf0,- 0x44, 0x59, 0x96, 0x8d, 0x0= e, 0xd2, 0x47, 0x76,
- = 0x64, 0x88, 0x59, 0xe9, 0x38, 0x03, 0x97, 0x96,
- 0x98, 0x45, 0xfb, 0xf5, 0xff, 0x23, 0x00, = 0x32,
- 0x13, 0x02, = 0x13, 0x03, 0x13, 0x01, 0xc0, 0x2c,
- 0xc0, 0x30, 0x00, 0x9f, 0xcc, 0xa9, 0xcc, 0xa8,- 0xcc, 0xaa, 0xc0, 0x2b, 0xc= 0, 0x2f, 0x00, 0x9e,
- = 0xc0, 0x24, 0xc0, 0x28, 0x00, 0x6b, 0xc0, 0x23,
- 0xc0, 0x27, 0x00, 0x67, 0xc0, 0x0a, 0xc0, = 0x14,
- 0x00, 0x39, = 0xc0, 0x09, 0xc0, 0x13, 0x00, 0x33,
- 0x00, 0xff, 0x01, 0x00, 0x00, 0x8d, 0x00, 0x0b,- 0x00, 0x04, 0x03, 0x00, 0x0= 1, 0x02, 0x00, 0x0a,
- = 0x00, 0x0c, 0x00, 0x0a, 0x00, 0x1d, 0x00, 0x17,
- 0x00, 0x1e, 0x00, 0x19, 0x00, 0x18, 0x00, = 0x16,
- 0x00, 0x00, = 0x00, 0x17, 0x00, 0x00, 0x00, 0x0d,
- 0x00, 0x30, 0x00, 0x2e, 0x04, 0x03, 0x05, 0x03,- 0x06, 0x03, 0x08, 0x07, 0x0= 8, 0x08, 0x08, 0x09,
- = 0x08, 0x0a, 0x08, 0x0b, 0x08, 0x04, 0x08, 0x05,
- 0x08, 0x06, 0x04, 0x01, 0x05, 0x01, 0x06, = 0x01,
- 0x03, 0x03, = 0x02, 0x03, 0x03, 0x01, 0x02, 0x01,
- 0x03, 0x02, 0x02, 0x02, 0x04, 0x02, 0x05, 0x02,- 0x06, 0x02, 0x00, 0x2b, 0x0= 0, 0x05, 0x04, 0x03,
- = 0x04, 0x03, 0x03, 0x00, 0x2d, 0x00, 0x02, 0x01,
- 0x01, 0x00, 0x33, 0x00, 0x26, 0x00, 0x24, = 0x00,
- 0x1d, 0x00, = 0x20, 0x0e, 0xc9, 0x7a, 0xff, 0x58,
- 0xdb, 0x56, 0xf6, 0x40, 0xd1, 0xed, 0xdb, 0x91,- 0x81, 0xd6, 0xef, 0x83, 0x8= 6, 0x8a, 0xb2, 0x3d,
- = 0x88, 0x92, 0x3f, 0xd8, 0x51, 0x9c, 0xd6, 0x26,
- 0x56, 0x33, 0x6b
+ 0x20, 0x14, 0x01, 0x4e, 0xbc, 0x80, 0xc6,= 0x14, 0x2b, 0x7b, 0xc8, 0x76, 0xfb, 0xc5, 0x2e, 0x27,
+ 0xb1, 0xc5, 0x07, 0x35, 0x5b, 0xb6, = 0x00, 0x6b, 0xae, 0x71, 0xba, 0x4e, 0x38, 0x00, 0x00, 0x00,
+ 0x03, 0x61, 0xd3, 0xff, 0x53, 0= x00, 0x00, 0x00, 0x00, 0x01, 0x16, 0x03, 0x01, 0x01, 0x0c, 0x01,

= + 0x00, 0x01, 0x08, 0x03, 0x= 03, 0x8c, 0xaa, 0xac, 0x3a, 0x1a, 0x07, 0xbd, 0xe7, 0xb7, 0x50, 0x06,
+ 0x9b, 0x94, 0x0c, 0x3= 4, 0x4b, 0x5a, 0x35, 0xca, 0xc4, 0x79, 0xbd, 0xc9, 0x09, 0xb0, 0x7b, 0xd9,<= /span>
+ 0xee, 0xbb, 0x7d= , 0xe7, 0x25, 0x20, 0x39, 0x38, 0xe2, 0x18, 0x33, 0x36, 0x14, 0x9f, 0x34, 0= xf0,
+ 0x44, 0x59,= 0x96, 0x8d, 0x0e, 0xd2, 0x47, 0x76, 0x64, 0x88, 0x59, 0xe9, 0x38, 0x03, 0x= 97, 0x96,
+ 0x98, = 0x45, 0xfb, 0xf5, 0xff, 0x23, 0x00, 0x32, 0x13, 0x02, 0x13, 0x03, 0x13, 0x0= 1, 0xc0, 0x2c,
+ 0= xc0, 0x30, 0x00, 0x9f, 0xcc, 0xa9, 0xcc, 0xa8, 0xcc, 0xaa, 0xc0, 0x2b, 0xc0= , 0x2f, 0x00, 0x9e,
+= 0xc0, 0x24, 0xc0, 0x28, 0x00, 0x6b, 0xc0, 0x23, 0xc0, 0x27, 0x00, 0x67,= 0xc0, 0x0a, 0xc0, 0x14,
+ 0x00, 0x39, 0xc0, 0x09, 0xc0, 0x13, 0x00, 0x33, 0x00, 0xff, 0x01, = 0x00, 0x00, 0x8d, 0x00, 0x0b,
+ 0x00, 0x04, 0x03, 0x00, 0x01, 0x02, 0x00, 0x0a, 0x00, 0x0c, 0= x00, 0x0a, 0x00, 0x1d, 0x00, 0x17,
+ 0x00, 0x1e, 0x00, 0x19, 0x00, 0x18, 0x00, 0x16, 0x00, 0x= 00, 0x00, 0x17, 0x00, 0x00, 0x00, 0x0d,
+ 0x00, 0x30, 0x00, 0x2e, 0x04, 0x03, 0x05, 0x03, 0x0= 6, 0x03, 0x08, 0x07, 0x08, 0x08, 0x08, 0x09,
+ 0x08, 0x0a, 0x08, 0x0b, 0x08, 0x04, 0x08, 0x05= , 0x08, 0x06, 0x04, 0x01, 0x05, 0x01, 0x06, 0x01,
+ 0x03, 0x03, 0x02, 0x03, 0x03, 0x01, 0x02,= 0x01, 0x03, 0x02, 0x02, 0x02, 0x04, 0x02, 0x05, 0x02,
+ 0x06, 0x02, 0x00, 0x2b, 0x00, 0x05, = 0x04, 0x03, 0x04, 0x03, 0x03, 0x00, 0x2d, 0x00, 0x02, 0x01,
+ 0x01, 0x00, 0x33, 0x00, 0x26, 0= x00, 0x24, 0x00, 0x1d, 0x00, 0x20, 0x0e, 0xc9, 0x7a, 0xff, 0x58,

= + 0xdb, 0x56, 0xf6, 0x40, 0x= d1, 0xed, 0xdb, 0x91, 0x81, 0xd6, 0xef, 0x83, 0x86, 0x8a, 0xb2, 0x3d,
+ 0x88, 0x92, 0x3f, 0xd= 8, 0x51, 0x9c, 0xd6, 0x26, 0x56, 0x33, 0x6b
};
<= span>

/* This is a truncated packet as we do not care for= the TLS payload in the
* unit test */
-const uint8_t client_control_with_ack[] = =3D {
- 0x20, 0x78, = 0x19, 0xbf, 0x2e, 0xbc, 0xd1, 0x9a,
- 0x45, 0x01, 0x00, 0x00, 0x00, 0x00, 0xea,
- 0xfe, 0xbf, 0xa4, 0x41, 0x8a, 0xe= 3, 0x1b,

- 0x00, 0x0= 0, 0x00, 0x01, 0x16, 0x03, 0x01
-};
+const u= int8_t client_control_with_ack[] =3D { 0x20, 0x78, 0x19, 0xbf, 0x2e, 0xbc, = 0xd1, 0x9a,
+ = 0x45, 0x01, 0x00, 0x00, 0x00, 0x00, 0xe= a, 0xfe,
+ = 0xbf, 0xa4, 0x41, 0x8a, 0xe3, 0x1b, 0x00, = 0x00,
+ = 0x00, 0x01, 0x16, 0x03, 0x01 };

-const uint8_t cli= ent_ack_none_random_id[] =3D {
- 0x28, 0xae, 0xb9, 0xaf, 0xe1, 0xf0, 0x1d, 0x79,
- 0xc8, 0x01, 0x00, 0x00, 0x00, 0x= 00, 0xdd,

- 0x85, 0x= db, 0x53, 0x56, 0x23, 0xb0, 0x2e
-};
+const = uint8_t client_ack_none_random_id[] =3D { 0x28, 0xae, 0xb9, 0xaf, 0xe1, 0xf= 0, 0x1d, 0x79,
+ = 0xc8, 0x01, 0x00, 0x00, 0x00, 0x00= , 0xdd, 0x85,
+ = 0xdb, 0x53, 0x56, 0x23, 0xb0, 0x2e = };

struct tls_auth_standalone
= init_tas_auth(int key_direction)
{
= struct tls_auth_standalone tas =3D { 0 };
- struct frame frame =3D { {.headroom =3D 200, .= payload_size =3D 1400}, 0};
+ struct frame frame =3D { { .headroom =3D 200, .payload_size =3D= 1400 }, 0 };
tas.frame =3D frame;

tas.tls_wrap.mode =3D TLS_WRAP_AUTH;
= /* we ignore packet ids on for the first packet check */
- tas.tls_wrap.opt.flags |=3D (CO_I= GNORE_PACKET_ID|CO_PACKET_ID_LONG_FORM);

+ tas.tls_wrap.opt.flags |=3D (CO_IGNORE_PACKET_ID |= CO_PACKET_ID_LONG_FORM);

struct key= _type tls_crypt_kt;
init_key_type(&tls_crypt_kt, &= quot;none", "SHA1", true, false);
- crypto_read_openvpn_key(&a= mp;tls_crypt_kt, &tas.tls_wrap.opt.key_ctx_bi,
- static_key, true, = key_direction,
- = "Control Channel Authentication", "tls-= auth",
- = NULL);
+ crypto_read_openvpn_key(&tls_crypt_kt, &tas.tls_wrap.opt.k= ey_ctx_bi, static_key, true,
+ key_direction, "Control Channel A= uthentication", "tls-auth", NULL);
tas.= workbuf =3D alloc_buf(1600);

return = tas;
@@ -197,11 +165,10 @@
{
struct tls_auth_standalone tas =3D { 0 };

tas.= tls_wrap.mode =3D TLS_WRAP_CRYPT;
- tas.tls_wrap.opt.flags |=3D (CO_IGNORE_PACKET_ID|CO_PACKET_= ID_LONG_FORM);
+ t= as.tls_wrap.opt.flags |=3D (CO_IGNORE_PACKET_ID | CO_PACKET_ID_LONG_FORM);<= /span>

- = tls_crypt_init_key(&tas.tls_wrap.opt.key_ctx_bi,
- &tas.tls_wrap.or= iginal_wrap_keydata, static_key,
- true, server);
+ tls_crypt_init_key(&tas.tls_wrap.opt.k= ey_ctx_bi, &tas.tls_wrap.original_wrap_keydata,
+ static_key, true, = server);
tas.workbuf =3D alloc_buf(1600);
tas.tls_wrap.work =3D alloc_buf(1600);

@@ -248,7 +215,7 @@
free_tls_pre_decrypt_state(= &state);

/* flip a byte in vario= us places */
- for (= int i =3D 0; i<sizeof(client_reset_v2_tls_crypt); i++)
+ for (int i =3D 0; i < sizeof(c= lient_reset_v2_tls_crypt); i++)
{
= buf_reset_len(&buf);
buf_write(&buf, = client_reset_v2_tls_crypt, sizeof(client_reset_v2_tls_crypt));
@@ -391,7 +358,7 @@

assert_int_equal(ack.len, 1);<= /span>
assert_int_equal(ack.packet_id[0], 0);

- struct session_= id expected_id =3D { .id =3D {0xea, 0xfe, 0xbf, 0xa4, 0x41, 0x8a, 0xe3, 0x1= b }};
+ struct ses= sion_id expected_id =3D { .id =3D { 0xea, 0xfe, 0xbf, 0xa4, 0x41, 0x8a, 0xe= 3, 0x1b } };
assert_memory_equal(&sid, &expect= ed_id, SID_SIZE);

buf_reset_len(&= ;buf);
@@ -405,7 +372,7 @@
assert_int_= equal(ack.len, 1);
assert_int_equal(ack.packet_id[0], = 0);

-= struct session_id expected_id2 =3D { .id =3D {0xdd, 0x85, 0xdb, 0x53, 0= x56, 0x23, 0xb0, 0x2e }};
+ struct session_id expected_id2 =3D { .id =3D { 0xdd, 0x85, 0xdb, = 0x53, 0x56, 0x23, 0xb0, 0x2e } };
assert_memory_equal(= &sid, &expected_id2, SID_SIZE);

= buf_reset_len(&buf);
@@ -484,7 +451,7 @@
= ASSERT(md_valid("SHA256"));
hmac_= ctx_t *hmac_ctx =3D hmac_ctx_new();

- uint8_t key[SHA256_DIGEST_LENGTH] =3D {= 1, 2, 3, 0};
+ uin= t8_t key[SHA256_DIGEST_LENGTH] =3D { 1, 2, 3, 0 };
=
hmac_ctx_init(hmac_ctx, key, "SHA256");
= return hmac_ctx;
@@ -502,28 +469,30 @@ addr.addr.in4.sin_addr.s_addr =3D ntohl(0xff000ff);
<= span> addr.addr.in4.sin_port =3D ntohs(1195);

<= br>- struct session_id client_= id =3D { {0, 1, 2, 3, 4, 5, 6, 7}};
+ struct session_id client_id =3D { { 0, 1, 2, 3, 4, 5, 6= , 7 } };

now =3D 1005;
struct session_id server_id =3D calculate_session_id_hmac(client_id= , &addr, hmac, handwindow, 0);



- struct session_id expe= cted_server_id =3D {{0x84, 0x73, 0x52, 0x2b, 0x5b, 0xa9, 0x2a, 0x70}};
+ struct session_id ex= pected_server_id =3D { { 0x84, 0x73, 0x52, 0x2b, 0x5b, 0xa9, 0x2a, 0x70 } }= ;
/* We have to deal with different structs here annoy= ingly */
/* Linux has an unsigned short int as family_= t and this is field is always
* stored in host endian= ness even though the rest of the struct isn't...,
= * so Linux little endian differs from all BSD and Linux big endian */
- if (sizeof(addr.addr.i= n4.sin_family) =3D=3D sizeof(unsigned short int)
- && ntohs(AF_INET) !=3D AF_INET)<= /span>
+ if (sizeof(addr.= addr.in4.sin_family) =3D=3D sizeof(unsigned short int) && ntohs(AF_= INET) !=3D AF_INET)
{
- struct session_id linuxle =3D {{0x8b, 0xeb, 0x= 3d, 0x20, 0x14, 0x53, 0xbe, 0x0a }};
+ struct session_id linuxle =3D { { 0x8b, 0xeb, 0x3d= , 0x20, 0x14, 0x53, 0xbe, 0x0a } };
expected_serve= r_id =3D linuxle;
}
assert_memory= _equal(expected_server_id.id, server_id.id, SID_SIZE);

- struct session_id se= rver_id_m1 =3D calculate_session_id_hmac(client_id, &addr, hmac, handwi= ndow, -1);
- struct = session_id server_id_p1 =3D calculate_session_id_hmac(client_id, &addr,= hmac, handwindow, 1);
= - struct session_id server_id_p2 =3D calculate_session_id_hmac(client_id= , &addr, hmac, handwindow, 2);
+ struct session_id server_id_m1 =3D
+ calculate_session_id_hmac(client_= id, &addr, hmac, handwindow, -1);
+ struct session_id server_id_p1 =3D
+ calculate_session_id_hmac(clie= nt_id, &addr, hmac, handwindow, 1);
+ struct session_id server_id_p2 =3D
+ calculate_session_id_hmac(cl= ient_id, &addr, hmac, handwindow, 2);

assert_memory_not_equal(expected_server_id.id, server_id_m1.id, SID_S= IZE);

assert_memory_not_equal(expected_server_id.id, s= erver_id_p1.id, SID_SIZE);
@@ -532,10 +501,13 @@
= * and shifts the ids by one */
now =3D 106= 2;

- = struct session_id server_id2_m2 =3D calculate_session_id_hmac(client_id,= &addr, hmac, handwindow, -2);
- struct session_id server_id2_m1 =3D calculate_session_id_h= mac(client_id, &addr, hmac, handwindow, -1);
+ struct session_id server_id2_m2 =3D=
+ calculate_session_= id_hmac(client_id, &addr, hmac, handwindow, -2);
+ struct session_id server_id2_m1 =3D
+ calculate_ses= sion_id_hmac(client_id, &addr, hmac, handwindow, -1);
= struct session_id server_id2 =3D calculate_session_id_hmac(client_id, &= amp;addr, hmac, handwindow, 0);
- struct session_id server_id2_p1 =3D calculate_session_id_hmac= (client_id, &addr, hmac, handwindow, 1);
+ struct session_id server_id2_p1 =3D
= + calculate_session_id_h= mac(client_id, &addr, hmac, handwindow, 1);
assert_memory_equal(server_id2_m2.id, server_id_m1.id, SID_SIZE= );
assert_memory_equal(server_id2_m1.id, expected_serv= er_id.id, SID_SIZE);
@@ -553,19 +525,20 @@
= struct tls_auth_standalone tas =3D { 0 };
struct = tls_pre_decrypt_state state =3D { 0 };

- struct session_id client_id =3D {{0,= 1, 2, 3, 4, 5, 6, 7}};
- struct session_id server_id =3D {{8, 9, 0, 9, 8, 7, 6, 2}};+ struct session_id client_= id =3D { { 0, 1, 2, 3, 4, 5, 6, 7 } };
+ struct session_id server_id =3D { { 8, 9, 0, 9, 8, 7= , 6, 2 } };

enum first_packet_verdic= t verdict;

tas.tls_wrap.mode =3D TLS= _WRAP_NONE;
- struct= frame frame =3D { {.headroom =3D 200, .payload_size =3D 1400}, 0};<= br>+ struct frame frame =3D = { { .headroom =3D 200, .payload_size =3D 1400 }, 0 };
= tas.frame =3D frame;
tas.workbuf =3D alloc_buf(1600);<= /span>

uint8_t header =3D 0 | (P_CONTROL_HA= RD_RESET_CLIENT_V2 << P_OPCODE_SHIFT);

- struct buffer buf =3D tls_rese= t_standalone(&tas.tls_wrap, &tas, &client_id, &server_id, h= eader, false);

+ s= truct buffer buf =3D
= + tls_reset_standalone(&tas.tls_wrap, &tas, &client_id, = &server_id, header, false);

<= br> verdict =3D tls_pre_decrypt_lite(&tas, &state, &f= rom, &buf);
@@ -573,7 +546,8 @@

/* Assure repeated generation of reset is deterministic/sta= teless*/
assert_memory_equal(state.peer_session_id.id,= client_id.id, SID_SIZE);
- struct buffer buf2 =3D tls_reset_standalone(&tas.tls_wrap, &= ;tas, &client_id, &server_id, header, false);
+ struct buffer buf2 =3D
+ tls_reset_standalone(&= tas.tls_wrap, &tas, &client_id, &server_id, header, false);
assert_int_equal(BLEN(&buf), BLEN(&buf2));=
assert_memory_equal(BPTR(&buf), BPTR(&buf2), BLEN(&a= mp;buf));

@@ -592,14 +566,15 @@
packet_id_init(&tas_client.tls_wrap.opt.p= acket_id, 5, 5, "UNITTEST", 0);

- struct session_id client_id =3D {= {0xab, 1, 2, 3, 4, 5, 6, 0xcd}};

- struct session_id server_id =3D {{8, 9, 0xa, 0xc, 8, 7, 6, 2= }};
+ struct sessi= on_id client_id =3D { { 0xab, 1, 2, 3, 4, 5, 6, 0xcd } };
+ struct session_id server_id =3D {= { 8, 9, 0xa, 0xc, 8, 7, 6, 2 } };

u= int8_t header =3D 0 | (P_CONTROL_HARD_RESET_CLIENT_V2 << P_OPCODE_SHI= FT);

now =3D 0x22446688;
<= span> reset_packet_id_send(&tas_client.tls_wrap.opt.packet_id.send)= ;

- struct buffer bu= f =3D tls_reset_standalone(&tas_client.tls_wrap, &tas_client, &= client_id, &server_id, header, false);
+ struct buffer buf =3D tls_reset_standalone(&= tas_client.tls_wrap, &tas_client, &client_id,
+ = &server_id, header, false);

= enum first_packet_verdict verdict =3D tls_pre_decrypt_lite(&tas_server,= &state, &from, &buf);
assert_int_equal(ve= rdict, VERDICT_VALID_RESET_V2);
@@ -608,7 +583,8 @@<= br>
/* Assure repeated generation of reset is d= eterministic/stateless*/
reset_packet_id_send(&tas= _client.tls_wrap.opt.packet_id.send);
- struct buffer buf2 =3D tls_reset_standalone(&tas_cl= ient.tls_wrap, &tas_client, &client_id, &server_id, header, fal= se);
+ struct buff= er buf2 =3D tls_reset_standalone(&tas_client.tls_wrap, &tas_client,= &client_id,
+ = &server_id, header, false);<= /span>
assert_int_equal(BLEN(&buf), BLEN(&buf2));
assert_memory_equal(BPTR(&buf), BPTR(&buf2), BLEN= (&buf));

@@ -644,7 +620,7 @@ assert_string_equal(BSTR(&cmd4), "valid one again&quo= t;);
assert_int_equal(cmd5.len, 0);
<= /span>
- const uint8_t nonu= ll[6] =3D { 'n', 'o', ' ', 'N', 'U'= , 'L'};
+ = const uint8_t nonull[6] =3D { 'n', 'o', ' ', 'N= ', 'U', 'L' };
struct buffer nonul= l_buf =3D alloc_buf_gc(1024, &gc);

= buf_write(&nonull_buf, nonull, sizeof(nonull));
@@ -= 658,18 +634,16 @@
main(void)
{
= openvpn_unit_test_setup();
- const struct CMUnitTest tests[] =3D {
- cmocka_unit_test(test_tls_decry= pt_lite_none),
- = cmocka_unit_test(test_tls_decrypt_lite_auth),
- cmocka_unit_test(test_tls_decrypt_lite_cry= pt),
- cmocka_un= it_test(test_parse_ack),
- cmocka_unit_test(test_veri= fy_hmac_none),
- = cmocka_unit_test(test_verify_hmac_tls_auth),
- cmocka_unit_test(test_generate_reset_packet= _plain),
- cmock= a_unit_test(test_generate_reset_packet_tls_auth),
- cmocka_unit_test(test_extract_control_m= essage)
- };<= br>+ const struct CMUnitTest= tests[] =3D { cmocka_unit_test(test_tls_decrypt_lite_none),
+ = cmocka_unit_test(test_tls_decrypt_lite_auth),

+ c= mocka_unit_test(test_tls_decrypt_lite_crypt),
+ cmocka_un= it_test(test_parse_ack),
+ cmocka_unit_test(test_calc_ses= sion_id_hmac_static),
+ cmocka_unit_test(test_verify_hmac= _none),
+ = cmocka_unit_test(test_verify_hmac_tls_auth),
+ = cmocka_unit_test(test_generate_reset_packet_plain),
+ = cmocka_unit_test(test_generate_reset_packet_tls_auth),
+ = cmocka_unit_test(test_extract_control_message) };
=
#if defined(ENABLE_CRYPTO_OPENSSL)
OpenSSL_add_all_algorithms();

diff --git a/tests/unit= _tests/openvpn/test_provider.c b/tests/unit_tests/openvpn/test_provider.c
index a8aea0c..463b394 100644
--- a/tests/un= it_tests/openvpn/test_provider.c
+++ b/tests/unit_tests/ope= nvpn/test_provider.c
@@ -45,7 +45,7 @@
sta= tic int mgmt_callback_called;

#ifndef _c= ountof
-#define _counto= f(x) sizeof((x))/sizeof(*(x))
+#define _countof(x) sizeof((x)) / sizeof(*(x))
#= endif

static OSSL_PROVIDER *prov[2];
@@ -70,7 +70,7 @@
= "MCowBQYDK2VwAyEA+q5xjF5hGyyqYZidJdz/0saEQabL3N4wIZJBxNGbgJE=3D\n&q= uot;
"-----END PUBLIC K= EY-----";

-static const char *pubkeys[] =3D {pubkey1, pubkey2, pubkey3};
+static const char *pub= keys[] =3D { pubkey1, pubkey2, pubkey3 };

static const char *prov_name =3D "ovpn.xkey";

=
@@ -84,11 +84,10 @@
"bG9yZSBtYWd= uYSBhbGlxdWEu";

/* Sha256 digest of= test_msg excluding NUL terminator */
-static const uint8_t test_digest[] =3D {
- 0x77, 0x38, 0x65, 0x00, 0x1e, 0x96, = 0x48, 0xc6, 0x57, 0x0b, 0xae,
- 0xc0, 0xb7, 0x96, 0xf9, 0x66, 0x4d, 0x5f, 0xd0, 0xb7, 0xdb, 0xf= 3,
- 0x3a, 0xbf, 0x0= 2, 0xcc, 0x78, 0x61, 0x83, 0x20, 0x20, 0xee
-};
+static const uint8_t test_digest[] =3D { 0x77, 0x38, 0x65, 0x00, 0x1e,= 0x96, 0x48, 0xc6,
+ = 0x57, 0x0b, 0xae, 0xc0, 0xb7, 0x96, 0= xf9, 0x66,
+ = 0x4d, 0x5f, 0xd0, 0xb7, 0xdb, 0xf3, 0x3a, 0xb= f,
+ = 0x02, 0xcc, 0x78, 0x61, 0x83, 0x20, 0x20, 0xee };

static const char *test_digest_b64 =3D &quo= t;dzhlAB6WSMZXC67At5b5Zk1f0Lfb8zq/Asx4YYMgIO4=3D";

@@ -97,10 +96,9 @@
* --- the smallest size= of the actual signature with the above
* keys. */
-static con= st uint8_t good_sig[] =3D {
- 0xd8, 0xa7, 0xd9, 0x81, 0xd8, 0xaa, 0xd8, 0xad, 0x20, 0xd9, 0x8a,= 0xd8,
- 0xa7, 0x20,= 0xd8, 0xb3, 0xd9, 0x85, 0xd8, 0xb3, 0xd9, 0x85, 0x0
-};
+static const uint8_t good_sig[] =3D { 0xd8, 0xa7, 0xd9, 0x81= , 0xd8, 0xaa, 0xd8, 0xad,
+ 0x20, 0xd9, 0x8a, 0xd8, 0xa7, 0x2= 0, 0xd8, 0xb3,
+ = 0xd9, 0x85, 0xd8, 0xb3, 0xd9, 0x85, 0x0 };

static const char *good_sig_b64 =3D "= ;2KfZgdiq2K0g2YrYpyDYs9mF2LPZhQA=3D";

@@ -153,8 +151,7 @@

* the management client.
= */
char *
-management_query_pk_sig(struct management *man, const char *b6= 4_data,
- = const char *algorithm)
+management_query_pk_sig(struct management *man, const char *b6= 4_data, const char *algorithm)
{
char= *out =3D NULL;

@@ -195,7 +192,7 @@
{
assert_true(OSSL_PROVIDER_available(NULL= , prov_name));

- const char *algs[] =3D {"RSA", "ECDSA"};=
+ const char *alg= s[] =3D { "RSA", "ECDSA" };
for (size_t i =3D 0; i < _countof(algs); i++)
{

@@ -206,7 +203,7 @@
EVP_S= IGNATURE_free(sig);
}

- const char *names[] =3D {"R= SA", "EC"};

+ const char *names[] =3D { "RSA", "EC" };

for (size_t i =3D 0; i < _countof(na= mes); i++)
{
@@ -225,7 +222,7 @@
uint8_t *sig =3D NULL;
size_t siglen = =3D 0;

+ OSSL_PARAM params[6] =3D { OSSL_PARAM_END= };

const char *mdname =3D "SHA= 256";
const char *padmode =3D "pss";
@@ -233,11 +230,15 @@

= if (EVP_PKEY_get_id(pkey) =3D=3D EVP_PKEY_RSA)
{
- params[0] =3D OSSL_= PARAM_construct_utf8_string(OSSL_SIGNATURE_PARAM_DIGEST, (char *)mdname, 0)= ;
- params[1] = =3D OSSL_PARAM_construct_utf8_string(OSSL_SIGNATURE_PARAM_PAD_MODE, (char *= )padmode, 0);
- = params[2] =3D OSSL_PARAM_construct_utf8_string(OSSL_SIGNATURE_PARAM_PSS_SAL= TLEN, (char *)saltlen, 0);
+ params[0] =3D
+ OSSL_PARAM_construct_utf8_string(OSSL_SIGNATURE_PARAM_= DIGEST, (char *)mdname, 0);
+ params[1] =3D
+ OSSL_PARAM_construct_utf8_string(OSSL_SIGNATURE_PARAM= _PAD_MODE, (char *)padmode, 0);
+ params[2] =3D
+ OSSL_PARAM_construct_utf8_string(OSSL_SIGNATURE_P= ARAM_PSS_SALTLEN, (char *)saltlen, 0);
/* same dig= est for mgf1 */
- = params[3] =3D OSSL_PARAM_construct_utf8_string(OSSL_SIGNATURE_PARAM_MGF1_= DIGEST, (char *)saltlen, 0);
+ params[3] =3D
+ OSSL_PARAM_construct_utf8_string(OSSL_SIGNATURE_PARA= M_MGF1_DIGEST, (char *)saltlen, 0);
params[4] =3D = OSSL_PARAM_construct_end();
}
els= e if (EVP_PKEY_get_id(pkey) =3D=3D EVP_PKEY_ED25519)
@@ -25= 0,8 +251,7 @@
EVP_PKEY_CTX *pctx =3D NULL;
<= span> EVP_MD_CTX *mctx =3D EVP_MD_CTX_new();

- if (!mctx
- || EVP_DigestSignInit_ex(mctx,= &pctx, mdname, NULL, NULL, pkey, params) <=3D 0)
+ if (!mctx || EVP_DigestSignInit_e= x(mctx, &pctx, mdname, NULL, NULL, pkey, params) <=3D 0)
<= span> {

fail_msg("Failed to initialize EV= P_DigestSignInit_ex()");
goto done;@@ -291,7 +291,7 @@
EVP_PKEY *privkey =3D x= key_load_management_key(NULL, pubkey);
assert_true= (privkey !=3D NULL);

- management->settings.flags =3D MF_EXTERNAL_KEY|= MF_EXTERNAL_KEY_PSSPAD;
+ management->settings.flags =3D MF_EXTERNAL_KEY | MF_EXTERNAL= _KEY_PSSPAD;

/* first without di= gest support in management client */
again:
@@ -328,8 +328,8 @@

}

= static int
-xkey_sign(= void *handle, unsigned char *sig, size_t *siglen,
- const unsigned char *tbs, size_t tbsl= en, XKEY_SIGALG s)
+x= key_sign(void *handle, unsigned char *sig, size_t *siglen, const unsigned c= har *tbs, size_t tbslen,
+ XKEY_SIGALG s)
{
if (!= sig)
{
@@ -386,7 +386,8 @@
<= span> pubkey =3D load_pubkey(pubkeys[i]);

= assert_true(pubkey !=3D NULL);

- EVP_PKEY *privkey =3D xkey_load_generic_= key(NULL, (void *)dummy, pubkey, xkey_sign, xkey_free);
+ EVP_PKEY *privkey =3D+ xkey_load_generic= _key(NULL, (void *)dummy, pubkey, xkey_sign, xkey_free);
= assert_true(privkey !=3D NULL);

= xkey_sign_called =3D 0;
diff --git a/tests/unit_test= s/openvpn/test_push_update_msg.c b/tests/unit_tests/openvpn/test_push_updat= e_msg.c
index d47286a..0f4ad41 100644
--- a= /tests/unit_tests/openvpn/test_push_update_msg.c
+++ b/test= s/unit_tests/openvpn/test_push_update_msg.c
@@ -14,36 +14,1= 7 @@
unsigned int
pull_permission_mask(co= nst struct context *c)
{
- unsigned int flags =3D
- OPT_P_UP
- | OPT_P_ROUTE_EXTRAS
- | OPT_P_SOCKBUF
- | OPT_P_SOCKFLAGS
- | OPT_P_SETENV
- | OPT_P_SHAPER
- | OPT_P_TIMER
- | OPT_P_COMP
- | OPT_P_PERSIST
- | OPT_P_MESSAGES
- | OPT_P_EXPLICIT_NOTIFY
- | OPT_P_ECHO
- | OPT_P_PULL_MODE
- | OPT_P_PEER_ID=
- | OPT_P_NCP
- | OPT_P_PUSH_MT= U
- | OPT_P_ROUT= E
- | OPT_P_DHCP= DNS;
+ unsigned in= t flags =3D OPT_P_UP | OPT_P_ROUTE_EXTRAS | OPT_P_SOCKBUF | OPT_P_SOCKFLAGS=
+ = | OPT_P_SETENV | OPT_P_SHAPER | OPT_P_TIMER | OPT_P_COMP | OPT_P_PERS= IST
+ = | OPT_P_MESSAGES | OPT_P_EXPLICIT_NOTIFY | OPT_P_ECHO | OPT_P_PULL= _MODE
+ = | OPT_P_PEER_ID | OPT_P_NCP | OPT_P_PUSH_MTU | OPT_P_ROUTE | OPT= _P_DHCPDNS;
return flags;
}
bool
-apply_push_options(struct context *c,
- struct options *options,=
- struct bu= ffer *buf,
- = unsigned int permission_mask,
- unsigned int *option_types_found,=
- struct en= v_set *es,
- = bool is_update)
+apply_push_options(struct context *c, struct options *options, struct b= uffer *buf,
+ = unsigned int permission_mask, unsigned int *option_types_found,<= /span>
+ s= truct env_set *es, bool is_update)
{
= char line[OPTION_PARM_SIZE];

@@ -80,10 +6= 1,8 @@
}

int
= -process_incoming_push_msg(struct= context *c,
- = const struct buffer *buffer,
- bool honor_received_optio= ns,
- = unsigned int permission_mask,
+process_incoming_push_msg(struct context *c, const struct= buffer *buffer,
+ = bool honor_received_options, unsigned int permission= _mask,
unsigned int *option_type= s_found)
{
struct buffer buf =3D *buf= fer;
@@ -92,16 +71,13 @@
{
<= span> return PUSH_MSG_REQUEST;

}
- else if (honor_received_options=

- &&am= p; buf_string_compare_advance(&buf, push_reply_cmd))
+ else if (honor_received_options &a= mp;& buf_string_compare_advance(&buf, push_reply_cmd))
{

return PUSH_MSG_REPLY;
= }
- else if (ho= nor_received_options
- = && buf_string_compare_advance(&buf, push_update_cmd= ))
+ else if (hono= r_received_options && buf_string_compare_advance(&buf, push_upd= ate_cmd))
{
- return process_incoming_push_update(c, permission_mask,<= /span>
- = option_types_found, &buf);
+ return process_incoming_push_upda= te(c, permission_mask, option_types_found, &buf);
= }
else
{
@@ -116,= 11 +92,14 @@
{
struct context *c =3D = *state;
struct buffer buf =3D alloc_buf(256);- const char *update_msg =3D= "PUSH_UPDATE,dhcp-option DNS 8.8.8.8, route 0.0.0.0 0.0.0.0 10.10.10.= 1";
+ const c= har *update_msg =3D
+= "PUSH_UPDATE,dhcp-option DNS 8.8.8.8, route 0.0.0.0 0.0.0.0 10= .10.10.1";
buf_write(&buf, update_msg, strlen= (update_msg));
unsigned int option_types_found =3D 0;<= /span>

- = assert_int_equal(process_incoming_push_msg(c, &buf, c->options.pull,= pull_permission_mask(c), &option_types_found), PUSH_MSG_UPDATE);
+ assert_int_equal(proc= ess_incoming_push_msg(c, &buf, c->options.pull, pull_permission_mask= (c),
+ = &option_types_found),
+ PUSH_MSG_UPDATE)= ;

free_buf(&buf);
}

@@ -134,7 +113,9 @@
buf_write(&am= p;buf, update_msg, strlen(update_msg));
unsigned int o= ption_types_found =3D 0;

- assert_int_equal(process_incoming_push_msg(c, &= ;buf, c->options.pull, pull_permission_mask(c), &option_types_found)= , PUSH_MSG_ERROR);
+ = assert_int_equal(process_incoming_push_msg(c, &buf, c->options.pu= ll, pull_permission_mask(c),
+ &option_types_f= ound),
+ = PUSH_MSG_ERROR);

free_buf(&a= mp;buf);
}
@@ -149,7 +130,9 @@
<= span> buf_write(&buf, update_msg, strlen(update_msg));

unsigned int option_types_found =3D 0;

- assert_int_equal(process_in= coming_push_msg(c, &buf, c->options.pull, pull_permission_mask(c), &= amp;option_types_found), PUSH_MSG_ERROR);
+ assert_int_equal(process_incoming_push_msg(c, &am= p;buf, c->options.pull, pull_permission_mask(c),
+ = &option_types_found),
+ PUSH_MSG_ERROR);
<= br> free_buf(&buf);
}
@@ -16= 3,7 +146,9 @@
buf_write(&buf, update_msg, strlen(u= pdate_msg));
unsigned int option_types_found =3D 0;

- as= sert_int_equal(process_incoming_push_msg(c, &buf, c->options.pull, p= ull_permission_mask(c), &option_types_found), PUSH_MSG_UPDATE);<= br>+ assert_int_equal(proces= s_incoming_push_msg(c, &buf, c->options.pull, pull_permission_mask(c= ),
+ = &option_types_found),
+ PUSH_MSG_UPDATE);<= /span>

free_buf(&buf);
= }
@@ -177,7 +162,9 @@
buf_write(&= buf, update_msg, strlen(update_msg));
unsigned int opt= ion_types_found =3D 0;

- assert_int_equal(process_incoming_push_msg(c, &b= uf, c->options.pull, pull_permission_mask(c), &option_types_found), = PUSH_MSG_ERROR);
+ = assert_int_equal(process_incoming_push_msg(c, &buf, c->options.pull= , pull_permission_mask(c),
+ &option_types_fou= nd),
+ = PUSH_MSG_ERROR);

free_buf(&= ;buf);
}
@@ -191,7 +178,9 @@
buf_write(&buf, update_msg, strlen(update_msg));

unsigned int option_types_found =3D 0;


<= span style=3D"color: hsl(0, 100%, 40%);">- assert_int_equal(process_inco= ming_push_msg(c, &buf, c->options.pull, pull_permission_mask(c), &am= p;option_types_found), PUSH_MSG_ERROR);

+ assert_int_equal(process_incoming_push_msg(c, &= buf, c->options.pull, pull_permission_mask(c),
+ = &option_types_found),
+ PUSH_MSG_ERROR);

<= span> free_buf(&buf);

}
@@ -201,11= +190,14 @@
{
struct context *c =3D *= state;
struct buffer buf =3D alloc_buf(256);- const char *update_msg =3D = "PUSH_UPDATE,-dhcp-option, route 10.10.10.0, dhcp-option DNS 1.1.1.1, = route 10.11.12.0, dhcp-option DOMAIN corp.local, keepalive 10 60";
+ const char *update_= msg =3D
+ &quo= t;PUSH_UPDATE,-dhcp-option, route 10.10.10.0, dhcp-option DNS 1.1.1.1, rout= e 10.11.12.0, dhcp-option DOMAIN corp.local, keepalive 10 60";<= br> buf_write(&buf, update_msg, strlen(update_msg)); unsigned int option_types_found =3D 0;

- assert_int_equal(proces= s_incoming_push_msg(c, &buf, c->options.pull, pull_permission_mask(c= ), &option_types_found), PUSH_MSG_UPDATE);
+ assert_int_equal(process_incoming_push_msg(c= , &buf, c->options.pull, pull_permission_mask(c),
+ = &option_types_found),
+ PUSH_MSG_UPDATE);

free_buf(&buf);
}
@@= -215,11 +207,14 @@
{
struct context = *c =3D *state;
struct buffer buf =3D alloc_buf(256);
- const char *update_= msg =3D "PUSH_UPDATE,-dhcp-option,dhcp-option DNS 8.8.8.8,redirect-gat= eway local,route 192.168.1.0 255.255.255.0";
+ const char *update_msg =3D
+ "PUSH_UPDATE,-dhcp-op= tion,dhcp-option DNS 8.8.8.8,redirect-gateway local,route 192.168.1.0 255.2= 55.255.0";

buf_write(&buf, update_msg, strlen= (update_msg));
unsigned int option_types_found =3D 0;<= /span>

- = assert_int_equal(process_incoming_push_msg(c, &buf, c->options.pull,= pull_permission_mask(c), &option_types_found), PUSH_MSG_UPDATE);
+ assert_int_equal(proc= ess_incoming_push_msg(c, &buf, c->options.pull, pull_permission_mask= (c),
+ = &option_types_found),
+ PUSH_MSG_UPDATE)= ;

free_buf(&buf);
}

@@ -249,7 +244,8 @@
cmocka_un= it_test_setup_teardown(test_incoming_push_message_basic, setup, teardown),<= /span>
cmocka_unit_test_setup_teardown(test_incoming_push= _message_error1, setup, teardown),
cmocka_unit_tes= t_setup_teardown(test_incoming_push_message_error2, setup, teardown),
- cmocka_unit_test_se= tup_teardown(test_incoming_push_message_not_updatable_option, setup, teardo= wn),
+ cmocka_= unit_test_setup_teardown(test_incoming_push_message_not_updatable_option, s= etup,
+ = teardown),
cmocka_unit_t= est_setup_teardown(test_incoming_push_message_1, setup, teardown), cmocka_unit_test_setup_teardown(test_incoming_push_message= _bad_format, setup, teardown),
cmocka_unit_test_se= tup_teardown(test_incoming_push_message_mix, setup, teardown),
diff --git a/tests/unit_tests/openvpn/test_ssl.c b/tests/unit_tests/ope= nvpn/test_ssl.c

index c758f87..7bf5396 100644
--- a/tests/unit_tests/openvpn/test_ssl.c

+++ b/tests/un= it_tests/openvpn/test_ssl.c
@@ -159,7 +159,7 @@
<= span> static int

init(void **state)
{
- (void) state;<= br>+ (void)state;
= global_state.gc =3D gc_new();
global_state.= certfile =3D platform_create_temp_file(get_tmp_dir(), "cert", &am= p;global_state.gc);
global_state.keyfile =3D platform_= create_temp_file(get_tmp_dir(), "key", &global_state.gc);
@@ -180,7 +180,7 @@
static int
cleanup(void **state)

{
- (void) state;
+ (void)state;
unlink(global_sta= te.certfile);
unlink(global_state.keyfile);
= gc_free(&global_state.gc);
@@ -220,7 +220,7 = @@
static void
test_load_certificate_and_= key(void **state)
{
- (void) state;
+ (void)state;
struct tls_root_ctx ctx = =3D { 0 };

/* test loading of inline= d cert and key.
@@ -242,11 +242,11 @@
stat= ic void
test_load_certificate_and_key_uri(void **state)
{
- (= void) state;
+ (vo= id)state;

#if !defined(HAVE_OPENSSL_STOR= E)
skip();
-#else /* HAVE_OPENSSL_STORE */
+#else /* HAVE_OPENSSL_STORE */

struct tls_root_ctx ctx =3D { 0 };
co= nst char *certfile =3D global_state.certfile;
@@ -306,7 +30= 6,6 @@
frame->buf.tailroom =3D overhead;
=
frame->tun_mtu =3D tls_mtu;
-

}
=
static void
@@ -333,7 +332,6 @@ /* Test encryption, decryption for all packet sizes */ for (int i =3D 1; i <=3D frame.buf.payload_size; ++i)
{
-
/* msg(M_INFO, "TESTING ENCRYPT/DECRYPT of packe= t length=3D%d", i); */

/*
@@ -413,7 +411,6 @@
static void
<= span> check_aead_limits(struct crypto_options *co, bool chachapoly)
<= br> {
- /* Check that we correctly react when we have a nearing AEAD li= mits */

/* manually increase the sen= d counter to be past
@@ -445,9 +442,8 @@
= {
/* Check always against the GCM usage limit h= ere to see if that
* check works */
- assert_true(aead_usage_limi= t_reached((1ull << 36),

- &co->key_ctx_bi= .encrypt,
- = co->packet_id.send.id));
+ assert_true(

+ aead_usage_limit_reac= hed((1ull << 36), &co->key_ctx_bi.encrypt, co->packet_id.se= nd.id));

return;
}
=
@@ -464,10 +460,9 @@


static struct crypto_options
-init_crypto_options(const char *cipher, con= st char *auth, bool epoch,
- struct key2 *statickey)
+init_crypto_options(const char *cipher, const = char *auth, bool epoch, struct key2 *statickey)
{- struct key2 key2 =3D { .n = =3D 2};
+ struct k= ey2 key2 =3D { .n =3D 2 };

if (stati= ckey)
{
@@ -488,7 +483,7 @@
=
if (epoch)
{
- struct epoch_key e1 =3D { = .epoch =3D 1, .epoch_key =3D { 0 }};

+ struct epoch_key e1 =3D { .epoch =3D 1, .epoch_key= =3D { 0 } };
memcpy(e1.epoch_key, key2.keys[0].ci= pher, sizeof(e1.epoch_key));
co.flags |=3D CO_EPOC= H_DATA_KEY_FORMAT;
epoch_init_key_ctx(&co, &am= p;kt, &e1, &e1, 5);
@@ -633,11 +628,11 @@ static struct key2
create_key(void)
{

- struct key2 k= ey2 =3D {.n =3D 2};
+= struct key2 key2 =3D { .n =3D 2 };

- const uint8_t key[] =3D
- {'a', 'b', = 9;c', 'd', 'e', 'f', 'g', 'h', = '0', '1', '2', '3', '4', '5'= ;, '6', '7', 'A', 'B', 'C', 'D&= #39;, 'E', 'F',

- 'G', 'H', 'j', 'k', 'u&#= 39;, 'c', 'h', 'e', 'n', 'l'};
+ const uint8_t key[] = =3D { 'a', 'b', 'c', 'd', 'e', '= ;f', 'g', 'h', '0', '1', '2',
+ = '3', '4', '5', '6', '7', = 9;A', 'B', 'C', 'D', 'E', 'F',<= /span>
+ = 'G', 'H', 'j', 'k', 'u', &#= 39;c', 'h', 'e', 'n', 'l' };
=
static_assert(sizeof(key) =3D=3D 32, "Siz= e of key should be 32 bytes");

@@ -6= 47,7 +642,7 @@

for (int i =3D 0; i &= lt; sizeof(key2.keys); i++)
{
- keydata[i] =3D (uint8_t) (key[i % size= of(key)] ^ i);
+ = keydata[i] =3D (uint8_t)(key[i % sizeof(key)] ^ i);
= }

ASSERT(memcpy(key2.keys[0].cipher= , keydata, sizeof(key2.keys[0].cipher)));
@@ -663,8 +658,7 = @@
{
struct key2 key2 =3D create_key(= );

- = struct crypto_options co =3D init_crypto_options("AES-256-GCM"= , "none", epoch,
- &key2);<= br>+ struct crypto_options c= o =3D init_crypto_options("AES-256-GCM", "none", epoch,= &key2);

struct gc_arena gc =3D = gc_new();

@@ -716,41 +710,40 @@
if (epoch)
{
<= span style=3D"color: hsl(0, 100%, 40%);">- uint8_t packetid1[8] =3D = {0, 0x04, 0, 0, 0, 0, 0, 1};

+ uint8_t packetid1[8] =3D { 0, 0x04, 0, 0, 0, 0, 0, 1 };
assert_memory_equal(BPTR(&buf), packetid1, 8);
}
else
{
- uint8_t packetid1[= 4] =3D {0, 0, 0, 1};
= + uint8_t packetid1[4] =3D { 0, 0, 0, 1 };
= assert_memory_equal(BPTR(&buf), packetid1, 4);
}

if (epoch)
{
uint8_t *tag_location =3D BEND(&buf) - OPENVPN_AE= AD_TAG_LENGTH;
- = const uint8_t exp_tag_epoch[16] =3D
- {0x0f, 0xff, 0xf5, 0x91, 0x3d, 0x39, 0xd7, 0x5b,
- 0x18, 0x57, 0x3b= , 0x57, 0x48, 0x58, 0x9a, 0x7d};
+ const uint8_t exp_tag_epoch[16] =3D { 0x0f, 0xff, 0xf5= , 0x91, 0x3d, 0x39, 0xd7, 0x5b,
+ 0x18, 0x57, 0x3b, 0= x57, 0x48, 0x58, 0x9a, 0x7d };

a= ssert_memory_equal(tag_location, exp_tag_epoch, OPENVPN_AEAD_TAG_LENGTH);
}
else
{
uint8_t *tag_location =3D BPTR(&buf) + 4;- const uint8_t exp_tag_= noepoch[16] =3D
- = {0x1f, 0xdd, 0x90, 0x8f, 0x0e, 0x9d, 0xc2, 0x5e, 0x79, 0xd8, 0x32, 0x02, = 0x0d, 0x58, 0xe7, 0x3f};
+ const uint8_t exp_tag_noepoch[16] =3D { 0x1f, 0xdd, 0x90, 0x8f= , 0x0e, 0x9d, 0xc2, 0x5e,
+ 0x79, 0xd8, 0x32, 0x02,= 0x0d, 0x58, 0xe7, 0x3f };
assert_memory_equal(tag= _location, exp_tag_noepoch, OPENVPN_AEAD_TAG_LENGTH);
= }

/* Check some bytes at the beginni= ng of the encrypted part */
if (epoch)
{

- const = uint8_t bytesat14[6] =3D {0x36, 0xaa, 0xb4, 0xd4, 0x9c, 0xe6};
+ const uint8_t bytesat14[= 6] =3D { 0x36, 0xaa, 0xb4, 0xd4, 0x9c, 0xe6 };

ass= ert_memory_equal(BPTR(&buf) + 14, bytesat14, sizeof(bytesat14));=
}
else
{- const uint8_t bytesat30= [6] =3D {0xa8, 0x2e, 0x6b, 0x17, 0x06, 0xd9};
+ const uint8_t bytesat30[6] =3D { 0xa8, 0x= 2e, 0x6b, 0x17, 0x06, 0xd9 };
assert_memory_equal(= BPTR(&buf) + 30, bytesat30, sizeof(bytesat30));
}<= /span>

diff --git a/tests/unit_tests/openvpn/tes= t_tls_crypt.c b/tests/unit_tests/openvpn/test_tls_crypt.c
i= ndex 1b5eb27..532bfcd 100644
--- a/tests/unit_tests/openvpn= /test_tls_crypt.c
+++ b/tests/unit_tests/openvpn/test_tls_c= rypt.c
@@ -39,8 +39,7 @@
/* Define this fu= nction here as dummy since including the ssl_*.c files
* = leads to having to include even more unrelated code */
boo= l
-key_state_export_key= ing_material(struct tls_session *session,
- const char *label, siz= e_t label_size,
+key_= state_export_keying_material(struct tls_session *session, const char *label= , size_t label_size,
void= *ekm, size_t ekm_size)
{
memset(ekm,= 0xba, ekm_size);
@@ -48,22 +47,22 @@
}


-#define TESTBUF_SIZE 128
+#define TESTBUF_SIZE 128

/* Defines for use in the tests and the mock parse_line() */
-#define PATH1 &qu= ot;/s p a c e"
-#d= efine PATH2 "/foo bar/baz"
-#define PARAM1 "param1"
-#define PARAM2 "param two&q= uot;

+#define PATH1 = "/s p a c e"
+#define PARAM1 "param1"
+#define PARAM2 "param two"

-stati= c const char *test_server_key =3D \
+static const char *test_server_key =3D
= "-----BEGIN OpenVPN tls-crypt-v2 server key-----\n"
"AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISIjJCUmJygpKiss= LS4v\n"

"MDEyMzQ1Njc4OTo7PD0+P0BBQkNERUZHSEl= KS0xNTk9QUVJTVFVWV1hZWltcXV5f\n"
"YGFiY2RlZm= doaWprbG1ub3BxcnN0dXZ3eHl6e3x9fn8=3D\n"
"---= --END OpenVPN tls-crypt-v2 server key-----\n";

-static const char *test_cli= ent_key =3D \
+static= const char *test_client_key =3D
"-----BEGIN Open= VPN tls-crypt-v2 client key-----\n"
"AAECAwQ= FBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISIjJCUmJygpKissLS4v\n" "MDEyMzQ1Njc4OTo7PD0+P0BBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZW= ltcXV5f\n"
@@ -81,7 +80,7 @@
<= br>
/* Has custom metadata of AABBCCDD (base64) */<= /span>
-static const char *tes= t_client_key_metadata =3D \
+static const char *test_client_key_metadata =3D
= "-----BEGIN OpenVPN tls-crypt-v2 client key-----\n"
<= span> "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISIjJCUmJygpKis= sLS4v\n"

"MDEyMzQ1Njc4OTo7PD0+P0BBQkNERUZHSE= lKS0xNTk9QUVJTVFVWV1hZWltcXV5f\n"
@@ -98,8 +97,8 @@
"-----END OpenVPN tls-crypt-v2 client key-----\n&qu= ot;;

int
-__wrap_parse_line(const char *line, char **p, const i= nt n, const char *file,
- const int line_num, int msglevel, struct gc_arena *gc)<= /span>
+__wrap_parse_line(co= nst char *line, char **p, const int n, const char *file, const int line_num= ,
+ = int msglevel, struct gc_arena *gc)
{
= p[0] =3D PATH1 PATH2;
p[1] =3D PARAM1;
@@ -141,7 +140,8 @@

return true;
}

-struc= t test_tls_crypt_context {
+struct test_tls_crypt_context
+{
struct crypto_options co; struct key_type kt;
struct buffer source;<= /span>
@@ -156,8 +156,10 @@
struct test_tls_c= rypt_context *ctx =3D calloc(1, sizeof(*ctx));
*state = =3D ctx;

- struct key_parameters key =3D { .cipher =3D { 0 }, .hmac =3D { 0 }= ,
- = .hmac_size =3D MAX_HMAC_KEY_LENGTH, .cipher_size =3D MAX_CIPH= ER_KEY_LENGTH };
+ = struct key_parameters key =3D { .cipher =3D { 0 },
+ .hmac = =3D { 0 },
+ = .hmac_size =3D MAX_HMAC_KEY_LENGTH,
+ = .cipher_size =3D MAX_CIPHER_KEY_LENGTH };


ctx->kt =3D tls_crypt_kt();

if (!ctx->kt.c= ipher || !ctx->kt.digest)
@@ -187,8 +189,7 @@
= static int
test_tls_crypt_teardown(void **state)
{
- s= truct test_tls_crypt_context *ctx =3D
- (struct test_tls_crypt_context *)*state;
= + struct test_tls_crypt_cont= ext *ctx =3D (struct test_tls_crypt_context *)*state;

free_buf(&ctx->source);
free_= buf(&ctx->ciphertext);
@@ -216,7 +217,7 @@ static void
tls_crypt_loopback(void **state)
{
- stru= ct test_tls_crypt_context *ctx =3D (struct test_tls_crypt_context *) *state= ;
+ struct test_tl= s_crypt_context *ctx =3D (struct test_tls_crypt_context *)*state;
skip_if_tls_crypt_not_supported(ctx);<= br>
@@ -224,8 +225,7 @@
assert_= true(BLEN(&ctx->source) < BLEN(&ctx->ciphertext));<= br> assert_true(tls_crypt_unwrap(&ctx->ciphertext, &ct= x->unwrapped, &ctx->co));
assert_int_equal(B= LEN(&ctx->source), BLEN(&ctx->unwrapped));
- assert_memory_equal(BPTR(&ctx-&g= t;source), BPTR(&ctx->unwrapped),
- BLEN(&ctx->source));
+ assert_memory_equal(= BPTR(&ctx->source), BPTR(&ctx->unwrapped), BLEN(&ctx->= source));
}


= @@ -235,8 +235,7 @@
static void
tes= t_tls_crypt_secure_reneg_key(void **state)
{
- struct test_tls_crypt_context *= ctx =3D

- (struc= t test_tls_crypt_context *)*state;
+ struct test_tls_crypt_context *ctx =3D (struct test_tls_= crypt_context *)*state;

struct gc_ar= ena gc =3D gc_new();

@@ -255,19 +254,19 @= @
tls_crypt_wrap(&ctx->source, &rctx->wo= rk, &rctx->opt);
assert_int_equal(buf_len(&= ctx->source) + 40, buf_len(&rctx->work));

- uint8_t expected_cipher= text[] =3D {
- 0= x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0xe3, 0x19, 0x27, 0x7f, 0x1c= , 0x8d, 0x6e, 0x6a,
- = 0x77, 0x96, 0xa8, 0x55, 0x33, 0x7b, 0x9c, 0xfb, 0x56, 0xe1, 0xf1, 0x3= a, 0x87, 0x0e, 0x66, 0x47,
- 0xdf, 0xa1, 0x95, 0xc9, 0x2c, 0x17, 0xa0, 0x15, 0xba, 0x49, 0x= 67, 0xa1, 0x1d, 0x55, 0xea, 0x1a,
- 0x06, 0xa7
- };
+ = uint8_t expected_ciphertext[] =3D { 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x0= 0, 0x00, 0xe3, 0x19,
= + 0x27, 0x7f, 0x1c, 0x8d, 0x6e, 0x6a, = 0x77, 0x96, 0xa8, 0x55,
+ 0x33, 0x7b, 0x9c, 0xfb, 0x56, 0xe= 1, 0xf1, 0x3a, 0x87, 0x0e,
+ 0x66, 0x47, 0xdf, 0xa1, 0x95, = 0xc9, 0x2c, 0x17, 0xa0, 0x15,
+ 0xba, 0x49, 0x67, 0xa1, 0x1= d, 0x55, 0xea, 0x1a, 0x06, 0xa7 };
assert_memory_equal= (BPTR(&rctx->work), expected_ciphertext, buf_len(&rctx->work)= );
tls_wrap_free(&session.tls_wrap_reneg);<= br>
/* Use previous tls-crypt key as 0x00, with= xor we should have the same key
* and expect the sam= e result */
session.tls_wrap.mode =3D TLS_WRAP_CRYPT;<= /span>
- memset(&sessio= n.tls_wrap.original_wrap_keydata.keys, 0x00, sizeof(session.tls_wrap.origin= al_wrap_keydata.keys));
+ memset(&session.tls_wrap.original_wrap_keydata.keys, 0x00,
+ sizeof(sessio= n.tls_wrap.original_wrap_keydata.keys));
session.tls_w= rap.original_wrap_keydata.n =3D 2;

t= ls_session_generate_dynamic_tls_crypt_key(&session);
@@= -278,7 +277,8 @@
tls_wrap_free(&session.tls_wrap_= reneg);

/* XOR should not force a di= fferent key */
- mem= set(&session.tls_wrap.original_wrap_keydata.keys, 0x42, sizeof(session.= tls_wrap.original_wrap_keydata.keys));
+ memset(&session.tls_wrap.original_wrap_keydata.k= eys, 0x42,
+ = sizeof(session.tls_wrap.original_wrap_keydata.keys));
= tls_session_generate_dynamic_tls_crypt_key(&session);

tls_crypt_wrap(&ctx->source, &rctx->w= ork, &rctx->opt);
@@ -302,7 +302,7 @@
static void

tls_crypt_loopback_zero_len(void **state)
{
- = struct test_tls_crypt_context *ctx =3D (struct test_tls_crypt_context *) *s= tate;
+ struct tes= t_tls_crypt_context *ctx =3D (struct test_tls_crypt_context *)*state;

skip_if_tls_crypt_not_supported(ctx);

@@ -312,8 +312,7 @@
ass= ert_true(BLEN(&ctx->source) < BLEN(&ctx->ciphertext));
assert_true(tls_crypt_unwrap(&ctx->ciphertext, &am= p;ctx->unwrapped, &ctx->co));
assert_int_equ= al(BLEN(&ctx->source), BLEN(&ctx->unwrapped));
- assert_memory_equal(BPTR(&ct= x->source), BPTR(&ctx->unwrapped),

- BLEN(&ctx->source));<= /span>
+ assert_memory_eq= ual(BPTR(&ctx->source), BPTR(&ctx->unwrapped), BLEN(&ctx-= >source));
}

/**
@@ -322,20 +321,19 @@
static void
<= span> tls_crypt_loopback_max_len(void **state)

{- struct test_tls_crypt_conte= xt *ctx =3D (struct test_tls_crypt_context *) *state;
+ struct test_tls_crypt_context *ctx = =3D (struct test_tls_crypt_context *)*state;

skip_if_tls_crypt_not_supported(ctx);


= buf_clear(&ctx->source);
- assert_non_null(buf_write_alloc(&ctx->sourc= e,
- = TESTBUF_SIZE - BLEN(&ctx->ciphertext) - tls_crypt_b= uf_overhead()));
+ = assert_non_null(buf_write_alloc(&ctx->source, TESTBUF_SIZE - BLEN(&= amp;ctx->ciphertext)
+ - tls_crypt_buf_o= verhead()));

assert_true(tls_crypt_w= rap(&ctx->source, &ctx->ciphertext, &ctx->co));=
assert_true(BLEN(&ctx->source) < BLEN(&ctx->= ;ciphertext));
assert_true(tls_crypt_unwrap(&ctx-&= gt;ciphertext, &ctx->unwrapped, &ctx->co));
= assert_int_equal(BLEN(&ctx->source), BLEN(&ctx->unwrapped= ));
- assert_memory_= equal(BPTR(&ctx->source), BPTR(&ctx->unwrapped),
- BLEN(&= ctx->source));

+ = assert_memory_equal(BPTR(&ctx->source), BPTR(&ctx->unwrappe= d), BLEN(&ctx->source));
}
=
/**
@@ -344,13 +342,13 @@
stati= c void
tls_crypt_fail_msg_too_long(void **state) {
- struct t= est_tls_crypt_context *ctx =3D (struct test_tls_crypt_context *) *state;
+ struct test_tls_cr= ypt_context *ctx =3D (struct test_tls_crypt_context *)*state;

skip_if_tls_crypt_not_supported(ctx);
<= span>

buf_clear(&ctx->source);
- assert_non_null(buf_write_alloc(&= amp;ctx->source,

- = TESTBUF_SIZE - BLEN(&ctx->cipherte= xt) - tls_crypt_buf_overhead() + 1));
+ assert_non_null(buf_write_alloc(&ctx->source, = TESTBUF_SIZE - BLEN(&ctx->ciphertext)
+ = - tls_crypt_buf_overhead() + 1));
assert_false(tls= _crypt_wrap(&ctx->source, &ctx->ciphertext, &ctx->co))= ;
}

@@ -361,13 +359,15 @= @
static void
tls_crypt_fail_invalid_key(= void **state)
{
- struct test_tls_crypt_context *ctx =3D (struct test_tls_cryp= t_context *) *state;
= + struct test_tls_crypt_context *ctx =3D (struct test_tls_crypt_context = *)*state;

skip_if_tls_crypt_not_supp= orted(ctx);

/* Change decrypt key */=
- struct key_parame= ters key =3D { .cipher =3D { 1 }, .hmac =3D { 1 },
- .cipher_size= =3D MAX_CIPHER_KEY_LENGTH, .hmac_size =3D MAX_HMAC_KEY_LENGTH };+ struct key_parameters key= =3D { .cipher =3D { 1 },
+ .hmac =3D { 1 },
+ .cip= her_size =3D MAX_CIPHER_KEY_LENGTH,
+ .hmac_size =3D MAX_HMAC_K= EY_LENGTH };
free_key_ctx(&ctx->co.key_ctx_bi.d= ecrypt);
init_key_ctx(&ctx->co.key_ctx_bi.decry= pt, &key, &ctx->kt, false, "TEST");
<= /span>
@@ -382,7 +382,7 @@
static void
= tls_crypt_fail_replay(void **state)
{
- struct test_tls_crypt_context *= ctx =3D (struct test_tls_crypt_context *) *state;

+ struct test_tls_crypt_context *ctx =3D (s= truct test_tls_crypt_context *)*state;

= skip_if_tls_crypt_not_supported(ctx);

= @@ -402,7 +402,7 @@
static void
tls_crypt= _ignore_replay(void **state)
{
- struct test_tls_crypt_context *ctx =3D (struc= t test_tls_crypt_context *) *state;
+ struct test_tls_crypt_context *ctx =3D (struct test_tls= _crypt_context *)*state;

skip_if_tls= _crypt_not_supported(ctx);

@@ -416,7 +416= ,8 @@
assert_true(tls_crypt_unwrap(&ctx->cipher= text, &ctx->unwrapped, &ctx->co));
}<= br>
-struct test= _tls_crypt_v2_context {
+struct test_tls_crypt_v2_context
+{
struct gc_arena gc;
struct key2 server_key2;

struct key_ctx_bi serve= r_keys;
@@ -436,17 +437,15 @@
ctx->= gc =3D gc_new();

/* Slightly longer = buffers to be able to test too-long data */
- ctx->metadata =3D alloc_buf_gc(TLS_CRYPT_V2_MA= X_METADATA_LEN+16, &ctx->gc);
- ctx->unwrapped_metadata =3D alloc_buf_gc(TLS_CRYPT_V2= _MAX_METADATA_LEN+16,
-= &ctx->gc);
- ctx->wkc =3D alloc_buf_gc(TLS= _CRYPT_V2_MAX_WKC_LEN+16, &ctx->gc);

+ ctx->metadata =3D alloc_buf_gc(TLS_CRYPT_V2_= MAX_METADATA_LEN + 16, &ctx->gc);
+ ctx->unwrapped_metadata =3D alloc_buf_gc(TLS_CR= YPT_V2_MAX_METADATA_LEN + 16, &ctx->gc);
+ ctx->wkc =3D alloc_buf_gc(TLS_CRYPT_V2_M= AX_WKC_LEN + 16, &ctx->gc);

/= * Generate server key */
rand_bytes((void *)ctx->se= rver_key2.keys, sizeof(ctx->server_key2.keys));
ctx= ->server_key2.n =3D 2;
struct key_type kt =3D tls_c= rypt_kt();
- init_ke= y_ctx_bi(&ctx->server_keys, &ctx->server_key2,
- KEY_DIRECTION_BI= DIRECTIONAL, &kt,

+ init_key_ctx_bi(&ctx->server_keys, &ctx->server_key2, K= EY_DIRECTION_BIDIRECTIONAL, &kt,
&= quot;tls-crypt-v2 server key");

= /* Generate client key */
@@ -459,8 +458,7 @@
static int

test_tls_crypt_v2_teardown(void **state)
{
- = struct test_tls_crypt_v2_context *ctx =3D
- (struct test_tls_crypt_v2_context *) *state;
+ struct test_tls_cr= ypt_v2_context *ctx =3D (struct test_tls_crypt_v2_context *)*state;<= br>
free_key_ctx_bi(&ctx->server_keys);<= /span>
free_key_ctx_bi(&ctx->client_key);
@@ -478,27 +476,20 @@

static void
tls= _crypt_v2_wrap_unwrap_no_metadata(void **state)
{- struct test_tls_crypt_v2_c= ontext *ctx =3D
- = (struct test_tls_crypt_v2_context *) *state;
+ struct test_tls_crypt_v2_context *ctx =3D (s= truct test_tls_crypt_v2_context *)*state;

- struct buffer wrapped_client_key = =3D alloc_buf_gc(TLS_CRYPT_V2_MAX_WKC_LEN,

- &a= mp;ctx->gc);
- as= sert_true(tls_crypt_v2_wrap_client_key(&wrapped_client_key,
<= span style=3D"color: hsl(0, 100%, 40%);">- = &ctx->client_key2,

- &ctx->m= etadata,
- = &ctx->server_keys.encrypt,- = &ctx->gc));
+ struct buffer wrapped_client_key =3D alloc_buf_gc(TLS_CRYP= T_V2_MAX_WKC_LEN, &ctx->gc);
+ assert_true(tls_crypt_v2_wrap_client_key(&wrapped_c= lient_key, &ctx->client_key2, &ctx->metadata,
+ = &ctx->server_keys.encrypt, &ctx->gc));


- struct buffe= r unwrap_metadata =3D alloc_buf_gc(TLS_CRYPT_V2_MAX_METADATA_LEN,- = &ctx->gc);
+ struct buffer unwrap_metadata =3D alloc_buf_gc(TLS_CRYP= T_V2_MAX_METADATA_LEN, &ctx->gc);
struct key2 u= nwrapped_client_key2 =3D { 0 };
- assert_true(tls_crypt_v2_unwrap_client_key(&unwrapped_cli= ent_key2,
- = &unwrap_metadata,
- = wrapped_client_key,
- &ctx->server_key= s.decrypt));
+ ass= ert_true(tls_crypt_v2_unwrap_client_key(&unwrapped_client_key2, &un= wrap_metadata,
+ = wrapped_client_key, &ctx->= server_keys.decrypt));

- assert_true(0 =3D=3D memcmp(ctx->client_key2.keys= , unwrapped_client_key2.keys,
- sizeof(ctx->client_key2.keys)));
+ assert_true(0
+ =3D=3D me= mcmp(ctx->client_key2.keys, unwrapped_client_key2.keys,
+ sizeof(ctx= ->client_key2.keys)));
}

/**

@@ -508,26 +499,21 @@
static void=
tls_crypt_v2_wrap_unwrap_max_metadata(void **state)
{
- stru= ct test_tls_crypt_v2_context *ctx =3D
- (struct test_tls_crypt_v2_context *) *state;=
+ struct test_tls_crypt_= v2_context *ctx =3D (struct test_tls_crypt_v2_context *)*state;
<= span>

- uint8_t *me= tadata =3D
- buf= _write_alloc(&ctx->metadata, TLS_CRYPT_V2_MAX_METADATA_LEN);<= br>+ uint8_t *metadata =3D b= uf_write_alloc(&ctx->metadata, TLS_CRYPT_V2_MAX_METADATA_LEN);
assert_true(rand_bytes(metadata, TLS_CRYPT_V2_MAX_METADATA_= LEN));
- assert_true= (tls_crypt_v2_wrap_client_key(&ctx->wkc, &ctx->client_key2,
- = &ctx->metadata,
- &ct= x->server_keys.encrypt,
- &ctx->gc));=
+ assert_true(tls_crypt_= v2_wrap_client_key(&ctx->wkc, &ctx->client_key2, &ctx->= ;metadata,
+ = &ctx->server_keys.encrypt, &= ctx->gc));

- struct buffer unwrap_metadata =3D alloc_buf_gc(TLS_CRYPT_V2_M= AX_METADATA_LEN,
- = &ctx->gc);
+ struct buffer unwrap_metadata= =3D alloc_buf_gc(TLS_CRYPT_V2_MAX_METADATA_LEN, &ctx->gc);
struct key2 unwrapped_client_key2 =3D { 0 };
- assert_true(tls_crypt_v2_unwrap_cli= ent_key(&unwrapped_client_key2,
- &unwrap_me= tadata, ctx->wkc,
= + assert_true(tls_crypt_v2_unwrap_client_key(&unwrapped_client_key2,= &unwrap_metadata, ctx->wkc,
= &ctx->server_keys.decrypt));

- assert_true(0 = =3D=3D memcmp(ctx->client_key2.keys, unwrapped_client_key2.keys,<= br>- s= izeof(ctx->client_key2.keys)));
+ assert_true(0
+ =3D=3D memcmp(ctx->client_key2.keys, unwrap= ped_client_key2.keys,
+ sizeof(ctx->client_key2.keys)));
<= span> assert_true(buf_equal(&ctx->metadata, &unwrap_metadata= ));


struct tls_wrap_ctx wrap_ctx =3D= {
@@ -545,14 +531,11 @@
static void
tls_crypt_v2_wrap_too_long_metadata(void **state)
{

- struct test_= tls_crypt_v2_context *ctx =3D
- (struct test_tls_crypt_v2_context *) *state;
+ struct test_tls_crypt_v2_conte= xt *ctx =3D (struct test_tls_crypt_v2_context *)*state;


- assert_true(buf_inc= _len(&ctx->metadata, TLS_CRYPT_V2_MAX_METADATA_LEN+1));
- assert_false(tls_crypt_v2_wrap= _client_key(&ctx->wkc, &ctx->client_key2,

- = &ctx->metadata,
- &ctx->server_key= s.encrypt,
- = &ctx->gc));
+ assert_true(buf_inc_len(&ctx->= metadata, TLS_CRYPT_V2_MAX_METADATA_LEN + 1));
+ assert_false(tls_crypt_v2_wrap_client_key(&a= mp;ctx->wkc, &ctx->client_key2, &ctx->metadata,
= + = &ctx->server_keys.encrypt, &ctx->gc));=
}

/**
@@ -562= ,28 +545,22 @@
static void
tls_crypt_v2_w= rap_unwrap_wrong_key(void **state)
{
- struct test_tls_crypt_v2_context *ctx = =3D
- (struct te= st_tls_crypt_v2_context *) *state;
+ struct test_tls_crypt_v2_context *ctx =3D (struct test_t= ls_crypt_v2_context *)*state;

- assert_true(tls_crypt_v2_wrap_client_key(&= ;ctx->wkc, &ctx->client_key2,
- &ctx->= ;metadata,
- = &ctx->server_keys.encrypt,<= br>- = &ctx->gc));
+ assert_true(tls_crypt_v2_wrap_client_key(&ctx->wk= c, &ctx->client_key2, &ctx->metadata,
+ = &ctx->server_keys.encrypt, &ctx->gc));
<= /span>
/* Change server key */
struct ke= y_type kt =3D tls_crypt_kt();
free_key_ctx_bi(&ctx= ->server_keys);
memset(&ctx->server_key2.key= s, 0, sizeof(ctx->server_key2.keys));
- init_key_ctx_bi(&ctx->server_keys, &ctx-&= gt;server_key2,
- = KEY_DIRECTION_BIDIRECTIONAL, &kt,
+ init_key_ctx_bi(&ctx->server_k= eys, &ctx->server_key2, KEY_DIRECTION_BIDIRECTIONAL, &kt,=
"wrong tls-crypt-v2 server key");<= /span>


struct key2 unwrap= ped_client_key2 =3D { 0 };
- assert_false(tls_crypt_v2_unwrap_client_key(&unwrapped_client_= key2,
- = &ctx->unwrapped_metadata,
= - = ctx->wkc,
- &ctx->server_= keys.decrypt));
+ = assert_false(tls_crypt_v2_unwrap_client_key(&unwrapped_client_key2, &am= p;ctx->unwrapped_metadata,
+ ctx->wkc, &= ;ctx->server_keys.decrypt));

cons= t struct key2 zero =3D { 0 };
assert_true(0 =3D=3D mem= cmp(&unwrapped_client_key2, &zero, sizeof(zero)));
= @@ -597,23 +574,17 @@
static void
tls_cry= pt_v2_wrap_unwrap_dst_too_small(void **state)
{
= - struct test_tls_crypt_v2_con= text *ctx =3D
- = (struct test_tls_crypt_v2_context *) *state;
+ struct test_tls_crypt_v2_context *ctx =3D (str= uct test_tls_crypt_v2_context *)*state;

- uint8_t *metadata =3D
- buf_write_alloc(&ctx-&g= t;metadata, TLS_CRYPT_V2_MAX_METADATA_LEN);

+ uint8_t *metadata =3D buf_write_alloc(&ctx-= >metadata, TLS_CRYPT_V2_MAX_METADATA_LEN);
assert_t= rue(rand_bytes(metadata, TLS_CRYPT_V2_MAX_METADATA_LEN));
- assert_true(tls_crypt_v2_wrap_clien= t_key(&ctx->wkc, &ctx->client_key2,
- &a= mp;ctx->metadata,
- = &ctx->server_keys.encryp= t,
- = &ctx->gc));
+ assert_true(tls_crypt_v2_wrap_client_key(&= ctx->wkc, &ctx->client_key2, &ctx->metadata,
+ = &ctx->server_keys.encrypt, &ctx->gc));

=
struct key2 unwrapped_client_key2 =3D { 0 };
- struct buffer unwra= pped_metadata =3D
- = alloc_buf_gc(TLS_CRYPT_V2_MAX_METADATA_LEN-1, &ctx->gc);<= br>- assert_false(tls_crypt_v2= _unwrap_client_key(&unwrapped_client_key2,
- &a= mp;unwrapped_metadata, ctx->wkc,
- &ctx->= server_keys.decrypt));
+ assert_false(tls_crypt_v2_unwrap_client_key(&unwrapp= ed_client_key2, &unwrapped_metadata,
+ ctx-&g= t;wkc, &ctx->server_keys.decrypt));

const struct key2 zero =3D { 0 };

assert_true(0= =3D=3D memcmp(&unwrapped_client_key2, &zero, sizeof(zero)));
@@ -626,8 +597,7 @@
const char *filename = =3D "testfilename.key";

ex= pect_string(__wrap_buffer_write_file, filename, filename);
- expect_memory(__wrap_buffer_write_= file, pem, test_server_key,
- strlen(test_server_key));
+ expect_memory(__wrap_buffer_write_file, p= em, test_server_key, strlen(test_server_key));
will_re= turn(__wrap_buffer_write_file, true);

= tls_crypt_v2_write_server_key_file(filename);
@@ -640,8 += 610,7 @@

/* Test writing the client = key */
expect_string(__wrap_buffer_write_file, filenam= e, filename);
- expe= ct_memory(__wrap_buffer_write_file, pem, test_client_key,
- strlen(test_client_ke= y));
+ expect_memo= ry(__wrap_buffer_write_file, pem, test_client_key, strlen(test_client_key))= ;
will_return(__wrap_buffer_write_file, true);<= br>
/* Key generation re-reads the created file= as a sanity check */
@@ -667,8 +636,7 @@
= expect_string(__wrap_buffer_read_from_file, filename, filename);=
will_return(__wrap_buffer_read_from_file, test_client_key_me= tadata);

- tls_crypt_v2_write_client_key_file(filename, b64metadata, test_ser= ver_key,
- = true);
+ tls_crypt_v2_write_client_key_file(filename, b64metadata, = test_server_key, true);
}

int

@@ -676,44 +644,31 @@
{
<= span> openvpn_unit_test_setup();

const struct CMUn= itTest tests[] =3D {
- = cmocka_unit_test_setup_teardown(tls_crypt_loopback,
- = test_tls_crypt_setup,
+ cmocka_unit_test_setup_teardown(tls_crypt_loopback, test_tls_cr= ypt_setup,
test_tl= s_crypt_teardown),
- = cmocka_unit_test_setup_teardown(tls_crypt_loopback_zero_len,- = test_tls_crypt_setup,
+ cmocka_unit_test_setup_teardown(tls_crypt_loopback_zero_= len, test_tls_crypt_setup,
= test_tls_crypt_teardown),
- cmocka_unit_test_setup_teardown(tls_crypt_loopback_max= _len,
- = test_tls_crypt_setup,
+ cmocka_unit_test_setup_teardown(tls_crypt= _loopback_max_len, test_tls_crypt_setup,
= test_tls_crypt_teardown),
- cmocka_unit_test_setup_teardown(tls_cryp= t_fail_msg_too_long,
- = test_tls_crypt_setup,
+ cmocka_unit_test_setup_tea= rdown(tls_crypt_fail_msg_too_long, test_tls_crypt_setup,

= test_tls_crypt_teardown),
= - cmocka_unit_test_setup_t= eardown(tls_crypt_fail_invalid_key,
- test_tls_crypt_setup,=
+ cmocka_unit= _test_setup_teardown(tls_crypt_fail_invalid_key, test_tls_crypt_setup,
test_tls_crypt_teardow= n),
- cmocka_uni= t_test_setup_teardown(tls_crypt_fail_replay,
- test_tls_cry= pt_setup,
+ cm= ocka_unit_test_setup_teardown(tls_crypt_fail_replay, test_tls_crypt_setup,<= /span>
test_tls_crypt_tea= rdown),
- cmocka= _unit_test_setup_teardown(tls_crypt_ignore_replay,
- test_t= ls_crypt_setup,
+ = cmocka_unit_test_setup_teardown(tls_crypt_ignore_replay, test_tls_crypt= _setup,
test_tls_c= rypt_teardown),
cmocka_unit_test_setup_teardown(tl= s_crypt_v2_wrap_unwrap_no_metadata,
- test_tls_crypt_v2_set= up,
- = test_tls_crypt_v2_teardown),
+ test= _tls_crypt_v2_setup, test_tls_crypt_v2_teardown),
= cmocka_unit_test_setup_teardown(tls_crypt_v2_wrap_unwrap_max_metadata,
- = test_tls_crypt_v2_setup,
- test_tls_crypt_v2_= teardown),
+ = test_tls_crypt_v2_setup, test_tls_crypt_v2_t= eardown),
cmocka_unit_test_setup_teardown(tls_cryp= t_v2_wrap_too_long_metadata,
- test_tls_crypt_v2_setup,
- = test_tls_crypt_v2_teardown),
- cmocka_unit_test_setup_teardown(tls_crypt_v2_= wrap_unwrap_wrong_key,
= - test_tls_crypt_v2_setup,+ = test_tls_crypt_v2_setup, test_tls_crypt_v2_teardown),
= + cmocka_unit_test_setup= _teardown(tls_crypt_v2_wrap_unwrap_wrong_key, test_tls_crypt_v2_setup,
test_tls_crypt_v2_tear= down),
cmocka_unit_test_setup_teardown(tls_crypt_v= 2_wrap_unwrap_dst_too_small,
- test_tls_crypt_v2_setup,
- = test_tls_crypt_v2_teardown),
- cmocka_unit_test_setup_teardown(test_tls_cryp= t_secure_reneg_key,
- = test_tls_crypt_setup,
+ = test_tls_crypt_v2_setup, test_tls_crypt_v2_teardown),

+ cmocka_unit_test_setup_teard= own(test_tls_crypt_secure_reneg_key, test_tls_crypt_setup,
= test_tls_crypt_teardown), cmocka_unit_test(test_tls_crypt_v2_write_server_key_file),=
cmocka_unit_test(test_tls_crypt_v2_write_client_k= ey_file),
diff --git a/tests/unit_tests/openvpn/test_user_p= ass.c b/tests/unit_tests/openvpn/test_user_pass.c
index 74f= 67a7..460b37f 100644
--- a/tests/unit_tests/openvpn/test_us= er_pass.c
+++ b/tests/unit_tests/openvpn/test_user_pass.c
@@ -64,19 +64,16 @@
assert_true(0);
}
bool
-management_query_user_pass(struct management *man,- str= uct user_pass *up,
- = const char *type,
- const unsigned int flags,
- = const char *static_challenge)
+management_query_user_pass(struct management *man, struct user= _pass *up, const char *type,
+ const unsigned int flags, const char *s= tatic_challenge)
{
assert_true(0);
return false;
}
/* stu= bs for some unused functions instead of pulling in too many dependencies */=
int
-= parse_line(const char *line, char **p, const int n, const char *file,
- const int line_n= um, int msglevel, struct gc_arena *gc)
+parse_line(const char *line, char **p, const int n, cons= t char *file, const int line_num,
+ int msglevel, struct gc_arena *gc)
{

assert_true(0);
return 0;
@@ -162,7 +159,9 @@
/*FIXME: query_user_e= xec() called even though nothing queued */
will_return= (query_user_exec_builtin, true);
/* FIXME? content aft= er first two lines just ignored */
- assert_true(get_user_pass_cr(&up, "#iuser and =EC= =BB=A4=EB=AE=A4=EB=8B=88=ED=8B=B0\n//ipassw=C3=B6rd!\nsome other content\nn= ot relevant", "UT", flags, NULL));
+ assert_true(
+ get_user_pass_cr(&up, "#iuser a= nd =EC=BB=A4=EB=AE=A4=EB=8B=88=ED=8B=B0\n//ipassw=C3=B6rd!\nsome other cont= ent\nnot relevant",
+ "UT", flags, NULL));
assert_true(up.defined);

assert_string_equal(up= .username, "#iuser and =EC=BB=A4=EB=AE=A4=EB=8B=88=ED=8B=B0");
assert_string_equal(up.password, "//ipassw=C3=B6rd!= ");
@@ -250,7 +249,7 @@
unsigned = int flags =3D 0;

char authfile[PATH_= MAX] =3D { 0 };
- op= envpn_test_get_srcdir_dir(authfile, PATH_MAX, "input/user_pass.txt&quo= t; );
+ openvpn_te= st_get_srcdir_dir(authfile, PATH_MAX, "input/user_pass.txt");

/*FIXME: query_user_exec() called even = though nothing queued */
will_return(query_user_exec_b= uiltin, true);
@@ -292,7 +291,8 @@
con= st char *challenge =3D "CRV1:R,E:Om01u7Fh4LrGBS7uh0SWmzwabUiGiW6l:Y3Ix= :Please enter token PIN";
unsigned int flags =3D = GET_USER_PASS_DYNAMIC_CHALLENGE;

- expect_string(query_user_exec_builtin, que= ry_user[i].prompt, "CHALLENGE: Please enter token PIN");+ expect_string(query_user= _exec_builtin, query_user[i].prompt,
+ "CHALLENGE: Please enter token PIN&= quot;);
will_return(query_user_exec_builtin, "cha= llenge_response");
will_return(query_user_exec_bu= iltin, true);
assert_true(get_user_pass_cr(&up, NU= LL, "UT", flags, challenge));
@@ -314,7 +314,8 @@=
expect_string(query_user_exec_builtin, query_user[i].= prompt, "Enter UT Password:");
will_return(q= uery_user_exec_builtin, "cpassword");
will_r= eturn(query_user_exec_builtin, true);
- expect_string(query_user_exec_builtin, query_user[i].pr= ompt, "CHALLENGE: Please enter token PIN");
+ expect_string(query_user_exec_builtin= , query_user[i].prompt,
+ "CHALLENGE: Please enter token PIN");
will_return(query_user_exec_builtin, "challenge_respon= se");
will_return(query_user_exec_builtin, true);=
assert_true(get_user_pass_cr(&up, NULL, "UT&= quot;, flags, challenge));
@@ -332,7 +333,8 @@
expect_string(query_user_exec_builtin, query_user[i].prompt, "= ;Enter UT Password:");

will_return(query_user_exe= c_builtin, "c1password");
will_return(query_= user_exec_builtin, true);
- expect_string(query_user_exec_builtin, query_user[i].prompt, "= CHALLENGE: Please enter token PIN");
+ expect_string(query_user_exec_builtin, query_user= [i].prompt,
+ = "CHALLENGE: Please enter token PIN");
= will_return(query_user_exec_builtin, "0123456");
will_return(query_user_exec_builtin, true);

a= ssert_true(get_user_pass_cr(&up, NULL, "UT", flags, challenge= ));
@@ -343,11 +345,12 @@

reset_user_pass(&up);


- flags =3D GET_USER_PASS_STATIC_CHALLENGE|GE= T_USER_PASS_INLINE_CREDS;
+ flags =3D GET_USER_PASS_STATIC_CHALLENGE | GET_USER_PASS_INLINE_C= REDS;

/*FIXME: query_user_exec() cal= led even though nothing queued */
will_return(query_us= er_exec_builtin, true);
- expect_string(query_user_exec_builtin, query_user[i].prompt, "CH= ALLENGE: Please enter token PIN");
+ expect_string(query_user_exec_builtin, query_user[i= ].prompt,
+ = "CHALLENGE: Please enter token PIN");
= will_return(query_user_exec_builtin, "challenge_response");
will_return(query_user_exec_builtin, true);
assert_true(get_user_pass_cr(&up, "iuser\nipassword",= "UT", flags, challenge));

diff --git a/tests/uni= t_tests/plugins/auth-pam/test_search_and_replace.c b/tests/unit_tests/plugi= ns/auth-pam/test_search_and_replace.c
index 50b241d..a861bf= d 100644
--- a/tests/unit_tests/plugins/auth-pam/test_searc= h_and_replace.c
+++ b/tests/unit_tests/plugins/auth-pam/tes= t_search_and_replace.c
@@ -12,7 +12,6 @@
s= tatic void
pass_any_null_param__returns_null(void **state)=
{
-
char DUMMY[] =3D "DUMMY";

assert_null(searchandreplace(NULL, DUMMY, DUMMY));
@@ -23,7 +22,6 @@
static void
= pass_any_empty_string__returns_null(void **state)
{
-
char = DUMMY[] =3D "DUMMY";
char EMPTY[] =3D "= ";


To view, visi= t change = 791. To unsubscribe, or for help writing mail filters, visit settings.

Gerrit-Project: openvpn
Gerrit-Branch: master
Gerrit-Change-Id: I2566ad493629e1f5fdfa6f6483b= 8973463404e3e
Gerrit-Change-Number: 791
Gerrit-PatchSet: 23
Gerrit-Owner: flichtenheld <frank@...2723...= .>
Gerrit-Reviewer: plaisthos <arne-openvpn@...1186...= .1227...>
Gerrit-CC: cron2 <gert@...1296...>
Gerrit-CC: openvpn-devel <openvpn-devel@...1484...= ts.sourceforge.net>
Gerrit-CC: ordex <antonio@...2726...>
Gerrit-Attention: plaisthos <arne-openvpn@...220...= ..1227...>
Gerrit-Attention: cron2 <gert@...1296...>= ;
Gerrit-Attention: ordex <antonio@...2726...= >
Gerrit-MessageType: newpatchset
--aFNSkfgjrpU=--