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