]> git.ipfire.org Git - thirdparty/openvpn.git/blame - init.c
Fixed minor issue with --redirect-gateway bypass-dhcp or bypass-dns
[thirdparty/openvpn.git] / 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 *
1c0cc4ad 8 * Copyright (C) 2002-2008 Telethra, 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
6fbf66fa
JY
25#include "syshead.h"
26
27#include "win32.h"
28#include "init.h"
29#include "sig.h"
30#include "occ.h"
31#include "list.h"
32#include "otime.h"
33#include "pool.h"
34#include "gremlin.h"
ce98fd24 35#include "pkcs11.h"
6add6b2f 36#include "ps.h"
e12fe286 37#include "lladdr.h"
6fbf66fa
JY
38
39#include "memdbg.h"
40
41#include "occ-inline.h"
42
43/*
44 * Crypto initialization flags
45 */
46#define CF_LOAD_PERSISTED_PACKET_ID (1<<0)
47#define CF_INIT_TLS_MULTI (1<<1)
48#define CF_INIT_TLS_AUTH_STANDALONE (1<<2)
49
50static void do_init_first_time (struct context *c);
51
52void
53context_clear (struct context *c)
54{
55 CLEAR (*c);
56}
57
58void
59context_clear_1 (struct context *c)
60{
61 CLEAR (c->c1);
62}
63
64void
65context_clear_2 (struct context *c)
66{
67 CLEAR (c->c2);
68}
69
70void
71context_clear_all_except_first_time (struct context *c)
72{
73 const bool first_time_save = c->first_time;
a9c802b2 74 const struct context_persist cpsave = c->persist;
6fbf66fa
JY
75 context_clear (c);
76 c->first_time = first_time_save;
a9c802b2 77 c->persist = cpsave;
6fbf66fa
JY
78}
79
80/*
4e9a51d7
JY
81 * Should be called after options->ce is modified at the top
82 * of a SIGUSR1 restart.
6fbf66fa
JY
83 */
84static void
4e9a51d7 85update_options_ce_post (struct options *options)
6fbf66fa 86{
4e9a51d7
JY
87#if P2MP
88 /*
89 * In pull mode, we usually import --ping/--ping-restart parameters from
90 * the server. However we should also set an initial default --ping-restart
91 * for the period of time before we pull the --ping-restart parameter
92 * from the server.
93 */
94 if (options->pull
95 && options->ping_rec_timeout_action == PING_UNDEF
96 && options->ce.proto == PROTO_UDPv4)
97 {
98 options->ping_rec_timeout = PRE_PULL_INITIAL_PING_RESTART;
99 options->ping_rec_timeout_action = PING_RESTART;
100 }
101#endif
102#ifdef USE_CRYPTO
103 /*
104 * Don't use replay window for TCP mode (i.e. require that packets be strictly in sequence).
105 */
106 if (link_socket_proto_connection_oriented (options->ce.proto))
107 options->replay_window = options->replay_time = 0;
108#endif
109}
6fbf66fa 110
4e9a51d7
JY
111/*
112 * Initialize and possibly randomize connection list.
113 */
114static void
115init_connection_list (struct context *c)
116{
117#ifdef ENABLE_CONNECTION
118 struct connection_list *l = c->options.connection_list;
119 if (l)
6fbf66fa 120 {
6fbf66fa
JY
121 l->current = -1;
122 if (c->options.remote_random)
4e9a51d7
JY
123 {
124 int i;
125 for (i = 0; i < l->len; ++i)
126 {
127 const int j = get_random () % l->len;
128 if (i != j)
129 {
130 struct connection_entry *tmp;
131 tmp = l->array[i];
132 l->array[i] = l->array[j];
133 l->array[j] = tmp;
134 }
135 }
136 }
6fbf66fa 137 }
4e9a51d7
JY
138#endif
139}
140
141/*
142 * Increment to next connection entry
143 */
144static void
145next_connection_entry (struct context *c)
146{
147#ifdef ENABLE_CONNECTION
148 struct connection_list *l = c->options.connection_list;
149 if (l)
150 {
151 if (l->no_advance && l->current >= 0)
152 {
153 l->no_advance = false;
154 }
155 else
156 {
157 int i;
158 if (++l->current >= l->len)
159 l->current = 0;
160
161 dmsg (D_CONNECTION_LIST, "CONNECTION_LIST len=%d current=%d",
162 l->len, l->current);
163 for (i = 0; i < l->len; ++i)
164 {
165 dmsg (D_CONNECTION_LIST, "[%d] %s:%d",
166 i,
167 l->array[i]->remote,
168 l->array[i]->remote_port);
169 }
170 }
171 c->options.ce = *l->array[l->current];
172 }
173#endif
174 update_options_ce_post (&c->options);
6fbf66fa
JY
175}
176
92bbb061
JY
177/*
178 * Query for private key and auth-user-pass username/passwords
179 */
180static void
181init_query_passwords (struct context *c)
182{
183#if defined(USE_CRYPTO) && defined(USE_SSL)
184 /* Certificate password input */
185 if (c->options.key_pass_file)
186 pem_password_setup (c->options.key_pass_file);
187#endif
188
189#if P2MP
190 /* Auth user/pass input */
191 if (c->options.auth_user_pass_file)
192 auth_user_pass_setup (c->options.auth_user_pass_file);
193#endif
194}
195
4e9a51d7
JY
196/*
197 * Initialize/Uninitialize HTTP or SOCKS proxy
198 */
199
200#ifdef GENERAL_PROXY_SUPPORT
201
202static int
203proxy_scope (struct context *c)
204{
205 return connection_list_defined (&c->options) ? 2 : 1;
206}
207
208static void
209uninit_proxy_dowork (struct context *c)
210{
211#ifdef ENABLE_HTTP_PROXY
212 if (c->c1.http_proxy_owned && c->c1.http_proxy)
213 {
214 http_proxy_close (c->c1.http_proxy);
215 c->c1.http_proxy = NULL;
216 c->c1.http_proxy_owned = false;
217 }
218#endif
219#ifdef ENABLE_SOCKS
220 if (c->c1.socks_proxy_owned && c->c1.socks_proxy)
221 {
222 socks_proxy_close (c->c1.socks_proxy);
223 c->c1.socks_proxy = NULL;
224 c->c1.socks_proxy_owned = false;
225 }
226#endif
227}
228
229static void
230init_proxy_dowork (struct context *c)
6fbf66fa 231{
f214bb21
JY
232#ifdef ENABLE_HTTP_PROXY
233 bool did_http = false;
234#else
235 const bool did_http = false;
236#endif
237
4e9a51d7
JY
238 uninit_proxy_dowork (c);
239
240#ifdef ENABLE_HTTP_PROXY
241 if (c->options.ce.http_proxy_options || c->options.auto_proxy_info)
242 {
243 /* Possible HTTP proxy user/pass input */
244 c->c1.http_proxy = http_proxy_new (c->options.ce.http_proxy_options,
245 c->options.auto_proxy_info);
246 if (c->c1.http_proxy)
247 {
248 did_http = true;
249 c->c1.http_proxy_owned = true;
250 }
251 }
252#endif
253
254#ifdef ENABLE_SOCKS
255 if (!did_http && (c->options.ce.socks_proxy_server || c->options.auto_proxy_info))
256 {
257 c->c1.socks_proxy = socks_proxy_new (c->options.ce.socks_proxy_server,
258 c->options.ce.socks_proxy_port,
259 c->options.ce.socks_proxy_retry,
260 c->options.auto_proxy_info);
261 if (c->c1.socks_proxy)
262 {
263 c->c1.socks_proxy_owned = true;
264 }
265 }
266#endif
267}
268
269static void
270init_proxy (struct context *c, const int scope)
271{
272 if (scope == proxy_scope (c))
273 init_proxy_dowork (c);
274}
275
276static void
277uninit_proxy (struct context *c)
278{
279 if (c->sig->signal_received != SIGUSR1 || proxy_scope (c) == 2)
280 uninit_proxy_dowork (c);
281}
282
283#else
284
285static inline void
286init_proxy (struct context *c, const int scope)
287{
288}
289
290static inline void
291uninit_proxy (struct context *c, const int scope)
292{
293}
294
295#endif
296
297void
298context_init_1 (struct context *c)
299{
6fbf66fa
JY
300 context_clear_1 (c);
301
302 packet_id_persist_init (&c->c1.pid_persist);
4e9a51d7
JY
303
304 init_connection_list (c);
6fbf66fa 305
92bbb061 306 init_query_passwords (c);
ce98fd24
JY
307
308#if defined(ENABLE_PKCS11)
06d92b29 309 if (c->first_time) {
ce98fd24 310 int i;
18597b93 311 pkcs11_initialize (true, c->options.pkcs11_pin_cache_period);
ce98fd24 312 for (i=0;i<MAX_PARMS && c->options.pkcs11_providers[i] != NULL;i++)
18597b93 313 pkcs11_addProvider (c->options.pkcs11_providers[i], c->options.pkcs11_protected_authentication[i],
718526e0 314 c->options.pkcs11_private_mode[i], c->options.pkcs11_cert_private[i]);
ce98fd24
JY
315 }
316#endif
984cf003 317
c67d59cd 318#if 0 /* test get_user_pass with GET_USER_PASS_NEED_OK flag */
dd1047f5
JY
319 {
320 /*
321 * In the management interface, you can okay the request by entering "needok token-insertion-request ok"
322 */
323 struct user_pass up;
324 CLEAR (up);
325 strcpy (up.username, "Please insert your cryptographic token"); /* put the high-level message in up.username */
326 get_user_pass (&up, NULL, "token-insertion-request", GET_USER_PASS_MANAGEMENT|GET_USER_PASS_NEED_OK);
327 msg (M_INFO, "RET:%s", up.password); /* will return the third argument to management interface
328 'needok' command, usually 'ok' or 'cancel'. */
329 }
330#endif
331
4e9a51d7
JY
332 /* initialize HTTP or SOCKS proxy object at scope level 1 */
333 init_proxy (c, 1);
6fbf66fa
JY
334}
335
336void
337context_gc_free (struct context *c)
338{
339 gc_free (&c->c2.gc);
340 gc_free (&c->options.gc);
341 gc_free (&c->gc);
342}
343
6add6b2f
JY
344#if PORT_SHARE
345
346static void
347close_port_share (void)
348{
349 if (port_share)
350 {
351 port_share_close (port_share);
352 port_share = NULL;
353 }
354}
355
356static void
357init_port_share (struct context *c)
358{
359 if (!port_share && (c->options.port_share_host && c->options.port_share_port))
360 {
361 port_share = port_share_open (c->options.port_share_host,
362 c->options.port_share_port);
363 if (port_share == NULL)
364 msg (M_FATAL, "Fatal error: Port sharing failed");
365 }
366}
367
368#endif
369
6fbf66fa
JY
370bool
371init_static (void)
372{
5a2e9a25 373 /* configure_path (); */
c67d59cd 374
6fbf66fa
JY
375#if defined(USE_CRYPTO) && defined(DMALLOC)
376 openssl_dmalloc_init ();
377#endif
378
379 init_random_seed (); /* init random() function, only used as
380 source for weak random numbers */
381 error_reset (); /* initialize error.c */
382 reset_check_status (); /* initialize status check code in socket.c */
383
384#ifdef WIN32
385 init_win32 ();
386#endif
387
388#ifdef OPENVPN_DEBUG_COMMAND_LINE
389 {
390 int i;
391 for (i = 0; i < argc; ++i)
392 msg (M_INFO, "argv[%d] = '%s'", i, argv[i]);
393 }
394#endif
395
396 update_time ();
397
398#ifdef USE_CRYPTO
399 init_ssl_lib ();
400
401 /* init PRNG used for IV generation */
402 /* When forking, copy this to more places in the code to avoid fork
403 random-state predictability */
404 prng_init ();
405#endif
406
407#ifdef PID_TEST
408 packet_id_interactive_test (); /* test the sequence number code */
409 return false;
410#endif
411
412#ifdef SCHEDULE_TEST
413 schedule_test ();
414 return false;
415#endif
416
417#ifdef LIST_TEST
418 list_test ();
419 return false;
420#endif
421
422#ifdef IFCONFIG_POOL_TEST
423 ifconfig_pool_test (0x0A010004, 0x0A0100FF);
424 return false;
425#endif
426
427#ifdef CHARACTER_CLASS_DEBUG
428 character_class_debug ();
429 return false;
430#endif
431
432#ifdef EXTRACT_X509_FIELD_TEST
433 extract_x509_field_test ();
434 return false;
435#endif
436
428b8279
JY
437#ifdef TIME_TEST
438 time_test ();
439 return false;
440#endif
441
6cd276ba 442#ifdef GEN_PATH_TEST
ddad0a8c
JY
443 {
444 struct gc_arena gc = gc_new ();
445 const char *fn = gen_path ("foo",
446 "bar",
447 &gc);
448 printf ("%s\n", fn);
449 gc_free (&gc);
450 }
6cd276ba
JY
451 return false;
452#endif
ddad0a8c 453
6cd276ba
JY
454#ifdef STATUS_PRINTF_TEST
455 {
456 struct gc_arena gc = gc_new ();
457 const char *tmp_file = create_temp_filename ("/tmp", "foo", &gc);
458 struct status_output *so = status_open (tmp_file, 0, -1, NULL, STATUS_OUTPUT_WRITE);
459 status_printf (so, "%s", "foo");
460 status_printf (so, "%s", "bar");
461 if (!status_close (so))
462 msg (M_WARN, "STATUS_PRINTF_TEST: %s: write error", tmp_file);
463 gc_free (&gc);
464 }
ddad0a8c
JY
465 return false;
466#endif
467
26bb4c74
JY
468#ifdef ARGV_TEST
469 {
470 void argv_test (void);
471 argv_test ();
472 return false;
473 }
474#endif
475
6fbf66fa
JY
476 return true;
477}
478
479void
480uninit_static (void)
481{
482 openvpn_thread_cleanup ();
483
484#ifdef USE_CRYPTO
485 free_ssl_lib ();
6835555e 486#endif
ce98fd24 487
ce98fd24 488#ifdef ENABLE_PKCS11
984cf003 489 pkcs11_terminate ();
ce98fd24 490#endif
6fbf66fa 491
6add6b2f
JY
492#if PORT_SHARE
493 close_port_share ();
494#endif
495
6fbf66fa
JY
496#if defined(MEASURE_TLS_HANDSHAKE_STATS) && defined(USE_CRYPTO) && defined(USE_SSL)
497 show_tls_performance_stats ();
498#endif
499}
500
501void
502init_verb_mute (struct context *c, unsigned int flags)
503{
504 if (flags & IVM_LEVEL_1)
505 {
506 /* set verbosity and mute levels */
507 set_check_status (D_LINK_ERRORS, D_READ_WRITE);
508 set_debug_level (c->options.verbosity, SDL_CONSTRAIN);
509 set_mute_cutoff (c->options.mute);
510 }
511
512 /* special D_LOG_RW mode */
513 if (flags & IVM_LEVEL_2)
514 c->c2.log_rw = (check_debug_level (D_LOG_RW) && !check_debug_level (D_LOG_RW + 1));
515}
516
517/*
518 * Possibly set --dev based on --dev-node.
519 * For example, if --dev-node /tmp/foo/tun, and --dev undefined,
520 * set --dev to tun.
521 */
522void
523init_options_dev (struct options *options)
524{
525 if (!options->dev)
526 options->dev = dev_component_in_dev_node (options->dev_node);
527}
528
529bool
530print_openssl_info (const struct options *options)
531{
532 /*
533 * OpenSSL info print mode?
534 */
535#ifdef USE_CRYPTO
536 if (options->show_ciphers || options->show_digests || options->show_engines
537#ifdef USE_SSL
538 || options->show_tls_ciphers
539#endif
540 )
541 {
542 if (options->show_ciphers)
543 show_available_ciphers ();
544 if (options->show_digests)
545 show_available_digests ();
546 if (options->show_engines)
547 show_available_engines ();
548#ifdef USE_SSL
549 if (options->show_tls_ciphers)
550 show_available_tls_ciphers ();
551#endif
552 return true;
553 }
554#endif
555 return false;
556}
557
558/*
559 * Static pre-shared key generation mode?
560 */
561bool
562do_genkey (const struct options * options)
563{
564#ifdef USE_CRYPTO
565 if (options->genkey)
566 {
567 int nbits_written;
568
569 notnull (options->shared_secret_file,
570 "shared secret output file (--secret)");
571
572 if (options->mlock) /* should we disable paging? */
573 do_mlockall (true);
574
575 nbits_written = write_key_file (2, options->shared_secret_file);
576
577 msg (D_GENKEY | M_NOPREFIX,
578 "Randomly generated %d bit key written to %s", nbits_written,
579 options->shared_secret_file);
580 return true;
581 }
582#endif
583 return false;
584}
585
586/*
587 * Persistent TUN/TAP device management mode?
588 */
589bool
590do_persist_tuntap (const struct options *options)
591{
592#ifdef TUNSETPERSIST
593 if (options->persist_config)
594 {
595 /* sanity check on options for --mktun or --rmtun */
596 notnull (options->dev, "TUN/TAP device (--dev)");
4e9a51d7 597 if (options->ce.remote || options->ifconfig_local
6fbf66fa
JY
598 || options->ifconfig_remote_netmask
599#ifdef USE_CRYPTO
600 || options->shared_secret_file
601#ifdef USE_SSL
602 || options->tls_server || options->tls_client
603#endif
604#endif
605 )
606 msg (M_FATAL|M_OPTERR,
607 "options --mktun or --rmtun should only be used together with --dev");
608 tuncfg (options->dev, options->dev_type, options->dev_node,
004d8b48 609 options->tun_ipv6, options->persist_mode,
0aee9ca7 610 options->username, options->groupname, &options->tuntap_options);
e12fe286
JY
611 if (options->persist_mode && options->lladdr)
612 set_lladdr(options->dev, options->lladdr, NULL);
6fbf66fa
JY
613 return true;
614 }
615#endif
616 return false;
617}
618
619/*
620 * Should we become a daemon?
621 * Return true if we did it.
622 */
623static bool
624possibly_become_daemon (const struct options *options, const bool first_time)
625{
626 bool ret = false;
627 if (first_time && options->daemon)
628 {
629 ASSERT (!options->inetd);
630 if (daemon (options->cd_dir != NULL, options->log) < 0)
631 msg (M_ERR, "daemon() failed");
225d5fe9 632 restore_signal_state ();
6fbf66fa
JY
633 if (options->log)
634 set_std_files_to_null (true);
6835555e
JY
635
636#if defined(ENABLE_PKCS11)
984cf003 637 pkcs11_forkFixup ();
6835555e
JY
638#endif
639
6fbf66fa
JY
640 ret = true;
641 }
642 return ret;
643}
644
645/*
646 * Actually do UID/GID downgrade, and chroot, if requested.
647 */
648static void
649do_uid_gid_chroot (struct context *c, bool no_delay)
650{
651 static const char why_not[] = "will be delayed because of --client, --pull, or --up-delay";
92bbb061 652 struct context_0 *c0 = c->c0;
6fbf66fa 653
92bbb061 654 if (c->first_time && c0 && !c0->uid_gid_set)
6fbf66fa
JY
655 {
656 /* chroot if requested */
657 if (c->options.chroot_dir)
658 {
659 if (no_delay)
660 do_chroot (c->options.chroot_dir);
661 else
662 msg (M_INFO, "NOTE: chroot %s", why_not);
663 }
664
665 /* set user and/or group that we want to setuid/setgid to */
666 if (no_delay)
667 {
92bbb061
JY
668 set_group (&c0->group_state);
669 set_user (&c0->user_state);
670 c0->uid_gid_set = true;
6fbf66fa 671 }
92bbb061 672 else if (c0->uid_gid_specified)
6fbf66fa
JY
673 {
674 msg (M_INFO, "NOTE: UID/GID downgrade %s", why_not);
675 }
676 }
677}
678
679/*
680 * Return common name in a way that is formatted for
681 * prepending to msg() output.
682 */
683const char *
684format_common_name (struct context *c, struct gc_arena *gc)
685{
686 struct buffer out = alloc_buf_gc (256, gc);
687#if defined(USE_CRYPTO) && defined(USE_SSL)
688 if (c->c2.tls_multi)
689 {
690 buf_printf (&out, "[%s] ", tls_common_name (c->c2.tls_multi, false));
691 }
692#endif
693 return BSTR (&out);
694}
695
696void
697pre_setup (const struct options *options)
698{
699#ifdef WIN32
700 if (options->exit_event_name)
701 {
702 win32_signal_open (&win32_signal,
703 WSO_FORCE_SERVICE,
704 options->exit_event_name,
705 options->exit_event_initial_state);
706 }
707 else
708 {
709 win32_signal_open (&win32_signal,
710 WSO_FORCE_CONSOLE,
711 NULL,
712 false);
713
714 /* put a title on the top window bar */
715 if (win32_signal.mode == WSO_MODE_CONSOLE)
716 {
717 window_title_save (&window_title);
718 window_title_generate (options->config);
719 }
720 }
721#endif
722}
723
724void
725reset_coarse_timers (struct context *c)
726{
727 c->c2.coarse_timer_wakeup = 0;
728}
729
730/*
731 * Initialize timers
732 */
733static void
734do_init_timers (struct context *c, bool deferred)
735{
736 update_time ();
737 reset_coarse_timers (c);
738
739 /* initialize inactivity timeout */
740 if (c->options.inactivity_timeout)
741 event_timeout_init (&c->c2.inactivity_interval, c->options.inactivity_timeout, now);
742
743 /* initialize pings */
744
745 if (c->options.ping_send_timeout)
746 event_timeout_init (&c->c2.ping_send_interval, c->options.ping_send_timeout, 0);
747
748 if (c->options.ping_rec_timeout)
749 event_timeout_init (&c->c2.ping_rec_interval, c->options.ping_rec_timeout, now);
750
751 if (!deferred)
752 {
753 /* initialize connection establishment timer */
754 event_timeout_init (&c->c2.wait_for_connect, 1, now);
755
756#ifdef ENABLE_OCC
757 /* initialize occ timers */
758
759 if (c->options.occ
760 && !TLS_MODE (c)
761 && c->c2.options_string_local && c->c2.options_string_remote)
762 event_timeout_init (&c->c2.occ_interval, OCC_INTERVAL_SECONDS, now);
763
764 if (c->options.mtu_test)
765 event_timeout_init (&c->c2.occ_mtu_load_test_interval, OCC_MTU_LOAD_INTERVAL_SECONDS, now);
766#endif
767
768 /* initialize packet_id persistence timer */
769#ifdef USE_CRYPTO
770 if (c->options.packet_id_file)
771 event_timeout_init (&c->c2.packet_id_persist_interval, 60, now);
772#endif
773
774#if defined(USE_CRYPTO) && defined(USE_SSL)
775 /* initialize tmp_int optimization that limits the number of times we call
776 tls_multi_process in the main event loop */
777 interval_init (&c->c2.tmp_int, TLS_MULTI_HORIZON, TLS_MULTI_REFRESH);
778#endif
779 }
780}
781
782/*
783 * Initialize traffic shaper.
784 */
785static void
786do_init_traffic_shaper (struct context *c)
787{
788#ifdef HAVE_GETTIMEOFDAY
789 /* initialize traffic shaper (i.e. transmit bandwidth limiter) */
790 if (c->options.shaper)
791 {
792 shaper_init (&c->c2.shaper, c->options.shaper);
793 shaper_msg (&c->c2.shaper);
794 }
795#endif
796}
797
798/*
799 * Allocate a route list structure if at least one
800 * --route option was specified.
801 */
802static void
803do_alloc_route_list (struct context *c)
804{
805 if (c->options.routes && !c->c1.route_list)
806 c->c1.route_list = new_route_list (&c->gc);
807}
808
809
810/*
811 * Initialize the route list, resolving any DNS names in route
812 * options and saving routes in the environment.
813 */
814static void
815do_init_route_list (const struct options *options,
816 struct route_list *route_list,
817 const struct link_socket_info *link_socket_info,
818 bool fatal,
819 struct env_set *es)
820{
821 const char *gw = NULL;
822 int dev = dev_type_enum (options->dev, options->dev_type);
40ac3d7a 823 int metric = 0;
6fbf66fa 824
3c7f2f55 825 if (dev == DEV_TYPE_TUN && (options->topology == TOP_NET30 || options->topology == TOP_P2P))
6fbf66fa
JY
826 gw = options->ifconfig_remote_netmask;
827 if (options->route_default_gateway)
828 gw = options->route_default_gateway;
40ac3d7a
JY
829 if (options->route_default_metric)
830 metric = options->route_default_metric;
6fbf66fa
JY
831
832 if (!init_route_list (route_list,
833 options->routes,
834 gw,
40ac3d7a 835 metric,
6fbf66fa
JY
836 link_socket_current_remote (link_socket_info),
837 es))
838 {
839 if (fatal)
840 openvpn_exit (OPENVPN_EXIT_STATUS_ERROR); /* exit point */
841 }
842 else
843 {
844 /* copy routes to environment */
845 setenv_routes (es, route_list);
846 }
847}
848
849/*
850 * Called after all initialization has been completed.
851 */
852void
853initialization_sequence_completed (struct context *c, const unsigned int flags)
854{
855 static const char message[] = "Initialization Sequence Completed";
856
857 /* If we delayed UID/GID downgrade or chroot, do it now */
858 do_uid_gid_chroot (c, true);
859
860 /* Test if errors */
861 if (flags & ISC_ERRORS)
a9c802b2 862 {
6fbf66fa 863#ifdef WIN32
a9c802b2
JY
864 show_routes (M_INFO|M_NOPREFIX);
865 show_adapters (M_INFO|M_NOPREFIX);
866 msg (M_INFO, "%s With Errors ( see http://openvpn.net/faq.html#dhcpclientserv )", message);
6fbf66fa 867#else
a9c802b2 868 msg (M_INFO, "%s With Errors", message);
6fbf66fa 869#endif
a9c802b2 870 }
6fbf66fa
JY
871 else
872 msg (M_INFO, "%s", message);
873
4e9a51d7
JY
874 /* Flag connection_list that we initialized */
875 if ((flags & (ISC_ERRORS|ISC_SERVER)) == 0 && connection_list_defined (&c->options))
876 connection_list_set_no_advance (&c->options);
6fbf66fa
JY
877
878#ifdef ENABLE_MANAGEMENT
879 /* Tell management interface that we initialized */
880 if (management)
881 {
882 in_addr_t tun_local = 0;
5ad84585 883 in_addr_t tun_remote = 0; /* FKS */
6fbf66fa
JY
884 const char *detail = "SUCCESS";
885 if (c->c1.tuntap)
886 tun_local = c->c1.tuntap->local;
5ad84585 887 tun_remote = htonl (c->c1.link_socket_addr.actual.dest.sa.sin_addr.s_addr);
6fbf66fa
JY
888 if (flags & ISC_ERRORS)
889 detail = "ERROR";
890 management_set_state (management,
891 OPENVPN_STATE_CONNECTED,
892 detail,
5ad84585
JY
893 tun_local,
894 tun_remote);
6fbf66fa
JY
895 if (tun_local)
896 management_post_tunnel_open (management, tun_local);
897 }
898#endif
899
900}
901
902/*
903 * Possibly add routes and/or call route-up script
904 * based on options.
905 */
906void
907do_route (const struct options *options,
908 struct route_list *route_list,
909 const struct tuntap *tt,
910 const struct plugin_list *plugins,
911 struct env_set *es)
912{
913 if (!options->route_noexec && route_list)
914 add_routes (route_list, tt, ROUTE_OPTION_FLAGS (options), es);
915
916 if (plugin_defined (plugins, OPENVPN_PLUGIN_ROUTE_UP))
917 {
344ee918 918 if (plugin_call (plugins, OPENVPN_PLUGIN_ROUTE_UP, NULL, NULL, es) != OPENVPN_PLUGIN_FUNC_SUCCESS)
6fbf66fa
JY
919 msg (M_WARN, "WARNING: route-up plugin call failed");
920 }
921
922 if (options->route_script)
923 {
5a2e9a25 924 struct argv argv = argv_new ();
6fbf66fa 925 setenv_str (es, "script_type", "route-up");
5a2e9a25
JY
926 argv_printf (&argv, "%s", options->route_script);
927 openvpn_execve_check (&argv, es, S_SCRIPT, "Route script failed");
928 argv_reset (&argv);
6fbf66fa
JY
929 }
930
931#ifdef WIN32
932 if (options->show_net_up)
933 {
934 show_routes (M_INFO|M_NOPREFIX);
935 show_adapters (M_INFO|M_NOPREFIX);
936 }
937 else if (check_debug_level (D_SHOW_NET))
938 {
939 show_routes (D_SHOW_NET|M_NOPREFIX);
940 show_adapters (D_SHOW_NET|M_NOPREFIX);
941 }
942#endif
943}
944
945/*
946 * Save current pulled options string in the c1 context store, so we can
947 * compare against it after possible future restarts.
948 */
949#if P2MP
950static void
951save_pulled_options_string (struct context *c, const char *newstring)
952{
953 if (c->c1.pulled_options_string_save)
954 free (c->c1.pulled_options_string_save);
955
956 c->c1.pulled_options_string_save = NULL;
957
958 if (newstring)
959 c->c1.pulled_options_string_save = string_alloc (newstring, NULL);
960}
961#endif
962
963/*
964 * initialize tun/tap device object
965 */
966static void
967do_init_tun (struct context *c)
968{
969 c->c1.tuntap = init_tun (c->options.dev,
970 c->options.dev_type,
3c7f2f55 971 c->options.topology,
6fbf66fa
JY
972 c->options.ifconfig_local,
973 c->options.ifconfig_remote_netmask,
974 addr_host (&c->c1.link_socket_addr.local),
975 addr_host (&c->c1.link_socket_addr.remote),
976 !c->options.ifconfig_nowarn,
977 c->c2.es);
978
979 init_tun_post (c->c1.tuntap,
980 &c->c2.frame,
981 &c->options.tuntap_options);
982
983 c->c1.tuntap_owned = true;
984}
985
986/*
987 * Open tun/tap device, ifconfig, call up script, etc.
988 */
989
990static bool
991do_open_tun (struct context *c)
992{
993 struct gc_arena gc = gc_new ();
994 bool ret = false;
995
996 c->c2.ipv4_tun = (!c->options.tun_ipv6
997 && is_dev_type (c->options.dev, c->options.dev_type, "tun"));
998
999 if (!c->c1.tuntap)
1000 {
1001 /* initialize (but do not open) tun/tap object */
1002 do_init_tun (c);
1003
1004 /* allocate route list structure */
1005 do_alloc_route_list (c);
1006
1007 /* parse and resolve the route option list */
3c7f2f55 1008 if (c->options.routes && c->c1.route_list && c->c2.link_socket)
6fbf66fa
JY
1009 do_init_route_list (&c->options, c->c1.route_list, &c->c2.link_socket->info, false, c->c2.es);
1010
1011 /* do ifconfig */
1012 if (!c->options.ifconfig_noexec
1013 && ifconfig_order () == IFCONFIG_BEFORE_TUN_OPEN)
1014 {
1015 /* guess actual tun/tap unit number that will be returned
1016 by open_tun */
1017 const char *guess = guess_tuntap_dev (c->options.dev,
1018 c->options.dev_type,
1019 c->options.dev_node,
1020 &gc);
1021 do_ifconfig (c->c1.tuntap, guess, TUN_MTU_SIZE (&c->c2.frame), c->c2.es);
1022 }
1023
1024 /* open the tun device */
1025 open_tun (c->options.dev, c->options.dev_type, c->options.dev_node,
1026 c->options.tun_ipv6, c->c1.tuntap);
1027
e12fe286
JY
1028 /* set the hardware address */
1029 if (c->options.lladdr)
1030 set_lladdr(c->c1.tuntap->actual_name, c->options.lladdr, c->c2.es);
1031
6fbf66fa
JY
1032 /* do ifconfig */
1033 if (!c->options.ifconfig_noexec
1034 && ifconfig_order () == IFCONFIG_AFTER_TUN_OPEN)
1035 {
1036 do_ifconfig (c->c1.tuntap, c->c1.tuntap->actual_name, TUN_MTU_SIZE (&c->c2.frame), c->c2.es);
1037 }
1038
1039 /* run the up script */
1040 run_up_down (c->options.up_script,
3c7f2f55 1041 c->plugins,
6fbf66fa
JY
1042 OPENVPN_PLUGIN_UP,
1043 c->c1.tuntap->actual_name,
1044 TUN_MTU_SIZE (&c->c2.frame),
1045 EXPANDED_SIZE (&c->c2.frame),
1046 print_in_addr_t (c->c1.tuntap->local, IA_EMPTY_IF_UNDEF, &gc),
1047 print_in_addr_t (c->c1.tuntap->remote_netmask, IA_EMPTY_IF_UNDEF, &gc),
1048 "init",
1049 NULL,
1050 "up",
1051 c->c2.es);
1052
1053 /* possibly add routes */
1054 if (!c->options.route_delay_defined)
3c7f2f55 1055 do_route (&c->options, c->c1.route_list, c->c1.tuntap, c->plugins, c->c2.es);
6fbf66fa
JY
1056
1057 /*
1058 * Did tun/tap driver give us an MTU?
1059 */
1060 if (c->c1.tuntap->post_open_mtu)
1061 frame_set_mtu_dynamic (&c->c2.frame,
1062 c->c1.tuntap->post_open_mtu,
1063 SET_MTU_TUN | SET_MTU_UPPER_BOUND);
1064
1065 ret = true;
1066 }
1067 else
1068 {
1069 msg (M_INFO, "Preserving previous TUN/TAP instance: %s",
1070 c->c1.tuntap->actual_name);
1071
1072 /* run the up script if user specified --up-restart */
1073 if (c->options.up_restart)
1074 run_up_down (c->options.up_script,
3c7f2f55 1075 c->plugins,
6fbf66fa
JY
1076 OPENVPN_PLUGIN_UP,
1077 c->c1.tuntap->actual_name,
1078 TUN_MTU_SIZE (&c->c2.frame),
1079 EXPANDED_SIZE (&c->c2.frame),
1080 print_in_addr_t (c->c1.tuntap->local, IA_EMPTY_IF_UNDEF, &gc),
1081 print_in_addr_t (c->c1.tuntap->remote_netmask, IA_EMPTY_IF_UNDEF, &gc),
1082 "restart",
1083 NULL,
1084 "up",
1085 c->c2.es);
1086 }
1087 gc_free (&gc);
1088 return ret;
1089}
1090
1091/*
1092 * Close TUN/TAP device
1093 */
1094
1095static void
1096do_close_tun_simple (struct context *c)
1097{
1098 msg (D_CLOSE, "Closing TUN/TAP interface");
1099 close_tun (c->c1.tuntap);
1100 c->c1.tuntap = NULL;
1101 c->c1.tuntap_owned = false;
1102#if P2MP
1103 save_pulled_options_string (c, NULL); /* delete C1-saved pulled_options_string */
1104#endif
1105}
1106
1107static void
1108do_close_tun (struct context *c, bool force)
1109{
1110 struct gc_arena gc = gc_new ();
1111 if (c->c1.tuntap && c->c1.tuntap_owned)
1112 {
1113 const char *tuntap_actual = string_alloc (c->c1.tuntap->actual_name, &gc);
1114 const in_addr_t local = c->c1.tuntap->local;
1115 const in_addr_t remote_netmask = c->c1.tuntap->remote_netmask;
1116
1117 if (force || !(c->sig->signal_received == SIGUSR1 && c->options.persist_tun))
1118 {
1119#ifdef ENABLE_MANAGEMENT
1120 /* tell management layer we are about to close the TUN/TAP device */
1121 if (management)
1122 management_pre_tunnel_close (management);
1123#endif
1124
1125 /* delete any routes we added */
1126 if (c->c1.route_list)
1127 delete_routes (c->c1.route_list, c->c1.tuntap, ROUTE_OPTION_FLAGS (&c->options), c->c2.es);
1128
1129 /* actually close tun/tap device based on --down-pre flag */
1130 if (!c->options.down_pre)
1131 do_close_tun_simple (c);
1132
1133 /* Run the down script -- note that it will run at reduced
1134 privilege if, for example, "--user nobody" was used. */
1135 run_up_down (c->options.down_script,
3c7f2f55 1136 c->plugins,
6fbf66fa
JY
1137 OPENVPN_PLUGIN_DOWN,
1138 tuntap_actual,
1139 TUN_MTU_SIZE (&c->c2.frame),
1140 EXPANDED_SIZE (&c->c2.frame),
1141 print_in_addr_t (local, IA_EMPTY_IF_UNDEF, &gc),
1142 print_in_addr_t (remote_netmask, IA_EMPTY_IF_UNDEF, &gc),
1143 "init",
1144 signal_description (c->sig->signal_received,
1145 c->sig->signal_text),
1146 "down",
1147 c->c2.es);
1148
1149 /* actually close tun/tap device based on --down-pre flag */
1150 if (c->options.down_pre)
1151 do_close_tun_simple (c);
1152 }
1153 else
1154 {
1155 /* run the down script on this restart if --up-restart was specified */
1156 if (c->options.up_restart)
1157 run_up_down (c->options.down_script,
3c7f2f55 1158 c->plugins,
6fbf66fa
JY
1159 OPENVPN_PLUGIN_DOWN,
1160 tuntap_actual,
1161 TUN_MTU_SIZE (&c->c2.frame),
1162 EXPANDED_SIZE (&c->c2.frame),
1163 print_in_addr_t (local, IA_EMPTY_IF_UNDEF, &gc),
1164 print_in_addr_t (remote_netmask, IA_EMPTY_IF_UNDEF, &gc),
1165 "restart",
1166 signal_description (c->sig->signal_received,
1167 c->sig->signal_text),
1168 "down",
1169 c->c2.es);
1170 }
1171 }
1172 gc_free (&gc);
1173}
1174
1175/*
1176 * Handle delayed tun/tap interface bringup due to --up-delay or --pull
1177 */
1178
1179void
1180do_up (struct context *c, bool pulled_options, unsigned int option_types_found)
1181{
1182 if (!c->c2.do_up_ran)
1183 {
1184 reset_coarse_timers (c);
1185
1186 if (pulled_options && option_types_found)
1187 do_deferred_options (c, option_types_found);
1188
1189 /* if --up-delay specified, open tun, do ifconfig, and run up script now */
1190 if (c->options.up_delay || PULL_DEFINED (&c->options))
1191 {
1192 c->c2.did_open_tun = do_open_tun (c);
1193 update_time ();
1194
1195#if P2MP
1196 /*
1197 * Was tun interface object persisted from previous restart iteration,
1198 * and if so did pulled options string change from previous iteration?
1199 */
1200 if (!c->c2.did_open_tun
1201 && PULL_DEFINED (&c->options)
1202 && c->c1.tuntap
1203 && (!c->c1.pulled_options_string_save || !c->c2.pulled_options_string
1204 || strcmp (c->c1.pulled_options_string_save, c->c2.pulled_options_string)))
1205 {
1206 /* if so, close tun, delete routes, then reinitialize tun and add routes */
1207 msg (M_INFO, "NOTE: Pulled options changed on restart, will need to close and reopen TUN/TAP device.");
1208 do_close_tun (c, true);
1209 openvpn_sleep (1);
1210 c->c2.did_open_tun = do_open_tun (c);
1211 update_time ();
1212 }
1213#endif
1214 }
1215
1216 if (c->c2.did_open_tun)
1217 {
1218#if P2MP
1219 save_pulled_options_string (c, c->c2.pulled_options_string);
1220#endif
1221
1222 /* if --route-delay was specified, start timer */
1223 if (c->options.route_delay_defined)
1224 {
1225 event_timeout_init (&c->c2.route_wakeup, c->options.route_delay, now);
1226 event_timeout_init (&c->c2.route_wakeup_expire, c->options.route_delay + c->options.route_delay_window, now);
c67d59cd
JY
1227 if (c->c1.tuntap)
1228 tun_standby_init (c->c1.tuntap);
6fbf66fa
JY
1229 }
1230 else
1231 {
1232 initialization_sequence_completed (c, 0); /* client/p2p --route-delay undefined */
1233 }
1234 }
1235 else if (c->options.mode == MODE_POINT_TO_POINT)
1236 {
1237 initialization_sequence_completed (c, 0); /* client/p2p restart with --persist-tun */
1238 }
1239
1240 c->c2.do_up_ran = true;
1241 }
1242}
1243
1244/*
1245 * These are the option categories which will be accepted by pull.
1246 */
1247unsigned int
3c7f2f55 1248pull_permission_mask (const struct context *c)
6fbf66fa 1249{
3c7f2f55
JY
1250 unsigned int flags =
1251 OPT_P_UP
1252 | OPT_P_ROUTE_EXTRAS
1253 | OPT_P_IPWIN32
00d39170
JY
1254 | OPT_P_SOCKBUF
1255 | OPT_P_SOCKFLAGS
3c7f2f55
JY
1256 | OPT_P_SETENV
1257 | OPT_P_SHAPER
1258 | OPT_P_TIMER
537073fd 1259 | OPT_P_COMP
3c7f2f55
JY
1260 | OPT_P_PERSIST
1261 | OPT_P_MESSAGES
1262 | OPT_P_EXPLICIT_NOTIFY
1263 | OPT_P_ECHO
1264 | OPT_P_PULL_MODE;
1265
1266 if (!c->options.route_nopull)
1267 flags |= OPT_P_ROUTE;
1268
1269 return flags;
6fbf66fa
JY
1270}
1271
1272/*
1273 * Handle non-tun-related pulled options.
1274 */
1275void
1276do_deferred_options (struct context *c, const unsigned int found)
1277{
1278 if (found & OPT_P_MESSAGES)
1279 {
1280 init_verb_mute (c, IVM_LEVEL_1|IVM_LEVEL_2);
1281 msg (D_PUSH, "OPTIONS IMPORT: --verb and/or --mute level changed");
1282 }
1283 if (found & OPT_P_TIMER)
1284 {
1285 do_init_timers (c, true);
1286 msg (D_PUSH, "OPTIONS IMPORT: timers and/or timeouts modified");
1287 }
1288
1289#ifdef ENABLE_OCC
1290 if (found & OPT_P_EXPLICIT_NOTIFY)
1291 {
4e9a51d7 1292 if (c->options.ce.proto != PROTO_UDPv4 && c->options.explicit_exit_notification)
6fbf66fa
JY
1293 {
1294 msg (D_PUSH, "OPTIONS IMPORT: --explicit-exit-notify can only be used with --proto udp");
1295 c->options.explicit_exit_notification = 0;
1296 }
1297 else
1298 msg (D_PUSH, "OPTIONS IMPORT: explicit notify parm(s) modified");
1299 }
1300#endif
1301
537073fd
JY
1302#ifdef USE_LZO
1303 if (found & OPT_P_COMP)
1304 {
1305 if (lzo_defined (&c->c2.lzo_compwork))
1306 {
1307 msg (D_PUSH, "OPTIONS IMPORT: LZO parms modified");
1308 lzo_modify_flags (&c->c2.lzo_compwork, c->options.lzo);
1309 }
1310 }
1311#endif
1312
6fbf66fa
JY
1313 if (found & OPT_P_SHAPER)
1314 {
1315 msg (D_PUSH, "OPTIONS IMPORT: traffic shaper enabled");
1316 do_init_traffic_shaper (c);
1317 }
1318
00d39170
JY
1319 if (found & OPT_P_SOCKBUF)
1320 {
1321 msg (D_PUSH, "OPTIONS IMPORT: --sndbuf/--rcvbuf options modified");
1322 link_socket_update_buffer_sizes (c->c2.link_socket, c->options.rcvbuf, c->options.sndbuf);
1323 }
1324
1325 if (found & OPT_P_SOCKFLAGS)
1326 {
1327 msg (D_PUSH, "OPTIONS IMPORT: --socket-flags option modified");
1328 link_socket_update_flags (c->c2.link_socket, c->options.sockflags);
1329 }
1330
6fbf66fa
JY
1331 if (found & OPT_P_PERSIST)
1332 msg (D_PUSH, "OPTIONS IMPORT: --persist options modified");
1333 if (found & OPT_P_UP)
1334 msg (D_PUSH, "OPTIONS IMPORT: --ifconfig/up options modified");
1335 if (found & OPT_P_ROUTE)
1336 msg (D_PUSH, "OPTIONS IMPORT: route options modified");
3c7f2f55
JY
1337 if (found & OPT_P_ROUTE_EXTRAS)
1338 msg (D_PUSH, "OPTIONS IMPORT: route-related options modified");
6fbf66fa
JY
1339 if (found & OPT_P_IPWIN32)
1340 msg (D_PUSH, "OPTIONS IMPORT: --ip-win32 and/or --dhcp-option options modified");
1341 if (found & OPT_P_SETENV)
1342 msg (D_PUSH, "OPTIONS IMPORT: environment modified");
1343}
1344
1345/*
1346 * Possible hold on initialization
1347 */
1348static bool
1349do_hold (struct context *c)
1350{
1351#ifdef ENABLE_MANAGEMENT
1352 if (management)
1353 {
1354 /* if c is defined, daemonize before hold */
92bbb061 1355 if (c && c->options.daemon && management_should_daemonize (management))
6fbf66fa
JY
1356 do_init_first_time (c);
1357
1358 /* block until management hold is released */
1359 if (management_hold (management))
1360 return true;
1361 }
1362#endif
1363 return false;
1364}
1365
1366/*
1367 * Sleep before restart.
1368 */
1369static void
1370socket_restart_pause (struct context *c)
1371{
1372 bool proxy = false;
1373 int sec = 2;
1374
1375#ifdef ENABLE_HTTP_PROXY
4e9a51d7 1376 if (c->options.ce.http_proxy_options)
6fbf66fa
JY
1377 proxy = true;
1378#endif
1379#ifdef ENABLE_SOCKS
4e9a51d7 1380 if (c->options.ce.socks_proxy_server)
6fbf66fa
JY
1381 proxy = true;
1382#endif
1383
4e9a51d7 1384 switch (c->options.ce.proto)
6fbf66fa
JY
1385 {
1386 case PROTO_UDPv4:
1387 if (proxy)
4e9a51d7 1388 sec = c->options.ce.connect_retry_seconds;
6fbf66fa
JY
1389 break;
1390 case PROTO_TCPv4_SERVER:
1391 sec = 1;
1392 break;
1393 case PROTO_TCPv4_CLIENT:
4e9a51d7 1394 sec = c->options.ce.connect_retry_seconds;
6fbf66fa
JY
1395 break;
1396 }
1397
1398#ifdef ENABLE_DEBUG
1399 if (GREMLIN_CONNECTION_FLOOD_LEVEL (c->options.gremlin))
1400 sec = 0;
1401#endif
1402
1403#if P2MP
1404 if (auth_retry_get () == AR_NOINTERACT)
1405 sec = 10;
1406#endif
1407
a9c802b2
JY
1408 if (c->persist.restart_sleep_seconds > 0 && c->persist.restart_sleep_seconds > sec)
1409 sec = c->persist.restart_sleep_seconds;
1410 c->persist.restart_sleep_seconds = 0;
1411
2c21891e 1412 /* do managment hold on context restart, i.e. second, third, fourth, etc. initialization */
6fbf66fa
JY
1413 if (do_hold (NULL))
1414 sec = 0;
1415
1416 if (sec)
1417 {
1418 msg (D_RESTART, "Restart pause, %d second(s)", sec);
1419 openvpn_sleep (sec);
1420 }
1421}
1422
1423/*
1424 * Do a possible pause on context_2 initialization.
1425 */
1426static void
1427do_startup_pause (struct context *c)
1428{
1429 if (!c->first_time)
1430 socket_restart_pause (c);
1431 else
2c21891e 1432 do_hold (NULL); /* do management hold on first context initialization */
6fbf66fa
JY
1433}
1434
1435/*
1436 * Finalize MTU parameters based on command line or config file options.
1437 */
1438static void
1439frame_finalize_options (struct context *c, const struct options *o)
1440{
1441 if (!o)
1442 o = &c->options;
1443
1444 /*
1445 * Set adjustment factor for buffer alignment when no
1446 * cipher is used.
1447 */
1448 if (!CIPHER_ENABLED (c))
1449 {
1450 frame_align_to_extra_frame (&c->c2.frame);
1451 frame_or_align_flags (&c->c2.frame,
1452 FRAME_HEADROOM_MARKER_FRAGMENT
1453 |FRAME_HEADROOM_MARKER_READ_LINK
1454 |FRAME_HEADROOM_MARKER_READ_STREAM);
1455 }
1456
1457 frame_finalize (&c->c2.frame,
1458 o->link_mtu_defined,
1459 o->link_mtu,
1460 o->tun_mtu_defined,
1461 o->tun_mtu);
1462}
1463
1464/*
1465 * Free a key schedule, including OpenSSL components.
1466 */
1467static void
1468key_schedule_free (struct key_schedule *ks, bool free_ssl_ctx)
1469{
1470#ifdef USE_CRYPTO
1471 free_key_ctx_bi (&ks->static_key);
1472#ifdef USE_SSL
1473 if (ks->ssl_ctx && free_ssl_ctx)
1474 {
1475 SSL_CTX_free (ks->ssl_ctx);
1476 free_key_ctx_bi (&ks->tls_auth_key);
1477 }
1478#endif /* USE_SSL */
1479#endif /* USE_CRYPTO */
1480 CLEAR (*ks);
1481}
1482
1483#ifdef USE_CRYPTO
1484
1485static void
1486init_crypto_pre (struct context *c, const unsigned int flags)
1487{
1488 if (c->options.engine)
1489 init_crypto_lib_engine (c->options.engine);
1490
1491 if (flags & CF_LOAD_PERSISTED_PACKET_ID)
1492 {
1493 /* load a persisted packet-id for cross-session replay-protection */
1494 if (c->options.packet_id_file)
1495 packet_id_persist_load (&c->c1.pid_persist, c->options.packet_id_file);
1496 }
1497
1498 /* Initialize crypto options */
1499
1500 if (c->options.use_iv)
1501 c->c2.crypto_options.flags |= CO_USE_IV;
1502
1503 if (c->options.mute_replay_warnings)
1504 c->c2.crypto_options.flags |= CO_MUTE_REPLAY_WARNINGS;
1505}
1506
1507/*
1508 * Static Key Mode (using a pre-shared key)
1509 */
1510static void
1511do_init_crypto_static (struct context *c, const unsigned int flags)
1512{
1513 const struct options *options = &c->options;
1514 ASSERT (options->shared_secret_file);
1515
1516 init_crypto_pre (c, flags);
1517
1518 /* Initialize packet ID tracking */
1519 if (options->replay)
1520 {
1521 packet_id_init (&c->c2.packet_id, options->replay_window,
1522 options->replay_time);
1523 c->c2.crypto_options.packet_id = &c->c2.packet_id;
1524 c->c2.crypto_options.pid_persist = &c->c1.pid_persist;
1525 c->c2.crypto_options.flags |= CO_PACKET_ID_LONG_FORM;
1526 packet_id_persist_load_obj (&c->c1.pid_persist,
1527 c->c2.crypto_options.packet_id);
1528 }
1529
1530 if (!key_ctx_bi_defined (&c->c1.ks.static_key))
1531 {
1532 struct key2 key2;
1533 struct key_direction_state kds;
1534
1535 /* Get cipher & hash algorithms */
1536 init_key_type (&c->c1.ks.key_type, options->ciphername,
1537 options->ciphername_defined, options->authname,
1538 options->authname_defined, options->keysize,
1539 options->test_crypto, true);
1540
1541 /* Read cipher and hmac keys from shared secret file */
c959fc74
JY
1542 {
1543 unsigned int rkf_flags = RKF_MUST_SUCCEED;
1544 const char *rkf_file = options->shared_secret_file;
1545
1546#if ENABLE_INLINE_FILES
1547 if (options->shared_secret_file_inline)
1548 {
1549 rkf_file = options->shared_secret_file_inline;
1550 rkf_flags |= RKF_INLINE;
1551 }
1552#endif
1553 read_key_file (&key2, rkf_file, rkf_flags);
1554 }
6fbf66fa
JY
1555
1556 /* Check for and fix highly unlikely key problems */
1557 verify_fix_key2 (&key2, &c->c1.ks.key_type,
1558 options->shared_secret_file);
1559
1560 /* Initialize OpenSSL key objects */
1561 key_direction_state_init (&kds, options->key_direction);
1562 must_have_n_keys (options->shared_secret_file, "secret", &key2,
1563 kds.need_keys);
1564 init_key_ctx (&c->c1.ks.static_key.encrypt, &key2.keys[kds.out_key],
1565 &c->c1.ks.key_type, DO_ENCRYPT, "Static Encrypt");
1566 init_key_ctx (&c->c1.ks.static_key.decrypt, &key2.keys[kds.in_key],
1567 &c->c1.ks.key_type, DO_DECRYPT, "Static Decrypt");
1568
1569 /* Erase the temporary copy of key */
1570 CLEAR (key2);
1571 }
1572 else
1573 {
1574 msg (M_INFO, "Re-using pre-shared static key");
1575 }
1576
1577 /* Get key schedule */
1578 c->c2.crypto_options.key_ctx_bi = &c->c1.ks.static_key;
1579
1580 /* Compute MTU parameters */
1581 crypto_adjust_frame_parameters (&c->c2.frame,
1582 &c->c1.ks.key_type,
1583 options->ciphername_defined,
1584 options->use_iv, options->replay, true);
1585
1586 /* Sanity check on IV, sequence number, and cipher mode options */
1587 check_replay_iv_consistency (&c->c1.ks.key_type, options->replay,
1588 options->use_iv);
1589}
1590
1591#ifdef USE_SSL
1592
1593/*
1594 * Initialize the persistent component of OpenVPN's TLS mode,
1595 * which is preserved across SIGUSR1 resets.
1596 */
1597static void
1598do_init_crypto_tls_c1 (struct context *c)
1599{
1600 const struct options *options = &c->options;
1601
1602 if (!c->c1.ks.ssl_ctx)
1603 {
1604 /*
1605 * Initialize the OpenSSL library's global
1606 * SSL context.
1607 */
1608 c->c1.ks.ssl_ctx = init_ssl (options);
1609 if (!c->c1.ks.ssl_ctx)
1610 {
1611#if P2MP
1612 switch (auth_retry_get ())
1613 {
1614 case AR_NONE:
1615 msg (M_FATAL, "Error: private key password verification failed");
1616 break;
1617 case AR_INTERACT:
1618 ssl_purge_auth ();
1619 case AR_NOINTERACT:
1620 c->sig->signal_received = SIGUSR1; /* SOFT-SIGUSR1 -- Password failure error */
1621 break;
1622 default:
1623 ASSERT (0);
1624 }
1625 c->sig->signal_text = "private-key-password-failure";
1626 return;
1627#else
1628 msg (M_FATAL, "Error: private key password verification failed");
1629#endif
1630 }
1631
1632 /* Get cipher & hash algorithms */
1633 init_key_type (&c->c1.ks.key_type, options->ciphername,
1634 options->ciphername_defined, options->authname,
1635 options->authname_defined, options->keysize, true, true);
1636
1637 /* TLS handshake authentication (--tls-auth) */
1638 if (options->tls_auth_file)
c959fc74 1639 {
e5d281cf 1640 unsigned int flags = 0;
c959fc74
JY
1641 const char *file = options->tls_auth_file;
1642
1643#if ENABLE_INLINE_FILES
1644 if (options->tls_auth_file_inline)
1645 {
1646 flags |= GHK_INLINE;
1647 file = options->tls_auth_file_inline;
1648 }
1649#endif
1650 get_tls_handshake_key (&c->c1.ks.key_type,
1651 &c->c1.ks.tls_auth_key,
1652 file,
e5d281cf 1653 options->key_direction,
c959fc74
JY
1654 flags);
1655 }
d40f2b20
JY
1656
1657#if ENABLE_INLINE_FILES
1658 if (options->priv_key_file_inline)
1659 {
1660 string_clear (c->options.priv_key_file_inline);
1661 c->options.priv_key_file_inline = NULL;
1662 }
1663#endif
6fbf66fa
JY
1664 }
1665 else
1666 {
1667 msg (M_INFO, "Re-using SSL/TLS context");
1668 }
1669}
1670
1671static void
1672do_init_crypto_tls (struct context *c, const unsigned int flags)
1673{
1674 const struct options *options = &c->options;
1675 struct tls_options to;
1676 bool packet_id_long_form;
1677
1678 ASSERT (options->tls_server || options->tls_client);
1679 ASSERT (!options->test_crypto);
1680
1681 init_crypto_pre (c, flags);
1682
1683 /* Make sure we are either a TLS client or server but not both */
1684 ASSERT (options->tls_server == !options->tls_client);
1685
1686 /* initialize persistent component */
1687 do_init_crypto_tls_c1 (c);
1688 if (IS_SIG (c))
1689 return;
1690
1691 /* Sanity check on IV, sequence number, and cipher mode options */
1692 check_replay_iv_consistency (&c->c1.ks.key_type, options->replay,
1693 options->use_iv);
1694
1695 /* In short form, unique datagram identifier is 32 bits, in long form 64 bits */
1696 packet_id_long_form = cfb_ofb_mode (&c->c1.ks.key_type);
1697
1698 /* Compute MTU parameters */
1699 crypto_adjust_frame_parameters (&c->c2.frame,
1700 &c->c1.ks.key_type,
1701 options->ciphername_defined,
1702 options->use_iv,
1703 options->replay, packet_id_long_form);
1704 tls_adjust_frame_parameters (&c->c2.frame);
1705
1706 /* Set all command-line TLS-related options */
1707 CLEAR (to);
1708
1709 to.crypto_flags_and = ~(CO_PACKET_ID_LONG_FORM);
1710 if (packet_id_long_form)
1711 to.crypto_flags_or = CO_PACKET_ID_LONG_FORM;
1712
1713 to.ssl_ctx = c->c1.ks.ssl_ctx;
1714 to.key_type = c->c1.ks.key_type;
1715 to.server = options->tls_server;
1716 to.key_method = options->key_method;
1717 to.replay = options->replay;
1718 to.replay_window = options->replay_window;
1719 to.replay_time = options->replay_time;
1720 to.transition_window = options->transition_window;
1721 to.handshake_window = options->handshake_window;
1722 to.packet_timeout = options->tls_timeout;
1723 to.renegotiate_bytes = options->renegotiate_bytes;
1724 to.renegotiate_packets = options->renegotiate_packets;
1725 to.renegotiate_seconds = options->renegotiate_seconds;
1726 to.single_session = options->single_session;
1727
6add6b2f
JY
1728 /* should we not xmit any packets until we get an initial
1729 response from client? */
4e9a51d7 1730 if (to.server && options->ce.proto == PROTO_TCPv4_SERVER)
6add6b2f
JY
1731 to.xmit_hold = true;
1732
6fbf66fa
JY
1733#ifdef ENABLE_OCC
1734 to.disable_occ = !options->occ;
1735#endif
1736
1737 to.verify_command = options->tls_verify;
1738 to.verify_x509name = options->tls_remote;
1739 to.crl_file = options->crl_file;
1740 to.ns_cert_type = options->ns_cert_type;
411e89ae
JY
1741 memmove (to.remote_cert_ku, options->remote_cert_ku, sizeof (to.remote_cert_ku));
1742 to.remote_cert_eku = options->remote_cert_eku;
6fbf66fa
JY
1743 to.es = c->c2.es;
1744
1745#ifdef ENABLE_DEBUG
1746 to.gremlin = c->options.gremlin;
1747#endif
1748
3c7f2f55 1749 to.plugins = c->plugins;
6fbf66fa 1750
90efcacb
JY
1751#ifdef MANAGEMENT_DEF_AUTH
1752 to.mda_context = &c->c2.mda_context;
1753#endif
1754
6fbf66fa
JY
1755#if P2MP_SERVER
1756 to.auth_user_pass_verify_script = options->auth_user_pass_verify_script;
1757 to.auth_user_pass_verify_script_via_file = options->auth_user_pass_verify_script_via_file;
1758 to.tmp_dir = options->tmp_dir;
1759 to.username_as_common_name = options->username_as_common_name;
1760 if (options->ccd_exclusive)
1761 to.client_config_dir_exclusive = options->client_config_dir;
1762#endif
1763
1764 /* TLS handshake authentication (--tls-auth) */
1765 if (options->tls_auth_file)
1766 {
1767 to.tls_auth_key = c->c1.ks.tls_auth_key;
1768 to.tls_auth.pid_persist = &c->c1.pid_persist;
1769 to.tls_auth.flags |= CO_PACKET_ID_LONG_FORM;
1770 crypto_adjust_frame_parameters (&to.frame,
1771 &c->c1.ks.key_type,
1772 false, false, true, true);
1773 }
1774
1775 /* If we are running over TCP, allow for
1776 length prefix */
4e9a51d7 1777 socket_adjust_frame_parameters (&to.frame, options->ce.proto);
6fbf66fa
JY
1778
1779 /*
1780 * Initialize OpenVPN's master TLS-mode object.
1781 */
1782 if (flags & CF_INIT_TLS_MULTI)
1783 c->c2.tls_multi = tls_multi_init (&to);
1784
1785 if (flags & CF_INIT_TLS_AUTH_STANDALONE)
1786 c->c2.tls_auth_standalone = tls_auth_standalone_init (&to, &c->c2.gc);
1787}
1788
1789static void
1790do_init_finalize_tls_frame (struct context *c)
1791{
1792 if (c->c2.tls_multi)
1793 {
1794 tls_multi_init_finalize (c->c2.tls_multi, &c->c2.frame);
1795 ASSERT (EXPANDED_SIZE (&c->c2.tls_multi->opt.frame) <=
1796 EXPANDED_SIZE (&c->c2.frame));
1797 frame_print (&c->c2.tls_multi->opt.frame, D_MTU_INFO,
1798 "Control Channel MTU parms");
1799 }
1800 if (c->c2.tls_auth_standalone)
1801 {
1802 tls_auth_standalone_finalize (c->c2.tls_auth_standalone, &c->c2.frame);
1803 frame_print (&c->c2.tls_auth_standalone->frame, D_MTU_INFO,
1804 "TLS-Auth MTU parms");
1805 }
1806}
1807
1808#endif /* USE_SSL */
1809#endif /* USE_CRYPTO */
1810
1811#ifdef USE_CRYPTO
1812/*
1813 * No encryption or authentication.
1814 */
1815static void
1816do_init_crypto_none (const struct context *c)
1817{
1818 ASSERT (!c->options.test_crypto);
1819 msg (M_WARN,
1820 "******* WARNING *******: all encryption and authentication features disabled -- all data will be tunnelled as cleartext");
1821}
1822#endif
1823
1824static void
1825do_init_crypto (struct context *c, const unsigned int flags)
1826{
1827#ifdef USE_CRYPTO
1828 if (c->options.shared_secret_file)
1829 do_init_crypto_static (c, flags);
1830#ifdef USE_SSL
1831 else if (c->options.tls_server || c->options.tls_client)
1832 do_init_crypto_tls (c, flags);
1833#endif
1834 else /* no encryption or authentication. */
1835 do_init_crypto_none (c);
1836#else /* USE_CRYPTO */
1837 msg (M_WARN,
1838 "******* WARNING *******: " PACKAGE_NAME
1839 " built without OpenSSL -- encryption and authentication features disabled -- all data will be tunnelled as cleartext");
1840#endif /* USE_CRYPTO */
1841}
1842
1843static void
1844do_init_frame (struct context *c)
1845{
1846#ifdef USE_LZO
1847 /*
1848 * Initialize LZO compression library.
1849 */
537073fd 1850 if (c->options.lzo & LZO_SELECTED)
6fbf66fa
JY
1851 {
1852 lzo_adjust_frame_parameters (&c->c2.frame);
1853
1854 /*
1855 * LZO usage affects buffer alignment.
1856 */
1857 if (CIPHER_ENABLED (c))
1858 {
1859 frame_add_to_align_adjust (&c->c2.frame, LZO_PREFIX_LEN);
1860 frame_or_align_flags (&c->c2.frame,
1861 FRAME_HEADROOM_MARKER_FRAGMENT
1862 |FRAME_HEADROOM_MARKER_DECRYPT);
1863 }
1864
1865#ifdef ENABLE_FRAGMENT
1866 lzo_adjust_frame_parameters (&c->c2.frame_fragment_omit); /* omit LZO frame delta from final frame_fragment */
1867#endif
1868 }
537073fd 1869#endif /* USE_LZO */
6fbf66fa
JY
1870
1871#ifdef ENABLE_SOCKS
1872 /*
1873 * Adjust frame size for UDP Socks support.
1874 */
4e9a51d7
JY
1875 if (c->options.ce.socks_proxy_server)
1876 socks_adjust_frame_parameters (&c->c2.frame, c->options.ce.proto);
6fbf66fa
JY
1877#endif
1878
1879 /*
1880 * Adjust frame size based on the --tun-mtu-extra parameter.
1881 */
1882 if (c->options.tun_mtu_extra_defined)
1883 tun_adjust_frame_parameters (&c->c2.frame, c->options.tun_mtu_extra);
1884
1885 /*
1886 * Adjust frame size based on link socket parameters.
1887 * (Since TCP is a stream protocol, we need to insert
1888 * a packet length uint16_t in the buffer.)
1889 */
4e9a51d7 1890 socket_adjust_frame_parameters (&c->c2.frame, c->options.ce.proto);
6fbf66fa
JY
1891
1892 /*
1893 * Fill in the blanks in the frame parameters structure,
1894 * make sure values are rational, etc.
1895 */
1896 frame_finalize_options (c, NULL);
1897
1898#ifdef ENABLE_FRAGMENT
1899 /*
1900 * Set frame parameter for fragment code. This is necessary because
1901 * the fragmentation code deals with payloads which have already been
1902 * passed through the compression code.
1903 */
1904 c->c2.frame_fragment = c->c2.frame;
1905 frame_subtract_extra (&c->c2.frame_fragment, &c->c2.frame_fragment_omit);
1906#endif
1907
1908#if defined(ENABLE_FRAGMENT) && defined(ENABLE_OCC)
1909 /*
1910 * MTU advisories
1911 */
1912 if (c->options.fragment && c->options.mtu_test)
1913 msg (M_WARN,
1914 "WARNING: using --fragment and --mtu-test together may produce an inaccurate MTU test result");
1915#endif
1916
1917#ifdef ENABLE_FRAGMENT
1918 if ((c->options.mssfix || c->options.fragment)
1919 && TUN_MTU_SIZE (&c->c2.frame_fragment) != ETHERNET_MTU)
1920 msg (M_WARN,
1921 "WARNING: normally if you use --mssfix and/or --fragment, you should also set --tun-mtu %d (currently it is %d)",
1922 ETHERNET_MTU, TUN_MTU_SIZE (&c->c2.frame_fragment));
1923#endif
1924}
1925
1926static void
1927do_option_warnings (struct context *c)
1928{
1929 const struct options *o = &c->options;
1930
1931#if 1 /* JYFIXME -- port warning */
4e9a51d7 1932 if (!o->ce.port_option_used && (o->ce.local_port == OPENVPN_PORT && o->ce.remote_port == OPENVPN_PORT))
6fbf66fa
JY
1933 msg (M_WARN, "IMPORTANT: OpenVPN's default port number is now %d, based on an official port number assignment by IANA. OpenVPN 2.0-beta16 and earlier used 5000 as the default port.",
1934 OPENVPN_PORT);
1935#endif
1936
1937 if (o->ping_send_timeout && !o->ping_rec_timeout)
1938 msg (M_WARN, "WARNING: --ping should normally be used with --ping-restart or --ping-exit");
1939
6d89ede6
JY
1940 if (o->username || o->groupname || o->chroot_dir)
1941 {
1942 if (!o->persist_tun)
1943 msg (M_WARN, "WARNING: you are using user/group/chroot without persist-tun -- this may cause restarts to fail");
51b1d4c2
JY
1944 if (!o->persist_key
1945#ifdef ENABLE_PKCS11
1946 && !o->pkcs11_id
1947#endif
1948 )
6d89ede6
JY
1949 msg (M_WARN, "WARNING: you are using user/group/chroot without persist-key -- this may cause restarts to fail");
1950 }
6fbf66fa 1951
31f90e64
JY
1952 if (o->chroot_dir && !(o->username && o->groupname))
1953 msg (M_WARN, "WARNING: you are using chroot without specifying user and group -- this may cause the chroot jail to be insecure");
1954
6fbf66fa
JY
1955#if P2MP
1956 if (o->pull && o->ifconfig_local && c->first_time)
1957 msg (M_WARN, "WARNING: using --pull/--client and --ifconfig together is probably not what you want");
1958
1959#if P2MP_SERVER
1960 if (o->mode == MODE_SERVER)
1961 {
1962 if (o->duplicate_cn && o->client_config_dir)
1963 msg (M_WARN, "WARNING: using --duplicate-cn and --client-config-dir together is probably not what you want");
1964 if (o->duplicate_cn && o->ifconfig_pool_persist_filename)
1965 msg (M_WARN, "WARNING: --ifconfig-pool-persist will not work with --duplicate-cn");
1966 if (!o->keepalive_ping || !o->keepalive_timeout)
1967 msg (M_WARN, "WARNING: --keepalive option is missing from server config");
1968 }
1969#endif
1970#endif
1971
1972#ifdef USE_CRYPTO
1973 if (!o->replay)
1974 msg (M_WARN, "WARNING: You have disabled Replay Protection (--no-replay) which may make " PACKAGE_NAME " less secure");
1975 if (!o->use_iv)
1976 msg (M_WARN, "WARNING: You have disabled Crypto IVs (--no-iv) which may make " PACKAGE_NAME " less secure");
1977
1978#ifdef USE_SSL
1979 if (o->tls_client
1980 && !o->tls_verify
1981 && !o->tls_remote
027a87ce 1982 && !(o->ns_cert_type & NS_SSL_SERVER)
6117b639 1983 && !o->remote_cert_eku)
6fbf66fa 1984 msg (M_WARN, "WARNING: No server certificate verification method has been enabled. See http://openvpn.net/howto.html#mitm for more info.");
c04bc022
JY
1985 if (o->tls_remote)
1986 msg (M_WARN, "WARNING: Make sure you understand the semantics of --tls-remote before using it (see the man page).");
6fbf66fa 1987#endif
1ae9d051 1988#endif
6fbf66fa 1989
1ae9d051 1990#ifndef CONNECT_NONBLOCK
4e9a51d7 1991 if (o->ce.connect_timeout_defined)
1ae9d051 1992 msg (M_WARN, "NOTE: --connect-timeout option is not supported on this OS");
6fbf66fa 1993#endif
c04bc022
JY
1994
1995 if (script_security >= SSEC_SCRIPTS)
1996 msg (M_WARN, "NOTE: the current --script-security setting may allow this configuration to call user-defined scripts");
1997 if (script_security >= SSEC_PW_ENV)
1998 msg (M_WARN, "WARNING: the current --script-security setting may allow passwords to be passed to scripts via environmental variables");
6fbf66fa
JY
1999}
2000
2001static void
2002do_init_frame_tls (struct context *c)
2003{
2004#if defined(USE_CRYPTO) && defined(USE_SSL)
2005 do_init_finalize_tls_frame (c);
2006#endif
2007}
2008
2009struct context_buffers *
2010init_context_buffers (const struct frame *frame)
2011{
2012 struct context_buffers *b;
2013
2014 ALLOC_OBJ_CLEAR (b, struct context_buffers);
2015
2016 b->read_link_buf = alloc_buf (BUF_SIZE (frame));
2017 b->read_tun_buf = alloc_buf (BUF_SIZE (frame));
2018
2019 b->aux_buf = alloc_buf (BUF_SIZE (frame));
2020
2021#ifdef USE_CRYPTO
2022 b->encrypt_buf = alloc_buf (BUF_SIZE (frame));
2023 b->decrypt_buf = alloc_buf (BUF_SIZE (frame));
2024#endif
2025
2026#ifdef USE_LZO
2027 b->lzo_compress_buf = alloc_buf (BUF_SIZE (frame));
2028 b->lzo_decompress_buf = alloc_buf (BUF_SIZE (frame));
2029#endif
2030
2031 return b;
2032}
2033
2034void
2035free_context_buffers (struct context_buffers *b)
2036{
2037 if (b)
2038 {
2039 free_buf (&b->read_link_buf);
2040 free_buf (&b->read_tun_buf);
2041 free_buf (&b->aux_buf);
2042
2043#ifdef USE_LZO
2044 free_buf (&b->lzo_compress_buf);
2045 free_buf (&b->lzo_decompress_buf);
2046#endif
2047
2048#ifdef USE_CRYPTO
2049 free_buf (&b->encrypt_buf);
2050 free_buf (&b->decrypt_buf);
2051#endif
2052
2053 free (b);
2054 }
2055}
2056
2057/*
2058 * Now that we know all frame parameters, initialize
2059 * our buffers.
2060 */
2061static void
2062do_init_buffers (struct context *c)
2063{
2064 c->c2.buffers = init_context_buffers (&c->c2.frame);
2065 c->c2.buffers_owned = true;
2066}
2067
2068#ifdef ENABLE_FRAGMENT
2069/*
2070 * Fragmenting code has buffers to initialize
2071 * once frame parameters are known.
2072 */
2073static void
2074do_init_fragment (struct context *c)
2075{
2076 ASSERT (c->options.fragment);
2077 frame_set_mtu_dynamic (&c->c2.frame_fragment,
2078 c->options.fragment, SET_MTU_UPPER_BOUND);
2079 fragment_frame_init (c->c2.fragment, &c->c2.frame_fragment);
2080}
2081#endif
2082
2083/*
2084 * Set the --mssfix option.
2085 */
2086static void
2087do_init_mssfix (struct context *c)
2088{
2089 if (c->options.mssfix)
2090 {
2091 frame_set_mtu_dynamic (&c->c2.frame,
2092 c->options.mssfix, SET_MTU_UPPER_BOUND);
2093 }
2094}
2095
2096/*
2097 * Allocate our socket object.
2098 */
2099static void
2100do_link_socket_new (struct context *c)
2101{
2102 ASSERT (!c->c2.link_socket);
2103 c->c2.link_socket = link_socket_new ();
2104 c->c2.link_socket_owned = true;
2105}
2106
2107/*
2108 * bind the TCP/UDP socket
2109 */
2110static void
dc46c067 2111do_init_socket_1 (struct context *c, const int mode)
6fbf66fa 2112{
dc46c067
JY
2113 unsigned int sockflags = c->options.sockflags;
2114
2115#if PORT_SHARE
2116 if (c->options.port_share_host && c->options.port_share_port)
2117 sockflags |= SF_PORT_SHARE;
2118#endif
2119
6fbf66fa 2120 link_socket_init_phase1 (c->c2.link_socket,
4e9a51d7
JY
2121 connection_list_defined (&c->options),
2122 c->options.ce.local,
2123 c->options.ce.local_port,
2124 c->options.ce.remote,
2125 c->options.ce.remote_port,
2126 c->options.ce.proto,
6fbf66fa
JY
2127 mode,
2128 c->c2.accept_from,
2129#ifdef ENABLE_HTTP_PROXY
2130 c->c1.http_proxy,
2131#endif
2132#ifdef ENABLE_SOCKS
2133 c->c1.socks_proxy,
2134#endif
2135#ifdef ENABLE_DEBUG
2136 c->options.gremlin,
2137#endif
4e9a51d7
JY
2138 c->options.ce.bind_local,
2139 c->options.ce.remote_float,
6fbf66fa
JY
2140 c->options.inetd,
2141 &c->c1.link_socket_addr,
2142 c->options.ipchange,
3c7f2f55 2143 c->plugins,
6fbf66fa 2144 c->options.resolve_retry_seconds,
4e9a51d7
JY
2145 c->options.ce.connect_retry_seconds,
2146 c->options.ce.connect_timeout,
2147 c->options.ce.connect_retry_max,
6fbf66fa
JY
2148 c->options.mtu_discover_type,
2149 c->options.rcvbuf,
00d39170 2150 c->options.sndbuf,
dc46c067 2151 sockflags);
6fbf66fa
JY
2152}
2153
2154/*
2155 * finalize the TCP/UDP socket
2156 */
2157static void
2158do_init_socket_2 (struct context *c)
2159{
2160 link_socket_init_phase2 (c->c2.link_socket, &c->c2.frame,
2161 &c->sig->signal_received);
2162}
2163
2164/*
2165 * Print MTU INFO
2166 */
2167static void
2168do_print_data_channel_mtu_parms (struct context *c)
2169{
2170 frame_print (&c->c2.frame, D_MTU_INFO, "Data Channel MTU parms");
2171#ifdef ENABLE_FRAGMENT
2172 if (c->c2.fragment)
2173 frame_print (&c->c2.frame_fragment, D_MTU_INFO,
2174 "Fragmentation MTU parms");
2175#endif
2176}
2177
2178#ifdef ENABLE_OCC
2179/*
2180 * Get local and remote options compatibility strings.
2181 */
2182static void
2183do_compute_occ_strings (struct context *c)
2184{
2185 struct gc_arena gc = gc_new ();
2186
2187 c->c2.options_string_local =
2188 options_string (&c->options, &c->c2.frame, c->c1.tuntap, false, &gc);
2189 c->c2.options_string_remote =
2190 options_string (&c->options, &c->c2.frame, c->c1.tuntap, true, &gc);
2191
2192 msg (D_SHOW_OCC, "Local Options String: '%s'", c->c2.options_string_local);
2193 msg (D_SHOW_OCC, "Expected Remote Options String: '%s'",
2194 c->c2.options_string_remote);
2195
2196#ifdef USE_CRYPTO
2197 msg (D_SHOW_OCC_HASH, "Local Options hash (VER=%s): '%s'",
2198 options_string_version (c->c2.options_string_local, &gc),
2199 md5sum ((uint8_t*)c->c2.options_string_local,
2200 strlen (c->c2.options_string_local), 9, &gc));
2201 msg (D_SHOW_OCC_HASH, "Expected Remote Options hash (VER=%s): '%s'",
2202 options_string_version (c->c2.options_string_remote, &gc),
2203 md5sum ((uint8_t*)c->c2.options_string_remote,
2204 strlen (c->c2.options_string_remote), 9, &gc));
2205#endif
2206
2207#if defined(USE_CRYPTO) && defined(USE_SSL)
2208 if (c->c2.tls_multi)
2209 tls_multi_init_set_options (c->c2.tls_multi,
2210 c->c2.options_string_local,
2211 c->c2.options_string_remote);
2212#endif
2213
2214 gc_free (&gc);
2215}
2216#endif
2217
2218/*
2219 * These things can only be executed once per program instantiation.
2220 * Set up for possible UID/GID downgrade, but don't do it yet.
2221 * Daemonize if requested.
2222 */
2223static void
2224do_init_first_time (struct context *c)
2225{
92bbb061 2226 if (c->first_time && !c->did_we_daemonize && !c->c0)
6fbf66fa 2227 {
92bbb061
JY
2228 struct context_0 *c0;
2229
2230 ALLOC_OBJ_CLEAR_GC (c->c0, struct context_0, &c->gc);
2231 c0 = c->c0;
2232
6fbf66fa 2233 /* get user and/or group that we want to setuid/setgid to */
92bbb061
JY
2234 c0->uid_gid_specified =
2235 get_group (c->options.groupname, &c0->group_state) |
2236 get_user (c->options.username, &c0->user_state);
6fbf66fa
JY
2237
2238 /* get --writepid file descriptor */
92bbb061 2239 get_pid_file (c->options.writepid, &c0->pid_state);
6fbf66fa
JY
2240
2241 /* become a daemon if --daemon */
90e105d2 2242 c->did_we_daemonize = possibly_become_daemon (&c->options, c->first_time);
6fbf66fa
JY
2243
2244 /* should we disable paging? */
90e105d2 2245 if (c->options.mlock && c->did_we_daemonize)
6fbf66fa
JY
2246 do_mlockall (true); /* call again in case we daemonized */
2247
2248 /* save process ID in a file */
92bbb061 2249 write_pid (&c0->pid_state);
6fbf66fa
JY
2250
2251 /* should we change scheduling priority? */
2252 set_nice (c->options.nice);
2253 }
2254}
2255
2256/*
2257 * If xinetd/inetd mode, don't allow restart.
2258 */
2259static void
2260do_close_check_if_restart_permitted (struct context *c)
2261{
2262 if (c->options.inetd
2263 && (c->sig->signal_received == SIGHUP
2264 || c->sig->signal_received == SIGUSR1))
2265 {
2266 c->sig->signal_received = SIGTERM;
2267 msg (M_INFO,
2268 PACKAGE_NAME
2269 " started by inetd/xinetd cannot restart... Exiting.");
2270 }
2271}
2272
2273/*
2274 * free buffers
2275 */
2276static void
2277do_close_free_buf (struct context *c)
2278{
2279 if (c->c2.buffers_owned)
2280 {
2281 free_context_buffers (c->c2.buffers);
2282 c->c2.buffers = NULL;
2283 c->c2.buffers_owned = false;
2284 }
2285}
2286
2287/*
2288 * close TLS
2289 */
2290static void
2291do_close_tls (struct context *c)
2292{
2293#if defined(USE_CRYPTO) && defined(USE_SSL)
2294 if (c->c2.tls_multi)
2295 {
2296 tls_multi_free (c->c2.tls_multi, true);
2297 c->c2.tls_multi = NULL;
2298 }
2299
2300#ifdef ENABLE_OCC
2301 /* free options compatibility strings */
2302 if (c->c2.options_string_local)
2303 free (c->c2.options_string_local);
2304 if (c->c2.options_string_remote)
2305 free (c->c2.options_string_remote);
2306 c->c2.options_string_local = c->c2.options_string_remote = NULL;
2307#endif
2308#endif
2309}
2310
2311/*
2312 * Free key schedules
2313 */
2314static void
2315do_close_free_key_schedule (struct context *c, bool free_ssl_ctx)
2316{
2317 if (!(c->sig->signal_received == SIGUSR1 && c->options.persist_key))
2318 key_schedule_free (&c->c1.ks, free_ssl_ctx);
2319}
2320
2321/*
2322 * Close TCP/UDP connection
2323 */
2324static void
2325do_close_link_socket (struct context *c)
2326{
2327 if (c->c2.link_socket && c->c2.link_socket_owned)
2328 {
2329 link_socket_close (c->c2.link_socket);
2330 c->c2.link_socket = NULL;
2331 }
2332
2333 if (!(c->sig->signal_received == SIGUSR1 && c->options.persist_remote_ip))
2334 {
2335 CLEAR (c->c1.link_socket_addr.remote);
2336 CLEAR (c->c1.link_socket_addr.actual);
2337 }
2338
2339 if (!(c->sig->signal_received == SIGUSR1 && c->options.persist_local_ip))
2340 CLEAR (c->c1.link_socket_addr.local);
2341}
2342
2343/*
2344 * Close packet-id persistance file
2345 */
2346static void
2347do_close_packet_id (struct context *c)
2348{
2349#ifdef USE_CRYPTO
2350 packet_id_free (&c->c2.packet_id);
2351 packet_id_persist_save (&c->c1.pid_persist);
2352 if (!(c->sig->signal_received == SIGUSR1))
2353 packet_id_persist_close (&c->c1.pid_persist);
2354#endif
2355}
2356
2357#ifdef ENABLE_FRAGMENT
2358/*
2359 * Close fragmentation handler.
2360 */
2361static void
2362do_close_fragment (struct context *c)
2363{
2364 if (c->c2.fragment)
2365 {
2366 fragment_free (c->c2.fragment);
2367 c->c2.fragment = NULL;
2368 }
2369}
2370#endif
2371
2372/*
2373 * Open and close our event objects.
2374 */
2375
2376static void
2377do_event_set_init (struct context *c,
2378 bool need_us_timeout)
2379{
2380 unsigned int flags = 0;
2381
2382 c->c2.event_set_max = BASE_N_EVENTS;
2383
2384 flags |= EVENT_METHOD_FAST;
2385
2386 if (need_us_timeout)
2387 flags |= EVENT_METHOD_US_TIMEOUT;
2388
2389 c->c2.event_set = event_set_init (&c->c2.event_set_max, flags);
2390 c->c2.event_set_owned = true;
2391}
2392
2393static void
2394do_close_event_set (struct context *c)
2395{
2396 if (c->c2.event_set && c->c2.event_set_owned)
2397 {
2398 event_free (c->c2.event_set);
2399 c->c2.event_set = NULL;
2400 c->c2.event_set_owned = false;
2401 }
2402}
2403
2404/*
2405 * Open and close --status file
2406 */
2407
2408static void
2409do_open_status_output (struct context *c)
2410{
2411 if (!c->c1.status_output)
2412 {
2413 c->c1.status_output = status_open (c->options.status_file,
2414 c->options.status_file_update_freq,
2415 -1,
2416 NULL,
2417 STATUS_OUTPUT_WRITE);
2418 c->c1.status_output_owned = true;
2419 }
2420}
2421
2422static void
2423do_close_status_output (struct context *c)
2424{
2425 if (!(c->sig->signal_received == SIGUSR1))
2426 {
2427 if (c->c1.status_output_owned && c->c1.status_output)
2428 {
2429 status_close (c->c1.status_output);
2430 c->c1.status_output = NULL;
2431 c->c1.status_output_owned = false;
2432 }
2433 }
2434}
2435
2436/*
2437 * Handle ifconfig-pool persistance object.
2438 */
2439static void
2440do_open_ifconfig_pool_persist (struct context *c)
2441{
2442#if P2MP_SERVER
2443 if (!c->c1.ifconfig_pool_persist && c->options.ifconfig_pool_persist_filename)
2444 {
2445 c->c1.ifconfig_pool_persist = ifconfig_pool_persist_init (c->options.ifconfig_pool_persist_filename,
2446 c->options.ifconfig_pool_persist_refresh_freq);
2447 c->c1.ifconfig_pool_persist_owned = true;
2448 }
2449#endif
2450}
2451
2452static void
2453do_close_ifconfig_pool_persist (struct context *c)
2454{
2455#if P2MP_SERVER
2456 if (!(c->sig->signal_received == SIGUSR1))
2457 {
2458 if (c->c1.ifconfig_pool_persist && c->c1.ifconfig_pool_persist_owned)
2459 {
2460 ifconfig_pool_persist_close (c->c1.ifconfig_pool_persist);
2461 c->c1.ifconfig_pool_persist = NULL;
2462 c->c1.ifconfig_pool_persist_owned = false;
2463 }
2464 }
2465#endif
2466}
2467
2468/*
2469 * Inherit environmental variables
2470 */
2471
2472static void
2473do_inherit_env (struct context *c, const struct env_set *src)
2474{
2a64816b
JY
2475 c->c2.es = env_set_create (NULL);
2476 c->c2.es_owned = true;
6fbf66fa
JY
2477 env_set_inherit (c->c2.es, src);
2478}
2479
2a64816b
JY
2480static void
2481do_env_set_destroy (struct context *c)
2482{
2483 if (c->c2.es && c->c2.es_owned)
2484 {
2485 env_set_destroy (c->c2.es);
2486 c->c2.es = NULL;
2487 c->c2.es_owned = false;
2488 }
2489}
2490
6fbf66fa
JY
2491/*
2492 * Fast I/O setup. Fast I/O is an optimization which only works
2493 * if all of the following are true:
2494 *
2495 * (1) The platform is not Windows
2496 * (2) --proto udp is enabled
2497 * (3) --shaper is disabled
2498 */
2499static void
2500do_setup_fast_io (struct context *c)
2501{
2502 if (c->options.fast_io)
2503 {
2504#ifdef WIN32
2505 msg (M_INFO, "NOTE: --fast-io is disabled since we are running on Windows");
2506#else
4e9a51d7 2507 if (c->options.ce.proto != PROTO_UDPv4)
6fbf66fa
JY
2508 msg (M_INFO, "NOTE: --fast-io is disabled since we are not using UDP");
2509 else
2510 {
0475d17e 2511#ifdef HAVE_GETTIMEOFDAY
6fbf66fa
JY
2512 if (c->options.shaper)
2513 msg (M_INFO, "NOTE: --fast-io is disabled since we are using --shaper");
2514 else
0475d17e 2515#endif
6fbf66fa
JY
2516 {
2517 c->c2.fast_io = true;
2518 }
2519 }
2520#endif
2521 }
2522}
2523
2524static void
2525do_signal_on_tls_errors (struct context *c)
2526{
2527#if defined(USE_CRYPTO) && defined(USE_SSL)
2528 if (c->options.tls_exit)
2529 c->c2.tls_exit_signal = SIGTERM;
2530 else
2531 c->c2.tls_exit_signal = SIGUSR1;
2532#endif
2533}
2534
3c7f2f55 2535#ifdef ENABLE_PLUGIN
6fbf66fa 2536
3c7f2f55 2537void
e1791bb1 2538init_plugins (struct context *c)
6fbf66fa 2539{
3c7f2f55 2540 if (c->options.plugin_list && !c->plugins)
e1791bb1
JY
2541 {
2542 c->plugins = plugin_list_init (c->options.plugin_list);
2543 c->plugins_owned = true;
2544 }
2545}
2546
2547void
2548open_plugins (struct context *c, const bool import_options, int init_point)
2549{
2550 if (c->plugins && c->plugins_owned)
6fbf66fa 2551 {
3c7f2f55
JY
2552 if (import_options)
2553 {
2554 struct plugin_return pr, config;
2555 plugin_return_init (&pr);
e1791bb1 2556 plugin_list_open (c->plugins, c->options.plugin_list, &pr, c->c2.es, init_point);
3c7f2f55
JY
2557 plugin_return_get_column (&pr, &config, "config");
2558 if (plugin_return_defined (&config))
2559 {
2560 int i;
2561 for (i = 0; i < config.n; ++i)
2562 {
2563 unsigned int option_types_found = 0;
2564 if (config.list[i] && config.list[i]->value)
90efcacb 2565 options_string_import (&c->options,
3c7f2f55
JY
2566 config.list[i]->value,
2567 D_IMPORT_ERRORS|M_OPTERR,
2568 OPT_P_DEFAULT & ~OPT_P_PLUGIN,
2569 &option_types_found,
2570 c->es);
2571 }
2572 }
2573 plugin_return_free (&pr);
2574 }
2575 else
2576 {
e1791bb1 2577 plugin_list_open (c->plugins, c->options.plugin_list, NULL, c->c2.es, init_point);
3c7f2f55 2578 }
6fbf66fa 2579 }
6fbf66fa
JY
2580}
2581
2582static void
2583do_close_plugins (struct context *c)
2584{
3c7f2f55 2585 if (c->plugins && c->plugins_owned && !(c->sig->signal_received == SIGUSR1))
6fbf66fa 2586 {
3c7f2f55
JY
2587 plugin_list_close (c->plugins);
2588 c->plugins = NULL;
2589 c->plugins_owned = false;
6fbf66fa 2590 }
6fbf66fa
JY
2591}
2592
3c7f2f55
JY
2593static void
2594do_inherit_plugins (struct context *c, const struct context *src)
2595{
2596 if (!c->plugins && src->plugins)
2597 {
2598 c->plugins = plugin_list_inherit (src->plugins);
2599 c->plugins_owned = true;
2600 }
2601}
2602
2603#endif
2604
6fbf66fa
JY
2605#ifdef ENABLE_MANAGEMENT
2606
2607static void
2608management_callback_status_p2p (void *arg, const int version, struct status_output *so)
2609{
2610 struct context *c = (struct context *) arg;
2611 print_status (c, so);
2612}
2613
2614void
2615management_show_net_callback (void *arg, const int msglevel)
2616{
2617#ifdef WIN32
2618 show_routes (msglevel);
2619 show_adapters (msglevel);
2620 msg (msglevel, "END");
2621#else
2622 msg (msglevel, "ERROR: Sorry, this command is currently only implemented on Windows");
2623#endif
2624}
2625
2626#endif
2627
2628void
2629init_management_callback_p2p (struct context *c)
2630{
2631#ifdef ENABLE_MANAGEMENT
2632 if (management)
2633 {
2634 struct management_callback cb;
2635 CLEAR (cb);
2636 cb.arg = c;
2637 cb.status = management_callback_status_p2p;
2638 cb.show_net = management_show_net_callback;
2639 management_set_callback (management, &cb);
2640 }
2641#endif
2642}
2643
2644#ifdef ENABLE_MANAGEMENT
2645
2646void
2647init_management (struct context *c)
2648{
2649 if (!management)
2650 management = management_init ();
2651}
2652
2653bool
2654open_management (struct context *c)
2655{
2656 /* initialize management layer */
2657 if (management)
2658 {
2659 if (c->options.management_addr)
2660 {
90efcacb
JY
2661 unsigned int flags = c->options.management_flags;
2662 if (c->options.mode == MODE_SERVER)
2663 flags |= MF_SERVER;
6fbf66fa
JY
2664 if (management_open (management,
2665 c->options.management_addr,
2666 c->options.management_port,
2667 c->options.management_user_pass,
6fbf66fa
JY
2668 c->options.management_log_history_cache,
2669 c->options.management_echo_buffer_size,
2670 c->options.management_state_buffer_size,
2c21891e 2671 c->options.management_write_peer_info_file,
90efcacb
JY
2672 c->options.remap_sigusr1,
2673 flags))
6fbf66fa
JY
2674 {
2675 management_set_state (management,
2676 OPENVPN_STATE_CONNECTING,
2677 NULL,
5ad84585 2678 (in_addr_t)0,
6fbf66fa
JY
2679 (in_addr_t)0);
2680 }
2681
2c21891e 2682 /* initial management hold, called early, before first context initialization */
6fbf66fa
JY
2683 do_hold (c);
2684 if (IS_SIG (c))
2685 {
2686 msg (M_WARN, "Signal received from management interface, exiting");
2687 return false;
2688 }
2689 }
2690 else
2691 close_management ();
2692 }
2693 return true;
2694}
2695
2696void
2697close_management (void)
2698{
2699 if (management)
2700 {
2701 management_close (management);
2702 management = NULL;
2703 }
2704}
2705
2706#endif
2707
2708
2709void
2710uninit_management_callback (void)
2711{
2712#ifdef ENABLE_MANAGEMENT
2713 if (management)
2714 {
2715 management_clear_callback (management);
2716 }
2717#endif
2718}
2719
2720/*
2721 * Initialize a tunnel instance, handle pre and post-init
2722 * signal settings.
2723 */
2724void
2725init_instance_handle_signals (struct context *c, const struct env_set *env, const unsigned int flags)
2726{
2727 pre_init_signal_catch ();
2728 init_instance (c, env, flags);
2729 post_init_signal_catch ();
b540a9e0
JY
2730
2731 /*
2732 * This is done so that signals thrown during
2733 * initialization can bring us back to
2734 * a management hold.
2735 */
2736 if (IS_SIG (c))
d5badcf1
JY
2737 {
2738 remap_signal (c);
2739 uninit_management_callback ();
2740 }
6fbf66fa
JY
2741}
2742
2743/*
2744 * Initialize a tunnel instance.
2745 */
2746void
2747init_instance (struct context *c, const struct env_set *env, const unsigned int flags)
2748{
2749 const struct options *options = &c->options;
2750 const bool child = (c->mode == CM_CHILD_TCP || c->mode == CM_CHILD_UDP);
2751 int link_socket_mode = LS_MODE_DEFAULT;
2752
2753 /* init garbage collection level */
2754 gc_init (&c->c2.gc);
2755
2756 /* signals caught here will abort */
2757 c->sig->signal_received = 0;
2758 c->sig->signal_text = NULL;
2759 c->sig->hard = false;
2760
4e9a51d7
JY
2761 /* map in current connection entry */
2762 next_connection_entry (c);
2763
6fbf66fa
JY
2764 /* link_socket_mode allows CM_CHILD_TCP
2765 instances to inherit acceptable fds
2766 from a top-level parent */
4e9a51d7 2767 if (c->options.ce.proto == PROTO_TCPv4_SERVER)
6fbf66fa
JY
2768 {
2769 if (c->mode == CM_TOP)
2770 link_socket_mode = LS_MODE_TCP_LISTEN;
2771 else if (c->mode == CM_CHILD_TCP)
2772 link_socket_mode = LS_MODE_TCP_ACCEPT_FROM;
2773 }
2774
2775 /* should we disable paging? */
2776 if (c->first_time && options->mlock)
2777 do_mlockall (true);
2778
2779 /* possible sleep or management hold if restart */
2780 if (c->mode == CM_P2P || c->mode == CM_TOP)
2781 {
2782 do_startup_pause (c);
2783 if (IS_SIG (c))
2784 goto sig;
2785 }
2786
92bbb061
JY
2787#if P2MP
2788 /* get passwords if undefined */
2789 if (auth_retry_get () == AR_INTERACT)
2790 init_query_passwords (c);
2791#endif
2792
6fbf66fa
JY
2793 /* initialize context level 2 --verb/--mute parms */
2794 init_verb_mute (c, IVM_LEVEL_2);
2795
2796 /* set error message delay for non-server modes */
2797 if (c->mode == CM_P2P)
2798 set_check_status_error_delay (P2P_ERROR_DELAY_MS);
2799
2800 /* warn about inconsistent options */
2801 if (c->mode == CM_P2P || c->mode == CM_TOP)
2802 do_option_warnings (c);
2803
2804 /* inherit environmental variables */
2805 if (env)
2806 do_inherit_env (c, env);
2807
3c7f2f55 2808#ifdef ENABLE_PLUGIN
6fbf66fa
JY
2809 /* initialize plugins */
2810 if (c->mode == CM_P2P || c->mode == CM_TOP)
e1791bb1 2811 open_plugins (c, false, OPENVPN_PLUGIN_INIT_PRE_DAEMON);
3c7f2f55 2812#endif
6fbf66fa
JY
2813
2814 /* should we enable fast I/O? */
2815 if (c->mode == CM_P2P || c->mode == CM_TOP)
2816 do_setup_fast_io (c);
2817
2818 /* should we throw a signal on TLS errors? */
2819 do_signal_on_tls_errors (c);
2820
2821 /* open --status file */
2822 if (c->mode == CM_P2P || c->mode == CM_TOP)
2823 do_open_status_output (c);
2824
2825 /* open --ifconfig-pool-persist file */
2826 if (c->mode == CM_TOP)
2827 do_open_ifconfig_pool_persist (c);
2828
2829#ifdef ENABLE_OCC
2830 /* reset OCC state */
2831 if (c->mode == CM_P2P || child)
2832 c->c2.occ_op = occ_reset_op ();
2833#endif
2834
2835 /* our wait-for-i/o objects, different for posix vs. win32 */
2836 if (c->mode == CM_P2P)
2837 do_event_set_init (c, SHAPER_DEFINED (&c->options));
2838 else if (c->mode == CM_CHILD_TCP)
2839 do_event_set_init (c, false);
2840
4e9a51d7
JY
2841 /* initialize HTTP or SOCKS proxy object at scope level 2 */
2842 init_proxy (c, 2);
2843
6fbf66fa
JY
2844 /* allocate our socket object */
2845 if (c->mode == CM_P2P || c->mode == CM_TOP || c->mode == CM_CHILD_TCP)
2846 do_link_socket_new (c);
2847
2848#ifdef ENABLE_FRAGMENT
2849 /* initialize internal fragmentation object */
2850 if (options->fragment && (c->mode == CM_P2P || child))
2851 c->c2.fragment = fragment_init (&c->c2.frame);
2852#endif
2853
2854 /* init crypto layer */
2855 {
2856 unsigned int crypto_flags = 0;
2857 if (c->mode == CM_TOP)
2858 crypto_flags = CF_INIT_TLS_AUTH_STANDALONE;
2859 else if (c->mode == CM_P2P)
2860 crypto_flags = CF_LOAD_PERSISTED_PACKET_ID | CF_INIT_TLS_MULTI;
2861 else if (child)
2862 crypto_flags = CF_INIT_TLS_MULTI;
2863 do_init_crypto (c, crypto_flags);
76a59eae 2864 if (IS_SIG (c) && !child)
6fbf66fa
JY
2865 goto sig;
2866 }
2867
2868#ifdef USE_LZO
2869 /* initialize LZO compression library. */
537073fd
JY
2870 if ((options->lzo & LZO_SELECTED) && (c->mode == CM_P2P || child))
2871 lzo_compress_init (&c->c2.lzo_compwork, options->lzo);
6fbf66fa
JY
2872#endif
2873
2874 /* initialize MTU variables */
2875 do_init_frame (c);
2876
2877 /* initialize TLS MTU variables */
2878 do_init_frame_tls (c);
2879
2880 /* init workspace buffers whose size is derived from frame size */
2881 if (c->mode == CM_P2P || c->mode == CM_CHILD_TCP)
2882 do_init_buffers (c);
2883
2884#ifdef ENABLE_FRAGMENT
2885 /* initialize internal fragmentation capability with known frame size */
2886 if (options->fragment && (c->mode == CM_P2P || child))
2887 do_init_fragment (c);
2888#endif
2889
2890 /* initialize dynamic MTU variable */
2891 do_init_mssfix (c);
2892
2893 /* bind the TCP/UDP socket */
2894 if (c->mode == CM_P2P || c->mode == CM_TOP || c->mode == CM_CHILD_TCP)
2895 do_init_socket_1 (c, link_socket_mode);
2896
2897 /* initialize tun/tap device object,
2898 open tun/tap device, ifconfig, run up script, etc. */
2899 if (!(options->up_delay || PULL_DEFINED (options)) && (c->mode == CM_P2P || c->mode == CM_TOP))
2900 c->c2.did_open_tun = do_open_tun (c);
2901
2902 /* print MTU info */
2903 do_print_data_channel_mtu_parms (c);
2904
2905#ifdef ENABLE_OCC
2906 /* get local and remote options compatibility strings */
2907 if (c->mode == CM_P2P || child)
2908 do_compute_occ_strings (c);
2909#endif
2910
2911 /* initialize output speed limiter */
2912 if (c->mode == CM_P2P)
2913 do_init_traffic_shaper (c);
2914
2915 /* do one-time inits, and possibily become a daemon here */
2916 do_init_first_time (c);
2917
e1791bb1
JY
2918#ifdef ENABLE_PLUGIN
2919 /* initialize plugins */
2920 if (c->mode == CM_P2P || c->mode == CM_TOP)
2921 open_plugins (c, false, OPENVPN_PLUGIN_INIT_POST_DAEMON);
2922#endif
2923
6fbf66fa
JY
2924 /*
2925 * Actually do UID/GID downgrade, and chroot, if requested.
2926 * May be delayed by --client, --pull, or --up-delay.
2927 */
2928 do_uid_gid_chroot (c, c->c2.did_open_tun);
2929
2930 /* finalize the TCP/UDP socket */
2931 if (c->mode == CM_P2P || c->mode == CM_TOP || c->mode == CM_CHILD_TCP)
2932 do_init_socket_2 (c);
2933
2934 /* initialize timers */
2935 if (c->mode == CM_P2P || child)
2936 do_init_timers (c, false);
2937
e1791bb1
JY
2938#ifdef ENABLE_PLUGIN
2939 /* initialize plugins */
2940 if (c->mode == CM_P2P || c->mode == CM_TOP)
2941 open_plugins (c, false, OPENVPN_PLUGIN_INIT_POST_UID_CHANGE);
2942#endif
2943
6add6b2f
JY
2944#if PORT_SHARE
2945 /* share OpenVPN port with foreign (such as HTTPS) server */
2946 if (c->first_time && (c->mode == CM_P2P || c->mode == CM_TOP))
2947 init_port_share (c);
2948#endif
2949
47ae8457
JY
2950#ifdef ENABLE_PF
2951 if (child)
2952 pf_init_context (c);
2953#endif
2954
6fbf66fa
JY
2955 /* Check for signals */
2956 if (IS_SIG (c))
2957 goto sig;
2958
2959 return;
2960
2961 sig:
8d33c060
JY
2962 if (!c->sig->signal_text)
2963 c->sig->signal_text = "init_instance";
6fbf66fa
JY
2964 close_context (c, -1, flags);
2965 return;
2966}
2967
2968/*
2969 * Close a tunnel instance.
2970 */
2971void
2972close_instance (struct context *c)
2973{
2974 /* close event objects */
2975 do_close_event_set (c);
2976
2977 if (c->mode == CM_P2P
2978 || c->mode == CM_CHILD_TCP
2979 || c->mode == CM_CHILD_UDP
2980 || c->mode == CM_TOP)
2981 {
2982 /* if xinetd/inetd mode, don't allow restart */
2983 do_close_check_if_restart_permitted (c);
2984
2985#ifdef USE_LZO
537073fd 2986 if (lzo_defined (&c->c2.lzo_compwork))
6fbf66fa
JY
2987 lzo_compress_uninit (&c->c2.lzo_compwork);
2988#endif
2989
2990 /* free buffers */
2991 do_close_free_buf (c);
2992
2993 /* close TLS */
2994 do_close_tls (c);
2995
2996 /* free key schedules */
2997 do_close_free_key_schedule (c, (c->mode == CM_P2P || c->mode == CM_TOP));
2998
2999 /* close TCP/UDP connection */
3000 do_close_link_socket (c);
3001
3002 /* close TUN/TAP device */
3003 do_close_tun (c, false);
3004
90efcacb
JY
3005#ifdef MANAGEMENT_DEF_AUTH
3006 if (management)
3007 management_notify_client_close (management, &c->c2.mda_context, NULL);
3008#endif
3009
47ae8457
JY
3010#ifdef ENABLE_PF
3011 pf_destroy_context (&c->c2.pf);
3012#endif
3013
3c7f2f55 3014#ifdef ENABLE_PLUGIN
6fbf66fa
JY
3015 /* call plugin close functions and unload */
3016 do_close_plugins (c);
3c7f2f55 3017#endif
6fbf66fa
JY
3018
3019 /* close packet-id persistance file */
3020 do_close_packet_id (c);
3021
3022 /* close --status file */
3023 do_close_status_output (c);
3024
3025#ifdef ENABLE_FRAGMENT
3026 /* close fragmentation handler */
3027 do_close_fragment (c);
3028#endif
3029
3030 /* close --ifconfig-pool-persist obj */
3031 do_close_ifconfig_pool_persist (c);
3032
2a64816b
JY
3033 /* free up environmental variable store */
3034 do_env_set_destroy (c);
3035
4e9a51d7
JY
3036 /* close HTTP or SOCKS proxy */
3037 uninit_proxy (c);
3038
6fbf66fa
JY
3039 /* garbage collect */
3040 gc_free (&c->c2.gc);
3041 }
3042}
3043
3044void
3045inherit_context_child (struct context *dest,
3046 const struct context *src)
3047{
3048 CLEAR (*dest);
3049
4e9a51d7 3050 switch (src->options.ce.proto)
6fbf66fa
JY
3051 {
3052 case PROTO_UDPv4:
3053 dest->mode = CM_CHILD_UDP;
3054 break;
3055 case PROTO_TCPv4_SERVER:
3056 dest->mode = CM_CHILD_TCP;
3057 break;
3058 default:
3059 ASSERT (0);
3060 }
3061
6fbf66fa
JY
3062 dest->gc = gc_new ();
3063
3064 ALLOC_OBJ_CLEAR_GC (dest->sig, struct signal_info, &dest->gc);
3065
3066 /* c1 init */
3067 packet_id_persist_init (&dest->c1.pid_persist);
3068
3069#ifdef USE_CRYPTO
3070 dest->c1.ks.key_type = src->c1.ks.key_type;
3071#ifdef USE_SSL
3072 /* inherit SSL context */
3073 dest->c1.ks.ssl_ctx = src->c1.ks.ssl_ctx;
3074 dest->c1.ks.tls_auth_key = src->c1.ks.tls_auth_key;
3075#endif
3076#endif
3077
3078 /* options */
3079 dest->options = src->options;
3080 options_detach (&dest->options);
3081
3082 if (dest->mode == CM_CHILD_TCP)
3083 {
3084 /*
3085 * The CM_TOP context does the socket listen(),
3086 * and the CM_CHILD_TCP context does the accept().
3087 */
3088 dest->c2.accept_from = src->c2.link_socket;
3089 }
3090
3c7f2f55 3091#ifdef ENABLE_PLUGIN
6fbf66fa 3092 /* inherit plugins */
3c7f2f55
JY
3093 do_inherit_plugins (dest, src);
3094#endif
6fbf66fa
JY
3095
3096 /* context init */
79df31c8 3097 init_instance (dest, src->c2.es, CC_NO_CLOSE | CC_USR1_TO_HUP);
6fbf66fa
JY
3098 if (IS_SIG (dest))
3099 return;
3100
3101 /* inherit tun/tap interface object */
3102 dest->c1.tuntap = src->c1.tuntap;
3103
3104 /* UDP inherits some extra things which TCP does not */
3105 if (dest->mode == CM_CHILD_UDP)
3106 {
3107 /* inherit buffers */
3108 dest->c2.buffers = src->c2.buffers;
3109
3110 /* inherit parent link_socket and tuntap */
3111 dest->c2.link_socket = src->c2.link_socket;
3112
3113 ALLOC_OBJ_GC (dest->c2.link_socket_info, struct link_socket_info, &dest->gc);
3114 *dest->c2.link_socket_info = src->c2.link_socket->info;
3115
3116 /* locally override some link_socket_info fields */
3117 dest->c2.link_socket_info->lsa = &dest->c1.link_socket_addr;
3118 dest->c2.link_socket_info->connection_established = false;
3119 }
3120}
3121
3122void
3123inherit_context_top (struct context *dest,
3124 const struct context *src)
3125{
3126 /* copy parent */
3127 *dest = *src;
3128
3129 /*
3130 * CM_TOP_CLONE will prevent close_instance from freeing or closing
3131 * resources owned by the parent.
3132 *
3133 * Also note that CM_TOP_CLONE context objects are
3134 * closed by multi_top_free in multi.c.
3135 */
3136 dest->mode = CM_TOP_CLONE;
3137
3138 dest->first_time = false;
92bbb061 3139 dest->c0 = NULL;
6fbf66fa
JY
3140
3141 options_detach (&dest->options);
3142 gc_detach (&dest->gc);
3143 gc_detach (&dest->c2.gc);
3144
3c7f2f55
JY
3145 /* detach plugins */
3146 dest->plugins_owned = false;
3147
6fbf66fa
JY
3148#if defined(USE_CRYPTO) && defined(USE_SSL)
3149 dest->c2.tls_multi = NULL;
3150#endif
3151
3c7f2f55 3152 /* detach c1 ownership */
6fbf66fa
JY
3153 dest->c1.tuntap_owned = false;
3154 dest->c1.status_output_owned = false;
3155#if P2MP_SERVER
3156 dest->c1.ifconfig_pool_persist_owned = false;
3157#endif
3c7f2f55
JY
3158
3159 /* detach c2 ownership */
6fbf66fa
JY
3160 dest->c2.event_set_owned = false;
3161 dest->c2.link_socket_owned = false;
3162 dest->c2.buffers_owned = false;
2a64816b 3163 dest->c2.es_owned = false;
6fbf66fa
JY
3164
3165 dest->c2.event_set = NULL;
4e9a51d7 3166 if (src->options.ce.proto == PROTO_UDPv4)
6fbf66fa
JY
3167 do_event_set_init (dest, false);
3168}
3169
3170void
3171close_context (struct context *c, int sig, unsigned int flags)
3172{
79df31c8
JY
3173 ASSERT (c);
3174 ASSERT (c->sig);
3175
6fbf66fa
JY
3176 if (sig >= 0)
3177 c->sig->signal_received = sig;
3178
3179 if (c->sig->signal_received == SIGUSR1)
3180 {
3181 if ((flags & CC_USR1_TO_HUP)
3182 || (c->sig->hard && (flags & CC_HARD_USR1_TO_HUP)))
3183 c->sig->signal_received = SIGHUP;
3184 }
3185
79df31c8
JY
3186 if (!(flags & CC_NO_CLOSE))
3187 close_instance (c);
6fbf66fa
JY
3188
3189 if (flags & CC_GC_FREE)
3190 context_gc_free (c);
3191}
3192
3193#ifdef USE_CRYPTO
3194
3195static void
3196test_malloc (void)
3197{
3198 int i, j;
3199 msg (M_INFO, "Multithreaded malloc test...");
3200 for (i = 0; i < 25; ++i)
3201 {
3202 struct gc_arena gc = gc_new ();
3203 const int limit = get_random () & 0x03FF;
3204 for (j = 0; j < limit; ++j)
3205 {
3206 gc_malloc (get_random () & 0x03FF, false, &gc);
3207 }
3208 gc_free (&gc);
3209 }
3210}
3211
3212/*
3213 * Do a loopback test
3214 * on the crypto subsystem.
3215 */
3216static void *
3217test_crypto_thread (void *arg)
3218{
3219 struct context *c = (struct context *) arg;
3220 const struct options *options = &c->options;
3221#if defined(USE_PTHREAD)
3222 struct context *child = NULL;
3223 openvpn_thread_t child_id = 0;
3224#endif
3225
3226 ASSERT (options->test_crypto);
3227 init_verb_mute (c, IVM_LEVEL_1);
3228 context_init_1 (c);
3229 do_init_crypto_static (c, 0);
3230
3231#if defined(USE_PTHREAD)
3232 {
3233 if (c->first_time && options->n_threads > 1)
3234 {
3235 if (options->n_threads > 2)
3236 msg (M_FATAL, "ERROR: --test-crypto option only works with --threads set to 1 or 2");
3237 openvpn_thread_init ();
3238 ALLOC_OBJ (child, struct context);
3239 context_clear (child);
3240 child->options = *options;
3241 options_detach (&child->options);
3242 child->first_time = false;
3243 child_id = openvpn_thread_create (test_crypto_thread, (void *) child);
3244 }
3245 }
3246#endif
3247 frame_finalize_options (c, options);
3248
3249#if defined(USE_PTHREAD)
3250 if (options->n_threads == 2)
3251 test_malloc ();
3252#endif
3253
3254 test_crypto (&c->c2.crypto_options, &c->c2.frame);
3255
3256 key_schedule_free (&c->c1.ks, true);
3257 packet_id_free (&c->c2.packet_id);
3258
3259#if defined(USE_PTHREAD)
3260 if (c->first_time && options->n_threads > 1)
3261 openvpn_thread_join (child_id);
3262 if (child)
3263 free (child);
3264#endif
3265 context_gc_free (c);
3266 return NULL;
3267}
3268
3269#endif
3270
3271bool
3272do_test_crypto (const struct options *o)
3273{
3274#ifdef USE_CRYPTO
3275 if (o->test_crypto)
3276 {
3277 struct context c;
3278
3279 /* print version number */
3280 msg (M_INFO, "%s", title_string);
3281
3c7f2f55 3282 context_clear (&c);
6fbf66fa
JY
3283 c.options = *o;
3284 options_detach (&c.options);
3285 c.first_time = true;
3286 test_crypto_thread ((void *) &c);
3287 return true;
3288 }
3289#endif
3290 return false;
3291}