Update to OpenVPN 2.1rc18
[tomato.git] / release / src / router / openvpn / init.c
blobc94cfe25d518cedfa38c645eda506586c4b1811b
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-2009 OpenVPN Technologies, Inc. <sales@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 #include "syshead.h"
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"
35 #include "pkcs11.h"
36 #include "ps.h"
37 #include "lladdr.h"
38 #include "ping.h"
40 #include "memdbg.h"
42 #include "occ-inline.h"
45 * Crypto initialization flags
47 #define CF_LOAD_PERSISTED_PACKET_ID (1<<0)
48 #define CF_INIT_TLS_MULTI (1<<1)
49 #define CF_INIT_TLS_AUTH_STANDALONE (1<<2)
51 static void do_init_first_time (struct context *c);
53 void
54 context_clear (struct context *c)
56 CLEAR (*c);
59 void
60 context_clear_1 (struct context *c)
62 CLEAR (c->c1);
65 void
66 context_clear_2 (struct context *c)
68 CLEAR (c->c2);
71 void
72 context_clear_all_except_first_time (struct context *c)
74 const bool first_time_save = c->first_time;
75 const struct context_persist cpsave = c->persist;
76 context_clear (c);
77 c->first_time = first_time_save;
78 c->persist = cpsave;
82 * Should be called after options->ce is modified at the top
83 * of a SIGUSR1 restart.
85 static void
86 update_options_ce_post (struct options *options)
88 #if P2MP
90 * In pull mode, we usually import --ping/--ping-restart parameters from
91 * the server. However we should also set an initial default --ping-restart
92 * for the period of time before we pull the --ping-restart parameter
93 * from the server.
95 if (options->pull
96 && options->ping_rec_timeout_action == PING_UNDEF
97 && options->ce.proto == PROTO_UDPv4)
99 options->ping_rec_timeout = PRE_PULL_INITIAL_PING_RESTART;
100 options->ping_rec_timeout_action = PING_RESTART;
102 #endif
103 #ifdef USE_CRYPTO
105 * Don't use replay window for TCP mode (i.e. require that packets be strictly in sequence).
107 if (link_socket_proto_connection_oriented (options->ce.proto))
108 options->replay_window = options->replay_time = 0;
109 #endif
113 * Initialize and possibly randomize connection list.
115 static void
116 init_connection_list (struct context *c)
118 #ifdef ENABLE_CONNECTION
119 struct connection_list *l = c->options.connection_list;
120 if (l)
122 l->current = -1;
123 if (c->options.remote_random)
125 int i;
126 for (i = 0; i < l->len; ++i)
128 const int j = get_random () % l->len;
129 if (i != j)
131 struct connection_entry *tmp;
132 tmp = l->array[i];
133 l->array[i] = l->array[j];
134 l->array[j] = tmp;
139 #endif
143 * Increment to next connection entry
145 static void
146 next_connection_entry (struct context *c)
148 #ifdef ENABLE_CONNECTION
149 struct connection_list *l = c->options.connection_list;
150 if (l)
152 if (l->no_advance && l->current >= 0)
154 l->no_advance = false;
156 else
158 int i;
159 if (++l->current >= l->len)
160 l->current = 0;
162 dmsg (D_CONNECTION_LIST, "CONNECTION_LIST len=%d current=%d",
163 l->len, l->current);
164 for (i = 0; i < l->len; ++i)
166 dmsg (D_CONNECTION_LIST, "[%d] %s:%d",
168 l->array[i]->remote,
169 l->array[i]->remote_port);
172 c->options.ce = *l->array[l->current];
174 #endif
175 update_options_ce_post (&c->options);
179 * Query for private key and auth-user-pass username/passwords
181 static void
182 init_query_passwords (struct context *c)
184 #if defined(USE_CRYPTO) && defined(USE_SSL)
185 /* Certificate password input */
186 if (c->options.key_pass_file)
187 pem_password_setup (c->options.key_pass_file);
188 #endif
190 #if P2MP
191 /* Auth user/pass input */
192 if (c->options.auth_user_pass_file)
193 auth_user_pass_setup (c->options.auth_user_pass_file);
194 #endif
198 * Initialize/Uninitialize HTTP or SOCKS proxy
201 #ifdef GENERAL_PROXY_SUPPORT
203 static int
204 proxy_scope (struct context *c)
206 return connection_list_defined (&c->options) ? 2 : 1;
209 static void
210 uninit_proxy_dowork (struct context *c)
212 #ifdef ENABLE_HTTP_PROXY
213 if (c->c1.http_proxy_owned && c->c1.http_proxy)
215 http_proxy_close (c->c1.http_proxy);
216 c->c1.http_proxy = NULL;
217 c->c1.http_proxy_owned = false;
219 #endif
220 #ifdef ENABLE_SOCKS
221 if (c->c1.socks_proxy_owned && c->c1.socks_proxy)
223 socks_proxy_close (c->c1.socks_proxy);
224 c->c1.socks_proxy = NULL;
225 c->c1.socks_proxy_owned = false;
227 #endif
230 static void
231 init_proxy_dowork (struct context *c)
233 #ifdef ENABLE_HTTP_PROXY
234 bool did_http = false;
235 #else
236 const bool did_http = false;
237 #endif
239 uninit_proxy_dowork (c);
241 #ifdef ENABLE_HTTP_PROXY
242 if (c->options.ce.http_proxy_options || c->options.auto_proxy_info)
244 /* Possible HTTP proxy user/pass input */
245 c->c1.http_proxy = http_proxy_new (c->options.ce.http_proxy_options,
246 c->options.auto_proxy_info);
247 if (c->c1.http_proxy)
249 did_http = true;
250 c->c1.http_proxy_owned = true;
253 #endif
255 #ifdef ENABLE_SOCKS
256 if (!did_http && (c->options.ce.socks_proxy_server || c->options.auto_proxy_info))
258 c->c1.socks_proxy = socks_proxy_new (c->options.ce.socks_proxy_server,
259 c->options.ce.socks_proxy_port,
260 c->options.ce.socks_proxy_retry,
261 c->options.auto_proxy_info);
262 if (c->c1.socks_proxy)
264 c->c1.socks_proxy_owned = true;
267 #endif
270 static void
271 init_proxy (struct context *c, const int scope)
273 if (scope == proxy_scope (c))
274 init_proxy_dowork (c);
277 static void
278 uninit_proxy (struct context *c)
280 if (c->sig->signal_received != SIGUSR1 || proxy_scope (c) == 2)
281 uninit_proxy_dowork (c);
284 #else
286 static inline void
287 init_proxy (struct context *c, const int scope)
291 static inline void
292 uninit_proxy (struct context *c)
296 #endif
298 void
299 context_init_1 (struct context *c)
301 context_clear_1 (c);
303 packet_id_persist_init (&c->c1.pid_persist);
305 init_connection_list (c);
307 init_query_passwords (c);
309 #if defined(ENABLE_PKCS11)
310 if (c->first_time) {
311 int i;
312 pkcs11_initialize (true, c->options.pkcs11_pin_cache_period);
313 for (i=0;i<MAX_PARMS && c->options.pkcs11_providers[i] != NULL;i++)
314 pkcs11_addProvider (c->options.pkcs11_providers[i], c->options.pkcs11_protected_authentication[i],
315 c->options.pkcs11_private_mode[i], c->options.pkcs11_cert_private[i]);
317 #endif
319 #if 0 /* test get_user_pass with GET_USER_PASS_NEED_OK flag */
322 * In the management interface, you can okay the request by entering "needok token-insertion-request ok"
324 struct user_pass up;
325 CLEAR (up);
326 strcpy (up.username, "Please insert your cryptographic token"); /* put the high-level message in up.username */
327 get_user_pass (&up, NULL, "token-insertion-request", GET_USER_PASS_MANAGEMENT|GET_USER_PASS_NEED_OK);
328 msg (M_INFO, "RET:%s", up.password); /* will return the third argument to management interface
329 'needok' command, usually 'ok' or 'cancel'. */
331 #endif
333 /* initialize HTTP or SOCKS proxy object at scope level 1 */
334 init_proxy (c, 1);
337 void
338 context_gc_free (struct context *c)
340 gc_free (&c->c2.gc);
341 gc_free (&c->options.gc);
342 gc_free (&c->gc);
345 #if PORT_SHARE
347 static void
348 close_port_share (void)
350 if (port_share)
352 port_share_close (port_share);
353 port_share = NULL;
357 static void
358 init_port_share (struct context *c)
360 if (!port_share && (c->options.port_share_host && c->options.port_share_port))
362 port_share = port_share_open (c->options.port_share_host,
363 c->options.port_share_port);
364 if (port_share == NULL)
365 msg (M_FATAL, "Fatal error: Port sharing failed");
369 #endif
371 bool
372 init_static (void)
374 /* configure_path (); */
376 #if defined(USE_CRYPTO) && defined(DMALLOC)
377 openssl_dmalloc_init ();
378 #endif
380 init_random_seed (); /* init random() function, only used as
381 source for weak random numbers */
382 error_reset (); /* initialize error.c */
383 reset_check_status (); /* initialize status check code in socket.c */
385 #ifdef WIN32
386 init_win32 ();
387 #endif
389 #ifdef OPENVPN_DEBUG_COMMAND_LINE
391 int i;
392 for (i = 0; i < argc; ++i)
393 msg (M_INFO, "argv[%d] = '%s'", i, argv[i]);
395 #endif
397 update_time ();
399 #ifdef USE_CRYPTO
400 init_ssl_lib ();
402 /* init PRNG used for IV generation */
403 /* When forking, copy this to more places in the code to avoid fork
404 random-state predictability */
405 prng_init (NULL, 0);
406 #endif
408 #ifdef PID_TEST
409 packet_id_interactive_test (); /* test the sequence number code */
410 return false;
411 #endif
413 #ifdef SCHEDULE_TEST
414 schedule_test ();
415 return false;
416 #endif
418 #ifdef LIST_TEST
419 list_test ();
420 return false;
421 #endif
423 #ifdef IFCONFIG_POOL_TEST
424 ifconfig_pool_test (0x0A010004, 0x0A0100FF);
425 return false;
426 #endif
428 #ifdef CHARACTER_CLASS_DEBUG
429 character_class_debug ();
430 return false;
431 #endif
433 #ifdef EXTRACT_X509_FIELD_TEST
434 extract_x509_field_test ();
435 return false;
436 #endif
438 #ifdef TIME_TEST
439 time_test ();
440 return false;
441 #endif
443 #ifdef GEN_PATH_TEST
445 struct gc_arena gc = gc_new ();
446 const char *fn = gen_path ("foo",
447 "bar",
448 &gc);
449 printf ("%s\n", fn);
450 gc_free (&gc);
452 return false;
453 #endif
455 #ifdef STATUS_PRINTF_TEST
457 struct gc_arena gc = gc_new ();
458 const char *tmp_file = create_temp_filename ("/tmp", "foo", &gc);
459 struct status_output *so = status_open (tmp_file, 0, -1, NULL, STATUS_OUTPUT_WRITE);
460 status_printf (so, "%s", "foo");
461 status_printf (so, "%s", "bar");
462 if (!status_close (so))
463 msg (M_WARN, "STATUS_PRINTF_TEST: %s: write error", tmp_file);
464 gc_free (&gc);
466 return false;
467 #endif
469 #ifdef ARGV_TEST
471 void argv_test (void);
472 argv_test ();
473 return false;
475 #endif
477 #ifdef PRNG_TEST
479 struct gc_arena gc = gc_new ();
480 uint8_t rndbuf[8];
481 int i;
482 prng_init ("sha1", 16);
483 //prng_init (NULL, 0);
484 const int factor = 1;
485 for (i = 0; i < factor * 8; ++i)
487 #if 1
488 prng_bytes (rndbuf, sizeof (rndbuf));
489 #else
490 ASSERT(RAND_bytes (rndbuf, sizeof (rndbuf)));
491 #endif
492 printf ("[%d] %s\n", i, format_hex (rndbuf, sizeof (rndbuf), 0, &gc));
494 gc_free (&gc);
495 prng_uninit ();
496 return false;
498 #endif
500 return true;
503 void
504 uninit_static (void)
506 openvpn_thread_cleanup ();
508 #ifdef USE_CRYPTO
509 free_ssl_lib ();
510 #endif
512 #ifdef ENABLE_PKCS11
513 pkcs11_terminate ();
514 #endif
516 #if PORT_SHARE
517 close_port_share ();
518 #endif
520 #if defined(MEASURE_TLS_HANDSHAKE_STATS) && defined(USE_CRYPTO) && defined(USE_SSL)
521 show_tls_performance_stats ();
522 #endif
525 void
526 init_verb_mute (struct context *c, unsigned int flags)
528 if (flags & IVM_LEVEL_1)
530 /* set verbosity and mute levels */
531 set_check_status (D_LINK_ERRORS, D_READ_WRITE);
532 set_debug_level (c->options.verbosity, SDL_CONSTRAIN);
533 set_mute_cutoff (c->options.mute);
536 /* special D_LOG_RW mode */
537 if (flags & IVM_LEVEL_2)
538 c->c2.log_rw = (check_debug_level (D_LOG_RW) && !check_debug_level (D_LOG_RW + 1));
542 * Possibly set --dev based on --dev-node.
543 * For example, if --dev-node /tmp/foo/tun, and --dev undefined,
544 * set --dev to tun.
546 void
547 init_options_dev (struct options *options)
549 if (!options->dev)
550 options->dev = openvpn_basename (options->dev_node);
553 bool
554 print_openssl_info (const struct options *options)
557 * OpenSSL info print mode?
559 #ifdef USE_CRYPTO
560 if (options->show_ciphers || options->show_digests || options->show_engines
561 #ifdef USE_SSL
562 || options->show_tls_ciphers
563 #endif
566 if (options->show_ciphers)
567 show_available_ciphers ();
568 if (options->show_digests)
569 show_available_digests ();
570 if (options->show_engines)
571 show_available_engines ();
572 #ifdef USE_SSL
573 if (options->show_tls_ciphers)
574 show_available_tls_ciphers ();
575 #endif
576 return true;
578 #endif
579 return false;
583 * Static pre-shared key generation mode?
585 bool
586 do_genkey (const struct options * options)
588 #ifdef USE_CRYPTO
589 if (options->genkey)
591 int nbits_written;
593 notnull (options->shared_secret_file,
594 "shared secret output file (--secret)");
596 if (options->mlock) /* should we disable paging? */
597 do_mlockall (true);
599 nbits_written = write_key_file (2, options->shared_secret_file);
601 msg (D_GENKEY | M_NOPREFIX,
602 "Randomly generated %d bit key written to %s", nbits_written,
603 options->shared_secret_file);
604 return true;
606 #endif
607 return false;
611 * Persistent TUN/TAP device management mode?
613 bool
614 do_persist_tuntap (const struct options *options)
616 #ifdef TUNSETPERSIST
617 if (options->persist_config)
619 /* sanity check on options for --mktun or --rmtun */
620 notnull (options->dev, "TUN/TAP device (--dev)");
621 if (options->ce.remote || options->ifconfig_local
622 || options->ifconfig_remote_netmask
623 #ifdef USE_CRYPTO
624 || options->shared_secret_file
625 #ifdef USE_SSL
626 || options->tls_server || options->tls_client
627 #endif
628 #endif
630 msg (M_FATAL|M_OPTERR,
631 "options --mktun or --rmtun should only be used together with --dev");
632 tuncfg (options->dev, options->dev_type, options->dev_node,
633 options->tun_ipv6, options->persist_mode,
634 options->username, options->groupname, &options->tuntap_options);
635 if (options->persist_mode && options->lladdr)
636 set_lladdr(options->dev, options->lladdr, NULL);
637 return true;
639 #endif
640 return false;
644 * Should we become a daemon?
645 * Return true if we did it.
647 static bool
648 possibly_become_daemon (const struct options *options, const bool first_time)
650 bool ret = false;
651 if (first_time && options->daemon)
653 ASSERT (!options->inetd);
654 if (daemon (options->cd_dir != NULL, options->log) < 0)
655 msg (M_ERR, "daemon() failed");
656 restore_signal_state ();
657 if (options->log)
658 set_std_files_to_null (true);
660 #if defined(ENABLE_PKCS11)
661 pkcs11_forkFixup ();
662 #endif
664 ret = true;
666 return ret;
670 * Actually do UID/GID downgrade, and chroot, if requested.
672 static void
673 do_uid_gid_chroot (struct context *c, bool no_delay)
675 static const char why_not[] = "will be delayed because of --client, --pull, or --up-delay";
676 struct context_0 *c0 = c->c0;
678 if (c->first_time && c0 && !c0->uid_gid_set)
680 /* chroot if requested */
681 if (c->options.chroot_dir)
683 if (no_delay)
684 do_chroot (c->options.chroot_dir);
685 else
686 msg (M_INFO, "NOTE: chroot %s", why_not);
689 /* set user and/or group that we want to setuid/setgid to */
690 if (no_delay)
692 set_group (&c0->group_state);
693 set_user (&c0->user_state);
694 c0->uid_gid_set = true;
696 else if (c0->uid_gid_specified)
698 msg (M_INFO, "NOTE: UID/GID downgrade %s", why_not);
704 * Return common name in a way that is formatted for
705 * prepending to msg() output.
707 const char *
708 format_common_name (struct context *c, struct gc_arena *gc)
710 struct buffer out = alloc_buf_gc (256, gc);
711 #if defined(USE_CRYPTO) && defined(USE_SSL)
712 if (c->c2.tls_multi)
714 buf_printf (&out, "[%s] ", tls_common_name (c->c2.tls_multi, false));
716 #endif
717 return BSTR (&out);
720 void
721 pre_setup (const struct options *options)
723 #ifdef WIN32
724 if (options->exit_event_name)
726 win32_signal_open (&win32_signal,
727 WSO_FORCE_SERVICE,
728 options->exit_event_name,
729 options->exit_event_initial_state);
731 else
733 win32_signal_open (&win32_signal,
734 WSO_FORCE_CONSOLE,
735 NULL,
736 false);
738 /* put a title on the top window bar */
739 if (win32_signal.mode == WSO_MODE_CONSOLE)
741 window_title_save (&window_title);
742 window_title_generate (options->config);
745 #endif
748 void
749 reset_coarse_timers (struct context *c)
751 c->c2.coarse_timer_wakeup = 0;
755 * Initialize timers
757 static void
758 do_init_timers (struct context *c, bool deferred)
760 update_time ();
761 reset_coarse_timers (c);
763 /* initialize inactivity timeout */
764 if (c->options.inactivity_timeout)
765 event_timeout_init (&c->c2.inactivity_interval, c->options.inactivity_timeout, now);
767 /* initialize pings */
769 if (c->options.ping_send_timeout)
770 event_timeout_init (&c->c2.ping_send_interval, c->options.ping_send_timeout, 0);
772 if (c->options.ping_rec_timeout)
773 event_timeout_init (&c->c2.ping_rec_interval, c->options.ping_rec_timeout, now);
775 if (!deferred)
777 /* initialize connection establishment timer */
778 event_timeout_init (&c->c2.wait_for_connect, 1, now);
780 #ifdef ENABLE_OCC
781 /* initialize occ timers */
783 if (c->options.occ
784 && !TLS_MODE (c)
785 && c->c2.options_string_local && c->c2.options_string_remote)
786 event_timeout_init (&c->c2.occ_interval, OCC_INTERVAL_SECONDS, now);
788 if (c->options.mtu_test)
789 event_timeout_init (&c->c2.occ_mtu_load_test_interval, OCC_MTU_LOAD_INTERVAL_SECONDS, now);
790 #endif
792 /* initialize packet_id persistence timer */
793 #ifdef USE_CRYPTO
794 if (c->options.packet_id_file)
795 event_timeout_init (&c->c2.packet_id_persist_interval, 60, now);
796 #endif
798 #if defined(USE_CRYPTO) && defined(USE_SSL)
799 /* initialize tmp_int optimization that limits the number of times we call
800 tls_multi_process in the main event loop */
801 interval_init (&c->c2.tmp_int, TLS_MULTI_HORIZON, TLS_MULTI_REFRESH);
802 #endif
807 * Initialize traffic shaper.
809 static void
810 do_init_traffic_shaper (struct context *c)
812 #ifdef HAVE_GETTIMEOFDAY
813 /* initialize traffic shaper (i.e. transmit bandwidth limiter) */
814 if (c->options.shaper)
816 shaper_init (&c->c2.shaper, c->options.shaper);
817 shaper_msg (&c->c2.shaper);
819 #endif
823 * Allocate a route list structure if at least one
824 * --route option was specified.
826 static void
827 do_alloc_route_list (struct context *c)
829 if (c->options.routes && !c->c1.route_list)
830 c->c1.route_list = new_route_list (&c->gc);
835 * Initialize the route list, resolving any DNS names in route
836 * options and saving routes in the environment.
838 static void
839 do_init_route_list (const struct options *options,
840 struct route_list *route_list,
841 const struct link_socket_info *link_socket_info,
842 bool fatal,
843 struct env_set *es)
845 const char *gw = NULL;
846 int dev = dev_type_enum (options->dev, options->dev_type);
847 int metric = 0;
849 if (dev == DEV_TYPE_TUN && (options->topology == TOP_NET30 || options->topology == TOP_P2P))
850 gw = options->ifconfig_remote_netmask;
851 if (options->route_default_gateway)
852 gw = options->route_default_gateway;
853 if (options->route_default_metric)
854 metric = options->route_default_metric;
856 if (!init_route_list (route_list,
857 options->routes,
859 metric,
860 link_socket_current_remote (link_socket_info),
861 es))
863 if (fatal)
864 openvpn_exit (OPENVPN_EXIT_STATUS_ERROR); /* exit point */
866 else
868 /* copy routes to environment */
869 setenv_routes (es, route_list);
874 * Called after all initialization has been completed.
876 void
877 initialization_sequence_completed (struct context *c, const unsigned int flags)
879 static const char message[] = "Initialization Sequence Completed";
881 /* If we delayed UID/GID downgrade or chroot, do it now */
882 do_uid_gid_chroot (c, true);
884 /* Test if errors */
885 if (flags & ISC_ERRORS)
887 #ifdef WIN32
888 show_routes (M_INFO|M_NOPREFIX);
889 show_adapters (M_INFO|M_NOPREFIX);
890 msg (M_INFO, "%s With Errors ( see http://openvpn.net/faq.html#dhcpclientserv )", message);
891 #else
892 msg (M_INFO, "%s With Errors", message);
893 #endif
895 else
896 msg (M_INFO, "%s", message);
898 /* Flag connection_list that we initialized */
899 if ((flags & (ISC_ERRORS|ISC_SERVER)) == 0 && connection_list_defined (&c->options))
900 connection_list_set_no_advance (&c->options);
902 #ifdef ENABLE_MANAGEMENT
903 /* Tell management interface that we initialized */
904 if (management)
906 in_addr_t tun_local = 0;
907 in_addr_t tun_remote = 0; /* FKS */
908 const char *detail = "SUCCESS";
909 if (c->c1.tuntap)
910 tun_local = c->c1.tuntap->local;
911 tun_remote = htonl (c->c1.link_socket_addr.actual.dest.sa.sin_addr.s_addr);
912 if (flags & ISC_ERRORS)
913 detail = "ERROR";
914 management_set_state (management,
915 OPENVPN_STATE_CONNECTED,
916 detail,
917 tun_local,
918 tun_remote);
919 if (tun_local)
920 management_post_tunnel_open (management, tun_local);
922 #endif
927 * Possibly add routes and/or call route-up script
928 * based on options.
930 void
931 do_route (const struct options *options,
932 struct route_list *route_list,
933 const struct tuntap *tt,
934 const struct plugin_list *plugins,
935 struct env_set *es)
937 if (!options->route_noexec && route_list)
938 add_routes (route_list, tt, ROUTE_OPTION_FLAGS (options), es);
940 if (plugin_defined (plugins, OPENVPN_PLUGIN_ROUTE_UP))
942 if (plugin_call (plugins, OPENVPN_PLUGIN_ROUTE_UP, NULL, NULL, es) != OPENVPN_PLUGIN_FUNC_SUCCESS)
943 msg (M_WARN, "WARNING: route-up plugin call failed");
946 if (options->route_script)
948 struct argv argv = argv_new ();
949 setenv_str (es, "script_type", "route-up");
950 argv_printf (&argv, "%sc", options->route_script);
951 openvpn_execve_check (&argv, es, S_SCRIPT, "Route script failed");
952 argv_reset (&argv);
955 #ifdef WIN32
956 if (options->show_net_up)
958 show_routes (M_INFO|M_NOPREFIX);
959 show_adapters (M_INFO|M_NOPREFIX);
961 else if (check_debug_level (D_SHOW_NET))
963 show_routes (D_SHOW_NET|M_NOPREFIX);
964 show_adapters (D_SHOW_NET|M_NOPREFIX);
966 #endif
970 * Save current pulled options string in the c1 context store, so we can
971 * compare against it after possible future restarts.
973 #if P2MP
974 static void
975 save_pulled_options_string (struct context *c, const char *newstring)
977 if (c->c1.pulled_options_string_save)
978 free (c->c1.pulled_options_string_save);
980 c->c1.pulled_options_string_save = NULL;
982 if (newstring)
983 c->c1.pulled_options_string_save = string_alloc (newstring, NULL);
985 #endif
988 * initialize tun/tap device object
990 static void
991 do_init_tun (struct context *c)
993 c->c1.tuntap = init_tun (c->options.dev,
994 c->options.dev_type,
995 c->options.topology,
996 c->options.ifconfig_local,
997 c->options.ifconfig_remote_netmask,
998 addr_host (&c->c1.link_socket_addr.local),
999 addr_host (&c->c1.link_socket_addr.remote),
1000 !c->options.ifconfig_nowarn,
1001 c->c2.es);
1003 init_tun_post (c->c1.tuntap,
1004 &c->c2.frame,
1005 &c->options.tuntap_options);
1007 c->c1.tuntap_owned = true;
1011 * Open tun/tap device, ifconfig, call up script, etc.
1014 static bool
1015 do_open_tun (struct context *c)
1017 struct gc_arena gc = gc_new ();
1018 bool ret = false;
1020 c->c2.ipv4_tun = (!c->options.tun_ipv6
1021 && is_dev_type (c->options.dev, c->options.dev_type, "tun"));
1023 if (!c->c1.tuntap)
1025 /* initialize (but do not open) tun/tap object */
1026 do_init_tun (c);
1028 /* allocate route list structure */
1029 do_alloc_route_list (c);
1031 /* parse and resolve the route option list */
1032 if (c->options.routes && c->c1.route_list && c->c2.link_socket)
1033 do_init_route_list (&c->options, c->c1.route_list, &c->c2.link_socket->info, false, c->c2.es);
1035 /* do ifconfig */
1036 if (!c->options.ifconfig_noexec
1037 && ifconfig_order () == IFCONFIG_BEFORE_TUN_OPEN)
1039 /* guess actual tun/tap unit number that will be returned
1040 by open_tun */
1041 const char *guess = guess_tuntap_dev (c->options.dev,
1042 c->options.dev_type,
1043 c->options.dev_node,
1044 &gc);
1045 do_ifconfig (c->c1.tuntap, guess, TUN_MTU_SIZE (&c->c2.frame), c->c2.es);
1048 /* open the tun device */
1049 open_tun (c->options.dev, c->options.dev_type, c->options.dev_node,
1050 c->options.tun_ipv6, c->c1.tuntap);
1052 /* set the hardware address */
1053 if (c->options.lladdr)
1054 set_lladdr(c->c1.tuntap->actual_name, c->options.lladdr, c->c2.es);
1056 /* do ifconfig */
1057 if (!c->options.ifconfig_noexec
1058 && ifconfig_order () == IFCONFIG_AFTER_TUN_OPEN)
1060 do_ifconfig (c->c1.tuntap, c->c1.tuntap->actual_name, TUN_MTU_SIZE (&c->c2.frame), c->c2.es);
1063 /* run the up script */
1064 run_up_down (c->options.up_script,
1065 c->plugins,
1066 OPENVPN_PLUGIN_UP,
1067 c->c1.tuntap->actual_name,
1068 TUN_MTU_SIZE (&c->c2.frame),
1069 EXPANDED_SIZE (&c->c2.frame),
1070 print_in_addr_t (c->c1.tuntap->local, IA_EMPTY_IF_UNDEF, &gc),
1071 print_in_addr_t (c->c1.tuntap->remote_netmask, IA_EMPTY_IF_UNDEF, &gc),
1072 "init",
1073 NULL,
1074 "up",
1075 c->c2.es);
1077 /* possibly add routes */
1078 if (!c->options.route_delay_defined)
1079 do_route (&c->options, c->c1.route_list, c->c1.tuntap, c->plugins, c->c2.es);
1082 * Did tun/tap driver give us an MTU?
1084 if (c->c1.tuntap->post_open_mtu)
1085 frame_set_mtu_dynamic (&c->c2.frame,
1086 c->c1.tuntap->post_open_mtu,
1087 SET_MTU_TUN | SET_MTU_UPPER_BOUND);
1089 ret = true;
1091 else
1093 msg (M_INFO, "Preserving previous TUN/TAP instance: %s",
1094 c->c1.tuntap->actual_name);
1096 /* run the up script if user specified --up-restart */
1097 if (c->options.up_restart)
1098 run_up_down (c->options.up_script,
1099 c->plugins,
1100 OPENVPN_PLUGIN_UP,
1101 c->c1.tuntap->actual_name,
1102 TUN_MTU_SIZE (&c->c2.frame),
1103 EXPANDED_SIZE (&c->c2.frame),
1104 print_in_addr_t (c->c1.tuntap->local, IA_EMPTY_IF_UNDEF, &gc),
1105 print_in_addr_t (c->c1.tuntap->remote_netmask, IA_EMPTY_IF_UNDEF, &gc),
1106 "restart",
1107 NULL,
1108 "up",
1109 c->c2.es);
1111 gc_free (&gc);
1112 return ret;
1116 * Close TUN/TAP device
1119 static void
1120 do_close_tun_simple (struct context *c)
1122 msg (D_CLOSE, "Closing TUN/TAP interface");
1123 close_tun (c->c1.tuntap);
1124 c->c1.tuntap = NULL;
1125 c->c1.tuntap_owned = false;
1126 #if P2MP
1127 save_pulled_options_string (c, NULL); /* delete C1-saved pulled_options_string */
1128 #endif
1131 static void
1132 do_close_tun (struct context *c, bool force)
1134 struct gc_arena gc = gc_new ();
1135 if (c->c1.tuntap && c->c1.tuntap_owned)
1137 const char *tuntap_actual = string_alloc (c->c1.tuntap->actual_name, &gc);
1138 const in_addr_t local = c->c1.tuntap->local;
1139 const in_addr_t remote_netmask = c->c1.tuntap->remote_netmask;
1141 if (force || !(c->sig->signal_received == SIGUSR1 && c->options.persist_tun))
1143 #ifdef ENABLE_MANAGEMENT
1144 /* tell management layer we are about to close the TUN/TAP device */
1145 if (management)
1146 management_pre_tunnel_close (management);
1147 #endif
1149 /* delete any routes we added */
1150 if (c->c1.route_list)
1151 delete_routes (c->c1.route_list, c->c1.tuntap, ROUTE_OPTION_FLAGS (&c->options), c->c2.es);
1153 /* actually close tun/tap device based on --down-pre flag */
1154 if (!c->options.down_pre)
1155 do_close_tun_simple (c);
1157 /* Run the down script -- note that it will run at reduced
1158 privilege if, for example, "--user nobody" was used. */
1159 run_up_down (c->options.down_script,
1160 c->plugins,
1161 OPENVPN_PLUGIN_DOWN,
1162 tuntap_actual,
1163 TUN_MTU_SIZE (&c->c2.frame),
1164 EXPANDED_SIZE (&c->c2.frame),
1165 print_in_addr_t (local, IA_EMPTY_IF_UNDEF, &gc),
1166 print_in_addr_t (remote_netmask, IA_EMPTY_IF_UNDEF, &gc),
1167 "init",
1168 signal_description (c->sig->signal_received,
1169 c->sig->signal_text),
1170 "down",
1171 c->c2.es);
1173 /* actually close tun/tap device based on --down-pre flag */
1174 if (c->options.down_pre)
1175 do_close_tun_simple (c);
1177 else
1179 /* run the down script on this restart if --up-restart was specified */
1180 if (c->options.up_restart)
1181 run_up_down (c->options.down_script,
1182 c->plugins,
1183 OPENVPN_PLUGIN_DOWN,
1184 tuntap_actual,
1185 TUN_MTU_SIZE (&c->c2.frame),
1186 EXPANDED_SIZE (&c->c2.frame),
1187 print_in_addr_t (local, IA_EMPTY_IF_UNDEF, &gc),
1188 print_in_addr_t (remote_netmask, IA_EMPTY_IF_UNDEF, &gc),
1189 "restart",
1190 signal_description (c->sig->signal_received,
1191 c->sig->signal_text),
1192 "down",
1193 c->c2.es);
1196 gc_free (&gc);
1200 * Handle delayed tun/tap interface bringup due to --up-delay or --pull
1203 void
1204 do_up (struct context *c, bool pulled_options, unsigned int option_types_found)
1206 if (!c->c2.do_up_ran)
1208 reset_coarse_timers (c);
1210 if (pulled_options && option_types_found)
1211 do_deferred_options (c, option_types_found);
1213 /* if --up-delay specified, open tun, do ifconfig, and run up script now */
1214 if (c->options.up_delay || PULL_DEFINED (&c->options))
1216 c->c2.did_open_tun = do_open_tun (c);
1217 update_time ();
1219 #if P2MP
1221 * Was tun interface object persisted from previous restart iteration,
1222 * and if so did pulled options string change from previous iteration?
1224 if (!c->c2.did_open_tun
1225 && PULL_DEFINED (&c->options)
1226 && c->c1.tuntap
1227 && (!c->c1.pulled_options_string_save || !c->c2.pulled_options_string
1228 || strcmp (c->c1.pulled_options_string_save, c->c2.pulled_options_string)))
1230 /* if so, close tun, delete routes, then reinitialize tun and add routes */
1231 msg (M_INFO, "NOTE: Pulled options changed on restart, will need to close and reopen TUN/TAP device.");
1232 do_close_tun (c, true);
1233 openvpn_sleep (1);
1234 c->c2.did_open_tun = do_open_tun (c);
1235 update_time ();
1237 #endif
1240 if (c->c2.did_open_tun)
1242 #if P2MP
1243 save_pulled_options_string (c, c->c2.pulled_options_string);
1244 #endif
1246 /* if --route-delay was specified, start timer */
1247 if (c->options.route_delay_defined)
1249 event_timeout_init (&c->c2.route_wakeup, c->options.route_delay, now);
1250 event_timeout_init (&c->c2.route_wakeup_expire, c->options.route_delay + c->options.route_delay_window, now);
1251 if (c->c1.tuntap)
1252 tun_standby_init (c->c1.tuntap);
1254 else
1256 initialization_sequence_completed (c, 0); /* client/p2p --route-delay undefined */
1259 else if (c->options.mode == MODE_POINT_TO_POINT)
1261 initialization_sequence_completed (c, 0); /* client/p2p restart with --persist-tun */
1264 c->c2.do_up_ran = true;
1269 * These are the option categories which will be accepted by pull.
1271 unsigned int
1272 pull_permission_mask (const struct context *c)
1274 unsigned int flags =
1275 OPT_P_UP
1276 | OPT_P_ROUTE_EXTRAS
1277 | OPT_P_IPWIN32
1278 | OPT_P_SOCKBUF
1279 | OPT_P_SOCKFLAGS
1280 | OPT_P_SETENV
1281 | OPT_P_SHAPER
1282 | OPT_P_TIMER
1283 | OPT_P_COMP
1284 | OPT_P_PERSIST
1285 | OPT_P_MESSAGES
1286 | OPT_P_EXPLICIT_NOTIFY
1287 | OPT_P_ECHO
1288 | OPT_P_PULL_MODE;
1290 if (!c->options.route_nopull)
1291 flags |= OPT_P_ROUTE;
1293 return flags;
1297 * Handle non-tun-related pulled options.
1299 void
1300 do_deferred_options (struct context *c, const unsigned int found)
1302 if (found & OPT_P_MESSAGES)
1304 init_verb_mute (c, IVM_LEVEL_1|IVM_LEVEL_2);
1305 msg (D_PUSH, "OPTIONS IMPORT: --verb and/or --mute level changed");
1307 if (found & OPT_P_TIMER)
1309 do_init_timers (c, true);
1310 msg (D_PUSH, "OPTIONS IMPORT: timers and/or timeouts modified");
1313 #ifdef ENABLE_OCC
1314 if (found & OPT_P_EXPLICIT_NOTIFY)
1316 if (c->options.ce.proto != PROTO_UDPv4 && c->options.explicit_exit_notification)
1318 msg (D_PUSH, "OPTIONS IMPORT: --explicit-exit-notify can only be used with --proto udp");
1319 c->options.explicit_exit_notification = 0;
1321 else
1322 msg (D_PUSH, "OPTIONS IMPORT: explicit notify parm(s) modified");
1324 #endif
1326 #ifdef USE_LZO
1327 if (found & OPT_P_COMP)
1329 if (lzo_defined (&c->c2.lzo_compwork))
1331 msg (D_PUSH, "OPTIONS IMPORT: LZO parms modified");
1332 lzo_modify_flags (&c->c2.lzo_compwork, c->options.lzo);
1335 #endif
1337 if (found & OPT_P_SHAPER)
1339 msg (D_PUSH, "OPTIONS IMPORT: traffic shaper enabled");
1340 do_init_traffic_shaper (c);
1343 if (found & OPT_P_SOCKBUF)
1345 msg (D_PUSH, "OPTIONS IMPORT: --sndbuf/--rcvbuf options modified");
1346 link_socket_update_buffer_sizes (c->c2.link_socket, c->options.rcvbuf, c->options.sndbuf);
1349 if (found & OPT_P_SOCKFLAGS)
1351 msg (D_PUSH, "OPTIONS IMPORT: --socket-flags option modified");
1352 link_socket_update_flags (c->c2.link_socket, c->options.sockflags);
1355 if (found & OPT_P_PERSIST)
1356 msg (D_PUSH, "OPTIONS IMPORT: --persist options modified");
1357 if (found & OPT_P_UP)
1358 msg (D_PUSH, "OPTIONS IMPORT: --ifconfig/up options modified");
1359 if (found & OPT_P_ROUTE)
1360 msg (D_PUSH, "OPTIONS IMPORT: route options modified");
1361 if (found & OPT_P_ROUTE_EXTRAS)
1362 msg (D_PUSH, "OPTIONS IMPORT: route-related options modified");
1363 if (found & OPT_P_IPWIN32)
1364 msg (D_PUSH, "OPTIONS IMPORT: --ip-win32 and/or --dhcp-option options modified");
1365 if (found & OPT_P_SETENV)
1366 msg (D_PUSH, "OPTIONS IMPORT: environment modified");
1370 * Possible hold on initialization
1372 static bool
1373 do_hold (struct context *c)
1375 #ifdef ENABLE_MANAGEMENT
1376 if (management)
1378 /* if c is defined, daemonize before hold */
1379 if (c && c->options.daemon && management_should_daemonize (management))
1380 do_init_first_time (c);
1382 /* block until management hold is released */
1383 if (management_hold (management))
1384 return true;
1386 #endif
1387 return false;
1391 * Sleep before restart.
1393 static void
1394 socket_restart_pause (struct context *c)
1396 bool proxy = false;
1397 int sec = 2;
1399 #ifdef ENABLE_HTTP_PROXY
1400 if (c->options.ce.http_proxy_options)
1401 proxy = true;
1402 #endif
1403 #ifdef ENABLE_SOCKS
1404 if (c->options.ce.socks_proxy_server)
1405 proxy = true;
1406 #endif
1408 switch (c->options.ce.proto)
1410 case PROTO_UDPv4:
1411 if (proxy)
1412 sec = c->options.ce.connect_retry_seconds;
1413 break;
1414 case PROTO_TCPv4_SERVER:
1415 sec = 1;
1416 break;
1417 case PROTO_TCPv4_CLIENT:
1418 sec = c->options.ce.connect_retry_seconds;
1419 break;
1422 #ifdef ENABLE_DEBUG
1423 if (GREMLIN_CONNECTION_FLOOD_LEVEL (c->options.gremlin))
1424 sec = 0;
1425 #endif
1427 #if P2MP
1428 if (auth_retry_get () == AR_NOINTERACT)
1429 sec = 10;
1430 #endif
1432 if (c->persist.restart_sleep_seconds > 0 && c->persist.restart_sleep_seconds > sec)
1433 sec = c->persist.restart_sleep_seconds;
1434 c->persist.restart_sleep_seconds = 0;
1436 /* do managment hold on context restart, i.e. second, third, fourth, etc. initialization */
1437 if (do_hold (NULL))
1438 sec = 0;
1440 if (sec)
1442 msg (D_RESTART, "Restart pause, %d second(s)", sec);
1443 openvpn_sleep (sec);
1448 * Do a possible pause on context_2 initialization.
1450 static void
1451 do_startup_pause (struct context *c)
1453 if (!c->first_time)
1454 socket_restart_pause (c);
1455 else
1456 do_hold (NULL); /* do management hold on first context initialization */
1460 * Finalize MTU parameters based on command line or config file options.
1462 static void
1463 frame_finalize_options (struct context *c, const struct options *o)
1465 if (!o)
1466 o = &c->options;
1469 * Set adjustment factor for buffer alignment when no
1470 * cipher is used.
1472 if (!CIPHER_ENABLED (c))
1474 frame_align_to_extra_frame (&c->c2.frame);
1475 frame_or_align_flags (&c->c2.frame,
1476 FRAME_HEADROOM_MARKER_FRAGMENT
1477 |FRAME_HEADROOM_MARKER_READ_LINK
1478 |FRAME_HEADROOM_MARKER_READ_STREAM);
1481 frame_finalize (&c->c2.frame,
1482 o->link_mtu_defined,
1483 o->link_mtu,
1484 o->tun_mtu_defined,
1485 o->tun_mtu);
1489 * Free a key schedule, including OpenSSL components.
1491 static void
1492 key_schedule_free (struct key_schedule *ks, bool free_ssl_ctx)
1494 #ifdef USE_CRYPTO
1495 free_key_ctx_bi (&ks->static_key);
1496 #ifdef USE_SSL
1497 if (ks->ssl_ctx && free_ssl_ctx)
1499 SSL_CTX_free (ks->ssl_ctx);
1500 free_key_ctx_bi (&ks->tls_auth_key);
1502 #endif /* USE_SSL */
1503 #endif /* USE_CRYPTO */
1504 CLEAR (*ks);
1507 #ifdef USE_CRYPTO
1509 static void
1510 init_crypto_pre (struct context *c, const unsigned int flags)
1512 if (c->options.engine)
1513 init_crypto_lib_engine (c->options.engine);
1515 if (flags & CF_LOAD_PERSISTED_PACKET_ID)
1517 /* load a persisted packet-id for cross-session replay-protection */
1518 if (c->options.packet_id_file)
1519 packet_id_persist_load (&c->c1.pid_persist, c->options.packet_id_file);
1522 /* Initialize crypto options */
1524 if (c->options.use_iv)
1525 c->c2.crypto_options.flags |= CO_USE_IV;
1527 if (c->options.mute_replay_warnings)
1528 c->c2.crypto_options.flags |= CO_MUTE_REPLAY_WARNINGS;
1532 * Static Key Mode (using a pre-shared key)
1534 static void
1535 do_init_crypto_static (struct context *c, const unsigned int flags)
1537 const struct options *options = &c->options;
1538 ASSERT (options->shared_secret_file);
1540 init_crypto_pre (c, flags);
1542 /* Initialize packet ID tracking */
1543 if (options->replay)
1545 packet_id_init (&c->c2.packet_id, options->replay_window,
1546 options->replay_time);
1547 c->c2.crypto_options.packet_id = &c->c2.packet_id;
1548 c->c2.crypto_options.pid_persist = &c->c1.pid_persist;
1549 c->c2.crypto_options.flags |= CO_PACKET_ID_LONG_FORM;
1550 packet_id_persist_load_obj (&c->c1.pid_persist,
1551 c->c2.crypto_options.packet_id);
1554 if (!key_ctx_bi_defined (&c->c1.ks.static_key))
1556 struct key2 key2;
1557 struct key_direction_state kds;
1559 /* Get cipher & hash algorithms */
1560 init_key_type (&c->c1.ks.key_type, options->ciphername,
1561 options->ciphername_defined, options->authname,
1562 options->authname_defined, options->keysize,
1563 options->test_crypto, true);
1565 /* Read cipher and hmac keys from shared secret file */
1567 unsigned int rkf_flags = RKF_MUST_SUCCEED;
1568 const char *rkf_file = options->shared_secret_file;
1570 #if ENABLE_INLINE_FILES
1571 if (options->shared_secret_file_inline)
1573 rkf_file = options->shared_secret_file_inline;
1574 rkf_flags |= RKF_INLINE;
1576 #endif
1577 read_key_file (&key2, rkf_file, rkf_flags);
1580 /* Check for and fix highly unlikely key problems */
1581 verify_fix_key2 (&key2, &c->c1.ks.key_type,
1582 options->shared_secret_file);
1584 /* Initialize OpenSSL key objects */
1585 key_direction_state_init (&kds, options->key_direction);
1586 must_have_n_keys (options->shared_secret_file, "secret", &key2,
1587 kds.need_keys);
1588 init_key_ctx (&c->c1.ks.static_key.encrypt, &key2.keys[kds.out_key],
1589 &c->c1.ks.key_type, DO_ENCRYPT, "Static Encrypt");
1590 init_key_ctx (&c->c1.ks.static_key.decrypt, &key2.keys[kds.in_key],
1591 &c->c1.ks.key_type, DO_DECRYPT, "Static Decrypt");
1593 /* Erase the temporary copy of key */
1594 CLEAR (key2);
1596 else
1598 msg (M_INFO, "Re-using pre-shared static key");
1601 /* Get key schedule */
1602 c->c2.crypto_options.key_ctx_bi = &c->c1.ks.static_key;
1604 /* Compute MTU parameters */
1605 crypto_adjust_frame_parameters (&c->c2.frame,
1606 &c->c1.ks.key_type,
1607 options->ciphername_defined,
1608 options->use_iv, options->replay, true);
1610 /* Sanity check on IV, sequence number, and cipher mode options */
1611 check_replay_iv_consistency (&c->c1.ks.key_type, options->replay,
1612 options->use_iv);
1615 #ifdef USE_SSL
1618 * Initialize the persistent component of OpenVPN's TLS mode,
1619 * which is preserved across SIGUSR1 resets.
1621 static void
1622 do_init_crypto_tls_c1 (struct context *c)
1624 const struct options *options = &c->options;
1626 if (!c->c1.ks.ssl_ctx)
1629 * Initialize the OpenSSL library's global
1630 * SSL context.
1632 c->c1.ks.ssl_ctx = init_ssl (options);
1633 if (!c->c1.ks.ssl_ctx)
1635 #if P2MP
1636 switch (auth_retry_get ())
1638 case AR_NONE:
1639 msg (M_FATAL, "Error: private key password verification failed");
1640 break;
1641 case AR_INTERACT:
1642 ssl_purge_auth ();
1643 case AR_NOINTERACT:
1644 c->sig->signal_received = SIGUSR1; /* SOFT-SIGUSR1 -- Password failure error */
1645 break;
1646 default:
1647 ASSERT (0);
1649 c->sig->signal_text = "private-key-password-failure";
1650 return;
1651 #else
1652 msg (M_FATAL, "Error: private key password verification failed");
1653 #endif
1656 /* Get cipher & hash algorithms */
1657 init_key_type (&c->c1.ks.key_type, options->ciphername,
1658 options->ciphername_defined, options->authname,
1659 options->authname_defined, options->keysize, true, true);
1661 /* Initialize PRNG with config-specified digest */
1662 prng_init (options->prng_hash, options->prng_nonce_secret_len);
1664 /* TLS handshake authentication (--tls-auth) */
1665 if (options->tls_auth_file)
1667 unsigned int flags = 0;
1668 const char *file = options->tls_auth_file;
1670 #if ENABLE_INLINE_FILES
1671 if (options->tls_auth_file_inline)
1673 flags |= GHK_INLINE;
1674 file = options->tls_auth_file_inline;
1676 #endif
1677 get_tls_handshake_key (&c->c1.ks.key_type,
1678 &c->c1.ks.tls_auth_key,
1679 file,
1680 options->key_direction,
1681 flags);
1684 #if 0 /* was: #if ENABLE_INLINE_FILES -- Note that enabling this code will break restarts */
1685 if (options->priv_key_file_inline)
1687 string_clear (c->options.priv_key_file_inline);
1688 c->options.priv_key_file_inline = NULL;
1690 #endif
1692 else
1694 msg (M_INFO, "Re-using SSL/TLS context");
1698 static void
1699 do_init_crypto_tls (struct context *c, const unsigned int flags)
1701 const struct options *options = &c->options;
1702 struct tls_options to;
1703 bool packet_id_long_form;
1705 ASSERT (options->tls_server || options->tls_client);
1706 ASSERT (!options->test_crypto);
1708 init_crypto_pre (c, flags);
1710 /* Make sure we are either a TLS client or server but not both */
1711 ASSERT (options->tls_server == !options->tls_client);
1713 /* initialize persistent component */
1714 do_init_crypto_tls_c1 (c);
1715 if (IS_SIG (c))
1716 return;
1718 /* Sanity check on IV, sequence number, and cipher mode options */
1719 check_replay_iv_consistency (&c->c1.ks.key_type, options->replay,
1720 options->use_iv);
1722 /* In short form, unique datagram identifier is 32 bits, in long form 64 bits */
1723 packet_id_long_form = cfb_ofb_mode (&c->c1.ks.key_type);
1725 /* Compute MTU parameters */
1726 crypto_adjust_frame_parameters (&c->c2.frame,
1727 &c->c1.ks.key_type,
1728 options->ciphername_defined,
1729 options->use_iv,
1730 options->replay, packet_id_long_form);
1731 tls_adjust_frame_parameters (&c->c2.frame);
1733 /* Set all command-line TLS-related options */
1734 CLEAR (to);
1736 to.crypto_flags_and = ~(CO_PACKET_ID_LONG_FORM);
1737 if (packet_id_long_form)
1738 to.crypto_flags_or = CO_PACKET_ID_LONG_FORM;
1740 to.ssl_ctx = c->c1.ks.ssl_ctx;
1741 to.key_type = c->c1.ks.key_type;
1742 to.server = options->tls_server;
1743 to.key_method = options->key_method;
1744 to.replay = options->replay;
1745 to.replay_window = options->replay_window;
1746 to.replay_time = options->replay_time;
1747 to.transition_window = options->transition_window;
1748 to.handshake_window = options->handshake_window;
1749 to.packet_timeout = options->tls_timeout;
1750 to.renegotiate_bytes = options->renegotiate_bytes;
1751 to.renegotiate_packets = options->renegotiate_packets;
1752 to.renegotiate_seconds = options->renegotiate_seconds;
1753 to.single_session = options->single_session;
1755 /* should we not xmit any packets until we get an initial
1756 response from client? */
1757 if (to.server && options->ce.proto == PROTO_TCPv4_SERVER)
1758 to.xmit_hold = true;
1760 #ifdef ENABLE_OCC
1761 to.disable_occ = !options->occ;
1762 #endif
1764 to.verify_command = options->tls_verify;
1765 to.verify_x509name = options->tls_remote;
1766 to.crl_file = options->crl_file;
1767 to.ns_cert_type = options->ns_cert_type;
1768 memmove (to.remote_cert_ku, options->remote_cert_ku, sizeof (to.remote_cert_ku));
1769 to.remote_cert_eku = options->remote_cert_eku;
1770 to.es = c->c2.es;
1772 #ifdef ENABLE_DEBUG
1773 to.gremlin = c->options.gremlin;
1774 #endif
1776 to.plugins = c->plugins;
1778 #ifdef MANAGEMENT_DEF_AUTH
1779 to.mda_context = &c->c2.mda_context;
1780 #endif
1782 #if P2MP_SERVER
1783 to.auth_user_pass_verify_script = options->auth_user_pass_verify_script;
1784 to.auth_user_pass_verify_script_via_file = options->auth_user_pass_verify_script_via_file;
1785 to.tmp_dir = options->tmp_dir;
1786 to.ssl_flags = options->ssl_flags;
1787 if (options->ccd_exclusive)
1788 to.client_config_dir_exclusive = options->client_config_dir;
1789 #endif
1791 /* TLS handshake authentication (--tls-auth) */
1792 if (options->tls_auth_file)
1794 to.tls_auth_key = c->c1.ks.tls_auth_key;
1795 to.tls_auth.pid_persist = &c->c1.pid_persist;
1796 to.tls_auth.flags |= CO_PACKET_ID_LONG_FORM;
1797 crypto_adjust_frame_parameters (&to.frame,
1798 &c->c1.ks.key_type,
1799 false, false, true, true);
1802 /* If we are running over TCP, allow for
1803 length prefix */
1804 socket_adjust_frame_parameters (&to.frame, options->ce.proto);
1807 * Initialize OpenVPN's master TLS-mode object.
1809 if (flags & CF_INIT_TLS_MULTI)
1810 c->c2.tls_multi = tls_multi_init (&to);
1812 if (flags & CF_INIT_TLS_AUTH_STANDALONE)
1813 c->c2.tls_auth_standalone = tls_auth_standalone_init (&to, &c->c2.gc);
1816 static void
1817 do_init_finalize_tls_frame (struct context *c)
1819 if (c->c2.tls_multi)
1821 tls_multi_init_finalize (c->c2.tls_multi, &c->c2.frame);
1822 ASSERT (EXPANDED_SIZE (&c->c2.tls_multi->opt.frame) <=
1823 EXPANDED_SIZE (&c->c2.frame));
1824 frame_print (&c->c2.tls_multi->opt.frame, D_MTU_INFO,
1825 "Control Channel MTU parms");
1827 if (c->c2.tls_auth_standalone)
1829 tls_auth_standalone_finalize (c->c2.tls_auth_standalone, &c->c2.frame);
1830 frame_print (&c->c2.tls_auth_standalone->frame, D_MTU_INFO,
1831 "TLS-Auth MTU parms");
1835 #endif /* USE_SSL */
1836 #endif /* USE_CRYPTO */
1838 #ifdef USE_CRYPTO
1840 * No encryption or authentication.
1842 static void
1843 do_init_crypto_none (const struct context *c)
1845 ASSERT (!c->options.test_crypto);
1846 msg (M_WARN,
1847 "******* WARNING *******: all encryption and authentication features disabled -- all data will be tunnelled as cleartext");
1849 #endif
1851 static void
1852 do_init_crypto (struct context *c, const unsigned int flags)
1854 #ifdef USE_CRYPTO
1855 if (c->options.shared_secret_file)
1856 do_init_crypto_static (c, flags);
1857 #ifdef USE_SSL
1858 else if (c->options.tls_server || c->options.tls_client)
1859 do_init_crypto_tls (c, flags);
1860 #endif
1861 else /* no encryption or authentication. */
1862 do_init_crypto_none (c);
1863 #else /* USE_CRYPTO */
1864 msg (M_WARN,
1865 "******* WARNING *******: " PACKAGE_NAME
1866 " built without OpenSSL -- encryption and authentication features disabled -- all data will be tunnelled as cleartext");
1867 #endif /* USE_CRYPTO */
1870 static void
1871 do_init_frame (struct context *c)
1873 #ifdef USE_LZO
1875 * Initialize LZO compression library.
1877 if (c->options.lzo & LZO_SELECTED)
1879 lzo_adjust_frame_parameters (&c->c2.frame);
1882 * LZO usage affects buffer alignment.
1884 if (CIPHER_ENABLED (c))
1886 frame_add_to_align_adjust (&c->c2.frame, LZO_PREFIX_LEN);
1887 frame_or_align_flags (&c->c2.frame,
1888 FRAME_HEADROOM_MARKER_FRAGMENT
1889 |FRAME_HEADROOM_MARKER_DECRYPT);
1892 #ifdef ENABLE_FRAGMENT
1893 lzo_adjust_frame_parameters (&c->c2.frame_fragment_omit); /* omit LZO frame delta from final frame_fragment */
1894 #endif
1896 #endif /* USE_LZO */
1898 #ifdef ENABLE_SOCKS
1900 * Adjust frame size for UDP Socks support.
1902 if (c->options.ce.socks_proxy_server)
1903 socks_adjust_frame_parameters (&c->c2.frame, c->options.ce.proto);
1904 #endif
1907 * Adjust frame size based on the --tun-mtu-extra parameter.
1909 if (c->options.tun_mtu_extra_defined)
1910 tun_adjust_frame_parameters (&c->c2.frame, c->options.tun_mtu_extra);
1913 * Adjust frame size based on link socket parameters.
1914 * (Since TCP is a stream protocol, we need to insert
1915 * a packet length uint16_t in the buffer.)
1917 socket_adjust_frame_parameters (&c->c2.frame, c->options.ce.proto);
1920 * Fill in the blanks in the frame parameters structure,
1921 * make sure values are rational, etc.
1923 frame_finalize_options (c, NULL);
1925 #ifdef ENABLE_FRAGMENT
1927 * Set frame parameter for fragment code. This is necessary because
1928 * the fragmentation code deals with payloads which have already been
1929 * passed through the compression code.
1931 c->c2.frame_fragment = c->c2.frame;
1932 frame_subtract_extra (&c->c2.frame_fragment, &c->c2.frame_fragment_omit);
1933 #endif
1935 #if defined(ENABLE_FRAGMENT) && defined(ENABLE_OCC)
1937 * MTU advisories
1939 if (c->options.fragment && c->options.mtu_test)
1940 msg (M_WARN,
1941 "WARNING: using --fragment and --mtu-test together may produce an inaccurate MTU test result");
1942 #endif
1944 #ifdef ENABLE_FRAGMENT
1945 if ((c->options.mssfix || c->options.fragment)
1946 && TUN_MTU_SIZE (&c->c2.frame_fragment) != ETHERNET_MTU)
1947 msg (M_WARN,
1948 "WARNING: normally if you use --mssfix and/or --fragment, you should also set --tun-mtu %d (currently it is %d)",
1949 ETHERNET_MTU, TUN_MTU_SIZE (&c->c2.frame_fragment));
1950 #endif
1953 static void
1954 do_option_warnings (struct context *c)
1956 const struct options *o = &c->options;
1958 #if 1 /* JYFIXME -- port warning */
1959 if (!o->ce.port_option_used && (o->ce.local_port == OPENVPN_PORT && o->ce.remote_port == OPENVPN_PORT))
1960 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.",
1961 OPENVPN_PORT);
1962 #endif
1964 if (o->ping_send_timeout && !o->ping_rec_timeout)
1965 msg (M_WARN, "WARNING: --ping should normally be used with --ping-restart or --ping-exit");
1967 if (o->username || o->groupname || o->chroot_dir)
1969 if (!o->persist_tun)
1970 msg (M_WARN, "WARNING: you are using user/group/chroot without persist-tun -- this may cause restarts to fail");
1971 if (!o->persist_key
1972 #ifdef ENABLE_PKCS11
1973 && !o->pkcs11_id
1974 #endif
1976 msg (M_WARN, "WARNING: you are using user/group/chroot without persist-key -- this may cause restarts to fail");
1979 if (o->chroot_dir && !(o->username && o->groupname))
1980 msg (M_WARN, "WARNING: you are using chroot without specifying user and group -- this may cause the chroot jail to be insecure");
1982 #if P2MP
1983 if (o->pull && o->ifconfig_local && c->first_time)
1984 msg (M_WARN, "WARNING: using --pull/--client and --ifconfig together is probably not what you want");
1986 #if P2MP_SERVER
1987 if (o->server_bridge_defined | o->server_bridge_proxy_dhcp)
1988 msg (M_WARN, "NOTE: when bridging your LAN adapter with the TAP adapter, note that the new bridge adapter will often take on its own IP address that is different from what the LAN adapter was previously set to");
1990 if (o->mode == MODE_SERVER)
1992 if (o->duplicate_cn && o->client_config_dir)
1993 msg (M_WARN, "WARNING: using --duplicate-cn and --client-config-dir together is probably not what you want");
1994 if (o->duplicate_cn && o->ifconfig_pool_persist_filename)
1995 msg (M_WARN, "WARNING: --ifconfig-pool-persist will not work with --duplicate-cn");
1996 if (!o->keepalive_ping || !o->keepalive_timeout)
1997 msg (M_WARN, "WARNING: --keepalive option is missing from server config");
1999 #endif
2000 #endif
2002 #ifdef USE_CRYPTO
2003 if (!o->replay)
2004 msg (M_WARN, "WARNING: You have disabled Replay Protection (--no-replay) which may make " PACKAGE_NAME " less secure");
2005 if (!o->use_iv)
2006 msg (M_WARN, "WARNING: You have disabled Crypto IVs (--no-iv) which may make " PACKAGE_NAME " less secure");
2008 #ifdef USE_SSL
2009 if (o->tls_server)
2010 warn_on_use_of_common_subnets ();
2011 if (o->tls_client
2012 && !o->tls_verify
2013 && !o->tls_remote
2014 && !(o->ns_cert_type & NS_SSL_SERVER)
2015 && !o->remote_cert_eku)
2016 msg (M_WARN, "WARNING: No server certificate verification method has been enabled. See http://openvpn.net/howto.html#mitm for more info.");
2017 if (o->tls_remote)
2018 msg (M_WARN, "WARNING: Make sure you understand the semantics of --tls-remote before using it (see the man page).");
2019 #endif
2020 #endif
2022 #ifndef CONNECT_NONBLOCK
2023 if (o->ce.connect_timeout_defined)
2024 msg (M_WARN, "NOTE: --connect-timeout option is not supported on this OS");
2025 #endif
2027 if (script_security >= SSEC_SCRIPTS)
2028 msg (M_WARN, "NOTE: the current --script-security setting may allow this configuration to call user-defined scripts");
2029 else if (script_security >= SSEC_PW_ENV)
2030 msg (M_WARN, "WARNING: the current --script-security setting may allow passwords to be passed to scripts via environmental variables");
2031 else
2032 msg (M_WARN, "NOTE: " PACKAGE_NAME " 2.1 requires '--script-security 2' or higher to call user-defined scripts or executables");
2034 if (script_method == SM_SYSTEM)
2035 msg (M_WARN, "NOTE: --script-security method='system' is deprecated due to the fact that passed parameters will be subject to shell expansion");
2038 static void
2039 do_init_frame_tls (struct context *c)
2041 #if defined(USE_CRYPTO) && defined(USE_SSL)
2042 do_init_finalize_tls_frame (c);
2043 #endif
2046 struct context_buffers *
2047 init_context_buffers (const struct frame *frame)
2049 struct context_buffers *b;
2051 ALLOC_OBJ_CLEAR (b, struct context_buffers);
2053 b->read_link_buf = alloc_buf (BUF_SIZE (frame));
2054 b->read_tun_buf = alloc_buf (BUF_SIZE (frame));
2056 b->aux_buf = alloc_buf (BUF_SIZE (frame));
2058 #ifdef USE_CRYPTO
2059 b->encrypt_buf = alloc_buf (BUF_SIZE (frame));
2060 b->decrypt_buf = alloc_buf (BUF_SIZE (frame));
2061 #endif
2063 #ifdef USE_LZO
2064 b->lzo_compress_buf = alloc_buf (BUF_SIZE (frame));
2065 b->lzo_decompress_buf = alloc_buf (BUF_SIZE (frame));
2066 #endif
2068 return b;
2071 void
2072 free_context_buffers (struct context_buffers *b)
2074 if (b)
2076 free_buf (&b->read_link_buf);
2077 free_buf (&b->read_tun_buf);
2078 free_buf (&b->aux_buf);
2080 #ifdef USE_LZO
2081 free_buf (&b->lzo_compress_buf);
2082 free_buf (&b->lzo_decompress_buf);
2083 #endif
2085 #ifdef USE_CRYPTO
2086 free_buf (&b->encrypt_buf);
2087 free_buf (&b->decrypt_buf);
2088 #endif
2090 free (b);
2095 * Now that we know all frame parameters, initialize
2096 * our buffers.
2098 static void
2099 do_init_buffers (struct context *c)
2101 c->c2.buffers = init_context_buffers (&c->c2.frame);
2102 c->c2.buffers_owned = true;
2105 #ifdef ENABLE_FRAGMENT
2107 * Fragmenting code has buffers to initialize
2108 * once frame parameters are known.
2110 static void
2111 do_init_fragment (struct context *c)
2113 ASSERT (c->options.fragment);
2114 frame_set_mtu_dynamic (&c->c2.frame_fragment,
2115 c->options.fragment, SET_MTU_UPPER_BOUND);
2116 fragment_frame_init (c->c2.fragment, &c->c2.frame_fragment);
2118 #endif
2121 * Set the --mssfix option.
2123 static void
2124 do_init_mssfix (struct context *c)
2126 if (c->options.mssfix)
2128 frame_set_mtu_dynamic (&c->c2.frame,
2129 c->options.mssfix, SET_MTU_UPPER_BOUND);
2134 * Allocate our socket object.
2136 static void
2137 do_link_socket_new (struct context *c)
2139 ASSERT (!c->c2.link_socket);
2140 c->c2.link_socket = link_socket_new ();
2141 c->c2.link_socket_owned = true;
2145 * bind the TCP/UDP socket
2147 static void
2148 do_init_socket_1 (struct context *c, const int mode)
2150 unsigned int sockflags = c->options.sockflags;
2152 #if PORT_SHARE
2153 if (c->options.port_share_host && c->options.port_share_port)
2154 sockflags |= SF_PORT_SHARE;
2155 #endif
2157 link_socket_init_phase1 (c->c2.link_socket,
2158 connection_list_defined (&c->options),
2159 c->options.ce.local,
2160 c->options.ce.local_port,
2161 c->options.ce.remote,
2162 c->options.ce.remote_port,
2163 c->options.ce.proto,
2164 mode,
2165 c->c2.accept_from,
2166 #ifdef ENABLE_HTTP_PROXY
2167 c->c1.http_proxy,
2168 #endif
2169 #ifdef ENABLE_SOCKS
2170 c->c1.socks_proxy,
2171 #endif
2172 #ifdef ENABLE_DEBUG
2173 c->options.gremlin,
2174 #endif
2175 c->options.ce.bind_local,
2176 c->options.ce.remote_float,
2177 c->options.inetd,
2178 &c->c1.link_socket_addr,
2179 c->options.ipchange,
2180 c->plugins,
2181 c->options.resolve_retry_seconds,
2182 c->options.ce.connect_retry_seconds,
2183 c->options.ce.connect_timeout,
2184 c->options.ce.connect_retry_max,
2185 c->options.mtu_discover_type,
2186 c->options.rcvbuf,
2187 c->options.sndbuf,
2188 sockflags);
2192 * finalize the TCP/UDP socket
2194 static void
2195 do_init_socket_2 (struct context *c)
2197 link_socket_init_phase2 (c->c2.link_socket, &c->c2.frame,
2198 &c->sig->signal_received);
2202 * Print MTU INFO
2204 static void
2205 do_print_data_channel_mtu_parms (struct context *c)
2207 frame_print (&c->c2.frame, D_MTU_INFO, "Data Channel MTU parms");
2208 #ifdef ENABLE_FRAGMENT
2209 if (c->c2.fragment)
2210 frame_print (&c->c2.frame_fragment, D_MTU_INFO,
2211 "Fragmentation MTU parms");
2212 #endif
2215 #ifdef ENABLE_OCC
2217 * Get local and remote options compatibility strings.
2219 static void
2220 do_compute_occ_strings (struct context *c)
2222 struct gc_arena gc = gc_new ();
2224 c->c2.options_string_local =
2225 options_string (&c->options, &c->c2.frame, c->c1.tuntap, false, &gc);
2226 c->c2.options_string_remote =
2227 options_string (&c->options, &c->c2.frame, c->c1.tuntap, true, &gc);
2229 msg (D_SHOW_OCC, "Local Options String: '%s'", c->c2.options_string_local);
2230 msg (D_SHOW_OCC, "Expected Remote Options String: '%s'",
2231 c->c2.options_string_remote);
2233 #ifdef USE_CRYPTO
2234 msg (D_SHOW_OCC_HASH, "Local Options hash (VER=%s): '%s'",
2235 options_string_version (c->c2.options_string_local, &gc),
2236 md5sum ((uint8_t*)c->c2.options_string_local,
2237 strlen (c->c2.options_string_local), 9, &gc));
2238 msg (D_SHOW_OCC_HASH, "Expected Remote Options hash (VER=%s): '%s'",
2239 options_string_version (c->c2.options_string_remote, &gc),
2240 md5sum ((uint8_t*)c->c2.options_string_remote,
2241 strlen (c->c2.options_string_remote), 9, &gc));
2242 #endif
2244 #if defined(USE_CRYPTO) && defined(USE_SSL)
2245 if (c->c2.tls_multi)
2246 tls_multi_init_set_options (c->c2.tls_multi,
2247 c->c2.options_string_local,
2248 c->c2.options_string_remote);
2249 #endif
2251 gc_free (&gc);
2253 #endif
2256 * These things can only be executed once per program instantiation.
2257 * Set up for possible UID/GID downgrade, but don't do it yet.
2258 * Daemonize if requested.
2260 static void
2261 do_init_first_time (struct context *c)
2263 if (c->first_time && !c->did_we_daemonize && !c->c0)
2265 struct context_0 *c0;
2267 ALLOC_OBJ_CLEAR_GC (c->c0, struct context_0, &c->gc);
2268 c0 = c->c0;
2270 /* get user and/or group that we want to setuid/setgid to */
2271 c0->uid_gid_specified =
2272 get_group (c->options.groupname, &c0->group_state) |
2273 get_user (c->options.username, &c0->user_state);
2275 /* get --writepid file descriptor */
2276 get_pid_file (c->options.writepid, &c0->pid_state);
2278 /* become a daemon if --daemon */
2279 c->did_we_daemonize = possibly_become_daemon (&c->options, c->first_time);
2281 /* should we disable paging? */
2282 if (c->options.mlock && c->did_we_daemonize)
2283 do_mlockall (true); /* call again in case we daemonized */
2285 /* save process ID in a file */
2286 write_pid (&c0->pid_state);
2288 /* should we change scheduling priority? */
2289 set_nice (c->options.nice);
2294 * If xinetd/inetd mode, don't allow restart.
2296 static void
2297 do_close_check_if_restart_permitted (struct context *c)
2299 if (c->options.inetd
2300 && (c->sig->signal_received == SIGHUP
2301 || c->sig->signal_received == SIGUSR1))
2303 c->sig->signal_received = SIGTERM;
2304 msg (M_INFO,
2305 PACKAGE_NAME
2306 " started by inetd/xinetd cannot restart... Exiting.");
2311 * free buffers
2313 static void
2314 do_close_free_buf (struct context *c)
2316 if (c->c2.buffers_owned)
2318 free_context_buffers (c->c2.buffers);
2319 c->c2.buffers = NULL;
2320 c->c2.buffers_owned = false;
2325 * close TLS
2327 static void
2328 do_close_tls (struct context *c)
2330 #if defined(USE_CRYPTO) && defined(USE_SSL)
2331 if (c->c2.tls_multi)
2333 tls_multi_free (c->c2.tls_multi, true);
2334 c->c2.tls_multi = NULL;
2337 #ifdef ENABLE_OCC
2338 /* free options compatibility strings */
2339 if (c->c2.options_string_local)
2340 free (c->c2.options_string_local);
2341 if (c->c2.options_string_remote)
2342 free (c->c2.options_string_remote);
2343 c->c2.options_string_local = c->c2.options_string_remote = NULL;
2344 #endif
2345 #endif
2349 * Free key schedules
2351 static void
2352 do_close_free_key_schedule (struct context *c, bool free_ssl_ctx)
2354 if (!(c->sig->signal_received == SIGUSR1 && c->options.persist_key))
2355 key_schedule_free (&c->c1.ks, free_ssl_ctx);
2359 * Close TCP/UDP connection
2361 static void
2362 do_close_link_socket (struct context *c)
2364 if (c->c2.link_socket && c->c2.link_socket_owned)
2366 link_socket_close (c->c2.link_socket);
2367 c->c2.link_socket = NULL;
2370 if (!(c->sig->signal_received == SIGUSR1 && c->options.persist_remote_ip))
2372 CLEAR (c->c1.link_socket_addr.remote);
2373 CLEAR (c->c1.link_socket_addr.actual);
2376 if (!(c->sig->signal_received == SIGUSR1 && c->options.persist_local_ip))
2377 CLEAR (c->c1.link_socket_addr.local);
2381 * Close packet-id persistance file
2383 static void
2384 do_close_packet_id (struct context *c)
2386 #ifdef USE_CRYPTO
2387 packet_id_free (&c->c2.packet_id);
2388 packet_id_persist_save (&c->c1.pid_persist);
2389 if (!(c->sig->signal_received == SIGUSR1))
2390 packet_id_persist_close (&c->c1.pid_persist);
2391 #endif
2394 #ifdef ENABLE_FRAGMENT
2396 * Close fragmentation handler.
2398 static void
2399 do_close_fragment (struct context *c)
2401 if (c->c2.fragment)
2403 fragment_free (c->c2.fragment);
2404 c->c2.fragment = NULL;
2407 #endif
2410 * Open and close our event objects.
2413 static void
2414 do_event_set_init (struct context *c,
2415 bool need_us_timeout)
2417 unsigned int flags = 0;
2419 c->c2.event_set_max = BASE_N_EVENTS;
2421 flags |= EVENT_METHOD_FAST;
2423 if (need_us_timeout)
2424 flags |= EVENT_METHOD_US_TIMEOUT;
2426 c->c2.event_set = event_set_init (&c->c2.event_set_max, flags);
2427 c->c2.event_set_owned = true;
2430 static void
2431 do_close_event_set (struct context *c)
2433 if (c->c2.event_set && c->c2.event_set_owned)
2435 event_free (c->c2.event_set);
2436 c->c2.event_set = NULL;
2437 c->c2.event_set_owned = false;
2442 * Open and close --status file
2445 static void
2446 do_open_status_output (struct context *c)
2448 if (!c->c1.status_output)
2450 c->c1.status_output = status_open (c->options.status_file,
2451 c->options.status_file_update_freq,
2453 NULL,
2454 STATUS_OUTPUT_WRITE);
2455 c->c1.status_output_owned = true;
2459 static void
2460 do_close_status_output (struct context *c)
2462 if (!(c->sig->signal_received == SIGUSR1))
2464 if (c->c1.status_output_owned && c->c1.status_output)
2466 status_close (c->c1.status_output);
2467 c->c1.status_output = NULL;
2468 c->c1.status_output_owned = false;
2474 * Handle ifconfig-pool persistance object.
2476 static void
2477 do_open_ifconfig_pool_persist (struct context *c)
2479 #if P2MP_SERVER
2480 if (!c->c1.ifconfig_pool_persist && c->options.ifconfig_pool_persist_filename)
2482 c->c1.ifconfig_pool_persist = ifconfig_pool_persist_init (c->options.ifconfig_pool_persist_filename,
2483 c->options.ifconfig_pool_persist_refresh_freq);
2484 c->c1.ifconfig_pool_persist_owned = true;
2486 #endif
2489 static void
2490 do_close_ifconfig_pool_persist (struct context *c)
2492 #if P2MP_SERVER
2493 if (!(c->sig->signal_received == SIGUSR1))
2495 if (c->c1.ifconfig_pool_persist && c->c1.ifconfig_pool_persist_owned)
2497 ifconfig_pool_persist_close (c->c1.ifconfig_pool_persist);
2498 c->c1.ifconfig_pool_persist = NULL;
2499 c->c1.ifconfig_pool_persist_owned = false;
2502 #endif
2506 * Inherit environmental variables
2509 static void
2510 do_inherit_env (struct context *c, const struct env_set *src)
2512 c->c2.es = env_set_create (NULL);
2513 c->c2.es_owned = true;
2514 env_set_inherit (c->c2.es, src);
2517 static void
2518 do_env_set_destroy (struct context *c)
2520 if (c->c2.es && c->c2.es_owned)
2522 env_set_destroy (c->c2.es);
2523 c->c2.es = NULL;
2524 c->c2.es_owned = false;
2529 * Fast I/O setup. Fast I/O is an optimization which only works
2530 * if all of the following are true:
2532 * (1) The platform is not Windows
2533 * (2) --proto udp is enabled
2534 * (3) --shaper is disabled
2536 static void
2537 do_setup_fast_io (struct context *c)
2539 if (c->options.fast_io)
2541 #ifdef WIN32
2542 msg (M_INFO, "NOTE: --fast-io is disabled since we are running on Windows");
2543 #else
2544 if (c->options.ce.proto != PROTO_UDPv4)
2545 msg (M_INFO, "NOTE: --fast-io is disabled since we are not using UDP");
2546 else
2548 #ifdef HAVE_GETTIMEOFDAY
2549 if (c->options.shaper)
2550 msg (M_INFO, "NOTE: --fast-io is disabled since we are using --shaper");
2551 else
2552 #endif
2554 c->c2.fast_io = true;
2557 #endif
2561 static void
2562 do_signal_on_tls_errors (struct context *c)
2564 #if defined(USE_CRYPTO) && defined(USE_SSL)
2565 if (c->options.tls_exit)
2566 c->c2.tls_exit_signal = SIGTERM;
2567 else
2568 c->c2.tls_exit_signal = SIGUSR1;
2569 #endif
2572 #ifdef ENABLE_PLUGIN
2574 void
2575 init_plugins (struct context *c)
2577 if (c->options.plugin_list && !c->plugins)
2579 c->plugins = plugin_list_init (c->options.plugin_list);
2580 c->plugins_owned = true;
2584 void
2585 open_plugins (struct context *c, const bool import_options, int init_point)
2587 if (c->plugins && c->plugins_owned)
2589 if (import_options)
2591 struct plugin_return pr, config;
2592 plugin_return_init (&pr);
2593 plugin_list_open (c->plugins, c->options.plugin_list, &pr, c->c2.es, init_point);
2594 plugin_return_get_column (&pr, &config, "config");
2595 if (plugin_return_defined (&config))
2597 int i;
2598 for (i = 0; i < config.n; ++i)
2600 unsigned int option_types_found = 0;
2601 if (config.list[i] && config.list[i]->value)
2602 options_string_import (&c->options,
2603 config.list[i]->value,
2604 D_IMPORT_ERRORS|M_OPTERR,
2605 OPT_P_DEFAULT & ~OPT_P_PLUGIN,
2606 &option_types_found,
2607 c->es);
2610 plugin_return_free (&pr);
2612 else
2614 plugin_list_open (c->plugins, c->options.plugin_list, NULL, c->c2.es, init_point);
2619 static void
2620 do_close_plugins (struct context *c)
2622 if (c->plugins && c->plugins_owned && !(c->sig->signal_received == SIGUSR1))
2624 plugin_list_close (c->plugins);
2625 c->plugins = NULL;
2626 c->plugins_owned = false;
2630 static void
2631 do_inherit_plugins (struct context *c, const struct context *src)
2633 if (!c->plugins && src->plugins)
2635 c->plugins = plugin_list_inherit (src->plugins);
2636 c->plugins_owned = true;
2640 #endif
2642 #ifdef ENABLE_MANAGEMENT
2644 static void
2645 management_callback_status_p2p (void *arg, const int version, struct status_output *so)
2647 struct context *c = (struct context *) arg;
2648 print_status (c, so);
2651 void
2652 management_show_net_callback (void *arg, const int msglevel)
2654 #ifdef WIN32
2655 show_routes (msglevel);
2656 show_adapters (msglevel);
2657 msg (msglevel, "END");
2658 #else
2659 msg (msglevel, "ERROR: Sorry, this command is currently only implemented on Windows");
2660 #endif
2663 #endif
2665 void
2666 init_management_callback_p2p (struct context *c)
2668 #ifdef ENABLE_MANAGEMENT
2669 if (management)
2671 struct management_callback cb;
2672 CLEAR (cb);
2673 cb.arg = c;
2674 cb.status = management_callback_status_p2p;
2675 cb.show_net = management_show_net_callback;
2676 management_set_callback (management, &cb);
2678 #endif
2681 #ifdef ENABLE_MANAGEMENT
2683 void
2684 init_management (struct context *c)
2686 if (!management)
2687 management = management_init ();
2690 bool
2691 open_management (struct context *c)
2693 /* initialize management layer */
2694 if (management)
2696 if (c->options.management_addr)
2698 unsigned int flags = c->options.management_flags;
2699 if (c->options.mode == MODE_SERVER)
2700 flags |= MF_SERVER;
2701 if (management_open (management,
2702 c->options.management_addr,
2703 c->options.management_port,
2704 c->options.management_user_pass,
2705 c->options.management_client_user,
2706 c->options.management_client_group,
2707 c->options.management_log_history_cache,
2708 c->options.management_echo_buffer_size,
2709 c->options.management_state_buffer_size,
2710 c->options.management_write_peer_info_file,
2711 c->options.remap_sigusr1,
2712 flags))
2714 management_set_state (management,
2715 OPENVPN_STATE_CONNECTING,
2716 NULL,
2717 (in_addr_t)0,
2718 (in_addr_t)0);
2721 /* initial management hold, called early, before first context initialization */
2722 do_hold (c);
2723 if (IS_SIG (c))
2725 msg (M_WARN, "Signal received from management interface, exiting");
2726 return false;
2729 else
2730 close_management ();
2732 return true;
2735 void
2736 close_management (void)
2738 if (management)
2740 management_close (management);
2741 management = NULL;
2745 #endif
2748 void
2749 uninit_management_callback (void)
2751 #ifdef ENABLE_MANAGEMENT
2752 if (management)
2754 management_clear_callback (management);
2756 #endif
2760 * Initialize a tunnel instance, handle pre and post-init
2761 * signal settings.
2763 void
2764 init_instance_handle_signals (struct context *c, const struct env_set *env, const unsigned int flags)
2766 pre_init_signal_catch ();
2767 init_instance (c, env, flags);
2768 post_init_signal_catch ();
2771 * This is done so that signals thrown during
2772 * initialization can bring us back to
2773 * a management hold.
2775 if (IS_SIG (c))
2777 remap_signal (c);
2778 uninit_management_callback ();
2783 * Initialize a tunnel instance.
2785 void
2786 init_instance (struct context *c, const struct env_set *env, const unsigned int flags)
2788 const struct options *options = &c->options;
2789 const bool child = (c->mode == CM_CHILD_TCP || c->mode == CM_CHILD_UDP);
2790 int link_socket_mode = LS_MODE_DEFAULT;
2792 /* init garbage collection level */
2793 gc_init (&c->c2.gc);
2795 /* signals caught here will abort */
2796 c->sig->signal_received = 0;
2797 c->sig->signal_text = NULL;
2798 c->sig->hard = false;
2800 /* map in current connection entry */
2801 next_connection_entry (c);
2803 /* link_socket_mode allows CM_CHILD_TCP
2804 instances to inherit acceptable fds
2805 from a top-level parent */
2806 if (c->options.ce.proto == PROTO_TCPv4_SERVER)
2808 if (c->mode == CM_TOP)
2809 link_socket_mode = LS_MODE_TCP_LISTEN;
2810 else if (c->mode == CM_CHILD_TCP)
2811 link_socket_mode = LS_MODE_TCP_ACCEPT_FROM;
2814 /* should we disable paging? */
2815 if (c->first_time && options->mlock)
2816 do_mlockall (true);
2818 /* possible sleep or management hold if restart */
2819 if (c->mode == CM_P2P || c->mode == CM_TOP)
2821 do_startup_pause (c);
2822 if (IS_SIG (c))
2823 goto sig;
2826 #if P2MP
2827 /* get passwords if undefined */
2828 if (auth_retry_get () == AR_INTERACT)
2829 init_query_passwords (c);
2830 #endif
2832 /* initialize context level 2 --verb/--mute parms */
2833 init_verb_mute (c, IVM_LEVEL_2);
2835 /* set error message delay for non-server modes */
2836 if (c->mode == CM_P2P)
2837 set_check_status_error_delay (P2P_ERROR_DELAY_MS);
2839 /* warn about inconsistent options */
2840 if (c->mode == CM_P2P || c->mode == CM_TOP)
2841 do_option_warnings (c);
2843 /* inherit environmental variables */
2844 if (env)
2845 do_inherit_env (c, env);
2847 #ifdef ENABLE_PLUGIN
2848 /* initialize plugins */
2849 if (c->mode == CM_P2P || c->mode == CM_TOP)
2850 open_plugins (c, false, OPENVPN_PLUGIN_INIT_PRE_DAEMON);
2851 #endif
2853 /* should we enable fast I/O? */
2854 if (c->mode == CM_P2P || c->mode == CM_TOP)
2855 do_setup_fast_io (c);
2857 /* should we throw a signal on TLS errors? */
2858 do_signal_on_tls_errors (c);
2860 /* open --status file */
2861 if (c->mode == CM_P2P || c->mode == CM_TOP)
2862 do_open_status_output (c);
2864 /* open --ifconfig-pool-persist file */
2865 if (c->mode == CM_TOP)
2866 do_open_ifconfig_pool_persist (c);
2868 #ifdef ENABLE_OCC
2869 /* reset OCC state */
2870 if (c->mode == CM_P2P || child)
2871 c->c2.occ_op = occ_reset_op ();
2872 #endif
2874 /* our wait-for-i/o objects, different for posix vs. win32 */
2875 if (c->mode == CM_P2P)
2876 do_event_set_init (c, SHAPER_DEFINED (&c->options));
2877 else if (c->mode == CM_CHILD_TCP)
2878 do_event_set_init (c, false);
2880 /* initialize HTTP or SOCKS proxy object at scope level 2 */
2881 init_proxy (c, 2);
2883 /* allocate our socket object */
2884 if (c->mode == CM_P2P || c->mode == CM_TOP || c->mode == CM_CHILD_TCP)
2885 do_link_socket_new (c);
2887 #ifdef ENABLE_FRAGMENT
2888 /* initialize internal fragmentation object */
2889 if (options->fragment && (c->mode == CM_P2P || child))
2890 c->c2.fragment = fragment_init (&c->c2.frame);
2891 #endif
2893 /* init crypto layer */
2895 unsigned int crypto_flags = 0;
2896 if (c->mode == CM_TOP)
2897 crypto_flags = CF_INIT_TLS_AUTH_STANDALONE;
2898 else if (c->mode == CM_P2P)
2899 crypto_flags = CF_LOAD_PERSISTED_PACKET_ID | CF_INIT_TLS_MULTI;
2900 else if (child)
2901 crypto_flags = CF_INIT_TLS_MULTI;
2902 do_init_crypto (c, crypto_flags);
2903 if (IS_SIG (c) && !child)
2904 goto sig;
2907 #ifdef USE_LZO
2908 /* initialize LZO compression library. */
2909 if ((options->lzo & LZO_SELECTED) && (c->mode == CM_P2P || child))
2910 lzo_compress_init (&c->c2.lzo_compwork, options->lzo);
2911 #endif
2913 /* initialize MTU variables */
2914 do_init_frame (c);
2916 /* initialize TLS MTU variables */
2917 do_init_frame_tls (c);
2919 /* init workspace buffers whose size is derived from frame size */
2920 if (c->mode == CM_P2P || c->mode == CM_CHILD_TCP)
2921 do_init_buffers (c);
2923 #ifdef ENABLE_FRAGMENT
2924 /* initialize internal fragmentation capability with known frame size */
2925 if (options->fragment && (c->mode == CM_P2P || child))
2926 do_init_fragment (c);
2927 #endif
2929 /* initialize dynamic MTU variable */
2930 do_init_mssfix (c);
2932 /* bind the TCP/UDP socket */
2933 if (c->mode == CM_P2P || c->mode == CM_TOP || c->mode == CM_CHILD_TCP)
2934 do_init_socket_1 (c, link_socket_mode);
2936 /* initialize tun/tap device object,
2937 open tun/tap device, ifconfig, run up script, etc. */
2938 if (!(options->up_delay || PULL_DEFINED (options)) && (c->mode == CM_P2P || c->mode == CM_TOP))
2939 c->c2.did_open_tun = do_open_tun (c);
2941 /* print MTU info */
2942 do_print_data_channel_mtu_parms (c);
2944 #ifdef ENABLE_OCC
2945 /* get local and remote options compatibility strings */
2946 if (c->mode == CM_P2P || child)
2947 do_compute_occ_strings (c);
2948 #endif
2950 /* initialize output speed limiter */
2951 if (c->mode == CM_P2P)
2952 do_init_traffic_shaper (c);
2954 /* do one-time inits, and possibily become a daemon here */
2955 do_init_first_time (c);
2957 #ifdef ENABLE_PLUGIN
2958 /* initialize plugins */
2959 if (c->mode == CM_P2P || c->mode == CM_TOP)
2960 open_plugins (c, false, OPENVPN_PLUGIN_INIT_POST_DAEMON);
2961 #endif
2964 * Actually do UID/GID downgrade, and chroot, if requested.
2965 * May be delayed by --client, --pull, or --up-delay.
2967 do_uid_gid_chroot (c, c->c2.did_open_tun);
2969 /* finalize the TCP/UDP socket */
2970 if (c->mode == CM_P2P || c->mode == CM_TOP || c->mode == CM_CHILD_TCP)
2971 do_init_socket_2 (c);
2973 /* initialize timers */
2974 if (c->mode == CM_P2P || child)
2975 do_init_timers (c, false);
2977 #ifdef ENABLE_PLUGIN
2978 /* initialize plugins */
2979 if (c->mode == CM_P2P || c->mode == CM_TOP)
2980 open_plugins (c, false, OPENVPN_PLUGIN_INIT_POST_UID_CHANGE);
2981 #endif
2983 #if PORT_SHARE
2984 /* share OpenVPN port with foreign (such as HTTPS) server */
2985 if (c->first_time && (c->mode == CM_P2P || c->mode == CM_TOP))
2986 init_port_share (c);
2987 #endif
2989 #ifdef ENABLE_PF
2990 if (child)
2991 pf_init_context (c);
2992 #endif
2994 /* Check for signals */
2995 if (IS_SIG (c))
2996 goto sig;
2998 return;
3000 sig:
3001 if (!c->sig->signal_text)
3002 c->sig->signal_text = "init_instance";
3003 close_context (c, -1, flags);
3004 return;
3008 * Close a tunnel instance.
3010 void
3011 close_instance (struct context *c)
3013 /* close event objects */
3014 do_close_event_set (c);
3016 if (c->mode == CM_P2P
3017 || c->mode == CM_CHILD_TCP
3018 || c->mode == CM_CHILD_UDP
3019 || c->mode == CM_TOP)
3021 /* if xinetd/inetd mode, don't allow restart */
3022 do_close_check_if_restart_permitted (c);
3024 #ifdef USE_LZO
3025 if (lzo_defined (&c->c2.lzo_compwork))
3026 lzo_compress_uninit (&c->c2.lzo_compwork);
3027 #endif
3029 /* free buffers */
3030 do_close_free_buf (c);
3032 /* close TLS */
3033 do_close_tls (c);
3035 /* free key schedules */
3036 do_close_free_key_schedule (c, (c->mode == CM_P2P || c->mode == CM_TOP));
3038 /* close TCP/UDP connection */
3039 do_close_link_socket (c);
3041 /* close TUN/TAP device */
3042 do_close_tun (c, false);
3044 #ifdef MANAGEMENT_DEF_AUTH
3045 if (management)
3046 management_notify_client_close (management, &c->c2.mda_context, NULL);
3047 #endif
3049 #ifdef ENABLE_PF
3050 pf_destroy_context (&c->c2.pf);
3051 #endif
3053 #ifdef ENABLE_PLUGIN
3054 /* call plugin close functions and unload */
3055 do_close_plugins (c);
3056 #endif
3058 /* close packet-id persistance file */
3059 do_close_packet_id (c);
3061 /* close --status file */
3062 do_close_status_output (c);
3064 #ifdef ENABLE_FRAGMENT
3065 /* close fragmentation handler */
3066 do_close_fragment (c);
3067 #endif
3069 /* close --ifconfig-pool-persist obj */
3070 do_close_ifconfig_pool_persist (c);
3072 /* free up environmental variable store */
3073 do_env_set_destroy (c);
3075 /* close HTTP or SOCKS proxy */
3076 uninit_proxy (c);
3078 /* garbage collect */
3079 gc_free (&c->c2.gc);
3083 void
3084 inherit_context_child (struct context *dest,
3085 const struct context *src)
3087 CLEAR (*dest);
3089 switch (src->options.ce.proto)
3091 case PROTO_UDPv4:
3092 dest->mode = CM_CHILD_UDP;
3093 break;
3094 case PROTO_TCPv4_SERVER:
3095 dest->mode = CM_CHILD_TCP;
3096 break;
3097 default:
3098 ASSERT (0);
3101 dest->gc = gc_new ();
3103 ALLOC_OBJ_CLEAR_GC (dest->sig, struct signal_info, &dest->gc);
3105 /* c1 init */
3106 packet_id_persist_init (&dest->c1.pid_persist);
3108 #ifdef USE_CRYPTO
3109 dest->c1.ks.key_type = src->c1.ks.key_type;
3110 #ifdef USE_SSL
3111 /* inherit SSL context */
3112 dest->c1.ks.ssl_ctx = src->c1.ks.ssl_ctx;
3113 dest->c1.ks.tls_auth_key = src->c1.ks.tls_auth_key;
3114 #endif
3115 #endif
3117 /* options */
3118 dest->options = src->options;
3119 options_detach (&dest->options);
3121 if (dest->mode == CM_CHILD_TCP)
3124 * The CM_TOP context does the socket listen(),
3125 * and the CM_CHILD_TCP context does the accept().
3127 dest->c2.accept_from = src->c2.link_socket;
3130 #ifdef ENABLE_PLUGIN
3131 /* inherit plugins */
3132 do_inherit_plugins (dest, src);
3133 #endif
3135 /* context init */
3136 init_instance (dest, src->c2.es, CC_NO_CLOSE | CC_USR1_TO_HUP);
3137 if (IS_SIG (dest))
3138 return;
3140 /* inherit tun/tap interface object */
3141 dest->c1.tuntap = src->c1.tuntap;
3143 /* UDP inherits some extra things which TCP does not */
3144 if (dest->mode == CM_CHILD_UDP)
3146 /* inherit buffers */
3147 dest->c2.buffers = src->c2.buffers;
3149 /* inherit parent link_socket and tuntap */
3150 dest->c2.link_socket = src->c2.link_socket;
3152 ALLOC_OBJ_GC (dest->c2.link_socket_info, struct link_socket_info, &dest->gc);
3153 *dest->c2.link_socket_info = src->c2.link_socket->info;
3155 /* locally override some link_socket_info fields */
3156 dest->c2.link_socket_info->lsa = &dest->c1.link_socket_addr;
3157 dest->c2.link_socket_info->connection_established = false;
3161 void
3162 inherit_context_top (struct context *dest,
3163 const struct context *src)
3165 /* copy parent */
3166 *dest = *src;
3169 * CM_TOP_CLONE will prevent close_instance from freeing or closing
3170 * resources owned by the parent.
3172 * Also note that CM_TOP_CLONE context objects are
3173 * closed by multi_top_free in multi.c.
3175 dest->mode = CM_TOP_CLONE;
3177 dest->first_time = false;
3178 dest->c0 = NULL;
3180 options_detach (&dest->options);
3181 gc_detach (&dest->gc);
3182 gc_detach (&dest->c2.gc);
3184 /* detach plugins */
3185 dest->plugins_owned = false;
3187 #if defined(USE_CRYPTO) && defined(USE_SSL)
3188 dest->c2.tls_multi = NULL;
3189 #endif
3191 /* detach c1 ownership */
3192 dest->c1.tuntap_owned = false;
3193 dest->c1.status_output_owned = false;
3194 #if P2MP_SERVER
3195 dest->c1.ifconfig_pool_persist_owned = false;
3196 #endif
3198 /* detach c2 ownership */
3199 dest->c2.event_set_owned = false;
3200 dest->c2.link_socket_owned = false;
3201 dest->c2.buffers_owned = false;
3202 dest->c2.es_owned = false;
3204 dest->c2.event_set = NULL;
3205 if (src->options.ce.proto == PROTO_UDPv4)
3206 do_event_set_init (dest, false);
3209 void
3210 close_context (struct context *c, int sig, unsigned int flags)
3212 ASSERT (c);
3213 ASSERT (c->sig);
3215 if (sig >= 0)
3216 c->sig->signal_received = sig;
3218 if (c->sig->signal_received == SIGUSR1)
3220 if ((flags & CC_USR1_TO_HUP)
3221 || (c->sig->hard && (flags & CC_HARD_USR1_TO_HUP)))
3222 c->sig->signal_received = SIGHUP;
3225 if (!(flags & CC_NO_CLOSE))
3226 close_instance (c);
3228 if (flags & CC_GC_FREE)
3229 context_gc_free (c);
3232 #ifdef USE_CRYPTO
3234 static void
3235 test_malloc (void)
3237 int i, j;
3238 msg (M_INFO, "Multithreaded malloc test...");
3239 for (i = 0; i < 25; ++i)
3241 struct gc_arena gc = gc_new ();
3242 const int limit = get_random () & 0x03FF;
3243 for (j = 0; j < limit; ++j)
3245 gc_malloc (get_random () & 0x03FF, false, &gc);
3247 gc_free (&gc);
3252 * Do a loopback test
3253 * on the crypto subsystem.
3255 static void *
3256 test_crypto_thread (void *arg)
3258 struct context *c = (struct context *) arg;
3259 const struct options *options = &c->options;
3260 #if defined(USE_PTHREAD)
3261 struct context *child = NULL;
3262 openvpn_thread_t child_id = 0;
3263 #endif
3265 ASSERT (options->test_crypto);
3266 init_verb_mute (c, IVM_LEVEL_1);
3267 context_init_1 (c);
3268 do_init_crypto_static (c, 0);
3270 #if defined(USE_PTHREAD)
3272 if (c->first_time && options->n_threads > 1)
3274 if (options->n_threads > 2)
3275 msg (M_FATAL, "ERROR: --test-crypto option only works with --threads set to 1 or 2");
3276 openvpn_thread_init ();
3277 ALLOC_OBJ (child, struct context);
3278 context_clear (child);
3279 child->options = *options;
3280 options_detach (&child->options);
3281 child->first_time = false;
3282 child_id = openvpn_thread_create (test_crypto_thread, (void *) child);
3285 #endif
3286 frame_finalize_options (c, options);
3288 #if defined(USE_PTHREAD)
3289 if (options->n_threads == 2)
3290 test_malloc ();
3291 #endif
3293 test_crypto (&c->c2.crypto_options, &c->c2.frame);
3295 key_schedule_free (&c->c1.ks, true);
3296 packet_id_free (&c->c2.packet_id);
3298 #if defined(USE_PTHREAD)
3299 if (c->first_time && options->n_threads > 1)
3300 openvpn_thread_join (child_id);
3301 if (child)
3302 free (child);
3303 #endif
3304 context_gc_free (c);
3305 return NULL;
3308 #endif
3310 bool
3311 do_test_crypto (const struct options *o)
3313 #ifdef USE_CRYPTO
3314 if (o->test_crypto)
3316 struct context c;
3318 /* print version number */
3319 msg (M_INFO, "%s", title_string);
3321 context_clear (&c);
3322 c.options = *o;
3323 options_detach (&c.options);
3324 c.first_time = true;
3325 test_crypto_thread ((void *) &c);
3326 return true;
3328 #endif
3329 return false;