big svn cleanup
[anytun.git] / src / openvpn / init.c
blob9bd2960483bbdcb6f0f55df912afcf630037f845
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.
8 * Copyright (C) 2002-2005 OpenVPN Solutions LLC <info@openvpn.net>
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.
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.
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
25 #ifdef WIN32
26 #include "config-win32.h"
27 #else
28 #include "config.h"
29 #endif
31 #include "syshead.h"
33 #include "win32.h"
34 #include "init.h"
35 #include "sig.h"
36 #include "occ.h"
37 #include "list.h"
38 #include "otime.h"
39 #include "pool.h"
40 #include "gremlin.h"
42 #include "memdbg.h"
44 #include "occ-inline.h"
47 * Crypto initialization flags
49 #define CF_LOAD_PERSISTED_PACKET_ID (1<<0)
50 #define CF_INIT_TLS_MULTI (1<<1)
51 #define CF_INIT_TLS_AUTH_STANDALONE (1<<2)
53 static void do_init_first_time (struct context *c);
55 void
56 context_clear (struct context *c)
58 CLEAR (*c);
61 void
62 context_clear_1 (struct context *c)
64 CLEAR (c->c1);
67 void
68 context_clear_2 (struct context *c)
70 CLEAR (c->c2);
73 void
74 context_clear_all_except_first_time (struct context *c)
76 const bool first_time_save = c->first_time;
77 context_clear (c);
78 c->first_time = first_time_save;
82 * Initialize and possibly randomize remote list.
84 static void
85 init_remote_list (struct context *c)
87 c->c1.remote_list = NULL;
89 if (c->options.remote_list)
91 struct remote_list *l;
92 ALLOC_OBJ_GC (c->c1.remote_list, struct remote_list, &c->gc);
93 l = c->c1.remote_list;
94 *l = *c->options.remote_list;
95 l->current = -1;
96 if (c->options.remote_random)
97 remote_list_randomize (l);
102 * Query for private key and auth-user-pass username/passwords
104 static void
105 init_query_passwords (struct context *c)
107 #if defined(USE_CRYPTO) && defined(USE_SSL)
108 /* Certificate password input */
109 if (c->options.key_pass_file)
110 pem_password_setup (c->options.key_pass_file);
111 #endif
113 #if P2MP
114 /* Auth user/pass input */
116 if (c->options.auth_user_pass_file)
117 auth_user_pass_setup (c->options.auth_user_pass_file);
119 #endif
122 void
123 context_init_1 (struct context *c)
125 context_clear_1 (c);
127 packet_id_persist_init (&c->c1.pid_persist);
128 init_remote_list (c);
130 init_query_passwords (c);
132 #ifdef ENABLE_HTTP_PROXY
133 if (c->options.http_proxy_options)
135 /* Possible HTTP proxy user/pass input */
136 c->c1.http_proxy = new_http_proxy (c->options.http_proxy_options,
137 &c->gc);
139 #endif
141 #ifdef ENABLE_SOCKS
142 if (c->options.socks_proxy_server)
144 c->c1.socks_proxy = new_socks_proxy (c->options.socks_proxy_server,
145 c->options.socks_proxy_port,
146 c->options.socks_proxy_retry,
147 &c->gc);
149 #endif
152 void
153 context_gc_free (struct context *c)
155 gc_free (&c->c2.gc);
156 gc_free (&c->options.gc);
157 gc_free (&c->gc);
160 bool
161 init_static (void)
163 #if defined(USE_CRYPTO) && defined(DMALLOC)
164 openssl_dmalloc_init ();
165 #endif
167 init_random_seed (); /* init random() function, only used as
168 source for weak random numbers */
169 error_reset (); /* initialize error.c */
170 reset_check_status (); /* initialize status check code in socket.c */
172 #ifdef WIN32
173 init_win32 ();
174 #endif
176 #ifdef OPENVPN_DEBUG_COMMAND_LINE
178 int i;
179 for (i = 0; i < argc; ++i)
180 msg (M_INFO, "argv[%d] = '%s'", i, argv[i]);
182 #endif
184 update_time ();
186 #ifdef USE_CRYPTO
187 init_ssl_lib ();
189 /* init PRNG used for IV generation */
190 /* When forking, copy this to more places in the code to avoid fork
191 random-state predictability */
192 prng_init ();
193 #endif
195 #ifdef PID_TEST
196 packet_id_interactive_test (); /* test the sequence number code */
197 return false;
198 #endif
200 #ifdef SCHEDULE_TEST
201 schedule_test ();
202 return false;
203 #endif
205 #ifdef LIST_TEST
206 list_test ();
207 return false;
208 #endif
210 #ifdef IFCONFIG_POOL_TEST
211 ifconfig_pool_test (0x0A010004, 0x0A0100FF);
212 return false;
213 #endif
215 #ifdef CHARACTER_CLASS_DEBUG
216 character_class_debug ();
217 return false;
218 #endif
220 #ifdef EXTRACT_X509_FIELD_TEST
221 extract_x509_field_test ();
222 return false;
223 #endif
225 return true;
228 void
229 uninit_static (void)
231 openvpn_thread_cleanup ();
233 #ifdef USE_CRYPTO
234 free_ssl_lib ();
235 #endif
237 #if defined(MEASURE_TLS_HANDSHAKE_STATS) && defined(USE_CRYPTO) && defined(USE_SSL)
238 show_tls_performance_stats ();
239 #endif
242 void
243 init_verb_mute (struct context *c, unsigned int flags)
245 if (flags & IVM_LEVEL_1)
247 /* set verbosity and mute levels */
248 set_check_status (D_LINK_ERRORS, D_READ_WRITE);
249 set_debug_level (c->options.verbosity, SDL_CONSTRAIN);
250 set_mute_cutoff (c->options.mute);
253 /* special D_LOG_RW mode */
254 if (flags & IVM_LEVEL_2)
255 c->c2.log_rw = (check_debug_level (D_LOG_RW) && !check_debug_level (D_LOG_RW + 1));
259 * Possibly set --dev based on --dev-node.
260 * For example, if --dev-node /tmp/foo/tun, and --dev undefined,
261 * set --dev to tun.
263 void
264 init_options_dev (struct options *options)
266 if (!options->dev)
267 options->dev = dev_component_in_dev_node (options->dev_node);
270 bool
271 print_openssl_info (const struct options *options)
274 * OpenSSL info print mode?
276 #ifdef USE_CRYPTO
277 if (options->show_ciphers || options->show_digests || options->show_engines
278 #ifdef USE_SSL
279 || options->show_tls_ciphers
280 #endif
283 if (options->show_ciphers)
284 show_available_ciphers ();
285 if (options->show_digests)
286 show_available_digests ();
287 if (options->show_engines)
288 show_available_engines ();
289 #ifdef USE_SSL
290 if (options->show_tls_ciphers)
291 show_available_tls_ciphers ();
292 #endif
293 return true;
295 #endif
296 return false;
300 * Static pre-shared key generation mode?
302 bool
303 do_genkey (const struct options * options)
305 #ifdef USE_CRYPTO
306 if (options->genkey)
308 int nbits_written;
310 notnull (options->shared_secret_file,
311 "shared secret output file (--secret)");
313 if (options->mlock) /* should we disable paging? */
314 do_mlockall (true);
316 nbits_written = write_key_file (2, options->shared_secret_file);
318 msg (D_GENKEY | M_NOPREFIX,
319 "Randomly generated %d bit key written to %s", nbits_written,
320 options->shared_secret_file);
321 return true;
323 #endif
324 return false;
328 * Persistent TUN/TAP device management mode?
330 bool
331 do_persist_tuntap (const struct options *options)
333 #ifdef TUNSETPERSIST
334 if (options->persist_config)
336 /* sanity check on options for --mktun or --rmtun */
337 notnull (options->dev, "TUN/TAP device (--dev)");
338 if (options->remote_list || options->ifconfig_local
339 || options->ifconfig_remote_netmask
340 #ifdef USE_CRYPTO
341 || options->shared_secret_file
342 #ifdef USE_SSL
343 || options->tls_server || options->tls_client
344 #endif
345 #endif
347 msg (M_FATAL|M_OPTERR,
348 "options --mktun or --rmtun should only be used together with --dev");
349 tuncfg (options->dev, options->dev_type, options->dev_node,
350 options->tun_ipv6, options->persist_mode);
351 return true;
353 #endif
354 return false;
358 * Should we become a daemon?
359 * Return true if we did it.
361 static bool
362 possibly_become_daemon (const struct options *options, const bool first_time)
364 bool ret = false;
365 if (first_time && options->daemon)
367 ASSERT (!options->inetd);
368 if (daemon (options->cd_dir != NULL, options->log) < 0)
369 msg (M_ERR, "daemon() failed");
370 if (options->log)
371 set_std_files_to_null (true);
372 ret = true;
374 return ret;
378 * Actually do UID/GID downgrade, and chroot, if requested.
380 static void
381 do_uid_gid_chroot (struct context *c, bool no_delay)
383 static const char why_not[] = "will be delayed because of --client, --pull, or --up-delay";
384 struct context_0 *c0 = c->c0;
386 if (c->first_time && c0 && !c0->uid_gid_set)
388 /* chroot if requested */
389 if (c->options.chroot_dir)
391 if (no_delay)
392 do_chroot (c->options.chroot_dir);
393 else
394 msg (M_INFO, "NOTE: chroot %s", why_not);
397 /* set user and/or group that we want to setuid/setgid to */
398 if (no_delay)
400 set_group (&c0->group_state);
401 set_user (&c0->user_state);
402 c0->uid_gid_set = true;
404 else if (c0->uid_gid_specified)
406 msg (M_INFO, "NOTE: UID/GID downgrade %s", why_not);
412 * Return common name in a way that is formatted for
413 * prepending to msg() output.
415 const char *
416 format_common_name (struct context *c, struct gc_arena *gc)
418 struct buffer out = alloc_buf_gc (256, gc);
419 #if defined(USE_CRYPTO) && defined(USE_SSL)
420 if (c->c2.tls_multi)
422 buf_printf (&out, "[%s] ", tls_common_name (c->c2.tls_multi, false));
424 #endif
425 return BSTR (&out);
428 void
429 pre_setup (const struct options *options)
431 #ifdef WIN32
432 if (options->exit_event_name)
434 win32_signal_open (&win32_signal,
435 WSO_FORCE_SERVICE,
436 options->exit_event_name,
437 options->exit_event_initial_state);
439 else
441 win32_signal_open (&win32_signal,
442 WSO_FORCE_CONSOLE,
443 NULL,
444 false);
446 /* put a title on the top window bar */
447 if (win32_signal.mode == WSO_MODE_CONSOLE)
449 window_title_save (&window_title);
450 window_title_generate (options->config);
453 #endif
456 void
457 reset_coarse_timers (struct context *c)
459 c->c2.coarse_timer_wakeup = 0;
463 * Initialize timers
465 static void
466 do_init_timers (struct context *c, bool deferred)
468 update_time ();
469 reset_coarse_timers (c);
471 /* initialize inactivity timeout */
472 if (c->options.inactivity_timeout)
473 event_timeout_init (&c->c2.inactivity_interval, c->options.inactivity_timeout, now);
475 /* initialize pings */
477 if (c->options.ping_send_timeout)
478 event_timeout_init (&c->c2.ping_send_interval, c->options.ping_send_timeout, 0);
480 if (c->options.ping_rec_timeout)
481 event_timeout_init (&c->c2.ping_rec_interval, c->options.ping_rec_timeout, now);
483 if (!deferred)
485 /* initialize connection establishment timer */
486 event_timeout_init (&c->c2.wait_for_connect, 1, now);
488 #ifdef ENABLE_OCC
489 /* initialize occ timers */
491 if (c->options.occ
492 && !TLS_MODE (c)
493 && c->c2.options_string_local && c->c2.options_string_remote)
494 event_timeout_init (&c->c2.occ_interval, OCC_INTERVAL_SECONDS, now);
496 if (c->options.mtu_test)
497 event_timeout_init (&c->c2.occ_mtu_load_test_interval, OCC_MTU_LOAD_INTERVAL_SECONDS, now);
498 #endif
500 /* initialize packet_id persistence timer */
501 #ifdef USE_CRYPTO
502 if (c->options.packet_id_file)
503 event_timeout_init (&c->c2.packet_id_persist_interval, 60, now);
504 #endif
506 #if defined(USE_CRYPTO) && defined(USE_SSL)
507 /* initialize tmp_int optimization that limits the number of times we call
508 tls_multi_process in the main event loop */
509 interval_init (&c->c2.tmp_int, TLS_MULTI_HORIZON, TLS_MULTI_REFRESH);
510 #endif
515 * Initialize traffic shaper.
517 static void
518 do_init_traffic_shaper (struct context *c)
520 #ifdef HAVE_GETTIMEOFDAY
521 /* initialize traffic shaper (i.e. transmit bandwidth limiter) */
522 if (c->options.shaper)
524 shaper_init (&c->c2.shaper, c->options.shaper);
525 shaper_msg (&c->c2.shaper);
527 #endif
531 * Allocate a route list structure if at least one
532 * --route option was specified.
534 static void
535 do_alloc_route_list (struct context *c)
537 if (c->options.routes && !c->c1.route_list)
538 c->c1.route_list = new_route_list (&c->gc);
543 * Initialize the route list, resolving any DNS names in route
544 * options and saving routes in the environment.
546 static void
547 do_init_route_list (const struct options *options,
548 struct route_list *route_list,
549 const struct link_socket_info *link_socket_info,
550 bool fatal,
551 struct env_set *es)
553 const char *gw = NULL;
554 int dev = dev_type_enum (options->dev, options->dev_type);
556 if (dev == DEV_TYPE_TUN)
557 gw = options->ifconfig_remote_netmask;
558 if (options->route_default_gateway)
559 gw = options->route_default_gateway;
561 if (!init_route_list (route_list,
562 options->routes,
564 link_socket_current_remote (link_socket_info),
565 es))
567 if (fatal)
568 openvpn_exit (OPENVPN_EXIT_STATUS_ERROR); /* exit point */
570 else
572 /* copy routes to environment */
573 setenv_routes (es, route_list);
578 * Called after all initialization has been completed.
580 void
581 initialization_sequence_completed (struct context *c, const unsigned int flags)
583 static const char message[] = "Initialization Sequence Completed";
585 /* If we delayed UID/GID downgrade or chroot, do it now */
586 do_uid_gid_chroot (c, true);
588 /* Test if errors */
589 if (flags & ISC_ERRORS)
590 #ifdef WIN32
591 msg (M_INFO, "%s With Errors ( see http://openvpn.net/faq.html#dhcpclientserv )", message);
592 #else
593 msg (M_INFO, "%s With Errors", message);
594 #endif
595 else
596 msg (M_INFO, "%s", message);
598 /* Flag remote_list that we initialized */
599 if ((flags & (ISC_ERRORS|ISC_SERVER)) == 0 && c->c1.remote_list && c->c1.remote_list->len > 1)
600 c->c1.remote_list->no_advance = true;
602 #ifdef ENABLE_MANAGEMENT
603 /* Tell management interface that we initialized */
604 if (management)
606 in_addr_t tun_local = 0;
607 const char *detail = "SUCCESS";
608 if (c->c1.tuntap)
609 tun_local = c->c1.tuntap->local;
610 if (flags & ISC_ERRORS)
611 detail = "ERROR";
612 management_set_state (management,
613 OPENVPN_STATE_CONNECTED,
614 detail,
615 tun_local);
616 if (tun_local)
617 management_post_tunnel_open (management, tun_local);
619 #endif
624 * Possibly add routes and/or call route-up script
625 * based on options.
627 void
628 do_route (const struct options *options,
629 struct route_list *route_list,
630 const struct tuntap *tt,
631 const struct plugin_list *plugins,
632 struct env_set *es)
634 if (!options->route_noexec && route_list)
635 add_routes (route_list, tt, ROUTE_OPTION_FLAGS (options), es);
637 if (plugin_defined (plugins, OPENVPN_PLUGIN_ROUTE_UP))
639 if (plugin_call (plugins, OPENVPN_PLUGIN_ROUTE_UP, NULL, es))
640 msg (M_WARN, "WARNING: route-up plugin call failed");
643 if (options->route_script)
645 setenv_str (es, "script_type", "route-up");
646 system_check (options->route_script, es, S_SCRIPT, "Route script failed");
649 #ifdef WIN32
650 if (options->show_net_up)
652 show_routes (M_INFO|M_NOPREFIX);
653 show_adapters (M_INFO|M_NOPREFIX);
655 else if (check_debug_level (D_SHOW_NET))
657 show_routes (D_SHOW_NET|M_NOPREFIX);
658 show_adapters (D_SHOW_NET|M_NOPREFIX);
660 #endif
664 * Save current pulled options string in the c1 context store, so we can
665 * compare against it after possible future restarts.
667 #if P2MP
668 static void
669 save_pulled_options_string (struct context *c, const char *newstring)
671 if (c->c1.pulled_options_string_save)
672 free (c->c1.pulled_options_string_save);
674 c->c1.pulled_options_string_save = NULL;
676 if (newstring)
677 c->c1.pulled_options_string_save = string_alloc (newstring, NULL);
679 #endif
682 * initialize tun/tap device object
684 static void
685 do_init_tun (struct context *c)
687 c->c1.tuntap = init_tun (c->options.dev,
688 c->options.dev_type,
689 c->options.ifconfig_local,
690 c->options.ifconfig_remote_netmask,
691 addr_host (&c->c1.link_socket_addr.local),
692 addr_host (&c->c1.link_socket_addr.remote),
693 !c->options.ifconfig_nowarn,
694 c->c2.es);
696 init_tun_post (c->c1.tuntap,
697 &c->c2.frame,
698 &c->options.tuntap_options);
700 c->c1.tuntap_owned = true;
704 * Open tun/tap device, ifconfig, call up script, etc.
707 static bool
708 do_open_tun (struct context *c)
710 struct gc_arena gc = gc_new ();
711 bool ret = false;
713 c->c2.ipv4_tun = (!c->options.tun_ipv6
714 && is_dev_type (c->options.dev, c->options.dev_type, "tun"));
716 if (!c->c1.tuntap)
718 /* initialize (but do not open) tun/tap object */
719 do_init_tun (c);
721 /* allocate route list structure */
722 do_alloc_route_list (c);
724 /* parse and resolve the route option list */
725 if (c->c1.route_list && c->c2.link_socket)
726 do_init_route_list (&c->options, c->c1.route_list, &c->c2.link_socket->info, false, c->c2.es);
728 /* do ifconfig */
729 if (!c->options.ifconfig_noexec
730 && ifconfig_order () == IFCONFIG_BEFORE_TUN_OPEN)
732 /* guess actual tun/tap unit number that will be returned
733 by open_tun */
734 const char *guess = guess_tuntap_dev (c->options.dev,
735 c->options.dev_type,
736 c->options.dev_node,
737 &gc);
738 do_ifconfig (c->c1.tuntap, guess, TUN_MTU_SIZE (&c->c2.frame), c->c2.es);
741 /* open the tun device */
742 open_tun (c->options.dev, c->options.dev_type, c->options.dev_node,
743 c->options.tun_ipv6, c->c1.tuntap);
745 /* do ifconfig */
746 if (!c->options.ifconfig_noexec
747 && ifconfig_order () == IFCONFIG_AFTER_TUN_OPEN)
749 do_ifconfig (c->c1.tuntap, c->c1.tuntap->actual_name, TUN_MTU_SIZE (&c->c2.frame), c->c2.es);
752 /* run the up script */
753 run_up_down (c->options.up_script,
754 c->c1.plugins,
755 OPENVPN_PLUGIN_UP,
756 c->c1.tuntap->actual_name,
757 TUN_MTU_SIZE (&c->c2.frame),
758 EXPANDED_SIZE (&c->c2.frame),
759 print_in_addr_t (c->c1.tuntap->local, IA_EMPTY_IF_UNDEF, &gc),
760 print_in_addr_t (c->c1.tuntap->remote_netmask, IA_EMPTY_IF_UNDEF, &gc),
761 "init",
762 NULL,
763 "up",
764 c->c2.es);
766 /* possibly add routes */
767 if (!c->options.route_delay_defined)
768 do_route (&c->options, c->c1.route_list, c->c1.tuntap, c->c1.plugins, c->c2.es);
771 * Did tun/tap driver give us an MTU?
773 if (c->c1.tuntap->post_open_mtu)
774 frame_set_mtu_dynamic (&c->c2.frame,
775 c->c1.tuntap->post_open_mtu,
776 SET_MTU_TUN | SET_MTU_UPPER_BOUND);
778 ret = true;
780 else
782 msg (M_INFO, "Preserving previous TUN/TAP instance: %s",
783 c->c1.tuntap->actual_name);
785 /* run the up script if user specified --up-restart */
786 if (c->options.up_restart)
787 run_up_down (c->options.up_script,
788 c->c1.plugins,
789 OPENVPN_PLUGIN_UP,
790 c->c1.tuntap->actual_name,
791 TUN_MTU_SIZE (&c->c2.frame),
792 EXPANDED_SIZE (&c->c2.frame),
793 print_in_addr_t (c->c1.tuntap->local, IA_EMPTY_IF_UNDEF, &gc),
794 print_in_addr_t (c->c1.tuntap->remote_netmask, IA_EMPTY_IF_UNDEF, &gc),
795 "restart",
796 NULL,
797 "up",
798 c->c2.es);
800 gc_free (&gc);
801 return ret;
805 * Close TUN/TAP device
808 static void
809 do_close_tun_simple (struct context *c)
811 msg (D_CLOSE, "Closing TUN/TAP interface");
812 close_tun (c->c1.tuntap);
813 c->c1.tuntap = NULL;
814 c->c1.tuntap_owned = false;
815 #if P2MP
816 save_pulled_options_string (c, NULL); /* delete C1-saved pulled_options_string */
817 #endif
820 static void
821 do_close_tun (struct context *c, bool force)
823 struct gc_arena gc = gc_new ();
824 if (c->c1.tuntap && c->c1.tuntap_owned)
826 const char *tuntap_actual = string_alloc (c->c1.tuntap->actual_name, &gc);
827 const in_addr_t local = c->c1.tuntap->local;
828 const in_addr_t remote_netmask = c->c1.tuntap->remote_netmask;
830 if (force || !(c->sig->signal_received == SIGUSR1 && c->options.persist_tun))
832 #ifdef ENABLE_MANAGEMENT
833 /* tell management layer we are about to close the TUN/TAP device */
834 if (management)
835 management_pre_tunnel_close (management);
836 #endif
838 /* delete any routes we added */
839 if (c->c1.route_list)
840 delete_routes (c->c1.route_list, c->c1.tuntap, ROUTE_OPTION_FLAGS (&c->options), c->c2.es);
842 /* actually close tun/tap device based on --down-pre flag */
843 if (!c->options.down_pre)
844 do_close_tun_simple (c);
846 /* Run the down script -- note that it will run at reduced
847 privilege if, for example, "--user nobody" was used. */
848 run_up_down (c->options.down_script,
849 c->c1.plugins,
850 OPENVPN_PLUGIN_DOWN,
851 tuntap_actual,
852 TUN_MTU_SIZE (&c->c2.frame),
853 EXPANDED_SIZE (&c->c2.frame),
854 print_in_addr_t (local, IA_EMPTY_IF_UNDEF, &gc),
855 print_in_addr_t (remote_netmask, IA_EMPTY_IF_UNDEF, &gc),
856 "init",
857 signal_description (c->sig->signal_received,
858 c->sig->signal_text),
859 "down",
860 c->c2.es);
862 /* actually close tun/tap device based on --down-pre flag */
863 if (c->options.down_pre)
864 do_close_tun_simple (c);
866 else
868 /* run the down script on this restart if --up-restart was specified */
869 if (c->options.up_restart)
870 run_up_down (c->options.down_script,
871 c->c1.plugins,
872 OPENVPN_PLUGIN_DOWN,
873 tuntap_actual,
874 TUN_MTU_SIZE (&c->c2.frame),
875 EXPANDED_SIZE (&c->c2.frame),
876 print_in_addr_t (local, IA_EMPTY_IF_UNDEF, &gc),
877 print_in_addr_t (remote_netmask, IA_EMPTY_IF_UNDEF, &gc),
878 "restart",
879 signal_description (c->sig->signal_received,
880 c->sig->signal_text),
881 "down",
882 c->c2.es);
885 gc_free (&gc);
889 * Handle delayed tun/tap interface bringup due to --up-delay or --pull
892 void
893 do_up (struct context *c, bool pulled_options, unsigned int option_types_found)
895 if (!c->c2.do_up_ran)
897 reset_coarse_timers (c);
899 if (pulled_options && option_types_found)
900 do_deferred_options (c, option_types_found);
902 /* if --up-delay specified, open tun, do ifconfig, and run up script now */
903 if (c->options.up_delay || PULL_DEFINED (&c->options))
905 c->c2.did_open_tun = do_open_tun (c);
906 update_time ();
908 #if P2MP
910 * Was tun interface object persisted from previous restart iteration,
911 * and if so did pulled options string change from previous iteration?
913 if (!c->c2.did_open_tun
914 && PULL_DEFINED (&c->options)
915 && c->c1.tuntap
916 && (!c->c1.pulled_options_string_save || !c->c2.pulled_options_string
917 || strcmp (c->c1.pulled_options_string_save, c->c2.pulled_options_string)))
919 /* if so, close tun, delete routes, then reinitialize tun and add routes */
920 msg (M_INFO, "NOTE: Pulled options changed on restart, will need to close and reopen TUN/TAP device.");
921 do_close_tun (c, true);
922 openvpn_sleep (1);
923 c->c2.did_open_tun = do_open_tun (c);
924 update_time ();
926 #endif
929 if (c->c2.did_open_tun)
931 #if P2MP
932 save_pulled_options_string (c, c->c2.pulled_options_string);
933 #endif
935 /* if --route-delay was specified, start timer */
936 if (c->options.route_delay_defined)
938 event_timeout_init (&c->c2.route_wakeup, c->options.route_delay, now);
939 event_timeout_init (&c->c2.route_wakeup_expire, c->options.route_delay + c->options.route_delay_window, now);
941 else
943 initialization_sequence_completed (c, 0); /* client/p2p --route-delay undefined */
946 else if (c->options.mode == MODE_POINT_TO_POINT)
948 initialization_sequence_completed (c, 0); /* client/p2p restart with --persist-tun */
951 c->c2.do_up_ran = true;
956 * These are the option categories which will be accepted by pull.
958 unsigned int
959 pull_permission_mask (void)
961 return ( OPT_P_UP
962 | OPT_P_ROUTE
963 | OPT_P_IPWIN32
964 | OPT_P_SHAPER
965 | OPT_P_TIMER
966 | OPT_P_PERSIST
967 | OPT_P_MESSAGES
968 | OPT_P_EXPLICIT_NOTIFY
969 | OPT_P_ECHO);
973 * Handle non-tun-related pulled options.
975 void
976 do_deferred_options (struct context *c, const unsigned int found)
978 if (found & OPT_P_MESSAGES)
980 init_verb_mute (c, IVM_LEVEL_1|IVM_LEVEL_2);
981 msg (D_PUSH, "OPTIONS IMPORT: --verb and/or --mute level changed");
983 if (found & OPT_P_TIMER)
985 do_init_timers (c, true);
986 msg (D_PUSH, "OPTIONS IMPORT: timers and/or timeouts modified");
989 #ifdef ENABLE_OCC
990 if (found & OPT_P_EXPLICIT_NOTIFY)
992 if (c->options.proto != PROTO_UDPv4 && c->options.explicit_exit_notification)
994 msg (D_PUSH, "OPTIONS IMPORT: --explicit-exit-notify can only be used with --proto udp");
995 c->options.explicit_exit_notification = 0;
997 else
998 msg (D_PUSH, "OPTIONS IMPORT: explicit notify parm(s) modified");
1000 #endif
1002 if (found & OPT_P_SHAPER)
1004 msg (D_PUSH, "OPTIONS IMPORT: traffic shaper enabled");
1005 do_init_traffic_shaper (c);
1008 if (found & OPT_P_PERSIST)
1009 msg (D_PUSH, "OPTIONS IMPORT: --persist options modified");
1010 if (found & OPT_P_UP)
1011 msg (D_PUSH, "OPTIONS IMPORT: --ifconfig/up options modified");
1012 if (found & OPT_P_ROUTE)
1013 msg (D_PUSH, "OPTIONS IMPORT: route options modified");
1014 if (found & OPT_P_IPWIN32)
1015 msg (D_PUSH, "OPTIONS IMPORT: --ip-win32 and/or --dhcp-option options modified");
1016 if (found & OPT_P_SETENV)
1017 msg (D_PUSH, "OPTIONS IMPORT: environment modified");
1021 * Possible hold on initialization
1023 static bool
1024 do_hold (struct context *c)
1026 #ifdef ENABLE_MANAGEMENT
1027 if (management)
1029 /* if c is defined, daemonize before hold */
1030 if (c && c->options.daemon && management_should_daemonize (management))
1031 do_init_first_time (c);
1033 /* block until management hold is released */
1034 if (management_hold (management))
1035 return true;
1037 #endif
1038 return false;
1042 * Sleep before restart.
1044 static void
1045 socket_restart_pause (struct context *c)
1047 bool proxy = false;
1048 int sec = 2;
1050 #ifdef ENABLE_HTTP_PROXY
1051 if (c->options.http_proxy_options)
1052 proxy = true;
1053 #endif
1054 #ifdef ENABLE_SOCKS
1055 if (c->options.socks_proxy_server)
1056 proxy = true;
1057 #endif
1059 switch (c->options.proto)
1061 case PROTO_UDPv4:
1062 if (proxy)
1063 sec = c->options.connect_retry_seconds;
1064 break;
1065 case PROTO_TCPv4_SERVER:
1066 sec = 1;
1067 break;
1068 case PROTO_TCPv4_CLIENT:
1069 sec = c->options.connect_retry_seconds;
1070 break;
1073 #ifdef ENABLE_DEBUG
1074 if (GREMLIN_CONNECTION_FLOOD_LEVEL (c->options.gremlin))
1075 sec = 0;
1076 #endif
1078 #if P2MP
1079 if (auth_retry_get () == AR_NOINTERACT)
1080 sec = 10;
1081 #endif
1083 if (do_hold (NULL))
1084 sec = 0;
1086 if (sec)
1088 msg (D_RESTART, "Restart pause, %d second(s)", sec);
1089 openvpn_sleep (sec);
1094 * Do a possible pause on context_2 initialization.
1096 static void
1097 do_startup_pause (struct context *c)
1099 if (!c->first_time)
1100 socket_restart_pause (c);
1101 else
1102 do_hold (NULL);
1106 * Finalize MTU parameters based on command line or config file options.
1108 static void
1109 frame_finalize_options (struct context *c, const struct options *o)
1111 if (!o)
1112 o = &c->options;
1115 * Set adjustment factor for buffer alignment when no
1116 * cipher is used.
1118 if (!CIPHER_ENABLED (c))
1120 frame_align_to_extra_frame (&c->c2.frame);
1121 frame_or_align_flags (&c->c2.frame,
1122 FRAME_HEADROOM_MARKER_FRAGMENT
1123 |FRAME_HEADROOM_MARKER_READ_LINK
1124 |FRAME_HEADROOM_MARKER_READ_STREAM);
1127 frame_finalize (&c->c2.frame,
1128 o->link_mtu_defined,
1129 o->link_mtu,
1130 o->tun_mtu_defined,
1131 o->tun_mtu);
1135 * Free a key schedule, including OpenSSL components.
1137 static void
1138 key_schedule_free (struct key_schedule *ks, bool free_ssl_ctx)
1140 #ifdef USE_CRYPTO
1141 free_key_ctx_bi (&ks->static_key);
1142 #ifdef USE_SSL
1143 if (ks->ssl_ctx && free_ssl_ctx)
1145 SSL_CTX_free (ks->ssl_ctx);
1146 free_key_ctx_bi (&ks->tls_auth_key);
1148 #endif /* USE_SSL */
1149 #endif /* USE_CRYPTO */
1150 CLEAR (*ks);
1153 #ifdef USE_CRYPTO
1155 static void
1156 init_crypto_pre (struct context *c, const unsigned int flags)
1158 if (c->options.engine)
1159 init_crypto_lib_engine (c->options.engine);
1161 if (flags & CF_LOAD_PERSISTED_PACKET_ID)
1163 /* load a persisted packet-id for cross-session replay-protection */
1164 if (c->options.packet_id_file)
1165 packet_id_persist_load (&c->c1.pid_persist, c->options.packet_id_file);
1168 /* Initialize crypto options */
1170 if (c->options.use_iv)
1171 c->c2.crypto_options.flags |= CO_USE_IV;
1173 if (c->options.mute_replay_warnings)
1174 c->c2.crypto_options.flags |= CO_MUTE_REPLAY_WARNINGS;
1178 * Static Key Mode (using a pre-shared key)
1180 static void
1181 do_init_crypto_static (struct context *c, const unsigned int flags)
1183 const struct options *options = &c->options;
1184 ASSERT (options->shared_secret_file);
1186 init_crypto_pre (c, flags);
1188 /* Initialize packet ID tracking */
1189 if (options->replay)
1191 packet_id_init (&c->c2.packet_id, options->replay_window,
1192 options->replay_time);
1193 c->c2.crypto_options.packet_id = &c->c2.packet_id;
1194 c->c2.crypto_options.pid_persist = &c->c1.pid_persist;
1195 c->c2.crypto_options.flags |= CO_PACKET_ID_LONG_FORM;
1196 packet_id_persist_load_obj (&c->c1.pid_persist,
1197 c->c2.crypto_options.packet_id);
1200 if (!key_ctx_bi_defined (&c->c1.ks.static_key))
1202 struct key2 key2;
1203 struct key_direction_state kds;
1205 /* Get cipher & hash algorithms */
1206 init_key_type (&c->c1.ks.key_type, options->ciphername,
1207 options->ciphername_defined, options->authname,
1208 options->authname_defined, options->keysize,
1209 options->test_crypto, true);
1211 /* Read cipher and hmac keys from shared secret file */
1212 read_key_file (&key2, options->shared_secret_file, true);
1214 /* Check for and fix highly unlikely key problems */
1215 verify_fix_key2 (&key2, &c->c1.ks.key_type,
1216 options->shared_secret_file);
1218 /* Initialize OpenSSL key objects */
1219 key_direction_state_init (&kds, options->key_direction);
1220 must_have_n_keys (options->shared_secret_file, "secret", &key2,
1221 kds.need_keys);
1222 init_key_ctx (&c->c1.ks.static_key.encrypt, &key2.keys[kds.out_key],
1223 &c->c1.ks.key_type, DO_ENCRYPT, "Static Encrypt");
1224 init_key_ctx (&c->c1.ks.static_key.decrypt, &key2.keys[kds.in_key],
1225 &c->c1.ks.key_type, DO_DECRYPT, "Static Decrypt");
1227 /* Erase the temporary copy of key */
1228 CLEAR (key2);
1230 else
1232 msg (M_INFO, "Re-using pre-shared static key");
1235 /* Get key schedule */
1236 c->c2.crypto_options.key_ctx_bi = &c->c1.ks.static_key;
1238 /* Compute MTU parameters */
1239 crypto_adjust_frame_parameters (&c->c2.frame,
1240 &c->c1.ks.key_type,
1241 options->ciphername_defined,
1242 options->use_iv, options->replay, true);
1244 /* Sanity check on IV, sequence number, and cipher mode options */
1245 check_replay_iv_consistency (&c->c1.ks.key_type, options->replay,
1246 options->use_iv);
1249 #ifdef USE_SSL
1252 * Initialize the persistent component of OpenVPN's TLS mode,
1253 * which is preserved across SIGUSR1 resets.
1255 static void
1256 do_init_crypto_tls_c1 (struct context *c)
1258 const struct options *options = &c->options;
1260 if (!c->c1.ks.ssl_ctx)
1263 * Initialize the OpenSSL library's global
1264 * SSL context.
1266 c->c1.ks.ssl_ctx = init_ssl (options);
1267 if (!c->c1.ks.ssl_ctx)
1269 #if P2MP
1270 switch (auth_retry_get ())
1272 case AR_NONE:
1273 msg (M_FATAL, "Error: private key password verification failed");
1274 break;
1275 case AR_INTERACT:
1276 ssl_purge_auth ();
1277 case AR_NOINTERACT:
1278 c->sig->signal_received = SIGUSR1; /* SOFT-SIGUSR1 -- Password failure error */
1279 break;
1280 default:
1281 ASSERT (0);
1283 c->sig->signal_text = "private-key-password-failure";
1284 return;
1285 #else
1286 msg (M_FATAL, "Error: private key password verification failed");
1287 #endif
1290 /* Get cipher & hash algorithms */
1291 init_key_type (&c->c1.ks.key_type, options->ciphername,
1292 options->ciphername_defined, options->authname,
1293 options->authname_defined, options->keysize, true, true);
1295 /* TLS handshake authentication (--tls-auth) */
1296 if (options->tls_auth_file)
1297 get_tls_handshake_key (&c->c1.ks.key_type,
1298 &c->c1.ks.tls_auth_key,
1299 options->tls_auth_file,
1300 options->key_direction);
1302 else
1304 msg (M_INFO, "Re-using SSL/TLS context");
1308 static void
1309 do_init_crypto_tls (struct context *c, const unsigned int flags)
1311 const struct options *options = &c->options;
1312 struct tls_options to;
1313 bool packet_id_long_form;
1315 ASSERT (options->tls_server || options->tls_client);
1316 ASSERT (!options->test_crypto);
1318 init_crypto_pre (c, flags);
1320 /* Make sure we are either a TLS client or server but not both */
1321 ASSERT (options->tls_server == !options->tls_client);
1323 /* initialize persistent component */
1324 do_init_crypto_tls_c1 (c);
1325 if (IS_SIG (c))
1326 return;
1328 /* Sanity check on IV, sequence number, and cipher mode options */
1329 check_replay_iv_consistency (&c->c1.ks.key_type, options->replay,
1330 options->use_iv);
1332 /* In short form, unique datagram identifier is 32 bits, in long form 64 bits */
1333 packet_id_long_form = cfb_ofb_mode (&c->c1.ks.key_type);
1335 /* Compute MTU parameters */
1336 crypto_adjust_frame_parameters (&c->c2.frame,
1337 &c->c1.ks.key_type,
1338 options->ciphername_defined,
1339 options->use_iv,
1340 options->replay, packet_id_long_form);
1341 tls_adjust_frame_parameters (&c->c2.frame);
1343 /* Set all command-line TLS-related options */
1344 CLEAR (to);
1346 to.crypto_flags_and = ~(CO_PACKET_ID_LONG_FORM);
1347 if (packet_id_long_form)
1348 to.crypto_flags_or = CO_PACKET_ID_LONG_FORM;
1350 to.ssl_ctx = c->c1.ks.ssl_ctx;
1351 to.key_type = c->c1.ks.key_type;
1352 to.server = options->tls_server;
1353 to.key_method = options->key_method;
1354 to.replay = options->replay;
1355 to.replay_window = options->replay_window;
1356 to.replay_time = options->replay_time;
1357 to.transition_window = options->transition_window;
1358 to.handshake_window = options->handshake_window;
1359 to.packet_timeout = options->tls_timeout;
1360 to.renegotiate_bytes = options->renegotiate_bytes;
1361 to.renegotiate_packets = options->renegotiate_packets;
1362 to.renegotiate_seconds = options->renegotiate_seconds;
1363 to.single_session = options->single_session;
1365 #ifdef ENABLE_OCC
1366 to.disable_occ = !options->occ;
1367 #endif
1369 to.verify_command = options->tls_verify;
1370 to.verify_x509name = options->tls_remote;
1371 to.crl_file = options->crl_file;
1372 to.ns_cert_type = options->ns_cert_type;
1373 to.es = c->c2.es;
1375 #ifdef ENABLE_DEBUG
1376 to.gremlin = c->options.gremlin;
1377 #endif
1379 to.plugins = c->c1.plugins;
1381 #if P2MP_SERVER
1382 to.auth_user_pass_verify_script = options->auth_user_pass_verify_script;
1383 to.auth_user_pass_verify_script_via_file = options->auth_user_pass_verify_script_via_file;
1384 to.tmp_dir = options->tmp_dir;
1385 to.username_as_common_name = options->username_as_common_name;
1386 if (options->ccd_exclusive)
1387 to.client_config_dir_exclusive = options->client_config_dir;
1388 #endif
1390 /* TLS handshake authentication (--tls-auth) */
1391 if (options->tls_auth_file)
1393 to.tls_auth_key = c->c1.ks.tls_auth_key;
1394 to.tls_auth.pid_persist = &c->c1.pid_persist;
1395 to.tls_auth.flags |= CO_PACKET_ID_LONG_FORM;
1396 crypto_adjust_frame_parameters (&to.frame,
1397 &c->c1.ks.key_type,
1398 false, false, true, true);
1401 /* If we are running over TCP, allow for
1402 length prefix */
1403 socket_adjust_frame_parameters (&to.frame, options->proto);
1406 * Initialize OpenVPN's master TLS-mode object.
1408 if (flags & CF_INIT_TLS_MULTI)
1409 c->c2.tls_multi = tls_multi_init (&to);
1411 if (flags & CF_INIT_TLS_AUTH_STANDALONE)
1412 c->c2.tls_auth_standalone = tls_auth_standalone_init (&to, &c->c2.gc);
1415 static void
1416 do_init_finalize_tls_frame (struct context *c)
1418 if (c->c2.tls_multi)
1420 tls_multi_init_finalize (c->c2.tls_multi, &c->c2.frame);
1421 ASSERT (EXPANDED_SIZE (&c->c2.tls_multi->opt.frame) <=
1422 EXPANDED_SIZE (&c->c2.frame));
1423 frame_print (&c->c2.tls_multi->opt.frame, D_MTU_INFO,
1424 "Control Channel MTU parms");
1426 if (c->c2.tls_auth_standalone)
1428 tls_auth_standalone_finalize (c->c2.tls_auth_standalone, &c->c2.frame);
1429 frame_print (&c->c2.tls_auth_standalone->frame, D_MTU_INFO,
1430 "TLS-Auth MTU parms");
1434 #endif /* USE_SSL */
1435 #endif /* USE_CRYPTO */
1437 #ifdef USE_CRYPTO
1439 * No encryption or authentication.
1441 static void
1442 do_init_crypto_none (const struct context *c)
1444 ASSERT (!c->options.test_crypto);
1445 msg (M_WARN,
1446 "******* WARNING *******: all encryption and authentication features disabled -- all data will be tunnelled as cleartext");
1448 #endif
1450 static void
1451 do_init_crypto (struct context *c, const unsigned int flags)
1453 #ifdef USE_CRYPTO
1454 if (c->options.shared_secret_file)
1455 do_init_crypto_static (c, flags);
1456 #ifdef USE_SSL
1457 else if (c->options.tls_server || c->options.tls_client)
1458 do_init_crypto_tls (c, flags);
1459 #endif
1460 else /* no encryption or authentication. */
1461 do_init_crypto_none (c);
1462 #else /* USE_CRYPTO */
1463 msg (M_WARN,
1464 "******* WARNING *******: " PACKAGE_NAME
1465 " built without OpenSSL -- encryption and authentication features disabled -- all data will be tunnelled as cleartext");
1466 #endif /* USE_CRYPTO */
1469 static void
1470 do_init_frame (struct context *c)
1472 #ifdef USE_LZO
1474 * Initialize LZO compression library.
1476 if (c->options.comp_lzo)
1478 lzo_adjust_frame_parameters (&c->c2.frame);
1481 * LZO usage affects buffer alignment.
1483 if (CIPHER_ENABLED (c))
1485 frame_add_to_align_adjust (&c->c2.frame, LZO_PREFIX_LEN);
1486 frame_or_align_flags (&c->c2.frame,
1487 FRAME_HEADROOM_MARKER_FRAGMENT
1488 |FRAME_HEADROOM_MARKER_DECRYPT);
1491 #ifdef ENABLE_FRAGMENT
1492 lzo_adjust_frame_parameters (&c->c2.frame_fragment_omit); /* omit LZO frame delta from final frame_fragment */
1493 #endif
1495 #endif
1497 #ifdef ENABLE_SOCKS
1499 * Adjust frame size for UDP Socks support.
1501 if (c->options.socks_proxy_server)
1502 socks_adjust_frame_parameters (&c->c2.frame, c->options.proto);
1503 #endif
1506 * Adjust frame size based on the --tun-mtu-extra parameter.
1508 if (c->options.tun_mtu_extra_defined)
1509 tun_adjust_frame_parameters (&c->c2.frame, c->options.tun_mtu_extra);
1512 * Adjust frame size based on link socket parameters.
1513 * (Since TCP is a stream protocol, we need to insert
1514 * a packet length uint16_t in the buffer.)
1516 socket_adjust_frame_parameters (&c->c2.frame, c->options.proto);
1519 * Fill in the blanks in the frame parameters structure,
1520 * make sure values are rational, etc.
1522 frame_finalize_options (c, NULL);
1524 #ifdef ENABLE_FRAGMENT
1526 * Set frame parameter for fragment code. This is necessary because
1527 * the fragmentation code deals with payloads which have already been
1528 * passed through the compression code.
1530 c->c2.frame_fragment = c->c2.frame;
1531 frame_subtract_extra (&c->c2.frame_fragment, &c->c2.frame_fragment_omit);
1532 #endif
1534 #if defined(ENABLE_FRAGMENT) && defined(ENABLE_OCC)
1536 * MTU advisories
1538 if (c->options.fragment && c->options.mtu_test)
1539 msg (M_WARN,
1540 "WARNING: using --fragment and --mtu-test together may produce an inaccurate MTU test result");
1541 #endif
1543 #ifdef ENABLE_FRAGMENT
1544 if ((c->options.mssfix || c->options.fragment)
1545 && TUN_MTU_SIZE (&c->c2.frame_fragment) != ETHERNET_MTU)
1546 msg (M_WARN,
1547 "WARNING: normally if you use --mssfix and/or --fragment, you should also set --tun-mtu %d (currently it is %d)",
1548 ETHERNET_MTU, TUN_MTU_SIZE (&c->c2.frame_fragment));
1549 #endif
1552 static void
1553 do_option_warnings (struct context *c)
1555 const struct options *o = &c->options;
1557 #if 1 /* JYFIXME -- port warning */
1558 if (!o->port_option_used && (o->local_port == OPENVPN_PORT && o->remote_port == OPENVPN_PORT))
1559 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.",
1560 OPENVPN_PORT);
1561 #endif
1563 if (o->ping_send_timeout && !o->ping_rec_timeout)
1564 msg (M_WARN, "WARNING: --ping should normally be used with --ping-restart or --ping-exit");
1566 if ((o->username || o->groupname || o->chroot_dir) && (!o->persist_tun || !o->persist_key))
1567 msg (M_WARN, "WARNING: you are using user/group/chroot without persist-key/persist-tun -- this may cause restarts to fail");
1569 #if P2MP
1570 if (o->pull && o->ifconfig_local && c->first_time)
1571 msg (M_WARN, "WARNING: using --pull/--client and --ifconfig together is probably not what you want");
1573 #if P2MP_SERVER
1574 if (o->mode == MODE_SERVER)
1576 if (o->duplicate_cn && o->client_config_dir)
1577 msg (M_WARN, "WARNING: using --duplicate-cn and --client-config-dir together is probably not what you want");
1578 if (o->duplicate_cn && o->ifconfig_pool_persist_filename)
1579 msg (M_WARN, "WARNING: --ifconfig-pool-persist will not work with --duplicate-cn");
1580 if (!o->keepalive_ping || !o->keepalive_timeout)
1581 msg (M_WARN, "WARNING: --keepalive option is missing from server config");
1583 #endif
1584 #endif
1586 #ifdef USE_CRYPTO
1587 if (!o->replay)
1588 msg (M_WARN, "WARNING: You have disabled Replay Protection (--no-replay) which may make " PACKAGE_NAME " less secure");
1589 if (!o->use_iv)
1590 msg (M_WARN, "WARNING: You have disabled Crypto IVs (--no-iv) which may make " PACKAGE_NAME " less secure");
1592 #ifdef USE_SSL
1593 if (o->tls_client
1594 && !o->tls_verify
1595 && !o->tls_remote
1596 && !(o->ns_cert_type & NS_SSL_SERVER))
1597 msg (M_WARN, "WARNING: No server certificate verification method has been enabled. See http://openvpn.net/howto.html#mitm for more info.");
1598 #endif
1600 #endif
1603 static void
1604 do_init_frame_tls (struct context *c)
1606 #if defined(USE_CRYPTO) && defined(USE_SSL)
1607 do_init_finalize_tls_frame (c);
1608 #endif
1611 struct context_buffers *
1612 init_context_buffers (const struct frame *frame)
1614 struct context_buffers *b;
1616 ALLOC_OBJ_CLEAR (b, struct context_buffers);
1618 b->read_link_buf = alloc_buf (BUF_SIZE (frame));
1619 b->read_tun_buf = alloc_buf (BUF_SIZE (frame));
1621 b->aux_buf = alloc_buf (BUF_SIZE (frame));
1623 #ifdef USE_CRYPTO
1624 b->encrypt_buf = alloc_buf (BUF_SIZE (frame));
1625 b->decrypt_buf = alloc_buf (BUF_SIZE (frame));
1626 #endif
1628 #ifdef USE_LZO
1629 b->lzo_compress_buf = alloc_buf (BUF_SIZE (frame));
1630 b->lzo_decompress_buf = alloc_buf (BUF_SIZE (frame));
1631 #endif
1633 return b;
1636 void
1637 free_context_buffers (struct context_buffers *b)
1639 if (b)
1641 free_buf (&b->read_link_buf);
1642 free_buf (&b->read_tun_buf);
1643 free_buf (&b->aux_buf);
1645 #ifdef USE_LZO
1646 free_buf (&b->lzo_compress_buf);
1647 free_buf (&b->lzo_decompress_buf);
1648 #endif
1650 #ifdef USE_CRYPTO
1651 free_buf (&b->encrypt_buf);
1652 free_buf (&b->decrypt_buf);
1653 #endif
1655 free (b);
1660 * Now that we know all frame parameters, initialize
1661 * our buffers.
1663 static void
1664 do_init_buffers (struct context *c)
1666 c->c2.buffers = init_context_buffers (&c->c2.frame);
1667 c->c2.buffers_owned = true;
1670 #ifdef ENABLE_FRAGMENT
1672 * Fragmenting code has buffers to initialize
1673 * once frame parameters are known.
1675 static void
1676 do_init_fragment (struct context *c)
1678 ASSERT (c->options.fragment);
1679 frame_set_mtu_dynamic (&c->c2.frame_fragment,
1680 c->options.fragment, SET_MTU_UPPER_BOUND);
1681 fragment_frame_init (c->c2.fragment, &c->c2.frame_fragment);
1683 #endif
1686 * Set the --mssfix option.
1688 static void
1689 do_init_mssfix (struct context *c)
1691 if (c->options.mssfix)
1693 frame_set_mtu_dynamic (&c->c2.frame,
1694 c->options.mssfix, SET_MTU_UPPER_BOUND);
1699 * Allocate our socket object.
1701 static void
1702 do_link_socket_new (struct context *c)
1704 ASSERT (!c->c2.link_socket);
1705 c->c2.link_socket = link_socket_new ();
1706 c->c2.link_socket_owned = true;
1710 * bind the TCP/UDP socket
1712 static void
1713 do_init_socket_1 (struct context *c, int mode)
1715 link_socket_init_phase1 (c->c2.link_socket,
1716 c->options.local,
1717 c->c1.remote_list,
1718 c->options.local_port,
1719 c->options.proto,
1720 mode,
1721 c->c2.accept_from,
1722 #ifdef ENABLE_HTTP_PROXY
1723 c->c1.http_proxy,
1724 #endif
1725 #ifdef ENABLE_SOCKS
1726 c->c1.socks_proxy,
1727 #endif
1728 #ifdef ENABLE_DEBUG
1729 c->options.gremlin,
1730 #endif
1731 c->options.bind_local,
1732 c->options.remote_float,
1733 c->options.inetd,
1734 &c->c1.link_socket_addr,
1735 c->options.ipchange,
1736 c->c1.plugins,
1737 c->options.resolve_retry_seconds,
1738 c->options.connect_retry_seconds,
1739 c->options.mtu_discover_type,
1740 c->options.rcvbuf,
1741 c->options.sndbuf);
1745 * finalize the TCP/UDP socket
1747 static void
1748 do_init_socket_2 (struct context *c)
1750 link_socket_init_phase2 (c->c2.link_socket, &c->c2.frame,
1751 &c->sig->signal_received);
1755 * Print MTU INFO
1757 static void
1758 do_print_data_channel_mtu_parms (struct context *c)
1760 frame_print (&c->c2.frame, D_MTU_INFO, "Data Channel MTU parms");
1761 #ifdef ENABLE_FRAGMENT
1762 if (c->c2.fragment)
1763 frame_print (&c->c2.frame_fragment, D_MTU_INFO,
1764 "Fragmentation MTU parms");
1765 #endif
1768 #ifdef ENABLE_OCC
1770 * Get local and remote options compatibility strings.
1772 static void
1773 do_compute_occ_strings (struct context *c)
1775 struct gc_arena gc = gc_new ();
1777 c->c2.options_string_local =
1778 options_string (&c->options, &c->c2.frame, c->c1.tuntap, false, &gc);
1779 c->c2.options_string_remote =
1780 options_string (&c->options, &c->c2.frame, c->c1.tuntap, true, &gc);
1782 msg (D_SHOW_OCC, "Local Options String: '%s'", c->c2.options_string_local);
1783 msg (D_SHOW_OCC, "Expected Remote Options String: '%s'",
1784 c->c2.options_string_remote);
1786 #ifdef USE_CRYPTO
1787 msg (D_SHOW_OCC_HASH, "Local Options hash (VER=%s): '%s'",
1788 options_string_version (c->c2.options_string_local, &gc),
1789 md5sum ((uint8_t*)c->c2.options_string_local,
1790 strlen (c->c2.options_string_local), 9, &gc));
1791 msg (D_SHOW_OCC_HASH, "Expected Remote Options hash (VER=%s): '%s'",
1792 options_string_version (c->c2.options_string_remote, &gc),
1793 md5sum ((uint8_t*)c->c2.options_string_remote,
1794 strlen (c->c2.options_string_remote), 9, &gc));
1795 #endif
1797 #if defined(USE_CRYPTO) && defined(USE_SSL)
1798 if (c->c2.tls_multi)
1799 tls_multi_init_set_options (c->c2.tls_multi,
1800 c->c2.options_string_local,
1801 c->c2.options_string_remote);
1802 #endif
1804 gc_free (&gc);
1806 #endif
1809 * These things can only be executed once per program instantiation.
1810 * Set up for possible UID/GID downgrade, but don't do it yet.
1811 * Daemonize if requested.
1813 static void
1814 do_init_first_time (struct context *c)
1816 if (c->first_time && !c->did_we_daemonize && !c->c0)
1818 struct context_0 *c0;
1820 ALLOC_OBJ_CLEAR_GC (c->c0, struct context_0, &c->gc);
1821 c0 = c->c0;
1823 /* get user and/or group that we want to setuid/setgid to */
1824 c0->uid_gid_specified =
1825 get_group (c->options.groupname, &c0->group_state) |
1826 get_user (c->options.username, &c0->user_state);
1828 /* get --writepid file descriptor */
1829 get_pid_file (c->options.writepid, &c0->pid_state);
1831 /* become a daemon if --daemon */
1832 c->did_we_daemonize = possibly_become_daemon (&c->options, c->first_time);
1834 /* should we disable paging? */
1835 if (c->options.mlock && c->did_we_daemonize)
1836 do_mlockall (true); /* call again in case we daemonized */
1838 /* save process ID in a file */
1839 write_pid (&c0->pid_state);
1841 /* should we change scheduling priority? */
1842 set_nice (c->options.nice);
1847 * If xinetd/inetd mode, don't allow restart.
1849 static void
1850 do_close_check_if_restart_permitted (struct context *c)
1852 if (c->options.inetd
1853 && (c->sig->signal_received == SIGHUP
1854 || c->sig->signal_received == SIGUSR1))
1856 c->sig->signal_received = SIGTERM;
1857 msg (M_INFO,
1858 PACKAGE_NAME
1859 " started by inetd/xinetd cannot restart... Exiting.");
1864 * free buffers
1866 static void
1867 do_close_free_buf (struct context *c)
1869 if (c->c2.buffers_owned)
1871 free_context_buffers (c->c2.buffers);
1872 c->c2.buffers = NULL;
1873 c->c2.buffers_owned = false;
1878 * close TLS
1880 static void
1881 do_close_tls (struct context *c)
1883 #if defined(USE_CRYPTO) && defined(USE_SSL)
1884 if (c->c2.tls_multi)
1886 tls_multi_free (c->c2.tls_multi, true);
1887 c->c2.tls_multi = NULL;
1890 #ifdef ENABLE_OCC
1891 /* free options compatibility strings */
1892 if (c->c2.options_string_local)
1893 free (c->c2.options_string_local);
1894 if (c->c2.options_string_remote)
1895 free (c->c2.options_string_remote);
1896 c->c2.options_string_local = c->c2.options_string_remote = NULL;
1897 #endif
1898 #endif
1902 * Free key schedules
1904 static void
1905 do_close_free_key_schedule (struct context *c, bool free_ssl_ctx)
1907 if (!(c->sig->signal_received == SIGUSR1 && c->options.persist_key))
1908 key_schedule_free (&c->c1.ks, free_ssl_ctx);
1912 * Close TCP/UDP connection
1914 static void
1915 do_close_link_socket (struct context *c)
1917 if (c->c2.link_socket && c->c2.link_socket_owned)
1919 link_socket_close (c->c2.link_socket);
1920 c->c2.link_socket = NULL;
1923 if (!(c->sig->signal_received == SIGUSR1 && c->options.persist_remote_ip))
1925 CLEAR (c->c1.link_socket_addr.remote);
1926 CLEAR (c->c1.link_socket_addr.actual);
1929 if (!(c->sig->signal_received == SIGUSR1 && c->options.persist_local_ip))
1930 CLEAR (c->c1.link_socket_addr.local);
1934 * Close packet-id persistance file
1936 static void
1937 do_close_packet_id (struct context *c)
1939 #ifdef USE_CRYPTO
1940 packet_id_free (&c->c2.packet_id);
1941 packet_id_persist_save (&c->c1.pid_persist);
1942 if (!(c->sig->signal_received == SIGUSR1))
1943 packet_id_persist_close (&c->c1.pid_persist);
1944 #endif
1947 #ifdef ENABLE_FRAGMENT
1949 * Close fragmentation handler.
1951 static void
1952 do_close_fragment (struct context *c)
1954 if (c->c2.fragment)
1956 fragment_free (c->c2.fragment);
1957 c->c2.fragment = NULL;
1960 #endif
1963 * Open and close our event objects.
1966 static void
1967 do_event_set_init (struct context *c,
1968 bool need_us_timeout)
1970 unsigned int flags = 0;
1972 c->c2.event_set_max = BASE_N_EVENTS;
1974 flags |= EVENT_METHOD_FAST;
1976 if (need_us_timeout)
1977 flags |= EVENT_METHOD_US_TIMEOUT;
1979 c->c2.event_set = event_set_init (&c->c2.event_set_max, flags);
1980 c->c2.event_set_owned = true;
1983 static void
1984 do_close_event_set (struct context *c)
1986 if (c->c2.event_set && c->c2.event_set_owned)
1988 event_free (c->c2.event_set);
1989 c->c2.event_set = NULL;
1990 c->c2.event_set_owned = false;
1995 * Open and close --status file
1998 static void
1999 do_open_status_output (struct context *c)
2001 if (!c->c1.status_output)
2003 c->c1.status_output = status_open (c->options.status_file,
2004 c->options.status_file_update_freq,
2006 NULL,
2007 STATUS_OUTPUT_WRITE);
2008 c->c1.status_output_owned = true;
2012 static void
2013 do_close_status_output (struct context *c)
2015 if (!(c->sig->signal_received == SIGUSR1))
2017 if (c->c1.status_output_owned && c->c1.status_output)
2019 status_close (c->c1.status_output);
2020 c->c1.status_output = NULL;
2021 c->c1.status_output_owned = false;
2027 * Handle ifconfig-pool persistance object.
2029 static void
2030 do_open_ifconfig_pool_persist (struct context *c)
2032 #if P2MP_SERVER
2033 if (!c->c1.ifconfig_pool_persist && c->options.ifconfig_pool_persist_filename)
2035 c->c1.ifconfig_pool_persist = ifconfig_pool_persist_init (c->options.ifconfig_pool_persist_filename,
2036 c->options.ifconfig_pool_persist_refresh_freq);
2037 c->c1.ifconfig_pool_persist_owned = true;
2039 #endif
2042 static void
2043 do_close_ifconfig_pool_persist (struct context *c)
2045 #if P2MP_SERVER
2046 if (!(c->sig->signal_received == SIGUSR1))
2048 if (c->c1.ifconfig_pool_persist && c->c1.ifconfig_pool_persist_owned)
2050 ifconfig_pool_persist_close (c->c1.ifconfig_pool_persist);
2051 c->c1.ifconfig_pool_persist = NULL;
2052 c->c1.ifconfig_pool_persist_owned = false;
2055 #endif
2059 * Inherit environmental variables
2062 static void
2063 do_inherit_env (struct context *c, const struct env_set *src)
2065 c->c2.es = env_set_create (&c->c2.gc);
2066 env_set_inherit (c->c2.es, src);
2070 * Fast I/O setup. Fast I/O is an optimization which only works
2071 * if all of the following are true:
2073 * (1) The platform is not Windows
2074 * (2) --proto udp is enabled
2075 * (3) --shaper is disabled
2077 static void
2078 do_setup_fast_io (struct context *c)
2080 if (c->options.fast_io)
2082 #ifdef WIN32
2083 msg (M_INFO, "NOTE: --fast-io is disabled since we are running on Windows");
2084 #else
2085 if (c->options.proto != PROTO_UDPv4)
2086 msg (M_INFO, "NOTE: --fast-io is disabled since we are not using UDP");
2087 else
2089 if (c->options.shaper)
2090 msg (M_INFO, "NOTE: --fast-io is disabled since we are using --shaper");
2091 else
2093 c->c2.fast_io = true;
2096 #endif
2100 static void
2101 do_signal_on_tls_errors (struct context *c)
2103 #if defined(USE_CRYPTO) && defined(USE_SSL)
2104 if (c->options.tls_exit)
2105 c->c2.tls_exit_signal = SIGTERM;
2106 else
2107 c->c2.tls_exit_signal = SIGUSR1;
2108 #endif
2112 static void
2113 do_open_plugins (struct context *c)
2115 #ifdef ENABLE_PLUGIN
2116 if (c->options.plugin_list && !c->c1.plugins)
2118 c->c1.plugins = plugin_list_open (c->options.plugin_list, c->c2.es);
2119 c->c1.plugins_owned = true;
2121 #endif
2124 static void
2125 do_close_plugins (struct context *c)
2127 #ifdef ENABLE_PLUGIN
2128 if (c->c1.plugins && c->c1.plugins_owned && !(c->sig->signal_received == SIGUSR1))
2130 plugin_list_close (c->c1.plugins);
2131 c->c1.plugins = NULL;
2132 c->c1.plugins_owned = false;
2134 #endif
2137 #ifdef ENABLE_MANAGEMENT
2139 static void
2140 management_callback_status_p2p (void *arg, const int version, struct status_output *so)
2142 struct context *c = (struct context *) arg;
2143 print_status (c, so);
2146 void
2147 management_show_net_callback (void *arg, const int msglevel)
2149 #ifdef WIN32
2150 show_routes (msglevel);
2151 show_adapters (msglevel);
2152 msg (msglevel, "END");
2153 #else
2154 msg (msglevel, "ERROR: Sorry, this command is currently only implemented on Windows");
2155 #endif
2158 #endif
2160 void
2161 init_management_callback_p2p (struct context *c)
2163 #ifdef ENABLE_MANAGEMENT
2164 if (management)
2166 struct management_callback cb;
2167 CLEAR (cb);
2168 cb.arg = c;
2169 cb.status = management_callback_status_p2p;
2170 cb.show_net = management_show_net_callback;
2171 management_set_callback (management, &cb);
2173 #endif
2176 #ifdef ENABLE_MANAGEMENT
2178 void
2179 init_management (struct context *c)
2181 if (!management)
2182 management = management_init ();
2185 bool
2186 open_management (struct context *c)
2188 /* initialize management layer */
2189 if (management)
2191 if (c->options.management_addr)
2193 if (management_open (management,
2194 c->options.management_addr,
2195 c->options.management_port,
2196 c->options.management_user_pass,
2197 c->options.mode == MODE_SERVER,
2198 c->options.management_query_passwords,
2199 c->options.management_log_history_cache,
2200 c->options.management_echo_buffer_size,
2201 c->options.management_state_buffer_size,
2202 c->options.management_hold))
2204 management_set_state (management,
2205 OPENVPN_STATE_CONNECTING,
2206 NULL,
2207 (in_addr_t)0);
2210 /* possible wait */
2211 do_hold (c);
2212 if (IS_SIG (c))
2214 msg (M_WARN, "Signal received from management interface, exiting");
2215 return false;
2218 else
2219 close_management ();
2221 return true;
2224 void
2225 close_management (void)
2227 if (management)
2229 management_close (management);
2230 management = NULL;
2234 #endif
2237 void
2238 uninit_management_callback (void)
2240 #ifdef ENABLE_MANAGEMENT
2241 if (management)
2243 management_clear_callback (management);
2245 #endif
2249 * Initialize a tunnel instance, handle pre and post-init
2250 * signal settings.
2252 void
2253 init_instance_handle_signals (struct context *c, const struct env_set *env, const unsigned int flags)
2255 pre_init_signal_catch ();
2256 init_instance (c, env, flags);
2257 post_init_signal_catch ();
2261 * Initialize a tunnel instance.
2263 void
2264 init_instance (struct context *c, const struct env_set *env, const unsigned int flags)
2266 const struct options *options = &c->options;
2267 const bool child = (c->mode == CM_CHILD_TCP || c->mode == CM_CHILD_UDP);
2268 int link_socket_mode = LS_MODE_DEFAULT;
2270 /* init garbage collection level */
2271 gc_init (&c->c2.gc);
2273 /* signals caught here will abort */
2274 c->sig->signal_received = 0;
2275 c->sig->signal_text = NULL;
2276 c->sig->hard = false;
2278 /* link_socket_mode allows CM_CHILD_TCP
2279 instances to inherit acceptable fds
2280 from a top-level parent */
2281 if (c->options.proto == PROTO_TCPv4_SERVER)
2283 if (c->mode == CM_TOP)
2284 link_socket_mode = LS_MODE_TCP_LISTEN;
2285 else if (c->mode == CM_CHILD_TCP)
2286 link_socket_mode = LS_MODE_TCP_ACCEPT_FROM;
2289 /* should we disable paging? */
2290 if (c->first_time && options->mlock)
2291 do_mlockall (true);
2293 /* possible sleep or management hold if restart */
2294 if (c->mode == CM_P2P || c->mode == CM_TOP)
2296 do_startup_pause (c);
2297 if (IS_SIG (c))
2298 goto sig;
2301 #if P2MP
2302 /* get passwords if undefined */
2303 if (auth_retry_get () == AR_INTERACT)
2304 init_query_passwords (c);
2305 #endif
2307 /* initialize context level 2 --verb/--mute parms */
2308 init_verb_mute (c, IVM_LEVEL_2);
2310 /* set error message delay for non-server modes */
2311 if (c->mode == CM_P2P)
2312 set_check_status_error_delay (P2P_ERROR_DELAY_MS);
2314 /* warn about inconsistent options */
2315 if (c->mode == CM_P2P || c->mode == CM_TOP)
2316 do_option_warnings (c);
2318 /* inherit environmental variables */
2319 if (env)
2320 do_inherit_env (c, env);
2322 /* initialize plugins */
2323 if (c->mode == CM_P2P || c->mode == CM_TOP)
2324 do_open_plugins (c);
2326 /* should we enable fast I/O? */
2327 if (c->mode == CM_P2P || c->mode == CM_TOP)
2328 do_setup_fast_io (c);
2330 /* should we throw a signal on TLS errors? */
2331 do_signal_on_tls_errors (c);
2333 /* open --status file */
2334 if (c->mode == CM_P2P || c->mode == CM_TOP)
2335 do_open_status_output (c);
2337 /* open --ifconfig-pool-persist file */
2338 if (c->mode == CM_TOP)
2339 do_open_ifconfig_pool_persist (c);
2341 #ifdef ENABLE_OCC
2342 /* reset OCC state */
2343 if (c->mode == CM_P2P || child)
2344 c->c2.occ_op = occ_reset_op ();
2345 #endif
2347 /* our wait-for-i/o objects, different for posix vs. win32 */
2348 if (c->mode == CM_P2P)
2349 do_event_set_init (c, SHAPER_DEFINED (&c->options));
2350 else if (c->mode == CM_CHILD_TCP)
2351 do_event_set_init (c, false);
2353 /* allocate our socket object */
2354 if (c->mode == CM_P2P || c->mode == CM_TOP || c->mode == CM_CHILD_TCP)
2355 do_link_socket_new (c);
2357 #ifdef ENABLE_FRAGMENT
2358 /* initialize internal fragmentation object */
2359 if (options->fragment && (c->mode == CM_P2P || child))
2360 c->c2.fragment = fragment_init (&c->c2.frame);
2361 #endif
2363 /* init crypto layer */
2365 unsigned int crypto_flags = 0;
2366 if (c->mode == CM_TOP)
2367 crypto_flags = CF_INIT_TLS_AUTH_STANDALONE;
2368 else if (c->mode == CM_P2P)
2369 crypto_flags = CF_LOAD_PERSISTED_PACKET_ID | CF_INIT_TLS_MULTI;
2370 else if (child)
2371 crypto_flags = CF_INIT_TLS_MULTI;
2372 do_init_crypto (c, crypto_flags);
2373 if (IS_SIG (c) && !child)
2374 goto sig;
2377 #ifdef USE_LZO
2378 /* initialize LZO compression library. */
2379 if (options->comp_lzo && (c->mode == CM_P2P || child))
2380 lzo_compress_init (&c->c2.lzo_compwork, options->comp_lzo_adaptive);
2381 #endif
2383 /* initialize MTU variables */
2384 do_init_frame (c);
2386 /* initialize TLS MTU variables */
2387 do_init_frame_tls (c);
2389 /* init workspace buffers whose size is derived from frame size */
2390 if (c->mode == CM_P2P || c->mode == CM_CHILD_TCP)
2391 do_init_buffers (c);
2393 #ifdef ENABLE_FRAGMENT
2394 /* initialize internal fragmentation capability with known frame size */
2395 if (options->fragment && (c->mode == CM_P2P || child))
2396 do_init_fragment (c);
2397 #endif
2399 /* initialize dynamic MTU variable */
2400 do_init_mssfix (c);
2402 /* bind the TCP/UDP socket */
2403 if (c->mode == CM_P2P || c->mode == CM_TOP || c->mode == CM_CHILD_TCP)
2404 do_init_socket_1 (c, link_socket_mode);
2406 /* initialize tun/tap device object,
2407 open tun/tap device, ifconfig, run up script, etc. */
2408 if (!(options->up_delay || PULL_DEFINED (options)) && (c->mode == CM_P2P || c->mode == CM_TOP))
2409 c->c2.did_open_tun = do_open_tun (c);
2411 /* print MTU info */
2412 do_print_data_channel_mtu_parms (c);
2414 #ifdef ENABLE_OCC
2415 /* get local and remote options compatibility strings */
2416 if (c->mode == CM_P2P || child)
2417 do_compute_occ_strings (c);
2418 #endif
2420 /* initialize output speed limiter */
2421 if (c->mode == CM_P2P)
2422 do_init_traffic_shaper (c);
2424 /* do one-time inits, and possibily become a daemon here */
2425 do_init_first_time (c);
2428 * Actually do UID/GID downgrade, and chroot, if requested.
2429 * May be delayed by --client, --pull, or --up-delay.
2431 do_uid_gid_chroot (c, c->c2.did_open_tun);
2433 /* finalize the TCP/UDP socket */
2434 if (c->mode == CM_P2P || c->mode == CM_TOP || c->mode == CM_CHILD_TCP)
2435 do_init_socket_2 (c);
2437 /* initialize timers */
2438 if (c->mode == CM_P2P || child)
2439 do_init_timers (c, false);
2441 /* Check for signals */
2442 if (IS_SIG (c))
2443 goto sig;
2445 return;
2447 sig:
2448 c->sig->signal_text = "init_instance";
2449 close_context (c, -1, flags);
2450 return;
2454 * Close a tunnel instance.
2456 void
2457 close_instance (struct context *c)
2459 /* close event objects */
2460 do_close_event_set (c);
2462 if (c->mode == CM_P2P
2463 || c->mode == CM_CHILD_TCP
2464 || c->mode == CM_CHILD_UDP
2465 || c->mode == CM_TOP)
2467 /* if xinetd/inetd mode, don't allow restart */
2468 do_close_check_if_restart_permitted (c);
2470 #ifdef USE_LZO
2471 if (c->options.comp_lzo)
2472 lzo_compress_uninit (&c->c2.lzo_compwork);
2473 #endif
2475 /* free buffers */
2476 do_close_free_buf (c);
2478 /* close TLS */
2479 do_close_tls (c);
2481 /* free key schedules */
2482 do_close_free_key_schedule (c, (c->mode == CM_P2P || c->mode == CM_TOP));
2484 /* close TCP/UDP connection */
2485 do_close_link_socket (c);
2487 /* close TUN/TAP device */
2488 do_close_tun (c, false);
2490 /* call plugin close functions and unload */
2491 do_close_plugins (c);
2493 /* close packet-id persistance file */
2494 do_close_packet_id (c);
2496 /* close --status file */
2497 do_close_status_output (c);
2499 #ifdef ENABLE_FRAGMENT
2500 /* close fragmentation handler */
2501 do_close_fragment (c);
2502 #endif
2504 /* close --ifconfig-pool-persist obj */
2505 do_close_ifconfig_pool_persist (c);
2507 /* garbage collect */
2508 gc_free (&c->c2.gc);
2512 void
2513 inherit_context_child (struct context *dest,
2514 const struct context *src)
2516 CLEAR (*dest);
2518 switch (src->options.proto)
2520 case PROTO_UDPv4:
2521 dest->mode = CM_CHILD_UDP;
2522 break;
2523 case PROTO_TCPv4_SERVER:
2524 dest->mode = CM_CHILD_TCP;
2525 break;
2526 default:
2527 ASSERT (0);
2530 dest->gc = gc_new ();
2532 ALLOC_OBJ_CLEAR_GC (dest->sig, struct signal_info, &dest->gc);
2534 /* c1 init */
2535 packet_id_persist_init (&dest->c1.pid_persist);
2537 #ifdef USE_CRYPTO
2538 dest->c1.ks.key_type = src->c1.ks.key_type;
2539 #ifdef USE_SSL
2540 /* inherit SSL context */
2541 dest->c1.ks.ssl_ctx = src->c1.ks.ssl_ctx;
2542 dest->c1.ks.tls_auth_key = src->c1.ks.tls_auth_key;
2543 #endif
2544 #endif
2546 /* options */
2547 dest->options = src->options;
2548 options_detach (&dest->options);
2550 if (dest->mode == CM_CHILD_TCP)
2553 * The CM_TOP context does the socket listen(),
2554 * and the CM_CHILD_TCP context does the accept().
2556 dest->c2.accept_from = src->c2.link_socket;
2559 /* inherit plugins */
2560 dest->c1.plugins = src->c1.plugins;
2562 /* context init */
2563 init_instance (dest, src->c2.es, CC_NO_CLOSE | CC_USR1_TO_HUP);
2564 if (IS_SIG (dest))
2565 return;
2567 /* inherit tun/tap interface object */
2568 dest->c1.tuntap = src->c1.tuntap;
2570 /* UDP inherits some extra things which TCP does not */
2571 if (dest->mode == CM_CHILD_UDP)
2573 /* inherit buffers */
2574 dest->c2.buffers = src->c2.buffers;
2576 /* inherit parent link_socket and tuntap */
2577 dest->c2.link_socket = src->c2.link_socket;
2579 ALLOC_OBJ_GC (dest->c2.link_socket_info, struct link_socket_info, &dest->gc);
2580 *dest->c2.link_socket_info = src->c2.link_socket->info;
2582 /* locally override some link_socket_info fields */
2583 dest->c2.link_socket_info->lsa = &dest->c1.link_socket_addr;
2584 dest->c2.link_socket_info->connection_established = false;
2588 void
2589 inherit_context_top (struct context *dest,
2590 const struct context *src)
2592 /* copy parent */
2593 *dest = *src;
2596 * CM_TOP_CLONE will prevent close_instance from freeing or closing
2597 * resources owned by the parent.
2599 * Also note that CM_TOP_CLONE context objects are
2600 * closed by multi_top_free in multi.c.
2602 dest->mode = CM_TOP_CLONE;
2604 dest->first_time = false;
2605 dest->c0 = NULL;
2607 options_detach (&dest->options);
2608 gc_detach (&dest->gc);
2609 gc_detach (&dest->c2.gc);
2611 #if defined(USE_CRYPTO) && defined(USE_SSL)
2612 dest->c2.tls_multi = NULL;
2613 #endif
2615 dest->c1.tuntap_owned = false;
2616 dest->c1.status_output_owned = false;
2617 #if P2MP_SERVER
2618 dest->c1.ifconfig_pool_persist_owned = false;
2619 #endif
2620 dest->c2.event_set_owned = false;
2621 dest->c2.link_socket_owned = false;
2622 dest->c2.buffers_owned = false;
2624 dest->c2.event_set = NULL;
2625 if (src->options.proto == PROTO_UDPv4)
2626 do_event_set_init (dest, false);
2629 void
2630 close_context (struct context *c, int sig, unsigned int flags)
2632 ASSERT (c);
2633 ASSERT (c->sig);
2635 if (sig >= 0)
2636 c->sig->signal_received = sig;
2638 if (c->sig->signal_received == SIGUSR1)
2640 if ((flags & CC_USR1_TO_HUP)
2641 || (c->sig->hard && (flags & CC_HARD_USR1_TO_HUP)))
2642 c->sig->signal_received = SIGHUP;
2645 if (!(flags & CC_NO_CLOSE))
2646 close_instance (c);
2648 if (flags & CC_GC_FREE)
2649 context_gc_free (c);
2652 #ifdef USE_CRYPTO
2654 static void
2655 test_malloc (void)
2657 int i, j;
2658 msg (M_INFO, "Multithreaded malloc test...");
2659 for (i = 0; i < 25; ++i)
2661 struct gc_arena gc = gc_new ();
2662 const int limit = get_random () & 0x03FF;
2663 for (j = 0; j < limit; ++j)
2665 gc_malloc (get_random () & 0x03FF, false, &gc);
2667 gc_free (&gc);
2672 * Do a loopback test
2673 * on the crypto subsystem.
2675 static void *
2676 test_crypto_thread (void *arg)
2678 struct context *c = (struct context *) arg;
2679 const struct options *options = &c->options;
2680 #if defined(USE_PTHREAD)
2681 struct context *child = NULL;
2682 openvpn_thread_t child_id = 0;
2683 #endif
2685 ASSERT (options->test_crypto);
2686 init_verb_mute (c, IVM_LEVEL_1);
2687 context_init_1 (c);
2688 do_init_crypto_static (c, 0);
2690 #if defined(USE_PTHREAD)
2692 if (c->first_time && options->n_threads > 1)
2694 if (options->n_threads > 2)
2695 msg (M_FATAL, "ERROR: --test-crypto option only works with --threads set to 1 or 2");
2696 openvpn_thread_init ();
2697 ALLOC_OBJ (child, struct context);
2698 context_clear (child);
2699 child->options = *options;
2700 options_detach (&child->options);
2701 child->first_time = false;
2702 child_id = openvpn_thread_create (test_crypto_thread, (void *) child);
2705 #endif
2706 frame_finalize_options (c, options);
2708 #if defined(USE_PTHREAD)
2709 if (options->n_threads == 2)
2710 test_malloc ();
2711 #endif
2713 test_crypto (&c->c2.crypto_options, &c->c2.frame);
2715 key_schedule_free (&c->c1.ks, true);
2716 packet_id_free (&c->c2.packet_id);
2718 #if defined(USE_PTHREAD)
2719 if (c->first_time && options->n_threads > 1)
2720 openvpn_thread_join (child_id);
2721 if (child)
2722 free (child);
2723 #endif
2724 context_gc_free (c);
2725 return NULL;
2728 #endif
2730 bool
2731 do_test_crypto (const struct options *o)
2733 #ifdef USE_CRYPTO
2734 if (o->test_crypto)
2736 struct context c;
2738 /* print version number */
2739 msg (M_INFO, "%s", title_string);
2741 context_clear (&c);
2742 c.options = *o;
2743 options_detach (&c.options);
2744 c.first_time = true;
2745 test_crypto_thread ((void *) &c);
2746 return true;
2748 #endif
2749 return false;