Ticket #574: init.c

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