]> git.ipfire.org Git - thirdparty/openvpn.git/blame - src/openvpn/init.c
management: >REMOTE operation would overwrite ce change indicator
[thirdparty/openvpn.git] / src / openvpn / init.c
CommitLineData
6fbf66fa
JY
1/*
2 * OpenVPN -- An application to securely tunnel IP networks
3 * over a single TCP/UDP port, with support for SSL/TLS-based
4 * session authentication and key exchange,
5 * packet encryption, packet authentication, and
6 * packet compression.
7 *
58716979 8 * Copyright (C) 2002-2017 OpenVPN Technologies, Inc. <sales@openvpn.net>
6fbf66fa
JY
9 *
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License version 2
12 * as published by the Free Software Foundation.
13 *
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License
20 * along with this program (see the file COPYING included with this
21 * distribution); if not, write to the Free Software Foundation, Inc.,
22 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23 */
24
c110b289
ABL
25#ifdef HAVE_CONFIG_H
26#include "config.h"
27#elif defined(_MSC_VER)
28#include "config-msvc.h"
29#endif
30
6fbf66fa
JY
31#include "syshead.h"
32
c5931897
CH
33#ifdef ENABLE_SYSTEMD
34#include <systemd/sd-daemon.h>
35#endif
36
6fbf66fa
JY
37#include "win32.h"
38#include "init.h"
39#include "sig.h"
40#include "occ.h"
41#include "list.h"
42#include "otime.h"
43#include "pool.h"
44#include "gremlin.h"
ce98fd24 45#include "pkcs11.h"
6add6b2f 46#include "ps.h"
e12fe286 47#include "lladdr.h"
e7a65dfb 48#include "ping.h"
ffea644c 49#include "mstats.h"
63dc03d0 50#include "ssl_verify.h"
c6e24fa3 51#include "tls_crypt.h"
2191c471 52#include "forward-inline.h"
6fbf66fa
JY
53
54#include "memdbg.h"
55
56#include "occ-inline.h"
57
0c9eb1d3
JY
58static struct context *static_context; /* GLOBAL */
59
6fbf66fa
JY
60/*
61 * Crypto initialization flags
62 */
63#define CF_LOAD_PERSISTED_PACKET_ID (1<<0)
64#define CF_INIT_TLS_MULTI (1<<1)
65#define CF_INIT_TLS_AUTH_STANDALONE (1<<2)
66
81d882d5 67static void do_init_first_time(struct context *c);
6fbf66fa
JY
68
69void
81d882d5 70context_clear(struct context *c)
6fbf66fa 71{
81d882d5 72 CLEAR(*c);
6fbf66fa
JY
73}
74
75void
81d882d5 76context_clear_1(struct context *c)
6fbf66fa 77{
81d882d5 78 CLEAR(c->c1);
6fbf66fa
JY
79}
80
81void
81d882d5 82context_clear_2(struct context *c)
6fbf66fa 83{
81d882d5 84 CLEAR(c->c2);
6fbf66fa
JY
85}
86
87void
81d882d5 88context_clear_all_except_first_time(struct context *c)
6fbf66fa 89{
81d882d5
DS
90 const bool first_time_save = c->first_time;
91 const struct context_persist cpsave = c->persist;
92 context_clear(c);
93 c->first_time = first_time_save;
94 c->persist = cpsave;
6fbf66fa
JY
95}
96
97/*
4e9a51d7
JY
98 * Should be called after options->ce is modified at the top
99 * of a SIGUSR1 restart.
6fbf66fa
JY
100 */
101static void
81d882d5 102update_options_ce_post(struct options *options)
6fbf66fa 103{
4e9a51d7 104#if P2MP
81d882d5
DS
105 /*
106 * In pull mode, we usually import --ping/--ping-restart parameters from
107 * the server. However we should also set an initial default --ping-restart
108 * for the period of time before we pull the --ping-restart parameter
109 * from the server.
110 */
111 if (options->pull
112 && options->ping_rec_timeout_action == PING_UNDEF
113 && proto_is_dgram(options->ce.proto))
4e9a51d7 114 {
81d882d5
DS
115 options->ping_rec_timeout = PRE_PULL_INITIAL_PING_RESTART;
116 options->ping_rec_timeout_action = PING_RESTART;
4e9a51d7
JY
117 }
118#endif
4e9a51d7 119}
6fbf66fa 120
af1bf85a 121#ifdef ENABLE_MANAGEMENT
3cf6c932 122static bool
81d882d5 123management_callback_proxy_cmd(void *arg, const char **p)
3cf6c932 124{
81d882d5
DS
125 struct context *c = arg;
126 struct connection_entry *ce = &c->options.ce;
127 struct gc_arena *gc = &c->c2.gc;
128 bool ret = false;
3cf6c932 129
81d882d5
DS
130 update_time();
131 if (streq(p[1], "NONE"))
132 {
133 ret = true;
134 }
135 else if (p[2] && p[3])
af1bf85a 136 {
81d882d5 137 if (streq(p[1], "HTTP"))
af1bf85a 138 {
81d882d5
DS
139 struct http_proxy_options *ho;
140 if (ce->proto != PROTO_TCP && ce->proto != PROTO_TCP_CLIENT)
e719a053 141 {
81d882d5
DS
142 msg(M_WARN, "HTTP proxy support only works for TCP based connections");
143 return false;
af1bf85a 144 }
81d882d5
DS
145 ho = init_http_proxy_options_once(&ce->http_proxy_options, gc);
146 ho->server = string_alloc(p[2], gc);
147 ho->port = string_alloc(p[3], gc);
148 ho->auth_retry = (p[4] && streq(p[4], "nct") ? PAR_NCT : PAR_ALL);
149 ret = true;
af1bf85a 150 }
81d882d5 151 else if (streq(p[1], "SOCKS"))
af1bf85a 152 {
81d882d5
DS
153 ce->socks_proxy_server = string_alloc(p[2], gc);
154 ce->socks_proxy_port = p[3];
155 ret = true;
af1bf85a 156 }
3cf6c932 157 }
81d882d5
DS
158 else
159 {
160 msg(M_WARN, "Bad proxy command");
161 }
3cf6c932 162
81d882d5 163 ce->flags &= ~CE_MAN_QUERY_PROXY;
3cf6c932 164
81d882d5 165 return ret;
3cf6c932
JY
166}
167
168static bool
81d882d5
DS
169ce_management_query_proxy(struct context *c)
170{
171 const struct connection_list *l = c->options.connection_list;
172 struct connection_entry *ce = &c->options.ce;
173 struct gc_arena gc;
174 bool ret = true;
175
176 update_time();
177 if (management)
178 {
179 gc = gc_new();
180 {
181 struct buffer out = alloc_buf_gc(256, &gc);
182 buf_printf(&out, ">PROXY:%u,%s,%s", (l ? l->current : 0) + 1,
183 (proto_is_udp(ce->proto) ? "UDP" : "TCP"), np(ce->remote));
184 management_notify_generic(management, BSTR(&out));
185 }
186 ce->flags |= CE_MAN_QUERY_PROXY;
187 while (ce->flags & CE_MAN_QUERY_PROXY)
188 {
189 management_event_loop_n_seconds(management, 1);
190 if (IS_SIG(c))
af1bf85a 191 {
81d882d5
DS
192 ret = false;
193 break;
af1bf85a
HH
194 }
195 }
81d882d5 196 gc_free(&gc);
3cf6c932 197 }
af1bf85a 198
81d882d5 199 return ret;
3cf6c932
JY
200}
201
3cf6c932 202
54561af6 203static bool
81d882d5
DS
204management_callback_remote_cmd(void *arg, const char **p)
205{
206 struct context *c = (struct context *) arg;
207 struct connection_entry *ce = &c->options.ce;
208 int ret = false;
209 if (p[1] && ((ce->flags>>CE_MAN_QUERY_REMOTE_SHIFT)&CE_MAN_QUERY_REMOTE_MASK) == CE_MAN_QUERY_REMOTE_QUERY)
210 {
211 int flags = 0;
212 if (!strcmp(p[1], "ACCEPT"))
213 {
214 flags = CE_MAN_QUERY_REMOTE_ACCEPT;
215 ret = true;
216 }
217 else if (!strcmp(p[1], "SKIP"))
218 {
219 flags = CE_MAN_QUERY_REMOTE_SKIP;
220 ret = true;
221 }
222 else if (!strcmp(p[1], "MOD") && p[2] && p[3])
223 {
224 if (strlen(p[2]) < RH_HOST_LEN && strlen(p[3]) < RH_PORT_LEN)
225 {
226 struct remote_host_store *rhs = c->options.rh_store;
227 if (!rhs)
228 {
229 ALLOC_OBJ_CLEAR_GC(rhs, struct remote_host_store, &c->options.gc);
230 c->options.rh_store = rhs;
231 }
232 strncpynt(rhs->host, p[2], RH_HOST_LEN);
233 strncpynt(rhs->port, p[3], RH_PORT_LEN);
234
235 ce->remote = rhs->host;
236 ce->remote_port = rhs->port;
237 flags = CE_MAN_QUERY_REMOTE_MOD;
238 ret = true;
239 }
240 }
241 if (ret)
242 {
243 ce->flags &= ~(CE_MAN_QUERY_REMOTE_MASK<<CE_MAN_QUERY_REMOTE_SHIFT);
244 ce->flags |= ((flags&CE_MAN_QUERY_REMOTE_MASK)<<CE_MAN_QUERY_REMOTE_SHIFT);
245 }
246 }
247 return ret;
54561af6
JY
248}
249
250static bool
81d882d5
DS
251ce_management_query_remote(struct context *c)
252{
253 struct gc_arena gc = gc_new();
254 volatile struct connection_entry *ce = &c->options.ce;
e81f313a
DS
255 int ce_changed = true; /* presume the connection entry will be changed */
256
81d882d5
DS
257 update_time();
258 if (management)
259 {
260 struct buffer out = alloc_buf_gc(256, &gc);
e81f313a
DS
261
262 buf_printf(&out, ">REMOTE:%s,%s,%s", np(ce->remote), ce->remote_port,
263 proto2ascii(ce->proto, ce->af, false));
81d882d5 264 management_notify_generic(management, BSTR(&out));
e81f313a
DS
265
266 ce->flags &= ~(CE_MAN_QUERY_REMOTE_MASK << CE_MAN_QUERY_REMOTE_SHIFT);
267 ce->flags |= (CE_MAN_QUERY_REMOTE_QUERY << CE_MAN_QUERY_REMOTE_SHIFT);
268 while (((ce->flags >> CE_MAN_QUERY_REMOTE_SHIFT)
269 & CE_MAN_QUERY_REMOTE_MASK) == CE_MAN_QUERY_REMOTE_QUERY)
81d882d5
DS
270 {
271 management_event_loop_n_seconds(management, 1);
272 if (IS_SIG(c))
273 {
e81f313a 274 ce_changed = false; /* connection entry have not been set */
81d882d5
DS
275 break;
276 }
277 }
278 }
e81f313a
DS
279 gc_free(&gc);
280
281 if (ce_changed)
81d882d5 282 {
e81f313a
DS
283 /* If it is likely a connection entry was modified,
284 * check what changed in the flags and that it was not skipped
285 */
286 const int flags = ((ce->flags >> CE_MAN_QUERY_REMOTE_SHIFT)
287 & CE_MAN_QUERY_REMOTE_MASK);
288 ce_changed = (flags != CE_MAN_QUERY_REMOTE_SKIP);
81d882d5 289 }
e81f313a 290 return ce_changed;
54561af6 291}
cf93f0e0 292#endif /* ENABLE_MANAGEMENT */
54561af6 293
4e9a51d7
JY
294/*
295 * Initialize and possibly randomize connection list.
296 */
297static void
81d882d5 298init_connection_list(struct context *c)
4e9a51d7 299{
81d882d5 300 struct connection_list *l = c->options.connection_list;
23d61c56 301
81d882d5
DS
302 l->current = -1;
303 if (c->options.remote_random)
6fbf66fa 304 {
81d882d5
DS
305 int i;
306 for (i = 0; i < l->len; ++i)
23d61c56 307 {
81d882d5
DS
308 const int j = get_random() % l->len;
309 if (i != j)
23d61c56 310 {
81d882d5
DS
311 struct connection_entry *tmp;
312 tmp = l->array[i];
313 l->array[i] = l->array[j];
314 l->array[j] = tmp;
23d61c56
AS
315 }
316 }
6fbf66fa 317 }
4e9a51d7
JY
318}
319
23d61c56
AS
320/*
321 * Clear the remote address list
322 */
81d882d5
DS
323static void
324clear_remote_addrlist(struct link_socket_addr *lsa, bool free)
23d61c56 325{
e719a053 326 if (lsa->remote_list && free)
81d882d5
DS
327 {
328 freeaddrinfo(lsa->remote_list);
329 }
23d61c56
AS
330 lsa->remote_list = NULL;
331 lsa->current_remote = NULL;
332}
333
4e9a51d7
JY
334/*
335 * Increment to next connection entry
336 */
337static void
81d882d5
DS
338next_connection_entry(struct context *c)
339{
340 struct connection_list *l = c->options.connection_list;
341 bool ce_defined;
342 struct connection_entry *ce;
343 int n_cycles = 0;
344
345 do {
346 ce_defined = true;
347 if (c->options.no_advance && l->current >= 0)
348 {
349 c->options.no_advance = false;
350 }
23d61c56 351 else
81d882d5
DS
352 {
353 /* Check if there is another resolved address to try for
354 * the current connection */
355 if (c->c1.link_socket_addr.current_remote
356 && c->c1.link_socket_addr.current_remote->ai_next)
357 {
23d61c56 358 c->c1.link_socket_addr.current_remote =
81d882d5
DS
359 c->c1.link_socket_addr.current_remote->ai_next;
360 }
361 else
362 {
363 /* FIXME (schwabe) fix the persist-remote-ip option for real,
364 * this is broken probably ever since connection lists and multiple
365 * remote existed
366 */
367 if (!c->options.persist_remote_ip)
368 {
369 /* close_instance should have cleared the addrinfo objects */
370 ASSERT(c->c1.link_socket_addr.current_remote == NULL);
371 ASSERT(c->c1.link_socket_addr.remote_list == NULL);
372 }
373 else
374 {
375 c->c1.link_socket_addr.current_remote =
376 c->c1.link_socket_addr.remote_list;
377 }
378
379 /*
380 * Increase the number of connection attempts
381 * If this is connect-retry-max * size(l)
382 * OpenVPN will quit
383 */
384
385 c->options.unsuccessful_attempts++;
386
387 if (++l->current >= l->len)
388 {
389
390 l->current = 0;
391 if (++n_cycles >= 2)
392 {
393 msg(M_FATAL, "No usable connection profiles are present");
394 }
395 }
396 }
397 }
3cf6c932 398
81d882d5 399 ce = l->array[l->current];
3cf6c932 400
81d882d5
DS
401 if (ce->flags & CE_DISABLED)
402 {
403 ce_defined = false;
404 }
3cf6c932 405
81d882d5 406 c->options.ce = *ce;
cf93f0e0 407#ifdef ENABLE_MANAGEMENT
81d882d5
DS
408 if (ce_defined && management && management_query_remote_enabled(management))
409 {
410 /* allow management interface to override connection entry details */
411 ce_defined = ce_management_query_remote(c);
412 if (IS_SIG(c))
413 {
414 break;
415 }
416 }
417 else
cf93f0e0 418#endif
3cf6c932 419
af1bf85a 420#ifdef ENABLE_MANAGEMENT
81d882d5 421 if (ce_defined && management && management_query_proxy_enabled(management))
23d61c56 422 {
81d882d5
DS
423 ce_defined = ce_management_query_proxy(c);
424 if (IS_SIG(c))
425 {
426 break;
427 }
23d61c56 428 }
3cf6c932 429#endif
81d882d5 430 } while (!ce_defined);
23d61c56 431
81d882d5
DS
432 /* Check if this connection attempt would bring us over the limit */
433 if (c->options.connect_retry_max > 0
434 && c->options.unsuccessful_attempts > (l->len * c->options.connect_retry_max))
435 {
436 msg(M_FATAL, "All connections have been connect-retry-max (%d) times unsuccessful, exiting",
437 c->options.connect_retry_max);
438 }
439 update_options_ce_post(&c->options);
6fbf66fa
JY
440}
441
92bbb061
JY
442/*
443 * Query for private key and auth-user-pass username/passwords
444 */
315f6fbc 445void
81d882d5 446init_query_passwords(const struct context *c)
92bbb061 447{
ec828db6 448#ifdef ENABLE_CRYPTO
81d882d5
DS
449 /* Certificate password input */
450 if (c->options.key_pass_file)
451 {
452 pem_password_setup(c->options.key_pass_file);
453 }
92bbb061 454#endif
81d882d5 455
92bbb061 456#if P2MP
81d882d5
DS
457 /* Auth user/pass input */
458 if (c->options.auth_user_pass_file)
eab3e22f
JY
459 {
460#ifdef ENABLE_CLIENT_CR
81d882d5 461 auth_user_pass_setup(c->options.auth_user_pass_file, &c->options.sc_info);
eab3e22f 462#else
81d882d5 463 auth_user_pass_setup(c->options.auth_user_pass_file, NULL);
eab3e22f
JY
464#endif
465 }
92bbb061
JY
466#endif
467}
468
4e9a51d7
JY
469/*
470 * Initialize/Uninitialize HTTP or SOCKS proxy
471 */
472
4e9a51d7 473static void
81d882d5 474uninit_proxy_dowork(struct context *c)
4e9a51d7 475{
81d882d5 476 if (c->c1.http_proxy_owned && c->c1.http_proxy)
4e9a51d7 477 {
81d882d5
DS
478 http_proxy_close(c->c1.http_proxy);
479 c->c1.http_proxy = NULL;
480 c->c1.http_proxy_owned = false;
4e9a51d7 481 }
81d882d5 482 if (c->c1.socks_proxy_owned && c->c1.socks_proxy)
4e9a51d7 483 {
81d882d5
DS
484 socks_proxy_close(c->c1.socks_proxy);
485 c->c1.socks_proxy = NULL;
486 c->c1.socks_proxy_owned = false;
4e9a51d7 487 }
4e9a51d7
JY
488}
489
490static void
81d882d5 491init_proxy_dowork(struct context *c)
6fbf66fa 492{
81d882d5 493 bool did_http = false;
f214bb21 494
81d882d5 495 uninit_proxy_dowork(c);
4e9a51d7 496
81d882d5 497 if (c->options.ce.http_proxy_options)
4e9a51d7 498 {
81d882d5
DS
499 /* Possible HTTP proxy user/pass input */
500 c->c1.http_proxy = http_proxy_new(c->options.ce.http_proxy_options);
501 if (c->c1.http_proxy)
502 {
503 did_http = true;
504 c->c1.http_proxy_owned = true;
505 }
4e9a51d7 506 }
4e9a51d7 507
a4b8f653 508 if (!did_http && c->options.ce.socks_proxy_server)
4e9a51d7 509 {
81d882d5
DS
510 c->c1.socks_proxy = socks_proxy_new(c->options.ce.socks_proxy_server,
511 c->options.ce.socks_proxy_port,
512 c->options.ce.socks_proxy_authfile);
513 if (c->c1.socks_proxy)
514 {
515 c->c1.socks_proxy_owned = true;
516 }
4e9a51d7 517 }
4e9a51d7
JY
518}
519
520static void
81d882d5 521init_proxy(struct context *c)
4e9a51d7 522{
81d882d5 523 init_proxy_dowork(c);
4e9a51d7
JY
524}
525
526static void
81d882d5 527uninit_proxy(struct context *c)
4e9a51d7 528{
81d882d5 529 uninit_proxy_dowork(c);
4e9a51d7
JY
530}
531
4e9a51d7 532void
81d882d5 533context_init_1(struct context *c)
4e9a51d7 534{
81d882d5 535 context_clear_1(c);
6fbf66fa 536
81d882d5 537 packet_id_persist_init(&c->c1.pid_persist);
4e9a51d7 538
81d882d5 539 init_connection_list(c);
6fbf66fa 540
ce98fd24 541#if defined(ENABLE_PKCS11)
81d882d5
DS
542 if (c->first_time)
543 {
544 int i;
545 pkcs11_initialize(true, c->options.pkcs11_pin_cache_period);
546 for (i = 0; i<MAX_PARMS && c->options.pkcs11_providers[i] != NULL; i++)
547 pkcs11_addProvider(c->options.pkcs11_providers[i], c->options.pkcs11_protected_authentication[i],
548 c->options.pkcs11_private_mode[i], c->options.pkcs11_cert_private[i]);
549 }
ce98fd24 550#endif
984cf003 551
c67d59cd 552#if 0 /* test get_user_pass with GET_USER_PASS_NEED_OK flag */
81d882d5
DS
553 {
554 /*
555 * In the management interface, you can okay the request by entering "needok token-insertion-request ok"
556 */
557 struct user_pass up;
558 CLEAR(up);
559 strcpy(up.username, "Please insert your cryptographic token"); /* put the high-level message in up.username */
560 get_user_pass(&up, NULL, "token-insertion-request", GET_USER_PASS_MANAGEMENT|GET_USER_PASS_NEED_OK);
561 msg(M_INFO, "RET:%s", up.password); /* will return the third argument to management interface
562 * 'needok' command, usually 'ok' or 'cancel'. */
563 }
dd1047f5
JY
564#endif
565
6fbf66fa
JY
566}
567
568void
81d882d5 569context_gc_free(struct context *c)
6fbf66fa 570{
81d882d5
DS
571 gc_free(&c->c2.gc);
572 gc_free(&c->options.gc);
573 gc_free(&c->gc);
6fbf66fa
JY
574}
575
6add6b2f
JY
576#if PORT_SHARE
577
578static void
81d882d5 579close_port_share(void)
6add6b2f 580{
81d882d5 581 if (port_share)
6add6b2f 582 {
81d882d5
DS
583 port_share_close(port_share);
584 port_share = NULL;
6add6b2f
JY
585 }
586}
587
588static void
81d882d5 589init_port_share(struct context *c)
6add6b2f 590{
81d882d5 591 if (!port_share && (c->options.port_share_host && c->options.port_share_port))
6add6b2f 592 {
81d882d5
DS
593 port_share = port_share_open(c->options.port_share_host,
594 c->options.port_share_port,
595 MAX_RW_SIZE_LINK(&c->c2.frame),
596 c->options.port_share_journal_dir);
597 if (port_share == NULL)
598 {
599 msg(M_FATAL, "Fatal error: Port sharing failed");
600 }
6add6b2f
JY
601 }
602}
603
81d882d5 604#endif /* if PORT_SHARE */
6add6b2f 605
6fbf66fa 606bool
81d882d5 607init_static(void)
6fbf66fa 608{
81d882d5 609 /* configure_path (); */
c67d59cd 610
9b33b5a4 611#if defined(ENABLE_CRYPTO) && defined(DMALLOC)
81d882d5 612 crypto_init_dmalloc();
6fbf66fa
JY
613#endif
614
81d882d5
DS
615 init_random_seed(); /* init random() function, only used as
616 * source for weak random numbers */
617 error_reset(); /* initialize error.c */
618 reset_check_status(); /* initialize status check code in socket.c */
6fbf66fa 619
445b192a 620#ifdef _WIN32
81d882d5 621 init_win32();
6fbf66fa
JY
622#endif
623
624#ifdef OPENVPN_DEBUG_COMMAND_LINE
81d882d5
DS
625 {
626 int i;
627 for (i = 0; i < argc; ++i)
628 msg(M_INFO, "argv[%d] = '%s'", i, argv[i]);
629 }
6fbf66fa
JY
630#endif
631
81d882d5 632 update_time();
6fbf66fa 633
9b33b5a4 634#ifdef ENABLE_CRYPTO
81d882d5 635 init_ssl_lib();
6fbf66fa 636
81d882d5
DS
637 /* init PRNG used for IV generation */
638 /* When forking, copy this to more places in the code to avoid fork
639 * random-state predictability */
640 prng_init(NULL, 0);
6fbf66fa
JY
641#endif
642
643#ifdef PID_TEST
81d882d5
DS
644 packet_id_interactive_test(); /* test the sequence number code */
645 return false;
6fbf66fa
JY
646#endif
647
648#ifdef SCHEDULE_TEST
81d882d5
DS
649 schedule_test();
650 return false;
6fbf66fa
JY
651#endif
652
653#ifdef LIST_TEST
81d882d5
DS
654 list_test();
655 return false;
6fbf66fa
JY
656#endif
657
658#ifdef IFCONFIG_POOL_TEST
81d882d5
DS
659 ifconfig_pool_test(0x0A010004, 0x0A0100FF);
660 return false;
6fbf66fa
JY
661#endif
662
663#ifdef CHARACTER_CLASS_DEBUG
81d882d5
DS
664 character_class_debug();
665 return false;
6fbf66fa
JY
666#endif
667
668#ifdef EXTRACT_X509_FIELD_TEST
81d882d5
DS
669 extract_x509_field_test();
670 return false;
6fbf66fa
JY
671#endif
672
428b8279 673#ifdef TIME_TEST
81d882d5
DS
674 time_test();
675 return false;
428b8279
JY
676#endif
677
6a8ea970 678#ifdef TEST_GET_DEFAULT_GATEWAY
81d882d5
DS
679 {
680 struct route_gateway_info rgi;
681 struct route_ipv6_gateway_info rgi6;
682 get_default_gateway(&rgi);
683 get_default_gateway_ipv6(&rgi6, NULL);
684 print_default_gateway(M_INFO, &rgi, &rgi6);
685 return false;
686 }
6a8ea970
JY
687#endif
688
6cd276ba 689#ifdef GEN_PATH_TEST
81d882d5
DS
690 {
691 struct gc_arena gc = gc_new();
692 const char *fn = gen_path("foo",
693 "bar",
694 &gc);
695 printf("%s\n", fn);
696 gc_free(&gc);
697 }
698 return false;
6cd276ba 699#endif
ddad0a8c 700
6cd276ba 701#ifdef STATUS_PRINTF_TEST
81d882d5
DS
702 {
703 struct gc_arena gc = gc_new();
704 const char *tmp_file = create_temp_file("/tmp", "foo", &gc);
705 struct status_output *so = status_open(tmp_file, 0, -1, NULL, STATUS_OUTPUT_WRITE);
706 status_printf(so, "%s", "foo");
707 status_printf(so, "%s", "bar");
708 if (!status_close(so))
709 {
710 msg(M_WARN, "STATUS_PRINTF_TEST: %s: write error", tmp_file);
711 }
712 gc_free(&gc);
713 }
714 return false;
ddad0a8c
JY
715#endif
716
26bb4c74 717#ifdef ARGV_TEST
81d882d5
DS
718 {
719 void argv_test(void);
720
721 argv_test();
722 return false;
723 }
26bb4c74
JY
724#endif
725
03bfb228 726#ifdef PRNG_TEST
81d882d5
DS
727 {
728 struct gc_arena gc = gc_new();
729 uint8_t rndbuf[8];
730 int i;
731 prng_init("sha1", 16);
732 /*prng_init (NULL, 0);*/
733 const int factor = 1;
734 for (i = 0; i < factor * 8; ++i)
735 {
03bfb228 736#if 1
81d882d5 737 prng_bytes(rndbuf, sizeof(rndbuf));
03bfb228 738#else
81d882d5 739 ASSERT(rand_bytes(rndbuf, sizeof(rndbuf)));
03bfb228 740#endif
81d882d5
DS
741 printf("[%d] %s\n", i, format_hex(rndbuf, sizeof(rndbuf), 0, &gc));
742 }
743 gc_free(&gc);
744 prng_uninit();
745 return false;
746 }
747#endif /* ifdef PRNG_TEST */
03bfb228 748
7e1c085d 749#ifdef BUFFER_LIST_AGGREGATE_TEST
81d882d5
DS
750 /* test buffer_list_aggregate function */
751 {
752 static const char *text[] = {
753 "It was a bright cold day in April, ",
754 "and the clocks were striking ",
755 "thirteen. ",
756 "Winston Smith, ",
757 "his chin nuzzled into his breast in an ",
758 "effort to escape the vile wind, ",
759 "slipped quickly through the glass doors ",
760 "of Victory Mansions, though not quickly ",
761 "enough to prevent a swirl of gritty dust from ",
762 "entering along with him."
763 };
764
765 int iter, listcap;
766 for (listcap = 0; listcap < 12; ++listcap)
767 {
768 for (iter = 0; iter < 512; ++iter)
769 {
770 struct buffer_list *bl = buffer_list_new(listcap);
771 {
772 int i;
773 for (i = 0; i < SIZE(text); ++i)
774 buffer_list_push(bl, (unsigned char *)text[i]);
775 }
776 printf("[cap=%d i=%d] *************************\n", listcap, iter);
777 if (!(iter & 8))
778 {
779 buffer_list_aggregate(bl, iter/2);
780 }
781 if (!(iter & 16))
782 {
783 buffer_list_push(bl, (unsigned char *)"Even more text...");
784 }
785 buffer_list_aggregate(bl, iter);
786 if (!(iter & 1))
787 {
788 buffer_list_push(bl, (unsigned char *)"More text...");
789 }
790 {
791 struct buffer *buf;
792 while ((buf = buffer_list_peek(bl)))
793 {
794 int c;
795 printf("'");
796 while ((c = buf_read_u8(buf)) >= 0)
797 putchar(c);
798 printf("'\n");
799 buffer_list_advance(bl, 0);
800 }
801 }
802 buffer_list_free(bl);
803 }
804 }
805 return false;
806 }
807#endif /* ifdef BUFFER_LIST_AGGREGATE_TEST */
7e1c085d 808
ffea644c 809#ifdef MSTATS_TEST
81d882d5
DS
810 {
811 int i;
812 mstats_open("/dev/shm/mstats.dat");
813 for (i = 0; i < 30; ++i)
814 {
815 mmap_stats->n_clients += 1;
816 mmap_stats->link_write_bytes += 8;
817 mmap_stats->link_read_bytes += 16;
818 sleep(1);
819 }
820 mstats_close();
821 return false;
822 }
ffea644c
JY
823#endif
824
81d882d5 825 return true;
6fbf66fa
JY
826}
827
828void
81d882d5 829uninit_static(void)
6fbf66fa 830{
9b33b5a4 831#ifdef ENABLE_CRYPTO
81d882d5 832 free_ssl_lib();
6835555e 833#endif
ce98fd24 834
ce98fd24 835#ifdef ENABLE_PKCS11
81d882d5 836 pkcs11_terminate();
ce98fd24 837#endif
6fbf66fa 838
6add6b2f 839#if PORT_SHARE
81d882d5 840 close_port_share();
6add6b2f
JY
841#endif
842
ec828db6 843#if defined(MEASURE_TLS_HANDSHAKE_STATS) && defined(ENABLE_CRYPTO)
81d882d5 844 show_tls_performance_stats();
6fbf66fa
JY
845#endif
846}
847
848void
81d882d5 849init_verb_mute(struct context *c, unsigned int flags)
6fbf66fa 850{
81d882d5 851 if (flags & IVM_LEVEL_1)
6fbf66fa 852 {
81d882d5
DS
853 /* set verbosity and mute levels */
854 set_check_status(D_LINK_ERRORS, D_READ_WRITE);
855 set_debug_level(c->options.verbosity, SDL_CONSTRAIN);
856 set_mute_cutoff(c->options.mute);
6fbf66fa
JY
857 }
858
81d882d5
DS
859 /* special D_LOG_RW mode */
860 if (flags & IVM_LEVEL_2)
861 {
862 c->c2.log_rw = (check_debug_level(D_LOG_RW) && !check_debug_level(D_LOG_RW + 1));
863 }
6fbf66fa
JY
864}
865
866/*
867 * Possibly set --dev based on --dev-node.
868 * For example, if --dev-node /tmp/foo/tun, and --dev undefined,
869 * set --dev to tun.
870 */
871void
81d882d5 872init_options_dev(struct options *options)
6fbf66fa 873{
81d882d5
DS
874 if (!options->dev && options->dev_node)
875 {
876 char *dev_node = string_alloc(options->dev_node, NULL); /* POSIX basename() implementaions may modify its arguments */
877 options->dev = basename(dev_node);
878 }
6fbf66fa
JY
879}
880
881bool
81d882d5 882print_openssl_info(const struct options *options)
6fbf66fa 883{
81d882d5
DS
884 /*
885 * OpenSSL info print mode?
886 */
9b33b5a4 887#ifdef ENABLE_CRYPTO
81d882d5
DS
888 if (options->show_ciphers || options->show_digests || options->show_engines
889 || options->show_tls_ciphers || options->show_curves)
6fbf66fa 890 {
81d882d5
DS
891 if (options->show_ciphers)
892 {
893 show_available_ciphers();
894 }
895 if (options->show_digests)
896 {
897 show_available_digests();
898 }
899 if (options->show_engines)
900 {
901 show_available_engines();
902 }
903 if (options->show_tls_ciphers)
904 {
905 show_available_tls_ciphers(options->cipher_list);
906 }
907 if (options->show_curves)
908 {
909 show_available_curves();
910 }
911 return true;
6fbf66fa 912 }
81d882d5
DS
913#endif /* ifdef ENABLE_CRYPTO */
914 return false;
6fbf66fa
JY
915}
916
917/*
918 * Static pre-shared key generation mode?
919 */
920bool
81d882d5 921do_genkey(const struct options *options)
6fbf66fa 922{
9b33b5a4 923#ifdef ENABLE_CRYPTO
81d882d5 924 if (options->genkey)
6fbf66fa 925 {
81d882d5 926 int nbits_written;
6fbf66fa 927
81d882d5
DS
928 notnull(options->shared_secret_file,
929 "shared secret output file (--secret)");
6fbf66fa 930
81d882d5
DS
931 if (options->mlock) /* should we disable paging? */
932 {
933 platform_mlockall(true);
934 }
6fbf66fa 935
81d882d5 936 nbits_written = write_key_file(2, options->shared_secret_file);
6fbf66fa 937
81d882d5
DS
938 msg(D_GENKEY | M_NOPREFIX,
939 "Randomly generated %d bit key written to %s", nbits_written,
940 options->shared_secret_file);
941 return true;
6fbf66fa
JY
942 }
943#endif
81d882d5 944 return false;
6fbf66fa
JY
945}
946
947/*
948 * Persistent TUN/TAP device management mode?
949 */
950bool
81d882d5 951do_persist_tuntap(const struct options *options)
6fbf66fa 952{
81d882d5 953 if (options->persist_config)
6fbf66fa 954 {
81d882d5
DS
955 /* sanity check on options for --mktun or --rmtun */
956 notnull(options->dev, "TUN/TAP device (--dev)");
957 if (options->ce.remote || options->ifconfig_local
958 || options->ifconfig_remote_netmask
9b33b5a4 959#ifdef ENABLE_CRYPTO
81d882d5
DS
960 || options->shared_secret_file
961 || options->tls_server || options->tls_client
6fbf66fa 962#endif
81d882d5
DS
963 )
964 {
965 msg(M_FATAL|M_OPTERR,
966 "options --mktun or --rmtun should only be used together with --dev");
967 }
4ad2b65d 968#ifdef ENABLE_FEATURE_TUN_PERSIST
81d882d5
DS
969 tuncfg(options->dev, options->dev_type, options->dev_node,
970 options->persist_mode,
971 options->username, options->groupname, &options->tuntap_options);
972 if (options->persist_mode && options->lladdr)
973 {
974 set_lladdr(options->dev, options->lladdr, NULL);
975 }
976 return true;
977#else /* ifdef ENABLE_FEATURE_TUN_PERSIST */
978 msg( M_FATAL|M_OPTERR,
979 "options --mktun and --rmtun are not available on your operating "
980 "system. Please check 'man tun' (or 'tap'), whether your system "
981 "supports using 'ifconfig %s create' / 'destroy' to create/remove "
982 "persistant tunnel interfaces.", options->dev );
6fbf66fa 983#endif
4ad2b65d 984 }
81d882d5 985 return false;
6fbf66fa
JY
986}
987
988/*
989 * Should we become a daemon?
990 * Return true if we did it.
991 */
da9b2927 992bool
81d882d5 993possibly_become_daemon(const struct options *options)
6fbf66fa 994{
81d882d5 995 bool ret = false;
7660bba1
CH
996
997#ifdef ENABLE_SYSTEMD
81d882d5
DS
998 /* return without forking if we are running from systemd */
999 if (sd_notify(0, "READY=0") > 0)
1000 {
1001 return ret;
1002 }
7660bba1
CH
1003#endif
1004
81d882d5 1005 if (options->daemon)
6fbf66fa 1006 {
81d882d5
DS
1007 ASSERT(!options->inetd);
1008 /* Don't chdir immediately, but the end of the init sequence, if needed */
1009 if (daemon(1, options->log) < 0)
1010 {
1011 msg(M_ERR, "daemon() failed or unsupported");
1012 }
1013 restore_signal_state();
1014 if (options->log)
1015 {
1016 set_std_files_to_null(true);
1017 }
6835555e 1018
81d882d5 1019 ret = true;
6fbf66fa 1020 }
81d882d5 1021 return ret;
6fbf66fa
JY
1022}
1023
1024/*
99385447 1025 * Actually do UID/GID downgrade, chroot and SELinux context switching, if requested.
6fbf66fa
JY
1026 */
1027static void
81d882d5 1028do_uid_gid_chroot(struct context *c, bool no_delay)
6fbf66fa 1029{
81d882d5
DS
1030 static const char why_not[] = "will be delayed because of --client, --pull, or --up-delay";
1031 struct context_0 *c0 = c->c0;
6fbf66fa 1032
81d882d5 1033 if (c0 && !c0->uid_gid_chroot_set)
6fbf66fa 1034 {
81d882d5
DS
1035 /* chroot if requested */
1036 if (c->options.chroot_dir)
1037 {
1038 if (no_delay)
65140a3a
DS
1039 {
1040#ifdef ENABLE_SYSTEMD
81d882d5
DS
1041 /* If OpenVPN is started by systemd, the OpenVPN process needs
1042 * to provide a preliminary status report to systemd. This is
1043 * needed as $NOTIFY_SOCKET will not be available inside the
1044 * chroot, which sd_notify()/sd_notifyf() depends on.
1045 *
1046 * This approach is the simplest and the most non-intrusive
1047 * solution right before the 2.4_rc2 release.
1048 *
1049 * TODO: Consider altnernative solutions - bind mount?
1050 * systemd does not grok OpenVPN configuration files, thus cannot
1051 * have a sane way to know if OpenVPN will chroot or not and to
1052 * which subdirectory it will chroot into.
1053 */
1054 sd_notifyf(0, "READY=1\n"
1055 "STATUS=Entering chroot, most of the init completed successfully\n"
1056 "MAINPID=%lu", (unsigned long) getpid());
1057#endif
1058 platform_chroot(c->options.chroot_dir);
1059 }
1060 else if (c->first_time)
1061 {
1062 msg(M_INFO, "NOTE: chroot %s", why_not);
1063 }
1064 }
1065
1066 /* set user and/or group if we want to setuid/setgid */
1067 if (c0->uid_gid_specified)
1068 {
1069 if (no_delay)
1070 {
1071 platform_group_set(&c0->platform_state_group);
1072 platform_user_set(&c0->platform_state_user);
1073 }
1074 else if (c->first_time)
1075 {
1076 msg(M_INFO, "NOTE: UID/GID downgrade %s", why_not);
65140a3a 1077 }
81d882d5 1078 }
99385447 1079
ffea644c 1080#ifdef ENABLE_MEMSTATS
81d882d5
DS
1081 if (c->first_time && c->options.memstats_fn)
1082 {
1083 mstats_open(c->options.memstats_fn);
1084 }
ffea644c
JY
1085#endif
1086
cd5990e0 1087#ifdef ENABLE_SELINUX
81d882d5
DS
1088 /* Apply a SELinux context in order to restrict what OpenVPN can do
1089 * to _only_ what it is supposed to do after initialization is complete
1090 * (basically just network I/O operations). Doing it after chroot
1091 * requires /proc to be mounted in the chroot (which is annoying indeed
1092 * but doing it before requires more complex SELinux policies.
1093 */
1094 if (c->options.selinux_context)
1095 {
1096 if (no_delay)
1097 {
1098 if (-1 == setcon(c->options.selinux_context))
1099 {
1100 msg(M_ERR, "setcon to '%s' failed; is /proc accessible?", c->options.selinux_context);
1101 }
1102 else
1103 {
1104 msg(M_INFO, "setcon to '%s' succeeded", c->options.selinux_context);
1105 }
1106 }
1107 else if (c->first_time)
1108 {
1109 msg(M_INFO, "NOTE: setcon %s", why_not);
1110 }
1111 }
1112#endif
1113
1114 /* Privileges are going to be dropped by now (if requested), be sure
1115 * to prevent any future privilege dropping attempts from now on.
1116 */
1117 if (no_delay)
1118 {
1119 c0->uid_gid_chroot_set = true;
1120 }
6fbf66fa
JY
1121 }
1122}
1123
1124/*
1125 * Return common name in a way that is formatted for
1126 * prepending to msg() output.
1127 */
1128const char *
81d882d5 1129format_common_name(struct context *c, struct gc_arena *gc)
6fbf66fa 1130{
81d882d5 1131 struct buffer out = alloc_buf_gc(256, gc);
ec828db6 1132#ifdef ENABLE_CRYPTO
81d882d5 1133 if (c->c2.tls_multi)
6fbf66fa 1134 {
81d882d5 1135 buf_printf(&out, "[%s] ", tls_common_name(c->c2.tls_multi, false));
6fbf66fa
JY
1136 }
1137#endif
81d882d5 1138 return BSTR(&out);
6fbf66fa
JY
1139}
1140
1141void
81d882d5 1142pre_setup(const struct options *options)
6fbf66fa 1143{
445b192a 1144#ifdef _WIN32
81d882d5 1145 if (options->exit_event_name)
6fbf66fa 1146 {
81d882d5
DS
1147 win32_signal_open(&win32_signal,
1148 WSO_FORCE_SERVICE,
1149 options->exit_event_name,
1150 options->exit_event_initial_state);
6fbf66fa 1151 }
81d882d5 1152 else
6fbf66fa 1153 {
81d882d5
DS
1154 win32_signal_open(&win32_signal,
1155 WSO_FORCE_CONSOLE,
1156 NULL,
1157 false);
6fbf66fa 1158
81d882d5
DS
1159 /* put a title on the top window bar */
1160 if (win32_signal.mode == WSO_MODE_CONSOLE)
1161 {
1162 window_title_save(&window_title);
1163 window_title_generate(options->config);
1164 }
6fbf66fa 1165 }
81d882d5 1166#endif /* ifdef _WIN32 */
6fbf66fa
JY
1167}
1168
1169void
81d882d5 1170reset_coarse_timers(struct context *c)
6fbf66fa 1171{
81d882d5 1172 c->c2.coarse_timer_wakeup = 0;
6fbf66fa
JY
1173}
1174
f2134b7b
AS
1175/*
1176 * Initialise the server poll timeout timer
1177 * This timer is used in the http/socks proxy setup so it needs to be setup
1178 * before
1179 */
1180static void
81d882d5 1181do_init_server_poll_timeout(struct context *c)
f2134b7b 1182{
81d882d5 1183 update_time();
f2134b7b 1184 if (c->options.ce.connect_timeout)
81d882d5
DS
1185 {
1186 event_timeout_init(&c->c2.server_poll_interval, c->options.ce.connect_timeout, now);
1187 }
f2134b7b
AS
1188}
1189
6fbf66fa
JY
1190/*
1191 * Initialize timers
1192 */
1193static void
81d882d5 1194do_init_timers(struct context *c, bool deferred)
6fbf66fa 1195{
81d882d5
DS
1196 update_time();
1197 reset_coarse_timers(c);
6fbf66fa 1198
81d882d5
DS
1199 /* initialize inactivity timeout */
1200 if (c->options.inactivity_timeout)
1201 {
1202 event_timeout_init(&c->c2.inactivity_interval, c->options.inactivity_timeout, now);
1203 }
6fbf66fa 1204
81d882d5 1205 /* initialize pings */
6fbf66fa 1206
81d882d5
DS
1207 if (c->options.ping_send_timeout)
1208 {
1209 event_timeout_init(&c->c2.ping_send_interval, c->options.ping_send_timeout, 0);
1210 }
6fbf66fa 1211
81d882d5
DS
1212 if (c->options.ping_rec_timeout)
1213 {
1214 event_timeout_init(&c->c2.ping_rec_interval, c->options.ping_rec_timeout, now);
1215 }
6fbf66fa 1216
81d882d5 1217 if (!deferred)
6fbf66fa 1218 {
81d882d5
DS
1219 /* initialize connection establishment timer */
1220 event_timeout_init(&c->c2.wait_for_connect, 1, now);
6fbf66fa
JY
1221
1222#ifdef ENABLE_OCC
81d882d5 1223 /* initialize occ timers */
6fbf66fa 1224
81d882d5
DS
1225 if (c->options.occ
1226 && !TLS_MODE(c)
1227 && c->c2.options_string_local && c->c2.options_string_remote)
1228 {
1229 event_timeout_init(&c->c2.occ_interval, OCC_INTERVAL_SECONDS, now);
1230 }
6fbf66fa 1231
81d882d5
DS
1232 if (c->options.mtu_test)
1233 {
1234 event_timeout_init(&c->c2.occ_mtu_load_test_interval, OCC_MTU_LOAD_INTERVAL_SECONDS, now);
1235 }
6fbf66fa
JY
1236#endif
1237
81d882d5 1238 /* initialize packet_id persistence timer */
9b33b5a4 1239#ifdef ENABLE_CRYPTO
81d882d5
DS
1240 if (c->options.packet_id_file)
1241 {
1242 event_timeout_init(&c->c2.packet_id_persist_interval, 60, now);
1243 }
6fbf66fa 1244
81d882d5
DS
1245 /* initialize tmp_int optimization that limits the number of times we call
1246 * tls_multi_process in the main event loop */
1247 interval_init(&c->c2.tmp_int, TLS_MULTI_HORIZON, TLS_MULTI_REFRESH);
6fbf66fa
JY
1248#endif
1249 }
1250}
1251
1252/*
1253 * Initialize traffic shaper.
1254 */
1255static void
81d882d5 1256do_init_traffic_shaper(struct context *c)
6fbf66fa 1257{
3d163bc5 1258#ifdef ENABLE_FEATURE_SHAPER
81d882d5
DS
1259 /* initialize traffic shaper (i.e. transmit bandwidth limiter) */
1260 if (c->options.shaper)
6fbf66fa 1261 {
81d882d5
DS
1262 shaper_init(&c->c2.shaper, c->options.shaper);
1263 shaper_msg(&c->c2.shaper);
6fbf66fa
JY
1264 }
1265#endif
1266}
1267
1268/*
eb95f367
GD
1269 * Allocate route list structures for IPv4 and IPv6
1270 * (we do this for IPv4 even if no --route option has been seen, as other
1271 * parts of OpenVPN might want to fill the route-list with info, e.g. DHCP)
6fbf66fa
JY
1272 */
1273static void
81d882d5 1274do_alloc_route_list(struct context *c)
6fbf66fa 1275{
81d882d5
DS
1276 if (!c->c1.route_list)
1277 {
1278 ALLOC_OBJ_CLEAR_GC(c->c1.route_list, struct route_list, &c->gc);
1279 }
1280 if (c->options.routes_ipv6 && !c->c1.route_ipv6_list)
1281 {
1282 ALLOC_OBJ_CLEAR_GC(c->c1.route_ipv6_list, struct route_ipv6_list, &c->gc);
1283 }
6fbf66fa
JY
1284}
1285
1286
1287/*
1288 * Initialize the route list, resolving any DNS names in route
1289 * options and saving routes in the environment.
1290 */
1291static void
81d882d5
DS
1292do_init_route_list(const struct options *options,
1293 struct route_list *route_list,
1294 const struct link_socket_info *link_socket_info,
1295 struct env_set *es)
6fbf66fa 1296{
81d882d5
DS
1297 const char *gw = NULL;
1298 int dev = dev_type_enum(options->dev, options->dev_type);
1299 int metric = 0;
6fbf66fa 1300
81d882d5
DS
1301 if (dev == DEV_TYPE_TUN && (options->topology == TOP_NET30 || options->topology == TOP_P2P))
1302 {
1303 gw = options->ifconfig_remote_netmask;
1304 }
1305 if (options->route_default_gateway)
1306 {
1307 gw = options->route_default_gateway;
1308 }
1309 if (options->route_default_metric)
1310 {
1311 metric = options->route_default_metric;
1312 }
6fbf66fa 1313
81d882d5
DS
1314 if (init_route_list(route_list,
1315 options->routes,
1316 gw,
1317 metric,
1318 link_socket_current_remote(link_socket_info),
1319 es))
6fbf66fa 1320 {
81d882d5
DS
1321 /* copy routes to environment */
1322 setenv_routes(es, route_list);
6fbf66fa
JY
1323 }
1324}
1325
512cda46 1326static void
81d882d5
DS
1327do_init_route_ipv6_list(const struct options *options,
1328 struct route_ipv6_list *route_ipv6_list,
1329 const struct link_socket_info *link_socket_info,
1330 struct env_set *es)
512cda46 1331{
81d882d5
DS
1332 const char *gw = NULL;
1333 int metric = -1; /* no metric set */
512cda46 1334
81d882d5
DS
1335 gw = options->ifconfig_ipv6_remote; /* default GW = remote end */
1336#if 0 /* not yet done for IPv6 - TODO!*/
1337 if (options->route_ipv6_default_gateway) /* override? */
1338 {
1339 gw = options->route_ipv6_default_gateway;
1340 }
512cda46
GD
1341#endif
1342
81d882d5
DS
1343 if (options->route_default_metric)
1344 {
1345 metric = options->route_default_metric;
1346 }
512cda46 1347
81d882d5
DS
1348 /* redirect (IPv6) gateway to VPN? if yes, add a few more specifics
1349 */
1350 if (options->routes_ipv6->flags & RG_REROUTE_GW)
d227929b 1351 {
81d882d5
DS
1352 char *opt_list[] = { "::/3", "2000::/4", "3000::/4", "fc00::/7", NULL };
1353 int i;
d227929b 1354
81d882d5
DS
1355 for (i = 0; opt_list[i]; i++)
1356 {
1357 add_route_ipv6_to_option_list( options->routes_ipv6,
1358 string_alloc(opt_list[i], options->routes_ipv6->gc),
1359 NULL, NULL );
1360 }
d227929b
GD
1361 }
1362
81d882d5
DS
1363 if (init_route_ipv6_list(route_ipv6_list,
1364 options->routes_ipv6,
1365 gw,
1366 metric,
1367 link_socket_current_remote_ipv6(link_socket_info),
1368 es))
512cda46 1369 {
81d882d5
DS
1370 /* copy routes to environment */
1371 setenv_routes_ipv6(es, route_ipv6_list);
512cda46
GD
1372 }
1373}
1374
1375
6fbf66fa
JY
1376/*
1377 * Called after all initialization has been completed.
1378 */
1379void
81d882d5 1380initialization_sequence_completed(struct context *c, const unsigned int flags)
6fbf66fa 1381{
81d882d5 1382 static const char message[] = "Initialization Sequence Completed";
6fbf66fa 1383
81d882d5
DS
1384 /* Reset the unsuccessful connection counter on complete initialisation */
1385 c->options.unsuccessful_attempts = 0;
23d61c56 1386
81d882d5
DS
1387 /* If we delayed UID/GID downgrade or chroot, do it now */
1388 do_uid_gid_chroot(c, true);
6fbf66fa 1389
81d882d5
DS
1390 /* Test if errors */
1391 if (flags & ISC_ERRORS)
a9c802b2 1392 {
445b192a 1393#ifdef _WIN32
81d882d5
DS
1394 show_routes(M_INFO|M_NOPREFIX);
1395 show_adapters(M_INFO|M_NOPREFIX);
1396 msg(M_INFO, "%s With Errors ( see http://openvpn.net/faq.html#dhcpclientserv )", message);
6fbf66fa 1397#else
c5931897 1398#ifdef ENABLE_SYSTEMD
81d882d5 1399 sd_notifyf(0, "STATUS=Failed to start up: %s With Errors\nERRNO=1", message);
c5931897 1400#endif /* HAVE_SYSTEMD_SD_DAEMON_H */
81d882d5 1401 msg(M_INFO, "%s With Errors", message);
6fbf66fa 1402#endif
a9c802b2 1403 }
81d882d5 1404 else
c5931897
CH
1405 {
1406#ifdef ENABLE_SYSTEMD
81d882d5 1407 sd_notifyf(0, "READY=1\nSTATUS=%s\nMAINPID=%lu", message, (unsigned long) getpid());
c5931897 1408#endif
81d882d5 1409 msg(M_INFO, "%s", message);
c5931897 1410 }
6fbf66fa 1411
81d882d5
DS
1412 /* Flag that we initialized */
1413 if ((flags & (ISC_ERRORS|ISC_SERVER)) == 0)
1414 {
1415 c->options.no_advance = true;
1416 }
6fbf66fa 1417
445b192a 1418#ifdef _WIN32
81d882d5 1419 fork_register_dns_action(c->c1.tuntap);
b90c6f17
JY
1420#endif
1421
6fbf66fa 1422#ifdef ENABLE_MANAGEMENT
81d882d5
DS
1423 /* Tell management interface that we initialized */
1424 if (management)
1425 {
1426 in_addr_t *tun_local = NULL;
1427 struct in6_addr *tun_local6 = NULL;
1428 struct openvpn_sockaddr local, remote;
1429 struct link_socket_actual *actual;
1430 socklen_t sa_len = sizeof(local);
1431 const char *detail = "SUCCESS";
1432 if (flags & ISC_ERRORS)
1433 {
1434 detail = "ERROR";
1435 }
1436
1437 CLEAR(local);
1438 actual = &get_link_socket_info(c)->lsa->actual;
1439 remote = actual->dest;
1440 getsockname(c->c2.link_socket->sd, &local.addr.sa, &sa_len);
2191c471 1441#if ENABLE_IP_PKTINFO
81d882d5 1442 if (!addr_defined(&local))
2191c471 1443 {
81d882d5 1444 switch (local.addr.sa.sa_family)
2191c471 1445 {
81d882d5 1446 case AF_INET:
7efa60d9 1447#if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST)
81d882d5 1448 local.addr.in4.sin_addr = actual->pi.in4.ipi_spec_dst;
4a82a9ac 1449#else
81d882d5 1450 local.addr.in4.sin_addr = actual->pi.in4;
4a82a9ac 1451#endif
81d882d5
DS
1452 break;
1453
1454 case AF_INET6:
1455 local.addr.in6.sin6_addr = actual->pi.in6.ipi6_addr;
1456 break;
2191c471
HH
1457 }
1458 }
1459#endif
1460
81d882d5 1461 if (c->c1.tuntap)
2191c471 1462 {
81d882d5
DS
1463 tun_local = &c->c1.tuntap->local;
1464 tun_local6 = &c->c1.tuntap->local_ipv6;
1465 }
1466 management_set_state(management,
1467 OPENVPN_STATE_CONNECTED,
1468 detail,
1469 tun_local,
1470 tun_local6,
1471 &local,
1472 &remote);
1473 if (tun_local)
1474 {
1475 management_post_tunnel_open(management, *tun_local);
2191c471 1476 }
6fbf66fa 1477 }
81d882d5 1478#endif /* ifdef ENABLE_MANAGEMENT */
6fbf66fa
JY
1479}
1480
1481/*
1482 * Possibly add routes and/or call route-up script
1483 * based on options.
1484 */
1485void
81d882d5
DS
1486do_route(const struct options *options,
1487 struct route_list *route_list,
1488 struct route_ipv6_list *route_ipv6_list,
1489 const struct tuntap *tt,
1490 const struct plugin_list *plugins,
1491 struct env_set *es)
6fbf66fa 1492{
81d882d5 1493 if (!options->route_noexec && ( route_list || route_ipv6_list ) )
15be3202 1494 {
81d882d5
DS
1495 add_routes(route_list, route_ipv6_list, tt, ROUTE_OPTION_FLAGS(options), es);
1496 setenv_int(es, "redirect_gateway", route_did_redirect_default_gateway(route_list));
15be3202
JY
1497 }
1498#ifdef ENABLE_MANAGEMENT
81d882d5
DS
1499 if (management)
1500 {
1501 management_up_down(management, "UP", es);
1502 }
15be3202 1503#endif
6fbf66fa 1504
81d882d5 1505 if (plugin_defined(plugins, OPENVPN_PLUGIN_ROUTE_UP))
6fbf66fa 1506 {
81d882d5
DS
1507 if (plugin_call(plugins, OPENVPN_PLUGIN_ROUTE_UP, NULL, NULL, es) != OPENVPN_PLUGIN_FUNC_SUCCESS)
1508 {
1509 msg(M_WARN, "WARNING: route-up plugin call failed");
1510 }
6fbf66fa
JY
1511 }
1512
81d882d5 1513 if (options->route_script)
6fbf66fa 1514 {
81d882d5
DS
1515 struct argv argv = argv_new();
1516 setenv_str(es, "script_type", "route-up");
1517 argv_parse_cmd(&argv, options->route_script);
1518 openvpn_run_script(&argv, es, 0, "--route-up");
1519 argv_reset(&argv);
6fbf66fa
JY
1520 }
1521
445b192a 1522#ifdef _WIN32
81d882d5 1523 if (options->show_net_up)
6fbf66fa 1524 {
81d882d5
DS
1525 show_routes(M_INFO|M_NOPREFIX);
1526 show_adapters(M_INFO|M_NOPREFIX);
6fbf66fa 1527 }
81d882d5 1528 else if (check_debug_level(D_SHOW_NET))
6fbf66fa 1529 {
81d882d5
DS
1530 show_routes(D_SHOW_NET|M_NOPREFIX);
1531 show_adapters(D_SHOW_NET|M_NOPREFIX);
6fbf66fa
JY
1532 }
1533#endif
1534}
1535
6fbf66fa
JY
1536/*
1537 * initialize tun/tap device object
1538 */
1539static void
81d882d5 1540do_init_tun(struct context *c)
6fbf66fa 1541{
81d882d5
DS
1542 c->c1.tuntap = init_tun(c->options.dev,
1543 c->options.dev_type,
1544 c->options.topology,
1545 c->options.ifconfig_local,
1546 c->options.ifconfig_remote_netmask,
1547 c->options.ifconfig_ipv6_local,
1548 c->options.ifconfig_ipv6_netbits,
1549 c->options.ifconfig_ipv6_remote,
1550 c->c1.link_socket_addr.bind_local,
1551 c->c1.link_socket_addr.remote_list,
1552 !c->options.ifconfig_nowarn,
1553 c->c2.es);
1554
1555 init_tun_post(c->c1.tuntap,
1556 &c->c2.frame,
1557 &c->options.tuntap_options);
1558
1559 c->c1.tuntap_owned = true;
6fbf66fa
JY
1560}
1561
1562/*
1563 * Open tun/tap device, ifconfig, call up script, etc.
1564 */
1565
1566static bool
81d882d5 1567do_open_tun(struct context *c)
6fbf66fa 1568{
81d882d5
DS
1569 struct gc_arena gc = gc_new();
1570 bool ret = false;
6fbf66fa 1571
bd14d55d 1572#ifndef TARGET_ANDROID
81d882d5 1573 if (!c->c1.tuntap)
6fbf66fa 1574 {
bd14d55d
AS
1575#endif
1576
1577#ifdef TARGET_ANDROID
81d882d5
DS
1578 /* If we emulate persist-tun on android we still have to open a new tun and
1579 * then close the old */
1580 int oldtunfd = -1;
1581 if (c->c1.tuntap)
1582 {
1583 oldtunfd = c->c1.tuntap->fd;
1584 }
bd14d55d
AS
1585#endif
1586
81d882d5
DS
1587 /* initialize (but do not open) tun/tap object */
1588 do_init_tun(c);
6fbf66fa 1589
445b192a 1590#ifdef _WIN32
81d882d5
DS
1591 /* store (hide) interactive service handle in tuntap_options */
1592 c->c1.tuntap->options.msg_channel = c->options.msg_channel;
1593 msg(D_ROUTE, "interactive service msg_channel=%u", (unsigned int) c->options.msg_channel);
1594#endif
1595
1596 /* allocate route list structure */
1597 do_alloc_route_list(c);
1598
1599 /* parse and resolve the route option list */
1600 ASSERT(c->c2.link_socket);
1601 if (c->options.routes && c->c1.route_list)
1602 {
1603 do_init_route_list(&c->options, c->c1.route_list,
1604 &c->c2.link_socket->info, c->c2.es);
1605 }
1606 if (c->options.routes_ipv6 && c->c1.route_ipv6_list)
1607 {
1608 do_init_route_ipv6_list(&c->options, c->c1.route_ipv6_list,
1609 &c->c2.link_socket->info, c->c2.es);
1610 }
1611
1612 /* do ifconfig */
1613 if (!c->options.ifconfig_noexec
1614 && ifconfig_order() == IFCONFIG_BEFORE_TUN_OPEN)
1615 {
1616 /* guess actual tun/tap unit number that will be returned
1617 * by open_tun */
1618 const char *guess = guess_tuntap_dev(c->options.dev,
1619 c->options.dev_type,
1620 c->options.dev_node,
1621 &gc);
1622 do_ifconfig(c->c1.tuntap, guess, TUN_MTU_SIZE(&c->c2.frame), c->c2.es);
1623 }
1624
1625 /* possibly add routes */
1626 if (route_order() == ROUTE_BEFORE_TUN)
1627 {
94e6a2da 1628 /* Ignore route_delay, would cause ROUTE_BEFORE_TUN to be ignored */
81d882d5
DS
1629 do_route(&c->options, c->c1.route_list, c->c1.route_ipv6_list,
1630 c->c1.tuntap, c->plugins, c->c2.es);
1631 }
c058cbff 1632#ifdef TARGET_ANDROID
81d882d5
DS
1633 /* Store the old fd inside the fd so open_tun can use it */
1634 c->c1.tuntap->fd = oldtunfd;
1635#endif
1636 /* open the tun device */
1637 open_tun(c->options.dev, c->options.dev_type, c->options.dev_node,
1638 c->c1.tuntap);
1639
1640 /* set the hardware address */
1641 if (c->options.lladdr)
1642 {
1643 set_lladdr(c->c1.tuntap->actual_name, c->options.lladdr, c->c2.es);
1644 }
1645
1646 /* do ifconfig */
1647 if (!c->options.ifconfig_noexec
1648 && ifconfig_order() == IFCONFIG_AFTER_TUN_OPEN)
1649 {
1650 do_ifconfig(c->c1.tuntap, c->c1.tuntap->actual_name, TUN_MTU_SIZE(&c->c2.frame), c->c2.es);
1651 }
1652
1653 /* run the up script */
1654 run_up_down(c->options.up_script,
1655 c->plugins,
1656 OPENVPN_PLUGIN_UP,
1657 c->c1.tuntap->actual_name,
445b192a 1658#ifdef _WIN32
81d882d5
DS
1659 c->c1.tuntap->adapter_index,
1660#endif
1661 dev_type_string(c->options.dev, c->options.dev_type),
1662 TUN_MTU_SIZE(&c->c2.frame),
1663 EXPANDED_SIZE(&c->c2.frame),
1664 print_in_addr_t(c->c1.tuntap->local, IA_EMPTY_IF_UNDEF, &gc),
1665 print_in_addr_t(c->c1.tuntap->remote_netmask, IA_EMPTY_IF_UNDEF, &gc),
1666 "init",
1667 NULL,
1668 "up",
1669 c->c2.es);
6fbf66fa 1670
445b192a 1671#if defined(_WIN32)
81d882d5
DS
1672 if (c->options.block_outside_dns)
1673 {
1674 dmsg(D_LOW, "Blocking outside DNS");
2282b1be 1675 if (!win_wfp_block_dns(c->c1.tuntap->adapter_index, c->options.msg_channel))
81d882d5
DS
1676 {
1677 msg(M_FATAL, "Blocking DNS failed!");
1678 }
1679 }
38c85658
V
1680#endif
1681
81d882d5
DS
1682 /* possibly add routes */
1683 if ((route_order() == ROUTE_AFTER_TUN) && (!c->options.route_delay_defined))
1684 {
1685 do_route(&c->options, c->c1.route_list, c->c1.route_ipv6_list,
1686 c->c1.tuntap, c->plugins, c->c2.es);
1687 }
6fbf66fa 1688
81d882d5
DS
1689 /*
1690 * Did tun/tap driver give us an MTU?
1691 */
1692 if (c->c1.tuntap->post_open_mtu)
1693 {
1694 frame_set_mtu_dynamic(&c->c2.frame,
1695 c->c1.tuntap->post_open_mtu,
1696 SET_MTU_TUN | SET_MTU_UPPER_BOUND);
1697 }
6fbf66fa 1698
81d882d5
DS
1699 ret = true;
1700 static_context = c;
bd14d55d 1701#ifndef TARGET_ANDROID
81d882d5
DS
1702}
1703else
1704{
1705 msg(M_INFO, "Preserving previous TUN/TAP instance: %s",
1706 c->c1.tuntap->actual_name);
6fbf66fa 1707
81d882d5
DS
1708 /* explicitly set the ifconfig_* env vars */
1709 do_ifconfig_setenv(c->c1.tuntap, c->c2.es);
db950be8 1710
81d882d5
DS
1711 /* run the up script if user specified --up-restart */
1712 if (c->options.up_restart)
1713 {
1714 run_up_down(c->options.up_script,
1715 c->plugins,
1716 OPENVPN_PLUGIN_UP,
1717 c->c1.tuntap->actual_name,
445b192a 1718#ifdef _WIN32
81d882d5
DS
1719 c->c1.tuntap->adapter_index,
1720#endif
1721 dev_type_string(c->options.dev, c->options.dev_type),
1722 TUN_MTU_SIZE(&c->c2.frame),
1723 EXPANDED_SIZE(&c->c2.frame),
1724 print_in_addr_t(c->c1.tuntap->local, IA_EMPTY_IF_UNDEF, &gc),
1725 print_in_addr_t(c->c1.tuntap->remote_netmask, IA_EMPTY_IF_UNDEF, &gc),
1726 "restart",
1727 NULL,
1728 "up",
1729 c->c2.es);
1730 }
445b192a 1731#if defined(_WIN32)
81d882d5
DS
1732 if (c->options.block_outside_dns)
1733 {
1734 dmsg(D_LOW, "Blocking outside DNS");
1735 if (!win_wfp_block_dns(c->c1.tuntap->adapter_index, c->options.msg_channel))
451d2177 1736 {
81d882d5 1737 msg(M_FATAL, "Blocking DNS failed!");
451d2177 1738 }
6fbf66fa 1739 }
bd14d55d 1740#endif
81d882d5
DS
1741
1742}
1743#endif /* ifndef TARGET_ANDROID */
1744 gc_free(&gc);
1745 return ret;
6fbf66fa
JY
1746}
1747
1748/*
1749 * Close TUN/TAP device
1750 */
1751
1752static void
81d882d5 1753do_close_tun_simple(struct context *c)
6fbf66fa 1754{
81d882d5
DS
1755 msg(D_CLOSE, "Closing TUN/TAP interface");
1756 close_tun(c->c1.tuntap);
1757 c->c1.tuntap = NULL;
1758 c->c1.tuntap_owned = false;
6fbf66fa 1759#if P2MP
81d882d5 1760 CLEAR(c->c1.pulled_options_digest_save);
6fbf66fa
JY
1761#endif
1762}
1763
1764static void
81d882d5 1765do_close_tun(struct context *c, bool force)
6fbf66fa 1766{
81d882d5
DS
1767 struct gc_arena gc = gc_new();
1768 if (c->c1.tuntap && c->c1.tuntap_owned)
6fbf66fa 1769 {
81d882d5 1770 const char *tuntap_actual = string_alloc(c->c1.tuntap->actual_name, &gc);
445b192a 1771#ifdef _WIN32
81d882d5 1772 DWORD adapter_index = c->c1.tuntap->adapter_index;
9dff2c1f 1773#endif
81d882d5
DS
1774 const in_addr_t local = c->c1.tuntap->local;
1775 const in_addr_t remote_netmask = c->c1.tuntap->remote_netmask;
6fbf66fa 1776
81d882d5
DS
1777 if (force || !(c->sig->signal_received == SIGUSR1 && c->options.persist_tun))
1778 {
1779 static_context = NULL;
0c9eb1d3 1780
6fbf66fa 1781#ifdef ENABLE_MANAGEMENT
81d882d5
DS
1782 /* tell management layer we are about to close the TUN/TAP device */
1783 if (management)
1784 {
1785 management_pre_tunnel_close(management);
1786 management_up_down(management, "DOWN", c->c2.es);
1787 }
1788#endif
1789
1790 /* delete any routes we added */
1791 if (c->c1.route_list || c->c1.route_ipv6_list)
1792 {
1793 run_up_down(c->options.route_predown_script,
1794 c->plugins,
1795 OPENVPN_PLUGIN_ROUTE_PREDOWN,
1796 tuntap_actual,
445b192a 1797#ifdef _WIN32
81d882d5
DS
1798 adapter_index,
1799#endif
1800 NULL,
1801 TUN_MTU_SIZE(&c->c2.frame),
1802 EXPANDED_SIZE(&c->c2.frame),
1803 print_in_addr_t(local, IA_EMPTY_IF_UNDEF, &gc),
1804 print_in_addr_t(remote_netmask, IA_EMPTY_IF_UNDEF, &gc),
1805 "init",
1806 signal_description(c->sig->signal_received,
415421c2 1807 c->sig->signal_text),
81d882d5
DS
1808 "route-pre-down",
1809 c->c2.es);
415421c2 1810
81d882d5
DS
1811 delete_routes(c->c1.route_list, c->c1.route_ipv6_list,
1812 c->c1.tuntap, ROUTE_OPTION_FLAGS(&c->options), c->c2.es);
415421c2 1813 }
6fbf66fa 1814
81d882d5
DS
1815 /* actually close tun/tap device based on --down-pre flag */
1816 if (!c->options.down_pre)
1817 {
1818 do_close_tun_simple(c);
1819 }
6fbf66fa 1820
81d882d5
DS
1821 /* Run the down script -- note that it will run at reduced
1822 * privilege if, for example, "--user nobody" was used. */
1823 run_up_down(c->options.down_script,
1824 c->plugins,
1825 OPENVPN_PLUGIN_DOWN,
1826 tuntap_actual,
445b192a 1827#ifdef _WIN32
81d882d5
DS
1828 adapter_index,
1829#endif
1830 NULL,
1831 TUN_MTU_SIZE(&c->c2.frame),
1832 EXPANDED_SIZE(&c->c2.frame),
1833 print_in_addr_t(local, IA_EMPTY_IF_UNDEF, &gc),
1834 print_in_addr_t(remote_netmask, IA_EMPTY_IF_UNDEF, &gc),
1835 "init",
1836 signal_description(c->sig->signal_received,
1837 c->sig->signal_text),
1838 "down",
1839 c->c2.es);
6fbf66fa 1840
445b192a 1841#if defined(_WIN32)
38c85658
V
1842 if (c->options.block_outside_dns)
1843 {
2282b1be 1844 if (!win_wfp_uninit(c->options.msg_channel))
81d882d5
DS
1845 {
1846 msg(M_FATAL, "Uninitialising WFP failed!");
1847 }
38c85658
V
1848 }
1849#endif
1850
81d882d5
DS
1851 /* actually close tun/tap device based on --down-pre flag */
1852 if (c->options.down_pre)
1853 {
1854 do_close_tun_simple(c);
1855 }
1856 }
1857 else
1858 {
1859 /* run the down script on this restart if --up-restart was specified */
1860 if (c->options.up_restart)
1861 {
1862 run_up_down(c->options.down_script,
1863 c->plugins,
1864 OPENVPN_PLUGIN_DOWN,
1865 tuntap_actual,
445b192a 1866#ifdef _WIN32
81d882d5
DS
1867 adapter_index,
1868#endif
1869 NULL,
1870 TUN_MTU_SIZE(&c->c2.frame),
1871 EXPANDED_SIZE(&c->c2.frame),
1872 print_in_addr_t(local, IA_EMPTY_IF_UNDEF, &gc),
1873 print_in_addr_t(remote_netmask, IA_EMPTY_IF_UNDEF, &gc),
1874 "restart",
1875 signal_description(c->sig->signal_received,
1876 c->sig->signal_text),
1877 "down",
1878 c->c2.es);
1879 }
451d2177 1880
445b192a 1881#if defined(_WIN32)
81d882d5 1882 if (c->options.block_outside_dns)
451d2177 1883 {
81d882d5
DS
1884 if (!win_wfp_uninit(c->options.msg_channel))
1885 {
1886 msg(M_FATAL, "Uninitialising WFP failed!");
1887 }
451d2177
SN
1888 }
1889#endif
1890
81d882d5 1891 }
6fbf66fa 1892 }
81d882d5 1893 gc_free(&gc);
6fbf66fa
JY
1894}
1895
0c9eb1d3
JY
1896void
1897tun_abort()
1898{
81d882d5
DS
1899 struct context *c = static_context;
1900 if (c)
0c9eb1d3 1901 {
81d882d5
DS
1902 static_context = NULL;
1903 do_close_tun(c, true);
0c9eb1d3
JY
1904 }
1905}
1906
6fbf66fa
JY
1907/*
1908 * Handle delayed tun/tap interface bringup due to --up-delay or --pull
1909 */
1910
827de237
SK
1911#if P2MP
1912/**
1913 * Helper for do_up(). Take two option hashes and return true if they are not
1914 * equal, or either one is all-zeroes.
1915 */
1916static bool
2dd6501e 1917options_hash_changed_or_zero(const struct md5_digest *a,
81d882d5 1918 const struct md5_digest *b)
827de237 1919{
81d882d5
DS
1920 const struct md5_digest zero = {{0}};
1921 return memcmp(a, b, sizeof(struct md5_digest))
1922 || !memcmp(a, &zero, sizeof(struct md5_digest));
827de237
SK
1923}
1924#endif /* P2MP */
1925
d728ebed 1926bool
81d882d5 1927do_up(struct context *c, bool pulled_options, unsigned int option_types_found)
6fbf66fa 1928{
81d882d5 1929 if (!c->c2.do_up_ran)
6fbf66fa 1930 {
81d882d5 1931 reset_coarse_timers(c);
6fbf66fa 1932
81d882d5
DS
1933 if (pulled_options && option_types_found)
1934 {
1935 if (!do_deferred_options(c, option_types_found))
1936 {
1937 msg(D_PUSH_ERRORS, "ERROR: Failed to apply push options");
1938 return false;
1939 }
1940 }
6fbf66fa 1941
81d882d5
DS
1942 /* if --up-delay specified, open tun, do ifconfig, and run up script now */
1943 if (c->options.up_delay || PULL_DEFINED(&c->options))
1944 {
1945 c->c2.did_open_tun = do_open_tun(c);
1946 update_time();
6fbf66fa
JY
1947
1948#if P2MP
81d882d5
DS
1949 /*
1950 * Was tun interface object persisted from previous restart iteration,
1951 * and if so did pulled options string change from previous iteration?
1952 */
1953 if (!c->c2.did_open_tun
1954 && PULL_DEFINED(&c->options)
1955 && c->c1.tuntap
1956 && options_hash_changed_or_zero(&c->c1.pulled_options_digest_save,
1957 &c->c2.pulled_options_digest))
1958 {
1959 /* if so, close tun, delete routes, then reinitialize tun and add routes */
1960 msg(M_INFO, "NOTE: Pulled options changed on restart, will need to close and reopen TUN/TAP device.");
1961 do_close_tun(c, true);
1962 openvpn_sleep(1);
1963 c->c2.did_open_tun = do_open_tun(c);
1964 update_time();
1965 }
1966#endif
1967 }
1968
1969 if (c->c2.did_open_tun)
1970 {
6fbf66fa 1971#if P2MP
81d882d5
DS
1972 c->c1.pulled_options_digest_save = c->c2.pulled_options_digest;
1973#endif
1974
1975 /* if --route-delay was specified, start timer */
1976 if ((route_order() == ROUTE_AFTER_TUN) && c->options.route_delay_defined)
1977 {
1978 event_timeout_init(&c->c2.route_wakeup, c->options.route_delay, now);
1979 event_timeout_init(&c->c2.route_wakeup_expire, c->options.route_delay + c->options.route_delay_window, now);
1980 if (c->c1.tuntap)
1981 {
1982 tun_standby_init(c->c1.tuntap);
1983 }
1984 }
1985 else
1986 {
1987 initialization_sequence_completed(c, 0); /* client/p2p --route-delay undefined */
1988 }
1989 }
1990 else if (c->options.mode == MODE_POINT_TO_POINT)
1991 {
1992 initialization_sequence_completed(c, 0); /* client/p2p restart with --persist-tun */
1993 }
1994
1995 c->c2.do_up_ran = true;
1996 }
1997 return true;
6fbf66fa
JY
1998}
1999
2000/*
2001 * These are the option categories which will be accepted by pull.
2002 */
2003unsigned int
81d882d5
DS
2004pull_permission_mask(const struct context *c)
2005{
2006 unsigned int flags =
2007 OPT_P_UP
2008 | OPT_P_ROUTE_EXTRAS
2009 | OPT_P_SOCKBUF
2010 | OPT_P_SOCKFLAGS
2011 | OPT_P_SETENV
2012 | OPT_P_SHAPER
2013 | OPT_P_TIMER
2014 | OPT_P_COMP
2015 | OPT_P_PERSIST
2016 | OPT_P_MESSAGES
2017 | OPT_P_EXPLICIT_NOTIFY
2018 | OPT_P_ECHO
2019 | OPT_P_PULL_MODE
2020 | OPT_P_PEER_ID;
2021
2022 if (!c->options.route_nopull)
2023 {
2024 flags |= (OPT_P_ROUTE | OPT_P_IPWIN32);
2025 }
3c7f2f55 2026
d728ebed 2027#ifdef ENABLE_CRYPTO
81d882d5
DS
2028 if (c->options.ncp_enabled)
2029 {
2030 flags |= OPT_P_NCP;
2031 }
d728ebed
SK
2032#endif
2033
81d882d5 2034 return flags;
6fbf66fa
JY
2035}
2036
2037/*
2038 * Handle non-tun-related pulled options.
2039 */
d728ebed 2040bool
81d882d5 2041do_deferred_options(struct context *c, const unsigned int found)
6fbf66fa 2042{
81d882d5 2043 if (found & OPT_P_MESSAGES)
6fbf66fa 2044 {
81d882d5
DS
2045 init_verb_mute(c, IVM_LEVEL_1|IVM_LEVEL_2);
2046 msg(D_PUSH, "OPTIONS IMPORT: --verb and/or --mute level changed");
6fbf66fa 2047 }
81d882d5 2048 if (found & OPT_P_TIMER)
6fbf66fa 2049 {
81d882d5
DS
2050 do_init_timers(c, true);
2051 msg(D_PUSH, "OPTIONS IMPORT: timers and/or timeouts modified");
6fbf66fa
JY
2052 }
2053
2054#ifdef ENABLE_OCC
81d882d5 2055 if (found & OPT_P_EXPLICIT_NOTIFY)
6fbf66fa 2056 {
81d882d5
DS
2057 if (!proto_is_udp(c->options.ce.proto) && c->options.ce.explicit_exit_notification)
2058 {
2059 msg(D_PUSH, "OPTIONS IMPORT: --explicit-exit-notify can only be used with --proto udp");
2060 c->options.ce.explicit_exit_notification = 0;
2061 }
2062 else
2063 {
2064 msg(D_PUSH, "OPTIONS IMPORT: explicit notify parm(s) modified");
2065 }
6fbf66fa
JY
2066 }
2067#endif
2068
38d96bd7 2069#ifdef USE_COMP
81d882d5 2070 if (found & OPT_P_COMP)
537073fd 2071 {
81d882d5
DS
2072 msg(D_PUSH, "OPTIONS IMPORT: compression parms modified");
2073 comp_uninit(c->c2.comp_context);
2074 c->c2.comp_context = comp_init(&c->options.comp);
537073fd
JY
2075 }
2076#endif
2077
81d882d5 2078 if (found & OPT_P_SHAPER)
6fbf66fa 2079 {
81d882d5
DS
2080 msg(D_PUSH, "OPTIONS IMPORT: traffic shaper enabled");
2081 do_init_traffic_shaper(c);
6fbf66fa
JY
2082 }
2083
81d882d5 2084 if (found & OPT_P_SOCKBUF)
00d39170 2085 {
81d882d5
DS
2086 msg(D_PUSH, "OPTIONS IMPORT: --sndbuf/--rcvbuf options modified");
2087 link_socket_update_buffer_sizes(c->c2.link_socket, c->options.rcvbuf, c->options.sndbuf);
00d39170
JY
2088 }
2089
81d882d5 2090 if (found & OPT_P_SOCKFLAGS)
00d39170 2091 {
81d882d5
DS
2092 msg(D_PUSH, "OPTIONS IMPORT: --socket-flags option modified");
2093 link_socket_update_flags(c->c2.link_socket, c->options.sockflags);
00d39170
JY
2094 }
2095
81d882d5
DS
2096 if (found & OPT_P_PERSIST)
2097 {
2098 msg(D_PUSH, "OPTIONS IMPORT: --persist options modified");
2099 }
2100 if (found & OPT_P_UP)
2101 {
2102 msg(D_PUSH, "OPTIONS IMPORT: --ifconfig/up options modified");
2103 }
2104 if (found & OPT_P_ROUTE)
2105 {
2106 msg(D_PUSH, "OPTIONS IMPORT: route options modified");
2107 }
2108 if (found & OPT_P_ROUTE_EXTRAS)
2109 {
2110 msg(D_PUSH, "OPTIONS IMPORT: route-related options modified");
2111 }
2112 if (found & OPT_P_IPWIN32)
2113 {
2114 msg(D_PUSH, "OPTIONS IMPORT: --ip-win32 and/or --dhcp-option options modified");
2115 }
2116 if (found & OPT_P_SETENV)
2117 {
2118 msg(D_PUSH, "OPTIONS IMPORT: environment modified");
2119 }
65eedc35 2120
ec828db6 2121#ifdef ENABLE_CRYPTO
81d882d5
DS
2122 if (found & OPT_P_PEER_ID)
2123 {
2124 msg(D_PUSH, "OPTIONS IMPORT: peer-id set");
2125 c->c2.tls_multi->use_peer_id = true;
2126 c->c2.tls_multi->peer_id = c->options.peer_id;
2127 frame_add_to_extra_frame(&c->c2.frame, +3); /* peer-id overhead */
2128 if (!c->options.ce.link_mtu_defined)
2129 {
2130 frame_add_to_link_mtu(&c->c2.frame, +3);
2131 msg(D_PUSH, "OPTIONS IMPORT: adjusting link_mtu to %d",
2132 EXPANDED_SIZE(&c->c2.frame));
2133 }
2134 else
2135 {
2136 msg(M_WARN, "OPTIONS IMPORT: WARNING: peer-id set, but link-mtu"
2137 " fixed by config - reducing tun-mtu to %d, expect"
2138 " MTU problems", TUN_MTU_SIZE(&c->c2.frame) );
2139 }
2140 }
2141
2142 /* process (potentially pushed) crypto options */
2143 if (c->options.pull)
2144 {
2145 struct tls_session *session = &c->c2.tls_multi->session[TM_ACTIVE];
2146 if (found & OPT_P_NCP)
2147 {
2148 msg(D_PUSH, "OPTIONS IMPORT: data channel crypto options modified");
2149 }
2150 else if (c->options.ncp_enabled)
2151 {
2152 tls_poor_mans_ncp(&c->options, c->c2.tls_multi->remote_ciphername);
2153 }
2154 /* Do not regenerate keys if server sends an extra push reply */
2155 if (!session->key[KS_PRIMARY].crypto_options.key_ctx_bi.initialized
2156 && !tls_session_update_crypto_params(session, &c->options, &c->c2.frame))
2157 {
2158 msg(D_TLS_ERRORS, "OPTIONS ERROR: failed to import crypto options");
2159 return false;
2160 }
2161 }
2162#endif /* ifdef ENABLE_CRYPTO */
2163 return true;
6fbf66fa
JY
2164}
2165
2166/*
396d30c2
AS
2167 * Possible hold on initialization, holdtime is the
2168 * time OpenVPN would wait without management
6fbf66fa
JY
2169 */
2170static bool
81d882d5 2171do_hold(int holdtime)
6fbf66fa
JY
2172{
2173#ifdef ENABLE_MANAGEMENT
81d882d5 2174 if (management)
6fbf66fa 2175 {
81d882d5
DS
2176 /* block until management hold is released */
2177 if (management_hold(management, holdtime))
2178 {
2179 return true;
2180 }
6fbf66fa
JY
2181 }
2182#endif
81d882d5 2183 return false;
6fbf66fa
JY
2184}
2185
2186/*
2187 * Sleep before restart.
2188 */
2189static void
81d882d5 2190socket_restart_pause(struct context *c)
6fbf66fa 2191{
81d882d5
DS
2192 int sec = 2;
2193 int backoff = 0;
6fbf66fa 2194
81d882d5 2195 switch (c->options.ce.proto)
6fbf66fa 2196 {
81d882d5
DS
2197 case PROTO_TCP_SERVER:
2198 sec = 1;
2199 break;
2200
2201 case PROTO_UDP:
2202 case PROTO_TCP_CLIENT:
2203 sec = c->options.ce.connect_retry_seconds;
2204 break;
6fbf66fa
JY
2205 }
2206
2207#ifdef ENABLE_DEBUG
81d882d5
DS
2208 if (GREMLIN_CONNECTION_FLOOD_LEVEL(c->options.gremlin))
2209 {
2210 sec = 0;
2211 }
6fbf66fa
JY
2212#endif
2213
2214#if P2MP
81d882d5
DS
2215 if (auth_retry_get() == AR_NOINTERACT)
2216 {
2217 sec = 10;
2218 }
6fbf66fa
JY
2219#endif
2220
81d882d5
DS
2221 /* Slow down reconnection after 5 retries per remote -- for tcp only in client mode */
2222 if (c->options.ce.proto != PROTO_TCP_SERVER)
5d429efd 2223 {
81d882d5
DS
2224 backoff = (c->options.unsuccessful_attempts / c->options.connection_list->len) - 4;
2225 if (backoff > 0)
5d429efd 2226 {
81d882d5
DS
2227 /* sec is less than 2^16; we can left shift it by up to 15 bits without overflow */
2228 sec = max_int(sec, 1) << min_int(backoff, 15);
5d429efd
SN
2229 }
2230
81d882d5
DS
2231 if (sec > c->options.ce.connect_retry_seconds_max)
2232 {
2233 sec = c->options.ce.connect_retry_seconds_max;
2234 }
5d429efd
SN
2235 }
2236
81d882d5
DS
2237 if (c->persist.restart_sleep_seconds > 0 && c->persist.restart_sleep_seconds > sec)
2238 {
2239 sec = c->persist.restart_sleep_seconds;
2240 }
2241 else if (c->persist.restart_sleep_seconds == -1)
2242 {
2243 sec = 0;
2244 }
2245 c->persist.restart_sleep_seconds = 0;
a9c802b2 2246
81d882d5
DS
2247 /* do managment hold on context restart, i.e. second, third, fourth, etc. initialization */
2248 if (do_hold(sec))
2249 {
2250 sec = 0;
2251 }
6fbf66fa 2252
81d882d5 2253 if (sec)
6fbf66fa 2254 {
81d882d5
DS
2255 msg(D_RESTART, "Restart pause, %d second(s)", sec);
2256 openvpn_sleep(sec);
6fbf66fa
JY
2257 }
2258}
2259
2260/*
2261 * Do a possible pause on context_2 initialization.
2262 */
2263static void
81d882d5 2264do_startup_pause(struct context *c)
6fbf66fa 2265{
81d882d5
DS
2266 if (!c->first_time)
2267 {
2268 socket_restart_pause(c);
2269 }
2270 else
2271 {
2272 do_hold(0); /* do management hold on first context initialization */
2273 }
6fbf66fa
JY
2274}
2275
2276/*
2277 * Finalize MTU parameters based on command line or config file options.
2278 */
2279static void
81d882d5 2280frame_finalize_options(struct context *c, const struct options *o)
6fbf66fa 2281{
81d882d5
DS
2282 if (!o)
2283 {
2284 o = &c->options;
2285 }
6fbf66fa 2286
81d882d5
DS
2287 /*
2288 * Set adjustment factor for buffer alignment when no
2289 * cipher is used.
2290 */
2291 if (!CIPHER_ENABLED(c))
6fbf66fa 2292 {
81d882d5
DS
2293 frame_align_to_extra_frame(&c->c2.frame);
2294 frame_or_align_flags(&c->c2.frame,
2295 FRAME_HEADROOM_MARKER_FRAGMENT
2296 |FRAME_HEADROOM_MARKER_READ_LINK
2297 |FRAME_HEADROOM_MARKER_READ_STREAM);
6fbf66fa 2298 }
81d882d5
DS
2299
2300 frame_add_to_extra_buffer(&c->c2.frame, PAYLOAD_ALIGN);
2301 frame_finalize(&c->c2.frame,
2302 o->ce.link_mtu_defined,
2303 o->ce.link_mtu,
2304 o->ce.tun_mtu_defined,
2305 o->ce.tun_mtu);
6fbf66fa
JY
2306}
2307
2308/*
2309 * Free a key schedule, including OpenSSL components.
2310 */
2311static void
81d882d5 2312key_schedule_free(struct key_schedule *ks, bool free_ssl_ctx)
6fbf66fa 2313{
9b33b5a4 2314#ifdef ENABLE_CRYPTO
81d882d5
DS
2315 free_key_ctx_bi(&ks->static_key);
2316 if (tls_ctx_initialised(&ks->ssl_ctx) && free_ssl_ctx)
6fbf66fa 2317 {
81d882d5
DS
2318 tls_ctx_free(&ks->ssl_ctx);
2319 free_key_ctx_bi(&ks->tls_wrap_key);
6fbf66fa 2320 }
9b33b5a4 2321#endif /* ENABLE_CRYPTO */
81d882d5 2322 CLEAR(*ks);
6fbf66fa
JY
2323}
2324
9b33b5a4 2325#ifdef ENABLE_CRYPTO
6fbf66fa
JY
2326
2327static void
81d882d5 2328init_crypto_pre(struct context *c, const unsigned int flags)
6fbf66fa 2329{
81d882d5
DS
2330 if (c->options.engine)
2331 {
2332 crypto_init_lib_engine(c->options.engine);
2333 }
6fbf66fa 2334
81d882d5 2335 if (flags & CF_LOAD_PERSISTED_PACKET_ID)
6fbf66fa 2336 {
81d882d5
DS
2337 /* load a persisted packet-id for cross-session replay-protection */
2338 if (c->options.packet_id_file)
2339 {
2340 packet_id_persist_load(&c->c1.pid_persist, c->options.packet_id_file);
2341 }
6fbf66fa
JY
2342 }
2343
0f25d296 2344#ifdef ENABLE_PREDICTION_RESISTANCE
81d882d5
DS
2345 if (c->options.use_prediction_resistance)
2346 {
2347 rand_ctx_enable_prediction_resistance();
2348 }
0f25d296
AJ
2349#endif
2350
6fbf66fa
JY
2351}
2352
2353/*
2354 * Static Key Mode (using a pre-shared key)
2355 */
2356static void
81d882d5 2357do_init_crypto_static(struct context *c, const unsigned int flags)
6fbf66fa 2358{
81d882d5
DS
2359 const struct options *options = &c->options;
2360 ASSERT(options->shared_secret_file);
6fbf66fa 2361
81d882d5 2362 init_crypto_pre(c, flags);
2d9c6d20 2363
81d882d5 2364 /* Initialize flags */
81d882d5 2365 if (c->options.mute_replay_warnings)
6fbf66fa 2366 {
81d882d5 2367 c->c2.crypto_options.flags |= CO_MUTE_REPLAY_WARNINGS;
6fbf66fa
JY
2368 }
2369
81d882d5
DS
2370 /* Initialize packet ID tracking */
2371 if (options->replay)
6fbf66fa 2372 {
81d882d5
DS
2373 packet_id_init(&c->c2.crypto_options.packet_id,
2374 options->replay_window,
2375 options->replay_time,
2376 "STATIC", 0);
2377 c->c2.crypto_options.pid_persist = &c->c1.pid_persist;
2378 c->c2.crypto_options.flags |= CO_PACKET_ID_LONG_FORM;
2379 packet_id_persist_load_obj(&c->c1.pid_persist,
2380 &c->c2.crypto_options.packet_id);
2381 }
6fbf66fa 2382
81d882d5
DS
2383 if (!key_ctx_bi_defined(&c->c1.ks.static_key))
2384 {
2385 /* Get cipher & hash algorithms */
2386 init_key_type(&c->c1.ks.key_type, options->ciphername, options->authname,
2387 options->keysize, options->test_crypto, true);
2388
2389 /* Read cipher and hmac keys from shared secret file */
2390 crypto_read_openvpn_key(&c->c1.ks.key_type, &c->c1.ks.static_key,
2391 options->shared_secret_file,
2392 options->shared_secret_file_inline,
2393 options->key_direction, "Static Key Encryption",
2394 "secret");
6fbf66fa 2395 }
81d882d5 2396 else
6fbf66fa 2397 {
81d882d5 2398 msg(M_INFO, "Re-using pre-shared static key");
6fbf66fa
JY
2399 }
2400
81d882d5
DS
2401 /* Get key schedule */
2402 c->c2.crypto_options.key_ctx_bi = c->c1.ks.static_key;
6fbf66fa 2403
81d882d5 2404 /* Compute MTU parameters */
ef910e3e
SK
2405 crypto_adjust_frame_parameters(&c->c2.frame, &c->c1.ks.key_type,
2406 options->replay, true);
6fbf66fa 2407
ef910e3e
SK
2408 /* Sanity check on sequence number, and cipher mode options */
2409 check_replay_consistency(&c->c1.ks.key_type, options->replay);
6fbf66fa
JY
2410}
2411
6fbf66fa
JY
2412/*
2413 * Initialize the persistent component of OpenVPN's TLS mode,
2414 * which is preserved across SIGUSR1 resets.
2415 */
2416static void
81d882d5 2417do_init_crypto_tls_c1(struct context *c)
6fbf66fa 2418{
81d882d5 2419 const struct options *options = &c->options;
6fbf66fa 2420
81d882d5 2421 if (!tls_ctx_initialised(&c->c1.ks.ssl_ctx))
6fbf66fa 2422 {
81d882d5
DS
2423 /*
2424 * Initialize the OpenSSL library's global
2425 * SSL context.
2426 */
2427 init_ssl(options, &(c->c1.ks.ssl_ctx));
2428 if (!tls_ctx_initialised(&c->c1.ks.ssl_ctx))
2429 {
6fbf66fa 2430#if P2MP
81d882d5
DS
2431 switch (auth_retry_get())
2432 {
2433 case AR_NONE:
2434 msg(M_FATAL, "Error: private key password verification failed");
2435 break;
2436
2437 case AR_INTERACT:
2438 ssl_purge_auth(false);
2439
2440 case AR_NOINTERACT:
2441 c->sig->signal_received = SIGUSR1; /* SOFT-SIGUSR1 -- Password failure error */
2442 break;
2443
2444 default:
2445 ASSERT(0);
2446 }
2447 c->sig->signal_text = "private-key-password-failure";
2448 return;
2449#else /* if P2MP */
2450 msg(M_FATAL, "Error: private key password verification failed");
2451#endif
2452 }
2453
2454 /* Get cipher & hash algorithms */
2455 init_key_type(&c->c1.ks.key_type, options->ciphername, options->authname,
2456 options->keysize, true, true);
2457
2458 /* Initialize PRNG with config-specified digest */
2459 prng_init(options->prng_hash, options->prng_nonce_secret_len);
2460
2461 /* TLS handshake authentication (--tls-auth) */
2462 if (options->tls_auth_file)
2463 {
2464 /* Initialize key_type for tls-auth with auth only */
2465 CLEAR(c->c1.ks.tls_auth_key_type);
2466 if (!streq(options->authname, "none"))
2467 {
2468 c->c1.ks.tls_auth_key_type.digest = md_kt_get(options->authname);
2469 c->c1.ks.tls_auth_key_type.hmac_length =
2470 md_kt_size(c->c1.ks.tls_auth_key_type.digest);
2471 }
2472 else
2473 {
2474 msg(M_FATAL, "ERROR: tls-auth enabled, but no valid --auth "
2475 "algorithm specified ('%s')", options->authname);
2476 }
2477
2478 crypto_read_openvpn_key(&c->c1.ks.tls_auth_key_type,
2479 &c->c1.ks.tls_wrap_key, options->tls_auth_file,
2480 options->tls_auth_file_inline, options->key_direction,
2481 "Control Channel Authentication", "tls-auth");
2482 }
2483
2484 /* TLS handshake encryption+authentication (--tls-crypt) */
2485 if (options->tls_crypt_file)
2486 {
2487 tls_crypt_init_key(&c->c1.ks.tls_wrap_key, options->tls_crypt_file,
2488 options->tls_crypt_inline, options->tls_server);
2489 }
2490
2491 c->c1.ciphername = options->ciphername;
2492 c->c1.authname = options->authname;
2493 c->c1.keysize = options->keysize;
d728ebed 2494
1f4309ae 2495#if 0 /* was: #if ENABLE_INLINE_FILES -- Note that enabling this code will break restarts */
81d882d5
DS
2496 if (options->priv_key_file_inline)
2497 {
2498 string_clear(c->options.priv_key_file_inline);
2499 c->options.priv_key_file_inline = NULL;
2500 }
d40f2b20 2501#endif
6fbf66fa 2502 }
81d882d5 2503 else
6fbf66fa 2504 {
81d882d5 2505 msg(D_INIT_MEDIUM, "Re-using SSL/TLS context");
129d2924 2506
81d882d5
DS
2507 /* Restore pre-NCP cipher options */
2508 c->options.ciphername = c->c1.ciphername;
2509 c->options.authname = c->c1.authname;
2510 c->options.keysize = c->c1.keysize;
6fbf66fa
JY
2511 }
2512}
2513
2514static void
81d882d5 2515do_init_crypto_tls(struct context *c, const unsigned int flags)
6fbf66fa 2516{
81d882d5
DS
2517 const struct options *options = &c->options;
2518 struct tls_options to;
2519 bool packet_id_long_form;
6fbf66fa 2520
81d882d5
DS
2521 ASSERT(options->tls_server || options->tls_client);
2522 ASSERT(!options->test_crypto);
6fbf66fa 2523
81d882d5 2524 init_crypto_pre(c, flags);
6fbf66fa 2525
81d882d5
DS
2526 /* Make sure we are either a TLS client or server but not both */
2527 ASSERT(options->tls_server == !options->tls_client);
6fbf66fa 2528
81d882d5
DS
2529 /* initialize persistent component */
2530 do_init_crypto_tls_c1(c);
2531 if (IS_SIG(c))
2532 {
2533 return;
2534 }
2535
ef910e3e
SK
2536 /* Sanity check on sequence number, and cipher mode options */
2537 check_replay_consistency(&c->c1.ks.key_type, options->replay);
81d882d5
DS
2538
2539 /* In short form, unique datagram identifier is 32 bits, in long form 64 bits */
2540 packet_id_long_form = cipher_kt_mode_ofb_cfb(c->c1.ks.key_type.cipher);
2541
2542 /* Compute MTU parameters (postpone if we push/pull options) */
2543 if (c->options.pull || c->options.mode == MODE_SERVER)
2544 {
2545 /* Account for worst-case crypto overhead before allocating buffers */
2546 frame_add_to_extra_frame(&c->c2.frame, crypto_max_overhead());
2547 }
2548 else
2549 {
2550 crypto_adjust_frame_parameters(&c->c2.frame, &c->c1.ks.key_type,
ef910e3e 2551 options->replay, packet_id_long_form);
81d882d5
DS
2552 }
2553 tls_adjust_frame_parameters(&c->c2.frame);
6fbf66fa 2554
81d882d5
DS
2555 /* Set all command-line TLS-related options */
2556 CLEAR(to);
2557
81d882d5
DS
2558 if (options->mute_replay_warnings)
2559 {
2560 to.crypto_flags |= CO_MUTE_REPLAY_WARNINGS;
2561 }
2562
2563 to.crypto_flags &= ~(CO_PACKET_ID_LONG_FORM);
2564 if (packet_id_long_form)
2565 {
2566 to.crypto_flags |= CO_PACKET_ID_LONG_FORM;
2567 }
2568
2569 to.ssl_ctx = c->c1.ks.ssl_ctx;
2570 to.key_type = c->c1.ks.key_type;
2571 to.server = options->tls_server;
2572 to.key_method = options->key_method;
2573 to.replay = options->replay;
2574 to.replay_window = options->replay_window;
2575 to.replay_time = options->replay_time;
2576 to.tcp_mode = link_socket_proto_connection_oriented(options->ce.proto);
2577 to.config_ciphername = c->c1.ciphername;
2578 to.config_authname = c->c1.authname;
2579 to.ncp_enabled = options->ncp_enabled;
2580 to.transition_window = options->transition_window;
2581 to.handshake_window = options->handshake_window;
2582 to.packet_timeout = options->tls_timeout;
2583 to.renegotiate_bytes = options->renegotiate_bytes;
2584 to.renegotiate_packets = options->renegotiate_packets;
2585 to.renegotiate_seconds = options->renegotiate_seconds;
2586 to.single_session = options->single_session;
2587 to.mode = options->mode;
2588 to.pull = options->pull;
aaf72974 2589#ifdef ENABLE_PUSH_PEER_INFO
81d882d5
DS
2590 if (options->push_peer_info) /* all there is */
2591 {
2592 to.push_peer_info_detail = 2;
2593 }
2594 else if (options->pull) /* pull clients send some details */
2595 {
2596 to.push_peer_info_detail = 1;
2597 }
2598 else /* default: no peer-info at all */
2599 {
2600 to.push_peer_info_detail = 0;
2601 }
aaf72974 2602#endif
6fbf66fa 2603
81d882d5
DS
2604 /* should we not xmit any packets until we get an initial
2605 * response from client? */
2606 if (to.server && options->ce.proto == PROTO_TCP_SERVER)
2607 {
2608 to.xmit_hold = true;
2609 }
6add6b2f 2610
6fbf66fa 2611#ifdef ENABLE_OCC
81d882d5
DS
2612 to.disable_occ = !options->occ;
2613#endif
2614
2615 to.verify_command = options->tls_verify;
2616 to.verify_export_cert = options->tls_export_cert;
2617 to.verify_x509_type = (options->verify_x509_type & 0xff);
2618 to.verify_x509_name = options->verify_x509_name;
2619 to.crl_file = options->crl_file;
2620 to.crl_file_inline = options->crl_file_inline;
2621 to.ssl_flags = options->ssl_flags;
2622 to.ns_cert_type = options->ns_cert_type;
2623 memmove(to.remote_cert_ku, options->remote_cert_ku, sizeof(to.remote_cert_ku));
2624 to.remote_cert_eku = options->remote_cert_eku;
2625 to.verify_hash = options->verify_hash;
19dd3ef1 2626#ifdef ENABLE_X509ALTUSERNAME
81d882d5 2627 to.x509_username_field = (char *) options->x509_username_field;
19dd3ef1 2628#else
81d882d5 2629 to.x509_username_field = X509_USERNAME_FIELD_DEFAULT;
19dd3ef1 2630#endif
81d882d5 2631 to.es = c->c2.es;
6fbf66fa
JY
2632
2633#ifdef ENABLE_DEBUG
81d882d5 2634 to.gremlin = c->options.gremlin;
6fbf66fa
JY
2635#endif
2636
81d882d5 2637 to.plugins = c->plugins;
6fbf66fa 2638
90efcacb 2639#ifdef MANAGEMENT_DEF_AUTH
81d882d5 2640 to.mda_context = &c->c2.mda_context;
90efcacb
JY
2641#endif
2642
6fbf66fa 2643#if P2MP_SERVER
81d882d5
DS
2644 to.auth_user_pass_verify_script = options->auth_user_pass_verify_script;
2645 to.auth_user_pass_verify_script_via_file = options->auth_user_pass_verify_script_via_file;
2646 to.tmp_dir = options->tmp_dir;
2647 if (options->ccd_exclusive)
2648 {
2649 to.client_config_dir_exclusive = options->client_config_dir;
2650 }
2651 to.auth_user_pass_file = options->auth_user_pass_file;
2652 to.auth_token_generate = options->auth_token_generate;
2653 to.auth_token_lifetime = options->auth_token_lifetime;
6fbf66fa
JY
2654#endif
2655
81d882d5 2656 to.x509_track = options->x509_track;
9356bae8 2657
16d909e2 2658#if P2MP
eab3e22f 2659#ifdef ENABLE_CLIENT_CR
81d882d5 2660 to.sci = &options->sc_info;
16d909e2 2661#endif
eab3e22f
JY
2662#endif
2663
38d96bd7 2664#ifdef USE_COMP
81d882d5 2665 to.comp_options = options->comp;
38d96bd7
JY
2666#endif
2667
685e486e 2668#if defined(ENABLE_CRYPTO_OPENSSL) && OPENSSL_VERSION_NUMBER >= 0x10001000
81d882d5 2669 if (options->keying_material_exporter_label)
685e486e 2670 {
81d882d5
DS
2671 to.ekm_size = options->keying_material_exporter_length;
2672 if (to.ekm_size < 16 || to.ekm_size > 4095)
2673 {
2674 to.ekm_size = 0;
2675 }
685e486e 2676
81d882d5
DS
2677 to.ekm_label = options->keying_material_exporter_label;
2678 to.ekm_label_size = strlen(to.ekm_label);
685e486e 2679 }
81d882d5 2680 else
685e486e 2681 {
81d882d5 2682 to.ekm_size = 0;
685e486e
DK
2683 }
2684#endif
2685
81d882d5
DS
2686 /* TLS handshake authentication (--tls-auth) */
2687 if (options->tls_auth_file)
6fbf66fa 2688 {
81d882d5
DS
2689 to.tls_wrap.mode = TLS_WRAP_AUTH;
2690 to.tls_wrap.opt.key_ctx_bi = c->c1.ks.tls_wrap_key;
2691 to.tls_wrap.opt.pid_persist = &c->c1.pid_persist;
2692 to.tls_wrap.opt.flags |= CO_PACKET_ID_LONG_FORM;
ef910e3e
SK
2693 crypto_adjust_frame_parameters(&to.frame, &c->c1.ks.tls_auth_key_type,
2694 true, true);
6fbf66fa
JY
2695 }
2696
81d882d5
DS
2697 /* TLS handshake encryption (--tls-crypt) */
2698 if (options->tls_crypt_file)
c6e24fa3 2699 {
81d882d5
DS
2700 to.tls_wrap.mode = TLS_WRAP_CRYPT;
2701 to.tls_wrap.opt.key_ctx_bi = c->c1.ks.tls_wrap_key;
2702 to.tls_wrap.opt.pid_persist = &c->c1.pid_persist;
2703 to.tls_wrap.opt.flags |= CO_PACKET_ID_LONG_FORM;
2704 tls_crypt_adjust_frame_parameters(&to.frame);
c6e24fa3
SK
2705 }
2706
81d882d5
DS
2707 /* If we are running over TCP, allow for
2708 * length prefix */
2709 socket_adjust_frame_parameters(&to.frame, options->ce.proto);
6fbf66fa 2710
81d882d5
DS
2711 /*
2712 * Initialize OpenVPN's master TLS-mode object.
2713 */
2714 if (flags & CF_INIT_TLS_MULTI)
2715 {
2716 c->c2.tls_multi = tls_multi_init(&to);
2717 }
6fbf66fa 2718
81d882d5
DS
2719 if (flags & CF_INIT_TLS_AUTH_STANDALONE)
2720 {
2721 c->c2.tls_auth_standalone = tls_auth_standalone_init(&to, &c->c2.gc);
2722 }
6fbf66fa
JY
2723}
2724
2725static void
81d882d5 2726do_init_finalize_tls_frame(struct context *c)
6fbf66fa 2727{
81d882d5 2728 if (c->c2.tls_multi)
6fbf66fa 2729 {
81d882d5
DS
2730 tls_multi_init_finalize(c->c2.tls_multi, &c->c2.frame);
2731 ASSERT(EXPANDED_SIZE(&c->c2.tls_multi->opt.frame) <=
2732 EXPANDED_SIZE(&c->c2.frame));
2733 frame_print(&c->c2.tls_multi->opt.frame, D_MTU_INFO,
2734 "Control Channel MTU parms");
6fbf66fa 2735 }
81d882d5 2736 if (c->c2.tls_auth_standalone)
6fbf66fa 2737 {
81d882d5
DS
2738 tls_auth_standalone_finalize(c->c2.tls_auth_standalone, &c->c2.frame);
2739 frame_print(&c->c2.tls_auth_standalone->frame, D_MTU_INFO,
2740 "TLS-Auth MTU parms");
6fbf66fa
JY
2741 }
2742}
2743
6fbf66fa
JY
2744/*
2745 * No encryption or authentication.
2746 */
2747static void
81d882d5 2748do_init_crypto_none(const struct context *c)
6fbf66fa 2749{
81d882d5
DS
2750 ASSERT(!c->options.test_crypto);
2751 msg(M_WARN,
2752 "******* WARNING *******: all encryption and authentication features disabled -- all data will be tunnelled as cleartext");
6fbf66fa 2753}
81d882d5 2754#endif /* ifdef ENABLE_CRYPTO */
6fbf66fa
JY
2755
2756static void
81d882d5 2757do_init_crypto(struct context *c, const unsigned int flags)
6fbf66fa 2758{
9b33b5a4 2759#ifdef ENABLE_CRYPTO
81d882d5
DS
2760 if (c->options.shared_secret_file)
2761 {
2762 do_init_crypto_static(c, flags);
2763 }
2764 else if (c->options.tls_server || c->options.tls_client)
2765 {
2766 do_init_crypto_tls(c, flags);
2767 }
2768 else /* no encryption or authentication. */
2769 {
2770 do_init_crypto_none(c);
2771 }
9b33b5a4 2772#else /* ENABLE_CRYPTO */
81d882d5
DS
2773 msg(M_WARN,
2774 "******* WARNING *******: " PACKAGE_NAME
2775 " built without crypto library -- encryption and authentication features disabled -- all data will be tunnelled as cleartext");
9b33b5a4 2776#endif /* ENABLE_CRYPTO */
6fbf66fa
JY
2777}
2778
2779static void
81d882d5 2780do_init_frame(struct context *c)
6fbf66fa 2781{
38d96bd7 2782#ifdef USE_COMP
81d882d5
DS
2783 /*
2784 * modify frame parameters if compression is enabled
2785 */
2786 if (comp_enabled(&c->options.comp))
6fbf66fa 2787 {
81d882d5 2788 comp_add_to_extra_frame(&c->c2.frame);
6fbf66fa 2789
9403e3f4 2790#if !defined(ENABLE_LZ4)
81d882d5
DS
2791 /*
2792 * Compression usage affects buffer alignment when non-swapped algs
2793 * such as LZO is used.
2794 * Newer algs like LZ4 and comp-stub with COMP_F_SWAP don't need
2795 * any special alignment because of the control-byte swap approach.
2796 * LZO alignment (on the other hand) is problematic because
2797 * the presence of the control byte means that either the output of
2798 * decryption must be written to an unaligned buffer, or the input
2799 * to compression (or packet dispatch if packet is uncompressed)
2800 * must be read from an unaligned buffer.
2801 * This code tries to align the input to compression (or packet
2802 * dispatch if packet is uncompressed) at the cost of requiring
2803 * decryption output to be written to an unaligned buffer, so
2804 * it's more of a tradeoff than an optimal solution and we don't
2805 * include it when we are doing a modern build with LZ4.
2806 * Strictly speaking, on the server it would be better to execute
2807 * this code for every connection after we decide the compression
2808 * method, but currently the frame code doesn't appear to be
2809 * flexible enough for this, since the frame is already established
2810 * before it is known which compression options will be pushed.
2811 */
2812 if (comp_unswapped_prefix(&c->options.comp) && CIPHER_ENABLED(c))
2813 {
2814 frame_add_to_align_adjust(&c->c2.frame, COMP_PREFIX_LEN);
2815 frame_or_align_flags(&c->c2.frame,
2816 FRAME_HEADROOM_MARKER_FRAGMENT
2817 |FRAME_HEADROOM_MARKER_DECRYPT);
2818 }
38d96bd7 2819#endif
6fbf66fa
JY
2820
2821#ifdef ENABLE_FRAGMENT
81d882d5 2822 comp_add_to_extra_frame(&c->c2.frame_fragment_omit); /* omit compression frame delta from final frame_fragment */
6fbf66fa
JY
2823#endif
2824 }
38d96bd7 2825#endif /* USE_COMP */
6fbf66fa 2826
81d882d5
DS
2827 /*
2828 * Adjust frame size for UDP Socks support.
2829 */
2830 if (c->options.ce.socks_proxy_server)
2831 {
2832 socks_adjust_frame_parameters(&c->c2.frame, c->options.ce.proto);
2833 }
2834
2835 /*
2836 * Adjust frame size based on the --tun-mtu-extra parameter.
2837 */
2838 if (c->options.ce.tun_mtu_extra_defined)
2839 {
2840 tun_adjust_frame_parameters(&c->c2.frame, c->options.ce.tun_mtu_extra);
2841 }
2842
2843 /*
2844 * Adjust frame size based on link socket parameters.
2845 * (Since TCP is a stream protocol, we need to insert
2846 * a packet length uint16_t in the buffer.)
2847 */
2848 socket_adjust_frame_parameters(&c->c2.frame, c->options.ce.proto);
2849
2850 /*
2851 * Fill in the blanks in the frame parameters structure,
2852 * make sure values are rational, etc.
2853 */
2854 frame_finalize_options(c, NULL);
6fbf66fa 2855
38d96bd7 2856#ifdef USE_COMP
81d882d5
DS
2857 /*
2858 * Modify frame parameters if compression is compiled in.
2859 * Should be called after frame_finalize_options.
2860 */
2861 comp_add_to_extra_buffer(&c->c2.frame);
38d96bd7 2862#ifdef ENABLE_FRAGMENT
81d882d5 2863 comp_add_to_extra_buffer(&c->c2.frame_fragment_omit); /* omit compression frame delta from final frame_fragment */
38d96bd7
JY
2864#endif
2865#endif /* USE_COMP */
2866
81d882d5
DS
2867 /* packets with peer-id (P_DATA_V2) need 3 extra bytes in frame (on client)
2868 * and need link_mtu+3 bytes on socket reception (on server).
2869 *
2870 * accomodate receive path in f->extra_link, which has the side effect of
2871 * also increasing send buffers (BUF_SIZE() macro), which need to be
2872 * allocated big enough before receiving peer-id option from server.
2873 *
2874 * f->extra_frame is adjusted when peer-id option is push-received
2875 */
2876 frame_add_to_extra_link(&c->c2.frame, 3);
9e0963c1 2877
6fbf66fa 2878#ifdef ENABLE_FRAGMENT
81d882d5
DS
2879 /*
2880 * Set frame parameter for fragment code. This is necessary because
2881 * the fragmentation code deals with payloads which have already been
2882 * passed through the compression code.
2883 */
2884 c->c2.frame_fragment = c->c2.frame;
2885 frame_subtract_extra(&c->c2.frame_fragment, &c->c2.frame_fragment_omit);
6fbf66fa
JY
2886#endif
2887
2888#if defined(ENABLE_FRAGMENT) && defined(ENABLE_OCC)
81d882d5
DS
2889 /*
2890 * MTU advisories
2891 */
2892 if (c->options.ce.fragment && c->options.mtu_test)
2893 {
2894 msg(M_WARN,
2895 "WARNING: using --fragment and --mtu-test together may produce an inaccurate MTU test result");
2896 }
6fbf66fa
JY
2897#endif
2898
2899#ifdef ENABLE_FRAGMENT
81d882d5
DS
2900 if ((c->options.ce.mssfix || c->options.ce.fragment)
2901 && TUN_MTU_SIZE(&c->c2.frame_fragment) != ETHERNET_MTU)
2902 {
2903 msg(M_WARN,
2904 "WARNING: normally if you use --mssfix and/or --fragment, you should also set --tun-mtu %d (currently it is %d)",
2905 ETHERNET_MTU, TUN_MTU_SIZE(&c->c2.frame_fragment));
2906 }
6fbf66fa
JY
2907#endif
2908}
2909
2910static void
81d882d5 2911do_option_warnings(struct context *c)
6fbf66fa 2912{
81d882d5 2913 const struct options *o = &c->options;
6fbf66fa 2914
81d882d5
DS
2915 if (o->ping_send_timeout && !o->ping_rec_timeout)
2916 {
2917 msg(M_WARN, "WARNING: --ping should normally be used with --ping-restart or --ping-exit");
2918 }
6fbf66fa 2919
81d882d5 2920 if (o->username || o->groupname || o->chroot_dir
cd5990e0 2921#ifdef ENABLE_SELINUX
81d882d5 2922 || o->selinux_context
99385447 2923#endif
81d882d5
DS
2924 )
2925 {
2926 if (!o->persist_tun)
2927 {
2928 msg(M_WARN, "WARNING: you are using user/group/chroot/setcon without persist-tun -- this may cause restarts to fail");
2929 }
2930 if (!o->persist_key
51b1d4c2 2931#ifdef ENABLE_PKCS11
81d882d5 2932 && !o->pkcs11_id
51b1d4c2 2933#endif
81d882d5
DS
2934 )
2935 {
2936 msg(M_WARN, "WARNING: you are using user/group/chroot/setcon without persist-key -- this may cause restarts to fail");
2937 }
2938 }
6fbf66fa 2939
81d882d5
DS
2940 if (o->chroot_dir && !(o->username && o->groupname))
2941 {
2942 msg(M_WARN, "WARNING: you are using chroot without specifying user and group -- this may cause the chroot jail to be insecure");
2943 }
31f90e64 2944
6fbf66fa 2945#if P2MP
81d882d5
DS
2946 if (o->pull && o->ifconfig_local && c->first_time)
2947 {
2948 msg(M_WARN, "WARNING: using --pull/--client and --ifconfig together is probably not what you want");
2949 }
6fbf66fa
JY
2950
2951#if P2MP_SERVER
81d882d5
DS
2952 if (o->server_bridge_defined | o->server_bridge_proxy_dhcp)
2953 {
2954 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");
2955 }
f77c60d3 2956
81d882d5 2957 if (o->mode == MODE_SERVER)
6fbf66fa 2958 {
81d882d5
DS
2959 if (o->duplicate_cn && o->client_config_dir)
2960 {
2961 msg(M_WARN, "WARNING: using --duplicate-cn and --client-config-dir together is probably not what you want");
2962 }
2963 if (o->duplicate_cn && o->ifconfig_pool_persist_filename)
2964 {
2965 msg(M_WARN, "WARNING: --ifconfig-pool-persist will not work with --duplicate-cn");
2966 }
2967 if (!o->keepalive_ping || !o->keepalive_timeout)
2968 {
2969 msg(M_WARN, "WARNING: --keepalive option is missing from server config");
2970 }
6fbf66fa 2971 }
81d882d5
DS
2972#endif /* if P2MP_SERVER */
2973#endif /* if P2MP */
6fbf66fa 2974
9b33b5a4 2975#ifdef ENABLE_CRYPTO
81d882d5
DS
2976 if (!o->replay)
2977 {
2978 msg(M_WARN, "WARNING: You have disabled Replay Protection (--no-replay) which may make " PACKAGE_NAME " less secure");
2979 }
81d882d5
DS
2980
2981 if (o->tls_server)
2982 {
2983 warn_on_use_of_common_subnets();
2984 }
2985 if (o->tls_client
2986 && !o->tls_verify
2987 && o->verify_x509_type == VERIFY_X509_NONE
2988 && !(o->ns_cert_type & NS_CERT_CHECK_SERVER)
2989 && !o->remote_cert_eku)
2990 {
2991 msg(M_WARN, "WARNING: No server certificate verification method has been enabled. See http://openvpn.net/howto.html#mitm for more info.");
2992 }
2993#endif /* ifdef ENABLE_CRYPTO */
2994
2995 /* If a script is used, print appropiate warnings */
2996 if (o->user_script_used)
2997 {
2998 if (script_security >= SSEC_SCRIPTS)
2999 {
3000 msg(M_WARN, "NOTE: the current --script-security setting may allow this configuration to call user-defined scripts");
3001 }
3002 else if (script_security >= SSEC_PW_ENV)
3003 {
3004 msg(M_WARN, "WARNING: the current --script-security setting may allow passwords to be passed to scripts via environmental variables");
3005 }
3006 else
3007 {
3008 msg(M_WARN, "NOTE: starting with " PACKAGE_NAME " 2.1, '--script-security 2' or higher is required to call user-defined scripts or executables");
3009 }
3010 }
6fbf66fa
JY
3011}
3012
3013static void
81d882d5 3014do_init_frame_tls(struct context *c)
6fbf66fa 3015{
ec828db6 3016#ifdef ENABLE_CRYPTO
81d882d5 3017 do_init_finalize_tls_frame(c);
6fbf66fa
JY
3018#endif
3019}
3020
3021struct context_buffers *
81d882d5 3022init_context_buffers(const struct frame *frame)
6fbf66fa 3023{
81d882d5 3024 struct context_buffers *b;
6fbf66fa 3025
81d882d5 3026 ALLOC_OBJ_CLEAR(b, struct context_buffers);
6fbf66fa 3027
81d882d5
DS
3028 b->read_link_buf = alloc_buf(BUF_SIZE(frame));
3029 b->read_tun_buf = alloc_buf(BUF_SIZE(frame));
6fbf66fa 3030
81d882d5 3031 b->aux_buf = alloc_buf(BUF_SIZE(frame));
6fbf66fa 3032
9b33b5a4 3033#ifdef ENABLE_CRYPTO
81d882d5
DS
3034 b->encrypt_buf = alloc_buf(BUF_SIZE(frame));
3035 b->decrypt_buf = alloc_buf(BUF_SIZE(frame));
6fbf66fa
JY
3036#endif
3037
38d96bd7 3038#ifdef USE_COMP
81d882d5
DS
3039 b->compress_buf = alloc_buf(BUF_SIZE(frame));
3040 b->decompress_buf = alloc_buf(BUF_SIZE(frame));
6fbf66fa
JY
3041#endif
3042
81d882d5 3043 return b;
6fbf66fa
JY
3044}
3045
3046void
81d882d5 3047free_context_buffers(struct context_buffers *b)
6fbf66fa 3048{
81d882d5 3049 if (b)
6fbf66fa 3050 {
81d882d5
DS
3051 free_buf(&b->read_link_buf);
3052 free_buf(&b->read_tun_buf);
3053 free_buf(&b->aux_buf);
6fbf66fa 3054
38d96bd7 3055#ifdef USE_COMP
81d882d5
DS
3056 free_buf(&b->compress_buf);
3057 free_buf(&b->decompress_buf);
6fbf66fa
JY
3058#endif
3059
9b33b5a4 3060#ifdef ENABLE_CRYPTO
81d882d5
DS
3061 free_buf(&b->encrypt_buf);
3062 free_buf(&b->decrypt_buf);
6fbf66fa
JY
3063#endif
3064
81d882d5 3065 free(b);
6fbf66fa
JY
3066 }
3067}
3068
3069/*
3070 * Now that we know all frame parameters, initialize
3071 * our buffers.
3072 */
3073static void
81d882d5 3074do_init_buffers(struct context *c)
6fbf66fa 3075{
81d882d5
DS
3076 c->c2.buffers = init_context_buffers(&c->c2.frame);
3077 c->c2.buffers_owned = true;
6fbf66fa
JY
3078}
3079
3080#ifdef ENABLE_FRAGMENT
3081/*
3082 * Fragmenting code has buffers to initialize
3083 * once frame parameters are known.
3084 */
3085static void
81d882d5 3086do_init_fragment(struct context *c)
6fbf66fa 3087{
81d882d5
DS
3088 ASSERT(c->options.ce.fragment);
3089 frame_set_mtu_dynamic(&c->c2.frame_fragment,
3090 c->options.ce.fragment, SET_MTU_UPPER_BOUND);
3091 fragment_frame_init(c->c2.fragment, &c->c2.frame_fragment);
6fbf66fa
JY
3092}
3093#endif
3094
6fbf66fa
JY
3095/*
3096 * Allocate our socket object.
3097 */
3098static void
81d882d5 3099do_link_socket_new(struct context *c)
6fbf66fa 3100{
81d882d5
DS
3101 ASSERT(!c->c2.link_socket);
3102 c->c2.link_socket = link_socket_new();
3103 c->c2.link_socket_owned = true;
6fbf66fa
JY
3104}
3105
3106/*
3107 * bind the TCP/UDP socket
3108 */
3109static void
81d882d5 3110do_init_socket_1(struct context *c, const int mode)
6fbf66fa 3111{
81d882d5 3112 unsigned int sockflags = c->options.sockflags;
dc46c067
JY
3113
3114#if PORT_SHARE
81d882d5
DS
3115 if (c->options.port_share_host && c->options.port_share_port)
3116 {
3117 sockflags |= SF_PORT_SHARE;
3118 }
3119#endif
3120
3121 link_socket_init_phase1(c->c2.link_socket,
3122 c->options.ce.local,
3123 c->options.ce.local_port,
3124 c->options.ce.remote,
3125 c->options.ce.remote_port,
3126 c->c1.dns_cache,
3127 c->options.ce.proto,
3128 c->options.ce.af,
3129 c->options.ce.bind_ipv6_only,
3130 mode,
3131 c->c2.accept_from,
3132 c->c1.http_proxy,
3133 c->c1.socks_proxy,
6fbf66fa 3134#ifdef ENABLE_DEBUG
81d882d5
DS
3135 c->options.gremlin,
3136#endif
3137 c->options.ce.bind_local,
3138 c->options.ce.remote_float,
3139 c->options.inetd,
3140 &c->c1.link_socket_addr,
3141 c->options.ipchange,
3142 c->plugins,
3143 c->options.resolve_retry_seconds,
3144 c->options.ce.mtu_discover_type,
3145 c->options.rcvbuf,
3146 c->options.sndbuf,
3147 c->options.mark,
3148 &c->c2.server_poll_interval,
3149 sockflags);
6fbf66fa
JY
3150}
3151
3152/*
3153 * finalize the TCP/UDP socket
3154 */
3155static void
81d882d5 3156do_init_socket_2(struct context *c)
6fbf66fa 3157{
81d882d5
DS
3158 link_socket_init_phase2(c->c2.link_socket, &c->c2.frame,
3159 c->sig);
6fbf66fa
JY
3160}
3161
3162/*
3163 * Print MTU INFO
3164 */
3165static void
81d882d5 3166do_print_data_channel_mtu_parms(struct context *c)
6fbf66fa 3167{
81d882d5 3168 frame_print(&c->c2.frame, D_MTU_INFO, "Data Channel MTU parms");
6fbf66fa 3169#ifdef ENABLE_FRAGMENT
81d882d5
DS
3170 if (c->c2.fragment)
3171 {
3172 frame_print(&c->c2.frame_fragment, D_MTU_INFO,
3173 "Fragmentation MTU parms");
3174 }
6fbf66fa
JY
3175#endif
3176}
3177
3178#ifdef ENABLE_OCC
3179/*
3180 * Get local and remote options compatibility strings.
3181 */
3182static void
81d882d5 3183do_compute_occ_strings(struct context *c)
6fbf66fa 3184{
81d882d5 3185 struct gc_arena gc = gc_new();
6fbf66fa 3186
81d882d5
DS
3187 c->c2.options_string_local =
3188 options_string(&c->options, &c->c2.frame, c->c1.tuntap, false, &gc);
3189 c->c2.options_string_remote =
3190 options_string(&c->options, &c->c2.frame, c->c1.tuntap, true, &gc);
6fbf66fa 3191
81d882d5
DS
3192 msg(D_SHOW_OCC, "Local Options String (VER=%s): '%s'",
3193 options_string_version(c->c2.options_string_local, &gc),
3194 c->c2.options_string_local);
3195 msg(D_SHOW_OCC, "Expected Remote Options String (VER=%s): '%s'",
3196 options_string_version(c->c2.options_string_remote, &gc),
3197 c->c2.options_string_remote);
6fbf66fa 3198
9b33b5a4 3199#ifdef ENABLE_CRYPTO
81d882d5
DS
3200 if (c->c2.tls_multi)
3201 {
3202 tls_multi_init_set_options(c->c2.tls_multi,
3203 c->c2.options_string_local,
3204 c->c2.options_string_remote);
3205 }
6fbf66fa
JY
3206#endif
3207
81d882d5 3208 gc_free(&gc);
6fbf66fa 3209}
81d882d5 3210#endif /* ifdef ENABLE_OCC */
6fbf66fa
JY
3211
3212/*
3213 * These things can only be executed once per program instantiation.
3214 * Set up for possible UID/GID downgrade, but don't do it yet.
3215 * Daemonize if requested.
3216 */
3217static void
81d882d5 3218do_init_first_time(struct context *c)
6fbf66fa 3219{
81d882d5 3220 if (c->first_time && !c->c0)
6fbf66fa 3221 {
81d882d5 3222 struct context_0 *c0;
92bbb061 3223
81d882d5
DS
3224 ALLOC_OBJ_CLEAR_GC(c->c0, struct context_0, &c->gc);
3225 c0 = c->c0;
6fbf66fa 3226
81d882d5
DS
3227 /* get user and/or group that we want to setuid/setgid to */
3228 c0->uid_gid_specified =
3229 platform_group_get(c->options.groupname, &c0->platform_state_group)
3230 |platform_user_get(c->options.username, &c0->platform_state_user);
6fbf66fa 3231
81d882d5
DS
3232 /* perform postponed chdir if --daemon */
3233 if (c->did_we_daemonize && c->options.cd_dir == NULL)
3234 {
3235 platform_chdir("/");
3236 }
3237
3238 /* should we change scheduling priority? */
3239 platform_nice(c->options.nice);
6fbf66fa
JY
3240 }
3241}
3242
3243/*
3244 * If xinetd/inetd mode, don't allow restart.
3245 */
3246static void
81d882d5 3247do_close_check_if_restart_permitted(struct context *c)
6fbf66fa 3248{
81d882d5
DS
3249 if (c->options.inetd
3250 && (c->sig->signal_received == SIGHUP
3251 || c->sig->signal_received == SIGUSR1))
6fbf66fa 3252 {
81d882d5
DS
3253 c->sig->signal_received = SIGTERM;
3254 msg(M_INFO,
3255 PACKAGE_NAME
3256 " started by inetd/xinetd cannot restart... Exiting.");
6fbf66fa
JY
3257 }
3258}
3259
3260/*
3261 * free buffers
3262 */
3263static void
81d882d5 3264do_close_free_buf(struct context *c)
6fbf66fa 3265{
81d882d5 3266 if (c->c2.buffers_owned)
6fbf66fa 3267 {
81d882d5
DS
3268 free_context_buffers(c->c2.buffers);
3269 c->c2.buffers = NULL;
3270 c->c2.buffers_owned = false;
6fbf66fa
JY
3271 }
3272}
3273
3274/*
3275 * close TLS
3276 */
3277static void
81d882d5 3278do_close_tls(struct context *c)
6fbf66fa 3279{
ec828db6 3280#ifdef ENABLE_CRYPTO
81d882d5 3281 if (c->c2.tls_multi)
6fbf66fa 3282 {
81d882d5
DS
3283 tls_multi_free(c->c2.tls_multi, true);
3284 c->c2.tls_multi = NULL;
6fbf66fa
JY
3285 }
3286
3287#ifdef ENABLE_OCC
81d882d5
DS
3288 /* free options compatibility strings */
3289 if (c->c2.options_string_local)
3290 {
3291 free(c->c2.options_string_local);
3292 }
3293 if (c->c2.options_string_remote)
3294 {
3295 free(c->c2.options_string_remote);
3296 }
3297 c->c2.options_string_local = c->c2.options_string_remote = NULL;
6fbf66fa
JY
3298#endif
3299#endif
3300}
3301
3302/*
3303 * Free key schedules
3304 */
3305static void
81d882d5 3306do_close_free_key_schedule(struct context *c, bool free_ssl_ctx)
6fbf66fa 3307{
81d882d5
DS
3308 if (!(c->sig->signal_received == SIGUSR1 && c->options.persist_key))
3309 {
3310 key_schedule_free(&c->c1.ks, free_ssl_ctx);
3311 }
6fbf66fa
JY
3312}
3313
3314/*
3315 * Close TCP/UDP connection
3316 */
3317static void
81d882d5 3318do_close_link_socket(struct context *c)
6fbf66fa 3319{
81d882d5 3320 if (c->c2.link_socket && c->c2.link_socket_owned)
6fbf66fa 3321 {
81d882d5
DS
3322 link_socket_close(c->c2.link_socket);
3323 c->c2.link_socket = NULL;
6fbf66fa
JY
3324 }
3325
81d882d5
DS
3326
3327 /* Preserve the resolved list of remote if the user request to or if we want
3328 * reconnect to the same host again or there are still addresses that need
3329 * to be tried */
3330 if (!(c->sig->signal_received == SIGUSR1
3331 && ( (c->options.persist_remote_ip)
3332 ||
3333 ( c->sig->source != SIG_SOURCE_HARD
3334 && ((c->c1.link_socket_addr.current_remote && c->c1.link_socket_addr.current_remote->ai_next)
3335 || c->options.no_advance))
3336 )))
23d61c56 3337 {
81d882d5 3338 clear_remote_addrlist(&c->c1.link_socket_addr, !c->options.resolve_in_advance);
23d61c56
AS
3339 }
3340
3341 /* Clear the remote actual address when persist_remote_ip is not in use */
3342 if (!(c->sig->signal_received == SIGUSR1 && c->options.persist_remote_ip))
81d882d5
DS
3343 {
3344 CLEAR(c->c1.link_socket_addr.actual);
3345 }
6fbf66fa 3346
81d882d5
DS
3347 if (!(c->sig->signal_received == SIGUSR1 && c->options.persist_local_ip))
3348 {
3349 if (c->c1.link_socket_addr.bind_local && !c->options.resolve_in_advance)
3350 {
3351 freeaddrinfo(c->c1.link_socket_addr.bind_local);
3352 }
e719a053 3353
81d882d5
DS
3354 c->c1.link_socket_addr.bind_local = NULL;
3355 }
6fbf66fa
JY
3356}
3357
3358/*
3359 * Close packet-id persistance file
3360 */
3361static void
81d882d5 3362do_close_packet_id(struct context *c)
6fbf66fa 3363{
9b33b5a4 3364#ifdef ENABLE_CRYPTO
81d882d5
DS
3365 packet_id_free(&c->c2.crypto_options.packet_id);
3366 packet_id_persist_save(&c->c1.pid_persist);
3367 if (!(c->sig->signal_received == SIGUSR1))
3368 {
3369 packet_id_persist_close(&c->c1.pid_persist);
3370 }
6fbf66fa
JY
3371#endif
3372}
3373
3374#ifdef ENABLE_FRAGMENT
3375/*
3376 * Close fragmentation handler.
3377 */
3378static void
81d882d5 3379do_close_fragment(struct context *c)
6fbf66fa 3380{
81d882d5 3381 if (c->c2.fragment)
6fbf66fa 3382 {
81d882d5
DS
3383 fragment_free(c->c2.fragment);
3384 c->c2.fragment = NULL;
6fbf66fa
JY
3385 }
3386}
3387#endif
3388
3389/*
3390 * Open and close our event objects.
3391 */
3392
3393static void
81d882d5
DS
3394do_event_set_init(struct context *c,
3395 bool need_us_timeout)
6fbf66fa 3396{
81d882d5 3397 unsigned int flags = 0;
6fbf66fa 3398
81d882d5 3399 c->c2.event_set_max = BASE_N_EVENTS;
6fbf66fa 3400
81d882d5 3401 flags |= EVENT_METHOD_FAST;
6fbf66fa 3402
81d882d5
DS
3403 if (need_us_timeout)
3404 {
3405 flags |= EVENT_METHOD_US_TIMEOUT;
3406 }
6fbf66fa 3407
81d882d5
DS
3408 c->c2.event_set = event_set_init(&c->c2.event_set_max, flags);
3409 c->c2.event_set_owned = true;
6fbf66fa
JY
3410}
3411
3412static void
81d882d5 3413do_close_event_set(struct context *c)
6fbf66fa 3414{
81d882d5 3415 if (c->c2.event_set && c->c2.event_set_owned)
6fbf66fa 3416 {
81d882d5
DS
3417 event_free(c->c2.event_set);
3418 c->c2.event_set = NULL;
3419 c->c2.event_set_owned = false;
6fbf66fa
JY
3420 }
3421}
3422
3423/*
3424 * Open and close --status file
3425 */
3426
3427static void
81d882d5 3428do_open_status_output(struct context *c)
6fbf66fa 3429{
81d882d5 3430 if (!c->c1.status_output)
6fbf66fa 3431 {
81d882d5
DS
3432 c->c1.status_output = status_open(c->options.status_file,
3433 c->options.status_file_update_freq,
3434 -1,
3435 NULL,
3436 STATUS_OUTPUT_WRITE);
3437 c->c1.status_output_owned = true;
6fbf66fa
JY
3438 }
3439}
3440
3441static void
81d882d5 3442do_close_status_output(struct context *c)
6fbf66fa 3443{
81d882d5 3444 if (!(c->sig->signal_received == SIGUSR1))
6fbf66fa 3445 {
81d882d5
DS
3446 if (c->c1.status_output_owned && c->c1.status_output)
3447 {
3448 status_close(c->c1.status_output);
3449 c->c1.status_output = NULL;
3450 c->c1.status_output_owned = false;
3451 }
6fbf66fa
JY
3452 }
3453}
3454
3455/*
3456 * Handle ifconfig-pool persistance object.
3457 */
3458static void
81d882d5 3459do_open_ifconfig_pool_persist(struct context *c)
6fbf66fa
JY
3460{
3461#if P2MP_SERVER
81d882d5 3462 if (!c->c1.ifconfig_pool_persist && c->options.ifconfig_pool_persist_filename)
6fbf66fa 3463 {
81d882d5
DS
3464 c->c1.ifconfig_pool_persist = ifconfig_pool_persist_init(c->options.ifconfig_pool_persist_filename,
3465 c->options.ifconfig_pool_persist_refresh_freq);
3466 c->c1.ifconfig_pool_persist_owned = true;
6fbf66fa
JY
3467 }
3468#endif
3469}
3470
3471static void
81d882d5 3472do_close_ifconfig_pool_persist(struct context *c)
6fbf66fa
JY
3473{
3474#if P2MP_SERVER
81d882d5 3475 if (!(c->sig->signal_received == SIGUSR1))
6fbf66fa 3476 {
81d882d5
DS
3477 if (c->c1.ifconfig_pool_persist && c->c1.ifconfig_pool_persist_owned)
3478 {
3479 ifconfig_pool_persist_close(c->c1.ifconfig_pool_persist);
3480 c->c1.ifconfig_pool_persist = NULL;
3481 c->c1.ifconfig_pool_persist_owned = false;
3482 }
6fbf66fa
JY
3483 }
3484#endif
3485}
3486
3487/*
3488 * Inherit environmental variables
3489 */
3490
3491static void
81d882d5 3492do_inherit_env(struct context *c, const struct env_set *src)
6fbf66fa 3493{
81d882d5
DS
3494 c->c2.es = env_set_create(NULL);
3495 c->c2.es_owned = true;
3496 env_set_inherit(c->c2.es, src);
6fbf66fa
JY
3497}
3498
2a64816b 3499static void
81d882d5 3500do_env_set_destroy(struct context *c)
2a64816b 3501{
81d882d5 3502 if (c->c2.es && c->c2.es_owned)
2a64816b 3503 {
81d882d5
DS
3504 env_set_destroy(c->c2.es);
3505 c->c2.es = NULL;
3506 c->c2.es_owned = false;
2a64816b
JY
3507 }
3508}
3509
6fbf66fa
JY
3510/*
3511 * Fast I/O setup. Fast I/O is an optimization which only works
3512 * if all of the following are true:
3513 *
3514 * (1) The platform is not Windows
3515 * (2) --proto udp is enabled
3516 * (3) --shaper is disabled
3517 */
3518static void
81d882d5 3519do_setup_fast_io(struct context *c)
6fbf66fa 3520{
81d882d5 3521 if (c->options.fast_io)
6fbf66fa 3522 {
445b192a 3523#ifdef _WIN32
81d882d5 3524 msg(M_INFO, "NOTE: --fast-io is disabled since we are running on Windows");
6fbf66fa 3525#else
81d882d5
DS
3526 if (!proto_is_udp(c->options.ce.proto))
3527 {
3528 msg(M_INFO, "NOTE: --fast-io is disabled since we are not using UDP");
3529 }
3530 else
3531 {
3d163bc5 3532#ifdef ENABLE_FEATURE_SHAPER
81d882d5
DS
3533 if (c->options.shaper)
3534 {
3535 msg(M_INFO, "NOTE: --fast-io is disabled since we are using --shaper");
3536 }
3537 else
0475d17e 3538#endif
81d882d5
DS
3539 {
3540 c->c2.fast_io = true;
3541 }
3542 }
6fbf66fa
JY
3543#endif
3544 }
3545}
3546
3547static void
81d882d5 3548do_signal_on_tls_errors(struct context *c)
6fbf66fa 3549{
ec828db6 3550#ifdef ENABLE_CRYPTO
81d882d5
DS
3551 if (c->options.tls_exit)
3552 {
3553 c->c2.tls_exit_signal = SIGTERM;
3554 }
3555 else
3556 {
3557 c->c2.tls_exit_signal = SIGUSR1;
3558 }
6fbf66fa
JY
3559#endif
3560}
3561
3c7f2f55 3562#ifdef ENABLE_PLUGIN
6fbf66fa 3563
3c7f2f55 3564void
81d882d5 3565init_plugins(struct context *c)
6fbf66fa 3566{
81d882d5 3567 if (c->options.plugin_list && !c->plugins)
e1791bb1 3568 {
81d882d5
DS
3569 c->plugins = plugin_list_init(c->options.plugin_list);
3570 c->plugins_owned = true;
e1791bb1
JY
3571 }
3572}
3573
3574void
81d882d5
DS
3575open_plugins(struct context *c, const bool import_options, int init_point)
3576{
3577 if (c->plugins && c->plugins_owned)
3578 {
3579 if (import_options)
3580 {
3581 struct plugin_return pr, config;
3582 plugin_return_init(&pr);
3583 plugin_list_open(c->plugins, c->options.plugin_list, &pr, c->c2.es, init_point);
3584 plugin_return_get_column(&pr, &config, "config");
3585 if (plugin_return_defined(&config))
3586 {
3587 int i;
3588 for (i = 0; i < config.n; ++i)
3589 {
3590 unsigned int option_types_found = 0;
3591 if (config.list[i] && config.list[i]->value)
3592 {
3593 options_string_import(&c->options,
3594 config.list[i]->value,
3595 D_IMPORT_ERRORS|M_OPTERR,
3596 OPT_P_DEFAULT & ~OPT_P_PLUGIN,
3597 &option_types_found,
3598 c->es);
3599 }
3600 }
3601 }
3602 plugin_return_free(&pr);
3603 }
3604 else
3605 {
3606 plugin_list_open(c->plugins, c->options.plugin_list, NULL, c->c2.es, init_point);
3607 }
6fbf66fa 3608 }
6fbf66fa
JY
3609}
3610
3611static void
81d882d5 3612do_close_plugins(struct context *c)
6fbf66fa 3613{
81d882d5 3614 if (c->plugins && c->plugins_owned && !(c->sig->signal_received == SIGUSR1))
6fbf66fa 3615 {
81d882d5
DS
3616 plugin_list_close(c->plugins);
3617 c->plugins = NULL;
3618 c->plugins_owned = false;
6fbf66fa 3619 }
6fbf66fa
JY
3620}
3621
3c7f2f55 3622static void
81d882d5 3623do_inherit_plugins(struct context *c, const struct context *src)
3c7f2f55 3624{
81d882d5 3625 if (!c->plugins && src->plugins)
3c7f2f55 3626 {
81d882d5
DS
3627 c->plugins = plugin_list_inherit(src->plugins);
3628 c->plugins_owned = true;
3c7f2f55
JY
3629 }
3630}
3631
81d882d5 3632#endif /* ifdef ENABLE_PLUGIN */
3c7f2f55 3633
6fbf66fa
JY
3634#ifdef ENABLE_MANAGEMENT
3635
3636static void
81d882d5 3637management_callback_status_p2p(void *arg, const int version, struct status_output *so)
6fbf66fa 3638{
81d882d5
DS
3639 struct context *c = (struct context *) arg;
3640 print_status(c, so);
6fbf66fa
JY
3641}
3642
3643void
81d882d5 3644management_show_net_callback(void *arg, const int msglevel)
6fbf66fa 3645{
445b192a 3646#ifdef _WIN32
81d882d5
DS
3647 show_routes(msglevel);
3648 show_adapters(msglevel);
3649 msg(msglevel, "END");
6fbf66fa 3650#else
81d882d5 3651 msg(msglevel, "ERROR: Sorry, this command is currently only implemented on Windows");
6fbf66fa
JY
3652#endif
3653}
3654
30003978
AS
3655#ifdef TARGET_ANDROID
3656int
81d882d5 3657management_callback_network_change(void *arg, bool samenetwork)
30003978
AS
3658{
3659 /* Check if the client should translate the network change to a SIGUSR1 to
81d882d5
DS
3660 * reestablish the connection or just reprotect the socket
3661 *
3662 * At the moment just assume that, for all settings that use pull (not
3663 * --static) and are not using peer-id reestablishing the connection is
3664 * required (unless the network is the same)
3665 *
3666 * The function returns -1 on invalid fd and -2 if the socket cannot be
3667 * reused. On the -2 return value the man_network_change function triggers
3668 * a SIGUSR1 to force a reconnect.
3669 */
3670
3671 int socketfd = -1;
3672 struct context *c = (struct context *) arg;
3673 if (!c->c2.link_socket)
3674 {
3675 return -1;
3676 }
3677 if (c->c2.link_socket->sd == SOCKET_UNDEFINED)
3678 {
3679 return -1;
3680 }
30003978 3681
81d882d5
DS
3682 socketfd = c->c2.link_socket->sd;
3683 if (!c->options.pull || c->c2.tls_multi->use_peer_id || samenetwork)
3684 {
3685 return socketfd;
3686 }
3687 else
3688 {
3689 return -2;
3690 }
30003978 3691}
81d882d5 3692#endif /* ifdef TARGET_ANDROID */
30003978 3693
81d882d5 3694#endif /* ifdef ENABLE_MANAGEMENT */
6fbf66fa
JY
3695
3696void
81d882d5 3697init_management_callback_p2p(struct context *c)
6fbf66fa
JY
3698{
3699#ifdef ENABLE_MANAGEMENT
81d882d5
DS
3700 if (management)
3701 {
3702 struct management_callback cb;
3703 CLEAR(cb);
3704 cb.arg = c;
3705 cb.status = management_callback_status_p2p;
3706 cb.show_net = management_show_net_callback;
3707 cb.proxy_cmd = management_callback_proxy_cmd;
3708 cb.remote_cmd = management_callback_remote_cmd;
30003978 3709#ifdef TARGET_ANDROID
81d882d5 3710 cb.network_change = management_callback_network_change;
30003978 3711#endif
81d882d5 3712 management_set_callback(management, &cb);
6fbf66fa
JY
3713 }
3714#endif
3715}
3716
3717#ifdef ENABLE_MANAGEMENT
3718
3719void
81d882d5 3720init_management(struct context *c)
6fbf66fa 3721{
81d882d5
DS
3722 if (!management)
3723 {
3724 management = management_init();
3725 }
6fbf66fa
JY
3726}
3727
3728bool
81d882d5
DS
3729open_management(struct context *c)
3730{
3731 /* initialize management layer */
3732 if (management)
3733 {
3734 if (c->options.management_addr)
3735 {
3736 unsigned int flags = c->options.management_flags;
3737 if (c->options.mode == MODE_SERVER)
3738 {
3739 flags |= MF_SERVER;
3740 }
3741 if (management_open(management,
3742 c->options.management_addr,
3743 c->options.management_port,
3744 c->options.management_user_pass,
3745 c->options.management_client_user,
3746 c->options.management_client_group,
3747 c->options.management_log_history_cache,
3748 c->options.management_echo_buffer_size,
3749 c->options.management_state_buffer_size,
3750 c->options.management_write_peer_info_file,
3751 c->options.remap_sigusr1,
3752 flags))
3753 {
3754 management_set_state(management,
3755 OPENVPN_STATE_CONNECTING,
3756 NULL,
3757 NULL,
3758 NULL,
3759 NULL,
3760 NULL);
3761 }
3762
3763 /* initial management hold, called early, before first context initialization */
3764 do_hold(0);
3765 if (IS_SIG(c))
3766 {
3767 msg(M_WARN, "Signal received from management interface, exiting");
3768 return false;
3769 }
3770 }
3771 else
3772 {
3773 close_management();
3774 }
3775 }
3776 return true;
6fbf66fa
JY
3777}
3778
3779void
81d882d5 3780close_management(void)
6fbf66fa 3781{
81d882d5 3782 if (management)
6fbf66fa 3783 {
81d882d5
DS
3784 management_close(management);
3785 management = NULL;
6fbf66fa
JY
3786 }
3787}
3788
81d882d5 3789#endif /* ifdef ENABLE_MANAGEMENT */
6fbf66fa
JY
3790
3791
3792void
81d882d5 3793uninit_management_callback(void)
6fbf66fa
JY
3794{
3795#ifdef ENABLE_MANAGEMENT
81d882d5 3796 if (management)
6fbf66fa 3797 {
81d882d5 3798 management_clear_callback(management);
6fbf66fa
JY
3799 }
3800#endif
3801}
3802
3803/*
3804 * Initialize a tunnel instance, handle pre and post-init
3805 * signal settings.
3806 */
3807void
81d882d5 3808init_instance_handle_signals(struct context *c, const struct env_set *env, const unsigned int flags)
6fbf66fa 3809{
81d882d5
DS
3810 pre_init_signal_catch();
3811 init_instance(c, env, flags);
3812 post_init_signal_catch();
3813
3814 /*
3815 * This is done so that signals thrown during
3816 * initialization can bring us back to
3817 * a management hold.
3818 */
3819 if (IS_SIG(c))
d5badcf1 3820 {
81d882d5
DS
3821 remap_signal(c);
3822 uninit_management_callback();
d5badcf1 3823 }
6fbf66fa
JY
3824}
3825
3826/*
3827 * Initialize a tunnel instance.
3828 */
3829void
81d882d5 3830init_instance(struct context *c, const struct env_set *env, const unsigned int flags)
6fbf66fa 3831{
81d882d5
DS
3832 const struct options *options = &c->options;
3833 const bool child = (c->mode == CM_CHILD_TCP || c->mode == CM_CHILD_UDP);
3834 int link_socket_mode = LS_MODE_DEFAULT;
6fbf66fa 3835
81d882d5
DS
3836 /* init garbage collection level */
3837 gc_init(&c->c2.gc);
6fbf66fa 3838
81d882d5
DS
3839 /* inherit environmental variables */
3840 if (env)
3841 {
3842 do_inherit_env(c, env);
3843 }
ac1c2f25 3844
81d882d5
DS
3845 /* signals caught here will abort */
3846 c->sig->signal_received = 0;
3847 c->sig->signal_text = NULL;
3848 c->sig->source = SIG_SOURCE_SOFT;
6fbf66fa 3849
81d882d5
DS
3850 if (c->mode == CM_P2P)
3851 {
3852 init_management_callback_p2p(c);
3853 }
3cf6c932 3854
81d882d5
DS
3855 /* possible sleep or management hold if restart */
3856 if (c->mode == CM_P2P || c->mode == CM_TOP)
3cf6c932 3857 {
81d882d5
DS
3858 do_startup_pause(c);
3859 if (IS_SIG(c))
3860 {
3861 goto sig;
3862 }
3cf6c932
JY
3863 }
3864
81d882d5 3865 if (c->options.resolve_in_advance)
e719a053 3866 {
81d882d5
DS
3867 do_preresolve(c);
3868 if (IS_SIG(c))
3869 {
3870 goto sig;
3871 }
e719a053
AS
3872 }
3873
81d882d5
DS
3874 /* map in current connection entry */
3875 next_connection_entry(c);
4e9a51d7 3876
81d882d5
DS
3877 /* link_socket_mode allows CM_CHILD_TCP
3878 * instances to inherit acceptable fds
3879 * from a top-level parent */
3880 if (c->options.ce.proto == PROTO_TCP_SERVER)
6fbf66fa 3881 {
81d882d5
DS
3882 if (c->mode == CM_TOP)
3883 {
3884 link_socket_mode = LS_MODE_TCP_LISTEN;
3885 }
3886 else if (c->mode == CM_CHILD_TCP)
3887 {
3888 link_socket_mode = LS_MODE_TCP_ACCEPT_FROM;
3889 }
6fbf66fa
JY
3890 }
3891
81d882d5
DS
3892 /* should we disable paging? */
3893 if (c->first_time && options->mlock)
3894 {
3895 platform_mlockall(true);
3896 }
6fbf66fa 3897
92bbb061 3898#if P2MP
81d882d5
DS
3899 /* get passwords if undefined */
3900 if (auth_retry_get() == AR_INTERACT)
3901 {
3902 init_query_passwords(c);
3903 }
92bbb061
JY
3904#endif
3905
81d882d5
DS
3906 /* initialize context level 2 --verb/--mute parms */
3907 init_verb_mute(c, IVM_LEVEL_2);
3908
3909 /* set error message delay for non-server modes */
3910 if (c->mode == CM_P2P)
3911 {
3912 set_check_status_error_delay(P2P_ERROR_DELAY_MS);
3913 }
6fbf66fa 3914
81d882d5
DS
3915 /* warn about inconsistent options */
3916 if (c->mode == CM_P2P || c->mode == CM_TOP)
3917 {
3918 do_option_warnings(c);
3919 }
6fbf66fa 3920
3c7f2f55 3921#ifdef ENABLE_PLUGIN
81d882d5
DS
3922 /* initialize plugins */
3923 if (c->mode == CM_P2P || c->mode == CM_TOP)
3924 {
3925 open_plugins(c, false, OPENVPN_PLUGIN_INIT_PRE_DAEMON);
3926 }
3c7f2f55 3927#endif
6fbf66fa 3928
81d882d5
DS
3929 /* should we enable fast I/O? */
3930 if (c->mode == CM_P2P || c->mode == CM_TOP)
3931 {
3932 do_setup_fast_io(c);
3933 }
6fbf66fa 3934
81d882d5
DS
3935 /* should we throw a signal on TLS errors? */
3936 do_signal_on_tls_errors(c);
6fbf66fa 3937
81d882d5
DS
3938 /* open --status file */
3939 if (c->mode == CM_P2P || c->mode == CM_TOP)
3940 {
3941 do_open_status_output(c);
3942 }
6fbf66fa 3943
81d882d5
DS
3944 /* open --ifconfig-pool-persist file */
3945 if (c->mode == CM_TOP)
3946 {
3947 do_open_ifconfig_pool_persist(c);
3948 }
6fbf66fa
JY
3949
3950#ifdef ENABLE_OCC
81d882d5
DS
3951 /* reset OCC state */
3952 if (c->mode == CM_P2P || child)
3953 {
3954 c->c2.occ_op = occ_reset_op();
3955 }
6fbf66fa
JY
3956#endif
3957
81d882d5
DS
3958 /* our wait-for-i/o objects, different for posix vs. win32 */
3959 if (c->mode == CM_P2P)
3960 {
3961 do_event_set_init(c, SHAPER_DEFINED(&c->options));
3962 }
3963 else if (c->mode == CM_CHILD_TCP)
3964 {
3965 do_event_set_init(c, false);
3966 }
6fbf66fa 3967
81d882d5
DS
3968 /* initialize HTTP or SOCKS proxy object at scope level 2 */
3969 init_proxy(c);
4e9a51d7 3970
81d882d5
DS
3971 /* allocate our socket object */
3972 if (c->mode == CM_P2P || c->mode == CM_TOP || c->mode == CM_CHILD_TCP)
3973 {
3974 do_link_socket_new(c);
3975 }
6fbf66fa
JY
3976
3977#ifdef ENABLE_FRAGMENT
81d882d5
DS
3978 /* initialize internal fragmentation object */
3979 if (options->ce.fragment && (c->mode == CM_P2P || child))
3980 {
3981 c->c2.fragment = fragment_init(&c->c2.frame);
3982 }
6fbf66fa
JY
3983#endif
3984
81d882d5
DS
3985 /* init crypto layer */
3986 {
3987 unsigned int crypto_flags = 0;
3988 if (c->mode == CM_TOP)
3989 {
3990 crypto_flags = CF_INIT_TLS_AUTH_STANDALONE;
3991 }
3992 else if (c->mode == CM_P2P)
3993 {
3994 crypto_flags = CF_LOAD_PERSISTED_PACKET_ID | CF_INIT_TLS_MULTI;
3995 }
3996 else if (child)
3997 {
3998 crypto_flags = CF_INIT_TLS_MULTI;
3999 }
4000 do_init_crypto(c, crypto_flags);
4001 if (IS_SIG(c) && !child)
4002 {
4003 goto sig;
4004 }
4005 }
6fbf66fa 4006
38d96bd7 4007#ifdef USE_COMP
81d882d5
DS
4008 /* initialize compression library. */
4009 if (comp_enabled(&options->comp) && (c->mode == CM_P2P || child))
4010 {
4011 c->c2.comp_context = comp_init(&options->comp);
4012 }
6fbf66fa
JY
4013#endif
4014
81d882d5
DS
4015 /* initialize MTU variables */
4016 do_init_frame(c);
6fbf66fa 4017
81d882d5
DS
4018 /* initialize TLS MTU variables */
4019 do_init_frame_tls(c);
6fbf66fa 4020
81d882d5
DS
4021 /* init workspace buffers whose size is derived from frame size */
4022 if (c->mode == CM_P2P || c->mode == CM_CHILD_TCP)
4023 {
4024 do_init_buffers(c);
4025 }
6fbf66fa
JY
4026
4027#ifdef ENABLE_FRAGMENT
81d882d5
DS
4028 /* initialize internal fragmentation capability with known frame size */
4029 if (options->ce.fragment && (c->mode == CM_P2P || child))
4030 {
4031 do_init_fragment(c);
4032 }
6fbf66fa
JY
4033#endif
4034
81d882d5
DS
4035 /* initialize dynamic MTU variable */
4036 frame_init_mssfix(&c->c2.frame, &c->options);
6fbf66fa 4037
81d882d5
DS
4038 /* bind the TCP/UDP socket */
4039 if (c->mode == CM_P2P || c->mode == CM_TOP || c->mode == CM_CHILD_TCP)
4040 {
4041 do_init_socket_1(c, link_socket_mode);
4042 }
6fbf66fa 4043
81d882d5
DS
4044 /* initialize tun/tap device object,
4045 * open tun/tap device, ifconfig, run up script, etc. */
4046 if (!(options->up_delay || PULL_DEFINED(options)) && (c->mode == CM_P2P || c->mode == CM_TOP))
4047 {
4048 c->c2.did_open_tun = do_open_tun(c);
4049 }
6fbf66fa 4050
81d882d5
DS
4051 /* print MTU info */
4052 do_print_data_channel_mtu_parms(c);
6fbf66fa
JY
4053
4054#ifdef ENABLE_OCC
81d882d5
DS
4055 /* get local and remote options compatibility strings */
4056 if (c->mode == CM_P2P || child)
4057 {
4058 do_compute_occ_strings(c);
4059 }
6fbf66fa
JY
4060#endif
4061
81d882d5
DS
4062 /* initialize output speed limiter */
4063 if (c->mode == CM_P2P)
4064 {
4065 do_init_traffic_shaper(c);
4066 }
6fbf66fa 4067
81d882d5
DS
4068 /* do one-time inits, and possibily become a daemon here */
4069 do_init_first_time(c);
6fbf66fa 4070
e1791bb1 4071#ifdef ENABLE_PLUGIN
81d882d5
DS
4072 /* initialize plugins */
4073 if (c->mode == CM_P2P || c->mode == CM_TOP)
4074 {
4075 open_plugins(c, false, OPENVPN_PLUGIN_INIT_POST_DAEMON);
4076 }
e1791bb1
JY
4077#endif
4078
81d882d5
DS
4079 /* initialise connect timeout timer */
4080 do_init_server_poll_timeout(c);
4db06290 4081
81d882d5
DS
4082 /* finalize the TCP/UDP socket */
4083 if (c->mode == CM_P2P || c->mode == CM_TOP || c->mode == CM_CHILD_TCP)
4084 {
4085 do_init_socket_2(c);
4086 }
b3e97582 4087
81d882d5
DS
4088 /*
4089 * Actually do UID/GID downgrade, and chroot, if requested.
4090 * May be delayed by --client, --pull, or --up-delay.
4091 */
4092 do_uid_gid_chroot(c, c->c2.did_open_tun);
6fbf66fa 4093
81d882d5
DS
4094 /* initialize timers */
4095 if (c->mode == CM_P2P || child)
4096 {
4097 do_init_timers(c, false);
4098 }
6fbf66fa 4099
e1791bb1 4100#ifdef ENABLE_PLUGIN
81d882d5
DS
4101 /* initialize plugins */
4102 if (c->mode == CM_P2P || c->mode == CM_TOP)
4103 {
4104 open_plugins(c, false, OPENVPN_PLUGIN_INIT_POST_UID_CHANGE);
4105 }
e1791bb1
JY
4106#endif
4107
6add6b2f 4108#if PORT_SHARE
81d882d5
DS
4109 /* share OpenVPN port with foreign (such as HTTPS) server */
4110 if (c->first_time && (c->mode == CM_P2P || c->mode == CM_TOP))
4111 {
4112 init_port_share(c);
4113 }
6add6b2f 4114#endif
81d882d5 4115
47ae8457 4116#ifdef ENABLE_PF
81d882d5
DS
4117 if (child)
4118 {
4119 pf_init_context(c);
4120 }
47ae8457
JY
4121#endif
4122
81d882d5
DS
4123 /* Check for signals */
4124 if (IS_SIG(c))
4125 {
4126 goto sig;
4127 }
6fbf66fa 4128
81d882d5 4129 return;
6fbf66fa 4130
81d882d5
DS
4131sig:
4132 if (!c->sig->signal_text)
4133 {
4134 c->sig->signal_text = "init_instance";
4135 }
4136 close_context(c, -1, flags);
4137 return;
6fbf66fa
JY
4138}
4139
4140/*
4141 * Close a tunnel instance.
4142 */
4143void
81d882d5 4144close_instance(struct context *c)
6fbf66fa 4145{
81d882d5
DS
4146 /* close event objects */
4147 do_close_event_set(c);
6fbf66fa
JY
4148
4149 if (c->mode == CM_P2P
81d882d5
DS
4150 || c->mode == CM_CHILD_TCP
4151 || c->mode == CM_CHILD_UDP
4152 || c->mode == CM_TOP)
4153 {
4154 /* if xinetd/inetd mode, don't allow restart */
4155 do_close_check_if_restart_permitted(c);
6fbf66fa 4156
38d96bd7 4157#ifdef USE_COMP
81d882d5
DS
4158 if (c->c2.comp_context)
4159 {
4160 comp_uninit(c->c2.comp_context);
4161 c->c2.comp_context = NULL;
4162 }
6fbf66fa
JY
4163#endif
4164
81d882d5
DS
4165 /* free buffers */
4166 do_close_free_buf(c);
6fbf66fa 4167
81d882d5
DS
4168 /* close TLS */
4169 do_close_tls(c);
6fbf66fa 4170
81d882d5
DS
4171 /* free key schedules */
4172 do_close_free_key_schedule(c, (c->mode == CM_P2P || c->mode == CM_TOP));
6fbf66fa 4173
81d882d5
DS
4174 /* close TCP/UDP connection */
4175 do_close_link_socket(c);
6fbf66fa 4176
81d882d5
DS
4177 /* close TUN/TAP device */
4178 do_close_tun(c, false);
6fbf66fa 4179
90efcacb 4180#ifdef MANAGEMENT_DEF_AUTH
81d882d5
DS
4181 if (management)
4182 {
4183 management_notify_client_close(management, &c->c2.mda_context, NULL);
4184 }
90efcacb
JY
4185#endif
4186
47ae8457 4187#ifdef ENABLE_PF
81d882d5 4188 pf_destroy_context(&c->c2.pf);
47ae8457
JY
4189#endif
4190
3c7f2f55 4191#ifdef ENABLE_PLUGIN
81d882d5
DS
4192 /* call plugin close functions and unload */
4193 do_close_plugins(c);
3c7f2f55 4194#endif
6fbf66fa 4195
81d882d5
DS
4196 /* close packet-id persistance file */
4197 do_close_packet_id(c);
6fbf66fa 4198
81d882d5
DS
4199 /* close --status file */
4200 do_close_status_output(c);
6fbf66fa
JY
4201
4202#ifdef ENABLE_FRAGMENT
81d882d5
DS
4203 /* close fragmentation handler */
4204 do_close_fragment(c);
6fbf66fa
JY
4205#endif
4206
81d882d5
DS
4207 /* close --ifconfig-pool-persist obj */
4208 do_close_ifconfig_pool_persist(c);
6fbf66fa 4209
81d882d5
DS
4210 /* free up environmental variable store */
4211 do_env_set_destroy(c);
2a64816b 4212
81d882d5
DS
4213 /* close HTTP or SOCKS proxy */
4214 uninit_proxy(c);
4e9a51d7 4215
81d882d5
DS
4216 /* garbage collect */
4217 gc_free(&c->c2.gc);
4218 }
6fbf66fa
JY
4219}
4220
4221void
81d882d5
DS
4222inherit_context_child(struct context *dest,
4223 const struct context *src)
6fbf66fa 4224{
81d882d5 4225 CLEAR(*dest);
6fbf66fa 4226
81d882d5
DS
4227 /* proto_is_dgram will ASSERT(0) if proto is invalid */
4228 dest->mode = proto_is_dgram(src->options.ce.proto) ? CM_CHILD_UDP : CM_CHILD_TCP;
6fbf66fa 4229
81d882d5 4230 dest->gc = gc_new();
6fbf66fa 4231
81d882d5 4232 ALLOC_OBJ_CLEAR_GC(dest->sig, struct signal_info, &dest->gc);
6fbf66fa 4233
81d882d5
DS
4234 /* c1 init */
4235 packet_id_persist_init(&dest->c1.pid_persist);
6fbf66fa 4236
9b33b5a4 4237#ifdef ENABLE_CRYPTO
81d882d5
DS
4238 dest->c1.ks.key_type = src->c1.ks.key_type;
4239 /* inherit SSL context */
4240 dest->c1.ks.ssl_ctx = src->c1.ks.ssl_ctx;
4241 dest->c1.ks.tls_wrap_key = src->c1.ks.tls_wrap_key;
4242 dest->c1.ks.tls_auth_key_type = src->c1.ks.tls_auth_key_type;
4243 /* inherit pre-NCP ciphers */
4244 dest->c1.ciphername = src->c1.ciphername;
4245 dest->c1.authname = src->c1.authname;
4246 dest->c1.keysize = src->c1.keysize;
4247#endif
4248
4249 /* options */
4250 dest->options = src->options;
4251 options_detach(&dest->options);
4252
4253 if (dest->mode == CM_CHILD_TCP)
6fbf66fa 4254 {
81d882d5
DS
4255 /*
4256 * The CM_TOP context does the socket listen(),
4257 * and the CM_CHILD_TCP context does the accept().
4258 */
4259 dest->c2.accept_from = src->c2.link_socket;
6fbf66fa
JY
4260 }
4261
3c7f2f55 4262#ifdef ENABLE_PLUGIN
81d882d5
DS
4263 /* inherit plugins */
4264 do_inherit_plugins(dest, src);
3c7f2f55 4265#endif
6fbf66fa 4266
81d882d5
DS
4267 /* context init */
4268 init_instance(dest, src->c2.es, CC_NO_CLOSE | CC_USR1_TO_HUP);
4269 if (IS_SIG(dest))
4270 {
4271 return;
4272 }
6fbf66fa 4273
81d882d5
DS
4274 /* inherit tun/tap interface object */
4275 dest->c1.tuntap = src->c1.tuntap;
6fbf66fa 4276
81d882d5
DS
4277 /* UDP inherits some extra things which TCP does not */
4278 if (dest->mode == CM_CHILD_UDP)
6fbf66fa 4279 {
81d882d5
DS
4280 /* inherit buffers */
4281 dest->c2.buffers = src->c2.buffers;
6fbf66fa 4282
81d882d5
DS
4283 /* inherit parent link_socket and tuntap */
4284 dest->c2.link_socket = src->c2.link_socket;
6fbf66fa 4285
81d882d5
DS
4286 ALLOC_OBJ_GC(dest->c2.link_socket_info, struct link_socket_info, &dest->gc);
4287 *dest->c2.link_socket_info = src->c2.link_socket->info;
6fbf66fa 4288
81d882d5
DS
4289 /* locally override some link_socket_info fields */
4290 dest->c2.link_socket_info->lsa = &dest->c1.link_socket_addr;
4291 dest->c2.link_socket_info->connection_established = false;
6fbf66fa
JY
4292 }
4293}
4294
4295void
81d882d5
DS
4296inherit_context_top(struct context *dest,
4297 const struct context *src)
6fbf66fa 4298{
81d882d5
DS
4299 /* copy parent */
4300 *dest = *src;
6fbf66fa 4301
81d882d5
DS
4302 /*
4303 * CM_TOP_CLONE will prevent close_instance from freeing or closing
4304 * resources owned by the parent.
4305 *
4306 * Also note that CM_TOP_CLONE context objects are
4307 * closed by multi_top_free in multi.c.
4308 */
4309 dest->mode = CM_TOP_CLONE;
6fbf66fa 4310
81d882d5
DS
4311 dest->first_time = false;
4312 dest->c0 = NULL;
6fbf66fa 4313
81d882d5
DS
4314 options_detach(&dest->options);
4315 gc_detach(&dest->gc);
4316 gc_detach(&dest->c2.gc);
6fbf66fa 4317
81d882d5
DS
4318 /* detach plugins */
4319 dest->plugins_owned = false;
3c7f2f55 4320
ec828db6 4321#ifdef ENABLE_CRYPTO
81d882d5 4322 dest->c2.tls_multi = NULL;
6fbf66fa
JY
4323#endif
4324
81d882d5
DS
4325 /* detach c1 ownership */
4326 dest->c1.tuntap_owned = false;
4327 dest->c1.status_output_owned = false;
6fbf66fa 4328#if P2MP_SERVER
81d882d5 4329 dest->c1.ifconfig_pool_persist_owned = false;
6fbf66fa 4330#endif
3c7f2f55 4331
81d882d5
DS
4332 /* detach c2 ownership */
4333 dest->c2.event_set_owned = false;
4334 dest->c2.link_socket_owned = false;
4335 dest->c2.buffers_owned = false;
4336 dest->c2.es_owned = false;
6fbf66fa 4337
81d882d5
DS
4338 dest->c2.event_set = NULL;
4339 if (proto_is_dgram(src->options.ce.proto))
4340 {
4341 do_event_set_init(dest, false);
4342 }
38d96bd7
JY
4343
4344#ifdef USE_COMP
81d882d5 4345 dest->c2.comp_context = NULL;
38d96bd7 4346#endif
6fbf66fa
JY
4347}
4348
4349void
81d882d5 4350close_context(struct context *c, int sig, unsigned int flags)
6fbf66fa 4351{
81d882d5
DS
4352 ASSERT(c);
4353 ASSERT(c->sig);
79df31c8 4354
81d882d5
DS
4355 if (sig >= 0)
4356 {
4357 c->sig->signal_received = sig;
4358 }
6fbf66fa 4359
81d882d5 4360 if (c->sig->signal_received == SIGUSR1)
6fbf66fa 4361 {
81d882d5
DS
4362 if ((flags & CC_USR1_TO_HUP)
4363 || (c->sig->source == SIG_SOURCE_HARD && (flags & CC_HARD_USR1_TO_HUP)))
c058cbff 4364 {
81d882d5
DS
4365 c->sig->signal_received = SIGHUP;
4366 c->sig->signal_text = "close_context usr1 to hup";
c058cbff 4367 }
6fbf66fa
JY
4368 }
4369
81d882d5
DS
4370 if (!(flags & CC_NO_CLOSE))
4371 {
4372 close_instance(c);
4373 }
6fbf66fa 4374
81d882d5
DS
4375 if (flags & CC_GC_FREE)
4376 {
4377 context_gc_free(c);
4378 }
6fbf66fa
JY
4379}
4380
9b33b5a4 4381#ifdef ENABLE_CRYPTO
6fbf66fa 4382
6fbf66fa
JY
4383/*
4384 * Do a loopback test
4385 * on the crypto subsystem.
4386 */
4387static void *
81d882d5 4388test_crypto_thread(void *arg)
6fbf66fa 4389{
81d882d5
DS
4390 struct context *c = (struct context *) arg;
4391 const struct options *options = &c->options;
6fbf66fa 4392
81d882d5
DS
4393 ASSERT(options->test_crypto);
4394 init_verb_mute(c, IVM_LEVEL_1);
4395 context_init_1(c);
4396 next_connection_entry(c);
4397 do_init_crypto_static(c, 0);
6fbf66fa 4398
81d882d5 4399 frame_finalize_options(c, options);
6fbf66fa 4400
81d882d5 4401 test_crypto(&c->c2.crypto_options, &c->c2.frame);
6fbf66fa 4402
81d882d5
DS
4403 key_schedule_free(&c->c1.ks, true);
4404 packet_id_free(&c->c2.crypto_options.packet_id);
6fbf66fa 4405
81d882d5
DS
4406 context_gc_free(c);
4407 return NULL;
6fbf66fa
JY
4408}
4409
3ebc31f9 4410#endif /* ENABLE_CRYPTO */
6fbf66fa
JY
4411
4412bool
81d882d5 4413do_test_crypto(const struct options *o)
6fbf66fa 4414{
9b33b5a4 4415#ifdef ENABLE_CRYPTO
81d882d5 4416 if (o->test_crypto)
6fbf66fa 4417 {
81d882d5 4418 struct context c;
6fbf66fa 4419
81d882d5
DS
4420 /* print version number */
4421 msg(M_INFO, "%s", title_string);
6fbf66fa 4422
81d882d5
DS
4423 context_clear(&c);
4424 c.options = *o;
4425 options_detach(&c.options);
4426 c.first_time = true;
4427 test_crypto_thread((void *) &c);
4428 return true;
6fbf66fa
JY
4429 }
4430#endif
81d882d5 4431 return false;
6fbf66fa 4432}